/** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */!function(a){"use strict";function b(a,b,c,e){// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. var f=b&&b.prototype instanceof d?b:d,g=Object.create(f.prototype),h=new m(e||[]);return g._invoke=i(a,c,h),g}// Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function c(a,b,c){try{return{type:"normal",arg:a.call(b,c)}}catch(a){return{type:"throw",arg:a}}}// Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function d(){}function e(){}function f(){}// This is a polyfill for %IteratorPrototype% for environments that // don't natively support it. // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function g(a){["next","throw","return"].forEach(function(b){a[b]=function(a){return this._invoke(b,a)}})}function h(a){function b(d,e,f,g){var h=c(a[d],a,e);if("throw"===h.type)g(h.arg);else{var i=h.arg,j=i.value;return j&&"object"===typeof j&&q.call(j,"__await")?Promise.resolve(j.__await).then(function(a){b("next",a,f,g)},function(a){b("throw",a,f,g)}):Promise.resolve(j).then(function(a){// When a yielded Promise is resolved, its final value becomes // the .value of the Promise<{value,done}> result for the // current iteration. If the Promise is rejected, however, the // result for this iteration will be rejected with the same // reason. Note that rejections of yielded Promises are not // thrown back into the generator function, as is the case // when an awaited Promise is rejected. This difference in // behavior between yield and await is important, because it // allows the consumer to decide what to do with the yielded // rejection (swallow it and continue, manually .throw it back // into the generator, abandon iteration, whatever). With // await, by contrast, there is no opportunity to examine the // rejection reason outside the generator function, so the // only option is to throw it from the await expression, and // let the generator function handle the exception. i.value=a,f(i)},g)}}function d(a,c){function d(){return new Promise(function(d,e){b(a,c,d,e)})}return e=// If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to // call invoke immediately, without waiting on a callback to fire, // so that the async generator function has the opportunity to do // any necessary setup in a predictable way. This predictability // is why the Promise constructor synchronously invokes its // executor callback, and why async functions synchronously // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. e?e.then(d,// Avoid propagating failures to Promises returned by later // invocations of the iterator. d):d()}// Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). var e;this._invoke=d}function i(a,b,d){var e="suspendedStart";return function(f,g){if(e==="executing")throw new Error("Generator is already running");if("completed"===e){if("throw"===f)throw g;// Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return o()}for(d.method=f,d.arg=g;;){var h=d.delegate;if(h){var i=j(h,d);if(i){if(i===x)continue;return i}}if("next"===d.method)// Setting context._sent for legacy support of Babel's // function.sent implementation. d.sent=d._sent=d.arg;else if("throw"===d.method){if("suspendedStart"===e)throw e="completed",d.arg;d.dispatchException(d.arg)}else"return"===d.method&&d.abrupt("return",d.arg);e="executing";var k=c(a,b,d);if("normal"===k.type){if(e=d.done?"completed":"suspendedYield",k.arg===x)continue;return{value:k.arg,done:d.done}}"throw"===k.type&&(// Dispatch the exception by looping back around to the // context.dispatchException(context.arg) call above. e="completed",d.method="throw",d.arg=k.arg)}}}// Call delegate.iterator[context.method](context.arg) and handle the // result, either by returning a { value, done } result from the // delegate iterator, or by modifying context.method and context.arg, // setting context.delegate to null, and returning the ContinueSentinel. function j(a,b){var d=a.iterator[b.method];if(void 0===d){if(b.delegate=null,"throw"===b.method){if(a.iterator.return&&(b.method="return",b.arg=void 0,j(a,b),"throw"===b.method))// If maybeInvokeDelegate(context) changed context.method from // "return" to "throw", let that override the TypeError below. return x;b.method="throw",b.arg=new TypeError("The iterator does not provide a 'throw' method")}return x}var e=c(d,a.iterator,b.arg);if("throw"===e.type)return b.method="throw",b.arg=e.arg,b.delegate=null,x;var f=e.arg;if(!f)return b.method="throw",b.arg=new TypeError("iterator result is not an object"),b.delegate=null,x;if(f.done)b[a.resultName]=f.value,b.next=a.nextLoc,"return"!==b.method&&(b.method="next",b.arg=void 0);else// Re-yield the result returned by the delegate method. return f;// The delegate iterator is finished, so forget it and continue with // the outer generator. return b.delegate=null,x}// Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. function k(a){var b={tryLoc:a[0]};1 in a&&(b.catchLoc=a[1]),2 in a&&(b.finallyLoc=a[2],b.afterLoc=a[3]),this.tryEntries.push(b)}function l(a){var b=a.completion||{};b.type="normal",delete b.arg,a.completion=b}function m(a){// The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries=[{tryLoc:"root"}],a.forEach(k,this),this.reset(!0)}function n(a){if(a){var b=a[s];if(b)return b.call(a);if("function"===typeof a.next)return a;if(!isNaN(a.length)){var c=-1,d=function b(){for(;++c=o.length)return{done:true};return{done:false,value:o[i++]};},e:function e(_e2){throw _e2;},f:F};}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var normalCompletion=true,didErr=false,err;return{s:function s(){it=o[Symbol.iterator]();},n:function n(){var step=it.next();normalCompletion=step.done;return step;},e:function e(_e3){didErr=true;err=_e3;},f:function f(){try{if(!normalCompletion&&it.return!=null)it.return();}finally{if(didErr)throw err;}}};}function _toConsumableArray(arr){return _arrayWithoutHoles(arr)||_iterableToArray(arr)||_unsupportedIterableToArray(arr)||_nonIterableSpread();}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen);}function _iterableToArray(iter){if(typeof Symbol!=="undefined"&&Symbol.iterator in Object(iter))return Array.from(iter);}function _arrayWithoutHoles(arr){if(Array.isArray(arr))return _arrayLikeToArray(arr);}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i2&&arguments[2]!==undefined?arguments[2]:defaultPropertyDeclaration;var ctor=this.constructor;var attr=ctor._attributeNameForProperty(name,options);if(attr!==undefined){var attrValue=ctor._propertyValueToAttribute(value,options);// an undefined value does not change the attribute. if(attrValue===undefined){return;}// Track if the property is being reflected to avoid // setting the property again via `attributeChangedCallback`. Note: // 1. this takes advantage of the fact that the callback is synchronous. // 2. will behave incorrectly if multiple attributes are in the reaction // stack at time of calling. However, since we process attributes // in `update` this should not be possible (or an extreme corner case // that we'd like to discover). // mark state reflecting this._updateState=this._updateState|STATE_IS_REFLECTING_TO_ATTRIBUTE;if(attrValue==null){this.removeAttribute(attr);}else{this.setAttribute(attr,attrValue);}// mark state not reflecting this._updateState=this._updateState&~STATE_IS_REFLECTING_TO_ATTRIBUTE;}}},{key:"_attributeToProperty",value:function _attributeToProperty(name,value){// Use tracking info to avoid deserializing attribute value if it was // just set from a property setter. if(this._updateState&STATE_IS_REFLECTING_TO_ATTRIBUTE){return;}var ctor=this.constructor;// Note, hint this as an `AttributeMap` so closure clearly understands // the type; it has issues with tracking types through statics // tslint:disable-next-line:no-unnecessary-type-assertion var propName=ctor._attributeToPropertyMap.get(name);if(propName!==undefined){var options=ctor.getPropertyOptions(propName);// mark state reflecting this._updateState=this._updateState|STATE_IS_REFLECTING_TO_PROPERTY;this[propName]=// tslint:disable-next-line:no-any ctor._propertyValueFromAttribute(value,options);// mark state not reflecting this._updateState=this._updateState&~STATE_IS_REFLECTING_TO_PROPERTY;}}/** * This private version of `requestUpdate` does not access or return the * `updateComplete` promise. This promise can be overridden and is therefore * not free to access. */},{key:"_requestUpdate",value:function _requestUpdate(name,oldValue){var shouldRequestUpdate=true;// If we have a property key, perform property update steps. if(name!==undefined){var ctor=this.constructor;var options=ctor.getPropertyOptions(name);if(ctor._valueHasChanged(this[name],oldValue,options.hasChanged)){if(!this._changedProperties.has(name)){this._changedProperties.set(name,oldValue);}// Add to reflecting properties set. // Note, it's important that every change has a chance to add the // property to `_reflectingProperties`. This ensures setting // attribute + property reflects correctly. if(options.reflect===true&&!(this._updateState&STATE_IS_REFLECTING_TO_PROPERTY)){if(this._reflectingProperties===undefined){this._reflectingProperties=new Map();}this._reflectingProperties.set(name,options);}}else{// Abort the request if the property should not be considered changed. shouldRequestUpdate=false;}}if(!this._hasRequestedUpdate&&shouldRequestUpdate){this._updatePromise=this._enqueueUpdate();}}/** * Requests an update which is processed asynchronously. This should * be called when an element should update based on some state not triggered * by setting a property. In this case, pass no arguments. It should also be * called when manually implementing a property setter. In this case, pass the * property `name` and `oldValue` to ensure that any configured property * options are honored. Returns the `updateComplete` Promise which is resolved * when the update completes. * * @param name {PropertyKey} (optional) name of requesting property * @param oldValue {any} (optional) old value of requesting property * @returns {Promise} A Promise that is resolved when the update completes. */},{key:"requestUpdate",value:function requestUpdate(name,oldValue){this._requestUpdate(name,oldValue);return this.updateComplete;}/** * Sets up the element to asynchronously update. */},{key:"_enqueueUpdate",value:function(){var _enqueueUpdate2=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee(){var result;return regeneratorRuntime.wrap(function _callee$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:this._updateState=this._updateState|STATE_UPDATE_REQUESTED;_context2.prev=1;_context2.next=4;return this._updatePromise;case 4:_context2.next=8;break;case 6:_context2.prev=6;_context2.t0=_context2["catch"](1);case 8:result=this.performUpdate();// If `performUpdate` returns a Promise, we await it. This is done to // enable coordinating updates with a scheduler. Note, the result is // checked to avoid delaying an additional microtask unless we need to. if(!(result!=null)){_context2.next=12;break;}_context2.next=12;return result;case 12:return _context2.abrupt("return",!this._hasRequestedUpdate);case 13:case"end":return _context2.stop();}}},_callee,this,[[1,6]]);}));function _enqueueUpdate(){return _enqueueUpdate2.apply(this,arguments);}return _enqueueUpdate;}()},{key:"performUpdate",/** * Performs an element update. Note, if an exception is thrown during the * update, `firstUpdated` and `updated` will not be called. * * You can override this method to change the timing of updates. If this * method is overridden, `super.performUpdate()` must be called. * * For instance, to schedule updates to occur just before the next frame: * * ``` * protected async performUpdate(): Promise { * await new Promise((resolve) => requestAnimationFrame(() => resolve())); * super.performUpdate(); * } * ``` */value:function performUpdate(){// Mixin instance properties once, if they exist. if(this._instanceProperties){this._applyInstanceProperties();}var shouldUpdate=false;var changedProperties=this._changedProperties;try{shouldUpdate=this.shouldUpdate(changedProperties);if(shouldUpdate){this.update(changedProperties);}else{this._markUpdated();}}catch(e){// Prevent `firstUpdated` and `updated` from running when there's an // update exception. shouldUpdate=false;// Ensure element can accept additional updates after an exception. this._markUpdated();throw e;}if(shouldUpdate){if(!(this._updateState&STATE_HAS_UPDATED)){this._updateState=this._updateState|STATE_HAS_UPDATED;this.firstUpdated(changedProperties);}this.updated(changedProperties);}}},{key:"_markUpdated",value:function _markUpdated(){this._changedProperties=new Map();this._updateState=this._updateState&~STATE_UPDATE_REQUESTED;}/** * Returns a Promise that resolves when the element has completed updating. * The Promise value is a boolean that is `true` if the element completed the * update without triggering another update. The Promise result is `false` if * a property was set inside `updated()`. If the Promise is rejected, an * exception was thrown during the update. * * To await additional asynchronous work, override the `_getUpdateComplete` * method. For example, it is sometimes useful to await a rendered element * before fulfilling this Promise. To do this, first await * `super._getUpdateComplete()`, then any subsequent state. * * @returns {Promise} The Promise returns a boolean that indicates if the * update resolved without triggering another update. */},{key:"_getUpdateComplete",/** * Override point for the `updateComplete` promise. * * It is not safe to override the `updateComplete` getter directly due to a * limitation in TypeScript which means it is not possible to call a * superclass getter (e.g. `super.updateComplete.then(...)`) when the target * language is ES5 (https://github.com/microsoft/TypeScript/issues/338). * This method should be overridden instead. For example: * * class MyElement extends LitElement { * async _getUpdateComplete() { * await super._getUpdateComplete(); * await this._myChild.updateComplete; * } * } */value:function _getUpdateComplete(){return this._updatePromise;}/** * Controls whether or not `update` should be called when the element requests * an update. By default, this method always returns `true`, but this can be * customized to control when to update. * * @param _changedProperties Map of changed properties with old values */},{key:"shouldUpdate",value:function shouldUpdate(_changedProperties){return true;}/** * Updates the element. This method reflects property values to attributes. * It can be overridden to render and keep updated element DOM. * Setting properties inside this method will *not* trigger * another update. * * @param _changedProperties Map of changed properties with old values */},{key:"update",value:function update(_changedProperties){var _this5=this;if(this._reflectingProperties!==undefined&&this._reflectingProperties.size>0){// Use forEach so this works even if for/of loops are compiled to for // loops expecting arrays this._reflectingProperties.forEach(function(v,k){return _this5._propertyToAttribute(k,_this5[k],v);});this._reflectingProperties=undefined;}this._markUpdated();}/** * Invoked whenever the element is updated. Implement to perform * post-updating tasks via DOM APIs, for example, focusing an element. * * Setting properties inside this method will trigger the element to update * again after this update cycle completes. * * @param _changedProperties Map of changed properties with old values */},{key:"updated",value:function updated(_changedProperties){}/** * Invoked when the element is first updated. Implement to perform one time * work on the element after update. * * Setting properties inside this method will trigger the element to update * again after this update cycle completes. * * @param _changedProperties Map of changed properties with old values */},{key:"firstUpdated",value:function firstUpdated(_changedProperties){}},{key:"_hasRequestedUpdate",get:function get(){return this._updateState&STATE_UPDATE_REQUESTED;}},{key:"hasUpdated",get:function get(){return this._updateState&STATE_HAS_UPDATED;}},{key:"updateComplete",get:function get(){return this._getUpdateComplete();}}],[{key:"_ensureClassProperties",/** * Ensures the private `_classProperties` property metadata is created. * In addition to `finalize` this is also called in `createProperty` to * ensure the `@property` decorator can add property metadata. */ /** @nocollapse */value:function _ensureClassProperties(){var _this6=this;// ensure private storage for property declarations. if(!this.hasOwnProperty(JSCompiler_renameProperty('_classProperties',this))){this._classProperties=new Map();// NOTE: Workaround IE11 not supporting Map constructor argument. var superProperties=Object.getPrototypeOf(this)._classProperties;if(superProperties!==undefined){superProperties.forEach(function(v,k){return _this6._classProperties.set(k,v);});}}}/** * Creates a property accessor on the element prototype if one does not exist * and stores a PropertyDeclaration for the property with the given options. * The property setter calls the property's `hasChanged` property option * or uses a strict identity check to determine whether or not to request * an update. * * This method may be overridden to customize properties; however, * when doing so, it's important to call `super.createProperty` to ensure * the property is setup correctly. This method calls * `getPropertyDescriptor` internally to get a descriptor to install. * To customize what properties do when they are get or set, override * `getPropertyDescriptor`. To customize the options for a property, * implement `createProperty` like this: * * static createProperty(name, options) { * options = Object.assign(options, {myOption: true}); * super.createProperty(name, options); * } * * @nocollapse */},{key:"createProperty",value:function createProperty(name){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:defaultPropertyDeclaration;// Note, since this can be called by the `@property` decorator which // is called before `finalize`, we ensure storage exists for property // metadata. this._ensureClassProperties();this._classProperties.set(name,options);// Do not generate an accessor if the prototype already has one, since // it would be lost otherwise and that would never be the user's intention; // Instead, we expect users to call `requestUpdate` themselves from // user-defined accessors. Note that if the super has an accessor we will // still overwrite it if(options.noAccessor||this.prototype.hasOwnProperty(name)){return;}var key=_typeof(name)==='symbol'?Symbol():"__".concat(name);var descriptor=this.getPropertyDescriptor(name,key,options);if(descriptor!==undefined){Object.defineProperty(this.prototype,name,descriptor);}}/** * Returns a property descriptor to be defined on the given named property. * If no descriptor is returned, the property will not become an accessor. * For example, * * class MyElement extends LitElement { * static getPropertyDescriptor(name, key, options) { * const defaultDescriptor = * super.getPropertyDescriptor(name, key, options); * const setter = defaultDescriptor.set; * return { * get: defaultDescriptor.get, * set(value) { * setter.call(this, value); * // custom action. * }, * configurable: true, * enumerable: true * } * } * } * * @nocollapse */},{key:"getPropertyDescriptor",value:function getPropertyDescriptor(name,key,_options){return{// tslint:disable-next-line:no-any no symbol in index get:function get(){return this[key];},set:function set(value){var oldValue=this[name];this[key]=value;this._requestUpdate(name,oldValue);},configurable:true,enumerable:true};}/** * Returns the property options associated with the given property. * These options are defined with a PropertyDeclaration via the `properties` * object or the `@property` decorator and are registered in * `createProperty(...)`. * * Note, this method should be considered "final" and not overridden. To * customize the options for a given property, override `createProperty`. * * @nocollapse * @final */},{key:"getPropertyOptions",value:function getPropertyOptions(name){return this._classProperties&&this._classProperties.get(name)||defaultPropertyDeclaration;}/** * Creates property accessors for registered properties and ensures * any superclasses are also finalized. * @nocollapse */},{key:"finalize",value:function finalize(){// finalize any superclasses var superCtor=Object.getPrototypeOf(this);if(!superCtor.hasOwnProperty(finalized)){superCtor.finalize();}this[finalized]=true;this._ensureClassProperties();// initialize Map populated in observedAttributes this._attributeToPropertyMap=new Map();// make any properties // Note, only process "own" properties since this element will inherit // any properties defined on the superClass, and finalization ensures // the entire prototype chain is finalized. if(this.hasOwnProperty(JSCompiler_renameProperty('properties',this))){var props=this.properties;// support symbols in properties (IE11 does not support this) var propKeys=[].concat(_toConsumableArray(Object.getOwnPropertyNames(props)),_toConsumableArray(typeof Object.getOwnPropertySymbols==='function'?Object.getOwnPropertySymbols(props):[]));// This for/of is ok because propKeys is an array var _iterator=_createForOfIteratorHelper(propKeys),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var p=_step.value;// note, use of `any` is due to TypeSript lack of support for symbol in // index types // tslint:disable-next-line:no-any no symbol in index this.createProperty(p,props[p]);}}catch(err){_iterator.e(err);}finally{_iterator.f();}}}/** * Returns the property name for the given attribute `name`. * @nocollapse */},{key:"_attributeNameForProperty",value:function _attributeNameForProperty(name,options){var attribute=options.attribute;return attribute===false?undefined:typeof attribute==='string'?attribute:typeof name==='string'?name.toLowerCase():undefined;}/** * Returns true if a property should request an update. * Called when a property value is set and uses the `hasChanged` * option for the property if present or a strict identity check. * @nocollapse */},{key:"_valueHasChanged",value:function _valueHasChanged(value,old){var hasChanged=arguments.length>2&&arguments[2]!==undefined?arguments[2]:notEqual;return hasChanged(value,old);}/** * Returns the property value for the given attribute value. * Called via the `attributeChangedCallback` and uses the property's * `converter` or `converter.fromAttribute` property option. * @nocollapse */},{key:"_propertyValueFromAttribute",value:function _propertyValueFromAttribute(value,options){var type=options.type;var converter=options.converter||defaultConverter;var fromAttribute=typeof converter==='function'?converter:converter.fromAttribute;return fromAttribute?fromAttribute(value,type):value;}/** * Returns the attribute value for the given property value. If this * returns undefined, the property will *not* be reflected to an attribute. * If this returns null, the attribute will be removed, otherwise the * attribute will be set to the value. * This uses the property's `reflect` and `type.toAttribute` property options. * @nocollapse */},{key:"_propertyValueToAttribute",value:function _propertyValueToAttribute(value,options){if(options.reflect===undefined){return;}var type=options.type;var converter=options.converter;var toAttribute=converter&&converter.toAttribute||defaultConverter.toAttribute;return toAttribute(value,type);}},{key:"observedAttributes",get:function get(){var _this7=this;// note: piggy backing on this to ensure we're finalized. this.finalize();var attributes=[];// Use forEach so this works even if for/of loops are compiled to for loops // expecting arrays this._classProperties.forEach(function(v,p){var attr=_this7._attributeNameForProperty(p,v);if(attr!==undefined){_this7._attributeToPropertyMap.set(attr,p);attributes.push(attr);}});return attributes;}}]);return UpdatingElement;}(/*#__PURE__*/_wrapNativeSuper(HTMLElement));_a=finalized;/** * Marks class as having finished creating properties. */UpdatingElement[_a]=true;/** * @license * Copyright (c) 2017 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at * http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at * http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at * http://polymer.github.io/PATENTS.txt */var standardProperty=function standardProperty(options,element){// When decorating an accessor, pass it through and add property metadata. // Note, the `hasOwnProperty` check in `createProperty` ensures we don't // stomp over the user's accessor. if(element.kind==='method'&&element.descriptor&&!('value'in element.descriptor)){return Object.assign(Object.assign({},element),{finisher:function finisher(clazz){clazz.createProperty(element.key,options);}});}else{// createProperty() takes care of defining the property, but we still // must return some kind of descriptor, so return a descriptor for an // unused prototype field. The finisher calls createProperty(). return{kind:'field',key:Symbol(),placement:'own',descriptor:{},// When @babel/plugin-proposal-decorators implements initializers, // do this instead of the initializer below. See: // https://github.com/babel/babel/issues/9260 extras: [ // { // kind: 'initializer', // placement: 'own', // initializer: descriptor.initializer, // } // ], initializer:function initializer(){if(typeof element.initializer==='function'){this[element.key]=element.initializer.call(this);}},finisher:function finisher(clazz){clazz.createProperty(element.key,options);}};}};var legacyProperty=function legacyProperty(options,proto,name){proto.constructor.createProperty(name,options);};/** * A property decorator which creates a LitElement property which reflects a * corresponding attribute value. A `PropertyDeclaration` may optionally be * supplied to configure property features. * * This decorator should only be used for public fields. Private or protected * fields should use the internalProperty decorator. * * @example * * class MyElement { * @property({ type: Boolean }) * clicked = false; * } * * @ExportDecoratedItems */function property(options){// tslint:disable-next-line:no-any decorator return function(protoOrDescriptor,name){return name!==undefined?legacyProperty(options,protoOrDescriptor,name):standardProperty(options,protoOrDescriptor);};}/** @license Copyright (c) 2019 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */var supportsAdoptingStyleSheets='adoptedStyleSheets'in Document.prototype&&'replace'in CSSStyleSheet.prototype;/** * @license * Copyright (c) 2017 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at * http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at * http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at * http://polymer.github.io/PATENTS.txt */ // IMPORTANT: do not change the property name or the assignment expression. // This line will be used in regexes to search for LitElement usage. // TODO(justinfagnani): inject version number at build time (window['litElementVersions']||(window['litElementVersions']=[])).push('2.3.1');var HAS_WEBXR_DEVICE_API=navigator.xr!=null&&self.XRSession!=null&&navigator.xr.isSessionSupported!=null;var HAS_WEBXR_HIT_TEST_API=HAS_WEBXR_DEVICE_API&&self.XRSession.prototype.requestHitTestSource;var HAS_RESIZE_OBSERVER=self.ResizeObserver!=null;var HAS_INTERSECTION_OBSERVER=self.IntersectionObserver!=null;var IS_WEBXR_AR_CANDIDATE=HAS_WEBXR_HIT_TEST_API;var IS_MOBILE=function(){var userAgent=navigator.userAgent||navigator.vendor||self.opera;var check=false;if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(userAgent)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(userAgent.substr(0,4))){check=true;}return check;}();var IS_CHROMEOS=/\bCrOS\b/.test(navigator.userAgent);var USE_OFFSCREEN_CANVAS=false;var IS_ANDROID=/android/i.test(navigator.userAgent);var IS_IOS=/iPad|iPhone|iPod/.test(navigator.userAgent)&&!self.MSStream||navigator.platform==='MacIntel'&&navigator.maxTouchPoints>1;var IS_AR_QUICKLOOK_CANDIDATE=function(){var tempAnchor=document.createElement('a');return Boolean(tempAnchor.relList&&tempAnchor.relList.supports&&tempAnchor.relList.supports('ar'));}();var IS_SAFARI=/Safari\//.test(navigator.userAgent);var IS_IOS_CHROME=IS_IOS&&/CriOS\//.test(navigator.userAgent);var IS_IOS_SAFARI=IS_IOS&&IS_SAFARI;var IS_IE11=!window.ActiveXObject&&'ActiveXObject'in window;var CloseIcon="\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n";var ControlsPrompt="\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n";var ARGlyph="\n\n\n\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\n\n";var template=document.createElement('template');template.innerHTML="\n\n
\n
\n \n
\n\n \n
\n \n \n \n
\n\n \n\n
\n
\n \n ").concat(ControlsPrompt,"\n \n
\n
\n\n
\n \n\n
\n \n
\n
\n
\n
\n
\n
\n \n \n
\n
");var makeTemplate=function makeTemplate(tagName){var clone=document.createElement('template');clone.innerHTML=template.innerHTML;if(window.ShadyCSS){window.ShadyCSS.prepareTemplate(clone,tagName);}return clone;};// 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 get(){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');}var output=Object(target);for(var index=1;index>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 clamp(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 euclideanModulo(n,m){return(n%m+m)%m;},// Linear mapping from range to range mapLinear:function mapLinear(x,a1,a2,b1,b2){return b1+(x-a1)*(b2-b1)/(a2-a1);},// https://en.wikipedia.org/wiki/Linear_interpolation lerp:function lerp(x,y,t){return(1-t)*x+t*y;},// http://en.wikipedia.org/wiki/Smoothstep smoothstep:function smoothstep(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 smootherstep(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 interval randInt:function randInt(low,high){return low+Math.floor(Math.random()*(high-low+1));},// Random float from interval randFloat:function randFloat(low,high){return low+Math.random()*(high-low);},// Random float from <-range/2, range/2> interval randFloatSpread:function randFloatSpread(range){return range*(0.5-Math.random());},degToRad:function degToRad(degrees){return degrees*MathUtils.DEG2RAD;},radToDeg:function radToDeg(radians){return radians*MathUtils.RAD2DEG;},isPowerOfTwo:function isPowerOfTwo(value){return(value&value-1)===0&&value!==0;},ceilPowerOfTwo:function ceilPowerOfTwo(value){return Math.pow(2,Math.ceil(Math.log(value)/Math.LN2));},floorPowerOfTwo:function floorPowerOfTwo(value){return Math.pow(2,Math.floor(Math.log(value)/Math.LN2));},setQuaternionFromProperEuler:function setQuaternionFromProperEuler(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 var cos=Math.cos;var sin=Math.sin;var c2=cos(b/2);var s2=sin(b/2);var c13=cos((a+c)/2);var s13=sin((a+c)/2);var c1_3=cos((a-c)/2);var s1_3=sin((a-c)/2);var c3_1=cos((c-a)/2);var 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,y){this.x=x||0;this.y=y||0;}Object.defineProperties(Vector2.prototype,{"width":{get:function get(){return this.x;},set:function set(value){this.x=value;}},"height":{get:function get(){return this.y;},set:function set(value){this.y=value;}}});Object.assign(Vector2.prototype,{isVector2:true,set:function set(x,y){this.x=x;this.y=y;return this;},setScalar:function setScalar(scalar){this.x=scalar;this.y=scalar;return this;},setX:function setX(x){this.x=x;return this;},setY:function setY(y){this.y=y;return this;},setComponent:function setComponent(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 getComponent(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 clone(){return new this.constructor(this.x,this.y);},copy:function copy(v){this.x=v.x;this.y=v.y;return this;},add:function add(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 addScalar(s){this.x+=s;this.y+=s;return this;},addVectors:function addVectors(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this;},addScaledVector:function addScaledVector(v,s){this.x+=v.x*s;this.y+=v.y*s;return this;},sub:function sub(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 subScalar(s){this.x-=s;this.y-=s;return this;},subVectors:function subVectors(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this;},multiply:function multiply(v){this.x*=v.x;this.y*=v.y;return this;},multiplyScalar:function multiplyScalar(scalar){this.x*=scalar;this.y*=scalar;return this;},divide:function divide(v){this.x/=v.x;this.y/=v.y;return this;},divideScalar:function divideScalar(scalar){return this.multiplyScalar(1/scalar);},applyMatrix3:function applyMatrix3(m){var x=this.x,y=this.y;var 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 min(v){this.x=Math.min(this.x,v.x);this.y=Math.min(this.y,v.y);return this;},max:function max(v){this.x=Math.max(this.x,v.x);this.y=Math.max(this.y,v.y);return this;},clamp:function clamp(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 clampScalar(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 clampLength(min,max){var length=this.length();return this.divideScalar(length||1).multiplyScalar(Math.max(min,Math.min(max,length)));},floor:function floor(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this;},ceil:function ceil(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this;},round:function round(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this;},roundToZero:function roundToZero(){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 negate(){this.x=-this.x;this.y=-this.y;return this;},dot:function dot(v){return this.x*v.x+this.y*v.y;},cross:function cross(v){return this.x*v.y-this.y*v.x;},lengthSq:function lengthSq(){return this.x*this.x+this.y*this.y;},length:function length(){return Math.sqrt(this.x*this.x+this.y*this.y);},manhattanLength:function manhattanLength(){return Math.abs(this.x)+Math.abs(this.y);},normalize:function normalize(){return this.divideScalar(this.length()||1);},angle:function angle(){// computes the angle in radians with respect to the positive x-axis var angle=Math.atan2(-this.y,-this.x)+Math.PI;return angle;},distanceTo:function distanceTo(v){return Math.sqrt(this.distanceToSquared(v));},distanceToSquared:function distanceToSquared(v){var dx=this.x-v.x,dy=this.y-v.y;return dx*dx+dy*dy;},manhattanDistanceTo:function manhattanDistanceTo(v){return Math.abs(this.x-v.x)+Math.abs(this.y-v.y);},setLength:function setLength(length){return this.normalize().multiplyScalar(length);},lerp:function lerp(v,alpha){this.x+=(v.x-this.x)*alpha;this.y+=(v.y-this.y)*alpha;return this;},lerpVectors:function lerpVectors(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 equals(v){return v.x===this.x&&v.y===this.y;},fromArray:function fromArray(array,offset){if(offset===undefined)offset=0;this.x=array[offset];this.y=array[offset+1];return this;},toArray:function toArray(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;array[offset]=this.x;array[offset+1]=this.y;return array;},fromBufferAttribute:function fromBufferAttribute(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 rotateAround(center,angle){var c=Math.cos(angle),s=Math.sin(angle);var x=this.x-center.x;var 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 random(){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 set(n11,n12,n13,n21,n22,n23,n31,n32,n33){var 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 identity(){this.set(1,0,0,0,1,0,0,0,1);return this;},clone:function clone(){return new this.constructor().fromArray(this.elements);},copy:function copy(m){var te=this.elements;var 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 extractBasis(xAxis,yAxis,zAxis){xAxis.setFromMatrix3Column(this,0);yAxis.setFromMatrix3Column(this,1);zAxis.setFromMatrix3Column(this,2);return this;},setFromMatrix4:function setFromMatrix4(m){var 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 multiply(m){return this.multiplyMatrices(this,m);},premultiply:function premultiply(m){return this.multiplyMatrices(m,this);},multiplyMatrices:function multiplyMatrices(a,b){var ae=a.elements;var be=b.elements;var te=this.elements;var a11=ae[0],a12=ae[3],a13=ae[6];var a21=ae[1],a22=ae[4],a23=ae[7];var a31=ae[2],a32=ae[5],a33=ae[8];var b11=be[0],b12=be[3],b13=be[6];var b21=be[1],b22=be[4],b23=be[7];var 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 multiplyScalar(s){var 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 determinant(){var te=this.elements;var 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 getInverse(matrix,throwOnDegenerate){if(throwOnDegenerate!==undefined){console.warn("THREE.Matrix3: .getInverse() can no longer be configured to throw on degenerate.");}var 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);var 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 transpose(){var tmp,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 getNormalMatrix(matrix4){return this.setFromMatrix4(matrix4).getInverse(this).transpose();},transposeIntoArray:function transposeIntoArray(r){var 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 setUvTransform(tx,ty,sx,sy,rotation,cx,cy){var c=Math.cos(rotation);var 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 scale(sx,sy){var 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 rotate(theta){var c=Math.cos(theta);var s=Math.sin(theta);var te=this.elements;var a11=te[0],a12=te[3],a13=te[6];var 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 translate(tx,ty){var 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 equals(matrix){var te=this.elements;var me=matrix.elements;for(var i=0;i<9;i++){if(te[i]!==me[i])return false;}return true;},fromArray:function fromArray(array,offset){if(offset===undefined)offset=0;for(var i=0;i<9;i++){this.elements[i]=array[i+offset];}return this;},toArray:function toArray(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;var 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/ */var _canvas;var ImageUtils={getDataURL:function getDataURL(image){var canvas;if(typeof HTMLCanvasElement=='undefined'){return image.src;}else if(_instanceof(image,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;var context=_canvas.getContext('2d');if(_instanceof(image,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/ */var 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 updateMatrix(){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 clone(){return new this.constructor().copy(this);},copy:function copy(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 toJSON(meta){var isRootObject=meta===undefined||typeof meta==='string';if(!isRootObject&&meta.textures[this.uuid]!==undefined){return meta.textures[this.uuid];}var 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 var image=this.image;if(image.uuid===undefined){image.uuid=MathUtils.generateUUID();// UGH }if(!isRootObject&&meta.images[image.uuid]===undefined){var url;if(Array.isArray(image)){// process array of images e.g. CubeTexture url=[];for(var i=0,l=image.length;i1){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 set(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,y,z,w){this.x=x||0;this.y=y||0;this.z=z||0;this.w=w!==undefined?w:1;}Object.defineProperties(Vector4.prototype,{"width":{get:function get(){return this.z;},set:function set(value){this.z=value;}},"height":{get:function get(){return this.w;},set:function set(value){this.w=value;}}});Object.assign(Vector4.prototype,{isVector4:true,set:function set(x,y,z,w){this.x=x;this.y=y;this.z=z;this.w=w;return this;},setScalar:function setScalar(scalar){this.x=scalar;this.y=scalar;this.z=scalar;this.w=scalar;return this;},setX:function setX(x){this.x=x;return this;},setY:function setY(y){this.y=y;return this;},setZ:function setZ(z){this.z=z;return this;},setW:function setW(w){this.w=w;return this;},setComponent:function setComponent(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 getComponent(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 clone(){return new this.constructor(this.x,this.y,this.z,this.w);},copy:function copy(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 add(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 addScalar(s){this.x+=s;this.y+=s;this.z+=s;this.w+=s;return this;},addVectors:function addVectors(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 addScaledVector(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 sub(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 subScalar(s){this.x-=s;this.y-=s;this.z-=s;this.w-=s;return this;},subVectors:function subVectors(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 multiplyScalar(scalar){this.x*=scalar;this.y*=scalar;this.z*=scalar;this.w*=scalar;return this;},applyMatrix4:function applyMatrix4(m){var x=this.x,y=this.y,z=this.z,w=this.w;var 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 divideScalar(scalar){return this.multiplyScalar(1/scalar);},setAxisAngleFromQuaternion:function setAxisAngleFromQuaternion(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);var 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 setAxisAngleFromRotationMatrix(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) var angle,x,y,z,// variables for result 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)yy&&xx>zz){// m11 is the largest diagonal term if(xxzz){// m22 is the largest diagonal term if(yy=0?1:-1,sqrSin=1-cos*cos;// Skip the Slerp for tiny steps to avoid numeric problems: if(sqrSin>Number.EPSILON){var sin=Math.sqrt(sqrSin),len=Math.atan2(sin,cos*dir);s=Math.sin(s*len)/sin;t=Math.sin(t*len)/sin;}var 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){var 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 multiplyQuaternionsFlat(dst,dstOffset,src0,srcOffset0,src1,srcOffset1){var x0=src0[srcOffset0];var y0=src0[srcOffset0+1];var z0=src0[srcOffset0+2];var w0=src0[srcOffset0+3];var x1=src1[srcOffset1];var y1=src1[srcOffset1+1];var z1=src1[srcOffset1+2];var 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 get(){return this._x;},set:function set(value){this._x=value;this._onChangeCallback();}},y:{get:function get(){return this._y;},set:function set(value){this._y=value;this._onChangeCallback();}},z:{get:function get(){return this._z;},set:function set(value){this._z=value;this._onChangeCallback();}},w:{get:function get(){return this._w;},set:function set(value){this._w=value;this._onChangeCallback();}}});Object.assign(Quaternion.prototype,{isQuaternion:true,set:function set(x,y,z,w){this._x=x;this._y=y;this._z=z;this._w=w;this._onChangeCallback();return this;},clone:function clone(){return new this.constructor(this._x,this._y,this._z,this._w);},copy:function copy(quaternion){this._x=quaternion.x;this._y=quaternion.y;this._z=quaternion.z;this._w=quaternion.w;this._onChangeCallback();return this;},setFromEuler:function setFromEuler(euler,update){if(!(euler&&euler.isEuler)){throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');}var 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 var cos=Math.cos;var sin=Math.sin;var c1=cos(x/2);var c2=cos(y/2);var c3=cos(z/2);var s1=sin(x/2);var s2=sin(y/2);var 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 setFromAxisAngle(axis,angle){// http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm // assumes axis is normalized var 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 setFromRotationMatrix(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) var 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,s;if(trace>0){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){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){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{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 setFromUnitVectors(vFrom,vTo){// assumes direction vectors vFrom and vTo are normalized var EPS=0.000001;var r=vFrom.dot(vTo)+1;if(rMath.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 angleTo(q){return 2*Math.acos(Math.abs(MathUtils.clamp(this.dot(q),-1,1)));},rotateTowards:function rotateTowards(q,step){var angle=this.angleTo(q);if(angle===0)return this;var t=Math.min(1,step/angle);this.slerp(q,t);return this;},inverse:function inverse(){// quaternion is assumed to have unit length return this.conjugate();},conjugate:function conjugate(){this._x*=-1;this._y*=-1;this._z*=-1;this._onChangeCallback();return this;},dot:function dot(v){return this._x*v._x+this._y*v._y+this._z*v._z+this._w*v._w;},lengthSq:function lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w;},length:function length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w);},normalize:function normalize(){var 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 multiply(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 premultiply(q){return this.multiplyQuaternions(q,this);},multiplyQuaternions:function multiplyQuaternions(a,b){// from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm var qax=a._x,qay=a._y,qaz=a._z,qaw=a._w;var 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 slerp(qb,t){if(t===0)return this;if(t===1)return this.copy(qb);var x=this._x,y=this._y,z=this._z,w=this._w;// http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ var 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;}var sqrSinHalfTheta=1.0-cosHalfTheta*cosHalfTheta;if(sqrSinHalfTheta<=Number.EPSILON){var 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;}var sinHalfTheta=Math.sqrt(sqrSinHalfTheta);var halfTheta=Math.atan2(sinHalfTheta,cosHalfTheta);var 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 equals(quaternion){return quaternion._x===this._x&&quaternion._y===this._y&&quaternion._z===this._z&&quaternion._w===this._w;},fromArray:function fromArray(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 toArray(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 fromBufferAttribute(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 _onChange(callback){this._onChangeCallback=callback;return this;},_onChangeCallback:function _onChangeCallback(){}});/** * @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 */var _vector=new Vector3();var _quaternion=new Quaternion();function Vector3(x,y,z){this.x=x||0;this.y=y||0;this.z=z||0;}Object.assign(Vector3.prototype,{isVector3:true,set:function set(x,y,z){this.x=x;this.y=y;this.z=z;return this;},setScalar:function setScalar(scalar){this.x=scalar;this.y=scalar;this.z=scalar;return this;},setX:function setX(x){this.x=x;return this;},setY:function setY(y){this.y=y;return this;},setZ:function setZ(z){this.z=z;return this;},setComponent:function setComponent(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 getComponent(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 clone(){return new this.constructor(this.x,this.y,this.z);},copy:function copy(v){this.x=v.x;this.y=v.y;this.z=v.z;return this;},add:function add(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 addScalar(s){this.x+=s;this.y+=s;this.z+=s;return this;},addVectors:function addVectors(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this;},addScaledVector:function addScaledVector(v,s){this.x+=v.x*s;this.y+=v.y*s;this.z+=v.z*s;return this;},sub:function sub(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 subScalar(s){this.x-=s;this.y-=s;this.z-=s;return this;},subVectors:function subVectors(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this;},multiply:function multiply(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 multiplyScalar(scalar){this.x*=scalar;this.y*=scalar;this.z*=scalar;return this;},multiplyVectors:function multiplyVectors(a,b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this;},applyEuler:function applyEuler(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 applyAxisAngle(axis,angle){return this.applyQuaternion(_quaternion.setFromAxisAngle(axis,angle));},applyMatrix3:function applyMatrix3(m){var x=this.x,y=this.y,z=this.z;var 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 applyNormalMatrix(m){return this.applyMatrix3(m).normalize();},applyMatrix4:function applyMatrix4(m){var x=this.x,y=this.y,z=this.z;var e=m.elements;var 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 applyQuaternion(q){var x=this.x,y=this.y,z=this.z;var qx=q.x,qy=q.y,qz=q.z,qw=q.w;// calculate quat * vector var ix=qw*x+qy*z-qz*y;var iy=qw*y+qz*x-qx*z;var iz=qw*z+qx*y-qy*x;var 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 project(camera){return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);},unproject:function unproject(camera){return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);},transformDirection:function transformDirection(m){// input: THREE.Matrix4 affine matrix // vector interpreted as a direction var x=this.x,y=this.y,z=this.z;var 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 divide(v){this.x/=v.x;this.y/=v.y;this.z/=v.z;return this;},divideScalar:function divideScalar(scalar){return this.multiplyScalar(1/scalar);},min:function min(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 max(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 clamp(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 clampScalar(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 clampLength(min,max){var length=this.length();return this.divideScalar(length||1).multiplyScalar(Math.max(min,Math.min(max,length)));},floor:function floor(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this;},ceil:function ceil(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this;},round:function round(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this;},roundToZero:function roundToZero(){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 negate(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this;},dot:function dot(v){return this.x*v.x+this.y*v.y+this.z*v.z;},// TODO lengthSquared? lengthSq:function lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z;},length:function length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z);},manhattanLength:function manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z);},normalize:function normalize(){return this.divideScalar(this.length()||1);},setLength:function setLength(length){return this.normalize().multiplyScalar(length);},lerp:function lerp(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 lerpVectors(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 cross(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 crossVectors(a,b){var ax=a.x,ay=a.y,az=a.z;var 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 projectOnVector(v){var denominator=v.lengthSq();if(denominator===0)return this.set(0,0,0);var scalar=v.dot(this)/denominator;return this.copy(v).multiplyScalar(scalar);},projectOnPlane:function projectOnPlane(planeNormal){_vector.copy(this).projectOnVector(planeNormal);return this.sub(_vector);},reflect:function reflect(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 angleTo(v){var denominator=Math.sqrt(this.lengthSq()*v.lengthSq());if(denominator===0)return Math.PI/2;var theta=this.dot(v)/denominator;// clamp, to handle numerical problems return Math.acos(MathUtils.clamp(theta,-1,1));},distanceTo:function distanceTo(v){return Math.sqrt(this.distanceToSquared(v));},distanceToSquared:function distanceToSquared(v){var dx=this.x-v.x,dy=this.y-v.y,dz=this.z-v.z;return dx*dx+dy*dy+dz*dz;},manhattanDistanceTo:function manhattanDistanceTo(v){return Math.abs(this.x-v.x)+Math.abs(this.y-v.y)+Math.abs(this.z-v.z);},setFromSpherical:function setFromSpherical(s){return this.setFromSphericalCoords(s.radius,s.phi,s.theta);},setFromSphericalCoords:function setFromSphericalCoords(radius,phi,theta){var 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 setFromCylindrical(c){return this.setFromCylindricalCoords(c.radius,c.theta,c.y);},setFromCylindricalCoords:function setFromCylindricalCoords(radius,theta,y){this.x=radius*Math.sin(theta);this.y=y;this.z=radius*Math.cos(theta);return this;},setFromMatrixPosition:function setFromMatrixPosition(m){var e=m.elements;this.x=e[12];this.y=e[13];this.z=e[14];return this;},setFromMatrixScale:function setFromMatrixScale(m){var sx=this.setFromMatrixColumn(m,0).length();var sy=this.setFromMatrixColumn(m,1).length();var sz=this.setFromMatrixColumn(m,2).length();this.x=sx;this.y=sy;this.z=sz;return this;},setFromMatrixColumn:function setFromMatrixColumn(m,index){return this.fromArray(m.elements,index*4);},setFromMatrix3Column:function setFromMatrix3Column(m,index){return this.fromArray(m.elements,index*3);},equals:function equals(v){return v.x===this.x&&v.y===this.y&&v.z===this.z;},fromArray:function fromArray(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 toArray(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 fromBufferAttribute(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 random(){this.x=Math.random();this.y=Math.random();this.z=Math.random();return this;}});var _v1=new Vector3();var _m1=new Matrix4();var _zero=new Vector3(0,0,0);var _one=new Vector3(1,1,1);var _x=new Vector3();var _y=new Vector3();var _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 set(n11,n12,n13,n14,n21,n22,n23,n24,n31,n32,n33,n34,n41,n42,n43,n44){var 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 identity(){this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this;},clone:function clone(){return new Matrix4().fromArray(this.elements);},copy:function copy(m){var te=this.elements;var 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 copyPosition(m){var te=this.elements,me=m.elements;te[12]=me[12];te[13]=me[13];te[14]=me[14];return this;},extractBasis:function extractBasis(xAxis,yAxis,zAxis){xAxis.setFromMatrixColumn(this,0);yAxis.setFromMatrixColumn(this,1);zAxis.setFromMatrixColumn(this,2);return this;},makeBasis:function makeBasis(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 extractRotation(m){// this method does not support reflection matrices var te=this.elements;var me=m.elements;var scaleX=1/_v1.setFromMatrixColumn(m,0).length();var scaleY=1/_v1.setFromMatrixColumn(m,1).length();var 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 makeRotationFromEuler(euler){if(!(euler&&euler.isEuler)){console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');}var te=this.elements;var x=euler.x,y=euler.y,z=euler.z;var a=Math.cos(x),b=Math.sin(x);var c=Math.cos(y),d=Math.sin(y);var e=Math.cos(z),f=Math.sin(z);if(euler.order==='XYZ'){var 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'){var 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'){var 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'){var 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'){var 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'){var 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 makeRotationFromQuaternion(q){return this.compose(_zero,q,_one);},lookAt:function lookAt(eye,target,up){var 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 multiply(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 premultiply(m){return this.multiplyMatrices(m,this);},multiplyMatrices:function multiplyMatrices(a,b){var ae=a.elements;var be=b.elements;var te=this.elements;var a11=ae[0],a12=ae[4],a13=ae[8],a14=ae[12];var a21=ae[1],a22=ae[5],a23=ae[9],a24=ae[13];var a31=ae[2],a32=ae[6],a33=ae[10],a34=ae[14];var a41=ae[3],a42=ae[7],a43=ae[11],a44=ae[15];var b11=be[0],b12=be[4],b13=be[8],b14=be[12];var b21=be[1],b22=be[5],b23=be[9],b24=be[13];var b31=be[2],b32=be[6],b33=be[10],b34=be[14];var 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 multiplyScalar(s){var 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 determinant(){var te=this.elements;var n11=te[0],n12=te[4],n13=te[8],n14=te[12];var n21=te[1],n22=te[5],n23=te[9],n24=te[13];var n31=te[2],n32=te[6],n33=te[10],n34=te[14];var 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 transpose(){var te=this.elements;var 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 setPosition(x,y,z){var 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 getInverse(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 var 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;var 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);var 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 scale(v){var te=this.elements;var 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 getMaxScaleOnAxis(){var te=this.elements;var scaleXSq=te[0]*te[0]+te[1]*te[1]+te[2]*te[2];var scaleYSq=te[4]*te[4]+te[5]*te[5]+te[6]*te[6];var scaleZSq=te[8]*te[8]+te[9]*te[9]+te[10]*te[10];return Math.sqrt(Math.max(scaleXSq,scaleYSq,scaleZSq));},makeTranslation:function makeTranslation(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 makeRotationX(theta){var 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 makeRotationY(theta){var 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 makeRotationZ(theta){var 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 makeRotationAxis(axis,angle){// Based on http://www.gamedev.net/reference/articles/article1199.asp var c=Math.cos(angle);var s=Math.sin(angle);var t=1-c;var x=axis.x,y=axis.y,z=axis.z;var 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 makeScale(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 makeShear(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 compose(position,quaternion,scale){var te=this.elements;var x=quaternion._x,y=quaternion._y,z=quaternion._z,w=quaternion._w;var x2=x+x,y2=y+y,z2=z+z;var xx=x*x2,xy=x*y2,xz=x*z2;var yy=y*y2,yz=y*z2,zz=z*z2;var wx=w*x2,wy=w*y2,wz=w*z2;var 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 decompose(position,quaternion,scale){var te=this.elements;var sx=_v1.set(te[0],te[1],te[2]).length();var sy=_v1.set(te[4],te[5],te[6]).length();var sz=_v1.set(te[8],te[9],te[10]).length();// if determine is negative, we need to invert one scale var 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);var invSX=1/sx;var invSY=1/sy;var 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 makePerspective(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.');}var te=this.elements;var x=2*near/(right-left);var y=2*near/(top-bottom);var a=(right+left)/(right-left);var b=(top+bottom)/(top-bottom);var c=-(far+near)/(far-near);var 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 makeOrthographic(left,right,top,bottom,near,far){var te=this.elements;var w=1.0/(right-left);var h=1.0/(top-bottom);var p=1.0/(far-near);var x=(right+left)*w;var y=(top+bottom)*h;var 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 equals(matrix){var te=this.elements;var me=matrix.elements;for(var i=0;i<16;i++){if(te[i]!==me[i])return false;}return true;},fromArray:function fromArray(array,offset){if(offset===undefined)offset=0;for(var i=0;i<16;i++){this.elements[i]=array[i+offset];}return this;},toArray:function toArray(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;var 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 */var _matrix=new Matrix4();var _quaternion$1=new Quaternion();function Euler(x,y,z,order){this._x=x||0;this._y=y||0;this._z=z||0;this._order=order||Euler.DefaultOrder;}Euler.RotationOrders=['XYZ','YZX','ZXY','XZY','YXZ','ZYX'];Euler.DefaultOrder='XYZ';Object.defineProperties(Euler.prototype,{x:{get:function get(){return this._x;},set:function set(value){this._x=value;this._onChangeCallback();}},y:{get:function get(){return this._y;},set:function set(value){this._y=value;this._onChangeCallback();}},z:{get:function get(){return this._z;},set:function set(value){this._z=value;this._onChangeCallback();}},order:{get:function get(){return this._order;},set:function set(value){this._order=value;this._onChangeCallback();}}});Object.assign(Euler.prototype,{isEuler:true,set:function set(x,y,z,order){this._x=x;this._y=y;this._z=z;this._order=order||this._order;this._onChangeCallback();return this;},clone:function clone(){return new this.constructor(this._x,this._y,this._z,this._order);},copy:function copy(euler){this._x=euler._x;this._y=euler._y;this._z=euler._z;this._order=euler._order;this._onChangeCallback();return this;},setFromRotationMatrix:function setFromRotationMatrix(m,order,update){var clamp=MathUtils.clamp;// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) var te=m.elements;var m11=te[0],m12=te[4],m13=te[8];var m21=te[1],m22=te[5],m23=te[9];var 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 setFromQuaternion(q,order,update){_matrix.makeRotationFromQuaternion(q);return this.setFromRotationMatrix(_matrix,order,update);},setFromVector3:function setFromVector3(v,order){return this.set(v.x,v.y,v.z,order||this._order);},reorder:function reorder(newOrder){// WARNING: this discards revolution information -bhouston _quaternion$1.setFromEuler(this);return this.setFromQuaternion(_quaternion$1,newOrder);},equals:function equals(euler){return euler._x===this._x&&euler._y===this._y&&euler._z===this._z&&euler._order===this._order;},fromArray:function fromArray(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 toArray(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 toVector3(optionalResult){if(optionalResult){return optionalResult.set(this._x,this._y,this._z);}else{return new Vector3(this._x,this._y,this._z);}},_onChange:function _onChange(callback){this._onChangeCallback=callback;return this;},_onChangeCallback:function _onChangeCallback(){}});/** * @author mrdoob / http://mrdoob.com/ */function Layers(){this.mask=1|0;}Object.assign(Layers.prototype,{set:function set(channel){this.mask=1<1){for(var i=0;i1){for(var i=0;i0){object.children=[];for(var i=0;i0)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){var values=[];for(var key in cache){var data=cache[key];delete data.metadata;values.push(data);}return values;}},clone:function clone(recursive){return new this.constructor().copy(this,recursive);},copy:function copy(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(var i=0;imaxX)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 setFromBufferAttribute(attribute){var minX=+Infinity;var minY=+Infinity;var minZ=+Infinity;var maxX=-Infinity;var maxY=-Infinity;var maxZ=-Infinity;for(var i=0,l=attribute.count;imaxX)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 setFromPoints(points){this.makeEmpty();for(var i=0,il=points.length;ithis.max.x||point.ythis.max.y||point.zthis.max.z?false:true;},containsBox:function containsBox(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 getParameter(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 intersectsBox(box){// using 6 splitting planes to rule out intersections. return box.max.xthis.max.x||box.max.ythis.max.y||box.max.zthis.max.z?false:true;},intersectsSphere:function intersectsSphere(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 intersectsPlane(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. var 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 intersectsTriangle(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) var 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 clampPoint(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 distanceToPoint(point){var clampedPoint=_vector$1.copy(point).clamp(this.min,this.max);return clampedPoint.sub(point).length();},getBoundingSphere:function getBoundingSphere(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 intersect(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 union(box){this.min.min(box.min);this.max.max(box.max);return this;},applyMatrix4:function applyMatrix4(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 translate(offset){this.min.add(offset);this.max.add(offset);return this;},equals:function equals(box){return box.min.equals(this.min)&&box.max.equals(this.max);}});function satForAxes(axes,v0,v1,v2,extents){var i,j;for(i=0,j=axes.length-3;i<=j;i+=3){_testAxis.fromArray(axes,i);// project the aabb onto the seperating axis var 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 var p0=v0.dot(_testAxis);var p1=v1.dot(_testAxis);var 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;}var _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 set(center,radius){this.center.copy(center);this.radius=radius;return this;},setFromPoints:function setFromPoints(points,optionalCenter){var center=this.center;if(optionalCenter!==undefined){center.copy(optionalCenter);}else{_box$1.setFromPoints(points).getCenter(center);}var maxRadiusSq=0;for(var i=0,il=points.length;ithis.radius*this.radius){target.sub(this.center).normalize();target.multiplyScalar(this.radius).add(this.center);}return target;},getBoundingBox:function getBoundingBox(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 applyMatrix4(matrix){this.center.applyMatrix4(matrix);this.radius=this.radius*matrix.getMaxScaleOnAxis();return this;},translate:function translate(offset){this.center.add(offset);return this;},equals:function equals(sphere){return sphere.center.equals(this.center)&&sphere.radius===this.radius;}});var _vector$2=new Vector3();var _segCenter=new Vector3();var _segDir=new Vector3();var _diff=new Vector3();var _edge1=new Vector3();var _edge2=new Vector3();var _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 set(origin,direction){this.origin.copy(origin);this.direction.copy(direction);return this;},clone:function clone(){return new this.constructor().copy(this);},copy:function copy(ray){this.origin.copy(ray.origin);this.direction.copy(ray.direction);return this;},at:function at(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 lookAt(v){this.direction.copy(v).sub(this.origin).normalize();return this;},recast:function recast(t){this.origin.copy(this.at(t,_vector$2));return this;},closestPointToPoint:function closestPointToPoint(point,target){if(target===undefined){console.warn('THREE.Ray: .closestPointToPoint() target is now required');target=new Vector3();}target.subVectors(point,this.origin);var 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 distanceToPoint(point){return Math.sqrt(this.distanceSqToPoint(point));},distanceSqToPoint:function distanceSqToPoint(point){var 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 distanceSqToSegment(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);var segExtent=v0.distanceTo(v1)*0.5;var a01=-this.direction.dot(_segDir);var b0=_diff.dot(this.direction);var b1=-_diff.dot(_segDir);var c=_diff.lengthSq();var det=Math.abs(1-a01*a01);var 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. var 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 intersectSphere(sphere,target){_vector$2.subVectors(sphere.center,this.origin);var tca=_vector$2.dot(this.direction);var d2=_vector$2.dot(_vector$2)-tca*tca;var radius2=sphere.radius*sphere.radius;if(d2>radius2)return null;var thc=Math.sqrt(radius2-d2);// t0 = first intersect point - entrance on front of sphere var t0=tca-thc;// t1 = second intersect point - exit point on back of sphere var 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 intersectsSphere(sphere){return this.distanceSqToPoint(sphere.center)<=sphere.radius*sphere.radius;},distanceToPlane:function distanceToPlane(plane){var 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;}var t=-(this.origin.dot(plane.normal)+plane.constant)/denominator;// Return if the ray never intersects the plane return t>=0?t:null;},intersectPlane:function intersectPlane(plane,target){var t=this.distanceToPlane(plane);if(t===null){return null;}return this.at(t,target);},intersectsPlane:function intersectsPlane(plane){// check if the ray lies on the plane first var distToPoint=plane.distanceToPoint(this.origin);if(distToPoint===0){return true;}var 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 intersectBox(box,target){var tmin,tmax,tymin,tymax,tzmin,tzmax;var invdirx=1/this.direction.x,invdiry=1/this.direction.y,invdirz=1/this.direction.z;var 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=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=0?tmin:tmax,target);},intersectsBox:function intersectsBox(box){return this.intersectBox(box,_vector$2)!==null;},intersectTriangle:function intersectTriangle(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) var DdN=this.direction.dot(_normal);var 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);var DdQxE2=sign*this.direction.dot(_edge2.crossVectors(_diff,_edge2));// b1 < 0, no intersection if(DdQxE2<0){return null;}var 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. var 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 applyMatrix4(matrix4){this.origin.applyMatrix4(matrix4);this.direction.transformDirection(matrix4);return this;},equals:function equals(ray){return ray.origin.equals(this.origin)&&ray.direction.equals(this.direction);}});/** * @author bhouston / http://clara.io */var _vector1=new Vector3();var _vector2=new Vector3();var _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 set(normal,constant){this.normal.copy(normal);this.constant=constant;return this;},setComponents:function setComponents(x,y,z,w){this.normal.set(x,y,z);this.constant=w;return this;},setFromNormalAndCoplanarPoint:function setFromNormalAndCoplanarPoint(normal,point){this.normal.copy(normal);this.constant=-point.dot(this.normal);return this;},setFromCoplanarPoints:function setFromCoplanarPoints(a,b,c){var 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 clone(){return new this.constructor().copy(this);},copy:function copy(plane){this.normal.copy(plane.normal);this.constant=plane.constant;return this;},normalize:function normalize(){// Note: will lead to a divide by zero if the plane is invalid. var inverseNormalLength=1.0/this.normal.length();this.normal.multiplyScalar(inverseNormalLength);this.constant*=inverseNormalLength;return this;},negate:function negate(){this.constant*=-1;this.normal.negate();return this;},distanceToPoint:function distanceToPoint(point){return this.normal.dot(point)+this.constant;},distanceToSphere:function distanceToSphere(sphere){return this.distanceToPoint(sphere.center)-sphere.radius;},projectPoint:function projectPoint(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 intersectLine(line,target){if(target===undefined){console.warn('THREE.Plane: .intersectLine() target is now required');target=new Vector3();}var direction=line.delta(_vector1);var 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;}var 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 intersectsLine(line){// Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. var startSign=this.distanceToPoint(line.start);var endSign=this.distanceToPoint(line.end);return startSign<0&&endSign>0||endSign<0&&startSign>0;},intersectsBox:function intersectsBox(box){return box.intersectsPlane(this);},intersectsSphere:function intersectsSphere(sphere){return sphere.intersectsPlane(this);},coplanarPoint:function coplanarPoint(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 applyMatrix4(matrix,optionalNormalMatrix){var normalMatrix=optionalNormalMatrix||_normalMatrix.getNormalMatrix(matrix);var referencePoint=this.coplanarPoint(_vector1).applyMatrix4(matrix);var normal=this.normal.applyMatrix3(normalMatrix).normalize();this.constant=-referencePoint.dot(normal);return this;},translate:function translate(offset){this.constant-=offset.dot(this.normal);return this;},equals:function equals(plane){return plane.normal.equals(this.normal)&&plane.constant===this.constant;}});/** * @author bhouston / http://clara.io * @author mrdoob / http://mrdoob.com/ */var _v0$1=new Vector3();var _v1$3=new Vector3();var _v2$1=new Vector3();var _v3=new Vector3();var _vab=new Vector3();var _vac=new Vector3();var _vbc=new Vector3();var _vap=new Vector3();var _vbp=new Vector3();var _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 getNormal(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);var 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 getBarycoord(point,a,b,c,target){_v0$1.subVectors(c,a);_v1$3.subVectors(b,a);_v2$1.subVectors(point,a);var dot00=_v0$1.dot(_v0$1);var dot01=_v0$1.dot(_v1$3);var dot02=_v0$1.dot(_v2$1);var dot11=_v1$3.dot(_v1$3);var dot12=_v1$3.dot(_v2$1);var 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);}var invDenom=1/denom;var u=(dot11*dot02-dot01*dot12)*invDenom;var v=(dot00*dot12-dot01*dot02)*invDenom;// barycentric coordinates must always sum to 1 return target.set(1-u-v,v,u);},containsPoint:function containsPoint(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 getUV(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 isFrontFacing(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 set(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this;},setFromPointsAndIndices:function setFromPointsAndIndices(points,i0,i1,i2){this.a.copy(points[i0]);this.b.copy(points[i1]);this.c.copy(points[i2]);return this;},clone:function clone(){return new this.constructor().copy(this);},copy:function copy(triangle){this.a.copy(triangle.a);this.b.copy(triangle.b);this.c.copy(triangle.c);return this;},getArea:function getArea(){_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 getMidpoint(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 getNormal(target){return Triangle.getNormal(this.a,this.b,this.c,target);},getPlane:function getPlane(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 getBarycoord(point,target){return Triangle.getBarycoord(point,this.a,this.b,this.c,target);},getUV:function getUV(point,uv1,uv2,uv3,target){return Triangle.getUV(point,this.a,this.b,this.c,uv1,uv2,uv3,target);},containsPoint:function containsPoint(point){return Triangle.containsPoint(point,this.a,this.b,this.c);},isFrontFacing:function isFrontFacing(direction){return Triangle.isFrontFacing(this.a,this.b,this.c,direction);},intersectsBox:function intersectsBox(box){return box.intersectsTriangle(this);},closestPointToPoint:function closestPointToPoint(p,target){if(target===undefined){console.warn('THREE.Triangle: .closestPointToPoint() target is now required');target=new Vector3();}var a=this.a,b=this.b,c=this.c;var 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);var d1=_vab.dot(_vap);var 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);var d3=_vab.dot(_vbp);var d4=_vac.dot(_vbp);if(d3>=0&&d4<=d3){// vertex region of B; barycentric coords (0, 1, 0) return target.copy(b);}var 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);var d5=_vab.dot(_vcp);var d6=_vac.dot(_vcp);if(d6>=0&&d5<=d6){// vertex region of C; barycentric coords (0, 0, 1) return target.copy(c);}var 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);}var 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 var 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 equals(triangle){return triangle.a.equals(this.a)&&triangle.b.equals(this.b)&&triangle.c.equals(this.c);}});/** * @author mrdoob / http://mrdoob.com/ */var _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};var _hslA={h:0,s:0,l:0};var _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 set(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 setScalar(scalar){this.r=scalar;this.g=scalar;this.b=scalar;return this;},setHex:function setHex(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 setRGB(r,g,b){this.r=r;this.g=g;this.b=b;return this;},setHSL:function setHSL(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{var p=l<=0.5?l*(1+s):l+s-l*s;var 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 setStyle(style){function handleAlpha(string){if(string===undefined)return;if(parseFloat(string)<1){console.warn('THREE.Color: Alpha component of '+style+' will be ignored.');}}var m;if(m=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)){// rgb / hsl var color;var name=m[1];var 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) var h=parseFloat(color[1])/360;var s=parseInt(color[2],10)/100;var 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 var hex=m[1];var 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 setColorName(style){// color keywords var hex=_colorKeywords[style];if(hex!==undefined){// red this.setHex(hex);}else{// unknown color console.warn('THREE.Color: Unknown color '+style);}return this;},clone:function clone(){return new this.constructor(this.r,this.g,this.b);},copy:function copy(color){this.r=color.r;this.g=color.g;this.b=color.b;return this;},copyGammaToLinear:function copyGammaToLinear(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 copyLinearToGamma(color,gammaFactor){if(gammaFactor===undefined)gammaFactor=2.0;var 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 convertGammaToLinear(gammaFactor){this.copyGammaToLinear(this,gammaFactor);return this;},convertLinearToGamma:function convertLinearToGamma(gammaFactor){this.copyLinearToGamma(this,gammaFactor);return this;},copySRGBToLinear:function copySRGBToLinear(color){this.r=SRGBToLinear(color.r);this.g=SRGBToLinear(color.g);this.b=SRGBToLinear(color.b);return this;},copyLinearToSRGB:function copyLinearToSRGB(color){this.r=LinearToSRGB(color.r);this.g=LinearToSRGB(color.g);this.b=LinearToSRGB(color.b);return this;},convertSRGBToLinear:function convertSRGBToLinear(){this.copySRGBToLinear(this);return this;},convertLinearToSRGB:function convertLinearToSRGB(){this.copyLinearToSRGB(this);return this;},getHex:function getHex(){return this.r*255<<16^this.g*255<<8^this.b*255<<0;},getHexString:function getHexString(){return('000000'+this.getHex().toString(16)).slice(-6);},getHSL:function getHSL(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};}var r=this.r,g=this.g,b=this.b;var max=Math.max(r,g,b);var min=Math.min(r,g,b);var hue,saturation;var lightness=(min+max)/2.0;if(min===max){hue=0;saturation=0;}else{var delta=max-min;saturation=lightness<=0.5?delta/(max+min):delta/(2-max-min);switch(max){case r:hue=(g-b)/delta+(g0)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){var values=[];for(var key in cache){var data=cache[key];delete data.metadata;values.push(data);}return values;}if(isRoot){var textures=extractFromCache(meta.textures);var images=extractFromCache(meta.images);if(textures.length>0)data.textures=textures;if(images.length>0)data.images=images;}return data;},clone:function clone(){return new this.constructor().copy(this);},copy:function copy(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;var srcPlanes=source.clippingPlanes,dstPlanes=null;if(srcPlanes!==null){var n=srcPlanes.length;dstPlanes=new Array(n);for(var 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 dispose(){this.dispatchEvent({type:'dispose'});}});Object.defineProperty(Material.prototype,'needsUpdate',{set:function set(value){if(value===true)this.version++;}});/** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * * parameters = { * color: , * opacity: , * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * specularMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.Multiply, * reflectivity: , * refractionRatio: , * * depthTest: , * depthWrite: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: * } */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/ */var _vector$3=new Vector3();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 set(value){if(value===true)this.version++;}});Object.assign(BufferAttribute.prototype,{isBufferAttribute:true,onUploadCallback:function onUploadCallback(){},setUsage:function setUsage(value){this.usage=value;return this;},copy:function copy(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 copyAt(index1,attribute,index2){index1*=this.itemSize;index2*=attribute.itemSize;for(var i=0,l=this.itemSize;i0;var hasFaceVertexUv2=faceVertexUvs[1]&&faceVertexUvs[1].length>0;// morphs var morphTargets=geometry.morphTargets;var morphTargetsLength=morphTargets.length;var morphTargetsPosition;if(morphTargetsLength>0){morphTargetsPosition=[];for(var i=0;i0){morphTargetsNormal=[];for(var i=0;i0&&faces.length===0){console.error('THREE.DirectGeometry: Faceless geometries are not supported.');}for(var i=0;imax)max=array[_i];}return max;}/** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */var _bufferGeometryId=1;// BufferGeometry uses odd numbers as Id var _m1$2=new Matrix4();var _obj=new Object3D();var _offset=new Vector3();var _box$2=new Box3();var _boxMorphTargets=new Box3();var _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 getIndex(){return this.index;},setIndex:function setIndex(index){if(Array.isArray(index)){this.index=new(arrayMax(index)>65535?Uint32BufferAttribute:Uint16BufferAttribute)(index,1);}else{this.index=index;}},getAttribute:function getAttribute(name){return this.attributes[name];},setAttribute:function setAttribute(name,attribute){this.attributes[name]=attribute;return this;},deleteAttribute:function deleteAttribute(name){delete this.attributes[name];return this;},addGroup:function addGroup(start,count,materialIndex){this.groups.push({start:start,count:count,materialIndex:materialIndex!==undefined?materialIndex:0});},clearGroups:function clearGroups(){this.groups=[];},setDrawRange:function setDrawRange(start,count){this.drawRange.start=start;this.drawRange.count=count;},applyMatrix4:function applyMatrix4(matrix){var position=this.attributes.position;if(position!==undefined){position.applyMatrix4(matrix);position.needsUpdate=true;}var normal=this.attributes.normal;if(normal!==undefined){var normalMatrix=new Matrix3().getNormalMatrix(matrix);normal.applyNormalMatrix(normalMatrix);normal.needsUpdate=true;}var 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 rotateX(angle){// rotate geometry around world x-axis _m1$2.makeRotationX(angle);this.applyMatrix4(_m1$2);return this;},rotateY:function rotateY(angle){// rotate geometry around world y-axis _m1$2.makeRotationY(angle);this.applyMatrix4(_m1$2);return this;},rotateZ:function rotateZ(angle){// rotate geometry around world z-axis _m1$2.makeRotationZ(angle);this.applyMatrix4(_m1$2);return this;},translate:function translate(x,y,z){// translate geometry _m1$2.makeTranslation(x,y,z);this.applyMatrix4(_m1$2);return this;},scale:function scale(x,y,z){// scale geometry _m1$2.makeScale(x,y,z);this.applyMatrix4(_m1$2);return this;},lookAt:function lookAt(vector){_obj.lookAt(vector);_obj.updateMatrix();this.applyMatrix4(_obj.matrix);return this;},center:function center(){this.computeBoundingBox();this.boundingBox.getCenter(_offset).negate();this.translate(_offset.x,_offset.y,_offset.z);return this;},setFromObject:function setFromObject(object){// console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this ); var geometry=object.geometry;if(object.isPoints||object.isLine){var positions=new Float32BufferAttribute(geometry.vertices.length*3,3);var 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){var 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 setFromPoints(points){var position=[];for(var i=0,l=points.length;i0){var normals=new Float32Array(geometry.normals.length*3);this.setAttribute('normal',new BufferAttribute(normals,3).copyVector3sArray(geometry.normals));}if(geometry.colors.length>0){var colors=new Float32Array(geometry.colors.length*3);this.setAttribute('color',new BufferAttribute(colors,3).copyColorsArray(geometry.colors));}if(geometry.uvs.length>0){var uvs=new Float32Array(geometry.uvs.length*2);this.setAttribute('uv',new BufferAttribute(uvs,2).copyVector2sArray(geometry.uvs));}if(geometry.uvs2.length>0){var uvs2=new Float32Array(geometry.uvs2.length*2);this.setAttribute('uv2',new BufferAttribute(uvs2,2).copyVector2sArray(geometry.uvs2));}// groups this.groups=geometry.groups;// morphs for(var name in geometry.morphTargets){var array=[];var morphTargets=geometry.morphTargets[name];for(var i=0,l=morphTargets.length;i0){var skinIndices=new Float32BufferAttribute(geometry.skinIndices.length*4,4);this.setAttribute('skinIndex',skinIndices.copyVector4sArray(geometry.skinIndices));}if(geometry.skinWeights.length>0){var 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 computeBoundingBox(){if(this.boundingBox===null){this.boundingBox=new Box3();}var position=this.attributes.position;var morphAttributesPosition=this.morphAttributes.position;if(position!==undefined){this.boundingBox.setFromBufferAttribute(position);// process morph attributes if present if(morphAttributesPosition){for(var i=0,il=morphAttributesPosition.length;i0)data.userData=this.userData;if(this.parameters!==undefined){var parameters=this.parameters;for(var key in parameters){if(parameters[key]!==undefined)data[key]=parameters[key];}return data;}data.data={attributes:{}};var index=this.index;if(index!==null){data.data.index={type:index.array.constructor.name,array:Array.prototype.slice.call(index.array)};}var attributes=this.attributes;for(var key in attributes){var attribute=attributes[key];var attributeData=attribute.toJSON();if(attribute.name!=='')attributeData.name=attribute.name;data.data.attributes[key]=attributeData;}var morphAttributes={};var hasMorphAttributes=false;for(var key in this.morphAttributes){var attributeArray=this.morphAttributes[key];var array=[];for(var i=0,il=attributeArray.length;i0){morphAttributes[key]=array;hasMorphAttributes=true;}}if(hasMorphAttributes){data.data.morphAttributes=morphAttributes;data.data.morphTargetsRelative=this.morphTargetsRelative;}var groups=this.groups;if(groups.length>0){data.data.groups=JSON.parse(JSON.stringify(groups));}var boundingSphere=this.boundingSphere;if(boundingSphere!==null){data.data.boundingSphere={center:boundingSphere.center.toArray(),radius:boundingSphere.radius};}return data;},clone:function clone(){/* // Handle primitives var parameters = this.parameters; if ( parameters !== undefined ) { var values = []; for ( var key in parameters ) { values.push( parameters[ key ] ); } var 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 copy(source){var name,i,l;// reset this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingBox=null;this.boundingSphere=null;// name this.name=source.name;// index var index=source.index;if(index!==null){this.setIndex(index.clone());}// attributes var attributes=source.attributes;for(name in attributes){var attribute=attributes[name];this.setAttribute(name,attribute.clone());}// morph attributes var morphAttributes=source.morphAttributes;for(name in morphAttributes){var array=[];var morphAttribute=morphAttributes[name];// morphAttribute: array of Float32BufferAttributes for(i=0,l=morphAttribute.length;i0){var morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==undefined){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(m=0,ml=morphAttribute.length;m0){console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');}}},raycast:function raycast(raycaster,intersects){var geometry=this.geometry;var material=this.material;var 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;}var intersection;if(geometry.isBufferGeometry){var a,b,c;var index=geometry.index;var position=geometry.attributes.position;var morphPosition=geometry.morphAttributes.position;var morphTargetsRelative=geometry.morphTargetsRelative;var uv=geometry.attributes.uv;var uv2=geometry.attributes.uv2;var groups=geometry.groups;var drawRange=geometry.drawRange;var i,j,il,jl;var group,groupMaterial;var start,end;if(index!==null){// indexed buffer geometry if(Array.isArray(material)){for(i=0,il=groups.length;i0)uvs=faceVertexUvs;for(var f=0,fl=faces.length;fraycaster.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);var morphInfluences=object.morphTargetInfluences;if(material.morphTargets&&morphPosition&&morphInfluences){_morphA.set(0,0,0);_morphB.set(0,0,0);_morphC.set(0,0,0);for(var i=0,il=morphPosition.length;i0){for(var i=0;i0){this.normalsNeedUpdate=true;}},computeFlatVertexNormals:function computeFlatVertexNormals(){var f,fl,face;this.computeFaceNormals();for(f=0,fl=this.faces.length;f0){this.normalsNeedUpdate=true;}},computeMorphNormals:function computeMorphNormals(){var i,il,f,fl,face;// save original normals // - create temp variables on first access // otherwise just copy (for faster repeated calls) for(f=0,fl=this.faces.length;f=0;i--){var idx=faceIndicesToRemove[i];this.faces.splice(idx,1);for(j=0,jl=this.faceVertexUvs.length;j0;var hasFaceVertexNormal=face.vertexNormals.length>0;var hasFaceColor=face.color.r!==1||face.color.g!==1||face.color.b!==1;var hasFaceVertexColor=face.vertexColors.length>0;var 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){var 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){var vertexNormals=face.vertexNormals;faces.push(getNormalIndex(vertexNormals[0]),getNormalIndex(vertexNormals[1]),getNormalIndex(vertexNormals[2]));}if(hasFaceColor){faces.push(getColorIndex(face.color));}if(hasFaceVertexColor){var vertexColors=face.vertexColors;faces.push(getColorIndex(vertexColors[0]),getColorIndex(vertexColors[1]),getColorIndex(vertexColors[2]));}}function setBit(value,position,enabled){return enabled?value|1<0)data.data.colors=colors;if(uvs.length>0)data.data.uvs=[uvs];// temporal backward compatibility data.data.faces=faces;return data;},clone:function clone(){/* // Handle primitives var parameters = this.parameters; if ( parameters !== undefined ) { var values = []; for ( var key in parameters ) { values.push( parameters[ key ] ); } var 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 copy(source){var i,il,j,jl,k,kl;// 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 var vertices=source.vertices;for(i=0,il=vertices.length;i0?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(var _iy=0;_iy, * vertexShader: , * * wireframe: , * wireframeLinewidth: , * * lights: , * * skinning: , * morphTargets: , * morphNormals: * } */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){var data=Material.prototype.toJSON.call(this,meta);data.uniforms={};for(var name in this.uniforms){var uniform=this.uniforms[name];var 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;var extensions={};for(var 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 copy(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 getWorldDirection(target){if(target===undefined){console.warn('THREE.Camera: .getWorldDirection() target is now required');target=new Vector3();}this.updateMatrixWorld(true);var e=this.matrixWorld.elements;return target.set(-e[8],-e[9],-e[10]).normalize();},updateMatrixWorld:function updateMatrixWorld(force){Object3D.prototype.updateMatrixWorld.call(this,force);this.matrixWorldInverse.getInverse(this.matrixWorld);},updateWorldMatrix:function updateWorldMatrix(updateParents,updateChildren){Object3D.prototype.updateWorldMatrix.call(this,updateParents,updateChildren);this.matrixWorldInverse.getInverse(this.matrixWorld);},clone:function clone(){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 copy(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 setFocalLength(focalLength){// see http://www.bobatkins.com/photography/technical/field_of_view.html var 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 getFocalLength(){var vExtentSlope=Math.tan(MathUtils.DEG2RAD*0.5*this.fov);return 0.5*this.getFilmHeight()/vExtentSlope;},getEffectiveFOV:function getEffectiveFOV(){return MathUtils.RAD2DEG*2*Math.atan(Math.tan(MathUtils.DEG2RAD*0.5*this.fov)/this.zoom);},getFilmWidth:function getFilmWidth(){// film not completely covered in portrait format (aspect < 1) return this.filmGauge*Math.min(this.aspect,1);},getFilmHeight:function getFilmHeight(){// 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 * * var w = 1920; * var h = 1080; * var fullWidth = w * 3; * var 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 setViewOffset(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 clearViewOffset(){if(this.view!==null){this.view.enabled=false;}this.updateProjectionMatrix();},updateProjectionMatrix:function updateProjectionMatrix(){var 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){var fullWidth=view.fullWidth,fullHeight=view.fullHeight;left+=view.offsetX*width/fullWidth;top-=view.offsetY*height/fullHeight;width*=view.width/fullWidth;height*=view.height/fullHeight;}var 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 toJSON(meta){var 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/ */var 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;var 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);var 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);var 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);var 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);var 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);var 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();var currentXrEnabled=renderer.xr.enabled;var currentRenderTarget=renderer.getRenderTarget();renderer.xr.enabled=false;var 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){var currentRenderTarget=renderer.getRenderTarget();for(var 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;var scene=new Scene();var 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 "," #include ","}"].join('\n'),fragmentShader:["uniform sampler2D tEquirect;","varying vec3 vWorldDirection;","#include ","void main() {"," vec3 direction = normalize( vWorldDirection );"," vec2 sampleUV = equirectUv( direction );"," gl_FragColor = texture2D( tEquirect, sampleUV );","}"].join('\n')};var material=new ShaderMaterial({type:'CubemapFromEquirect',uniforms:cloneUniforms(shader.uniforms),vertexShader:shader.vertexShader,fragmentShader:shader.fragmentShader,side:BackSide,blending:NoBlending});material.uniforms.tEquirect.value=texture;var mesh=new Mesh(new BoxBufferGeometry(5,5,5),material);scene.add(mesh);var 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 */var _sphere$1=new Sphere();var _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 set(p0,p1,p2,p3,p4,p5){var 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 clone(){return new this.constructor().copy(this);},copy:function copy(frustum){var planes=this.planes;for(var i=0;i<6;i++){planes[i].copy(frustum.planes[i]);}return this;},setFromProjectionMatrix:function setFromProjectionMatrix(m){var planes=this.planes;var me=m.elements;var me0=me[0],me1=me[1],me2=me[2],me3=me[3];var me4=me[4],me5=me[5],me6=me[6],me7=me[7];var me8=me[8],me9=me[9],me10=me[10],me11=me[11];var 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 intersectsObject(object){var geometry=object.geometry;if(geometry.boundingSphere===null)geometry.computeBoundingSphere();_sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);return this.intersectsSphere(_sphere$1);},intersectsSprite:function intersectsSprite(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 intersectsSphere(sphere){var planes=this.planes;var center=sphere.center;var negRadius=-sphere.radius;for(var i=0;i<6;i++){var distance=planes[i].distanceToPoint(center);if(distance0?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 containsPoint(point){var planes=this.planes;for(var i=0;i<6;i++){if(planes[i].distanceToPoint(point)<0){return false;}}return true;}});/** * Uniforms library for shared webgl shaders */var 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:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowRadius:{},shadowMapSize:{}}},spotShadowMap:{value:[]},spotShadowMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowBias:{},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(){var context=null;var isAnimating=false;var animationLoop=null;function onAnimationFrame(time,frame){if(isAnimating===false)return;animationLoop(time,frame);context.requestAnimationFrame(onAnimationFrame);}return{start:function start(){if(isAnimating===true)return;if(animationLoop===null)return;context.requestAnimationFrame(onAnimationFrame);isAnimating=true;},stop:function stop(){isAnimating=false;},setAnimationLoop:function setAnimationLoop(callback){animationLoop=callback;},setContext:function setContext(value){context=value;}};}/** * @author mrdoob / http://mrdoob.com/ */function WebGLAttributes(gl,capabilities){var isWebGL2=capabilities.isWebGL2;var buffers=new WeakMap();function createBuffer(attribute,bufferType){var array=attribute.array;var usage=attribute.usage;var buffer=gl.createBuffer();gl.bindBuffer(bufferType,buffer);gl.bufferData(bufferType,array,usage);attribute.onUploadCallback();var type=5126;if(_instanceof(array,Float32Array)){type=5126;}else if(_instanceof(array,Float64Array)){console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');}else if(_instanceof(array,Uint16Array)){type=5123;}else if(_instanceof(array,Int16Array)){type=5122;}else if(_instanceof(array,Uint32Array)){type=5125;}else if(_instanceof(array,Int32Array)){type=5124;}else if(_instanceof(array,Int8Array)){type=5120;}else if(_instanceof(array,Uint8Array)){type=5121;}return{buffer:buffer,type:type,bytesPerElement:array.BYTES_PER_ELEMENT,version:attribute.version};}function updateBuffer(buffer,attribute,bufferType){var array=attribute.array;var 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;var data=buffers.get(attribute);if(data){gl.deleteBuffer(data.buffer);buffers.delete(attribute);}}function update(attribute,bufferType){if(attribute.isInterleavedBufferAttribute)attribute=attribute.data;var data=buffers.get(attribute);if(data===undefined){buffers.set(attribute,createBuffer(attribute,bufferType));}else if(data.version0&&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 */var isWebGL2=typeof WebGL2RenderingContext!=='undefined'&&_instanceof(gl,WebGL2RenderingContext)||typeof WebGL2ComputeRenderingContext!=='undefined'&&_instanceof(gl,WebGL2ComputeRenderingContext);/* eslint-enable no-undef */var precision=parameters.precision!==undefined?parameters.precision:'highp';var maxPrecision=getMaxPrecision(precision);if(maxPrecision!==precision){console.warn('THREE.WebGLRenderer:',precision,'not supported, using',maxPrecision,'instead.');precision=maxPrecision;}var logarithmicDepthBuffer=parameters.logarithmicDepthBuffer===true;var maxTextures=gl.getParameter(34930);var maxVertexTextures=gl.getParameter(35660);var maxTextureSize=gl.getParameter(3379);var maxCubemapSize=gl.getParameter(34076);var maxAttributes=gl.getParameter(34921);var maxVertexUniforms=gl.getParameter(36347);var maxVaryings=gl.getParameter(36348);var maxFragmentUniforms=gl.getParameter(36349);var vertexTextures=maxVertexTextures>0;var floatFragmentTextures=isWebGL2||!!extensions.get('OES_texture_float');var floatVertexTextures=vertexTextures&&floatFragmentTextures;var 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(){var scope=this,globalState=null,numGlobalPlanes=0,localClippingEnabled=false,renderingShadows=false,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){var 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{var nGlobal=renderingShadows?0:numGlobalPlanes,lGlobal=nGlobal*4,dstArray=cache.clippingState||null;uniform.value=dstArray;// ensure unique state dstArray=projectPlanes(planes,camera,lGlobal,fromCache);for(var 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){var nPlanes=planes!==null?planes.length:0,dstArray=null;if(nPlanes!==0){dstArray=uniform.value;if(skipTransform!==true||dstArray===null){var flatSize=dstOffset+nPlanes*4,viewMatrix=camera.matrixWorldInverse;viewNormalMatrix.getNormalMatrix(viewMatrix);if(dstArray===null||dstArray.length65535?Uint32BufferAttribute:Uint16BufferAttribute)(indices,1);attribute.version=version;attributes.update(attribute,34963);// var previousAttribute=wireframeAttributes.get(geometry);if(previousAttribute)attributes.remove(previousAttribute);// wireframeAttributes.set(geometry,attribute);}function getWireframeAttribute(geometry){var currentAttribute=wireframeAttributes.get(geometry);if(currentAttribute){var geometryIndex=geometry.index;if(geometryIndex!==null){// if the attribute is obsolete, create a new one if(currentAttribute.version0)return array;// unoptimized: ! isNaN( firstElem ) // see http://jacksondunstan.com/articles/983 var n=nBlocks*blockSize,r=arrayCacheF32[n];if(r===undefined){r=new Float32Array(n);arrayCacheF32[n]=r;}if(nBlocks!==0){firstElem.toArray(r,0);for(var 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(var i=0,l=a.length;i/gm;function resolveIncludes(string){return string.replace(includePattern,includeReplacer);}function includeReplacer(match,include){var string=ShaderChunk[include];if(string===undefined){throw new Error('Can not resolve #include <'+include+'>');}return resolveIncludes(string);}// Unroll Loops var deprecatedUnrollLoopPattern=/#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;var 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){var string='';for(var i=parseInt(start);i0?renderer.gammaFactor:1.0;var customExtensions=parameters.isWebGL2?'':generateExtensions(parameters);var customDefines=generateDefines(defines);var program=gl.createProgram();var 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&¶meters.fog?'#define USE_FOG':'',parameters.useFog&¶meters.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&¶meters.objectSpaceNormalMap?'#define OBJECTSPACE_NORMALMAP':'',parameters.normalMap&¶meters.tangentSpaceNormalMap?'#define TANGENTSPACE_NORMALMAP':'',parameters.clearcoatMap?'#define USE_CLEARCOATMAP':'',parameters.clearcoatRoughnessMap?'#define USE_CLEARCOAT_ROUGHNESSMAP':'',parameters.clearcoatNormalMap?'#define USE_CLEARCOAT_NORMALMAP':'',parameters.displacementMap&¶meters.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&¶meters.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&¶meters.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&¶meters.fog?'#define USE_FOG':'',parameters.useFog&¶meters.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&¶meters.objectSpaceNormalMap?'#define OBJECTSPACE_NORMALMAP':'',parameters.normalMap&¶meters.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&¶meters.rendererExtensionFragDepth?'#define USE_LOGDEPTHBUF_EXT':'',(parameters.extensionShaderTextureLOD||parameters.envMap)&¶meters.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':'',parameters.outputEncoding||parameters.mapEncoding||parameters.matcapEncoding||parameters.envMapEncoding||parameters.emissiveMapEncoding||parameters.lightMapEncoding?ShaderChunk['encodings_pars_fragment']:'',// this code is required here because it is used by the various encoding/decoding function defined below parameters.mapEncoding?getTexelDecodingFunction('mapTexelToLinear',parameters.mapEncoding):'',parameters.matcapEncoding?getTexelDecodingFunction('matcapTexelToLinear',parameters.matcapEncoding):'',parameters.envMapEncoding?getTexelDecodingFunction('envMapTexelToLinear',parameters.envMapEncoding):'',parameters.emissiveMapEncoding?getTexelDecodingFunction('emissiveMapTexelToLinear',parameters.emissiveMapEncoding):'',parameters.lightMapEncoding?getTexelDecodingFunction('lightMapTexelToLinear',parameters.lightMapEncoding):'',parameters.outputEncoding?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){var isGLSL3ShaderMaterial=false;var 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;}var vertexGlsl=prefixVertex+vertexShader;var fragmentGlsl=prefixFragment+fragmentShader;// console.log( '*VERTEX*', vertexGlsl ); // console.log( '*FRAGMENT*', fragmentGlsl ); var glVertexShader=WebGLShader(gl,35633,vertexGlsl);var 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){var programLog=gl.getProgramInfoLog(program).trim();var vertexLog=gl.getShaderInfoLog(glVertexShader).trim();var fragmentLog=gl.getShaderInfoLog(glFragmentShader).trim();var runnable=true;var haveDiagnostics=true;if(gl.getProgramParameter(program,35714)===false){runnable=false;var vertexErrors=getShaderErrors(gl,glVertexShader,'vertex');var 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 var cachedUniforms;this.getUniforms=function(){if(cachedUniforms===undefined){cachedUniforms=new WebGLUniforms(gl,program);}return cachedUniforms;};// set up caching for attribute locations var cachedAttributes;this.getAttributes=function(){if(cachedAttributes===undefined){cachedAttributes=fetchAttributeLocations(gl,program);}return cachedAttributes;};// free resource this.destroy=function(){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){var programs=[];var isWebGL2=capabilities.isWebGL2;var logarithmicDepthBuffer=capabilities.logarithmicDepthBuffer;var floatVertexTextures=capabilities.floatVertexTextures;var precision=capabilities.precision;var maxVertexUniforms=capabilities.maxVertexUniforms;var vertexTextures=capabilities.vertexTextures;var 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'};var 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){var shaderobject;if(shaderID){var shader=ShaderLib[shaderID];shaderobject={name:material.type,uniforms:UniformsUtils.clone(shader.uniforms),vertexShader:shader.vertexShader,fragmentShader:shader.fragmentShader};}else{shaderobject={name:material.type,uniforms:material.uniforms,vertexShader:material.vertexShader,fragmentShader:material.fragmentShader};}return shaderobject;}function allocateBones(object){var skeleton=object.skeleton;var 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) var nVertexUniforms=maxVertexUniforms;var nVertexMatrices=Math.floor((nVertexUniforms-20)/4);var maxBones=Math.min(nVertexMatrices,bones.length);if(maxBones0,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,onBeforeCompile:material.onBeforeCompile};return parameters;};this.getProgramCacheKey=function(parameters){var array=[];if(parameters.shaderID){array.push(parameters.shaderID);}else{array.push(parameters.fragmentShader);array.push(parameters.vertexShader);}if(parameters.defines!==undefined){for(var name in parameters.defines){array.push(name);array.push(parameters.defines[name]);}}if(parameters.isRawShaderMaterial===undefined){for(var i=0;i1)opaque.sort(customOpaqueSort||painterSortStable);if(transparent.length>1)transparent.sort(customTransparentSort||reversePainterSortStable);}function finish(){// Clear references from inactive renderItems in the list for(var i=renderItemsIndex,il=renderItems.length;i, * * map: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * wireframe: , * wireframeLinewidth: * } */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: , * nearDistance: , * farDistance: , * * skinning: , * morphTargets: , * * map: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: * * } */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 \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){var _frustum=new Frustum(),_shadowMapSize=new Vector2(),_viewportSize=new Vector2(),_viewport=new Vector4(),_depthMaterials=[],_distanceMaterials=[],_materialCache={};var shadowSide={0:BackSide,1:FrontSide,2:DoubleSide};var 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});var shadowMaterialHorizonal=shadowMaterialVertical.clone();shadowMaterialHorizonal.defines.HORIZONAL_PASS=1;var fullScreenTri=new BufferGeometry();fullScreenTri.setAttribute("position",new BufferAttribute(new Float32Array([-1,-1,0.5,3,-1,0.5,-1,3,0.5]),3));var fullScreenMesh=new Mesh(fullScreenTri,shadowMaterialVertical);var 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;var currentRenderTarget=_renderer.getRenderTarget();var activeCubeFace=_renderer.getActiveCubeFace();var activeMipmapLevel=_renderer.getActiveMipmapLevel();var _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(var i=0,il=lights.length;imaxTextureSize||_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){var 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){var 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();var viewportCount=shadow.getViewportCount();for(var vp=0;vp0;}var 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);}}var 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 var keyA=result.uuid,keyB=material.uuid;var materialsForVariant=_materialCache[keyA];if(materialsForVariant===undefined){materialsForVariant={};_materialCache[keyA]=materialsForVariant;}var 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;var 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);var geometry=_objects.update(object);var material=object.material;if(Array.isArray(material)){var groups=geometry.groups;for(var k=0,kl=groups.length;k=1.0;}else if(glVersion.indexOf('OpenGL ES')!==-1){version=parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion)[1]);lineWidthAvailable=version>=2.0;}var currentTextureSlot=null;var currentBoundTextures={};var currentScissor=new Vector4();var currentViewport=new Vector4();function createTexture(type,target,count){var data=new Uint8Array(4);// 4 is required to match default unpack alignment of 4. var texture=gl.createTexture();gl.bindTexture(type,texture);gl.texParameteri(type,10241,9728);gl.texParameteri(type,10240,9728);for(var i=0;imaxSize||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'&&_instanceof(image,HTMLImageElement)||typeof HTMLCanvasElement!=='undefined'&&_instanceof(image,HTMLCanvasElement)||typeof ImageBitmap!=='undefined'&&_instanceof(image,ImageBitmap)){var floor=needsPowerOfTwo?MathUtils.floorPowerOfTwo:Math.floor;var width=floor(scale*image.width);var height=floor(scale*image.height);if(_canvas===undefined)_canvas=createCanvas(width,height);// cube textures can't reuse the same canvas var canvas=needsNewCanvas?createCanvas(width,height):_canvas;canvas.width=width;canvas.height=height;var 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);var 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+'\'');}var 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){var texture=event.target;texture.removeEventListener('dispose',onTextureDispose);deallocateTexture(texture);if(texture.isVideoTexture){_videoTextures.delete(texture);}info.memory.textures--;}function onRenderTargetDispose(event){var renderTarget=event.target;renderTarget.removeEventListener('dispose',onRenderTargetDispose);deallocateRenderTarget(renderTarget);info.memory.textures--;}// function deallocateTexture(texture){var textureProperties=properties.get(texture);if(textureProperties.__webglInit===undefined)return;_gl.deleteTexture(textureProperties.__webglTexture);properties.remove(texture);}function deallocateRenderTarget(renderTarget){var renderTargetProperties=properties.get(renderTarget);var 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(var 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);}// var textureUnits=0;function resetTextureUnits(){textureUnits=0;}function allocateTextureUnit(){var 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){var textureProperties=properties.get(texture);if(texture.isVideoTexture)updateVideoTexture(texture);if(texture.version>0&&textureProperties.__version!==texture.version){var 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){var 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){var 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;var 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);var isCompressed=texture&&(texture.isCompressedTexture||texture.image[0].isCompressedTexture);var isDataTexture=texture.image[0]&&texture.image[0].isDataTexture;var cubeImage=[];for(var 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];}}var 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);var mipmaps;if(isCompressed){for(var i=0;i<6;i++){mipmaps=cubeImage[i].mipmaps;for(var j=0;j1||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){var 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);var needsPowerOfTwo=textureNeedsPowerOfTwo(texture)&&isPowerOfTwo(texture.image)===false;var image=resizeImage(texture.image,needsPowerOfTwo,false,maxTextureSize);var supportsMips=isPowerOfTwo(image)||isWebGL2,glFormat=utils.convert(texture.format),glType=utils.convert(texture.type),glInternalFormat=getInternalFormat(texture.internalFormat,glFormat,glType);setTextureParameters(textureType,texture,supportsMips);var mipmap,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(var i=0,il=mipmaps.length;i0&&supportsMips){for(var i=0,il=mipmaps.length;i=0){var geometryAttribute=geometryAttributes[name];if(geometryAttribute!==undefined){var normalized=geometryAttribute.normalized;var size=geometryAttribute.itemSize;var attribute=attributes.get(geometryAttribute);// TODO Attribute may not be available on context restore if(attribute===undefined)continue;var buffer=attribute.buffer;var type=attribute.type;var bytesPerElement=attribute.bytesPerElement;if(geometryAttribute.isInterleavedBufferAttribute){var data=geometryAttribute.data;var stride=data.stride;var offset=geometryAttribute.offset;if(data&&data.isInstancedInterleavedBuffer){state.enableAttributeAndDivisor(programAttribute,data.meshPerAttribute);if(geometry._maxInstanceCount===undefined){geometry._maxInstanceCount=data.meshPerAttribute*data.count;}}else{state.enableAttribute(programAttribute);}_gl.bindBuffer(34962,buffer);state.vertexAttribPointer(programAttribute,size,type,normalized,stride*bytesPerElement,offset*bytesPerElement);}else{if(geometryAttribute.isInstancedBufferAttribute){state.enableAttributeAndDivisor(programAttribute,geometryAttribute.meshPerAttribute);if(geometry._maxInstanceCount===undefined){geometry._maxInstanceCount=geometryAttribute.meshPerAttribute*geometryAttribute.count;}}else{state.enableAttribute(programAttribute);}_gl.bindBuffer(34962,buffer);state.vertexAttribPointer(programAttribute,size,type,normalized,0,0);}}else if(name==='instanceMatrix'){var attribute=attributes.get(object.instanceMatrix);// TODO Attribute may not be available on context restore if(attribute===undefined)continue;var buffer=attribute.buffer;var type=attribute.type;state.enableAttributeAndDivisor(programAttribute+0,1);state.enableAttributeAndDivisor(programAttribute+1,1);state.enableAttributeAndDivisor(programAttribute+2,1);state.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){var 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);}}}}}state.disableUnusedAttributes();}// 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);var compiled={};scene.traverse(function(object){var material=object.material;if(material){if(Array.isArray(material)){for(var _i2=0;_i2=0){material.numSupportedMorphTargets++;}}}if(material.morphNormals){material.numSupportedMorphNormals=0;for(var i=0;i<_this.maxMorphNormals;i++){if(programAttributes['morphNormal'+i]>=0){material.numSupportedMorphNormals++;}}}var 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 }var progUniforms=materialProperties.program.getUniforms(),uniformsList=WebGLUniforms.seqWithValue(progUniforms.seq,uniforms);materialProperties.uniformsList=uniformsList;}function setProgram(camera,scene,material,object){textures.resetTextureUnits();var fog=scene.fog;var environment=material.isMeshStandardMaterial?scene.environment:null;var encoding=_currentRenderTarget===null?_this.outputEncoding:_currentRenderTarget.texture.encoding;var materialProperties=properties.get(material);var lights=currentRenderState.state.lights;if(_clippingEnabled){if(_localClippingEnabled||camera!==_currentCamera){var 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;}var refreshProgram=false;var refreshMaterial=false;var refreshLights=false;var 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){var 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.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');var skeleton=object.skeleton;if(skeleton){var 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) var size=Math.sqrt(bones.length*4);// 4 pixels needed for 1 matrix size=MathUtils.ceilPowerOfTwo(size);size=Math.max(size,4);var boneMatrices=new Float32Array(size*size*4);// 4 floats per RGBA pixel boneMatrices.set(skeleton.boneMatrices);// copy current values var 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);p_uniforms.setValue(_gl,'toneMappingWhitePoint',_this.toneMappingWhitePoint);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);}var framebuffer=_framebuffer;var isCube=false;if(renderTarget){var __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){var 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;}var framebuffer=properties.get(renderTarget).__webglFramebuffer;if(renderTarget.isWebGLCubeRenderTarget&&activeCubeFaceIndex!==undefined){framebuffer=framebuffer[activeCubeFaceIndex];}if(framebuffer){var restore=false;if(framebuffer!==_currentFramebuffer){_gl.bindFramebuffer(36160,framebuffer);restore=true;}try{var texture=renderTarget.texture;var textureFormat=texture.format;var 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;var levelScale=Math.pow(2,-level);var width=Math.floor(texture.image.width*levelScale);var height=Math.floor(texture.image.height*levelScale);var 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;var width=srcTexture.image.width;var height=srcTexture.image.height;var glFormat=utils.convert(dstTexture.format);var glType=utils.convert(dstTexture.type);textures.setTexture2D(dstTexture,0);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 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 clone(){return new FogExp2(this.color,this.density);},toJSON:function toJSON()/* 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 clone(){return new Fog(this.color,this.near,this.far);},toJSON:function toJSON()/* 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;}Object.defineProperty(InterleavedBuffer.prototype,'needsUpdate',{set:function set(value){if(value===true)this.version++;}});Object.assign(InterleavedBuffer.prototype,{isInterleavedBuffer:true,onUploadCallback:function onUploadCallback(){},setUsage:function setUsage(value){this.usage=value;return this;},copy:function copy(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 copyAt(index1,attribute,index2){index1*=this.stride;index2*=attribute.stride;for(var i=0,l=this.stride;i, * map: new THREE.Texture( ), * alphaMap: new THREE.Texture( ), * rotation: , * sizeAttenuation: * } */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/ */var _geometry;var _intersectPoint=new Vector3();var _worldScale=new Vector3();var _mvPosition=new Vector3();var _alignedPosition=new Vector2();var _rotatedPosition=new Vector2();var _viewWorldMatrix=new Matrix4();var _vA$1=new Vector3();var _vB$1=new Vector3();var _vC$1=new Vector3();var _uvA$1=new Vector2();var _uvB$1=new Vector2();var _uvC$1=new Vector2();function Sprite(material){Object3D.call(this);this.type='Sprite';if(_geometry===undefined){_geometry=new BufferGeometry();var 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]);var 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 raycast(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);}var rotation=this.material.rotation;var sin,cos;if(rotation!==0){cos=Math.cos(rotation);sin=Math.sin(rotation);}var 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 var 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;}}var distance=raycaster.ray.origin.distanceTo(_intersectPoint);if(distanceraycaster.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});},clone:function clone(){return new this.constructor(this.material).copy(this);},copy:function copy(source){Object3D.prototype.copy.call(this,source);if(source.center!==undefined)this.center.copy(source.center);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/ */var _v1$4=new Vector3();var _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 copy(source){Object3D.prototype.copy.call(this,source,false);var levels=source.levels;for(var i=0,l=levels.length;i0){for(var i=1,l=levels.length;i0){_v1$4.setFromMatrixPosition(this.matrixWorld);var distance=raycaster.ray.origin.distanceTo(_v1$4);this.getObjectForDistance(distance).raycast(raycaster,intersects);}},update:function update(camera){var levels=this.levels;if(levels.length>1){_v1$4.setFromMatrixPosition(camera.matrixWorld);_v2$2.setFromMatrixPosition(this.matrixWorld);var distance=_v1$4.distanceTo(_v2$2)/camera.zoom;levels[0].object.visible=true;for(var i=1,l=levels.length;i=levels[i].distance){levels[i-1].object.visible=false;levels[i].object.visible=true;}else{break;}}this._currentLevel=i-1;for(;i, * opacity: , * * linewidth: , * 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/ */var _start=new Vector3();var _end=new Vector3();var _inverseMatrix$1=new Matrix4();var _ray$1=new Ray();var _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,computeLineDistances:function computeLineDistances(){var geometry=this.geometry;if(geometry.isBufferGeometry){// we assume non-indexed geometry if(geometry.index===null){var positionAttribute=geometry.attributes.position;var lineDistances=[0];for(var i=1,l=positionAttribute.count;ilocalThresholdSq)continue;interRay.applyMatrix4(this.matrixWorld);//Move back to world space for distance calculation var distance=raycaster.ray.origin.distanceTo(interRay);if(distanceraycaster.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(var i=0,l=positions.length/3-1;ilocalThresholdSq)continue;interRay.applyMatrix4(this.matrixWorld);//Move back to world space for distance calculation var distance=raycaster.ray.origin.distanceTo(interRay);if(distanceraycaster.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){var vertices=geometry.vertices;var nbVertices=vertices.length;for(var i=0;ilocalThresholdSq)continue;interRay.applyMatrix4(this.matrixWorld);//Move back to world space for distance calculation var distance=raycaster.ray.origin.distanceTo(interRay);if(distanceraycaster.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 updateMorphTargets(){var geometry=this.geometry;var m,ml,name;if(geometry.isBufferGeometry){var morphAttributes=geometry.morphAttributes;var keys=Object.keys(morphAttributes);if(keys.length>0){var morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==undefined){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(m=0,ml=morphAttribute.length;m0){console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');}}},clone:function clone(){return new this.constructor(this.geometry,this.material).copy(this);}});/** * @author mrdoob / http://mrdoob.com/ */var _start$1=new Vector3();var _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 computeLineDistances(){var geometry=this.geometry;if(geometry.isBufferGeometry){// we assume non-indexed geometry if(geometry.index===null){var positionAttribute=geometry.attributes.position;var lineDistances=[];for(var i=0,l=positionAttribute.count;i, * opacity: , * map: new THREE.Texture( ), * alphaMap: new THREE.Texture( ), * * size: , * sizeAttenuation: * * morphTargets: * } */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/ */var _inverseMatrix$2=new Matrix4();var _ray$2=new Ray();var _sphere$3=new Sphere();var _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,raycast:function raycast(raycaster,intersects){var geometry=this.geometry;var matrixWorld=this.matrixWorld;var 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);var localThreshold=threshold/((this.scale.x+this.scale.y+this.scale.z)/3);var localThresholdSq=localThreshold*localThreshold;if(geometry.isBufferGeometry){var index=geometry.index;var attributes=geometry.attributes;var positions=attributes.position.array;if(index!==null){var indices=index.array;for(var i=0,il=indices.length;i0){var morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==undefined){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(m=0,ml=morphAttribute.length;m0){console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');}}},clone:function clone(){return new this.constructor(this.geometry,this.material).copy(this);}});function testPoint(point,index,localThresholdSq,matrixWorld,raycaster,intersects,object){var rayPointDistanceSq=_ray$2.distanceSqToPoint(point);if(rayPointDistanceSqraycaster.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 update(){var 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 var vertices=[];// helper variables var i,j,l,o,ol;var edge=[0,0],edges={},e,edge1,edge2;var key,keys=['a','b','c'];var vertex;// different logic for Geometry and BufferGeometry if(geometry&&geometry.isGeometry){// create a data structure that contains all edges without duplicates var faces=geometry.faces;for(i=0,l=faces.length;i=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(i=0;i0.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){var stride=index*3;vertex.x=vertices[stride+0];vertex.y=vertices[stride+1];vertex.z=vertices[stride+2];}function correctUVs(){var a=new Vector3();var b=new Vector3();var c=new Vector3();var centroid=new Vector3();var uvA=new Vector2();var uvB=new Vector2();var uvC=new Vector2();for(var i=0,j=0;i80*dim){minX=maxX=data[0];minY=maxY=data[1];for(var i=dim;imaxX)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){var i,last;if(clockwise===signedArea(data,start,end,dim)>0){for(i=start;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;var 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);var 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){var 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 var 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){var 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 var minTX=a.xb.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; var minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);var 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){var p=start;do{var 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 var a=start;do{var b=a.next.next;while(b!==a.prev){if(a.i!==b.i&&isValidDiagonal(a,b)){// split the polygon in two by the diagonal var 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){var queue=[],i,len,start,end,list;for(i=0,len=holeIndices.length;i=p.next.y&&p.next.y!==p.y){var 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.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(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){var 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){var 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;i0||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){var p=start,leftmost=start;do{if(p.x=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){var o1=sign(area(p1,q1,p2));var o2=sign(area(p1,q1,q2));var o3=sign(area(p2,q2,p1));var 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){var 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){var 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){var a2=new Node$1(a.i,a.x,a.y),b2=new Node$1(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){var p=new Node$1(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$1(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){var sum=0;for(var i=start,j=end-dim;i2&&points[l-1].equals(points[0])){points.pop();}}function addContour(vertices,contour){for(var i=0;i, // number of points on the curves * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too * depth: , // Depth to extrude the shape * * bevelEnabled: , // turn on bevel * bevelThickness: , // how deep into the original shape bevel goes * bevelSize: , // how far from shape outline (including bevelOffset) is bevel * bevelOffset: , // how far from shape outline does bevel start * bevelSegments: , // number of bevel layers * * extrudePath: // curve to extrude shape along * * UVGenerator: // 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(){var data=Geometry.prototype.toJSON.call(this);var shapes=this.parameters.shapes;var 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];var scope=this;var verticesArray=[];var uvArray=[];for(var i=0,l=shapes.length;iNumber.EPSILON){// not collinear // length of vectors for normalizing var v_prev_len=Math.sqrt(v_prev_lensq);var 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 var ptPrevShift_x=inPrev.x-v_prev_y/v_prev_len;var ptPrevShift_y=inPrev.y+v_prev_x/v_prev_len;var ptNextShift_x=inNext.x-v_next_y/v_next_len;var ptNextShift_y=inNext.y+v_next_x/v_next_len;// scaling factor for v_prev to intersection point var 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 var 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 var 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);}var contourMovements=[];for(var i=0,il=contour.length,j=il-1,k=i+1;i 0; b -- ) { t=b/bevelSegments;z=bevelThickness*Math.cos(t*Math.PI/2);bs=bevelSize*Math.sin(t*Math.PI/2)+bevelOffset;// contract shape for(i=0,il=contour.length;i=0;b--){t=b/bevelSegments;z=bevelThickness*Math.cos(t*Math.PI/2);bs=bevelSize*Math.sin(t*Math.PI/2)+bevelOffset;// contract shape for(i=0,il=contour.length;i=0){j=i;k=i-1;if(k<0)k=contour.length-1;//console.log('b', i,j, i-1, k,vertices.length); var s=0,sl=steps+bevelSegments*2;for(s=0;s, // font * * size: , // size of the text * height: , // thickness to extrude text * curveSegments: , // number of points on the curves * * bevelEnabled: , // turn on bevel * bevelThickness: , // how deep into text bevel goes * bevelSize: , // how far from text outline (including bevelOffset) is bevel * bevelOffset: // 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||{};var font=parameters.font;if(!(font&&font.isFont)){console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');return new Geometry();}var 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;var thetaEnd=Math.min(thetaStart+thetaLength,Math.PI);var ix,iy;var index=0;var grid=[];var vertex=new Vector3();var normal=new Vector3();// buffers var indices=[];var vertices=[];var normals=[];var uvs=[];// generate vertices, normals and uvs for(iy=0;iy<=heightSegments;iy++){var verticesRow=[];var v=iy/heightSegments;// special case for the poles var uOffset=0;if(iy==0&&thetaStart==0){uOffset=0.5/widthSegments;}else if(iy==heightSegments&&thetaEnd==Math.PI){uOffset=-0.5/widthSegments;}for(ix=0;ix<=widthSegments;ix++){var 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(iy=0;iy0)indices.push(a,b,d);if(iy!==heightSegments-1||thetaEnd0)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(){var x,y;var normal=new Vector3();var vertex=new Vector3();var groupCount=0;// this will be used to calculate the normal var slope=(radiusBottom-radiusTop)/height;// generate vertices, normals and uvs for(y=0;y<=heightSegments;y++){var indexRow=[];var v=y/heightSegments;// calculate the radius of the current row var radius=v*(radiusBottom-radiusTop)+radiusTop;for(x=0;x<=radialSegments;x++){var u=x/radialSegments;var theta=u*thetaLength+thetaStart;var sinTheta=Math.sin(theta);var 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(x=0;x * } */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: , * roughness: , * metalness: , * opacity: , * * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * roughnessMap: new THREE.Texture( ), * * metalnessMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * envMapIntensity: * * refractionRatio: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */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: , * clearcoatMap: new THREE.Texture( ), * clearcoatRoughness: , * clearcoatRoughnessMap: new THREE.Texture( ), * clearcoatNormalScale: , * clearcoatNormalMap: new THREE.Texture( ), * * reflectivity: , * * sheen: , * * transparency: * } */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: , * specular: , * shininess: , * opacity: , * * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * specularMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.MultiplyOperation, * reflectivity: , * refractionRatio: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */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: , * specular: , * shininess: , * * map: new THREE.Texture( ), * gradientMap: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * specularMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */function MeshToonMaterial(parameters){Material.call(this);this.defines={'TOON':''};this.type='MeshToonMaterial';this.color=new Color(0xffffff);this.specular=new Color(0x111111);this.shininess=30;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.specularMap=null;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.specular.copy(source.specular);this.shininess=source.shininess;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.specularMap=source.specularMap;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: , * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * wireframe: , * wireframeLinewidth: * * skinning: , * morphTargets: , * morphNormals: * } */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: , * opacity: , * * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * specularMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.Multiply, * reflectivity: , * refractionRatio: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */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: , * opacity: , * * matcap: new THREE.Texture( ), * * map: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * alphaMap: new THREE.Texture( ), * * skinning: , * morphTargets: , * morphNormals: * } */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: , * opacity: , * * linewidth: , * * scale: , * dashSize: , * gapSize: * } */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/ */var AnimationUtils={// same as Array.prototype.slice, but also works on typed arrays arraySlice:function arraySlice(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 convertArray(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 isTypedArray(object){return ArrayBuffer.isView(object)&&!_instanceof(object,DataView);},// returns an array by which times and values can be sorted getKeyframeOrder:function getKeyframeOrder(times){function compareTime(i,j){return times[i]-times[j];}var n=times.length;var result=new Array(n);for(var 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 sortedArray(values,stride,order){var nValues=values.length;var result=new values.constructor(nValues);for(var i=0,dstOffset=0;dstOffset!==nValues;++i){var srcOffset=order[i]*stride;for(var j=0;j!==stride;++j){result[dstOffset++]=values[srcOffset+j];}}return result;},// function for parsing AOS keyframe formats flattenJSON:function flattenJSON(jsonKeys,times,values,valuePropertyName){var i=1,key=jsonKeys[0];while(key!==undefined&&key[valuePropertyName]===undefined){key=jsonKeys[i++];}if(key===undefined)return;// no data var 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 subclip(sourceClip,name,startFrame,endFrame,fps){fps=fps||30;var clip=sourceClip.clone();clip.name=name;var tracks=[];for(var i=0;i=endFrame)continue;times.push(track.times[j]);for(var k=0;kclip.tracks[i].times[0]){minStartTime=clip.tracks[i].times[0];}}// shift all tracks such that clip begins at t=0 for(var i=0;i=referenceTrack.times[lastIndex]){// Reference frame is after the last keyframe, so just use the last keyframe var startIndex=lastIndex*valueSize;referenceValue=AnimationUtils.arraySlice(referenceTrack.values,startIndex);}else{// Interpolate to the reference value var interpolant=referenceTrack.createInterpolant();interpolant.evaluate(referenceTime);referenceValue=interpolant.resultBuffer;}// Conjugate the quaternion if(referenceTrackType==='quaternion'){var 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 var numTimes=targetTrack.times.length;for(var j=0;j= t1 || t1 === undefined ) { forward_scan:if(!(t=t0)){// looping? var t1global=pp[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>>1;if(t seconds conversions) scale:function scale(timeScale){if(timeScale!==1.0){var times=this.times;for(var 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 trim(startTime,endTime){var times=this.times,nKeys=times.length,from=0,to=nKeys-1;while(from!==nKeys&×[from]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;}var 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 validate(){var valid=true;var valueSize=this.getValueSize();if(valueSize-Math.floor(valueSize)!==0){console.error('THREE.KeyframeTrack: Invalid value size in track.',this);valid=false;}var times=this.times,values=this.values,nKeys=times.length;if(nKeys===0){console.error('THREE.KeyframeTrack: Track is empty.',this);valid=false;}var prevTime=null;for(var i=0;i!==nKeys;i++){var 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(var i=0,n=values.length;i!==n;++i){var 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 optimize(){// times or values may be shared with other tracks, so overwriting is unsafe var times=AnimationUtils.arraySlice(this.times),values=AnimationUtils.arraySlice(this.values),stride=this.getValueSize(),smoothInterpolation=this.getInterpolation()===InterpolateSmooth,writeIndex=1,lastIndex=times.length-1;for(var i=1;i0){times[writeIndex]=times[lastIndex];for(var 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 clone(){var times=AnimationUtils.arraySlice(this.times,0);var values=AnimationUtils.arraySlice(this.values,0);var TypedKeyframeTrack=this.constructor;var 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 interpolate_(i1,t0,t,t1){var result=this.resultBuffer,values=this.sampleValues,stride=this.valueSize,offset=i1*stride,alpha=(t-t0)/(t1-t0);for(var 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 InterpolantFactoryMethodLinear(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');}var trackType=getTrackTypeForValueTypeName(json.type);if(json.times===undefined){var 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 parse(json){var tracks=[],jsonTracks=json.tracks,frameTime=1.0/(json.fps||1.0);for(var 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 toJSON(clip){var tracks=[],clipTracks=clip.tracks;var json={'name':clip.name,'duration':clip.duration,'tracks':tracks,'uuid':clip.uuid,'blendMode':clip.blendMode};for(var i=0,n=clipTracks.length;i!==n;++i){tracks.push(KeyframeTrack.toJSON(clipTracks[i]));}return json;},CreateFromMorphTargetSequence:function CreateFromMorphTargetSequence(name,morphTargetSequence,fps,noLoop){var numMorphTargets=morphTargetSequence.length;var tracks=[];for(var i=0;i1){var name=parts[1];var animationMorphTargets=animationToMorphTargets[name];if(!animationMorphTargets){animationToMorphTargets[name]=animationMorphTargets=[];}animationMorphTargets.push(morphTarget);}}var clips=[];for(var name in animationToMorphTargets){clips.push(AnimationClip.CreateFromMorphTargetSequence(name,animationToMorphTargets[name],fps,noLoop));}return clips;},// parse the animation.hierarchy format parseAnimation:function parseAnimation(animation,bones){if(!animation){console.error('THREE.AnimationClip: No animation in JSONLoader data.');return null;}var addNonemptyTrack=function addNonemptyTrack(trackType,trackName,animationKeys,propertyName,destTracks){// only return track if there are actually keys. if(animationKeys.length!==0){var times=[];var 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));}}};var tracks=[];var clipName=animation.name||'default';// automatic length determination in AnimationClip. var duration=animation.length||-1;var fps=animation.fps||30;var blendMode=animation.blendMode;var hierarchyTracks=animation.hierarchy||[];for(var h=0;h0||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 getPoint()/* 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 getPointAt(u,optionalTarget){var t=this.getUtoTmapping(u);return this.getPoint(t,optionalTarget);},// Get sequence of points using getPoint( t ) getPoints:function getPoints(divisions){if(divisions===undefined)divisions=5;var points=[];for(var d=0;d<=divisions;d++){points.push(this.getPoint(d/divisions));}return points;},// Get sequence of points using getPointAt( u ) getSpacedPoints:function getSpacedPoints(divisions){if(divisions===undefined)divisions=5;var points=[];for(var d=0;d<=divisions;d++){points.push(this.getPointAt(d/divisions));}return points;},// Get total curve arc length getLength:function getLength(){var lengths=this.getLengths();return lengths[lengths.length-1];},// Get list of cumulative segment lengths getLengths:function getLengths(divisions){if(divisions===undefined)divisions=this.arcLengthDivisions;if(this.cacheArcLengths&&this.cacheArcLengths.length===divisions+1&&!this.needsUpdate){return this.cacheArcLengths;}this.needsUpdate=false;var cache=[];var current,last=this.getPoint(0);var p,sum=0;cache.push(0);for(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 updateArcLengths(){this.needsUpdate=true;this.getLengths();},// Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant getUtoTmapping:function getUtoTmapping(u,distance){var arcLengths=this.getLengths();var i=0,il=arcLengths.length;var 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 var 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 var lengthBefore=arcLengths[i];var lengthAfter=arcLengths[i+1];var segmentLength=lengthAfter-lengthBefore;// determine where we are between the 'before' and 'after' points var segmentFraction=(targetArcLength-lengthBefore)/segmentLength;// add that fractional amount to t var 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 getTangent(t,optionalTarget){var delta=0.0001;var t1=t-delta;var t2=t+delta;// Capping in case of danger if(t1<0)t1=0;if(t2>1)t2=1;var pt1=this.getPoint(t1);var pt2=this.getPoint(t2);var tangent=optionalTarget||(pt1.isVector2?new Vector2():new Vector3());tangent.copy(pt2).sub(pt1).normalize();return tangent;},getTangentAt:function getTangentAt(u,optionalTarget){var t=this.getUtoTmapping(u);return this.getTangent(t,optionalTarget);},computeFrenetFrames:function computeFrenetFrames(segments,closed){// see http://www.cs.indiana.edu/pub/techreports/TR425.pdf var normal=new Vector3();var tangents=[];var normals=[];var binormals=[];var vec=new Vector3();var mat=new Matrix4();var i,u,theta;// compute the tangent vectors for each segment on the curve for(i=0;i<=segments;i++){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();var min=Number.MAX_VALUE;var tx=Math.abs(tangents[0].x);var ty=Math.abs(tangents[0].y);var 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(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();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){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(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 clone(){return new this.constructor().copy(this);},copy:function copy(source){this.arcLengthDivisions=source.arcLengthDivisions;return this;},toJSON:function toJSON(){var data={metadata:{version:4.5,type:'Curve',generator:'Curve.toJSON'}};data.arcLengthDivisions=this.arcLengthDivisions;data.type=this.type;return data;},fromJSON:function fromJSON(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){var point=optionalTarget||new Vector2();var twoPi=Math.PI*2;var deltaAngle=this.aEndAngle-this.aStartAngle;var samePoints=Math.abs(deltaAngle)twoPi){deltaAngle-=twoPi;}if(deltaAngle0?0:(Math.floor(Math.abs(intPoint)/l)+1)*l;}else if(weight===0&&intPoint===l-1){intPoint=l-2;weight=1;}var 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+2points.length-2?points.length-1:intPoint+1];var 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(var i=0,l=source.points.length;i=d){var diff=curveLengths[i]-d;var curve=this.curves[i];var segmentLength=curve.getLength();var u=segmentLength===0?0:1-diff/segmentLength;return curve.getPointAt(u);}i++;}return null;// loop where sum != 0, sum > d , sum+1 1&&!points[points.length-1].equals(points[0])){points.push(points[0]);}return points;},copy:function copy(source){Curve.prototype.copy.call(this,source);this.curves=[];for(var i=0,l=source.curves.length;i0){// if a previous curve is present, attempt to join var firstPoint=curve.getPoint(0);if(!firstPoint.equals(this.currentPoint)){this.lineTo(firstPoint.x,firstPoint.y);}}this.curves.push(curve);var lastPoint=curve.getPoint(1);this.currentPoint.copy(lastPoint);return this;},copy:function copy(source){CurvePath.prototype.copy.call(this,source);this.currentPoint.copy(source.currentPoint);return this;},toJSON:function toJSON(){var data=CurvePath.prototype.toJSON.call(this);data.currentPoint=this.currentPoint.toArray();return data;},fromJSON:function fromJSON(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 getPointsHoles(divisions){var holesPts=[];for(var i=0,l=this.holes.length;i0?true:false;}else{material.vertexColors=json.vertexColors;}}// Shader Material if(json.uniforms!==undefined){for(var name in json.uniforms){var 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(var 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){var 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 setTextures(value){this.textures=value;return this;}});/** * @author Don McCurdy / https://www.donmccurdy.com */var LoaderUtils={decodeText:function decodeText(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. var s='';for(var i=0,il=array.length;i0){var manager=new LoadingManager(onLoad);var loader=new ImageLoader(manager);loader.setCrossOrigin(this.crossOrigin);for(var i=0,il=json.length;i 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 var inside=false;for(var p=polyLen-1,q=0;qNumber.EPSILON){// not parallel if(edgeDy<0){edgeLowPt=inPolygon[q];edgeDx=-edgeDx;edgeHighPt=inPolygon[p];edgeDy=-edgeDy;}if(inPt.yedgeHighPt.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{var 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;}var isClockWise=ShapeUtils.isClockWise;var subPaths=this.subPaths;if(subPaths.length===0)return[];if(noHoles===true)return toShapesNoHoles(subPaths);var solid,tmpPath,tmpShape,shapes=[];if(subPaths.length===1){tmpPath=subPaths[0];tmpShape=new Shape();tmpShape.curves=tmpPath.curves;shapes.push(tmpShape);return shapes;}var holesFirst=!isClockWise(subPaths[0].getPoints());holesFirst=isCCW?!holesFirst:holesFirst;// console.log("Holes first", holesFirst); var betterShapeHoles=[];var newShapes=[];var newShapeHoles=[];var mainIdx=0;var tmpPoints;newShapes[mainIdx]=undefined;newShapeHoles[mainIdx]=[];for(var i=0,l=subPaths.length;i probably all Shapes with wrong orientation if(!newShapes[0])return toShapesNoHoles(subPaths);if(newShapes.length>1){var ambiguous=false;var toChange=[];for(var sIdx=0,sLen=newShapes.length;sIdx0){// console.log("to change: ", toChange); if(!ambiguous)newShapeHoles=betterShapeHoles;}}var tmpHoles;for(var i=0,il=newShapes.length;i0){this.source.connect(this.filters[0]);for(var i=1,l=this.filters.length;i0){this.source.disconnect(this.filters[0]);for(var i=1,l=this.filters.length;i' accumulate:function accumulate(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 var buffer=this.buffer,stride=this.valueSize,offset=accuIndex*stride+stride,currentWeight=this.cumulativeWeight;if(currentWeight===0){// accuN := incoming * weight for(var i=0;i!==stride;++i){buffer[offset+i]=buffer[i];}currentWeight=weight;}else{// accuN := accuN + incoming * weight currentWeight+=weight;var mix=weight/currentWeight;this._mixBufferRegion(buffer,offset,0,mix,stride);}this.cumulativeWeight=currentWeight;},// accumulate data in the 'incoming' region into 'add' accumulateAdditive:function accumulateAdditive(weight){var 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' to the binding when accus differ apply:function apply(accuIndex){var 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 ) var 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(var 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 saveOriginalState(){var binding=this.binding;var 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(var 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 restoreOriginalState(){var originalValueOffset=this.valueSize*3;this.binding.setValue(this.buffer,originalValueOffset);},_setAdditiveIdentityNumeric:function _setAdditiveIdentityNumeric(){var startIndex=this._addIndex*this.valueSize;var endIndex=startIndex+this.valueSize;for(var i=startIndex;i=0.5){for(var i=0;i!==stride;++i){buffer[dstOffset+i]=buffer[srcOffset+i];}}},_slerp:function _slerp(buffer,dstOffset,srcOffset,t){Quaternion.slerpFlat(buffer,dstOffset,buffer,dstOffset,buffer,srcOffset,t);},_slerpAdditive:function _slerpAdditive(buffer,dstOffset,srcOffset,t,stride){var 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 _lerp(buffer,dstOffset,srcOffset,t,stride){var s=1-t;for(var i=0;i!==stride;++i){var j=dstOffset+i;buffer[j]=buffer[j]*s+buffer[srcOffset+i]*t;}},_lerpAdditive:function _lerpAdditive(buffer,dstOffset,srcOffset,t,stride){for(var i=0;i!==stride;++i){var 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. var _RESERVED_CHARS_RE='\\[\\]\\.:\\/';var _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. var _wordChar='[^'+_RESERVED_CHARS_RE+']';var _wordCharOrDot='[^'+_RESERVED_CHARS_RE.replace('\\.','')+']';// Parent directories, delimited by '/' or ':'. Currently unused, but must // be matched to parse the rest of the track name. var _directoryRe=/((?:WC+[\/:])*)/.source.replace('WC',_wordChar);// Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'. var _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. var _objectRe=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC',_wordChar);// Property and accessor. May not contain reserved characters. Accessor may // contain any non-bracket characters. var _propertyRe=/\.(WC+)(?:\[(.+)\])?/.source.replace('WC',_wordChar);var _trackRe=new RegExp(''+'^'+_directoryRe+_nodeRe+_objectRe+_propertyRe+'$');var _supportedObjectNames=['material','materials','bones'];function Composite(targetGroup,path,optionalParsedPath){var parsedPath=optionalParsedPath||PropertyBinding.parseTrackName(path);this._targetGroup=targetGroup;this._bindings=targetGroup.subscribe_(path,parsedPath);}Object.assign(Composite.prototype,{getValue:function getValue(array,offset){this.bind();// bind all binding var firstValidIndex=this._targetGroup.nCachedObjects_,binding=this._bindings[firstValidIndex];// and only call .getValue on the first if(binding!==undefined)binding.getValue(array,offset);},setValue:function setValue(array,offset){var bindings=this._bindings;for(var i=this._targetGroup.nCachedObjects_,n=bindings.length;i!==n;++i){bindings[i].setValue(array,offset);}},bind:function bind(){var bindings=this._bindings;for(var i=this._targetGroup.nCachedObjects_,n=bindings.length;i!==n;++i){bindings[i].bind();}},unbind:function unbind(){var bindings=this._bindings;for(var 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 create(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 sanitizeNodeName(name){return name.replace(/\s/g,'_').replace(_reservedRe,'');},parseTrackName:function parseTrackName(trackName){var matches=_trackRe.exec(trackName);if(!matches){throw new Error('PropertyBinding: Cannot parse trackName: '+trackName);}var results={// directoryName: matches[ 1 ], // (tschw) currently unused nodeName:matches[2],objectName:matches[3],objectIndex:matches[4],propertyName:matches[5],// required propertyIndex:matches[6]};var lastDot=results.nodeName&&results.nodeName.lastIndexOf('.');if(lastDot!==undefined&&lastDot!==-1){var objectName=results.nodeName.substring(lastDot+1);// Object names must be checked against a whitelist. 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 findNode(root,nodeName){if(!nodeName||nodeName===""||nodeName==="."||nodeName===-1||nodeName===root.name||nodeName===root.uuid){return root;}// search into skeleton bones. if(root.skeleton){var bone=root.skeleton.getBoneByName(nodeName);if(bone!==undefined){return bone;}}// search into node subtree. if(root.children){var searchNodeSubtree=function searchNodeSubtree(children){for(var i=0;i this._bindingsIndicesByPath={};// inside: indices in these arrays var 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 add(){var objects=this._objects,nObjects=objects.length,nCachedObjects=this.nCachedObjects_,indicesByUUID=this._indicesByUUID,paths=this._paths,parsedPaths=this._parsedPaths,bindings=this._bindings,nBindings=bindings.length,knownObject=undefined;for(var i=0,n=arguments.length;i!==n;++i){var object=arguments[i],uuid=object.uuid,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(var j=0,m=nBindings;j!==m;++j){bindings[j].push(new PropertyBinding(object,paths[j],parsedPaths[j]));}}else if(index=nCachedObjects){// move existing object into the CACHED region var 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(var j=0,m=nBindings;j!==m;++j){var bindingsForPath=bindings[j],firstActive=bindingsForPath[lastCachedIndex],binding=bindingsForPath[index];bindingsForPath[index]=firstActive;bindingsForPath[lastCachedIndex]=binding;}}}// for arguments this.nCachedObjects_=nCachedObjects;},// remove & forget uncache:function uncache(){var objects=this._objects,nObjects=objects.length,nCachedObjects=this.nCachedObjects_,indicesByUUID=this._indicesByUUID,bindings=this._bindings,nBindings=bindings.length;for(var i=0,n=arguments.length;i!==n;++i){var object=arguments[i],uuid=object.uuid,index=indicesByUUID[uuid];if(index!==undefined){delete indicesByUUID[uuid];if(index 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 play(){this._mixer._activateAction(this);return this;},stop:function stop(){this._mixer._deactivateAction(this);return this.reset();},reset:function reset(){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 isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this);},// return true when play has been called isScheduled:function isScheduled(){return this._mixer._isActiveAction(this);},startAt:function startAt(time){this._startTime=time;return this;},setLoop:function setLoop(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 setEffectiveWeight(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 getEffectiveWeight(){return this._effectiveWeight;},fadeIn:function fadeIn(duration){return this._scheduleFading(duration,0,1);},fadeOut:function fadeOut(duration){return this._scheduleFading(duration,1,0);},crossFadeFrom:function crossFadeFrom(fadeOutAction,duration,warp){fadeOutAction.fadeOut(duration);this.fadeIn(duration);if(warp){var 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 crossFadeTo(fadeInAction,duration,warp){return fadeInAction.crossFadeFrom(this,duration,warp);},stopFading:function stopFading(){var 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 setEffectiveTimeScale(timeScale){this.timeScale=timeScale;this._effectiveTimeScale=this.paused?0:timeScale;return this.stopWarping();},// return the time scale considering warping and .paused getEffectiveTimeScale:function getEffectiveTimeScale(){return this._effectiveTimeScale;},setDuration:function setDuration(duration){this.timeScale=this._clip.duration/duration;return this.stopWarping();},syncWith:function syncWith(action){this.time=action.time;this.timeScale=action.timeScale;return this.stopWarping();},halt:function halt(duration){return this.warp(this._effectiveTimeScale,0,duration);},warp:function warp(startTimeScale,endTimeScale,duration){var mixer=this._mixer,now=mixer.time,interpolant=this._timeScaleInterpolant,timeScale=this.timeScale;if(interpolant===null){interpolant=mixer._lendControlInterpolant();this._timeScaleInterpolant=interpolant;}var 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 stopWarping(){var timeScaleInterpolant=this._timeScaleInterpolant;if(timeScaleInterpolant!==null){this._timeScaleInterpolant=null;this._mixer._takeBackControlInterpolant(timeScaleInterpolant);}return this;},// Object Accessors getMixer:function getMixer(){return this._mixer;},getClip:function getClip(){return this._clip;},getRoot:function getRoot(){return this._localRoot||this._mixer._root;},// Interna _update:function _update(time,deltaTime,timeDirection,accuIndex){// called by the mixer if(!this.enabled){// call ._updateWeight() to update ._effectiveWeight this._updateWeight(time);return;}var startTime=this._startTime;if(startTime!==null){// check for scheduled start of action var 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);var clipTime=this._updateTime(deltaTime);// note: _updateTime may disable the action resulting in // an effective weight of 0 var weight=this._updateWeight(time);if(weight>0){var interpolants=this._interpolants;var propertyMixers=this._propertyBindings;switch(this.blendMode){case AdditiveAnimationBlendMode:for(var j=0,m=interpolants.length;j!==m;++j){interpolants[j].evaluate(clipTime);propertyMixers[j].accumulateAdditive(weight);}break;case NormalAnimationBlendMode:default:for(var j=0,m=interpolants.length;j!==m;++j){interpolants[j].evaluate(clipTime);propertyMixers[j].accumulate(accuIndex,weight);}}}},_updateWeight:function _updateWeight(time){var weight=0;if(this.enabled){weight=this.weight;var interpolant=this._weightInterpolant;if(interpolant!==null){var 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 _updateTimeScale(time){var timeScale=0;if(!this.paused){timeScale=this.timeScale;var interpolant=this._timeScaleInterpolant;if(interpolant!==null){var 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 _updateTime(deltaTime){var time=this.time+deltaTime;var duration=this._clip.duration;var loop=this.loop;var loopCount=this._loopCount;var 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 var loopDelta=Math.floor(time/duration);// signed time-=duration*loopDelta;loopCount+=Math.abs(loopDelta);var 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 var 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 _setEndings(atStart,atEnd,pingPong){var 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 _scheduleFading(duration,weightNow,weightThen){var mixer=this._mixer,now=mixer.time,interpolant=this._weightInterpolant;if(interpolant===null){interpolant=mixer._lendControlInterpolant();this._weightInterpolant=interpolant;}var 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 _bindAction(action,prototypeAction){var root=action._localRoot||this._root,tracks=action._clip.tracks,nTracks=tracks.length,bindings=action._propertyBindings,interpolants=action._interpolants,rootUuid=root.uuid,bindingsByRoot=this._bindingsByRootAndName,bindingsByName=bindingsByRoot[rootUuid];if(bindingsByName===undefined){bindingsByName={};bindingsByRoot[rootUuid]=bindingsByName;}for(var i=0;i!==nTracks;++i){var track=tracks[i],trackName=track.name,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;}var 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 _activateAction(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 var 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);}var bindings=action._propertyBindings;// increment reference counts / sort out state for(var i=0,n=bindings.length;i!==n;++i){var binding=bindings[i];if(binding.useCount++===0){this._lendBinding(binding);binding.saveOriginalState();}}this._lendAction(action);}},_deactivateAction:function _deactivateAction(action){if(this._isActiveAction(action)){var bindings=action._propertyBindings;// decrement reference counts / sort out state for(var i=0,n=bindings.length;i!==n;++i){var binding=bindings[i];if(--binding.useCount===0){binding.restoreOriginalState();this._takeBackBinding(binding);}}this._takeBackAction(action);}},// Memory manager _initMemoryManager:function _initMemoryManager(){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;var 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 _isActiveAction(action){var index=action._cacheIndex;return index!==null&&index| inactive actions ] // s a // <-swap-> // a s var 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 _takeBackAction(action){// [ active actions | inactive actions ] // [ active actions |< inactive actions ] // a s // <-swap-> // s a var 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 _addInactiveBinding(binding,rootUuid,trackName){var bindingsByRoot=this._bindingsByRootAndName,bindingByName=bindingsByRoot[rootUuid],bindings=this._bindings;if(bindingByName===undefined){bindingByName={};bindingsByRoot[rootUuid]=bindingByName;}bindingByName[trackName]=binding;binding._cacheIndex=bindings.length;bindings.push(binding);},_removeInactiveBinding:function _removeInactiveBinding(binding){var 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 _lendBinding(binding){var 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 _takeBackBinding(binding){var 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 _lendControlInterpolant(){var interpolants=this._controlInterpolants,lastActiveIndex=this._nActiveControlInterpolants++,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 _takeBackControlInterpolant(interpolant){var 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 clipAction(clip,optionalRoot,blendMode){var root=optionalRoot||this._root,rootUuid=root.uuid,clipObject=typeof clip==='string'?AnimationClip.findByName(root,clip):clip,clipUuid=clipObject!==null?clipObject.uuid:clip,actionsForClip=this._actionsByClip[clipUuid],prototypeAction=null;if(blendMode===undefined){if(clipObject!==null){blendMode=clipObject.blendMode;}else{blendMode=NormalAnimationBlendMode;}}if(actionsForClip!==undefined){var 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 var 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 existingAction(clip,optionalRoot){var 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 stopAllAction(){var actions=this._actions,nActions=this._nActiveActions;for(var i=nActions-1;i>=0;--i){actions[i].stop();}return this;},// advance the time and update apply the animation update:function update(deltaTime){deltaTime*=this.timeScale;var actions=this._actions,nActions=this._nActiveActions,time=this.time+=deltaTime,timeDirection=Math.sign(deltaTime),accuIndex=this._accuIndex^=1;// run active actions for(var i=0;i!==nActions;++i){var action=actions[i];action._update(time,deltaTime,timeDirection,accuIndex);}// update scene graph var bindings=this._bindings,nBindings=this._nActiveBindings;for(var i=0;i!==nBindings;++i){bindings[i].apply(accuIndex);}return this;},// Allows you to seek to a specific time in an animation. setTime:function setTime(timeInSeconds){this.time=0;// Zero out time attribute for AnimationMixer object; for(var i=0;ithis.max.x||point.ythis.max.y?false:true;},containsBox:function containsBox(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 getParameter(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 intersectsBox(box){// using 4 splitting planes to rule out intersections return box.max.xthis.max.x||box.max.ythis.max.y?false:true;},clampPoint:function clampPoint(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 distanceToPoint(point){var clampedPoint=_vector$7.copy(point).clamp(this.min,this.max);return clampedPoint.sub(point).length();},intersect:function intersect(box){this.min.max(box.min);this.max.min(box.max);return this;},union:function union(box){this.min.min(box.min);this.max.max(box.max);return this;},translate:function translate(offset){this.min.add(offset);this.max.add(offset);return this;},equals:function equals(box){return box.min.equals(this.min)&&box.max.equals(this.max);}});/** * @author bhouston / http://clara.io */var _startP=new Vector3();var _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 set(start,end){this.start.copy(start);this.end.copy(end);return this;},clone:function clone(){return new this.constructor().copy(this);},copy:function copy(line){this.start.copy(line.start);this.end.copy(line.end);return this;},getCenter:function getCenter(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 delta(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 distanceSq(){return this.start.distanceToSquared(this.end);},distance:function distance(){return this.start.distanceTo(this.end);},at:function at(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 closestPointToPointParameter(point,clampToLine){_startP.subVectors(point,this.start);_startEnd.subVectors(this.end,this.start);var startEnd2=_startEnd.dot(_startEnd);var startEnd_startP=_startEnd.dot(_startP);var t=startEnd_startP/startEnd2;if(clampToLine){t=MathUtils.clamp(t,0,1);}return t;},closestPointToPoint:function closestPointToPoint(point,clampToLine,target){var 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 applyMatrix4(matrix){this.start.applyMatrix4(matrix);this.end.applyMatrix4(matrix);return this;},equals:function equals(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 */var _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;var geometry=new BufferGeometry();var 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(var i=0,j=1,l=32;i0.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();var 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;var vertices=[0,0,0,size,0,0,0,0,0,0,size,0,0,0,0,0,0,size];var colors=[1,0,0,1,0.6,0,0,1,0,0.6,1,0,0,0,1,0,0.6,1];var geometry=new BufferGeometry();geometry.setAttribute('position',new Float32BufferAttribute(vertices,3));geometry.setAttribute('color',new Float32BufferAttribute(colors,3));var 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. */var LOD_MIN=4;var LOD_MAX=8;var 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. var EXTRA_LOD_SIGMA=[0.125,0.215,0.35,0.446,0.526,0.582];var 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. var MAX_SAMPLES=20;var ENCODINGS=(_ENCODINGS={},_defineProperty(_ENCODINGS,LinearEncoding,0),_defineProperty(_ENCODINGS,sRGBEncoding,1),_defineProperty(_ENCODINGS,RGBEEncoding,2),_defineProperty(_ENCODINGS,RGBM7Encoding,3),_defineProperty(_ENCODINGS,RGBM16Encoding,4),_defineProperty(_ENCODINGS,RGBDEncoding,5),_defineProperty(_ENCODINGS,GammaEncoding,6),_ENCODINGS);var _flatCamera=new OrthographicCamera();var _createPlanes2=_createPlanes(),_lodPlanes=_createPlanes2._lodPlanes,_sizeLods=_createPlanes2._sizeLods,_sigmas=_createPlanes2._sigmas;var _oldTarget=null;// Golden Ratio var PHI=(1+Math.sqrt(5))/2;var 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. var _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 fromScene(scene){var sigma=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var near=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0.1;var far=arguments.length>3&&arguments[3]!==undefined?arguments[3]:100;_oldTarget=this._renderer.getRenderTarget();var 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 fromEquirectangular(equirectangular){equirectangular.magFilter=NearestFilter;equirectangular.minFilter=NearestFilter;equirectangular.generateMipmaps=false;return this.fromCubemap(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 fromCubemap(cubemap){_oldTarget=this._renderer.getRenderTarget();var cubeUVRenderTarget=this._allocateTargets(cubemap);this._textureToCubeUV(cubemap,cubeUVRenderTarget);this._applyPMREM(cubeUVRenderTarget);this._cleanup(cubeUVRenderTarget);return cubeUVRenderTarget;},/** * 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 compileCubemapShader(){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 compileEquirectangularShader(){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 dispose(){this._blurMaterial.dispose();if(this._cubemapShader!==null)this._cubemapShader.dispose();if(this._equirectShader!==null)this._equirectShader.dispose();for(var i=0;i<_lodPlanes.length;i++){_lodPlanes[i].dispose();}},// private interface _cleanup:function _cleanup(outputTarget){this._pingPongRenderTarget.dispose();this._renderer.setRenderTarget(_oldTarget);outputTarget.scissorTest=false;// reset viewport and scissor outputTarget.setSize(outputTarget.width,outputTarget.height);},_allocateTargets:function _allocateTargets(equirectangular){var params={magFilter:NearestFilter,minFilter:NearestFilter,generateMipmaps:false,type:UnsignedByteType,format:RGBEFormat,encoding:_isLDR(equirectangular)?equirectangular.encoding:RGBEEncoding,depthBuffer:false,stencilBuffer:false};var cubeUVRenderTarget=_createRenderTarget(params);cubeUVRenderTarget.depthBuffer=equirectangular?false:true;this._pingPongRenderTarget=_createRenderTarget(params);return cubeUVRenderTarget;},_compileMaterial:function _compileMaterial(material){var tmpMesh=new Mesh(_lodPlanes[0],material);this._renderer.compile(tmpMesh,_flatCamera);},_sceneToCubeUV:function _sceneToCubeUV(scene,near,far,cubeUVRenderTarget){var fov=90;var aspect=1;var cubeCamera=new PerspectiveCamera(fov,aspect,near,far);var upSign=[1,-1,1,1,1,1];var forwardSign=[1,1,1,-1,-1,-1];var renderer=this._renderer;var outputEncoding=renderer.outputEncoding;var toneMapping=renderer.toneMapping;var toneMappingExposure=renderer.toneMappingExposure;var clearColor=renderer.getClearColor();var clearAlpha=renderer.getClearAlpha();renderer.toneMapping=LinearToneMapping;renderer.toneMappingExposure=1.0;renderer.outputEncoding=LinearEncoding;var background=scene.background;if(background&&background.isColor){background.convertSRGBToLinear();// Convert linear to RGBE var maxComponent=Math.max(background.r,background.g,background.b);var fExp=Math.min(Math.max(Math.ceil(Math.log2(maxComponent)),-128.0),127.0);background=background.multiplyScalar(Math.pow(2.0,-fExp));var alpha=(fExp+128.0)/255.0;renderer.setClearColor(background,alpha);scene.background=null;}for(var i=0;i<6;i++){var 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.toneMappingExposure=toneMappingExposure;renderer.outputEncoding=outputEncoding;renderer.setClearColor(clearColor,clearAlpha);},_textureToCubeUV:function _textureToCubeUV(texture,cubeUVRenderTarget){var renderer=this._renderer;if(texture.isCubeTexture){if(this._cubemapShader==null){this._cubemapShader=_getCubemapShader();}}else{if(this._equirectShader==null){this._equirectShader=_getEquirectShader();}}var material=texture.isCubeTexture?this._cubemapShader:this._equirectShader;var mesh=new Mesh(_lodPlanes[0],material);var 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 _applyPMREM(cubeUVRenderTarget){var renderer=this._renderer;var autoClear=renderer.autoClear;renderer.autoClear=false;for(var i=1;iMAX_SAMPLES){console.warn("sigmaRadians, ".concat(sigmaRadians,", is too large and will clip, as it requested ").concat(samples," samples when the maximum is set to ").concat(MAX_SAMPLES));}var weights=[];var sum=0;for(var i=0;iLOD_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(){var _lodPlanes=[];var _sizeLods=[];var _sigmas=[];var lod=LOD_MAX;for(var i=0;iLOD_MAX-LOD_MIN){sigma=EXTRA_LOD_SIGMA[i-LOD_MAX+LOD_MIN-1];}else if(i==0){sigma=0;}_sigmas.push(sigma);var texelSize=1.0/(sizeLod-1);var min=-texelSize/2;var max=1+texelSize/2;var uv1=[min,min,max,min,max,max,min,min,max,max,min,max];var cubeFaces=6;var vertices=6;var positionSize=3;var uvSize=2;var faceIndexSize=1;var position=new Float32Array(positionSize*vertices*cubeFaces);var uv=new Float32Array(uvSize*vertices*cubeFaces);var faceIndex=new Float32Array(faceIndexSize*vertices*cubeFaces);for(var face=0;face2?0:-1;var 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);var fill=[face,face,face,face,face,face];faceIndex.set(fill,faceIndexSize*vertices*face);}var 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:_lodPlanes,_sizeLods:_sizeLods,_sigmas:_sigmas};}function _createRenderTarget(params){var 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){var weights=new Float32Array(maxSamples);var poleAxis=new Vector3(0,1,0);var shaderMaterial=new RawShaderMaterial({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:"\nprecision mediump float;\nprecision mediump int;\nvarying vec3 vOutputDirection;\nuniform sampler2D envMap;\nuniform int samples;\nuniform float weights[n];\nuniform bool latitudinal;\nuniform float dTheta;\nuniform float mipInt;\nuniform vec3 poleAxis;\n\n".concat(_getEncodings(),"\n\n#define ENVMAP_TYPE_CUBE_UV\n#include \n\nvec3 getSample(float theta, vec3 axis) {\n\tfloat cosTheta = cos(theta);\n\t// Rodrigues' axis-angle rotation\n\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t+ cross(axis, vOutputDirection) * sin(theta)\n\t\t+ axis * dot(axis, vOutputDirection) * (1.0 - cosTheta);\n\treturn bilinearCubeUV(envMap, sampleDirection, mipInt);\n}\n\nvoid main() {\n\tvec3 axis = latitudinal ? poleAxis : cross(poleAxis, vOutputDirection);\n\tif (all(equal(axis, vec3(0.0))))\n\t\taxis = vec3(vOutputDirection.z, 0.0, - vOutputDirection.x);\n\taxis = normalize(axis);\n\tgl_FragColor = vec4(0.0);\n\tgl_FragColor.rgb += weights[0] * getSample(0.0, axis);\n\tfor (int i = 1; i < n; i++) {\n\t\tif (i >= samples)\n\t\t\tbreak;\n\t\tfloat theta = dTheta * float(i);\n\t\tgl_FragColor.rgb += weights[i] * getSample(-1.0 * theta, axis);\n\t\tgl_FragColor.rgb += weights[i] * getSample(theta, axis);\n\t}\n\tgl_FragColor = linearToOutputTexel(gl_FragColor);\n}\n\t\t"),blending:NoBlending,depthTest:false,depthWrite:false});shaderMaterial.type='SphericalGaussianBlur';return shaderMaterial;}function _getEquirectShader(){var texelSize=new Vector2(1,1);var shaderMaterial=new RawShaderMaterial({uniforms:{'envMap':{value:null},'texelSize':{value:texelSize},'inputEncoding':{value:ENCODINGS[LinearEncoding]},'outputEncoding':{value:ENCODINGS[LinearEncoding]}},vertexShader:_getCommonVertexShader(),fragmentShader:"\nprecision mediump float;\nprecision mediump int;\nvarying vec3 vOutputDirection;\nuniform sampler2D envMap;\nuniform vec2 texelSize;\n\n".concat(_getEncodings(),"\n\n#include \n\nvoid main() {\n\tgl_FragColor = vec4(0.0);\n\tvec3 outputDirection = normalize(vOutputDirection);\n\tvec2 uv = equirectUv( outputDirection );\n\tvec2 f = fract(uv / texelSize - 0.5);\n\tuv -= f * texelSize;\n\tvec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n\tuv.x += texelSize.x;\n\tvec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n\tuv.y += texelSize.y;\n\tvec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n\tuv.x -= texelSize.x;\n\tvec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n\tvec3 tm = mix(tl, tr, f.x);\n\tvec3 bm = mix(bl, br, f.x);\n\tgl_FragColor.rgb = mix(tm, bm, f.y);\n\tgl_FragColor = linearToOutputTexel(gl_FragColor);\n}\n\t\t"),blending:NoBlending,depthTest:false,depthWrite:false});shaderMaterial.type='EquirectangularToCubeUV';return shaderMaterial;}function _getCubemapShader(){var shaderMaterial=new RawShaderMaterial({uniforms:{'envMap':{value:null},'inputEncoding':{value:ENCODINGS[LinearEncoding]},'outputEncoding':{value:ENCODINGS[LinearEncoding]}},vertexShader:_getCommonVertexShader(),fragmentShader:"\nprecision mediump float;\nprecision mediump int;\nvarying vec3 vOutputDirection;\nuniform samplerCube envMap;\n\n".concat(_getEncodings(),"\n\nvoid main() {\n\tgl_FragColor = vec4(0.0);\n\tgl_FragColor.rgb = envMapTexelToLinear(textureCube(envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ))).rgb;\n\tgl_FragColor = linearToOutputTexel(gl_FragColor);\n}\n\t\t"),blending:NoBlending,depthTest:false,depthWrite:false});shaderMaterial.type='CubemapToCubeUV';return shaderMaterial;}function _getCommonVertexShader(){return"\nprecision mediump float;\nprecision mediump int;\nattribute vec3 position;\nattribute vec2 uv;\nattribute float faceIndex;\nvarying vec3 vOutputDirection;\n\n// RH coordinate system; PMREM face-indexing convention\nvec3 getDirection(vec2 uv, float face) {\n\tuv = 2.0 * uv - 1.0;\n\tvec3 direction = vec3(uv, 1.0);\n\tif (face == 0.0) {\n\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\t} else if (face == 1.0) {\n\t\tdirection = direction.xzy;\n\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\t} else if (face == 2.0) {\n\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\t} else if (face == 3.0) {\n\t\tdirection = direction.zyx;\n\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\t} else if (face == 4.0) {\n\t\tdirection = direction.xzy;\n\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\t} else if (face == 5.0) {\n\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\t}\n\treturn direction;\n}\n\nvoid main() {\n\tvOutputDirection = getDirection(uv, faceIndex);\n\tgl_Position = vec4( position, 1.0 );\n}\n\t";}function _getEncodings(){return"\nuniform int inputEncoding;\nuniform int outputEncoding;\n\n#include \n\nvec4 inputTexelToLinear(vec4 value){\n\tif(inputEncoding == 0){\n\t\treturn value;\n\t}else if(inputEncoding == 1){\n\t\treturn sRGBToLinear(value);\n\t}else if(inputEncoding == 2){\n\t\treturn RGBEToLinear(value);\n\t}else if(inputEncoding == 3){\n\t\treturn RGBMToLinear(value, 7.0);\n\t}else if(inputEncoding == 4){\n\t\treturn RGBMToLinear(value, 16.0);\n\t}else if(inputEncoding == 5){\n\t\treturn RGBDToLinear(value, 256.0);\n\t}else{\n\t\treturn GammaToLinear(value, 2.2);\n\t}\n}\n\nvec4 linearToOutputTexel(vec4 value){\n\tif(outputEncoding == 0){\n\t\treturn value;\n\t}else if(outputEncoding == 1){\n\t\treturn LinearTosRGB(value);\n\t}else if(outputEncoding == 2){\n\t\treturn LinearToRGBE(value);\n\t}else if(outputEncoding == 3){\n\t\treturn LinearToRGBM(value, 7.0);\n\t}else if(outputEncoding == 4){\n\t\treturn LinearToRGBM(value, 16.0);\n\t}else if(outputEncoding == 5){\n\t\treturn LinearToRGBD(value, 256.0);\n\t}else{\n\t\treturn LinearToGamma(value, 2.2);\n\t}\n}\n\nvec4 envMapTexelToLinear(vec4 color) {\n\treturn inputTexelToLinear(color);\n}\n\t";}// 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 createPointsGeometry(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) var pts=this.getPoints(divisions);return this.createGeometry(pts);},createSpacedPointsGeometry:function createSpacedPointsGeometry(divisions){console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');// generate geometry from equidistant sampling along the path var pts=this.getSpacedPoints(divisions);return this.createGeometry(pts);},createGeometry:function createGeometry(points){console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');var geometry=new Geometry();for(var i=0,l=points.length;ib._taskLoad?-1:1;});}var worker=_this13.workerPool[_this13.workerPool.length-1];worker._taskCosts[taskID]=taskCost;worker._taskLoad+=taskCost;return worker;});},_releaseTask:function _releaseTask(worker,taskID){worker._taskLoad-=worker._taskCosts[taskID];delete worker._callbacks[taskID];delete worker._taskCosts[taskID];},debug:function debug(){console.log('Task load: ',this.workerPool.map(function(worker){return worker._taskLoad;}));},dispose:function dispose(){for(var i=0;i=2.0 are supported.'));return;}if(json.extensionsUsed){for(var i=0;i=0){console.warn('THREE.GLTFLoader: Unknown extension "'+extensionName+'".');}}}}var parser=new GLTFParser(json,extensions,{path:path||this.resourcePath||'',crossOrigin:this.crossOrigin,manager:this.manager});parser.fileLoader.setRequestHeader(this.requestHeader);parser.parse(onLoad,onError);}});/* GLTFREGISTRY */function GLTFRegistry(){var objects={};return{get:function get(key){return objects[key];},add:function add(key,object){objects[key]=object;},remove:function remove(key){delete objects[key];},removeAll:function removeAll(){objects={};}};}/*********************************/ /********** EXTENSIONS ***********/ /*********************************/var EXTENSIONS={KHR_BINARY_GLTF:'KHR_binary_glTF',KHR_DRACO_MESH_COMPRESSION:'KHR_draco_mesh_compression',KHR_LIGHTS_PUNCTUAL:'KHR_lights_punctual',KHR_MATERIALS_CLEARCOAT:'KHR_materials_clearcoat',KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:'KHR_materials_pbrSpecularGlossiness',KHR_MATERIALS_UNLIT:'KHR_materials_unlit',KHR_TEXTURE_TRANSFORM:'KHR_texture_transform',KHR_MESH_QUANTIZATION:'KHR_mesh_quantization',MSFT_TEXTURE_DDS:'MSFT_texture_dds'};/** * DDS Texture Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds * */function GLTFTextureDDSExtension(ddsLoader){if(!ddsLoader){throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader');}this.name=EXTENSIONS.MSFT_TEXTURE_DDS;this.ddsLoader=ddsLoader;}/** * Punctual Lights Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual */function GLTFLightsExtension(json){this.name=EXTENSIONS.KHR_LIGHTS_PUNCTUAL;var extension=json.extensions&&json.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL]||{};this.lightDefs=extension.lights||[];}GLTFLightsExtension.prototype.loadLight=function(lightIndex){var lightDef=this.lightDefs[lightIndex];var lightNode;var color=new Color(0xffffff);if(lightDef.color!==undefined)color.fromArray(lightDef.color);var range=lightDef.range!==undefined?lightDef.range:0;switch(lightDef.type){case'directional':lightNode=new DirectionalLight(color);lightNode.target.position.set(0,0,-1);lightNode.add(lightNode.target);break;case'point':lightNode=new PointLight(color);lightNode.distance=range;break;case'spot':lightNode=new SpotLight(color);lightNode.distance=range;// Handle spotlight properties. lightDef.spot=lightDef.spot||{};lightDef.spot.innerConeAngle=lightDef.spot.innerConeAngle!==undefined?lightDef.spot.innerConeAngle:0;lightDef.spot.outerConeAngle=lightDef.spot.outerConeAngle!==undefined?lightDef.spot.outerConeAngle:Math.PI/4.0;lightNode.angle=lightDef.spot.outerConeAngle;lightNode.penumbra=1.0-lightDef.spot.innerConeAngle/lightDef.spot.outerConeAngle;lightNode.target.position.set(0,0,-1);lightNode.add(lightNode.target);break;default:throw new Error('THREE.GLTFLoader: Unexpected light type, "'+lightDef.type+'".');}// Some lights (e.g. spot) default to a position other than the origin. Reset the position // here, because node-level parsing will only override position if explicitly specified. lightNode.position.set(0,0,0);lightNode.decay=2;if(lightDef.intensity!==undefined)lightNode.intensity=lightDef.intensity;lightNode.name=lightDef.name||'light_'+lightIndex;return Promise.resolve(lightNode);};/** * Unlit Materials Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit */function GLTFMaterialsUnlitExtension(){this.name=EXTENSIONS.KHR_MATERIALS_UNLIT;}GLTFMaterialsUnlitExtension.prototype.getMaterialType=function(){return MeshBasicMaterial;};GLTFMaterialsUnlitExtension.prototype.extendParams=function(materialParams,materialDef,parser){var pending=[];materialParams.color=new Color(1.0,1.0,1.0);materialParams.opacity=1.0;var metallicRoughness=materialDef.pbrMetallicRoughness;if(metallicRoughness){if(Array.isArray(metallicRoughness.baseColorFactor)){var array=metallicRoughness.baseColorFactor;materialParams.color.fromArray(array);materialParams.opacity=array[3];}if(metallicRoughness.baseColorTexture!==undefined){pending.push(parser.assignTexture(materialParams,'map',metallicRoughness.baseColorTexture));}}return Promise.all(pending);};/** * Clearcoat Materials Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat */function GLTFMaterialsClearcoatExtension(){this.name=EXTENSIONS.KHR_MATERIALS_CLEARCOAT;}GLTFMaterialsClearcoatExtension.prototype.getMaterialType=function(){return MeshPhysicalMaterial;};GLTFMaterialsClearcoatExtension.prototype.extendParams=function(materialParams,materialDef,parser){var pending=[];var extension=materialDef.extensions[this.name];if(extension.clearcoatFactor!==undefined){materialParams.clearcoat=extension.clearcoatFactor;}if(extension.clearcoatTexture!==undefined){pending.push(parser.assignTexture(materialParams,'clearcoatMap',extension.clearcoatTexture));}if(extension.clearcoatRoughnessFactor!==undefined){materialParams.clearcoatRoughness=extension.clearcoatRoughnessFactor;}if(extension.clearcoatRoughnessTexture!==undefined){pending.push(parser.assignTexture(materialParams,'clearcoatRoughnessMap',extension.clearcoatRoughnessTexture));}if(extension.clearcoatNormalTexture!==undefined){pending.push(parser.assignTexture(materialParams,'clearcoatNormalMap',extension.clearcoatNormalTexture));if(extension.clearcoatNormalTexture.scale!==undefined){var scale=extension.clearcoatNormalTexture.scale;materialParams.clearcoatNormalScale=new Vector2(scale,scale);}}return Promise.all(pending);};/* BINARY EXTENSION */var BINARY_EXTENSION_HEADER_MAGIC='glTF';var BINARY_EXTENSION_HEADER_LENGTH=12;var BINARY_EXTENSION_CHUNK_TYPES={JSON:0x4E4F534A,BIN:0x004E4942};function GLTFBinaryExtension(data){this.name=EXTENSIONS.KHR_BINARY_GLTF;this.content=null;this.body=null;var headerView=new DataView(data,0,BINARY_EXTENSION_HEADER_LENGTH);this.header={magic:LoaderUtils.decodeText(new Uint8Array(data.slice(0,4))),version:headerView.getUint32(4,true),length:headerView.getUint32(8,true)};if(this.header.magic!==BINARY_EXTENSION_HEADER_MAGIC){throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.');}else if(this.header.version<2.0){throw new Error('THREE.GLTFLoader: Legacy binary file detected.');}var chunkView=new DataView(data,BINARY_EXTENSION_HEADER_LENGTH);var chunkIndex=0;while(chunkIndex',specularMapParsFragmentChunk);shader.fragmentShader=shader.fragmentShader.replace('#include ',glossinessMapParsFragmentChunk);shader.fragmentShader=shader.fragmentShader.replace('#include ',specularMapFragmentChunk);shader.fragmentShader=shader.fragmentShader.replace('#include ',glossinessMapFragmentChunk);shader.fragmentShader=shader.fragmentShader.replace('#include ',lightPhysicalFragmentChunk);};/*eslint-disable*/Object.defineProperties(this,{specular:{get:function get(){return uniforms.specular.value;},set:function set(v){uniforms.specular.value=v;}},specularMap:{get:function get(){return uniforms.specularMap.value;},set:function set(v){uniforms.specularMap.value=v;}},glossiness:{get:function get(){return uniforms.glossiness.value;},set:function set(v){uniforms.glossiness.value=v;}},glossinessMap:{get:function get(){return uniforms.glossinessMap.value;},set:function set(v){uniforms.glossinessMap.value=v;//how about something like this - @pailhead if(v){this.defines.USE_GLOSSINESSMAP='';// set USE_ROUGHNESSMAP to enable vUv this.defines.USE_ROUGHNESSMAP='';}else{delete this.defines.USE_ROUGHNESSMAP;delete this.defines.USE_GLOSSINESSMAP;}}}});/*eslint-enable*/delete this.metalness;delete this.roughness;delete this.metalnessMap;delete this.roughnessMap;this.setValues(params);}GLTFMeshStandardSGMaterial.prototype=Object.create(MeshStandardMaterial.prototype);GLTFMeshStandardSGMaterial.prototype.constructor=GLTFMeshStandardSGMaterial;GLTFMeshStandardSGMaterial.prototype.copy=function(source){MeshStandardMaterial.prototype.copy.call(this,source);this.specularMap=source.specularMap;this.specular.copy(source.specular);this.glossinessMap=source.glossinessMap;this.glossiness=source.glossiness;delete this.metalness;delete this.roughness;delete this.metalnessMap;delete this.roughnessMap;return this;};function GLTFMaterialsPbrSpecularGlossinessExtension(){return{name:EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,specularGlossinessParams:['color','map','lightMap','lightMapIntensity','aoMap','aoMapIntensity','emissive','emissiveIntensity','emissiveMap','bumpMap','bumpScale','normalMap','normalMapType','displacementMap','displacementScale','displacementBias','specularMap','specular','glossinessMap','glossiness','alphaMap','envMap','envMapIntensity','refractionRatio'],getMaterialType:function getMaterialType(){return GLTFMeshStandardSGMaterial;},extendParams:function extendParams(materialParams,materialDef,parser){var pbrSpecularGlossiness=materialDef.extensions[this.name];materialParams.color=new Color(1.0,1.0,1.0);materialParams.opacity=1.0;var pending=[];if(Array.isArray(pbrSpecularGlossiness.diffuseFactor)){var array=pbrSpecularGlossiness.diffuseFactor;materialParams.color.fromArray(array);materialParams.opacity=array[3];}if(pbrSpecularGlossiness.diffuseTexture!==undefined){pending.push(parser.assignTexture(materialParams,'map',pbrSpecularGlossiness.diffuseTexture));}materialParams.emissive=new Color(0.0,0.0,0.0);materialParams.glossiness=pbrSpecularGlossiness.glossinessFactor!==undefined?pbrSpecularGlossiness.glossinessFactor:1.0;materialParams.specular=new Color(1.0,1.0,1.0);if(Array.isArray(pbrSpecularGlossiness.specularFactor)){materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor);}if(pbrSpecularGlossiness.specularGlossinessTexture!==undefined){var specGlossMapDef=pbrSpecularGlossiness.specularGlossinessTexture;pending.push(parser.assignTexture(materialParams,'glossinessMap',specGlossMapDef));pending.push(parser.assignTexture(materialParams,'specularMap',specGlossMapDef));}return Promise.all(pending);},createMaterial:function createMaterial(materialParams){var material=new GLTFMeshStandardSGMaterial(materialParams);material.fog=true;material.color=materialParams.color;material.map=materialParams.map===undefined?null:materialParams.map;material.lightMap=null;material.lightMapIntensity=1.0;material.aoMap=materialParams.aoMap===undefined?null:materialParams.aoMap;material.aoMapIntensity=1.0;material.emissive=materialParams.emissive;material.emissiveIntensity=1.0;material.emissiveMap=materialParams.emissiveMap===undefined?null:materialParams.emissiveMap;material.bumpMap=materialParams.bumpMap===undefined?null:materialParams.bumpMap;material.bumpScale=1;material.normalMap=materialParams.normalMap===undefined?null:materialParams.normalMap;material.normalMapType=TangentSpaceNormalMap;if(materialParams.normalScale)material.normalScale=materialParams.normalScale;material.displacementMap=null;material.displacementScale=1;material.displacementBias=0;material.specularMap=materialParams.specularMap===undefined?null:materialParams.specularMap;material.specular=materialParams.specular;material.glossinessMap=materialParams.glossinessMap===undefined?null:materialParams.glossinessMap;material.glossiness=materialParams.glossiness;material.alphaMap=null;material.envMap=materialParams.envMap===undefined?null:materialParams.envMap;material.envMapIntensity=1.0;material.refractionRatio=0.98;return material;}};}/** * Mesh Quantization Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization */function GLTFMeshQuantizationExtension(){this.name=EXTENSIONS.KHR_MESH_QUANTIZATION;}/*********************************/ /********** INTERPOLATION ********/ /*********************************/ // Spline Interpolation // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation function GLTFCubicSplineInterpolant(parameterPositions,sampleValues,sampleSize,resultBuffer){Interpolant.call(this,parameterPositions,sampleValues,sampleSize,resultBuffer);}GLTFCubicSplineInterpolant.prototype=Object.create(Interpolant.prototype);GLTFCubicSplineInterpolant.prototype.constructor=GLTFCubicSplineInterpolant;GLTFCubicSplineInterpolant.prototype.copySampleValue_=function(index){// Copies a sample value to the result buffer. See description of glTF // CUBICSPLINE values layout in interpolate_() function below. var result=this.resultBuffer,values=this.sampleValues,valueSize=this.valueSize,offset=index*valueSize*3+valueSize;for(var i=0;i!==valueSize;i++){result[i]=values[offset+i];}return result;};GLTFCubicSplineInterpolant.prototype.beforeStart_=GLTFCubicSplineInterpolant.prototype.copySampleValue_;GLTFCubicSplineInterpolant.prototype.afterEnd_=GLTFCubicSplineInterpolant.prototype.copySampleValue_;GLTFCubicSplineInterpolant.prototype.interpolate_=function(i1,t0,t,t1){var result=this.resultBuffer;var values=this.sampleValues;var stride=this.valueSize;var stride2=stride*2;var stride3=stride*3;var td=t1-t0;var p=(t-t0)/td;var pp=p*p;var ppp=pp*p;var offset1=i1*stride3;var offset0=offset1-stride3;var s2=-2*ppp+3*pp;var s3=ppp-pp;var s0=1-s2;var s1=s3-pp+p;// Layout of keyframe output values for CUBICSPLINE animations: // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ] for(var i=0;i!==stride;i++){var p0=values[offset0+i+stride];// splineVertex_k var m0=values[offset0+i+stride2]*td;// outTangent_k * (t_k+1 - t_k) var p1=values[offset1+i+stride];// splineVertex_k+1 var m1=values[offset1+i]*td;// inTangent_k+1 * (t_k+1 - t_k) result[i]=s0*p0+s1*m0+s2*p1+s3*m1;}return result;};/*********************************/ /********** INTERNALS ************/ /*********************************/ /* CONSTANTS */var WEBGL_CONSTANTS={FLOAT:5126,//FLOAT_MAT2: 35674, FLOAT_MAT3:35675,FLOAT_MAT4:35676,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,LINEAR:9729,REPEAT:10497,SAMPLER_2D:35678,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123};var WEBGL_COMPONENT_TYPES={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array};var WEBGL_FILTERS={9728:NearestFilter,9729:LinearFilter,9984:NearestMipmapNearestFilter,9985:LinearMipmapNearestFilter,9986:NearestMipmapLinearFilter,9987:LinearMipmapLinearFilter};var WEBGL_WRAPPINGS={33071:ClampToEdgeWrapping,33648:MirroredRepeatWrapping,10497:RepeatWrapping};var WEBGL_TYPE_SIZES={'SCALAR':1,'VEC2':2,'VEC3':3,'VEC4':4,'MAT2':4,'MAT3':9,'MAT4':16};var ATTRIBUTES={POSITION:'position',NORMAL:'normal',TANGENT:'tangent',TEXCOORD_0:'uv',TEXCOORD_1:'uv2',COLOR_0:'color',WEIGHTS_0:'skinWeight',JOINTS_0:'skinIndex'};var PATH_PROPERTIES={scale:'scale',translation:'position',rotation:'quaternion',weights:'morphTargetInfluences'};var INTERPOLATION={CUBICSPLINE:undefined,// We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each // keyframe track will be initialized with a default interpolation type, then modified. LINEAR:InterpolateLinear,STEP:InterpolateDiscrete};var ALPHA_MODES={OPAQUE:'OPAQUE',MASK:'MASK',BLEND:'BLEND'};var MIME_TYPE_FORMATS={'image/png':RGBAFormat,'image/jpeg':RGBFormat};/* UTILITY FUNCTIONS */function resolveURL(url,path){// Invalid URL if(typeof url!=='string'||url==='')return'';// Host Relative URL if(/^https?:\/\//i.test(path)&&/^\//.test(url)){path=path.replace(/(^https?:\/\/[^\/]+).*/i,'$1');}// Absolute URL http://,https://,// if(/^(https?:)?\/\//i.test(url))return url;// Data URI if(/^data:.*,.*$/i.test(url))return url;// Blob URL if(/^blob:.*$/i.test(url))return url;// Relative URL return path+url;}/** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material */function createDefaultMaterial(cache){if(cache['DefaultMaterial']===undefined){cache['DefaultMaterial']=new MeshStandardMaterial({color:0xFFFFFF,emissive:0x000000,metalness:1,roughness:1,transparent:false,depthTest:true,side:FrontSide});}return cache['DefaultMaterial'];}function addUnknownExtensionsToUserData(knownExtensions,object,objectDef){// Add unknown glTF extensions to an object's userData. for(var name in objectDef.extensions){if(knownExtensions[name]===undefined){object.userData.gltfExtensions=object.userData.gltfExtensions||{};object.userData.gltfExtensions[name]=objectDef.extensions[name];}}}/** * @param {Object3D|Material|BufferGeometry} object * @param {GLTF.definition} gltfDef */function assignExtrasToUserData(object,gltfDef){if(gltfDef.extras!==undefined){if(_typeof(gltfDef.extras)==='object'){Object.assign(object.userData,gltfDef.extras);}else{console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, '+gltfDef.extras);}}}/** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets * * @param {BufferGeometry} geometry * @param {Array} targets * @param {GLTFParser} parser * @return {Promise} */function addMorphTargets(geometry,targets,parser){var hasMorphPosition=false;var hasMorphNormal=false;for(var i=0,il=targets.length;i} */GLTFParser.prototype.getDependency=function(type,index){var cacheKey=type+':'+index;var dependency=this.cache.get(cacheKey);if(!dependency){switch(type){case'scene':dependency=this.loadScene(index);break;case'node':dependency=this.loadNode(index);break;case'mesh':dependency=this.loadMesh(index);break;case'accessor':dependency=this.loadAccessor(index);break;case'bufferView':dependency=this.loadBufferView(index);break;case'buffer':dependency=this.loadBuffer(index);break;case'material':dependency=this.loadMaterial(index);break;case'texture':dependency=this.loadTexture(index);break;case'skin':dependency=this.loadSkin(index);break;case'animation':dependency=this.loadAnimation(index);break;case'camera':dependency=this.loadCamera(index);break;case'light':dependency=this.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].loadLight(index);break;default:throw new Error('Unknown type: '+type);}this.cache.add(cacheKey,dependency);}return dependency;};/** * Requests all dependencies of the specified type asynchronously, with caching. * @param {string} type * @return {Promise>} */GLTFParser.prototype.getDependencies=function(type){var dependencies=this.cache.get(type);if(!dependencies){var parser=this;var defs=this.json[type+(type==='mesh'?'es':'s')]||[];dependencies=Promise.all(defs.map(function(def,index){return parser.getDependency(type,index);}));this.cache.add(type,dependencies);}return dependencies;};/** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views * @param {number} bufferIndex * @return {Promise} */GLTFParser.prototype.loadBuffer=function(bufferIndex){var bufferDef=this.json.buffers[bufferIndex];var loader=this.fileLoader;if(bufferDef.type&&bufferDef.type!=='arraybuffer'){throw new Error('THREE.GLTFLoader: '+bufferDef.type+' buffer type is not supported.');}// If present, GLB container is required to be the first buffer. if(bufferDef.uri===undefined&&bufferIndex===0){return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body);}var options=this.options;return new Promise(function(resolve,reject){loader.load(resolveURL(bufferDef.uri,options.path),resolve,undefined,function(){reject(new Error('THREE.GLTFLoader: Failed to load buffer "'+bufferDef.uri+'".'));});});};/** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views * @param {number} bufferViewIndex * @return {Promise} */GLTFParser.prototype.loadBufferView=function(bufferViewIndex){var bufferViewDef=this.json.bufferViews[bufferViewIndex];return this.getDependency('buffer',bufferViewDef.buffer).then(function(buffer){var byteLength=bufferViewDef.byteLength||0;var byteOffset=bufferViewDef.byteOffset||0;return buffer.slice(byteOffset,byteOffset+byteLength);});};/** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors * @param {number} accessorIndex * @return {Promise} */GLTFParser.prototype.loadAccessor=function(accessorIndex){var parser=this;var json=this.json;var accessorDef=this.json.accessors[accessorIndex];if(accessorDef.bufferView===undefined&&accessorDef.sparse===undefined){// Ignore empty accessors, which may be used to declare runtime // information about attributes coming from another source (e.g. Draco // compression extension). return Promise.resolve(null);}var pendingBufferViews=[];if(accessorDef.bufferView!==undefined){pendingBufferViews.push(this.getDependency('bufferView',accessorDef.bufferView));}else{pendingBufferViews.push(null);}if(accessorDef.sparse!==undefined){pendingBufferViews.push(this.getDependency('bufferView',accessorDef.sparse.indices.bufferView));pendingBufferViews.push(this.getDependency('bufferView',accessorDef.sparse.values.bufferView));}return Promise.all(pendingBufferViews).then(function(bufferViews){var bufferView=bufferViews[0];var itemSize=WEBGL_TYPE_SIZES[accessorDef.type];var TypedArray=WEBGL_COMPONENT_TYPES[accessorDef.componentType];// For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12. var elementBytes=TypedArray.BYTES_PER_ELEMENT;var itemBytes=elementBytes*itemSize;var byteOffset=accessorDef.byteOffset||0;var byteStride=accessorDef.bufferView!==undefined?json.bufferViews[accessorDef.bufferView].byteStride:undefined;var normalized=accessorDef.normalized===true;var array,bufferAttribute;// The buffer is not interleaved if the stride is the item size in bytes. if(byteStride&&byteStride!==itemBytes){// Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer // This makes sure that IBA.count reflects accessor.count properly var ibSlice=Math.floor(byteOffset/byteStride);var ibCacheKey='InterleavedBuffer:'+accessorDef.bufferView+':'+accessorDef.componentType+':'+ibSlice+':'+accessorDef.count;var ib=parser.cache.get(ibCacheKey);if(!ib){array=new TypedArray(bufferView,ibSlice*byteStride,accessorDef.count*byteStride/elementBytes);// Integer parameters to IB/IBA are in array elements, not bytes. ib=new InterleavedBuffer(array,byteStride/elementBytes);parser.cache.add(ibCacheKey,ib);}bufferAttribute=new InterleavedBufferAttribute(ib,itemSize,byteOffset%byteStride/elementBytes,normalized);}else{if(bufferView===null){array=new TypedArray(accessorDef.count*itemSize);}else{array=new TypedArray(bufferView,byteOffset,accessorDef.count*itemSize);}bufferAttribute=new BufferAttribute(array,itemSize,normalized);}// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors if(accessorDef.sparse!==undefined){var itemSizeIndices=WEBGL_TYPE_SIZES.SCALAR;var TypedArrayIndices=WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];var byteOffsetIndices=accessorDef.sparse.indices.byteOffset||0;var byteOffsetValues=accessorDef.sparse.values.byteOffset||0;var sparseIndices=new TypedArrayIndices(bufferViews[1],byteOffsetIndices,accessorDef.sparse.count*itemSizeIndices);var sparseValues=new TypedArray(bufferViews[2],byteOffsetValues,accessorDef.sparse.count*itemSize);if(bufferView!==null){// Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes. bufferAttribute=new BufferAttribute(bufferAttribute.array.slice(),bufferAttribute.itemSize,bufferAttribute.normalized);}for(var i=0,il=sparseIndices.length;i=2)bufferAttribute.setY(index,sparseValues[i*itemSize+1]);if(itemSize>=3)bufferAttribute.setZ(index,sparseValues[i*itemSize+2]);if(itemSize>=4)bufferAttribute.setW(index,sparseValues[i*itemSize+3]);if(itemSize>=5)throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.');}}return bufferAttribute;});};/** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures * @param {number} textureIndex * @return {Promise} */GLTFParser.prototype.loadTexture=function(textureIndex){var parser=this;var json=this.json;var options=this.options;var textureLoader=this.textureLoader;var URL=self.URL||self.webkitURL;var textureDef=json.textures[textureIndex];var textureExtensions=textureDef.extensions||{};var source;if(textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]){source=json.images[textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS].source];}else{source=json.images[textureDef.source];}var sourceURI=source.uri;var isObjectURL=false;if(source.bufferView!==undefined){// Load binary image data from bufferView, if provided. sourceURI=parser.getDependency('bufferView',source.bufferView).then(function(bufferView){isObjectURL=true;var blob=new Blob([bufferView],{type:source.mimeType});sourceURI=URL.createObjectURL(blob);return sourceURI;});}return Promise.resolve(sourceURI).then(function(sourceURI){// Load Texture resource. var loader=options.manager.getHandler(sourceURI);if(!loader){loader=textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]?parser.extensions[EXTENSIONS.MSFT_TEXTURE_DDS].ddsLoader:textureLoader;}return new Promise(function(resolve,reject){loader.load(resolveURL(sourceURI,options.path),resolve,undefined,reject);});}).then(function(texture){// Clean up resources and configure Texture. if(isObjectURL===true){URL.revokeObjectURL(sourceURI);}texture.flipY=false;if(textureDef.name)texture.name=textureDef.name;// Ignore unknown mime types, like DDS files. if(source.mimeType in MIME_TYPE_FORMATS){texture.format=MIME_TYPE_FORMATS[source.mimeType];}var samplers=json.samplers||{};var sampler=samplers[textureDef.sampler]||{};texture.magFilter=WEBGL_FILTERS[sampler.magFilter]||LinearFilter;texture.minFilter=WEBGL_FILTERS[sampler.minFilter]||LinearMipmapLinearFilter;texture.wrapS=WEBGL_WRAPPINGS[sampler.wrapS]||RepeatWrapping;texture.wrapT=WEBGL_WRAPPINGS[sampler.wrapT]||RepeatWrapping;parser.associations.set(texture,{type:'textures',index:textureIndex});return texture;});};/** * Asynchronously assigns a texture to the given material parameters. * @param {Object} materialParams * @param {string} mapName * @param {Object} mapDef * @return {Promise} */GLTFParser.prototype.assignTexture=function(materialParams,mapName,mapDef){var parser=this;return this.getDependency('texture',mapDef.index).then(function(texture){if(!texture.isCompressedTexture){switch(mapName){case'aoMap':case'emissiveMap':case'metalnessMap':case'normalMap':case'roughnessMap':texture.format=RGBFormat;break;}}// Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured // However, we will copy UV set 0 to UV set 1 on demand for aoMap if(mapDef.texCoord!==undefined&&mapDef.texCoord!=0&&!(mapName==='aoMap'&&mapDef.texCoord==1)){console.warn('THREE.GLTFLoader: Custom UV set '+mapDef.texCoord+' for texture '+mapName+' not yet supported.');}if(parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]){var transform=mapDef.extensions!==undefined?mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]:undefined;if(transform){var gltfReference=parser.associations.get(texture);texture=parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture,transform);parser.associations.set(texture,gltfReference);}}materialParams[mapName]=texture;});};/** * Assigns final material to a Mesh, Line, or Points instance. The instance * already has a material (generated from the glTF material options alone) * but reuse of the same glTF material may require multiple threejs materials * to accomodate different primitive types, defines, etc. New materials will * be created if necessary, and reused from a cache. * @param {Object3D} mesh Mesh, Line, or Points instance. */GLTFParser.prototype.assignFinalMaterial=function(mesh){var geometry=mesh.geometry;var material=mesh.material;var useVertexTangents=geometry.attributes.tangent!==undefined;var useVertexColors=geometry.attributes.color!==undefined;var useFlatShading=geometry.attributes.normal===undefined;var useSkinning=mesh.isSkinnedMesh===true;var useMorphTargets=Object.keys(geometry.morphAttributes).length>0;var useMorphNormals=useMorphTargets&&geometry.morphAttributes.normal!==undefined;if(mesh.isPoints){var cacheKey='PointsMaterial:'+material.uuid;var pointsMaterial=this.cache.get(cacheKey);if(!pointsMaterial){pointsMaterial=new PointsMaterial();Material.prototype.copy.call(pointsMaterial,material);pointsMaterial.color.copy(material.color);pointsMaterial.map=material.map;pointsMaterial.sizeAttenuation=false;// glTF spec says points should be 1px this.cache.add(cacheKey,pointsMaterial);}material=pointsMaterial;}else if(mesh.isLine){var cacheKey='LineBasicMaterial:'+material.uuid;var lineMaterial=this.cache.get(cacheKey);if(!lineMaterial){lineMaterial=new LineBasicMaterial();Material.prototype.copy.call(lineMaterial,material);lineMaterial.color.copy(material.color);this.cache.add(cacheKey,lineMaterial);}material=lineMaterial;}// Clone the material if it will be modified if(useVertexTangents||useVertexColors||useFlatShading||useSkinning||useMorphTargets){var cacheKey='ClonedMaterial:'+material.uuid+':';if(material.isGLTFSpecularGlossinessMaterial)cacheKey+='specular-glossiness:';if(useSkinning)cacheKey+='skinning:';if(useVertexTangents)cacheKey+='vertex-tangents:';if(useVertexColors)cacheKey+='vertex-colors:';if(useFlatShading)cacheKey+='flat-shading:';if(useMorphTargets)cacheKey+='morph-targets:';if(useMorphNormals)cacheKey+='morph-normals:';var cachedMaterial=this.cache.get(cacheKey);if(!cachedMaterial){cachedMaterial=material.clone();if(useSkinning)cachedMaterial.skinning=true;if(useVertexTangents)cachedMaterial.vertexTangents=true;if(useVertexColors)cachedMaterial.vertexColors=true;if(useFlatShading)cachedMaterial.flatShading=true;if(useMorphTargets)cachedMaterial.morphTargets=true;if(useMorphNormals)cachedMaterial.morphNormals=true;this.cache.add(cacheKey,cachedMaterial);this.associations.set(cachedMaterial,this.associations.get(material));}material=cachedMaterial;}// workarounds for mesh and geometry if(material.aoMap&&geometry.attributes.uv2===undefined&&geometry.attributes.uv!==undefined){geometry.setAttribute('uv2',geometry.attributes.uv);}// https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995 if(material.normalScale&&!useVertexTangents){material.normalScale.y=-material.normalScale.y;}if(material.clearcoatNormalScale&&!useVertexTangents){material.clearcoatNormalScale.y=-material.clearcoatNormalScale.y;}mesh.material=material;};/** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials * @param {number} materialIndex * @return {Promise} */GLTFParser.prototype.loadMaterial=function(materialIndex){var parser=this;var json=this.json;var extensions=this.extensions;var materialDef=json.materials[materialIndex];var materialType;var materialParams={};var materialExtensions=materialDef.extensions||{};var pending=[];if(materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]){var sgExtension=extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];materialType=sgExtension.getMaterialType();pending.push(sgExtension.extendParams(materialParams,materialDef,parser));}else if(materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]){var kmuExtension=extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];materialType=kmuExtension.getMaterialType();pending.push(kmuExtension.extendParams(materialParams,materialDef,parser));}else{// Specification: // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material materialType=MeshStandardMaterial;var metallicRoughness=materialDef.pbrMetallicRoughness||{};materialParams.color=new Color(1.0,1.0,1.0);materialParams.opacity=1.0;if(Array.isArray(metallicRoughness.baseColorFactor)){var array=metallicRoughness.baseColorFactor;materialParams.color.fromArray(array);materialParams.opacity=array[3];}if(metallicRoughness.baseColorTexture!==undefined){pending.push(parser.assignTexture(materialParams,'map',metallicRoughness.baseColorTexture));}materialParams.metalness=metallicRoughness.metallicFactor!==undefined?metallicRoughness.metallicFactor:1.0;materialParams.roughness=metallicRoughness.roughnessFactor!==undefined?metallicRoughness.roughnessFactor:1.0;if(metallicRoughness.metallicRoughnessTexture!==undefined){pending.push(parser.assignTexture(materialParams,'metalnessMap',metallicRoughness.metallicRoughnessTexture));pending.push(parser.assignTexture(materialParams,'roughnessMap',metallicRoughness.metallicRoughnessTexture));}}if(materialDef.doubleSided===true){materialParams.side=DoubleSide;}var alphaMode=materialDef.alphaMode||ALPHA_MODES.OPAQUE;if(alphaMode===ALPHA_MODES.BLEND){materialParams.transparent=true;// See: https://github.com/mrdoob/three.js/issues/17706 materialParams.depthWrite=false;}else{materialParams.transparent=false;if(alphaMode===ALPHA_MODES.MASK){materialParams.alphaTest=materialDef.alphaCutoff!==undefined?materialDef.alphaCutoff:0.5;}}if(materialDef.normalTexture!==undefined&&materialType!==MeshBasicMaterial){pending.push(parser.assignTexture(materialParams,'normalMap',materialDef.normalTexture));materialParams.normalScale=new Vector2(1,1);if(materialDef.normalTexture.scale!==undefined){materialParams.normalScale.set(materialDef.normalTexture.scale,materialDef.normalTexture.scale);}}if(materialDef.occlusionTexture!==undefined&&materialType!==MeshBasicMaterial){pending.push(parser.assignTexture(materialParams,'aoMap',materialDef.occlusionTexture));if(materialDef.occlusionTexture.strength!==undefined){materialParams.aoMapIntensity=materialDef.occlusionTexture.strength;}}if(materialDef.emissiveFactor!==undefined&&materialType!==MeshBasicMaterial){materialParams.emissive=new Color().fromArray(materialDef.emissiveFactor);}if(materialDef.emissiveTexture!==undefined&&materialType!==MeshBasicMaterial){pending.push(parser.assignTexture(materialParams,'emissiveMap',materialDef.emissiveTexture));}if(materialExtensions[EXTENSIONS.KHR_MATERIALS_CLEARCOAT]){var clearcoatExtension=extensions[EXTENSIONS.KHR_MATERIALS_CLEARCOAT];materialType=clearcoatExtension.getMaterialType();pending.push(clearcoatExtension.extendParams(materialParams,{extensions:materialExtensions},parser));}return Promise.all(pending).then(function(){var material;if(materialType===GLTFMeshStandardSGMaterial){material=extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams);}else{material=new materialType(materialParams);}if(materialDef.name)material.name=materialDef.name;// baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding. if(material.map)material.map.encoding=sRGBEncoding;if(material.emissiveMap)material.emissiveMap.encoding=sRGBEncoding;assignExtrasToUserData(material,materialDef);parser.associations.set(material,{type:'materials',index:materialIndex});if(materialDef.extensions)addUnknownExtensionsToUserData(extensions,material,materialDef);return material;});};/** * @param {BufferGeometry} geometry * @param {GLTF.Primitive} primitiveDef * @param {GLTFParser} parser */function computeBounds(geometry,primitiveDef,parser){var attributes=primitiveDef.attributes;var box=new Box3();if(attributes.POSITION!==undefined){var accessor=parser.json.accessors[attributes.POSITION];var min=accessor.min;var max=accessor.max;// glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement. if(min!==undefined&&max!==undefined){box.set(new Vector3(min[0],min[1],min[2]),new Vector3(max[0],max[1],max[2]));}else{console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.');return;}}else{return;}var targets=primitiveDef.targets;if(targets!==undefined){var maxDisplacement=new Vector3();var vector=new Vector3();for(var i=0,il=targets.length;i} */function addPrimitiveAttributes(geometry,primitiveDef,parser){var attributes=primitiveDef.attributes;var pending=[];function assignAttributeAccessor(accessorIndex,attributeName){return parser.getDependency('accessor',accessorIndex).then(function(accessor){geometry.setAttribute(attributeName,accessor);});}for(var gltfAttributeName in attributes){var threeAttributeName=ATTRIBUTES[gltfAttributeName]||gltfAttributeName.toLowerCase();// Skip attributes already provided by e.g. Draco extension. if(threeAttributeName in geometry.attributes)continue;pending.push(assignAttributeAccessor(attributes[gltfAttributeName],threeAttributeName));}if(primitiveDef.indices!==undefined&&!geometry.index){var accessor=parser.getDependency('accessor',primitiveDef.indices).then(function(accessor){geometry.setIndex(accessor);});pending.push(accessor);}assignExtrasToUserData(geometry,primitiveDef);computeBounds(geometry,primitiveDef,parser);return Promise.all(pending).then(function(){return primitiveDef.targets!==undefined?addMorphTargets(geometry,primitiveDef.targets,parser):geometry;});}/** * @param {BufferGeometry} geometry * @param {Number} drawMode * @return {BufferGeometry} */function toTrianglesDrawMode(geometry,drawMode){var index=geometry.getIndex();// generate index if not present if(index===null){var indices=[];var position=geometry.getAttribute('position');if(position!==undefined){for(var i=0;i} primitives * @return {Promise>} */GLTFParser.prototype.loadGeometries=function(primitives){var parser=this;var extensions=this.extensions;var cache=this.primitiveCache;function createDracoPrimitive(primitive){return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive,parser).then(function(geometry){return addPrimitiveAttributes(geometry,primitive,parser);});}var pending=[];for(var i=0,il=primitives.length;i} */GLTFParser.prototype.loadMesh=function(meshIndex){var parser=this;var json=this.json;var meshDef=json.meshes[meshIndex];var primitives=meshDef.primitives;var pending=[];for(var i=0,il=primitives.length;i0){updateMorphTargets(mesh,meshDef);}mesh.name=meshDef.name||'mesh_'+meshIndex;if(geometries.length>1)mesh.name+='_'+i;assignExtrasToUserData(mesh,meshDef);parser.assignFinalMaterial(mesh);meshes.push(mesh);}if(meshes.length===1){return meshes[0];}var group=new Group();for(var i=0,il=meshes.length;i} */GLTFParser.prototype.loadCamera=function(cameraIndex){var camera;var cameraDef=this.json.cameras[cameraIndex];var params=cameraDef[cameraDef.type];if(!params){console.warn('THREE.GLTFLoader: Missing camera parameters.');return;}if(cameraDef.type==='perspective'){camera=new PerspectiveCamera(MathUtils.radToDeg(params.yfov),params.aspectRatio||1,params.znear||1,params.zfar||2e6);}else if(cameraDef.type==='orthographic'){camera=new OrthographicCamera(-params.xmag,params.xmag,params.ymag,-params.ymag,params.znear,params.zfar);}if(cameraDef.name)camera.name=cameraDef.name;assignExtrasToUserData(camera,cameraDef);return Promise.resolve(camera);};/** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins * @param {number} skinIndex * @return {Promise} */GLTFParser.prototype.loadSkin=function(skinIndex){var skinDef=this.json.skins[skinIndex];var skinEntry={joints:skinDef.joints};if(skinDef.inverseBindMatrices===undefined){return Promise.resolve(skinEntry);}return this.getDependency('accessor',skinDef.inverseBindMatrices).then(function(accessor){skinEntry.inverseBindMatrices=accessor;return skinEntry;});};/** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations * @param {number} animationIndex * @return {Promise} */GLTFParser.prototype.loadAnimation=function(animationIndex){var json=this.json;var animationDef=json.animations[animationIndex];var pendingNodes=[];var pendingInputAccessors=[];var pendingOutputAccessors=[];var pendingSamplers=[];var pendingTargets=[];for(var i=0,il=animationDef.channels.length;i} */GLTFParser.prototype.loadNode=function(nodeIndex){var json=this.json;var extensions=this.extensions;var parser=this;var meshReferences=json.meshReferences;var meshUses=json.meshUses;var nodeDef=json.nodes[nodeIndex];return function(){var pending=[];if(nodeDef.mesh!==undefined){pending.push(parser.getDependency('mesh',nodeDef.mesh).then(function(mesh){var node;if(meshReferences[nodeDef.mesh]>1){var instanceNum=meshUses[nodeDef.mesh]++;node=mesh.clone();node.name+='_instance_'+instanceNum;}else{node=mesh;}// if weights are provided on the node, override weights on the mesh. if(nodeDef.weights!==undefined){node.traverse(function(o){if(!o.isMesh)return;for(var i=0,il=nodeDef.weights.length;i1){node=new Group();}else if(objects.length===1){node=objects[0];}else{node=new Object3D();}if(node!==objects[0]){for(var i=0,il=objects.length;i} */GLTFParser.prototype.loadScene=function(){// scene node hierachy builder function buildNodeHierachy(nodeId,parentObject,json,parser){var nodeDef=json.nodes[nodeId];return parser.getDependency('node',nodeId).then(function(node){if(nodeDef.skin===undefined)return node;// build skeleton here as well var skinEntry;return parser.getDependency('skin',nodeDef.skin).then(function(skin){skinEntry=skin;var pendingJoints=[];for(var i=0,il=skinEntry.joints.length;i1&&arguments[1]!==undefined?arguments[1]:5;_classCallCheck(this,CacheEvictionPolicy);this[_a$1]=new Map();this[_b]=[];this[$cache]=cache;this[$evictionThreshold]=evictionThreshold;}_createClass(CacheEvictionPolicy,[{key:"retainerCount",value:function retainerCount(key){return this[$retainerCount].get(key)||0;}},{key:"reset",value:function reset(){this[$retainerCount].clear();this[$recentlyUsed]=[];}},{key:"retain",value:function retain(key){if(!this[$retainerCount].has(key)){this[$retainerCount].set(key,0);}this[$retainerCount].set(key,this[$retainerCount].get(key)+1);var recentlyUsedIndex=this[$recentlyUsed].indexOf(key);if(recentlyUsedIndex!==-1){this[$recentlyUsed].splice(recentlyUsedIndex,1);}this[$recentlyUsed].unshift(key);this[$evict]();}},{key:"release",value:function release(key){if(this[$retainerCount].has(key)){this[$retainerCount].set(key,Math.max(this[$retainerCount].get(key)-1,0));}this[$evict]();}},{key:(_a$1=$retainerCount,_b=$recentlyUsed,$evict),value:function value(){if(this[$recentlyUsed].length=this[$evictionThreshold];--_i3){var key=this[$recentlyUsed][_i3];var retainerCount=this[$retainerCount].get(key);if(retainerCount===0){this[$cache].delete(key);this[$recentlyUsed].splice(_i3,1);}}}},{key:"evictionThreshold",set:function set(value){this[$evictionThreshold]=value;this[$evict]();},get:function get(){return this[$evictionThreshold];}},{key:"cache",get:function get(){return this[$cache];}}]);return CacheEvictionPolicy;}();var _a$2,_b$1;var loadWithLoader=function loadWithLoader(url,loader){var progressCallback=arguments.length>2&&arguments[2]!==undefined?arguments[2]:function(){};var onProgress=function onProgress(event){progressCallback(Math.max(0,Math.min(1,event.loaded/event.total)));};return new Promise(function(resolve,reject){loader.load(url,resolve,onProgress,reject);});};var cache=new Map();var preloaded=new Map();var dracoDecoderLocation;var dracoLoader=new DRACOLoader();var $loader=Symbol('loader');var $evictionPolicy=Symbol('evictionPolicy');var $GLTFInstance=Symbol('GLTFInstance');var CachingGLTFLoader=/*#__PURE__*/function(_EventDispatcher){_inherits(CachingGLTFLoader,_EventDispatcher);var _super4=_createSuper(CachingGLTFLoader);function CachingGLTFLoader(GLTFInstance){var _this14;_classCallCheck(this,CachingGLTFLoader);_this14=_super4.call(this);_this14[_b$1]=new GLTFLoader();_this14[$GLTFInstance]=GLTFInstance;_this14[$loader].setDRACOLoader(dracoLoader);return _this14;}_createClass(CachingGLTFLoader,[{key:"preload",value:function(){var _preload=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee2(url,element){var progressCallback,rawGLTFLoads,_GLTFInstance,gltfInstanceLoads,_args2=arguments;return regeneratorRuntime.wrap(function _callee2$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:progressCallback=_args2.length>2&&_args2[2]!==undefined?_args2[2]:function(){};this.dispatchEvent({type:'preload',element:element,src:url});if(!cache.has(url)){rawGLTFLoads=loadWithLoader(url,this[$loader],function(progress){progressCallback(progress*0.8);});_GLTFInstance=this[$GLTFInstance];gltfInstanceLoads=rawGLTFLoads.then(function(rawGLTF){return _GLTFInstance.prepare(rawGLTF);}).then(function(preparedGLTF){progressCallback(0.9);return new _GLTFInstance(preparedGLTF);});cache.set(url,gltfInstanceLoads);}_context3.next=5;return cache.get(url);case 5:preloaded.set(url,true);if(progressCallback){progressCallback(1.0);}case 7:case"end":return _context3.stop();}}},_callee2,this);}));function preload(_x2,_x3){return _preload.apply(this,arguments);}return preload;}()},{key:"load",value:function(){var _load=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee3(url,element){var _this15=this;var progressCallback,gltf,clone,_args3=arguments;return regeneratorRuntime.wrap(function _callee3$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:progressCallback=_args3.length>2&&_args3[2]!==undefined?_args3[2]:function(){};_context4.next=3;return this.preload(url,element,progressCallback);case 3:_context4.next=5;return cache.get(url);case 5:gltf=_context4.sent;_context4.next=8;return gltf.clone();case 8:clone=_context4.sent;this[$evictionPolicy].retain(url);clone.dispose=function(){var originalDispose=clone.dispose;var disposed=false;return function(){if(disposed){return;}disposed=true;originalDispose.apply(clone);_this15[$evictionPolicy].release(url);};}();return _context4.abrupt("return",clone);case 12:case"end":return _context4.stop();}}},_callee3,this);}));function load(_x4,_x5){return _load.apply(this,arguments);}return load;}()},{key:(_a$2=$evictionPolicy,_b$1=$loader,$evictionPolicy),get:function get(){return this.constructor[$evictionPolicy];}}],[{key:"setDRACODecoderLocation",value:function setDRACODecoderLocation(url){dracoDecoderLocation=url;dracoLoader.setDecoderPath(url);}},{key:"getDRACODecoderLocation",value:function getDRACODecoderLocation(){return dracoDecoderLocation;}},{key:"clearCache",value:function clearCache(){var _this16=this;cache.forEach(function(_value,url){_this16.delete(url);});this[$evictionPolicy].reset();}},{key:"has",value:function has(url){return cache.has(url);}},{key:"delete",value:function(){var _delete2=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee4(url){var gltfLoads,gltf;return regeneratorRuntime.wrap(function _callee4$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:if(this.has(url)){_context5.next=2;break;}return _context5.abrupt("return");case 2:gltfLoads=cache.get(url);preloaded.delete(url);cache.delete(url);_context5.next=7;return gltfLoads;case 7:gltf=_context5.sent;gltf.dispose();case 9:case"end":return _context5.stop();}}},_callee4,this);}));function _delete(_x6){return _delete2.apply(this,arguments);}return _delete;}()},{key:"hasFinishedLoading",value:function hasFinishedLoading(url){return!!preloaded.get(url);}},{key:"cache",get:function get(){return cache;}}]);return CachingGLTFLoader;}(EventDispatcher);CachingGLTFLoader[_a$2]=new CacheEvictionPolicy(CachingGLTFLoader);var _a$3;var SETTLING_TIME=10000;var DECAY_MILLISECONDS=50;var NATURAL_FREQUENCY=1/DECAY_MILLISECONDS;var NIL_SPEED=0.0002*NATURAL_FREQUENCY;var $velocity=Symbol('velocity');var Damper=/*#__PURE__*/function(){function Damper(){_classCallCheck(this,Damper);this[_a$3]=0;}_createClass(Damper,[{key:"update",value:function update(x,xGoal,timeStepMilliseconds,xNormalization){if(x==null||xNormalization===0){return xGoal;}if(x===xGoal&&this[$velocity]===0){return xGoal;}if(timeStepMilliseconds<0){return x;}var deltaX=x-xGoal;var intermediateVelocity=this[$velocity]+NATURAL_FREQUENCY*deltaX;var intermediateX=deltaX+timeStepMilliseconds*intermediateVelocity;var decay=Math.exp(-NATURAL_FREQUENCY*timeStepMilliseconds);var newVelocity=(intermediateVelocity-NATURAL_FREQUENCY*intermediateX)*decay;var acceleration=-NATURAL_FREQUENCY*(newVelocity+intermediateVelocity*decay);if(Math.abs(newVelocity)=0){this[$velocity]=0;return xGoal;}else{this[$velocity]=newVelocity;return xGoal+intermediateX*decay;}}}]);return Damper;}();_a$3=$velocity;/** * @author mrdoob / http://mrdoob.com/ */var CSS2DObject=function CSS2DObject(element){Object3D.call(this);this.element=element;this.element.style.position='absolute';this.addEventListener('removed',function(){this.traverse(function(object){if(_instanceof(object.element,Element)&&object.element.parentNode!==null){object.element.parentNode.removeChild(object.element);}});});};CSS2DObject.prototype=Object.create(Object3D.prototype);CSS2DObject.prototype.constructor=CSS2DObject;// var CSS2DRenderer=function CSS2DRenderer(){var _this=this;var _width,_height;var _widthHalf,_heightHalf;var vector=new Vector3();var viewMatrix=new Matrix4();var viewProjectionMatrix=new Matrix4();var cache={objects:new WeakMap()};var domElement=document.createElement('div');domElement.style.overflow='hidden';this.domElement=domElement;this.getSize=function(){return{width:_width,height:_height};};this.setSize=function(width,height){_width=width;_height=height;_widthHalf=_width/2;_heightHalf=_height/2;domElement.style.width=width+'px';domElement.style.height=height+'px';};var renderObject=function renderObject(object,scene,camera){if(_instanceof(object,CSS2DObject)){object.onBeforeRender(_this,scene,camera);vector.setFromMatrixPosition(object.matrixWorld);vector.applyMatrix4(viewProjectionMatrix);var element=object.element;var style='translate(-50%,-50%) translate('+(vector.x*_widthHalf+_widthHalf)+'px,'+(-vector.y*_heightHalf+_heightHalf)+'px)';element.style.WebkitTransform=style;element.style.MozTransform=style;element.style.oTransform=style;element.style.transform=style;element.style.display=object.visible&&vector.z>=-1&&vector.z<=1?'':'none';var objectData={distanceToCameraSquared:getDistanceToSquared(camera,object)};cache.objects.set(object,objectData);if(element.parentNode!==domElement){domElement.appendChild(element);}object.onAfterRender(_this,scene,camera);}for(var i=0,l=object.children.length;iMAX_PARSE_ITERATIONS){inputString='';break;}var expressionParseResult=parseExpression(inputString);var expression=expressionParseResult.nodes[0];if(expression==null||expression.terms.length===0){break;}expressions.push(expression);inputString=expressionParseResult.remainingInput;}return cache[cacheKey]=expressions;};}();var parseExpression=function(){var IS_IDENT_RE=/^(\-\-|[a-z\u0240-\uffff])/i;var IS_OPERATOR_RE=/^([\*\+\/]|[\-]\s)/i;var IS_EXPRESSION_END_RE=/^[\),]/;var FUNCTION_ARGUMENTS_FIRST_TOKEN='(';var HEX_FIRST_TOKEN='#';return function(inputString){var terms=[];while(inputString.length){inputString=inputString.trim();if(IS_EXPRESSION_END_RE.test(inputString)){break;}else if(inputString[0]===FUNCTION_ARGUMENTS_FIRST_TOKEN){var _parseFunctionArgumen=parseFunctionArguments(inputString),nodes=_parseFunctionArgumen.nodes,remainingInput=_parseFunctionArgumen.remainingInput;inputString=remainingInput;terms.push({type:'function',name:{type:'ident',value:'calc'},arguments:nodes});}else if(IS_IDENT_RE.test(inputString)){var identParseResult=parseIdent(inputString);var identNode=identParseResult.nodes[0];inputString=identParseResult.remainingInput;if(inputString[0]===FUNCTION_ARGUMENTS_FIRST_TOKEN){var _parseFunctionArgumen2=parseFunctionArguments(inputString),_nodes=_parseFunctionArgumen2.nodes,_remainingInput=_parseFunctionArgumen2.remainingInput;terms.push({type:'function',name:identNode,arguments:_nodes});inputString=_remainingInput;}else{terms.push(identNode);}}else if(IS_OPERATOR_RE.test(inputString)){terms.push({type:'operator',value:inputString[0]});inputString=inputString.slice(1);}else{var _ref=inputString[0]===HEX_FIRST_TOKEN?parseHex(inputString):parseNumber(inputString),_nodes2=_ref.nodes,_remainingInput2=_ref.remainingInput;if(_nodes2.length===0){break;}terms.push(_nodes2[0]);inputString=_remainingInput2;}}return{nodes:[{type:'expression',terms:terms}],remainingInput:inputString};};}();var parseIdent=function(){var NOT_IDENT_RE=/[^a-z^0-9^_^\-^\u0240-\uffff]/i;return function(inputString){var match=inputString.match(NOT_IDENT_RE);var ident=match==null?inputString:inputString.substr(0,match.index);var remainingInput=match==null?'':inputString.substr(match.index);return{nodes:[{type:'ident',value:ident}],remainingInput:remainingInput};};}();var parseNumber=function(){var VALUE_RE=/[\+\-]?(\d+[\.]\d+|\d+|[\.]\d+)([eE][\+\-]?\d+)?/;var UNIT_RE=/^[a-z%]+/i;var ALLOWED_UNITS=/^(m|mm|cm|rad|deg|[%])$/;return function(inputString){var valueMatch=inputString.match(VALUE_RE);var value=valueMatch==null?'0':valueMatch[0];inputString=value==null?inputString:inputString.slice(value.length);var unitMatch=inputString.match(UNIT_RE);var unit=unitMatch!=null&&unitMatch[0]!==''?unitMatch[0]:null;var remainingInput=unitMatch==null?inputString:inputString.slice(unit.length);if(unit!=null&&!ALLOWED_UNITS.test(unit)){unit=null;}return{nodes:[{type:'number',number:parseFloat(value)||0,unit:unit}],remainingInput:remainingInput};};}();var parseHex=function(){var HEX_RE=/^[a-f0-9]*/i;return function(inputString){inputString=inputString.slice(1).trim();var hexMatch=inputString.match(HEX_RE);var nodes=hexMatch==null?[]:[{type:'hex',value:hexMatch[0]}];return{nodes:nodes,remainingInput:hexMatch==null?inputString:inputString.slice(hexMatch[0].length)};};}();var parseFunctionArguments=function parseFunctionArguments(inputString){var expressionNodes=[];inputString=inputString.slice(1).trim();while(inputString.length){var expressionParseResult=parseExpression(inputString);expressionNodes.push(expressionParseResult.nodes[0]);inputString=expressionParseResult.remainingInput.trim();if(inputString[0]===','){inputString=inputString.slice(1).trim();}else if(inputString[0]===')'){inputString=inputString.slice(1);break;}}return{nodes:expressionNodes,remainingInput:inputString};};var $visitedTypes=Symbol('visitedTypes');var ASTWalker=/*#__PURE__*/function(){function ASTWalker(visitedTypes){_classCallCheck(this,ASTWalker);this[$visitedTypes]=visitedTypes;}_createClass(ASTWalker,[{key:"walk",value:function walk(ast,callback){var remaining=ast.slice();while(remaining.length){var next=remaining.shift();if(this[$visitedTypes].indexOf(next.type)>-1){callback(next);}switch(next.type){case'expression':remaining.unshift.apply(remaining,_toConsumableArray(next.terms));break;case'function':remaining.unshift.apply(remaining,[next.name].concat(_toConsumableArray(next.arguments)));break;}}}}]);return ASTWalker;}();var ZERO=Object.freeze({type:'number',number:0,unit:null});var degreesToRadians=function degreesToRadians(numberNode$$1){var fallbackRadianValue=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var number=numberNode$$1.number,unit=numberNode$$1.unit;if(!isFinite(number)){number=fallbackRadianValue;unit='rad';}else if(numberNode$$1.unit==='rad'||numberNode$$1.unit==null){return numberNode$$1;}var valueIsDegrees=unit==='deg'&&number!=null;var value=valueIsDegrees?number:0;var radians=value*Math.PI/180;return{type:'number',number:radians,unit:'rad'};};var lengthToBaseMeters=function lengthToBaseMeters(numberNode$$1){var fallbackMeterValue=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var number=numberNode$$1.number,unit=numberNode$$1.unit;if(!isFinite(number)){number=fallbackMeterValue;unit='m';}else if(numberNode$$1.unit==='m'){return numberNode$$1;}var scale;switch(unit){default:scale=1;break;case'cm':scale=1/100;break;case'mm':scale=1/1000;break;}var value=scale*number;return{type:'number',number:value,unit:'m'};};var normalizeUnit=function(){var identity=function identity(node){return node;};var unitNormalizers={'rad':identity,'deg':degreesToRadians,'m':identity,'mm':lengthToBaseMeters,'cm':lengthToBaseMeters};return function(node){var fallback=arguments.length>1&&arguments[1]!==undefined?arguments[1]:ZERO;var number=node.number,unit=node.unit;if(!isFinite(number)){number=fallback.number;unit=fallback.unit;}if(unit==null){return node;}var normalize=unitNormalizers[unit];if(normalize==null){return fallback;}return normalize(node);};}();var _a$4,_b$2,_c,_d;var $slot=Symbol('slot');var $pivot=Symbol('pivot');var $referenceCount=Symbol('referenceCount');var $updateVisibility=Symbol('updateVisibility');var $visible=Symbol('visible');var Hotspot=/*#__PURE__*/function(_CSS2DObject){_inherits(Hotspot,_CSS2DObject);var _super5=_createSuper(Hotspot);function Hotspot(config){var _this17;_classCallCheck(this,Hotspot);_this17=_super5.call(this,document.createElement('div'));_this17.normal=new Vector3(0,1,0);_this17[_a$4]=false;_this17[_b$2]=1;_this17[_c]=document.createElement('div');_this17[_d]=document.createElement('slot');_this17.element.classList.add('annotation-wrapper');_this17[$slot].name=config.name;_this17.element.appendChild(_this17[$pivot]);_this17[$pivot].appendChild(_this17[$slot]);_this17.updatePosition(config.position);_this17.updateNormal(config.normal);return _this17;}_createClass(Hotspot,[{key:"show",value:function show(){if(!this[$visible]){this[$visible]=true;this[$updateVisibility]();}}},{key:"hide",value:function hide(){if(this[$visible]){this[$visible]=false;this[$updateVisibility]();}}},{key:"increment",value:function increment(){this[$referenceCount]++;}},{key:"decrement",value:function decrement(){if(this[$referenceCount]>0){--this[$referenceCount];}return this[$referenceCount]===0;}},{key:"updatePosition",value:function updatePosition(position){if(position==null)return;var positionNodes=parseExpressions(position)[0].terms;for(var _i4=0;_i4<3;++_i4){this.position.setComponent(_i4,normalizeUnit(positionNodes[_i4]).number);}}},{key:"updateNormal",value:function updateNormal(normal){if(normal==null)return;var normalNodes=parseExpressions(normal)[0].terms;for(var _i5=0;_i5<3;++_i5){this.normal.setComponent(_i5,normalizeUnit(normalNodes[_i5]).number);}}},{key:"orient",value:function orient(radians){this[$pivot].style.transform="rotate(".concat(radians,"rad)");}},{key:(_a$4=$visible,_b$2=$referenceCount,_c=$pivot,_d=$slot,$updateVisibility),value:function value(){var _this18=this;if(this[$visible]){this.element.classList.remove('hide');}else{this.element.classList.add('hide');}this[$slot].assignedNodes().forEach(function(node){if(node.nodeType!==Node.ELEMENT_NODE){return;}var element=node;var visibilityAttribute=element.dataset.visibilityAttribute;if(visibilityAttribute!=null){var attributeName="data-".concat(visibilityAttribute);if(_this18[$visible]){element.setAttribute(attributeName,'');}else{element.removeAttribute(attributeName);}}element.dispatchEvent(new CustomEvent('hotspot-visibility',{detail:{visible:_this18[$visible]}}));});}}]);return Hotspot;}(CSS2DObject);var reduceVertices=function reduceVertices(model,func){var value=0;var vector=new Vector3();model.traverse(function(object){var i,l;object.updateWorldMatrix(false,false);var geometry=object.geometry;if(geometry!==undefined){if(geometry.isGeometry){var _vertices=geometry.vertices;for(i=0,l=_vertices.length;i0;this.boundingBox.copy(model.boundingBox);this.size.copy(model.size);var boundingBox=this.boundingBox,size=this.size;if(this.isAnimated){var maxDimension=Math.max(size.x,size.y,size.z)*ANIMATION_SCALING;size.y=maxDimension;boundingBox.expandByVector(size.subScalar(maxDimension).multiplyScalar(-0.5));boundingBox.max.y=boundingBox.min.y+maxDimension;size.set(maxDimension,maxDimension,maxDimension);}var shadowOffset=size.y*OFFSET;this.position.y=boundingBox.max.y+shadowOffset;boundingBox.getCenter(this.floor.position);this.setSoftness(softness);}},{key:"setSoftness",value:function setSoftness(softness){var resolution=Math.pow(2,LOG_MAX_RESOLUTION-softness*(LOG_MAX_RESOLUTION-LOG_MIN_RESOLUTION));this.setMapSize(resolution);}},{key:"setMapSize",value:function setMapSize(maxMapSize){var _this$shadow=this.shadow,camera=_this$shadow.camera,mapSize=_this$shadow.mapSize,map=_this$shadow.map;var size=this.size,boundingBox=this.boundingBox;if(map!=null){map.dispose();this.shadow.map=null;}if(this.isAnimated){maxMapSize*=ANIMATION_SCALING;}var width=Math.floor(size.x>size.z?maxMapSize:maxMapSize*size.x/size.z);var height=Math.floor(size.x>size.z?maxMapSize*size.z/size.x:maxMapSize);mapSize.set(width,height);var widthPad=2.5*size.x/width;var heightPad=2.5*size.z/height;camera.left=-boundingBox.max.x-widthPad;camera.right=-boundingBox.min.x+widthPad;camera.bottom=boundingBox.min.z-heightPad;camera.top=boundingBox.max.z+heightPad;this.setScaleAndOffset(camera.zoom,0);this.shadow.updateMatrices(this);this.floor.scale.set(size.x+2*widthPad,size.z+2*heightPad,1);this.needsUpdate=true;}},{key:"setIntensity",value:function setIntensity(intensity){this.shadowMaterial.opacity=intensity;if(intensity>0){this.visible=true;this.floor.visible=true;}else{this.visible=false;this.floor.visible=false;}}},{key:"getIntensity",value:function getIntensity(){return this.shadowMaterial.opacity;}},{key:"setRotation",value:function setRotation(radiansY){this.shadow.camera.up.set(Math.sin(radiansY),0,Math.cos(radiansY));this.shadow.updateMatrices(this);}},{key:"setScaleAndOffset",value:function setScaleAndOffset(scale,offset){var sizeY=this.size.y;var inverseScale=1/scale;var shadowOffset=sizeY*OFFSET;this.floor.position.y=2*shadowOffset-sizeY+offset*inverseScale;var camera=this.shadow.camera;camera.zoom=scale;camera.near=0;camera.far=sizeY*scale-offset;camera.projectionMatrix.makeOrthographic(camera.left*scale,camera.right*scale,camera.top*scale,camera.bottom*scale,camera.near,camera.far);camera.projectionMatrixInverse.getInverse(camera.projectionMatrix);}}]);return Shadow;}(DirectionalLight);var _a$5,_b$3;var DEFAULT_FOV_DEG=45;var DEFAULT_HALF_FOV=DEFAULT_FOV_DEG/2*Math.PI/180;var SAFE_RADIUS_RATIO=Math.sin(DEFAULT_HALF_FOV);var DEFAULT_TAN_FOV=Math.tan(DEFAULT_HALF_FOV);var $shadow=Symbol('shadow');var $cancelPendingSourceChange=Symbol('cancelPendingSourceChange');var $currentGLTF=Symbol('currentGLTF');var view=new Vector3();var target=new Vector3();var normalWorld=new Vector3();var Model=/*#__PURE__*/function(_Object3D){_inherits(Model,_Object3D);var _super7=_createSuper(Model);function Model(){var _this20;_classCallCheck(this,Model);_this20=_super7.call(this);_this20[_a$5]=null;_this20[_b$3]=null;_this20.animationsByName=new Map();_this20.currentAnimationAction=null;_this20.animations=[];_this20.modelContainer=new Object3D();_this20.animationNames=[];_this20.boundingBox=new Box3();_this20.size=new Vector3();_this20.idealCameraDistance=0;_this20.fieldOfViewAspect=0;_this20.userData={url:null};_this20.url=null;_this20.name='Model';_this20.modelContainer.name='ModelContainer';_this20.add(_this20.modelContainer);_this20.mixer=new AnimationMixer(_this20.modelContainer);return _this20;}_createClass(Model,[{key:"hasModel",value:function hasModel(){return!!this.modelContainer.children.length;}},{key:"setObject",value:function setObject(model){this.clear();this.modelContainer.add(model);this.updateFraming();this.dispatchEvent({type:'model-load'});}},{key:"setSource",value:function(){var _setSource=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee6(element,url,progressCallback){var _this21=this;var gltf,_gltf,animations,animationsByName,animationNames,_iterator2,_step2,animation;return regeneratorRuntime.wrap(function _callee6$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:if(!(!url||url===this.url)){_context7.next=3;break;}if(progressCallback){progressCallback(1);}return _context7.abrupt("return");case 3:if(this[$cancelPendingSourceChange]!=null){this[$cancelPendingSourceChange]();this[$cancelPendingSourceChange]=null;}this.url=url;_context7.prev=5;_context7.next=8;return new Promise(/*#__PURE__*/function(){var _ref2=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee5(resolve,reject){var result;return regeneratorRuntime.wrap(function _callee5$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:_this21[$cancelPendingSourceChange]=function(){return reject();};_context6.prev=1;_context6.next=4;return element[$renderer].loader.load(url,element,progressCallback);case 4:result=_context6.sent;resolve(result);_context6.next=11;break;case 8:_context6.prev=8;_context6.t0=_context6["catch"](1);reject(_context6.t0);case 11:case"end":return _context6.stop();}}},_callee5,null,[[1,8]]);}));return function(_x10,_x11){return _ref2.apply(this,arguments);};}());case 8:gltf=_context7.sent;_context7.next=16;break;case 11:_context7.prev=11;_context7.t0=_context7["catch"](5);if(!(_context7.t0==null)){_context7.next=15;break;}return _context7.abrupt("return");case 15:throw _context7.t0;case 16:this.clear();this[$currentGLTF]=gltf;if(gltf!=null){this.modelContainer.add(gltf.scene);}_gltf=gltf,animations=_gltf.animations;animationsByName=new Map();animationNames=[];_iterator2=_createForOfIteratorHelper(animations);try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){animation=_step2.value;animationsByName.set(animation.name,animation);animationNames.push(animation.name);}}catch(err){_iterator2.e(err);}finally{_iterator2.f();}this.animations=animations;this.animationsByName=animationsByName;this.animationNames=animationNames;this.userData.url=url;this.updateFraming();this.dispatchEvent({type:'model-load',url:url});case 30:case"end":return _context7.stop();}}},_callee6,this,[[5,11]]);}));function setSource(_x7,_x8,_x9){return _setSource.apply(this,arguments);}return setSource;}()},{key:"playAnimation",value:function playAnimation(){var name=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;var crossfadeTime=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var animations=this.animations;if(animations==null||animations.length===0){console.warn("Cannot play animation (model does not have any animations)");return;}var animationClip=null;if(name!=null){animationClip=this.animationsByName.get(name);}if(animationClip==null){animationClip=animations[0];}try{var lastAnimationAction=this.currentAnimationAction;this.currentAnimationAction=this.mixer.clipAction(animationClip,this).play();this.currentAnimationAction.enabled=true;if(lastAnimationAction!=null&&this.currentAnimationAction!==lastAnimationAction){this.currentAnimationAction.crossFadeFrom(lastAnimationAction,crossfadeTime,false);}}catch(error){console.error(error);}}},{key:"stopAnimation",value:function stopAnimation(){if(this.currentAnimationAction!=null){this.currentAnimationAction.stop();this.currentAnimationAction.reset();this.currentAnimationAction=null;}this.mixer.stopAllAction();}},{key:"updateAnimation",value:function updateAnimation(step){this.mixer.update(step);}},{key:"clear",value:function clear(){this.url=null;this.userData={url:null};var gltf=this[$currentGLTF];if(gltf!=null){var _iterator3=_createForOfIteratorHelper(this.modelContainer.children),_step3;try{for(_iterator3.s();!(_step3=_iterator3.n()).done;){var child=_step3.value;this.modelContainer.remove(child);}}catch(err){_iterator3.e(err);}finally{_iterator3.f();}gltf.dispose();this[$currentGLTF]=null;}if(this.currentAnimationAction!=null){this.currentAnimationAction.stop();this.currentAnimationAction=null;}this.mixer.stopAllAction();this.mixer.uncacheRoot(this);}},{key:"updateFraming",value:function updateFraming(){var _this22=this;var center=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;this.remove(this.modelContainer);if(center==null){this.boundingBox.setFromObject(this.modelContainer);this.boundingBox.getSize(this.size);center=this.boundingBox.getCenter(new Vector3());}var radiusSquared=function radiusSquared(value,vertex){return Math.max(value,center.distanceToSquared(vertex));};var framedRadius=Math.sqrt(reduceVertices(this.modelContainer,radiusSquared));this.idealCameraDistance=framedRadius/SAFE_RADIUS_RATIO;var horizontalFov=function horizontalFov(value,vertex){vertex.sub(center);var radiusXZ=Math.sqrt(vertex.x*vertex.x+vertex.z*vertex.z);return Math.max(value,radiusXZ/(_this22.idealCameraDistance-Math.abs(vertex.y)));};this.fieldOfViewAspect=reduceVertices(this.modelContainer,horizontalFov)/DEFAULT_TAN_FOV;this.add(this.modelContainer);}},{key:"setShadowIntensity",value:function setShadowIntensity(shadowIntensity,shadowSoftness){var shadow=this[$shadow];if(shadow!=null){shadow.setIntensity(shadowIntensity);shadow.setModel(this,shadowSoftness);}else if(shadowIntensity>0){shadow=new Shadow(this,shadowSoftness);shadow.setIntensity(shadowIntensity);this[$shadow]=shadow;}}},{key:"setShadowSoftness",value:function setShadowSoftness(softness){var shadow=this[$shadow];if(shadow!=null){shadow.setSoftness(softness);}}},{key:"setShadowRotation",value:function setShadowRotation(radiansY){var shadow=this[$shadow];if(shadow!=null){shadow.setRotation(radiansY);}}},{key:"updateShadow",value:function updateShadow(){var shadow=this[$shadow];if(shadow==null){return false;}else{var needsUpdate=shadow.needsUpdate;shadow.needsUpdate=false;return needsUpdate;}}},{key:"setShadowScaleAndOffset",value:function setShadowScaleAndOffset(scale,offset){var shadow=this[$shadow];if(shadow!=null){shadow.setScaleAndOffset(scale,offset);}}},{key:"addHotspot",value:function addHotspot(hotspot){this.add(hotspot);}},{key:"removeHotspot",value:function removeHotspot(hotspot){this.remove(hotspot);}},{key:"forHotspots",value:function forHotspots(func){var children=this.children;for(var _i6=0,l=children.length;_i61&&arguments[1]!==undefined?arguments[1]:this;raycaster.setFromCamera(pixelPosition,this.getCamera());var hits=raycaster.intersectObject(object,true);if(hits.length===0){return null;}var hit=hits[0];if(hit.face==null){return null;}return{position:hit.point,normal:hit.face.normal};}},{key:"yaw",set:function set(radiansY){this.rotation.y=radiansY;this.model.setShadowRotation(radiansY);this.isDirty=true;},get:function get(){return this.rotation.y;}}]);return ModelScene;}(Scene);/** * @author Emmett Lalish / elalish * * This class generates custom mipmaps for a roughness map by encoding the lost variation in the * normal map mip levels as increased roughness in the corresponding roughness mip levels. This * helps with rendering accuracy for MeshStandardMaterial, and also helps with anti-aliasing when * using PMREM. If the normal map is larger than the roughness map, the roughness map will be * enlarged to match the dimensions of the normal map. */var _mipmapMaterial=_getMipmapMaterial();var _mesh$1=new Mesh(new PlaneBufferGeometry(2,2),_mipmapMaterial);var _flatCamera$1=new OrthographicCamera(0,1,0,1,0,1);var _tempTarget=null;var _renderer=null;function RoughnessMipmapper(renderer){_renderer=renderer;_renderer.compile(_mesh$1,_flatCamera$1);}RoughnessMipmapper.prototype={constructor:RoughnessMipmapper,generateMipmaps:function generateMipmaps(material){var roughnessMap=material.roughnessMap,normalMap=material.normalMap;if(roughnessMap==null||normalMap==null||!roughnessMap.generateMipmaps||material.userData.roughnessUpdated)return;material.userData.roughnessUpdated=true;var width=Math.max(roughnessMap.image.width,normalMap.image.width);var height=Math.max(roughnessMap.image.height,normalMap.image.height);if(!MathUtils.isPowerOfTwo(width)||!MathUtils.isPowerOfTwo(height))return;var oldTarget=_renderer.getRenderTarget();var autoClear=_renderer.autoClear;_renderer.autoClear=false;if(_tempTarget==null||_tempTarget.width!==width||_tempTarget.height!==height){if(_tempTarget!=null)_tempTarget.dispose();_tempTarget=new WebGLRenderTarget(width,height,{depthBuffer:false,stencilBuffer:false});_tempTarget.scissorTest=true;}if(width!==roughnessMap.image.width||height!==roughnessMap.image.height){var newRoughnessTarget=new WebGLRenderTarget(width,height,{minFilter:LinearMipMapLinearFilter,depthBuffer:false,stencilBuffer:false});newRoughnessTarget.texture.generateMipmaps=true;// Setting the render target causes the memory to be allocated. _renderer.setRenderTarget(newRoughnessTarget);material.roughnessMap=newRoughnessTarget.texture;if(material.metalnessMap==roughnessMap)material.metalnessMap=material.roughnessMap;if(material.aoMap==roughnessMap)material.aoMap=material.roughnessMap;}_mipmapMaterial.uniforms.roughnessMap.value=roughnessMap;_mipmapMaterial.uniforms.normalMap.value=normalMap;var position=new Vector2(0,0);var texelSize=_mipmapMaterial.uniforms.texelSize.value;for(var mip=0;width>=1&&height>=1;++mip,width/=2,height/=2){// Rendering to a mip level is not allowed in webGL1. Instead we must set // up a secondary texture to write the result to, then copy it back to the // proper mipmap level. texelSize.set(1.0/width,1.0/height);if(mip==0)texelSize.set(0.0,0.0);_tempTarget.viewport.set(position.x,position.y,width,height);_tempTarget.scissor.set(position.x,position.y,width,height);_renderer.setRenderTarget(_tempTarget);_renderer.render(_mesh$1,_flatCamera$1);_renderer.copyFramebufferToTexture(position,material.roughnessMap,mip);_mipmapMaterial.uniforms.roughnessMap.value=material.roughnessMap;}if(roughnessMap!==material.roughnessMap)roughnessMap.dispose();_renderer.setRenderTarget(oldTarget);_renderer.autoClear=autoClear;},dispose:function dispose(){_mipmapMaterial.dispose();_mesh$1.geometry.dispose();if(_tempTarget!=null)_tempTarget.dispose();}};function _getMipmapMaterial(){var shaderMaterial=new RawShaderMaterial({uniforms:{roughnessMap:{value:null},normalMap:{value:null},texelSize:{value:new Vector2(1,1)}},vertexShader:"\nprecision mediump float;\nprecision mediump int;\nattribute vec3 position;\nattribute vec2 uv;\nvarying vec2 vUv;\nvoid main() {\n vUv = uv;\n gl_Position = vec4( position, 1.0 );\n}\n ",fragmentShader:"\nprecision mediump float;\nprecision mediump int;\nvarying vec2 vUv;\nuniform sampler2D roughnessMap;\nuniform sampler2D normalMap;\nuniform vec2 texelSize;\n\n#define ENVMAP_TYPE_CUBE_UV\nvec4 envMapTexelToLinear(vec4 a){return a;}\n#include \n\nfloat roughnessToVariance(float roughness) {\nfloat variance = 0.0;\nif (roughness >= r1) {\n variance = (r0 - roughness) * (v1 - v0) / (r0 - r1) + v0;\n} else if (roughness >= r4) {\n variance = (r1 - roughness) * (v4 - v1) / (r1 - r4) + v1;\n} else if (roughness >= r5) {\n variance = (r4 - roughness) * (v5 - v4) / (r4 - r5) + v4;\n} else {\n float roughness2 = roughness * roughness;\n variance = 1.79 * roughness2 * roughness2;\n}\nreturn variance;\n}\nfloat varianceToRoughness(float variance) {\nfloat roughness = 0.0;\nif (variance >= v1) {\n roughness = (v0 - variance) * (r1 - r0) / (v0 - v1) + r0;\n} else if (variance >= v4) {\n roughness = (v1 - variance) * (r4 - r1) / (v1 - v4) + r1;\n} else if (variance >= v5) {\n roughness = (v4 - variance) * (r5 - r4) / (v4 - v5) + r4;\n} else {\n roughness = pow(0.559 * variance, 0.25);// 0.559 = 1.0 / 1.79\n}\nreturn roughness;\n}\n\nvoid main() {\n gl_FragColor = texture2D(roughnessMap, vUv, -1.0);\n if (texelSize.x == 0.0) return;\n float roughness = gl_FragColor.g;\n float variance = roughnessToVariance(roughness);\n vec3 avgNormal;\n for (float x = -1.0; x < 2.0; x += 2.0) {\n for (float y = -1.0; y < 2.0; y += 2.0) {\n vec2 uv = vUv + vec2(x, y) * 0.25 * texelSize;\n avgNormal += normalize(texture2D(normalMap, uv, -1.0).xyz - 0.5);\n }\n }\n variance += 1.0 - 0.25 * length(avgNormal);\n gl_FragColor.g = varianceToRoughness(variance);\n}\n",blending:NoBlending,depthTest:false,depthWrite:false});shaderMaterial.type='RoughnessMipmapper';return shaderMaterial;}var deserializeUrl=function deserializeUrl(url){return url!=null&&url!=='null'?toFullUrl(url):null;};var assertIsArCandidate=function assertIsArCandidate(){if(IS_WEBXR_AR_CANDIDATE){return;}var missingApis=[];if(!HAS_WEBXR_DEVICE_API){missingApis.push('WebXR Device API');}if(!HAS_WEBXR_HIT_TEST_API){missingApis.push('WebXR Hit Test API');}throw new Error("The following APIs are required for AR, but are missing in this browser: ".concat(missingApis.join(', ')));};var toFullUrl=function toFullUrl(partialUrl){var url=new URL(partialUrl,window.location.toString());return url.toString();};var throttle=function throttle(fn,ms){var timer=null;var throttled=function throttled(){if(timer!=null){return;}fn.apply(void 0,arguments);timer=self.setTimeout(function(){return timer=null;},ms);};throttled.flush=function(){if(timer!=null){self.clearTimeout(timer);timer=null;}};return throttled;};var debounce=function debounce(fn,ms){var timer=null;return function(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}if(timer!=null){self.clearTimeout(timer);}timer=self.setTimeout(function(){timer=null;fn.apply(void 0,args);},ms);};};var clamp=function clamp(value,lowerLimit,upperLimit){return Math.max(lowerLimit,Math.min(upperLimit,value));};var CAPPED_DEVICE_PIXEL_RATIO=1;var resolveDpr=function(){var HAS_META_VIEWPORT_TAG=function(){var metas=document.head!=null?Array.from(document.head.querySelectorAll('meta')):[];var _iterator4=_createForOfIteratorHelper(metas),_step4;try{for(_iterator4.s();!(_step4=_iterator4.n()).done;){var meta=_step4.value;if(meta.name==='viewport'){return true;}}}catch(err){_iterator4.e(err);}finally{_iterator4.f();}return false;}();if(!HAS_META_VIEWPORT_TAG){console.warn('No detected; will cap pixel density at 1.');}return function(){return HAS_META_VIEWPORT_TAG?window.devicePixelRatio:CAPPED_DEVICE_PIXEL_RATIO;};}();var isDebugMode=function(){var debugQueryParameterName='model-viewer-debug-mode';var debugQueryParameter=new RegExp("[?&]".concat(debugQueryParameterName,"(&|$)"));return function(){return self.ModelViewerElement&&self.ModelViewerElement.debugMode||self.location&&self.location.search&&self.location.search.match(debugQueryParameter);};}();var getFirstMapKey=function getFirstMapKey(map){if(map.keys!=null){return map.keys().next().value||null;}var firstKey=null;try{map.forEach(function(_value,key,_map){firstKey=key;throw new Error();});}catch(_error){}return firstKey;};var RADIUS=0.2;var LINE_WIDTH=0.03;var MAX_OPACITY=0.75;var SEGMENTS=12;var DELTA_PHI=Math.PI/(2*SEGMENTS);var vector2=new Vector2();var addCorner=function addCorner(vertices,cornerX,cornerY){var phi=cornerX>0?cornerY>0?0:-Math.PI/2:cornerY>0?Math.PI/2:Math.PI;for(var _i7=0;_i7<=SEGMENTS;++_i7){vertices.push(cornerX+(RADIUS-LINE_WIDTH)*Math.cos(phi),cornerY+(RADIUS-LINE_WIDTH)*Math.sin(phi),0,cornerX+RADIUS*Math.cos(phi),cornerY+RADIUS*Math.sin(phi),0);phi+=DELTA_PHI;}};var PlacementBox=/*#__PURE__*/function(_Mesh){_inherits(PlacementBox,_Mesh);var _super9=_createSuper(PlacementBox);function PlacementBox(model){var _this25;_classCallCheck(this,PlacementBox);var geometry=new BufferGeometry();var triangles=[];var vertices=[];var size=model.size,boundingBox=model.boundingBox;var x=size.x/2;var y=size.z/2;addCorner(vertices,x,y);addCorner(vertices,-x,y);addCorner(vertices,-x,-y);addCorner(vertices,x,-y);var numVertices=vertices.length/3;for(var _i8=0;_i80;}},{key:"dispose",value:function dispose(){var _this$hitPlane=this.hitPlane,geometry=_this$hitPlane.geometry,material=_this$hitPlane.material;geometry.dispose();material.dispose();this.geometry.dispose();this.material.dispose();}},{key:"offsetHeight",set:function set(offset){this.position.y=this.shadowHeight+offset;},get:function get(){return this.position.y-this.shadowHeight;}},{key:"show",set:function set(visible){this.goalOpacity=visible?MAX_OPACITY:0;}}]);return PlacementBox;}(Mesh);var assertContext=function assertContext(context){if(context==null){throw new Error('WebGL is not available!');}return context;};var getContext=function getContext(canvas,options){return assertContext(canvas.getContext('webgl',options)||canvas.getContext('experimental-webgl',options));};var applyExtensionCompatibility=function applyExtensionCompatibility(gl){var testShaders={'EXT_shader_texture_lod':"\n #extension GL_EXT_shader_texture_lod : enable\n precision mediump float;\n uniform sampler2D tex;\n void main() {\n gl_FragColor = texture2DLodEXT(tex, vec2(0.0, 0.0), 0.0);\n }"};function confirmExtension(gl,name){var shader=gl.createShader(gl.FRAGMENT_SHADER);gl.shaderSource(shader,testShaders[name]);gl.compileShader(shader);var status=gl.getShaderParameter(shader,gl.COMPILE_STATUS);gl.deleteShader(shader);return status;}var getExtension=gl.getExtension;gl.getExtension=function(name){var extension;if(testShaders[name]){extension=getExtension.call(gl,name);if(extension&&!confirmExtension(gl,name)){extension=null;}}else{extension=getExtension.call(gl,name);}return extension;};};var _a$6,_b$4,_c$1,_d$1,_e,_f,_g,_h,_j,_k,_l,_m,_o,_p,_q,_r,_s,_t,_u,_v,_w,_x$1,_y$1,_z$1,_0,_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12;var AR_SHADOW_INTENSITY=0.3;var ROTATION_RATE=1.5;var HIT_ANGLE_DEG=20;var INTRO_DAMPER_RATE=0.4;var SCALE_SNAP_HIGH=1.2;var SCALE_SNAP_LOW=1/SCALE_SNAP_HIGH;var ARStatus={NOT_PRESENTING:'not-presenting',SESSION_STARTED:'session-started',OBJECT_PLACED:'object-placed'};var $presentedScene=Symbol('presentedScene');var $placementBox=Symbol('placementBox');var $lastTick=Symbol('lastTick');var $turntableRotation=Symbol('turntableRotation');var $oldShadowIntensity=Symbol('oldShadowIntensity');var $oldBackground=Symbol('oldBackground');var $rafId=Symbol('rafId');var $currentSession=Symbol('currentSession');var $tick=Symbol('tick');var $refSpace=Symbol('refSpace');var $viewerRefSpace=Symbol('viewerRefSpace');var $frame=Symbol('frame');var $initialized=Symbol('initialized');var $initialModelToWorld=Symbol('initialModelToWorld');var $placementComplete=Symbol('placementComplete');var $initialHitSource=Symbol('hitTestSource');var $transientHitTestSource=Symbol('transiertHitTestSource');var $inputSource=Symbol('inputSource');var $isTranslating=Symbol('isTranslating');var $isRotating=Symbol('isRotating');var $isScaling=Symbol('isScaling');var $lastDragPosition=Symbol('lastDragPosition');var $lastScalar=Symbol('lastScalar');var $goalPosition=Symbol('goalPosition');var $goalYaw=Symbol('goalYaw');var $goalScale=Symbol('goalScale');var $xDamper=Symbol('xDamper');var $yDamper=Symbol('yDamper');var $zDamper=Symbol('zDamper');var $yawDamper=Symbol('yawDamper');var $scaleDamper=Symbol('scaleDamper');var $damperRate=Symbol('damperRate');var $resolveCleanup=Symbol('resolveCleanup');var $exitWebXRButtonContainer=Symbol('exitWebXRButtonContainer');var $onWebXRFrame=Symbol('onWebXRFrame');var $postSessionCleanup=Symbol('postSessionCleanup');var $updateCamera=Symbol('updateCamera');var $placeInitially=Symbol('placeInitially');var $getHitPoint=Symbol('getHitPoint');var $onSelectStart=Symbol('onSelectStart');var $onSelectEnd=Symbol('onSelect');var $onUpdateScene=Symbol('onUpdateScene');var $fingerSeparation=Symbol('fingerSeparation');var $processInput=Symbol('processInput');var $moveScene=Symbol('moveScene');var $onExitWebXRButtonContainerClick=Symbol('onExitWebXRButtonContainerClick');var vector3$1=new Vector3();var matrix4=new Matrix4();var hitPosition=new Vector3();var ARRenderer=/*#__PURE__*/function(_EventDispatcher2){_inherits(ARRenderer,_EventDispatcher2);var _super10=_createSuper(ARRenderer);function ARRenderer(renderer){var _this26;_classCallCheck(this,ARRenderer);_this26=_super10.call(this);_this26.renderer=renderer;_this26.camera=new PerspectiveCamera();_this26[_a$6]=null;_this26[_b$4]=null;_this26[_c$1]=null;_this26[_d$1]=null;_this26[_e]=null;_this26[_f]=null;_this26[_g]=null;_this26[_h]=null;_this26[_j]=null;_this26[_k]=null;_this26[_l]=null;_this26[_m]=null;_this26[_o]=null;_this26[_p]=null;_this26[_q]=null;_this26[_r]=null;_this26[_s]=false;_this26[_t]=new Matrix4();_this26[_u]=false;_this26[_v]=false;_this26[_w]=false;_this26[_x$1]=false;_this26[_y$1]=new Vector3();_this26[_z$1]=0;_this26[_0]=new Vector3();_this26[_1]=0;_this26[_2]=1;_this26[_3]=new Damper();_this26[_4]=new Damper();_this26[_5]=new Damper();_this26[_6]=new Damper();_this26[_7]=new Damper();_this26[_8]=1;_this26[_9]=function(){return _this26.stopPresenting();};_this26[_10]=function(){if(_this26[$placementBox]!=null&&_this26.isPresenting){_this26[$placementBox].dispose();_this26[$placementBox]=new PlacementBox(_this26[$presentedScene].model);}};_this26[_11]=function(event){var hitSource=_this26[$transientHitTestSource];if(hitSource==null){return;}var fingers=_this26[$frame].getHitTestResultsForTransientInput(hitSource);var scene=_this26[$presentedScene];var box=_this26[$placementBox];if(fingers.length===1){_this26[$inputSource]=event.inputSource;var axes=_this26[$inputSource].gamepad.axes;var _hitPosition=box.getHit(_this26[$presentedScene],axes[0],axes[1]);box.show=true;if(_hitPosition!=null){_this26[$isTranslating]=true;_this26[$lastDragPosition].copy(_hitPosition);}else{_this26[$isRotating]=true;_this26[$lastScalar]=axes[0];}}else if(fingers.length===2&&scene.canScale){box.show=true;_this26[$isScaling]=true;_this26[$lastScalar]=_this26[$fingerSeparation](fingers)/scene.scale.x;}};_this26[_12]=function(){_this26[$isTranslating]=false;_this26[$isRotating]=false;_this26[$isScaling]=false;_this26[$inputSource]=null;_this26[$goalPosition].y+=_this26[$placementBox].offsetHeight*_this26[$presentedScene].scale.x;_this26[$placementBox].show=false;};_this26.threeRenderer=renderer.threeRenderer;_this26.camera.matrixAutoUpdate=false;return _this26;}_createClass(ARRenderer,[{key:"resolveARSession",value:function(){var _resolveARSession=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee8(scene){var session,gl,waitForXRAnimationFrame,_session$renderState$,framebuffer,framebufferWidth,framebufferHeight,exitButton;return regeneratorRuntime.wrap(function _callee8$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:assertIsArCandidate();_context9.next=3;return navigator.xr.requestSession('immersive-ar',{requiredFeatures:['hit-test'],optionalFeatures:['dom-overlay'],domOverlay:{root:scene.element.shadowRoot.querySelector('div.annotation-container')}});case 3:session=_context9.sent;gl=assertContext(this.renderer.context3D);_context9.next=7;return gl.makeXRCompatible();case 7:session.updateRenderState({baseLayer:new XRWebGLLayer(session,gl,{alpha:true})});waitForXRAnimationFrame=new Promise(function(resolve,_reject){session.requestAnimationFrame(function(){return resolve();});});_context9.next=11;return waitForXRAnimationFrame;case 11:scene.element[$onResize](window.screen);_session$renderState$=session.renderState.baseLayer,framebuffer=_session$renderState$.framebuffer,framebufferWidth=_session$renderState$.framebufferWidth,framebufferHeight=_session$renderState$.framebufferHeight;this.threeRenderer.setFramebuffer(framebuffer);this.threeRenderer.setPixelRatio(1);this.threeRenderer.setSize(framebufferWidth,framebufferHeight,false);exitButton=scene.element.shadowRoot.querySelector('.slot.exit-webxr-ar-button');exitButton.classList.add('enabled');exitButton.addEventListener('click',this[$onExitWebXRButtonContainerClick]);this[$exitWebXRButtonContainer]=exitButton;return _context9.abrupt("return",session);case 21:case"end":return _context9.stop();}}},_callee8,this);}));function resolveARSession(_x14){return _resolveARSession.apply(this,arguments);}return resolveARSession;}()},{key:"supportsPresentation",value:function(){var _supportsPresentation=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee9(){return regeneratorRuntime.wrap(function _callee9$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:_context10.prev=0;assertIsArCandidate();_context10.next=4;return navigator.xr.isSessionSupported('immersive-ar');case 4:return _context10.abrupt("return",_context10.sent);case 7:_context10.prev=7;_context10.t0=_context10["catch"](0);return _context10.abrupt("return",false);case 10:case"end":return _context10.stop();}}},_callee9,null,[[0,7]]);}));function supportsPresentation(){return _supportsPresentation.apply(this,arguments);}return supportsPresentation;}()},{key:"present",value:function(){var _present=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee10(scene){var _this27=this;var waitForAnimationFrame,currentSession,radians,ray;return regeneratorRuntime.wrap(function _callee10$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:if(this.isPresenting){console.warn('Cannot present while a model is already presenting');}waitForAnimationFrame=new Promise(function(resolve,_reject){requestAnimationFrame(function(){return resolve();});});scene.model.setHotspotsVisibility(false);scene.isDirty=true;_context11.next=6;return waitForAnimationFrame;case 6:this[$presentedScene]=scene;_context11.next=9;return this.resolveARSession(scene);case 9:currentSession=_context11.sent;currentSession.addEventListener('end',function(){_this27[$postSessionCleanup]();},{once:true});_context11.next=13;return currentSession.requestReferenceSpace('local');case 13:this[$refSpace]=_context11.sent;_context11.next=16;return currentSession.requestReferenceSpace('viewer');case 16:this[$viewerRefSpace]=_context11.sent;scene.setCamera(this.camera);this[$initialized]=false;this[$damperRate]=INTRO_DAMPER_RATE;this[$turntableRotation]=scene.yaw;scene.yaw=0;this[$goalYaw]=0;this[$goalScale]=1;this[$oldBackground]=scene.background;scene.background=null;this[$oldShadowIntensity]=scene.shadowIntensity;scene.setShadowIntensity(0);scene.addEventListener('model-load',this[$onUpdateScene]);radians=HIT_ANGLE_DEG*Math.PI/180;ray=new XRRay(new DOMPoint(0,0,0),{x:0,y:-Math.sin(radians),z:-Math.cos(radians)});currentSession.requestHitTestSource({space:this[$viewerRefSpace],offsetRay:ray}).then(function(hitTestSource){_this27[$initialHitSource]=hitTestSource;});this[$currentSession]=currentSession;this[$placementBox]=new PlacementBox(scene.model);this[$placementComplete]=false;this[$lastTick]=performance.now();this[$tick]();case 37:case"end":return _context11.stop();}}},_callee10,this);}));function present(_x15){return _present.apply(this,arguments);}return present;}()},{key:"stopPresenting",value:function(){var _stopPresenting=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee11(){var _this28=this;var cleanupPromise;return regeneratorRuntime.wrap(function _callee11$(_context12){while(1){switch(_context12.prev=_context12.next){case 0:if(this.isPresenting){_context12.next=2;break;}return _context12.abrupt("return");case 2:cleanupPromise=new Promise(function(resolve){_this28[$resolveCleanup]=resolve;});_context12.prev=3;_context12.next=6;return this[$currentSession].end();case 6:_context12.next=8;return cleanupPromise;case 8:_context12.next=15;break;case 10:_context12.prev=10;_context12.t0=_context12["catch"](3);console.warn('Error while trying to end AR session');console.warn(_context12.t0);this[$postSessionCleanup]();case 15:case"end":return _context12.stop();}}},_callee11,this,[[3,10]]);}));function stopPresenting(){return _stopPresenting.apply(this,arguments);}return stopPresenting;}()},{key:(_a$6=$placementBox,_b$4=$lastTick,_c$1=$turntableRotation,_d$1=$oldShadowIntensity,_e=$oldBackground,_f=$rafId,_g=$currentSession,_h=$refSpace,_j=$viewerRefSpace,_k=$frame,_l=$initialHitSource,_m=$transientHitTestSource,_o=$inputSource,_p=$presentedScene,_q=$resolveCleanup,_r=$exitWebXRButtonContainer,_s=$initialized,_t=$initialModelToWorld,_u=$placementComplete,_v=$isTranslating,_w=$isRotating,_x$1=$isScaling,_y$1=$lastDragPosition,_z$1=$lastScalar,_0=$goalPosition,_1=$goalYaw,_2=$goalScale,_3=$xDamper,_4=$yDamper,_5=$zDamper,_6=$yawDamper,_7=$scaleDamper,_8=$damperRate,_9=$onExitWebXRButtonContainerClick,$postSessionCleanup),value:function value(){this.threeRenderer.setFramebuffer(null);var session=this[$currentSession];if(session!=null){session.removeEventListener('selectstart',this[$onSelectStart]);session.removeEventListener('selectend',this[$onSelectEnd]);session.cancelAnimationFrame(this[$rafId]);this[$currentSession]=null;}var scene=this[$presentedScene];if(scene!=null){var model=scene.model,element=scene.element;scene.setCamera(scene.camera);model.remove(this[$placementBox]);scene.position.set(0,0,0);scene.scale.set(1,1,1);model.setShadowScaleAndOffset(1,0);var yaw=this[$turntableRotation];if(yaw!=null){scene.yaw=yaw;}var intensity=this[$oldShadowIntensity];if(intensity!=null){scene.setShadowIntensity(intensity);}var background=this[$oldBackground];if(background!=null){scene.background=background;}scene.removeEventListener('model-load',this[$onUpdateScene]);model.orientHotspots(0);element.requestUpdate('cameraTarget');element[$onResize](element.getBoundingClientRect());}this.renderer.height=0;var exitButton=this[$exitWebXRButtonContainer];if(exitButton!=null){exitButton.classList.remove('enabled');exitButton.removeEventListener('click',this[$onExitWebXRButtonContainerClick]);this[$exitWebXRButtonContainer]=null;}var hitSource=this[$transientHitTestSource];if(hitSource!=null){hitSource.cancel();this[$transientHitTestSource]=null;}var hitSourceInitial=this[$initialHitSource];if(hitSourceInitial!=null){hitSourceInitial.cancel();this[$initialHitSource]=null;}if(this[$placementBox]!=null){this[$placementBox].dispose();this[$placementBox]=null;}this[$lastTick]=null;this[$turntableRotation]=null;this[$oldShadowIntensity]=null;this[$oldBackground]=null;this[$rafId]=null;this[$refSpace]=null;this[$presentedScene]=null;this[$viewerRefSpace]=null;this[$frame]=null;this[$inputSource]=null;if(this[$resolveCleanup]!=null){this[$resolveCleanup]();}this.dispatchEvent({type:'status',status:ARStatus.NOT_PRESENTING});}},{key:"updateTarget",value:function updateTarget(){var scene=this[$presentedScene];if(scene!=null){var _target2=scene.getTarget();scene.setTarget(_target2.x,scene.model.boundingBox.min.y,_target2.z);}}},{key:(_10=$onUpdateScene,$updateCamera),value:function value(view){var camera=this.camera;var cameraMatrix=camera.matrix;cameraMatrix.fromArray(view.transform.matrix);camera.updateMatrixWorld(true);camera.position.setFromMatrixPosition(cameraMatrix);if(this[$initialHitSource]!=null){var _this$$presentedScene=this[$presentedScene],position=_this$$presentedScene.position,model=_this$$presentedScene.model;var radius=model.idealCameraDistance;camera.getWorldDirection(position);position.multiplyScalar(radius);position.add(camera.position);}if(!this[$initialized]){camera.projectionMatrix.fromArray(view.projectionMatrix);camera.projectionMatrixInverse.getInverse(camera.projectionMatrix);var _camera$position=camera.position,x=_camera$position.x,z=_camera$position.z;var scene=this[$presentedScene];scene.pointTowards(x,z);scene.model.updateMatrixWorld(true);this[$goalYaw]=scene.yaw;this[$initialModelToWorld].copy(scene.model.matrixWorld);scene.model.setHotspotsVisibility(true);this[$initialized]=true;this.dispatchEvent({type:'status',status:ARStatus.SESSION_STARTED});}this[$presentedScene].model.orientHotspots(Math.atan2(cameraMatrix.elements[1],cameraMatrix.elements[5]));}},{key:$placeInitially,value:function value(frame){var _this29=this;var hitSource=this[$initialHitSource];if(hitSource==null){return;}var hitTestResults=frame.getHitTestResults(hitSource);if(hitTestResults.length==0){return;}var hit=hitTestResults[0];var hitMatrix=this[$getHitPoint](hit);if(hitMatrix==null){return;}this.placeModel(hitMatrix);hitSource.cancel();this[$initialHitSource]=null;var session=frame.session;session.addEventListener('selectstart',this[$onSelectStart]);session.addEventListener('selectend',this[$onSelectEnd]);session.requestHitTestSourceForTransientInput({profile:'generic-touchscreen'}).then(function(hitTestSource){_this29[$transientHitTestSource]=hitTestSource;});}},{key:$getHitPoint,value:function value(hitResult){var pose=hitResult.getPose(this[$refSpace]);if(pose==null){return null;}var hitMatrix=matrix4.fromArray(pose.transform.matrix);return hitMatrix.elements[5]>0.75?hitPosition.setFromMatrixPosition(hitMatrix):null;}},{key:"placeModel",value:function placeModel(hit){var scene=this[$presentedScene];var model=scene.model;var _model$boundingBox=model.boundingBox,min=_model$boundingBox.min,max=_model$boundingBox.max;this[$placementBox].show=true;var goal=this[$goalPosition];goal.copy(hit);var floor=hit.y;var origin=this.camera.position.clone();var direction=hit.clone().sub(origin).normalize();origin.sub(direction.multiplyScalar(model.idealCameraDistance));var ray=new Ray(origin,direction.normalize());var modelToWorld=this[$initialModelToWorld];var modelPosition=new Vector3().setFromMatrixPosition(modelToWorld).add(hit);modelToWorld.setPosition(modelPosition);var world2Model=new Matrix4().getInverse(modelToWorld);ray.applyMatrix4(world2Model);max.y+=10;ray.intersectBox(model.boundingBox,modelPosition);max.y-=10;if(modelPosition!=null){modelPosition.applyMatrix4(modelToWorld);goal.add(hit).sub(modelPosition);}var target=scene.getTarget();scene.setTarget(target.x,min.y,target.z);goal.y=floor;this.dispatchEvent({type:'status',status:ARStatus.OBJECT_PLACED});}},{key:(_11=$onSelectStart,_12=$onSelectEnd,$fingerSeparation),value:function value(fingers){var fingerOne=fingers[0].inputSource.gamepad.axes;var fingerTwo=fingers[1].inputSource.gamepad.axes;var deltaX=fingerTwo[0]-fingerOne[0];var deltaY=fingerTwo[1]-fingerOne[1];return Math.sqrt(deltaX*deltaX+deltaY*deltaY);}},{key:$processInput,value:function value(frame){var _this30=this;var hitSource=this[$transientHitTestSource];if(hitSource==null){return;}if(!this[$isTranslating]&&!this[$isScaling]&&!this[$isRotating]){return;}var fingers=frame.getHitTestResultsForTransientInput(hitSource);var scene=this[$presentedScene];var scale=scene.scale.x;if(this[$isScaling]){if(fingers.length<2){this[$isScaling]=false;}else{var separation=this[$fingerSeparation](fingers);var _scale2=separation/this[$lastScalar];this[$goalScale]=_scale2SCALE_SNAP_LOW?1:_scale2;}return;}else if(fingers.length===2&&scene.canScale){this[$isTranslating]=false;this[$isRotating]=false;this[$isScaling]=true;this[$lastScalar]=this[$fingerSeparation](fingers)/scale;return;}if(this[$isRotating]){var thisDragX=this[$inputSource].gamepad.axes[0];this[$goalYaw]+=(thisDragX-this[$lastScalar])*ROTATION_RATE;this[$lastScalar]=thisDragX;}else if(this[$isTranslating]){fingers.forEach(function(finger){if(finger.inputSource!==_this30[$inputSource]||finger.results.length<1){return;}var hit=_this30[$getHitPoint](finger.results[0]);if(hit==null){return;}_this30[$goalPosition].sub(_this30[$lastDragPosition]);var offset=hit.y-_this30[$lastDragPosition].y;if(offset<0){_this30[$placementBox].offsetHeight=offset/scale;_this30[$presentedScene].model.setShadowScaleAndOffset(scale,offset);var cameraPosition=vector3$1.copy(_this30.camera.position);var alpha=-offset/(cameraPosition.y-hit.y);cameraPosition.multiplyScalar(alpha);hit.multiplyScalar(1-alpha).add(cameraPosition);}_this30[$goalPosition].add(hit);_this30[$lastDragPosition].copy(hit);});}}},{key:$moveScene,value:function value(delta){var scene=this[$presentedScene];var model=scene.model,position=scene.position,yaw=scene.yaw;var radius=model.idealCameraDistance;var goal=this[$goalPosition];var oldScale=scene.scale.x;var box=this[$placementBox];if(this[$initialHitSource]==null&&(!goal.equals(position)||this[$goalScale]!==oldScale)){var x=position.x,y=position.y,z=position.z;delta*=this[$damperRate];x=this[$xDamper].update(x,goal.x,delta,radius);y=this[$yDamper].update(y,goal.y,delta,radius);z=this[$zDamper].update(z,goal.z,delta,radius);position.set(x,y,z);var newScale=this[$scaleDamper].update(oldScale,this[$goalScale],delta,1);scene.scale.set(newScale,newScale,newScale);if(!this[$isTranslating]){var offset=goal.y-y;if(this[$placementComplete]){box.offsetHeight=offset/newScale;model.setShadowScaleAndOffset(newScale,offset);}else if(offset===0){this[$placementComplete]=true;box.show=false;scene.setShadowIntensity(AR_SHADOW_INTENSITY);this[$damperRate]=1;}}}box.updateOpacity(delta);scene.updateTarget(delta);scene.updateMatrixWorld(true);scene.yaw=this[$yawDamper].update(yaw,this[$goalYaw],delta,Math.PI);}},{key:$tick,value:function value(){var _this31=this;this[$rafId]=this[$currentSession].requestAnimationFrame(function(time,frame){return _this31[$onWebXRFrame](time,frame);});}},{key:$onWebXRFrame,value:function value(time,frame){this[$frame]=frame;var pose=frame.getViewerPose(this[$refSpace]);this[$tick]();var scene=this[$presentedScene];if(pose==null||scene==null){return;}this[$updateCamera](pose.views[0]);this[$placeInitially](frame);this[$processInput](frame);var delta=time-this[$lastTick];this[$moveScene](delta);this.renderer.preRender(scene,time,delta);this[$lastTick]=time;this.threeRenderer.render(scene,this.camera);}},{key:"presentedScene",get:function get(){return this[$presentedScene];}},{key:"isPresenting",get:function get(){return this[$presentedScene]!=null;}}]);return ARRenderer;}(EventDispatcher);var Debugger=/*#__PURE__*/function(){function Debugger(renderer){_classCallCheck(this,Debugger);renderer.threeRenderer.debug={checkShaderErrors:true};Promise.resolve().then(function(){self.dispatchEvent(new CustomEvent('model-viewer-renderer-debug',{detail:{renderer:renderer,THREE:{ShaderMaterial:ShaderMaterial,Texture:Texture,Mesh:Mesh,Scene:Scene,PlaneBufferGeometry:PlaneBufferGeometry,OrthographicCamera:OrthographicCamera,WebGLRenderTarget:WebGLRenderTarget}}}));});}_createClass(Debugger,[{key:"addScene",value:function addScene(scene){self.dispatchEvent(new CustomEvent('model-viewer-scene-added-debug',{detail:{scene:scene}}));}},{key:"removeScene",value:function removeScene(scene){self.dispatchEvent(new CustomEvent('model-viewer-scene-removed-debug',{detail:{scene:scene}}));}}]);return Debugger;}();var $threeGLTF=Symbol('threeGLTF');var $gltf=Symbol('gltf');var $gltfElementMap=Symbol('gltfElementMap');var $threeObjectMap=Symbol('threeObjectMap');var $parallelTraverseThreeScene=Symbol('parallelTraverseThreeScene');var $correlateOriginalThreeGLTF=Symbol('correlateOriginalThreeGLTF');var $correlateCloneThreeGLTF=Symbol('correlateCloneThreeGLTF');/** * The Three.js GLTFLoader provides us with an in-memory representation * of a glTF in terms of Three.js constructs. It also provides us with a copy * of the deserialized glTF without any Three.js decoration, and a mapping of * glTF elements to their corresponding Three.js constructs. * * A CorrelatedSceneGraph exposes a synchronously available mapping of glTF * element references to their corresponding Three.js constructs. */var CorrelatedSceneGraph=/*#__PURE__*/function(){function CorrelatedSceneGraph(threeGLTF,gltf,threeObjectMap,gltfElementMap){_classCallCheck(this,CorrelatedSceneGraph);this[$threeGLTF]=threeGLTF;this[$gltf]=gltf;this[$gltfElementMap]=gltfElementMap;this[$threeObjectMap]=threeObjectMap;}/** * Produce a CorrelatedSceneGraph from a naturally generated Three.js GLTF. * Such GLTFs are produced by Three.js' GLTFLoader, and contain cached * details that expedite the correlation step. * * If a CorrelatedSceneGraph is provided as the second argument, re-correlates * a cloned Three.js GLTF with a clone of the glTF hierarchy used to produce * the upstream Three.js GLTF that the clone was created from. The result * CorrelatedSceneGraph is representative of the cloned hierarchy. */_createClass(CorrelatedSceneGraph,[{key:"threeGLTF",/** * The source Three.js GLTF result given to us by a Three.js GLTFLoader. */get:function get(){return this[$threeGLTF];}/** * The in-memory deserialized source glTF. */},{key:"gltf",get:function get(){return this[$gltf];}/** * A Map of glTF element references to arrays of corresponding Three.js * object references. Three.js objects are kept in arrays to account for * cases where more than one Three.js object corresponds to a single glTF * element. */},{key:"gltfElementMap",get:function get(){return this[$gltfElementMap];}/** * A map of individual Three.js objects to corresponding elements in the * source glTF. */},{key:"threeObjectMap",get:function get(){return this[$threeObjectMap];}}],[{key:"from",value:function from(threeGLTF,upstreamCorrelatedSceneGraph){if(upstreamCorrelatedSceneGraph!=null){return this[$correlateCloneThreeGLTF](threeGLTF,upstreamCorrelatedSceneGraph);}else{return this[$correlateOriginalThreeGLTF](threeGLTF);}}},{key:$correlateOriginalThreeGLTF,value:function value(threeGLTF){var gltf=threeGLTF.parser.json;var associations=threeGLTF.parser.associations;var gltfElementMap=new Map();// NOTE: IE11 does not have Map iterator methods associations.forEach(function(gltfElementReference,threeObject){// Note: GLTFLoader creates a "default" material that has no corresponding // glTF element in the case that no materials are specified in the source // glTF. This means that for basic models without any of their own // materials, we might accidentally try to present a configurable glTF // material that doesn't exist. It might be valuable to make this default // material configurable in the future, but for now we ignore it. if(gltfElementReference==null){return;}var type=gltfElementReference.type,index=gltfElementReference.index;var elementArray=gltf[type]||[];var gltfElement=elementArray[index];if(gltfElement==null){// TODO: Maybe throw here... return;}var threeObjects=gltfElementMap.get(gltfElement);if(threeObjects==null){threeObjects=new Set();gltfElementMap.set(gltfElement,threeObjects);}threeObjects.add(threeObject);});return new CorrelatedSceneGraph(threeGLTF,gltf,associations,gltfElementMap);}/** * Transfers the association between a raw glTF and a Three.js scene graph * to a clone of the Three.js scene graph, resolved as a new * CorrelatedsceneGraph instance. */},{key:$correlateCloneThreeGLTF,value:function value(cloneThreeGLTF,upstreamCorrelatedSceneGraph){var originalThreeGLTF=upstreamCorrelatedSceneGraph.threeGLTF;var originalGLTF=upstreamCorrelatedSceneGraph.gltf;var cloneGLTF=JSON.parse(JSON.stringify(originalGLTF));var cloneThreeObjectMap=new Map();var cloneGLTFELementMap=new Map();for(var _i9=0;_i9',alphaChunk);}:function(shader){shader.fragmentShader=shader.fragmentShader.replace('#include ',alphaChunk);oldOnBeforeCompile(shader,undefined);};clone.shadowSide=FrontSide;if(clone.transparent){clone.depthWrite=false;}if(!clone.alphaTest&&!clone.transparent){clone.alphaTest=-0.5;}sourceUUIDToClonedMaterial.set(material.uuid,clone);return clone;}},{key:"correlatedSceneGraph",get:function get(){return this[$preparedGLTF][$correlatedSceneGraph];}}],[{key:$prepare,value:function value(source){var prepared=_get(_getPrototypeOf(ModelViewerGLTFInstance),$prepare,this).call(this,source);if(prepared[$correlatedSceneGraph]==null){prepared[$correlatedSceneGraph]=CorrelatedSceneGraph.from(prepared);}var scene=prepared.scene;var meshesToDuplicate=[];scene.traverse(function(node){node.renderOrder=1000;node.frustumCulled=false;if(!node.name){node.name=node.uuid;}if(!node.isMesh){return;}node.castShadow=true;var mesh=node;var transparent=false;var materials=Array.isArray(mesh.material)?mesh.material:[mesh.material];materials.forEach(function(material){if(material.isMeshStandardMaterial){if(material.transparent&&material.side===DoubleSide){transparent=true;material.side=FrontSide;}Renderer.singleton.roughnessMipmapper.generateMipmaps(material);}});if(transparent){meshesToDuplicate.push(mesh);}});for(var _i12=0,_meshesToDuplicate=meshesToDuplicate;_i12<_meshesToDuplicate.length;_i12++){var mesh=_meshesToDuplicate[_i12];var materials=Array.isArray(mesh.material)?mesh.material:[mesh.material];var duplicateMaterials=materials.map(function(material){var backMaterial=material.clone();backMaterial.side=BackSide;return backMaterial;});var duplicateMaterial=Array.isArray(mesh.material)?duplicateMaterials:duplicateMaterials[0];var meshBack=new Mesh(mesh.geometry,duplicateMaterial);meshBack.renderOrder=-1;mesh.add(meshBack);}return prepared;}}]);return ModelViewerGLTFInstance;}(GLTFInstance);/** * @author Nikos M. / https://github.com/foo123/ */ // https://github.com/mrdoob/three.js/issues/5552 // http://en.wikipedia.org/wiki/RGBE_image_format var RGBELoader=function RGBELoader(manager){DataTextureLoader.call(this,manager);this.type=UnsignedByteType;};RGBELoader.prototype=Object.assign(Object.create(DataTextureLoader.prototype),{constructor:RGBELoader,// adapted from http://www.graphics.cornell.edu/~bjw/rgbe.html parse:function parse(buffer){var/* return codes for rgbe routines */ //RGBE_RETURN_SUCCESS = 0, RGBE_RETURN_FAILURE=-1,/* default error routine. change this to change error handling */rgbe_read_error=1,rgbe_write_error=2,rgbe_format_error=3,rgbe_memory_error=4,rgbe_error=function rgbe_error(rgbe_error_code,msg){switch(rgbe_error_code){case rgbe_read_error:console.error("RGBELoader Read Error: "+(msg||''));break;case rgbe_write_error:console.error("RGBELoader Write Error: "+(msg||''));break;case rgbe_format_error:console.error("RGBELoader Bad File Format: "+(msg||''));break;default:case rgbe_memory_error:console.error("RGBELoader: Error: "+(msg||''));}return RGBE_RETURN_FAILURE;},/* offsets to red, green, and blue components in a data (float) pixel */ //RGBE_DATA_RED = 0, //RGBE_DATA_GREEN = 1, //RGBE_DATA_BLUE = 2, /* number of floats per pixel, use 4 since stored in rgba image format */ //RGBE_DATA_SIZE = 4, /* flags indicating which fields in an rgbe_header_info are valid */RGBE_VALID_PROGRAMTYPE=1,RGBE_VALID_FORMAT=2,RGBE_VALID_DIMENSIONS=4,NEWLINE="\n",fgets=function fgets(buffer,lineLimit,consume){lineLimit=!lineLimit?1024:lineLimit;var p=buffer.pos,i=-1,len=0,s='',chunkSize=128,chunk=String.fromCharCode.apply(null,new Uint16Array(buffer.subarray(p,p+chunkSize)));while(0>(i=chunk.indexOf(NEWLINE))&&len=0; i--) { byteCode = m.charCodeAt(i); if (byteCode > 0x7f && byteCode <= 0x7ff) byteLen++; else if (byteCode > 0x7ff && byteCode <= 0xffff) byteLen += 2; if (byteCode >= 0xDC00 && byteCode <= 0xDFFF) i--; //trail surrogate }*/if(false!==consume)buffer.pos+=len+i+1;return s+chunk.slice(0,i);}return false;},/* minimal header reading. modify if you want to parse more information */RGBE_ReadHeader=function RGBE_ReadHeader(buffer){var line,match,// regexes to parse header info fields magic_token_re=/^#\?(\S+)$/,gamma_re=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,exposure_re=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,format_re=/^\s*FORMAT=(\S+)\s*$/,dimensions_re=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,// RGBE format header struct header={valid:0,/* indicate which fields are valid */string:'',/* the actual header string */comments:'',/* comments found in header */programtype:'RGBE',/* listed at beginning of file to identify it after "#?". defaults to "RGBE" */format:'',/* RGBE format, default 32-bit_rle_rgbe */gamma:1.0,/* image has already been gamma corrected with given gamma. defaults to 1.0 (no correction) */exposure:1.0,/* a value of 1.0 in an image corresponds to watts/steradian/m^2. defaults to 1.0 */width:0,height:0/* image dimensions, width/height */};if(buffer.pos>=buffer.byteLength||!(line=fgets(buffer))){return rgbe_error(rgbe_read_error,"no header found");}/* if you want to require the magic token then uncomment the next line */if(!(match=line.match(magic_token_re))){return rgbe_error(rgbe_format_error,"bad initial token");}header.valid|=RGBE_VALID_PROGRAMTYPE;header.programtype=match[1];header.string+=line+"\n";while(true){line=fgets(buffer);if(false===line)break;header.string+=line+"\n";if('#'===line.charAt(0)){header.comments+=line+"\n";continue;// comment line }if(match=line.match(gamma_re)){header.gamma=parseFloat(match[1],10);}if(match=line.match(exposure_re)){header.exposure=parseFloat(match[1],10);}if(match=line.match(format_re)){header.valid|=RGBE_VALID_FORMAT;header.format=match[1];//'32-bit_rle_rgbe'; }if(match=line.match(dimensions_re)){header.valid|=RGBE_VALID_DIMENSIONS;header.height=parseInt(match[1],10);header.width=parseInt(match[2],10);}if(header.valid&RGBE_VALID_FORMAT&&header.valid&RGBE_VALID_DIMENSIONS)break;}if(!(header.valid&RGBE_VALID_FORMAT)){return rgbe_error(rgbe_format_error,"missing format specifier");}if(!(header.valid&RGBE_VALID_DIMENSIONS)){return rgbe_error(rgbe_format_error,"missing image size specifier");}return header;},RGBE_ReadPixels_RLE=function RGBE_ReadPixels_RLE(buffer,w,h){var data_rgba,offset,pos,count,byteValue,scanline_buffer,ptr,ptr_end,i,l,off,isEncodedRun,scanline_width=w,num_scanlines=h,rgbeStart;if(// run length encoding is not allowed so read flat scanline_width<8||scanline_width>0x7fff||// this file is not run length encoded 2!==buffer[0]||2!==buffer[1]||buffer[2]&0x80){// return the flat buffer return new Uint8Array(buffer);}if(scanline_width!==(buffer[2]<<8|buffer[3])){return rgbe_error(rgbe_format_error,"wrong scanline width");}data_rgba=new Uint8Array(4*w*h);if(!data_rgba.length){return rgbe_error(rgbe_memory_error,"unable to allocate buffer space");}offset=0;pos=0;ptr_end=4*scanline_width;rgbeStart=new Uint8Array(4);scanline_buffer=new Uint8Array(ptr_end);// read in each successive scanline while(num_scanlines>0&&posbuffer.byteLength){return rgbe_error(rgbe_read_error);}rgbeStart[0]=buffer[pos++];rgbeStart[1]=buffer[pos++];rgbeStart[2]=buffer[pos++];rgbeStart[3]=buffer[pos++];if(2!=rgbeStart[0]||2!=rgbeStart[1]||(rgbeStart[2]<<8|rgbeStart[3])!=scanline_width){return rgbe_error(rgbe_format_error,"bad rgbe scanline format");}// read each of the four channels for the scanline into the buffer // first red, then green, then blue, then exponent ptr=0;while(ptr128;if(isEncodedRun)count-=128;if(0===count||ptr+count>ptr_end){return rgbe_error(rgbe_format_error,"bad scanline data");}if(isEncodedRun){// a (encoded) run of the same value byteValue=buffer[pos++];for(i=0;i>16&0x8000;/* Get the sign */var m=x>>12&0x07ff;/* Keep one extra bit for rounding */var e=x>>23&0xff;/* Using int is faster here */ /* If zero, or denormal, or exponent underflows too much for a denormal * half, return signed zero. */if(e<103)return bits;/* If NaN, return NaN. If Inf or exponent overflow, return Inf. */if(e>142){bits|=0x7c00;/* If exponent was 0xff and one mantissa bit was set, it means NaN, * not Inf, so make sure we set one mantissa bit too. */bits|=(e==255?0:1)&&x&0x007fffff;return bits;}/* If exponent underflows but not too much, return a denormal */if(e<113){m|=0x0800;/* Extra rounding may overflow and set mantissa to 0 and exponent * to 1, which is OK. */bits|=(m>>114-e)+(m>>113-e&1);return bits;}bits|=e-112<<10|m>>1;/* Extra rounding. An overflow will set mantissa to 0 and increment * the exponent, which is OK. */bits+=m&1;return bits;}return function(sourceArray,sourceOffset,destArray,destOffset){var e=sourceArray[sourceOffset+3];var scale=Math.pow(2.0,e-128.0)/255.0;destArray[destOffset+0]=toHalf(sourceArray[sourceOffset+0]*scale);destArray[destOffset+1]=toHalf(sourceArray[sourceOffset+1]*scale);destArray[destOffset+2]=toHalf(sourceArray[sourceOffset+2]*scale);};}();var byteArray=new Uint8Array(buffer);byteArray.pos=0;var rgbe_header_info=RGBE_ReadHeader(byteArray);if(RGBE_RETURN_FAILURE!==rgbe_header_info){var w=rgbe_header_info.width,h=rgbe_header_info.height,image_rgba_data=RGBE_ReadPixels_RLE(byteArray.subarray(byteArray.pos),w,h);if(RGBE_RETURN_FAILURE!==image_rgba_data){switch(this.type){case UnsignedByteType:var data=image_rgba_data;var format=RGBEFormat;// handled as THREE.RGBAFormat in shaders var type=UnsignedByteType;break;case FloatType:var numElements=image_rgba_data.length/4*3;var floatArray=new Float32Array(numElements);for(var j=0;j1&&_args12[1]!==undefined?_args12[1]:function(){};_context13.prev=1;this[$PMREMGenerator].compileEquirectangularShader();isHDR=HDR_FILE_RE.test(url);_loader=isHDR?hdrLoader:ldrLoader;_context13.next=7;return new Promise(function(resolve,reject){return _loader.load(url,resolve,function(event){progressCallback(event.loaded/event.total*0.9);},reject);});case 7:texture=_context13.sent;progressCallback(1.0);this[$addMetadata](texture,url,'Equirectangular');if(isHDR){texture.encoding=RGBEEncoding;texture.minFilter=NearestFilter;texture.magFilter=NearestFilter;texture.flipY=true;}else{texture.encoding=GammaEncoding;}return _context13.abrupt("return",texture);case 12:_context13.prev=12;if(progressCallback){progressCallback(1);}return _context13.finish(12);case 15:case"end":return _context13.stop();}}},_callee12,this,[[1,,12,15]]);}));function load(_x16){return _load2.apply(this,arguments);}return load;}()},{key:"loadEquirectAsCubeUV",value:function(){var _loadEquirectAsCubeUV=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee13(url){var progressCallback,equirect,cubeUV,_args13=arguments;return regeneratorRuntime.wrap(function _callee13$(_context14){while(1){switch(_context14.prev=_context14.next){case 0:progressCallback=_args13.length>1&&_args13[1]!==undefined?_args13[1]:function(){};equirect=null;_context14.prev=2;_context14.next=5;return this.load(url,progressCallback);case 5:equirect=_context14.sent;cubeUV=this[$PMREMGenerator].fromEquirectangular(equirect);this[$addMetadata](cubeUV.texture,url,'CubeUV');return _context14.abrupt("return",cubeUV);case 9:_context14.prev=9;if(equirect!=null){equirect.dispose();}return _context14.finish(9);case 12:case"end":return _context14.stop();}}},_callee13,this,[[2,,9,12]]);}));function loadEquirectAsCubeUV(_x17){return _loadEquirectAsCubeUV.apply(this,arguments);}return loadEquirectAsCubeUV;}()},{key:"generateEnvironmentMapAndSkybox",value:function(){var _generateEnvironmentMapAndSkybox=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee14(){var skyboxUrl,environmentMapUrl,options,progressTracker,updateGenerationProgress,skyboxLoads,environmentMapLoads,_yield$Promise$all,_yield$Promise$all2,environmentMap,skybox,_args14=arguments;return regeneratorRuntime.wrap(function _callee14$(_context15){while(1){switch(_context15.prev=_context15.next){case 0:skyboxUrl=_args14.length>0&&_args14[0]!==undefined?_args14[0]:null;environmentMapUrl=_args14.length>1&&_args14[1]!==undefined?_args14[1]:null;options=_args14.length>2&&_args14[2]!==undefined?_args14[2]:{};progressTracker=options.progressTracker;updateGenerationProgress=progressTracker!=null?progressTracker.beginActivity():function(){};_context15.prev=5;skyboxLoads=Promise.resolve(null);if(!!skyboxUrl){skyboxLoads=this[$loadEnvironmentMapFromUrl](skyboxUrl,progressTracker);}if(!!environmentMapUrl){environmentMapLoads=this[$loadEnvironmentMapFromUrl](environmentMapUrl,progressTracker);}else if(!!skyboxUrl){environmentMapLoads=skyboxLoads;}else{environmentMapLoads=this[$loadGeneratedEnvironmentMap]();}_context15.next=11;return Promise.all([environmentMapLoads,skyboxLoads]);case 11:_yield$Promise$all=_context15.sent;_yield$Promise$all2=_slicedToArray(_yield$Promise$all,2);environmentMap=_yield$Promise$all2[0];skybox=_yield$Promise$all2[1];if(!(environmentMap==null)){_context15.next=17;break;}throw new Error('Failed to load environment map.');case 17:environmentMap=environmentMap;this[$addMetadata](environmentMap.texture,environmentMapUrl,'PMREM');if(skybox!=null){this[$addMetadata](skybox.texture,skyboxUrl,'PMREM');}return _context15.abrupt("return",{environmentMap:environmentMap,skybox:skybox});case 21:_context15.prev=21;updateGenerationProgress(1.0);return _context15.finish(21);case 24:case"end":return _context15.stop();}}},_callee14,this,[[5,,21,24]]);}));function generateEnvironmentMapAndSkybox(){return _generateEnvironmentMapAndSkybox.apply(this,arguments);}return generateEnvironmentMapAndSkybox;}()},{key:(_a$7=$generatedEnvironmentMap,_b$5=$environmentMapCache,$addMetadata),value:function value(texture,url,mapping){if(texture==null){return;}texture.userData=Object.assign(Object.assign({},userData),{url:url,mapping:mapping});}},{key:$loadEnvironmentMapFromUrl,value:function value(url,progressTracker){if(!this[$environmentMapCache].has(url)){var progressCallback=progressTracker?progressTracker.beginActivity():function(){};var environmentMapLoads=this.loadEquirectAsCubeUV(url,progressCallback);this[$environmentMapCache].set(url,environmentMapLoads);}return this[$environmentMapCache].get(url);}},{key:$loadGeneratedEnvironmentMap,value:function value(){if(this[$generatedEnvironmentMap]==null){var defaultScene=new EnvironmentScene();this[$generatedEnvironmentMap]=this[$PMREMGenerator].fromScene(defaultScene,GENERATED_SIGMA);defaultScene.dispose();}return Promise.resolve(this[$generatedEnvironmentMap]);}},{key:"dispose",value:function(){var _dispose=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee15(){var allTargetsLoad,_i13,_allTargetsLoad,targetLoads,_target3;return regeneratorRuntime.wrap(function _callee15$(_context16){while(1){switch(_context16.prev=_context16.next){case 0:allTargetsLoad=[];this[$environmentMapCache].forEach(function(targetLoads){allTargetsLoad.push(targetLoads);});this[$environmentMapCache].clear();_i13=0,_allTargetsLoad=allTargetsLoad;case 4:if(!(_i13<_allTargetsLoad.length)){_context16.next=18;break;}targetLoads=_allTargetsLoad[_i13];_context16.prev=6;_context16.next=9;return targetLoads;case 9:_target3=_context16.sent;_target3.dispose();_context16.next=15;break;case 13:_context16.prev=13;_context16.t0=_context16["catch"](6);case 15:_i13++;_context16.next=4;break;case 18:if(this[$generatedEnvironmentMap]!=null){this[$generatedEnvironmentMap].dispose();this[$generatedEnvironmentMap]=null;}case 19:case"end":return _context16.stop();}}},_callee15,this,[[6,13]]);}));function dispose(){return _dispose.apply(this,arguments);}return dispose;}()},{key:"pmremGenerator",get:function get(){return this[$PMREMGenerator];}}]);return TextureUtils;}(EventDispatcher);var _a$8,_b$6;var DURATION_DECAY=0.2;var LOW_FRAME_DURATION_MS=18;var HIGH_FRAME_DURATION_MS=26;var MAX_AVG_CHANGE_MS=2;var SCALE_STEP=0.79;var DEFAULT_MIN_SCALE=0.5;var $onWebGLContextLost=Symbol('onWebGLContextLost');var $webGLContextLostHandler=Symbol('webGLContextLostHandler');var $singleton=Symbol('singleton');var Renderer=/*#__PURE__*/function(_EventDispatcher4){_inherits(Renderer,_EventDispatcher4);var _super14=_createSuper(Renderer);function Renderer(options){var _this35;_classCallCheck(this,Renderer);_this35=_super14.call(this);_this35.loader=new CachingGLTFLoader(ModelViewerGLTFInstance);_this35.width=0;_this35.height=0;_this35.dpr=1;_this35.minScale=DEFAULT_MIN_SCALE;_this35.debugger=null;_this35.scenes=new Set();_this35.multipleScenesVisible=false;_this35.scale=1;_this35.avgFrameDuration=(HIGH_FRAME_DURATION_MS+LOW_FRAME_DURATION_MS)/2;_this35[_b$6]=function(event){return _this35[$onWebGLContextLost](event);};var webGlOptions={alpha:true,antialias:true,powerPreference:'high-performance',preserveDrawingBuffer:true};_this35.dpr=resolveDpr();_this35.canvasElement=document.createElement('canvas');_this35.canvasElement.id='webgl-canvas';_this35.canvas3D=_this35.canvasElement;_this35.canvas3D.addEventListener('webglcontextlost',_this35[$webGLContextLostHandler]);try{_this35.context3D=getContext(_this35.canvas3D,webGlOptions);applyExtensionCompatibility(_this35.context3D);_this35.threeRenderer=new WebGLRenderer({canvas:_this35.canvas3D,context:_this35.context3D});_this35.threeRenderer.autoClear=true;_this35.threeRenderer.outputEncoding=GammaEncoding;_this35.threeRenderer.gammaFactor=2.2;_this35.threeRenderer.physicallyCorrectLights=true;_this35.threeRenderer.setPixelRatio(1);_this35.threeRenderer.shadowMap.enabled=true;_this35.threeRenderer.shadowMap.type=PCFSoftShadowMap;_this35.threeRenderer.shadowMap.autoUpdate=false;_this35.debugger=options!=null&&!!options.debug?new Debugger(_assertThisInitialized(_this35)):null;_this35.threeRenderer.debug={checkShaderErrors:!!_this35.debugger};_this35.threeRenderer.toneMapping=ACESFilmicToneMapping;}catch(error){_this35.context3D=null;console.warn(error);}_this35.arRenderer=new ARRenderer(_assertThisInitialized(_this35));_this35.textureUtils=_this35.canRender?new TextureUtils(_this35.threeRenderer):null;_this35.roughnessMipmapper=new RoughnessMipmapper(_this35.threeRenderer);_this35.updateRendererSize();_this35.lastTick=performance.now();_this35.avgFrameDuration=0;return _this35;}_createClass(Renderer,[{key:"updateRendererSize",value:function updateRendererSize(){var dpr=resolveDpr();if(dpr!==this.dpr){var _iterator5=_createForOfIteratorHelper(this.scenes),_step5;try{for(_iterator5.s();!(_step5=_iterator5.n()).done;){var scene=_step5.value;var element=scene.element;element[$updateSize](element.getBoundingClientRect());}}catch(err){_iterator5.e(err);}finally{_iterator5.f();}}var width=0;var height=0;var _iterator6=_createForOfIteratorHelper(this.scenes),_step6;try{for(_iterator6.s();!(_step6=_iterator6.n()).done;){var _scene=_step6.value;width=Math.max(width,_scene.width);height=Math.max(height,_scene.height);}}catch(err){_iterator6.e(err);}finally{_iterator6.f();}if(width===this.width&&height===this.height&&dpr===this.dpr){return;}this.width=width;this.height=height;this.dpr=dpr;if(this.canRender){this.threeRenderer.setSize(width*dpr,height*dpr,false);}var widthCSS=width/this.scale;var heightCSS=height/this.scale;this.canvasElement.style.width="".concat(widthCSS,"px");this.canvasElement.style.height="".concat(heightCSS,"px");var _iterator7=_createForOfIteratorHelper(this.scenes),_step7;try{for(_iterator7.s();!(_step7=_iterator7.n()).done;){var _scene2=_step7.value;var canvas=_scene2.canvas;canvas.width=width*dpr;canvas.height=height*dpr;canvas.style.width="".concat(widthCSS,"px");canvas.style.height="".concat(heightCSS,"px");_scene2.isDirty=true;}}catch(err){_iterator7.e(err);}finally{_iterator7.f();}}},{key:"updateRendererScale",value:function updateRendererScale(){var scale=this.scale;if(this.avgFrameDuration>HIGH_FRAME_DURATION_MS&&scale>this.minScale){scale*=SCALE_STEP;}else if(this.avgFrameDuration0){this.threeRenderer.setAnimationLoop(function(time){return _this36.render(time);});}if(this.debugger!=null){this.debugger.addScene(scene);}}},{key:"unregisterScene",value:function unregisterScene(scene){this.scenes.delete(scene);if(this.canRender&&this.scenes.size===0){this.threeRenderer.setAnimationLoop(null);}if(this.debugger!=null){this.debugger.removeScene(scene);}}},{key:"displayCanvas",value:function displayCanvas(scene){return this.multipleScenesVisible?scene.element[$canvas]:this.canvasElement;}},{key:"selectCanvas",value:function selectCanvas(){var visibleScenes=0;var visibleInput=null;var _iterator9=_createForOfIteratorHelper(this.scenes),_step9;try{for(_iterator9.s();!(_step9=_iterator9.n()).done;){var scene=_step9.value;if(scene.element[$sceneIsReady]()){++visibleScenes;visibleInput=scene.element[$userInputElement];}}}catch(err){_iterator9.e(err);}finally{_iterator9.f();}var multipleScenesVisible=visibleScenes>1||USE_OFFSCREEN_CANVAS;var canvasElement=this.canvasElement;if(multipleScenesVisible===this.multipleScenesVisible&&(multipleScenesVisible||canvasElement.parentElement===visibleInput)){return;}this.multipleScenesVisible=multipleScenesVisible;if(multipleScenesVisible){canvasElement.classList.remove('show');}var _iterator10=_createForOfIteratorHelper(this.scenes),_step10;try{for(_iterator10.s();!(_step10=_iterator10.n()).done;){var _scene3=_step10.value;var userInputElement=_scene3.element[$userInputElement];var canvas=_scene3.element[$canvas];if(multipleScenesVisible){canvas.classList.add('show');_scene3.isDirty=true;}else if(userInputElement===visibleInput){userInputElement.appendChild(canvasElement);canvasElement.classList.add('show');canvas.classList.remove('show');_scene3.isDirty=true;}}}catch(err){_iterator10.e(err);}finally{_iterator10.f();}}},{key:"preRender",value:function preRender(scene,t,delta){var element=scene.element,exposure=scene.exposure,model=scene.model;element[$tick$1](t,delta);var exposureIsNumber=typeof exposure==='number'&&!self.isNaN(exposure);this.threeRenderer.toneMappingExposure=exposureIsNumber?exposure:1.0;if(model.updateShadow()){this.threeRenderer.shadowMap.needsUpdate=true;}}},{key:"render",value:function render(t){var delta=t-this.lastTick;this.lastTick=t;if(!this.canRender||this.isPresenting){return;}this.avgFrameDuration+=clamp(DURATION_DECAY*(delta-this.avgFrameDuration),-MAX_AVG_CHANGE_MS,MAX_AVG_CHANGE_MS);this.selectCanvas();this.updateRendererSize();this.updateRendererScale();var dpr=this.dpr,scale=this.scale;var _iterator11=_createForOfIteratorHelper(this.scenes),_step11;try{for(_iterator11.s();!(_step11=_iterator11.n()).done;){var scene=_step11.value;if(!scene.element[$sceneIsReady]()){continue;}this.preRender(scene,t,delta);if(!scene.isDirty){continue;}scene.isDirty=false;var width=Math.ceil(scene.width*scale*dpr);var height=Math.ceil(scene.height*scale*dpr);this.threeRenderer.setRenderTarget(null);this.threeRenderer.setViewport(0,Math.floor(this.height*dpr)-height,width,height);this.threeRenderer.render(scene,scene.getCamera());if(this.multipleScenesVisible){if(scene.context==null){scene.createContext();}{var context2D=scene.context;context2D.clearRect(0,0,width,height);context2D.drawImage(this.canvas3D,0,0,width,height,0,0,width,height);}}}}catch(err){_iterator11.e(err);}finally{_iterator11.f();}}},{key:"dispose",value:function dispose(){if(this.textureUtils!=null){this.textureUtils.dispose();}if(this.threeRenderer!=null){this.threeRenderer.dispose();}this.textureUtils=null;this.threeRenderer=null;this.scenes.clear();this.canvas3D.removeEventListener('webglcontextlost',this[$webGLContextLostHandler]);}},{key:(_a$8=$singleton,_b$6=$webGLContextLostHandler,$onWebGLContextLost),value:function value(event){this.dispatchEvent({type:'contextlost',sourceEvent:event});}},{key:"canRender",get:function get(){return this.threeRenderer!=null&&this.context3D!=null;}},{key:"scaleFactor",get:function get(){return this.scale;}},{key:"isPresenting",get:function get(){return this.arRenderer.isPresenting;}}],[{key:"resetSingleton",value:function resetSingleton(){this[$singleton].dispose();this[$singleton]=new Renderer({debug:isDebugMode()});}},{key:"singleton",get:function get(){return this[$singleton];}}]);return Renderer;}(EventDispatcher);Renderer[_a$8]=new Renderer({debug:isDebugMode()});var dataUrlToBlob=/*#__PURE__*/function(){var _ref4=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee16(base64DataUrl){return regeneratorRuntime.wrap(function _callee16$(_context17){while(1){switch(_context17.prev=_context17.next){case 0:return _context17.abrupt("return",new Promise(function(resolve,reject){var sliceSize=512;var typeMatch=base64DataUrl.match(/data:(.*);/);if(!typeMatch){return reject(new Error("".concat(base64DataUrl," is not a valid data Url")));}var type=typeMatch[1];var base64=base64DataUrl.replace(/data:image\/\w+;base64,/,'');var byteCharacters=atob(base64);var byteArrays=[];for(var offset=0;offset=0;i--){if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;}return c>3&&r&&Object.defineProperty(target,key,r),r;};var _a$a,_b$8,_c$2,_d$2,_e$1,_f$1,_g$1,_h$1,_j$1,_k$1;var CLEAR_MODEL_TIMEOUT_MS=1000;var FALLBACK_SIZE_UPDATE_THRESHOLD_MS=50;var ANNOUNCE_MODEL_VISIBILITY_DEBOUNCE_THRESHOLD=0;var UNSIZED_MEDIA_WIDTH=300;var UNSIZED_MEDIA_HEIGHT=150;var blobCanvas=document.createElement('canvas');var blobContext=null;var $template=Symbol('template');var $fallbackResizeHandler=Symbol('fallbackResizeHandler');var $defaultAriaLabel=Symbol('defaultAriaLabel');var $resizeObserver=Symbol('resizeObserver');var $intersectionObserver=Symbol('intersectionObserver');var $clearModelTimeout=Symbol('clearModelTimeout');var $onContextLost=Symbol('onContextLost');var $contextLostHandler=Symbol('contextLostHandler');var $loaded=Symbol('loaded');var $updateSize=Symbol('updateSize');var $isElementInViewport=Symbol('isElementInViewport');var $announceModelVisibility=Symbol('announceModelVisibility');var $ariaLabel=Symbol('ariaLabel');var $loadedTime=Symbol('loadedTime');var $updateSource=Symbol('updateSource');var $markLoaded=Symbol('markLoaded');var $container=Symbol('container');var $userInputElement=Symbol('input');var $canvas=Symbol('canvas');var $scene=Symbol('scene');var $needsRender=Symbol('needsRender');var $tick$1=Symbol('tick');var $onModelLoad=Symbol('onModelLoad');var $onResize=Symbol('onResize');var $renderer=Symbol('renderer');var $progressTracker=Symbol('progressTracker');var $getLoaded=Symbol('getLoaded');var $getModelIsVisible=Symbol('getModelIsVisible');var $shouldAttemptPreload=Symbol('shouldAttemptPreload');var $sceneIsReady=Symbol('sceneIsReady');var toVector3D=function toVector3D(v){return{x:v.x,y:v.y,z:v.z,toString:function toString(){return"".concat(this.x,"m ").concat(this.y,"m ").concat(this.z,"m");}};};var ModelViewerElementBase=/*#__PURE__*/function(_UpdatingElement){_inherits(ModelViewerElementBase,_UpdatingElement);var _super15=_createSuper(ModelViewerElementBase);function ModelViewerElementBase(){var _this39;_classCallCheck(this,ModelViewerElementBase);_this39=_super15.call(this);_this39.alt=null;_this39.src=null;_this39[_a$a]=false;_this39[_b$8]=false;_this39[_c$2]=0;_this39[_d$2]=null;_this39[_e$1]=debounce(function(){var boundingRect=_this39.getBoundingClientRect();_this39[$updateSize](boundingRect);},FALLBACK_SIZE_UPDATE_THRESHOLD_MS);_this39[_f$1]=debounce(function(oldVisibility){var newVisibility=_this39.modelIsVisible;if(newVisibility!==oldVisibility){_this39.dispatchEvent(new CustomEvent('model-visibility',{detail:{visible:newVisibility}}));}},ANNOUNCE_MODEL_VISIBILITY_DEBOUNCE_THRESHOLD);_this39[_g$1]=null;_this39[_h$1]=null;_this39[_j$1]=new ProgressTracker();_this39[_k$1]=function(event){return _this39[$onContextLost](event);};var template$$1=_this39.constructor.template;if(window.ShadyCSS){window.ShadyCSS.styleElement(_assertThisInitialized(_this39),{});}_this39.attachShadow({mode:'open'});var shadowRoot=_this39.shadowRoot;shadowRoot.appendChild(template$$1.content.cloneNode(true));_this39[$container]=shadowRoot.querySelector('.container');_this39[$userInputElement]=shadowRoot.querySelector('.userInput');_this39[$canvas]=shadowRoot.querySelector('canvas');_this39[$defaultAriaLabel]=_this39[$userInputElement].getAttribute('aria-label');var width,height;if(_this39.isConnected){var rect=_this39.getBoundingClientRect();width=rect.width;height=rect.height;}else{width=UNSIZED_MEDIA_WIDTH;height=UNSIZED_MEDIA_HEIGHT;}_this39[$scene]=new ModelScene({canvas:_this39[$canvas],element:_assertThisInitialized(_this39),width:width,height:height});_this39[$scene].addEventListener('model-load',function(event){_this39[$markLoaded]();_this39[$onModelLoad]();_this39.dispatchEvent(new CustomEvent('load',{detail:{url:event.url}}));});Promise.resolve().then(function(){_this39[$updateSize](_this39.getBoundingClientRect());});if(HAS_RESIZE_OBSERVER){_this39[$resizeObserver]=new ResizeObserver(function(entries){if(_this39[$renderer].isPresenting){return;}var _iterator13=_createForOfIteratorHelper(entries),_step13;try{for(_iterator13.s();!(_step13=_iterator13.n()).done;){var entry=_step13.value;if(entry.target===_assertThisInitialized(_this39)){_this39[$updateSize](entry.contentRect);}}}catch(err){_iterator13.e(err);}finally{_iterator13.f();}});}if(HAS_INTERSECTION_OBSERVER){_this39[$intersectionObserver]=new IntersectionObserver(function(entries){var _iterator14=_createForOfIteratorHelper(entries),_step14;try{for(_iterator14.s();!(_step14=_iterator14.n()).done;){var entry=_step14.value;if(entry.target===_assertThisInitialized(_this39)){var oldVisibility=_this39.modelIsVisible;_this39[$isElementInViewport]=entry.isIntersecting;_this39[$announceModelVisibility](oldVisibility);if(_this39[$isElementInViewport]&&!_this39[$sceneIsReady]()){_this39[$updateSource]();}}}}catch(err){_iterator14.e(err);}finally{_iterator14.f();}},{root:null,rootMargin:'0px',threshold:0});}else{_this39[$isElementInViewport]=true;}return _this39;}_createClass(ModelViewerElementBase,[{key:"connectedCallback",value:function connectedCallback(){_get(_getPrototypeOf(ModelViewerElementBase.prototype),"connectedCallback",this)&&_get(_getPrototypeOf(ModelViewerElementBase.prototype),"connectedCallback",this).call(this);if(HAS_RESIZE_OBSERVER){this[$resizeObserver].observe(this);}else{self.addEventListener('resize',this[$fallbackResizeHandler]);}if(HAS_INTERSECTION_OBSERVER){this[$intersectionObserver].observe(this);}var renderer=this[$renderer];renderer.addEventListener('contextlost',this[$contextLostHandler]);renderer.registerScene(this[$scene]);if(this[$clearModelTimeout]!=null){self.clearTimeout(this[$clearModelTimeout]);this[$clearModelTimeout]=null;this.requestUpdate('src',null);}}},{key:"disconnectedCallback",value:function disconnectedCallback(){var _this40=this;_get(_getPrototypeOf(ModelViewerElementBase.prototype),"disconnectedCallback",this)&&_get(_getPrototypeOf(ModelViewerElementBase.prototype),"disconnectedCallback",this).call(this);if(HAS_RESIZE_OBSERVER){this[$resizeObserver].unobserve(this);}else{self.removeEventListener('resize',this[$fallbackResizeHandler]);}if(HAS_INTERSECTION_OBSERVER){this[$intersectionObserver].unobserve(this);}var renderer=this[$renderer];renderer.removeEventListener('contextlost',this[$contextLostHandler]);renderer.unregisterScene(this[$scene]);this[$clearModelTimeout]=self.setTimeout(function(){_this40[$scene].model.clear();},CLEAR_MODEL_TIMEOUT_MS);}},{key:"updated",value:function updated(changedProperties){_get(_getPrototypeOf(ModelViewerElementBase.prototype),"updated",this).call(this,changedProperties);if(changedProperties.has('src')&&(this.src==null||this.src!==this[$scene].model.url)){this[$loaded]=false;this[$loadedTime]=0;this[$updateSource]();}if(changedProperties.has('alt')){var ariaLabel=this.alt==null?this[$defaultAriaLabel]:this.alt;this[$userInputElement].setAttribute('aria-label',ariaLabel);}}},{key:"toDataURL",value:function toDataURL(type,encoderOptions){return this[$renderer].displayCanvas(this[$scene]).toDataURL(type,encoderOptions);}},{key:"toBlob",value:function(){var _toBlob=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee18(options){var _this41=this;var mimeType,qualityArgument,idealAspect,_this$$scene,width,height,model,aspect,_this$$renderer,dpr,scaleFactor,outputWidth,outputHeight,offsetX,offsetY,oldHeight,oldWidth;return regeneratorRuntime.wrap(function _callee18$(_context19){while(1){switch(_context19.prev=_context19.next){case 0:mimeType=options?options.mimeType:undefined;qualityArgument=options?options.qualityArgument:undefined;idealAspect=options?options.idealAspect:undefined;_this$$scene=this[$scene],width=_this$$scene.width,height=_this$$scene.height,model=_this$$scene.model,aspect=_this$$scene.aspect;_this$$renderer=this[$renderer],dpr=_this$$renderer.dpr,scaleFactor=_this$$renderer.scaleFactor;outputWidth=width*scaleFactor*dpr;outputHeight=height*scaleFactor*dpr;offsetX=0;offsetY=0;if(idealAspect===true){if(model.fieldOfViewAspect>aspect){oldHeight=outputHeight;outputHeight=Math.round(outputWidth/model.fieldOfViewAspect);offsetY=(oldHeight-outputHeight)/2;}else{oldWidth=outputWidth;outputWidth=Math.round(outputHeight*model.fieldOfViewAspect);offsetX=(oldWidth-outputWidth)/2;}}blobCanvas.width=outputWidth;blobCanvas.height=outputHeight;_context19.prev=12;return _context19.abrupt("return",new Promise(/*#__PURE__*/function(){var _ref5=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee17(resolve,reject){return regeneratorRuntime.wrap(function _callee17$(_context18){while(1){switch(_context18.prev=_context18.next){case 0:if(blobContext==null){blobContext=blobCanvas.getContext('2d');}blobContext.drawImage(_this41[$renderer].displayCanvas(_this41[$scene]),offsetX,offsetY,outputWidth,outputHeight,0,0,outputWidth,outputHeight);if(!blobCanvas.msToBlob){_context18.next=5;break;}if(!(!mimeType||mimeType==='image/png')){_context18.next=5;break;}return _context18.abrupt("return",resolve(blobCanvas.msToBlob()));case 5:if(blobCanvas.toBlob){_context18.next=11;break;}_context18.t0=resolve;_context18.next=9;return dataUrlToBlob(blobCanvas.toDataURL(mimeType,qualityArgument));case 9:_context18.t1=_context18.sent;return _context18.abrupt("return",(0,_context18.t0)(_context18.t1));case 11:blobCanvas.toBlob(function(blob){if(!blob){return reject(new Error('Unable to retrieve canvas blob'));}resolve(blob);},mimeType,qualityArgument);case 12:case"end":return _context18.stop();}}},_callee17);}));return function(_x20,_x21){return _ref5.apply(this,arguments);};}()));case 14:_context19.prev=14;this[$updateSize]({width:width,height:height});return _context19.finish(14);case 17:case"end":return _context19.stop();}}},_callee18,this,[[12,,14,17]]);}));function toBlob(_x19){return _toBlob.apply(this,arguments);}return toBlob;}()},{key:$getLoaded,value:function value(){return this[$loaded];}},{key:$getModelIsVisible,value:function value(){return this.loaded&&this[$isElementInViewport];}},{key:$shouldAttemptPreload,value:function value(){return!!this.src&&this[$isElementInViewport];}},{key:$sceneIsReady,value:function value(){return this[$loaded];}},{key:$updateSize,value:function value(_ref6){var width=_ref6.width,height=_ref6.height;this[$container].style.width="".concat(width,"px");this[$container].style.height="".concat(height,"px");this[$onResize]({width:parseFloat(width),height:parseFloat(height)});}},{key:$tick$1,value:function value(_time,_delta){}},{key:$markLoaded,value:function value(){if(this[$loaded]){return;}this[$loaded]=true;this[$loadedTime]=performance.now();}},{key:$needsRender,value:function value(){this[$scene].isDirty=true;}},{key:$onModelLoad,value:function value(){}},{key:$onResize,value:function value(e){this[$scene].setSize(e.width,e.height);}},{key:$onContextLost,value:function value(event){this.dispatchEvent(new CustomEvent('error',{detail:{type:'webglcontextlost',sourceError:event.sourceEvent}}));}},{key:$updateSource,value:function(){var _value2=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee19(){var updateSourceProgress,source,detail;return regeneratorRuntime.wrap(function _callee19$(_context20){while(1){switch(_context20.prev=_context20.next){case 0:if(!(this.loaded||!this[$shouldAttemptPreload]())){_context20.next=2;break;}return _context20.abrupt("return");case 2:updateSourceProgress=this[$progressTracker].beginActivity();source=this.src;_context20.prev=4;_context20.next=7;return this[$scene].setModelSource(source,function(progress){return updateSourceProgress(progress*0.8);});case 7:detail={url:source};this.dispatchEvent(new CustomEvent('preload',{detail:detail}));_context20.next=14;break;case 11:_context20.prev=11;_context20.t0=_context20["catch"](4);this.dispatchEvent(new CustomEvent('error',{detail:_context20.t0}));case 14:_context20.prev=14;updateSourceProgress(0.9);requestAnimationFrame(function(){updateSourceProgress(1.0);});return _context20.finish(14);case 18:case"end":return _context20.stop();}}},_callee19,this,[[4,11,14,18]]);}));function value(){return _value2.apply(this,arguments);}return value;}()},{key:"loaded",get:function get(){return this[$getLoaded]();}},{key:(_a$a=$isElementInViewport,_b$8=$loaded,_c$2=$loadedTime,_d$2=$clearModelTimeout,_e$1=$fallbackResizeHandler,_f$1=$announceModelVisibility,_g$1=$resizeObserver,_h$1=$intersectionObserver,_j$1=$progressTracker,_k$1=$contextLostHandler,$renderer),get:function get(){return Renderer.singleton;}},{key:"modelIsVisible",get:function get(){return this[$getModelIsVisible]();}},{key:$ariaLabel,get:function get(){return this.alt==null||this.alt==='null'?this[$defaultAriaLabel]:this.alt;}}],[{key:"is",get:function get(){return'model-viewer';}},{key:"template",get:function get(){if(!this.hasOwnProperty($template)){this[$template]=makeTemplate(this.is);}return this[$template];}},{key:"modelCacheSize",set:function set(value){CachingGLTFLoader[$evictionPolicy].evictionThreshold=value;},get:function get(){return CachingGLTFLoader[$evictionPolicy].evictionThreshold;}},{key:"minimumRenderScale",set:function set(value){if(value>1){console.warn(' minimumRenderScale has been clamped to a maximum value of 1.');}if(value<=0){console.warn(' minimumRenderScale has been clamped to a minimum value of 0. This could result in single-pixel renders on some devices; consider increasing.');}Renderer.singleton.minScale=Math.max(0,Math.min(1,value));},get:function get(){return Renderer.singleton.minScale;}}]);return ModelViewerElementBase;}(UpdatingElement);__decorate([property({type:String})],ModelViewerElementBase.prototype,"alt",void 0);__decorate([property({type:String})],ModelViewerElementBase.prototype,"src",void 0);var __decorate$1=undefined&&undefined.__decorate||function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if((typeof Reflect==="undefined"?"undefined":_typeof(Reflect))==="object"&&typeof undefined==="function")r=undefined(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--){if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;}return c>3&&r&&Object.defineProperty(target,key,r),r;};var MILLISECONDS_PER_SECOND=1000.0;var $changeAnimation=Symbol('changeAnimation');var $paused=Symbol('paused');var AnimationMixin=function AnimationMixin(ModelViewerElement){var _a;var AnimationModelViewerElement=/*#__PURE__*/function(_ModelViewerElement){_inherits(AnimationModelViewerElement,_ModelViewerElement);var _super16=_createSuper(AnimationModelViewerElement);function AnimationModelViewerElement(){var _this42;_classCallCheck(this,AnimationModelViewerElement);_this42=_super16.apply(this,arguments);_this42.autoplay=false;_this42.animationName=undefined;_this42.animationCrossfadeDuration=300;_this42[_a]=true;return _this42;}_createClass(AnimationModelViewerElement,[{key:"pause",value:function pause(){if(this[$paused]){return;}this[$paused]=true;this[$renderer].threeRenderer.shadowMap.autoUpdate=false;this.dispatchEvent(new CustomEvent('pause'));}},{key:"play",value:function play(){if(this[$paused]&&this.availableAnimations.length>0){this[$paused]=false;this[$renderer].threeRenderer.shadowMap.autoUpdate=true;if(!this[$scene].model.hasActiveAnimation){this[$changeAnimation]();}this.dispatchEvent(new CustomEvent('play'));}}},{key:(_a=$paused,$onModelLoad),value:function value(){this[$paused]=true;if(this.autoplay){this[$changeAnimation]();this.play();}}},{key:$tick$1,value:function value(_time,delta){_get(_getPrototypeOf(AnimationModelViewerElement.prototype),$tick$1,this).call(this,_time,delta);if(this[$paused]||!this.modelIsVisible){return;}var model=this[$scene].model;model.updateAnimation(delta/MILLISECONDS_PER_SECOND);this[$needsRender]();}},{key:"updated",value:function updated(changedProperties){_get(_getPrototypeOf(AnimationModelViewerElement.prototype),"updated",this).call(this,changedProperties);if(changedProperties.has('autoplay')&&this.autoplay){this.play();}if(changedProperties.has('animationName')){this[$changeAnimation]();}}},{key:$updateSource,value:function(){var _value3=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee20(){return regeneratorRuntime.wrap(function _callee20$(_context21){while(1){switch(_context21.prev=_context21.next){case 0:this[$scene].model.stopAnimation();return _context21.abrupt("return",_get(_getPrototypeOf(AnimationModelViewerElement.prototype),$updateSource,this).call(this));case 2:case"end":return _context21.stop();}}},_callee20,this);}));function value(){return _value3.apply(this,arguments);}return value;}()},{key:$changeAnimation,value:function value(){var model=this[$scene].model;model.playAnimation(this.animationName,this.animationCrossfadeDuration/MILLISECONDS_PER_SECOND);if(this[$paused]){model.updateAnimation(0);this[$needsRender]();}}},{key:"availableAnimations",get:function get(){if(this.loaded){return this[$scene].model.animationNames;}return[];}},{key:"paused",get:function get(){return this[$paused];}},{key:"currentTime",get:function get(){return this[$scene].model.animationTime;},set:function set(value){this[$scene].model.animationTime=value;this[$renderer].threeRenderer.shadowMap.needsUpdate=true;this[$needsRender]();}}]);return AnimationModelViewerElement;}(ModelViewerElement);__decorate$1([property({type:Boolean})],AnimationModelViewerElement.prototype,"autoplay",void 0);__decorate$1([property({type:String,attribute:'animation-name'})],AnimationModelViewerElement.prototype,"animationName",void 0);__decorate$1([property({type:Number,attribute:'animation-crossfade-duration'})],AnimationModelViewerElement.prototype,"animationCrossfadeDuration",void 0);return AnimationModelViewerElement;};var $annotationRenderer=Symbol('annotationRenderer');var $hotspotMap=Symbol('hotspotMap');var $mutationCallback=Symbol('mutationCallback');var $observer=Symbol('observer');var $addHotspot=Symbol('addHotspot');var $removeHotspot=Symbol('removeHotspot');var pixelPosition=new Vector2();var worldToModel=new Matrix4();var AnnotationMixin=function AnnotationMixin(ModelViewerElement){var _a,_b,_c,_d;var AnnotationModelViewerElement=/*#__PURE__*/function(_ModelViewerElement2){_inherits(AnnotationModelViewerElement,_ModelViewerElement2);var _super17=_createSuper(AnnotationModelViewerElement);function AnnotationModelViewerElement(){var _this43;_classCallCheck(this,AnnotationModelViewerElement);for(var _len2=arguments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2];}_this43=_super17.call.apply(_super17,[this].concat(args));_this43[_a]=new CSS2DRenderer();_this43[_b]=new Map();_this43[_c]=function(mutations){mutations.forEach(function(mutation){if(!_instanceof(mutation,MutationRecord)||mutation.type==='childList'){mutation.addedNodes.forEach(function(node){_this43[$addHotspot](node);});mutation.removedNodes.forEach(function(node){_this43[$removeHotspot](node);});_this43[$needsRender]();}});};_this43[_d]=new MutationObserver(_this43[$mutationCallback]);var shadowRoot=_this43.shadowRoot;var domElement=_this43[$annotationRenderer].domElement;domElement.classList.add('annotation-container');shadowRoot.querySelector('.container').appendChild(domElement);domElement.appendChild(shadowRoot.querySelector('.default'));return _this43;}_createClass(AnnotationModelViewerElement,[{key:"connectedCallback",value:function connectedCallback(){_get(_getPrototypeOf(AnnotationModelViewerElement.prototype),"connectedCallback",this).call(this);for(var _i15=0;_i15-1;});var result=new Set();var _iterator15=_createForOfIteratorHelper(names),_step15;try{for(_iterator15.s();!(_step15=_iterator15.n()).done;){var name=_step15.value;result.add(name);}}catch(err){_iterator15.e(err);}finally{_iterator15.f();}return result;}catch(_error){}return new Set();};};var __decorate$2=undefined&&undefined.__decorate||function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if((typeof Reflect==="undefined"?"undefined":_typeof(Reflect))==="object"&&typeof undefined==="function")r=undefined(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--){if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;}return c>3&&r&&Object.defineProperty(target,key,r),r;};var openIOSARQuickLook=function(){var anchor=document.createElement('a');anchor.setAttribute('rel','ar');anchor.appendChild(document.createElement('img'));return function(usdzSrc,arScale){var modelUrl=new URL(usdzSrc,self.location.toString());if(arScale==='fixed'){modelUrl.hash='allowsContentScaling=0';}anchor.setAttribute('href',modelUrl.toString());anchor.click();};}();var openSceneViewer=function(){var anchor=document.createElement('a');var noArViewerSigil='#model-viewer-no-ar-fallback';var fallbackInvoked=false;return function(gltfSrc,title,arScale){if(fallbackInvoked){return;}var location=self.location.toString();var locationUrl=new URL(location);var modelUrl=new URL(gltfSrc,location);var scheme=modelUrl.protocol.replace(':','');locationUrl.hash=noArViewerSigil;var intentParams="?file=".concat(encodeURIComponent(modelUrl.toString()),"&mode=ar_only&link=").concat(location,"&title=").concat(encodeURIComponent(title));if(arScale==='fixed'){intentParams+="&resizable=false";}var intent="intent://arvr.google.com/scene-viewer/1.0".concat(intentParams,"#Intent;scheme=").concat(scheme,";package=com.google.ar.core;action=android.intent.action.VIEW;S.browser_fallback_url=").concat(encodeURIComponent(locationUrl.toString()),";end;");var undoHashChange=function undoHashChange(){if(self.location.hash===noArViewerSigil&&!fallbackInvoked){fallbackInvoked=true;self.history.back();}};self.addEventListener('hashchange',undoHashChange,{once:true});anchor.setAttribute('href',intent);anchor.click();};}();var deserializeQuickLookBrowsers=enumerationDeserializer(['safari','chrome']);var deserializeARModes=enumerationDeserializer(['quick-look','scene-viewer','webxr','none']);var DEFAULT_AR_MODES='webxr scene-viewer quick-look';var ARMode={QUICK_LOOK:'quick-look',SCENE_VIEWER:'scene-viewer',WEBXR:'webxr',NONE:'none'};var $arButtonContainer=Symbol('arButtonContainer');var $enterARWithWebXR=Symbol('enterARWithWebXR');var $canActivateAR=Symbol('canActivateAR');var $arMode=Symbol('arMode');var $arModes=Symbol('arModes');var $canLaunchQuickLook=Symbol('canLaunchQuickLook');var $quickLookBrowsers=Symbol('quickLookBrowsers');var $onARButtonContainerClick=Symbol('onARButtonContainerClick');var $onARStatus=Symbol('onARStatus');var ARMixin=function ARMixin(ModelViewerElement){var _a,_b,_c,_d,_e,_f,_g;var ARModelViewerElement=/*#__PURE__*/function(_ModelViewerElement3){_inherits(ARModelViewerElement,_ModelViewerElement3);var _super18=_createSuper(ARModelViewerElement);function ARModelViewerElement(){var _this44;_classCallCheck(this,ARModelViewerElement);_this44=_super18.apply(this,arguments);_this44.ar=false;_this44.arScale='auto';_this44.arModes=DEFAULT_AR_MODES;_this44.iosSrc=null;_this44.quickLookBrowsers='safari';_this44[_a]=false;_this44[_b]=_this44.shadowRoot.querySelector('.ar-button');_this44[_c]=new Set();_this44[_d]=ARMode.NONE;_this44[_e]=new Set();_this44[_f]=function(event){event.preventDefault();_this44.activateAR();};_this44[_g]=function(_ref7){var status=_ref7.status;if(status===ARStatus.NOT_PRESENTING||_this44[$renderer].arRenderer.presentedScene===_this44[$scene]){_this44.setAttribute('ar-status',status);_this44.dispatchEvent(new CustomEvent('ar-status',{detail:{status:status}}));}};return _this44;}_createClass(ARModelViewerElement,[{key:"activateAR",value:function(){var _activateAR=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee21(){return regeneratorRuntime.wrap(function _callee21$(_context22){while(1){switch(_context22.prev=_context22.next){case 0:_context22.t0=this[$arMode];_context22.next=_context22.t0===ARMode.QUICK_LOOK?3:_context22.t0===ARMode.WEBXR?5:_context22.t0===ARMode.SCENE_VIEWER?8:10;break;case 3:openIOSARQuickLook(this.iosSrc,this.arScale);return _context22.abrupt("break",12);case 5:_context22.next=7;return this[$enterARWithWebXR]();case 7:return _context22.abrupt("break",12);case 8:openSceneViewer(this.src,this.alt||'',this.arScale);return _context22.abrupt("break",12);case 10:console.warn('No AR Mode can be activated. This is probably due to missing \ configuration or device capabilities');return _context22.abrupt("break",12);case 12:case"end":return _context22.stop();}}},_callee21,this);}));function activateAR(){return _activateAR.apply(this,arguments);}return activateAR;}()},{key:(_a=$canActivateAR,_b=$arButtonContainer,_c=$arModes,_d=$arMode,_e=$quickLookBrowsers,_f=$onARButtonContainerClick,_g=$onARStatus,$enterARWithWebXR),value:function(){var _value4=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee22(){return regeneratorRuntime.wrap(function _callee22$(_context23){while(1){switch(_context23.prev=_context23.next){case 0:console.log('Attempting to present in AR...');_context23.prev=1;_context23.next=4;return this[$renderer].arRenderer.present(this[$scene]);case 4:_context23.next=12;break;case 6:_context23.prev=6;_context23.t0=_context23["catch"](1);console.warn('Error while trying to present to AR');console.error(_context23.t0);_context23.next=12;return this[$renderer].arRenderer.stopPresenting();case 12:case"end":return _context23.stop();}}},_callee22,this,[[1,6]]);}));function value(){return _value4.apply(this,arguments);}return value;}()},{key:"connectedCallback",value:function connectedCallback(){_get(_getPrototypeOf(ARModelViewerElement.prototype),"connectedCallback",this).call(this);this[$renderer].arRenderer.addEventListener('status',this[$onARStatus]);this.setAttribute('ar-status',ARStatus.NOT_PRESENTING);}},{key:"disconnectedCallback",value:function disconnectedCallback(){_get(_getPrototypeOf(ARModelViewerElement.prototype),"disconnectedCallback",this).call(this);this[$renderer].arRenderer.removeEventListener('status',this[$onARStatus]);}},{key:"update",value:function(){var _update2=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee23(changedProperties){var arModes,_i16,_arModes,value;return regeneratorRuntime.wrap(function _callee23$(_context24){while(1){switch(_context24.prev=_context24.next){case 0:_get(_getPrototypeOf(ARModelViewerElement.prototype),"update",this).call(this,changedProperties);if(changedProperties.has('quickLookBrowsers')){this[$quickLookBrowsers]=deserializeQuickLookBrowsers(this.quickLookBrowsers);}if(!(!changedProperties.has('ar')&&!changedProperties.has('arModes')&&!changedProperties.has('iosSrc'))){_context24.next=4;break;}return _context24.abrupt("return");case 4:if(changedProperties.has('arModes')){this[$arModes]=deserializeARModes(this.arModes);}if(changedProperties.has('arScale')){this[$scene].canScale=this.arScale!=='fixed';}this[$arMode]=ARMode.NONE;if(!this.ar){_context24.next=34;break;}arModes=[];this[$arModes].forEach(function(value){arModes.push(value);});_i16=0,_arModes=arModes;case 11:if(!(_i16<_arModes.length)){_context24.next=34;break;}value=_arModes[_i16];_context24.t0=value==='webxr'&&IS_WEBXR_AR_CANDIDATE;if(!_context24.t0){_context24.next=18;break;}_context24.next=17;return this[$renderer].arRenderer.supportsPresentation();case 17:_context24.t0=_context24.sent;case 18:if(!_context24.t0){_context24.next=23;break;}this[$arMode]=ARMode.WEBXR;return _context24.abrupt("break",34);case 23:if(!(value==='scene-viewer'&&IS_ANDROID)){_context24.next=28;break;}this[$arMode]=ARMode.SCENE_VIEWER;return _context24.abrupt("break",34);case 28:if(!(value==='quick-look'&&!!this.iosSrc&&this[$canLaunchQuickLook]&&IS_AR_QUICKLOOK_CANDIDATE)){_context24.next=31;break;}this[$arMode]=ARMode.QUICK_LOOK;return _context24.abrupt("break",34);case 31:_i16++;_context24.next=11;break;case 34:if(this.canActivateAR){this[$arButtonContainer].classList.add('enabled');this[$arButtonContainer].addEventListener('click',this[$onARButtonContainerClick]);}else{this[$arButtonContainer].removeEventListener('click',this[$onARButtonContainerClick]);this[$arButtonContainer].classList.remove('enabled');}case 35:case"end":return _context24.stop();}}},_callee23,this);}));function update(_x22){return _update2.apply(this,arguments);}return update;}()},{key:"canActivateAR",get:function get(){return this[$arMode]!==ARMode.NONE;}},{key:$canLaunchQuickLook,get:function get(){if(IS_IOS_CHROME){return this[$quickLookBrowsers].has('chrome');}else if(IS_IOS_SAFARI){return this[$quickLookBrowsers].has('safari');}return false;}}]);return ARModelViewerElement;}(ModelViewerElement);__decorate$2([property({type:Boolean,attribute:'ar'})],ARModelViewerElement.prototype,"ar",void 0);__decorate$2([property({type:String,attribute:'ar-scale'})],ARModelViewerElement.prototype,"arScale",void 0);__decorate$2([property({type:String,attribute:'ar-modes'})],ARModelViewerElement.prototype,"arModes",void 0);__decorate$2([property({type:String,attribute:'ios-src'})],ARModelViewerElement.prototype,"iosSrc",void 0);__decorate$2([property({type:String,attribute:'quick-look-browsers'})],ARModelViewerElement.prototype,"quickLookBrowsers",void 0);return ARModelViewerElement;};var _a$b,_b$9,_c$3;var $evaluate=Symbol('evaluate');var $lastValue=Symbol('lastValue');var Evaluator=/*#__PURE__*/function(){function Evaluator(){_classCallCheck(this,Evaluator);this[_a$b]=null;}_createClass(Evaluator,[{key:"evaluate",value:function evaluate(){if(!this.isConstant||this[$lastValue]==null){this[$lastValue]=this[$evaluate]();}return this[$lastValue];}},{key:"isConstant",get:function get(){return false;}}],[{key:"evaluatableFor",value:function evaluatableFor(node){var basis=arguments.length>1&&arguments[1]!==undefined?arguments[1]:ZERO;if(_instanceof(node,Evaluator)){return node;}if(node.type==='number'){if(node.unit==='%'){return new PercentageEvaluator(node,basis);}return node;}switch(node.name.value){case'calc':return new CalcEvaluator(node,basis);case'env':return new EnvEvaluator(node);}return ZERO;}},{key:"evaluate",value:function evaluate(evaluatable){if(_instanceof(evaluatable,Evaluator)){return evaluatable.evaluate();}return evaluatable;}},{key:"isConstant",value:function isConstant(evaluatable){if(_instanceof(evaluatable,Evaluator)){return evaluatable.isConstant;}return true;}},{key:"applyIntrinsics",value:function applyIntrinsics(evaluated,intrinsics){var basis=intrinsics.basis,keywords=intrinsics.keywords;var auto=keywords.auto;return basis.map(function(basisNode,index){var autoSubstituteNode=auto[index]==null?basisNode:auto[index];var evaluatedNode=evaluated[index]?evaluated[index]:autoSubstituteNode;if(evaluatedNode.type==='ident'){var keyword=evaluatedNode.value;if(keyword in keywords){evaluatedNode=keywords[keyword][index];}}if(evaluatedNode==null||evaluatedNode.type==='ident'){evaluatedNode=autoSubstituteNode;}if(evaluatedNode.unit==='%'){return numberNode(evaluatedNode.number/100*basisNode.number,basisNode.unit);}evaluatedNode=normalizeUnit(evaluatedNode,basisNode);if(evaluatedNode.unit!==basisNode.unit){return basisNode;}return evaluatedNode;});}}]);return Evaluator;}();_a$b=$lastValue;var $percentage=Symbol('percentage');var $basis=Symbol('basis');var PercentageEvaluator=/*#__PURE__*/function(_Evaluator){_inherits(PercentageEvaluator,_Evaluator);var _super19=_createSuper(PercentageEvaluator);function PercentageEvaluator(percentage,basis){var _this45;_classCallCheck(this,PercentageEvaluator);_this45=_super19.call(this);_this45[$percentage]=percentage;_this45[$basis]=basis;return _this45;}_createClass(PercentageEvaluator,[{key:$evaluate,value:function value(){return numberNode(this[$percentage].number/100*this[$basis].number,this[$basis].unit);}},{key:"isConstant",get:function get(){return true;}}]);return PercentageEvaluator;}(Evaluator);var $identNode=Symbol('identNode');var EnvEvaluator=/*#__PURE__*/function(_Evaluator2){_inherits(EnvEvaluator,_Evaluator2);var _super20=_createSuper(EnvEvaluator);function EnvEvaluator(envFunction){var _this46;_classCallCheck(this,EnvEvaluator);_this46=_super20.call(this);_this46[_b$9]=null;var identNode=envFunction.arguments.length?envFunction.arguments[0].terms[0]:null;if(identNode!=null&&identNode.type==='ident'){_this46[$identNode]=identNode;}return _this46;}_createClass(EnvEvaluator,[{key:(_b$9=$identNode,$evaluate),value:function value(){if(this[$identNode]!=null){switch(this[$identNode].value){case'window-scroll-y':var verticalScrollPosition=window.pageYOffset;var verticalScrollMax=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight);var scrollY=verticalScrollPosition/(verticalScrollMax-window.innerHeight)||0;return{type:'number',number:scrollY,unit:null};}}return ZERO;}},{key:"isConstant",get:function get(){return false;}}]);return EnvEvaluator;}(Evaluator);var IS_MULTIPLICATION_RE=/[\*\/]/;var $evaluator=Symbol('evalutor');var CalcEvaluator=/*#__PURE__*/function(_Evaluator3){_inherits(CalcEvaluator,_Evaluator3);var _super21=_createSuper(CalcEvaluator);function CalcEvaluator(calcFunction){var _this47;var basis=arguments.length>1&&arguments[1]!==undefined?arguments[1]:ZERO;_classCallCheck(this,CalcEvaluator);_this47=_super21.call(this);_this47[_c$3]=null;if(calcFunction.arguments.length!==1){return _possibleConstructorReturn(_this47);}var terms=calcFunction.arguments[0].terms.slice();var secondOrderTerms=[];while(terms.length){var term=terms.shift();if(secondOrderTerms.length>0){var previousTerm=secondOrderTerms[secondOrderTerms.length-1];if(previousTerm.type==='operator'&&IS_MULTIPLICATION_RE.test(previousTerm.value)){var operator=secondOrderTerms.pop();var leftValue=secondOrderTerms.pop();if(leftValue==null){return _possibleConstructorReturn(_this47);}secondOrderTerms.push(new OperatorEvaluator(operator,Evaluator.evaluatableFor(leftValue,basis),Evaluator.evaluatableFor(term,basis)));continue;}}secondOrderTerms.push(term.type==='operator'?term:Evaluator.evaluatableFor(term,basis));}while(secondOrderTerms.length>2){var _secondOrderTerms$spl=secondOrderTerms.splice(0,3),_secondOrderTerms$spl2=_slicedToArray(_secondOrderTerms$spl,3),left=_secondOrderTerms$spl2[0],_operator=_secondOrderTerms$spl2[1],right=_secondOrderTerms$spl2[2];if(_operator.type!=='operator'){return _possibleConstructorReturn(_this47);}secondOrderTerms.unshift(new OperatorEvaluator(_operator,Evaluator.evaluatableFor(left,basis),Evaluator.evaluatableFor(right,basis)));}if(secondOrderTerms.length===1){_this47[$evaluator]=secondOrderTerms[0];}return _this47;}_createClass(CalcEvaluator,[{key:(_c$3=$evaluator,$evaluate),value:function value(){return this[$evaluator]!=null?Evaluator.evaluate(this[$evaluator]):ZERO;}},{key:"isConstant",get:function get(){return this[$evaluator]==null||Evaluator.isConstant(this[$evaluator]);}}]);return CalcEvaluator;}(Evaluator);var $operator=Symbol('operator');var $left=Symbol('left');var $right=Symbol('right');var OperatorEvaluator=/*#__PURE__*/function(_Evaluator4){_inherits(OperatorEvaluator,_Evaluator4);var _super22=_createSuper(OperatorEvaluator);function OperatorEvaluator(operator,left,right){var _this48;_classCallCheck(this,OperatorEvaluator);_this48=_super22.call(this);_this48[$operator]=operator;_this48[$left]=left;_this48[$right]=right;return _this48;}_createClass(OperatorEvaluator,[{key:$evaluate,value:function value(){var leftNode=normalizeUnit(Evaluator.evaluate(this[$left]));var rightNode=normalizeUnit(Evaluator.evaluate(this[$right]));var leftValue=leftNode.number,leftUnit=leftNode.unit;var rightValue=rightNode.number,rightUnit=rightNode.unit;if(rightUnit!=null&&leftUnit!=null&&rightUnit!=leftUnit){return ZERO;}var unit=leftUnit||rightUnit;var value;switch(this[$operator].value){case'+':value=leftValue+rightValue;break;case'-':value=leftValue-rightValue;break;case'/':value=leftValue/rightValue;break;case'*':value=leftValue*rightValue;break;default:return ZERO;}return{type:'number',number:value,unit:unit};}},{key:"isConstant",get:function get(){return Evaluator.isConstant(this[$left])&&Evaluator.isConstant(this[$right]);}}]);return OperatorEvaluator;}(Evaluator);var $evaluatables=Symbol('evaluatables');var $intrinsics=Symbol('intrinsics');var StyleEvaluator=/*#__PURE__*/function(_Evaluator5){_inherits(StyleEvaluator,_Evaluator5);var _super23=_createSuper(StyleEvaluator);function StyleEvaluator(expressions,intrinsics){var _this49;_classCallCheck(this,StyleEvaluator);_this49=_super23.call(this);_this49[$intrinsics]=intrinsics;var firstExpression=expressions[0];var terms=firstExpression!=null?firstExpression.terms:[];_this49[$evaluatables]=intrinsics.basis.map(function(basisNode,index){var term=terms[index];if(term==null){return{type:'ident',value:'auto'};}if(term.type==='ident'){return term;}return Evaluator.evaluatableFor(term,basisNode);});return _this49;}_createClass(StyleEvaluator,[{key:$evaluate,value:function value(){var evaluated=this[$evaluatables].map(function(evaluatable){return Evaluator.evaluate(evaluatable);});return Evaluator.applyIntrinsics(evaluated,this[$intrinsics]).map(function(numberNode$$1){return numberNode$$1.number;});}},{key:"isConstant",get:function get(){var _iterator16=_createForOfIteratorHelper(this[$evaluatables]),_step16;try{for(_iterator16.s();!(_step16=_iterator16.n()).done;){var evaluatable=_step16.value;if(!Evaluator.isConstant(evaluatable)){return false;}}}catch(err){_iterator16.e(err);}finally{_iterator16.f();}return true;}}]);return StyleEvaluator;}(Evaluator);var _a$c,_b$a,_c$4,_d$3;var $instances=Symbol('instances');var $activateListener=Symbol('activateListener');var $deactivateListener=Symbol('deactivateListener');var $notifyInstances=Symbol('notifyInstances');var $notify=Symbol('notify');var $scrollCallback=Symbol('callback');var ScrollObserver=/*#__PURE__*/function(){function ScrollObserver(callback){_classCallCheck(this,ScrollObserver);this[$scrollCallback]=callback;}_createClass(ScrollObserver,[{key:"observe",value:function observe(){if(ScrollObserver[$instances].size===0){ScrollObserver[$activateListener]();}ScrollObserver[$instances].add(this);}},{key:"disconnect",value:function disconnect(){ScrollObserver[$instances].delete(this);if(ScrollObserver[$instances].size===0){ScrollObserver[$deactivateListener]();}}},{key:$notify,value:function value(){this[$scrollCallback]();}}],[{key:$notifyInstances,value:function value(){var _iterator17=_createForOfIteratorHelper(ScrollObserver[$instances]),_step17;try{for(_iterator17.s();!(_step17=_iterator17.n()).done;){var instance=_step17.value;instance[$notify]();}}catch(err){_iterator17.e(err);}finally{_iterator17.f();}}},{key:(_a$c=$instances,$activateListener),value:function value(){window.addEventListener('scroll',this[$notifyInstances],{passive:true});}},{key:$deactivateListener,value:function value(){window.removeEventListener('scroll',this[$notifyInstances]);}}]);return ScrollObserver;}();ScrollObserver[_a$c]=new Set();var $computeStyleCallback=Symbol('computeStyleCallback');var $astWalker=Symbol('astWalker');var $dependencies=Symbol('dependencies');var $scrollHandler=Symbol('scrollHandler');var $onScroll=Symbol('onScroll');var StyleEffector=/*#__PURE__*/function(){function StyleEffector(callback){var _this50=this;_classCallCheck(this,StyleEffector);this[_b$a]={};this[_c$4]=new ASTWalker(['function']);this[_d$3]=function(){return _this50[$onScroll]();};this[$computeStyleCallback]=callback;}_createClass(StyleEffector,[{key:"observeEffectsFor",value:function observeEffectsFor(ast){var _this51=this;var newDependencies={};var oldDependencies=this[$dependencies];this[$astWalker].walk(ast,function(functionNode){var name=functionNode.name;var firstArgument=functionNode.arguments[0];var firstTerm=firstArgument.terms[0];if(name.value!=='env'||firstTerm==null||firstTerm.type!=='ident'){return;}switch(firstTerm.value){case'window-scroll-y':if(newDependencies['window-scroll']==null){var observer='window-scroll'in oldDependencies?oldDependencies['window-scroll']:new ScrollObserver(_this51[$scrollHandler]);observer.observe();delete oldDependencies['window-scroll'];newDependencies['window-scroll']=observer;}break;}});for(var environmentState in oldDependencies){var observer=oldDependencies[environmentState];observer.disconnect();}this[$dependencies]=newDependencies;}},{key:"dispose",value:function dispose(){for(var environmentState in this[$dependencies]){var observer=this[$dependencies][environmentState];observer.disconnect();}}},{key:(_b$a=$dependencies,_c$4=$astWalker,_d$3=$scrollHandler,$onScroll),value:function value(){this[$computeStyleCallback]({relatedState:'window-scroll'});}}]);return StyleEffector;}();var style=function style(config){var observeEffects=config.observeEffects||false;var getIntrinsics=_instanceof(config.intrinsics,Function)?config.intrinsics:function(){return config.intrinsics;};return function(proto,propertyName){var _Object$definePropert;var originalUpdated=proto.updated;var originalConnectedCallback=proto.connectedCallback;var originalDisconnectedCallback=proto.disconnectedCallback;var $styleEffector=Symbol("".concat(propertyName,"StyleEffector"));var $styleEvaluator=Symbol("".concat(propertyName,"StyleEvaluator"));var $updateEvaluator=Symbol("".concat(propertyName,"UpdateEvaluator"));var $evaluateAndSync=Symbol("".concat(propertyName,"EvaluateAndSync"));Object.defineProperties(proto,(_Object$definePropert={},_defineProperty(_Object$definePropert,$styleEffector,{value:null,writable:true}),_defineProperty(_Object$definePropert,$styleEvaluator,{value:null,writable:true}),_defineProperty(_Object$definePropert,$updateEvaluator,{value:function value(){var _this52=this;var ast=parseExpressions(this[propertyName]);this[$styleEvaluator]=new StyleEvaluator(ast,getIntrinsics(this));if(this[$styleEffector]==null&&observeEffects){this[$styleEffector]=new StyleEffector(function(){return _this52[$evaluateAndSync]();});}if(this[$styleEffector]!=null){this[$styleEffector].observeEffectsFor(ast);}}}),_defineProperty(_Object$definePropert,$evaluateAndSync,{value:function value(){if(this[$styleEvaluator]==null){return;}var result=this[$styleEvaluator].evaluate();this[config.updateHandler](result);}}),_defineProperty(_Object$definePropert,"updated",{value:function value(changedProperties){if(changedProperties.has(propertyName)){this[$updateEvaluator]();this[$evaluateAndSync]();}originalUpdated.call(this,changedProperties);}}),_defineProperty(_Object$definePropert,"connectedCallback",{value:function value(){originalConnectedCallback.call(this);this.requestUpdate(propertyName,this[propertyName]);}}),_defineProperty(_Object$definePropert,"disconnectedCallback",{value:function value(){originalDisconnectedCallback.call(this);if(this[$styleEffector]!=null){this[$styleEffector].dispose();this[$styleEffector]=null;}}}),_Object$definePropert));};};var _a$d,_b$b,_c$5,_d$4,_e$2,_f$2,_g$2,_h$2,_j$2,_k$2,_l$1;var DEFAULT_OPTIONS=Object.freeze({minimumRadius:0,maximumRadius:Infinity,minimumPolarAngle:Math.PI/8,maximumPolarAngle:Math.PI-Math.PI/8,minimumAzimuthalAngle:-Infinity,maximumAzimuthalAngle:Infinity,minimumFieldOfView:10,maximumFieldOfView:45,eventHandlingBehavior:'prevent-all',interactionPolicy:'always-allow'});var $spherical=Symbol('spherical');var $goalSpherical=Symbol('goalSpherical');var $thetaDamper=Symbol('thetaDamper');var $phiDamper=Symbol('phiDamper');var $radiusDamper=Symbol('radiusDamper');var $logFov=Symbol('fov');var $goalLogFov=Symbol('goalLogFov');var $fovDamper=Symbol('fovDamper');var $options=Symbol('options');var $touchMode=Symbol('touchMode');var $canInteract=Symbol('canInteract');var $interactionEnabled=Symbol('interactionEnabled');var $userAdjustOrbit=Symbol('userAdjustOrbit');var $isUserChange=Symbol('isUserChange');var $isStationary=Symbol('isMoving');var $moveCamera=Symbol('moveCamera');var $isUserPointing=Symbol('isUserPointing');var $pointerIsDown=Symbol('pointerIsDown');var $lastPointerPosition=Symbol('lastPointerPosition');var $lastTouches=Symbol('lastTouches');var $pixelLengthToSphericalAngle=Symbol('pixelLengthToSphericalAngle');var $twoTouchDistance=Symbol('twoTouchDistance');var $wrapAngle=Symbol('wrapAngle');var $onMouseMove=Symbol('onMouseMove');var $onMouseDown=Symbol('onMouseDown');var $onMouseUp=Symbol('onMouseUp');var $onTouchStart=Symbol('onTouchStart');var $onTouchEnd=Symbol('onTouchEnd');var $onTouchMove=Symbol('onTouchMove');var $onWheel=Symbol('onWheel');var $onKeyDown=Symbol('onKeyDown');var $handlePointerMove=Symbol('handlePointerMove');var $handleSinglePointerMove=Symbol('handleSinglePointerMove');var $handlePointerDown=Symbol('handlePointerDown');var $handleSinglePointerDown=Symbol('handleSinglePointerDown');var $handlePointerUp=Symbol('handlePointerUp');var $handleWheel=Symbol('handleWheel');var $handleKey=Symbol('handleKey');var TOUCH_EVENT_RE=/^touch(start|end|move)$/;var KEYBOARD_ORBIT_INCREMENT=Math.PI/8;var ZOOM_SENSITIVITY=0.04;var KeyCode={PAGE_UP:33,PAGE_DOWN:34,LEFT:37,UP:38,RIGHT:39,DOWN:40};var ChangeSource={USER_INTERACTION:'user-interaction',NONE:'none'};var SmoothControls=/*#__PURE__*/function(_EventDispatcher5){_inherits(SmoothControls,_EventDispatcher5);var _super24=_createSuper(SmoothControls);function SmoothControls(camera,element){var _this53;_classCallCheck(this,SmoothControls);_this53=_super24.call(this);_this53.camera=camera;_this53.element=element;_this53[_a$d]=false;_this53[_b$b]=false;_this53[_c$5]=false;_this53[_d$4]=new Spherical();_this53[_e$2]=new Spherical();_this53[_f$2]=new Damper();_this53[_g$2]=new Damper();_this53[_h$2]=new Damper();_this53[_j$2]=new Damper();_this53[_k$2]=false;_this53[_l$1]={clientX:0,clientY:0};_this53[$onMouseMove]=function(event){return _this53[$handlePointerMove](event);};_this53[$onMouseDown]=function(event){return _this53[$handlePointerDown](event);};_this53[$onMouseUp]=function(event){return _this53[$handlePointerUp](event);};_this53[$onWheel]=function(event){return _this53[$handleWheel](event);};_this53[$onKeyDown]=function(event){return _this53[$handleKey](event);};_this53[$onTouchStart]=function(event){return _this53[$handlePointerDown](event);};_this53[$onTouchEnd]=function(event){return _this53[$handlePointerUp](event);};_this53[$onTouchMove]=function(event){return _this53[$handlePointerMove](event);};_this53[$options]=Object.assign({},DEFAULT_OPTIONS);_this53.setOrbit(0,Math.PI/2,1);_this53.setFieldOfView(100);_this53.jumpToGoal();return _this53;}_createClass(SmoothControls,[{key:"enableInteraction",value:function enableInteraction(){if(this[$interactionEnabled]===false){var element=this.element;element.addEventListener('mousemove',this[$onMouseMove]);element.addEventListener('mousedown',this[$onMouseDown]);element.addEventListener('wheel',this[$onWheel]);element.addEventListener('keydown',this[$onKeyDown]);element.addEventListener('touchstart',this[$onTouchStart]);element.addEventListener('touchmove',this[$onTouchMove]);self.addEventListener('mouseup',this[$onMouseUp]);self.addEventListener('touchend',this[$onTouchEnd]);this.element.style.cursor='grab';this[$interactionEnabled]=true;}}},{key:"disableInteraction",value:function disableInteraction(){if(this[$interactionEnabled]===true){var element=this.element;element.removeEventListener('mousemove',this[$onMouseMove]);element.removeEventListener('mousedown',this[$onMouseDown]);element.removeEventListener('wheel',this[$onWheel]);element.removeEventListener('keydown',this[$onKeyDown]);element.removeEventListener('touchstart',this[$onTouchStart]);element.removeEventListener('touchmove',this[$onTouchMove]);self.removeEventListener('mouseup',this[$onMouseUp]);self.removeEventListener('touchend',this[$onTouchEnd]);element.style.cursor='';this[$interactionEnabled]=false;}}},{key:"getCameraSpherical",value:function getCameraSpherical(){var target=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new Spherical();return target.copy(this[$spherical]);}},{key:"getFieldOfView",value:function getFieldOfView(){return this.camera.fov;}},{key:"applyOptions",value:function applyOptions(options){Object.assign(this[$options],options);this.setOrbit();this.setFieldOfView(Math.exp(this[$goalLogFov]));}},{key:"updateNearFar",value:function updateNearFar(nearPlane,farPlane){this.camera.near=Math.max(nearPlane,farPlane/1000);this.camera.far=farPlane;this.camera.updateProjectionMatrix();}},{key:"updateAspect",value:function updateAspect(aspect){this.camera.aspect=aspect;this.camera.updateProjectionMatrix();}},{key:"setOrbit",value:function setOrbit(){var goalTheta=arguments.length>0&&arguments[0]!==undefined?arguments[0]:this[$goalSpherical].theta;var goalPhi=arguments.length>1&&arguments[1]!==undefined?arguments[1]:this[$goalSpherical].phi;var goalRadius=arguments.length>2&&arguments[2]!==undefined?arguments[2]:this[$goalSpherical].radius;var _this$$options=this[$options],minimumAzimuthalAngle=_this$$options.minimumAzimuthalAngle,maximumAzimuthalAngle=_this$$options.maximumAzimuthalAngle,minimumPolarAngle=_this$$options.minimumPolarAngle,maximumPolarAngle=_this$$options.maximumPolarAngle,minimumRadius=_this$$options.minimumRadius,maximumRadius=_this$$options.maximumRadius;var _this$$goalSpherical=this[$goalSpherical],theta=_this$$goalSpherical.theta,phi=_this$$goalSpherical.phi,radius=_this$$goalSpherical.radius;var nextTheta=clamp(goalTheta,minimumAzimuthalAngle,maximumAzimuthalAngle);if(!isFinite(minimumAzimuthalAngle)&&!isFinite(maximumAzimuthalAngle)){this[$spherical].theta=this[$wrapAngle](this[$spherical].theta-nextTheta)+nextTheta;}var nextPhi=clamp(goalPhi,minimumPolarAngle,maximumPolarAngle);var nextRadius=clamp(goalRadius,minimumRadius,maximumRadius);if(nextTheta===theta&&nextPhi===phi&&nextRadius===radius){return false;}this[$goalSpherical].theta=nextTheta;this[$goalSpherical].phi=nextPhi;this[$goalSpherical].radius=nextRadius;this[$goalSpherical].makeSafe();this[$isUserChange]=false;return true;}},{key:"setRadius",value:function setRadius(radius){this[$goalSpherical].radius=radius;this.setOrbit();}},{key:"setFieldOfView",value:function setFieldOfView(fov){var _this$$options2=this[$options],minimumFieldOfView=_this$$options2.minimumFieldOfView,maximumFieldOfView=_this$$options2.maximumFieldOfView;fov=clamp(fov,minimumFieldOfView,maximumFieldOfView);this[$goalLogFov]=Math.log(fov);}},{key:"adjustOrbit",value:function adjustOrbit(deltaTheta,deltaPhi,deltaZoom){var _this$$goalSpherical2=this[$goalSpherical],theta=_this$$goalSpherical2.theta,phi=_this$$goalSpherical2.phi,radius=_this$$goalSpherical2.radius;var _this$$options3=this[$options],minimumRadius=_this$$options3.minimumRadius,maximumRadius=_this$$options3.maximumRadius,minimumFieldOfView=_this$$options3.minimumFieldOfView,maximumFieldOfView=_this$$options3.maximumFieldOfView;var dTheta=this[$spherical].theta-theta;var dThetaLimit=Math.PI-0.001;var goalTheta=theta-clamp(deltaTheta,-dThetaLimit-dTheta,dThetaLimit-dTheta);var goalPhi=phi-deltaPhi;var deltaRatio=deltaZoom===0?0:deltaZoom>0?(maximumRadius-radius)/(Math.log(maximumFieldOfView)-this[$goalLogFov]):(radius-minimumRadius)/(this[$goalLogFov]-Math.log(minimumFieldOfView));var goalRadius=radius+deltaZoom*Math.min(isFinite(deltaRatio)?deltaRatio:Infinity,maximumRadius-minimumRadius);var handled=this.setOrbit(goalTheta,goalPhi,goalRadius);if(deltaZoom!==0){var goalLogFov=this[$goalLogFov]+deltaZoom;this.setFieldOfView(Math.exp(goalLogFov));handled=true;}return handled;}},{key:"jumpToGoal",value:function jumpToGoal(){this.update(0,SETTLING_TIME);}},{key:"update",value:function update(_time,delta){if(this[$isStationary]()){return;}var _this$$options4=this[$options],maximumPolarAngle=_this$$options4.maximumPolarAngle,maximumRadius=_this$$options4.maximumRadius;var dTheta=this[$spherical].theta-this[$goalSpherical].theta;if(Math.abs(dTheta)>Math.PI&&!isFinite(this[$options].minimumAzimuthalAngle)&&!isFinite(this[$options].maximumAzimuthalAngle)){this[$spherical].theta-=Math.sign(dTheta)*2*Math.PI;}this[$spherical].theta=this[$thetaDamper].update(this[$spherical].theta,this[$goalSpherical].theta,delta,Math.PI);this[$spherical].phi=this[$phiDamper].update(this[$spherical].phi,this[$goalSpherical].phi,delta,maximumPolarAngle);this[$spherical].radius=this[$radiusDamper].update(this[$spherical].radius,this[$goalSpherical].radius,delta,maximumRadius);this[$logFov]=this[$fovDamper].update(this[$logFov],this[$goalLogFov],delta,1);this[$moveCamera]();}},{key:(_a$d=$interactionEnabled,_b$b=$isUserChange,_c$5=$isUserPointing,_d$4=$spherical,_e$2=$goalSpherical,_f$2=$thetaDamper,_g$2=$phiDamper,_h$2=$radiusDamper,_j$2=$fovDamper,_k$2=$pointerIsDown,_l$1=$lastPointerPosition,$isStationary),value:function value(){return this[$goalSpherical].theta===this[$spherical].theta&&this[$goalSpherical].phi===this[$spherical].phi&&this[$goalSpherical].radius===this[$spherical].radius&&this[$goalLogFov]===this[$logFov];}},{key:$moveCamera,value:function value(){this[$spherical].makeSafe();this.camera.position.setFromSpherical(this[$spherical]);this.camera.setRotationFromEuler(new Euler(this[$spherical].phi-Math.PI/2,this[$spherical].theta,0,'YXZ'));if(this.camera.fov!==Math.exp(this[$logFov])){this.camera.fov=Math.exp(this[$logFov]);this.camera.updateProjectionMatrix();}var source=this[$isUserChange]?ChangeSource.USER_INTERACTION:ChangeSource.NONE;this.dispatchEvent({type:'change',source:source});}},{key:$userAdjustOrbit,value:function value(deltaTheta,deltaPhi,deltaZoom){var handled=this.adjustOrbit(deltaTheta,deltaPhi,deltaZoom);this[$isUserChange]=true;this.dispatchEvent({type:'change',source:ChangeSource.USER_INTERACTION});return handled;}},{key:$wrapAngle,value:function value(radians){var normalized=(radians+Math.PI)/(2*Math.PI);var wrapped=normalized-Math.floor(normalized);return wrapped*2*Math.PI-Math.PI;}},{key:$pixelLengthToSphericalAngle,value:function value(pixelLength){return 2*Math.PI*pixelLength/this.element.clientHeight;}},{key:$twoTouchDistance,value:function value(touchOne,touchTwo){var xOne=touchOne.clientX,yOne=touchOne.clientY;var xTwo=touchTwo.clientX,yTwo=touchTwo.clientY;var xDelta=xTwo-xOne;var yDelta=yTwo-yOne;return Math.sqrt(xDelta*xDelta+yDelta*yDelta);}},{key:$handlePointerMove,value:function value(event){if(!this[$pointerIsDown]||!this[$canInteract]){return;}var handled=false;if(TOUCH_EVENT_RE.test(event.type)){var touches=event.touches;switch(this[$touchMode]){case'zoom':if(this[$lastTouches].length>1&&touches.length>1){var lastTouchDistance=this[$twoTouchDistance](this[$lastTouches][0],this[$lastTouches][1]);var touchDistance=this[$twoTouchDistance](touches[0],touches[1]);var deltaZoom=ZOOM_SENSITIVITY*(lastTouchDistance-touchDistance)/10.0;handled=this[$userAdjustOrbit](0,0,deltaZoom);}break;case'rotate':handled=this[$handleSinglePointerMove](touches[0]);break;}this[$lastTouches]=touches;}else{handled=this[$handleSinglePointerMove](event);}if((handled||this[$options].eventHandlingBehavior==='prevent-all')&&event.cancelable){event.preventDefault();}}},{key:$handleSinglePointerMove,value:function value(pointer){var clientX=pointer.clientX,clientY=pointer.clientY;var deltaTheta=this[$pixelLengthToSphericalAngle](clientX-this[$lastPointerPosition].clientX);var deltaPhi=this[$pixelLengthToSphericalAngle](clientY-this[$lastPointerPosition].clientY);this[$lastPointerPosition].clientX=clientX;this[$lastPointerPosition].clientY=clientY;if(this[$isUserPointing]===false){this[$isUserPointing]=true;this.dispatchEvent({type:'pointer-change-start',pointer:Object.assign({},pointer)});}return this[$userAdjustOrbit](deltaTheta,deltaPhi,0);}},{key:$handlePointerDown,value:function value(event){this[$pointerIsDown]=true;this[$isUserPointing]=false;if(TOUCH_EVENT_RE.test(event.type)){var touches=event.touches;switch(touches.length){default:case 1:this[$touchMode]='rotate';this[$handleSinglePointerDown](touches[0]);break;case 2:this[$touchMode]='zoom';break;}this[$lastTouches]=touches;}else{this[$handleSinglePointerDown](event);}}},{key:$handleSinglePointerDown,value:function value(pointer){this[$lastPointerPosition].clientX=pointer.clientX;this[$lastPointerPosition].clientY=pointer.clientY;this.element.style.cursor='grabbing';}},{key:$handlePointerUp,value:function value(_event){this.element.style.cursor='grab';this[$pointerIsDown]=false;if(this[$isUserPointing]){this.dispatchEvent({type:'pointer-change-end',pointer:Object.assign({},this[$lastPointerPosition])});}}},{key:$handleWheel,value:function value(event){if(!this[$canInteract]){return;}var deltaZoom=event.deltaY*ZOOM_SENSITIVITY/30;if((this[$userAdjustOrbit](0,0,deltaZoom)||this[$options].eventHandlingBehavior==='prevent-all')&&event.cancelable){event.preventDefault();}}},{key:$handleKey,value:function value(event){var relevantKey=false;var handled=false;switch(event.keyCode){case KeyCode.PAGE_UP:relevantKey=true;handled=this[$userAdjustOrbit](0,0,ZOOM_SENSITIVITY);break;case KeyCode.PAGE_DOWN:relevantKey=true;handled=this[$userAdjustOrbit](0,0,-1*ZOOM_SENSITIVITY);break;case KeyCode.UP:relevantKey=true;handled=this[$userAdjustOrbit](0,-KEYBOARD_ORBIT_INCREMENT,0);break;case KeyCode.DOWN:relevantKey=true;handled=this[$userAdjustOrbit](0,KEYBOARD_ORBIT_INCREMENT,0);break;case KeyCode.LEFT:relevantKey=true;handled=this[$userAdjustOrbit](-KEYBOARD_ORBIT_INCREMENT,0,0);break;case KeyCode.RIGHT:relevantKey=true;handled=this[$userAdjustOrbit](KEYBOARD_ORBIT_INCREMENT,0,0);break;}if(relevantKey&&(handled||this[$options].eventHandlingBehavior==='prevent-all')&&event.cancelable){event.preventDefault();}}},{key:"interactionEnabled",get:function get(){return this[$interactionEnabled];}},{key:"options",get:function get(){return this[$options];}},{key:$canInteract,get:function get(){if(this[$options].interactionPolicy=='allow-when-focused'){var rootNode=this.element.getRootNode();return rootNode.activeElement===this.element;}return this[$options].interactionPolicy==='always-allow';}}]);return SmoothControls;}(EventDispatcher);var easeInOutQuad=function easeInOutQuad(t){return t<.5?2*t*t:-1+(4-2*t)*t;};var interpolate=function interpolate(start,end){var ease=arguments.length>2&&arguments[2]!==undefined?arguments[2]:easeInOutQuad;return function(time){return start+(end-start)*ease(time);};};var sequence=function sequence(tracks,weights){var totalWeight=weights.reduce(function(total,weight){return total+weight;},0);var ratios=weights.map(function(weight){return weight/totalWeight;});return function(time){var start=0;var ratio=Infinity;var track=function track(){return 0;};for(var _i17=0;_i17=0;i--){if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;}return c>3&&r&&Object.defineProperty(target,key,r),r;};var PROMPT_ANIMATION_TIME=5000;var wiggle=timeline(0,[{frames:6,value:0},{frames:5,value:-1},{frames:1,value:-1},{frames:8,value:1},{frames:1,value:1},{frames:5,value:0},{frames:12,value:0}]);var fade=timeline(0,[{frames:2,value:0},{frames:1,value:1},{frames:5,value:1},{frames:1,value:0},{frames:4,value:0}]);var DEFAULT_CAMERA_ORBIT='0deg 75deg 105%';var DEFAULT_CAMERA_TARGET='auto auto auto';var DEFAULT_FIELD_OF_VIEW='auto';var MINIMUM_RADIUS_RATIO=1.1*SAFE_RADIUS_RATIO;var AZIMUTHAL_QUADRANT_LABELS=['front','right','back','left'];var POLAR_TRIENT_LABELS=['upper-','','lower-'];var DEFAULT_INTERACTION_PROMPT_THRESHOLD=3000;var INTERACTION_PROMPT='Use mouse, touch or arrow keys to control the camera!';var InteractionPromptStrategy={AUTO:'auto',WHEN_FOCUSED:'when-focused',NONE:'none'};var InteractionPromptStyle={BASIC:'basic',WIGGLE:'wiggle'};var InteractionPolicy={ALWAYS_ALLOW:'always-allow',WHEN_FOCUSED:'allow-when-focused'};var fieldOfViewIntrinsics=function fieldOfViewIntrinsics(element){return{basis:[numberNode(element[$zoomAdjustedFieldOfView]*Math.PI/180,'rad')],keywords:{auto:[null]}};};var minFieldOfViewIntrinsics={basis:[degreesToRadians(numberNode(25,'deg'))],keywords:{auto:[null]}};var maxFieldOfViewIntrinsics=function maxFieldOfViewIntrinsics(element){var scene=element[$scene];return{basis:[degreesToRadians(numberNode(45,'deg'))],keywords:{auto:[numberNode(scene.framedFieldOfView,'deg')]}};};var cameraOrbitIntrinsics=function(){var defaultTerms=parseExpressions(DEFAULT_CAMERA_ORBIT)[0].terms;var theta=normalizeUnit(defaultTerms[0]);var phi=normalizeUnit(defaultTerms[1]);return function(element){var radius=element[$scene].model.idealCameraDistance;return{basis:[theta,phi,numberNode(radius,'m')],keywords:{auto:[null,null,numberNode(105,'%')]}};};}();var minCameraOrbitIntrinsics=function minCameraOrbitIntrinsics(element){var radius=MINIMUM_RADIUS_RATIO*element[$scene].model.idealCameraDistance;return{basis:[numberNode(-Infinity,'rad'),numberNode(Math.PI/8,'rad'),numberNode(radius,'m')],keywords:{auto:[null,null,null]}};};var maxCameraOrbitIntrinsics=function maxCameraOrbitIntrinsics(element){var orbitIntrinsics=cameraOrbitIntrinsics(element);var evaluator=new StyleEvaluator([],orbitIntrinsics);var defaultRadius=evaluator.evaluate()[2];return{basis:[numberNode(Infinity,'rad'),numberNode(Math.PI-Math.PI/8,'rad'),numberNode(defaultRadius,'m')],keywords:{auto:[null,null,null]}};};var cameraTargetIntrinsics=function cameraTargetIntrinsics(element){var center=element[$scene].model.boundingBox.getCenter(new Vector3());return{basis:[numberNode(center.x,'m'),numberNode(center.y,'m'),numberNode(center.z,'m')],keywords:{auto:[null,null,null]}};};var HALF_PI=Math.PI/2.0;var THIRD_PI=Math.PI/3.0;var QUARTER_PI=HALF_PI/2.0;var TAU=2.0*Math.PI;var $controls=Symbol('controls');var $promptElement=Symbol('promptElement');var $promptAnimatedContainer=Symbol('promptAnimatedContainer');var $deferInteractionPrompt=Symbol('deferInteractionPrompt');var $updateAria=Symbol('updateAria');var $updateCameraForRadius=Symbol('updateCameraForRadius');var $blurHandler=Symbol('blurHandler');var $focusHandler=Symbol('focusHandler');var $changeHandler=Symbol('changeHandler');var $pointerChangeHandler=Symbol('pointerChangeHandler');var $onBlur=Symbol('onBlur');var $onFocus=Symbol('onFocus');var $onChange=Symbol('onChange');var $onPointerChange=Symbol('onPointerChange');var $waitingToPromptUser=Symbol('waitingToPromptUser');var $userHasInteracted=Symbol('userHasInteracted');var $promptElementVisibleTime=Symbol('promptElementVisibleTime');var $lastPromptOffset=Symbol('lastPromptOffset');var $focusedTime=Symbol('focusedTime');var $zoomAdjustedFieldOfView=Symbol('zoomAdjustedFieldOfView');var $lastSpherical=Symbol('lastSpherical');var $jumpCamera=Symbol('jumpCamera');var $initialized$1=Symbol('initialized');var $maintainThetaPhi=Symbol('maintainThetaPhi');var $syncCameraOrbit=Symbol('syncCameraOrbit');var $syncFieldOfView=Symbol('syncFieldOfView');var $syncCameraTarget=Symbol('syncCameraTarget');var $syncMinCameraOrbit=Symbol('syncMinCameraOrbit');var $syncMaxCameraOrbit=Symbol('syncMaxCameraOrbit');var $syncMinFieldOfView=Symbol('syncMinFieldOfView');var $syncMaxFieldOfView=Symbol('syncMaxFieldOfView');var ControlsMixin=function ControlsMixin(ModelViewerElement){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o,_p,_q,_r,_s;var ControlsModelViewerElement=/*#__PURE__*/function(_ModelViewerElement4){_inherits(ControlsModelViewerElement,_ModelViewerElement4);var _super25=_createSuper(ControlsModelViewerElement);function ControlsModelViewerElement(){var _this54;_classCallCheck(this,ControlsModelViewerElement);_this54=_super25.apply(this,arguments);_this54.cameraControls=false;_this54.cameraOrbit=DEFAULT_CAMERA_ORBIT;_this54.cameraTarget=DEFAULT_CAMERA_TARGET;_this54.fieldOfView=DEFAULT_FIELD_OF_VIEW;_this54.minCameraOrbit='auto';_this54.maxCameraOrbit='auto';_this54.minFieldOfView='auto';_this54.maxFieldOfView='auto';_this54.interactionPromptThreshold=DEFAULT_INTERACTION_PROMPT_THRESHOLD;_this54.interactionPromptStyle=InteractionPromptStyle.WIGGLE;_this54.interactionPrompt=InteractionPromptStrategy.AUTO;_this54.interactionPolicy=InteractionPolicy.ALWAYS_ALLOW;_this54[_a]=_this54.shadowRoot.querySelector('.interaction-prompt');_this54[_b]=_this54.shadowRoot.querySelector('.interaction-prompt > .animated-container');_this54[_c]=Infinity;_this54[_d]=0;_this54[_e]=Infinity;_this54[_f]=false;_this54[_g]=false;_this54[_h]=new SmoothControls(_this54[$scene].camera,_this54[$userInputElement]);_this54[_j]=0;_this54[_k]=new Spherical();_this54[_l]=false;_this54[_m]=false;_this54[_o]=false;_this54[_p]=function(event){return _this54[$onChange](event);};_this54[_q]=function(event){return _this54[$onPointerChange](event);};_this54[_r]=function(){return _this54[$onFocus]();};_this54[_s]=function(){return _this54[$onBlur]();};return _this54;}_createClass(ControlsModelViewerElement,[{key:"getCameraOrbit",value:function getCameraOrbit(){var _this$$lastSpherical=this[$lastSpherical],theta=_this$$lastSpherical.theta,phi=_this$$lastSpherical.phi,radius=_this$$lastSpherical.radius;return{theta:theta,phi:phi,radius:radius};}},{key:"getCameraTarget",value:function getCameraTarget(){return this[$scene].getTarget();}},{key:"getFieldOfView",value:function getFieldOfView(){return this[$controls].getFieldOfView();}},{key:"getMinimumFieldOfView",value:function getMinimumFieldOfView(){return this[$controls].options.minimumFieldOfView;}},{key:"getMaximumFieldOfView",value:function getMaximumFieldOfView(){return this[$controls].options.maximumFieldOfView;}},{key:"jumpCameraToGoal",value:function jumpCameraToGoal(){this[$jumpCamera]=true;this.requestUpdate($jumpCamera,false);}},{key:"resetInteractionPrompt",value:function resetInteractionPrompt(){this[$lastPromptOffset]=0;this[$promptElementVisibleTime]=Infinity;this[$userHasInteracted]=false;this[$waitingToPromptUser]=this.interactionPrompt===InteractionPromptStrategy.AUTO&&this.cameraControls;}},{key:"connectedCallback",value:function connectedCallback(){_get(_getPrototypeOf(ControlsModelViewerElement.prototype),"connectedCallback",this).call(this);this[$controls].addEventListener('change',this[$changeHandler]);this[$controls].addEventListener('pointer-change-start',this[$pointerChangeHandler]);this[$controls].addEventListener('pointer-change-end',this[$pointerChangeHandler]);}},{key:"disconnectedCallback",value:function disconnectedCallback(){_get(_getPrototypeOf(ControlsModelViewerElement.prototype),"disconnectedCallback",this).call(this);this[$controls].removeEventListener('change',this[$changeHandler]);this[$controls].removeEventListener('pointer-change-start',this[$pointerChangeHandler]);this[$controls].removeEventListener('pointer-change-end',this[$pointerChangeHandler]);}},{key:"updated",value:function updated(changedProperties){var _this55=this;_get(_getPrototypeOf(ControlsModelViewerElement.prototype),"updated",this).call(this,changedProperties);var controls=this[$controls];var input=this[$userInputElement];if(changedProperties.has('cameraControls')){if(this.cameraControls){controls.enableInteraction();if(this.interactionPrompt===InteractionPromptStrategy.AUTO){this[$waitingToPromptUser]=true;}input.addEventListener('focus',this[$focusHandler]);input.addEventListener('blur',this[$blurHandler]);}else{input.removeEventListener('focus',this[$focusHandler]);input.removeEventListener('blur',this[$blurHandler]);controls.disableInteraction();this[$deferInteractionPrompt]();}}if(changedProperties.has('interactionPrompt')||changedProperties.has('cameraControls')||changedProperties.has('src')){if(this.interactionPrompt===InteractionPromptStrategy.AUTO&&this.cameraControls&&!this[$userHasInteracted]){this[$waitingToPromptUser]=true;}else{this[$deferInteractionPrompt]();}}if(changedProperties.has('interactionPromptStyle')){this[$promptElement].classList.toggle('wiggle',this.interactionPromptStyle===InteractionPromptStyle.WIGGLE);}if(changedProperties.has('interactionPolicy')){var interactionPolicy=this.interactionPolicy;controls.applyOptions({interactionPolicy:interactionPolicy});}if(this[$jumpCamera]===true){Promise.resolve().then(function(){_this55[$controls].jumpToGoal();_this55[$scene].jumpToGoal();_this55[$jumpCamera]=false;});}}},{key:(_a=$promptElement,_b=$promptAnimatedContainer,_c=$focusedTime,_d=$lastPromptOffset,_e=$promptElementVisibleTime,_f=$userHasInteracted,_g=$waitingToPromptUser,_h=$controls,_j=$zoomAdjustedFieldOfView,_k=$lastSpherical,_l=$jumpCamera,_m=$initialized$1,_o=$maintainThetaPhi,_p=$changeHandler,_q=$pointerChangeHandler,_r=$focusHandler,_s=$blurHandler,$syncFieldOfView),value:function value(style$$1){this[$controls].setFieldOfView(style$$1[0]*180/Math.PI);}},{key:$syncCameraOrbit,value:function value(style$$1){if(this[$maintainThetaPhi]){var _this$getCameraOrbit=this.getCameraOrbit(),theta=_this$getCameraOrbit.theta,phi=_this$getCameraOrbit.phi;style$$1[0]=theta;style$$1[1]=phi;this[$maintainThetaPhi]=false;}this[$controls].setOrbit(style$$1[0],style$$1[1],style$$1[2]);}},{key:$syncMinCameraOrbit,value:function value(style$$1){this[$controls].applyOptions({minimumAzimuthalAngle:style$$1[0],minimumPolarAngle:style$$1[1],minimumRadius:style$$1[2]});this.jumpCameraToGoal();}},{key:$syncMaxCameraOrbit,value:function value(style$$1){this[$controls].applyOptions({maximumAzimuthalAngle:style$$1[0],maximumPolarAngle:style$$1[1],maximumRadius:style$$1[2]});this[$updateCameraForRadius](style$$1[2]);this.jumpCameraToGoal();}},{key:$syncMinFieldOfView,value:function value(style$$1){this[$controls].applyOptions({minimumFieldOfView:style$$1[0]*180/Math.PI});this.jumpCameraToGoal();}},{key:$syncMaxFieldOfView,value:function value(style$$1){this[$controls].applyOptions({maximumFieldOfView:style$$1[0]*180/Math.PI});this.jumpCameraToGoal();}},{key:$syncCameraTarget,value:function value(style$$1){var _style$$=_slicedToArray(style$$1,3),x=_style$$[0],y=_style$$[1],z=_style$$[2];this[$scene].setTarget(x,y,z);this[$renderer].arRenderer.updateTarget();}},{key:$tick$1,value:function value(time,delta){_get(_getPrototypeOf(ControlsModelViewerElement.prototype),$tick$1,this).call(this,time,delta);if(this[$renderer].isPresenting||!this.modelIsVisible){return;}var now=performance.now();if(this[$waitingToPromptUser]){var thresholdTime=this.interactionPrompt===InteractionPromptStrategy.AUTO?this[$loadedTime]:this[$focusedTime];if(this.loaded&&now>thresholdTime+this.interactionPromptThreshold){this[$userInputElement].setAttribute('aria-label',INTERACTION_PROMPT);this[$waitingToPromptUser]=false;this[$promptElementVisibleTime]=now;this[$promptElement].classList.add('visible');}}if(isFinite(this[$promptElementVisibleTime])&&this.interactionPromptStyle===InteractionPromptStyle.WIGGLE){var scene=this[$scene];var animationTime=(now-this[$promptElementVisibleTime])/PROMPT_ANIMATION_TIME%1;var offset=wiggle(animationTime);var opacity=fade(animationTime);this[$promptAnimatedContainer].style.opacity="".concat(opacity);if(offset!==this[$lastPromptOffset]){var xOffset=offset*scene.width*0.05;var deltaTheta=(offset-this[$lastPromptOffset])*Math.PI/16;this[$promptAnimatedContainer].style.transform="translateX(".concat(xOffset,"px)");this[$controls].adjustOrbit(deltaTheta,0,0);this[$lastPromptOffset]=offset;}}this[$controls].update(time,delta);this[$scene].updateTarget(delta);}},{key:$deferInteractionPrompt,value:function value(){this[$waitingToPromptUser]=false;this[$promptElement].classList.remove('visible');this[$promptElementVisibleTime]=Infinity;}},{key:$updateCameraForRadius,value:function value(radius){var idealCameraDistance=this[$scene].model.idealCameraDistance;var maximumRadius=Math.max(idealCameraDistance,radius);var near=0;var far=2*maximumRadius;this[$controls].updateNearFar(near,far);}},{key:$updateAria,value:function value(){var _this$$lastSpherical2=this[$lastSpherical],lastTheta=_this$$lastSpherical2.theta,lastPhi=_this$$lastSpherical2.phi;var _this$$controls$getCa=this[$controls].getCameraSpherical(this[$lastSpherical]),theta=_this$$controls$getCa.theta,phi=_this$$controls$getCa.phi;var rootNode=this.getRootNode();if(rootNode!=null&&rootNode.activeElement===this){var lastAzimuthalQuadrant=(4+Math.floor((lastTheta%TAU+QUARTER_PI)/HALF_PI))%4;var azimuthalQuadrant=(4+Math.floor((theta%TAU+QUARTER_PI)/HALF_PI))%4;var lastPolarTrient=Math.floor(lastPhi/THIRD_PI);var polarTrient=Math.floor(phi/THIRD_PI);if(azimuthalQuadrant!==lastAzimuthalQuadrant||polarTrient!==lastPolarTrient){var azimuthalQuadrantLabel=AZIMUTHAL_QUADRANT_LABELS[azimuthalQuadrant];var polarTrientLabel=POLAR_TRIENT_LABELS[polarTrient];var ariaLabel="View from stage ".concat(polarTrientLabel).concat(azimuthalQuadrantLabel);this[$userInputElement].setAttribute('aria-label',ariaLabel);}}}},{key:$onResize,value:function value(event){var controls=this[$controls];var oldFramedFieldOfView=this[$scene].framedFieldOfView;_get(_getPrototypeOf(ControlsModelViewerElement.prototype),$onResize,this).call(this,event);var newFramedFieldOfView=this[$scene].framedFieldOfView;var zoom=controls.getFieldOfView()/oldFramedFieldOfView;this[$zoomAdjustedFieldOfView]=newFramedFieldOfView*zoom;controls.updateAspect(this[$scene].aspect);this.requestUpdate('maxFieldOfView',this.maxFieldOfView);this.requestUpdate('fieldOfView',this.fieldOfView);this.jumpCameraToGoal();}},{key:$onModelLoad,value:function value(){_get(_getPrototypeOf(ControlsModelViewerElement.prototype),$onModelLoad,this).call(this);var framedFieldOfView=this[$scene].framedFieldOfView;this[$zoomAdjustedFieldOfView]=framedFieldOfView;if(this[$initialized$1]){this[$maintainThetaPhi]=true;}else{this[$initialized$1]=true;}this.requestUpdate('maxFieldOfView',this.maxFieldOfView);this.requestUpdate('fieldOfView',this.fieldOfView);this.requestUpdate('minCameraOrbit',this.minCameraOrbit);this.requestUpdate('maxCameraOrbit',this.maxCameraOrbit);this.requestUpdate('cameraOrbit',this.cameraOrbit);this.requestUpdate('cameraTarget',this.cameraTarget);this.jumpCameraToGoal();}},{key:$onFocus,value:function value(){var input=this[$userInputElement];if(!isFinite(this[$focusedTime])){this[$focusedTime]=performance.now();}var ariaLabel=this[$ariaLabel];if(input.getAttribute('aria-label')!==ariaLabel){input.setAttribute('aria-label',ariaLabel);}if(this.interactionPrompt===InteractionPromptStrategy.WHEN_FOCUSED&&!this[$userHasInteracted]){this[$waitingToPromptUser]=true;}}},{key:$onBlur,value:function value(){if(this.interactionPrompt!==InteractionPromptStrategy.WHEN_FOCUSED){return;}this[$waitingToPromptUser]=false;this[$promptElement].classList.remove('visible');this[$promptElementVisibleTime]=Infinity;this[$focusedTime]=Infinity;}},{key:$onChange,value:function value(_ref8){var source=_ref8.source;this[$updateAria]();this[$needsRender]();if(source===ChangeSource.USER_INTERACTION){this[$userHasInteracted]=true;this[$deferInteractionPrompt]();}this.dispatchEvent(new CustomEvent('camera-change',{detail:{source:source}}));}},{key:$onPointerChange,value:function value(event){if(event.type==='pointer-change-start'){this[$container].classList.add('pointer-tumbling');}else{this[$container].classList.remove('pointer-tumbling');}}}]);return ControlsModelViewerElement;}(ModelViewerElement);__decorate$3([property({type:Boolean,attribute:'camera-controls'})],ControlsModelViewerElement.prototype,"cameraControls",void 0);__decorate$3([style({intrinsics:cameraOrbitIntrinsics,observeEffects:true,updateHandler:$syncCameraOrbit}),property({type:String,attribute:'camera-orbit',hasChanged:function hasChanged(){return true;}})],ControlsModelViewerElement.prototype,"cameraOrbit",void 0);__decorate$3([style({intrinsics:cameraTargetIntrinsics,observeEffects:true,updateHandler:$syncCameraTarget}),property({type:String,attribute:'camera-target',hasChanged:function hasChanged(){return true;}})],ControlsModelViewerElement.prototype,"cameraTarget",void 0);__decorate$3([style({intrinsics:fieldOfViewIntrinsics,observeEffects:true,updateHandler:$syncFieldOfView}),property({type:String,attribute:'field-of-view',hasChanged:function hasChanged(){return true;}})],ControlsModelViewerElement.prototype,"fieldOfView",void 0);__decorate$3([style({intrinsics:minCameraOrbitIntrinsics,updateHandler:$syncMinCameraOrbit}),property({type:String,attribute:'min-camera-orbit',hasChanged:function hasChanged(){return true;}})],ControlsModelViewerElement.prototype,"minCameraOrbit",void 0);__decorate$3([style({intrinsics:maxCameraOrbitIntrinsics,updateHandler:$syncMaxCameraOrbit}),property({type:String,attribute:'max-camera-orbit',hasChanged:function hasChanged(){return true;}})],ControlsModelViewerElement.prototype,"maxCameraOrbit",void 0);__decorate$3([style({intrinsics:minFieldOfViewIntrinsics,updateHandler:$syncMinFieldOfView}),property({type:String,attribute:'min-field-of-view',hasChanged:function hasChanged(){return true;}})],ControlsModelViewerElement.prototype,"minFieldOfView",void 0);__decorate$3([style({intrinsics:maxFieldOfViewIntrinsics,updateHandler:$syncMaxFieldOfView}),property({type:String,attribute:'max-field-of-view',hasChanged:function hasChanged(){return true;}})],ControlsModelViewerElement.prototype,"maxFieldOfView",void 0);__decorate$3([property({type:Number,attribute:'interaction-prompt-threshold'})],ControlsModelViewerElement.prototype,"interactionPromptThreshold",void 0);__decorate$3([property({type:String,attribute:'interaction-prompt-style'})],ControlsModelViewerElement.prototype,"interactionPromptStyle",void 0);__decorate$3([property({type:String,attribute:'interaction-prompt'})],ControlsModelViewerElement.prototype,"interactionPrompt",void 0);__decorate$3([property({type:String,attribute:'interaction-policy'})],ControlsModelViewerElement.prototype,"interactionPolicy",void 0);return ControlsModelViewerElement;};var __decorate$4=undefined&&undefined.__decorate||function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if((typeof Reflect==="undefined"?"undefined":_typeof(Reflect))==="object"&&typeof undefined==="function")r=undefined(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--){if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;}return c>3&&r&&Object.defineProperty(target,key,r),r;};var BASE_OPACITY=0.1;var DEFAULT_SHADOW_INTENSITY=0.0;var DEFAULT_SHADOW_SOFTNESS=1.0;var DEFAULT_EXPOSURE=1.0;var $currentEnvironmentMap=Symbol('currentEnvironmentMap');var $applyEnvironmentMap=Symbol('applyEnvironmentMap');var $updateEnvironment=Symbol('updateEnvironment');var $cancelEnvironmentUpdate=Symbol('cancelEnvironmentUpdate');var $onPreload=Symbol('onPreload');var EnvironmentMixin=function EnvironmentMixin(ModelViewerElement){var _a,_b,_c;var EnvironmentModelViewerElement=/*#__PURE__*/function(_ModelViewerElement5){_inherits(EnvironmentModelViewerElement,_ModelViewerElement5);var _super26=_createSuper(EnvironmentModelViewerElement);function EnvironmentModelViewerElement(){var _this56;_classCallCheck(this,EnvironmentModelViewerElement);_this56=_super26.apply(this,arguments);_this56.environmentImage=null;_this56.skyboxImage=null;_this56.shadowIntensity=DEFAULT_SHADOW_INTENSITY;_this56.shadowSoftness=DEFAULT_SHADOW_SOFTNESS;_this56.exposure=DEFAULT_EXPOSURE;_this56[_a]=null;_this56[_b]=null;_this56[_c]=function(event){if(event.element===_assertThisInitialized(_this56)){_this56[$updateEnvironment]();}};return _this56;}_createClass(EnvironmentModelViewerElement,[{key:"connectedCallback",value:function connectedCallback(){_get(_getPrototypeOf(EnvironmentModelViewerElement.prototype),"connectedCallback",this).call(this);this[$renderer].loader.addEventListener('preload',this[$onPreload]);}},{key:"disconnectedCallback",value:function disconnectedCallback(){_get(_getPrototypeOf(EnvironmentModelViewerElement.prototype),"disconnectedCallback",this).call(this);this[$renderer].loader.removeEventListener('preload',this[$onPreload]);}},{key:"updated",value:function updated(changedProperties){_get(_getPrototypeOf(EnvironmentModelViewerElement.prototype),"updated",this).call(this,changedProperties);if(changedProperties.has('shadowIntensity')){this[$scene].setShadowIntensity(this.shadowIntensity*BASE_OPACITY);this[$needsRender]();}if(changedProperties.has('shadowSoftness')){this[$scene].setShadowSoftness(this.shadowSoftness);this[$needsRender]();}if(changedProperties.has('exposure')){this[$scene].exposure=this.exposure;this[$needsRender]();}if((changedProperties.has('environmentImage')||changedProperties.has('skyboxImage'))&&this[$shouldAttemptPreload]()){this[$updateEnvironment]();}}},{key:(_a=$currentEnvironmentMap,_b=$cancelEnvironmentUpdate,_c=$onPreload,$onModelLoad),value:function value(){_get(_getPrototypeOf(EnvironmentModelViewerElement.prototype),$onModelLoad,this).call(this);if(this[$currentEnvironmentMap]!=null){this[$applyEnvironmentMap](this[$currentEnvironmentMap]);}}},{key:$updateEnvironment,value:function(){var _value5=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee25(){var _this57=this;var skyboxImage,environmentImage,textureUtils,_yield$Promise,environmentMap,skybox;return regeneratorRuntime.wrap(function _callee25$(_context26){while(1){switch(_context26.prev=_context26.next){case 0:skyboxImage=this.skyboxImage,environmentImage=this.environmentImage;if(this[$cancelEnvironmentUpdate]!=null){this[$cancelEnvironmentUpdate]();this[$cancelEnvironmentUpdate]=null;}textureUtils=this[$renderer].textureUtils;if(!(textureUtils==null)){_context26.next=5;break;}return _context26.abrupt("return");case 5:_context26.prev=5;_context26.next=8;return new Promise(/*#__PURE__*/function(){var _ref9=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee24(resolve,reject){var texturesLoad;return regeneratorRuntime.wrap(function _callee24$(_context25){while(1){switch(_context25.prev=_context25.next){case 0:texturesLoad=textureUtils.generateEnvironmentMapAndSkybox(deserializeUrl(skyboxImage),deserializeUrl(environmentImage),{progressTracker:_this57[$progressTracker]});_this57[$cancelEnvironmentUpdate]=function(){return reject(texturesLoad);};_context25.t0=resolve;_context25.next=5;return texturesLoad;case 5:_context25.t1=_context25.sent;(0,_context25.t0)(_context25.t1);case 7:case"end":return _context25.stop();}}},_callee24);}));return function(_x23,_x24){return _ref9.apply(this,arguments);};}());case 8:_yield$Promise=_context26.sent;environmentMap=_yield$Promise.environmentMap;skybox=_yield$Promise.skybox;if(skybox!=null){this[$scene].background=skybox.texture;}else{this[$scene].background=null;}this[$applyEnvironmentMap](environmentMap.texture);this[$scene].model.dispatchEvent({type:'envmap-update'});_context26.next=21;break;case 16:_context26.prev=16;_context26.t0=_context26["catch"](5);if(!_instanceof(_context26.t0,Error)){_context26.next=21;break;}this[$applyEnvironmentMap](null);throw _context26.t0;case 21:case"end":return _context26.stop();}}},_callee25,this,[[5,16]]);}));function value(){return _value5.apply(this,arguments);}return value;}()},{key:$applyEnvironmentMap,value:function value(environmentMap){this[$currentEnvironmentMap]=environmentMap;this[$scene].environment=this[$currentEnvironmentMap];this.dispatchEvent(new CustomEvent('environment-change'));this[$needsRender]();}}]);return EnvironmentModelViewerElement;}(ModelViewerElement);__decorate$4([property({type:String,attribute:'environment-image'})],EnvironmentModelViewerElement.prototype,"environmentImage",void 0);__decorate$4([property({type:String,attribute:'skybox-image'})],EnvironmentModelViewerElement.prototype,"skyboxImage",void 0);__decorate$4([property({type:Number,attribute:'shadow-intensity'})],EnvironmentModelViewerElement.prototype,"shadowIntensity",void 0);__decorate$4([property({type:Number,attribute:'shadow-softness'})],EnvironmentModelViewerElement.prototype,"shadowSoftness",void 0);__decorate$4([property({type:Number})],EnvironmentModelViewerElement.prototype,"exposure",void 0);return EnvironmentModelViewerElement;};var _a$e,_b$c;var INITIAL_STATUS_ANNOUNCEMENT='This page includes one or more 3D models that are loading';var FINISHED_LOADING_ANNOUNCEMENT='All 3D models in the page have loaded';var UPDATE_STATUS_DEBOUNCE_MS=100;var $modelViewerStatusInstance=Symbol('modelViewerStatusInstance');var $updateStatus=Symbol('updateStatus');var LoadingStatusAnnouncer=/*#__PURE__*/function(_EventDispatcher6){_inherits(LoadingStatusAnnouncer,_EventDispatcher6);var _super27=_createSuper(LoadingStatusAnnouncer);function LoadingStatusAnnouncer(){var _this58;_classCallCheck(this,LoadingStatusAnnouncer);_this58=_super27.call(this);_this58[_a$e]=null;_this58.registeredInstanceStatuses=new Map();_this58.loadingPromises=[];_this58.statusElement=document.createElement('p');_this58.statusUpdateInProgress=false;_this58[_b$c]=debounce(function(){return _this58.updateStatus();},UPDATE_STATUS_DEBOUNCE_MS);var _assertThisInitialize=_assertThisInitialized(_this58),statusElement=_assertThisInitialize.statusElement;var style=statusElement.style;statusElement.setAttribute('role','status');statusElement.classList.add('screen-reader-only');style.top=style.left='0';style.pointerEvents='none';return _this58;}_createClass(LoadingStatusAnnouncer,[{key:"registerInstance",value:function registerInstance(modelViewer){if(this.registeredInstanceStatuses.has(modelViewer)){return;}var onUnregistered=function onUnregistered(){};var loadShouldBeMeasured=modelViewer.loaded===false&&!!modelViewer.src;var loadAttemptCompletes=new Promise(function(resolve){if(!loadShouldBeMeasured){resolve();return;}var resolveHandler=function resolveHandler(){resolve();modelViewer.removeEventListener('load',resolveHandler);modelViewer.removeEventListener('error',resolveHandler);};modelViewer.addEventListener('load',resolveHandler);modelViewer.addEventListener('error',resolveHandler);onUnregistered=resolveHandler;});this.registeredInstanceStatuses.set(modelViewer,{onUnregistered:onUnregistered});this.loadingPromises.push(loadAttemptCompletes);if(this.modelViewerStatusInstance==null){this.modelViewerStatusInstance=modelViewer;}}},{key:"unregisterInstance",value:function unregisterInstance(modelViewer){if(!this.registeredInstanceStatuses.has(modelViewer)){return;}var statuses=this.registeredInstanceStatuses;var instanceStatus=statuses.get(modelViewer);statuses.delete(modelViewer);instanceStatus.onUnregistered();if(this.modelViewerStatusInstance===modelViewer){this.modelViewerStatusInstance=statuses.size>0?getFirstMapKey(statuses):null;}}},{key:"updateStatus",value:function(){var _updateStatus=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee26(){var loadingPromises;return regeneratorRuntime.wrap(function _callee26$(_context27){while(1){switch(_context27.prev=_context27.next){case 0:if(!(this.statusUpdateInProgress||this.loadingPromises.length===0)){_context27.next=2;break;}return _context27.abrupt("return");case 2:this.statusElement.textContent=INITIAL_STATUS_ANNOUNCEMENT;this.statusUpdateInProgress=true;this.dispatchEvent({type:'initial-status-announced'});case 5:if(!this.loadingPromises.length){_context27.next=12;break;}loadingPromises=this.loadingPromises;this.loadingPromises=[];_context27.next=10;return Promise.all(loadingPromises);case 10:_context27.next=5;break;case 12:this.statusElement.textContent=FINISHED_LOADING_ANNOUNCEMENT;this.statusUpdateInProgress=false;this.dispatchEvent({type:'finished-loading-announced'});case 15:case"end":return _context27.stop();}}},_callee26,this);}));function updateStatus(){return _updateStatus.apply(this,arguments);}return updateStatus;}()},{key:"modelViewerStatusInstance",get:function get(){return this[$modelViewerStatusInstance];},set:function set(value){var currentInstance=this[$modelViewerStatusInstance];if(currentInstance===value){return;}var statusElement=this.statusElement;if(value!=null&&value.shadowRoot!=null){value.shadowRoot.appendChild(statusElement);}else if(statusElement.parentNode!=null){statusElement.parentNode.removeChild(statusElement);}this[$modelViewerStatusInstance]=value;this[$updateStatus]();}}]);return LoadingStatusAnnouncer;}(EventDispatcher);_a$e=$modelViewerStatusInstance,_b$c=$updateStatus;var __decorate$5=undefined&&undefined.__decorate||function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if((typeof Reflect==="undefined"?"undefined":_typeof(Reflect))==="object"&&typeof undefined==="function")r=undefined(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--){if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;}return c>3&&r&&Object.defineProperty(target,key,r),r;};var PROGRESS_BAR_UPDATE_THRESHOLD=100;var PROGRESS_MASK_BASE_OPACITY=0.2;var DEFAULT_DRACO_DECODER_LOCATION='https://www.gstatic.com/draco/versioned/decoders/1.3.5/';var SPACE_KEY=32;var ENTER_KEY=13;var RevealStrategy={AUTO:'auto',INTERACTION:'interaction',MANUAL:'manual'};var LoadingStrategy={AUTO:'auto',LAZY:'lazy',EAGER:'eager'};var PosterDismissalSource={INTERACTION:'interaction'};var loadingStatusAnnouncer=new LoadingStatusAnnouncer();var $defaultProgressBarElement=Symbol('defaultProgressBarElement');var $defaultProgressMaskElement=Symbol('defaultProgressMaskElement');var $posterContainerElement=Symbol('posterContainerElement');var $defaultPosterElement=Symbol('defaultPosterElement');var $posterDismissalSource=Symbol('posterDismissalSource');var $showPoster=Symbol('showPoster');var $hidePoster=Symbol('hidePoster');var $modelIsRevealed=Symbol('modelIsRevealed');var $updateProgressBar=Symbol('updateProgressBar');var $lastReportedProgress=Symbol('lastReportedProgress');var $ariaLabelCallToAction=Symbol('ariaLabelCallToAction');var $clickHandler=Symbol('clickHandler');var $keydownHandler=Symbol('keydownHandler');var $progressHandler=Symbol('processHandler');var $onClick=Symbol('onClick');var $onKeydown=Symbol('onKeydown');var $onProgress=Symbol('onProgress');var LoadingMixin=function LoadingMixin(ModelViewerElement){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m;var LoadingModelViewerElement=/*#__PURE__*/function(_ModelViewerElement6){_inherits(LoadingModelViewerElement,_ModelViewerElement6);var _super28=_createSuper(LoadingModelViewerElement);function LoadingModelViewerElement(){var _this59;_classCallCheck(this,LoadingModelViewerElement);for(var _len3=arguments.length,args=new Array(_len3),_key3=0;_key3<_len3;_key3++){args[_key3]=arguments[_key3];}_this59=_super28.call.apply(_super28,[this].concat(args));_this59.poster=null;_this59.reveal=RevealStrategy.AUTO;_this59.loading=LoadingStrategy.AUTO;_this59[_a]=false;_this59[_b]=0;_this59[_c]=null;_this59[_d]=_this59.shadowRoot.querySelector('.slot.poster');_this59[_e]=_this59.shadowRoot.querySelector('#default-poster');_this59[_f]=_this59.shadowRoot.querySelector('#default-progress-bar > .bar');_this59[_g]=_this59.shadowRoot.querySelector('#default-progress-bar > .mask');_this59[_h]=_this59[$defaultPosterElement].getAttribute('aria-label');_this59[_j]=function(){return _this59[$onClick]();};_this59[_k]=function(event){return _this59[$onKeydown](event);};_this59[_l]=function(event){return _this59[$onProgress](event);};_this59[_m]=throttle(function(progress){var parentNode=_this59[$defaultProgressBarElement].parentNode;requestAnimationFrame(function(){_this59[$defaultProgressMaskElement].style.opacity="".concat((1.0-progress)*PROGRESS_MASK_BASE_OPACITY);_this59[$defaultProgressBarElement].style.transform="scaleX(".concat(progress,")");if(progress===0){parentNode.removeChild(_this59[$defaultProgressBarElement]);parentNode.appendChild(_this59[$defaultProgressBarElement]);}if(progress===1.0){_this59[$defaultProgressBarElement].classList.add('hide');}else{_this59[$defaultProgressBarElement].classList.remove('hide');}});},PROGRESS_BAR_UPDATE_THRESHOLD);var ModelViewerElement=self.ModelViewerElement||{};var dracoDecoderLocation=ModelViewerElement.dracoDecoderLocation||DEFAULT_DRACO_DECODER_LOCATION;CachingGLTFLoader.setDRACODecoderLocation(dracoDecoderLocation);return _this59;}_createClass(LoadingModelViewerElement,[{key:"dismissPoster",value:function dismissPoster(){if(this[$sceneIsReady]()){this[$hidePoster]();}else{this[$posterDismissalSource]=PosterDismissalSource.INTERACTION;this[$updateSource]();}}},{key:"connectedCallback",value:function connectedCallback(){_get(_getPrototypeOf(LoadingModelViewerElement.prototype),"connectedCallback",this).call(this);this[$posterContainerElement].addEventListener('click',this[$clickHandler]);this[$posterContainerElement].addEventListener('keydown',this[$keydownHandler]);this[$progressTracker].addEventListener('progress',this[$progressHandler]);loadingStatusAnnouncer.registerInstance(this);}},{key:"disconnectedCallback",value:function disconnectedCallback(){_get(_getPrototypeOf(LoadingModelViewerElement.prototype),"disconnectedCallback",this).call(this);this[$posterContainerElement].removeEventListener('click',this[$clickHandler]);this[$posterContainerElement].removeEventListener('keydown',this[$keydownHandler]);this[$progressTracker].removeEventListener('progress',this[$progressHandler]);loadingStatusAnnouncer.unregisterInstance(this);}},{key:"updated",value:function(){var _updated=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee27(changedProperties){return regeneratorRuntime.wrap(function _callee27$(_context28){while(1){switch(_context28.prev=_context28.next){case 0:_get(_getPrototypeOf(LoadingModelViewerElement.prototype),"updated",this).call(this,changedProperties);if(changedProperties.has('poster')&&this.poster!=null){this[$defaultPosterElement].style.backgroundImage="url(".concat(this.poster,")");}if(changedProperties.has('alt')){this[$defaultPosterElement].setAttribute('aria-label',"".concat(this[$ariaLabel],". ").concat(this[$ariaLabelCallToAction]));}if(changedProperties.has('reveal')||changedProperties.has('loaded')){if(!this[$sceneIsReady]()){this[$updateSource]();}}case 4:case"end":return _context28.stop();}}},_callee27,this);}));function updated(_x25){return _updated.apply(this,arguments);}return updated;}()},{key:(_a=$modelIsRevealed,_b=$lastReportedProgress,_c=$posterDismissalSource,_d=$posterContainerElement,_e=$defaultPosterElement,_f=$defaultProgressBarElement,_g=$defaultProgressMaskElement,_h=$ariaLabelCallToAction,_j=$clickHandler,_k=$keydownHandler,_l=$progressHandler,_m=$updateProgressBar,$onClick),value:function value(){if(this.reveal===RevealStrategy.MANUAL){return;}this.dismissPoster();}},{key:$onKeydown,value:function value(event){if(this.reveal===RevealStrategy.MANUAL){return;}switch(event.keyCode){case SPACE_KEY:case ENTER_KEY:this.dismissPoster();break;default:break;}}},{key:$onProgress,value:function value(event){var progress=event.detail.totalProgress;this[$lastReportedProgress]=Math.max(progress,this[$lastReportedProgress]);if(progress===1.0){this[$updateProgressBar].flush();if(this[$sceneIsReady]()&&(this[$posterDismissalSource]!=null||this.reveal===RevealStrategy.AUTO)){this[$hidePoster]();}}this[$updateProgressBar](progress);this.dispatchEvent(new CustomEvent('progress',{detail:{totalProgress:progress}}));}},{key:$shouldAttemptPreload,value:function value(){return!!this.src&&(this[$posterDismissalSource]!=null||this.loading===LoadingStrategy.EAGER||this.reveal===RevealStrategy.AUTO&&this[$isElementInViewport]);}},{key:$sceneIsReady,value:function value(){var src=this.src;return!!src&&_get(_getPrototypeOf(LoadingModelViewerElement.prototype),$sceneIsReady,this).call(this)&&this[$lastReportedProgress]===1.0;}},{key:$showPoster,value:function value(){var _this60=this;var posterContainerElement=this[$posterContainerElement];var defaultPosterElement=this[$defaultPosterElement];var posterContainerOpacity=parseFloat(self.getComputedStyle(posterContainerElement).opacity);defaultPosterElement.removeAttribute('tabindex');defaultPosterElement.removeAttribute('aria-hidden');posterContainerElement.classList.add('show');if(posterContainerOpacity<1.0){posterContainerElement.addEventListener('transitionend',function(){var oldVisibility=_this60.modelIsVisible;_this60[$modelIsRevealed]=false;_this60[$announceModelVisibility](oldVisibility);},{once:true});}}},{key:$hidePoster,value:function value(){var _this61=this;this[$posterDismissalSource]=null;var posterContainerElement=this[$posterContainerElement];var defaultPosterElement=this[$defaultPosterElement];if(posterContainerElement.classList.contains('show')){posterContainerElement.classList.remove('show');posterContainerElement.addEventListener('transitionend',function(){var oldVisibility=_this61.modelIsVisible;requestAnimationFrame(function(){_this61[$modelIsRevealed]=true;_this61[$announceModelVisibility](oldVisibility);var root=_this61.getRootNode();if(root&&root.activeElement===_this61){_this61[$userInputElement].focus();}defaultPosterElement.setAttribute('aria-hidden','true');defaultPosterElement.tabIndex=-1;});},{once:true});}}},{key:$getModelIsVisible,value:function value(){return _get(_getPrototypeOf(LoadingModelViewerElement.prototype),$getModelIsVisible,this).call(this)&&this[$modelIsRevealed];}},{key:$updateSource,value:function(){var _value6=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee28(){return regeneratorRuntime.wrap(function _callee28$(_context29){while(1){switch(_context29.prev=_context29.next){case 0:this[$lastReportedProgress]=0;this[$showPoster]();_context29.next=4;return _get(_getPrototypeOf(LoadingModelViewerElement.prototype),$updateSource,this).call(this);case 4:case"end":return _context29.stop();}}},_callee28,this);}));function value(){return _value6.apply(this,arguments);}return value;}()}],[{key:"mapURLs",value:function mapURLs(callback){Renderer.singleton.loader[$loader].manager.setURLModifier(callback);}},{key:"dracoDecoderLocation",set:function set(value){CachingGLTFLoader.setDRACODecoderLocation(value);},get:function get(){return CachingGLTFLoader.getDRACODecoderLocation();}}]);return LoadingModelViewerElement;}(ModelViewerElement);__decorate$5([property({type:String})],LoadingModelViewerElement.prototype,"poster",void 0);__decorate$5([property({type:String})],LoadingModelViewerElement.prototype,"reveal",void 0);__decorate$5([property({type:String})],LoadingModelViewerElement.prototype,"loading",void 0);return LoadingModelViewerElement;};/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */ /** * Adapted from WorkerDOM * @see https://github.com/ampproject/worker-dom/blob/master/src/worker-thread/index.amp.ts */var ALLOWLISTED_GLOBALS={Array:true,ArrayBuffer:true,BigInt:true,BigInt64Array:true,BigUint64Array:true,Boolean:true,Cache:true,CustomEvent:true,DataView:true,Date:true,Error:true,EvalError:true,Event:true,EventTarget:true,Float32Array:true,Float64Array:true,Function:true,Infinity:true,Int16Array:true,Int32Array:true,Int8Array:true,Intl:true,JSON:true,Map:true,Math:true,MessagePort:true,MessageEvent:true,MessageChannel:true,NaN:true,Number:true,Object:true,Promise:true,Proxy:true,RangeError:true,ReferenceError:true,Reflect:true,RegExp:true,Set:true,String:true,Symbol:true,SyntaxError:true,TextDecoder:true,TextEncoder:true,TypeError:true,URIError:true,URL:true,Uint16Array:true,Uint32Array:true,Uint8Array:true,Uint8ClampedArray:true,WeakMap:true,WeakSet:true,WebAssembly:true,atob:true,addEventListener:true,removeEventListener:true,btoa:true,caches:true,clearInterval:true,clearTimeout:true,console:true,decodeURI:true,decodeURIComponent:true,document:true,encodeURI:true,encodeURIComponent:true,escape:true,fetch:true,indexedDB:true,isFinite:true,isNaN:true,location:true,navigator:true,onerror:true,onrejectionhandled:true,onunhandledrejection:true,parseFloat:true,parseInt:true,performance:true,postMessage:true,requestAnimationFrame:true,cancelAnimationFrame:true,self:true,setTimeout:true,setInterval:true,unescape:true};/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */ /** * A constructor factory for a Image class. The Image is defined based on * a provided implementation for all specified 3DOM scene graph element types. * * The sole reason for using this factory pattern is to enable sound type * checking while also providing for the ability to stringify the factory so * that it can be part of a runtime-generated Worker script. * * @see ../api.ts */function defineImage(ThreeDOMElement){var $kernel=Symbol('kernel');var $uri=Symbol('uri');var $name=Symbol('name');var Image=/*#__PURE__*/function(_ThreeDOMElement){_inherits(Image,_ThreeDOMElement);var _super29=_createSuper(Image);function Image(kernel,serialized){var _this62;_classCallCheck(this,Image);_this62=_super29.call(this,kernel);_this62[$kernel]=kernel;_this62[$uri]=serialized.uri||null;_this62[$name]=serialized.name;return _this62;}_createClass(Image,[{key:"setURI",value:function(){var _setURI=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee29(uri){return regeneratorRuntime.wrap(function _callee29$(_context30){while(1){switch(_context30.prev=_context30.next){case 0:this[$kernel].mutate(this,'uri',uri);case 1:case"end":return _context30.stop();}}},_callee29,this);}));function setURI(_x26){return _setURI.apply(this,arguments);}return setURI;}()},{key:"name",get:function get(){return this[$name];}},{key:"type",get:function get(){return this.uri!=null?'external':'embedded';}},{key:"uri",get:function get(){return this[$uri];}}]);return Image;}(ThreeDOMElement);return Image;}/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */ /** * A constructor factory for a Material class. The Material is defined based on * a provided implementation for all specified 3DOM scene graph element types. * * The sole reason for using this factory pattern is to enable sound type * checking while also providing for the ability to stringify the factory so * that it can be part of a runtime-generated Worker script. * * @see ../api.ts */function defineMaterial(ThreeDOMElement){var _a,_b,_c;var $pbrMetallicRoughness=Symbol('pbrMetallicRoughness');var $normalTexture=Symbol('normalTexture');var $occlusionTexture=Symbol('occlusionTexture');var $emissiveTexture=Symbol('emissiveTexture');var $kernel=Symbol('kernel');var $name=Symbol('name');/** * A Material represents a live material in the backing scene graph. Its * primary purpose is to give the user write access to discrete properties * (for example, the base color factor) of the backing material. */var Material=/*#__PURE__*/function(_ThreeDOMElement2){_inherits(Material,_ThreeDOMElement2);var _super30=_createSuper(Material);function Material(kernel,serialized){var _this63;_classCallCheck(this,Material);_this63=_super30.call(this,kernel,serialized);_this63[_a]=null;_this63[_b]=null;_this63[_c]=null;_this63[$kernel]=kernel;if(serialized.name!=null){_this63[$name]=serialized.name;}var pbrMetallicRoughness=serialized.pbrMetallicRoughness,normalTexture=serialized.normalTexture,occlusionTexture=serialized.occlusionTexture,emissiveTexture=serialized.emissiveTexture;_this63[$pbrMetallicRoughness]=kernel.deserialize('pbr-metallic-roughness',pbrMetallicRoughness);if(normalTexture!=null){_this63[$normalTexture]=kernel.deserialize('texture-info',normalTexture);}if(occlusionTexture!=null){_this63[$occlusionTexture]=kernel.deserialize('texture-info',occlusionTexture);}if(emissiveTexture!=null){_this63[$emissiveTexture]=kernel.deserialize('texture-info',emissiveTexture);}return _this63;}/** * The PBR properties that are assigned to this material, if any. */_createClass(Material,[{key:"pbrMetallicRoughness",get:function get(){return this[$pbrMetallicRoughness];}},{key:"normalTexture",get:function get(){return this[$normalTexture];}},{key:"occlusionTexture",get:function get(){return this[$occlusionTexture];}},{key:"emissiveTexture",get:function get(){return this[$emissiveTexture];}/** * The name of the material. Note that names are optional and not * guaranteed to be unique. */},{key:"name",get:function get(){return this[$name];}}]);return Material;}(ThreeDOMElement);_a=$normalTexture,_b=$occlusionTexture,_c=$emissiveTexture;return Material;}/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */ /** * A constructor factory for a ModelKernel class. The ModelKernel is defined * based on a provided implementation for all specified 3DOM scene graph * element types. * * The sole reason for using this factory pattern is to enable sound type * checking while also providing for the ability to stringify the factory so * that it can be part of a runtime-generated Worker script. */function defineModelKernel(ThreeDOMMessageType,ThreeDOMElement,Model,Material,PBRMetallicRoughness,Sampler,Image,Texture,TextureInfo){var _a,_b,_c,_d,_e,_f;var constructorsByType={'model':Model,'material':Material,'pbr-metallic-roughness':PBRMetallicRoughness,'texture-info':TextureInfo,'sampler':Sampler,'image':Image,'texture':Texture};var $onMessageEvent=Symbol('onMessageEvent');var $messageEventHandler=Symbol('messageEventHandler');var $port=Symbol('port');var $model=Symbol('model');var $elementsByLocalId=Symbol('elementsByLocalId');var $localIdsByElement=Symbol('localIdsByElement');var $elementsByType=Symbol('elementsByType');var $pendingMutations=Symbol('pendingMutations');var $nextMutationId=Symbol('nextMutationId');/** * A ModelKernel is the core business logic implementation for a distinct * Model that has been exposed to a script execution context. The ModelKernel * is an internal detail, and should never be explicitly exposed to users of * a Model. * * The ModelKernel primarily handles deserializing scene graph elements, and * communicating mutations from the 3DOM execution context to the host * execution context where the backing scene graph lives. * * A ModelKernel also maintains a comprehensive map of elements by type to * assist scene graph elements in querying for their contemporaries. */var ModelKernel=/*#__PURE__*/function(){function ModelKernel(port,serialized){var _this64=this;_classCallCheck(this,ModelKernel);this[_a]=new Map();this[_b]=new Map();this[_c]=new Map();this[_d]=function(event){return _this64[$onMessageEvent](event);};this[_e]=new Map();this[_f]=0;var types=Object.keys(constructorsByType);for(var _i19=0,_types=types;_i19<_types.length;_i19++){var type=_types[_i19];this[$elementsByType].set(type,new Set());}this[$port]=port;this[$port].addEventListener('message',this[$messageEventHandler]);this[$port].start();this[$model]=this.deserialize('model',serialized);}/** * The root scene graph element, a Model, that is the entrypoint for the * entire scene graph that is backed by this kernel. */_createClass(ModelKernel,[{key:"mutate",/** * Mutate a property of a property of a given scene graph element. All * direct mutations of the scene graph are considered asynchronous. This * method returns a Promise that resolves when the mutation has been * successfully applied to the backing scene graph, and rejects if the * mutation failed or is otherwise not allowed. * * TODO(#1006): How to validate values? */value:function(){var _mutate=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee30(element,property,value){var _this65=this;var id;return regeneratorRuntime.wrap(function _callee30$(_context31){while(1){switch(_context31.prev=_context31.next){case 0:if(this[$localIdsByElement].has(element)){_context31.next=2;break;}throw new Error('Cannot mutate unknown element');case 2:id=this[$localIdsByElement].get(element);if(_instanceof(value,ThreeDOMElement)){value=this[$localIdsByElement].get(value);}return _context31.abrupt("return",new Promise(function(resolve,reject){var mutationId=_this65[$nextMutationId]++;// TODO(#1006): Validate mutations before sending to host context: _this65[$port].postMessage({type:ThreeDOMMessageType.MUTATE,id:id,property:property,value:value,mutationId:mutationId});// TODO(#1011): Add timeout to reject this mutation: _this65[$pendingMutations].set(mutationId,{resolve:resolve,reject:reject});}));case 5:case"end":return _context31.stop();}}},_callee30,this);}));function mutate(_x27,_x28,_x29){return _mutate.apply(this,arguments);}return mutate;}()/** * Deserializes a JSON representation of a scene graph element into a live * element that is backed by this ModelKernel. */},{key:"deserialize",value:function deserialize(type,serialized){if(!(type in constructorsByType)){throw new Error("Cannot deserialize unknown type: ".concat(type));}var id=serialized.id;// TODO: Add test to ensure that we don't double-deserialize elements if(this[$elementsByLocalId].has(id)){return this[$elementsByLocalId].get(id);}var ElementConstructor=constructorsByType[type];// eslint-disable-next-line @typescript-eslint/no-explicit-any var element=new ElementConstructor(this,serialized);this[$elementsByLocalId].set(id,element);this[$localIdsByElement].set(element,id);// We know that the all accepted types have been pre-populated in the // [$elementsByType] map: // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this[$elementsByType].get(type).add(element);return element;}/** * Look up all scene graph elements given a type string. Type strings * are lower-cased, hyphenated versions of the constructor names of their * corresponding classes. For example, a query for 'pbr-metallic-roughness' * element types will yield the list of PBRMetallicRoughness elements in * sparse tree order. */},{key:"getElementsByType",value:function getElementsByType(type){if(!this[$elementsByType].has(type)){return[];}// eslint-disable-next-line @typescript-eslint/no-non-null-assertion return Array.from(this[$elementsByType].get(type));}/** * Deactivate the ModelKernel. This has the effect of blocking all future * mutations to the scene graph. Once deactivated, a ModelKernel cannot be * reactivated. * * The ModelKernel should be deactivated before it is disposed of, or else * it will leak in memory. */},{key:"deactivate",value:function deactivate(){this[$port].close();this[$port].removeEventListener('message',this[$messageEventHandler]);}},{key:(_a=$elementsByLocalId,_b=$localIdsByElement,_c=$elementsByType,_d=$messageEventHandler,_e=$pendingMutations,_f=$nextMutationId,$onMessageEvent),value:function value(event){var data=event.data;switch(data&&data.type){case ThreeDOMMessageType.MUTATION_RESULT:{var message=data;var applied=message.applied,mutationId=message.mutationId;var pendingMutation=this[$pendingMutations].get(mutationId);this[$pendingMutations].delete(mutationId);if(pendingMutation!=null){applied?pendingMutation.resolve():pendingMutation.reject();}break;}}}},{key:"model",get:function get(){return this[$model];}}]);return ModelKernel;}();return ModelKernel;}/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */ /** * A constructor factory for a Model class. The Model is defined based on a * provided implementation for all specified 3DOM scene graph element types. * * The sole reason for using this factory pattern is to enable sound type * checking while also providing for the ability to stringify the factory so * that it can be part of a runtime-generated Worker script. * * @see ../api.ts */function defineModel(ThreeDOMElement){var _a;var $materials=Symbol('material');var $kernel=Symbol('kernel');/** * A Model is the root element of a 3DOM scene graph. It is considered the * element of provenance for all other elements that participate in the same * graph. All other elements in the graph can be accessed in from the Model * in some fashion. */var Model=/*#__PURE__*/function(_ThreeDOMElement3){_inherits(Model,_ThreeDOMElement3);var _super31=_createSuper(Model);function Model(kernel,serialized){var _this66;_classCallCheck(this,Model);_this66=_super31.call(this,kernel);_this66[_a]=Object.freeze([]);_this66[$kernel]=kernel;var _iterator18=_createForOfIteratorHelper(serialized.materials),_step18;try{for(_iterator18.s();!(_step18=_iterator18.n()).done;){var material=_step18.value;_this66[$kernel].deserialize('material',material);}}catch(err){_iterator18.e(err);}finally{_iterator18.f();}return _this66;}/** * The set of Material elements in the graph, in sparse traversal order. * Note that this set will include any Materials that are not part of the * currently activate scene. * * TODO(#1002): This value needs to be sensitive to scene graph order */_createClass(Model,[{key:"materials",get:function get(){return this[$kernel].getElementsByType('material');}/** * A Model has no owner model; it owns itself. */},{key:"ownerModel",get:function get(){return undefined;}}]);return Model;}(ThreeDOMElement);_a=$materials;return Model;}/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */ /** * A constructor factory for a PBRMetallicRoughness class. The * PBRMetallicRoughness is defined based on a provided implementation for all * specified 3DOM scene graph element types. * * The sole reason for using this factory pattern is to enable sound type * checking while also providing for the ability to stringify the factory so * that it can be part of a runtime-generated Worker script. * * @see ../api.ts */function definePBRMetallicRoughness(ThreeDOMElement){var _a,_b;var $kernel=Symbol('kernel');var $baseColorFactor=Symbol('baseColorFactor');var $baseColorTexture=Symbol('baseColorTexture');var $metallicRoughnessTexture=Symbol('metallicRoughnessTexture');var $metallicFactor=Symbol('metallicFactor');var $roughnessFactor=Symbol('roughnessFactor');/** * PBRMetallicRoughness exposes the PBR properties for a given Material. */var PBRMetallicRoughness=/*#__PURE__*/function(_ThreeDOMElement4){_inherits(PBRMetallicRoughness,_ThreeDOMElement4);var _super32=_createSuper(PBRMetallicRoughness);function PBRMetallicRoughness(kernel,serialized){var _this67;_classCallCheck(this,PBRMetallicRoughness);_this67=_super32.call(this,kernel,serialized);_this67[_a]=null;_this67[_b]=null;_this67[$kernel]=kernel;_this67[$baseColorFactor]=Object.freeze(serialized.baseColorFactor);_this67[$metallicFactor]=Object.freeze(serialized.metallicFactor);_this67[$roughnessFactor]=Object.freeze(serialized.roughnessFactor);var baseColorTexture=serialized.baseColorTexture,metallicRoughnessTexture=serialized.metallicRoughnessTexture;if(baseColorTexture!=null){_this67[$baseColorTexture]=kernel.deserialize('texture-info',baseColorTexture);}if(metallicRoughnessTexture!=null){_this67[$metallicRoughnessTexture]=kernel.deserialize('texture-info',metallicRoughnessTexture);}return _this67;}/** * The base color factor of the material in RGBA format. */_createClass(PBRMetallicRoughness,[{key:"setBaseColorFactor",/** * Set the base color factor of the material. * Requires the material-properties capability. * * @see ../api.ts */value:function(){var _setBaseColorFactor=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee31(color){return regeneratorRuntime.wrap(function _callee31$(_context32){while(1){switch(_context32.prev=_context32.next){case 0:_context32.next=2;return this[$kernel].mutate(this,'baseColorFactor',color);case 2:this[$baseColorFactor]=Object.freeze(color);case 3:case"end":return _context32.stop();}}},_callee31,this);}));function setBaseColorFactor(_x30){return _setBaseColorFactor.apply(this,arguments);}return setBaseColorFactor;}()/** * Set the metallic factor of the material. * Requires the material-properties capability. * * @see ../api.ts */},{key:"setMetallicFactor",value:function(){var _setMetallicFactor=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee32(color){return regeneratorRuntime.wrap(function _callee32$(_context33){while(1){switch(_context33.prev=_context33.next){case 0:_context33.next=2;return this[$kernel].mutate(this,'metallicFactor',color);case 2:this[$metallicFactor]=Object.freeze(color);case 3:case"end":return _context33.stop();}}},_callee32,this);}));function setMetallicFactor(_x31){return _setMetallicFactor.apply(this,arguments);}return setMetallicFactor;}()/** * Set the roughness factor of the material. * Requires the material-properties capability. * * @see ../api.ts */},{key:"setRoughnessFactor",value:function(){var _setRoughnessFactor=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee33(color){return regeneratorRuntime.wrap(function _callee33$(_context34){while(1){switch(_context34.prev=_context34.next){case 0:_context34.next=2;return this[$kernel].mutate(this,'roughnessFactor',color);case 2:this[$roughnessFactor]=Object.freeze(color);case 3:case"end":return _context34.stop();}}},_callee33,this);}));function setRoughnessFactor(_x32){return _setRoughnessFactor.apply(this,arguments);}return setRoughnessFactor;}()},{key:"baseColorFactor",get:function get(){return this[$baseColorFactor];}/** * The metalness factor of the material in range [0,1]. */},{key:"metallicFactor",get:function get(){return this[$metallicFactor];}/** * The roughness factor of the material in range [0,1]. */},{key:"roughnessFactor",get:function get(){return this[$roughnessFactor];}},{key:"baseColorTexture",get:function get(){return this[$baseColorTexture];}},{key:"metallicRoughnessTexture",get:function get(){return this[$metallicRoughnessTexture];}}]);return PBRMetallicRoughness;}(ThreeDOMElement);_a=$baseColorTexture,_b=$metallicRoughnessTexture;return PBRMetallicRoughness;}/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */ /** * A constructor factory for a Sampler class. The Sampler is defined based on * a provided implementation for all specified 3DOM scene graph element types. * * The sole reason for using this factory pattern is to enable sound type * checking while also providing for the ability to stringify the factory so * that it can be part of a runtime-generated Worker script. * * @see ../api.ts */function defineSampler(ThreeDOMElement){var _a,_b;var $kernel=Symbol('kernel');var $minFilter=Symbol('minFilter');var $magFilter=Symbol('magFilter');var $wrapS=Symbol('wrapS');var $wrapT=Symbol('wrapT');var $name=Symbol('name');var Sampler=/*#__PURE__*/function(_ThreeDOMElement5){_inherits(Sampler,_ThreeDOMElement5);var _super33=_createSuper(Sampler);function Sampler(kernel,serialized){var _this68;_classCallCheck(this,Sampler);_this68=_super33.call(this,kernel);_this68[_a]=null;_this68[_b]=null;_this68[$kernel]=kernel;_this68[$name]=serialized.name;_this68[$minFilter]=serialized.minFilter||null;_this68[$magFilter]=serialized.magFilter||null;_this68[$wrapS]=serialized.wrapS||10497;_this68[$wrapT]=serialized.wrapT||10497;return _this68;}_createClass(Sampler,[{key:"setMinFilter",value:function(){var _setMinFilter=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee34(filter){return regeneratorRuntime.wrap(function _callee34$(_context35){while(1){switch(_context35.prev=_context35.next){case 0:_context35.next=2;return this[$kernel].mutate(this,'minFilter',filter);case 2:this[$minFilter]=filter;case 3:case"end":return _context35.stop();}}},_callee34,this);}));function setMinFilter(_x33){return _setMinFilter.apply(this,arguments);}return setMinFilter;}()},{key:"setMagFilter",value:function(){var _setMagFilter=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee35(filter){return regeneratorRuntime.wrap(function _callee35$(_context36){while(1){switch(_context36.prev=_context36.next){case 0:_context36.next=2;return this[$kernel].mutate(this,'magFilter',filter);case 2:this[$magFilter]=filter;case 3:case"end":return _context36.stop();}}},_callee35,this);}));function setMagFilter(_x34){return _setMagFilter.apply(this,arguments);}return setMagFilter;}()},{key:"setWrapS",value:function(){var _setWrapS=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee36(mode){return regeneratorRuntime.wrap(function _callee36$(_context37){while(1){switch(_context37.prev=_context37.next){case 0:_context37.next=2;return this[$kernel].mutate(this,'wrapS',mode);case 2:this[$wrapS]=mode;case 3:case"end":return _context37.stop();}}},_callee36,this);}));function setWrapS(_x35){return _setWrapS.apply(this,arguments);}return setWrapS;}()},{key:"setWrapT",value:function(){var _setWrapT=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee37(mode){return regeneratorRuntime.wrap(function _callee37$(_context38){while(1){switch(_context38.prev=_context38.next){case 0:_context38.next=2;return this[$kernel].mutate(this,'wrapT',mode);case 2:this[$wrapT]=mode;case 3:case"end":return _context38.stop();}}},_callee37,this);}));function setWrapT(_x36){return _setWrapT.apply(this,arguments);}return setWrapT;}()},{key:"name",get:function get(){return this[$name];}},{key:"minFilter",get:function get(){return this[$minFilter];}},{key:"magFilter",get:function get(){return this[$magFilter];}},{key:"wrapS",get:function get(){return this[$wrapS];}},{key:"wrapT",get:function get(){return this[$wrapT];}}]);return Sampler;}(ThreeDOMElement);_a=$minFilter,_b=$magFilter;return Sampler;}/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */ /** * A constructor factory for a TextureInfo class. The TextureInfo is defined * based on a provided implementation for all specified 3DOM scene graph element * types. * * The sole reason for using this factory pattern is to enable sound type * checking while also providing for the ability to stringify the factory so * that it can be part of a runtime-generated Worker script. * * @see ../api.ts */function defineTextureInfo(ThreeDOMElement){var _a;var $kernel=Symbol('kernel');var $texture=Symbol('texture');var TextureInfo=/*#__PURE__*/function(_ThreeDOMElement6){_inherits(TextureInfo,_ThreeDOMElement6);var _super34=_createSuper(TextureInfo);function TextureInfo(kernel,serialized){var _this69;_classCallCheck(this,TextureInfo);_this69=_super34.call(this,kernel);_this69[_a]=null;_this69[$kernel]=kernel;var texture=serialized.texture;if(texture!=null){_this69[$texture]=kernel.deserialize('texture',texture);}return _this69;}_createClass(TextureInfo,[{key:"setTexture",value:function(){var _setTexture=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee38(texture){return regeneratorRuntime.wrap(function _callee38$(_context39){while(1){switch(_context39.prev=_context39.next){case 0:_context39.next=2;return this[$kernel].mutate(this,'texture',texture);case 2:this[$texture]=texture;case 3:case"end":return _context39.stop();}}},_callee38,this);}));function setTexture(_x37){return _setTexture.apply(this,arguments);}return setTexture;}()},{key:"texture",get:function get(){return this[$texture];}}]);return TextureInfo;}(ThreeDOMElement);_a=$texture;return TextureInfo;}/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */ /** * A constructor factory for a Texture class. The Texture is defined * based on a provided implementation for all specified 3DOM scene graph element * types. * * The sole reason for using this factory pattern is to enable sound type * checking while also providing for the ability to stringify the factory so * that it can be part of a runtime-generated Worker script. * * @see ../api.ts */function defineTexture(ThreeDOMElement){var _a,_b;var $kernel=Symbol('kernel');var $source=Symbol('source');var $sampler=Symbol('sampler');var $name=Symbol('name');var Texture=/*#__PURE__*/function(_ThreeDOMElement7){_inherits(Texture,_ThreeDOMElement7);var _super35=_createSuper(Texture);function Texture(kernel,serialized){var _this70;_classCallCheck(this,Texture);_this70=_super35.call(this,kernel);_this70[_a]=null;_this70[_b]=null;_this70[$kernel]=kernel;var sampler=serialized.sampler,source=serialized.source,name=serialized.name;_this70[$name]=name;if(sampler!=null){_this70[$sampler]=kernel.deserialize('sampler',sampler);}if(source!=null){_this70[$source]=kernel.deserialize('image',source);}return _this70;}_createClass(Texture,[{key:"setSampler",value:function(){var _setSampler=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee39(sampler){return regeneratorRuntime.wrap(function _callee39$(_context40){while(1){switch(_context40.prev=_context40.next){case 0:_context40.next=2;return this[$kernel].mutate(this,'sampler',sampler);case 2:this[$sampler]=sampler;case 3:case"end":return _context40.stop();}}},_callee39,this);}));function setSampler(_x38){return _setSampler.apply(this,arguments);}return setSampler;}()},{key:"setSource",value:function(){var _setSource2=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee40(image){return regeneratorRuntime.wrap(function _callee40$(_context41){while(1){switch(_context41.prev=_context41.next){case 0:_context41.next=2;return this[$kernel].mutate(this,'source',image);case 2:this[$source]=image;case 3:case"end":return _context41.stop();}}},_callee40,this);}));function setSource(_x39){return _setSource2.apply(this,arguments);}return setSource;}()},{key:"name",get:function get(){return this[$name];}},{key:"sampler",get:function get(){return this[$sampler];}},{key:"source",get:function get(){return this[$source];}}]);return Texture;}(ThreeDOMElement);_a=$source,_b=$sampler;return Texture;}/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */ /** * A constructor factory for a ThreeDOMElement class. The ThreeDOMElement is * defined based on a provided implementation for all specified 3DOM scene graph * element types. * * The sole reason for using this factory pattern is to enable sound type * checking while also providing for the ability to stringify the factory so * that it can be part of a runtime-generated Worker script. * * @see ../api.ts */function defineThreeDOMElement(){var $ownerModel=Symbol('ownerModel');/** * The basic implementation for all 3DOM scene graph participants. * Scene graph nodes are distinguished by their "owner" Model. All scene * graph nodes have an owner Model associated with them except for the * sole Model in the scene graph, whose ownerModel property is not defined. */var ThreeDOMElement=/*#__PURE__*/function(){function ThreeDOMElement(kernel){_classCallCheck(this,ThreeDOMElement);if(kernel==null){throw new Error('Illegal constructor');}this[$ownerModel]=kernel.model;}/** * The Model of provenance for this scene graph element, or undefined if * element is itself a Model. */_createClass(ThreeDOMElement,[{key:"ownerModel",get:function get(){return this[$ownerModel];}}]);return ThreeDOMElement;}();return ThreeDOMElement;}/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */ /** * The protocol between 3DOM execution contexts is strictly defined. * Only specific types of messages are allowed, and their types are * all included in the ThreeDOMMessageType map. */var ThreeDOMMessageType={// === Host -> Scene Graph === // Used when the host execution context and scene graph execution context // are negotiating a connection HANDSHAKE:1,// A message that indicates that a custom script is meant to be imported // into the scene graph execution context IMPORT_SCRIPT:2,// A notification from the host execution context that the main Model has // changed, including the sparse, serialized scene graph of the new Model MODEL_CHANGE:3,// A notification that confirms or denies a request from the scene graph // context to mutate the scene graph MUTATION_RESULT:4,// === Scene Graph => Host === // Notification sent to the host execution context to indicate that the // scene graph execution context has finished initializing CONTEXT_INITIALIZED:5,// A request from the scene graph execution context to mutate some detail // of the backing host scene graph MUTATE:6};/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */var generateAPI=function generateAPI(){return"\nvar ThreeDOMMessageType = ".concat(JSON.stringify(ThreeDOMMessageType),";\n\n").concat(defineModelKernel.toString(),"\n").concat(defineThreeDOMElement.toString(),"\n").concat(defineModel.toString(),"\n").concat(defineMaterial.toString(),"\n").concat(definePBRMetallicRoughness.toString(),"\n").concat(defineSampler.toString(),"\n").concat(defineImage.toString(),"\n").concat(defineTexture.toString(),"\n").concat(defineTextureInfo.toString(),"\n\nvar ThreeDOMElement = ").concat(defineThreeDOMElement.name,"();\nvar Model = ").concat(defineModel.name,"(ThreeDOMElement);\nvar Material = ").concat(defineMaterial.name,"(ThreeDOMElement);\nvar PBRMetallicRoughness = ").concat(definePBRMetallicRoughness.name,"(ThreeDOMElement);\nvar Sampler = ").concat(defineSampler.name,"(ThreeDOMElement);\nvar Image = ").concat(defineImage.name,"(ThreeDOMElement);\nvar Texture = ").concat(defineTexture.name,"(ThreeDOMElement);\nvar TextureInfo = ").concat(defineTextureInfo.name,"(ThreeDOMElement);\n\nvar ModelKernel = ").concat(defineModelKernel.name,"(\n ThreeDOMMessageType,\n ThreeDOMElement,\n Model,\n Material,\n PBRMetallicRoughness,\n Sampler,\n Image,\n Texture,\n TextureInfo\n);\n\n// Populate the global scope with constructors\n// so that author code can use instanceof checks\nself.ThreeDOMElement = ThreeDOMElement;\nself.Model = Model;\nself.Material = Material;\nself.PBRMetallicRoughness = PBRMetallicRoughness;\nself.Sampler = Sampler;\nself.Image = Image;\nself.Texture = Texture;\nself.TextureInfo = TextureInfo;\n");};/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */function filterTextures(){var errorMessage='Capability "textures" not allowed';var descriptor={value:function value(){throw new Error(errorMessage);},configurable:false,writable:false};Object.defineProperties(this.Texture.prototype,{'setSampler':descriptor,'setSource':descriptor});Object.defineProperties(this.Image.prototype,{'setURI':descriptor});Object.defineProperties(this.Sampler.prototype,{'setMinFilter':descriptor,'setMagFilter':descriptor,'setWrapS':descriptor,'setWrapT':descriptor});}/** * Given a 3DOM execution context, patch any methods that give write access * to otherwise configurable material properties so that they are automatically * rejected when invoked. */function filterMaterialProperties(){var errorMessage='Capability "material-properties" not allowed';Object.defineProperty(this.PBRMetallicRoughness.prototype,'setBaseColorFactor',{value:function value(){throw new Error(errorMessage);},configurable:false,writable:false});Object.defineProperty(this.PBRMetallicRoughness.prototype,'setMetallicFactor',{value:function value(){throw new Error(errorMessage);},configurable:false,writable:false});Object.defineProperty(this.PBRMetallicRoughness.prototype,'setRoughnessFactor',{value:function value(){throw new Error(errorMessage);},configurable:false,writable:false});}/** * Given a 3DOM execution context, patch any methods, classes or other APIs * related to Web Messaging so that they throw or are otherwise rendered * impotent. * * TODO(#1001): We probably need to crawl up the prototype chain on this one */function filterMessaging(){var errorMessage='Capability "messaging" not allowed';var rejectInvocation=function rejectInvocation(){throw new Error(errorMessage);};var originalAddEventListener=this.addEventListener;Object.defineProperties(this,{postMessage:{value:rejectInvocation,configurable:false},MessageChannel:{value:rejectInvocation,configurable:false},MessageEvent:{value:rejectInvocation,configurable:false},onmessage:{set:function set(){rejectInvocation();},configurable:false},addEventListener:{value:function value(type,listener,options){if(type==='message'){rejectInvocation();}originalAddEventListener.call(this,type,listener,options);},configurable:false}});}/** * Given a 3DOM execution context, patch the global Fetch API so that any * attempts to perform network operations are immediately rejected. */function filterFetch(){Object.defineProperties(this,{fetch:{value:function value(){throw new Error('Capability "fetch" not allowed');},configurable:false}});}var capabilityFilterMap={'textures':filterTextures,'messaging':filterMessaging,'material-properties':filterMaterialProperties,'fetch':filterFetch};/** * Given a list of 3DOM capability strings, this factory produces a script * fragment that patches the global execution context so that any omitted * capabilities are explicitly disallowed. */var generateCapabilityFilter=function generateCapabilityFilter(capabilities){var filtersToApply=Object.keys(capabilityFilterMap);var capabilityFilters=[];for(var _i20=0,_filtersToApply=filtersToApply;_i20<_filtersToApply.length;_i20++){var capability=_filtersToApply[_i20];// Skip filters that are allowed by the list of capabilities if(capabilities.indexOf(capability)>-1){continue;}var filter=capabilityFilterMap[capability];capabilityFilters.push("(".concat(filter.toString(),").call(self);"));}return capabilityFilters.join('\n');};/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */ /** * Adapted from WorkerDOM * NOTE: The context could also be DedicatedWorkerGlobalScope, but the * TypeScript WebWorker lib seems to conflict with the dom lib * * @see https://github.com/ampproject/worker-dom/blob/master/src/worker-thread/index.amp.ts */function patchContext(context,allowList){// Crawl up the prototype chain until we get to EventTarget so that we // don't go overboard deleting fundamental properties of things: while(context&&context.constructor!==EventTarget){Object.getOwnPropertyNames(context).forEach(function(property){// eslint-disable-next-line no-prototype-builtins if(allowList.hasOwnProperty(property)&&allowList[property]===true){// Skip allowed property return;}try{delete context[property];}catch(e){console.warn(e);}});context=Object.getPrototypeOf(context);}}/** * Given an "allow" list that maps context property names to booleans (true for * allowed, false for disallowed), this factory produces a script chunk that * can patch the global context so that only allowed properties/APIs are * available. * * Disallowed properties are deleted on the global context and its prototype * chain. Omiting a property from the allow list is tantamount to disallowing * it. */var generateContextPatch=function generateContextPatch(allowList){return"(".concat(patchContext.toString(),")(self, ").concat(JSON.stringify(allowList),");");};/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */ /** * A function that will be stringified and appended the a runtime-generated * execution context script to initialize the scene graph execution context. * * The sole reason for using this pattern is to enable sound type * checking while also providing for the ability to stringify the factory so * that it can be part of a runtime-generated Worker script. */function initialize(ThreeDOMMessageType,ModelKernel,preservedContext){var _this71=this;var currentKernel=null;preservedContext.addEventListener('message',function(event){var data=event.data;if(data&&data.type&&data.type===ThreeDOMMessageType.HANDSHAKE){var globalPort=event.ports[0];globalPort.addEventListener('message',function(event){var data=event.data;if(data&&data.type){switch(data.type){// Instantiate a new ModelKernel, and notify the execution context // of the new Model with a 'model-change' event: case ThreeDOMMessageType.MODEL_CHANGE:{var previousModel=currentKernel!=null?currentKernel.model:undefined;var serialized=data.model;var port=event.ports[0];if(currentKernel!=null){currentKernel.deactivate();}else if(serialized==null){// Do not proceed if transitioning from null to null break;}if(serialized!=null){currentKernel=new ModelKernel(port,serialized);_this71.model=currentKernel.model;}else{currentKernel=null;_this71.model=undefined;}var modelChangeEvent=new Event('model-change');modelChangeEvent.previousModel=previousModel;modelChangeEvent.model=_this71.model;_this71.dispatchEvent(modelChangeEvent);break;}// Import an external script into the execution context: case ThreeDOMMessageType.IMPORT_SCRIPT:{var url=data.url;if(url){preservedContext.importScripts(url);}break;}}}});globalPort.start();// Notify the host execution context that the scene graph execution // is ready: globalPort.postMessage({type:ThreeDOMMessageType.CONTEXT_INITIALIZED});}});}/** * A factory that produces a stringified initializer function. */var generateInitializer=function generateInitializer(){return initialize.toString();};/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */var _a$f,_b$d;var $modelGraft=Symbol('modelGraft');var $port=Symbol('port');var $messageEventHandler=Symbol('messageEventHandler');var $onMessageEvent=Symbol('onMessageEvent');/** * A ModelGraftManipulator is an internal construct intended to consolidate * any mutations that operate on the backing scene graph. It can be thought * of as a host execution context counterpart to the ModelKernel in the scene * graph execution context. */var ModelGraftManipulator=/*#__PURE__*/function(){function ModelGraftManipulator(modelGraft,port){var _this72=this;_classCallCheck(this,ModelGraftManipulator);this[_a$f]=function(event){return _this72[$onMessageEvent](event);};this[$modelGraft]=modelGraft;this[$port]=port;this[$port].addEventListener('message',this[$messageEventHandler]);this[$port].start();}/** * Clean up internal state so that the ModelGraftManipulator can be properly * garbage collected. */_createClass(ModelGraftManipulator,[{key:"dispose",value:function dispose(){this[$port].removeEventListener('message',this[$messageEventHandler]);this[$port].close();}},{key:(_a$f=$messageEventHandler,$onMessageEvent),value:function value(event){var data=event.data;if(data&&data.type){if(data.type===ThreeDOMMessageType.MUTATE){var applied=false;var mutationId=data.mutationId;try{this[$modelGraft].mutate(data.id,data.property,data.value);applied=true;}finally{this[$port].postMessage({type:ThreeDOMMessageType.MUTATION_RESULT,applied:applied,mutationId:mutationId});}}}}}]);return ModelGraftManipulator;}();var ALL_CAPABILITIES=Object.freeze(['messaging','material-properties','fetch']);/** * Constructs and returns a string representing a fully-formed scene graph * execution context script, including context patching, capabilities and * scene graph API constructs. */var generateContextScriptSource=function generateContextScriptSource(){var capabilities=arguments.length>0&&arguments[0]!==undefined?arguments[0]:ALL_CAPABILITIES;return";(function() {\nvar preservedContext = {\n postMessage: self.postMessage.bind(self),\n addEventListener: self.addEventListener.bind(self),\n importScripts: self.importScripts.bind(self)\n};\n\n".concat(generateContextPatch(ALLOWLISTED_GLOBALS),"\n").concat(generateAPI(),"\n").concat(generateCapabilityFilter(capabilities),"\n(").concat(generateInitializer(),").call(self, ThreeDOMMessageType, ModelKernel, preservedContext);\n\n})();");};var $worker=Symbol('worker');var $workerInitializes=Symbol('workerInitializes');var $modelGraftManipulator=Symbol('modelGraftManipulator');/** * A ThreeDOMExecutionContext is created in the host execution context that * wishes to invoke scripts in a specially crafted and carefully isolated * script context, referred to as the scene graph execution context. For * practical implementation purposes, the scene graph execution context is * a Worker whose global scope has been heavily patched before any custom * script is subsequently invoked in it. * * The ThreeDOMExecutionContext must be given a set of allowed capabilities * when it is created. The allowed capabilities cannot be changed after the * scene graph execution context has been established. */var ThreeDOMExecutionContext=/*#__PURE__*/function(_EventTarget){_inherits(ThreeDOMExecutionContext,_EventTarget);var _super36=_createSuper(ThreeDOMExecutionContext);function ThreeDOMExecutionContext(capabilities){var _this73;_classCallCheck(this,ThreeDOMExecutionContext);_this73=_super36.call(this);_this73[_b$d]=null;var contextScriptSource=generateContextScriptSource(capabilities);var url=URL.createObjectURL(new Blob([contextScriptSource],{type:'text/javascript'}));_this73[$worker]=new Worker(url);_this73[$workerInitializes]=new Promise(function(resolve){var _MessageChannel=new MessageChannel(),port1=_MessageChannel.port1,port2=_MessageChannel.port2;var onMessageEvent=function onMessageEvent(event){if(event.data&&event.data.type===ThreeDOMMessageType.CONTEXT_INITIALIZED){port1.removeEventListener('message',onMessageEvent);resolve(port1);}};_this73[$worker].postMessage({type:ThreeDOMMessageType.HANDSHAKE},[port2]);port1.addEventListener('message',onMessageEvent);port1.start();});return _this73;}_createClass(ThreeDOMExecutionContext,[{key:"changeModel",value:function(){var _changeModel=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee41(modelGraft){var port,_MessageChannel2,port1,port2,modelGraftManipulator;return regeneratorRuntime.wrap(function _callee41$(_context42){while(1){switch(_context42.prev=_context42.next){case 0:_context42.next=2;return this[$workerInitializes];case 2:port=_context42.sent;_MessageChannel2=new MessageChannel(),port1=_MessageChannel2.port1,port2=_MessageChannel2.port2;port.postMessage({type:ThreeDOMMessageType.MODEL_CHANGE,model:modelGraft!=null&&modelGraft.model!=null?modelGraft.model.toJSON():null},[port2]);modelGraftManipulator=this[$modelGraftManipulator];if(modelGraftManipulator!=null){modelGraftManipulator.dispose();this[$modelGraftManipulator]=null;}if(modelGraft!=null){this[$modelGraftManipulator]=new ModelGraftManipulator(modelGraft,port1);}case 8:case"end":return _context42.stop();}}},_callee41,this);}));function changeModel(_x40){return _changeModel.apply(this,arguments);}return changeModel;}()/** * Evaluate an arbitrary chunk of script in the scene graph execution context. * The script is guaranteed to be evaluated after the scene graph execution * context is fully initialized. It is not guaranteed to be evaluated before * or after a Model is made available in the scene graph execution context. * * Note that web browsers do not universally support module scripts ("ESM") in * Workers, so for now all scripts must be valid non-module scripts. */},{key:"eval",value:function(){var _eval2=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee42(scriptSource){return regeneratorRuntime.wrap(function _callee42$(_context43){while(1){switch(_context43.prev=_context43.next){case 0:_context43.next=2;return this.import(URL.createObjectURL(new Blob([scriptSource],{type:'text/javascript'})));case 2:case"end":return _context43.stop();}}},_callee42,this);}));function _eval(_x41){return _eval2.apply(this,arguments);}return _eval;}()/* end eval marker (do not remove) */ /** * Load a script by URL in the scene graph execution context. Generally works * the same as eval, but is generally safer because it allows you full control * of the script text. Like eval, does not support module scripts. */},{key:"import",value:function(){var _import2=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee43(url){var port;return regeneratorRuntime.wrap(function _callee43$(_context44){while(1){switch(_context44.prev=_context44.next){case 0:_context44.next=2;return this[$workerInitializes];case 2:port=_context44.sent;port.postMessage({type:ThreeDOMMessageType.IMPORT_SCRIPT,url:url});case 4:case"end":return _context44.stop();}}},_callee43,this);}));function _import(_x42){return _import2.apply(this,arguments);}return _import;}()/** * Terminates the scene graph execution context, closes the designated * messaging port and generally cleans up the ThreeDOMExecutionContext * so that it can be properly garbage collected. */},{key:"terminate",value:function(){var _terminate=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee44(){var modelGraftManipulator,port;return regeneratorRuntime.wrap(function _callee44$(_context45){while(1){switch(_context45.prev=_context45.next){case 0:this[$worker].terminate();modelGraftManipulator=this[$modelGraftManipulator];if(modelGraftManipulator!=null){modelGraftManipulator.dispose();this[$modelGraftManipulator]=null;}_context45.next=5;return this[$workerInitializes];case 5:port=_context45.sent;port.close();case 7:case"end":return _context45.stop();}}},_callee44,this);}));function terminate(){return _terminate.apply(this,arguments);}return terminate;}()},{key:"worker",get:function get(){return this[$worker];}}]);return ThreeDOMExecutionContext;}(/*#__PURE__*/_wrapNativeSuper(EventTarget));_b$d=$modelGraftManipulator;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */ /** * Produces a "locally" unique ID. This ID is only guaranteed to be unique * over the lifetime of the function and in the current execution context. */var getLocallyUniqueId=function(){var id=0;return function(){return id++;};}();var $callbacks=Symbol('callbacks');var $visitMesh=Symbol('visitMesh');var $visitElement=Symbol('visitElement');var $visitNode=Symbol('visitNode');var $visitScene=Symbol('visitScene');var $visitMaterial=Symbol('visitMaterial');/** * GLTFTreeVisitor implements a deterministic traversal order of a valid, * deserialized glTF 2.0 model. It supports selective element visitation via * callbacks configured based on element type. For example, to visit all * materials in all scenes in a glTF: * * ```javascript * const visitor = new GLTFTreeVisitor({ * material: (material, index, hierarchy) => { * // material is a glTF 2.0 Material * // index is the index of material in gltf.materials * // hierarchy includes ancestors of material in the glTF * } * }); * * visitor.visit(someInMemoryGLTF, { allScenes: true }); * ``` * * The traversal order of the visitor is pre-order, depth-first. * * Note that the traversal order is not guaranteed to correspond to the * index of a given element in any way. Rather, traversal order is based * on the hierarchical order of the scene graph. */var GLTFTreeVisitor=/*#__PURE__*/function(){function GLTFTreeVisitor(callbacks){_classCallCheck(this,GLTFTreeVisitor);this[$callbacks]=callbacks;}/** * Visit a given in-memory glTF via the configured callbacks of this visitor. * Optionally, all scenes may be visited (as opposed to just the active one). * Sparse traversal can also be specified, in which case elements that * re-appear multiple times in the scene graph will only be visited once. */_createClass(GLTFTreeVisitor,[{key:"visit",value:function visit(gltf){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var allScenes=!!options.allScenes;var sparse=!!options.sparse;var scenes=allScenes?gltf.scenes||[]:gltf.scenes&&gltf.scene!=null?[gltf.scenes[gltf.scene]]:[];var state={hierarchy:[],visited:new Set(),sparse:sparse,gltf:gltf};var _iterator19=_createForOfIteratorHelper(scenes),_step19;try{for(_iterator19.s();!(_step19=_iterator19.n()).done;){var scene=_step19.value;this[$visitScene](gltf.scenes.indexOf(scene),state);}}catch(err){_iterator19.e(err);}finally{_iterator19.f();}}},{key:$visitElement,value:function value(index,elementList,state,visit,traverse){if(elementList==null){return;}var element=elementList[index];var sparse=state.sparse,hierarchy=state.hierarchy,visited=state.visited;if(element==null){return;}if(sparse&&visited.has(element)){return;}visited.add(element);hierarchy.push(element);if(visit!=null){visit(element,index,hierarchy);}if(traverse!=null){traverse(element);}hierarchy.pop();}},{key:$visitScene,value:function value(index,state){var _this74=this;var gltf=state.gltf;var visit=this[$callbacks].scene;this[$visitElement](index,gltf.scenes,state,visit,function(scene){// A scene is not required to have a list of nodes if(scene.nodes==null){return;}var _iterator20=_createForOfIteratorHelper(scene.nodes),_step20;try{for(_iterator20.s();!(_step20=_iterator20.n()).done;){var nodeIndex=_step20.value;_this74[$visitNode](nodeIndex,state);}}catch(err){_iterator20.e(err);}finally{_iterator20.f();}});}},{key:$visitNode,value:function value(index,state){var _this75=this;var gltf=state.gltf;var visit=this[$callbacks].node;this[$visitElement](index,gltf.nodes,state,visit,function(node){if(node.mesh!=null){_this75[$visitMesh](node.mesh,state);}if(node.children!=null){var _iterator21=_createForOfIteratorHelper(node.children),_step21;try{for(_iterator21.s();!(_step21=_iterator21.n()).done;){var childNodeIndex=_step21.value;_this75[$visitNode](childNodeIndex,state);}}catch(err){_iterator21.e(err);}finally{_iterator21.f();}}});}},{key:$visitMesh,value:function value(index,state){var _this76=this;var gltf=state.gltf;var visit=this[$callbacks].mesh;this[$visitElement](index,gltf.meshes,state,visit,function(mesh){var _iterator22=_createForOfIteratorHelper(mesh.primitives),_step22;try{for(_iterator22.s();!(_step22=_iterator22.n()).done;){var primitive=_step22.value;if(primitive.material!=null){_this76[$visitMaterial](primitive.material,state);}}}catch(err){_iterator22.e(err);}finally{_iterator22.f();}});}},{key:$visitMaterial,value:function value(index,state){var gltf=state.gltf;var visit=this[$callbacks].material;this[$visitElement](index,gltf.materials,state,visit);}}]);return GLTFTreeVisitor;}();// 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 get(){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');}var output=Object(target);for(var index=1;index>8&0xff]+_lut$1[d0>>16&0xff]+_lut$1[d0>>24&0xff]+'-'+_lut$1[d1&0xff]+_lut$1[d1>>8&0xff]+'-'+_lut$1[d1>>16&0x0f|0x40]+_lut$1[d1>>24&0xff]+'-'+_lut$1[d2&0x3f|0x80]+_lut$1[d2>>8&0xff]+'-'+_lut$1[d2>>16&0xff]+_lut$1[d2>>24&0xff]+_lut$1[d3&0xff]+_lut$1[d3>>8&0xff]+_lut$1[d3>>16&0xff]+_lut$1[d3>>24&0xff];// .toUpperCase() here flattens concatenated strings to save heap memory space. return uuid.toUpperCase();},clamp:function clamp(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 euclideanModulo(n,m){return(n%m+m)%m;},// Linear mapping from range to range mapLinear:function mapLinear(x,a1,a2,b1,b2){return b1+(x-a1)*(b2-b1)/(a2-a1);},// https://en.wikipedia.org/wiki/Linear_interpolation lerp:function lerp(x,y,t){return(1-t)*x+t*y;},// http://en.wikipedia.org/wiki/Smoothstep smoothstep:function smoothstep(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 smootherstep(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 interval randInt:function randInt(low,high){return low+Math.floor(Math.random()*(high-low+1));},// Random float from interval randFloat:function randFloat(low,high){return low+Math.random()*(high-low);},// Random float from <-range/2, range/2> interval randFloatSpread:function randFloatSpread(range){return range*(0.5-Math.random());},degToRad:function degToRad(degrees){return degrees*MathUtils$1.DEG2RAD;},radToDeg:function radToDeg(radians){return radians*MathUtils$1.RAD2DEG;},isPowerOfTwo:function isPowerOfTwo(value){return(value&value-1)===0&&value!==0;},ceilPowerOfTwo:function ceilPowerOfTwo(value){return Math.pow(2,Math.ceil(Math.log(value)/Math.LN2));},floorPowerOfTwo:function floorPowerOfTwo(value){return Math.pow(2,Math.floor(Math.log(value)/Math.LN2));},setQuaternionFromProperEuler:function setQuaternionFromProperEuler(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 var cos=Math.cos;var sin=Math.sin;var c2=cos(b/2);var s2=sin(b/2);var c13=cos((a+c)/2);var s13=sin((a+c)/2);var c1_3=cos((a-c)/2);var s1_3=sin((a-c)/2);var c3_1=cos((c-a)/2);var 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$1(x,y){this.x=x||0;this.y=y||0;}Object.defineProperties(Vector2$1.prototype,{"width":{get:function get(){return this.x;},set:function set(value){this.x=value;}},"height":{get:function get(){return this.y;},set:function set(value){this.y=value;}}});Object.assign(Vector2$1.prototype,{isVector2:true,set:function set(x,y){this.x=x;this.y=y;return this;},setScalar:function setScalar(scalar){this.x=scalar;this.y=scalar;return this;},setX:function setX(x){this.x=x;return this;},setY:function setY(y){this.y=y;return this;},setComponent:function setComponent(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 getComponent(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 clone(){return new this.constructor(this.x,this.y);},copy:function copy(v){this.x=v.x;this.y=v.y;return this;},add:function add(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 addScalar(s){this.x+=s;this.y+=s;return this;},addVectors:function addVectors(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this;},addScaledVector:function addScaledVector(v,s){this.x+=v.x*s;this.y+=v.y*s;return this;},sub:function sub(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 subScalar(s){this.x-=s;this.y-=s;return this;},subVectors:function subVectors(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this;},multiply:function multiply(v){this.x*=v.x;this.y*=v.y;return this;},multiplyScalar:function multiplyScalar(scalar){this.x*=scalar;this.y*=scalar;return this;},divide:function divide(v){this.x/=v.x;this.y/=v.y;return this;},divideScalar:function divideScalar(scalar){return this.multiplyScalar(1/scalar);},applyMatrix3:function applyMatrix3(m){var x=this.x,y=this.y;var 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 min(v){this.x=Math.min(this.x,v.x);this.y=Math.min(this.y,v.y);return this;},max:function max(v){this.x=Math.max(this.x,v.x);this.y=Math.max(this.y,v.y);return this;},clamp:function clamp(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 clampScalar(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 clampLength(min,max){var length=this.length();return this.divideScalar(length||1).multiplyScalar(Math.max(min,Math.min(max,length)));},floor:function floor(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this;},ceil:function ceil(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this;},round:function round(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this;},roundToZero:function roundToZero(){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 negate(){this.x=-this.x;this.y=-this.y;return this;},dot:function dot(v){return this.x*v.x+this.y*v.y;},cross:function cross(v){return this.x*v.y-this.y*v.x;},lengthSq:function lengthSq(){return this.x*this.x+this.y*this.y;},length:function length(){return Math.sqrt(this.x*this.x+this.y*this.y);},manhattanLength:function manhattanLength(){return Math.abs(this.x)+Math.abs(this.y);},normalize:function normalize(){return this.divideScalar(this.length()||1);},angle:function angle(){// computes the angle in radians with respect to the positive x-axis var angle=Math.atan2(-this.y,-this.x)+Math.PI;return angle;},distanceTo:function distanceTo(v){return Math.sqrt(this.distanceToSquared(v));},distanceToSquared:function distanceToSquared(v){var dx=this.x-v.x,dy=this.y-v.y;return dx*dx+dy*dy;},manhattanDistanceTo:function manhattanDistanceTo(v){return Math.abs(this.x-v.x)+Math.abs(this.y-v.y);},setLength:function setLength(length){return this.normalize().multiplyScalar(length);},lerp:function lerp(v,alpha){this.x+=(v.x-this.x)*alpha;this.y+=(v.y-this.y)*alpha;return this;},lerpVectors:function lerpVectors(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 equals(v){return v.x===this.x&&v.y===this.y;},fromArray:function fromArray(array,offset){if(offset===undefined)offset=0;this.x=array[offset];this.y=array[offset+1];return this;},toArray:function toArray(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;array[offset]=this.x;array[offset+1]=this.y;return array;},fromBufferAttribute:function fromBufferAttribute(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 rotateAround(center,angle){var c=Math.cos(angle),s=Math.sin(angle);var x=this.x-center.x;var 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 random(){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$1(){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$1.prototype,{isMatrix3:true,set:function set(n11,n12,n13,n21,n22,n23,n31,n32,n33){var 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 identity(){this.set(1,0,0,0,1,0,0,0,1);return this;},clone:function clone(){return new this.constructor().fromArray(this.elements);},copy:function copy(m){var te=this.elements;var 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 extractBasis(xAxis,yAxis,zAxis){xAxis.setFromMatrix3Column(this,0);yAxis.setFromMatrix3Column(this,1);zAxis.setFromMatrix3Column(this,2);return this;},setFromMatrix4:function setFromMatrix4(m){var 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 multiply(m){return this.multiplyMatrices(this,m);},premultiply:function premultiply(m){return this.multiplyMatrices(m,this);},multiplyMatrices:function multiplyMatrices(a,b){var ae=a.elements;var be=b.elements;var te=this.elements;var a11=ae[0],a12=ae[3],a13=ae[6];var a21=ae[1],a22=ae[4],a23=ae[7];var a31=ae[2],a32=ae[5],a33=ae[8];var b11=be[0],b12=be[3],b13=be[6];var b21=be[1],b22=be[4],b23=be[7];var 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 multiplyScalar(s){var 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 determinant(){var te=this.elements;var 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 getInverse(matrix,throwOnDegenerate){if(throwOnDegenerate!==undefined){console.warn("THREE.Matrix3: .getInverse() can no longer be configured to throw on degenerate.");}var 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);var 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 transpose(){var tmp,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 getNormalMatrix(matrix4){return this.setFromMatrix4(matrix4).getInverse(this).transpose();},transposeIntoArray:function transposeIntoArray(r){var 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 setUvTransform(tx,ty,sx,sy,rotation,cx,cy){var c=Math.cos(rotation);var 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 scale(sx,sy){var 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 rotate(theta){var c=Math.cos(theta);var s=Math.sin(theta);var te=this.elements;var a11=te[0],a12=te[3],a13=te[6];var 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 translate(tx,ty){var 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 equals(matrix){var te=this.elements;var me=matrix.elements;for(var i=0;i<9;i++){if(te[i]!==me[i])return false;}return true;},fromArray:function fromArray(array,offset){if(offset===undefined)offset=0;for(var i=0;i<9;i++){this.elements[i]=array[i+offset];}return this;},toArray:function toArray(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;var 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/ */var _canvas$1;var ImageUtils$1={getDataURL:function getDataURL(image){var canvas;if(typeof HTMLCanvasElement=='undefined'){return image.src;}else if(_instanceof(image,HTMLCanvasElement)){canvas=image;}else{if(_canvas$1===undefined)_canvas$1=document.createElementNS('http://www.w3.org/1999/xhtml','canvas');_canvas$1.width=image.width;_canvas$1.height=image.height;var context=_canvas$1.getContext('2d');if(_instanceof(image,ImageData)){context.putImageData(image,0,0);}else{context.drawImage(image,0,0,image.width,image.height);}canvas=_canvas$1;}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/ */var textureId$1=0;function Texture$1(image,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding){Object.defineProperty(this,'id',{value:textureId$1++});this.uuid=MathUtils$1.generateUUID();this.name='';this.image=image!==undefined?image:Texture$1.DEFAULT_IMAGE;this.mipmaps=[];this.mapping=mapping!==undefined?mapping:Texture$1.DEFAULT_MAPPING;this.wrapS=wrapS!==undefined?wrapS:ClampToEdgeWrapping$1;this.wrapT=wrapT!==undefined?wrapT:ClampToEdgeWrapping$1;this.magFilter=magFilter!==undefined?magFilter:LinearFilter$1;this.minFilter=minFilter!==undefined?minFilter:LinearMipmapLinearFilter$1;this.anisotropy=anisotropy!==undefined?anisotropy:1;this.format=format!==undefined?format:RGBAFormat$1;this.internalFormat=null;this.type=type!==undefined?type:UnsignedByteType$1;this.offset=new Vector2$1(0,0);this.repeat=new Vector2$1(1,1);this.center=new Vector2$1(0,0);this.rotation=0;this.matrixAutoUpdate=true;this.matrix=new Matrix3$1();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$1;this.version=0;this.onUpdate=null;}Texture$1.DEFAULT_IMAGE=undefined;Texture$1.DEFAULT_MAPPING=UVMapping$1;Texture$1.prototype=Object.assign(Object.create(EventDispatcher$1.prototype),{constructor:Texture$1,isTexture:true,updateMatrix:function updateMatrix(){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 clone(){return new this.constructor().copy(this);},copy:function copy(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 toJSON(meta){var isRootObject=meta===undefined||typeof meta==='string';if(!isRootObject&&meta.textures[this.uuid]!==undefined){return meta.textures[this.uuid];}var 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 var image=this.image;if(image.uuid===undefined){image.uuid=MathUtils$1.generateUUID();// UGH }if(!isRootObject&&meta.images[image.uuid]===undefined){var url;if(Array.isArray(image)){// process array of images e.g. CubeTexture url=[];for(var i=0,l=image.length;i1){switch(this.wrapS){case RepeatWrapping$1:uv.x=uv.x-Math.floor(uv.x);break;case ClampToEdgeWrapping$1:uv.x=uv.x<0?0:1;break;case MirroredRepeatWrapping$1: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$1:uv.y=uv.y-Math.floor(uv.y);break;case ClampToEdgeWrapping$1:uv.y=uv.y<0?0:1;break;case MirroredRepeatWrapping$1: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$1.prototype,"needsUpdate",{set:function set(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$1(x,y,z,w){this.x=x||0;this.y=y||0;this.z=z||0;this.w=w!==undefined?w:1;}Object.defineProperties(Vector4$1.prototype,{"width":{get:function get(){return this.z;},set:function set(value){this.z=value;}},"height":{get:function get(){return this.w;},set:function set(value){this.w=value;}}});Object.assign(Vector4$1.prototype,{isVector4:true,set:function set(x,y,z,w){this.x=x;this.y=y;this.z=z;this.w=w;return this;},setScalar:function setScalar(scalar){this.x=scalar;this.y=scalar;this.z=scalar;this.w=scalar;return this;},setX:function setX(x){this.x=x;return this;},setY:function setY(y){this.y=y;return this;},setZ:function setZ(z){this.z=z;return this;},setW:function setW(w){this.w=w;return this;},setComponent:function setComponent(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 getComponent(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 clone(){return new this.constructor(this.x,this.y,this.z,this.w);},copy:function copy(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 add(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 addScalar(s){this.x+=s;this.y+=s;this.z+=s;this.w+=s;return this;},addVectors:function addVectors(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 addScaledVector(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 sub(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 subScalar(s){this.x-=s;this.y-=s;this.z-=s;this.w-=s;return this;},subVectors:function subVectors(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 multiplyScalar(scalar){this.x*=scalar;this.y*=scalar;this.z*=scalar;this.w*=scalar;return this;},applyMatrix4:function applyMatrix4(m){var x=this.x,y=this.y,z=this.z,w=this.w;var 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 divideScalar(scalar){return this.multiplyScalar(1/scalar);},setAxisAngleFromQuaternion:function setAxisAngleFromQuaternion(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);var 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 setAxisAngleFromRotationMatrix(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) var angle,x,y,z,// variables for result 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)yy&&xx>zz){// m11 is the largest diagonal term if(xxzz){// m22 is the largest diagonal term if(yy=0?1:-1,sqrSin=1-cos*cos;// Skip the Slerp for tiny steps to avoid numeric problems: if(sqrSin>Number.EPSILON){var sin=Math.sqrt(sqrSin),len=Math.atan2(sin,cos*dir);s=Math.sin(s*len)/sin;t=Math.sin(t*len)/sin;}var 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){var 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 multiplyQuaternionsFlat(dst,dstOffset,src0,srcOffset0,src1,srcOffset1){var x0=src0[srcOffset0];var y0=src0[srcOffset0+1];var z0=src0[srcOffset0+2];var w0=src0[srcOffset0+3];var x1=src1[srcOffset1];var y1=src1[srcOffset1+1];var z1=src1[srcOffset1+2];var 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$1.prototype,{x:{get:function get(){return this._x;},set:function set(value){this._x=value;this._onChangeCallback();}},y:{get:function get(){return this._y;},set:function set(value){this._y=value;this._onChangeCallback();}},z:{get:function get(){return this._z;},set:function set(value){this._z=value;this._onChangeCallback();}},w:{get:function get(){return this._w;},set:function set(value){this._w=value;this._onChangeCallback();}}});Object.assign(Quaternion$1.prototype,{isQuaternion:true,set:function set(x,y,z,w){this._x=x;this._y=y;this._z=z;this._w=w;this._onChangeCallback();return this;},clone:function clone(){return new this.constructor(this._x,this._y,this._z,this._w);},copy:function copy(quaternion){this._x=quaternion.x;this._y=quaternion.y;this._z=quaternion.z;this._w=quaternion.w;this._onChangeCallback();return this;},setFromEuler:function setFromEuler(euler,update){if(!(euler&&euler.isEuler)){throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');}var 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 var cos=Math.cos;var sin=Math.sin;var c1=cos(x/2);var c2=cos(y/2);var c3=cos(z/2);var s1=sin(x/2);var s2=sin(y/2);var 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 setFromAxisAngle(axis,angle){// http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm // assumes axis is normalized var 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 setFromRotationMatrix(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) var 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,s;if(trace>0){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){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){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{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 setFromUnitVectors(vFrom,vTo){// assumes direction vectors vFrom and vTo are normalized var EPS=0.000001;var r=vFrom.dot(vTo)+1;if(rMath.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 angleTo(q){return 2*Math.acos(Math.abs(MathUtils$1.clamp(this.dot(q),-1,1)));},rotateTowards:function rotateTowards(q,step){var angle=this.angleTo(q);if(angle===0)return this;var t=Math.min(1,step/angle);this.slerp(q,t);return this;},inverse:function inverse(){// quaternion is assumed to have unit length return this.conjugate();},conjugate:function conjugate(){this._x*=-1;this._y*=-1;this._z*=-1;this._onChangeCallback();return this;},dot:function dot(v){return this._x*v._x+this._y*v._y+this._z*v._z+this._w*v._w;},lengthSq:function lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w;},length:function length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w);},normalize:function normalize(){var 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 multiply(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 premultiply(q){return this.multiplyQuaternions(q,this);},multiplyQuaternions:function multiplyQuaternions(a,b){// from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm var qax=a._x,qay=a._y,qaz=a._z,qaw=a._w;var 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 slerp(qb,t){if(t===0)return this;if(t===1)return this.copy(qb);var x=this._x,y=this._y,z=this._z,w=this._w;// http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ var 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;}var sqrSinHalfTheta=1.0-cosHalfTheta*cosHalfTheta;if(sqrSinHalfTheta<=Number.EPSILON){var 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;}var sinHalfTheta=Math.sqrt(sqrSinHalfTheta);var halfTheta=Math.atan2(sinHalfTheta,cosHalfTheta);var 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 equals(quaternion){return quaternion._x===this._x&&quaternion._y===this._y&&quaternion._z===this._z&&quaternion._w===this._w;},fromArray:function fromArray(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 toArray(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 fromBufferAttribute(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 _onChange(callback){this._onChangeCallback=callback;return this;},_onChangeCallback:function _onChangeCallback(){}});/** * @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 */var _vector$c=new Vector3$1();var _quaternion$5=new Quaternion$1();function Vector3$1(x,y,z){this.x=x||0;this.y=y||0;this.z=z||0;}Object.assign(Vector3$1.prototype,{isVector3:true,set:function set(x,y,z){this.x=x;this.y=y;this.z=z;return this;},setScalar:function setScalar(scalar){this.x=scalar;this.y=scalar;this.z=scalar;return this;},setX:function setX(x){this.x=x;return this;},setY:function setY(y){this.y=y;return this;},setZ:function setZ(z){this.z=z;return this;},setComponent:function setComponent(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 getComponent(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 clone(){return new this.constructor(this.x,this.y,this.z);},copy:function copy(v){this.x=v.x;this.y=v.y;this.z=v.z;return this;},add:function add(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 addScalar(s){this.x+=s;this.y+=s;this.z+=s;return this;},addVectors:function addVectors(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this;},addScaledVector:function addScaledVector(v,s){this.x+=v.x*s;this.y+=v.y*s;this.z+=v.z*s;return this;},sub:function sub(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 subScalar(s){this.x-=s;this.y-=s;this.z-=s;return this;},subVectors:function subVectors(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this;},multiply:function multiply(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 multiplyScalar(scalar){this.x*=scalar;this.y*=scalar;this.z*=scalar;return this;},multiplyVectors:function multiplyVectors(a,b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this;},applyEuler:function applyEuler(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$5.setFromEuler(euler));},applyAxisAngle:function applyAxisAngle(axis,angle){return this.applyQuaternion(_quaternion$5.setFromAxisAngle(axis,angle));},applyMatrix3:function applyMatrix3(m){var x=this.x,y=this.y,z=this.z;var 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 applyNormalMatrix(m){return this.applyMatrix3(m).normalize();},applyMatrix4:function applyMatrix4(m){var x=this.x,y=this.y,z=this.z;var e=m.elements;var 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 applyQuaternion(q){var x=this.x,y=this.y,z=this.z;var qx=q.x,qy=q.y,qz=q.z,qw=q.w;// calculate quat * vector var ix=qw*x+qy*z-qz*y;var iy=qw*y+qz*x-qx*z;var iz=qw*z+qx*y-qy*x;var 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 project(camera){return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);},unproject:function unproject(camera){return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);},transformDirection:function transformDirection(m){// input: THREE.Matrix4 affine matrix // vector interpreted as a direction var x=this.x,y=this.y,z=this.z;var 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 divide(v){this.x/=v.x;this.y/=v.y;this.z/=v.z;return this;},divideScalar:function divideScalar(scalar){return this.multiplyScalar(1/scalar);},min:function min(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 max(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 clamp(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 clampScalar(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 clampLength(min,max){var length=this.length();return this.divideScalar(length||1).multiplyScalar(Math.max(min,Math.min(max,length)));},floor:function floor(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this;},ceil:function ceil(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this;},round:function round(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this;},roundToZero:function roundToZero(){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 negate(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this;},dot:function dot(v){return this.x*v.x+this.y*v.y+this.z*v.z;},// TODO lengthSquared? lengthSq:function lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z;},length:function length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z);},manhattanLength:function manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z);},normalize:function normalize(){return this.divideScalar(this.length()||1);},setLength:function setLength(length){return this.normalize().multiplyScalar(length);},lerp:function lerp(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 lerpVectors(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 cross(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 crossVectors(a,b){var ax=a.x,ay=a.y,az=a.z;var 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 projectOnVector(v){var denominator=v.lengthSq();if(denominator===0)return this.set(0,0,0);var scalar=v.dot(this)/denominator;return this.copy(v).multiplyScalar(scalar);},projectOnPlane:function projectOnPlane(planeNormal){_vector$c.copy(this).projectOnVector(planeNormal);return this.sub(_vector$c);},reflect:function reflect(normal){// reflect incident vector off plane orthogonal to normal // normal is assumed to have unit length return this.sub(_vector$c.copy(normal).multiplyScalar(2*this.dot(normal)));},angleTo:function angleTo(v){var denominator=Math.sqrt(this.lengthSq()*v.lengthSq());if(denominator===0)return Math.PI/2;var theta=this.dot(v)/denominator;// clamp, to handle numerical problems return Math.acos(MathUtils$1.clamp(theta,-1,1));},distanceTo:function distanceTo(v){return Math.sqrt(this.distanceToSquared(v));},distanceToSquared:function distanceToSquared(v){var dx=this.x-v.x,dy=this.y-v.y,dz=this.z-v.z;return dx*dx+dy*dy+dz*dz;},manhattanDistanceTo:function manhattanDistanceTo(v){return Math.abs(this.x-v.x)+Math.abs(this.y-v.y)+Math.abs(this.z-v.z);},setFromSpherical:function setFromSpherical(s){return this.setFromSphericalCoords(s.radius,s.phi,s.theta);},setFromSphericalCoords:function setFromSphericalCoords(radius,phi,theta){var 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 setFromCylindrical(c){return this.setFromCylindricalCoords(c.radius,c.theta,c.y);},setFromCylindricalCoords:function setFromCylindricalCoords(radius,theta,y){this.x=radius*Math.sin(theta);this.y=y;this.z=radius*Math.cos(theta);return this;},setFromMatrixPosition:function setFromMatrixPosition(m){var e=m.elements;this.x=e[12];this.y=e[13];this.z=e[14];return this;},setFromMatrixScale:function setFromMatrixScale(m){var sx=this.setFromMatrixColumn(m,0).length();var sy=this.setFromMatrixColumn(m,1).length();var sz=this.setFromMatrixColumn(m,2).length();this.x=sx;this.y=sy;this.z=sz;return this;},setFromMatrixColumn:function setFromMatrixColumn(m,index){return this.fromArray(m.elements,index*4);},setFromMatrix3Column:function setFromMatrix3Column(m,index){return this.fromArray(m.elements,index*3);},equals:function equals(v){return v.x===this.x&&v.y===this.y&&v.z===this.z;},fromArray:function fromArray(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 toArray(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 fromBufferAttribute(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 random(){this.x=Math.random();this.y=Math.random();this.z=Math.random();return this;}});var _v1$6=new Vector3$1();var _m1$4=new Matrix4$1();var _zero$1=new Vector3$1(0,0,0);var _one$1=new Vector3$1(1,1,1);var _x$2=new Vector3$1();var _y$2=new Vector3$1();var _z$2=new Vector3$1();/** * @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$1(){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$1.prototype,{isMatrix4:true,set:function set(n11,n12,n13,n14,n21,n22,n23,n24,n31,n32,n33,n34,n41,n42,n43,n44){var 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 identity(){this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this;},clone:function clone(){return new Matrix4$1().fromArray(this.elements);},copy:function copy(m){var te=this.elements;var 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 copyPosition(m){var te=this.elements,me=m.elements;te[12]=me[12];te[13]=me[13];te[14]=me[14];return this;},extractBasis:function extractBasis(xAxis,yAxis,zAxis){xAxis.setFromMatrixColumn(this,0);yAxis.setFromMatrixColumn(this,1);zAxis.setFromMatrixColumn(this,2);return this;},makeBasis:function makeBasis(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 extractRotation(m){// this method does not support reflection matrices var te=this.elements;var me=m.elements;var scaleX=1/_v1$6.setFromMatrixColumn(m,0).length();var scaleY=1/_v1$6.setFromMatrixColumn(m,1).length();var scaleZ=1/_v1$6.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 makeRotationFromEuler(euler){if(!(euler&&euler.isEuler)){console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');}var te=this.elements;var x=euler.x,y=euler.y,z=euler.z;var a=Math.cos(x),b=Math.sin(x);var c=Math.cos(y),d=Math.sin(y);var e=Math.cos(z),f=Math.sin(z);if(euler.order==='XYZ'){var 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'){var 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'){var 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'){var 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'){var 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'){var 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 makeRotationFromQuaternion(q){return this.compose(_zero$1,q,_one$1);},lookAt:function lookAt(eye,target,up){var te=this.elements;_z$2.subVectors(eye,target);if(_z$2.lengthSq()===0){// eye and target are in the same position _z$2.z=1;}_z$2.normalize();_x$2.crossVectors(up,_z$2);if(_x$2.lengthSq()===0){// up and z are parallel if(Math.abs(up.z)===1){_z$2.x+=0.0001;}else{_z$2.z+=0.0001;}_z$2.normalize();_x$2.crossVectors(up,_z$2);}_x$2.normalize();_y$2.crossVectors(_z$2,_x$2);te[0]=_x$2.x;te[4]=_y$2.x;te[8]=_z$2.x;te[1]=_x$2.y;te[5]=_y$2.y;te[9]=_z$2.y;te[2]=_x$2.z;te[6]=_y$2.z;te[10]=_z$2.z;return this;},multiply:function multiply(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 premultiply(m){return this.multiplyMatrices(m,this);},multiplyMatrices:function multiplyMatrices(a,b){var ae=a.elements;var be=b.elements;var te=this.elements;var a11=ae[0],a12=ae[4],a13=ae[8],a14=ae[12];var a21=ae[1],a22=ae[5],a23=ae[9],a24=ae[13];var a31=ae[2],a32=ae[6],a33=ae[10],a34=ae[14];var a41=ae[3],a42=ae[7],a43=ae[11],a44=ae[15];var b11=be[0],b12=be[4],b13=be[8],b14=be[12];var b21=be[1],b22=be[5],b23=be[9],b24=be[13];var b31=be[2],b32=be[6],b33=be[10],b34=be[14];var 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 multiplyScalar(s){var 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 determinant(){var te=this.elements;var n11=te[0],n12=te[4],n13=te[8],n14=te[12];var n21=te[1],n22=te[5],n23=te[9],n24=te[13];var n31=te[2],n32=te[6],n33=te[10],n34=te[14];var 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 transpose(){var te=this.elements;var 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 setPosition(x,y,z){var 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 getInverse(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 var 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;var 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);var 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 scale(v){var te=this.elements;var 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 getMaxScaleOnAxis(){var te=this.elements;var scaleXSq=te[0]*te[0]+te[1]*te[1]+te[2]*te[2];var scaleYSq=te[4]*te[4]+te[5]*te[5]+te[6]*te[6];var scaleZSq=te[8]*te[8]+te[9]*te[9]+te[10]*te[10];return Math.sqrt(Math.max(scaleXSq,scaleYSq,scaleZSq));},makeTranslation:function makeTranslation(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 makeRotationX(theta){var 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 makeRotationY(theta){var 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 makeRotationZ(theta){var 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 makeRotationAxis(axis,angle){// Based on http://www.gamedev.net/reference/articles/article1199.asp var c=Math.cos(angle);var s=Math.sin(angle);var t=1-c;var x=axis.x,y=axis.y,z=axis.z;var 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 makeScale(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 makeShear(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 compose(position,quaternion,scale){var te=this.elements;var x=quaternion._x,y=quaternion._y,z=quaternion._z,w=quaternion._w;var x2=x+x,y2=y+y,z2=z+z;var xx=x*x2,xy=x*y2,xz=x*z2;var yy=y*y2,yz=y*z2,zz=z*z2;var wx=w*x2,wy=w*y2,wz=w*z2;var 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 decompose(position,quaternion,scale){var te=this.elements;var sx=_v1$6.set(te[0],te[1],te[2]).length();var sy=_v1$6.set(te[4],te[5],te[6]).length();var sz=_v1$6.set(te[8],te[9],te[10]).length();// if determine is negative, we need to invert one scale var 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$4.copy(this);var invSX=1/sx;var invSY=1/sy;var invSZ=1/sz;_m1$4.elements[0]*=invSX;_m1$4.elements[1]*=invSX;_m1$4.elements[2]*=invSX;_m1$4.elements[4]*=invSY;_m1$4.elements[5]*=invSY;_m1$4.elements[6]*=invSY;_m1$4.elements[8]*=invSZ;_m1$4.elements[9]*=invSZ;_m1$4.elements[10]*=invSZ;quaternion.setFromRotationMatrix(_m1$4);scale.x=sx;scale.y=sy;scale.z=sz;return this;},makePerspective:function makePerspective(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.');}var te=this.elements;var x=2*near/(right-left);var y=2*near/(top-bottom);var a=(right+left)/(right-left);var b=(top+bottom)/(top-bottom);var c=-(far+near)/(far-near);var 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 makeOrthographic(left,right,top,bottom,near,far){var te=this.elements;var w=1.0/(right-left);var h=1.0/(top-bottom);var p=1.0/(far-near);var x=(right+left)*w;var y=(top+bottom)*h;var 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 equals(matrix){var te=this.elements;var me=matrix.elements;for(var i=0;i<16;i++){if(te[i]!==me[i])return false;}return true;},fromArray:function fromArray(array,offset){if(offset===undefined)offset=0;for(var i=0;i<16;i++){this.elements[i]=array[i+offset];}return this;},toArray:function toArray(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;var 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 */var _matrix$1=new Matrix4$1();var _quaternion$1$1=new Quaternion$1();function Euler$1(x,y,z,order){this._x=x||0;this._y=y||0;this._z=z||0;this._order=order||Euler$1.DefaultOrder;}Euler$1.RotationOrders=['XYZ','YZX','ZXY','XZY','YXZ','ZYX'];Euler$1.DefaultOrder='XYZ';Object.defineProperties(Euler$1.prototype,{x:{get:function get(){return this._x;},set:function set(value){this._x=value;this._onChangeCallback();}},y:{get:function get(){return this._y;},set:function set(value){this._y=value;this._onChangeCallback();}},z:{get:function get(){return this._z;},set:function set(value){this._z=value;this._onChangeCallback();}},order:{get:function get(){return this._order;},set:function set(value){this._order=value;this._onChangeCallback();}}});Object.assign(Euler$1.prototype,{isEuler:true,set:function set(x,y,z,order){this._x=x;this._y=y;this._z=z;this._order=order||this._order;this._onChangeCallback();return this;},clone:function clone(){return new this.constructor(this._x,this._y,this._z,this._order);},copy:function copy(euler){this._x=euler._x;this._y=euler._y;this._z=euler._z;this._order=euler._order;this._onChangeCallback();return this;},setFromRotationMatrix:function setFromRotationMatrix(m,order,update){var clamp=MathUtils$1.clamp;// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) var te=m.elements;var m11=te[0],m12=te[4],m13=te[8];var m21=te[1],m22=te[5],m23=te[9];var 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 setFromQuaternion(q,order,update){_matrix$1.makeRotationFromQuaternion(q);return this.setFromRotationMatrix(_matrix$1,order,update);},setFromVector3:function setFromVector3(v,order){return this.set(v.x,v.y,v.z,order||this._order);},reorder:function reorder(newOrder){// WARNING: this discards revolution information -bhouston _quaternion$1$1.setFromEuler(this);return this.setFromQuaternion(_quaternion$1$1,newOrder);},equals:function equals(euler){return euler._x===this._x&&euler._y===this._y&&euler._z===this._z&&euler._order===this._order;},fromArray:function fromArray(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 toArray(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 toVector3(optionalResult){if(optionalResult){return optionalResult.set(this._x,this._y,this._z);}else{return new Vector3$1(this._x,this._y,this._z);}},_onChange:function _onChange(callback){this._onChangeCallback=callback;return this;},_onChangeCallback:function _onChangeCallback(){}});/** * @author mrdoob / http://mrdoob.com/ */function Layers$1(){this.mask=1|0;}Object.assign(Layers$1.prototype,{set:function set(channel){this.mask=1<1){for(var i=0;i1){for(var i=0;i0){object.children=[];for(var i=0;i0)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){var values=[];for(var key in cache){var data=cache[key];delete data.metadata;values.push(data);}return values;}},clone:function clone(recursive){return new this.constructor().copy(this,recursive);},copy:function copy(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(var i=0;imaxX)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 setFromBufferAttribute(attribute){var minX=+Infinity;var minY=+Infinity;var minZ=+Infinity;var maxX=-Infinity;var maxY=-Infinity;var maxZ=-Infinity;for(var i=0,l=attribute.count;imaxX)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 setFromPoints(points){this.makeEmpty();for(var i=0,il=points.length;ithis.max.x||point.ythis.max.y||point.zthis.max.z?false:true;},containsBox:function containsBox(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 getParameter(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$1();}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 intersectsBox(box){// using 6 splitting planes to rule out intersections. return box.max.xthis.max.x||box.max.ythis.max.y||box.max.zthis.max.z?false:true;},intersectsSphere:function intersectsSphere(sphere){// Find the point on the AABB closest to the sphere center. this.clampPoint(sphere.center,_vector$1$1);// If that point is inside the sphere, the AABB and sphere intersect. return _vector$1$1.distanceToSquared(sphere.center)<=sphere.radius*sphere.radius;},intersectsPlane:function intersectsPlane(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. var 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 intersectsTriangle(triangle){if(this.isEmpty()){return false;}// compute box center and extents this.getCenter(_center$1);_extents$1.subVectors(this.max,_center$1);// translate triangle to aabb origin _v0$2.subVectors(triangle.a,_center$1);_v1$2$1.subVectors(triangle.b,_center$1);_v2$4.subVectors(triangle.c,_center$1);// compute edge vectors for triangle _f0$1.subVectors(_v1$2$1,_v0$2);_f1$1.subVectors(_v2$4,_v1$2$1);_f2$1.subVectors(_v0$2,_v2$4);// 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) var axes=[0,-_f0$1.z,_f0$1.y,0,-_f1$1.z,_f1$1.y,0,-_f2$1.z,_f2$1.y,_f0$1.z,0,-_f0$1.x,_f1$1.z,0,-_f1$1.x,_f2$1.z,0,-_f2$1.x,-_f0$1.y,_f0$1.x,0,-_f1$1.y,_f1$1.x,0,-_f2$1.y,_f2$1.x,0];if(!satForAxes$1(axes,_v0$2,_v1$2$1,_v2$4,_extents$1)){return false;}// test 3 face normals from the aabb axes=[1,0,0,0,1,0,0,0,1];if(!satForAxes$1(axes,_v0$2,_v1$2$1,_v2$4,_extents$1)){return false;}// finally testing the face normal of the triangle // use already existing triangle edge vectors here _triangleNormal$1.crossVectors(_f0$1,_f1$1);axes=[_triangleNormal$1.x,_triangleNormal$1.y,_triangleNormal$1.z];return satForAxes$1(axes,_v0$2,_v1$2$1,_v2$4,_extents$1);},clampPoint:function clampPoint(point,target){if(target===undefined){console.warn('THREE.Box3: .clampPoint() target is now required');target=new Vector3$1();}return target.copy(point).clamp(this.min,this.max);},distanceToPoint:function distanceToPoint(point){var clampedPoint=_vector$1$1.copy(point).clamp(this.min,this.max);return clampedPoint.sub(point).length();},getBoundingSphere:function getBoundingSphere(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$1).length()*0.5;return target;},intersect:function intersect(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 union(box){this.min.min(box.min);this.max.max(box.max);return this;},applyMatrix4:function applyMatrix4(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$1[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(matrix);// 000 _points$1[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(matrix);// 001 _points$1[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(matrix);// 010 _points$1[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(matrix);// 011 _points$1[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(matrix);// 100 _points$1[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(matrix);// 101 _points$1[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(matrix);// 110 _points$1[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(matrix);// 111 this.setFromPoints(_points$1);return this;},translate:function translate(offset){this.min.add(offset);this.max.add(offset);return this;},equals:function equals(box){return box.min.equals(this.min)&&box.max.equals(this.max);}});function satForAxes$1(axes,v0,v1,v2,extents){var i,j;for(i=0,j=axes.length-3;i<=j;i+=3){_testAxis$1.fromArray(axes,i);// project the aabb onto the seperating axis var r=extents.x*Math.abs(_testAxis$1.x)+extents.y*Math.abs(_testAxis$1.y)+extents.z*Math.abs(_testAxis$1.z);// project all 3 vertices of the triangle onto the seperating axis var p0=v0.dot(_testAxis$1);var p1=v1.dot(_testAxis$1);var p2=v2.dot(_testAxis$1);// 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;}var _box$1$1=new Box3$1();/** * @author bhouston / http://clara.io * @author mrdoob / http://mrdoob.com/ */function Sphere$1(center,radius){this.center=center!==undefined?center:new Vector3$1();this.radius=radius!==undefined?radius:-1;}Object.assign(Sphere$1.prototype,{set:function set(center,radius){this.center.copy(center);this.radius=radius;return this;},setFromPoints:function setFromPoints(points,optionalCenter){var center=this.center;if(optionalCenter!==undefined){center.copy(optionalCenter);}else{_box$1$1.setFromPoints(points).getCenter(center);}var maxRadiusSq=0;for(var i=0,il=points.length;ithis.radius*this.radius){target.sub(this.center).normalize();target.multiplyScalar(this.radius).add(this.center);}return target;},getBoundingBox:function getBoundingBox(target){if(target===undefined){console.warn('THREE.Sphere: .getBoundingBox() target is now required');target=new Box3$1();}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 applyMatrix4(matrix){this.center.applyMatrix4(matrix);this.radius=this.radius*matrix.getMaxScaleOnAxis();return this;},translate:function translate(offset){this.center.add(offset);return this;},equals:function equals(sphere){return sphere.center.equals(this.center)&&sphere.radius===this.radius;}});var _vector$2$1=new Vector3$1();var _segCenter$1=new Vector3$1();var _segDir$1=new Vector3$1();var _diff$1=new Vector3$1();var _edge1$1=new Vector3$1();var _edge2$1=new Vector3$1();var _normal$1=new Vector3$1();/** * @author bhouston / http://clara.io */function Ray$1(origin,direction){this.origin=origin!==undefined?origin:new Vector3$1();this.direction=direction!==undefined?direction:new Vector3$1(0,0,-1);}Object.assign(Ray$1.prototype,{set:function set(origin,direction){this.origin.copy(origin);this.direction.copy(direction);return this;},clone:function clone(){return new this.constructor().copy(this);},copy:function copy(ray){this.origin.copy(ray.origin);this.direction.copy(ray.direction);return this;},at:function at(t,target){if(target===undefined){console.warn('THREE.Ray: .at() target is now required');target=new Vector3$1();}return target.copy(this.direction).multiplyScalar(t).add(this.origin);},lookAt:function lookAt(v){this.direction.copy(v).sub(this.origin).normalize();return this;},recast:function recast(t){this.origin.copy(this.at(t,_vector$2$1));return this;},closestPointToPoint:function closestPointToPoint(point,target){if(target===undefined){console.warn('THREE.Ray: .closestPointToPoint() target is now required');target=new Vector3$1();}target.subVectors(point,this.origin);var 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 distanceToPoint(point){return Math.sqrt(this.distanceSqToPoint(point));},distanceSqToPoint:function distanceSqToPoint(point){var directionDistance=_vector$2$1.subVectors(point,this.origin).dot(this.direction);// point behind the ray if(directionDistance<0){return this.origin.distanceToSquared(point);}_vector$2$1.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);return _vector$2$1.distanceToSquared(point);},distanceSqToSegment:function distanceSqToSegment(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$1.copy(v0).add(v1).multiplyScalar(0.5);_segDir$1.copy(v1).sub(v0).normalize();_diff$1.copy(this.origin).sub(_segCenter$1);var segExtent=v0.distanceTo(v1)*0.5;var a01=-this.direction.dot(_segDir$1);var b0=_diff$1.dot(this.direction);var b1=-_diff$1.dot(_segDir$1);var c=_diff$1.lengthSq();var det=Math.abs(1-a01*a01);var 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. var 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$1).multiplyScalar(s1).add(_segCenter$1);}return sqrDist;},intersectSphere:function intersectSphere(sphere,target){_vector$2$1.subVectors(sphere.center,this.origin);var tca=_vector$2$1.dot(this.direction);var d2=_vector$2$1.dot(_vector$2$1)-tca*tca;var radius2=sphere.radius*sphere.radius;if(d2>radius2)return null;var thc=Math.sqrt(radius2-d2);// t0 = first intersect point - entrance on front of sphere var t0=tca-thc;// t1 = second intersect point - exit point on back of sphere var 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 intersectsSphere(sphere){return this.distanceSqToPoint(sphere.center)<=sphere.radius*sphere.radius;},distanceToPlane:function distanceToPlane(plane){var 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;}var t=-(this.origin.dot(plane.normal)+plane.constant)/denominator;// Return if the ray never intersects the plane return t>=0?t:null;},intersectPlane:function intersectPlane(plane,target){var t=this.distanceToPlane(plane);if(t===null){return null;}return this.at(t,target);},intersectsPlane:function intersectsPlane(plane){// check if the ray lies on the plane first var distToPoint=plane.distanceToPoint(this.origin);if(distToPoint===0){return true;}var 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 intersectBox(box,target){var tmin,tmax,tymin,tymax,tzmin,tzmax;var invdirx=1/this.direction.x,invdiry=1/this.direction.y,invdirz=1/this.direction.z;var 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=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=0?tmin:tmax,target);},intersectsBox:function intersectsBox(box){return this.intersectBox(box,_vector$2$1)!==null;},intersectTriangle:function intersectTriangle(a,b,c,backfaceCulling,target){// Compute the offset origin, edges, and normal. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h _edge1$1.subVectors(b,a);_edge2$1.subVectors(c,a);_normal$1.crossVectors(_edge1$1,_edge2$1);// 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) var DdN=this.direction.dot(_normal$1);var sign;if(DdN>0){if(backfaceCulling)return null;sign=1;}else if(DdN<0){sign=-1;DdN=-DdN;}else{return null;}_diff$1.subVectors(this.origin,a);var DdQxE2=sign*this.direction.dot(_edge2$1.crossVectors(_diff$1,_edge2$1));// b1 < 0, no intersection if(DdQxE2<0){return null;}var DdE1xQ=sign*this.direction.dot(_edge1$1.cross(_diff$1));// 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. var QdN=-sign*_diff$1.dot(_normal$1);// t < 0, no intersection if(QdN<0){return null;}// Ray intersects triangle. return this.at(QdN/DdN,target);},applyMatrix4:function applyMatrix4(matrix4){this.origin.applyMatrix4(matrix4);this.direction.transformDirection(matrix4);return this;},equals:function equals(ray){return ray.origin.equals(this.origin)&&ray.direction.equals(this.direction);}});/** * @author bhouston / http://clara.io */var _vector1$1=new Vector3$1();var _vector2$1=new Vector3$1();var _normalMatrix$1=new Matrix3$1();function Plane$1(normal,constant){// normal is assumed to be normalized this.normal=normal!==undefined?normal:new Vector3$1(1,0,0);this.constant=constant!==undefined?constant:0;}Object.assign(Plane$1.prototype,{isPlane:true,set:function set(normal,constant){this.normal.copy(normal);this.constant=constant;return this;},setComponents:function setComponents(x,y,z,w){this.normal.set(x,y,z);this.constant=w;return this;},setFromNormalAndCoplanarPoint:function setFromNormalAndCoplanarPoint(normal,point){this.normal.copy(normal);this.constant=-point.dot(this.normal);return this;},setFromCoplanarPoints:function setFromCoplanarPoints(a,b,c){var normal=_vector1$1.subVectors(c,b).cross(_vector2$1.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 clone(){return new this.constructor().copy(this);},copy:function copy(plane){this.normal.copy(plane.normal);this.constant=plane.constant;return this;},normalize:function normalize(){// Note: will lead to a divide by zero if the plane is invalid. var inverseNormalLength=1.0/this.normal.length();this.normal.multiplyScalar(inverseNormalLength);this.constant*=inverseNormalLength;return this;},negate:function negate(){this.constant*=-1;this.normal.negate();return this;},distanceToPoint:function distanceToPoint(point){return this.normal.dot(point)+this.constant;},distanceToSphere:function distanceToSphere(sphere){return this.distanceToPoint(sphere.center)-sphere.radius;},projectPoint:function projectPoint(point,target){if(target===undefined){console.warn('THREE.Plane: .projectPoint() target is now required');target=new Vector3$1();}return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);},intersectLine:function intersectLine(line,target){if(target===undefined){console.warn('THREE.Plane: .intersectLine() target is now required');target=new Vector3$1();}var direction=line.delta(_vector1$1);var 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;}var 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 intersectsLine(line){// Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. var startSign=this.distanceToPoint(line.start);var endSign=this.distanceToPoint(line.end);return startSign<0&&endSign>0||endSign<0&&startSign>0;},intersectsBox:function intersectsBox(box){return box.intersectsPlane(this);},intersectsSphere:function intersectsSphere(sphere){return sphere.intersectsPlane(this);},coplanarPoint:function coplanarPoint(target){if(target===undefined){console.warn('THREE.Plane: .coplanarPoint() target is now required');target=new Vector3$1();}return target.copy(this.normal).multiplyScalar(-this.constant);},applyMatrix4:function applyMatrix4(matrix,optionalNormalMatrix){var normalMatrix=optionalNormalMatrix||_normalMatrix$1.getNormalMatrix(matrix);var referencePoint=this.coplanarPoint(_vector1$1).applyMatrix4(matrix);var normal=this.normal.applyMatrix3(normalMatrix).normalize();this.constant=-referencePoint.dot(normal);return this;},translate:function translate(offset){this.constant-=offset.dot(this.normal);return this;},equals:function equals(plane){return plane.normal.equals(this.normal)&&plane.constant===this.constant;}});/** * @author bhouston / http://clara.io * @author mrdoob / http://mrdoob.com/ */var _v0$1$1=new Vector3$1();var _v1$3$1=new Vector3$1();var _v2$1$1=new Vector3$1();var _v3$2=new Vector3$1();var _vab$1=new Vector3$1();var _vac$1=new Vector3$1();var _vbc$1=new Vector3$1();var _vap$1=new Vector3$1();var _vbp$1=new Vector3$1();var _vcp$1=new Vector3$1();function Triangle$1(a,b,c){this.a=a!==undefined?a:new Vector3$1();this.b=b!==undefined?b:new Vector3$1();this.c=c!==undefined?c:new Vector3$1();}Object.assign(Triangle$1,{getNormal:function getNormal(a,b,c,target){if(target===undefined){console.warn('THREE.Triangle: .getNormal() target is now required');target=new Vector3$1();}target.subVectors(c,b);_v0$1$1.subVectors(a,b);target.cross(_v0$1$1);var 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 getBarycoord(point,a,b,c,target){_v0$1$1.subVectors(c,a);_v1$3$1.subVectors(b,a);_v2$1$1.subVectors(point,a);var dot00=_v0$1$1.dot(_v0$1$1);var dot01=_v0$1$1.dot(_v1$3$1);var dot02=_v0$1$1.dot(_v2$1$1);var dot11=_v1$3$1.dot(_v1$3$1);var dot12=_v1$3$1.dot(_v2$1$1);var denom=dot00*dot11-dot01*dot01;if(target===undefined){console.warn('THREE.Triangle: .getBarycoord() target is now required');target=new Vector3$1();}// 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);}var invDenom=1/denom;var u=(dot11*dot02-dot01*dot12)*invDenom;var v=(dot00*dot12-dot01*dot02)*invDenom;// barycentric coordinates must always sum to 1 return target.set(1-u-v,v,u);},containsPoint:function containsPoint(point,a,b,c){Triangle$1.getBarycoord(point,a,b,c,_v3$2);return _v3$2.x>=0&&_v3$2.y>=0&&_v3$2.x+_v3$2.y<=1;},getUV:function getUV(point,p1,p2,p3,uv1,uv2,uv3,target){this.getBarycoord(point,p1,p2,p3,_v3$2);target.set(0,0);target.addScaledVector(uv1,_v3$2.x);target.addScaledVector(uv2,_v3$2.y);target.addScaledVector(uv3,_v3$2.z);return target;},isFrontFacing:function isFrontFacing(a,b,c,direction){_v0$1$1.subVectors(c,b);_v1$3$1.subVectors(a,b);// strictly front facing return _v0$1$1.cross(_v1$3$1).dot(direction)<0?true:false;}});Object.assign(Triangle$1.prototype,{set:function set(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this;},setFromPointsAndIndices:function setFromPointsAndIndices(points,i0,i1,i2){this.a.copy(points[i0]);this.b.copy(points[i1]);this.c.copy(points[i2]);return this;},clone:function clone(){return new this.constructor().copy(this);},copy:function copy(triangle){this.a.copy(triangle.a);this.b.copy(triangle.b);this.c.copy(triangle.c);return this;},getArea:function getArea(){_v0$1$1.subVectors(this.c,this.b);_v1$3$1.subVectors(this.a,this.b);return _v0$1$1.cross(_v1$3$1).length()*0.5;},getMidpoint:function getMidpoint(target){if(target===undefined){console.warn('THREE.Triangle: .getMidpoint() target is now required');target=new Vector3$1();}return target.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3);},getNormal:function getNormal(target){return Triangle$1.getNormal(this.a,this.b,this.c,target);},getPlane:function getPlane(target){if(target===undefined){console.warn('THREE.Triangle: .getPlane() target is now required');target=new Plane$1();}return target.setFromCoplanarPoints(this.a,this.b,this.c);},getBarycoord:function getBarycoord(point,target){return Triangle$1.getBarycoord(point,this.a,this.b,this.c,target);},getUV:function getUV(point,uv1,uv2,uv3,target){return Triangle$1.getUV(point,this.a,this.b,this.c,uv1,uv2,uv3,target);},containsPoint:function containsPoint(point){return Triangle$1.containsPoint(point,this.a,this.b,this.c);},isFrontFacing:function isFrontFacing(direction){return Triangle$1.isFrontFacing(this.a,this.b,this.c,direction);},intersectsBox:function intersectsBox(box){return box.intersectsTriangle(this);},closestPointToPoint:function closestPointToPoint(p,target){if(target===undefined){console.warn('THREE.Triangle: .closestPointToPoint() target is now required');target=new Vector3$1();}var a=this.a,b=this.b,c=this.c;var 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$1.subVectors(b,a);_vac$1.subVectors(c,a);_vap$1.subVectors(p,a);var d1=_vab$1.dot(_vap$1);var d2=_vac$1.dot(_vap$1);if(d1<=0&&d2<=0){// vertex region of A; barycentric coords (1, 0, 0) return target.copy(a);}_vbp$1.subVectors(p,b);var d3=_vab$1.dot(_vbp$1);var d4=_vac$1.dot(_vbp$1);if(d3>=0&&d4<=d3){// vertex region of B; barycentric coords (0, 1, 0) return target.copy(b);}var 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$1,v);}_vcp$1.subVectors(p,c);var d5=_vab$1.dot(_vcp$1);var d6=_vac$1.dot(_vcp$1);if(d6>=0&&d5<=d6){// vertex region of C; barycentric coords (0, 0, 1) return target.copy(c);}var 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$1,w);}var va=d3*d6-d5*d4;if(va<=0&&d4-d3>=0&&d5-d6>=0){_vbc$1.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$1,w);// edge region of BC }// face region var denom=1/(va+vb+vc);// u = va * denom v=vb*denom;w=vc*denom;return target.copy(a).addScaledVector(_vab$1,v).addScaledVector(_vac$1,w);},equals:function equals(triangle){return triangle.a.equals(this.a)&&triangle.b.equals(this.b)&&triangle.c.equals(this.c);}});/** * @author mrdoob / http://mrdoob.com/ */var _colorKeywords$1={'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};var _hslA$1={h:0,s:0,l:0};var _hslB$1={h:0,s:0,l:0};function Color$1(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$1(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$1(c){return c<0.04045?c*0.0773993808:Math.pow(c*0.9478672986+0.0521327014,2.4);}function LinearToSRGB$1(c){return c<0.0031308?c*12.92:1.055*Math.pow(c,0.41666)-0.055;}Object.assign(Color$1.prototype,{isColor:true,r:1,g:1,b:1,set:function set(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 setScalar(scalar){this.r=scalar;this.g=scalar;this.b=scalar;return this;},setHex:function setHex(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 setRGB(r,g,b){this.r=r;this.g=g;this.b=b;return this;},setHSL:function setHSL(h,s,l){// h,s,l ranges are in 0.0 - 1.0 h=MathUtils$1.euclideanModulo(h,1);s=MathUtils$1.clamp(s,0,1);l=MathUtils$1.clamp(l,0,1);if(s===0){this.r=this.g=this.b=l;}else{var p=l<=0.5?l*(1+s):l+s-l*s;var q=2*l-p;this.r=hue2rgb$1(q,p,h+1/3);this.g=hue2rgb$1(q,p,h);this.b=hue2rgb$1(q,p,h-1/3);}return this;},setStyle:function setStyle(style){function handleAlpha(string){if(string===undefined)return;if(parseFloat(string)<1){console.warn('THREE.Color: Alpha component of '+style+' will be ignored.');}}var m;if(m=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)){// rgb / hsl var color;var name=m[1];var 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) var h=parseFloat(color[1])/360;var s=parseInt(color[2],10)/100;var 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 var hex=m[1];var 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 setColorName(style){// color keywords var hex=_colorKeywords$1[style];if(hex!==undefined){// red this.setHex(hex);}else{// unknown color console.warn('THREE.Color: Unknown color '+style);}return this;},clone:function clone(){return new this.constructor(this.r,this.g,this.b);},copy:function copy(color){this.r=color.r;this.g=color.g;this.b=color.b;return this;},copyGammaToLinear:function copyGammaToLinear(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 copyLinearToGamma(color,gammaFactor){if(gammaFactor===undefined)gammaFactor=2.0;var 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 convertGammaToLinear(gammaFactor){this.copyGammaToLinear(this,gammaFactor);return this;},convertLinearToGamma:function convertLinearToGamma(gammaFactor){this.copyLinearToGamma(this,gammaFactor);return this;},copySRGBToLinear:function copySRGBToLinear(color){this.r=SRGBToLinear$1(color.r);this.g=SRGBToLinear$1(color.g);this.b=SRGBToLinear$1(color.b);return this;},copyLinearToSRGB:function copyLinearToSRGB(color){this.r=LinearToSRGB$1(color.r);this.g=LinearToSRGB$1(color.g);this.b=LinearToSRGB$1(color.b);return this;},convertSRGBToLinear:function convertSRGBToLinear(){this.copySRGBToLinear(this);return this;},convertLinearToSRGB:function convertLinearToSRGB(){this.copyLinearToSRGB(this);return this;},getHex:function getHex(){return this.r*255<<16^this.g*255<<8^this.b*255<<0;},getHexString:function getHexString(){return('000000'+this.getHex().toString(16)).slice(-6);},getHSL:function getHSL(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};}var r=this.r,g=this.g,b=this.b;var max=Math.max(r,g,b);var min=Math.min(r,g,b);var hue,saturation;var lightness=(min+max)/2.0;if(min===max){hue=0;saturation=0;}else{var delta=max-min;saturation=lightness<=0.5?delta/(max+min):delta/(2-max-min);switch(max){case r:hue=(g-b)/delta+(g0)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){var values=[];for(var key in cache){var data=cache[key];delete data.metadata;values.push(data);}return values;}if(isRoot){var textures=extractFromCache(meta.textures);var images=extractFromCache(meta.images);if(textures.length>0)data.textures=textures;if(images.length>0)data.images=images;}return data;},clone:function clone(){return new this.constructor().copy(this);},copy:function copy(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;var srcPlanes=source.clippingPlanes,dstPlanes=null;if(srcPlanes!==null){var n=srcPlanes.length;dstPlanes=new Array(n);for(var 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 dispose(){this.dispatchEvent({type:'dispose'});}});Object.defineProperty(Material$1.prototype,'needsUpdate',{set:function set(value){if(value===true)this.version++;}});/** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * * parameters = { * color: , * opacity: , * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * specularMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.Multiply, * reflectivity: , * refractionRatio: , * * depthTest: , * depthWrite: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: * } */function MeshBasicMaterial$1(parameters){Material$1.call(this);this.type='MeshBasicMaterial';this.color=new Color$1(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$1;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$1.prototype=Object.create(Material$1.prototype);MeshBasicMaterial$1.prototype.constructor=MeshBasicMaterial$1;MeshBasicMaterial$1.prototype.isMeshBasicMaterial=true;MeshBasicMaterial$1.prototype.copy=function(source){Material$1.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/ */var _vector$3$1=new Vector3$1();function BufferAttribute$1(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$1;this.updateRange={offset:0,count:-1};this.version=0;}Object.defineProperty(BufferAttribute$1.prototype,'needsUpdate',{set:function set(value){if(value===true)this.version++;}});Object.assign(BufferAttribute$1.prototype,{isBufferAttribute:true,onUploadCallback:function onUploadCallback(){},setUsage:function setUsage(value){this.usage=value;return this;},copy:function copy(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 copyAt(index1,attribute,index2){index1*=this.itemSize;index2*=attribute.itemSize;for(var i=0,l=this.itemSize;i0;var hasFaceVertexUv2=faceVertexUvs[1]&&faceVertexUvs[1].length>0;// morphs var morphTargets=geometry.morphTargets;var morphTargetsLength=morphTargets.length;var morphTargetsPosition;if(morphTargetsLength>0){morphTargetsPosition=[];for(var i=0;i0){morphTargetsNormal=[];for(var i=0;i0&&faces.length===0){console.error('THREE.DirectGeometry: Faceless geometries are not supported.');}for(var i=0;imax)max=array[_i21];}return max;}/** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */var _bufferGeometryId$1=1;// BufferGeometry uses odd numbers as Id var _m1$2$1=new Matrix4$1();var _obj$2=new Object3D$1();var _offset$2=new Vector3$1();var _box$2$1=new Box3$1();var _boxMorphTargets$1=new Box3$1();var _vector$4$1=new Vector3$1();function BufferGeometry$1(){Object.defineProperty(this,'id',{value:_bufferGeometryId$1+=2});this.uuid=MathUtils$1.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$1.prototype=Object.assign(Object.create(EventDispatcher$1.prototype),{constructor:BufferGeometry$1,isBufferGeometry:true,getIndex:function getIndex(){return this.index;},setIndex:function setIndex(index){if(Array.isArray(index)){this.index=new(arrayMax$1(index)>65535?Uint32BufferAttribute$1:Uint16BufferAttribute$1)(index,1);}else{this.index=index;}},getAttribute:function getAttribute(name){return this.attributes[name];},setAttribute:function setAttribute(name,attribute){this.attributes[name]=attribute;return this;},deleteAttribute:function deleteAttribute(name){delete this.attributes[name];return this;},addGroup:function addGroup(start,count,materialIndex){this.groups.push({start:start,count:count,materialIndex:materialIndex!==undefined?materialIndex:0});},clearGroups:function clearGroups(){this.groups=[];},setDrawRange:function setDrawRange(start,count){this.drawRange.start=start;this.drawRange.count=count;},applyMatrix4:function applyMatrix4(matrix){var position=this.attributes.position;if(position!==undefined){position.applyMatrix4(matrix);position.needsUpdate=true;}var normal=this.attributes.normal;if(normal!==undefined){var normalMatrix=new Matrix3$1().getNormalMatrix(matrix);normal.applyNormalMatrix(normalMatrix);normal.needsUpdate=true;}var 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 rotateX(angle){// rotate geometry around world x-axis _m1$2$1.makeRotationX(angle);this.applyMatrix4(_m1$2$1);return this;},rotateY:function rotateY(angle){// rotate geometry around world y-axis _m1$2$1.makeRotationY(angle);this.applyMatrix4(_m1$2$1);return this;},rotateZ:function rotateZ(angle){// rotate geometry around world z-axis _m1$2$1.makeRotationZ(angle);this.applyMatrix4(_m1$2$1);return this;},translate:function translate(x,y,z){// translate geometry _m1$2$1.makeTranslation(x,y,z);this.applyMatrix4(_m1$2$1);return this;},scale:function scale(x,y,z){// scale geometry _m1$2$1.makeScale(x,y,z);this.applyMatrix4(_m1$2$1);return this;},lookAt:function lookAt(vector){_obj$2.lookAt(vector);_obj$2.updateMatrix();this.applyMatrix4(_obj$2.matrix);return this;},center:function center(){this.computeBoundingBox();this.boundingBox.getCenter(_offset$2).negate();this.translate(_offset$2.x,_offset$2.y,_offset$2.z);return this;},setFromObject:function setFromObject(object){// console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this ); var geometry=object.geometry;if(object.isPoints||object.isLine){var positions=new Float32BufferAttribute$1(geometry.vertices.length*3,3);var colors=new Float32BufferAttribute$1(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){var lineDistances=new Float32BufferAttribute$1(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 setFromPoints(points){var position=[];for(var i=0,l=points.length;i0){var normals=new Float32Array(geometry.normals.length*3);this.setAttribute('normal',new BufferAttribute$1(normals,3).copyVector3sArray(geometry.normals));}if(geometry.colors.length>0){var colors=new Float32Array(geometry.colors.length*3);this.setAttribute('color',new BufferAttribute$1(colors,3).copyColorsArray(geometry.colors));}if(geometry.uvs.length>0){var uvs=new Float32Array(geometry.uvs.length*2);this.setAttribute('uv',new BufferAttribute$1(uvs,2).copyVector2sArray(geometry.uvs));}if(geometry.uvs2.length>0){var uvs2=new Float32Array(geometry.uvs2.length*2);this.setAttribute('uv2',new BufferAttribute$1(uvs2,2).copyVector2sArray(geometry.uvs2));}// groups this.groups=geometry.groups;// morphs for(var name in geometry.morphTargets){var array=[];var morphTargets=geometry.morphTargets[name];for(var i=0,l=morphTargets.length;i0){var skinIndices=new Float32BufferAttribute$1(geometry.skinIndices.length*4,4);this.setAttribute('skinIndex',skinIndices.copyVector4sArray(geometry.skinIndices));}if(geometry.skinWeights.length>0){var skinWeights=new Float32BufferAttribute$1(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 computeBoundingBox(){if(this.boundingBox===null){this.boundingBox=new Box3$1();}var position=this.attributes.position;var morphAttributesPosition=this.morphAttributes.position;if(position!==undefined){this.boundingBox.setFromBufferAttribute(position);// process morph attributes if present if(morphAttributesPosition){for(var i=0,il=morphAttributesPosition.length;i0)data.userData=this.userData;if(this.parameters!==undefined){var parameters=this.parameters;for(var key in parameters){if(parameters[key]!==undefined)data[key]=parameters[key];}return data;}data.data={attributes:{}};var index=this.index;if(index!==null){data.data.index={type:index.array.constructor.name,array:Array.prototype.slice.call(index.array)};}var attributes=this.attributes;for(var key in attributes){var attribute=attributes[key];var attributeData=attribute.toJSON();if(attribute.name!=='')attributeData.name=attribute.name;data.data.attributes[key]=attributeData;}var morphAttributes={};var hasMorphAttributes=false;for(var key in this.morphAttributes){var attributeArray=this.morphAttributes[key];var array=[];for(var i=0,il=attributeArray.length;i0){morphAttributes[key]=array;hasMorphAttributes=true;}}if(hasMorphAttributes){data.data.morphAttributes=morphAttributes;data.data.morphTargetsRelative=this.morphTargetsRelative;}var groups=this.groups;if(groups.length>0){data.data.groups=JSON.parse(JSON.stringify(groups));}var boundingSphere=this.boundingSphere;if(boundingSphere!==null){data.data.boundingSphere={center:boundingSphere.center.toArray(),radius:boundingSphere.radius};}return data;},clone:function clone(){/* // Handle primitives var parameters = this.parameters; if ( parameters !== undefined ) { var values = []; for ( var key in parameters ) { values.push( parameters[ key ] ); } var geometry = Object.create( this.constructor.prototype ); this.constructor.apply( geometry, values ); return geometry; } return new this.constructor().copy( this ); */return new BufferGeometry$1().copy(this);},copy:function copy(source){var name,i,l;// reset this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingBox=null;this.boundingSphere=null;// name this.name=source.name;// index var index=source.index;if(index!==null){this.setIndex(index.clone());}// attributes var attributes=source.attributes;for(name in attributes){var attribute=attributes[name];this.setAttribute(name,attribute.clone());}// morph attributes var morphAttributes=source.morphAttributes;for(name in morphAttributes){var array=[];var morphAttribute=morphAttributes[name];// morphAttribute: array of Float32BufferAttributes for(i=0,l=morphAttribute.length;i0){var morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==undefined){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(m=0,ml=morphAttribute.length;m0){console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');}}},raycast:function raycast(raycaster,intersects){var geometry=this.geometry;var material=this.material;var matrixWorld=this.matrixWorld;if(material===undefined)return;// Checking boundingSphere distance to ray if(geometry.boundingSphere===null)geometry.computeBoundingSphere();_sphere$4.copy(geometry.boundingSphere);_sphere$4.applyMatrix4(matrixWorld);if(raycaster.ray.intersectsSphere(_sphere$4)===false)return;// _inverseMatrix$3.getInverse(matrixWorld);_ray$3.copy(raycaster.ray).applyMatrix4(_inverseMatrix$3);// Check boundingBox before continuing if(geometry.boundingBox!==null){if(_ray$3.intersectsBox(geometry.boundingBox)===false)return;}var intersection;if(geometry.isBufferGeometry){var a,b,c;var index=geometry.index;var position=geometry.attributes.position;var morphPosition=geometry.morphAttributes.position;var morphTargetsRelative=geometry.morphTargetsRelative;var uv=geometry.attributes.uv;var uv2=geometry.attributes.uv2;var groups=geometry.groups;var drawRange=geometry.drawRange;var i,j,il,jl;var group,groupMaterial;var start,end;if(index!==null){// indexed buffer geometry if(Array.isArray(material)){for(i=0,il=groups.length;i0)uvs=faceVertexUvs;for(var f=0,fl=faces.length;fraycaster.far)return null;return{distance:distance,point:_intersectionPointWorld$1.clone(),object:object};}function checkBufferGeometryIntersection$1(object,material,raycaster,ray,position,morphPosition,morphTargetsRelative,uv,uv2,a,b,c){_vA$2.fromBufferAttribute(position,a);_vB$2.fromBufferAttribute(position,b);_vC$2.fromBufferAttribute(position,c);var morphInfluences=object.morphTargetInfluences;if(material.morphTargets&&morphPosition&&morphInfluences){_morphA$1.set(0,0,0);_morphB$1.set(0,0,0);_morphC$1.set(0,0,0);for(var i=0,il=morphPosition.length;i0){for(var i=0;i0){this.normalsNeedUpdate=true;}},computeFlatVertexNormals:function computeFlatVertexNormals(){var f,fl,face;this.computeFaceNormals();for(f=0,fl=this.faces.length;f0){this.normalsNeedUpdate=true;}},computeMorphNormals:function computeMorphNormals(){var i,il,f,fl,face;// save original normals // - create temp variables on first access // otherwise just copy (for faster repeated calls) for(f=0,fl=this.faces.length;f=0;i--){var idx=faceIndicesToRemove[i];this.faces.splice(idx,1);for(j=0,jl=this.faceVertexUvs.length;j0;var hasFaceVertexNormal=face.vertexNormals.length>0;var hasFaceColor=face.color.r!==1||face.color.g!==1||face.color.b!==1;var hasFaceVertexColor=face.vertexColors.length>0;var 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){var 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){var vertexNormals=face.vertexNormals;faces.push(getNormalIndex(vertexNormals[0]),getNormalIndex(vertexNormals[1]),getNormalIndex(vertexNormals[2]));}if(hasFaceColor){faces.push(getColorIndex(face.color));}if(hasFaceVertexColor){var vertexColors=face.vertexColors;faces.push(getColorIndex(vertexColors[0]),getColorIndex(vertexColors[1]),getColorIndex(vertexColors[2]));}}function setBit(value,position,enabled){return enabled?value|1<0)data.data.colors=colors;if(uvs.length>0)data.data.uvs=[uvs];// temporal backward compatibility data.data.faces=faces;return data;},clone:function clone(){/* // Handle primitives var parameters = this.parameters; if ( parameters !== undefined ) { var values = []; for ( var key in parameters ) { values.push( parameters[ key ] ); } var geometry = Object.create( this.constructor.prototype ); this.constructor.apply( geometry, values ); return geometry; } return new this.constructor().copy( this ); */return new Geometry$1().copy(this);},copy:function copy(source){var i,il,j,jl,k,kl;// 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 var vertices=source.vertices;for(i=0,il=vertices.length;i0?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(var _iy2=0;_iy2, * vertexShader: , * * wireframe: , * wireframeLinewidth: , * * lights: , * * skinning: , * morphTargets: , * morphNormals: * } */function ShaderMaterial$1(parameters){Material$1.call(this);this.type='ShaderMaterial';this.defines={};this.uniforms={};this.vertexShader=default_vertex$1;this.fragmentShader=default_fragment$1;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$1.prototype=Object.create(Material$1.prototype);ShaderMaterial$1.prototype.constructor=ShaderMaterial$1;ShaderMaterial$1.prototype.isShaderMaterial=true;ShaderMaterial$1.prototype.copy=function(source){Material$1.prototype.copy.call(this,source);this.fragmentShader=source.fragmentShader;this.vertexShader=source.vertexShader;this.uniforms=cloneUniforms$1(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$1.prototype.toJSON=function(meta){var data=Material$1.prototype.toJSON.call(this,meta);data.uniforms={};for(var name in this.uniforms){var uniform=this.uniforms[name];var 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;var extensions={};for(var 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$1(){Object3D$1.call(this);this.type='Camera';this.matrixWorldInverse=new Matrix4$1();this.projectionMatrix=new Matrix4$1();this.projectionMatrixInverse=new Matrix4$1();}Camera$1.prototype=Object.assign(Object.create(Object3D$1.prototype),{constructor:Camera$1,isCamera:true,copy:function copy(source,recursive){Object3D$1.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 getWorldDirection(target){if(target===undefined){console.warn('THREE.Camera: .getWorldDirection() target is now required');target=new Vector3$1();}this.updateMatrixWorld(true);var e=this.matrixWorld.elements;return target.set(-e[8],-e[9],-e[10]).normalize();},updateMatrixWorld:function updateMatrixWorld(force){Object3D$1.prototype.updateMatrixWorld.call(this,force);this.matrixWorldInverse.getInverse(this.matrixWorld);},updateWorldMatrix:function updateWorldMatrix(updateParents,updateChildren){Object3D$1.prototype.updateWorldMatrix.call(this,updateParents,updateChildren);this.matrixWorldInverse.getInverse(this.matrixWorld);},clone:function clone(){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$1(fov,aspect,near,far){Camera$1.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$1.prototype=Object.assign(Object.create(Camera$1.prototype),{constructor:PerspectiveCamera$1,isPerspectiveCamera:true,copy:function copy(source,recursive){Camera$1.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 setFocalLength(focalLength){// see http://www.bobatkins.com/photography/technical/field_of_view.html var vExtentSlope=0.5*this.getFilmHeight()/focalLength;this.fov=MathUtils$1.RAD2DEG*2*Math.atan(vExtentSlope);this.updateProjectionMatrix();},/** * Calculates the focal length from the current .fov and .filmGauge. */getFocalLength:function getFocalLength(){var vExtentSlope=Math.tan(MathUtils$1.DEG2RAD*0.5*this.fov);return 0.5*this.getFilmHeight()/vExtentSlope;},getEffectiveFOV:function getEffectiveFOV(){return MathUtils$1.RAD2DEG*2*Math.atan(Math.tan(MathUtils$1.DEG2RAD*0.5*this.fov)/this.zoom);},getFilmWidth:function getFilmWidth(){// film not completely covered in portrait format (aspect < 1) return this.filmGauge*Math.min(this.aspect,1);},getFilmHeight:function getFilmHeight(){// 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 * * var w = 1920; * var h = 1080; * var fullWidth = w * 3; * var 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 setViewOffset(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 clearViewOffset(){if(this.view!==null){this.view.enabled=false;}this.updateProjectionMatrix();},updateProjectionMatrix:function updateProjectionMatrix(){var near=this.near,top=near*Math.tan(MathUtils$1.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){var fullWidth=view.fullWidth,fullHeight=view.fullHeight;left+=view.offsetX*width/fullWidth;top-=view.offsetY*height/fullHeight;width*=view.width/fullWidth;height*=view.height/fullHeight;}var 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 toJSON(meta){var data=Object3D$1.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/ */var fov$1=90,aspect$1=1;function CubeCamera$1(near,far,renderTarget){Object3D$1.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;var cameraPX=new PerspectiveCamera$1(fov$1,aspect$1,near,far);cameraPX.layers=this.layers;cameraPX.up.set(0,-1,0);cameraPX.lookAt(new Vector3$1(1,0,0));this.add(cameraPX);var cameraNX=new PerspectiveCamera$1(fov$1,aspect$1,near,far);cameraNX.layers=this.layers;cameraNX.up.set(0,-1,0);cameraNX.lookAt(new Vector3$1(-1,0,0));this.add(cameraNX);var cameraPY=new PerspectiveCamera$1(fov$1,aspect$1,near,far);cameraPY.layers=this.layers;cameraPY.up.set(0,0,1);cameraPY.lookAt(new Vector3$1(0,1,0));this.add(cameraPY);var cameraNY=new PerspectiveCamera$1(fov$1,aspect$1,near,far);cameraNY.layers=this.layers;cameraNY.up.set(0,0,-1);cameraNY.lookAt(new Vector3$1(0,-1,0));this.add(cameraNY);var cameraPZ=new PerspectiveCamera$1(fov$1,aspect$1,near,far);cameraPZ.layers=this.layers;cameraPZ.up.set(0,-1,0);cameraPZ.lookAt(new Vector3$1(0,0,1));this.add(cameraPZ);var cameraNZ=new PerspectiveCamera$1(fov$1,aspect$1,near,far);cameraNZ.layers=this.layers;cameraNZ.up.set(0,-1,0);cameraNZ.lookAt(new Vector3$1(0,0,-1));this.add(cameraNZ);this.update=function(renderer,scene){if(this.parent===null)this.updateMatrixWorld();var currentXrEnabled=renderer.xr.enabled;var currentRenderTarget=renderer.getRenderTarget();renderer.xr.enabled=false;var 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){var currentRenderTarget=renderer.getRenderTarget();for(var i=0;i<6;i++){renderer.setRenderTarget(renderTarget,i);renderer.clear(color,depth,stencil);}renderer.setRenderTarget(currentRenderTarget);};}CubeCamera$1.prototype=Object.create(Object3D$1.prototype);CubeCamera$1.prototype.constructor=CubeCamera$1;/** * @author alteredq / http://alteredqualia.com * @author WestLangley / http://github.com/WestLangley */function WebGLCubeRenderTarget$1(size,options,dummy){if(Number.isInteger(options)){console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');options=dummy;}WebGLRenderTarget$1.call(this,size,size,options);}WebGLCubeRenderTarget$1.prototype=Object.create(WebGLRenderTarget$1.prototype);WebGLCubeRenderTarget$1.prototype.constructor=WebGLCubeRenderTarget$1;WebGLCubeRenderTarget$1.prototype.isWebGLCubeRenderTarget=true;WebGLCubeRenderTarget$1.prototype.fromEquirectangularTexture=function(renderer,texture){this.texture.type=texture.type;this.texture.format=texture.format;this.texture.encoding=texture.encoding;var scene=new Scene$1();var 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 "," #include ","}"].join('\n'),fragmentShader:["uniform sampler2D tEquirect;","varying vec3 vWorldDirection;","#include ","void main() {"," vec3 direction = normalize( vWorldDirection );"," vec2 sampleUV = equirectUv( direction );"," gl_FragColor = texture2D( tEquirect, sampleUV );","}"].join('\n')};var material=new ShaderMaterial$1({type:'CubemapFromEquirect',uniforms:cloneUniforms$1(shader.uniforms),vertexShader:shader.vertexShader,fragmentShader:shader.fragmentShader,side:BackSide$1,blending:NoBlending$1});material.uniforms.tEquirect.value=texture;var mesh=new Mesh$1(new BoxBufferGeometry$1(5,5,5),material);scene.add(mesh);var camera=new CubeCamera$1(1,10,this);camera.update(renderer,scene);mesh.geometry.dispose();mesh.material.dispose();return this;};/** * @author alteredq / http://alteredqualia.com/ */function DataTexture$1(data,width,height,format,type,mapping,wrapS,wrapT,magFilter,minFilter,anisotropy,encoding){Texture$1.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$1;this.minFilter=minFilter!==undefined?minFilter:NearestFilter$1;this.generateMipmaps=false;this.flipY=false;this.unpackAlignment=1;this.needsUpdate=true;}DataTexture$1.prototype=Object.create(Texture$1.prototype);DataTexture$1.prototype.constructor=DataTexture$1;DataTexture$1.prototype.isDataTexture=true;/** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * @author bhouston / http://clara.io */var _sphere$1$1=new Sphere$1();var _vector$5$1=new Vector3$1();function Frustum$1(p0,p1,p2,p3,p4,p5){this.planes=[p0!==undefined?p0:new Plane$1(),p1!==undefined?p1:new Plane$1(),p2!==undefined?p2:new Plane$1(),p3!==undefined?p3:new Plane$1(),p4!==undefined?p4:new Plane$1(),p5!==undefined?p5:new Plane$1()];}Object.assign(Frustum$1.prototype,{set:function set(p0,p1,p2,p3,p4,p5){var 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 clone(){return new this.constructor().copy(this);},copy:function copy(frustum){var planes=this.planes;for(var i=0;i<6;i++){planes[i].copy(frustum.planes[i]);}return this;},setFromProjectionMatrix:function setFromProjectionMatrix(m){var planes=this.planes;var me=m.elements;var me0=me[0],me1=me[1],me2=me[2],me3=me[3];var me4=me[4],me5=me[5],me6=me[6],me7=me[7];var me8=me[8],me9=me[9],me10=me[10],me11=me[11];var 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 intersectsObject(object){var geometry=object.geometry;if(geometry.boundingSphere===null)geometry.computeBoundingSphere();_sphere$1$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);return this.intersectsSphere(_sphere$1$1);},intersectsSprite:function intersectsSprite(sprite){_sphere$1$1.center.set(0,0,0);_sphere$1$1.radius=0.7071067811865476;_sphere$1$1.applyMatrix4(sprite.matrixWorld);return this.intersectsSphere(_sphere$1$1);},intersectsSphere:function intersectsSphere(sphere){var planes=this.planes;var center=sphere.center;var negRadius=-sphere.radius;for(var i=0;i<6;i++){var distance=planes[i].distanceToPoint(center);if(distance0?box.max.x:box.min.x;_vector$5$1.y=plane.normal.y>0?box.max.y:box.min.y;_vector$5$1.z=plane.normal.z>0?box.max.z:box.min.z;if(plane.distanceToPoint(_vector$5$1)<0){return false;}}return true;},containsPoint:function containsPoint(point){var planes=this.planes;for(var i=0;i<6;i++){if(planes[i].distanceToPoint(point)<0){return false;}}return true;}});/** * Uniforms library for shared webgl shaders */var UniformsLib$1={common:{diffuse:{value:new Color$1(0xeeeeee)},opacity:{value:1.0},map:{value:null},uvTransform:{value:new Matrix3$1()},uv2Transform:{value:new Matrix3$1()},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,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$1(0xffffff)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowRadius:{},shadowMapSize:{}}},spotShadowMap:{value:[]},spotShadowMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowBias:{},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$1(0xeeeeee)},opacity:{value:1.0},size:{value:1.0},scale:{value:1.0},map:{value:null},alphaMap:{value:null},uvTransform:{value:new Matrix3$1()}},sprite:{diffuse:{value:new Color$1(0xeeeeee)},opacity:{value:1.0},center:{value:new Vector2$1(0.5,0.5)},rotation:{value:0.0},map:{value:null},alphaMap:{value:null},uvTransform:{value:new Matrix3$1()}}};/** * @author mrdoob / http://mrdoob.com/ */function WebGLAnimation$1(){var context=null;var isAnimating=false;var animationLoop=null;function onAnimationFrame(time,frame){if(isAnimating===false)return;animationLoop(time,frame);context.requestAnimationFrame(onAnimationFrame);}return{start:function start(){if(isAnimating===true)return;if(animationLoop===null)return;context.requestAnimationFrame(onAnimationFrame);isAnimating=true;},stop:function stop(){isAnimating=false;},setAnimationLoop:function setAnimationLoop(callback){animationLoop=callback;},setContext:function setContext(value){context=value;}};}/** * @author mrdoob / http://mrdoob.com/ */function WebGLAttributes$1(gl,capabilities){var isWebGL2=capabilities.isWebGL2;var buffers=new WeakMap();function createBuffer(attribute,bufferType){var array=attribute.array;var usage=attribute.usage;var buffer=gl.createBuffer();gl.bindBuffer(bufferType,buffer);gl.bufferData(bufferType,array,usage);attribute.onUploadCallback();var type=5126;if(_instanceof(array,Float32Array)){type=5126;}else if(_instanceof(array,Float64Array)){console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');}else if(_instanceof(array,Uint16Array)){type=5123;}else if(_instanceof(array,Int16Array)){type=5122;}else if(_instanceof(array,Uint32Array)){type=5125;}else if(_instanceof(array,Int32Array)){type=5124;}else if(_instanceof(array,Int8Array)){type=5120;}else if(_instanceof(array,Uint8Array)){type=5121;}return{buffer:buffer,type:type,bytesPerElement:array.BYTES_PER_ELEMENT,version:attribute.version};}function updateBuffer(buffer,attribute,bufferType){var array=attribute.array;var 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;var data=buffers.get(attribute);if(data){gl.deleteBuffer(data.buffer);buffers.delete(attribute);}}function update(attribute,bufferType){if(attribute.isInterleavedBufferAttribute)attribute=attribute.data;var data=buffers.get(attribute);if(data===undefined){buffers.set(attribute,createBuffer(attribute,bufferType));}else if(data.version0&&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 */var isWebGL2=typeof WebGL2RenderingContext!=='undefined'&&_instanceof(gl,WebGL2RenderingContext)||typeof WebGL2ComputeRenderingContext!=='undefined'&&_instanceof(gl,WebGL2ComputeRenderingContext);/* eslint-enable no-undef */var precision=parameters.precision!==undefined?parameters.precision:'highp';var maxPrecision=getMaxPrecision(precision);if(maxPrecision!==precision){console.warn('THREE.WebGLRenderer:',precision,'not supported, using',maxPrecision,'instead.');precision=maxPrecision;}var logarithmicDepthBuffer=parameters.logarithmicDepthBuffer===true;var maxTextures=gl.getParameter(34930);var maxVertexTextures=gl.getParameter(35660);var maxTextureSize=gl.getParameter(3379);var maxCubemapSize=gl.getParameter(34076);var maxAttributes=gl.getParameter(34921);var maxVertexUniforms=gl.getParameter(36347);var maxVaryings=gl.getParameter(36348);var maxFragmentUniforms=gl.getParameter(36349);var vertexTextures=maxVertexTextures>0;var floatFragmentTextures=isWebGL2||!!extensions.get('OES_texture_float');var floatVertexTextures=vertexTextures&&floatFragmentTextures;var 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$1(){var scope=this,globalState=null,numGlobalPlanes=0,localClippingEnabled=false,renderingShadows=false,plane=new Plane$1(),viewNormalMatrix=new Matrix3$1(),uniform={value:null,needsUpdate:false};this.uniform=uniform;this.numPlanes=0;this.numIntersection=0;this.init=function(planes,enableLocalClipping,camera){var 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{var nGlobal=renderingShadows?0:numGlobalPlanes,lGlobal=nGlobal*4,dstArray=cache.clippingState||null;uniform.value=dstArray;// ensure unique state dstArray=projectPlanes(planes,camera,lGlobal,fromCache);for(var 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){var nPlanes=planes!==null?planes.length:0,dstArray=null;if(nPlanes!==0){dstArray=uniform.value;if(skipTransform!==true||dstArray===null){var flatSize=dstOffset+nPlanes*4,viewMatrix=camera.matrixWorldInverse;viewNormalMatrix.getNormalMatrix(viewMatrix);if(dstArray===null||dstArray.length65535?Uint32BufferAttribute$1:Uint16BufferAttribute$1)(indices,1);attribute.version=version;attributes.update(attribute,34963);// var previousAttribute=wireframeAttributes.get(geometry);if(previousAttribute)attributes.remove(previousAttribute);// wireframeAttributes.set(geometry,attribute);}function getWireframeAttribute(geometry){var currentAttribute=wireframeAttributes.get(geometry);if(currentAttribute){var geometryIndex=geometry.index;if(geometryIndex!==null){// if the attribute is obsolete, create a new one if(currentAttribute.version0)return array;// unoptimized: ! isNaN( firstElem ) // see http://jacksondunstan.com/articles/983 var n=nBlocks*blockSize,r=arrayCacheF32$1[n];if(r===undefined){r=new Float32Array(n);arrayCacheF32$1[n]=r;}if(nBlocks!==0){firstElem.toArray(r,0);for(var i=1,offset=0;i!==nBlocks;++i){offset+=blockSize;array[i].toArray(r,offset);}}return r;}function arraysEqual$1(a,b){if(a.length!==b.length)return false;for(var i=0,l=a.length;i/gm;function resolveIncludes$1(string){return string.replace(includePattern$1,includeReplacer$1);}function includeReplacer$1(match,include){var string=ShaderChunk$1[include];if(string===undefined){throw new Error('Can not resolve #include <'+include+'>');}return resolveIncludes$1(string);}// Unroll Loops var deprecatedUnrollLoopPattern$1=/#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;var unrollLoopPattern$1=/#pragma unroll_loop_start[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}[\s]+?#pragma unroll_loop_end/g;function unrollLoops$1(string){return string.replace(unrollLoopPattern$1,loopReplacer$1).replace(deprecatedUnrollLoopPattern$1,deprecatedLoopReplacer$1);}function deprecatedLoopReplacer$1(match,start,end,snippet){console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');return loopReplacer$1(match,start,end,snippet);}function loopReplacer$1(match,start,end,snippet){var string='';for(var i=parseInt(start);i0?renderer.gammaFactor:1.0;var customExtensions=parameters.isWebGL2?'':generateExtensions$1(parameters);var customDefines=generateDefines$1(defines);var program=gl.createProgram();var prefixVertex,prefixFragment;if(parameters.isRawShaderMaterial){prefixVertex=[customDefines].filter(filterEmptyLine$1).join('\n');if(prefixVertex.length>0){prefixVertex+='\n';}prefixFragment=[customExtensions,customDefines].filter(filterEmptyLine$1).join('\n');if(prefixFragment.length>0){prefixFragment+='\n';}}else{prefixVertex=[generatePrecision$1(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&¶meters.fog?'#define USE_FOG':'',parameters.useFog&¶meters.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&¶meters.objectSpaceNormalMap?'#define OBJECTSPACE_NORMALMAP':'',parameters.normalMap&¶meters.tangentSpaceNormalMap?'#define TANGENTSPACE_NORMALMAP':'',parameters.clearcoatMap?'#define USE_CLEARCOATMAP':'',parameters.clearcoatRoughnessMap?'#define USE_CLEARCOAT_ROUGHNESSMAP':'',parameters.clearcoatNormalMap?'#define USE_CLEARCOAT_NORMALMAP':'',parameters.displacementMap&¶meters.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&¶meters.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&¶meters.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$1).join('\n');prefixFragment=[customExtensions,generatePrecision$1(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&¶meters.fog?'#define USE_FOG':'',parameters.useFog&¶meters.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&¶meters.objectSpaceNormalMap?'#define OBJECTSPACE_NORMALMAP':'',parameters.normalMap&¶meters.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&¶meters.rendererExtensionFragDepth?'#define USE_LOGDEPTHBUF_EXT':'',(parameters.extensionShaderTextureLOD||parameters.envMap)&¶meters.rendererExtensionShaderTextureLod?'#define TEXTURE_LOD_EXT':'','uniform mat4 viewMatrix;','uniform vec3 cameraPosition;','uniform bool isOrthographic;',parameters.toneMapping!==NoToneMapping$1?'#define TONE_MAPPING':'',parameters.toneMapping!==NoToneMapping$1?ShaderChunk$1['tonemapping_pars_fragment']:'',// this code is required here because it is used by the toneMapping() function defined below parameters.toneMapping!==NoToneMapping$1?getToneMappingFunction$1('toneMapping',parameters.toneMapping):'',parameters.dithering?'#define DITHERING':'',parameters.outputEncoding||parameters.mapEncoding||parameters.matcapEncoding||parameters.envMapEncoding||parameters.emissiveMapEncoding||parameters.lightMapEncoding?ShaderChunk$1['encodings_pars_fragment']:'',// this code is required here because it is used by the various encoding/decoding function defined below parameters.mapEncoding?getTexelDecodingFunction$1('mapTexelToLinear',parameters.mapEncoding):'',parameters.matcapEncoding?getTexelDecodingFunction$1('matcapTexelToLinear',parameters.matcapEncoding):'',parameters.envMapEncoding?getTexelDecodingFunction$1('envMapTexelToLinear',parameters.envMapEncoding):'',parameters.emissiveMapEncoding?getTexelDecodingFunction$1('emissiveMapTexelToLinear',parameters.emissiveMapEncoding):'',parameters.lightMapEncoding?getTexelDecodingFunction$1('lightMapTexelToLinear',parameters.lightMapEncoding):'',parameters.outputEncoding?getTexelEncodingFunction$1('linearToOutputTexel',parameters.outputEncoding):'',parameters.depthPacking?'#define DEPTH_PACKING '+parameters.depthPacking:'','\n'].filter(filterEmptyLine$1).join('\n');}vertexShader=resolveIncludes$1(vertexShader);vertexShader=replaceLightNums$1(vertexShader,parameters);vertexShader=replaceClippingPlaneNums$1(vertexShader,parameters);fragmentShader=resolveIncludes$1(fragmentShader);fragmentShader=replaceLightNums$1(fragmentShader,parameters);fragmentShader=replaceClippingPlaneNums$1(fragmentShader,parameters);vertexShader=unrollLoops$1(vertexShader);fragmentShader=unrollLoops$1(fragmentShader);if(parameters.isWebGL2&&!parameters.isRawShaderMaterial){var isGLSL3ShaderMaterial=false;var 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;}var vertexGlsl=prefixVertex+vertexShader;var fragmentGlsl=prefixFragment+fragmentShader;// console.log( '*VERTEX*', vertexGlsl ); // console.log( '*FRAGMENT*', fragmentGlsl ); var glVertexShader=WebGLShader$1(gl,35633,vertexGlsl);var glFragmentShader=WebGLShader$1(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){var programLog=gl.getProgramInfoLog(program).trim();var vertexLog=gl.getShaderInfoLog(glVertexShader).trim();var fragmentLog=gl.getShaderInfoLog(glFragmentShader).trim();var runnable=true;var haveDiagnostics=true;if(gl.getProgramParameter(program,35714)===false){runnable=false;var vertexErrors=getShaderErrors$1(gl,glVertexShader,'vertex');var fragmentErrors=getShaderErrors$1(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 var cachedUniforms;this.getUniforms=function(){if(cachedUniforms===undefined){cachedUniforms=new WebGLUniforms$1(gl,program);}return cachedUniforms;};// set up caching for attribute locations var cachedAttributes;this.getAttributes=function(){if(cachedAttributes===undefined){cachedAttributes=fetchAttributeLocations$1(gl,program);}return cachedAttributes;};// free resource this.destroy=function(){gl.deleteProgram(program);this.program=undefined;};// this.name=parameters.shaderName;this.id=programIdCount$1++;this.cacheKey=cacheKey;this.usedTimes=1;this.program=program;this.vertexShader=glVertexShader;this.fragmentShader=glFragmentShader;return this;}/** * @author mrdoob / http://mrdoob.com/ */function WebGLPrograms$1(renderer,extensions,capabilities){var programs=[];var isWebGL2=capabilities.isWebGL2;var logarithmicDepthBuffer=capabilities.logarithmicDepthBuffer;var floatVertexTextures=capabilities.floatVertexTextures;var precision=capabilities.precision;var maxVertexUniforms=capabilities.maxVertexUniforms;var vertexTextures=capabilities.vertexTextures;var 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'};var 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){var shaderobject;if(shaderID){var shader=ShaderLib$1[shaderID];shaderobject={name:material.type,uniforms:UniformsUtils$1.clone(shader.uniforms),vertexShader:shader.vertexShader,fragmentShader:shader.fragmentShader};}else{shaderobject={name:material.type,uniforms:material.uniforms,vertexShader:material.vertexShader,fragmentShader:material.fragmentShader};}return shaderobject;}function allocateBones(object){var skeleton=object.skeleton;var 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) var nVertexUniforms=maxVertexUniforms;var nVertexMatrices=Math.floor((nVertexUniforms-20)/4);var maxBones=Math.min(nVertexMatrices,bones.length);if(maxBones0,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$1,physicallyCorrectLights:renderer.physicallyCorrectLights,premultipliedAlpha:material.premultipliedAlpha,alphaTest:material.alphaTest,doubleSided:material.side===DoubleSide$1,flipSided:material.side===BackSide$1,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,onBeforeCompile:material.onBeforeCompile};return parameters;};this.getProgramCacheKey=function(parameters){var array=[];if(parameters.shaderID){array.push(parameters.shaderID);}else{array.push(parameters.fragmentShader);array.push(parameters.vertexShader);}if(parameters.defines!==undefined){for(var name in parameters.defines){array.push(name);array.push(parameters.defines[name]);}}if(parameters.isRawShaderMaterial===undefined){for(var i=0;i1)opaque.sort(customOpaqueSort||painterSortStable$1);if(transparent.length>1)transparent.sort(customTransparentSort||reversePainterSortStable$1);}function finish(){// Clear references from inactive renderItems in the list for(var i=renderItemsIndex,il=renderItems.length;i, * * map: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * wireframe: , * wireframeLinewidth: * } */function MeshDepthMaterial$1(parameters){Material$1.call(this);this.type='MeshDepthMaterial';this.depthPacking=BasicDepthPacking$1;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$1.prototype=Object.create(Material$1.prototype);MeshDepthMaterial$1.prototype.constructor=MeshDepthMaterial$1;MeshDepthMaterial$1.prototype.isMeshDepthMaterial=true;MeshDepthMaterial$1.prototype.copy=function(source){Material$1.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: , * nearDistance: , * farDistance: , * * skinning: , * morphTargets: , * * map: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: * * } */function MeshDistanceMaterial$1(parameters){Material$1.call(this);this.type='MeshDistanceMaterial';this.referencePosition=new Vector3$1();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$1.prototype=Object.create(Material$1.prototype);MeshDistanceMaterial$1.prototype.constructor=MeshDistanceMaterial$1;MeshDistanceMaterial$1.prototype.isMeshDistanceMaterial=true;MeshDistanceMaterial$1.prototype.copy=function(source){Material$1.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$1="uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \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$1="void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";/** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */function WebGLShadowMap$1(_renderer,_objects,maxTextureSize){var _frustum=new Frustum$1(),_shadowMapSize=new Vector2$1(),_viewportSize=new Vector2$1(),_viewport=new Vector4$1(),_depthMaterials=[],_distanceMaterials=[],_materialCache={};var shadowSide={0:BackSide$1,1:FrontSide$1,2:DoubleSide$1};var shadowMaterialVertical=new ShaderMaterial$1({defines:{SAMPLE_RATE:2.0/8.0,HALF_SAMPLE_RATE:1.0/8.0},uniforms:{shadow_pass:{value:null},resolution:{value:new Vector2$1()},radius:{value:4.0}},vertexShader:vsm_vert$1,fragmentShader:vsm_frag$1});var shadowMaterialHorizonal=shadowMaterialVertical.clone();shadowMaterialHorizonal.defines.HORIZONAL_PASS=1;var fullScreenTri=new BufferGeometry$1();fullScreenTri.setAttribute("position",new BufferAttribute$1(new Float32Array([-1,-1,0.5,3,-1,0.5,-1,3,0.5]),3));var fullScreenMesh=new Mesh$1(fullScreenTri,shadowMaterialVertical);var scope=this;this.enabled=false;this.autoUpdate=true;this.needsUpdate=false;this.type=PCFShadowMap$1;this.render=function(lights,scene,camera){if(scope.enabled===false)return;if(scope.autoUpdate===false&&scope.needsUpdate===false)return;if(lights.length===0)return;var currentRenderTarget=_renderer.getRenderTarget();var activeCubeFace=_renderer.getActiveCubeFace();var activeMipmapLevel=_renderer.getActiveMipmapLevel();var _state=_renderer.state;// Set GL state for depth map. _state.setBlending(NoBlending$1);_state.buffers.color.setClear(1,1,1,1);_state.buffers.depth.setTest(true);_state.setScissorTest(false);// render depth map for(var i=0,il=lights.length;imaxTextureSize||_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$1){var pars={minFilter:LinearFilter$1,magFilter:LinearFilter$1,format:RGBAFormat$1};shadow.map=new WebGLRenderTarget$1(_shadowMapSize.x,_shadowMapSize.y,pars);shadow.map.texture.name=light.name+".shadowMap";shadow.mapPass=new WebGLRenderTarget$1(_shadowMapSize.x,_shadowMapSize.y,pars);shadow.camera.updateProjectionMatrix();}if(shadow.map===null){var pars={minFilter:NearestFilter$1,magFilter:NearestFilter$1,format:RGBAFormat$1};shadow.map=new WebGLRenderTarget$1(_shadowMapSize.x,_shadowMapSize.y,pars);shadow.map.texture.name=light.name+".shadowMap";shadow.camera.updateProjectionMatrix();}_renderer.setRenderTarget(shadow.map);_renderer.clear();var viewportCount=shadow.getViewportCount();for(var vp=0;vp0;}var 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);}}var 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 var keyA=result.uuid,keyB=material.uuid;var materialsForVariant=_materialCache[keyA];if(materialsForVariant===undefined){materialsForVariant={};_materialCache[keyA]=materialsForVariant;}var 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$1){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;var visible=object.layers.test(camera.layers);if(visible&&(object.isMesh||object.isLine||object.isPoints)){if((object.castShadow||object.receiveShadow&&type===VSMShadowMap$1)&&(!object.frustumCulled||_frustum.intersectsObject(object))){object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse,object.matrixWorld);var geometry=_objects.update(object);var material=object.material;if(Array.isArray(material)){var groups=geometry.groups;for(var k=0,kl=groups.length;k=1.0;}else if(glVersion.indexOf('OpenGL ES')!==-1){version=parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion)[1]);lineWidthAvailable=version>=2.0;}var currentTextureSlot=null;var currentBoundTextures={};var currentScissor=new Vector4$1();var currentViewport=new Vector4$1();function createTexture(type,target,count){var data=new Uint8Array(4);// 4 is required to match default unpack alignment of 4. var texture=gl.createTexture();gl.bindTexture(type,texture);gl.texParameteri(type,10241,9728);gl.texParameteri(type,10240,9728);for(var i=0;imaxSize||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'&&_instanceof(image,HTMLImageElement)||typeof HTMLCanvasElement!=='undefined'&&_instanceof(image,HTMLCanvasElement)||typeof ImageBitmap!=='undefined'&&_instanceof(image,ImageBitmap)){var floor=needsPowerOfTwo?MathUtils$1.floorPowerOfTwo:Math.floor;var width=floor(scale*image.width);var height=floor(scale*image.height);if(_canvas===undefined)_canvas=createCanvas(width,height);// cube textures can't reuse the same canvas var canvas=needsNewCanvas?createCanvas(width,height):_canvas;canvas.width=width;canvas.height=height;var 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$1.isPowerOfTwo(image.width)&&MathUtils$1.isPowerOfTwo(image.height);}function textureNeedsPowerOfTwo(texture){if(isWebGL2)return false;return texture.wrapS!==ClampToEdgeWrapping$1||texture.wrapT!==ClampToEdgeWrapping$1||texture.minFilter!==NearestFilter$1&&texture.minFilter!==LinearFilter$1;}function textureNeedsGenerateMipmaps(texture,supportsMips){return texture.generateMipmaps&&supportsMips&&texture.minFilter!==NearestFilter$1&&texture.minFilter!==LinearFilter$1;}function generateMipmap(target,texture,width,height){_gl.generateMipmap(target);var 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+'\'');}var 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$1||f===NearestMipmapNearestFilter$1||f===NearestMipmapLinearFilter$1){return 9728;}return 9729;}// function onTextureDispose(event){var texture=event.target;texture.removeEventListener('dispose',onTextureDispose);deallocateTexture(texture);if(texture.isVideoTexture){_videoTextures.delete(texture);}info.memory.textures--;}function onRenderTargetDispose(event){var renderTarget=event.target;renderTarget.removeEventListener('dispose',onRenderTargetDispose);deallocateRenderTarget(renderTarget);info.memory.textures--;}// function deallocateTexture(texture){var textureProperties=properties.get(texture);if(textureProperties.__webglInit===undefined)return;_gl.deleteTexture(textureProperties.__webglTexture);properties.remove(texture);}function deallocateRenderTarget(renderTarget){var renderTargetProperties=properties.get(renderTarget);var 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(var 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);}// var textureUnits=0;function resetTextureUnits(){textureUnits=0;}function allocateTextureUnit(){var 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){var textureProperties=properties.get(texture);if(texture.isVideoTexture)updateVideoTexture(texture);if(texture.version>0&&textureProperties.__version!==texture.version){var 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){var 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){var 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;var 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);var isCompressed=texture&&(texture.isCompressedTexture||texture.image[0].isCompressedTexture);var isDataTexture=texture.image[0]&&texture.image[0].isDataTexture;var cubeImage=[];for(var 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];}}var 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);var mipmaps;if(isCompressed){for(var i=0;i<6;i++){mipmaps=cubeImage[i].mipmaps;for(var j=0;j1||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){var 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);var needsPowerOfTwo=textureNeedsPowerOfTwo(texture)&&isPowerOfTwo(texture.image)===false;var image=resizeImage(texture.image,needsPowerOfTwo,false,maxTextureSize);var supportsMips=isPowerOfTwo(image)||isWebGL2,glFormat=utils.convert(texture.format),glType=utils.convert(texture.type),glInternalFormat=getInternalFormat(texture.internalFormat,glFormat,glType);setTextureParameters(textureType,texture,supportsMips);var mipmap,mipmaps=texture.mipmaps;if(texture.isDepthTexture){// populate depth texture with dummy data glInternalFormat=6402;if(isWebGL2){if(texture.type===FloatType$1){glInternalFormat=36012;}else if(texture.type===UnsignedIntType$1){glInternalFormat=33190;}else if(texture.type===UnsignedInt248Type$1){glInternalFormat=35056;}else{glInternalFormat=33189;// WebGL2 requires sized internalformat for glTexImage2D }}else{if(texture.type===FloatType$1){console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');}}// validation checks for WebGL 1 if(texture.format===DepthFormat$1&&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$1&&texture.type!==UnsignedIntType$1){console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');texture.type=UnsignedShortType$1;glType=utils.convert(texture.type);}}if(texture.format===DepthStencilFormat$1&&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$1){console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');texture.type=UnsignedInt248Type$1;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(var i=0,il=mipmaps.length;i0&&supportsMips){for(var i=0,il=mipmaps.length;i=0){var geometryAttribute=geometryAttributes[name];if(geometryAttribute!==undefined){var normalized=geometryAttribute.normalized;var size=geometryAttribute.itemSize;var attribute=attributes.get(geometryAttribute);// TODO Attribute may not be available on context restore if(attribute===undefined)continue;var buffer=attribute.buffer;var type=attribute.type;var bytesPerElement=attribute.bytesPerElement;if(geometryAttribute.isInterleavedBufferAttribute){var data=geometryAttribute.data;var stride=data.stride;var offset=geometryAttribute.offset;if(data&&data.isInstancedInterleavedBuffer){state.enableAttributeAndDivisor(programAttribute,data.meshPerAttribute);if(geometry._maxInstanceCount===undefined){geometry._maxInstanceCount=data.meshPerAttribute*data.count;}}else{state.enableAttribute(programAttribute);}_gl.bindBuffer(34962,buffer);state.vertexAttribPointer(programAttribute,size,type,normalized,stride*bytesPerElement,offset*bytesPerElement);}else{if(geometryAttribute.isInstancedBufferAttribute){state.enableAttributeAndDivisor(programAttribute,geometryAttribute.meshPerAttribute);if(geometry._maxInstanceCount===undefined){geometry._maxInstanceCount=geometryAttribute.meshPerAttribute*geometryAttribute.count;}}else{state.enableAttribute(programAttribute);}_gl.bindBuffer(34962,buffer);state.vertexAttribPointer(programAttribute,size,type,normalized,0,0);}}else if(name==='instanceMatrix'){var attribute=attributes.get(object.instanceMatrix);// TODO Attribute may not be available on context restore if(attribute===undefined)continue;var buffer=attribute.buffer;var type=attribute.type;state.enableAttributeAndDivisor(programAttribute+0,1);state.enableAttributeAndDivisor(programAttribute+1,1);state.enableAttributeAndDivisor(programAttribute+2,1);state.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){var 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);}}}}}state.disableUnusedAttributes();}// 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);var compiled={};scene.traverse(function(object){var material=object.material;if(material){if(Array.isArray(material)){for(var _i22=0;_i22=0){material.numSupportedMorphTargets++;}}}if(material.morphNormals){material.numSupportedMorphNormals=0;for(var i=0;i<_this.maxMorphNormals;i++){if(programAttributes['morphNormal'+i]>=0){material.numSupportedMorphNormals++;}}}var 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 }var progUniforms=materialProperties.program.getUniforms(),uniformsList=WebGLUniforms$1.seqWithValue(progUniforms.seq,uniforms);materialProperties.uniformsList=uniformsList;}function setProgram(camera,scene,material,object){textures.resetTextureUnits();var fog=scene.fog;var environment=material.isMeshStandardMaterial?scene.environment:null;var encoding=_currentRenderTarget===null?_this.outputEncoding:_currentRenderTarget.texture.encoding;var materialProperties=properties.get(material);var lights=currentRenderState.state.lights;if(_clippingEnabled){if(_localClippingEnabled||camera!==_currentCamera){var 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;}var refreshProgram=false;var refreshMaterial=false;var refreshLights=false;var 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){var 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.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');var skeleton=object.skeleton;if(skeleton){var 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) var size=Math.sqrt(bones.length*4);// 4 pixels needed for 1 matrix size=MathUtils$1.ceilPowerOfTwo(size);size=Math.max(size,4);var boneMatrices=new Float32Array(size*size*4);// 4 floats per RGBA pixel boneMatrices.set(skeleton.boneMatrices);// copy current values var boneTexture=new DataTexture$1(boneMatrices,size,size,RGBAFormat$1,FloatType$1);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);p_uniforms.setValue(_gl,'toneMappingWhitePoint',_this.toneMappingWhitePoint);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$1.LTC_1;if(m_uniforms.ltc_2!==undefined)m_uniforms.ltc_2.value=UniformsLib$1.LTC_2;WebGLUniforms$1.upload(_gl,materialProperties.uniformsList,m_uniforms,textures);}if(material.isShaderMaterial&&material.uniformsNeedUpdate===true){WebGLUniforms$1.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);}var framebuffer=_framebuffer;var isCube=false;if(renderTarget){var __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){var 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;}var framebuffer=properties.get(renderTarget).__webglFramebuffer;if(renderTarget.isWebGLCubeRenderTarget&&activeCubeFaceIndex!==undefined){framebuffer=framebuffer[activeCubeFaceIndex];}if(framebuffer){var restore=false;if(framebuffer!==_currentFramebuffer){_gl.bindFramebuffer(36160,framebuffer);restore=true;}try{var texture=renderTarget.texture;var textureFormat=texture.format;var textureType=texture.type;if(textureFormat!==RGBAFormat$1&&utils.convert(textureFormat)!==_gl.getParameter(35739)){console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');return;}if(textureType!==UnsignedByteType$1&&utils.convert(textureType)!==_gl.getParameter(35738)&&// IE11, Edge and Chrome Mac < 52 (#9513) !(textureType===FloatType$1&&(capabilities.isWebGL2||extensions.get('OES_texture_float')||extensions.get('WEBGL_color_buffer_float')))&&// Chrome Mac >= 52 and Firefox !(textureType===HalfFloatType$1&&(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;var levelScale=Math.pow(2,-level);var width=Math.floor(texture.image.width*levelScale);var height=Math.floor(texture.image.height*levelScale);var 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;var width=srcTexture.image.width;var height=srcTexture.image.height;var glFormat=utils.convert(dstTexture.format);var glType=utils.convert(dstTexture.type);textures.setTexture2D(dstTexture,0);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 mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */function FogExp2$1(color,density){this.name='';this.color=new Color$1(color);this.density=density!==undefined?density:0.00025;}Object.assign(FogExp2$1.prototype,{isFogExp2:true,clone:function clone(){return new FogExp2$1(this.color,this.density);},toJSON:function toJSON()/* meta */{return{type:'FogExp2',color:this.color.getHex(),density:this.density};}});/** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */function Fog$1(color,near,far){this.name='';this.color=new Color$1(color);this.near=near!==undefined?near:1;this.far=far!==undefined?far:1000;}Object.assign(Fog$1.prototype,{isFog:true,clone:function clone(){return new Fog$1(this.color,this.near,this.far);},toJSON:function toJSON()/* meta */{return{type:'Fog',color:this.color.getHex(),near:this.near,far:this.far};}});/** * @author benaadams / https://twitter.com/ben_a_adams */function InterleavedBuffer$1(array,stride){this.array=array;this.stride=stride;this.count=array!==undefined?array.length/stride:0;this.usage=StaticDrawUsage$1;this.updateRange={offset:0,count:-1};this.version=0;}Object.defineProperty(InterleavedBuffer$1.prototype,'needsUpdate',{set:function set(value){if(value===true)this.version++;}});Object.assign(InterleavedBuffer$1.prototype,{isInterleavedBuffer:true,onUploadCallback:function onUploadCallback(){},setUsage:function setUsage(value){this.usage=value;return this;},copy:function copy(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 copyAt(index1,attribute,index2){index1*=this.stride;index2*=attribute.stride;for(var i=0,l=this.stride;i, * map: new THREE.Texture( ), * alphaMap: new THREE.Texture( ), * rotation: , * sizeAttenuation: * } */function SpriteMaterial$1(parameters){Material$1.call(this);this.type='SpriteMaterial';this.color=new Color$1(0xffffff);this.map=null;this.alphaMap=null;this.rotation=0;this.sizeAttenuation=true;this.transparent=true;this.setValues(parameters);}SpriteMaterial$1.prototype=Object.create(Material$1.prototype);SpriteMaterial$1.prototype.constructor=SpriteMaterial$1;SpriteMaterial$1.prototype.isSpriteMaterial=true;SpriteMaterial$1.prototype.copy=function(source){Material$1.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/ */var _geometry$1;var _intersectPoint$1=new Vector3$1();var _worldScale$1=new Vector3$1();var _mvPosition$1=new Vector3$1();var _alignedPosition$1=new Vector2$1();var _rotatedPosition$1=new Vector2$1();var _viewWorldMatrix$1=new Matrix4$1();var _vA$1$1=new Vector3$1();var _vB$1$1=new Vector3$1();var _vC$1$1=new Vector3$1();var _uvA$1$1=new Vector2$1();var _uvB$1$1=new Vector2$1();var _uvC$1$1=new Vector2$1();function Sprite$1(material){Object3D$1.call(this);this.type='Sprite';if(_geometry$1===undefined){_geometry$1=new BufferGeometry$1();var 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]);var interleavedBuffer=new InterleavedBuffer$1(float32Array,5);_geometry$1.setIndex([0,1,2,0,2,3]);_geometry$1.setAttribute('position',new InterleavedBufferAttribute$1(interleavedBuffer,3,0,false));_geometry$1.setAttribute('uv',new InterleavedBufferAttribute$1(interleavedBuffer,2,3,false));}this.geometry=_geometry$1;this.material=material!==undefined?material:new SpriteMaterial$1();this.center=new Vector2$1(0.5,0.5);}Sprite$1.prototype=Object.assign(Object.create(Object3D$1.prototype),{constructor:Sprite$1,isSprite:true,raycast:function raycast(raycaster,intersects){if(raycaster.camera===null){console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');}_worldScale$1.setFromMatrixScale(this.matrixWorld);_viewWorldMatrix$1.copy(raycaster.camera.matrixWorld);this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse,this.matrixWorld);_mvPosition$1.setFromMatrixPosition(this.modelViewMatrix);if(raycaster.camera.isPerspectiveCamera&&this.material.sizeAttenuation===false){_worldScale$1.multiplyScalar(-_mvPosition$1.z);}var rotation=this.material.rotation;var sin,cos;if(rotation!==0){cos=Math.cos(rotation);sin=Math.sin(rotation);}var center=this.center;transformVertex$1(_vA$1$1.set(-0.5,-0.5,0),_mvPosition$1,center,_worldScale$1,sin,cos);transformVertex$1(_vB$1$1.set(0.5,-0.5,0),_mvPosition$1,center,_worldScale$1,sin,cos);transformVertex$1(_vC$1$1.set(0.5,0.5,0),_mvPosition$1,center,_worldScale$1,sin,cos);_uvA$1$1.set(0,0);_uvB$1$1.set(1,0);_uvC$1$1.set(1,1);// check first triangle var intersect=raycaster.ray.intersectTriangle(_vA$1$1,_vB$1$1,_vC$1$1,false,_intersectPoint$1);if(intersect===null){// check second triangle transformVertex$1(_vB$1$1.set(-0.5,0.5,0),_mvPosition$1,center,_worldScale$1,sin,cos);_uvB$1$1.set(0,1);intersect=raycaster.ray.intersectTriangle(_vA$1$1,_vC$1$1,_vB$1$1,false,_intersectPoint$1);if(intersect===null){return;}}var distance=raycaster.ray.origin.distanceTo(_intersectPoint$1);if(distanceraycaster.far)return;intersects.push({distance:distance,point:_intersectPoint$1.clone(),uv:Triangle$1.getUV(_intersectPoint$1,_vA$1$1,_vB$1$1,_vC$1$1,_uvA$1$1,_uvB$1$1,_uvC$1$1,new Vector2$1()),face:null,object:this});},clone:function clone(){return new this.constructor(this.material).copy(this);},copy:function copy(source){Object3D$1.prototype.copy.call(this,source);if(source.center!==undefined)this.center.copy(source.center);return this;}});function transformVertex$1(vertexPosition,mvPosition,center,scale,sin,cos){// compute position in camera space _alignedPosition$1.subVectors(vertexPosition,center).addScalar(0.5).multiply(scale);// to check if rotation is not zero if(sin!==undefined){_rotatedPosition$1.x=cos*_alignedPosition$1.x-sin*_alignedPosition$1.y;_rotatedPosition$1.y=sin*_alignedPosition$1.x+cos*_alignedPosition$1.y;}else{_rotatedPosition$1.copy(_alignedPosition$1);}vertexPosition.copy(mvPosition);vertexPosition.x+=_rotatedPosition$1.x;vertexPosition.y+=_rotatedPosition$1.y;// transform to world space vertexPosition.applyMatrix4(_viewWorldMatrix$1);}/** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */var _v1$4$1=new Vector3$1();var _v2$2$1=new Vector3$1();function LOD$1(){Object3D$1.call(this);this._currentLevel=0;this.type='LOD';Object.defineProperties(this,{levels:{enumerable:true,value:[]}});this.autoUpdate=true;}LOD$1.prototype=Object.assign(Object.create(Object3D$1.prototype),{constructor:LOD$1,isLOD:true,copy:function copy(source){Object3D$1.prototype.copy.call(this,source,false);var levels=source.levels;for(var i=0,l=levels.length;i0){for(var i=1,l=levels.length;i0){_v1$4$1.setFromMatrixPosition(this.matrixWorld);var distance=raycaster.ray.origin.distanceTo(_v1$4$1);this.getObjectForDistance(distance).raycast(raycaster,intersects);}},update:function update(camera){var levels=this.levels;if(levels.length>1){_v1$4$1.setFromMatrixPosition(camera.matrixWorld);_v2$2$1.setFromMatrixPosition(this.matrixWorld);var distance=_v1$4$1.distanceTo(_v2$2$1)/camera.zoom;levels[0].object.visible=true;for(var i=1,l=levels.length;i=levels[i].distance){levels[i-1].object.visible=false;levels[i].object.visible=true;}else{break;}}this._currentLevel=i-1;for(;i, * opacity: , * * linewidth: , * linecap: "round", * linejoin: "round" * } */function LineBasicMaterial$1(parameters){Material$1.call(this);this.type='LineBasicMaterial';this.color=new Color$1(0xffffff);this.linewidth=1;this.linecap='round';this.linejoin='round';this.morphTargets=false;this.setValues(parameters);}LineBasicMaterial$1.prototype=Object.create(Material$1.prototype);LineBasicMaterial$1.prototype.constructor=LineBasicMaterial$1;LineBasicMaterial$1.prototype.isLineBasicMaterial=true;LineBasicMaterial$1.prototype.copy=function(source){Material$1.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/ */var _start$2=new Vector3$1();var _end$2=new Vector3$1();var _inverseMatrix$1$1=new Matrix4$1();var _ray$1$1=new Ray$1();var _sphere$2$1=new Sphere$1();function Line$1(geometry,material,mode){if(mode===1){console.error('THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.');}Object3D$1.call(this);this.type='Line';this.geometry=geometry!==undefined?geometry:new BufferGeometry$1();this.material=material!==undefined?material:new LineBasicMaterial$1();this.updateMorphTargets();}Line$1.prototype=Object.assign(Object.create(Object3D$1.prototype),{constructor:Line$1,isLine:true,computeLineDistances:function computeLineDistances(){var geometry=this.geometry;if(geometry.isBufferGeometry){// we assume non-indexed geometry if(geometry.index===null){var positionAttribute=geometry.attributes.position;var lineDistances=[0];for(var i=1,l=positionAttribute.count;ilocalThresholdSq)continue;interRay.applyMatrix4(this.matrixWorld);//Move back to world space for distance calculation var distance=raycaster.ray.origin.distanceTo(interRay);if(distanceraycaster.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(var i=0,l=positions.length/3-1;ilocalThresholdSq)continue;interRay.applyMatrix4(this.matrixWorld);//Move back to world space for distance calculation var distance=raycaster.ray.origin.distanceTo(interRay);if(distanceraycaster.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){var vertices=geometry.vertices;var nbVertices=vertices.length;for(var i=0;ilocalThresholdSq)continue;interRay.applyMatrix4(this.matrixWorld);//Move back to world space for distance calculation var distance=raycaster.ray.origin.distanceTo(interRay);if(distanceraycaster.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 updateMorphTargets(){var geometry=this.geometry;var m,ml,name;if(geometry.isBufferGeometry){var morphAttributes=geometry.morphAttributes;var keys=Object.keys(morphAttributes);if(keys.length>0){var morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==undefined){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(m=0,ml=morphAttribute.length;m0){console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');}}},clone:function clone(){return new this.constructor(this.geometry,this.material).copy(this);}});/** * @author mrdoob / http://mrdoob.com/ */var _start$1$1=new Vector3$1();var _end$1$1=new Vector3$1();function LineSegments$1(geometry,material){Line$1.call(this,geometry,material);this.type='LineSegments';}LineSegments$1.prototype=Object.assign(Object.create(Line$1.prototype),{constructor:LineSegments$1,isLineSegments:true,computeLineDistances:function computeLineDistances(){var geometry=this.geometry;if(geometry.isBufferGeometry){// we assume non-indexed geometry if(geometry.index===null){var positionAttribute=geometry.attributes.position;var lineDistances=[];for(var i=0,l=positionAttribute.count;i, * opacity: , * map: new THREE.Texture( ), * alphaMap: new THREE.Texture( ), * * size: , * sizeAttenuation: * * morphTargets: * } */function PointsMaterial$1(parameters){Material$1.call(this);this.type='PointsMaterial';this.color=new Color$1(0xffffff);this.map=null;this.alphaMap=null;this.size=1;this.sizeAttenuation=true;this.morphTargets=false;this.setValues(parameters);}PointsMaterial$1.prototype=Object.create(Material$1.prototype);PointsMaterial$1.prototype.constructor=PointsMaterial$1;PointsMaterial$1.prototype.isPointsMaterial=true;PointsMaterial$1.prototype.copy=function(source){Material$1.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/ */var _inverseMatrix$2$1=new Matrix4$1();var _ray$2$1=new Ray$1();var _sphere$3$1=new Sphere$1();var _position$1$1=new Vector3$1();function Points$1(geometry,material){Object3D$1.call(this);this.type='Points';this.geometry=geometry!==undefined?geometry:new BufferGeometry$1();this.material=material!==undefined?material:new PointsMaterial$1();this.updateMorphTargets();}Points$1.prototype=Object.assign(Object.create(Object3D$1.prototype),{constructor:Points$1,isPoints:true,raycast:function raycast(raycaster,intersects){var geometry=this.geometry;var matrixWorld=this.matrixWorld;var threshold=raycaster.params.Points.threshold;// Checking boundingSphere distance to ray if(geometry.boundingSphere===null)geometry.computeBoundingSphere();_sphere$3$1.copy(geometry.boundingSphere);_sphere$3$1.applyMatrix4(matrixWorld);_sphere$3$1.radius+=threshold;if(raycaster.ray.intersectsSphere(_sphere$3$1)===false)return;// _inverseMatrix$2$1.getInverse(matrixWorld);_ray$2$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2$1);var localThreshold=threshold/((this.scale.x+this.scale.y+this.scale.z)/3);var localThresholdSq=localThreshold*localThreshold;if(geometry.isBufferGeometry){var index=geometry.index;var attributes=geometry.attributes;var positions=attributes.position.array;if(index!==null){var indices=index.array;for(var i=0,il=indices.length;i0){var morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==undefined){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(m=0,ml=morphAttribute.length;m0){console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');}}},clone:function clone(){return new this.constructor(this.geometry,this.material).copy(this);}});function testPoint$1(point,index,localThresholdSq,matrixWorld,raycaster,intersects,object){var rayPointDistanceSq=_ray$2$1.distanceSqToPoint(point);if(rayPointDistanceSqraycaster.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$1(video,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy){Texture$1.call(this,video,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy);this.format=format!==undefined?format:RGBFormat$1;this.minFilter=minFilter!==undefined?minFilter:LinearFilter$1;this.magFilter=magFilter!==undefined?magFilter:LinearFilter$1;this.generateMipmaps=false;}VideoTexture$1.prototype=Object.assign(Object.create(Texture$1.prototype),{constructor:VideoTexture$1,isVideoTexture:true,update:function update(){var video=this.image;if(video.readyState>=video.HAVE_CURRENT_DATA){this.needsUpdate=true;}}});/** * @author alteredq / http://alteredqualia.com/ */function CompressedTexture$1(mipmaps,width,height,format,type,mapping,wrapS,wrapT,magFilter,minFilter,anisotropy,encoding){Texture$1.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$1.prototype=Object.create(Texture$1.prototype);CompressedTexture$1.prototype.constructor=CompressedTexture$1;CompressedTexture$1.prototype.isCompressedTexture=true;/** * @author mrdoob / http://mrdoob.com/ */function CanvasTexture$1(canvas,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy){Texture$1.call(this,canvas,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy);this.needsUpdate=true;}CanvasTexture$1.prototype=Object.create(Texture$1.prototype);CanvasTexture$1.prototype.constructor=CanvasTexture$1;CanvasTexture$1.prototype.isCanvasTexture=true;/** * @author Matt DesLauriers / @mattdesl * @author atix / arthursilber.de */function DepthTexture$1(width,height,type,mapping,wrapS,wrapT,magFilter,minFilter,anisotropy,format){format=format!==undefined?format:DepthFormat$1;if(format!==DepthFormat$1&&format!==DepthStencilFormat$1){throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');}if(type===undefined&&format===DepthFormat$1)type=UnsignedShortType$1;if(type===undefined&&format===DepthStencilFormat$1)type=UnsignedInt248Type$1;Texture$1.call(this,null,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy);this.image={width:width,height:height};this.magFilter=magFilter!==undefined?magFilter:NearestFilter$1;this.minFilter=minFilter!==undefined?minFilter:NearestFilter$1;this.flipY=false;this.generateMipmaps=false;}DepthTexture$1.prototype=Object.create(Texture$1.prototype);DepthTexture$1.prototype.constructor=DepthTexture$1;DepthTexture$1.prototype.isDepthTexture=true;/** * @author mrdoob / http://mrdoob.com/ * @author Mugen87 / https://github.com/Mugen87 */function WireframeGeometry$1(geometry){BufferGeometry$1.call(this);this.type='WireframeGeometry';// buffer var vertices=[];// helper variables var i,j,l,o,ol;var edge=[0,0],edges={},e,edge1,edge2;var key,keys=['a','b','c'];var vertex;// different logic for Geometry and BufferGeometry if(geometry&&geometry.isGeometry){// create a data structure that contains all edges without duplicates var faces=geometry.faces;for(i=0,l=faces.length;i=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(i=0;i0.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){var stride=index*3;vertex.x=vertices[stride+0];vertex.y=vertices[stride+1];vertex.z=vertices[stride+2];}function correctUVs(){var a=new Vector3$1();var b=new Vector3$1();var c=new Vector3$1();var centroid=new Vector3$1();var uvA=new Vector2$1();var uvB=new Vector2$1();var uvC=new Vector2$1();for(var i=0,j=0;i80*dim){minX=maxX=data[0];minY=maxY=data[1];for(var i=dim;imaxX)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$1(outerNode,triangles,dim,minX,minY,invSize);return triangles;}};// create a circular doubly linked list from polygon points in the specified winding order function linkedList$1(data,start,end,dim,clockwise){var i,last;if(clockwise===signedArea$1(data,start,end,dim)>0){for(i=start;i=start;i-=dim){last=insertNode$1(i,data[i],data[i+1],last);}}if(last&&equals$1(last,last.next)){removeNode$1(last);last=last.next;}return last;}// eliminate colinear or duplicate points function filterPoints$1(start,end){if(!start)return start;if(!end)end=start;var p=start,again;do{again=false;if(!p.steiner&&(equals$1(p,p.next)||area$1(p.prev,p,p.next)===0)){removeNode$1(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$1(ear,triangles,dim,minX,minY,invSize,pass){if(!ear)return;// interlink polygon nodes in z-order if(!pass&&invSize)indexCurve$1(ear,minX,minY,invSize);var 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$1(ear,minX,minY,invSize):isEar$1(ear)){// cut off the triangle triangles.push(prev.i/dim);triangles.push(ear.i/dim);triangles.push(next.i/dim);removeNode$1(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$1(filterPoints$1(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$1(filterPoints$1(ear),triangles,dim);earcutLinked$1(ear,triangles,dim,minX,minY,invSize,2);// as a last resort, try splitting the remaining polygon into two }else if(pass===2){splitEarcut$1(ear,triangles,dim,minX,minY,invSize);}break;}}}// check whether a polygon node forms a valid ear with adjacent nodes function isEar$1(ear){var a=ear.prev,b=ear,c=ear.next;if(area$1(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 var p=ear.next.next;while(p!==ear.prev){if(pointInTriangle$1(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area$1(p.prev,p,p.next)>=0)return false;p=p.next;}return true;}function isEarHashed$1(ear,minX,minY,invSize){var a=ear.prev,b=ear,c=ear.next;if(area$1(a,b,c)>=0)return false;// reflex, can't be an ear // triangle bbox; min & max are calculated like this for speed var minTX=a.xb.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; var minZ=zOrder$1(minTX,minTY,minX,minY,invSize),maxZ=zOrder$1(maxTX,maxTY,minX,minY,invSize);var 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$1(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area$1(p.prev,p,p.next)>=0)return false;p=p.prevZ;if(n!==ear.prev&&n!==ear.next&&pointInTriangle$1(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area$1(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$1(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area$1(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$1(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area$1(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$1(start,triangles,dim){var p=start;do{var a=p.prev,b=p.next.next;if(!equals$1(a,b)&&intersects$1(a,p,p.next,b)&&locallyInside$1(a,b)&&locallyInside$1(b,a)){triangles.push(a.i/dim);triangles.push(p.i/dim);triangles.push(b.i/dim);// remove two nodes involved removeNode$1(p);removeNode$1(p.next);p=start=b;}p=p.next;}while(p!==start);return filterPoints$1(p);}// try splitting polygon into two and triangulate them independently function splitEarcut$1(start,triangles,dim,minX,minY,invSize){// look for a valid diagonal that divides the polygon into two var a=start;do{var b=a.next.next;while(b!==a.prev){if(a.i!==b.i&&isValidDiagonal$1(a,b)){// split the polygon in two by the diagonal var c=splitPolygon$1(a,b);// filter colinear points around the cuts a=filterPoints$1(a,a.next);c=filterPoints$1(c,c.next);// run earcut on each half earcutLinked$1(a,triangles,dim,minX,minY,invSize);earcutLinked$1(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$1(data,holeIndices,outerNode,dim){var queue=[],i,len,start,end,list;for(i=0,len=holeIndices.length;i=p.next.y&&p.next.y!==p.y){var 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.x&&p.x>=mx&&hx!==p.x&&pointInTriangle$1(hym.x||p.x===m.x&§orContainsSector$1(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$1(m,p){return area$1(m.prev,m,p.prev)<0&&area$1(p.next,m,m.next)<0;}// interlink polygon nodes in z-order function indexCurve$1(start,minX,minY,invSize){var p=start;do{if(p.z===null)p.z=zOrder$1(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$1(p);}// Simon Tatham's linked list merge sort algorithm // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html function sortLinked$1(list){var 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;i0||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$1(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$1(start){var p=start,leftmost=start;do{if(p.x=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$1(a,b){return a.next.i!==b.i&&a.prev.i!==b.i&&!intersectsPolygon$1(a,b)&&(// dones't intersect other edges locallyInside$1(a,b)&&locallyInside$1(b,a)&&middleInside$1(a,b)&&(// locally visible area$1(a.prev,a,b.prev)||area$1(a,b.prev,b))||// does not create opposite-facing sectors equals$1(a,b)&&area$1(a.prev,a,a.next)>0&&area$1(b.prev,b,b.next)>0);// special zero-length case }// signed area of a triangle function area$1(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$1(p1,p2){return p1.x===p2.x&&p1.y===p2.y;}// check if two segments intersect function intersects$1(p1,q1,p2,q2){var o1=sign$1(area$1(p1,q1,p2));var o2=sign$1(area$1(p1,q1,q2));var o3=sign$1(area$1(p2,q2,p1));var o4=sign$1(area$1(p2,q2,q1));if(o1!==o2&&o3!==o4)return true;// general case if(o1===0&&onSegment$1(p1,p2,q1))return true;// p1, q1 and p2 are collinear and p2 lies on p1q1 if(o2===0&&onSegment$1(p1,q2,q1))return true;// p1, q1 and q2 are collinear and q2 lies on p1q1 if(o3===0&&onSegment$1(p2,p1,q2))return true;// p2, q2 and p1 are collinear and p1 lies on p2q2 if(o4===0&&onSegment$1(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$1(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$1(num){return num>0?1:num<0?-1:0;}// check if a polygon diagonal intersects any polygon segments function intersectsPolygon$1(a,b){var p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects$1(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$1(a,b){return area$1(a.prev,a,a.next)<0?area$1(a,b,a.next)>=0&&area$1(a,a.prev,b)>=0:area$1(a,b,a.prev)<0||area$1(a,a.next,b)<0;}// check if the middle point of a polygon diagonal is inside the polygon function middleInside$1(a,b){var 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$1(a,b){var a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(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$1(i,x,y,last){var p=new Node$2(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$1(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$2(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$1(data,start,end,dim){var sum=0;for(var i=start,j=end-dim;i2&&points[l-1].equals(points[0])){points.pop();}}function addContour$1(vertices,contour){for(var i=0;i, // number of points on the curves * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too * depth: , // Depth to extrude the shape * * bevelEnabled: , // turn on bevel * bevelThickness: , // how deep into the original shape bevel goes * bevelSize: , // how far from shape outline (including bevelOffset) is bevel * bevelOffset: , // how far from shape outline does bevel start * bevelSegments: , // number of bevel layers * * extrudePath: // curve to extrude shape along * * UVGenerator: // object that provides UV generator functions * * } */ // ExtrudeGeometry function ExtrudeGeometry$1(shapes,options){Geometry$1.call(this);this.type='ExtrudeGeometry';this.parameters={shapes:shapes,options:options};this.fromBufferGeometry(new ExtrudeBufferGeometry$1(shapes,options));this.mergeVertices();}ExtrudeGeometry$1.prototype=Object.create(Geometry$1.prototype);ExtrudeGeometry$1.prototype.constructor=ExtrudeGeometry$1;ExtrudeGeometry$1.prototype.toJSON=function(){var data=Geometry$1.prototype.toJSON.call(this);var shapes=this.parameters.shapes;var options=this.parameters.options;return toJSON$2(shapes,options,data);};// ExtrudeBufferGeometry function ExtrudeBufferGeometry$1(shapes,options){BufferGeometry$1.call(this);this.type='ExtrudeBufferGeometry';this.parameters={shapes:shapes,options:options};shapes=Array.isArray(shapes)?shapes:[shapes];var scope=this;var verticesArray=[];var uvArray=[];for(var i=0,l=shapes.length;iNumber.EPSILON){// not collinear // length of vectors for normalizing var v_prev_len=Math.sqrt(v_prev_lensq);var 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 var ptPrevShift_x=inPrev.x-v_prev_y/v_prev_len;var ptPrevShift_y=inPrev.y+v_prev_x/v_prev_len;var ptNextShift_x=inNext.x-v_next_y/v_next_len;var ptNextShift_y=inNext.y+v_next_x/v_next_len;// scaling factor for v_prev to intersection point var 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 var v_trans_lensq=v_trans_x*v_trans_x+v_trans_y*v_trans_y;if(v_trans_lensq<=2){return new Vector2$1(v_trans_x,v_trans_y);}else{shrink_by=Math.sqrt(v_trans_lensq/2);}}else{// handle special case of collinear edges var 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$1(v_trans_x/shrink_by,v_trans_y/shrink_by);}var contourMovements=[];for(var i=0,il=contour.length,j=il-1,k=i+1;i 0; b -- ) { t=b/bevelSegments;z=bevelThickness*Math.cos(t*Math.PI/2);bs=bevelSize*Math.sin(t*Math.PI/2)+bevelOffset;// contract shape for(i=0,il=contour.length;i=0;b--){t=b/bevelSegments;z=bevelThickness*Math.cos(t*Math.PI/2);bs=bevelSize*Math.sin(t*Math.PI/2)+bevelOffset;// contract shape for(i=0,il=contour.length;i=0){j=i;k=i-1;if(k<0)k=contour.length-1;//console.log('b', i,j, i-1, k,vertices.length); var s=0,sl=steps+bevelSegments*2;for(s=0;s, // font * * size: , // size of the text * height: , // thickness to extrude text * curveSegments: , // number of points on the curves * * bevelEnabled: , // turn on bevel * bevelThickness: , // how deep into text bevel goes * bevelSize: , // how far from text outline (including bevelOffset) is bevel * bevelOffset: // how far from text outline does bevel start * } */ // TextGeometry function TextGeometry$1(text,parameters){Geometry$1.call(this);this.type='TextGeometry';this.parameters={text:text,parameters:parameters};this.fromBufferGeometry(new TextBufferGeometry$1(text,parameters));this.mergeVertices();}TextGeometry$1.prototype=Object.create(Geometry$1.prototype);TextGeometry$1.prototype.constructor=TextGeometry$1;// TextBufferGeometry function TextBufferGeometry$1(text,parameters){parameters=parameters||{};var font=parameters.font;if(!(font&&font.isFont)){console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');return new Geometry$1();}var 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$1.call(this,shapes,parameters);this.type='TextBufferGeometry';}TextBufferGeometry$1.prototype=Object.create(ExtrudeBufferGeometry$1.prototype);TextBufferGeometry$1.prototype.constructor=TextBufferGeometry$1;/** * @author mrdoob / http://mrdoob.com/ * @author benaadams / https://twitter.com/ben_a_adams * @author Mugen87 / https://github.com/Mugen87 */ // SphereGeometry function SphereGeometry$1(radius,widthSegments,heightSegments,phiStart,phiLength,thetaStart,thetaLength){Geometry$1.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$1(radius,widthSegments,heightSegments,phiStart,phiLength,thetaStart,thetaLength));this.mergeVertices();}SphereGeometry$1.prototype=Object.create(Geometry$1.prototype);SphereGeometry$1.prototype.constructor=SphereGeometry$1;// SphereBufferGeometry function SphereBufferGeometry$1(radius,widthSegments,heightSegments,phiStart,phiLength,thetaStart,thetaLength){BufferGeometry$1.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;var thetaEnd=Math.min(thetaStart+thetaLength,Math.PI);var ix,iy;var index=0;var grid=[];var vertex=new Vector3$1();var normal=new Vector3$1();// buffers var indices=[];var vertices=[];var normals=[];var uvs=[];// generate vertices, normals and uvs for(iy=0;iy<=heightSegments;iy++){var verticesRow=[];var v=iy/heightSegments;// special case for the poles var uOffset=0;if(iy==0&&thetaStart==0){uOffset=0.5/widthSegments;}else if(iy==heightSegments&&thetaEnd==Math.PI){uOffset=-0.5/widthSegments;}for(ix=0;ix<=widthSegments;ix++){var 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(iy=0;iy0)indices.push(a,b,d);if(iy!==heightSegments-1||thetaEnd0)generateCap(true);if(radiusBottom>0)generateCap(false);}// build geometry this.setIndex(indices);this.setAttribute('position',new Float32BufferAttribute$1(vertices,3));this.setAttribute('normal',new Float32BufferAttribute$1(normals,3));this.setAttribute('uv',new Float32BufferAttribute$1(uvs,2));function generateTorso(){var x,y;var normal=new Vector3$1();var vertex=new Vector3$1();var groupCount=0;// this will be used to calculate the normal var slope=(radiusBottom-radiusTop)/height;// generate vertices, normals and uvs for(y=0;y<=heightSegments;y++){var indexRow=[];var v=y/heightSegments;// calculate the radius of the current row var radius=v*(radiusBottom-radiusTop)+radiusTop;for(x=0;x<=radialSegments;x++){var u=x/radialSegments;var theta=u*thetaLength+thetaStart;var sinTheta=Math.sin(theta);var 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(x=0;x * } */function ShadowMaterial$1(parameters){Material$1.call(this);this.type='ShadowMaterial';this.color=new Color$1(0x000000);this.transparent=true;this.setValues(parameters);}ShadowMaterial$1.prototype=Object.create(Material$1.prototype);ShadowMaterial$1.prototype.constructor=ShadowMaterial$1;ShadowMaterial$1.prototype.isShadowMaterial=true;ShadowMaterial$1.prototype.copy=function(source){Material$1.prototype.copy.call(this,source);this.color.copy(source.color);return this;};/** * @author mrdoob / http://mrdoob.com/ */function RawShaderMaterial$1(parameters){ShaderMaterial$1.call(this,parameters);this.type='RawShaderMaterial';}RawShaderMaterial$1.prototype=Object.create(ShaderMaterial$1.prototype);RawShaderMaterial$1.prototype.constructor=RawShaderMaterial$1;RawShaderMaterial$1.prototype.isRawShaderMaterial=true;/** * @author WestLangley / http://github.com/WestLangley * * parameters = { * color: , * roughness: , * metalness: , * opacity: , * * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * roughnessMap: new THREE.Texture( ), * * metalnessMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * envMapIntensity: * * refractionRatio: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */function MeshStandardMaterial$1(parameters){Material$1.call(this);this.defines={'STANDARD':''};this.type='MeshStandardMaterial';this.color=new Color$1(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$1(0x000000);this.emissiveIntensity=1.0;this.emissiveMap=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap$1;this.normalScale=new Vector2$1(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$1.prototype=Object.create(Material$1.prototype);MeshStandardMaterial$1.prototype.constructor=MeshStandardMaterial$1;MeshStandardMaterial$1.prototype.isMeshStandardMaterial=true;MeshStandardMaterial$1.prototype.copy=function(source){Material$1.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: , * clearcoatMap: new THREE.Texture( ), * clearcoatRoughness: , * clearcoatRoughnessMap: new THREE.Texture( ), * clearcoatNormalScale: , * clearcoatNormalMap: new THREE.Texture( ), * * reflectivity: , * * sheen: , * * transparency: * } */function MeshPhysicalMaterial$1(parameters){MeshStandardMaterial$1.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,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$1.prototype=Object.create(MeshStandardMaterial$1.prototype);MeshPhysicalMaterial$1.prototype.constructor=MeshPhysicalMaterial$1;MeshPhysicalMaterial$1.prototype.isMeshPhysicalMaterial=true;MeshPhysicalMaterial$1.prototype.copy=function(source){MeshStandardMaterial$1.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$1()).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: , * specular: , * shininess: , * opacity: , * * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * specularMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.MultiplyOperation, * reflectivity: , * refractionRatio: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */function MeshPhongMaterial$1(parameters){Material$1.call(this);this.type='MeshPhongMaterial';this.color=new Color$1(0xffffff);// diffuse this.specular=new Color$1(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$1(0x000000);this.emissiveIntensity=1.0;this.emissiveMap=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap$1;this.normalScale=new Vector2$1(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.specularMap=null;this.alphaMap=null;this.envMap=null;this.combine=MultiplyOperation$1;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$1.prototype=Object.create(Material$1.prototype);MeshPhongMaterial$1.prototype.constructor=MeshPhongMaterial$1;MeshPhongMaterial$1.prototype.isMeshPhongMaterial=true;MeshPhongMaterial$1.prototype.copy=function(source){Material$1.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: , * specular: , * shininess: , * * map: new THREE.Texture( ), * gradientMap: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * specularMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */function MeshToonMaterial$1(parameters){Material$1.call(this);this.defines={'TOON':''};this.type='MeshToonMaterial';this.color=new Color$1(0xffffff);this.specular=new Color$1(0x111111);this.shininess=30;this.map=null;this.gradientMap=null;this.lightMap=null;this.lightMapIntensity=1.0;this.aoMap=null;this.aoMapIntensity=1.0;this.emissive=new Color$1(0x000000);this.emissiveIntensity=1.0;this.emissiveMap=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap$1;this.normalScale=new Vector2$1(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.specularMap=null;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$1.prototype=Object.create(Material$1.prototype);MeshToonMaterial$1.prototype.constructor=MeshToonMaterial$1;MeshToonMaterial$1.prototype.isMeshToonMaterial=true;MeshToonMaterial$1.prototype.copy=function(source){Material$1.prototype.copy.call(this,source);this.color.copy(source.color);this.specular.copy(source.specular);this.shininess=source.shininess;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.specularMap=source.specularMap;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: , * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * wireframe: , * wireframeLinewidth: * * skinning: , * morphTargets: , * morphNormals: * } */function MeshNormalMaterial$1(parameters){Material$1.call(this);this.type='MeshNormalMaterial';this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap$1;this.normalScale=new Vector2$1(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$1.prototype=Object.create(Material$1.prototype);MeshNormalMaterial$1.prototype.constructor=MeshNormalMaterial$1;MeshNormalMaterial$1.prototype.isMeshNormalMaterial=true;MeshNormalMaterial$1.prototype.copy=function(source){Material$1.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: , * opacity: , * * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * specularMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.Multiply, * reflectivity: , * refractionRatio: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */function MeshLambertMaterial$1(parameters){Material$1.call(this);this.type='MeshLambertMaterial';this.color=new Color$1(0xffffff);// diffuse this.map=null;this.lightMap=null;this.lightMapIntensity=1.0;this.aoMap=null;this.aoMapIntensity=1.0;this.emissive=new Color$1(0x000000);this.emissiveIntensity=1.0;this.emissiveMap=null;this.specularMap=null;this.alphaMap=null;this.envMap=null;this.combine=MultiplyOperation$1;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$1.prototype=Object.create(Material$1.prototype);MeshLambertMaterial$1.prototype.constructor=MeshLambertMaterial$1;MeshLambertMaterial$1.prototype.isMeshLambertMaterial=true;MeshLambertMaterial$1.prototype.copy=function(source){Material$1.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: , * opacity: , * * matcap: new THREE.Texture( ), * * map: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * alphaMap: new THREE.Texture( ), * * skinning: , * morphTargets: , * morphNormals: * } */function MeshMatcapMaterial$1(parameters){Material$1.call(this);this.defines={'MATCAP':''};this.type='MeshMatcapMaterial';this.color=new Color$1(0xffffff);// diffuse this.matcap=null;this.map=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap$1;this.normalScale=new Vector2$1(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$1.prototype=Object.create(Material$1.prototype);MeshMatcapMaterial$1.prototype.constructor=MeshMatcapMaterial$1;MeshMatcapMaterial$1.prototype.isMeshMatcapMaterial=true;MeshMatcapMaterial$1.prototype.copy=function(source){Material$1.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: , * opacity: , * * linewidth: , * * scale: , * dashSize: , * gapSize: * } */function LineDashedMaterial$1(parameters){LineBasicMaterial$1.call(this);this.type='LineDashedMaterial';this.scale=1;this.dashSize=3;this.gapSize=1;this.setValues(parameters);}LineDashedMaterial$1.prototype=Object.create(LineBasicMaterial$1.prototype);LineDashedMaterial$1.prototype.constructor=LineDashedMaterial$1;LineDashedMaterial$1.prototype.isLineDashedMaterial=true;LineDashedMaterial$1.prototype.copy=function(source){LineBasicMaterial$1.prototype.copy.call(this,source);this.scale=source.scale;this.dashSize=source.dashSize;this.gapSize=source.gapSize;return this;};var Materials$1=/*#__PURE__*/Object.freeze({__proto__:null,ShadowMaterial:ShadowMaterial$1,SpriteMaterial:SpriteMaterial$1,RawShaderMaterial:RawShaderMaterial$1,ShaderMaterial:ShaderMaterial$1,PointsMaterial:PointsMaterial$1,MeshPhysicalMaterial:MeshPhysicalMaterial$1,MeshStandardMaterial:MeshStandardMaterial$1,MeshPhongMaterial:MeshPhongMaterial$1,MeshToonMaterial:MeshToonMaterial$1,MeshNormalMaterial:MeshNormalMaterial$1,MeshLambertMaterial:MeshLambertMaterial$1,MeshDepthMaterial:MeshDepthMaterial$1,MeshDistanceMaterial:MeshDistanceMaterial$1,MeshBasicMaterial:MeshBasicMaterial$1,MeshMatcapMaterial:MeshMatcapMaterial$1,LineDashedMaterial:LineDashedMaterial$1,LineBasicMaterial:LineBasicMaterial$1,Material:Material$1});/** * @author tschw * @author Ben Houston / http://clara.io/ * @author David Sarno / http://lighthaus.us/ */var AnimationUtils$1={// same as Array.prototype.slice, but also works on typed arrays arraySlice:function arraySlice(array,from,to){if(AnimationUtils$1.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 convertArray(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 isTypedArray(object){return ArrayBuffer.isView(object)&&!_instanceof(object,DataView);},// returns an array by which times and values can be sorted getKeyframeOrder:function getKeyframeOrder(times){function compareTime(i,j){return times[i]-times[j];}var n=times.length;var result=new Array(n);for(var 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 sortedArray(values,stride,order){var nValues=values.length;var result=new values.constructor(nValues);for(var i=0,dstOffset=0;dstOffset!==nValues;++i){var srcOffset=order[i]*stride;for(var j=0;j!==stride;++j){result[dstOffset++]=values[srcOffset+j];}}return result;},// function for parsing AOS keyframe formats flattenJSON:function flattenJSON(jsonKeys,times,values,valuePropertyName){var i=1,key=jsonKeys[0];while(key!==undefined&&key[valuePropertyName]===undefined){key=jsonKeys[i++];}if(key===undefined)return;// no data var 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 subclip(sourceClip,name,startFrame,endFrame,fps){fps=fps||30;var clip=sourceClip.clone();clip.name=name;var tracks=[];for(var i=0;i=endFrame)continue;times.push(track.times[j]);for(var k=0;kclip.tracks[i].times[0]){minStartTime=clip.tracks[i].times[0];}}// shift all tracks such that clip begins at t=0 for(var i=0;i=referenceTrack.times[lastIndex]){// Reference frame is after the last keyframe, so just use the last keyframe var startIndex=lastIndex*valueSize;referenceValue=AnimationUtils$1.arraySlice(referenceTrack.values,startIndex);}else{// Interpolate to the reference value var interpolant=referenceTrack.createInterpolant();interpolant.evaluate(referenceTime);referenceValue=interpolant.resultBuffer;}// Conjugate the quaternion if(referenceTrackType==='quaternion'){var referenceQuat=new Quaternion$1(referenceValue[0],referenceValue[1],referenceValue[2],referenceValue[3]).normalize().conjugate();referenceQuat.toArray(referenceValue);}// Subtract the reference value from all of the track values var numTimes=targetTrack.times.length;for(var j=0;j= t1 || t1 === undefined ) { forward_scan:if(!(t=t0)){// looping? var t1global=pp[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>>1;if(t seconds conversions) scale:function scale(timeScale){if(timeScale!==1.0){var times=this.times;for(var 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 trim(startTime,endTime){var times=this.times,nKeys=times.length,from=0,to=nKeys-1;while(from!==nKeys&×[from]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;}var stride=this.getValueSize();this.times=AnimationUtils$1.arraySlice(times,from,to);this.values=AnimationUtils$1.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 validate(){var valid=true;var valueSize=this.getValueSize();if(valueSize-Math.floor(valueSize)!==0){console.error('THREE.KeyframeTrack: Invalid value size in track.',this);valid=false;}var times=this.times,values=this.values,nKeys=times.length;if(nKeys===0){console.error('THREE.KeyframeTrack: Track is empty.',this);valid=false;}var prevTime=null;for(var i=0;i!==nKeys;i++){var 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$1.isTypedArray(values)){for(var i=0,n=values.length;i!==n;++i){var 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 optimize(){// times or values may be shared with other tracks, so overwriting is unsafe var times=AnimationUtils$1.arraySlice(this.times),values=AnimationUtils$1.arraySlice(this.values),stride=this.getValueSize(),smoothInterpolation=this.getInterpolation()===InterpolateSmooth$1,writeIndex=1,lastIndex=times.length-1;for(var i=1;i0){times[writeIndex]=times[lastIndex];for(var 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$1.arraySlice(times,0,writeIndex);this.values=AnimationUtils$1.arraySlice(values,0,writeIndex*stride);}else{this.times=times;this.values=values;}return this;},clone:function clone(){var times=AnimationUtils$1.arraySlice(this.times,0);var values=AnimationUtils$1.arraySlice(this.values,0);var TypedKeyframeTrack=this.constructor;var 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$1(name,times,values){KeyframeTrack$1.call(this,name,times,values);}BooleanKeyframeTrack$1.prototype=Object.assign(Object.create(KeyframeTrack$1.prototype),{constructor:BooleanKeyframeTrack$1,ValueTypeName:'bool',ValueBufferType:Array,DefaultInterpolation:InterpolateDiscrete$1,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$1(name,times,values,interpolation){KeyframeTrack$1.call(this,name,times,values,interpolation);}ColorKeyframeTrack$1.prototype=Object.assign(Object.create(KeyframeTrack$1.prototype),{constructor:ColorKeyframeTrack$1,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$1(name,times,values,interpolation){KeyframeTrack$1.call(this,name,times,values,interpolation);}NumberKeyframeTrack$1.prototype=Object.assign(Object.create(KeyframeTrack$1.prototype),{constructor:NumberKeyframeTrack$1,ValueTypeName:'number'// ValueBufferType is inherited // DefaultInterpolation is inherited });/** * Spherical linear unit quaternion interpolant. * * @author tschw */function QuaternionLinearInterpolant$1(parameterPositions,sampleValues,sampleSize,resultBuffer){Interpolant$1.call(this,parameterPositions,sampleValues,sampleSize,resultBuffer);}QuaternionLinearInterpolant$1.prototype=Object.assign(Object.create(Interpolant$1.prototype),{constructor:QuaternionLinearInterpolant$1,interpolate_:function interpolate_(i1,t0,t,t1){var result=this.resultBuffer,values=this.sampleValues,stride=this.valueSize,offset=i1*stride,alpha=(t-t0)/(t1-t0);for(var end=offset+stride;offset!==end;offset+=4){Quaternion$1.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$1(name,times,values,interpolation){KeyframeTrack$1.call(this,name,times,values,interpolation);}QuaternionKeyframeTrack$1.prototype=Object.assign(Object.create(KeyframeTrack$1.prototype),{constructor:QuaternionKeyframeTrack$1,ValueTypeName:'quaternion',// ValueBufferType is inherited DefaultInterpolation:InterpolateLinear$1,InterpolantFactoryMethodLinear:function InterpolantFactoryMethodLinear(result){return new QuaternionLinearInterpolant$1(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$1(name,times,values,interpolation){KeyframeTrack$1.call(this,name,times,values,interpolation);}StringKeyframeTrack$1.prototype=Object.assign(Object.create(KeyframeTrack$1.prototype),{constructor:StringKeyframeTrack$1,ValueTypeName:'string',ValueBufferType:Array,DefaultInterpolation:InterpolateDiscrete$1,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$1(name,times,values,interpolation){KeyframeTrack$1.call(this,name,times,values,interpolation);}VectorKeyframeTrack$1.prototype=Object.assign(Object.create(KeyframeTrack$1.prototype),{constructor:VectorKeyframeTrack$1,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$1(name,duration,tracks,blendMode){this.name=name;this.tracks=tracks;this.duration=duration!==undefined?duration:-1;this.blendMode=blendMode!==undefined?blendMode:NormalAnimationBlendMode$1;this.uuid=MathUtils$1.generateUUID();// this means it should figure out its duration by scanning the tracks if(this.duration<0){this.resetDuration();}}function getTrackTypeForValueTypeName$1(typeName){switch(typeName.toLowerCase()){case'scalar':case'double':case'float':case'number':case'integer':return NumberKeyframeTrack$1;case'vector':case'vector2':case'vector3':case'vector4':return VectorKeyframeTrack$1;case'color':return ColorKeyframeTrack$1;case'quaternion':return QuaternionKeyframeTrack$1;case'bool':case'boolean':return BooleanKeyframeTrack$1;case'string':return StringKeyframeTrack$1;}throw new Error('THREE.KeyframeTrack: Unsupported typeName: '+typeName);}function parseKeyframeTrack$1(json){if(json.type===undefined){throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');}var trackType=getTrackTypeForValueTypeName$1(json.type);if(json.times===undefined){var times=[],values=[];AnimationUtils$1.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$1,{parse:function parse(json){var tracks=[],jsonTracks=json.tracks,frameTime=1.0/(json.fps||1.0);for(var i=0,n=jsonTracks.length;i!==n;++i){tracks.push(parseKeyframeTrack$1(jsonTracks[i]).scale(frameTime));}return new AnimationClip$1(json.name,json.duration,tracks,json.blendMode);},toJSON:function toJSON(clip){var tracks=[],clipTracks=clip.tracks;var json={'name':clip.name,'duration':clip.duration,'tracks':tracks,'uuid':clip.uuid,'blendMode':clip.blendMode};for(var i=0,n=clipTracks.length;i!==n;++i){tracks.push(KeyframeTrack$1.toJSON(clipTracks[i]));}return json;},CreateFromMorphTargetSequence:function CreateFromMorphTargetSequence(name,morphTargetSequence,fps,noLoop){var numMorphTargets=morphTargetSequence.length;var tracks=[];for(var i=0;i1){var name=parts[1];var animationMorphTargets=animationToMorphTargets[name];if(!animationMorphTargets){animationToMorphTargets[name]=animationMorphTargets=[];}animationMorphTargets.push(morphTarget);}}var clips=[];for(var name in animationToMorphTargets){clips.push(AnimationClip$1.CreateFromMorphTargetSequence(name,animationToMorphTargets[name],fps,noLoop));}return clips;},// parse the animation.hierarchy format parseAnimation:function parseAnimation(animation,bones){if(!animation){console.error('THREE.AnimationClip: No animation in JSONLoader data.');return null;}var addNonemptyTrack=function addNonemptyTrack(trackType,trackName,animationKeys,propertyName,destTracks){// only return track if there are actually keys. if(animationKeys.length!==0){var times=[];var values=[];AnimationUtils$1.flattenJSON(animationKeys,times,values,propertyName);// empty keys are filtered out, so check again if(times.length!==0){destTracks.push(new trackType(trackName,times,values));}}};var tracks=[];var clipName=animation.name||'default';// automatic length determination in AnimationClip. var duration=animation.length||-1;var fps=animation.fps||30;var blendMode=animation.blendMode;var hierarchyTracks=animation.hierarchy||[];for(var h=0;h0||url.search(/^data\:image\/jpeg/)===0;texture.format=isJPEG?RGBFormat$1:RGBAFormat$1;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$1(){this.type='Curve';this.arcLengthDivisions=200;}Object.assign(Curve$1.prototype,{// Virtual base class method to overwrite and implement in subclasses // - t [0 .. 1] getPoint:function getPoint()/* 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 getPointAt(u,optionalTarget){var t=this.getUtoTmapping(u);return this.getPoint(t,optionalTarget);},// Get sequence of points using getPoint( t ) getPoints:function getPoints(divisions){if(divisions===undefined)divisions=5;var points=[];for(var d=0;d<=divisions;d++){points.push(this.getPoint(d/divisions));}return points;},// Get sequence of points using getPointAt( u ) getSpacedPoints:function getSpacedPoints(divisions){if(divisions===undefined)divisions=5;var points=[];for(var d=0;d<=divisions;d++){points.push(this.getPointAt(d/divisions));}return points;},// Get total curve arc length getLength:function getLength(){var lengths=this.getLengths();return lengths[lengths.length-1];},// Get list of cumulative segment lengths getLengths:function getLengths(divisions){if(divisions===undefined)divisions=this.arcLengthDivisions;if(this.cacheArcLengths&&this.cacheArcLengths.length===divisions+1&&!this.needsUpdate){return this.cacheArcLengths;}this.needsUpdate=false;var cache=[];var current,last=this.getPoint(0);var p,sum=0;cache.push(0);for(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 updateArcLengths(){this.needsUpdate=true;this.getLengths();},// Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant getUtoTmapping:function getUtoTmapping(u,distance){var arcLengths=this.getLengths();var i=0,il=arcLengths.length;var 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 var 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 var lengthBefore=arcLengths[i];var lengthAfter=arcLengths[i+1];var segmentLength=lengthAfter-lengthBefore;// determine where we are between the 'before' and 'after' points var segmentFraction=(targetArcLength-lengthBefore)/segmentLength;// add that fractional amount to t var 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 getTangent(t,optionalTarget){var delta=0.0001;var t1=t-delta;var t2=t+delta;// Capping in case of danger if(t1<0)t1=0;if(t2>1)t2=1;var pt1=this.getPoint(t1);var pt2=this.getPoint(t2);var tangent=optionalTarget||(pt1.isVector2?new Vector2$1():new Vector3$1());tangent.copy(pt2).sub(pt1).normalize();return tangent;},getTangentAt:function getTangentAt(u,optionalTarget){var t=this.getUtoTmapping(u);return this.getTangent(t,optionalTarget);},computeFrenetFrames:function computeFrenetFrames(segments,closed){// see http://www.cs.indiana.edu/pub/techreports/TR425.pdf var normal=new Vector3$1();var tangents=[];var normals=[];var binormals=[];var vec=new Vector3$1();var mat=new Matrix4$1();var i,u,theta;// compute the tangent vectors for each segment on the curve for(i=0;i<=segments;i++){u=i/segments;tangents[i]=this.getTangentAt(u,new Vector3$1());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$1();binormals[0]=new Vector3$1();var min=Number.MAX_VALUE;var tx=Math.abs(tangents[0].x);var ty=Math.abs(tangents[0].y);var 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(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();theta=Math.acos(MathUtils$1.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){theta=Math.acos(MathUtils$1.clamp(normals[0].dot(normals[segments]),-1,1));theta/=segments;if(tangents[0].dot(vec.crossVectors(normals[0],normals[segments]))>0){theta=-theta;}for(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 clone(){return new this.constructor().copy(this);},copy:function copy(source){this.arcLengthDivisions=source.arcLengthDivisions;return this;},toJSON:function toJSON(){var data={metadata:{version:4.5,type:'Curve',generator:'Curve.toJSON'}};data.arcLengthDivisions=this.arcLengthDivisions;data.type=this.type;return data;},fromJSON:function fromJSON(json){this.arcLengthDivisions=json.arcLengthDivisions;return this;}});function EllipseCurve$1(aX,aY,xRadius,yRadius,aStartAngle,aEndAngle,aClockwise,aRotation){Curve$1.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$1.prototype=Object.create(Curve$1.prototype);EllipseCurve$1.prototype.constructor=EllipseCurve$1;EllipseCurve$1.prototype.isEllipseCurve=true;EllipseCurve$1.prototype.getPoint=function(t,optionalTarget){var point=optionalTarget||new Vector2$1();var twoPi=Math.PI*2;var deltaAngle=this.aEndAngle-this.aStartAngle;var samePoints=Math.abs(deltaAngle)twoPi){deltaAngle-=twoPi;}if(deltaAngle0?0:(Math.floor(Math.abs(intPoint)/l)+1)*l;}else if(weight===0&&intPoint===l-1){intPoint=l-2;weight=1;}var p0,p1,p2,p3;// 4 points if(this.closed||intPoint>0){p0=points[(intPoint-1)%l];}else{// extrapolate first point tmp$1.subVectors(points[0],points[1]).add(points[0]);p0=tmp$1;}p1=points[intPoint%l];p2=points[(intPoint+1)%l];if(this.closed||intPoint+2points.length-2?points.length-1:intPoint+1];var p3=points[intPoint>points.length-3?points.length-1:intPoint+2];point.set(CatmullRom$1(weight,p0.x,p1.x,p2.x,p3.x),CatmullRom$1(weight,p0.y,p1.y,p2.y,p3.y));return point;};SplineCurve$1.prototype.copy=function(source){Curve$1.prototype.copy.call(this,source);this.points=[];for(var i=0,l=source.points.length;i=d){var diff=curveLengths[i]-d;var curve=this.curves[i];var segmentLength=curve.getLength();var u=segmentLength===0?0:1-diff/segmentLength;return curve.getPointAt(u);}i++;}return null;// loop where sum != 0, sum > d , sum+1 1&&!points[points.length-1].equals(points[0])){points.push(points[0]);}return points;},copy:function copy(source){Curve$1.prototype.copy.call(this,source);this.curves=[];for(var i=0,l=source.curves.length;i0){// if a previous curve is present, attempt to join var firstPoint=curve.getPoint(0);if(!firstPoint.equals(this.currentPoint)){this.lineTo(firstPoint.x,firstPoint.y);}}this.curves.push(curve);var lastPoint=curve.getPoint(1);this.currentPoint.copy(lastPoint);return this;},copy:function copy(source){CurvePath$1.prototype.copy.call(this,source);this.currentPoint.copy(source.currentPoint);return this;},toJSON:function toJSON(){var data=CurvePath$1.prototype.toJSON.call(this);data.currentPoint=this.currentPoint.toArray();return data;},fromJSON:function fromJSON(json){CurvePath$1.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$1(points){Path$1.call(this,points);this.uuid=MathUtils$1.generateUUID();this.type='Shape';this.holes=[];}Shape$1.prototype=Object.assign(Object.create(Path$1.prototype),{constructor:Shape$1,getPointsHoles:function getPointsHoles(divisions){var holesPts=[];for(var i=0,l=this.holes.length;i0?true:false;}else{material.vertexColors=json.vertexColors;}}// Shader Material if(json.uniforms!==undefined){for(var name in json.uniforms){var 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$1().setHex(uniform.value);break;case'v2':material.uniforms[name].value=new Vector2$1().fromArray(uniform.value);break;case'v3':material.uniforms[name].value=new Vector3$1().fromArray(uniform.value);break;case'v4':material.uniforms[name].value=new Vector4$1().fromArray(uniform.value);break;case'm3':material.uniforms[name].value=new Matrix3$1().fromArray(uniform.value);case'm4':material.uniforms[name].value=new Matrix4$1().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(var 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){var normalScale=json.normalScale;if(Array.isArray(normalScale)===false){// Blender exporter used to export a scalar. See #7459 normalScale=[normalScale,normalScale];}material.normalScale=new Vector2$1().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$1().fromArray(json.clearcoatNormalScale);return material;},setTextures:function setTextures(value){this.textures=value;return this;}});/** * @author Don McCurdy / https://www.donmccurdy.com */var LoaderUtils$1={decodeText:function decodeText(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. var s='';for(var i=0,il=array.length;i0){var manager=new LoadingManager$1(onLoad);var loader=new ImageLoader$1(manager);loader.setCrossOrigin(this.crossOrigin);for(var i=0,il=json.length;i 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 var inside=false;for(var p=polyLen-1,q=0;qNumber.EPSILON){// not parallel if(edgeDy<0){edgeLowPt=inPolygon[q];edgeDx=-edgeDx;edgeHighPt=inPolygon[p];edgeDy=-edgeDy;}if(inPt.yedgeHighPt.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{var 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;}var isClockWise=ShapeUtils$1.isClockWise;var subPaths=this.subPaths;if(subPaths.length===0)return[];if(noHoles===true)return toShapesNoHoles(subPaths);var solid,tmpPath,tmpShape,shapes=[];if(subPaths.length===1){tmpPath=subPaths[0];tmpShape=new Shape$1();tmpShape.curves=tmpPath.curves;shapes.push(tmpShape);return shapes;}var holesFirst=!isClockWise(subPaths[0].getPoints());holesFirst=isCCW?!holesFirst:holesFirst;// console.log("Holes first", holesFirst); var betterShapeHoles=[];var newShapes=[];var newShapeHoles=[];var mainIdx=0;var tmpPoints;newShapes[mainIdx]=undefined;newShapeHoles[mainIdx]=[];for(var i=0,l=subPaths.length;i probably all Shapes with wrong orientation if(!newShapes[0])return toShapesNoHoles(subPaths);if(newShapes.length>1){var ambiguous=false;var toChange=[];for(var sIdx=0,sLen=newShapes.length;sIdx0){// console.log("to change: ", toChange); if(!ambiguous)newShapeHoles=betterShapeHoles;}}var tmpHoles;for(var i=0,il=newShapes.length;i0){this.source.connect(this.filters[0]);for(var i=1,l=this.filters.length;i0){this.source.disconnect(this.filters[0]);for(var i=1,l=this.filters.length;i' accumulate:function accumulate(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 var buffer=this.buffer,stride=this.valueSize,offset=accuIndex*stride+stride,currentWeight=this.cumulativeWeight;if(currentWeight===0){// accuN := incoming * weight for(var i=0;i!==stride;++i){buffer[offset+i]=buffer[i];}currentWeight=weight;}else{// accuN := accuN + incoming * weight currentWeight+=weight;var mix=weight/currentWeight;this._mixBufferRegion(buffer,offset,0,mix,stride);}this.cumulativeWeight=currentWeight;},// accumulate data in the 'incoming' region into 'add' accumulateAdditive:function accumulateAdditive(weight){var 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' to the binding when accus differ apply:function apply(accuIndex){var 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 ) var 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(var 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 saveOriginalState(){var binding=this.binding;var 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(var 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 restoreOriginalState(){var originalValueOffset=this.valueSize*3;this.binding.setValue(this.buffer,originalValueOffset);},_setAdditiveIdentityNumeric:function _setAdditiveIdentityNumeric(){var startIndex=this._addIndex*this.valueSize;var endIndex=startIndex+this.valueSize;for(var i=startIndex;i=0.5){for(var i=0;i!==stride;++i){buffer[dstOffset+i]=buffer[srcOffset+i];}}},_slerp:function _slerp(buffer,dstOffset,srcOffset,t){Quaternion$1.slerpFlat(buffer,dstOffset,buffer,dstOffset,buffer,srcOffset,t);},_slerpAdditive:function _slerpAdditive(buffer,dstOffset,srcOffset,t,stride){var workOffset=this._workIndex*stride;// Store result in intermediate buffer offset Quaternion$1.multiplyQuaternionsFlat(buffer,workOffset,buffer,dstOffset,buffer,srcOffset);// Slerp to the intermediate result Quaternion$1.slerpFlat(buffer,dstOffset,buffer,dstOffset,buffer,workOffset,t);},_lerp:function _lerp(buffer,dstOffset,srcOffset,t,stride){var s=1-t;for(var i=0;i!==stride;++i){var j=dstOffset+i;buffer[j]=buffer[j]*s+buffer[srcOffset+i]*t;}},_lerpAdditive:function _lerpAdditive(buffer,dstOffset,srcOffset,t,stride){for(var i=0;i!==stride;++i){var 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. var _RESERVED_CHARS_RE$1='\\[\\]\\.:\\/';var _reservedRe$1=new RegExp('['+_RESERVED_CHARS_RE$1+']','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. var _wordChar$1='[^'+_RESERVED_CHARS_RE$1+']';var _wordCharOrDot$1='[^'+_RESERVED_CHARS_RE$1.replace('\\.','')+']';// Parent directories, delimited by '/' or ':'. Currently unused, but must // be matched to parse the rest of the track name. var _directoryRe$1=/((?:WC+[\/:])*)/.source.replace('WC',_wordChar$1);// Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'. var _nodeRe$1=/(WCOD+)?/.source.replace('WCOD',_wordCharOrDot$1);// Object on target node, and accessor. May not contain reserved // characters. Accessor may contain any character except closing bracket. var _objectRe$1=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC',_wordChar$1);// Property and accessor. May not contain reserved characters. Accessor may // contain any non-bracket characters. var _propertyRe$1=/\.(WC+)(?:\[(.+)\])?/.source.replace('WC',_wordChar$1);var _trackRe$1=new RegExp(''+'^'+_directoryRe$1+_nodeRe$1+_objectRe$1+_propertyRe$1+'$');var _supportedObjectNames$1=['material','materials','bones'];function Composite$1(targetGroup,path,optionalParsedPath){var parsedPath=optionalParsedPath||PropertyBinding$1.parseTrackName(path);this._targetGroup=targetGroup;this._bindings=targetGroup.subscribe_(path,parsedPath);}Object.assign(Composite$1.prototype,{getValue:function getValue(array,offset){this.bind();// bind all binding var firstValidIndex=this._targetGroup.nCachedObjects_,binding=this._bindings[firstValidIndex];// and only call .getValue on the first if(binding!==undefined)binding.getValue(array,offset);},setValue:function setValue(array,offset){var bindings=this._bindings;for(var i=this._targetGroup.nCachedObjects_,n=bindings.length;i!==n;++i){bindings[i].setValue(array,offset);}},bind:function bind(){var bindings=this._bindings;for(var i=this._targetGroup.nCachedObjects_,n=bindings.length;i!==n;++i){bindings[i].bind();}},unbind:function unbind(){var bindings=this._bindings;for(var i=this._targetGroup.nCachedObjects_,n=bindings.length;i!==n;++i){bindings[i].unbind();}}});function PropertyBinding$1(rootNode,path,parsedPath){this.path=path;this.parsedPath=parsedPath||PropertyBinding$1.parseTrackName(path);this.node=PropertyBinding$1.findNode(rootNode,this.parsedPath.nodeName)||rootNode;this.rootNode=rootNode;}Object.assign(PropertyBinding$1,{Composite:Composite$1,create:function create(root,path,parsedPath){if(!(root&&root.isAnimationObjectGroup)){return new PropertyBinding$1(root,path,parsedPath);}else{return new PropertyBinding$1.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 sanitizeNodeName(name){return name.replace(/\s/g,'_').replace(_reservedRe$1,'');},parseTrackName:function parseTrackName(trackName){var matches=_trackRe$1.exec(trackName);if(!matches){throw new Error('PropertyBinding: Cannot parse trackName: '+trackName);}var results={// directoryName: matches[ 1 ], // (tschw) currently unused nodeName:matches[2],objectName:matches[3],objectIndex:matches[4],propertyName:matches[5],// required propertyIndex:matches[6]};var lastDot=results.nodeName&&results.nodeName.lastIndexOf('.');if(lastDot!==undefined&&lastDot!==-1){var objectName=results.nodeName.substring(lastDot+1);// Object names must be checked against a whitelist. 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$1.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 findNode(root,nodeName){if(!nodeName||nodeName===""||nodeName==="."||nodeName===-1||nodeName===root.name||nodeName===root.uuid){return root;}// search into skeleton bones. if(root.skeleton){var bone=root.skeleton.getBoneByName(nodeName);if(bone!==undefined){return bone;}}// search into node subtree. if(root.children){var searchNodeSubtree=function searchNodeSubtree(children){for(var i=0;i this._bindingsIndicesByPath={};// inside: indices in these arrays var 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$1.prototype,{isAnimationObjectGroup:true,add:function add(){var objects=this._objects,nObjects=objects.length,nCachedObjects=this.nCachedObjects_,indicesByUUID=this._indicesByUUID,paths=this._paths,parsedPaths=this._parsedPaths,bindings=this._bindings,nBindings=bindings.length,knownObject=undefined;for(var i=0,n=arguments.length;i!==n;++i){var object=arguments[i],uuid=object.uuid,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(var j=0,m=nBindings;j!==m;++j){bindings[j].push(new PropertyBinding$1(object,paths[j],parsedPaths[j]));}}else if(index=nCachedObjects){// move existing object into the CACHED region var 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(var j=0,m=nBindings;j!==m;++j){var bindingsForPath=bindings[j],firstActive=bindingsForPath[lastCachedIndex],binding=bindingsForPath[index];bindingsForPath[index]=firstActive;bindingsForPath[lastCachedIndex]=binding;}}}// for arguments this.nCachedObjects_=nCachedObjects;},// remove & forget uncache:function uncache(){var objects=this._objects,nObjects=objects.length,nCachedObjects=this.nCachedObjects_,indicesByUUID=this._indicesByUUID,bindings=this._bindings,nBindings=bindings.length;for(var i=0,n=arguments.length;i!==n;++i){var object=arguments[i],uuid=object.uuid,index=indicesByUUID[uuid];if(index!==undefined){delete indicesByUUID[uuid];if(index 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$1.prototype,{// State & Scheduling play:function play(){this._mixer._activateAction(this);return this;},stop:function stop(){this._mixer._deactivateAction(this);return this.reset();},reset:function reset(){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 isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this);},// return true when play has been called isScheduled:function isScheduled(){return this._mixer._isActiveAction(this);},startAt:function startAt(time){this._startTime=time;return this;},setLoop:function setLoop(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 setEffectiveWeight(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 getEffectiveWeight(){return this._effectiveWeight;},fadeIn:function fadeIn(duration){return this._scheduleFading(duration,0,1);},fadeOut:function fadeOut(duration){return this._scheduleFading(duration,1,0);},crossFadeFrom:function crossFadeFrom(fadeOutAction,duration,warp){fadeOutAction.fadeOut(duration);this.fadeIn(duration);if(warp){var 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 crossFadeTo(fadeInAction,duration,warp){return fadeInAction.crossFadeFrom(this,duration,warp);},stopFading:function stopFading(){var 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 setEffectiveTimeScale(timeScale){this.timeScale=timeScale;this._effectiveTimeScale=this.paused?0:timeScale;return this.stopWarping();},// return the time scale considering warping and .paused getEffectiveTimeScale:function getEffectiveTimeScale(){return this._effectiveTimeScale;},setDuration:function setDuration(duration){this.timeScale=this._clip.duration/duration;return this.stopWarping();},syncWith:function syncWith(action){this.time=action.time;this.timeScale=action.timeScale;return this.stopWarping();},halt:function halt(duration){return this.warp(this._effectiveTimeScale,0,duration);},warp:function warp(startTimeScale,endTimeScale,duration){var mixer=this._mixer,now=mixer.time,interpolant=this._timeScaleInterpolant,timeScale=this.timeScale;if(interpolant===null){interpolant=mixer._lendControlInterpolant();this._timeScaleInterpolant=interpolant;}var 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 stopWarping(){var timeScaleInterpolant=this._timeScaleInterpolant;if(timeScaleInterpolant!==null){this._timeScaleInterpolant=null;this._mixer._takeBackControlInterpolant(timeScaleInterpolant);}return this;},// Object Accessors getMixer:function getMixer(){return this._mixer;},getClip:function getClip(){return this._clip;},getRoot:function getRoot(){return this._localRoot||this._mixer._root;},// Interna _update:function _update(time,deltaTime,timeDirection,accuIndex){// called by the mixer if(!this.enabled){// call ._updateWeight() to update ._effectiveWeight this._updateWeight(time);return;}var startTime=this._startTime;if(startTime!==null){// check for scheduled start of action var 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);var clipTime=this._updateTime(deltaTime);// note: _updateTime may disable the action resulting in // an effective weight of 0 var weight=this._updateWeight(time);if(weight>0){var interpolants=this._interpolants;var propertyMixers=this._propertyBindings;switch(this.blendMode){case AdditiveAnimationBlendMode$1:for(var j=0,m=interpolants.length;j!==m;++j){interpolants[j].evaluate(clipTime);propertyMixers[j].accumulateAdditive(weight);}break;case NormalAnimationBlendMode$1:default:for(var j=0,m=interpolants.length;j!==m;++j){interpolants[j].evaluate(clipTime);propertyMixers[j].accumulate(accuIndex,weight);}}}},_updateWeight:function _updateWeight(time){var weight=0;if(this.enabled){weight=this.weight;var interpolant=this._weightInterpolant;if(interpolant!==null){var 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 _updateTimeScale(time){var timeScale=0;if(!this.paused){timeScale=this.timeScale;var interpolant=this._timeScaleInterpolant;if(interpolant!==null){var 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 _updateTime(deltaTime){var time=this.time+deltaTime;var duration=this._clip.duration;var loop=this.loop;var loopCount=this._loopCount;var pingPong=loop===LoopPingPong$1;if(deltaTime===0){if(loopCount===-1)return time;return pingPong&&(loopCount&1)===1?duration-time:time;}if(loop===LoopOnce$1){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 var loopDelta=Math.floor(time/duration);// signed time-=duration*loopDelta;loopCount+=Math.abs(loopDelta);var 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 var 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 _setEndings(atStart,atEnd,pingPong){var settings=this._interpolantSettings;if(pingPong){settings.endingStart=ZeroSlopeEnding$1;settings.endingEnd=ZeroSlopeEnding$1;}else{// assuming for LoopOnce atStart == atEnd == true if(atStart){settings.endingStart=this.zeroSlopeAtStart?ZeroSlopeEnding$1:ZeroCurvatureEnding$1;}else{settings.endingStart=WrapAroundEnding$1;}if(atEnd){settings.endingEnd=this.zeroSlopeAtEnd?ZeroSlopeEnding$1:ZeroCurvatureEnding$1;}else{settings.endingEnd=WrapAroundEnding$1;}}},_scheduleFading:function _scheduleFading(duration,weightNow,weightThen){var mixer=this._mixer,now=mixer.time,interpolant=this._weightInterpolant;if(interpolant===null){interpolant=mixer._lendControlInterpolant();this._weightInterpolant=interpolant;}var 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$1(root){this._root=root;this._initMemoryManager();this._accuIndex=0;this.time=0;this.timeScale=1.0;}AnimationMixer$1.prototype=Object.assign(Object.create(EventDispatcher$1.prototype),{constructor:AnimationMixer$1,_bindAction:function _bindAction(action,prototypeAction){var root=action._localRoot||this._root,tracks=action._clip.tracks,nTracks=tracks.length,bindings=action._propertyBindings,interpolants=action._interpolants,rootUuid=root.uuid,bindingsByRoot=this._bindingsByRootAndName,bindingsByName=bindingsByRoot[rootUuid];if(bindingsByName===undefined){bindingsByName={};bindingsByRoot[rootUuid]=bindingsByName;}for(var i=0;i!==nTracks;++i){var track=tracks[i],trackName=track.name,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;}var path=prototypeAction&&prototypeAction._propertyBindings[i].binding.parsedPath;binding=new PropertyMixer$1(PropertyBinding$1.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 _activateAction(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 var 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);}var bindings=action._propertyBindings;// increment reference counts / sort out state for(var i=0,n=bindings.length;i!==n;++i){var binding=bindings[i];if(binding.useCount++===0){this._lendBinding(binding);binding.saveOriginalState();}}this._lendAction(action);}},_deactivateAction:function _deactivateAction(action){if(this._isActiveAction(action)){var bindings=action._propertyBindings;// decrement reference counts / sort out state for(var i=0,n=bindings.length;i!==n;++i){var binding=bindings[i];if(--binding.useCount===0){binding.restoreOriginalState();this._takeBackBinding(binding);}}this._takeBackAction(action);}},// Memory manager _initMemoryManager:function _initMemoryManager(){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;var 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 _isActiveAction(action){var index=action._cacheIndex;return index!==null&&index| inactive actions ] // s a // <-swap-> // a s var 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 _takeBackAction(action){// [ active actions | inactive actions ] // [ active actions |< inactive actions ] // a s // <-swap-> // s a var 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 _addInactiveBinding(binding,rootUuid,trackName){var bindingsByRoot=this._bindingsByRootAndName,bindingByName=bindingsByRoot[rootUuid],bindings=this._bindings;if(bindingByName===undefined){bindingByName={};bindingsByRoot[rootUuid]=bindingByName;}bindingByName[trackName]=binding;binding._cacheIndex=bindings.length;bindings.push(binding);},_removeInactiveBinding:function _removeInactiveBinding(binding){var 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 _lendBinding(binding){var 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 _takeBackBinding(binding){var 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 _lendControlInterpolant(){var interpolants=this._controlInterpolants,lastActiveIndex=this._nActiveControlInterpolants++,interpolant=interpolants[lastActiveIndex];if(interpolant===undefined){interpolant=new LinearInterpolant$1(new Float32Array(2),new Float32Array(2),1,this._controlInterpolantsResultBuffer);interpolant.__cacheIndex=lastActiveIndex;interpolants[lastActiveIndex]=interpolant;}return interpolant;},_takeBackControlInterpolant:function _takeBackControlInterpolant(interpolant){var 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 clipAction(clip,optionalRoot,blendMode){var root=optionalRoot||this._root,rootUuid=root.uuid,clipObject=typeof clip==='string'?AnimationClip$1.findByName(root,clip):clip,clipUuid=clipObject!==null?clipObject.uuid:clip,actionsForClip=this._actionsByClip[clipUuid],prototypeAction=null;if(blendMode===undefined){if(clipObject!==null){blendMode=clipObject.blendMode;}else{blendMode=NormalAnimationBlendMode$1;}}if(actionsForClip!==undefined){var 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 var newAction=new AnimationAction$1(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 existingAction(clip,optionalRoot){var root=optionalRoot||this._root,rootUuid=root.uuid,clipObject=typeof clip==='string'?AnimationClip$1.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 stopAllAction(){var actions=this._actions,nActions=this._nActiveActions;for(var i=nActions-1;i>=0;--i){actions[i].stop();}return this;},// advance the time and update apply the animation update:function update(deltaTime){deltaTime*=this.timeScale;var actions=this._actions,nActions=this._nActiveActions,time=this.time+=deltaTime,timeDirection=Math.sign(deltaTime),accuIndex=this._accuIndex^=1;// run active actions for(var i=0;i!==nActions;++i){var action=actions[i];action._update(time,deltaTime,timeDirection,accuIndex);}// update scene graph var bindings=this._bindings,nBindings=this._nActiveBindings;for(var i=0;i!==nBindings;++i){bindings[i].apply(accuIndex);}return this;},// Allows you to seek to a specific time in an animation. setTime:function setTime(timeInSeconds){this.time=0;// Zero out time attribute for AnimationMixer object; for(var i=0;ithis.max.x||point.ythis.max.y?false:true;},containsBox:function containsBox(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 getParameter(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$1();}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 intersectsBox(box){// using 4 splitting planes to rule out intersections return box.max.xthis.max.x||box.max.ythis.max.y?false:true;},clampPoint:function clampPoint(point,target){if(target===undefined){console.warn('THREE.Box2: .clampPoint() target is now required');target=new Vector2$1();}return target.copy(point).clamp(this.min,this.max);},distanceToPoint:function distanceToPoint(point){var clampedPoint=_vector$7$1.copy(point).clamp(this.min,this.max);return clampedPoint.sub(point).length();},intersect:function intersect(box){this.min.max(box.min);this.max.min(box.max);return this;},union:function union(box){this.min.min(box.min);this.max.max(box.max);return this;},translate:function translate(offset){this.min.add(offset);this.max.add(offset);return this;},equals:function equals(box){return box.min.equals(this.min)&&box.max.equals(this.max);}});/** * @author bhouston / http://clara.io */var _startP$1=new Vector3$1();var _startEnd$1=new Vector3$1();function Line3$1(start,end){this.start=start!==undefined?start:new Vector3$1();this.end=end!==undefined?end:new Vector3$1();}Object.assign(Line3$1.prototype,{set:function set(start,end){this.start.copy(start);this.end.copy(end);return this;},clone:function clone(){return new this.constructor().copy(this);},copy:function copy(line){this.start.copy(line.start);this.end.copy(line.end);return this;},getCenter:function getCenter(target){if(target===undefined){console.warn('THREE.Line3: .getCenter() target is now required');target=new Vector3$1();}return target.addVectors(this.start,this.end).multiplyScalar(0.5);},delta:function delta(target){if(target===undefined){console.warn('THREE.Line3: .delta() target is now required');target=new Vector3$1();}return target.subVectors(this.end,this.start);},distanceSq:function distanceSq(){return this.start.distanceToSquared(this.end);},distance:function distance(){return this.start.distanceTo(this.end);},at:function at(t,target){if(target===undefined){console.warn('THREE.Line3: .at() target is now required');target=new Vector3$1();}return this.delta(target).multiplyScalar(t).add(this.start);},closestPointToPointParameter:function closestPointToPointParameter(point,clampToLine){_startP$1.subVectors(point,this.start);_startEnd$1.subVectors(this.end,this.start);var startEnd2=_startEnd$1.dot(_startEnd$1);var startEnd_startP=_startEnd$1.dot(_startP$1);var t=startEnd_startP/startEnd2;if(clampToLine){t=MathUtils$1.clamp(t,0,1);}return t;},closestPointToPoint:function closestPointToPoint(point,clampToLine,target){var t=this.closestPointToPointParameter(point,clampToLine);if(target===undefined){console.warn('THREE.Line3: .closestPointToPoint() target is now required');target=new Vector3$1();}return this.delta(target).multiplyScalar(t).add(this.start);},applyMatrix4:function applyMatrix4(matrix){this.start.applyMatrix4(matrix);this.end.applyMatrix4(matrix);return this;},equals:function equals(line){return line.start.equals(this.start)&&line.end.equals(this.end);}});/** * @author alteredq / http://alteredqualia.com/ */function ImmediateRenderObject$1(material){Object3D$1.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$1.prototype=Object.create(Object3D$1.prototype);ImmediateRenderObject$1.prototype.constructor=ImmediateRenderObject$1;ImmediateRenderObject$1.prototype.isImmediateRenderObject=true;/** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley */var _vector$8$1=new Vector3$1();function SpotLightHelper$1(light,color){Object3D$1.call(this);this.light=light;this.light.updateMatrixWorld();this.matrix=light.matrixWorld;this.matrixAutoUpdate=false;this.color=color;var geometry=new BufferGeometry$1();var 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(var i=0,j=1,l=32;i0.99999){this.quaternion.set(0,0,0,1);}else if(dir.y<-0.99999){this.quaternion.set(1,0,0,0);}else{_axis$1.set(dir.z,0,-dir.x).normalize();var radians=Math.acos(dir.y);this.quaternion.setFromAxisAngle(_axis$1,radians);}};ArrowHelper$1.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$1.prototype.setColor=function(color){this.line.material.color.set(color);this.cone.material.color.set(color);};ArrowHelper$1.prototype.copy=function(source){Object3D$1.prototype.copy.call(this,source,false);this.line.copy(source.line);this.cone.copy(source.cone);return this;};ArrowHelper$1.prototype.clone=function(){return new this.constructor().copy(this);};/** * @author sroucheray / http://sroucheray.org/ * @author mrdoob / http://mrdoob.com/ */function AxesHelper$1(size){size=size||1;var vertices=[0,0,0,size,0,0,0,0,0,0,size,0,0,0,0,0,0,size];var colors=[1,0,0,1,0.6,0,0,1,0,0.6,1,0,0,0,1,0,0.6,1];var geometry=new BufferGeometry$1();geometry.setAttribute('position',new Float32BufferAttribute$1(vertices,3));geometry.setAttribute('color',new Float32BufferAttribute$1(colors,3));var material=new LineBasicMaterial$1({vertexColors:true,toneMapped:false});LineSegments$1.call(this,geometry,material);this.type='AxesHelper';}AxesHelper$1.prototype=Object.create(LineSegments$1.prototype);AxesHelper$1.prototype.constructor=AxesHelper$1;/** * @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. */var LOD_MIN$1=4;var LOD_MAX$1=8;// 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. var EXTRA_LOD_SIGMA$1=[0.125,0.215,0.35,0.446,0.526,0.582];var TOTAL_LODS$1=LOD_MAX$1-LOD_MIN$1+1+EXTRA_LOD_SIGMA$1.length;var _flatCamera$2=new OrthographicCamera$1();var _createPlanes$=_createPlanes$1(),_lodPlanes$1=_createPlanes$._lodPlanes,_sizeLods$1=_createPlanes$._sizeLods,_sigmas$1=_createPlanes$._sigmas;function _createPlanes$1(){var _lodPlanes=[];var _sizeLods=[];var _sigmas=[];var lod=LOD_MAX$1;for(var i=0;iLOD_MAX$1-LOD_MIN$1){sigma=EXTRA_LOD_SIGMA$1[i-LOD_MAX$1+LOD_MIN$1-1];}else if(i==0){sigma=0;}_sigmas.push(sigma);var texelSize=1.0/(sizeLod-1);var min=-texelSize/2;var max=1+texelSize/2;var uv1=[min,min,max,min,max,max,min,min,max,max,min,max];var cubeFaces=6;var vertices=6;var positionSize=3;var uvSize=2;var faceIndexSize=1;var position=new Float32Array(positionSize*vertices*cubeFaces);var uv=new Float32Array(uvSize*vertices*cubeFaces);var faceIndex=new Float32Array(faceIndexSize*vertices*cubeFaces);for(var face=0;face2?0:-1;var 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);var fill=[face,face,face,face,face,face];faceIndex.set(fill,faceIndexSize*vertices*face);}var planes=new BufferGeometry$1();planes.setAttribute('position',new BufferAttribute$1(position,positionSize));planes.setAttribute('uv',new BufferAttribute$1(uv,uvSize));planes.setAttribute('faceIndex',new BufferAttribute$1(faceIndex,faceIndexSize));_lodPlanes.push(planes);if(lod>LOD_MIN$1){lod--;}}return{_lodPlanes:_lodPlanes,_sizeLods:_sizeLods,_sigmas:_sigmas};}// Curve$1.create=function(construct,getPoint){console.log('THREE.Curve.create() has been deprecated');construct.prototype=Object.create(Curve$1.prototype);construct.prototype.constructor=construct;construct.prototype.getPoint=getPoint;return construct;};// Object.assign(CurvePath$1.prototype,{createPointsGeometry:function createPointsGeometry(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) var pts=this.getPoints(divisions);return this.createGeometry(pts);},createSpacedPointsGeometry:function createSpacedPointsGeometry(divisions){console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');// generate geometry from equidistant sampling along the path var pts=this.getSpacedPoints(divisions);return this.createGeometry(pts);},createGeometry:function createGeometry(points){console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');var geometry=new Geometry$1();for(var i=0,l=points.length;i2&&arguments[2]!==undefined?arguments[2]:null;_classCallCheck(this,ThreeDOMElement);this[_a$g]=getLocallyUniqueId();this[$graft]=graft;this[$sourceObject]=element;this[$correlatedObjects]=correlatedObjects;graft.adopt(this);}/** * The Model of provenance for this scene graph element. */_createClass(ThreeDOMElement,[{key:"mutate",/** * Mutate a property of the scene graph element. Returns a promise that * resolves when the mutation has been successfully applied. */value:function mutate(_property,_value){throw new Error('Mutation not implemented for this element');}/** * Serialize the element in order to share it with a worker context. */},{key:"toJSON",value:function toJSON(){var serialized={id:this[$id]};var name=this.name;if(name!=null){serialized.name=name;}return serialized;}},{key:"ownerModel",get:function get(){return this[$graft].model;}/** * The unique ID that marks this element. In generally, an ID should only be * considered unique to the element in the context of its scene graph. These * IDs are not guaranteed to be stable across script executions. */},{key:"internalID",get:function get(){return this[$id];}/** * Some (but not all) scene graph elements may have an optional name. The * Object3D.prototype.name property is sometimes auto-generated by Three.js. * We only want to expose a name that is set in the source glTF, so Three.js * generated names are ignored. */},{key:"name",get:function get(){return this[$sourceObject].name||null;}/** * The backing Three.js scene graph construct for this element. */},{key:"correlatedObjects",get:function get(){return this[$correlatedObjects];}/** * The canonical GLTF or GLTFElement represented by this facade. */},{key:"sourceObject",get:function get(){return this[$sourceObject];}}]);return ThreeDOMElement;}();_a$g=$id;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */var _a$h;var loader=new ImageLoader$1();var $threeTextures=Symbol('threeTextures');var $bufferViewImages=Symbol('bufferViewImages');/** * Image facade implementation for Three.js textures */var Image=/*#__PURE__*/function(_ThreeDOMElement8){_inherits(Image,_ThreeDOMElement8);var _super39=_createSuper(Image);function Image(graft,image,correlatedTextures){var _this79;_classCallCheck(this,Image);_this79=_super39.call(this,graft,image,correlatedTextures);_this79[_a$h]=new WeakMap();if(image.bufferView!=null){var _iterator23=_createForOfIteratorHelper(correlatedTextures),_step23;try{for(_iterator23.s();!(_step23=_iterator23.n()).done;){var texture=_step23.value;_this79[$bufferViewImages].set(texture,texture.image);}}catch(err){_iterator23.e(err);}finally{_iterator23.f();}}return _this79;}_createClass(Image,[{key:"mutate",value:function(){var _mutate2=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee45(property,value){var image,_iterator24,_step24,texture;return regeneratorRuntime.wrap(function _callee45$(_context46){while(1){switch(_context46.prev=_context46.next){case 0:image=null;if(!(property!=='uri')){_context46.next=3;break;}throw new Error("Cannot configure property \"".concat(property,"\" on Image"));case 3:if(!(value!=null)){_context46.next=7;break;}_context46.next=6;return new Promise(function(resolve,reject){loader.load(value,resolve,undefined,reject);});case 6:image=_context46.sent;case 7:_iterator24=_createForOfIteratorHelper(this[$threeTextures]);try{for(_iterator24.s();!(_step24=_iterator24.n()).done;){texture=_step24.value;// If the URI is set to null but the Image had an associated buffer view // (this would happen if it started out as embedded), then fall back to // the cached object URL created by GLTFLoader: if(image==null&&this.sourceObject.bufferView!=null){texture.image=this[$bufferViewImages].get(texture);}else{texture.image=image;}texture.needsUpdate=true;}}catch(err){_iterator24.e(err);}finally{_iterator24.f();}case 9:case"end":return _context46.stop();}}},_callee45,this);}));function mutate(_x43,_x44){return _mutate2.apply(this,arguments);}return mutate;}()},{key:"toJSON",value:function toJSON(){var serialized=_get(_getPrototypeOf(Image.prototype),"toJSON",this).call(this);var uri=this.sourceObject.uri;if(uri!=null){serialized.uri=uri;}return serialized;}},{key:$threeTextures,get:function get(){return this[$correlatedObjects];}}]);return Image;}(ThreeDOMElement);_a$h=$bufferViewImages;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */var isMinFilter=function(){var minFilterValues=[9728,9729,9984,9985,9986,9987];return function(value){return minFilterValues.indexOf(value)>-1;};}();var isMagFilter=function(){var magFilterValues=[9728,9729];return function(value){return magFilterValues.indexOf(value)>-1;};}();var isWrapMode=function(){var wrapModes=[33071,33648,10497];return function(value){return wrapModes.indexOf(value)>-1;};}();var isValidSamplerValue=function isValidSamplerValue(property,value){switch(property){case'minFilter':return isMinFilter(value);case'magFilter':return isMagFilter(value);case'wrapS':case'wrapT':return isWrapMode(value);default:throw new Error("Cannot configure property \"".concat(property,"\" on Sampler"));}};// These defaults represent a convergence of glTF defaults for wrap mode and // Three.js defaults for filters. Per glTF 2.0 spec, a renderer may choose its // own defaults for filters. // @see https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#reference-sampler // @see https://threejs.org/docs/#api/en/textures/Texture var defaultValues={minFilter:9987,magFilter:9729,wrapS:10497,wrapT:10497};var $threeTextures$1=Symbol('threeTextures');/** * Sampler facade implementation for Three.js textures */var Sampler=/*#__PURE__*/function(_ThreeDOMElement9){_inherits(Sampler,_ThreeDOMElement9);var _super40=_createSuper(Sampler);_createClass(Sampler,[{key:$threeTextures$1,get:function get(){return this[$correlatedObjects];}}]);function Sampler(graft,sampler,correlatedTextures){_classCallCheck(this,Sampler);return _super40.call(this,graft,sampler,correlatedTextures);}_createClass(Sampler,[{key:"mutate",value:function(){var _mutate3=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee46(property,value){var sampler,_iterator25,_step25,texture,_iterator26,_step26,_texture;return regeneratorRuntime.wrap(function _callee46$(_context47){while(1){switch(_context47.prev=_context47.next){case 0:sampler=this.sourceObject;if(value!=null){if(isValidSamplerValue(property,value)){sampler[property]=value;_iterator25=_createForOfIteratorHelper(this[$threeTextures$1]);try{for(_iterator25.s();!(_step25=_iterator25.n()).done;){texture=_step25.value;texture[property]=value;texture.needsUpdate=true;}}catch(err){_iterator25.e(err);}finally{_iterator25.f();}}}else if(property in sampler){delete sampler[property];_iterator26=_createForOfIteratorHelper(this[$threeTextures$1]);try{for(_iterator26.s();!(_step26=_iterator26.n()).done;){_texture=_step26.value;_texture[property]=defaultValues[property];_texture.needsUpdate=true;}}catch(err){_iterator26.e(err);}finally{_iterator26.f();}}case 2:case"end":return _context47.stop();}}},_callee46,this);}));function mutate(_x45,_x46){return _mutate3.apply(this,arguments);}return mutate;}()},{key:"toJSON",value:function toJSON(){var serialized=_get(_getPrototypeOf(Sampler.prototype),"toJSON",this).call(this);var _this$sourceObject=this.sourceObject,minFilter=_this$sourceObject.minFilter,magFilter=_this$sourceObject.magFilter,wrapS=_this$sourceObject.wrapS,wrapT=_this$sourceObject.wrapT;if(minFilter!=null){serialized.minFilter=minFilter;}if(magFilter!=null){serialized.magFilter=magFilter;}if(wrapS!==10497){serialized.wrapS=wrapS;}if(wrapT!==10497){serialized.wrapT=wrapT;}return serialized;}}]);return Sampler;}(ThreeDOMElement);/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */var _a$i,_b$e;var $source=Symbol('source');var $sampler=Symbol('sampler');/** * Material facade implementation for Three.js materials */var Texture$2=/*#__PURE__*/function(_ThreeDOMElement10){_inherits(Texture$2,_ThreeDOMElement10);var _super41=_createSuper(Texture$2);function Texture$2(graft,texture,correlatedTextures){var _this80;_classCallCheck(this,Texture$2);_this80=_super41.call(this,graft,texture,correlatedTextures);_this80[_a$i]=null;_this80[_b$e]=null;var glTF=graft.correlatedSceneGraph.gltf;var samplerIndex=texture.sampler,imageIndex=texture.source;if(samplerIndex!=null){var sampler=glTF.samplers&&glTF.samplers[samplerIndex];if(sampler!=null){_this80[$sampler]=new Sampler(graft,sampler,correlatedTextures);}}if(imageIndex!=null){var image=glTF.images&&glTF.images[imageIndex];if(image!=null){_this80[$source]=new Image(graft,image,correlatedTextures);}}return _this80;}_createClass(Texture$2,[{key:"toJSON",value:function toJSON(){var serialized=_get(_getPrototypeOf(Texture$2.prototype),"toJSON",this).call(this);var sampler=this.sampler,source=this.source;if(sampler!=null){serialized.sampler=sampler.toJSON();}if(source!=null){serialized.source=source.toJSON();}return serialized;}},{key:"sampler",get:function get(){return this[$sampler];}},{key:"source",get:function get(){return this[$source];}}]);return Texture$2;}(ThreeDOMElement);_a$i=$source,_b$e=$sampler;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */var _a$j;var $texture=Symbol('texture');/** * TextureInfo facade implementation for Three.js materials */var TextureInfo=/*#__PURE__*/function(_ThreeDOMElement11){_inherits(TextureInfo,_ThreeDOMElement11);var _super42=_createSuper(TextureInfo);function TextureInfo(graft,textureInfo,correlatedTextures){var _this81;_classCallCheck(this,TextureInfo);_this81=_super42.call(this,graft,textureInfo,correlatedTextures);_this81[_a$j]=null;var glTF=graft.correlatedSceneGraph.gltf;var textureIndex=textureInfo.index;var texture=textureIndex!=null&&glTF.textures!=null?glTF.textures[textureIndex]:null;if(texture!=null){_this81[$texture]=new Texture$2(graft,texture,correlatedTextures);}return _this81;}_createClass(TextureInfo,[{key:"toJSON",value:function toJSON(){var serialized=_get(_getPrototypeOf(TextureInfo.prototype),"toJSON",this).call(this);var texture=this.texture;if(texture!=null){serialized.texture=texture.toJSON();}return serialized;}},{key:"texture",get:function get(){return this[$texture];}}]);return TextureInfo;}(ThreeDOMElement);_a$j=$texture;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */var _a$k,_b$f;var $threeMaterials=Symbol('threeMaterials');var $baseColorTexture=Symbol('baseColorTexture');var $metallicRoughnessTexture=Symbol('metallicRoughnessTexture');/** * PBR material properties facade implementation for Three.js materials */var PBRMetallicRoughness=/*#__PURE__*/function(_ThreeDOMElement12){_inherits(PBRMetallicRoughness,_ThreeDOMElement12);var _super43=_createSuper(PBRMetallicRoughness);function PBRMetallicRoughness(graft,pbrMetallicRoughness,correlatedMaterials){var _this82;_classCallCheck(this,PBRMetallicRoughness);_this82=_super43.call(this,graft,pbrMetallicRoughness,correlatedMaterials);_this82[_a$k]=null;_this82[_b$f]=null;var baseColorTexture=pbrMetallicRoughness.baseColorTexture,metallicRoughnessTexture=pbrMetallicRoughness.metallicRoughnessTexture;var baseColorTextures=new Set();var metallicRoughnessTextures=new Set();var _iterator27=_createForOfIteratorHelper(correlatedMaterials),_step27;try{for(_iterator27.s();!(_step27=_iterator27.n()).done;){var material=_step27.value;if(baseColorTexture!=null&&material.map!=null){baseColorTextures.add(material.map);}// NOTE: GLTFLoader users the same texture for metalnessMap and // roughnessMap in this case // @see https://github.com/mrdoob/three.js/blob/b4473c25816df4a09405c7d887d5c418ef47ee76/examples/js/loaders/GLTFLoader.js#L2173-L2174 if(metallicRoughnessTexture!=null&&material.metalnessMap!=null){metallicRoughnessTextures.add(material.metalnessMap);}}}catch(err){_iterator27.e(err);}finally{_iterator27.f();}if(baseColorTextures.size>0){_this82[$baseColorTexture]=new TextureInfo(graft,baseColorTexture,baseColorTextures);}if(metallicRoughnessTextures.size>0){_this82[$metallicRoughnessTexture]=new TextureInfo(graft,metallicRoughnessTexture,metallicRoughnessTextures);}return _this82;}_createClass(PBRMetallicRoughness,[{key:"mutate",value:function(){var _mutate4=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee47(property,value){var _iterator28,_step28,material,pbrMetallicRoughness,_iterator29,_step29,_material,_pbrMetallicRoughness,_iterator30,_step30,_material2,_pbrMetallicRoughness2;return regeneratorRuntime.wrap(function _callee47$(_context48){while(1){switch(_context48.prev=_context48.next){case 0:if(['baseColorFactor','metallicFactor','roughnessFactor'].includes(property)){_context48.next=2;break;}throw new Error("Cannot mutate ".concat(property," on PBRMetallicRoughness"));case 2:_context48.t0=property;_context48.next=_context48.t0==='baseColorFactor'?5:_context48.t0==='metallicFactor'?8:_context48.t0==='roughnessFactor'?11:14;break;case 5:_iterator28=_createForOfIteratorHelper(this[$threeMaterials]);try{for(_iterator28.s();!(_step28=_iterator28.n()).done;){material=_step28.value;material.color.fromArray(value);material.opacity=value[3];pbrMetallicRoughness=this[$sourceObject];if(value===1&&value===1&&value===1&&value===1){delete pbrMetallicRoughness.baseColorFactor;}else{pbrMetallicRoughness.baseColorFactor=value;}}}catch(err){_iterator28.e(err);}finally{_iterator28.f();}return _context48.abrupt("break",14);case 8:_iterator29=_createForOfIteratorHelper(this[$threeMaterials]);try{for(_iterator29.s();!(_step29=_iterator29.n()).done;){_material=_step29.value;_material.metalness=value;_pbrMetallicRoughness=this[$sourceObject];_pbrMetallicRoughness.metallicFactor=value;}}catch(err){_iterator29.e(err);}finally{_iterator29.f();}return _context48.abrupt("break",14);case 11:_iterator30=_createForOfIteratorHelper(this[$threeMaterials]);try{for(_iterator30.s();!(_step30=_iterator30.n()).done;){_material2=_step30.value;_material2.roughness=value;_pbrMetallicRoughness2=this[$sourceObject];_pbrMetallicRoughness2.roughnessFactor=value;}}catch(err){_iterator30.e(err);}finally{_iterator30.f();}return _context48.abrupt("break",14);case 14:case"end":return _context48.stop();}}},_callee47,this);}));function mutate(_x47,_x48){return _mutate4.apply(this,arguments);}return mutate;}()},{key:"toJSON",value:function toJSON(){var serialized=_get(_getPrototypeOf(PBRMetallicRoughness.prototype),"toJSON",this).call(this);var baseColorTexture=this.baseColorTexture,metallicRoughnessTexture=this.metallicRoughnessTexture,baseColorFactor=this.baseColorFactor,roughnessFactor=this.roughnessFactor,metallicFactor=this.metallicFactor;if(baseColorTexture!=null){serialized.baseColorTexture=baseColorTexture.toJSON();}if(baseColorFactor!=null){serialized.baseColorFactor=baseColorFactor;}if(metallicFactor!=null){serialized.metallicFactor=metallicFactor;}if(roughnessFactor!=null){serialized.roughnessFactor=roughnessFactor;}if(metallicRoughnessTexture!=null){serialized.metallicRoughnessTexture=metallicRoughnessTexture.toJSON();}return serialized;}},{key:(_a$k=$baseColorTexture,_b$f=$metallicRoughnessTexture,$threeMaterials),get:function get(){return this[$correlatedObjects];}},{key:"baseColorFactor",get:function get(){return this.sourceObject.baseColorFactor||[1,1,1,1];}},{key:"metallicFactor",get:function get(){return this.sourceObject.metallicFactor||0;}},{key:"roughnessFactor",get:function get(){return this.sourceObject.roughnessFactor||0;}},{key:"baseColorTexture",get:function get(){return this[$baseColorTexture];}},{key:"metallicRoughnessTexture",get:function get(){return this[$metallicRoughnessTexture];}}]);return PBRMetallicRoughness;}(ThreeDOMElement);/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */var _a$l,_b$g,_c$6,_d$5;var $pbrMetallicRoughness=Symbol('pbrMetallicRoughness');var $normalTexture=Symbol('normalTexture');var $occlusionTexture=Symbol('occlusionTexture');var $emissiveTexture=Symbol('emissiveTexture');/** * Material facade implementation for Three.js materials */var Material$2=/*#__PURE__*/function(_ThreeDOMElement13){_inherits(Material$2,_ThreeDOMElement13);var _super44=_createSuper(Material$2);function Material$2(graft,material,correlatedMaterials){var _this83;_classCallCheck(this,Material$2);_this83=_super44.call(this,graft,material,correlatedMaterials);_this83[_a$l]=null;_this83[_b$g]=null;_this83[_c$6]=null;_this83[_d$5]=null;var pbrMetallicRoughness=material.pbrMetallicRoughness,normalTexture=material.normalTexture,occlusionTexture=material.occlusionTexture,emissiveTexture=material.emissiveTexture;if(pbrMetallicRoughness!=null){_this83[$pbrMetallicRoughness]=new PBRMetallicRoughness(graft,pbrMetallicRoughness,correlatedMaterials);}var normalTextures=new Set();var occlusionTextures=new Set();var emissiveTextures=new Set();var _iterator31=_createForOfIteratorHelper(correlatedMaterials),_step31;try{for(_iterator31.s();!(_step31=_iterator31.n()).done;){var _material3=_step31.value;var normalMap=_material3.normalMap,aoMap=_material3.aoMap,emissiveMap=_material3.emissiveMap;if(normalTexture!=null&&normalMap!=null){normalTextures.add(normalMap);}if(occlusionTexture!=null&&aoMap!=null){occlusionTextures.add(aoMap);}if(emissiveTexture!=null&&emissiveMap!=null){emissiveTextures.add(emissiveMap);}}}catch(err){_iterator31.e(err);}finally{_iterator31.f();}if(normalTextures.size>0){_this83[$normalTexture]=new TextureInfo(graft,normalTexture,normalTextures);}if(occlusionTextures.size>0){_this83[$occlusionTexture]=new TextureInfo(graft,occlusionTexture,occlusionTextures);}if(emissiveTextures.size>0){_this83[$emissiveTexture]=new TextureInfo(graft,emissiveTexture,emissiveTextures);}return _this83;}_createClass(Material$2,[{key:"toJSON",value:function toJSON(){var serialized=_get(_getPrototypeOf(Material$2.prototype),"toJSON",this).call(this);var pbrMetallicRoughness=this.pbrMetallicRoughness,normalTexture=this.normalTexture,occlusionTexture=this.occlusionTexture,emissiveTexture=this.emissiveTexture;if(pbrMetallicRoughness!=null){serialized.pbrMetallicRoughness=pbrMetallicRoughness.toJSON();}if(normalTexture!=null){serialized.normalTexture=normalTexture.toJSON();}if(occlusionTexture!=null){serialized.occlusionTexture=occlusionTexture.toJSON();}if(emissiveTexture!=null){serialized.emissiveTexture=emissiveTexture.toJSON();}return serialized;}},{key:"pbrMetallicRoughness",get:function get(){return this[$pbrMetallicRoughness];}},{key:"normalTexture",get:function get(){return this[$normalTexture];}},{key:"occlusionTexture",get:function get(){return this[$occlusionTexture];}},{key:"emissiveTexture",get:function get(){return this[$emissiveTexture];}}]);return Material$2;}(ThreeDOMElement);_a$l=$pbrMetallicRoughness,_b$g=$normalTexture,_c$6=$occlusionTexture,_d$5=$emissiveTexture;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */var _a$m,_b$h;var $modelUri=Symbol('modelUri');var $materials=Symbol('materials');/** * A Model facades the top-level GLTF object returned by Three.js' GLTFLoader. * Currently, the model only bothers itself with the materials in the Three.js * scene graph. */var Model$1=/*#__PURE__*/function(_ThreeDOMElement14){_inherits(Model$1,_ThreeDOMElement14);var _super45=_createSuper(Model$1);function Model$1(graft,modelUri,correlatedSceneGraph){var _this84;_classCallCheck(this,Model$1);_this84=_super45.call(this,graft,correlatedSceneGraph.gltf);_this84[_a$m]='';_this84[_b$h]=[];_this84[$modelUri]=modelUri;var visitor=new GLTFTreeVisitor({material:function material(_material4){_this84[$materials].push(new Material$2(graft,_material4,correlatedSceneGraph.gltfElementMap.get(_material4)));}});visitor.visit(correlatedSceneGraph.gltf,{sparse:true});return _this84;}/** * A flat list of all unique materials found in this scene graph. Materials * are listed in the order they appear during pre-order, depth-first traveral * of the scene graph. * * TODO(#1003): How do we handle non-active scenes? * TODO(#1002): Desctibe and enforce traversal order */_createClass(Model$1,[{key:"toJSON",value:function toJSON(){var serialized=_get(_getPrototypeOf(Model$1.prototype),"toJSON",this).call(this);serialized.modelUri=this[$modelUri];serialized.materials=this[$materials].map(function(material){return material.toJSON();});return serialized;}},{key:"materials",get:function get(){return this[$materials];}}]);return Model$1;}(ThreeDOMElement);_a$m=$modelUri,_b$h=$materials;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * 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. */var _a$n;var $model=Symbol('model');var $correlatedSceneGraph$1=Symbol('correlatedSceneGraph');var $elementsByInternalId=Symbol('elementsByInternalId');/** * ModelGraft * * This is a coordination primitive between a scene graph as represented by the * output for Three.js' GLTFLoader and a counterpart 3DOM facade. Since this is * the Three.js-specific implementation of the facade, the input is a GLTF-like * object whose keys refer to Three.js-specific constructs (e.g., gltf.scene is * a THREE.Scene). * * When created, the ModelGraft produces a Model that can be traversed and * manipulated to mutate the Three.js scene graph synchronously (but * indirectly). The benefit of this is that mutations to the Three.js scene can * be performed in a Three.js-agnostic fashion that is potentially portable to * alternative rendering backends. * * The scene graph representation produced by the ModelGraft is designed to * match the structures described in the glTF 2.0 spec as closely as possible. * Where there are deviations, it is usually for the purpose of making * synchronization easier, or else for ergonomics. For example, in glTF 2.0, the * graph is a series of flat arrays where nodes cross-reference each other by * index to represent hierarchy, but in a Model nodes have array members * containing refrences to their hierarchical children. * * An important goal of ModelGraft is to enable a scene in one JavaScript * context to be manipulated by script in a remote context, such as a distant * worker thread or even a different process. So, every node in the graph * is able to be serialized, and the serialized form includes an ID that is * locally unique to the ModelGraft instance that the node came from so that * the remote context can refer back to it. A ModelGraft can be thought of as * the host execution context counterpart to the ModelKernel in the scene graph * execution context. */var ModelGraft=/*#__PURE__*/function(_EventTarget2){_inherits(ModelGraft,_EventTarget2);var _super46=_createSuper(ModelGraft);function ModelGraft(modelUri,correlatedSceneGraph){var _this85;_classCallCheck(this,ModelGraft);_this85=_super46.call(this);_this85[_a$n]=new Map();_this85[$correlatedSceneGraph$1]=correlatedSceneGraph;_this85[$model]=new Model$1(_assertThisInitialized(_this85),modelUri,correlatedSceneGraph);return _this85;}_createClass(ModelGraft,[{key:"getElementByInternalId",value:function getElementByInternalId(id){var element=this[$elementsByInternalId].get(id);if(element==null){return null;}return element;}},{key:"adopt",value:function adopt(element){this[$elementsByInternalId].set(element.internalID,element);}},{key:"mutate",value:function(){var _mutate5=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee48(id,property,value){var element;return regeneratorRuntime.wrap(function _callee48$(_context49){while(1){switch(_context49.prev=_context49.next){case 0:// TODO(#1005): Manipulations probably need to be validated against // allowed capabilities here. We already do this on the scene graph // execution context side, but it would be safer to do it on both sides element=this.getElementByInternalId(id);if(!(element!=null)){_context49.next=5;break;}_context49.next=4;return element.mutate(property,value);case 4:this.dispatchEvent(new CustomEvent('mutation',{detail:{element:element}}));case 5:case"end":return _context49.stop();}}},_callee48,this);}));function mutate(_x49,_x50,_x51){return _mutate5.apply(this,arguments);}return mutate;}()},{key:"correlatedSceneGraph",get:function get(){return this[$correlatedSceneGraph$1];}},{key:"model",get:function get(){return this[$model];}}]);return ModelGraft;}(/*#__PURE__*/_wrapNativeSuper(EventTarget));_a$n=$elementsByInternalId;/** * @author fernandojsg / http://fernandojsg.com * @author Don McCurdy / https://www.donmccurdy.com * @author Takahiro / https://github.com/takahirox */ //------------------------------------------------------------------------------ // Constants //------------------------------------------------------------------------------ var WEBGL_CONSTANTS={POINTS:0x0000,LINES:0x0001,LINE_LOOP:0x0002,LINE_STRIP:0x0003,TRIANGLES:0x0004,TRIANGLE_STRIP:0x0005,TRIANGLE_FAN:0x0006,UNSIGNED_BYTE:0x1401,UNSIGNED_SHORT:0x1403,FLOAT:0x1406,UNSIGNED_INT:0x1405,ARRAY_BUFFER:0x8892,ELEMENT_ARRAY_BUFFER:0x8893,NEAREST:0x2600,LINEAR:0x2601,NEAREST_MIPMAP_NEAREST:0x2700,LINEAR_MIPMAP_NEAREST:0x2701,NEAREST_MIPMAP_LINEAR:0x2702,LINEAR_MIPMAP_LINEAR:0x2703,CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497};var THREE_TO_WEBGL={};THREE_TO_WEBGL[NearestFilter]=WEBGL_CONSTANTS.NEAREST;THREE_TO_WEBGL[NearestMipmapNearestFilter]=WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST;THREE_TO_WEBGL[NearestMipmapLinearFilter]=WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR;THREE_TO_WEBGL[LinearFilter]=WEBGL_CONSTANTS.LINEAR;THREE_TO_WEBGL[LinearMipmapNearestFilter]=WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST;THREE_TO_WEBGL[LinearMipmapLinearFilter]=WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR;THREE_TO_WEBGL[ClampToEdgeWrapping]=WEBGL_CONSTANTS.CLAMP_TO_EDGE;THREE_TO_WEBGL[RepeatWrapping]=WEBGL_CONSTANTS.REPEAT;THREE_TO_WEBGL[MirroredRepeatWrapping]=WEBGL_CONSTANTS.MIRRORED_REPEAT;var PATH_PROPERTIES={scale:'scale',position:'translation',quaternion:'rotation',morphTargetInfluences:'weights'};//------------------------------------------------------------------------------ // GLTF Exporter //------------------------------------------------------------------------------ var GLTFExporter=function GLTFExporter(){};GLTFExporter.prototype={constructor:GLTFExporter,/** * Parse scenes and generate GLTF output * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes * @param {Function} onDone Callback on completed * @param {Object} options options */parse:function parse(input,onDone,options){var DEFAULT_OPTIONS={binary:false,trs:false,onlyVisible:true,truncateDrawRange:true,embedImages:true,maxTextureSize:Infinity,animations:[],forcePowerOfTwoTextures:false,includeCustomExtensions:false};options=Object.assign({},DEFAULT_OPTIONS,options);if(options.animations.length>0){// Only TRS properties, and not matrices, may be targeted by animation. options.trs=true;}var outputJSON={asset:{version:"2.0",generator:"GLTFExporter"}};var byteOffset=0;var buffers=[];var pending=[];var nodeMap=new Map();var skins=[];var extensionsUsed={};var cachedData={meshes:new Map(),attributes:new Map(),attributesNormalized:new Map(),materials:new Map(),textures:new Map(),images:new Map()};var cachedCanvas;var uids=new Map();var uid=0;/** * Assign and return a temporal unique id for an object * especially which doesn't have .uuid * @param {Object} object * @return {Integer} */function getUID(object){if(!uids.has(object))uids.set(object,uid++);return uids.get(object);}/** * Compare two arrays * @param {Array} array1 Array 1 to compare * @param {Array} array2 Array 2 to compare * @return {Boolean} Returns true if both arrays are equal */function equalArray(array1,array2){return array1.length===array2.length&&array1.every(function(element,index){return element===array2[index];});}/** * Converts a string to an ArrayBuffer. * @param {string} text * @return {ArrayBuffer} */function stringToArrayBuffer(text){if(window.TextEncoder!==undefined){return new TextEncoder().encode(text).buffer;}var array=new Uint8Array(new ArrayBuffer(text.length));for(var i=0,il=text.length;i0xFF?0x20:value;}return array.buffer;}/** * Get the min and max vectors from the given attribute * @param {BufferAttribute} attribute Attribute to find the min/max in range from start to start + count * @param {Integer} start * @param {Integer} count * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components) */function getMinMax(attribute,start,count){var output={min:new Array(attribute.itemSize).fill(Number.POSITIVE_INFINITY),max:new Array(attribute.itemSize).fill(Number.NEGATIVE_INFINITY)};for(var i=start;i0.0005)return false;}return true;}/** * Creates normalized normal buffer attribute. * * @param {BufferAttribute} normal * @returns {BufferAttribute} * */function createNormalizedNormalAttribute(normal){if(cachedData.attributesNormalized.has(normal)){return cachedData.attributesNormalized.get(normal);}var attribute=normal.clone();var v=new Vector3();for(var i=0,il=attribute.count;i0){gltfProperty.extras=json;}}catch(error){console.warn('THREE.GLTFExporter: userData of \''+object.name+'\' '+'won\'t be serialized because of JSON.stringify error - '+error.message);}}/** * Applies a texture transform, if present, to the map definition. Requires * the KHR_texture_transform extension. */function applyTextureTransform(mapDef,texture){var didTransform=false;var transformDef={};if(texture.offset.x!==0||texture.offset.y!==0){transformDef.offset=texture.offset.toArray();didTransform=true;}if(texture.rotation!==0){transformDef.rotation=texture.rotation;didTransform=true;}if(texture.repeat.x!==1||texture.repeat.y!==1){transformDef.scale=texture.repeat.toArray();didTransform=true;}if(didTransform){mapDef.extensions=mapDef.extensions||{};mapDef.extensions['KHR_texture_transform']=transformDef;extensionsUsed['KHR_texture_transform']=true;}}/** * Process a buffer to append to the default one. * @param {ArrayBuffer} buffer * @return {Integer} */function processBuffer(buffer){if(!outputJSON.buffers){outputJSON.buffers=[{byteLength:0}];}// All buffers are merged before export. buffers.push(buffer);return 0;}/** * Process and generate a BufferView * @param {BufferAttribute} attribute * @param {number} componentType * @param {number} start * @param {number} count * @param {number} target (Optional) Target usage of the BufferView * @return {Object} */function processBufferView(attribute,componentType,start,count,target){if(!outputJSON.bufferViews){outputJSON.bufferViews=[];}// Create a new dataview and dump the attribute's array into it var componentSize;if(componentType===WEBGL_CONSTANTS.UNSIGNED_BYTE){componentSize=1;}else if(componentType===WEBGL_CONSTANTS.UNSIGNED_SHORT){componentSize=2;}else{componentSize=4;}var byteLength=getPaddedBufferSize(count*attribute.itemSize*componentSize);var dataView=new DataView(new ArrayBuffer(byteLength));var offset=0;for(var i=start;i4){// no support for interleaved data for itemSize > 4 value=attribute.array[i*attribute.itemSize+a];}else{if(a===0)value=attribute.getX(i);else if(a===1)value=attribute.getY(i);else if(a===2)value=attribute.getZ(i);else if(a===3)value=attribute.getW(i);}if(componentType===WEBGL_CONSTANTS.FLOAT){dataView.setFloat32(offset,value,true);}else if(componentType===WEBGL_CONSTANTS.UNSIGNED_INT){dataView.setUint32(offset,value,true);}else if(componentType===WEBGL_CONSTANTS.UNSIGNED_SHORT){dataView.setUint16(offset,value,true);}else if(componentType===WEBGL_CONSTANTS.UNSIGNED_BYTE){dataView.setUint8(offset,value);}offset+=componentSize;}}var gltfBufferView={buffer:processBuffer(dataView.buffer),byteOffset:byteOffset,byteLength:byteLength};if(target!==undefined)gltfBufferView.target=target;if(target===WEBGL_CONSTANTS.ARRAY_BUFFER){// Only define byteStride for vertex attributes. gltfBufferView.byteStride=attribute.itemSize*componentSize;}byteOffset+=byteLength;outputJSON.bufferViews.push(gltfBufferView);// @TODO Merge bufferViews where possible. var output={id:outputJSON.bufferViews.length-1,byteLength:0};return output;}/** * Process and generate a BufferView from an image Blob. * @param {Blob} blob * @return {Promise} */function processBufferViewImage(blob){if(!outputJSON.bufferViews){outputJSON.bufferViews=[];}return new Promise(function(resolve){var reader=new window.FileReader();reader.readAsArrayBuffer(blob);reader.onloadend=function(){var buffer=getPaddedArrayBuffer(reader.result);var bufferView={buffer:processBuffer(buffer),byteOffset:byteOffset,byteLength:buffer.byteLength};byteOffset+=buffer.byteLength;outputJSON.bufferViews.push(bufferView);resolve(outputJSON.bufferViews.length-1);};});}/** * Process attribute to generate an accessor * @param {BufferAttribute} attribute Attribute to process * @param {BufferGeometry} geometry (Optional) Geometry used for truncated draw range * @param {Integer} start (Optional) * @param {Integer} count (Optional) * @return {Integer} Index of the processed accessor on the "accessors" array */function processAccessor(attribute,geometry,start,count){var types={1:'SCALAR',2:'VEC2',3:'VEC3',4:'VEC4',16:'MAT4'};var componentType;// Detect the component type of the attribute array (float, uint or ushort) if(attribute.array.constructor===Float32Array){componentType=WEBGL_CONSTANTS.FLOAT;}else if(attribute.array.constructor===Uint32Array){componentType=WEBGL_CONSTANTS.UNSIGNED_INT;}else if(attribute.array.constructor===Uint16Array){componentType=WEBGL_CONSTANTS.UNSIGNED_SHORT;}else if(attribute.array.constructor===Uint8Array){componentType=WEBGL_CONSTANTS.UNSIGNED_BYTE;}else{throw new Error('THREE.GLTFExporter: Unsupported bufferAttribute component type.');}if(start===undefined)start=0;if(count===undefined)count=attribute.count;// @TODO Indexed buffer geometry with drawRange not supported yet if(options.truncateDrawRange&&geometry!==undefined&&geometry.index===null){var end=start+count;var end2=geometry.drawRange.count===Infinity?attribute.count:geometry.drawRange.start+geometry.drawRange.count;start=Math.max(start,geometry.drawRange.start);count=Math.min(end,end2)-start;if(count<0)count=0;}// Skip creating an accessor if the attribute doesn't have data to export if(count===0){return null;}var minMax=getMinMax(attribute,start,count);var bufferViewTarget;// If geometry isn't provided, don't infer the target usage of the bufferView. For // animation samplers, target must not be set. if(geometry!==undefined){bufferViewTarget=attribute===geometry.index?WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER:WEBGL_CONSTANTS.ARRAY_BUFFER;}var bufferView=processBufferView(attribute,componentType,start,count,bufferViewTarget);var gltfAccessor={bufferView:bufferView.id,byteOffset:bufferView.byteOffset,componentType:componentType,count:count,max:minMax.max,min:minMax.min,type:types[attribute.itemSize]};if(attribute.normalized===true){gltfAccessor.normalized=true;}if(!outputJSON.accessors){outputJSON.accessors=[];}outputJSON.accessors.push(gltfAccessor);return outputJSON.accessors.length-1;}/** * Process image * @param {Image} image to process * @param {Integer} format of the image (e.g. THREE.RGBFormat, RGBAFormat etc) * @param {Boolean} flipY before writing out the image * @return {Integer} Index of the processed texture in the "images" array */function processImage(image,format,flipY){if(!cachedData.images.has(image)){cachedData.images.set(image,{});}var cachedImages=cachedData.images.get(image);var mimeType=format===RGBAFormat?'image/png':'image/jpeg';var key=mimeType+":flipY/"+flipY.toString();if(cachedImages[key]!==undefined){return cachedImages[key];}if(!outputJSON.images){outputJSON.images=[];}var gltfImage={mimeType:mimeType};if(options.embedImages){var canvas=cachedCanvas=cachedCanvas||document.createElement('canvas');canvas.width=Math.min(image.width,options.maxTextureSize);canvas.height=Math.min(image.height,options.maxTextureSize);if(options.forcePowerOfTwoTextures&&!isPowerOfTwo(canvas)){console.warn('GLTFExporter: Resized non-power-of-two image.',image);canvas.width=MathUtils.floorPowerOfTwo(canvas.width);canvas.height=MathUtils.floorPowerOfTwo(canvas.height);}var ctx=canvas.getContext('2d');if(flipY===true){ctx.translate(0,canvas.height);ctx.scale(1,-1);}ctx.drawImage(image,0,0,canvas.width,canvas.height);if(options.binary===true){pending.push(new Promise(function(resolve){canvas.toBlob(function(blob){processBufferViewImage(blob).then(function(bufferViewIndex){gltfImage.bufferView=bufferViewIndex;resolve();});},mimeType);}));}else{gltfImage.uri=canvas.toDataURL(mimeType);}}else{gltfImage.uri=image.src;}outputJSON.images.push(gltfImage);var index=outputJSON.images.length-1;cachedImages[key]=index;return index;}/** * Process sampler * @param {Texture} map Texture to process * @return {Integer} Index of the processed texture in the "samplers" array */function processSampler(map){if(!outputJSON.samplers){outputJSON.samplers=[];}var gltfSampler={magFilter:THREE_TO_WEBGL[map.magFilter],minFilter:THREE_TO_WEBGL[map.minFilter],wrapS:THREE_TO_WEBGL[map.wrapS],wrapT:THREE_TO_WEBGL[map.wrapT]};outputJSON.samplers.push(gltfSampler);return outputJSON.samplers.length-1;}/** * Process texture * @param {Texture} map Map to process * @return {Integer} Index of the processed texture in the "textures" array */function processTexture(map){if(cachedData.textures.has(map)){return cachedData.textures.get(map);}if(!outputJSON.textures){outputJSON.textures=[];}var gltfTexture={sampler:processSampler(map),source:processImage(map.image,map.format,map.flipY)};if(map.name){gltfTexture.name=map.name;}outputJSON.textures.push(gltfTexture);var index=outputJSON.textures.length-1;cachedData.textures.set(map,index);return index;}/** * Process material * @param {THREE.Material} material Material to process * @return {Integer} Index of the processed material in the "materials" array */function processMaterial(material){if(cachedData.materials.has(material)){return cachedData.materials.get(material);}if(material.isShaderMaterial){console.warn('GLTFExporter: THREE.ShaderMaterial not supported.');return null;}if(!outputJSON.materials){outputJSON.materials=[];}// @QUESTION Should we avoid including any attribute that has the default value? var gltfMaterial={pbrMetallicRoughness:{}};if(material.isMeshBasicMaterial){gltfMaterial.extensions={KHR_materials_unlit:{}};extensionsUsed['KHR_materials_unlit']=true;}else if(material.isGLTFSpecularGlossinessMaterial){gltfMaterial.extensions={KHR_materials_pbrSpecularGlossiness:{}};extensionsUsed['KHR_materials_pbrSpecularGlossiness']=true;}else if(!material.isMeshStandardMaterial){console.warn('GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.');}// pbrMetallicRoughness.baseColorFactor var color=material.color.toArray().concat([material.opacity]);if(!equalArray(color,[1,1,1,1])){gltfMaterial.pbrMetallicRoughness.baseColorFactor=color;}if(material.isMeshStandardMaterial){gltfMaterial.pbrMetallicRoughness.metallicFactor=material.metalness;gltfMaterial.pbrMetallicRoughness.roughnessFactor=material.roughness;}else if(material.isMeshBasicMaterial){gltfMaterial.pbrMetallicRoughness.metallicFactor=0.0;gltfMaterial.pbrMetallicRoughness.roughnessFactor=0.9;}else{gltfMaterial.pbrMetallicRoughness.metallicFactor=0.5;gltfMaterial.pbrMetallicRoughness.roughnessFactor=0.5;}// pbrSpecularGlossiness diffuse, specular and glossiness factor if(material.isGLTFSpecularGlossinessMaterial){if(gltfMaterial.pbrMetallicRoughness.baseColorFactor){gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.diffuseFactor=gltfMaterial.pbrMetallicRoughness.baseColorFactor;}var specularFactor=[1,1,1];material.specular.toArray(specularFactor,0);gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.specularFactor=specularFactor;gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.glossinessFactor=material.glossiness;}// pbrMetallicRoughness.metallicRoughnessTexture if(material.metalnessMap||material.roughnessMap){if(material.metalnessMap===material.roughnessMap){var metalRoughMapDef={index:processTexture(material.metalnessMap)};applyTextureTransform(metalRoughMapDef,material.metalnessMap);gltfMaterial.pbrMetallicRoughness.metallicRoughnessTexture=metalRoughMapDef;}else{console.warn('THREE.GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.');}}// pbrMetallicRoughness.baseColorTexture or pbrSpecularGlossiness diffuseTexture if(material.map){var baseColorMapDef={index:processTexture(material.map)};applyTextureTransform(baseColorMapDef,material.map);if(material.isGLTFSpecularGlossinessMaterial){gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.diffuseTexture=baseColorMapDef;}gltfMaterial.pbrMetallicRoughness.baseColorTexture=baseColorMapDef;}// pbrSpecularGlossiness specular map if(material.isGLTFSpecularGlossinessMaterial&&material.specularMap){var specularMapDef={index:processTexture(material.specularMap)};applyTextureTransform(specularMapDef,material.specularMap);gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.specularGlossinessTexture=specularMapDef;}if(material.emissive){// emissiveFactor var emissive=material.emissive.clone().multiplyScalar(material.emissiveIntensity).toArray();if(!equalArray(emissive,[0,0,0])){gltfMaterial.emissiveFactor=emissive;}// emissiveTexture if(material.emissiveMap){var emissiveMapDef={index:processTexture(material.emissiveMap)};applyTextureTransform(emissiveMapDef,material.emissiveMap);gltfMaterial.emissiveTexture=emissiveMapDef;}}// normalTexture if(material.normalMap){var normalMapDef={index:processTexture(material.normalMap)};if(material.normalScale&&material.normalScale.x!==-1){if(material.normalScale.x!==material.normalScale.y){console.warn('THREE.GLTFExporter: Normal scale components are different, ignoring Y and exporting X.');}normalMapDef.scale=material.normalScale.x;}applyTextureTransform(normalMapDef,material.normalMap);gltfMaterial.normalTexture=normalMapDef;}// occlusionTexture if(material.aoMap){var occlusionMapDef={index:processTexture(material.aoMap),texCoord:1};if(material.aoMapIntensity!==1.0){occlusionMapDef.strength=material.aoMapIntensity;}applyTextureTransform(occlusionMapDef,material.aoMap);gltfMaterial.occlusionTexture=occlusionMapDef;}// alphaMode if(material.transparent){gltfMaterial.alphaMode='BLEND';}else{if(material.alphaTest>0.0){gltfMaterial.alphaMode='MASK';gltfMaterial.alphaCutoff=material.alphaTest;}}// doubleSided if(material.side===DoubleSide){gltfMaterial.doubleSided=true;}if(material.name!==''){gltfMaterial.name=material.name;}serializeUserData(material,gltfMaterial);outputJSON.materials.push(gltfMaterial);var index=outputJSON.materials.length-1;cachedData.materials.set(material,index);return index;}/** * Process mesh * @param {THREE.Mesh} mesh Mesh to process * @return {Integer} Index of the processed mesh in the "meshes" array */function processMesh(mesh){var meshCacheKeyParts=[mesh.geometry.uuid];if(Array.isArray(mesh.material)){for(var i=0,l=mesh.material.length;i0){var weights=[];var targetNames=[];var reverseDictionary={};if(mesh.morphTargetDictionary!==undefined){for(var key in mesh.morphTargetDictionary){reverseDictionary[mesh.morphTargetDictionary[key]]=key;}}for(var i=0;i0){gltfMesh.extras={};gltfMesh.extras.targetNames=targetNames;}}var isMultiMaterial=Array.isArray(mesh.material);if(isMultiMaterial&&geometry.groups.length===0)return null;var materials=isMultiMaterial?mesh.material:[mesh.material];var groups=isMultiMaterial?geometry.groups:[{materialIndex:0,start:undefined,count:undefined}];for(var i=0,il=groups.length;i0)primitive.targets=targets;if(geometry.index!==null){var cacheKey=getUID(geometry.index);if(groups[i].start!==undefined||groups[i].count!==undefined){cacheKey+=':'+groups[i].start+':'+groups[i].count;}if(cachedData.attributes.has(cacheKey)){primitive.indices=cachedData.attributes.get(cacheKey);}else{primitive.indices=processAccessor(geometry.index,geometry,groups[i].start,groups[i].count);cachedData.attributes.set(cacheKey,primitive.indices);}if(primitive.indices===null)delete primitive.indices;}var material=processMaterial(materials[groups[i].materialIndex]);if(material!==null){primitive.material=material;}primitives.push(primitive);}gltfMesh.primitives=primitives;if(!outputJSON.meshes){outputJSON.meshes=[];}outputJSON.meshes.push(gltfMesh);var index=outputJSON.meshes.length-1;cachedData.meshes.set(meshCacheKey,index);return index;}/** * Process camera * @param {THREE.Camera} camera Camera to process * @return {Integer} Index of the processed mesh in the "camera" array */function processCamera(camera){if(!outputJSON.cameras){outputJSON.cameras=[];}var isOrtho=camera.isOrthographicCamera;var gltfCamera={type:isOrtho?'orthographic':'perspective'};if(isOrtho){gltfCamera.orthographic={xmag:camera.right*2,ymag:camera.top*2,zfar:camera.far<=0?0.001:camera.far,znear:camera.near<0?0:camera.near};}else{gltfCamera.perspective={aspectRatio:camera.aspect,yfov:MathUtils.degToRad(camera.fov),zfar:camera.far<=0?0.001:camera.far,znear:camera.near<0?0:camera.near};}if(camera.name!==''){gltfCamera.name=camera.type;}outputJSON.cameras.push(gltfCamera);return outputJSON.cameras.length-1;}/** * Creates glTF animation entry from AnimationClip object. * * Status: * - Only properties listed in PATH_PROPERTIES may be animated. * * @param {THREE.AnimationClip} clip * @param {THREE.Object3D} root * @return {number} */function processAnimation(clip,root){if(!outputJSON.animations){outputJSON.animations=[];}clip=GLTFExporter.Utils.mergeMorphTargetTracks(clip.clone(),root);var tracks=clip.tracks;var channels=[];var samplers=[];for(var i=0;i0)lightDef.range=light.distance;}else if(light.isSpotLight){lightDef.type='spot';if(light.distance>0)lightDef.range=light.distance;lightDef.spot={};lightDef.spot.innerConeAngle=(light.penumbra-1.0)*light.angle*-1.0;lightDef.spot.outerConeAngle=light.angle;}if(light.decay!==undefined&&light.decay!==2){console.warn('THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, '+'and expects light.decay=2.');}if(light.target&&(light.target.parent!==light||light.target.position.x!==0||light.target.position.y!==0||light.target.position.z!==-1)){console.warn('THREE.GLTFExporter: Light direction may be lost. For best results, '+'make light.target a child of the light with position 0,0,-1.');}var lights=outputJSON.extensions['KHR_lights_punctual'].lights;lights.push(lightDef);return lights.length-1;}/** * Process Object3D node * @param {THREE.Object3D} node Object3D to processNode * @return {Integer} Index of the node in the nodes list */function processNode(object){if(!outputJSON.nodes){outputJSON.nodes=[];}var gltfNode={};if(options.trs){var rotation=object.quaternion.toArray();var position=object.position.toArray();var scale=object.scale.toArray();if(!equalArray(rotation,[0,0,0,1])){gltfNode.rotation=rotation;}if(!equalArray(position,[0,0,0])){gltfNode.translation=position;}if(!equalArray(scale,[1,1,1])){gltfNode.scale=scale;}}else{if(object.matrixAutoUpdate){object.updateMatrix();}if(!equalArray(object.matrix.elements,[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])){gltfNode.matrix=object.matrix.elements;}}// We don't export empty strings name because it represents no-name in Three.js. if(object.name!==''){gltfNode.name=String(object.name);}serializeUserData(object,gltfNode);if(object.isMesh||object.isLine||object.isPoints){var mesh=processMesh(object);if(mesh!==null){gltfNode.mesh=mesh;}}else if(object.isCamera){gltfNode.camera=processCamera(object);}else if(object.isDirectionalLight||object.isPointLight||object.isSpotLight){if(!extensionsUsed['KHR_lights_punctual']){outputJSON.extensions=outputJSON.extensions||{};outputJSON.extensions['KHR_lights_punctual']={lights:[]};extensionsUsed['KHR_lights_punctual']=true;}gltfNode.extensions=gltfNode.extensions||{};gltfNode.extensions['KHR_lights_punctual']={light:processLight(object)};}else if(object.isLight){console.warn('THREE.GLTFExporter: Only directional, point, and spot lights are supported.',object);return null;}if(object.isSkinnedMesh){skins.push(object);}if(object.children.length>0){var children=[];for(var i=0,l=object.children.length;i0){gltfNode.children=children;}}outputJSON.nodes.push(gltfNode);var nodeIndex=outputJSON.nodes.length-1;nodeMap.set(object,nodeIndex);return nodeIndex;}/** * Process Scene * @param {Scene} node Scene to process */function processScene(scene){if(!outputJSON.scenes){outputJSON.scenes=[];outputJSON.scene=0;}var gltfScene={};if(scene.name!==''){gltfScene.name=scene.name;}outputJSON.scenes.push(gltfScene);var nodes=[];for(var i=0,l=scene.children.length;i0){gltfScene.nodes=nodes;}serializeUserData(scene,gltfScene);}/** * Creates a Scene to hold a list of objects and parse it * @param {Array} objects List of objects to process */function processObjects(objects){var scene=new Scene();scene.name='AuxScene';for(var i=0;i0){processObjects(objectsWithoutScene);}for(var i=0;i0)outputJSON.extensionsUsed=extensionsUsedList;// Update bytelength of the single buffer. if(outputJSON.buffers&&outputJSON.buffers.length>0)outputJSON.buffers[0].byteLength=blob.size;if(options.binary===true){// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification var GLB_HEADER_BYTES=12;var GLB_HEADER_MAGIC=0x46546C67;var GLB_VERSION=2;var GLB_CHUNK_PREFIX_BYTES=8;var GLB_CHUNK_TYPE_JSON=0x4E4F534A;var GLB_CHUNK_TYPE_BIN=0x004E4942;var reader=new window.FileReader();reader.readAsArrayBuffer(blob);reader.onloadend=function(){// Binary chunk. var binaryChunk=getPaddedArrayBuffer(reader.result);var binaryChunkPrefix=new DataView(new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES));binaryChunkPrefix.setUint32(0,binaryChunk.byteLength,true);binaryChunkPrefix.setUint32(4,GLB_CHUNK_TYPE_BIN,true);// JSON chunk. var jsonChunk=getPaddedArrayBuffer(stringToArrayBuffer(JSON.stringify(outputJSON)),0x20);var jsonChunkPrefix=new DataView(new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES));jsonChunkPrefix.setUint32(0,jsonChunk.byteLength,true);jsonChunkPrefix.setUint32(4,GLB_CHUNK_TYPE_JSON,true);// GLB header. var header=new ArrayBuffer(GLB_HEADER_BYTES);var headerView=new DataView(header);headerView.setUint32(0,GLB_HEADER_MAGIC,true);headerView.setUint32(4,GLB_VERSION,true);var totalByteLength=GLB_HEADER_BYTES+jsonChunkPrefix.byteLength+jsonChunk.byteLength+binaryChunkPrefix.byteLength+binaryChunk.byteLength;headerView.setUint32(8,totalByteLength,true);var glbBlob=new Blob([header,jsonChunkPrefix,jsonChunk,binaryChunkPrefix,binaryChunk],{type:'application/octet-stream'});var glbReader=new window.FileReader();glbReader.readAsArrayBuffer(glbBlob);glbReader.onloadend=function(){onDone(glbReader.result);};};}else{if(outputJSON.buffers&&outputJSON.buffers.length>0){var reader=new window.FileReader();reader.readAsDataURL(blob);reader.onloadend=function(){var base64data=reader.result;outputJSON.buffers[0].uri=base64data;onDone(outputJSON);};}else{onDone(outputJSON);}}});}};GLTFExporter.Utils={insertKeyframe:function insertKeyframe(track,time){var tolerance=0.001;// 1ms var valueSize=track.getValueSize();var times=new track.TimeBufferType(track.times.length+1);var values=new track.ValueBufferType(track.values.length+valueSize);var interpolant=track.createInterpolant(new track.ValueBufferType(valueSize));var index;if(track.times.length===0){times[0]=time;for(var i=0;itrack.times[track.times.length-1]){if(Math.abs(track.times[track.times.length-1]-time)time){times.set(track.times.slice(0,i+1),0);times[i+1]=time;times.set(track.times.slice(i+1),i+2);values.set(track.values.slice(0,(i+1)*valueSize),0);values.set(interpolant.evaluate(time),(i+1)*valueSize);values.set(track.values.slice((i+1)*valueSize),(i+2)*valueSize);index=i+1;break;}}}track.times=times;track.values=values;return index;},mergeMorphTargetTracks:function mergeMorphTargetTracks(clip,root){var tracks=[];var mergedTracks={};var sourceTracks=clip.tracks;for(var i=0;i=0;i--){if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;}return c>3&&r&&Object.defineProperty(target,key,r),r;};var SCENE_GRAPH_SCRIPT_TYPE='experimental-scene-graph-worklet';var VALID_CAPABILITIES=new Set(['messaging','fetch','material-properties','textures']);var $onChildListMutation=Symbol('onChildListMutation');var $childListMutationHandler=Symbol('childListMutationHandler');var $mutationObserver=Symbol('mutationObserver');var $createExecutionContext=Symbol('createExecutionContext');var $onScriptElementAdded=Symbol('onScriptElementAdded');var $executionContext=Symbol('executionContext');var $updateExecutionContextModel=Symbol('updateExecutionContextModel');var $currentGLTF$1=Symbol('currentGLTF');var $modelGraft$1=Symbol('modelGraft');var $onModelGraftMutation=Symbol('onModelGraftMutation');var $modelGraftMutationHandler=Symbol('modelGraftMutationHandler');var $isValid3DOMScript=Symbol('isValid3DOMScript');var SceneGraphMixin=function SceneGraphMixin(ModelViewerElement){var _a,_b,_c,_d,_e;var _f;var SceneGraphModelViewerElement=/*#__PURE__*/function(_ModelViewerElement7){_inherits(SceneGraphModelViewerElement,_ModelViewerElement7);var _super47=_createSuper(SceneGraphModelViewerElement);function SceneGraphModelViewerElement(){var _this86;_classCallCheck(this,SceneGraphModelViewerElement);_this86=_super47.apply(this,arguments);_this86[_f]=null;_this86[_a]=function(records){return _this86[$onChildListMutation](records);};_this86[_b]=function(event){return _this86[$onModelGraftMutation](event);};_this86[_c]=new MutationObserver(_this86[$childListMutationHandler]);_this86[_d]=null;_this86[_e]=null;return _this86;}_createClass(SceneGraphModelViewerElement,[{key:"connectedCallback",value:function connectedCallback(){_get(_getPrototypeOf(SceneGraphModelViewerElement.prototype),"connectedCallback",this).call(this);this[$mutationObserver].observe(this,{childList:true});var script=this.querySelector("script[type=\"".concat(SCENE_GRAPH_SCRIPT_TYPE,"\"]:last-of-type"));if(script!=null&&this[$isValid3DOMScript](script)){this[$onScriptElementAdded](script);}}},{key:"disconnectedCallback",value:function(){var _disconnectedCallback=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee49(){var executionContext;return regeneratorRuntime.wrap(function _callee49$(_context50){while(1){switch(_context50.prev=_context50.next){case 0:_get(_getPrototypeOf(SceneGraphModelViewerElement.prototype),"disconnectedCallback",this).call(this);this[$mutationObserver].disconnect();executionContext=this[$executionContext];if(!(executionContext!=null)){_context50.next=7;break;}_context50.next=6;return executionContext.terminate();case 6:this[$executionContext]=null;case 7:case"end":return _context50.stop();}}},_callee49,this);}));function disconnectedCallback(){return _disconnectedCallback.apply(this,arguments);}return disconnectedCallback;}()},{key:"updated",value:function updated(changedProperties){_get(_getPrototypeOf(SceneGraphModelViewerElement.prototype),"updated",this).call(this,changedProperties);if(changedProperties.has($modelGraft$1)){var oldModelGraft=changedProperties.get($modelGraft$1);if(oldModelGraft!=null){oldModelGraft.removeEventListener('mutation',this[$modelGraftMutationHandler]);}var modelGraft=this[$modelGraft$1];if(modelGraft!=null){modelGraft.addEventListener('mutation',this[$modelGraftMutationHandler]);}}}},{key:(_f=$modelGraft$1,_a=$childListMutationHandler,_b=$modelGraftMutationHandler,_c=$mutationObserver,_d=$executionContext,_e=$currentGLTF$1,$onModelLoad),value:function value(){_get(_getPrototypeOf(SceneGraphModelViewerElement.prototype),$onModelLoad,this).call(this);this[$updateExecutionContextModel]();}},{key:$isValid3DOMScript,value:function value(node){return _instanceof(node,HTMLScriptElement)&&(node.textContent||node.src)&&node.getAttribute('type')===SCENE_GRAPH_SCRIPT_TYPE;}},{key:$onChildListMutation,value:function value(records){if(this.parentNode==null){return;}var lastScriptElement=null;var _iterator32=_createForOfIteratorHelper(records),_step32;try{for(_iterator32.s();!(_step32=_iterator32.n()).done;){var record=_step32.value;for(var _i23=0,_Array$from=Array.from(record.addedNodes);_i23<_Array$from.length;_i23++){var node=_Array$from[_i23];if(this[$isValid3DOMScript](node)){lastScriptElement=node;}}}}catch(err){_iterator32.e(err);}finally{_iterator32.f();}if(lastScriptElement!=null){this[$onScriptElementAdded](lastScriptElement);}}},{key:$onScriptElementAdded,value:function value(script){if(!this[$isValid3DOMScript](script)){return;}var allowString=script.getAttribute('allow')||'';var allowList=allowString.split(';').map(function(fragment){return fragment.trim();}).filter(function(capability){return VALID_CAPABILITIES.has(capability);});if(script.src){this[$createExecutionContext](script.src,allowList);}else{this[$createExecutionContext](script.textContent,allowList,{eval:true});}}},{key:$createExecutionContext,value:function(){var _value7=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee50(scriptSource,capabilities){var options,executionContext,_args50=arguments;return regeneratorRuntime.wrap(function _callee50$(_context51){while(1){switch(_context51.prev=_context51.next){case 0:options=_args50.length>2&&_args50[2]!==undefined?_args50[2]:{eval:false};executionContext=this[$executionContext];if(!(executionContext!=null)){_context51.next=5;break;}_context51.next=5;return executionContext.terminate();case 5:this[$executionContext]=executionContext=new ThreeDOMExecutionContext(capabilities);this.dispatchEvent(new CustomEvent('worklet-created',{detail:{worklet:this.worklet}}));if(!options.eval){_context51.next=12;break;}_context51.next=10;return executionContext.eval(scriptSource);case 10:_context51.next=14;break;case 12:_context51.next=14;return executionContext.import(scriptSource);case 14:this[$updateExecutionContextModel]();case 15:case"end":return _context51.stop();}}},_callee50,this);}));function value(_x52,_x53){return _value7.apply(this,arguments);}return value;}()},{key:$updateExecutionContextModel,value:function value(){var executionContext=this[$executionContext];if(executionContext==null||this.parentNode==null){return;}var scene=this[$scene];var model=scene.model;var currentGLTF=model.currentGLTF;var modelGraft=null;if(currentGLTF!=null){var correlatedSceneGraph=currentGLTF.correlatedSceneGraph;var currentModelGraft=this[$modelGraft$1];if(correlatedSceneGraph!=null){if(currentModelGraft!=null&¤tGLTF===this[$currentGLTF$1]){return;}modelGraft=new ModelGraft(model.url||'',correlatedSceneGraph);}}executionContext.changeModel(modelGraft);this[$modelGraft$1]=modelGraft;this[$currentGLTF$1]=currentGLTF;}},{key:$onModelGraftMutation,value:function value(_event){this[$needsRender]();}},{key:"exportScene",value:function(){var _exportScene=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee52(options){var model;return regeneratorRuntime.wrap(function _callee52$(_context53){while(1){switch(_context53.prev=_context53.next){case 0:model=this[$scene].model;return _context53.abrupt("return",new Promise(/*#__PURE__*/function(){var _ref10=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee51(resolve,reject){var opts,exporter;return regeneratorRuntime.wrap(function _callee51$(_context52){while(1){switch(_context52.prev=_context52.next){case 0:if(!(model==null)){_context52.next=2;break;}return _context52.abrupt("return",reject('Model missing or not yet loaded'));case 2:opts={animations:model.animations,binary:(options===null||options===void 0?void 0:options.binary)||false,trs:(options===null||options===void 0?void 0:options.trs)||true,onlyVisible:(options===null||options===void 0?void 0:options.onlyVisible)||true,maxTextureSize:(options===null||options===void 0?void 0:options.maxTextureSize)||Infinity,forcePowerOfTwoTextures:(options===null||options===void 0?void 0:options.forcePowerOfTwoTextures)||false,includeCustomExtensions:(options===null||options===void 0?void 0:options.includeCustomExtensions)||false,embedImages:(options===null||options===void 0?void 0:options.embedImages)||true,truncateDrawRange:true};exporter=new GLTFExporter();exporter.parse(model,function(gltf){return resolve(new Blob([opts.binary?gltf:JSON.stringify(gltf)],{type:opts.binary?'application/octet-stream':'application/json'}));},opts);case 5:case"end":return _context52.stop();}}},_callee51);}));return function(_x55,_x56){return _ref10.apply(this,arguments);};}()));case 2:case"end":return _context53.stop();}}},_callee52,this);}));function exportScene(_x54){return _exportScene.apply(this,arguments);}return exportScene;}()},{key:"worklet",get:function get(){var executionContext=this[$executionContext];return executionContext!=null?executionContext.worker:null;}}]);return SceneGraphModelViewerElement;}(ModelViewerElement);__decorate$6([property({type:Object})],SceneGraphModelViewerElement.prototype,_f,void 0);return SceneGraphModelViewerElement;};var __decorate$7=undefined&&undefined.__decorate||function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if((typeof Reflect==="undefined"?"undefined":_typeof(Reflect))==="object"&&typeof undefined==="function")r=undefined(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--){if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;}return c>3&&r&&Object.defineProperty(target,key,r),r;};var ROTATION_SPEED=Math.PI/32;var AUTO_ROTATE_DELAY_DEFAULT=3000;var $autoRotateStartTime=Symbol('autoRotateStartTime');var $cameraChangeHandler=Symbol('cameraChangeHandler');var $onCameraChange=Symbol('onCameraChange');var StagingMixin=function StagingMixin(ModelViewerElement){var _a,_b;var StagingModelViewerElement=/*#__PURE__*/function(_ModelViewerElement8){_inherits(StagingModelViewerElement,_ModelViewerElement8);var _super48=_createSuper(StagingModelViewerElement);function StagingModelViewerElement(){var _this87;_classCallCheck(this,StagingModelViewerElement);_this87=_super48.apply(this,arguments);_this87.autoRotate=false;_this87.autoRotateDelay=AUTO_ROTATE_DELAY_DEFAULT;_this87[_a]=performance.now();_this87[_b]=function(event){return _this87[$onCameraChange](event);};return _this87;}_createClass(StagingModelViewerElement,[{key:"connectedCallback",value:function connectedCallback(){_get(_getPrototypeOf(StagingModelViewerElement.prototype),"connectedCallback",this).call(this);this.addEventListener('camera-change',this[$cameraChangeHandler]);this[$autoRotateStartTime]=performance.now();}},{key:"disconnectedCallback",value:function disconnectedCallback(){_get(_getPrototypeOf(StagingModelViewerElement.prototype),"disconnectedCallback",this).call(this);this.removeEventListener('camera-change',this[$cameraChangeHandler]);this[$autoRotateStartTime]=performance.now();}},{key:"updated",value:function updated(changedProperties){_get(_getPrototypeOf(StagingModelViewerElement.prototype),"updated",this).call(this,changedProperties);if(changedProperties.has('autoRotate')){this[$autoRotateStartTime]=performance.now();}}},{key:(_a=$autoRotateStartTime,_b=$cameraChangeHandler,$tick$1),value:function value(time,delta){_get(_getPrototypeOf(StagingModelViewerElement.prototype),$tick$1,this).call(this,time,delta);if(!this.autoRotate||!this.modelIsVisible||this[$renderer].isPresenting){return;}var rotationDelta=Math.min(delta,time-this[$autoRotateStartTime]-this.autoRotateDelay);if(rotationDelta>0){this[$scene].yaw=this.turntableRotation+ROTATION_SPEED*rotationDelta*0.001;}}},{key:$onCameraChange,value:function value(event){if(!this.autoRotate){return;}if(event.detail.source==='user-interaction'){this[$autoRotateStartTime]=performance.now();}}},{key:"resetTurntableRotation",value:function resetTurntableRotation(){this[$scene].yaw=0;}},{key:"turntableRotation",get:function get(){return this[$scene].yaw;}}]);return StagingModelViewerElement;}(ModelViewerElement);__decorate$7([property({type:Boolean,attribute:'auto-rotate'})],StagingModelViewerElement.prototype,"autoRotate",void 0);__decorate$7([property({type:Number,attribute:'auto-rotate-delay'})],StagingModelViewerElement.prototype,"autoRotateDelay",void 0);return StagingModelViewerElement;};var FocusVisiblePolyfillMixin=function FocusVisiblePolyfillMixin(SuperClass){var _a;var coordinateWithPolyfill=function coordinateWithPolyfill(instance){if(instance.shadowRoot==null||instance.hasAttribute('data-js-focus-visible')){return function(){};}if(self.applyFocusVisiblePolyfill){self.applyFocusVisiblePolyfill(instance.shadowRoot);}else{var coordinationHandler=function coordinationHandler(){self.applyFocusVisiblePolyfill(instance.shadowRoot);};self.addEventListener('focus-visible-polyfill-ready',coordinationHandler,{once:true});return function(){self.removeEventListener('focus-visible-polyfill-ready',coordinationHandler);};}return function(){};};var $endPolyfillCoordination=Symbol('endPolyfillCoordination');var FocusVisibleCoordinator=/*#__PURE__*/function(_SuperClass){_inherits(FocusVisibleCoordinator,_SuperClass);var _super49=_createSuper(FocusVisibleCoordinator);function FocusVisibleCoordinator(){var _this88;_classCallCheck(this,FocusVisibleCoordinator);_this88=_super49.apply(this,arguments);_this88[_a]=null;return _this88;}_createClass(FocusVisibleCoordinator,[{key:"connectedCallback",value:function connectedCallback(){_get(_getPrototypeOf(FocusVisibleCoordinator.prototype),"connectedCallback",this)&&_get(_getPrototypeOf(FocusVisibleCoordinator.prototype),"connectedCallback",this).call(this);if(this[$endPolyfillCoordination]==null){this[$endPolyfillCoordination]=coordinateWithPolyfill(this);}}},{key:"disconnectedCallback",value:function disconnectedCallback(){_get(_getPrototypeOf(FocusVisibleCoordinator.prototype),"disconnectedCallback",this)&&_get(_getPrototypeOf(FocusVisibleCoordinator.prototype),"disconnectedCallback",this).call(this);if(this[$endPolyfillCoordination]!=null){this[$endPolyfillCoordination]();this[$endPolyfillCoordination]=null;}}}]);return FocusVisibleCoordinator;}(SuperClass);_a=$endPolyfillCoordination;return FocusVisibleCoordinator;};var ModelViewerElement=AnnotationMixin(SceneGraphMixin(StagingMixin(EnvironmentMixin(ControlsMixin(ARMixin(LoadingMixin(AnimationMixin(FocusVisiblePolyfillMixin(ModelViewerElementBase)))))))));customElements.define('model-viewer',ModelViewerElement);exports.ModelViewerElement=ModelViewerElement;Object.defineProperty(exports,'__esModule',{value:true});});