7 lines
1.4 MiB
Plaintext
7 lines
1.4 MiB
Plaintext
/**
|
||
* @license
|
||
* PlayCanvas Engine v1.66.3 revision bf0b7c6e9 (RELEASE)
|
||
* Copyright 2011-2023 PlayCanvas Ltd. All rights reserved.
|
||
*/
|
||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).pc={})}(this,(function(t){"use strict";function e(t,e,i){t.prototype[e]||Object.defineProperty(t.prototype,e,{value:i,configurable:!0,enumerable:!1,writable:!0})}e(Array,"fill",(function(t){if(null==this)throw new TypeError("this is null or not defined");for(var e=Object(this),i=e.length>>>0,n=arguments[1]>>0,s=n<0?Math.max(i+n,0):Math.min(n,i),r=arguments[2],a=void 0===r?i:r>>0,o=a<0?Math.max(i+a,0):Math.min(a,i);s<o;)e[s]=t,s++;return e})),e(Array,"find",(function(t){if(null==this)throw TypeError('"this" is null or not defined');var e=Object(this),i=e.length>>>0;if("function"!=typeof t)throw TypeError("predicate must be a function");for(var n=arguments[1],s=0;s<i;){var r=e[s];if(t.call(n,r,s,e))return r;s++}})),e(Array,"findIndex",(function(t){if(null==this)throw new TypeError('"this" is null or not defined');var e=Object(this),i=e.length>>>0;if("function"!=typeof t)throw new TypeError("predicate must be a function");for(var n=arguments[1],s=0;s<i;){var r=e[s];if(t.call(n,r,s,e))return s;s++}return-1})),Math.log2=Math.log2||function(t){return Math.log(t)*Math.LOG2E},Math.sign||(Math.sign=function(t){return(t>0)-(t<0)||+t}),void 0===Number.isFinite&&(Number.isFinite=function(t){return"number"==typeof t&&isFinite(t)}),"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(t,e){if(null==t)throw new TypeError("Cannot convert undefined or null to object");for(var i=Object(t),n=1;n<arguments.length;n++){var s=arguments[n];if(null!=s)for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&(i[r]=s[r])}return i},writable:!0,configurable:!0}),Object.values=Object.values||function(t){return Object.keys(t).map((function(e){return t[e]}))},function(){if("undefined"!=typeof navigator&&"undefined"!=typeof document){navigator.pointer=navigator.pointer||navigator.webkitPointer||navigator.mozPointer;var t=function(){var t=document.createEvent("CustomEvent");t.initCustomEvent("pointerlockchange",!0,!1,null),document.dispatchEvent(t)},e=function(){var t=document.createEvent("CustomEvent");t.initCustomEvent("pointerlockerror",!0,!1,null),document.dispatchEvent(t)};document.addEventListener("webkitpointerlockchange",t,!1),document.addEventListener("webkitpointerlocklost",t,!1),document.addEventListener("mozpointerlockchange",t,!1),document.addEventListener("mozpointerlocklost",t,!1),document.addEventListener("webkitpointerlockerror",e,!1),document.addEventListener("mozpointerlockerror",e,!1),Element.prototype.mozRequestPointerLock?Element.prototype.requestPointerLock=function(){this.mozRequestPointerLock()}:Element.prototype.requestPointerLock=Element.prototype.requestPointerLock||Element.prototype.webkitRequestPointerLock||Element.prototype.mozRequestPointerLock,!Element.prototype.requestPointerLock&&navigator.pointer&&(Element.prototype.requestPointerLock=function(){document.pointerLockElement=this,navigator.pointer.lock(this,t,e)}),document.exitPointerLock=document.exitPointerLock||document.webkitExitPointerLock||document.mozExitPointerLock,document.exitPointerLock||(document.exitPointerLock=function(){navigator.pointer&&(document.pointerLockElement=null,navigator.pointer.unlock())})}}(),e(String,"endsWith",(function(t,e){return(void 0===e||e>this.length)&&(e=this.length),this.substring(e-t.length,e)===t})),e(String,"includes",(function(t,e){return"number"!=typeof e&&(e=0),!(e+t.length>this.length)&&-1!==this.indexOf(t,e)})),e(String,"startsWith",(function(t,e){var i=e>0?0|e:0;return this.substring(i,i+t.length)===t})),e(String,"trimEnd",(function(){return this.replace(new RegExp(/[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/.source+"$","g"),"")}));for(var i=0,n=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array];i<n.length;i++){var s=n[i];e(s,"fill",Array.prototype.fill),e(s,"join",Array.prototype.join)}var r={};function a(t,e){var i;r[t]=!0,void 0!==e&&(i=e,window.console&&window.console.error&&window.console.error(i))}var o=function t(e){var i=e.gl;this.ext=e,this.isAlive=!0,this.hasBeenBound=!1,this.elementArrayBuffer=null,this.attribs=new Array(e.maxVertexAttribs);for(var n=0;n<this.attribs.length;n++){var s=new t.VertexAttrib(i);this.attribs[n]=s}this.maxAttrib=0};(o.VertexAttrib=function(t){this.enabled=!1,this.buffer=null,this.size=4,this.type=t.FLOAT,this.normalized=!1,this.stride=16,this.offset=0,this.cached="",this.recache()}).prototype.recache=function(){this.cached=[this.size,this.type,this.normalized,this.stride,this.offset].join(":")};var h=function(t){var e=this;this.gl=t,function(t){var e=t.getError;t.getError=function(){do{(i=e.apply(t))!=t.NO_ERROR&&(r[i]=!0)}while(i!=t.NO_ERROR);for(var i in r)if(r[i])return delete r[i],parseInt(i);return t.NO_ERROR}}(t);var i=this.original={getParameter:t.getParameter,enableVertexAttribArray:t.enableVertexAttribArray,disableVertexAttribArray:t.disableVertexAttribArray,bindBuffer:t.bindBuffer,getVertexAttrib:t.getVertexAttrib,vertexAttribPointer:t.vertexAttribPointer};t.getParameter=function(t){return t==e.VERTEX_ARRAY_BINDING_OES?e.currentVertexArrayObject==e.defaultVertexArrayObject?null:e.currentVertexArrayObject:i.getParameter.apply(this,arguments)},t.enableVertexAttribArray=function(t){var n=e.currentVertexArrayObject;return n.maxAttrib=Math.max(n.maxAttrib,t),n.attribs[t].enabled=!0,i.enableVertexAttribArray.apply(this,arguments)},t.disableVertexAttribArray=function(t){var n=e.currentVertexArrayObject;return n.maxAttrib=Math.max(n.maxAttrib,t),n.attribs[t].enabled=!1,i.disableVertexAttribArray.apply(this,arguments)},t.bindBuffer=function(n,s){switch(n){case t.ARRAY_BUFFER:e.currentArrayBuffer=s;break;case t.ELEMENT_ARRAY_BUFFER:e.currentVertexArrayObject.elementArrayBuffer=s}return i.bindBuffer.apply(this,arguments)},t.getVertexAttrib=function(n,s){var r=e.currentVertexArrayObject.attribs[n];switch(s){case t.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING:return r.buffer;case t.VERTEX_ATTRIB_ARRAY_ENABLED:return r.enabled;case t.VERTEX_ATTRIB_ARRAY_SIZE:return r.size;case t.VERTEX_ATTRIB_ARRAY_STRIDE:return r.stride;case t.VERTEX_ATTRIB_ARRAY_TYPE:return r.type;case t.VERTEX_ATTRIB_ARRAY_NORMALIZED:return r.normalized;default:return i.getVertexAttrib.apply(this,arguments)}},t.vertexAttribPointer=function(t,n,s,r,a,o){var h=e.currentVertexArrayObject;h.maxAttrib=Math.max(h.maxAttrib,t);var l=h.attribs[t];return l.buffer=e.currentArrayBuffer,l.size=n,l.type=s,l.normalized=r,l.stride=a,l.offset=o,l.recache(),i.vertexAttribPointer.apply(this,arguments)},t.instrumentExtension&&t.instrumentExtension(this,"OES_vertex_array_object"),t.canvas.addEventListener("webglcontextrestored",(function(){var t;t="OESVertexArrayObject emulation library context restored",window.console&&window.console.log&&window.console.log(t),e.reset_()}),!0),this.reset_()};h.prototype.VERTEX_ARRAY_BINDING_OES=34229,h.prototype.reset_=function(){if(void 0!==this.vertexArrayObjects)for(var t=0;t<this.vertexArrayObjects.length;++t)this.vertexArrayObjects.isAlive=!1;var e=this.gl;this.maxVertexAttribs=e.getParameter(e.MAX_VERTEX_ATTRIBS),this.defaultVertexArrayObject=new o(this),this.currentVertexArrayObject=null,this.currentArrayBuffer=null,this.vertexArrayObjects=[this.defaultVertexArrayObject],this.bindVertexArrayOES(null)},h.prototype.createVertexArrayOES=function(){var t=new o(this);return this.vertexArrayObjects.push(t),t},h.prototype.deleteVertexArrayOES=function(t){t.isAlive=!1,this.vertexArrayObjects.splice(this.vertexArrayObjects.indexOf(t),1),this.currentVertexArrayObject==t&&this.bindVertexArrayOES(null)},h.prototype.isVertexArrayOES=function(t){return!!(t&&t instanceof o&&t.hasBeenBound&&t.ext==this)},h.prototype.bindVertexArrayOES=function(t){var e=this.gl;if(!t||t.isAlive){var i=this.original,n=this.currentVertexArrayObject;this.currentVertexArrayObject=t||this.defaultVertexArrayObject,this.currentVertexArrayObject.hasBeenBound=!0;var s=this.currentVertexArrayObject;if(n!=s){n&&s.elementArrayBuffer==n.elementArrayBuffer||i.bindBuffer.call(e,e.ELEMENT_ARRAY_BUFFER,s.elementArrayBuffer);for(var r=this.currentArrayBuffer,o=Math.max(n?n.maxAttrib:0,s.maxAttrib),h=0;h<=o;h++){var l=s.attribs[h],c=n?n.attribs[h]:null;if(n&&l.enabled==c.enabled||(l.enabled?i.enableVertexAttribArray.call(e,h):i.disableVertexAttribArray.call(e,h)),l.enabled){var u=!1;n&&l.buffer==c.buffer||(r!=l.buffer&&(i.bindBuffer.call(e,e.ARRAY_BUFFER,l.buffer),r=l.buffer),u=!0),(u||l.cached!=c.cached)&&i.vertexAttribPointer.call(e,h,l.size,l.type,l.normalized,l.stride,l.offset)}}this.currentArrayBuffer!=r&&i.bindBuffer.call(e,e.ARRAY_BUFFER,this.currentArrayBuffer)}}else a(e.INVALID_OPERATION,"bindVertexArrayOES: attempt to bind deleted arrayObject")};var l="GpuTimings",c="1.66.3",u="bf0b7c6e9",d=function(){for(var t={},e=["Array","Object","Function","Date","RegExp","Float32Array"],i=0;i<e.length;i++)t["[object "+e[i]+"]"]=e[i].toLowerCase();return t}();function f(t){if(null===t)return"null";var e=typeof t;return"undefined"===e||"number"===e||"string"===e||"boolean"===e?e:d[Object.prototype.toString.call(t)]}function p(t,e){for(var i in e){var n=e[i];"object"===f(n)?t[i]=p({},n):"array"===f(n)?t[i]=p([],n):t[i]=n}return t}function m(){m=function(){return e};var t,e={},i=Object.prototype,n=i.hasOwnProperty,s=Object.defineProperty||function(t,e,i){t[e]=i.value},r="function"==typeof Symbol?Symbol:{},a=r.iterator||"@@iterator",o=r.asyncIterator||"@@asyncIterator",h=r.toStringTag||"@@toStringTag";function l(t,e,i){return Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,i){return t[e]=i}}function c(t,e,i,n){var r=e&&e.prototype instanceof g?e:g,a=Object.create(r.prototype),o=new I(n||[]);return s(a,"_invoke",{value:E(t,i,o)}),a}function u(t,e,i){try{return{type:"normal",arg:t.call(e,i)}}catch(t){return{type:"throw",arg:t}}}e.wrap=c;var d="suspendedStart",f="suspendedYield",p="executing",_="completed",v={};function g(){}function y(){}function x(){}var S={};l(S,a,(function(){return this}));var b=Object.getPrototypeOf,w=b&&b(b(L([])));w&&w!==i&&n.call(w,a)&&(S=w);var T=x.prototype=g.prototype=Object.create(S);function A(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function C(t,e){function i(s,r,a,o){var h=u(t[s],t,r);if("throw"!==h.type){var l=h.arg,c=l.value;return c&&"object"==typeof c&&n.call(c,"__await")?e.resolve(c.__await).then((function(t){i("next",t,a,o)}),(function(t){i("throw",t,a,o)})):e.resolve(c).then((function(t){l.value=t,a(l)}),(function(t){return i("throw",t,a,o)}))}o(h.arg)}var r;s(this,"_invoke",{value:function(t,n){function s(){return new e((function(e,s){i(t,n,e,s)}))}return r=r?r.then(s,s):s()}})}function E(e,i,n){var s=d;return function(r,a){if(s===p)throw new Error("Generator is already running");if(s===_){if("throw"===r)throw a;return{value:t,done:!0}}for(n.method=r,n.arg=a;;){var o=n.delegate;if(o){var h=M(o,n);if(h){if(h===v)continue;return h}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(s===d)throw s=_,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);s=p;var l=u(e,i,n);if("normal"===l.type){if(s=n.done?_:f,l.arg===v)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(s=_,n.method="throw",n.arg=l.arg)}}}function M(e,i){var n=i.method,s=e.iterator[n];if(s===t)return i.delegate=null,"throw"===n&&e.iterator.return&&(i.method="return",i.arg=t,M(e,i),"throw"===i.method)||"return"!==n&&(i.method="throw",i.arg=new TypeError("The iterator does not provide a '"+n+"' method")),v;var r=u(s,e.iterator,i.arg);if("throw"===r.type)return i.method="throw",i.arg=r.arg,i.delegate=null,v;var a=r.arg;return a?a.done?(i[e.resultName]=a.value,i.next=e.nextLoc,"return"!==i.method&&(i.method="next",i.arg=t),i.delegate=null,v):a:(i.method="throw",i.arg=new TypeError("iterator result is not an object"),i.delegate=null,v)}function P(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function R(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function I(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(P,this),this.reset(!0)}function L(e){if(e||""===e){var i=e[a];if(i)return i.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var s=-1,r=function i(){for(;++s<e.length;)if(n.call(e,s))return i.value=e[s],i.done=!1,i;return i.value=t,i.done=!0,i};return r.next=r}}throw new TypeError(typeof e+" is not iterable")}return y.prototype=x,s(T,"constructor",{value:x,configurable:!0}),s(x,"constructor",{value:y,configurable:!0}),y.displayName=l(x,h,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===y||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,x):(t.__proto__=x,l(t,h,"GeneratorFunction")),t.prototype=Object.create(T),t},e.awrap=function(t){return{__await:t}},A(C.prototype),l(C.prototype,o,(function(){return this})),e.AsyncIterator=C,e.async=function(t,i,n,s,r){void 0===r&&(r=Promise);var a=new C(c(t,i,n,s),r);return e.isGeneratorFunction(i)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},A(T),l(T,h,"Generator"),l(T,a,(function(){return this})),l(T,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),i=[];for(var n in e)i.push(n);return i.reverse(),function t(){for(;i.length;){var n=i.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=L,I.prototype={constructor:I,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(R),!e)for(var i in this)"t"===i.charAt(0)&&n.call(this,i)&&!isNaN(+i.slice(1))&&(this[i]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var i=this;function s(n,s){return o.type="throw",o.arg=e,i.next=n,s&&(i.method="next",i.arg=t),!!s}for(var r=this.tryEntries.length-1;r>=0;--r){var a=this.tryEntries[r],o=a.completion;if("root"===a.tryLoc)return s("end");if(a.tryLoc<=this.prev){var h=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(h&&l){if(this.prev<a.catchLoc)return s(a.catchLoc,!0);if(this.prev<a.finallyLoc)return s(a.finallyLoc)}else if(h){if(this.prev<a.catchLoc)return s(a.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return s(a.finallyLoc)}}}},abrupt:function(t,e){for(var i=this.tryEntries.length-1;i>=0;--i){var s=this.tryEntries[i];if(s.tryLoc<=this.prev&&n.call(s,"finallyLoc")&&this.prev<s.finallyLoc){var r=s;break}}r&&("break"===t||"continue"===t)&&r.tryLoc<=e&&e<=r.finallyLoc&&(r=null);var a=r?r.completion:{};return a.type=t,a.arg=e,r?(this.method="next",this.next=r.finallyLoc,v):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),v},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var i=this.tryEntries[e];if(i.finallyLoc===t)return this.complete(i.completion,i.afterLoc),R(i),v}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var i=this.tryEntries[e];if(i.tryLoc===t){var n=i.completion;if("throw"===n.type){var s=n.arg;R(i)}return s}}throw new Error("illegal catch attempt")},delegateYield:function(e,i,n){return this.delegate={iterator:L(e),resultName:i,nextLoc:n},"next"===this.method&&(this.arg=t),v}},e}function _(t,e,i,n,s,r,a){try{var o=t[r](a),h=o.value}catch(t){return void i(t)}o.done?e(h):Promise.resolve(h).then(n,s)}function v(t){return function(){var e=this,i=arguments;return new Promise((function(n,s){var r=t.apply(e,i);function a(t){_(r,n,s,a,o,"next",t)}function o(t){_(r,n,s,a,o,"throw",t)}a(void 0)}))}}function g(t,e){for(var i=0;i<e.length;i++){var n=e[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,C(n.key),n)}}function y(t,e,i){return e&&g(t.prototype,e),i&&g(t,i),Object.defineProperty(t,"prototype",{writable:!1}),t}function x(){return x=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(t[n]=i[n])}return t},x.apply(this,arguments)}function S(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,b(t,e)}function b(t,e){return b=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},b(t,e)}function w(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function T(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,n=new Array(e);i<e;i++)n[i]=t[i];return n}function A(t,e){var i="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(i)return(i=i.call(t)).next.bind(i);if(Array.isArray(t)||(i=function(t,e){if(t){if("string"==typeof t)return T(t,e);var i=Object.prototype.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?T(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){i&&(t=i);var n=0;return function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function C(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var n=i.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}var E=function(){function t(){}return t.set=function(t,e){},t.get=function(e){return t._traceChannels.has(e)},t}();E._traceChannels=new Set,E.stack=!1;var M=function(){function t(t,e,i,n,s){void 0===s&&(s=!1),this.handler=void 0,this.name=void 0,this.callback=void 0,this.scope=void 0,this._once=void 0,this._removed=!1,this.handler=t,this.name=e,this.callback=i,this.scope=n,this._once=s}var e=t.prototype;return e.off=function(){this._removed||this.handler.off(this.name,this.callback,this.scope)},e.on=function(t,e,i){return void 0===i&&(i=this),this.handler._addCallback(t,e,i,!1)},e.once=function(t,e,i){return void 0===i&&(i=this),this.handler._addCallback(t,e,i,!0)},y(t,[{key:"removed",get:function(){return this._removed},set:function(t){t&&(this._removed=!0)}}]),t}(),P=function(){function t(){this._callbacks=new Map,this._callbackActive=new Map}var e=t.prototype;return e.initEventHandler=function(){this._callbacks=new Map,this._callbackActive=new Map},e._addCallback=function(t,e,i,n){if(this._callbacks.has(t)||this._callbacks.set(t,[]),this._callbackActive.has(t)){var s=this._callbackActive.get(t);s&&s===this._callbacks.get(t)&&this._callbackActive.set(t,s.slice())}var r=new M(this,t,e,i,n);return this._callbacks.get(t).push(r),r},e.on=function(t,e,i){return void 0===i&&(i=this),this._addCallback(t,e,i,!1)},e.once=function(t,e,i){return void 0===i&&(i=this),this._addCallback(t,e,i,!0)},e.off=function(t,e,i){if(t)this._callbackActive.has(t)&&this._callbackActive.get(t)===this._callbacks.get(t)&&this._callbackActive.set(t,this._callbackActive.get(t).slice());else for(var n,s=A(this._callbackActive);!(n=s()).done;){var r=n.value,a=r[0],o=r[1];this._callbacks.has(a)&&(this._callbacks.get(a)===o&&this._callbackActive.set(a,o.slice()))}if(t)if(e){var h=this._callbacks.get(t);if(!h)return this;for(var l=0;l<h.length;l++)h[l].callback===e&&(i&&h[l].scope!==i||(h[l].removed=!0,h.splice(l,1),l--));0===h.length&&this._callbacks.delete(t)}else{var c=this._callbacks.get(t);if(c){for(var u=0;u<c.length;u++)c[u].removed=!0;this._callbacks.delete(t)}}else{for(var d,f=A(this._callbacks.values());!(d=f()).done;)for(var p=d.value,m=0;m<p.length;m++)p[m].removed=!0;this._callbacks.clear()}return this},e.fire=function(t,e,i,n,s,r,a,o,h){if(!t)return this;var l,c=this._callbacks.get(t);if(!c)return this;this._callbackActive.has(t)?this._callbackActive.get(t)!==c&&(l=c.slice()):this._callbackActive.set(t,c);for(var u=0;(l||this._callbackActive.get(t))&&u<(l||this._callbackActive.get(t)).length;u++){var d=(l||this._callbackActive.get(t))[u];if(d.callback&&(d.callback.call(d.scope,e,i,n,s,r,a,o,h),d._once)){var f=this._callbacks.get(t),p=f?f.indexOf(d):-1;if(-1!==p){this._callbackActive.get(t)===f&&this._callbackActive.set(t,this._callbackActive.get(t).slice());var m=this._callbacks.get(t);if(!m)continue;m[p].removed=!0,m.splice(p,1),0===m.length&&this._callbacks.delete(t)}}}return l||this._callbackActive.delete(t),this},e.hasEvent=function(t){var e;return!(null==(e=this._callbacks.get(t))||!e.length)},t}(),R={attach:function(t){var e=R;return t._addCallback=e._addCallback,t.on=e.on,t.off=e.off,t.fire=e.fire,t.once=e.once,t.hasEvent=e.hasEvent,P.prototype.initEventHandler.call(t),t},_addCallback:P.prototype._addCallback,on:P.prototype.on,off:P.prototype.off,fire:P.prototype.fire,once:P.prototype.once,hasEvent:P.prototype.hasEvent},I={create:function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){var e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)}))}},L={delimiter:"/",join:function(){for(var t=arguments.length,e=arguments[0],i=0;i<t-1;++i){var n=arguments[i],s=arguments[i+1];s[0]!==L.delimiter?n&&s&&n[n.length-1]!==L.delimiter&&s[0]!==L.delimiter?e+=L.delimiter+s:e+=s:e=s}return e},normalize:function(t){for(var e=t.startsWith(L.delimiter),i=t.endsWith(L.delimiter),n=t.split("/"),s="",r=[],a=0;a<n.length;a++)""!==n[a]&&"."!==n[a]&&(".."===n[a]&&r.length>0?r=r.slice(0,r.length-2):(a>0&&r.push(L.delimiter),r.push(n[a])));return s=r.join(""),e||s[0]!==L.delimiter||(s=s.slice(1)),i&&s[s.length-1]!==L.delimiter&&(s+=L.delimiter),s},split:function(t){var e=t.lastIndexOf(L.delimiter);return-1!==e?[t.substring(0,e),t.substring(e+1)]:["",t]},getBasename:function(t){return L.split(t)[1]},getDirectory:function(t){return L.split(t)[0]},getExtension:function(t){var e=t.split("?")[0].split(".").pop();return e!==t?"."+e:""},isRelativePath:function(t){return"/"!==t.charAt(0)&&null===t.match(/:\/\//)},extractPath:function(t){var e="",i=t.split("/"),n=0;if(i.length>1)if(L.isRelativePath(t))if("."===i[0])for(n=0;n<i.length-1;++n)e+=0===n?i[n]:"/"+i[n];else if(".."===i[0])for(n=0;n<i.length-1;++n)e+=0===n?i[n]:"/"+i[n];else for(e=".",n=0;n<i.length-1;++n)e+="/"+i[n];else for(n=0;n<i.length-1;++n)e+=0===n?i[n]:"/"+i[n];return e}},D="undefined"!=typeof navigator?navigator.userAgent:"",O="undefined"!=typeof window?"browser":"node",k=/android/i.test(D)?"android":/ip([ao]d|hone)/i.test(D)?"ios":/windows/i.test(D)?"windows":/mac os/i.test(D)?"osx":/linux/i.test(D)?"linux":/cros/i.test(D)?"cros":null,F="browser"!==O?null:/(Chrome\/|Chromium\/|Edg.*\/)/.test(D)?"chrome":/Safari\//.test(D)?"safari":/Firefox\//.test(D)?"firefox":"other",B=/xbox/i.test(D),U="browser"===O&&("ontouchstart"in window||"maxTouchPoints"in navigator&&navigator.maxTouchPoints>0),N=!("browser"!==O||!navigator.getGamepads&&!navigator.webkitGetGamepads),z="undefined"!=typeof Worker,V=function(){var t=!1;try{var e=Object.defineProperty({},"passive",{get:function(){return t=!0,!1}});window.addEventListener("testpassive",null,e),window.removeEventListener("testpassive",null,e)}catch(t){}return t}(),G={environment:O,global:"browser"===O?window:global,browser:"browser"===O,desktop:["windows","osx","linux","cros"].includes(k),mobile:["android","ios"].includes(k),ios:"ios"===k,android:"android"===k,xbox:B,gamepads:N,touch:U,workers:z,passiveEvents:V,browserName:F},H="abcdefghijklmnopqrstuvwxyz",W="ABCDEFGHIJKLMNOPQRSTUVWXYZ",X=55296,j=56319,q=56320,Y=57343,K=127462,Z=127487,Q=65024,$=65039;function J(t,e){void 0===e&&(e=0);var i=t.length;if(e<0||e>=i)return null;var n=t.charCodeAt(e);if(i>1&&n>=X&&n<=j){var s=t.charCodeAt(e+1);if(s>=q&&s<=Y)return{code:1024*(n-X)+s-q+65536,long:!0}}return{code:n,long:!1}}function tt(t,e,i){if(!t)return!1;var n=J(t);if(n){var s=n.code;return s>=e&&s<=i}return!1}function et(t,e){if(e===t.length-1)return 1;if(tt(t[e],X,j)){var i=t.substring(e,e+2),n=t.substring(e+2,e+4);return tt(n,127995,127999)||tt(i,K,Z)&&tt(n,K,Z)?4:tt(n,Q,$)?3:2}return tt(t[e+1],Q,$)?2:1}var it,nt,st,rt={ASCII_LOWERCASE:H,ASCII_UPPERCASE:W,ASCII_LETTERS:H+W,format:function(t){for(var e=0;e<(arguments.length<=1?0:arguments.length-1);e++)t=t.replace("{"+e+"}",e+1<1||arguments.length<=e+1?void 0:arguments[e+1]);return t},getCodePoint:function(t,e){var i=J(t,e);return i&&i.code},getCodePoints:function(t){if("string"!=typeof t)throw new TypeError("Not a string");for(var e,i=0,n=[];e=J(t,i);)n.push(e.code),i+=e.long?2:1;return n},getSymbols:function(t){if("string"!=typeof t)throw new TypeError("Not a string");for(var e,i=0,n=t.length,s=[],r=0;i<n;)if(tt(e=t[i+(r+=et(t,i+r))],8400,8447)&&(e=t[i+r++]),tt(e,Q,$)&&(e=t[i+r++]),e&&8205===e.charCodeAt(0))e=t[i+r++];else{var a=t.substring(i,i+r);s.push(a),i+=r,r=0}return s},fromCodePoint:function(){for(var t,e,i,n=[],s=0;s<arguments.length;++s)e=(t=Number(arguments[s]))-65536,i=t>65535?[55296+(e>>10),e%1024+56320]:[t],n.push(String.fromCharCode.apply(null,i));return n.join("")}},at=function(){function t(){this._list=[],this._index={}}var e=t.prototype;return e.push=function(t,e){if(this._index[t])throw Error("Key already in index "+t);var i=this._list.push(e)-1;this._index[t]=i},e.has=function(t){return void 0!==this._index[t]},e.get=function(t){var e=this._index[t];return void 0!==e?this._list[e]:null},e.remove=function(t){var e=this._index[t];if(void 0!==e){for(t in this._list.splice(e,1),delete this._index[t],this._index){var i=this._index[t];i>e&&(this._index[t]=i-1)}return!0}return!1},e.list=function(){return this._list},e.clear=function(){for(var t in this._list.length=0,this._index)delete this._index[t]},t}(),ot=function(){function t(){}return t.loadScript=function(t,e){var i=document.createElement("script");i.setAttribute("src",t),i.onload=function(){e(null)},i.onerror=function(){e("Failed to load script='"+t+"'")},document.body.appendChild(i)},t.loadWasm=function(e,i,n){var s=t.wasmSupported()&&i.glueUrl&&i.wasmUrl?i.glueUrl:i.fallbackUrl;s?t.loadScript(s,(function(t){if(t)n(t,null);else{var s=window[e];window[e]=void 0,s({locateFile:function(){return i.wasmUrl},onAbort:function(){n("wasm module aborted.")}}).then((function(t){n(null,t)}))}})):n("No supported wasm modules found.",null)},t.getModule=function(e){return t.modules.hasOwnProperty(e)||(t.modules[e]={config:null,initializing:!1,instance:null,callbacks:[]}),t.modules[e]},t.initialize=function(e,i){if(!i.initializing){var n=i.config;(n.glueUrl||n.wasmUrl||n.fallbackUrl)&&(i.initializing=!0,t.loadWasm(e,n,(function(t,s){t?n.errorHandler?n.errorHandler(t):console.error("failed to initialize module="+e+" error="+t):(i.instance=s,i.callbacks.forEach((function(t){t(s)})))})))}},t}();ot.modules={},ot.wasmSupported=(it=function(){try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){var t=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(t instanceof WebAssembly.Module)return new WebAssembly.Instance(t)instanceof WebAssembly.Instance}}catch(t){}return!1},st=nt={},function(){return st===nt&&(st=it()),st});var ht=function(){function t(){}return t.setConfig=function(t,e){var i=ot.getModule(t);i.config=e,i.callbacks.length>0&&ot.initialize(t,i)},t.getConfig=function(t){var e;return null==(e=ot.modules)||null==(e=e[t])?void 0:e.config},t.getInstance=function(t,e){var i=ot.getModule(t);i.instance?e(i.instance):(i.callbacks.push(e),i.config&&ot.initialize(t,i))},t}(),lt=function(){function t(t){this.arraybuffer=t,this.dataView=new DataView(t),this.offset=0,this.stack=[]}var e=t.prototype;return e.reset=function(t){void 0===t&&(t=0),this.offset=t},e.skip=function(t){this.offset+=t},e.align=function(t){this.offset=this.offset+t-1&~(t-1)},e._inc=function(t){return this.offset+=t,this.offset-t},e.readChar=function(){return String.fromCharCode(this.dataView.getUint8(this.offset++))},e.readChars=function(t){for(var e="",i=0;i<t;++i)e+=this.readChar();return e},e.readU8=function(){return this.dataView.getUint8(this.offset++)},e.readU16=function(){return this.dataView.getUint16(this._inc(2),!0)},e.readU32=function(){return this.dataView.getUint32(this._inc(4),!0)},e.readU64=function(){return this.readU32()+Math.pow(2,32)*this.readU32()},e.readU32be=function(){return this.dataView.getUint32(this._inc(4),!1)},e.readArray=function(t){for(var e=0;e<t.length;++e)t[e]=this.readU8()},e.readLine=function(){for(var t=this.dataView,e="";!(this.offset>=t.byteLength);){var i=String.fromCharCode(this.readU8());if("\n"===i)break;e+=i}return e},y(t,[{key:"remainingBytes",get:function(){return this.dataView.byteLength-this.offset}}]),t}(),ct=function(){function t(t){this.items=[],this.length=0,this.loopIndex=-1,this._sortBy=void 0,this._sortHandler=void 0,this._sortBy=t.sortBy,this._sortHandler=this._doSort.bind(this)}var e=t.prototype;return e._binarySearch=function(t){for(var e,i,n=0,s=this.items.length-1,r=t[this._sortBy];n<=s;)e=Math.floor((n+s)/2),(i=this.items[e][this._sortBy])<=r?n=e+1:i>r&&(s=e-1);return n},e._doSort=function(t,e){var i=this._sortBy;return t[i]-e[i]},e.insert=function(t){var e=this._binarySearch(t);this.items.splice(e,0,t),this.length++,this.loopIndex>=e&&this.loopIndex++},e.append=function(t){this.items.push(t),this.length++},e.remove=function(t){var e=this.items.indexOf(t);e<0||(this.items.splice(e,1),this.length--,this.loopIndex>=e&&this.loopIndex--)},e.sort=function(){var t=this.loopIndex>=0?this.items[this.loopIndex]:null;this.items.sort(this._sortHandler),null!==t&&(this.loopIndex=this.items.indexOf(t))},t}(),ut=function(t){function e(e){var i;return(i=t.call(this)||this)._index={},i._list=[],i._parent=e,i}S(e,t);var i=e.prototype;return i.add=function(){var t=!1,e=this._processArguments(arguments,!0);if(!e.length)return t;for(var i=0;i<e.length;i++)this._index[e[i]]||(t=!0,this._index[e[i]]=!0,this._list.push(e[i]),this.fire("add",e[i],this._parent));return t&&this.fire("change",this._parent),t},i.remove=function(){var t=!1;if(!this._list.length)return t;var e=this._processArguments(arguments,!0);if(!e.length)return t;for(var i=0;i<e.length;i++)this._index[e[i]]&&(t=!0,delete this._index[e[i]],this._list.splice(this._list.indexOf(e[i]),1),this.fire("remove",e[i],this._parent));return t&&this.fire("change",this._parent),t},i.clear=function(){if(this._list.length){var t=this._list.slice(0);this._list=[],this._index={};for(var e=0;e<t.length;e++)this.fire("remove",t[e],this._parent);this.fire("change",this._parent)}},i.has=function(){return!!this._list.length&&this._has(this._processArguments(arguments))},i._has=function(t){if(!this._list.length||!t.length)return!1;for(var e=0;e<t.length;e++)if(1===t[e].length){if(this._index[t[e][0]])return!0}else{for(var i=!0,n=0;n<t[e].length;n++)if(!this._index[t[e][n]]){i=!1;break}if(i)return!0}return!1},i.list=function(){return this._list.slice(0)},i._processArguments=function(t,e){var i=[],n=[];if(!t||!t.length)return i;for(var s=0;s<t.length;s++)if(t[s]instanceof Array){e||(n=[]);for(var r=0;r<t[s].length;r++)"string"==typeof t[s][r]&&(e?i.push(t[s][r]):n.push(t[s][r]));!e&&n.length&&i.push(n)}else"string"==typeof t[s]&&(e?i.push(t[s]):i.push([t[s]]));return i},y(e,[{key:"size",get:function(){return this._list.length}}]),e}(P),dt="undefined"!=typeof window&&window.performance&&window.performance.now?performance.now.bind(performance):Date.now;var ft,pt=/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,mt=function(){function t(t){this.scheme=void 0,this.authority=void 0,this.path=void 0,this.query=void 0,this.fragment=void 0;var e=t.match(pt);this.scheme=e[2],this.authority=e[4],this.path=e[5],this.query=e[7],this.fragment=e[9]}var e=t.prototype;return e.toString=function(){var t="";return this.scheme&&(t+=this.scheme+":"),this.authority&&(t+="//"+this.authority),t+=this.path,this.query&&(t+="?"+this.query),this.fragment&&(t+="#"+this.fragment),t},e.getQuery=function(){var t={};if(this.query)for(var e,i=A(decodeURIComponent(this.query).split("&"));!(e=i()).done;){var n=e.value.split("=");t[n[0]]=n[1]}return t},e.setQuery=function(t){var e="";for(var i in t)t.hasOwnProperty(i)&&(""!==e&&(e+="&"),e+=encodeURIComponent(i)+"="+encodeURIComponent(t[i]));this.query=e},t}(),_t={DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,clamp:function(t,e,i){return t>=i?i:t<=e?e:t},intToBytes24:function(t){return[t>>16&255,t>>8&255,255&t]},intToBytes32:function(t){return[t>>24&255,t>>16&255,t>>8&255,255&t]},bytesToInt24:function(t,e,i){return t.length&&(i=t[2],e=t[1],t=t[0]),t<<16|e<<8|i},bytesToInt32:function(t,e,i,n){return t.length&&(n=t[3],i=t[2],e=t[1],t=t[0]),(t<<24|e<<16|i<<8|n)>>>0},lerp:function(t,e,i){return t+(e-t)*_t.clamp(i,0,1)},lerpAngle:function(t,e,i){return e-t>180&&(e-=360),e-t<-180&&(e+=360),_t.lerp(t,e,_t.clamp(i,0,1))},powerOfTwo:function(t){return 0!==t&&!(t&t-1)},nextPowerOfTwo:function(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,++t},nearestPowerOfTwo:function(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))},random:function(t,e){var i=e-t;return Math.random()*i+t},smoothstep:function(t,e,i){return i<=t?0:i>=e?1:(i=(i-t)/(e-t))*i*(3-2*i)},smootherstep:function(t,e,i){return i<=t?0:i>=e?1:(i=(i-t)/(e-t))*i*i*(i*(6*i-15)+10)},roundUp:function(t,e){return 0===e?t:Math.ceil(t/e)*e},between:function(t,e,i,n){var s=Math.min(e,i),r=Math.max(e,i);return n?t>=s&&t<=r:t>s&&t<r}},vt=function(){function t(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=1),this.r=void 0,this.g=void 0,this.b=void 0,this.a=void 0;var s=t.length;3===s||4===s?(this.r=t[0],this.g=t[1],this.b=t[2],this.a=void 0!==t[3]?t[3]:1):(this.r=t,this.g=e,this.b=i,this.a=n)}var e=t.prototype;return e.clone=function(){return new(0,this.constructor)(this.r,this.g,this.b,this.a)},e.copy=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},e.equals=function(t){return this.r===t.r&&this.g===t.g&&this.b===t.b&&this.a===t.a},e.set=function(t,e,i,n){return void 0===n&&(n=1),this.r=t,this.g=e,this.b=i,this.a=n,this},e.lerp=function(t,e,i){return this.r=t.r+i*(e.r-t.r),this.g=t.g+i*(e.g-t.g),this.b=t.b+i*(e.b-t.b),this.a=t.a+i*(e.a-t.a),this},e.fromString=function(t){var e,i=parseInt(t.replace("#","0x"),16);return t.length>7?e=_t.intToBytes32(i):(e=_t.intToBytes24(i))[3]=255,this.set(e[0]/255,e[1]/255,e[2]/255,e[3]/255),this},e.toString=function(t){var e="#"+((1<<24)+(Math.round(255*this.r)<<16)+(Math.round(255*this.g)<<8)+Math.round(255*this.b)).toString(16).slice(1);if(!0===t){var i=Math.round(255*this.a).toString(16);this.a<16/255?e+="0"+i:e+=i}return e},t}();ft=vt,vt.BLACK=Object.freeze(new ft(0,0,0,1)),vt.BLUE=Object.freeze(new ft(0,0,1,1)),vt.CYAN=Object.freeze(new ft(0,1,1,1)),vt.GRAY=Object.freeze(new ft(.5,.5,.5,1)),vt.GREEN=Object.freeze(new ft(0,1,0,1)),vt.MAGENTA=Object.freeze(new ft(1,0,1,1)),vt.RED=Object.freeze(new ft(1,0,0,1)),vt.WHITE=Object.freeze(new ft(1,1,1,1)),vt.YELLOW=Object.freeze(new ft(1,1,0,1));var gt,yt,xt=function(){function t(t,e){void 0===e&&(e=0),this._curve=void 0,this._left=-1/0,this._right=1/0,this._recip=0,this._p0=0,this._p1=0,this._m0=0,this._m1=0,this._curve=t,this._reset(e)}var e=t.prototype;return e.evaluate=function(t,e){var i;void 0===e&&(e=!1),(e||t<this._left||t>=this._right)&&this._reset(t);var n=this._curve.type;if(5===n)i=this._p0;else{var s=0===this._recip?0:(t-this._left)*this._recip;i=0===n?_t.lerp(this._p0,this._p1,s):1===n?_t.lerp(this._p0,this._p1,s*s*(3-2*s)):this._evaluateHermite(this._p0,this._p1,this._m0,this._m1,s)}return i},e._reset=function(t){var e=this._curve.keys,i=e.length;if(i)if(t<e[0][0])this._left=-1/0,this._right=e[0][0],this._recip=0,this._p0=this._p1=e[0][1],this._m0=this._m1=0;else if(t>=e[i-1][0])this._left=e[i-1][0],this._right=1/0,this._recip=0,this._p0=this._p1=e[i-1][1],this._m0=this._m1=0;else{for(var n=0;t>=e[n+1][0];)n++;this._left=e[n][0],this._right=e[n+1][0];var s=1/(this._right-this._left);this._recip=isFinite(s)?s:0,this._p0=e[n][1],this._p1=e[n+1][1],this._isHermite()&&this._calcTangents(e,n)}else this._left=-1/0,this._right=1/0,this._recip=0,this._p0=this._p1=this._m0=this._m1=0},e._isHermite=function(){return 2===this._curve.type||3===this._curve.type||4===this._curve.type},e._calcTangents=function(t,e){var i,n,s=t[e],r=t[e+1];if(i=0===e?[t[0][0]+(t[0][0]-t[1][0]),t[0][1]+(t[0][1]-t[1][1])]:t[e-1],n=e===t.length-2?[t[e+1][0]+(t[e+1][0]-t[e][0]),t[e+1][1]+(t[e+1][1]-t[e][1])]:t[e+2],4===this._curve.type){var a=2*(r[0]-s[0])/(r[0]-i[0]),o=2*(r[0]-s[0])/(n[0]-s[0]);this._m0=this._curve.tension*(isFinite(a)?a:0)*(r[1]-i[1]),this._m1=this._curve.tension*(isFinite(o)?o:0)*(n[1]-s[1])}else{var h=(r[0]-s[0])/(s[0]-i[0]),l=(r[0]-s[0])/(n[0]-r[0]),c=s[1]+(i[1]-s[1])*(isFinite(h)?h:0),u=r[1]+(n[1]-r[1])*(isFinite(l)?l:0),d=2===this._curve.type?.5:this._curve.tension;this._m0=d*(r[1]-c),this._m1=d*(u-s[1])}},e._evaluateHermite=function(t,e,i,n,s){var r=s*s,a=s+s,o=1-s,h=o*o;return t*((1+a)*h)+i*(s*h)+e*(r*(3-a))+n*(r*(s-1))},t}(),St=function(){function t(t){if(this.keys=[],this.type=1,this.tension=.5,this._eval=new xt(this),t)for(var e=0;e<t.length-1;e+=2)this.keys.push([t[e],t[e+1]]);this.sort()}var e=t.prototype;return e.add=function(t,e){for(var i=this.keys,n=i.length,s=0;s<n&&!(i[s][0]>t);s++);var r=[t,e];return this.keys.splice(s,0,r),r},e.get=function(t){return this.keys[t]},e.sort=function(){this.keys.sort((function(t,e){return t[0]-e[0]}))},e.value=function(t){return this._eval.evaluate(t,!0)},e.closest=function(t){for(var e=this.keys,i=e.length,n=2,s=null,r=0;r<i;r++){var a=Math.abs(t-e[r][0]);if(!(n>=a))break;n=a,s=e[r]}return s},e.clone=function(){var t=new this.constructor;return t.keys=p(t.keys,this.keys),t.type=this.type,t.tension=this.tension,t},e.quantize=function(t){t=Math.max(t,2);var e=new Float32Array(t),i=1/(t-1);e[0]=this._eval.evaluate(0,!0);for(var n=1;n<t;n++)e[n]=this._eval.evaluate(i*n);return e},e.quantizeClamped=function(t,e,i){for(var n=this.quantize(t),s=0;s<n.length;++s)n[s]=Math.min(i,Math.max(e,n[s]));return n},y(t,[{key:"length",get:function(){return this.keys.length}}]),t}(),bt=function(){function t(){if(this.curves=[],this._type=1,arguments.length>1)for(var t=0;t<arguments.length;t++)this.curves.push(new St(arguments[t]));else if(0===arguments.length)this.curves.push(new St);else{var e=arguments[0];if("number"==typeof e)for(var i=0;i<e;i++)this.curves.push(new St);else for(var n=0;n<e.length;n++)this.curves.push(new St(e[n]))}}var e=t.prototype;return e.get=function(t){return this.curves[t]},e.value=function(t,e){void 0===e&&(e=[]);var i=this.curves.length;e.length=i;for(var n=0;n<i;n++)e[n]=this.curves[n].value(t);return e},e.clone=function(){var t=new this.constructor;t.curves=[];for(var e=0;e<this.curves.length;e++)t.curves.push(this.curves[e].clone());return t._type=this._type,t},e.quantize=function(t){t=Math.max(t,2);for(var e=this.curves.length,i=new Float32Array(t*e),n=1/(t-1),s=0;s<e;s++)for(var r=new xt(this.curves[s]),a=0;a<t;a++)i[a*e+s]=r.evaluate(n*a);return i},e.quantizeClamped=function(t,e,i){for(var n=this.quantize(t),s=0;s<n.length;++s)n[s]=Math.min(i,Math.max(e,n[s]));return n},y(t,[{key:"length",get:function(){return this.curves.length}},{key:"type",get:function(){return this._type},set:function(t){this._type=t;for(var e=0;e<this.curves.length;e++)this.curves[e].type=t}}]),t}(),wt=function(){function t(t,e,i){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),this.x=void 0,this.y=void 0,this.z=void 0,3===t.length?(this.x=t[0],this.y=t[1],this.z=t[2]):(this.x=t,this.y=e,this.z=i)}var e=t.prototype;return e.add=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},e.add2=function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this},e.addScalar=function(t){return this.x+=t,this.y+=t,this.z+=t,this},e.addScaled=function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this},e.clone=function(){return new(0,this.constructor)(this.x,this.y,this.z)},e.copy=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},e.cross=function(t,e){var i=t.x,n=t.y,s=t.z,r=e.x,a=e.y,o=e.z;return this.x=n*o-a*s,this.y=s*r-o*i,this.z=i*a-r*n,this},e.distance=function(t){var e=this.x-t.x,i=this.y-t.y,n=this.z-t.z;return Math.sqrt(e*e+i*i+n*n)},e.div=function(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this},e.div2=function(t,e){return this.x=t.x/e.x,this.y=t.y/e.y,this.z=t.z/e.z,this},e.divScalar=function(t){return this.x/=t,this.y/=t,this.z/=t,this},e.dot=function(t){return this.x*t.x+this.y*t.y+this.z*t.z},e.equals=function(t){return this.x===t.x&&this.y===t.y&&this.z===t.z},e.equalsApprox=function(t,e){return void 0===e&&(e=1e-6),Math.abs(this.x-t.x)<e&&Math.abs(this.y-t.y)<e&&Math.abs(this.z-t.z)<e},e.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},e.lengthSq=function(){return this.x*this.x+this.y*this.y+this.z*this.z},e.lerp=function(t,e,i){return this.x=t.x+i*(e.x-t.x),this.y=t.y+i*(e.y-t.y),this.z=t.z+i*(e.z-t.z),this},e.mul=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},e.mul2=function(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this},e.mulScalar=function(t){return this.x*=t,this.y*=t,this.z*=t,this},e.normalize=function(t){void 0===t&&(t=this);var e=t.x*t.x+t.y*t.y+t.z*t.z;if(e>0){var i=1/Math.sqrt(e);this.x=t.x*i,this.y=t.y*i,this.z=t.z*i}return this},e.floor=function(t){return void 0===t&&(t=this),this.x=Math.floor(t.x),this.y=Math.floor(t.y),this.z=Math.floor(t.z),this},e.ceil=function(t){return void 0===t&&(t=this),this.x=Math.ceil(t.x),this.y=Math.ceil(t.y),this.z=Math.ceil(t.z),this},e.round=function(t){return void 0===t&&(t=this),this.x=Math.round(t.x),this.y=Math.round(t.y),this.z=Math.round(t.z),this},e.min=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},e.max=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},e.project=function(t){var e=(this.x*t.x+this.y*t.y+this.z*t.z)/(t.x*t.x+t.y*t.y+t.z*t.z);return this.x=t.x*e,this.y=t.y*e,this.z=t.z*e,this},e.set=function(t,e,i){return this.x=t,this.y=e,this.z=i,this},e.sub=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},e.sub2=function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this},e.subScalar=function(t){return this.x-=t,this.y-=t,this.z-=t,this},e.toString=function(){return"["+this.x+", "+this.y+", "+this.z+"]"},t}();gt=wt,wt.ZERO=Object.freeze(new gt(0,0,0)),wt.ONE=Object.freeze(new gt(1,1,1)),wt.UP=Object.freeze(new gt(0,1,0)),wt.DOWN=Object.freeze(new gt(0,-1,0)),wt.RIGHT=Object.freeze(new gt(1,0,0)),wt.LEFT=Object.freeze(new gt(-1,0,0)),wt.FORWARD=Object.freeze(new gt(0,0,-1)),wt.BACK=Object.freeze(new gt(0,0,1));var Tt,At=function(){function t(){this.data=new Float32Array(9),this.data[0]=this.data[4]=this.data[8]=1}var e=t.prototype;return e.clone=function(){return(new(0,this.constructor)).copy(this)},e.copy=function(t){var e=t.data,i=this.data;return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],this},e.set=function(t){var e=this.data;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],this},e.equals=function(t){var e=this.data,i=t.data;return e[0]===i[0]&&e[1]===i[1]&&e[2]===i[2]&&e[3]===i[3]&&e[4]===i[4]&&e[5]===i[5]&&e[6]===i[6]&&e[7]===i[7]&&e[8]===i[8]},e.isIdentity=function(){var t=this.data;return 1===t[0]&&0===t[1]&&0===t[2]&&0===t[3]&&1===t[4]&&0===t[5]&&0===t[6]&&0===t[7]&&1===t[8]},e.setIdentity=function(){var t=this.data;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,this},e.toString=function(){return"["+this.data.join(", ")+"]"},e.transpose=function(t){void 0===t&&(t=this);var e,i=t.data,n=this.data;i===n?(e=i[1],n[1]=i[3],n[3]=e,e=i[2],n[2]=i[6],n[6]=e,e=i[5],n[5]=i[7],n[7]=e):(n[0]=i[0],n[1]=i[3],n[2]=i[6],n[3]=i[1],n[4]=i[4],n[5]=i[7],n[6]=i[2],n[7]=i[5],n[8]=i[8]);return this},e.setFromMat4=function(t){var e=t.data,i=this.data;return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[4],i[4]=e[5],i[5]=e[6],i[6]=e[8],i[7]=e[9],i[8]=e[10],this},e.invertMat4=function(t){var e=t.data,i=e[0],n=e[1],s=e[2],r=e[4],a=e[5],o=e[6],h=e[8],l=e[9],c=e[10],u=c*a-o*l,d=-c*n+s*l,f=o*n-s*a,p=-c*r+o*h,m=c*i-s*h,_=-o*i+s*r,v=l*r-a*h,g=-l*i+n*h,y=a*i-n*r,x=i*u+n*p+s*v;if(0===x)this.setIdentity();else{var S=1/x,b=this.data;b[0]=u*S,b[1]=d*S,b[2]=f*S,b[3]=p*S,b[4]=m*S,b[5]=_*S,b[6]=v*S,b[7]=g*S,b[8]=y*S}return this},e.transformVector=function(t,e){void 0===e&&(e=new wt);var i=this.data,n=t.x,s=t.y,r=t.z;return e.x=n*i[0]+s*i[3]+r*i[6],e.y=n*i[1]+s*i[4]+r*i[7],e.z=n*i[2]+s*i[5]+r*i[8],e},t}();yt=At,At.IDENTITY=Object.freeze(new yt),At.ZERO=Object.freeze((new yt).set([0,0,0,0,0,0,0,0,0]));var Ct,Et=function(){function t(t,e){void 0===t&&(t=0),void 0===e&&(e=0),this.x=void 0,this.y=void 0,2===t.length?(this.x=t[0],this.y=t[1]):(this.x=t,this.y=e)}var e=t.prototype;return e.add=function(t){return this.x+=t.x,this.y+=t.y,this},e.add2=function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this},e.addScalar=function(t){return this.x+=t,this.y+=t,this},e.addScaled=function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this},e.clone=function(){return new(0,this.constructor)(this.x,this.y)},e.copy=function(t){return this.x=t.x,this.y=t.y,this},e.cross=function(t){return this.x*t.y-this.y*t.x},e.distance=function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},e.div=function(t){return this.x/=t.x,this.y/=t.y,this},e.div2=function(t,e){return this.x=t.x/e.x,this.y=t.y/e.y,this},e.divScalar=function(t){return this.x/=t,this.y/=t,this},e.dot=function(t){return this.x*t.x+this.y*t.y},e.equals=function(t){return this.x===t.x&&this.y===t.y},e.equalsApprox=function(t,e){return void 0===e&&(e=1e-6),Math.abs(this.x-t.x)<e&&Math.abs(this.y-t.y)<e},e.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},e.lengthSq=function(){return this.x*this.x+this.y*this.y},e.lerp=function(t,e,i){return this.x=t.x+i*(e.x-t.x),this.y=t.y+i*(e.y-t.y),this},e.mul=function(t){return this.x*=t.x,this.y*=t.y,this},e.mul2=function(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this},e.mulScalar=function(t){return this.x*=t,this.y*=t,this},e.normalize=function(t){void 0===t&&(t=this);var e=t.x*t.x+t.y*t.y;if(e>0){var i=1/Math.sqrt(e);this.x=t.x*i,this.y=t.y*i}return this},e.rotate=function(t){var e=Math.atan2(this.x,this.y)+t*_t.DEG_TO_RAD,i=Math.sqrt(this.x*this.x+this.y*this.y);return this.x=Math.sin(e)*i,this.y=Math.cos(e)*i,this},e.angle=function(){return Math.atan2(this.x,this.y)*_t.RAD_TO_DEG},e.angleTo=function(t){return Math.atan2(this.x*t.y+this.y*t.x,this.x*t.x+this.y*t.y)*_t.RAD_TO_DEG},e.floor=function(t){return void 0===t&&(t=this),this.x=Math.floor(t.x),this.y=Math.floor(t.y),this},e.ceil=function(t){return void 0===t&&(t=this),this.x=Math.ceil(t.x),this.y=Math.ceil(t.y),this},e.round=function(t){return void 0===t&&(t=this),this.x=Math.round(t.x),this.y=Math.round(t.y),this},e.min=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),this},e.max=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),this},e.set=function(t,e){return this.x=t,this.y=e,this},e.sub=function(t){return this.x-=t.x,this.y-=t.y,this},e.sub2=function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this},e.subScalar=function(t){return this.x-=t,this.y-=t,this},e.toString=function(){return"["+this.x+", "+this.y+"]"},t.angleRad=function(t,e){return Math.atan2(t.x*e.y-t.y*e.x,t.x*e.x+t.y*e.y)},t}();Tt=Et,Et.ZERO=Object.freeze(new Tt(0,0)),Et.ONE=Object.freeze(new Tt(1,1)),Et.UP=Object.freeze(new Tt(0,1)),Et.DOWN=Object.freeze(new Tt(0,-1)),Et.RIGHT=Object.freeze(new Tt(1,0)),Et.LEFT=Object.freeze(new Tt(-1,0));var Mt,Pt=function(){function t(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),this.x=void 0,this.y=void 0,this.z=void 0,this.w=void 0,4===t.length?(this.x=t[0],this.y=t[1],this.z=t[2],this.w=t[3]):(this.x=t,this.y=e,this.z=i,this.w=n)}var e=t.prototype;return e.add=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},e.add2=function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this},e.addScalar=function(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this},e.addScaled=function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this},e.clone=function(){return new(0,this.constructor)(this.x,this.y,this.z,this.w)},e.copy=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},e.div=function(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this.w/=t.w,this},e.div2=function(t,e){return this.x=t.x/e.x,this.y=t.y/e.y,this.z=t.z/e.z,this.w=t.w/e.w,this},e.divScalar=function(t){return this.x/=t,this.y/=t,this.z/=t,this.w/=t,this},e.dot=function(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w},e.equals=function(t){return this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},e.equalsApprox=function(t,e){return void 0===e&&(e=1e-6),Math.abs(this.x-t.x)<e&&Math.abs(this.y-t.y)<e&&Math.abs(this.z-t.z)<e&&Math.abs(this.w-t.w)<e},e.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},e.lengthSq=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},e.lerp=function(t,e,i){return this.x=t.x+i*(e.x-t.x),this.y=t.y+i*(e.y-t.y),this.z=t.z+i*(e.z-t.z),this.w=t.w+i*(e.w-t.w),this},e.mul=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},e.mul2=function(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this.w=t.w*e.w,this},e.mulScalar=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},e.normalize=function(t){void 0===t&&(t=this);var e=t.x*t.x+t.y*t.y+t.z*t.z+t.w*t.w;if(e>0){var i=1/Math.sqrt(e);this.x=t.x*i,this.y=t.y*i,this.z=t.z*i,this.w=t.w*i}return this},e.floor=function(t){return void 0===t&&(t=this),this.x=Math.floor(t.x),this.y=Math.floor(t.y),this.z=Math.floor(t.z),this.w=Math.floor(t.w),this},e.ceil=function(t){return void 0===t&&(t=this),this.x=Math.ceil(t.x),this.y=Math.ceil(t.y),this.z=Math.ceil(t.z),this.w=Math.ceil(t.w),this},e.round=function(t){return void 0===t&&(t=this),this.x=Math.round(t.x),this.y=Math.round(t.y),this.z=Math.round(t.z),this.w=Math.round(t.w),this},e.min=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},e.max=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},e.set=function(t,e,i,n){return this.x=t,this.y=e,this.z=i,this.w=n,this},e.sub=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},e.sub2=function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this},e.subScalar=function(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this},e.toString=function(){return"["+this.x+", "+this.y+", "+this.z+", "+this.w+"]"},t}();Ct=Pt,Pt.ZERO=Object.freeze(new Ct(0,0,0,0)),Pt.ONE=Object.freeze(new Ct(1,1,1,1));var Rt,It=new Et,Lt=new wt,Dt=new wt,Ot=new wt,kt=new wt,Ft=function(){function t(){this.data=new Float32Array(16),this.data[0]=this.data[5]=this.data[10]=this.data[15]=1}t._getPerspectiveHalfSize=function(t,e,i,n,s){s?(t.x=n*Math.tan(e*Math.PI/360),t.y=t.x/i):(t.y=n*Math.tan(e*Math.PI/360),t.x=t.y*i)};var e=t.prototype;return e.add2=function(t,e){var i=t.data,n=e.data,s=this.data;return s[0]=i[0]+n[0],s[1]=i[1]+n[1],s[2]=i[2]+n[2],s[3]=i[3]+n[3],s[4]=i[4]+n[4],s[5]=i[5]+n[5],s[6]=i[6]+n[6],s[7]=i[7]+n[7],s[8]=i[8]+n[8],s[9]=i[9]+n[9],s[10]=i[10]+n[10],s[11]=i[11]+n[11],s[12]=i[12]+n[12],s[13]=i[13]+n[13],s[14]=i[14]+n[14],s[15]=i[15]+n[15],this},e.add=function(t){return this.add2(this,t)},e.clone=function(){return(new(0,this.constructor)).copy(this)},e.copy=function(t){var e=t.data,i=this.data;return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15],this},e.equals=function(t){var e=this.data,i=t.data;return e[0]===i[0]&&e[1]===i[1]&&e[2]===i[2]&&e[3]===i[3]&&e[4]===i[4]&&e[5]===i[5]&&e[6]===i[6]&&e[7]===i[7]&&e[8]===i[8]&&e[9]===i[9]&&e[10]===i[10]&&e[11]===i[11]&&e[12]===i[12]&&e[13]===i[13]&&e[14]===i[14]&&e[15]===i[15]},e.isIdentity=function(){var t=this.data;return 1===t[0]&&0===t[1]&&0===t[2]&&0===t[3]&&0===t[4]&&1===t[5]&&0===t[6]&&0===t[7]&&0===t[8]&&0===t[9]&&1===t[10]&&0===t[11]&&0===t[12]&&0===t[13]&&0===t[14]&&1===t[15]},e.mul2=function(t,e){var i,n,s,r,a=t.data,o=e.data,h=this.data,l=a[0],c=a[1],u=a[2],d=a[3],f=a[4],p=a[5],m=a[6],_=a[7],v=a[8],g=a[9],y=a[10],x=a[11],S=a[12],b=a[13],w=a[14],T=a[15];return i=o[0],n=o[1],s=o[2],r=o[3],h[0]=l*i+f*n+v*s+S*r,h[1]=c*i+p*n+g*s+b*r,h[2]=u*i+m*n+y*s+w*r,h[3]=d*i+_*n+x*s+T*r,i=o[4],n=o[5],s=o[6],r=o[7],h[4]=l*i+f*n+v*s+S*r,h[5]=c*i+p*n+g*s+b*r,h[6]=u*i+m*n+y*s+w*r,h[7]=d*i+_*n+x*s+T*r,i=o[8],n=o[9],s=o[10],r=o[11],h[8]=l*i+f*n+v*s+S*r,h[9]=c*i+p*n+g*s+b*r,h[10]=u*i+m*n+y*s+w*r,h[11]=d*i+_*n+x*s+T*r,i=o[12],n=o[13],s=o[14],r=o[15],h[12]=l*i+f*n+v*s+S*r,h[13]=c*i+p*n+g*s+b*r,h[14]=u*i+m*n+y*s+w*r,h[15]=d*i+_*n+x*s+T*r,this},e.mulAffine2=function(t,e){var i,n,s,r=t.data,a=e.data,o=this.data,h=r[0],l=r[1],c=r[2],u=r[4],d=r[5],f=r[6],p=r[8],m=r[9],_=r[10],v=r[12],g=r[13],y=r[14];return i=a[0],n=a[1],s=a[2],o[0]=h*i+u*n+p*s,o[1]=l*i+d*n+m*s,o[2]=c*i+f*n+_*s,o[3]=0,i=a[4],n=a[5],s=a[6],o[4]=h*i+u*n+p*s,o[5]=l*i+d*n+m*s,o[6]=c*i+f*n+_*s,o[7]=0,i=a[8],n=a[9],s=a[10],o[8]=h*i+u*n+p*s,o[9]=l*i+d*n+m*s,o[10]=c*i+f*n+_*s,o[11]=0,i=a[12],n=a[13],s=a[14],o[12]=h*i+u*n+p*s+v,o[13]=l*i+d*n+m*s+g,o[14]=c*i+f*n+_*s+y,o[15]=1,this},e.mul=function(t){return this.mul2(this,t)},e.transformPoint=function(t,e){void 0===e&&(e=new wt);var i=this.data,n=t.x,s=t.y,r=t.z;return e.x=n*i[0]+s*i[4]+r*i[8]+i[12],e.y=n*i[1]+s*i[5]+r*i[9]+i[13],e.z=n*i[2]+s*i[6]+r*i[10]+i[14],e},e.transformVector=function(t,e){void 0===e&&(e=new wt);var i=this.data,n=t.x,s=t.y,r=t.z;return e.x=n*i[0]+s*i[4]+r*i[8],e.y=n*i[1]+s*i[5]+r*i[9],e.z=n*i[2]+s*i[6]+r*i[10],e},e.transformVec4=function(t,e){void 0===e&&(e=new Pt);var i=this.data,n=t.x,s=t.y,r=t.z,a=t.w;return e.x=n*i[0]+s*i[4]+r*i[8]+a*i[12],e.y=n*i[1]+s*i[5]+r*i[9]+a*i[13],e.z=n*i[2]+s*i[6]+r*i[10]+a*i[14],e.w=n*i[3]+s*i[7]+r*i[11]+a*i[15],e},e.setLookAt=function(t,e,i){Ot.sub2(t,e).normalize(),Dt.copy(i).normalize(),Lt.cross(Dt,Ot).normalize(),Dt.cross(Ot,Lt);var n=this.data;return n[0]=Lt.x,n[1]=Lt.y,n[2]=Lt.z,n[3]=0,n[4]=Dt.x,n[5]=Dt.y,n[6]=Dt.z,n[7]=0,n[8]=Ot.x,n[9]=Ot.y,n[10]=Ot.z,n[11]=0,n[12]=t.x,n[13]=t.y,n[14]=t.z,n[15]=1,this},e.setFrustum=function(t,e,i,n,s,r){var a=2*s,o=e-t,h=n-i,l=r-s,c=this.data;return c[0]=a/o,c[1]=0,c[2]=0,c[3]=0,c[4]=0,c[5]=a/h,c[6]=0,c[7]=0,c[8]=(e+t)/o,c[9]=(n+i)/h,c[10]=(-r-s)/l,c[11]=-1,c[12]=0,c[13]=0,c[14]=-a*r/l,c[15]=0,this},e.setPerspective=function(e,i,n,s,r){return t._getPerspectiveHalfSize(It,e,i,n,r),this.setFrustum(-It.x,It.x,-It.y,It.y,n,s)},e.setOrtho=function(t,e,i,n,s,r){var a=this.data;return a[0]=2/(e-t),a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=2/(n-i),a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=-2/(r-s),a[11]=0,a[12]=-(e+t)/(e-t),a[13]=-(n+i)/(n-i),a[14]=-(r+s)/(r-s),a[15]=1,this},e.setFromAxisAngle=function(t,e){e*=_t.DEG_TO_RAD;var i=t.x,n=t.y,s=t.z,r=Math.cos(e),a=Math.sin(e),o=1-r,h=o*i,l=o*n,c=this.data;return c[0]=h*i+r,c[1]=h*n+a*s,c[2]=h*s-a*n,c[3]=0,c[4]=h*n-a*s,c[5]=l*n+r,c[6]=l*s+a*i,c[7]=0,c[8]=h*s+a*n,c[9]=l*s-i*a,c[10]=o*s*s+r,c[11]=0,c[12]=0,c[13]=0,c[14]=0,c[15]=1,this},e.setTranslate=function(t,e,i){var n=this.data;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=t,n[13]=e,n[14]=i,n[15]=1,this},e.setScale=function(t,e,i){var n=this.data;return n[0]=t,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=e,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=i,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this},e.setViewport=function(t,e,i,n){var s=this.data;return s[0]=.5*i,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=.5*n,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=.5,s[11]=0,s[12]=t+.5*i,s[13]=e+.5*n,s[14]=.5,s[15]=1,this},e.setReflection=function(t,e){var i=t.x,n=t.y,s=t.z,r=this.data;return r[0]=1-2*i*i,r[1]=-2*i*n,r[2]=-2*i*s,r[3]=0,r[4]=-2*i*n,r[5]=1-2*n*n,r[6]=-2*n*s,r[7]=0,r[8]=-2*i*s,r[9]=-2*n*s,r[10]=1-2*s*s,r[11]=0,r[12]=-2*i*e,r[13]=-2*n*e,r[14]=-2*s*e,r[15]=1,this},e.invert=function(t){void 0===t&&(t=this);var e=t.data,i=e[0],n=e[1],s=e[2],r=e[3],a=e[4],o=e[5],h=e[6],l=e[7],c=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],_=e[14],v=e[15],g=i*o-n*a,y=i*h-s*a,x=i*l-r*a,S=n*h-s*o,b=n*l-r*o,w=s*l-r*h,T=c*m-u*p,A=c*_-d*p,C=c*v-f*p,E=u*_-d*m,M=u*v-f*m,P=d*v-f*_,R=g*P-y*M+x*E+S*C-b*A+w*T;if(0===R)this.setIdentity();else{var I=1/R,L=this.data;L[0]=(o*P-h*M+l*E)*I,L[1]=(-n*P+s*M-r*E)*I,L[2]=(m*w-_*b+v*S)*I,L[3]=(-u*w+d*b-f*S)*I,L[4]=(-a*P+h*C-l*A)*I,L[5]=(i*P-s*C+r*A)*I,L[6]=(-p*w+_*x-v*y)*I,L[7]=(c*w-d*x+f*y)*I,L[8]=(a*M-o*C+l*T)*I,L[9]=(-i*M+n*C-r*T)*I,L[10]=(p*b-m*x+v*g)*I,L[11]=(-c*b+u*x-f*g)*I,L[12]=(-a*E+o*A-h*T)*I,L[13]=(i*E-n*A+s*T)*I,L[14]=(-p*S+m*y-_*g)*I,L[15]=(c*S-u*y+d*g)*I}return this},e.set=function(t){var e=this.data;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],this},e.setIdentity=function(){var t=this.data;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this},e.setTRS=function(t,e,i){var n=e.x,s=e.y,r=e.z,a=e.w,o=i.x,h=i.y,l=i.z,c=n+n,u=s+s,d=r+r,f=n*c,p=n*u,m=n*d,_=s*u,v=s*d,g=r*d,y=a*c,x=a*u,S=a*d,b=this.data;return b[0]=(1-(_+g))*o,b[1]=(p+S)*o,b[2]=(m-x)*o,b[3]=0,b[4]=(p-S)*h,b[5]=(1-(f+g))*h,b[6]=(v+y)*h,b[7]=0,b[8]=(m+x)*l,b[9]=(v-y)*l,b[10]=(1-(f+_))*l,b[11]=0,b[12]=t.x,b[13]=t.y,b[14]=t.z,b[15]=1,this},e.transpose=function(t){void 0===t&&(t=this);var e,i=t.data,n=this.data;i===n?(e=i[1],n[1]=i[4],n[4]=e,e=i[2],n[2]=i[8],n[8]=e,e=i[3],n[3]=i[12],n[12]=e,e=i[6],n[6]=i[9],n[9]=e,e=i[7],n[7]=i[13],n[13]=e,e=i[11],n[11]=i[14],n[14]=e):(n[0]=i[0],n[1]=i[4],n[2]=i[8],n[3]=i[12],n[4]=i[1],n[5]=i[5],n[6]=i[9],n[7]=i[13],n[8]=i[2],n[9]=i[6],n[10]=i[10],n[11]=i[14],n[12]=i[3],n[13]=i[7],n[14]=i[11],n[15]=i[15]);return this},e.getTranslation=function(t){return void 0===t&&(t=new wt),t.set(this.data[12],this.data[13],this.data[14])},e.getX=function(t){return void 0===t&&(t=new wt),t.set(this.data[0],this.data[1],this.data[2])},e.getY=function(t){return void 0===t&&(t=new wt),t.set(this.data[4],this.data[5],this.data[6])},e.getZ=function(t){return void 0===t&&(t=new wt),t.set(this.data[8],this.data[9],this.data[10])},e.getScale=function(t){return void 0===t&&(t=new wt),this.getX(Lt),this.getY(Dt),this.getZ(Ot),t.set(Lt.length(),Dt.length(),Ot.length()),t},e.setFromEulerAngles=function(t,e,i){t*=_t.DEG_TO_RAD,e*=_t.DEG_TO_RAD,i*=_t.DEG_TO_RAD;var n=Math.sin(-t),s=Math.cos(-t),r=Math.sin(-e),a=Math.cos(-e),o=Math.sin(-i),h=Math.cos(-i),l=this.data;return l[0]=a*h,l[1]=-a*o,l[2]=r,l[3]=0,l[4]=s*o+h*n*r,l[5]=s*h-n*r*o,l[6]=-a*n,l[7]=0,l[8]=n*o-s*h*r,l[9]=h*n+s*r*o,l[10]=s*a,l[11]=0,l[12]=0,l[13]=0,l[14]=0,l[15]=1,this},e.getEulerAngles=function(t){void 0===t&&(t=new wt),this.getScale(kt);var e=kt.x,i=kt.y,n=kt.z;if(0===e||0===i||0===n)return t.set(0,0,0);var s,r,a=this.data,o=Math.asin(-a[2]/e),h=.5*Math.PI;return o<h?o>-h?(s=Math.atan2(a[6]/i,a[10]/n),r=Math.atan2(a[1]/e,a[0]/e)):(r=0,s=-Math.atan2(a[4]/i,a[5]/i)):(r=0,s=Math.atan2(a[4]/i,a[5]/i)),t.set(s,o,r).mulScalar(_t.RAD_TO_DEG)},e.toString=function(){return"["+this.data.join(", ")+"]"},y(t,[{key:"scaleSign",get:function(){return this.getX(Lt),this.getY(Dt),this.getZ(Ot),Lt.cross(Lt,Dt),Lt.dot(Ot)<0?-1:1}}]),t}();Mt=Ft,Ft.IDENTITY=Object.freeze(new Mt),Ft.ZERO=Object.freeze((new Mt).set([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]));var Bt=function(){function t(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=1),this.x=void 0,this.y=void 0,this.z=void 0,this.w=void 0,4===t.length?(this.x=t[0],this.y=t[1],this.z=t[2],this.w=t[3]):(this.x=t,this.y=e,this.z=i,this.w=n)}var e=t.prototype;return e.clone=function(){return new(0,this.constructor)(this.x,this.y,this.z,this.w)},e.conjugate=function(t){return void 0===t&&(t=this),this.x=-1*t.x,this.y=-1*t.y,this.z=-1*t.z,this.w=t.w,this},e.copy=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},e.equals=function(t){return this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},e.equalsApprox=function(t,e){return void 0===e&&(e=1e-6),Math.abs(this.x-t.x)<e&&Math.abs(this.y-t.y)<e&&Math.abs(this.z-t.z)<e&&Math.abs(this.w-t.w)<e},e.getAxisAngle=function(t){var e=2*Math.acos(this.w),i=Math.sin(e/2);return 0!==i?(t.x=this.x/i,t.y=this.y/i,t.z=this.z/i,(t.x<0||t.y<0||t.z<0)&&(t.x*=-1,t.y*=-1,t.z*=-1,e*=-1)):(t.x=1,t.y=0,t.z=0),e*_t.RAD_TO_DEG},e.getEulerAngles=function(t){var e,i,n;void 0===t&&(t=new wt);var s=this.x,r=this.y,a=this.z,o=this.w,h=2*(o*r-s*a);return h<=-.99999?(e=2*Math.atan2(s,o),i=-Math.PI/2,n=0):h>=.99999?(e=2*Math.atan2(s,o),i=Math.PI/2,n=0):(e=Math.atan2(2*(o*s+r*a),1-2*(s*s+r*r)),i=Math.asin(h),n=Math.atan2(2*(o*a+s*r),1-2*(r*r+a*a))),t.set(e,i,n).mulScalar(_t.RAD_TO_DEG)},e.invert=function(t){return void 0===t&&(t=this),this.conjugate(t).normalize()},e.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},e.lengthSq=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},e.mul=function(t){var e=this.x,i=this.y,n=this.z,s=this.w,r=t.x,a=t.y,o=t.z,h=t.w;return this.x=s*r+e*h+i*o-n*a,this.y=s*a+i*h+n*r-e*o,this.z=s*o+n*h+e*a-i*r,this.w=s*h-e*r-i*a-n*o,this},e.mul2=function(t,e){var i=t.x,n=t.y,s=t.z,r=t.w,a=e.x,o=e.y,h=e.z,l=e.w;return this.x=r*a+i*l+n*h-s*o,this.y=r*o+n*l+s*a-i*h,this.z=r*h+s*l+i*o-n*a,this.w=r*l-i*a-n*o-s*h,this},e.normalize=function(t){void 0===t&&(t=this);var e=t.length();return 0===e?(this.x=this.y=this.z=0,this.w=1):(e=1/e,this.x=t.x*e,this.y=t.y*e,this.z=t.z*e,this.w=t.w*e),this},e.set=function(t,e,i,n){return this.x=t,this.y=e,this.z=i,this.w=n,this},e.setFromAxisAngle=function(t,e){e*=.5*_t.DEG_TO_RAD;var i=Math.sin(e),n=Math.cos(e);return this.x=i*t.x,this.y=i*t.y,this.z=i*t.z,this.w=n,this},e.setFromEulerAngles=function(t,e,i){if(t instanceof wt){var n=t;t=n.x,e=n.y,i=n.z}var s=.5*_t.DEG_TO_RAD;t*=s,e*=s,i*=s;var r=Math.sin(t),a=Math.cos(t),o=Math.sin(e),h=Math.cos(e),l=Math.sin(i),c=Math.cos(i);return this.x=r*h*c-a*o*l,this.y=a*o*c+r*h*l,this.z=a*h*l-r*o*c,this.w=a*h*c+r*o*l,this},e.setFromMat4=function(t){var e,i,n,s,r,a,o,h,l,c,u,d,f,p;if(e=(t=t.data)[0],i=t[1],n=t[2],s=t[4],r=t[5],a=t[6],o=t[8],h=t[9],l=t[10],0===(d=e*e+i*i+n*n))return this;if(d=1/Math.sqrt(d),0===(f=s*s+r*r+a*a))return this;if(f=1/Math.sqrt(f),0===(p=o*o+h*h+l*l))return this;i*=d,n*=d,s*=f,a*=f,o*=p=1/Math.sqrt(p),h*=p;var m=(e*=d)+(r*=f)+(l*=p);return m>=0?(c=Math.sqrt(m+1),this.w=.5*c,c=.5/c,this.x=(a-h)*c,this.y=(o-n)*c,this.z=(i-s)*c):e>r?e>l?(u=e-(r+l)+1,u=Math.sqrt(u),this.x=.5*u,u=.5/u,this.w=(a-h)*u,this.y=(i+s)*u,this.z=(n+o)*u):(u=l-(e+r)+1,u=Math.sqrt(u),this.z=.5*u,u=.5/u,this.w=(i-s)*u,this.x=(o+n)*u,this.y=(h+a)*u):r>l?(u=r-(l+e)+1,u=Math.sqrt(u),this.y=.5*u,u=.5/u,this.w=(o-n)*u,this.z=(a+h)*u,this.x=(s+i)*u):(u=l-(e+r)+1,u=Math.sqrt(u),this.z=.5*u,u=.5/u,this.w=(i-s)*u,this.x=(o+n)*u,this.y=(h+a)*u),this},e.setFromDirections=function(t,e){var i=1+t.dot(e);return i<Number.EPSILON?Math.abs(t.x)>Math.abs(t.y)?(this.x=-t.z,this.y=0,this.z=t.x,this.w=0):(this.x=0,this.y=-t.z,this.z=t.y,this.w=0):(this.x=t.y*e.z-t.z*e.y,this.y=t.z*e.x-t.x*e.z,this.z=t.x*e.y-t.y*e.x,this.w=i),this.normalize()},e.slerp=function(t,e,i){var n=t.x,s=t.y,r=t.z,a=t.w,o=e.x,h=e.y,l=e.z,c=e.w,u=a*c+n*o+s*h+r*l;if(u<0&&(c=-c,o=-o,h=-h,l=-l,u=-u),Math.abs(u)>=1)return this.w=a,this.x=n,this.y=s,this.z=r,this;var d=Math.acos(u),f=Math.sqrt(1-u*u);if(Math.abs(f)<.001)return this.w=.5*a+.5*c,this.x=.5*n+.5*o,this.y=.5*s+.5*h,this.z=.5*r+.5*l,this;var p=Math.sin((1-i)*d)/f,m=Math.sin(i*d)/f;return this.w=a*p+c*m,this.x=n*p+o*m,this.y=s*p+h*m,this.z=r*p+l*m,this},e.transformVector=function(t,e){void 0===e&&(e=new wt);var i=t.x,n=t.y,s=t.z,r=this.x,a=this.y,o=this.z,h=this.w,l=h*i+a*s-o*n,c=h*n+o*i-r*s,u=h*s+r*n-a*i,d=-r*i-a*n-o*s;return e.x=l*h+d*-r+c*-o-u*-a,e.y=c*h+d*-a+u*-r-l*-o,e.z=u*h+d*-o+l*-a-c*-r,e},e.toString=function(){return"["+this.x+", "+this.y+", "+this.z+", "+this.w+"]"},t}();Rt=Bt,Bt.IDENTITY=Object.freeze(new Rt(0,0,0,1)),Bt.ZERO=Object.freeze(new Rt(0,0,0,0));var Ut=new wt,Nt=new wt,zt=new wt,Vt=new wt,Gt=new wt,Ht=function(){function t(t,e){void 0===t&&(t=new wt),void 0===e&&(e=new wt(.5,.5,.5)),this.center=void 0,this.halfExtents=void 0,this._min=new wt,this._max=new wt,this.center=t,this.halfExtents=e}var e=t.prototype;return e.add=function(t){var e=this.center,i=e.x,n=e.y,s=e.z,r=this.halfExtents,a=r.x,o=r.y,h=r.z,l=i-a,c=i+a,u=n-o,d=n+o,f=s-h,p=s+h,m=t.center,_=m.x,v=m.y,g=m.z,y=t.halfExtents,x=y.x,S=y.y,b=y.z,w=_-x,T=_+x,A=v-S,C=v+S,E=g-b,M=g+b;w<l&&(l=w),T>c&&(c=T),A<u&&(u=A),C>d&&(d=C),E<f&&(f=E),M>p&&(p=M),e.x=.5*(l+c),e.y=.5*(u+d),e.z=.5*(f+p),r.x=.5*(c-l),r.y=.5*(d-u),r.z=.5*(p-f)},e.copy=function(t){this.center.copy(t.center),this.halfExtents.copy(t.halfExtents)},e.clone=function(){return new t(this.center.clone(),this.halfExtents.clone())},e.intersects=function(t){var e=this.getMax(),i=this.getMin(),n=t.getMax(),s=t.getMin();return i.x<=n.x&&e.x>=s.x&&i.y<=n.y&&e.y>=s.y&&i.z<=n.z&&e.z>=s.z},e._intersectsRay=function(t,e){var i=Ut.copy(this.getMin()).sub(t.origin),n=Nt.copy(this.getMax()).sub(t.origin),s=t.direction;0===s.x?(i.x=i.x<0?-Number.MAX_VALUE:Number.MAX_VALUE,n.x=n.x<0?-Number.MAX_VALUE:Number.MAX_VALUE):(i.x/=s.x,n.x/=s.x),0===s.y?(i.y=i.y<0?-Number.MAX_VALUE:Number.MAX_VALUE,n.y=n.y<0?-Number.MAX_VALUE:Number.MAX_VALUE):(i.y/=s.y,n.y/=s.y),0===s.z?(i.z=i.z<0?-Number.MAX_VALUE:Number.MAX_VALUE,n.z=n.z<0?-Number.MAX_VALUE:Number.MAX_VALUE):(i.z/=s.z,n.z/=s.z);var r=zt.set(Math.min(i.x,n.x),Math.min(i.y,n.y),Math.min(i.z,n.z)),a=Vt.set(Math.max(i.x,n.x),Math.max(i.y,n.y),Math.max(i.z,n.z)),o=Math.min(Math.min(a.x,a.y),a.z),h=Math.max(Math.max(r.x,r.y),r.z),l=o>=h&&h>=0;return l&&e.copy(t.direction).mulScalar(h).add(t.origin),l},e._fastIntersectsRay=function(t){var e=Ut,i=Nt,n=zt,s=Vt,r=Gt,a=t.direction;return e.sub2(t.origin,this.center),s.set(Math.abs(e.x),Math.abs(e.y),Math.abs(e.z)),n.mul2(e,a),!(s.x>this.halfExtents.x&&n.x>=0)&&(!(s.y>this.halfExtents.y&&n.y>=0)&&(!(s.z>this.halfExtents.z&&n.z>=0)&&(r.set(Math.abs(a.x),Math.abs(a.y),Math.abs(a.z)),i.cross(a,e),i.set(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z)),!(i.x>this.halfExtents.y*r.z+this.halfExtents.z*r.y)&&(!(i.y>this.halfExtents.x*r.z+this.halfExtents.z*r.x)&&!(i.z>this.halfExtents.x*r.y+this.halfExtents.y*r.x)))))},e.intersectsRay=function(t,e){return e?this._intersectsRay(t,e):this._fastIntersectsRay(t)},e.setMinMax=function(t,e){this.center.add2(e,t).mulScalar(.5),this.halfExtents.sub2(e,t).mulScalar(.5)},e.getMin=function(){return this._min.copy(this.center).sub(this.halfExtents)},e.getMax=function(){return this._max.copy(this.center).add(this.halfExtents)},e.containsPoint=function(t){var e=this.getMin(),i=this.getMax();return!(t.x<e.x||t.x>i.x||t.y<e.y||t.y>i.y||t.z<e.z||t.z>i.z)},e.setFromTransformedAabb=function(t,e,i){void 0===i&&(i=!1);var n=t.center,s=t.halfExtents,r=e.data,a=r[0],o=r[4],h=r[8],l=r[1],c=r[5],u=r[9],d=r[2],f=r[6],p=r[10];if(i){var m=a*a+o*o+h*h;if(m>0){var _=1/Math.sqrt(m);a*=_,o*=_,h*=_}if((m=l*l+c*c+u*u)>0){var v=1/Math.sqrt(m);l*=v,c*=v,u*=v}if((m=d*d+f*f+p*p)>0){var g=1/Math.sqrt(m);d*=g,f*=g,p*=g}}this.center.set(r[12]+a*n.x+o*n.y+h*n.z,r[13]+l*n.x+c*n.y+u*n.z,r[14]+d*n.x+f*n.y+p*n.z),this.halfExtents.set(Math.abs(a)*s.x+Math.abs(o)*s.y+Math.abs(h)*s.z,Math.abs(l)*s.x+Math.abs(c)*s.y+Math.abs(u)*s.z,Math.abs(d)*s.x+Math.abs(f)*s.y+Math.abs(p)*s.z)},t.computeMinMax=function(t,e,i,n){if(void 0===n&&(n=t.length/3),n>0){for(var s=t[0],r=t[1],a=t[2],o=s,h=r,l=a,c=3*n,u=3;u<c;u+=3){var d=t[u],f=t[u+1],p=t[u+2];d<s&&(s=d),f<r&&(r=f),p<a&&(a=p),d>o&&(o=d),f>h&&(h=f),p>l&&(l=p)}e.set(s,r,a),i.set(o,h,l)}},e.compute=function(e,i){t.computeMinMax(e,Ut,Nt,i),this.setMinMax(Ut,Nt)},e.intersectsBoundingSphere=function(t){return this._distanceToBoundingSphereSq(t)<=t.radius*t.radius},e._distanceToBoundingSphereSq=function(t){for(var e=this.getMin(),i=this.getMax(),n=0,s=["x","y","z"],r=0;r<3;++r){var a=0,o=t.center[s[r]],h=e[s[r]],l=i[s[r]],c=0;o<h&&(a+=(c=h-o)*c),o>l&&(a+=(c=o-l)*c),n+=a}return n},e._expand=function(t,e){Ut.add2(this.getMin(),t),Nt.add2(this.getMax(),e),this.setMinMax(Ut,Nt)},t}(),Wt=new wt,Xt=new wt,jt=function(){function t(t,e){void 0===t&&(t=new wt),void 0===e&&(e=.5),this.center=void 0,this.radius=void 0,this.center=t,this.radius=e}var e=t.prototype;return e.containsPoint=function(t){var e=Wt.sub2(t,this.center).lengthSq(),i=this.radius;return e<i*i},e.intersectsRay=function(t,e){var i=Wt.copy(t.origin).sub(this.center),n=i.dot(Xt.copy(t.direction).normalize()),s=i.dot(i)-this.radius*this.radius;if(s>0&&n>0)return!1;var r=n*n-s;if(r<0)return!1;var a=Math.abs(-n-Math.sqrt(r));return e&&e.copy(t.direction).mulScalar(a).add(t.origin),!0},e.intersectsBoundingSphere=function(t){Wt.sub2(t.center,this.center);var e=t.radius+this.radius;return Wt.lengthSq()<=e*e},t}(),qt=function(){function t(){this.planes=[];for(var t=0;t<6;t++)this.planes[t]=[]}var e=t.prototype;return e.setFromMat4=function(t){var e,i=t.data,n=this.planes;(e=n[0])[0]=i[3]-i[0],e[1]=i[7]-i[4],e[2]=i[11]-i[8],e[3]=i[15]-i[12];var s=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=s,e[1]/=s,e[2]/=s,e[3]/=s,(e=n[1])[0]=i[3]+i[0],e[1]=i[7]+i[4],e[2]=i[11]+i[8],e[3]=i[15]+i[12],s=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]),e[0]/=s,e[1]/=s,e[2]/=s,e[3]/=s,(e=n[2])[0]=i[3]+i[1],e[1]=i[7]+i[5],e[2]=i[11]+i[9],e[3]=i[15]+i[13],s=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]),e[0]/=s,e[1]/=s,e[2]/=s,e[3]/=s,(e=n[3])[0]=i[3]-i[1],e[1]=i[7]-i[5],e[2]=i[11]-i[9],e[3]=i[15]-i[13],s=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]),e[0]/=s,e[1]/=s,e[2]/=s,e[3]/=s,(e=n[4])[0]=i[3]-i[2],e[1]=i[7]-i[6],e[2]=i[11]-i[10],e[3]=i[15]-i[14],s=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]),e[0]/=s,e[1]/=s,e[2]/=s,e[3]/=s,(e=n[5])[0]=i[3]+i[2],e[1]=i[7]+i[6],e[2]=i[11]+i[10],e[3]=i[15]+i[14],s=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]),e[0]/=s,e[1]/=s,e[2]/=s,e[3]/=s},e.containsPoint=function(t){var e,i;for(e=0;e<6;e++)if((i=this.planes[e])[0]*t.x+i[1]*t.y+i[2]*t.z+i[3]<=0)return!1;return!0},e.containsSphere=function(t){var e,i,n,s=0,r=t.radius,a=t.center,o=a.x,h=a.y,l=a.z,c=this.planes;for(i=0;i<6;i++){if((e=(n=c[i])[0]*o+n[1]*h+n[2]*l+n[3])<=-r)return 0;e>r&&s++}return 6===s?2:1},t}(),Yt=function(){function t(t,e){this.origin=new wt,this.direction=wt.FORWARD.clone(),t&&this.origin.copy(t),e&&this.direction.copy(e)}var e=t.prototype;return e.set=function(t,e){return this.origin.copy(t),this.direction.copy(e),this},e.copy=function(t){return this.set(t.origin,t.direction)},e.clone=function(){return new this.constructor(this.origin,this.direction)},t}(),Kt=new Yt,Zt=new wt,Qt=new jt,$t=new Ft,Jt=function(){function t(t,e){void 0===t&&(t=new Ft),void 0===e&&(e=new wt(.5,.5,.5)),this.halfExtents=void 0,this._modelTransform=void 0,this._worldTransform=void 0,this._aabb=void 0,this.halfExtents=e,this._modelTransform=t.clone().invert(),this._worldTransform=t.clone(),this._aabb=new Ht(new wt,this.halfExtents)}var e=t.prototype;return e.intersectsRay=function(t,e){if(this._modelTransform.transformPoint(t.origin,Kt.origin),this._modelTransform.transformVector(t.direction,Kt.direction),e){var i=this._aabb._intersectsRay(Kt,e);return $t.copy(this._modelTransform).invert().transformPoint(e,e),i}return this._aabb._fastIntersectsRay(Kt)},e.containsPoint=function(t){return this._modelTransform.transformPoint(t,Zt),this._aabb.containsPoint(Zt)},e.intersectsBoundingSphere=function(t){return this._modelTransform.transformPoint(t.center,Qt.center),Qt.radius=t.radius,!!this._aabb.intersectsBoundingSphere(Qt)},y(t,[{key:"worldTransform",get:function(){return this._worldTransform},set:function(t){this._worldTransform.copy(t),this._modelTransform.copy(t).invert()}}]),t}(),te=function(){function t(t,e){void 0===t&&(t=wt.UP),void 0===e&&(e=0),this.normal=new wt,this.distance=void 0,this.normal.copy(t),this.distance=e}var e=t.prototype;return e.setFromPointNormal=function(t,e){return this.normal.copy(e),this.distance=-this.normal.dot(t),this},e.intersectsLine=function(t,e,i){var n=this.distance,s=this.normal.dot(t)+n,r=s/(s-(this.normal.dot(e)+n)),a=r>=0&&r<=1;return a&&i&&i.lerp(t,e,r),a},e.intersectsRay=function(t,e){var i=this.normal.dot(t.direction);if(0===i)return!1;var n=-(this.normal.dot(t.origin)+this.distance)/i;return n>=0&&e&&e.copy(t.direction).mulScalar(n).add(t.origin),n>=0},e.copy=function(t){return this.normal.copy(t.normal),this.distance=t.distance,this},e.clone=function(){return(new(0,this.constructor)).copy(this)},t}(),ee="linear",ie="inverse",ne="exponential",se=0,re=10,ae=11,oe=12,he=13,le=14,ce=15,ue=16,de=17,fe=18,pe=21,me=24,_e=25,ve=26,ge=27,ye=new Map([[0,{name:"A8",size:1}],[1,{name:"L8",size:1}],[2,{name:"LA8",size:2}],[3,{name:"RGB565",size:2}],[4,{name:"RGBA5551",size:2}],[5,{name:"RGBA4",size:2}],[6,{name:"RGB8",size:4}],[7,{name:"RGBA8",size:4}],[ae,{name:"RGB16F",size:8}],[oe,{name:"RGBA16F",size:8}],[he,{name:"RGB32F",size:16}],[le,{name:"RGBA32F",size:16}],[ce,{name:"R32F",size:4}],[ue,{name:"DEPTH",size:4}],[de,{name:"DEPTHSTENCIL",size:4}],[fe,{name:"111110F",size:4}],[19,{name:"SRGB",size:4}],[20,{name:"SRGBA",size:4}],[31,{name:"BGRA8",size:4}],[8,{name:"DXT1",blockSize:8}],[9,{name:"DXT3",blockSize:16}],[re,{name:"DXT5",blockSize:16}],[pe,{name:"ETC1",blockSize:8}],[22,{name:"ETC2_RGB",blockSize:8}],[23,{name:"ETC2_RGBA",blockSize:16}],[me,{name:"PVRTC_2BPP_RGB_1",blockSize:8}],[_e,{name:"PVRTC_2BPP_RGBA_1",blockSize:8}],[ve,{name:"PVRTC_4BPP_RGB_1",blockSize:8}],[ge,{name:"PVRTC_4BPP_RGBA_1",blockSize:8}],[28,{name:"ASTC_4x4",blockSize:16}],[29,{name:"ATC_RGB",blockSize:8}],[30,{name:"ATC_RGBA",blockSize:16}]]),xe=function(t){return void 0!==ye.get(t).blockSize},Se=function(t){switch(t){case he:case le:return Float32Array;case 3:case 4:case 5:case ae:case oe:return Uint16Array;default:return Uint8Array}},be=5,we="POSITION",Te="NORMAL",Ae="TANGENT",Ce="BLENDWEIGHT",Ee="BLENDINDICES",Me="COLOR",Pe="TEXCOORD",Re="TEXCOORD0",Ie="TEXCOORD1",Le="TEXCOORD2",De="TEXCOORD3",Oe="TEXCOORD4",ke="TEXCOORD5",Fe="TEXCOORD6",Be="TEXCOORD7",Ue="ATTR",Ne="ATTR0",ze="ATTR1",Ve="ATTR2",Ge="ATTR3",He="ATTR4",We="ATTR5",Xe="ATTR6",je="ATTR7",qe="ATTR8",Ye="ATTR9",Ke="ATTR10",Ze="ATTR11",Qe="ATTR12",$e="ATTR13",Je="ATTR14",ti="ATTR15",ei="default",ii="rgbm",ni="rgbe",si="rgbp",ri="swizzleGGGR",ai="2d",oi="2d-array",hi="cube",li="3d",ci="none",ui="cube",di="equirect",fi="octahedral",pi="wgsl",mi=1,_i=13,vi=14,gi=["bool","int","float","vec2","vec3","vec4","ivec2","ivec3","ivec4","bec2","bec3","bec4","mat2","mat3","mat4","sampler2D","samplerCube","","sampler2DShadow","samplerCubeShadow","sampler3D","","",""],yi="webgl1",xi="webgl2",Si="webgpu",bi="null",wi=["mesh","view"],Ti="default",Ai=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array],Ci=[1,1,2,2,4,4,4],Ei={Int8Array:0,Uint8Array:mi,Int16Array:2,Uint16Array:3,Int32Array:4,Uint32Array:5,Float32Array:6},Mi=[Uint8Array,Uint16Array,Uint32Array],Pi=[1,2,4],Ri={};Ri[we]=0,Ri[Te]=1,Ri[Ce]=2,Ri[Ee]=3,Ri[Me]=4,Ri[Re]=5,Ri[Ie]=6,Ri[Le]=7,Ri[De]=8,Ri[Oe]=9,Ri[ke]=10,Ri[Fe]=11,Ri[Be]=12,Ri[Ae]=13,Ri[Ne]=0,Ri[ze]=1,Ri[Ve]=2,Ri[Ge]=3,Ri[He]=4,Ri[We]=5,Ri[Xe]=6,Ri[je]=7,Ri[qe]=8,Ri[Ye]=9,Ri[Ke]=10,Ri[Ze]=11,Ri[Qe]=12,Ri[$e]=13,Ri[Je]=14,Ri[ti]=15;var Ii,Li,Di="1.65",Oi=function(t,e,i,n){return void 0===n&&(n=1),t&~(n<<i)|e<<i},ki=function(t,e,i){return void 0===i&&(i=1),t>>e&i},Fi=function(t,e,i){void 0===i&&(i=1);var n=i<<e;return(t&n)===n},Bi=15,Ui=function(){function t(t,e,i,n,s,r,a,o,h,l,c){void 0===t&&(t=!1),void 0===e&&(e=0),void 0===i&&(i=1),void 0===n&&(n=0),void 0===o&&(o=!0),void 0===h&&(h=!0),void 0===l&&(l=!0),void 0===c&&(c=!0),this.target0=0,this.setColorBlend(e,i,n),this.setAlphaBlend(null!=s?s:e,null!=r?r:i,null!=a?a:n),this.setColorWrite(o,h,l,c),this.blend=t}var e=t.prototype;return e.setColorBlend=function(t,e,i){this.target0=Oi(this.target0,t,0,7),this.target0=Oi(this.target0,e,3,Bi),this.target0=Oi(this.target0,i,7,Bi)},e.setAlphaBlend=function(t,e,i){this.target0=Oi(this.target0,t,11,7),this.target0=Oi(this.target0,e,14,Bi),this.target0=Oi(this.target0,i,18,Bi)},e.setColorWrite=function(t,e,i,n){this.redWrite=t,this.greenWrite=e,this.blueWrite=i,this.alphaWrite=n},e.copy=function(t){return this.target0=t.target0,this},e.clone=function(){var t=new this.constructor;return t.copy(this)},e.equals=function(t){return this.target0===t.target0},y(t,[{key:"blend",get:function(){return Fi(this.target0,26)},set:function(t){this.target0=Oi(this.target0,t?1:0,26)}},{key:"colorOp",get:function(){return ki(this.target0,0,7)}},{key:"colorSrcFactor",get:function(){return ki(this.target0,3,Bi)}},{key:"colorDstFactor",get:function(){return ki(this.target0,7,Bi)}},{key:"alphaOp",get:function(){return ki(this.target0,11,7)}},{key:"alphaSrcFactor",get:function(){return ki(this.target0,14,Bi)}},{key:"alphaDstFactor",get:function(){return ki(this.target0,18,Bi)}},{key:"redWrite",get:function(){return Fi(this.target0,22)},set:function(t){this.target0=Oi(this.target0,t?1:0,22)}},{key:"greenWrite",get:function(){return Fi(this.target0,23)},set:function(t){this.target0=Oi(this.target0,t?1:0,23)}},{key:"blueWrite",get:function(){return Fi(this.target0,24)},set:function(t){this.target0=Oi(this.target0,t?1:0,24)}},{key:"alphaWrite",get:function(){return Fi(this.target0,25)},set:function(t){this.target0=Oi(this.target0,t?1:0,25)}},{key:"allWrite",get:function(){return ki(this.target0,22,15)}},{key:"key",get:function(){return this.target0}}]),t}();Ii=Ui,Ui.NOBLEND=Object.freeze(new Ii),Ui.NOWRITE=Object.freeze(new Ii(void 0,void 0,void 0,void 0,void 0,void 0,void 0,!1,!1,!1,!1)),Ui.ALPHABLEND=Object.freeze(new Ii(!0,0,6,8));var Ni=function(){function t(t,e){void 0===t&&(t=3),void 0===e&&(e=!0),this.data=0,this.func=t,this.write=e}var e=t.prototype;return e.copy=function(t){return this.data=t.data,this},e.clone=function(){var t=new this.constructor;return t.copy(this)},e.equals=function(t){return this.data===t.data},y(t,[{key:"test",get:function(){return 7!==this.func},set:function(t){this.func=t?3:7}},{key:"write",get:function(){return Fi(this.data,3)},set:function(t){this.data=Oi(this.data,t?1:0,3)}},{key:"func",get:function(){return ki(this.data,0,7)},set:function(t){this.data=Oi(this.data,t,0,7)}},{key:"key",get:function(){return this.data}}]),t}();Li=Ni,Ni.DEFAULT=Object.freeze(new Li),Ni.NODEPTH=Object.freeze(new Li(7,!1)),Ni.WRITEDEPTH=Object.freeze(new Li(7,!0));var zi=function(){function t(){this.globalId=0,this.revision=0}var e=t.prototype;return e.equals=function(t){return this.globalId===t.globalId&&this.revision===t.revision},e.copy=function(t){this.globalId=t.globalId,this.revision=t.revision},e.reset=function(){this.globalId=0,this.revision=0},t}(),Vi=0,Gi=function(){function t(){Vi++,this.version=new zi,this.version.globalId=Vi}return t.prototype.increment=function(){this.version.revision++},t}(),Hi=function(){function t(t){this.name=t,this.value=null,this.versionObject=new Gi}var e=t.prototype;return e.toJSON=function(t){},e.setValue=function(t){this.value=t,this.versionObject.increment()},e.getValue=function(){return this.value},t}(),Wi=function(){function t(t){this.name=t,this.variables=new Map}var e=t.prototype;return e.resolve=function(t){return this.variables.has(t)||this.variables.set(t,new Hi(t)),this.variables.get(t)},e.removeValue=function(t){for(var e in this.variables){var i=this.variables[e];i.value===t&&(i.value=null)}},t}(),Xi=0,ji=function(){function t(t,e,i,n,s){void 0===n&&(n=0),this.device=t,this.format=e,this.numVertices=i,this.usage=n,this.id=Xi++,this.impl=t.createVertexBufferImpl(this,e),this.numBytes=e.verticesByteSize?e.verticesByteSize:e.size*i,this.adjustVramSizeTracking(t._vram,this.numBytes),s?this.setData(s):this.storage=new ArrayBuffer(this.numBytes),this.device.buffers.push(this)}var e=t.prototype;return e.destroy=function(){var t=this.device,e=t.buffers.indexOf(this);-1!==e&&t.buffers.splice(e,1),this.impl.initialized&&(this.impl.destroy(t),this.adjustVramSizeTracking(t._vram,-this.storage.byteLength))},e.adjustVramSizeTracking=function(t,e){t.vb+=e},e.loseContext=function(){this.impl.loseContext()},e.getFormat=function(){return this.format},e.getUsage=function(){return this.usage},e.getNumVertices=function(){return this.numVertices},e.lock=function(){return this.storage},e.unlock=function(){this.impl.unlock(this)},e.setData=function(t){return t.byteLength===this.numBytes&&(this.storage=t,this.unlock(),!0)},t}();function qi(t){for(var e=0,i=0,n=t.length;i<n;i++)e=(e<<5)-e+t.charCodeAt(i),e|=0;return e}function Yi(t){for(var e=2166136261,i=0;i<t.length;i++)e^=t[i],e*=16777619;return e>>>0}var Ki,Zi=function(){function t(){this.map=new Map,this.id=0}return t.prototype.get=function(t){var e=this.map.get(t);return void 0===e&&(e=this.id++,this.map.set(t,e)),e},t}(),Qi=new Zi,$i=[2,4,8,12,16],Ji=function(){function t(t,e,i){this.device=t,this._elements=[],this.hasUv0=!1,this.hasUv1=!1,this.hasColor=!1,this.hasTangents=!1,this.verticesByteSize=0,this.vertexCount=i,this.interleaved=void 0===i,this.instancing=!1,this.size=e.reduce((function(t,e){return t+4*Math.ceil(e.components*Ci[e.type]/4)}),0);for(var n,s=0,r=0,a=e.length;r<a;r++){var o,h=e[r];n=h.components*Ci[h.type],i&&(s=_t.roundUp(s,n));var l={name:h.semantic,offset:i?s:h.hasOwnProperty("offset")?h.offset:s,stride:i?n:h.hasOwnProperty("stride")?h.stride:this.size,dataType:h.type,numComponents:h.components,normalize:null!=(o=h.normalize)&&o,size:n};this._elements.push(l),s+=i?n*i:4*Math.ceil(n/4),h.semantic===Re?this.hasUv0=!0:h.semantic===Ie?this.hasUv1=!0:h.semantic===Me?this.hasColor=!0:h.semantic===Ae&&(this.hasTangents=!0)}i&&(this.verticesByteSize=s),this._evaluateHash()}t.getDefaultInstancingFormat=function(e){return t._defaultInstancingFormat||(t._defaultInstancingFormat=new t(e,[{semantic:Qe,components:4,type:6},{semantic:$e,components:4,type:6},{semantic:Je,components:4,type:6},{semantic:ti,components:4,type:6}])),t._defaultInstancingFormat},t.isElementValid=function(t,e){var i=e.components*Ci[e.type];return!(t.isWebGPU&&!$i.includes(i))};var e=t.prototype;return e.update=function(){this._evaluateHash()},e._evaluateHash=function(){for(var t,e,i=[],n=[],s=this._elements.length,r=0;r<s;r++){var a=this._elements[r];t=a.name,t+=a.dataType,t+=a.numComponents,t+=a.normalize,i.push(t),e=t,e+=a.offset,e+=a.stride,e+=a.size,n.push(e)}i.sort(),this.batchingHash=qi(i.join()),this.renderingHashString=n.join("_"),this.renderingHash=Qi.get(this.renderingHashString)},y(t,[{key:"elements",get:function(){return this._elements}}]),t}();Ji._defaultInstancingFormat=null;var tn=new Zi,en=function(){function t(t){var e,i,n,s,r,a,o;void 0===t&&(t={}),this._func=void 0,this._ref=void 0,this._fail=void 0,this._zfail=void 0,this._zpass=void 0,this._readMask=void 0,this._writeMask=void 0,this._dirty=!0,this._key=void 0,this._func=null!=(e=t.func)?e:7,this._ref=null!=(i=t.ref)?i:0,this._readMask=null!=(n=t.readMask)?n:255,this._writeMask=null!=(s=t.writeMask)?s:255,this._fail=null!=(r=t.fail)?r:0,this._zfail=null!=(a=t.zfail)?a:0,this._zpass=null!=(o=t.zpass)?o:0,this._evalKey()}var e=t.prototype;return e._evalKey=function(){var t=this._func+","+this._ref+","+this._fail+","+this._zfail+","+this._zpass+","+this._readMask+","+this._writeMask;this._key=tn.get(t),this._dirty=!1},e.copy=function(t){return this._func=t._func,this._ref=t._ref,this._readMask=t._readMask,this._writeMask=t._writeMask,this._fail=t._fail,this._zfail=t._zfail,this._zpass=t._zpass,this._dirty=t._dirty,this._key=t._key,this},e.clone=function(){var t=new this.constructor;return t.copy(this)},y(t,[{key:"func",get:function(){return this._func},set:function(t){this._func=t,this._dirty=!0}},{key:"ref",get:function(){return this._ref},set:function(t){this._ref=t,this._dirty=!0}},{key:"fail",get:function(){return this._fail},set:function(t){this._fail=t,this._dirty=!0}},{key:"zfail",get:function(){return this._zfail},set:function(t){this._zfail=t,this._dirty=!0}},{key:"zpass",get:function(){return this._zpass},set:function(t){this._zpass=t,this._dirty=!0}},{key:"readMask",get:function(){return this._readMask},set:function(t){this._readMask=t,this._dirty=!0}},{key:"writeMask",get:function(){return this._writeMask},set:function(t){this._writeMask=t,this._dirty=!0}},{key:"key",get:function(){return this._dirty&&this._evalKey(),this._key}}]),t}();Ki=en,en.DEFAULT=Object.freeze(new Ki);var nn=function(t){function e(e,i){var n,s,r,a,o;(o=t.call(this)||this).canvas=void 0,o.backBuffer=null,o.backBufferSize=new Et,o.backBufferFormat=void 0,o.backBufferAntialias=!1,o.isWebGPU=!1,o.isWebGL1=!1,o.isWebGL2=!1,o.scope=void 0,o.boneLimit=void 0,o.maxAnisotropy=void 0,o.maxCubeMapSize=void 0,o.maxTextureSize=void 0,o.maxVolumeSize=void 0,o.maxColorAttachments=1,o.precision=void 0,o.samples=void 0,o.supportsStencil=void 0,o.supportsMrt=!1,o.supportsVolumeTextures=!1,o.renderTarget=null,o.shaders=[],o.textures=[],o.targets=new Set,o.renderVersion=0,o.renderPassIndex=void 0,o.insideRenderPass=!1,o.supportsInstancing=void 0,o.supportsUniformBuffers=!1,o.textureFloatRenderable=void 0,o.textureHalfFloatRenderable=void 0,o.textureFloatFilterable=!0,o.quadVertexBuffer=void 0,o.blendState=new Ui,o.depthState=new Ni,o.stencilEnabled=!1,o.stencilFront=new en,o.stencilBack=new en,o.dynamicBuffers=void 0,o.gpuProfiler=void 0,o.defaultClearOptions={color:[0,0,0,1],depth:1,stencil:0,flags:3},o.canvas=e,o.initOptions=x({},i),null!=(n=o.initOptions).depth||(n.depth=!0),null!=(s=o.initOptions).stencil||(s.stencil=!0),null!=(r=o.initOptions).antialias||(r.antialias=!0),null!=(a=o.initOptions).powerPreference||(a.powerPreference="high-performance"),o._maxPixelRatio=G.browser?Math.min(1,window.devicePixelRatio):1,o.buffers=[],o._vram={tex:0,vb:0,ib:0,ub:0},o._shaderStats={vsCompiled:0,fsCompiled:0,linked:0,materialShaders:0,compileTime:0},o.initializeContextCaches(),o._drawCallsPerFrame=0,o._shaderSwitchesPerFrame=0,o._primsPerFrame=[];for(var h=0;h<=6;h++)o._primsPerFrame[h]=0;return o._renderTargetCreationTime=0,o.scope=new Wi("Device"),o.textureBias=o.scope.resolve("textureBias"),o.textureBias.setValue(0),o}S(e,t);var i=e.prototype;return i.postInit=function(){var t=new Ji(this,[{semantic:we,components:2,type:6}]),e=new Float32Array([-1,-1,1,-1,-1,1,1,1]);this.quadVertexBuffer=new ji(this,t,4,0,e)},i.destroy=function(){var t,e,i;this.fire("destroy"),null==(t=this.quadVertexBuffer)||t.destroy(),this.quadVertexBuffer=null,null==(e=this.dynamicBuffers)||e.destroy(),this.dynamicBuffers=null,null==(i=this.gpuProfiler)||i.destroy(),this.gpuProfiler=null},i.onDestroyShader=function(t){this.fire("destroy:shader",t);var e=this.shaders.indexOf(t);-1!==e&&this.shaders.splice(e,1)},i.postDestroy=function(){this.scope=null,this.canvas=null},i.toJSON=function(t){},i.initializeContextCaches=function(){this.indexBuffer=null,this.vertexBuffers=[],this.shader=null,this.renderTarget=null},i.initializeRenderState=function(){this.blendState=new Ui,this.depthState=new Ni,this.cullMode=1,this.vx=this.vy=this.vw=this.vh=0,this.sx=this.sy=this.sw=this.sh=0},i.setStencilState=function(t,e){},i.setBlendState=function(t){},i.setDepthState=function(t){},i.setCullMode=function(t){},i.setRenderTarget=function(t){this.renderTarget=t},i.setIndexBuffer=function(t){this.indexBuffer=t},i.setVertexBuffer=function(t){t&&this.vertexBuffers.push(t)},i.getRenderTarget=function(){return this.renderTarget},i.initRenderTarget=function(t){t.initialized||(t.init(),this.targets.add(t))},i._isBrowserInterface=function(t){return this._isImageBrowserInterface(t)||this._isImageCanvasInterface(t)||this._isImageVideoInterface(t)},i._isImageBrowserInterface=function(t){return"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap||"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement},i._isImageCanvasInterface=function(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement},i._isImageVideoInterface=function(t){return"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement},i.resizeCanvas=function(t,e){var i=Math.min(this._maxPixelRatio,G.browser?window.devicePixelRatio:1),n=Math.floor(t*i),s=Math.floor(e*i);n===this.canvas.width&&s===this.canvas.height||this.setResolution(n,s)},i.setResolution=function(t,i){this.canvas.width=t,this.canvas.height=i,this.fire(e.EVENT_RESIZE,t,i)},i.updateClientRect=function(){this.clientRect=this.canvas.getBoundingClientRect()},i.getBoneLimit=function(){return this.boneLimit},i.setBoneLimit=function(t){this.boneLimit=t},i.frameStart=function(){this.renderPassIndex=0,this.renderVersion++},i.frameEnd=function(){},y(e,[{key:"width",get:function(){return this.canvas.width}},{key:"height",get:function(){return this.canvas.height}},{key:"fullscreen",get:function(){return!1},set:function(t){}},{key:"maxPixelRatio",get:function(){return this._maxPixelRatio},set:function(t){this._maxPixelRatio=t}},{key:"deviceType",get:function(){return this._deviceType}}]),e}(P);nn.EVENT_RESIZE="resizecanvas";var sn=0,rn=function(){function t(t){var e,i,n,s,r,a,o;void 0===t&&(t={}),this.name=void 0,this._device=void 0,this._colorBuffer=void 0,this._colorBuffers=void 0,this._depthBuffer=void 0,this._depth=void 0,this._stencil=void 0,this._samples=void 0,this.autoResolve=void 0,this._face=void 0,this.flipY=void 0,this.id=sn++;var h=arguments[1],l=arguments[2];if(t instanceof nn?(this._colorBuffer=h,t=l):this._colorBuffer=t.colorBuffer,this._colorBuffer&&(this._colorBuffers=[this._colorBuffer]),this._depthBuffer=t.depthBuffer,this._face=null!=(e=t.face)?e:0,this._depthBuffer){var c=this._depthBuffer._format;c===ue?(this._depth=!0,this._stencil=!1):c===de?(this._depth=!0,this._stencil=!0):(this._depth=!1,this._stencil=!1)}else{var u,d;this._depth=null==(u=t.depth)||u,this._stencil=null!=(d=t.stencil)&&d}t.colorBuffers&&(this._colorBuffers||(this._colorBuffers=[].concat(t.colorBuffers),this._colorBuffer=t.colorBuffers[0]));var f=(null==(i=this._colorBuffer)?void 0:i.device)||(null==(n=this._depthBuffer)?void 0:n.device)||t.graphicsDevice;this._device=f,null==(s=this._colorBuffers)||s.forEach((function(t){t._isRenderTarget=!0}));var p,m,_=this._device.maxSamples;(this._samples=Math.min(null!=(r=t.samples)?r:1,_),f.isWebGPU&&(this._samples=this._samples>1?_:1),this.autoResolve=null==(a=t.autoResolve)||a,this.name=t.name,this.name)||(this.name=null==(p=this._colorBuffer)?void 0:p.name);this.name||(this.name=null==(m=this._depthBuffer)?void 0:m.name);this.name||(this.name="Untitled"),this.flipY=null!=(o=t.flipY)&&o,this.validateMrt(),this.impl=f.createRenderTargetImpl(this)}var e=t.prototype;return e.destroy=function(){var t=this._device;t&&(t.targets.delete(this),t.renderTarget===this&&t.setRenderTarget(null),this.destroyFrameBuffers())},e.destroyFrameBuffers=function(){var t=this._device;t&&this.impl.destroy(t)},e.destroyTextureBuffers=function(){var t,e;null==(t=this._depthBuffer)||t.destroy(),this._depthBuffer=null,null==(e=this._colorBuffers)||e.forEach((function(t){t.destroy()})),this._colorBuffers=null,this._colorBuffer=null},e.resize=function(t,e){var i,n,s=this._device;this.destroyFrameBuffers(),s.renderTarget===this&&s.setRenderTarget(null),null==(i=this._depthBuffer)||i.resize(t,e),null==(n=this._colorBuffers)||n.forEach((function(i){i.resize(t,e)})),this.validateMrt(),this.impl=s.createRenderTargetImpl(this)},e.validateMrt=function(){},e.init=function(){this.impl.init(this._device,this)},e.loseContext=function(){this.impl.loseContext()},e.resolve=function(t,e){void 0===t&&(t=!0),void 0===e&&(e=!!this._depthBuffer),this._device&&this._samples>1&&this.impl.resolve(this._device,this,t,e)},e.copy=function(t,e,i){if(!this._device){if(!t._device)return!1;this._device=t._device}return this._device.copyRenderTarget(t,this,e,i)},e.getColorBuffer=function(t){var e;return null==(e=this._colorBuffers)?void 0:e[t]},y(t,[{key:"initialized",get:function(){return this.impl.initialized}},{key:"device",get:function(){return this._device}},{key:"samples",get:function(){return this._samples}},{key:"depth",get:function(){return this._depth}},{key:"stencil",get:function(){return this._stencil}},{key:"colorBuffer",get:function(){return this._colorBuffer}},{key:"depthBuffer",get:function(){return this._depthBuffer}},{key:"face",get:function(){return this._face}},{key:"width",get:function(){var t,e;return(null==(t=this._colorBuffer)?void 0:t.width)||(null==(e=this._depthBuffer)?void 0:e.width)||this._device.width}},{key:"height",get:function(){var t,e;return(null==(t=this._colorBuffer)?void 0:t.height)||(null==(e=this._depthBuffer)?void 0:e.height)||this._device.height}}]),t}(),an=function(){function t(){this.bindGroup=void 0}var e=t.prototype;return e.update=function(t){this.destroy();var e=t.device,i=this.createDescriptor(e,t);this.bindGroup=e.wgpu.createBindGroup(i)},e.destroy=function(){this.bindGroup=null},e.createDescriptor=function(t,e){var i=[],n=e.format,s=0;return e.uniformBuffers.forEach((function(t){var e=t.persistent?t.impl.buffer:t.allocation.gpuBuffer.buffer;i.push({binding:s++,resource:{buffer:e,offset:0,size:t.format.byteSize}})})),e.textures.forEach((function(e,r){var a=e.impl,o=n.textureFormats[r],h=a.getView(t);i.push({binding:s++,resource:h});var l=a.getSampler(t,o.sampleType);i.push({binding:s++,resource:l})})),{layout:e.format.impl.bindGroupLayout,entries:i}},t}(),on=function(){function t(){}return t.shaderStage=function(t){var e=0;return 1&t&&(e|=GPUShaderStage.VERTEX),2&t&&(e|=GPUShaderStage.FRAGMENT),4&t&&(e|=GPUShaderStage.COMPUTE),e},t}(),hn=[];hn[0]="filtering",hn[1]="non-filtering",hn[2]="comparison";var ln=[];ln[0]="float",ln[1]="unfilterable-float",ln[2]="depth";var cn=new Zi,un=function(){function t(t){var e=t.device,i=this.createDescriptor(t),n=i.key,s=i.descr;this.key=cn.get(n),this.bindGroupLayout=e.wgpu.createBindGroupLayout(s)}var e=t.prototype;return e.destroy=function(){this.bindGroupLayout=null},e.loseContext=function(){},e.getTextureSlot=function(t,e){return t.bufferFormats.length+2*e},e.createDescriptor=function(t){var e=[],i="",n=0;return t.bufferFormats.forEach((function(t){var s=on.shaderStage(t.visibility);i+="#"+n+"U:"+s,e.push({binding:n++,visibility:s,buffer:{type:"uniform",hasDynamicOffset:!0}})})),t.textureFormats.forEach((function(t){var s=on.shaderStage(t.visibility),r=t.sampleType,a=t.textureDimension,o=ln[r];i+="#"+n+"T:"+s+"-"+o+"-"+a+"-false",e.push({binding:n++,visibility:s,texture:{sampleType:o,viewDimension:a,multisampled:false}});var h=hn[r];i+="#"+n+"S:"+s+"-"+h,e.push({binding:n++,visibility:s,sampler:{type:h}})})),{key:i,descr:{entries:e}}},t}(),dn=function(){function t(){this.buffer=null}var e=t.prototype;return e.destroy=function(t){this.buffer&&(this.buffer.destroy(),this.buffer=null)},e.loseContext=function(){},e.unlock=function(t,e,i,n){var s,r,a=t.wgpu;if(!this.buffer){var o=n.byteLength+3&-4;this.buffer=t.wgpu.createBuffer({size:o,usage:i|GPUBufferUsage.COPY_DST})}var h=null!=(s=n.byteOffset)?s:0,l=new Uint8Array(null!=(r=n.buffer)?r:n,h,n.byteLength),c=new Uint8Array(this.buffer.size);c.set(l),a.queue.writeBuffer(this.buffer,0,c,0,c.length)},y(t,[{key:"initialized",get:function(){return!!this.buffer}}]),t}(),fn=function(t){function e(e){var i;return(i=t.call(this)||this).format=null,i.format=1===e.format?"uint16":"uint32",i}return S(e,t),e.prototype.unlock=function(e){var i=e.device;t.prototype.unlock.call(this,i,e.usage,GPUBufferUsage.INDEX,e.storage)},e}(dn),pn=function(t,e){if(t.size!==e.size)return!1;for(var i=0;i<t.length;i++)if(t[i]!==e[i])return!1;return!0},mn=[];mn[0]="sint8",mn[mi]="uint8",mn[2]="sint16",mn[3]="uint16",mn[4]="sint32",mn[5]="uint32",mn[6]="float32";var _n=[];_n[0]="snorm8",_n[mi]="unorm8",_n[2]="snorm16",_n[3]="unorm16",_n[4]="sint32",_n[5]="uint32",_n[6]="float32";var vn=function(){function t(){this.cache=new Map}var e=t.prototype;return e.get=function(t,e){void 0===e&&(e=null);var i=this.getKey(t,e),n=this.cache.get(i);return n||(n=this.create(t,e),this.cache.set(i,n)),n},e.getKey=function(t,e){var i;return void 0===e&&(e=null),(null==t?void 0:t.renderingHashString)+"-"+(null==(i=e)?void 0:i.renderingHashString)},e.create=function(t,e){var i=[],n=function(t){for(var e=t.interleaved,n=t.instancing?"instance":"vertex",s=[],r=t.elements.length,a=0;a<r;a++){var o=t.elements[a],h=Ri[o.name],l=o.normalize?_n:mn;s.push({shaderLocation:h,offset:e?o.offset:0,format:l[o.dataType]+(o.numComponents>1?"x"+o.numComponents:"")}),e&&a!==r-1||(i.push({attributes:s,arrayStride:o.stride,stepMode:n}),s=[])}};return t&&n(t),e&&n(e),i},t}(),gn=["point-list","line-list",void 0,"line-strip","triangle-list","triangle-strip",void 0],yn=["add","subtract","reverse-subtract","min","max"],xn=["zero","one","src","one-minus-src","dst","one-minus-dst","src-alpha","src-alpha-saturated","one-minus-src-alpha","dst-alpha","one-minus-dst-alpha","constant","one-minus-constant"],Sn=["never","less","equal","less-equal","greater","not-equal","greater-equal","always"],bn=["none","back","front"],wn=["keep","zero","replace","increment-clamp","increment-wrap","decrement-clamp","decrement-wrap","invert"],Tn=[],An=function(){this.pipeline=void 0,this.hashes=void 0},Cn=function(){function t(t){this.lookupHashes=new Uint32Array(13),this.device=t,this.vertexBufferLayout=new vn,this.cache=new Map}var e=t.prototype;return e.get=function(t,e,i,n,s,r,a,o,h,l,c,u){var d,f,p,m,_,v,g,y,x=this.lookupHashes;x[0]=t.type,x[1]=n.id,x[2]=h,x[3]=o.key,x[4]=a.key,x[5]=null!=(d=null==e?void 0:e.renderingHash)?d:0,x[6]=null!=(f=null==i?void 0:i.renderingHash)?f:0,x[7]=s.impl.key,x[8]=null!=(p=null==(m=r[0])?void 0:m.key)?p:0,x[9]=null!=(_=null==(v=r[1])?void 0:v.key)?_:0,x[10]=null!=(g=null==(y=r[2])?void 0:y.key)?g:0,x[11]=l?c.key:0,x[12]=l?u.key:0;var S=Yi(x),b=this.cache.get(S);if(b)for(var w=0;w<b.length;w++){var T=b[w];if(pn(T.hashes,x))return T.pipeline}var A=gn[t.type],C=this.getPipelineLayout(r),E=this.vertexBufferLayout.get(e,i),M=new An;return M.hashes=new Uint32Array(x),M.pipeline=this.create(A,n,s,C,a,o,E,h,l,c,u),b?b.push(M):b=[M],this.cache.set(S,b),M.pipeline},e.getPipelineLayout=function(t){t.forEach((function(t){Tn.push(t.bindGroupLayout)}));var e={bindGroupLayouts:Tn},i=this.device.wgpu.createPipelineLayout(e);return Tn.length=0,i},e.getBlend=function(t){var e;return t.blend&&(e={color:{operation:yn[t.colorOp],srcFactor:xn[t.colorSrcFactor],dstFactor:xn[t.colorDstFactor]},alpha:{operation:yn[t.alphaOp],srcFactor:xn[t.alphaSrcFactor],dstFactor:xn[t.alphaDstFactor]}}),e},e.getDepthStencil=function(t,e,i,n,s){var r,a=e.depth,o=e.stencil;return(a||o)&&(r={format:e.impl.depthFormat},a?(r.depthWriteEnabled=t.write,r.depthCompare=Sn[t.func]):(r.depthWriteEnabled=!1,r.depthCompare="always"),o&&i&&(r.stencilReadMas=n.readMask,r.stencilWriteMask=n.writeMask,r.stencilFront={compare:Sn[n.func],failOp:wn[n.fail],passOp:wn[n.zpass],depthFailOp:wn[n.zfail]},r.stencilBack={compare:Sn[s.func],failOp:wn[s.fail],passOp:wn[s.zpass],depthFailOp:wn[s.zfail]})),r},e.create=function(t,e,i,n,s,r,a,o,h,l,c){var u=this.device.wgpu,d=e.impl,f={vertex:{module:d.getVertexShaderModule(),entryPoint:d.vertexEntryPoint,buffers:a},primitive:{topology:t,frontFace:"ccw",cullMode:bn[o]},depthStencil:this.getDepthStencil(r,i,h,l,c),multisample:{count:i.samples},layout:n},p=i.impl.colorAttachments;if(p.length>0){f.fragment={module:d.getFragmentShaderModule(),entryPoint:d.fragmentEntryPoint,targets:[]};var m=0;s.redWrite&&(m|=GPUColorWrite.RED),s.greenWrite&&(m|=GPUColorWrite.GREEN),s.blueWrite&&(m|=GPUColorWrite.BLUE),s.alphaWrite&&(m|=GPUColorWrite.ALPHA);var _=this.getBlend(s);p.forEach((function(t){f.fragment.targets.push({format:t.format,writeMask:m,blend:_})}))}return u.createRenderPipeline(f)},t}(),En=new Zi,Mn=function(){function t(){this.format=void 0,this.multisampledBuffer=void 0}return t.prototype.destroy=function(){var t;null==(t=this.multisampledBuffer)||t.destroy(),this.multisampledBuffer=null},t}(),Pn=function(){function t(t){var e=this;this.initialized=!1,this.key=void 0,this.colorAttachments=[],this.depthFormat=void 0,this.hasStencil=void 0,this.depthTexture=null,this.depthTextureInternal=!1,this.assignedColorTexture=null,this.renderPassDescriptor={},this.renderTarget=t,t._colorBuffers&&t._colorBuffers.forEach((function(t,i){e.setColorAttachment(i,void 0,t.impl.format)})),this.updateKey()}var e=t.prototype;return e.destroy=function(t){var e;(this.initialized=!1,this.depthTextureInternal)&&(null==(e=this.depthTexture)||e.destroy(),this.depthTexture=null);this.assignedColorTexture=null,this.colorAttachments.forEach((function(t){t.destroy()})),this.colorAttachments.length=0},e.updateKey=function(){var t=this.renderTarget,e=t.samples+":"+(t.depth?this.depthFormat:"nodepth");this.colorAttachments.forEach((function(t){e+=":"+t.format})),this.key=En.get(e)},e.setDepthFormat=function(t){this.depthFormat=t,this.hasStencil="depth24plus-stencil8"===t},e.assignColorTexture=function(t){this.assignedColorTexture=t;var e=t.createView(),i=this.renderPassDescriptor.colorAttachments[0];this.renderTarget.samples>1?i.resolveTarget=e:i.view=e,this.setColorAttachment(0,void 0,t.format),this.updateKey()},e.setColorAttachment=function(t,e,i){this.colorAttachments[t]||(this.colorAttachments[t]=new Mn),e&&(this.colorAttachments[t].multisampledBuffer=e),i&&(this.colorAttachments[t].format=i)},e.init=function(t,e){var i,n,s=t.wgpu;this.initDepthStencil(s,e),this.renderPassDescriptor.colorAttachments=[];for(var r=null!=(i=null==(n=e._colorBuffers)?void 0:n.length)?i:1,a=0;a<r;++a){var o,h=this.initColor(s,e,a),l=0===a&&(null==(o=this.colorAttachments[0])?void 0:o.format);(h.view||l)&&this.renderPassDescriptor.colorAttachments.push(h)}this.initialized=!0},e.initDepthStencil=function(t,e){var i=e.samples,n=e.width,s=e.height,r=e.depth,a=e.depthBuffer;if(r||a){if(a)this.depthTexture=a.impl.gpuTexture,this.setDepthFormat(a.impl.format);else{this.setDepthFormat("depth24plus-stencil8");var o={size:[n,s,1],dimension:"2d",sampleCount:i,format:this.depthFormat,usage:GPUTextureUsage.RENDER_ATTACHMENT};o.usage|=i>1?GPUTextureUsage.TEXTURE_BINDING:GPUTextureUsage.COPY_SRC,this.depthTexture=t.createTexture(o),this.depthTextureInternal=!0}this.renderPassDescriptor.depthStencilAttachment={view:this.depthTexture.createView()}}},e.initColor=function(t,e,i){var n={},s=e.samples,r=e.width,a=e.height,o=e.getColorBuffer(i),h=null;if(o){h=o.cubemap?o.impl.createView({dimension:"2d",baseArrayLayer:e.face,arrayLayerCount:1,mipLevelCount:1}):o.impl.createView({mipLevelCount:1})}if(s>1){var l,c,u={size:[r,a,1],dimension:"2d",sampleCount:s,format:null!=(l=null==(c=this.colorAttachments[i])?void 0:c.format)?l:o.impl.format,usage:GPUTextureUsage.RENDER_ATTACHMENT},d=t.createTexture(u);this.setColorAttachment(i,d,u.format),n.view=d.createView(),n.resolveTarget=h}else n.view=h;return n},e.setupForRenderPass=function(t){for(var e,i,n=null!=(e=null==(i=this.renderPassDescriptor.colorAttachments)?void 0:i.length)?e:0,s=0;s<n;++s){var r=this.renderPassDescriptor.colorAttachments[s],a=t.colorArrayOps[s];r.clearValue=a.clearValue,r.loadOp=a.clear?"clear":"load",r.storeOp=a.store?"store":"discard"}var o=this.renderPassDescriptor.depthStencilAttachment;o&&(o.depthClearValue=t.depthStencilOps.clearDepthValue,o.depthLoadOp=t.depthStencilOps.clearDepth?"clear":"load",o.depthStoreOp=t.depthStencilOps.storeDepth?"store":"discard",o.depthReadOnly=!1,this.hasStencil&&(o.stencilClearValue=t.depthStencilOps.clearStencilValue,o.stencilLoadOp=t.depthStencilOps.clearStencil?"clear":"load",o.stencilStoreOp=t.depthStencilOps.storeStencil?"store":"discard",o.stencilReadOnly=!1))},e.loseContext=function(){this.initialized=!1},e.resolve=function(t,e,i,n){},t}(),Rn=[];Rn[2]=1,Rn[3]=2,Rn[4]=3,Rn[5]=4,Rn[1]=1,Rn[6]=2,Rn[7]=3,Rn[8]=4,Rn[0]=1,Rn[9]=2,Rn[10]=3,Rn[11]=4,Rn[12]=8,Rn[13]=12,Rn[14]=16;var In,Ln=function(){function t(t,e,i){if(void 0===i&&(i=0),this.name=void 0,this.type=void 0,this.byteSize=void 0,this.offset=void 0,this.scopeId=void 0,this.count=void 0,this.shortName=t,this.name=i?t+"[0]":t,this.type=e,this.updateType=e,i)switch(e){case 2:this.updateType=17;break;case 3:this.updateType=21;break;case 4:this.updateType=22;break;case 5:this.updateType=23;break;case vi:this.updateType=24}this.count=i;var n=Rn[e];i&&(n=_t.roundUp(n,4)),this.byteSize=4*n,i&&(this.byteSize*=i)}return t.prototype.calculateOffset=function(t){var e=this.byteSize<=8?this.byteSize:16;this.count&&(e=16),t=_t.roundUp(t,e),this.offset=t/4},t}(),Dn=function(){function t(t,e){this.byteSize=0,this.map=new Map,this.scope=t.scope,this.uniforms=e;for(var i=0,n=0;n<e.length;n++){var s=e[n];s.calculateOffset(i),i=4*s.offset+s.byteSize,s.scopeId=this.scope.resolve(s.name),this.map.set(s.name,s)}this.byteSize=_t.roundUp(i,16)}var e=t.prototype;return e.get=function(t){return this.map.get(t)},e.getShaderDeclaration=function(t,e){var i="layout(set = "+t+", binding = "+e+", std140) uniform ub_"+wi[t]+" {\n";return this.uniforms.forEach((function(t){var e=gi[t.type];i+=" "+e+" "+t.shortName+(t.count?"["+t.count+"]":"")+";\n"})),i+"};\n"},t}(),On=0,kn=((In={})[ai]="texture2D",In[hi]="textureCube",In[li]="texture3D",In),Fn=function(t,e){this.name=t,this.visibility=e},Bn=function(t,e,i,n){void 0===i&&(i=ai),void 0===n&&(n=0),this.scopeId=void 0,this.name=t,this.visibility=e,this.textureDimension=i,this.sampleType=n},Un=function(){function t(t,e,i){var n=this;void 0===e&&(e=[]),void 0===i&&(i=[]),this.id=On++,this.device=t,this.bufferFormats=e,this.bufferFormatsMap=new Map,e.forEach((function(t,e){return n.bufferFormatsMap.set(t.name,e)})),this.textureFormats=i;var s=t.scope;this.textureFormatsMap=new Map,i.forEach((function(t,e){n.textureFormatsMap.set(t.name,e),t.scopeId=s.resolve(t.name)})),this.impl=t.createBindGroupFormatImpl(this)}var e=t.prototype;return e.destroy=function(){this.impl.destroy()},e.getTexture=function(t){var e=this.textureFormatsMap.get(t);return void 0!==e?this.textureFormats[e]:null},e.getShaderDeclarationTextures=function(t){var e="",i=this.bufferFormats.length;return this.textureFormats.forEach((function(n){var s=kn[n.textureDimension];e+="layout(set = "+t+", binding = "+i+++") uniform "+s+" "+n.name+";\nlayout(set = "+t+", binding = "+i+++") uniform sampler "+n.name+"_sampler;\n"})),e},e.loseContext=function(){},t}(),Nn=/[ \t]*(\battribute\b|\bvarying\b|\buniform\b)/g,zn=/(\battribute\b|\bvarying\b|\bout\b|\buniform\b)[ \t]*([^;]+)([;]+)/g,Vn="@@@",Gn=/([\w-]+)\[(.*?)\]/,Hn=new Set(["highp","mediump","lowp"]),Wn=new Set(["sampler2DShadow","samplerCubeShadow"]),Xn={sampler2D:ai,sampler3D:li,samplerCube:hi,samplerCubeShadow:hi,sampler2DShadow:ai,sampler2DArray:oi,sampler2DArrayShadow:oi},jn=function(t,e){this.line=t;var i=t.trim().split(/\s+/);if(Hn.has(i[0])&&(this.precision=i.shift()),this.type=i.shift(),t.includes(","),t.includes("[")){var n=i.join(" "),s=Gn.exec(n);this.name=s[1],this.arraySize=Number(s[2]),isNaN(this.arraySize)&&(e.failed=!0)}else this.name=i.shift(),this.arraySize=0;this.isSampler=-1!==this.type.indexOf("sampler")},qn=function(){function t(){}return t.run=function(e,i,n){var s=new Map,r=t.extract(i.vshader),a=t.extract(i.fshader),o=t.processAttributes(r.attributes,i.attributes,i.processingOptions),h=t.processVaryings(r.varyings,s,!0),l=t.processVaryings(a.varyings,s,!1),c=t.processOuts(a.outs),u=r.uniforms.concat(a.uniforms),d=Array.from(new Set(u)).map((function(t){return new jn(t,n)})),f=t.processUniforms(e,d,i.processingOptions,n),p=o+"\n"+h+"\n"+f.code,m=r.src.replace(Vn,p),_=l+"\n"+c+"\n"+f.code;return{vshader:m,fshader:a.src.replace(Vn,_),meshUniformBufferFormat:f.meshUniformBufferFormat,meshBindGroupFormat:f.meshBindGroupFormat}},t.extract=function(e){for(var i,n=[],s=[],r=[],a=[],o=Vn+"\n";null!==(i=Nn.exec(e));){var h=i[1];switch(h){case"attribute":case"varying":case"uniform":case"out":zn.lastIndex=i.index;var l=zn.exec(e);"attribute"===h?n.push(l[2]):"varying"===h?s.push(l[2]):"out"===h?r.push(l[2]):"uniform"===h&&a.push(l[2]),e=t.cutOut(e,i.index,zn.lastIndex,o),Nn.lastIndex=i.index+o.length,o=""}}return{src:e,attributes:n,varyings:s,outs:r,uniforms:a}},t.processUniforms=function(t,e,i,n){var s=[],r=[];e.forEach((function(t){t.isSampler?s.push(t):r.push(t)}));var a=[];r.forEach((function(t){if(!i.hasUniform(t.name)){var e=gi.indexOf(t.type),n=new Ln(t.name,e,t.arraySize);a.push(n)}}));var o=a.length?new Dn(t,a):null,h=[];o&&h.push(new Fn(Ti,3));var l=[];s.forEach((function(t){if(!i.hasTexture(t.name)){var e=0;"highp"===t.precision&&(e=1),Wn.has(t.type)&&(e=2);var n=Xn[t.type];l.push(new Bn(t.name,3,n,e))}}));var c=new Un(t,h,l),u="";return i.uniformFormats.forEach((function(t,e){t&&(u+=t.getShaderDeclaration(e,0))})),o&&(u+=o.getShaderDeclaration(0,0)),i.bindGroupFormats.forEach((function(t,e){t&&(u+=t.getShaderDeclarationTextures(e))})),{code:u+=c.getShaderDeclarationTextures(0),meshUniformBufferFormat:o,meshBindGroupFormat:c}},t.processVaryings=function(e,i,n){var s="",r=n?"out":"in";return e.forEach((function(e,a){var o=t.splitToWords(e),h=o[0],l=o[1];n?i.set(l,a):a=i.get(l),s+="layout(location = "+a+") "+r+" "+h+" "+l+";\n"})),s},t.processOuts=function(t){var e="";return t.forEach((function(t,i){e+="layout(location = "+i+") out "+t+";\n"})),e},t.getTypeCount=function(t){var e=t.substring(t.length-1),i=parseInt(e,10);return isNaN(i)?1:i},t.processAttributes=function(e,i,n){var s="";return e.forEach((function(e){var r=t.splitToWords(e),a=r[0],o=r[1];if(i.hasOwnProperty(o)){var h,l=i[o],c=Ri[l],u=n.getVertexElement(l);if(u){var d=u.dataType;if(6!==d&&!u.normalize){var f=t.getTypeCount(a),p="_private_"+o;h="vec"+f+" "+o+" = vec"+f+"("+p+");\n",o=p;var m=0===d||2===d||4===d;a=1===f?m?"int":"uint":m?"ivec"+f:"uvec"+f}}s+="layout(location = "+c+") in "+a+" "+o+";\n",h&&(s+=h)}})),s},t.splitToWords=function(t){return(t=t.replace(/\s+/g," ").trim()).split(" ")},t.cutOut=function(t,e,i,n){return t.substring(0,e)+n+t.substring(i)},t}(),Yn=function(){function t(t){this._vertexCode=void 0,this._fragmentCode=void 0,this.vertexEntryPoint="main",this.fragmentEntryPoint="main",this.shader=t;var e=t.definition;e.shaderLanguage===pi?(this._vertexCode=e.vshader,this._fragmentCode=e.fshader,this.vertexEntryPoint="vertexMain",this.fragmentEntryPoint="fragmentMain",t.ready=!0):e.processingOptions&&this.process()}var e=t.prototype;return e.destroy=function(t){this._vertexCode=null,this._fragmentCode=null},e.createShaderModule=function(t,e){return this.shader.device.wgpu.createShaderModule({code:t})},e.getVertexShaderModule=function(){return this.createShaderModule(this._vertexCode,"Vertex")},e.getFragmentShaderModule=function(){return this.createShaderModule(this._fragmentCode,"Fragment")},e.process=function(){var t=this.shader,e=qn.run(t.device,t.definition,t);this._vertexCode=this.transpile(e.vshader,"vertex",t.definition.vshader),this._fragmentCode=this.transpile(e.fshader,"fragment",t.definition.fshader),this._vertexCode&&this._fragmentCode?t.ready=!0:t.failed=!0,t.meshUniformBufferFormat=e.meshUniformBufferFormat,t.meshBindGroupFormat=e.meshBindGroupFormat},e.transpile=function(t,e,i){try{var n=this.shader.device.glslang.compileGLSL(t,e);return this.shader.device.twgsl.convertSpirV2WGSL(n)}catch(n){console.error("Failed to transpile webgl "+e+" shader ["+this.shader.label+"] to WebGPU: ["+n.message+"]",{processed:t,original:i,shader:this.shader})}},e.loseContext=function(){},e.restoreContext=function(t,e){},y(t,[{key:"vertexCode",get:function(){return this._vertexCode}},{key:"fragmentCode",get:function(){return this._fragmentCode}}]),t}(),Kn=function(){function t(){}return t.calcLevelDimension=function(t,e){return Math.max(t>>e,1)},t.calcLevelGpuSize=function(t,e,i,n){var s,r,a,o=ye.get(n),h=null!=(s=null==(r=ye.get(n))?void 0:r.size)?s:0;if(h>0)return t*e*i*h;var l=null!=(a=o.blockSize)?a:0,c=Math.floor((t+3)/4),u=Math.floor((e+3)/4),d=Math.floor((i+3)/4);return n!==me&&n!==_e||(c=Math.max(Math.floor(c/2),1)),c*u*d*l},t.calcGpuSize=function(e,i,n,s,r,a){for(var o=0;o+=t.calcLevelGpuSize(e,i,n,s),r&&(1!==e||1!==i||1!==n);)e=Math.max(e>>1,1),i=Math.max(i>>1,1),n=Math.max(n>>1,1);return o*(a?6:1)},t}(),Zn=[];Zn[0]="",Zn[1]="r8unorm",Zn[2]="rg8unorm",Zn[3]="",Zn[4]="",Zn[5]="",Zn[6]="rgba8unorm",Zn[7]="rgba8unorm",Zn[8]="bc1-rgba-unorm",Zn[9]="bc2-rgba-unorm",Zn[10]="bc3-rgba-unorm",Zn[11]="",Zn[12]="rgba16float",Zn[13]="",Zn[14]="rgba32float",Zn[15]="r32float",Zn[16]="depth32float",Zn[17]="depth24plus-stencil8",Zn[18]="rg11b10ufloat",Zn[19]="",Zn[20]="",Zn[21]="",Zn[22]="etc2-rgb8unorm",Zn[23]="etc2-rgba8unorm",Zn[24]="",Zn[25]="",Zn[26]="",Zn[27]="",Zn[28]="astc-4x4-unorm",Zn[29]="",Zn[30]="",Zn[31]="bgra8unorm";var Qn=[];Qn[0]="repeat",Qn[1]="clamp-to-edge",Qn[2]="mirror-repeat";var $n=[];$n[0]={level:"nearest",mip:"nearest"},$n[1]={level:"linear",mip:"nearest"},$n[2]={level:"nearest",mip:"nearest"},$n[3]={level:"nearest",mip:"linear"},$n[4]={level:"linear",mip:"nearest"},$n[5]={level:"linear",mip:"linear"};var Jn=function(){function t(t){this.gpuTexture=void 0,this.view=void 0,this.samplers=[],this.descr=void 0,this.format=void 0,this.texture=t,this.format=Zn[t.format],this.create(t.device)}var e=t.prototype;return e.create=function(t){var e,i=this.texture,n=t.wgpu,s=i.requiredMipLevels;this.descr={size:{width:i.width,height:i.height,depthOrArrayLayers:i.cubemap?6:1},format:this.format,mipLevelCount:s,sampleCount:1,dimension:i.volume?"3d":"2d",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|(xe(i.format)?0:GPUTextureUsage.RENDER_ATTACHMENT)|GPUTextureUsage.COPY_SRC},this.gpuTexture=n.createTexture(this.descr),this.texture.format===de&&(e={format:"depth24plus",aspect:"depth-only"}),this.view=this.createView(e)},e.destroy=function(t){},e.propertyChanged=function(t){this.samplers.length=0},e.getView=function(t){return this.uploadImmediate(t,this.texture),this.view},e.createView=function(t){var e,i,n,s,r,a,o,h=null!=t?t:{},l=this.descr,c=this.texture,u={format:null!=(e=h.format)?e:l.format,dimension:null!=(i=h.dimension)?i:c.cubemap?"cube":c.volume?"3d":"2d",aspect:null!=(n=h.aspect)?n:"all",baseMipLevel:null!=(s=h.baseMipLevel)?s:0,mipLevelCount:null!=(r=h.mipLevelCount)?r:l.mipLevelCount,baseArrayLayer:null!=(a=h.baseArrayLayer)?a:0,arrayLayerCount:null!=(o=h.arrayLayerCount)?o:l.depthOrArrayLayers};return this.gpuTexture.createView(u)},e.getSampler=function(t,e){var i=this.samplers[e];if(!i){var n=this.texture,s={addressModeU:Qn[n.addressU],addressModeV:Qn[n.addressV],addressModeW:Qn[n.addressW]};!e&&n.compareOnRead&&(e=2),2===e?(s.compare="less",s.magFilter="linear",s.minFilter="linear"):1===e||this.texture.format===le||this.texture.format===de||this.texture.format===oe?(s.magFilter="nearest",s.minFilter="nearest",s.mipmapFilter="nearest"):(s.magFilter=$n[n.magFilter].level,s.minFilter=$n[n.minFilter].level,s.mipmapFilter=$n[n.minFilter].mip);var r="linear"===s.minFilter&&"linear"===s.magFilter&&"linear"===s.mipmapFilter;s.maxAnisotropy=r?_t.clamp(Math.round(n._anisotropy),1,t.maxTextureAnisotropy):1,i=t.wgpu.createSampler(s),this.samplers[e]=i}return i},e.loseContext=function(){},e.uploadImmediate=function(t,e){(e._needsUpload||e._needsMipmapsUpload)&&(this.uploadData(t),e._needsUpload=!1,e._needsMipmapsUpload=!1)},e.uploadData=function(t){var e=this.texture;if(e._levels){for(var i=!1,n=e.requiredMipLevels,s=0;s<n;s++){var r=e._levels[s];if(r)if(e.cubemap)for(var a=0;a<6;a++){var o=r[a];o&&(this.isExternalImage(o)?(this.uploadExternalImage(t,o,s,a),i=!0):ArrayBuffer.isView(o)&&(this.uploadTypedArrayData(t,o,s,a),i=!0))}else e._volume||(this.isExternalImage(r)?(this.uploadExternalImage(t,r,s,0),i=!0):ArrayBuffer.isView(r)&&(this.uploadTypedArrayData(t,r,s,0),i=!0))}i&&e.mipmaps&&!xe(e.format)&&t.mipmapRenderer.generate(this)}},e.isExternalImage=function(t){return t instanceof ImageBitmap||t instanceof HTMLVideoElement||t instanceof HTMLCanvasElement||t instanceof OffscreenCanvas},e.uploadExternalImage=function(t,e,i,n){var s={source:e,origin:[0,0],flipY:!1},r={texture:this.gpuTexture,mipLevel:i,origin:[0,0,n],aspect:"all"},a={width:this.descr.size.width,height:this.descr.size.height,depthOrArrayLayers:1};t.submit(),e instanceof HTMLCanvasElement&&e.getContext("2d"),t.wgpu.queue.copyExternalImageToTexture(s,r,a)},e.uploadTypedArrayData=function(t,e,i,n){var s=this.texture,r=t.wgpu,a={texture:this.gpuTexture,origin:[0,0,n],mipLevel:i},o=Kn.calcLevelDimension(s.width,i),h=Kn.calcLevelDimension(s.height,i);Kn.calcLevelGpuSize(o,h,1,s.format);var l,c,u=ye.get(s.format);if(u.size)l={offset:0,bytesPerRow:u.size*o,rowsPerImage:h},c={width:o,height:h};else if(u.blockSize){var d=function(t){return Math.floor((t+3)/4)};l={offset:0,bytesPerRow:u.blockSize*d(o),rowsPerImage:d(h)},c={width:Math.max(4,o),height:Math.max(4,h)}}t.submit(),r.queue.writeTexture(a,e,l,c)},t}(),ts=function(t){function e(e){return t.call(this)||this}S(e,t);var i=e.prototype;return i.destroy=function(e){t.prototype.destroy.call(this,e)},i.unlock=function(e){var i=e.device;t.prototype.unlock.call(this,i,void 0,GPUBufferUsage.UNIFORM,e.storage)},e}(dn),es=function(t){function e(e,i){return t.call(this)||this}S(e,t);var i=e.prototype;return i.destroy=function(e){t.prototype.destroy.call(this,e)},i.unlock=function(e){var i=e.device;t.prototype.unlock.call(this,i,e.usage,GPUBufferUsage.VERTEX,e.storage)},e}(dn),is=/[ \t]*#(ifn?def|if|endif|else|elif|define|undef|extension)/g,ns=/define[ \t]+([^\n]+)\r?(?:\n|$)/g,ss=/extension[ \t]+([\w-]+)[ \t]*:[ \t]*(enable|require)/g,rs=/undef[ \t]+([^\n]+)\r?(?:\n|$)/g,as=/(ifdef|ifndef|if)[ \t]*([^\r\n]+)\r?\n/g,os=/(endif|else|elif)([ \t]+[^\r\n]+)?\r?(?:\n|$)/g,hs=/([\w-]+)/,ls=/(!|\s)?defined\(([\w-]+)\)/,cs=/[><=|&+-]/g,us=function(){function t(){}return t.run=function(t,e){void 0===e&&(e=!1),t=(t=t.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm,"$1")).split(/\r?\n/).map((function(t){return t.trimEnd()})).join("\n");var i=new Map;if(e){var n=new Map,s=t.match(/(pcFragColor[1-8])\b/g);null==s||s.forEach((function(t){var e,i=parseInt(t.charAt(t.length-1),10);n.set(i,(null!=(e=n.get(i))?e:0)+1)})),n.forEach((function(t,e){1===t&&i.set("REMOVE_COLOR_ATTACHMENT_"+e,"")}))}t=this._preprocess(t,i);var r=new Map;return i.forEach((function(t,e){Number.isInteger(parseFloat(t))&&!t.includes(".")&&r.set(e,t)})),null!==t&&(t=t.split(/\r?\n/).map((function(t){return""===t.trim()?"":t})).map((function(t){return r.forEach((function(e,i){t=t.replace(new RegExp("\\["+i+"\\]","g"),"["+e+"]")})),t})).join("\n"),t=t.replace(/(\n\n){3,}/gm,"\n\n")),t},t._preprocess=function(e,i){void 0===i&&(i=new Map);for(var n,s=e,r=[],a=!1;null!==(n=is.exec(e));){var o=n[1];switch(o){case"define":ns.lastIndex=n.index;var h=ns.exec(e);a||(a=null===h);var l=h[1];hs.lastIndex=h.index;var c=hs.exec(l)[1],u=l.substring(c.length).trim();""===u&&(u="true"),t._keep(r)&&i.set(c,u),is.lastIndex=h.index+h[0].length;break;case"undef":rs.lastIndex=n.index;var d=rs.exec(e),f=d[1].trim();t._keep(r)&&i.delete(f),is.lastIndex=d.index+d[0].length;break;case"extension":ss.lastIndex=n.index;var p=ss.exec(e);if(a||(a=null===p),p){var m=p[1];t._keep(r)&&i.set(m,"true")}is.lastIndex=p.index+p[0].length;break;case"ifdef":case"ifndef":case"if":as.lastIndex=n.index;var _=as.exec(e),v=_[2],g=t.evaluate(v,i);a||(a=g.error);var y=g.result;"ifndef"===o&&(y=!y),r.push({anyKeep:y,keep:y,start:n.index,end:as.lastIndex}),is.lastIndex=_.index+_[0].length;break;case"endif":case"else":case"elif":os.lastIndex=n.index;var x=os.exec(e),S=r.pop(),b=S.keep?e.substring(S.end,n.index):"";e=e.substring(0,S.start)+b+e.substring(os.lastIndex),is.lastIndex=S.start+b.length;var w=x[1];if("else"===w||"elif"===w){var T=!1;if(!S.anyKeep)if("else"===w)T=!S.keep;else{var A=t.evaluate(x[2],i);T=A.result,a||(a=A.error)}r.push({anyKeep:S.anyKeep||T,keep:T,start:is.lastIndex,end:is.lastIndex})}}}return a?(console.warn("Failed to preprocess shader: ",{source:s}),s):e},t._keep=function(t){for(var e=0;e<t.length;e++)if(!t[e].keep)return!1;return!0},t.evaluate=function(t,e){var i=null===cs.exec(t),n=!1,s=ls.exec(t);s&&(n="!"===s[1],t=s[2]),t=t.trim();var r=e.has(t);return n&&(r=!r),{result:r,error:!i}},t}(),ds=0,fs=function(){function t(t,e){this.meshUniformBufferFormat=void 0,this.meshBindGroupFormat=void 0,this.id=ds++,this.device=t,this.definition=e,this.name=e.name||"Untitled",e.vshader=us.run(e.vshader),e.fshader=us.run(e.fshader,t.isWebGL2),this.init(),this.impl=t.createShaderImpl(this)}var e=t.prototype;return e.init=function(){this.ready=!1,this.failed=!1},e.destroy=function(){this.device.onDestroyShader(this),this.impl.destroy(this)},e.loseContext=function(){this.init(),this.impl.loseContext()},e.restoreContext=function(){this.impl.restoreContext(this.device,this)},y(t,[{key:"label",get:function(){return"Shader Id "+this.id+" "+this.name}}]),t}(),ps=0,ms=function(){function t(t,e,i){this.renderVersionUpdated=-1,this.uniformBuffers=void 0,this.uniformBufferOffsets=[],this.id=ps++,this.device=t,this.format=e,this.dirty=!0,this.impl=t.createBindGroupImpl(this),this.textures=[],this.uniformBuffers=[],this.defaultUniformBuffer=i,i&&this.setUniformBuffer(Ti,i)}var e=t.prototype;return e.destroy=function(){this.impl.destroy(),this.impl=null,this.format=null,this.defaultUniformBuffer=null},e.setUniformBuffer=function(t,e){var i=this.format.bufferFormatsMap.get(t);this.uniformBuffers[i]!==e&&(this.uniformBuffers[i]=e,this.dirty=!0)},e.setTexture=function(t,e){var i=this.format.textureFormatsMap.get(t);this.textures[i]!==e?(this.textures[i]=e,this.dirty=!0):this.renderVersionUpdated<e.renderVersionDirty&&(this.dirty=!0)},e.update=function(){for(var t=this.format.textureFormats,e=0;e<t.length;e++){var i=t[e],n=i.scopeId.value;this.setTexture(i.name,n)}this.uniformBufferOffsets.length=this.uniformBuffers.length;for(var s=0;s<this.uniformBuffers.length;s++){var r=this.uniformBuffers[s];this.uniformBufferOffsets[s]=r.offset,this.renderVersionUpdated<r.renderVersionDirty&&(this.dirty=!0)}this.dirty&&(this.dirty=!1,this.renderVersionUpdated=this.device.renderVersion,this.impl.update(this))},t}(),_s=function(){this.gpuBuffer=void 0,this.stagingBuffer=void 0,this.offset=void 0,this.size=void 0},vs=function(){this.storage=void 0,this.gpuBuffer=void 0,this.offset=void 0},gs=function(){function t(t,e,i){this.bufferSize=void 0,this.gpuBuffers=[],this.stagingBuffers=[],this.usedBuffers=[],this.activeBuffer=null,this.device=t,this.bufferSize=e,this.bufferAlignment=i}var e=t.prototype;return e.destroy=function(){var t=this;this.gpuBuffers.forEach((function(e){e.destroy(t.device)})),this.gpuBuffers=null,this.stagingBuffers.forEach((function(e){e.destroy(t.device)})),this.stagingBuffers=null,this.usedBuffers=null,this.activeBuffer=null},e.alloc=function(t,e){if(this.activeBuffer){var i=_t.roundUp(this.activeBuffer.size,this.bufferAlignment);this.bufferSize-i<e&&this.scheduleSubmit()}if(!this.activeBuffer){var n=this.gpuBuffers.pop();n||(n=this.createBuffer(this.device,this.bufferSize,!1));var s=this.stagingBuffers.pop();s||(s=this.createBuffer(this.device,this.bufferSize,!0)),this.activeBuffer=new _s,this.activeBuffer.stagingBuffer=s,this.activeBuffer.gpuBuffer=n,this.activeBuffer.offset=0,this.activeBuffer.size=0}var r=this.activeBuffer,a=_t.roundUp(r.size,this.bufferAlignment);t.gpuBuffer=r.gpuBuffer,t.offset=a,t.storage=r.stagingBuffer.alloc(a,e),r.size=a+e},e.scheduleSubmit=function(){this.activeBuffer&&(this.usedBuffers.push(this.activeBuffer),this.activeBuffer=null)},e.submit=function(){this.scheduleSubmit()},t}(),ys=[];ys[2]=function(t,e,i){t.storageFloat32[i]=e},ys[3]=function(t,e,i){var n=t.storageFloat32;n[i]=e[0],n[i+1]=e[1]},ys[4]=function(t,e,i){var n=t.storageFloat32;n[i]=e[0],n[i+1]=e[1],n[i+2]=e[2]},ys[5]=function(t,e,i){var n=t.storageFloat32;n[i]=e[0],n[i+1]=e[1],n[i+2]=e[2],n[i+3]=e[3]},ys[1]=function(t,e,i){t.storageInt32[i]=e},ys[6]=function(t,e,i){var n=t.storageInt32;n[i]=e[0],n[i+1]=e[1]},ys[7]=function(t,e,i){var n=t.storageInt32;n[i]=e[0],n[i+1]=e[1],n[i+2]=e[2]},ys[8]=function(t,e,i){var n=t.storageInt32;n[i]=e[0],n[i+1]=e[1],n[i+2]=e[2],n[i+3]=e[3]},ys[12]=function(t,e,i){var n=t.storageFloat32;n[i]=e[0],n[i+1]=e[1],n[i+4]=e[2],n[i+5]=e[3],n[i+8]=e[4],n[i+9]=e[5]},ys[13]=function(t,e,i){var n=t.storageFloat32;n[i]=e[0],n[i+1]=e[1],n[i+2]=e[2],n[i+4]=e[3],n[i+5]=e[4],n[i+6]=e[5],n[i+8]=e[6],n[i+9]=e[7],n[i+10]=e[8]},ys[17]=function(t,e,i,n){for(var s=t.storageFloat32,r=0;r<n;r++)s[i+4*r]=e[r]},ys[21]=function(t,e,i,n){for(var s=t.storageFloat32,r=0;r<n;r++)s[i+4*r]=e[2*r],s[i+4*r+1]=e[2*r+1]},ys[22]=function(t,e,i,n){for(var s=t.storageFloat32,r=0;r<n;r++)s[i+4*r]=e[3*r],s[i+4*r+1]=e[3*r+1],s[i+4*r+2]=e[3*r+2]};var xs=function(){function t(t,e,i){if(void 0===i&&(i=!0),this.device=void 0,this.persistent=void 0,this.allocation=void 0,this.storageFloat32=void 0,this.storageInt32=void 0,this.renderVersionDirty=0,this.device=t,this.format=e,this.persistent=i,i){this.impl=t.createUniformBufferImpl(this);var n=new ArrayBuffer(e.byteSize);this.assignStorage(new Int32Array(n)),t._vram.ub+=this.format.byteSize}else this.allocation=new vs}var e=t.prototype;return e.destroy=function(){if(this.persistent){var t=this.device;this.impl.destroy(t),t._vram.ub-=this.format.byteSize}},e.assignStorage=function(t){this.storageInt32=t,this.storageFloat32=new Float32Array(t.buffer,t.byteOffset,t.byteLength/4)},e.loseContext=function(){var t;null==(t=this.impl)||t.loseContext()},e.setUniform=function(t){var e=t.offset,i=t.scopeId.value;if(null!=i){var n=ys[t.updateType];n?n(this,i,e,t.count):this.storageFloat32.set(i,e)}},e.set=function(t){var e=this.format.map.get(t);e&&this.setUniform(e)},e.update=function(){var t=this.persistent;if(!t){var e=this.allocation,i=e.gpuBuffer;this.device.dynamicBuffers.alloc(e,this.format.byteSize),this.assignStorage(e.storage),i!==e.gpuBuffer&&(this.renderVersionDirty=this.device.renderVersion)}for(var n=this.format.uniforms,s=0;s<n.length;s++)this.setUniform(n[s]);t?this.impl.unlock(this):(this.storageFloat32=null,this.storageInt32=null)},y(t,[{key:"offset",get:function(){return this.persistent?0:this.allocation.offset}}]),t}(),Ss={type:be,base:0,count:4,indexed:!1},bs=function(){function t(t){var e="\n\n struct ub_mesh {\n color : vec4f,\n depth: f32\n }\n\n @group(0) @binding(0) var<uniform> ubMesh : ub_mesh;\n\n var<private> pos : array<vec2f, 4> = array<vec2f, 4>(\n vec2(-1.0, 1.0), vec2(1.0, 1.0),\n vec2(-1.0, -1.0), vec2(1.0, -1.0)\n );\n\n struct VertexOutput {\n @builtin(position) position : vec4f\n }\n\n @vertex\n fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput {\n var output : VertexOutput;\n output.position = vec4(pos[vertexIndex], ubMesh.depth, 1.0);\n return output;\n }\n\n @fragment\n fn fragmentMain() -> @location(0) vec4f {\n return ubMesh.color;\n }\n ";this.shader=new fs(t,{name:"WebGPUClearRendererShader",shaderLanguage:pi,vshader:e,fshader:e}),this.uniformBuffer=new xs(t,new Dn(t,[new Ln("color",5),new Ln("depth",2)]),!1);var i=new Un(t,[new Fn(Ti,3)]);this.bindGroup=new ms(t,i,this.uniformBuffer),this.colorData=new Float32Array(4),this.colorId=t.scope.resolve("color"),this.depthId=t.scope.resolve("depth")}var e=t.prototype;return e.destroy=function(){this.shader.destroy(),this.shader=null,this.uniformBuffer.destroy(),this.uniformBuffer=null,this.bindGroup.destroy(),this.bindGroup=null},e.clear=function(t,e,i,n){var s,r=null!=(s=(i=i||n).flags)?s:n.flags;if(0!==r){if(1&r&&e.colorBuffer){var a,o=null!=(a=i.color)?a:n.color;this.colorData.set(o),t.setBlendState(Ui.NOBLEND)}else t.setBlendState(Ui.NOWRITE);if(this.colorId.setValue(this.colorData),2&r&&e.depth){var h,l=null!=(h=i.depth)?h:n.depth;this.depthId.setValue(l),t.setDepthState(Ni.WRITEDEPTH)}else this.depthId.setValue(1),t.setDepthState(Ni.NODEPTH);4&r&&e.stencil,t.setCullMode(se),t.setShader(this.shader);var c=this.bindGroup;c.defaultUniformBuffer.update(),c.update(),t.setBindGroup(0,c),t.draw(Ss)}},t}(),ws=function(){function t(t){this.device=void 0,this.device=t;var e="\n \n var<private> pos : array<vec2f, 4> = array<vec2f, 4>(\n vec2(-1.0, 1.0), vec2(1.0, 1.0),\n vec2(-1.0, -1.0), vec2(1.0, -1.0)\n );\n\n struct VertexOutput {\n @builtin(position) position : vec4f,\n @location(0) texCoord : vec2f\n };\n\n @vertex\n fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput {\n var output : VertexOutput;\n output.texCoord = pos[vertexIndex] * vec2f(0.5, -0.5) + vec2f(0.5);\n output.position = vec4f(pos[vertexIndex], 0, 1);\n return output;\n }\n\n @group(0) @binding(0) var imgSampler : sampler;\n @group(0) @binding(1) var img : texture_2d<f32>;\n\n @fragment\n fn fragmentMain(@location(0) texCoord : vec2f) -> @location(0) vec4f {\n return textureSample(img, imgSampler, texCoord);\n }\n ";this.shader=new fs(t,{name:"WebGPUMipmapRendererShader",shaderLanguage:pi,vshader:e,fshader:e}),this.minSampler=t.wgpu.createSampler({minFilter:"linear"})}var e=t.prototype;return e.destroy=function(){this.shader.destroy(),this.shader=null},e.generate=function(t){var e,i=t.descr;if(!(i.mipLevelCount<=1||t.texture.volume)){for(var n=this.device,s=n.wgpu,r=this.shader.impl,a=s.createRenderPipeline({layout:"auto",vertex:{module:r.getVertexShaderModule(),entryPoint:r.vertexEntryPoint},fragment:{module:r.getFragmentShaderModule(),entryPoint:r.fragmentEntryPoint,targets:[{format:i.format}]},primitive:{topology:"triangle-strip"}}),o=t.texture.cubemap?6:1,h=[],l=0;l<o;l++)h.push(t.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:l}));for(var c=null!=(e=n.commandEncoder)?e:s.createCommandEncoder(),u=1;u<i.mipLevelCount;u++)for(var d=0;d<o;d++){var f=t.createView({dimension:"2d",baseMipLevel:u,mipLevelCount:1,baseArrayLayer:d}),p=c.beginRenderPass({colorAttachments:[{view:f,loadOp:"clear",storeOp:"store"}]}),m=s.createBindGroup({layout:a.getBindGroupLayout(0),entries:[{binding:0,resource:this.minSampler},{binding:1,resource:h[d]}]});p.setPipeline(a),p.setBindGroup(0,m),p.draw(4),p.end(),h[d]=f}if(!n.commandEncoder){var _=c.finish();n.addCommandBuffer(_)}n.pipeline=null}},t}(),Ts=function(t){function e(e,i,n){var s;return(s=t.call(this,e)||this).buffer=null,s.mappedRange=null,s.buffer=e.wgpu.createBuffer({size:i,usage:n?GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,mappedAtCreation:n}),n&&s.onAvailable(),e._vram.ub+=i,s}S(e,t);var i=e.prototype;return i.destroy=function(t){t._vram.ub-=this.buffer.size,this.buffer.destroy(),this.buffer=null},i.onAvailable=function(){this.mappedRange=this.buffer.getMappedRange()},i.alloc=function(t,e){return new Int32Array(this.mappedRange,t,e/4)},e}((function(t){this.device=void 0,this.device=t})),As=function(t){function e(){for(var e,i=arguments.length,n=new Array(i),s=0;s<i;s++)n[s]=arguments[s];return(e=t.call.apply(t,[this].concat(n))||this).pendingStagingBuffers=[],e}S(e,t);var i=e.prototype;return i.createBuffer=function(t,e,i){return new Ts(t,e,i)},i.submit=function(){t.prototype.submit.call(this);var e=this.usedBuffers.length;if(e){for(var i=this.device,n=this.gpuBuffers,s=i.wgpu.createCommandEncoder(),r=e-1;r>=0;r--){var a=this.usedBuffers[r],o=a.stagingBuffer,h=a.gpuBuffer,l=a.offset,c=a.size,u=o.buffer;u.unmap(),s.copyBufferToBuffer(u,l,h.buffer,l,c),n.push(h)}var d=s.finish();i.addCommandBuffer(d,!0);for(var f=0;f<e;f++){var p=this.usedBuffers[f].stagingBuffer;this.pendingStagingBuffers.push(p)}this.usedBuffers.length=0}},i.onCommandBuffersSubmitted=function(){var t=this,e=this.pendingStagingBuffers.length;if(e){for(var i=function(){var e=t.pendingStagingBuffers[n];e.buffer.mapAsync(GPUMapMode.WRITE).then((function(){t.stagingBuffers&&(e.onAvailable(),t.stagingBuffers.push(e))}))},n=0;n<e;n++)i();this.pendingStagingBuffers.length=0}},e}(gs),Cs=function(){function t(){this.frameAllocations=[],this.pastFrameAllocations=new Map,this._enabled=!1,this._enableRequest=!1,this._frameTime=0}var e=t.prototype;return e.loseContext=function(){this.pastFrameAllocations.clear()},e.processEnableRequest=function(){this._enableRequest!==this._enabled&&(this._enabled=this._enableRequest,this._enabled||(this._frameTime=0))},e.request=function(t){this.pastFrameAllocations.set(t,this.frameAllocations),this.frameAllocations=[]},e.report=function(t,e){if(e){var i=this.pastFrameAllocations.get(t);if(e.length>0&&(this._frameTime=e[0]),E.get(l))for(var n=0;n<i.length;++n)i[n]}this.pastFrameAllocations.delete(t)},e.getSlot=function(t){var e=this.frameAllocations.length;return this.frameAllocations.push(t),e},y(t,[{key:"enabled",get:function(){return this._enableRequest},set:function(t){this._enableRequest=t}},{key:"slotCount",get:function(){return this.frameAllocations.length}}]),t}(),Es=function(){function t(t,e,i){this.querySet=void 0,this.stagingBuffers=[],this.activeStagingBuffer=null,this.bytesPerSlot=void 0,this.device=t,this.capacity=i,this.bytesPerSlot=e?8:4;var n=t.wgpu;this.querySet=n.createQuerySet({type:e?"timestamp":"occlusion",count:i}),this.queryBuffer=n.createBuffer({size:this.bytesPerSlot*i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST})}var e=t.prototype;return e.destroy=function(){var t,e;null==(t=this.querySet)||t.destroy(),this.querySet=null,null==(e=this.queryBuffer)||e.destroy(),this.queryBuffer=null,this.activeStagingBuffer=null,this.stagingBuffers.forEach((function(t){t.destroy()})),this.stagingBuffers=null},e.getStagingBuffer=function(){var t=this.stagingBuffers.pop();return t||(t=this.device.wgpu.createBuffer({size:this.queryBuffer.size,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})),t},e.resolve=function(t){var e=this.device,i=e.wgpu.createCommandEncoder();i.resolveQuerySet(this.querySet,0,t,this.queryBuffer,0);var n=this.getStagingBuffer();this.activeStagingBuffer=n,i.copyBufferToBuffer(this.queryBuffer,0,n,0,this.bytesPerSlot*t);var s=i.finish();e.addCommandBuffer(s)},e.request=function(t,e){var i=this,n=this.activeStagingBuffer;return this.activeStagingBuffer=null,n.mapAsync(GPUMapMode.READ).then((function(){for(var s=new BigInt64Array(n.getMappedRange()),r=[],a=0;a<t;a++)r.push(1e-6*Number(s[2*a+1]-s[2*a]));return n.unmap(),i.stagingBuffers.push(n),{renderVersion:e,timings:r}}))},t}(),Ms=function(t){function e(e){var i;return(i=t.call(this)||this).device=void 0,i.frameGPUMarkerSlot=void 0,i.device=e,i.timestampQueriesSet=e.supportsTimestampQuery?new Es(e,!0,512):null,i}S(e,t);var i=e.prototype;return i.destroy=function(){var t;null==(t=this.timestampQueriesSet)||t.destroy(),this.timestampQueriesSet=null},i.frameMarker=function(t){if(this.timestampQueriesSet){var e=this.device.wgpu.createCommandEncoder();this.frameGPUMarkerSlot=t?this.getSlot("GpuFrame"):this.frameGPUMarkerSlot,e.writeTimestamp(this.timestampQueriesSet.querySet,2*this.frameGPUMarkerSlot+(t?0:1));var i=e.finish();this.device.addCommandBuffer(i,t)}},i.frameStart=function(){this.processEnableRequest(),this._enabled&&this.frameMarker(!0)},i.frameEnd=function(){var t;this._enabled&&(this.frameMarker(!1),null==(t=this.timestampQueriesSet)||t.resolve(2*this.slotCount))},i.request=function(){var e=this;if(this._enabled){var i,n=this.device.renderVersion;null==(i=this.timestampQueriesSet)||i.request(this.slotCount,n).then((function(t){e.report(t.renderVersion,t.timings)})),t.prototype.request.call(this,n)}},e}(Cs),Ps=function(){function t(t){this.device=void 0,this.pipelineCache=new Map,this.device=t;var e="\n \n var<private> pos : array<vec2f, 4> = array<vec2f, 4>(\n vec2(-1.0, 1.0), vec2(1.0, 1.0), vec2(-1.0, -1.0), vec2(1.0, -1.0)\n );\n\n struct VertexOutput {\n @builtin(position) position : vec4f,\n };\n\n @vertex\n fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput {\n var output : VertexOutput;\n output.position = vec4f(pos[vertexIndex], 0, 1);\n return output;\n }\n\n @group(0) @binding(0) var img : texture_depth_multisampled_2d;\n\n @fragment\n fn fragmentMain(@builtin(position) fragColor: vec4f) -> @location(0) vec4f {\n // load th depth value from sample index 0\n var depth = textureLoad(img, vec2i(fragColor.xy), 0u);\n return vec4<f32>(depth, 0.0, 0.0, 0.0);\n }\n ";this.shader=new fs(t,{name:"WebGPUResolverDepthShader",shaderLanguage:pi,vshader:e,fshader:e})}var e=t.prototype;return e.destroy=function(){this.shader.destroy(),this.shader=null,this.pipelineCache=null},e.getPipeline=function(t){var e=this.pipelineCache.get(t);return e||(e=this.createPipeline(t),this.pipelineCache.set(t,e)),e},e.createPipeline=function(t){var e=this.shader.impl;return this.device.wgpu.createRenderPipeline({layout:"auto",vertex:{module:e.getVertexShaderModule(),entryPoint:e.vertexEntryPoint},fragment:{module:e.getFragmentShaderModule(),entryPoint:e.fragmentEntryPoint,targets:[{format:t}]},primitive:{topology:"triangle-strip"}})},e.resolveDepth=function(t,e,i){for(var n=this.device,s=n.wgpu,r=this.getPipeline(i.format),a=e.depthOrArrayLayers,o=0;o<a;o++){var h=e.createView({dimension:"2d",aspect:"depth-only",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:o}),l=i.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:o}),c=t.beginRenderPass({colorAttachments:[{view:l,loadOp:"clear",storeOp:"store"}]}),u=s.createBindGroup({layout:r.getBindGroupLayout(0),entries:[{binding:0,resource:h}]});c.setPipeline(r),c.setBindGroup(0,u),c.draw(4),c.end()}n.pipeline=null},t}(),Rs=function(t){function e(e,i){var n,s,r;return void 0===i&&(i={}),(r=t.call(this,e,i)||this).renderPipeline=new Cn(w(r)),r.clearRenderer=void 0,r.mipmapRenderer=void 0,r.pipeline=void 0,r.bindGroupFormats=[],r.commandEncoder=void 0,r.commandBuffers=[],r.limits=void 0,(i=r.initOptions).alpha=null==(n=i.alpha)||n,r.backBufferAntialias=null!=(s=i.antialias)&&s,r.isWebGPU=!0,r._deviceType=Si,r.setupPassEncoderDefaults(),r}S(e,t);var i,n=e.prototype;return n.destroy=function(){this.clearRenderer.destroy(),this.clearRenderer=null,this.mipmapRenderer.destroy(),this.mipmapRenderer=null,this.resolver.destroy(),this.resolver=null,t.prototype.destroy.call(this)},n.initDeviceCaps=function(){this.disableParticleSystem=!0;var t=this.gpuAdapter.limits;this.limits=t,this.precision="highp",this.maxPrecision="highp",this.maxSamples=4,this.maxTextures=16,this.maxTextureSize=t.maxTextureDimension2D,this.maxCubeMapSize=t.maxTextureDimension2D,this.maxVolumeSize=t.maxTextureDimension3D,this.maxColorAttachments=t.maxColorAttachments,this.maxPixelRatio=1,this.maxAnisotropy=16,this.supportsInstancing=!0,this.supportsUniformBuffers=!0,this.supportsVolumeTextures=!0,this.supportsBoneTextures=!0,this.supportsMorphTargetTexturesCore=!0,this.supportsAreaLights=!0,this.supportsDepthShadow=!0,this.supportsGpuParticles=!1,this.supportsMrt=!0,this.extUintElement=!0,this.extTextureFloat=!0,this.textureFloatRenderable=!0,this.extTextureHalfFloat=!0,this.textureHalfFloatRenderable=!0,this.textureHalfFloatUpdatable=!0,this.boneLimit=1024,this.supportsImageBitmap=!0,this.extStandardDerivatives=!0,this.extBlendMinmax=!0,this.areaLightLutFormat=this.textureFloatFilterable?le:7,this.supportsTextureFetch=!0,this.samples=this.backBufferAntialias?4:1},n.initWebGpu=(i=v(m().mark((function t(e,i){var n,s,r,a,o,h,l=this;return m().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(window.navigator.gpu){t.next=2;break}throw new Error("Unable to retrieve GPU. Ensure you are using a browser that supports WebGPU rendering.");case 2:return t.next=4,Promise.all([import(""+i).then((function(t){return twgsl(i.replace(".js",".wasm"))})),import(""+e).then((function(t){return t.default()}))]);case 4:return n=t.sent,this.twgsl=n[0],this.glslang=n[1],s={powerPreference:"default"!==this.initOptions.powerPreference?this.initOptions.powerPreference:void 0},t.next=10,window.navigator.gpu.requestAdapter(s);case 10:return this.gpuAdapter=t.sent,r=[],a=function(t){var e=l.gpuAdapter.features.has(t);return e&&r.push(t),e},this.textureFloatFilterable=a("float32-filterable"),this.extCompressedTextureS3TC=a("texture-compression-bc"),this.extCompressedTextureETC=a("texture-compression-etc2"),this.extCompressedTextureASTC=a("texture-compression-astc"),this.supportsTimestampQuery=a("timestamp-query"),o={requiredFeatures:r,requiredLimits:{},defaultQueue:{label:"Default Queue"}},t.next=21,this.gpuAdapter.requestDevice(o);case 21:return this.wgpu=t.sent,this.initDeviceCaps(),this.gpuContext=this.canvas.getContext("webgpu"),h=navigator.gpu.getPreferredCanvasFormat(),this.backBufferFormat="rgba8unorm"===h?7:31,this.canvasConfig={device:this.wgpu,colorSpace:"srgb",alphaMode:this.initOptions.alpha?"premultiplied":"opaque",format:h,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST,viewFormats:[]},this.gpuContext.configure(this.canvasConfig),this.createBackbuffer(),this.clearRenderer=new bs(this),this.mipmapRenderer=new ws(this),this.resolver=new Ps(this),this.postInit(),t.abrupt("return",this);case 34:case"end":return t.stop()}}),t,this)}))),function(t,e){return i.apply(this,arguments)}),n.postInit=function(){t.prototype.postInit.call(this),this.gpuProfiler=new Ms(this),this.dynamicBuffers=new As(this,1048576,this.limits.minUniformBufferOffsetAlignment)},n.createBackbuffer=function(){this.supportsStencil=this.initOptions.stencil,this.backBuffer=new rn({name:"WebgpuFramebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples})},n.frameStart=function(){t.prototype.frameStart.call(this),this.gpuProfiler.frameStart(),this.submit();var e=this.gpuContext.getCurrentTexture();this.backBufferSize.x===e.width&&this.backBufferSize.y===e.height||(this.backBufferSize.set(e.width,e.height),this.backBuffer.destroy(),this.backBuffer=null,this.createBackbuffer());var i=this.backBuffer,n=i.impl;n.setColorAttachment(0,void 0,e.format),this.initRenderTarget(i),n.assignColorTexture(e)},n.frameEnd=function(){t.prototype.frameEnd.call(this),this.gpuProfiler.frameEnd(),this.submit(),this.gpuProfiler.request()},n.createUniformBufferImpl=function(t){return new ts(t)},n.createVertexBufferImpl=function(t,e){return new es(t,e)},n.createIndexBufferImpl=function(t){return new fn(t)},n.createShaderImpl=function(t){return new Yn(t)},n.createTextureImpl=function(t){return new Jn(t)},n.createRenderTargetImpl=function(t){return new Pn(t)},n.createBindGroupFormatImpl=function(t){return new un(t)},n.createBindGroupImpl=function(t){return new an},n.setBindGroup=function(t,e){this.passEncoder&&(this.passEncoder.setBindGroup(t,e.impl.bindGroup,e.uniformBufferOffsets),this.bindGroupFormats[t]=e.format.impl)},n.submitVertexBuffer=function(t,e){for(var i=t.format.elements,n=i.length,s=t.impl.buffer,r=0;r<n;r++)this.passEncoder.setVertexBuffer(e+r,s,i[r].offset);return n},n.draw=function(t,e,i){if(void 0===e&&(e=1),this.shader.ready&&!this.shader.failed){var n=this.passEncoder,s=this.vertexBuffers[0],r=this.vertexBuffers[1];if(this.vertexBuffers.length=0,s){var a=this.submitVertexBuffer(s,0);r&&this.submitVertexBuffer(r,a)}var o=this.renderPipeline.get(t,null==s?void 0:s.format,null==r?void 0:r.format,this.shader,this.renderTarget,this.bindGroupFormats,this.blendState,this.depthState,this.cullMode,this.stencilEnabled,this.stencilFront,this.stencilBack);this.pipeline!==o&&(this.pipeline=o,n.setPipeline(o));var h=this.indexBuffer;h?(this.indexBuffer=null,n.setIndexBuffer(h.impl.buffer,h.impl.format),n.drawIndexed(t.count,e,0,0,0)):n.draw(t.count,e,0,0)}},n.setShader=function(t){return this.shader=t,!0},n.setBlendState=function(t){this.blendState.copy(t)},n.setDepthState=function(t){this.depthState.copy(t)},n.setStencilState=function(t,e){if(t||e){this.stencilEnabled=!0,this.stencilFront.copy(null!=t?t:en.DEFAULT),this.stencilBack.copy(null!=e?e:en.DEFAULT);var i=this.stencilFront.ref;this.stencilRef!==i&&(this.stencilRef=i,this.passEncoder.setStencilReference(i))}else this.stencilEnabled=!1},n.setBlendColor=function(t,e,i,n){},n.setCullMode=function(t){this.cullMode=t},n.setAlphaToCoverage=function(t){},n.initializeContextCaches=function(){t.prototype.initializeContextCaches.call(this)},n.setupPassEncoderDefaults=function(){this.stencilRef=0},n._uploadDirtyTextures=function(){this.textures.forEach((function(t){(t._needsUpload||t._needsMipmaps)&&t.upload()}))},n.startPass=function(t){this._uploadDirtyTextures();var e=t.renderTarget||this.backBuffer;this.renderTarget=e;var i=e.impl;this.commandEncoder=this.wgpu.createCommandEncoder(),e!==this.backBuffer&&this.initRenderTarget(e),i.setupForRenderPass(t),this.pipeline=null;var n=i.renderPassDescriptor;if(this.gpuProfiler._enabled&&this.gpuProfiler.timestampQueriesSet){var s=this.gpuProfiler.getSlot(t.name);n.timestampWrites={querySet:this.gpuProfiler.timestampQueriesSet.querySet,beginningOfPassWriteIndex:2*s,endOfPassWriteIndex:2*s+1}}this.passEncoder=this.commandEncoder.beginRenderPass(n),this.setupPassEncoderDefaults();var r=e.width,a=e.height;this.setViewport(0,0,r,a),this.setScissor(0,0,r,a),this.insideRenderPass=!0},n.endPass=function(t){this.passEncoder.end(),this.passEncoder=null,this.insideRenderPass=!1,this.bindGroupFormats.length=0;for(var e=0;e<t.colorArrayOps.length;e++){t.colorArrayOps[e].mipmaps&&this.mipmapRenderer.generate(t.renderTarget._colorBuffers[e].impl)}var i=this.commandEncoder.finish();this.addCommandBuffer(i),this.commandEncoder=null},n.addCommandBuffer=function(t,e){void 0===e&&(e=!1),e?this.commandBuffers.unshift(t):this.commandBuffers.push(t)},n.submit=function(){this.commandBuffers.length>0&&(this.dynamicBuffers.submit(),this.wgpu.queue.submit(this.commandBuffers),this.commandBuffers.length=0,this.dynamicBuffers.onCommandBuffersSubmitted())},n.clear=function(t){t.flags&&this.clearRenderer.clear(this,this.renderTarget,t,this.defaultClearOptions)},n.setDepthBias=function(t){},n.setDepthBiasValues=function(t,e){},n.setViewport=function(t,e,i,n){this.passEncoder&&(this.renderTarget.flipY||(e=this.renderTarget.height-e-n),this.vx=t,this.vy=e,this.vw=i,this.vh=n,this.passEncoder.setViewport(t,e,i,n,0,1))},n.setScissor=function(t,e,i,n){this.passEncoder&&(this.renderTarget.flipY||(e=this.renderTarget.height-e-n),this.sx=t,this.sy=e,this.sw=i,this.sh=n,this.passEncoder.setScissorRect(t,e,i,n))},n.copyRenderTarget=function(t,e,i,n){var s,r={width:t?t.width:e.width,height:t?t.height:e.height,depthOrArrayLayers:1},a=null!=(s=this.commandEncoder)?s:this.wgpu.createCommandEncoder();if(i){var o={texture:t?t.colorBuffer.impl.gpuTexture:this.renderTarget.impl.assignedColorTexture,mipLevel:0},h={texture:e?e.colorBuffer.impl.gpuTexture:this.renderTarget.impl.assignedColorTexture,mipLevel:0};a.copyTextureToTexture(o,h,r)}if(n){var l=(t||this.renderTarget).impl.depthTexture;if(t.samples>1){var c=e.colorBuffer.impl.gpuTexture;this.resolver.resolveDepth(a,l,c)}else{var u={texture:l,mipLevel:0},d={texture:e?e.depthBuffer.impl.gpuTexture:this.renderTarget.impl.depthTexture,mipLevel:0};a.copyTextureToTexture(u,d,r)}}if(!this.commandEncoder){var f=a.finish();this.addCommandBuffer(f)}return!0},e}(nn),Is=0,Ls=function(){function t(t,e){var i,n,s,r,a,o,h,l,c,u,d,f,p,m,_,v,g,y,x,S;(void 0===e&&(e={}),this.name=void 0,this._isRenderTarget=!1,this._gpuSize=0,this.id=Is++,this._invalid=!1,this._lockedLevel=-1,this.renderVersionDirty=0,this.device=t,this.name=null!=(i=e.name)?i:"",this._width=Math.floor(null!=(n=e.width)?n:4),this._height=Math.floor(null!=(s=e.height)?s:4),this._format=null!=(r=e.format)?r:7,this._compressed=xe(this._format),t.supportsVolumeTextures)?(this._volume=null!=(x=e.volume)&&x,this._depth=Math.floor(null!=(S=e.depth)?S:1)):(this._volume=!1,this._depth=1);this._cubemap=null!=(a=e.cubemap)&&a,this.fixCubemapSeams=null!=(o=e.fixCubemapSeams)&&o,this._flipY=null!=(h=e.flipY)&&h,this._premultiplyAlpha=null!=(l=e.premultiplyAlpha)&&l,this._mipmaps=null==(c=null!=(u=e.mipmaps)?u:e.autoMipmap)||c,this._minFilter=null!=(d=e.minFilter)?d:5,this._magFilter=null!=(f=e.magFilter)?f:1,this._anisotropy=null!=(p=e.anisotropy)?p:1,this._addressU=null!=(m=e.addressU)?m:0,this._addressV=null!=(_=e.addressV)?_:0,this._addressW=null!=(v=e.addressW)?v:0,this._compareOnRead=null!=(g=e.compareOnRead)&&g,this._compareFunc=null!=(y=e.compareFunc)?y:1,this.type=ei,e.hasOwnProperty("type")?this.type=e.type:e.hasOwnProperty("rgbm")?this.type=e.rgbm?ii:ei:e.hasOwnProperty("swizzleGGGR")&&(this.type=e.swizzleGGGR?ri:ei),this.projection=ci,this._cubemap?this.projection=ui:e.projection&&e.projection!==ui&&(this.projection=e.projection),this.impl=t.createTextureImpl(this),this.dirtyAll(),this._levels=e.levels,this._levels?this.upload():this._levels=this._cubemap?[[null,null,null,null,null,null]]:[null],t.textures.push(this)}var e,i=t.prototype;return i.destroy=function(){var t=this.device;if(t){var e=t.textures.indexOf(this);-1!==e&&t.textures.splice(e,1),t.scope.removeValue(this),this.impl.destroy(t),this.adjustVramSizeTracking(t._vram,-this._gpuSize),this._levels=null,this.device=null}},i.resize=function(t,e,i){void 0===i&&(i=1);var n=this.device;this.adjustVramSizeTracking(n._vram,-this._gpuSize),this.impl.destroy(n),this._width=t,this._height=e,this._depth=i,this.impl=n.createTextureImpl(this),this.dirtyAll()},i.loseContext=function(){this.impl.loseContext(),this.dirtyAll()},i.adjustVramSizeTracking=function(t,e){t.tex+=e},i.propertyChanged=function(t){this.impl.propertyChanged(t),this.renderVersionDirty=this.device.renderVersion},i.dirtyAll=function(){this._levelsUpdated=this._cubemap?[[!0,!0,!0,!0,!0,!0]]:[!0],this._needsUpload=!0,this._needsMipmapsUpload=this._mipmaps,this._mipmapsUploaded=!1,this.propertyChanged(255)},i.lock=function(t){void 0===t&&(t={}),void 0===t.level&&(t.level=0),void 0===t.face&&(t.face=0),void 0===t.mode&&(t.mode=2),this._lockedLevel=t.level;var e=this.cubemap?this._levels[t.face]:this._levels;if(null===e[t.level]){var i=Math.max(1,this._width>>t.level),n=Math.max(1,this._height>>t.level),s=Math.max(1,this._depth>>t.level),r=new ArrayBuffer(Kn.calcLevelGpuSize(i,n,s,this._format));e[t.level]=new(Se(this._format))(r)}return e[t.level]},i.setSource=function(t,e){void 0===e&&(e=0);var i,n,s=!1;if(this._cubemap){if(t[0]){i=t[0].width||0,n=t[0].height||0;for(var r=0;r<6;r++){var a=t[r];if(!a||a.width!==i||a.height!==n||!this.device._isBrowserInterface(a)){s=!0;break}}}else s=!0;if(!s)for(var o=0;o<6;o++)this._levels[e][o]!==t[o]&&(this._levelsUpdated[e][o]=!0)}else this.device._isBrowserInterface(t)||(s=!0),s||(t!==this._levels[e]&&(this._levelsUpdated[e]=!0),i=t.width,n=t.height);if(s)if(this._width=4,this._height=4,this._cubemap)for(var h=0;h<6;h++)this._levels[e][h]=null,this._levelsUpdated[e][h]=!0;else this._levels[e]=null,this._levelsUpdated[e]=!0;else 0===e&&(this._width=i,this._height=n),this._levels[e]=t;this._invalid===s&&s||(this._invalid=s,this.upload())},i.getSource=function(t){return void 0===t&&(t=0),this._levels[t]},i.unlock=function(){this._lockedLevel,this.upload(),this._lockedLevel=-1},i.upload=function(){var t,e;this._needsUpload=!0,this._needsMipmapsUpload=this._mipmaps,null==(t=(e=this.impl).uploadImmediate)||t.call(e,this.device,this)},i.downloadAsync=(e=v(m().mark((function t(){var e,i,n,s=this;return m().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:e=[],i=m().mark((function t(){var i,r,a,o;return m().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:i=new rn({colorBuffer:s,depth:!1,face:n}),s.device.setRenderTarget(i),s.device.initRenderTarget(i),(r=s.cubemap?s._levels[n]:s._levels)[0],r[0]&&s.device._isBrowserInterface(r[0])&&(r[0]=null),a=s.lock({face:n}),o=null==s.device.readPixelsAsync?void 0:s.device.readPixelsAsync(0,0,s.width,s.height,a).then((function(){return i.destroy()})),e.push(o);case 9:case"end":return t.stop()}}),t)})),n=0;case 3:if(!(n<(this.cubemap?6:1))){t.next=8;break}return t.delegateYield(i(),"t0",5);case 5:n++,t.next=3;break;case 8:return t.next=10,Promise.all(e);case 10:case"end":return t.stop()}}),t,this)}))),function(){return e.apply(this,arguments)}),y(t,[{key:"requiredMipLevels",get:function(){return this.mipmaps?Math.floor(Math.log2(Math.max(this.width,this.height)))+1:1}},{key:"minFilter",get:function(){return this._minFilter},set:function(t){this._minFilter!==t&&(this._minFilter=t,this.propertyChanged(1))}},{key:"magFilter",get:function(){return this._magFilter},set:function(t){this._magFilter!==t&&(this._magFilter=t,this.propertyChanged(2))}},{key:"addressU",get:function(){return this._addressU},set:function(t){this._addressU!==t&&(this._addressU=t,this.propertyChanged(4))}},{key:"addressV",get:function(){return this._addressV},set:function(t){this._addressV!==t&&(this._addressV=t,this.propertyChanged(8))}},{key:"addressW",get:function(){return this._addressW},set:function(t){this.device.supportsVolumeTextures&&this._volume&&t!==this._addressW&&(this._addressW=t,this.propertyChanged(16))}},{key:"compareOnRead",get:function(){return this._compareOnRead},set:function(t){this._compareOnRead!==t&&(this._compareOnRead=t,this.propertyChanged(32))}},{key:"compareFunc",get:function(){return this._compareFunc},set:function(t){this._compareFunc!==t&&(this._compareFunc=t,this.propertyChanged(64))}},{key:"anisotropy",get:function(){return this._anisotropy},set:function(t){this._anisotropy!==t&&(this._anisotropy=t,this.propertyChanged(128))}},{key:"mipmaps",get:function(){return this._mipmaps},set:function(t){this._mipmaps!==t&&(this._mipmaps=t,this.device.isWebGPU,t&&(this._needsMipmapsUpload=!0))}},{key:"width",get:function(){return this._width}},{key:"height",get:function(){return this._height}},{key:"depth",get:function(){return this._depth}},{key:"format",get:function(){return this._format}},{key:"cubemap",get:function(){return this._cubemap}},{key:"gpuSize",get:function(){var t=this.pot&&this._mipmaps&&!(this._compressed&&1===this._levels.length);return Kn.calcGpuSize(this._width,this._height,this._depth,this._format,t,this._cubemap)}},{key:"volume",get:function(){return this._volume}},{key:"flipY",get:function(){return this._flipY},set:function(t){this._flipY!==t&&(this._flipY=t,this._needsUpload=!0)}},{key:"premultiplyAlpha",get:function(){return this._premultiplyAlpha},set:function(t){this._premultiplyAlpha!==t&&(this._premultiplyAlpha=t,this._needsUpload=!0)}},{key:"pot",get:function(){return _t.powerOfTwo(this._width)&&_t.powerOfTwo(this._height)}},{key:"encoding",get:function(){switch(this.type){case ii:return"rgbm";case ni:return"rgbe";case si:return"rgbp";default:return this.format===ae||this.format===he||this.format===oe||this.format===le?"linear":"srgb"}}}]),t}(),Ds=function(){function t(){this.bufferId=null}var e=t.prototype;return e.destroy=function(t){this.bufferId&&(t.gl.deleteBuffer(this.bufferId),this.bufferId=null)},e.loseContext=function(){this.bufferId=null},e.unlock=function(t,e,i,n){var s,r=t.gl;switch(this.bufferId||(this.bufferId=r.createBuffer()),e){case 0:s=r.STATIC_DRAW;break;case 1:s=r.DYNAMIC_DRAW;break;case 2:s=r.STREAM_DRAW;break;case 3:s=t.isWebGL2?r.DYNAMIC_COPY:r.STATIC_DRAW}r.bindBuffer(i,this.bufferId),r.bufferData(i,n,s)},y(t,[{key:"initialized",get:function(){return!!this.bufferId}}]),t}(),Os=function(t){function e(){for(var e,i=arguments.length,n=new Array(i),s=0;s<i;s++)n[s]=arguments[s];return(e=t.call.apply(t,[this].concat(n))||this).vao=null,e}S(e,t);var i=e.prototype;return i.destroy=function(e){t.prototype.destroy.call(this,e),e.boundVao=null,e.gl.bindVertexArray(null)},i.loseContext=function(){t.prototype.loseContext.call(this),this.vao=null},i.unlock=function(e){var i=e.device;t.prototype.unlock.call(this,i,e.usage,i.gl.ARRAY_BUFFER,e.storage)},e}(Ds),ks=function(t){function e(e){var i;i=t.call(this)||this;var n=e.device.gl,s=e.format;return 0===s?i.glFormat=n.UNSIGNED_BYTE:1===s?i.glFormat=n.UNSIGNED_SHORT:2===s&&(i.glFormat=n.UNSIGNED_INT),i}return S(e,t),e.prototype.unlock=function(e){var i=e.device;t.prototype.unlock.call(this,i,e.usage,i.gl.ELEMENT_ARRAY_BUFFER,e.storage)},e}(Ds),Fs=function(t,e,i,n){if(this.locationId=n,this.scopeId=t.scope.resolve(e),this.version=new zi,"[0]"===e.substring(e.length-3))switch(i){case 2:i=17;break;case 3:i=21;break;case 4:i=22;break;case 5:i=23}this.dataType=i,this.value=[null,null,null,null],this.array=[]},Bs=function(){function t(){this._cache=new Map}var e=t.prototype;return e.get=function(t,e){var i=this;return this._cache.has(t)||(this._cache.set(t,e()),t.on("destroy",(function(){i.remove(t)})),t.on("devicelost",(function(){var e;null==(e=i._cache.get(t))||null==e.loseContext||e.loseContext(t)}))),this._cache.get(t)},e.remove=function(t){var e;null==(e=this._cache.get(t))||null==e.destroy||e.destroy(t),this._cache.delete(t)},t}(),Us=["gl_VertexID","gl_InstanceID","gl_DrawID","gl_BaseVertex","gl_BaseInstance"],Ns=function(){function t(){this.map=new Map}var e=t.prototype;return e.destroy=function(t){this.map.forEach((function(e){t.gl.deleteShader(e)}))},e.loseContext=function(t){this.map.clear()},t}(),zs=function(){function t(){this.shaders=[]}return t.prototype.loseContext=function(t){this.shaders=[]},t}(),Vs=new Bs,Gs=new Bs,Hs=new Bs,Ws=function(){function t(e){this.compileDuration=0,this.init(),this.compile(e.device,e),t.getBatchShaders(e.device).push(e),e.device.shaders.push(e)}var e=t.prototype;return e.destroy=function(t){this.glProgram&&(t.device.gl.deleteProgram(this.glProgram),this.glProgram=null)},e.init=function(){this.uniforms=[],this.samplers=[],this.attributes=[],this.glProgram=null,this.glVertexShader=null,this.glFragmentShader=null},t.getBatchShaders=function(t){return Hs.get(t,(function(){return new zs})).shaders},t.endShaderBatch=function(e){var i=t.getBatchShaders(e);i.forEach((function(t){return t.impl.link(e,t)})),i.length=0},e.loseContext=function(){this.init()},e.restoreContext=function(t,e){this.compile(t,e)},e.compile=function(t,e){var i=e.definition;this.glVertexShader=this._compileShaderSource(t,i.vshader,!0),this.glFragmentShader=this._compileShaderSource(t,i.fshader,!1)},e.link=function(t,e){if(!this.glProgram){var i=t.gl;if(!i.isContextLost()){var n=i.createProgram();this.glProgram=n,i.attachShader(n,this.glVertexShader),i.attachShader(n,this.glFragmentShader);var s=e.definition,r=s.attributes;if(t.isWebGL2&&s.useTransformFeedback){var a=[];for(var o in r)r.hasOwnProperty(o)&&a.push("out_"+o);i.transformFeedbackVaryings(n,a,i.INTERLEAVED_ATTRIBS)}for(var h in r)if(r.hasOwnProperty(h)){var l=r[h],c=Ri[l];i.bindAttribLocation(n,c,h)}i.linkProgram(n)}}},e._compileShaderSource=function(t,e,i){var n=t.gl,s=(i?Vs:Gs).get(t,(function(){return new Ns})),r=s.map.get(e);if(!r){if(!(r=n.createShader(i?n.VERTEX_SHADER:n.FRAGMENT_SHADER))&&n.isContextLost())return r;n.shaderSource(r,e),n.compileShader(r),s.map.set(e,r)}return r},e.finalize=function(t,e){var i=t.gl;if(i.isContextLost())return!0;this.glProgram||this.link(t,e);var n=this.glProgram,s=e.definition;if(!i.getProgramParameter(n,i.LINK_STATUS)){if(!this._isCompiled(t,e,this.glVertexShader,s.vshader,"vertex"))return!1;if(!this._isCompiled(t,e,this.glFragmentShader,s.fshader,"fragment"))return!1;var r="Failed to link shader program. Error: "+i.getProgramInfoLog(n);return console.error(r),!1}for(var a=0,o=i.getProgramParameter(n,i.ACTIVE_ATTRIBUTES);a<o;){var h=i.getActiveAttrib(n,a++),l=i.getAttribLocation(n,h.name);if(-1===Us.indexOf(h.name))if(void 0===s.attributes[h.name])console.error('Vertex shader attribute "'+h.name+'" is not mapped to a semantic in shader definition, shader ['+e.label+"]",e),e.failed=!0;else{var c=new Fs(t,s.attributes[h.name],t.pcUniformType[h.type],l);this.attributes.push(c)}}a=0;for(var u=i.getProgramParameter(n,i.ACTIVE_UNIFORMS);a<u;){var d=i.getActiveUniform(n,a++),f=i.getUniformLocation(n,d.name),p=new Fs(t,d.name,t.pcUniformType[d.type],f);d.type===i.SAMPLER_2D||d.type===i.SAMPLER_CUBE||t.isWebGL2&&(d.type===i.SAMPLER_2D_SHADOW||d.type===i.SAMPLER_CUBE_SHADOW||d.type===i.SAMPLER_3D)?this.samplers.push(p):this.uniforms.push(p)}return e.ready=!0,!0},e._isCompiled=function(t,e,i,n,s){var r=t.gl;if(!r.getShaderParameter(i,r.COMPILE_STATUS)){var a=r.getShaderInfoLog(i),o=this._processError(n,a),h=o[0];o[1];var l="Failed to compile "+s+" shader:\n\n"+a+"\n"+h;return console.error(l),!1}return!0},e._processError=function(t,e){var i={},n="";if(t){var s=t.split("\n"),r=0,a=s.length;if(e&&e.startsWith("ERROR:")){var o=e.match(/^ERROR:\s([0-9]+):([0-9]+):\s*(.+)/);o&&(i.message=o[3],i.line=parseInt(o[2],10),r=Math.max(0,i.line-6),a=Math.min(s.length,i.line+5))}for(var h=r;h<a;h++)n+=h+1+":\t"+s[h]+"\n";i.source=t}return[n,i]},t}();function Xs(t,e){var i=t.width,n=t.height;if(i>e||n>e){var s=e/Math.max(i,n),r=Math.floor(i*s),a=Math.floor(n*s),o=document.createElement("canvas");return o.width=r,o.height=a,o.getContext("2d").drawImage(t,0,0,i,n,0,0,r,a),o}return t}var js=function(){function t(){this._glTexture=null,this._glTarget=void 0,this._glFormat=void 0,this._glInternalFormat=void 0,this._glPixelType=void 0,this.dirtyParameterFlags=0}var e=t.prototype;return e.destroy=function(t){if(this._glTexture){for(var e=0;e<t.textureUnits.length;e++)for(var i=t.textureUnits[e],n=0;n<i.length;n++)i[n]===this._glTexture&&(i[n]=null);t.gl.deleteTexture(this._glTexture),this._glTexture=null}},e.loseContext=function(){this._glTexture=null},e.propertyChanged=function(t){this.dirtyParameterFlags|=t},e.initialize=function(t,e){var i=t.gl;switch(this._glTexture=i.createTexture(),this._glTarget=e._cubemap?i.TEXTURE_CUBE_MAP:e._volume?i.TEXTURE_3D:i.TEXTURE_2D,e._format){case 0:this._glFormat=i.ALPHA,this._glInternalFormat=i.ALPHA,this._glPixelType=i.UNSIGNED_BYTE;break;case 1:this._glFormat=i.LUMINANCE,this._glInternalFormat=i.LUMINANCE,this._glPixelType=i.UNSIGNED_BYTE;break;case 2:this._glFormat=i.LUMINANCE_ALPHA,this._glInternalFormat=i.LUMINANCE_ALPHA,this._glPixelType=i.UNSIGNED_BYTE;break;case 3:this._glFormat=i.RGB,this._glInternalFormat=i.RGB,this._glPixelType=i.UNSIGNED_SHORT_5_6_5;break;case 4:this._glFormat=i.RGBA,this._glInternalFormat=i.RGBA,this._glPixelType=i.UNSIGNED_SHORT_5_5_5_1;break;case 5:this._glFormat=i.RGBA,this._glInternalFormat=i.RGBA,this._glPixelType=i.UNSIGNED_SHORT_4_4_4_4;break;case 6:this._glFormat=i.RGB,this._glInternalFormat=t.isWebGL2?i.RGB8:i.RGB,this._glPixelType=i.UNSIGNED_BYTE;break;case 7:this._glFormat=i.RGBA,this._glInternalFormat=t.isWebGL2?i.RGBA8:i.RGBA,this._glPixelType=i.UNSIGNED_BYTE;break;case 8:this._glFormat=i.RGB,this._glInternalFormat=t.extCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;break;case 9:this._glFormat=i.RGBA,this._glInternalFormat=t.extCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;break;case re:this._glFormat=i.RGBA,this._glInternalFormat=t.extCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;break;case pe:this._glFormat=i.RGB,this._glInternalFormat=t.extCompressedTextureETC1.COMPRESSED_RGB_ETC1_WEBGL;break;case me:this._glFormat=i.RGB,this._glInternalFormat=t.extCompressedTexturePVRTC.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;break;case _e:this._glFormat=i.RGBA,this._glInternalFormat=t.extCompressedTexturePVRTC.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;break;case ve:this._glFormat=i.RGB,this._glInternalFormat=t.extCompressedTexturePVRTC.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;break;case ge:this._glFormat=i.RGBA,this._glInternalFormat=t.extCompressedTexturePVRTC.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;break;case 22:this._glFormat=i.RGB,this._glInternalFormat=t.extCompressedTextureETC.COMPRESSED_RGB8_ETC2;break;case 23:this._glFormat=i.RGBA,this._glInternalFormat=t.extCompressedTextureETC.COMPRESSED_RGBA8_ETC2_EAC;break;case 28:this._glFormat=i.RGBA,this._glInternalFormat=t.extCompressedTextureASTC.COMPRESSED_RGBA_ASTC_4x4_KHR;break;case 29:this._glFormat=i.RGB,this._glInternalFormat=t.extCompressedTextureATC.COMPRESSED_RGB_ATC_WEBGL;break;case 30:this._glFormat=i.RGBA,this._glInternalFormat=t.extCompressedTextureATC.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL;break;case ae:this._glFormat=i.RGB,t.isWebGL2?(this._glInternalFormat=i.RGB16F,this._glPixelType=i.HALF_FLOAT):(this._glInternalFormat=i.RGB,this._glPixelType=t.extTextureHalfFloat.HALF_FLOAT_OES);break;case oe:this._glFormat=i.RGBA,t.isWebGL2?(this._glInternalFormat=i.RGBA16F,this._glPixelType=i.HALF_FLOAT):(this._glInternalFormat=i.RGBA,this._glPixelType=t.extTextureHalfFloat.HALF_FLOAT_OES);break;case he:this._glFormat=i.RGB,t.isWebGL2?this._glInternalFormat=i.RGB32F:this._glInternalFormat=i.RGB,this._glPixelType=i.FLOAT;break;case le:this._glFormat=i.RGBA,t.isWebGL2?this._glInternalFormat=i.RGBA32F:this._glInternalFormat=i.RGBA,this._glPixelType=i.FLOAT;break;case ce:this._glFormat=i.RED,this._glInternalFormat=i.R32F,this._glPixelType=i.FLOAT;break;case ue:t.isWebGL2?(this._glFormat=i.DEPTH_COMPONENT,this._glInternalFormat=i.DEPTH_COMPONENT32F,this._glPixelType=i.FLOAT):(this._glFormat=i.DEPTH_COMPONENT,this._glInternalFormat=i.DEPTH_COMPONENT,this._glPixelType=i.UNSIGNED_SHORT);break;case de:this._glFormat=i.DEPTH_STENCIL,t.isWebGL2?(this._glInternalFormat=i.DEPTH24_STENCIL8,this._glPixelType=i.UNSIGNED_INT_24_8):(this._glInternalFormat=i.DEPTH_STENCIL,this._glPixelType=t.extDepthTexture.UNSIGNED_INT_24_8_WEBGL);break;case fe:this._glFormat=i.RGB,this._glInternalFormat=i.R11F_G11F_B10F,this._glPixelType=i.UNSIGNED_INT_10F_11F_11F_REV;break;case 19:this._glFormat=i.RGB,this._glInternalFormat=i.SRGB8,this._glPixelType=i.UNSIGNED_BYTE;break;case 20:this._glFormat=i.RGBA,this._glInternalFormat=i.SRGB8_ALPHA8,this._glPixelType=i.UNSIGNED_BYTE}},e.upload=function(t,e){var i=t.gl;if(e._needsUpload||!(e._needsMipmapsUpload&&e._mipmapsUploaded||!e.pot)){for(var n,s,r=0,a=e.requiredMipLevels;e._levels[r]||0===r;)if(e._needsUpload||0!==r){if(r&&(!e._needsMipmapsUpload||!e._mipmaps))break;if(n=e._levels[r],1===r&&!e._compressed&&e._levels.length<a&&(i.generateMipmap(this._glTarget),e._mipmapsUploaded=!0),e._cubemap){var o=void 0;if(t._isBrowserInterface(n[0])){for(o=0;o<6;o++)if(e._levelsUpdated[0][o]){var h=n[o];t._isImageBrowserInterface(h)&&(h.width>t.maxCubeMapSize||h.height>t.maxCubeMapSize)&&(h=Xs(h,t.maxCubeMapSize),0===r&&(e._width=h.width,e._height=h.height)),t.setUnpackFlipY(!1),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha),i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+o,r,this._glInternalFormat,this._glFormat,this._glPixelType,h)}}else for(s=1/Math.pow(2,r),o=0;o<6;o++)if(e._levelsUpdated[0][o]){var l=n[o];e._compressed?i.compressedTexImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+o,r,this._glInternalFormat,Math.max(e._width*s,1),Math.max(e._height*s,1),0,l):(t.setUnpackFlipY(!1),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha),i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+o,r,this._glInternalFormat,Math.max(e._width*s,1),Math.max(e._height*s,1),0,this._glFormat,this._glPixelType,l))}}else e._volume?(s=1/Math.pow(2,r),e._compressed?i.compressedTexImage3D(i.TEXTURE_3D,r,this._glInternalFormat,Math.max(e._width*s,1),Math.max(e._height*s,1),Math.max(e._depth*s,1),0,n):(t.setUnpackFlipY(!1),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha),i.texImage3D(i.TEXTURE_3D,r,this._glInternalFormat,Math.max(e._width*s,1),Math.max(e._height*s,1),Math.max(e._depth*s,1),0,this._glFormat,this._glPixelType,n))):(t._isBrowserInterface(n)?(t._isImageBrowserInterface(n)&&(n.width>t.maxTextureSize||n.height>t.maxTextureSize)&&(n=Xs(n,t.maxTextureSize),0===r&&(e._width=n.width,e._height=n.height)),t.setUnpackFlipY(e._flipY),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha),i.texImage2D(i.TEXTURE_2D,r,this._glInternalFormat,this._glFormat,this._glPixelType,n)):(s=1/Math.pow(2,r),e._compressed?i.compressedTexImage2D(i.TEXTURE_2D,r,this._glInternalFormat,Math.max(Math.floor(e._width*s),1),Math.max(Math.floor(e._height*s),1),0,n):(t.setUnpackFlipY(!1),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha),i.texImage2D(i.TEXTURE_2D,r,this._glInternalFormat,Math.max(e._width*s,1),Math.max(e._height*s,1),0,this._glFormat,this._glPixelType,n))),e._mipmapsUploaded=0!==r);r++}else r++;if(e._needsUpload)if(e._cubemap)for(var c=0;c<6;c++)e._levelsUpdated[0][c]=!1;else e._levelsUpdated[0]=!1;!e._compressed&&e._mipmaps&&e._needsMipmapsUpload&&(e.pot||t.isWebGL2)&&1===e._levels.length&&(i.generateMipmap(this._glTarget),e._mipmapsUploaded=!0),e._gpuSize&&e.adjustVramSizeTracking(t._vram,-e._gpuSize),e._gpuSize=e.gpuSize,e.adjustVramSizeTracking(t._vram,e._gpuSize)}},t}(),qs=function(){function t(t,e){this.msaaFB=void 0,this.resolveFB=void 0,this.msaaFB=t,this.resolveFB=e}return t.prototype.destroy=function(t){this.msaaFB&&(t.deleteRenderbuffer(this.msaaFB),this.msaaFB=null),this.resolveFB&&(t.deleteRenderbuffer(this.resolveFB),this.resolveFB=null)},t}(),Ys=function(){function t(){this._glFrameBuffer=null,this._glDepthBuffer=null,this._glResolveFrameBuffer=null,this.colorMrtFramebuffers=null,this._glMsaaColorBuffers=[],this._glMsaaDepthBuffer=null,this.suppliedColorFramebuffer=void 0,this._isInitialized=!1}var e=t.prototype;return e.destroy=function(t){var e,i=t.gl;this._isInitialized=!1,this._glFrameBuffer&&(this._glFrameBuffer!==this.suppliedColorFramebuffer&&i.deleteFramebuffer(this._glFrameBuffer),this._glFrameBuffer=null),this._glDepthBuffer&&(i.deleteRenderbuffer(this._glDepthBuffer),this._glDepthBuffer=null),this._glResolveFrameBuffer&&(this._glResolveFrameBuffer!==this.suppliedColorFramebuffer&&i.deleteFramebuffer(this._glResolveFrameBuffer),this._glResolveFrameBuffer=null),this._glMsaaColorBuffers.forEach((function(t){i.deleteRenderbuffer(t)})),this._glMsaaColorBuffers.length=0,null==(e=this.colorMrtFramebuffers)||e.forEach((function(t){t.destroy(i)})),this.colorMrtFramebuffers=null,this._glMsaaDepthBuffer&&(i.deleteRenderbuffer(this._glMsaaDepthBuffer),this._glMsaaDepthBuffer=null),this.suppliedColorFramebuffer=void 0},e.init=function(t,e){var i=t.gl;this._isInitialized=!0;var n=[];if(void 0!==this.suppliedColorFramebuffer)this._glFrameBuffer=this.suppliedColorFramebuffer;else{var s,r,a,o;this._glFrameBuffer=i.createFramebuffer(),t.setFramebuffer(this._glFrameBuffer);for(var h=null!=(s=null==(r=e._colorBuffers)?void 0:r.length)?s:0,l=t.isWebGL2?i.COLOR_ATTACHMENT0:null!=(a=null==(o=t.extDrawBuffers)?void 0:o.COLOR_ATTACHMENT0_WEBGL)?a:i.COLOR_ATTACHMENT0,c=0;c<h;++c){var u=e.getColorBuffer(c);u&&(u.impl._glTexture||(u._width=Math.min(u.width,t.maxRenderBufferSize),u._height=Math.min(u.height,t.maxRenderBufferSize),t.setTexture(u,0)),i.framebufferTexture2D(i.FRAMEBUFFER,l+c,u._cubemap?i.TEXTURE_CUBE_MAP_POSITIVE_X+e._face:i.TEXTURE_2D,u.impl._glTexture,0),n.push(l+c))}t.drawBuffers&&t.drawBuffers(n);var d=e._depthBuffer;if(d)d.impl._glTexture||(d._width=Math.min(d.width,t.maxRenderBufferSize),d._height=Math.min(d.height,t.maxRenderBufferSize),t.setTexture(d,0)),e._stencil?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,d._cubemap?i.TEXTURE_CUBE_MAP_POSITIVE_X+e._face:i.TEXTURE_2D,e._depthBuffer.impl._glTexture,0):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,d._cubemap?i.TEXTURE_CUBE_MAP_POSITIVE_X+e._face:i.TEXTURE_2D,e._depthBuffer.impl._glTexture,0);else if(e._depth){if(!(e._samples>1&&t.isWebGL2)){if(this._glDepthBuffer||(this._glDepthBuffer=i.createRenderbuffer()),i.bindRenderbuffer(i.RENDERBUFFER,this._glDepthBuffer),e._stencil)i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,e.width,e.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,this._glDepthBuffer);else{var f=t.isWebGL2?i.DEPTH_COMPONENT32F:i.DEPTH_COMPONENT16;i.renderbufferStorage(i.RENDERBUFFER,f,e.width,e.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,this._glDepthBuffer)}i.bindRenderbuffer(i.RENDERBUFFER,null)}}}if(t.isWebGL2&&e._samples>1){var p,m;this._glResolveFrameBuffer=this._glFrameBuffer,this._glFrameBuffer=i.createFramebuffer(),t.setFramebuffer(this._glFrameBuffer);var _=null!=(p=null==(m=e._colorBuffers)?void 0:m.length)?p:0;if(void 0!==this.suppliedColorFramebuffer){var v=i.createRenderbuffer();this._glMsaaColorBuffers.push(v);var g=7===t.backBufferFormat?i.RGBA8:i.RGB8;i.bindRenderbuffer(i.RENDERBUFFER,v),i.renderbufferStorageMultisample(i.RENDERBUFFER,e._samples,g,e.width,e.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,v)}else for(var y=0;y<_;++y){var x=e.getColorBuffer(y);if(x){var S=i.createRenderbuffer();this._glMsaaColorBuffers.push(S),i.bindRenderbuffer(i.RENDERBUFFER,S),i.renderbufferStorageMultisample(i.RENDERBUFFER,e._samples,x.impl._glInternalFormat,e.width,e.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+y,i.RENDERBUFFER,S)}}e._depth&&(this._glMsaaDepthBuffer||(this._glMsaaDepthBuffer=i.createRenderbuffer()),i.bindRenderbuffer(i.RENDERBUFFER,this._glMsaaDepthBuffer),e._stencil?(i.renderbufferStorageMultisample(i.RENDERBUFFER,e._samples,i.DEPTH24_STENCIL8,e.width,e.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,this._glMsaaDepthBuffer)):(i.renderbufferStorageMultisample(i.RENDERBUFFER,e._samples,i.DEPTH_COMPONENT32F,e.width,e.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,this._glMsaaDepthBuffer))),_>1&&(this._createMsaaMrtFramebuffers(t,e,_),t.setFramebuffer(this._glFrameBuffer),t.drawBuffers(n))}},e._createMsaaMrtFramebuffers=function(t,e,i){var n=t.gl;this.colorMrtFramebuffers=[];for(var s=0;s<i;++s){var r=e.getColorBuffer(s),a=n.createFramebuffer();t.setFramebuffer(a);var o=this._glMsaaColorBuffers[s];n.bindRenderbuffer(n.RENDERBUFFER,o),n.renderbufferStorageMultisample(n.RENDERBUFFER,e._samples,r.impl._glInternalFormat,e.width,e.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.RENDERBUFFER,o),t.drawBuffers([n.COLOR_ATTACHMENT0]);var h=n.createFramebuffer();t.setFramebuffer(h),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,r._cubemap?n.TEXTURE_CUBE_MAP_POSITIVE_X+e._face:n.TEXTURE_2D,r.impl._glTexture,0),this.colorMrtFramebuffers[s]=new qs(a,h)}},e._checkFbo=function(t,e,i){var n=t.gl;switch(n.checkFramebufferStatus(n.FRAMEBUFFER)){case n.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:case n.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:case n.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:case n.FRAMEBUFFER_UNSUPPORTED:}},e.loseContext=function(){this._glFrameBuffer=null,this._glDepthBuffer=null,this._glResolveFrameBuffer=null,this._glMsaaColorBuffers.length=0,this._glMsaaDepthBuffer=null,this.colorMrtFramebuffers=null,this.suppliedColorFramebuffer=void 0,this._isInitialized=!1},e.internalResolve=function(t,e,i,n,s){t.setScissor(0,0,n.width,n.height);var r=t.gl;r.bindFramebuffer(r.READ_FRAMEBUFFER,e),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,i),r.blitFramebuffer(0,0,n.width,n.height,0,0,n.width,n.height,s,r.NEAREST)},e.resolve=function(t,e,i,n){if(t.isWebGL2){var s=t.gl;if(this.colorMrtFramebuffers){if(i)for(var r=0;r<this.colorMrtFramebuffers.length;r++){var a=this.colorMrtFramebuffers[r];this.internalResolve(t,a.msaaFB,a.resolveFB,e,s.COLOR_BUFFER_BIT)}n&&this.internalResolve(t,this._glFrameBuffer,this._glResolveFrameBuffer,e,s.DEPTH_BUFFER_BIT)}else this.internalResolve(t,this._glFrameBuffer,this._glResolveFrameBuffer,e,(i?s.COLOR_BUFFER_BIT:0)|(n?s.DEPTH_BUFFER_BIT:0));s.bindFramebuffer(s.FRAMEBUFFER,this._glFrameBuffer)}},y(t,[{key:"initialized",get:function(){return this._isInitialized}}]),t}(),Ks="\n#define pcFragColor0 gl_FragData[0]\n#if COLOR_ATTACHMENT_1\n#define pcFragColor1 gl_FragData[1]\n#endif\n#if COLOR_ATTACHMENT_2\n#define pcFragColor2 gl_FragData[2]\n#endif\n#if COLOR_ATTACHMENT_3\n#define pcFragColor3 gl_FragData[3]\n#endif\n#if COLOR_ATTACHMENT_4\n#define pcFragColor4 gl_FragData[4]\n#endif\n#if COLOR_ATTACHMENT_5\n#define pcFragColor5 gl_FragData[5]\n#endif\n#if COLOR_ATTACHMENT_6\n#define pcFragColor6 gl_FragData[6]\n#endif\n#if COLOR_ATTACHMENT_7\n#define pcFragColor7 gl_FragData[7]\n#endif\n#define texture2DBias texture2D\n#define SHADOWMAP_PASS(name) name\n#define SHADOWMAP_ACCEPT(name) sampler2D name\n#define TEXTURE_PASS(name) name\n#define TEXTURE_ACCEPT(name) sampler2D name\n#ifndef SUPPORTS_TEXLOD\n\t#define texture2DLodEXT texture2D\n\t#define texture2DProjLodEXT textureProj\n\t#define textureCubeLodEXT textureCube\n\t#define textureShadow texture2D\n#else\n\t#define textureShadow(res, uv) texture2DGradEXT(res, uv, vec2(1, 1), vec2(1, 1))\n#endif\n#ifdef SUPPORTS_MRT\n\t#define gl_FragColor pcFragColor0\n#endif\n",Zs="\nlayout(location = 0) out highp vec4 pc_fragColor;\n#ifndef REMOVE_COLOR_ATTACHMENT_1\n#if COLOR_ATTACHMENT_1\nlayout(location = 1) out highp vec4 pc_fragColor1;\n#endif\n#endif\n#ifndef REMOVE_COLOR_ATTACHMENT_2\n#if COLOR_ATTACHMENT_2\nlayout(location = 2) out highp vec4 pc_fragColor2;\n#endif\n#endif\n#ifndef REMOVE_COLOR_ATTACHMENT_3\n#if COLOR_ATTACHMENT_3\nlayout(location = 3) out highp vec4 pc_fragColor3;\n#endif\n#endif\n#ifndef REMOVE_COLOR_ATTACHMENT_4\n#if COLOR_ATTACHMENT_4\nlayout(location = 4) out highp vec4 pc_fragColor4;\n#endif\n#endif\n#ifndef REMOVE_COLOR_ATTACHMENT_5\n#if COLOR_ATTACHMENT_5\nlayout(location = 5) out highp vec4 pc_fragColor5;\n#endif\n#endif\n#ifndef REMOVE_COLOR_ATTACHMENT_6\n#if COLOR_ATTACHMENT_6\nlayout(location = 6) out highp vec4 pc_fragColor6;\n#endif\n#endif\n#ifndef REMOVE_COLOR_ATTACHMENT_7\n#if COLOR_ATTACHMENT_7\nlayout(location = 7) out highp vec4 pc_fragColor7;\n#endif\n#endif\n#define gl_FragColor pc_fragColor\n#define pcFragColor0 pc_fragColor\n#define pcFragColor1 pc_fragColor1\n#define pcFragColor2 pc_fragColor2\n#define pcFragColor3 pc_fragColor3\n#define pcFragColor4 pc_fragColor4\n#define pcFragColor5 pc_fragColor5\n#define pcFragColor6 pc_fragColor6\n#define pcFragColor7 pc_fragColor7\n#define varying in\n#define texture2D texture\n#define texture2DBias texture\n#define textureCube texture\n#define texture2DProj textureProj\n#define texture2DLodEXT textureLod\n#define texture2DProjLodEXT textureProjLod\n#define textureCubeLodEXT textureLod\n#define texture2DGradEXT textureGrad\n#define texture2DProjGradEXT textureProjGrad\n#define textureCubeGradEXT textureGrad\n#define textureShadow(res, uv) textureGrad(res, uv, vec2(1, 1), vec2(1, 1))\n#define SHADOWMAP_PASS(name) name\n#define SHADOWMAP_ACCEPT(name) sampler2DShadow name\n#define TEXTURE_PASS(name) name\n#define TEXTURE_ACCEPT(name) sampler2D name\n#define GL2\n#define SUPPORTS_TEXLOD\n#define SUPPORTS_MRT\n",Qs="\n#define attribute in\n#define varying out\n#define texture2D texture\n#define GL2\n#define VERTEXSHADER\n",$s="\n#extension GL_EXT_samplerless_texture_functions : require\nlayout(location = 0) out highp vec4 pc_fragColor;\nlayout(location = 1) out highp vec4 pc_fragColor1;\nlayout(location = 2) out highp vec4 pc_fragColor2;\nlayout(location = 3) out highp vec4 pc_fragColor3;\nlayout(location = 4) out highp vec4 pc_fragColor4;\nlayout(location = 5) out highp vec4 pc_fragColor5;\nlayout(location = 6) out highp vec4 pc_fragColor6;\nlayout(location = 7) out highp vec4 pc_fragColor7;\n#define gl_FragColor pc_fragColor\n#define pcFragColor0 pc_fragColor\n#define pcFragColor1 pc_fragColor1\n#define pcFragColor2 pc_fragColor2\n#define pcFragColor3 pc_fragColor3\n#define pcFragColor4 pc_fragColor4\n#define pcFragColor5 pc_fragColor5\n#define pcFragColor6 pc_fragColor6\n#define pcFragColor7 pc_fragColor7\n#define texture2D(res, uv) texture(sampler2D(res, res ## _sampler), uv)\n#define texture2DBias(res, uv, bias) texture(sampler2D(res, res ## _sampler), uv, bias)\n#define texture2DLodEXT(res, uv, lod) textureLod(sampler2D(res, res ## _sampler), uv, lod)\n#define textureCube(res, uv) texture(samplerCube(res, res ## _sampler), uv)\n#define textureCubeLodEXT(res, uv, lod) textureLod(samplerCube(res, res ## _sampler), uv, lod)\n#define textureShadow(res, uv) textureLod(sampler2DShadow(res, res ## _sampler), uv, 0.0)\n#define SHADOWMAP_PASS(name) name, name ## _sampler\n#define SHADOWMAP_ACCEPT(name) texture2D name, sampler name ## _sampler\n#define TEXTURE_PASS(name) name, name ## _sampler\n#define TEXTURE_ACCEPT(name) texture2D name, sampler name ## _sampler\n#define GL2\n#define WEBGPU\n#define SUPPORTS_TEXLOD\n#define SUPPORTS_MRT\n",Js="\n#extension GL_EXT_samplerless_texture_functions : require\n#define texture2D(res, uv) texture(sampler2D(res, res ## _sampler), uv)\n#define GL2\n#define WEBGPU\n#define VERTEXSHADER\n",tr="\nvec2 getGrabScreenPos(vec4 clipPos) {\n\tvec2 uv = (clipPos.xy / clipPos.w) * 0.5 + 0.5;\n\t#ifdef WEBGPU\n\t\tuv.y = 1.0 - uv.y;\n\t#endif\n\treturn uv;\n}\nvec2 getImageEffectUV(vec2 uv) {\n\t#ifdef WEBGPU\n\t\tuv.y = 1.0 - uv.y;\n\t#endif\n\treturn uv;\n}\n",er={vertex_position:we,vertex_normal:Te,vertex_tangent:Ae,vertex_texCoord0:Re,vertex_texCoord1:Ie,vertex_texCoord2:Le,vertex_texCoord3:De,vertex_texCoord4:Oe,vertex_texCoord5:ke,vertex_texCoord6:Fe,vertex_texCoord7:Be,vertex_color:Me,vertex_boneIndices:Ee,vertex_boneWeights:Ce},ir=function(){function t(){}return t.createDefinition=function(e,i){var n,s,r=function(n,s,r,a){for(var o=e.isWebGPU?n:e.isWebGL2?s:t.gl1Extensions(e,i)+r,h="",l=0;l<e.maxColorAttachments;l++)h+="#define COLOR_ATTACHMENT_"+l+"\n";return h+o},a=null!=(n=i.name)?n:"Untitled",o=i.vertexDefines||r(Js,Qs,""),h=t.versionCode(e)+o+tr+t.getShaderNameCode(a)+i.vertexCode,l=i.fragmentDefines||r($s,Zs,Ks),c=(i.fragmentPreamble||"")+t.versionCode(e)+l+t.precisionCode(e)+"\n"+tr+t.getShaderNameCode(a)+(i.fragmentCode||t.dummyFragmentCode());return{name:a,attributes:null!=(s=i.attributes)?s:t.collectAttributes(i.vertexCode),vshader:h,fshader:c,useTransformFeedback:i.useTransformFeedback}},t.getShaderNameCode=function(t){return"#define SHADER_NAME "+t+"\n"},t.gl1Extensions=function(t,e,i){var n;return i?n=e.vertexExtensions?e.vertexExtensions+"\n":"":(n=e.fragmentExtensions?e.fragmentExtensions+"\n":"",t.extStandardDerivatives&&(n+="#extension GL_OES_standard_derivatives : enable\n"),t.extTextureLod&&(n+="#extension GL_EXT_shader_texture_lod : enable\n",n+="#define SUPPORTS_TEXLOD\n"),t.extDrawBuffers&&(n+="#extension GL_EXT_draw_buffers : require\n",n+="#define SUPPORTS_MRT\n")),n},t.dummyFragmentCode=function(){return"void main(void) {gl_FragColor = vec4(0.0);}"},t.versionCode=function(t){return t.isWebGPU?"#version 450\n":t.isWebGL2?"#version 300 es\n":""},t.precisionCode=function(t,e){var i="";e&&"highp"!==e&&"mediump"!==e&&"lowp"!==e&&(e=null),e&&("highp"===e&&"highp"!==t.maxPrecision&&(e="mediump"),"mediump"===e&&"lowp"===t.maxPrecision&&(e="lowp"));var n=e||t.precision;return t.isWebGPU?i="precision "+n+" float;\nprecision "+n+" int;\n":(i="precision "+n+" float;\n",t.isWebGL2&&(i+="precision "+n+" sampler2DShadow;\n")),i},t.collectAttributes=function(t){for(var e={},i=0,n=t.indexOf("attribute");n>=0&&!(n>0&&"/"===t[n-1]);){var s=t.indexOf(";",n),r=t.lastIndexOf(" ",s),a=t.substring(r+1,s),o=er[a];void 0!==o?e[a]=o:(e[a]="ATTR"+i,i++),n=t.indexOf("attribute",n+1)}return e},t}(),nr=function(){function t(){this.renderVersion=void 0,this.queries=[]}return t.prototype.destroy=function(t){this.queries.forEach((function(e){return t.deleteQuery(e)})),this.queries=null},t}(),sr=function(t){function e(e){var i;return(i=t.call(this)||this).device=void 0,i.freeQueries=[],i.frameQueries=[],i.previousFrameQueries=[],i.timings=[],i.device=e,i.ext=e.extDisjointTimerQuery,i}S(e,t);var i=e.prototype;return i.destroy=function(){var t=this;this.freeQueries.forEach((function(e){return t.device.gl.deleteQuery(e)})),this.frameQueries.forEach((function(e){return t.device.gl.deleteQuery(e)})),this.previousFrameQueries.forEach((function(e){return e.destroy(t.device.gl)})),this.freeQueries=null,this.frameQueries=null,this.previousFrameQueries=null},i.loseContext=function(){t.prototype.loseContext.call(this),this.freeQueries=[],this.frameQueries=[],this.previousFrameQueries=[]},i.restoreContext=function(){this.ext=this.device.extDisjointTimerQuery},i.getQuery=function(){var t;return null!=(t=this.freeQueries.pop())?t:this.device.gl.createQuery()},i.start=function(t){if(this.ext){var e=this.getSlot(t),i=this.getQuery();return this.frameQueries[e]=i,this.device.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,i),e}},i.end=function(t){void 0!==t&&this.device.gl.endQuery(this.ext.TIME_ELAPSED_EXT)},i.frameStart=function(){this.processEnableRequest(),this._enabled&&(this.frameGPUMarkerSlot=this.start("GpuFrame"))},i.frameEnd=function(){this._enabled&&this.end(this.frameGPUMarkerSlot)},i.request=function(){var e=this;if(this._enabled){var i=this.ext,n=this.device.gl,s=this.device.renderVersion,r=this.frameQueries;if(r.length>0){this.frameQueries=[];var a=new nr;a.queries=r,a.renderVersion=s,this.previousFrameQueries.push(a)}if(this.previousFrameQueries.length>0){var o=this.previousFrameQueries[0],h=o.queries,l=h[h.length-1],c=n.getQueryParameter(l,n.QUERY_RESULT_AVAILABLE),u=n.getParameter(i.GPU_DISJOINT_EXT);if(c&&!u){this.previousFrameQueries.shift();var d=this.timings;d.length=0;for(var f=0;f<h.length;f++){var p=h[f],m=n.getQueryParameter(p,n.QUERY_RESULT);d[f]=1e-6*m,this.freeQueries.push(p)}this.report(o.renderVersion,d)}u&&(this.previousFrameQueries.forEach((function(t){e.report(t.renderVersion,null),t.destroy(n)})),this.previousFrameQueries.length=0)}t.prototype.request.call(this,s)}},e}(Cs),rr=[],ar="\nattribute vec2 vertex_position;\nvarying vec2 vUv0;\nvoid main(void)\n{\n\tgl_Position = vec4(vertex_position, 0.5, 1.0);\n\tvUv0 = vertex_position.xy*0.5+0.5;\n}\n";function or(t,e,i){var n=t.renderTarget;t.setRenderTarget(e),t.updateBegin(),t.setCullMode(se),t.setBlendState(Ui.NOBLEND),t.setDepthState(Ni.NODEPTH),t.setStencilState(null,null),t.setVertexBuffer(t.quadVertexBuffer,0),t.setShader(i),t.draw({type:be,base:0,count:4,indexed:!1}),t.updateEnd(),t.setRenderTarget(n),t.updateBegin()}function hr(t,e){var i=!0,n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,2,2,0,t.RGBA,e,null);var s=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0),t.checkFramebufferStatus(t.FRAMEBUFFER)!==t.FRAMEBUFFER_COMPLETE&&(i=!1),t.bindTexture(t.TEXTURE_2D,null),t.deleteTexture(n),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteFramebuffer(s),i}var lr=function(t){function e(e,i){var n,s;void 0===i&&(i={}),(s=t.call(this,e,i)||this).gl=void 0,s._defaultFramebuffer=null,s._defaultFramebufferChanged=!1,i=s.initOptions,s.updateClientRect(),s.initTextureUnits(),s.contextLost=!1,s._contextLostHandler=function(t){t.preventDefault(),s.contextLost=!0,s.loseContext(),s.fire("devicelost")},s._contextRestoredHandler=function(){s.contextLost=!1,s.restoreContext(),s.fire("devicerestored")};var r="undefined"!=typeof navigator&&navigator.userAgent;s.forceDisableMultisampling=r&&r.includes("AppleWebKit")&&(r.includes("15.4")||r.includes("15_4")),s.forceDisableMultisampling&&(i.antialias=!1);var a=null;if(s.backBufferAntialias=null!=(n=i.antialias)&&n,i.antialias=!1,i.gl)a=i.gl;else for(var o=void 0===i.preferWebGl2||i.preferWebGl2?["webgl2","webgl","experimental-webgl"]:["webgl","experimental-webgl"],l=0;l<o.length&&!(a=e.getContext(o[l],i));l++);if(!a)throw new Error("WebGL not supported");s.gl=a,s.isWebGL2="undefined"!=typeof WebGL2RenderingContext&&a instanceof WebGL2RenderingContext,s.isWebGL1=!s.isWebGL2,s._deviceType=s.isWebGL2?xi:yi,s.updateBackbufferFormat(null);var c,u,d,f,p,m="chrome"===G.browserName,_="safari"===G.browserName,v=G.browser&&-1!==navigator.appVersion.indexOf("Mac");s._tempEnableSafariTextureUnitWorkaround=_,s._tempMacChromeBlitFramebufferWorkaround=v&&m&&!i.alpha,s.isWebGL2||function(t){if(t.getSupportedExtensions){if(-1!=t.getSupportedExtensions().indexOf("OES_vertex_array_object"))return}else if(t.getExtension&&t.getExtension("OES_vertex_array_object"))return;if(t.getSupportedExtensions){var e=t.getSupportedExtensions;t.getSupportedExtensions=function(){var t=e.call(this)||[];return t.push("OES_vertex_array_object"),t}}var i=t.getExtension;t.getExtension=function(e){return"OES_vertex_array_object"==e?(t.__OESVertexArrayObject||(t.__OESVertexArrayObject=new h(t)),t.__OESVertexArrayObject):i?i.call(this,e):null}}(a),e.addEventListener("webglcontextlost",s._contextLostHandler,!1),e.addEventListener("webglcontextrestored",s._contextRestoredHandler,!1),s.initializeExtensions(),s.initializeCapabilities(),s.initializeRenderState(),s.initializeContextCaches(),s.createBackbuffer(null),s.supportsImageBitmap=!_&&"undefined"!=typeof ImageBitmap,s.glAddress=[a.REPEAT,a.CLAMP_TO_EDGE,a.MIRRORED_REPEAT],s.glBlendEquation=[a.FUNC_ADD,a.FUNC_SUBTRACT,a.FUNC_REVERSE_SUBTRACT,s.isWebGL2?a.MIN:s.extBlendMinmax?s.extBlendMinmax.MIN_EXT:a.FUNC_ADD,s.isWebGL2?a.MAX:s.extBlendMinmax?s.extBlendMinmax.MAX_EXT:a.FUNC_ADD],s.glBlendFunctionColor=[a.ZERO,a.ONE,a.SRC_COLOR,a.ONE_MINUS_SRC_COLOR,a.DST_COLOR,a.ONE_MINUS_DST_COLOR,a.SRC_ALPHA,a.SRC_ALPHA_SATURATE,a.ONE_MINUS_SRC_ALPHA,a.DST_ALPHA,a.ONE_MINUS_DST_ALPHA,a.CONSTANT_COLOR,a.ONE_MINUS_CONSTANT_COLOR],s.glBlendFunctionAlpha=[a.ZERO,a.ONE,a.SRC_COLOR,a.ONE_MINUS_SRC_COLOR,a.DST_COLOR,a.ONE_MINUS_DST_COLOR,a.SRC_ALPHA,a.SRC_ALPHA_SATURATE,a.ONE_MINUS_SRC_ALPHA,a.DST_ALPHA,a.ONE_MINUS_DST_ALPHA,a.CONSTANT_ALPHA,a.ONE_MINUS_CONSTANT_ALPHA],s.glComparison=[a.NEVER,a.LESS,a.EQUAL,a.LEQUAL,a.GREATER,a.NOTEQUAL,a.GEQUAL,a.ALWAYS],s.glStencilOp=[a.KEEP,a.ZERO,a.REPLACE,a.INCR,a.INCR_WRAP,a.DECR,a.DECR_WRAP,a.INVERT],s.glClearFlag=[0,a.COLOR_BUFFER_BIT,a.DEPTH_BUFFER_BIT,a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT,a.STENCIL_BUFFER_BIT,a.STENCIL_BUFFER_BIT|a.COLOR_BUFFER_BIT,a.STENCIL_BUFFER_BIT|a.DEPTH_BUFFER_BIT,a.STENCIL_BUFFER_BIT|a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT],s.glCull=[0,a.BACK,a.FRONT,a.FRONT_AND_BACK],s.glFilter=[a.NEAREST,a.LINEAR,a.NEAREST_MIPMAP_NEAREST,a.NEAREST_MIPMAP_LINEAR,a.LINEAR_MIPMAP_NEAREST,a.LINEAR_MIPMAP_LINEAR],s.glPrimitive=[a.POINTS,a.LINES,a.LINE_LOOP,a.LINE_STRIP,a.TRIANGLES,a.TRIANGLE_STRIP,a.TRIANGLE_FAN],s.glType=[a.BYTE,a.UNSIGNED_BYTE,a.SHORT,a.UNSIGNED_SHORT,a.INT,a.UNSIGNED_INT,a.FLOAT],s.pcUniformType={},s.pcUniformType[a.BOOL]=0,s.pcUniformType[a.INT]=1,s.pcUniformType[a.FLOAT]=2,s.pcUniformType[a.FLOAT_VEC2]=3,s.pcUniformType[a.FLOAT_VEC3]=4,s.pcUniformType[a.FLOAT_VEC4]=5,s.pcUniformType[a.INT_VEC2]=6,s.pcUniformType[a.INT_VEC3]=7,s.pcUniformType[a.INT_VEC4]=8,s.pcUniformType[a.BOOL_VEC2]=9,s.pcUniformType[a.BOOL_VEC3]=10,s.pcUniformType[a.BOOL_VEC4]=11,s.pcUniformType[a.FLOAT_MAT2]=12,s.pcUniformType[a.FLOAT_MAT3]=_i,s.pcUniformType[a.FLOAT_MAT4]=vi,s.pcUniformType[a.SAMPLER_2D]=15,s.pcUniformType[a.SAMPLER_CUBE]=16,s.isWebGL2&&(s.pcUniformType[a.SAMPLER_2D_SHADOW]=18,s.pcUniformType[a.SAMPLER_CUBE_SHADOW]=19,s.pcUniformType[a.SAMPLER_3D]=20),s.targetToSlot={},s.targetToSlot[a.TEXTURE_2D]=0,s.targetToSlot[a.TEXTURE_CUBE_MAP]=1,s.targetToSlot[a.TEXTURE_3D]=2,s.commitFunction=[],s.commitFunction[0]=function(t,e){t.value!==e&&(a.uniform1i(t.locationId,e),t.value=e)},s.commitFunction[1]=s.commitFunction[0],s.commitFunction[2]=function(t,e){t.value!==e&&(a.uniform1f(t.locationId,e),t.value=e)},s.commitFunction[3]=function(t,e){p=t.value,c=e[0],u=e[1],p[0]===c&&p[1]===u||(a.uniform2fv(t.locationId,e),p[0]=c,p[1]=u)},s.commitFunction[4]=function(t,e){p=t.value,c=e[0],u=e[1],d=e[2],p[0]===c&&p[1]===u&&p[2]===d||(a.uniform3fv(t.locationId,e),p[0]=c,p[1]=u,p[2]=d)},s.commitFunction[5]=function(t,e){p=t.value,c=e[0],u=e[1],d=e[2],f=e[3],p[0]===c&&p[1]===u&&p[2]===d&&p[3]===f||(a.uniform4fv(t.locationId,e),p[0]=c,p[1]=u,p[2]=d,p[3]=f)},s.commitFunction[6]=function(t,e){p=t.value,c=e[0],u=e[1],p[0]===c&&p[1]===u||(a.uniform2iv(t.locationId,e),p[0]=c,p[1]=u)},s.commitFunction[9]=s.commitFunction[6],s.commitFunction[7]=function(t,e){p=t.value,c=e[0],u=e[1],d=e[2],p[0]===c&&p[1]===u&&p[2]===d||(a.uniform3iv(t.locationId,e),p[0]=c,p[1]=u,p[2]=d)},s.commitFunction[10]=s.commitFunction[7],s.commitFunction[8]=function(t,e){p=t.value,c=e[0],u=e[1],d=e[2],f=e[3],p[0]===c&&p[1]===u&&p[2]===d&&p[3]===f||(a.uniform4iv(t.locationId,e),p[0]=c,p[1]=u,p[2]=d,p[3]=f)},s.commitFunction[11]=s.commitFunction[8],s.commitFunction[12]=function(t,e){a.uniformMatrix2fv(t.locationId,!1,e)},s.commitFunction[13]=function(t,e){a.uniformMatrix3fv(t.locationId,!1,e)},s.commitFunction[14]=function(t,e){a.uniformMatrix4fv(t.locationId,!1,e)},s.commitFunction[17]=function(t,e){a.uniform1fv(t.locationId,e)},s.commitFunction[21]=function(t,e){a.uniform2fv(t.locationId,e)},s.commitFunction[22]=function(t,e){a.uniform3fv(t.locationId,e)},s.commitFunction[23]=function(t,e){a.uniform4fv(t.locationId,e)},s.supportsBoneTextures=s.extTextureFloat&&s.maxVertexTextures>0;var g=s.vertexUniformsCount;return g-=16,g-=8,g-=1,g-=16,s.boneLimit=Math.floor(g/3),s.boneLimit=Math.min(s.boneLimit,128),"Mali-450 MP"===s.unmaskedRenderer&&(s.boneLimit=34),s.constantTexSource=s.scope.resolve("source"),s.extTextureFloat?s.isWebGL2?s.textureFloatRenderable=!!s.extColorBufferFloat:s.textureFloatRenderable=hr(a,a.FLOAT):s.textureFloatRenderable=!1,s.extColorBufferHalfFloat?s.textureHalfFloatRenderable=!!s.extColorBufferHalfFloat:s.extTextureHalfFloat?s.isWebGL2?s.textureHalfFloatRenderable=!!s.extColorBufferFloat:s.textureHalfFloatRenderable=hr(a,s.extTextureHalfFloat.HALF_FLOAT_OES):s.textureHalfFloatRenderable=!1,s.supportsMorphTargetTexturesCore="highp"===s.maxPrecision&&s.maxVertexTextures>=2,s.supportsDepthShadow=s.isWebGL2,s._textureFloatHighPrecision=void 0,s._textureHalfFloatUpdatable=void 0,s.areaLightLutFormat=7,s.extTextureHalfFloat&&s.textureHalfFloatUpdatable&&s.extTextureHalfFloatLinear?s.areaLightLutFormat=oe:s.extTextureFloat&&s.extTextureFloatLinear&&(s.areaLightLutFormat=le),s.postInit(),s}S(e,t);var i,n=e.prototype;return n.postInit=function(){t.prototype.postInit.call(this),this.gpuProfiler=new sr(this)},n.destroy=function(){t.prototype.destroy.call(this);var e=this.gl;this.isWebGL2&&this.feedback&&e.deleteTransformFeedback(this.feedback),this.clearVertexArrayObjectCache(),this.canvas.removeEventListener("webglcontextlost",this._contextLostHandler,!1),this.canvas.removeEventListener("webglcontextrestored",this._contextRestoredHandler,!1),this._contextLostHandler=null,this._contextRestoredHandler=null,this.gl=null,t.prototype.postDestroy.call(this)},n.createBackbuffer=function(t){this.supportsStencil=this.initOptions.stencil,this.backBuffer=new rn({name:"WebglFramebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples}),this.backBuffer.impl.suppliedColorFramebuffer=t},n.updateBackbufferFormat=function(t){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,t);var i=this.gl.getParameter(this.gl.ALPHA_BITS);this.backBufferFormat=i?7:6},n.updateBackbuffer=function(){var t=this.canvas.width!==this.backBufferSize.x||this.canvas.height!==this.backBufferSize.y;(this._defaultFramebufferChanged||t)&&(this._defaultFramebufferChanged&&this.updateBackbufferFormat(this._defaultFramebuffer),this._defaultFramebufferChanged=!1,this.backBufferSize.set(this.canvas.width,this.canvas.height),this.backBuffer.destroy(),this.createBackbuffer(this._defaultFramebuffer))},n.createVertexBufferImpl=function(t,e){return new Os},n.createIndexBufferImpl=function(t){return new ks(t)},n.createShaderImpl=function(t){return new Ws(t)},n.createTextureImpl=function(t){return new js},n.createRenderTargetImpl=function(t){return new Ys},n.getPrecision=function(){var t=this.gl,e="highp";if(t.getShaderPrecisionFormat){var i=t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT),n=t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT),s=t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT),r=t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT);if(i&&n&&s&&r){var a=i.precision>0&&s.precision>0,o=n.precision>0&&r.precision>0;a||(e=o?"mediump":"lowp")}}return e},n.getExtension=function(){for(var t=0;t<arguments.length;t++)if(-1!==this.supportedExtensions.indexOf(arguments[t]))return this.gl.getExtension(arguments[t]);return null},n.initializeExtensions=function(){var t,e=this.gl;if(this.supportedExtensions=null!=(t=e.getSupportedExtensions())?t:[],this._extDisjointTimerQuery=null,this.isWebGL2)this.extBlendMinmax=!0,this.extDrawBuffers=!0,this.drawBuffers=e.drawBuffers.bind(e),this.extInstancing=!0,this.extStandardDerivatives=!0,this.extTextureFloat=!0,this.extTextureHalfFloat=!0,this.extTextureLod=!0,this.extUintElement=!0,this.extVertexArrayObject=!0,this.extColorBufferFloat=this.getExtension("EXT_color_buffer_float"),this.extDepthTexture=!0;else{var i;if(this.extBlendMinmax=this.getExtension("EXT_blend_minmax"),this.extDrawBuffers=this.getExtension("WEBGL_draw_buffers"),this.extInstancing=this.getExtension("ANGLE_instanced_arrays"),this.drawBuffers=null==(i=this.extDrawBuffers)?void 0:i.drawBuffersWEBGL.bind(this.extDrawBuffers),this.extInstancing){var n=this.extInstancing;e.drawArraysInstanced=n.drawArraysInstancedANGLE.bind(n),e.drawElementsInstanced=n.drawElementsInstancedANGLE.bind(n),e.vertexAttribDivisor=n.vertexAttribDivisorANGLE.bind(n)}if(this.extStandardDerivatives=this.getExtension("OES_standard_derivatives"),this.extTextureFloat=this.getExtension("OES_texture_float"),this.extTextureHalfFloat=this.getExtension("OES_texture_half_float"),this.extTextureLod=this.getExtension("EXT_shader_texture_lod"),this.extUintElement=this.getExtension("OES_element_index_uint"),this.extVertexArrayObject=this.getExtension("OES_vertex_array_object"),this.extVertexArrayObject){var s=this.extVertexArrayObject;e.createVertexArray=s.createVertexArrayOES.bind(s),e.deleteVertexArray=s.deleteVertexArrayOES.bind(s),e.isVertexArray=s.isVertexArrayOES.bind(s),e.bindVertexArray=s.bindVertexArrayOES.bind(s)}this.extColorBufferFloat=null,this.extDepthTexture=e.getExtension("WEBGL_depth_texture")}this.extDebugRendererInfo=this.getExtension("WEBGL_debug_renderer_info"),this.extTextureFloatLinear=this.getExtension("OES_texture_float_linear"),this.extTextureHalfFloatLinear=this.getExtension("OES_texture_half_float_linear"),this.extFloatBlend=this.getExtension("EXT_float_blend"),this.extTextureFilterAnisotropic=this.getExtension("EXT_texture_filter_anisotropic","WEBKIT_EXT_texture_filter_anisotropic"),this.extCompressedTextureETC1=this.getExtension("WEBGL_compressed_texture_etc1"),this.extCompressedTextureETC=this.getExtension("WEBGL_compressed_texture_etc"),this.extCompressedTexturePVRTC=this.getExtension("WEBGL_compressed_texture_pvrtc","WEBKIT_WEBGL_compressed_texture_pvrtc"),this.extCompressedTextureS3TC=this.getExtension("WEBGL_compressed_texture_s3tc","WEBKIT_WEBGL_compressed_texture_s3tc"),this.extCompressedTextureATC=this.getExtension("WEBGL_compressed_texture_atc"),this.extCompressedTextureASTC=this.getExtension("WEBGL_compressed_texture_astc"),this.extParallelShaderCompile=this.getExtension("KHR_parallel_shader_compile"),this.extColorBufferHalfFloat=this.getExtension("EXT_color_buffer_half_float")},n.initializeCapabilities=function(){var t,e,i,n=this.gl,s="undefined"!=typeof navigator?navigator.userAgent:"";this.maxPrecision=this.precision=this.getPrecision();var r=n.getContextAttributes();this.supportsMsaa=null!=(t=null==r?void 0:r.antialias)&&t,this.supportsStencil=null!=(e=null==r?void 0:r.stencil)&&e,this.supportsInstancing=!!this.extInstancing,this.maxTextureSize=n.getParameter(n.MAX_TEXTURE_SIZE),this.maxCubeMapSize=n.getParameter(n.MAX_CUBE_MAP_TEXTURE_SIZE),this.maxRenderBufferSize=n.getParameter(n.MAX_RENDERBUFFER_SIZE),this.maxTextures=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),this.maxCombinedTextures=n.getParameter(n.MAX_COMBINED_TEXTURE_IMAGE_UNITS),this.maxVertexTextures=n.getParameter(n.MAX_VERTEX_TEXTURE_IMAGE_UNITS),this.vertexUniformsCount=n.getParameter(n.MAX_VERTEX_UNIFORM_VECTORS),this.fragmentUniformsCount=n.getParameter(n.MAX_FRAGMENT_UNIFORM_VECTORS),this.isWebGL2?(this.maxDrawBuffers=n.getParameter(n.MAX_DRAW_BUFFERS),this.maxColorAttachments=n.getParameter(n.MAX_COLOR_ATTACHMENTS),this.maxVolumeSize=n.getParameter(n.MAX_3D_TEXTURE_SIZE),this.supportsMrt=!0,this.supportsVolumeTextures=!0):(i=this.extDrawBuffers,this.supportsMrt=!!i,this.maxDrawBuffers=i?n.getParameter(i.MAX_DRAW_BUFFERS_WEBGL):1,this.maxColorAttachments=i?n.getParameter(i.MAX_COLOR_ATTACHMENTS_WEBGL):1,this.maxVolumeSize=1),i=this.extDebugRendererInfo,this.unmaskedRenderer=i?n.getParameter(i.UNMASKED_RENDERER_WEBGL):"",this.unmaskedVendor=i?n.getParameter(i.UNMASKED_VENDOR_WEBGL):"";this.supportsGpuParticles=!("ARM"===this.unmaskedVendor&&s.match(/SM-[a-zA-Z0-9]+/)||this.unmaskedRenderer.match(/\bMali-G52+/)),i=this.extTextureFilterAnisotropic,this.maxAnisotropy=i?n.getParameter(i.MAX_TEXTURE_MAX_ANISOTROPY_EXT):1;var a=this.isWebGL2&&!this.forceDisableMultisampling;this.maxSamples=a?n.getParameter(n.MAX_SAMPLES):1,this.maxSamples=Math.min(this.maxSamples,4),this.samples=a&&this.backBufferAntialias?this.maxSamples:1,this.supportsAreaLights=this.isWebGL2||!G.android,this.supportsTextureFetch=this.isWebGL2,this.maxTextures<=8&&(this.supportsAreaLights=!1)},n.initializeRenderState=function(){t.prototype.initializeRenderState.call(this);var e=this.gl;e.disable(e.BLEND),e.blendFunc(e.ONE,e.ZERO),e.blendEquation(e.FUNC_ADD),e.colorMask(!0,!0,!0,!0),this.blendColor=new vt(0,0,0,0),e.blendColor(0,0,0,0),e.enable(e.CULL_FACE),e.cullFace(e.BACK),e.enable(e.DEPTH_TEST),e.depthFunc(e.LEQUAL),e.depthMask(!0),this.stencil=!1,e.disable(e.STENCIL_TEST),this.stencilFuncFront=this.stencilFuncBack=7,this.stencilRefFront=this.stencilRefBack=0,this.stencilMaskFront=this.stencilMaskBack=255,e.stencilFunc(e.ALWAYS,0,255),this.stencilFailFront=this.stencilFailBack=0,this.stencilZfailFront=this.stencilZfailBack=0,this.stencilZpassFront=this.stencilZpassBack=0,this.stencilWriteMaskFront=255,this.stencilWriteMaskBack=255,e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.stencilMask(255),this.alphaToCoverage=!1,this.raster=!0,this.isWebGL2&&(e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.disable(e.RASTERIZER_DISCARD)),this.depthBiasEnabled=!1,e.disable(e.POLYGON_OFFSET_FILL),this.clearDepth=1,e.clearDepth(1),this.clearColor=new vt(0,0,0,0),e.clearColor(0,0,0,0),this.clearStencil=0,e.clearStencil(0),this.isWebGL2?e.hint(e.FRAGMENT_SHADER_DERIVATIVE_HINT,e.NICEST):this.extStandardDerivatives&&e.hint(this.extStandardDerivatives.FRAGMENT_SHADER_DERIVATIVE_HINT_OES,e.NICEST),e.enable(e.SCISSOR_TEST),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.NONE),this.unpackFlipY=!1,e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),this.unpackPremultiplyAlpha=!1,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_ALIGNMENT,1)},n.initTextureUnits=function(t){void 0===t&&(t=16),this.textureUnits=[];for(var e=0;e<t;e++)this.textureUnits.push([null,null,null])},n.initializeContextCaches=function(){t.prototype.initializeContextCaches.call(this),this._vaoMap=new Map,this.boundVao=null,this.activeFramebuffer=null,this.feedback=null,this.transformFeedbackBuffer=null,this.textureUnit=0,this.initTextureUnits(this.maxCombinedTextures)},n.loseContext=function(){var t;this.backBufferSize.set(-1,-1);for(var e,i=A(this.shaders);!(e=i()).done;){e.value.loseContext()}for(var n,s=A(this.textures);!(n=s()).done;){n.value.loseContext()}for(var r,a=A(this.buffers);!(r=a()).done;){r.value.loseContext()}for(var o,h=A(this.targets);!(o=h()).done;){o.value.loseContext()}null==(t=this.gpuProfiler)||t.loseContext()},n.restoreContext=function(){var t;this.initializeExtensions(),this.initializeCapabilities(),this.initializeRenderState(),this.initializeContextCaches();for(var e,i=A(this.shaders);!(e=i()).done;){e.value.restoreContext()}for(var n,s=A(this.buffers);!(n=s()).done;){n.value.unlock()}null==(t=this.gpuProfiler)||t.restoreContext()},n.endShaderBatch=function(){Ws.endShaderBatch(this)},n.setViewport=function(t,e,i,n){this.vx===t&&this.vy===e&&this.vw===i&&this.vh===n||(this.gl.viewport(t,e,i,n),this.vx=t,this.vy=e,this.vw=i,this.vh=n)},n.setScissor=function(t,e,i,n){this.sx===t&&this.sy===e&&this.sw===i&&this.sh===n||(this.gl.scissor(t,e,i,n),this.sx=t,this.sy=e,this.sw=i,this.sh=n)},n.setFramebuffer=function(t){if(this.activeFramebuffer!==t){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,t),this.activeFramebuffer=t}},n.copyRenderTarget=function(t,e,i,n){var s=this.gl;if(t===this.backBuffer&&(t=null),!this.isWebGL2&&n)return!1;if(i)if(e){if(t){if(!t._colorBuffer||!e._colorBuffer)return!1;if(t._colorBuffer._format!==e._colorBuffer._format)return!1}}else if(!t._colorBuffer)return!1;if(n&&t&&!t._depth){if(!t._depthBuffer||!e._depthBuffer)return!1;if(t._depthBuffer._format!==e._depthBuffer._format)return!1}if(this.isWebGL2&&e){var r,a=this.renderTarget;this.renderTarget=e,this.updateBegin();var o=t?t.impl._glFrameBuffer:null==(r=this.backBuffer)?void 0:r.impl._glFrameBuffer,h=e.impl._glFrameBuffer;s.bindFramebuffer(s.READ_FRAMEBUFFER,o),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,h);var l=t?t.width:e.width,c=t?t.height:e.height;s.blitFramebuffer(0,0,l,c,0,0,l,c,(i?s.COLOR_BUFFER_BIT:0)|(n?s.DEPTH_BUFFER_BIT:0),s.NEAREST),this.renderTarget=a,s.bindFramebuffer(s.FRAMEBUFFER,a?a.impl._glFrameBuffer:null)}else{var u=this.getCopyShader();this.constantTexSource.setValue(t._colorBuffer),or(this,e,u)}return!0},n.getCopyShader=function(){return this._copyShader||(this._copyShader=new fs(this,ir.createDefinition(this,{name:"outputTex2D",vertexCode:ar,fragmentCode:"\nvarying vec2 vUv0;\nuniform sampler2D source;\nvoid main(void) {\n\tgl_FragColor = texture2D(source, vUv0);\n}\n"}))),this._copyShader},n.frameStart=function(){t.prototype.frameStart.call(this),this.updateBackbuffer(),this.gpuProfiler.frameStart()},n.frameEnd=function(){t.prototype.frameEnd.call(this),this.gpuProfiler.frameEnd(),this.gpuProfiler.request()},n.startPass=function(t){var e=t.renderTarget||this.backBuffer;this.renderTarget=e,this.updateBegin();var i=t.colorOps,n=t.depthStencilOps;if(null!=i&&i.clear||n.clearDepth||n.clearStencil){var s=t.renderTarget,r=s?s.width:this.width,a=s?s.height:this.height;this.setViewport(0,0,r,a),this.setScissor(0,0,r,a);var o=0,h={};null!=i&&i.clear&&(o|=1,h.color=[i.clearValue.r,i.clearValue.g,i.clearValue.b,i.clearValue.a]),n.clearDepth&&(o|=2,h.depth=n.clearDepthValue),n.clearStencil&&(o|=4,h.stencil=n.clearStencilValue),h.flags=o,this.clear(h)}this.insideRenderPass=!0},n.endPass=function(t){this.unbindVertexArray();var e=this.renderTarget,i=t.colorArrayOps.length;if(e){var n;if(this.isWebGL2){rr.length=0;for(var s=this.gl,r=0;r<i;r++){var a=t.colorArrayOps[r];a.store||a.resolve||rr.push(s.COLOR_ATTACHMENT0+r)}e!==this.backBuffer&&(t.depthStencilOps.storeDepth||rr.push(s.DEPTH_ATTACHMENT),t.depthStencilOps.storeStencil||rr.push(s.STENCIL_ATTACHMENT)),rr.length>0&&t.fullSizeClearRect&&s.invalidateFramebuffer(s.DRAW_FRAMEBUFFER,rr)}null!=(n=t.colorOps)&&n.resolve&&this.isWebGL2&&t.samples>1&&e.autoResolve&&e.resolve(!0,!1);for(var o=0;o<i;o++){if(t.colorArrayOps[o].mipmaps){var h=e._colorBuffers[o];h&&h.impl._glTexture&&h.mipmaps&&(h.pot||this.isWebGL2)&&(this.activeTexture(this.maxCombinedTextures-1),this.bindTexture(h),this.gl.generateMipmap(h.impl._glTarget))}}}this.insideRenderPass=!1},n.updateBegin=function(){var t;if(this.boundVao=null,this._tempEnableSafariTextureUnitWorkaround)for(var e=0;e<this.textureUnits.length;++e)for(var i=0;i<3;++i)this.textureUnits[e][i]=null;var n=null!=(t=this.renderTarget)?t:this.backBuffer,s=n.impl;s.initialized||this.initRenderTarget(n),this.setFramebuffer(s._glFrameBuffer)},n.updateEnd=function(){this.unbindVertexArray();var t=this.renderTarget;if(t&&t!==this.backBuffer){this.isWebGL2&&t._samples>1&&t.autoResolve&&t.resolve();var e=t._colorBuffer;e&&e.impl._glTexture&&e.mipmaps&&(e.pot||this.isWebGL2)&&(this.activeTexture(this.maxCombinedTextures-1),this.bindTexture(e),this.gl.generateMipmap(e.impl._glTarget))}},n.setUnpackFlipY=function(t){if(this.unpackFlipY!==t){this.unpackFlipY=t;var e=this.gl;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,t)}},n.setUnpackPremultiplyAlpha=function(t){if(this.unpackPremultiplyAlpha!==t){this.unpackPremultiplyAlpha=t;var e=this.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t)}},n.activeTexture=function(t){this.textureUnit!==t&&(this.gl.activeTexture(this.gl.TEXTURE0+t),this.textureUnit=t)},n.bindTexture=function(t){var e=t.impl,i=e._glTarget,n=e._glTexture,s=this.textureUnit,r=this.targetToSlot[i];this.textureUnits[s][r]!==n&&(this.gl.bindTexture(i,n),this.textureUnits[s][r]=n)},n.bindTextureOnUnit=function(t,e){var i=t.impl,n=i._glTarget,s=i._glTexture,r=this.targetToSlot[n];this.textureUnits[e][r]!==s&&(this.activeTexture(e),this.gl.bindTexture(n,s),this.textureUnits[e][r]=s)},n.setTextureParameters=function(t){var e=this.gl,i=t.impl.dirtyParameterFlags,n=t.impl._glTarget;if(1&i){var s=t._minFilter;(!t.pot&&!this.isWebGL2||!t._mipmaps||t._compressed&&1===t._levels.length)&&(2===s||3===s?s=0:4!==s&&5!==s||(s=1)),e.texParameteri(n,e.TEXTURE_MIN_FILTER,this.glFilter[s])}if(2&i&&e.texParameteri(n,e.TEXTURE_MAG_FILTER,this.glFilter[t._magFilter]),4&i&&(this.isWebGL2?e.texParameteri(n,e.TEXTURE_WRAP_S,this.glAddress[t._addressU]):e.texParameteri(n,e.TEXTURE_WRAP_S,this.glAddress[t.pot?t._addressU:1])),8&i&&(this.isWebGL2?e.texParameteri(n,e.TEXTURE_WRAP_T,this.glAddress[t._addressV]):e.texParameteri(n,e.TEXTURE_WRAP_T,this.glAddress[t.pot?t._addressV:1])),16&i&&this.isWebGL2&&e.texParameteri(n,e.TEXTURE_WRAP_R,this.glAddress[t._addressW]),32&i&&this.isWebGL2&&e.texParameteri(n,e.TEXTURE_COMPARE_MODE,t._compareOnRead?e.COMPARE_REF_TO_TEXTURE:e.NONE),64&i&&this.isWebGL2&&e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,this.glComparison[t._compareFunc]),128&i){var r=this.extTextureFilterAnisotropic;r&&e.texParameterf(n,r.TEXTURE_MAX_ANISOTROPY_EXT,_t.clamp(Math.round(t._anisotropy),1,this.maxAnisotropy))}},n.setTexture=function(t,e){var i=t.impl;i._glTexture||i.initialize(this,t),i.dirtyParameterFlags>0||t._needsUpload||t._needsMipmapsUpload?(this.activeTexture(e),this.bindTexture(t),i.dirtyParameterFlags&&(this.setTextureParameters(t),i.dirtyParameterFlags=0),(t._needsUpload||t._needsMipmapsUpload)&&(i.upload(this,t),t._needsUpload=!1,t._needsMipmapsUpload=!1)):this.bindTextureOnUnit(t,e)},n.createVertexArray=function(t){var e,i,n=t.length>1;if(n){e="";for(var s=0;s<t.length;s++){var r=t[s];e+=r.id+r.format.renderingHash}i=this._vaoMap.get(e)}if(!i){var a=this.gl;i=a.createVertexArray(),a.bindVertexArray(i),a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,null);for(var o=0;o<t.length;o++){var h=t[o];a.bindBuffer(a.ARRAY_BUFFER,h.impl.bufferId);for(var l=h.format.elements,c=0;c<l.length;c++){var u=l[c],d=Ri[u.name];a.vertexAttribPointer(d,u.numComponents,this.glType[u.dataType],u.normalize,u.stride,u.offset),a.enableVertexAttribArray(d),h.format.instancing&&a.vertexAttribDivisor(d,1)}}a.bindVertexArray(null),a.bindBuffer(a.ARRAY_BUFFER,null),n&&this._vaoMap.set(e,i)}return i},n.unbindVertexArray=function(){this.boundVao&&(this.boundVao=null,this.gl.bindVertexArray(null))},n.setBuffers=function(){var t,e=this.gl;if(1===this.vertexBuffers.length){var i=this.vertexBuffers[0];i.impl.vao||(i.impl.vao=this.createVertexArray(this.vertexBuffers)),t=i.impl.vao}else t=this.createVertexArray(this.vertexBuffers);this.boundVao!==t&&(this.boundVao=t,e.bindVertexArray(t)),this.vertexBuffers.length=0;var n=this.indexBuffer?this.indexBuffer.impl.bufferId:null;e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)},n.draw=function(t,e,i){var n,s,r,a,o,h,l,c,u=this.gl,d=this.shader;if(d){var f=d.impl.samplers,p=d.impl.uniforms;i||this.setBuffers();for(var m=0,_=0,v=f.length;_<v;_++){if(!(s=(n=f[_]).scopeId.value))return;if(s instanceof Ls)r=s,this.setTexture(r,m),n.slot!==m&&(u.uniform1i(n.locationId,m),n.slot=m),m++;else{n.array.length=0,a=s.length;for(var g=0;g<a;g++)r=s[g],this.setTexture(r,m),n.array[g]=m,m++;u.uniform1iv(n.locationId,n.array)}}for(var y=0,x=p.length;y<x;y++)h=(o=p[y]).scopeId,l=o.version,c=h.versionObject.version,l.globalId===c.globalId&&l.revision===c.revision||(l.globalId=c.globalId,l.revision=c.revision,null!==h.value&&this.commitFunction[o.dataType](o,h.value));this.isWebGL2&&this.transformFeedbackBuffer&&(u.bindBufferBase(u.TRANSFORM_FEEDBACK_BUFFER,0,this.transformFeedbackBuffer.impl.bufferId),u.beginTransformFeedback(u.POINTS));var S=this.glPrimitive[t.type],b=t.count;if(t.indexed){var w=this.indexBuffer,T=w.impl.glFormat,A=t.base*w.bytesPerIndex;e>0?u.drawElementsInstanced(S,b,T,A,e):u.drawElements(S,b,T,A)}else{var C=t.base;e>0?u.drawArraysInstanced(S,C,b,e):u.drawArrays(S,C,b)}this.isWebGL2&&this.transformFeedbackBuffer&&(u.endTransformFeedback(),u.bindBufferBase(u.TRANSFORM_FEEDBACK_BUFFER,0,null)),this._drawCallsPerFrame++}},n.clear=function(t){var e,i=this.defaultClearOptions,n=null!=(e=(t=t||i).flags)?e:i.flags;if(0!==n){var s=this.gl;if(1&n){var r,a=null!=(r=t.color)?r:i.color,o=a[0],h=a[1],l=a[2],c=a[3],u=this.clearColor;o===u.r&&h===u.g&&l===u.b&&c===u.a||(this.gl.clearColor(o,h,l,c),this.clearColor.set(o,h,l,c)),this.setBlendState(Ui.NOBLEND)}if(2&n){var d,f=null!=(d=t.depth)?d:i.depth;f!==this.clearDepth&&(this.gl.clearDepth(f),this.clearDepth=f),this.setDepthState(Ni.WRITEDEPTH)}if(4&n){var p,m=null!=(p=t.stencil)?p:i.stencil;m!==this.clearStencil&&(this.gl.clearStencil(m),this.clearStencil=m)}s.clear(this.glClearFlag[n])}},n.submit=function(){this.gl.flush()},n.readPixels=function(t,e,i,n,s){var r=this.gl;r.readPixels(t,e,i,n,r.RGBA,r.UNSIGNED_BYTE,s)},n.readPixelsAsync=(i=v(m().mark((function t(e,i,n,s,r){var a,o,h,l,c,u,d,f,p,_=this;return m().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(l=this.gl,this.isWebGL2){t.next=4;break}return this.readPixels(e,i,n,s,r),t.abrupt("return");case 4:return c=function(t,e){var i=l.fenceSync(l.SYNC_GPU_COMMANDS_COMPLETE,0);return _.submit(),new Promise((function(n,s){!function r(){var a=l.clientWaitSync(i,t,0);a===l.WAIT_FAILED?(l.deleteSync(i),s(new Error("webgl clientWaitSync sync failed"))):a===l.TIMEOUT_EXPIRED?setTimeout(r,e):(l.deleteSync(i),n())}()}))},u=null==(a=this.renderTarget.colorBuffer)?void 0:a.impl,d=null!=(o=null==u?void 0:u._glFormat)?o:l.RGBA,f=null!=(h=null==u?void 0:u._glPixelType)?h:l.UNSIGNED_BYTE,p=l.createBuffer(),l.bindBuffer(l.PIXEL_PACK_BUFFER,p),l.bufferData(l.PIXEL_PACK_BUFFER,r.byteLength,l.STREAM_READ),l.readPixels(e,i,n,s,d,f,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),t.next=15,c(0,20);case 15:l.bindBuffer(l.PIXEL_PACK_BUFFER,p),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,r),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteBuffer(p);case 19:case"end":return t.stop()}}),t,this)}))),function(t,e,n,s,r){return i.apply(this,arguments)}),n.setAlphaToCoverage=function(t){this.isWebGL1||this.alphaToCoverage!==t&&(this.alphaToCoverage=t,t?this.gl.enable(this.gl.SAMPLE_ALPHA_TO_COVERAGE):this.gl.disable(this.gl.SAMPLE_ALPHA_TO_COVERAGE))},n.setTransformFeedbackBuffer=function(t){if(this.transformFeedbackBuffer!==t&&(this.transformFeedbackBuffer=t,this.isWebGL2)){var e=this.gl;t?(this.feedback||(this.feedback=e.createTransformFeedback()),e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,this.feedback)):e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,null)}},n.setRaster=function(t){this.raster!==t&&(this.raster=t,this.isWebGL2&&(t?this.gl.disable(this.gl.RASTERIZER_DISCARD):this.gl.enable(this.gl.RASTERIZER_DISCARD)))},n.setDepthBias=function(t){this.depthBiasEnabled!==t&&(this.depthBiasEnabled=t,t?this.gl.enable(this.gl.POLYGON_OFFSET_FILL):this.gl.disable(this.gl.POLYGON_OFFSET_FILL))},n.setDepthBiasValues=function(t,e){this.gl.polygonOffset(e,t)},n.setStencilTest=function(t){if(this.stencil!==t){var e=this.gl;t?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this.stencil=t}},n.setStencilFunc=function(t,e,i){this.stencilFuncFront===t&&this.stencilRefFront===e&&this.stencilMaskFront===i&&this.stencilFuncBack===t&&this.stencilRefBack===e&&this.stencilMaskBack===i||(this.gl.stencilFunc(this.glComparison[t],e,i),this.stencilFuncFront=this.stencilFuncBack=t,this.stencilRefFront=this.stencilRefBack=e,this.stencilMaskFront=this.stencilMaskBack=i)},n.setStencilFuncFront=function(t,e,i){if(this.stencilFuncFront!==t||this.stencilRefFront!==e||this.stencilMaskFront!==i){var n=this.gl;n.stencilFuncSeparate(n.FRONT,this.glComparison[t],e,i),this.stencilFuncFront=t,this.stencilRefFront=e,this.stencilMaskFront=i}},n.setStencilFuncBack=function(t,e,i){if(this.stencilFuncBack!==t||this.stencilRefBack!==e||this.stencilMaskBack!==i){var n=this.gl;n.stencilFuncSeparate(n.BACK,this.glComparison[t],e,i),this.stencilFuncBack=t,this.stencilRefBack=e,this.stencilMaskBack=i}},n.setStencilOperation=function(t,e,i,n){this.stencilFailFront===t&&this.stencilZfailFront===e&&this.stencilZpassFront===i&&this.stencilFailBack===t&&this.stencilZfailBack===e&&this.stencilZpassBack===i||(this.gl.stencilOp(this.glStencilOp[t],this.glStencilOp[e],this.glStencilOp[i]),this.stencilFailFront=this.stencilFailBack=t,this.stencilZfailFront=this.stencilZfailBack=e,this.stencilZpassFront=this.stencilZpassBack=i),this.stencilWriteMaskFront===n&&this.stencilWriteMaskBack===n||(this.gl.stencilMask(n),this.stencilWriteMaskFront=n,this.stencilWriteMaskBack=n)},n.setStencilOperationFront=function(t,e,i,n){this.stencilFailFront===t&&this.stencilZfailFront===e&&this.stencilZpassFront===i||(this.gl.stencilOpSeparate(this.gl.FRONT,this.glStencilOp[t],this.glStencilOp[e],this.glStencilOp[i]),this.stencilFailFront=t,this.stencilZfailFront=e,this.stencilZpassFront=i),this.stencilWriteMaskFront!==n&&(this.gl.stencilMaskSeparate(this.gl.FRONT,n),this.stencilWriteMaskFront=n)},n.setStencilOperationBack=function(t,e,i,n){this.stencilFailBack===t&&this.stencilZfailBack===e&&this.stencilZpassBack===i||(this.gl.stencilOpSeparate(this.gl.BACK,this.glStencilOp[t],this.glStencilOp[e],this.glStencilOp[i]),this.stencilFailBack=t,this.stencilZfailBack=e,this.stencilZpassBack=i),this.stencilWriteMaskBack!==n&&(this.gl.stencilMaskSeparate(this.gl.BACK,n),this.stencilWriteMaskBack=n)},n.setBlendState=function(t){var e=this.blendState;if(!e.equals(t)){var i=this.gl,n=t.blend,s=t.colorOp,r=t.alphaOp,a=t.colorSrcFactor,o=t.colorDstFactor,h=t.alphaSrcFactor,l=t.alphaDstFactor;if(e.blend!==n&&(n?i.enable(i.BLEND):i.disable(i.BLEND)),e.colorOp!==s||e.alphaOp!==r){var c=this.glBlendEquation;i.blendEquationSeparate(c[s],c[r])}e.colorSrcFactor===a&&e.colorDstFactor===o&&e.alphaSrcFactor===h&&e.alphaDstFactor===l||i.blendFuncSeparate(this.glBlendFunctionColor[a],this.glBlendFunctionColor[o],this.glBlendFunctionAlpha[h],this.glBlendFunctionAlpha[l]),e.allWrite!==t.allWrite&&this.gl.colorMask(t.redWrite,t.greenWrite,t.blueWrite,t.alphaWrite),e.copy(t)}},n.setBlendColor=function(t,e,i,n){var s=this.blendColor;t===s.r&&e===s.g&&i===s.b&&n===s.a||(this.gl.blendColor(t,e,i,n),s.set(t,e,i,n))},n.setStencilState=function(t,e){t||e?(this.setStencilTest(!0),t===e?(this.setStencilFunc(t.func,t.ref,t.readMask),this.setStencilOperation(t.fail,t.zfail,t.zpass,t.writeMask)):(null!=t||(t=en.DEFAULT),this.setStencilFuncFront(t.func,t.ref,t.readMask),this.setStencilOperationFront(t.fail,t.zfail,t.zpass,t.writeMask),null!=e||(e=en.DEFAULT),this.setStencilFuncBack(e.func,e.ref,e.readMask),this.setStencilOperationBack(e.fail,e.zfail,e.zpass,e.writeMask))):this.setStencilTest(!1)},n.setDepthState=function(t){var e=this.depthState;if(!e.equals(t)){var i=this.gl,n=t.write;e.write!==n&&i.depthMask(n);var s=t.func,r=t.test;!r&&n&&(r=!0,s=7),e.func!==s&&i.depthFunc(this.glComparison[s]),e.test!==r&&(r?i.enable(i.DEPTH_TEST):i.disable(i.DEPTH_TEST)),e.copy(t)}},n.setCullMode=function(t){if(this.cullMode!==t){if(t===se)this.gl.disable(this.gl.CULL_FACE);else{this.cullMode===se&&this.gl.enable(this.gl.CULL_FACE);var e=this.glCull[t];this.cullFace!==e&&(this.gl.cullFace(e),this.cullFace=e)}this.cullMode=t}},n.setShader=function(t){if(t!==this.shader){if(t.failed)return!1;if(!t.ready&&!t.impl.finalize(this,t))return t.failed=!0,!1;this.shader=t,this.gl.useProgram(t.impl.glProgram),this.attributesInvalidated=!0}return!0},n.getHdrFormat=function(t,e,i,n){var s=this.extTextureHalfFloat&&(!e||this.textureHalfFloatRenderable)&&(!i||this.textureHalfFloatUpdatable)&&(!n||this.extTextureHalfFloatLinear),r=this.extTextureFloat&&(!e||this.textureFloatRenderable)&&(!n||this.extTextureFloatLinear);return s&&r?t?le:oe:s?oe:r?le:null},n.clearVertexArrayObjectCache=function(){var t=this.gl;this._vaoMap.forEach((function(e,i,n){t.deleteVertexArray(e)})),this._vaoMap.clear()},y(e,[{key:"extDisjointTimerQuery",get:function(){return this._extDisjointTimerQuery||this.isWebGL2&&(this._extDisjointTimerQuery=this.getExtension("EXT_disjoint_timer_query_webgl2","EXT_disjoint_timer_query")),this._extDisjointTimerQuery}},{key:"defaultFramebuffer",get:function(){return this._defaultFramebuffer},set:function(t){this._defaultFramebuffer!==t&&(this._defaultFramebuffer=t,this._defaultFramebufferChanged=!0)}},{key:"fullscreen",get:function(){return!!document.fullscreenElement},set:function(t){t?this.gl.canvas.requestFullscreen():document.exitFullscreen()}},{key:"textureFloatHighPrecision",get:function(){return void 0===this._textureFloatHighPrecision&&(this._textureFloatHighPrecision=function(t){if(!t.textureFloatRenderable)return!1;var e=new fs(t,ir.createDefinition(t,{name:"ptest1",vertexCode:ar,fragmentCode:"\nvoid main(void) { \n\tgl_FragColor = vec4(2147483648.0);\n}\n"})),i=new fs(t,ir.createDefinition(t,{name:"ptest2",vertexCode:ar,fragmentCode:"\nuniform sampler2D source;\nvec4 packFloat(float depth) {\n\tconst vec4 bit_shift = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);\n\tvec4 res = mod(depth * bit_shift * vec4(255), vec4(256) ) / vec4(255);\n\tres -= res.xxyz * bit_mask;\n\treturn res;\n}\nvoid main(void) {\n\tfloat c = texture2D(source, vec2(0.0)).r;\n\tfloat diff = abs(c - 2147483648.0) / 2147483648.0;\n\tgl_FragColor = packFloat(diff);\n}\n"})),n={format:le,width:1,height:1,mipmaps:!1,minFilter:0,magFilter:0,name:"testFHP"},s=new Ls(t,n),r=new rn({colorBuffer:s,depth:!1});or(t,r,e),n.format=7;var a=new Ls(t,n),o=new rn({colorBuffer:a,depth:!1});t.constantTexSource.setValue(s),or(t,o,i);var h=t.activeFramebuffer;t.setFramebuffer(o.impl._glFrameBuffer);var l=new Uint8Array(4);t.readPixels(0,0,1,1,l),t.setFramebuffer(h);var c=l[0]/255/16777216+l[1]/255/65536+l[2]/255/256+l[3]/255;return s.destroy(),r.destroy(),a.destroy(),o.destroy(),e.destroy(),i.destroy(),0===c}(this)),this._textureFloatHighPrecision}},{key:"textureHalfFloatUpdatable",get:function(){return void 0===this._textureHalfFloatUpdatable&&(this.isWebGL2?this._textureHalfFloatUpdatable=!0:this._textureHalfFloatUpdatable=function(t,e){var i=!0,n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE);var s=new Uint16Array(16);return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,2,2,0,t.RGBA,e,s),t.getError()!==t.NO_ERROR&&(i=!1,console.log("Above error related to HALF_FLOAT_OES can be ignored, it was triggered by testing half float texture support")),t.bindTexture(t.TEXTURE_2D,null),t.deleteTexture(n),i}(this.gl,this.extTextureHalfFloat.HALF_FLOAT_OES)),this._textureHalfFloatUpdatable}}]),e}(nn),cr=function(){function t(){}return t.prototype.unlock=function(t){},t}(),ur=function(){function t(){}var e=t.prototype;return e.destroy=function(t){},e.init=function(t,e){},e.loseContext=function(){},e.resolve=function(t,e,i,n){},t}(),dr=function(){function t(){}var e=t.prototype;return e.destroy=function(t){},e.loseContext=function(){},e.restoreContext=function(t,e){},t}(),fr=function(){function t(){}var e=t.prototype;return e.destroy=function(t){},e.propertyChanged=function(t){},e.loseContext=function(){},t}(),pr=function(){function t(){}var e=t.prototype;return e.destroy=function(t){},e.unlock=function(t){},t}(),mr=function(t){function e(e,i){var n;return void 0===i&&(i={}),i=(n=t.call(this,e,i)||this).initOptions,n.isNull=!0,n._deviceType=bi,n.samples=1,n}S(e,t);var i=e.prototype;return i.destroy=function(){t.prototype.destroy.call(this)},i.initDeviceCaps=function(){this.disableParticleSystem=!0,this.precision="highp",this.maxPrecision="highp",this.maxSamples=4,this.maxTextures=16,this.maxTextureSize=4096,this.maxCubeMapSize=4096,this.maxVolumeSize=4096,this.maxColorAttachments=8,this.maxPixelRatio=1,this.maxAnisotropy=16,this.supportsInstancing=!0,this.supportsUniformBuffers=!1,this.supportsVolumeTextures=!0,this.supportsBoneTextures=!0,this.supportsMorphTargetTexturesCore=!0,this.supportsAreaLights=!0,this.supportsDepthShadow=!0,this.supportsGpuParticles=!1,this.supportsMrt=!0,this.extUintElement=!0,this.extTextureFloat=!0,this.textureFloatRenderable=!0,this.extTextureHalfFloat=!0,this.textureHalfFloatRenderable=!0,this.textureHalfFloatUpdatable=!0,this.boneLimit=1024,this.supportsImageBitmap=!0,this.extStandardDerivatives=!0,this.extBlendMinmax=!0,this.areaLightLutFormat=7,this.supportsTextureFetch=!0},i.postInit=function(){t.prototype.postInit.call(this)},i.frameStart=function(){t.prototype.frameStart.call(this)},i.frameEnd=function(){t.prototype.frameEnd.call(this)},i.createVertexBufferImpl=function(t,e){return new pr(t,e)},i.createIndexBufferImpl=function(t){return new cr(t)},i.createShaderImpl=function(t){return new dr(t)},i.createTextureImpl=function(t){return new fr(t)},i.createRenderTargetImpl=function(t){return new ur(t)},i.draw=function(t,e,i){},i.setShader=function(t){return!0},i.setBlendState=function(t){},i.setDepthState=function(t){},i.setStencilState=function(t,e){},i.setBlendColor=function(t,e,i,n){},i.setCullMode=function(t){},i.setAlphaToCoverage=function(t){},i.initializeContextCaches=function(){t.prototype.initializeContextCaches.call(this)},i.startPass=function(t){},i.endPass=function(t){},i.clear=function(t){},i.setDepthBias=function(t){},i.setDepthBiasValues=function(t,e){},i.setViewport=function(t,e,i,n){},i.setScissor=function(t,e,i,n){},i.copyRenderTarget=function(t,e,i,n){return!0},e}(nn);var _r=0,vr=function(){function t(t,e,i,n,s){void 0===n&&(n=0),this.device=t,this.format=e,this.numIndices=i,this.usage=n,this.id=_r++,this.impl=t.createIndexBufferImpl(this);var r=Pi[e];this.bytesPerIndex=r,this.numBytes=this.numIndices*r,s?this.setData(s):this.storage=new ArrayBuffer(this.numBytes),this.adjustVramSizeTracking(t._vram,this.numBytes),this.device.buffers.push(this)}var e=t.prototype;return e.destroy=function(){var t=this.device,e=t.buffers.indexOf(this);-1!==e&&t.buffers.splice(e,1),this.device.indexBuffer===this&&(this.device.indexBuffer=null),this.impl.initialized&&(this.impl.destroy(t),this.adjustVramSizeTracking(t._vram,-this.storage.byteLength))},e.adjustVramSizeTracking=function(t,e){t.ib+=e},e.loseContext=function(){this.impl.loseContext()},e.getFormat=function(){return this.format},e.getNumIndices=function(){return this.numIndices},e.lock=function(){return this.storage},e.unlock=function(){this.impl.unlock(this)},e.setData=function(t){return t.byteLength===this.numBytes&&(this.storage=t,this.unlock(),!0)},e._lockTypedArray=function(){var t=this.lock();return 2===this.format?new Uint32Array(t):1===this.format?new Uint16Array(t):new Uint8Array(t)},e.writeData=function(t,e){var i=this._lockTypedArray();if(t.length>e)if(ArrayBuffer.isView(t))t=t.subarray(0,e),i.set(t);else for(var n=0;n<e;n++)i[n]=t[n];else i.set(t);this.unlock()},e.readData=function(t){var e=this._lockTypedArray(),i=this.numIndices;if(ArrayBuffer.isView(t))t.set(e);else{t.length=0;for(var n=0;n<i;n++)t[n]=e[n]}return i},t}(),gr=function(){function t(t,e){void 0===e&&(e=3),this.device=t.device;var i=this.device.gl;this._inputBuffer=t,3===e&&t.usage!==e&&(i.bindBuffer(i.ARRAY_BUFFER,t.impl.bufferId),i.bufferData(i.ARRAY_BUFFER,t.storage,i.DYNAMIC_COPY)),this._outputBuffer=new ji(t.device,t.format,t.numVertices,e,t.storage)}t.createShader=function(t,e,i){return new fs(t,ir.createDefinition(t,{name:i,vertexCode:e,useTransformFeedback:!0}))};var e=t.prototype;return e.destroy=function(){this._outputBuffer.destroy()},e.process=function(t,e){void 0===e&&(e=!0);var i=this.device,n=i.getRenderTarget();if(i.setRenderTarget(null),i.updateBegin(),i.setVertexBuffer(this._inputBuffer,0),i.setRaster(!1),i.setTransformFeedbackBuffer(this._outputBuffer),i.setShader(t),i.draw({type:0,base:0,count:this._inputBuffer.numVertices,indexed:!1}),i.setTransformFeedbackBuffer(null),i.setRaster(!0),i.updateEnd(),i.setRenderTarget(n),e){var s=this._inputBuffer.impl.bufferId;this._inputBuffer.impl.bufferId=this._outputBuffer.impl.bufferId,this._outputBuffer.impl.bufferId=s,s=this._inputBuffer.impl.vao,this._inputBuffer.impl.vao=this._outputBuffer.impl.vao,this._outputBuffer.impl.vao=s}},y(t,[{key:"inputBuffer",get:function(){return this._inputBuffer}},{key:"outputBuffer",get:function(){return this._outputBuffer}}]),t}();function yr(t){this.array[this.index]=t}function xr(t,e){this.array[this.index]=t,this.array[this.index+1]=e}function Sr(t,e,i){this.array[this.index]=t,this.array[this.index+1]=e,this.array[this.index+2]=i}function br(t,e,i,n){this.array[this.index]=t,this.array[this.index+1]=e,this.array[this.index+2]=i,this.array[this.index+3]=n}function wr(t,e,i){this.array[t]=e[i]}function Tr(t,e,i){this.array[t]=e[i],this.array[t+1]=e[i+1]}function Ar(t,e,i){this.array[t]=e[i],this.array[t+1]=e[i+1],this.array[t+2]=e[i+2]}function Cr(t,e,i){this.array[t]=e[i],this.array[t+1]=e[i+1],this.array[t+2]=e[i+2],this.array[t+3]=e[i+3]}function Er(t,e,i){e[i]=this.array[t]}function Mr(t,e,i){e[i]=this.array[t],e[i+1]=this.array[t+1]}function Pr(t,e,i){e[i]=this.array[t],e[i+1]=this.array[t+1],e[i+2]=this.array[t+2]}function Rr(t,e,i){e[i]=this.array[t],e[i+1]=this.array[t+1],e[i+2]=this.array[t+2],e[i+3]=this.array[t+3]}var Ir=function(){function t(t,e,i){switch(this.index=0,this.numComponents=e.numComponents,i.interleaved?this.array=new Ai[e.dataType](t,e.offset):this.array=new Ai[e.dataType](t,e.offset,i.vertexCount*e.numComponents),this.stride=e.stride/this.array.constructor.BYTES_PER_ELEMENT,e.numComponents){case 1:this.set=yr,this.getToArray=Er,this.setFromArray=wr;break;case 2:this.set=xr,this.getToArray=Mr,this.setFromArray=Tr;break;case 3:this.set=Sr,this.getToArray=Pr,this.setFromArray=Ar;break;case 4:this.set=br,this.getToArray=Rr,this.setFromArray=Cr}}var e=t.prototype;return e.get=function(t){return this.array[this.index+t]},e.set=function(t,e,i,n){},e.getToArray=function(t,e,i){},e.setFromArray=function(t,e,i){},t}(),Lr=function(){function t(t){this.vertexBuffer=t,this.vertexFormatSize=t.getFormat().size,this.buffer=this.vertexBuffer.lock(),this.accessors=[],this.element={};for(var e=this.vertexBuffer.getFormat(),i=0;i<e.elements.length;i++){var n=e.elements[i];this.accessors[i]=new Ir(this.buffer,n,e),this.element[n.name]=this.accessors[i]}}var e=t.prototype;return e.next=function(t){void 0===t&&(t=1);for(var e=0,i=this.accessors,n=this.accessors.length;e<n;){var s=i[e++];s.index+=t*s.stride}},e.end=function(){this.vertexBuffer.unlock()},e.writeData=function(t,e,i){var n=this.element[t];if(n){i>this.vertexBuffer.numVertices&&(i=this.vertexBuffer.numVertices);var s=n.numComponents;if(this.vertexBuffer.getFormat().interleaved)for(var r=0,a=0;a<i;a++)n.setFromArray(r,e,a*s),r+=n.stride;else if(e.length>i*s){var o=i*s;if(ArrayBuffer.isView(e))e=e.subarray(0,o),n.array.set(e);else for(var h=0;h<o;h++)n.array[h]=e[h]}else n.array.set(e)}},e.readData=function(t,e){var i=this.element[t],n=0;if(i){var s;n=this.vertexBuffer.numVertices;var r=i.numComponents;if(this.vertexBuffer.getFormat().interleaved){Array.isArray(e)&&(e.length=0),i.index=0;var a=0;for(s=0;s<n;s++)i.getToArray(a,e,s*r),a+=i.stride}else if(ArrayBuffer.isView(e))e.set(i.array);else{e.length=0;var o=n*r;for(s=0;s<o;s++)e[s]=i.array[s]}}return n},t}(),Dr="mouse",Or="keyboard",kr="gamepad",Fr="mousedown",Br="mousemove",Ur="mouseup",Nr="mousewheel",zr="gamepadconnected",Vr="gamepaddisconnected",Gr=function(t,e){e?(this.key=e.keyCode,this.element=e.target,this.event=e):(this.key=null,this.element=null,this.event=null)},Hr=new Gr;function Wr(t){return Hr.key=t.keyCode,Hr.element=t.target,Hr.event=t,Hr}function Xr(t){return"string"==typeof t?t.toUpperCase().charCodeAt(0):t}var jr={9:"Tab",13:"Enter",16:"Shift",17:"Control",18:"Alt",27:"Escape",37:"Left",38:"Up",39:"Right",40:"Down",46:"Delete",91:"Win"},qr=function(t){function e(e,i){var n;return void 0===i&&(i={}),(n=t.call(this)||this)._element=null,n._keyDownHandler=n._handleKeyDown.bind(w(n)),n._keyUpHandler=n._handleKeyUp.bind(w(n)),n._keyPressHandler=n._handleKeyPress.bind(w(n)),n._visibilityChangeHandler=n._handleVisibilityChange.bind(w(n)),n._windowBlurHandler=n._handleWindowBlur.bind(w(n)),n._keymap={},n._lastmap={},e&&n.attach(e),n.preventDefault=i.preventDefault||!1,n.stopPropagation=i.stopPropagation||!1,n}S(e,t);var i=e.prototype;return i.attach=function(t){this._element&&this.detach(),this._element=t,this._element.addEventListener("keydown",this._keyDownHandler,!1),this._element.addEventListener("keypress",this._keyPressHandler,!1),this._element.addEventListener("keyup",this._keyUpHandler,!1),document.addEventListener("visibilitychange",this._visibilityChangeHandler,!1),window.addEventListener("blur",this._windowBlurHandler,!1)},i.detach=function(){this._element&&(this._element.removeEventListener("keydown",this._keyDownHandler),this._element.removeEventListener("keypress",this._keyPressHandler),this._element.removeEventListener("keyup",this._keyUpHandler),this._element=null,document.removeEventListener("visibilitychange",this._visibilityChangeHandler,!1),window.removeEventListener("blur",this._windowBlurHandler,!1))},i.toKeyIdentifier=function(t){t=Xr(t);var e=jr[t.toString()];if(e)return e;for(var i=t.toString(16).toUpperCase(),n=i.length,s=0;s<4-n;s++)i="0"+i;return"U+"+i},i._handleKeyDown=function(t){var e=t.keyCode||t.charCode;if(void 0!==e){var i=this.toKeyIdentifier(e);this._keymap[i]=!0,this.fire("keydown",Wr(t)),this.preventDefault&&t.preventDefault(),this.stopPropagation&&t.stopPropagation()}},i._handleKeyUp=function(t){var e=t.keyCode||t.charCode;if(void 0!==e){var i=this.toKeyIdentifier(e);delete this._keymap[i],this.fire("keyup",Wr(t)),this.preventDefault&&t.preventDefault(),this.stopPropagation&&t.stopPropagation()}},i._handleKeyPress=function(t){this.fire("keypress",Wr(t)),this.preventDefault&&t.preventDefault(),this.stopPropagation&&t.stopPropagation()},i._handleVisibilityChange=function(){"hidden"===document.visibilityState&&this._handleWindowBlur()},i._handleWindowBlur=function(){this._keymap={},this._lastmap={}},i.update=function(){for(var t in this._lastmap)delete this._lastmap[t];for(var e in this._keymap)this._keymap.hasOwnProperty(e)&&(this._lastmap[e]=this._keymap[e])},i.isPressed=function(t){var e=Xr(t),i=this.toKeyIdentifier(e);return!!this._keymap[i]},i.wasPressed=function(t){var e=Xr(t),i=this.toKeyIdentifier(e);return!!this._keymap[i]&&!this._lastmap[i]},i.wasReleased=function(t){var e=Xr(t),i=this.toKeyIdentifier(e);return!this._keymap[i]&&!!this._lastmap[i]},e}(P);function Yr(){return!!(document.pointerLockElement||document.mozPointerLockElement||document.webkitPointerLockElement)}var Kr=function t(e,i){var n={x:0,y:0};if(i){if(i instanceof t)throw Error("Expected MouseEvent");n=e._getTargetCoords(i)}else i={};if(n)this.x=n.x,this.y=n.y;else{if(!Yr())return;this.x=0,this.y=0}this.wheelDelta=0,"wheel"===i.type&&(i.deltaY>0?this.wheelDelta=1:i.deltaY<0&&(this.wheelDelta=-1)),Yr()?(this.dx=i.movementX||i.webkitMovementX||i.mozMovementX||0,this.dy=i.movementY||i.webkitMovementY||i.mozMovementY||0):(this.dx=this.x-e._lastX,this.dy=this.y-e._lastY),"mousedown"===i.type||"mouseup"===i.type?this.button=i.button:this.button=-1,this.buttons=e._buttons.slice(0),this.element=i.target,this.ctrlKey=i.ctrlKey||!1,this.altKey=i.altKey||!1,this.shiftKey=i.shiftKey||!1,this.metaKey=i.metaKey||!1,this.event=i},Zr=function(t){function e(e){var i;return(i=t.call(this)||this)._lastX=0,i._lastY=0,i._buttons=[!1,!1,!1],i._lastbuttons=[!1,!1,!1],i._upHandler=i._handleUp.bind(w(i)),i._downHandler=i._handleDown.bind(w(i)),i._moveHandler=i._handleMove.bind(w(i)),i._wheelHandler=i._handleWheel.bind(w(i)),i._contextMenuHandler=function(t){t.preventDefault()},i._target=null,i._attached=!1,i.attach(e),i}S(e,t),e.isPointerLocked=function(){return Yr()};var i=e.prototype;return i.attach=function(t){if(this._target=t,!this._attached){this._attached=!0;var e=!!G.passiveEvents&&{passive:!1};window.addEventListener("mouseup",this._upHandler,e),window.addEventListener("mousedown",this._downHandler,e),window.addEventListener("mousemove",this._moveHandler,e),window.addEventListener("wheel",this._wheelHandler,e)}},i.detach=function(){if(this._attached){this._attached=!1,this._target=null;var t=!!G.passiveEvents&&{passive:!1};window.removeEventListener("mouseup",this._upHandler,t),window.removeEventListener("mousedown",this._downHandler,t),window.removeEventListener("mousemove",this._moveHandler,t),window.removeEventListener("wheel",this._wheelHandler,t)}},i.disableContextMenu=function(){this._target&&this._target.addEventListener("contextmenu",this._contextMenuHandler)},i.enableContextMenu=function(){this._target&&this._target.removeEventListener("contextmenu",this._contextMenuHandler)},i.enablePointerLock=function(t,e){if(document.body.requestPointerLock){t&&document.addEventListener("pointerlockchange",(function e(){t(),document.removeEventListener("pointerlockchange",e)}),!1),e&&document.addEventListener("pointerlockerror",(function t(){e(),document.removeEventListener("pointerlockerror",t)}),!1),document.body.requestPointerLock()}else e&&e()},i.disablePointerLock=function(t){if(document.exitPointerLock){t&&document.addEventListener("pointerlockchange",(function e(){t(),document.removeEventListener("pointerlockchange",e)}),!1),document.exitPointerLock()}},i.update=function(){this._lastbuttons[0]=this._buttons[0],this._lastbuttons[1]=this._buttons[1],this._lastbuttons[2]=this._buttons[2]},i.isPressed=function(t){return this._buttons[t]},i.wasPressed=function(t){return this._buttons[t]&&!this._lastbuttons[t]},i.wasReleased=function(t){return!this._buttons[t]&&this._lastbuttons[t]},i._handleUp=function(t){this._buttons[t.button]=!1;var e=new Kr(this,t);e.event&&this.fire(Ur,e)},i._handleDown=function(t){this._buttons[t.button]=!0;var e=new Kr(this,t);e.event&&this.fire(Fr,e)},i._handleMove=function(t){var e=new Kr(this,t);e.event&&(this.fire(Br,e),this._lastX=e.x,this._lastY=e.y)},i._handleWheel=function(t){var e=new Kr(this,t);e.event&&this.fire(Nr,e)},i._getTargetCoords=function(t){var e=this._target.getBoundingClientRect(),i=Math.floor(e.left),n=Math.floor(e.top);return t.clientX<i||t.clientX>=i+this._target.clientWidth||t.clientY<n||t.clientY>=n+this._target.clientHeight?null:{x:t.clientX-i,y:t.clientY-n}},e}(P),Qr=function(){function t(t,e){void 0===e&&(e={}),this._keyboard=e.keyboard||null,this._mouse=e.mouse||null,this._gamepads=e.gamepads||null,this._element=null,this._actions={},this._axes={},this._axesValues={},t&&this.attach(t)}var e=t.prototype;return e.attach=function(t){this._element=t,this._keyboard&&this._keyboard.attach(t),this._mouse&&this._mouse.attach(t)},e.detach=function(){this._keyboard&&this._keyboard.detach(),this._mouse&&this._mouse.detach(),this._element=null},e.disableContextMenu=function(){this._mouse||this._enableMouse(),this._mouse.disableContextMenu()},e.enableContextMenu=function(){this._mouse||this._enableMouse(),this._mouse.enableContextMenu()},e.update=function(t){for(var e in this._keyboard&&this._keyboard.update(),this._mouse&&this._mouse.update(),this._gamepads&&this._gamepads.update(),this._axesValues={},this._axes)this._axesValues[e]=[]},e.appendAction=function(t,e){this._actions[t]=this._actions[t]||[],this._actions[t].push(e)},e.registerKeys=function(t,e){if(this._keyboard||this._enableKeyboard(),this._actions[t])throw new Error("Action: "+t+" already registered");if(void 0===e)throw new Error("Invalid button");e.length||(e=[e]),this.appendAction(t,{type:Or,keys:e})},e.registerMouse=function(t,e){if(this._mouse||this._enableMouse(),void 0===e)throw new Error("Invalid button");this.appendAction(t,{type:Dr,button:e})},e.registerPadButton=function(t,e,i){if(void 0===i)throw new Error("Invalid button");this.appendAction(t,{type:kr,button:i,pad:e})},e.registerAxis=function(t){var e=t.name;this._axes[e]||(this._axes[e]=[]);var i=this._axes[e].push(e);(t=t||{}).pad=t.pad||0;var n=function(n,s,r,a){switch(s){case"mousex":n._mouse.on(Br,(function(t){n._axesValues[e][i]=t.dx/10}));break;case"mousey":n._mouse.on(Br,(function(t){n._axesValues[e][i]=t.dy/10}));break;case"key":n._axes[e].push((function(){return n._keyboard.isPressed(a)?r:0}));break;case"padrx":n._axes[e].push((function(){return n._gamepads.getAxis(t.pad,2)}));break;case"padry":n._axes[e].push((function(){return n._gamepads.getAxis(t.pad,3)}));break;case"padlx":n._axes[e].push((function(){return n._gamepads.getAxis(t.pad,0)}));break;case"padly":n._axes[e].push((function(){return n._gamepads.getAxis(t.pad,1)}));break;default:throw new Error("Unknown axis")}};n(this,t.positive,1,t.positiveKey),(t.negativeKey||t.negative!==t.positive)&&n(this,t.negative,-1,t.negativeKey)},e.isPressed=function(t){if(!this._actions[t])return!1;for(var e=this._actions[t].length,i=0;i<e;++i){var n=this._actions[t][i];switch(n.type){case Or:if(this._keyboard)for(var s=n.keys.length,r=0;r<s;r++)if(this._keyboard.isPressed(n.keys[r]))return!0;break;case Dr:if(this._mouse&&this._mouse.isPressed(n.button))return!0;break;case kr:if(this._gamepads&&this._gamepads.isPressed(n.pad,n.button))return!0}}return!1},e.wasPressed=function(t){if(!this._actions[t])return!1;for(var e=this._actions[t].length,i=0;i<e;++i){var n=this._actions[t][i];switch(n.type){case Or:if(this._keyboard)for(var s=n.keys.length,r=0;r<s;r++)if(this._keyboard.wasPressed(n.keys[r]))return!0;break;case Dr:if(this._mouse&&this._mouse.wasPressed(n.button))return!0;break;case kr:if(this._gamepads&&this._gamepads.wasPressed(n.pad,n.button))return!0}}return!1},e.getAxis=function(t){var e=0;if(this._axes[t])for(var i=this._axes[t].length,n=0;n<i;n++)if("function"===f(this._axes[t][n])){var s=this._axes[t][n]();Math.abs(s)>Math.abs(e)&&(e=s)}else this._axesValues[t]&&Math.abs(this._axesValues[t][n])>Math.abs(e)&&(e=this._axesValues[t][n]);return e},e._enableMouse=function(){if(this._mouse=new Zr,!this._element)throw new Error("Controller must be attached to an Element");this._mouse.attach(this._element)},e._enableKeyboard=function(){if(this._keyboard=new qr,!this._element)throw new Error("Controller must be attached to an Element");this._keyboard.attach(this._element)},t}(),$r=Object.freeze([]),Jr=function(){return $r};"undefined"!=typeof navigator&&(Jr=(navigator.getGamepads||navigator.webkitGetGamepads||Jr).bind(navigator));var ta={buttons:{PAD_FACE_1:0,PAD_FACE_2:1,PAD_FACE_3:2,PAD_FACE_4:3,PAD_L_SHOULDER_1:4,PAD_R_SHOULDER_1:5,PAD_L_SHOULDER_2:6,PAD_R_SHOULDER_2:7,PAD_SELECT:8,PAD_START:9,PAD_L_STICK_BUTTON:10,PAD_R_STICK_BUTTON:11,PAD_UP:12,PAD_DOWN:13,PAD_LEFT:14,PAD_RIGHT:15,PAD_VENDOR:16,XRPAD_TRIGGER:0,XRPAD_SQUEEZE:1,XRPAD_TOUCHPAD_BUTTON:2,XRPAD_STICK_BUTTON:3,XRPAD_A:4,XRPAD_B:5},axes:{PAD_L_STICK_X:0,PAD_L_STICK_Y:1,PAD_R_STICK_X:2,PAD_R_STICK_Y:3,XRPAD_TOUCHPAD_X:0,XRPAD_TOUCHPAD_Y:1,XRPAD_STICK_X:2,XRPAD_STICK_Y:3}},ea={DEFAULT:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_3","PAD_FACE_4","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_UP","PAD_DOWN","PAD_LEFT","PAD_RIGHT","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"]},DEFAULT_DUAL:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_3","PAD_FACE_4","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"],synthesizedButtons:{PAD_UP:{axis:0,min:0,max:1},PAD_DOWN:{axis:0,min:-1,max:0},PAD_LEFT:{axis:0,min:-1,max:0},PAD_RIGHT:{axis:0,min:0,max:1}}},PS3:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_4","PAD_FACE_3","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_UP","PAD_DOWN","PAD_LEFT","PAD_RIGHT","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"],mapping:"standard"},DEFAULT_XR:{buttons:["XRPAD_TRIGGER","XRPAD_SQUEEZE","XRPAD_TOUCHPAD_BUTTON","XRPAD_STICK_BUTTON","XRPAD_A","XRPAD_B"],axes:["XRPAD_TOUCHPAD_X","XRPAD_TOUCHPAD_Y","XRPAD_STICK_X","XRPAD_STICK_Y"],mapping:"xr-standard"}},ia={"Product: 0268":"PS3"},na={};function sa(t){var e=na[t.id];if(e)return e;for(var i in ia)if(-1!==t.id.indexOf(i)){var n=ia[i];if(!t.mapping){var s=ea["RAW_"+n];if(s)return s}return ea[n]}if("xr-standard"===t.mapping)return ea.DEFAULT_XR;var r=ea.DEFAULT,a=t.buttons.length<r.buttons.length?ea.DEFAULT_DUAL:r;return a.mapping=t.mapping,a}var ra=.25;function aa(t){return new Promise((function(e){setTimeout(e,t)}))}var oa=function(){function t(t,e){var i,n;(this.value=0,this.pressed=!1,this.touched=!1,this.wasPressed=!1,this.wasReleased=!1,this.wasTouched=!1,"number"==typeof t)?(this.value=t,this.pressed=1===t,this.touched=t>0):(this.value=t.value,this.pressed=t.pressed,this.touched=null!=(i=t.touched)?i:t.value>0);e&&("number"==typeof e?(this.wasPressed=1!==e&&this.pressed,this.wasReleased=1===e&&!this.pressed,this.wasTouched=0===e&&this.touched):(this.wasPressed=!e.pressed&&this.pressed,this.wasReleased=e.pressed&&!this.pressed,this.wasTouched=!(null!=(n=e.touched)?n:e.value>0)&&this.touched))}return t.prototype.update=function(t){var e,i=t.value,n=t.pressed,s=null!=(e=t.touched)?e:i>0;this.wasPressed=!this.pressed&&n,this.wasReleased=this.pressed&&!n,this.wasTouched=!this.touched&&s,this.value=i,this.pressed=n,this.touched=s},t}(),ha=Object.freeze(new oa(0)),la=function(){function t(t,e){this._compiledMapping={buttons:[],axes:[]},this.id=t.id,this.index=t.index,this._buttons=t.buttons.map((function(t){return new oa(t)})),this._axes=[].concat(t.axes),this._previousAxes=[].concat(t.axes),this.mapping=e.mapping,this.map=e,this.hand=t.hand||"none",this.pad=t,this._compileMapping()}var e,i=t.prototype;return i._compileMapping=function(){var t=this,e=this._compiledMapping,i=e.axes,n=e.buttons,s=ta.axes,r=ta.buttons;i.length=0,n.length=0,this.map.axes&&this.map.axes.forEach((function(e,n){i[s[e]]=function(){return t.pad.axes[n]||0}}));for(var a=0,o=i.length;a<o;a++)i[a]||(i[a]=function(){return 0});var h=this.map.buttons;h&&h.forEach((function(e,i){n[r[e]]=function(){return t._buttons[i]||ha}}));var l=this.map.synthesizedButtons;l&&Object.entries(l).forEach((function(e){var i=e[1],s=i.axis,a=i.max,o=i.min;n[r[e[0]]]=function(){var e,i;return new oa(Math.abs(_t.clamp(null!=(e=t._axes[s])?e:0,o,a)),Math.abs(_t.clamp(null!=(i=t._previousAxes[s])?i:0,o,a)))}}));for(var c=0,u=n.length;c<u;c++)n[c]||(n[c]=function(){return ha})},i.update=function(t){this.pad=t;var e=this._previousAxes,i=this._axes;e.length=0,e.push.apply(e,i),i.length=0,i.push.apply(i,t.axes);for(var n=this._buttons,s=0,r=n.length;s<r;s++)n[s].update(t.buttons[s]);return this},i.updateMap=function(t){t.mapping="custom",na[this.id]=t,this.map=t,this.mapping="custom",this._compileMapping()},i.resetMap=function(){if(na[this.id]){delete na[this.id];var t=sa(this.pad);this.map=t,this.mapping=t.mapping,this._compileMapping()}},i.pulse=(e=v(m().mark((function t(e,i,n){var s,r,a,o,h,l,c,u;return m().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!(s=this.pad.vibrationActuator?[this.pad.vibrationActuator]:this.pad.hapticActuators||$r).length){t.next=9;break}return h=null!=(r=null==n?void 0:n.startDelay)?r:0,l=null!=(a=null==n?void 0:n.strongMagnitude)?a:e,c=null!=(o=null==n?void 0:n.weakMagnitude)?o:e,t.next=7,Promise.all(s.map(function(){var t=v(m().mark((function t(n){return m().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n){t.next=2;break}return t.abrupt("return",!0);case 2:if(!n.playEffect){t.next=6;break}return t.abrupt("return",n.playEffect(n.type,{duration:i,startDelay:h,strongMagnitude:l,weakMagnitude:c}));case 6:if(!n.pulse){t.next=10;break}return t.next=9,aa(h);case 9:return t.abrupt("return",n.pulse(e,i));case 10:return t.abrupt("return",!1);case 11:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}()));case 7:return u=t.sent,t.abrupt("return",u.some((function(t){return!0===t||"complete"===t})));case 9:return t.abrupt("return",!1);case 10:case"end":return t.stop()}}),t,this)}))),function(t,i,n){return e.apply(this,arguments)}),i.getButton=function(t){var e=this._compiledMapping.buttons[t];return e?e():ha},i.isPressed=function(t){return this.getButton(t).pressed},i.wasPressed=function(t){return this.getButton(t).wasPressed},i.wasReleased=function(t){return this.getButton(t).wasReleased},i.isTouched=function(t){return this.getButton(t).touched},i.wasTouched=function(t){return this.getButton(t).wasTouched},i.getValue=function(t){return this.getButton(t).value},i.getAxis=function(t){var e=this.axes[t];return e&&Math.abs(e)>ra?e:0},y(t,[{key:"connected",get:function(){return this.pad.connected}},{key:"axes",get:function(){return this._compiledMapping.axes.map((function(t){return t()}))}},{key:"buttons",get:function(){return this._compiledMapping.buttons.map((function(t){return t()}))}}]),t}(),ca=function(t){function e(){var e;return(e=t.call(this)||this).gamepadsSupported=G.gamepads,e.current=[],e._previous=[],e._ongamepadconnectedHandler=e._ongamepadconnected.bind(w(e)),e._ongamepaddisconnectedHandler=e._ongamepaddisconnected.bind(w(e)),window.addEventListener("gamepadconnected",e._ongamepadconnectedHandler,!1),window.addEventListener("gamepaddisconnected",e._ongamepaddisconnectedHandler,!1),e.poll(),e}S(e,t);var i=e.prototype;return i._ongamepadconnected=function(t){for(var e=new la(t.gamepad,this.getMap(t.gamepad)),i=this.current,n=i.findIndex((function(t){return t.index===e.index}));-1!==n;)i.splice(n,1),n=i.findIndex((function(t){return t.index===e.index}));i.push(e),this.fire(zr,e)},i._ongamepaddisconnected=function(t){var e=this.current,i=e.findIndex((function(e){return e.index===t.gamepad.index}));-1!==i&&(this.fire(Vr,e[i]),e.splice(i,1))},i.update=function(){this.poll()},i.poll=function(t){void 0===t&&(t=[]),t.length>0&&(t.length=0);for(var e=Jr(),i=0,n=e.length;i<n;i++)if(e[i]){var s=this.findByIndex(e[i].index);if(s)t.push(s.update(e[i]));else{var r=new la(e[i],this.getMap(e[i]));this.current.push(r),t.push(r)}}return t},i.destroy=function(){window.removeEventListener("gamepadconnected",this._ongamepadconnectedHandler,!1),window.removeEventListener("gamepaddisconnected",this._ongamepaddisconnectedHandler,!1)},i.getMap=function(t){return sa(t)},i.isPressed=function(t,e){var i;return(null==(i=this.current[t])?void 0:i.isPressed(e))||!1},i.wasPressed=function(t,e){var i;return(null==(i=this.current[t])?void 0:i.wasPressed(e))||!1},i.wasReleased=function(t,e){var i;return(null==(i=this.current[t])?void 0:i.wasReleased(e))||!1},i.getAxis=function(t,e){var i;return(null==(i=this.current[t])?void 0:i.getAxis(e))||0},i.pulse=function(t,e,i,n){var s=this.current[t];return s?s.pulse(e,i,n):Promise.resolve(!1)},i.pulseAll=function(t,e,i){return Promise.all(this.current.map((function(n){return n.pulse(t,e,i)})))},i.findById=function(t){return this.current.find((function(e){return e&&e.id===t}))||null},i.findByIndex=function(t){return this.current.find((function(e){return e&&e.index===t}))||null},y(e,[{key:"deadZone",get:function(){return ra},set:function(t){ra=t}},{key:"previous",get:function(){for(var t=this.current,e=0,i=t.length;e<i;e++){var n=t[e]._buttons;this._previous[e]||(this._previous[e]=[]);for(var s=0,r=n.length;s<r;s++){var a=n[e];this.previous[e][s]=!!a&&(!a.wasPressed&&a.pressed||a.wasReleased)}}return this._previous.length=this.current.length,this._previous}}]),e}(P);function ua(t){for(var e=0,i=0,n=t.target;!(n instanceof HTMLElement);)n=n.parentNode;var s=n;do{e+=s.offsetLeft-s.scrollLeft,i+=s.offsetTop-s.scrollTop,s=s.offsetParent}while(s);return{x:t.pageX-e,y:t.pageY-i}}var da=function(t){var e=ua(t);this.id=t.identifier,this.x=e.x,this.y=e.y,this.target=t.target,this.touch=t},fa=function(){function t(t,e){if(this.element=e.target,this.event=e,this.touches=[],this.changedTouches=[],e){for(var i=0,n=e.touches.length;i<n;i++)this.touches.push(new da(e.touches[i]));for(var s=0,r=e.changedTouches.length;s<r;s++)this.changedTouches.push(new da(e.changedTouches[s]))}}return t.prototype.getTouchById=function(t,e){for(var i=0,n=e.length;i<n;i++)if(e[i].id===t)return e[i];return null},t}(),pa=function(t){function e(e){var i;return(i=t.call(this)||this)._element=null,i._startHandler=i._handleTouchStart.bind(w(i)),i._endHandler=i._handleTouchEnd.bind(w(i)),i._moveHandler=i._handleTouchMove.bind(w(i)),i._cancelHandler=i._handleTouchCancel.bind(w(i)),i.attach(e),i}S(e,t);var i=e.prototype;return i.attach=function(t){this._element&&this.detach(),this._element=t,this._element.addEventListener("touchstart",this._startHandler,!1),this._element.addEventListener("touchend",this._endHandler,!1),this._element.addEventListener("touchmove",this._moveHandler,!1),this._element.addEventListener("touchcancel",this._cancelHandler,!1)},i.detach=function(){this._element&&(this._element.removeEventListener("touchstart",this._startHandler,!1),this._element.removeEventListener("touchend",this._endHandler,!1),this._element.removeEventListener("touchmove",this._moveHandler,!1),this._element.removeEventListener("touchcancel",this._cancelHandler,!1)),this._element=null},i._handleTouchStart=function(t){this.fire("touchstart",new fa(this,t))},i._handleTouchEnd=function(t){this.fire("touchend",new fa(this,t))},i._handleTouchMove=function(t){t.preventDefault(),this.fire("touchmove",new fa(this,t))},i._handleTouchCancel=function(t){this.fire("touchcancel",new fa(this,t))},e}(P),ma=function(){function t(){}var e=t.prototype;return e.get=function(t,e,i){return"function"==typeof e&&(i=e,e={}),this.request("GET",t,e,i)},e.post=function(t,e,i,n){return"function"==typeof i&&(n=i,i={}),i.postdata=e,this.request("POST",t,i,n)},e.put=function(t,e,i,n){return"function"==typeof i&&(n=i,i={}),i.postdata=e,this.request("PUT",t,i,n)},e.del=function(t,e,i){return"function"==typeof e&&(i=e,e={}),this.request("DELETE",t,e,i)},e.request=function(e,i,n,s){var r,a,o,h=this,l=!1;if("function"==typeof n&&(s=n,n={}),n.retry&&(n=Object.assign({retries:0,maxRetries:5},n)),n.callback=s,null==n.async&&(n.async=!0),null==n.headers&&(n.headers={}),null!=n.postdata)if(n.postdata instanceof Document)o=n.postdata;else if(n.postdata instanceof FormData)o=n.postdata;else if(n.postdata instanceof Object){var c=n.headers["Content-Type"];switch(void 0===c&&(n.headers["Content-Type"]=t.ContentType.FORM_URLENCODED,c=n.headers["Content-Type"]),c){case t.ContentType.FORM_URLENCODED:o="";var u=!0;for(var d in n.postdata){if(n.postdata.hasOwnProperty(d))u?u=!1:o+="&",o+=encodeURIComponent(d)+"="+encodeURIComponent(n.postdata[d])}break;default:case t.ContentType.JSON:null==c&&(n.headers["Content-Type"]=t.ContentType.JSON),o=JSON.stringify(n.postdata)}}else o=n.postdata;if(!1===n.cache){var f=dt();(r=new mt(i)).query?r.query=r.query+"&ts="+f:r.query="ts="+f,i=r.toString()}n.query&&(a=p((r=new mt(i)).getQuery(),n.query),r.setQuery(a),i=r.toString());var m=new XMLHttpRequest;for(var _ in m.open(e,i,n.async),m.withCredentials=void 0!==n.withCredentials&&n.withCredentials,m.responseType=n.responseType||this._guessResponseType(i),n.headers)n.headers.hasOwnProperty(_)&&m.setRequestHeader(_,n.headers[_]);m.onreadystatechange=function(){h._onReadyStateChange(e,i,n,m)},m.onerror=function(){h._onError(e,i,n,m),l=!0};try{m.send(o)}catch(t){l||n.error(m.status,m,t)}return m},e._guessResponseType=function(e){var i=new mt(e),n=L.getExtension(i.path).toLowerCase();return t.binaryExtensions.indexOf(n)>=0?t.ResponseType.ARRAY_BUFFER:".json"===n?t.ResponseType.JSON:".xml"===n?t.ResponseType.DOCUMENT:t.ResponseType.TEXT},e._isBinaryContentType=function(e){return[t.ContentType.BASIS,t.ContentType.BIN,t.ContentType.DDS,t.ContentType.GLB,t.ContentType.MP3,t.ContentType.MP4,t.ContentType.OGG,t.ContentType.OPUS,t.ContentType.WAV].indexOf(e)>=0},e._isBinaryResponseType=function(e){return e===t.ResponseType.ARRAY_BUFFER||e===t.ResponseType.BLOB||e===t.ResponseType.JSON},e._onReadyStateChange=function(t,e,i,n){if(4===n.readyState)switch(n.status){case 0:n.responseURL&&n.responseURL.startsWith("file:///")?this._onSuccess(t,e,i,n):this._onError(t,e,i,n);break;case 200:case 201:case 206:case 304:this._onSuccess(t,e,i,n);break;default:this._onError(t,e,i,n)}},e._onSuccess=function(e,i,n,s){var r,a,o=s.getResponseHeader("Content-Type");o&&(a=o.split(";")[0].trim());try{r=this._isBinaryContentType(a)||this._isBinaryResponseType(s.responseType)?s.response:a===t.ContentType.JSON||i.split("?")[0].endsWith(".json")?JSON.parse(s.responseText):s.responseType===t.ResponseType.DOCUMENT||a===t.ContentType.XML?s.responseXML:s.responseText,n.callback(null,r)}catch(t){n.callback(t)}},e._onError=function(e,i,n,s){var r=this;if(!n.retrying)if(n.retry&&n.retries<n.maxRetries){n.retries++,n.retrying=!0;var a=_t.clamp(Math.pow(2,n.retries)*t.retryDelay,0,n.maxRetryDelay||5e3);console.log(e+": "+i+" - Error "+s.status+". Retrying in "+a+" ms"),setTimeout((function(){n.retrying=!1,r.request(e,i,n,n.callback)}),a)}else n.callback(0===s.status?"Network error":s.status,null)},t}();ma.ContentType={AAC:"audio/aac",BASIS:"image/basis",BIN:"application/octet-stream",DDS:"image/dds",FORM_URLENCODED:"application/x-www-form-urlencoded",GIF:"image/gif",GLB:"model/gltf-binary",JPEG:"image/jpeg",JSON:"application/json",MP3:"audio/mpeg",MP4:"audio/mp4",OGG:"audio/ogg",OPUS:'audio/ogg; codecs="opus"',PNG:"image/png",TEXT:"text/plain",WAV:"audio/x-wav",XML:"application/xml"},ma.ResponseType={TEXT:"text",ARRAY_BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json"},ma.binaryExtensions=[".model",".wav",".ogg",".mp3",".mp4",".m4a",".aac",".dds",".basis",".glb",".opus"],ma.retryDelay=100;var _a=new ma;function va(){return!("undefined"==typeof AudioContext&&"undefined"==typeof webkitAudioContext)}var ga=function(){function t(t,e,i){var n,s,r;if(void 0===i&&(i={}),this.volume=null!=(n=i.volume)?n:1,this.loop=null!=(s=i.loop)&&s,this.pitch=null!=(r=i.pitch)?r:1,this.sound=e,this.paused=!1,this.suspended=!1,this.manager=t,this.source=null,va()){this.startTime=0,this.startOffset=0;var a=t.context;this.gain=a.createGain()}else e.audio&&(this.source=e.audio.cloneNode(!1),this.source.pause())}var e=t.prototype;return e.getVolume=function(){return this.volume},e.getLoop=function(){return this.loop},e.setLoop=function(t){this.loop=t,this.source&&(this.source.loop=t)},e.getPitch=function(){return this.pitch},e.onManagerVolumeChange=function(){this.setVolume(this.getVolume())},e.onManagerSuspend=function(){this.isPlaying()&&!this.suspended&&(this.suspended=!0,this.pause())},e.onManagerResume=function(){this.suspended&&(this.suspended=!1,this.unpause())},e.play=function(){if(this.source)throw new Error("Call stop() before calling play()");this._createSource(),this.source&&(this.startTime=this.manager.context.currentTime,this.source.start(0,this.startOffset%this.source.buffer.duration),this.setVolume(this.volume),this.setLoop(this.loop),this.setPitch(this.pitch),this.manager.on("volumechange",this.onManagerVolumeChange,this),this.manager.on("suspend",this.onManagerSuspend,this),this.manager.on("resume",this.onManagerResume,this),this.manager.suspended&&this.onManagerSuspend())},e.pause=function(){this.source&&(this.paused=!0,this.startOffset+=this.manager.context.currentTime-this.startTime,this.source.stop(0),this.source=null)},e.unpause=function(){!this.source&&this.paused?(this._createSource(),this.source&&(this.startTime=this.manager.context.currentTime,this.source.start(0,this.startOffset%this.source.buffer.duration),this.setVolume(this.volume),this.setLoop(this.loop),this.setPitch(this.pitch),this.paused=!1)):console.warn("Call pause() before unpausing.")},e.stop=function(){this.source&&(this.source.stop(0),this.source=null),this.manager.off("volumechange",this.onManagerVolumeChange,this),this.manager.off("suspend",this.onManagerSuspend,this),this.manager.off("resume",this.onManagerResume,this)},e.setVolume=function(t){t=_t.clamp(t,0,1),this.volume=t,this.gain&&(this.gain.gain.value=t*this.manager.volume)},e.setPitch=function(t){this.pitch=t,this.source&&(this.source.playbackRate.value=t)},e.isPlaying=function(){return!this.paused&&this.source.playbackState===this.source.PLAYING_STATE},e.getDuration=function(){return this.source?this.source.buffer.duration:0},e._createSource=function(){var t=this.manager.context;this.sound.buffer&&(this.source=t.createBufferSource(),this.source.buffer=this.sound.buffer,this.source.connect(this.gain),this.gain.connect(t.destination),this.loop||(this.source.onended=this.pause.bind(this)))},t}();va()||Object.assign(ga.prototype,{play:function(){this.source&&(this.paused=!1,this.setVolume(this.volume),this.setLoop(this.loop),this.setPitch(this.pitch),this.source.play()),this.manager.on("volumechange",this.onManagerVolumeChange,this),this.manager.on("suspend",this.onManagerSuspend,this),this.manager.on("resume",this.onManagerResume,this),this.manager.suspended&&this.onManagerSuspend()},pause:function(){this.source&&(this.paused=!0,this.source.pause())},unpause:function(){this.source&&(this.paused=!1,this.source.play())},stop:function(){this.source&&this.source.pause(),this.manager.off("volumechange",this.onManagerVolumeChange,this),this.manager.off("suspend",this.onManagerSuspend,this),this.manager.off("resume",this.onManagerResume,this)},setVolume:function(t){t=_t.clamp(t,0,1),this.volume=t,this.source&&(this.source.volume=t*this.manager.volume)},setPitch:function(t){this.pitch=t,this.source&&(this.source.playbackRate=t)},getDuration:function(){return this.source&&!isNaN(this.source.duration)?this.source.duration:0},isPlaying:function(){return!this.source.paused}});var ya=function(t){function e(e,i,n){var s;return(s=t.call(this,e,i,n)||this).position=new wt,s.velocity=new wt,va()?s.panner=e.context.createPanner():(s.maxDistance=1e4,s.minDistance=1,s.rollOffFactor=1,s.distanceModel=ie),s}S(e,t);var i=e.prototype;return i.getPosition=function(){return this.position},i.setPosition=function(t){this.position.copy(t);var e=this.panner;"positionX"in e?(e.positionX.value=t.x,e.positionY.value=t.y,e.positionZ.value=t.z):e.setPosition&&e.setPosition(t.x,t.y,t.z)},i.getVelocity=function(){return this.velocity},i.setVelocity=function(t){this.velocity.copy(t)},i.getMaxDistance=function(){return this.panner.maxDistance},i.setMaxDistance=function(t){this.panner.maxDistance=t},i.getMinDistance=function(){return this.panner.refDistance},i.setMinDistance=function(t){this.panner.refDistance=t},i.getRollOffFactor=function(){return this.panner.rolloffFactor},i.setRollOffFactor=function(t){this.panner.rolloffFactor=t},i.getDistanceModel=function(){return this.panner.distanceModel},i.setDistanceModel=function(t){this.panner.distanceModel=t},i._createSource=function(){var t=this.manager.context;this.source=t.createBufferSource(),this.source.buffer=this.sound.buffer,this.source.connect(this.panner),this.panner.connect(this.gain),this.gain.connect(t.destination),this.loop||(this.source.onended=this.pause.bind(this))},e}(ga);if(!va()){var xa=new wt;Object.assign(ya.prototype,{setPosition:function(t){if(this.position.copy(t),this.source){var e=function(t,e,i,n,s,r){var a=(xa=xa.sub2(t,e)).length();if(a<i)return 1;if(a>n)return 0;var o=0;return r===ee?o=1-s*(a-i)/(n-i):r===ie?o=i/(i+s*(a-i)):r===ne&&(o=Math.pow(a/i,-s)),_t.clamp(o,0,1)}(this.manager.listener.getPosition(),this.position,this.minDistance,this.maxDistance,this.rollOffFactor,this.distanceModel),i=this.getVolume();this.source.volume=i*e}},getMaxDistance:function(){return this.maxDistance},setMaxDistance:function(t){this.maxDistance=t},getMinDistance:function(){return this.minDistance},setMinDistance:function(t){this.minDistance=t},getRollOffFactor:function(){return this.rollOffFactor},setRollOffFactor:function(t){this.rollOffFactor=t},getDistanceModel:function(){return this.distanceModel},setDistanceModel:function(t){this.distanceModel=t}})}var Sa=function(){function t(t){this._manager=t,this.position=new wt,this.velocity=new wt,this.orientation=new Ft}var e=t.prototype;return e.getPosition=function(){return this.position},e.setPosition=function(t){this.position.copy(t);var e=this.listener;e&&("positionX"in e?(e.positionX.value=t.x,e.positionY.value=t.y,e.positionZ.value=t.z):e.setPosition&&e.setPosition(t.x,t.y,t.z))},e.getVelocity=function(){return this.velocity},e.setVelocity=function(t){},e.setOrientation=function(t){this.orientation.copy(t);var e=this.listener;if(e){var i=t.data;"forwardX"in e?(e.forwardX.value=-i[8],e.forwardY.value=-i[9],e.forwardZ.value=-i[10],e.upX.value=i[4],e.upY.value=i[5],e.upZ.value=i[6]):e.setOrientation&&e.setOrientation(-i[8],-i[9],-i[10],i[4],i[5],i[6])}},e.getOrientation=function(){return this.orientation},y(t,[{key:"listener",get:function(){var t=this._manager.context;return t?t.listener:null}}]),t}(),ba="running",wa=["click","touchstart","mousedown"],Ta=function(t){function e(){var e;return(e=t.call(this)||this)._context=null,e.AudioContext="undefined"!=typeof AudioContext&&AudioContext||"undefined"!=typeof webkitAudioContext&&webkitAudioContext,e.AudioContext,e._unlockHandlerFunc=e._unlockHandler.bind(w(e)),e._userSuspended=!1,e.listener=new Sa(w(e)),e._volume=1,e}S(e,t);var i=e.prototype;return i.suspend=function(){this._userSuspended||(this._userSuspended=!0,this._context&&this._context.state===ba&&this._suspend())},i.resume=function(){this._userSuspended&&(this._userSuspended=!1,this._context&&this._context.state!==ba&&this._resume())},i.destroy=function(){var t;(this.fire("destroy"),this._context)&&(this._removeUnlockListeners(),null==(t=this._context)||t.close(),this._context=null)},i.playSound=function(t,e){void 0===e&&(e={});var i=null;return ga&&(i=new ga(this,t,e)).play(),i},i.playSound3d=function(t,e,i){void 0===i&&(i={});var n=null;return ya&&((n=new ya(this,t,i)).setPosition(e),i.volume&&n.setVolume(i.volume),i.loop&&n.setLoop(i.loop),i.maxDistance&&n.setMaxDistance(i.maxDistance),i.minDistance&&n.setMinDistance(i.minDistance),i.rollOffFactor&&n.setRollOffFactor(i.rollOffFactor),i.distanceModel&&n.setDistanceModel(i.distanceModel),n.play()),n},i._resume=function(){var t=this;this._context.resume().then((function(){var e=t._context.createBufferSource();e.buffer=t._context.createBuffer(1,1,t._context.sampleRate),e.connect(t._context.destination),e.start(0),e.onended=function(i){e.disconnect(0),t.fire("resume")}}),(function(t){})).catch((function(t){}))},i._suspend=function(){var t=this;this._context.suspend().then((function(){t.fire("suspend")}),(function(t){})).catch((function(t){}))},i._unlockHandler=function(){this._removeUnlockListeners(),this._userSuspended||this._context.state===ba||this._resume()},i._registerUnlockListeners=function(){var t=this;wa.forEach((function(e){window.addEventListener(e,t._unlockHandlerFunc,!1)}))},i._removeUnlockListeners=function(){var t=this;wa.forEach((function(e){window.removeEventListener(e,t._unlockHandlerFunc,!1)}))},y(e,[{key:"volume",get:function(){return this._volume},set:function(t){t=_t.clamp(t,0,1),this._volume=t,this.fire("volumechange",t)}},{key:"suspended",get:function(){return this._userSuspended}},{key:"context",get:function(){return!this._context&&this.AudioContext&&(this._context=new this.AudioContext,this._context.state!==ba&&this._registerUnlockListeners()),this._context}}]),e}(P),Aa=function(){function t(t){this.audio=void 0,this.buffer=void 0,t instanceof Audio?this.audio=t:this.buffer=t}return y(t,[{key:"duration",get:function(){var t=0;return this.buffer?t=this.buffer.duration:this.audio&&(t=this.audio.duration),t||0}}]),t}();function Ca(t,e){return t%e||0}var Ea=function(t){function e(e,i,n){var s;return(s=t.call(this)||this).source=null,s._manager=e,s._volume=void 0!==n.volume?_t.clamp(Number(n.volume)||0,0,1):1,s._pitch=void 0!==n.pitch?Math.max(.01,Number(n.pitch)||0):1,s._loop=!(void 0===n.loop||!n.loop),s._sound=i,s._state=2,s._suspended=!1,s._suspendEndEvent=0,s._suspendInstanceEvents=!1,s._playWhenLoaded=!0,s._startTime=Math.max(0,Number(n.startTime)||0),s._duration=Math.max(0,Number(n.duration)||0),s._startOffset=null,s._onPlayCallback=n.onPlay,s._onPauseCallback=n.onPause,s._onResumeCallback=n.onResume,s._onStopCallback=n.onStop,s._onEndCallback=n.onEnd,va()?(s._startedAt=0,s._currentTime=0,s._currentOffset=0,s._inputNode=null,s._connectorNode=null,s._firstNode=null,s._lastNode=null,s._waitingContextSuspension=!1,s._initializeNodes(),s._endedHandler=s._onEnded.bind(w(s))):(s._isReady=!1,s._loadedMetadataHandler=s._onLoadedMetadata.bind(w(s)),s._timeUpdateHandler=s._onTimeUpdate.bind(w(s)),s._endedHandler=s._onEnded.bind(w(s)),s._createSource()),s}S(e,t);var i=e.prototype;return i._onPlay=function(){this.fire("play"),this._onPlayCallback&&this._onPlayCallback(this)},i._onPause=function(){this.fire("pause"),this._onPauseCallback&&this._onPauseCallback(this)},i._onResume=function(){this.fire("resume"),this._onResumeCallback&&this._onResumeCallback(this)},i._onStop=function(){this.fire("stop"),this._onStopCallback&&this._onStopCallback(this)},i._onEnded=function(){this._suspendEndEvent>0?this._suspendEndEvent--:(this.fire("end"),this._onEndCallback&&this._onEndCallback(this),this.stop())},i._onManagerVolumeChange=function(){this.volume=this._volume},i._onManagerSuspend=function(){0!==this._state||this._suspended||(this._suspended=!0,this.pause())},i._onManagerResume=function(){this._suspended&&(this._suspended=!1,this.resume())},i._initializeNodes=function(){this.gain=this._manager.context.createGain(),this._inputNode=this.gain,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination)},i.play=function(){return 2!==this._state&&this.stop(),this._state=0,this._playWhenLoaded=!1,!this._waitingContextSuspension&&(this._manager.suspended?(this._manager.once("resume",this._playAudioImmediate,this),this._waitingContextSuspension=!0,!1):(this._playAudioImmediate(),!0))},i._playAudioImmediate=function(){if(this._waitingContextSuspension=!1,0===this._state){this.source||this._createSource();var t=Ca(this._startOffset,this.duration);t=Ca(this._startTime+t,this._sound.duration),this._startOffset=null,this._duration?this.source.start(0,t,this._duration):this.source.start(0,t),this._startedAt=this._manager.context.currentTime,this._currentTime=0,this._currentOffset=t,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._manager.on("volumechange",this._onManagerVolumeChange,this),this._manager.on("suspend",this._onManagerSuspend,this),this._manager.on("resume",this._onManagerResume,this),this._manager.on("destroy",this._onManagerDestroy,this),this._suspendInstanceEvents||this._onPlay()}},i.pause=function(){return this._playWhenLoaded=!1,0===this._state&&(this._state=1,this._waitingContextSuspension||(this._updateCurrentTime(),this._suspendEndEvent++,this.source.stop(0),this.source=null,this._startOffset=null,this._suspendInstanceEvents||this._onPause()),!0)},i.resume=function(){if(1!==this._state)return!1;var t=this.currentTime;return this._state=0,this._waitingContextSuspension||(this.source||this._createSource(),null!==this._startOffset&&(t=Ca(this._startOffset,this.duration),t=Ca(this._startTime+t,this._sound.duration),this._startOffset=null),this._duration?this.source.start(0,t,this._duration):this.source.start(0,t),this._startedAt=this._manager.context.currentTime,this._currentOffset=t,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._playWhenLoaded=!1,this._suspendInstanceEvents||this._onResume()),!0},i.stop=function(){if(this._playWhenLoaded=!1,2===this._state)return!1;var t=0===this._state;return this._state=2,this._waitingContextSuspension||(this._manager.off("volumechange",this._onManagerVolumeChange,this),this._manager.off("suspend",this._onManagerSuspend,this),this._manager.off("resume",this._onManagerResume,this),this._manager.off("destroy",this._onManagerDestroy,this),this._startedAt=0,this._currentTime=0,this._currentOffset=0,this._startOffset=null,this._suspendEndEvent++,t&&this.source&&this.source.stop(0),this.source=null,this._suspendInstanceEvents||this._onStop()),!0},i.setExternalNodes=function(t,e){if(t){e||(e=t);var i=this._manager.context.destination;this._firstNode!==t&&(this._firstNode?this._connectorNode.disconnect(this._firstNode):this._connectorNode.disconnect(i),this._firstNode=t,this._connectorNode.connect(t)),this._lastNode!==e&&(this._lastNode&&this._lastNode.disconnect(i),this._lastNode=e,this._lastNode.connect(i))}else console.error("The firstNode must be a valid Audio Node")},i.clearExternalNodes=function(){var t=this._manager.context.destination;this._firstNode&&(this._connectorNode.disconnect(this._firstNode),this._firstNode=null),this._lastNode&&(this._lastNode.disconnect(t),this._lastNode=null),this._connectorNode.connect(t)},i.getExternalNodes=function(){return[this._firstNode,this._lastNode]},i._createSource=function(){if(!this._sound)return null;var t=this._manager.context;return this._sound.buffer&&(this.source=t.createBufferSource(),this.source.buffer=this._sound.buffer,this.source.connect(this._inputNode),this.source.onended=this._endedHandler,this.source.loopStart=Ca(this._startTime,this.source.buffer.duration),this._duration&&(this.source.loopEnd=Math.max(this.source.loopStart,Ca(this._startTime+this._duration,this.source.buffer.duration)))),this.source},i._updateCurrentTime=function(){this._currentTime=Ca((this._manager.context.currentTime-this._startedAt)*this._pitch+this._currentOffset,this.duration)},i._onManagerDestroy=function(){this.source&&0===this._state&&(this.source.stop(0),this.source=null)},y(e,[{key:"currentTime",get:function(){return null!==this._startOffset?this._startOffset:1===this._state?this._currentTime:2!==this._state&&this.source?(this._updateCurrentTime(),this._currentTime):0},set:function(t){if(!(t<0))if(0===this._state){var e=this._suspendInstanceEvents;this._suspendInstanceEvents=!0,this.stop(),this._startOffset=t,this.play(),this._suspendInstanceEvents=e}else this._startOffset=t,this._currentTime=t}},{key:"duration",get:function(){return this._sound?this._duration?Ca(this._duration,this._sound.duration):this._sound.duration:0},set:function(t){this._duration=Math.max(0,Number(t)||0);var e=0===this._state;this.stop(),e&&this.play()}},{key:"isPaused",get:function(){return 1===this._state}},{key:"isPlaying",get:function(){return 0===this._state}},{key:"isStopped",get:function(){return 2===this._state}},{key:"isSuspended",get:function(){return this._suspended}},{key:"loop",get:function(){return this._loop},set:function(t){this._loop=!!t,this.source&&(this.source.loop=this._loop)}},{key:"pitch",get:function(){return this._pitch},set:function(t){this._currentOffset=this.currentTime,this._startedAt=this._manager.context.currentTime,this._pitch=Math.max(Number(t)||0,.01),this.source&&(this.source.playbackRate.value=this._pitch)}},{key:"sound",get:function(){return this._sound},set:function(t){this._sound=t,2!==this._state?this.stop():this._createSource()}},{key:"startTime",get:function(){return this._startTime},set:function(t){this._startTime=Math.max(0,Number(t)||0);var e=0===this._state;this.stop(),e&&this.play()}},{key:"volume",get:function(){return this._volume},set:function(t){t=_t.clamp(t,0,1),this._volume=t,this.gain&&(this.gain.gain.value=t*this._manager.volume)}}]),e}(P);va()||(Object.assign(Ea.prototype,{play:function(){return 2!==this._state&&this.stop(),!(!this.source&&!this._createSource())&&(this.volume=this._volume,this.pitch=this._pitch,this.loop=this._loop,this.source.play(),this._state=0,this._playWhenLoaded=!1,this._manager.on("volumechange",this._onManagerVolumeChange,this),this._manager.on("suspend",this._onManagerSuspend,this),this._manager.on("resume",this._onManagerResume,this),this._manager.on("destroy",this._onManagerDestroy,this),this._manager.suspended&&this._onManagerSuspend(),this._suspendInstanceEvents||this._onPlay(),!0)},pause:function(){return!(!this.source||0!==this._state)&&(this._suspendEndEvent++,this.source.pause(),this._playWhenLoaded=!1,this._state=1,this._startOffset=null,this._suspendInstanceEvents||this._onPause(),!0)},resume:function(){return!(!this.source||1!==this._state)&&(this._state=0,this._playWhenLoaded=!1,this.source.paused&&(this.source.play(),this._suspendInstanceEvents||this._onResume()),!0)},stop:function(){return!(!this.source||2===this._state)&&(this._manager.off("volumechange",this._onManagerVolumeChange,this),this._manager.off("suspend",this._onManagerSuspend,this),this._manager.off("resume",this._onManagerResume,this),this._manager.off("destroy",this._onManagerDestroy,this),this._suspendEndEvent++,this.source.pause(),this._playWhenLoaded=!1,this._state=2,this._startOffset=null,this._suspendInstanceEvents||this._onStop(),!0)},setExternalNodes:function(){},clearExternalNodes:function(){},getExternalNodes:function(){return[null,null]},_onLoadedMetadata:function(){this.source.removeEventListener("loadedmetadata",this._loadedMetadataHandler),this._isReady=!0;var t=Ca(this._startOffset,this.duration);t=Ca(this._startTime+t,this._sound.duration),this._startOffset=null,this.source.currentTime=t},_createSource:function(){return this._sound&&this._sound.audio&&(this._isReady=!1,this.source=this._sound.audio.cloneNode(!0),this.source.addEventListener("loadedmetadata",this._loadedMetadataHandler),this.source.addEventListener("timeupdate",this._timeUpdateHandler),this.source.onended=this._endedHandler),this.source},_onTimeUpdate:function(){this._duration&&this.source.currentTime>Ca(this._startTime+this._duration,this.source.duration)&&(this.loop?this.source.currentTime=Ca(this._startTime,this.source.duration):(this.source.removeEventListener("timeupdate",this._timeUpdateHandler),this.source.pause(),this._onEnded()))},_onManagerDestroy:function(){this.source&&this.source.pause()}}),Object.defineProperty(Ea.prototype,"volume",{get:function(){return this._volume},set:function(t){t=_t.clamp(t,0,1),this._volume=t,this.source&&(this.source.volume=t*this._manager.volume)}}),Object.defineProperty(Ea.prototype,"pitch",{get:function(){return this._pitch},set:function(t){this._pitch=Math.max(Number(t)||0,.01),this.source&&(this.source.playbackRate=this._pitch)}}),Object.defineProperty(Ea.prototype,"sound",{get:function(){return this._sound},set:function(t){this.stop(),this._sound=t}}),Object.defineProperty(Ea.prototype,"currentTime",{get:function(){return null!==this._startOffset?this._startOffset:2!==this._state&&this.source?this.source.currentTime-this._startTime:0},set:function(t){t<0||(this._startOffset=t,this.source&&this._isReady&&(this.source.currentTime=Ca(this._startTime+Ca(t,this.duration),this._sound.duration),this._startOffset=null))}}));var Ma=function(t){function e(e,i,n){var s;return void 0===n&&(n={}),(s=t.call(this,e,i,n)||this)._position=new wt,s._velocity=new wt,n.position&&(s.position=n.position),s.maxDistance=void 0!==n.maxDistance?Number(n.maxDistance):1e4,s.refDistance=void 0!==n.refDistance?Number(n.refDistance):1,s.rollOffFactor=void 0!==n.rollOffFactor?Number(n.rollOffFactor):1,s.distanceModel=void 0!==n.distanceModel?n.distanceModel:ee,s}return S(e,t),e.prototype._initializeNodes=function(){this.gain=this._manager.context.createGain(),this.panner=this._manager.context.createPanner(),this.panner.connect(this.gain),this._inputNode=this.panner,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination)},y(e,[{key:"position",get:function(){return this._position},set:function(t){this._position.copy(t);var e=this.panner;"positionX"in e?(e.positionX.value=t.x,e.positionY.value=t.y,e.positionZ.value=t.z):e.setPosition&&e.setPosition(t.x,t.y,t.z)}},{key:"velocity",get:function(){return this._velocity},set:function(t){this._velocity.copy(t)}},{key:"maxDistance",get:function(){return this.panner.maxDistance},set:function(t){this.panner.maxDistance=t}},{key:"refDistance",get:function(){return this.panner.refDistance},set:function(t){this.panner.refDistance=t}},{key:"rollOffFactor",get:function(){return this.panner.rolloffFactor},set:function(t){this.panner.rolloffFactor=t}},{key:"distanceModel",get:function(){return this.panner.distanceModel},set:function(t){this.panner.distanceModel=t}}]),e}(Ea);if(!va()){var Pa=new wt;Object.defineProperty(Ma.prototype,"position",{get:function(){return this._position},set:function(t){if(this._position.copy(t),this.source){var e=function(t,e,i,n,s,r){var a=(Pa=Pa.sub2(t,e)).length();if(a<i)return 1;if(a>n)return 0;var o=0;return r===ee?o=1-s*(a-i)/(n-i):r===ie?o=i/(i+s*(a-i)):r===ne&&(o=Math.pow(a/i,-s)),_t.clamp(o,0,1)}(this._manager.listener.getPosition(),this._position,this.refDistance,this.maxDistance,this.rollOffFactor,this.distanceModel),i=this.volume;this.source.volume=i*e*this._manager.volume}}}),Object.defineProperty(Ma.prototype,"maxDistance",{get:function(){return this._maxDistance},set:function(t){this._maxDistance=t}}),Object.defineProperty(Ma.prototype,"refDistance",{get:function(){return this._refDistance},set:function(t){this._refDistance=t}}),Object.defineProperty(Ma.prototype,"rollOffFactor",{get:function(){return this._rollOffFactor},set:function(t){this._rollOffFactor=t}}),Object.defineProperty(Ma.prototype,"distanceModel",{get:function(){return this._distanceModel},set:function(t){this._distanceModel=t}})}var Ra="none",Ia="linear",La={0:"PCF3",1:"VSM8",2:"VSM16",3:"VSM32",4:"PCF5",5:"PCF1",6:"PCSS"},Da="mul",Oa=32,ka=128,Fa=256,Ba=512,Ua=1024,Na=2048,za=4096,Va=8192,Ga=function(){function t(){this._refCount=0}var e=t.prototype;return e.incRefCount=function(){this._refCount++},e.decRefCount=function(){this._refCount--},y(t,[{key:"refCount",get:function(){return this._refCount}}]),t}(),Ha=function(){function t(){}return t.set=function(e){t._graphicsDevice=e},t.get=function(){return t._graphicsDevice},t}();Ha._graphicsDevice=null;var Wa=0,Xa=function(){function t(){this.initDefaults()}var e=t.prototype;return e.initDefaults=function(){this.recreate=!1,this.verticesUsage=0,this.indicesUsage=0,this.maxVertices=0,this.maxIndices=0,this.vertexCount=0,this.indexCount=0,this.vertexStreamsUpdated=!1,this.indexStreamUpdated=!1,this.vertexStreamDictionary={},this.indices=null},e._changeVertexCount=function(t,e){this.vertexCount||(this.vertexCount=t)},t}();Xa.DEFAULT_COMPONENTS_POSITION=3,Xa.DEFAULT_COMPONENTS_NORMAL=3,Xa.DEFAULT_COMPONENTS_UV=2,Xa.DEFAULT_COMPONENTS_COLORS=4;var ja=function(t,e,i,n){this.data=t,this.componentCount=e,this.dataType=i,this.dataTypeNormalize=n},qa=function(t){function e(e){var i;return(i=t.call(this)||this)._aabbVer=0,i.id=Wa++,i.device=e||Ha.get(),i.vertexBuffer=null,i.indexBuffer=[null],i.primitive=[{type:0,base:0,count:0}],i.skin=null,i._morph=null,i._geometryData=null,i._aabb=new Ht,i.boneAabb=null,i}S(e,t);var i=e.prototype;return i.destroy=function(){var t=this.morph;t&&(this.morph=null,t.refCount<1&&t.destroy()),this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=null);for(var e=0;e<this.indexBuffer.length;e++)this._destroyIndexBuffer(e);this.indexBuffer.length=0,this._geometryData=null},i._destroyIndexBuffer=function(t){this.indexBuffer[t]&&(this.indexBuffer[t].destroy(),this.indexBuffer[t]=null)},i._initBoneAabbs=function(t){var e,i,n,s,r;this.boneAabb=[],this.boneUsed=[];for(var a,o,h,l=[],c=[],u=this.boneUsed,d=this.skin.boneNames.length,f=0;f<d;f++)l[f]=new wt(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),c[f]=new wt(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(var p=new Lr(this.vertexBuffer),m=p.element[we],_=p.element[Ce],v=p.element[Ee],g=this.vertexBuffer.numVertices,y=0;y<g;y++){for(var x=0;x<4;x++){if(_.array[_.index+x]>0){var S=v.array[v.index+x];if(u[S]=!0,e=m.array[m.index],i=m.array[m.index+1],n=m.array[m.index+2],s=c[S],(r=l[S]).x>e&&(r.x=e),r.y>i&&(r.y=i),r.z>n&&(r.z=n),s.x<e&&(s.x=e),s.y<i&&(s.y=i),s.z<n&&(s.z=n),t){for(var b=a=e,w=o=i,T=h=n,A=0;A<t.length;A++){var C=t[A],E=C.deltaPositions[3*y],M=C.deltaPositions[3*y+1],P=C.deltaPositions[3*y+2];E<0?b+=E:a+=E,M<0?w+=M:o+=M,P<0?T+=P:h+=P}r.x>b&&(r.x=b),r.y>w&&(r.y=w),r.z>T&&(r.z=T),s.x<a&&(s.x=a),s.y<o&&(s.y=o),s.z<h&&(s.z=h)}}}p.next()}var R=this.vertexBuffer.getFormat().elements.find((function(t){return t.name===we}));if(R&&R.normalize)for(var I=function(){switch(R.dataType){case 0:return function(t){return Math.max(t/127,-1)};case mi:return function(t){return t/255};case 2:return function(t){return Math.max(t/32767,-1)};case 3:return function(t){return t/65535};default:return function(t){return t}}}(),L=0;L<d;L++)if(u[L]){var D=l[L],O=c[L];D.set(I(D.x),I(D.y),I(D.z)),O.set(I(O.x),I(O.y),I(O.z))}for(var k=0;k<d;k++){var F=new Ht;F.setMinMax(l[k],c[k]),this.boneAabb.push(F)}},i._initGeometryData=function(){this._geometryData||(this._geometryData=new Xa,this.vertexBuffer&&(this._geometryData.vertexCount=this.vertexBuffer.numVertices,this._geometryData.maxVertices=this.vertexBuffer.numVertices),this.indexBuffer.length>0&&this.indexBuffer[0]&&(this._geometryData.indexCount=this.indexBuffer[0].numIndices,this._geometryData.maxIndices=this.indexBuffer[0].numIndices))},i.clear=function(t,e,i,n){void 0===i&&(i=0),void 0===n&&(n=0),this._initGeometryData(),this._geometryData.initDefaults(),this._geometryData.recreate=!0,this._geometryData.maxVertices=i,this._geometryData.maxIndices=n,this._geometryData.verticesUsage=t?0:1,this._geometryData.indicesUsage=e?0:1},i.setVertexStream=function(t,e,i,n,s,r){void 0===s&&(s=6),void 0===r&&(r=!1),this._initGeometryData();var a=n||e.length/i;this._geometryData._changeVertexCount(a,t),this._geometryData.vertexStreamsUpdated=!0,this._geometryData.vertexStreamDictionary[t]=new ja(e,i,s,r)},i.getVertexStream=function(t,e){var i=0,n=!1;if(this._geometryData){var s=this._geometryData.vertexStreamDictionary[t];s&&(n=!0,i=this._geometryData.vertexCount,ArrayBuffer.isView(e)?e.set(s.data):(e.length=0,e.push(s.data)))}n||this.vertexBuffer&&(i=new Lr(this.vertexBuffer).readData(t,e));return i},i.setPositions=function(t,e,i){void 0===e&&(e=Xa.DEFAULT_COMPONENTS_POSITION),this.setVertexStream(we,t,e,i,6,!1)},i.setNormals=function(t,e,i){void 0===e&&(e=Xa.DEFAULT_COMPONENTS_NORMAL),this.setVertexStream(Te,t,e,i,6,!1)},i.setUvs=function(t,e,i,n){void 0===i&&(i=Xa.DEFAULT_COMPONENTS_UV),this.setVertexStream(Pe+t,e,i,n,6,!1)},i.setColors=function(t,e,i){void 0===e&&(e=Xa.DEFAULT_COMPONENTS_COLORS),this.setVertexStream(Me,t,e,i,6,!1)},i.setColors32=function(t,e){this.setVertexStream(Me,t,Xa.DEFAULT_COMPONENTS_COLORS,e,mi,!0)},i.setIndices=function(t,e){this._initGeometryData(),this._geometryData.indexStreamUpdated=!0,this._geometryData.indices=t,this._geometryData.indexCount=e||t.length},i.getPositions=function(t){return this.getVertexStream(we,t)},i.getNormals=function(t){return this.getVertexStream(Te,t)},i.getUvs=function(t,e){return this.getVertexStream(Pe+t,e)},i.getColors=function(t){return this.getVertexStream(Me,t)},i.getIndices=function(t){var e=0;if(this._geometryData&&this._geometryData.indices){var i=this._geometryData.indices;if(e=this._geometryData.indexCount,ArrayBuffer.isView(t))t.set(i);else{t.length=0;for(var n=0,s=i.length;n<s;n++)t.push(i[n])}}else{if(this.indexBuffer.length>0&&this.indexBuffer[0])e=this.indexBuffer[0].readData(t)}return e},i.update=function(t,e){if(void 0===t&&(t=4),void 0===e&&(e=!0),this._geometryData){if(e){var i=this._geometryData.vertexStreamDictionary[we];i&&3===i.componentCount&&(this._aabb.compute(i.data,this._geometryData.vertexCount),this._aabbVer++)}var n=this._geometryData.recreate;this._geometryData.vertexCount>this._geometryData.maxVertices&&(n=!0,this._geometryData.maxVertices=this._geometryData.vertexCount),n&&this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=null);var s=this._geometryData.recreate;this._geometryData.indexCount>this._geometryData.maxIndices&&(s=!0,this._geometryData.maxIndices=this._geometryData.indexCount),s&&this.indexBuffer.length>0&&this.indexBuffer[0]&&(this.indexBuffer[0].destroy(),this.indexBuffer[0]=null),this._geometryData.vertexStreamsUpdated&&this._updateVertexBuffer(),this._geometryData.indexStreamUpdated&&this._updateIndexBuffer(),this.primitive[0].type=t,this.indexBuffer.length>0&&this.indexBuffer[0]?this._geometryData.indexStreamUpdated&&(this.primitive[0].count=this._geometryData.indexCount,this.primitive[0].indexed=!0):this._geometryData.vertexStreamsUpdated&&(this.primitive[0].count=this._geometryData.vertexCount,this.primitive[0].indexed=!1),this._geometryData.vertexCount=0,this._geometryData.indexCount=0,this._geometryData.vertexStreamsUpdated=!1,this._geometryData.indexStreamUpdated=!1,this._geometryData.recreate=!1,this.updateRenderStates()}},i._buildVertexFormat=function(t){var e=[];for(var i in this._geometryData.vertexStreamDictionary){var n=this._geometryData.vertexStreamDictionary[i];e.push({semantic:i,components:n.componentCount,type:n.dataType,normalize:n.dataTypeNormalize})}return new Ji(this.device,e,t)},i._updateVertexBuffer=function(){if(!this.vertexBuffer){var t=this._geometryData.maxVertices,e=this._buildVertexFormat(t);this.vertexBuffer=new ji(this.device,e,t,this._geometryData.verticesUsage)}var i=new Lr(this.vertexBuffer),n=this._geometryData.vertexCount;for(var s in this._geometryData.vertexStreamDictionary){var r=this._geometryData.vertexStreamDictionary[s];i.writeData(s,r.data,n),delete this._geometryData.vertexStreamDictionary[s]}i.end()},i._updateIndexBuffer=function(){if(this.indexBuffer.length<=0||!this.indexBuffer[0]){var t=this._geometryData.maxVertices>65535?2:1;this.indexBuffer[0]=new vr(this.device,t,this._geometryData.maxIndices,this._geometryData.indicesUsage)}var e=this._geometryData.indices;e&&(this.indexBuffer[0].writeData(e,this._geometryData.indexCount),this._geometryData.indices=null)},i.prepareRenderState=function(t){1===t?this.generateWireframe():2===t&&(this.primitive[2]={type:0,base:0,count:this.vertexBuffer?this.vertexBuffer.numVertices:0,indexed:!1})},i.updateRenderStates=function(){this.primitive[2]&&this.prepareRenderState(2),this.primitive[1]&&this.prepareRenderState(1)},i.generateWireframe=function(){this._destroyIndexBuffer(1);var t,e=this.vertexBuffer.numVertices,i=[];if(this.indexBuffer.length>0&&this.indexBuffer[0]){for(var n=[[0,1],[1,2],[2,0]],s=this.primitive[0].base,r=this.primitive[0].count,a=this.indexBuffer[0],o=new Mi[a.format](a.storage),h=new Set,l=s;l<s+r;l+=3)for(var c=0;c<3;c++){var u=o[l+n[c][0]],d=o[l+n[c][1]],f=u>d?d*e+u:u*e+d;h.has(f)||(h.add(f),i.push(u,d))}t=a.format}else{for(var p=0;p<e;p+=3)i.push(p,p+1,p+1,p+2,p+2,p);t=i.length>65535?2:1}var m=new vr(this.vertexBuffer.device,t,i.length);new Mi[m.format](m.storage).set(i),m.unlock(),this.primitive[1]={type:1,base:0,count:i.length,indexed:!0},this.indexBuffer[1]=m},y(e,[{key:"morph",get:function(){return this._morph},set:function(t){t!==this._morph&&(this._morph&&this._morph.decRefCount(),this._morph=t,t&&t.incRefCount())}},{key:"aabb",get:function(){return this._aabb},set:function(t){this._aabb=t,this._aabbVer++}}]),e}(Ga),Ya=4/64,Ka=1-2*Ya,Za=[];function Qa(t,e){for(var i=e.length/3,n=t.length/3,s=new wt,r=new wt,a=new wt,o=new wt,h=new wt,l=new wt,c=[],u=0;u<t.length;u++)c[u]=0;for(var d=0;d<i;d++){var f=e[3*d],p=e[3*d+1],m=e[3*d+2];s.set(t[3*f],t[3*f+1],t[3*f+2]),r.set(t[3*p],t[3*p+1],t[3*p+2]),a.set(t[3*m],t[3*m+1],t[3*m+2]),o.sub2(r,s),h.sub2(a,s),l.cross(o,h).normalize(),c[3*f]+=l.x,c[3*f+1]+=l.y,c[3*f+2]+=l.z,c[3*p]+=l.x,c[3*p+1]+=l.y,c[3*p+2]+=l.z,c[3*m]+=l.x,c[3*m+1]+=l.y,c[3*m+2]+=l.z}for(var _=0;_<n;_++){var v=c[3*_],g=c[3*_+1],y=c[3*_+2],x=1/Math.sqrt(v*v+g*g+y*y);c[3*_]*=x,c[3*_+1]*=x,c[3*_+2]*=x}return c}function $a(t,e,i,n){for(var s=n.length/3,r=t.length/3,a=new wt,o=new wt,h=new wt,l=new Et,c=new Et,u=new Et,d=new wt,f=new wt,p=new Float32Array(3*r),m=new Float32Array(3*r),_=[],v=0;v<s;v++){var g=n[3*v],y=n[3*v+1],x=n[3*v+2];a.set(t[3*g],t[3*g+1],t[3*g+2]),o.set(t[3*y],t[3*y+1],t[3*y+2]),h.set(t[3*x],t[3*x+1],t[3*x+2]),l.set(i[2*g],i[2*g+1]),c.set(i[2*y],i[2*y+1]),u.set(i[2*x],i[2*x+1]);var S=o.x-a.x,b=h.x-a.x,w=o.y-a.y,T=h.y-a.y,A=o.z-a.z,C=h.z-a.z,E=c.x-l.x,M=u.x-l.x,P=c.y-l.y,R=u.y-l.y,I=E*R-M*P;if(0===I)d.set(0,1,0),f.set(1,0,0);else{var L=1/I;d.set((R*S-P*b)*L,(R*w-P*T)*L,(R*A-P*C)*L),f.set((E*b-M*S)*L,(E*T-M*w)*L,(E*C-M*A)*L)}p[3*g+0]+=d.x,p[3*g+1]+=d.y,p[3*g+2]+=d.z,p[3*y+0]+=d.x,p[3*y+1]+=d.y,p[3*y+2]+=d.z,p[3*x+0]+=d.x,p[3*x+1]+=d.y,p[3*x+2]+=d.z,m[3*g+0]+=f.x,m[3*g+1]+=f.y,m[3*g+2]+=f.z,m[3*y+0]+=f.x,m[3*y+1]+=f.y,m[3*y+2]+=f.z,m[3*x+0]+=f.x,m[3*x+1]+=f.y,m[3*x+2]+=f.z}for(var D=new wt,O=new wt,k=new wt,F=new wt,B=0;B<r;B++){k.set(e[3*B],e[3*B+1],e[3*B+2]),D.set(p[3*B],p[3*B+1],p[3*B+2]),O.set(m[3*B],m[3*B+1],m[3*B+2]);var U=k.dot(D);F.copy(k).mulScalar(U),F.sub2(D,F).normalize(),_[4*B]=F.x,_[4*B+1]=F.y,_[4*B+2]=F.z,F.cross(k,D),_[4*B+3]=F.dot(O)<0?-1:1}return _}function Ja(t,e,i){var n=new qa(t);return n.setPositions(e),i&&(i.normals&&n.setNormals(i.normals),i.tangents&&n.setVertexStream(Ae,i.tangents,4),i.colors&&n.setColors32(i.colors),i.uvs&&n.setUvs(0,i.uvs),i.uvs1&&n.setUvs(1,i.uvs1),i.blendIndices&&n.setVertexStream(Ee,i.blendIndices,4,i.blendIndices.length/4,mi),i.blendWeights&&n.setVertexStream(Ce,i.blendWeights,4),i.indices&&n.setIndices(i.indices)),n.update(),n}function to(t,e){var i,n,s,r,a;void 0===e&&(e={});for(var o=null!=(i=e.tubeRadius)?i:.2,h=null!=(n=e.ringRadius)?n:.3,l=null!=(s=e.segments)?s:30,c=null!=(r=e.sides)?r:20,u=null!=(a=e.calculateTangents)&&a,d=[],f=[],p=[],m=[],_=0;_<=c;_++)for(var v=0;v<=l;v++){var g=Math.cos(2*Math.PI*v/l)*(h+o*Math.cos(2*Math.PI*_/c)),y=Math.sin(2*Math.PI*_/c)*o,x=Math.sin(2*Math.PI*v/l)*(h+o*Math.cos(2*Math.PI*_/c)),S=Math.cos(2*Math.PI*v/l)*Math.cos(2*Math.PI*_/c),b=Math.sin(2*Math.PI*_/c),w=Math.sin(2*Math.PI*v/l)*Math.cos(2*Math.PI*_/c),T=_/c,A=1-v/l;if(d.push(g,y,x),f.push(S,b,w),p.push(T,1-A),_<c&&v<l){var C=_*(l+1)+v,E=(_+1)*(l+1)+v,M=_*(l+1)+(v+1),P=(_+1)*(l+1)+(v+1);m.push(C,E,M),m.push(E,P,M)}}var R={normals:f,uvs:p,uvs1:p,indices:m};return u&&(R.tangents=$a(d,f,p,m)),Ja(t,d,R)}function eo(t,e,i,n,s,r){var a,o=new wt,h=new wt,l=new wt,c=new wt,u=new wt,d=new wt,f=[],p=[],m=[],_=[],v=[];if(i>0)for(var g=0;g<=n;g++)for(var y=0;y<=s;y++){var x=y/s*2*Math.PI-Math.PI,S=Math.sin(x),b=Math.cos(x);u.set(S*t,-i/2,b*t),c.set(S*e,i/2,b*e),o.lerp(u,c,g/n),h.sub2(c,u).normalize(),d.set(b,0,-S),l.cross(d,h).normalize(),f.push(o.x,o.y,o.z),p.push(l.x,l.y,l.z);var w=y/s,T=g/n;m.push(w,1-T);var A=T;if(T=w,w=(w=A)*Ka+Ya,T=T*Ka+Ya,w/=3,_.push(w,1-T),g<n&&y<s){var C=g*(s+1)+y,E=g*(s+1)+(y+1),M=(g+1)*(s+1)+y,P=(g+1)*(s+1)+(y+1);v.push(C,E,M),v.push(E,P,M)}}if(r){for(var R=Math.floor(s/2),I=s,L=i/2,D=0;D<=R;D++)for(var O=D*Math.PI*.5/R,k=Math.sin(O),F=Math.cos(O),B=0;B<=I;B++){var U=2*B*Math.PI/I-Math.PI/2,N=Math.sin(U),z=Math.cos(U)*k,V=F,G=N*k,H=1-B/I,W=1-D/R;f.push(z*e,V*e+L,G*e),p.push(z,V,G),m.push(H,1-W),H=H*Ka+Ya,W=W*Ka+Ya,H/=3,W/=3,H+=1/3,_.push(H,1-W)}a=(n+1)*(s+1);for(var X=0;X<R;++X)for(var j=0;j<I;++j){var q=X*(I+1)+j,Y=q+I+1;v.push(a+q+1,a+Y,a+q),v.push(a+q+1,a+Y+1,a+Y)}for(var K=0;K<=R;K++)for(var Z=.5*Math.PI+K*Math.PI*.5/R,Q=Math.sin(Z),$=Math.cos(Z),J=0;J<=I;J++){var tt=2*J*Math.PI/I-Math.PI/2,et=Math.sin(tt),it=Math.cos(tt)*Q,nt=$,st=et*Q,rt=1-J/I,at=1-K/R;f.push(it*e,nt*e-L,st*e),p.push(it,nt,st),m.push(rt,1-at),rt=rt*Ka+Ya,at=at*Ka+Ya,rt/=3,at/=3,rt+=2/3,_.push(rt,1-at)}a=(n+1)*(s+1)+(I+1)*(R+1);for(var ot=0;ot<R;++ot)for(var ht=0;ht<I;++ht){var lt=ot*(I+1)+ht,ct=lt+I+1;v.push(a+lt+1,a+ct,a+lt),v.push(a+lt+1,a+ct+1,a+ct)}}else{if(a=(n+1)*(s+1),t>0)for(var ut=0;ut<s;ut++){var dt=ut/s*2*Math.PI,ft=Math.sin(dt),pt=-i/2,mt=Math.cos(dt),_t=1-(ft+1)/2,vt=(mt+1)/2;f.push(ft*t,pt,mt*t),p.push(0,-1,0),m.push(_t,1-vt),_t=_t*Ka+Ya,vt=vt*Ka+Ya,_t/=3,vt/=3,_t+=1/3,_.push(_t,1-vt),ut>1&&v.push(a,a+ut,a+ut-1)}if(a+=s,e>0)for(var gt=0;gt<s;gt++){var yt=gt/s*2*Math.PI,xt=Math.sin(yt),St=i/2,bt=Math.cos(yt),Tt=1-(xt+1)/2,At=(bt+1)/2;f.push(xt*e,St,bt*e),p.push(0,1,0),m.push(Tt,1-At),Tt=Tt*Ka+Ya,At=At*Ka+Ya,Tt/=3,At/=3,Tt+=2/3,_.push(Tt,1-At),gt>1&&v.push(a,a+gt-1,a+gt)}}return{positions:f,normals:p,uvs:m,uvs1:_,indices:v}}function io(t,e){var i,n,s,r,a;void 0===e&&(e={});var o=null!=(i=e.radius)?i:.5,h=null!=(n=e.height)?n:1,l=null!=(s=e.heightSegments)?s:5,c=null!=(r=e.capSegments)?r:20,u=null!=(a=e.calculateTangents)&&a,d=eo(o,o,h,l,c,!1);return u&&(d.tangents=$a(d.positions,d.normals,d.uvs,d.indices)),Ja(t,d.positions,d)}function no(t,e){var i,n,s,r,a;void 0===e&&(e={});var o=null!=(i=e.radius)?i:.3,h=null!=(n=e.height)?n:1,l=null!=(s=e.heightSegments)?s:1,c=null!=(r=e.sides)?r:20,u=null!=(a=e.calculateTangents)&&a,d=eo(o,o,h-2*o,l,c,!0);return u&&(d.tangents=$a(d.positions,d.normals,d.uvs,d.indices)),Ja(t,d.positions,d)}function so(t,e){var i,n,s,r,a,o;void 0===e&&(e={});var h=null!=(i=e.baseRadius)?i:.5,l=null!=(n=e.peakRadius)?n:0,c=null!=(s=e.height)?s:1,u=null!=(r=e.heightSegments)?r:5,d=null!=(a=e.capSegments)?a:18,f=null!=(o=e.calculateTangents)&&o,p=eo(h,l,c,u,d,!1);return f&&(p.tangents=$a(p.positions,p.normals,p.uvs,p.indices)),Ja(t,p.positions,p)}function ro(t,e){var i,n,s,r;void 0===e&&(e={});for(var a=null!=(i=e.radius)?i:.5,o=null!=(n=e.latitudeBands)?n:16,h=null!=(s=e.longitudeBands)?s:16,l=null!=(r=e.calculateTangents)&&r,c=[],u=[],d=[],f=[],p=0;p<=o;p++)for(var m=p*Math.PI/o,_=Math.sin(m),v=Math.cos(m),g=0;g<=h;g++){var y=2*g*Math.PI/h-Math.PI/2,x=Math.sin(y),S=Math.cos(y)*_,b=v,w=x*_,T=1-g/h,A=1-p/o;c.push(S*a,b*a,w*a),u.push(S,b,w),d.push(T,1-A)}for(var C=0;C<o;++C)for(var E=0;E<h;++E){var M=C*(h+1)+E,P=M+h+1;f.push(M+1,P,M),f.push(M+1,P+1,P)}var R={normals:u,uvs:d,uvs1:d,indices:f};return l&&(R.tangents=$a(c,u,d,f)),Ja(t,c,R)}function ao(t,e){var i,n,s,r;void 0===e&&(e={});for(var a=null!=(i=e.halfExtents)?i:new Et(.5,.5),o=null!=(n=e.widthSegments)?n:5,h=null!=(s=e.lengthSegments)?s:5,l=null!=(r=e.calculateTangents)&&r,c=[],u=[],d=[],f=[],p=0,m=0;m<=o;m++)for(var _=0;_<=h;_++){var v=-a.x+2*a.x*m/o,g=-(-a.y+2*a.y*_/h),y=m/o,x=_/h;c.push(v,0,g),u.push(0,1,0),d.push(y,1-x),m<o&&_<h&&(f.push(p+h+1,p+1,p),f.push(p+h+1,p+h+2,p+1)),p++}var S={normals:u,uvs:d,uvs1:d,indices:f};return l&&(S.tangents=$a(c,u,d,f)),Ja(t,c,S)}function oo(t,e){var i,n,s,r,a;void 0===e&&(e={});var o=null!=(i=e.halfExtents)?i:new wt(.5,.5,.5),h=null!=(n=e.widthSegments)?n:1,l=null!=(s=e.lengthSegments)?s:1,c=null!=(r=e.heightSegments)?r:1,u=null!=(a=e.calculateTangents)&&a,d=[new wt(-o.x,-o.y,o.z),new wt(o.x,-o.y,o.z),new wt(o.x,o.y,o.z),new wt(-o.x,o.y,o.z),new wt(o.x,-o.y,-o.z),new wt(-o.x,-o.y,-o.z),new wt(-o.x,o.y,-o.z),new wt(o.x,o.y,-o.z)],f=[[0,1,3],[4,5,7],[3,2,6],[1,0,4],[1,4,2],[5,0,6]],p=[[0,0,1],[0,0,-1],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0]],m=1,_=2,v=3,g=4,y=5,x=[],S=[],b=[],w=[],T=[],A=0,C=function(t,e,i){for(var n=new wt,s=new wt,r=new wt,a=new wt,o=0;o<=e;o++)for(var h=0;h<=i;h++){n.lerp(d[f[t][0]],d[f[t][1]],o/e),s.lerp(d[f[t][0]],d[f[t][2]],h/i),r.sub2(s,d[f[t][0]]),a.add2(n,r);var l=o/e,c=h/i;x.push(a.x,a.y,a.z),S.push(p[t][0],p[t][1],p[t][2]),b.push(l,1-c),l=l*Ka+Ya,c=c*Ka+Ya,l/=3,c/=3,l+=t%3/3,c+=Math.floor(t/3)/3,w.push(l,1-c),o<e&&h<i&&(T.push(A+i+1,A+1,A),T.push(A+i+1,A+i+2,A+1)),A++}};C(0,h,c),C(m,h,c),C(_,h,l),C(v,h,l),C(g,l,c),C(y,l,c);var E={normals:S,uvs:b,uvs1:w,indices:T};return u&&(E.tangents=$a(x,S,b,T)),Ja(t,x,E)}function ho(t,e){for(var i=null,n=0;n<Za.length;n++)Za[n].type===e&&Za[n].device===t&&(i=Za[n].primData);if(!i){var s,r;switch(e){case"box":s=oo(t),r={x:2,y:2,z:2,uv:2/3};break;case"capsule":s=no(t,{radius:.5,height:2}),r={x:2*Math.PI,y:Math.PI,z:2*Math.PI,uv:1/3+1/3/3*2};break;case"cone":s=so(t,{baseRadius:.5,peakRadius:0,height:1}),r={x:2.54,y:2.54,z:2.54,uv:1/3+1/3/3};break;case"cylinder":s=io(t,{radius:.5,height:1}),r={x:Math.PI,y:1.58,z:Math.PI,uv:1/3+1/3/3*2};break;case"plane":s=ao(t,{halfExtents:new Et(.5,.5),widthSegments:1,lengthSegments:1}),r={x:0,y:1,z:0,uv:1};break;case"sphere":s=ro(t,{radius:.5}),r={x:Math.PI,y:Math.PI,z:Math.PI,uv:1};break;case"torus":s=to(t,{tubeRadius:.2,ringRadius:.3}),r={x:.5*Math.PI*.5-.1*Math.PI*.1,y:.4,z:.4,uv:1};break;default:throw new Error("Invalid primitive type: "+e)}s.incRefCount(),i={mesh:s,area:r},Za.push({type:e,device:t,primData:i})}return i}var lo=function(){this.clearValue=new vt(0,0,0,1),this.clear=!1,this.store=!1,this.resolve=!0,this.mipmaps=!1},co=function(){this.clearDepthValue=1,this.clearStencilValue=0,this.clearDepth=!1,this.clearStencil=!1,this.storeDepth=!1,this.storeStencil=!1},uo=function(){function t(t,e){this.name=void 0,this.renderTarget=void 0,this.samples=0,this.colorArrayOps=[],this.depthStencilOps=void 0,this.requiresCubemaps=!0,this.fullSizeClearRect=!0,this._execute=void 0,this.executeEnabled=!0,this._before=void 0,this._after=void 0,this.device=t,this._execute=e}var e=t.prototype;return e.destroy=function(){},e.init=function(t){var e;void 0===t&&(t=null),this.renderTarget=t,this.samples=Math.max(this.renderTarget?this.renderTarget.samples:this.device.samples,1),this.depthStencilOps=new co;for(var i=t?null==(e=t._colorBuffers)?void 0:e.length:1,n=0;n<i;n++){var s,r=new lo;this.colorArrayOps[n]=r,1===this.samples&&(r.store=!0,r.resolve=!1),null!=(s=this.renderTarget)&&null!=(s=s._colorBuffers)&&s[n].mipmaps&&(r.mipmaps=!0)}},e.before=function(){var t;null==(t=this._before)||t.call(this)},e.execute=function(){var t;null==(t=this._execute)||t.call(this)},e.after=function(){var t;null==(t=this._after)||t.call(this)},e.setClearColor=function(t){for(var e=this.colorArrayOps.length,i=0;i<e;i++){var n=this.colorArrayOps[i];n.clearValue.copy(t),n.clear=!0}},e.setClearDepth=function(t){this.depthStencilOps.clearDepthValue=t,this.depthStencilOps.clearDepth=!0},e.setClearStencil=function(t){this.depthStencilOps.clearStencilValue=t,this.depthStencilOps.clearStencil=!0},e.render=function(){var t=this.device,e=void 0!==this.renderTarget;this.before(),this.executeEnabled&&(e&&t.startPass(this),this.execute(),e&&t.endPass(this)),this.after(),t.renderPassIndex++},y(t,[{key:"colorOps",get:function(){return this.colorArrayOps[0]}}]),t}(),fo=function(){function t(t,e,i){this.uniformFormats=[],this.bindGroupFormats=[],this.vertexFormat=void 0,this.uniformFormats[1]=t,this.bindGroupFormats[1]=e,this.vertexFormat=i}var e=t.prototype;return e.hasUniform=function(t){for(var e=0;e<this.uniformFormats.length;e++){var i=this.uniformFormats[e];if(null!=i&&i.get(t))return!0}return!1},e.hasTexture=function(t){for(var e=0;e<this.bindGroupFormats.length;e++){var i=this.bindGroupFormats[e];if(null!=i&&i.getTexture(t))return!0}return!1},e.getVertexElement=function(t){var e;return null==(e=this.vertexFormat)?void 0:e.elements.find((function(e){return e.name===t}))},e.generateKey=function(t){var e,i=JSON.stringify(this.uniformFormats)+JSON.stringify(this.bindGroupFormats);t.isWebGPU&&(i+=null==(e=this.vertexFormat)?void 0:e.renderingHashString);return i},t}(),po="\nvec3 decodeLinear(vec4 raw) {\n\treturn raw.rgb;\n}\nfloat decodeGamma(float raw) {\n\treturn pow(raw, 2.2);\n}\nvec3 decodeGamma(vec3 raw) {\n\treturn pow(raw, vec3(2.2));\n}\nvec3 decodeGamma(vec4 raw) {\n\treturn pow(raw.xyz, vec3(2.2));\n}\nvec3 decodeRGBM(vec4 raw) {\n\tvec3 color = (8.0 * raw.a) * raw.rgb;\n\treturn color * color;\n}\nvec3 decodeRGBP(vec4 raw) {\n\tvec3 color = raw.rgb * (-raw.a * 7.0 + 8.0);\n\treturn color * color;\n}\nvec3 decodeRGBE(vec4 raw) {\n\tif (raw.a == 0.0) {\n\t\treturn vec3(0.0, 0.0, 0.0);\n\t} else {\n\t\treturn raw.xyz * pow(2.0, raw.w * 255.0 - 128.0);\n\t}\n}\nvec4 passThrough(vec4 raw) {\n\treturn raw;\n}\n",mo="\nvec4 encodeLinear(vec3 source) {\n\treturn vec4(source, 1.0);\n}\nvec4 encodeGamma(vec3 source) {\n\treturn vec4(pow(source + 0.0000001, vec3(1.0 / 2.2)), 1.0);\n}\nvec4 encodeRGBM(vec3 source) {\n\tvec4 result;\n\tresult.rgb = pow(source.rgb, vec3(0.5));\n\tresult.rgb *= 1.0 / 8.0;\n\tresult.a = saturate( max( max( result.r, result.g ), max( result.b, 1.0 / 255.0 ) ) );\n\tresult.a = ceil(result.a * 255.0) / 255.0;\n\tresult.rgb /= result.a;\n\treturn result;\n}\nvec4 encodeRGBP(vec3 source) {\n\tvec3 gamma = pow(source, vec3(0.5));\n\tfloat maxVal = min(8.0, max(1.0, max(gamma.x, max(gamma.y, gamma.z))));\n\tfloat v = 1.0 - ((maxVal - 1.0) / 7.0);\n\tv = ceil(v * 255.0) / 255.0;\n\treturn vec4(gamma / (-v * 7.0 + 8.0), v);\t\n}\nvec4 encodeRGBE(vec3 source) {\n\tfloat maxVal = max(source.x, max(source.y, source.z));\n\tif (maxVal < 1e-32) {\n\t\treturn vec4(0, 0, 0, 0);\n\t} else {\n\t\tfloat e = ceil(log2(maxVal));\n\t\treturn vec4(source / pow(2.0, e), (e + 128.0) / 255.0);\n\t}\n}\n",_o={alphaTestPS:"\nuniform float alpha_ref;\nvoid alphaTest(float a) {\n\tif (a < alpha_ref) discard;\n}\n",ambientConstantPS:"\nvoid addAmbient(vec3 worldNormal) {\n\tdDiffuseLight += light_globalAmbient;\n}\n",ambientEnvPS:"\n#ifndef ENV_ATLAS\n#define ENV_ATLAS\nuniform sampler2D texture_envAtlas;\n#endif\nvoid addAmbient(vec3 worldNormal) {\n\tvec3 dir = normalize(cubeMapRotate(worldNormal) * vec3(-1.0, 1.0, 1.0));\n\tvec2 uv = mapUv(toSphericalUv(dir), vec4(128.0, 256.0 + 128.0, 64.0, 32.0) / atlasSize);\n\tvec4 raw = texture2D(texture_envAtlas, uv);\n\tvec3 linear = $DECODE(raw);\n\tdDiffuseLight += processEnvironment(linear);\n}\n",ambientSHPS:"\nuniform vec3 ambientSH[9];\nvoid addAmbient(vec3 worldNormal) {\n\tvec3 n = cubeMapRotate(worldNormal);\n\tvec3 color =\n\t\tambientSH[0] +\n\t\tambientSH[1] * n.x +\n\t\tambientSH[2] * n.y +\n\t\tambientSH[3] * n.z +\n\t\tambientSH[4] * n.x * n.z +\n\t\tambientSH[5] * n.z * n.y +\n\t\tambientSH[6] * n.y * n.x +\n\t\tambientSH[7] * (3.0 * n.z * n.z - 1.0) +\n\t\tambientSH[8] * (n.x * n.x - n.y * n.y);\n\tdDiffuseLight += processEnvironment(max(color, vec3(0.0)));\n}\n",aoPS:"\nvoid getAO() {\n\tdAo = 1.0;\n\t#ifdef MAPTEXTURE\n\tfloat aoBase = texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\tdAo *= addAoDetail(aoBase);\n\t#endif\n\t#ifdef MAPVERTEX\n\tdAo *= saturate(vVertexColor.$VC);\n\t#endif\n}\n",aoDetailMapPS:"\nfloat addAoDetail(float ao) {\n#ifdef MAPTEXTURE\n\tfloat aoDetail = texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\treturn detailMode_$DETAILMODE(vec3(ao), vec3(aoDetail)).r;\n#else\n\treturn ao;\n#endif\n}\n",aoDiffuseOccPS:"\nvoid occludeDiffuse(float ao) {\n\tdDiffuseLight *= ao;\n}\n",aoSpecOccPS:"\nuniform float material_occludeSpecularIntensity;\nvoid occludeSpecular(float gloss, float ao, vec3 worldNormal, vec3 viewDir) {\n\tfloat specPow = exp2(gloss * 11.0);\n\tfloat specOcc = saturate(pow(dot(worldNormal, viewDir) + ao, 0.01*specPow) - 1.0 + ao);\n\tspecOcc = mix(1.0, specOcc, material_occludeSpecularIntensity);\n\tdSpecularLight *= specOcc;\n\tdReflection *= specOcc;\n\t\n#ifdef LIT_SHEEN\n\tsSpecularLight *= specOcc;\n\tsReflection *= specOcc;\n#endif\n}\n",aoSpecOccConstPS:"\nvoid occludeSpecular(float gloss, float ao, vec3 worldNormal, vec3 viewDir) {\n\tfloat specPow = exp2(gloss * 11.0);\n\tfloat specOcc = saturate(pow(dot(worldNormal, viewDir) + ao, 0.01*specPow) - 1.0 + ao);\n\tdSpecularLight *= specOcc;\n\tdReflection *= specOcc;\n\t\n#ifdef LIT_SHEEN\n\tsSpecularLight *= specOcc;\n\tsReflection *= specOcc;\n#endif\n}\n",aoSpecOccConstSimplePS:"\nvoid occludeSpecular(float gloss, float ao, vec3 worldNormal, vec3 viewDir) {\n\tdSpecularLight *= ao;\n\tdReflection *= ao;\n#ifdef LIT_SHEEN\n\tsSpecularLight *= ao;\n\tsReflection *= ao;\n#endif\n}\n",aoSpecOccSimplePS:"\nuniform float material_occludeSpecularIntensity;\nvoid occludeSpecular(float gloss, float ao, vec3 worldNormal, vec3 viewDir) {\n\tfloat specOcc = mix(1.0, ao, material_occludeSpecularIntensity);\n\tdSpecularLight *= specOcc;\n\tdReflection *= specOcc;\n#ifdef LIT_SHEEN\n\tsSpecularLight *= specOcc;\n\tsReflection *= specOcc;\n#endif\n}\n",basePS:"\nuniform vec3 view_position;\nuniform vec3 light_globalAmbient;\nfloat square(float x) {\n\treturn x*x;\n}\nfloat saturate(float x) {\n\treturn clamp(x, 0.0, 1.0);\n}\nvec3 saturate(vec3 x) {\n\treturn clamp(x, vec3(0.0), vec3(1.0));\n}\n",baseVS:"\nattribute vec3 vertex_position;\nattribute vec3 vertex_normal;\nattribute vec4 vertex_tangent;\nattribute vec2 vertex_texCoord0;\nattribute vec2 vertex_texCoord1;\nattribute vec4 vertex_color;\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\nuniform mat3 matrix_normal;\nvec3 dPositionW;\nmat4 dModelMatrix;\nmat3 dNormalMatrix;\n",baseNineSlicedPS:"\n#define NINESLICED\nvarying vec2 vMask;\nvarying vec2 vTiledUv;\nuniform mediump vec4 innerOffset;\nuniform mediump vec2 outerScale;\nuniform mediump vec4 atlasRect;\nvec2 nineSlicedUv;\n",baseNineSlicedVS:"\n#define NINESLICED\nvarying vec2 vMask;\nvarying vec2 vTiledUv;\nuniform mediump vec4 innerOffset;\nuniform mediump vec2 outerScale;\nuniform mediump vec4 atlasRect;\n",baseNineSlicedTiledPS:"\n#define NINESLICED\n#define NINESLICETILED\nvarying vec2 vMask;\nvarying vec2 vTiledUv;\nuniform mediump vec4 innerOffset;\nuniform mediump vec2 outerScale;\nuniform mediump vec4 atlasRect;\nvec2 nineSlicedUv;\n",biasConstPS:"\n#define SHADOWBIAS\n#define SHADOW_SAMPLE_Z_BIAS\nfloat getShadowBias(float resolution, float maxBias) {\n\treturn maxBias;\n}\n",blurVSMPS:"\nvarying vec2 vUv0;\nuniform sampler2D source;\nuniform vec2 pixelOffset;\n#ifdef GAUSS\nuniform float weight[SAMPLES];\n#endif\n#ifdef PACKED\nfloat decodeFloatRG(vec2 rg) {\n\treturn rg.y*(1.0/255.0) + rg.x;\n}\nvec2 encodeFloatRG( float v ) {\n\tvec2 enc = vec2(1.0, 255.0) * v;\n\tenc = fract(enc);\n\tenc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n\treturn enc;\n}\n#endif\nvoid main(void) {\n\tvec3 moments = vec3(0.0);\n\tvec2 uv = vUv0 - pixelOffset * (float(SAMPLES) * 0.5);\n\tfor (int i=0; i<SAMPLES; i++) {\n\t\tvec4 c = texture2D(source, uv + pixelOffset * float(i));\n\t\t#ifdef PACKED\n\t\tc.xy = vec2(decodeFloatRG(c.xy), decodeFloatRG(c.zw));\n\t\t#endif\n\t\t#ifdef GAUSS\n\t\tmoments += c.xyz * weight[i];\n\t\t#else\n\t\tmoments += c.xyz;\n\t\t#endif\n\t}\n\t#ifndef GAUSS\n\tmoments /= float(SAMPLES);\n\t#endif\n\t#ifdef PACKED\n\tgl_FragColor = vec4(encodeFloatRG(moments.x), encodeFloatRG(moments.y));\n\t#else\n\tgl_FragColor = vec4(moments.x, moments.y, moments.z, 1.0);\n\t#endif\n}\n",clearCoatPS:"\n#ifdef MAPFLOAT\nuniform float material_clearCoat;\n#endif\nvoid getClearCoat() {\n\tccSpecularity = 1.0;\n\t#ifdef MAPFLOAT\n\tccSpecularity *= material_clearCoat;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tccSpecularity *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tccSpecularity *= saturate(vVertexColor.$VC);\n\t#endif\n}\n",clearCoatGlossPS:"\n#ifdef MAPFLOAT\nuniform float material_clearCoatGloss;\n#endif\nvoid getClearCoatGlossiness() {\n\tccGlossiness = 1.0;\n\t#ifdef MAPFLOAT\n\tccGlossiness *= material_clearCoatGloss;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tccGlossiness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tccGlossiness *= saturate(vVertexColor.$VC);\n\t#endif\n\t#ifdef MAPINVERT\n\tccGlossiness = 1.0 - ccGlossiness;\n\t#endif\n\tccGlossiness += 0.0000001;\n}\n",clearCoatNormalPS:"\n#ifdef MAPTEXTURE\nuniform float material_clearCoatBumpiness;\n#endif\nvoid getClearCoatNormal() {\n#ifdef MAPTEXTURE\n\tvec3 normalMap = unpackNormal(texture2DBias($SAMPLER, $UV, textureBias));\n\tnormalMap = mix(vec3(0.0, 0.0, 1.0), normalMap, material_clearCoatBumpiness);\n\tccNormalW = normalize(dTBN * normalMap);\n#else\n\tccNormalW = dVertexNormalW;\n#endif\n}\n",clusteredLightCookiesPS:"\nvec3 _getCookieClustered(TEXTURE_ACCEPT(tex), vec2 uv, float intensity, bool isRgb, vec4 cookieChannel) {\n\tvec4 pixel = mix(vec4(1.0), texture2DLodEXT(tex, uv, 0.0), intensity);\n\treturn isRgb == true ? pixel.rgb : vec3(dot(pixel, cookieChannel));\n}\nvec3 getCookie2DClustered(TEXTURE_ACCEPT(tex), mat4 transform, vec3 worldPosition, float intensity, bool isRgb, vec4 cookieChannel) {\n\tvec4 projPos = transform * vec4(worldPosition, 1.0);\n\treturn _getCookieClustered(TEXTURE_PASS(tex), projPos.xy / projPos.w, intensity, isRgb, cookieChannel);\n}\nvec3 getCookieCubeClustered(TEXTURE_ACCEPT(tex), vec3 dir, float intensity, bool isRgb, vec4 cookieChannel, float shadowTextureResolution, float shadowEdgePixels, vec3 omniAtlasViewport) {\n\tvec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir);\n\treturn _getCookieClustered(TEXTURE_PASS(tex), uv, intensity, isRgb, cookieChannel);\n}\n",clusteredLightShadowsPS:"\nvoid _getShadowCoordPerspZbuffer(mat4 shadowMatrix, vec4 shadowParams, vec3 wPos) {\n\tvec4 projPos = shadowMatrix * vec4(wPos, 1.0);\n\tprojPos.xyz /= projPos.w;\n\tdShadowCoord = projPos.xyz;\n}\nvoid getShadowCoordPerspZbufferNormalOffset(mat4 shadowMatrix, vec4 shadowParams, vec3 normal) {\n\tvec3 wPos = vPositionW + normal * shadowParams.y;\n\t_getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, wPos);\n}\nvec3 normalOffsetPointShadow(vec4 shadowParams, vec3 lightPos, inout vec3 lightDir, vec3 lightDirNorm, vec3 normal) {\n\tfloat distScale = length(lightDir);\n\tvec3 wPos = vPositionW + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;\n\tvec3 dir = wPos - lightPos;\n\treturn dir;\n}\n#ifdef GL2\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\tfloat getShadowOmniClusteredPCF1(SHADOWMAP_ACCEPT(shadowMap), vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {\n\t\tfloat shadowTextureResolution = shadowParams.x;\n\t\tvec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n\t\tfloat shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;\n\t\treturn textureShadow(shadowMap, vec3(uv, shadowZ));\n\t}\n\t#endif\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF3)\n\tfloat getShadowOmniClusteredPCF3(SHADOWMAP_ACCEPT(shadowMap), vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {\n\t\tfloat shadowTextureResolution = shadowParams.x;\n\t\tvec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n\t\tfloat shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;\n\t\tvec3 shadowCoord = vec3(uv, shadowZ);\n\t\treturn getShadowPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);\n\t}\n\t#endif\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\tfloat getShadowOmniClusteredPCF5(SHADOWMAP_ACCEPT(shadowMap), vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {\n\t\tfloat shadowTextureResolution = shadowParams.x;\n\t\tvec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n\t\tfloat shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;\n\t\tvec3 shadowCoord = vec3(uv, shadowZ);\n\t\treturn getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);\n\t}\n\t#endif\n#else\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\tfloat getShadowOmniClusteredPCF1(sampler2D shadowMap, vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {\n\t\tfloat shadowTextureResolution = shadowParams.x;\n\t\tvec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n\t\tfloat depth = unpackFloat(textureShadow(shadowMap, uv));\n\t\tfloat shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;\n\t\treturn depth > shadowZ ? 1.0 : 0.0;\n\t}\n\t#endif\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF3)\n\tfloat getShadowOmniClusteredPCF3(sampler2D shadowMap, vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {\n\t\tfloat shadowTextureResolution = shadowParams.x;\n\t\tvec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n\t\tfloat shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;\n\t\tvec3 shadowCoord = vec3(uv, shadowZ);\n\t\treturn getShadowPCF3x3(shadowMap, shadowCoord, shadowParams);\n\t}\n\t#endif\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\tfloat getShadowOmniClusteredPCF5(sampler2D shadowMap, vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {\n\t\tfloat shadowTextureResolution = shadowParams.x;\n\t\tvec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n\t\tfloat shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;\n\t\tvec3 shadowCoord = vec3(uv, shadowZ);\n\t\treturn getShadowPCF3x3(shadowMap, shadowCoord, shadowParams);\n\t}\n\t#endif\n#endif\n#ifdef GL2\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\tfloat getShadowSpotClusteredPCF1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n\t\treturn textureShadow(shadowMap, shadowCoord);\n\t}\n\t#endif\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF3)\n\tfloat getShadowSpotClusteredPCF3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n\t\treturn getShadowSpotPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);\n\t}\n\t#endif\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\tfloat getShadowSpotClusteredPCF5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n\t\treturn getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);\n\t}\n\t#endif\n#else\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\tfloat getShadowSpotClusteredPCF1(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n\t\tfloat depth = unpackFloat(textureShadow(shadowMap, shadowCoord.xy));\n\t\treturn depth > shadowCoord.z ? 1.0 : 0.0;\n\t}\n\t#endif\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF3)\n\tfloat getShadowSpotClusteredPCF3(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n\t\treturn getShadowSpotPCF3x3(shadowMap, shadowCoord, shadowParams);\n\t}\n\t#endif\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\tfloat getShadowSpotClusteredPCF5(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n\t\treturn getShadowSpotPCF3x3(shadowMap, shadowCoord, shadowParams);\n\t}\n\t#endif\n#endif\n",clusteredLightUtilsPS:"\nvec2 getCubemapFaceCoordinates(const vec3 dir, out float faceIndex, out vec2 tileOffset)\n{\n\tvec3 vAbs = abs(dir);\n\tfloat ma;\n\tvec2 uv;\n\tif (vAbs.z >= vAbs.x && vAbs.z >= vAbs.y) {\n\t\tfaceIndex = dir.z < 0.0 ? 5.0 : 4.0;\n\t\tma = 0.5 / vAbs.z;\n\t\tuv = vec2(dir.z < 0.0 ? -dir.x : dir.x, -dir.y);\n\t\ttileOffset.x = 2.0;\n\t\ttileOffset.y = dir.z < 0.0 ? 1.0 : 0.0;\n\t} else if(vAbs.y >= vAbs.x) {\n\t\tfaceIndex = dir.y < 0.0 ? 3.0 : 2.0;\n\t\tma = 0.5 / vAbs.y;\n\t\tuv = vec2(dir.x, dir.y < 0.0 ? -dir.z : dir.z);\n\t\ttileOffset.x = 1.0;\n\t\ttileOffset.y = dir.y < 0.0 ? 1.0 : 0.0;\n\t} else {\n\t\tfaceIndex = dir.x < 0.0 ? 1.0 : 0.0;\n\t\tma = 0.5 / vAbs.x;\n\t\tuv = vec2(dir.x < 0.0 ? dir.z : -dir.z, -dir.y);\n\t\ttileOffset.x = 0.0;\n\t\ttileOffset.y = dir.x < 0.0 ? 1.0 : 0.0;\n\t}\n\treturn uv * ma + 0.5;\n}\nvec2 getCubemapAtlasCoordinates(const vec3 omniAtlasViewport, float shadowEdgePixels, float shadowTextureResolution, const vec3 dir) {\n\tfloat faceIndex;\n\tvec2 tileOffset;\n\tvec2 uv = getCubemapFaceCoordinates(dir, faceIndex, tileOffset);\n\tfloat atlasFaceSize = omniAtlasViewport.z;\n\tfloat tileSize = shadowTextureResolution * atlasFaceSize;\n\tfloat offset = shadowEdgePixels / tileSize;\n\tuv = uv * vec2(1.0 - offset * 2.0) + vec2(offset * 1.0);\n\tuv *= atlasFaceSize;\n\tuv += tileOffset * atlasFaceSize;\n\tuv += omniAtlasViewport.xy;\n\treturn uv;\n}\n",clusteredLightPS:"\nuniform highp sampler2D clusterWorldTexture;\nuniform highp sampler2D lightsTexture8;\nuniform highp sampler2D lightsTextureFloat;\n#if defined(CLUSTER_COOKIES)\n\t#define CLUSTER_COOKIES_OR_SHADOWS\n#endif\n#if defined(CLUSTER_SHADOWS)\n\t#define CLUSTER_COOKIES_OR_SHADOWS\n#endif\n#ifdef CLUSTER_SHADOWS\n\t#ifdef GL2\n\t\tuniform sampler2DShadow shadowAtlasTexture;\n\t#else\n\t\tuniform sampler2D shadowAtlasTexture;\n\t#endif\n#endif\n#ifdef CLUSTER_COOKIES\n\tuniform sampler2D cookieAtlasTexture;\n#endif\n#ifdef GL2\n\tuniform int clusterMaxCells;\n#else\n\tuniform float clusterMaxCells;\n\tuniform vec4 lightsTextureInvSize;\n#endif\nuniform float clusterSkip;\nuniform vec3 clusterCellsCountByBoundsSize;\nuniform vec3 clusterTextureSize;\nuniform vec3 clusterBoundsMin;\nuniform vec3 clusterBoundsDelta;\nuniform vec3 clusterCellsDot;\nuniform vec3 clusterCellsMax;\nuniform vec2 clusterCompressionLimit0;\nuniform vec2 shadowAtlasParams;\nstruct ClusterLightData {\n\tvec3 halfWidth;\n\tfloat lightType;\n\tvec3 halfHeight;\n\t#ifdef GL2\n\t\tint lightIndex;\n\t#else\n\t\tfloat lightV;\n\t#endif\n\tvec3 position;\n\tfloat shape;\n\tvec3 direction;\n\tfloat falloffMode;\n\tvec3 color;\n\tfloat shadowIntensity;\n\tvec3 omniAtlasViewport;\n\tfloat range;\n\tvec4 cookieChannelMask;\n\tfloat shadowBias;\n\tfloat shadowNormalBias;\n\tfloat innerConeAngleCos;\n\tfloat outerConeAngleCos;\n\tfloat cookie;\n\tfloat cookieRgb;\n\tfloat cookieIntensity;\n\tfloat mask;\n};\nmat4 lightProjectionMatrix;\n#define isClusteredLightCastShadow(light) ( light.shadowIntensity > 0.0 )\n#define isClusteredLightCookie(light) (light.cookie > 0.5 )\n#define isClusteredLightCookieRgb(light) (light.cookieRgb > 0.5 )\n#define isClusteredLightSpot(light) ( light.lightType > 0.5 )\n#define isClusteredLightFalloffLinear(light) ( light.falloffMode < 0.5 )\n#define isClusteredLightArea(light) ( light.shape > 0.1 )\n#define isClusteredLightRect(light) ( light.shape < 0.3 )\n#define isClusteredLightDisk(light) ( light.shape < 0.6 )\n#ifdef CLUSTER_MESH_DYNAMIC_LIGHTS\n\t#define acceptLightMask(light) ( light.mask < 0.75)\n#else\n\t#define acceptLightMask(light) ( light.mask > 0.25)\n#endif\nvec4 decodeClusterLowRange4Vec4(vec4 d0, vec4 d1, vec4 d2, vec4 d3) {\n\treturn vec4(\n\t\tbytes2floatRange4(d0, -2.0, 2.0),\n\t\tbytes2floatRange4(d1, -2.0, 2.0),\n\t\tbytes2floatRange4(d2, -2.0, 2.0),\n\t\tbytes2floatRange4(d3, -2.0, 2.0)\n\t);\n}\n#ifdef GL2\n\tvec4 sampleLightsTexture8(const ClusterLightData clusterLightData, int index) {\n\t\treturn texelFetch(lightsTexture8, ivec2(index, clusterLightData.lightIndex), 0);\n\t}\n\tvec4 sampleLightTextureF(const ClusterLightData clusterLightData, int index) {\n\t\treturn texelFetch(lightsTextureFloat, ivec2(index, clusterLightData.lightIndex), 0);\n\t}\n#else\n\tvec4 sampleLightsTexture8(const ClusterLightData clusterLightData, float index) {\n\t\treturn texture2DLodEXT(lightsTexture8, vec2(index * lightsTextureInvSize.z, clusterLightData.lightV), 0.0);\n\t}\n\tvec4 sampleLightTextureF(const ClusterLightData clusterLightData, float index) {\n\t\treturn texture2DLodEXT(lightsTextureFloat, vec2(index * lightsTextureInvSize.x, clusterLightData.lightV), 0.0);\n\t}\n#endif\nvoid decodeClusterLightCore(inout ClusterLightData clusterLightData, float lightIndex) {\n\t#ifdef GL2\n\t\tclusterLightData.lightIndex = int(lightIndex);\n\t#else\n\t\tclusterLightData.lightV = (lightIndex + 0.5) * lightsTextureInvSize.w;\n\t#endif\n\tvec4 lightInfo = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_FLAGS);\n\tclusterLightData.lightType = lightInfo.x;\n\tclusterLightData.shape = lightInfo.y;\n\tclusterLightData.falloffMode = lightInfo.z;\n\tclusterLightData.shadowIntensity = lightInfo.w;\n\tvec4 colorA = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COLOR_A);\n\tvec4 colorB = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COLOR_B);\n\tclusterLightData.color = vec3(bytes2float2(colorA.xy), bytes2float2(colorA.zw), bytes2float2(colorB.xy)) * clusterCompressionLimit0.y;\n\tclusterLightData.cookie = colorB.z;\n\tclusterLightData.mask = colorB.w;\n\t#ifdef CLUSTER_TEXTURE_FLOAT\n\t\tvec4 lightPosRange = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_POSITION_RANGE);\n\t\tclusterLightData.position = lightPosRange.xyz;\n\t\tclusterLightData.range = lightPosRange.w;\n\t\tvec4 lightDir_Unused = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_SPOT_DIRECTION);\n\t\tclusterLightData.direction = lightDir_Unused.xyz;\n\t#else\n\t\tvec4 encPosX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_POSITION_X);\n\t\tvec4 encPosY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_POSITION_Y);\n\t\tvec4 encPosZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_POSITION_Z);\n\t\tclusterLightData.position = vec3(bytes2float4(encPosX), bytes2float4(encPosY), bytes2float4(encPosZ)) * clusterBoundsDelta + clusterBoundsMin;\n\t\tvec4 encRange = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_RANGE);\n\t\tclusterLightData.range = bytes2float4(encRange) * clusterCompressionLimit0.x;\n\t\tvec4 encDirX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_DIRECTION_X);\n\t\tvec4 encDirY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_DIRECTION_Y);\n\t\tvec4 encDirZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_DIRECTION_Z);\n\t\tclusterLightData.direction = vec3(bytes2float4(encDirX), bytes2float4(encDirY), bytes2float4(encDirZ)) * 2.0 - 1.0;\n\t#endif\n}\nvoid decodeClusterLightSpot(inout ClusterLightData clusterLightData) {\n\tvec4 coneAngle = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_ANGLES);\n\tclusterLightData.innerConeAngleCos = bytes2float2(coneAngle.xy) * 2.0 - 1.0;\n\tclusterLightData.outerConeAngleCos = bytes2float2(coneAngle.zw) * 2.0 - 1.0;\n}\nvoid decodeClusterLightOmniAtlasViewport(inout ClusterLightData clusterLightData) {\n\t#ifdef CLUSTER_TEXTURE_FLOAT\n\t\tclusterLightData.omniAtlasViewport = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_0).xyz;\n\t#else\n\t\tvec4 viewportA = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_ATLAS_VIEWPORT_A);\n\t\tvec4 viewportB = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_ATLAS_VIEWPORT_B);\n\t\tclusterLightData.omniAtlasViewport = vec3(bytes2float2(viewportA.xy), bytes2float2(viewportA.zw), bytes2float2(viewportB.xy));\n\t#endif\n}\nvoid decodeClusterLightAreaData(inout ClusterLightData clusterLightData) {\n\t#ifdef CLUSTER_TEXTURE_FLOAT\n\t\tclusterLightData.halfWidth = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_AREA_DATA_WIDTH).xyz;\n\t\tclusterLightData.halfHeight = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_AREA_DATA_HEIGHT).xyz;\n\t#else\n\t\tvec4 areaWidthX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_WIDTH_X);\n\t\tvec4 areaWidthY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_WIDTH_Y);\n\t\tvec4 areaWidthZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_WIDTH_Z);\n\t\tclusterLightData.halfWidth = vec3(mantissaExponent2Float(areaWidthX), mantissaExponent2Float(areaWidthY), mantissaExponent2Float(areaWidthZ));\n\t\tvec4 areaHeightX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_HEIGHT_X);\n\t\tvec4 areaHeightY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_HEIGHT_Y);\n\t\tvec4 areaHeightZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_HEIGHT_Z);\n\t\tclusterLightData.halfHeight = vec3(mantissaExponent2Float(areaHeightX), mantissaExponent2Float(areaHeightY), mantissaExponent2Float(areaHeightZ));\n\t#endif\n}\nvoid decodeClusterLightProjectionMatrixData(inout ClusterLightData clusterLightData) {\n\t\n\t#ifdef CLUSTER_TEXTURE_FLOAT\n\t\tvec4 m0 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_0);\n\t\tvec4 m1 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_1);\n\t\tvec4 m2 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_2);\n\t\tvec4 m3 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_3);\n\t#else\n\t\tvec4 m00 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_00);\n\t\tvec4 m01 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_01);\n\t\tvec4 m02 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_02);\n\t\tvec4 m03 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_03);\n\t\tvec4 m0 = decodeClusterLowRange4Vec4(m00, m01, m02, m03);\n\t\tvec4 m10 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_10);\n\t\tvec4 m11 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_11);\n\t\tvec4 m12 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_12);\n\t\tvec4 m13 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_13);\n\t\tvec4 m1 = decodeClusterLowRange4Vec4(m10, m11, m12, m13);\n\t\tvec4 m20 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_20);\n\t\tvec4 m21 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_21);\n\t\tvec4 m22 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_22);\n\t\tvec4 m23 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_23);\n\t\tvec4 m2 = decodeClusterLowRange4Vec4(m20, m21, m22, m23);\n\t\tvec4 m30 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_30);\n\t\tvec4 m31 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_31);\n\t\tvec4 m32 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_32);\n\t\tvec4 m33 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_33);\n\t\tvec4 m3 = vec4(mantissaExponent2Float(m30), mantissaExponent2Float(m31), mantissaExponent2Float(m32), mantissaExponent2Float(m33));\n\t#endif\n\t\n\tlightProjectionMatrix = mat4(m0, m1, m2, m3);\n}\nvoid decodeClusterLightShadowData(inout ClusterLightData clusterLightData) {\n\t\n\tvec4 biases = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SHADOW_BIAS);\n\tclusterLightData.shadowBias = bytes2floatRange2(biases.xy, -1.0, 20.0),\n\tclusterLightData.shadowNormalBias = bytes2float2(biases.zw);\n}\nvoid decodeClusterLightCookieData(inout ClusterLightData clusterLightData) {\n\tvec4 cookieA = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COOKIE_A);\n\tclusterLightData.cookieIntensity = cookieA.x;\n\tclusterLightData.cookieRgb = cookieA.y;\n\tclusterLightData.cookieChannelMask = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COOKIE_B);\n}\nvoid evaluateLight(\n\tClusterLightData light, \n\tvec3 worldNormal, \n\tvec3 viewDir, \n\tvec3 reflectionDir,\n#if defined(LIT_CLEARCOAT)\n\tvec3 clearcoatReflectionDir,\n#endif\n\tfloat gloss, \n\tvec3 specularity, \n\tvec3 geometricNormal, \n\tmat3 tbn, \n#if defined(LIT_IRIDESCENCE)\n\tvec3 iridescenceFresnel,\n#endif\n\tvec3 clearcoat_worldNormal,\n\tfloat clearcoat_gloss,\n\tfloat sheen_gloss,\n\tfloat iridescence_intensity\n) {\n\tvec3 cookieAttenuation = vec3(1.0);\n\tfloat diffuseAttenuation = 1.0;\n\tfloat falloffAttenuation = 1.0;\n\tgetLightDirPoint(light.position);\n\t#ifdef CLUSTER_AREALIGHTS\n\tif (isClusteredLightArea(light)) {\n\t\tdecodeClusterLightAreaData(light);\n\t\tif (isClusteredLightRect(light)) {\n\t\t\tcalcRectLightValues(light.position, light.halfWidth, light.halfHeight);\n\t\t} else if (isClusteredLightDisk(light)) {\n\t\t\tcalcDiskLightValues(light.position, light.halfWidth, light.halfHeight);\n\t\t} else {\n\t\t\tcalcSphereLightValues(light.position, light.halfWidth, light.halfHeight);\n\t\t}\n\t\tfalloffAttenuation = getFalloffWindow(light.range, dLightDirW);\n\t} else\n\t#endif\n\t{\n\t\tif (isClusteredLightFalloffLinear(light))\n\t\t\tfalloffAttenuation = getFalloffLinear(light.range, dLightDirW);\n\t\telse\n\t\t\tfalloffAttenuation = getFalloffInvSquared(light.range, dLightDirW);\n\t}\n\tif (falloffAttenuation > 0.00001) {\n\t\t#ifdef CLUSTER_AREALIGHTS\n\t\tif (isClusteredLightArea(light)) {\n\t\t\tif (isClusteredLightRect(light)) {\n\t\t\t\tdiffuseAttenuation = getRectLightDiffuse(worldNormal, viewDir, dLightDirW, dLightDirNormW) * 16.0;\n\t\t\t} else if (isClusteredLightDisk(light)) {\n\t\t\t\tdiffuseAttenuation = getDiskLightDiffuse(worldNormal, viewDir, dLightDirW, dLightDirNormW) * 16.0;\n\t\t\t} else {\n\t\t\t\tdiffuseAttenuation = getSphereLightDiffuse(worldNormal, viewDir, dLightDirW, dLightDirNormW) * 16.0;\n\t\t\t}\n\t\t} else\n\t\t#endif\n\t\t{\n\t\t\tfalloffAttenuation *= getLightDiffuse(worldNormal, viewDir, dLightDirW, dLightDirNormW); \n\t\t}\n\t\tif (isClusteredLightSpot(light)) {\n\t\t\tdecodeClusterLightSpot(light);\n\t\t\tfalloffAttenuation *= getSpotEffect(light.direction, light.innerConeAngleCos, light.outerConeAngleCos, dLightDirNormW);\n\t\t}\n\t\t#if defined(CLUSTER_COOKIES_OR_SHADOWS)\n\t\tif (falloffAttenuation > 0.00001) {\n\t\t\tif (isClusteredLightCastShadow(light) || isClusteredLightCookie(light)) {\n\t\t\t\tif (isClusteredLightSpot(light)) {\n\t\t\t\t\tdecodeClusterLightProjectionMatrixData(light);\n\t\t\t\t} else {\n\t\t\t\t\tdecodeClusterLightOmniAtlasViewport(light);\n\t\t\t\t}\n\t\t\t\tfloat shadowTextureResolution = shadowAtlasParams.x;\n\t\t\t\tfloat shadowEdgePixels = shadowAtlasParams.y;\n\t\t\t\t#ifdef CLUSTER_COOKIES\n\t\t\t\tif (isClusteredLightCookie(light)) {\n\t\t\t\t\tdecodeClusterLightCookieData(light);\n\t\t\t\t\tif (isClusteredLightSpot(light)) {\n\t\t\t\t\t\tcookieAttenuation = getCookie2DClustered(TEXTURE_PASS(cookieAtlasTexture), lightProjectionMatrix, vPositionW, light.cookieIntensity, isClusteredLightCookieRgb(light), light.cookieChannelMask);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcookieAttenuation = getCookieCubeClustered(TEXTURE_PASS(cookieAtlasTexture), dLightDirW, light.cookieIntensity, isClusteredLightCookieRgb(light), light.cookieChannelMask, shadowTextureResolution, shadowEdgePixels, light.omniAtlasViewport);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t#endif\n\t\t\t\t#ifdef CLUSTER_SHADOWS\n\t\t\t\tif (isClusteredLightCastShadow(light)) {\n\t\t\t\t\tdecodeClusterLightShadowData(light);\n\t\t\t\t\tvec4 shadowParams = vec4(shadowTextureResolution, light.shadowNormalBias, light.shadowBias, 1.0 / light.range);\n\t\t\t\t\tif (isClusteredLightSpot(light)) {\n\t\t\t\t\t\tgetShadowCoordPerspZbufferNormalOffset(lightProjectionMatrix, shadowParams, geometricNormal);\n\t\t\t\t\t\t\n\t\t\t\t\t\t#if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\t\t\t\t\t\t\tfloat shadow = getShadowSpotClusteredPCF1(SHADOWMAP_PASS(shadowAtlasTexture), dShadowCoord, shadowParams);\n\t\t\t\t\t\t#elif defined(CLUSTER_SHADOW_TYPE_PCF3)\n\t\t\t\t\t\t\tfloat shadow = getShadowSpotClusteredPCF3(SHADOWMAP_PASS(shadowAtlasTexture), dShadowCoord, shadowParams);\n\t\t\t\t\t\t#elif defined(CLUSTER_SHADOW_TYPE_PCF5)\n\t\t\t\t\t\t\tfloat shadow = getShadowSpotClusteredPCF5(SHADOWMAP_PASS(shadowAtlasTexture), dShadowCoord, shadowParams);\n\t\t\t\t\t\t#elif defined(CLUSTER_SHADOW_TYPE_PCSS)\n\t\t\t\t\t\t\tfloat shadow = getShadowSpotClusteredPCSS(SHADOWMAP_PASS(shadowAtlasTexture), dShadowCoord, shadowParams);\n\t\t\t\t\t\t#endif\n\t\t\t\t\t\tfalloffAttenuation *= mix(1.0, shadow, light.shadowIntensity);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvec3 dir = normalOffsetPointShadow(shadowParams, dLightPosW, dLightDirW, dLightDirNormW, geometricNormal);\n\t\t\t\t\t\t#if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\t\t\t\t\t\t\tfloat shadow = getShadowOmniClusteredPCF1(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir);\n\t\t\t\t\t\t#elif defined(CLUSTER_SHADOW_TYPE_PCF3)\n\t\t\t\t\t\t\tfloat shadow = getShadowOmniClusteredPCF3(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir);\n\t\t\t\t\t\t#elif defined(CLUSTER_SHADOW_TYPE_PCF5)\n\t\t\t\t\t\t\tfloat shadow = getShadowOmniClusteredPCF5(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir);\n\t\t\t\t\t\t#endif\n\t\t\t\t\t\tfalloffAttenuation *= mix(1.0, shadow, light.shadowIntensity);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t#endif\n\t\t\t}\n\t\t}\n\t\t#endif\n\t\t#ifdef CLUSTER_AREALIGHTS\n\t\tif (isClusteredLightArea(light)) {\n\t\t\t{\n\t\t\t\tvec3 areaDiffuse = (diffuseAttenuation * falloffAttenuation) * light.color * cookieAttenuation;\n\t\t\t\t#if defined(LIT_SPECULAR)\n\t\t\t\t\t#if defined(LIT_CONSERVE_ENERGY)\n\t\t\t\t\t\tareaDiffuse = mix(areaDiffuse, vec3(0), dLTCSpecFres);\n\t\t\t\t\t#endif\n\t\t\t\t#endif\n\t\t\t\tdDiffuseLight += areaDiffuse;\n\t\t\t}\n\t\t\t#ifdef LIT_SPECULAR\n\t\t\t\tfloat areaLightSpecular;\n\t\t\t\tif (isClusteredLightRect(light)) {\n\t\t\t\t\tareaLightSpecular = getRectLightSpecular(worldNormal, viewDir);\n\t\t\t\t} else if (isClusteredLightDisk(light)) {\n\t\t\t\t\tareaLightSpecular = getDiskLightSpecular(worldNormal, viewDir);\n\t\t\t\t} else {\n\t\t\t\t\tareaLightSpecular = getSphereLightSpecular(worldNormal, viewDir);\n\t\t\t\t}\n\t\t\t\tdSpecularLight += dLTCSpecFres * areaLightSpecular * falloffAttenuation * light.color * cookieAttenuation;\n\t\t\t\t#ifdef LIT_CLEARCOAT\n\t\t\t\t\tfloat areaLightSpecularCC;\n\t\t\t\t\tif (isClusteredLightRect(light)) {\n\t\t\t\t\t\tareaLightSpecularCC = getRectLightSpecular(clearcoat_worldNormal, viewDir);\n\t\t\t\t\t} else if (isClusteredLightDisk(light)) {\n\t\t\t\t\t\tareaLightSpecularCC = getDiskLightSpecular(clearcoat_worldNormal, viewDir);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tareaLightSpecularCC = getSphereLightSpecular(clearcoat_worldNormal, viewDir);\n\t\t\t\t\t}\n\t\t\t\t\tccSpecularLight += ccLTCSpecFres * areaLightSpecularCC * falloffAttenuation * light.color * cookieAttenuation;\n\t\t\t\t#endif\n\t\t\t#endif\n\t\t} else\n\t\t#endif\n\t\t{\n\t\t\t{\n\t\t\t\tvec3 punctualDiffuse = falloffAttenuation * light.color * cookieAttenuation;\n\t\t\t\t#if defined(CLUSTER_AREALIGHTS)\n\t\t\t\t#if defined(LIT_SPECULAR)\n\t\t\t\t#if defined(LIT_CONSERVE_ENERGY)\n\t\t\t\t\tpunctualDiffuse = mix(punctualDiffuse, vec3(0), specularity);\n\t\t\t\t#endif\n\t\t\t\t#endif\n\t\t\t\t#endif\n\t\t\t\tdDiffuseLight += punctualDiffuse;\n\t\t\t}\n \n\t\t\t#ifdef LIT_SPECULAR\n\t\t\t\tvec3 halfDir = normalize(-dLightDirNormW + viewDir);\n\t\t\t\t\n\t\t\t\t#ifdef LIT_SPECULAR_FRESNEL\n\t\t\t\t\tdSpecularLight += \n\t\t\t\t\t\tgetLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, dLightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * \n\t\t\t\t\t\tgetFresnel(\n\t\t\t\t\t\t\tdot(viewDir, halfDir), \n\t\t\t\t\t\t\tgloss, \n\t\t\t\t\t\t\tspecularity\n\t\t\t\t\t\t#if defined(LIT_IRIDESCENCE)\n\t\t\t\t\t\t\t, iridescenceFresnel,\n\t\t\t\t\t\t\tiridescence_intensity\n\t\t\t\t\t\t#endif\n\t\t\t\t\t\t\t);\n\t\t\t\t#else\n\t\t\t\t\tdSpecularLight += getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, dLightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * specularity;\n\t\t\t\t#endif\n\t\t\t\t#ifdef LIT_CLEARCOAT\n\t\t\t\t\t#ifdef LIT_SPECULAR_FRESNEL\n\t\t\t\t\t\tccSpecularLight += getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, dLightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * getFresnelCC(dot(viewDir, halfDir));\n\t\t\t\t\t#else\n\t\t\t\t\t\tccSpecularLight += getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, dLightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation; \n\t\t\t\t\t#endif\n\t\t\t\t#endif\n\t\t\t\t#ifdef LIT_SHEEN\n\t\t\t\t\tsSpecularLight += getLightSpecularSheen(halfDir, worldNormal, viewDir, dLightDirNormW, sheen_gloss) * falloffAttenuation * light.color * cookieAttenuation;\n\t\t\t\t#endif\n\t\t\t#endif\n\t\t}\n\t}\n\tdAtten = falloffAttenuation;\n\tdAttenD = diffuseAttenuation;\n\tdAtten3 = cookieAttenuation;\n}\nvoid evaluateClusterLight(\n\tfloat lightIndex, \n\tvec3 worldNormal, \n\tvec3 viewDir, \n\tvec3 reflectionDir, \n#if defined(LIT_CLEARCOAT)\n\tvec3 clearcoatReflectionDir,\n#endif\n\tfloat gloss, \n\tvec3 specularity, \n\tvec3 geometricNormal, \n\tmat3 tbn, \n#if defined(LIT_IRIDESCENCE)\n\tvec3 iridescenceFresnel,\n#endif\n\tvec3 clearcoat_worldNormal,\n\tfloat clearcoat_gloss,\n\tfloat sheen_gloss,\n\tfloat iridescence_intensity\n) {\n\tClusterLightData clusterLightData;\n\tdecodeClusterLightCore(clusterLightData, lightIndex);\n\tif (acceptLightMask(clusterLightData))\n\t\tevaluateLight(\n\t\t\tclusterLightData, \n\t\t\tworldNormal, \n\t\t\tviewDir, \n\t\t\treflectionDir, \n#if defined(LIT_CLEARCOAT)\n\t\t\tclearcoatReflectionDir, \n#endif\n\t\t\tgloss, \n\t\t\tspecularity, \n\t\t\tgeometricNormal, \n\t\t\ttbn, \n#if defined(LIT_IRIDESCENCE)\n\t\t\tiridescenceFresnel,\n#endif\n\t\t\tclearcoat_worldNormal,\n\t\t\tclearcoat_gloss,\n\t\t\tsheen_gloss,\n\t\t\tiridescence_intensity\n\t\t);\n}\nvoid addClusteredLights(\n\tvec3 worldNormal, \n\tvec3 viewDir, \n\tvec3 reflectionDir, \n#if defined(LIT_CLEARCOAT)\n\tvec3 clearcoatReflectionDir,\n#endif\n\tfloat gloss, \n\tvec3 specularity, \n\tvec3 geometricNormal, \n\tmat3 tbn, \n#if defined(LIT_IRIDESCENCE)\n\tvec3 iridescenceFresnel,\n#endif\n\tvec3 clearcoat_worldNormal,\n\tfloat clearcoat_gloss,\n\tfloat sheen_gloss,\n\tfloat iridescence_intensity\n) {\n\tif (clusterSkip > 0.5)\n\t\treturn;\n\tvec3 cellCoords = floor((vPositionW - clusterBoundsMin) * clusterCellsCountByBoundsSize);\n\tif (!(any(lessThan(cellCoords, vec3(0.0))) || any(greaterThanEqual(cellCoords, clusterCellsMax)))) {\n\t\tfloat cellIndex = dot(clusterCellsDot, cellCoords);\n\t\tfloat clusterV = floor(cellIndex * clusterTextureSize.y);\n\t\tfloat clusterU = cellIndex - (clusterV * clusterTextureSize.x);\n\t\t#ifdef GL2\n\t\t\tfor (int lightCellIndex = 0; lightCellIndex < clusterMaxCells; lightCellIndex++) {\n\t\t\t\tfloat lightIndex = texelFetch(clusterWorldTexture, ivec2(int(clusterU) + lightCellIndex, clusterV), 0).x;\n\t\t\t\tif (lightIndex <= 0.0)\n\t\t\t\t\t\treturn;\n\t\t\t\tevaluateClusterLight(\n\t\t\t\t\tlightIndex * 255.0, \n\t\t\t\t\tworldNormal, \n\t\t\t\t\tviewDir, \n\t\t\t\t\treflectionDir,\n#if defined(LIT_CLEARCOAT)\n\t\t\t\t\tclearcoatReflectionDir,\n#endif\n\t\t\t\t\tgloss, \n\t\t\t\t\tspecularity, \n\t\t\t\t\tgeometricNormal, \n\t\t\t\t\ttbn, \n#if defined(LIT_IRIDESCENCE)\n\t\t\t\t\tiridescenceFresnel,\n#endif\n\t\t\t\t\tclearcoat_worldNormal,\n\t\t\t\t\tclearcoat_gloss,\n\t\t\t\t\tsheen_gloss,\n\t\t\t\t\tiridescence_intensity\n\t\t\t\t); \n\t\t\t}\n\t\t#else\n\t\t\tclusterV = (clusterV + 0.5) * clusterTextureSize.z;\n\t\t\tconst float maxLightCells = 256.0;\n\t\t\tfor (float lightCellIndex = 0.5; lightCellIndex < maxLightCells; lightCellIndex++) {\n\t\t\t\tfloat lightIndex = texture2DLodEXT(clusterWorldTexture, vec2(clusterTextureSize.y * (clusterU + lightCellIndex), clusterV), 0.0).x;\n\t\t\t\tif (lightIndex <= 0.0)\n\t\t\t\t\treturn;\n\t\t\t\t\n\t\t\t\tevaluateClusterLight(\n\t\t\t\t\tlightIndex * 255.0, \n\t\t\t\t\tworldNormal, \n\t\t\t\t\tviewDir, \n\t\t\t\t\treflectionDir,\n#if defined(LIT_CLEARCOAT)\n\t\t\t\t\tclearcoatReflectionDir,\n#endif\n\t\t\t\t\tgloss, \n\t\t\t\t\tspecularity, \n\t\t\t\t\tgeometricNormal, \n\t\t\t\t\ttbn, \n#if defined(LIT_IRIDESCENCE)\n\t\t\t\t\tiridescenceFresnel,\n#endif\n\t\t\t\t\tclearcoat_worldNormal,\n\t\t\t\t\tclearcoat_gloss,\n\t\t\t\t\tsheen_gloss,\n\t\t\t\t\tiridescence_intensity\n\t\t\t\t); \n\t\t\t\tif (lightCellIndex >= clusterMaxCells) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t#endif\n\t}\n}\n",combinePS:"\nvec3 combineColor(vec3 albedo, vec3 sheenSpecularity, float clearcoatSpecularity) {\n\tvec3 ret = vec3(0);\n#ifdef LIT_OLD_AMBIENT\n\tret += (dDiffuseLight - light_globalAmbient) * albedo + material_ambient * light_globalAmbient;\n#else\n\tret += albedo * dDiffuseLight;\n#endif\n#ifdef LIT_SPECULAR\n\tret += dSpecularLight;\n#endif\n#ifdef LIT_REFLECTIONS\n\tret += dReflection.rgb * dReflection.a;\n#endif\n#ifdef LIT_SHEEN\n\tfloat sheenScaling = 1.0 - max(max(sheenSpecularity.r, sheenSpecularity.g), sheenSpecularity.b) * 0.157;\n\tret = ret * sheenScaling + (sSpecularLight + sReflection.rgb) * sheenSpecularity;\n#endif\n#ifdef LIT_CLEARCOAT\n\tfloat clearCoatScaling = 1.0 - ccFresnel * clearcoatSpecularity;\n\tret = ret * clearCoatScaling + (ccSpecularLight + ccReflection.rgb) * clearcoatSpecularity;\n#endif\n\treturn ret;\n}\n",cookiePS:"\nvec4 getCookie2D(sampler2D tex, mat4 transform, float intensity) {\n\tvec4 projPos = transform * vec4(vPositionW, 1.0);\n\tprojPos.xy /= projPos.w;\n\treturn mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);\n}\nvec4 getCookie2DClip(sampler2D tex, mat4 transform, float intensity) {\n\tvec4 projPos = transform * vec4(vPositionW, 1.0);\n\tprojPos.xy /= projPos.w;\n\tif (projPos.x < 0.0 || projPos.x > 1.0 || projPos.y < 0.0 || projPos.y > 1.0 || projPos.z < 0.0) return vec4(0.0);\n\treturn mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);\n}\nvec4 getCookie2DXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {\n\tvec4 projPos = transform * vec4(vPositionW, 1.0);\n\tprojPos.xy /= projPos.w;\n\tprojPos.xy += cookieOffset;\n\tvec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);\n\treturn mix(vec4(1.0), texture2D(tex, uv), intensity);\n}\nvec4 getCookie2DClipXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {\n\tvec4 projPos = transform * vec4(vPositionW, 1.0);\n\tprojPos.xy /= projPos.w;\n\tprojPos.xy += cookieOffset;\n\tif (projPos.x < 0.0 || projPos.x > 1.0 || projPos.y < 0.0 || projPos.y > 1.0 || projPos.z < 0.0) return vec4(0.0);\n\tvec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);\n\treturn mix(vec4(1.0), texture2D(tex, uv), intensity);\n}\nvec4 getCookieCube(samplerCube tex, mat4 transform, float intensity) {\n\treturn mix(vec4(1.0), textureCube(tex, dLightDirNormW * mat3(transform)), intensity);\n}\n",cubeMapProjectBoxPS:"\nuniform vec3 envBoxMin;\nuniform vec3 envBoxMax;\nvec3 cubeMapProject(vec3 nrdir) {\n\tnrdir = cubeMapRotate(nrdir);\n\tvec3 rbmax = (envBoxMax - vPositionW) / nrdir;\n\tvec3 rbmin = (envBoxMin - vPositionW) / nrdir;\n\tvec3 rbminmax;\n\trbminmax.x = nrdir.x>0.0? rbmax.x : rbmin.x;\n\trbminmax.y = nrdir.y>0.0? rbmax.y : rbmin.y;\n\trbminmax.z = nrdir.z>0.0? rbmax.z : rbmin.z;\n\tfloat fa = min(min(rbminmax.x, rbminmax.y), rbminmax.z);\n\tvec3 posonbox = vPositionW + nrdir * fa;\n\tvec3 envBoxPos = (envBoxMin + envBoxMax) * 0.5;\n\treturn normalize(posonbox - envBoxPos);\n}\n",cubeMapProjectNonePS:"\nvec3 cubeMapProject(vec3 dir) {\n\treturn cubeMapRotate(dir);\n}\n",cubeMapRotatePS:"\n#ifdef CUBEMAP_ROTATION\nuniform mat3 cubeMapRotationMatrix;\n#endif\nvec3 cubeMapRotate(vec3 refDir) {\n#ifdef CUBEMAP_ROTATION\n\treturn refDir * cubeMapRotationMatrix;\n#else\n\treturn refDir;\n#endif\n}\n",debugOutputPS:"\n#ifdef DEBUG_ALBEDO_PASS\ngl_FragColor = vec4(gammaCorrectOutput(litArgs_albedo), 1.0);\n#endif\n#ifdef DEBUG_UV0_PASS\ngl_FragColor = vec4(litArgs_albedo , 1.0);\n#endif\n#ifdef DEBUG_WORLD_NORMAL_PASS\ngl_FragColor = vec4(litArgs_worldNormal * 0.5 + 0.5, 1.0);\n#endif\n#ifdef DEBUG_OPACITY_PASS\ngl_FragColor = vec4(vec3(litArgs_opacity) , 1.0);\n#endif\n#ifdef DEBUG_SPECULARITY_PASS\ngl_FragColor = vec4(litArgs_specularity, 1.0);\n#endif\n#ifdef DEBUG_GLOSS_PASS\ngl_FragColor = vec4(vec3(litArgs_gloss) , 1.0);\n#endif\n#ifdef DEBUG_METALNESS_PASS\ngl_FragColor = vec4(vec3(litArgs_metalness) , 1.0);\n#endif\n#ifdef DEBUG_AO_PASS\ngl_FragColor = vec4(vec3(litArgs_ao) , 1.0);\n#endif\n#ifdef DEBUG_EMISSION_PASS\ngl_FragColor = vec4(gammaCorrectOutput(litArgs_emission), 1.0);\n#endif\n",debugProcessFrontendPS:"\n#ifdef DEBUG_LIGHTING_PASS\nlitArgs_albedo = vec3(0.5);\n#endif\n#ifdef DEBUG_UV0_PASS\n#ifdef VARYING_VUV0\nlitArgs_albedo = vec3(vUv0, 0);\n#else\nlitArgs_albedo = vec3(0);\n#endif\n#endif\n",detailModesPS:"\nvec3 detailMode_mul(vec3 c1, vec3 c2) {\n\treturn c1 * c2;\n}\nvec3 detailMode_add(vec3 c1, vec3 c2) {\n\treturn c1 + c2;\n}\nvec3 detailMode_screen(vec3 c1, vec3 c2) {\n\treturn 1.0 - (1.0 - c1)*(1.0 - c2);\n}\nvec3 detailMode_overlay(vec3 c1, vec3 c2) {\n\treturn mix(1.0 - 2.0*(1.0 - c1)*(1.0 - c2), 2.0*c1*c2, step(c1, vec3(0.5)));\n}\nvec3 detailMode_min(vec3 c1, vec3 c2) {\n\treturn min(c1, c2);\n}\nvec3 detailMode_max(vec3 c1, vec3 c2) {\n\treturn max(c1, c2);\n}\n",diffusePS:"\n#ifdef MAPCOLOR\nuniform vec3 material_diffuse;\n#endif\nvoid getAlbedo() {\n\tdAlbedo = vec3(1.0);\n#ifdef MAPCOLOR\n\tdAlbedo *= material_diffuse.rgb;\n#endif\n#ifdef MAPTEXTURE\n\tvec3 albedoBase = $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n\tdAlbedo *= addAlbedoDetail(albedoBase);\n#endif\n#ifdef MAPVERTEX\n\tdAlbedo *= gammaCorrectInput(saturate(vVertexColor.$VC));\n#endif\n}\n",diffuseDetailMapPS:"\nvec3 addAlbedoDetail(vec3 albedo) {\n#ifdef MAPTEXTURE\n\tvec3 albedoDetail = $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n\treturn detailMode_$DETAILMODE(albedo, albedoDetail);\n#else\n\treturn albedo;\n#endif\n}\n",decodePS:po,emissivePS:"\n#ifdef MAPCOLOR\nuniform vec3 material_emissive;\n#endif\n#ifdef MAPFLOAT\nuniform float material_emissiveIntensity;\n#endif\nvoid getEmission() {\n\tdEmission = vec3(1.0);\n\t#ifdef MAPFLOAT\n\tdEmission *= material_emissiveIntensity;\n\t#endif\n\t#ifdef MAPCOLOR\n\tdEmission *= material_emissive;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tdEmission *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tdEmission *= gammaCorrectInput(saturate(vVertexColor.$VC));\n\t#endif\n}\n",encodePS:mo,endPS:"\n\tgl_FragColor.rgb = combineColor(litArgs_albedo, litArgs_sheen_specularity, litArgs_clearcoat_specularity);\n\tgl_FragColor.rgb += litArgs_emission;\n\tgl_FragColor.rgb = addFog(gl_FragColor.rgb);\n\t#ifndef HDR\n\tgl_FragColor.rgb = toneMap(gl_FragColor.rgb);\n\tgl_FragColor.rgb = gammaCorrectOutput(gl_FragColor.rgb);\n\t#endif\n",endVS:"\n",envAtlasPS:"\nconst float atlasSize = 512.0;\nconst float seamSize = 1.0 / atlasSize;\nvec2 mapUv(vec2 uv, vec4 rect) {\n\treturn vec2(mix(rect.x + seamSize, rect.x + rect.z - seamSize, uv.x),\n\t\t\t\tmix(rect.y + seamSize, rect.y + rect.w - seamSize, uv.y));\n}\nvec2 mapRoughnessUv(vec2 uv, float level) {\n\tfloat t = 1.0 / exp2(level);\n\treturn mapUv(uv, vec4(0, 1.0 - t, t, t * 0.5));\n}\nvec2 mapShinyUv(vec2 uv, float level) {\n\tfloat t = 1.0 / exp2(level);\n\treturn mapUv(uv, vec4(1.0 - t, 1.0 - t, t, t * 0.5));\n}\n",envConstPS:"\nvec3 processEnvironment(vec3 color) {\n\treturn color;\n}\n",envMultiplyPS:"\nuniform float skyboxIntensity;\nvec3 processEnvironment(vec3 color) {\n\treturn color * skyboxIntensity;\n}\n",extensionPS:"\n",extensionVS:"\n",falloffInvSquaredPS:"\nfloat getFalloffWindow(float lightRadius, vec3 lightDir) {\n\tfloat sqrDist = dot(lightDir, lightDir);\n\tfloat invRadius = 1.0 / lightRadius;\n\treturn square( saturate( 1.0 - square( sqrDist * square(invRadius) ) ) );\n}\nfloat getFalloffInvSquared(float lightRadius, vec3 lightDir) {\n\tfloat sqrDist = dot(lightDir, lightDir);\n\tfloat falloff = 1.0 / (sqrDist + 1.0);\n\tfloat invRadius = 1.0 / lightRadius;\n\tfalloff *= 16.0;\n\tfalloff *= square( saturate( 1.0 - square( sqrDist * square(invRadius) ) ) );\n\treturn falloff;\n}\n",falloffLinearPS:"\nfloat getFalloffLinear(float lightRadius, vec3 lightDir) {\n\tfloat d = length(lightDir);\n\treturn max(((lightRadius - d) / lightRadius), 0.0);\n}\n",fixCubemapSeamsNonePS:"\nvec3 fixSeams(vec3 vec, float mipmapIndex) {\n\treturn vec;\n}\nvec3 fixSeams(vec3 vec) {\n\treturn vec;\n}\nvec3 fixSeamsStatic(vec3 vec, float invRecMipSize) {\n\treturn vec;\n}\nvec3 calcSeam(vec3 vec) {\n\treturn vec3(0);\n}\nvec3 applySeam(vec3 vec, vec3 seam, float scale) {\n\treturn vec;\n}\n",fixCubemapSeamsStretchPS:"\nvec3 fixSeams(vec3 vec, float mipmapIndex) {\n\tvec3 avec = abs(vec);\n\tfloat scale = 1.0 - exp2(mipmapIndex) / 128.0;\n\tfloat M = max(max(avec.x, avec.y), avec.z);\n\tif (avec.x != M) vec.x *= scale;\n\tif (avec.y != M) vec.y *= scale;\n\tif (avec.z != M) vec.z *= scale;\n\treturn vec;\n}\nvec3 fixSeams(vec3 vec) {\n\tvec3 avec = abs(vec);\n\tfloat scale = 1.0 - 1.0 / 128.0;\n\tfloat M = max(max(avec.x, avec.y), avec.z);\n\tif (avec.x != M) vec.x *= scale;\n\tif (avec.y != M) vec.y *= scale;\n\tif (avec.z != M) vec.z *= scale;\n\treturn vec;\n}\nvec3 fixSeamsStatic(vec3 vec, float invRecMipSize) {\n\tvec3 avec = abs(vec);\n\tfloat scale = invRecMipSize;\n\tfloat M = max(max(avec.x, avec.y), avec.z);\n\tif (avec.x != M) vec.x *= scale;\n\tif (avec.y != M) vec.y *= scale;\n\tif (avec.z != M) vec.z *= scale;\n\treturn vec;\n}\nvec3 calcSeam(vec3 vec) {\n\tvec3 avec = abs(vec);\n\tfloat M = max(avec.x, max(avec.y, avec.z));\n\treturn vec3(avec.x != M ? 1.0 : 0.0,\n\t\t\t\tavec.y != M ? 1.0 : 0.0,\n\t\t\t\tavec.z != M ? 1.0 : 0.0);\n}\nvec3 applySeam(vec3 vec, vec3 seam, float scale) {\n\treturn vec * (seam * -scale + vec3(1.0));\n}\n",floatUnpackingPS:"\nfloat bytes2float2(vec2 data) {\n\treturn dot(data, vec2(1.0, 1.0 / 255.0));\n}\nfloat bytes2float3(vec3 data) {\n\treturn dot(data, vec3(1.0, 1.0 / 255.0, 1.0 / 65025.0));\n}\nfloat bytes2float4(vec4 data) {\n\treturn dot(data, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n}\nfloat bytes2floatRange2(vec2 data, float min, float max) {\n\treturn mix(min, max, bytes2float2(data));\n}\nfloat bytes2floatRange3(vec3 data, float min, float max) {\n\treturn mix(min, max, bytes2float3(data));\n}\nfloat bytes2floatRange4(vec4 data, float min, float max) {\n\treturn mix(min, max, bytes2float4(data));\n}\nfloat mantissaExponent2Float(vec4 pack)\n{\n\tfloat value = bytes2floatRange3(pack.xyz, -1.0, 1.0);\n\tfloat exponent = floor(pack.w * 255.0 - 127.0);\n\treturn value * exp2(exponent);\n}\n",fogExpPS:"\nuniform vec3 fog_color;\nuniform float fog_density;\nfloat dBlendModeFogFactor = 1.0;\nvec3 addFog(vec3 color) {\n\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\tfloat fogFactor = exp(-depth * fog_density);\n\tfogFactor = clamp(fogFactor, 0.0, 1.0);\n\treturn mix(fog_color * dBlendModeFogFactor, color, fogFactor);\n}\n",fogExp2PS:"\nuniform vec3 fog_color;\nuniform float fog_density;\nfloat dBlendModeFogFactor = 1.0;\nvec3 addFog(vec3 color) {\n\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\tfloat fogFactor = exp(-depth * depth * fog_density * fog_density);\n\tfogFactor = clamp(fogFactor, 0.0, 1.0);\n\treturn mix(fog_color * dBlendModeFogFactor, color, fogFactor);\n}\n",fogLinearPS:"\nuniform vec3 fog_color;\nuniform float fog_start;\nuniform float fog_end;\nfloat dBlendModeFogFactor = 1.0;\nvec3 addFog(vec3 color) {\n\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\tfloat fogFactor = (fog_end - depth) / (fog_end - fog_start);\n\tfogFactor = clamp(fogFactor, 0.0, 1.0);\n\treturn mix(fog_color * dBlendModeFogFactor, color, fogFactor);\n}\n",fogNonePS:"\nfloat dBlendModeFogFactor = 1.0;\nvec3 addFog(vec3 color) {\n\treturn color;\n}\n",fresnelSchlickPS:"\nvec3 getFresnel(\n\t\tfloat cosTheta, \n\t\tfloat gloss, \n\t\tvec3 specularity\n#if defined(LIT_IRIDESCENCE)\n\t\t, vec3 iridescenceFresnel, \n\t\tfloat iridescenceIntensity\n#endif\n\t) {\n\tfloat fresnel = pow(1.0 - max(cosTheta, 0.0), 5.0);\n\tfloat glossSq = gloss * gloss;\n\tvec3 ret = specularity + (max(vec3(glossSq), specularity) - specularity) * fresnel;\n#if defined(LIT_IRIDESCENCE)\n\treturn mix(ret, iridescenceFresnel, iridescenceIntensity);\n#else\n\treturn ret;\n#endif\t\n}\nfloat getFresnelCC(float cosTheta) {\n\tfloat fresnel = pow(1.0 - max(cosTheta, 0.0), 5.0);\n\treturn 0.04 + (1.0 - 0.04) * fresnel;\n}\n",fullscreenQuadPS:"\nvarying vec2 vUv0;\nuniform sampler2D source;\nvoid main(void) {\n\tgl_FragColor = texture2D(source, vUv0);\n}\n",fullscreenQuadVS:"\nattribute vec2 vertex_position;\nvarying vec2 vUv0;\nvoid main(void)\n{\n\tgl_Position = vec4(vertex_position, 0.5, 1.0);\n\tvUv0 = vertex_position.xy*0.5+0.5;\n}\n",gamma1_0PS:"\nfloat gammaCorrectInput(float color) {\n\treturn color;\n}\nvec3 gammaCorrectInput(vec3 color) {\n\treturn color;\n}\nvec4 gammaCorrectInput(vec4 color) {\n\treturn color;\n}\nvec3 gammaCorrectOutput(vec3 color) {\n\treturn color;\n}\n",gamma2_2PS:"\nfloat gammaCorrectInput(float color) {\n\treturn decodeGamma(color);\n}\nvec3 gammaCorrectInput(vec3 color) {\n\treturn decodeGamma(color);\n}\nvec4 gammaCorrectInput(vec4 color) {\n\treturn vec4(decodeGamma(color.xyz), color.w);\n}\nvec3 gammaCorrectOutput(vec3 color) {\n#ifdef HDR\n\treturn color;\n#else\n\treturn pow(color + 0.0000001, vec3(1.0 / 2.2));\n#endif\n}\n",gles2PS:Ks,gles3PS:Zs,gles3VS:Qs,glossPS:"\n#ifdef MAPFLOAT\nuniform float material_gloss;\n#endif\nvoid getGlossiness() {\n\tdGlossiness = 1.0;\n\t#ifdef MAPFLOAT\n\tdGlossiness *= material_gloss;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tdGlossiness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tdGlossiness *= saturate(vVertexColor.$VC);\n\t#endif\n\t#ifdef MAPINVERT\n\tdGlossiness = 1.0 - dGlossiness;\n\t#endif\n\tdGlossiness += 0.0000001;\n}\n",iridescenceDiffractionPS:"\nuniform float material_iridescenceRefractionIndex;\n#ifndef PI\n#define PI 3.14159265\n#endif\nfloat iridescence_iorToFresnel(float transmittedIor, float incidentIor) {\n\treturn pow((transmittedIor - incidentIor) / (transmittedIor + incidentIor), 2.0);\n}\nvec3 iridescence_iorToFresnel(vec3 transmittedIor, float incidentIor) {\n\treturn pow((transmittedIor - vec3(incidentIor)) / (transmittedIor + vec3(incidentIor)), vec3(2.0));\n}\nvec3 iridescence_fresnelToIor(vec3 f0) {\n\tvec3 sqrtF0 = sqrt(f0);\n\treturn (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0);\n}\nvec3 iridescence_sensitivity(float opd, vec3 shift) {\n\tfloat phase = 2.0 * PI * opd * 1.0e-9;\n\tconst vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13);\n\tconst vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06);\n\tconst vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09);\n\tvec3 xyz = val * sqrt(2.0 * PI * var) * cos(pos * phase + shift) * exp(-pow(phase, 2.0) * var);\n\txyz.x += 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + shift[0]) * exp(-4.5282e+09 * pow(phase, 2.0));\n\txyz /= vec3(1.0685e-07);\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t3.2404542, -0.9692660, 0.0556434,\n\t -1.5371385, 1.8760108, -0.2040259,\n\t -0.4985314, 0.0415560, 1.0572252\n\t);\n\treturn XYZ_TO_REC709 * xyz;\n}\nfloat iridescence_fresnel(float cosTheta, float f0) {\n\tfloat x = clamp(1.0 - cosTheta, 0.0, 1.0);\n\tfloat x2 = x * x;\n\tfloat x5 = x * x2 * x2;\n\treturn f0 + (1.0 - f0) * x5;\n} \nvec3 iridescence_fresnel(float cosTheta, vec3 f0) {\n\tfloat x = clamp(1.0 - cosTheta, 0.0, 1.0);\n\tfloat x2 = x * x;\n\tfloat x5 = x * x2 * x2; \n\treturn f0 + (vec3(1.0) - f0) * x5;\n}\nvec3 calcIridescence(float outsideIor, float cosTheta, vec3 base_f0, float iridescenceThickness) {\n\tfloat iridescenceIor = mix(outsideIor, material_iridescenceRefractionIndex, smoothstep(0.0, 0.03, iridescenceThickness));\n\tfloat sinTheta2Sq = pow(outsideIor / iridescenceIor, 2.0) * (1.0 - pow(cosTheta, 2.0));\n\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\tif (cosTheta2Sq < 0.0) {\n\t\treturn vec3(1.0);\n\t}\n\tfloat cosTheta2 = sqrt(cosTheta2Sq);\n\tfloat r0 = iridescence_iorToFresnel(iridescenceIor, outsideIor);\n\tfloat r12 = iridescence_fresnel(cosTheta, r0);\n\tfloat r21 = r12;\n\tfloat t121 = 1.0 - r12;\n\tfloat phi12 = iridescenceIor < outsideIor ? PI : 0.0;\n\tfloat phi21 = PI - phi12;\n\tvec3 baseIor = iridescence_fresnelToIor(base_f0 + vec3(0.0001));\n\tvec3 r1 = iridescence_iorToFresnel(baseIor, iridescenceIor);\n\tvec3 r23 = iridescence_fresnel(cosTheta2, r1);\n\tvec3 phi23 = vec3(0.0);\n\tif (baseIor[0] < iridescenceIor) phi23[0] = PI;\n\tif (baseIor[1] < iridescenceIor) phi23[1] = PI;\n\tif (baseIor[2] < iridescenceIor) phi23[2] = PI;\n\tfloat opd = 2.0 * iridescenceIor * iridescenceThickness * cosTheta2;\n\tvec3 phi = vec3(phi21) + phi23; \n\tvec3 r123Sq = clamp(r12 * r23, 1e-5, 0.9999);\n\tvec3 r123 = sqrt(r123Sq);\n\tvec3 rs = pow(t121, 2.0) * r23 / (1.0 - r123Sq);\n\tvec3 c0 = r12 + rs;\n\tvec3 i = c0;\n\tvec3 cm = rs - t121;\n\tfor (int m = 1; m <= 2; m++) {\n\t\tcm *= r123;\n\t\tvec3 sm = 2.0 * iridescence_sensitivity(float(m) * opd, float(m) * phi);\n\t\ti += cm * sm;\n\t}\n\treturn max(i, vec3(0.0));\n}\nvec3 getIridescence(float cosTheta, vec3 specularity, float iridescenceThickness) {\n\treturn calcIridescence(1.0, cosTheta, specularity, iridescenceThickness);\n}\n",iridescencePS:"\n#ifdef MAPFLOAT\nuniform float material_iridescence;\n#endif\nvoid getIridescence() {\n\tfloat iridescence = 1.0;\n\t#ifdef MAPFLOAT\n\tiridescence *= material_iridescence;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tiridescence *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\t#endif\n\tdIridescence = iridescence; \n}\n",iridescenceThicknessPS:"\nuniform float material_iridescenceThicknessMax;\n#ifdef MAPTEXTURE\nuniform float material_iridescenceThicknessMin;\n#endif\nvoid getIridescenceThickness() {\n\t#ifdef MAPTEXTURE\n\tfloat blend = texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\tfloat iridescenceThickness = mix(material_iridescenceThicknessMin, material_iridescenceThicknessMax, blend);\n\t#else\n\tfloat iridescenceThickness = material_iridescenceThicknessMax;\n\t#endif\n\tdIridescenceThickness = iridescenceThickness; \n}\n",instancingVS:"\nattribute vec4 instance_line1;\nattribute vec4 instance_line2;\nattribute vec4 instance_line3;\nattribute vec4 instance_line4;\n",iorPS:"\n#ifdef MAPFLOAT\nuniform float material_refractionIndex;\n#endif\nvoid getIor() {\n#ifdef MAPFLOAT\n\tdIor = material_refractionIndex;\n#else\n\tdIor = 1.0 / 1.5;\n#endif\n}\n",lightDiffuseLambertPS:"\nfloat getLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {\n\treturn max(dot(worldNormal, -lightDirNorm), 0.0);\n}\n",lightDirPointPS:"\nvoid getLightDirPoint(vec3 lightPosW) {\n\tdLightDirW = vPositionW - lightPosW;\n\tdLightDirNormW = normalize(dLightDirW);\n\tdLightPosW = lightPosW;\n}\n",lightmapAddPS:"\nvoid addLightMap(\n\tvec3 lightmap, \n\tvec3 dir, \n\tvec3 worldNormal, \n\tvec3 viewDir, \n\tvec3 reflectionDir, \n\tfloat gloss, \n\tvec3 specularity, \n\tvec3 vertexNormal, \n\tmat3 tbn\n#if defined(LIT_IRIDESCENCE)\n\tvec3 iridescenceFresnel, \n\tfloat iridescenceIntensity\n#endif\n) {\n\tdDiffuseLight += lightmap;\n}\n",lightmapDirAddPS:"\nvoid addLightMap(\n\tvec3 lightmap, \n\tvec3 dir, \n\tvec3 worldNormal, \n\tvec3 viewDir, \n\tvec3 reflectionDir, \n\tfloat gloss, \n\tvec3 specularity, \n\tvec3 vertexNormal, \n\tmat3 tbn\n#if defined(LIT_IRIDESCENCE)\n\tvec3 iridescenceFresnel, \n\tfloat iridescenceIntensity\n#endif\n) {\n\tif (dot(dir, dir) < 0.0001) {\n\t\tdDiffuseLight += lightmap;\n\t} else {\n\t\tfloat vlight = saturate(dot(dir, -vertexNormal));\n\t\tfloat flight = saturate(dot(dir, -worldNormal));\n\t\tfloat nlight = (flight / max(vlight, 0.01)) * 0.5;\n\t\tdDiffuseLight += lightmap * nlight * 2.0;\n\t\tvec3 halfDir = normalize(-dir + viewDir);\n\t\tvec3 specularLight = lightmap * getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, dir, gloss, tbn);\n#ifdef LIT_SPECULAR_FRESNEL\n\t\tspecularLight *= \n\t\t\tgetFresnel(dot(viewDir, halfDir), \n\t\t\tgloss, \n\t\t\tspecularity\n\t\t#if defined(LIT_IRIDESCENCE)\n\t\t\t, iridescenceFresnel,\n\t\t\tiridescenceIntensity\n\t\t#endif\n\t\t\t);\n#endif\n\t\tdSpecularLight += specularLight;\n\t}\n}\n",lightmapDirPS:"\nuniform sampler2D texture_lightMap;\nuniform sampler2D texture_dirLightMap;\nvoid getLightMap() {\n\tdLightmap = $DECODE(texture2DBias(texture_lightMap, $UV, textureBias)).$CH;\n\tvec3 dir = texture2DBias(texture_dirLightMap, $UV, textureBias).xyz * 2.0 - 1.0;\n\tfloat dirDot = dot(dir, dir);\n\tdLightmapDir = (dirDot > 0.001) ? dir / sqrt(dirDot) : vec3(0.0);\n}\n",lightmapSinglePS:"\nvoid getLightMap() {\n\tdLightmap = vec3(1.0);\n\t#ifdef MAPTEXTURE\n\tdLightmap *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tdLightmap *= saturate(vVertexColor.$VC);\n\t#endif\n}\n",lightSpecularAnisoGGXPS:"\nfloat calcLightSpecular(float gloss, vec3 worldNormal, vec3 viewDir, vec3 h, vec3 lightDirNorm, mat3 tbn) {\n\tfloat PI = 3.141592653589793;\n\tfloat roughness = max((1.0 - gloss) * (1.0 - gloss), 0.001);\n\tfloat anisotropy = material_anisotropy * roughness;\n \n\tfloat at = max((roughness + anisotropy), roughness / 4.0);\n\tfloat ab = max((roughness - anisotropy), roughness / 4.0);\n\tfloat NoH = dot(worldNormal, h);\n\tfloat ToH = dot(tbn[0], h);\n\tfloat BoH = dot(tbn[1], h);\n\tfloat a2 = at * ab;\n\tvec3 v = vec3(ab * ToH, at * BoH, a2 * NoH);\n\tfloat v2 = dot(v, v);\n\tfloat w2 = a2 / v2;\n\tfloat D = a2 * w2 * w2 * (1.0 / PI);\n\tfloat ToV = dot(tbn[0], viewDir);\n\tfloat BoV = dot(tbn[1], viewDir);\n\tfloat ToL = dot(tbn[0], -lightDirNorm);\n\tfloat BoL = dot(tbn[1], -lightDirNorm);\n\tfloat NoV = dot(worldNormal, viewDir);\n\tfloat NoL = dot(worldNormal, -lightDirNorm);\n\tfloat lambdaV = NoL * length(vec3(at * ToV, ab * BoV, NoV));\n\tfloat lambdaL = NoV * length(vec3(at * ToL, ab * BoL, NoL));\n\tfloat G = 0.5 / (lambdaV + lambdaL);\n\treturn D * G;\n}\nfloat getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) {\n\treturn calcLightSpecular(gloss, worldNormal, viewDir, h, lightDirNorm, tbn);\n}\n",lightSpecularBlinnPS:"\nfloat calcLightSpecular(float gloss, vec3 worldNormal, vec3 h) {\n\tfloat nh = max( dot( h, worldNormal ), 0.0 );\n\tfloat specPow = exp2(gloss * 11.0);\n\tspecPow = max(specPow, 0.0001);\n\treturn pow(nh, specPow) * (specPow + 2.0) / 8.0;\n}\nfloat getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) {\n\treturn calcLightSpecular(gloss, worldNormal, h);\n}\n",lightSpecularPhongPS:"\nfloat calcLightSpecular(float gloss, vec3 reflDir, vec3 lightDirNorm) {\n\tfloat specPow = gloss;\n\treturn pow(max(dot(reflDir, -lightDirNorm), 0.0), specPow + 0.0001);\n}\nfloat getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) {\n\treturn calcLightSpecular(gloss, reflDir, lightDirNorm);\n}\n",lightSheenPS:"\nfloat sheenD(vec3 normal, vec3 h, float roughness) {\n\tfloat invR = 1.0 / (roughness * roughness);\n\tfloat cos2h = max(dot(normal, h), 0.0);\n\tcos2h *= cos2h;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\n\treturn (2.0 + invR) * pow(sin2h, invR * 0.5) / (2.0 * PI);\n}\nfloat sheenV(vec3 normal, vec3 viewDir, vec3 light) {\n\tfloat NoV = max(dot(normal, viewDir), 0.000001);\n\tfloat NoL = max(dot(normal, light), 0.000001);\n\treturn 1.0 / (4.0 * (NoL + NoV - NoL * NoV));\n}\nfloat getLightSpecularSheen(vec3 h, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float sheenGloss) {\n\tfloat D = sheenD(worldNormal, h, sheenGloss);\n\tfloat V = sheenV(worldNormal, viewDir, -lightDirNorm);\n\treturn D * V;\n}\n",linearizeDepthPS:"\n#ifndef LINEARIZE_DEPTH\n#define LINEARIZE_DEPTH\nfloat linearizeDepth(float z, vec4 cameraParams) {\n\tif (cameraParams.w == 0.0)\n\t\treturn (cameraParams.z * cameraParams.y) / (cameraParams.y + z * (cameraParams.z - cameraParams.y));\n\telse\n\t\treturn cameraParams.z + z * (cameraParams.y - cameraParams.z);\n}\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params;\n#endif\n#ifdef GL2\nfloat linearizeDepth(float z) {\n\treturn linearizeDepth(z, camera_params);\n}\n#else\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n\tconst vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n\treturn dot(rgbaDepth, bitShift);\n}\n#endif\n#endif\n#endif\n",litShaderArgsPS:"\nvec3 litArgs_albedo;\nfloat litArgs_opacity;\nvec3 litArgs_emission;\nvec3 litArgs_worldNormal;\nfloat litArgs_ao;\nvec3 litArgs_lightmap;\nvec3 litArgs_lightmapDir;\nfloat litArgs_metalness;\nvec3 litArgs_specularity;\nfloat litArgs_specularityFactor;\nfloat litArgs_gloss;\nfloat litArgs_sheen_gloss;\nvec3 litArgs_sheen_specularity;\nfloat litArgs_transmission;\nfloat litArgs_thickness;\nfloat litArgs_ior;\nfloat litArgs_iridescence_intensity;\nfloat litArgs_iridescence_thickness;\nvec3 litArgs_clearcoat_worldNormal;\nfloat litArgs_clearcoat_specularity;\nfloat litArgs_clearcoat_gloss;\n",ltcPS:"\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nstruct Coords {\n\tvec3 coord0;\n\tvec3 coord1;\n\tvec3 coord2;\n\tvec3 coord3;\n};\nfloat LTC_EvaluateRect( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in Coords rectCoords) {\n\tvec3 v1 = rectCoords.coord1 - rectCoords.coord0;\n\tvec3 v2 = rectCoords.coord3 - rectCoords.coord0;\n\t\n\tvec3 lightNormal = cross( v1, v2 );\n\tfloat factor = sign(-dot( lightNormal, P - rectCoords.coord0 ));\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = factor * cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords.coord0 - P );\n\tcoords[ 1 ] = mat * ( rectCoords.coord1 - P );\n\tcoords[ 2 ] = mat * ( rectCoords.coord2 - P );\n\tcoords[ 3 ] = mat * ( rectCoords.coord3 - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn result;\n}\nCoords dLTCCoords;\nCoords getLTCLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){\n\tCoords coords;\n\tcoords.coord0 = lightPos + halfWidth - halfHeight;\n\tcoords.coord1 = lightPos - halfWidth - halfHeight;\n\tcoords.coord2 = lightPos - halfWidth + halfHeight;\n\tcoords.coord3 = lightPos + halfWidth + halfHeight;\n\treturn coords;\n}\nfloat dSphereRadius;\nCoords getSphereLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){\n\tdSphereRadius = max(length(halfWidth), length(halfHeight));\n\tvec3 f = reflect(normalize(lightPos - view_position), vNormalW);\n\tvec3 w = normalize(cross(f, halfHeight));\n\tvec3 h = normalize(cross(f, w));\n\treturn getLTCLightCoords(lightPos, w * dSphereRadius, h * dSphereRadius);\n}\nvec2 dLTCUV;\n#ifdef LIT_CLEARCOAT\nvec2 ccLTCUV;\n#endif\nvec2 getLTCLightUV(float gloss, vec3 worldNormal, vec3 viewDir)\n{\n\tfloat roughness = max((1.0 - gloss) * (1.0 - gloss), 0.001);\n\treturn LTC_Uv( worldNormal, viewDir, roughness );\n}\nvec3 dLTCSpecFres;\n#ifdef LIT_CLEARCOAT\nvec3 ccLTCSpecFres;\n#endif\nvec3 getLTCLightSpecFres(vec2 uv, vec3 specularity)\n{\n\tvec4 t2 = texture2DLodEXT(areaLightsLutTex2, uv, 0.0);\n\t#ifdef AREA_R8_G8_B8_A8_LUTS\n\tt2 *= vec4(0.693103,1,1,1);\n\tt2 += vec4(0.306897,0,0,0);\n\t#endif\n\treturn specularity * t2.x + ( vec3( 1.0 ) - specularity) * t2.y;\n}\nvoid calcLTCLightValues(float gloss, vec3 worldNormal, vec3 viewDir, vec3 specularity, float clearcoatGloss, vec3 clearcoatWorldNormal, float clearcoatSpecularity)\n{\n\tdLTCUV = getLTCLightUV(gloss, worldNormal, viewDir);\n\tdLTCSpecFres = getLTCLightSpecFres(dLTCUV, specularity); \n#ifdef LIT_CLEARCOAT\n\tccLTCUV = getLTCLightUV(clearcoatGloss, clearcoatWorldNormal, viewDir);\n\tccLTCSpecFres = getLTCLightSpecFres(ccLTCUV, vec3(clearcoatSpecularity));\n#endif\n}\nvoid calcRectLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight)\n{\n\tdLTCCoords = getLTCLightCoords(lightPos, halfWidth, halfHeight);\n}\nvoid calcDiskLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight)\n{\n\tcalcRectLightValues(lightPos, halfWidth, halfHeight);\n}\nvoid calcSphereLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight)\n{\n\tdLTCCoords = getSphereLightCoords(lightPos, halfWidth, halfHeight);\n}\nvec3 SolveCubic(vec4 Coefficient)\n{\n\tfloat pi = 3.14159;\n\tCoefficient.xyz /= Coefficient.w;\n\tCoefficient.yz /= 3.0;\n\tfloat A = Coefficient.w;\n\tfloat B = Coefficient.z;\n\tfloat C = Coefficient.y;\n\tfloat D = Coefficient.x;\n\tvec3 Delta = vec3(\n\t\t-Coefficient.z * Coefficient.z + Coefficient.y,\n\t\t-Coefficient.y * Coefficient.z + Coefficient.x,\n\t\tdot(vec2(Coefficient.z, -Coefficient.y), Coefficient.xy)\n\t);\n\tfloat Discriminant = dot(vec2(4.0 * Delta.x, -Delta.y), Delta.zy);\n\tvec3 RootsA, RootsD;\n\tvec2 xlc, xsc;\n\t{\n\t\tfloat A_a = 1.0;\n\t\tfloat C_a = Delta.x;\n\t\tfloat D_a = -2.0 * B * Delta.x + Delta.y;\n\t\tfloat Theta = atan(sqrt(Discriminant), -D_a) / 3.0;\n\t\tfloat x_1a = 2.0 * sqrt(-C_a) * cos(Theta);\n\t\tfloat x_3a = 2.0 * sqrt(-C_a) * cos(Theta + (2.0 / 3.0) * pi);\n\t\tfloat xl;\n\t\tif ((x_1a + x_3a) > 2.0 * B)\n\t\t\txl = x_1a;\n\t\telse\n\t\t\txl = x_3a;\n\t\txlc = vec2(xl - B, A);\n\t}\n\t{\n\t\tfloat A_d = D;\n\t\tfloat C_d = Delta.z;\n\t\tfloat D_d = -D * Delta.y + 2.0 * C * Delta.z;\n\t\tfloat Theta = atan(D * sqrt(Discriminant), -D_d) / 3.0;\n\t\tfloat x_1d = 2.0 * sqrt(-C_d) * cos(Theta);\n\t\tfloat x_3d = 2.0 * sqrt(-C_d) * cos(Theta + (2.0 / 3.0) * pi);\n\t\tfloat xs;\n\t\tif (x_1d + x_3d < 2.0 * C)\n\t\t\txs = x_1d;\n\t\telse\n\t\t\txs = x_3d;\n\t\txsc = vec2(-D, xs + C);\n\t}\n\tfloat E = xlc.y * xsc.y;\n\tfloat F = -xlc.x * xsc.y - xlc.y * xsc.x;\n\tfloat G = xlc.x * xsc.x;\n\tvec2 xmc = vec2(C * F - B * G, -B * F + C * E);\n\tvec3 Root = vec3(xsc.x / xsc.y, xmc.x / xmc.y, xlc.x / xlc.y);\n\tif (Root.x < Root.y && Root.x < Root.z)\n\t\tRoot.xyz = Root.yxz;\n\telse if (Root.z < Root.x && Root.z < Root.y)\n\t\tRoot.xyz = Root.xzy;\n\treturn Root;\n}\nfloat LTC_EvaluateDisk(vec3 N, vec3 V, vec3 P, mat3 Minv, Coords points)\n{\n\tvec3 T1, T2;\n\tT1 = normalize(V - N * dot(V, N));\n\tT2 = cross(N, T1);\n\tmat3 R = transposeMat3( mat3( T1, T2, N ) );\n\tvec3 L_[ 3 ];\n\tL_[ 0 ] = R * ( points.coord0 - P );\n\tL_[ 1 ] = R * ( points.coord1 - P );\n\tL_[ 2 ] = R * ( points.coord2 - P );\n\tvec3 Lo_i = vec3(0);\n\tvec3 C = 0.5 * (L_[0] + L_[2]);\n\tvec3 V1 = 0.5 * (L_[1] - L_[2]);\n\tvec3 V2 = 0.5 * (L_[1] - L_[0]);\n\tC = Minv * C;\n\tV1 = Minv * V1;\n\tV2 = Minv * V2;\n\tfloat a, b;\n\tfloat d11 = dot(V1, V1);\n\tfloat d22 = dot(V2, V2);\n\tfloat d12 = dot(V1, V2);\n\tif (abs(d12) / sqrt(d11 * d22) > 0.0001)\n\t{\n\t\tfloat tr = d11 + d22;\n\t\tfloat det = -d12 * d12 + d11 * d22;\n\t\tdet = sqrt(det);\n\t\tfloat u = 0.5 * sqrt(tr - 2.0 * det);\n\t\tfloat v = 0.5 * sqrt(tr + 2.0 * det);\n\t\tfloat e_max = (u + v) * (u + v);\n\t\tfloat e_min = (u - v) * (u - v);\n\t\tvec3 V1_, V2_;\n\t\tif (d11 > d22)\n\t\t{\n\t\t\tV1_ = d12 * V1 + (e_max - d11) * V2;\n\t\t\tV2_ = d12 * V1 + (e_min - d11) * V2;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tV1_ = d12*V2 + (e_max - d22)*V1;\n\t\t\tV2_ = d12*V2 + (e_min - d22)*V1;\n\t\t}\n\t\ta = 1.0 / e_max;\n\t\tb = 1.0 / e_min;\n\t\tV1 = normalize(V1_);\n\t\tV2 = normalize(V2_);\n\t}\n\telse\n\t{\n\t\ta = 1.0 / dot(V1, V1);\n\t\tb = 1.0 / dot(V2, V2);\n\t\tV1 *= sqrt(a);\n\t\tV2 *= sqrt(b);\n\t}\n\tvec3 V3 = cross(V1, V2);\n\tif (dot(C, V3) < 0.0)\n\t\tV3 *= -1.0;\n\tfloat L = dot(V3, C);\n\tfloat x0 = dot(V1, C) / L;\n\tfloat y0 = dot(V2, C) / L;\n\tfloat E1 = inversesqrt(a);\n\tfloat E2 = inversesqrt(b);\n\ta *= L * L;\n\tb *= L * L;\n\tfloat c0 = a * b;\n\tfloat c1 = a * b * (1.0 + x0 * x0 + y0 * y0) - a - b;\n\tfloat c2 = 1.0 - a * (1.0 + x0 * x0) - b * (1.0 + y0 * y0);\n\tfloat c3 = 1.0;\n\tvec3 roots = SolveCubic(vec4(c0, c1, c2, c3));\n\tfloat e1 = roots.x;\n\tfloat e2 = roots.y;\n\tfloat e3 = roots.z;\n\tvec3 avgDir = vec3(a * x0 / (a - e2), b * y0 / (b - e2), 1.0);\n\tmat3 rotate = mat3(V1, V2, V3);\n\tavgDir = rotate * avgDir;\n\tavgDir = normalize(avgDir);\n\tfloat L1 = sqrt(-e2 / e3);\n\tfloat L2 = sqrt(-e2 / e1);\n\tfloat formFactor = L1 * L2 * inversesqrt((1.0 + L1 * L1) * (1.0 + L2 * L2));\n\t\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tvec2 uv = vec2(avgDir.z * 0.5 + 0.5, formFactor);\n\tuv = uv*LUT_SCALE + LUT_BIAS;\n\tfloat scale = texture2DLodEXT(areaLightsLutTex2, uv, 0.0).w;\n\treturn formFactor*scale;\n}\nfloat getRectLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {\n\treturn LTC_EvaluateRect( worldNormal, viewDir, vPositionW, mat3( 1.0 ), dLTCCoords );\n}\nfloat getDiskLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {\n\treturn LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, mat3( 1.0 ), dLTCCoords );\n}\nfloat getSphereLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {\n\tfloat falloff = dSphereRadius / (dot(lightDir, lightDir) + dSphereRadius);\n\treturn getLightDiffuse(worldNormal, viewDir, lightDir, lightDirNorm) * falloff;\n}\nmat3 getLTCLightInvMat(vec2 uv)\n{\n\tvec4 t1 = texture2DLodEXT(areaLightsLutTex1, uv, 0.0);\n\t#ifdef AREA_R8_G8_B8_A8_LUTS\n\tt1 *= vec4(1.001, 0.3239, 0.60437568, 1.0);\n\tt1 += vec4(0.0, -0.2976, -0.01381, 0.0);\n\t#endif\n\treturn mat3(\n\t\tvec3( t1.x, 0, t1.y ),\n\t\tvec3(\t0, 1,\t0 ),\n\t\tvec3( t1.z, 0, t1.w )\n\t);\n}\nfloat calcRectLightSpecular(vec3 worldNormal, vec3 viewDir, vec2 uv) {\n\tmat3 mInv = getLTCLightInvMat(uv);\n\treturn LTC_EvaluateRect( worldNormal, viewDir, vPositionW, mInv, dLTCCoords );\n}\nfloat getRectLightSpecular(vec3 worldNormal, vec3 viewDir) {\n\treturn calcRectLightSpecular(worldNormal, viewDir, dLTCUV);\n}\nfloat calcDiskLightSpecular(vec3 worldNormal, vec3 viewDir, vec2 uv) {\n\tmat3 mInv = getLTCLightInvMat(uv);\n\treturn LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, mInv, dLTCCoords );\n}\nfloat getDiskLightSpecular(vec3 worldNormal, vec3 viewDir) {\n\treturn calcDiskLightSpecular(worldNormal, viewDir, dLTCUV);\n}\nfloat getSphereLightSpecular(vec3 worldNormal, vec3 viewDir) {\n\treturn calcDiskLightSpecular(worldNormal, viewDir, dLTCUV);\n}\n",metalnessPS:"\n#ifdef MAPFLOAT\nuniform float material_metalness;\n#endif\nvoid getMetalness() {\n\tfloat metalness = 1.0;\n\t#ifdef MAPFLOAT\n\tmetalness *= material_metalness;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tmetalness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tmetalness *= saturate(vVertexColor.$VC);\n\t#endif\n\tdMetalness = metalness;\n}\n",metalnessModulatePS:"\nvec3 getSpecularModulate(in vec3 specularity, in vec3 albedo, in float metalness, in float f0) {\n\tvec3 dielectricF0 = f0 * specularity;\n\treturn mix(dielectricF0, albedo, metalness);\n}\nvec3 getAlbedoModulate(in vec3 albedo, in float metalness) {\n\treturn albedo * (1.0 - metalness);\n}\n",msdfPS:"\nuniform sampler2D texture_msdfMap;\n#ifdef GL_OES_standard_derivatives\n#define USE_FWIDTH\n#endif\n#ifdef GL2\n#define USE_FWIDTH\n#endif\nfloat median(float r, float g, float b) {\n\treturn max(min(r, g), min(max(r, g), b));\n}\nfloat map (float min, float max, float v) {\n\treturn (v - min) / (max - min);\n}\nuniform float font_sdfIntensity;\nuniform float font_pxrange;\nuniform float font_textureWidth;\n#ifdef UNIFORM_TEXT_PARAMETERS\nuniform vec4 outline_color;\nuniform float outline_thickness;\nuniform vec4 shadow_color;\nuniform vec2 shadow_offset;\n#else\nvarying vec4 outline_color;\nvarying float outline_thickness;\nvarying vec4 shadow_color;\nvarying vec2 shadow_offset;\n#endif\nvec4 applyMsdf(vec4 color) {\n\tvec3 tsample = texture2D(texture_msdfMap, vUv0).rgb;\n\tvec2 uvShdw = vUv0 - shadow_offset;\n\tvec3 ssample = texture2D(texture_msdfMap, uvShdw).rgb;\n\tfloat sigDist = median(tsample.r, tsample.g, tsample.b);\n\tfloat sigDistShdw = median(ssample.r, ssample.g, ssample.b);\n\tfloat smoothingMax = 0.2;\n\t#ifdef USE_FWIDTH\n\tvec2 w = fwidth(vUv0);\n\tfloat smoothing = clamp(w.x * font_textureWidth / font_pxrange, 0.0, smoothingMax);\n\t#else\n\tfloat font_size = 16.0;\n\tfloat smoothing = clamp(font_pxrange / font_size, 0.0, smoothingMax);\n\t#endif\n\tfloat mapMin = 0.05;\n\tfloat mapMax = clamp(1.0 - font_sdfIntensity, mapMin, 1.0);\n\tfloat sigDistInner = map(mapMin, mapMax, sigDist);\n\tfloat sigDistOutline = map(mapMin, mapMax, sigDist + outline_thickness);\n\tsigDistShdw = map(mapMin, mapMax, sigDistShdw + outline_thickness);\n\tfloat center = 0.5;\n\tfloat inside = smoothstep(center-smoothing, center+smoothing, sigDistInner);\n\tfloat outline = smoothstep(center-smoothing, center+smoothing, sigDistOutline);\n\tfloat shadow = smoothstep(center-smoothing, center+smoothing, sigDistShdw);\n\tvec4 tcolor = (outline > inside) ? outline * vec4(outline_color.a * outline_color.rgb, outline_color.a) : vec4(0.0);\n\ttcolor = mix(tcolor, color, inside);\n\tvec4 scolor = (shadow > outline) ? shadow * vec4(shadow_color.a * shadow_color.rgb, shadow_color.a) : tcolor;\n\ttcolor = mix(scolor, tcolor, outline);\n\t\n\treturn tcolor;\n}\n",msdfVS:"\nattribute vec3 vertex_outlineParameters;\nattribute vec3 vertex_shadowParameters;\nvarying vec4 outline_color;\nvarying float outline_thickness;\nvarying vec4 shadow_color;\nvarying vec2 shadow_offset;\nvoid unpackMsdfParams() {\n\tvec3 little = mod(vertex_outlineParameters, 256.);\n\tvec3 big = (vertex_outlineParameters - little) / 256.;\n\toutline_color.rb = little.xy / 255.;\n\toutline_color.ga = big.xy / 255.;\n\toutline_thickness = little.z / 255. * 0.2;\n\tlittle = mod(vertex_shadowParameters, 256.);\n\tbig = (vertex_shadowParameters - little) / 256.;\n\tshadow_color.rb = little.xy / 255.;\n\tshadow_color.ga = big.xy / 255.;\n\tshadow_offset = (vec2(little.z, big.z) / 127. - 1.) * 0.005;\n}\n",normalVS:"\n#ifdef MORPHING_TEXTURE_BASED_NORMAL\nuniform highp sampler2D morphNormalTex;\n#endif\nvec3 getNormal() {\n\t#ifdef SKIN\n\tdNormalMatrix = mat3(dModelMatrix[0].xyz, dModelMatrix[1].xyz, dModelMatrix[2].xyz);\n\t#elif defined(INSTANCING)\n\tdNormalMatrix = mat3(instance_line1.xyz, instance_line2.xyz, instance_line3.xyz);\n\t#else\n\tdNormalMatrix = matrix_normal;\n\t#endif\n\tvec3 tempNormal = vertex_normal;\n\t#ifdef MORPHING\n\t#ifdef MORPHING_NRM03\n\ttempNormal += morph_weights_a[0] * morph_nrm0;\n\ttempNormal += morph_weights_a[1] * morph_nrm1;\n\ttempNormal += morph_weights_a[2] * morph_nrm2;\n\ttempNormal += morph_weights_a[3] * morph_nrm3;\n\t#endif\n\t#ifdef MORPHING_NRM47\n\ttempNormal += morph_weights_b[0] * morph_nrm4;\n\ttempNormal += morph_weights_b[1] * morph_nrm5;\n\ttempNormal += morph_weights_b[2] * morph_nrm6;\n\ttempNormal += morph_weights_b[3] * morph_nrm7;\n\t#endif\n\t#endif\n\t#ifdef MORPHING_TEXTURE_BASED_NORMAL\n\t\t#ifdef WEBGPU\n\t\t\tivec2 morphUV = getTextureMorphCoords();\n\t\t\tvec3 morphNormal = texelFetch(morphNormalTex, ivec2(morphUV), 0).xyz;\n\t\t#else\n\t\t\tvec2 morphUV = getTextureMorphCoords();\n\t\t\tvec3 morphNormal = texture2D(morphNormalTex, morphUV).xyz;\n\t\t#endif\n\ttempNormal += morphNormal;\n\t#endif\n\treturn normalize(dNormalMatrix * tempNormal);\n}\n",normalDetailMapPS:"\n#ifdef MAPTEXTURE\nuniform float material_normalDetailMapBumpiness;\nvec3 blendNormals(vec3 n1, vec3 n2) {\n\tn1 += vec3(0, 0, 1);\n\tn2 *= vec3(-1, -1, 1);\n\treturn n1 * dot(n1, n2) / n1.z - n2;\n}\n#endif\nvec3 addNormalDetail(vec3 normalMap) {\n#ifdef MAPTEXTURE\n\tvec3 normalDetailMap = unpackNormal(texture2DBias($SAMPLER, $UV, textureBias));\n\tnormalDetailMap = mix(vec3(0.0, 0.0, 1.0), normalDetailMap, material_normalDetailMapBumpiness);\n\treturn blendNormals(normalMap, normalDetailMap);\n#else\n\treturn normalMap;\n#endif\n}\n",normalInstancedVS:"\nvec3 getNormal() {\n\tdNormalMatrix = mat3(instance_line1.xyz, instance_line2.xyz, instance_line3.xyz);\n\treturn normalize(dNormalMatrix * vertex_normal);\n}\n",normalMapPS:"\n#ifdef MAPTEXTURE\nuniform float material_bumpiness;\n#endif\nvoid getNormal() {\n#ifdef MAPTEXTURE\n\tvec3 normalMap = unpackNormal(texture2DBias($SAMPLER, $UV, textureBias));\n\tnormalMap = mix(vec3(0.0, 0.0, 1.0), normalMap, material_bumpiness);\n\tdNormalW = normalize(dTBN * addNormalDetail(normalMap));\n#else\n\tdNormalW = dVertexNormalW;\n#endif\n}\n",normalSkinnedVS:"\nvec3 getNormal() {\n\tdNormalMatrix = mat3(dModelMatrix[0].xyz, dModelMatrix[1].xyz, dModelMatrix[2].xyz);\n\treturn normalize(dNormalMatrix * vertex_normal);\n}\n",normalXYPS:"\nvec3 unpackNormal(vec4 nmap) {\n\tvec3 normal;\n\tnormal.xy = nmap.wy * 2.0 - 1.0;\n\tnormal.z = sqrt(1.0 - saturate(dot(normal.xy, normal.xy)));\n\treturn normal;\n}\n",normalXYZPS:"\nvec3 unpackNormal(vec4 nmap) {\n\treturn nmap.xyz * 2.0 - 1.0;\n}\n",opacityPS:"\n#ifdef MAPFLOAT\nuniform float material_opacity;\n#endif\nvoid getOpacity() {\n\tdAlpha = 1.0;\n\t#ifdef MAPFLOAT\n\tdAlpha *= material_opacity;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tdAlpha *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tdAlpha *= clamp(vVertexColor.$VC, 0.0, 1.0);\n\t#endif\n}\n",outputPS:"\n",outputAlphaPS:"\ngl_FragColor.a = litArgs_opacity;\n",outputAlphaOpaquePS:"\n\tgl_FragColor.a = 1.0;\n",outputAlphaPremulPS:"\ngl_FragColor.rgb *= litArgs_opacity;\ngl_FragColor.a = litArgs_opacity;\n",outputTex2DPS:"\nvarying vec2 vUv0;\nuniform sampler2D source;\nvoid main(void) {\n\tgl_FragColor = texture2D(source, vUv0);\n}\n",packDepthPS:"\nvec4 packFloat(float depth) {\n\tconst vec4 bit_shift = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);\n\tvec4 res = mod(depth * bit_shift * vec4(255), vec4(256) ) / vec4(255);\n\tres -= res.xxyz * bit_mask;\n\treturn res;\n}\n",sheenPS:"\n#ifdef MAPCOLOR\nuniform vec3 material_sheen;\n#endif\nvoid getSheen() {\n\tvec3 sheenColor = vec3(1, 1, 1);\n\t#ifdef MAPCOLOR\n\tsheenColor *= material_sheen;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tsheenColor *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tsheenColor *= saturate(vVertexColor.$VC);\n\t#endif\n\tsSpecularity = sheenColor;\n}\n",sheenGlossPS:"\n#ifdef MAPFLOAT\nuniform float material_sheenGloss;\n#endif\nvoid getSheenGlossiness() {\n\tfloat sheenGlossiness = 1.0;\n\t#ifdef MAPFLOAT\n\tsheenGlossiness *= material_sheenGloss;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tsheenGlossiness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tsheenGlossiness *= saturate(vVertexColor.$VC);\n\t#endif\n\t#ifdef MAPINVERT\n\tsheenGlossiness = 1.0 - sheenGlossiness;\n\t#endif\n\tsheenGlossiness += 0.0000001;\n\tsGlossiness = sheenGlossiness;\n}\n",parallaxPS:"\nuniform float material_heightMapFactor;\nvoid getParallax() {\n\tfloat parallaxScale = material_heightMapFactor;\n\tfloat height = texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\theight = height * parallaxScale - parallaxScale*0.5;\n\tvec3 viewDirT = dViewDirW * dTBN;\n\tviewDirT.z += 0.42;\n\tdUvOffset = height * (viewDirT.xy / viewDirT.z);\n}\n",particlePS:"\nvarying vec4 texCoordsAlphaLife;\nuniform sampler2D colorMap;\nuniform sampler2D colorParam;\nuniform float graphSampleSize;\nuniform float graphNumSamples;\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params;\n#endif\nuniform float softening;\nuniform float colorMult;\nfloat saturate(float x) {\n\treturn clamp(x, 0.0, 1.0);\n}\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n\tconst vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n\tfloat depth = dot(rgbaDepth, bitShift);\n\treturn depth;\n}\n#endif\nvoid main(void) {\n\tvec4 tex = gammaCorrectInput(texture2D(colorMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y)));\n\tvec4 ramp = gammaCorrectInput(texture2D(colorParam, vec2(texCoordsAlphaLife.w, 0.0)));\n\tramp.rgb *= colorMult;\n\tramp.a += texCoordsAlphaLife.z;\n\tvec3 rgb = tex.rgb * ramp.rgb;\n\tfloat a = tex.a * ramp.a;\n",particleVS:"\nvec3 unpack3NFloats(float src) {\n\tfloat r = fract(src);\n\tfloat g = fract(src * 256.0);\n\tfloat b = fract(src * 65536.0);\n\treturn vec3(r, g, b);\n}\nfloat saturate(float x) {\n\treturn clamp(x, 0.0, 1.0);\n}\nvec4 tex1Dlod_lerp(highp sampler2D tex, vec2 tc) {\n\treturn mix( texture2D(tex,tc), texture2D(tex,tc + graphSampleSize), fract(tc.x*graphNumSamples) );\n}\nvec4 tex1Dlod_lerp(highp sampler2D tex, vec2 tc, out vec3 w) {\n\tvec4 a = texture2D(tex,tc);\n\tvec4 b = texture2D(tex,tc + graphSampleSize);\n\tfloat c = fract(tc.x*graphNumSamples);\n\tvec3 unpackedA = unpack3NFloats(a.w);\n\tvec3 unpackedB = unpack3NFloats(b.w);\n\tw = mix(unpackedA, unpackedB, c);\n\treturn mix(a, b, c);\n}\nvec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix) {\n\tfloat c = cos(pRotation);\n\tfloat s = sin(pRotation);\n\tmat2 m = mat2(c, -s, s, c);\n\trotMatrix = m;\n\treturn m * quadXY;\n}\nvec3 billboard(vec3 InstanceCoords, vec2 quadXY) {\n\t#ifdef SCREEN_SPACE\n\t\tvec3 pos = vec3(-1, 0, 0) * quadXY.x + vec3(0, -1, 0) * quadXY.y;\n\t#else\n\t\tvec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y;\n\t#endif\n\treturn pos;\n}\nvec3 customFace(vec3 InstanceCoords, vec2 quadXY) {\n\tvec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y;\n\treturn pos;\n}\nvec2 safeNormalize(vec2 v) {\n\tfloat l = length(v);\n\treturn (l > 1e-06) ? v / l : v;\n}\nvoid main(void) {\n\tvec3 meshLocalPos = particle_vertexData.xyz;\n\tfloat id = floor(particle_vertexData.w);\n\tfloat rndFactor = fract(sin(id + 1.0 + seed));\n\tvec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));\n\tfloat uv = id / numParticlesPot;\n\treadInput(uv);\n#ifdef LOCAL_SPACE\n\tinVel = mat3(matrix_model) * inVel;\n#endif\n\tvec2 velocityV = safeNormalize((mat3(matrix_view) * inVel).xy);\n\tfloat particleLifetime = lifetime;\n\tif (inLife <= 0.0 || inLife > particleLifetime || !inShow) meshLocalPos = vec3(0.0);\n\tvec2 quadXY = meshLocalPos.xy;\n\tfloat nlife = clamp(inLife / particleLifetime, 0.0, 1.0);\n\tvec3 paramDiv;\n\tvec4 params = tex1Dlod_lerp(internalTex2, vec2(nlife, 0), paramDiv);\n\tfloat scale = params.y;\n\tfloat scaleDiv = paramDiv.x;\n\tfloat alphaDiv = paramDiv.z;\n\tscale += (scaleDiv * 2.0 - 1.0) * scaleDivMult * fract(rndFactor*10000.0);\n#ifndef USE_MESH\n\ttexCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);\n#else\n\ttexCoordsAlphaLife = vec4(particle_uv, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);\n#endif\n\tvec3 particlePos = inPos;\n\tvec3 particlePosMoved = vec3(0.0);\n\tmat2 rotMatrix;\n",particleAnimFrameClampVS:"\n\tfloat animFrame = min(floor(texCoordsAlphaLife.w * animTexParams.y) + animTexParams.x, animTexParams.z);\n",particleAnimFrameLoopVS:"\n\tfloat animFrame = floor(mod(texCoordsAlphaLife.w * animTexParams.y + animTexParams.x, animTexParams.z + 1.0));\n",particleAnimTexVS:"\n\tfloat animationIndex;\n\tif (animTexIndexParams.y == 1.0) {\n\t\tanimationIndex = floor((animTexParams.w + 1.0) * rndFactor3.z) * (animTexParams.z + 1.0);\n\t} else {\n\t\tanimationIndex = animTexIndexParams.x * (animTexParams.z + 1.0);\n\t}\n\tfloat atlasX = (animationIndex + animFrame) * animTexTilesParams.x;\n\tfloat atlasY = 1.0 - floor(atlasX + 1.0) * animTexTilesParams.y;\n\tatlasX = fract(atlasX);\n\ttexCoordsAlphaLife.xy *= animTexTilesParams.xy;\n\ttexCoordsAlphaLife.xy += vec2(atlasX, atlasY);\n",particleInputFloatPS:"\nvoid readInput(float uv) {\n\tvec4 tex = texture2D(particleTexIN, vec2(uv, 0.25));\n\tvec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.75));\n\tinPos = tex.xyz;\n\tinVel = tex2.xyz;\n\tinAngle = (tex.w < 0.0? -tex.w : tex.w) - 1000.0;\n\tinShow = tex.w >= 0.0;\n\tinLife = tex2.w;\n}\n",particleInputRgba8PS:"\n#define PI2 6.283185307179586\nuniform vec3 inBoundsSize;\nuniform vec3 inBoundsCenter;\nuniform float maxVel;\nfloat decodeFloatRG(vec2 rg) {\n\treturn rg.y*(1.0/255.0) + rg.x;\n}\nfloat decodeFloatRGBA( vec4 rgba ) {\n return dot( rgba, vec4(1.0, 1.0/255.0, 1.0/65025.0, 1.0/160581375.0) );\n}\nvoid readInput(float uv) {\n\tvec4 tex0 = texture2D(particleTexIN, vec2(uv, 0.125));\n\tvec4 tex1 = texture2D(particleTexIN, vec2(uv, 0.375));\n\tvec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.625));\n\tvec4 tex3 = texture2D(particleTexIN, vec2(uv, 0.875));\n\tinPos = vec3(decodeFloatRG(tex0.rg), decodeFloatRG(tex0.ba), decodeFloatRG(tex1.rg));\n\tinPos = (inPos - vec3(0.5)) * inBoundsSize + inBoundsCenter;\n\tinVel = tex2.xyz;\n\tinVel = (inVel - vec3(0.5)) * maxVel;\n\tinAngle = decodeFloatRG(tex1.ba) * PI2;\n\tinShow = tex2.a > 0.5;\n\tinLife = decodeFloatRGBA(tex3);\n\tfloat maxNegLife = max(lifetime, (numParticles - 1.0) * (rate+rateDiv));\n\tfloat maxPosLife = lifetime+1.0;\n\tinLife = inLife * (maxNegLife + maxPosLife) - maxNegLife;\n}\n",particleOutputFloatPS:"\nvoid writeOutput() {\n\tif (gl_FragCoord.y<1.0) {\n\t\tgl_FragColor = vec4(outPos, (outAngle + 1000.0) * visMode);\n\t} else {\n\t\tgl_FragColor = vec4(outVel, outLife);\n\t}\n}\n",particleOutputRgba8PS:"\nuniform vec3 outBoundsMul;\nuniform vec3 outBoundsAdd;\nvec2 encodeFloatRG( float v ) {\n\tvec2 enc = vec2(1.0, 255.0) * v;\n\tenc = fract(enc);\n\tenc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n\treturn enc;\n}\nvec4 encodeFloatRGBA( float v ) {\n\tvec4 enc = vec4(1.0, 255.0, 65025.0, 160581375.0) * v;\n\tenc = fract(enc);\n\tenc -= enc.yzww * vec4(1.0/255.0,1.0/255.0,1.0/255.0,0.0);\n\treturn enc;\n}\nvoid writeOutput() {\n\toutPos = outPos * outBoundsMul + outBoundsAdd;\n\toutAngle = fract(outAngle / PI2);\n\toutVel = (outVel / maxVel) + vec3(0.5);\n\tfloat maxNegLife = max(lifetime, (numParticles - 1.0) * (rate+rateDiv));\n\tfloat maxPosLife = lifetime+1.0;\n\toutLife = (outLife + maxNegLife) / (maxNegLife + maxPosLife);\n\tif (gl_FragCoord.y < 1.0) {\n\t\tgl_FragColor = vec4(encodeFloatRG(outPos.x), encodeFloatRG(outPos.y));\n\t} else if (gl_FragCoord.y < 2.0) {\n\t\tgl_FragColor = vec4(encodeFloatRG(outPos.z), encodeFloatRG(outAngle));\n\t} else if (gl_FragCoord.y < 3.0) {\n\t\tgl_FragColor = vec4(outVel, visMode*0.5+0.5);\n\t} else {\n\t\tgl_FragColor = encodeFloatRGBA(outLife);\n\t}\n}\n",particleUpdaterAABBPS:"\nuniform mat3 spawnBounds;\nuniform vec3 spawnPosInnerRatio;\nvec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {\n\tvec3 pos = inBounds - vec3(0.5);\n\tvec3 posAbs = abs(pos);\n\tvec3 maxPos = vec3(max(posAbs.x, max(posAbs.y, posAbs.z)));\n\tvec3 edge = maxPos + (vec3(0.5) - maxPos) * spawnPosInnerRatio;\n\tpos.x = edge.x * (maxPos.x == posAbs.x ? sign(pos.x) : 2.0 * pos.x);\n\tpos.y = edge.y * (maxPos.y == posAbs.y ? sign(pos.y) : 2.0 * pos.y);\n\tpos.z = edge.z * (maxPos.z == posAbs.z ? sign(pos.z) : 2.0 * pos.z);\n#ifndef LOCAL_SPACE\n\treturn emitterPos + spawnBounds * pos;\n#else\n\treturn spawnBounds * pos;\n#endif\n}\nvoid addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {\n\tlocalVelocity -= vec3(0, 0, initialVelocity);\n}\n",particleUpdaterEndPS:"\n\twriteOutput();\n}\n",particleUpdaterInitPS:"\nvarying vec2 vUv0;\nuniform highp sampler2D particleTexIN;\nuniform highp sampler2D internalTex0;\nuniform highp sampler2D internalTex1;\nuniform highp sampler2D internalTex2;\nuniform highp sampler2D internalTex3;\nuniform mat3 emitterMatrix, emitterMatrixInv;\nuniform vec3 emitterScale;\nuniform vec3 emitterPos, frameRandom, localVelocityDivMult, velocityDivMult;\nuniform float delta, rate, rateDiv, lifetime, numParticles, rotSpeedDivMult, radialSpeedDivMult, seed;\nuniform float startAngle, startAngle2;\nuniform float initialVelocity;\nuniform float graphSampleSize;\nuniform float graphNumSamples;\nvec3 inPos;\nvec3 inVel;\nfloat inAngle;\nbool inShow;\nfloat inLife;\nfloat visMode;\nvec3 outPos;\nvec3 outVel;\nfloat outAngle;\nbool outShow;\nfloat outLife;\n",particleUpdaterNoRespawnPS:"\n\tif (outLife >= lifetime) {\n\t\toutLife -= max(lifetime, (numParticles - 1.0) * particleRate);\n\t\tvisMode = -1.0;\n\t}\n",particleUpdaterOnStopPS:"\n\tvisMode = outLife < 0.0? -1.0: visMode;\n",particleUpdaterRespawnPS:"\n\tif (outLife >= lifetime) {\n\t\toutLife -= max(lifetime, (numParticles - 1.0) * particleRate);\n\t\tvisMode = 1.0;\n\t}\n\tvisMode = outLife < 0.0? 1.0: visMode;\n",particleUpdaterSpherePS:"\nuniform float spawnBoundsSphere;\nuniform float spawnBoundsSphereInnerRatio;\nvec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {\n\tfloat rnd4 = fract(rndFactor * 1000.0);\n\tvec3 norm = normalize(inBounds.xyz - vec3(0.5));\n\tfloat r = rnd4 * (1.0 - spawnBoundsSphereInnerRatio) + spawnBoundsSphereInnerRatio;\n#ifndef LOCAL_SPACE\n\treturn emitterPos + norm * r * spawnBoundsSphere;\n#else\n\treturn norm * r * spawnBoundsSphere;\n#endif\n}\nvoid addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {\n\tlocalVelocity += normalize(inBounds - vec3(0.5)) * initialVelocity;\n}\n",particleUpdaterStartPS:"\nfloat saturate(float x) {\n\treturn clamp(x, 0.0, 1.0);\n}\nvec3 unpack3NFloats(float src) {\n\tfloat r = fract(src);\n\tfloat g = fract(src * 256.0);\n\tfloat b = fract(src * 65536.0);\n\treturn vec3(r, g, b);\n}\nvec3 tex1Dlod_lerp(highp sampler2D tex, vec2 tc, out vec3 w) {\n\tvec4 a = texture2D(tex, tc);\n\tvec4 b = texture2D(tex, tc + graphSampleSize);\n\tfloat c = fract(tc.x * graphNumSamples);\n\tvec3 unpackedA = unpack3NFloats(a.w);\n\tvec3 unpackedB = unpack3NFloats(b.w);\n\tw = mix(unpackedA, unpackedB, c);\n\treturn mix(a.xyz, b.xyz, c);\n}\n#define HASHSCALE4 vec4(1031, .1030, .0973, .1099)\nvec4 hash41(float p) {\n\tvec4 p4 = fract(vec4(p) * HASHSCALE4);\n\tp4 += dot(p4, p4.wzxy+19.19);\n\treturn fract(vec4((p4.x + p4.y)*p4.z, (p4.x + p4.z)*p4.y, (p4.y + p4.z)*p4.w, (p4.z + p4.w)*p4.x));\n}\nvoid main(void) {\n\tif (gl_FragCoord.x > numParticles) discard;\n\treadInput(vUv0.x);\n\tvisMode = inShow? 1.0 : -1.0;\n\tvec4 rndFactor = hash41(gl_FragCoord.x + seed);\n\tfloat particleRate = rate + rateDiv * rndFactor.x;\n\toutLife = inLife + delta;\n\tfloat nlife = clamp(outLife / lifetime, 0.0, 1.0);\n\tvec3 localVelocityDiv;\n\tvec3 velocityDiv;\n\tvec3 paramDiv;\n\tvec3 localVelocity = tex1Dlod_lerp(internalTex0, vec2(nlife, 0), localVelocityDiv);\n\tvec3 velocity =\t tex1Dlod_lerp(internalTex1, vec2(nlife, 0), velocityDiv);\n\tvec3 params =\t\ttex1Dlod_lerp(internalTex2, vec2(nlife, 0), paramDiv);\n\tfloat rotSpeed = params.x;\n\tfloat rotSpeedDiv = paramDiv.y;\n\tvec3 radialParams = tex1Dlod_lerp(internalTex3, vec2(nlife, 0), paramDiv);\n\tfloat radialSpeed = radialParams.x;\n\tfloat radialSpeedDiv = radialParams.y;\n\tbool respawn = inLife <= 0.0 || outLife >= lifetime;\n\tinPos = respawn ? calcSpawnPosition(rndFactor.xyz, rndFactor.x) : inPos;\n\tinAngle = respawn ? mix(startAngle, startAngle2, rndFactor.x) : inAngle;\n#ifndef LOCAL_SPACE\n\tvec3 radialVel = inPos - emitterPos;\n#else\n\tvec3 radialVel = inPos;\n#endif\n\tradialVel = (dot(radialVel, radialVel) > 1.0E-8) ? radialSpeed * normalize(radialVel) : vec3(0.0);\n\tradialVel += (radialSpeedDiv * vec3(2.0) - vec3(1.0)) * radialSpeedDivMult * rndFactor.xyz;\n\tlocalVelocity +=\t(localVelocityDiv * vec3(2.0) - vec3(1.0)) * localVelocityDivMult * rndFactor.xyz;\n\tvelocity +=\t\t (velocityDiv * vec3(2.0) - vec3(1.0)) * velocityDivMult * rndFactor.xyz;\n\trotSpeed +=\t\t (rotSpeedDiv * 2.0 - 1.0) * rotSpeedDivMult * rndFactor.y;\n\taddInitialVelocity(localVelocity, rndFactor.xyz);\n#ifndef LOCAL_SPACE\n\toutVel = emitterMatrix * localVelocity + (radialVel + velocity) * emitterScale;\n#else\n\toutVel = (localVelocity + radialVel) / emitterScale + emitterMatrixInv * velocity;\n#endif\n\toutPos = inPos + outVel * delta;\n\toutAngle = inAngle + rotSpeed * delta;\n",particle_billboardVS:"\n\tquadXY = rotate(quadXY, inAngle, rotMatrix);\n\tvec3 localPos = billboard(particlePos, quadXY);\n",particle_blendAddPS:"\n\tdBlendModeFogFactor = 0.0;\n\trgb *= saturate(gammaCorrectInput(max(a, 0.0)));\n\tif ((rgb.r + rgb.g + rgb.b) < 0.000001) discard;\n",particle_blendMultiplyPS:"\n\trgb = mix(vec3(1.0), rgb, vec3(a));\n\tif (rgb.r + rgb.g + rgb.b > 2.99) discard;\n",particle_blendNormalPS:"\n\tif (a < 0.01) discard;\n",particle_cpuVS:"\nattribute vec4 particle_vertexData;\nattribute vec4 particle_vertexData2;\nattribute vec4 particle_vertexData3;\nattribute float particle_vertexData4;\n#ifndef USE_MESH\nattribute vec2 particle_vertexData5;\n#else\nattribute vec4 particle_vertexData5;\n#endif\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nuniform mat3 matrix_normal;\nuniform mat4 matrix_viewInverse;\nuniform float numParticles;\nuniform float lifetime;\nuniform float stretch;\nuniform float seed;\nuniform vec3 wrapBounds;\nuniform vec3 emitterScale;\nuniform vec3 faceTangent;\nuniform vec3 faceBinorm;\nuniform highp sampler2D internalTex0;\nuniform highp sampler2D internalTex1;\nuniform highp sampler2D internalTex2;\nuniform vec3 emitterPos;\nvarying vec4 texCoordsAlphaLife;\nvec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix)\n{\n\tfloat c = cos(pRotation);\n\tfloat s = sin(pRotation);\n\tmat2 m = mat2(c, -s, s, c);\n\trotMatrix = m;\n\treturn m * quadXY;\n}\nvec3 billboard(vec3 InstanceCoords, vec2 quadXY)\n{\n\tvec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y;\n\treturn pos;\n}\nvec3 customFace(vec3 InstanceCoords, vec2 quadXY)\n{\n\tvec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y;\n\treturn pos;\n}\nvoid main(void)\n{\n\tvec3 particlePos = particle_vertexData.xyz;\n\tvec3 inPos = particlePos;\n\tvec3 vertPos = particle_vertexData3.xyz;\n\tvec3 inVel = vec3(particle_vertexData2.w, particle_vertexData3.w, particle_vertexData5.x);\n\tfloat id = floor(particle_vertexData4);\n\tfloat rndFactor = fract(sin(id + 1.0 + seed));\n\tvec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));\n#ifdef LOCAL_SPACE\n\tinVel = mat3(matrix_model) * inVel;\n#endif\n\tvec2 velocityV = normalize((mat3(matrix_view) * inVel).xy);\n\tvec2 quadXY = vertPos.xy;\n#ifdef USE_MESH\n\ttexCoordsAlphaLife = vec4(particle_vertexData5.zw, particle_vertexData2.z, particle_vertexData.w);\n#else\n\ttexCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, particle_vertexData2.z, particle_vertexData.w);\n#endif\n\tmat2 rotMatrix;\n\tfloat inAngle = particle_vertexData2.x;\n\tvec3 particlePosMoved = vec3(0.0);\n\tvec3 meshLocalPos = particle_vertexData3.xyz;\n",particle_cpu_endVS:"\n\tlocalPos *= particle_vertexData2.y * emitterScale;\n\tlocalPos += particlePos;\n\tgl_Position = matrix_viewProjection * vec4(localPos, 1.0);\n",particle_customFaceVS:"\n\tquadXY = rotate(quadXY, inAngle, rotMatrix);\n\tvec3 localPos = customFace(particlePos, quadXY);\n",particle_endPS:"\n\trgb = addFog(rgb);\n\trgb = toneMap(rgb);\n\trgb = gammaCorrectOutput(rgb);\n\tgl_FragColor = vec4(rgb, a);\n}\n",particle_endVS:"\n\tlocalPos *= scale * emitterScale;\n\tlocalPos += particlePos;\n\t#ifdef SCREEN_SPACE\n\tgl_Position = vec4(localPos.x, localPos.y, 0.0, 1.0);\n\t#else\n\tgl_Position = matrix_viewProjection * vec4(localPos.xyz, 1.0);\n\t#endif\n",particle_halflambertPS:"\n\tvec3 negNormal = normal*0.5+0.5;\n\tvec3 posNormal = -normal*0.5+0.5;\n\tnegNormal *= negNormal;\n\tposNormal *= posNormal;\n",particle_initVS:"\nattribute vec4 particle_vertexData;\n#ifdef USE_MESH\nattribute vec2 particle_uv;\n#endif\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\nuniform mat3 matrix_normal;\nuniform mat4 matrix_viewInverse;\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nuniform float numParticles, numParticlesPot;\nuniform float graphSampleSize;\nuniform float graphNumSamples;\nuniform float stretch;\nuniform vec3 wrapBounds;\nuniform vec3 emitterScale, emitterPos, faceTangent, faceBinorm;\nuniform float rate, rateDiv, lifetime, deltaRandomnessStatic, scaleDivMult, alphaDivMult, seed, delta;\nuniform sampler2D particleTexOUT, particleTexIN;\nuniform highp sampler2D internalTex0;\nuniform highp sampler2D internalTex1;\nuniform highp sampler2D internalTex2;\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params;\n#endif\nvarying vec4 texCoordsAlphaLife;\nvec3 inPos;\nvec3 inVel;\nfloat inAngle;\nbool inShow;\nfloat inLife;\n",particle_lambertPS:"\n\tvec3 negNormal = max(normal, vec3(0.0));\n\tvec3 posNormal = max(-normal, vec3(0.0));\n",particle_lightingPS:"\n\tvec3 light = negNormal.x*lightCube[0] + posNormal.x*lightCube[1] +\n\t\t\t\t\t\tnegNormal.y*lightCube[2] + posNormal.y*lightCube[3] +\n\t\t\t\t\t\tnegNormal.z*lightCube[4] + posNormal.z*lightCube[5];\n\trgb *= light;\n",particle_localShiftVS:"\n\tparticlePos = (matrix_model * vec4(particlePos, 1.0)).xyz;\n",particle_meshVS:"\n\tvec3 localPos = meshLocalPos;\n\tlocalPos.xy = rotate(localPos.xy, inAngle, rotMatrix);\n\tlocalPos.yz = rotate(localPos.yz, inAngle, rotMatrix);\n\tbillboard(particlePos, quadXY);\n",particle_normalVS:"\n\tNormal = normalize(localPos + matrix_viewInverse[2].xyz);\n",particle_normalMapPS:"\n\tvec3 normalMap = normalize(texture2D(normalMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y)).xyz * 2.0 - 1.0);\n\tvec3 normal = ParticleMat * normalMap;\n",particle_pointAlongVS:"\n\tinAngle = atan(velocityV.x, velocityV.y);\n",particle_softPS:"\n\tfloat depth = getLinearScreenDepth();\n\tfloat particleDepth = vDepth;\n\tfloat depthDiff = saturate(abs(particleDepth - depth) * softening);\n\ta *= depthDiff;\n",particle_softVS:"\n\tvDepth = getLinearDepth(localPos);\n",particle_stretchVS:"\n\tvec3 moveDir = inVel * stretch;\n\tvec3 posPrev = particlePos - moveDir;\n\tposPrev += particlePosMoved;\n\tvec2 centerToVertexV = normalize((mat3(matrix_view) * localPos).xy);\n\tfloat interpolation = dot(-velocityV, centerToVertexV) * 0.5 + 0.5;\n\tparticlePos = mix(particlePos, posPrev, interpolation);\n",particle_TBNVS:"\n\tmat3 rot3 = mat3(rotMatrix[0][0], rotMatrix[0][1], 0.0, rotMatrix[1][0], rotMatrix[1][1], 0.0, 0.0, 0.0, 1.0);\n\tParticleMat = mat3(-matrix_viewInverse[0].xyz, -matrix_viewInverse[1].xyz, matrix_viewInverse[2].xyz) * rot3;\n",particle_wrapVS:"\n\tvec3 origParticlePos = particlePos;\n\tparticlePos -= matrix_model[3].xyz;\n\tparticlePos = mod(particlePos, wrapBounds) - wrapBounds * 0.5;\n\tparticlePos += matrix_model[3].xyz;\n\tparticlePosMoved = particlePos - origParticlePos;\n",reflDirPS:"\nvoid getReflDir(vec3 worldNormal, vec3 viewDir, float gloss, mat3 tbn) {\n\tdReflDirW = normalize(-reflect(viewDir, worldNormal));\n}\n",reflDirAnisoPS:"\nvoid getReflDir(vec3 worldNormal, vec3 viewDir, float gloss, mat3 tbn) {\n\tfloat roughness = sqrt(1.0 - min(gloss, 1.0));\n\tfloat anisotropy = material_anisotropy * roughness;\n\tvec3 anisotropicDirection = anisotropy >= 0.0 ? tbn[1] : tbn[0];\n\tvec3 anisotropicTangent = cross(anisotropicDirection, viewDir);\n\tvec3 anisotropicNormal = cross(anisotropicTangent, anisotropicDirection);\n\tvec3 bentNormal = normalize(mix(normalize(worldNormal), normalize(anisotropicNormal), anisotropy));\n\tdReflDirW = reflect(-viewDir, bentNormal);\n}\n",reflectionCCPS:"\n#ifdef LIT_CLEARCOAT\nvoid addReflectionCC(vec3 reflDir, float gloss) {\n\tccReflection += calcReflection(reflDir, gloss);\n}\n#endif\n",reflectionCubePS:"\nuniform samplerCube texture_cubeMap;\nuniform float material_reflectivity;\nvec3 calcReflection(vec3 reflDir, float gloss) {\n\tvec3 lookupVec = fixSeams(cubeMapProject(reflDir));\n\tlookupVec.x *= -1.0;\n\treturn $DECODE(textureCube(texture_cubeMap, lookupVec));\n}\nvoid addReflection(vec3 reflDir, float gloss) { \n\tdReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);\n}\n",reflectionEnvHQPS:"\n#ifndef ENV_ATLAS\n#define ENV_ATLAS\nuniform sampler2D texture_envAtlas;\n#endif\nuniform samplerCube texture_cubeMap;\nuniform float material_reflectivity;\nvec3 calcReflection(vec3 reflDir, float gloss) {\n\tvec3 dir = cubeMapProject(reflDir) * vec3(-1.0, 1.0, 1.0);\n\tvec2 uv = toSphericalUv(dir);\n\tfloat level = saturate(1.0 - gloss) * 5.0;\n\tfloat ilevel = floor(level);\n\tfloat flevel = level - ilevel;\n\tvec3 sharp = $DECODE_CUBEMAP(textureCube(texture_cubeMap, fixSeams(dir)));\n\tvec3 roughA = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel)));\n\tvec3 roughB = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel + 1.0)));\n\treturn processEnvironment(mix(sharp, mix(roughA, roughB, flevel), min(level, 1.0)));\n}\nvoid addReflection(vec3 reflDir, float gloss) { \n\tdReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);\n}\n",reflectionEnvPS:"\n#ifndef ENV_ATLAS\n#define ENV_ATLAS\nuniform sampler2D texture_envAtlas;\n#endif\nuniform float material_reflectivity;\nfloat shinyMipLevel(vec2 uv) {\n\tvec2 dx = dFdx(uv);\n\tvec2 dy = dFdy(uv);\n\tvec2 uv2 = vec2(fract(uv.x + 0.5), uv.y);\n\tvec2 dx2 = dFdx(uv2);\n\tvec2 dy2 = dFdy(uv2);\n\tfloat maxd = min(max(dot(dx, dx), dot(dy, dy)), max(dot(dx2, dx2), dot(dy2, dy2)));\n\treturn clamp(0.5 * log2(maxd) - 1.0 + textureBias, 0.0, 5.0);\n}\nvec3 calcReflection(vec3 reflDir, float gloss) {\n\tvec3 dir = cubeMapProject(reflDir) * vec3(-1.0, 1.0, 1.0);\n\tvec2 uv = toSphericalUv(dir);\n\tfloat level = saturate(1.0 - gloss) * 5.0;\n\tfloat ilevel = floor(level);\n\tfloat level2 = shinyMipLevel(uv * atlasSize);\n\tfloat ilevel2 = floor(level2);\n\tvec2 uv0, uv1;\n\tfloat weight;\n\tif (ilevel == 0.0) {\n\t\tuv0 = mapShinyUv(uv, ilevel2);\n\t\tuv1 = mapShinyUv(uv, ilevel2 + 1.0);\n\t\tweight = level2 - ilevel2;\n\t} else {\n\t\tuv0 = uv1 = mapRoughnessUv(uv, ilevel);\n\t\tweight = 0.0;\n\t}\n\tvec3 linearA = $DECODE(texture2D(texture_envAtlas, uv0));\n\tvec3 linearB = $DECODE(texture2D(texture_envAtlas, uv1));\n\tvec3 linear0 = mix(linearA, linearB, weight);\n\tvec3 linear1 = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel + 1.0)));\n\treturn processEnvironment(mix(linear0, linear1, level - ilevel));\n}\nvoid addReflection(vec3 reflDir, float gloss) { \n\tdReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);\n}\n",reflectionSpherePS:"\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nuniform sampler2D texture_sphereMap;\nuniform float material_reflectivity;\nvec3 calcReflection(vec3 reflDir, float gloss) {\n\tvec3 reflDirV = (mat3(matrix_view) * reflDir).xyz;\n\tfloat m = 2.0 * sqrt( dot(reflDirV.xy, reflDirV.xy) + (reflDirV.z+1.0)*(reflDirV.z+1.0) );\n\tvec2 sphereMapUv = reflDirV.xy / m + 0.5;\n\treturn $DECODE(texture2D(texture_sphereMap, sphereMapUv));\n}\nvoid addReflection(vec3 reflDir, float gloss) { \n\tdReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);\n}\n",reflectionSphereLowPS:"\nuniform sampler2D texture_sphereMap;\nuniform float material_reflectivity;\nvec3 calcReflection(vec3 reflDir, float gloss) {\n\tvec3 reflDirV = vNormalV;\n\tvec2 sphereMapUv = reflDirV.xy * 0.5 + 0.5;\n\treturn $DECODE(texture2D(texture_sphereMap, sphereMapUv));\n}\nvoid addReflection(vec3 reflDir, float gloss) { \n\tdReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);\n}\n",reflectionSheenPS:"\nvoid addReflectionSheen(vec3 worldNormal, vec3 viewDir, float gloss) {\n\tfloat NoV = dot(worldNormal, viewDir);\n\tfloat alphaG = gloss * gloss;\n\tfloat a = gloss < 0.25 ? -339.2 * alphaG + 161.4 * gloss - 25.9 : -8.48 * alphaG + 14.3 * gloss - 9.95;\n\tfloat b = gloss < 0.25 ? 44.0 * alphaG - 23.7 * gloss + 3.26 : 1.97 * alphaG - 3.27 * gloss + 0.72;\n\tfloat DG = exp( a * NoV + b ) + ( gloss < 0.25 ? 0.0 : 0.1 * ( gloss - 0.25 ) );\n\tsReflection += calcReflection(worldNormal, 0.0) * saturate(DG);\n}\n",refractionCubePS:"\nvec3 refract2(vec3 viewVec, vec3 normal, float IOR) {\n\tfloat vn = dot(viewVec, normal);\n\tfloat k = 1.0 - IOR * IOR * (1.0 - vn * vn);\n\tvec3 refrVec = IOR * viewVec - (IOR * vn + sqrt(k)) * normal;\n\treturn refrVec;\n}\nvoid addRefraction(\n\tvec3 worldNormal, \n\tvec3 viewDir, \n\tfloat thickness, \n\tfloat gloss, \n\tvec3 specularity, \n\tvec3 albedo, \n\tfloat transmission,\n\tfloat refractionIndex\n#if defined(LIT_IRIDESCENCE)\n\t, vec3 iridescenceFresnel,\n\tfloat iridescenceIntensity\n#endif \n) {\n\tvec4 tmpRefl = dReflection;\n\tvec3 reflectionDir = refract2(-viewDir, worldNormal, refractionIndex);\n\tdReflection = vec4(0);\n\taddReflection(reflectionDir, gloss);\n\tdDiffuseLight = mix(dDiffuseLight, dReflection.rgb * albedo, transmission);\n\tdReflection = tmpRefl;\n}\n",refractionDynamicPS:"\nuniform float material_invAttenuationDistance;\nuniform vec3 material_attenuation;\nvoid addRefraction(\n\tvec3 worldNormal, \n\tvec3 viewDir, \n\tfloat thickness, \n\tfloat gloss, \n\tvec3 specularity, \n\tvec3 albedo, \n\tfloat transmission,\n\tfloat refractionIndex\n#if defined(LIT_IRIDESCENCE)\n\t, vec3 iridescenceFresnel,\n\tfloat iridescenceIntensity\n#endif\n) {\n\tvec3 modelScale;\n\tmodelScale.x = length(vec3(matrix_model[0].xyz));\n\tmodelScale.y = length(vec3(matrix_model[1].xyz));\n\tmodelScale.z = length(vec3(matrix_model[2].xyz));\n\tvec3 refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndex)) * thickness * modelScale;\n\tvec4 pointOfRefraction = vec4(vPositionW + refractionVector, 1.0);\n\tvec4 projectionPoint = matrix_viewProjection * pointOfRefraction;\n\tvec2 uv = getGrabScreenPos(projectionPoint);\n\t#ifdef SUPPORTS_TEXLOD\n\t\tfloat iorToRoughness = (1.0 - gloss) * clamp((1.0 / refractionIndex) * 2.0 - 2.0, 0.0, 1.0);\n\t\tfloat refractionLod = log2(uScreenSize.x) * iorToRoughness;\n\t\tvec3 refraction = texture2DLodEXT(uSceneColorMap, uv, refractionLod).rgb;\n\t#else\n\t\tvec3 refraction = texture2D(uSceneColorMap, uv).rgb;\n\t#endif\n\tvec3 transmittance;\n\tif (material_invAttenuationDistance != 0.0)\n\t{\n\t\tvec3 attenuation = -log(material_attenuation) * material_invAttenuationDistance;\n\t\ttransmittance = exp(-attenuation * length(refractionVector));\n\t}\n\telse\n\t{\n\t\ttransmittance = refraction;\n\t}\n\tvec3 fresnel = vec3(1.0) - \n\t\tgetFresnel(\n\t\t\tdot(viewDir, worldNormal), \n\t\t\tgloss, \n\t\t\tspecularity\n\t\t#if defined(LIT_IRIDESCENCE)\n\t\t\t, iridescenceFresnel,\n\t\t\tiridescenceIntensity\n\t\t#endif\n\t\t);\n\tdDiffuseLight = mix(dDiffuseLight, refraction * transmittance * fresnel, transmission);\n}\n",reprojectPS:"\nvarying vec2 vUv0;\n#ifdef CUBEMAP_SOURCE\n\tuniform samplerCube sourceCube;\n#else\n\tuniform sampler2D sourceTex;\n#endif\n#ifdef USE_SAMPLES_TEX\n\tuniform sampler2D samplesTex;\n\tuniform vec2 samplesTexInverseSize;\n#endif\nuniform vec4 params;\nuniform vec2 params2;\nfloat targetFace() { return params.x; }\nfloat specularPower() { return params.y; }\nfloat sourceCubeSeamScale() { return params.z; }\nfloat targetCubeSeamScale() { return params.w; }\nfloat targetTotalPixels() { return params2.x; }\nfloat sourceTotalPixels() { return params2.y; }\nfloat PI = 3.141592653589793;\nfloat saturate(float x) {\n\treturn clamp(x, 0.0, 1.0);\n}\n"+po+"\n"+mo+"\nvec3 modifySeams(vec3 dir, float scale) {\n\tvec3 adir = abs(dir);\n\tfloat M = max(max(adir.x, adir.y), adir.z);\n\treturn dir / M * vec3(\n\t\tadir.x == M ? 1.0 : scale,\n\t\tadir.y == M ? 1.0 : scale,\n\t\tadir.z == M ? 1.0 : scale\n\t);\n}\nvec2 toSpherical(vec3 dir) {\n\treturn vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y));\n}\nvec3 fromSpherical(vec2 uv) {\n\treturn vec3(cos(uv.y) * sin(uv.x),\n\t\t\t\tsin(uv.y),\n\t\t\t\tcos(uv.y) * cos(uv.x));\n}\nvec3 getDirectionEquirect() {\n\treturn fromSpherical((vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0) * vec2(PI, PI * 0.5));\n}\nfloat signNotZero(float k){\n\treturn(k >= 0.0) ? 1.0 : -1.0;\n}\nvec2 signNotZero(vec2 v) {\n\treturn vec2(signNotZero(v.x), signNotZero(v.y));\n}\nvec3 octDecode(vec2 o) {\n\tvec3 v = vec3(o.x, 1.0 - abs(o.x) - abs(o.y), o.y);\n\tif (v.y < 0.0) {\n\t\tv.xz = (1.0 - abs(v.zx)) * signNotZero(v.xz);\n\t}\n\treturn normalize(v);\n}\nvec3 getDirectionOctahedral() {\n\treturn octDecode(vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0);\n}\nvec2 octEncode(in vec3 v) {\n\tfloat l1norm = abs(v.x) + abs(v.y) + abs(v.z);\n\tvec2 result = v.xz * (1.0 / l1norm);\n\tif (v.y < 0.0) {\n\t\tresult = (1.0 - abs(result.yx)) * signNotZero(result.xy);\n\t}\n\treturn result;\n}\n#ifdef CUBEMAP_SOURCE\n\tvec4 sampleCubemap(vec3 dir) {\n\t\treturn textureCube(sourceCube, modifySeams(dir, 1.0 - sourceCubeSeamScale()));\n\t}\n\tvec4 sampleCubemap(vec2 sph) {\n\treturn sampleCubemap(fromSpherical(sph));\n}\n\tvec4 sampleCubemap(vec3 dir, float mipLevel) {\n\t\treturn textureCubeLodEXT(sourceCube, modifySeams(dir, 1.0 - exp2(mipLevel) * sourceCubeSeamScale()), mipLevel);\n\t}\n\tvec4 sampleCubemap(vec2 sph, float mipLevel) {\n\t\treturn sampleCubemap(fromSpherical(sph), mipLevel);\n\t}\n#else\n\tvec4 sampleEquirect(vec2 sph) {\n\t\tvec2 uv = sph / vec2(PI * 2.0, PI) + 0.5;\n\t\treturn texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n\t}\n\tvec4 sampleEquirect(vec3 dir) {\n\t\treturn sampleEquirect(toSpherical(dir));\n\t}\n\tvec4 sampleEquirect(vec2 sph, float mipLevel) {\n\t\tvec2 uv = sph / vec2(PI * 2.0, PI) + 0.5;\n\t\treturn texture2DLodEXT(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel);\n\t}\n\tvec4 sampleEquirect(vec3 dir, float mipLevel) {\n\t\treturn sampleEquirect(toSpherical(dir), mipLevel);\n\t}\n\tvec4 sampleOctahedral(vec3 dir) {\n\t\tvec2 uv = octEncode(dir) * 0.5 + 0.5;\n\t\treturn texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n\t}\n\tvec4 sampleOctahedral(vec2 sph) {\n\t\treturn sampleOctahedral(fromSpherical(sph));\n\t}\n\tvec4 sampleOctahedral(vec3 dir, float mipLevel) {\n\t\tvec2 uv = octEncode(dir) * 0.5 + 0.5;\n\t\treturn texture2DLodEXT(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel);\n\t}\n\tvec4 sampleOctahedral(vec2 sph, float mipLevel) {\n\t\treturn sampleOctahedral(fromSpherical(sph), mipLevel);\n\t}\n#endif\nvec3 getDirectionCubemap() {\n\tvec2 st = vUv0 * 2.0 - 1.0;\n\tfloat face = targetFace();\n\tvec3 vec;\n\tif (face == 0.0) {\n\t\tvec = vec3(1, -st.y, -st.x);\n\t} else if (face == 1.0) {\n\t\tvec = vec3(-1, -st.y, st.x);\n\t} else if (face == 2.0) {\n\t\tvec = vec3(st.x, 1, st.y);\n\t} else if (face == 3.0) {\n\t\tvec = vec3(st.x, -1, -st.y);\n\t} else if (face == 4.0) {\n\t\tvec = vec3(st.x, -st.y, 1);\n\t} else {\n\t\tvec = vec3(-st.x, -st.y, -1);\n\t}\n\treturn normalize(modifySeams(vec, 1.0 / (1.0 - targetCubeSeamScale())));\n}\nmat3 matrixFromVector(vec3 n) {\n\tfloat a = 1.0 / (1.0 + n.z);\n\tfloat b = -n.x * n.y * a;\n\tvec3 b1 = vec3(1.0 - n.x * n.x * a, b, -n.x);\n\tvec3 b2 = vec3(b, 1.0 - n.y * n.y * a, -n.y);\n\treturn mat3(b1, b2, n);\n}\nmat3 matrixFromVectorSlow(vec3 n) {\n\tvec3 up = (1.0 - abs(n.y) <= 0.0000001) ? vec3(0.0, 0.0, n.y > 0.0 ? 1.0 : -1.0) : vec3(0.0, 1.0, 0.0);\n\tvec3 x = normalize(cross(up, n));\n\tvec3 y = cross(n, x);\n\treturn mat3(x, y, n);\n}\nvec4 reproject() {\n\tif (NUM_SAMPLES <= 1) {\n\t\treturn ENCODE_FUNC(DECODE_FUNC(SOURCE_FUNC(TARGET_FUNC())));\n\t} else {\n\t\tvec3 t = TARGET_FUNC();\n\t\tvec3 tu = dFdx(t);\n\t\tvec3 tv = dFdy(t);\n\t\tvec3 result = vec3(0.0);\n\t\tfor (float u = 0.0; u < NUM_SAMPLES_SQRT; ++u) {\n\t\t\tfor (float v = 0.0; v < NUM_SAMPLES_SQRT; ++v) {\n\t\t\t\tresult += DECODE_FUNC(SOURCE_FUNC(normalize(t +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttu * (u / NUM_SAMPLES_SQRT - 0.5) +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttv * (v / NUM_SAMPLES_SQRT - 0.5))));\n\t\t\t}\n\t\t}\n\t\treturn ENCODE_FUNC(result / (NUM_SAMPLES_SQRT * NUM_SAMPLES_SQRT));\n\t}\n}\nvec4 unpackFloat = vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0);\n#ifdef USE_SAMPLES_TEX\n\tvoid unpackSample(int i, out vec3 L, out float mipLevel) {\n\t\tfloat u = (float(i * 4) + 0.5) * samplesTexInverseSize.x;\n\t\tfloat v = (floor(u) + 0.5) * samplesTexInverseSize.y;\n\t\tvec4 raw;\n\t\traw.x = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n\t\traw.y = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n\t\traw.z = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n\t\traw.w = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat);\n\t\tL.xyz = raw.xyz * 2.0 - 1.0;\n\t\tmipLevel = raw.w * 8.0;\n\t}\n\tvec4 prefilterSamples() {\n\t\tmat3 vecSpace = matrixFromVectorSlow(TARGET_FUNC());\n\t\tvec3 L;\n\t\tfloat mipLevel;\n\t\tvec3 result = vec3(0.0);\n\t\tfloat totalWeight = 0.0;\n\t\tfor (int i = 0; i < NUM_SAMPLES; ++i) {\n\t\t\tunpackSample(i, L, mipLevel);\n\t\t\tresult += DECODE_FUNC(SOURCE_FUNC(vecSpace * L, mipLevel)) * L.z;\n\t\t\ttotalWeight += L.z;\n\t\t}\n\t\treturn ENCODE_FUNC(result / totalWeight);\n\t}\n\tvec4 prefilterSamplesUnweighted() {\n\t\tmat3 vecSpace = matrixFromVectorSlow(TARGET_FUNC());\n\t\tvec3 L;\n\t\tfloat mipLevel;\n\t\tvec3 result = vec3(0.0);\n\t\tfloat totalWeight = 0.0;\n\t\tfor (int i = 0; i < NUM_SAMPLES; ++i) {\n\t\t\tunpackSample(i, L, mipLevel);\n\t\t\tresult += DECODE_FUNC(SOURCE_FUNC(vecSpace * L, mipLevel));\n\t\t}\n\t\treturn ENCODE_FUNC(result / float(NUM_SAMPLES));\n\t}\n#endif\nvoid main(void) {\n\tgl_FragColor = PROCESS_FUNC();\n}\n",screenDepthPS:"\nuniform highp sampler2D uSceneDepthMap;\n#ifndef SCREENSIZE\n#define SCREENSIZE\nuniform vec4 uScreenSize;\n#endif\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\n#ifndef LINEARIZE_DEPTH\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params;\n#endif\n#define LINEARIZE_DEPTH\n#ifdef GL2\nfloat linearizeDepth(float z) {\n\tif (camera_params.w == 0.0)\n\t\treturn (camera_params.z * camera_params.y) / (camera_params.y + z * (camera_params.z - camera_params.y));\n\telse\n\t\treturn camera_params.z + z * (camera_params.y - camera_params.z);\n}\n#else\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n\tconst vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n\treturn dot(rgbaDepth, bitShift);\n}\n#endif\n#endif\n#endif\nfloat getLinearScreenDepth(vec2 uv) {\n\t#ifdef GL2\n\t\treturn linearizeDepth(texture2D(uSceneDepthMap, uv).r);\n\t#else\n\t\treturn unpackFloat(texture2D(uSceneDepthMap, uv)) * camera_params.y;\n\t#endif\n}\n#ifndef VERTEXSHADER\nfloat getLinearScreenDepth() {\n\tvec2 uv = gl_FragCoord.xy * uScreenSize.zw;\n\treturn getLinearScreenDepth(uv);\n}\n#endif\nfloat getLinearDepth(vec3 pos) {\n\treturn -(matrix_view * vec4(pos, 1.0)).z;\n}\n",shadowCascadesPS:"\nconst float maxCascades = 4.0;\nmat4 cascadeShadowMat;\nvoid getShadowCascadeMatrix(mat4 shadowMatrixPalette[4], float shadowCascadeDistances[4], float shadowCascadeCount) {\n\tfloat depth = 1.0 / gl_FragCoord.w;\n\tfloat cascadeIndex = 0.0;\n\tfor (float i = 0.0; i < maxCascades; i++) {\n\t\tif (depth < shadowCascadeDistances[int(i)]) {\n\t\t\tcascadeIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tcascadeIndex = min(cascadeIndex, shadowCascadeCount - 1.0);\n\t#ifdef GL2\n\t\tcascadeShadowMat = shadowMatrixPalette[int(cascadeIndex)];\n\t#else\n\t\tif (cascadeIndex == 0.0) {\n\t\t\tcascadeShadowMat = shadowMatrixPalette[0];\n\t\t}\n\t\telse if (cascadeIndex == 1.0) {\n\t\t\tcascadeShadowMat = shadowMatrixPalette[1];\n\t\t}\n\t\telse if (cascadeIndex == 2.0) {\n\t\t\tcascadeShadowMat = shadowMatrixPalette[2];\n\t\t}\n\t\telse {\n\t\t\tcascadeShadowMat = shadowMatrixPalette[3];\n\t\t}\n\t#endif\n}\nvoid fadeShadow(float shadowCascadeDistances[4]) {\t\t\t\t \n\tfloat depth = 1.0 / gl_FragCoord.w;\n\tif (depth > shadowCascadeDistances[int(maxCascades - 1.0)]) {\n\t\tdShadowCoord.z = -9999999.0;\n\t}\n}\n",shadowEVSMPS:"\nfloat VSM$(sampler2D tex, vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n\tvec3 moments = texture2D(tex, texCoords).xyz;\n\treturn calculateEVSM(moments, Z, vsmBias, exponent);\n}\nfloat getShadowVSM$(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n\treturn VSM$(shadowMap, shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent);\n}\nfloat getShadowSpotVSM$(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n\treturn VSM$(shadowMap, shadowCoord.xy, shadowParams.x, length(lightDir) * shadowParams.w + shadowParams.z, shadowParams.y, exponent);\n}\n",shadowEVSMnPS:"\nfloat VSM$(TEXTURE_ACCEPT(tex), vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n\tfloat pixelSize = 1.0 / resolution;\n\ttexCoords -= vec2(pixelSize);\n\tvec3 s00 = texture2D(tex, texCoords).xyz;\n\tvec3 s10 = texture2D(tex, texCoords + vec2(pixelSize, 0)).xyz;\n\tvec3 s01 = texture2D(tex, texCoords + vec2(0, pixelSize)).xyz;\n\tvec3 s11 = texture2D(tex, texCoords + vec2(pixelSize)).xyz;\n\tvec2 fr = fract(texCoords * resolution);\n\tvec3 h0 = mix(s00, s10, fr.x);\n\tvec3 h1 = mix(s01, s11, fr.x);\n\tvec3 moments = mix(h0, h1, fr.y);\n\treturn calculateEVSM(moments, Z, vsmBias, exponent);\n}\nfloat getShadowVSM$(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n\treturn VSM$(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent);\n}\nfloat getShadowSpotVSM$(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n\treturn VSM$(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, length(lightDir) * shadowParams.w + shadowParams.z, shadowParams.y, exponent);\n}\n",shadowPCSSPS:"\n#define PCSS_SAMPLE_COUNT 16\nuniform float pcssDiskSamples[PCSS_SAMPLE_COUNT];\nuniform float pcssSphereSamples[PCSS_SAMPLE_COUNT];\nvec2 vogelDisk(int sampleIndex, float count, float phi, float r) {\n\tconst float GoldenAngle = 2.4;\n\tfloat theta = float(sampleIndex) * GoldenAngle + phi;\n\tfloat sine = sin(theta);\n\tfloat cosine = cos(theta);\n\treturn vec2(r * cosine, r * sine);\n}\nvec3 vogelSphere(int sampleIndex, float count, float phi, float r) {\n\tconst float GoldenAngle = 2.4;\n\tfloat theta = float(sampleIndex) * GoldenAngle + phi;\n\tfloat weight = float(sampleIndex) / count;\n\treturn vec3(cos(theta) * r, weight, sin(theta) * r);\n}\nfloat noise(vec2 screenPos) {\n\tconst float PHI = 1.61803398874989484820459;\n\treturn fract(sin(dot(screenPos * PHI, screenPos)) * screenPos.x);\n}\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n\tconst vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n\treturn dot(rgbaDepth, bitShift);\n}\n#endif\nfloat viewSpaceDepth(float depth, mat4 invProjection) {\n\tfloat z = depth * 2.0 - 1.0;\n\tvec4 clipSpace = vec4(0.0, 0.0, z, 1.0);\n\tvec4 viewSpace = invProjection * clipSpace;\n\treturn viewSpace.z;\n}\nfloat PCSSBlockerDistance(TEXTURE_ACCEPT(shadowMap), vec2 sampleCoords[PCSS_SAMPLE_COUNT], vec2 shadowCoords, vec2 searchSize, float z) {\n\tfloat blockers = 0.0;\n\tfloat averageBlocker = 0.0;\n\tfor (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {\n\t\tvec2 offset = sampleCoords[i] * searchSize;\n\t\tvec2 sampleUV = shadowCoords + offset;\n\t#ifdef GL2\n\t\tfloat blocker = textureLod(shadowMap, sampleUV, 0.0).r;\n\t#else\n\t\tfloat blocker = unpackFloat(texture2D(shadowMap, sampleUV));\n\t#endif\t\t\n\t\tfloat isBlocking = step(blocker, z);\n\t\tblockers += isBlocking;\n\t\taverageBlocker += blocker * isBlocking;\n\t}\n\tif (blockers > 0.0)\n\t\treturn averageBlocker /= blockers;\n\treturn -1.0;\n}\nfloat PCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoords, vec4 cameraParams, vec2 shadowSearchArea) {\n\tfloat receiverDepth = shadowCoords.z;\n#ifndef GL2\n\treceiverDepth *= 1.0 / (cameraParams.y - cameraParams.z);\n#endif\n\tvec2 samplePoints[PCSS_SAMPLE_COUNT];\n\tfloat noise = noise( gl_FragCoord.xy ) * 2.0 * PI;\n\tfor (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {\n\t\tfloat pcssPresample = pcssDiskSamples[i];\n\t\tsamplePoints[i] = vogelDisk(i, float(PCSS_SAMPLE_COUNT), noise, pcssPresample);\n\t}\n\tfloat averageBlocker = PCSSBlockerDistance(TEXTURE_PASS(shadowMap), samplePoints, shadowCoords.xy, shadowSearchArea, receiverDepth);\n\tif (averageBlocker == -1.0) {\n\t\treturn 1.0;\n\t} else {\n\t\tvec2 filterRadius = ((receiverDepth - averageBlocker) / averageBlocker) * shadowSearchArea * cameraParams.x;\n\t\tfloat shadow = 0.0;\n\t\tfor (int i = 0; i < PCSS_SAMPLE_COUNT; i ++)\n\t\t{\n\t\t\tvec2 sampleUV = samplePoints[i] * filterRadius;\n\t\t\tsampleUV = shadowCoords.xy + sampleUV;\n\t\t#ifdef GL2\n\t\t\tfloat depth = textureLod(shadowMap, sampleUV, 0.0).r;\n\t\t#else\n\t\t\tfloat depth = unpackFloat(texture2D(shadowMap, sampleUV));\n\t\t#endif\n\t\t\tshadow += step(receiverDepth, depth);\n\t\t}\n\t\treturn shadow / float(PCSS_SAMPLE_COUNT);\n\t} \n}\nfloat PCSSCubeBlockerDistance(samplerCube shadowMap, vec3 lightDirNorm, vec3 samplePoints[PCSS_SAMPLE_COUNT], float z, float shadowSearchArea) {\n\tfloat blockers = 0.0;\n\tfloat averageBlocker = 0.0;\n\tfor (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {\n\t\tvec3 sampleDir = lightDirNorm + samplePoints[i] * shadowSearchArea;\n\t\tsampleDir = normalize(sampleDir);\n\t#ifdef GL2\n\t\tfloat blocker = textureCubeLodEXT(shadowMap, sampleDir, 0.0).r;\n\t#else\n\t\tfloat blocker = unpackFloat(textureCube(shadowMap, sampleDir));\n\t#endif\n\t\tfloat isBlocking = step(blocker, z);\n\t\tblockers += isBlocking;\n\t\taverageBlocker += blocker * isBlocking;\n\t}\n\tif (blockers > 0.0)\n\t\treturn averageBlocker /= float(blockers);\n\treturn -1.0;\n}\nfloat PCSSCube(samplerCube shadowMap, vec4 shadowParams, vec3 shadowCoords, vec4 cameraParams, float shadowSearchArea, vec3 lightDir) {\n\t\n\tvec3 samplePoints[PCSS_SAMPLE_COUNT];\n\tfloat noise = noise( gl_FragCoord.xy ) * 2.0 * PI;\n\tfor (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {\n\t\tfloat r = pcssSphereSamples[i];\n\t\tsamplePoints[i] = vogelSphere(i, float(PCSS_SAMPLE_COUNT), noise, r);\n\t}\n\tfloat receiverDepth = length(lightDir) * shadowParams.w + shadowParams.z;\n\tvec3 lightDirNorm = normalize(lightDir);\n\t\n\tfloat averageBlocker = PCSSCubeBlockerDistance(shadowMap, lightDirNorm, samplePoints, receiverDepth, shadowSearchArea);\n\tif (averageBlocker == -1.0) {\n\t\treturn 1.0;\n\t} else {\n\t\tfloat filterRadius = ((receiverDepth - averageBlocker) / averageBlocker) * shadowSearchArea;\n\t\tfloat shadow = 0.0;\n\t\tfor (int i = 0; i < PCSS_SAMPLE_COUNT; i++)\n\t\t{\n\t\t\tvec3 offset = samplePoints[i] * filterRadius;\n\t\t\tvec3 sampleDir = lightDirNorm + offset;\n\t\t\tsampleDir = normalize(sampleDir);\n\t\t\t#ifdef GL2\n\t\t\t\tfloat depth = textureCubeLodEXT(shadowMap, sampleDir, 0.0).r;\n\t\t\t#else\n\t\t\t\tfloat depth = unpackFloat(textureCube(shadowMap, sampleDir));\n\t\t\t#endif\n\t\t\tshadow += step(receiverDepth, depth);\n\t\t}\n\t\treturn shadow / float(PCSS_SAMPLE_COUNT);\n\t}\n}\nfloat getShadowPointPCSS(samplerCube shadowMap, vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec2 shadowSearchArea, vec3 lightDir) {\n\treturn PCSSCube(shadowMap, shadowParams, shadowCoord, cameraParams, shadowSearchArea.x, lightDir);\n}\nfloat getShadowSpotPCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec2 shadowSearchArea, vec3 lightDir) {\n\treturn PCSS(TEXTURE_PASS(shadowMap), shadowCoord, cameraParams, shadowSearchArea);\n}\nfloat getShadowPCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec2 shadowSearchArea, vec3 lightDir) {\n\treturn PCSS(TEXTURE_PASS(shadowMap), shadowCoord, cameraParams, shadowSearchArea);\n}\n",shadowSampleCoordPS:"\nvec3 getShadowSampleCoord$LIGHT(mat4 shadowTransform, vec4 shadowParams, vec3 worldPosition, vec3 lightPos, inout vec3 lightDir, vec3 lightDirNorm, vec3 normal) {\n\tvec3 surfacePosition = worldPosition;\n#ifdef SHADOW_SAMPLE_POINT\n\t#ifdef SHADOW_SAMPLE_NORMAL_OFFSET\n\t\tfloat distScale = length(lightDir);\n\t\tsurfacePosition = worldPosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;\n\t\tlightDir = surfacePosition - lightPos;\n\t\treturn lightDir;\n\t#endif\n#else\n\t#ifdef SHADOW_SAMPLE_SOURCE_ZBUFFER\n\t\t#ifdef SHADOW_SAMPLE_NORMAL_OFFSET\n\t\t\tsurfacePosition = worldPosition + normal * shadowParams.y;\n\t\t#endif\n\t#else\n\t\t#ifdef SHADOW_SAMPLE_NORMAL_OFFSET\n\t\t\t#ifdef SHADOW_SAMPLE_ORTHO\n\t\t\t\tfloat distScale = 1.0;\n\t\t\t#else\n\t\t\t\tfloat distScale = abs(dot(vPositionW - lightPos, lightDirNorm));\n\t\t\t#endif\n\t\t\tsurfacePosition = worldPosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;\n\t\t#endif\n\t#endif\n\tvec4 positionInShadowSpace = shadowTransform * vec4(surfacePosition, 1.0);\n\t#ifdef SHADOW_SAMPLE_ORTHO\n\t\tpositionInShadowSpace.z = saturate(positionInShadowSpace.z) - 0.0001;\n\t#else\n\t\t#ifdef SHADOW_SAMPLE_SOURCE_ZBUFFER\n\t\t\tpositionInShadowSpace.xyz /= positionInShadowSpace.w;\n\t\t#else\n\t\t\tpositionInShadowSpace.xy /= positionInShadowSpace.w;\n\t\t\tpositionInShadowSpace.z = length(lightDir) * shadowParams.w;\n\t\t#endif\n\t#endif\n\t#ifdef SHADOW_SAMPLE_Z_BIAS\n\t\tpositionInShadowSpace.z += getShadowBias(shadowParams.x, shadowParams.z);\n\t#endif\n\tsurfacePosition = positionInShadowSpace.xyz;\n#endif\n\treturn surfacePosition;\n}\n",shadowStandardPS:"\nvec3 lessThan2(vec3 a, vec3 b) {\n\treturn clamp((b - a)*1000.0, 0.0, 1.0);\n}\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\n\tfloat unpackFloat(vec4 rgbaDepth) {\n\t\tconst vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n\t\treturn dot(rgbaDepth, bitShift);\n\t}\n#endif\n#ifdef GL2\nfloat _getShadowPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec3 shadowParams) {\n\tfloat z = shadowCoord.z;\n\tvec2 uv = shadowCoord.xy * shadowParams.x;\n\tfloat shadowMapSizeInv = 1.0 / shadowParams.x;\n\tvec2 base_uv = floor(uv + 0.5);\n\tfloat s = (uv.x + 0.5 - base_uv.x);\n\tfloat t = (uv.y + 0.5 - base_uv.y);\n\tbase_uv -= vec2(0.5);\n\tbase_uv *= shadowMapSizeInv;\n\tfloat sum = 0.0;\n\tfloat uw0 = (3.0 - 2.0 * s);\n\tfloat uw1 = (1.0 + 2.0 * s);\n\tfloat u0 = (2.0 - s) / uw0 - 1.0;\n\tfloat u1 = s / uw1 + 1.0;\n\tfloat vw0 = (3.0 - 2.0 * t);\n\tfloat vw1 = (1.0 + 2.0 * t);\n\tfloat v0 = (2.0 - t) / vw0 - 1.0;\n\tfloat v1 = t / vw1 + 1.0;\n\tu0 = u0 * shadowMapSizeInv + base_uv.x;\n\tv0 = v0 * shadowMapSizeInv + base_uv.y;\n\tu1 = u1 * shadowMapSizeInv + base_uv.x;\n\tv1 = v1 * shadowMapSizeInv + base_uv.y;\n\tsum += uw0 * vw0 * textureShadow(shadowMap, vec3(u0, v0, z));\n\tsum += uw1 * vw0 * textureShadow(shadowMap, vec3(u1, v0, z));\n\tsum += uw0 * vw1 * textureShadow(shadowMap, vec3(u0, v1, z));\n\tsum += uw1 * vw1 * textureShadow(shadowMap, vec3(u1, v1, z));\n\tsum *= 1.0f / 16.0;\n\treturn sum;\n}\nfloat getShadowPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n\treturn _getShadowPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);\n}\nfloat getShadowSpotPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n\treturn _getShadowPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);\n}\nfloat getShadowPCF1x1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n\treturn textureShadow(shadowMap, shadowCoord);\n}\nfloat getShadowSpotPCF1x1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n\treturn textureShadow(shadowMap, shadowCoord);\n}\n#else\nfloat _xgetShadowPCF3x3(mat3 depthKernel, vec3 shadowCoord, sampler2D shadowMap, vec3 shadowParams) {\n\tmat3 shadowKernel;\n\tvec3 shadowZ = vec3(shadowCoord.z);\n\tshadowKernel[0] = vec3(greaterThan(depthKernel[0], shadowZ));\n\tshadowKernel[1] = vec3(greaterThan(depthKernel[1], shadowZ));\n\tshadowKernel[2] = vec3(greaterThan(depthKernel[2], shadowZ));\n\tvec2 fractionalCoord = fract( shadowCoord.xy * shadowParams.x );\n\tshadowKernel[0] = mix(shadowKernel[0], shadowKernel[1], fractionalCoord.x);\n\tshadowKernel[1] = mix(shadowKernel[1], shadowKernel[2], fractionalCoord.x);\n\tvec4 shadowValues;\n\tshadowValues.x = mix(shadowKernel[0][0], shadowKernel[0][1], fractionalCoord.y);\n\tshadowValues.y = mix(shadowKernel[0][1], shadowKernel[0][2], fractionalCoord.y);\n\tshadowValues.z = mix(shadowKernel[1][0], shadowKernel[1][1], fractionalCoord.y);\n\tshadowValues.w = mix(shadowKernel[1][1], shadowKernel[1][2], fractionalCoord.y);\n\treturn dot( shadowValues, vec4( 1.0 ) ) * 0.25;\n}\nfloat _getShadowPCF3x3(sampler2D shadowMap, vec3 shadowCoord, vec3 shadowParams) {\n\tfloat xoffset = 1.0 / shadowParams.x;\n\tfloat dx0 = -xoffset;\n\tfloat dx1 = xoffset;\n\tmat3 depthKernel;\n\tdepthKernel[0][0] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(dx0, dx0)));\n\tdepthKernel[0][1] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(dx0, 0.0)));\n\tdepthKernel[0][2] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(dx0, dx1)));\n\tdepthKernel[1][0] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(0.0, dx0)));\n\tdepthKernel[1][1] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy));\n\tdepthKernel[1][2] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(0.0, dx1)));\n\tdepthKernel[2][0] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(dx1, dx0)));\n\tdepthKernel[2][1] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(dx1, 0.0)));\n\tdepthKernel[2][2] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(dx1, dx1)));\n\treturn _xgetShadowPCF3x3(depthKernel, shadowCoord, shadowMap, shadowParams);\n}\nfloat getShadowPCF3x3(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n\treturn _getShadowPCF3x3(shadowMap, shadowCoord, shadowParams.xyz);\n}\nfloat getShadowSpotPCF3x3(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n\treturn _getShadowPCF3x3(shadowMap, shadowCoord, shadowParams.xyz);\n}\nfloat _getShadowPCF1x1(sampler2D shadowMap, vec3 shadowCoord) {\n\tfloat shadowSample = unpackFloat(textureShadow(shadowMap, shadowCoord.xy));\n\treturn shadowSample > shadowCoord.z ? 1.0 : 0.0;\n}\nfloat getShadowPCF1x1(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n\treturn _getShadowPCF1x1(shadowMap, shadowCoord);\n}\nfloat getShadowSpotPCF1x1(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n\treturn _getShadowPCF1x1(shadowMap, shadowCoord);\n}\n#endif\n#ifndef WEBGPU\nfloat _getShadowPoint(samplerCube shadowMap, vec4 shadowParams, vec3 dir) {\n\tvec3 tc = normalize(dir);\n\tvec3 tcAbs = abs(tc);\n\tvec4 dirX = vec4(1,0,0, tc.x);\n\tvec4 dirY = vec4(0,1,0, tc.y);\n\tfloat majorAxisLength = tc.z;\n\tif ((tcAbs.x > tcAbs.y) && (tcAbs.x > tcAbs.z)) {\n\t\tdirX = vec4(0,0,1, tc.z);\n\t\tdirY = vec4(0,1,0, tc.y);\n\t\tmajorAxisLength = tc.x;\n\t} else if ((tcAbs.y > tcAbs.x) && (tcAbs.y > tcAbs.z)) {\n\t\tdirX = vec4(1,0,0, tc.x);\n\t\tdirY = vec4(0,0,1, tc.z);\n\t\tmajorAxisLength = tc.y;\n\t}\n\tfloat shadowParamsInFaceSpace = ((1.0/shadowParams.x) * 2.0) * abs(majorAxisLength);\n\tvec3 xoffset = (dirX.xyz * shadowParamsInFaceSpace);\n\tvec3 yoffset = (dirY.xyz * shadowParamsInFaceSpace);\n\tvec3 dx0 = -xoffset;\n\tvec3 dy0 = -yoffset;\n\tvec3 dx1 = xoffset;\n\tvec3 dy1 = yoffset;\n\tmat3 shadowKernel;\n\tmat3 depthKernel;\n\tdepthKernel[0][0] = unpackFloat(textureCube(shadowMap, tc + dx0 + dy0));\n\tdepthKernel[0][1] = unpackFloat(textureCube(shadowMap, tc + dx0));\n\tdepthKernel[0][2] = unpackFloat(textureCube(shadowMap, tc + dx0 + dy1));\n\tdepthKernel[1][0] = unpackFloat(textureCube(shadowMap, tc + dy0));\n\tdepthKernel[1][1] = unpackFloat(textureCube(shadowMap, tc));\n\tdepthKernel[1][2] = unpackFloat(textureCube(shadowMap, tc + dy1));\n\tdepthKernel[2][0] = unpackFloat(textureCube(shadowMap, tc + dx1 + dy0));\n\tdepthKernel[2][1] = unpackFloat(textureCube(shadowMap, tc + dx1));\n\tdepthKernel[2][2] = unpackFloat(textureCube(shadowMap, tc + dx1 + dy1));\n\tvec3 shadowZ = vec3(length(dir) * shadowParams.w + shadowParams.z);\n\tshadowKernel[0] = vec3(lessThan2(depthKernel[0], shadowZ));\n\tshadowKernel[1] = vec3(lessThan2(depthKernel[1], shadowZ));\n\tshadowKernel[2] = vec3(lessThan2(depthKernel[2], shadowZ));\n\tvec2 uv = (vec2(dirX.w, dirY.w) / abs(majorAxisLength)) * 0.5;\n\tvec2 fractionalCoord = fract( uv * shadowParams.x );\n\tshadowKernel[0] = mix(shadowKernel[0], shadowKernel[1], fractionalCoord.x);\n\tshadowKernel[1] = mix(shadowKernel[1], shadowKernel[2], fractionalCoord.x);\n\tvec4 shadowValues;\n\tshadowValues.x = mix(shadowKernel[0][0], shadowKernel[0][1], fractionalCoord.y);\n\tshadowValues.y = mix(shadowKernel[0][1], shadowKernel[0][2], fractionalCoord.y);\n\tshadowValues.z = mix(shadowKernel[1][0], shadowKernel[1][1], fractionalCoord.y);\n\tshadowValues.w = mix(shadowKernel[1][1], shadowKernel[1][2], fractionalCoord.y);\n\treturn 1.0 - dot( shadowValues, vec4( 1.0 ) ) * 0.25;\n}\nfloat getShadowPointPCF3x3(samplerCube shadowMap, vec3 shadowCoord, vec4 shadowParams, vec3 lightDir) {\n\treturn _getShadowPoint(shadowMap, shadowParams, lightDir);\n}\n#endif\n",shadowStandardGL2PS:"\nfloat _getShadowPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec3 shadowParams) {\n\tfloat z = shadowCoord.z;\n\tvec2 uv = shadowCoord.xy * shadowParams.x;\n\tfloat shadowMapSizeInv = 1.0 / shadowParams.x;\n\tvec2 base_uv = floor(uv + 0.5);\n\tfloat s = (uv.x + 0.5 - base_uv.x);\n\tfloat t = (uv.y + 0.5 - base_uv.y);\n\tbase_uv -= vec2(0.5);\n\tbase_uv *= shadowMapSizeInv;\n\tfloat uw0 = (4.0 - 3.0 * s);\n\tfloat uw1 = 7.0;\n\tfloat uw2 = (1.0 + 3.0 * s);\n\tfloat u0 = (3.0 - 2.0 * s) / uw0 - 2.0;\n\tfloat u1 = (3.0 + s) / uw1;\n\tfloat u2 = s / uw2 + 2.0;\n\tfloat vw0 = (4.0 - 3.0 * t);\n\tfloat vw1 = 7.0;\n\tfloat vw2 = (1.0 + 3.0 * t);\n\tfloat v0 = (3.0 - 2.0 * t) / vw0 - 2.0;\n\tfloat v1 = (3.0 + t) / vw1;\n\tfloat v2 = t / vw2 + 2.0;\n\tfloat sum = 0.0;\n\tu0 = u0 * shadowMapSizeInv + base_uv.x;\n\tv0 = v0 * shadowMapSizeInv + base_uv.y;\n\tu1 = u1 * shadowMapSizeInv + base_uv.x;\n\tv1 = v1 * shadowMapSizeInv + base_uv.y;\n\tu2 = u2 * shadowMapSizeInv + base_uv.x;\n\tv2 = v2 * shadowMapSizeInv + base_uv.y;\n\tsum += uw0 * vw0 * textureShadow(shadowMap, vec3(u0, v0, z));\n\tsum += uw1 * vw0 * textureShadow(shadowMap, vec3(u1, v0, z));\n\tsum += uw2 * vw0 * textureShadow(shadowMap, vec3(u2, v0, z));\n\tsum += uw0 * vw1 * textureShadow(shadowMap, vec3(u0, v1, z));\n\tsum += uw1 * vw1 * textureShadow(shadowMap, vec3(u1, v1, z));\n\tsum += uw2 * vw1 * textureShadow(shadowMap, vec3(u2, v1, z));\n\tsum += uw0 * vw2 * textureShadow(shadowMap, vec3(u0, v2, z));\n\tsum += uw1 * vw2 * textureShadow(shadowMap, vec3(u1, v2, z));\n\tsum += uw2 * vw2 * textureShadow(shadowMap, vec3(u2, v2, z));\n\tsum *= 1.0f / 144.0;\n\tsum = saturate(sum);\n\treturn sum;\n}\nfloat getShadowPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n\treturn _getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);\n}\nfloat getShadowSpotPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n\treturn _getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);\n}\n",shadowVSM8PS:"\nfloat calculateVSM8(vec3 moments, float Z, float vsmBias) {\n\tfloat VSMBias = vsmBias;\n\tfloat depthScale = VSMBias * Z;\n\tfloat minVariance1 = depthScale * depthScale;\n\treturn chebyshevUpperBound(moments.xy, Z, minVariance1, 0.1);\n}\nfloat decodeFloatRG(vec2 rg) {\n\treturn rg.y*(1.0/255.0) + rg.x;\n}\nfloat VSM8(TEXTURE_ACCEPT(tex), vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n\tvec4 c = texture2D(tex, texCoords);\n\tvec3 moments = vec3(decodeFloatRG(c.xy), decodeFloatRG(c.zw), 0.0);\n\treturn calculateVSM8(moments, Z, vsmBias);\n}\nfloat getShadowVSM8(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n\treturn VSM8(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, 0.0);\n}\nfloat getShadowSpotVSM8(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n\treturn VSM8(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, length(lightDir) * shadowParams.w + shadowParams.z, shadowParams.y, 0.0);\n}\n",shadowVSM_commonPS:"\nfloat linstep(float a, float b, float v) {\n\treturn saturate((v - a) / (b - a));\n}\nfloat reduceLightBleeding(float pMax, float amount) {\n return linstep(amount, 1.0, pMax);\n}\nfloat chebyshevUpperBound(vec2 moments, float mean, float minVariance, float lightBleedingReduction) {\n\tfloat variance = moments.y - (moments.x * moments.x);\n\tvariance = max(variance, minVariance);\n\tfloat d = mean - moments.x;\n\tfloat pMax = variance / (variance + (d * d));\n\tpMax = reduceLightBleeding(pMax, lightBleedingReduction);\n\treturn (mean <= moments.x ? 1.0 : pMax);\n}\nfloat calculateEVSM(vec3 moments, float Z, float vsmBias, float exponent) {\n\tZ = 2.0 * Z - 1.0;\n\tfloat warpedDepth = exp(exponent * Z);\n\tmoments.xy += vec2(warpedDepth, warpedDepth*warpedDepth) * (1.0 - moments.z);\n\tfloat VSMBias = vsmBias;\n\tfloat depthScale = VSMBias * exponent * warpedDepth;\n\tfloat minVariance1 = depthScale * depthScale;\n\treturn chebyshevUpperBound(moments.xy, warpedDepth, minVariance1, 0.1);\n}\n",skinBatchConstVS:"\nattribute float vertex_boneIndices;\nuniform vec4 matrix_pose[BONE_LIMIT * 3];\nmat4 getBoneMatrix(const in float i) {\n\tvec4 v1 = matrix_pose[int(3.0 * i)];\n\tvec4 v2 = matrix_pose[int(3.0 * i + 1.0)];\n\tvec4 v3 = matrix_pose[int(3.0 * i + 2.0)];\n\treturn mat4(\n\t\tv1.x, v2.x, v3.x, 0,\n\t\tv1.y, v2.y, v3.y, 0,\n\t\tv1.z, v2.z, v3.z, 0,\n\t\tv1.w, v2.w, v3.w, 1\n\t);\n}\n",skinBatchTexVS:"\nattribute float vertex_boneIndices;\nuniform highp sampler2D texture_poseMap;\nuniform vec4 texture_poseMapSize;\nmat4 getBoneMatrix(const in float i) {\n\tfloat j = i * 3.0;\n\tfloat dx = texture_poseMapSize.z;\n\tfloat dy = texture_poseMapSize.w;\n\tfloat y = floor(j * dx);\n\tfloat x = j - (y * texture_poseMapSize.x);\n\ty = dy * (y + 0.5);\n\tvec4 v1 = texture2D(texture_poseMap, vec2(dx * (x + 0.5), y));\n\tvec4 v2 = texture2D(texture_poseMap, vec2(dx * (x + 1.5), y));\n\tvec4 v3 = texture2D(texture_poseMap, vec2(dx * (x + 2.5), y));\n\treturn mat4(\n\t\tv1.x, v2.x, v3.x, 0,\n\t\tv1.y, v2.y, v3.y, 0,\n\t\tv1.z, v2.z, v3.z, 0,\n\t\tv1.w, v2.w, v3.w, 1\n\t);\n}\n",skinConstVS:"\nattribute vec4 vertex_boneWeights;\nattribute vec4 vertex_boneIndices;\nuniform vec4 matrix_pose[BONE_LIMIT * 3];\nvoid getBoneMatrix(const in float i, out vec4 v1, out vec4 v2, out vec4 v3) {\n\tv1 = matrix_pose[int(3.0 * i)];\n\tv2 = matrix_pose[int(3.0 * i + 1.0)];\n\tv3 = matrix_pose[int(3.0 * i + 2.0)];\n}\nmat4 getSkinMatrix(const in vec4 indices, const in vec4 weights) {\n\tvec4 a1, a2, a3;\n\tgetBoneMatrix(indices.x, a1, a2, a3);\n\tvec4 b1, b2, b3;\n\tgetBoneMatrix(indices.y, b1, b2, b3);\n\tvec4 c1, c2, c3;\n\tgetBoneMatrix(indices.z, c1, c2, c3);\n\tvec4 d1, d2, d3;\n\tgetBoneMatrix(indices.w, d1, d2, d3);\n\tvec4 v1 = a1 * weights.x + b1 * weights.y + c1 * weights.z + d1 * weights.w;\n\tvec4 v2 = a2 * weights.x + b2 * weights.y + c2 * weights.z + d2 * weights.w;\n\tvec4 v3 = a3 * weights.x + b3 * weights.y + c3 * weights.z + d3 * weights.w;\n\tfloat one = dot(weights, vec4(1.0));\n\treturn mat4(\n\t\tv1.x, v2.x, v3.x, 0,\n\t\tv1.y, v2.y, v3.y, 0,\n\t\tv1.z, v2.z, v3.z, 0,\n\t\tv1.w, v2.w, v3.w, one\n\t);\n}\n",skinTexVS:"\nattribute vec4 vertex_boneWeights;\nattribute vec4 vertex_boneIndices;\nuniform highp sampler2D texture_poseMap;\nuniform vec4 texture_poseMapSize;\nvoid getBoneMatrix(const in float index, out vec4 v1, out vec4 v2, out vec4 v3) {\n\tfloat i = float(index);\n\tfloat j = i * 3.0;\n\tfloat dx = texture_poseMapSize.z;\n\tfloat dy = texture_poseMapSize.w;\n\t\n\tfloat y = floor(j * dx);\n\tfloat x = j - (y * texture_poseMapSize.x);\n\ty = dy * (y + 0.5);\n\tv1 = texture2D(texture_poseMap, vec2(dx * (x + 0.5), y));\n\tv2 = texture2D(texture_poseMap, vec2(dx * (x + 1.5), y));\n\tv3 = texture2D(texture_poseMap, vec2(dx * (x + 2.5), y));\n}\nmat4 getSkinMatrix(const in vec4 indices, const in vec4 weights) {\n\tvec4 a1, a2, a3;\n\tgetBoneMatrix(indices.x, a1, a2, a3);\n\tvec4 b1, b2, b3;\n\tgetBoneMatrix(indices.y, b1, b2, b3);\n\tvec4 c1, c2, c3;\n\tgetBoneMatrix(indices.z, c1, c2, c3);\n\tvec4 d1, d2, d3;\n\tgetBoneMatrix(indices.w, d1, d2, d3);\n\tvec4 v1 = a1 * weights.x + b1 * weights.y + c1 * weights.z + d1 * weights.w;\n\tvec4 v2 = a2 * weights.x + b2 * weights.y + c2 * weights.z + d2 * weights.w;\n\tvec4 v3 = a3 * weights.x + b3 * weights.y + c3 * weights.z + d3 * weights.w;\n\tfloat one = dot(weights, vec4(1.0));\n\treturn mat4(\n\t\tv1.x, v2.x, v3.x, 0,\n\t\tv1.y, v2.y, v3.y, 0,\n\t\tv1.z, v2.z, v3.z, 0,\n\t\tv1.w, v2.w, v3.w, one\n\t);\n}\n",skyboxEnvPS:"\nvarying vec3 vViewDir;\nuniform sampler2D texture_envAtlas;\nuniform float mipLevel;\nvoid main(void) {\n\tvec3 dir = vViewDir * vec3(-1.0, 1.0, 1.0);\n\tvec2 uv = toSphericalUv(normalize(dir));\n\tvec3 linear = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, mipLevel)));\n\tgl_FragColor = vec4(gammaCorrectOutput(toneMap(processEnvironment(linear))), 1.0);\n}\n",skyboxHDRPS:"\nvarying vec3 vViewDir;\nuniform samplerCube texture_cubeMap;\nvoid main(void) {\n\tvec3 dir=vViewDir;\n\tdir.x *= -1.0;\n\tvec3 linear = $DECODE(textureCube(texture_cubeMap, fixSeamsStatic(dir, $FIXCONST)));\n\tgl_FragColor = vec4(gammaCorrectOutput(toneMap(processEnvironment(linear))), 1.0);\n}\n",skyboxVS:"\nattribute vec3 aPosition;\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nuniform mat4 matrix_projectionSkybox;\nuniform mat3 cubeMapRotationMatrix;\nvarying vec3 vViewDir;\nvoid main(void) {\n\tmat4 view = matrix_view;\n\tview[3][0] = view[3][1] = view[3][2] = 0.0;\n\tgl_Position = matrix_projectionSkybox * view * vec4(aPosition, 1.0);\n\tgl_Position.z = gl_Position.w - 0.00001;\n\tvViewDir = aPosition * cubeMapRotationMatrix;\n}\n",specularPS:"\n#ifdef MAPCOLOR\nuniform vec3 material_specular;\n#endif\nvoid getSpecularity() {\n\tvec3 specularColor = vec3(1,1,1);\n\t#ifdef MAPCOLOR\n\tspecularColor *= material_specular;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tspecularColor *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tspecularColor *= saturate(vVertexColor.$VC);\n\t#endif\n\tdSpecularity = specularColor;\n}\n",sphericalPS:"\nconst float PI = 3.141592653589793;\nvec2 toSpherical(vec3 dir) {\n\treturn vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y));\n}\nvec2 toSphericalUv(vec3 dir) {\n\tvec2 uv = toSpherical(dir) / vec2(PI * 2.0, PI) + 0.5;\n\treturn vec2(uv.x, 1.0 - uv.y);\n}\n",specularityFactorPS:"\n#ifdef MAPFLOAT\nuniform float material_specularityFactor;\n#endif\nvoid getSpecularityFactor() {\n\tfloat specularityFactor = 1.0;\n\t#ifdef MAPFLOAT\n\tspecularityFactor *= material_specularityFactor;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tspecularityFactor *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tspecularityFactor *= saturate(vVertexColor.$VC);\n\t#endif\n\tdSpecularityFactor = specularityFactor;\n}\n",spotPS:"\nfloat getSpotEffect(vec3 lightSpotDir, float lightInnerConeAngle, float lightOuterConeAngle, vec3 lightDirNorm) {\n\tfloat cosAngle = dot(lightDirNorm, lightSpotDir);\n\treturn smoothstep(lightOuterConeAngle, lightInnerConeAngle, cosAngle);\n}\n",startPS:"\nvoid main(void) {\n\tdReflection = vec4(0);\n\t#ifdef LIT_CLEARCOAT\n\tccSpecularLight = vec3(0);\n\tccReflection = vec3(0);\n\t#endif\n",startVS:"\nvoid main(void) {\n\tgl_Position = getPosition();\n",startNineSlicedPS:"\n\tnineSlicedUv = vUv0;\n\tnineSlicedUv.y = 1.0 - nineSlicedUv.y;\n",startNineSlicedTiledPS:"\n\tvec2 tileMask = step(vMask, vec2(0.99999));\n\tvec2 tileSize = 0.5 * (innerOffset.xy + innerOffset.zw);\n\tvec2 tileScale = vec2(1.0) / (vec2(1.0) - tileSize);\n\tvec2 clampedUv = mix(innerOffset.xy * 0.5, vec2(1.0) - innerOffset.zw * 0.5, fract((vTiledUv - tileSize) * tileScale));\n\tclampedUv = clampedUv * atlasRect.zw + atlasRect.xy;\n\tnineSlicedUv = vUv0 * tileMask + clampedUv * (vec2(1.0) - tileMask);\n\tnineSlicedUv.y = 1.0 - nineSlicedUv.y;\n\t\n",storeEVSMPS:"\nfloat exponent = VSM_EXPONENT;\ndepth = 2.0 * depth - 1.0;\ndepth = exp(exponent * depth);\ngl_FragColor = vec4(depth, depth*depth, 1.0, 1.0);\n",tangentBinormalVS:"\nvec3 getTangent() {\n\treturn normalize(dNormalMatrix * vertex_tangent.xyz);\n}\nvec3 getBinormal() {\n\treturn cross(vNormalW, vTangentW) * vertex_tangent.w;\n}\n",TBNPS:"\nvoid getTBN(vec3 tangent, vec3 binormal, vec3 normal) {\n\tdTBN = mat3(normalize(tangent), normalize(binormal), normalize(normal));\n}\n",TBNderivativePS:"\nuniform float tbnBasis;\nvoid getTBN(vec3 tangent, vec3 binormal, vec3 normal) {\n\tvec2 uv = $UV;\n\tvec3 dp1 = dFdx( vPositionW );\n\tvec3 dp2 = dFdy( vPositionW );\n\tvec2 duv1 = dFdx( uv );\n\tvec2 duv2 = dFdy( uv );\n\tvec3 dp2perp = cross( dp2, normal );\n\tvec3 dp1perp = cross( normal, dp1 );\n\tvec3 T = dp2perp * duv1.x + dp1perp * duv2.x;\n\tvec3 B = dp2perp * duv1.y + dp1perp * duv2.y;\n\tfloat denom = max( dot(T,T), dot(B,B) );\n\tfloat invmax = (denom == 0.0) ? 0.0 : tbnBasis / sqrt( denom );\n\tdTBN = mat3(T * invmax, -B * invmax, normal );\n}\n",TBNfastPS:"\nvoid getTBN(vec3 tangent, vec3 binormal, vec3 normal) {\n\tdTBN = mat3(tangent, binormal, normal);\n}\n",TBNObjectSpacePS:"\nvoid getTBN(vec3 tangent, vec3 binormal, vec3 normal) {\n\tvec3 B = cross(normal, vObjectSpaceUpW);\n\tvec3 T = cross(normal, B);\n\tif (dot(B,B)==0.0)\n\t{\n\t\tfloat major=max(max(normal.x, normal.y), normal.z);\n\t\tif (normal.x == major)\n\t\t{\n\t\t\tB=cross(normal, vec3(0,1,0));\n\t\t\tT=cross(normal, B);\n\t\t}\n\t\telse if (normal.y == major)\n\t\t{\n\t\t\tB=cross(normal, vec3(0,0,1));\n\t\t\tT=cross(normal, B);\n\t\t}\n\t\telse if (normal.z == major)\n\t\t{\n\t\t\tB=cross(normal, vec3(1,0,0));\n\t\t\tT=cross(normal, B);\n\t\t}\n\t}\n\tdTBN = mat3(normalize(T), normalize(B), normalize(normal));\n}\n",textureSamplePS:"\nvec4 texture2DSRGB(sampler2D tex, vec2 uv) {\n\treturn gammaCorrectInput(texture2D(tex, uv));\n}\nvec4 texture2DSRGB(sampler2D tex, vec2 uv, float bias) {\n\treturn gammaCorrectInput(texture2D(tex, uv, bias));\n}\nvec3 texture2DRGBM(sampler2D tex, vec2 uv) {\n\treturn decodeRGBM(texture2D(tex, uv));\n}\nvec3 texture2DRGBM(sampler2D tex, vec2 uv, float bias) {\n\treturn decodeRGBM(texture2D(tex, uv, bias));\n}\nvec3 texture2DRGBE(sampler2D tex, vec2 uv) {\n\treturn decodeRGBM(texture2D(tex, uv));\n}\nvec3 texture2DRGBE(sampler2D tex, vec2 uv, float bias) {\n\treturn decodeRGBM(texture2D(tex, uv, bias));\n}\n",thicknessPS:"\n#ifdef MAPFLOAT\nuniform float material_thickness;\n#endif\nvoid getThickness() {\n\tdThickness = 1.0;\n\t#ifdef MAPFLOAT\n\tdThickness *= material_thickness;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tdThickness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tdThickness *= saturate(vVertexColor.$VC);\n\t#endif\n}\n",tonemappingAcesPS:"\nuniform float exposure;\nvec3 toneMap(vec3 color) {\n\tfloat tA = 2.51;\n\tfloat tB = 0.03;\n\tfloat tC = 2.43;\n\tfloat tD = 0.59;\n\tfloat tE = 0.14;\n\tvec3 x = color * exposure;\n\treturn (x*(tA*x+tB))/(x*(tC*x+tD)+tE);\n}\n",tonemappingAces2PS:"\nuniform float exposure;\nconst mat3 ACESInputMat = mat3(\n\t0.59719, 0.35458, 0.04823,\n\t0.07600, 0.90834, 0.01566,\n\t0.02840, 0.13383, 0.83777\n);\nconst mat3 ACESOutputMat = mat3(\n\t 1.60475, -0.53108, -0.07367,\n\t-0.10208, 1.10813, -0.00605,\n\t-0.00327, -0.07276, 1.07602\n);\nvec3 RRTAndODTFit(vec3 v) {\n\tvec3 a = v * (v + 0.0245786) - 0.000090537;\n\tvec3 b = v * (0.983729 * v + 0.4329510) + 0.238081;\n\treturn a / b;\n}\nvec3 toneMap(vec3 color) {\n\tcolor *= exposure / 0.6;\n\tcolor = color * ACESInputMat;\n\tcolor = RRTAndODTFit(color);\n\tcolor = color * ACESOutputMat;\n\tcolor = clamp(color, 0.0, 1.0);\n\treturn color;\n}\n",tonemappingFilmicPS:"\nconst float A = 0.15;\nconst float B = 0.50;\nconst float C = 0.10;\nconst float D = 0.20;\nconst float E = 0.02;\nconst float F = 0.30;\nconst float W = 11.2;\nuniform float exposure;\nvec3 uncharted2Tonemap(vec3 x) {\n return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\n}\nvec3 toneMap(vec3 color) {\n\tcolor = uncharted2Tonemap(color * exposure);\n\tvec3 whiteScale = 1.0 / uncharted2Tonemap(vec3(W,W,W));\n\tcolor = color * whiteScale;\n\treturn color;\n}\n",tonemappingHejlPS:"\nuniform float exposure;\nvec3 toneMap(vec3 color) {\n\tcolor *= exposure;\n\tconst float A = 0.22, B = 0.3, C = .1, D = 0.2, E = .01, F = 0.3;\n\tconst float Scl = 1.25;\n\tvec3 h = max( vec3(0.0), color - vec3(0.004) );\n\treturn (h*((Scl*A)*h+Scl*vec3(C*B,C*B,C*B))+Scl*vec3(D*E,D*E,D*E)) / (h*(A*h+vec3(B,B,B))+vec3(D*F,D*F,D*F)) - Scl*vec3(E/F,E/F,E/F);\n}\n",tonemappingLinearPS:"\nuniform float exposure;\nvec3 toneMap(vec3 color) {\n\treturn color * exposure;\n}\n",tonemappingNonePS:"\nvec3 toneMap(vec3 color) {\n\treturn color;\n}\n",transformVS:"\n#ifdef PIXELSNAP\nuniform vec4 uScreenSize;\n#endif\n#ifdef SCREENSPACE\nuniform float projectionFlipY;\n#endif\n#ifdef MORPHING\nuniform vec4 morph_weights_a;\nuniform vec4 morph_weights_b;\n#endif\n#ifdef MORPHING_TEXTURE_BASED\n\tuniform vec4 morph_tex_params;\n\t#ifdef WEBGPU\n\t\tivec2 getTextureMorphCoords() {\n\t\t\tivec2 textureSize = ivec2(morph_tex_params.xy);\n\t\t\tint morphGridV = int(morph_vertex_id / textureSize.x);\n\t\t\tint morphGridU = int(morph_vertex_id - (morphGridV * textureSize.x));\n\t\t\tmorphGridV = textureSize.y - morphGridV - 1;\n\t\t\treturn ivec2(morphGridU, morphGridV);\n\t\t}\n\t#else\n\t\tvec2 getTextureMorphCoords() {\n\t\t\tvec2 textureSize = morph_tex_params.xy;\n\t\t\tvec2 invTextureSize = morph_tex_params.zw;\n\t\t\tfloat morphGridV = floor(morph_vertex_id * invTextureSize.x);\n\t\t\tfloat morphGridU = morph_vertex_id - (morphGridV * textureSize.x);\n\t\t\treturn vec2(morphGridU, morphGridV) * invTextureSize + (0.5 * invTextureSize);\n\t\t}\n\t#endif\n#endif\n#ifdef MORPHING_TEXTURE_BASED_POSITION\nuniform highp sampler2D morphPositionTex;\n#endif\nmat4 getModelMatrix() {\n\t#ifdef DYNAMICBATCH\n\treturn getBoneMatrix(vertex_boneIndices);\n\t#elif defined(SKIN)\n\treturn matrix_model * getSkinMatrix(vertex_boneIndices, vertex_boneWeights);\n\t#elif defined(INSTANCING)\n\treturn mat4(instance_line1, instance_line2, instance_line3, instance_line4);\n\t#else\n\treturn matrix_model;\n\t#endif\n}\nvec4 getPosition() {\n\tdModelMatrix = getModelMatrix();\n\tvec3 localPos = vertex_position;\n\t#ifdef NINESLICED\n\tlocalPos.xz *= outerScale;\n\tvec2 positiveUnitOffset = clamp(vertex_position.xz, vec2(0.0), vec2(1.0));\n\tvec2 negativeUnitOffset = clamp(-vertex_position.xz, vec2(0.0), vec2(1.0));\n\tlocalPos.xz += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;\n\tvTiledUv = (localPos.xz - outerScale + innerOffset.xy) * -0.5 + 1.0;\n\tlocalPos.xz *= -0.5;\n\tlocalPos = localPos.xzy;\n\t#endif\n\t#ifdef MORPHING\n\t#ifdef MORPHING_POS03\n\tlocalPos.xyz += morph_weights_a[0] * morph_pos0;\n\tlocalPos.xyz += morph_weights_a[1] * morph_pos1;\n\tlocalPos.xyz += morph_weights_a[2] * morph_pos2;\n\tlocalPos.xyz += morph_weights_a[3] * morph_pos3;\n\t#endif\n\t#ifdef MORPHING_POS47\n\tlocalPos.xyz += morph_weights_b[0] * morph_pos4;\n\tlocalPos.xyz += morph_weights_b[1] * morph_pos5;\n\tlocalPos.xyz += morph_weights_b[2] * morph_pos6;\n\tlocalPos.xyz += morph_weights_b[3] * morph_pos7;\n\t#endif\n\t#endif\n\t#ifdef MORPHING_TEXTURE_BASED_POSITION\n\t\t#ifdef WEBGPU\n\t\t\tivec2 morphUV = getTextureMorphCoords();\n\t\t\tvec3 morphPos = texelFetch(morphPositionTex, ivec2(morphUV), 0).xyz;\n\t\t#else\n\t\t\tvec2 morphUV = getTextureMorphCoords();\n\t\t\tvec3 morphPos = texture2D(morphPositionTex, morphUV).xyz;\n\t\t#endif\n\t\tlocalPos += morphPos;\n\t#endif\n\tvec4 posW = dModelMatrix * vec4(localPos, 1.0);\n\t#ifdef SCREENSPACE\n\tposW.zw = vec2(0.0, 1.0);\n\t#endif\n\tdPositionW = posW.xyz;\n\tvec4 screenPos;\n\t#ifdef UV1LAYOUT\n\tscreenPos = vec4(vertex_texCoord1.xy * 2.0 - 1.0, 0.5, 1);\n\t#else\n\t#ifdef SCREENSPACE\n\tscreenPos = posW;\n\tscreenPos.y *= projectionFlipY;\n\t#else\n\tscreenPos = matrix_viewProjection * posW;\n\t#endif\n\t#ifdef PIXELSNAP\n\tscreenPos.xy = (screenPos.xy * 0.5) + 0.5;\n\tscreenPos.xy *= uScreenSize.xy;\n\tscreenPos.xy = floor(screenPos.xy);\n\tscreenPos.xy *= uScreenSize.zw;\n\tscreenPos.xy = (screenPos.xy * 2.0) - 1.0;\n\t#endif\n\t#endif\n\treturn screenPos;\n}\nvec3 getWorldPosition() {\n\treturn dPositionW;\n}\n",transformDeclVS:"\nattribute vec3 vertex_position;\nuniform mat4 matrix_model;\nuniform mat4 matrix_viewProjection;\nvec3 dPositionW;\nmat4 dModelMatrix;\n",transmissionPS:"\n#ifdef MAPFLOAT\nuniform float material_refraction;\n#endif\nvoid getRefraction() {\n\tfloat refraction = 1.0;\n\t#ifdef MAPFLOAT\n\trefraction = material_refraction;\n\t#endif\n\t#ifdef MAPTEXTURE\n\trefraction *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\trefraction *= saturate(vVertexColor.$VC);\n\t#endif\n\tdTransmission = refraction;\n}\n",uv0VS:"\n#ifdef NINESLICED\nvec2 getUv0() {\n\tvec2 uv = vertex_position.xz;\n\tvec2 positiveUnitOffset = clamp(vertex_position.xz, vec2(0.0), vec2(1.0));\n\tvec2 negativeUnitOffset = clamp(-vertex_position.xz, vec2(0.0), vec2(1.0));\n\tuv += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;\n\tuv = uv * -0.5 + 0.5;\n\tuv = uv * atlasRect.zw + atlasRect.xy;\n\tvMask = vertex_texCoord0.xy;\n\treturn uv;\n}\n#else\nvec2 getUv0() {\n\treturn vertex_texCoord0;\n}\n#endif\n",uv1VS:"\nvec2 getUv1() {\n\treturn vertex_texCoord1;\n}\n",viewDirPS:"\nvoid getViewDir() {\n\tdViewDirW = normalize(view_position - vPositionW);\n}\n",viewNormalVS:"\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nvec3 getViewNormal() {\n\treturn mat3(matrix_view) * vNormalW;\n}\n",webgpuPS:$s,webgpuVS:Js},vo=new Bs;function go(t){return vo.get(t)}function yo(t,e){vo.get(t,(function(){return e}))}var xo=function(){function t(){}return t.begin=function(){return"void main(void)\n{\n"},t.end=function(){return"}\n"},t.skinCode=function(t,e){return e||(e=_o),t.supportsBoneTextures?e.skinTexVS:"#define BONE_LIMIT "+t.getBoneLimit()+"\n"+e.skinConstVS},t.fogCode=function(t,e){return e||(e=_o),"linear"===t?e.fogLinearPS?e.fogLinearPS:_o.fogLinearPS:"exp"===t?e.fogExpPS?e.fogExpPS:_o.fogExpPS:"exp2"===t?e.fogExp2PS?e.fogExp2PS:_o.fogExp2PS:e.fogNonePS?e.fogNonePS:_o.fogNonePS},t.gammaCode=function(t,e){return e||(e=_o),1===t||2===t?e.gamma2_2PS?e.gamma2_2PS:_o.gamma2_2PS:3===t?"#define HDR\n"+(e.gamma2_2PS?e.gamma2_2PS:_o.gamma2_2PS):e.gamma1_0PS?e.gamma1_0PS:_o.gamma1_0PS},t.tonemapCode=function(t,e){return e||(e=_o),1===t?e.tonemappingFilmicPS?e.tonemappingFilmicPS:_o.tonemappingFilmicPS:0===t?e.tonemappingLinearPS?e.tonemappingLinearPS:_o.tonemappingLinearPS:2===t?e.tonemappingHejlPS?e.tonemappingHejlPS:_o.tonemappingHejlPS:3===t?e.tonemappingAcesPS?e.tonemappingAcesPS:_o.tonemappingAcesPS:4===t?e.tonemappingAces2PS?e.tonemappingAces2PS:_o.tonemappingAces2PS:e.tonemapingNonePS?e.tonemapingNonePS:_o.tonemappingNonePS},t}();function So(t,e,i,n){return void 0===n&&(n=!1),new fs(t,ir.createDefinition(t,{name:e+"_"+i,vertexCode:_o[e],fragmentCode:_o[i],useTransformFeedback:n}))}function bo(t,e,i,n,s,r){void 0===r&&(r=!1);var a=go(t),o=a.getCachedShader(n);return o||(o=new fs(t,ir.createDefinition(t,{name:n,vertexCode:e,fragmentCode:i,attributes:s,useTransformFeedback:r})),a.setCachedShader(n,o)),o}var wo=function(t){function e(e,i){var n;return(n=t.call(this)||this).key=e,n.shaderDefinition=i,n}S(e,t);var i=e.prototype;return i.generateKey=function(t){return this.key},i.createShaderDefinition=function(t,e){return this.shaderDefinition},e}(xo);function To(t,e){var i,n=t.definition,s=(null!=(i=n.name)?i:"shader")+"-id-"+t.id,r=new wo(s,n),a="shader",o=go(t.device);o.register(a,r);var h=o.getProgram(a,{},e);return o.unregister(a),h}_o.createShader=So,_o.createShaderFromCode=bo;var Ao={type:be,base:0,count:4,indexed:!1},Co=new Pt,Eo=new Pt,Mo=function(){function t(t){this.uniformBuffer=void 0,this.bindGroup=void 0;var e=t.device;if(this.shader=t,e.supportsUniformBuffers){var i=new fo;this.shader=To(t,i);var n=this.shader.meshUniformBufferFormat;n&&(this.uniformBuffer=new xs(e,n,!1));var s=this.shader.meshBindGroupFormat;this.bindGroup=new ms(e,s,this.uniformBuffer)}}var e=t.prototype;return e.destroy=function(){var t,e;null==(t=this.uniformBuffer)||t.destroy(),this.uniformBuffer=null,null==(e=this.bindGroup)||e.destroy(),this.bindGroup=null},e.render=function(t,e){var i,n=this.shader.device;t&&(Co.set(n.vx,n.vy,n.vw,n.vh),Eo.set(n.sx,n.sy,n.sw,n.sh),e=null!=(i=e)?i:t,n.setViewport(t.x,t.y,t.z,t.w),n.setScissor(e.x,e.y,e.z,e.w));n.setVertexBuffer(n.quadVertexBuffer,0);var s=this.shader;if(n.setShader(s),n.supportsUniformBuffers){var r,a=this.bindGroup;null==(r=a.defaultUniformBuffer)||r.update(),a.update(),n.setBindGroup(0,a)}n.draw(Ao),t&&(n.setViewport(Co.x,Co.y,Co.z,Co.w),n.setScissor(Eo.x,Eo.y,Eo.z,Eo.w))},t}(),Po=new Pt;function Ro(t,e,i,n,s){t.setCullMode(se),t.setDepthState(Ni.NODEPTH),t.setStencilState(null,null);var r=new Mo(i);n||((n=Po).x=0,n.y=0,n.z=e?e.width:t.width,n.w=e?e.height:t.height);var a=new uo(t,(function(){r.render(n,s)}));a.init(e),a.colorOps.clear=!1,a.depthStencilOps.clearDepth=!1,t.isWebGPU&&null===e&&t.samples>1&&(a.colorOps.store=!0),a.render(),r.destroy()}var Io=new Bs,Lo=function(){function t(t,e,i){void 0===i&&(i={}),this.index=void 0,this.name=void 0,this.shaderDefine=void 0,this.name=t,this.index=e,Object.assign(this,i),this.initShaderDefines()}return t.prototype.initShaderDefines=function(){var t;this.isShadow?t="SHADOW":this.isForward?t="FORWARD":2===this.index?t="DEPTH":3===this.index&&(t="PICK");var e=t?"#define "+t+"_PASS\n":"",i="#define "+this.name.toUpperCase()+"_PASS\n";this.shaderDefines=e+i},t}(),Do=function(){function t(){var t=this;this.passesNamed=new Map,this.passesIndexed=[],this.nextIndex=0;var e=function(e,i,n){t.allocate(e,n)};e("forward",0,{isForward:!0}),e("forward_hdr",0,{isForward:!0}),e("depth"),e("pick"),e("shadow")}t.get=function(e){return Io.get(e,(function(){return new t}))};var e=t.prototype;return e.allocate=function(t,e){var i=this.passesNamed.get(t);return void 0===i&&(i=new Lo(t,this.nextIndex,e),this.passesNamed.set(i.name,i),this.passesIndexed[i.index]=i,this.nextIndex++),i},e.getByIndex=function(t){return this.passesIndexed[t]},e.getByName=function(t){return this.passesNamed.get(t)},t}(),Oo=function(t){function e(){return t.apply(this,arguments)||this}S(e,t);var i=e.prototype;return i.generateKey=function(t){var e="basic";return t.fog&&(e+="_fog"),t.alphaTest&&(e+="_atst"),t.vertexColors&&(e+="_vcol"),t.diffuseMap&&(e+="_diff"),t.skin&&(e+="_skin"),t.screenSpace&&(e+="_ss"),t.useInstancing&&(e+="_inst"),t.useMorphPosition&&(e+="_morphp"),t.useMorphNormal&&(e+="_morphn"),t.useMorphTextureBased&&(e+="_morpht"),e+="_"+t.pass},i.createShaderDefinition=function(t,e){var i={vertex_position:we};e.skin&&(i.vertex_boneWeights=Ce,i.vertex_boneIndices=Ee),e.vertexColors&&(i.vertex_color=Me),e.diffuseMap&&(i.vertex_texCoord0=Re);var n=Do.get(t).getByIndex(e.pass).shaderDefines,s=n;s+=_o.transformDeclVS,e.skin?(s+=xo.skinCode(t),s+=_o.transformSkinnedVS):s+=_o.transformVS,e.vertexColors&&(s+="attribute vec4 vertex_color;\n",s+="varying vec4 vColor;\n"),e.diffuseMap&&(s+="attribute vec2 vertex_texCoord0;\n",s+="varying vec2 vUv0;\n"),2===e.pass&&(s+="varying float vDepth;\n",s+="#ifndef VIEWMATRIX\n",s+="#define VIEWMATRIX\n",s+="uniform mat4 matrix_view;\n",s+="#endif\n",s+="#ifndef CAMERAPLANES\n",s+="#define CAMERAPLANES\n",s+="uniform vec4 camera_params;\n\n",s+="#endif\n"),s+=xo.begin(),s+=" gl_Position = getPosition();\n",2===e.pass&&(s+=" vDepth = -(matrix_view * vec4(getWorldPosition(),1.0)).z * camera_params.x;\n"),e.vertexColors&&(s+=" vColor = vertex_color;\n"),e.diffuseMap&&(s+=" vUv0 = vertex_texCoord0;\n"),s+=xo.end();var r=n;return e.vertexColors?r+="varying vec4 vColor;\n":r+="uniform vec4 uColor;\n",e.diffuseMap&&(r+="varying vec2 vUv0;\n",r+="uniform sampler2D texture_diffuseMap;\n"),e.fog&&(r+=xo.fogCode(e.fog)),e.alphaTest&&(r+=_o.alphaTestPS),2===e.pass&&(r+="varying float vDepth;\n",r+=_o.packDepthPS),r+=xo.begin(),e.vertexColors?r+=" gl_FragColor = vColor;\n":r+=" gl_FragColor = uColor;\n",e.diffuseMap&&(r+=" gl_FragColor *= texture2D(texture_diffuseMap, vUv0);\n"),e.alphaTest&&(r+=" alphaTest(gl_FragColor.a);\n"),3!==e.pass&&(2===e.pass?r+=" gl_FragColor = packFloat(vDepth);\n":e.fog&&(r+=" glFragColor.rgb = addFog(gl_FragColor.rgb);\n")),r+=xo.end(),ir.createDefinition(t,{name:"BasicShader",attributes:i,vertexCode:s,fragmentCode:r})},e}(xo),ko=new Oo,Fo=new Bs;function Bo(t){return Fo.get(t)}var Uo=[];Uo[0]={src:1,dst:1,op:2},Uo[3]={src:1,dst:0,op:0},Uo[2]={src:6,dst:8,op:0},Uo[4]={src:1,dst:8,op:0},Uo[1]={src:1,dst:1,op:0},Uo[6]={src:6,dst:1,op:0},Uo[7]={src:4,dst:2,op:0},Uo[8]={src:5,dst:1,op:0},Uo[5]={src:4,dst:0,op:0},Uo[9]={src:1,dst:1,op:3},Uo[10]={src:1,dst:1,op:4};var No=0,zo=function(){function t(){this._shader=null,this.meshInstances=[],this.name="Untitled",this.userId="",this.id=No++,this.variants=new Map,this.parameters={},this.alphaTest=0,this.alphaToCoverage=!1,this._blendState=new Ui,this._depthState=new Ni,this.cull=1,this.stencilFront=null,this.stencilBack=null,this.depthBias=0,this.slopeDepthBias=0,this._shaderVersion=0,this._scene=null,this.dirty=!0}var e=t.prototype;return e._updateTransparency=function(){for(var t=this.transparent,e=this.meshInstances,i=0;i<e.length;i++)e[i].transparent=t},e.copy=function(t){var e;return this.name=t.name,this._shader=t._shader,this.alphaTest=t.alphaTest,this.alphaToCoverage=t.alphaToCoverage,this._blendState.copy(t._blendState),this._depthState.copy(t._depthState),this.cull=t.cull,this.depthBias=t.depthBias,this.slopeDepthBias=t.slopeDepthBias,this.stencilFront=null==(e=t.stencilFront)?void 0:e.clone(),t.stencilBack&&(this.stencilBack=t.stencilFront===t.stencilBack?this.stencilFront:t.stencilBack.clone()),this},e.clone=function(){var t=new this.constructor;return t.copy(this)},e._updateMeshInstanceKeys=function(){for(var t=this.meshInstances,e=0;e<t.length;e++)t[e].updateKey()},e.updateUniforms=function(t,e){},e.getShaderVariant=function(t,e,i,n,s,r,a,o,h){var l=new fo(a,o,h);return To(this._shader,l)},e.update=function(){this.dirty=!0,this._shader&&(this._shader.failed=!1)},e.clearParameters=function(){this.parameters={}},e.getParameters=function(){return this.parameters},e.clearVariants=function(){this.variants.clear();for(var t=this.meshInstances,e=t.length,i=0;i<e;i++)t[i].clearShaders()},e.getParameter=function(t){return this.parameters[t]},e.setParameter=function(t,e){if(void 0===e&&"object"==typeof t){var i=t;if(i.length){for(var n=0;n<i.length;n++)this.setParameter(i[n]);return}t=i.name,e=i.value}var s=this.parameters[t];s?s.data=e:this.parameters[t]={scopeId:null,data:e}},e.deleteParameter=function(t){this.parameters[t]&&delete this.parameters[t]},e.setParameters=function(t,e){var i=this.parameters;for(var n in void 0===e&&(e=i),e){var s=i[n];s&&(s.scopeId||(s.scopeId=t.scope.resolve(n)),s.scopeId.setValue(s.data))}},e.destroy=function(){this.variants.clear(),this._shader=null;for(var t=0;t<this.meshInstances.length;t++){var e=this.meshInstances[t];if(e.clearShaders(),e._material=null,e.mesh){var i=Bo(e.mesh.device);this!==i&&(e.material=i)}}this.meshInstances.length=0},e.addMeshInstanceRef=function(t){this.meshInstances.push(t)},e.removeMeshInstanceRef=function(t){var e=this.meshInstances,i=e.indexOf(t);-1!==i&&e.splice(i,1)},y(t,[{key:"redWrite",get:function(){return this._blendState.redWrite},set:function(t){this._blendState.redWrite=t}},{key:"greenWrite",get:function(){return this._blendState.greenWrite},set:function(t){this._blendState.greenWrite=t}},{key:"blueWrite",get:function(){return this._blendState.blueWrite},set:function(t){this._blendState.blueWrite=t}},{key:"alphaWrite",get:function(){return this._blendState.alphaWrite},set:function(t){this._blendState.alphaWrite=t}},{key:"shader",get:function(){return this._shader},set:function(t){this._shader=t}},{key:"transparent",get:function(){return this._blendState.blend}},{key:"blendState",get:function(){return this._blendState},set:function(t){this._blendState.copy(t),this._updateTransparency()}},{key:"blendType",get:function(){if(!this.transparent)return 3;for(var t=this._blendState,e=t.colorOp,i=t.colorSrcFactor,n=t.colorDstFactor,s=t.alphaOp,r=t.alphaSrcFactor,a=t.alphaDstFactor,o=0;o<Uo.length;o++){var h=Uo[o];if(h.src===i&&h.dst===n&&h.op===e&&h.src===r&&h.dst===a&&h.op===s)return o}return 2},set:function(t){var e=Uo[t];this._blendState.setColorBlend(e.op,e.src,e.dst),this._blendState.setAlphaBlend(e.op,e.src,e.dst);var i=3!==t;this._blendState.blend!==i&&(this._blendState.blend=i,this._updateTransparency()),this._updateMeshInstanceKeys()}},{key:"depthState",get:function(){return this._depthState},set:function(t){this._depthState.copy(t)}},{key:"depthTest",get:function(){return this._depthState.test},set:function(t){this._depthState.test=t}},{key:"depthFunc",get:function(){return this._depthState.func},set:function(t){this._depthState.func=t}},{key:"depthWrite",get:function(){return this._depthState.write},set:function(t){this._depthState.write=t}}]),t}(),Vo=function(t){function e(){for(var e,i=arguments.length,n=new Array(i),s=0;s<i;s++)n[s]=arguments[s];return(e=t.call.apply(t,[this].concat(n))||this).color=new vt(1,1,1,1),e.colorUniform=new Float32Array(4),e.colorMap=null,e.vertexColors=!1,e}S(e,t);var i=e.prototype;return i.copy=function(e){return t.prototype.copy.call(this,e),this.color.copy(e.color),this.colorMap=e.colorMap,this.vertexColors=e.vertexColors,this},i.updateUniforms=function(t,e){this.clearParameters(),this.colorUniform[0]=this.color.r,this.colorUniform[1]=this.color.g,this.colorUniform[2]=this.color.b,this.colorUniform[3]=this.color.a,this.setParameter("uColor",this.colorUniform),this.colorMap&&this.setParameter("texture_diffuseMap",this.colorMap)},i.getShaderVariant=function(t,e,i,n,s,r,a,o,h){var l={skin:i&&0!=(2&i),screenSpace:i&&0!=(i&Fa),useInstancing:i&&0!=(i&Oa),useMorphPosition:i&&0!=(i&Ua),useMorphNormal:i&&0!=(i&Na),useMorphTextureBased:i&&0!=(i&za),alphaTest:this.alphaTest>0,vertexColors:this.vertexColors,diffuseMap:!!this.colorMap,pass:s},c=new fo(a,o,h),u=go(t);return u.register("basic",ko),u.getProgram("basic",l,c,this.userId)},e}(zo),Go=function(){function t(t,e,i){this._aabb=new Ht,this.origMeshInstances=void 0,this.meshInstance=null,this.dynamic=void 0,this.batchGroupId=void 0,this.origMeshInstances=t,this.dynamic=e,this.batchGroupId=i}var e=t.prototype;return e.destroy=function(t,e){this.meshInstance&&(this.removeFromLayers(t,e),this.meshInstance.destroy(),this.meshInstance=null)},e.addToLayers=function(t,e){for(var i=0;i<e.length;i++){var n=t.layers.getLayerById(e[i]);n&&n.addMeshInstances([this.meshInstance])}},e.removeFromLayers=function(t,e){for(var i=0;i<e.length;i++){var n=t.layers.getLayerById(e[i]);n&&n.removeMeshInstances([this.meshInstance])}},e.updateBoundingBox=function(){this._aabb.copy(this.origMeshInstances[0].aabb);for(var t=1;t<this.origMeshInstances.length;t++)this._aabb.add(this.origMeshInstances[t].aabb);this.meshInstance.aabb=this._aabb,this.meshInstance._aabbVer=0},t}(),Ho=function(t,e,i,n,s){void 0===s&&(s=[0]),this._ui=!1,this._sprite=!1,this._obj={model:[],element:[],sprite:[],render:[]},this.id=void 0,this.name=void 0,this.dynamic=void 0,this.maxAabbSize=void 0,this.layers=void 0,this.id=t,this.name=e,this.dynamic=i,this.maxAabbSize=n,this.layers=s};Ho.MODEL="model",Ho.ELEMENT="element",Ho.SPRITE="sprite",Ho.RENDER="render";var Wo=new Ft,Xo=function(){function t(t){this.bones=void 0,this._dirty=!0,this._rootBone=null,this._skinUpdateIndex=-1,this._updateBeforeCull=!0,t&&this.initSkin(t)}var e=t.prototype;return e.init=function(t,e){if(t.supportsBoneTextures){var i=3*e,n=Math.ceil(Math.sqrt(i));n=_t.roundUp(n,3);var s=Math.ceil(i/n);this.boneTexture=new Ls(t,{width:n,height:s,format:le,mipmaps:!1,minFilter:0,magFilter:0,name:"skin"}),this.matrixPalette=this.boneTexture.lock()}else this.matrixPalette=new Float32Array(12*e)},e.destroy=function(){this.boneTexture&&(this.boneTexture.destroy(),this.boneTexture=null)},e.resolve=function(t,e){this.rootBone=t;for(var i=this.skin,n=[],s=0;s<i.boneNames.length;s++){var r=i.boneNames[s],a=t.findByName(r);a||(a=e),n.push(a)}this.bones=n},e.initSkin=function(t){this.skin=t,this.bones=[];var e=t.inverseBindPose.length;this.init(t.device,e),this.matrices=[];for(var i=0;i<e;i++)this.matrices[i]=new Ft},e.uploadBones=function(t){t.supportsBoneTextures&&(this.boneTexture.lock(),this.boneTexture.unlock())},e._updateMatrices=function(t,e){if(this._skinUpdateIndex!==e){this._skinUpdateIndex=e,Wo.copy(t.getWorldTransform()).invert();for(var i=this.bones.length-1;i>=0;i--)this.matrices[i].mulAffine2(Wo,this.bones[i].getWorldTransform()),this.matrices[i].mulAffine2(this.matrices[i],this.skin.inverseBindPose[i])}},e.updateMatrices=function(t,e){this._updateBeforeCull&&this._updateMatrices(t,e)},e.updateMatrixPalette=function(t,e){this._updateMatrices(t,e);for(var i=this.matrixPalette,n=this.bones.length,s=0;s<n;s++){var r=this.matrices[s].data,a=12*s;i[a]=r[0],i[a+1]=r[4],i[a+2]=r[8],i[a+3]=r[12],i[a+4]=r[1],i[a+5]=r[5],i[a+6]=r[9],i[a+7]=r[13],i[a+8]=r[2],i[a+9]=r[6],i[a+10]=r[10],i[a+11]=r[14]}this.uploadBones(this.skin.device)},y(t,[{key:"rootBone",get:function(){return this._rootBone},set:function(t){this._rootBone=t}}]),t}(),jo=function(t){function e(e,i,n){var s;s=t.call(this)||this;var r=i.length;return s.init(e,r),s.device=e,s.rootNode=n,s.bones=i,s}S(e,t);var i=e.prototype;return i.updateMatrices=function(t,e){},i.updateMatrixPalette=function(t,e){for(var i=this.matrixPalette,n=this.bones.length,s=0;s<n;s++){var r=this.bones[s].getWorldTransform().data,a=12*s;i[a]=r[0],i[a+1]=r[4],i[a+2]=r[8],i[a+3]=r[12],i[a+4]=r[1],i[a+5]=r[5],i[a+6]=r[9],i[a+7]=r[13],i[a+8]=r[2],i[a+9]=r[6],i[a+10]=r[10],i[a+11]=r[14]}this.uploadBones(this.device)},e}(Xo),qo=new Ft,Yo=new wt,Ko=new Bt,Zo=new Bt,Qo=new wt,$o=new wt,Jo=new Ft,th=new Bt,eh=new wt,ih=new Ft,nh=new Bt,sh=new Bt,rh=new Ft,ah=new wt,oh=new wt,hh=function(t){function e(e){var i;return void 0===e&&(e="Untitled"),(i=t.call(this)||this).name=void 0,i.tags=new ut(w(i)),i._labels={},i.localPosition=new wt,i.localRotation=new Bt,i.localScale=new wt(1,1,1),i.localEulerAngles=new wt,i.position=new wt,i.rotation=new Bt,i.eulerAngles=new wt,i._scale=null,i.localTransform=new Ft,i._dirtyLocal=!1,i._aabbVer=0,i._frozen=!1,i.worldTransform=new Ft,i._dirtyWorld=!1,i._worldScaleSign=0,i._normalMatrix=new At,i._dirtyNormal=!0,i._right=null,i._up=null,i._forward=null,i._parent=null,i._children=[],i._graphDepth=0,i._enabled=!0,i._enabledInHierarchy=!1,i.scaleCompensation=!1,i.name=e,i}S(e,t);var i=e.prototype;return i._notifyHierarchyStateChanged=function(t,e){t._onHierarchyStateChanged(e);for(var i=t._children,n=0,s=i.length;n<s;n++)i[n]._enabled&&this._notifyHierarchyStateChanged(i[n],e)},i._onHierarchyStateChanged=function(t){this._enabledInHierarchy=t,t&&!this._frozen&&this._unfreezeParentToRoot()},i._cloneInternal=function(t){t.name=this.name;var e=this.tags._list;t.tags.clear();for(var i=0;i<e.length;i++)t.tags.add(e[i]);t._labels=Object.assign({},this._labels),t.localPosition.copy(this.localPosition),t.localRotation.copy(this.localRotation),t.localScale.copy(this.localScale),t.localEulerAngles.copy(this.localEulerAngles),t.position.copy(this.position),t.rotation.copy(this.rotation),t.eulerAngles.copy(this.eulerAngles),t.localTransform.copy(this.localTransform),t._dirtyLocal=this._dirtyLocal,t.worldTransform.copy(this.worldTransform),t._dirtyWorld=this._dirtyWorld,t._dirtyNormal=this._dirtyNormal,t._aabbVer=this._aabbVer+1,t._enabled=this._enabled,t.scaleCompensation=this.scaleCompensation,t._enabledInHierarchy=!1},i.clone=function(){var t=new this.constructor;return this._cloneInternal(t),t},i.copy=function(t){return t._cloneInternal(this),this},i.destroy=function(){this.remove();for(var t=this._children;t.length;){var e=t.pop();e._parent=null,e.destroy()}this.fire("destroy",this),this.off()},i.find=function(t,e){var i=[],n=this._children.length;if(t instanceof Function){var s=t;s(this)&&i.push(this);for(var r=0;r<n;r++){var a=this._children[r].find(s);a.length&&(i=i.concat(a))}}else{this[t]&&(this[t]instanceof Function?this[t]():this[t])===e&&i.push(this);for(var o=0;o<n;++o){var h=this._children[o].find(t,e);h.length&&(i=i.concat(h))}}return i},i.findOne=function(t,e){var i=this._children.length,n=null;if(t instanceof Function){var s=t;if(n=s(this))return this;for(var r=0;r<i;r++)if(n=this._children[r].findOne(s))return n}else{if(this[t]&&(this[t]instanceof Function?this[t]():this[t])===e)return this;for(var a=0;a<i;a++)if(null!==(n=this._children[a].findOne(t,e)))return n}return null},i.findByTag=function(){var t=arguments,e=[];return function i(n,s){var r;s&&(r=n.tags).has.apply(r,t)&&e.push(n);for(var a=0;a<n._children.length;a++)i(n._children[a],!0)}(this,!1),e},i.findByName=function(t){if(this.name===t)return this;for(var e=0;e<this._children.length;e++){var i=this._children[e].findByName(t);if(null!==i)return i}return null},i.findByPath=function(t){for(var e,i=Array.isArray(t)?t:t.split("/"),n=this,s=function(t){if(n=n.children.find((function(e){return e.name===i[t]})),!n)return{v:null}},r=0,a=i.length;r<a;++r)if(e=s(r))return e.v;return n},i.forEach=function(t,e){t.call(e,this);for(var i=this._children,n=0;n<i.length;n++)i[n].forEach(t,e)},i.isDescendantOf=function(t){for(var e=this._parent;e;){if(e===t)return!0;e=e._parent}return!1},i.isAncestorOf=function(t){return t.isDescendantOf(this)},i.getEulerAngles=function(){return this.getWorldTransform().getEulerAngles(this.eulerAngles),this.eulerAngles},i.getLocalEulerAngles=function(){return this.localRotation.getEulerAngles(this.localEulerAngles),this.localEulerAngles},i.getLocalPosition=function(){return this.localPosition},i.getLocalRotation=function(){return this.localRotation},i.getLocalScale=function(){return this.localScale},i.getLocalTransform=function(){return this._dirtyLocal&&(this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale),this._dirtyLocal=!1),this.localTransform},i.getPosition=function(){return this.getWorldTransform().getTranslation(this.position),this.position},i.getRotation=function(){return this.rotation.setFromMat4(this.getWorldTransform()),this.rotation},i.getScale=function(){return this._scale||(this._scale=new wt),this.getWorldTransform().getScale(this._scale)},i.getWorldTransform=function(){return this._dirtyLocal||this._dirtyWorld?(this._parent&&this._parent.getWorldTransform(),this._sync(),this.worldTransform):this.worldTransform},i.remove=function(){var t;null==(t=this._parent)||t.removeChild(this)},i.reparent=function(t,e){this.remove(),t&&(e>=0?t.insertChild(this,e):t.addChild(this))},i.setLocalEulerAngles=function(t,e,i){this.localRotation.setFromEulerAngles(t,e,i),this._dirtyLocal||this._dirtifyLocal()},i.setLocalPosition=function(t,e,i){t instanceof wt?this.localPosition.copy(t):this.localPosition.set(t,e,i),this._dirtyLocal||this._dirtifyLocal()},i.setLocalRotation=function(t,e,i,n){t instanceof Bt?this.localRotation.copy(t):this.localRotation.set(t,e,i,n),this._dirtyLocal||this._dirtifyLocal()},i.setLocalScale=function(t,e,i){t instanceof wt?this.localScale.copy(t):this.localScale.set(t,e,i),this._dirtyLocal||this._dirtifyLocal()},i._dirtifyLocal=function(){this._dirtyLocal||(this._dirtyLocal=!0,this._dirtyWorld||this._dirtifyWorld())},i._unfreezeParentToRoot=function(){for(var t=this._parent;t;)t._frozen=!1,t=t._parent},i._dirtifyWorld=function(){this._dirtyWorld||this._unfreezeParentToRoot(),this._dirtifyWorldInternal()},i._dirtifyWorldInternal=function(){if(!this._dirtyWorld){this._frozen=!1,this._dirtyWorld=!0;for(var t=0;t<this._children.length;t++)this._children[t]._dirtyWorld||this._children[t]._dirtifyWorldInternal()}this._dirtyNormal=!0,this._worldScaleSign=0,this._aabbVer++},i.setPosition=function(t,e,i){t instanceof wt?eh.copy(t):eh.set(t,e,i),null===this._parent?this.localPosition.copy(eh):(ih.copy(this._parent.getWorldTransform()).invert(),ih.transformPoint(eh,this.localPosition)),this._dirtyLocal||this._dirtifyLocal()},i.setRotation=function(t,e,i,n){if(t instanceof Bt?nh.copy(t):nh.set(t,e,i,n),null===this._parent)this.localRotation.copy(nh);else{var s=this._parent.getRotation();sh.copy(s).invert(),this.localRotation.copy(sh).mul(nh)}this._dirtyLocal||this._dirtifyLocal()},i.setEulerAngles=function(t,e,i){if(this.localRotation.setFromEulerAngles(t,e,i),null!==this._parent){var n=this._parent.getRotation();sh.copy(n).invert(),this.localRotation.mul2(sh,this.localRotation)}this._dirtyLocal||this._dirtifyLocal()},i.addChild=function(t){this._prepareInsertChild(t),this._children.push(t),this._onInsertChild(t)},i.addChildAndSaveTransform=function(t){var e=t.getPosition(),i=t.getRotation();this._prepareInsertChild(t),t.setPosition(Jo.copy(this.worldTransform).invert().transformPoint(e)),t.setRotation(th.copy(this.getRotation()).invert().mul(i)),this._children.push(t),this._onInsertChild(t)},i.insertChild=function(t,e){this._prepareInsertChild(t),this._children.splice(e,0,t),this._onInsertChild(t)},i._prepareInsertChild=function(t){t.remove()},i._fireOnHierarchy=function(t,e,i){this.fire(t,i);for(var n=0;n<this._children.length;n++)this._children[n]._fireOnHierarchy(e,e,i)},i._onInsertChild=function(t){t._parent=this;var e=t._enabled&&this.enabled;t._enabledInHierarchy!==e&&(t._enabledInHierarchy=e,t._notifyHierarchyStateChanged(t,e)),t._updateGraphDepth(),t._dirtifyWorld(),this._frozen&&t._unfreezeParentToRoot(),t._fireOnHierarchy("insert","inserthierarchy",this),this.fire&&this.fire("childinsert",t)},i._updateGraphDepth=function(){this._graphDepth=this._parent?this._parent._graphDepth+1:0;for(var t=0,e=this._children.length;t<e;t++)this._children[t]._updateGraphDepth()},i.removeChild=function(t){var e=this._children.indexOf(t);-1!==e&&(this._children.splice(e,1),t._parent=null,t._fireOnHierarchy("remove","removehierarchy",this),this.fire("childremove",t))},i._sync=function(){if(this._dirtyLocal&&(this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale),this._dirtyLocal=!1),this._dirtyWorld){if(null===this._parent)this.worldTransform.copy(this.localTransform);else if(this.scaleCompensation){var t,e=this._parent,i=this.localScale,n=e;if(n){for(;n&&n.scaleCompensation;)n=n._parent;n&&(n=n._parent)&&(t=n.worldTransform.getScale(),Qo.mul2(t,this.localScale),i=Qo)}Zo.setFromMat4(e.worldTransform),Ko.mul2(Zo,this.localRotation);var s=e.worldTransform;e.scaleCompensation&&($o.mul2(t,e.getLocalScale()),qo.setTRS(e.worldTransform.getTranslation(Yo),Zo,$o),s=qo),s.transformPoint(this.localPosition,Yo),this.worldTransform.setTRS(Yo,Ko,i)}else this.worldTransform.mulAffine2(this._parent.worldTransform,this.localTransform);this._dirtyWorld=!1}},i.syncHierarchy=function(){if(this._enabled&&!this._frozen){this._frozen=!0,(this._dirtyLocal||this._dirtyWorld)&&this._sync();for(var t=this._children,e=0,i=t.length;e<i;e++)t[e].syncHierarchy()}},i.lookAt=function(t,e,i,n,s,r){if(void 0===n&&(n=0),void 0===s&&(s=1),void 0===r&&(r=0),t instanceof wt)ah.copy(t),e instanceof wt?oh.copy(e):oh.copy(wt.UP);else{if(void 0===i)return;ah.set(t,e,i),oh.set(n,s,r)}rh.setLookAt(this.getPosition(),ah,oh),nh.setFromMat4(rh),this.setRotation(nh)},i.translate=function(t,e,i){t instanceof wt?eh.copy(t):eh.set(t,e,i),eh.add(this.getPosition()),this.setPosition(eh)},i.translateLocal=function(t,e,i){t instanceof wt?eh.copy(t):eh.set(t,e,i),this.localRotation.transformVector(eh,eh),this.localPosition.add(eh),this._dirtyLocal||this._dirtifyLocal()},i.rotate=function(t,e,i){if(nh.setFromEulerAngles(t,e,i),null===this._parent)this.localRotation.mul2(nh,this.localRotation);else{var n=this.getRotation(),s=this._parent.getRotation();sh.copy(s).invert(),nh.mul2(sh,nh),this.localRotation.mul2(nh,n)}this._dirtyLocal||this._dirtifyLocal()},i.rotateLocal=function(t,e,i){nh.setFromEulerAngles(t,e,i),this.localRotation.mul(nh),this._dirtyLocal||this._dirtifyLocal()},y(e,[{key:"right",get:function(){return this._right||(this._right=new wt),this.getWorldTransform().getX(this._right).normalize()}},{key:"up",get:function(){return this._up||(this._up=new wt),this.getWorldTransform().getY(this._up).normalize()}},{key:"forward",get:function(){return this._forward||(this._forward=new wt),this.getWorldTransform().getZ(this._forward).normalize().mulScalar(-1)}},{key:"normalMatrix",get:function(){var t=this._normalMatrix;return this._dirtyNormal&&(t.invertMat4(this.getWorldTransform()).transpose(),this._dirtyNormal=!1),t}},{key:"enabled",get:function(){return this._enabled&&this._enabledInHierarchy},set:function(t){var e;this._enabled!==t&&(this._enabled=t,(t&&null!=(e=this._parent)&&e.enabled||!t)&&this._notifyHierarchyStateChanged(this,t))}},{key:"parent",get:function(){return this._parent}},{key:"path",get:function(){var t=this._parent;if(!t)return"";for(var e=this.name;t&&t._parent;)e=t.name+"/"+e,t=t._parent;return e}},{key:"root",get:function(){for(var t=this;t._parent;)t=t._parent;return t}},{key:"children",get:function(){return this._children}},{key:"graphDepth",get:function(){return this._graphDepth}},{key:"worldScaleSign",get:function(){return 0===this._worldScaleSign&&(this._worldScaleSign=this.getWorldTransform().scaleSign),this._worldScaleSign}}]),e}(P),lh=function(){function t(){this.cache=new Map}var e=t.prototype;return e.destroy=function(){this.cache.forEach((function(t,e){e.destroy()})),this.cache.clear()},e.incRef=function(t){var e=(this.cache.get(t)||0)+1;this.cache.set(t,e)},e.decRef=function(t){if(t){var e=this.cache.get(t);e&&(0===--e?(this.cache.delete(t),t.destroy()):this.cache.set(t,e))}},t}(),ch=function(){function t(){}return t.incRef=function(t){this.cache.incRef(t)},t.decRef=function(t){this.cache.decRef(t)},t.destroy=function(){this.cache.destroy()},t}();ch.cache=new lh;var uh=0,dh=new Ht,fh=new Ht,ph=new jt,mh=new Set,_h=function(t){this.vertexBuffer=null,this.count=t},vh=function(){function t(){this.shader=void 0,this.bindGroup=null}var e=t.prototype;return e.getBindGroup=function(t){if(!this.bindGroup){var e=this.shader,i=e.meshUniformBufferFormat,n=new xs(t,i,!1),s=e.meshBindGroupFormat;this.bindGroup=new ms(t,s,n)}return this.bindGroup},e.destroy=function(){var t,e=this.bindGroup;e&&(null==(t=e.defaultUniformBuffer)||t.destroy(),e.destroy(),this.bindGroup=null)},t}(),gh=function(){function t(){this.shaderInstances=new Map}return t.prototype.destroy=function(){this.shaderInstances.forEach((function(t){return t.destroy()})),this.shaderInstances.clear()},t}(),yh=function(){function t(t,e,i){if(void 0===i&&(i=null),this.visible=!0,this.castShadow=!1,this.transparent=!1,this._material=null,this._shaderCache=[],this.id=uh++,this.pick=!0,t instanceof hh){var n=t;t=e,e=i,i=n}this._key=[0,0],this.node=i,this._mesh=t,t.incRefCount(),this.material=e,this._shaderDefs=65536,this._shaderDefs|=t.vertexBuffer.format.hasUv0?4:0,this._shaderDefs|=t.vertexBuffer.format.hasUv1?8:0,this._shaderDefs|=t.vertexBuffer.format.hasColor?16:0,this._shaderDefs|=t.vertexBuffer.format.hasTangents?Ba:0,this.layer=15,this._renderStyle=0,this._receiveShadow=!0,this._screenSpace=!1,this._noDepthDrawGl1=!1,this.cull=!0,this._updateAabb=!0,this._updateAabbFunc=null,this._calculateSortDistance=null,this.updateKey(),this._skinInstance=null,this._morphInstance=null,this.instancingData=null,this._customAabb=null,this.aabb=new Ht,this._aabbVer=-1,this._aabbMeshVer=-1,this.drawOrder=0,this.visibleThisFrame=!1,this.isVisibleFunc=null,this.parameters={},this.stencilFront=null,this.stencilBack=null,this.flipFacesFactor=1}var e=t.prototype;return e.clearShaders=function(){for(var t=this._shaderCache,e=0;e<t.length;e++){var i;null==(i=t[e])||i.destroy(),t[e]=null}},e.getShaderInstance=function(t,e,i,n,s,r){var a,o=this._shaderCache[t];if(o?a=o.shaderInstances.get(e):(o=new gh,this._shaderCache[t]=o),!a){var h=this._material,l=this._shaderDefs,c=t+"_"+l+"_"+e;if((a=new vh).shader=h.variants.get(c),!a.shader){var u=h.getShaderVariant(this.mesh.device,i,l,null,t,r,n,s,this._mesh.vertexBuffer.format);h.variants.set(c,u),a.shader=u}o.shaderInstances.set(e,a)}return a},e._updateShaderDefs=function(t){t!==this._shaderDefs&&(this._shaderDefs=t,this.clearShaders())},e.destroy=function(){var e,i,n=this.mesh;n&&(this.mesh=null,n.refCount<1&&n.destroy()),this.setRealtimeLightmap(t.lightmapParamNames[0],null),this.setRealtimeLightmap(t.lightmapParamNames[1],null),null==(e=this._skinInstance)||e.destroy(),this._skinInstance=null,null==(i=this.morphInstance)||i.destroy(),this.morphInstance=null,this.clearShaders(),this.material=null},t._prepareRenderStyleForArray=function(t,e){if(t){for(var i=0;i<t.length;i++){t[i]._renderStyle=e;var n=t[i].mesh;mh.has(n)||(mh.add(n),n.prepareRenderState(e))}mh.clear()}},e._isVisible=function(t){return!!this.visible&&(this.isVisibleFunc?this.isVisibleFunc(t):(ph.center=this.aabb.center,ph.radius=this._aabb.halfExtents.length(),t.frustum.containsSphere(ph)))},e.updateKey=function(){var t=this.material,e=t.alphaToCoverage||t.alphaTest?2:t.blendType;this._key[0]=(15&this.layer)<<27|(3===e?1:0)<<26|(33554431&t.id)<<0},e.setInstancing=function(t){t?(this.instancingData=new _h(t.numVertices),this.instancingData.vertexBuffer=t,t.format.instancing=!0,this.cull=!1):(this.instancingData=null,this.cull=!0),this._updateShaderDefs(t?this._shaderDefs|Oa:-33&this._shaderDefs)},e.ensureMaterial=function(t){this.material||(this.material=Bo(t))},e.clearParameters=function(){this.parameters={}},e.getParameters=function(){return this.parameters},e.getParameter=function(t){return this.parameters[t]},e.setParameter=function(t,e,i){if(void 0===i&&(i=-262141),void 0===e&&"object"==typeof t){var n=t;if(n.length){for(var s=0;s<n.length;s++)this.setParameter(n[s]);return}t=n.name,e=n.value}var r=this.parameters[t];r?(r.data=e,r.passFlags=i):this.parameters[t]={scopeId:null,data:e,passFlags:i}},e.setRealtimeLightmap=function(t,e){var i=this.getParameter(t);i!==e&&(i&&ch.decRef(i.data),e?(ch.incRef(e),this.setParameter(t,e)):this.deleteParameter(t))},e.deleteParameter=function(t){this.parameters[t]&&delete this.parameters[t]},e.setParameters=function(t,e){var i=this.parameters;for(var n in i){var s=i[n];s.passFlags&e&&(s.scopeId||(s.scopeId=t.scope.resolve(n)),s.scopeId.setValue(s.data))}},e.setLightmapped=function(e){e?this.mask=-6&(2|this.mask):(this.setRealtimeLightmap(t.lightmapParamNames[0],null),this.setRealtimeLightmap(t.lightmapParamNames[1],null),this._shaderDefs&=-8385,this.mask=-7&(1|this.mask))},e.setCustomAabb=function(t){t?this._customAabb?this._customAabb.copy(t):this._customAabb=t.clone():(this._customAabb=null,this._aabbVer=-1),this._setupSkinUpdate()},e._setupSkinUpdate=function(){this._skinInstance&&(this._skinInstance._updateBeforeCull=!this._customAabb)},y(t,[{key:"renderStyle",get:function(){return this._renderStyle},set:function(t){this._renderStyle=t,this.mesh.prepareRenderState(t)}},{key:"mesh",get:function(){return this._mesh},set:function(t){t!==this._mesh&&(this._mesh&&this._mesh.decRefCount(),this._mesh=t,t&&t.incRefCount())}},{key:"aabb",get:function(){if(!this._updateAabb)return this._aabb;if(this._updateAabbFunc)return this._updateAabbFunc(this._aabb);var t=this._customAabb,e=!!t;if(!t)if(t=dh,this.skinInstance){if(!this.mesh.boneAabb){var i=this._morphInstance?this._morphInstance.morph._targets:null;this.mesh._initBoneAabbs(i)}for(var n=this.mesh.boneUsed,s=!0,r=0;r<this.mesh.boneAabb.length;r++)n[r]&&(fh.setFromTransformedAabb(this.mesh.boneAabb[r],this.skinInstance.matrices[r]),s?(s=!1,t.center.copy(fh.center),t.halfExtents.copy(fh.halfExtents)):t.add(fh));e=!0}else if(this.node._aabbVer!==this._aabbVer||this.mesh._aabbVer!==this._aabbMeshVer){if(this.mesh?(t.center.copy(this.mesh.aabb.center),t.halfExtents.copy(this.mesh.aabb.halfExtents)):(t.center.set(0,0,0),t.halfExtents.set(0,0,0)),this.mesh&&this.mesh.morph){var a=this.mesh.morph.aabb;t._expand(a.getMin(),a.getMax())}e=!0,this._aabbVer=this.node._aabbVer,this._aabbMeshVer=this.mesh._aabbVer}return e&&this._aabb.setFromTransformedAabb(t,this.node.getWorldTransform()),this._aabb},set:function(t){this._aabb=t}},{key:"material",get:function(){return this._material},set:function(t){this.clearShaders();var e=this._material;e&&e.removeMeshInstanceRef(this),this._material=t,t&&(t.addMeshInstanceRef(this),this.transparent=t.transparent,this.updateKey())}},{key:"layer",get:function(){return this._layer},set:function(t){this._layer=t,this.updateKey()}},{key:"calculateSortDistance",get:function(){return this._calculateSortDistance},set:function(t){this._calculateSortDistance=t}},{key:"receiveShadow",get:function(){return this._receiveShadow},set:function(t){this._receiveShadow!==t&&(this._receiveShadow=t,this._updateShaderDefs(t?-2&this._shaderDefs:1|this._shaderDefs))}},{key:"skinInstance",get:function(){return this._skinInstance},set:function(t){this._skinInstance=t,this._updateShaderDefs(t?2|this._shaderDefs:-3&this._shaderDefs),this._setupSkinUpdate()}},{key:"morphInstance",get:function(){return this._morphInstance},set:function(t){var e;null==(e=this._morphInstance)||e.destroy(),this._morphInstance=t;var i=this._shaderDefs;i=t&&t.morph.useTextureMorph?i|za:-4097&i,i=t&&t.morph.morphPositions?i|Ua:-1025&i,i=t&&t.morph.morphNormals?i|Na:-2049&i,this._updateShaderDefs(i)}},{key:"screenSpace",get:function(){return this._screenSpace},set:function(t){this._screenSpace!==t&&(this._screenSpace=t,this._updateShaderDefs(t?this._shaderDefs|Fa:-257&this._shaderDefs))}},{key:"key",get:function(){return this._key[0]},set:function(t){this._key[0]=t}},{key:"mask",get:function(){return this._shaderDefs>>16},set:function(t){var e=65535&this._shaderDefs;this._updateShaderDefs(e|t<<16)}},{key:"instancingCount",get:function(){return this.instancingData?this.instancingData.count:0},set:function(t){this.instancingData&&(this.instancingData.count=t)}}]),t}();function xh(t,e){if(t&&!e)return!1;if(!t&&e)return!1;if((t=t.data)===(e=e.data))return!0;if(t instanceof Float32Array&&e instanceof Float32Array){if(t.length!==e.length)return!1;for(var i=0;i<t.length;i++)if(t[i]!==e[i])return!1;return!0}return!1}function Sh(t,e){for(var i in t)if(t.hasOwnProperty(i)&&!xh(t[i],e[i]))return!1;for(var n in e)if(e.hasOwnProperty(n)&&!xh(e[n],t[n]))return!1;return!0}yh.lightmapParamNames=["texture_lightMap","texture_dirLightMap"];var bh=[0,1,3,2,3,1],wh=[0,1,3,0,3,2],Th=new At;function Ah(t){return t.node.worldTransform.scaleSign}var Ch,Eh=function(){function t(t,e,i){this.device=t,this.rootNode=e,this.scene=i,this._init=!1,this._batchGroups={},this._batchGroupCounter=0,this._batchList=[],this._dirtyGroups=[]}var e=t.prototype;return e.destroy=function(){this.device=null,this.rootNode=null,this.scene=null,this._batchGroups={},this._batchList=[],this._dirtyGroups=[]},e.addGroup=function(t,e,i,n,s){if(void 0===n&&(n=this._batchGroupCounter,this._batchGroupCounter++),!this._batchGroups[n]){var r=new Ho(n,t,e,i,s);return this._batchGroups[n]=r,r}},e.removeGroup=function(t){if(this._batchGroups[t]){for(var e=[],i=0;i<this._batchList.length;i++)this._batchList[i].batchGroupId===t?this.destroyBatch(this._batchList[i]):e.push(this._batchList[i]);this._batchList=e,this._removeModelsFromBatchGroup(this.rootNode,t),delete this._batchGroups[t]}},e.markGroupDirty=function(t){this._dirtyGroups.indexOf(t)<0&&this._dirtyGroups.push(t)},e.getGroupByName=function(t){var e=this._batchGroups;for(var i in e)if(e.hasOwnProperty(i)&&e[i].name===t)return e[i];return null},e.getBatches=function(t){for(var e=[],i=this._batchList.length,n=0;n<i;n++){var s=this._batchList[n];s.batchGroupId===t&&e.push(s)}return e},e._removeModelsFromBatchGroup=function(t,e){if(t.enabled){t.model&&t.model.batchGroupId===e&&(t.model.batchGroupId=-1),t.render&&t.render.batchGroupId===e&&(t.render.batchGroupId=-1),t.element&&t.element.batchGroupId===e&&(t.element.batchGroupId=-1),t.sprite&&t.sprite.batchGroupId===e&&(t.sprite.batchGroupId=-1);for(var i=0;i<t._children.length;i++)this._removeModelsFromBatchGroup(t._children[i],e)}},e.insert=function(t,e,i){var n=this._batchGroups[e];n&&n._obj[t].indexOf(i)<0&&(n._obj[t].push(i),this.markGroupDirty(e))},e.remove=function(t,e,i){var n=this._batchGroups[e];if(n){var s=n._obj[t].indexOf(i);s>=0&&(n._obj[t].splice(s,1),this.markGroupDirty(e))}},e._extractRender=function(t,e,i,n){return t.render&&(e=n[t.render.batchGroupId]=e.concat(t.render.meshInstances),t.render.removeFromLayers()),e},e._extractModel=function(t,e,i,n){return t.model&&t.model.model&&(e=n[t.model.batchGroupId]=e.concat(t.model.meshInstances),t.model.removeModelFromLayers()),e},e._extractElement=function(t,e,i){if(t.element){var n=!1;t.element._text&&t.element._text._model.meshInstances.length>0?(e.push(t.element._text._model.meshInstances[0]),t.element.removeModelFromLayers(t.element._text._model),n=!0):t.element._image&&(e.push(t.element._image._renderable.meshInstance),t.element.removeModelFromLayers(t.element._image._renderable.model),t.element._image._renderable.unmaskMeshInstance&&(e.push(t.element._image._renderable.unmaskMeshInstance),t.element._image._renderable.unmaskMeshInstance.stencilFront&&t.element._image._renderable.unmaskMeshInstance.stencilBack||(t.element._dirtifyMask(),t.element._onPrerender())),n=!0),n&&(i._ui=!0)}},e._collectAndRemoveMeshInstances=function(t,e){for(var i=0;i<e.length;i++){var n=e[i],s=this._batchGroups[n];if(s){var r=t[n];r||(r=t[n]=[]);for(var a=0;a<s._obj.model.length;a++)r=this._extractModel(s._obj.model[a],r,s,t);for(var o=0;o<s._obj.render.length;o++)r=this._extractRender(s._obj.render[o],r,s,t);for(var h=0;h<s._obj.element.length;h++)this._extractElement(s._obj.element[h],r,s);for(var l=0;l<s._obj.sprite.length;l++){var c=s._obj.sprite[l];c.sprite&&c.sprite._meshInstance&&(s.dynamic||0===c.sprite.sprite._renderMode)&&(r.push(c.sprite._meshInstance),c.sprite.removeModelFromLayers(),s._sprite=!0,c.sprite._batchGroup=s)}}}},e.generate=function(t){var e={};t||(t=Object.keys(this._batchGroups));for(var i,n,s,r,a=[],o=0;o<this._batchList.length;o++)t.indexOf(this._batchList[o].batchGroupId)<0?a.push(this._batchList[o]):this.destroyBatch(this._batchList[o]);if(this._batchList=a,this._collectAndRemoveMeshInstances(e,t),t===this._dirtyGroups)this._dirtyGroups.length=0;else{for(var h=[],l=0;l<this._dirtyGroups.length;l++)t.indexOf(this._dirtyGroups[l])<0&&h.push(this._dirtyGroups[l]);this._dirtyGroups=h}for(var c in e)if(e.hasOwnProperty(c)&&(i=e[c],s=this._batchGroups[c])){n=this.prepare(i,s.dynamic,s.maxAabbSize,s._ui||s._sprite);for(var u=0;u<n.length;u++)(r=this.create(n[u],s.dynamic,parseInt(c,10)))&&r.addToLayers(this.scene,s.layers)}},e.prepare=function(t,e,i,n){if(void 0===i&&(i=Number.POSITIVE_INFINITY),0===t.length)return[];var s,r=.5*i,a=this.device.supportsBoneTextures?1024:this.device.boneLimit,o=this.device.extUintElement?4294967295:65535,h=new Ht,l=new Ht,c=null,u=[],d=0;n&&t.sort((function(t,e){return t.drawOrder-e.drawOrder}));for(var f,p=t,m=n?function(t){c?c.add(t.aabb):c=t.aabb.clone(),f.push(t)}:function(t){f.push(t)};p.length>0;){u[d]=[p[0]],f=[];var _=p[0].material,v=p[0].layer,g=p[0]._shaderDefs,y=p[0].parameters,x=p[0].stencilFront,S=p[0].mesh.vertexBuffer.getNumVertices(),b=p[0].drawOrder;h.copy(p[0].aabb);var w=Ah(p[0]),T=p[0].mesh.vertexBuffer.format.batchingHash,A=p[0].mesh.primitive[0].indexed;c=null;for(var C=1;C<p.length;C++){var E=p[C];if(e&&u[d].length>=a){f=f.concat(p.slice(C));break}_!==E.material||v!==E.layer||T!==E.mesh.vertexBuffer.format.batchingHash||A!==E.mesh.primitive[0].indexed||g!==E._shaderDefs||S+E.mesh.vertexBuffer.getNumVertices()>o?m(E):(l.copy(h),l.add(E.aabb),l.halfExtents.x>r||l.halfExtents.y>r||l.halfExtents.z>r?m(E):(!x||(s=E.stencilFront)&&x.func===s.func&&x.zpass===s.zpass)&&w===Ah(E)&&Sh(y,E.parameters)?n&&c&&c.intersects(E.aabb)&&E.drawOrder!==b?m(E):(h.add(E.aabb),S+=E.mesh.vertexBuffer.getNumVertices(),u[d].push(E)):m(E))}d++,p=f}return u},e.collectBatchedMeshData=function(t,e){for(var i=null,n=0,s=0,r=null,a=0;a<t.length;a++)if(t[a].visible){var o=t[a].mesh;if(n+=o.vertexBuffer.numVertices,o.primitive[0].indexed)s+=o.primitive[0].count;else{var h=o.primitive[0].type;6!==h&&h!==be||4===o.primitive[0].count&&(s+=6)}if(!i){r=t[a].material,i={};for(var l=o.vertexBuffer.format.elements,c=0;c<l.length;c++){i[l[c].name]={numComponents:l[c].numComponents,dataType:l[c].dataType,normalize:l[c].normalize,count:0}}e&&(i[Ee]={numComponents:1,dataType:6,normalize:!1,count:0})}}return{streams:i,batchNumVerts:n,batchNumIndices:s,material:r}},e.create=function(t,e,i){if(!this._init){var n="#define BONE_LIMIT "+this.device.getBoneLimit()+"\n";this.transformVS=n+"#define DYNAMICBATCH\n"+_o.transformVS,this.skinTexVS=_o.skinBatchTexVS,this.skinConstVS=_o.skinBatchConstVS,this.vertexFormats={},this._init=!0}var s,r,a,o=null,h=null,l=this.collectBatchedMeshData(t,e);if(l.streams){var c,u,d,f=l.streams,p=l.material,m=l.batchNumVerts,_=l.batchNumIndices;h=new Go(t,e,i),this._batchList.push(h);var v,g=0,y=0,x=new wt,S=new(m<=65535?Uint16Array:Uint32Array)(_);for(s in f)(o=f[s]).typeArrayType=Ai[o.dataType],o.elementByteSize=Ci[o.dataType],o.buffer=new o.typeArrayType(m*o.numComponents);for(var b=0;b<t.length;b++)if(t[b].visible){for(s in a=(r=t[b].mesh).vertexBuffer.numVertices,e||(v=t[b].node.getWorldTransform()),f)if(s!==Ee){var w=new(o=f[s]).typeArrayType(o.buffer.buffer,o.elementByteSize*o.count),T=r.getVertexStream(s,w)*o.numComponents;if(o.count+=T,!e&&o.numComponents>=3)if(s===we)for(var A=0;A<T;A+=o.numComponents)x.set(w[A],w[A+1],w[A+2]),v.transformPoint(x,x),w[A]=x.x,w[A+1]=x.y,w[A+2]=x.z;else if(s===Te||s===Ae){Th.invertMat4(v).transpose();for(var C=0;C<T;C+=o.numComponents)x.set(w[C],w[C+1],w[C+2]),Th.transformVector(x,x),w[C]=x.x,w[C+1]=x.y,w[C+2]=x.z}}if(e){o=f[Ee];for(var E=0;E<a;E++)o.buffer[o.count++]=b}if(r.primitive[0].indexed){c=r.primitive[0].base,u=r.primitive[0].count;var M=r.indexBuffer[0].getFormat();d=new Mi[M](r.indexBuffer[0].storage)}else{var P=r.primitive[0].type;if(6===P||P===be){if(4!==r.primitive[0].count){u=0;continue}c=0,u=6,d=6===P?bh:wh}}for(var R=0;R<u;R++)S[R+y]=d[c+R]+g;y+=u,g+=a}for(s in r=new qa(this.device),f)o=f[s],r.setVertexStream(s,o.buffer,o.numComponents,void 0,o.dataType,o.normalize);S.length>0&&r.setIndices(S),r.update(4,!1),e&&((p=p.clone()).chunks.transformVS=this.transformVS,p.chunks.skinTexVS=this.skinTexVS,p.chunks.skinConstVS=this.skinConstVS,p.update());var I=new yh(r,p,this.rootNode);I.castShadow=h.origMeshInstances[0].castShadow,I.parameters=h.origMeshInstances[0].parameters,I.layer=h.origMeshInstances[0].layer,I._shaderDefs=h.origMeshInstances[0]._shaderDefs,I.cull=h.origMeshInstances[0].cull;var L=this._batchGroups[i];if(L&&L._ui&&(I.cull=!1),e){for(var D=[],O=0;O<h.origMeshInstances.length;O++)D.push(h.origMeshInstances[O].node);I.skinInstance=new jo(this.device,D,this.rootNode)}I._updateAabb=!1,I.drawOrder=h.origMeshInstances[0].drawOrder,I.stencilFront=h.origMeshInstances[0].stencilFront,I.stencilBack=h.origMeshInstances[0].stencilBack,I.flipFacesFactor=Ah(h.origMeshInstances[0]),I.castShadow=h.origMeshInstances[0].castShadow,h.meshInstance=I,h.updateBoundingBox()}return h},e.updateAll=function(){this._dirtyGroups.length>0&&this.generate(this._dirtyGroups);for(var t=0;t<this._batchList.length;t++)this._batchList[t].dynamic&&this._batchList[t].updateBoundingBox()},e.clone=function(t,e){var i=new Go(e,t.dynamic,t.batchGroupId);this._batchList.push(i);for(var n=[],s=0;s<e.length;s++)n.push(e[s].node);return i.meshInstance=new yh(t.meshInstance.mesh,t.meshInstance.material,t.meshInstance.node),i.meshInstance._updateAabb=!1,i.meshInstance.parameters=e[0].parameters,i.meshInstance.cull=e[0].cull,i.meshInstance.layer=e[0].layer,t.dynamic&&(i.meshInstance.skinInstance=new jo(this.device,n,this.rootNode)),i.meshInstance.castShadow=t.meshInstance.castShadow,i.meshInstance._shader=t.meshInstance._shader.slice(),i.meshInstance.castShadow=t.meshInstance.castShadow,i},e.destroyBatch=function(t){t.destroy(this.scene,this._batchGroups[t.batchGroupId].layers)},t}(),Mh=["uSceneColorMap","texture_grabPass"],Ph=function(t){function e(e,i){var n;return(n=t.call(this,e)||this).colorRenderTarget=null,n.camera=null,n.camera=i,n}S(e,t);var i=e.prototype;return i.destroy=function(){t.prototype.destroy.call(this),this.releaseRenderTarget(this.colorRenderTarget)},i.shouldReallocate=function(t,e,i){if((null==t?void 0:t.colorBuffer.format)!==i)return!0;var n=(null==e?void 0:e.width)||this.device.width,s=(null==e?void 0:e.height)||this.device.height;return!t||n!==t.width||s!==t.height},i.allocateRenderTarget=function(t,e,i,n){var s=i.isWebGL2,r=new Ls(i,{name:Mh[0],format:n,width:e?e.colorBuffer.width:i.width,height:e?e.colorBuffer.height:i.height,mipmaps:s,minFilter:s?5:1,magFilter:1,addressU:1,addressV:1});return t?(t.destroyFrameBuffers(),t._colorBuffer=r,t._colorBuffers=[r]):t=new rn({name:"ColorGrabRT",colorBuffer:r,depth:!1,stencil:!1,autoResolve:!1}),t},i.releaseRenderTarget=function(t){t&&(t.destroyTextureBuffers(),t.destroy())},i.before=function(){var t,e,i,n=this.camera,s=this.device,r=null!=(t=null==(e=n.renderTarget)?void 0:e.colorBuffer.format)?t:this.device.backBufferFormat;this.shouldReallocate(this.colorRenderTarget,null==(i=n.renderTarget)?void 0:i.colorBuffer,r)&&(this.releaseRenderTarget(this.colorRenderTarget),this.colorRenderTarget=this.allocateRenderTarget(this.colorRenderTarget,n.renderTarget,s,r));var a=this.colorRenderTarget.colorBuffer;Mh.forEach((function(t){return s.scope.resolve(t).setValue(a)}))},i.execute=function(){var t=this.device,e=this.colorRenderTarget.colorBuffer;if(t.isWebGPU)t.copyRenderTarget(this.camera.renderTarget,this.colorRenderTarget,!0,!1),t.mipmapRenderer.generate(this.colorRenderTarget.colorBuffer.impl);else if(t.isWebGL2)t.copyRenderTarget(t.renderTarget,this.colorRenderTarget,!0,!1),t.activeTexture(t.maxCombinedTextures-1),t.bindTexture(e),t.gl.generateMipmap(e.impl._glTarget);else{e.impl._glTexture||e.impl.initialize(t,e),t.bindTexture(e);var i=t.gl;i.copyTexImage2D(i.TEXTURE_2D,0,e.impl._glFormat,0,0,e.width,e.height,0),e._needsUpload=!1,e._needsMipmapsUpload=!1}},e}(uo),Rh=["uSceneDepthMap","uDepthMap"],Ih=function(t){function e(e,i){var n;return(n=t.call(this,e)||this).depthRenderTarget=null,n.camera=null,n.camera=i,n}S(e,t);var i=e.prototype;return i.destroy=function(){t.prototype.destroy.call(this),this.releaseRenderTarget(this.depthRenderTarget)},i.shouldReallocate=function(t,e){var i=(null==e?void 0:e.width)||this.device.width,n=(null==e?void 0:e.height)||this.device.height;return!t||i!==t.width||n!==t.height},i.allocateRenderTarget=function(t,e,i,n,s){var r=new Ls(i,{name:Rh[0],format:n,width:e?e.colorBuffer.width:i.width,height:e?e.colorBuffer.height:i.height,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1});return t?(t.destroyFrameBuffers(),s?t._depthBuffer=r:(t._colorBuffer=r,t._colorBuffers=[r])):t=new rn({name:"DepthGrabRT",colorBuffer:s?null:r,depthBuffer:s?r:null,depth:!s,stencil:i.supportsStencil,autoResolve:!1}),t},i.releaseRenderTarget=function(t){t&&(t.destroyTextureBuffers(),t.destroy())},i.before=function(){var t,e,i,n,s,r=this.camera,a=this.device,o=!0,h=de;a.isWebGPU&&((null!=(n=null==(s=r.renderTarget)?void 0:s.samples)?n:a.samples)>1&&(h=ce,o=!1));var l=null!=(t=null==(e=r.renderTarget)?void 0:e.depthBuffer)?t:null==(i=r.renderTarget)?void 0:i.colorBuffer;this.shouldReallocate(this.depthRenderTarget,l)&&(this.releaseRenderTarget(this.depthRenderTarget),this.depthRenderTarget=this.allocateRenderTarget(this.depthRenderTarget,r.renderTarget,a,h,o));var c=o?this.depthRenderTarget.depthBuffer:this.depthRenderTarget.colorBuffer;Rh.forEach((function(t){return a.scope.resolve(t).setValue(c)}))},i.execute=function(){var t=this.device;if(t.isWebGL2&&t.renderTarget.samples>1){var e=t.renderTarget.impl._glFrameBuffer,i=this.depthRenderTarget;t.renderTarget=i,t.updateBegin(),this.depthRenderTarget.impl.internalResolve(t,e,i.impl._glFrameBuffer,this.depthRenderTarget,t.gl.DEPTH_BUFFER_BIT)}else t.copyRenderTarget(t.renderTarget,this.depthRenderTarget,!1,!0)},e}(uo),Lh=new vt(254/255,254/255,254/255,254/255),Dh=[],Oh=[[],[],[]],kh=["uSceneDepthMap","uDepthMap"],Fh=function(t){function e(e,i,n){var s;return(s=t.call(this,e)||this).renderer=i,s.camera=n,s}S(e,t);var i=e.prototype;return i.destroy=function(){t.prototype.destroy.call(this),this.releaseRenderTarget(this.renderTarget)},i.update=function(t){this.scene=t},i.shouldReallocate=function(t,e){var i=e.width,n=e.height;return!t||i!==t.width||n!==t.height},i.allocateRenderTarget=function(t,e,i){var n,s,r=new Ls(i,{name:kh[0],format:7,width:null!=(n=null==e?void 0:e.width)?n:this.device.width,height:null!=(s=null==e?void 0:e.height)?s:this.device.height,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1});return t?(t.destroyFrameBuffers(),t._colorBuffer=r,t._colorBuffers=[r]):t=new rn({name:kh[0]+"RT}",colorBuffer:r,depth:!0,stencil:!1}),t},i.releaseRenderTarget=function(t){t&&(t.destroyTextureBuffers(),t.destroy())},i.before=function(){var t,e=this.camera,i=this.device,n=null!=(t=e.renderTarget)?t:i.backBuffer;if(this.shouldReallocate(this.renderTarget,n)){var s;null==(s=this.renderTarget)||s.destroyTextureBuffers();var r=this.allocateRenderTarget(this.renderTarget,e.renderTarget,i);this.renderTarget?this.renderTarget=r:(this.init(r),this.setClearColor(Lh),this.setClearDepth(1))}var a=this.renderTarget.colorBuffer;kh.forEach((function(t){return i.scope.resolve(t).setValue(a)}))},i.execute=function(){for(var t=this.device,e=this.renderer,i=this.camera,n=this.scene,s=this.renderTarget,r=n.layers.layerList,a=n.layers.subLayerEnabled,o=n.layers.subLayerList,h=0;h<r.length;h++){var l=r[h];if(l.enabled&&a[h]&&l.camerasSet.has(i)){if(1===l.id)break;for(var c=l.getCulledInstances(i),u=o[h]?c.transparent:c.opaque,d=0;d<u.length;d++){var f,p=u[d];null!=(f=p.material)&&f.depthWrite&&!p._noDepthDrawGl1&&Dh.push(p)}e.setCameraUniforms(i,s),e.renderForward(i,Dh,Oh,2,(function(e){t.setBlendState(Ui.NOBLEND)}),l),Dh.length=0}}},e}(uo),Bh=new wt,Uh=new wt,Nh=new wt,zh=new Ft,Vh=[new wt,new wt,new wt,new wt,new wt,new wt,new wt,new wt],Gh=function(){function t(){this.shaderPassInfo=null,this.renderPassColorGrab=null,this.renderPassDepthGrab=null,this._aspectRatio=16/9,this._aspectRatioMode=0,this._calculateProjection=null,this._calculateTransform=null,this._clearColor=new vt(.75,.75,.75,1),this._clearColorBuffer=!0,this._clearDepth=1,this._clearDepthBuffer=!0,this._clearStencil=0,this._clearStencilBuffer=!0,this._cullFaces=!0,this._farClip=1e3,this._flipFaces=!1,this._fov=45,this._frustumCulling=!0,this._horizontalFov=!1,this._layers=[0,1,2,4,3],this._layersSet=new Set(this._layers),this._nearClip=.1,this._node=null,this._orthoHeight=10,this._projection=0,this._rect=new Pt(0,0,1,1),this._renderTarget=null,this._scissorRect=new Pt(0,0,1,1),this._scissorRectClear=!1,this._aperture=16,this._shutter=.001,this._sensitivity=1e3,this._projMat=new Ft,this._projMatDirty=!0,this._projMatSkybox=new Ft,this._viewMat=new Ft,this._viewMatDirty=!0,this._viewProjMat=new Ft,this._viewProjMatDirty=!0,this.frustum=new qt,this._xr=null,this._xrProperties={horizontalFov:this._horizontalFov,fov:this._fov,aspectRatio:this._aspectRatio,farClip:this._farClip,nearClip:this._nearClip}}var e=t.prototype;return e.destroy=function(){var t,e;null==(t=this.renderPassColorGrab)||t.destroy(),this.renderPassColorGrab=null,null==(e=this.renderPassDepthGrab)||e.destroy(),this.renderPassDepthGrab=null},e.clone=function(){return(new t).copy(this)},e.copy=function(t){return this._aspectRatio=t._aspectRatio,this._farClip=t._farClip,this._fov=t._fov,this._horizontalFov=t._horizontalFov,this._nearClip=t._nearClip,this._xrProperties.aspectRatio=t._xrProperties.aspectRatio,this._xrProperties.farClip=t._xrProperties.farClip,this._xrProperties.fov=t._xrProperties.fov,this._xrProperties.horizontalFov=t._xrProperties.horizontalFov,this._xrProperties.nearClip=t._xrProperties.nearClip,this.aspectRatioMode=t.aspectRatioMode,this.calculateProjection=t.calculateProjection,this.calculateTransform=t.calculateTransform,this.clearColor=t.clearColor,this.clearColorBuffer=t.clearColorBuffer,this.clearDepth=t.clearDepth,this.clearDepthBuffer=t.clearDepthBuffer,this.clearStencil=t.clearStencil,this.clearStencilBuffer=t.clearStencilBuffer,this.cullFaces=t.cullFaces,this.flipFaces=t.flipFaces,this.frustumCulling=t.frustumCulling,this.layers=t.layers,this.orthoHeight=t.orthoHeight,this.projection=t.projection,this.rect=t.rect,this.renderTarget=t.renderTarget,this.scissorRect=t.scissorRect,this.aperture=t.aperture,this.shutter=t.shutter,this.sensitivity=t.sensitivity,this.shaderPassInfo=t.shaderPassInfo,this._projMatDirty=!0,this},e._enableRenderPassColorGrab=function(t,e){var i;e?this.renderPassColorGrab||(this.renderPassColorGrab=new Ph(t,this)):(null==(i=this.renderPassColorGrab)||i.destroy(),this.renderPassColorGrab=null)},e._enableRenderPassDepthGrab=function(t,e,i){var n;i?this.renderPassDepthGrab||(this.renderPassDepthGrab=t.isWebGL1?new Fh(t,e,this):new Ih(t,this)):(null==(n=this.renderPassDepthGrab)||n.destroy(),this.renderPassDepthGrab=null)},e._updateViewProjMat=function(){(this._projMatDirty||this._viewMatDirty||this._viewProjMatDirty)&&(this._viewProjMat.mul2(this.projectionMatrix,this.viewMatrix),this._viewProjMatDirty=!1)},e.worldToScreen=function(t,e,i,n){void 0===n&&(n=new wt),this._updateViewProjMat(),this._viewProjMat.transformPoint(t,n);var s=this._viewProjMat.data,r=t.x*s[3]+t.y*s[7]+t.z*s[11]+1*s[15];return n.x=.5*(n.x/r+1)*e,n.y=.5*(1-n.y/r)*i,n},e.screenToWorld=function(t,e,i,n,s,r){void 0===r&&(r=new wt);var a=this.farClip-this.nearClip;if(Bh.set(t/n,(s-e)/s,i/a),Bh.mulScalar(2),Bh.sub(wt.ONE),0===this._projection){Ft._getPerspectiveHalfSize(Uh,this.fov,this.aspectRatio,this.nearClip,this.horizontalFov),Uh.x*=Bh.x,Uh.y*=Bh.y;var o=this._node.getWorldTransform();Uh.z=-this.nearClip,o.transformPoint(Uh,Nh);var h=this._node.getPosition();r.sub2(Nh,h),r.normalize(),r.mulScalar(i),r.add(h)}else this._updateViewProjMat(),zh.copy(this._viewProjMat).invert(),zh.transformPoint(Bh,r);return r},e._evaluateProjectionMatrix=function(){if(this._projMatDirty){if(0===this._projection)this._projMat.setPerspective(this.fov,this.aspectRatio,this.nearClip,this.farClip,this.horizontalFov),this._projMatSkybox.copy(this._projMat);else{var t=this._orthoHeight,e=t*this.aspectRatio;this._projMat.setOrtho(-e,e,-t,t,this.nearClip,this.farClip),this._projMatSkybox.setPerspective(this.fov,this.aspectRatio,this.nearClip,this.farClip)}this._projMatDirty=!1}},e.getProjectionMatrixSkybox=function(){return this._evaluateProjectionMatrix(),this._projMatSkybox},e.getExposure=function(){var t=Math.log2(this._aperture*this._aperture/this._shutter*100/this._sensitivity);return 1/(1.2*Math.pow(2,t))},e.getScreenSize=function(t){if(0===this._projection){var e=this._node.getPosition().distance(t.center);if(e<t.radius)return 1;var i=Math.asin(t.radius/e),n=Math.tan(i),s=Math.tan(this.fov/2*_t.DEG_TO_RAD);return Math.min(n/s,1)}return _t.clamp(t.radius/this._orthoHeight,0,1)},e.getFrustumCorners=function(t,e){void 0===t&&(t=this.nearClip),void 0===e&&(e=this.farClip);var i=this.fov*Math.PI/180,n=0===this._projection?Math.tan(i/2)*t:this._orthoHeight,s=n*this.aspectRatio,r=Vh;return r[0].x=s,r[0].y=-n,r[0].z=-t,r[1].x=s,r[1].y=n,r[1].z=-t,r[2].x=-s,r[2].y=n,r[2].z=-t,r[3].x=-s,r[3].y=-n,r[3].z=-t,0===this._projection&&(s=(n=Math.tan(i/2)*e)*this.aspectRatio),r[4].x=s,r[4].y=-n,r[4].z=-e,r[5].x=s,r[5].y=n,r[5].z=-e,r[6].x=-s,r[6].y=n,r[6].z=-e,r[7].x=-s,r[7].y=-n,r[7].z=-e,r},e.setXrProperties=function(t){Object.assign(this._xrProperties,t),this._projMatDirty=!0},y(t,[{key:"fullSizeClearRect",get:function(){var t=this._scissorRectClear?this.scissorRect:this._rect;return 0===t.x&&0===t.y&&1===t.z&&1===t.w}},{key:"aspectRatio",get:function(){var t;return null!=(t=this.xr)&&t.active?this._xrProperties.aspectRatio:this._aspectRatio},set:function(t){this._aspectRatio!==t&&(this._aspectRatio=t,this._projMatDirty=!0)}},{key:"aspectRatioMode",get:function(){return this._aspectRatioMode},set:function(t){this._aspectRatioMode!==t&&(this._aspectRatioMode=t,this._projMatDirty=!0)}},{key:"calculateProjection",get:function(){return this._calculateProjection},set:function(t){this._calculateProjection=t,this._projMatDirty=!0}},{key:"calculateTransform",get:function(){return this._calculateTransform},set:function(t){this._calculateTransform=t}},{key:"clearColor",get:function(){return this._clearColor},set:function(t){this._clearColor.copy(t)}},{key:"clearColorBuffer",get:function(){return this._clearColorBuffer},set:function(t){this._clearColorBuffer=t}},{key:"clearDepth",get:function(){return this._clearDepth},set:function(t){this._clearDepth=t}},{key:"clearDepthBuffer",get:function(){return this._clearDepthBuffer},set:function(t){this._clearDepthBuffer=t}},{key:"clearStencil",get:function(){return this._clearStencil},set:function(t){this._clearStencil=t}},{key:"clearStencilBuffer",get:function(){return this._clearStencilBuffer},set:function(t){this._clearStencilBuffer=t}},{key:"cullFaces",get:function(){return this._cullFaces},set:function(t){this._cullFaces=t}},{key:"farClip",get:function(){var t;return null!=(t=this.xr)&&t.active?this._xrProperties.farClip:this._farClip},set:function(t){this._farClip!==t&&(this._farClip=t,this._projMatDirty=!0)}},{key:"flipFaces",get:function(){return this._flipFaces},set:function(t){this._flipFaces=t}},{key:"fov",get:function(){var t;return null!=(t=this.xr)&&t.active?this._xrProperties.fov:this._fov},set:function(t){this._fov!==t&&(this._fov=t,this._projMatDirty=!0)}},{key:"frustumCulling",get:function(){return this._frustumCulling},set:function(t){this._frustumCulling=t}},{key:"horizontalFov",get:function(){var t;return null!=(t=this.xr)&&t.active?this._xrProperties.horizontalFov:this._horizontalFov},set:function(t){this._horizontalFov!==t&&(this._horizontalFov=t,this._projMatDirty=!0)}},{key:"layers",get:function(){return this._layers},set:function(t){this._layers=t.slice(0),this._layersSet=new Set(this._layers)}},{key:"layersSet",get:function(){return this._layersSet}},{key:"nearClip",get:function(){var t;return null!=(t=this.xr)&&t.active?this._xrProperties.nearClip:this._nearClip},set:function(t){this._nearClip!==t&&(this._nearClip=t,this._projMatDirty=!0)}},{key:"node",get:function(){return this._node},set:function(t){this._node=t}},{key:"orthoHeight",get:function(){return this._orthoHeight},set:function(t){this._orthoHeight!==t&&(this._orthoHeight=t,this._projMatDirty=!0)}},{key:"projection",get:function(){return this._projection},set:function(t){this._projection!==t&&(this._projection=t,this._projMatDirty=!0)}},{key:"projectionMatrix",get:function(){return this._evaluateProjectionMatrix(),this._projMat}},{key:"rect",get:function(){return this._rect},set:function(t){this._rect.copy(t)}},{key:"renderTarget",get:function(){return this._renderTarget},set:function(t){this._renderTarget=t}},{key:"scissorRect",get:function(){return this._scissorRect},set:function(t){this._scissorRect.copy(t)}},{key:"viewMatrix",get:function(){if(this._viewMatDirty){var t=this._node.getWorldTransform();this._viewMat.copy(t).invert(),this._viewMatDirty=!1}return this._viewMat}},{key:"aperture",get:function(){return this._aperture},set:function(t){this._aperture=t}},{key:"sensitivity",get:function(){return this._sensitivity},set:function(t){this._sensitivity=t}},{key:"shutter",get:function(){return this._shutter},set:function(t){this._shutter=t}},{key:"xr",get:function(){return this._xr},set:function(t){this._xr!==t&&(this._xr=t,this._projMatDirty=!0)}}]),t}(),Hh=function(){this.hasTangents=!1,this.chunks={},this.pass=0,this.alphaTest=!1,this.blendType=3,this.separateAmbient=!1,this.screenSpace=!1,this.skin=!1,this.useInstancing=!1,this.useMorphPosition=!1,this.useMorphNormal=!1,this.useMorphTextureBased=!1,this.nineSlicedMode=0,this.clusteredLightingEnabled=!0,this.clusteredLightingCookiesEnabled=!1,this.clusteredLightingShadowsEnabled=!1,this.clusteredLightingShadowType=0,this.clusteredLightingAreaLightsEnabled=!1,this.vertexColors=!1,this.lightMapEnabled=!1,this.dirLightMapEnabled=!1,this.useHeights=!1,this.useNormals=!1,this.useClearCoatNormals=!1,this.useAo=!1,this.diffuseMapEnabled=!1,this.useAmbientTint=!1,this.customFragmentShader=null,this.pixelSnap=!1,this.shadingModel=0,this.ambientSH=!1,this.fastTbn=!1,this.twoSidedLighting=!1,this.occludeDirect=!1,this.occludeSpecular=0,this.occludeSpecularFloat=!1,this.useMsdf=!1,this.msdfTextAttribute=!1,this.alphaToCoverage=!1,this.opacityFadesSpecular=!1,this.cubeMapProjection=0,this.conserveEnergy=!1,this.useSpecular=!1,this.useSpecularityFactor=!1,this.enableGGXSpecular=!1,this.fresnelModel=0,this.useRefraction=!1,this.useClearCoat=!1,this.useSheen=!1,this.useIridescence=!1,this.useMetalness=!1,this.useDynamicRefraction=!1,this.fog=Ra,this.gamma=0,this.toneMap=-1,this.fixSeams=!1,this.reflectionSource=null,this.reflectionEncoding=null,this.reflectionCubemapEncoding=null,this.ambientSource="constant",this.ambientEncoding=null,this.skyboxIntensity=1,this.useCubeMapRotation=!1,this.lightMapWithoutAmbient=!1,this.lights=[],this.noShadow=!1,this.lightMaskDynamic=0,this.userAttributes={}},Wh=function(){function t(){}return t.update=function(e,i,n,s,r,a){t.updateSharedOptions(e,i,n,s,r),t.updateMaterialOptions(e,i),t.updateEnvOptions(e,i,n),t.updateLightingOptions(e,i,s,a),1===r&&(e.gamma=3,e.toneMap=0)},t.updateSharedOptions=function(t,e,i,n,s){t.chunks=e.chunks,t.pass=s,t.alphaTest=e.alphaTest>0,t.blendType=e.blendType,t.screenSpace=n&&0!=(n&Fa),t.skin=n&&0!=(2&n),t.useInstancing=n&&0!=(n&Oa),t.useMorphPosition=n&&0!=(n&Ua),t.useMorphNormal=n&&0!=(n&Na),t.useMorphTextureBased=n&&0!=(n&za),t.hasTangents=n&&0!=(n&Ba),t.nineSlicedMode=e.nineSlicedMode||0,e.useLighting&&i.clusteredLightingEnabled?(t.clusteredLightingEnabled=!0,t.clusteredLightingCookiesEnabled=i.lighting.cookiesEnabled,t.clusteredLightingShadowsEnabled=i.lighting.shadowsEnabled,t.clusteredLightingShadowType=i.lighting.shadowType,t.clusteredLightingAreaLightsEnabled=i.lighting.areaLightsEnabled):(t.clusteredLightingEnabled=!1,t.clusteredLightingCookiesEnabled=!1,t.clusteredLightingShadowsEnabled=!1,t.clusteredLightingAreaLightsEnabled=!1)},t.updateMaterialOptions=function(t,e){t.useAmbientTint=!1,t.separateAmbient=!1,t.customFragmentShader=null,t.pixelSnap=e.pixelSnap,t.shadingModel=e.shadingModel,t.ambientSH=e.ambientSH,t.fastTbn=e.fastTbn,t.twoSidedLighting=e.twoSidedLighting,t.occludeDirect=e.occludeDirect,t.occludeSpecular=e.occludeSpecular,t.occludeSpecularFloat=1!==e.occludeSpecularIntensity,t.useMsdf=!1,t.msdfTextAttribute=!1,t.alphaToCoverage=e.alphaToCoverage,t.opacityFadesSpecular=e.opacityFadesSpecular,t.cubeMapProjection=0,t.conserveEnergy=e.conserveEnergy&&1===e.shadingModel,t.useSpecular=e.hasSpecular,t.useSpecularityFactor=e.hasSpecularityFactor,t.enableGGXSpecular=e.ggxSpecular,t.fresnelModel=e.fresnelModel,t.useRefraction=e.hasRefraction,t.useClearCoat=e.hasClearCoat,t.useSheen=e.hasSheen,t.useIridescence=e.hasIrridescence,t.useMetalness=e.hasMetalness,t.useDynamicRefraction=e.dynamicRefraction,t.vertexColors=!1,t.lightMapEnabled=e.hasLighting,t.dirLightMapEnabled=e.dirLightMap,t.useHeights=e.hasHeights,t.useNormals=e.hasNormals,t.useClearCoatNormals=e.hasClearCoatNormals,t.useAo=e.hasAo,t.diffuseMapEnabled=e.hasDiffuseMap},t.updateEnvOptions=function(t,e,i){t.fog=e.useFog?i.fog:"none",t.gamma=e.useGammaTonemap?i.gammaCorrection:0,t.toneMap=e.useGammaTonemap?i.toneMapping:-1,t.fixSeams=!1,e.useSkybox&&i.envAtlas&&i.skybox?(t.reflectionSource="envAtlasHQ",t.reflectionEncoding=i.envAtlas.encoding,t.reflectionCubemapEncoding=i.skybox.encoding):e.useSkybox&&i.envAtlas?(t.reflectionSource="envAtlas",t.reflectionEncoding=i.envAtlas.encoding):e.useSkybox&&i.skybox?(t.reflectionSource="cubeMap",t.reflectionEncoding=i.skybox.encoding):(t.reflectionSource=null,t.reflectionEncoding=null),e.ambientSH?(t.ambientSource="ambientSH",t.ambientEncoding=null):t.reflectionSource&&i.envAtlas?(t.ambientSource="envAtlas",t.ambientEncoding=i.envAtlas.encoding):(t.ambientSource="constant",t.ambientEncoding=null);var n=!!t.reflectionSource;t.skyboxIntensity=n&&(1!==i.skyboxIntensity||i.physicalUnits),t.useCubeMapRotation=n&&i._skyboxRotationShaderInclude},t.updateLightingOptions=function(e,i,n,s){if(e.lightMapWithoutAmbient=!1,i.useLighting){var r=[],a=n?n>>16:1;e.lightMaskDynamic=!!(1&a),e.lightMapWithoutAmbient=!1,s&&(t.collectLights(0,s[0],r,a),t.collectLights(1,s[1],r,a),t.collectLights(2,s[2],r,a)),e.lights=r}else e.lights=[];0!==e.lights.length&&0==(1&n)||(e.noShadow=!0)},t.collectLights=function(t,e,i,n){for(var s=0;s<e.length;s++){var r=e[s];r.enabled&&r.mask&n&&i.push(r)}},t}(),Xh=function(){function t(){this.code=""}var e=t.prototype;return e.append=function(){for(var t=this,e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];i.forEach((function(e){e.endsWith("\n")?t.code+=e:t.code+=e+"\n"}))},e.prepend=function(){for(var t=this,e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];i.forEach((function(e){e.endsWith("\n")?t.code=e+t.code:t.code=e+"\n"+t.code}))},t}(),jh={linear:"decodeLinear",srgb:"decodeGamma",rgbm:"decodeRGBM",rgbe:"decodeRGBE",rgbp:"decodeRGBP"},qh={linear:"encodeLinear",srgb:"encodeGamma",rgbm:"encodeRGBM",rgbe:"encodeRGBE",rgbp:"encodeRGBP"},Yh=function(){function t(){}return t.decodeFunc=function(t){return jh[t]||"decodeGamma"},t.encodeFunc=function(t){return qh[t]||"encodeGamma"},t}(),Kh=1/255,Zh=new Float32Array(1),Qh=new Int32Array(Zh.buffer),$h=function(){function t(){}return t.float2Half=function(t){Zh[0]=t;var e=Qh[0],i=e>>16&32768,n=e>>12&2047,s=e>>23&255;return s<103?i:s>142?(i|=31744,i|=(255===s?0:1)&&8388607&e):s<113?i|=((n|=2048)>>114-s)+(n>>113-s&1):(i|=s-112<<10|n>>1,i+=1&n)},t.float2Bytes=function(t,e,i,n){var s=255*t%1;if(e[i+0]=Math.round(255*(t%1-Kh*s)),n>1){var r=65025*t%1;if(e[i+1]=Math.round(255*(s-Kh*r)),n>2){var a=16581375*t%1;e[i+2]=Math.round(255*(r-Kh*a)),n>3&&(e[i+3]=Math.round(255*a))}}},t.float2BytesRange=function(e,i,n,s,r,a){e=_t.clamp((e-s)/(r-s),0,1),t.float2Bytes(e,i,n,a)},t.float2MantissaExponent=function(e,i,n,s){var r=Math.floor(Math.log2(Math.abs(e)))+1;e/=Math.pow(2,r),t.float2BytesRange(e,i,n,-1,1,s-1),i[n+s-1]=Math.round(r+127)},t}(),Jh=new Ft,tl=new Ft,el=new Ft,il=function(){function t(){}return t.create=function(e,i,n){var s=new Gh;switch(s.node=new hh(e),s.aspectRatio=1,s.aspectRatioMode=1,s._scissorRectClear=!0,i){case 1:s.node.setRotation(t.pointLightRotations[n]),s.fov=90,s.projection=0;break;case 2:s.projection=0;break;case 0:s.projection=1}return s},t.evalSpotCookieMatrix=function(e){var i=t._spotCookieCamera;i||(i=t.create("SpotCookieCamera",2),t._spotCookieCamera=i),i.fov=2*e._outerConeAngle;var n=i._node;n.setPosition(e._node.getPosition()),n.setRotation(e._node.getRotation()),n.rotateLocal(-90,0,0),Jh.setTRS(n.getPosition(),n.getRotation(),wt.ONE).invert(),tl.mul2(i.projectionMatrix,Jh);var s=e.cookieMatrix,r=e.atlasViewport;return el.setViewport(r.x,r.y,r.z,r.w),s.mul2(el,tl),s},t}();il.pointLightRotations=[(new Bt).setFromEulerAngles(0,90,180),(new Bt).setFromEulerAngles(0,-90,180),(new Bt).setFromEulerAngles(90,0,0),(new Bt).setFromEulerAngles(-90,0,0),(new Bt).setFromEulerAngles(0,180,180),(new Bt).setFromEulerAngles(0,0,180)],il._spotCookieCamera=null;var nl=new wt,sl=new Float32Array(6),rl=new wt(-.5,0,0),al=new wt(0,0,.5),ol={FLAGS:0,COLOR_A:1,COLOR_B:2,SPOT_ANGLES:3,SHADOW_BIAS:4,COOKIE_A:5,COOKIE_B:6,COUNT_ALWAYS:7,POSITION_X:7,POSITION_Y:8,POSITION_Z:9,RANGE:10,SPOT_DIRECTION_X:11,SPOT_DIRECTION_Y:12,SPOT_DIRECTION_Z:13,PROJ_MAT_00:14,ATLAS_VIEWPORT_A:14,PROJ_MAT_01:15,ATLAS_VIEWPORT_B:15,PROJ_MAT_02:16,PROJ_MAT_03:17,PROJ_MAT_10:18,PROJ_MAT_11:19,PROJ_MAT_12:20,PROJ_MAT_13:21,PROJ_MAT_20:22,PROJ_MAT_21:23,PROJ_MAT_22:24,PROJ_MAT_23:25,PROJ_MAT_30:26,PROJ_MAT_31:27,PROJ_MAT_32:28,PROJ_MAT_33:29,AREA_DATA_WIDTH_X:30,AREA_DATA_WIDTH_Y:31,AREA_DATA_WIDTH_Z:32,AREA_DATA_HEIGHT_X:33,AREA_DATA_HEIGHT_Y:34,AREA_DATA_HEIGHT_Z:35,COUNT:36},hl={POSITION_RANGE:0,SPOT_DIRECTION:1,PROJ_MAT_0:2,ATLAS_VIEWPORT:2,PROJ_MAT_1:3,PROJ_MAT_2:4,PROJ_MAT_3:5,AREA_DATA_WIDTH:6,AREA_DATA_HEIGHT:7,COUNT:8},ll=function(){function t(e){this.device=e,this.cookiesEnabled=!1,this.shadowsEnabled=!1,this.areaLightsEnabled=!1,this.maxLights=255;var i=ol.COUNT_ALWAYS,n=0;t.lightTextureFormat===t.FORMAT_FLOAT?n=hl.COUNT:i=ol.COUNT,this.lights8=new Uint8ClampedArray(4*i*this.maxLights),this.lightsTexture8=t.createTexture(this.device,i,this.maxLights,7,"LightsTexture8"),this._lightsTexture8Id=this.device.scope.resolve("lightsTexture8"),n?(this.lightsFloat=new Float32Array(4*n*this.maxLights),this.lightsTextureFloat=t.createTexture(this.device,n,this.maxLights,le,"LightsTextureFloat"),this._lightsTextureFloatId=this.device.scope.resolve("lightsTextureFloat")):(this.lightsFloat=null,this.lightsTextureFloat=null,this._lightsTextureFloatId=void 0),this._lightsTextureInvSizeId=this.device.scope.resolve("lightsTextureInvSize"),this._lightsTextureInvSizeData=new Float32Array(4),this._lightsTextureInvSizeData[0]=n?1/this.lightsTextureFloat.width:0,this._lightsTextureInvSizeData[1]=n?1/this.lightsTextureFloat.height:0,this._lightsTextureInvSizeData[2]=1/this.lightsTexture8.width,this._lightsTextureInvSizeData[3]=1/this.lightsTexture8.height,this.invMaxColorValue=0,this.invMaxAttenuation=0,this.boundsMin=new wt,this.boundsDelta=new wt}t.initShaderDefines=function(){var e=t.lightTextureFormat===t.FORMAT_FLOAT?"FLOAT":"8BIT";t.shaderDefines="\n \n#define CLUSTER_TEXTURE_"+e+"\n "+t.buildShaderDefines(ol,"CLUSTER_TEXTURE_8_")+"\n "+t.buildShaderDefines(hl,"CLUSTER_TEXTURE_F_")+"\n "},t.buildShaderDefines=function(e,i){var n="",s=t.useTexelFetch?"":".5";return Object.keys(e).forEach((function(t){n+="\n#define "+i+t+" "+e[t]+s})),n},t.init=function(e){t.lightTextureFormat=e.extTextureFloat&&e.maxTextures>8?t.FORMAT_FLOAT:t.FORMAT_8BIT,t.useTexelFetch=e.supportsTextureFetch,t.initShaderDefines()},t.createTexture=function(t,e,i,n,s){return new Ls(t,{name:s,width:e,height:i,mipmaps:!1,format:n,addressU:1,addressV:1,type:ei,magFilter:0,minFilter:0,anisotropy:1})};var e=t.prototype;return e.destroy=function(){this.lightsTexture8&&(this.lightsTexture8.destroy(),this.lightsTexture8=null),this.lightsTextureFloat&&(this.lightsTextureFloat.destroy(),this.lightsTextureFloat=null)},e.setCompressionRanges=function(t,e){this.invMaxColorValue=1/e,this.invMaxAttenuation=1/t},e.setBounds=function(t,e){this.boundsMin.copy(t),this.boundsDelta.copy(e)},e.uploadTextures=function(){this.lightsTextureFloat&&(this.lightsTextureFloat.lock().set(this.lightsFloat),this.lightsTextureFloat.unlock()),this.lightsTexture8.lock().set(this.lights8),this.lightsTexture8.unlock()},e.updateUniforms=function(){this._lightsTexture8Id.setValue(this.lightsTexture8),t.lightTextureFormat===t.FORMAT_FLOAT&&this._lightsTextureFloatId.setValue(this.lightsTextureFloat),this._lightsTextureInvSizeId.setValue(this._lightsTextureInvSizeData)},e.getSpotDirection=function(t,e){e._node.getWorldTransform().getY(t).mulScalar(-1),t.normalize()},e.getLightAreaSizes=function(t){var e=t._node.getWorldTransform();return e.transformVector(rl,nl),sl[0]=nl.x,sl[1]=nl.y,sl[2]=nl.z,e.transformVector(al,nl),sl[3]=nl.x,sl[4]=nl.y,sl[5]=nl.z,sl},e.addLightDataFlags=function(t,e,i,n,s,r){t[e+0]=n?255:0,t[e+1]=64*i._shape,t[e+2]=255*i._falloffMode,t[e+3]=s?255*r:0},e.addLightDataColor=function(t,e,i,n,s){var r=this.invMaxColorValue,a=n?i._linearFinalColor:i._finalColor;$h.float2Bytes(a[0]*r,t,e+0,2),$h.float2Bytes(a[1]*r,t,e+2,2),$h.float2Bytes(a[2]*r,t,e+4,2),t[e+6]=s?255:0;var o=!!(1&i.mask),h=!!(2&i.mask);t[e+7]=o&&h?127:h?255:0},e.addLightDataSpotAngles=function(t,e,i){$h.float2Bytes(.499999*i._innerConeAngleCos+.5,t,e+0,2),$h.float2Bytes(.499999*i._outerConeAngleCos+.5,t,e+2,2)},e.addLightDataShadowBias=function(t,e,i){var n=i.getRenderData(null,0),s=i._getUniformBiasValues(n);$h.float2BytesRange(s.bias,t,e,-1,20,2),$h.float2Bytes(s.normalBias,t,e+2,2)},e.addLightDataPositionRange=function(t,e,i,n){var s=nl.sub2(n,this.boundsMin).div(this.boundsDelta);$h.float2Bytes(s.x,t,e+0,4),$h.float2Bytes(s.y,t,e+4,4),$h.float2Bytes(s.z,t,e+8,4),$h.float2Bytes(i.attenuationEnd*this.invMaxAttenuation,t,e+12,4)},e.addLightDataSpotDirection=function(t,e,i){this.getSpotDirection(nl,i),$h.float2Bytes(.499999*nl.x+.5,t,e+0,4),$h.float2Bytes(.499999*nl.y+.5,t,e+4,4),$h.float2Bytes(.499999*nl.z+.5,t,e+8,4)},e.addLightDataLightProjMatrix=function(t,e,i){for(var n=i.data,s=0;s<12;s++)$h.float2BytesRange(n[s],t,e+4*s,-2,2,4);for(var r=12;r<16;r++)$h.float2MantissaExponent(n[r],t,e+4*r,4)},e.addLightDataCookies=function(t,e,i){var n="rgb"===i._cookieChannel;if(t[e+0]=Math.floor(255*i.cookieIntensity),t[e+1]=n?255:0,!n){var s=i._cookieChannel;t[e+4]="rrr"===s?255:0,t[e+5]="ggg"===s?255:0,t[e+6]="bbb"===s?255:0,t[e+7]="aaa"===s?255:0}},e.addLightAtlasViewport=function(t,e,i){$h.float2Bytes(i.x,t,e+0,2),$h.float2Bytes(i.y,t,e+2,2),$h.float2Bytes(i.z/3,t,e+4,2)},e.addLightAreaSizes=function(t,e,i){for(var n=this.getLightAreaSizes(i),s=0;s<6;s++)$h.float2MantissaExponent(n[s],t,e+4*s,4)},e.addLightData=function(e,i,n){var s=2===e._type,r=e.atlasViewportAllocated,a=this.cookiesEnabled&&!!e._cookie&&r,o=this.areaLightsEnabled&&0!==e.shape,h=this.shadowsEnabled&&e.castShadows&&r,l=e._node.getPosition(),c=null,u=null;s?h?c=e.getRenderData(null,0).shadowMatrix:a&&(c=il.evalSpotCookieMatrix(e)):(h||a)&&(u=e.atlasViewport);var d=this.lights8,f=i*this.lightsTexture8.width*4;if(this.addLightDataFlags(d,f+4*ol.FLAGS,e,s,h,e.shadowIntensity),this.addLightDataColor(d,f+4*ol.COLOR_A,e,n,a),s&&this.addLightDataSpotAngles(d,f+4*ol.SPOT_ANGLES,e),e.castShadows&&this.addLightDataShadowBias(d,f+4*ol.SHADOW_BIAS,e),a&&this.addLightDataCookies(d,f+4*ol.COOKIE_A,e),t.lightTextureFormat===t.FORMAT_FLOAT){var p=this.lightsFloat,m=i*this.lightsTextureFloat.width*4;if(p[m+4*hl.POSITION_RANGE+0]=l.x,p[m+4*hl.POSITION_RANGE+1]=l.y,p[m+4*hl.POSITION_RANGE+2]=l.z,p[m+4*hl.POSITION_RANGE+3]=e.attenuationEnd,s&&(this.getSpotDirection(nl,e),p[m+4*hl.SPOT_DIRECTION+0]=nl.x,p[m+4*hl.SPOT_DIRECTION+1]=nl.y,p[m+4*hl.SPOT_DIRECTION+2]=nl.z),c)for(var _=c.data,v=0;v<16;v++)p[m+4*hl.PROJ_MAT_0+v]=_[v];if(u&&(p[m+4*hl.ATLAS_VIEWPORT+0]=u.x,p[m+4*hl.ATLAS_VIEWPORT+1]=u.y,p[m+4*hl.ATLAS_VIEWPORT+2]=u.z/3),o){var g=this.getLightAreaSizes(e);p[m+4*hl.AREA_DATA_WIDTH+0]=g[0],p[m+4*hl.AREA_DATA_WIDTH+1]=g[1],p[m+4*hl.AREA_DATA_WIDTH+2]=g[2],p[m+4*hl.AREA_DATA_HEIGHT+0]=g[3],p[m+4*hl.AREA_DATA_HEIGHT+1]=g[4],p[m+4*hl.AREA_DATA_HEIGHT+2]=g[5]}}else this.addLightDataPositionRange(d,f+4*ol.POSITION_X,e,l),s&&this.addLightDataSpotDirection(d,f+4*ol.SPOT_DIRECTION_X,e),c&&this.addLightDataLightProjMatrix(d,f+4*ol.PROJ_MAT_00,c),u&&this.addLightAtlasViewport(d,f+4*ol.ATLAS_VIEWPORT_A,u),o&&this.addLightAreaSizes(d,f+4*ol.AREA_DATA_WIDTH_X,e)},t}();Ch=ll,ll.FORMAT_FLOAT=0,ll.FORMAT_8BIT=1,ll.lightTextureFormat=Ch.FORMAT_8BIT,ll.useTexelFetch=!1,ll.shaderDefines="";var cl={vertex_normal:Te,vertex_tangent:Ae,vertex_texCoord0:Re,vertex_texCoord1:Ie,vertex_color:Me,vertex_boneWeights:Ce,vertex_boneIndices:Ee},ul={vVertexColor:"vec4",vPositionW:"vec3",vNormalV:"vec3",vNormalW:"vec3",vTangentW:"vec3",vBinormalW:"vec3",vObjectSpaceUpW:"vec3",vUv0:"vec2",vUv1:"vec2"},dl=function(){function t(t,e){if(this.device=t,this.options=e,this.attributes={vertex_position:we},e.userAttributes)for(var i=0,n=Object.entries(e.userAttributes);i<n.length;i++){var s=n[i],r=s[0],a=s[1];this.attributes[a]=r}if(e.chunks){var o=e.chunks;for(var h in this.chunks=Object.create(_o),_o)if(o.hasOwnProperty(h)){var l=o[h];for(var c in cl)cl.hasOwnProperty(c)&&l.indexOf(c)>=0&&(this.attributes[c]=cl[c]);this.chunks[h]=l}}else this.chunks=_o;this.shaderPassInfo=Do.get(this.device).getByIndex(e.pass),this.shadowPass=this.shaderPassInfo.isShadow,this.lighting=e.lights.length>0||e.dirLightMapEnabled||e.clusteredLightingEnabled,this.reflections=!!e.reflectionSource,this.needsNormal=this.lighting||this.reflections||e.useSpecular||e.ambientSH||e.useHeights||e.enableGGXSpecular||e.clusteredLightingEnabled&&!this.shadowPass||e.useClearCoatNormals,this.needsNormal=this.needsNormal&&!this.shadowPass,this.needsSceneColor=e.useDynamicRefraction,this.needsScreenSize=e.useDynamicRefraction,this.needsTransforms=e.useDynamicRefraction,this.varyings="",this.varyingDefines="",this.vshader=null,this.frontendDecl=null,this.frontendCode=null,this.frontendFunc=null,this.lightingUv=null,this.defines=[],this.fshader=null}var e=t.prototype;return e._vsAddBaseCode=function(t,e,i){return t+=e.baseVS,1!==i.nineSlicedMode&&2!==i.nineSlicedMode||(t+=e.baseNineSlicedVS),t},e._vsAddTransformCode=function(t,e,i,n){return t+=this.chunks.transformVS},e._setMapTransform=function(t,e,i,n){var s=i+100*n;if(!t[3][s]){var r="texture_"+e+"MapTransform";t[0]+="uniform vec3 "+r+"0;\n",t[0]+="uniform vec3 "+r+"1;\n",t[1]+="varying vec2 vUV"+n+"_"+i+";\n",t[2]+=" vUV"+n+"_"+i+" = vec2(dot(vec3(uv"+n+", 1), "+r+"0), dot(vec3(uv"+n+", 1), "+r+"1));\n",t[3][s]=!0}return t},e._fsGetBaseCode=function(){var t=this.options,e=this.chunks,i=this.chunks.basePS;return 1===t.nineSlicedMode?i+=e.baseNineSlicedPS:2===t.nineSlicedMode&&(i+=e.baseNineSlicedTiledPS),i},e._fsGetStartCode=function(t,e,i,n){var s=i.startPS;return 1===n.nineSlicedMode?s+=i.startNineSlicedPS:2===n.nineSlicedMode&&(s+=i.startNineSlicedTiledPS),s},e._getLightSourceShapeString=function(t){switch(t){case 1:return"Rect";case 2:return"Disk";case 3:return"Sphere";default:return""}},e.generateVertexShader=function(t,e,i){var n=this,s=this.device,r=this.options,a=this.chunks,o="",h="";o=this._vsAddBaseCode(o,a,r),h+=" vPositionW = getWorldPosition();\n",2===this.options.pass&&(o+="varying float vDepth;\n",o+="#ifndef VIEWMATRIX\n",o+="#define VIEWMATRIX\n",o+="uniform mat4 matrix_view;\n",o+="#endif\n",o+="#ifndef CAMERAPLANES\n",o+="#define CAMERAPLANES\n",o+="uniform vec4 camera_params;\n\n",o+="#endif\n",h+=" vDepth = -(matrix_view * vec4(vPositionW,1.0)).z * camera_params.x;\n"),this.options.useInstancing&&(this.attributes.instance_line1=Qe,this.attributes.instance_line2=$e,this.attributes.instance_line3=Je,this.attributes.instance_line4=ti,o+=a.instancingVS),this.needsNormal&&(this.attributes.vertex_normal=Te,h+=" vNormalW = getNormal();\n","sphereMap"===r.reflectionSource&&s.fragmentUniformsCount<=16&&(o+=a.viewNormalVS,h+=" vNormalV = getViewNormal();\n"),r.hasTangents&&(r.useHeights||r.useNormals||r.enableGGXSpecular)?(this.attributes.vertex_tangent=Ae,o+=a.tangentBinormalVS,h+=" vTangentW = getTangent();\n",h+=" vBinormalW = getBinormal();\n"):!r.enableGGXSpecular&&s.extStandardDerivatives||(h+=" vObjectSpaceUpW = normalize(dNormalMatrix * vec3(0, 1, 0));\n"));for(var l=0;l<2;l++)t[l]&&(this.attributes["vertex_texCoord"+l]="TEXCOORD"+l,o+=a["uv"+l+"VS"],h+=" vec2 uv"+l+" = getUv"+l+"();\n"),e[l]&&(h+=" vUv"+l+" = uv"+l+";\n");var c=[o,this.varyings,h,[]];if(i.forEach((function(t){n._setMapTransform(c,t.name,t.id,t.uv)})),o=c[0],this.varyings=c[1],h=c[2],r.vertexColors&&(this.attributes.vertex_color=Me,h+=" vVertexColor = vertex_color;\n"),r.useMsdf&&r.msdfTextAttribute&&(this.attributes.vertex_outlineParameters=qe,this.attributes.vertex_shadowParameters=Ye,h+=" unpackMsdfParams();\n",o+=a.msdfVS),r.useMorphPosition||r.useMorphNormal)if(r.useMorphTextureBased){o+="#define MORPHING_TEXTURE_BASED\n",r.useMorphPosition&&(o+="#define MORPHING_TEXTURE_BASED_POSITION\n"),r.useMorphNormal&&(o+="#define MORPHING_TEXTURE_BASED_NORMAL\n"),this.attributes.morph_vertex_id=ti;var u=s.isWebGPU?"uint":"float";o+="attribute "+u+" morph_vertex_id;\n"}else o+="#define MORPHING\n",r.useMorphPosition?(this.attributes.morph_pos0=qe,this.attributes.morph_pos1=Ye,this.attributes.morph_pos2=Ke,this.attributes.morph_pos3=Ze,o+="#define MORPHING_POS03\n",o+="attribute vec3 morph_pos0;\n",o+="attribute vec3 morph_pos1;\n",o+="attribute vec3 morph_pos2;\n",o+="attribute vec3 morph_pos3;\n"):r.useMorphNormal&&(this.attributes.morph_nrm0=qe,this.attributes.morph_nrm1=Ye,this.attributes.morph_nrm2=Ke,this.attributes.morph_nrm3=Ze,o+="#define MORPHING_NRM03\n",o+="attribute vec3 morph_nrm0;\n",o+="attribute vec3 morph_nrm1;\n",o+="attribute vec3 morph_nrm2;\n",o+="attribute vec3 morph_nrm3;\n"),r.useMorphNormal?(this.attributes.morph_nrm4=Qe,this.attributes.morph_nrm5=$e,this.attributes.morph_nrm6=Je,this.attributes.morph_nrm7=ti,o+="#define MORPHING_NRM47\n",o+="attribute vec3 morph_nrm4;\n",o+="attribute vec3 morph_nrm5;\n",o+="attribute vec3 morph_nrm6;\n",o+="attribute vec3 morph_nrm7;\n"):(this.attributes.morph_pos4=Qe,this.attributes.morph_pos5=$e,this.attributes.morph_pos6=Je,this.attributes.morph_pos7=ti,o+="#define MORPHING_POS47\n",o+="attribute vec3 morph_pos4;\n",o+="attribute vec3 morph_pos5;\n",o+="attribute vec3 morph_pos6;\n",o+="attribute vec3 morph_pos7;\n");r.skin?(this.attributes.vertex_boneWeights=Ce,this.attributes.vertex_boneIndices=Ee,o+=xo.skinCode(s,a),o+="#define SKIN\n"):r.useInstancing&&(o+="#define INSTANCING\n"),r.screenSpace&&(o+="#define SCREENSPACE\n"),r.pixelSnap&&(o+="#define PIXELSNAP\n"),o=this._vsAddTransformCode(o,s,a,r),this.needsNormal&&(o+=a.normalVS),o+="\n",o+=a.startVS,o+=h,o+=a.endVS,o+="}",Object.keys(ul).forEach((function(t){o.indexOf(t)>=0&&(n.varyings+="varying "+ul[t]+" "+t+";\n",n.varyingDefines+="#define VARYING_"+t.toUpperCase()+"\n")}));var d=this.shaderPassInfo.shaderDefines;this.vshader=d+this.varyings+o},e._fsGetBeginCode=function(){for(var t=this.shaderPassInfo.shaderDefines,e=0;e<this.defines.length;e++)t+="#define "+this.defines[e]+"\n";return t},e._fsGetPickPassCode=function(){var t=this._fsGetBeginCode();return t+="uniform vec4 uColor;\n",t+=this.varyings,t+=this.varyingDefines,t+=this.frontendDecl,t+=this.frontendCode,t+=xo.begin(),t+=this.frontendFunc,t+=" gl_FragColor = uColor;\n",t+=xo.end()},e._fsGetDepthPassCode=function(){var t=this.chunks,e=this._fsGetBeginCode();return e+="varying float vDepth;\n",e+=this.varyings,e+=this.varyingDefines,e+=t.packDepthPS,e+=this.frontendDecl,e+=this.frontendCode,e+=xo.begin(),e+=this.frontendFunc,e+=" gl_FragColor = packFloat(vDepth);\n",e+=xo.end()},e._fsGetShadowPassCode=function(){var t=this.device,e=this.options,i=this.chunks,n=this.varyings,s=this.shaderPassInfo.lightType,r=this.shaderPassInfo.shadowType;0!==s&&e.clusteredLightingEnabled&&(1!==r&&2!==r&&3!==r&&6!==r||(r=0));var a=this._fsGetBeginCode();t.extStandardDerivatives&&t.isWebGL1&&(a+="uniform vec2 polygonOffset;\n"),3===r?t.textureFloatHighPrecision?a+="#define VSM_EXPONENT 15.0\n\n":a+="#define VSM_EXPONENT 5.54\n\n":2===r&&(a+="#define VSM_EXPONENT 5.54\n\n"),0!==s&&(a+="uniform vec3 view_position;\n",a+="uniform float light_radius;\n"),a+=n,a+=this.varyingDefines,a+=this.frontendDecl,a+=this.frontendCode;var o=5===r||0===r||4===r||6===r,h=1===s&&6!==r&&!e.clusteredLightingEnabled,l=o&&!t.supportsDepthShadow||h;l?a+=i.packDepthPS:1===r&&(a+="vec2 encodeFloatRG( float v ) {\n",a+=" vec2 enc = vec2(1.0, 255.0) * v;\n",a+=" enc = fract(enc);\n",a+=" enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n",a+=" return enc;\n",a+="}\n\n"),6===r&&(a+=_o.linearizeDepthPS),a+=xo.begin(),a+=this.frontendFunc;var c=1===r||2===r||3===r,u=!1;if(0===s||!c&&2===s?a+=" float depth = gl_FragCoord.z;\n":(a+=" float depth = min(distance(view_position, vPositionW) / light_radius, 0.99999);\n",u=!0),t.isWebGL1&&t.extStandardDerivatives&&(a+=" float minValue = 2.3374370500153186e-10; //(1.0 / 255.0) / (256.0 * 256.0 * 256.0);\n",a+=" depth += polygonOffset.x * max(abs(dFdx(depth)), abs(dFdy(depth))) + minValue * polygonOffset.y;\n",u=!0),l)a+=" gl_FragColor = packFloat(depth);\n";else if(c)a+=1===r?" gl_FragColor = vec4(encodeFloatRG(depth), encodeFloatRG(depth*depth));\n":i.storeEVSMPS;else{6===r?a+=" gl_FragColor.r = depth;\n":(u&&(a+=" gl_FragDepth = depth;\n"),a+=" gl_FragColor = vec4(1.0);\n")}return a+=xo.end()},e._fsGetLitPassCode=function(){var t=this.device,e=this.options,i=this.chunks,n=new Xh,s=new Xh,r=new Xh,a=new Xh;!1===e.opacityFadesSpecular&&n.append("uniform float material_alphaFade;"),e.useSpecular&&(this.defines.push("LIT_SPECULAR"),this.reflections&&this.defines.push("LIT_REFLECTIONS"),e.useClearCoat&&this.defines.push("LIT_CLEARCOAT"),e.fresnelModel>0&&this.defines.push("LIT_SPECULAR_FRESNEL"),e.conserveEnergy&&this.defines.push("LIT_CONSERVE_ENERGY"),e.useSheen&&this.defines.push("LIT_SHEEN"),e.useIridescence&&this.defines.push("LIT_IRIDESCENCE"));var o=[],h=0,l=!1,c=!1,u=!1,d=e.lights.some((function(t){return t._shape&&0!==t._shape}));e.clusteredLightingEnabled&&e.clusteredLightingAreaLightsEnabled&&(d=!0);var f="highp";7===t.areaLightLutFormat&&(n.append("#define AREA_R8_G8_B8_A8_LUTS"),f="lowp"),(d||e.clusteredLightingEnabled)&&(n.append("#define AREA_LIGHTS"),n.append("uniform "+f+" sampler2D areaLightsLutTex1;"),n.append("uniform "+f+" sampler2D areaLightsLutTex2;"));for(var p=0;p<e.lights.length;p++){var m=e.lights[p],_=m._type;if(!e.clusteredLightingEnabled||0===_){var v=d&&m._shape?m._shape:0;n.append("uniform vec3 light"+p+"_color;"),6===m._shadowType&&m.castShadows&&!e.noShadow&&(n.append("uniform float light"+p+"_shadowSearchArea;"),n.append("uniform vec4 light"+p+"_cameraParams;")),0===_?n.append("uniform vec3 light"+p+"_direction;"):(n.append("uniform vec3 light"+p+"_position;"),n.append("uniform float light"+p+"_radius;"),2===_&&(n.append("uniform vec3 light"+p+"_direction;"),n.append("uniform float light"+p+"_innerConeAngle;"),n.append("uniform float light"+p+"_outerConeAngle;"))),0!==v&&(0===_&&n.append("uniform vec3 light"+p+"_position;"),n.append("uniform vec3 light"+p+"_halfWidth;"),n.append("uniform vec3 light"+p+"_halfHeight;")),m.castShadows&&!e.noShadow&&(n.append("uniform mat4 light"+p+"_shadowMatrix;"),n.append("uniform float light"+p+"_shadowIntensity;"),0===_&&(n.append("uniform mat4 light"+p+"_shadowMatrixPalette[4];"),n.append("uniform float light"+p+"_shadowCascadeDistances[4];"),n.append("uniform float light"+p+"_shadowCascadeCount;")),n.append("uniform vec4 light"+p+"_shadowParams;"),0===_&&(l=!0),1===_?n.append("uniform samplerCube light"+p+"_shadowMap;"):m._isPcf&&t.supportsDepthShadow?n.append("uniform sampler2DShadow light"+p+"_shadowMap;"):n.append("uniform sampler2D light"+p+"_shadowMap;"),h++,o[m._shadowType]=!0,m._isVsm&&(c=!0),6===m._shadowType&&(u=!0)),m._cookie&&(m._cookie._cubemap?1===_&&(n.append("uniform samplerCube light"+p+"_cookie;"),n.append("uniform float light"+p+"_cookieIntensity;"),m.castShadows&&!e.noShadow||n.append("uniform mat4 light"+p+"_shadowMatrix;")):2===_&&(n.append("uniform sampler2D light"+p+"_cookie;"),n.append("uniform float light"+p+"_cookieIntensity;"),m.castShadows&&!e.noShadow||n.append("uniform mat4 light"+p+"_shadowMatrix;"),m._cookieTransform&&(n.append("uniform vec4 light"+p+"_cookieMatrix;"),n.append("uniform vec2 light"+p+"_cookieOffset;"))))}}var g=this.needsNormal&&(e.useNormals||e.useClearCoatNormals||e.enableGGXSpecular&&!e.useHeights);if(g&&(e.hasTangents?s.append(e.fastTbn?i.TBNfastPS:i.TBNPS):t.extStandardDerivatives&&(e.useNormals||e.useClearCoatNormals)?s.append(i.TBNderivativePS.replace(/\$UV/g,this.lightingUv)):s.append(i.TBNObjectSpacePS)),s.append(i.sphericalPS),s.append(i.decodePS),s.append(xo.gammaCode(e.gamma,i)),s.append(xo.tonemapCode(e.toneMap,i)),s.append(xo.fogCode(e.fog,i)),s.append(this.frontendCode),e.useCubeMapRotation&&n.append("#define CUBEMAP_ROTATION"),this.needsNormal&&(s.append(i.cubeMapRotatePS),s.append(e.cubeMapProjection>0?i.cubeMapProjectBoxPS:i.cubeMapProjectNonePS),s.append(e.skyboxIntensity?i.envMultiplyPS:i.envConstPS)),(this.lighting&&e.useSpecular||this.reflections)&&(e.useMetalness&&s.append(i.metalnessModulatePS),2===e.fresnelModel&&s.append(i.fresnelSchlickPS),e.useIridescence&&s.append(i.iridescenceDiffractionPS)),e.useAo)switch(s.append(i.aoDiffuseOccPS),e.occludeSpecular){case 1:s.append(e.occludeSpecularFloat?i.aoSpecOccSimplePS:i.aoSpecOccConstSimplePS);break;case 2:s.append(e.occludeSpecularFloat?i.aoSpecOccPS:i.aoSpecOccConstPS)}if("envAtlasHQ"===e.reflectionSource)s.append(e.fixSeams?i.fixCubemapSeamsStretchPS:i.fixCubemapSeamsNonePS),s.append(i.envAtlasPS),s.append(i.reflectionEnvHQPS.replace(/\$DECODE_CUBEMAP/g,Yh.decodeFunc(e.reflectionCubemapEncoding)).replace(/\$DECODE/g,Yh.decodeFunc(e.reflectionEncoding)));else if("envAtlas"===e.reflectionSource)s.append(i.envAtlasPS),s.append(i.reflectionEnvPS.replace(/\$DECODE/g,Yh.decodeFunc(e.reflectionEncoding)));else if("cubeMap"===e.reflectionSource)s.append(e.fixSeams?i.fixCubemapSeamsStretchPS:i.fixCubemapSeamsNonePS),s.append(i.reflectionCubePS.replace(/\$DECODE/g,Yh.decodeFunc(e.reflectionEncoding)));else if("sphereMap"===e.reflectionSource){var y=t.fragmentUniformsCount>16?i.reflectionSpherePS:i.reflectionSphereLowPS;s.append(y.replace(/\$DECODE/g,Yh.decodeFunc(e.reflectionEncoding)))}this.reflections&&(e.useClearCoat&&s.append(i.reflectionCCPS),e.useSheen&&s.append(i.reflectionSheenPS)),e.useRefraction&&(e.useDynamicRefraction?s.append(i.refractionDynamicPS):this.reflections&&s.append(i.refractionCubePS)),e.useSheen&&s.append(i.lightSheenPS),e.clusteredLightingEnabled&&(s.append(i.clusteredLightUtilsPS),e.clusteredLightingCookiesEnabled&&s.append(i.clusteredLightCookiesPS),e.clusteredLightingShadowsEnabled&&!e.noShadow&&(o[0]=!0,o[4]=!0,o[6]=!0)),(h>0||e.clusteredLightingEnabled)&&(l&&s.append(i.shadowCascadesPS),(o[5]||o[0])&&s.append(i.shadowStandardPS),o[4]&&!t.isWebGL1&&s.append(i.shadowStandardGL2PS),c&&(s.append(i.shadowVSM_commonPS),o[1]&&s.append(i.shadowVSM8PS),o[2]&&s.append(t.extTextureHalfFloatLinear?i.shadowEVSMPS.replace(/\$/g,"16"):i.shadowEVSMnPS.replace(/\$/g,"16")),o[3]&&s.append(t.extTextureFloatLinear?i.shadowEVSMPS.replace(/\$/g,"32"):i.shadowEVSMnPS.replace(/\$/g,"32"))),u&&(s.append(i.linearizeDepthPS),s.append(i.shadowPCSSPS)),t.isWebGL2||t.isWebGPU||t.extStandardDerivatives||s.append(i.biasConstPS)),e.enableGGXSpecular&&s.append("uniform float material_anisotropy;"),this.lighting&&(s.append(i.lightDiffuseLambertPS),(d||e.clusteredLightingAreaLightsEnabled)&&s.append(i.ltcPS));var x=!1;e.useSpecular&&(this.lighting&&s.append(0===e.shadingModel?i.lightSpecularPhongPS:e.enableGGXSpecular?i.lightSpecularAnisoGGXPS:i.lightSpecularBlinnPS),e.fresnelModel||this.reflections||e.diffuseMapEnabled||(n.append("uniform vec3 material_ambient;"),n.append("#define LIT_OLD_AMBIENT"),x=!0)),s.append(i.combinePS),e.lightMapEnabled&&s.append(e.useSpecular&&e.dirLightMapEnabled?i.lightmapDirAddPS:i.lightmapAddPS);var S=!e.lightMapEnabled||e.lightMapWithoutAmbient;S&&("ambientSH"===e.ambientSource?s.append(i.ambientSHPS):"envAtlas"===e.ambientSource?("envAtlas"!==e.reflectionSource&&"envAtlasHQ"!==e.reflectionSource&&s.append(i.envAtlasPS),s.append(i.ambientEnvPS.replace(/\$DECODE/g,Yh.decodeFunc(e.ambientEncoding)))):s.append(i.ambientConstantPS)),e.useAmbientTint&&!x&&n.append("uniform vec3 material_ambient;"),e.useMsdf&&(e.msdfTextAttribute||n.append("#define UNIFORM_TEXT_PARAMETERS"),s.append(i.msdfPS)),this.needsNormal&&(s.append(i.viewDirPS),e.useSpecular&&s.append(e.enableGGXSpecular?i.reflDirAnisoPS:i.reflDirPS));var b,w=!1,T=!1,A=!1,C=!1,E=!1;if(e.clusteredLightingEnabled&&this.lighting&&(C=!0,w=!0,T=!0,E=!0,s.append(i.floatUnpackingPS),e.lightMaskDynamic&&n.append("#define CLUSTER_MESH_DYNAMIC_LIGHTS"),e.clusteredLightingCookiesEnabled&&n.append("#define CLUSTER_COOKIES"),e.clusteredLightingShadowsEnabled&&!e.noShadow&&(n.append("#define CLUSTER_SHADOWS"),n.append("#define CLUSTER_SHADOW_TYPE_"+La[e.clusteredLightingShadowType])),e.clusteredLightingAreaLightsEnabled&&n.append("#define CLUSTER_AREALIGHTS"),n.append(ll.shaderDefines),e.clusteredLightingShadowsEnabled&&!e.noShadow&&s.append(i.clusteredLightShadowsPS),s.append(i.clusteredLightPS)),e.twoSidedLighting&&n.append("uniform float twoSidedLightingNegScaleFactor;"),a.append(this._fsGetStartCode(a,t,i,e)),this.needsNormal&&(e.twoSidedLighting?a.append(" dVertexNormalW = normalize(gl_FrontFacing ? vNormalW * twoSidedLightingNegScaleFactor : -vNormalW * twoSidedLightingNegScaleFactor);"):a.append(" dVertexNormalW = normalize(vNormalW);"),(e.useHeights||e.useNormals)&&e.hasTangents&&(e.twoSidedLighting?(a.append(" dTangentW = gl_FrontFacing ? vTangentW * twoSidedLightingNegScaleFactor : -vTangentW * twoSidedLightingNegScaleFactor;"),a.append(" dBinormalW = gl_FrontFacing ? vBinormalW * twoSidedLightingNegScaleFactor : -vBinormalW * twoSidedLightingNegScaleFactor;")):(a.append(" dTangentW = vTangentW;"),a.append(" dBinormalW = vBinormalW;"))),a.append(" getViewDir();"),g&&a.append(" getTBN(dTangentW, dBinormalW, dVertexNormalW);")),a.append(this.frontendFunc),this.needsNormal&&(e.useSpecular&&r.append(" getReflDir(litArgs_worldNormal, dViewDirW, litArgs_gloss, dTBN);"),e.useClearCoat&&r.append(" ccReflDirW = normalize(-reflect(dViewDirW, litArgs_clearcoat_worldNormal));")),(this.lighting&&e.useSpecular||this.reflections)&&(e.useMetalness&&(r.append(" float f0 = 1.0 / litArgs_ior; f0 = (f0 - 1.0) / (f0 + 1.0); f0 *= f0;"),r.append(" litArgs_specularity = getSpecularModulate(litArgs_specularity, litArgs_albedo, litArgs_metalness, f0);"),r.append(" litArgs_albedo = getAlbedoModulate(litArgs_albedo, litArgs_metalness);")),e.useIridescence&&r.append(" vec3 iridescenceFresnel = getIridescence(saturate(dot(dViewDirW, litArgs_worldNormal)), litArgs_specularity, litArgs_iridescence_thickness);")),S&&(r.append(" addAmbient(litArgs_worldNormal);"),e.conserveEnergy&&e.useSpecular&&r.append(" dDiffuseLight = dDiffuseLight * (1.0 - litArgs_specularity);"),e.separateAmbient&&r.append("\n vec3 dAmbientLight = dDiffuseLight;\n dDiffuseLight = vec3(0);\n ")),e.useAmbientTint&&!x&&r.append(" dDiffuseLight *= material_ambient;"),e.useAo&&!e.occludeDirect&&r.append(" occludeDiffuse(litArgs_ao);"),e.lightMapEnabled&&r.append(" addLightMap(\n litArgs_lightmap, \n litArgs_lightmapDir, \n litArgs_worldNormal, \n dViewDirW, \n dReflDirW, \n litArgs_gloss, \n litArgs_specularity, \n dVertexNormalW,\n dTBN\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel,\n litArgs_iridescence_intensity\n #endif\n );"),this.lighting||this.reflections){this.reflections&&(e.useClearCoat&&(r.append(" addReflectionCC(ccReflDirW, litArgs_clearcoat_gloss);"),e.fresnelModel>0?(r.append(" ccFresnel = getFresnelCC(dot(dViewDirW, litArgs_clearcoat_worldNormal));"),r.append(" ccReflection.rgb *= ccFresnel;")):r.append(" ccFresnel = 0.0;")),e.useSpecularityFactor&&r.append(" ccReflection.rgb *= litArgs_specularityFactor;"),e.useSheen&&r.append(" addReflectionSheen(litArgs_worldNormal, dViewDirW, litArgs_sheen_gloss);"),r.append(" addReflection(dReflDirW, litArgs_gloss);"),e.fresnelModel>0?r.append(" dReflection.rgb *= \n getFresnel(\n dot(dViewDirW, litArgs_worldNormal), \n litArgs_gloss, \n litArgs_specularity\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel,\n litArgs_iridescence_intensity\n #endif\n );"):r.append(" dReflection.rgb *= litArgs_specularity;"),e.useSpecularityFactor&&r.append(" dReflection.rgb *= litArgs_specularityFactor;")),d&&(r.append(" dSpecularLight *= litArgs_specularity;"),e.useSpecular&&r.append(" calcLTCLightValues(litArgs_gloss, litArgs_worldNormal, dViewDirW, litArgs_specularity, litArgs_clearcoat_gloss, litArgs_clearcoat_worldNormal, litArgs_clearcoat_specularity);"));for(var M=0;M<e.lights.length;M++){var P=e.lights[M],R=P._type;if(!e.clusteredLightingEnabled||0===R){b=!1;var I=d&&P._shape?P.shape:0,L=d&&P._shape?this._getLightSourceShapeString(I):"";if(0!==I&&r.append(" calc"+L+"LightValues(light"+M+"_position, light"+M+"_halfWidth, light"+M+"_halfHeight);"),0===R?(r.append(" dLightDirNormW = light"+M+"_direction;"),r.append(" dAtten = 1.0;")):(P._cookie&&(2!==R||P._cookie._cubemap?1===R&&P._cookie._cubemap&&(E=!0,b=!0):(E=!0,b=!0)),r.append(" getLightDirPoint(light"+M+"_position);"),w=!0,b&&(2===R?r.append(" dAtten3 = getCookie2D"+(P._cookieFalloff?"":"Clip")+(P._cookieTransform?"Xform":"")+"(light"+M+"_cookie, light"+M+"_shadowMatrix, light"+M+"_cookieIntensity"+(P._cookieTransform?", light"+M+"_cookieMatrix, light"+M+"_cookieOffset":"")+")."+P._cookieChannel+";"):r.append(" dAtten3 = getCookieCube(light"+M+"_cookie, light"+M+"_shadowMatrix, light"+M+"_cookieIntensity)."+P._cookieChannel+";")),0===I?0===P._falloffMode?(r.append(" dAtten = getFalloffLinear(light"+M+"_radius, dLightDirW);"),T=!0):(r.append(" dAtten = getFalloffInvSquared(light"+M+"_radius, dLightDirW);"),A=!0):(r.append(" dAtten = getFalloffWindow(light"+M+"_radius, dLightDirW);"),A=!0),r.append(" if (dAtten > 0.00001) {"),2===R&&(b&&!P._cookieFalloff||(r.append(" dAtten *= getSpotEffect(light"+M+"_direction, light"+M+"_innerConeAngle, light"+M+"_outerConeAngle, dLightDirNormW);"),C=!0))),0!==I?0===R?r.append(" dAttenD = getLightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirW, dLightDirNormW);"):r.append(" dAttenD = get"+L+"LightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirW, dLightDirNormW) * 16.0;"):r.append(" dAtten *= getLightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirW, dLightDirNormW);"),P.castShadows&&!e.noShadow){var D=6===P._shadowType,O=1===P._shadowType||2===P._shadowType||3===P._shadowType,k=5===P._shadowType||0===P._shadowType||4===P._shadowType,F=null,B=void 0;switch(P._shadowType){case 1:F="VSM8",B="0.0";break;case 2:F="VSM16",B="5.54";break;case 3:F="VSM32",B=t.textureFloatHighPrecision?"15.0":"5.54";break;case 5:F="PCF1x1";break;case 4:F="PCF5x5";break;case 6:F="PCSS";break;default:F="PCF3x3"}if(null!==F){P._normalOffsetBias&&!P._isVsm&&s.append("#define SHADOW_SAMPLE_NORMAL_OFFSET"),0===R&&s.append("#define SHADOW_SAMPLE_ORTHO"),((k||D)&&t.isWebGL2||t.isWebGPU||t.extStandardDerivatives)&&s.append("#define SHADOW_SAMPLE_SOURCE_ZBUFFER"),1===R&&s.append("#define SHADOW_SAMPLE_POINT");var U=i.shadowSampleCoordPS;s.append(U.replace("$LIGHT",M)),s.append("#undef SHADOW_SAMPLE_NORMAL_OFFSET"),s.append("#undef SHADOW_SAMPLE_ORTHO"),s.append("#undef SHADOW_SAMPLE_SOURCE_ZBUFFER"),s.append("#undef SHADOW_SAMPLE_POINT");var N="light"+M+"_shadowMatrix";0===R&&P.numCascades>1&&(r.append(" getShadowCascadeMatrix(light"+M+"_shadowMatrixPalette, light"+M+"_shadowCascadeDistances, light"+M+"_shadowCascadeCount);"),N="cascadeShadowMat"),r.append(" dShadowCoord = getShadowSampleCoord"+M+"("+N+", light"+M+"_shadowParams, vPositionW, dLightPosW, dLightDirW, dLightDirNormW, dVertexNormalW);"),0===R&&r.append(" fadeShadow(light"+M+"_shadowCascadeDistances);");var z="SHADOWMAP_PASS(light"+M+"_shadowMap), dShadowCoord, light"+M+"_shadowParams";if(O)z=z+", "+B+", dLightDirW";else if(D){var V="vec2(light"+M+"_shadowSearchArea)";0!==I&&(V="vec2(length(light"+M+"_halfWidth), length(light"+M+"_halfHeight)) * light"+M+"_shadowSearchArea"),z=z+", light"+M+"_cameraParams, "+V+", dLightDirW"}1===R?(F="Point"+F,D||(z+=", dLightDirW")):2===R&&(F="Spot"+F),r.append(" float shadow"+M+" = getShadow"+F+"("+z+");"),r.append(" dAtten *= mix(1.0, shadow"+M+", light"+M+"_shadowIntensity);")}}if(0!==I?e.conserveEnergy&&e.useSpecular?r.append(" dDiffuseLight += ((dAttenD * dAtten) * light"+M+"_color"+(b?" * dAtten3":"")+") * (1.0 - dLTCSpecFres);"):r.append(" dDiffuseLight += (dAttenD * dAtten) * light"+M+"_color"+(b?" * dAtten3":"")+";"):d&&e.conserveEnergy&&e.useSpecular?r.append(" dDiffuseLight += (dAtten * light"+M+"_color"+(b?" * dAtten3":"")+") * (1.0 - litArgs_specularity);"):r.append(" dDiffuseLight += dAtten * light"+M+"_color"+(b?" * dAtten3":"")+";"),e.useSpecular&&r.append(" dHalfDirW = normalize(-dLightDirNormW + dViewDirW);"),P.affectSpecularity)if(0!==I)e.useClearCoat&&r.append(" ccSpecularLight += ccLTCSpecFres * get"+L+"LightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * light"+M+"_color"+(b?" * dAtten3":"")+";"),e.useSpecular&&r.append(" dSpecularLight += dLTCSpecFres * get"+L+"LightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * light"+M+"_color"+(b?" * dAtten3":"")+";");else{var G=!1;0===R&&e.fresnelModel>0&&(G=!0),e.useClearCoat&&r.append(" ccSpecularLight += getLightSpecular(dHalfDirW, ccReflDirW, litArgs_clearcoat_worldNormal, dViewDirW, dLightDirNormW, litArgs_clearcoat_gloss, dTBN) * dAtten * light"+M+"_color"+(b?" * dAtten3":"")+(G?" * getFresnelCC(dot(dViewDirW, dHalfDirW));":";")),e.useSheen&&r.append(" sSpecularLight += getLightSpecularSheen(dHalfDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_sheen_gloss) * dAtten * light"+M+"_color"+(b?" * dAtten3;":";")),e.useSpecular&&r.append(" dSpecularLight += getLightSpecular(dHalfDirW, dReflDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_gloss, dTBN) * dAtten * light"+M+"_color"+(b?" * dAtten3":"")+(G?" \n * getFresnel(\n dot(dViewDirW, dHalfDirW), \n litArgs_gloss, \n litArgs_specularity\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel, \n litArgs_iridescence_intensity\n #endif\n );":"* litArgs_specularity;"))}0!==R&&r.append(" }")}}e.clusteredLightingEnabled&&this.lighting&&(T=!0,A=!0,w=!0,r.append(" addClusteredLights(\n litArgs_worldNormal, \n dViewDirW, \n dReflDirW,\n #if defined(LIT_CLEARCOAT)\n ccReflDirW,\n #endif\n litArgs_gloss, \n litArgs_specularity, \n dVertexNormalW, \n dTBN, \n #if defined(LIT_IRIDESCENCE)\n iridescenceFresnel,\n #endif\n litArgs_clearcoat_worldNormal, \n litArgs_clearcoat_gloss,\n litArgs_sheen_gloss,\n litArgs_iridescence_intensity\n );")),d&&(e.useClearCoat&&r.append(" litArgs_clearcoat_specularity = 1.0;"),e.useSpecular&&r.append(" litArgs_specularity = vec3(1);")),e.useRefraction&&r.append(" addRefraction(\n litArgs_worldNormal, \n dViewDirW, \n litArgs_thickness, \n litArgs_gloss, \n litArgs_specularity, \n litArgs_albedo, \n litArgs_transmission,\n litArgs_ior\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel, \n litArgs_iridescence_intensity\n #endif\n );")}e.useAo&&(e.occludeDirect&&r.append(" occludeDiffuse(litArgs_ao);"),1!==e.occludeSpecular&&2!==e.occludeSpecular||r.append(" occludeSpecular(litArgs_gloss, litArgs_ao, litArgs_worldNormal, dViewDirW);")),e.useSpecularityFactor&&r.append(" dSpecularLight *= litArgs_specularityFactor;"),!1===e.opacityFadesSpecular&&(2!==e.blendType&&4!==e.blendType||(r.append("float specLum = dot((dSpecularLight + dReflection.rgb * dReflection.a), vec3( 0.2126, 0.7152, 0.0722 ));"),r.append("#ifdef LIT_CLEARCOAT\n specLum += dot(ccSpecularLight * litArgs_clearcoat_specularity + ccReflection.rgb * litArgs_clearcoat_specularity, vec3( 0.2126, 0.7152, 0.0722 ));\n#endif"),r.append("litArgs_opacity = clamp(litArgs_opacity + gammaCorrectInput(specLum), 0.0, 1.0);")),r.append("litArgs_opacity *= material_alphaFade;")),r.append(i.endPS),2===e.blendType||6===e.blendType||e.alphaToCoverage?r.append(i.outputAlphaPS):4===e.blendType?r.append(i.outputAlphaPremulPS):r.append(i.outputAlphaOpaquePS),e.useMsdf&&r.append(" gl_FragColor = applyMsdf(gl_FragColor);"),r.append(i.outputPS),r.append(i.debugOutputPS),w&&s.prepend(i.lightDirPointPS),T&&s.prepend(i.falloffLinearPS),A&&s.prepend(i.falloffInvSquaredPS),C&&s.prepend(i.spotPS),E&&!e.clusteredLightingEnabled&&s.prepend(i.cookiePS);var H="",W="void evaluateBackend() {\n"+r.code+"\n}";s.append(W),a.append(i.debugProcessFrontendPS),a.append(" evaluateBackend();"),a.append(xo.end());var X=n.code+s.code+a.code;return X.includes("dTBN")&&(H+="mat3 dTBN;\n"),X.includes("dVertexNormalW")&&(H+="vec3 dVertexNormalW;\n"),X.includes("dTangentW")&&(H+="vec3 dTangentW;\n"),X.includes("dBinormalW")&&(H+="vec3 dBinormalW;\n"),X.includes("dViewDirW")&&(H+="vec3 dViewDirW;\n"),X.includes("dReflDirW")&&(H+="vec3 dReflDirW;\n"),X.includes("dHalfDirW")&&(H+="vec3 dHalfDirW;\n"),X.includes("ccReflDirW")&&(H+="vec3 ccReflDirW;\n"),X.includes("dLightDirNormW")&&(H+="vec3 dLightDirNormW;\n"),X.includes("dLightDirW")&&(H+="vec3 dLightDirW;\n"),X.includes("dLightPosW")&&(H+="vec3 dLightPosW;\n"),X.includes("dShadowCoord")&&(H+="vec3 dShadowCoord;\n"),X.includes("dReflection")&&(H+="vec4 dReflection;\n"),X.includes("dDiffuseLight")&&(H+="vec3 dDiffuseLight;\n"),X.includes("dSpecularLight")&&(H+="vec3 dSpecularLight;\n"),X.includes("dAtten")&&(H+="float dAtten;\n"),X.includes("dAttenD")&&(H+="float dAttenD;\n"),X.includes("dAtten3")&&(H+="vec3 dAtten3;\n"),X.includes("dMsdf")&&(H+="vec4 dMsdf;\n"),X.includes("ccFresnel")&&(H+="float ccFresnel;\n"),X.includes("ccReflection")&&(H+="vec3 ccReflection;\n"),X.includes("ccSpecularLight")&&(H+="vec3 ccSpecularLight;\n"),X.includes("ccSpecularityNoFres")&&(H+="float ccSpecularityNoFres;\n"),X.includes("sSpecularLight")&&(H+="vec3 sSpecularLight;\n"),X.includes("sReflection")&&(H+="vec3 sReflection;\n"),this._fsGetBeginCode()+this.varyings+this.varyingDefines+this._fsGetBaseCode()+H+this.frontendDecl+X},e.generateFragmentShader=function(t,e,i,n){var s,r=this.options;this.frontendDecl=t,this.frontendCode=e,this.frontendFunc=i,this.lightingUv=n,3===r.pass?this.fshader=this._fsGetPickPassCode():2===r.pass?this.fshader=this._fsGetDepthPassCode():this.shadowPass?this.fshader=this._fsGetShadowPassCode():r.customFragmentShader?this.fshader=this._fsGetBeginCode()+r.customFragmentShader:this.fshader=this._fsGetLitPassCode(),null==(s=this.handleCompatibility)||s.call(this)},e.getDefinition=function(){var t=ir.createDefinition(this.device,{name:"LitShader",attributes:this.attributes,vertexCode:this.vshader,fragmentCode:this.fshader});return this.shaderPassInfo.isForward&&(t.tag=1),t},t}(),fl={generateKey:function(t){return"lit"+Object.keys(t).sort().map((function(e){return"chunks"===e?fl.generateChunksKey(t):"lights"===e?fl.generateLightsKey(t):e+t[e]})).join("\n")},generateLightsKey:function(t){return"lights:"+t.lights.map((function(e){return t.clusteredLightingEnabled&&0!==e._type?"":e.key+","})).join("")},generateChunksKey:function(t){var e;return"chunks:\n"+Object.keys(null!=(e=t.chunks)?e:{}).sort().map((function(e){return e+t.chunks[e]})).join("")}},pl=[0,1,2,3,4,5,6,7],ml=function(t){function e(){return t.apply(this,arguments)||this}S(e,t);var i=e.prototype;return i.generateKey=function(t){return"lit"+pl.map((function(e,i){return t.usedUvs[i]?"1":"0"})).join("")+t.shaderChunk+fl.generateKey(t.litOptions)},i.createShaderDefinition=function(t,e){var i=new dl(t,e.litOptions),n=new Xh,s=new Xh,r=new Xh;n.append("uniform float textureBias;"),n.append(i.chunks.litShaderArgsPS),s.append(e.shaderChunk),r.code="evaluateFrontend();",r.code="\n"+r.code.split("\n").map((function(t){return" "+t})).join("\n")+"\n\n";var a=e.usedUvs||[!0];return i.generateVertexShader(a,a,[]),i.generateFragmentShader(n.code,s.code,r.code,"vUv0"),i.getDefinition()},e}(xo),_l=new ml,vl=new function(){this.usedUvs=void 0,this.shaderChunk=void 0,this.litOptions=new Hh},gl=function(t){function e(){for(var e,i=arguments.length,n=new Array(i),s=0;s<i;s++)n[s]=arguments[s];return(e=t.call.apply(t,[this].concat(n))||this).usedUvs=[!0],e.shaderChunk="void evaluateFrontend() {}\n",e.chunks=null,e.useLighting=!0,e.useFog=!0,e.useGammaTonemap=!0,e.useSkybox=!0,e.shadingModel=1,e.ambientSH=null,e.pixelSnap=!1,e.nineSlicedMode=null,e.fastTbn=!1,e.twoSidedLighting=!1,e.occludeDirect=!1,e.occludeSpecular=1,e.occludeSpecularIntensity=1,e.opacityFadesSpecular=!0,e.conserveEnergy=!0,e.ggxSpecular=!1,e.fresnelModel=2,e.dynamicRefraction=!1,e.hasAo=!1,e.hasSpecular=!1,e.hasSpecularityFactor=!1,e.hasLighting=!1,e.hasHeights=!1,e.hasNormals=!1,e.hasSheen=!1,e.hasRefraction=!1,e.hasIrridescence=!1,e.hasMetalness=!1,e.hasClearCoat=!1,e.hasClearCoatNormals=!1,e}return S(e,t),e.prototype.getShaderVariant=function(t,e,i,n,s,r,a,o,h){vl.usedUvs=this.usedUvs.slice(),vl.shaderChunk=this.shaderChunk,Wh.update(vl.litOptions,this,e,i,s,r);var l=new fo(a,o,h),c=go(t);return c.register("lit",_l),c.getProgram("lit",vl,l,this.userId)},e}(zo),yl=new wt,xl=new wt,Sl=new wt,bl=new Ht,wl=1e-6,Tl=function(){this.light=null,this.min=new wt,this.max=new wt},Al=function(){function t(t){this.clusterTexture=void 0,this.device=t,this.name="Untitled",this.reportCount=0,this.boundsMin=new wt,this.boundsMax=new wt,this.boundsDelta=new wt,this._cells=new wt(1,1,1),this._cellsLimit=new wt,this.cells=this._cells,this.maxCellLightCount=4,this._maxAttenuation=0,this._maxColorValue=0,this._usedLights=[],this._usedLights.push(new Tl),this.lightsBuffer=new ll(t),this.registerUniforms(t)}var e=t.prototype;return e.destroy=function(){this.lightsBuffer.destroy(),this.releaseClusterTexture()},e.releaseClusterTexture=function(){this.clusterTexture&&(this.clusterTexture.destroy(),this.clusterTexture=null)},e.registerUniforms=function(t){this._clusterSkipId=t.scope.resolve("clusterSkip"),this._clusterMaxCellsId=t.scope.resolve("clusterMaxCells"),this._clusterWorldTextureId=t.scope.resolve("clusterWorldTexture"),this._clusterTextureSizeId=t.scope.resolve("clusterTextureSize"),this._clusterTextureSizeData=new Float32Array(3),this._clusterBoundsMinId=t.scope.resolve("clusterBoundsMin"),this._clusterBoundsMinData=new Float32Array(3),this._clusterBoundsDeltaId=t.scope.resolve("clusterBoundsDelta"),this._clusterBoundsDeltaData=new Float32Array(3),this._clusterCellsCountByBoundsSizeId=t.scope.resolve("clusterCellsCountByBoundsSize"),this._clusterCellsCountByBoundsSizeData=new Float32Array(3),this._clusterCellsDotId=t.scope.resolve("clusterCellsDot"),this._clusterCellsDotData=new Float32Array(3),this._clusterCellsMaxId=t.scope.resolve("clusterCellsMax"),this._clusterCellsMaxData=new Float32Array(3),this._clusterCompressionLimit0Id=t.scope.resolve("clusterCompressionLimit0"),this._clusterCompressionLimit0Data=new Float32Array(2)},e.updateParams=function(t){t&&(this.cells=t.cells,this.maxCellLightCount=t.maxLightsPerCell,this.lightsBuffer.cookiesEnabled=t.cookiesEnabled,this.lightsBuffer.shadowsEnabled=t.shadowsEnabled,this.lightsBuffer.areaLightsEnabled=t.areaLightsEnabled)},e.updateCells=function(){if(this._cellsDirty){this._cellsDirty=!1;var t=this._cells.x,e=this._cells.y,i=this._cells.z,n=t*e*i,s=this.maxCellLightCount*n,r=Math.ceil(Math.sqrt(s));r=_t.roundUp(r,this.maxCellLightCount);var a=Math.ceil(s/r);this._clusterCellsMaxData[0]=t,this._clusterCellsMaxData[1]=e,this._clusterCellsMaxData[2]=i,this._clusterCellsDotData[0]=this.maxCellLightCount,this._clusterCellsDotData[1]=t*i*this.maxCellLightCount,this._clusterCellsDotData[2]=t*this.maxCellLightCount,this.clusters=new Uint8ClampedArray(s),this.counts=new Int32Array(n),this._clusterTextureSizeData[0]=r,this._clusterTextureSizeData[1]=1/r,this._clusterTextureSizeData[2]=1/a,this.releaseClusterTexture(),this.clusterTexture=ll.createTexture(this.device,r,a,1,"ClusterTexture")}},e.uploadTextures=function(){this.clusterTexture.lock().set(this.clusters),this.clusterTexture.unlock(),this.lightsBuffer.uploadTextures()},e.updateUniforms=function(){this._clusterSkipId.setValue(this._usedLights.length>1?0:1),this.lightsBuffer.updateUniforms(),this._clusterWorldTextureId.setValue(this.clusterTexture),this._clusterMaxCellsId.setValue(this.maxCellLightCount);var t=this.boundsDelta;this._clusterCellsCountByBoundsSizeData[0]=this._cells.x/t.x,this._clusterCellsCountByBoundsSizeData[1]=this._cells.y/t.y,this._clusterCellsCountByBoundsSizeData[2]=this._cells.z/t.z,this._clusterCellsCountByBoundsSizeId.setValue(this._clusterCellsCountByBoundsSizeData),this._clusterBoundsMinData[0]=this.boundsMin.x,this._clusterBoundsMinData[1]=this.boundsMin.y,this._clusterBoundsMinData[2]=this.boundsMin.z,this._clusterBoundsDeltaData[0]=t.x,this._clusterBoundsDeltaData[1]=t.y,this._clusterBoundsDeltaData[2]=t.z,this._clusterCompressionLimit0Data[0]=this._maxAttenuation,this._clusterCompressionLimit0Data[1]=this._maxColorValue,this._clusterTextureSizeId.setValue(this._clusterTextureSizeData),this._clusterBoundsMinId.setValue(this._clusterBoundsMinData),this._clusterBoundsDeltaId.setValue(this._clusterBoundsDeltaData),this._clusterCellsDotId.setValue(this._clusterCellsDotData),this._clusterCellsMaxId.setValue(this._clusterCellsMaxData),this._clusterCompressionLimit0Id.setValue(this._clusterCompressionLimit0Data)},e.evalLightCellMinMax=function(t,e,i){e.copy(t.min),e.sub(this.boundsMin),e.div(this.boundsDelta),e.mul2(e,this.cells),e.floor(),i.copy(t.max),i.sub(this.boundsMin),i.div(this.boundsDelta),i.mul2(i,this.cells),i.ceil(),e.max(wt.ZERO),i.min(this._cellsLimit)},e.collectLights=function(t){var e=this.lightsBuffer.maxLights,i=this._usedLights,n=1;t.forEach((function(t){var s,r=!!(3&t.mask),a=2===t.type&&0===t._outerConeAngle;t.enabled&&0!==t.type&&t.visibleThisFrame&&t.intensity>0&&r&&!a&&(n<e&&(n<i.length?s=i[n]:(s=new Tl,i.push(s)),s.light=t,t.getBoundingBox(bl),s.min.copy(bl.getMin()),s.max.copy(bl.getMax()),n++))})),i.length=n},e.evaluateBounds=function(){var t=this._usedLights,e=this.boundsMin,i=this.boundsMax;if(t.length>1){e.copy(t[1].min),i.copy(t[1].max);for(var n=2;n<t.length;n++)e.min(t[n].min),i.max(t[n].max)}else e.set(0,0,0),i.set(1,1,1);this.boundsDelta.sub2(i,e),this.lightsBuffer.setBounds(e,this.boundsDelta)},e.evaluateCompressionLimits=function(t){for(var e=0,i=0,n=this._usedLights,s=1;s<n.length;s++){var r=n[s].light;e=Math.max(r.attenuationEnd,e);var a=t?r._linearFinalColor:r._finalColor;i=Math.max(a[0],i),i=Math.max(a[1],i),i=Math.max(a[2],i)}this._maxAttenuation=e+wl,this._maxColorValue=i+wl,this.lightsBuffer.setCompressionRanges(this._maxAttenuation,this._maxColorValue)},e.updateClusters=function(t){this.counts.fill(0),this.clusters.fill(0);for(var e=this._cells.x,i=this._cells.z,n=this.counts,s=this._maxCellLightCount,r=this.clusters,a=this.maxCellLightCount,o=this._usedLights,h=1;h<o.length;h++){var l=o[h],c=l.light;this.lightsBuffer.addLightData(c,h,t),this.evalLightCellMinMax(l,xl,Sl);for(var u=xl.x,d=Sl.x,f=xl.y,p=Sl.y,m=xl.z,_=Sl.z,v=u;v<=d;v++)for(var g=m;g<=_;g++)for(var y=f;y<=p;y++){var x=v+e*(g+y*i),S=n[x];S<s&&(r[a*x+S]=h,n[x]=S+1)}}},e.update=function(t,e,i){this.updateParams(i),this.updateCells(),this.collectLights(t),this.evaluateBounds(),this.evaluateCompressionLimits(e),this.updateClusters(e),this.uploadTextures()},e.activate=function(){this.updateUniforms()},y(t,[{key:"maxCellLightCount",get:function(){return this._maxCellLightCount},set:function(t){t!==this._maxCellLightCount&&(this._maxCellLightCount=t,this._cellsDirty=!0)}},{key:"cells",get:function(){return this._cells},set:function(t){yl.copy(t).floor(),this._cells.equals(yl)||(this._cells.copy(yl),this._cellsLimit.copy(yl).sub(wt.ONE),this._cellsDirty=!0)}}]),t}(),Cl=function(){function t(t,e){this.texture=t,this.cached=!1,this.renderTargets=e}return t.prototype.destroy=function(){this.texture&&(this.texture.destroy(),this.texture=null);for(var t=this.renderTargets,e=0;e<t.length;e++)t[e].destroy();this.renderTargets.length=0},t.getShadowFormat=function(t,e){return 3===e?le:2===e?oe:4===e?ue:5!==e&&0!==e||!t.supportsDepthShadow?6!==e||t.isWebGL1?7:ce:ue},t.getShadowFiltering=function(t,e){return 5!==e&&0!==e&&6!==e||t.supportsDepthShadow?3===e?t.extTextureFloatLinear?1:0:2===e?t.extTextureHalfFloatLinear?1:0:1:0},t.create=function(t,e){return 1===e._type?this.createCubemap(t,e._shadowResolution,e._shadowType):this.create2dMap(t,e._shadowResolution,e._shadowType)},t.createAtlas=function(t,e,i){for(var n=this.create2dMap(t,e,i),s=n.renderTargets,r=s[0],a=0;a<5;a++)s.push(r);return n},t.create2dMap=function(e,i,n){var s=this.getShadowFormat(e,n),r=this.getShadowFiltering(e,n),a=new Ls(e,{format:s,width:i,height:i,mipmaps:!1,minFilter:r,magFilter:r,addressU:1,addressV:1,name:"ShadowMap2D"}),o=null;return 4===n||(5===n||0===n)&&e.supportsDepthShadow?(a.compareOnRead=!0,a.compareFunc=1,o=new rn({depthBuffer:a})):o=new rn({colorBuffer:a,depth:!0}),e.isWebGPU&&(o.flipY=!0),new t(a,[o])},t.createCubemap=function(e,i,n){for(var s=6!==n||e.isWebGL1?7:ce,r=new Ls(e,{format:s,width:i,height:i,cubemap:!0,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1,name:"ShadowMapCube"}),a=[],o=0;o<6;o++){var h=new rn({colorBuffer:r,face:o,depth:!0});a.push(h)}return new t(r,a)},t}(),El=[],Ml=[],Pl=new Pt,Rl=new Pt,Il=function(t){this.size=Math.floor(1024*t.w),this.used=!1,this.lightId=-1,this.rect=t},Ll=function(){function t(t){this.device=t,this.version=1,this.shadowAtlasResolution=2048,this.shadowAtlas=null,this.shadowEdgePixels=3,this.cookieAtlasResolution=4,this.cookieAtlas=new Ls(this.device,{name:"CookieAtlas",width:this.cookieAtlasResolution,height:this.cookieAtlasResolution,format:7,cubemap:!1,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1}),this.cookieRenderTarget=new rn({colorBuffer:this.cookieAtlas,depth:!1,flipY:!0}),this.slots=[],this.atlasSplit=[],this.cubeSlotsOffsets=[new Et(0,0),new Et(0,1),new Et(1,0),new Et(1,1),new Et(2,0),new Et(2,1)],this.scissorVec=new Pt,this.allocateShadowAtlas(1),this.allocateCookieAtlas(1),this.allocateUniforms()}var e=t.prototype;return e.destroy=function(){this.destroyShadowAtlas(),this.destroyCookieAtlas()},e.destroyShadowAtlas=function(){var t;null==(t=this.shadowAtlas)||t.destroy(),this.shadowAtlas=null},e.destroyCookieAtlas=function(){var t,e;null==(t=this.cookieAtlas)||t.destroy(),this.cookieAtlas=null,null==(e=this.cookieRenderTarget)||e.destroy(),this.cookieRenderTarget=null},e.allocateShadowAtlas=function(t){if(!this.shadowAtlas||this.shadowAtlas.texture.width!==t){this.version++,this.destroyShadowAtlas(),this.shadowAtlas=Cl.createAtlas(this.device,t,0),this.shadowAtlas.cached=!0;var e=4/this.shadowAtlasResolution;this.scissorVec.set(e,e,-2*e,-2*e)}},e.allocateCookieAtlas=function(t){this.cookieAtlas.width!==t&&(this.cookieRenderTarget.resize(t,t),this.version++)},e.allocateUniforms=function(){this._shadowAtlasTextureId=this.device.scope.resolve("shadowAtlasTexture"),this._shadowAtlasParamsId=this.device.scope.resolve("shadowAtlasParams"),this._shadowAtlasParams=new Float32Array(2),this._cookieAtlasTextureId=this.device.scope.resolve("cookieAtlasTexture")},e.updateUniforms=function(){var t=this.shadowAtlas.renderTargets[0],e=!this.device.isWebGL1&&!0?t.depthBuffer:t.colorBuffer;this._shadowAtlasTextureId.setValue(e),this._shadowAtlasParams[0]=this.shadowAtlasResolution,this._shadowAtlasParams[1]=this.shadowEdgePixels,this._shadowAtlasParamsId.setValue(this._shadowAtlasParams),this._cookieAtlasTextureId.setValue(this.cookieAtlas)},e.subdivide=function(t,e){var i=e.atlasSplit;if(!i){var n=Math.ceil(Math.sqrt(t));(i=Ml)[0]=n,i.length=1}var s,r;if(s=i,r=this.atlasSplit,s.length!==r.length||!s.every((function(t,e){return t===r[e]}))){var a;this.version++,this.slots.length=0,this.atlasSplit.length=0,(a=this.atlasSplit).push.apply(a,i);var o=this.atlasSplit[0];if(o>1)for(var h=1/o,l=0;l<o;l++)for(var c=0;c<o;c++){var u=new Pt(l*h,c*h,h,h),d=this.atlasSplit[1+l*o+c];if(d>1)for(var f=0;f<d;f++)for(var p=0;p<d;p++){var m=h/d,_=new Pt(u.x+f*m,u.y+p*m,m,m);this.slots.push(new Il(_))}else this.slots.push(new Il(u))}else this.slots.push(new Il(new Pt(0,0,1,1)));this.slots.sort((function(t,e){return e.size-t.size}))}},e.collectLights=function(t,e){var i=e.cookiesEnabled,n=e.shadowsEnabled,s=!1,r=!1,a=El;a.length=0;return(i||n)&&function(t){for(var e=0;e<t.length;e++){var o=t[e];if(o.visibleThisFrame){var h=n&&o.castShadows,l=i&&!!o.cookie;s||(s=h),r||(r=l),(h||l)&&a.push(o)}}}(t),a.sort((function(t,e){return e.maxScreenSize-t.maxScreenSize})),s&&this.allocateShadowAtlas(this.shadowAtlasResolution),r&&this.allocateCookieAtlas(this.cookieAtlasResolution),(s||r)&&this.subdivide(a.length,e),a},e.setupSlot=function(t,e){t.atlasViewport.copy(e);for(var i=t.numShadowFaces,n=0;n<i;n++)if(t.castShadows||t._cookie){if(Pl.copy(e),Rl.copy(e),2===t._type&&Pl.add(this.scissorVec),1===t._type){var s=Pl.z/3,r=this.cubeSlotsOffsets[n];Pl.x+=s*r.x,Pl.y+=s*r.y,Pl.z=s,Pl.w=s,Rl.copy(Pl)}if(t.castShadows){var a=t.getRenderData(null,n);a.shadowViewport.copy(Pl),a.shadowScissor.copy(Rl)}}},e.assignSlot=function(t,e,i){t.atlasViewportAllocated=!0;var n=this.slots[e];n.lightId=t.id,n.used=!0,i&&(t.atlasSlotUpdated=!0,t.atlasVersion=this.version,t.atlasSlotIndex=e)},e.update=function(t,e){this.shadowAtlasResolution=e.shadowAtlasResolution,this.cookieAtlasResolution=e.cookieAtlasResolution;var i=this.collectLights(t,e);if(i.length>0){for(var n=this.slots,s=0;s<n.length;s++)n[s].used=!1;for(var r=Math.min(i.length,n.length),a=0;a<r;a++){var o=i[a];o.castShadows&&(o._shadowMap=this.shadowAtlas);var h=n[o.atlasSlotIndex];if(o.atlasVersion===this.version&&o.id===(null==h?void 0:h.lightId)){var l=n[o.atlasSlotIndex];l.size!==n[a].size||l.used||this.assignSlot(o,o.atlasSlotIndex,!1)}}for(var c=0,u=0;u<r;u++){for(;c<n.length&&n[c].used;)c++;var d=i[u];d.atlasViewportAllocated||this.assignSlot(d,c,!0);var f=n[d.atlasSlotIndex];this.setupSlot(d,f.rect)}}this.updateUniforms()},t}(),Dl=[new wt(-1,0,0),new wt(1,0,0),new wt(0,-1,0),new wt(0,1,0),new wt(0,0,-1),new wt(0,0,1)],Ol=function(){function t(){this.colors=new Float32Array(18)}return t.prototype.update=function(t,e){for(var i=this.colors,n=t.r,s=t.g,r=t.b,a=0;a<6;a++)i[3*a]=n,i[3*a+1]=s,i[3*a+2]=r;for(var o=0;o<e.length;o++){var h=e[o];if(0===h._type)for(var l=0;l<6;l++){var c=Math.max(Dl[l].dot(h._direction),0)*h._intensity,u=h._color;i[3*l]+=u.r*c,i[3*l+1]+=u.g*c,i[3*l+2]+=u.b*c}}},t}(),kl=function(){function t(){this.cache=new Map}var e=t.prototype;return e.destroy=function(){this.clear(),this.cache=null},e.clear=function(){this.cache.forEach((function(t){t.forEach((function(t){t.destroy()}))})),this.cache.clear()},e.getKey=function(t){return(1===t._type)+"-"+t._shadowType+"-"+t._shadowResolution},e.get=function(t,e){var i=this.getKey(e),n=this.cache.get(i);if(n&&n.length)return n.pop();var s=Cl.create(t,e);return s.cached=!0,s},e.add=function(t,e){var i=this.getKey(t),n=this.cache.get(i);n?n.push(e):this.cache.set(i,[e])},t}(),Fl=function(){function t(t,e){this.shadowLights=[],this.renderer=void 0,this.shadowRenderer=void 0,this.device=void 0,this.renderer=t,this.shadowRenderer=e,this.device=t.device}var e=t.prototype;return e.cull=function(t,e,i){void 0===i&&(i=null);var n=this.renderer.scene.clusteredLightingEnabled;t.visibleThisFrame=!0,n||t._shadowMap||(t._shadowMap=Cl.create(this.device,t));for(var s=t._type,r=2===s?1:6,a=0;a<r;a++){var o=t.getRenderData(null,a),h=o.shadowCamera;h.nearClip=t.attenuationEnd/1e3,h.farClip=t.attenuationEnd,o.depthRangeCompensation=h.farClip-h.nearClip;var l=h._node,c=t._node;if(l.setPosition(c.getPosition()),2===s)h.fov=2*t._outerConeAngle,l.setRotation(c.getRotation()),l.rotateLocal(-90,0,0);else if(1===s)if(n){var u=2/(this.shadowRenderer.lightTextureAtlas.shadowAtlasResolution*t.atlasViewport.z/3)*this.shadowRenderer.lightTextureAtlas.shadowEdgePixels;h.fov=Math.atan(1+u)*_t.RAD_TO_DEG*2}else h.fov=90;this.renderer.updateCameraFrustum(h),this.shadowRenderer.cullShadowCasters(e,t,o.visibleCasters,h,i)}},e.prepareLights=function(t,e){for(var i,n=0;n<e.length;n++){var s=e[n];if(this.shadowRenderer.needsShadowRendering(s)&&s.atlasViewportAllocated){t.push(s);for(var r=0;r<s.numShadowFaces;r++)i=this.shadowRenderer.prepareFace(s,null,r)}}return i},e.prepareClusteredRenderPass=function(t,e){var i=this,n=this.shadowLights,s=this.prepareLights(n,e),r=n.length;r&&(this.shadowRenderer.setupRenderPass(t,s,!1),t._execute=function(){for(var t=0;t<r;t++)for(var e=n[t],s=0;s<e.numShadowFaces;s++)i.shadowRenderer.renderFace(e,null,s,!0);n.length=0})},e.setupNonClusteredFaceRenderPass=function(t,e,i,n){var s=this,r=this.shadowRenderer.prepareFace(e,null,i),a=new uo(this.device,(function(){s.shadowRenderer.renderFace(e,null,i,!1)}));this.shadowRenderer.setupRenderPass(a,r,!0),n&&(a._after=function(){s.shadowRenderer.renderVsm(e,r)}),t.addRenderPass(a)},e.buildNonClusteredRenderPasses=function(t,e){for(var i=0;i<e.length;i++){var n=e[i];if(this.shadowRenderer.needsShadowRendering(n))for(var s=2===n._type,r=n.numShadowFaces,a=0;a<r;a++)this.setupNonClusteredFaceRenderPass(t,n,a,s)}},t}(),Bl=new Ht,Ul=new wt,Nl=new Ft,zl=[new wt,new wt,new wt,new wt,new wt,new wt,new wt,new wt],Vl={min:0,max:0};function Gl(t,e,i){zl[0].x=zl[1].x=zl[2].x=zl[3].x=e.x,zl[1].y=zl[3].y=zl[7].y=zl[5].y=e.y,zl[2].z=zl[3].z=zl[6].z=zl[7].z=e.z,zl[4].x=zl[5].x=zl[6].x=zl[7].x=i.x,zl[0].y=zl[2].y=zl[4].y=zl[6].y=i.y,zl[0].z=zl[1].z=zl[4].z=zl[5].z=i.z;for(var n=9999999999,s=-9999999999,r=0;r<8;++r){t.transformPoint(zl[r],zl[r]);var a=zl[r].z;a<n&&(n=a),a>s&&(s=a)}return Vl.min=n,Vl.max=s,Vl}var Hl=function(){function t(t,e){this.renderer=void 0,this.shadowRenderer=void 0,this.device=void 0,this.renderer=t,this.shadowRenderer=e,this.device=t.device}var e=t.prototype;return e.cull=function(t,e,i,n){void 0===n&&(n=null),t.visibleThisFrame=!0,t._shadowMap||(t._shadowMap=Cl.create(this.device,t));var s=i._nearClip;this.generateSplitDistances(t,s,Math.min(i._farClip,t.shadowDistance));for(var r=t.shadowUpdateOverrides,a=0;a<t.numCascades&&0!==(null==r?void 0:r[a]);a++){var o=t.getRenderData(i,a),h=o.shadowCamera;h.renderTarget=t._shadowMap.renderTargets[0],o.shadowViewport.copy(t.cascades[a]),o.shadowScissor.copy(t.cascades[a]);var l=h._node,c=t._node;l.setPosition(c.getPosition()),l.setRotation(c.getRotation()),l.rotateLocal(-90,0,0);var u=0===a?s:t._shadowCascadeDistances[a-1],d=t._shadowCascadeDistances[a],f=i.getFrustumCorners(u,d);Ul.set(0,0,0);for(var p=i.node.getWorldTransform(),m=0;m<8;m++)p.transformPoint(f[m],f[m]),Ul.add(f[m]);Ul.mulScalar(1/8);for(var _=0,v=0;v<8;v++){var g=f[v].sub(Ul).length();g>_&&(_=g)}var y=l.right,x=l.up,S=l.forward,b=.25*t._shadowResolution/_,w=Math.ceil(Ul.dot(x)*b)/b,T=Math.ceil(Ul.dot(y)*b)/b,A=x.mulScalar(w),C=y.mulScalar(T),E=Ul.dot(S),M=S.mulScalar(E);Ul.add2(A,C).add(M),l.setPosition(Ul),l.translateLocal(0,0,1e6),h.nearClip=.01,h.farClip=2e6,h.orthoHeight=_,this.renderer.updateCameraFrustum(h),this.shadowRenderer.cullShadowCasters(e,t,o.visibleCasters,h,n);for(var P=!0,R=o.visibleCasters,I=0;I<R.length;I++){var L=R[I];P?(P=!1,Bl.copy(L.aabb)):Bl.add(L.aabb)}Nl.copy(l.getWorldTransform()).invert();var D=Gl(Nl,Bl.getMin(),Bl.getMax());l.translateLocal(0,0,D.max+.1),h.farClip=D.max-D.min+.2,o.depthRangeCompensation=h.farClip,o.projectionCompensation=_}},e.generateSplitDistances=function(t,e,i){t._shadowCascadeDistances.fill(i);for(var n=1;n<t.numCascades;n++){var s=n/t.numCascades,r=e+(i-e)*s,a=e*Math.pow(i/e,s),o=_t.lerp(r,a,t.cascadeDistribution);t._shadowCascadeDistances[n-1]=o}},e.addLightRenderPasses=function(t,e,i){for(var n,s=this,r=e.numShadowFaces,a=e.shadowUpdateOverrides,o=!0,h=0;h<r;h++)0===(null==a?void 0:a[h])&&(o=!1),n=this.shadowRenderer.prepareFace(e,i,h);var l=new uo(this.device,(function(){for(var t=0;t<r;t++)0!==(null==a?void 0:a[t])&&s.shadowRenderer.renderFace(e,i,t,!o),1===(null==a?void 0:a[t])&&(a[t]=0)}));l._after=function(){s.shadowRenderer.renderVsm(e,i)},this.shadowRenderer.setupRenderPass(l,n,o),t.addRenderPass(l)},e.buildFrameGraph=function(t,e,i){for(var n=0;n<e.length;n++){var s=e[n];this.shadowRenderer.needsShadowRendering(s)&&this.addLightRenderPasses(t,s,i.camera)}},t}();function Wl(t,e){return Math.exp(-t*t/(2*e*e))}var Xl=new Set,jl=new Ft,ql=new Ft,Yl=new Float32Array(2),Kl=new Pt(1,1,0,0),Zl=new Ft,Ql=function(){function t(t,e){this.shadowPassCache=[],this.device=t.device,this.renderer=t,this.lightTextureAtlas=e;var i=this.device.scope;this.polygonOffsetId=i.resolve("polygonOffset"),this.polygonOffset=new Float32Array(2),this.sourceId=i.resolve("source"),this.pixelOffsetId=i.resolve("pixelOffset"),this.weightId=i.resolve("weight[0]"),this.blurVsmShaderCode=[_o.blurVSMPS,"#define GAUSS\n"+_o.blurVSMPS];var n="#define PACKED\n";this.blurPackedVsmShaderCode=[n+this.blurVsmShaderCode[0],n+this.blurVsmShaderCode[1]],this.blurVsmShader=[{},{}],this.blurPackedVsmShader=[{},{}],this.blurVsmWeights={},this.shadowMapLightRadiusId=i.resolve("light_radius"),this.viewUniformFormat=null,this.viewBindGroupFormat=null,this.blendStateWrite=new Ui,this.blendStateNoWrite=new Ui,this.blendStateNoWrite.setColorWrite(!1,!1,!1,!1)}t.createShadowCamera=function(t,e,i,n){var s=il.create("ShadowCamera",i,n);return s.clearColor=e>=1&&e<=3?new vt(0,0,0,0):new vt(1,1,1,1),s.clearDepthBuffer=!0,s.clearStencilBuffer=!1,s},t.setShadowCameraSettings=function(t,e,i,n,s){var r=4===i||(5===i||0===i)&&e.supportsDepthShadow;1!==n||s||(r=!1),t.clearColorBuffer=!r};var e=t.prototype;return e._cullShadowCastersInternal=function(t,e,i){for(var n=t.length,s=0;s<n;s++){var r=t[s];r.castShadow&&(r.cull&&!r._isVisible(i)||(r.visibleThisFrame=!0,e.push(r)))}},e.cullShadowCasters=function(t,e,i,n,s){if(i.length=0,s)this._cullShadowCastersInternal(s,i,n);else{for(var r=t.layerList,a=r.length,o=0;o<a;o++){var h=r[o];h._lightsSet.has(e)&&(Xl.has(h)||(Xl.add(h),this._cullShadowCastersInternal(h.shadowCasters,i,n)))}Xl.clear()}i.sort(this.renderer.sortCompareDepth)},e.setupRenderState=function(t,e){var i=this.renderer.scene.clusteredLightingEnabled;t.isWebGL2||t.isWebGPU?1!==e._type||i?(t.setDepthBias(!0),t.setDepthBiasValues(-1e3*e.shadowBias,-1e3*e.shadowBias)):t.setDepthBias(!1):t.extStandardDerivatives&&(1===e._type?(this.polygonOffset[0]=0,this.polygonOffset[1]=0,this.polygonOffsetId.setValue(this.polygonOffset)):(this.polygonOffset[0]=-1e3*e.shadowBias,this.polygonOffset[1]=-1e3*e.shadowBias,this.polygonOffsetId.setValue(this.polygonOffset)));var n=t.isWebGL2||t.isWebGPU,s=i?e._isPcf&&n:e._isPcf&&n&&1!==e._type;t.setBlendState(s?this.blendStateNoWrite:this.blendStateWrite),t.setDepthState(Ni.DEFAULT),t.setStencilState(null,null)},e.restoreRenderState=function(t){t.isWebGL2||t.isWebGPU?t.setDepthBias(!1):t.extStandardDerivatives&&(this.polygonOffset[0]=0,this.polygonOffset[1]=0,this.polygonOffsetId.setValue(this.polygonOffset))},e.dispatchUniforms=function(t,e,i,n){var s=e._node;0!==t._type&&(this.renderer.dispatchViewPos(s.getPosition()),this.shadowMapLightRadiusId.setValue(t.attenuationEnd)),jl.setTRS(s.getPosition(),s.getRotation(),wt.ONE).invert(),ql.mul2(e.projectionMatrix,jl);var r=i.shadowViewport;e.rect=r,e.scissorRect=i.shadowScissor,Zl.setViewport(r.x,r.y,r.z,r.w),i.shadowMatrix.mul2(Zl,ql),0===t._type&&t._shadowMatrixPalette.set(i.shadowMatrix.data,16*n)},e.getShadowPass=function(t){var e,i=t._type,n=t._shadowType,s=null==(e=this.shadowPassCache[i])?void 0:e[n];if(!s){var r="ShadowPass_"+i+"_"+n;s=Do.get(this.device).allocate(r,{isShadow:!0,lightType:i,shadowType:n}),this.shadowPassCache[i]||(this.shadowPassCache[i]=[]),this.shadowPassCache[i][n]=s}return s.index},e.submitCasters=function(t,e){for(var i=this.device,n=this.renderer,s=n.scene,r=this.getShadowPass(e),a=t.length,o=0;o<a;o++){var h=t[o],l=h.mesh;h.ensureMaterial(i);var c=h.material;n.setBaseConstants(i,c),n.setSkinning(i,h),c.dirty&&(c.updateUniforms(i,s),c.dirty=!1),c.chunks&&(n.setupCullMode(!0,1,h),c.setParameters(i),h.setParameters(i,16));var u=h.getShaderInstance(r,0,s,this.viewUniformFormat,this.viewBindGroupFormat),d=u.shader;h._key[1]=d.id,!d.failed&&i.setShader(d),n.setVertexBuffers(i,l),n.setMorphing(i,h.morphInstance),this.renderer.setupMeshUniformBuffers(u,h);var f=h.renderStyle;i.setIndexBuffer(l.indexBuffer[f]),n.drawInstance(i,h,l,f),n._shadowDrawCalls++}},e.needsShadowRendering=function(t){var e=t.enabled&&t.castShadows&&0!==t.shadowUpdateMode&&t.visibleThisFrame;return 1===t.shadowUpdateMode&&(t.shadowUpdateMode=0),e&&(this.renderer._shadowMapUpdates+=t.numShadowFaces),e},e.getLightRenderData=function(t,e,i){return t.getRenderData(0===t._type?e:null,i)},e.setupRenderPass=function(t,e,i){var n=e.renderTarget;t.init(n),t.depthStencilOps.clearDepthValue=1,t.depthStencilOps.clearDepth=i,n.depthBuffer?t.depthStencilOps.storeDepth=!0:(t.colorOps.clearValue.copy(e.clearColor),t.colorOps.clear=i,t.depthStencilOps.storeDepth=!1),t.requiresCubemaps=!1},e.prepareFace=function(e,i,n){var s=e._type,r=e._shadowType,a=this.renderer.scene.clusteredLightingEnabled,o=this.getLightRenderData(e,i,n).shadowCamera;t.setShadowCameraSettings(o,this.device,r,s,a);var h=0===s?0:n;return o.renderTarget=e._shadowMap.renderTargets[h],o},e.renderFace=function(t,e,i,n,s){void 0===s&&(s=!0);var r=this.device,a=this.getLightRenderData(t,e,i),o=a.shadowCamera;this.dispatchUniforms(t,o,a,i);var h=o.renderTarget,l=this.renderer;l.setCameraUniforms(o,h),r.supportsUniformBuffers&&l.setupViewUniformBuffers(a.viewBindGroups,this.viewUniformFormat,this.viewBindGroupFormat,1),s?(l.setupViewport(o,h),n&&l.clear(o)):l.clearView(o,h,!0,!1),this.setupRenderState(r,t),this.submitCasters(a.visibleCasters,t),this.restoreRenderState(r)},e.render=function(t,e,i){if(void 0===i&&(i=!0),this.needsShadowRendering(t)){for(var n=t.numShadowFaces,s=0;s<n;s++)this.prepareFace(t,e,s),this.renderFace(t,e,s,!0,i);this.renderVsm(t,e)}},e.renderVsm=function(t,e){t._isVsm&&t._vsmBlurSize>1&&(this.renderer.scene.clusteredLightingEnabled&&0!==t._type||this.applyVsmBlur(t,e))},e.getVsmBlurShader=function(t,e,i){var n=(t?this.blurPackedVsmShader:this.blurVsmShader)[e][i];if(!n){this.blurVsmWeights[i]=function(t){for(var e=(t-1)/6,i=.5*(t-1),n=new Array(t),s=0,r=0;r<t;++r)n[r]=Wl(r-i,e),s+=n[r];for(var a=0;a<t;++a)n[a]/=s;return n}(i);var s=_o.fullscreenQuadVS,r="#define SAMPLES "+i+"\n";r+=t?this.blurPackedVsmShaderCode[e]:this.blurVsmShaderCode[e];var a="blurVsm"+e+i+t;n=bo(this.device,s,r,a),t?this.blurPackedVsmShader[e][i]=n:this.blurVsmShader[e][i]=n}return n},e.applyVsmBlur=function(t,e){var i=this.device;i.setBlendState(Ui.NOBLEND);var n=t.getRenderData(0===t._type?e:null,0).shadowCamera.renderTarget,s=this.renderer.shadowMapCache.get(i,t),r=s.renderTargets[0],a=1===t._shadowType,o=t.vsmBlurMode,h=t._vsmBlurSize,l=this.getVsmBlurShader(a,o,h);Kl.z=t._shadowResolution-2,Kl.w=Kl.z,this.sourceId.setValue(n.colorBuffer),Yl[0]=1/t._shadowResolution,Yl[1]=0,this.pixelOffsetId.setValue(Yl),1===o&&this.weightId.setValue(this.blurVsmWeights[h]),Ro(i,r,l,null,Kl),this.sourceId.setValue(r.colorBuffer),Yl[1]=Yl[0],Yl[0]=0,this.pixelOffsetId.setValue(Yl),Ro(i,n,l,null,Kl),this.renderer.shadowMapCache.add(t,s)},e.initViewBindGroupFormat=function(){this.device.supportsUniformBuffers&&!this.viewUniformFormat&&(this.viewUniformFormat=new Dn(this.device,[new Ln("matrix_viewProjection",vi)]),this.viewBindGroupFormat=new Un(this.device,[new Fn(Ti,3)],[]))},e.frameUpdate=function(){this.initViewBindGroupFormat()},t}(),$l=[],Jl=function(){function t(t){this._empty=null,this._allocated=[],this._clusters=new Map,this.device=t}var e=t.prototype;return e.destroy=function(){this._empty&&(this._empty.destroy(),this._empty=null),this._allocated.forEach((function(t){t.destroy()})),this._allocated.length=0},e.assign=function(t){var e=this.empty;$l.push.apply($l,this._allocated),this._allocated.length=0,this._clusters.clear();for(var i=t.length,n=0;n<i;n++){var s=t[n];s.lightClusters=null;var r=s.layer;if(r.hasClusteredLights&&r.meshInstances.length){var a,o=r.getLightIdHash(),h=this._clusters.get(o),l=null==h?void 0:h.lightClusters;if(!l)l=null!=(a=$l.pop())?a:new Al(this.device),this._allocated.push(l),this._clusters.set(o,s);s.lightClusters=l}s.lightClusters||(s.lightClusters=e)}$l.forEach((function(t){return t.destroy()})),$l.length=0},e.update=function(t,e,i){this.assign(t),this._clusters.forEach((function(t){var n=t.layer;t.lightClusters.update(n.clusteredLightsSet,e,i)}))},y(t,[{key:"count",get:function(){return this._allocated.length}},{key:"empty",get:function(){if(!this._empty){var t=new Al(this.device);t.name="ClusterEmpty",t.update([],!1,null),this._empty=t}return this._empty}}]),t}(),tc="\n\tattribute vec2 vertex_position;\n\tvarying vec2 uv0;\n\tvoid main(void) {\n\t\tgl_Position = vec4(vertex_position, 0.5, 1.0);\n\t\tuv0 = vertex_position.xy * 0.5 + 0.5;\n\t\t#ifndef WEBGPU\n\t\t\tuv0.y = 1.0 - uv0.y;\n\t\t#endif\n\t}",ec=new Pt,ic=[],nc=function(t){function e(e,i){var n;return(n=t.call(this,e)||this)._quadRenderer2D=null,n._quadRendererCube=null,n._filteredLights=[],n._cubeSlotsOffsets=i,n.requiresCubemaps=!1,n.blitTextureId=e.scope.resolve("blitTexture"),n.invViewProjId=e.scope.resolve("invViewProj"),n}S(e,t);var i=e.prototype;return i.destroy=function(){var t,e;null==(t=this._quadRenderer2D)||t.destroy(),this._quadRenderer2D=null,null==(e=this._quadRendererCube)||e.destroy(),this._quadRendererCube=null},e.create=function(t,i){var n=new e(t.device,i);return n.init(t),n.colorOps.clear=!1,n.depthStencilOps.clearDepth=!1,n},i.update=function(t){var e=this._filteredLights;this.filter(t,e),this.executeEnabled=e.length>0},i.filter=function(t,e){for(var i=0;i<t.length;i++){var n=t[i];0!==n._type&&(n.atlasViewportAllocated&&n.atlasSlotUpdated&&n.enabled&&n.cookie&&n.visibleThisFrame&&e.push(n))}},i.initInvViewProjMatrices=function(){if(!ic.length)for(var t=0;t<6;t++){var e=il.create(null,1,t),i=e.projectionMatrix,n=e.node.getLocalTransform().clone().invert();ic[t]=(new Ft).mul2(i,n).invert()}},i.execute=function(){var t=this.device;t.setBlendState(Ui.NOBLEND),t.setCullMode(se),t.setDepthState(Ni.NODEPTH),t.setStencilState();for(var e=this.renderTarget.colorBuffer.width,i=this._cubeSlotsOffsets,n=this._filteredLights,s=0;s<n.length;s++){var r=n[s],a=r.numShadowFaces,o=a>1?this.quadRendererCube:this.quadRenderer2D;a>1&&this.initInvViewProjMatrices(),this.blitTextureId.setValue(r.cookie);for(var h=0;h<a;h++){if(ec.copy(r.atlasViewport),a>1){var l=ec.z/3,c=i[h];ec.x+=l*c.x,ec.y+=l*c.y,ec.z=l,ec.w=l,this.invViewProjId.setValue(ic[h].data)}ec.mulScalar(e),o.render(ec)}}n.length=0},y(e,[{key:"quadRenderer2D",get:function(){if(!this._quadRenderer2D){var t=bo(this.device,tc,"\n\tvarying vec2 uv0;\n\tuniform sampler2D blitTexture;\n\tvoid main(void) {\n\t\tgl_FragColor = texture2D(blitTexture, uv0);\n\t}","cookieRenderer2d");this._quadRenderer2D=new Mo(t)}return this._quadRenderer2D}},{key:"quadRendererCube",get:function(){if(!this._quadRendererCube){var t=bo(this.device,tc,"\n\tvarying vec2 uv0;\n\tuniform samplerCube blitTexture;\n\tuniform mat4 invViewProj;\n\tvoid main(void) {\n\t\tvec4 projPos = vec4(uv0 * 2.0 - 1.0, 0.5, 1.0);\n\t\tvec4 worldPos = invViewProj * projPos;\n\t\tgl_FragColor = textureCube(blitTexture, worldPos.xyz);\n\t}","cookieRendererCube");this._quadRendererCube=new Mo(t)}return this._quadRendererCube}}]),e}(uo),sc=0,rc=[0,0,0,0],ac=new Ft,oc=new Ft,hc=new Ft,lc=new At,cc=new jt,uc=(new Ft).setScale(1,-1,1),dc=new Set,fc=new Set,pc=(new Ft).set([1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1]),mc=new Ft,_c=new Ft,vc=new Ft,gc=new Ft,yc=new Set,xc=[],Sc=[],bc=function(){function t(t){this.clustersDebugRendered=!1,this.processingMeshInstances=new Set,this.worldClustersAllocator=void 0,this.lights=[],this.localLights=[],this.device=t,this.scene=null,this.worldClustersAllocator=new Jl(t),this.lightTextureAtlas=new Ll(t),this.shadowMapCache=new kl,this.shadowRenderer=new Ql(this,this.lightTextureAtlas),this._shadowRendererLocal=new Fl(this,this.shadowRenderer),this._shadowRendererDirectional=new Hl(this,this.shadowRenderer),this.cookiesRenderPass=nc.create(this.lightTextureAtlas.cookieRenderTarget,this.lightTextureAtlas.cubeSlotsOffsets),this.viewUniformFormat=null,this.viewBindGroupFormat=null,this._skinTime=0,this._morphTime=0,this._cullTime=0,this._shadowMapTime=0,this._lightClustersTime=0,this._layerCompositionUpdateTime=0,this._shadowDrawCalls=0,this._skinDrawCalls=0,this._instancedDrawCalls=0,this._shadowMapUpdates=0,this._numDrawCallsCulled=0,this._camerasRendered=0,this._lightClusters=0;var e=t.scope;this.boneTextureId=e.resolve("texture_poseMap"),this.boneTextureSizeId=e.resolve("texture_poseMapSize"),this.poseMatrixId=e.resolve("matrix_pose[0]"),this.modelMatrixId=e.resolve("matrix_model"),this.normalMatrixId=e.resolve("matrix_normal"),this.viewInvId=e.resolve("matrix_viewInverse"),this.viewPos=new Float32Array(3),this.viewPosId=e.resolve("view_position"),this.projId=e.resolve("matrix_projection"),this.projSkyboxId=e.resolve("matrix_projectionSkybox"),this.viewId=e.resolve("matrix_view"),this.viewId3=e.resolve("matrix_view3"),this.viewProjId=e.resolve("matrix_viewProjection"),this.flipYId=e.resolve("projectionFlipY"),this.tbnBasis=e.resolve("tbnBasis"),this.nearClipId=e.resolve("camera_near"),this.farClipId=e.resolve("camera_far"),this.cameraParams=new Float32Array(4),this.cameraParamsId=e.resolve("camera_params"),this.alphaTestId=e.resolve("alpha_ref"),this.opacityMapId=e.resolve("texture_opacityMap"),this.exposureId=e.resolve("exposure"),this.twoSidedLightingNegScaleFactorId=e.resolve("twoSidedLightingNegScaleFactor"),this.twoSidedLightingNegScaleFactorId.setValue(0),this.morphWeightsA=e.resolve("morph_weights_a"),this.morphWeightsB=e.resolve("morph_weights_b"),this.morphPositionTex=e.resolve("morphPositionTex"),this.morphNormalTex=e.resolve("morphNormalTex"),this.morphTexParams=e.resolve("morph_tex_params"),this.lightCube=new Ol,this.constantLightCube=e.resolve("lightCube[0]")}var e=t.prototype;return e.destroy=function(){this.shadowRenderer=null,this._shadowRendererLocal=null,this._shadowRendererDirectional=null,this.shadowMapCache.destroy(),this.shadowMapCache=null,this.cookiesRenderPass.destroy(),this.cookiesRenderPass=null,this.lightTextureAtlas.destroy(),this.lightTextureAtlas=null},e.sortCompare=function(t,e){if(t.layer===e.layer){if(t.drawOrder&&e.drawOrder)return t.drawOrder-e.drawOrder;if(t.zdist&&e.zdist)return e.zdist-t.zdist;if(t.zdist2&&e.zdist2)return t.zdist2-e.zdist2}return e._key[0]-t._key[0]},e.sortCompareMesh=function(t,e){if(t.layer===e.layer){if(t.drawOrder&&e.drawOrder)return t.drawOrder-e.drawOrder;if(t.zdist&&e.zdist)return e.zdist-t.zdist}var i=t._key[0],n=e._key[0];return i===n&&t.mesh&&e.mesh?e.mesh.id-t.mesh.id:n-i},e.sortCompareDepth=function(t,e){var i=t._key[1],n=e._key[1];return i===n&&t.mesh&&e.mesh?e.mesh.id-t.mesh.id:n-i},e.setupViewport=function(t,e){var i=this.device,n=e?e.width:i.width,s=e?e.height:i.height,r=t.rect,a=Math.floor(r.x*n),o=Math.floor(r.y*s),h=Math.floor(r.z*n),l=Math.floor(r.w*s);if(i.setViewport(a,o,h,l),t._scissorRectClear){var c=t.scissorRect;a=Math.floor(c.x*n),o=Math.floor(c.y*s),h=Math.floor(c.z*n),l=Math.floor(c.w*s)}i.setScissor(a,o,h,l)},e.setCameraUniforms=function(t,e){var i=null==e?void 0:e.flipY,n=1;if(t.xr&&t.xr.session){var s,r=t._node.parent;r&&(s=r.getWorldTransform());var a=t.xr.views;n=a.length;for(var o=0;o<n;o++){var h=a[o];r?(h.viewInvOffMat.mul2(s,h.viewInvMat),h.viewOffMat.copy(h.viewInvOffMat).invert()):(h.viewInvOffMat.copy(h.viewInvMat),h.viewOffMat.copy(h.viewMat)),h.viewMat3.setFromMat4(h.viewOffMat),h.projViewOffMat.mul2(h.projMat,h.viewOffMat),h.position[0]=h.viewInvOffMat.data[12],h.position[1]=h.viewInvOffMat.data[13],h.position[2]=h.viewInvOffMat.data[14],t.frustum.setFromMat4(h.projViewOffMat)}}else{var l=t.projectionMatrix;t.calculateProjection&&t.calculateProjection(l,0);var c=t.getProjectionMatrixSkybox();if(i&&(l=mc.mul2(uc,l),c=_c.mul2(uc,c)),this.device.isWebGPU&&(l=vc.mul2(pc,l),c=gc.mul2(pc,c)),this.projId.setValue(l.data),this.projSkyboxId.setValue(c.data),t.calculateTransform)t.calculateTransform(oc,0);else{var u=t._node.getPosition(),d=t._node.getRotation();oc.setTRS(u,d,wt.ONE)}this.viewInvId.setValue(oc.data),hc.copy(oc).invert(),this.viewId.setValue(hc.data),lc.setFromMat4(hc),this.viewId3.setValue(lc.data),ac.mul2(l,hc),this.viewProjId.setValue(ac.data),this.flipYId.setValue(i?-1:1),this.dispatchViewPos(t._node.getPosition()),t.frustum.setFromMat4(ac)}this.tbnBasis.setValue(i?-1:1);var f=t._nearClip,p=t._farClip;return this.nearClipId.setValue(f),this.farClipId.setValue(p),this.cameraParams[0]=1/p,this.cameraParams[1]=p,this.cameraParams[2]=f,this.cameraParams[3]=1===t.projection?1:0,this.cameraParamsId.setValue(this.cameraParams),this.exposureId.setValue(this.scene.physicalUnits?t.getExposure():this.scene.exposure),n},e.clear=function(t,e,i,n){var s=((null!=e?e:t._clearColorBuffer)?1:0)|((null!=i?i:t._clearDepthBuffer)?2:0)|((null!=n?n:t._clearStencilBuffer)?4:0);s&&this.device.clear({color:[t._clearColor.r,t._clearColor.g,t._clearColor.b,t._clearColor.a],depth:t._clearDepth,stencil:t._clearStencil,flags:s})},e.setCamera=function(t,e,i,n){this.setCameraUniforms(t,e),this.clearView(t,e,i,!1)},e.clearView=function(t,e,i,n){var s=this.device;if(s.setRenderTarget(e),s.updateBegin(),n&&(s.setColorWrite(!0,!0,!0,!0),s.setDepthWrite(!0)),this.setupViewport(t,e),i){var r=t._clearOptions;s.clear(r||{color:[t._clearColor.r,t._clearColor.g,t._clearColor.b,t._clearColor.a],depth:t._clearDepth,flags:(t._clearColorBuffer?1:0)|(t._clearDepthBuffer?2:0)|(t._clearStencilBuffer?4:0),stencil:t._clearStencil})}},e.setupCullMode=function(t,e,i){var n=i.material,s=se;if(t){var r=1;2!==n.cull&&1!==n.cull||(r=e*i.flipFacesFactor*i.node.worldScaleSign),s=r<0?2===n.cull?1:2:n.cull}this.device.setCullMode(s),s===se&&n.cull===se&&this.twoSidedLightingNegScaleFactorId.setValue(i.node.worldScaleSign)},e.updateCameraFrustum=function(t){if(t.xr&&t.xr.views.length){var e=t.xr.views[0];return ac.mul2(e.projMat,e.viewOffMat),void t.frustum.setFromMat4(ac)}var i=t.projectionMatrix;if(t.calculateProjection&&t.calculateProjection(i,0),t.calculateTransform)t.calculateTransform(oc,0);else{var n=t._node.getPosition(),s=t._node.getRotation();oc.setTRS(n,s,wt.ONE),this.viewInvId.setValue(oc.data)}hc.copy(oc).invert(),ac.mul2(i,hc),t.frustum.setFromMat4(ac)},e.setBaseConstants=function(t,e){t.setCullMode(e.cull),e.opacityMap&&this.opacityMapId.setValue(e.opacityMap),(e.opacityMap||e.alphaTest>0)&&this.alphaTestId.setValue(e.alphaTest)},e.updateCpuSkinMatrices=function(t){sc++;var e=t.length;if(0!==e)for(var i=0;i<e;i++){var n=t[i].skinInstance;n&&(n.updateMatrices(t[i].node,sc),n._dirty=!0)}},e.updateGpuSkinMatrices=function(t){for(var e,i=A(t);!(e=i()).done;){var n=e.value,s=n.skinInstance;s&&s._dirty&&(s.updateMatrixPalette(n.node,sc),s._dirty=!1)}},e.updateMorphing=function(t){for(var e,i=A(t);!(e=i()).done;){var n=e.value.morphInstance;n&&n._dirty&&n.update()}},e.gpuUpdate=function(t){this.updateGpuSkinMatrices(t),this.updateMorphing(t)},e.setVertexBuffers=function(t,e){t.setVertexBuffer(e.vertexBuffer)},e.setMorphing=function(t,e){if(e)if(e.morph.useTextureMorph)t.setVertexBuffer(e.morph.vertexBufferIds),this.morphPositionTex.setValue(e.texturePositions),this.morphNormalTex.setValue(e.textureNormals),this.morphTexParams.setValue(e._textureParams);else{for(var i=0;i<e._activeVertexBuffers.length;i++){var n=e._activeVertexBuffers[i];if(n){var s=Ue+(i+8);n.format.elements[0].name=s,n.format.elements[0].scopeId=t.scope.resolve(s),n.format.update(),t.setVertexBuffer(n)}}this.morphWeightsA.setValue(e._shaderMorphWeightsA),this.morphWeightsB.setValue(e._shaderMorphWeightsB)}},e.setSkinning=function(t,e){if(e.skinInstance)if(this._skinDrawCalls++,t.supportsBoneTextures){var i=e.skinInstance.boneTexture;this.boneTextureId.setValue(i),rc[0]=i.width,rc[1]=i.height,rc[2]=1/i.width,rc[3]=1/i.height,this.boneTextureSizeId.setValue(rc)}else this.poseMatrixId.setValue(e.skinInstance.matrixPalette)},e.dispatchViewPos=function(t){var e=this.viewPos;e[0]=t.x,e[1]=t.y,e[2]=t.z,this.viewPosId.setValue(e)},e.initViewBindGroupFormat=function(t){if(this.device.supportsUniformBuffers&&!this.viewUniformFormat){var e=[new Ln("matrix_viewProjection",vi),new Ln("cubeMapRotationMatrix",_i),new Ln("view_position",4),new Ln("skyboxIntensity",2),new Ln("exposure",2),new Ln("textureBias",2)];t&&e.push.apply(e,[new Ln("clusterCellsCountByBoundsSize",4),new Ln("clusterTextureSize",4),new Ln("clusterBoundsMin",4),new Ln("clusterBoundsDelta",4),new Ln("clusterCellsDot",4),new Ln("clusterCellsMax",4),new Ln("clusterCompressionLimit0",3),new Ln("shadowAtlasParams",3),new Ln("clusterMaxCells",1),new Ln("clusterSkip",2)]),this.viewUniformFormat=new Dn(this.device,e);var i=[new Fn(Ti,3)],n=[new Bn("lightsTextureFloat",2,ai,1),new Bn("lightsTexture8",2,ai,1),new Bn("shadowAtlasTexture",2,ai,2),new Bn("cookieAtlasTexture",2,ai,0),new Bn("areaLightsLutTex1",2,ai,0),new Bn("areaLightsLutTex2",2,ai,0)];t&&n.push.apply(n,[new Bn("clusterWorldTexture",2,ai,1)]),this.viewBindGroupFormat=new Un(this.device,i,n)}},e.setupViewUniformBuffers=function(t,e,i,n){for(var s=this.device;t.length<n;){var r=new xs(s,e,!1),a=new ms(s,i,r);t.push(a)}var o=t[0];o.defaultUniformBuffer.update(),o.update(),s.setBindGroup(1,o)},e.setupMeshUniformBuffers=function(t,e){var i=this.device;if(i.supportsUniformBuffers){this.modelMatrixId.setValue(e.node.worldTransform.data),this.normalMatrixId.setValue(e.node.normalMatrix.data);var n=t.getBindGroup(i);n.defaultUniformBuffer.update(),n.update(),i.setBindGroup(0,n)}},e.drawInstance=function(t,e,i,n,s){var r=e.node.worldTransform;this.modelMatrixId.setValue(r.data),s&&this.normalMatrixId.setValue(e.node.normalMatrix.data);var a=e.instancingData;a?a.count>0&&(this._instancedDrawCalls++,t.setVertexBuffer(a.vertexBuffer),t.draw(i.primitive[n],a.count)):t.draw(i.primitive[n])},e.drawInstance2=function(t,e,i,n){var s=e.instancingData;s?s.count>0&&(this._instancedDrawCalls++,t.draw(i.primitive[n],s.count,!0)):t.draw(i.primitive[n],void 0,!0)},e.cull=function(t,e,i){var n=i.opaque;n.length=0;var s=i.transparent;s.length=0;for(var r=t.frustumCulling,a=e.length,o=0;o<a;o++){var h=e[o];if(h.visible)if(!r||!h.cull||h._isVisible(t))h.visibleThisFrame=!0,(h.transparent?s:n).push(h),(h.skinInstance||h.morphInstance)&&this.processingMeshInstances.add(h)}},e.collectLights=function(t){this.lights.length=0,this.localLights.length=0;for(var e=this.scene._stats,i=t.layerList.length,n=0;n<i;n++){var s=t.layerList[n];if(!fc.has(s)){fc.add(s);for(var r=s._lights,a=0;a<r.length;a++){var o=r[a];dc.has(o)||(dc.add(o),this.lights.push(o),0!==o._type&&this.localLights.push(o))}}}e.lights=this.lights.length,dc.clear(),fc.clear()},e.cullLights=function(t,e){for(var i=this.scene.clusteredLightingEnabled,n=this.scene.physicalUnits,s=0;s<e.length;s++){var r=e[s];if(r.enabled)if(0!==r._type)if(r.getBoundingSphere(cc),t.frustum.containsSphere(cc)){r.visibleThisFrame=!0,r.usePhysicalUnits=n;var a=t.getScreenSize(cc);r.maxScreenSize=Math.max(r.maxScreenSize,a)}else i||r.castShadows&&!r.shadowMap&&(r.visibleThisFrame=!0);else r.usePhysicalUnits=this.scene.physicalUnits}},e.cullShadowmaps=function(t){for(var e=this.scene.clusteredLightingEnabled,i=0;i<this.localLights.length;i++){var n=this.localLights[i];0!==n._type&&(e?n.atlasSlotUpdated&&0===n.shadowUpdateMode&&(n.shadowUpdateMode=1):0===n.shadowUpdateMode&&n.castShadows&&(n.getRenderData(null,0).shadowCamera.renderTarget||(n.shadowUpdateMode=1)),n.visibleThisFrame&&n.castShadows&&0!==n.shadowUpdateMode&&this._shadowRendererLocal.cull(n,t))}for(var s=t._renderActions,r=0;r<s.length;r++){var a=s[r];a.directionalLights.length=0;var o=a.camera.camera;if(a.firstCameraUse){for(var h=o.layers,l=0;l<h.length;l++){var c=t.getLayerById(h[l]);if(c)for(var u=c.splitLights[0],d=0;d<u.length;d++){var f=u[d];f.castShadows&&!yc.has(f)&&(yc.add(f),a.directionalLights.push(f),this._shadowRendererDirectional.cull(f,t,o))}}yc.clear()}}},e.cullComposition=function(t){this.processingMeshInstances.clear();for(var e=t._renderActions,i=0;i<e.length;i++){var n=e[i],s=n.layerIndex,r=t.layerList[s];if(r.enabled&&t.subLayerEnabled[s]){var a=n.camera;if(a){a.frameUpdate(n.renderTarget),n.firstCameraUse&&(this.updateCameraFrustum(a.camera),this._camerasRendered++),this.cullLights(a.camera,r._lights),r.onPreCull&&r.onPreCull(t.camerasMap.get(a));var o=r.getCulledInstances(a.camera),h=r.meshInstances;this.cull(a.camera,h,o),r.onPostCull&&r.onPostCull(t.camerasMap.get(a))}}}this.scene.clusteredLightingEnabled&&this.updateLightTextureAtlas(),this.cullShadowmaps(t)},e.updateShaders=function(t,e){for(var i=t.length,n=0;n<i;n++){var s=t[n].material;if(s&&!yc.has(s)&&(yc.add(s),s.getShaderVariant!==zo.prototype.getShaderVariant)){if(e&&(!s.useLighting||s.emitter&&!s.emitter.lighting))continue;s.clearVariants()}}yc.clear()},e.beginFrame=function(t){for(var e=this.scene,i=e.updateShaders,n=t.layerList,s=n.length,r=0;r<s;r++)for(var a=n[r].meshInstances,o=a.length,h=0;h<o;h++){var l=a[h];l.visibleThisFrame=!1,i&&xc.push(l),l.skinInstance&&Sc.push(l)}if(i){var c=!e.updateShaders;this.updateShaders(xc,c),e.updateShaders=!1,e._shaderVersion++}this.updateCpuSkinMatrices(Sc),xc.length=0,Sc.length=0;for(var u=this.lights,d=u.length,f=0;f<d;f++)u[f].beginFrame()},e.updateLightTextureAtlas=function(){this.lightTextureAtlas.update(this.localLights,this.scene.lighting)},e.updateClusters=function(t){var e=t._renderActions;this.worldClustersAllocator.update(e,this.scene.gammaCorrection,this.scene.lighting)},e.updateLayerComposition=function(t,e){for(var i=t.layerList.length,n=0;n<i;n++)t.layerList[n]._postRenderCounter=0;for(var s=this.scene._shaderVersion,r=0;r<i;r++){var a=t.layerList[r];a._shaderVersion=s,a._preRenderCalledForCameras=0,a._postRenderCalledForCameras=0;var o=t.subLayerList[r];a._postRenderCounter|=o?2:1,a._postRenderCounterMax=a._postRenderCounter}t._update()},e.frameUpdate=function(){this.clustersDebugRendered=!1,this.initViewBindGroupFormat(this.scene.clusteredLightingEnabled)},t}(),wc=2.399963229728653,Tc=function(t,e,i){var n=e*wc,s=Math.sqrt(e)/Math.sqrt(i);t.x=s*Math.cos(n),t.y=s*Math.sin(n)},Ac=function(t,e,i,n,s){void 0===n&&(n=0),void 0===s&&(s=1),n=1-2*n,s=1-2*s;var r=_t.lerp(n,s,e/i),a=Math.sqrt(1-r*r),o=wc*e;t.x=Math.cos(o)*a,t.y=r,t.z=Math.sin(o)*a},Cc=function(t){var e=(t<<16|t>>>16)>>>0;return 2.3283064365386963e-10*(e=((16711935&(e=((252645135&(e=((858993459&(e=((1431655765&e)<<1|(2863311530&e)>>>1)>>>0))<<2|(3435973836&e)>>>2)>>>0))<<4|(4042322160&e)>>>4)>>>0))<<8|(4278255360&e)>>>8)>>>0)},Ec=function(t){switch(t){case ui:return"Cubemap";case fi:return"Octahedral";default:return"Equirect"}},Mc=function(t,e,i){if(t<=0)e[i+0]=0,e[i+1]=0,e[i+2]=0,e[i+3]=0;else if(t>=1)e[i+0]=255,e[i+1]=0,e[i+2]=0,e[i+3]=0;else{var n=1*t%1,s=255*t%1,r=65025*t%1,a=16581375*t%1;n-=s/255,s-=r/255,r-=a/255,e[i+0]=Math.min(255,Math.floor(256*n)),e[i+1]=Math.min(255,Math.floor(256*s)),e[i+2]=Math.min(255,Math.floor(256*r)),e[i+3]=Math.min(255,Math.floor(256*a))}},Pc=function(t,e,i,n){var s=2*i*Math.PI,r=Math.pow(1-e,1/(n+1)),a=Math.sqrt(1-r*r);t.set(Math.cos(s)*a,Math.sin(s)*a,r).normalize()},Rc=function(t,e,i){var n=2*i*Math.PI,s=Math.sqrt(1-e),r=Math.sqrt(e);t.set(Math.cos(n)*r,Math.sin(n)*r,s).normalize()},Ic=function(t,e,i,n){var s=2*i*Math.PI,r=Math.sqrt((1-e)/(1+(n*n-1)*e)),a=Math.sqrt(1-r*r);t.set(Math.cos(s)*a,Math.sin(s)*a,r).normalize()},Lc=function(t,e){var i=t*e,n=e/(1-t*t+i*i);return n*n*(1/Math.PI)},Dc={16:{2:26,8:20,32:17,128:16,512:16},32:{2:53,8:40,32:34,128:32,512:32},128:{2:214,8:163,32:139,128:130,512:128},1024:{2:1722,8:1310,32:1114,128:1041,512:1025}},Oc=function(t,e,i){for(var n=i/t,s=1-Math.log2(e)/11,r=s*s,a=new wt,o=new wt,h=new wt(0,0,1),l=[],c=function(t,e){var i=Dc[t];return i&&i[e]||t}(t,e),u=0;u<c;++u){Ic(a,u/c,Cc(u),r);var d=a.z;if(o.set(a.x,a.y,a.z).mulScalar(2*d).sub(h),o.z>0){var f=Lc(Math.min(1,d),r)/4+.001,p=.5*Math.log2(n/f);l.push(o.x,o.y,o.z,p)}}for(;l.length<4*t;)l.push(0,0,0,0);return l},kc=function(t,e,i){var n=function(t){for(var e=t.length,i=Math.min(e,512),n=Math.ceil(e/i),s=new Uint8Array(i*n*4),r=0,a=0;a<e;a+=4)Mc(.5*t[a+0]+.5,s,r+0),Mc(.5*t[a+1]+.5,s,r+4),Mc(.5*t[a+2]+.5,s,r+8),Mc(t[a+3]/8,s,r+12),r+=16;return{width:i,height:n,data:s}}(i);return new Ls(t,{name:e,width:n.width,height:n.height,mipmaps:!1,minFilter:0,magFilter:0,levels:[n.data]})},Fc=function(){function t(t){void 0===t&&(t=!0),this.map=new Map,this.destroyContent=t}var e=t.prototype;return e.destroy=function(){this.destroyContent&&this.map.forEach((function(t,e){t.destroy()}))},e.get=function(t,e){if(!this.map.has(t)){var i=e();return this.map.set(t,i),i}return this.map.get(t)},t}(),Bc=new Fc(!1),Uc=new Bs,Nc=function(t,e,i){return Uc.get(t,(function(){return new Fc})).get(e,(function(){return kc(t,e,Bc.get(e,i))}))},zc=function(t,e,i){return Nc(t,"lambert-samples-"+e+"-"+i,(function(){return function(t,e){for(var i=e/t,n=new wt,s=[],r=0;r<t;++r){Rc(n,r/t,Cc(r));var a=n.z/Math.PI,o=.5*Math.log2(i/a);s.push(n.x,n.y,n.z,o)}return s}(e,i)}))},Vc=function(t,e,i){return Nc(t,"phong-samples-"+e+"-"+i,(function(){return function(t,e){for(var i=new wt,n=[],s=0;s<t;++s)Pc(i,s/t,Cc(s),e),n.push(i.x,i.y,i.z,0);return n}(e,i)}))};function Gc(t,e,i){var n;void 0===i&&(i={}),t instanceof nn&&(t=arguments[1],e=arguments[2],i={},void 0!==arguments[3]&&(i.specularPower=arguments[3]),void 0!==arguments[4]&&(i.numSamples=arguments[4]));var s=i.hasOwnProperty("specularPower")?i.specularPower:1,r=i.hasOwnProperty("face")?i.face:null,a=i.hasOwnProperty("distribution")?i.distribution:1===s?"none":"phong",o={none:"reproject",lambert:"prefilterSamplesUnweighted",phong:"prefilterSamplesUnweighted",ggx:"prefilterSamples"}[a]||"reproject",h=o.startsWith("prefilterSamples"),l=Yh.decodeFunc(t.encoding),c=Yh.encodeFunc(e.encoding),u="sample"+Ec(t.projection),d="getDirection"+Ec(e.projection),f=i.hasOwnProperty("numSamples")?i.numSamples:1024,p=o+"_"+l+"_"+c+"_"+u+"_"+d+"_"+f,m=t.device,_=go(m).getCachedShader(p);_||(_=bo(m,"\nattribute vec2 vertex_position;\n\nuniform vec4 uvMod;\n\nvarying vec2 vUv0;\n\nvoid main(void) {\n gl_Position = vec4(vertex_position, 0.5, 1.0);\n vUv0 = getImageEffectUV((vertex_position.xy * 0.5 + 0.5) * uvMod.xy + uvMod.zw);\n}\n","#define PROCESS_FUNC "+o+"\n"+(h?"#define USE_SAMPLES_TEX\n":"")+(t.cubemap?"#define CUBEMAP_SOURCE\n":"")+"#define DECODE_FUNC "+l+"\n#define ENCODE_FUNC "+c+"\n#define SOURCE_FUNC "+u+"\n#define TARGET_FUNC "+d+"\n#define NUM_SAMPLES "+f+"\n#define NUM_SAMPLES_SQRT "+Math.round(Math.sqrt(f)).toFixed(1)+"\n"+"\n"+_o.reprojectPS,p));m.setBlendState(Ui.NOBLEND),m.scope.resolve(t.cubemap?"sourceCube":"sourceTex").setValue(t);var v=m.scope.resolve("params"),g=m.scope.resolve("params2"),y=m.scope.resolve("uvMod");if(null!=(n=i)&&n.seamPixels){var x=i.seamPixels,S=(i.rect?i.rect.z:e.width)-2*x,b=(i.rect?i.rect.w:e.height)-2*x;y.setValue([(S+2*x)/S,(b+2*x)/b,-x/S,-x/b])}else y.setValue([1,1,0,0]);var w=[0,s,t.fixCubemapSeams?1/t.width:0,e.fixCubemapSeams?1/e.width:0],T=[e.width*e.height*(e.cubemap?6:1),t.width*t.height*(t.cubemap?6:1)];if(h){var A=t.width*t.height*(t.cubemap?6:1),C="ggx"===a?function(t,e,i,n){return Nc(t,"ggx-samples-"+e+"-"+i+"-"+n,(function(){return Oc(e,i,n)}))}(m,f,s,A):"lambert"===a?zc(m,f,A):Vc(m,f,s);m.scope.resolve("samplesTex").setValue(C),m.scope.resolve("samplesTexInverseSize").setValue([1/C.width,1/C.height])}for(var E=0;E<(e.cubemap?6:1);E++)if(null===r||E===r){var M,P=new rn({colorBuffer:e,face:E,depth:!1,flipY:m.isWebGPU});w[0]=E,v.setValue(w),g.setValue(T),Ro(m,P,_,null==(M=i)?void 0:M.rect),P.destroy()}}var Hc=function(t,e){return void 0===e&&(e=0),1+Math.floor(Math.log2(Math.max(t,e)))},Wc=function(){function t(){}return t.generateSkyboxCubemap=function(t,e){var i=function(t,e,i,n){return new Ls(t,{name:"lighting-"+e,cubemap:!0,width:e,height:e,format:i,type:7===i?si:ei,addressU:1,addressV:1,fixCubemapSeams:!0,mipmaps:!!n})}(t.device,e||(t.cubemap?t.width:t.width/4),7,!1);return Gc(t,i,{numSamples:1024}),i},t.generateLightingSource=function(t,e){var i=t.device,n=function(t){return function(t){return t.extTextureHalfFloat&&t.textureHalfFloatRenderable}(t)?oe:function(t){return t.extTextureFloat&&t.textureFloatRenderable}(t)?le:7}(i),s=(null==e?void 0:e.target)||new Ls(i,{name:"lighting-source",cubemap:!0,width:(null==e?void 0:e.size)||128,height:(null==e?void 0:e.size)||128,format:n,type:7===n?si:ei,addressU:1,addressV:1,fixCubemapSeams:!1,mipmaps:!0});return Gc(t,s,{numSamples:t.mipmaps?1:1024}),s},t.generateAtlas=function(t,e){for(var i=t.device,n=(null==e?void 0:e.target)||new Ls(i,{name:"envAtlas",width:(null==e?void 0:e.size)||512,height:(null==e?void 0:e.size)||512,format:7,type:si,projection:di,addressU:1,addressV:1,mipmaps:!1}),s=n.width/512,r=new Pt(0,0,512*s,256*s),a=Hc(256)-Hc(4),o=0;o<a;++o)Gc(t,n,{numSamples:1,rect:r,seamPixels:s}),r.x+=r.w,r.y+=r.w,r.z=Math.max(1,Math.floor(.5*r.z)),r.w=Math.max(1,Math.floor(.5*r.w));r.set(0,256*s,256*s,128*s);for(var h=1;h<7;++h)Gc(t,n,{numSamples:(null==e?void 0:e.numReflectionSamples)||1024,distribution:(null==e?void 0:e.distribution)||"ggx",specularPower:Math.max(1,2048>>2*h),rect:r,seamPixels:s}),r.y+=r.w,r.z=Math.max(1,Math.floor(.5*r.z)),r.w=Math.max(1,Math.floor(.5*r.w));return r.set(128*s,384*s,64*s,32*s),Gc(t,n,{numSamples:(null==e?void 0:e.numAmbientSamples)||2048,distribution:"lambert",rect:r,seamPixels:s}),n},t.generatePrefilteredAtlas=function(t,e){for(var i=t[0].device,n=t[0].format,s=t[0].type,r=(null==e?void 0:e.target)||new Ls(i,{name:"envPrefilteredAtlas",width:(null==e?void 0:e.size)||512,height:(null==e?void 0:e.size)||512,format:n,type:s,projection:di,addressU:1,addressV:1,mipmaps:!1}),a=r.width/512,o=new Pt(0,0,512*a,256*a),h=Hc(512),l=0;l<h;++l)Gc(t[0],r,{numSamples:1,rect:o,seamPixels:a}),o.x+=o.w,o.y+=o.w,o.z=Math.max(1,Math.floor(.5*o.z)),o.w=Math.max(1,Math.floor(.5*o.w));o.set(0,256*a,256*a,128*a);for(var c=1;c<t.length;++c)Gc(t[c],r,{numSamples:1,rect:o,seamPixels:a}),o.y+=o.w,o.z=Math.max(1,Math.floor(.5*o.z)),o.w=Math.max(1,Math.floor(.5*o.w));return o.set(128*a,384*a,64*a,32*a),null!=e&&e.legacyAmbient?Gc(t[5],r,{numSamples:1,rect:o,seamPixels:a}):Gc(t[0],r,{numSamples:(null==e?void 0:e.numSamples)||2048,distribution:"lambert",rect:o,seamPixels:a}),r},t}(),Xc=function(){function t(){this.forceUv1=!1,this.ambientTint=!1,this.diffuseTint=!1,this.specularTint=!1,this.metalnessTint=!1,this.glossTint=!1,this.emissiveTint=!1,this.opacityTint=!1,this.emissiveEncoding="linear",this.lightMapEncoding="linear",this.packedNormal=!1,this.glossInvert=!1,this.sheenGlossInvert=!1,this.clearCoatGlossInvert=!1,this.litOptions=new Hh}return y(t,[{key:"pass",get:function(){return this.litOptions.pass}}]),t}(),jc=[],qc=function(t){return Object.keys(t).filter((function(t){return"litOptions"!==t})).sort()},Yc=function(t){function e(){for(var e,i=arguments.length,n=new Array(i),s=0;s<i;s++)n[s]=arguments[s];return(e=t.call.apply(t,[this].concat(n))||this).optionsContext=new Xc,e.optionsContextMin=new Xc,e}S(e,t);var i=e.prototype;return i.generateKey=function(t){var e;return t===this.optionsContextMin?(this.propsMin||(this.propsMin=qc(t)),e=this.propsMin):t===this.optionsContext?(this.props||(this.props=qc(t)),e=this.props):e=qc(t),"standard:\n"+e.map((function(e){return e+t[e]})).join("\n")+fl.generateKey(t.litOptions)},i._getUvSourceExpression=function(t,e,i){var n,s=i[t],r=i[e],a=0===i.litOptions.pass||1===i.litOptions.pass;return a&&1===i.litOptions.nineSlicedMode||a&&2===i.litOptions.nineSlicedMode?n="nineSlicedUv":(n=0===s?"vUv"+r:"vUV"+r+"_"+s,i.heightMap&&"heightMapTransform"!==t&&(n+=" + dUvOffset")),n},i._addMapDef=function(t,e){return e?"#define "+t+"\n":"#undef "+t+"\n"},i._addMapDefs=function(t,e,i,n,s){return this._addMapDef("MAPFLOAT",t)+this._addMapDef("MAPCOLOR",e)+this._addMapDef("MAPVERTEX",i)+this._addMapDef("MAPTEXTURE",n)+this._addMapDef("MAPINVERT",s)},i._addMap=function(t,e,i,n,s,r){void 0===r&&(r=null);var a=t+"Map",o=a+"Uv",h=a+"Identifier",l=a+"Transform",c=a+"Channel",u=t+"VertexColorChannel",d=t+"VertexColor",f=t+"Mode",p=t+"Invert",m=i[t+"Tint"],_=i[d],v=i[a],g=i[h],y=i[f],x=n[e];if(v){var S=this._getUvSourceExpression(l,o,i);if(x=x.replace(/\$UV/g,S).replace(/\$CH/g,i[c]),s&&-1!==x.search(/\$SAMPLER/g)){var b="texture_"+a,w=s[g];w?b=w:s[g]=b,x=x.replace(/\$SAMPLER/g,b)}if(r&&(x="aaa"===i[c]?x.replace(/\$DECODE/g,"passThrough"):x.replace(/\$DECODE/g,Yh.decodeFunc(i.litOptions.gamma||"srgb"!==r?r:"linear"))).indexOf("$texture2DSAMPLE")){x=x.replace(/\$texture2DSAMPLE/g,{linear:"texture2D",srgb:"texture2DSRGB",rgbm:"texture2DRGBM",rgbe:"texture2DRGBE"}[r]||"texture2D")}}_&&(x=x.replace(/\$VC/g,i[u])),y&&(x=x.replace(/\$DETAILMODE/g,y));var T=!!(1&m),A=!!(2&m),C=!!i[p];return(x=this._addMapDefs(T,A,_,v,C)+x).replace(/\$/g,"")},i._correctChannel=function(t,e,i){if(i[t]>0){if(i[t]<e.length)return e.substring(0,i[t]);if(i[t]>e.length){for(var n=e,s=n.charAt(n.length-1),r=i[t]-n.length,a=0;a<r;a++)n+=s;return n}return e}},i.createShaderDefinition=function(t,e){var i=Do.get(t).getByIndex(e.litOptions.pass).isForward,n=new dl(t,e.litOptions),s=[],r=[],a=[],o={};for(var h in jc){var l=h+"Map";if(e[h+"VertexColor"]){var c=h+"VertexColorChannel";e[c]=this._correctChannel(h,e[c],jc)}if(e[l]){var u=l+"Channel",d=l+"Transform",f=l+"Uv";e[f]=Math.min(e[f],1),e[u]=this._correctChannel(h,e[u],jc);var p=e[f];s[p]=!0,r[p]=r[p]||e[l]&&!e[d],e[d]&&a.push({name:h,id:e[d],uv:e[f]})}}e.forceUv1&&(s[1]=!0,r[1]=void 0===r[1]||r[1]),n.generateVertexShader(s,r,a),0===e.litOptions.shadingModel?(e.litOptions.fresnelModel=0,e.litOptions.ambientSH=!1):e.litOptions.fresnelModel=0===e.litOptions.fresnelModel?2:e.litOptions.fresnelModel;var m=new Xh,_=new Xh,v=new Xh,g=new Xh,y="";if(2===e.litOptions.nineSlicedMode?m.append("const float textureBias = -1000.0;"):m.append("uniform float textureBias;"),i){if(e.heightMap&&(m.append("vec2 dUvOffset;"),_.append(this._addMap("height","parallaxPS",e,n.chunks,o)),v.append("getParallax();")),3!==e.litOptions.blendType||e.litOptions.alphaTest||e.litOptions.alphaToCoverage?(m.append("float dAlpha;"),_.append(this._addMap("opacity","opacityPS",e,n.chunks,o)),v.append("getOpacity();"),g.append("litArgs_opacity = dAlpha;"),e.litOptions.alphaTest&&(_.append(n.chunks.alphaTestPS),v.append("alphaTest(dAlpha);"))):m.append("float dAlpha = 1.0;"),n.needsNormal){if((e.normalMap||e.clearCoatNormalMap)&&(_.append(e.packedNormal?n.chunks.normalXYPS:n.chunks.normalXYZPS),!e.litOptions.hasTangents)){var x=e.normalMap?"normalMap":"clearCoatNormalMap";y=this._getUvSourceExpression(x+"Transform",x+"Uv",e)}m.append("vec3 dNormalW;"),_.append(this._addMap("normalDetail","normalDetailMapPS",e,n.chunks,o)),_.append(this._addMap("normal","normalMapPS",e,n.chunks,o)),v.append("getNormal();"),g.append("litArgs_worldNormal = dNormalW;")}if(n.needsSceneColor&&m.append("uniform sampler2D uSceneColorMap;"),n.needsScreenSize&&m.append("uniform vec4 uScreenSize;"),n.needsTransforms&&(m.append("uniform mat4 matrix_viewProjection;"),m.append("uniform mat4 matrix_model;")),(e.diffuseDetail||e.aoDetail)&&_.append(n.chunks.detailModesPS),m.append("vec3 dAlbedo;"),e.diffuseDetail&&_.append(this._addMap("diffuseDetail","diffuseDetailMapPS",e,n.chunks,o,e.diffuseDetailEncoding)),_.append(this._addMap("diffuse","diffusePS",e,n.chunks,o,e.diffuseEncoding)),v.append("getAlbedo();"),g.append("litArgs_albedo = dAlbedo;"),e.litOptions.useRefraction&&(m.append("float dTransmission;"),_.append(this._addMap("refraction","transmissionPS",e,n.chunks,o)),v.append("getRefraction();"),g.append("litArgs_transmission = dTransmission;"),m.append("float dThickness;"),_.append(this._addMap("thickness","thicknessPS",e,n.chunks,o)),v.append("getThickness();"),g.append("litArgs_thickness = dThickness;")),e.litOptions.useIridescence&&(m.append("float dIridescence;"),_.append(this._addMap("iridescence","iridescencePS",e,n.chunks,o)),v.append("getIridescence();"),g.append("litArgs_iridescence_intensity = dIridescence;"),m.append("float dIridescenceThickness;"),_.append(this._addMap("iridescenceThickness","iridescenceThicknessPS",e,n.chunks,o)),v.append("getIridescenceThickness();"),g.append("litArgs_iridescence_thickness = dIridescenceThickness;")),n.lighting&&e.litOptions.useSpecular||n.reflections?(m.append("vec3 dSpecularity;"),m.append("float dGlossiness;"),e.litOptions.useSheen&&(m.append("vec3 sSpecularity;"),_.append(this._addMap("sheen","sheenPS",e,n.chunks,o,e.sheenEncoding)),v.append("getSheen();"),g.append("litArgs_sheen_specularity = sSpecularity;"),m.append("float sGlossiness;"),_.append(this._addMap("sheenGloss","sheenGlossPS",e,n.chunks,o)),v.append("getSheenGlossiness();"),g.append("litArgs_sheen_gloss = sGlossiness;")),e.litOptions.useMetalness&&(m.append("float dMetalness;"),_.append(this._addMap("metalness","metalnessPS",e,n.chunks,o)),v.append("getMetalness();"),g.append("litArgs_metalness = dMetalness;"),m.append("float dIor;"),_.append(this._addMap("ior","iorPS",e,n.chunks,o)),v.append("getIor();"),g.append("litArgs_ior = dIor;")),e.litOptions.useSpecularityFactor&&(m.append("float dSpecularityFactor;"),_.append(this._addMap("specularityFactor","specularityFactorPS",e,n.chunks,o)),v.append("getSpecularityFactor();"),g.append("litArgs_specularityFactor = dSpecularityFactor;")),e.useSpecularColor?_.append(this._addMap("specular","specularPS",e,n.chunks,o,e.specularEncoding)):_.append("void getSpecularity() { dSpecularity = vec3(1); }"),_.append(this._addMap("gloss","glossPS",e,n.chunks,o)),v.append("getGlossiness();"),v.append("getSpecularity();"),g.append("litArgs_specularity = dSpecularity;"),g.append("litArgs_gloss = dGlossiness;")):(m.append("vec3 dSpecularity = vec3(0.0);"),m.append("float dGlossiness = 0.0;")),e.aoDetail&&_.append(this._addMap("aoDetail","aoDetailMapPS",e,n.chunks,o)),(e.aoMap||e.aoVertexColor)&&(m.append("float dAo;"),_.append(this._addMap("ao","aoPS",e,n.chunks,o)),v.append("getAO();"),g.append("litArgs_ao = dAo;")),m.append("vec3 dEmission;"),_.append(this._addMap("emissive","emissivePS",e,n.chunks,o,e.emissiveEncoding)),v.append("getEmission();"),g.append("litArgs_emission = dEmission;"),e.litOptions.useClearCoat&&(m.append("float ccSpecularity;"),m.append("float ccGlossiness;"),m.append("vec3 ccNormalW;"),_.append(this._addMap("clearCoat","clearCoatPS",e,n.chunks,o)),_.append(this._addMap("clearCoatGloss","clearCoatGlossPS",e,n.chunks,o)),_.append(this._addMap("clearCoatNormal","clearCoatNormalPS",e,n.chunks,o)),v.append("getClearCoat();"),v.append("getClearCoatGlossiness();"),v.append("getClearCoatNormal();"),g.append("litArgs_clearcoat_specularity = ccSpecularity;"),g.append("litArgs_clearcoat_gloss = ccGlossiness;"),g.append("litArgs_clearcoat_worldNormal = ccNormalW;")),e.lightMap||e.lightVertexColor){var S=e.dirLightMap&&e.litOptions.useSpecular,b=S?"lightmapDirPS":"lightmapSinglePS";m.append("vec3 dLightmap;"),S&&m.append("vec3 dLightmapDir;"),_.append(this._addMap("light",b,e,n.chunks,o,e.lightMapEncoding)),v.append("getLightMap();"),g.append("litArgs_lightmap = dLightmap;"),S&&g.append("litArgs_lightmapDir = dLightmapDir;")}-1===_.code.indexOf("texture2DSRGB")&&-1===_.code.indexOf("texture2DRGBM")&&-1===_.code.indexOf("texture2DRGBE")||_.prepend(n.chunks.textureSamplePS)}else e.litOptions.alphaTest&&(m.append("float dAlpha;"),_.append(this._addMap("opacity","opacityPS",e,n.chunks,o)),_.append(n.chunks.alphaTestPS),v.append("getOpacity();"),v.append("alphaTest(dAlpha);"),g.append("litArgs_opacity = dAlpha;"));for(var w in m.append(n.chunks.litShaderArgsPS),_.append("void evaluateFrontend() { \n"+v.code+"\n"+g.code+"\n }\n"),v.code="evaluateFrontend();",o)m.append("uniform sampler2D "+o[w]+";");return v.code="\n"+v.code.split("\n").map((function(t){return" "+t})).join("\n")+"\n\n",n.generateFragmentShader(m.code,_.code,v.code,y),n.getDefinition()},e}(xo),Kc=new Yc,Zc=function(t,e){if(t.length!==e.length)return!1;for(var i=0;i<t.length;++i)if(t[i]!==e[i])return!1;return!0},Qc=function(t){return 1!==t.r||1!==t.g||1!==t.b},$c=function(){function t(){this._mapXForms=null}var e=t.prototype;return e.updateMinRef=function(t,e,i,n,s,r){this._updateSharedOptions(t,e,i,n,s),this._updateMinOptions(t,i),this._updateUVOptions(t,i,n,!0)},e.updateRef=function(t,e,i,n,s,r){this._updateSharedOptions(t,e,i,n,s),this._updateEnvOptions(t,i,e),this._updateMaterialOptions(t,i),1===s&&(t.litOptions.gamma&&(t.litOptions.gamma=3),t.litOptions.toneMap=0),t.litOptions.hasTangents=n&&0!=(n&Ba),this._updateLightOptions(t,e,i,n,r),this._updateUVOptions(t,i,n,!1)},e._updateSharedOptions=function(t,e,i,n,s){t.forceUv1=i.forceUv1,i.userAttributes&&(t.litOptions.userAttributes=Object.fromEntries(i.userAttributes.entries())),t.litOptions.chunks=i.chunks||{},t.litOptions.pass=s,t.litOptions.alphaTest=i.alphaTest>0,t.litOptions.blendType=i.blendType,t.litOptions.screenSpace=n&&0!=(n&Fa),t.litOptions.skin=n&&0!=(2&n),t.litOptions.useInstancing=n&&0!=(n&Oa),t.litOptions.useMorphPosition=n&&0!=(n&Ua),t.litOptions.useMorphNormal=n&&0!=(n&Na),t.litOptions.useMorphTextureBased=n&&0!=(n&za),t.litOptions.nineSlicedMode=i.nineSlicedMode||0,e.clusteredLightingEnabled&&i.useLighting?(t.litOptions.clusteredLightingEnabled=!0,t.litOptions.clusteredLightingCookiesEnabled=e.lighting.cookiesEnabled,t.litOptions.clusteredLightingShadowsEnabled=e.lighting.shadowsEnabled,t.litOptions.clusteredLightingShadowType=e.lighting.shadowType,t.litOptions.clusteredLightingAreaLightsEnabled=e.lighting.areaLightsEnabled):(t.litOptions.clusteredLightingEnabled=!1,t.litOptions.clusteredLightingCookiesEnabled=!1,t.litOptions.clusteredLightingShadowsEnabled=!1,t.litOptions.clusteredLightingAreaLightsEnabled=!1)},e._updateUVOptions=function(t,e,i,n){var s=!1,r=!1,a=!1;i&&(s=0!=(4&i),r=0!=(8&i),a=0!=(16&i)),t.litOptions.vertexColors=!1,this._mapXForms=[];var o={};for(var h in jc)this._updateTexOptions(t,e,h,s,r,a,n,o);this._mapXForms=null,t.litOptions.lightMapEnabled=t.lightMap,t.litOptions.dirLightMapEnabled=t.dirLightMap,t.litOptions.useHeights=t.heightMap,t.litOptions.useNormals=t.normalMap,t.litOptions.useClearCoatNormals=t.clearCoatNormalMap,t.litOptions.useAo=t.aoMap||t.aoVertexColor,t.litOptions.diffuseMapEnabled=t.diffuseMap},e._updateTexOptions=function(t,e,i,n,s,r,a,o){var h="opacity"===i;if(!a||h){var l=i+"Map",c=i+"VertexColor",u=i+"VertexColorChannel",d=l+"Channel",f=l+"Transform",p=l+"Uv",m=l+"Identifier";if("light"!==i&&(t[l]=!1,t[m]=void 0,t[d]="",t[f]=0,t[p]=0),t[c]=!1,t[u]="",h&&3===e.blendType&&0===e.alphaTest&&!e.alphaToCoverage)return;if("height"!==i&&e[c]&&r&&(t[c]=e[c],t[u]=e[u],t.litOptions.vertexColors=!0),e[l]){var _=!0;if(0!==e[p]||n||(_=!1),1!==e[p]||s||(_=!1),_){var v=e[l].id,g=o[v];void 0===g&&(o[v]=i,g=i),t[l]=!!e[l],t[m]=g,t[f]=this._getMapTransformID(e.getUniform(f),e[p]),t[d]=e[d],t[p]=e[p]}}}},e._updateMinOptions=function(t,e){t.opacityTint=1!==e.opacity&&3!==e.blendType,t.litOptions.lights=[]},e._updateMaterialOptions=function(t,e){var i,n,s,r,a,o=(e.diffuseTint||!e.diffuseMap&&!e.diffuseVertexColor)&&Qc(e.diffuse),h=!!(e.useMetalness||e.specularMap||e.sphereMap||e.cubeMap||(a=e.specular,0!==a.r||0!==a.g||0!==a.b)||e.specularityFactor>0&&e.useMetalness||e.enableGGXSpecular||e.clearCoat>0),l=!e.useMetalness||e.useMetalnessSpecularColor,c=h&&(e.specularTint||!e.specularMap&&!e.specularVertexColor)&&Qc(e.specular),u=h&&e.useMetalnessSpecularColor&&(e.specularityFactorTint||e.specularityFactor<1&&!e.specularityFactorMap),d=!e.emissiveMap||Qc(e.emissive)&&e.emissiveTint,f=1!==e.emissiveIntensity,p=!!e.normalMap&&(e.normalMap.format===re||e.normalMap.type===ri);t.opacityTint=1!==e.opacity&&3!==e.blendType?1:0,t.ambientTint=e.ambientTint,t.diffuseTint=o?2:0,t.specularTint=c?2:0,t.specularityFactorTint=u?1:0,t.metalnessTint=e.useMetalness&&e.metalness<1?1:0,t.glossTint=1,t.emissiveTint=(d?2:0)+(f?1:0),t.diffuseEncoding=null==(i=e.diffuseMap)?void 0:i.encoding,t.diffuseDetailEncoding=null==(n=e.diffuseDetailMap)?void 0:n.encoding,t.emissiveEncoding=null==(s=e.emissiveMap)?void 0:s.encoding,t.lightMapEncoding=null==(r=e.lightMap)?void 0:r.encoding,t.packedNormal=p,t.refractionTint=1!==e.refraction?1:0,t.refractionIndexTint=e.refractionIndex!==1/1.5?1:0,t.thicknessTint=e.useDynamicRefraction&&1!==e.thickness?1:0,t.specularEncoding=e.specularEncoding||"linear",t.sheenEncoding=e.sheenEncoding||"linear",t.aoMapUv=e.aoUvSet,t.aoDetail=!!e.aoMap,t.diffuseDetail=!!e.diffuseMap,t.normalDetail=!!e.normalMap,t.diffuseDetailMode=e.diffuseDetailMode,t.aoDetailMode=e.aoDetailMode,t.clearCoatTint=1!==e.clearCoat?1:0,t.clearCoatGloss=!!e.clearCoatGloss,t.clearCoatGlossTint=1!==e.clearCoatGloss?1:0,t.iorTint=e.refractionIndex!==1/1.5?1:0,t.iridescenceTint=1!==e.iridescence?1:0,t.sheenTint=e.useSheen&&Qc(e.sheen)?2:0,t.sheenGlossTint=1,t.glossInvert=e.glossInvert,t.sheenGlossInvert=e.sheenGlossInvert,t.clearCoatGlossInvert=e.clearCoatGlossInvert,t.useSpecularColor=l,t.litOptions.separateAmbient=!1,t.litOptions.useAmbientTint=e.ambientTint,t.litOptions.customFragmentShader=e.customFragmentShader,t.litOptions.pixelSnap=e.pixelSnap,t.litOptions.shadingModel=e.shadingModel,t.litOptions.ambientSH=!!e.ambientSH,t.litOptions.fastTbn=e.fastTbn,t.litOptions.twoSidedLighting=e.twoSidedLighting,t.litOptions.occludeSpecular=e.occludeSpecular,t.litOptions.occludeSpecularFloat=1!==e.occludeSpecularIntensity,t.litOptions.useMsdf=!!e.msdfMap,t.litOptions.msdfTextAttribute=!!e.msdfTextAttribute,t.litOptions.alphaToCoverage=e.alphaToCoverage,t.litOptions.opacityFadesSpecular=e.opacityFadesSpecular,t.litOptions.cubeMapProjection=e.cubeMapProjection,t.litOptions.occludeDirect=e.occludeDirect,t.litOptions.conserveEnergy=e.conserveEnergy&&0!==e.shadingModel,t.litOptions.useSpecular=h,t.litOptions.useSpecularityFactor=(u||!!e.specularityFactorMap)&&e.useMetalnessSpecularColor,t.litOptions.enableGGXSpecular=e.enableGGXSpecular,t.litOptions.fresnelModel=e.fresnelModel,t.litOptions.useRefraction=(e.refraction||!!e.refractionMap)&&(e.useDynamicRefraction||!!t.litOptions.reflectionSource),t.litOptions.useClearCoat=!!e.clearCoat,t.litOptions.useSheen=e.useSheen,t.litOptions.useIridescence=e.useIridescence&&0!==e.iridescence,t.litOptions.useMetalness=e.useMetalness,t.litOptions.useDynamicRefraction=e.useDynamicRefraction},e._updateEnvOptions=function(t,e,i){t.litOptions.fog=e.useFog?i.fog:"none",t.litOptions.gamma=e.useGammaTonemap?i.gammaCorrection:0,t.litOptions.toneMap=e.useGammaTonemap?i.toneMapping:-1,t.litOptions.fixSeams=!!e.cubeMap&&e.cubeMap.fixCubemapSeams;var n=0===e.shadingModel,s=!1;if(e.envAtlas&&e.cubeMap&&!n?(t.litOptions.reflectionSource="envAtlasHQ",t.litOptions.reflectionEncoding=e.envAtlas.encoding,t.litOptions.reflectionCubemapEncoding=e.cubeMap.encoding):e.envAtlas&&!n?(t.litOptions.reflectionSource="envAtlas",t.litOptions.reflectionEncoding=e.envAtlas.encoding):e.cubeMap?(t.litOptions.reflectionSource="cubeMap",t.litOptions.reflectionEncoding=e.cubeMap.encoding):e.sphereMap?(t.litOptions.reflectionSource="sphereMap",t.litOptions.reflectionEncoding=e.sphereMap.encoding):e.useSkybox&&i.envAtlas&&i.skybox&&!n?(t.litOptions.reflectionSource="envAtlasHQ",t.litOptions.reflectionEncoding=i.envAtlas.encoding,t.litOptions.reflectionCubemapEncoding=i.skybox.encoding,s=!0):e.useSkybox&&i.envAtlas&&!n?(t.litOptions.reflectionSource="envAtlas",t.litOptions.reflectionEncoding=i.envAtlas.encoding,s=!0):e.useSkybox&&i.skybox?(t.litOptions.reflectionSource="cubeMap",t.litOptions.reflectionEncoding=i.skybox.encoding,s=!0):(t.litOptions.reflectionSource=null,t.litOptions.reflectionEncoding=null),e.ambientSH&&!n)t.litOptions.ambientSource="ambientSH",t.litOptions.ambientEncoding=null;else{var r=e.envAtlas||(e.useSkybox&&i.envAtlas?i.envAtlas:null);r&&!n?(t.litOptions.ambientSource="envAtlas",t.litOptions.ambientEncoding=r.encoding):(t.litOptions.ambientSource="constant",t.litOptions.ambientEncoding=null)}t.litOptions.skyboxIntensity=s&&(1!==i.skyboxIntensity||i.physicalUnits),t.litOptions.useCubeMapRotation=s&&i._skyboxRotationShaderInclude},e._updateLightOptions=function(t,e,i,n,s){if(t.lightMap=!1,t.lightMapChannel="",t.lightMapUv=0,t.lightMapTransform=0,t.litOptions.lightMapWithoutAmbient=!1,t.dirLightMap=!1,n&&(t.litOptions.noShadow=0!=(1&n),0!=(64&n)&&(t.lightMapEncoding=7===e.lightmapPixelFormat?"rgbm":"linear",t.lightMap=!0,t.lightMapChannel="rgb",t.lightMapUv=1,t.lightMapTransform=0,t.litOptions.lightMapWithoutAmbient=!i.lightMap,0!=(n&ka)&&(t.dirLightMap=!0),0!=(n&Va)&&(t.litOptions.lightMapWithoutAmbient=!1))),i.useLighting){var r=[],a=n?n>>16:1;t.litOptions.lightMaskDynamic=!!(1&a),s&&(Wh.collectLights(0,s[0],r,a),Wh.collectLights(1,s[1],r,a),Wh.collectLights(2,s[2],r,a)),t.litOptions.lights=r}else t.litOptions.lights=[];0===t.litOptions.lights.length&&(t.litOptions.noShadow=!0)},e._getMapTransformID=function(t,e){if(!t)return 0;var i=this._mapXForms[e];i||(i=[],this._mapXForms[e]=i);for(var n=0;n<i.length;n++)if(Zc(i[n][0].value,t[0].value)&&Zc(i[n][1].value,t[1].value))return n+1;return i.push(t)},t}();function Jc(t,e,i){void 0===e&&(e=!0),void 0===i&&(i=!0);var n={};return n[t+"Map"]="texture",n[t+"MapTiling"]="vec2",n[t+"MapOffset"]="vec2",n[t+"MapRotation"]="number",n[t+"MapUv"]="number",e&&(n[t+"MapChannel"]="string",i&&(n[t+"VertexColor"]="boolean",n[t+"VertexColorChannel"]="string")),n}var tu=x({name:"string",chunks:"chunks",mappingFormat:"string",_engine:"boolean",ambient:"rgb",ambientTint:"boolean"},Jc("ao"),Jc("aoDetail",!0,!1),{aoDetailMode:"string",diffuse:"rgb",diffuseTint:"boolean"},Jc("diffuse"),Jc("diffuseDetail",!0,!1),{diffuseDetailMode:"string",specular:"rgb",specularTint:"boolean"},Jc("specular"),{occludeSpecular:"enum:occludeSpecular",specularityFactor:"number",specularityFactorTint:"boolean"},Jc("specularityFactor"),{useMetalness:"boolean",metalness:"number",enableGGXSpecular:"boolean",anisotropy:"number",metalnessTint:"boolean"},Jc("metalness"),{useMetalnessSpecularColor:"boolean",conserveEnergy:"boolean",shininess:"number",gloss:"number",glossInvert:"boolean"},Jc("gloss"),{clearCoat:"number"},Jc("clearCoat"),{clearCoatGloss:"number",clearCoatGlossInvert:"boolean"},Jc("clearCoatGloss"),{clearCoatBumpiness:"number"},Jc("clearCoatNormal",!1),{useSheen:"boolean",sheen:"rgb",sheenTint:"boolean"},Jc("sheen"),{sheenGloss:"number",sheenGlossTint:"boolean",sheenGlossInvert:"boolean"},Jc("sheenGloss"),{fresnelModel:"number",emissive:"rgb",emissiveTint:"boolean"},Jc("emissive"),{emissiveIntensity:"number"},Jc("normal",!1),{bumpiness:"number"},Jc("normalDetail",!1),{normalDetailMapBumpiness:"number"},Jc("height",!0,!1),{heightMapFactor:"number",alphaToCoverage:"boolean",alphaTest:"number",alphaFade:"number",opacity:"number"},Jc("opacity"),{opacityFadesSpecular:"boolean",reflectivity:"number",refraction:"number",refractionTint:"boolean"},Jc("refraction"),{refractionIndex:"number",thickness:"number",thicknessTint:"boolean"},Jc("thickness"),{attenuation:"rgb",attenuationDistance:"number",useDynamicRefraction:"boolean",sphereMap:"texture",cubeMap:"cubemap",cubeMapProjection:"number",cubeMapProjectionBox:"boundingbox",useIridescence:"boolean",iridescence:"number",iridescenceTint:"boolean"},Jc("iridescence"),{iridescenceThicknessTint:"boolean",iridescenceThicknessMin:"number",iridescenceThicknessMax:"number",iridescenceRefractionIndex:"number"},Jc("iridescenceThickness"),Jc("light"),{depthTest:"boolean",depthFunc:"enum:depthFunc",depthWrite:"boolean",depthBias:"number",slopeDepthBias:"number",cull:"enum:cull",blendType:"enum:blendType",shadingModel:"enum:shadingModel",useFog:"boolean",useLighting:"boolean",useSkybox:"boolean",useGammaTonemap:"boolean",envAtlas:"texture",twoSidedLighting:"boolean"}),eu=[];for(var iu in tu){"texture"===tu[iu]&&eu.push(iu)}var nu=[];for(var su in tu){"cubemap"===tu[su]&&nu.push(su)}var ru={aoMapVertexColor:"boolean",diffuseMapTint:"boolean",diffuseMapVertexColor:"boolean",emissiveMapTint:"boolean",emissiveMapVertexColor:"boolean",glossMapVertexColor:"boolean",metalnessMapVertexColor:"boolean",opacityMapVertexColor:"boolean",specularAntialias:"boolean",specularMapTint:"boolean",specularMapVertexColor:"boolean"},au={},ou={},hu=new Set,lu=function(t){function e(){var e;return(e=t.call(this)||this).userAttributes=new Map,e._dirtyShader=!0,e._assetReferences={},e._activeParams=new Set,e._activeLightingParams=new Set,e.shaderOptBuilder=new $c,e.reset(),e}S(e,t);var i=e.prototype;return i.reset=function(){var t=this;Object.keys(au).forEach((function(e){t["_"+e]=au[e].value()})),this._chunks={},this._uniformCache={}},i.copy=function(e){var i=this;for(var n in t.prototype.copy.call(this,e),Object.keys(au).forEach((function(t){i[t]=e[t]})),e._chunks)e._chunks.hasOwnProperty(n)&&(this._chunks[n]=e._chunks[n]);return this},i.setAttribute=function(t,e){this.userAttributes.set(e,t)},i._setParameter=function(t,e){hu.add(t),this.setParameter(t,e)},i._setParameters=function(t){var e=this;t.forEach((function(t){e._setParameter(t.name,t.value)}))},i._processParameters=function(t){var e=this,i=this[t];i.forEach((function(t){hu.has(t)||delete e.parameters[t]})),this[t]=hu,(hu=i).clear()},i._updateMap=function(t){var e=t+"Map",i=this[e];if(i){this._setParameter("texture_"+e,i);var n=e+"Transform",s=this.getUniform(n);s&&this._setParameters(s)}},i._allocUniform=function(t,e){var i=this._uniformCache[t];return i||(i=e(),this._uniformCache[t]=i),i},i.getUniform=function(t,e,i){return ou[t](this,e,i)},i.updateUniforms=function(t,e){var i=this,n=function(n){return i.getUniform(n,t,e)};for(var s in this._setParameter("material_ambient",n("ambient")),this.diffuseMap&&!this.diffuseTint||this._setParameter("material_diffuse",n("diffuse")),this.useMetalness?((!this.metalnessMap||this.metalness<1)&&this._setParameter("material_metalness",this.metalness),this.specularMap&&!this.specularTint||this._setParameter("material_specular",n("specular")),this.specularityFactorMap&&!this.specularityFactorTint||this._setParameter("material_specularityFactor",this.specularityFactor),this.sheenMap&&!this.sheenTint||this._setParameter("material_sheen",n("sheen")),this.sheenGlossMap&&!this.sheenGlossTint||this._setParameter("material_sheenGloss",this.sheenGloss),this._setParameter("material_refractionIndex",this.refractionIndex)):this.specularMap&&!this.specularTint||this._setParameter("material_specular",n("specular")),this.enableGGXSpecular&&this._setParameter("material_anisotropy",this.anisotropy),this.clearCoat>0&&(this._setParameter("material_clearCoat",this.clearCoat),this._setParameter("material_clearCoatGloss",this.clearCoatGloss),this._setParameter("material_clearCoatBumpiness",this.clearCoatBumpiness)),this._setParameter("material_gloss",n("gloss")),this.emissiveMap&&!this.emissiveTint||this._setParameter("material_emissive",n("emissive")),1!==this.emissiveIntensity&&this._setParameter("material_emissiveIntensity",this.emissiveIntensity),this.refraction>0&&this._setParameter("material_refraction",this.refraction),this.useDynamicRefraction&&(this._setParameter("material_thickness",this.thickness),this._setParameter("material_attenuation",n("attenuation")),this._setParameter("material_invAttenuationDistance",0===this.attenuationDistance?0:1/this.attenuationDistance)),this.useIridescence&&(this._setParameter("material_iridescence",this.iridescence),this._setParameter("material_iridescenceRefractionIndex",this.iridescenceRefractionIndex),this._setParameter("material_iridescenceThicknessMin",this.iridescenceThicknessMin),this._setParameter("material_iridescenceThicknessMax",this.iridescenceThicknessMax)),this._setParameter("material_opacity",this.opacity),!1===this.opacityFadesSpecular&&this._setParameter("material_alphaFade",this.alphaFade),this.occludeSpecular&&this._setParameter("material_occludeSpecularIntensity",this.occludeSpecularIntensity),1===this.cubeMapProjection&&this._setParameter(n("cubeMapProjectionBox")),jc)this._updateMap(s);this.ambientSH&&this._setParameter("ambientSH[0]",this.ambientSH),this.normalMap&&this._setParameter("material_bumpiness",this.bumpiness),this.normalMap&&this.normalDetailMap&&this._setParameter("material_normalDetailMapBumpiness",this.normalDetailMapBumpiness),this.heightMap&&this._setParameter("material_heightMapFactor",n("heightMapFactor"));var r=0===this.shadingModel;this.envAtlas&&this.cubeMap&&!r?(this._setParameter("texture_envAtlas",this.envAtlas),this._setParameter("texture_cubeMap",this.cubeMap)):this.envAtlas&&!r?this._setParameter("texture_envAtlas",this.envAtlas):this.cubeMap?this._setParameter("texture_cubeMap",this.cubeMap):this.sphereMap&&this._setParameter("texture_sphereMap",this.sphereMap),this._setParameter("material_reflectivity",this.reflectivity),this._processParameters("_activeParams"),this._dirtyShader&&this.clearVariants()},i.updateEnvUniforms=function(t,e){var i=0===this.shadingModel;!(this.envAtlas&&!i||this.cubeMap||this.sphereMap)&&this.useSkybox&&(e.envAtlas&&e.skybox&&!i?(this._setParameter("texture_envAtlas",e.envAtlas),this._setParameter("texture_cubeMap",e.skybox)):e.envAtlas&&!i?this._setParameter("texture_envAtlas",e.envAtlas):e.skybox&&this._setParameter("texture_cubeMap",e.skybox)),this._processParameters("_activeLightingParams")},i.getShaderVariant=function(t,e,i,n,s,r,a,o,h){this.updateEnvUniforms(t,e);var l=Do.get(t).getByIndex(s),c=2===s||3===s||l.isShadow,u=c?Kc.optionsContextMin:Kc.optionsContext;c?this.shaderOptBuilder.updateMinRef(u,e,this,i,s,r):this.shaderOptBuilder.updateRef(u,e,this,i,s,r),this.onUpdateShader&&(u=this.onUpdateShader(u));var d=new fo(a,o,h),f=go(t);f.register("standard",Kc);var p=f.getProgram("standard",u,d,this.userId);return this._dirtyShader=!1,p},i.destroy=function(){for(var e in this._assetReferences)this._assetReferences[e]._unbind();this._assetReferences=null,t.prototype.destroy.call(this)},y(e,[{key:"shader",get:function(){return null},set:function(t){}},{key:"chunks",get:function(){return this._dirtyShader=!0,this._chunks},set:function(t){this._dirtyShader=!0,this._chunks=t}}]),e}(zo);lu.TEXTURE_PARAMETERS=eu,lu.CUBEMAP_PARAMETERS=nu;var cu=function(t,e){ou[t]=e},uu=function(t,e,i,n){Object.defineProperty(lu.prototype,t,{get:n||function(){return this["_"+t]},set:i}),au[t]={value:e}},du=function(t){return t.defaultValue&&t.defaultValue.clone?function(t){var e="_"+t.name,i=t.dirtyShaderFunc||function(){return!0};uu(t.name,(function(){return t.defaultValue.clone()}),(function(t){var n=this[e];n.equals(t)||(this._dirtyShader=this._dirtyShader||i(n,t),this[e]=n.copy(t))}),t.getterFunc)}(t):function(t){var e="_"+t.name,i=t.dirtyShaderFunc||function(){return!0};uu(t.name,(function(){return t.defaultValue}),(function(t){var n=this[e];n!==t&&(this._dirtyShader=this._dirtyShader||i(n,t),this[e]=t)}),t.getterFunc)}(t)};function fu(t,e,i,n){void 0===e&&(e="rgb"),void 0===i&&(i=!0),void 0===n&&(n=0),jc[t]=e.length||-1,du({name:t+"Map",defaultValue:null,dirtyShaderFunc:function(t,e){return!!t!=!!e||t&&(t.type!==e.type||t.fixCubemapSeams!==e.fixCubemapSeams||t.format!==e.format)}}),du({name:t+"MapTiling",defaultValue:new Et(1,1)}),du({name:t+"MapOffset",defaultValue:new Et(0,0)}),du({name:t+"MapRotation",defaultValue:0}),du({name:t+"MapUv",defaultValue:n}),e&&(du({name:t+"MapChannel",defaultValue:e}),i&&(du({name:t+"VertexColor",defaultValue:!1}),du({name:t+"VertexColorChannel",defaultValue:e})));var s=t+"MapTiling",r=t+"MapOffset",a=t+"MapRotation",o=t+"MapTransform";cu(o,(function(t,e,i){var n=t[s],h=t[r],l=t[a];if(1===n.x&&1===n.y&&0===h.x&&0===h.y&&0===l)return null;var c=t._allocUniform(o,(function(){return[{name:"texture_"+o+"0",value:new Float32Array(3)},{name:"texture_"+o+"1",value:new Float32Array(3)}]})),u=Math.cos(l*_t.DEG_TO_RAD),d=Math.sin(l*_t.DEG_TO_RAD),f=c[0].value;f[0]=u*n.x,f[1]=-d*n.y,f[2]=h.x;var p=c[1].value;return p[0]=d*n.x,p[1]=u*n.y,p[2]=1-n.y-h.y,c}))}function pu(t,e){du({name:t,defaultValue:e,getterFunc:function(){return this._dirtyShader=!0,this["_"+t]}}),cu(t,(function(e,i,n){var s=e._allocUniform(t,(function(){return new Float32Array(3)})),r=e[t];return e.useGammaTonemap&&n.gammaCorrection?(s[0]=Math.pow(r.r,2.2),s[1]=Math.pow(r.g,2.2),s[2]=Math.pow(r.b,2.2)):(s[0]=r.r,s[1]=r.g,s[2]=r.b),s}))}function mu(t,e,i){du({name:t,defaultValue:e,dirtyShaderFunc:function(t,e){return(0===t||1===t)!=(0===e||1===e)}}),cu(t,i)}function _u(t,e){du({name:t,defaultValue:null,dirtyShaderFunc:function(t,e){return!!t==!!e}}),cu(t,e)}function vu(t,e){du({name:t,defaultValue:e})}!function(){pu("ambient",new vt(.7,.7,.7)),pu("diffuse",new vt(1,1,1)),pu("specular",new vt(0,0,0)),pu("emissive",new vt(0,0,0)),pu("sheen",new vt(1,1,1)),pu("attenuation",new vt(1,1,1)),mu("emissiveIntensity",1),mu("specularityFactor",1),mu("sheenGloss",0),mu("gloss",.25,(function(t,e,i){return 0===t.shadingModel?Math.pow(2,11*t.gloss):t.gloss})),mu("heightMapFactor",1,(function(t,e,i){return.025*t.heightMapFactor})),mu("opacity",1),mu("alphaFade",1),mu("alphaTest",0),mu("bumpiness",1),mu("normalDetailMapBumpiness",1),mu("reflectivity",1),mu("occludeSpecularIntensity",1),mu("refraction",0),mu("refractionIndex",1/1.5),mu("thickness",0),mu("attenuationDistance",0),mu("metalness",1),mu("anisotropy",0),mu("clearCoat",0),mu("clearCoatGloss",1),mu("clearCoatBumpiness",1),mu("aoUvSet",0,null),mu("iridescence",0),mu("iridescenceRefractionIndex",1/1.5),mu("iridescenceThicknessMin",0),mu("iridescenceThicknessMax",0),_u("ambientSH"),_u("cubeMapProjectionBox",(function(t,e,i){var n=t._allocUniform("cubeMapProjectionBox",(function(){return[{name:"envBoxMin",value:new Float32Array(3)},{name:"envBoxMax",value:new Float32Array(3)}]})),s=t.cubeMapProjectionBox.getMin(),r=n[0].value;r[0]=s.x,r[1]=s.y,r[2]=s.z;var a=t.cubeMapProjectionBox.getMax(),o=n[1].value;return o[0]=a.x,o[1]=a.y,o[2]=a.z,n})),vu("ambientTint",!1),vu("diffuseTint",!1),vu("specularTint",!1),vu("specularityFactorTint",!1),vu("emissiveTint",!1),vu("fastTbn",!1),vu("useMetalness",!1),vu("useMetalnessSpecularColor",!1),vu("useSheen",!1),vu("enableGGXSpecular",!1),vu("occludeDirect",!1),vu("normalizeNormalMap",!0),vu("conserveEnergy",!0),vu("opacityFadesSpecular",!0),vu("occludeSpecular",1),vu("shadingModel",1),vu("fresnelModel",2),vu("useDynamicRefraction",!1),vu("cubeMapProjection",0),vu("customFragmentShader",null),vu("useFog",!0),vu("useLighting",!0),vu("useGammaTonemap",!0),vu("useSkybox",!0),vu("forceUv1",!1),vu("pixelSnap",!1),vu("twoSidedLighting",!1),vu("nineSlicedMode",void 0),vu("msdfTextAttribute",!1),vu("useIridescence",!1),vu("glossInvert",!1),vu("sheenGlossInvert",!1),vu("clearCoatGlossInvert",!1),fu("diffuse"),fu("specular"),fu("emissive"),fu("thickness","g"),fu("specularityFactor","g"),fu("normal",""),fu("metalness","g"),fu("gloss","g"),fu("opacity","a"),fu("refraction","g"),fu("height","g",!1),fu("ao","g"),fu("light","rgb",!0,1),fu("msdf",""),fu("diffuseDetail","rgb",!1),fu("normalDetail",""),fu("aoDetail","g",!1),fu("clearCoat","g"),fu("clearCoatGloss","g"),fu("clearCoatNormal",""),fu("sheen","rgb"),fu("sheenGloss","g"),fu("iridescence","g"),fu("iridescenceThickness","g"),vu("diffuseDetailMode",Da),vu("aoDetailMode",Da),_u("cubeMap"),_u("sphereMap"),_u("envAtlas");var t=[null,null,null,null,null,null];uu("prefilteredCubemaps",(function(){return t.slice()}),(function(t){var e=this._prefilteredCubemaps;t=t||[];for(var i=!1,n=!0,s=0;s<6;++s){var r=t[s]||null;e[s]!==r&&(e[s]=r,i=!0),n=n&&!!e[s]}i&&(n?this.envAtlas=Wc.generatePrefilteredAtlas(e,{target:this.envAtlas}):this.envAtlas&&(this.envAtlas.destroy(),this.envAtlas=null),this._dirtyShader=!0)}),(function(){return this._prefilteredCubemaps}))}(),new wt(1,1,1),new wt(40,0,0);var gu={drawCalls:[],shaderInstances:[],isNewMaterial:[],lightMaskChanged:[],clear:function(){this.drawCalls.length=0,this.shaderInstances.length=0,this.isNewMaterial.length=0,this.lightMaskChanged.length=0}};var yu=function(t){function e(e){var i,n=(i=t.call(this,e)||this).device;i._forwardDrawCalls=0,i._materialSwitches=0,i._depthMapTime=0,i._forwardTime=0,i._sortTime=0;var s=n.scope;return i.fogColorId=s.resolve("fog_color"),i.fogStartId=s.resolve("fog_start"),i.fogEndId=s.resolve("fog_end"),i.fogDensityId=s.resolve("fog_density"),i.ambientId=s.resolve("light_globalAmbient"),i.skyboxIntensityId=s.resolve("skyboxIntensity"),i.cubeMapRotationMatrixId=s.resolve("cubeMapRotationMatrix"),i.pcssDiskSamplesId=s.resolve("pcssDiskSamples[0]"),i.pcssSphereSamplesId=s.resolve("pcssSphereSamples[0]"),i.lightColorId=[],i.lightDir=[],i.lightDirId=[],i.lightShadowMapId=[],i.lightShadowMatrixId=[],i.lightShadowParamsId=[],i.lightShadowIntensity=[],i.lightRadiusId=[],i.lightPos=[],i.lightPosId=[],i.lightWidth=[],i.lightWidthId=[],i.lightHeight=[],i.lightHeightId=[],i.lightInAngleId=[],i.lightOutAngleId=[],i.lightCookieId=[],i.lightCookieIntId=[],i.lightCookieMatrixId=[],i.lightCookieOffsetId=[],i.lightShadowSearchAreaId=[],i.lightCameraParamsId=[],i.shadowMatrixPaletteId=[],i.shadowCascadeDistancesId=[],i.shadowCascadeCountId=[],i.screenSizeId=s.resolve("uScreenSize"),i._screenSize=new Float32Array(4),i.fogColor=new Float32Array(3),i.ambientColor=new Float32Array(3),i.pcssDiskSamples=function(t){for(var e=[],i=0;i<t;++i){var n=Math.sqrt(i+.5)/Math.sqrt(t);e.push(n)}return e}(16),i.pcssSphereSamples=function(t){for(var e=[],i=0;i<t;i++){var n=i/t,s=Math.sqrt(1-n*n);e.push(s)}return e}(16),i}S(e,t);var i=e.prototype;return i.destroy=function(){t.prototype.destroy.call(this)},i.dispatchGlobalLights=function(t){if(this.ambientColor[0]=t.ambientLight.r,this.ambientColor[1]=t.ambientLight.g,this.ambientColor[2]=t.ambientLight.b,t.gammaCorrection)for(var e=0;e<3;e++)this.ambientColor[e]=Math.pow(this.ambientColor[e],2.2);if(t.physicalUnits)for(var i=0;i<3;i++)this.ambientColor[i]*=t.ambientLuminance;this.ambientId.setValue(this.ambientColor),this.skyboxIntensityId.setValue(t.physicalUnits?t.skyboxLuminance:t.skyboxIntensity),this.cubeMapRotationMatrixId.setValue(t._skyboxRotationMat3.data)},i._resolveLight=function(t,e){var i="light"+e;this.lightColorId[e]=t.resolve(i+"_color"),this.lightDir[e]=new Float32Array(3),this.lightDirId[e]=t.resolve(i+"_direction"),this.lightShadowMapId[e]=t.resolve(i+"_shadowMap"),this.lightShadowMatrixId[e]=t.resolve(i+"_shadowMatrix"),this.lightShadowParamsId[e]=t.resolve(i+"_shadowParams"),this.lightShadowIntensity[e]=t.resolve(i+"_shadowIntensity"),this.lightShadowSearchAreaId[e]=t.resolve(i+"_shadowSearchArea"),this.lightRadiusId[e]=t.resolve(i+"_radius"),this.lightPos[e]=new Float32Array(3),this.lightPosId[e]=t.resolve(i+"_position"),this.lightWidth[e]=new Float32Array(3),this.lightWidthId[e]=t.resolve(i+"_halfWidth"),this.lightHeight[e]=new Float32Array(3),this.lightHeightId[e]=t.resolve(i+"_halfHeight"),this.lightInAngleId[e]=t.resolve(i+"_innerConeAngle"),this.lightOutAngleId[e]=t.resolve(i+"_outerConeAngle"),this.lightCookieId[e]=t.resolve(i+"_cookie"),this.lightCookieIntId[e]=t.resolve(i+"_cookieIntensity"),this.lightCookieMatrixId[e]=t.resolve(i+"_cookieMatrix"),this.lightCookieOffsetId[e]=t.resolve(i+"_cookieOffset"),this.lightCameraParamsId[e]=t.resolve(i+"_cameraParams"),this.shadowMatrixPaletteId[e]=t.resolve(i+"_shadowMatrixPalette[0]"),this.shadowCascadeDistancesId[e]=t.resolve(i+"_shadowCascadeDistances[0]"),this.shadowCascadeCountId[e]=t.resolve(i+"_shadowCascadeCount")},i.setLTCDirectionalLight=function(t,e,i,n,s){this.lightPos[e][0]=n.x-i.x*s,this.lightPos[e][1]=n.y-i.y*s,this.lightPos[e][2]=n.z-i.z*s,this.lightPosId[e].setValue(this.lightPos[e]);var r=t.transformVector(new wt(-.5,0,0));this.lightWidth[e][0]=r.x*s,this.lightWidth[e][1]=r.y*s,this.lightWidth[e][2]=r.z*s,this.lightWidthId[e].setValue(this.lightWidth[e]);var a=t.transformVector(new wt(0,0,.5));this.lightHeight[e][0]=a.x*s,this.lightHeight[e][1]=a.y*s,this.lightHeight[e][2]=a.z*s,this.lightHeightId[e].setValue(this.lightHeight[e])},i.dispatchDirectLights=function(t,e,i,n){for(var s=0,r=this.device.scope,a=0;a<t.length;a++)if(t[a].mask&i){var o=t[a],h=o._node.getWorldTransform();if(this.lightColorId[s]||this._resolveLight(r,s),this.lightColorId[s].setValue(e.gammaCorrection?o._linearFinalColor:o._finalColor),h.getY(o._direction).mulScalar(-1),o._direction.normalize(),this.lightDir[s][0]=o._direction.x,this.lightDir[s][1]=o._direction.y,this.lightDir[s][2]=o._direction.z,this.lightDirId[s].setValue(this.lightDir[s]),0!==o.shape&&this.setLTCDirectionalLight(h,s,o._direction,n._node.getPosition(),n.farClip),o.castShadows){var l=o.getRenderData(n,0),c=o._getUniformBiasValues(l);this.lightShadowMapId[s].setValue(l.shadowBuffer),this.lightShadowMatrixId[s].setValue(l.shadowMatrix.data),this.shadowMatrixPaletteId[s].setValue(o._shadowMatrixPalette),this.shadowCascadeDistancesId[s].setValue(o._shadowCascadeDistances),this.shadowCascadeCountId[s].setValue(o.numCascades),this.lightShadowIntensity[s].setValue(o.shadowIntensity);var u=50/l.projectionCompensation,d=o.penumbraSize/l.shadowCamera.renderTarget.width;this.lightShadowSearchAreaId[s].setValue(d*u);var f=o._shadowCameraParams;f.length=4,f[0]=l.depthRangeCompensation,f[1]=l.shadowCamera._farClip,f[2]=l.shadowCamera._nearClip,f[3]=1,this.lightCameraParamsId[s].setValue(f);var p=o._shadowRenderParams;p.length=4,p[0]=o._shadowResolution,p[1]=c.normalBias,p[2]=c.bias,p[3]=0,this.lightShadowParamsId[s].setValue(p)}s++}return s},i.setLTCPositionalLight=function(t,e){var i=t.transformVector(new wt(-.5,0,0));this.lightWidth[e][0]=i.x,this.lightWidth[e][1]=i.y,this.lightWidth[e][2]=i.z,this.lightWidthId[e].setValue(this.lightWidth[e]);var n=t.transformVector(new wt(0,0,.5));this.lightHeight[e][0]=n.x,this.lightHeight[e][1]=n.y,this.lightHeight[e][2]=n.z,this.lightHeightId[e].setValue(this.lightHeight[e])},i.dispatchOmniLight=function(t,e,i,n){var s=i._node.getWorldTransform();if(this.lightColorId[n]||this._resolveLight(e,n),this.lightRadiusId[n].setValue(i.attenuationEnd),this.lightColorId[n].setValue(t.gammaCorrection?i._linearFinalColor:i._finalColor),s.getTranslation(i._position),this.lightPos[n][0]=i._position.x,this.lightPos[n][1]=i._position.y,this.lightPos[n][2]=i._position.z,this.lightPosId[n].setValue(this.lightPos[n]),0!==i.shape&&this.setLTCPositionalLight(s,n),i.castShadows){var r=i.getRenderData(null,0);this.lightShadowMapId[n].setValue(r.shadowBuffer);var a=i._getUniformBiasValues(r),o=i._shadowRenderParams;o.length=4,o[0]=i._shadowResolution,o[1]=a.normalBias,o[2]=a.bias,o[3]=1/i.attenuationEnd,this.lightShadowParamsId[n].setValue(o),this.lightShadowIntensity[n].setValue(i.shadowIntensity);var h=i.penumbraSize/r.shadowCamera.renderTarget.width;this.lightShadowSearchAreaId[n].setValue(h);var l=i._shadowCameraParams;l.length=4,l[0]=r.depthRangeCompensation,l[1]=r.shadowCamera._farClip,l[2]=r.shadowCamera._nearClip,l[3]=0,this.lightCameraParamsId[n].setValue(l)}i._cookie&&(this.lightCookieId[n].setValue(i._cookie),this.lightShadowMatrixId[n].setValue(s.data),this.lightCookieIntId[n].setValue(i.cookieIntensity))},i.dispatchSpotLight=function(t,e,i,n){var s=i._node.getWorldTransform();if(this.lightColorId[n]||this._resolveLight(e,n),this.lightInAngleId[n].setValue(i._innerConeAngleCos),this.lightOutAngleId[n].setValue(i._outerConeAngleCos),this.lightRadiusId[n].setValue(i.attenuationEnd),this.lightColorId[n].setValue(t.gammaCorrection?i._linearFinalColor:i._finalColor),s.getTranslation(i._position),this.lightPos[n][0]=i._position.x,this.lightPos[n][1]=i._position.y,this.lightPos[n][2]=i._position.z,this.lightPosId[n].setValue(this.lightPos[n]),0!==i.shape&&this.setLTCPositionalLight(s,n),s.getY(i._direction).mulScalar(-1),i._direction.normalize(),this.lightDir[n][0]=i._direction.x,this.lightDir[n][1]=i._direction.y,this.lightDir[n][2]=i._direction.z,this.lightDirId[n].setValue(this.lightDir[n]),i.castShadows){var r=i.getRenderData(null,0);this.lightShadowMapId[n].setValue(r.shadowBuffer),this.lightShadowMatrixId[n].setValue(r.shadowMatrix.data);var a=i._getUniformBiasValues(r),o=i._shadowRenderParams;o.length=4,o[0]=i._shadowResolution,o[1]=a.normalBias,o[2]=a.bias,o[3]=1/i.attenuationEnd,this.lightShadowParamsId[n].setValue(o),this.lightShadowIntensity[n].setValue(i.shadowIntensity);var h=i.penumbraSize/r.shadowCamera.renderTarget.width,l=r.shadowCamera._fov*Math.PI/180,c=1/Math.tan(l/2);this.lightShadowSearchAreaId[n].setValue(h*c);var u=i._shadowCameraParams;u.length=4,u[0]=r.depthRangeCompensation,u[1]=r.shadowCamera._farClip,u[2]=r.shadowCamera._nearClip,u[3]=0,this.lightCameraParamsId[n].setValue(u)}if(i._cookie){if(!i.castShadows){var d=il.evalSpotCookieMatrix(i);this.lightShadowMatrixId[n].setValue(d.data)}this.lightCookieId[n].setValue(i._cookie),this.lightCookieIntId[n].setValue(i.cookieIntensity),i._cookieTransform&&(i._cookieTransformUniform[0]=i._cookieTransform.x,i._cookieTransformUniform[1]=i._cookieTransform.y,i._cookieTransformUniform[2]=i._cookieTransform.z,i._cookieTransformUniform[3]=i._cookieTransform.w,this.lightCookieMatrixId[n].setValue(i._cookieTransformUniform),i._cookieOffsetUniform[0]=i._cookieOffset.x,i._cookieOffsetUniform[1]=i._cookieOffset.y,this.lightCookieOffsetId[n].setValue(i._cookieOffsetUniform))}},i.dispatchLocalLights=function(t,e,i,n){for(var s=n,r=this.device.scope,a=t[1],o=a.length,h=0;h<o;h++){var l=a[h];l.mask&i&&(this.dispatchOmniLight(e,r,l,s),s++)}for(var c=t[2],u=c.length,d=0;d<u;d++){var f=c[d];f.mask&i&&(this.dispatchSpotLight(e,r,f,s),s++)}},i.renderForwardPrepareMaterials=function(t,e,i,n,s){var r,a=function(t,e,i,n){gu.drawCalls.push(t),gu.shaderInstances.push(e),gu.isNewMaterial.push(i),gu.lightMaskChanged.push(n)};gu.clear();for(var o,h,l=this.device,c=this.scene,u=c.clusteredLightingEnabled,d=null!=(r=null==n?void 0:n.getLightHash(u))?r:0,f=null,p=e.length,m=0;m<p;m++){var _=e[m];_.ensureMaterial(l);var v=_.material,g=_._shaderDefs,y=_.mask;v&&v===f&&g!==o&&(f=null),v!==f&&(this._materialSwitches++,v._scene=c,v.dirty&&(v.updateUniforms(l,c),v.dirty=!1));var x=_.getShaderInstance(s,d,c,this.viewUniformFormat,this.viewBindGroupFormat,i);a(_,x,v!==f,!f||y!==h),f=v,o=g,h=y}return null==l.endShaderBatch||l.endShaderBatch(),gu},i.renderForwardInternal=function(t,e,i,n,s,r){for(var a=this.device,o=this.scene,h=1<<n,l=r?-1:1,c=this.scene.clusteredLightingEnabled,u=e.drawCalls.length,d=0;d<u;d++){var f,p,m=e.drawCalls[d],_=e.isNewMaterial[d],v=e.lightMaskChanged[d],g=e.shaderInstances[d],y=m.material;m._shaderDefs;var x=m.mask;if(_){var S=g.shader;if(!S.failed&&a.setShader(S),S.failed)break;if(y.setParameters(a),v){var b=this.dispatchDirectLights(i[0],o,x,t);c||this.dispatchLocalLights(i,o,x,b)}this.alphaTestId.setValue(y.alphaTest),a.setBlendState(y.blendState),a.setDepthState(y.depthState),a.setAlphaToCoverage(y.alphaToCoverage),y.depthBias||y.slopeDepthBias?(a.setDepthBias(!0),a.setDepthBiasValues(y.depthBias,y.slopeDepthBias)):a.setDepthBias(!1)}this.setupCullMode(t._cullFaces,l,m);var w=null!=(f=m.stencilFront)?f:y.stencilFront,T=null!=(p=m.stencilBack)?p:y.stencilBack;a.setStencilState(w,T);var A=m.mesh;m.setParameters(a,h),this.setVertexBuffers(a,A),this.setMorphing(a,m.morphInstance),this.setSkinning(a,m),this.setupMeshUniformBuffers(g,m);var C=m.renderStyle;if(a.setIndexBuffer(A.indexBuffer[C]),null==s||s(m,d),t.xr&&t.xr.session&&t.xr.views.length)for(var E=t.xr.views,M=0;M<E.length;M++){var P=E[M];a.setViewport(P.viewport.x,P.viewport.y,P.viewport.z,P.viewport.w),this.projId.setValue(P.projMat.data),this.projSkyboxId.setValue(P.projMat.data),this.viewId.setValue(P.viewOffMat.data),this.viewInvId.setValue(P.viewInvOffMat.data),this.viewId3.setValue(P.viewMat3.data),this.viewProjId.setValue(P.projViewOffMat.data),this.viewPosId.setValue(P.position),0===M?this.drawInstance(a,m,A,C,!0):this.drawInstance2(a,m,A,C),this._forwardDrawCalls++}else this.drawInstance(a,m,A,C,!0),this._forwardDrawCalls++;d<u-1&&!e.isNewMaterial[d+1]&&y.setParameters(a,m.parameters)}},i.renderForward=function(t,e,i,n,s,r,a){var o=this.renderForwardPrepareMaterials(t,e,i,r,n);this.renderForwardInternal(t,o,i,n,s,a),gu.clear()},i.setSceneConstants=function(){var t=this.scene;if(this.dispatchGlobalLights(t),t.fog!==Ra){if(this.fogColor[0]=t.fogColor.r,this.fogColor[1]=t.fogColor.g,this.fogColor[2]=t.fogColor.b,t.gammaCorrection)for(var e=0;e<3;e++)this.fogColor[e]=Math.pow(this.fogColor[e],2.2);this.fogColorId.setValue(this.fogColor),t.fog===Ia?(this.fogStartId.setValue(t.fogStart),this.fogEndId.setValue(t.fogEnd)):this.fogDensityId.setValue(t.fogDensity)}var i=this.device;this._screenSize[0]=i.width,this._screenSize[1]=i.height,this._screenSize[2]=1/i.width,this._screenSize[3]=1/i.height,this.screenSizeId.setValue(this._screenSize),this.pcssDiskSamplesId.setValue(this.pcssDiskSamples),this.pcssSphereSamplesId.setValue(this.pcssSphereSamples)},i.buildFrameGraph=function(t,e){var i=this,n=this.scene.clusteredLightingEnabled,s=this.device.isWebGL1;if(t.reset(),this.update(e),n){if(this.scene.lighting.cookiesEnabled){var r=this.cookiesRenderPass;r.update(this.lights),t.addRenderPass(r)}var a=new uo(this.device);a.requiresCubemaps=!1,t.addRenderPass(a),this.scene.lighting.shadowsEnabled&&this._shadowRendererLocal.prepareClusteredRenderPass(a,this.localLights),a._after=function(){i.updateClusters(e)}}else this._shadowRendererLocal.buildNonClusteredRenderPasses(t,this.localLights);for(var o=0,h=!0,l=null,c=e._renderActions,u=function(){var n=c[d],r=e.layerList[n.layerIndex],a=n.camera,u=a.camera.renderPassDepthGrab;if(u&&s&&n.firstCameraUse&&(u.update(i.scene),t.addRenderPass(u)),!n.isLayerEnabled(e))return 0;var f=1===r.id;if(s&&f&&!a.renderSceneColorMap)return 0;var p=f&&(a.renderSceneColorMap||a.renderSceneDepthMap);n.hasDirectionalShadowLights&&a&&i._shadowRendererDirectional.buildFrameGraph(t,n.directionalLights,a),h&&(h=!1,o=d,l=n.renderTarget);for(var m=d+1;c[m]&&!c[m].isLayerEnabled(e);)m++;var _=c[m],v=!!_&&1===e.layerList[_.layerIndex].id&&(a.renderSceneColorMap||a.renderSceneDepthMap)&&!s;if(!_||_.renderTarget!==l||_.hasDirectionalShadowLights||v||p){if(f&&o===d||i.addMainRenderPass(t,e,l,o,d),f&&(a.renderSceneColorMap&&t.addRenderPass(a.camera.renderPassColorGrab),a.renderSceneDepthMap&&!s&&t.addRenderPass(a.camera.renderPassDepthGrab)),n.triggerPostprocess&&null!=a&&a.onPostprocessing){var g=new uo(i.device,(function(){i.renderPassPostprocessing(n)}));g.requiresCubemaps=!1,t.addRenderPass(g)}h=!0}},d=o;d<c.length;d++)u()},i.addMainRenderPass=function(t,e,i,n,s){var r=this,a={start:n,end:s},o=new uo(this.device,(function(){r.renderPassRenderActions(e,a)})),h=e._renderActions,l=h[n],c=h[s],u=l.camera;u&&(l.firstCameraUse&&u.onPreRender&&(o._before=function(){u.onPreRender()}),c.lastCameraUse&&u.onPostRender&&(o._after=function(){u.onPostRender()})),o.init(i),o.fullSizeClearRect=u.camera.fullSizeClearRect,o.fullSizeClearRect&&(l.clearColor&&o.setClearColor(u.camera.clearColor),l.clearDepth&&o.setClearDepth(u.camera.clearDepth),l.clearStencil&&o.setClearStencil(u.camera.clearStencil)),t.addRenderPass(o)},i.update=function(t){this.frameUpdate(),this.shadowRenderer.frameUpdate();var e=this.scene.clusteredLightingEnabled;this.scene._updateSky(this.device),this.updateLayerComposition(t,e),this.collectLights(t),this.beginFrame(t),this.setSceneConstants(),this.cullComposition(t),this.gpuUpdate(this.processingMeshInstances)},i.renderPassPostprocessing=function(t){t.camera.onPostprocessing()},i.renderPassRenderActions=function(t,e){for(var i=t._renderActions,n=e.start;n<=e.end;n++)this.renderRenderAction(t,i[n],n===e.start)},i.renderRenderAction=function(t,e,i){var n=this.scene.clusteredLightingEnabled,s=this.device,r=e.layerIndex,a=t.layerList[r],o=t.subLayerList[r],h=e.camera,l=t.camerasMap.get(h);if(e.isLayerEnabled(t)){if(!o&&a.onPreRenderOpaque?a.onPreRenderOpaque(l):o&&a.onPreRenderTransparent&&a.onPreRenderTransparent(l),a._preRenderCalledForCameras&1<<l||(a.onPreRender&&a.onPreRender(l),a._preRenderCalledForCameras|=1<<l),h){var c,u,d;this.setupViewport(h.camera,e.renderTarget),i&&h.camera.fullSizeClearRect||this.clear(h.camera,e.clearColor,e.clearDepth,e.clearStencil),a.sortVisible(h.camera,o);var f=a.getCulledInstances(h.camera),p=o?f.transparent:f.opaque;this.scene.immediate.onPreRenderLayer(a,p,o),a.requiresLightCube&&(this.lightCube.update(this.scene.ambientLight,a._lights),this.constantLightCube.setValue(this.lightCube.colors)),n&&e.lightClusters&&(e.lightClusters.activate(),this.clustersDebugRendered||this.scene.lighting.debugLayer!==a.id||(this.clustersDebugRendered=!0)),this.scene._activeCamera=h.camera;var m=this.setCameraUniforms(h.camera,e.renderTarget);s.supportsUniformBuffers&&this.setupViewUniformBuffers(e.viewBindGroups,this.viewUniformFormat,this.viewBindGroupFormat,m);var _=!!(h.camera._flipFaces^(null==e||null==(c=e.renderTarget)?void 0:c.flipY)),v=null!=(u=null==(d=h.camera.shaderPassInfo)?void 0:d.index)?u:a.shaderPass,g=this._forwardDrawCalls;this.renderForward(h.camera,p,a.splitLights,v,a.onDrawCall,a,_),a._forwardDrawCalls+=this._forwardDrawCalls-g,s.setBlendState(Ui.NOBLEND),s.setStencilState(null,null),s.setAlphaToCoverage(!1),s.setDepthBias(!1)}!o&&a.onPostRenderOpaque?a.onPostRenderOpaque(l):o&&a.onPostRenderTransparent&&a.onPostRenderTransparent(l),!a.onPostRender||a._postRenderCalledForCameras&1<<l||(a._postRenderCounter&=~(o?2:1),0===a._postRenderCounter&&(a.onPostRender(l),a._postRenderCalledForCameras|=1<<l,a._postRenderCounter=a._postRenderCounterMax))}},e}(bc);var xu,Su=[null,function(t,e){return t.drawOrder-e.drawOrder},function(t,e){var i=t._key[0],n=e._key[0];return i===n&&t.mesh&&e.mesh?e.mesh.id-t.mesh.id:n-i},function(t,e){return e.zdist-t.zdist},function(t,e){return t.zdist-e.zdist}],bu=0,wu=[],Tu=new Set,Au=function(){this.opaque=[],this.transparent=[]},Cu=function(){function t(t){var e,i,n,s;void 0===t&&(t={}),this.meshInstances=[],this.meshInstancesSet=new Set,this.shadowCasters=[],this.shadowCastersSet=new Set,this._visibleInstances=new WeakMap,this._lights=[],this._lightsSet=new Set,this._clusteredLightsSet=new Set,this._splitLights=[[],[],[]],this._splitLightsDirty=!0,this.requiresLightCube=!1,this.cameras=[],this.camerasSet=new Set,this._dirtyCameras=!1,void 0!==t.id?(this.id=t.id,bu=Math.max(this.id+1,bu)):this.id=bu++,this.name=t.name,this._enabled=null==(e=t.enabled)||e,this._refCounter=this._enabled?1:0,this.opaqueSortMode=null!=(i=t.opaqueSortMode)?i:2,this.transparentSortMode=null!=(n=t.transparentSortMode)?n:3,t.renderTarget&&(this.renderTarget=t.renderTarget),this.shaderPass=null!=(s=t.shaderPass)?s:0,this._clearColorBuffer=!!t.clearColorBuffer,this._clearDepthBuffer=!!t.clearDepthBuffer,this._clearStencilBuffer=!!t.clearStencilBuffer,this.onPreCull=t.onPreCull,this.onPreRender=t.onPreRender,this.onPreRenderOpaque=t.onPreRenderOpaque,this.onPreRenderTransparent=t.onPreRenderTransparent,this.onPostCull=t.onPostCull,this.onPostRender=t.onPostRender,this.onPostRenderOpaque=t.onPostRenderOpaque,this.onPostRenderTransparent=t.onPostRenderTransparent,this.onDrawCall=t.onDrawCall,this.onEnable=t.onEnable,this.onDisable=t.onDisable,this._enabled&&this.onEnable&&this.onEnable(),this.layerReference=t.layerReference,this.customSortCallback=null,this.customCalculateSortValues=null,this._lightHash=0,this._lightHashDirty=!1,this._lightIdHash=0,this._lightIdHashDirty=!1,this._shaderVersion=-1}var e=t.prototype;return e.incrementCounter=function(){0===this._refCounter&&(this._enabled=!0,this.onEnable&&this.onEnable()),this._refCounter++},e.decrementCounter=function(){if(1===this._refCounter)this._enabled=!1,this.onDisable&&this.onDisable();else if(0===this._refCounter)return;this._refCounter--},e.addMeshInstances=function(t,e){for(var i=this.meshInstances,n=this.meshInstancesSet,s=0;s<t.length;s++){var r=t[s];n.has(r)||(i.push(r),n.add(r),Tu.add(r.material))}if(e||this.addShadowCasters(t),Tu.size>0){var a=this._shaderVersion;Tu.forEach((function(t){a>=0&&t._shaderVersion!==a&&(t.getShaderVariant!==zo.prototype.getShaderVariant&&t.clearVariants(),t._shaderVersion=a)})),Tu.clear()}},e.removeMeshInstances=function(t,e){for(var i=this.meshInstances,n=this.meshInstancesSet,s=0;s<t.length;s++){var r=t[s];if(n.has(r)){n.delete(r);var a=i.indexOf(r);a>=0&&i.splice(a,1)}}e||this.removeShadowCasters(t)},e.addShadowCasters=function(t){for(var e=this.shadowCasters,i=this.shadowCastersSet,n=0;n<t.length;n++){var s=t[n];s.castShadow&&!i.has(s)&&(i.add(s),e.push(s))}},e.removeShadowCasters=function(t){for(var e=this.shadowCasters,i=this.shadowCastersSet,n=0;n<t.length;n++){var s=t[n];if(i.has(s)){i.delete(s);var r=e.indexOf(s);r>=0&&e.splice(r,1)}}},e.clearMeshInstances=function(t){void 0===t&&(t=!1),this.meshInstances.length=0,this.meshInstancesSet.clear(),t||(this.shadowCasters.length=0,this.shadowCastersSet.clear())},e.markLightsDirty=function(){this._lightHashDirty=!0,this._lightIdHashDirty=!0,this._splitLightsDirty=!0},e.addLight=function(t){var e=t.light;this._lightsSet.has(e)||(this._lightsSet.add(e),this._lights.push(e),this.markLightsDirty()),0!==e.type&&this._clusteredLightsSet.add(e)},e.removeLight=function(t){var e=t.light;this._lightsSet.has(e)&&(this._lightsSet.delete(e),this._lights.splice(this._lights.indexOf(e),1),this.markLightsDirty()),0!==e.type&&this._clusteredLightsSet.delete(e)},e.clearLights=function(){var t=this;this._lightsSet.forEach((function(e){return e.removeLayer(t)})),this._lightsSet.clear(),this._clusteredLightsSet.clear(),this._lights.length=0,this.markLightsDirty()},e.evaluateLightHash=function(t,e,i){for(var n=0,s=this._lights,r=0;r<s.length;r++){var a=0!==s[r].type;(t&&a||e&&!a)&&wu.push(i?s[r].id:s[r].key)}return wu.length>0&&(wu.sort(),n=Yi(wu),wu.length=0),n},e.getLightHash=function(t){return this._lightHashDirty&&(this._lightHashDirty=!1,this._lightHash=this.evaluateLightHash(!t,!0,!1)),this._lightHash},e.getLightIdHash=function(){return this._lightIdHashDirty&&(this._lightIdHashDirty=!1,this._lightIdHash=this.evaluateLightHash(!0,!1,!0)),this._lightIdHash},e.addCamera=function(t){this.camerasSet.has(t.camera)||(this.camerasSet.add(t.camera),this.cameras.push(t),this._dirtyCameras=!0)},e.removeCamera=function(t){if(this.camerasSet.has(t.camera)){this.camerasSet.delete(t.camera);var e=this.cameras.indexOf(t);this.cameras.splice(e,1),this._dirtyCameras=!0}},e.clearCameras=function(){this.cameras.length=0,this.camerasSet.clear(),this._dirtyCameras=!0},e._calculateSortDistances=function(t,e,i,n){for(var s=0;s<e;s++){var r=t[s];if(!(r.layer<=2))if(r.calculateSortDistance)r.zdist=r.calculateSortDistance(r,i,n);else{var a=r.aabb.center,o=a.x-i.x,h=a.y-i.y,l=a.z-i.z;r.zdist=o*n.x+h*n.y+l*n.z}}},e.getCulledInstances=function(t){var e=this._visibleInstances.get(t);return e||(e=new Au,this._visibleInstances.set(t,e)),e},e.sortVisible=function(t,e){var i=e?this.transparentSortMode:this.opaqueSortMode;if(0!==i){var n=this.getCulledInstances(t),s=e?n.transparent:n.opaque,r=t.node;if(5===i){var a=r.getPosition(),o=r.forward;this.customCalculateSortValues&&this.customCalculateSortValues(s,s.length,a,o),this.customSortCallback&&s.sort(this.customSortCallback)}else{if(3===i||4===i){var h=r.getPosition(),l=r.forward;this._calculateSortDistances(s,s.length,h,l)}s.sort(Su[i])}}},y(t,[{key:"enabled",get:function(){return this._enabled},set:function(t){t!==this._enabled&&(this._enabled=t,t?(this.incrementCounter(),this.onEnable&&this.onEnable()):(this.decrementCounter(),this.onDisable&&this.onDisable()))}},{key:"clearColorBuffer",get:function(){return this._clearColorBuffer},set:function(t){this._clearColorBuffer=t,this._dirtyCameras=!0}},{key:"clearDepthBuffer",get:function(){return this._clearDepthBuffer},set:function(t){this._clearDepthBuffer=t,this._dirtyCameras=!0}},{key:"clearStencilBuffer",get:function(){return this._clearStencilBuffer},set:function(t){this._clearStencilBuffer=t,this._dirtyCameras=!0}},{key:"hasClusteredLights",get:function(){return this._clusteredLightsSet.size>0}},{key:"clusteredLightsSet",get:function(){return this._clusteredLightsSet}},{key:"splitLights",get:function(){if(this._splitLightsDirty){this._splitLightsDirty=!1;for(var t=this._splitLights,e=0;e<t.length;e++)t[e].length=0;for(var i=this._lights,n=0;n<i.length;n++){var s=i[n];s.enabled&&t[s._type].push(s)}for(var r=0;r<t.length;r++)t[r].sort((function(t,e){return t.key-e.key}))}return this._splitLights}}]),t}(),Eu=function(t,e){return t.priority-e.priority},Mu=function(t){return t.sort(Eu)},Pu=function(){function t(){this.layerIndex=0,this.layer=null,this.camera=null,this.renderTarget=null,this.lightClusters=null,this.clearColor=!1,this.clearDepth=!1,this.clearStencil=!1,this.triggerPostprocess=!1,this.firstCameraUse=!1,this.lastCameraUse=!1,this.directionalLights=[],this.viewBindGroups=[]}var e=t.prototype;return e.destroy=function(){this.viewBindGroups.forEach((function(t){t.defaultUniformBuffer.destroy(),t.destroy()})),this.viewBindGroups.length=0},e.isLayerEnabled=function(t){return t.layerList[this.layerIndex].enabled&&t.subLayerEnabled[this.layerIndex]},y(t,[{key:"hasDirectionalShadowLights",get:function(){return this.directionalLights.length>0}}]),t}(),Ru=function(t){function e(e){var i;return void 0===e&&(e="Untitled"),(i=t.call(this)||this).layerList=[],i.layerIdMap=new Map,i.layerNameMap=new Map,i.subLayerList=[],i.subLayerEnabled=[],i.cameras=[],i.camerasMap=new Map,i._renderActions=[],i.name=e,i._opaqueOrder={},i._transparentOrder={},i._dirtyCameras=!1,i}S(e,t);var i=e.prototype;return i.destroy=function(){this._renderActions.forEach((function(t){return t.destroy()})),this._renderActions=null},i._update=function(){var t=this.layerList.length;if(!this._dirtyCameras)for(var e=0;e<t;e++)if(this.layerList[e]._dirtyCameras){this._dirtyCameras=!0;break}if(this._dirtyCameras){this._dirtyCameras=!1,this.cameras.length=0;for(var i=0;i<t;i++){var n=this.layerList[i];n._dirtyCameras=!1;for(var s=0;s<n.cameras.length;s++){var r=n.cameras[s];this.cameras.indexOf(r)<0&&this.cameras.push(r)}}this.cameras.length>1&&Mu(this.cameras),this.camerasMap.clear();for(var a=0;a<this.cameras.length;a++)this.camerasMap.set(this.cameras[a],a);for(var o=[],h=0,l=0;l<this.cameras.length;l++){var c=this.cameras[l];o.length=0;for(var u=!0,d=h,f=null,p=!1,m=0;m<t;m++){var _=this.layerList[m],v=this.subLayerEnabled[m];_&&v&&_.cameras.length>0&&c.layers.indexOf(_.id)>=0&&(o.push(_),p||_.id!==c.disablePostEffectsLayer||(p=!0,f&&(f.triggerPostprocess=!0)),f=this.addRenderAction(this._renderActions,h,_,m,c,u,p),h++,u=!1)}d<h&&(f.lastCameraUse=!0),!p&&f&&(f.triggerPostprocess=!0),c.renderTarget&&c.postEffectsEnabled&&this.propagateRenderTarget(d-1,c)}for(var g=h;g<this._renderActions.length;g++)this._renderActions[g].destroy();this._renderActions.length=h,this._logRenderActions()}},i.addRenderAction=function(t,e,i,n,s,r,a){var o=t[e];o||(o=t[e]=new Pu);var h=i.renderTarget;s&&s.renderTarget&&1!==i.id&&(h=s.renderTarget);for(var l=!1,c=e-1;c>=0;c--)if(t[c].camera===s&&t[c].renderTarget===h){l=!0;break}var u=r||!l,d=!!u&&s.clearColorBuffer,f=!!u&&s.clearDepthBuffer,p=!!u&&s.clearStencilBuffer;return d||(d=i.clearColorBuffer),f||(f=i.clearDepthBuffer),p||(p=i.clearStencilBuffer),a&&s.postEffectsEnabled&&(h=null),o.triggerPostprocess=!1,o.layerIndex=n,o.layer=i,o.camera=s,o.renderTarget=h,o.clearColor=d,o.clearDepth=f,o.clearStencil=p,o.firstCameraUse=r,o.lastCameraUse=!1,o},i.propagateRenderTarget=function(t,e){for(var i=t;i>=0;i--){var n=this._renderActions[i],s=this.layerList[n.layerIndex];if(n.renderTarget&&1!==s.id)break;if(1!==s.id){var r=null==n?void 0:n.camera.camera;if(r&&(!e.camera.rect.equals(r.rect)||!e.camera.scissorRect.equals(r.scissorRect)))break;n.renderTarget=e.renderTarget}}},i._logRenderActions=function(){},i._isLayerAdded=function(t){return this.layerIdMap.get(t.id)===t},i._isSublayerAdded=function(t,e){for(var i=0;i<this.layerList.length;i++)if(this.layerList[i]===t&&this.subLayerList[i]===e)return!0;return!1},i.push=function(t){this._isLayerAdded(t)||(this.layerList.push(t),this.layerList.push(t),this._opaqueOrder[t.id]=this.subLayerList.push(!1)-1,this._transparentOrder[t.id]=this.subLayerList.push(!0)-1,this.subLayerEnabled.push(!0),this.subLayerEnabled.push(!0),this._updateLayerMaps(),this._dirtyCameras=!0,this.fire("add",t))},i.insert=function(t,e){if(!this._isLayerAdded(t)){this.layerList.splice(e,0,t,t),this.subLayerList.splice(e,0,!1,!0);var i=this.layerList.length;this._updateOpaqueOrder(e,i-1),this._updateTransparentOrder(e,i-1),this.subLayerEnabled.splice(e,0,!0,!0),this._updateLayerMaps(),this._dirtyCameras=!0,this.fire("add",t)}},i.remove=function(t){var e=this.layerList.indexOf(t);for(delete this._opaqueOrder[e],delete this._transparentOrder[e];e>=0;)this.layerList.splice(e,1),this.subLayerList.splice(e,1),this.subLayerEnabled.splice(e,1),e=this.layerList.indexOf(t),this._dirtyCameras=!0,this.fire("remove",t);var i=this.layerList.length;this._updateOpaqueOrder(0,i-1),this._updateTransparentOrder(0,i-1),this._updateLayerMaps()},i.pushOpaque=function(t){this._isSublayerAdded(t,!1)||(this.layerList.push(t),this._opaqueOrder[t.id]=this.subLayerList.push(!1)-1,this.subLayerEnabled.push(!0),this._updateLayerMaps(),this._dirtyCameras=!0,this.fire("add",t))},i.insertOpaque=function(t,e){if(!this._isSublayerAdded(t,!1)){this.layerList.splice(e,0,t),this.subLayerList.splice(e,0,!1);var i=this.subLayerList.length;this._updateOpaqueOrder(e,i-1),this.subLayerEnabled.splice(e,0,!0),this._updateLayerMaps(),this._dirtyCameras=!0,this.fire("add",t)}},i.removeOpaque=function(t){for(var e=0,i=this.layerList.length;e<i;e++)if(this.layerList[e]===t&&!this.subLayerList[e]){this.layerList.splice(e,1),this.subLayerList.splice(e,1),i--,this._updateOpaqueOrder(e,i-1),this.subLayerEnabled.splice(e,1),this._dirtyCameras=!0,this.layerList.indexOf(t)<0&&this.fire("remove",t);break}this._updateLayerMaps()},i.pushTransparent=function(t){this._isSublayerAdded(t,!0)||(this.layerList.push(t),this._transparentOrder[t.id]=this.subLayerList.push(!0)-1,this.subLayerEnabled.push(!0),this._updateLayerMaps(),this._dirtyCameras=!0,this.fire("add",t))},i.insertTransparent=function(t,e){if(!this._isSublayerAdded(t,!0)){this.layerList.splice(e,0,t),this.subLayerList.splice(e,0,!0);var i=this.subLayerList.length;this._updateTransparentOrder(e,i-1),this.subLayerEnabled.splice(e,0,!0),this._updateLayerMaps(),this._dirtyCameras=!0,this.fire("add",t)}},i.removeTransparent=function(t){for(var e=0,i=this.layerList.length;e<i;e++)if(this.layerList[e]===t&&this.subLayerList[e]){this.layerList.splice(e,1),this.subLayerList.splice(e,1),i--,this._updateTransparentOrder(e,i-1),this.subLayerEnabled.splice(e,1),this._dirtyCameras=!0,this.layerList.indexOf(t)<0&&this.fire("remove",t);break}this._updateLayerMaps()},i._getSublayerIndex=function(t,e){var i=this.layerList.indexOf(t);if(i<0)return-1;if(this.subLayerList[i]!==e){if((i=this.layerList.indexOf(t,i+1))<0)return-1;if(this.subLayerList[i]!==e)return-1}return i},i.getOpaqueIndex=function(t){return this._getSublayerIndex(t,!1)},i.getTransparentIndex=function(t){return this._getSublayerIndex(t,!0)},i._updateLayerMaps=function(){this.layerIdMap.clear(),this.layerNameMap.clear();for(var t=0;t<this.layerList.length;t++){var e=this.layerList[t];this.layerIdMap.set(e.id,e),this.layerNameMap.set(e.name,e)}},i.getLayerById=function(t){var e;return null!=(e=this.layerIdMap.get(t))?e:null},i.getLayerByName=function(t){var e;return null!=(e=this.layerNameMap.get(t))?e:null},i._updateOpaqueOrder=function(t,e){for(var i=t;i<=e;i++)!1===this.subLayerList[i]&&(this._opaqueOrder[this.layerList[i].id]=i)},i._updateTransparentOrder=function(t,e){for(var i=t;i<=e;i++)!0===this.subLayerList[i]&&(this._transparentOrder[this.layerList[i].id]=i)},i._sortLayersDescending=function(t,e,i){for(var n=-1,s=-1,r=0,a=t.length;r<a;r++){var o=t[r];i.hasOwnProperty(o)&&(n=Math.max(n,i[o]))}for(var h=0,l=e.length;h<l;h++){var c=e[h];i.hasOwnProperty(c)&&(s=Math.max(s,i[c]))}return-1===n&&-1!==s?1:-1===s&&-1!==n?-1:s-n},i.sortTransparentLayers=function(t,e){return this._sortLayersDescending(t,e,this._transparentOrder)},i.sortOpaqueLayers=function(t,e){return this._sortLayersDescending(t,e,this._opaqueOrder)},e}(P),Iu=new wt,Lu={bias:0,normalBias:0},Du={r:0,g:1,b:2,a:3},Ou={directional:0,omni:1,point:1,spot:2},ku=[[new Pt(0,0,1,1)],[new Pt(0,0,.5,.5),new Pt(0,.5,.5,.5)],[new Pt(0,0,.5,.5),new Pt(0,.5,.5,.5),new Pt(.5,0,.5,.5)],[new Pt(0,0,.5,.5),new Pt(0,.5,.5,.5),new Pt(.5,0,.5,.5),new Pt(.5,.5,.5,.5)]],Fu=0,Bu=function(){function t(t,e,i,n){this.light=n,this.camera=e,this.shadowCamera=Ql.createShadowCamera(t,n._shadowType,n._type,i),this.shadowMatrix=new Ft,this.shadowViewport=new Pt(0,0,1,1),this.shadowScissor=new Pt(0,0,1,1),this.depthRangeCompensation=0,this.projectionCompensation=0,this.face=i,this.visibleCasters=[],this.viewBindGroups=[]}return t.prototype.destroy=function(){this.viewBindGroups.forEach((function(t){t.defaultUniformBuffer.destroy(),t.destroy()})),this.viewBindGroups.length=0},y(t,[{key:"shadowBuffer",get:function(){var t=this.shadowCamera.renderTarget;if(t){var e=this.light;return 1===e._type?t.colorBuffer:e._isPcf&&e.device.supportsDepthShadow?t.depthBuffer:t.colorBuffer}return null}}]),t}(),Uu=function(){function t(t){this.layers=new Set,this.device=t,this.id=Fu++,this._type=0,this._color=new vt(.8,.8,.8),this._intensity=1,this._affectSpecularity=!0,this._luminance=0,this._castShadows=!1,this._enabled=!1,this._mask=1,this.isStatic=!1,this.key=0,this.bakeDir=!0,this.bakeNumSamples=1,this.bakeArea=0,this.attenuationStart=10,this.attenuationEnd=10,this._falloffMode=0,this._shadowType=0,this._vsmBlurSize=11,this.vsmBlurMode=1,this.vsmBias=.0025,this._cookie=null,this.cookieIntensity=1,this._cookieFalloff=!0,this._cookieChannel="rgb",this._cookieTransform=null,this._cookieTransformUniform=new Float32Array(4),this._cookieOffset=null,this._cookieOffsetUniform=new Float32Array(2),this._cookieTransformSet=!1,this._cookieOffsetSet=!1,this._innerConeAngle=40,this._outerConeAngle=45,this.cascades=null,this._shadowMatrixPalette=null,this._shadowCascadeDistances=null,this.numCascades=1,this.cascadeDistribution=.5,this._shape=0,this._finalColor=new Float32Array([.8,.8,.8]);var e=Math.pow(this._finalColor[0],2.2);this._linearFinalColor=new Float32Array([e,e,e]),this._position=new wt(0,0,0),this._direction=new wt(0,0,0),this._innerConeAngleCos=Math.cos(this._innerConeAngle*Math.PI/180),this._updateOuterAngle(this._outerConeAngle),this._usePhysicalUnits=void 0,this._shadowMap=null,this._shadowRenderParams=[],this._shadowCameraParams=[],this.shadowDistance=40,this._shadowResolution=1024,this.shadowBias=-5e-4,this.shadowIntensity=1,this._normalOffsetBias=0,this.shadowUpdateMode=2,this.shadowUpdateOverrides=null,this._penumbraSize=1,this._isVsm=!1,this._isPcf=!0,this._cookieMatrix=null,this._atlasViewport=null,this.atlasViewportAllocated=!1,this.atlasVersion=0,this.atlasSlotIndex=0,this.atlasSlotUpdated=!1,this._node=null,this._renderData=[],this.visibleThisFrame=!1,this.maxScreenSize=0}var e=t.prototype;return e.destroy=function(){this._destroyShadowMap(),this.releaseRenderData(),this._renderData=null},e.releaseRenderData=function(){if(this._renderData){for(var t=0;t<this._renderData.length;t++)this._renderData[t].destroy();this._renderData.length=0}},e.addLayer=function(t){this.layers.add(t)},e.removeLayer=function(t){this.layers.delete(t)},e._updateOuterAngle=function(t){var e=t*Math.PI/180;this._outerConeAngleCos=Math.cos(e),this._outerConeAngleSin=Math.sin(e)},e.beginFrame=function(){this.visibleThisFrame=0===this._type&&this._enabled,this.maxScreenSize=0,this.atlasViewportAllocated=!1,this.atlasSlotUpdated=!1},e._destroyShadowMap=function(){if(this.releaseRenderData(),this._shadowMap&&(this._shadowMap.cached||this._shadowMap.destroy(),this._shadowMap=null),0===this.shadowUpdateMode&&(this.shadowUpdateMode=1),this.shadowUpdateOverrides)for(var t=0;t<this.shadowUpdateOverrides.length;t++)0===this.shadowUpdateOverrides[t]&&(this.shadowUpdateOverrides[t]=1)},e.getRenderData=function(t,e){for(var i=0;i<this._renderData.length;i++){var n=this._renderData[i];if(n.camera===t&&n.face===e)return n}var s=new Bu(this.device,t,e,this);return this._renderData.push(s),s},e.clone=function(){var e=new t(this.device);return e.type=this._type,e.setColor(this._color),e.intensity=this._intensity,e.affectSpecularity=this._affectSpecularity,e.luminance=this._luminance,e.castShadows=this.castShadows,e._enabled=this._enabled,e.attenuationStart=this.attenuationStart,e.attenuationEnd=this.attenuationEnd,e.falloffMode=this._falloffMode,e.shadowType=this._shadowType,e.vsmBlurSize=this._vsmBlurSize,e.vsmBlurMode=this.vsmBlurMode,e.vsmBias=this.vsmBias,e.penumbraSize=this.penumbraSize,e.shadowUpdateMode=this.shadowUpdateMode,e.mask=this.mask,this.shadowUpdateOverrides&&(e.shadowUpdateOverrides=this.shadowUpdateOverrides.slice()),e.innerConeAngle=this._innerConeAngle,e.outerConeAngle=this._outerConeAngle,e.numCascades=this.numCascades,e.cascadeDistribution=this.cascadeDistribution,e.shape=this._shape,e.shadowBias=this.shadowBias,e.normalOffsetBias=this._normalOffsetBias,e.shadowResolution=this._shadowResolution,e.shadowDistance=this.shadowDistance,e.shadowIntensity=this.shadowIntensity,e},t.getLightUnitConversion=function(t,e,i){switch(void 0===e&&(e=Math.PI/4),void 0===i&&(i=0),t){case 2:var n=Math.cos(e),s=Math.cos(i);return 2*Math.PI*(1-s+(s-n)/2);case 1:return 4*Math.PI;case 0:return 1}},e._getUniformBiasValues=function(t){var e=t.shadowCamera._farClip;switch(this._type){case 1:Lu.bias=this.shadowBias,Lu.normalBias=this._normalOffsetBias;break;case 2:this._isVsm?Lu.bias=-2e-4:(Lu.bias=20*this.shadowBias,this.device.isWebGL1&&this.device.extStandardDerivatives&&(Lu.bias*=-100)),Lu.normalBias=this._isVsm?this.vsmBias/(this.attenuationEnd/7):this._normalOffsetBias;break;case 0:this._isVsm?Lu.bias=-2e-4:(Lu.bias=this.shadowBias/e*100,this.device.isWebGL1&&this.device.extStandardDerivatives&&(Lu.bias*=-100)),Lu.normalBias=this._isVsm?this.vsmBias/(e/7):this._normalOffsetBias}return Lu},e.getColor=function(){return this._color},e.getBoundingSphere=function(t){if(2===this._type){var e=this.attenuationEnd,i=this._outerConeAngle,n=this._outerConeAngleCos,s=this._node;Iu.copy(s.up),i>45?(t.radius=e*this._outerConeAngleSin,Iu.mulScalar(-e*n)):(t.radius=e/(2*n),Iu.mulScalar(-t.radius)),t.center.add2(s.getPosition(),Iu)}else 1===this._type&&(t.center=this._node.getPosition(),t.radius=this.attenuationEnd)},e.getBoundingBox=function(t){if(2===this._type){var e=this.attenuationEnd,i=this._outerConeAngle,n=this._node,s=Math.abs(Math.sin(i*_t.DEG_TO_RAD)*e);t.center.set(0,.5*-e,0),t.halfExtents.set(s,.5*e,s),t.setFromTransformedAabb(t,n.getWorldTransform(),!0)}else 1===this._type&&(t.center.copy(this._node.getPosition()),t.halfExtents.set(this.attenuationEnd,this.attenuationEnd,this.attenuationEnd))},e._updateFinalColor=function(){var e=this._color,i=e.r,n=e.g,s=e.b,r=this._intensity;this._usePhysicalUnits&&(r=this._luminance/t.getLightUnitConversion(this._type,this._outerConeAngle*_t.DEG_TO_RAD,this._innerConeAngle*_t.DEG_TO_RAD));var a=this._finalColor,o=this._linearFinalColor;a[0]=i*r,a[1]=n*r,a[2]=s*r,r>=1?(o[0]=Math.pow(i,2.2)*r,o[1]=Math.pow(n,2.2)*r,o[2]=Math.pow(s,2.2)*r):(o[0]=Math.pow(a[0],2.2),o[1]=Math.pow(a[1],2.2),o[2]=Math.pow(a[2],2.2))},e.setColor=function(){1===arguments.length?this._color.set(arguments[0].r,arguments[0].g,arguments[0].b):3===arguments.length&&this._color.set(arguments[0],arguments[1],arguments[2]),this._updateFinalColor()},e.layersDirty=function(){this.layers.forEach((function(t){t.markLightsDirty()}))},e.updateKey=function(){var t=this._type<<29|(this._castShadows?1:0)<<28|this._shadowType<<25|this._falloffMode<<23|(0!==this._normalOffsetBias?1:0)<<22|(this._cookie?1:0)<<21|(this._cookieFalloff?1:0)<<20|Du[this._cookieChannel.charAt(0)]<<18|(this._cookieTransform?1:0)<<12|this._shape<<10|this.numCascades-1<<8|(this.affectSpecularity?1:0)<<7|this.mask<<6;3===this._cookieChannel.length&&(t|=Du[this._cookieChannel.charAt(1)]<<16,t|=Du[this._cookieChannel.charAt(2)]<<14),t!==this.key&&this.layersDirty(),this.key=t},y(t,[{key:"numCascades",get:function(){return this.cascades.length},set:function(t){this.cascades&&this.numCascades===t||(this.cascades=ku[t-1],this._shadowMatrixPalette=new Float32Array(64),this._shadowCascadeDistances=new Float32Array(4),this._destroyShadowMap(),this.updateKey())}},{key:"shadowMap",get:function(){return this._shadowMap},set:function(t){this._shadowMap!==t&&(this._destroyShadowMap(),this._shadowMap=t)}},{key:"mask",get:function(){return this._mask},set:function(t){this._mask!==t&&(this._mask=t,this.updateKey())}},{key:"numShadowFaces",get:function(){var t=this._type;return 0===t?this.numCascades:1===t?6:1}},{key:"type",get:function(){return this._type},set:function(t){if(this._type!==t){this._type=t,this._destroyShadowMap(),this.updateKey();var e=this._shadowType;this._shadowType=null,this.shadowUpdateOverrides=null,this.shadowType=e}}},{key:"shape",get:function(){return this._shape},set:function(t){if(this._shape!==t){this._shape=t,this._destroyShadowMap(),this.updateKey();var e=this._shadowType;this._shadowType=null,this.shadowType=e}}},{key:"usePhysicalUnits",get:function(){return this._usePhysicalUnits},set:function(t){this._usePhysicalUnits!==t&&(this._usePhysicalUnits=t,this._updateFinalColor())}},{key:"shadowType",get:function(){return this._shadowType},set:function(t){if(this._shadowType!==t){var e=this.device;1===this._type&&0!==t&&6!==t&&(t=0);var i=e.supportsDepthShadow;4!==t||i||(t=0),3!==t||e.textureFloatRenderable&&e.textureFloatFilterable||(t=2),2!==t||e.textureHalfFloatRenderable||(t=1),this._isVsm=t>=1&&t<=3,this._isPcf=5===t||0===t||4===t,this._shadowType=t,this._destroyShadowMap(),this.updateKey()}}},{key:"enabled",get:function(){return this._enabled},set:function(t){this._enabled!==t&&(this._enabled=t,this.layersDirty())}},{key:"castShadows",get:function(){return this._castShadows&&4!==this._mask&&0!==this._mask},set:function(t){this._castShadows!==t&&(this._castShadows=t,this._destroyShadowMap(),this.layersDirty(),this.updateKey())}},{key:"shadowResolution",get:function(){return this._shadowResolution},set:function(t){this._shadowResolution!==t&&(t=1===this._type?Math.min(t,this.device.maxCubeMapSize):Math.min(t,this.device.maxTextureSize),this._shadowResolution=t,this._destroyShadowMap())}},{key:"vsmBlurSize",get:function(){return this._vsmBlurSize},set:function(t){this._vsmBlurSize!==t&&(t%2==0&&t++,this._vsmBlurSize=t)}},{key:"normalOffsetBias",get:function(){return this._normalOffsetBias},set:function(t){this._normalOffsetBias!==t&&((!this._normalOffsetBias&&t||this._normalOffsetBias&&!t)&&this.updateKey(),this._normalOffsetBias=t)}},{key:"falloffMode",get:function(){return this._falloffMode},set:function(t){this._falloffMode!==t&&(this._falloffMode=t,this.updateKey())}},{key:"innerConeAngle",get:function(){return this._innerConeAngle},set:function(t){this._innerConeAngle!==t&&(this._innerConeAngle=t,this._innerConeAngleCos=Math.cos(t*Math.PI/180),this._usePhysicalUnits&&this._updateFinalColor())}},{key:"outerConeAngle",get:function(){return this._outerConeAngle},set:function(t){this._outerConeAngle!==t&&(this._outerConeAngle=t,this._updateOuterAngle(t),this._usePhysicalUnits&&this._updateFinalColor())}},{key:"penumbraSize",get:function(){return this._penumbraSize},set:function(t){this._penumbraSize=t}},{key:"intensity",get:function(){return this._intensity},set:function(t){this._intensity!==t&&(this._intensity=t,this._updateFinalColor())}},{key:"affectSpecularity",get:function(){return this._affectSpecularity},set:function(t){0===this._type&&(this._affectSpecularity=t,this.updateKey())}},{key:"luminance",get:function(){return this._luminance},set:function(t){this._luminance!==t&&(this._luminance=t,this._updateFinalColor())}},{key:"cookieMatrix",get:function(){return this._cookieMatrix||(this._cookieMatrix=new Ft),this._cookieMatrix}},{key:"atlasViewport",get:function(){return this._atlasViewport||(this._atlasViewport=new Pt(0,0,1,1)),this._atlasViewport}},{key:"cookie",get:function(){return this._cookie},set:function(t){this._cookie!==t&&(this._cookie=t,this.updateKey())}},{key:"cookieFalloff",get:function(){return this._cookieFalloff},set:function(t){this._cookieFalloff!==t&&(this._cookieFalloff=t,this.updateKey())}},{key:"cookieChannel",get:function(){return this._cookieChannel},set:function(t){if(this._cookieChannel!==t){if(t.length<3)for(var e=t.charAt(t.length-1),i=3-t.length,n=0;n<i;n++)t+=e;this._cookieChannel=t,this.updateKey()}}},{key:"cookieTransform",get:function(){return this._cookieTransform},set:function(t){this._cookieTransform!==t&&(this._cookieTransform=t,this._cookieTransformSet=!!t,t&&!this._cookieOffset&&(this.cookieOffset=new Et,this._cookieOffsetSet=!1),this.updateKey())}},{key:"cookieOffset",get:function(){return this._cookieOffset},set:function(t){this._cookieOffset!==t&&(!(!this._cookieTransformSet&&!t)&&!t&&this._cookieOffset?this._cookieOffset.set(0,0):this._cookieOffset=t,this._cookieOffsetSet=!!t,t&&!this._cookieTransform&&(this.cookieTransform=new Pt(1,1,0,0),this._cookieTransformSet=!1),this.updateKey())}}]),t}(),Nu=function(){function t(t,e,i){this._areaLightsEnabled=!1,this._cells=new wt(10,3,10),this._maxLightsPerCell=255,this._shadowsEnabled=!0,this._shadowType=0,this._shadowAtlasResolution=2048,this._cookiesEnabled=!1,this._cookieAtlasResolution=2048,this.debugLayer=void 0,this.atlasSplit=null,this._supportsAreaLights=t,this._maxTextureSize=e,this._dirtyLightsFnc=i}return t.prototype.applySettings=function(t){var e,i,n,s,r,a,o;this.shadowsEnabled=null!=(e=t.lightingShadowsEnabled)?e:this.shadowsEnabled,this.cookiesEnabled=null!=(i=t.lightingCookiesEnabled)?i:this.cookiesEnabled,this.areaLightsEnabled=null!=(n=t.lightingAreaLightsEnabled)?n:this.areaLightsEnabled,this.shadowAtlasResolution=null!=(s=t.lightingShadowAtlasResolution)?s:this.shadowAtlasResolution,this.cookieAtlasResolution=null!=(r=t.lightingCookieAtlasResolution)?r:this.cookieAtlasResolution,this.maxLightsPerCell=null!=(a=t.lightingMaxLightsPerCell)?a:this.maxLightsPerCell,this.shadowType=null!=(o=t.lightingShadowType)?o:this.shadowType,t.lightingCells&&(this.cell=new wt(t.lightingCells))},y(t,[{key:"cells",get:function(){return this._cells},set:function(t){this._cells.copy(t)}},{key:"maxLightsPerCell",get:function(){return this._maxLightsPerCell},set:function(t){this._maxLightsPerCell=_t.clamp(t,1,255)}},{key:"cookieAtlasResolution",get:function(){return this._cookieAtlasResolution},set:function(t){this._cookieAtlasResolution=_t.clamp(t,32,this._maxTextureSize)}},{key:"shadowAtlasResolution",get:function(){return this._shadowAtlasResolution},set:function(t){this._shadowAtlasResolution=_t.clamp(t,32,this._maxTextureSize)}},{key:"shadowType",get:function(){return this._shadowType},set:function(t){this._shadowType!==t&&(this._shadowType=t,this._dirtyLightsFnc())}},{key:"cookiesEnabled",get:function(){return this._cookiesEnabled},set:function(t){this._cookiesEnabled!==t&&(this._cookiesEnabled=t,this._dirtyLightsFnc())}},{key:"areaLightsEnabled",get:function(){return this._areaLightsEnabled},set:function(t){this._supportsAreaLights&&this._areaLightsEnabled!==t&&(this._areaLightsEnabled=t,this._dirtyLightsFnc())}},{key:"shadowsEnabled",get:function(){return this._shadowsEnabled},set:function(t){this._shadowsEnabled!==t&&(this._shadowsEnabled=t,this._dirtyLightsFnc())}}]),t}(),zu=new Ui(!0,0,1,1),Vu=function(){function t(t){var e=this;this.morph=t,t.incRefCount(),this.device=t.device,this._weights=[],this._weightMap=new Map;for(var i=0;i<t._targets.length;i++){var n=t._targets[i];n.name&&this._weightMap.set(n.name,i),this.setWeight(i,n.defaultWeight)}if(this._activeTargets=[],t.useTextureMorph){this.shaderCache={},this.maxSubmitCount=this.device.maxTextures,this._shaderMorphWeights=new Float32Array(this.maxSubmitCount);var s=function(i,n){return e[n]=t._createTexture(i,t._renderTextureFormat),new rn({colorBuffer:e[n],depth:!1})};t.morphPositions&&(this.rtPositions=s("MorphRTPos","texturePositions")),t.morphNormals&&(this.rtNormals=s("MorphRTNrm","textureNormals")),this._textureParams=new Float32Array([t.morphTextureWidth,t.morphTextureHeight,1/t.morphTextureWidth,1/t.morphTextureHeight]);for(var r=0;r<this.maxSubmitCount;r++)this["morphBlendTex"+r]=this.device.scope.resolve("morphBlendTex"+r);this.morphFactor=this.device.scope.resolve("morphFactor[0]"),this.zeroTextures=!1}else this.maxSubmitCount=8,this._shaderMorphWeights=new Float32Array(this.maxSubmitCount),this._shaderMorphWeightsA=new Float32Array(this._shaderMorphWeights.buffer,0,4),this._shaderMorphWeightsB=new Float32Array(this._shaderMorphWeights.buffer,16,4),this._activeVertexBuffers=new Array(this.maxSubmitCount)}var e=t.prototype;return e.destroy=function(){this.shader=null;var t=this.morph;t&&(this.morph=null,t.decRefCount(),t.refCount<1&&t.destroy()),this.rtPositions&&(this.rtPositions.destroy(),this.rtPositions=null),this.texturePositions&&(this.texturePositions.destroy(),this.texturePositions=null),this.rtNormals&&(this.rtNormals.destroy(),this.rtNormals=null),this.textureNormals&&(this.textureNormals.destroy(),this.textureNormals=null)},e.clone=function(){return new t(this.morph)},e._getWeightIndex=function(t){return"string"==typeof t?this._weightMap.get(t):t},e.getWeight=function(t){var e=this._getWeightIndex(t);return this._weights[e]},e.setWeight=function(t,e){var i=this._getWeightIndex(t);this._weights[i]=e,this._dirty=!0},e._getFragmentShader=function(t){var e="";t>0&&(e+="varying vec2 uv0;\nuniform highp float morphFactor["+t+"];\n");for(var i=0;i<t;i++)e+="uniform highp sampler2D morphBlendTex"+i+";\n";e+="void main (void) {\n highp vec4 color = vec4(0, 0, 0, 1);\n";for(var n=0;n<t;n++)e+=" color.xyz += morphFactor["+n+"] * texture2D(morphBlendTex"+n+", uv0).xyz;\n";return e+=" gl_FragColor = color;\n}\n"},e._getShader=function(t){var e=this.shaderCache[t];if(!e){var i=this._getFragmentShader(t);e=bo(this.device,"\n\tattribute vec2 vertex_position;\n\tvarying vec2 uv0;\n\tvoid main(void) {\n\t\tgl_Position = vec4(vertex_position, 0.5, 1.0);\n\t\tuv0 = vertex_position.xy * 0.5 + 0.5;\n\t}\n\t",i,"textureMorph"+t),this.shaderCache[t]=e}return e},e._updateTextureRenderTarget=function(t,e){for(var i=this,n=this.device,s=function(e,s){i.morphFactor.setValue(i._shaderMorphWeights),n.setBlendState(s?zu:Ui.NOBLEND);var r=i._getShader(e);Ro(n,t,r)},r=0,a=!1,o=this._activeTargets.length,h=0;h<o;h++){var l=this._activeTargets[h],c=l.target[e];c&&(this["morphBlendTex"+r].setValue(c),this._shaderMorphWeights[r]=l.weight,++r>=this.maxSubmitCount&&(s(r,a),r=0,a=!0))}(r>0||0===o&&!this.zeroTextures)&&s(r,a)},e._updateTextureMorph=function(){this.device,(this._activeTargets.length>0||!this.zeroTextures)&&(this.rtPositions&&this._updateTextureRenderTarget(this.rtPositions,"texturePositions"),this.rtNormals&&this._updateTextureRenderTarget(this.rtNormals,"textureNormals"),this.zeroTextures=0===this._activeTargets.length)},e._updateVertexMorph=function(){for(var t=this.maxSubmitCount,e=0;e<t;e++)this._shaderMorphWeights[e]=0,this._activeVertexBuffers[e]=null;for(var i=0,n=this.morph.morphPositions?4:0,s=0;s<this._activeTargets.length;s++){var r=this._activeTargets[s].target;r._vertexBufferPositions&&(this._activeVertexBuffers[i]=r._vertexBufferPositions,this._shaderMorphWeights[i]=this._activeTargets[s].weight,i++),r._vertexBufferNormals&&(this._activeVertexBuffers[n]=r._vertexBufferNormals,this._shaderMorphWeights[n]=this._activeTargets[s].weight,n++)}},e.update=function(){this._dirty=!1;for(var t=this.morph._targets,e=0,i=0;i<t.length;i++){var n=Math.abs(this.getWeight(i));if(n>1e-5){this._activeTargets.length<=e&&(this._activeTargets[e]={});var s=this._activeTargets[e++];s.absWeight=n,s.weight=this.getWeight(i),s.target=t[i]}}this._activeTargets.length=e;var r=this.morph.maxActiveTargets;this._activeTargets.length>r&&(this._activeTargets.sort((function(t,e){return t.absWeight<e.absWeight?1:e.absWeight<t.absWeight?-1:0})),this._activeTargets.length=r),this.morph.useTextureMorph?this._updateTextureMorph():this._updateVertexMorph()},t}(),Gu=function(){function t(){this.graph=null,this.meshInstances=[],this.skinInstances=[],this.morphInstances=[],this.cameras=[],this.lights=[],this._shadersVersion=0,this._immutable=!1}var e=t.prototype;return e.getGraph=function(){return this.graph},e.setGraph=function(t){this.graph=t},e.getCameras=function(){return this.cameras},e.setCameras=function(t){this.cameras=t},e.getLights=function(){return this.lights},e.setLights=function(t){this.lights=t},e.getMaterials=function(){for(var t=[],e=0;e<this.meshInstances.length;e++){var i=this.meshInstances[e];-1===t.indexOf(i.material)&&t.push(i.material)}return t},e.clone=function(){for(var e=[],i=[],n=function t(n){var s=n.clone();e.push(n),i.push(s);for(var r=0;r<n._children.length;r++)s.addChild(t(n._children[r]));return s}(this.graph),s=[],r=[],a=[],o=0;o<this.skinInstances.length;o++){for(var h=this.skinInstances[o].skin,l=new Xo(h),c=[],u=0;u<h.boneNames.length;u++){var d=h.boneNames[u],f=n.findByName(d);c.push(f)}l.bones=c,r.push(l)}for(var p=0;p<this.morphInstances.length;p++){var m=this.morphInstances[p].morph,_=new Vu(m);a.push(_)}for(var v=0;v<this.meshInstances.length;v++){var g=this.meshInstances[v],y=e.indexOf(g.node),x=new yh(g.mesh,g.material,i[y]);if(g.skinInstance){var S=this.skinInstances.indexOf(g.skinInstance);x.skinInstance=r[S]}if(g.morphInstance){var b=this.morphInstances.indexOf(g.morphInstance);x.morphInstance=a[b]}s.push(x)}var w=new t;return w.graph=n,w.meshInstances=s,w.skinInstances=r,w.morphInstances=a,w.getGraph().syncHierarchy(),w},e.destroy=function(){for(var t=this.meshInstances,e=0;e<t.length;e++)t[e].destroy();this.meshInstances.length=0},e.generateWireframe=function(){yh._prepareRenderStyleForArray(this.meshInstances,1)},t}(),Hu=function(t){function e(e,i,n){var s,r=(void 0===n?{}:n).preferHighPrecision,a=void 0!==r&&r;(s=t.call(this)||this)._aabb=void 0,s.preferHighPrecision=void 0,s.device=i||Ha.get(),s.preferHighPrecision=a,s._targets=e.slice();var o=s.device;if(o.supportsMorphTargetTexturesCore){var h=o.extTextureHalfFloat&&o.textureHalfFloatRenderable?oe:void 0,l=o.extTextureFloat&&o.textureFloatRenderable?le:void 0;s._renderTextureFormat=s.preferHighPrecision?null!=l?l:h:null!=h?h:l;var c=o.extTextureHalfFloat&&o.textureHalfFloatUpdatable?oe:void 0,u=o.extTextureFloat?he:void 0;s._textureFormat=s.preferHighPrecision?null!=u?u:c:null!=c?c:u,void 0!==s._renderTextureFormat&&void 0!==s._textureFormat&&(s._useTextureMorph=!0)}return s._init(),s._updateMorphFlags(),s}S(e,t);var i=e.prototype;return i._init=function(){if(this._useTextureMorph&&(this._useTextureMorph=this._initTextureBased()),!this._useTextureMorph)for(var t=0;t<this._targets.length;t++)this._targets[t]._initVertexBuffers(this.device);for(var e=0;e<this._targets.length;e++)this._targets[e]._postInit()},i._findSparseSet=function(t,e,i,n){for(var s=1,r=t[0].length,a=0;a<r;a+=3){for(var o=!1,h=0;h<t.length;h++){var l=t[h];if(0!==l[a]||0!==l[a+1]||0!==l[a+2]){o=!0;break}}o?(e.push(s+n),i.push(a/3),s++):e.push(0+n)}return s},i._initTextureBased=function(){for(var t=this.device.isWebGPU,e=t?0:.2,i=[],n=[],s=0;s<this._targets.length;s++){var r=this._targets[s];r.options.deltaPositions&&(i.push(r.options.deltaPositions),n.push({target:r,name:"texturePositions"})),r.options.deltaNormals&&(i.push(r.options.deltaNormals),n.push({target:r,name:"textureNormals"}))}var a=[],o=[],h=this._findSparseSet(i,a,o,e),l=Math.min(this.device.maxTextureSize,4096),c=Math.ceil(Math.sqrt(h));c=Math.min(c,l);var u=Math.ceil(h/c);if(u>l)return!1;this.morphTextureWidth=c,this.morphTextureHeight=u;var d=!1,f=3,p=$h.float2Half;this._textureFormat===oe&&(d=!0,f=4);for(var m=[],_=0;_<i.length;_++)m.push(this._createTexture("MorphTarget",this._textureFormat));for(var v=0;v<i.length;v++){var g=i[v],y=m[v],x=y.lock();if(d)for(var S=0;S<o.length;S++){var b=3*o[S],w=S*f+f;x[w]=p(g[b]),x[w+1]=p(g[b+1]),x[w+2]=p(g[b+2])}else for(var T=0;T<o.length;T++){var A=3*o[T],C=T*f+f;x[C]=g[A],x[C+1]=g[A+1],x[C+2]=g[A+2]}y.unlock(),n[v].target._setTexture(n[v].name,y)}var E=[{semantic:ti,components:1,type:t?5:6}];return this.vertexBufferIds=new ji(this.device,new Ji(this.device,E,a.length),a.length,0,t?new Uint32Array(a):new Float32Array(a)),!0},i.destroy=function(){var t;null==(t=this.vertexBufferIds)||t.destroy(),this.vertexBufferIds=null;for(var e=0;e<this._targets.length;e++)this._targets[e].destroy();this._targets.length=0},i._updateMorphFlags=function(){this._morphPositions=!1,this._morphNormals=!1;for(var t=0;t<this._targets.length;t++){var e=this._targets[t];e.morphPositions&&(this._morphPositions=!0),e.morphNormals&&(this._morphNormals=!0)}},i._createTexture=function(t,e){return new Ls(this.device,{width:this.morphTextureWidth,height:this.morphTextureHeight,format:e,cubemap:!1,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1,name:t})},y(e,[{key:"aabb",get:function(){if(!this._aabb){for(var t=new wt,e=new wt,i=0;i<this._targets.length;i++){var n=this._targets[i].aabb;t.min(n.getMin()),e.max(n.getMax())}this._aabb=new Ht,this._aabb.setMinMax(t,e)}return this._aabb}},{key:"morphPositions",get:function(){return this._morphPositions}},{key:"morphNormals",get:function(){return this._morphNormals}},{key:"maxActiveTargets",get:function(){return this._useTextureMorph?this._targets.length:this._morphPositions&&this._morphNormals?4:8}},{key:"useTextureMorph",get:function(){return this._useTextureMorph}},{key:"targets",get:function(){return this._targets}}]),e}(Ga),Wu=function(){function t(t){this.used=!1,2===arguments.length&&(t=arguments[1]),this.options=t,this._name=t.name,this._defaultWeight=t.defaultWeight||0,this._aabb=t.aabb,this.deltaPositions=t.deltaPositions}var e=t.prototype;return e.destroy=function(){var t,e,i,n;null==(t=this._vertexBufferPositions)||t.destroy(),this._vertexBufferPositions=null,null==(e=this._vertexBufferNormals)||e.destroy(),this._vertexBufferNormals=null,null==(i=this.texturePositions)||i.destroy(),this.texturePositions=null,null==(n=this.textureNormals)||n.destroy(),this.textureNormals=null},e.clone=function(){return new t(this.options)},e._postInit=function(){this.options.preserveData||(this.options=null),this.used=!0},e._initVertexBuffers=function(t){var e=this.options;this._vertexBufferPositions=this._createVertexBuffer(t,e.deltaPositions,e.deltaPositionsType),this._vertexBufferNormals=this._createVertexBuffer(t,e.deltaNormals,e.deltaNormalsType),this._vertexBufferPositions&&(this.deltaPositions=this._vertexBufferPositions.lock())},e._createVertexBuffer=function(t,e,i){return void 0===i&&(i=6),e?new ji(t,new Ji(t,[{semantic:Ne,components:3,type:i}]),e.length/3,0,e):null},e._setTexture=function(t,e){this[t]=e},y(t,[{key:"name",get:function(){return this._name}},{key:"defaultWeight",get:function(){return this._defaultWeight}},{key:"aabb",get:function(){return this._aabb||(this._aabb=new Ht,this.deltaPositions&&this._aabb.compute(this.deltaPositions)),this._aabb}},{key:"morphPositions",get:function(){return!!this._vertexBufferPositions||!!this.texturePositions}},{key:"morphNormals",get:function(){return!!this._vertexBufferNormals||!!this.textureNormals}}]),t}(),Xu=function(t){function e(){return t.apply(this,arguments)||this}S(e,t);var i=e.prototype;return i.generateKey=function(t){var e="particle";for(var i in t)t.hasOwnProperty(i)&&(e+=t[i]);return e},i._animTex=function(t){var e="";return e+=t.animTexLoop?_o.particleAnimFrameLoopVS:_o.particleAnimFrameClampVS,e+=_o.particleAnimTexVS},i.createShaderDefinition=function(t,e){var i="#define PARTICLE_"+(e.useCpu?"CPU":"GPU")+"\n",n="#define PARTICLE\n"+i,s="#define VERTEXSHADER\n"+i;e.mesh&&(s+="#define USE_MESH\n"),e.localSpace&&(s+="#define LOCAL_SPACE\n"),e.screenSpace&&(s+="#define SCREEN_SPACE\n"),e.animTex&&(s+="\nuniform vec2 animTexTilesParams;\n"),e.animTex&&(s+="\nuniform vec4 animTexParams;\n"),e.animTex&&(s+="\nuniform vec2 animTexIndexParams;\n"),2===e.normal&&(s+="\nvarying mat3 ParticleMat;\n"),1===e.normal&&(s+="\nvarying vec3 Normal;\n"),e.soft&&(s+="\nvarying float vDepth;\n");var r=e.customFace?_o.particle_customFaceVS:_o.particle_billboardVS;return e.useCpu?(e.soft>0&&(s+=_o.screenDepthPS),s+=_o.particle_cpuVS,e.localSpace&&(s+=_o.particle_localShiftVS),e.animTex&&(s+=this._animTex(e)),e.alignToMotion&&(s+=_o.particle_pointAlongVS),s+=e.mesh?_o.particle_meshVS:r,1===e.normal&&(s+=_o.particle_normalVS),2===e.normal&&(s+=_o.particle_TBNVS),e.stretch>0&&(s+=_o.particle_stretchVS),s+=_o.particle_cpu_endVS,e.soft>0&&(s+=_o.particle_softVS)):(s+=_o.particle_initVS,s+=e.pack8?_o.particleInputRgba8PS:_o.particleInputFloatPS,e.soft>0&&(s+=_o.screenDepthPS),s+=_o.particleVS,e.localSpace&&(s+=_o.particle_localShiftVS),e.animTex&&(s+=this._animTex(e)),e.wrap&&(s+=_o.particle_wrapVS),e.alignToMotion&&(s+=_o.particle_pointAlongVS),s+=e.mesh?_o.particle_meshVS:r,1===e.normal&&(s+=_o.particle_normalVS),2===e.normal&&(s+=_o.particle_TBNVS),e.stretch>0&&(s+=_o.particle_stretchVS),s+=_o.particle_endVS,e.soft>0&&(s+=_o.particle_softVS)),s+="}\n",e.normal>0&&(1===e.normal?n+="\nvarying vec3 Normal;\n":2===e.normal&&(n+="\nvarying mat3 ParticleMat;\n"),n+="\nuniform vec3 lightCube[6];\n"),e.soft&&(n+="\nvarying float vDepth;\n"),0===e.normal&&"none"===e.fog&&(e.srgb=!1),n+=_o.decodePS,n+=xo.gammaCode(e.gamma),n+=xo.tonemapCode(e.toneMap),"linear"===e.fog?n+=_o.fogLinearPS:"exp"===e.fog?n+=_o.fogExpPS:"exp2"===e.fog?n+=_o.fogExp2PS:n+=_o.fogNonePS,2===e.normal&&(n+="\nuniform sampler2D normalMap;\n"),e.soft>0&&(n+=_o.screenDepthPS),n+=_o.particlePS,e.soft>0&&(n+=_o.particle_softPS),1===e.normal&&(n+="\nvec3 normal = Normal;\n"),2===e.normal&&(n+=_o.particle_normalMapPS),e.normal>0&&(n+=e.halflambert?_o.particle_halflambertPS:_o.particle_lambertPS),e.normal>0&&(n+=_o.particle_lightingPS),2===e.blend?n+=_o.particle_blendNormalPS:1===e.blend?n+=_o.particle_blendAddPS:5===e.blend&&(n+=_o.particle_blendMultiplyPS),n+=_o.particle_endPS,ir.createDefinition(t,{name:"ParticleShader",vertexCode:s,fragmentCode:n})},e}(xo),ju=new Xu,qu=1,Yu=new Ft,Ku=new Ft,Zu=new wt,Qu=new wt,$u=new wt,Ju=new wt,td=new wt,ed=new wt,id=new wt,nd=new wt,sd=new wt,rd=new wt,ad=new wt,od=new wt,hd=new wt;function ld(t){return t-Math.floor(t)}function cd(t){return Math.max(Math.min(t,1),0)}function ud(t,e){return t-e*Math.floor(t/e)}function dd(t){var e=ld(t),i=ld(255*t);return[e-=i/255,i-=i/255]}var fd=function(){function t(t){this._emitter=t}var e=t.prototype;return e.calcSpawnPosition=function(t,e,i,n,s){var r=this._emitter,a=Math.random(),o=Math.random(),h=Math.random(),l=Math.random();if(r.useCpu&&(t[4*s+0+2*r.numParticlesPot*4]=a,t[4*s+1+2*r.numParticlesPot*4]=o,t[4*s+2+2*r.numParticlesPot*4]=h),Qu.x=a-.5,Qu.y=o-.5,Qu.z=h-.5,0===r.emitterShape){var c=Math.max(Math.abs(Qu.x),Math.max(Math.abs(Qu.y),Math.abs(Qu.z))),u=c+(.5-c)*i[0],d=c+(.5-c)*i[1],f=c+(.5-c)*i[2];Qu.x=u*(c===Math.abs(Qu.x)?Math.sign(Qu.x):2*Qu.x),Qu.y=d*(c===Math.abs(Qu.y)?Math.sign(Qu.y):2*Qu.y),Qu.z=f*(c===Math.abs(Qu.z)?Math.sign(Qu.z):2*Qu.z),r.localSpace?Zu.copy(e.transformPoint(Qu)):Zu.copy(n).add(e.transformPoint(Qu))}else{Qu.normalize();var p=0===r.emitterRadius?0:r.emitterRadiusInner/r.emitterRadius,m=l*(1-p)+p;r.localSpace?Zu.copy(Qu.mulScalar(m*r.emitterRadius)):Zu.copy(n).add(Qu.mulScalar(m*r.emitterRadius))}var _,v,g,y,x,S=-_t.lerp(r.rate,r.rate2,a)*s;if(r.pack8){var b=(Zu.x-r.worldBounds.center.x)/r.worldBoundsSize.x+.5,w=(Zu.y-r.worldBounds.center.y)/r.worldBoundsSize.y+.5,T=(Zu.z-r.worldBounds.center.z)/r.worldBoundsSize.z+.5,A=_t.lerp(r.startAngle*_t.DEG_TO_RAD,r.startAngle2*_t.DEG_TO_RAD,a);A=A%(2*Math.PI)/(2*Math.PI);var C=dd(b);t[4*s]=C[0],t[4*s+1]=C[1];var E=dd(w);t[4*s+2]=E[0],t[4*s+3]=E[1];var M=dd(T);t[4*s+0+4*r.numParticlesPot]=M[0],t[4*s+1+4*r.numParticlesPot]=M[1];var P=dd(A);t[4*s+2+4*r.numParticlesPot]=P[0],t[4*s+3+4*r.numParticlesPot]=P[1];t[4*s+3+4*r.numParticlesPot*2]=1;var R=Math.max(r.lifetime,(r.numParticles-1)*Math.max(r.rate,r.rate2)),I=r.lifetime+1,L=(v=ld(_=S=(S+R)/(R+I)),g=ld(255*_),y=ld(65025*_),x=ld(160581375*_),[v-=g/255,g-=y/255,y-=x/255,x-=x/255]);t[4*s+0+4*r.numParticlesPot*3]=L[0],t[4*s+1+4*r.numParticlesPot*3]=L[1],t[4*s+2+4*r.numParticlesPot*3]=L[2],t[4*s+3+4*r.numParticlesPot*3]=L[3]}else t[4*s]=Zu.x,t[4*s+1]=Zu.y,t[4*s+2]=Zu.z,t[4*s+3]=_t.lerp(r.startAngle*_t.DEG_TO_RAD,r.startAngle2*_t.DEG_TO_RAD,a),t[4*s+3+4*r.numParticlesPot]=S},e.update=function(t,e,i,n,s,r,a,o){var h,l,c,u=this._emitter;if(u.meshInstance.node){for(var d=u.meshInstance.node.worldTransform,f=0;f<12;f++)Yu.data[f]=d.data[f];Ku.copy(Yu),Ku.invert(),xu=u.meshInstance.node.localScale,qu=Math.max(Math.max(xu.x,xu.y),xu.z)}r=null===u.meshInstance.node||u.localSpace?wt.ZERO:u.meshInstance.node.getPosition();for(var p,m,_,v,g,y,x,S,b=u.camera?u.camera._node.getPosition():wt.ZERO,w=u.useMesh?17:15,T=u.precision-1,A=0;A<u.numParticles;A++){var C=Math.floor(u.vbCPU[A*u.numParticleVerts*(u.useMesh?6:4)+3]),E=i[4*C+0+2*u.numParticlesPot*4];$u.x=E,$u.y=i[4*C+1+2*u.numParticlesPot*4],$u.z=i[4*C+2+2*u.numParticlesPot*4];var M=u.rate+(u.rate2-u.rate)*E,P=u.lifetime,R=i[4*C+3+4*u.numParticlesPot]+a,I=cd(R/P),L=0,D=0;(R-a<=0||R>=P)&&this.calcSpawnPosition(i,n,s,r,C);var O=R>0&&R<P;O&&(c=I*T,p=Math.floor(c),m=Math.ceil(c),c%=1,_=(h=u.qRotSpeed[p])+((l=u.qRotSpeed[m])-h)*c,v=(h=u.qRotSpeed2[p])+((l=u.qRotSpeed2[m])-h)*c,L=(h=u.qScale[p])+((l=u.qScale[m])-h)*c,g=(h=u.qScale2[p])+((l=u.qScale2[m])-h)*c,y=(h=u.qAlpha[p])+((l=u.qAlpha[m])-h)*c,x=(h=u.qAlpha2[p])+((l=u.qAlpha2[m])-h)*c,S=(h=u.qRadialSpeed[p])+((l=u.qRadialSpeed[m])-h)*c,S+=100*E%1*((h=u.qRadialSpeed2[p])+((l=u.qRadialSpeed2[m])-h)*c-S),Ju.x=i[4*C],Ju.y=i[4*C+1],Ju.z=i[4*C+2],u.localSpace?sd.copy(Ju):sd.copy(Ju).sub(r),sd.normalize().mulScalar(S),p*=3,m*=3,h=u.qLocalVelocity[p],l=u.qLocalVelocity[m],ed.x=h+(l-h)*c,h=u.qLocalVelocity[p+1],l=u.qLocalVelocity[m+1],ed.y=h+(l-h)*c,h=u.qLocalVelocity[p+2],l=u.qLocalVelocity[m+2],ed.z=h+(l-h)*c,h=u.qLocalVelocity2[p],l=u.qLocalVelocity2[m],nd.x=h+(l-h)*c,h=u.qLocalVelocity2[p+1],l=u.qLocalVelocity2[m+1],nd.y=h+(l-h)*c,h=u.qLocalVelocity2[p+2],l=u.qLocalVelocity2[m+2],nd.z=h+(l-h)*c,h=u.qVelocity[p],l=u.qVelocity[m],td.x=h+(l-h)*c,h=u.qVelocity[p+1],l=u.qVelocity[m+1],td.y=h+(l-h)*c,h=u.qVelocity[p+2],l=u.qVelocity[m+2],td.z=h+(l-h)*c,h=u.qVelocity2[p],l=u.qVelocity2[m],id.x=h+(l-h)*c,h=u.qVelocity2[p+1],l=u.qVelocity2[m+1],id.y=h+(l-h)*c,h=u.qVelocity2[p+2],l=u.qVelocity2[m+2],id.z=h+(l-h)*c,ed.x+=(nd.x-ed.x)*$u.x,ed.y+=(nd.y-ed.y)*$u.y,ed.z+=(nd.z-ed.z)*$u.z,u.initialVelocity>0&&(1===u.emitterShape?(Qu.copy($u).mulScalar(2).sub(wt.ONE).normalize(),ed.add(Qu.mulScalar(u.initialVelocity))):ed.add(wt.FORWARD.mulScalar(u.initialVelocity))),td.x+=(id.x-td.x)*$u.x,td.y+=(id.y-td.y)*$u.y,td.z+=(id.z-td.z)*$u.z,_+=(v-_)*$u.y,L=(L+1e4*E%1*(g-L))*qu,D=1e3*E%1*(x-y),u.meshInstance.node&&(u.localSpace?(ed.x/=xu.x,ed.y/=xu.y,ed.z/=xu.z):Yu.transformPoint(ed,ed)),u.localSpace?(Ku.transformPoint(td,td),ed.add(td).add(sd)):(ed.add(td.mul(xu)),ed.add(sd.mul(xu))),od.copy(ed),rd.copy(Ju).add(ed.mulScalar(a)),ad.copy(rd),i[4*C]=ad.x,i[4*C+1]=ad.y,i[4*C+2]=ad.z,i[4*C+3]+=_*a,u.wrap&&u.wrapBounds&&(u.localSpace||ad.sub(r),ad.x=ud(ad.x,u.wrapBounds.x)-.5*u.wrapBounds.x,ad.y=ud(ad.y,u.wrapBounds.y)-.5*u.wrapBounds.y,ad.z=ud(ad.z,u.wrapBounds.z)-.5*u.wrapBounds.z,u.localSpace||ad.add(r)),u.sort>0&&(1===u.sort?(hd.copy(ad).sub(b),u.particleDistance[C]=-(hd.x*hd.x+hd.y*hd.y+hd.z*hd.z)):2===u.sort?u.particleDistance[C]=R:3===u.sort&&(u.particleDistance[C]=-R))),o?R<0&&(i[4*C+3+2*u.numParticlesPot*4]=-1):(R>=P&&(R-=Math.max(P,(u.numParticles-1)*M),i[4*C+3+2*u.numParticlesPot*4]=u.loop?1:-1),R<0&&u.loop&&(i[4*C+3+2*u.numParticlesPot*4]=1)),i[4*C+3+2*u.numParticlesPot*4]<0&&(O=!1),i[4*C+3+4*u.numParticlesPot]=R;for(var k=0;k<u.numParticleVerts;k++){var F=(A*u.numParticleVerts+k)*(u.useMesh?6:4),B=u.vbCPU[F],U=u.vbCPU[F+1],N=u.vbCPU[F+2];O||(B=U=N=0);var z=A*u.numParticleVerts*w+k*w;t[z]=ad.x,t[z+1]=ad.y,t[z+2]=ad.z,t[z+3]=I,t[z+4]=u.alignToMotion?0:i[4*C+3],t[z+5]=L,t[z+6]=D,t[z+7]=od.x,t[z+8]=B,t[z+9]=U,t[z+10]=N,t[z+11]=od.y,t[z+12]=C,t[z+13]=od.z,t[z+14]=u.vbCPU[F+3],u.useMesh&&(t[z+15]=u.vbCPU[F+4],t[z+16]=u.vbCPU[F+5])}}if(u.sort>0&&u.camera){for(var V=u.useMesh?6:4,G=u.particleDistance,H=0;H<u.numParticles;H++)e[H][0]=H,e[H][1]=G[Math.floor(u.vbCPU[H*u.numParticleVerts*V+3])];u.vbOld.set(u.vbCPU),e.sort((function(t,e){return t[1]-e[1]}));for(var W=0;W<u.numParticles;W++)for(var X=e[W][0]*u.numParticleVerts*V,j=W*u.numParticleVerts*V,q=0;q<u.numParticleVerts*V;q++)u.vbCPU[j+q]=u.vbOld[X+q]}},t}(),pd=new At,md=new At,_d=new At,vd=function(){function t(t,e){this._emitter=t,this.frameRandomUniform=new Float32Array(3),this.emitterPosUniform=new Float32Array(3),this.emitterScaleUniform=new Float32Array([1,1,1]),this.worldBoundsMulUniform=new Float32Array(3),this.worldBoundsAddUniform=new Float32Array(3),this.inBoundsSizeUniform=new Float32Array(3),this.inBoundsCenterUniform=new Float32Array(3),this.constantParticleTexIN=e.scope.resolve("particleTexIN"),this.constantParticleTexOUT=e.scope.resolve("particleTexOUT"),this.constantEmitterPos=e.scope.resolve("emitterPos"),this.constantEmitterScale=e.scope.resolve("emitterScale"),this.constantSpawnBounds=e.scope.resolve("spawnBounds"),this.constantSpawnPosInnerRatio=e.scope.resolve("spawnPosInnerRatio"),this.constantSpawnBoundsSphere=e.scope.resolve("spawnBoundsSphere"),this.constantSpawnBoundsSphereInnerRatio=e.scope.resolve("spawnBoundsSphereInnerRatio"),this.constantInitialVelocity=e.scope.resolve("initialVelocity"),this.constantFrameRandom=e.scope.resolve("frameRandom"),this.constantDelta=e.scope.resolve("delta"),this.constantRate=e.scope.resolve("rate"),this.constantRateDiv=e.scope.resolve("rateDiv"),this.constantLifetime=e.scope.resolve("lifetime"),this.constantGraphSampleSize=e.scope.resolve("graphSampleSize"),this.constantGraphNumSamples=e.scope.resolve("graphNumSamples"),this.constantInternalTex0=e.scope.resolve("internalTex0"),this.constantInternalTex1=e.scope.resolve("internalTex1"),this.constantInternalTex2=e.scope.resolve("internalTex2"),this.constantInternalTex3=e.scope.resolve("internalTex3"),this.constantEmitterMatrix=e.scope.resolve("emitterMatrix"),this.constantEmitterMatrixInv=e.scope.resolve("emitterMatrixInv"),this.constantNumParticles=e.scope.resolve("numParticles"),this.constantNumParticlesPot=e.scope.resolve("numParticlesPot"),this.constantLocalVelocityDivMult=e.scope.resolve("localVelocityDivMult"),this.constantVelocityDivMult=e.scope.resolve("velocityDivMult"),this.constantRotSpeedDivMult=e.scope.resolve("rotSpeedDivMult"),this.constantSeed=e.scope.resolve("seed"),this.constantStartAngle=e.scope.resolve("startAngle"),this.constantStartAngle2=e.scope.resolve("startAngle2"),this.constantOutBoundsMul=e.scope.resolve("outBoundsMul"),this.constantOutBoundsAdd=e.scope.resolve("outBoundsAdd"),this.constantInBoundsSize=e.scope.resolve("inBoundsSize"),this.constantInBoundsCenter=e.scope.resolve("inBoundsCenter"),this.constantMaxVel=e.scope.resolve("maxVel"),this.constantFaceTangent=e.scope.resolve("faceTangent"),this.constantFaceBinorm=e.scope.resolve("faceBinorm")}var e=t.prototype;return e._setInputBounds=function(){this.inBoundsSizeUniform[0]=this._emitter.prevWorldBoundsSize.x,this.inBoundsSizeUniform[1]=this._emitter.prevWorldBoundsSize.y,this.inBoundsSizeUniform[2]=this._emitter.prevWorldBoundsSize.z,this.constantInBoundsSize.setValue(this.inBoundsSizeUniform),this.inBoundsCenterUniform[0]=this._emitter.prevWorldBoundsCenter.x,this.inBoundsCenterUniform[1]=this._emitter.prevWorldBoundsCenter.y,this.inBoundsCenterUniform[2]=this._emitter.prevWorldBoundsCenter.z,this.constantInBoundsCenter.setValue(this.inBoundsCenterUniform)},e.randomize=function(){this.frameRandomUniform[0]=Math.random(),this.frameRandomUniform[1]=Math.random(),this.frameRandomUniform[2]=Math.random()},e.update=function(t,e,i,n,s){var r=this._emitter;t.setBlendState(Ui.NOBLEND),t.setDepthState(Ni.NODEPTH),t.setCullMode(se),this.randomize(),this.constantGraphSampleSize.setValue(1/r.precision),this.constantGraphNumSamples.setValue(r.precision),this.constantNumParticles.setValue(r.numParticles),this.constantNumParticlesPot.setValue(r.numParticlesPot),this.constantInternalTex0.setValue(r.internalTex0),this.constantInternalTex1.setValue(r.internalTex1),this.constantInternalTex2.setValue(r.internalTex2),this.constantInternalTex3.setValue(r.internalTex3);var a=r.meshInstance.node,o=null===a?wt.ONE:a.localScale;if(r.pack8){this.worldBoundsMulUniform[0]=r.worldBoundsMul.x,this.worldBoundsMulUniform[1]=r.worldBoundsMul.y,this.worldBoundsMulUniform[2]=r.worldBoundsMul.z,this.constantOutBoundsMul.setValue(this.worldBoundsMulUniform),this.worldBoundsAddUniform[0]=r.worldBoundsAdd.x,this.worldBoundsAddUniform[1]=r.worldBoundsAdd.y,this.worldBoundsAddUniform[2]=r.worldBoundsAdd.z,this.constantOutBoundsAdd.setValue(this.worldBoundsAddUniform),this._setInputBounds();var h=r.maxVel*Math.max(Math.max(o.x,o.y),o.z);h=Math.max(h,1),this.constantMaxVel.setValue(h)}var l=null===a||r.localSpace?wt.ZERO:a.getPosition(),c=null===a?Ft.IDENTITY:a.getWorldTransform();0===r.emitterShape?(pd.setFromMat4(e),this.constantSpawnBounds.setValue(pd.data),this.constantSpawnPosInnerRatio.setValue(i)):(this.constantSpawnBoundsSphere.setValue(r.emitterRadius),this.constantSpawnBoundsSphereInnerRatio.setValue(0===r.emitterRadius?0:r.emitterRadiusInner/r.emitterRadius)),this.constantInitialVelocity.setValue(r.initialVelocity),md.setFromMat4(c),_d.invertMat4(c),this.emitterPosUniform[0]=l.x,this.emitterPosUniform[1]=l.y,this.emitterPosUniform[2]=l.z,this.constantEmitterPos.setValue(this.emitterPosUniform),this.constantFrameRandom.setValue(this.frameRandomUniform),this.constantDelta.setValue(n),this.constantRate.setValue(r.rate),this.constantRateDiv.setValue(r.rate2-r.rate),this.constantStartAngle.setValue(r.startAngle*_t.DEG_TO_RAD),this.constantStartAngle2.setValue(r.startAngle2*_t.DEG_TO_RAD),this.constantSeed.setValue(r.seed),this.constantLifetime.setValue(r.lifetime),this.emitterScaleUniform[0]=o.x,this.emitterScaleUniform[1]=o.y,this.emitterScaleUniform[2]=o.z,this.constantEmitterScale.setValue(this.emitterScaleUniform),this.constantEmitterMatrix.setValue(md.data),this.constantEmitterMatrixInv.setValue(_d.data),this.constantLocalVelocityDivMult.setValue(r.localVelocityUMax),this.constantVelocityDivMult.setValue(r.velocityUMax),this.constantRotSpeedDivMult.setValue(r.rotSpeedUMax[0]);var u=r.swapTex?r.particleTexOUT:r.particleTexIN;u=r.beenReset?r.particleTexStart:u;var d=r.swapTex?r.particleTexIN:r.particleTexOUT;this.constantParticleTexIN.setValue(u),Ro(t,r.swapTex?r.rtParticleTexIN:r.rtParticleTexOUT,s?r.shaderParticleUpdateOnStop:r.loop?r.shaderParticleUpdateRespawn:r.shaderParticleUpdateNoRespawn),r.material.setParameter("particleTexOUT",u),r.material.setParameter("particleTexIN",d),r.beenReset=!1,r.swapTex=!r.swapTex,r.prevWorldBoundsSize.copy(r.worldBoundsSize),r.prevWorldBoundsCenter.copy(r.worldBounds.center),r.pack8&&this._setInputBounds()},t}(),gd=[[-1,-1],[1,-1],[1,1],[-1,1]];function yd(t,e,i,n,s,r,a){void 0===s&&(s=le);var o=0;a&&7===s&&(o=1);var h=new Ls(t,{width:e,height:i,format:s,cubemap:!1,mipmaps:!1,minFilter:o,magFilter:o,addressU:1,addressV:1,name:"ParticleSystemTexture"}),l=h.lock();if(7===s){for(var c=new Uint8Array(n.length),u=0;u<n.length;u++)c[u]=n[u]*r*255;n=c}return l.set(n),h.unlock(),h}function xd(t){return Math.max(Math.min(t,1),0)}var Sd,bd,wd=new St([0,0,1,0]),Td=new St([0,1,1,1]),Ad=new bt([0,0,1,0],[0,0,1,0],[0,0,1,0]),Cd=new bt([0,1,1,1],[0,1,1,1],[0,1,1,1]),Ed=2,Md=new Float32Array(3),Pd=new Ft,Rd=new wt,Id=new wt,Ld=new wt;function Dd(t,e){void 0!==bd[t]&&null!==bd[t]?Sd[t]=bd[t]:Sd[t]=e}function Od(t,e,i){return(255*t<<16|255*e<<8|255*i)/(1<<24)}function kd(t,e){for(var i=t.length/3,n=new Array(4*i),s=0;s<i;s++)n[4*s]=t[3*s],n[4*s+1]=t[3*s+1],n[4*s+2]=t[3*s+2],n[4*s+3]=Od(e[3*s],e[3*s+1],e[3*s+2]);return n}function Fd(t,e){for(var i=e.length,n=t.length/i,s=0;s<n;s++)for(var r=0;r<i;r++){var a=Math.abs(t[s*i+r]);e[r]=Math.max(e[r],a)}}function Bd(t,e,i){var n=function(t,e){for(var i=new Float32Array(t.length),n=0;n<t.length;n++)i[n]=t[n]-e[n];return i}(e,t);return Fd(n,i),function(t,e){for(var i=e.length,n=t.length/i,s=0;s<n;s++)for(var r=0;r<i;r++)t[s*i+r]/=0===e[r]?1:e[r],t[s*i+r]*=.5,t[s*i+r]+=.5}(n,i),n}var Ud=new Bs,Nd=function(){function t(t,e){this.graphicsDevice=t;var i=t;this.precision=32,this._addTimeTime=0,Sd=this,bd=e,Dd("numParticles",1),this.numParticles>t.maxTextureSize&&(this.numParticles=t.maxTextureSize),Dd("rate",1),Dd("rate2",this.rate),Dd("lifetime",50),Dd("emitterExtents",new wt(0,0,0)),Dd("emitterExtentsInner",new wt(0,0,0)),Dd("emitterRadius",0),Dd("emitterRadiusInner",0),Dd("emitterShape",0),Dd("initialVelocity",1),Dd("wrap",!1),Dd("localSpace",!1),Dd("screenSpace",!1),Dd("wrapBounds",null),Dd("colorMap",this.defaultParamTexture),Dd("normalMap",null),Dd("loop",!0),Dd("preWarm",!1),Dd("sort",0),Dd("mode",0),Dd("scene",null),Dd("lighting",!1),Dd("halfLambert",!1),Dd("intensity",1),Dd("stretch",0),Dd("alignToMotion",!1),Dd("depthSoftening",0),Dd("mesh",null),Dd("particleNormal",new wt(0,1,0)),Dd("orientation",0),Dd("depthWrite",!1),Dd("noFog",!1),Dd("blendType",2),Dd("node",null),Dd("startAngle",0),Dd("startAngle2",this.startAngle),Dd("animTilesX",1),Dd("animTilesY",1),Dd("animStartFrame",0),Dd("animNumFrames",1),Dd("animNumAnimations",1),Dd("animIndex",0),Dd("randomizeAnimIndex",!1),Dd("animSpeed",1),Dd("animLoop",!0),this._gpuUpdater=new vd(this,i),this._cpuUpdater=new fd(this),this.emitterPosUniform=new Float32Array(3),this.wrapBoundsUniform=new Float32Array(3),this.emitterScaleUniform=new Float32Array([1,1,1]),Dd("colorGraph",Cd),Dd("colorGraph2",this.colorGraph),Dd("scaleGraph",Td),Dd("scaleGraph2",this.scaleGraph),Dd("alphaGraph",Td),Dd("alphaGraph2",this.alphaGraph),Dd("localVelocityGraph",Ad),Dd("localVelocityGraph2",this.localVelocityGraph),Dd("velocityGraph",Ad),Dd("velocityGraph2",this.velocityGraph),Dd("rotationSpeedGraph",wd),Dd("rotationSpeedGraph2",this.rotationSpeedGraph),Dd("radialSpeedGraph",wd),Dd("radialSpeedGraph2",this.radialSpeedGraph),this.animTilesParams=new Float32Array(2),this.animParams=new Float32Array(4),this.animIndexParams=new Float32Array(2),this.internalTex0=null,this.internalTex1=null,this.internalTex2=null,this.colorParam=null,this.vbToSort=null,this.vbOld=null,this.particleDistance=null,this.camera=null,this.swapTex=!1,this.useMesh=!0,this.useCpu=!t.supportsGpuParticles,this.pack8=!0,this.localBounds=new Ht,this.worldBoundsNoTrail=new Ht,this.worldBoundsTrail=[new Ht,new Ht],this.worldBounds=new Ht,this.worldBoundsSize=new wt,this.prevWorldBoundsSize=new wt,this.prevWorldBoundsCenter=new wt,this.prevEmitterExtents=this.emitterExtents,this.prevEmitterRadius=this.emitterRadius,this.worldBoundsMul=new wt,this.worldBoundsAdd=new wt,this.timeToSwitchBounds=0,this.shaderParticleUpdateRespawn=null,this.shaderParticleUpdateNoRespawn=null,this.shaderParticleUpdateOnStop=null,this.numParticleVerts=0,this.numParticleIndices=0,this.material=null,this.meshInstance=null,this.drawOrder=0,this.seed=Math.random(),this.fixedTimeStep=1/60,this.maxSubSteps=10,this.simTime=0,this.simTimeTotal=0,this.beenReset=!1,this._layer=null,this.rebuild()}var e=t.prototype;return e.onChangeCamera=function(){this.regenShader(),this.resetMaterial()},e.calculateBoundsMad=function(){this.worldBoundsMul.x=1/this.worldBoundsSize.x,this.worldBoundsMul.y=1/this.worldBoundsSize.y,this.worldBoundsMul.z=1/this.worldBoundsSize.z,this.worldBoundsAdd.copy(this.worldBounds.center).mul(this.worldBoundsMul).mulScalar(-1),this.worldBoundsAdd.x+=.5,this.worldBoundsAdd.y+=.5,this.worldBoundsAdd.z+=.5},e.calculateWorldBounds=function(){if(this.node){if(this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),!this.useCpu){(0===this.emitterShape?!this.emitterExtents.equals(this.prevEmitterExtents):!(this.emitterRadius===this.prevEmitterRadius))&&this.calculateLocalBounds()}var t=this.node.getWorldTransform();this.localSpace?this.worldBoundsNoTrail.copy(this.localBounds):this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,t),this.worldBoundsTrail[0].add(this.worldBoundsNoTrail),this.worldBoundsTrail[1].add(this.worldBoundsNoTrail);var e=this.simTimeTotal;e>=this.timeToSwitchBounds&&(this.worldBoundsTrail[0].copy(this.worldBoundsTrail[1]),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.timeToSwitchBounds=e+this.lifetime),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.localSpace?(this.meshInstance.aabb.setFromTransformedAabb(this.worldBounds,t),this.meshInstance.mesh.aabb.setFromTransformedAabb(this.worldBounds,t)):(this.meshInstance.aabb.copy(this.worldBounds),this.meshInstance.mesh.aabb.copy(this.worldBounds)),this.meshInstance._aabbVer=1-this.meshInstance._aabbVer,this.pack8&&this.calculateBoundsMad()}},e.resetWorldBounds=function(){this.node&&(this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,this.localSpace?Ft.IDENTITY:this.node.getWorldTransform()),this.worldBoundsTrail[0].copy(this.worldBoundsNoTrail),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.simTimeTotal=0,this.timeToSwitchBounds=0)},e.calculateLocalBounds=function(){for(var t,e,i,n=Number.MAX_VALUE,s=Number.MAX_VALUE,r=Number.MAX_VALUE,a=-Number.MAX_VALUE,o=-Number.MAX_VALUE,h=-Number.MAX_VALUE,l=0,c=0,u=this.lifetime/this.precision,d=[this.qVelocity,this.qVelocity2],f=[this.qLocalVelocity,this.qLocalVelocity2],p=[0,0],m=[0,0],_=[0,0],v=[0,0],g=[0,0],y=0;y<this.precision+1;y++){for(var x=Math.min(y,this.precision-1),S=0;S<2;S++)t=f[S][3*x+0]*u+p[S],e=f[S][3*x+1]*u+m[S],i=f[S][3*x+2]*u+_[S],n=Math.min(t,n),s=Math.min(e,s),r=Math.min(i,r),a=Math.max(t,a),o=Math.max(e,o),h=Math.max(i,h),p[S]=t,m[S]=e,_[S]=i;for(var b=0;b<2;b++)g[b]+=u*Math.sqrt(d[b][3*x+0]*d[b][3*x+0]+d[b][3*x+1]*d[b][3*x+1]+d[b][3*x+2]*d[b][3*x+2]);v[0]+=this.qRadialSpeed[x]*u,v[1]+=this.qRadialSpeed2[x]*u,l=Math.max(l,Math.max(Math.abs(v[0]),Math.abs(v[1]))),c=Math.max(c,this.qScale[x])}0===this.emitterShape?(t=.5*this.emitterExtents.x,e=.5*this.emitterExtents.y,i=.5*this.emitterExtents.z):(t=this.emitterRadius,e=this.emitterRadius,i=this.emitterRadius);var w=Math.max(g[0],g[1]);Id.x=n-c-t-l-w,Id.y=s-c-e-l-w,Id.z=r-c-i-l-w,Ld.x=a+c+t+l+w,Ld.y=o+c+e+l+w,Ld.z=h+c+i+l+w,this.localBounds.setMinMax(Id,Ld)},e.rebuild=function(){var t=this.graphicsDevice;(null===this.colorMap&&(this.colorMap=this.defaultParamTexture),this.spawnBounds=0===this.emitterShape?this.emitterExtents:this.emitterRadius,this.useCpu=this.useCpu||this.sort>0||t.maxVertexTextures<=1||t.fragmentUniformsCount<64||t.forceCpuParticles||!t.extTextureFloat,this._destroyResources(),this.pack8=(this.pack8||!t.textureFloatRenderable)&&!this.useCpu,Ed=this.useCpu||this.pack8?4:2,this.useMesh=!1,this.mesh)&&(this.numParticles*this.mesh.vertexBuffer.numVertices>65535||(this.useMesh=!0));this.numParticlesPot=_t.nextPowerOfTwo(this.numParticles),this.rebuildGraphs(),this.calculateLocalBounds(),this.resetWorldBounds(),this.node&&(this.worldBounds.setFromTransformedAabb(this.localBounds,this.localSpace?Ft.IDENTITY:this.node.getWorldTransform()),this.worldBoundsTrail[0].copy(this.worldBounds),this.worldBoundsTrail[1].copy(this.worldBounds),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.pack8&&this.calculateBoundsMad()),this.vbToSort=new Array(this.numParticles);for(var e=0;e<this.numParticles;e++)this.vbToSort[e]=[0,0];this.particleDistance=new Float32Array(this.numParticles),this._gpuUpdater.randomize(),this.particleTex=new Float32Array(this.numParticlesPot*Ed*4);var i=null===this.node||this.localSpace?wt.ZERO:this.node.getPosition();0===this.emitterShape&&(null===this.node||this.localSpace?Pd.setTRS(wt.ZERO,Bt.IDENTITY,this.spawnBounds):Pd.setTRS(wt.ZERO,this.node.getRotation(),Rd.copy(this.spawnBounds).mul(this.node.localScale)),Md[0]=0!==this.emitterExtents.x?this.emitterExtentsInner.x/this.emitterExtents.x:0,Md[1]=0!==this.emitterExtents.y?this.emitterExtentsInner.y/this.emitterExtents.y:0,Md[2]=0!==this.emitterExtents.z?this.emitterExtentsInner.z/this.emitterExtents.z:0);for(var n=0;n<this.numParticles;n++)this._cpuUpdater.calcSpawnPosition(this.particleTex,Pd,Md,i,n),this.useCpu&&(this.particleTex[4*n+3+2*this.numParticlesPot*4]=1);this.particleTexStart=new Float32Array(this.numParticlesPot*Ed*4);for(var s=0;s<this.particleTexStart.length;s++)this.particleTexStart[s]=this.particleTex[s];this.useCpu||(this.pack8?(this.particleTexIN=yd(t,this.numParticlesPot,Ed,this.particleTex,7,1,!1),this.particleTexOUT=yd(t,this.numParticlesPot,Ed,this.particleTex,7,1,!1),this.particleTexStart=yd(t,this.numParticlesPot,Ed,this.particleTexStart,7,1,!1)):(this.particleTexIN=yd(t,this.numParticlesPot,Ed,this.particleTex),this.particleTexOUT=yd(t,this.numParticlesPot,Ed,this.particleTex),this.particleTexStart=yd(t,this.numParticlesPot,Ed,this.particleTexStart)),this.rtParticleTexIN=new rn({colorBuffer:this.particleTexIN,depth:!1}),this.rtParticleTexOUT=new rn({colorBuffer:this.particleTexOUT,depth:!1}),this.swapTex=!1);var r=(this.localSpace?"#define LOCAL_SPACE\n":"")+_o.particleUpdaterInitPS+(this.pack8?_o.particleInputRgba8PS+_o.particleOutputRgba8PS:_o.particleInputFloatPS+_o.particleOutputFloatPS)+(0===this.emitterShape?_o.particleUpdaterAABBPS:_o.particleUpdaterSpherePS)+_o.particleUpdaterStartPS,a=r+_o.particleUpdaterRespawnPS+_o.particleUpdaterEndPS,o=r+_o.particleUpdaterNoRespawnPS+_o.particleUpdaterEndPS,h=r+_o.particleUpdaterOnStopPS+_o.particleUpdaterEndPS,l=this.emitterShape+""+this.pack8+this.localSpace;this.shaderParticleUpdateRespawn=bo(t,_o.fullscreenQuadVS,a,"fsQuad0"+l),this.shaderParticleUpdateNoRespawn=bo(t,_o.fullscreenQuadVS,o,"fsQuad1"+l),this.shaderParticleUpdateOnStop=bo(t,_o.fullscreenQuadVS,h,"fsQuad2"+l),this.numParticleVerts=this.useMesh?this.mesh.vertexBuffer.numVertices:4,this.numParticleIndices=this.useMesh?this.mesh.indexBuffer[0].numIndices:6,this._allocate(this.numParticles);var c=new qa(t);c.vertexBuffer=this.vertexBuffer,c.indexBuffer[0]=this.indexBuffer,c.primitive[0].type=4,c.primitive[0].base=0,c.primitive[0].count=this.numParticles*this.numParticleIndices,c.primitive[0].indexed=!0,this.material=new zo,this.material.name=this.node.name,this.material.cull=se,this.material.alphaWrite=!1,this.material.blendType=this.blendType,this.material.depthWrite=this.depthWrite,this.material.emitter=this,this.regenShader(),this.resetMaterial();var u=!this.meshInstance||this.meshInstance.visible;this.meshInstance=new yh(c,this.material,this.node),this.meshInstance.pick=!1,this.meshInstance.updateKey(),this.meshInstance.cull=!0,this.meshInstance._noDepthDrawGl1=!0,this.localSpace?this.meshInstance.aabb.setFromTransformedAabb(this.worldBounds,this.node.getWorldTransform()):this.meshInstance.aabb.copy(this.worldBounds),this.meshInstance._updateAabb=!1,this.meshInstance.visible=u,this._initializeTextures(),this.resetTime(),this.addTime(0,!1),this.preWarm&&this.prewarm(this.lifetime)},e._isAnimated=function(){return this.animNumFrames>=1&&(this.animTilesX>1||this.animTilesY>1)&&(this.colorMap&&this.colorMap!==this.defaultParamTexture||this.normalMap)},e.rebuildGraphs=function(){var t=this.precision,e=this.graphicsDevice;this.qLocalVelocity=this.localVelocityGraph.quantize(t),this.qVelocity=this.velocityGraph.quantize(t),this.qColor=this.colorGraph.quantizeClamped(t,0,1),this.qRotSpeed=this.rotationSpeedGraph.quantize(t),this.qScale=this.scaleGraph.quantize(t),this.qAlpha=this.alphaGraph.quantize(t),this.qRadialSpeed=this.radialSpeedGraph.quantize(t),this.qLocalVelocity2=this.localVelocityGraph2.quantize(t),this.qVelocity2=this.velocityGraph2.quantize(t),this.qColor2=this.colorGraph2.quantizeClamped(t,0,1),this.qRotSpeed2=this.rotationSpeedGraph2.quantize(t),this.qScale2=this.scaleGraph2.quantize(t),this.qAlpha2=this.alphaGraph2.quantize(t),this.qRadialSpeed2=this.radialSpeedGraph2.quantize(t);for(var i=0;i<t;i++)this.qRotSpeed[i]*=_t.DEG_TO_RAD,this.qRotSpeed2[i]*=_t.DEG_TO_RAD;if(this.localVelocityUMax=new Float32Array(3),this.velocityUMax=new Float32Array(3),this.colorUMax=new Float32Array(3),this.rotSpeedUMax=[0],this.scaleUMax=[0],this.alphaUMax=[0],this.radialSpeedUMax=[0],this.qLocalVelocityDiv=Bd(this.qLocalVelocity,this.qLocalVelocity2,this.localVelocityUMax),this.qVelocityDiv=Bd(this.qVelocity,this.qVelocity2,this.velocityUMax),this.qColorDiv=Bd(this.qColor,this.qColor2,this.colorUMax),this.qRotSpeedDiv=Bd(this.qRotSpeed,this.qRotSpeed2,this.rotSpeedUMax),this.qScaleDiv=Bd(this.qScale,this.qScale2,this.scaleUMax),this.qAlphaDiv=Bd(this.qAlpha,this.qAlpha2,this.alphaUMax),this.qRadialSpeedDiv=Bd(this.qRadialSpeed,this.qRadialSpeed2,this.radialSpeedUMax),this.pack8){var n=[0,0,0];Fd(this.qVelocity,n);var s=[0,0,0];Fd(this.qVelocity2,s);var r=[0,0,0];Fd(this.qLocalVelocity,r);var a=[0,0,0];Fd(this.qLocalVelocity2,a);var o=[0];Fd(this.qRadialSpeed,o);var h=[0];Fd(this.qRadialSpeed2,h);var l=Math.max(n[0],s[0]);l=Math.max(l,n[1]),l=Math.max(l,s[1]),l=Math.max(l,n[2]),l=Math.max(l,s[2]);var c=Math.max(r[0],a[0]);c=Math.max(c,r[1]),c=Math.max(c,a[1]),c=Math.max(c,r[2]),c=Math.max(c,a[2]);var u=Math.max(o[0],h[0]);this.maxVel=l+c+u}this.useCpu||(this.internalTex0=yd(e,t,1,kd(this.qLocalVelocity,this.qLocalVelocityDiv)),this.internalTex1=yd(e,t,1,kd(this.qVelocity,this.qVelocityDiv)),this.internalTex2=yd(e,t,1,function(t,e,i,n,s){for(var r=new Array(4*t.length),a=0;a<t.length;a++)r[4*a]=t[a],r[4*a+1]=e[a],r[4*a+2]=0,r[4*a+3]=Od(i[a],n[a],s[a]);return r}(this.qRotSpeed,this.qScale,this.qScaleDiv,this.qRotSpeedDiv,this.qAlphaDiv)),this.internalTex3=yd(e,t,1,function(t,e){for(var i=new Array(4*t.length),n=0;n<t.length;n++)i[4*n]=t[n],i[4*n+1]=e[n],i[4*n+2]=0,i[4*n+3]=0;return i}(this.qRadialSpeed,this.qRadialSpeedDiv))),this.colorParam=yd(e,t,1,function(t,e){for(var i=new Array(4*e.length),n=0;n<e.length;n++)i[4*n]=t[3*n],i[4*n+1]=t[3*n+1],i[4*n+2]=t[3*n+2],i[4*n+3]=e[n];return i}(this.qColor,this.qAlpha),7,1,!0)},e._initializeTextures=function(){this.colorMap&&(this.material.setParameter("colorMap",this.colorMap),this.lighting&&this.normalMap&&this.material.setParameter("normalMap",this.normalMap))},e.regenShader=function(){var t=go(this.graphicsDevice);t.register("particle",ju);var e=null!==this.normalMap;this.normalOption=0,this.lighting&&(this.normalOption=e?2:1),this.material.getShaderVariant=function(e,i,n,s,r,a,o,h){this.emitter.scene&&this.emitter.camera!==this.emitter.scene._activeCamera&&(this.emitter.camera=this.emitter.scene._activeCamera,this.emitter.onChangeCamera());var l=this.emitter.inTools,c=new fo(o,h);return t.getProgram("particle",{pass:0,useCpu:this.emitter.useCpu,normal:this.emitter.normalOption,halflambert:this.emitter.halfLambert,stretch:this.emitter.stretch,alignToMotion:this.emitter.alignToMotion,soft:this.emitter.depthSoftening,mesh:this.emitter.useMesh,gamma:this.emitter.scene?this.emitter.scene.gammaCorrection:0,toneMap:this.emitter.scene?this.emitter.scene.toneMapping:0,fog:this.emitter.scene&&!this.emitter.noFog?this.emitter.scene.fog:"none",wrap:this.emitter.wrap&&this.emitter.wrapBounds,localSpace:this.emitter.localSpace,screenSpace:!l&&this.emitter.screenSpace,blend:this.blendType,animTex:this.emitter._isAnimated(),animTexLoop:this.emitter.animLoop,pack8:this.emitter.pack8,customFace:0!==this.emitter.orientation},c)},this.material.shader=this.material.getShaderVariant()},e.resetMaterial=function(){var t=this.material;t.setParameter("stretch",this.stretch),this._isAnimated()&&(t.setParameter("animTexTilesParams",this.animTilesParams),t.setParameter("animTexParams",this.animParams),t.setParameter("animTexIndexParams",this.animIndexParams)),t.setParameter("colorMult",this.intensity),this.useCpu||(t.setParameter("internalTex0",this.internalTex0),t.setParameter("internalTex1",this.internalTex1),t.setParameter("internalTex2",this.internalTex2),t.setParameter("internalTex3",this.internalTex3)),t.setParameter("colorParam",this.colorParam),t.setParameter("numParticles",this.numParticles),t.setParameter("numParticlesPot",this.numParticlesPot),t.setParameter("lifetime",this.lifetime),t.setParameter("rate",this.rate),t.setParameter("rateDiv",this.rate2-this.rate),t.setParameter("seed",this.seed),t.setParameter("scaleDivMult",this.scaleUMax[0]),t.setParameter("alphaDivMult",this.alphaUMax[0]),t.setParameter("radialSpeedDivMult",this.radialSpeedUMax[0]),t.setParameter("graphNumSamples",this.precision),t.setParameter("graphSampleSize",1/this.precision),t.setParameter("emitterScale",new Float32Array([1,1,1])),this.pack8&&(this._gpuUpdater._setInputBounds(),t.setParameter("inBoundsSize",this._gpuUpdater.inBoundsSizeUniform),t.setParameter("inBoundsCenter",this._gpuUpdater.inBoundsCenterUniform),t.setParameter("maxVel",this.maxVel)),this.wrap&&this.wrapBounds&&(this.wrapBoundsUniform[0]=this.wrapBounds.x,this.wrapBoundsUniform[1]=this.wrapBounds.y,this.wrapBoundsUniform[2]=this.wrapBounds.z,t.setParameter("wrapBounds",this.wrapBoundsUniform)),this.colorMap&&t.setParameter("colorMap",this.colorMap),this.lighting&&this.normalMap&&t.setParameter("normalMap",this.normalMap),this.depthSoftening>0&&t.setParameter("softening",1/(this.depthSoftening*this.depthSoftening*100)),this.stretch>0&&(t.cull=se),this._compParticleFaceParams()},e._compParticleFaceParams=function(){var t,e;if(0===this.orientation)t=new Float32Array([1,0,0]),e=new Float32Array([0,0,1]);else{var i;if(1===this.orientation)i=this.particleNormal.normalize();else i=(null===this.node?Ft.IDENTITY:this.node.getWorldTransform()).transformVector(this.particleNormal).normalize();var n=new wt(1,0,0);1===Math.abs(n.dot(i))&&n.set(0,0,1);var s=(new wt).cross(i,n).normalize();n.cross(s,i).normalize(),t=new Float32Array([n.x,n.y,n.z]),e=new Float32Array([s.x,s.y,s.z])}this.material.setParameter("faceTangent",t),this.material.setParameter("faceBinorm",e)},e._allocate=function(t){var e=t*this.numParticleVerts,i=t*this.numParticleIndices;if(void 0===this.vertexBuffer||this.vertexBuffer.getNumVertices()!==e){if(this.useCpu){var n=[{semantic:Ne,components:4,type:6},{semantic:ze,components:4,type:6},{semantic:Ve,components:4,type:6},{semantic:Ge,components:1,type:6},{semantic:He,components:this.useMesh?4:2,type:6}],s=new Ji(this.graphicsDevice,n);this.vertexBuffer=new ji(this.graphicsDevice,s,e,1),this.indexBuffer=new vr(this.graphicsDevice,1,i)}else{var r=[{semantic:Ne,components:4,type:6}];this.useMesh&&r.push({semantic:ze,components:2,type:6});var a=new Ji(this.graphicsDevice,r);this.vertexBuffer=new ji(this.graphicsDevice,a,e,1),this.indexBuffer=new vr(this.graphicsDevice,1,i)}var o,h,l,c=new Float32Array(this.vertexBuffer.lock());if(this.useMesh){h=(o=new Float32Array(this.mesh.vertexBuffer.lock())).length/this.mesh.vertexBuffer.numVertices;for(var u=0;u<this.mesh.vertexBuffer.format.elements.length;u++)if(this.mesh.vertexBuffer.format.elements[u].name===Re){l=this.mesh.vertexBuffer.format.elements[u].offset/4;break}}for(var d=0;d<e;d++){var f=Math.floor(d/this.numParticleVerts);if(this.useMesh){var p=d%this.numParticleVerts;c[6*d]=o[p*h],c[6*d+1]=o[p*h+1],c[6*d+2]=o[p*h+2],c[6*d+3]=f,c[6*d+4]=o[p*h+l+0],c[6*d+5]=1-o[p*h+l+1]}else{var m=d%4;c[4*d]=gd[m][0],c[4*d+1]=gd[m][1],c[4*d+2]=0,c[4*d+3]=f}}this.useCpu&&(this.vbCPU=new Float32Array(c),this.vbOld=new Float32Array(this.vbCPU.length)),this.vertexBuffer.unlock(),this.useMesh&&this.mesh.vertexBuffer.unlock();var _=0,v=new Uint16Array(this.indexBuffer.lock());this.useMesh&&(o=new Uint16Array(this.mesh.indexBuffer[0].lock()));for(var g=0;g<t;g++)if(this.useMesh)for(var y=0;y<this.numParticleIndices;y++)v[g*this.numParticleIndices+y]=o[y]+g*this.numParticleVerts;else{var x=4*g;v[_++]=x,v[_++]=x+1,v[_++]=x+2,v[_++]=x,v[_++]=x+2,v[_++]=x+3}this.indexBuffer.unlock(),this.useMesh&&this.mesh.indexBuffer[0].unlock()}},e.reset=function(){if(this.beenReset=!0,this.seed=Math.random(),this.material.setParameter("seed",this.seed),this.useCpu)for(var t=0;t<this.particleTexStart.length;t++)this.particleTex[t]=this.particleTexStart[t];else this._initializeTextures();this.resetWorldBounds(),this.resetTime();var e=this.loop;this.loop=!0,this.addTime(0,!1),this.loop=e,this.preWarm&&this.prewarm(this.lifetime)},e.prewarm=function(t){for(var e=t/this.lifetime,i=Math.min(Math.floor(e*this.precision),this.precision),n=t/i,s=0;s<i;s++)this.addTime(n,!1)},e.resetTime=function(){var t,e;this.endTime=(t=this,e=Math.max(t.rate,t.rate2)*t.numParticles+t.lifetime,Date.now()+1e3*e)},e.finishFrame=function(){this.useCpu&&this.vertexBuffer.unlock()},e.addTime=function(t,e){var i,n=this.graphicsDevice;if(this.simTimeTotal+=t,this.calculateWorldBounds(),this._isAnimated()){var s=this.animTilesParams;s[0]=1/this.animTilesX,s[1]=1/this.animTilesY;var r=this.animParams;r[0]=this.animStartFrame,r[1]=this.animNumFrames*this.animSpeed,r[2]=this.animNumFrames-1,r[3]=this.animNumAnimations-1;var a=this.animIndexParams;a[0]=this.animIndex,a[1]=this.randomizeAnimIndex}this.scene&&this.camera!==this.scene._activeCamera&&(this.camera=this.scene._activeCamera,this.onChangeCamera()),0===this.emitterShape&&(Md[0]=0!==this.emitterExtents.x?this.emitterExtentsInner.x/this.emitterExtents.x:0,Md[1]=0!==this.emitterExtents.y?this.emitterExtentsInner.y/this.emitterExtents.y:0,Md[2]=0!==this.emitterExtents.z?this.emitterExtentsInner.z/this.emitterExtents.z:0,null===this.meshInstance.node?Pd.setTRS(wt.ZERO,Bt.IDENTITY,this.emitterExtents):Pd.setTRS(wt.ZERO,this.meshInstance.node.getRotation(),Rd.copy(this.emitterExtents).mul(this.meshInstance.node.localScale)));var o=null===this.meshInstance.node?wt.ONE:this.meshInstance.node.localScale;if(this.emitterScaleUniform[0]=o.x,this.emitterScaleUniform[1]=o.y,this.emitterScaleUniform[2]=o.z,this.material.setParameter("emitterScale",this.emitterScaleUniform),this.localSpace&&this.meshInstance.node&&(i=this.meshInstance.node.getPosition(),this.emitterPosUniform[0]=i.x,this.emitterPosUniform[1]=i.y,this.emitterPosUniform[2]=i.z,this.material.setParameter("emitterPos",this.emitterPosUniform)),this._compParticleFaceParams(),this.useCpu){var h=new Float32Array(this.vertexBuffer.lock());this._cpuUpdater.update(h,this.vbToSort,this.particleTex,Pd,Md,i,t,e)}else this._gpuUpdater.update(n,Pd,Md,t,e);this.loop||Date.now()>this.endTime&&(this.onFinished&&this.onFinished(),this.meshInstance.visible=!1),this.meshInstance&&(this.meshInstance.drawOrder=this.drawOrder)},e._destroyResources=function(){this.particleTexIN&&(this.particleTexIN.destroy(),this.particleTexIN=null),this.particleTexOUT&&(this.particleTexOUT.destroy(),this.particleTexOUT=null),this.particleTexStart&&this.particleTexStart.destroy&&(this.particleTexStart.destroy(),this.particleTexStart=null),this.rtParticleTexIN&&(this.rtParticleTexIN.destroy(),this.rtParticleTexIN=null),this.rtParticleTexOUT&&(this.rtParticleTexOUT.destroy(),this.rtParticleTexOUT=null),this.internalTex0&&(this.internalTex0.destroy(),this.internalTex0=null),this.internalTex1&&(this.internalTex1.destroy(),this.internalTex1=null),this.internalTex2&&(this.internalTex2.destroy(),this.internalTex2=null),this.internalTex3&&(this.internalTex3.destroy(),this.internalTex3=null),this.colorParam&&(this.colorParam.destroy(),this.colorParam=null),this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=void 0),this.indexBuffer&&(this.indexBuffer.destroy(),this.indexBuffer=void 0),this.material&&(this.material.destroy(),this.material=null)},e.destroy=function(){this.camera=null,this._destroyResources()},y(t,[{key:"defaultParamTexture",get:function(){var t=this;return Ud.get(this.graphicsDevice,(function(){for(var e=16,i=new Float32Array(1024),n=0;n<e;n++)for(var s=0;s<e;s++){var r=s+1-8.5,a=n+1-8.5,o=xd(1-xd(Math.sqrt(r*r+a*a)/e)-.5),h=n*e+s;i[4*h]=1,i[4*h+1]=1,i[4*h+2]=1,i[4*h+3]=o}var l=yd(t.graphicsDevice,e,e,i,7,1,!0);return l.minFilter=1,l.magFilter=1,l}))}}]),t}(),zd=function(t){function e(){return t.apply(this,arguments)||this}S(e,t);var i=e.prototype;return i.generateKey=function(t){return"cubemap"===t.type?"skybox-"+t.type+"-"+t.encoding+"-"+t.useIntensity+"-"+t.gamma+"-"+t.toneMapping+"-"+t.fixSeams+"-"+t.mip:"skybox-"+t.type+"-"+t.encoding+"-"+t.useIntensity+"-"+t.gamma+"-"+t.toneMapping},i.createShaderDefinition=function(t,e){var i="";if("cubemap"===e.type){i+=e.mip?_o.fixCubemapSeamsStretchPS:_o.fixCubemapSeamsNonePS,i+=e.useIntensity?_o.envMultiplyPS:_o.envConstPS,i+=_o.decodePS,i+=xo.gammaCode(e.gamma),i+=xo.tonemapCode(e.toneMapping),i+=_o.skyboxHDRPS.replace(/\$DECODE/g,Yh.decodeFunc(e.encoding)).replace(/\$FIXCONST/g,1-1/[128,64,16,8,4,2][e.mip]+"")}else i+=e.useIntensity?_o.envMultiplyPS:_o.envConstPS,i+=_o.decodePS,i+=xo.gammaCode(e.gamma),i+=xo.tonemapCode(e.toneMapping),i+=_o.sphericalPS,i+=_o.envAtlasPS,i+=_o.skyboxEnvPS.replace(/\$DECODE/g,Yh.decodeFunc(e.encoding));return ir.createDefinition(t,{name:"SkyboxShader",attributes:{aPosition:we},vertexCode:_o.skyboxVS,fragmentCode:i})},e}(xo),Vd=new zd,Gd=function(){function t(t,e,i){this.meshInstance=void 0;var n=new zo;n.getShaderVariant=function(n,s,r,a,o,h,l,c){var u={pass:o,encoding:i.encoding,useIntensity:1!==e.skyboxIntensity||e.physicalUnits,gamma:1===o?e.gammaCorrection?3:0:e.gammaCorrection,toneMapping:1===o?0:e.toneMapping};i.cubemap?(u.type="cubemap",u.mip=i.fixCubemapSeams?e.skyboxMip:0,u.fixSeams=i.fixCubemapSeams):u.type="envAtlas";var d=new fo(l,c),f=go(t);return f.register("skybox",Vd),f.getProgram("skybox",u,d)},i.cubemap?n.setParameter("texture_cubeMap",i):(n.setParameter("texture_envAtlas",i),n.setParameter("mipLevel",e._skyboxMip)),n.cull=2,n.depthWrite=!1;var s=e.layers.getLayerById(2);if(s){var r=new hh("Skybox"),a=oo(t),o=new yh(a,n,r);this.meshInstance=o,o.cull=!1,o._noDepthDrawGl1=!0,o.pick=!1,s.addMeshInstances([o]),this.skyLayer=s}}return t.prototype.destroy=function(){this.meshInstance&&(this.skyLayer&&this.skyLayer.removeMeshInstances([this.meshInstance]),this.meshInstance.destroy(),this.meshInstance=null)},t}(),Hd=new hh;Hd.worldTransform=Ft.IDENTITY,Hd._dirtyWorld=Hd._dirtyNormal=!1;var Wd=function(){function t(t,e,i){this.material=e,this.layer=i,this.positions=[],this.colors=[],this.mesh=new qa(t),this.meshInstance=null}var e=t.prototype;return e.addLines=function(t,e){for(var i=this.positions,n=t.length,s=0;s<n;s++){var r=t[s];i.push(r.x,r.y,r.z)}var a=this.colors;if(e.length)for(var o=0;o<n;o++){var h=e[o];a.push(h.r,h.g,h.b,h.a)}else for(var l=0;l<n;l++)a.push(e.r,e.g,e.b,e.a)},e.addLinesArrays=function(t,e){for(var i=this.positions,n=0;n<t.length;n+=3)i.push(t[n],t[n+1],t[n+2]);var s=this.colors;if(e.length)for(var r=0;r<e.length;r+=4)s.push(e[r],e[r+1],e[r+2],e[r+3]);else for(var a=t.length/3,o=0;o<a;o++)s.push(e.r,e.g,e.b,e.a)},e.onPreRender=function(t,e){this.positions.length>0&&this.material.transparent===e&&(this.mesh.setPositions(this.positions),this.mesh.setColors(this.colors),this.mesh.update(1,!1),this.meshInstance||(this.meshInstance=new yh(this.mesh,this.material,Hd)),this.positions.length=0,this.colors.length=0,t.push(this.meshInstance))},t}(),Xd=function(){function t(t){this.device=t,this.map=new Map}var e=t.prototype;return e.getBatch=function(t,e){var i=this.map.get(t);return i||(i=new Wd(this.device,t,e),this.map.set(t,i)),i},e.onPreRender=function(t,e){this.map.forEach((function(i){i.onPreRender(t,e)}))},t}(),jd=[],qd=function(){function t(t){this.device=t,this.quadMesh=null,this.textureShader=null,this.depthTextureShader=null,this.cubeLocalPos=null,this.cubeWorldPos=null,this.batchesMap=new Map,this.allBatches=new Set,this.updatedLayers=new Set,this._materialDepth=null,this._materialNoDepth=null,this.layerMeshInstances=new Map}var e=t.prototype;return e.createMaterial=function(t){var e=new Vo;return e.vertexColors=!0,e.blendType=2,e.depthTest=t,e.update(),e},e.getBatch=function(t,e){var i=this.batchesMap.get(t);i||(i=new Xd(this.device),this.batchesMap.set(t,i)),this.allBatches.add(i);var n=e?this.materialDepth:this.materialNoDepth;return i.getBatch(n,t)},e.getShader=function(t,e){if(!this[t]){this[t]=bo(this.device,"\n\t\t\t\tattribute vec2 vertex_position;\n\t\t\t\tuniform mat4 matrix_model;\n\t\t\t\tvarying vec2 uv0;\n\t\t\t\tvoid main(void) {\n\t\t\t\t\tgl_Position = matrix_model * vec4(vertex_position, 0, 1);\n\t\t\t\t\tuv0 = vertex_position.xy + 0.5;\n\t\t\t\t}\n\t\t\t",e,"DebugShader:"+t)}return this[t]},e.getTextureShader=function(){return this.getShader("textureShader","\n\t\t\tvarying vec2 uv0;\n\t\t\tuniform sampler2D colorMap;\n\t\t\tvoid main (void) {\n\t\t\t\tgl_FragColor = vec4(texture2D(colorMap, uv0).xyz, 1);\n\t\t\t}\n\t\t")},e.getUnfilterableTextureShader=function(){return this.getShader("textureShaderUnfilterable","\n\t\t\tvarying vec2 uv0;\n\t\t\tuniform highp sampler2D colorMap;\n\t\t\tvoid main (void) {\n\t\t\t\tivec2 uv = ivec2(uv0 * textureSize(colorMap, 0));\n\t\t\t\tgl_FragColor = vec4(texelFetch(colorMap, uv, 0).xyz, 1);\n\t\t\t}\n\t\t")},e.getDepthTextureShader=function(){return this.getShader("depthTextureShader","\n\t\t\t"+_o.screenDepthPS+"\n\t\t\tvarying vec2 uv0;\n\t\t\tvoid main() {\n\t\t\t\tfloat depth = getLinearScreenDepth(uv0) * camera_params.x;\n\t\t\t\tgl_FragColor = vec4(vec3(depth), 1.0);\n\t\t\t}\n\t\t")},e.getQuadMesh=function(){return this.quadMesh||(this.quadMesh=new qa(this.device),this.quadMesh.setPositions([-.5,-.5,0,.5,-.5,0,-.5,.5,0,.5,.5,0]),this.quadMesh.update(be)),this.quadMesh},e.drawMesh=function(t,e,i,n,s){if(!n){var r=this.getGraphNode(e);n=new yh(i,t,r)}var a=this.layerMeshInstances.get(s);a||(a=[],this.layerMeshInstances.set(s,a)),a.push(n)},e.drawWireAlignedBox=function(t,e,i,n,s){jd.push(t.x,t.y,t.z,t.x,e.y,t.z,t.x,e.y,t.z,e.x,e.y,t.z,e.x,e.y,t.z,e.x,t.y,t.z,e.x,t.y,t.z,t.x,t.y,t.z,t.x,t.y,e.z,t.x,e.y,e.z,t.x,e.y,e.z,e.x,e.y,e.z,e.x,e.y,e.z,e.x,t.y,e.z,e.x,t.y,e.z,t.x,t.y,e.z,t.x,t.y,t.z,t.x,t.y,e.z,t.x,e.y,t.z,t.x,e.y,e.z,e.x,e.y,t.z,e.x,e.y,e.z,e.x,t.y,t.z,e.x,t.y,e.z),this.getBatch(s,n).addLinesArrays(jd,i),jd.length=0},e.drawWireSphere=function(t,e,i,n,s,r){for(var a=2*Math.PI/n,o=0,h=0;h<n;h++){var l=Math.sin(o),c=Math.cos(o);o+=a;var u=Math.sin(o),d=Math.cos(o);jd.push(t.x+e*l,t.y,t.z+e*c),jd.push(t.x+e*u,t.y,t.z+e*d),jd.push(t.x+e*l,t.y+e*c,t.z),jd.push(t.x+e*u,t.y+e*d,t.z),jd.push(t.x,t.y+e*l,t.z+e*c),jd.push(t.x,t.y+e*u,t.z+e*d)}this.getBatch(r,s).addLinesArrays(jd,i),jd.length=0},e.getGraphNode=function(t){var e=new hh("ImmediateDebug");return e.worldTransform=t,e._dirtyWorld=e._dirtyNormal=!1,e},e.onPreRenderLayer=function(t,e,i){if(this.batchesMap.forEach((function(n,s){s===t&&n.onPreRender(e,i)})),!this.updatedLayers.has(t)){this.updatedLayers.add(t);var n=this.layerMeshInstances.get(t);if(n){for(var s=0;s<n.length;s++)e.push(n[s]);n.length=0}}},e.onPostRender=function(){this.allBatches.clear(),this.updatedLayers.clear()},y(t,[{key:"materialDepth",get:function(){return this._materialDepth||(this._materialDepth=this.createMaterial(!0)),this._materialDepth}},{key:"materialNoDepth",get:function(){return this._materialNoDepth||(this._materialNoDepth=this.createMaterial(!1)),this._materialNoDepth}}]),t}(),Yd=function(t){function e(e){var i;return(i=t.call(this)||this).ambientBake=!1,i.ambientBakeOcclusionBrightness=0,i.ambientBakeOcclusionContrast=0,i.ambientLight=new vt(0,0,0),i.ambientLuminance=0,i.exposure=1,i.fogColor=new vt(0,0,0),i.fogDensity=0,i.fogEnd=1e3,i.fogStart=1,i.lightmapSizeMultiplier=1,i.lightmapMaxResolution=2048,i.lightmapMode=1,i.lightmapFilterEnabled=!1,i.lightmapHDR=!1,i.root=null,i.sky=null,i.physicalUnits=!1,i.device=e||Ha.get(),i._gravity=new wt(0,-9.8,0),i._layers=null,i._fog=Ra,i._gammaCorrection=1,i._toneMapping=0,i._skyboxCubeMap=null,i._prefilteredCubemaps=[],i._envAtlas=null,i._internalEnvAtlas=null,i._skyboxIntensity=1,i._skyboxLuminance=0,i._skyboxMip=0,i._skyboxRotationShaderInclude=!1,i._skyboxRotation=new Bt,i._skyboxRotationMat3=new At,i._skyboxRotationMat4=new Ft,i._ambientBakeNumSamples=1,i._ambientBakeSpherePart=.4,i._lightmapFilterRange=10,i._lightmapFilterSmoothness=.2,i._clusteredLightingEnabled=!0,i._lightingParams=new Nu(i.device.supportsAreaLights,i.device.maxTextureSize,(function(){i.updateShaders=!0})),i._stats={meshInstances:0,lights:0,dynamicLights:0,bakedLights:0,updateShadersTime:0},i.updateShaders=!0,i._shaderVersion=0,i.immediate=new qd(i.device),i}S(e,t);var i=e.prototype;return i.destroy=function(){this._resetSky(),this.root=null,this.off()},i.drawLine=function(t,e,i,n,s){void 0===i&&(i=vt.WHITE),void 0===n&&(n=!0),void 0===s&&(s=this.defaultDrawLayer),this.immediate.getBatch(s,n).addLines([t,e],[i,i])},i.drawLines=function(t,e,i,n){void 0===i&&(i=!0),void 0===n&&(n=this.defaultDrawLayer),this.immediate.getBatch(n,i).addLines(t,e)},i.drawLineArrays=function(t,e,i,n){void 0===i&&(i=!0),void 0===n&&(n=this.defaultDrawLayer),this.immediate.getBatch(n,i).addLinesArrays(t,e)},i.applySettings=function(t){var e,i,n,s,r=this,a=t.physics,o=t.render;this._gravity.set(a.gravity[0],a.gravity[1],a.gravity[2]),this.ambientLight.set(o.global_ambient[0],o.global_ambient[1],o.global_ambient[2]),this.ambientLuminance=o.ambientLuminance,this._fog=o.fog,this.fogColor.set(o.fog_color[0],o.fog_color[1],o.fog_color[2]),this.fogStart=o.fog_start,this.fogEnd=o.fog_end,this.fogDensity=o.fog_density,this._gammaCorrection=o.gamma_correction,this._toneMapping=o.tonemapping,this.lightmapSizeMultiplier=o.lightmapSizeMultiplier,this.lightmapMaxResolution=o.lightmapMaxResolution,this.lightmapMode=o.lightmapMode,this.exposure=o.exposure,this._skyboxIntensity=null!=(e=o.skyboxIntensity)?e:1,this._skyboxLuminance=null!=(i=o.skyboxLuminance)?i:2e4,this._skyboxMip=null!=(n=o.skyboxMip)?n:0,o.skyboxRotation&&(this.skyboxRotation=(new Bt).setFromEulerAngles(o.skyboxRotation[0],o.skyboxRotation[1],o.skyboxRotation[2])),this.clusteredLightingEnabled=null!=(s=o.clusteredLightingEnabled)&&s,this.lighting.applySettings(o),["lightmapFilterEnabled","lightmapFilterRange","lightmapFilterSmoothness","ambientBake","ambientBakeNumSamples","ambientBakeSpherePart","ambientBakeOcclusionBrightness","ambientBakeOcclusionContrast"].forEach((function(t){o.hasOwnProperty(t)&&(r[t]=o[t])})),this._resetSky()},i._getSkyboxTex=function(){var t=this._prefilteredCubemaps;if(this._skyboxMip){return t[[0,1,3,4,5,6][this._skyboxMip]]||this._envAtlas||t[0]||this._skyboxCubeMap}return this._skyboxCubeMap||t[0]||this._envAtlas},i._updateSky=function(t){if(!this.sky){var e=this._getSkyboxTex();e&&(this.sky=new Gd(t,this,e),this.fire("set:skybox",e))}},i._resetSky=function(){var t;null==(t=this.sky)||t.destroy(),this.sky=null,this.updateShaders=!0},i.setSkybox=function(t){t?(this.skybox=t[0]||null,t[1]&&!t[1].cubemap?this.envAtlas=t[1]:this.prefilteredCubemaps=t.slice(1)):(this.skybox=null,this.envAtlas=null)},y(e,[{key:"defaultDrawLayer",get:function(){return this.layers.getLayerById(3)}},{key:"ambientBakeNumSamples",get:function(){return this._ambientBakeNumSamples},set:function(t){this._ambientBakeNumSamples=_t.clamp(Math.floor(t),1,255)}},{key:"ambientBakeSpherePart",get:function(){return this._ambientBakeSpherePart},set:function(t){this._ambientBakeSpherePart=_t.clamp(t,.001,1)}},{key:"clusteredLightingEnabled",get:function(){return this._clusteredLightingEnabled},set:function(t){this.device.isWebGPU&&!t||(this._clusteredLightingEnabled||!t?this._clusteredLightingEnabled=t:console.error("Turning on disabled clustered lighting is not currently supported"))}},{key:"envAtlas",get:function(){return this._envAtlas},set:function(t){t!==this._envAtlas&&(this._envAtlas=t,t&&(t.addressU=1,t.addressV=1,t.minFilter=1,t.magFilter=1,t.mipmaps=!1),this._prefilteredCubemaps=[],this._internalEnvAtlas&&(this._internalEnvAtlas.destroy(),this._internalEnvAtlas=null),this._resetSky())}},{key:"fog",get:function(){return this._fog},set:function(t){t!==this._fog&&(this._fog=t,this.updateShaders=!0)}},{key:"gammaCorrection",get:function(){return this._gammaCorrection},set:function(t){t!==this._gammaCorrection&&(this._gammaCorrection=t,this.updateShaders=!0)}},{key:"layers",get:function(){return this._layers},set:function(t){var e=this._layers;this._layers=t,this.fire("set:layers",e,t)}},{key:"lighting",get:function(){return this._lightingParams}},{key:"lightmapFilterRange",get:function(){return this._lightmapFilterRange},set:function(t){this._lightmapFilterRange=Math.max(t,.001)}},{key:"lightmapFilterSmoothness",get:function(){return this._lightmapFilterSmoothness},set:function(t){this._lightmapFilterSmoothness=Math.max(t,.001)}},{key:"prefilteredCubemaps",get:function(){return this._prefilteredCubemaps},set:function(t){t=t||[];var e=this._prefilteredCubemaps,i=e.length!==t.length||e.some((function(e,i){return e!==t[i]}));if(i){var n=6===t.length&&t.every((function(t){return!!t}));n?(this._internalEnvAtlas=Wc.generatePrefilteredAtlas(t,{target:this._internalEnvAtlas}),this._envAtlas=this._internalEnvAtlas):(this._internalEnvAtlas&&(this._internalEnvAtlas.destroy(),this._internalEnvAtlas=null),this._envAtlas=null),this._prefilteredCubemaps=t.slice(),this._resetSky()}}},{key:"skybox",get:function(){return this._skyboxCubeMap},set:function(t){t!==this._skyboxCubeMap&&(this._skyboxCubeMap=t,this._resetSky())}},{key:"skyboxIntensity",get:function(){return this._skyboxIntensity},set:function(t){t!==this._skyboxIntensity&&(this._skyboxIntensity=t,this._resetSky())}},{key:"skyboxLuminance",get:function(){return this._skyboxLuminance},set:function(t){t!==this._skyboxLuminance&&(this._skyboxLuminance=t,this._resetSky())}},{key:"skyboxMip",get:function(){return this._skyboxMip},set:function(t){t!==this._skyboxMip&&(this._skyboxMip=t,this._resetSky())}},{key:"skyboxRotation",get:function(){return this._skyboxRotation},set:function(t){if(!this._skyboxRotation.equals(t)){var e=t.equals(Bt.IDENTITY);this._skyboxRotation.copy(t),e?this._skyboxRotationMat3.setIdentity():(this._skyboxRotationMat4.setTRS(wt.ZERO,t,wt.ONE),this._skyboxRotationMat3.invertMat4(this._skyboxRotationMat4)),this._skyboxRotationShaderInclude||e||(this._skyboxRotationShaderInclude=!0,this._resetSky())}}},{key:"toneMapping",get:function(){return this._toneMapping},set:function(t){t!==this._toneMapping&&(this._toneMapping=t,this.updateShaders=!0)}},{key:"lightmapPixelFormat",get:function(){return this.lightmapHDR&&this.device.getHdrFormat(!1,!0,!1,!0)||7}}]),e}(P),Kd=function(t,e,i){this.device=t,this.inverseBindPose=e,this.boneNames=i},Zd=[0,0,1,0,0,1,0,0,1,0,0,1],Qd=[0,1,3,2,3,1],$d=function(t){function e(e,i){var n;return(n=t.call(this)||this)._device=e,n._pixelsPerUnit=i&&void 0!==i.pixelsPerUnit?i.pixelsPerUnit:1,n._renderMode=i&&void 0!==i.renderMode?i.renderMode:0,n._atlas=i&&void 0!==i.atlas?i.atlas:null,n._frameKeys=i&&void 0!==i.frameKeys?i.frameKeys:null,n._meshes=[],n._updatingProperties=!1,n._meshesDirty=!1,n._atlas&&n._frameKeys&&n._createMeshes(),n}S(e,t);var i=e.prototype;return i._createMeshes=function(){for(var t=this._meshes.length,e=0;e<t;e++){var i=this._meshes[e];i&&i.destroy()}var n=this._frameKeys.length;this._meshes=new Array(n);for(var s=1===this.renderMode||2===this._renderMode?this._create9SliceMesh:this._createSimpleMesh,r=0;r<n;r++){var a=this._atlas.frames[this._frameKeys[r]];this._meshes[r]=a?s.call(this,a):null}this.fire("set:meshes")},i._createSimpleMesh=function(t){var e=t.rect,i=this._atlas.texture.width,n=this._atlas.texture.height,s=e.z/this._pixelsPerUnit,r=e.w/this._pixelsPerUnit,a=t.pivot.x,o=t.pivot.y,h=[-a*s,-o*r,0,(1-a)*s,-o*r,0,(1-a)*s,(1-o)*r,0,-a*s,(1-o)*r,0],l=e.x/i,c=1-e.y/n,u=(e.x+e.z)/i,d=1-(e.y+e.w)/n,f=[l,c,u,c,u,d,l,d];return Ja(this._device,h,{uvs:f,normals:Zd,indices:Qd})},i._create9SliceMesh=function(){for(var t=Et.ONE,e=[],i=[],n=[],s=[],r=0,a=0;a<=3;a++)for(var o=0===a||3===a?0:1,h=0;h<=3;h++){var l=-t.x+2*t.x*(a<=1?0:3)/3,c=-(-t.y+2*t.y*(h<=1?0:3)/3),u=0===h||3===h?0:1;e.push(-l,0,c),i.push(0,1,0),n.push(o,u),a<3&&h<3&&(s.push(r+3+1,r+1,r),s.push(r+3+1,r+3+2,r+1)),r++}var d={normals:i,uvs:n,indices:s};return Ja(this._device,e,d)},i._onSetFrames=function(t){this._updatingProperties?this._meshesDirty=!0:this._createMeshes()},i._onFrameChanged=function(t,e){var i=this._frameKeys.indexOf(t);i<0||(e?0===this.renderMode&&(this._meshes[i]=this._createSimpleMesh(e)):this._meshes[i]=null,this.fire("set:meshes"))},i._onFrameRemoved=function(t){var e=this._frameKeys.indexOf(t);e<0||(this._meshes[e]=null,this.fire("set:meshes"))},i.startUpdate=function(){this._updatingProperties=!0,this._meshesDirty=!1},i.endUpdate=function(){this._updatingProperties=!1,this._meshesDirty&&this._atlas&&this._frameKeys&&this._createMeshes(),this._meshesDirty=!1},i.destroy=function(){for(var t,e=A(this._meshes);!(t=e()).done;){var i=t.value;i&&i.destroy()}this._meshes.length=0},y(e,[{key:"frameKeys",get:function(){return this._frameKeys},set:function(t){this._frameKeys=t,this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes()),this.fire("set:frameKeys",t)}},{key:"atlas",get:function(){return this._atlas},set:function(t){t!==this._atlas&&(this._atlas&&(this._atlas.off("set:frames",this._onSetFrames,this),this._atlas.off("set:frame",this._onFrameChanged,this),this._atlas.off("remove:frame",this._onFrameRemoved,this)),this._atlas=t,this._atlas&&this._frameKeys&&(this._atlas.on("set:frames",this._onSetFrames,this),this._atlas.on("set:frame",this._onFrameChanged,this),this._atlas.on("remove:frame",this._onFrameRemoved,this),this._updatingProperties?this._meshesDirty=!0:this._createMeshes()),this.fire("set:atlas",t))}},{key:"pixelsPerUnit",get:function(){return this._pixelsPerUnit},set:function(t){this._pixelsPerUnit!==t&&(this._pixelsPerUnit=t,this.fire("set:pixelsPerUnit",t),this._atlas&&this._frameKeys&&0===this.renderMode&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes()))}},{key:"renderMode",get:function(){return this._renderMode},set:function(t){if(this._renderMode!==t){var e=this._renderMode;this._renderMode=t,this.fire("set:renderMode",t),0!==e&&0!==t||this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes())}}},{key:"meshes",get:function(){return this._meshes}}]),e}(P),Jd=function(t){function e(){var e;return(e=t.call(this)||this)._texture=null,e._frames=null,e}S(e,t);var i=e.prototype;return i.setFrame=function(t,e){var i=this._frames[t];i?(i.rect.copy(e.rect),i.pivot.copy(e.pivot),i.border.copy(e.border)):(i={rect:e.rect.clone(),pivot:e.pivot.clone(),border:e.border.clone()},this._frames[t]=i),this.fire("set:frame",t.toString(),i)},i.removeFrame=function(t){var e=this._frames[t];e&&(delete this._frames[t],this.fire("remove:frame",t.toString(),e))},i.destroy=function(){this._texture&&this._texture.destroy()},y(e,[{key:"texture",get:function(){return this._texture},set:function(t){this._texture=t,this.fire("set:texture",t)}},{key:"frames",get:function(){return this._frames},set:function(t){this._frames=t,this.fire("set:frames",t)}}]),e}(P),tf=function(t,e,i,n){this.time=t,this.position=e,this.rotation=i,this.scale=n},ef=function(){this._name="",this._keys=[]},nf=function(){function t(){this.name="",this.duration=0,this._nodes=[],this._nodeDict={}}var e=t.prototype;return e.getNode=function(t){return this._nodeDict[t]},e.addNode=function(t){this._nodes.push(t),this._nodeDict[t._name]=t},y(t,[{key:"nodes",get:function(){return this._nodes}}]),t}(),sf=function(){function t(){this._written=!1,this._name="",this._keyFrames=[],this._quat=new Bt,this._pos=new wt,this._scale=new wt,this._targetNode=null}var e=t.prototype;return e.getTarget=function(){return this._targetNode},e.setTarget=function(t){this._targetNode=t},t}(),rf=function(){function t(t){var e=this;this.looping=!0,this._animation=null,this._time=0,this._interpolatedKeys=[],this._interpolatedKeyDict={},this._currKeyIndices={},this.graph=null;!function t(i){var n=new sf;n._name=i.name,e._interpolatedKeys.push(n),e._interpolatedKeyDict[i.name]=n,e._currKeyIndices[i.name]=0;for(var s=0;s<i._children.length;s++)t(i._children[s])}(t)}var e=t.prototype;return e.addTime=function(t){if(null!==this._animation){var e=this._animation._nodes,i=this._animation.duration;if(this._time===i&&!this.looping)return;if(this._time+=t,this._time>i){this._time=this.looping?0:i;for(var n=0;n<e.length;n++){var s=e[n]._name;this._currKeyIndices[s]=0}}else if(this._time<0){this._time=this.looping?i:0;for(var r=0;r<e.length;r++){var a=e[r],o=a._name;this._currKeyIndices[o]=a._keys.length-2}}for(var h=t>=0?1:-1,l=0;l<e.length;l++){var c=e[l],u=c._name,d=c._keys,f=this._interpolatedKeyDict[u];if(void 0!==f){var p=!1;if(1!==d.length)for(var m=this._currKeyIndices[u];m<d.length-1&&m>=0;m+=h){var _=d[m],v=d[m+1];if(_.time<=this._time&&v.time>=this._time){var g=(this._time-_.time)/(v.time-_.time);f._pos.lerp(_.position,v.position,g),f._quat.slerp(_.rotation,v.rotation,g),f._scale.lerp(_.scale,v.scale,g),f._written=!0,this._currKeyIndices[u]=m,p=!0;break}}(1===d.length||!p&&0===this._time&&this.looping)&&(f._pos.copy(d[0].position),f._quat.copy(d[0].rotation),f._scale.copy(d[0].scale),f._written=!0)}}}},e.blend=function(t,e,i){for(var n=this._interpolatedKeys.length,s=0;s<n;s++){var r=t._interpolatedKeys[s],a=e._interpolatedKeys[s],o=this._interpolatedKeys[s];r._written&&a._written?(o._quat.slerp(r._quat,e._interpolatedKeys[s]._quat,i),o._pos.lerp(r._pos,e._interpolatedKeys[s]._pos,i),o._scale.lerp(r._scale,a._scale,i),o._written=!0):r._written?(o._quat.copy(r._quat),o._pos.copy(r._pos),o._scale.copy(r._scale),o._written=!0):a._written&&(o._quat.copy(a._quat),o._pos.copy(a._pos),o._scale.copy(a._scale),o._written=!0)}},e.setGraph=function(t){if(this.graph=t,t)for(var e=0;e<this._interpolatedKeys.length;e++){var i=this._interpolatedKeys[e],n=t.findByName(i._name);this._interpolatedKeys[e].setTarget(n)}else for(var s=0;s<this._interpolatedKeys.length;s++)this._interpolatedKeys[s].setTarget(null)},e.updateGraph=function(){if(this.graph)for(var t=0;t<this._interpolatedKeys.length;t++){var e=this._interpolatedKeys[t];if(e._written){var i=e.getTarget();i.localPosition.copy(e._pos),i.localRotation.copy(e._quat),i.localScale.copy(e._scale),i._dirtyLocal||i._dirtifyLocal(),e._written=!1}}},y(t,[{key:"animation",get:function(){return this._animation},set:function(t){this._animation=t,this.currentTime=0}},{key:"currentTime",get:function(){return this._time},set:function(t){this._time=t;for(var e=this._interpolatedKeys.length,i=0;i<e;i++){var n=this._interpolatedKeys[i]._name;this._currKeyIndices[n]=0}this.addTime(0),this.updateGraph()}},{key:"numNodes",get:function(){return this._interpolatedKeys.length}}]),t}(),af=new Pt,of=function(){function t(t){this.device=t,this.needsDepthBuffer=!1}var e=t.prototype;return e.render=function(t,e,i){},e.drawQuad=function(t,e,i){var n;if(i){var s=t?t.width:this.device.width,r=t?t.height:this.device.height;n=af.set(i.x*s,i.y*r,i.z*s,i.w*r)}this.device.setBlendState(Ui.NOBLEND),Ro(this.device,t,e,n)},t}();function hf(t,e){return Math.atan2(t*e,Math.sqrt(t*t+e*e+1))}function lf(t,e,i){var n=2*(t+.5)/i-1,s=2*(e+.5)/i-1,r=1/i,a=(n*=1-1/i)-r,o=(s*=1-1/i)-r,h=n+r,l=s+r,c=hf(a,o)-hf(a,l)-hf(h,o)+hf(h,l);return 0===t&&0===e||t===i-1&&0===e||0===t&&e===i-1||t===i-1&&e===i-1?c/=3:0!==t&&0!==e&&t!==i-1&&e!==i-1||(c*=.5),c}of.quadVertexShader="\n attribute vec2 aPosition;\n varying vec2 vUv0;\n void main(void)\n {\n gl_Position = vec4(aPosition, 0.0, 1.0);\n vUv0 = getImageEffectUV((aPosition.xy + 1.0) * 0.5);\n }\n ";var cf,uf=function(){function t(t,e){var i=this;this.processedCache=new Map,this.definitionsCache=new Map,this._generators=new Map,this._device=t,this._isClearingCache=!1,this._precached=!1,this._programsCollection=[],this._defaultStdMatOption=new Xc,this._defaultStdMatOptionMin=new Xc,e.shaderOptBuilder.updateRef(this._defaultStdMatOption,{},e,null,[],0,null),e.shaderOptBuilder.updateMinRef(this._defaultStdMatOptionMin,{},e,null,4,null),t.on("destroy:shader",(function(t){i.removeFromCache(t)}))}var e=t.prototype;return e.destroy=function(){this.clearCache()},e.register=function(t,e){this._generators.has(t)||this._generators.set(t,e)},e.unregister=function(t){this._generators.has(t)&&this._generators.delete(t)},e.isRegistered=function(t){return this._generators.has(t)},e.generateShaderDefinition=function(t,e,i,n){var s=this.definitionsCache.get(i);if(!s){var r,a,o,h;null!=(r=n.litOptions)&&r.lights&&(h=n.litOptions.lights,n.litOptions.lights=h.map((function(t){var e=t.clone?t.clone():t;return e.key=t.key,e}))),this.storeNewProgram(e,n),null!=(a=n.litOptions)&&a.lights&&(n.litOptions.lights=h),this._precached;var l=this._device;(s=t.createShaderDefinition(l,n)).name=null!=(o=s.name)?o:n.pass?e+"-pass:"+n.pass:e,this.definitionsCache.set(i,s)}return s},e.getCachedShader=function(t){return this.processedCache.get(t)},e.setCachedShader=function(t,e){this.processedCache.set(t,e)},e.getProgram=function(t,e,i,n){var s=this._generators.get(t);if(!s)return null;var r=qi(s.generateKey(e)),a=r+"#"+qi(i.generateKey(this._device)),o=this.getCachedShader(a);if(!o){var h,l=this.generateShaderDefinition(s,t,r,e),c="";void 0!==e.pass&&(c="-"+(h=Do.get(this._device).getByIndex(e.pass)).name),this._device.fire("shader:generate",{userMaterialId:n,shaderPassInfo:h,definition:l});var u={name:""+l.name+c+"-proc",attributes:l.attributes,vshader:l.vshader,fshader:l.fshader,processingOptions:i};o=new fs(this._device,u),this.setCachedShader(a,o)}return o},e.storeNewProgram=function(t,e){var i={};if("standard"===t){var n=this._getDefaultStdMatOptions(e.pass);for(var s in e)(e.hasOwnProperty(s)&&n[s]!==e[s]||"pass"===s)&&(i[s]=e[s]);for(var r in e.litOptions)i[r]=e.litOptions[r]}else i=e;this._programsCollection.push(JSON.stringify({name:t,options:i}))},e.dumpPrograms=function(){var t="let device = pc.app ? pc.app.graphicsDevice : pc.Application.getApplication().graphicsDevice;\n";t+="let shaders = [",this._programsCollection[0]&&(t+="\n\t"+this._programsCollection[0]);for(var e=1;e<this._programsCollection.length;++e)t+=",\n\t"+this._programsCollection[e];t+="\n];\n",t+="device.getProgramLibrary().precompile(shaders);\n",t+='if (pc.version != "'+c+'" || pc.revision != "'+u+'")\n',t+='\tconsole.warn("precompile-shaders.js: engine version mismatch, rebuild shaders lib with current engine");';var i=document.createElement("a");i.setAttribute("href","data:text/plain;charset=utf-8,"+encodeURIComponent(t)),i.setAttribute("download","precompile-shaders.js"),i.style.display="none",document.body.appendChild(i),i.click(),document.body.removeChild(i)},e.clearCache=function(){this._isClearingCache=!0,this.processedCache.forEach((function(t){t.destroy()})),this.processedCache.clear(),this._isClearingCache=!1},e.removeFromCache=function(t){var e=this;this._isClearingCache||this.processedCache.forEach((function(i,n){t===i&&e.processedCache.delete(n)}))},e._getDefaultStdMatOptions=function(t){var e=Do.get(this._device).getByIndex(t);return 2===t||3===t||e.isShadow?this._defaultStdMatOptionMin:this._defaultStdMatOption},e.precompile=function(t){if(t)for(var e=new Array(t.length),i=0;i<t.length;i++){if("standard"===t[i].name){var n=t[i].options,s=this._getDefaultStdMatOptions(n.pass);for(var r in s)s.hasOwnProperty(r)&&void 0===n[r]&&(n[r]=s[r])}e[i]=this.getProgram(t[i].name,t[i].options)}this._precached=!0},t}(),df={bakeDirLmEndPS:"\n\tvec4 dirLm = texture2D(texture_dirLightMap, vUv1);\n\tif (bakeDir > 0.5) {\n\t\tif (dAtten > 0.00001) {\n\t\t\tdirLm.xyz = dirLm.xyz * 2.0 - vec3(1.0);\n\t\t\tdAtten = saturate(dAtten);\n\t\t\tgl_FragColor.rgb = normalize(dLightDirNormW.xyz*dAtten + dirLm.xyz*dirLm.w) * 0.5 + vec3(0.5);\n\t\t\tgl_FragColor.a = dirLm.w + dAtten;\n\t\t\tgl_FragColor.a = max(gl_FragColor.a, 1.0 / 255.0);\n\t\t} else {\n\t\t\tgl_FragColor = dirLm;\n\t\t}\n\t} else {\n\t\tgl_FragColor.rgb = dirLm.xyz;\n\t\tgl_FragColor.a = max(dirLm.w, dAtten > 0.00001? (1.0/255.0) : 0.0);\n\t}\n",bakeLmEndPS:"\n#ifdef LIGHTMAP_RGBM\n\tgl_FragColor.rgb = dDiffuseLight;\n\tgl_FragColor.rgb = pow(gl_FragColor.rgb, vec3(0.5));\n\tgl_FragColor.rgb /= 8.0;\n\tgl_FragColor.a = clamp( max( max( gl_FragColor.r, gl_FragColor.g ), max( gl_FragColor.b, 1.0 / 255.0 ) ), 0.0,1.0 );\n\tgl_FragColor.a = ceil(gl_FragColor.a * 255.0) / 255.0;\n\tgl_FragColor.rgb /= gl_FragColor.a;\n#else\n\tgl_FragColor = vec4(dDiffuseLight, 1.0);\n#endif\n",dilatePS:"\nvarying vec2 vUv0;\nuniform sampler2D source;\nuniform vec2 pixelOffset;\nvoid main(void) {\n\tvec4 c = texture2D(source, vUv0);\n\tc = c.a>0.0? c : texture2D(source, vUv0 - pixelOffset);\n\tc = c.a>0.0? c : texture2D(source, vUv0 + vec2(0, -pixelOffset.y));\n\tc = c.a>0.0? c : texture2D(source, vUv0 + vec2(pixelOffset.x, -pixelOffset.y));\n\tc = c.a>0.0? c : texture2D(source, vUv0 + vec2(-pixelOffset.x, 0));\n\tc = c.a>0.0? c : texture2D(source, vUv0 + vec2(pixelOffset.x, 0));\n\tc = c.a>0.0? c : texture2D(source, vUv0 + vec2(-pixelOffset.x, pixelOffset.y));\n\tc = c.a>0.0? c : texture2D(source, vUv0 + vec2(0, pixelOffset.y));\n\tc = c.a>0.0? c : texture2D(source, vUv0 + pixelOffset);\n\tgl_FragColor = c;\n}\n",bilateralDeNoisePS:"\nfloat normpdf3(in vec3 v, in float sigma) {\n\treturn 0.39894 * exp(-0.5 * dot(v, v) / (sigma * sigma)) / sigma;\n}\nvec3 decodeRGBM(vec4 rgbm) {\n\tvec3 color = (8.0 * rgbm.a) * rgbm.rgb;\n\treturn color * color;\n}\nfloat saturate(float x) {\n\treturn clamp(x, 0.0, 1.0);\n}\nvec4 encodeRGBM(vec3 color) {\n\tvec4 encoded;\n\tencoded.rgb = pow(color.rgb, vec3(0.5));\n\tencoded.rgb *= 1.0 / 8.0;\n\tencoded.a = saturate( max( max( encoded.r, encoded.g ), max( encoded.b, 1.0 / 255.0 ) ) );\n\tencoded.a = ceil(encoded.a * 255.0) / 255.0;\n\tencoded.rgb /= encoded.a;\n\treturn encoded;\n}\n#define MSIZE 15\nvarying vec2 vUv0;\nuniform sampler2D source;\nuniform vec2 pixelOffset;\nuniform vec2 sigmas;\nuniform float bZnorm;\nuniform float kernel[MSIZE];\nvoid main(void) {\n\t\n\tvec4 pixelRgbm = texture2D(source, vUv0);\n\tif (pixelRgbm.a <= 0.0) {\n\t\tgl_FragColor = pixelRgbm;\n\t\treturn ;\n\t}\n\tfloat sigma = sigmas.x;\n\tfloat bSigma = sigmas.y;\n\tvec3 pixelHdr = decodeRGBM(pixelRgbm);\n\tvec3 accumulatedHdr = vec3(0.0);\n\tfloat accumulatedFactor = 0.0;\n\tconst int kSize = (MSIZE-1)/2;\n\tfor (int i = -kSize; i <= kSize; ++i) {\n\t\tfor (int j = -kSize; j <= kSize; ++j) {\n\t\t\t\n\t\t\tvec2 coord = vUv0 + vec2(float(i), float(j)) * pixelOffset;\n\t\t\tvec4 rgbm = texture2D(source, coord);\n\t\t\tif (rgbm.a > 0.0) {\n\t\t\t\tvec3 hdr = decodeRGBM(rgbm);\n\t\t\t\tfloat factor = kernel[kSize + j] * kernel[kSize + i];\n\t\t\t\tfactor *= normpdf3(hdr - pixelHdr, bSigma) * bZnorm;\n\t\t\t\taccumulatedHdr += factor * hdr;\n\t\t\t\taccumulatedFactor += factor;\n\t\t\t}\n\t\t}\n\t}\n\tgl_FragColor = encodeRGBM(accumulatedHdr / accumulatedFactor);\n}\n"},ff="FILL_WINDOW",pf="KEEP_ASPECT",mf="AUTO",_f="FIXED";function vf(){return cf}function gf(t){cf=t,Ha.set(null==t?void 0:t.graphicsDevice)}var yf=function(){function t(){}return t.push=function(e,i){i&&t._types.length>0?console.assert("Script Ordering Error. Contact support@playcanvas.com"):t._types.push(e)},t}();yf._types=[];var xf=!1,Sf=!1,bf={app:null,create:function(t,e){if(xf){var i=e(bf.app);i._pcScriptName=t,yf.push(i,xf),this.fire("created",t,e)}},attribute:function(t,e,i,n){},createLoadingScreen:function(t){Sf||(Sf=!0,t(vf()))}};Object.defineProperty(bf,"legacy",{get:function(){return xf},set:function(t){xf=t}}),R.attach(bf);var wf=function(){function t(){this.renderPasses=[],this.renderTargetMap=new Map}var e=t.prototype;return e.addRenderPass=function(t){this.renderPasses.push(t)},e.reset=function(){this.renderPasses.length=0},e.compile=function(){for(var t=this.renderTargetMap,e=this.renderPasses,i=0;i<e.length;i++){var n=e[i],s=n.renderTarget;if(void 0!==s){var r=t.get(s);if(r){for(var a=n.colorArrayOps.length,o=0;o<a;o++){n.colorArrayOps[o].clear||(r.colorArrayOps[o].store=!0)}n.depthStencilOps.clearDepth||(r.depthStencilOps.storeDepth=!0),n.depthStencilOps.clearStencil||(r.depthStencilOps.storeStencil=!0)}t.set(s,n)}}for(var h=null,l=null,c=0;c<e.length;c++){var u=e[c],d=u.renderTarget,f=null==d?void 0:d.colorBuffer;if(null!=f&&f.cubemap){if(h===f)for(var p=l.colorArrayOps.length,m=0;m<p;m++)l.colorArrayOps[m].mipmaps=!1;h=d.colorBuffer,l=u}else u.requiresCubemaps&&(h=null,l=null)}t.clear()},e.render=function(t){this.compile();for(var e=this.renderPasses,i=0;i<e.length;i++)e[i].render()},t}(),Tf=function(){function t(t,e){this.texture0=t,this.texture1=e}return t.prototype.destroy=function(){var t,e;null==(t=this.texture0)||t.destroy(),null==(e=this.texture1)||e.destroy()},t}(),Af=new Bs,Cf=function(){function t(){}return t.createTexture=function(t,e,i,n){return void 0===n&&(n=""),new Ls(t,{name:"AreaLightLUT"+n,width:i,height:i,format:e,addressU:1,addressV:1,type:ei,magFilter:1,minFilter:0,anisotropy:1,mipmaps:!1})},t.applyTextures=function(t,e,i){Af.remove(t),Af.get(t,(function(){return new Tf(e,e===i?null:i)})),t.scope.resolve("areaLightsLutTex1").setValue(e),t.scope.resolve("areaLightsLutTex2").setValue(i)},t.createPlaceholder=function(e){var i=t.createTexture(e,e.areaLightLutFormat,2,"placeholder");i.lock().fill(0),i.unlock(),t.applyTextures(e,i,i)},t.set=function(e,i,n){function s(e,i,n){var s=t.createTexture(e,n,64);return s.lock().set(i),s.unlock(),s}function r(t,e,i){for(var n=t.length,s=new Float32Array(n),r=0;r<n;r++){var a=r%4;s[r]=(t[r]+e[a])*i[a]}return s}function a(t){for(var e=t.length,i=new Uint16Array(e),n=$h.float2Half,s=0;s<e;s++)i[s]=n(t[s]);return i}function o(t){for(var e=t.length,i=new Uint8ClampedArray(e),n=0;n<e;n++)i[n]=255*t[n];return i}var h,l,c=i,u=n,d=e.areaLightLutFormat;if(d===le)h=c,l=u;else if(d===oe)h=a(c),l=a(u);else{h=o(r(c,[0,.2976,.01381,0],[.999,3.08737,1.6546,.603249])),l=o(r(u,[-.306897,0,0,0],[1.442787,1,1,1]))}var f=s(e,h,d),p=s(e,l,d);t.applyTextures(e,f,p)},t}(),Ef="en-US",Mf={en:"en-US",es:"en-ES",zh:"zh-CN","zh-HK":"zh-TW","zh-TW":"zh-HK","zh-MO":"zh-HK",fr:"fr-FR",de:"de-DE",it:"it-IT",ru:"ru-RU",ja:"ja-JP"},Pf={};function Rf(t,e){for(var i=0,n=t.length;i<n;i++)Pf[t[i]]=e}function If(t){var e=t.indexOf("-");return-1!==e?t.substring(0,e):t}function Lf(t,e){if(e[t])return t;var i=Mf[t];if(i&&e[i])return i;var n=If(t);return e[i=Mf[n]]?i:e[n]?n:Ef}Rf(["ja","ko","th","vi","zh","id"],(function(t){return 0})),Rf(["fa","hi"],(function(t){return t>=0&&t<=1?0:1})),Rf(["fr","pt"],(function(t){return t>=0&&t<2?0:1})),Rf(["da"],(function(t){return 1===t||!Number.isInteger(t)&&t>=0&&t<=1?0:1})),Rf(["de","en","it","el","es","tr","fi","sv","nb","no","ur"],(function(t){return 1===t?0:1})),Rf(["ru","uk"],(function(t){if(Number.isInteger(t)){var e=t%10,i=t%100;if(1===e&&11!==i)return 0;if(e>=2&&e<=4&&(i<12||i>14))return 1;if(0===e||e>=5&&e<=9||i>=11&&i<=14)return 2}return 3})),Rf(["pl"],(function(t){if(Number.isInteger(t)){if(1===t)return 0;var e=t%10,i=t%100;if(e>=2&&e<=4&&(i<12||i>14))return 1;if(e>=0&&e<=1||e>=5&&e<=9||i>=12&&i<=14)return 2}return 3})),Rf(["ar"],(function(t){if(0===t)return 0;if(1===t)return 1;if(2===t)return 2;if(Number.isInteger(t)){var e=t%100;if(e>=3&&e<=10)return 3;if(e>=11&&e<=99)return 4}return 5}));var Df=Pf[If(Ef)];function Of(t){return Pf[t]||Df}var kf,Ff=new RegExp("^\\s*(?:(?:[a-z]+[a-z0-9\\-\\+\\.]*:)?//|data:|blob:)","i"),Bf=function(){function t(t,e,i,n,s,r){void 0===t&&(t=""),void 0===e&&(e=""),void 0===i&&(i=null),void 0===n&&(n=null),void 0===s&&(s=null),void 0===r&&(r=null),this.url=t,this.filename=e,this.hash=i,this.size=n,this.opt=s,this.contents=r}return t.prototype.equals=function(t){return this.url===t.url&&this.filename===t.filename&&this.hash===t.hash&&this.size===t.size&&this.opt===t.opt&&this.contents===t.contents},t}(),Uf=-1,Nf={pvr:"extCompressedTexturePVRTC",dxt:"extCompressedTextureS3TC",etc2:"extCompressedTextureETC",etc1:"extCompressedTextureETC1",basis:"canvas"},zf=["pvr","dxt","etc2","etc1","basis"],Vf=function(t){function e(e,i,n,s,r){var a;return(a=t.call(this)||this)._id=Uf--,a._name=e||"",a.type=i,a.tags=new ut(w(a)),a._preload=!1,a._file=null,a._data=s||{},a.options=r||{},a._resources=[],a._i18n={},a.loaded=!1,a.loading=!1,a.registry=null,n&&(a.file=n),a}S(e,t);var i=e.prototype;return i.getFileUrl=function(){var t=this.file;if(!t||!t.url)return null;var e=t.url;if(this.registry&&this.registry.prefix&&!Ff.test(e)&&(e=this.registry.prefix+e),"script"!==this.type&&t.hash){var i=-1!==e.indexOf("?")?"&":"?";e+=i+"t="+t.hash}return e},i.getAbsoluteUrl=function(t){if(t.startsWith("blob:")||t.startsWith("data:"))return t;var e=L.getDirectory(this.file.url);return L.join(e,t)},i.getLocalizedAssetId=function(t){return t=Lf(t,this._i18n),this._i18n[t]||null},i.addLocalizedAssetId=function(t,e){this._i18n[t]=e,this.fire("add:localized",t,e)},i.removeLocalizedAssetId=function(t){var e=this._i18n[t];e&&(delete this._i18n[t],this.fire("remove:localized",t,e))},i.ready=function(t,e){e=e||this,this.loaded?t.call(e,this):this.once("load",(function(i){t.call(e,i)}))},i.reload=function(){this.loaded&&(this.loaded=!1,this.registry.load(this))},i.unload=function(){if(this.loaded||0!==this._resources.length){this.fire("unload",this),this.registry.fire("unload:"+this.id,this);var t=this._resources;this.resources=[],this.loaded=!1,this.file&&this.registry._loader.clearCache(this.getFileUrl(),this.type);for(var e=0;e<t.length;++e){var i=t[e];i&&i.destroy&&i.destroy()}}},e.fetchArrayBuffer=function(t,e,i,n){var s;void 0===n&&(n=0),null!=i&&null!=(s=i.file)&&s.contents?setTimeout((function(){e(null,i.file.contents)})):_a.get(t,{cache:!0,responseType:"arraybuffer",retry:n>0,maxRetries:n},e)},y(e,[{key:"id",get:function(){return this._id},set:function(t){this._id=t}},{key:"name",get:function(){return this._name},set:function(t){if(this._name!==t){var e=this._name;this._name=t,this.fire("name",this,this._name,e)}}},{key:"file",get:function(){return this._file},set:function(t){var e=this;if(t&&t.variants&&-1!==["texture","textureatlas","bundle"].indexOf(this.type)){var i,n=(null==(i=this.registry)||null==(i=i._loader)?void 0:i._app)||vf(),s=null==n?void 0:n.graphicsDevice;if(s)for(var r=function(){var i=zf[a];if(t.variants[i]&&s[Nf[i]])return t=t.variants[i],0;if(n.enableBundles){var r=n.bundles.listBundlesForAsset(e);if(r&&r.find((function(t){var e;return null==t||null==(e=t.file)?void 0:e.variants[i]})))return 0}},a=0,o=zf.length;a<o&&0!==r();a++);}var h=this._file,l=t?new Bf(t.url,t.filename,t.hash,t.size,t.opt,t.contents):null;(!!l!=!!h||l&&!l.equals(h))&&(this._file=l,this.fire("change",this,"file",l,h),this.reload())}},{key:"data",get:function(){return this._data},set:function(t){var e=this._data;this._data=t,t!==e&&(this.fire("change",this,"data",t,e),this.loaded&&this.registry._loader.patch(this,this.registry))}},{key:"resource",get:function(){return this._resources[0]},set:function(t){var e=this._resources[0];this._resources[0]=t,this.fire("change",this,"resource",t,e)}},{key:"resources",get:function(){return this._resources},set:function(t){var e=this._resources;this._resources=t,this.fire("change",this,"resources",t,e)}},{key:"preload",get:function(){return this._preload},set:function(t){t=!!t,this._preload!==t&&(this._preload=t,this._preload&&!this.loaded&&!this.loading&&this.registry&&this.registry.load(this))}},{key:"loadFaces",get:function(){return this._loadFaces},set:function(t){t=!!t,this.hasOwnProperty("_loadFaces")&&t===this._loadFaces||(this._loadFaces=t,this.loaded&&this.registry._loader.patch(this,this.registry))}}]),e}(P),Gf=function(){function t(t){void 0===t&&(t=null),this._index={},this._key=void 0,this._key=t}var e=t.prototype;return e.addItem=function(t){for(var e,i=A(t.tags._list);!(e=i()).done;){var n=e.value;this.add(n,t)}},e.removeItem=function(t){for(var e,i=A(t.tags._list);!(e=i()).done;){var n=e.value;this.remove(n,t)}},e.add=function(t,e){this._index[t]&&-1!==this._index[t].list.indexOf(e)||(this._index[t]||(this._index[t]={list:[]},this._key&&(this._index[t].keys={})),this._index[t].list.push(e),this._key&&(this._index[t].keys[e[this._key]]=e))},e.remove=function(t,e){if(this._index[t]&&(!this._key||this._index[t].keys[e[this._key]])){var i=this._index[t].list.indexOf(e);-1!==i&&(this._index[t].list.splice(i,1),this._key&&delete this._index[t].keys[e[this._key]],0===this._index[t].list.length&&delete this._index[t])}},e.find=function(t){for(var e,i,n,s,r,a=this,o={},h=[],l=function(t,e){return a._index[t].list.length-a._index[e].list.length},c=0;c<t.length;c++){if((i=t[c])instanceof Array){if(0===i.length)continue;if(1!==i.length){r=!1;for(var u=0;u<i.length;u++)if(!this._index[i[u]]){r=!0;break}if(r)continue;1===(s=(n=i.slice(0).sort(l)).slice(1)).length&&(s=s[0]);for(var d=0;d<this._index[n[0]].list.length;d++)e=this._index[n[0]].list[d],(this._key?!o[e[this._key]]:-1===h.indexOf(e))&&e.tags.has(s)&&(this._key&&(o[e[this._key]]=!0),h.push(e));continue}i=i[0]}if(i&&"string"==typeof i&&this._index[i])for(var f=0;f<this._index[i].list.length;f++)e=this._index[i].list[f],this._key?o[e[this._key]]||(o[e[this._key]]=!0,h.push(e)):-1===h.indexOf(e)&&h.push(e)}return h},t}(),Hf=function(t){function e(e){var i;return(i=t.call(this)||this)._assets=new Set,i._idToAsset=new Map,i._urlToAsset=new Map,i._nameToAsset=new Map,i._tags=new Gf("_id"),i.prefix=null,i._loader=e,i}S(e,t);var i=e.prototype;return i.list=function(t){void 0===t&&(t={});var e=Array.from(this._assets);return void 0!==t.preload?e.filter((function(e){return e.preload===t.preload})):e},i.add=function(t){var e,i;this._assets.has(t)||(this._assets.add(t),this._idToAsset.set(t.id,t),null!=(e=t.file)&&e.url&&this._urlToAsset.set(t.file.url,t),this._nameToAsset.has(t.name)||this._nameToAsset.set(t.name,new Set),this._nameToAsset.get(t.name).add(t),t.on("name",this._onNameChange,this),t.registry=this,this._tags.addItem(t),t.tags.on("add",this._onTagAdd,this),t.tags.on("remove",this._onTagRemove,this),this.fire("add",t),this.fire("add:"+t.id,t),null!=(i=t.file)&&i.url&&this.fire("add:url:"+t.file.url,t),t.preload&&this.load(t))},i.remove=function(t){var e,i;if(!this._assets.has(t))return!1;if(this._assets.delete(t),this._idToAsset.delete(t.id),null!=(e=t.file)&&e.url&&this._urlToAsset.delete(t.file.url),t.off("name",this._onNameChange,this),this._nameToAsset.has(t.name)){var n=this._nameToAsset.get(t.name);n.delete(t),0===n.size&&this._nameToAsset.delete(t.name)}return this._tags.removeItem(t),t.tags.off("add",this._onTagAdd,this),t.tags.off("remove",this._onTagRemove,this),t.fire("remove",t),this.fire("remove",t),this.fire("remove:"+t.id,t),null!=(i=t.file)&&i.url&&this.fire("remove:url:"+t.file.url,t),!0},i.get=function(t){return this._idToAsset.get(Number(t))},i.getByUrl=function(t){return this._urlToAsset.get(t)},i.load=function(t){var e=this;if(!t.loading&&!t.loaded){var i=t.file,n=function(n){n instanceof Array?t.resources=n:t.resource=n,e._loader.patch(t,e),e.fire("load",t),e.fire("load:"+t.id,t),i&&i.url&&e.fire("load:url:"+i.url,t),t.fire("load",t)};if(i||"cubemap"===t.type)this.fire("load:start",t),this.fire("load:"+t.id+":start",t),t.loading=!0,this._loader.load(t.getFileUrl(),t.type,(function(i,s,r){if(t.loaded=!0,t.loading=!1,i)e.fire("error",i,t),e.fire("error:"+t.id,i,t),t.fire("error",i,t);else{if(!bf.legacy&&"script"===t.type){var a=e._loader.getHandler("script");a._cache[t.id]&&a._cache[t.id].parentNode===document.head&&document.head.removeChild(a._cache[t.id]),a._cache[t.id]=r}n(s)}}),t);else{var s=this._loader.open(t.type,t.data);t.loaded=!0,n(s)}}},i.loadFromUrl=function(t,e,i){this.loadFromUrlAndFilename(t,null,e,i)},i.loadFromUrlAndFilename=function(t,e,i,n){var s=this,r=L.getBasename(e||t),a={filename:e||r,url:t},o=this.getByUrl(t);if(o){if(o.loaded)return void n(o.loadFromUrlError||null,o)}else o=new Vf(r,i,a),this.add(o);var h=function(t){t.once("load",(function(t){"material"===i?s._loadTextures(t,(function(e,i){n(e,t)})):n(null,t)})),t.once("error",(function(e){e&&(s.loadFromUrlError=e),n(e,t)})),s.load(t)};o.resource?n(null,o):"model"===i?this._loadModel(o,h):h(o)},i._loadModel=function(t,e){var i=this,n=t.getFileUrl(),s=L.getExtension(n);if(".json"===s||".glb"===s){var r=L.getDirectory(n),a=L.getBasename(n),o=L.join(r,a.replace(s,".mapping.json"));this._loader.load(o,"json",(function(n,s){n?(t.data={mapping:[]},e(t)):i._loadMaterials(t,s,(function(i,n){t.data=s,e(t)}))}))}else e(t)},i._loadMaterials=function(t,e,i){for(var n=this,s=[],r=0,a=function(t,e){n._loadTextures(e,(function(t,n){s.push(e),s.length===r&&i(null,s)}))},o=0;o<e.mapping.length;o++){var h=e.mapping[o].path;if(h){r++;var l=t.getAbsoluteUrl(h);this.loadFromUrl(l,"material",a)}}0===r&&i(null,s)},i._loadTextures=function(t,e){var i=[],n=0,s=t.data;if("path"===s.mappingFormat){for(var r=function(t,s){t&&console.error(t),i.push(s),i.length===n&&e(null,i)},a=eu,o=0;o<a.length;o++){var h=s[a[o]];if(h&&"string"==typeof h){n++;var l=t.getAbsoluteUrl(h);this.loadFromUrl(l,"texture",r)}}0===n&&e(null,i)}else e(null,i)},i._onTagAdd=function(t,e){this._tags.add(t,e)},i._onTagRemove=function(t,e){this._tags.remove(t,e)},i._onNameChange=function(t,e,i){if(this._nameToAsset.has(i)){var n=this._nameToAsset.get(i);n.delete(t),0===n.size&&this._nameToAsset.delete(i)}this._nameToAsset.has(t.name)||this._nameToAsset.set(t.name,new Set),this._nameToAsset.get(t.name).add(t)},i.findByTag=function(){return this._tags.find(arguments)},i.filter=function(t){return Array.from(this._assets).filter((function(e){return t(e)}))},i.find=function(t,e){var i=this._nameToAsset.get(t);if(!i)return null;for(var n,s=A(i);!(n=s()).done;){var r=n.value;if(!e||r.type===e)return r}return null},i.findAll=function(t,e){var i=this._nameToAsset.get(t);if(!i)return[];var n=Array.from(i);return e?n.filter((function(t){return t.type===e})):n},e}(P),Wf=function(){function t(t){this._assets=t,this._bundleAssets={},this._assetsInBundles={},this._urlsInBundles={},this._fileRequests={},this._assets.on("add",this._onAssetAdded,this),this._assets.on("remove",this._onAssetRemoved,this)}var e=t.prototype;return e._onAssetAdded=function(t){if("bundle"===t.type){this._bundleAssets[t.id]=t,this._registerBundleEventListeners(t.id);for(var e=0,i=t.data.assets.length;e<i;e++)this._indexAssetInBundle(t.data.assets[e],t)}else this._assetsInBundles[t.id]&&this._indexAssetFileUrls(t)},e._registerBundleEventListeners=function(t){this._assets.on("load:"+t,this._onBundleLoaded,this),this._assets.on("error:"+t,this._onBundleError,this)},e._unregisterBundleEventListeners=function(t){this._assets.off("load:"+t,this._onBundleLoaded,this),this._assets.off("error:"+t,this._onBundleError,this)},e._indexAssetInBundle=function(t,e){if(this._assetsInBundles[t]){var i=this._assetsInBundles[t];-1===i.indexOf(e)&&i.push(e)}else this._assetsInBundles[t]=[e];var n=this._assets.get(t);n&&this._indexAssetFileUrls(n)},e._indexAssetFileUrls=function(t){var e=this._getAssetFileUrls(t);if(e)for(var i=0,n=e.length;i<n;i++){var s=e[i];this._urlsInBundles[s]=this._assetsInBundles[t.id]}},e._getAssetFileUrls=function(t){var e=t.getFileUrl();if(!e)return null;var i=[e=this._normalizeUrl(e)];if("font"===t.type)for(var n=t.data.info.maps.length,s=1;s<n;s++)i.push(e.replace(".png",s+".png"));return i},e._normalizeUrl=function(t){return t&&t.split("?")[0]},e._onAssetRemoved=function(t){if("bundle"===t.type){for(var e in delete this._bundleAssets[t.id],this._unregisterBundleEventListeners(t.id),this._assetsInBundles){var i=this._assetsInBundles[e],n=i.indexOf(t);if(-1!==n&&(i.splice(n,1),!i.length))for(var s in delete this._assetsInBundles[e],this._urlsInBundles)this._urlsInBundles[s]===i&&delete this._urlsInBundles[s]}this._onBundleError("Bundle "+t.id+" was removed",t)}else if(this._assetsInBundles[t.id]){delete this._assetsInBundles[t.id];for(var r=this._getAssetFileUrls(t),a=0,o=r.length;a<o;a++)delete this._urlsInBundles[r[a]]}},e._onBundleLoaded=function(t){var e=this;t.resource?requestAnimationFrame((function(){if(e._fileRequests)for(var i in e._fileRequests){var n=e._urlsInBundles[i];if(n&&-1!==n.indexOf(t)){var s=decodeURIComponent(i),r=null;t.resource.hasBlobUrl(s)||(r="Bundle "+t.id+" does not contain URL "+i);for(var a=e._fileRequests[i],o=0,h=a.length;o<h;o++)r?a[o](r):a[o](null,t.resource.getBlobUrl(s));delete e._fileRequests[i]}}})):this._onBundleError("Bundle "+t.id+" failed to load",t)},e._onBundleError=function(t,e){for(var i in this._fileRequests){if(!this._findLoadedOrLoadingBundleForUrl(i)){for(var n=this._fileRequests[i],s=0,r=n.length;s<r;s++)n[s](t);delete this._fileRequests[i]}}},e._findLoadedOrLoadingBundleForUrl=function(t){var e=this._urlsInBundles[t];if(!e)return null;for(var i=e.length,n=0;n<i;n++)if(e[n].loaded&&e[n].resource)return e[n];for(var s=0;s<i;s++)if(e[s].loading)return e[s];return null},e.listBundlesForAsset=function(t){return this._assetsInBundles[t.id]||null},e.list=function(){var t=[];for(var e in this._bundleAssets)t.push(this._bundleAssets[e]);return t},e.hasUrl=function(t){return!!this._urlsInBundles[t]},e.canLoadUrl=function(t){return!!this._findLoadedOrLoadingBundleForUrl(t)},e.loadUrl=function(t,e){var i=this._findLoadedOrLoadingBundleForUrl(t);if(i)if(i.loaded){var n=decodeURIComponent(t);if(!i.resource.hasBlobUrl(n))return void e("Bundle "+i.id+" does not contain URL "+t);e(null,i.resource.getBlobUrl(n))}else this._fileRequests.hasOwnProperty(t)?this._fileRequests[t].push(e):this._fileRequests[t]=[e];else e("URL "+t+" not found in any bundles")},e.destroy=function(){for(var t in this._assets.off("add",this._onAssetAdded,this),this._assets.off("remove",this._onAssetRemoved,this),this._bundleAssets)this._unregisterBundleEventListeners(t);this._assets=null,this._bundleAssets=null,this._assetsInBundles=null,this._urlsInBundles=null,this._fileRequests=null},t}(),Xf=function(t){function e(){var e;return(e=t.call(this)||this).anim=void 0,e.animation=void 0,e.audiolistener=void 0,e.audiosource=void 0,e.button=void 0,e.camera=void 0,e.collision=void 0,e.element=void 0,e.joint=void 0,e.layoutchild=void 0,e.layoutgroup=void 0,e.light=void 0,e.model=void 0,e.particlesystem=void 0,e.render=void 0,e.rigidbody=void 0,e.screen=void 0,e.script=void 0,e.scrollbar=void 0,e.scrollview=void 0,e.sound=void 0,e.sprite=void 0,e.zone=void 0,e.list=[],e}S(e,t);var i=e.prototype;return i.add=function(t){var e=t.id;if(this[e])throw new Error("ComponentSystem name '"+e+"' already registered or not allowed");this[e]=t,this.list.push(t)},i.remove=function(t){var e=t.id;if(!this[e])throw new Error("No ComponentSystem named '"+e+"' registered");delete this[e];var i=this.list.indexOf(this[e]);-1!==i&&this.list.splice(i,1)},i.destroy=function(){this.off();for(var t=0;t<this.list.length;t++)this.list[t].destroy()},e}(P),jf=function(){function t(t){this._blobUrls={};for(var e=0,i=t.length;e<i;e++)t[e].url&&(this._blobUrls[t[e].name]=t[e].url)}var e=t.prototype;return e.hasBlobUrl=function(t){return!!this._blobUrls[t]},e.getBlobUrl=function(t){return this._blobUrls[t]},e.destroy=function(){for(var t in this._blobUrls)URL.revokeObjectURL(this._blobUrls[t]);this._blobUrls=null},t}();function qf(t){var e,i;if("undefined"!=typeof TextDecoder)try{e=new TextDecoder("utf-8"),i=new TextDecoder("windows-1252")}catch(t){console.warn("TextDecoder not supported - pc.Untar module will not work")}else console.warn("TextDecoder not supported - pc.Untar module will not work");function n(t){this._fields=t}function s(t){this._arrayBuffer=t||new ArrayBuffer(0),this._bufferView=new DataView(this._arrayBuffer),this._globalPaxHeader=null,this._paxHeader=null,this._bytesRead=0}n.parse=function(t,i,s){for(var r=new Uint8Array(t,i,s),a=0,o=[];a<s;){var h=void 0;for(h=a;h<s&&32!==r[h];h++);if(h>=s)throw new Error("Invalid PAX header data format.");var l=parseInt(e.decode(new Uint8Array(t,i+a,h-a)),10),c=e.decode(new Uint8Array(t,i+h+1,l-(h-a)-2)).split("=");if(2!==c.length)throw new Error("Invalid PAX header data format.");0===c[1].length&&(c[1]=null),o.push({name:c[0],value:c[1]}),a+=l}return new n(o)},n.prototype.applyHeader=function(t){for(var e=0;e<this._fields.length;e++){var i=this._fields[e].name,n=this._fields[e].value;"path"===i&&(i="name"),null===n?delete t[i]:t[i]=n}},t||(kf=s),s.prototype._hasNext=function(){return this._bytesRead+4<this._arrayBuffer.byteLength&&0!==this._bufferView.getUint32(this._bytesRead)},s.prototype._readNextFile=function(){var e=new DataView(this._arrayBuffer,this._bytesRead,512),s=i.decode(e);this._bytesRead+=512;var r=s.substring(0,100).replace(/\0/g,""),a=s.substring(257,263),o=parseInt(s.substring(124,136),8),h=s.substring(156,157),l=this._bytesRead,c=null,u=!1;switch(h){case"0":case"":if(u=!0,!t){var d=new Blob([this._arrayBuffer.slice(this._bytesRead,this._bytesRead+o)]);c=URL.createObjectURL(d)}break;case"g":this._globalPaxHeader=n.parse(this._arrayBuffer,this._bytesRead,o);break;case"x":this._paxHeader=n.parse(this._arrayBuffer,this._bytesRead,o)}this._bytesRead+=o;var f=o%512;if(0!==f&&(this._bytesRead+=512-f),!u)return null;if(-1!==a.indexOf("ustar")){var p=s.substring(345,500).replace(/\0/g,"");p.length>0&&(r=p.trim()+r.trim())}var m={name:r,start:l,size:o,url:c};return this._globalPaxHeader&&this._globalPaxHeader.applyHeader(m),this._paxHeader&&(this._paxHeader.applyHeader(m),this._paxHeader=null),m},s.prototype.untar=function(t){if(!e)return console.error("Cannot untar because TextDecoder interface is not available for this platform."),[];for(var i=[];this._hasNext();){var n=this._readNextFile();n&&(t&&n.name&&(n.name=t+n.name),i.push(n))}return i},t&&(self.onmessage=function(t){var e=t.data.id;try{var i=new s(t.data.arrayBuffer).untar(t.data.prefix);postMessage({id:e,files:i,arrayBuffer:t.data.arrayBuffer},[t.data.arrayBuffer])}catch(t){postMessage({id:e,error:t.toString()})}})}var Yf=null;var Kf=function(){function t(t){this._requestId=0,this._pendingRequests={},this._filenamePrefix=t,this._worker=new Worker(function(){if(!Yf){var t="("+qf.toString()+")(true)\n\n",e=new Blob([t],{type:"application/javascript"});Yf=URL.createObjectURL(e)}return Yf}()),this._worker.addEventListener("message",this._onMessage.bind(this))}var e=t.prototype;return e._onMessage=function(t){var e=t.data.id;if(this._pendingRequests[e]){var i=this._pendingRequests[e];if(delete this._pendingRequests[e],t.data.error)i(t.data.error);else{for(var n=t.data.arrayBuffer,s=0,r=t.data.files.length;s<r;s++){var a=t.data.files[s],o=new Blob([n.slice(a.start,a.start+a.size)]);a.url=URL.createObjectURL(o)}i(null,t.data.files)}}},e.untar=function(t,e){var i=this._requestId++;this._pendingRequests[i]=e,this._worker.postMessage({id:i,prefix:this._filenamePrefix,arrayBuffer:t},[t])},e.hasPendingRequests=function(){return Object.keys(this._pendingRequests).length>0},e.destroy=function(){this._worker&&(this._worker.terminate(),this._worker=null,this._pendingRequests=null)},t}();qf();var Zf=function(){function t(t){this.handlerType="bundle",this._assets=t.assets,this._worker=null,this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t});var i=this;_a.get(t.load,{responseType:ma.ResponseType.ARRAY_BUFFER,retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(n,s){if(n)e("Error loading bundle resource "+t.original+": "+n);else try{i._untar(s,e)}catch(i){e("Error loading bundle resource "+t.original+": "+i)}}))},e._untar=function(t,e){var i=this;if(G.workers)i._worker||(i._worker=new Kf(i._assets.prefix)),i._worker.untar(t,(function(t,n){e(t,n),i._worker.hasPendingRequests()||(i._worker.destroy(),i._worker=null)}));else{var n=new kf(t).untar(i._assets.prefix);e(null,n)}},e.open=function(t,e){return new jf(e)},e.patch=function(t,e){},t}(),Qf=function(){function t(t){this._handlers={},this._requests={},this._cache={},this._app=t}var e=t.prototype;return e.addHandler=function(t,e){this._handlers[t]=e,e._loader=this},e.removeHandler=function(t){delete this._handlers[t]},e.getHandler=function(t){return this._handlers[t]},t.makeKey=function(t,e){return t+"-"+e},e.load=function(e,i,n,s){var r=this._handlers[i];if(r)if(e){var a=t.makeKey(e,i);if(void 0!==this._cache[a])n(null,this._cache[a]);else if(this._requests[a])this._requests[a].push(n);else{this._requests[a]=[n];var o=this,h=function(t,e){t?o._onFailure(a,t):r.load(e,(function(t,i,n){if(o._requests[a])if(t)o._onFailure(a,t);else try{o._onSuccess(a,r.open(e.original,i,s),n)}catch(t){o._onFailure(a,t)}}),s)},l=e.split("?")[0];if(this._app.enableBundles&&this._app.bundles.hasUrl(l)){if(!this._app.bundles.canLoadUrl(l))return void h("Bundle for "+e+" not loaded yet");this._app.bundles.loadUrl(l,(function(t,e){h(t,{load:e,original:l})}))}else h(null,{load:e,original:s&&s.file.filename||e})}}else this._loadNull(r,n,s);else n("No resource handler for asset type: '"+i+"' when loading ["+e+"]")},e._loadNull=function(t,e,i){t.load(null,(function(n,s,r){if(n)e(n);else try{e(null,t.open(null,s,i),r)}catch(t){e(t)}}),i)},e._onSuccess=function(t,e,i){null!==e?this._cache[t]=e:delete this._cache[t];for(var n=0;n<this._requests[t].length;n++)this._requests[t][n](null,e,i);delete this._requests[t]},e._onFailure=function(t,e){if(console.error(e),this._requests[t]){for(var i=0;i<this._requests[t].length;i++)this._requests[t][i](e);delete this._requests[t]}},e.open=function(t,e){var i=this._handlers[t];return i?i.open(null,e):(console.warn("No resource handler found for: "+t),e)},e.patch=function(t,e){var i=this._handlers[t.type];i?i.patch&&i.patch(t,e):console.warn("No resource handler found for: "+t.type)},e.clearCache=function(e,i){var n=t.makeKey(e,i);delete this._cache[n]},e.getFromCache=function(e,i){var n=t.makeKey(e,i);if(this._cache[n])return this._cache[n]},e.enableRetry=function(t){for(var e in void 0===t&&(t=5),t=Math.max(0,t)||0,this._handlers)this._handlers[e].maxRetries=t},e.disableRetry=function(){for(var t in this._handlers)this._handlers[t].maxRetries=0},e.destroy=function(){this._handlers={},this._requests={},this._cache={}},t}(),$f=function(){function t(){}var e=t.prototype;return e._validate=function(t){if(!t.header)throw new Error('pc.I18n#addData: Missing "header" field');if(!t.header.version)throw new Error('pc.I18n#addData: Missing "header.version" field');if(1!==t.header.version)throw new Error('pc.I18n#addData: Invalid "header.version" field');if(!t.data)throw new Error('pc.I18n#addData: Missing "data" field');if(!Array.isArray(t.data))throw new Error('pc.I18n#addData: "data" field must be an array');for(var e=0,i=t.data.length;e<i;e++){var n=t.data[e];if(!n.info)throw new Error('pc.I18n#addData: missing "data['+e+'].info" field');if(!n.info.locale)throw new Error('pc.I18n#addData: missing "data['+e+'].info.locale" field');if("string"!=typeof n.info.locale)throw new Error('pc.I18n#addData: "data['+e+'].info.locale" must be a string');if(!n.messages)throw new Error('pc.I18n#addData: missing "data['+e+'].messages" field')}},e.parse=function(t){return t.data},t}(),Jf=function(t){function e(e){var i;return(i=t.call(this)||this).locale=Ef,i._translations={},i._availableLangs={},i._app=e,i._assets=[],i._parser=new $f,i}S(e,t),e.findAvailableLocale=function(t,e){return Lf(t,e)};var i=e.prototype;return i.findAvailableLocale=function(t){if(this._translations[t])return t;var e=If(t);return this._findFallbackLocale(t,e)},i.getText=function(t,e){var i,n=t;e||(e=this._locale,i=this._lang);var s=this._translations[e];return s||(i||(i=If(e)),e=this._findFallbackLocale(e,i),s=this._translations[e]),s&&s.hasOwnProperty(t)&&(n=s[t],Array.isArray(n)&&(n=n[0]),null==n&&(n=t)),n},i.getPluralText=function(t,e,i){var n,s,r=t;i?s=Of(n=If(i)):(i=this._locale,n=this._lang,s=this._pluralFn);var a=this._translations[i];if(a||(s=Of(n=If(i=this._findFallbackLocale(i,n))),a=this._translations[i]),a&&a[t]&&s){var o=s(e);null==(r=a[t][o])&&(r=t)}return r},i.addData=function(t){var e;try{e=this._parser.parse(t)}catch(t){return void console.error(t)}for(var i=0,n=e.length;i<n;i++){var s=e[i],r=s.info.locale,a=s.messages;if(!this._translations[r]){this._translations[r]={};var o=If(r);this._availableLangs[o]||(this._availableLangs[o]=r)}Object.assign(this._translations[r],a),this.fire("data:add",r,a)}},i.removeData=function(t){var e;try{e=this._parser.parse(t)}catch(t){return void console.error(t)}for(var i=0,n=e.length;i<n;i++){var s=e[i],r=s.info.locale,a=this._translations[r];if(a){var o=s.messages;for(var h in o)delete a[h];0===Object.keys(a).length&&(delete this._translations[r],delete this._availableLangs[If(r)]),this.fire("data:remove",r,o)}}},i.destroy=function(){this._translations=null,this._availableLangs=null,this._assets=null,this._parser=null,this.off()},i._findFallbackLocale=function(t,e){var i=Mf[t];return i&&this._translations[i]||(i=Mf[e])&&this._translations[i]||(i=this._availableLangs[e])&&this._translations[i]?i:Ef},i._onAssetAdd=function(t){t.on("load",this._onAssetLoad,this),t.on("change",this._onAssetChange,this),t.on("remove",this._onAssetRemove,this),t.on("unload",this._onAssetUnload,this),t.resource&&this._onAssetLoad(t)},i._onAssetLoad=function(t){this.addData(t.resource)},i._onAssetChange=function(t){t.resource&&this.addData(t.resource)},i._onAssetRemove=function(t){t.off("load",this._onAssetLoad,this),t.off("change",this._onAssetChange,this),t.off("remove",this._onAssetRemove,this),t.off("unload",this._onAssetUnload,this),t.resource&&this.removeData(t.resource),this._app.assets.once("add:"+t.id,this._onAssetAdd,this)},i._onAssetUnload=function(t){t.resource&&this.removeData(t.resource)},y(e,[{key:"assets",get:function(){return this._assets},set:function(t){for(var e={},i=0,n=t.length;i<n;i++){e[t[i]instanceof Vf?t[i].id:t[i]]=!0}for(var s=this._assets.length;s--;){var r=this._assets[s];if(!e[r]){this._app.assets.off("add:"+r,this._onAssetAdd,this);var a=this._app.assets.get(r);a&&this._onAssetRemove(a),this._assets.splice(s,1)}}for(var o in e){var h=parseInt(o,10);if(-1===this._assets.indexOf(h)){this._assets.push(h);var l=this._app.assets.get(h);l?this._onAssetAdd(l):this._app.assets.once("add:"+h,this._onAssetAdd,this)}}}},{key:"locale",get:function(){return this._locale},set:function(t){if(this._locale!==t){var e=If(t);if("in"!==e||(n=e="id",t=-1!==(s=(i=t).indexOf("-"))?n+i.substring(s):n,this._locale!==t)){var i,n,s,r=this._locale;this._locale=t,this._lang=e,this._pluralFn=Of(this._lang),this.fire("set:locale",t,r)}}}}]),e}(P),tp=function(t){function e(e){var i;return(i=t.call(this)||this).app=e,i._scripts={},i._list=[],i}S(e,t);var i=e.prototype;return i.destroy=function(){this.app=null,this.off()},i.add=function(t){var e=this,i=t.__name;return this._scripts.hasOwnProperty(i)?(setTimeout((function(){if(t.prototype.swap){var n=e._scripts[i],s=e._list.indexOf(n);e._list[s]=t,e._scripts[i]=t,e.fire("swap",i,t),e.fire("swap:"+i,t)}else console.warn("script registry already has '"+i+"' script, define 'swap' method for new script type to enable code hot swapping")})),!1):(this._scripts[i]=t,this._list.push(t),this.fire("add",i,t),this.fire("add:"+i,t),setTimeout((function(){if(e._scripts.hasOwnProperty(i)&&e.app&&e.app.systems&&e.app.systems.script){var t,n=e.app.systems.script._components,s=[],r=[];for(n.loopIndex=0;n.loopIndex<n.length;n.loopIndex++){var a=n.items[n.loopIndex];if(a._scriptsIndex[i]&&a._scriptsIndex[i].awaiting){a._scriptsData&&a._scriptsData[i]&&(t=a._scriptsData[i].attributes);var o=a.create(i,{preloading:!0,ind:a._scriptsIndex[i].ind,attributes:t});o&&s.push(o)}}for(var h=0;h<s.length;h++)s[h].__initializeAttributes();for(var l=0;l<s.length;l++)s[l].enabled&&(s[l]._initialized=!0,r.push(s[l]),s[l].initialize&&s[l].initialize());for(var c=0;c<r.length;c++)r[c].enabled&&!r[c]._postInitialized&&(r[c]._postInitialized=!0,r[c].postInitialize&&r[c].postInitialize())}})),!0)},i.remove=function(t){var e=t,i=t;if("string"!=typeof i?i=e.__name:e=this.get(i),this.get(i)!==e)return!1;delete this._scripts[i];var n=this._list.indexOf(e);return this._list.splice(n,1),this.fire("remove",i,e),this.fire("remove:"+i,e),!0},i.get=function(t){return this._scripts[t]||null},i.has=function(t){if("string"==typeof t)return this._scripts.hasOwnProperty(t);if(!t)return!1;var e=t.__name;return this._scripts[e]===t},i.list=function(){return this._list},e}(P),ep=[],ip=function(t){function e(e,i){var n;return void 0===i&&(i=vf()),(n=t.call(this,e)||this).anim=void 0,n.animation=void 0,n.audiolistener=void 0,n.button=void 0,n.camera=void 0,n.collision=void 0,n.element=void 0,n.layoutchild=void 0,n.layoutgroup=void 0,n.light=void 0,n.model=void 0,n.particlesystem=void 0,n.render=void 0,n.rigidbody=void 0,n.screen=void 0,n.script=void 0,n.scrollbar=void 0,n.scrollview=void 0,n.sound=void 0,n.sprite=void 0,n.c={},n._app=void 0,n._destroying=!1,n._guid=null,n._template=!1,n._app=i,n}S(e,t);var i=e.prototype;return i.addComponent=function(t,e){var i=this._app.systems[t];return i?this.c[t]?null:i.addComponent(this,e):null},i.removeComponent=function(t){var e=this._app.systems[t];e&&this.c[t]&&e.removeComponent(this)},i.findComponent=function(t){var e=this.findOne((function(e){return e.c&&e.c[t]}));return e&&e.c[t]},i.findComponents=function(t){return this.find((function(e){return e.c&&e.c[t]})).map((function(e){return e.c[t]}))},i.getGuid=function(){return this._guid||this.setGuid(I.create()),this._guid},i.setGuid=function(t){var e=this._app._entityIndex;this._guid&&delete e[this._guid],this._guid=t,e[this._guid]=this},i._notifyHierarchyStateChanged=function(t,e){var i=!1;t===this&&0===ep.length&&(i=!0),t._beingEnabled=!0,t._onHierarchyStateChanged(e),t._onHierarchyStatePostChanged&&ep.push(t);for(var n=t._children,s=0,r=n.length;s<r;s++)n[s]._enabled&&this._notifyHierarchyStateChanged(n[s],e);if(t._beingEnabled=!1,i){for(var a=0;a<ep.length;a++)ep[a]._onHierarchyStatePostChanged();ep.length=0}},i._onHierarchyStateChanged=function(e){t.prototype._onHierarchyStateChanged.call(this,e);var i=this.c;for(var n in i)if(i.hasOwnProperty(n)){var s=i[n];s.enabled&&(e?s.onEnable():s.onDisable())}},i._onHierarchyStatePostChanged=function(){var t=this.c;for(var e in t)t.hasOwnProperty(e)&&t[e].onPostStateChange()},i.findByGuid=function(t){if(this._guid===t)return this;var e=this._app._entityIndex[t];return e&&(e===this||e.isDescendantOf(this))?e:null},i.destroy=function(){for(var e in this._destroying=!0,this.c)this.c[e].enabled=!1;for(var i in this.c)this.c[i].system.removeComponent(this);t.prototype.destroy.call(this),this._guid&&delete this._app._entityIndex[this._guid],this._destroying=!1},i.clone=function(){var t={},e=this._cloneRecursively(t);return t[this.getGuid()]=e,np(this,this,e,t),e},i._cloneRecursively=function(i){var n=new this.constructor(void 0,this._app);for(var s in t.prototype._cloneInternal.call(this,n),this.c){this.c[s].system.cloneComponent(this,n)}for(var r=0;r<this._children.length;r++){var a=this._children[r];if(a instanceof e){var o=a._cloneRecursively(i);n.addChild(o),i[a.getGuid()]=o}}return n},e}(hh);function np(t,e,i,n){if(e instanceof ip){var s=e.c;for(var r in s)for(var a=s[r],o=a.system.getPropertiesOfType("entity"),h=0,l=o.length;h<l;h++){var c=o[h].name,u=a[c];if(!!t.findByGuid(u)){var d=n[u].getGuid();d&&(i.c[r][c]=d)}}s.script&&!i._app.useLegacyScriptAttributeCloning&&i.script.resolveDuplicatedEntityReferenceProperties(s.script,n),s.render&&i.render.resolveDuplicatedEntityReferenceProperties(s.render,n),s.anim&&i.anim.resolveDuplicatedEntityReferenceProperties(s.anim,n);for(var f=e.children.filter((function(t){return t instanceof ip})),p=i.children.filter((function(t){return t instanceof ip})),m=0,_=f.length;m<_;m++)np(t,f[m],p[m],n)}}var sp=function(){function t(t,e){this.name=void 0,this.url=void 0,this.data=null,this._loading=!1,this._onLoadedCallbacks=[],this.name=t,this.url=e}return y(t,[{key:"loaded",get:function(){return!!this.data}},{key:"loading",get:function(){return this._loading}}]),t}(),rp=function(){function t(t){this._app=void 0,this._list=[],this._index={},this._urlIndex={},this._app=t}var e=t.prototype;return e.destroy=function(){this._app=null},e.list=function(){return this._list},e.add=function(t,e){if(this._index.hasOwnProperty(t))return!1;var i=new sp(t,e),n=this._list.push(i);return this._index[i.name]=n-1,this._urlIndex[i.url]=n-1,!0},e.find=function(t){return this._index.hasOwnProperty(t)?this._list[this._index[t]]:null},e.findByUrl=function(t){return this._urlIndex.hasOwnProperty(t)?this._list[this._urlIndex[t]]:null},e.remove=function(t){if(this._index.hasOwnProperty(t)){var e=this._index[t],i=this._list[e];delete this._urlIndex[i.url],delete this._index[t],this._list.splice(e,1);for(var n=0;n<this._list.length;n++)i=this._list[n],this._index[i.name]=n,this._urlIndex[i.url]=n}},e._loadSceneData=function(t,e,i){var n=this._app,s=t;if("string"==typeof t&&(t=this.findByUrl(s)||this.find(s)||new sp("Untitled",s)),s=t.url)if(t.loaded)i(null,t);else{if(n.assets&&n.assets.prefix&&!Ff.test(s)&&(s=L.join(n.assets.prefix,s)),t._onLoadedCallbacks.push(i),!t._loading)n.loader.getHandler("hierarchy").load(s,(function(i,n){t.data=n,t._loading=!1;for(var s=0;s<t._onLoadedCallbacks.length;s++)t._onLoadedCallbacks[s](i,t);e||(t.data=null),t._onLoadedCallbacks.length=0}));t._loading=!0}else i("Cannot find scene to load")},e.loadSceneData=function(t,e){this._loadSceneData(t,!0,e)},e.unloadSceneData=function(t){"string"==typeof t&&(t=this.findByUrl(t)),t&&(t.data=null)},e._loadSceneHierarchy=function(t,e,i){var n=this;this._loadSceneData(t,!1,(function(t,s){if(t)i&&i(t);else{e&&e(s);var r=n._app;r._preloadScripts(s.data,(function(){var t=r.loader.getHandler("hierarchy");r.systems.script.preloading=!0;var e=t.open(s.url,s.data);r.systems.script.preloading=!1,r.loader.clearCache(s.url,"hierarchy"),r.root.addChild(e),r.systems.fire("initialize",e),r.systems.fire("postInitialize",e),r.systems.fire("postPostInitialize",e),i&&i(null,e)}))}}))},e.loadSceneHierarchy=function(t,e){this._loadSceneHierarchy(t,null,e)},e.loadSceneSettings=function(t,e){var i=this;this._loadSceneData(t,!1,(function(t,n){t?e&&e(t):(i._app.applySceneSettings(n.data.settings),e&&e(null))}))},e.changeScene=function(t,e){var i=this._app;this._loadSceneHierarchy(t,(function(t){for(var e=i.root.children;e.length;)e[0].destroy();i.applySceneSettings(t.data.settings)}),e)},e.loadScene=function(t,e){var i=this,n=this._app,s=n.loader.getHandler("scene");n.assets&&n.assets.prefix&&!Ff.test(t)&&(t=L.join(n.assets.prefix,t)),s.load(t,(function(r,a){if(r)e&&e(r);else{n._preloadScripts(a,(function(){n.systems.script.preloading=!0;var r=s.open(t,a),o=i.findByUrl(t);o&&!o.loaded&&(o.data=a),n.systems.script.preloading=!1,n.loader.clearCache(t,"scene"),n.loader.patch({resource:r,type:"scene"},n.assets),n.root.addChild(r.root),n.systems.rigidbody&&"undefined"!=typeof Ammo&&n.systems.rigidbody.gravity.set(r._gravity.x,r._gravity.y,r._gravity.z),e&&e(null,r)}))}}))},t}(),ap=function(){function t(t){this.frame={fps:0,ms:0,dt:0,updateStart:0,updateTime:0,renderStart:0,renderTime:0,physicsStart:0,physicsTime:0,cullTime:0,sortTime:0,skinTime:0,morphTime:0,instancingTime:0,triangles:0,otherPrimitives:0,shaders:0,materials:0,cameras:0,shadowMapUpdates:0,shadowMapTime:0,depthMapTime:0,forwardTime:0,lightClustersTime:0,lightClusters:0,_timeToCountFrames:0,_fpsAccum:0},this.drawCalls={forward:0,depth:0,shadow:0,immediate:0,misc:0,total:0,skinned:0,instanced:0,removedByInstancing:0},this.misc={renderTargetCreationTime:0},this.particles={updatesPerFrame:0,_updatesPerFrame:0,frameTime:0,_frameTime:0},this.shaders=t._shaderStats,this.vram=t._vram,Object.defineProperty(this.vram,"totalUsed",{get:function(){return this.tex+this.vb+this.ib}}),Object.defineProperty(this.vram,"geom",{get:function(){return this.vb+this.ib}})}return y(t,[{key:"scene",get:function(){return vf().scene._stats}},{key:"lightmapper",get:function(){var t;return null==(t=vf().lightmapper)?void 0:t.stats}},{key:"batcher",get:function(){var t=vf()._batcher;return t?t._stats:null}}]),t}(),op=function(){function t(t){this.length=t,this.count=0}var e=t.prototype;return e.inc=function(){this.count++},e.done=function(){return this.count===this.length},t}();t.app=null;var hp=function(e){function i(n){var s;return s=e.call(this)||this,i._applications[n.id]=w(s),gf(w(s)),t.app=w(s),s._destroyRequested=!1,s._inFrameUpdate=!1,s._time=0,s.timeScale=1,s.maxDeltaTime=.1,s.frame=0,s.autoRender=!0,s.renderNextFrame=!1,s.useLegacyScriptAttributeCloning=bf.legacy,s._librariesLoaded=!1,s._fillMode=pf,s._resolutionMode=_f,s._allowResize=!0,s.context=w(s),s}S(i,e);var n=i.prototype;return n.init=function(t){var e=this,i=t.graphicsDevice;this.graphicsDevice=i,Ha.set(i),this._initDefaultMaterial(),this._initProgramLibrary(),this.stats=new ap(i),this._soundManager=t.soundManager,this.loader=new Qf(this),ll.init(i),this._entityIndex={},this.scene=new Yd(i),this._registerSceneImmediate(this.scene),this.root=new ip,this.root._enabledInHierarchy=!0,this.assets=new Hf(this.loader),t.assetPrefix&&(this.assets.prefix=t.assetPrefix),this.bundles=new Wf(this.assets),this.enableBundles="undefined"!=typeof TextDecoder,this.scriptsOrder=t.scriptsOrder||[],this.scripts=new tp(this),this.i18n=new Jf(this),this.scenes=new rp(this),this.defaultLayerWorld=new Cu({name:"World",id:0}),this.defaultLayerDepth=new Cu({name:"Depth",id:1,enabled:!1,opaqueSortMode:0}),this.defaultLayerSkybox=new Cu({name:"Skybox",id:2,opaqueSortMode:0}),this.defaultLayerUi=new Cu({name:"UI",id:4,transparentSortMode:1}),this.defaultLayerImmediate=new Cu({name:"Immediate",id:3,opaqueSortMode:0});var n=new Ru("default");n.pushOpaque(this.defaultLayerWorld),n.pushOpaque(this.defaultLayerDepth),n.pushOpaque(this.defaultLayerSkybox),n.pushTransparent(this.defaultLayerWorld),n.pushOpaque(this.defaultLayerImmediate),n.pushTransparent(this.defaultLayerImmediate),n.pushTransparent(this.defaultLayerUi),this.scene.layers=n,Cf.createPlaceholder(i),this.renderer=new yu(i),this.renderer.scene=this.scene,this.frameGraph=new wf,this.lightmapper=null,t.lightmapper&&(this.lightmapper=new t.lightmapper(i,this.root,this.scene,this.renderer,this.assets),this.once("prerender",this._firstBake,this)),this._batcher=null,t.batchManager&&(this._batcher=new t.batchManager(i,this.root,this.scene),this.once("prerender",this._firstBatch,this)),this.keyboard=t.keyboard||null,this.mouse=t.mouse||null,this.touch=t.touch||null,this.gamepads=t.gamepads||null,this.elementInput=t.elementInput||null,this.elementInput&&(this.elementInput.app=this),this.xr=t.xr?new t.xr(this):null,this.elementInput&&this.elementInput.attachSelectEvents(),this._inTools=!1,this._skyboxAsset=null,this._scriptPrefix=t.scriptPrefix||"",this.enableBundles&&this.loader.addHandler("bundle",new Zf(this)),t.resourceHandlers.forEach((function(t){var i=new t(e);e.loader.addHandler(i.handlerType,i)})),this.systems=new Xf,t.componentSystems.forEach((function(t){e.systems.add(new t(e))})),this._visibilityChangeHandler=this.onVisibilityChange.bind(this),"undefined"!=typeof document&&(void 0!==document.hidden?(this._hiddenAttr="hidden",document.addEventListener("visibilitychange",this._visibilityChangeHandler,!1)):void 0!==document.mozHidden?(this._hiddenAttr="mozHidden",document.addEventListener("mozvisibilitychange",this._visibilityChangeHandler,!1)):void 0!==document.msHidden?(this._hiddenAttr="msHidden",document.addEventListener("msvisibilitychange",this._visibilityChangeHandler,!1)):void 0!==document.webkitHidden&&(this._hiddenAttr="webkitHidden",document.addEventListener("webkitvisibilitychange",this._visibilityChangeHandler,!1))),this.tick=cp(this)},i.getApplication=function(t){return t?i._applications[t]:vf()},n._initDefaultMaterial=function(){var t=new lu;t.name="Default Material",t.shadingModel=1,function(t,e){Fo.get(t,(function(){return e}))}(this.graphicsDevice,t)},n._initProgramLibrary=function(){var t=new uf(this.graphicsDevice,new lu);yo(this.graphicsDevice,t)},n.configure=function(t,e){var i=this;_a.get(t,(function(t,n){if(t)e(t);else{var s=n.application_properties,r=n.scenes,a=n.assets;i._parseApplicationProperties(s,(function(t){i._parseScenes(r),i._parseAssets(a),e(t||null)}))}}))},n.preload=function(t){var e=this;this.fire("preload:start");var i=this.assets.list({preload:!0}),n=new op(i.length),s=!1,r=function(){e.graphicsDevice&&!s&&n.done()&&(s=!0,e.fire("preload:end"),t())},a=i.length;if(n.length)for(var o=function(t){n.inc(),e.fire("preload:progress",n.count/a),n.done()&&r()},h=function(t,i){n.inc(),e.fire("preload:progress",n.count/a),n.done()&&r()},l=0;l<i.length;l++)i[l].loaded?(n.inc(),this.fire("preload:progress",n.count/a),n.done()&&r()):(i[l].once("load",o),i[l].once("error",h),this.assets.load(i[l]));else r()},n._preloadScripts=function(t,e){var i=this;if(bf.legacy){this.systems.script.preloading=!0;var n=this._getScriptReferences(t),s=n.length,r=new op(s),a=/^http(s)?:\/\//;if(s)for(var o=function(t,n){t&&console.error(t),r.inc(),r.done()&&(i.systems.script.preloading=!1,e())},h=0;h<s;h++){var l=n[h];!a.test(l.toLowerCase())&&this._scriptPrefix&&(l=L.join(this._scriptPrefix,n[h])),this.loader.load(l,"script",o)}else this.systems.script.preloading=!1,e()}else e()},n._parseApplicationProperties=function(t,e){if("number"==typeof t.maxAssetRetries&&t.maxAssetRetries>0&&this.loader.enableRetry(t.maxAssetRetries),t.useDevicePixelRatio||(t.useDevicePixelRatio=t.use_device_pixel_ratio),t.resolutionMode||(t.resolutionMode=t.resolution_mode),t.fillMode||(t.fillMode=t.fill_mode),this._width=t.width,this._height=t.height,t.useDevicePixelRatio&&(this.graphicsDevice.maxPixelRatio=window.devicePixelRatio),this.setCanvasResolution(t.resolutionMode,this._width,this._height),this.setCanvasFillMode(t.fillMode,this._width,this._height),t.layers&&t.layerOrder){var i=new Ru("application"),n={};for(var s in t.layers){var r=t.layers[s];r.id=parseInt(s,10),r.enabled=1!==r.id,n[s]=new Cu(r)}for(var a=0,o=t.layerOrder.length;a<o;a++){var h=t.layerOrder[a],l=n[h.layer];l&&(h.transparent?i.pushTransparent(l):i.pushOpaque(l),i.subLayerEnabled[a]=h.enabled)}this.scene.layers=i}if(t.batchGroups){var c=this.batcher;if(c)for(var u=0,d=t.batchGroups.length;u<d;u++){var f=t.batchGroups[u];c.addGroup(f.name,f.dynamic,f.maxAabbSize,f.id,f.layers)}}t.i18nAssets&&(this.i18n.assets=t.i18nAssets),this._loadLibraries(t.libraries,e)},n._loadLibraries=function(t,e){var i=this,n=t.length,s=n,r=/^http(s)?:\/\//;if(n)for(var a=function(t,n){s--,t?e(t):0===s&&(i.onLibrariesLoaded(),e(null))},o=0;o<n;++o){var h=t[o];!r.test(h.toLowerCase())&&this._scriptPrefix&&(h=L.join(this._scriptPrefix,h)),this.loader.load(h,"script",a)}else this.onLibrariesLoaded(),e(null)},n._parseScenes=function(t){if(t)for(var e=0;e<t.length;e++)this.scenes.add(t[e].name,t[e].url)},n._parseAssets=function(t){var e=[],i={},n={};if(bf.legacy){if(this.enableBundles)for(var s in t)"bundle"===t[s].type&&(n[s]=!0,e.push(t[s]));for(var r in t)n[r]||e.push(t[r])}else{for(var a=0;a<this.scriptsOrder.length;a++){var o=this.scriptsOrder[a];t[o]&&(i[o]=!0,e.push(t[o]))}if(this.enableBundles)for(var h in t)"bundle"===t[h].type&&(n[h]=!0,e.push(t[h]));for(var l in t)i[l]||n[l]||e.push(t[l])}for(var c=0;c<e.length;c++){var u=e[c],d=new Vf(u.name,u.type,u.file,u.data);if(d.id=parseInt(u.id,10),d.preload=!!u.preload&&u.preload,d.loaded="script"===u.type&&u.data&&u.data.loadingType>0,d.tags.add(u.tags),u.i18n)for(var f in u.i18n)d.addLocalizedAssetId(f,u.i18n[f]);this.assets.add(d)}},n._getScriptReferences=function(t){var e=[];t.settings.priority_scripts&&(e=t.settings.priority_scripts);for(var i=[],n={},s=0;s<e.length;s++)i.push(e[s]),n[e[s]]=!0;var r=t.entities;for(var a in r)if(r[a].components.script)for(var o=r[a].components.script.scripts,h=0;h<o.length;h++)n[o[h].url]||(i.push(o[h].url),n[o[h].url]=!0);return i},n.start=function(){this.frame=0,this.fire("start",{timestamp:dt(),target:this}),this._librariesLoaded||this.onLibrariesLoaded(),this.systems.fire("initialize",this.root),this.fire("initialize"),this.systems.fire("postInitialize",this.root),this.systems.fire("postPostInitialize",this.root),this.fire("postinitialize"),this.tick()},n.inputUpdate=function(t){this.controller&&this.controller.update(t),this.mouse&&this.mouse.update(),this.keyboard&&this.keyboard.update(),this.gamepads&&this.gamepads.update()},n.update=function(t){this.frame++,this.graphicsDevice.updateClientRect(),bf.legacy&&this.systems.fire("fixedUpdate",1/60),this.systems.fire(this._inTools?"toolsUpdate":"update",t),this.systems.fire("animationUpdate",t),this.systems.fire("postUpdate",t),this.fire("update",t),this.inputUpdate(t)},n.frameStart=function(){this.graphicsDevice.frameStart()},n.frameEnd=function(){this.graphicsDevice.frameEnd()},n.render=function(){this.fire("prerender"),this.root.syncHierarchy(),this._batcher&&this._batcher.updateAll(),this.renderComposition(this.scene.layers),this.fire("postrender")},n.renderComposition=function(t){this.renderer.buildFrameGraph(this.frameGraph,t),this.frameGraph.render(this.graphicsDevice)},n._fillFrameStatsBasic=function(t,e,i){var n=this.stats.frame;n.dt=e,n.ms=i,t>n._timeToCountFrames?(n.fps=n._fpsAccum,n._fpsAccum=0,n._timeToCountFrames=t+1e3):n._fpsAccum++,this.stats.drawCalls.total=this.graphicsDevice._drawCallsPerFrame,this.graphicsDevice._drawCallsPerFrame=0},n._fillFrameStats=function(){var t=this.stats.frame;t.cameras=this.renderer._camerasRendered,t.materials=this.renderer._materialSwitches,t.shaders=this.graphicsDevice._shaderSwitchesPerFrame,t.shadowMapUpdates=this.renderer._shadowMapUpdates,t.shadowMapTime=this.renderer._shadowMapTime,t.depthMapTime=this.renderer._depthMapTime,t.forwardTime=this.renderer._forwardTime;var e=this.graphicsDevice._primsPerFrame;t.triangles=e[4]/3+Math.max(e[be]-2,0)+Math.max(e[6]-2,0),t.cullTime=this.renderer._cullTime,t.sortTime=this.renderer._sortTime,t.skinTime=this.renderer._skinTime,t.morphTime=this.renderer._morphTime,t.lightClusters=this.renderer._lightClusters,t.lightClustersTime=this.renderer._lightClustersTime,t.otherPrimitives=0;for(var i=0;i<e.length;i++)i<4&&(t.otherPrimitives+=e[i]),e[i]=0;this.renderer._camerasRendered=0,this.renderer._materialSwitches=0,this.renderer._shadowMapUpdates=0,this.graphicsDevice._shaderSwitchesPerFrame=0,this.renderer._cullTime=0,this.renderer._layerCompositionUpdateTime=0,this.renderer._lightClustersTime=0,this.renderer._sortTime=0,this.renderer._skinTime=0,this.renderer._morphTime=0,this.renderer._shadowMapTime=0,this.renderer._depthMapTime=0,this.renderer._forwardTime=0,(t=this.stats.drawCalls).forward=this.renderer._forwardDrawCalls,t.culled=this.renderer._numDrawCallsCulled,t.depth=0,t.shadow=this.renderer._shadowDrawCalls,t.skinned=this.renderer._skinDrawCalls,t.immediate=0,t.instanced=0,t.removedByInstancing=0,t.misc=t.total-(t.forward+t.shadow),this.renderer._depthDrawCalls=0,this.renderer._shadowDrawCalls=0,this.renderer._forwardDrawCalls=0,this.renderer._numDrawCallsCulled=0,this.renderer._skinDrawCalls=0,this.renderer._immediateRendered=0,this.renderer._instancedDrawCalls=0,this.stats.misc.renderTargetCreationTime=this.graphicsDevice.renderTargetCreationTime,(t=this.stats.particles).updatesPerFrame=t._updatesPerFrame,t.frameTime=t._frameTime,t._updatesPerFrame=0,t._frameTime=0},n.setCanvasFillMode=function(t,e,i){this._fillMode=t,this.resizeCanvas(e,i)},n.setCanvasResolution=function(t,e,i){this._resolutionMode=t,t===mf&&void 0===e&&(e=this.graphicsDevice.canvas.clientWidth,i=this.graphicsDevice.canvas.clientHeight),this.graphicsDevice.resizeCanvas(e,i)},n.isHidden=function(){return document[this._hiddenAttr]},n.onVisibilityChange=function(){this.isHidden()?this._soundManager&&this._soundManager.suspend():this._soundManager&&this._soundManager.resume()},n.resizeCanvas=function(t,e){if(this._allowResize&&(!this.xr||!this.xr.session)){var i=window.innerWidth,n=window.innerHeight;if(this._fillMode===pf){var s=this.graphicsDevice.canvas.width/this.graphicsDevice.canvas.height;s>i/n?e=(t=i)/s:t=(e=n)*s}else this._fillMode===ff&&(t=i,e=n);return this.graphicsDevice.canvas.style.width=t+"px",this.graphicsDevice.canvas.style.height=e+"px",this.updateCanvasSize(),{width:t,height:e}}},n.updateCanvasSize=function(){var t;if(this._allowResize&&(null==(t=this.xr)||!t.active)&&this._resolutionMode===mf){var e=this.graphicsDevice.canvas;this.graphicsDevice.resizeCanvas(e.clientWidth,e.clientHeight)}},n.onLibrariesLoaded=function(){this._librariesLoaded=!0,this.systems.rigidbody&&this.systems.rigidbody.onLibraryLoaded()},n.applySceneSettings=function(t){var e;if(this.systems.rigidbody&&"undefined"!=typeof Ammo){var i=t.physics.gravity;this.systems.rigidbody.gravity.set(i[0],i[1],i[2])}this.scene.applySettings(t),t.render.hasOwnProperty("skybox")&&(t.render.skybox?(e=this.assets.get(t.render.skybox))?this.setSkybox(e):this.assets.once("add:"+t.render.skybox,this.setSkybox,this):this.setSkybox(null))},n.setAreaLightLuts=function(t,e){t&&e&&Cf.set(this.graphicsDevice,t,e)},n.setSkybox=function(t){var e=this;if(t!==this._skyboxAsset){var i=function(){e.setSkybox(null)},n=function(){e.scene.setSkybox(e._skyboxAsset?e._skyboxAsset.resources:null)};this._skyboxAsset&&(this.assets.off("load:"+this._skyboxAsset.id,n,this),this.assets.off("remove:"+this._skyboxAsset.id,i,this),this._skyboxAsset.off("change",n,this)),this._skyboxAsset=t,this._skyboxAsset&&(this.assets.on("load:"+this._skyboxAsset.id,n,this),this.assets.once("remove:"+this._skyboxAsset.id,i,this),this._skyboxAsset.on("change",n,this),0!==this.scene.skyboxMip||this._skyboxAsset.loadFaces||(this._skyboxAsset.loadFaces=!0),this.assets.load(this._skyboxAsset)),n()}},n._firstBake=function(){var t;null==(t=this.lightmapper)||t.bake(null,this.scene.lightmapMode)},n._firstBatch=function(){var t;null==(t=this.batcher)||t.generate()},n._processTimestamp=function(t){return t},n.drawLine=function(t,e,i,n,s){this.scene.drawLine(t,e,i,n,s)},n.drawLines=function(t,e,i,n){void 0===i&&(i=!0),void 0===n&&(n=this.scene.defaultDrawLayer),this.scene.drawLines(t,e,i,n)},n.drawLineArrays=function(t,e,i,n){void 0===i&&(i=!0),void 0===n&&(n=this.scene.defaultDrawLayer),this.scene.drawLineArrays(t,e,i,n)},n.drawWireSphere=function(t,e,i,n,s,r){void 0===i&&(i=vt.WHITE),void 0===n&&(n=20),void 0===s&&(s=!0),void 0===r&&(r=this.scene.defaultDrawLayer),this.scene.immediate.drawWireSphere(t,e,i,n,s,r)},n.drawWireAlignedBox=function(t,e,i,n,s){void 0===i&&(i=vt.WHITE),void 0===n&&(n=!0),void 0===s&&(s=this.scene.defaultDrawLayer),this.scene.immediate.drawWireAlignedBox(t,e,i,n,s)},n.drawMeshInstance=function(t,e){void 0===e&&(e=this.scene.defaultDrawLayer),this.scene.immediate.drawMesh(null,null,null,t,e)},n.drawMesh=function(t,e,i,n){void 0===n&&(n=this.scene.defaultDrawLayer),this.scene.immediate.drawMesh(e,i,t,null,n)},n.drawQuad=function(t,e,i){void 0===i&&(i=this.scene.defaultDrawLayer),this.scene.immediate.drawMesh(e,t,this.scene.immediate.getQuadMesh(),null,i)},n.drawTexture=function(t,e,i,n,s,r,a,o){if(void 0===a&&(a=this.scene.defaultDrawLayer),void 0===o&&(o=!0),!1!==o||this.graphicsDevice.isWebGPU){var h=new Ft;h.setTRS(new wt(t,e,0),Bt.IDENTITY,new wt(i,-n,0)),r||((r=new zo).cull=se,r.setParameter("colorMap",s),r.shader=o?this.scene.immediate.getTextureShader():this.scene.immediate.getUnfilterableTextureShader(),r.update()),this.drawQuad(h,r,a)}},n.drawDepthTexture=function(t,e,i,n,s){void 0===s&&(s=this.scene.defaultDrawLayer);var r=new zo;r.cull=se,r.shader=this.scene.immediate.getDepthTextureShader(),r.update(),this.drawTexture(t,e,i,n,null,r,s)},n.destroy=function(){var t,e,n,s;if(this._inFrameUpdate)this._destroyRequested=!0;else{var r=this.graphicsDevice.canvas.id;this.fire("destroy",this),this.off("librariesloaded"),"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this._visibilityChangeHandler,!1),document.removeEventListener("mozvisibilitychange",this._visibilityChangeHandler,!1),document.removeEventListener("msvisibilitychange",this._visibilityChangeHandler,!1),document.removeEventListener("webkitvisibilitychange",this._visibilityChangeHandler,!1)),this._visibilityChangeHandler=null,this.root.destroy(),this.root=null,this.mouse&&(this.mouse.off(),this.mouse.detach(),this.mouse=null),this.keyboard&&(this.keyboard.off(),this.keyboard.detach(),this.keyboard=null),this.touch&&(this.touch.off(),this.touch.detach(),this.touch=null),this.elementInput&&(this.elementInput.detach(),this.elementInput=null),this.gamepads&&(this.gamepads.destroy(),this.gamepads=null),this.controller&&(this.controller=null),this.systems.destroy(),this.scene.layers&&this.scene.layers.destroy();for(var a=this.assets.list(),o=0;o<a.length;o++)a[o].unload(),a[o].off();this.assets.off(),this.bundles.destroy(),this.bundles=null,this.i18n.destroy(),this.i18n=null;var h=this.loader.getHandler("script");null==h||h.clearCache(),this.loader.destroy(),this.loader=null,this.scene.destroy(),this.scene=null,this.systems=null,this.context=null,this.scripts.destroy(),this.scripts=null,this.scenes.destroy(),this.scenes=null,null==(t=this.lightmapper)||t.destroy(),this.lightmapper=null,this._batcher&&(this._batcher.destroy(),this._batcher=null),this._entityIndex={},this.defaultLayerDepth.onPreRenderOpaque=null,this.defaultLayerDepth.onPostRenderOpaque=null,this.defaultLayerDepth.onDisable=null,this.defaultLayerDepth.onEnable=null,this.defaultLayerDepth=null,this.defaultLayerWorld=null,null==(e=this.xr)||e.end(),null==(n=this.xr)||n.destroy(),this.renderer.destroy(),this.renderer=null,this.graphicsDevice.destroy(),this.graphicsDevice=null,this.tick=null,this.off(),null==(s=this._soundManager)||s.destroy(),this._soundManager=null,bf.app=null,i._applications[r]=null,vf()===this&&gf(null)}},n.getEntityFromIndex=function(t){return this._entityIndex[t]},n._registerSceneImmediate=function(t){this.on("postrender",t.immediate.onPostRender,t.immediate)},y(i,[{key:"soundManager",get:function(){return this._soundManager}},{key:"batcher",get:function(){return this._batcher}},{key:"fillMode",get:function(){return this._fillMode}},{key:"resolutionMode",get:function(){return this._resolutionMode}}]),i}(P);hp._applications={};var lp={},cp=function(e){var i,n=e;return function(e,s){var r;if(n.graphicsDevice){gf(n),i&&(window.cancelAnimationFrame(i),i=null),t.app=n;var a=n._processTimestamp(e)||dt(),o=a-(n._time||a),h=o/1e3;if(h=_t.clamp(h,0,n.maxDeltaTime),h*=n.timeScale,n._time=a,i=null!=(r=n.xr)&&r.session?n.xr.session.requestAnimationFrame(n.tick):G.browser?window.requestAnimationFrame(n.tick):null,!n.graphicsDevice.contextLost){n._fillFrameStatsBasic(a,h,o),n._inFrameUpdate=!0,n.fire("frameupdate",o);var l,c=!0;if(s)c=null==(l=n.xr)?void 0:l.update(s),n.graphicsDevice.defaultFramebuffer=s.session.renderState.baseLayer.framebuffer;else n.graphicsDevice.defaultFramebuffer=null;c&&(n.update(h),n.fire("framerender"),(n.autoRender||n.renderNextFrame)&&(n.updateCanvasSize(),n.frameStart(),n.render(),n.frameEnd(),n.renderNextFrame=!1),lp.timestamp=dt(),lp.target=n,n.fire("frameend",lp)),n._inFrameUpdate=!1,n._destroyRequested&&n.destroy()}}}},up=function(){this.elementInput=void 0,this.keyboard=void 0,this.mouse=void 0,this.touch=void 0,this.gamepads=void 0,this.scriptPrefix=void 0,this.assetPrefix=void 0,this.scriptsOrder=void 0,this.soundManager=void 0,this.graphicsDevice=void 0,this.lightmapper=void 0,this.batchManager=void 0,this.xr=void 0,this.componentSystems=[],this.resourceHandlers=[]},dp=new jt,fp=function(){function t(t,e){this.scene=t,this.light=e,this.store(),e.numCascades=1,0!==e.type&&(e._node.getWorldTransform(),e.getBoundingSphere(dp),this.lightBounds=new Ht,this.lightBounds.center.copy(dp.center),this.lightBounds.halfExtents.set(dp.radius,dp.radius,dp.radius))}var e=t.prototype;return e.store=function(){this.mask=this.light.mask,this.shadowUpdateMode=this.light.shadowUpdateMode,this.enabled=this.light.enabled,this.intensity=this.light.intensity,this.rotation=this.light._node.getLocalRotation().clone(),this.numCascades=this.light.numCascades},e.restore=function(){var t=this.light;t.mask=this.mask,t.shadowUpdateMode=this.shadowUpdateMode,t.enabled=this.enabled,t.intensity=this.intensity,t._node.setLocalRotation(this.rotation),t.numCascades=this.numCascades},e.startBake=function(){this.light.enabled=!0,this.light._destroyShadowMap(),this.light.beginFrame()},e.endBake=function(t){var e=this.light;e.enabled=!1,e.shadowMap&&(e.shadowMap.cached&&t.add(e,e.shadowMap),e.shadowMap=null)},t}(),pp=new Et,mp=function(t){function e(){return t.apply(this,arguments)||this}return S(e,t),e.prototype.prepareVirtualLight=function(t,e){var i=this.light;if(i._node.setLocalRotation(this.rotation),t>0){var n=i.bakeArea;Tc(pp,t,e),pp.mulScalar(.5*n),i._node.rotateLocal(pp.x,0,pp.y)}i._node.getWorldTransform();var s=this.scene.gammaCorrection?2.2:1,r=Math.pow(this.intensity,s);i.intensity=Math.pow(r/e,1/s)},y(e,[{key:"numVirtualLights",get:function(){return 0===this.light.type?this.light.bakeNumSamples:1}}]),e}(fp),_p=new wt,vp=function(t){function e(e){var i=new ip("AmbientLight");return i.addComponent("light",{type:"directional",affectDynamic:!0,affectLightmapped:!1,bake:!0,bakeNumSamples:e.ambientBakeNumSamples,castShadows:!0,normalOffsetBias:.05,shadowBias:.2,shadowDistance:1,shadowResolution:2048,shadowType:0,color:vt.WHITE,intensity:1,bakeDir:!1}),t.call(this,e,i.light.light)||this}return S(e,t),e.prototype.prepareVirtualLight=function(t,e){Ac(_p,t,e,0,this.scene.ambientBakeSpherePart),this.light._node.lookAt(_p.mulScalar(-1)),this.light._node.rotateLocal(90,0,0);var i=this.scene.gammaCorrection?2.2:1,n=2*Math.PI*this.scene.ambientBakeSpherePart,s=Math.pow(n,i);this.light.intensity=Math.pow(s/e,1/i)},y(e,[{key:"numVirtualLights",get:function(){return this.light.bakeNumSamples}}]),e}(fp),gp=function(){function t(t,e){void 0===e&&(e=null),this.node=t,this.component=t.render||t.model,e=e||this.component.meshInstances,this.store(),this.meshInstances=e,this.bounds=null,this.renderTargets=[]}var e=t.prototype;return e.store=function(){this.castShadows=this.component.castShadows},e.restore=function(){this.component.castShadows=this.castShadows},t}(),yp=function(){function t(t){this.device=t,this.shaderDilate=bo(t,_o.fullscreenQuadVS,df.dilatePS,"lmDilate"),this.constantTexSource=t.scope.resolve("source"),this.constantPixelOffset=t.scope.resolve("pixelOffset"),this.pixelOffset=new Float32Array(2),this.shaderDenoise=null,this.sigmas=null,this.constantSigmas=null,this.kernel=null}var e=t.prototype;return e.setSourceTexture=function(t){this.constantTexSource.setValue(t)},e.prepare=function(t,e){this.pixelOffset[0]=1/t,this.pixelOffset[1]=1/e,this.constantPixelOffset.setValue(this.pixelOffset)},e.prepareDenoise=function(t,e){this.shaderDenoise||(this.shaderDenoise=bo(this.device,_o.fullscreenQuadVS,df.bilateralDeNoisePS,"lmBilateralDeNoise"),this.sigmas=new Float32Array(2),this.constantSigmas=this.device.scope.resolve("sigmas"),this.constantKernel=this.device.scope.resolve("kernel[0]"),this.bZnorm=this.device.scope.resolve("bZnorm")),this.sigmas[0]=t,this.sigmas[1]=e,this.constantSigmas.setValue(this.sigmas),this.evaluateDenoiseUniforms(t,e)},e.evaluateDenoiseUniforms=function(t,e){function i(t,e){return.39894*Math.exp(-.5*t*t/(e*e))/e}this.kernel=this.kernel||new Float32Array(15);for(var n=this.kernel,s=Math.floor(7),r=0;r<=s;++r){var a=i(r,t);n[s+r]=a,n[s-r]=a}this.constantKernel.setValue(this.kernel);var o=1/i(0,e);this.bZnorm.setValue(o)},t}(),xp=new wt,Sp=function(){function t(t,e,i,n,s){this.device=t,this.root=e,this.scene=i,this.renderer=n,this.assets=s,this.shadowMapCache=n.shadowMapCache,this._tempSet=new Set,this._initCalled=!1,this.passMaterials=[],this.ambientAOMaterial=null,this.fog="",this.ambientLight=new vt,this.renderTargets=new Map,this.stats={renderPasses:0,lightmapCount:0,totalRenderTime:0,forwardTime:0,fboTime:0,shadowMapTime:0,compileTime:0,shadersLinked:0}}var e=t.prototype;return e.destroy=function(){var t;ch.decRef(this.blackTex),this.blackTex=null,ch.destroy(),this.device=null,this.root=null,this.scene=null,this.renderer=null,this.assets=null,null==(t=this.camera)||t.destroy(),this.camera=null},e.initBake=function(t){if(!this._initCalled){this._initCalled=!0,this.lightmapFilters=new yp(t),this.constantBakeDir=t.scope.resolve("bakeDir"),this.materials=[],this.blackTex=new Ls(this.device,{width:4,height:4,format:7,type:ii,name:"lightmapBlack"}),ch.incRef(this.blackTex);var e=new Gh;e.clearColor.set(0,0,0,0),e.clearColorBuffer=!0,e.clearDepthBuffer=!1,e.clearStencilBuffer=!1,e.frustumCulling=!1,e.projection=1,e.aspectRatio=1,e.node=new hh,this.camera=e}if(this.scene.clusteredLightingEnabled){var i=new Nu(t.supportsAreaLights,t.maxTextureSize,(function(){}));this.lightingParams=i;var n=this.scene.lighting;i.shadowsEnabled=n.shadowsEnabled,i.shadowAtlasResolution=n.shadowAtlasResolution,i.cookiesEnabled=n.cookiesEnabled,i.cookieAtlasResolution=n.cookieAtlasResolution,i.areaLightsEnabled=n.areaLightsEnabled,i.cells=new wt(3,3,3),i.maxLightsPerCell=4,this.worldClusters=new Al(t),this.worldClusters.name="ClusterLightmapper"}},e.finishBake=function(t){function e(t){ch.decRef(t.colorBuffer),t.destroy()}this.materials=[],this.renderTargets.forEach((function(t){e(t)})),this.renderTargets.clear(),t.forEach((function(t){t.renderTargets.forEach((function(t){e(t)})),t.renderTargets.length=0})),this.ambientAOMaterial=null,this.worldClusters&&(this.worldClusters.destroy(),this.worldClusters=null)},e.createMaterialForPass=function(t,e,i,n){var s=new lu;if(s.name="lmMaterial-pass:"+i+"-ambient:"+n,s.chunks.APIVersion=Di,s.chunks.transformVS="#define UV1LAYOUT\n"+_o.transformVS,0===i){var r=df.bakeLmEndPS;n?r="\n dDiffuseLight = ((dDiffuseLight - 0.5) * max("+e.ambientBakeOcclusionContrast.toFixed(1)+" + 1.0, 0.0)) + 0.5;\n dDiffuseLight += vec3("+e.ambientBakeOcclusionBrightness.toFixed(1)+");\n dDiffuseLight = saturate(dDiffuseLight);\n dDiffuseLight *= dAmbientLight;\n "+r:(s.ambient=new vt(0,0,0),s.ambientTint=!0),s.chunks.basePS=_o.basePS+(7===e.lightmapPixelFormat?"\n#define LIGHTMAP_RGBM\n":""),s.chunks.endPS=r,s.lightMap=this.blackTex}else s.chunks.basePS=_o.basePS+"\nuniform sampler2D texture_dirLightMap;\nuniform float bakeDir;\n",s.chunks.endPS=df.bakeDirLmEndPS;return s.chunks.outputAlphaPS="\n",s.chunks.outputAlphaOpaquePS="\n",s.chunks.outputAlphaPremulPS="\n",s.cull=se,s.forceUv1=!0,s.update(),s},e.createMaterials=function(t,e,i){for(var n=0;n<i;n++)this.passMaterials[n]||(this.passMaterials[n]=this.createMaterialForPass(t,e,n,!1));this.ambientAOMaterial||(this.ambientAOMaterial=this.createMaterialForPass(t,e,0,!0),this.ambientAOMaterial.onUpdateShader=function(t){return t.litOptions.lightMapWithoutAmbient=!0,t.litOptions.separateAmbient=!0,t})},e.createTexture=function(t,e){return new Ls(this.device,{width:t,height:t,format:this.scene.lightmapPixelFormat,mipmaps:!1,type:7===this.scene.lightmapPixelFormat?ii:ei,minFilter:0,magFilter:0,addressU:1,addressV:1,name:e})},e.collectModels=function(t,e,i){var n,s,r;if(t.enabled){var a;if(null!=(n=t.model)&&n.model&&null!=(s=t.model)&&s.enabled&&(i&&i.push(new gp(t)),t.model.lightmapped&&e&&(a=t.model.model.meshInstances)),null!=(r=t.render)&&r.enabled&&(i&&i.push(new gp(t)),t.render.lightmapped&&e&&(a=t.render.meshInstances)),a){for(var o=!0,h=0;h<a.length;h++)if(!a[h].mesh.vertexBuffer.format.hasUv1){o=!1;break}if(o){for(var l=[],c=0;c<a.length;c++){var u=a[c].mesh;this._tempSet.has(u)?e.push(new gp(t,[a[c]])):l.push(a[c]),this._tempSet.add(u)}this._tempSet.clear(),l.length>0&&e.push(new gp(t,l))}}for(var d=0;d<t._children.length;d++)this.collectModels(t._children[d],e,i)}},e.prepareShadowCasters=function(t){for(var e=[],i=0;i<t.length;i++){var n=t[i].component;if(n.castShadows=n.castShadowsLightmap,n.castShadowsLightmap)for(var s=t[i].meshInstances,r=0;r<s.length;r++)s[r].visibleThisFrame=!0,e.push(s[r])}return e},e.updateTransforms=function(t){for(var e=0;e<t.length;e++)for(var i=t[e].meshInstances,n=0;n<i.length;n++)i[n].node.getWorldTransform()},e.calculateLightmapSize=function(t){var e,i,n,s=this.scene.lightmapSizeMultiplier||16,r=xp;t.model?(n=t.model.lightmapSizeMultiplier,t.model.asset?(e=this.assets.get(t.model.asset).data).area&&(i=e.area):t.model._area&&(e=t.model)._area&&(i=e._area)):t.render&&(n=t.render.lightmapSizeMultiplier,"asset"!==t.render.type&&t.render._area&&(e=t.render)._area&&(i=e._area));var a={x:1,y:1,z:1,uv:1};i&&(a.x=i.x,a.y=i.y,a.z=i.z,a.uv=i.uv);var o=n||1;a.x*=o,a.y*=o,a.z*=o;var h=t.render||t.model,l=this.computeNodeBounds(h.meshInstances);r.copy(l.halfExtents);var c=a.x*r.y*r.z+a.y*r.x*r.z+a.z*r.x*r.y;return c/=a.uv,c=Math.sqrt(c),Math.min(_t.nextPowerOfTwo(c*s),this.scene.lightmapMaxResolution||2048)},e.setLightmapping=function(t,e,i,n){for(var s=0;s<t.length;s++)for(var r=t[s],a=r.meshInstances,o=0;o<a.length;o++){var h=a[o];if(h.setLightmapped(e),e){n&&(h._shaderDefs|=n),h.mask=2;for(var l=0;l<i;l++){var c=r.renderTargets[l].colorBuffer;c.minFilter=1,c.magFilter=1,h.setRealtimeLightmap(yh.lightmapParamNames[l],c)}}}},e.bake=function(t,e){void 0===e&&(e=1);var i=this.device;if(!i.isWebGPU){var n=dt();this.scene._updateSky(i),this.stats.renderPasses=0,this.stats.shadowMapTime=0,this.stats.forwardTime=0;var s=i._shaderStats.linked,r=i._renderTargetCreationTime,a=i._shaderStats.compileTime,o=[],h=[];if(t){for(var l=0;l<t.length;l++)this.collectModels(t[l],o,null);this.collectModels(this.root,null,h)}else this.collectModels(this.root,o,h);if(o.length>0){this.renderer.shadowRenderer.frameUpdate();var c=1===e?2:1;this.setLightmapping(o,!1,c),this.initBake(i),this.bakeInternal(c,o,h);var u=64;1===e&&(u|=ka),this.scene.ambientBake&&(u|=Va),this.setLightmapping(o,!0,c,u),this.finishBake(o)}var d=dt();this.stats.totalRenderTime=d-n,this.stats.shadersLinked=i._shaderStats.linked-s,this.stats.compileTime=i._shaderStats.compileTime-a,this.stats.fboTime=i._renderTargetCreationTime-r,this.stats.lightmapCount=o.length}},e.allocateTextures=function(t,e){for(var i=0;i<t.length;i++){for(var n=t[i],s=this.calculateLightmapSize(n.node),r=0;r<e;r++){var a=this.createTexture(s,"lightmapper_lightmap_"+i);ch.incRef(a),n.renderTargets[r]=new rn({colorBuffer:a,depth:!1})}if(!this.renderTargets.has(s)){var o=this.createTexture(s,"lightmapper_temp_lightmap_"+s);ch.incRef(o),this.renderTargets.set(s,new rn({colorBuffer:o,depth:!1}))}}},e.prepareLightsToBake=function(t,e,i){if(this.scene.ambientBake){var n=new vp(this.scene);i.push(n)}for(var s=this.renderer.lights,r=0;r<s.length;r++){var a=s[r],o=new mp(this.scene,a);e.push(o),a.enabled&&0!=(4&a.mask)&&(a.mask=7,a.shadowUpdateMode=0===a.type?2:1,i.push(o))}i.sort()},e.restoreLights=function(t){for(var e=0;e<t.length;e++)t[e].restore()},e.setupScene=function(){this.fog=this.scene.fog,this.ambientLight.copy(this.scene.ambientLight),this.scene.fog=Ra,this.scene.ambientBake||this.scene.ambientLight.set(0,0,0),this.renderer.setSceneConstants()},e.restoreScene=function(){this.scene.fog=this.fog,this.scene.ambientLight.copy(this.ambientLight)},e.computeNodeBounds=function(t){var e=new Ht;if(t.length>0){e.copy(t[0].aabb);for(var i=1;i<t.length;i++)e.add(t[i].aabb)}return e},e.computeNodesBounds=function(t){for(var e=0;e<t.length;e++){var i=t[e].meshInstances;t[e].bounds=this.computeNodeBounds(i)}},e.computeBounds=function(t){for(var e=new Ht,i=0;i<t.length;i++){e.copy(t[0].aabb);for(var n=1;n<t.length;n++)e.add(t[n].aabb)}return e},e.backupMaterials=function(t){for(var e=0;e<t.length;e++)this.materials[e]=t[e].material},e.restoreMaterials=function(t){for(var e=0;e<t.length;e++)t[e].material=this.materials[e]},e.lightCameraPrepare=function(t,e){var i,n=e.light;2===n.type&&((i=n.getRenderData(null,0).shadowCamera)._node.setPosition(n._node.getPosition()),i._node.setRotation(n._node.getRotation()),i._node.rotateLocal(-90,0,0),i.projection=0,i.nearClip=n.attenuationEnd/1e3,i.farClip=n.attenuationEnd,i.aspectRatio=1,i.fov=2*n._outerConeAngle,this.renderer.updateCameraFrustum(i));return i},e.lightCameraPrepareAndCull=function(t,e,i,n){var s=t.light,r=!0;if(0===s.type){xp.copy(n.center),xp.y+=n.halfExtents.y,this.camera.node.setPosition(xp),this.camera.node.setEulerAngles(-90,0,0),this.camera.nearClip=0,this.camera.farClip=2*n.halfExtents.y;var a=Math.max(n.halfExtents.x,n.halfExtents.z);this.camera.orthoHeight=a}else t.lightBounds.intersects(e.bounds)||(r=!1);if(2===s.type){for(var o=!1,h=e.meshInstances,l=0;l<h.length;l++)if(h[l]._isVisible(i)){o=!0;break}o||(r=!1)}return r},e.setupLightArray=function(t,e){t[0].length=0,t[1].length=0,t[2].length=0,t[e.type][0]=e,e.visibleThisFrame=!0},e.renderShadowMap=function(t,e,i,n){var s=n.light,r=this.scene.clusteredLightingEnabled,a=s.castShadows&&(!r||this.scene.lighting.shadowsEnabled);if(!e&&a){s.shadowMap||r||(s.shadowMap=this.shadowMapCache.get(this.device,s)),0===s.type?this.renderer._shadowRendererDirectional.cull(s,t,this.camera,i):this.renderer._shadowRendererLocal.cull(s,t,i);this.renderer.shadowRenderer.render(s,this.camera,!1)}return!0},e.postprocessTextures=function(t,e,i){var n=this.lightmapFilters.shaderDilate,s=this.scene.lightmapFilterEnabled;s&&this.lightmapFilters.prepareDenoise(this.scene.lightmapFilterRange,this.scene.lightmapFilterSmoothness),t.setBlendState(Ui.NOBLEND),t.setDepthState(Ni.NODEPTH),t.setStencilState(null,null);for(var r=0;r<e.length;r++)for(var a=e[r],o=0;o<i;o++){var h=a.renderTargets[o],l=h.colorBuffer,c=this.renderTargets.get(l.width),u=c.colorBuffer;this.lightmapFilters.prepare(l.width,l.height);for(var d=0;d<1;d++){this.lightmapFilters.setSourceTexture(l),Ro(t,c,s&&0===o&&0===d?this.lightmapFilters.shaderDenoise:n),this.lightmapFilters.setSourceTexture(u),Ro(t,h,n)}}},e.bakeInternal=function(t,e,i){var n=this.scene,s=n.layers,r=this.device,a=n.clusteredLightingEnabled;this.createMaterials(r,n,t),this.setupScene(),s._update(),this.computeNodesBounds(e),this.allocateTextures(e,t),this.renderer.collectLights(s);var o=[],h=[];this.prepareLightsToBake(s,o,h),this.updateTransforms(i);var l=this.prepareShadowCasters(i);this.renderer.updateCpuSkinMatrices(l),this.renderer.gpuUpdate(l);var c,u,d,f,p=this.computeBounds(l);for(c=0;c<e.length;c++){for(d=e[c].meshInstances,u=0;u<d.length;u++)(f=d[u]).setLightmapped(!1),f.mask=4,f.setRealtimeLightmap(yh.lightmapParamNames[0],f.material.lightMap?f.material.lightMap:this.blackTex),f.setRealtimeLightmap(yh.lightmapParamNames[1],this.blackTex)}for(u=0;u<h.length;u++)h[u].light.enabled=!1;var m,_,v=[[],[],[]],g=!1;for(c=0;c<h.length;c++){var y=h[c],x=y instanceof vp,S=0===y.light.type,b=y.numVirtualLights;t>1&&b>1&&y.light.bakeDir&&(b=1);for(var w=0;w<b;w++){b>1&&y.prepareVirtualLight(w,b),y.startBake();var T=!1,A=this.lightCameraPrepare(r,y);for(_=0;_<e.length;_++){var C=e[_];if(d=C.meshInstances,this.lightCameraPrepareAndCull(y,C,A,p)){this.setupLightArray(v,y.light);var E=S?[]:[y.light];for(a&&this.renderer.lightTextureAtlas.update(E,this.lightingParams),T=this.renderShadowMap(s,T,l,y),a&&this.worldClusters.update(E,this.scene.gammaCorrection,this.lightingParams),this.backupMaterials(d),m=0;m<t&&!(m>0&&w>0)&&!(x&&m>0);m++){var M=C.renderTargets[m],P=C.renderTargets[m].colorBuffer.width,R=this.renderTargets.get(P),I=R.colorBuffer;0===m?g=n.updateShaders:g&&(n.updateShaders=!0);var L=this.passMaterials[m];for(x&&w+1===b&&0===m&&(L=this.ambientAOMaterial),u=0;u<d.length;u++)d[u].material=L;for(this.renderer.updateShaders(d),this.renderer.setCamera(this.camera,R,!0),1===m&&this.constantBakeDir.setValue(y.light.bakeDir?1:0),a&&this.worldClusters.activate(),this.renderer._forwardTime=0,this.renderer._shadowMapTime=0,this.renderer.renderForward(this.camera,d,v,1),r.updateEnd(),C.renderTargets[m]=R,this.renderTargets.set(P,M),u=0;u<d.length;u++)(f=d[u]).setRealtimeLightmap(yh.lightmapParamNames[m],I),f._shaderDefs|=64}this.restoreMaterials(d)}}y.endBake(this.shadowMapCache)}}for(this.postprocessTextures(r,e,t),_=0;_<i.length;_++)i[_].restore();this.restoreLights(o),this.restoreScene(),a||this.shadowMapCache.clear()},t}(),bp=function(t){function e(e,i){var n;return(n=t.call(this)||this).system=void 0,n.entity=void 0,n.system=e,n.entity=i,n.system.schema&&!n._accessorsBuilt&&n.buildAccessors(n.system.schema),n.on("set",(function(t,e,i){this.fire("set_"+t,t,e,i)})),n.on("set_enabled",n.onSetEnabled,w(n)),n}S(e,t),e._buildAccessors=function(t,e){e.forEach((function(e){var i="object"==typeof e?e.name:e;Object.defineProperty(t,i,{get:function(){return this.data[i]},set:function(t){var e=this.data,n=e[i];e[i]=t,this.fire("set",i,n,t)},configurable:!0})})),t._accessorsBuilt=!0};var i=e.prototype;return i.buildAccessors=function(t){e._buildAccessors(this,t)},i.onSetEnabled=function(t,e,i){e!==i&&this.entity.enabled&&(i?this.onEnable():this.onDisable())},i.onEnable=function(){},i.onDisable=function(){},i.onPostStateChange=function(){},y(e,[{key:"data",get:function(){var t=this.system.store[this.entity.getGuid()];return t?t.data:null}}]),e}(P),wp=function(t){function e(e){var i;return(i=t.call(this)||this).app=e,i.store={},i.schema=[],i}S(e,t);var i=e.prototype;return i.addComponent=function(t,e){void 0===e&&(e={});var i=new this.ComponentType(this,t),n=new this.DataType;return this.store[t.getGuid()]={entity:t,data:n},t[this.id]=i,t.c[this.id]=i,this.initializeComponentData(i,e,[]),this.fire("add",t,i),i},i.removeComponent=function(t){var e=this.store[t.getGuid()],i=t.c[this.id];this.fire("beforeremove",t,i),delete this.store[t.getGuid()],t[this.id]=void 0,delete t.c[this.id],this.fire("remove",t,e.data)},i.cloneComponent=function(t,e){var i=this.store[t.getGuid()];return this.addComponent(e,i.data)},i.initializeComponentData=function(t,e,i){void 0===e&&(e={});for(var n=0,s=i.length;n<s;n++){var r=i[n],a=void 0,o=void 0;"object"==typeof r?(a=r.name,o=r.type):(a=r,o=void 0);var h=e[a];void 0!==h?(void 0!==o&&(h=Tp(h,o)),t[a]=h):t[a]=t.data[a]}t.enabled&&t.entity.enabled&&t.onEnable()},i.getPropertiesOfType=function(t){var e=[];return(this.schema||[]).forEach((function(i){i&&"object"==typeof i&&i.type===t&&e.push(i)})),e},i.destroy=function(){this.off()},e}(P);function Tp(t,e){if(!t)return t;switch(e){case"rgb":return t instanceof vt?t.clone():new vt(t[0],t[1],t[2]);case"rgba":return t instanceof vt?t.clone():new vt(t[0],t[1],t[2],t[3]);case"vec2":return t instanceof Et?t.clone():new Et(t[0],t[1]);case"vec3":return t instanceof wt?t.clone():new wt(t[0],t[1],t[2]);case"vec4":return t instanceof Pt?t.clone():new Pt(t[0],t[1],t[2],t[3]);case"boolean":case"number":case"string":case"entity":return t;default:throw new Error("Could not convert unhandled type: "+e)}}var Ap=function(){function t(){this._left=1/0,this._right=-1/0,this._len=0,this._recip=0,this._p0=0,this._p1=0,this._t=0,this._hermite={valid:!1,p0:0,m0:0,p1:0,m1:0}}var e=t.prototype;return e.update=function(t,e){if(t<this._left||t>=this._right){var i=e.length;if(i)if(t<e[0])this._left=-1/0,this._right=e[0],this._len=0,this._recip=0,this._p0=this._p1=0;else if(t>=e[i-1])this._left=e[i-1],this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=i-1;else{var n=this._findKey(t,e);this._left=e[n],this._right=e[n+1],this._len=this._right-this._left;var s=1/this._len;this._recip=isFinite(s)?s:0,this._p0=n,this._p1=n+1}else this._left=-1/0,this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=0}this._t=0===this._recip?0:(t-this._left)*this._recip,this._hermite.valid=!1},e._findKey=function(t,e){for(var i=0;t>=e[i+1];)i++;return i},e.eval=function(t,e,i){var n=i._data,s=i._components,r=this._p0*s;if(0===e)for(var a=0;a<s;++a)t[a]=n[r+a];else{var o=this._t,h=this._p1*s;switch(e){case 1:for(var l=0;l<s;++l)t[l]=_t.lerp(n[r+l],n[h+l],o);break;case 2:var c=this._hermite;if(!c.valid){var u=o*o,d=o+o,f=1-o,p=f*f;c.valid=!0,c.p0=(1+d)*p,c.m0=o*p,c.p1=u*(3-d),c.m1=u*(o-1)}for(var m=(3*this._p0+1)*s,_=(3*this._p0+2)*s,v=(3*this._p1+1)*s,g=(3*this._p1+0)*s,y=0;y<s;++y)t[y]=c.p0*n[m+y]+c.m0*n[_+y]*this._len+c.p1*n[v+y]+c.m1*n[g+y]*this._len}}},t}(),Cp=function(t){this._name=t.name+"Snapshot",this._time=-1,this._cache=[],this._results=[];for(var e=0;e<t._inputs.length;++e)this._cache[e]=new Ap;for(var i=t._curves,n=t._outputs,s=0;s<i.length;++s){for(var r=n[i[s]._output],a=[],o=0;o<r._components;++o)a[o]=0;this._results[s]=a}},Ep=function(){function t(t,e,i,n,s,r){this._name=t.name,this._track=t,this._snapshot=new Cp(t),this._playing=n,this._time=e,this._speed=i,this._loop=s,this._blendWeight=1,this._blendOrder=0,this._eventHandler=r,this.alignCursorToCurrentTime()}var e=t.prototype;return e.nextEventAheadOfTime=function(t){return!!this.nextEvent&&(this.isReverse?this.nextEvent.time<=t:this.nextEvent.time>=t)},e.nextEventBehindTime=function(t){return!!this.nextEvent&&(t===this.track.duration?this.isReverse?this.nextEvent.time>=t:this.nextEvent.time<=t:this.isReverse?this.nextEvent.time>t:this.nextEvent.time<t)},e.resetEventCursor=function(){this._eventCursor=this.isReverse?this._track.events.length-1:0},e.moveEventCursor=function(){this._eventCursor+=this.isReverse?-1:1,this._eventCursor>=this.track.events.length?this._eventCursor=0:this._eventCursor<0&&(this._eventCursor=this.track.events.length-1)},e.clipFrameTime=function(e){var i=t.eventFrame;i.start=0,i.end=e,i.residual=0,this.isReverse?e<0&&(i.start=this.track.duration,i.end=0,i.residual=e+this.track.duration):e>this.track.duration&&(i.start=0,i.end=this.track.duration,i.residual=e-this.track.duration)},e.alignCursorToCurrentTime=function(){for(this.resetEventCursor();this.nextEventBehindTime(this._time)&&this._eventCursor!==this.eventCursorEnd;)this.moveEventCursor()},e.fireNextEvent=function(){this._eventHandler.fire(this.nextEvent.name,x({track:this.track},this.nextEvent)),this.moveEventCursor()},e.fireNextEventInFrame=function(t,e){return!(!this.nextEventAheadOfTime(t)||!this.nextEventBehindTime(e))&&(this.fireNextEvent(),!0)},e.activeEventsForFrame=function(e,i){var n=t.eventFrame;this.clipFrameTime(i);for(var s=this.eventCursor;this.fireNextEventInFrame(e,n.end)&&s!==this.eventCursor;);this.loop&&Math.abs(n.residual)>0&&this.activeEventsForFrame(n.start,n.residual)},e.progressForTime=function(t){return t*this._speed/this._track.duration},e._update=function(t){if(this._playing){var e=this._time,i=this._track.duration,n=this._speed,s=this._loop;this._track.events.length>0&&i>0&&this.activeEventsForFrame(e,e+n*t),e+=n*t,n>=0?e>i&&(s?e=e%i||0:(e=this._track.duration,this.pause())):e<0&&(s?e=i+(e%i||0):(e=0,this.pause())),this._time=e}this._time!==this._snapshot._time&&this._track.eval(this._time,this._snapshot)},e.play=function(){this._playing=!0,this._time=0},e.stop=function(){this._playing=!1,this._time=0},e.pause=function(){this._playing=!1},e.resume=function(){this._playing=!0},e.reset=function(){this._time=0},y(t,[{key:"name",get:function(){return this._name},set:function(t){this._name=t}},{key:"track",get:function(){return this._track},set:function(t){this._track=t,this._snapshot=new Cp(t)}},{key:"snapshot",get:function(){return this._snapshot}},{key:"time",get:function(){return this._time},set:function(t){this._time=t,this.alignCursorToCurrentTime()}},{key:"speed",get:function(){return this._speed},set:function(t){var e=Math.sign(t)!==Math.sign(this._speed);this._speed=t,e&&this.alignCursorToCurrentTime()}},{key:"loop",get:function(){return this._loop},set:function(t){this._loop=t}},{key:"blendWeight",get:function(){return this._blendWeight},set:function(t){this._blendWeight=t}},{key:"blendOrder",get:function(){return this._blendOrder},set:function(t){this._blendOrder=t}},{key:"eventCursor",get:function(){return this._eventCursor},set:function(t){this._eventCursor=t}},{key:"eventCursorEnd",get:function(){return this.isReverse?0:this._track.events.length-1}},{key:"nextEvent",get:function(){return this._track.events[this._eventCursor]}},{key:"isReverse",get:function(){return this._speed<0}}]),t}();Ep.eventFrame={start:0,end:0,residual:0};var Mp="NONE",Pp="PREV_STATE",Rp="NEXT_STATE",Ip="PREV_STATE_NEXT_STATE",Lp="NEXT_STATE_PREV_STATE",Dp="GREATER_THAN",Op="LESS_THAN",kp="GREATER_THAN_EQUAL_TO",Fp="LESS_THAN_EQUAL_TO",Bp="EQUAL_TO",Up="NOT_EQUAL_TO",Np="INTEGER",zp="FLOAT",Vp="BOOLEAN",Gp="TRIGGER",Hp="2D_DIRECTIONAL",Wp="2D_CARTESIAN",Xp="DIRECT",jp="START",qp="END",Yp="ANY",Kp=[jp,qp,Yp],Zp="OVERWRITE",Qp="ADDITIVE",$p=function(){function t(){}return t.dot=function(t,e){for(var i=t.length,n=0,s=0;s<i;++s)n+=t[s]*e[s];return n},t.normalize=function(e){var i=t.dot(e,e);if(i>0){i=1/Math.sqrt(i);for(var n=e.length,s=0;s<n;++s)e[s]*=i}},t.set=function(e,i,n){var s=e.length;if("quaternion"===n){var r=t.dot(i,i);r>0&&(r=1/Math.sqrt(r));for(var a=0;a<s;++a)e[a]=i[a]*r}else for(var o=0;o<s;++o)e[o]=i[o]},t.blendVec=function(t,e,i,n){for(var s=n?1:1-i,r=t.length,a=0;a<r;++a)t[a]=t[a]*s+e[a]*i},t.blendQuat=function(e,i,n,s){var r=e.length,a=s?1:1-n;t.dot(e,i)<0&&(n=-n);for(var o=0;o<r;++o)e[o]=e[o]*a+i[o]*n;s||t.normalize(e)},t.blend=function(e,i,n,s,r){"quaternion"===s?t.blendQuat(e,i,n,r):t.blendVec(e,i,n,r)},t.stableSort=function(t,e){for(var i=t.length,n=0;n<i-1;++n)for(var s=n+1;s<i;++s)if(e(t[s],t[n])){var r=t[n];t[n]=t[s],t[s]=r}},t}(),Jp=function(){function t(e,i){this._component=e,this.mask=new Int8Array(e.layers.length),this.weights=new Float32Array(e.layers.length),this.totalWeight=0,this.counter=0,this.layerCounter=0,this.valueType=i,this.dirty=!0,this.value=i===t.TYPE_QUAT?[0,0,0,1]:[0,0,0],this.baseValue=null,this.setter=null}var e=t.prototype;return e.getWeight=function(t){return this.dirty&&this.updateWeights(),this._normalizeWeights&&0===this.totalWeight||!this.mask[t]?0:this._normalizeWeights?this.weights[t]/this.totalWeight:_t.clamp(this.weights[t],0,1)},e._layerBlendType=function(t){return this._component.layers[t].blendType},e.setMask=function(t,e){this.mask[t]=e,this._normalizeWeights&&(this._component.layers[t].blendType===Zp&&(this.mask=this.mask.fill(0,0,t)),this.dirty=!0)},e.updateWeights=function(){this.totalWeight=0;for(var t=0;t<this.weights.length;t++)this.weights[t]=this._component.layers[t].weight,this.totalWeight+=this.mask[t]*this.weights[t];this.dirty=!1},e.updateValue=function(e,i){if(0===this.counter&&($p.set(this.value,t.IDENTITY_QUAT_ARR,this.valueType),this._normalizeWeights||$p.blend(this.value,this.baseValue,1,this.valueType)),this.mask[e]&&0!==this.getWeight(e)){if(this._layerBlendType(e)!==Qp||this._normalizeWeights)$p.blend(this.value,i,this.getWeight(e),this.valueType);else if(this.valueType===t.TYPE_QUAT){var n=t.q1.set(this.value[0],this.value[1],this.value[2],this.value[3]),s=t.q2.set(this.baseValue[0],this.baseValue[1],this.baseValue[2],this.baseValue[3]),r=t.q3.set(i[0],i[1],i[2],i[3]),a=s.invert().mul(r);a.slerp(Bt.IDENTITY,a,this.getWeight(e)),n.mul(a),t.quatArr[0]=n.x,t.quatArr[1]=n.y,t.quatArr[2]=n.z,t.quatArr[3]=n.w,$p.set(this.value,t.quatArr,this.valueType)}else t.vecArr[0]=i[0]-this.baseValue[0],t.vecArr[1]=i[1]-this.baseValue[1],t.vecArr[2]=i[2]-this.baseValue[2],$p.blend(this.value,t.vecArr,this.getWeight(e),this.valueType,!0);this.setter&&this.setter(this.value)}},e.unbind=function(){this.setter&&this.setter(this.baseValue)},y(t,[{key:"_normalizeWeights",get:function(){return this._component.normalizeWeights}}]),t}();Jp.TYPE_QUAT="quaternion",Jp.TYPE_VEC3="vector3",Jp.q1=new Bt,Jp.q2=new Bt,Jp.q3=new Bt,Jp.quatArr=[0,0,0,1],Jp.vecArr=[0,0,0],Jp.IDENTITY_QUAT_ARR=[0,0,0,1];var tm,em=function(){function t(t){this._binder=t,this._clips=[],this._inputs=[],this._outputs=[],this._targets={}}var e=t.prototype;return e.addClip=function(t){for(var e=this._targets,i=this._binder,n=t.track.curves,s=t.snapshot,r=[],a=[],o=0;o<n.length;++o)for(var h=n[o].paths,l=0;l<h.length;++l){var c=h[l],u=i.resolve(c),d=e[u&&u.targetPath||null];if(!d&&u){d={target:u,value:[],curves:0,blendCounter:0};for(var f=0;f<d.target.components;++f)d.value.push(0);if(e[u.targetPath]=d,i.animComponent){if(!i.animComponent.targets[u.targetPath]){var p=void 0;p="localRotation"===u.targetPath.substring(u.targetPath.length-13)?Jp.TYPE_QUAT:Jp.TYPE_VEC3,i.animComponent.targets[u.targetPath]=new Jp(i.animComponent,p)}i.animComponent.targets[u.targetPath].layerCounter++,i.animComponent.targets[u.targetPath].setMask(i.layerIndex,1)}}d&&(d.curves++,r.push(s._results[o]),a.push(d))}this._clips.push(t),this._inputs.push(r),this._outputs.push(a)},e.removeClip=function(t){for(var e=this._targets,i=this._binder,n=this._clips,s=n[t].track.curves,r=0;r<s.length;++r)for(var a=s[r].paths,o=0;o<a.length;++o){var h=a[o],l=this._binder.resolve(h);l&&(l.curves--,0===l.curves&&(i.unresolve(h),delete e[l.targetPath],i.animComponent&&i.animComponent.targets[l.targetPath].layerCounter--))}n.splice(t,1),this._inputs.splice(t,1),this._outputs.splice(t,1)},e.removeClips=function(){for(;this._clips.length>0;)this.removeClip(0)},e.updateClipTrack=function(t,e){this._clips.forEach((function(i){i.name.includes(t)&&(i.track=e)})),this.rebind()},e.findClip=function(t){for(var e=this._clips,i=0;i<e.length;++i){var n=e[i];if(n.name===t)return n}return null},e.rebind=function(){var t=this;this._binder.rebind(),this._targets={};var e=[].concat(this.clips);this.removeClips(),e.forEach((function(e){t.addClip(e)}))},e.assignMask=function(t){return this._binder.assignMask(t)},e.update=function(t,e){void 0===e&&(e=!0);var i=this._clips,n=i.map((function(t,e){return e}));$p.stableSort(n,(function(t,e){return i[t].blendOrder<i[e].blendOrder}));for(var s=0;s<n.length;++s){var r=n[s],a=i[r],o=this._inputs[r],h=this._outputs[r],l=a.blendWeight;if(l>0&&a._update(t),!e)break;var c=void 0,u=void 0,d=void 0;if(l>=1)for(var f=0;f<o.length;++f)c=o[f],d=(u=h[f]).value,$p.set(d,c,u.target.type),u.blendCounter++;else if(l>0)for(var p=0;p<o.length;++p)c=o[p],d=(u=h[p]).value,0===u.blendCounter?$p.set(d,c,u.target.type):$p.blend(d,c,l,u.target.type),u.blendCounter++}var m=this._targets,_=this._binder;for(var v in m)if(m.hasOwnProperty(v)){var g=m[v];if(_.animComponent&&g.target.isTransform){var y=_.animComponent.targets[v];y.counter===y.layerCounter&&(y.counter=0),y.path||(y.path=v,y.baseValue=g.target.get(),y.setter=g.target.set),y.updateValue(_.layerIndex,g.value),y.counter++}else g.target.set(g.value);g.blendCounter=0}this._binder.update(t)},y(t,[{key:"clips",get:function(){return this._clips}}]),t}(),im=function(){function t(t){this._events=[].concat(t),this._events.sort((function(t,e){return t.time-e.time}))}return y(t,[{key:"events",get:function(){return this._events}}]),t}(),nm=function(){function t(t,e,i,n,s,r){void 0===r&&(r=new im([])),this._name=t,this._duration=e,this._inputs=i,this._outputs=n,this._curves=s,this._animEvents=r}return t.prototype.eval=function(t,e){e._time=t;for(var i=this._inputs,n=this._outputs,s=this._curves,r=e._cache,a=e._results,o=0;o<i.length;++o)r[o].update(t,i[o]._data);for(var h=0;h<s.length;++h){var l=s[h],c=n[l._output],u=a[h];r[l._input].eval(u,l._interpolation,c)}},y(t,[{key:"name",get:function(){return this._name}},{key:"duration",get:function(){return this._duration}},{key:"inputs",get:function(){return this._inputs}},{key:"outputs",get:function(){return this._outputs}},{key:"curves",get:function(){return this._curves}},{key:"events",get:function(){return this._animEvents.events},set:function(t){this._animEvents=t}}]),t}();tm=nm,nm.EMPTY=Object.freeze(new tm("empty",Number.MAX_VALUE,[],[],[]));var sm=function(){function t(){}t.joinPath=function(t,e){e=e||".";return t.map((function(t){return t.replace(/\\/g,"\\\\").replace(new RegExp("\\"+e,"g"),"\\"+e)})).join(e)},t.splitPath=function(t,e){e=e||".";for(var i=[],n="",s=0;s<t.length;){var r=t[s++];"\\"===r&&s<t.length?n+="\\"===(r=t[s++])||r===e?r:"\\"+r:r===e?(i.push(n),n=""):n+=r}return n.length>0&&i.push(n),i},t.encode=function(t,e,i){return(Array.isArray(t)?t.join("/"):t)+"/"+e+"/"+(Array.isArray(i)?i.join("/"):i)};var e=t.prototype;return e.resolve=function(t){return null},e.unresolve=function(t){},e.update=function(t){},t}(),rm=function(){function t(t,e,i,n){t.set?(this._set=t.set,this._get=t.get):this._set=t,this._type=e,this._components=i,this._targetPath=n,this._isTransform="localRotation"===this._targetPath.substring(this._targetPath.length-13)||"localPosition"===this._targetPath.substring(this._targetPath.length-13)||"localScale"===this._targetPath.substring(this._targetPath.length-10)}return y(t,[{key:"set",get:function(){return this._set}},{key:"get",get:function(){return this._get}},{key:"type",get:function(){return this._type}},{key:"components",get:function(){return this._components}},{key:"targetPath",get:function(){return this._targetPath}},{key:"isTransform",get:function(){return this._isTransform}}]),t}(),am=function(){function t(e){var i=this;if(this._isPathInMask=function(t,e){var n=i._mask[t];return!!n&&!!(n.children||e&&!1!==n.value)},this.graph=e,e){this._mask=null;var n={};!function t(e){n[e.name]=e;for(var i=0;i<e.children.length;++i)t(e.children[i])}(e),this.nodes=n,this.targetCache={};var s=function(t){for(var e,i=t;i&&!(i instanceof ip);)i=i.parent;return i&&(i.render?e=i.render.meshInstances:i.model&&(e=i.model.meshInstances)),e};this.nodeCounts={},this.activeNodes=[],this.handlers={localPosition:function(e){var i=e.localPosition;return t.createAnimTarget((function(t){i.set.apply(i,t)}),"vector",3,e,"localPosition")},localRotation:function(e){var i=e.localRotation;return t.createAnimTarget((function(t){i.set.apply(i,t)}),"quaternion",4,e,"localRotation")},localScale:function(e){var i=e.localScale;return t.createAnimTarget((function(t){i.set.apply(i,t)}),"vector",3,e,"localScale")},weight:function(e,i){i=0===i.indexOf("name.")?i.replace("name.",""):Number(i);var n,r=s(e);if(r)for(var a=function(){if(r[o].node.name===e.name&&r[o].morphInstance){var t=r[o].morphInstance;n||(n=[]),n.push((function(e){t.setWeight(i,e[0])}))}},o=0;o<r.length;++o)a();if(n){return t.createAnimTarget((function(t){for(var e=0;e<n.length;++e)n[e](t)}),"number",1,e,"weight."+i)}return null},materialTexture:function(e,n){var r=s(e);if(r){for(var a,o=0;o<r.length;++o)if(r[o].node.name===e.name){a=r[o];break}if(a){return t.createAnimTarget((function(t){var e=i.animComponent.system.app.assets.get(t[0]);e&&e.resource&&"texture"===e.type&&(a.material[n]=e.resource,a.material.update())}),"vector",1,e,"materialTexture","material")}}return null}}}}var e=t.prototype;return e._isPathActive=function(t){if(!this._mask)return!0;for(var e=[t.entityPath[0],this.graph.name],i=0;i<e.length;++i){var n=e[i];if(this._isPathInMask(n,1===t.entityPath.length))return!0;for(var s=1;s<t.entityPath.length;s++)if(n+="/"+t.entityPath[s],this._isPathInMask(n,s===t.entityPath.length-1))return!0}return!1},e.findNode=function(t){return this._isPathActive(t)?(this.graph&&((e=this.graph.findByPath(t.entityPath))||(e=this.graph.findByPath(t.entityPath.slice(1)))),e||(e=this.nodes[t.entityPath[t.entityPath.length-1]||""]),e):null;var e},t.createAnimTarget=function(t,e,i,n,s,r){var a=sm.encode(n.path,r||"entity",s);return new rm(t,e,i,a)},e.resolve=function(t){var e=sm.encode(t.entityPath,t.component,t.propertyPath),i=this.targetCache[e];if(i)return i;var n=this.findNode(t);if(!n)return null;var s=this.handlers[t.propertyPath];return s&&(i=s(n))?(this.targetCache[e]=i,this.nodeCounts[n.path]?this.nodeCounts[n.path]++:(this.activeNodes.push(n),this.nodeCounts[n.path]=1),i):null},e.unresolve=function(t){if("graph"===t.component){var e=this.nodes[t.entityPath[t.entityPath.length-1]||""];if(this.nodeCounts[e.path]--,0===this.nodeCounts[e.path]){var i=this.activeNodes,n=i.indexOf(e.node),s=i.length;n<s-1&&(i[n]=i[s-1]),i.pop()}}},e.update=function(t){for(var e=this.activeNodes,i=0;i<e.length;++i)e[i]._dirtifyLocal()},e.assignMask=function(t){return t!==this._mask&&(this._mask=t,!0)},t}(),om=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._animations={},n._assets=[],n._loop=!0,n.animEvaluator=null,n.model=null,n.skeleton=null,n.fromSkel=null,n.toSkel=null,n.animationsIndex={},n.prevAnim=null,n.currAnim=null,n.blend=0,n.blending=!1,n.blendSpeed=0,n.activate=!0,n.speed=1,n}S(e,t);var i=e.prototype;return i.play=function(t,e){if(void 0===e&&(e=0),this.enabled&&this.entity.enabled&&this.animations[t]){if(this.prevAnim=this.currAnim,this.currAnim=t,this.model){this.skeleton||this.animEvaluator||this._createAnimationController();var i=this.animations[this.prevAnim],n=this.animations[this.currAnim];if(this.blending=e>0&&!!this.prevAnim,this.blending&&(this.blend=0,this.blendSpeed=1/e),this.skeleton&&(this.blending?(this.fromSkel.animation=i,this.fromSkel.addTime(this.skeleton._time),this.toSkel.animation=n):this.skeleton.animation=n),this.animEvaluator){var s=this.animEvaluator;if(this.blending)for(;s.clips.length>1;)s.removeClip(0);else this.animEvaluator.removeClips();var r=new Ep(this.animations[this.currAnim],0,1,!0,this.loop);r.name=this.currAnim,r.blendWeight=this.blending?0:1,r.reset(),this.animEvaluator.addClip(r)}}this.playing=!0}},i.getAnimation=function(t){return this.animations[t]},i.setModel=function(t){t!==this.model&&(this._resetAnimationController(),this.model=t,this.animations&&this.currAnim&&this.animations[this.currAnim]&&this.play(this.currAnim))},i.onSetAnimations=function(){var t=this.entity.model;if(t){var e=t.model;e&&e!==this.model&&this.setModel(e)}if(!this.currAnim&&this.activate&&this.enabled&&this.entity.enabled){var i=Object.keys(this._animations);i.length>0&&this.play(i[0])}},i._resetAnimationController=function(){this.skeleton=null,this.fromSkel=null,this.toSkel=null,this.animEvaluator=null},i._createAnimationController=function(){var t=this.model,e=this.animations,i=!1,n=!1;for(var s in e){if(e.hasOwnProperty(s))e[s].constructor===nm?n=!0:i=!0}var r=t.getGraph();i?(this.fromSkel=new rf(r),this.toSkel=new rf(r),this.skeleton=new rf(r),this.skeleton.looping=this.loop,this.skeleton.setGraph(r)):n&&(this.animEvaluator=new em(new am(this.entity)))},i.loadAnimationAssets=function(t){var e=this;if(t&&t.length)for(var i=this.system.app.assets,n=function(t){if(t.resources.length>1)for(var i=0;i<t.resources.length;i++)e.animations[t.resources[i].name]=t.resources[i],e.animationsIndex[t.id]=t.resources[i].name;else e.animations[t.name]=t.resource,e.animationsIndex[t.id]=t.name;e.animations=e.animations},s=function(t){t.off("change",e.onAssetChanged,e),t.on("change",e.onAssetChanged,e),t.off("remove",e.onAssetRemoved,e),t.on("remove",e.onAssetRemoved,e),t.resource?n(t):(t.once("load",n,e),e.enabled&&e.entity.enabled&&i.load(t))},r=0,a=t.length;r<a;r++){var o=i.get(t[r]);o?s(o):i.on("add:"+t[r],s)}},i.onAssetChanged=function(t,e,i,n){if("resource"===e||"resources"===e)if("resources"===e&&i&&0===i.length&&(i=null),i){var s=!1;if(i.length>1){if(n&&n.length>1)for(var r=0;r<n.length;r++)delete this.animations[n[r].name];else delete this.animations[t.name];s=!1;for(var a=0;a<i.length;a++)this.animations[i[a].name]=i[a],s||this.currAnim!==i[a].name||this.playing&&this.enabled&&this.entity.enabled&&(s=!0,this.play(i[a].name));s||(this._stopCurrentAnimation(),this.onSetAnimations())}else{if(n&&n.length>1)for(var o=0;o<n.length;o++)delete this.animations[n[o].name];this.animations[t.name]=i[0]||i,s=!1,this.currAnim===t.name&&this.playing&&this.enabled&&this.entity.enabled&&(s=!0,this.play(t.name)),s||(this._stopCurrentAnimation(),this.onSetAnimations())}this.animationsIndex[t.id]=t.name}else{if(n.length>1)for(var h=0;h<n.length;h++)delete this.animations[n[h].name],this.currAnim===n[h].name&&this._stopCurrentAnimation();else delete this.animations[t.name],this.currAnim===t.name&&this._stopCurrentAnimation();delete this.animationsIndex[t.id]}},i.onAssetRemoved=function(t){if(t.off("remove",this.onAssetRemoved,this),this.animations){if(t.resources.length>1)for(var e=0;e<t.resources.length;e++)delete this.animations[t.resources[e].name],this.currAnim===t.resources[e].name&&this._stopCurrentAnimation();else delete this.animations[t.name],this.currAnim===t.name&&this._stopCurrentAnimation();delete this.animationsIndex[t.id]}},i._stopCurrentAnimation=function(){if(this.currAnim=null,this.playing=!1,this.skeleton&&(this.skeleton.currentTime=0,this.skeleton.animation=null),this.animEvaluator){for(var t=0;t<this.animEvaluator.clips.length;++t)this.animEvaluator.clips[t].stop();this.animEvaluator.update(0),this.animEvaluator.removeClips()}},i.onEnable=function(){t.prototype.onEnable.call(this);var e=this.assets,i=this.system.app.assets;if(e)for(var n=0,s=e.length;n<s;n++){var r=e[n];r instanceof Vf||(r=i.get(r)),r&&!r.resource&&i.load(r)}if(this.activate&&!this.currAnim){var a=Object.keys(this.animations);a.length>0&&this.play(a[0])}},i.onBeforeRemove=function(){for(var t=0;t<this.assets.length;t++){var e=this.assets[t];"number"==typeof e&&(e=this.system.app.assets.get(e)),e&&(e.off("change",this.onAssetChanged,this),e.off("remove",this.onAssetRemoved,this))}this.skeleton=null,this.fromSkel=null,this.toSkel=null,this.animEvaluator=null},i.update=function(t){if(this.blending&&(this.blend+=t*this.blendSpeed,this.blend>=1&&(this.blend=1)),this.playing){var e=this.skeleton;if(null!==e&&null!==this.model){if(this.blending)e.blend(this.fromSkel,this.toSkel,this.blend);else{var i=t*this.speed;e.addTime(i),(this.speed>0&&e._time===e.animation.duration&&!this.loop||this.speed<0&&0===e._time&&!this.loop)&&(this.playing=!1)}this.blending&&1===this.blend&&(e.animation=this.toSkel.animation),e.updateGraph()}}var n=this.animEvaluator;if(n){for(var s=0;s<n.clips.length;++s){var r=n.clips[s];r.speed=this.speed,this.playing?r.resume():r.pause()}this.blending&&n.clips.length>1&&(n.clips[1].blendWeight=this.blend),n.update(t)}this.blending&&1===this.blend&&(this.blending=!1)},y(e,[{key:"animations",get:function(){return this._animations},set:function(t){this._animations=t,this.onSetAnimations()}},{key:"assets",get:function(){return this._assets},set:function(t){var e=this._assets;if(e&&e.length)for(var i=0;i<e.length;i++)if(e[i]){var n=this.system.app.assets.get(e[i]);if(n){n.off("change",this.onAssetChanged,this),n.off("remove",this.onAssetRemoved,this);var s=this.animationsIndex[n.id];this.currAnim===s&&this._stopCurrentAnimation(),delete this.animations[s],delete this.animationsIndex[n.id]}}this._assets=t;var r=t.map((function(t){return t instanceof Vf?t.id:t}));this.loadAnimationAssets(r)}},{key:"currentTime",get:function(){if(this.skeleton)return this.skeleton._time;if(this.animEvaluator){var t=this.animEvaluator.clips;if(t.length>0)return t[t.length-1].time}return 0},set:function(t){if(this.skeleton&&(this.skeleton.currentTime=t,this.skeleton.addTime(0),this.skeleton.updateGraph()),this.animEvaluator)for(var e=this.animEvaluator.clips,i=0;i<e.length;++i)e[i].time=t}},{key:"duration",get:function(){return this.currAnim?this.animations[this.currAnim].duration:0}},{key:"loop",get:function(){return this._loop},set:function(t){if(this._loop=t,this.skeleton&&(this.skeleton.looping=t),this.animEvaluator)for(var e=0;e<this.animEvaluator.clips.length;++e)this.animEvaluator.clips[e].loop=t}}]),e}(bp),hm=function(){this.enabled=!0},lm=["enabled"],cm=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="animation",i.ComponentType=om,i.DataType=hm,i.schema=lm,i.on("beforeremove",i.onBeforeRemove,w(i)),i.app.systems.on("update",i.onUpdate,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){for(var s,r=A(["activate","enabled","loop","speed","assets"]);!(s=r()).done;){var a=s.value;i.hasOwnProperty(a)&&(e[a]=i[a])}t.prototype.initializeComponentData.call(this,e,i,lm)},i.cloneComponent=function(t,e){this.addComponent(e,{}),e.animation.assets=t.animation.assets.slice(),e.animation.speed=t.animation.speed,e.animation.loop=t.animation.loop,e.animation.activate=t.animation.activate,e.animation.enabled=t.animation.enabled;var i={},n=t.animation.animations;for(var s in n)n.hasOwnProperty(s)&&(i[s]=n[s]);e.animation.animations=i;var r={},a=t.animation.animationsIndex;for(var o in a)a.hasOwnProperty(o)&&(r[o]=a[o]);return e.animation.animationsIndex=r,e.animation},i.onBeforeRemove=function(t,e){e.onBeforeRemove()},i.onUpdate=function(t){var e=this.store;for(var i in e)if(e.hasOwnProperty(i)){var n=e[i];n.data.enabled&&n.entity.enabled&&n.entity.animation.update(t)}},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},e}(wp);bp._buildAccessors(om.prototype,lm);var um=function(){function t(t,e,i,n,s){void 0===s&&(s=1),this._state=t,this._parent=e,this._name=i,Array.isArray(n)?(this._point=new Et(n[0],n[1]),this._pointLength=this._point.length()):(this._point=n,this._pointLength=n),this._speed=s,this._weightedSpeed=1,this._weight=1,this._animTrack=null}return y(t,[{key:"parent",get:function(){return this._parent}},{key:"name",get:function(){return this._name}},{key:"path",get:function(){return this._parent?this._parent.path+"."+this._name:this._name}},{key:"point",get:function(){return this._point}},{key:"pointLength",get:function(){return this._pointLength}},{key:"weight",get:function(){return this._parent?this._parent.weight*this._weight:this._weight},set:function(t){this._weight=t}},{key:"normalizedWeight",get:function(){var t=this._state.totalWeight;return 0===t?0:this.weight/t}},{key:"speed",get:function(){return this._weightedSpeed*this._speed}},{key:"absoluteSpeed",get:function(){return Math.abs(this._speed)}},{key:"weightedSpeed",get:function(){return this._weightedSpeed},set:function(t){this._weightedSpeed=t}},{key:"animTrack",get:function(){return this._animTrack},set:function(t){this._animTrack=t}}]),t}(),dm=function(t){function e(e,i,n,s,r,a,o,h,l){var c;(c=t.call(this,e,i,n,s)||this)._parameters=r,c._parameterValues=new Array(r.length),c._children=[],c._findParameter=l,c._syncAnimations=!1!==o,c._pointCache={};for(var u=0;u<a.length;u++){var d=a[u];d.children?c._children.push(h(d.type,w(c),null,n,1,d.parameter?[d.parameter]:d.parameters,d.children,h,l)):c._children.push(new um(e,w(c),d.name,d.point,d.speed))}return c}S(e,t);var i=e.prototype;return i.getChild=function(t){for(var e=0;e<this._children.length;e++)if(this._children[e].name===t)return this._children[e];return null},i.updateParameterValues=function(){for(var t=!0,e=0;e<this._parameterValues.length;e++){var i=this._findParameter(this._parameters[e]).value;this._parameterValues[e]!==i&&(this._parameterValues[e]=i,t=!1)}return t},i.getNodeWeightedDuration=function(t){return this._children[t].animTrack.duration/this._children[t].speedMultiplier*this._children[t].weight},i.getNodeCount=function(){for(var t=0,i=0;i<this._children.length;i++){this._children[i].constructor===e?t+=this._children[i].getNodeCount():t++}return t},y(e,[{key:"weight",get:function(){return this.calculateWeights(),this._parent?this._parent.weight*this._weight:this._weight}},{key:"syncAnimations",get:function(){return this._syncAnimations}}]),e}(um),fm=function(t){function e(e,i,n,s,r,a,o,h,l){return a.sort((function(t,e){return t.point-e.point})),t.call(this,e,i,n,s,r,a,o,h,l)||this}return S(e,t),e.prototype.calculateWeights=function(){if(!this.updateParameterValues()){var t=0;this._children[0].weight=0;for(var e=0;e<this._children.length;e++){var i=this._children[e];if(e!==this._children.length-1){var n=this._children[e+1];if(i.point===n.point)i.weight=.5,n.weight=.5;else if(_t.between(this._parameterValues[0],i.point,n.point,!0)){var s=Math.abs(i.point-n.point),r=(s-Math.abs(i.point-this._parameterValues[0]))/s;i.weight=r,n.weight=1-r}else n.weight=0}this._syncAnimations&&(t+=i.animTrack.duration/i.absoluteSpeed*i.weight)}if(this._syncAnimations)for(var a=0;a<this._children.length;a++){var o=this._children[a];o.weightedSpeed=o.animTrack.duration/o.absoluteSpeed/t}}},e}(dm),pm=function(t){function e(){return t.apply(this,arguments)||this}S(e,t);var i=e.prototype;return i.pointDistanceCache=function(t,e){var i=""+t+e;return this._pointCache[i]||(this._pointCache[i]=this._children[e].point.clone().sub(this._children[t].point)),this._pointCache[i]},i.calculateWeights=function(){var t;if(!this.updateParameterValues()){var i,n;(t=e._p).set.apply(t,this._parameterValues),i=0,n=0;for(var s=0;s<this._children.length;s++){var r=this._children[s],a=r.point;e._pip.set(e._p.x,e._p.y).sub(a);for(var o=Number.MAX_VALUE,h=0;h<this._children.length;h++)if(s!==h){var l=this.pointDistanceCache(s,h),c=_t.clamp(1-e._pip.dot(l)/l.lengthSq(),0,1);c<o&&(o=c)}r.weight=o,i+=o,this._syncAnimations&&(n+=r.animTrack.duration/r.absoluteSpeed*r.weight)}for(var u=0;u<this._children.length;u++){var d=this._children[u];d.weight=d._weight/i,this._syncAnimations&&(d.weightedSpeed=d.animTrack.duration/d.absoluteSpeed/n)}}},e}(dm);pm._p=new Et,pm._pip=new Et;var mm=function(t){function e(){return t.apply(this,arguments)||this}S(e,t);var i=e.prototype;return i.pointCache=function(t,e){var i=""+t+e;return this._pointCache[i]||(this._pointCache[i]=new Et((this._children[e].pointLength-this._children[t].pointLength)/((this._children[e].pointLength+this._children[t].pointLength)/2),2*Et.angleRad(this._children[t].point,this._children[e].point))),this._pointCache[i]},i.calculateWeights=function(){var t;if(!this.updateParameterValues()){var i,n;(t=e._p).set.apply(t,this._parameterValues);var s=e._p.length();i=0,n=0;for(var r=0;r<this._children.length;r++){for(var a=this._children[r],o=a.point,h=a.pointLength,l=Number.MAX_VALUE,c=0;c<this._children.length;c++)if(r!==c){var u=this.pointCache(r,c),d=this._children[c].pointLength;e._pip.set((s-h)/((d+h)/2),2*Et.angleRad(o,e._p));var f=_t.clamp(1-Math.abs(e._pip.dot(u)/u.lengthSq()),0,1);f<l&&(l=f)}a.weight=l,i+=l,this._syncAnimations&&(n+=a.animTrack.duration/a.absoluteSpeed*a.weight)}for(var p=0;p<this._children.length;p++){var m=this._children[p];if(m.weight=m._weight/i,this._syncAnimations){var _=m.animTrack.duration/n*i;m.weightedSpeed=m.absoluteSpeed*_}}}},e}(dm);mm._p=new Et,mm._pip=new Et;var _m=function(t){function e(){return t.apply(this,arguments)||this}return S(e,t),e.prototype.calculateWeights=function(){if(!this.updateParameterValues()){for(var t=0,e=0,i=0;i<this._children.length;i++)if(t+=Math.max(this._parameterValues[i],0),this._syncAnimations){var n=this._children[i];e+=n.animTrack.duration/n.absoluteSpeed*n.weight}for(var s=0;s<this._children.length;s++){var r=this._children[s],a=Math.max(this._parameterValues[s],0);t?(r.weight=a/t,this._syncAnimations&&(r.weightedSpeed=r.animTrack.duration/r.absoluteSpeed/e)):(r.weight=0,this._syncAnimations&&(r.weightedSpeed=0))}}},e}(dm),vm=function(){function t(t,e,i,n,s){void 0===i&&(i=1),void 0===n&&(n=!0),this._animations={},this._animationList=[],this._controller=t,this._name=e,this._speed=i,this._loop=n,this._hasAnimations=!1,this._blendTree=s?this._createTree(s.type,this,null,e,1,s.parameter?[s.parameter]:s.parameters,s.children,s.syncAnimations,this._createTree,this._controller.findParameter):new um(this,null,e,1,i)}var e=t.prototype;return e._createTree=function(t,e,i,n,s,r,a,o,h,l){switch(t){case"1D":return new fm(e,i,n,s,r,a,o,h,l);case Wp:return new pm(e,i,n,s,r,a,o,h,l);case Hp:return new mm(e,i,n,s,r,a,o,h,l);case Xp:return new _m(e,i,n,s,r,a,o,h,l)}},e._getNodeFromPath=function(t){for(var e=this._blendTree,i=1;i<t.length;i++)e=e.getChild(t[i]);return e},e.addAnimation=function(t,e){var i=t.join("."),n=this._animationList.findIndex((function(t){return t.path===i}));if(n>=0)this._animationList[n].animTrack=e;else{var s=this._getNodeFromPath(t);s.animTrack=e,this._animationList.push(s)}this._updateHasAnimations()},e._updateHasAnimations=function(){this._hasAnimations=this._animationList.length>0&&this._animationList.every((function(t){return t.animTrack&&t.animTrack!==nm.EMPTY}))},y(t,[{key:"name",get:function(){return this._name}},{key:"animations",get:function(){return this._animationList},set:function(t){this._animationList=t,this._updateHasAnimations()}},{key:"hasAnimations",get:function(){return this._hasAnimations}},{key:"speed",get:function(){return this._speed},set:function(t){this._speed=t}},{key:"loop",get:function(){return this._loop},set:function(t){this._loop=t}},{key:"nodeCount",get:function(){return this._blendTree&&this._blendTree.constructor!==um?this._blendTree.getNodeCount():1}},{key:"playable",get:function(){return-1!==Kp.indexOf(this.name)||this.animations.length===this.nodeCount}},{key:"looping",get:function(){if(this.animations.length>0){var t=this.name+"."+this.animations[0].animTrack.name,e=this._controller.animEvaluator.findClip(t);if(e)return e.loop}return!1}},{key:"totalWeight",get:function(){for(var t=0,e=0;e<this.animations.length;e++)t+=this.animations[e].weight;return t}},{key:"timelineDuration",get:function(){for(var t=0,e=0;e<this.animations.length;e++){var i=this.animations[e];i.animTrack.duration>t&&(t=i.animTrack.duration)}return t}}]),t}(),gm=function(){function t(t){var e=t.from,i=t.to,n=t.time,s=void 0===n?0:n,r=t.priority,a=void 0===r?0:r,o=t.conditions,h=void 0===o?[]:o,l=t.exitTime,c=void 0===l?null:l,u=t.transitionOffset,d=void 0===u?null:u,f=t.interruptionSource,p=void 0===f?Mp:f;this._from=e,this._to=i,this._time=s,this._priority=a,this._conditions=h,this._exitTime=c,this._transitionOffset=d,this._interruptionSource=p}return y(t,[{key:"from",get:function(){return this._from}},{key:"to",get:function(){return this._to},set:function(t){this._to=t}},{key:"time",get:function(){return this._time}},{key:"priority",get:function(){return this._priority}},{key:"conditions",get:function(){return this._conditions}},{key:"exitTime",get:function(){return this._exitTime}},{key:"transitionOffset",get:function(){return this._transitionOffset}},{key:"interruptionSource",get:function(){return this._interruptionSource}},{key:"hasExitTime",get:function(){return!!this.exitTime}}]),t}(),ym=function(){function t(t,e,i,n,s,r,a){var o=this;this.findParameter=function(t){return o._findParameter(t)},this._animEvaluator=t,this._states={},this._stateNames=[],this._eventHandler=s,this._findParameter=r,this._consumeTrigger=a;for(var h=0;h<e.length;h++)this._states[e[h].name]=new vm(this,e[h].name,e[h].speed,e[h].loop,e[h].blendTree),this._stateNames.push(e[h].name);this._transitions=i.map((function(t){return new gm(x({},t))})),this._findTransitionsFromStateCache={},this._findTransitionsBetweenStatesCache={},this._previousStateName=null,this._activeStateName=jp,this._activeStateDuration=0,this._activeStateDurationDirty=!0,this._playing=!1,this._activate=n,this._currTransitionTime=1,this._totalTransitionTime=1,this._isTransitioning=!1,this._transitionInterruptionSource=Mp,this._transitionPreviousStates=[],this._timeInState=0,this._timeInStateBefore=0}var e=t.prototype;return e.assignMask=function(t){return this._animEvaluator.assignMask(t)},e._findState=function(t){return this._states[t]},e._getActiveStateProgressForTime=function(t){if(this.activeStateName===jp||this.activeStateName===qp||this.activeStateName===Yp)return 1;var e=this._animEvaluator.findClip(this.activeStateAnimations[0].name);return e?e.progressForTime(t):null},e._findTransitionsFromState=function(t){var e=this._findTransitionsFromStateCache[t];return e||(e=this._transitions.filter((function(e){return e.from===t})),Mu(e),this._findTransitionsFromStateCache[t]=e),e},e._findTransitionsBetweenStates=function(t,e){var i=this._findTransitionsBetweenStatesCache[t+"->"+e];return i||(i=this._transitions.filter((function(i){return i.from===t&&i.to===e})),Mu(i),this._findTransitionsBetweenStatesCache[t+"->"+e]=i),i},e._transitionHasConditionsMet=function(t){for(var e=t.conditions,i=0;i<e.length;i++){var n=e[i],s=this._findParameter(n.parameterName);switch(n.predicate){case Dp:if(!(s.value>n.value))return!1;break;case Op:if(!(s.value<n.value))return!1;break;case kp:if(!(s.value>=n.value))return!1;break;case Fp:if(!(s.value<=n.value))return!1;break;case Bp:if(s.value!==n.value)return!1;break;case Up:if(s.value===n.value)return!1}}return!0},e._findTransition=function(t,e){var i=this,n=[];if(t&&e)n=n.concat(this._findTransitionsBetweenStates(t,e));else if(this._isTransitioning)switch(this._transitionInterruptionSource){case Pp:n=(n=n.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(Yp));break;case Rp:n=(n=n.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(Yp));break;case Ip:n=(n=(n=n.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(Yp));break;case Lp:n=(n=(n=n.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(Yp))}else n=(n=n.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(Yp));if(n=n.filter((function(t){if(t.to===i.activeStateName)return!1;if(t.hasExitTime){var e=i._getActiveStateProgressForTime(i._timeInStateBefore),n=i._getActiveStateProgressForTime(i._timeInState);if(t.exitTime<1&&i.activeState.loop&&(e-=Math.floor(e),n-=Math.floor(n)),n===e){if(n!==t.exitTime)return null}else if(!(t.exitTime>e&&t.exitTime<=n))return null}return i._transitionHasConditionsMet(t)})),n.length>0){var s=n[0];if(s.to===qp){var r=this._findTransitionsFromState(jp)[0];s.to=r.to}return s}return null},e.updateStateFromTransition=function(t){var e,i,n;this.previousState=t.from?this.activeStateName:null,this.activeState=t.to,this._activeStateDurationDirty=!0;for(var s=0;s<t.conditions.length;s++){var r=t.conditions[s];this._findParameter(r.parameterName).type===Gp&&this._consumeTrigger(r.parameterName)}if(this.previousState){this._isTransitioning||(this._transitionPreviousStates=[]),this._transitionPreviousStates.push({name:this._previousStateName,weight:1});for(var a=Math.min(0!==this._totalTransitionTime?this._currTransitionTime/this._totalTransitionTime:1,1),o=0;o<this._transitionPreviousStates.length;o++){this._isTransitioning?o!==this._transitionPreviousStates.length-1?this._transitionPreviousStates[o].weight*=1-a:this._transitionPreviousStates[o].weight=a:this._transitionPreviousStates[o].weight=1,e=this._findState(this._transitionPreviousStates[o].name);for(var h=0;h<e.animations.length;h++)i=e.animations[h],(n=this._animEvaluator.findClip(i.name+".previous."+o))||((n=this._animEvaluator.findClip(i.name)).name=i.name+".previous."+o),o!==this._transitionPreviousStates.length-1&&n.pause()}}this._isTransitioning=!0,this._totalTransitionTime=t.time,this._currTransitionTime=0,this._transitionInterruptionSource=t.interruptionSource;var l=this.activeState,c=t.transitionOffset&&t.transitionOffset>0&&t.transitionOffset<1,u=0,d=0;if(c){var f=l.timelineDuration*t.transitionOffset;u=f,d=f}this._timeInState=u,this._timeInStateBefore=d;for(var p=0;p<l.animations.length;p++){if(n=this._animEvaluator.findClip(l.animations[p].name))n.reset();else{var m=Number.isFinite(l.animations[p].speed)?l.animations[p].speed:l.speed;(n=new Ep(l.animations[p].animTrack,this._timeInState,m,!0,l.loop,this._eventHandler)).name=l.animations[p].name,this._animEvaluator.addClip(n)}if(t.time>0?n.blendWeight=0:n.blendWeight=l.animations[p].normalizedWeight,n.play(),c)n.time=l.timelineDuration*t.transitionOffset;else{var _=l.speed>=0?0:this.activeStateDuration;n.time=_}}},e._transitionToState=function(t){if(this._findState(t)){var e=this._findTransition(this._activeStateName,t);e||(this._animEvaluator.removeClips(),e=new gm({from:null,to:t})),this.updateStateFromTransition(e)}},e.assignAnimation=function(t,e,i,n){var s=t.split("."),r=this._findState(s[0]);r||(r=new vm(this,s[0],i),this._states[s[0]]=r,this._stateNames.push(s[0])),r.addAnimation(s,e),this._animEvaluator.updateClipTrack(r.name,e),void 0!==i&&(r.speed=i),void 0!==n&&(r.loop=n),!this._playing&&this._activate&&this.playable&&this.play(),this._activeStateDurationDirty=!0},e.removeNodeAnimations=function(t){if(-1!==Kp.indexOf(t))return!1;var e=this._findState(t);return!!e&&(e.animations=[],!0)},e.play=function(t){t&&this._transitionToState(t),this._playing=!0},e.pause=function(){this._playing=!1},e.reset=function(){this._previousStateName=null,this._activeStateName=jp,this._playing=!1,this._currTransitionTime=1,this._totalTransitionTime=1,this._isTransitioning=!1,this._timeInState=0,this._timeInStateBefore=0,this._animEvaluator.removeClips()},e.rebind=function(){this._animEvaluator.rebind()},e.update=function(t){if(this._playing){var e,i,n;(this.activeState.loop||this._timeInState<this.activeStateDuration)&&(this._timeInStateBefore=this._timeInState,this._timeInState+=t*this.activeState.speed,!this.activeState.loop&&this._timeInState>this.activeStateDuration&&(this._timeInState=this.activeStateDuration,t=this.activeStateDuration-this._timeInStateBefore));var s=this._findTransition(this._activeStateName);if(s&&this.updateStateFromTransition(s),this._isTransitioning)if(this._currTransitionTime+=t,this._currTransitionTime<=this._totalTransitionTime){for(var r=0!==this._totalTransitionTime?this._currTransitionTime/this._totalTransitionTime:1,a=0;a<this._transitionPreviousStates.length;a++){e=this._findState(this._transitionPreviousStates[a].name);for(var o=this._transitionPreviousStates[a].weight,h=0;h<e.animations.length;h++)i=e.animations[h],(n=this._animEvaluator.findClip(i.name+".previous."+a))&&(n.blendWeight=(1-r)*i.normalizedWeight*o)}e=this.activeState;for(var l=0;l<e.animations.length;l++)i=e.animations[l],this._animEvaluator.findClip(i.name).blendWeight=r*i.normalizedWeight}else{this._isTransitioning=!1;for(var c=this.activeStateAnimations.length,u=this._animEvaluator.clips.length,d=0;d<u-c;d++)this._animEvaluator.removeClip(0);this._transitionPreviousStates=[],e=this.activeState;for(var f=0;f<e.animations.length;f++)i=e.animations[f],(n=this._animEvaluator.findClip(i.name))&&(n.blendWeight=i.normalizedWeight)}else if(this.activeState._blendTree.constructor!==um){e=this.activeState;for(var p=0;p<e.animations.length;p++)i=e.animations[p],(n=this._animEvaluator.findClip(i.name))&&(n.blendWeight=i.normalizedWeight,i.parent.syncAnimations&&(n.speed=i.speed))}this._animEvaluator.update(t,this.activeState.hasAnimations)}},y(t,[{key:"animEvaluator",get:function(){return this._animEvaluator}},{key:"activeState",get:function(){return this._findState(this._activeStateName)},set:function(t){this._activeStateName=t}},{key:"activeStateName",get:function(){return this._activeStateName}},{key:"activeStateAnimations",get:function(){return this.activeState.animations}},{key:"previousState",get:function(){return this._findState(this._previousStateName)},set:function(t){this._previousStateName=t}},{key:"previousStateName",get:function(){return this._previousStateName}},{key:"playable",get:function(){for(var t=!0,e=0;e<this._stateNames.length;e++)this._states[this._stateNames[e]].playable||(t=!1);return t}},{key:"playing",get:function(){return this._playing},set:function(t){this._playing=t}},{key:"activeStateProgress",get:function(){return this._getActiveStateProgressForTime(this._timeInState)}},{key:"activeStateDuration",get:function(){if(this._activeStateDurationDirty){for(var t=0,e=0;e<this.activeStateAnimations.length;e++){var i=this._animEvaluator.findClip(this.activeStateAnimations[e].name);i&&(t=Math.max(t,i.track.duration))}this._activeStateDuration=t,this._activeStateDurationDirty=!1}return this._activeStateDuration}},{key:"activeStateCurrentTime",get:function(){return this._timeInState},set:function(t){this._timeInStateBefore=t,this._timeInState=t;for(var e=0;e<this.activeStateAnimations.length;e++){var i=this.animEvaluator.findClip(this.activeStateAnimations[e].name);i&&(i.time=t)}}},{key:"transitioning",get:function(){return this._isTransitioning}},{key:"transitionProgress",get:function(){return this._currTransitionTime/this._totalTransitionTime}},{key:"states",get:function(){return this._stateNames}}]),t}(),xm=new Et,Sm=new wt,bm=new Pt,wm=new vt,Tm=new Bt,Am=function(t){function e(e,i,n,s,r){var a;return(a=t.call(this,i)||this).animComponent=e,a._mask=s,a.layerName=n,a.layerIndex=r,a}S(e,t),e._packFloat=function(t){return t[0]},e._packBoolean=function(t){return!!t[0]},e._packVec2=function(t){return xm.x=t[0],xm.y=t[1],xm},e._packVec3=function(t){return Sm.x=t[0],Sm.y=t[1],Sm.z=t[2],Sm},e._packVec4=function(t){return bm.x=t[0],bm.y=t[1],bm.z=t[2],bm.w=t[3],bm},e._packColor=function(t){return wm.r=t[0],wm.g=t[1],wm.b=t[2],wm.a=t[3],wm},e._packQuat=function(t){return Tm.x=t[0],Tm.y=t[1],Tm.z=t[2],Tm.w=t[3],Tm};var i=e.prototype;return i.resolve=function(t){var e,i,n,s=sm.encode(t.entityPath,t.component,t.propertyPath),r=this.targetCache[s];if(r)return r;switch(t.component){case"entity":e=this._getEntityFromHierarchy(t.entityPath),n=sm.encode(e.path,"entity",t.propertyPath),i=e;break;case"graph":if(!(i=this.findNode(t)))return null;n=sm.encode(i.path,"graph",t.propertyPath);break;default:if(!(i=(e=this._getEntityFromHierarchy(t.entityPath)).findComponent(t.component)))return null;n=sm.encode(e.path,t.component,t.propertyPath)}return r=this._createAnimTargetForProperty(i,t.propertyPath,n),this.targetCache[s]=r,r},i.update=function(t){var e=this.activeNodes;if(e)for(var i=0;i<e.length;i++)e[i]._dirtifyLocal()},i._getEntityFromHierarchy=function(t){if(!this.animComponent.entity.name===t[0])return null;var e=this.animComponent.entity;return 1===t.length?e:e._parent.findByPath(t)},i._resolvePath=function(t,e,i){for(var n=e.length-(i?0:1),s=0;s<n;s++)t=t[e[s]];return t},i._setter=function(t,e,i){var n=this._resolvePath(t,e),s=e[e.length-1],r="set"+s.substring(0,1).toUpperCase()+s.substring(1);if(n[r]){var a=n["get"+s.substring(0,1).toUpperCase()+s.substring(1)].bind(n)();a=[a.x,a.y,a.z,a.w];var o=n[r].bind(n);return{set:function(t){o(i(t))},get:function(){return a}}}var h=n[s];if("object"==typeof h&&h.hasOwnProperty("copy"))return function(t){h.copy(i(t))};if(-1!==[Et,wt,Pt,vt,Bt].indexOf(n.constructor)&&e.length>1){var l=e.length>2?this._resolvePath(t,e.slice(0,-1)):t,c=e[e.length-2];return function(t){n[s]=i(t),l[c]=n}}return function(t){n[s]=i(t)}},i._createAnimTargetForProperty=function(t,i,n){if(this.handlers&&i[0].startsWith("weight."))return this.handlers.weight(t,i[0].replace("weight.",""));if(this.handlers&&"material"===i[0]&&2===i.length){var s=i[1];if(s.endsWith("Map"))return this.handlers.materialTexture(t,s)}var r,a,o,h=this._resolvePath(t,i,!0);if(void 0===h)return null;if("number"==typeof h)r=this._setter(t,i,e._packFloat),a="vector",o=1;else if("boolean"==typeof h)r=this._setter(t,i,e._packBoolean),a="vector",o=1;else if("object"==typeof h)switch(h.constructor){case Et:r=this._setter(t,i,e._packVec2),a="vector",o=2;break;case wt:r=this._setter(t,i,e._packVec3),a="vector",o=3;break;case Pt:r=this._setter(t,i,e._packVec4),a="vector",o=4;break;case vt:r=this._setter(t,i,e._packColor),a="vector",o=4;break;case Bt:r=this._setter(t,i,e._packQuat),a="quaternion",o=4;break;default:return null}return-1!==i.indexOf("material")?new rm((function(e){r(e),t.material.update()}),a,o,n):new rm(r,a,o,n)},i.rebind=function(){this.targetCache={},this.animComponent.rootBone?this.graph=this.animComponent.rootBone:this.graph=this.animComponent.entity;var t={};!function e(i){t[i.name]=i;for(var n=0;n<i.children.length;++n)e(i.children[n])}(this.graph),this.nodes=t},e}(am),Cm=function(){function t(t,e,i,n,s,r){void 0===n&&(n=1),void 0===s&&(s=Zp),void 0===r&&(r=!0),this._name=t,this._controller=e,this._component=i,this._weight=n,this._blendType=s,this._normalizedWeight=r,this._mask=null,this._blendTime=0,this._blendTimeElapsed=0,this._startingWeight=0,this._targetWeight=0}var e=t.prototype;return e.play=function(t){this._controller.play(t)},e.pause=function(){this._controller.pause()},e.reset=function(){this._controller.reset()},e.rebind=function(){this._controller.rebind()},e.update=function(t){this._blendTime&&(this._blendTimeElapsed<this._blendTime?(this.weight=_t.lerp(this._startingWeight,this._targetWeight,this._blendTimeElapsed/this._blendTime),this._blendTimeElapsed+=t):(this.weight=this._targetWeight,this._blendTime=0,this._blendTimeElapsed=0,this._startingWeight=0,this._targetWeight=0)),this._controller.update(t)},e.blendToWeight=function(t,e){this._startingWeight=this.weight,this._targetWeight=t,this._blendTime=Math.max(0,e),this._blendTimeElapsed=0},e.assignMask=function(t){this._controller.assignMask(t)&&this._component.rebind(),this._mask=t},e.assignAnimation=function(t,e,i,n){e instanceof nm&&(this._controller.assignAnimation(t,e,i,n),0===this._controller._transitions.length&&this._controller._transitions.push(new gm({from:"START",to:t})),this._component.activate&&this._component.playable&&(this._component.playing=!0))},e.removeNodeAnimations=function(t){this._controller.removeNodeAnimations(t)&&(this._component.playing=!1)},e.getAnimationAsset=function(t){return this._component.animationAssets[this.name+":"+t]},e.transition=function(t,e,i){void 0===e&&(e=0),void 0===i&&(i=null),this._controller.updateStateFromTransition(new gm({from:this._controller.activeStateName,to:t,time:e,transitionOffset:i}))},y(t,[{key:"name",get:function(){return this._name}},{key:"playing",get:function(){return this._controller.playing},set:function(t){this._controller.playing=t}},{key:"playable",get:function(){return this._controller.playable}},{key:"activeState",get:function(){return this._controller.activeStateName}},{key:"previousState",get:function(){return this._controller.previousStateName}},{key:"activeStateProgress",get:function(){return this._controller.activeStateProgress}},{key:"activeStateDuration",get:function(){return this._controller.activeStateDuration}},{key:"activeStateCurrentTime",get:function(){return this._controller.activeStateCurrentTime},set:function(t){var e=this._controller,i=e.playing;e.playing=!0,e.activeStateCurrentTime=t,i||e.update(0),e.playing=i}},{key:"transitioning",get:function(){return this._controller.transitioning}},{key:"transitionProgress",get:function(){return this.transitioning?this._controller.transitionProgress:null}},{key:"states",get:function(){return this._controller.states}},{key:"weight",get:function(){return this._weight},set:function(t){this._weight=t,this._component.dirtifyTargets()}},{key:"blendType",get:function(){return this._blendType},set:function(t){t!==this._blendType&&(this._blendType=t,this._controller.normalizeWeights&&this._component.rebind())}},{key:"mask",get:function(){return this._mask},set:function(t){this._controller.assignMask(t)&&this._component.rebind(),this._mask=t}}]),t}(),Em=function(){function t(t){if(this._layers=[],this._parameters={},Array.isArray(t.layers))this._layers=t.layers;else for(var e in t.layers){for(var i=t.layers[e],n={name:i.name,blendType:i.blendType,weight:i.weight,states:[],transitions:[]},s=0;s<i.states.length;s++)n.states.push(t.states[i.states[s]]);for(var r=0;r<i.transitions.length;r++){var a=t.transitions[i.transitions[r]];if(a.conditions&&!Array.isArray(a.conditions)){for(var o=Object.keys(a.conditions),h=[],l=0;l<o.length;l++){var c=a.conditions[o[l]];c.parameterName&&h.push(c)}a.conditions=h}Number.isInteger(a.from)&&(a.from=t.states[a.from].name),Number.isInteger(a.to)&&(a.to=t.states[a.to].name),n.transitions.push(a)}this._layers.push(n)}for(var u in t.parameters){var d=t.parameters[u];this._parameters[d.name]={type:d.type,value:d.value}}}return y(t,[{key:"parameters",get:function(){return Object.assign({},this._parameters)}},{key:"layers",get:function(){return this._layers}}]),t}(),Mm=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this).findParameter=function(t){return n._parameters[t]},n.consumeTrigger=function(t){n._consumedTriggers.add(t)},n._stateGraphAsset=null,n._animationAssets={},n._speed=1,n._activate=!0,n._playing=!1,n._rootBone=null,n._stateGraph=null,n._layers=[],n._layerIndices={},n._parameters={},n._targets={},n._consumedTriggers=new Set,n._normalizeWeights=!1,n}S(e,t);var i=e.prototype;return i._onStateGraphAssetChangeEvent=function(t){var e=this.animationAssets,i=this.layers.map((function(t){return t.mask}));this.removeStateGraph(),this._stateGraph=new Em(t._data),this.loadStateGraph(this._stateGraph),this.animationAssets=e,this.loadAnimationAssets(),this.layers.forEach((function(t,e){t.mask=i[e]})),this.rebind()},i.dirtifyTargets=function(){for(var t=Object.values(this._targets),e=0;e<t.length;e++)t[e].dirty=!0},i._addLayer=function(t){var e,i=t.name,n=t.states,s=t.transitions,r=t.weight,a=t.mask,o=t.blendType;e=this.rootBone?this.rootBone:this.entity;var h=this._layers.length,l=new Am(this,e,i,a,h),c=new em(l),u=new ym(c,n,s,this._activate,this,this.findParameter,this.consumeTrigger);return this._layers.push(new Cm(i,u,this,r,o)),this._layerIndices[i]=h,this._layers[h]},i.addLayer=function(t,e,i,n){var s=this.findAnimationLayer(t);if(s)return s;return this._addLayer({name:t,states:[{name:"START",speed:1}],transitions:[],weight:e,mask:i,blendType:n})},i._assignParameters=function(t){this._parameters={};for(var e=Object.keys(t.parameters),i=0;i<e.length;i++){var n=e[i];this._parameters[n]={type:t.parameters[n].type,value:t.parameters[n].value}}},i.loadStateGraph=function(t){this._stateGraph=t,this._assignParameters(t),this._layers=[];for(var e=!1,i=0;i<t.layers.length;i++){var n=t.layers[i];this._addLayer(x({},n)),n.states.some((function(t){return t.blendTree}))&&(e=!0)}e||this.setupAnimationAssets()},i.setupAnimationAssets=function(){for(var t=0;t<this._layers.length;t++)for(var e=this._layers[t],i=e.name,n=0;n<e.states.length;n++){var s=e.states[n];if(-1===Kp.indexOf(s)){var r=i+":"+s;this._animationAssets[r]||(this._animationAssets[r]={asset:null})}}this.loadAnimationAssets()},i.loadAnimationAssets=function(){for(var t=0;t<this._layers.length;t++)for(var e=this._layers[t],i=0;i<e.states.length;i++){var n=e.states[i];if(-1===Kp.indexOf(n)){var s=this._animationAssets[e.name+":"+n];if(s&&s.asset){var r=s.asset,a=this.system.app.assets.get(r);a&&(a.resource?this.onAnimationAssetLoaded(e.name,n,a):(a.once("load",function(t,e){return function(i){this.onAnimationAssetLoaded(t,e,i)}.bind(this)}.bind(this)(e.name,n)),this.system.app.assets.load(a)))}else this.findAnimationLayer(e.name).assignAnimation(n,nm.EMPTY)}}},i.onAnimationAssetLoaded=function(t,e,i){this.findAnimationLayer(t).assignAnimation(e,i.resource)},i.removeStateGraph=function(){this._stateGraph=null,this._stateGraphAsset=null,this._animationAssets={},this._layers=[],this._layerIndices={},this._parameters={},this._playing=!1,this.unbind(),this._targets={}},i.reset=function(){this._assignParameters(this._stateGraph);for(var t=0;t<this._layers.length;t++){var e=this._layers[t].playing;this._layers[t].reset(),this._layers[t].playing=e}},i.unbind=function(){var t=this;this._normalizeWeights||Object.keys(this._targets).forEach((function(e){t._targets[e].unbind()}))},i.rebind=function(){this._targets={};for(var t=0;t<this._layers.length;t++)this._layers[t].rebind()},i.findAnimationLayer=function(t){var e=this._layerIndices[t];return this._layers[e]||null},i.addAnimationState=function(t,e,i,n,s){void 0===i&&(i=1),void 0===n&&(n=!0),void 0===s&&(s="Base"),this._stateGraph||this.loadStateGraph(new Em({layers:[{name:s,states:[{name:"START",speed:1},{name:t,speed:i,loop:n,defaultState:!0}],transitions:[{from:"START",to:t}]}],parameters:{}}));var r,a=this.findAnimationLayer(s);a?a.assignAnimation(t,e,i,n):null==(r=this.addLayer(s))||r.assignAnimation(t,e,i,n)},i.assignAnimation=function(t,e,i,n,s){if(void 0===n&&(n=1),void 0===s&&(s=!0),!this._stateGraph&&-1===t.indexOf("."))return this.loadStateGraph(new Em({layers:[{name:"Base",states:[{name:"START",speed:1},{name:t,speed:n,loop:s,defaultState:!0}],transitions:[{from:"START",to:t}]}],parameters:{}})),void this.baseLayer.assignAnimation(t,e);var r=i?this.findAnimationLayer(i):this.baseLayer;r&&r.assignAnimation(t,e,n,s)},i.removeNodeAnimations=function(t,e){var i=e?this.findAnimationLayer(e):this.baseLayer;i&&i.removeNodeAnimations(t)},i.getParameterValue=function(t,e){var i=this._parameters[t];if(i&&i.type===e)return i.value},i.setParameterValue=function(t,e,i){var n=this._parameters[t];n&&n.type===e&&(n.value=i)},i.getFloat=function(t){return this.getParameterValue(t,zp)},i.setFloat=function(t,e){this.setParameterValue(t,zp,e)},i.getInteger=function(t){return this.getParameterValue(t,Np)},i.setInteger=function(t,e){"number"==typeof e&&e%1==0&&this.setParameterValue(t,Np,e)},i.getBoolean=function(t){return this.getParameterValue(t,Vp)},i.setBoolean=function(t,e){this.setParameterValue(t,Vp,!!e)},i.getTrigger=function(t){return this.getParameterValue(t,Gp)},i.setTrigger=function(t,e){void 0===e&&(e=!1),this.setParameterValue(t,Gp,!0),e&&this._consumedTriggers.add(t)},i.resetTrigger=function(t){this.setParameterValue(t,Gp,!1)},i.onBeforeRemove=function(){Number.isFinite(this._stateGraphAsset)&&this.system.app.assets.get(this._stateGraphAsset).off("change",this._onStateGraphAssetChangeEvent,this)},i.update=function(t){for(var e=this,i=0;i<this.layers.length;i++)this.layers[i].update(t*this.speed);this._consumedTriggers.forEach((function(t){e.parameters[t].value=!1})),this._consumedTriggers.clear()},i.resolveDuplicatedEntityReferenceProperties=function(t,e){t.rootBone&&e[t.rootBone.getGuid()]?this.rootBone=e[t.rootBone.getGuid()]:this.rebind()},y(e,[{key:"stateGraphAsset",get:function(){return this._stateGraphAsset},set:function(t){var e=this;if(null!==t){var i,n;if(this._stateGraphAsset)this.system.app.assets.get(this._stateGraphAsset).off("change",this._onStateGraphAssetChangeEvent,this);t instanceof Vf?(i=t.id,(n=this.system.app.assets.get(i))||(this.system.app.assets.add(t),n=this.system.app.assets.get(i))):(i=t,n=this.system.app.assets.get(i)),n&&this._stateGraphAsset!==i&&(n.resource?(this._stateGraph=n.resource,this.loadStateGraph(this._stateGraph),n.on("change",this._onStateGraphAssetChangeEvent,this)):(n.once("load",(function(t){e._stateGraph=t.resource,e.loadStateGraph(e._stateGraph)})),n.on("change",this._onStateGraphAssetChangeEvent,this),this.system.app.assets.load(n)),this._stateGraphAsset=i)}else this.removeStateGraph()}},{key:"normalizeWeights",get:function(){return this._normalizeWeights},set:function(t){this._normalizeWeights=t,this.unbind()}},{key:"animationAssets",get:function(){return this._animationAssets},set:function(t){this._animationAssets=t,this.loadAnimationAssets()}},{key:"speed",get:function(){return this._speed},set:function(t){this._speed=t}},{key:"activate",get:function(){return this._activate},set:function(t){this._activate=t}},{key:"playing",get:function(){return this._playing},set:function(t){this._playing=t}},{key:"rootBone",get:function(){return this._rootBone},set:function(t){if("string"==typeof t){var e=this.entity.root.findByGuid(t);this._rootBone=e}else this._rootBone=t instanceof ip?t:null;this.rebind()}},{key:"stateGraph",get:function(){return this._stateGraph},set:function(t){this._stateGraph=t}},{key:"layers",get:function(){return this._layers}},{key:"layerIndices",get:function(){return this._layerIndices},set:function(t){this._layerIndices=t}},{key:"parameters",get:function(){return this._parameters},set:function(t){this._parameters=t}},{key:"targets",get:function(){return this._targets},set:function(t){this._targets=t}},{key:"playable",get:function(){for(var t=0;t<this._layers.length;t++)if(!this._layers[t].playable)return!1;return!0}},{key:"baseLayer",get:function(){return this._layers.length>0?this._layers[0]:null}}]),e}(bp),Pm=function(){this.enabled=!0},Rm=["enabled"],Im=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="anim",i.ComponentType=Mm,i.DataType=Pm,i.schema=Rm,i.on("beforeremove",i.onBeforeRemove,w(i)),i.app.systems.on("animationUpdate",i.onAnimationUpdate,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){var s=this;t.prototype.initializeComponentData.call(this,e,i,Rm);var r=["animationAssets","stateGraph","layers","masks"];Object.keys(i).forEach((function(t){r.includes(t)||(e[t]=i[t])})),i.stateGraph&&(e.stateGraph=i.stateGraph,e.loadStateGraph(e.stateGraph)),i.layers?i.layers.forEach((function(t,i){t._controller.states.forEach((function(n){t._controller._states[n]._animationList.forEach((function(n){if(n.animTrack&&n.animTrack!==nm.EMPTY)e.layers[i].assignAnimation(n.name,n.animTrack);else{var r=s.app.assets.get(t._component._animationAssets[t.name+":"+n.name].asset);r&&!r.loaded&&r.once("load",(function(){e.layers[i].assignAnimation(n.name,r.resource)}))}}))}))})):i.animationAssets&&(e.animationAssets=Object.assign(e.animationAssets,i.animationAssets)),i.masks&&Object.keys(i.masks).forEach((function(t){if(e.layers[t]){var n=i.masks[t].mask,s={};Object.keys(n).forEach((function(t){s[decodeURI(t)]=n[t]})),e.layers[t].mask=s}}))},i.onAnimationUpdate=function(t){var e=this.store;for(var i in e)if(e.hasOwnProperty(i)){var n=e[i].entity.anim;n.data.enabled&&n.entity.enabled&&n.playing&&n.update(t)}},i.cloneComponent=function(t,e){var i;t.anim.rootBone&&t.anim.rootBone!==t||(i={},t.anim.layers.forEach((function(t,n){if(t.mask){var s={};Object.keys(t.mask).forEach((function(i){var n=i.split("/");n.shift();var r=[e.name].concat(n).join("/");s[r]=t.mask[i]})),i[n]={mask:s}}})));var n={stateGraphAsset:t.anim.stateGraphAsset,animationAssets:t.anim.animationAssets,speed:t.anim.speed,activate:t.anim.activate,playing:t.anim.playing,rootBone:t.anim.rootBone,stateGraph:t.anim.stateGraph,layers:t.anim.layers,layerIndices:t.anim.layerIndices,parameters:t.anim.parameters,normalizeWeights:t.anim.normalizeWeights,masks:i};return this.addComponent(e,n)},i.onBeforeRemove=function(t,e){e.onBeforeRemove()},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("animationUpdate",this.onAnimationUpdate,this)},e}(wp);bp._buildAccessors(Mm.prototype,Rm);var Lm=function(t){function e(e,i){return t.call(this,e,i)||this}S(e,t);var i=e.prototype;return i.setCurrentListener=function(){if(this.enabled&&this.entity.audiolistener&&this.entity.enabled){this.system.current=this.entity;var t=this.system.current.getPosition();this.system.manager.listener.setPosition(t)}},i.onEnable=function(){this.setCurrentListener()},i.onDisable=function(){this.system.current===this.entity&&(this.system.current=null)},e}(bp),Dm=function(){this.enabled=!0},Om=["enabled"],km=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="audiolistener",i.ComponentType=Lm,i.DataType=Dm,i.schema=Om,i.manager=e.soundManager,i.current=null,i.app.systems.on("update",i.onUpdate,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){n=["enabled"],t.prototype.initializeComponentData.call(this,e,i,n)},i.onUpdate=function(t){if(this.current){var e=this.current.getPosition();this.manager.listener.setPosition(e);var i=this.current.getWorldTransform();this.manager.listener.setOrientation(i)}},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},e}(wp);bp._buildAccessors(Lm.prototype,Om);var Fm=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this).on("set_assets",n.onSetAssets,w(n)),n.on("set_loop",n.onSetLoop,w(n)),n.on("set_volume",n.onSetVolume,w(n)),n.on("set_pitch",n.onSetPitch,w(n)),n.on("set_minDistance",n.onSetMinDistance,w(n)),n.on("set_maxDistance",n.onSetMaxDistance,w(n)),n.on("set_rollOffFactor",n.onSetRollOffFactor,w(n)),n.on("set_distanceModel",n.onSetDistanceModel,w(n)),n.on("set_3d",n.onSet3d,w(n)),n}S(e,t);var i=e.prototype;return i.play=function(t){if(this.enabled&&this.entity.enabled){var e;this.channel&&this.stop();var i=this.data;if(i.sources[t])if(i["3d"]){var n=this.entity.getPosition();e=this.system.manager.playSound3d(i.sources[t],n,i),i.currentSource=t,i.channel=e}else e=this.system.manager.playSound(i.sources[t],i),i.currentSource=t,i.channel=e}},i.pause=function(){this.channel&&this.channel.pause()},i.unpause=function(){this.channel&&this.channel.paused&&this.channel.unpause()},i.stop=function(){this.channel&&(this.channel.stop(),this.channel=null)},i.onSetAssets=function(t,e,i){var n=[],s=i.length;if(e&&e.length)for(var r=0;r<e.length;r++)if(e[r]){var a=this.system.app.assets.get(e[r]);a&&(a.off("change",this.onAssetChanged,this),a.off("remove",this.onAssetRemoved,this),this.currentSource===a.name&&this.stop())}if(s)for(var o=0;o<s;o++)e.indexOf(i[o])<0&&(i[o]instanceof Vf?n.push(i[o].id):n.push(i[o]));!this.system._inTools&&n.length&&this.loadAudioSourceAssets(n)},i.onAssetChanged=function(t,e,i,n){"resource"===e&&(this.data.sources&&(this.data.sources[t.name]=i,this.data.currentSource===t.name&&this.channel&&(this.channel.paused?(this.play(t.name),this.pause()):this.play(t.name))))},i.onAssetRemoved=function(t){t.off("remove",this.onAssetRemoved,this),this.data.sources[t.name]&&(delete this.data.sources[t.name],this.data.currentSource===t.name&&(this.stop(),this.data.currentSource=null))},i.onSetLoop=function(t,e,i){e!==i&&this.channel&&this.channel.setLoop(i)},i.onSetVolume=function(t,e,i){e!==i&&this.channel&&this.channel.setVolume(i)},i.onSetPitch=function(t,e,i){e!==i&&this.channel&&this.channel.setPitch(i)},i.onSetMaxDistance=function(t,e,i){e!==i&&this.channel instanceof ya&&this.channel.setMaxDistance(i)},i.onSetMinDistance=function(t,e,i){e!==i&&this.channel instanceof ya&&this.channel.setMinDistance(i)},i.onSetRollOffFactor=function(t,e,i){e!==i&&this.channel instanceof ya&&this.channel.setRollOffFactor(i)},i.onSetDistanceModel=function(t,e,i){e!==i&&this.channel instanceof ya&&this.channel.setDistanceModel(i)},i.onSet3d=function(t,e,i){if(e!==i&&this.system.initialized&&this.currentSource){var n=!1,s=!1;this.channel&&(n=this.channel.paused,s=this.channel.suspended),this.play(this.currentSource),this.channel&&(this.channel.paused=n,this.channel.suspended=s)}},i.onEnable=function(){var t=this.data.assets;if(t)for(var e=this.system.app.assets,i=0,n=t.length;i<n;i++){var s=t[i];s instanceof Vf||(s=e.get(s)),s&&!s.resource&&e.load(s)}this.system.initialized&&(this.data.activate&&!this.channel?this.play(this.currentSource):this.unpause())},i.onDisable=function(){this.pause()},i.loadAudioSourceAssets=function(t){var e=this,i=t.map((function(t){return e.system.app.assets.get(t)})),n={},s=null,r=i.length,a=function(t){r--},o=function(){e.data.sources=n,e.data.currentSource=s,e.enabled&&e.activate&&s&&e.onEnable()};i.forEach((function(i,h){i?(s=s||i.name,i.off("change",e.onAssetChanged,e),i.on("change",e.onAssetChanged,e),i.off("remove",e.onAssetRemoved,e),i.on("remove",e.onAssetRemoved,e),i.off("error",a,e),i.on("error",a,e),i.ready((function(t){n[t.name]=t.resource,0===--r&&o()})),!i.resource&&e.enabled&&e.entity.enabled&&e.system.app.assets.load(i)):(0===--r&&o(),e.system.app.assets.on("add:"+t[h],(function(t){t.ready((function(t){e.data.sources[t.name]=t.resource})),t.resource||e.system.app.assets.load(t)})))}))},e}(bp),Bm=function(){this.enabled=!0,this.assets=[],this.activate=!0,this.volume=1,this.pitch=1,this.loop=!1,this["3d"]=!0,this.minDistance=1,this.maxDistance=1e4,this.rollOffFactor=1,this.distanceModel=ie,this.paused=!0,this.sources={},this.currentSource=null,this.channel=null},Um=["enabled","assets","volume","pitch","loop","activate","3d","minDistance","maxDistance","rollOffFactor","distanceModel","sources","currentSource","channel"],Nm=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="audiosource",i.ComponentType=Fm,i.DataType=Bm,i.schema=Um,i.manager=e.soundManager,i.initialized=!1,i.app.systems.on("initialize",i.onInitialize,w(i)),i.app.systems.on("update",i.onUpdate,w(i)),i.on("remove",i.onRemove,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){n=["activate","volume","pitch","loop","3d","minDistance","maxDistance","rollOffFactor","distanceModel","enabled","assets"],t.prototype.initializeComponentData.call(this,e,i,n),e.paused=!(e.enabled&&e.activate)},i.onInitialize=function(t){t.audiosource&&t.enabled&&t.audiosource.enabled&&t.audiosource.activate&&t.audiosource.play(t.audiosource.currentSource);for(var e=t._children,i=0,n=e.length;i<n;i++)e[i]instanceof ip&&this.onInitialize(e[i]);this.initialized=!0},i.onUpdate=function(t){var e=this.store;for(var i in e)if(e.hasOwnProperty(i)){var n=e[i],s=n.entity,r=n.data;if(r.enabled&&s.enabled&&r.channel instanceof ya){var a=s.getPosition();r.channel.setPosition(a)}}},i.onRemove=function(t,e){e.channel&&(e.channel.stop(),e.channel=null)},i.setVolume=function(t){this.manager.setVolume(t)},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("initialize",this.onInitialize,this),this.app.systems.off("update",this.onUpdate,this)},e}(wp);bp._buildAccessors(Fm.prototype,Um);var zm=function(t){function e(e,i,n){var s;if(s=t.call(this)||this,!(e&&e instanceof bp))throw new Error("The parentComponent argument is required and must be a Component");if(!i||"string"!=typeof i)throw new Error("The propertyName argument is required and must be a string");if(n&&"object"!=typeof n)throw new Error("If provided, the eventConfig argument must be an object");return s._parentComponent=e,s._entityPropertyName=i,s._entity=null,s._app=e.system.app,s._configureEventListeners(n||{},{"entity#destroy":s._onEntityDestroy}),s._toggleLifecycleListeners("on"),s}S(e,t);var i=e.prototype;return i._configureEventListeners=function(t,e){var i=this._parseEventListenerConfig(t,"external",this._parentComponent),n=this._parseEventListenerConfig(e,"internal",this);this._eventListenerConfigs=i.concat(n),this._listenerStatusFlags={},this._gainListeners={},this._loseListeners={}},i._parseEventListenerConfig=function(t,e,i){return Object.keys(t).map((function(n,s){var r=n.split("#"),a=r[0],o=r[1],h=t[n];if(2!==r.length||"string"!=typeof a||0===a.length||"string"!=typeof o||0===o.length)throw new Error("Invalid event listener description: `"+n+"`");if("function"!=typeof h)throw new Error("Invalid or missing callback for event listener `"+n+"`");return{id:e+"_"+s+"_"+n,sourceName:a,eventName:o,callback:h,scope:i}}),this)},i._toggleLifecycleListeners=function(t){this._parentComponent[t]("set_"+this._entityPropertyName,this._onSetEntity,this),this._parentComponent.system[t]("beforeremove",this._onParentComponentRemove,this),this._app.systems[t]("postPostInitialize",this._updateEntityReference,this),this._app[t]("tools:sceneloaded",this._onSceneLoaded,this);for(var e=[],i=0;i<this._eventListenerConfigs.length;++i){var n=this._eventListenerConfigs[i],s=this._app.systems[n.sourceName];s&&(-1===e.indexOf(s)&&e.push(s),s&&"gain"===n.eventName&&(this._gainListeners[n.sourceName]=n),s&&"lose"===n.eventName&&(this._loseListeners[n.sourceName]=n))}for(var r=0;r<e.length;++r)e[r][t]("add",this._onComponentAdd,this),e[r][t]("beforeremove",this._onComponentRemove,this)},i._onSetEntity=function(t,e,i){if(i instanceof ip)this._updateEntityReference();else{if(null!=i&&"string"!=typeof i)return void console.warn("Entity field `"+this._entityPropertyName+"` was set to unexpected type '"+typeof i+"'");e!==i&&this._updateEntityReference()}},i.onParentComponentEnable=function(){this._entity||this._updateEntityReference()},i._onSceneLoaded=function(){this._updateEntityReference()},i._updateEntityReference=function(){var t,e=this._parentComponent.data[this._entityPropertyName];if(e instanceof ip)e=(t=e).getGuid(),this._parentComponent.data[this._entityPropertyName]=e;else{var i=this._parentComponent.system.app.root;t=this._parentComponent.entity.isDescendantOf(i)&&e?i.findByGuid(e):null}this._entity!==t&&(this._entity&&this._onBeforeEntityChange(),this._entity=t,this._entity&&this._onAfterEntityChange(),this.fire("set:entity",this._entity))},i._onBeforeEntityChange=function(){this._toggleEntityListeners("off"),this._callAllGainOrLoseListeners(this._loseListeners)},i._onAfterEntityChange=function(){this._toggleEntityListeners("on"),this._callAllGainOrLoseListeners(this._gainListeners)},i._onComponentAdd=function(t,e){var i=e.system.id;t===this._entity&&(this._callGainOrLoseListener(i,this._gainListeners),this._toggleComponentListeners("on",i))},i._onComponentRemove=function(t,e){var i=e.system.id;t===this._entity&&(this._callGainOrLoseListener(i,this._loseListeners),this._toggleComponentListeners("off",i,!0))},i._callAllGainOrLoseListeners=function(t){for(var e in this._entity.c)this._callGainOrLoseListener(e,t)},i._callGainOrLoseListener=function(t,e){if(this._entity.c.hasOwnProperty(t)&&e[t]){var i=e[t];i.callback.call(i.scope)}},i._toggleEntityListeners=function(t,e){if(this._entity)for(var i=0;i<this._eventListenerConfigs.length;++i)this._safeToggleListener(t,this._eventListenerConfigs[i],e)},i._toggleComponentListeners=function(t,e,i){for(var n=0;n<this._eventListenerConfigs.length;++n){var s=this._eventListenerConfigs[n];s.sourceName===e&&this._safeToggleListener(t,s,i)}},i._safeToggleListener=function(t,e,i){var n="on"===t;if(!n||!this._listenerStatusFlags[e.id]){var s=this._getEventSource(e.sourceName,i);s&&(s[t](e.eventName,e.callback,e.scope),this._listenerStatusFlags[e.id]=n)}},i._getEventSource=function(t,e){if("entity"===t)return this._entity;var i=this._entity[t];return i||(e||console.warn("Entity has no component with name "+t),null)},i._onEntityDestroy=function(t){this._entity===t&&(this._toggleEntityListeners("off",!0),this._entity=null)},i._onParentComponentRemove=function(t,e){e===this._parentComponent&&(this._toggleLifecycleListeners("off"),this._toggleEntityListeners("off",!0))},i.hasComponent=function(t){return!(!this._entity||!this._entity.c)&&!!this._entity.c[t]},y(e,[{key:"entity",get:function(){return this._entity}}]),e}(P),Vm="group",Gm="image",Hm="text",Wm="stretch",Xm="contain",jm="cover",qm="DEFAULT",Ym="HOVER",Km="PRESSED",Zm="INACTIVE",Qm={};Qm[qm]="_defaultTint",Qm[Ym]="hoverTint",Qm[Km]="pressedTint",Qm[Zm]="inactiveTint";var $m={};$m[qm]="_defaultSpriteAsset",$m[Ym]="hoverSpriteAsset",$m[Km]="pressedSpriteAsset",$m[Zm]="inactiveSpriteAsset";var Jm={};Jm[qm]="_defaultSpriteFrame",Jm[Ym]="hoverSpriteFrame",Jm[Km]="pressedSpriteFrame",Jm[Zm]="inactiveSpriteFrame";var t_=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._visualState=qm,n._isHovering=!1,n._hoveringCounter=0,n._isPressed=!1,n._defaultTint=new vt(1,1,1,1),n._defaultSpriteAsset=null,n._defaultSpriteFrame=0,n._imageReference=new zm(w(n),"imageEntity",{"element#gain":n._onImageElementGain,"element#lose":n._onImageElementLose,"element#set:color":n._onSetColor,"element#set:opacity":n._onSetOpacity,"element#set:spriteAsset":n._onSetSpriteAsset,"element#set:spriteFrame":n._onSetSpriteFrame}),n._toggleLifecycleListeners("on",e),n}S(e,t);var i=e.prototype;return i._toggleLifecycleListeners=function(t,e){this[t]("set_active",this._onSetActive,this),this[t]("set_transitionMode",this._onSetTransitionMode,this),this[t]("set_hoverTint",this._onSetTransitionValue,this),this[t]("set_pressedTint",this._onSetTransitionValue,this),this[t]("set_inactiveTint",this._onSetTransitionValue,this),this[t]("set_hoverSpriteAsset",this._onSetTransitionValue,this),this[t]("set_hoverSpriteFrame",this._onSetTransitionValue,this),this[t]("set_pressedSpriteAsset",this._onSetTransitionValue,this),this[t]("set_pressedSpriteFrame",this._onSetTransitionValue,this),this[t]("set_inactiveSpriteAsset",this._onSetTransitionValue,this),this[t]("set_inactiveSpriteFrame",this._onSetTransitionValue,this),e.app.systems.element[t]("add",this._onElementComponentAdd,this),e.app.systems.element[t]("beforeremove",this._onElementComponentRemove,this)},i._onSetActive=function(t,e,i){e!==i&&this._updateVisualState()},i._onSetTransitionMode=function(t,e,i){e!==i&&(this._cancelTween(),this._resetToDefaultVisualState(e),this._forceReapplyVisualState())},i._onSetTransitionValue=function(t,e,i){e!==i&&this._forceReapplyVisualState()},i._onElementComponentRemove=function(t){this.entity===t&&this._toggleHitElementListeners("off")},i._onElementComponentAdd=function(t){this.entity===t&&this._toggleHitElementListeners("on")},i._onImageElementLose=function(){this._cancelTween(),this._resetToDefaultVisualState(this.transitionMode)},i._onImageElementGain=function(){this._storeDefaultVisualState(),this._forceReapplyVisualState()},i._toggleHitElementListeners=function(t){if(this.entity.element){var e="on"===t;if(e&&this._hasHitElementListeners)return;this.entity.element[t]("mouseenter",this._onMouseEnter,this),this.entity.element[t]("mouseleave",this._onMouseLeave,this),this.entity.element[t]("mousedown",this._onMouseDown,this),this.entity.element[t]("mouseup",this._onMouseUp,this),this.entity.element[t]("touchstart",this._onTouchStart,this),this.entity.element[t]("touchend",this._onTouchEnd,this),this.entity.element[t]("touchleave",this._onTouchLeave,this),this.entity.element[t]("touchcancel",this._onTouchCancel,this),this.entity.element[t]("selectstart",this._onSelectStart,this),this.entity.element[t]("selectend",this._onSelectEnd,this),this.entity.element[t]("selectenter",this._onSelectEnter,this),this.entity.element[t]("selectleave",this._onSelectLeave,this),this.entity.element[t]("click",this._onClick,this),this._hasHitElementListeners=e}},i._storeDefaultVisualState=function(){if(this._imageReference.hasComponent("element")){var t=this._imageReference.entity.element;t.type!==Vm&&(this._storeDefaultColor(t.color),this._storeDefaultOpacity(t.opacity),this._storeDefaultSpriteAsset(t.spriteAsset),this._storeDefaultSpriteFrame(t.spriteFrame))}},i._storeDefaultColor=function(t){this._defaultTint.r=t.r,this._defaultTint.g=t.g,this._defaultTint.b=t.b},i._storeDefaultOpacity=function(t){this._defaultTint.a=t},i._storeDefaultSpriteAsset=function(t){this._defaultSpriteAsset=t},i._storeDefaultSpriteFrame=function(t){this._defaultSpriteFrame=t},i._onSetColor=function(t){this._isApplyingTint||(this._storeDefaultColor(t),this._forceReapplyVisualState())},i._onSetOpacity=function(t){this._isApplyingTint||(this._storeDefaultOpacity(t),this._forceReapplyVisualState())},i._onSetSpriteAsset=function(t){this._isApplyingSprite||(this._storeDefaultSpriteAsset(t),this._forceReapplyVisualState())},i._onSetSpriteFrame=function(t){this._isApplyingSprite||(this._storeDefaultSpriteFrame(t),this._forceReapplyVisualState())},i._onMouseEnter=function(t){this._isHovering=!0,this._updateVisualState(),this._fireIfActive("mouseenter",t)},i._onMouseLeave=function(t){this._isHovering=!1,this._isPressed=!1,this._updateVisualState(),this._fireIfActive("mouseleave",t)},i._onMouseDown=function(t){this._isPressed=!0,this._updateVisualState(),this._fireIfActive("mousedown",t)},i._onMouseUp=function(t){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("mouseup",t)},i._onTouchStart=function(t){this._isPressed=!0,this._updateVisualState(),this._fireIfActive("touchstart",t)},i._onTouchEnd=function(t){t.event.preventDefault(),this._isPressed=!1,this._updateVisualState(),this._fireIfActive("touchend",t)},i._onTouchLeave=function(t){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("touchleave",t)},i._onTouchCancel=function(t){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("touchcancel",t)},i._onSelectStart=function(t){this._isPressed=!0,this._updateVisualState(),this._fireIfActive("selectstart",t)},i._onSelectEnd=function(t){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("selectend",t)},i._onSelectEnter=function(t){this._hoveringCounter++,1===this._hoveringCounter&&(this._isHovering=!0,this._updateVisualState()),this._fireIfActive("selectenter",t)},i._onSelectLeave=function(t){this._hoveringCounter--,0===this._hoveringCounter&&(this._isHovering=!1,this._isPressed=!1,this._updateVisualState()),this._fireIfActive("selectleave",t)},i._onClick=function(t){this._fireIfActive("click",t)},i._fireIfActive=function(t,e){this.data.active&&this.fire(t,e)},i._updateVisualState=function(t){var e=this._visualState,i=this._determineVisualState();if((e!==i||t)&&this.enabled)switch(this._visualState=i,e===Ym&&this._fireIfActive("hoverend"),e===Km&&this._fireIfActive("pressedend"),i===Ym&&this._fireIfActive("hoverstart"),i===Km&&this._fireIfActive("pressedstart"),this.transitionMode){case 0:var n=this[Qm[this._visualState]];this._applyTint(n);break;case 1:var s=$m[this._visualState],r=Jm[this._visualState],a=this[s],o=this[r];this._applySprite(a,o)}},i._forceReapplyVisualState=function(){this._updateVisualState(!0)},i._resetToDefaultVisualState=function(t){if(this._imageReference.hasComponent("element"))switch(t){case 0:this._cancelTween(),this._applyTintImmediately(this._defaultTint);break;case 1:this._applySprite(this._defaultSpriteAsset,this._defaultSpriteFrame)}},i._determineVisualState=function(){return this.active?this._isPressed?Km:this._isHovering?Ym:qm:Zm},i._applySprite=function(t,e){e=e||0,this._imageReference.hasComponent("element")&&(this._isApplyingSprite=!0,this._imageReference.entity.element.spriteAsset!==t&&(this._imageReference.entity.element.spriteAsset=t),this._imageReference.entity.element.spriteFrame!==e&&(this._imageReference.entity.element.spriteFrame=e),this._isApplyingSprite=!1)},i._applyTint=function(t){this._cancelTween(),0===this.fadeDuration?this._applyTintImmediately(t):this._applyTintWithTween(t)},i._applyTintImmediately=function(t){if(t&&this._imageReference.hasComponent("element")&&this._imageReference.entity.element.type!==Vm){var e=e_(t);this._isApplyingTint=!0,e.equals(this._imageReference.entity.element.color)||(this._imageReference.entity.element.color=e),this._imageReference.entity.element.opacity!==t.a&&(this._imageReference.entity.element.opacity=t.a),this._isApplyingTint=!1}},i._applyTintWithTween=function(t){if(t&&this._imageReference.hasComponent("element")&&this._imageReference.entity.element.type!==Vm){var e=e_(t),i=this._imageReference.entity.element.color,n=this._imageReference.entity.element.opacity;e.equals(i)&&t.a===n||(this._tweenInfo={startTime:dt(),from:new vt(i.r,i.g,i.b,n),to:t.clone(),lerpColor:new vt})}},i._updateTintTween=function(){var t=dt()-this._tweenInfo.startTime,e=0===this.fadeDuration?1:t/this.fadeDuration;if(e=_t.clamp(e,0,1),Math.abs(e-1)>1e-5){var i=this._tweenInfo.lerpColor;i.lerp(this._tweenInfo.from,this._tweenInfo.to,e),this._applyTintImmediately(new vt(i.r,i.g,i.b,i.a))}else this._applyTintImmediately(this._tweenInfo.to),this._cancelTween()},i._cancelTween=function(){delete this._tweenInfo},i.onUpdate=function(){this._tweenInfo&&this._updateTintTween()},i.onEnable=function(){this._isHovering=!1,this._hoveringCounter=0,this._isPressed=!1,this._imageReference.onParentComponentEnable(),this._toggleHitElementListeners("on"),this._forceReapplyVisualState()},i.onDisable=function(){this._toggleHitElementListeners("off"),this._resetToDefaultVisualState(this.transitionMode)},i.onRemove=function(){this._toggleLifecycleListeners("off",this.system),this.onDisable()},e}(bp);function e_(t){return new vt(t.r,t.g,t.b)}var i_=function(){this.enabled=!0,this.active=!0,this.imageEntity=null,this.hitPadding=new Pt,this.transitionMode=0,this.hoverTint=new vt(.75,.75,.75),this.pressedTint=new vt(.5,.5,.5),this.inactiveTint=new vt(.25,.25,.25),this.fadeDuration=0,this.hoverSpriteAsset=null,this.hoverSpriteFrame=0,this.pressedSpriteAsset=null,this.pressedSpriteFrame=0,this.inactiveSpriteAsset=null,this.inactiveSpriteFrame=0},n_=["enabled","active",{name:"imageEntity",type:"entity"},{name:"hitPadding",type:"vec4"},"transitionMode",{name:"hoverTint",type:"rgba"},{name:"pressedTint",type:"rgba"},{name:"inactiveTint",type:"rgba"},"fadeDuration","hoverSpriteAsset","hoverSpriteFrame","pressedSpriteAsset","pressedSpriteFrame","inactiveSpriteAsset","inactiveSpriteFrame"],s_=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="button",i.ComponentType=t_,i.DataType=i_,i.schema=n_,i.on("beforeremove",i._onRemoveComponent,w(i)),i.app.systems.on("update",i.onUpdate,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){t.prototype.initializeComponentData.call(this,e,i,n_)},i.onUpdate=function(t){var e=this.store;for(var i in e){var n=e[i].entity,s=n.button;s.enabled&&n.enabled&&s.onUpdate()}},i._onRemoveComponent=function(t,e){e.onRemove()},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},e}(wp);bp._buildAccessors(t_.prototype,n_);var r_,a_,o_,h_=new wt,l_=new Bt,c_=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._compoundParent=null,n._hasOffset=!1,n.entity.on("insert",n._onInsert,w(n)),n.on("set_type",n.onSetType,w(n)),n.on("set_halfExtents",n.onSetHalfExtents,w(n)),n.on("set_linearOffset",n.onSetOffset,w(n)),n.on("set_angularOffset",n.onSetOffset,w(n)),n.on("set_radius",n.onSetRadius,w(n)),n.on("set_height",n.onSetHeight,w(n)),n.on("set_axis",n.onSetAxis,w(n)),n.on("set_asset",n.onSetAsset,w(n)),n.on("set_renderAsset",n.onSetRenderAsset,w(n)),n.on("set_model",n.onSetModel,w(n)),n.on("set_render",n.onSetRender,w(n)),n}S(e,t);var i=e.prototype;return i.onSetType=function(t,e,i){e!==i&&this.system.changeType(this,e,i)},i.onSetHalfExtents=function(t,e,i){var n=this.data.type;this.data.initialized&&"box"===n&&this.system.recreatePhysicalShapes(this)},i.onSetOffset=function(t,e,i){this._hasOffset=!this.data.linearOffset.equals(wt.ZERO)||!this.data.angularOffset.equals(Bt.IDENTITY),this.data.initialized&&this.system.recreatePhysicalShapes(this)},i.onSetRadius=function(t,e,i){var n=this.data.type;!this.data.initialized||"sphere"!==n&&"capsule"!==n&&"cylinder"!==n&&"cone"!==n||this.system.recreatePhysicalShapes(this)},i.onSetHeight=function(t,e,i){var n=this.data.type;!this.data.initialized||"capsule"!==n&&"cylinder"!==n&&"cone"!==n||this.system.recreatePhysicalShapes(this)},i.onSetAxis=function(t,e,i){var n=this.data.type;!this.data.initialized||"capsule"!==n&&"cylinder"!==n&&"cone"!==n||this.system.recreatePhysicalShapes(this)},i.onSetAsset=function(t,e,i){var n=this.system.app.assets;if(e){var s=n.get(e);s&&s.off("remove",this.onAssetRemoved,this)}if(i){i instanceof Vf&&(this.data.asset=i.id);var r=n.get(this.data.asset);r&&(r.off("remove",this.onAssetRemoved,this),r.on("remove",this.onAssetRemoved,this))}this.data.initialized&&"mesh"===this.data.type&&(i||(this.data.model=null),this.system.recreatePhysicalShapes(this))},i.onSetRenderAsset=function(t,e,i){var n=this.system.app.assets;if(e){var s=n.get(e);s&&s.off("remove",this.onRenderAssetRemoved,this)}if(i){i instanceof Vf&&(this.data.renderAsset=i.id);var r=n.get(this.data.renderAsset);r&&(r.off("remove",this.onRenderAssetRemoved,this),r.on("remove",this.onRenderAssetRemoved,this))}this.data.initialized&&"mesh"===this.data.type&&(i||(this.data.render=null),this.system.recreatePhysicalShapes(this))},i.onSetModel=function(t,e,i){this.data.initialized&&"mesh"===this.data.type&&this.system.implementations.mesh.doRecreatePhysicalShape(this)},i.onSetRender=function(t,e,i){this.onSetModel(t,e,i)},i.onAssetRemoved=function(t){t.off("remove",this.onAssetRemoved,this),this.data.asset===t.id&&(this.asset=null)},i.onRenderAssetRemoved=function(t){t.off("remove",this.onRenderAssetRemoved,this),this.data.renderAsset===t.id&&(this.renderAsset=null)},i._getCompoundChildShapeIndex=function(t){for(var e=this.data.shape,i=e.getNumChildShapes(),n=0;n<i;n++){if(e.getChildShape(n).ptr===t.ptr)return n}return null},i._onInsert=function(t){if("undefined"!=typeof Ammo)if(this._compoundParent)this.system.recreatePhysicalShapes(this);else if(!this.entity.rigidbody)for(var e=this.entity.parent;e;){if(e.collision&&"compound"===e.collision.type){0===e.collision.shape.getNumChildShapes()?this.system.recreatePhysicalShapes(e.collision):this.system.recreatePhysicalShapes(this);break}e=e.parent}},i._updateCompound=function(){var t=this.entity;if(t._dirtyWorld){for(var e=t._dirtyLocal,i=t;i&&!e&&(!i.collision||i.collision!==this._compoundParent);)i._dirtyLocal&&(e=!0),i=i.parent;if(e){t.forEach(this.system.implementations.compound._updateEachDescendantTransform,t);var n=this._compoundParent.entity.rigidbody;n&&n.activate()}}},i.getShapePosition=function(){var t=this.entity.getPosition();if(this._hasOffset){var e=this.entity.getRotation(),i=this.data.linearOffset;return l_.copy(e).transformVector(i,h_),h_.add(t)}return t},i.getShapeRotation=function(){var t=this.entity.getRotation();return this._hasOffset?l_.copy(t).mul(this.data.angularOffset):t},i.onEnable=function(){if("mesh"===this.data.type&&(this.data.asset||this.data.renderAsset)&&this.data.initialized){var t=this.system.app.assets.get(this.data.asset||this.data.renderAsset);if(t&&(!t.resource||!this.data.shape))return void this.system.recreatePhysicalShapes(this)}if(this.entity.rigidbody)this.entity.rigidbody.enabled&&this.entity.rigidbody.enableSimulation();else if(this._compoundParent&&this!==this._compoundParent)if(0===this._compoundParent.shape.getNumChildShapes())this.system.recreatePhysicalShapes(this._compoundParent);else{var e=this.system._getNodeTransform(this.entity,this._compoundParent.entity);this._compoundParent.shape.addChildShape(e,this.data.shape),Ammo.destroy(e),this._compoundParent.entity.rigidbody&&this._compoundParent.entity.rigidbody.activate()}else this.entity.trigger&&this.entity.trigger.enable()},i.onDisable=function(){this.entity.rigidbody?this.entity.rigidbody.disableSimulation():this._compoundParent&&this!==this._compoundParent?this._compoundParent.entity._destroying||(this.system._removeCompoundChild(this._compoundParent,this.data.shape),this._compoundParent.entity.rigidbody&&this._compoundParent.entity.rigidbody.activate()):this.entity.trigger&&this.entity.trigger.disable()},i.onBeforeRemove=function(){this.asset&&(this.asset=null),this.renderAsset&&(this.renderAsset=null),this.entity.off("insert",this._onInsert,this),this.off()},e}(bp),u_=function(){this.enabled=!0,this.type="box",this.halfExtents=new wt(.5,.5,.5),this.linearOffset=new wt,this.angularOffset=new Bt,this.radius=.5,this.axis=1,this.height=2,this.asset=null,this.renderAsset=null,this.shape=null,this.model=null,this.render=null,this.initialized=!1},d_="static",f_="dynamic",p_="kinematic",m_=65535,__=65533,v_=function(){function t(t,e,i){this.entity=e.entity,this.component=e,this.app=t,"undefined"==typeof Ammo||r_||(r_=new Ammo.btVector3,a_=new Ammo.btQuaternion,o_=new Ammo.btTransform),this.initialize(i)}var e=t.prototype;return e.initialize=function(t){var e=this.entity,i=t.shape;if(i&&"undefined"!=typeof Ammo){e.trigger&&e.trigger.destroy();var n=this.component;if(n){var s=n.getShapePosition(),r=n.getShapeRotation();r_.setValue(s.x,s.y,s.z),a_.setValue(r.x,r.y,r.z,r.w)}else{var a=e.getPosition(),o=e.getRotation();r_.setValue(a.x,a.y,a.z),a_.setValue(o.x,o.y,o.z,o.w)}o_.setOrigin(r_),o_.setRotation(a_);var h=this.app.systems.rigidbody.createBody(1,i,o_);h.setRestitution(0),h.setFriction(0),h.setDamping(0,0),r_.setValue(0,0,0),h.setLinearFactor(r_),h.setAngularFactor(r_),h.setCollisionFlags(4|h.getCollisionFlags()),h.entity=e,this.body=h,this.component.enabled&&e.enabled&&this.enable()}},e.destroy=function(){var t=this.body;t&&(this.disable(),this.app.systems.rigidbody.destroyBody(t))},e._getEntityTransform=function(t){var e=this.component;if(e){var i=e.getShapePosition(),n=e.getShapeRotation();r_.setValue(i.x,i.y,i.z),a_.setValue(n.x,n.y,n.z,n.w)}else{var s=this.entity.getPosition(),r=this.entity.getRotation();r_.setValue(s.x,s.y,s.z),a_.setValue(r.x,r.y,r.z,r.w)}t.setOrigin(r_),t.setRotation(a_)},e.updateTransform=function(){this._getEntityTransform(o_);var t=this.body;t.setWorldTransform(o_),t.activate()},e.enable=function(){var t=this.body;if(t){var e=this.app.systems;e.rigidbody.addBody(t,16,65517),e.rigidbody._triggers.push(this),t.forceActivationState(1),this.updateTransform()}},e.disable=function(){var t=this.body;if(t){var e=this.app.systems,i=e.rigidbody._triggers.indexOf(this);i>-1&&e.rigidbody._triggers.splice(i,1),e.rigidbody.removeBody(t),t.forceActivationState(5)}},t}(),g_=new Ft,y_=new wt,x_=new wt,S_=new Bt,b_=new hh,w_=["enabled","type","halfExtents","linearOffset","angularOffset","radius","axis","height","asset","renderAsset","shape","model","render"],T_=function(){function t(t){this.system=t}var e=t.prototype;return e.beforeInitialize=function(t,e){e.shape=null,e.model=new Gu,e.model.graph=new hh},e.afterInitialize=function(t,e){this.recreatePhysicalShapes(t),t.data.initialized=!0},e.reset=function(t,e){this.beforeInitialize(t,e),this.afterInitialize(t,e)},e.recreatePhysicalShapes=function(t){var e=t.entity,i=t.data;if("undefined"!=typeof Ammo){e.trigger&&(e.trigger.destroy(),delete e.trigger),i.shape&&(t._compoundParent&&(this.system._removeCompoundChild(t._compoundParent,i.shape),t._compoundParent.entity.rigidbody&&t._compoundParent.entity.rigidbody.activate()),this.destroyShape(i)),i.shape=this.createPhysicalShape(t.entity,i);var n=!t._compoundParent;if("compound"!==i.type||t._compoundParent&&t!==t._compoundParent){if("compound"!==i.type&&(t._compoundParent&&t===t._compoundParent&&e.forEach(this.system.implementations.compound._updateEachDescendant,t),!t.rigidbody)){t._compoundParent=null;for(var s=e.parent;s;){if(s.collision&&"compound"===s.collision.type){t._compoundParent=s.collision;break}s=s.parent}}}else t._compoundParent=t,e.forEach(this._addEachDescendant,t);t._compoundParent&&t!==t._compoundParent&&(n&&0===t._compoundParent.shape.getNumChildShapes()?this.system.recreatePhysicalShapes(t._compoundParent):(this.system.updateCompoundChildTransform(e),t._compoundParent.entity.rigidbody&&t._compoundParent.entity.rigidbody.activate())),e.rigidbody?(e.rigidbody.disableSimulation(),e.rigidbody.createBody(),e.enabled&&e.rigidbody.enabled&&e.rigidbody.enableSimulation()):t._compoundParent||(e.trigger?e.trigger.initialize(i):e.trigger=new v_(this.system.app,t,i))}},e.createPhysicalShape=function(t,e){},e.updateTransform=function(t,e,i,n){t.entity.trigger&&t.entity.trigger.updateTransform()},e.destroyShape=function(t){t.shape&&(Ammo.destroy(t.shape),t.shape=null)},e.beforeRemove=function(t,e){e.data.shape&&(e._compoundParent&&!e._compoundParent.entity._destroying&&(this.system._removeCompoundChild(e._compoundParent,e.data.shape),e._compoundParent.entity.rigidbody&&e._compoundParent.entity.rigidbody.activate()),e._compoundParent=null,this.destroyShape(e.data))},e.remove=function(t,e){t.rigidbody&&t.rigidbody.body&&t.rigidbody.disableSimulation(),t.trigger&&(t.trigger.destroy(),delete t.trigger)},e.clone=function(t,e){var i=this.system.store[t.getGuid()],n={enabled:i.data.enabled,type:i.data.type,halfExtents:[i.data.halfExtents.x,i.data.halfExtents.y,i.data.halfExtents.z],linearOffset:[i.data.linearOffset.x,i.data.linearOffset.y,i.data.linearOffset.z],angularOffset:[i.data.angularOffset.x,i.data.angularOffset.y,i.data.angularOffset.z,i.data.angularOffset.w],radius:i.data.radius,axis:i.data.axis,height:i.data.height,asset:i.data.asset,renderAsset:i.data.renderAsset,model:i.data.model,render:i.data.render};return this.system.addComponent(e,n)},t}(),A_=function(t){function e(){return t.apply(this,arguments)||this}return S(e,t),e.prototype.createPhysicalShape=function(t,e){if("undefined"!=typeof Ammo){var i=e.halfExtents,n=new Ammo.btVector3(i?i.x:.5,i?i.y:.5,i?i.z:.5),s=new Ammo.btBoxShape(n);return Ammo.destroy(n),s}},e}(T_),C_=function(t){function e(){return t.apply(this,arguments)||this}return S(e,t),e.prototype.createPhysicalShape=function(t,e){if("undefined"!=typeof Ammo)return new Ammo.btSphereShape(e.radius)},e}(T_),E_=function(t){function e(){return t.apply(this,arguments)||this}return S(e,t),e.prototype.createPhysicalShape=function(t,e){var i,n,s,r=null!=(i=e.axis)?i:1,a=null!=(n=e.radius)?n:.5,o=Math.max((null!=(s=e.height)?s:2)-2*a,0),h=null;if("undefined"!=typeof Ammo)switch(r){case 0:h=new Ammo.btCapsuleShapeX(a,o);break;case 1:h=new Ammo.btCapsuleShape(a,o);break;case 2:h=new Ammo.btCapsuleShapeZ(a,o)}return h},e}(T_),M_=function(t){function e(){return t.apply(this,arguments)||this}return S(e,t),e.prototype.createPhysicalShape=function(t,e){var i,n,s,r=null!=(i=e.axis)?i:1,a=null!=(n=e.radius)?n:.5,o=null!=(s=e.height)?s:1,h=null,l=null;if("undefined"!=typeof Ammo)switch(r){case 0:h=new Ammo.btVector3(.5*o,a,a),l=new Ammo.btCylinderShapeX(h);break;case 1:h=new Ammo.btVector3(a,.5*o,a),l=new Ammo.btCylinderShape(h);break;case 2:h=new Ammo.btVector3(a,a,.5*o),l=new Ammo.btCylinderShapeZ(h)}return h&&Ammo.destroy(h),l},e}(T_),P_=function(t){function e(){return t.apply(this,arguments)||this}return S(e,t),e.prototype.createPhysicalShape=function(t,e){var i,n,s,r=null!=(i=e.axis)?i:1,a=null!=(n=e.radius)?n:.5,o=null!=(s=e.height)?s:1,h=null;if("undefined"!=typeof Ammo)switch(r){case 0:h=new Ammo.btConeShapeX(a,o);break;case 1:h=new Ammo.btConeShape(a,o);break;case 2:h=new Ammo.btConeShapeZ(a,o)}return h},e}(T_),R_=function(t){function e(){return t.apply(this,arguments)||this}S(e,t);var i=e.prototype;return i.beforeInitialize=function(t,e){},i.createAmmoMesh=function(t,e,i){var n;if(this.system._triMeshCache[t.id])n=this.system._triMeshCache[t.id];else{for(var s,r,a=t.vertexBuffer,o=a.getFormat(),h=0;h<o.elements.length;h++){var l=o.elements[h];if(l.name===we){r=new Float32Array(a.lock(),l.offset),s=l.stride/4;break}}var c=[];t.getIndices(c);var u,d,f,p=t.primitive[0].count/3,m=new Ammo.btVector3,_=new Ammo.btVector3,v=new Ammo.btVector3,g=t.primitive[0].base;n=new Ammo.btTriangleMesh,this.system._triMeshCache[t.id]=n;for(var y=0;y<p;y++)u=c[g+3*y]*s,d=c[g+3*y+1]*s,f=c[g+3*y+2]*s,m.setValue(r[u],r[u+1],r[u+2]),_.setValue(r[d],r[d+1],r[d+2]),v.setValue(r[f],r[f+1],r[f+2]),n.addTriangle(m,_,v,!0);Ammo.destroy(m),Ammo.destroy(_),Ammo.destroy(v)}var x=new Ammo.btBvhTriangleMeshShape(n,!0),S=this.system._getNodeScaling(e);x.setLocalScaling(S),Ammo.destroy(S);var b=this.system._getNodeTransform(e);i.addChildShape(b,x),Ammo.destroy(b)},i.createPhysicalShape=function(t,e){if("undefined"!=typeof Ammo&&(e.model||e.render)){var i=new Ammo.btCompoundShape;if(e.model)for(var n=e.model.meshInstances,s=0;s<n.length;s++)this.createAmmoMesh(n[s].mesh,n[s].node,i);else if(e.render)for(var r=e.render.meshes,a=0;a<r.length;a++)this.createAmmoMesh(r[a],b_,i);var o=t.getWorldTransform().getScale(),h=new Ammo.btVector3(o.x,o.y,o.z);return i.setLocalScaling(h),Ammo.destroy(h),i}},i.recreatePhysicalShapes=function(t){var e=t.data;(e.renderAsset||e.asset)&&t.enabled&&t.entity.enabled?this.loadAsset(t,e.renderAsset||e.asset,e.renderAsset?"render":"model"):this.doRecreatePhysicalShape(t)},i.loadAsset=function(t,e,i){var n=this,s=t.data,r=this.system.app.assets,a=r.get(e);a?(a.ready((function(e){s[i]=e.resource,n.doRecreatePhysicalShape(t)})),r.load(a)):r.once("add:"+e,(function(e){e.ready((function(e){s[i]=e.resource,n.doRecreatePhysicalShape(t)})),r.load(e)}))},i.doRecreatePhysicalShape=function(t){var e=t.entity,i=t.data;i.model||i.render?(this.destroyShape(i),i.shape=this.createPhysicalShape(e,i),e.rigidbody?(e.rigidbody.disableSimulation(),e.rigidbody.createBody(),e.enabled&&e.rigidbody.enabled&&e.rigidbody.enableSimulation()):e.trigger?e.trigger.initialize(i):e.trigger=new v_(this.system.app,t,i)):(this.beforeRemove(e,t),this.remove(e,i))},i.updateTransform=function(e,i,n,s){if(e.shape){var r=e.entity.getWorldTransform().getScale(),a=e.shape.getLocalScaling();r.x===a.x()&&r.y===a.y()&&r.z===a.z()||this.doRecreatePhysicalShape(e)}t.prototype.updateTransform.call(this,e,i,n,s)},i.destroyShape=function(t){if(t.shape){for(var e=t.shape.getNumChildShapes(),i=0;i<e;i++){var n=t.shape.getChildShape(i);Ammo.destroy(n)}Ammo.destroy(t.shape),t.shape=null}},e}(T_),I_=function(t){function e(){return t.apply(this,arguments)||this}S(e,t);var i=e.prototype;return i.createPhysicalShape=function(t,e){if("undefined"!=typeof Ammo)return new Ammo.btCompoundShape},i._addEachDescendant=function(t){t.collision&&!t.rigidbody&&(t.collision._compoundParent=this,t!==this.entity&&t.collision.system.recreatePhysicalShapes(t.collision))},i._updateEachDescendant=function(t){t.collision&&t.collision._compoundParent===this&&(t.collision._compoundParent=null,t===this.entity||t.rigidbody||t.collision.system.recreatePhysicalShapes(t.collision))},i._updateEachDescendantTransform=function(t){t.collision&&t.collision._compoundParent===this.collision._compoundParent&&this.collision.system.updateCompoundChildTransform(t)},e}(T_),L_=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="collision",i.ComponentType=c_,i.DataType=u_,i.schema=w_,i.implementations={},i._triMeshCache={},i.on("beforeremove",i.onBeforeRemove,w(i)),i.on("remove",i.onRemove,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){for(var s,r={},a=0,o=(n=["type","halfExtents","radius","axis","height","shape","model","asset","render","renderAsset","enabled","linearOffset","angularOffset"]).length;a<o;a++){var h=n[a];r[h]=i[h]}if(i.hasOwnProperty("asset")?(-1!==(s=n.indexOf("model"))&&n.splice(s,1),-1!==(s=n.indexOf("render"))&&n.splice(s,1)):i.hasOwnProperty("model")&&-1!==(s=n.indexOf("asset"))&&n.splice(s,1),r.type||(r.type=e.data.type),e.data.type=r.type,Array.isArray(r.halfExtents)&&(r.halfExtents=new wt(r.halfExtents)),Array.isArray(r.linearOffset)&&(r.linearOffset=new wt(r.linearOffset)),Array.isArray(r.angularOffset)){var l=r.angularOffset;3===l.length?r.angularOffset=(new Bt).setFromEulerAngles(l[0],l[1],l[2]):r.angularOffset=new Bt(r.angularOffset)}var c=this._createImplementation(r.type);c.beforeInitialize(e,r),t.prototype.initializeComponentData.call(this,e,r,n),c.afterInitialize(e,r)},i._createImplementation=function(t){if(void 0===this.implementations[t]){var e;switch(t){case"box":e=new A_(this);break;case"sphere":e=new C_(this);break;case"capsule":e=new E_(this);break;case"cylinder":e=new M_(this);break;case"cone":e=new P_(this);break;case"mesh":e=new R_(this);break;case"compound":e=new I_(this)}this.implementations[t]=e}return this.implementations[t]},i._getImplementation=function(t){return this.implementations[t.collision.data.type]},i.cloneComponent=function(t,e){return this._getImplementation(t).clone(t,e)},i.onBeforeRemove=function(t,e){this.implementations[e.data.type].beforeRemove(t,e),e.onBeforeRemove()},i.onRemove=function(t,e){this.implementations[e.type].remove(t,e)},i.updateCompoundChildTransform=function(t){if(this._removeCompoundChild(t.collision._compoundParent,t.collision.data.shape),t.enabled&&t.collision.enabled){var e=this._getNodeTransform(t,t.collision._compoundParent.entity);t.collision._compoundParent.shape.addChildShape(e,t.collision.data.shape),Ammo.destroy(e)}},i._removeCompoundChild=function(t,e){if(t.shape.removeChildShape)t.shape.removeChildShape(e);else{var i=t._getCompoundChildShapeIndex(e);null!==i&&t.shape.removeChildShapeByIndex(i)}},i.onTransformChanged=function(t,e,i,n){this.implementations[t.data.type].updateTransform(t,e,i,n)},i.changeType=function(t,e,i){this.implementations[e].beforeRemove(t.entity,t),this.implementations[e].remove(t.entity,t.data),this._createImplementation(i).reset(t,t.data)},i.recreatePhysicalShapes=function(t){this.implementations[t.data.type].recreatePhysicalShapes(t)},i._calculateNodeRelativeTransform=function(t,e){if(t===e){var i=t.getWorldTransform().getScale();g_.setScale(i.x,i.y,i.z)}else this._calculateNodeRelativeTransform(t.parent,e),g_.mul(t.getLocalTransform())},i._getNodeScaling=function(t){var e=t.getWorldTransform().getScale();return new Ammo.btVector3(e.x,e.y,e.z)},i._getNodeTransform=function(t,e){var i,n;e?(this._calculateNodeRelativeTransform(t,e),i=y_,n=S_,g_.getTranslation(i),n.setFromMat4(g_)):(i=t.getPosition(),n=t.getRotation());var s=new Ammo.btQuaternion,r=new Ammo.btTransform;r.setIdentity();var a=r.getOrigin(),o=t.collision;if(o&&o._hasOffset){var h=o.data.linearOffset,l=o.data.angularOffset,c=x_;S_.copy(n).transformVector(h,c),c.add(i),S_.copy(n).mul(l),a.setValue(c.x,c.y,c.z),s.setValue(S_.x,S_.y,S_.z,S_.w)}else a.setValue(i.x,i.y,i.z),s.setValue(n.x,n.y,n.z,n.w);return r.setRotation(s),Ammo.destroy(s),Ammo.destroy(a),r},i.destroy=function(){for(var e in this._triMeshCache)Ammo.destroy(this._triMeshCache[e]);this._triMeshCache=null,t.prototype.destroy.call(this)},e}(wp);bp._buildAccessors(c_.prototype,w_);var D_=new Bs,O_=function(){function t(t,e,i){this._entity=t,this._element=t.element,this.model=new Gu,this.node=new hh,this.model.graph=this.node,this.mesh=e,this.meshInstance=new yh(this.mesh,i,this.node),this.meshInstance.name="ImageElement: "+t.name,this.meshInstance.castShadow=!1,this.meshInstance.receiveShadow=!1,this._meshDirty=!1,this.model.meshInstances.push(this.meshInstance),this._entity.addChild(this.model.graph),this.model._entity=this._entity,this.unmaskMeshInstance=null}var e=t.prototype;return e.destroy=function(){this.setMaterial(null),this._element.removeModelFromLayers(this.model),this.model.destroy(),this.model=null,this.node=null,this.mesh=null,this.meshInstance=null,this._entity=null,this._element=null},e.setMesh=function(t){this.meshInstance&&(this.mesh=t,this.meshInstance.mesh=t,this.meshInstance.visible=!!t,this.unmaskMeshInstance&&(this.unmaskMeshInstance.mesh=t),this.forceUpdateAabb())},e.setMask=function(t){if(this.meshInstance){if(t)for(var e in this.unmaskMeshInstance=new yh(this.mesh,this.meshInstance.material,this.node),this.unmaskMeshInstance.name="Unmask: "+this._entity.name,this.unmaskMeshInstance.castShadow=!1,this.unmaskMeshInstance.receiveShadow=!1,this.unmaskMeshInstance.pick=!1,this.model.meshInstances.push(this.unmaskMeshInstance),this.meshInstance.parameters)this.unmaskMeshInstance.setParameter(e,this.meshInstance.parameters[e].data);else{var i=this.model.meshInstances.indexOf(this.unmaskMeshInstance);i>=0&&this.model.meshInstances.splice(i,1),this.unmaskMeshInstance=null}this._entity.enabled&&this._element.enabled&&(this._element.removeModelFromLayers(this.model),this._element.addModelToLayers(this.model))}},e.setMaterial=function(t){this.meshInstance&&(this.meshInstance.material=t,this.unmaskMeshInstance&&(this.unmaskMeshInstance.material=t))},e.setParameter=function(t,e){this.meshInstance&&(this.meshInstance.setParameter(t,e),this.unmaskMeshInstance&&this.unmaskMeshInstance.setParameter(t,e))},e.deleteParameter=function(t){this.meshInstance&&(this.meshInstance.deleteParameter(t),this.unmaskMeshInstance&&this.unmaskMeshInstance.deleteParameter(t))},e.setUnmaskDrawOrder=function(){if(this.meshInstance){if(this.unmaskMeshInstance){var t=function t(e){var i,n=e.children,s=n.length;if(s){for(var r=0;r<s;r++)n[r].element&&(i=n[r]);return i?t(i)||i:null}return null}(this._entity);t&&t.element?this.unmaskMeshInstance.drawOrder=t.element.drawOrder+t.element.getMaskOffset():this.unmaskMeshInstance.drawOrder=this.meshInstance.drawOrder+this._element.getMaskOffset()}}},e.setDrawOrder=function(t){this.meshInstance&&(this.meshInstance.drawOrder=t)},e.setCull=function(t){if(this.meshInstance){var e=this._element,i=null;t&&e._isScreenSpace()&&(i=function(t){return e.isVisibleForCamera(t)}),this.meshInstance.cull=t,this.meshInstance.isVisibleFunc=i,this.unmaskMeshInstance&&(this.unmaskMeshInstance.cull=t,this.unmaskMeshInstance.isVisibleFunc=i)}},e.setScreenSpace=function(t){this.meshInstance&&(this.meshInstance.screenSpace=t,this.unmaskMeshInstance&&(this.unmaskMeshInstance.screenSpace=t))},e.setLayer=function(t){this.meshInstance&&(this.meshInstance.layer=t,this.unmaskMeshInstance&&(this.unmaskMeshInstance.layer=t))},e.forceUpdateAabb=function(t){this.meshInstance&&(this.meshInstance._aabbVer=-1,this.unmaskMeshInstance&&(this.unmaskMeshInstance._aabbVer=-1))},e.setAabbFunc=function(t){this.meshInstance&&(this.meshInstance._updateAabbFunc=t,this.unmaskMeshInstance&&(this.unmaskMeshInstance._updateAabbFunc=t))},t}(),k_=function(){function t(t){this._element=t,this._entity=t.entity,this._system=t.system,this._textureAsset=null,this._texture=null,this._materialAsset=null,this._material=null,this._spriteAsset=null,this._sprite=null,this._spriteFrame=0,this._pixelsPerUnit=null,this._targetAspectRatio=-1,this._rect=new Pt(0,0,1,1),this._mask=!1,this._maskRef=0,this._outerScale=new Et,this._outerScaleUniform=new Float32Array(2),this._innerOffset=new Pt,this._innerOffsetUniform=new Float32Array(4),this._atlasRect=new Pt,this._atlasRectUniform=new Float32Array(4),this._defaultMesh=this._createMesh(),this._renderable=new O_(this._entity,this._defaultMesh,this._material),this._color=new vt(1,1,1,1),this._colorUniform=new Float32Array([1,1,1]),this._renderable.setParameter("material_emissive",this._colorUniform),this._renderable.setParameter("material_opacity",1),this._updateAabbFunc=this._updateAabb.bind(this),this._onScreenChange(this._element.screen),this._element.on("resize",this._onParentResizeOrPivotChange,this),this._element.on("set:pivot",this._onParentResizeOrPivotChange,this),this._element.on("screen:set:screenspace",this._onScreenSpaceChange,this),this._element.on("set:screen",this._onScreenChange,this),this._element.on("set:draworder",this._onDrawOrderChange,this),this._element.on("screen:set:resolution",this._onResolutionChange,this)}var e=t.prototype;return e.destroy=function(){this.textureAsset=null,this.spriteAsset=null,this.materialAsset=null,this._renderable.setMesh(this._defaultMesh),this._renderable.destroy(),this._defaultMesh=null,this._element.off("resize",this._onParentResizeOrPivotChange,this),this._element.off("set:pivot",this._onParentResizeOrPivotChange,this),this._element.off("screen:set:screenspace",this._onScreenSpaceChange,this),this._element.off("set:screen",this._onScreenChange,this),this._element.off("set:draworder",this._onDrawOrderChange,this),this._element.off("screen:set:resolution",this._onResolutionChange,this)},e._onResolutionChange=function(t){},e._onParentResizeOrPivotChange=function(){this._renderable.mesh&&this._updateMesh(this._renderable.mesh)},e._onScreenSpaceChange=function(t){this._updateMaterial(t)},e._onScreenChange=function(t,e){t?this._updateMaterial(t.screen.screenSpace):this._updateMaterial(!1)},e._onDrawOrderChange=function(t){this._renderable.setDrawOrder(t),this.mask&&this._element.screen&&this._element.screen.screen.once("syncdraworder",(function(){this._renderable.setUnmaskDrawOrder()}),this)},e._hasUserMaterial=function(){return!!this._materialAsset||!!this._material&&-1===this._system.defaultImageMaterials.indexOf(this._material)},e._use9Slicing=function(){return this.sprite&&(1===this.sprite.renderMode||2===this.sprite.renderMode)},e._updateMaterial=function(t){var e=!!this._mask,i=!(!this.sprite||1!==this.sprite.renderMode),n=!(!this.sprite||2!==this.sprite.renderMode);this._hasUserMaterial()||(this._material=this._system.getImageElementMaterial(t,e,i,n)),this._renderable&&(this._renderable.setCull(!this._element._isScreenSpace()||this._element._isScreenCulled()),this._renderable.setMaterial(this._material),this._renderable.setScreenSpace(t),this._renderable.setLayer(t?0:15))},e._createMesh=function(){var t=this._element,e=t.calculatedWidth,i=t.calculatedHeight,n=this._rect,s=this._system.app.graphicsDevice,r=new Float32Array([e,0,0,0,0,1,n.x+n.z,1-n.y,e,i,0,0,0,1,n.x+n.z,1-(n.y+n.w),0,0,0,0,0,1,n.x,1-n.y,0,i,0,0,0,1,n.x,1-(n.y+n.w)]),a=D_.get(s,(function(){return new Ji(s,[{semantic:we,components:3,type:6},{semantic:Te,components:3,type:6},{semantic:Re,components:2,type:6}])})),o=new ji(s,a,4,0,r.buffer),h=new qa(s);return h.vertexBuffer=o,h.primitive[0].type=be,h.primitive[0].base=0,h.primitive[0].count=4,h.primitive[0].indexed=!1,h.aabb.setMinMax(wt.ZERO,new wt(e,i,0)),this._updateMesh(h),h},e._updateMesh=function(t){var e=this._element,i=e.calculatedWidth,n=e.calculatedHeight;if(e.fitMode!==Wm&&this._targetAspectRatio>0){var s=e.calculatedWidth/e.calculatedHeight;e.fitMode===Xm&&s>this._targetAspectRatio||e.fitMode===jm&&s<this._targetAspectRatio?i=e.calculatedHeight*this._targetAspectRatio:n=e.calculatedWidth/this._targetAspectRatio}var r=e._isScreenSpace();if(this._updateMaterial(r),this._renderable&&this._renderable.forceUpdateAabb(),!this.sprite||1!==this.sprite.renderMode&&2!==this.sprite.renderMode){var a=t.vertexBuffer,o=new Float32Array(a.lock()),h=e.pivot.x,l=e.pivot.y;o[0]=i-h*i,o[1]=0-l*n,o[8]=i-h*i,o[9]=n-l*n,o[16]=0-h*i,o[17]=0-l*n,o[24]=0-h*i,o[25]=n-l*n;var c=1,u=1,d=this._rect;if(this._sprite&&this._sprite.frameKeys[this._spriteFrame]&&this._sprite.atlas){var f=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]];f&&(d=f.rect,c=this._sprite.atlas.texture.width,u=this._sprite.atlas.texture.height)}o[6]=(d.x+d.z)/c,o[7]=1-d.y/u,o[14]=(d.x+d.z)/c,o[15]=1-(d.y+d.w)/u,o[22]=d.x/c,o[23]=1-d.y/u,o[30]=d.x/c,o[31]=1-(d.y+d.w)/u,a.unlock();var p=new wt(0-h*i,0-l*n,0),m=new wt(i-h*i,n-l*n,0);t.aabb.setMinMax(p,m),this._renderable&&(this._renderable.node.setLocalScale(1,1,1),this._renderable.node.setLocalPosition(0,0,0),this._renderable.setAabbFunc(null))}else{var _=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]],v=2/_.rect.z,g=2/_.rect.w;this._innerOffset.set(_.border.x*v,_.border.y*g,_.border.z*v,_.border.w*g);var y=this.sprite.atlas.texture;this._atlasRect.set(_.rect.x/y.width,_.rect.y/y.height,_.rect.z/y.width,_.rect.w/y.height);var x=null!==this._pixelsPerUnit?this._pixelsPerUnit:this.sprite.pixelsPerUnit,S=_.rect.z/x,b=_.rect.w/x;this._outerScale.set(Math.max(i,this._innerOffset.x*S),Math.max(n,this._innerOffset.y*b));var w=S,T=b;this._outerScale.x/=S,this._outerScale.y/=b,w*=_t.clamp(i/(this._innerOffset.x*S),1e-4,1),T*=_t.clamp(n/(this._innerOffset.y*b),1e-4,1),this._renderable&&(this._innerOffsetUniform[0]=this._innerOffset.x,this._innerOffsetUniform[1]=this._innerOffset.y,this._innerOffsetUniform[2]=this._innerOffset.z,this._innerOffsetUniform[3]=this._innerOffset.w,this._renderable.setParameter("innerOffset",this._innerOffsetUniform),this._atlasRectUniform[0]=this._atlasRect.x,this._atlasRectUniform[1]=this._atlasRect.y,this._atlasRectUniform[2]=this._atlasRect.z,this._atlasRectUniform[3]=this._atlasRect.w,this._renderable.setParameter("atlasRect",this._atlasRectUniform),this._outerScaleUniform[0]=this._outerScale.x,this._outerScaleUniform[1]=this._outerScale.y,this._renderable.setParameter("outerScale",this._outerScaleUniform),this._renderable.setAabbFunc(this._updateAabbFunc),this._renderable.node.setLocalScale(w,T,1),this._renderable.node.setLocalPosition((.5-e.pivot.x)*i,(.5-e.pivot.y)*n,0))}this._meshDirty=!1},e._updateSprite=function(){var t=!1,e=null;if(this._targetAspectRatio=-1,this._sprite&&this._sprite.atlas){e=this._sprite.meshes[this.spriteFrame],t=1===this._sprite.renderMode||2===this._sprite.renderMode;var i=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]];(null==i?void 0:i.rect.w)>0&&(this._targetAspectRatio=i.rect.z/i.rect.w)}this.mesh=t?e:this._defaultMesh,this.refreshMesh()},e.refreshMesh=function(){this.mesh&&(this._element._beingInitialized?this._meshDirty=!0:this._updateMesh(this.mesh))},e._updateAabb=function(t){return t.center.set(0,0,0),t.halfExtents.set(.5*this._outerScale.x,.5*this._outerScale.y,.001),t.setFromTransformedAabb(t,this._renderable.node.getWorldTransform()),t},e._toggleMask=function(){this._element._dirtifyMask();var t=this._element._isScreenSpace();this._updateMaterial(t),this._renderable.setMask(!!this._mask)},e._onMaterialLoad=function(t){this.material=t.resource},e._onMaterialAdded=function(t){this._system.app.assets.off("add:"+t.id,this._onMaterialAdded,this),this._materialAsset===t.id&&this._bindMaterialAsset(t)},e._bindMaterialAsset=function(t){this._entity.enabled&&(t.on("load",this._onMaterialLoad,this),t.on("change",this._onMaterialChange,this),t.on("remove",this._onMaterialRemove,this),t.resource?this._onMaterialLoad(t):this._system.app.assets.load(t))},e._unbindMaterialAsset=function(t){t.off("load",this._onMaterialLoad,this),t.off("change",this._onMaterialChange,this),t.off("remove",this._onMaterialRemove,this)},e._onMaterialChange=function(){},e._onMaterialRemove=function(){},e._onTextureAdded=function(t){this._system.app.assets.off("add:"+t.id,this._onTextureAdded,this),this._textureAsset===t.id&&this._bindTextureAsset(t)},e._bindTextureAsset=function(t){this._entity.enabled&&(t.on("load",this._onTextureLoad,this),t.on("change",this._onTextureChange,this),t.on("remove",this._onTextureRemove,this),t.resource?this._onTextureLoad(t):this._system.app.assets.load(t))},e._unbindTextureAsset=function(t){t.off("load",this._onTextureLoad,this),t.off("change",this._onTextureChange,this),t.off("remove",this._onTextureRemove,this)},e._onTextureLoad=function(t){this.texture=t.resource},e._onTextureChange=function(t){},e._onTextureRemove=function(t){},e._onSpriteAssetAdded=function(t){this._system.app.assets.off("add:"+t.id,this._onSpriteAssetAdded,this),this._spriteAsset===t.id&&this._bindSpriteAsset(t)},e._bindSpriteAsset=function(t){this._entity.enabled&&(t.on("load",this._onSpriteAssetLoad,this),t.on("change",this._onSpriteAssetChange,this),t.on("remove",this._onSpriteAssetRemove,this),t.resource?this._onSpriteAssetLoad(t):this._system.app.assets.load(t))},e._unbindSpriteAsset=function(t){t.off("load",this._onSpriteAssetLoad,this),t.off("change",this._onSpriteAssetChange,this),t.off("remove",this._onSpriteAssetRemove,this),t.data.textureAtlasAsset&&this._system.app.assets.off("load:"+t.data.textureAtlasAsset,this._onTextureAtlasLoad,this)},e._onSpriteAssetLoad=function(t){if(t&&t.resource)if(t.resource.atlas)this.sprite=t.resource;else{var e=t.data.textureAtlasAsset;if(e){var i=this._system.app.assets;i.off("load:"+e,this._onTextureAtlasLoad,this),i.once("load:"+e,this._onTextureAtlasLoad,this)}}else this.sprite=null},e._onSpriteAssetChange=function(t){this._onSpriteAssetLoad(t)},e._onSpriteAssetRemove=function(t){},e._bindSprite=function(t){t.on("set:meshes",this._onSpriteMeshesChange,this),t.on("set:pixelsPerUnit",this._onSpritePpuChange,this),t.on("set:atlas",this._onAtlasTextureChange,this),t.atlas&&t.atlas.on("set:texture",this._onAtlasTextureChange,this)},e._unbindSprite=function(t){t.off("set:meshes",this._onSpriteMeshesChange,this),t.off("set:pixelsPerUnit",this._onSpritePpuChange,this),t.off("set:atlas",this._onAtlasTextureChange,this),t.atlas&&t.atlas.off("set:texture",this._onAtlasTextureChange,this)},e._onSpriteMeshesChange=function(){this._sprite&&(this._spriteFrame=_t.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite()},e._onSpritePpuChange=function(){0!==this.sprite.renderMode&&null===this._pixelsPerUnit&&this._updateSprite()},e._onAtlasTextureChange=function(){this.sprite&&this.sprite.atlas&&this.sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"))},e._onTextureAtlasLoad=function(t){var e=this._spriteAsset;e instanceof Vf?this._onSpriteAssetLoad(e):this._onSpriteAssetLoad(this._system.app.assets.get(e))},e.onEnable=function(){if(this._materialAsset){var t=this._system.app.assets.get(this._materialAsset);t&&t.resource!==this._material&&this._bindMaterialAsset(t)}if(this._textureAsset){var e=this._system.app.assets.get(this._textureAsset);e&&e.resource!==this._texture&&this._bindTextureAsset(e)}if(this._spriteAsset){var i=this._system.app.assets.get(this._spriteAsset);i&&i.resource!==this._sprite&&this._bindSpriteAsset(i)}this._element.addModelToLayers(this._renderable.model)},e.onDisable=function(){this._element.removeModelFromLayers(this._renderable.model)},e._setStencil=function(t){this._renderable.meshInstance.stencilFront=t,this._renderable.meshInstance.stencilBack=t;var e=0;if(this._element.maskedBy&&(e=this._element.maskedBy.element._image._maskRef),this._renderable.unmaskMeshInstance){var i=new en({ref:e+1,func:2,zpass:5});this._renderable.unmaskMeshInstance.stencilFront=i,this._renderable.unmaskMeshInstance.stencilBack=i}},e._removeMaterialAssetEvents=function(){if(this._materialAsset){var t=this._system.app.assets;t.off("add:"+this._materialAsset,this._onMaterialAdded,this);var e=t.get(this._materialAsset);e&&(e.off("load",this._onMaterialLoad,this),e.off("change",this._onMaterialChange,this),e.off("remove",this._onMaterialRemove,this))}},y(t,[{key:"color",get:function(){return this._color},set:function(t){var e=t.r,i=t.g,n=t.b;this._color.r===e&&this._color.g===i&&this._color.b===n||(this._color.r=e,this._color.g=i,this._color.b=n,this._colorUniform[0]=e,this._colorUniform[1]=i,this._colorUniform[2]=n,this._renderable.setParameter("material_emissive",this._colorUniform)),this._element&&this._element.fire("set:color",this._color)}},{key:"opacity",get:function(){return this._color.a},set:function(t){t!==this._color.a&&(this._color.a=t,this._renderable.setParameter("material_opacity",t)),this._element&&this._element.fire("set:opacity",t)}},{key:"rect",get:function(){return this._rect},set:function(t){var e,i,n,s;t instanceof Pt?(e=t.x,i=t.y,n=t.z,s=t.w):(e=t[0],i=t[1],n=t[2],s=t[3]),e===this._rect.x&&i===this._rect.y&&n===this._rect.z&&s===this._rect.w||(this._rect.set(e,i,n,s),this._renderable.mesh&&(this._element._beingInitialized?this._meshDirty=!0:this._updateMesh(this._renderable.mesh)))}},{key:"material",get:function(){return this._material},set:function(t){if(this._material!==t){if(!t){var e=this._element._isScreenSpace();t=this.mask?e?this._system.defaultScreenSpaceImageMaskMaterial:this._system.defaultImageMaskMaterial:e?this._system.defaultScreenSpaceImageMaterial:this._system.defaultImageMaterial}if(this._material=t,this._materialAsset){var i=this._system.app.assets.get(this._materialAsset);i&&i.resource===t||(this._removeMaterialAssetEvents(),this._materialAsset=null)}t&&(this._renderable.setMaterial(t),this._hasUserMaterial()?(this._renderable.deleteParameter("material_opacity"),this._renderable.deleteParameter("material_emissive")):(this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._renderable.setParameter("material_emissive",this._colorUniform),this._renderable.setParameter("material_opacity",this._color.a)))}}},{key:"materialAsset",get:function(){return this._materialAsset},set:function(t){var e=this._system.app.assets,i=t;if(t instanceof Vf&&(i=t.id),this._materialAsset!==i)if(this._removeMaterialAssetEvents(),this._materialAsset=i,this._materialAsset){var n=e.get(this._materialAsset);n?this._bindMaterialAsset(n):(this._materialAsset=null,this.material=null,this._materialAsset=i,e.on("add:"+this._materialAsset,this._onMaterialAdded,this))}else this._materialAsset=null,this.material=null,this._materialAsset=i}},{key:"texture",get:function(){return this._texture},set:function(t){if(this._texture!==t){if(this._textureAsset){var e=this._system.app.assets.get(this._textureAsset);e&&e.resource!==t&&(this.textureAsset=null)}if(this._texture=t,t){this._spriteAsset&&(this.spriteAsset=null),this._renderable.setParameter("texture_emissiveMap",this._texture),this._renderable.setParameter("texture_opacityMap",this._texture),this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._renderable.setParameter("material_emissive",this._colorUniform),this._renderable.setParameter("material_opacity",this._color.a);var i=this._texture.width/this._texture.height;i!==this._targetAspectRatio&&(this._targetAspectRatio=i,this._element.fitMode!==Wm&&this.refreshMesh())}else this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"),this._targetAspectRatio=-1,this._element.fitMode!==Wm&&this.refreshMesh()}}},{key:"textureAsset",get:function(){return this._textureAsset},set:function(t){var e=this._system.app.assets,i=t;if(t instanceof Vf&&(i=t.id),this._textureAsset!==i){if(this._textureAsset){e.off("add:"+this._textureAsset,this._onTextureAdded,this);var n=e.get(this._textureAsset);n&&(n.off("load",this._onTextureLoad,this),n.off("change",this._onTextureChange,this),n.off("remove",this._onTextureRemove,this))}if(this._textureAsset=i,this._textureAsset){var s=e.get(this._textureAsset);s?this._bindTextureAsset(s):(this.texture=null,e.on("add:"+this._textureAsset,this._onTextureAdded,this))}else this.texture=null}}},{key:"spriteAsset",get:function(){return this._spriteAsset},set:function(t){var e=this._system.app.assets,i=t;if(t instanceof Vf&&(i=t.id),this._spriteAsset!==i){if(this._spriteAsset){e.off("add:"+this._spriteAsset,this._onSpriteAssetAdded,this);var n=e.get(this._spriteAsset);n&&this._unbindSpriteAsset(n)}if(this._spriteAsset=i,this._spriteAsset){var s=e.get(this._spriteAsset);s?this._bindSpriteAsset(s):(this.sprite=null,e.on("add:"+this._spriteAsset,this._onSpriteAssetAdded,this))}else this.sprite=null}this._element&&this._element.fire("set:spriteAsset",i)}},{key:"sprite",get:function(){return this._sprite},set:function(t){if(this._sprite!==t){if(this._sprite&&this._unbindSprite(this._sprite),this._spriteAsset){var e=this._system.app.assets.get(this._spriteAsset);e&&e.resource!==t&&(this.spriteAsset=null)}this._sprite=t,this._sprite&&(this._bindSprite(this._sprite),this._textureAsset&&(this.textureAsset=null)),this._sprite&&this._sprite.atlas&&this._sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap")),this._sprite&&(this._spriteFrame=_t.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite()}}},{key:"spriteFrame",get:function(){return this._spriteFrame},set:function(t){var e=this._spriteFrame;this._sprite?this._spriteFrame=_t.clamp(t,0,this._sprite.frameKeys.length-1):this._spriteFrame=t,this._spriteFrame!==e&&this._updateSprite(),this._element&&this._element.fire("set:spriteFrame",t)}},{key:"mesh",get:function(){return this._renderable.mesh},set:function(t){this._renderable.setMesh(t),this._defaultMesh===t?this._renderable.setAabbFunc(null):this._renderable.setAabbFunc(this._updateAabbFunc)}},{key:"mask",get:function(){return this._mask},set:function(t){this._mask!==t&&(this._mask=t,this._toggleMask())}},{key:"pixelsPerUnit",get:function(){return this._pixelsPerUnit},set:function(t){this._pixelsPerUnit!==t&&(this._pixelsPerUnit=t,!this._sprite||1!==this._sprite.renderMode&&2!==this._sprite.renderMode||this._updateSprite())}},{key:"aabb",get:function(){return this._renderable.meshInstance?this._renderable.meshInstance.aabb:null}}]),t}(),F_=function(t){function e(e){var i;return(i=t.call(this)||this)._app=e,e.i18n.on("set:locale",i._onSetLocale,w(i)),i._autoLoad=!1,i._disableLocalization=!1,i._defaultAsset=null,i._localizedAsset=null,i}S(e,t);var i=e.prototype;return i._bindDefaultAsset=function(){var t=this._app.assets.get(this._defaultAsset);t?this._onDefaultAssetAdd(t):this._app.assets.once("add:"+this._defaultAsset,this._onDefaultAssetAdd,this)},i._unbindDefaultAsset=function(){if(this._defaultAsset){this._app.assets.off("add:"+this._defaultAsset,this._onDefaultAssetAdd,this);var t=this._app.assets.get(this._defaultAsset);t&&(t.off("add:localized",this._onLocaleAdd,this),t.off("remove:localized",this._onLocaleRemove,this),t.off("remove",this._onDefaultAssetRemove,this))}},i._onDefaultAssetAdd=function(t){this._defaultAsset===t.id&&(t.on("add:localized",this._onLocaleAdd,this),t.on("remove:localized",this._onLocaleRemove,this),t.once("remove",this._onDefaultAssetRemove,this))},i._onDefaultAssetRemove=function(t){this._defaultAsset===t.id&&(t.off("add:localized",this._onLocaleAdd,this),t.off("remove:localized",this._onLocaleAdd,this),this._app.assets.once("add:"+this._defaultAsset,this._onDefaultAssetAdd,this))},i._bindLocalizedAsset=function(){if(this._autoLoad){var t=this._app.assets.get(this._localizedAsset);t&&(t.on("load",this._onLocalizedAssetLoad,this),t.on("change",this._onLocalizedAssetChange,this),t.on("remove",this._onLocalizedAssetRemove,this),t.resource?this._onLocalizedAssetLoad(t):this._app.assets.load(t))}},i._unbindLocalizedAsset=function(){var t=this._app.assets.get(this._localizedAsset);t&&(t.off("load",this._onLocalizedAssetLoad,this),t.off("change",this._onLocalizedAssetChange,this),t.off("remove",this._onLocalizedAssetRemove,this))},i._onLocalizedAssetAdd=function(t){this._localizedAsset===t.id&&this._bindLocalizedAsset()},i._onLocalizedAssetLoad=function(t){this.fire("load",t)},i._onLocalizedAssetChange=function(t,e,i,n){this.fire("change",t,e,i,n)},i._onLocalizedAssetRemove=function(t){this._localizedAsset===t.id&&(this.localizedAsset=this._defaultAsset),this.fire("remove",t)},i._onLocaleAdd=function(t,e){this._app.i18n.locale===t&&this._onSetLocale(t)},i._onLocaleRemove=function(t,e){this._app.i18n.locale===t&&this._onSetLocale(t)},i._onSetLocale=function(t){if(this._defaultAsset){var e=this._app.assets.get(this._defaultAsset);if(e&&!this._disableLocalization){var i=e.getLocalizedAssetId(t);this.localizedAsset=i||this._defaultAsset}else this.localizedAsset=this._defaultAsset}else this.localizedAsset=null},i.destroy=function(){this.defaultAsset=null,this._app.i18n.off("set:locale",this._onSetLocale,this),this.off()},y(e,[{key:"defaultAsset",get:function(){return this._defaultAsset},set:function(t){var e=t instanceof Vf?t.id:t;this._defaultAsset!==e&&(this._defaultAsset&&this._unbindDefaultAsset(),this._defaultAsset=e,this._defaultAsset&&this._bindDefaultAsset(),this._onSetLocale(this._app.i18n.locale))}},{key:"localizedAsset",get:function(){return this._localizedAsset},set:function(t){var e=t instanceof Vf?t.id:t;this._localizedAsset!==e&&(this._localizedAsset&&(this._app.assets.off("add:"+this._localizedAsset,this._onLocalizedAssetAdd,this),this._unbindLocalizedAsset(),this._localizedAsset=null),this._localizedAsset=e,this._localizedAsset&&(this._app.assets.get(this._localizedAsset)?this._bindLocalizedAsset():this._app.assets.once("add:"+this._localizedAsset,this._onLocalizedAssetAdd,this)))}},{key:"autoLoad",get:function(){return this._autoLoad},set:function(t){this._autoLoad!==t&&(this._autoLoad=t,this._autoLoad&&this._localizedAsset&&(this._unbindLocalizedAsset(),this._bindLocalizedAsset()))}},{key:"disableLocalization",get:function(){return this._disableLocalization},set:function(t){this._disableLocalization!==t&&(this._disableLocalization=t,this._onSetLocale(this._app.i18n.locale))}}]),e}(P),B_="msdf",U_="bitmap",N_=/[A-Z|a-z|0-9|_|-|/]/,z_=function(){function t(t){this._symbols=t,this._index=0,this._last=0,this._cur=this._symbols.length>0?this._symbols[0]:null,this._buf=[],this._mode="text",this._error=null}var e=t.prototype;return e.read=function(){for(var t=this._read();8===t;)t=this._read();return 0!==t&&1!==t&&(this._last=this._index),t},e.buf=function(){return this._buf},e.last=function(){return this._last},e.error=function(){return this._error},e.debugPrint=function(){for(var t=["EOF","ERROR","TEXT","OPEN_BRACKET","CLOSE_BRACKET","EQUALS","STRING","IDENTIFIER","WHITESPACE"],e=this.read(),i="";i+=(i.length>0?"\n":"")+t[e]+" '"+this.buf().join("")+"'",0!==e&&1!==e;)e=this.read();return i},e._read=function(){return this._buf=[],this._eof()?0:"text"===this._mode?this._text():this._tag()},e._text=function(){for(;;)switch(this._cur){case null:return this._buf.length>0?2:0;case"[":return this._mode="tag",this._buf.length>0?2:this._tag();case"\\":if(this._next(),"["===this._cur)this._store();else this._output("\\");break;default:this._store()}},e._tag=function(){switch(this._cur){case null:return this._error="unexpected end of input reading tag",1;case"[":return this._store(),3;case"]":return this._store(),this._mode="text",4;case"=":return this._store(),5;case" ":case"\t":case"\n":case"\r":case"\v":case"\f":return this._whitespace();case'"':return this._string();default:return this._isIdentifierSymbol(this._cur)?this._identifier():(this._error="unrecognized character",1)}},e._whitespace=function(){for(this._store();-1!==" \t\n\r\v\f".indexOf(this._cur);)this._store();return 8},e._string=function(){for(this._next();;)switch(this._cur){case null:return this._error="unexpected end of input reading string",1;case'"':return this._next(),6;default:this._store()}},e._identifier=function(){for(this._store();null!==this._cur&&this._isIdentifierSymbol(this._cur);)this._store();return 7},e._isIdentifierSymbol=function(t){return 1===t.length&&null!==t.match(N_)},e._eof=function(){return null===this._cur},e._next=function(){return this._eof()||(this._index++,this._cur=this._index<this._symbols.length?this._symbols[this._index]:null),this._cur},e._store=function(){return this._buf.push(this._cur),this._next()},e._output=function(t){this._buf.push(t)},t}(),V_=function(){function t(t){this._scanner=new z_(t),this._error=null}var e=t.prototype;return e.parse=function(t,e){for(;;){switch(this._scanner.read()){case 0:return!0;case 1:default:return!1;case 2:Array.prototype.push.apply(t,this._scanner.buf());break;case 3:if(!this._parseTag(t,e))return!1}}},e.error=function(){return"Error evaluating markup at #"+this._scanner.last().toString()+" ("+(this._scanner.error()||this._error)+")"},e._parseTag=function(t,e){var i=this._scanner.read();if(7!==i)return this._error="expected identifier",!1;var n=this._scanner.buf().join("");if("/"===n[0]){for(var s=e.length-1;s>=0;--s)if(n==="/"+e[s].name&&null===e[s].end)return e[s].end=t.length,4===(i=this._scanner.read())||(this._error="expected close bracket",!1);return this._error="failed to find matching tag",!1}var r={name:n,value:null,attributes:{},start:t.length,end:null};if(5===(i=this._scanner.read())){if(6!==(i=this._scanner.read()))return this._error="expected string",!1;r.value=this._scanner.buf().join(""),i=this._scanner.read()}for(;;){switch(i){case 4:return e.push(r),!0;case 7:var a=this._scanner.buf().join("");if(5!==(i=this._scanner.read()))return this._error="expected equals",!1;if(6!==(i=this._scanner.read()))return this._error="expected string",!1;var o=this._scanner.buf().join("");r.attributes[a]=o;break;default:return this._error="expected close bracket or identifier",!1}i=this._scanner.read()}},t}();function G_(t,e){for(var i in e)if(e.hasOwnProperty(i)){var n=e[i];n instanceof Object?(t.hasOwnProperty(i)||(t[i]={}),G_(t[i],e[i])):t[i]=n}}function H_(t){if(0===t.length)return null;for(var e={},i=0;i<t.length;++i){var n=t[i],s={};s[n.name]={value:n.value,attributes:n.attributes},G_(e,s)}return e}function W_(t){var e=new V_(t),i=[],n=[];if(!e.parse(i,n))return console.warn(e.error()),{symbols:t,tags:null};var s=n.find((function(t){return null===t.end}));if(s)return console.warn("Markup error: found unclosed tag='"+s.name+"'"),{symbols:t,tags:null};var r=function(t,e){if(0===t.length)return null;for(var i={},n=0;n<t.length;++n){var s=t[n];i.hasOwnProperty(s.start)?null===i[s.start].open?i[s.start].open=[s]:i[s.start].open.push(s):i[s.start]={open:[s],close:null},i.hasOwnProperty(s.end)?null===i[s.end].close?i[s.end].close=[s]:i[s.end].close.push(s):i[s.end]={open:null,close:[s]}}var r=[];function a(t){r=r.filter((function(e){return void 0===t.find((function(t){return t===e}))}))}function o(t){for(var e=0;e<t.length;++e)r.push(t[e])}for(var h=Object.keys(i).sort((function(t,e){return t-e})),l=[],c=0;c<h.length;++c){var u=i[h[c]];null!==u.close&&a(u.close),null!==u.open&&o(u.open),l.push({start:h[c],tags:H_(r)})}for(var d=[],f=null,p=0;p<l.length;++p){for(var m=l[p];d.length<m.start;)d.push(f?f.tags:null);f=m}for(;d.length<e;)d.push(null);return d}(n,i.length);return{symbols:i,tags:r}}var X_=function(){function t(){}return t.evaluate=function(t){return W_(t)},t}(),j_=function(){this.count=0,this.quad=0,this.lines={},this.positions=[],this.normals=[],this.uvs=[],this.colors=[],this.indices=[],this.outlines=[],this.shadows=[],this.meshInstance=null};function q_(t,e){var i=new qa(t);return i.setPositions(e.positions),i.setNormals(e.normals),i.setColors32(e.colors),i.setUvs(0,e.uvs),i.setIndices(e.indices),i.setVertexStream(qe,e.outlines,3,void 0,6,!1),i.setVertexStream(Ye,e.shadows,3,void 0,6,!1),i.update(),i}var Y_=/^[\r\n]$/,K_=/^[ \t]$/,Z_=/^[ \t\-]|[\u200b]$/,Q_=/^[a-z0-9]$/i,$_=/^[\u1100-\u11ff]|[\u3000-\u9fff]|[\ua960-\ua97f]|[\uac00-\ud7ff]$/,J_=/^[〕〉》」』】〙〗〟ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻]$/,tv=["","","","","","","","","","","","",""],ev={width:0,height:0,xadvance:0,xoffset:0,yoffset:0},iv=new vt,nv=new Et,sv=function(){function t(t){this._element=t,this._system=t.system,this._entity=t.entity,this._text="",this._symbols=[],this._colorPalette=[],this._outlinePalette=[],this._shadowPalette=[],this._symbolColors=null,this._symbolOutlineParams=null,this._symbolShadowParams=null,this._i18nKey=null,this._fontAsset=new F_(this._system.app),this._fontAsset.disableLocalization=!0,this._fontAsset.on("load",this._onFontLoad,this),this._fontAsset.on("change",this._onFontChange,this),this._fontAsset.on("remove",this._onFontRemove,this),this._font=null,this._color=new vt(1,1,1,1),this._colorUniform=new Float32Array(3),this._spacing=1,this._fontSize=32,this._fontMinY=0,this._fontMaxY=0,this._originalFontSize=32,this._maxFontSize=32,this._minFontSize=8,this._autoFitWidth=!1,this._autoFitHeight=!1,this._maxLines=-1,this._lineHeight=32,this._scaledLineHeight=32,this._wrapLines=!1,this._drawOrder=0,this._alignment=new Et(.5,.5),this._autoWidth=!0,this._autoHeight=!0,this.width=0,this.height=0,this._node=new hh,this._model=new Gu,this._model.graph=this._node,this._entity.addChild(this._node),this._meshInfo=[],this._material=null,this._aabbDirty=!0,this._aabb=new Ht,this._noResize=!1,this._currentMaterialType=null,this._maskedMaterialSrc=null,this._rtlReorder=!1,this._unicodeConverter=!1,this._rtl=!1,this._outlineColor=new vt(0,0,0,1),this._outlineColorUniform=new Float32Array(4),this._outlineThicknessScale=.2,this._outlineThickness=0,this._shadowColor=new vt(0,0,0,1),this._shadowColorUniform=new Float32Array(4),this._shadowOffsetScale=.005,this._shadowOffset=new Et(0,0),this._shadowOffsetUniform=new Float32Array(2),this._enableMarkup=!1,this._onScreenChange(this._element.screen),t.on("resize",this._onParentResize,this),t.on("set:screen",this._onScreenChange,this),t.on("screen:set:screenspace",this._onScreenSpaceChange,this),t.on("set:draworder",this._onDrawOrderChange,this),t.on("set:pivot",this._onPivotChange,this),this._system.app.i18n.on("set:locale",this._onLocaleSet,this),this._system.app.i18n.on("data:add",this._onLocalizationData,this),this._system.app.i18n.on("data:remove",this._onLocalizationData,this),this._rangeStart=0,this._rangeEnd=0}var e=t.prototype;return e.destroy=function(){this._setMaterial(null),this._model&&(this._element.removeModelFromLayers(this._model),this._model.destroy(),this._model=null),this._fontAsset.destroy(),this.font=null,this._element.off("resize",this._onParentResize,this),this._element.off("set:screen",this._onScreenChange,this),this._element.off("screen:set:screenspace",this._onScreenSpaceChange,this),this._element.off("set:draworder",this._onDrawOrderChange,this),this._element.off("set:pivot",this._onPivotChange,this),this._system.app.i18n.off("set:locale",this._onLocaleSet,this),this._system.app.i18n.off("data:add",this._onLocalizationData,this),this._system.app.i18n.off("data:remove",this._onLocalizationData,this)},e._onParentResize=function(t,e){this._noResize||this._font&&this._updateText()},e._onScreenChange=function(t){t?this._updateMaterial(t.screen.screenSpace):this._updateMaterial(!1)},e._onScreenSpaceChange=function(t){this._updateMaterial(t)},e._onDrawOrderChange=function(t){if(this._drawOrder=t,this._model)for(var e=0,i=this._model.meshInstances.length;e<i;e++)this._model.meshInstances[e].drawOrder=t},e._onPivotChange=function(t){this._font&&this._updateText()},e._onLocaleSet=function(t){if(this._i18nKey){if(this.fontAsset){var e=this._system.app.assets.get(this.fontAsset);e&&e.resource&&e.resource===this._font||(this.font=null)}this._resetLocalizedText()}},e._onLocalizationData=function(t,e){this._i18nKey&&e[this._i18nKey]&&this._resetLocalizedText()},e._resetLocalizedText=function(){this._setText(this._system.app.i18n.getText(this._i18nKey))},e._setText=function(t){if(this.unicodeConverter){var e=this._system.getUnicodeConverter();e?t=e(t):console.warn("Element created with unicodeConverter option but no unicodeConverter function registered")}this._text!==t&&(this._font&&this._updateText(t),this._text=t)},e._updateText=function(t){var e;if(void 0===t&&(t=this._text),this._symbols=rt.getSymbols(t.normalize?t.normalize("NFC"):t),0===this._symbols.length&&(this._symbols=[" "]),this._enableMarkup){var i=X_.evaluate(this._symbols);this._symbols=i.symbols,e=i.tags||[]}if(this._rtlReorder){var n=this._system.app.systems.element.getRtlReorder();if(n){var s=n(this._symbols);this._rtl=s.rtl,this._symbols=s.mapping.map((function(t){return this._symbols[t]}),this),e&&(e=s.mapping.map((function(t){return e[t]})))}else console.warn("Element created with rtlReorder option but no rtlReorder function registered")}else this._rtl=!1;var r=function(t,e){return t.toString(!0).toLowerCase()+":"+e.toFixed(2)},a=function(t,e){return t.toString(!0).toLowerCase()+":"+e.x.toFixed(2)+":"+e.y.toFixed(2)};if(e){var o={},h={},l={};this._colorPalette=[Math.round(255*this._color.r),Math.round(255*this._color.g),Math.round(255*this._color.b)],this._outlinePalette=[Math.round(255*this._outlineColor.r),Math.round(255*this._outlineColor.g),Math.round(255*this._outlineColor.b),Math.round(255*this._outlineColor.a),Math.round(255*this._outlineThickness)],this._shadowPalette=[Math.round(255*this._shadowColor.r),Math.round(255*this._shadowColor.g),Math.round(255*this._shadowColor.b),Math.round(255*this._shadowColor.a),Math.round(127*this._shadowOffset.x),Math.round(127*this._shadowOffset.y)],this._symbolColors=[],this._symbolOutlineParams=[],this._symbolShadowParams=[],o[this._color.toString(!1).toLowerCase()]=0,h[r(this._outlineColor,this._outlineThickness)]=0,l[a(this._shadowColor,this._shadowOffset)]=0;for(var c=0,u=this._symbols.length;c<u;++c){var d=e[c],f=0;if(d&&d.color&&d.color.value){var p=d.color.value;if(7===p.length&&"#"===p[0]){var m=p.substring(1).toLowerCase();o.hasOwnProperty(m)?f=o[m]:/^([0-9a-f]{2}){3}$/.test(m)&&(f=this._colorPalette.length/3,o[m]=f,this._colorPalette.push(parseInt(m.substring(0,2),16)),this._colorPalette.push(parseInt(m.substring(2,4),16)),this._colorPalette.push(parseInt(m.substring(4,6),16)))}}this._symbolColors.push(f);var _=0;if(d&&d.outline&&(d.outline.attributes.color||d.outline.attributes.thickness)){var v=d.outline.attributes.color?iv.fromString(d.outline.attributes.color):this._outlineColor,g=Number(d.outline.attributes.thickness);(Number.isNaN(v.r)||Number.isNaN(v.g)||Number.isNaN(v.b)||Number.isNaN(v.a))&&(v=this._outlineColor),Number.isNaN(g)&&(g=this._outlineThickness);var y=r(v,g);h.hasOwnProperty(y)?_=h[y]:(_=this._outlinePalette.length/5,h[y]=_,this._outlinePalette.push(Math.round(255*v.r),Math.round(255*v.g),Math.round(255*v.b),Math.round(255*v.a),Math.round(255*g)))}this._symbolOutlineParams.push(_);var x=0;if(d&&d.shadow&&(d.shadow.attributes.color||d.shadow.attributes.offset||d.shadow.attributes.offsetX||d.shadow.attributes.offsetY)){var S=d.shadow.attributes.color?iv.fromString(d.shadow.attributes.color):this._shadowColor,b=Number(d.shadow.attributes.offset),w=Number(d.shadow.attributes.offsetX),T=Number(d.shadow.attributes.offsetY);(Number.isNaN(S.r)||Number.isNaN(S.g)||Number.isNaN(S.b)||Number.isNaN(S.a))&&(S=this._shadowColor);var A=nv.set(Number.isNaN(w)?Number.isNaN(b)?this._shadowOffset.x:b:w,Number.isNaN(T)?Number.isNaN(b)?this._shadowOffset.y:b:T),C=a(S,A);l.hasOwnProperty(C)?x=l[C]:(x=this._shadowPalette.length/6,l[C]=x,this._shadowPalette.push(Math.round(255*S.r),Math.round(255*S.g),Math.round(255*S.b),Math.round(255*S.a),Math.round(127*A.x),Math.round(127*A.y)))}this._symbolShadowParams.push(x)}}else this._colorPalette=[],this._symbolColors=null,this._symbolOutlineParams=null,this._symbolShadowParams=null;this._updateMaterialEmissive(),this._updateMaterialOutline(),this._updateMaterialShadow();for(var E=this._calculateCharsPerTexture(),M=!1,P=this._element,R=P._isScreenSpace(),I=P._isScreenCulled(),L=function(t){return P.isVisibleForCamera(t)},D=0,O=this._meshInfo.length;D<O;D++){var k=E[D]||0,F=this._meshInfo[D];if(F.count!==k){if(M||(P.removeModelFromLayers(this._model),M=!0),F.count=k,F.positions.length=F.normals.length=3*k*4,F.indices.length=3*k*2,F.uvs.length=2*k*4,F.colors.length=4*k*4,F.outlines.length=4*k*3,F.shadows.length=4*k*3,F.meshInstance&&this._removeMeshInstance(F.meshInstance),0===k){F.meshInstance=null;continue}for(var B=0;B<k;B++)F.indices[3*B*2+0]=4*B,F.indices[3*B*2+1]=4*B+1,F.indices[3*B*2+2]=4*B+3,F.indices[3*B*2+3]=4*B+2,F.indices[3*B*2+4]=4*B+3,F.indices[3*B*2+5]=4*B+1,F.normals[4*B*3+0]=0,F.normals[4*B*3+1]=0,F.normals[4*B*3+2]=-1,F.normals[4*B*3+3]=0,F.normals[4*B*3+4]=0,F.normals[4*B*3+5]=-1,F.normals[4*B*3+6]=0,F.normals[4*B*3+7]=0,F.normals[4*B*3+8]=-1,F.normals[4*B*3+9]=0,F.normals[4*B*3+10]=0,F.normals[4*B*3+11]=-1;var U=q_(this._system.app.graphicsDevice,F),N=new yh(U,this._material,this._node);if(N.name="Text Element: "+this._entity.name,N.castShadow=!1,N.receiveShadow=!1,N.cull=!R,N.screenSpace=R,N.drawOrder=this._drawOrder,I&&(N.cull=!0,N.isVisibleFunc=L),this._setTextureParams(N,this._font.textures[D]),N.setParameter("material_emissive",this._colorUniform),N.setParameter("material_opacity",this._color.a),N.setParameter("font_sdfIntensity",this._font.intensity),N.setParameter("font_pxrange",this._getPxRange(this._font)),N.setParameter("font_textureWidth",this._font.data.info.maps[D].width),N.setParameter("outline_color",this._outlineColorUniform),N.setParameter("outline_thickness",this._outlineThicknessScale*this._outlineThickness),N.setParameter("shadow_color",this._shadowColorUniform),this._symbolShadowParams)this._shadowOffsetUniform[0]=0,this._shadowOffsetUniform[1]=0;else{var z=-this._font.data.info.maps[D].width/this._font.data.info.maps[D].height;this._shadowOffsetUniform[0]=this._shadowOffsetScale*this._shadowOffset.x,this._shadowOffsetUniform[1]=z*this._shadowOffsetScale*this._shadowOffset.y}N.setParameter("shadow_offset",this._shadowOffsetUniform),F.meshInstance=N,this._model.meshInstances.push(N)}}this._element.maskedBy&&this._element._setMaskedBy(this._element.maskedBy),M&&this._element.enabled&&this._entity.enabled&&this._element.addModelToLayers(this._model),this._updateMeshes(),this._rangeStart=0,this._rangeEnd=this._symbols.length,this._updateRenderRange()},e._removeMeshInstance=function(t){t.destroy();var e=this._model.meshInstances.indexOf(t);-1!==e&&this._model.meshInstances.splice(e,1)},e._setMaterial=function(t){if(this._material=t,this._model)for(var e=0,i=this._model.meshInstances.length;e<i;e++){this._model.meshInstances[e].material=t}},e._updateMaterial=function(t){var e=this._element,i=e._isScreenCulled(),n=function(t){return e.isVisibleForCamera(t)},s=this._font&&this._font.type===B_;if(this._material=this._system.getTextElementMaterial(t,s,this._enableMarkup),this._model)for(var r=0,a=this._model.meshInstances.length;r<a;r++){var o=this._model.meshInstances[r];o.cull=!t,o.material=this._material,o.screenSpace=t,i?(o.cull=!0,o.isVisibleFunc=n):o.isVisibleFunc=null}},e._updateMaterialEmissive=function(){this._symbolColors?(this._colorUniform[0]=1,this._colorUniform[1]=1,this._colorUniform[2]=1):(this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b)},e._updateMaterialOutline=function(){this._symbolOutlineParams?(this._outlineColorUniform[0]=0,this._outlineColorUniform[1]=0,this._outlineColorUniform[2]=0,this._outlineColorUniform[3]=1):(this._outlineColorUniform[0]=this._outlineColor.r,this._outlineColorUniform[1]=this._outlineColor.g,this._outlineColorUniform[2]=this._outlineColor.b,this._outlineColorUniform[3]=this._outlineColor.a)},e._updateMaterialShadow=function(){this._symbolOutlineParams?(this._shadowColorUniform[0]=0,this._shadowColorUniform[1]=0,this._shadowColorUniform[2]=0,this._shadowColorUniform[3]=0):(this._shadowColorUniform[0]=this._shadowColor.r,this._shadowColorUniform[1]=this._shadowColor.g,this._shadowColorUniform[2]=this._shadowColor.b,this._shadowColorUniform[3]=this._shadowColor.a)},e._isWordBoundary=function(t){return Z_.test(t)},e._isValidNextChar=function(t){return null!==t&&!J_.test(t)},e._isNextCJKBoundary=function(t,e){return $_.test(t)&&(Z_.test(e)||Q_.test(e))},e._isNextCJKWholeWord=function(t){return $_.test(t)},e._updateMeshes=function(){var t=this._font.data,e=this,i=Math.min(this._minFontSize,this._maxFontSize),n=this._maxFontSize,s=this._shouldAutoFit();s&&(this._fontSize=this._maxFontSize);var r=this._symbols.length,a=0,o=0,h=0,l=0,c=1,u=0,d=0,f=0,p=0,m=0,_=0,v=Math.abs(this._element.anchor.x-this._element.anchor.z)>=1e-4,g=this._element.calculatedWidth;(this.autoWidth&&!v||!this._wrapLines)&&(g=Number.POSITIVE_INFINITY);var y,x,S,b,w=0,T=0;function A(t,i,n){e._lineWidths.push(Math.abs(n));var s=f>i?i+1:f,r=f>i?f+1:i,h=t.slice(s,r);if(_)for(var l=h.length;l--&&_>0;)Y_.test(h[l])&&(h.splice(l,1),_--);e._lineContents.push(h.join("")),a=0,o-=e._scaledLineHeight,c++,p=0,m=0,_=0,u=0,f=i}for(var C=!0;C;){C=!1,this._scaledLineHeight=s?this._lineHeight*this._fontSize/(this._maxFontSize||1e-4):this._lineHeight,this.width=0,this.height=0,this._lineWidths=[],this._lineContents=[],a=0,o=0,h=0,l=0,c=1,u=0,d=0,f=0,p=0,m=0,_=0;var E=this._fontSize/32;w=this._fontMinY*E,T=this._fontMaxY*E;for(var M=0;M<this._meshInfo.length;M++)this._meshInfo[M].quad=0,this._meshInfo[M].lines={};for(var P=255,R=255,I=255,L=65535,D=65535,O=0,k=65535,F=65535,B=32639,U=0;U<r;U++){if(y=this._symbols[U],b=U+1>=r?null:this._symbols[U+1],Y_.test(y))_++,(!this._wrapLines||this._maxLines<0||c<this._maxLines)&&(A(this._symbols,U,l),d=U+1,f=U+1);else{var N=0,z=0,V=0,G=1,H=void 0;if(!(x=t.chars[y]))if(-1!==tv.indexOf(y))x=ev;else if(t.chars[" "])x=t.chars[" "];else for(var W in t.chars){x=t.chars[W];break}if(x){var X=0;if(m>0){var j=this._font.data.kerning;if(j){var q=j[rt.getCodePoint(this._symbols[U-1])||0];q&&(X=q[rt.getCodePoint(this._symbols[U])||0]||0)}}H=x.scale||1,G=E*((x.width+x.height)/2)/H,V=(x.xadvance+X)*E,N=(x.xoffset-X)*E,z=x.yoffset*E}else console.error("Couldn't substitute missing character: '"+y+"'");var Y=K_.test(y),K=x&&x.map||0,Z=-this._font.data.info.maps[K].width/this._font.data.info.maps[K].height,Q=this._meshInfo[K],$=a+this._spacing*V;if($>g&&m>0&&!Y&&(this._maxLines<0||c<this._maxLines)){if(0!==p){var J=Math.max(U-d,0);if(this._meshInfo.length<=1)Q.lines[c-1]-=J,Q.quad-=J;else for(var tt=U,et=d;et<tt;et++){var it=this._symbols[et],nt=t.chars[it],st=this._meshInfo[nt&&nt.map||0];st.lines[c-1]-=1,st.quad-=1}U-=J+1,A(this._symbols,d,u);continue}d=U,A(this._symbols,U,l)}S=Q.quad,Q.lines[c-1]=S;var at=a-N,ot=at+G,ht=o-z,lt=ht+G;if(this._rtl){var ct=G-N-this._spacing*V-N;at-=ct,ot-=ct}Q.positions[4*S*3+0]=at,Q.positions[4*S*3+1]=ht,Q.positions[4*S*3+2]=h,Q.positions[4*S*3+3]=ot,Q.positions[4*S*3+4]=ht,Q.positions[4*S*3+5]=h,Q.positions[4*S*3+6]=ot,Q.positions[4*S*3+7]=lt,Q.positions[4*S*3+8]=h,Q.positions[4*S*3+9]=at,Q.positions[4*S*3+10]=lt,Q.positions[4*S*3+11]=h,this.width=Math.max(this.width,$);var ut=void 0;if(this._shouldAutoFitWidth()&&this.width>this._element.calculatedWidth&&(ut=Math.floor(this._element.fontSize*this._element.calculatedWidth/(this.width||1e-4)),(ut=_t.clamp(ut,i,n))!==this._element.fontSize)){this._fontSize=ut,C=!0;break}if(this.height=Math.max(this.height,T-(o+w)),this._shouldAutoFitHeight()&&this.height>this._element.calculatedHeight&&(ut=_t.clamp(this._fontSize-1,i,n))!==this._element.fontSize){this._fontSize=ut,C=!0;break}a+=this._spacing*V,Y||(l=a),(this._isWordBoundary(y)||this._isValidNextChar(b)&&(this._isNextCJKBoundary(y,b)||this._isNextCJKWholeWord(b)))&&(p++,u=l,d=U+1),m++;var dt=this._getUv(y);if(Q.uvs[4*S*2+0]=dt[0],Q.uvs[4*S*2+1]=1-dt[1],Q.uvs[4*S*2+2]=dt[2],Q.uvs[4*S*2+3]=1-dt[1],Q.uvs[4*S*2+4]=dt[2],Q.uvs[4*S*2+5]=1-dt[3],Q.uvs[4*S*2+6]=dt[0],Q.uvs[4*S*2+7]=1-dt[3],this._symbolColors){var ft=3*this._symbolColors[U];P=this._colorPalette[ft],R=this._colorPalette[ft+1],I=this._colorPalette[ft+2]}if(Q.colors[4*S*4+0]=P,Q.colors[4*S*4+1]=R,Q.colors[4*S*4+2]=I,Q.colors[4*S*4+3]=255,Q.colors[4*S*4+4]=P,Q.colors[4*S*4+5]=R,Q.colors[4*S*4+6]=I,Q.colors[4*S*4+7]=255,Q.colors[4*S*4+8]=P,Q.colors[4*S*4+9]=R,Q.colors[4*S*4+10]=I,Q.colors[4*S*4+11]=255,Q.colors[4*S*4+12]=P,Q.colors[4*S*4+13]=R,Q.colors[4*S*4+14]=I,Q.colors[4*S*4+15]=255,this._symbolOutlineParams){var pt=5*this._symbolOutlineParams[U];L=this._outlinePalette[pt]+256*this._outlinePalette[pt+1],D=this._outlinePalette[pt+2]+256*this._outlinePalette[pt+3],O=this._outlinePalette[pt+4]}if(Q.outlines[4*S*3+0]=L,Q.outlines[4*S*3+1]=D,Q.outlines[4*S*3+2]=O,Q.outlines[4*S*3+3]=L,Q.outlines[4*S*3+4]=D,Q.outlines[4*S*3+5]=O,Q.outlines[4*S*3+6]=L,Q.outlines[4*S*3+7]=D,Q.outlines[4*S*3+8]=O,Q.outlines[4*S*3+9]=L,Q.outlines[4*S*3+10]=D,Q.outlines[4*S*3+11]=O,this._symbolShadowParams){var mt=6*this._symbolShadowParams[U];k=this._shadowPalette[mt]+256*this._shadowPalette[mt+1],F=this._shadowPalette[mt+2]+256*this._shadowPalette[mt+3],B=this._shadowPalette[mt+4]+127+256*Math.round(Z*this._shadowPalette[mt+5]+127)}Q.shadows[4*S*3+0]=k,Q.shadows[4*S*3+1]=F,Q.shadows[4*S*3+2]=B,Q.shadows[4*S*3+3]=k,Q.shadows[4*S*3+4]=F,Q.shadows[4*S*3+5]=B,Q.shadows[4*S*3+6]=k,Q.shadows[4*S*3+7]=F,Q.shadows[4*S*3+8]=B,Q.shadows[4*S*3+9]=k,Q.shadows[4*S*3+10]=F,Q.shadows[4*S*3+11]=B,Q.quad++}}C||f<r&&A(this._symbols,r,a)}this._noResize=!0,this.autoWidth=this._autoWidth,this.autoHeight=this._autoHeight,this._noResize=!1;for(var vt=this._element.pivot.x,gt=this._element.pivot.y,yt=this._alignment.x,xt=this._alignment.y,St=0;St<this._meshInfo.length;St++)if(0!==this._meshInfo[St].count){var bt=0;for(var wt in this._meshInfo[St].lines){for(var Tt=this._meshInfo[St].lines[wt],At=this._lineWidths[parseInt(wt,10)],Ct=-vt*this._element.calculatedWidth+yt*(this._element.calculatedWidth-At)*(this._rtl?-1:1),Et=(1-gt)*this._element.calculatedHeight-T-(1-xt)*(this._element.calculatedHeight-this.height),Mt=bt;Mt<=Tt;Mt++)this._meshInfo[St].positions[4*Mt*3]+=Ct,this._meshInfo[St].positions[4*Mt*3+3]+=Ct,this._meshInfo[St].positions[4*Mt*3+6]+=Ct,this._meshInfo[St].positions[4*Mt*3+9]+=Ct,this._meshInfo[St].positions[4*Mt*3+1]+=Et,this._meshInfo[St].positions[4*Mt*3+4]+=Et,this._meshInfo[St].positions[4*Mt*3+7]+=Et,this._meshInfo[St].positions[4*Mt*3+10]+=Et;if(this._rtl)for(var Pt=bt;Pt<=Tt;Pt++){for(var Rt=4*Pt*3,It=0;It<4;++It)this._meshInfo[St].positions[Rt+3*It]=this._element.calculatedWidth-this._meshInfo[St].positions[Rt+3*It]+2*Ct;var Lt=this._meshInfo[St].positions[Rt+3],Dt=this._meshInfo[St].positions[Rt+6];this._meshInfo[St].positions[Rt+3]=this._meshInfo[St].positions[Rt+0],this._meshInfo[St].positions[Rt+6]=this._meshInfo[St].positions[Rt+9],this._meshInfo[St].positions[Rt+0]=Lt,this._meshInfo[St].positions[Rt+9]=Dt}bt=Tt+1}for(var Ot=4*this._meshInfo[St].count,kt=4*this._meshInfo[St].quad,Ft=new Lr(this._meshInfo[St].meshInstance.mesh.vertexBuffer),Bt=0;Bt<Ot;Bt++)Bt>=kt?(Ft.element[we].set(0,0,0),Ft.element[Re].set(0,0),Ft.element[Me].set(0,0,0,0),Ft.element[qe].set(0,0,0,0),Ft.element[Ye].set(0,0,0,0)):(Ft.element[we].set(this._meshInfo[St].positions[3*Bt+0],this._meshInfo[St].positions[3*Bt+1],this._meshInfo[St].positions[3*Bt+2]),Ft.element[Re].set(this._meshInfo[St].uvs[2*Bt+0],this._meshInfo[St].uvs[2*Bt+1]),Ft.element[Me].set(this._meshInfo[St].colors[4*Bt+0],this._meshInfo[St].colors[4*Bt+1],this._meshInfo[St].colors[4*Bt+2],this._meshInfo[St].colors[4*Bt+3]),Ft.element[qe].set(this._meshInfo[St].outlines[3*Bt+0],this._meshInfo[St].outlines[3*Bt+1],this._meshInfo[St].outlines[3*Bt+2]),Ft.element[Ye].set(this._meshInfo[St].shadows[3*Bt+0],this._meshInfo[St].shadows[3*Bt+1],this._meshInfo[St].shadows[3*Bt+2])),Ft.next();Ft.end(),this._meshInfo[St].meshInstance.mesh.aabb.compute(this._meshInfo[St].positions),this._meshInfo[St].meshInstance._aabbVer=-1}this._aabbDirty=!0},e._onFontRender=function(){this.font=this._font},e._onFontLoad=function(t){this.font!==t.resource&&(this.font=t.resource)},e._onFontChange=function(t,e,i,n){if("data"===e){this._font.data=i;for(var s=this._font.data.info.maps.length,r=0;r<s;r++)if(this._meshInfo[r]){var a=this._meshInfo[r].meshInstance;a&&(a.setParameter("font_sdfIntensity",this._font.intensity),a.setParameter("font_pxrange",this._getPxRange(this._font)),a.setParameter("font_textureWidth",this._font.data.info.maps[r].width))}}},e._onFontRemove=function(t){},e._setTextureParams=function(t,e){this._font&&(this._font.type===B_?(t.deleteParameter("texture_emissiveMap"),t.deleteParameter("texture_opacityMap"),t.setParameter("texture_msdfMap",e)):this._font.type===U_&&(t.deleteParameter("texture_msdfMap"),t.setParameter("texture_emissiveMap",e),t.setParameter("texture_opacityMap",e)))},e._getPxRange=function(t){for(var e=Object.keys(this._font.data.chars),i=0;i<e.length;i++){var n=this._font.data.chars[e[i]];if(n.range)return(n.scale||1)*n.range}return 2},e._getUv=function(t){var e=this._font.data;if(!e.chars[t]){return e.chars[" "]?this._getUv(" "):[0,0,0,0]}var i=e.chars[t].map,n=e.info.maps[i].width,s=e.info.maps[i].height,r=e.chars[t].x,a=e.chars[t].y,o=r,h=a,l=r+e.chars[t].width,c=a-e.chars[t].height,u=1-e.chars[t].height/s;return[o/n,u-h/s,l/n,u-c/s]},e.onEnable=function(){this._fontAsset.autoLoad=!0,this._model&&this._element.addModelToLayers(this._model)},e.onDisable=function(){this._fontAsset.autoLoad=!1,this._model&&this._element.removeModelFromLayers(this._model)},e._setStencil=function(t){if(this._model)for(var e=this._model.meshInstances,i=0;i<e.length;i++)e[i].stencilFront=t,e[i].stencilBack=t},e._shouldAutoFitWidth=function(){return this._autoFitWidth&&!this._autoWidth},e._shouldAutoFitHeight=function(){return this._autoFitHeight&&!this._autoHeight},e._shouldAutoFit=function(){return this._autoFitWidth&&!this._autoWidth||this._autoFitHeight&&!this._autoHeight},e._calculateCharsPerTexture=function(t){var e={};void 0===t&&(t=this._symbols.length);for(var i=0,n=t;i<n;i++){var s=this._symbols[i],r=this._font.data.chars[s];r||(r=this._font.data.chars[" "])||(r=this._font.data.chars[Object.keys(this._font.data.chars)[0]]);var a=r.map;e[a]?e[a]++:e[a]=1}return e},e._updateRenderRange=function(){for(var t=0===this._rangeStart?0:this._calculateCharsPerTexture(this._rangeStart),e=0===this._rangeEnd?0:this._calculateCharsPerTexture(this._rangeEnd),i=0,n=this._meshInfo.length;i<n;i++){var s=t[i]||0,r=e[i]||0,a=this._meshInfo[i].meshInstance;if(a){var o=a.mesh;o&&(o.primitive[0].base=3*s*2,o.primitive[0].count=3*(r-s)*2)}}},y(t,[{key:"text",get:function(){return this._text},set:function(t){this._i18nKey=null;var e=null!=t&&t.toString()||"";this._setText(e)}},{key:"key",get:function(){return this._i18nKey},set:function(t){var e=null!==t?t.toString():null;this._i18nKey!==e&&(this._i18nKey=e,e?(this._fontAsset.disableLocalization=!1,this._resetLocalizedText()):this._fontAsset.disableLocalization=!0)}},{key:"color",get:function(){return this._color},set:function(t){var e=t.r,i=t.g,n=t.b;if((this._color.r!==e||this._color.g!==i||this._color.b!==n)&&(this._color.r=e,this._color.g=i,this._color.b=n,this._model)){if(this._symbolColors)this._font&&this._updateText();else{this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b;for(var s=0,r=this._model.meshInstances.length;s<r;s++){this._model.meshInstances[s].setParameter("material_emissive",this._colorUniform)}}this._element&&this._element.fire("set:color",this._color)}}},{key:"opacity",get:function(){return this._color.a},set:function(t){if(this._color.a!==t&&(this._color.a=t,this._model))for(var e=0,i=this._model.meshInstances.length;e<i;e++){this._model.meshInstances[e].setParameter("material_opacity",t)}this._element&&this._element.fire("set:opacity",t)}},{key:"lineHeight",get:function(){return this._lineHeight},set:function(t){var e=this._lineHeight;this._lineHeight=t,this._scaledLineHeight=t,e!==t&&this._font&&this._updateText()}},{key:"wrapLines",get:function(){return this._wrapLines},set:function(t){var e=this._wrapLines;this._wrapLines=t,e!==t&&this._font&&this._updateText()}},{key:"lines",get:function(){return this._lineContents}},{key:"spacing",get:function(){return this._spacing},set:function(t){var e=this._spacing;this._spacing=t,e!==t&&this._font&&this._updateText()}},{key:"fontSize",get:function(){return this._fontSize},set:function(t){var e=this._fontSize;this._fontSize=t,this._originalFontSize=t,e!==t&&this._font&&this._updateText()}},{key:"fontAsset",get:function(){return this._fontAsset.localizedAsset},set:function(t){this._fontAsset.defaultAsset=t}},{key:"font",get:function(){return this._font},set:function(t){var e;if(this._font&&(e=this._font.type,this._font.off&&this._font.off("render",this._onFontRender,this)),this._font=t,this._fontMinY=0,this._fontMaxY=0,t){var i=this._font.data;for(var n in i.chars){var s=i.chars[n];s.bounds&&(this._fontMinY=Math.min(this._fontMinY,s.bounds[1]),this._fontMaxY=Math.max(this._fontMaxY,s.bounds[3]))}if(this._font.on&&this._font.on("render",this._onFontRender,this),this._fontAsset.localizedAsset)this._system.app.assets.get(this._fontAsset.localizedAsset).resource!==this._font&&(this._fontAsset.defaultAsset=null);if(t.type!==e){var r=this._element._isScreenSpace();this._updateMaterial(r)}for(var a=0,o=this._font.textures.length;a<o;a++)if(this._meshInfo[a]){var h=this._meshInfo[a].meshInstance;h&&(h.setParameter("font_sdfIntensity",this._font.intensity),h.setParameter("font_pxrange",this._getPxRange(this._font)),h.setParameter("font_textureWidth",this._font.data.info.maps[a].width),this._setTextureParams(h,this._font.textures[a]))}else this._meshInfo[a]=new j_;for(var l=!1,c=this._font.textures.length;c<this._meshInfo.length;c++)this._meshInfo[c].meshInstance&&(l||(this._element.removeModelFromLayers(this._model),l=!0),this._removeMeshInstance(this._meshInfo[c].meshInstance));this._meshInfo.length>this._font.textures.length&&(this._meshInfo.length=this._font.textures.length),this._updateText()}}},{key:"alignment",get:function(){return this._alignment},set:function(t){t instanceof Et?this._alignment.set(t.x,t.y):this._alignment.set(t[0],t[1]),this._font&&this._updateText()}},{key:"autoWidth",get:function(){return this._autoWidth},set:function(t){var e=this._autoWidth;if(this._autoWidth=t,t&&Math.abs(this._element.anchor.x-this._element.anchor.z)<1e-4&&(this._element.width=this.width),e!==t){var i=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;i!==this._fontSize&&(this._fontSize=i,this._font&&this._updateText())}}},{key:"autoHeight",get:function(){return this._autoHeight},set:function(t){var e=this._autoHeight;if(this._autoHeight=t,t&&Math.abs(this._element.anchor.y-this._element.anchor.w)<1e-4&&(this._element.height=this.height),e!==t){var i=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;i!==this._fontSize&&(this._fontSize=i,this._font&&this._updateText())}}},{key:"rtlReorder",get:function(){return this._rtlReorder},set:function(t){this._rtlReorder!==t&&(this._rtlReorder=t,this._font&&this._updateText())}},{key:"unicodeConverter",get:function(){return this._unicodeConverter},set:function(t){this._unicodeConverter!==t&&(this._unicodeConverter=t,this._setText(this._text))}},{key:"aabb",get:function(){if(this._aabbDirty){for(var t=!1,e=0;e<this._meshInfo.length;e++)this._meshInfo[e].meshInstance&&(t?this._aabb.add(this._meshInfo[e].meshInstance.aabb):(this._aabb.copy(this._meshInfo[e].meshInstance.aabb),t=!0));this._aabbDirty=!1}return this._aabb}},{key:"outlineColor",get:function(){return this._outlineColor},set:function(t){var e=t instanceof vt?t.r:t[0],i=t instanceof vt?t.g:t[1],n=t instanceof vt?t.b:t[2],s=t instanceof vt?t.a:t[3];if((this._outlineColor.r!==e||this._outlineColor.g!==i||this._outlineColor.b!==n||this._outlineColor.a!==s)&&(this._outlineColor.r=e,this._outlineColor.g=i,this._outlineColor.b=n,this._outlineColor.a=s,this._model)){if(this._symbolOutlineParams)this._font&&this._updateText();else{this._outlineColorUniform[0]=this._outlineColor.r,this._outlineColorUniform[1]=this._outlineColor.g,this._outlineColorUniform[2]=this._outlineColor.b,this._outlineColorUniform[3]=this._outlineColor.a;for(var r=0,a=this._model.meshInstances.length;r<a;r++){this._model.meshInstances[r].setParameter("outline_color",this._outlineColorUniform)}}this._element&&this._element.fire("set:outline",this._color)}}},{key:"outlineThickness",get:function(){return this._outlineThickness},set:function(t){var e=this._outlineThickness;if(this._outlineThickness=t,e!==t&&this._font){if(!this._model)return;if(this._symbolOutlineParams)this._font&&this._updateText();else for(var i=0,n=this._model.meshInstances.length;i<n;i++){this._model.meshInstances[i].setParameter("outline_thickness",this._outlineThicknessScale*this._outlineThickness)}}}},{key:"shadowColor",get:function(){return this._shadowColor},set:function(t){var e=t instanceof vt?t.r:t[0],i=t instanceof vt?t.g:t[1],n=t instanceof vt?t.b:t[2],s=t instanceof vt?t.a:t[3];if((this._shadowColor.r!==e||this._shadowColor.g!==i||this._shadowColor.b!==n||this._shadowColor.a!==s)&&(this._shadowColor.r=e,this._shadowColor.g=i,this._shadowColor.b=n,this._shadowColor.a=s,this._model))if(this._symbolShadowParams)this._font&&this._updateText();else{this._shadowColorUniform[0]=this._shadowColor.r,this._shadowColorUniform[1]=this._shadowColor.g,this._shadowColorUniform[2]=this._shadowColor.b,this._shadowColorUniform[3]=this._shadowColor.a;for(var r=0,a=this._model.meshInstances.length;r<a;r++){this._model.meshInstances[r].setParameter("shadow_color",this._shadowColorUniform)}}}},{key:"shadowOffset",get:function(){return this._shadowOffset},set:function(t){var e=t instanceof Et?t.x:t[0],i=t instanceof Et?t.y:t[1];if((this._shadowOffset.x!==e||this._shadowOffset.y!==i)&&(this._shadowOffset.set(e,i),this._font&&this._model))if(this._symbolShadowParams)this._updateText();else for(var n=0,s=this._model.meshInstances.length;n<s;n++){var r=-this._font.data.info.maps[n].width/this._font.data.info.maps[n].height;this._shadowOffsetUniform[0]=this._shadowOffsetScale*this._shadowOffset.x,this._shadowOffsetUniform[1]=r*this._shadowOffsetScale*this._shadowOffset.y,this._model.meshInstances[n].setParameter("shadow_offset",this._shadowOffsetUniform)}}},{key:"minFontSize",get:function(){return this._minFontSize},set:function(t){this._minFontSize!==t&&(this._minFontSize=t,this.font&&this._shouldAutoFit()&&this._updateText())}},{key:"maxFontSize",get:function(){return this._maxFontSize},set:function(t){this._maxFontSize!==t&&(this._maxFontSize=t,this.font&&this._shouldAutoFit()&&this._updateText())}},{key:"autoFitWidth",get:function(){return this._autoFitWidth},set:function(t){this._autoFitWidth!==t&&(this._autoFitWidth=t,this._fontSize=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize,this.font&&this._updateText())}},{key:"autoFitHeight",get:function(){return this._autoFitHeight},set:function(t){this._autoFitHeight!==t&&(this._autoFitHeight=t,this._fontSize=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize,this.font&&this._updateText())}},{key:"maxLines",get:function(){return this._maxLines},set:function(t){this._maxLines!==t&&(null===t&&-1===this._maxLines||(this._maxLines=null===t?-1:t,this.font&&this._wrapLines&&this._updateText()))}},{key:"enableMarkup",get:function(){return this._enableMarkup},set:function(t){if(t=!!t,this._enableMarkup!==t){this._enableMarkup=t,this.font&&this._updateText();var e=this._element._isScreenSpace();this._updateMaterial(e)}}},{key:"symbols",get:function(){return this._symbols}},{key:"symbolColors",get:function(){return null===this._symbolColors?null:this._symbolColors.map((function(t){return this._colorPalette.slice(3*t,3*t+3)}),this)}},{key:"symbolOutlineParams",get:function(){return null===this._symbolOutlineParams?null:this._symbolOutlineParams.map((function(t){return this._outlinePalette.slice(5*t,5*t+5)}),this)}},{key:"symbolShadowParams",get:function(){return null===this._symbolShadowParams?null:this._symbolShadowParams.map((function(t){return this._shadowPalette.slice(6*t,6*t+6)}),this)}},{key:"rtl",get:function(){return this._rtl}},{key:"rangeStart",get:function(){return this._rangeStart},set:function(t){(t=Math.max(0,Math.min(t,this._symbols.length)))!==this._rangeStart&&(this._rangeStart=t,this._updateRenderRange())}},{key:"rangeEnd",get:function(){return this._rangeEnd},set:function(t){(t=Math.max(this._rangeStart,Math.min(t,this._symbols.length)))!==this._rangeEnd&&(this._rangeEnd=t,this._updateRenderRange())}}]),t}(),rv=new wt,av=new Ft,ov=new wt,hv=new wt,lv=new Ft,cv=new Ft,uv=new Ft,dv=new Ft,fv=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._beingInitialized=!1,n._anchor=new Pt,n._localAnchor=new Pt,n._pivot=new Et,n._width=n._calculatedWidth=32,n._height=n._calculatedHeight=32,n._margin=new Pt(0,0,-32,-32),n._modelTransform=new Ft,n._screenToWorld=new Ft,n._anchorTransform=new Ft,n._anchorDirty=!0,n._parentWorldTransform=new Ft,n._screenTransform=new Ft,n._screenCorners=[new wt,new wt,new wt,new wt],n._canvasCorners=[new Et,new Et,new Et,new Et],n._worldCorners=[new wt,new wt,new wt,new wt],n._cornersDirty=!0,n._canvasCornersDirty=!0,n._worldCornersDirty=!0,n.entity.on("insert",n._onInsert,w(n)),n._patch(),n.screen=null,n._type=Vm,n._image=null,n._text=null,n._group=null,n._drawOrder=0,n._fitMode=Wm,n._useInput=!1,n._layers=[4],n._addedModels=[],n._batchGroupId=-1,n._offsetReadAt=0,n._maskOffset=.5,n._maskedBy=null,n}S(e,t);var i=e.prototype;return i._patch=function(){this.entity._sync=this._sync,this.entity.setPosition=this._setPosition,this.entity.setLocalPosition=this._setLocalPosition},i._unpatch=function(){this.entity._sync=ip.prototype._sync,this.entity.setPosition=ip.prototype.setPosition,this.entity.setLocalPosition=ip.prototype.setLocalPosition},i._setPosition=function(t,e,i){this.element.screen?(t instanceof wt?rv.copy(t):rv.set(t,e,i),this.getWorldTransform(),av.copy(this.element._screenToWorld).invert(),av.transformPoint(rv,this.localPosition),this._dirtyLocal||this._dirtifyLocal()):ip.prototype.setPosition.call(this,t,e,i)},i._setLocalPosition=function(t,e,i){t instanceof wt?this.localPosition.copy(t):this.localPosition.set(t,e,i);var n=this.element,s=this.localPosition,r=n._pivot;n._margin.x=s.x-n._calculatedWidth*r.x,n._margin.z=n._localAnchor.z-n._localAnchor.x-n._calculatedWidth-n._margin.x,n._margin.y=s.y-n._calculatedHeight*r.y,n._margin.w=n._localAnchor.w-n._localAnchor.y-n._calculatedHeight-n._margin.y,this._dirtyLocal||this._dirtifyLocal()},i._sync=function(){var t=this.element,e=t.screen;if(e){if(t._anchorDirty){var i=0,n=0,s=0,r=1;if(this._parent&&this._parent.element)i=this._parent.element.calculatedWidth,n=this._parent.element.calculatedHeight,s=this._parent.element.pivot.x,r=this._parent.element.pivot.y;else{var a=e.screen.resolution;i=a.x/e.screen.scale,n=a.y/e.screen.scale}t._anchorTransform.setTranslate(i*(t.anchor.x-s),-n*(r-t.anchor.y),0),t._anchorDirty=!1,t._calculateLocalAnchors()}t._sizeDirty&&t._calculateSize(!1,!1)}if(this._dirtyLocal){this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale);var o=this.localPosition,h=t._pivot;t._margin.x=o.x-t._calculatedWidth*h.x,t._margin.z=t._localAnchor.z-t._localAnchor.x-t._calculatedWidth-t._margin.x,t._margin.y=o.y-t._calculatedHeight*h.y,t._margin.w=t._localAnchor.w-t._localAnchor.y-t._calculatedHeight-t._margin.y,this._dirtyLocal=!1}if(!e)return this._dirtyWorld&&(t._cornersDirty=!0,t._canvasCornersDirty=!0,t._worldCornersDirty=!0),void ip.prototype._sync.call(this);if(this._dirtyWorld){if(null===this._parent)this.worldTransform.copy(this.localTransform);else if(this._parent.element?t._screenToWorld.mul2(this._parent.element._modelTransform,t._anchorTransform):t._screenToWorld.copy(t._anchorTransform),t._modelTransform.mul2(t._screenToWorld,this.localTransform),e){t._screenToWorld.mul2(e.screen._screenMatrix,t._screenToWorld),e.screen.screenSpace||t._screenToWorld.mul2(e.worldTransform,t._screenToWorld),this.worldTransform.mul2(t._screenToWorld,this.localTransform);var l=t._parentWorldTransform;l.setIdentity();var c=this._parent;c&&c.element&&c!==e&&(lv.setTRS(wt.ZERO,c.getLocalRotation(),c.getLocalScale()),l.mul2(c.element._parentWorldTransform,lv));var u=ov;u.set(0,0,this.localPosition.z);var d=hv;d.set(t._absLeft+t._pivot.x*t.calculatedWidth,t._absBottom+t._pivot.y*t.calculatedHeight,0),lv.setTranslate(-d.x,-d.y,-d.z),cv.setTRS(u,this.getLocalRotation(),this.getLocalScale()),uv.setTranslate(d.x,d.y,d.z),t._screenTransform.mul2(t._parentWorldTransform,uv).mul(cv).mul(lv),t._cornersDirty=!0,t._canvasCornersDirty=!0,t._worldCornersDirty=!0}else this.worldTransform.copy(t._modelTransform);this._dirtyWorld=!1}},i._onInsert=function(t){var e=this._parseUpToScreen();this.entity._dirtifyWorld(),this._updateScreen(e.screen),this._dirtifyMask()},i._dirtifyMask=function(){for(var t=this.entity;t;){var e=t.parent;if((null===e||e.screen)&&t.element){this.system._prerender&&this.system._prerender.length||(this.system._prerender=[],this.system.app.once("prerender",this._onPrerender,this));var i=this.system._prerender.indexOf(this.entity);i>=0&&this.system._prerender.splice(i,1),this.system._prerender.indexOf(t)<0&&this.system._prerender.push(t)}t=e}},i._onPrerender=function(){for(var t=0;t<this.system._prerender.length;t++){var e=this.system._prerender[t];if(e.element){e.element.syncMask(1)}}this.system._prerender.length=0},i._bindScreen=function(t){t._bindElement(this)},i._unbindScreen=function(t){t._unbindElement(this)},i._updateScreen=function(t){this.screen&&this.screen!==t&&this._unbindScreen(this.screen.screen);var e=this.screen;this.screen=t,this.screen&&this._bindScreen(this.screen.screen),this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY),this.fire("set:screen",this.screen,e),this._anchorDirty=!0;for(var i=this.entity.children,n=0,s=i.length;n<s;n++)i[n].element&&i[n].element._updateScreen(t);this.screen&&this.screen.screen.syncDrawOrder()},i.syncMask=function(t){var e=this._parseUpToScreen();this._updateMask(e.mask,t)},i._setMaskedBy=function(t){var e=this._image||this._text;if(t){var i=t.element._image._maskRef;null==e||e._setStencil(new en({ref:i,func:2})),this._maskedBy=t}else null==e||e._setStencil(null),this._maskedBy=null},i._updateMask=function(t,e){if(t){if(this._setMaskedBy(t),this.mask){var i=t.element._image._maskRef,n=new en({ref:i,func:2,zpass:3});this._image._setStencil(n),this._image._maskRef=e,e++,t=this.entity}for(var s=this.entity.children,r=0,a=s.length;r<a;r++){var o;null==(o=s[r].element)||o._updateMask(t,e)}this.mask&&e--}else{if(this._setMaskedBy(null),this.mask){var h=new en({ref:e,func:7,zpass:2});this._image._setStencil(h),this._image._maskRef=e,e++,t=this.entity}for(var l=this.entity.children,c=0,u=l.length;c<u;c++){var d;null==(d=l[c].element)||d._updateMask(t,e)}this.mask&&e--}},i._parseUpToScreen=function(){for(var t={screen:null,mask:null},e=this.entity._parent;e&&!e.screen;)e.element&&e.element.mask&&(t.mask||(t.mask=e)),e=e.parent;return e&&e.screen&&(t.screen=e),t},i._onScreenResize=function(t){this._anchorDirty=!0,this._cornersDirty=!0,this._worldCornersDirty=!0,this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY),this.fire("screen:set:resolution",t)},i._onScreenSpaceChange=function(){this.fire("screen:set:screenspace",this.screen.screen.screenSpace)},i._onScreenRemove=function(){this.screen&&(this.screen._destroying?this.screen=null:this._updateScreen(null))},i._calculateLocalAnchors=function(){var t=1e3,e=1e3,i=this.entity._parent;if(i&&i.element)t=i.element.calculatedWidth,e=i.element.calculatedHeight;else if(this.screen){var n=this.screen.screen.resolution,s=this.screen.screen.scale;t=n.x/s,e=n.y/s}this._localAnchor.set(this._anchor.x*t,this._anchor.y*e,this._anchor.z*t,this._anchor.w*e)},i.getOffsetPosition=function(t,e){var i=this.entity.getLocalPosition().clone();return i.x+=t,i.y+=e,this._screenToWorld.transformPoint(i,i),i},i.onLayersChanged=function(t,e){this.addModelToLayers(this._image?this._image._renderable.model:this._text._model),t.off("add",this.onLayerAdded,this),t.off("remove",this.onLayerRemoved,this),e.on("add",this.onLayerAdded,this),e.on("remove",this.onLayerRemoved,this)},i.onLayerAdded=function(t){this.layers.indexOf(t.id)<0||(this._image?t.addMeshInstances(this._image._renderable.model.meshInstances):this._text&&t.addMeshInstances(this._text._model.meshInstances))},i.onLayerRemoved=function(t){this.layers.indexOf(t.id)<0||(this._image?t.removeMeshInstances(this._image._renderable.model.meshInstances):this._text&&t.removeMeshInstances(this._text._model.meshInstances))},i.onEnable=function(){var t;(this._image&&this._image.onEnable(),this._text&&this._text.onEnable(),this._group&&this._group.onEnable(),this.useInput&&this.system.app.elementInput&&this.system.app.elementInput.addElement(this),this.system.app.scene.on("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.on("add",this.onLayerAdded,this),this.system.app.scene.layers.on("remove",this.onLayerRemoved,this)),this._batchGroupId>=0)&&(null==(t=this.system.app.batcher)||t.insert(Ho.ELEMENT,this.batchGroupId,this.entity));this.fire("enableelement")},i.onDisable=function(){var t;(this.system.app.scene.off("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.off("add",this.onLayerAdded,this),this.system.app.scene.layers.off("remove",this.onLayerRemoved,this)),this._image&&this._image.onDisable(),this._text&&this._text.onDisable(),this._group&&this._group.onDisable(),this.system.app.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this),this._batchGroupId>=0)&&(null==(t=this.system.app.batcher)||t.remove(Ho.ELEMENT,this.batchGroupId,this.entity));this.fire("disableelement")},i.onRemove=function(){this.entity.off("insert",this._onInsert,this),this._unpatch(),this._image&&this._image.destroy(),this._text&&this._text.destroy(),this.system.app.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this),this.screen&&this.screen.screen&&(this._unbindScreen(this.screen.screen),this.screen.screen.syncDrawOrder()),this.off()},i._calculateSize=function(t,e){if(this.entity._parent||this.screen){this._calculateLocalAnchors();var i=this._absRight-this._absLeft,n=this._absTop-this._absBottom;t?this._setWidth(i):this._setCalculatedWidth(i,!1),e?this._setHeight(n):this._setCalculatedHeight(n,!1);var s=this.entity.getLocalPosition();s.x=this._margin.x+this._calculatedWidth*this._pivot.x,s.y=this._margin.y+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(s),this._sizeDirty=!1}},i._setWidth=function(t){this._width=t,this._setCalculatedWidth(t,!1),this.fire("set:width",this._width)},i._setHeight=function(t){this._height=t,this._setCalculatedHeight(t,!1),this.fire("set:height",this._height)},i._setCalculatedWidth=function(t,e){if(!(Math.abs(t-this._calculatedWidth)<=1e-4)){if(this._calculatedWidth=t,this.entity._dirtifyLocal(),e){var i=this.entity.getLocalPosition(),n=this._pivot;this._margin.x=i.x-this._calculatedWidth*n.x,this._margin.z=this._localAnchor.z-this._localAnchor.x-this._calculatedWidth-this._margin.x}this._flagChildrenAsDirty(),this.fire("set:calculatedWidth",this._calculatedWidth),this.fire("resize",this._calculatedWidth,this._calculatedHeight)}},i._setCalculatedHeight=function(t,e){if(!(Math.abs(t-this._calculatedHeight)<=1e-4)){if(this._calculatedHeight=t,this.entity._dirtifyLocal(),e){var i=this.entity.getLocalPosition(),n=this._pivot;this._margin.y=i.y-this._calculatedHeight*n.y,this._margin.w=this._localAnchor.w-this._localAnchor.y-this._calculatedHeight-this._margin.y}this._flagChildrenAsDirty(),this.fire("set:calculatedHeight",this._calculatedHeight),this.fire("resize",this._calculatedWidth,this._calculatedHeight)}},i._flagChildrenAsDirty=function(){for(var t=this.entity._children,e=0,i=t.length;e<i;e++)t[e].element&&(t[e].element._anchorDirty=!0,t[e].element._sizeDirty=!0)},i.addModelToLayers=function(t){this._addedModels.push(t);for(var e=0;e<this.layers.length;e++){var i=this.system.app.scene.layers.getLayerById(this.layers[e]);i&&i.addMeshInstances(t.meshInstances)}},i.removeModelFromLayers=function(t){var e=this._addedModels.indexOf(t);e>=0&&this._addedModels.splice(e,1);for(var i=0;i<this.layers.length;i++){var n=this.system.app.scene.layers.getLayerById(this.layers[i]);n&&n.removeMeshInstances(t.meshInstances)}},i.getMaskOffset=function(){var t=this.system.app.frame;this._offsetReadAt!==t&&(this._maskOffset=.5,this._offsetReadAt=t);var e=this._maskOffset;return this._maskOffset-=.001,e},i.isVisibleForCamera=function(t){var e,i,n,s;if(this.maskedBy){var r=this.maskedBy.element.screenCorners;e=Math.min(Math.min(r[0].x,r[1].x),Math.min(r[2].x,r[3].x)),i=Math.max(Math.max(r[0].x,r[1].x),Math.max(r[2].x,r[3].x)),s=Math.min(Math.min(r[0].y,r[1].y),Math.min(r[2].y,r[3].y)),n=Math.max(Math.max(r[0].y,r[1].y),Math.max(r[2].y,r[3].y))}else{var a=this.system.app.graphicsDevice.width,o=this.system.app.graphicsDevice.height,h=t._rect.z*a,l=t._rect.w*o;i=(e=t._rect.x*a)+h,s=(n=(1-t._rect.y)*o)-l}var c=this.screenCorners,u=Math.min(Math.min(c[0].x,c[1].x),Math.min(c[2].x,c[3].x)),d=Math.max(Math.max(c[0].x,c[1].x),Math.max(c[2].x,c[3].x)),f=Math.min(Math.min(c[0].y,c[1].y),Math.min(c[2].y,c[3].y)),p=Math.max(Math.max(c[0].y,c[1].y),Math.max(c[2].y,c[3].y));return!(d<e||u>i||f>n||p<s)},i._isScreenSpace=function(){return!(!this.screen||!this.screen.screen)&&this.screen.screen.screenSpace},i._isScreenCulled=function(){return!(!this.screen||!this.screen.screen)&&this.screen.screen.cull},i._dirtyBatch=function(){var t;-1!==this.batchGroupId&&(null==(t=this.system.app.batcher)||t.markGroupDirty(this.batchGroupId))},y(e,[{key:"_absLeft",get:function(){return this._localAnchor.x+this._margin.x}},{key:"_absRight",get:function(){return this._localAnchor.z-this._margin.z}},{key:"_absTop",get:function(){return this._localAnchor.w-this._margin.w}},{key:"_absBottom",get:function(){return this._localAnchor.y+this._margin.y}},{key:"_hasSplitAnchorsX",get:function(){return Math.abs(this._anchor.x-this._anchor.z)>.001}},{key:"_hasSplitAnchorsY",get:function(){return Math.abs(this._anchor.y-this._anchor.w)>.001}},{key:"aabb",get:function(){return this._image?this._image.aabb:this._text?this._text.aabb:null}},{key:"anchor",get:function(){return this._anchor},set:function(t){var e;t instanceof Pt?this._anchor.copy(t):(e=this._anchor).set.apply(e,t);this.entity._parent||this.screen?this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY):this._calculateLocalAnchors(),this._anchorDirty=!0,this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:anchor",this._anchor)}},{key:"batchGroupId",get:function(){return this._batchGroupId},set:function(t){if(this._batchGroupId!==t){var e,i;if(this.entity.enabled&&this._batchGroupId>=0)null==(e=this.system.app.batcher)||e.remove(Ho.ELEMENT,this.batchGroupId,this.entity);if(this.entity.enabled&&t>=0)null==(i=this.system.app.batcher)||i.insert(Ho.ELEMENT,t,this.entity);t<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&(this._image&&this._image._renderable.model?this.addModelToLayers(this._image._renderable.model):this._text&&this._text._model&&this.addModelToLayers(this._text._model)),this._batchGroupId=t}}},{key:"bottom",get:function(){return this._margin.y},set:function(t){this._margin.y=t;var e=this.entity.getLocalPosition(),i=this._absTop,n=this._localAnchor.y+t;this._setHeight(i-n),e.y=t+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(e)}},{key:"calculatedWidth",get:function(){return this._calculatedWidth},set:function(t){this._setCalculatedWidth(t,!0)}},{key:"calculatedHeight",get:function(){return this._calculatedHeight},set:function(t){this._setCalculatedHeight(t,!0)}},{key:"canvasCorners",get:function(){if(!this._canvasCornersDirty||!this.screen||!this.screen.screen.screenSpace)return this._canvasCorners;for(var t=this.system.app.graphicsDevice,e=this.screenCorners,i=t.canvas.clientWidth/t.width,n=t.canvas.clientHeight/t.height,s=0;s<4;s++)this._canvasCorners[s].set(e[s].x*i,(t.height-e[s].y)*n);return this._canvasCornersDirty=!1,this._canvasCorners}},{key:"drawOrder",get:function(){return this._drawOrder},set:function(t){var e=0;this.screen&&(e=this.screen.screen.priority),t>16777215&&(t=16777215),this._drawOrder=(e<<24)+t,this.fire("set:draworder",this._drawOrder)}},{key:"height",get:function(){return this._height},set:function(t){this._height=t,this._hasSplitAnchorsY||this._setCalculatedHeight(t,!0),this.fire("set:height",this._height)}},{key:"layers",get:function(){return this._layers},set:function(t){if(this._addedModels.length)for(var e=0;e<this._layers.length;e++){var i=this.system.app.scene.layers.getLayerById(this._layers[e]);if(i)for(var n=0;n<this._addedModels.length;n++)i.removeMeshInstances(this._addedModels[n].meshInstances)}if(this._layers=t,this.enabled&&this.entity.enabled&&this._addedModels.length)for(var s=0;s<this._layers.length;s++){var r=this.system.app.scene.layers.getLayerById(this._layers[s]);if(r)for(var a=0;a<this._addedModels.length;a++)r.addMeshInstances(this._addedModels[a].meshInstances)}}},{key:"left",get:function(){return this._margin.x},set:function(t){this._margin.x=t;var e=this.entity.getLocalPosition(),i=this._absRight,n=this._localAnchor.x+t;this._setWidth(i-n),e.x=t+this._calculatedWidth*this._pivot.x,this.entity.setLocalPosition(e)}},{key:"margin",get:function(){return this._margin},set:function(t){this._margin.copy(t),this._calculateSize(!0,!0),this.fire("set:margin",this._margin)}},{key:"maskedBy",get:function(){return this._maskedBy}},{key:"pivot",get:function(){return this._pivot},set:function(t){var e=this.pivot,i=this.margin,n=e.x,s=e.y;t instanceof Et?e.copy(t):e.set.apply(e,t);var r=i.x+i.z,a=e.x-n;i.x+=r*a,i.z-=r*a;var o=i.y+i.w,h=e.y-s;i.y+=o*h,i.w-=o*h,this._anchorDirty=!0,this._cornersDirty=!0,this._worldCornersDirty=!0,this._calculateSize(!1,!1),this._flagChildrenAsDirty(),this.fire("set:pivot",e)}},{key:"right",get:function(){return this._margin.z},set:function(t){this._margin.z=t;var e=this.entity.getLocalPosition(),i=this._absLeft,n=this._localAnchor.z-t;this._setWidth(n-i),e.x=this._localAnchor.z-this._localAnchor.x-t-this._calculatedWidth*(1-this._pivot.x),this.entity.setLocalPosition(e)}},{key:"screenCorners",get:function(){if(!this._cornersDirty||!this.screen)return this._screenCorners;var t=this.entity.parent&&this.entity.parent.element&&this.entity.parent.element.screenCorners[0];this._screenCorners[0].set(this._absLeft,this._absBottom,0),this._screenCorners[1].set(this._absRight,this._absBottom,0),this._screenCorners[2].set(this._absRight,this._absTop,0),this._screenCorners[3].set(this._absLeft,this._absTop,0);for(var e=this.screen.screen.screenSpace,i=0;i<4;i++)this._screenTransform.transformPoint(this._screenCorners[i],this._screenCorners[i]),e&&this._screenCorners[i].mulScalar(this.screen.screen.scale),t&&this._screenCorners[i].add(t);return this._cornersDirty=!1,this._canvasCornersDirty=!0,this._worldCornersDirty=!0,this._screenCorners}},{key:"textWidth",get:function(){return this._text?this._text.width:0}},{key:"textHeight",get:function(){return this._text?this._text.height:0}},{key:"top",get:function(){return this._margin.w},set:function(t){this._margin.w=t;var e=this.entity.getLocalPosition(),i=this._absBottom,n=this._localAnchor.w-t;this._setHeight(n-i),e.y=this._localAnchor.w-this._localAnchor.y-t-this._calculatedHeight*(1-this._pivot.y),this.entity.setLocalPosition(e)}},{key:"type",get:function(){return this._type},set:function(t){t!==this._type&&(this._type=t,this._image&&(this._image.destroy(),this._image=null),this._text&&(this._text.destroy(),this._text=null),t===Gm?this._image=new k_(this):t===Hm&&(this._text=new sv(this)))}},{key:"useInput",get:function(){return this._useInput},set:function(t){this._useInput!==t&&(this._useInput=t,this.system.app.elementInput?t?this.enabled&&this.entity.enabled&&this.system.app.elementInput.addElement(this):this.system.app.elementInput.removeElement(this):this._useInput,this.fire("set:useInput",t))}},{key:"fitMode",get:function(){return this._fitMode},set:function(t){this._fitMode=t,this._calculateSize(!0,!0),this._image&&this._image.refreshMesh()}},{key:"width",get:function(){return this._width},set:function(t){this._width=t,this._hasSplitAnchorsX||this._setCalculatedWidth(t,!0),this.fire("set:width",this._width)}},{key:"worldCorners",get:function(){if(!this._worldCornersDirty)return this._worldCorners;if(this.screen){var t=this.screenCorners;if(!this.screen.screen.screenSpace){lv.copy(this.screen.screen._screenMatrix),lv.data[13]=-lv.data[13],lv.mul2(this.screen.getWorldTransform(),lv);for(var e=0;e<4;e++)lv.transformPoint(t[e],this._worldCorners[e])}}else{var i=this.entity.getLocalPosition();lv.setTranslate(-i.x,-i.y,-i.z),cv.setTRS(wt.ZERO,this.entity.getLocalRotation(),this.entity.getLocalScale()),uv.setTranslate(i.x,i.y,i.z);var n=this.entity.parent?this.entity.parent:this.entity;dv.copy(n.getWorldTransform()),dv.mul(uv).mul(cv).mul(lv),ov.set(i.x-this.pivot.x*this.calculatedWidth,i.y-this.pivot.y*this.calculatedHeight,i.z),dv.transformPoint(ov,this._worldCorners[0]),ov.set(i.x+(1-this.pivot.x)*this.calculatedWidth,i.y-this.pivot.y*this.calculatedHeight,i.z),dv.transformPoint(ov,this._worldCorners[1]),ov.set(i.x+(1-this.pivot.x)*this.calculatedWidth,i.y+(1-this.pivot.y)*this.calculatedHeight,i.z),dv.transformPoint(ov,this._worldCorners[2]),ov.set(i.x-this.pivot.x*this.calculatedWidth,i.y+(1-this.pivot.y)*this.calculatedHeight,i.z),dv.transformPoint(ov,this._worldCorners[3])}return this._worldCornersDirty=!1,this._worldCorners}}]),e}(bp);function pv(t){Object.defineProperty(fv.prototype,t,{get:function(){return this._text?this._text[t]:this._image?this._image[t]:null},set:function(e){this._text?(this._text[t]!==e&&this._dirtyBatch(),this._text[t]=e):this._image&&(this._image[t]!==e&&this._dirtyBatch(),this._image[t]=e)}})}pv("fontSize"),pv("minFontSize"),pv("maxFontSize"),pv("maxLines"),pv("autoFitWidth"),pv("autoFitHeight"),pv("color"),pv("font"),pv("fontAsset"),pv("spacing"),pv("lineHeight"),pv("wrapLines"),pv("lines"),pv("alignment"),pv("autoWidth"),pv("autoHeight"),pv("rtlReorder"),pv("unicodeConverter"),pv("text"),pv("key"),pv("texture"),pv("textureAsset"),pv("material"),pv("materialAsset"),pv("sprite"),pv("spriteAsset"),pv("spriteFrame"),pv("pixelsPerUnit"),pv("opacity"),pv("rect"),pv("mask"),pv("outlineColor"),pv("outlineThickness"),pv("shadowColor"),pv("shadowOffset"),pv("enableMarkup"),pv("rangeStart"),pv("rangeEnd");var mv=function(){this.enabled=!0},_v=["enabled"],vv=function(t){function e(e){var i;(i=t.call(this,e)||this).id="element",i.ComponentType=fv,i.DataType=mv,i.schema=_v,i._unicodeConverter=null,i._rtlReorder=null,i._defaultTexture=new Ls(e.graphicsDevice,{width:1,height:1,format:7,name:"element-system"});var n=i._defaultTexture.lock(),s=new Uint8Array(4);return s[0]=255,s[1]=255,s[2]=255,s[3]=255,n.set(s),i._defaultTexture.unlock(),i.defaultImageMaterial=null,i.defaultImage9SlicedMaterial=null,i.defaultImage9TiledMaterial=null,i.defaultImageMaskMaterial=null,i.defaultImage9SlicedMaskMaterial=null,i.defaultImage9TiledMaskMaterial=null,i.defaultScreenSpaceImageMaterial=null,i.defaultScreenSpaceImage9SlicedMaterial=null,i.defaultScreenSpaceImage9TiledMaterial=null,i.defaultScreenSpaceImageMask9SlicedMaterial=null,i.defaultScreenSpaceImageMask9TiledMaterial=null,i.defaultScreenSpaceImageMaskMaterial=null,i._defaultTextMaterials={},i.defaultImageMaterials=[],i.on("beforeremove",i.onRemoveComponent,w(i)),i}S(e,t);var i=e.prototype;return i.destroy=function(){t.prototype.destroy.call(this),this._defaultTexture.destroy()},i.initializeComponentData=function(e,i,n){e._beingInitialized=!0,void 0!==i.anchor&&(i.anchor instanceof Pt?e.anchor.copy(i.anchor):e.anchor.set(i.anchor[0],i.anchor[1],i.anchor[2],i.anchor[3])),void 0!==i.pivot&&(i.pivot instanceof Et?e.pivot.copy(i.pivot):e.pivot.set(i.pivot[0],i.pivot[1]));var s,r=Math.abs(e.anchor.x-e.anchor.z)>.001,a=Math.abs(e.anchor.y-e.anchor.w)>.001,o=!1;void 0!==i.margin&&(i.margin instanceof Pt?e.margin.copy(i.margin):e._margin.set(i.margin[0],i.margin[1],i.margin[2],i.margin[3]),o=!0),void 0!==i.left&&(e._margin.x=i.left,o=!0),void 0!==i.bottom&&(e._margin.y=i.bottom,o=!0),void 0!==i.right&&(e._margin.z=i.right,o=!0),void 0!==i.top&&(e._margin.w=i.top,o=!0),o&&(e.margin=e._margin);var h=!1;void 0===i.width||r?r&&(h=!0):e.width=i.width,void 0===i.height||a?a&&(h=!0):e.height=i.height,h&&(e.anchor=e.anchor),void 0!==i.enabled&&(e.enabled=i.enabled),void 0!==i.useInput&&(e.useInput=i.useInput),void 0!==i.fitMode&&(e.fitMode=i.fitMode),e.batchGroupId=void 0===i.batchGroupId||null===i.batchGroupId?-1:i.batchGroupId,i.layers&&Array.isArray(i.layers)&&(e.layers=i.layers.slice(0)),void 0!==i.type&&(e.type=i.type),e.type===Gm?(void 0!==i.rect&&(e.rect=i.rect),void 0!==i.color&&((s=i.color)instanceof vt||(s=new vt(i.color[0],i.color[1],i.color[2])),e.color=s),void 0!==i.opacity&&(e.opacity=i.opacity),void 0!==i.textureAsset&&(e.textureAsset=i.textureAsset),i.texture&&(e.texture=i.texture),void 0!==i.spriteAsset&&(e.spriteAsset=i.spriteAsset),i.sprite&&(e.sprite=i.sprite),void 0!==i.spriteFrame&&(e.spriteFrame=i.spriteFrame),void 0!==i.pixelsPerUnit&&null!==i.pixelsPerUnit&&(e.pixelsPerUnit=i.pixelsPerUnit),void 0!==i.materialAsset&&(e.materialAsset=i.materialAsset),i.material&&(e.material=i.material),void 0!==i.mask&&(e.mask=i.mask)):e.type===Hm&&(void 0!==i.autoWidth&&(e.autoWidth=i.autoWidth),void 0!==i.autoHeight&&(e.autoHeight=i.autoHeight),void 0!==i.rtlReorder&&(e.rtlReorder=i.rtlReorder),void 0!==i.unicodeConverter&&(e.unicodeConverter=i.unicodeConverter),null!==i.text&&void 0!==i.text?e.text=i.text:null!==i.key&&void 0!==i.key&&(e.key=i.key),void 0!==i.color&&((s=i.color)instanceof vt||(s=new vt(s[0],s[1],s[2])),e.color=s),void 0!==i.opacity&&(e.opacity=i.opacity),void 0!==i.spacing&&(e.spacing=i.spacing),void 0!==i.fontSize&&(e.fontSize=i.fontSize,i.lineHeight||(e.lineHeight=i.fontSize)),void 0!==i.lineHeight&&(e.lineHeight=i.lineHeight),void 0!==i.maxLines&&(e.maxLines=i.maxLines),void 0!==i.wrapLines&&(e.wrapLines=i.wrapLines),void 0!==i.minFontSize&&(e.minFontSize=i.minFontSize),void 0!==i.maxFontSize&&(e.maxFontSize=i.maxFontSize),i.autoFitWidth&&(e.autoFitWidth=i.autoFitWidth),i.autoFitHeight&&(e.autoFitHeight=i.autoFitHeight),void 0!==i.fontAsset&&(e.fontAsset=i.fontAsset),void 0!==i.font&&(e.font=i.font),void 0!==i.alignment&&(e.alignment=i.alignment),void 0!==i.outlineColor&&(e.outlineColor=i.outlineColor),void 0!==i.outlineThickness&&(e.outlineThickness=i.outlineThickness),void 0!==i.shadowColor&&(e.shadowColor=i.shadowColor),void 0!==i.shadowOffset&&(e.shadowOffset=i.shadowOffset),void 0!==i.enableMarkup&&(e.enableMarkup=i.enableMarkup));var l=e._parseUpToScreen();l.screen&&e._updateScreen(l.screen),t.prototype.initializeComponentData.call(this,e,i,n),e._beingInitialized=!1,e.type===Gm&&e._image._meshDirty&&e._image._updateMesh(e._image.mesh)},i.onRemoveComponent=function(t,e){e.onRemove()},i.cloneComponent=function(t,e){var i=t.element,n={enabled:i.enabled,width:i.width,height:i.height,anchor:i.anchor.clone(),pivot:i.pivot.clone(),margin:i.margin.clone(),alignment:i.alignment&&i.alignment.clone()||i.alignment,autoWidth:i.autoWidth,autoHeight:i.autoHeight,type:i.type,rect:i.rect&&i.rect.clone()||i.rect,rtlReorder:i.rtlReorder,unicodeConverter:i.unicodeConverter,materialAsset:i.materialAsset,material:i.material,color:i.color&&i.color.clone()||i.color,opacity:i.opacity,textureAsset:i.textureAsset,texture:i.texture,spriteAsset:i.spriteAsset,sprite:i.sprite,spriteFrame:i.spriteFrame,pixelsPerUnit:i.pixelsPerUnit,spacing:i.spacing,lineHeight:i.lineHeight,wrapLines:i.wrapLines,layers:i.layers,fontSize:i.fontSize,minFontSize:i.minFontSize,maxFontSize:i.maxFontSize,autoFitWidth:i.autoFitWidth,autoFitHeight:i.autoFitHeight,maxLines:i.maxLines,fontAsset:i.fontAsset,font:i.font,useInput:i.useInput,fitMode:i.fitMode,batchGroupId:i.batchGroupId,mask:i.mask,outlineColor:i.outlineColor&&i.outlineColor.clone()||i.outlineColor,outlineThickness:i.outlineThickness,shadowColor:i.shadowColor&&i.shadowColor.clone()||i.shadowColor,shadowOffset:i.shadowOffset&&i.shadowOffset.clone()||i.shadowOffset,enableMarkup:i.enableMarkup};return void 0!==i.key&&null!==i.key?n.key=i.key:n.text=i.text,this.addComponent(e,n)},i.getTextElementMaterial=function(t,e,i){var n=(t&&1)|(e&&2)|(i&&4),s=this._defaultTextMaterials[n];if(s)return s;var r="TextMaterial";return s=new lu,e?(s.msdfMap=this._defaultTexture,s.msdfTextAttribute=i,s.emissive.set(1,1,1)):(r="Bitmap"+r,s.emissive.set(.5,.5,.5),s.emissiveMap=this._defaultTexture,s.emissiveTint=!0,s.opacityMap=this._defaultTexture,s.opacityMapChannel="a"),t&&(r="ScreenSpace"+r,s.depthTest=!1),s.name="default"+r,s.useLighting=!1,s.useGammaTonemap=!1,s.useFog=!1,s.useSkybox=!1,s.diffuse.set(0,0,0),s.opacity=.5,s.blendType=4,s.depthWrite=!1,s.emissiveVertexColor=!0,s.update(),this._defaultTextMaterials[n]=s,s},i._createBaseImageMaterial=function(){var t=new lu;return t.diffuse.set(0,0,0),t.emissive.set(.5,.5,.5),t.emissiveMap=this._defaultTexture,t.emissiveTint=!0,t.opacityMap=this._defaultTexture,t.opacityMapChannel="a",t.opacityTint=!0,t.opacity=0,t.useLighting=!1,t.useGammaTonemap=!1,t.useFog=!1,t.useSkybox=!1,t.blendType=4,t.depthWrite=!1,t},i.getImageElementMaterial=function(t,e,i,n){return t?e?i?(this.defaultScreenSpaceImageMask9SlicedMaterial||(this.defaultScreenSpaceImageMask9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMask9SlicedMaterial.name="defaultScreenSpaceImageMask9SlicedMaterial",this.defaultScreenSpaceImageMask9SlicedMaterial.nineSlicedMode=1,this.defaultScreenSpaceImageMask9SlicedMaterial.depthTest=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9SlicedMaterial.redWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.greenWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.blueWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9SlicedMaterial)),this.defaultScreenSpaceImageMask9SlicedMaterial):n?(this.defaultScreenSpaceImageMask9TiledMaterial||(this.defaultScreenSpaceImageMask9TiledMaterial=this.defaultScreenSpaceImage9TiledMaterial.clone(),this.defaultScreenSpaceImageMask9TiledMaterial.name="defaultScreenSpaceImageMask9TiledMaterial",this.defaultScreenSpaceImageMask9TiledMaterial.nineSlicedMode=2,this.defaultScreenSpaceImageMask9TiledMaterial.depthTest=!1,this.defaultScreenSpaceImageMask9TiledMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9TiledMaterial.redWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.greenWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.blueWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9TiledMaterial)),this.defaultScreenSpaceImageMask9TiledMaterial):(this.defaultScreenSpaceImageMaskMaterial||(this.defaultScreenSpaceImageMaskMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaskMaterial.name="defaultScreenSpaceImageMaskMaterial",this.defaultScreenSpaceImageMaskMaterial.depthTest=!1,this.defaultScreenSpaceImageMaskMaterial.alphaTest=1,this.defaultScreenSpaceImageMaskMaterial.redWrite=!1,this.defaultScreenSpaceImageMaskMaterial.greenWrite=!1,this.defaultScreenSpaceImageMaskMaterial.blueWrite=!1,this.defaultScreenSpaceImageMaskMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaskMaterial)),this.defaultScreenSpaceImageMaskMaterial):i?(this.defaultScreenSpaceImage9SlicedMaterial||(this.defaultScreenSpaceImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9SlicedMaterial.name="defaultScreenSpaceImage9SlicedMaterial",this.defaultScreenSpaceImage9SlicedMaterial.nineSlicedMode=1,this.defaultScreenSpaceImage9SlicedMaterial.depthTest=!1,this.defaultScreenSpaceImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9SlicedMaterial)),this.defaultScreenSpaceImage9SlicedMaterial):n?(this.defaultScreenSpaceImage9TiledMaterial||(this.defaultScreenSpaceImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9TiledMaterial.name="defaultScreenSpaceImage9TiledMaterial",this.defaultScreenSpaceImage9TiledMaterial.nineSlicedMode=2,this.defaultScreenSpaceImage9TiledMaterial.depthTest=!1,this.defaultScreenSpaceImage9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9TiledMaterial)),this.defaultScreenSpaceImage9TiledMaterial):(this.defaultScreenSpaceImageMaterial||(this.defaultScreenSpaceImageMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaterial.name="defaultScreenSpaceImageMaterial",this.defaultScreenSpaceImageMaterial.depthTest=!1,this.defaultScreenSpaceImageMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaterial)),this.defaultScreenSpaceImageMaterial):e?i?(this.defaultImage9SlicedMaskMaterial||(this.defaultImage9SlicedMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaskMaterial.name="defaultImage9SlicedMaskMaterial",this.defaultImage9SlicedMaskMaterial.nineSlicedMode=1,this.defaultImage9SlicedMaskMaterial.alphaTest=1,this.defaultImage9SlicedMaskMaterial.redWrite=!1,this.defaultImage9SlicedMaskMaterial.greenWrite=!1,this.defaultImage9SlicedMaskMaterial.blueWrite=!1,this.defaultImage9SlicedMaskMaterial.alphaWrite=!1,this.defaultImage9SlicedMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaskMaterial)),this.defaultImage9SlicedMaskMaterial):n?(this.defaultImage9TiledMaskMaterial||(this.defaultImage9TiledMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaskMaterial.name="defaultImage9TiledMaskMaterial",this.defaultImage9TiledMaskMaterial.nineSlicedMode=2,this.defaultImage9TiledMaskMaterial.alphaTest=1,this.defaultImage9TiledMaskMaterial.redWrite=!1,this.defaultImage9TiledMaskMaterial.greenWrite=!1,this.defaultImage9TiledMaskMaterial.blueWrite=!1,this.defaultImage9TiledMaskMaterial.alphaWrite=!1,this.defaultImage9TiledMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9TiledMaskMaterial)),this.defaultImage9TiledMaskMaterial):(this.defaultImageMaskMaterial||(this.defaultImageMaskMaterial=this._createBaseImageMaterial(),this.defaultImageMaskMaterial.name="defaultImageMaskMaterial",this.defaultImageMaskMaterial.alphaTest=1,this.defaultImageMaskMaterial.redWrite=!1,this.defaultImageMaskMaterial.greenWrite=!1,this.defaultImageMaskMaterial.blueWrite=!1,this.defaultImageMaskMaterial.alphaWrite=!1,this.defaultImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImageMaskMaterial)),this.defaultImageMaskMaterial):i?(this.defaultImage9SlicedMaterial||(this.defaultImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaterial.name="defaultImage9SlicedMaterial",this.defaultImage9SlicedMaterial.nineSlicedMode=1,this.defaultImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaterial)),this.defaultImage9SlicedMaterial):n?(this.defaultImage9TiledMaterial||(this.defaultImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaterial.name="defaultImage9TiledMaterial",this.defaultImage9TiledMaterial.nineSlicedMode=2,this.defaultImage9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9TiledMaterial)),this.defaultImage9TiledMaterial):(this.defaultImageMaterial||(this.defaultImageMaterial=this._createBaseImageMaterial(),this.defaultImageMaterial.name="defaultImageMaterial",this.defaultImageMaterial.update(),this.defaultImageMaterials.push(this.defaultImageMaterial)),this.defaultImageMaterial)},i.registerUnicodeConverter=function(t){this._unicodeConverter=t},i.registerRtlReorder=function(t){this._rtlReorder=t},i.getUnicodeConverter=function(){return this._unicodeConverter},i.getRtlReorder=function(){return this._rtlReorder},e}(wp);bp._buildAccessors(fv.prototype,_v);var gv="free",yv="limited",xv="locked",Sv=["angularDampingX","angularDampingY","angularDampingZ","angularEquilibriumX","angularEquilibriumY","angularEquilibriumZ","angularLimitsX","angularLimitsY","angularLimitsZ","angularMotionX","angularMotionY","angularMotionZ","angularSpringX","angularSpringY","angularSpringZ","angularStiffnessX","angularStiffnessY","angularStiffnessZ","breakForce","enableCollision","enabled","entityA","entityB","linearDampingX","linearDampingY","linearDampingZ","linearEquilibriumX","linearEquilibriumY","linearEquilibriumZ","linearLimitsX","linearLimitsY","linearLimitsZ","linearMotionX","linearMotionY","linearMotionZ","linearSpringX","linearSpringY","linearSpringZ","linearStiffnessX","linearStiffnessY","linearStiffnessZ"],bv=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._constraint=null,n._entityA=null,n._entityB=null,n._breakForce=34e37,n._enableCollision=!0,n._linearMotionX=xv,n._linearLimitsX=new Et(0,0),n._linearSpringX=!1,n._linearStiffnessX=0,n._linearDampingX=1,n._linearEquilibriumX=0,n._linearMotionY=xv,n._linearLimitsY=new Et(0,0),n._linearSpringY=!1,n._linearStiffnessY=0,n._linearDampingY=1,n._linearEquilibriumY=0,n._linearMotionZ=xv,n._linearLimitsZ=new Et(0,0),n._linearSpringZ=!1,n._linearStiffnessZ=0,n._linearDampingZ=1,n._linearEquilibriumZ=0,n._angularMotionX=xv,n._angularLimitsX=new Et(0,0),n._angularSpringX=!1,n._angularStiffnessX=0,n._angularDampingX=1,n._angularEquilibriumX=0,n._angularMotionY=xv,n._angularLimitsY=new Et(0,0),n._angularSpringY=!1,n._angularStiffnessY=0,n._angularDampingY=1,n._angularEquilibriumY=0,n._angularMotionZ=xv,n._angularLimitsZ=new Et(0,0),n._angularSpringZ=!1,n._angularEquilibriumZ=0,n._angularDampingZ=1,n._angularStiffnessZ=0,n.on("set_enabled",n._onSetEnabled,w(n)),n}S(e,t);var i=e.prototype;return i._convertTransform=function(t,e){var i=t.getTranslation(),n=new Bt;n.setFromMat4(t);var s=new Ammo.btVector3(i.x,i.y,i.z),r=new Ammo.btQuaternion(n.x,n.y,n.z,n.w);e.setOrigin(s),e.setRotation(r),Ammo.destroy(s),Ammo.destroy(r)},i._updateAngularLimits=function(){var t=this._constraint;if(t){var e,i,n,s,r,a;this._angularMotionX===yv?(e=this._angularLimitsX.x*_t.DEG_TO_RAD,s=this._angularLimitsX.y*_t.DEG_TO_RAD):this._angularMotionX===gv?(e=1,s=0):e=s=0,this._angularMotionY===yv?(i=this._angularLimitsY.x*_t.DEG_TO_RAD,r=this._angularLimitsY.y*_t.DEG_TO_RAD):this._angularMotionY===gv?(i=1,r=0):i=r=0,this._angularMotionZ===yv?(n=this._angularLimitsZ.x*_t.DEG_TO_RAD,a=this._angularLimitsZ.y*_t.DEG_TO_RAD):this._angularMotionZ===gv?(n=1,a=0):n=a=0;var o=new Ammo.btVector3(e,i,n);t.setAngularLowerLimit(o),o.setValue(s,r,a),t.setAngularUpperLimit(o),Ammo.destroy(o)}},i._updateLinearLimits=function(){var t=this._constraint;if(t){var e,i,n,s,r,a;this._linearMotionX===yv?(e=this._linearLimitsX.x,s=this._linearLimitsX.y):this._linearMotionX===gv?(e=1,s=0):e=s=0,this._linearMotionY===yv?(i=this._linearLimitsY.x,r=this._linearLimitsY.y):this._linearMotionY===gv?(i=1,r=0):i=r=0,this._linearMotionZ===yv?(n=this._linearLimitsZ.x,a=this._linearLimitsZ.y):this._linearMotionZ===gv?(n=1,a=0):n=a=0;var o=new Ammo.btVector3(e,i,n);t.setLinearLowerLimit(o),o.setValue(s,r,a),t.setLinearUpperLimit(o),Ammo.destroy(o)}},i._createConstraint=function(){if(this._entityA&&this._entityA.rigidbody){this._destroyConstraint();var t=new Ft,e=this._entityA.rigidbody.body;e.activate();var i=this.entity.getWorldTransform(),n=this._entityA.getWorldTransform().clone().invert();t.mul2(n,i);var s=new Ammo.btTransform;if(this._convertTransform(t,s),this._entityB&&this._entityB.rigidbody){var r=this._entityB.rigidbody.body;r.activate();var a=this._entityB.getWorldTransform().clone().invert();t.mul2(a,i);var o=new Ammo.btTransform;this._convertTransform(t,o),this._constraint=new Ammo.btGeneric6DofSpringConstraint(e,r,s,o,!this._enableCollision),Ammo.destroy(o)}else this._constraint=new Ammo.btGeneric6DofSpringConstraint(e,s,!this._enableCollision);Ammo.destroy(s);for(var h=["X","Y","Z","X","Y","Z"],l=0;l<6;l++){var c=l<3?"_linear":"_angular";this._constraint.enableSpring(l,this[c+"Spring"+h[l]]),this._constraint.setDamping(l,this[c+"Damping"+h[l]]),this._constraint.setEquilibriumPoint(l,this[c+"Equilibrium"+h[l]]),this._constraint.setStiffness(l,this[c+"Stiffness"+h[l]])}this._constraint.setBreakingImpulseThreshold(this._breakForce),this._updateLinearLimits(),this._updateAngularLimits(),this.system.app.systems.rigidbody.dynamicsWorld.addConstraint(this._constraint,!this._enableCollision)}},i._destroyConstraint=function(){this._constraint&&(this.system.app.systems.rigidbody.dynamicsWorld.removeConstraint(this._constraint),Ammo.destroy(this._constraint),this._constraint=null)},i.initFromData=function(t){for(var e=0,i=Sv;e<i.length;e++){var n=i[e];t.hasOwnProperty(n)&&(t[n]instanceof Et?this["_"+n].copy(t[n]):this["_"+n]=t[n])}this._createConstraint()},i.onEnable=function(){this._createConstraint()},i.onDisable=function(){this._destroyConstraint()},i._onSetEnabled=function(t,e,i){},i._onBeforeRemove=function(){this.fire("remove")},y(e,[{key:"entityA",get:function(){return this._entityA},set:function(t){this._destroyConstraint(),this._entityA=t,this._createConstraint()}},{key:"entityB",get:function(){return this._entityB},set:function(t){this._destroyConstraint(),this._entityB=t,this._createConstraint()}},{key:"breakForce",get:function(){return this._breakForce},set:function(t){this._constraint&&this._breakForce!==t&&(this._constraint.setBreakingImpulseThreshold(t),this._breakForce=t)}},{key:"enableCollision",get:function(){return this._enableCollision},set:function(t){this._destroyConstraint(),this._enableCollision=t,this._createConstraint()}},{key:"angularLimitsX",get:function(){return this._angularLimitsX},set:function(t){this._angularLimitsX.equals(t)||(this._angularLimitsX.copy(t),this._updateAngularLimits())}},{key:"angularMotionX",get:function(){return this._angularMotionX},set:function(t){this._angularMotionX!==t&&(this._angularMotionX=t,this._updateAngularLimits())}},{key:"angularLimitsY",get:function(){return this._angularLimitsY},set:function(t){this._angularLimitsY.equals(t)||(this._angularLimitsY.copy(t),this._updateAngularLimits())}},{key:"angularMotionY",get:function(){return this._angularMotionY},set:function(t){this._angularMotionY!==t&&(this._angularMotionY=t,this._updateAngularLimits())}},{key:"angularLimitsZ",get:function(){return this._angularLimitsZ},set:function(t){this._angularLimitsZ.equals(t)||(this._angularLimitsZ.copy(t),this._updateAngularLimits())}},{key:"angularMotionZ",get:function(){return this._angularMotionZ},set:function(t){this._angularMotionZ!==t&&(this._angularMotionZ=t,this._updateAngularLimits())}},{key:"linearLimitsX",get:function(){return this._linearLimitsX},set:function(t){this._linearLimitsX.equals(t)||(this._linearLimitsX.copy(t),this._updateLinearLimits())}},{key:"linearMotionX",get:function(){return this._linearMotionX},set:function(t){this._linearMotionX!==t&&(this._linearMotionX=t,this._updateLinearLimits())}},{key:"linearLimitsY",get:function(){return this._linearLimitsY},set:function(t){this._linearLimitsY.equals(t)||(this._linearLimitsY.copy(t),this._updateLinearLimits())}},{key:"linearMotionY",get:function(){return this._linearMotionY},set:function(t){this._linearMotionY!==t&&(this._linearMotionY=t,this._updateLinearLimits())}},{key:"linearLimitsZ",get:function(){return this._linearLimitsZ},set:function(t){this._linearLimitsZ.equals(t)||(this._linearLimitsZ.copy(t),this._updateLinearLimits())}},{key:"linearMotionZ",get:function(){return this._linearMotionZ},set:function(t){this._linearMotionZ!==t&&(this._linearMotionZ=t,this._updateLinearLimits())}}]),e}(bp),wv={Damping:"setDamping",Equilibrium:"setEquilibriumPoint",Spring:"enableSpring",Stiffness:"setStiffness"};["linear","angular"].forEach((function(t){["Damping","Equilibrium","Spring","Stiffness"].forEach((function(e){["X","Y","Z"].forEach((function(i){var n=t+e+i,s="_"+n,r="linear"===t?0:3;"Y"===i&&(r+=1),"Z"===i&&(r+=2),Object.defineProperty(bv.prototype,n,{get:function(){return this[s]},set:function(t){this[s]!==t&&(this[s]=t,this._constraint[wv[e]](r,t))}})}))}))}));var Tv=function(){this.enabled=!0},Av=["enabled"],Cv=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="joint",i.app=e,i.ComponentType=bv,i.DataType=Tv,i.schema=Av,i}return S(e,t),e.prototype.initializeComponentData=function(t,e,i){t.initFromData(e)},e}(wp);bp._buildAccessors(bv.prototype,Av);var Ev=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._minWidth=0,n._minHeight=0,n._maxWidth=null,n._maxHeight=null,n._fitWidthProportion=0,n._fitHeightProportion=0,n._excludeFromLayout=!1,n}return S(e,t),y(e,[{key:"minWidth",get:function(){return this._minWidth},set:function(t){t!==this._minWidth&&(this._minWidth=t,this.fire("resize"))}},{key:"minHeight",get:function(){return this._minHeight},set:function(t){t!==this._minHeight&&(this._minHeight=t,this.fire("resize"))}},{key:"maxWidth",get:function(){return this._maxWidth},set:function(t){t!==this._maxWidth&&(this._maxWidth=t,this.fire("resize"))}},{key:"maxHeight",get:function(){return this._maxHeight},set:function(t){t!==this._maxHeight&&(this._maxHeight=t,this.fire("resize"))}},{key:"fitWidthProportion",get:function(){return this._fitWidthProportion},set:function(t){t!==this._fitWidthProportion&&(this._fitWidthProportion=t,this.fire("resize"))}},{key:"fitHeightProportion",get:function(){return this._fitHeightProportion},set:function(t){t!==this._fitHeightProportion&&(this._fitHeightProportion=t,this.fire("resize"))}},{key:"excludeFromLayout",get:function(){return this._excludeFromLayout},set:function(t){t!==this._excludeFromLayout&&(this._excludeFromLayout=t,this.fire("resize"))}}]),e}(bp),Mv=function(){this.enabled=!0},Pv=["enabled"],Rv=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="layoutchild",i.ComponentType=Ev,i.DataType=Mv,i.schema=Pv,i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){void 0!==i.enabled&&(e.enabled=i.enabled),void 0!==i.minWidth&&(e.minWidth=i.minWidth),void 0!==i.minHeight&&(e.minHeight=i.minHeight),void 0!==i.maxWidth&&(e.maxWidth=i.maxWidth),void 0!==i.maxHeight&&(e.maxHeight=i.maxHeight),void 0!==i.fitWidthProportion&&(e.fitWidthProportion=i.fitWidthProportion),void 0!==i.fitHeightProportion&&(e.fitHeightProportion=i.fitHeightProportion),void 0!==i.excludeFromLayout&&(e.excludeFromLayout=i.excludeFromLayout),t.prototype.initializeComponentData.call(this,e,i,n)},i.cloneComponent=function(t,e){var i=t.layoutchild;return this.addComponent(e,{enabled:i.enabled,minWidth:i.minWidth,minHeight:i.minHeight,maxWidth:i.maxWidth,maxHeight:i.maxHeight,fitWidthProportion:i.fitWidthProportion,fitHeightProportion:i.fitHeightProportion,excludeFromLayout:i.excludeFromLayout})},e}(wp);bp._buildAccessors(Ev.prototype,Pv);var Iv={0:{axis:"x",size:"width",calculatedSize:"calculatedWidth",minSize:"minWidth",maxSize:"maxWidth",fitting:"widthFitting",fittingProportion:"fitWidthProportion"},1:{axis:"y",size:"height",calculatedSize:"calculatedHeight",minSize:"minHeight",maxSize:"maxHeight",fitting:"heightFitting",fittingProportion:"fitHeightProportion"}},Lv={0:1,1:0},Dv={minWidth:0,minHeight:0,maxWidth:Number.POSITIVE_INFINITY,maxHeight:Number.POSITIVE_INFINITY,width:null,height:null,fitWidthProportion:0,fitHeightProportion:0},Ov="NONE",kv="APPLY_STRETCHING",Fv="APPLY_SHRINKING",Bv=new Et;function Uv(t){var e,i=Iv[t],n=Iv[Lv[t]];function s(t,e){return-e[i.size]*t.pivot[i.axis]}function r(t,e){return-e[n.size]*t.pivot[n.axis]}function a(t,e){return e[i.size]*(1-t.pivot[i.axis])}function o(t){var e=t.entity.layoutchild;return!e||!e.enabled||!e.excludeFromLayout}function h(t,e,i){switch(t){case 0:return Ov;case 1:return e<i?kv:Ov;case 2:return e>=i?Fv:Ov;case 3:return e<i?kv:Fv;default:throw new Error("Unrecognized fitting mode: "+t)}}function l(t,i){return _(t,i.size)+(t.length-1)*e.spacing[i.axis]}function c(t,e,i){for(var n=g(t,i.maxSize),s=v(t,i.fittingProportion),r=S(s,n),a=Bv[i.axis]-e,o=0;o<t.length;++o){var h=n[o],l=d(h,a,s,r),c=t[h][i.size]+l,u=t[h][i.maxSize],f=Math.min(c,u);t[h][i.size]=f,a-=l-Math.max(c-f,0)}}function u(t,e,i){for(var n=g(t,i.minSize,!0),s=function(t){if(1===t.length)return[1];for(var e=[],i=t.length,n=0;n<i;++n)e.push((1-t[n])/(i-1));return e}(v(t,i.fittingProportion)),r=S(s,n),a=e-Bv[i.axis],o=0;o<t.length;++o){var h=n[o],l=d(h,a,s,r),c=t[h][i.size]-l,u=t[h][i.minSize],f=Math.max(c,u);t[h][i.size]=f,a-=l-Math.max(f-c,0)}}function d(t,e,i,n){var s=i[t],r=n[t];return Math.abs(s)<1e-5&&Math.abs(r)<1e-5?e:e*s/r}function f(t){for(var e=[],i=0;i<t.length;++i){var n=t[i],s=Math.max(p(n,"minWidth"),0),r=Math.max(p(n,"minHeight"),0),a=Math.max(p(n,"maxWidth"),s),o=Math.max(p(n,"maxHeight"),r),h=m(p(n,"width"),s,a),l=m(p(n,"height"),r,o),c=p(n,"fitWidthProportion"),u=p(n,"fitHeightProportion");e.push({minWidth:s,minHeight:r,maxWidth:a,maxHeight:o,width:h,height:l,fitWidthProportion:c,fitHeightProportion:u})}return e}function p(t,e){var i=t.entity.layoutchild;return i&&i.enabled&&void 0!==i[e]&&null!==i[e]?i[e]:void 0!==t[e]?t[e]:Dv[e]}function m(t,e,i){return Math.min(Math.max(t,e),i)}function _(t,e){return t.reduce((function(t,i){return t+i[e]}),0)}function v(t,e){var i=_(t,e),n=[],s=t.length;if(0===i)for(var r=0;r<s;++r)n.push(1/s);else for(var a=0;a<s;++a)n.push(t[a][e]/i);return n}function g(t,e,i){return t.forEach(y),t.slice().sort((function(t,n){return i?n[e]-t[e]:t[e]-n[e]})).map(x)}function y(t,e){t.index=e}function x(t){return t.index}function S(t,e){var i=[];i[e[t.length-1]]=t[e[t.length-1]];for(var n=t.length-2;n>=0;--n)i[e[n]]=i[e[n+1]]+t[e[n]];return i}return function(t,d){t=t.filter(o),e=d,Bv.x=e.containerSize.x-e.padding.x-e.padding.z,Bv.y=e.containerSize.y-e.padding.y-e.padding.w,function(t){for(var e=0;e<t.length;++e){var i=t[e],n=i.anchor;0===n.x&&0===n.y&&0===n.z&&0===n.w||(i.anchor=Pt.ZERO)}}(t);var p=function(t){var i=0===e.orientation&&e.reverseX||1===e.orientation&&e.reverseY,n=0===e.orientation&&e.reverseY||1===e.orientation&&e.reverseX;if(i)for(var s=0;s<t.length;++s)i&&t[s].reverse();n&&t.reverse();return t}(function(t){if(!e.wrap)return[t];for(var n=[[]],s=f(t),r=0,a=2===e[i.fitting],o=0;o<t.length;++o){n[n.length-1].length>0&&(r+=e.spacing[i.axis]);var h=s[o][i.size];r+=h,!a&&r>Bv[i.axis]&&0!==n[n.length-1].length&&(r=h,n.push([])),n[n.length-1].push(t[o]),a&&r>Bv[i.axis]&&o!==t.length-1&&(r=0,n.push([]))}return n}(t)),m=function(t,i){for(var s=[],r=[],a=0;a<t.length;++a){var o=t[a];o.largestElement=null,o.largestSize={width:Number.NEGATIVE_INFINITY,height:Number.NEGATIVE_INFINITY};for(var d=0;d<o.length;++d){var f=i[a][d];f[n.size]>o.largestSize[n.size]&&(o.largestElement=o[d],o.largestSize=f)}s.push(o.largestElement),r.push(o.largestSize)}var p=l(r,n),m=h(e[n.fitting],p,Bv[n.axis]);m===kv?c(r,p,n):m===Fv&&u(r,p,n);for(var _=0;_<t.length;++_)for(var v=t[_],g=0;g<v.length;++g){var y=i[_][g],x=y[n.size],S=1===t.length?Bv[n.axis]:v.largestSize[n.size],b=h(e[n.fitting],x,S);b===kv?y[n.size]=Math.min(S,y[n.maxSize]):b===Fv&&(y[n.size]=Math.max(S,y[n.minSize]))}return i}(p,function(t){for(var n=[],s=0;s<t.length;++s){var r=f(t[s]),a=l(r,i),o=h(e[i.fitting],a,Bv[i.axis]);o===kv?c(r,a,i):o===Fv&&u(r,a,i),n.push(r)}return n}(p)),_=function(t,o){var h={};h[i.axis]=0,h[n.axis]=0,t[i.size]=Number.NEGATIVE_INFINITY;for(var l=[],c=0;c<t.length;++c){var u=t[c];if(0!==u.length){for(var d=[],f=o[c],p=0;p<u.length;++p){var m=u[p],_=f[p];h[n.axis]-=r(m,_),h[i.axis]-=s(m,_),d[p]={},d[p][i.axis]=h[i.axis],d[p][n.axis]=h[n.axis],h[n.axis]+=r(m,_),h[i.axis]+=a(m,_)+e.spacing[i.axis]}u[i.size]=h[i.axis]-e.spacing[i.axis],u[n.size]=u.largestSize[n.size],t[i.size]=Math.max(t[i.size],u[i.size]),h[i.axis]=0,h[n.axis]+=u[n.size]+e.spacing[n.axis],l.push(d)}else l.push([])}return t[n.size]=h[n.axis]-e.spacing[n.axis],l}(p,m);return function(t,s,r){for(var a=e.alignment[i.axis],o=e.alignment[n.axis],h=e.padding[i.axis],l=e.padding[n.axis],c=0;c<t.length;++c)for(var u=t[c],d=s[c],f=r[c],p=(Bv[i.axis]-u[i.size])*a+h,m=(Bv[n.axis]-t[n.size])*o+l,_=0;_<u.length;++_){var v=(u[n.size]-d[_][n.size])*e.alignment[n.axis];f[_][i.axis]+=p,f[_][n.axis]+=m+v}}(p,m,_),function(t,s,r){for(var a=0;a<t.length;++a)for(var o=t[a],h=s[a],l=r[a],c=0;c<o.length;++c){var u=o[c];u[i.calculatedSize]=h[c][i.size],u[n.calculatedSize]=h[c][n.size],0===e.orientation?u.entity.setLocalPosition(l[c][i.axis],l[c][n.axis],u.entity.getLocalPosition().z):u.entity.setLocalPosition(l[c][n.axis],l[c][i.axis],u.entity.getLocalPosition().z)}}(p,m,_),function(t){var i=t.width,n=t.height,s=(Bv.x-i)*e.alignment.x+e.padding.x,r=(Bv.y-n)*e.alignment.y+e.padding.y;return{bounds:new Pt(s,r,i,n)}}(p)}}var Nv={};Nv[0]=Uv(0),Nv[1]=Uv(1);var zv=function(){function t(){}return t.prototype.calculateLayout=function(t,e){var i=Nv[e.orientation];if(i)return i(t,e);throw new Error("Unrecognized orientation value: "+e.orientation)},t}();function Vv(t){return t.element}function Gv(t){return t.enabled&&t.element&&t.element.enabled}var Hv=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._orientation=0,n._reverseX=!1,n._reverseY=!0,n._alignment=new Et(0,1),n._padding=new Pt,n._spacing=new Et,n._widthFitting=0,n._heightFitting=0,n._wrap=!1,n._layoutCalculator=new zv,n._listenForReflowEvents(n.entity,"on"),n.entity.children.forEach((function(t){n._listenForReflowEvents(t,"on")})),n.entity.on("childinsert",n._onChildInsert,w(n)),n.entity.on("childremove",n._onChildRemove,w(n)),e.app.systems.element.on("add",n._onElementOrLayoutComponentAdd,w(n)),e.app.systems.element.on("beforeremove",n._onElementOrLayoutComponentRemove,w(n)),e.app.systems.layoutchild.on("add",n._onElementOrLayoutComponentAdd,w(n)),e.app.systems.layoutchild.on("beforeremove",n._onElementOrLayoutComponentRemove,w(n)),n}S(e,t);var i=e.prototype;return i._isSelfOrChild=function(t){return t===this.entity||-1!==this.entity.children.indexOf(t)},i._listenForReflowEvents=function(t,e){t.element&&(t.element[e]("enableelement",this._scheduleReflow,this),t.element[e]("disableelement",this._scheduleReflow,this),t.element[e]("resize",this._scheduleReflow,this),t.element[e]("set:pivot",this._scheduleReflow,this)),t.layoutchild&&(t.layoutchild[e]("set_enabled",this._scheduleReflow,this),t.layoutchild[e]("resize",this._scheduleReflow,this))},i._onElementOrLayoutComponentAdd=function(t){this._isSelfOrChild(t)&&(this._listenForReflowEvents(t,"on"),this._scheduleReflow())},i._onElementOrLayoutComponentRemove=function(t){this._isSelfOrChild(t)&&(this._listenForReflowEvents(t,"off"),this._scheduleReflow())},i._onChildInsert=function(t){this._listenForReflowEvents(t,"on"),this._scheduleReflow()},i._onChildRemove=function(t){this._listenForReflowEvents(t,"off"),this._scheduleReflow()},i._scheduleReflow=function(){this.enabled&&this.entity&&this.entity.enabled&&!this._isPerformingReflow&&this.system.scheduleReflow(this)},i.reflow=function(){var t=Vv(this.entity),e=this.entity.children.filter(Gv).map(Vv);if(t&&0!==e.length){var i=Math.max(t.calculatedWidth,0),n=Math.max(t.calculatedHeight,0),s={orientation:this._orientation,reverseX:this._reverseX,reverseY:this._reverseY,alignment:this._alignment,padding:this._padding,spacing:this._spacing,widthFitting:this._widthFitting,heightFitting:this._heightFitting,wrap:this._wrap,containerSize:new Et(i,n)};this._isPerformingReflow=!0;var r=this._layoutCalculator.calculateLayout(e,s);this._isPerformingReflow=!1,this.fire("reflow",r)}},i.onEnable=function(){this._scheduleReflow()},i.onRemove=function(){var t=this;this.entity.off("childinsert",this._onChildInsert,this),this.entity.off("childremove",this._onChildRemove,this),this._listenForReflowEvents(this.entity,"off"),this.entity.children.forEach((function(e){t._listenForReflowEvents(e,"off")})),this.system.app.systems.element.off("add",this._onElementOrLayoutComponentAdd,this),this.system.app.systems.element.off("beforeremove",this._onElementOrLayoutComponentRemove,this),this.system.app.systems.layoutchild.off("add",this._onElementOrLayoutComponentAdd,this),this.system.app.systems.layoutchild.off("beforeremove",this._onElementOrLayoutComponentRemove,this)},y(e,[{key:"orientation",get:function(){return this._orientation},set:function(t){t!==this._orientation&&(this._orientation=t,this._scheduleReflow())}},{key:"reverseX",get:function(){return this._reverseX},set:function(t){t!==this._reverseX&&(this._reverseX=t,this._scheduleReflow())}},{key:"reverseY",get:function(){return this._reverseY},set:function(t){t!==this._reverseY&&(this._reverseY=t,this._scheduleReflow())}},{key:"alignment",get:function(){return this._alignment},set:function(t){t.equals(this._alignment)||(this._alignment.copy(t),this._scheduleReflow())}},{key:"padding",get:function(){return this._padding},set:function(t){t.equals(this._padding)||(this._padding.copy(t),this._scheduleReflow())}},{key:"spacing",get:function(){return this._spacing},set:function(t){t.equals(this._spacing)||(this._spacing.copy(t),this._scheduleReflow())}},{key:"widthFitting",get:function(){return this._widthFitting},set:function(t){t!==this._widthFitting&&(this._widthFitting=t,this._scheduleReflow())}},{key:"heightFitting",get:function(){return this._heightFitting},set:function(t){t!==this._heightFitting&&(this._heightFitting=t,this._scheduleReflow())}},{key:"wrap",get:function(){return this._wrap},set:function(t){t!==this._wrap&&(this._wrap=t,this._scheduleReflow())}}]),e}(bp),Wv=function(){this.enabled=!0},Xv=["enabled"],jv=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="layoutgroup",i.ComponentType=Hv,i.DataType=Wv,i.schema=Xv,i._reflowQueue=[],i.on("beforeremove",i._onRemoveComponent,w(i)),i.app.systems.on("postUpdate",i._onPostUpdate,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){void 0!==i.enabled&&(e.enabled=i.enabled),void 0!==i.orientation&&(e.orientation=i.orientation),void 0!==i.reverseX&&(e.reverseX=i.reverseX),void 0!==i.reverseY&&(e.reverseY=i.reverseY),void 0!==i.alignment&&(e.alignment=Array.isArray(i.alignment)?new Et(i.alignment):i.alignment),void 0!==i.padding&&(e.padding=Array.isArray(i.padding)?new Pt(i.padding):i.padding),void 0!==i.spacing&&(e.spacing=Array.isArray(i.spacing)?new Et(i.spacing):i.spacing),void 0!==i.widthFitting&&(e.widthFitting=i.widthFitting),void 0!==i.heightFitting&&(e.heightFitting=i.heightFitting),void 0!==i.wrap&&(e.wrap=i.wrap),t.prototype.initializeComponentData.call(this,e,i,n)},i.cloneComponent=function(t,e){var i=t.layoutgroup;return this.addComponent(e,{enabled:i.enabled,orientation:i.orientation,reverseX:i.reverseX,reverseY:i.reverseY,alignment:i.alignment,padding:i.padding,spacing:i.spacing,widthFitting:i.widthFitting,heightFitting:i.heightFitting,wrap:i.wrap})},i.scheduleReflow=function(t){-1===this._reflowQueue.indexOf(t)&&this._reflowQueue.push(t)},i._onPostUpdate=function(){this._processReflowQueue()},i._processReflowQueue=function(){if(0!==this._reflowQueue.length)for(var t=0;this._reflowQueue.length>0;){var e=this._reflowQueue.slice();this._reflowQueue.length=0,e.sort((function(t,e){return t.entity.graphDepth-e.entity.graphDepth}));for(var i=0;i<e.length;++i)e[i].reflow();if(++t>=100){console.warn("Max reflow iterations limit reached, bailing.");break}}},i._onRemoveComponent=function(t,e){e.onRemove()},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("postUpdate",this._onPostUpdate,this)},e}(wp);bp._buildAccessors(Hv.prototype,Xv);var qv=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._type="asset",n._asset=null,n._model=null,n._mapping={},n._castShadows=!0,n._receiveShadows=!0,n._materialAsset=null,n._material=void 0,n._castShadowsLightmap=!0,n._lightmapped=!1,n._lightmapSizeMultiplier=1,n.isStatic=!1,n._layers=[0],n._batchGroupId=-1,n._customAabb=null,n._area=null,n._materialEvents=null,n._clonedModel=!1,n._material=e.defaultMaterial,i.on("remove",n.onRemoveChild,w(n)),i.on("removehierarchy",n.onRemoveChild,w(n)),i.on("insert",n.onInsertChild,w(n)),i.on("inserthierarchy",n.onInsertChild,w(n)),n}S(e,t);var i=e.prototype;return i.addModelToLayers=function(){for(var t=this.system.app.scene.layers,e=0;e<this._layers.length;e++){var i=t.getLayerById(this._layers[e]);i&&i.addMeshInstances(this.meshInstances)}},i.removeModelFromLayers=function(){for(var t=this.system.app.scene.layers,e=0;e<this._layers.length;e++){var i=t.getLayerById(this._layers[e]);i&&i.removeMeshInstances(this.meshInstances)}},i.onRemoveChild=function(){this._model&&this.removeModelFromLayers()},i.onInsertChild=function(){this._model&&this.enabled&&this.entity.enabled&&this.addModelToLayers()},i.onRemove=function(){this.asset=null,this.model=null,this.materialAsset=null,this._unsetMaterialEvents(),this.entity.off("remove",this.onRemoveChild,this),this.entity.off("insert",this.onInsertChild,this)},i.onLayersChanged=function(t,e){this.addModelToLayers(),t.off("add",this.onLayerAdded,this),t.off("remove",this.onLayerRemoved,this),e.on("add",this.onLayerAdded,this),e.on("remove",this.onLayerRemoved,this)},i.onLayerAdded=function(t){this.layers.indexOf(t.id)<0||t.addMeshInstances(this.meshInstances)},i.onLayerRemoved=function(t){this.layers.indexOf(t.id)<0||t.removeMeshInstances(this.meshInstances)},i._setMaterialEvent=function(t,e,i,n){var s=e+":"+i;this.system.app.assets.on(s,n,this),this._materialEvents||(this._materialEvents=[]),this._materialEvents[t]||(this._materialEvents[t]={}),this._materialEvents[t][s]={id:i,handler:n}},i._unsetMaterialEvents=function(){var t=this.system.app.assets,e=this._materialEvents;if(e){for(var i=0,n=e.length;i<n;i++)if(e[i]){var s=e[i];for(var r in s)t.off(r,s[r].handler,this)}this._materialEvents=null}},i._getAssetByIdOrPath=function(t){var e=null;if(isNaN(parseInt(t,10))){if(this.asset){var i=this._getMaterialAssetUrl(t);i&&(e=this.system.app.assets.getByUrl(i))}}else e=this.system.app.assets.get(t);return e},i._getMaterialAssetUrl=function(t){if(!this.asset)return null;var e=this.system.app.assets.get(this.asset);return e?e.getAbsoluteUrl(t):null},i._loadAndSetMeshInstanceMaterial=function(t,e,i){var n=this.system.app.assets;t&&(t.resource?(e.material=t.resource,this._setMaterialEvent(i,"remove",t.id,(function(){e.material=this.system.defaultMaterial}))):(this._setMaterialEvent(i,"load",t.id,(function(n){e.material=n.resource,this._setMaterialEvent(i,"remove",t.id,(function(){e.material=this.system.defaultMaterial}))})),this.enabled&&this.entity.enabled&&n.load(t)))},i.onEnable=function(){var t=this.system.app,e=t.scene;e.on("set:layers",this.onLayersChanged,this),e.layers&&(e.layers.on("add",this.onLayerAdded,this),e.layers.on("remove",this.onLayerRemoved,this));var i,n,s="asset"===this._type;if(this._model?this.addModelToLayers():s&&this._asset&&(i=t.assets.get(this._asset))&&i.resource!==this._model&&this._bindModelAsset(i),this._materialAsset&&(i=t.assets.get(this._materialAsset))&&i.resource!==this._material&&this._bindMaterialAsset(i),s&&this._mapping)for(var r in this._mapping)this._mapping[r]&&(i=this._getAssetByIdOrPath(this._mapping[r]))&&!i.resource&&t.assets.load(i);this._batchGroupId>=0&&(null==(n=t.batcher)||n.insert(Ho.MODEL,this.batchGroupId,this.entity))},i.onDisable=function(){var t,e=this.system.app,i=e.scene;(i.off("set:layers",this.onLayersChanged,this),i.layers&&(i.layers.off("add",this.onLayerAdded,this),i.layers.off("remove",this.onLayerRemoved,this)),this._batchGroupId>=0)&&(null==(t=e.batcher)||t.remove(Ho.MODEL,this.batchGroupId,this.entity));this._model&&this.removeModelFromLayers()},i.hide=function(){if(this._model)for(var t=this._model.meshInstances,e=0,i=t.length;e<i;e++)t[e].visible=!1},i.show=function(){if(this._model)for(var t=this._model.meshInstances,e=0,i=t.length;e<i;e++)t[e].visible=!0},i._bindMaterialAsset=function(t){if(t.on("load",this._onMaterialAssetLoad,this),t.on("unload",this._onMaterialAssetUnload,this),t.on("remove",this._onMaterialAssetRemove,this),t.on("change",this._onMaterialAssetChange,this),t.resource)this._onMaterialAssetLoad(t);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(t)}},i._unbindMaterialAsset=function(t){t.off("load",this._onMaterialAssetLoad,this),t.off("unload",this._onMaterialAssetUnload,this),t.off("remove",this._onMaterialAssetRemove,this),t.off("change",this._onMaterialAssetChange,this)},i._onMaterialAssetAdd=function(t){this.system.app.assets.off("add:"+t.id,this._onMaterialAssetAdd,this),this._materialAsset===t.id&&this._bindMaterialAsset(t)},i._onMaterialAssetLoad=function(t){this._setMaterial(t.resource)},i._onMaterialAssetUnload=function(t){this._setMaterial(this.system.defaultMaterial)},i._onMaterialAssetRemove=function(t){this._onMaterialAssetUnload(t)},i._onMaterialAssetChange=function(t){},i._bindModelAsset=function(t){if(this._unbindModelAsset(t),t.on("load",this._onModelAssetLoad,this),t.on("unload",this._onModelAssetUnload,this),t.on("change",this._onModelAssetChange,this),t.on("remove",this._onModelAssetRemove,this),t.resource)this._onModelAssetLoad(t);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(t)}},i._unbindModelAsset=function(t){t.off("load",this._onModelAssetLoad,this),t.off("unload",this._onModelAssetUnload,this),t.off("change",this._onModelAssetChange,this),t.off("remove",this._onModelAssetRemove,this)},i._onModelAssetAdded=function(t){this.system.app.assets.off("add:"+t.id,this._onModelAssetAdded,this),t.id===this._asset&&this._bindModelAsset(t)},i._onModelAssetLoad=function(t){this.model=t.resource.clone(),this._clonedModel=!0},i._onModelAssetUnload=function(t){this.model=null},i._onModelAssetChange=function(t,e,i,n){"data"===e&&(this.mapping=this._mapping)},i._onModelAssetRemove=function(t){this.model=null},i._setMaterial=function(t){if(this._material!==t){this._material=t;var e=this._model;if(e&&"asset"!==this._type)for(var i=e.meshInstances,n=0,s=i.length;n<s;n++)i[n].material=t}},y(e,[{key:"meshInstances",get:function(){return this._model?this._model.meshInstances:null},set:function(t){this._model&&(this._model.meshInstances=t)}},{key:"customAabb",get:function(){return this._customAabb},set:function(t){if(this._customAabb=t,this._model){var e=this._model.meshInstances;if(e)for(var i=0;i<e.length;i++)e[i].setCustomAabb(this._customAabb)}}},{key:"type",get:function(){return this._type},set:function(t){if(this._type!==t)if(this._area=null,this._type=t,"asset"===t)null!==this._asset?this._bindModelAsset(this._asset):this.model=null;else{var e=ho(this.system.app.graphicsDevice,t);this._area=e.area;var i=e.mesh,n=new hh,s=new Gu;s.graph=n,s.meshInstances=[new yh(i,this._material,n)],this.model=s,this._asset=null}}},{key:"asset",get:function(){return this._asset},set:function(t){var e=this.system.app.assets,i=t;if(t instanceof Vf&&(i=t.id),this._asset!==i){if(this._asset){e.off("add:"+this._asset,this._onModelAssetAdded,this);var n=e.get(this._asset);n&&this._unbindModelAsset(n)}if(this._asset=i,this._asset){var s=e.get(this._asset);s?this._bindModelAsset(s):(this.model=null,e.on("add:"+this._asset,this._onModelAssetAdded,this))}else this.model=null}}},{key:"model",get:function(){return this._model},set:function(t){if(this._model!==t&&(!t||!t._immutable)&&(this._model&&(this._model._immutable=!1,this.removeModelFromLayers(),this._model.getGraph().destroy(),delete this._model._entity,this._clonedModel&&(this._model.destroy(),this._clonedModel=!1)),this._model=t,this._model)){this._model._immutable=!0;for(var e=this._model.meshInstances,i=0;i<e.length;i++)e[i].castShadow=this._castShadows,e[i].receiveShadow=this._receiveShadows,e[i].setCustomAabb(this._customAabb);this.lightmapped=this._lightmapped,this.entity.addChild(this._model.graph),this.enabled&&this.entity.enabled&&this.addModelToLayers(),this._model._entity=this.entity,this.entity.animation&&this.entity.animation.setModel(this._model),this.entity.anim&&this.entity.anim.rebind(),"asset"===this.type?this.mapping=this._mapping:this._unsetMaterialEvents()}}},{key:"lightmapped",get:function(){return this._lightmapped},set:function(t){if(t!==this._lightmapped&&(this._lightmapped=t,this._model))for(var e=this._model.meshInstances,i=0;i<e.length;i++)e[i].setLightmapped(t)}},{key:"castShadows",get:function(){return this._castShadows},set:function(t){if(this._castShadows!==t){var e=this._model;if(e){var i=this.layers,n=this.system.app.scene;if(this._castShadows&&!t)for(var s=0;s<i.length;s++){var r=this.system.app.scene.layers.getLayerById(this.layers[s]);r&&r.removeShadowCasters(e.meshInstances)}for(var a=e.meshInstances,o=0;o<a.length;o++)a[o].castShadow=t;if(!this._castShadows&&t)for(var h=0;h<i.length;h++){var l=n.layers.getLayerById(i[h]);l&&l.addShadowCasters(e.meshInstances)}}this._castShadows=t}}},{key:"receiveShadows",get:function(){return this._receiveShadows},set:function(t){if(this._receiveShadows!==t&&(this._receiveShadows=t,this._model))for(var e=this._model.meshInstances,i=0,n=e.length;i<n;i++)e[i].receiveShadow=t}},{key:"castShadowsLightmap",get:function(){return this._castShadowsLightmap},set:function(t){this._castShadowsLightmap=t}},{key:"lightmapSizeMultiplier",get:function(){return this._lightmapSizeMultiplier},set:function(t){this._lightmapSizeMultiplier=t}},{key:"layers",get:function(){return this._layers},set:function(t){var e=this.system.app.scene.layers;if(this.meshInstances)for(var i=0;i<this._layers.length;i++){var n=e.getLayerById(this._layers[i]);n&&n.removeMeshInstances(this.meshInstances)}this._layers.length=0;for(var s=0;s<t.length;s++)this._layers[s]=t[s];if(this.enabled&&this.entity.enabled&&this.meshInstances)for(var r=0;r<this._layers.length;r++){var a=e.getLayerById(this._layers[r]);a&&a.addMeshInstances(this.meshInstances)}}},{key:"batchGroupId",get:function(){return this._batchGroupId},set:function(t){if(this._batchGroupId!==t){var e,i;if(this.entity.enabled&&this._batchGroupId>=0)null==(e=this.system.app.batcher)||e.remove(Ho.MODEL,this.batchGroupId,this.entity);if(this.entity.enabled&&t>=0)null==(i=this.system.app.batcher)||i.insert(Ho.MODEL,t,this.entity);t<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addModelToLayers(),this._batchGroupId=t}}},{key:"materialAsset",get:function(){return this._materialAsset},set:function(t){var e=t;t instanceof Vf&&(e=t.id);var i=this.system.app.assets;if(e!==this._materialAsset){if(this._materialAsset){i.off("add:"+this._materialAsset,this._onMaterialAssetAdd,this);var n=i.get(this._materialAsset);n&&this._unbindMaterialAsset(n)}if(this._materialAsset=e,this._materialAsset){var s=i.get(this._materialAsset);s?this._bindMaterialAsset(s):(this._setMaterial(this.system.defaultMaterial),i.on("add:"+this._materialAsset,this._onMaterialAssetAdd,this))}else this._setMaterial(this.system.defaultMaterial)}}},{key:"material",get:function(){return this._material},set:function(t){this._material!==t&&(this.materialAsset=null,this._setMaterial(t))}},{key:"mapping",get:function(){return this._mapping},set:function(t){if("asset"===this._type&&(this._unsetMaterialEvents(),t||(t={}),this._mapping=t,this._model))for(var e=this._model.meshInstances,i=this.asset?this.system.app.assets.get(this.asset):null,n=i?i.data.mapping:null,s=null,r=0,a=e.length;r<a;r++)if(void 0!==t[r])t[r]?(s=this.system.app.assets.get(t[r]),this._loadAndSetMeshInstanceMaterial(s,e[r],r)):e[r].material=this.system.defaultMaterial;else if(n)if(n[r]&&(n[r].material||n[r].path)){if(void 0!==n[r].material)s=this.system.app.assets.get(n[r].material);else if(void 0!==n[r].path){var o=this._getMaterialAssetUrl(n[r].path);o&&(s=this.system.app.assets.getByUrl(o))}this._loadAndSetMeshInstanceMaterial(s,e[r],r)}else e[r].material=this.system.defaultMaterial}}]),e}(bp),Yv=function(){this.enabled=!0},Kv=["enabled"],Zv=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="model",i.ComponentType=qv,i.DataType=Yv,i.schema=Kv,i.defaultMaterial=Bo(e.graphicsDevice),i.on("beforeremove",i.onRemove,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){n=["material","materialAsset","asset","castShadows","receiveShadows","castShadowsLightmap","lightmapped","lightmapSizeMultiplier","type","mapping","layers","isStatic","batchGroupId"],null!==i.batchGroupId&&void 0!==i.batchGroupId||(i.batchGroupId=-1),i.layers&&i.layers.length&&(i.layers=i.layers.slice(0));for(var s=0;s<n.length;s++)i.hasOwnProperty(n[s])&&(e[n[s]]=i[n[s]]);i.aabbCenter&&i.aabbHalfExtents&&(e.customAabb=new Ht(new wt(i.aabbCenter),new wt(i.aabbHalfExtents))),t.prototype.initializeComponentData.call(this,e,i,["enabled"])},i.cloneComponent=function(t,e){var i={type:t.model.type,asset:t.model.asset,castShadows:t.model.castShadows,receiveShadows:t.model.receiveShadows,castShadowsLightmap:t.model.castShadowsLightmap,lightmapped:t.model.lightmapped,lightmapSizeMultiplier:t.model.lightmapSizeMultiplier,isStatic:t.model.isStatic,enabled:t.model.enabled,layers:t.model.layers,batchGroupId:t.model.batchGroupId,mapping:p({},t.model.mapping)},n=t.model.materialAsset;n instanceof Vf||null==n||(n=this.app.assets.get(n));var s=t.model.material;s&&s!==this.defaultMaterial&&n&&s!==n.resource||(i.materialAsset=n);var r=this.addComponent(e,i);if(t.model.model&&"asset"===t.model.type&&!t.model.asset&&(r.model=t.model.model.clone(),r._clonedModel=!0),i.materialAsset||(r.material=s),t.model.model)for(var a=t.model.model.meshInstances,o=r.model.meshInstances,h=0;h<a.length;h++)o[h].mask=a[h].mask,o[h].material=a[h].material,o[h].layer=a[h].layer,o[h].receiveShadow=a[h].receiveShadow;return t.model.customAabb&&(r.customAabb=t.model.customAabb.clone()),r},i.onRemove=function(t,e){e.onRemove()},e}(wp);bp._buildAccessors(qv.prototype,Kv);var Qv,$v=["emitterExtents","emitterRadius","emitterExtentsInner","emitterRadiusInner","loop","initialVelocity","animSpeed","normalMap","particleNormal"],Jv=["numParticles","lifetime","rate","rate2","startAngle","startAngle2","lighting","halfLambert","intensity","wrap","wrapBounds","depthWrite","noFog","sort","stretch","alignToMotion","preWarm","emitterShape","animTilesX","animTilesY","animStartFrame","animNumFrames","animNumAnimations","animIndex","randomizeAnimIndex","animLoop","colorMap","localSpace","screenSpace","orientation"],tg=["scaleGraph","scaleGraph2","colorGraph","colorGraph2","alphaGraph","alphaGraph2","velocityGraph","velocityGraph2","localVelocityGraph","localVelocityGraph2","rotationSpeedGraph","rotationSpeedGraph2","radialSpeedGraph","radialSpeedGraph2"],eg=["colorMapAsset","normalMapAsset","meshAsset","renderAsset"],ig=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._requestedDepth=!1,n._drawOrder=0,n.on("set_colorMapAsset",n.onSetColorMapAsset,w(n)),n.on("set_normalMapAsset",n.onSetNormalMapAsset,w(n)),n.on("set_meshAsset",n.onSetMeshAsset,w(n)),n.on("set_mesh",n.onSetMesh,w(n)),n.on("set_renderAsset",n.onSetRenderAsset,w(n)),n.on("set_loop",n.onSetLoop,w(n)),n.on("set_blendType",n.onSetBlendType,w(n)),n.on("set_depthSoftening",n.onSetDepthSoftening,w(n)),n.on("set_layers",n.onSetLayers,w(n)),$v.forEach((function(t){n.on("set_"+t,n.onSetSimpleProperty,w(n))})),Jv.forEach((function(t){n.on("set_"+t,n.onSetComplexProperty,w(n))})),tg.forEach((function(t){n.on("set_"+t,n.onSetGraphProperty,w(n))})),n}S(e,t);var i=e.prototype;return i.addMeshInstanceToLayers=function(){if(this.emitter)for(var t=0;t<this.layers.length;t++){var e=this.system.app.scene.layers.getLayerById(this.layers[t]);e&&(e.addMeshInstances([this.emitter.meshInstance]),this.emitter._layer=e)}},i.removeMeshInstanceFromLayers=function(){if(this.emitter)for(var t=0;t<this.layers.length;t++){var e=this.system.app.scene.layers.getLayerById(this.layers[t]);e&&e.removeMeshInstances([this.emitter.meshInstance])}},i.onSetLayers=function(t,e,i){if(this.emitter){for(var n=0;n<e.length;n++){var s=this.system.app.scene.layers.getLayerById(e[n]);s&&s.removeMeshInstances([this.emitter.meshInstance])}if(this.enabled&&this.entity.enabled)for(var r=0;r<i.length;r++){var a=this.system.app.scene.layers.getLayerById(i[r]);a&&a.addMeshInstances([this.emitter.meshInstance])}}},i.onLayersChanged=function(t,e){this.addMeshInstanceToLayers(),t.off("add",this.onLayerAdded,this),t.off("remove",this.onLayerRemoved,this),e.on("add",this.onLayerAdded,this),e.on("remove",this.onLayerRemoved,this)},i.onLayerAdded=function(t){this.emitter&&(this.layers.indexOf(t.id)<0||t.addMeshInstances([this.emitter.meshInstance]))},i.onLayerRemoved=function(t){this.emitter&&(this.layers.indexOf(t.id)<0||t.removeMeshInstances([this.emitter.meshInstance]))},i._bindColorMapAsset=function(t){if(t.on("load",this._onColorMapAssetLoad,this),t.on("unload",this._onColorMapAssetUnload,this),t.on("remove",this._onColorMapAssetRemove,this),t.on("change",this._onColorMapAssetChange,this),t.resource)this._onColorMapAssetLoad(t);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(t)}},i._unbindColorMapAsset=function(t){t.off("load",this._onColorMapAssetLoad,this),t.off("unload",this._onColorMapAssetUnload,this),t.off("remove",this._onColorMapAssetRemove,this),t.off("change",this._onColorMapAssetChange,this)},i._onColorMapAssetLoad=function(t){this.colorMap=t.resource},i._onColorMapAssetUnload=function(t){this.colorMap=null},i._onColorMapAssetRemove=function(t){this._onColorMapAssetUnload(t)},i._onColorMapAssetChange=function(t){},i.onSetColorMapAsset=function(t,e,i){var n=this,s=this.system.app.assets;if(e){var r=s.get(e);r&&this._unbindColorMapAsset(r)}if(i){i instanceof Vf&&(this.data.colorMapAsset=i.id,i=i.id);var a=s.get(i);a?this._bindColorMapAsset(a):s.once("add:"+i,(function(t){n._bindColorMapAsset(t)}))}else this.colorMap=null},i._bindNormalMapAsset=function(t){if(t.on("load",this._onNormalMapAssetLoad,this),t.on("unload",this._onNormalMapAssetUnload,this),t.on("remove",this._onNormalMapAssetRemove,this),t.on("change",this._onNormalMapAssetChange,this),t.resource)this._onNormalMapAssetLoad(t);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(t)}},i._unbindNormalMapAsset=function(t){t.off("load",this._onNormalMapAssetLoad,this),t.off("unload",this._onNormalMapAssetUnload,this),t.off("remove",this._onNormalMapAssetRemove,this),t.off("change",this._onNormalMapAssetChange,this)},i._onNormalMapAssetLoad=function(t){this.normalMap=t.resource},i._onNormalMapAssetUnload=function(t){this.normalMap=null},i._onNormalMapAssetRemove=function(t){this._onNormalMapAssetUnload(t)},i._onNormalMapAssetChange=function(t){},i.onSetNormalMapAsset=function(t,e,i){var n=this,s=this.system.app.assets;if(e){var r=s.get(e);r&&this._unbindNormalMapAsset(r)}if(i){i instanceof Vf&&(this.data.normalMapAsset=i.id,i=i.id);var a=s.get(i);a?this._bindNormalMapAsset(a):s.once("add:"+i,(function(t){n._bindNormalMapAsset(t)}))}else this.normalMap=null},i._bindMeshAsset=function(t){if(t.on("load",this._onMeshAssetLoad,this),t.on("unload",this._onMeshAssetUnload,this),t.on("remove",this._onMeshAssetRemove,this),t.on("change",this._onMeshAssetChange,this),t.resource)this._onMeshAssetLoad(t);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(t)}},i._unbindMeshAsset=function(t){t.off("load",this._onMeshAssetLoad,this),t.off("unload",this._onMeshAssetUnload,this),t.off("remove",this._onMeshAssetRemove,this),t.off("change",this._onMeshAssetChange,this)},i._onMeshAssetLoad=function(t){this._onMeshChanged(t.resource)},i._onMeshAssetUnload=function(t){this.mesh=null},i._onMeshAssetRemove=function(t){this._onMeshAssetUnload(t)},i._onMeshAssetChange=function(t){},i.onSetMeshAsset=function(t,e,i){var n=this.system.app.assets;if(e){var s=n.get(e);s&&this._unbindMeshAsset(s)}if(i){i instanceof Vf&&(this.data.meshAsset=i.id,i=i.id);var r=n.get(i);r&&this._bindMeshAsset(r)}else this._onMeshChanged(null)},i.onSetMesh=function(t,e,i){!i||i instanceof Vf||"number"==typeof i?this.meshAsset=i:this._onMeshChanged(i)},i._onMeshChanged=function(t){!t||t instanceof qa||(t=t.meshInstances[0]?t.meshInstances[0].mesh:null),this.data.mesh=t,this.emitter&&(this.emitter.mesh=t,this.emitter.resetMaterial(),this.rebuild())},i.onSetRenderAsset=function(t,e,i){var n=this.system.app.assets;if(e){var s=n.get(e);s&&this._unbindRenderAsset(s)}if(i){i instanceof Vf&&(this.data.renderAsset=i.id,i=i.id);var r=n.get(i);r&&this._bindRenderAsset(r)}else this._onRenderChanged(null)},i._bindRenderAsset=function(t){if(t.on("load",this._onRenderAssetLoad,this),t.on("unload",this._onRenderAssetUnload,this),t.on("remove",this._onRenderAssetRemove,this),t.resource)this._onRenderAssetLoad(t);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(t)}},i._unbindRenderAsset=function(t){t.off("load",this._onRenderAssetLoad,this),t.off("unload",this._onRenderAssetUnload,this),t.off("remove",this._onRenderAssetRemove,this),t.resource&&t.resource.off("set:meshes",this._onRenderSetMeshes,this)},i._onRenderAssetLoad=function(t){this._onRenderChanged(t.resource)},i._onRenderAssetUnload=function(t){this._onRenderChanged(null)},i._onRenderAssetRemove=function(t){this._onRenderAssetUnload(t)},i._onRenderChanged=function(t){t?(t.off("set:meshes",this._onRenderSetMeshes,this),t.on("set:meshes",this._onRenderSetMeshes,this),t.meshes&&this._onRenderSetMeshes(t.meshes)):this._onMeshChanged(null)},i._onRenderSetMeshes=function(t){this._onMeshChanged(t&&t[0])},i.onSetLoop=function(t,e,i){this.emitter&&(this.emitter[t]=i,this.emitter.resetTime())},i.onSetBlendType=function(t,e,i){this.emitter&&(this.emitter[t]=i,this.emitter.material.blendType=i,this.emitter.resetMaterial(),this.rebuild())},i._requestDepth=function(){this._requestedDepth||(Qv||(Qv=this.system.app.scene.layers.getLayerById(1)),Qv&&(Qv.incrementCounter(),this._requestedDepth=!0))},i._releaseDepth=function(){this._requestedDepth&&Qv&&(Qv.decrementCounter(),this._requestedDepth=!1)},i.onSetDepthSoftening=function(t,e,i){e!==i&&(i?(this.enabled&&this.entity.enabled&&this._requestDepth(),this.emitter&&(this.emitter[t]=i)):(this.enabled&&this.entity.enabled&&this._releaseDepth(),this.emitter&&(this.emitter[t]=i)),this.emitter&&(this.reset(),this.emitter.resetMaterial(),this.rebuild()))},i.onSetSimpleProperty=function(t,e,i){this.emitter&&(this.emitter[t]=i,this.emitter.resetMaterial())},i.onSetComplexProperty=function(t,e,i){this.emitter&&(this.emitter[t]=i,this.emitter.resetMaterial(),this.rebuild(),this.reset())},i.onSetGraphProperty=function(t,e,i){this.emitter&&(this.emitter[t]=i,this.emitter.rebuildGraphs(),this.emitter.resetMaterial())},i.onEnable=function(){for(var t=this.data,e=0,i=eg.length;e<i;e++){var n=t[eg[e]];if(n){if(!(n instanceof Vf)){if(!(parseInt(n,10)>=0))continue;n=this.system.app.assets.get(n)}n&&!n.resource&&this.system.app.assets.load(n)}}if(!this.system.app.graphicsDevice.disableParticleSystem){if(!this.emitter){var s=t.mesh;s instanceof qa||(s=null),this.emitter=new Nd(this.system.app.graphicsDevice,{numParticles:t.numParticles,emitterExtents:t.emitterExtents,emitterExtentsInner:t.emitterExtentsInner,emitterRadius:t.emitterRadius,emitterRadiusInner:t.emitterRadiusInner,emitterShape:t.emitterShape,initialVelocity:t.initialVelocity,wrap:t.wrap,localSpace:t.localSpace,screenSpace:t.screenSpace,wrapBounds:t.wrapBounds,lifetime:t.lifetime,rate:t.rate,rate2:t.rate2,orientation:t.orientation,particleNormal:t.particleNormal,animTilesX:t.animTilesX,animTilesY:t.animTilesY,animStartFrame:t.animStartFrame,animNumFrames:t.animNumFrames,animNumAnimations:t.animNumAnimations,animIndex:t.animIndex,randomizeAnimIndex:t.randomizeAnimIndex,animSpeed:t.animSpeed,animLoop:t.animLoop,startAngle:t.startAngle,startAngle2:t.startAngle2,scaleGraph:t.scaleGraph,scaleGraph2:t.scaleGraph2,colorGraph:t.colorGraph,colorGraph2:t.colorGraph2,alphaGraph:t.alphaGraph,alphaGraph2:t.alphaGraph2,localVelocityGraph:t.localVelocityGraph,localVelocityGraph2:t.localVelocityGraph2,velocityGraph:t.velocityGraph,velocityGraph2:t.velocityGraph2,rotationSpeedGraph:t.rotationSpeedGraph,rotationSpeedGraph2:t.rotationSpeedGraph2,radialSpeedGraph:t.radialSpeedGraph,radialSpeedGraph2:t.radialSpeedGraph2,colorMap:t.colorMap,normalMap:t.normalMap,loop:t.loop,preWarm:t.preWarm,sort:t.sort,stretch:t.stretch,alignToMotion:t.alignToMotion,lighting:t.lighting,halfLambert:t.halfLambert,intensity:t.intensity,depthSoftening:t.depthSoftening,scene:this.system.app.scene,mesh:s,depthWrite:t.depthWrite,noFog:t.noFog,node:this.entity,blendType:t.blendType}),this.emitter.meshInstance.node=this.entity,this.emitter.drawOrder=this.drawOrder,t.autoPlay||(this.pause(),this.emitter.meshInstance.visible=!1)}this.emitter.colorMap&&this.addMeshInstanceToLayers(),this.system.app.scene.on("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.on("add",this.onLayerAdded,this),this.system.app.scene.layers.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&t.depthSoftening&&this._requestDepth()}},i.onDisable=function(){this.system.app.scene.off("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.off("add",this.onLayerAdded,this),this.system.app.scene.layers.off("remove",this.onLayerRemoved,this)),this.emitter&&(this.removeMeshInstanceFromLayers(),this.data.depthSoftening&&this._releaseDepth(),this.emitter.camera=null)},i.onBeforeRemove=function(){this.enabled&&(this.enabled=!1),this.emitter&&(this.emitter.destroy(),this.emitter=null);for(var t=0;t<eg.length;t++){var e=eg[t];this.data[e]&&(this[e]=null)}this.off()},i.reset=function(){this.emitter&&this.emitter.reset()},i.stop=function(){this.emitter&&(this.emitter.loop=!1,this.emitter.resetTime(),this.emitter.addTime(0,!0))},i.pause=function(){this.data.paused=!0},i.unpause=function(){this.data.paused=!1},i.play=function(){this.data.paused=!1,this.emitter&&(this.emitter.meshInstance.visible=!0,this.emitter.loop=this.data.loop,this.emitter.resetTime())},i.isPlaying=function(){return!this.data.paused&&(!(!this.emitter||!this.emitter.loop)||Date.now()<=this.emitter.endTime)},i.rebuild=function(){var t=this.enabled;this.enabled=!1,this.emitter&&(this.emitter.rebuild(),this.emitter.meshInstance.node=this.entity),this.enabled=t},y(e,[{key:"drawOrder",get:function(){return this._drawOrder},set:function(t){this._drawOrder=t,this.emitter&&(this.emitter.drawOrder=t)}}]),e}(bp),ng=function(){this.numParticles=1,this.rate=1,this.rate2=null,this.startAngle=0,this.startAngle2=null,this.lifetime=50,this.emitterExtents=new wt,this.emitterExtentsInner=new wt,this.emitterRadius=0,this.emitterRadiusInner=0,this.emitterShape=0,this.initialVelocity=0,this.wrapBounds=new wt,this.localSpace=!1,this.screenSpace=!1,this.colorMap=null,this.colorMapAsset=null,this.normalMap=null,this.normalMapAsset=null,this.loop=!0,this.preWarm=!1,this.sort=0,this.mode=0,this.scene=null,this.lighting=!1,this.halfLambert=!1,this.intensity=1,this.stretch=0,this.alignToMotion=!1,this.depthSoftening=0,this.meshAsset=null,this.mesh=null,this.depthWrite=!1,this.noFog=!1,this.orientation=0,this.particleNormal=new wt(0,1,0),this.animTilesX=1,this.animTilesY=1,this.animStartFrame=0,this.animNumFrames=1,this.animNumAnimations=1,this.animIndex=0,this.randomizeAnimIndex=!1,this.animSpeed=1,this.animLoop=!0,this.scaleGraph=null,this.scaleGraph2=null,this.colorGraph=null,this.colorGraph2=null,this.alphaGraph=null,this.alphaGraph2=null,this.localVelocityGraph=null,this.localVelocityGraph2=null,this.velocityGraph=null,this.velocityGraph2=null,this.rotationSpeedGraph=null,this.rotationSpeedGraph2=null,this.radialSpeedGraph=null,this.radialSpeedGraph2=null,this.blendType=2,this.enabled=!0,this.paused=!1,this.autoPlay=!0,this.layers=[0]},sg=["enabled","autoPlay","numParticles","lifetime","rate","rate2","startAngle","startAngle2","loop","preWarm","lighting","halfLambert","intensity","depthWrite","noFog","depthSoftening","sort","blendType","stretch","alignToMotion","emitterShape","emitterExtents","emitterExtentsInner","emitterRadius","emitterRadiusInner","initialVelocity","wrap","wrapBounds","localSpace","screenSpace","colorMapAsset","normalMapAsset","mesh","meshAsset","renderAsset","orientation","particleNormal","localVelocityGraph","localVelocityGraph2","velocityGraph","velocityGraph2","rotationSpeedGraph","rotationSpeedGraph2","radialSpeedGraph","radialSpeedGraph2","scaleGraph","scaleGraph2","colorGraph","colorGraph2","alphaGraph","alphaGraph2","colorMap","normalMap","animTilesX","animTilesY","animStartFrame","animNumFrames","animNumAnimations","animIndex","randomizeAnimIndex","animSpeed","animLoop","layers"],rg=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="particlesystem",i.ComponentType=ig,i.DataType=ng,i.schema=sg,i.propertyTypes={emitterExtents:"vec3",emitterExtentsInner:"vec3",particleNormal:"vec3",wrapBounds:"vec3",localVelocityGraph:"curveset",localVelocityGraph2:"curveset",velocityGraph:"curveset",velocityGraph2:"curveset",colorGraph:"curveset",colorGraph2:"curveset",alphaGraph:"curve",alphaGraph2:"curve",rotationSpeedGraph:"curve",rotationSpeedGraph2:"curve",radialSpeedGraph:"curve",radialSpeedGraph2:"curve",scaleGraph:"curve",scaleGraph2:"curve"},i.on("beforeremove",i.onBeforeRemove,w(i)),i.app.systems.on("update",i.onUpdate,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){var s={};n=[];var r=this.propertyTypes;for(var a in(i.mesh instanceof Vf||"number"==typeof i.mesh)&&(i.meshAsset=i.mesh,delete i.mesh),i){if(i.hasOwnProperty(a)&&(n.push(a),s[a]=i[a]),"vec3"===r[a])Array.isArray(s[a])&&(s[a]=new wt(s[a][0],s[a][1],s[a][2]));else if("curve"===r[a]){if(!(s[a]instanceof St)){var o=s[a].type;s[a]=new St(s[a].keys),s[a].type=o}}else if("curveset"===r[a]&&!(s[a]instanceof bt)){var h=s[a].type;s[a]=new bt(s[a].keys),s[a].type=h}s.layers&&Array.isArray(s.layers)&&(s.layers=s.layers.slice(0))}t.prototype.initializeComponentData.call(this,e,s,n)},i.cloneComponent=function(t,e){for(var i=t.particlesystem.data,n=this.schema,s={},r=0,a=n.length;r<a;r++){var o=n[r],h=i[o];h instanceof wt||h instanceof St||h instanceof bt?(h=h.clone(),s[o]=h):"layers"===o?s.layers=i.layers.slice(0):null!=h&&(s[o]=h)}return this.addComponent(e,s)},i.onUpdate=function(t){for(var e,i=this.store,n=this.app.stats.particles,s=this.app.scene.layers,r=0;r<s.layerList.length;r++)s.layerList[r].requiresLightCube=!1;for(var a in i)if(i.hasOwnProperty(a)){var o=i[a],h=o.entity,l=o.data;if(l.enabled&&h.enabled){var c=h.particlesystem.emitter;if(null==c||!c.meshInstance.visible)continue;if(c.lighting)for(var u=l.layers,d=0;d<u.length;d++){var f=s.getLayerById(u[d]);f&&(f.requiresLightCube=!0)}if(!l.paused){if(c.simTime+=t,c.simTime>c.fixedTimeStep&&(e=Math.floor(c.simTime/c.fixedTimeStep),c.simTime-=e*c.fixedTimeStep),e){e=Math.min(e,c.maxSubSteps);for(var p=0;p<e;p++)c.addTime(c.fixedTimeStep,!1);n._updatesPerFrame+=e,n._frameTime+=c._addTimeTime,c._addTimeTime=0}c.finishFrame()}}}},i.onBeforeRemove=function(t,e){e.onBeforeRemove()},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},e}(wp);bp._buildAccessors(ig.prototype,sg);var ag=function(t){function e(e,i){var n;return(n=t.call(this)||this).skin=e,n.skinInstance=i,n}return S(e,t),e}(Ga),og=function(){function t(){}return t.createCachedSkinInstance=function(e,i,n){var s=t.getCachedSkinInstance(e,i);return s||((s=new Xo(e)).resolve(i,n),t.addCachedSkinInstance(e,i,s)),s},t.getCachedSkinInstance=function(e,i){var n=null,s=t._skinInstanceCache.get(i);if(s){var r=s.find((function(t){return t.skin===e}));r&&(r.incRefCount(),n=r.skinInstance)}return n},t.addCachedSkinInstance=function(e,i,n){var s=t._skinInstanceCache.get(i);s||(s=[],t._skinInstanceCache.set(i,s));var r=s.find((function(t){return t.skin===e}));r||(r=new ag(e,n),s.push(r)),r.incRefCount()},t.removeCachedSkinInstance=function(e){if(e){var i=e.rootBone;if(i){var n=t._skinInstanceCache.get(i);if(n){var s=n.findIndex((function(t){return t.skinInstance===e}));if(s>=0){var r=n[s];r.decRefCount(),0===r.refCount&&(n.splice(s,1),n.length||t._skinInstanceCache.delete(i),e&&(e.destroy(),r.skinInstance=null))}}}}},t}();og._skinInstanceCache=new Map;var hg=function(){function t(t,e,i,n,s){this.propertyName=t,this.parent=e,this._scope=s,this._registry=i,this.id=null,this.url=null,this.asset=null,this._onAssetLoad=n.load,this._onAssetAdd=n.add,this._onAssetRemove=n.remove,this._onAssetUnload=n.unload}var e=t.prototype;return e._bind=function(){this.id&&(this._onAssetLoad&&this._registry.on("load:"+this.id,this._onLoad,this),this._onAssetAdd&&this._registry.once("add:"+this.id,this._onAdd,this),this._onAssetRemove&&this._registry.on("remove:"+this.id,this._onRemove,this),this._onAssetUnload&&this._registry.on("unload:"+this.id,this._onUnload,this)),this.url&&(this._onAssetLoad&&this._registry.on("load:url:"+this.url,this._onLoad,this),this._onAssetAdd&&this._registry.once("add:url:"+this.url,this._onAdd,this),this._onAssetRemove&&this._registry.on("remove:url:"+this.url,this._onRemove,this))},e._unbind=function(){this.id&&(this._onAssetLoad&&this._registry.off("load:"+this.id,this._onLoad,this),this._onAssetAdd&&this._registry.off("add:"+this.id,this._onAdd,this),this._onAssetRemove&&this._registry.off("remove:"+this.id,this._onRemove,this),this._onAssetUnload&&this._registry.off("unload:"+this.id,this._onUnload,this)),this.url&&(this._onAssetLoad&&this._registry.off("load:"+this.url,this._onLoad,this),this._onAssetAdd&&this._registry.off("add:"+this.url,this._onAdd,this),this._onAssetRemove&&this._registry.off("remove:"+this.url,this._onRemove,this))},e._onLoad=function(t){this._onAssetLoad.call(this._scope,this.propertyName,this.parent,t)},e._onAdd=function(t){this.asset=t,this._onAssetAdd.call(this._scope,this.propertyName,this.parent,t)},e._onRemove=function(t){this._onAssetRemove.call(this._scope,this.propertyName,this.parent,t),this.asset=null},e._onUnload=function(t){this._onAssetUnload.call(this._scope,this.propertyName,this.parent,t)},y(t,[{key:"id",get:function(){return this._id},set:function(t){if(this.url)throw Error("Can't set id and url");this._unbind(),this._id=t,this.asset=this._registry.get(this._id),this._bind()}},{key:"url",get:function(){return this._url},set:function(t){if(this.id)throw Error("Can't set id and url");this._unbind(),this._url=t,this.asset=this._registry.getByUrl(this._url),this._bind()}}]),t}(),lg=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._type="asset",n._castShadows=!0,n._receiveShadows=!0,n._castShadowsLightmap=!0,n._lightmapped=!1,n._lightmapSizeMultiplier=1,n.isStatic=!1,n._batchGroupId=-1,n._layers=[0],n._renderStyle=0,n._meshInstances=[],n._customAabb=null,n._area=null,n._assetReference=[],n._materialReferences=[],n._material=void 0,n._rootBone=void 0,n._rootBone=new zm(w(n),"rootBone"),n._rootBone.on("set:entity",n._onSetRootBone,w(n)),n._assetReference=new hg("asset",w(n),e.app.assets,{add:n._onRenderAssetAdded,load:n._onRenderAssetLoad,remove:n._onRenderAssetRemove,unload:n._onRenderAssetUnload},w(n)),n._material=e.defaultMaterial,i.on("remove",n.onRemoveChild,w(n)),i.on("removehierarchy",n.onRemoveChild,w(n)),i.on("insert",n.onInsertChild,w(n)),i.on("inserthierarchy",n.onInsertChild,w(n)),n}S(e,t);var i=e.prototype;return i.assignAsset=function(t){var e=t instanceof Vf?t.id:t;this._assetReference.id=e},i._onSetRootBone=function(t){t&&this._onRootBoneChanged()},i._onRootBoneChanged=function(){this._clearSkinInstances(),this.enabled&&this.entity.enabled&&this._cloneSkinInstances()},i.destroyMeshInstances=function(){var t=this._meshInstances;if(t){this.removeFromLayers(),this._clearSkinInstances();for(var e=0;e<t.length;e++)t[e].destroy();this._meshInstances.length=0}},i.addToLayers=function(){for(var t=this.system.app.scene.layers,e=0;e<this._layers.length;e++){var i=t.getLayerById(this._layers[e]);i&&i.addMeshInstances(this._meshInstances)}},i.removeFromLayers=function(){if(this._meshInstances&&this._meshInstances.length)for(var t=this.system.app.scene.layers,e=0;e<this._layers.length;e++){var i=t.getLayerById(this._layers[e]);i&&i.removeMeshInstances(this._meshInstances)}},i.onRemoveChild=function(){this.removeFromLayers()},i.onInsertChild=function(){this._meshInstances&&this.enabled&&this.entity.enabled&&this.addToLayers()},i.onRemove=function(){this.destroyMeshInstances(),this.asset=null,this.materialAsset=null,this._assetReference.id=null;for(var t=0;t<this._materialReferences.length;t++)this._materialReferences[t].id=null;this.entity.off("remove",this.onRemoveChild,this),this.entity.off("insert",this.onInsertChild,this)},i.onLayersChanged=function(t,e){this.addToLayers(),t.off("add",this.onLayerAdded,this),t.off("remove",this.onLayerRemoved,this),e.on("add",this.onLayerAdded,this),e.on("remove",this.onLayerRemoved,this)},i.onLayerAdded=function(t){this.layers.indexOf(t.id)<0||t.addMeshInstances(this._meshInstances)},i.onLayerRemoved=function(t){this.layers.indexOf(t.id)<0||t.removeMeshInstances(this._meshInstances)},i.onEnable=function(){var t=this.system.app,e=t.scene;this._rootBone.onParentComponentEnable(),this._cloneSkinInstances(),e.on("set:layers",this.onLayersChanged,this),e.layers&&(e.layers.on("add",this.onLayerAdded,this),e.layers.on("remove",this.onLayerRemoved,this));var i,n="asset"===this._type;this._meshInstances&&this._meshInstances.length?this.addToLayers():n&&this.asset&&this._onRenderAssetAdded();for(var s=0;s<this._materialReferences.length;s++)this._materialReferences[s].asset&&this.system.app.assets.load(this._materialReferences[s].asset);this._batchGroupId>=0&&(null==(i=t.batcher)||i.insert(Ho.RENDER,this.batchGroupId,this.entity))},i.onDisable=function(){var t,e=this.system.app,i=e.scene;(i.off("set:layers",this.onLayersChanged,this),i.layers&&(i.layers.off("add",this.onLayerAdded,this),i.layers.off("remove",this.onLayerRemoved,this)),this._batchGroupId>=0)&&(null==(t=e.batcher)||t.remove(Ho.RENDER,this.batchGroupId,this.entity));this.removeFromLayers()},i.hide=function(){if(this._meshInstances)for(var t=0;t<this._meshInstances.length;t++)this._meshInstances[t].visible=!1},i.show=function(){if(this._meshInstances)for(var t=0;t<this._meshInstances.length;t++)this._meshInstances[t].visible=!0},i._onRenderAssetAdded=function(){this._assetReference.asset&&(this._assetReference.asset.resource?this._onRenderAssetLoad():this.enabled&&this.entity.enabled&&this.system.app.assets.load(this._assetReference.asset))},i._onRenderAssetLoad=function(){if(this.destroyMeshInstances(),this._assetReference.asset){var t=this._assetReference.asset.resource;t.off("set:meshes",this._onSetMeshes,this),t.on("set:meshes",this._onSetMeshes,this),t.meshes&&this._onSetMeshes(t.meshes)}},i._onSetMeshes=function(t){this._cloneMeshes(t)},i._clearSkinInstances=function(){for(var t=0;t<this._meshInstances.length;t++){var e=this._meshInstances[t];og.removeCachedSkinInstance(e.skinInstance),e.skinInstance=null}},i._cloneSkinInstances=function(){if(this._meshInstances.length&&this._rootBone.entity instanceof hh)for(var t=0;t<this._meshInstances.length;t++){var e=this._meshInstances[t],i=e.mesh;i.skin&&!e.skinInstance&&(e.skinInstance=og.createCachedSkinInstance(i.skin,this._rootBone.entity,this.entity))}},i._cloneMeshes=function(t){if(t&&t.length){for(var e=[],i=0;i<t.length;i++){var n=t[i],s=this._materialReferences[i]&&this._materialReferences[i].asset&&this._materialReferences[i].asset.resource,r=new yh(n,s||this.system.defaultMaterial,this.entity);e.push(r),n.morph&&(r.morphInstance=new Vu(n.morph))}this.meshInstances=e,this._cloneSkinInstances()}},i._onRenderAssetUnload=function(){"asset"===this._type&&this.destroyMeshInstances()},i._onRenderAssetRemove=function(){this._assetReference.asset&&this._assetReference.asset.resource&&this._assetReference.asset.resource.off("set:meshes",this._onSetMeshes,this),this._onRenderAssetUnload()},i._onMaterialAdded=function(t,e,i){i.resource?this._onMaterialLoad(t,e,i):this.enabled&&this.entity.enabled&&this.system.app.assets.load(i)},i._updateMainMaterial=function(t,e){0===t&&(this.material=e)},i._onMaterialLoad=function(t,e,i){this._meshInstances[t]&&(this._meshInstances[t].material=i.resource),this._updateMainMaterial(t,i.resource)},i._onMaterialRemove=function(t,e,i){this._meshInstances[t]&&(this._meshInstances[t].material=this.system.defaultMaterial),this._updateMainMaterial(t,this.system.defaultMaterial)},i._onMaterialUnload=function(t,e,i){this._meshInstances[t]&&(this._meshInstances[t].material=this.system.defaultMaterial),this._updateMainMaterial(t,this.system.defaultMaterial)},i.resolveDuplicatedEntityReferenceProperties=function(t,e){t.rootBone&&e[t.rootBone]&&(this.rootBone=e[t.rootBone]),this._clearSkinInstances()},y(e,[{key:"renderStyle",get:function(){return this._renderStyle},set:function(t){this._renderStyle!==t&&(this._renderStyle=t,yh._prepareRenderStyleForArray(this._meshInstances,t))}},{key:"customAabb",get:function(){return this._customAabb},set:function(t){this._customAabb=t;var e=this._meshInstances;if(e)for(var i=0;i<e.length;i++)e[i].setCustomAabb(this._customAabb)}},{key:"type",get:function(){return this._type},set:function(t){if(this._type!==t&&(this._area=null,this._type=t,this.destroyMeshInstances(),"asset"!==t)){var e=this._material;e&&e!==this.system.defaultMaterial||(e=this._materialReferences[0]&&this._materialReferences[0].asset&&this._materialReferences[0].asset.resource);var i=ho(this.system.app.graphicsDevice,t);this._area=i.area,this.meshInstances=[new yh(i.mesh,e||this.system.defaultMaterial,this.entity)]}}},{key:"meshInstances",get:function(){return this._meshInstances},set:function(t){if(this.destroyMeshInstances(),this._meshInstances=t,this._meshInstances){for(var e=this._meshInstances,i=0;i<e.length;i++)e[i].node||(e[i].node=this.entity),e[i].castShadow=this._castShadows,e[i].receiveShadow=this._receiveShadows,e[i].renderStyle=this._renderStyle,e[i].setLightmapped(this._lightmapped),e[i].setCustomAabb(this._customAabb);this.enabled&&this.entity.enabled&&this.addToLayers()}}},{key:"lightmapped",get:function(){return this._lightmapped},set:function(t){if(t!==this._lightmapped){this._lightmapped=t;var e=this._meshInstances;if(e)for(var i=0;i<e.length;i++)e[i].setLightmapped(t)}}},{key:"castShadows",get:function(){return this._castShadows},set:function(t){if(this._castShadows!==t){var e=this._meshInstances;if(e){var i=this.layers,n=this.system.app.scene;if(this._castShadows&&!t)for(var s=0;s<i.length;s++){var r=n.layers.getLayerById(this.layers[s]);r&&r.removeShadowCasters(e)}for(var a=0;a<e.length;a++)e[a].castShadow=t;if(!this._castShadows&&t)for(var o=0;o<i.length;o++){var h=n.layers.getLayerById(i[o]);h&&h.addShadowCasters(e)}}this._castShadows=t}}},{key:"receiveShadows",get:function(){return this._receiveShadows},set:function(t){if(this._receiveShadows!==t){this._receiveShadows=t;var e=this._meshInstances;if(e)for(var i=0;i<e.length;i++)e[i].receiveShadow=t}}},{key:"castShadowsLightmap",get:function(){return this._castShadowsLightmap},set:function(t){this._castShadowsLightmap=t}},{key:"lightmapSizeMultiplier",get:function(){return this._lightmapSizeMultiplier},set:function(t){this._lightmapSizeMultiplier=t}},{key:"layers",get:function(){return this._layers},set:function(t){var e,i=this.system.app.scene.layers;if(this._meshInstances)for(var n=0;n<this._layers.length;n++)(e=i.getLayerById(this._layers[n]))&&e.removeMeshInstances(this._meshInstances);this._layers.length=0;for(var s=0;s<t.length;s++)this._layers[s]=t[s];if(this.enabled&&this.entity.enabled&&this._meshInstances)for(var r=0;r<this._layers.length;r++)(e=i.getLayerById(this._layers[r]))&&e.addMeshInstances(this._meshInstances)}},{key:"batchGroupId",get:function(){return this._batchGroupId},set:function(t){if(this._batchGroupId!==t){var e,i;if(this.entity.enabled&&this._batchGroupId>=0)null==(e=this.system.app.batcher)||e.remove(Ho.RENDER,this.batchGroupId,this.entity);if(this.entity.enabled&&t>=0)null==(i=this.system.app.batcher)||i.insert(Ho.RENDER,t,this.entity);t<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addToLayers(),this._batchGroupId=t}}},{key:"material",get:function(){return this._material},set:function(t){if(this._material!==t&&(this._material=t,this._meshInstances&&"asset"!==this._type))for(var e=0;e<this._meshInstances.length;e++)this._meshInstances[e].material=t}},{key:"materialAssets",get:function(){return this._materialReferences.map((function(t){return t.id}))},set:function(t){if(void 0===t&&(t=[]),this._materialReferences.length>t.length){for(var e=t.length;e<this._materialReferences.length;e++)this._materialReferences[e].id=null;this._materialReferences.length=t.length}for(var i=0;i<t.length;i++)if(this._materialReferences[i]||this._materialReferences.push(new hg(i,this,this.system.app.assets,{add:this._onMaterialAdded,load:this._onMaterialLoad,remove:this._onMaterialRemove,unload:this._onMaterialUnload},this)),t[i]){var n=t[i]instanceof Vf?t[i].id:t[i];this._materialReferences[i].id!==n&&(this._materialReferences[i].id=n),this._materialReferences[i].asset&&this._onMaterialAdded(i,this,this._materialReferences[i].asset)}else this._materialReferences[i].id=null,this._meshInstances[i]&&(this._meshInstances[i].material=this.system.defaultMaterial)}},{key:"asset",get:function(){return this._assetReference.id},set:function(t){var e=t instanceof Vf?t.id:t;this._assetReference.id!==e&&(this._assetReference.asset&&this._assetReference.asset.resource&&this._onRenderAssetRemove(),this._assetReference.id=e,this._assetReference.asset&&this._onRenderAssetAdded())}}]),e}(bp),cg=function(){this.enabled=!0,this.rootBone=null},ug=[{name:"rootBone",type:"entity"},"enabled"],dg=["material","meshInstances","asset","materialAssets","castShadows","receiveShadows","castShadowsLightmap","lightmapped","lightmapSizeMultiplier","renderStyle","type","layers","isStatic","batchGroupId"],fg=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="render",i.ComponentType=lg,i.DataType=cg,i.schema=ug,i.defaultMaterial=Bo(e.graphicsDevice),i.on("beforeremove",i.onRemove,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){null!==i.batchGroupId&&void 0!==i.batchGroupId||(i.batchGroupId=-1),i.layers&&i.layers.length&&(i.layers=i.layers.slice(0));for(var s=0;s<dg.length;s++)i.hasOwnProperty(dg[s])&&(e[dg[s]]=i[dg[s]]);i.aabbCenter&&i.aabbHalfExtents&&(e.customAabb=new Ht(new wt(i.aabbCenter),new wt(i.aabbHalfExtents))),t.prototype.initializeComponentData.call(this,e,i,ug)},i.cloneComponent=function(t,e){for(var i={},n=0;n<dg.length;n++)i[dg[n]]=t.render[dg[n]];i.enabled=t.render.enabled,delete i.meshInstances;var s=this.addComponent(e,i),r=t.render.meshInstances,a=r.map((function(t){return t.mesh}));s._onSetMeshes(a);for(var o=0;o<r.length;o++)s.meshInstances[o].material=r[o].material;return t.render.customAabb&&(s.customAabb=t.render.customAabb.clone()),s},i.onRemove=function(t,e){e.onRemove()},e}(wp);bp._buildAccessors(lg.prototype,ug);var pg,mg,_g,vg,gg,yg,xg=function(){function t(t,e){this._pool=[],this._count=0,this._constructor=t,this._resize(e)}var e=t.prototype;return e._resize=function(t){if(t>this._pool.length)for(var e=this._pool.length;e<t;e++)this._pool[e]=new this._constructor},e.allocate=function(){return this._count>=this._pool.length&&this._resize(2*this._pool.length),this._pool[this._count++]},e.freeAll=function(){this._count=0},t}(),Sg=new Bt,bg=new Bt,wg=new wt,Tg=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._angularDamping=0,n._angularFactor=new wt(1,1,1),n._angularVelocity=new wt,n._body=null,n._friction=.5,n._group=2,n._linearDamping=0,n._linearFactor=new wt(1,1,1),n._linearVelocity=new wt,n._mask=__,n._mass=1,n._restitution=0,n._rollingFriction=0,n._simulationEnabled=!1,n._type=d_,n}S(e,t),e.onLibraryLoaded=function(){"undefined"!=typeof Ammo&&(pg=new Ammo.btTransform,mg=new Ammo.btVector3,_g=new Ammo.btVector3,vg=new Ammo.btQuaternion)};var i=e.prototype;return i.createBody=function(){var t,e=this.entity;if(e.collision&&(t=e.collision.shape,e.trigger&&(e.trigger.destroy(),delete e.trigger)),t){this._body&&this.system.onRemove(e,this);var i=this._type===f_?this._mass:0;this._getEntityTransform(pg);var n=this.system.createBody(i,t,pg);if(n.setRestitution(this._restitution),n.setFriction(this._friction),n.setRollingFriction(this._rollingFriction),n.setDamping(this._linearDamping,this._angularDamping),this._type===f_){var s=this._linearFactor;mg.setValue(s.x,s.y,s.z),n.setLinearFactor(mg);var r=this._angularFactor;mg.setValue(r.x,r.y,r.z),n.setAngularFactor(mg)}else this._type===p_&&(n.setCollisionFlags(2|n.getCollisionFlags()),n.setActivationState(4));n.entity=e,this.body=n,this.enabled&&e.enabled&&this.enableSimulation()}},i.isActive=function(){return!!this._body&&this._body.isActive()},i.activate=function(){this._body&&this._body.activate()},i.enableSimulation=function(){var t=this.entity;if(t.collision&&t.collision.enabled&&!this._simulationEnabled){var e=this._body;if(e){switch(this.system.addBody(e,this._group,this._mask),this._type){case f_:this.system._dynamic.push(this),e.forceActivationState(1),this.syncEntityToBody();break;case p_:this.system._kinematic.push(this),e.forceActivationState(4);break;case d_:e.forceActivationState(1),this.syncEntityToBody()}"compound"===t.collision.type&&this.system._compounds.push(t.collision),e.activate(),this._simulationEnabled=!0}}},i.disableSimulation=function(){var t=this._body;if(t&&this._simulationEnabled){var e=this.system,i=e._compounds.indexOf(this.entity.collision);i>-1&&e._compounds.splice(i,1),(i=e._dynamic.indexOf(this))>-1&&e._dynamic.splice(i,1),(i=e._kinematic.indexOf(this))>-1&&e._kinematic.splice(i,1),e.removeBody(t),t.forceActivationState(5),this._simulationEnabled=!1}},i.applyForce=function(t,e,i,n,s,r){var a=this._body;a&&(a.activate(),t instanceof wt?mg.setValue(t.x,t.y,t.z):mg.setValue(t,e,i),e instanceof wt?_g.setValue(e.x,e.y,e.z):void 0!==n?_g.setValue(n,s,r):_g.setValue(0,0,0),a.applyForce(mg,_g))},i.applyTorque=function(t,e,i){var n=this._body;n&&(n.activate(),t instanceof wt?mg.setValue(t.x,t.y,t.z):mg.setValue(t,e,i),n.applyTorque(mg))},i.applyImpulse=function(t,e,i,n,s,r){var a=this._body;a&&(a.activate(),t instanceof wt?mg.setValue(t.x,t.y,t.z):mg.setValue(t,e,i),e instanceof wt?_g.setValue(e.x,e.y,e.z):void 0!==n?_g.setValue(n,s,r):_g.setValue(0,0,0),a.applyImpulse(mg,_g))},i.applyTorqueImpulse=function(t,e,i){var n=this._body;n&&(n.activate(),t instanceof wt?mg.setValue(t.x,t.y,t.z):mg.setValue(t,e,i),n.applyTorqueImpulse(mg))},i.isStatic=function(){return this._type===d_},i.isStaticOrKinematic=function(){return this._type===d_||this._type===p_},i.isKinematic=function(){return this._type===p_},i._getEntityTransform=function(t){var e=this.entity,i=e.collision;if(i){var n=i.getShapePosition(),s=i.getShapeRotation();mg.setValue(n.x,n.y,n.z),vg.setValue(s.x,s.y,s.z,s.w)}else{var r=e.getPosition(),a=e.getRotation();mg.setValue(r.x,r.y,r.z),vg.setValue(a.x,a.y,a.z,a.w)}t.setOrigin(mg),t.setRotation(vg)},i.syncEntityToBody=function(){var t=this._body;if(t){if(this._getEntityTransform(pg),t.setWorldTransform(pg),this._type===p_){var e=t.getMotionState();e&&e.setWorldTransform(pg)}t.activate()}},i._updateDynamic=function(){var t=this._body;if(t.isActive()){var e=t.getMotionState();if(e){var i=this.entity;e.getWorldTransform(pg);var n=pg.getOrigin(),s=pg.getRotation(),r=i.collision;if(r&&r._hasOffset){var a=r.data.linearOffset,o=r.data.angularOffset,h=bg.copy(o).invert(),l=Sg.set(s.x(),s.y(),s.z(),s.w()).mul(h);l.transformVector(a,wg),i.setPosition(n.x()-wg.x,n.y()-wg.y,n.z()-wg.z),i.setRotation(l)}else i.setPosition(n.x(),n.y(),n.z()),i.setRotation(s.x(),s.y(),s.z(),s.w())}}},i._updateKinematic=function(){var t=this._body.getMotionState();t&&(this._getEntityTransform(pg),t.setWorldTransform(pg))},i.teleport=function(t,e,i,n,s,r){t instanceof wt?this.entity.setPosition(t):this.entity.setPosition(t,e,i),e instanceof Bt?this.entity.setRotation(e):e instanceof wt?this.entity.setEulerAngles(e):void 0!==n&&this.entity.setEulerAngles(n,s,r),this.syncEntityToBody()},i.onEnable=function(){this._body||this.createBody(),this.enableSimulation()},i.onDisable=function(){this.disableSimulation()},y(e,[{key:"angularDamping",get:function(){return this._angularDamping},set:function(t){this._angularDamping!==t&&(this._angularDamping=t,this._body&&this._body.setDamping(this._linearDamping,t))}},{key:"angularFactor",get:function(){return this._angularFactor},set:function(t){this._angularFactor.equals(t)||(this._angularFactor.copy(t),this._body&&this._type===f_&&(mg.setValue(t.x,t.y,t.z),this._body.setAngularFactor(mg)))}},{key:"angularVelocity",get:function(){if(this._body&&this._type===f_){var t=this._body.getAngularVelocity();this._angularVelocity.set(t.x(),t.y(),t.z())}return this._angularVelocity},set:function(t){this._body&&this._type===f_&&(this._body.activate(),mg.setValue(t.x,t.y,t.z),this._body.setAngularVelocity(mg),this._angularVelocity.copy(t))}},{key:"body",get:function(){return this._body},set:function(t){this._body!==t&&(this._body=t,t&&this._simulationEnabled&&t.activate())}},{key:"friction",get:function(){return this._friction},set:function(t){this._friction!==t&&(this._friction=t,this._body&&this._body.setFriction(t))}},{key:"group",get:function(){return this._group},set:function(t){this._group!==t&&(this._group=t,this.enabled&&this.entity.enabled&&(this.disableSimulation(),this.enableSimulation()))}},{key:"linearDamping",get:function(){return this._linearDamping},set:function(t){this._linearDamping!==t&&(this._linearDamping=t,this._body&&this._body.setDamping(t,this._angularDamping))}},{key:"linearFactor",get:function(){return this._linearFactor},set:function(t){this._linearFactor.equals(t)||(this._linearFactor.copy(t),this._body&&this._type===f_&&(mg.setValue(t.x,t.y,t.z),this._body.setLinearFactor(mg)))}},{key:"linearVelocity",get:function(){if(this._body&&this._type===f_){var t=this._body.getLinearVelocity();this._linearVelocity.set(t.x(),t.y(),t.z())}return this._linearVelocity},set:function(t){this._body&&this._type===f_&&(this._body.activate(),mg.setValue(t.x,t.y,t.z),this._body.setLinearVelocity(mg),this._linearVelocity.copy(t))}},{key:"mask",get:function(){return this._mask},set:function(t){this._mask!==t&&(this._mask=t,this.enabled&&this.entity.enabled&&(this.disableSimulation(),this.enableSimulation()))}},{key:"mass",get:function(){return this._mass},set:function(t){if(this._mass!==t&&(this._mass=t,this._body&&this._type===f_)){var e=this.enabled&&this.entity.enabled;e&&this.disableSimulation(),this._body.getCollisionShape().calculateLocalInertia(t,mg),this._body.setMassProps(t,mg),this._body.updateInertiaTensor(),e&&this.enableSimulation()}}},{key:"restitution",get:function(){return this._restitution},set:function(t){this._restitution!==t&&(this._restitution=t,this._body&&this._body.setRestitution(t))}},{key:"rollingFriction",get:function(){return this._rollingFriction},set:function(t){this._rollingFriction!==t&&(this._rollingFriction=t,this._body&&this._body.setRollingFriction(t))}},{key:"type",get:function(){return this._type},set:function(t){if(this._type!==t){switch(this._type=t,this.disableSimulation(),t){case f_:this._group=1,this._mask=m_;break;case p_:this._group=4,this._mask=m_;break;default:this._group=2,this._mask=__}this.createBody()}}}]),e}(bp),Ag=function(){this.enabled=!0},Cg=function(t,e,i,n){this.entity=t,this.point=e,this.normal=i,this.hitFraction=n},Eg=function(t,e,i){0===arguments.length?(this.a=null,this.b=null,this.impulse=0,this.localPointA=new wt,this.localPointB=new wt,this.pointA=new wt,this.pointB=new wt,this.normal=new wt):(this.a=t,this.b=e,this.impulse=i.impulse,this.localPointA=i.localPoint,this.localPointB=i.localPointOther,this.pointA=i.point,this.pointB=i.pointOther,this.normal=i.normal)},Mg=function(t,e,i,n,s,r){void 0===t&&(t=new wt),void 0===e&&(e=new wt),void 0===i&&(i=new wt),void 0===n&&(n=new wt),void 0===s&&(s=new wt),void 0===r&&(r=0),this.localPoint=t,this.localPointOther=e,this.point=i,this.pointOther=n,this.normal=s,this.impulse=r},Pg=function(t,e){this.other=t,this.contacts=e},Rg=["enabled"],Ig=function(t){function e(e){var i;return(i=t.call(this,e)||this).maxSubSteps=10,i.fixedTimeStep=1/60,i.gravity=new wt(0,-9.81,0),i._gravityFloat32=new Float32Array(3),i._dynamic=[],i._kinematic=[],i._triggers=[],i._compounds=[],i.id="rigidbody",i._stats=e.stats.frame,i.ComponentType=Tg,i.DataType=Ag,i.contactPointPool=null,i.contactResultPool=null,i.singleContactResultPool=null,i.schema=Rg,i.collisions={},i.frameCollisions={},i.on("beforeremove",i.onBeforeRemove,w(i)),i.on("remove",i.onRemove,w(i)),i}S(e,t);var i=e.prototype;return i.onLibraryLoaded=function(){if("undefined"!=typeof Ammo){if(this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.overlappingPairCache=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.dynamicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.overlappingPairCache,this.solver,this.collisionConfiguration),this.dynamicsWorld.setInternalTickCallback){var t=Ammo.addFunction(this._checkForCollisions.bind(this),"vif");this.dynamicsWorld.setInternalTickCallback(t)}gg=new Ammo.btVector3,yg=new Ammo.btVector3,Tg.onLibraryLoaded(),this.contactPointPool=new xg(Mg,1),this.contactResultPool=new xg(Pg,1),this.singleContactResultPool=new xg(Eg,1),this.app.systems.on("update",this.onUpdate,this)}else this.app.systems.off("update",this.onUpdate,this)},i.initializeComponentData=function(e,i,n){for(var s=0,r=["mass","linearDamping","angularDamping","linearFactor","angularFactor","friction","rollingFriction","restitution","type","group","mask"];s<r.length;s++){var a=r[s];if(i.hasOwnProperty(a)){var o=i[a];Array.isArray(o)?e[a]=new wt(o[0],o[1],o[2]):e[a]=o}}t.prototype.initializeComponentData.call(this,e,i,["enabled"])},i.cloneComponent=function(t,e){var i=t.rigidbody,n={enabled:i.enabled,mass:i.mass,linearDamping:i.linearDamping,angularDamping:i.angularDamping,linearFactor:[i.linearFactor.x,i.linearFactor.y,i.linearFactor.z],angularFactor:[i.angularFactor.x,i.angularFactor.y,i.angularFactor.z],friction:i.friction,rollingFriction:i.rollingFriction,restitution:i.restitution,type:i.type,group:i.group,mask:i.mask};return this.addComponent(e,n)},i.onBeforeRemove=function(t,e){e.enabled&&(e.enabled=!1)},i.onRemove=function(t,e){var i=e.body;i&&(this.removeBody(i),this.destroyBody(i),e.body=null)},i.addBody=function(t,e,i){void 0!==e&&void 0!==i?this.dynamicsWorld.addRigidBody(t,e,i):this.dynamicsWorld.addRigidBody(t)},i.removeBody=function(t){this.dynamicsWorld.removeRigidBody(t)},i.createBody=function(t,e,i){var n=new Ammo.btVector3(0,0,0);0!==t&&e.calculateLocalInertia(t,n);var s=new Ammo.btDefaultMotionState(i),r=new Ammo.btRigidBodyConstructionInfo(t,s,e,n),a=new Ammo.btRigidBody(r);return Ammo.destroy(r),Ammo.destroy(n),a},i.destroyBody=function(t){var e=t.getMotionState();e&&Ammo.destroy(e),Ammo.destroy(t)},i.raycastFirst=function(t,e,i){if(void 0===i&&(i={}),i.filterTags||i.filterCallback)return i.sort=!0,this.raycastAll(t,e,i)[0]||null;var n=null;gg.setValue(t.x,t.y,t.z),yg.setValue(e.x,e.y,e.z);var s=new Ammo.ClosestRayResultCallback(gg,yg);if("number"==typeof i.filterCollisionGroup&&s.set_m_collisionFilterGroup(i.filterCollisionGroup),"number"==typeof i.filterCollisionMask&&s.set_m_collisionFilterMask(i.filterCollisionMask),this.dynamicsWorld.rayTest(gg,yg,s),s.hasHit()){var r=s.get_m_collisionObject(),a=Ammo.castObject(r,Ammo.btRigidBody);if(a){var o=s.get_m_hitPointWorld(),h=s.get_m_hitNormalWorld();n=new Cg(a.entity,new wt(o.x(),o.y(),o.z()),new wt(h.x(),h.y(),h.z()),s.get_m_closestHitFraction())}}return Ammo.destroy(s),n},i.raycastAll=function(t,e,i){void 0===i&&(i={});var n=[];gg.setValue(t.x,t.y,t.z),yg.setValue(e.x,e.y,e.z);var s=new Ammo.AllHitsRayResultCallback(gg,yg);if("number"==typeof i.filterCollisionGroup&&s.set_m_collisionFilterGroup(i.filterCollisionGroup),"number"==typeof i.filterCollisionMask&&s.set_m_collisionFilterMask(i.filterCollisionMask),this.dynamicsWorld.rayTest(gg,yg,s),s.hasHit()){for(var r=s.get_m_collisionObjects(),a=s.get_m_hitPointWorld(),o=s.get_m_hitNormalWorld(),h=s.get_m_hitFractions(),l=r.size(),c=0;c<l;c++){var u=Ammo.castObject(r.at(c),Ammo.btRigidBody);if(u&&u.entity){var d;if(i.filterTags&&!(d=u.entity.tags).has.apply(d,i.filterTags)||i.filterCallback&&!i.filterCallback(u.entity))continue;var f=a.at(c),p=o.at(c),m=new Cg(u.entity,new wt(f.x(),f.y(),f.z()),new wt(p.x(),p.y(),p.z()),h.at(c));n.push(m)}}i.sort&&n.sort((function(t,e){return t.hitFraction-e.hitFraction}))}return Ammo.destroy(s),n},i._storeCollision=function(t,e){var i=!1,n=t.getGuid();return this.collisions[n]=this.collisions[n]||{others:[],entity:t},this.collisions[n].others.indexOf(e)<0&&(this.collisions[n].others.push(e),i=!0),this.frameCollisions[n]=this.frameCollisions[n]||{others:[],entity:t},this.frameCollisions[n].others.push(e),i},i._createContactPointFromAmmo=function(t){var e=t.get_m_localPointA(),i=t.get_m_localPointB(),n=t.getPositionWorldOnA(),s=t.getPositionWorldOnB(),r=t.get_m_normalWorldOnB(),a=this.contactPointPool.allocate();return a.localPoint.set(e.x(),e.y(),e.z()),a.localPointOther.set(i.x(),i.y(),i.z()),a.point.set(n.x(),n.y(),n.z()),a.pointOther.set(s.x(),s.y(),s.z()),a.normal.set(r.x(),r.y(),r.z()),a.impulse=t.getAppliedImpulse(),a},i._createReverseContactPointFromAmmo=function(t){var e=t.get_m_localPointA(),i=t.get_m_localPointB(),n=t.getPositionWorldOnA(),s=t.getPositionWorldOnB(),r=t.get_m_normalWorldOnB(),a=this.contactPointPool.allocate();return a.localPointOther.set(e.x(),e.y(),e.z()),a.localPoint.set(i.x(),i.y(),i.z()),a.pointOther.set(n.x(),n.y(),n.z()),a.point.set(s.x(),s.y(),s.z()),a.normal.set(r.x(),r.y(),r.z()),a.impulse=t.getAppliedImpulse(),a},i._createSingleContactResult=function(t,e,i){var n=this.singleContactResultPool.allocate();return n.a=t,n.b=e,n.localPointA=i.localPoint,n.localPointB=i.localPointOther,n.pointA=i.point,n.pointB=i.pointOther,n.normal=i.normal,n.impulse=i.impulse,n},i._createContactResult=function(t,e){var i=this.contactResultPool.allocate();return i.other=t,i.contacts=e,i},i._cleanOldCollisions=function(){for(var t in this.collisions)if(this.collisions.hasOwnProperty(t)){for(var e=this.frameCollisions[t],i=this.collisions[t],n=i.entity,s=n.collision,r=n.rigidbody,a=i.others,o=a.length;o--;){var h=a[o];(!e||e.others.indexOf(h)<0)&&(a.splice(o,1),n.trigger?(s&&s.fire("triggerleave",h),h.rigidbody&&h.rigidbody.fire("triggerleave",n)):h.trigger||(r&&r.fire("collisionend",h),s&&s.fire("collisionend",h)))}0===a.length&&delete this.collisions[t]}},i._hasContactEvent=function(t){var e=t.collision;if(e&&(e.hasEvent("collisionstart")||e.hasEvent("collisionend")||e.hasEvent("contact")))return!0;var i=t.rigidbody;return i&&(i.hasEvent("collisionstart")||i.hasEvent("collisionend")||i.hasEvent("contact"))},i._checkForCollisions=function(t,e){var i=Ammo.wrapPointer(t,Ammo.btDynamicsWorld).getDispatcher(),n=i.getNumManifolds();this.frameCollisions={};for(var s=0;s<n;s++){var r=i.getManifoldByIndexInternal(s),a=r.getBody0(),o=r.getBody1(),h=Ammo.castObject(a,Ammo.btRigidBody),l=Ammo.castObject(o,Ammo.btRigidBody),c=h.entity,u=l.entity;if(c&&u){var d=h.getCollisionFlags(),f=l.getCollisionFlags(),p=r.getNumContacts(),m=[],_=[],v=void 0;if(p>0)if(4&d||4&f){var g=c.collision&&(c.collision.hasEvent("triggerenter")||c.collision.hasEvent("triggerleave")),y=u.collision&&(u.collision.hasEvent("triggerenter")||u.collision.hasEvent("triggerleave")),x=c.rigidbody&&(c.rigidbody.hasEvent("triggerenter")||c.rigidbody.hasEvent("triggerleave")),S=u.rigidbody&&(u.rigidbody.hasEvent("triggerenter")||u.rigidbody.hasEvent("triggerleave"));g&&(!(v=this._storeCollision(c,u))||4&f||c.collision.fire("triggerenter",u)),y&&(!(v=this._storeCollision(u,c))||4&d||u.collision.fire("triggerenter",c)),x&&(v||(v=this._storeCollision(u,c)),v&&c.rigidbody.fire("triggerenter",u)),S&&(v||(v=this._storeCollision(c,u)),v&&u.rigidbody.fire("triggerenter",c))}else{var b=this._hasContactEvent(c),w=this._hasContactEvent(u),T=this.hasEvent("contact");if(T||b||w){for(var A=0;A<p;A++){var C=r.getContactPoint(A),E=this._createContactPointFromAmmo(C);if(b||w){m.push(E);var M=this._createReverseContactPointFromAmmo(C);_.push(M)}if(T){var P=this._createSingleContactResult(c,u,E);this.fire("contact",P)}}if(b){var R=this._createContactResult(u,m);v=this._storeCollision(c,u),c.collision&&(c.collision.fire("contact",R),v&&c.collision.fire("collisionstart",R)),c.rigidbody&&(c.rigidbody.fire("contact",R),v&&c.rigidbody.fire("collisionstart",R))}if(w){var I=this._createContactResult(c,_);v=this._storeCollision(u,c),u.collision&&(u.collision.fire("contact",I),v&&u.collision.fire("collisionstart",I)),u.rigidbody&&(u.rigidbody.fire("contact",I),v&&u.rigidbody.fire("collisionstart",I))}}}}}this._cleanOldCollisions(),this.contactPointPool.freeAll(),this.contactResultPool.freeAll(),this.singleContactResultPool.freeAll()},i.onUpdate=function(t){var e,i;this._gravityFloat32[0]=this.gravity.x,this._gravityFloat32[1]=this.gravity.y,this._gravityFloat32[2]=this.gravity.z;var n=this.dynamicsWorld.getGravity();n.x()===this._gravityFloat32[0]&&n.y()===this._gravityFloat32[1]&&n.z()===this._gravityFloat32[2]||(n.setValue(this.gravity.x,this.gravity.y,this.gravity.z),this.dynamicsWorld.setGravity(n));var s=this._triggers;for(e=0,i=s.length;e<i;e++)s[e].updateTransform();var r=this._compounds;for(e=0,i=r.length;e<i;e++)r[e]._updateCompound();var a=this._kinematic;for(e=0,i=a.length;e<i;e++)a[e]._updateKinematic();this.dynamicsWorld.stepSimulation(t,this.maxSubSteps,this.fixedTimeStep);var o=this._dynamic;for(e=0,i=o.length;e<i;e++)o[e]._updateDynamic();this.dynamicsWorld.setInternalTickCallback||this._checkForCollisions(Ammo.getPointer(this.dynamicsWorld),t)},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this),"undefined"!=typeof Ammo&&(Ammo.destroy(this.dynamicsWorld),Ammo.destroy(this.solver),Ammo.destroy(this.overlappingPairCache),Ammo.destroy(this.dispatcher),Ammo.destroy(this.collisionConfiguration),this.dynamicsWorld=null,this.solver=null,this.overlappingPairCache=null,this.dispatcher=null,this.collisionConfiguration=null)},e}(wp);bp._buildAccessors(Tg.prototype,Rg);var Lg="none",Dg="blend",Og=new Ft,kg=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._resolution=new Et(640,320),n._referenceResolution=new Et(640,320),n._scaleMode=Lg,n.scale=1,n._scaleBlend=.5,n._priority=0,n._screenSpace=!1,n.cull=n._screenSpace,n._screenMatrix=new Ft,n._elements=new Set,e.app.graphicsDevice.on("resizecanvas",n._onResize,w(n)),n}S(e,t);var i=e.prototype;return i.syncDrawOrder=function(){this.system.queueDrawOrderSync(this.entity.getGuid(),this._processDrawOrderSync,this)},i._recurseDrawOrderSync=function(t,e){if(!(t instanceof ip))return e;if(t.element){var i,n=t.element.drawOrder;if(t.element.drawOrder=e++,t.element._batchGroupId>=0&&n!==t.element.drawOrder)null==(i=this.system.app.batcher)||i.markGroupDirty(t.element._batchGroupId)}t.particlesystem&&(t.particlesystem.drawOrder=e++);for(var s=t.children,r=0;r<s.length;r++)e=this._recurseDrawOrderSync(s[r],e);return e},i._processDrawOrderSync=function(){this._recurseDrawOrderSync(this.entity,1),this.fire("syncdraworder")},i._calcProjectionMatrix=function(){var t=this._resolution.x/this.scale,e=this._resolution.y/this.scale,i=t,n=-e;this._screenMatrix.setOrtho(0,i,n,0,1,-1),this._screenSpace||(Og.setScale(.5*t,.5*e,1),this._screenMatrix.mul2(Og,this._screenMatrix))},i._updateScale=function(){this.scale=this._calcScale(this._resolution,this.referenceResolution)},i._calcScale=function(t,e){var i=Math.log2(t.x/e.x),n=Math.log2(t.y/e.y);return Math.pow(2,i*(1-this._scaleBlend)+n*this._scaleBlend)},i._onResize=function(t,e){this._screenSpace&&(this._resolution.set(t,e),this.resolution=this._resolution)},i._bindElement=function(t){this._elements.add(t)},i._unbindElement=function(t){this._elements.delete(t)},i.onRemove=function(){this.system.app.graphicsDevice.off("resizecanvas",this._onResize,this),this.fire("remove"),this._elements.forEach((function(t){return t._onScreenRemove()})),this._elements.clear(),this.off()},y(e,[{key:"resolution",get:function(){return this._resolution},set:function(t){var e=this;this._screenSpace?this._resolution.set(this.system.app.graphicsDevice.width,this.system.app.graphicsDevice.height):this._resolution.set(t.x,t.y),this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:resolution",this._resolution),this._elements.forEach((function(t){return t._onScreenResize(e._resolution)}))}},{key:"referenceResolution",get:function(){return this._scaleMode===Lg?this._resolution:this._referenceResolution},set:function(t){var e=this;this._referenceResolution.set(t.x,t.y),this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:referenceresolution",this._resolution),this._elements.forEach((function(t){return t._onScreenResize(e._resolution)}))}},{key:"screenSpace",get:function(){return this._screenSpace},set:function(t){this._screenSpace=t,this._screenSpace&&this._resolution.set(this.system.app.graphicsDevice.width,this.system.app.graphicsDevice.height),this.resolution=this._resolution,this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:screenspace",this._screenSpace),this._elements.forEach((function(t){return t._onScreenSpaceChange()}))}},{key:"scaleMode",get:function(){return this._scaleMode},set:function(t){t!==Lg&&t!==Dg&&(t=Lg),this._screenSpace||t===Lg||(t=Lg),this._scaleMode=t,this.resolution=this._resolution,this.fire("set:scalemode",this._scaleMode)}},{key:"scaleBlend",get:function(){return this._scaleBlend},set:function(t){var e=this;this._scaleBlend=t,this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:scaleblend",this._scaleBlend),this._elements.forEach((function(t){return t._onScreenResize(e._resolution)}))}},{key:"priority",get:function(){return this._priority},set:function(t){t>255&&(t=255),this._priority!==t&&(this._priority=t,this.syncDrawOrder())}}]),e}(bp),Fg=function(){this.enabled=!0},Bg=["enabled"],Ug=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="screen",i.ComponentType=kg,i.DataType=Fg,i.schema=Bg,i.windowResolution=new Et,i._drawOrderSyncQueue=new at,i.app.graphicsDevice.on("resizecanvas",i._onResize,w(i)),i.app.systems.on("update",i._onUpdate,w(i)),i.on("beforeremove",i.onRemoveComponent,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){void 0!==i.priority&&(e.priority=i.priority),void 0!==i.screenSpace&&(e.screenSpace=i.screenSpace),e.cull=e.screenSpace,void 0!==i.scaleMode&&(e.scaleMode=i.scaleMode),void 0!==i.scaleBlend&&(e.scaleBlend=i.scaleBlend),void 0!==i.resolution&&(i.resolution instanceof Et?e._resolution.copy(i.resolution):e._resolution.set(i.resolution[0],i.resolution[1]),e.resolution=e._resolution),void 0!==i.referenceResolution&&(i.referenceResolution instanceof Et?e._referenceResolution.copy(i.referenceResolution):e._referenceResolution.set(i.referenceResolution[0],i.referenceResolution[1]),e.referenceResolution=e._referenceResolution),e.syncDrawOrder(),t.prototype.initializeComponentData.call(this,e,i,n)},i.destroy=function(){t.prototype.destroy.call(this),this.app.graphicsDevice.off("resizecanvas",this._onResize,this),this.app.systems.off("update",this._onUpdate,this)},i._onUpdate=function(t){var e=this.store;for(var i in e)e[i].entity.screen.update&&e[i].entity.screen.update(t)},i._onResize=function(t,e){this.windowResolution.x=t,this.windowResolution.y=e},i.cloneComponent=function(t,e){var i=t.screen;return this.addComponent(e,{enabled:i.enabled,screenSpace:i.screenSpace,scaleMode:i.scaleMode,resolution:i.resolution.clone(),referenceResolution:i.referenceResolution.clone()})},i.onRemoveComponent=function(t,e){e.onRemove()},i.processDrawOrderSyncQueue=function(){for(var t=this._drawOrderSyncQueue.list(),e=0;e<t.length;e++){var i=t[e];i.callback.call(i.scope)}this._drawOrderSyncQueue.clear()},i.queueDrawOrderSync=function(t,e,i){this._drawOrderSyncQueue.list().length||this.app.once("prerender",this.processDrawOrderSyncQueue,this),this._drawOrderSyncQueue.has(t)||this._drawOrderSyncQueue.push(t,{callback:e,scope:i})},e}(wp);bp._buildAccessors(kg.prototype,Bg);var Ng=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this).on("set_scripts",n.onSetScripts,w(n)),n}S(e,t);var i=e.prototype;return i.send=function(t,e){var i,n=Array.prototype.slice.call(arguments,2),s=this.entity.script.instances;if(s&&s[t]&&(i=s[t].instance[e]))return i.apply(s[t].instance,n)},i.onEnable=function(){this.data.areScriptsLoaded&&!this.system.preloading&&(this.data.initialized?this.system._enableScriptComponent(this):this.system._initializeScriptComponent(this),this.data.postInitialized||this.system._postInitializeScriptComponent(this))},i.onDisable=function(){this.system._disableScriptComponent(this)},i.onSetScripts=function(t,e,i){if(!this.system._inTools||this.runInTools){if(this._updateScriptAttributes(e,i))return;this.enabled&&this.system._disableScriptComponent(this),this.system._destroyScriptComponent(this),this.data.areScriptsLoaded=!1;var n=i.map((function(t){return t.url}));if(this._loadFromCache(n))return;this._loadScripts(n)}},i._updateScriptAttributes=function(t,e){var i=!0;if(t.length!==e.length)i=!1;else for(var n=0,s=e.length;n<s;n++)if(t[n].url!==e[n].url){i=!1;break}if(i)for(var r in this.instances)this.instances.hasOwnProperty(r)&&this.system._updateAccessors(this.entity,this.instances[r]);return i},i._loadFromCache=function(t){for(var e=[],i=this.system.app._scriptPrefix||"",n=/^http(s)?:\/\//i,s=0,r=t.length;s<r;s++){var a=t[s];n.test(a)||(a=L.join(i,a));var o=this.system.app.loader.getFromCache(a,"script");if(!o)return!1;e.push(o)}for(var h=0,l=e.length;h<l;h++){var c=e[h];if(!0!==c&&(c&&this.entity.script&&!this.entity.script.instances[c._pcScriptName])){var u=new c(this.entity);this.system._preRegisterInstance(this.entity,t[h],c._pcScriptName,u)}}return this.data&&(this.data.areScriptsLoaded=!0),this.system.preloading||(this.system.onInitialize(this.entity),this.system.onPostInitialize(this.entity)),!0},i._loadScripts=function(t){var e=this,i=t.length,n=this.system.app._scriptPrefix||"";t.forEach((function(t){var s=null,r=null;t.toLowerCase().startsWith("http://")||t.toLowerCase().startsWith("https://")?(r=t,s=t):(r=t,s=L.join(n,t)),e.system.app.loader.load(s,"script",(function(t,n){if(i--,t)console.error(t);else if(n&&e.entity.script&&!e.entity.script.instances[n._pcScriptName]){var s=new n(e.entity);e.system._preRegisterInstance(e.entity,r,n._pcScriptName,s)}0===i&&(e.data.areScriptsLoaded=!0,e.system.preloading||(e.system.onInitialize(e.entity),e.system.onPostInitialize(e.entity)))}))}))},e}(bp),zg=function(){this.scripts=[],this.enabled=!0,this.instances={},this._instances={},this.runInTools=!1,this.attributes={},this.initialized=!1,this.postInitialized=!1,this.areScriptsLoaded=!1},Vg=["enabled","scripts","instances","runInTools"],Gg="initialize",Hg="postInitialize",Wg="update",Xg="postUpdate",jg="fixedUpdate",qg="toolsUpdate",Yg=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="script",i.ComponentType=Ng,i.DataType=zg,i.schema=Vg,i.preloading=!1,i.instancesWithUpdate=[],i.instancesWithFixedUpdate=[],i.instancesWithPostUpdate=[],i.instancesWithToolsUpdate=[],i.on("beforeremove",i.onBeforeRemove,w(i)),i.app.systems.on(Gg,i.onInitialize,w(i)),i.app.systems.on(Hg,i.onPostInitialize,w(i)),i.app.systems.on(Wg,i.onUpdate,w(i)),i.app.systems.on(jg,i.onFixedUpdate,w(i)),i.app.systems.on(Xg,i.onPostUpdate,w(i)),i.app.systems.on(qg,i.onToolsUpdate,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){n=["runInTools","enabled","scripts"],i.scripts&&i.scripts.length&&i.scripts.forEach((function(t){if(t.attributes&&Array.isArray(t.attributes)){for(var e={},i=0;i<t.attributes.length;i++)e[t.attributes[i].name]=t.attributes[i];t.attributes=e}})),t.prototype.initializeComponentData.call(this,e,i,n)},i.cloneComponent=function(t,e){for(var i=this.store[t.getGuid()],n={runInTools:i.data.runInTools,scripts:[],enabled:i.data.enabled},s=i.data.scripts,r=0,a=s.length;r<a;r++){var o=s[r].attributes;o&&delete s[r].attributes,n.scripts.push(p({},s[r])),o&&(n.scripts[r].attributes=this._cloneAttributes(o),s[r].attributes=o)}return this.addComponent(e,n)},i.onBeforeRemove=function(t,e){e.enabled&&this._disableScriptComponent(e),this._destroyScriptComponent(e)},i.onInitialize=function(t){if(this._registerInstances(t),t.enabled){t.script&&t.script.enabled&&this._initializeScriptComponent(t.script);for(var e=t._children,i=0,n=e.length;i<n;i++)e[i]instanceof ip&&this.onInitialize(e[i])}},i.onPostInitialize=function(t){if(t.enabled){t.script&&t.script.enabled&&this._postInitializeScriptComponent(t.script);for(var e=t._children,i=0,n=e.length;i<n;i++)e[i]instanceof ip&&this.onPostInitialize(e[i])}},i._callInstancesMethod=function(t,e){var i=t.data.instances;for(var n in i)if(i.hasOwnProperty(n)){var s=i[n].instance;s[e]&&s[e]()}},i._initializeScriptComponent=function(t){this._callInstancesMethod(t,Gg),t.data.initialized=!0,t.enabled&&t.entity.enabled&&this._enableScriptComponent(t)},i._enableScriptComponent=function(t){this._callInstancesMethod(t,"onEnable")},i._disableScriptComponent=function(t){this._callInstancesMethod(t,"onDisable")},i._destroyScriptComponent=function(t){var e=t.data.instances;for(var i in e)if(e.hasOwnProperty(i)){var n=e[i].instance;if(n.destroy&&n.destroy(),n.update){var s=this.instancesWithUpdate.indexOf(n);s>=0&&this.instancesWithUpdate.splice(s,1)}if(n.fixedUpdate){var r=this.instancesWithFixedUpdate.indexOf(n);r>=0&&this.instancesWithFixedUpdate.splice(r,1)}if(n.postUpdate){var a=this.instancesWithPostUpdate.indexOf(n);a>=0&&this.instancesWithPostUpdate.splice(a,1)}if(n.toolsUpdate){var o=this.instancesWithToolsUpdate.indexOf(n);o>=0&&this.instancesWithToolsUpdate.splice(o,1)}t.instances[i].instance===t[i]&&delete t[i],delete t.instances[i]}},i._postInitializeScriptComponent=function(t){this._callInstancesMethod(t,Hg),t.data.postInitialized=!0},i._updateInstances=function(t,e,i){for(var n=0,s=e.length;n<s;n++){var r=e[n];r&&r.entity&&r.entity.enabled&&r.entity.script.enabled&&r[t](i)}},i.onUpdate=function(t){this._updateInstances(Wg,this.instancesWithUpdate,t)},i.onFixedUpdate=function(t){this._updateInstances(jg,this.instancesWithFixedUpdate,t)},i.onPostUpdate=function(t){this._updateInstances(Xg,this.instancesWithPostUpdate,t)},i.onToolsUpdate=function(t){this._updateInstances(qg,this.instancesWithToolsUpdate,t)},i.broadcast=function(t,e){var i=Array.prototype.slice.call(arguments,2),n=this.store;for(var s in n)if(n.hasOwnProperty(s)){var r=n[s].data;if(r.instances[t]){var a=r.instances[t].instance[e];a&&a.apply(r.instances[t].instance,i)}}},i._preRegisterInstance=function(t,e,i,n){if(t.script){if(t.script.data._instances=t.script.data._instances||{},t.script.data._instances[i])throw Error("Script name collision '"+i+"'. Scripts from '"+e+"' and '"+t.script.data._instances[i].url+"' {"+t.getGuid()+"}");t.script.data._instances[i]={url:e,name:i,instance:n}}},i._registerInstances=function(t){if(t.script&&t.script.data._instances){for(var e in t.script.instances=t.script.data._instances,t.script.instances){var i=t.script.instances[e],n=i.instance;if(R.attach(n),n.update&&this.instancesWithUpdate.push(n),n.fixedUpdate&&this.instancesWithFixedUpdate.push(n),n.postUpdate&&this.instancesWithPostUpdate.push(n),n.toolsUpdate&&this.instancesWithToolsUpdate.push(n),t.script.scripts&&this._createAccessors(t,i),t.script[e])throw Error("Script with name '"+e+"' is already attached to Script Component");t.script[e]=n}delete t.script.data._instances}for(var s=t._children,r=0,a=s.length;r<a;r++)s[r]instanceof ip&&this._registerInstances(s[r])},i._cloneAttributes=function(t){var e={};for(var i in t)if(t.hasOwnProperty(i))if("entity"!==t[i].type)e[i]=p({},t[i]);else{var n=t[i].value;delete t[i].value,e[i]=p({},t[i]),e[i].value=n,t[i].value=n}return e},i._createAccessors=function(t,e){for(var i=t.script.scripts.length,n=e.url,s=0;s<i;s++){var r=t.script.scripts[s];if(r.url===n){var a=r.attributes;if(r.name&&a){for(var o in a)a.hasOwnProperty(o)&&this._createAccessor(a[o],e);t.script.data.attributes[r.name]=this._cloneAttributes(a)}break}}},i._createAccessor=function(t,e){var i=this;t={name:t.name,value:t.value,type:t.type},this._convertAttributeValue(t),Object.defineProperty(e.instance,t.name,{get:function(){return t.value},set:function(n){var s=t.value;t.value=n,i._convertAttributeValue(t),e.instance.fire("set",t.name,s,t.value)},configurable:!0})},i._updateAccessors=function(t,e){for(var i=t.script.scripts.length,n=e.url,s=0;s<i;s++){var r=t.script,a=r.scripts[s];if(a.url===n){var o=a.name,h=a.attributes;if(o){if(h)for(var l in h)h.hasOwnProperty(l)&&this._createAccessor(h[l],e);var c=r.data.attributes[o];if(c)for(var u in c){var d=c[u];u in h?h[u].value!==d.value&&e.instance.onAttributeChanged&&e.instance.onAttributeChanged(d.name,d.value,h[u].value):delete e.instance[d.name]}h?r.data.attributes[o]=this._cloneAttributes(h):delete r.data.attributes[o]}break}}},i._convertAttributeValue=function(t){if("rgb"===t.type||"rgba"===t.type)Array.isArray(t.value)&&(t.value=3===t.value.length?new vt(t.value[0],t.value[1],t.value[2]):new vt(t.value[0],t.value[1],t.value[2],t.value[3]));else if("vec2"===t.type)Array.isArray(t.value)&&(t.value=new Et(t.value[0],t.value[1]));else if("vec3"===t.type||"vector"===t.type)Array.isArray(t.value)&&(t.value=new wt(t.value[0],t.value[1],t.value[2]));else if("vec4"===t.type)Array.isArray(t.value)&&(t.value=new Pt(t.value[0],t.value[1],t.value[2],t.value[3]));else if("entity"===t.type)null!==t.value&&"string"==typeof t.value&&(t.value=this.app.root.findByGuid(t.value));else if("curve"===t.type||"colorcurve"===t.type){var e=t.value.keys[0]instanceof Array?bt:St;t.value=new e(t.value.keys),t.value.type=t.value.type}},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off(Gg,this.onInitialize,this),this.app.systems.off(Hg,this.onPostInitialize,this),this.app.systems.off(Wg,this.onUpdate,this),this.app.systems.off(jg,this.onFixedUpdate,this),this.app.systems.off(Xg,this.onPostUpdate,this),this.app.systems.off(qg,this.onToolsUpdate,this)},e}(wp);bp._buildAccessors(Ng.prototype,Vg);var Kg=new Et,Zg=new wt,Qg=new Yt,$g=new te,Jg=new wt,ty=new wt,ey=new Bt,iy={x:"y",y:"x"},ny=function(t){function e(e,i){var n;if(n=t.call(this)||this,!(e&&e instanceof fv))throw new Error("Element was null or not an ElementComponent");if(i&&"x"!==i&&"y"!==i)throw new Error("Unrecognized axis: "+i);return n._element=e,n._app=e.system.app,n._axis=i||null,n._enabled=!0,n._dragScale=new wt,n._dragStartMousePosition=new wt,n._dragStartHandlePosition=new wt,n._deltaMousePosition=new wt,n._deltaHandlePosition=new wt,n._isDragging=!1,n._toggleLifecycleListeners("on"),n}S(e,t);var i=e.prototype;return i._toggleLifecycleListeners=function(t){this._element[t]("mousedown",this._onMouseDownOrTouchStart,this),this._element[t]("touchstart",this._onMouseDownOrTouchStart,this),this._element[t]("selectstart",this._onMouseDownOrTouchStart,this)},i._toggleDragListeners=function(t){var e="on"===t;this._hasDragListeners&&e||(this._app.mouse&&(this._element[t]("mousemove",this._onMove,this),this._element[t]("mouseup",this._onMouseUpOrTouchEnd,this)),G.touch&&(this._element[t]("touchmove",this._onMove,this),this._element[t]("touchend",this._onMouseUpOrTouchEnd,this),this._element[t]("touchcancel",this._onMouseUpOrTouchEnd,this)),this._element[t]("selectmove",this._onMove,this),this._element[t]("selectend",this._onMouseUpOrTouchEnd,this),this._hasDragListeners=e)},i._onMouseDownOrTouchStart=function(t){if(this._element&&!this._isDragging&&this.enabled){this._dragCamera=t.camera,this._calculateDragScale();var e=this._screenToLocal(t);e&&(this._toggleDragListeners("on"),this._isDragging=!0,this._dragStartMousePosition.copy(e),this._dragStartHandlePosition.copy(this._element.entity.getLocalPosition()),this.fire("drag:start"))}},i._onMouseUpOrTouchEnd=function(){this._isDragging&&(this._isDragging=!1,this._toggleDragListeners("off"),this.fire("drag:end"))},i._screenToLocal=function(t){return t.inputSource?Qg.set(t.inputSource.getOrigin(),t.inputSource.getDirection()):(this._determineInputPosition(t),this._chooseRayOriginAndDirection()),Jg.copy(this._element.entity.forward).mulScalar(-1),$g.setFromPointNormal(this._element.entity.getPosition(),Jg),$g.intersectsRay(Qg,ty)?(ey.copy(this._element.entity.getRotation()).invert().transformVector(ty,ty),ty.mul(this._dragScale),ty):null},i._determineInputPosition=function(t){var e=this._app.graphicsDevice.maxPixelRatio;void 0!==t.x&&void 0!==t.y?(Kg.x=t.x*e,Kg.y=t.y*e):t.changedTouches?(Kg.x=t.changedTouches[0].x*e,Kg.y=t.changedTouches[0].y*e):console.warn("Could not determine position from input event")},i._chooseRayOriginAndDirection=function(){this._element.screen&&this._element.screen.screen.screenSpace?(Qg.origin.set(Kg.x,-Kg.y,0),Qg.direction.copy(wt.FORWARD)):(Zg.copy(this._dragCamera.screenToWorld(Kg.x,Kg.y,1)),Qg.origin.copy(this._dragCamera.entity.getPosition()),Qg.direction.copy(Zg).sub(Qg.origin).normalize())},i._calculateDragScale=function(){var t=this._element.entity.parent,e=this._element.screen&&this._element.screen.screen,i=e&&e.screenSpace,n=i?e.scale:1,s=this._dragScale;for(s.set(n,n,n);t&&(s.mul(t.getLocalScale()),t=t.parent,!i||!t.screen););s.x=1/s.x,s.y=1/s.y,s.z=0},i._onMove=function(t){var e=this._element,i=this._deltaMousePosition,n=this._deltaHandlePosition,s=this._axis;if(e&&this._isDragging&&this.enabled&&e.enabled&&e.entity.enabled){var r=this._screenToLocal(t);if(r){if(i.sub2(r,this._dragStartMousePosition),n.add2(this._dragStartHandlePosition,i),s){var a=e.entity.getLocalPosition(),o=iy[s];n[o]=a[o]}e.entity.setLocalPosition(n),this.fire("drag:move",n)}}},i.destroy=function(){this._toggleLifecycleListeners("off"),this._toggleDragListeners("off")},y(e,[{key:"enabled",get:function(){return this._enabled},set:function(t){this._enabled=t}},{key:"isDragging",get:function(){return this._isDragging}}]),e}(P),sy=new Et,ry=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._viewportReference=new zm(w(n),"viewportEntity",{"element#gain":n._onViewportElementGain,"element#resize":n._onSetContentOrViewportSize}),n._contentReference=new zm(w(n),"contentEntity",{"element#gain":n._onContentElementGain,"element#lose":n._onContentElementLose,"element#resize":n._onSetContentOrViewportSize}),n._scrollbarUpdateFlags={},n._scrollbarReferences={},n._scrollbarReferences[0]=new zm(w(n),"horizontalScrollbarEntity",{"scrollbar#set:value":n._onSetHorizontalScrollbarValue,"scrollbar#gain":n._onHorizontalScrollbarGain}),n._scrollbarReferences[1]=new zm(w(n),"verticalScrollbarEntity",{"scrollbar#set:value":n._onSetVerticalScrollbarValue,"scrollbar#gain":n._onVerticalScrollbarGain}),n._prevContentSizes={},n._prevContentSizes[0]=null,n._prevContentSizes[1]=null,n._scroll=new Et,n._velocity=new wt,n._dragStartPosition=new wt,n._disabledContentInput=!1,n._disabledContentInputEntities=[],n._toggleLifecycleListeners("on",e),n._toggleElementListeners("on"),n}S(e,t);var i=e.prototype;return i._toggleLifecycleListeners=function(t,e){this[t]("set_horizontal",this._onSetHorizontalScrollingEnabled,this),this[t]("set_vertical",this._onSetVerticalScrollingEnabled,this),e.app.systems.element[t]("add",this._onElementComponentAdd,this),e.app.systems.element[t]("beforeremove",this._onElementComponentRemove,this)},i._toggleElementListeners=function(t){if(this.entity.element){if("on"===t&&this._hasElementListeners)return;this.entity.element[t]("resize",this._onSetContentOrViewportSize,this),this.entity.element[t](Nr,this._onMouseWheel,this),this._hasElementListeners="on"===t}},i._onElementComponentAdd=function(t){this.entity===t&&this._toggleElementListeners("on")},i._onElementComponentRemove=function(t){this.entity===t&&this._toggleElementListeners("off")},i._onViewportElementGain=function(){this._syncAll()},i._onContentElementGain=function(){this._destroyDragHelper(),this._contentDragHelper=new ny(this._contentReference.entity.element),this._contentDragHelper.on("drag:start",this._onContentDragStart,this),this._contentDragHelper.on("drag:end",this._onContentDragEnd,this),this._contentDragHelper.on("drag:move",this._onContentDragMove,this),this._prevContentSizes[0]=null,this._prevContentSizes[1]=null,this._syncAll()},i._onContentElementLose=function(){this._destroyDragHelper()},i._onContentDragStart=function(){this._contentReference.entity&&this.enabled&&this.entity.enabled&&this._dragStartPosition.copy(this._contentReference.entity.getLocalPosition())},i._onContentDragEnd=function(){this._prevContentDragPosition=null,this._enableContentInput()},i._onContentDragMove=function(t){if(this._contentReference.entity&&this.enabled&&this.entity.enabled&&(this._wasDragged=!0,this._setScrollFromContentPosition(t),this._setVelocityFromContentPositionDelta(t),!this._disabledContentInput)){var e=t.x-this._dragStartPosition.x,i=t.y-this._dragStartPosition.y;(Math.abs(e)>this.dragThreshold||Math.abs(i)>this.dragThreshold)&&this._disableContentInput()}},i._onSetContentOrViewportSize=function(){this._syncAll()},i._onSetHorizontalScrollbarValue=function(t){!this._scrollbarUpdateFlags[0]&&this.enabled&&this.entity.enabled&&this._onSetScroll(t,null)},i._onSetVerticalScrollbarValue=function(t){!this._scrollbarUpdateFlags[1]&&this.enabled&&this.entity.enabled&&this._onSetScroll(null,t)},i._onSetHorizontalScrollingEnabled=function(){this._syncScrollbarEnabledState(0)},i._onSetVerticalScrollingEnabled=function(){this._syncScrollbarEnabledState(1)},i._onHorizontalScrollbarGain=function(){this._syncScrollbarEnabledState(0),this._syncScrollbarPosition(0)},i._onVerticalScrollbarGain=function(){this._syncScrollbarEnabledState(1),this._syncScrollbarPosition(1)},i._onSetScroll=function(t,e,i){!1!==i&&this._velocity.set(0,0,0);var n=this._updateAxis(t,"x",0),s=this._updateAxis(e,"y",1);(n||s)&&this.fire("set:scroll",this._scroll)},i._updateAxis=function(t,e,i){var n=null!==t&&Math.abs(t-this._scroll[e])>1e-5;return(n||this._isDragging()||0===t)&&(this._scroll[e]=this._determineNewScrollValue(t,e,i),this._syncContentPosition(i),this._syncScrollbarPosition(i)),n},i._determineNewScrollValue=function(t,e,i){if(!this._getScrollingEnabled(i))return this._scroll[e];switch(this.scrollMode){case 0:return _t.clamp(t,0,this._getMaxScrollValue(i));case 1:return this._setVelocityFromOvershoot(t,e,i),t;case 2:return t;default:return console.warn("Unhandled scroll mode:"+this.scrollMode),t}},i._syncAll=function(){this._syncContentPosition(0),this._syncContentPosition(1),this._syncScrollbarPosition(0),this._syncScrollbarPosition(1),this._syncScrollbarEnabledState(0),this._syncScrollbarEnabledState(1)},i._syncContentPosition=function(t){var e=this._getAxis(t),i=this._getSign(t),n=this._contentReference.entity;if(n){var s=this._prevContentSizes[t],r=this._getContentSize(t);if(null!==s&&Math.abs(s-r)>1e-4){var a=this._getMaxOffset(t,s),o=this._getMaxOffset(t,r);this._scroll[e]=0===o?1:_t.clamp(this._scroll[e]*a/o,0,1)}var h=this._scroll[e]*this._getMaxOffset(t),l=n.getLocalPosition();l[e]=h*i,n.setLocalPosition(l),this._prevContentSizes[t]=r}},i._syncScrollbarPosition=function(t){var e=this._getAxis(t),i=this._scrollbarReferences[t].entity;i&&i.scrollbar&&(this._scrollbarUpdateFlags[t]=!0,i.scrollbar.value=this._scroll[e],i.scrollbar.handleSize=this._getScrollbarHandleSize(e,t),this._scrollbarUpdateFlags[t]=!1)},i._syncScrollbarEnabledState=function(t){var e=this._scrollbarReferences[t].entity;if(e){var i=this._getScrollingEnabled(t),n=this._getScrollbarVisibility(t);switch(n){case 0:return void(e.enabled=i);case 1:return void(e.enabled=i&&this._contentIsLargerThanViewport(t));default:console.warn("Unhandled scrollbar visibility:"+n),e.enabled=i}}},i._contentIsLargerThanViewport=function(t){return this._getContentSize(t)>this._getViewportSize(t)},i._contentPositionToScrollValue=function(t){var e=this._getMaxOffset(0),i=this._getMaxOffset(1);return sy.x=0===e?0:t.x/e,sy.y=0===i?0:t.y/-i,sy},i._getMaxOffset=function(t,e){e=void 0===e?this._getContentSize(t):e;var i=this._getViewportSize(t);return e<i?-this._getViewportSize(t):i-e},i._getMaxScrollValue=function(t){return this._contentIsLargerThanViewport(t)?1:0},i._getScrollbarHandleSize=function(t,e){var i=this._getViewportSize(e),n=this._getContentSize(e);if(Math.abs(n)<.001)return 1;var s=Math.min(i/n,1),r=this._toOvershoot(this._scroll[t],e);return 0===r?s:s/(1+Math.abs(r))},i._getViewportSize=function(t){return this._getSize(t,this._viewportReference)},i._getContentSize=function(t){return this._getSize(t,this._contentReference)},i._getSize=function(t,e){return e.entity&&e.entity.element?e.entity.element[this._getCalculatedDimension(t)]:0},i._getScrollingEnabled=function(t){return 0===t?this.horizontal:1===t?this.vertical:void 0},i._getScrollbarVisibility=function(t){return 0===t?this.horizontalScrollbarVisibility:1===t?this.verticalScrollbarVisibility:void 0},i._getSign=function(t){return 0===t?1:-1},i._getAxis=function(t){return 0===t?"x":"y"},i._getCalculatedDimension=function(t){return 0===t?"calculatedWidth":"calculatedHeight"},i._destroyDragHelper=function(){this._contentDragHelper&&this._contentDragHelper.destroy()},i.onUpdate=function(){this._contentReference.entity&&(this._updateVelocity(),this._syncScrollbarEnabledState(0),this._syncScrollbarEnabledState(1))},i._updateVelocity=function(){if(!this._isDragging()){if(1===this.scrollMode&&(this._hasOvershoot("x",0)&&this._setVelocityFromOvershoot(this.scroll.x,"x",0),this._hasOvershoot("y",1)&&this._setVelocityFromOvershoot(this.scroll.y,"y",1)),Math.abs(this._velocity.x)>1e-4||Math.abs(this._velocity.y)>1e-4){var t=this._contentReference.entity.getLocalPosition();t.x+=this._velocity.x,t.y+=this._velocity.y,this._contentReference.entity.setLocalPosition(t),this._setScrollFromContentPosition(t)}this._velocity.x*=1-this.friction,this._velocity.y*=1-this.friction}},i._hasOvershoot=function(t,e){return Math.abs(this._toOvershoot(this.scroll[t],e))>.001},i._toOvershoot=function(t,e){var i=this._getMaxScrollValue(e);return t<0?t:t>i?t-i:0},i._setVelocityFromOvershoot=function(t,e,i){var n=this._toOvershoot(t,i)*this._getMaxOffset(i)*this._getSign(i);Math.abs(n)>0&&(this._velocity[e]=-n/(50*this.bounceAmount+1))},i._setVelocityFromContentPositionDelta=function(t){this._prevContentDragPosition?(this._velocity.sub2(t,this._prevContentDragPosition),this._prevContentDragPosition.copy(t)):(this._velocity.set(0,0,0),this._prevContentDragPosition=t.clone())},i._setScrollFromContentPosition=function(t){var e=this._contentPositionToScrollValue(t);this._isDragging()&&(e=this._applyScrollValueTension(e)),this._onSetScroll(e.x,e.y,!1)},i._applyScrollValueTension=function(t){var e=this._getMaxScrollValue(0),i=this._toOvershoot(t.x,0);return i>0?t.x=e+1*Math.log10(1+i):i<0&&(t.x=-1*Math.log10(1-i)),e=this._getMaxScrollValue(1),(i=this._toOvershoot(t.y,1))>0?t.y=e+1*Math.log10(1+i):i<0&&(t.y=-1*Math.log10(1-i)),t},i._isDragging=function(){return this._contentDragHelper&&this._contentDragHelper.isDragging},i._setScrollbarComponentsEnabled=function(t){this._scrollbarReferences[0].hasComponent("scrollbar")&&(this._scrollbarReferences[0].entity.scrollbar.enabled=t),this._scrollbarReferences[1].hasComponent("scrollbar")&&(this._scrollbarReferences[1].entity.scrollbar.enabled=t)},i._setContentDraggingEnabled=function(t){this._contentDragHelper&&(this._contentDragHelper.enabled=t)},i._onMouseWheel=function(t){if(this.useMouseWheel){var e=t.event,i=e.deltaX/this._contentReference.entity.element.calculatedWidth*this.mouseWheelSensitivity.x,n=e.deltaY/this._contentReference.entity.element.calculatedHeight*this.mouseWheelSensitivity.y,s=_t.clamp(this._scroll.x+i,0,this._getMaxScrollValue(0)),r=_t.clamp(this._scroll.y+n,0,this._getMaxScrollValue(1));this.scroll=new Et(s,r)}},i._enableContentInput=function(){for(;this._disabledContentInputEntities.length;){var t=this._disabledContentInputEntities.pop();t.element&&(t.element.useInput=!0)}this._disabledContentInput=!1},i._disableContentInput=function(){var t=this,e=function e(i){i.element&&i.element.useInput&&(t._disabledContentInputEntities.push(i),i.element.useInput=!1);for(var n=i.children,s=0,r=n.length;s<r;s++)e(n[s])},i=this._contentReference.entity;if(i)for(var n=i.children,s=0,r=n.length;s<r;s++)e(n[s]);this._disabledContentInput=!0},i.onEnable=function(){this._viewportReference.onParentComponentEnable(),this._contentReference.onParentComponentEnable(),this._scrollbarReferences[0].onParentComponentEnable(),this._scrollbarReferences[1].onParentComponentEnable(),this._setScrollbarComponentsEnabled(!0),this._setContentDraggingEnabled(!0),this._syncAll()},i.onDisable=function(){this._setScrollbarComponentsEnabled(!1),this._setContentDraggingEnabled(!1)},i.onRemove=function(){this._toggleLifecycleListeners("off",this.system),this._toggleElementListeners("off"),this._destroyDragHelper()},y(e,[{key:"scroll",get:function(){return this._scroll},set:function(t){this._onSetScroll(t.x,t.y)}}]),e}(bp),ay=function(){this.enabled=!0},oy=[{name:"enabled",type:"boolean"},{name:"horizontal",type:"boolean"},{name:"vertical",type:"boolean"},{name:"scrollMode",type:"number"},{name:"bounceAmount",type:"number"},{name:"friction",type:"number"},{name:"dragThreshold",type:"number"},{name:"useMouseWheel",type:"boolean"},{name:"mouseWheelSensitivity",type:"vec2"},{name:"horizontalScrollbarVisibility",type:"number"},{name:"verticalScrollbarVisibility",type:"number"},{name:"viewportEntity",type:"entity"},{name:"contentEntity",type:"entity"},{name:"horizontalScrollbarEntity",type:"entity"},{name:"verticalScrollbarEntity",type:"entity"}],hy=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="scrollview",i.ComponentType=ry,i.DataType=ay,i.schema=oy,i.on("beforeremove",i._onRemoveComponent,w(i)),i.app.systems.on("update",i.onUpdate,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){void 0===i.dragThreshold&&(i.dragThreshold=10),void 0===i.useMouseWheel&&(i.useMouseWheel=!0),void 0===i.mouseWheelSensitivity&&(i.mouseWheelSensitivity=new Et(1,1)),t.prototype.initializeComponentData.call(this,e,i,oy)},i.onUpdate=function(t){var e=this.store;for(var i in e){var n=e[i].entity,s=n.scrollview;s.enabled&&n.enabled&&s.onUpdate()}},i._onRemoveComponent=function(t,e){e.onRemove()},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},e}(wp);bp._buildAccessors(ry.prototype,oy);var ly=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._handleReference=new zm(w(n),"handleEntity",{"element#gain":n._onHandleElementGain,"element#lose":n._onHandleElementLose,"element#set:anchor":n._onSetHandleAlignment,"element#set:margin":n._onSetHandleAlignment,"element#set:pivot":n._onSetHandleAlignment}),n._toggleLifecycleListeners("on"),n}S(e,t);var i=e.prototype;return i._toggleLifecycleListeners=function(t){this[t]("set_value",this._onSetValue,this),this[t]("set_handleSize",this._onSetHandleSize,this),this[t]("set_orientation",this._onSetOrientation,this)},i._onHandleElementGain=function(){this._destroyDragHelper(),this._handleDragHelper=new ny(this._handleReference.entity.element,this._getAxis()),this._handleDragHelper.on("drag:move",this._onHandleDrag,this),this._updateHandlePositionAndSize()},i._onHandleElementLose=function(){this._destroyDragHelper()},i._onHandleDrag=function(t){this._handleReference.entity&&this.enabled&&this.entity.enabled&&(this.value=this._handlePositionToScrollValue(t[this._getAxis()]))},i._onSetValue=function(t,e,i){Math.abs(i-e)>1e-5&&(this.data.value=_t.clamp(i,0,1),this._updateHandlePositionAndSize(),this.fire("set:value",this.data.value))},i._onSetHandleSize=function(t,e,i){Math.abs(i-e)>1e-5&&(this.data.handleSize=_t.clamp(i,0,1),this._updateHandlePositionAndSize())},i._onSetHandleAlignment=function(){this._updateHandlePositionAndSize()},i._onSetOrientation=function(t,e,i){i!==e&&this._handleReference.hasComponent("element")&&(this._handleReference.entity.element[this._getOppositeDimension()]=0)},i._updateHandlePositionAndSize=function(){var t=this._handleReference.entity,e=t&&t.element;if(t){var i=t.getLocalPosition();i[this._getAxis()]=this._getHandlePosition(),this._handleReference.entity.setLocalPosition(i)}e&&(e[this._getDimension()]=this._getHandleLength())},i._handlePositionToScrollValue=function(t){return t*this._getSign()/this._getUsableTrackLength()},i._scrollValueToHandlePosition=function(t){return t*this._getSign()*this._getUsableTrackLength()},i._getUsableTrackLength=function(){return Math.max(this._getTrackLength()-this._getHandleLength(),.001)},i._getTrackLength=function(){return this.entity.element?0===this.orientation?this.entity.element.calculatedWidth:this.entity.element.calculatedHeight:0},i._getHandleLength=function(){return this._getTrackLength()*this.handleSize},i._getHandlePosition=function(){return this._scrollValueToHandlePosition(this.value)},i._getSign=function(){return 0===this.orientation?1:-1},i._getAxis=function(){return 0===this.orientation?"x":"y"},i._getDimension=function(){return 0===this.orientation?"width":"height"},i._getOppositeDimension=function(){return 0===this.orientation?"height":"width"},i._destroyDragHelper=function(){this._handleDragHelper&&this._handleDragHelper.destroy()},i._setHandleDraggingEnabled=function(t){this._handleDragHelper&&(this._handleDragHelper.enabled=t)},i.onEnable=function(){this._handleReference.onParentComponentEnable(),this._setHandleDraggingEnabled(!0)},i.onDisable=function(){this._setHandleDraggingEnabled(!1)},i.onRemove=function(){this._destroyDragHelper(),this._toggleLifecycleListeners("off")},e}(bp),cy=function(){this.enabled=!0},uy=[{name:"enabled",type:"boolean"},{name:"orientation",type:"number"},{name:"value",type:"number"},{name:"handleSize",type:"number"},{name:"handleEntity",type:"entity"}],dy=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="scrollbar",i.ComponentType=ly,i.DataType=cy,i.schema=uy,i.on("beforeremove",i._onRemoveComponent,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){t.prototype.initializeComponentData.call(this,e,i,uy)},i._onRemoveComponent=function(t,e){e.onRemove()},e}(wp);bp._buildAccessors(ly.prototype,uy);var fy={volume:0,pitch:0,loop:!1,startTime:0,duration:0,position:new wt,maxDistance:0,refDistance:0,rollOffFactor:0,distanceModel:0,onPlay:null,onPause:null,onResume:null,onStop:null,onEnd:null},py=function(t){function e(e,i,n){var s;return void 0===i&&(i="Untitled"),void 0===n&&(n={}),(s=t.call(this)||this).name=void 0,s.instances=[],s._component=e,s._assets=e.system.app.assets,s._manager=e.system.manager,s.name=i,s._volume=void 0!==n.volume?_t.clamp(Number(n.volume)||0,0,1):1,s._pitch=void 0!==n.pitch?Math.max(.01,Number(n.pitch)||0):1,s._loop=!(void 0===n.loop||!n.loop),s._duration=n.duration>0?n.duration:null,s._startTime=Math.max(0,Number(n.startTime)||0),s._overlap=!!n.overlap,s._autoPlay=!!n.autoPlay,s._firstNode=null,s._lastNode=null,s._asset=n.asset,s._asset instanceof Vf&&(s._asset=s._asset.id),s._onInstancePlayHandler=s._onInstancePlay.bind(w(s)),s._onInstancePauseHandler=s._onInstancePause.bind(w(s)),s._onInstanceResumeHandler=s._onInstanceResume.bind(w(s)),s._onInstanceStopHandler=s._onInstanceStop.bind(w(s)),s._onInstanceEndHandler=s._onInstanceEnd.bind(w(s)),s}S(e,t);var i=e.prototype;return i.play=function(){if(this.overlap||this.stop(),this.isLoaded||this._hasAsset()){var t=this._createInstance();if(this.instances.push(t),this.isLoaded)t.play();else{var e=function(e){var i=t._playWhenLoaded;t.sound=e,i&&t.play()};this.off("load",e),this.once("load",e),this.load()}return t}},i.pause=function(){for(var t=!1,e=this.instances,i=0,n=e.length;i<n;i++)e[i].pause()&&(t=!0);return t},i.resume=function(){for(var t=!1,e=this.instances,i=0,n=e.length;i<n;i++)e[i].resume()&&(t=!0);return t},i.stop=function(){for(var t=!1,e=this.instances,i=e.length;i--;)e[i].stop(),t=!0;return e.length=0,t},i.load=function(){if(this._hasAsset()){var t=this._assets.get(this._asset);if(!t)return this._assets.off("add:"+this._asset,this._onAssetAdd,this),void this._assets.once("add:"+this._asset,this._onAssetAdd,this);if(t.off("remove",this._onAssetRemoved,this),t.on("remove",this._onAssetRemoved,this),!t.resource)return t.off("load",this._onAssetLoad,this),t.once("load",this._onAssetLoad,this),void this._assets.load(t);this.fire("load",t.resource)}},i.setExternalNodes=function(t,e){if(t){if(e||(e=t),this._firstNode=t,this._lastNode=e,!this._overlap)for(var i=this.instances,n=0,s=i.length;n<s;n++)i[n].setExternalNodes(t,e)}else console.error("The firstNode must have a valid AudioNode")},i.clearExternalNodes=function(){if(this._firstNode=null,this._lastNode=null,!this._overlap)for(var t=this.instances,e=0,i=t.length;e<i;e++)t[e].clearExternalNodes()},i.getExternalNodes=function(){return[this._firstNode,this._lastNode]},i._hasAsset=function(){return null!=this._asset},i._createInstance=function(){var t=null,e=this._component,i=null;if(this._hasAsset()){var n=this._assets.get(this._asset);n&&(i=n.resource)}var s=fy;return s.volume=this._volume*e.volume,s.pitch=this._pitch*e.pitch,s.loop=this._loop,s.startTime=this._startTime,s.duration=this._duration,s.onPlay=this._onInstancePlayHandler,s.onPause=this._onInstancePauseHandler,s.onResume=this._onInstanceResumeHandler,s.onStop=this._onInstanceStopHandler,s.onEnd=this._onInstanceEndHandler,e.positional?(s.position.copy(e.entity.getPosition()),s.maxDistance=e.maxDistance,s.refDistance=e.refDistance,s.rollOffFactor=e.rollOffFactor,s.distanceModel=e.distanceModel,t=new Ma(this._manager,i,s)):t=new Ea(this._manager,i,s),this._firstNode&&t.setExternalNodes(this._firstNode,this._lastNode),t},i._onInstancePlay=function(t){this.fire("play",t),this._component.fire("play",this,t)},i._onInstancePause=function(t){this.fire("pause",t),this._component.fire("pause",this,t)},i._onInstanceResume=function(t){this.fire("resume",t),this._component.fire("resume",this,t)},i._onInstanceStop=function(t){var e=this.instances.indexOf(t);-1!==e&&this.instances.splice(e,1),this.fire("stop",t),this._component.fire("stop",this,t)},i._onInstanceEnd=function(t){var e=this.instances.indexOf(t);-1!==e&&this.instances.splice(e,1),this.fire("end",t),this._component.fire("end",this,t)},i._onAssetAdd=function(t){this.load()},i._onAssetLoad=function(t){this.load()},i._onAssetRemoved=function(t){t.off("remove",this._onAssetRemoved,this),this._assets.off("add:"+t.id,this._onAssetAdd,this),this.stop()},i.updatePosition=function(t){for(var e=this.instances,i=0,n=e.length;i<n;i++)e[i].position=t},y(e,[{key:"asset",get:function(){return this._asset},set:function(t){var e=this._asset;if(e){this._assets.off("add:"+e,this._onAssetAdd,this);var i=this._assets.get(e);i&&i.off("remove",this._onAssetRemoved,this)}this._asset=t,this._asset instanceof Vf&&(this._asset=this._asset.id),this._hasAsset()&&this._component.enabled&&this._component.entity.enabled&&this.load()}},{key:"autoPlay",get:function(){return this._autoPlay},set:function(t){this._autoPlay=!!t}},{key:"duration",get:function(){var t=0;if(this._hasAsset()){var e=this._assets.get(this._asset);t=null!=e&&e.resource?e.resource.duration:0}return null!=this._duration?this._duration%(t||1):t},set:function(t){if(this._duration=Math.max(0,Number(t)||0)||null,!this._overlap)for(var e=this.instances,i=0,n=e.length;i<n;i++)e[i].duration=this._duration}},{key:"isLoaded",get:function(){if(this._hasAsset()){var t=this._assets.get(this._asset);if(t)return!!t.resource}return!1}},{key:"isPaused",get:function(){var t=this.instances,e=t.length;if(0===e)return!1;for(var i=0;i<e;i++)if(!t[i].isPaused)return!1;return!0}},{key:"isPlaying",get:function(){for(var t=this.instances,e=0,i=t.length;e<i;e++)if(t[e].isPlaying)return!0;return!1}},{key:"isStopped",get:function(){for(var t=this.instances,e=0,i=t.length;e<i;e++)if(!t[e].isStopped)return!1;return!0}},{key:"loop",get:function(){return this._loop},set:function(t){this._loop=!!t;for(var e=this.instances,i=0,n=e.length;i<n;i++)e[i].loop=this._loop}},{key:"overlap",get:function(){return this._overlap},set:function(t){this._overlap=!!t}},{key:"pitch",get:function(){return this._pitch},set:function(t){if(this._pitch=Math.max(Number(t)||0,.01),!this._overlap)for(var e=this.instances,i=0,n=e.length;i<n;i++)e[i].pitch=this.pitch*this._component.pitch}},{key:"startTime",get:function(){return this._startTime},set:function(t){if(this._startTime=Math.max(0,Number(t)||0),!this._overlap)for(var e=this.instances,i=0,n=e.length;i<n;i++)e[i].startTime=this._startTime}},{key:"volume",get:function(){return this._volume},set:function(t){if(this._volume=_t.clamp(Number(t)||0,0,1),!this._overlap)for(var e=this.instances,i=0,n=e.length;i<n;i++)e[i].volume=this._volume*this._component.volume}}]),e}(P),my=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._volume=1,n._pitch=1,n._positional=!0,n._refDistance=1,n._maxDistance=1e4,n._rollOffFactor=1,n._distanceModel=ee,n._slots={},n._playingBeforeDisable={},n}S(e,t);var i=e.prototype;return i._updateSoundInstances=function(t,e,i){var n=this._slots;for(var s in n){var r=n[s];if(!r.overlap)for(var a=r.instances,o=0,h=a.length;o<h;o++)a[o][t]=i?r[t]*e:e}},i.onEnable=function(){if(!this.system._inTools){var t=this._slots,e=this._playingBeforeDisable;for(var i in t){var n=t[i];n.autoPlay&&n.isStopped?n.play():e[i]?n.resume():n.isLoaded||n.load()}}},i.onDisable=function(){var t=this._slots,e={};for(var i in t)t[i].overlap||t[i].isPlaying&&(t[i].pause(),e[i]=!0);this._playingBeforeDisable=e},i.onRemove=function(){this.off()},i.addSlot=function(t,e){var i=this._slots;if(i[t])return null;var n=new py(this,t,e);return i[t]=n,n.autoPlay&&this.enabled&&this.entity.enabled&&n.play(),n},i.removeSlot=function(t){var e=this._slots;e[t]&&(e[t].stop(),delete e[t])},i.slot=function(t){return this._slots[t]},i._getSlotProperty=function(t,e){if(this.enabled&&this.entity.enabled){var i=this._slots[t];if(i)return i[e]}},i.isPlaying=function(t){return this._getSlotProperty(t,"isPlaying")||!1},i.isLoaded=function(t){return this._getSlotProperty(t,"isLoaded")||!1},i.isPaused=function(t){return this._getSlotProperty(t,"isPaused")||!1},i.isStopped=function(t){return this._getSlotProperty(t,"isStopped")||!1},i.play=function(t){if(!this.enabled||!this.entity.enabled)return null;var e=this._slots[t];return e?e.play():null},i.pause=function(t){var e=this._slots;if(t){var i=e[t];if(!i)return;i.pause()}else for(var n in e)e[n].pause()},i.resume=function(t){var e=this._slots;if(t){var i=e[t];if(!i)return;i.isPaused&&i.resume()}else for(var n in e)e[n].resume()},i.stop=function(t){var e=this._slots;if(t){var i=e[t];if(!i)return;i.stop()}else for(var n in e)e[n].stop()},y(e,[{key:"distanceModel",get:function(){return this._distanceModel},set:function(t){this._distanceModel=t,this._updateSoundInstances("distanceModel",t,!1)}},{key:"maxDistance",get:function(){return this._maxDistance},set:function(t){this._maxDistance=t,this._updateSoundInstances("maxDistance",t,!1)}},{key:"refDistance",get:function(){return this._refDistance},set:function(t){this._refDistance=t,this._updateSoundInstances("refDistance",t,!1)}},{key:"rollOffFactor",get:function(){return this._rollOffFactor},set:function(t){this._rollOffFactor=t,this._updateSoundInstances("rollOffFactor",t,!1)}},{key:"pitch",get:function(){return this._pitch},set:function(t){this._pitch=t,this._updateSoundInstances("pitch",t,!0)}},{key:"volume",get:function(){return this._volume},set:function(t){this._volume=t,this._updateSoundInstances("volume",t,!0)}},{key:"positional",get:function(){return this._positional},set:function(t){this._positional=t;var e=this._slots;for(var i in e){var n=e[i];if(!n.overlap)for(var s=n.instances,r=s.length-1;r>=0;r--){var a=s[r].isPlaying||s[r].isSuspended,o=s[r].currentTime;a&&s[r].stop();var h=n._createInstance();a&&(h.play(),h.currentTime=o),s.push(h)}}}},{key:"slots",get:function(){return this._slots},set:function(t){var e=this._slots;if(e)for(var i in e)e[i].stop();var n={};for(var s in t)t[s]instanceof py?n[t[s].name]=t[s]:t[s].name&&(n[t[s].name]=new py(this,t[s].name,t[s]));this._slots=n,this.enabled&&this.entity.enabled&&this.onEnable()}}]),e}(bp),_y=function(){this.enabled=!0},vy=["enabled"],gy=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="sound",i.ComponentType=my,i.DataType=_y,i.schema=vy,i.manager=e.soundManager,i.app.systems.on("update",i.onUpdate,w(i)),i.on("beforeremove",i.onBeforeRemove,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){n=["volume","pitch","positional","refDistance","maxDistance","rollOffFactor","distanceModel","slots"];for(var s=0;s<n.length;s++)i.hasOwnProperty(n[s])&&(e[n[s]]=i[n[s]]);t.prototype.initializeComponentData.call(this,e,i,["enabled"])},i.cloneComponent=function(t,e){var i=t.sound,n=i.slots,s={};for(var r in n){var a=n[r];s[r]={name:a.name,volume:a.volume,pitch:a.pitch,loop:a.loop,duration:a.duration,startTime:a.startTime,overlap:a.overlap,autoPlay:a.autoPlay,asset:a.asset}}var o={distanceModel:i.distanceModel,enabled:i.enabled,maxDistance:i.maxDistance,pitch:i.pitch,positional:i.positional,refDistance:i.refDistance,rollOffFactor:i.rollOffFactor,slots:s,volume:i.volume};return this.addComponent(e,o)},i.onUpdate=function(t){var e=this.store;for(var i in e)if(e.hasOwnProperty(i)){var n=e[i].entity;if(n.enabled){var s=n.sound;if(s.enabled&&s.positional){var r=n.getPosition(),a=s.slots;for(var o in a)a[o].updatePosition(r)}}}},i.onBeforeRemove=function(t,e){var i=e.slots;for(var n in i)i[n].overlap||i[n].stop();e.onRemove()},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},y(e,[{key:"volume",get:function(){return this.manager.volume},set:function(t){this.manager.volume=t}},{key:"context",get:function(){return va()?this.manager.context:null}}]),e}(wp);bp._buildAccessors(my.prototype,vy);var yy="simple",xy="animated",Sy=function(t){function e(e,i){var n;return(n=t.call(this)||this)._component=e,n._frame=0,n._sprite=null,n._spriteAsset=null,n.spriteAsset=i.spriteAsset,n.name=i.name,n.fps=i.fps||0,n.loop=i.loop||!1,n._playing=!1,n._paused=!1,n._time=0,n}S(e,t);var i=e.prototype;return i._onSpriteAssetAdded=function(t){this._component.system.app.assets.off("add:"+t.id,this._onSpriteAssetAdded,this),this._spriteAsset===t.id&&this._bindSpriteAsset(t)},i._bindSpriteAsset=function(t){t.on("load",this._onSpriteAssetLoad,this),t.on("remove",this._onSpriteAssetRemove,this),t.resource?this._onSpriteAssetLoad(t):this._component.system.app.assets.load(t)},i._unbindSpriteAsset=function(t){t&&(t.off("load",this._onSpriteAssetLoad,this),t.off("remove",this._onSpriteAssetRemove,this),t.resource&&!t.resource.atlas&&this._component.system.app.assets.off("load:"+t.data.textureAtlasAsset,this._onTextureAtlasLoad,this))},i._onSpriteAssetLoad=function(t){if(t.resource)if(t.resource.atlas)this.sprite=t.resource;else{var e=t.data.textureAtlasAsset,i=this._component.system.app.assets;i.off("load:"+e,this._onTextureAtlasLoad,this),i.once("load:"+e,this._onTextureAtlasLoad,this)}else this.sprite=null},i._onTextureAtlasLoad=function(t){var e=this._spriteAsset;e instanceof Vf?this._onSpriteAssetLoad(e):this._onSpriteAssetLoad(this._component.system.app.assets.get(e))},i._onSpriteAssetRemove=function(t){this.sprite=null},i._onSpriteMeshesChange=function(){this._component.currentClip===this&&this._component._showFrame(this.frame)},i._onSpritePpuChanged=function(){this._component.currentClip===this&&0!==this.sprite.renderMode&&this._component._showFrame(this.frame)},i._update=function(t){if(0!==this.fps&&this._playing&&!this._paused&&this._sprite){var e=this.fps<0?-1:1,i=this._time+t*this._component.speed*e,n=this.duration,s=i>n||i<0;this._setTime(i);var r=this.frame;(r=this._sprite?Math.floor(this._sprite.frameKeys.length*this._time/n):0)!==this._frame&&this._setFrame(r),s&&(this.loop?(this.fire("loop"),this._component.fire("loop",this)):(this._playing=!1,this._paused=!1,this.fire("end"),this._component.fire("end",this)))}},i._setTime=function(t){this._time=t;var e=this.duration;this._time<0?this.loop?this._time=this._time%e+e:this._time=0:this._time>e&&(this.loop?this._time%=e:this._time=e)},i._setFrame=function(t){this._sprite?this._frame=_t.clamp(t,0,this._sprite.frameKeys.length-1):this._frame=t,this._component.currentClip===this&&this._component._showFrame(this._frame)},i._destroy=function(){if(this._spriteAsset){var t=this._component.system.app.assets;this._unbindSpriteAsset(t.get(this._spriteAsset))}this._sprite&&(this.sprite=null),this._spriteAsset&&(this.spriteAsset=null)},i.play=function(){this._playing||(this._playing=!0,this._paused=!1,this.frame=0,this.fire("play"),this._component.fire("play",this))},i.pause=function(){this._playing&&!this._paused&&(this._paused=!0,this.fire("pause"),this._component.fire("pause",this))},i.resume=function(){this._paused&&(this._paused=!1,this.fire("resume"),this._component.fire("resume",this))},i.stop=function(){this._playing&&(this._playing=!1,this._paused=!1,this._time=0,this.frame=0,this.fire("stop"),this._component.fire("stop",this))},y(e,[{key:"duration",get:function(){if(this._sprite){var t=this.fps||Number.MIN_VALUE;return this._sprite.frameKeys.length/Math.abs(t)}return 0}},{key:"frame",get:function(){return this._frame},set:function(t){this._setFrame(t);var e=this.fps||Number.MIN_VALUE;this._setTime(this._frame/e)}},{key:"isPaused",get:function(){return this._paused}},{key:"isPlaying",get:function(){return this._playing}},{key:"sprite",get:function(){return this._sprite},set:function(t){var e;(this._sprite&&(this._sprite.off("set:meshes",this._onSpriteMeshesChange,this),this._sprite.off("set:pixelsPerUnit",this._onSpritePpuChanged,this),this._sprite.off("set:atlas",this._onSpriteMeshesChange,this),this._sprite.atlas&&this._sprite.atlas.off("set:texture",this._onSpriteMeshesChange,this)),this._sprite=t,this._sprite&&(this._sprite.on("set:meshes",this._onSpriteMeshesChange,this),this._sprite.on("set:pixelsPerUnit",this._onSpritePpuChanged,this),this._sprite.on("set:atlas",this._onSpriteMeshesChange,this),this._sprite.atlas&&this._sprite.atlas.on("set:texture",this._onSpriteMeshesChange,this)),this._component.currentClip===this)&&(t&&t.atlas?(t.atlas.texture&&((e=this._component._meshInstance)&&(e.setParameter("texture_emissiveMap",t.atlas.texture),e.setParameter("texture_opacityMap",t.atlas.texture)),this._component.enabled&&this._component.entity.enabled&&this._component._showModel()),this.time&&this.fps?this.time=this.time:this.frame=this.frame):((e=this._component._meshInstance)&&(e.deleteParameter("texture_emissiveMap"),e.deleteParameter("texture_opacityMap")),this._component._hideModel()))}},{key:"spriteAsset",get:function(){return this._spriteAsset},set:function(t){var e=this._component.system.app.assets,i=t;if(t instanceof Vf&&(i=t.id),this._spriteAsset!==i){if(this._spriteAsset){var n=e.get(this._spriteAsset);n&&this._unbindSpriteAsset(n)}if(this._spriteAsset=i,this._spriteAsset){var s=e.get(this._spriteAsset);s?this._bindSpriteAsset(s):(this.sprite=null,e.on("add:"+this._spriteAsset,this._onSpriteAssetAdded,this))}else this.sprite=null}}},{key:"time",get:function(){return this._time},set:function(t){this._setTime(t),this._sprite?this.frame=Math.min(this._sprite.frameKeys.length-1,Math.floor(this._time*Math.abs(this.fps))):this.frame=0}}]),e}(P),by="texture_emissiveMap",wy="texture_opacityMap",Ty="material_emissive",Ay="material_opacity",Cy=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._type=yy,n._material=e.defaultMaterial,n._color=new vt(1,1,1,1),n._colorUniform=new Float32Array(3),n._speed=1,n._flipX=!1,n._flipY=!1,n._width=1,n._height=1,n._drawOrder=0,n._layers=[0],n._outerScale=new Et(1,1),n._outerScaleUniform=new Float32Array(2),n._innerOffset=new Pt,n._innerOffsetUniform=new Float32Array(4),n._atlasRect=new Pt,n._atlasRectUniform=new Float32Array(4),n._batchGroupId=-1,n._batchGroup=null,n._node=new hh,n._model=new Gu,n._model.graph=n._node,n._meshInstance=null,i.addChild(n._model.graph),n._model._entity=i,n._updateAabbFunc=n._updateAabb.bind(w(n)),n._addedModel=!1,n._autoPlayClip=null,n._clips={},n._defaultClip=new Sy(w(n),{name:n.entity.name,fps:0,loop:!1,spriteAsset:null}),n._currentClip=n._defaultClip,n}S(e,t);var i=e.prototype;return i.onEnable=function(){var t,e=this.system.app,i=e.scene;(i.on("set:layers",this._onLayersChanged,this),i.layers&&(i.layers.on("add",this._onLayerAdded,this),i.layers.on("remove",this._onLayerRemoved,this)),this._showModel(),this._autoPlayClip&&this._tryAutoPlay(),this._batchGroupId>=0)&&(null==(t=e.batcher)||t.insert(Ho.SPRITE,this._batchGroupId,this.entity))},i.onDisable=function(){var t,e=this.system.app,i=e.scene;(i.off("set:layers",this._onLayersChanged,this),i.layers&&(i.layers.off("add",this._onLayerAdded,this),i.layers.off("remove",this._onLayerRemoved,this)),this.stop(),this._hideModel(),this._batchGroupId>=0)&&(null==(t=e.batcher)||t.remove(Ho.SPRITE,this._batchGroupId,this.entity))},i.onDestroy=function(){var t;for(var e in this._currentClip=null,this._defaultClip&&(this._defaultClip._destroy(),this._defaultClip=null),this._clips)this._clips[e]._destroy();this._clips=null,this._hideModel(),this._model=null,null==(t=this._node)||t.remove(),this._node=null,this._meshInstance&&(this._meshInstance.material=null,this._meshInstance.mesh=null,this._meshInstance=null)},i._showModel=function(){if(!this._addedModel&&this._meshInstance){for(var t=[this._meshInstance],e=0,i=this._layers.length;e<i;e++){var n=this.system.app.scene.layers.getLayerById(this._layers[e]);n&&n.addMeshInstances(t)}this._addedModel=!0}},i._hideModel=function(){if(this._addedModel&&this._meshInstance){for(var t=[this._meshInstance],e=0,i=this._layers.length;e<i;e++){var n=this.system.app.scene.layers.getLayerById(this._layers[e]);n&&n.removeMeshInstances(t)}this._addedModel=!1}},i._showFrame=function(t){if(this.sprite){var e=this.sprite.meshes[t];if(e){var i;if(i=1===this.sprite.renderMode?this.system.default9SlicedMaterialSlicedMode:2===this.sprite.renderMode?this.system.default9SlicedMaterialTiledMode:this.system.defaultMaterial,this._meshInstance||(this._meshInstance=new yh(e,this._material,this._node),this._meshInstance.castShadow=!1,this._meshInstance.receiveShadow=!1,this._meshInstance.drawOrder=this._drawOrder,this._model.meshInstances.push(this._meshInstance),this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._meshInstance.setParameter(Ty,this._colorUniform),this._meshInstance.setParameter(Ay,this._color.a),this.enabled&&this.entity.enabled&&this._showModel()),this._meshInstance.material!==i&&(this._meshInstance.material=i),this._meshInstance.mesh!==e&&(this._meshInstance.mesh=e,this._meshInstance.visible=!0,this._meshInstance._aabbVer=-1),this.sprite.atlas&&this.sprite.atlas.texture?(this._meshInstance.setParameter(by,this.sprite.atlas.texture),this._meshInstance.setParameter(wy,this.sprite.atlas.texture)):(this._meshInstance.deleteParameter(by),this._meshInstance.deleteParameter(wy)),!this.sprite.atlas||1!==this.sprite.renderMode&&2!==this.sprite.renderMode)this._meshInstance._updateAabbFunc=null;else{this._meshInstance._updateAabbFunc=this._updateAabbFunc;var n=this.sprite.atlas.frames[this.sprite.frameKeys[t]];if(n){var s=2/n.rect.z,r=2/n.rect.w;this._innerOffset.set(n.border.x*s,n.border.y*r,n.border.z*s,n.border.w*r);var a=this.sprite.atlas.texture;this._atlasRect.set(n.rect.x/a.width,n.rect.y/a.height,n.rect.z/a.width,n.rect.w/a.height)}else this._innerOffset.set(0,0,0,0);this._innerOffsetUniform[0]=this._innerOffset.x,this._innerOffsetUniform[1]=this._innerOffset.y,this._innerOffsetUniform[2]=this._innerOffset.z,this._innerOffsetUniform[3]=this._innerOffset.w,this._meshInstance.setParameter("innerOffset",this._innerOffsetUniform),this._atlasRectUniform[0]=this._atlasRect.x,this._atlasRectUniform[1]=this._atlasRect.y,this._atlasRectUniform[2]=this._atlasRect.z,this._atlasRectUniform[3]=this._atlasRect.w,this._meshInstance.setParameter("atlasRect",this._atlasRectUniform)}this._updateTransform()}else this._meshInstance&&(this._meshInstance.mesh=null,this._meshInstance.visible=!1)}},i._updateTransform=function(){var t=this.flipX?-1:1,e=this.flipY?-1:1,i=0,n=0;if(this.sprite&&(1===this.sprite.renderMode||2===this.sprite.renderMode)){var s=1,r=1;if(this.sprite.atlas){var a=this.sprite.atlas.frames[this.sprite.frameKeys[this.frame]];a&&(s=a.rect.z,r=a.rect.w,i=(.5-a.pivot.x)*this._width,n=(.5-a.pivot.y)*this._height)}var o=s/this.sprite.pixelsPerUnit,h=r/this.sprite.pixelsPerUnit;this._outerScale.set(Math.max(this._width,this._innerOffset.x*o),Math.max(this._height,this._innerOffset.y*h)),t*=o,e*=h,this._outerScale.x/=o,this._outerScale.y/=h,t*=_t.clamp(this._width/(this._innerOffset.x*o),1e-4,1),e*=_t.clamp(this._height/(this._innerOffset.y*h),1e-4,1),this._meshInstance&&(this._outerScaleUniform[0]=this._outerScale.x,this._outerScaleUniform[1]=this._outerScale.y,this._meshInstance.setParameter("outerScale",this._outerScaleUniform))}this._node.setLocalScale(t,e,1),this._node.setLocalPosition(i,n,0)},i._updateAabb=function(t){return t.center.set(0,0,0),t.halfExtents.set(.5*this._outerScale.x,.5*this._outerScale.y,.001),t.setFromTransformedAabb(t,this._node.getWorldTransform()),t},i._tryAutoPlay=function(){if(this._autoPlayClip&&this.type===xy){var t=this._clips[this._autoPlayClip];!t||t.isPlaying||this._currentClip&&this._currentClip.isPlaying||this.enabled&&this.entity.enabled&&this.play(t.name)}},i._onLayersChanged=function(t,e){t.off("add",this.onLayerAdded,this),t.off("remove",this.onLayerRemoved,this),e.on("add",this.onLayerAdded,this),e.on("remove",this.onLayerRemoved,this),this.enabled&&this.entity.enabled&&this._showModel()},i._onLayerAdded=function(t){this.layers.indexOf(t.id)<0||this._addedModel&&this.enabled&&this.entity.enabled&&this._meshInstance&&t.addMeshInstances([this._meshInstance])},i._onLayerRemoved=function(t){this._meshInstance&&(this.layers.indexOf(t.id)<0||t.removeMeshInstances([this._meshInstance]))},i.removeModelFromLayers=function(){for(var t=0;t<this.layers.length;t++){var e=this.system.app.scene.layers.getLayerById(this.layers[t]);e&&e.removeMeshInstances([this._meshInstance])}},i.addClip=function(t){var e=new Sy(this,{name:t.name,fps:t.fps,loop:t.loop,spriteAsset:t.spriteAsset});return this._clips[t.name]=e,e.name&&e.name===this._autoPlayClip&&this._tryAutoPlay(),e},i.removeClip=function(t){delete this._clips[t]},i.clip=function(t){return this._clips[t]},i.play=function(t){var e=this._clips[t],i=this._currentClip;return i&&i!==e&&(i._playing=!1),this._currentClip=e,this._currentClip&&(this._currentClip=e,this._currentClip.play()),e},i.pause=function(){this._currentClip!==this._defaultClip&&this._currentClip.isPlaying&&this._currentClip.pause()},i.resume=function(){this._currentClip!==this._defaultClip&&this._currentClip.isPaused&&this._currentClip.resume()},i.stop=function(){this._currentClip!==this._defaultClip&&this._currentClip.stop()},y(e,[{key:"type",get:function(){return this._type},set:function(t){this._type!==t&&(this._type=t,this._type===yy?(this.stop(),this._currentClip=this._defaultClip,this.enabled&&this.entity.enabled&&(this._currentClip.frame=this.frame,this._currentClip.sprite?this._showModel():this._hideModel())):this._type===xy&&(this.stop(),this._autoPlayClip&&this._tryAutoPlay(),this._currentClip&&this._currentClip.isPlaying&&this.enabled&&this.entity.enabled?this._showModel():this._hideModel()))}},{key:"frame",get:function(){return this._currentClip.frame},set:function(t){this._currentClip.frame=t}},{key:"spriteAsset",get:function(){return this._defaultClip._spriteAsset},set:function(t){this._defaultClip.spriteAsset=t}},{key:"sprite",get:function(){return this._currentClip.sprite},set:function(t){this._currentClip.sprite=t}},{key:"material",get:function(){return this._material},set:function(t){this._material=t,this._meshInstance&&(this._meshInstance.material=t)}},{key:"color",get:function(){return this._color},set:function(t){this._color.r=t.r,this._color.g=t.g,this._color.b=t.b,this._meshInstance&&(this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._meshInstance.setParameter(Ty,this._colorUniform))}},{key:"opacity",get:function(){return this._color.a},set:function(t){this._color.a=t,this._meshInstance&&this._meshInstance.setParameter(Ay,t)}},{key:"clips",get:function(){return this._clips},set:function(t){if(t){for(var e in this._clips){var i=!1;for(var n in t)if(t[n].name===e){i=!0,this._clips[e].fps=t[n].fps,this._clips[e].loop=t[n].loop,t[n].hasOwnProperty("sprite")?this._clips[e].sprite=t[n].sprite:t[n].hasOwnProperty("spriteAsset")&&(this._clips[e].spriteAsset=t[n].spriteAsset);break}i||this.removeClip(e)}for(var s in t)this._clips[t[s].name]||this.addClip(t[s]);this._autoPlayClip&&this._tryAutoPlay(),this._currentClip&&this._currentClip.sprite||this._hideModel()}else for(var r in this._clips)this.removeClip(r)}},{key:"currentClip",get:function(){return this._currentClip}},{key:"speed",get:function(){return this._speed},set:function(t){this._speed=t}},{key:"flipX",get:function(){return this._flipX},set:function(t){this._flipX!==t&&(this._flipX=t,this._updateTransform())}},{key:"flipY",get:function(){return this._flipY},set:function(t){this._flipY!==t&&(this._flipY=t,this._updateTransform())}},{key:"width",get:function(){return this._width},set:function(t){t!==this._width&&(this._width=t,this._outerScale.x=this._width,!this.sprite||2!==this.sprite.renderMode&&1!==this.sprite.renderMode||this._updateTransform())}},{key:"height",get:function(){return this._height},set:function(t){t!==this._height&&(this._height=t,this._outerScale.y=this.height,!this.sprite||2!==this.sprite.renderMode&&1!==this.sprite.renderMode||this._updateTransform())}},{key:"batchGroupId",get:function(){return this._batchGroupId},set:function(t){if(this._batchGroupId!==t){var e,i,n=this._batchGroupId;if(this._batchGroupId=t,this.entity.enabled&&n>=0)null==(e=this.system.app.batcher)||e.remove(Ho.SPRITE,n,this.entity);if(this.entity.enabled&&t>=0)null==(i=this.system.app.batcher)||i.insert(Ho.SPRITE,t,this.entity);else n>=0&&this._currentClip&&this._currentClip.sprite&&this.enabled&&this.entity.enabled&&this._showModel()}}},{key:"autoPlayClip",get:function(){return this._autoPlayClip},set:function(t){this._autoPlayClip=t instanceof Sy?t.name:t,this._tryAutoPlay()}},{key:"drawOrder",get:function(){return this._drawOrder},set:function(t){this._drawOrder=t,this._meshInstance&&(this._meshInstance.drawOrder=t)}},{key:"layers",get:function(){return this._layers},set:function(t){this._addedModel&&this._hideModel(),this._layers=t,this._meshInstance&&this.enabled&&this.entity.enabled&&this._showModel()}},{key:"aabb",get:function(){return this._meshInstance?this._meshInstance.aabb:null}}]),e}(bp),Ey=function(){this.enabled=!0},My=["enabled"],Py=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="sprite",i.ComponentType=Cy,i.DataType=Ey,i.schema=My,i._defaultTexture=null,i._defaultMaterial=null,i._default9SlicedMaterialSlicedMode=null,i._default9SlicedMaterialTiledMode=null,i.app.systems.on("update",i.onUpdate,w(i)),i.on("beforeremove",i.onBeforeRemove,w(i)),i}S(e,t);var i=e.prototype;return i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this),this._defaultTexture&&(this._defaultTexture.destroy(),this._defaultTexture=null)},i.initializeComponentData=function(e,i,n){if(void 0!==i.enabled&&(e.enabled=i.enabled),e.type=i.type,i.layers&&Array.isArray(i.layers)&&(e.layers=i.layers.slice(0)),void 0!==i.drawOrder&&(e.drawOrder=i.drawOrder),void 0!==i.color){var s,r;if(i.color instanceof vt)e.color.set(i.color.r,i.color.g,i.color.b,null!=(s=i.opacity)?s:1);else e.color.set(i.color[0],i.color[1],i.color[2],null!=(r=i.opacity)?r:1);e.color=e.color}if(void 0!==i.opacity&&(e.opacity=i.opacity),void 0!==i.flipX&&(e.flipX=i.flipX),void 0!==i.flipY&&(e.flipY=i.flipY),void 0!==i.width&&(e.width=i.width),void 0!==i.height&&(e.height=i.height),void 0!==i.spriteAsset&&(e.spriteAsset=i.spriteAsset),i.sprite&&(e.sprite=i.sprite),void 0!==i.frame&&(e.frame=i.frame),i.clips)for(var a in i.clips)e.addClip(i.clips[a]);void 0!==i.speed&&(e.speed=i.speed),i.autoPlayClip&&(e.autoPlayClip=i.autoPlayClip),e.batchGroupId=void 0===i.batchGroupId||null===i.batchGroupId?-1:i.batchGroupId,t.prototype.initializeComponentData.call(this,e,i,n)},i.cloneComponent=function(t,e){var i=t.sprite;return this.addComponent(e,{enabled:i.enabled,type:i.type,spriteAsset:i.spriteAsset,sprite:i.sprite,width:i.width,height:i.height,frame:i.frame,color:i.color.clone(),opacity:i.opacity,flipX:i.flipX,flipY:i.flipY,speed:i.speed,clips:i.clips,autoPlayClip:i.autoPlayClip,batchGroupId:i.batchGroupId,drawOrder:i.drawOrder,layers:i.layers.slice(0)})},i.onUpdate=function(t){var e=this.store;for(var i in e)if(e.hasOwnProperty(i)){var n=e[i];if(n.data.enabled&&n.entity.enabled){var s=n.entity.sprite;s._currentClip&&s._currentClip._update(t)}}},i.onBeforeRemove=function(t,e){e.onDestroy()},y(e,[{key:"defaultMaterial",get:function(){if(!this._defaultMaterial){var t=new Ls(this.app.graphicsDevice,{width:1,height:1,format:7,name:"sprite"}),e=new Uint8Array(t.lock());e[0]=e[1]=e[2]=e[3]=255,t.unlock();var i=new lu;i.diffuse.set(0,0,0),i.emissive.set(.5,.5,.5),i.emissiveMap=t,i.emissiveTint=!0,i.opacityMap=t,i.opacityMapChannel="a",i.opacityTint=!0,i.opacity=0,i.useLighting=!1,i.useGammaTonemap=!1,i.useFog=!1,i.useSkybox=!1,i.blendType=4,i.depthWrite=!1,i.pixelSnap=!1,i.cull=se,i.update(),this._defaultTexture=t,this._defaultMaterial=i}return this._defaultMaterial},set:function(t){this._defaultMaterial=t}},{key:"default9SlicedMaterialSlicedMode",get:function(){if(!this._default9SlicedMaterialSlicedMode){var t=this.defaultMaterial.clone();t.nineSlicedMode=1,t.update(),this._default9SlicedMaterialSlicedMode=t}return this._default9SlicedMaterialSlicedMode},set:function(t){this._default9SlicedMaterialSlicedMode=t}},{key:"default9SlicedMaterialTiledMode",get:function(){if(!this._default9SlicedMaterialTiledMode){var t=this.defaultMaterial.clone();t.nineSlicedMode=2,t.update(),this._default9SlicedMaterialTiledMode=t}return this._default9SlicedMaterialTiledMode},set:function(t){this._default9SlicedMaterialTiledMode=t}}]),e}(wp);bp._buildAccessors(Cy.prototype,My);var Ry=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._oldState=!0,n._size=new wt,n.on("set_enabled",n._onSetEnabled,w(n)),n}S(e,t);var i=e.prototype;return i.onEnable=function(){this._checkState()},i.onDisable=function(){this._checkState()},i._onSetEnabled=function(t,e,i){this._checkState()},i._checkState=function(){var t=this.enabled&&this.entity.enabled;t!==this._oldState&&(this._oldState=t,this.fire("enable"),this.fire("state",this.enabled))},i._onBeforeRemove=function(){this.fire("remove")},y(e,[{key:"size",get:function(){return this._size},set:function(t){t instanceof wt?this._size.copy(t):t instanceof Array&&t.length>=3&&this.size.set(t[0],t[1],t[2])}}]),e}(bp),Iy=function(){this.enabled=!0},Ly=["enabled"],Dy=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="zone",i.ComponentType=Ry,i.DataType=Iy,i.schema=Ly,i.on("beforeremove",i._onBeforeRemove,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(t,e,i){t.enabled=!e.hasOwnProperty("enabled")||!!e.enabled,e.size&&(e.size instanceof wt?t.size.copy(e.size):e.size instanceof Array&&e.size.length>=3&&t.size.set(e.size[0],e.size[1],e.size[2]))},i.cloneComponent=function(t,e){var i={size:t.zone.size};return this.addComponent(e,i)},i._onBeforeRemove=function(t,e){e._onBeforeRemove()},e}(wp);bp._buildAccessors(Ry.prototype,Ly);var Oy=function(t,e){this.effect=t,this.inputTarget=e,this.outputTarget=null,this.name=t.constructor.name},ky=function(){function t(t,e){this.app=t,this.camera=e,this.destinationRenderTarget=null,this.effects=[],this.enabled=!1,this.depthTarget=null,e.on("set:rect",this.onCameraRectChanged,this)}var e=t.prototype;return e._allocateColorBuffer=function(t,e){var i,n,s=this.camera.rect,r=this.destinationRenderTarget,a=this.app.graphicsDevice,o=Math.floor(s.z*(null!=(i=null==r?void 0:r.width)?i:a.width)),h=Math.floor(s.w*(null!=(n=null==r?void 0:r.height)?n:a.height));return new Ls(a,{name:e,format:t,width:o,height:h,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1})},e._createOffscreenTarget=function(t,e){var i=this.app.graphicsDevice,n=e&&i.getHdrFormat(!1,!0,!1,!1)||7,s=this.camera.entity.name+"-posteffect-"+this.effects.length,r=this._allocateColorBuffer(n,s);return new rn({colorBuffer:r,depth:t,stencil:t&&this.app.graphicsDevice.supportsStencil,samples:t?i.samples:1})},e._resizeOffscreenTarget=function(t){var e=t.colorBuffer.format,i=t.colorBuffer.name;t.destroyFrameBuffers(),t.destroyTextureBuffers(),t._colorBuffer=this._allocateColorBuffer(e,i),t._colorBuffers=[t._colorBuffer]},e._destroyOffscreenTarget=function(t){t.destroyTextureBuffers(),t.destroy()},e.addEffect=function(t){var e=this.effects,i=0===e.length,n=this._createOffscreenTarget(i,t.hdr),s=new Oy(t,n);e.push(s),this._sourceTarget=s.inputTarget,e.length>1&&(e[e.length-2].outputTarget=s.inputTarget),this._newPostEffect=t,t.needsDepthBuffer&&this._requestDepthMap(),this.enable(),this._newPostEffect=void 0},e.removeEffect=function(t){for(var e=-1,i=0,n=this.effects.length;i<n;i++)if(this.effects[i].effect===t){e=i;break}e>=0&&(e>0?this.effects[e-1].outputTarget=e+1<this.effects.length?this.effects[e+1].inputTarget:null:this.effects.length>1&&(this.effects[1].inputTarget._depth||(this._destroyOffscreenTarget(this.effects[1].inputTarget),this.effects[1].inputTarget=this._createOffscreenTarget(!0,this.effects[1].hdr),this._sourceTarget=this.effects[1].inputTarget),this.camera.renderTarget=this.effects[1].inputTarget),this._destroyOffscreenTarget(this.effects[e].inputTarget),this.effects.splice(e,1)),this.enabled&&t.needsDepthBuffer&&this._releaseDepthMap(),0===this.effects.length&&this.disable()},e._requestDepthMaps=function(){for(var t=0,e=this.effects.length;t<e;t++){var i=this.effects[t].effect;this._newPostEffect!==i&&(i.needsDepthBuffer&&this._requestDepthMap())}},e._releaseDepthMaps=function(){for(var t=0,e=this.effects.length;t<e;t++){this.effects[t].effect.needsDepthBuffer&&this._releaseDepthMap()}},e._requestDepthMap=function(){var t=this.app.scene.layers.getLayerById(1);t&&(t.incrementCounter(),this.camera.requestSceneDepthMap(!0))},e._releaseDepthMap=function(){var t=this.app.scene.layers.getLayerById(1);t&&(t.decrementCounter(),this.camera.requestSceneDepthMap(!1))},e.destroy=function(){for(var t=0,e=this.effects.length;t<e;t++)this.effects[t].inputTarget.destroy();this.effects.length=0,this.disable()},e.enable=function(){var t=this;!this.enabled&&this.effects.length&&(this.enabled=!0,this._requestDepthMaps(),this.app.graphicsDevice.on("resizecanvas",this._onCanvasResized,this),this.destinationRenderTarget=this.camera.renderTarget,this.camera.renderTarget=this.effects[0].inputTarget,this.camera.onPostprocessing=function(){if(t.enabled){var e=null,i=t.effects.length;if(i)for(var n=0;n<i;n++){var s=t.effects[n],r=s.outputTarget;n===i-1&&(e=t.camera.rect,t.destinationRenderTarget&&(r=t.destinationRenderTarget)),s.effect.render(s.inputTarget,r,e)}}})},e.disable=function(){this.enabled&&(this.enabled=!1,this.app.graphicsDevice.off("resizecanvas",this._onCanvasResized,this),this._releaseDepthMaps(),this._destroyOffscreenTarget(this._sourceTarget),this.camera.renderTarget=null,this.camera.onPostprocessing=null)},e._onCanvasResized=function(t,e){var i,n,s=this.camera.rect,r=this.destinationRenderTarget;t=null!=(i=null==r?void 0:r.width)?i:t,e=null!=(n=null==r?void 0:r.height)?n:e,this.camera.camera.aspectRatio=t*s.z/(e*s.w),this.resizeRenderTargets()},e.resizeRenderTargets=function(){for(var t,e,i=this.app.graphicsDevice,n=this.destinationRenderTarget,s=null!=(t=null==n?void 0:n.width)?t:i.width,r=null!=(e=null==n?void 0:n.height)?e:i.height,a=this.camera.rect,o=Math.floor(a.z*s),h=Math.floor(a.w*r),l=this.effects,c=0,u=l.length;c<u;c++){var d=l[c];d.inputTarget.width===o&&d.inputTarget.height===h||this._resizeOffscreenTarget(d.inputTarget)}},e.onCameraRectChanged=function(t,e,i){this.enabled&&this.resizeRenderTargets()},t}(),Fy=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this).onPostprocessing=null,n.onPreRender=null,n.onPostRender=null,n._renderSceneDepthMap=0,n._renderSceneColorMap=0,n._sceneDepthMapRequested=!1,n._sceneColorMapRequested=!1,n._priority=0,n._disablePostEffectsLayer=4,n._camera=new Gh,n._camera.node=i,n._postEffects=new ky(e.app,w(n)),n}S(e,t);var i=e.prototype;return i.setShaderPass=function(t){var e=Do.get(this.system.app.graphicsDevice),i=t?e.allocate(t,{isForward:!0}):null;return this._camera.shaderPassInfo=i,i.index},i.getShaderPass=function(){var t;return null==(t=this._camera.shaderPassInfo)?void 0:t.name},i._enableDepthLayer=function(t){if(this.layers.find((function(t){return 1===t}))){var e=this.system.app.scene.layers.getLayerById(1);t?null==e||e.incrementCounter():null==e||e.decrementCounter()}else if(t)return!1;return!0},i.requestSceneColorMap=function(t){this._renderSceneColorMap+=t?1:-1,this._enableDepthLayer(t),this.camera._enableRenderPassColorGrab(this.system.app.graphicsDevice,this.renderSceneColorMap)},i.requestSceneDepthMap=function(t){this._renderSceneDepthMap+=t?1:-1,this._enableDepthLayer(t),this.camera._enableRenderPassDepthGrab(this.system.app.graphicsDevice,this.system.app.renderer,this.renderSceneDepthMap)},i.dirtyLayerCompositionCameras=function(){this.system.app.scene.layers._dirtyCameras=!0},i.screenToWorld=function(t,e,i,n){var s=this.system.app.graphicsDevice,r=s.clientRect.width,a=s.clientRect.height;return this._camera.screenToWorld(t,e,i,r,a,n)},i.worldToScreen=function(t,e){var i=this.system.app.graphicsDevice,n=i.clientRect.width,s=i.clientRect.height;return this._camera.worldToScreen(t,n,s,e)},i.onAppPrerender=function(){this._camera._viewMatDirty=!0,this._camera._viewProjMatDirty=!0},i.addCameraToLayers=function(){for(var t=this.layers,e=0;e<t.length;e++){var i=this.system.app.scene.layers.getLayerById(t[e]);i&&i.addCamera(this)}},i.removeCameraFromLayers=function(){for(var t=this.layers,e=0;e<t.length;e++){var i=this.system.app.scene.layers.getLayerById(t[e]);i&&i.removeCamera(this)}},i.onLayersChanged=function(t,e){this.addCameraToLayers(),t.off("add",this.onLayerAdded,this),t.off("remove",this.onLayerRemoved,this),e.on("add",this.onLayerAdded,this),e.on("remove",this.onLayerRemoved,this)},i.onLayerAdded=function(t){this.layers.indexOf(t.id)<0||t.addCamera(this)},i.onLayerRemoved=function(t){this.layers.indexOf(t.id)<0||t.removeCamera(this)},i.onEnable=function(){var t=this.system,e=t.app.scene,i=e.layers;t.addCamera(this),e.on("set:layers",this.onLayersChanged,this),i&&(i.on("add",this.onLayerAdded,this),i.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&this.addCameraToLayers(),this.postEffects.enable()},i.onDisable=function(){var t=this.system,e=t.app.scene,i=e.layers;this.postEffects.disable(),this.removeCameraFromLayers(),e.off("set:layers",this.onLayersChanged,this),i&&(i.off("add",this.onLayerAdded,this),i.off("remove",this.onLayerRemoved,this)),t.removeCamera(this)},i.onRemove=function(){this.onDisable(),this.off(),this.camera.destroy()},i.calculateAspectRatio=function(t){var e=this.system.app.graphicsDevice,i=t?t.width:e.width,n=t?t.height:e.height;return i*this.rect.z/(n*this.rect.w)},i.frameUpdate=function(t){0===this.aspectRatioMode&&(this.aspectRatio=this.calculateAspectRatio(t))},i.startXr=function(t,e,i){this.system.app.xr.start(this,t,e,i)},i.endXr=function(t){this._camera.xr?this._camera.xr.end(t):t&&t(new Error("Camera is not in XR"))},i.copy=function(t){this.aperture=t.aperture,this.aspectRatio=t.aspectRatio,this.aspectRatioMode=t.aspectRatioMode,this.calculateProjection=t.calculateProjection,this.calculateTransform=t.calculateTransform,this.clearColor=t.clearColor,this.clearColorBuffer=t.clearColorBuffer,this.clearDepthBuffer=t.clearDepthBuffer,this.clearStencilBuffer=t.clearStencilBuffer,this.cullFaces=t.cullFaces,this.disablePostEffectsLayer=t.disablePostEffectsLayer,this.farClip=t.farClip,this.flipFaces=t.flipFaces,this.fov=t.fov,this.frustumCulling=t.frustumCulling,this.horizontalFov=t.horizontalFov,this.layers=t.layers,this.nearClip=t.nearClip,this.orthoHeight=t.orthoHeight,this.priority=t.priority,this.projection=t.projection,this.rect=t.rect,this.renderTarget=t.renderTarget,this.scissorRect=t.scissorRect,this.sensitivity=t.sensitivity,this.shutter=t.shutter},y(e,[{key:"aperture",get:function(){return this._camera.aperture},set:function(t){this._camera.aperture=t}},{key:"aspectRatio",get:function(){return this._camera.aspectRatio},set:function(t){this._camera.aspectRatio=t}},{key:"aspectRatioMode",get:function(){return this._camera.aspectRatioMode},set:function(t){this._camera.aspectRatioMode=t}},{key:"calculateProjection",get:function(){return this._camera.calculateProjection},set:function(t){this._camera.calculateProjection=t}},{key:"calculateTransform",get:function(){return this._camera.calculateTransform},set:function(t){this._camera.calculateTransform=t}},{key:"camera",get:function(){return this._camera}},{key:"clearColor",get:function(){return this._camera.clearColor},set:function(t){this._camera.clearColor=t}},{key:"clearColorBuffer",get:function(){return this._camera.clearColorBuffer},set:function(t){this._camera.clearColorBuffer=t,this.dirtyLayerCompositionCameras()}},{key:"clearDepthBuffer",get:function(){return this._camera.clearDepthBuffer},set:function(t){this._camera.clearDepthBuffer=t,this.dirtyLayerCompositionCameras()}},{key:"clearStencilBuffer",get:function(){return this._camera.clearStencilBuffer},set:function(t){this._camera.clearStencilBuffer=t,this.dirtyLayerCompositionCameras()}},{key:"cullFaces",get:function(){return this._camera.cullFaces},set:function(t){this._camera.cullFaces=t}},{key:"disablePostEffectsLayer",get:function(){return this._disablePostEffectsLayer},set:function(t){this._disablePostEffectsLayer=t,this.dirtyLayerCompositionCameras()}},{key:"farClip",get:function(){return this._camera.farClip},set:function(t){this._camera.farClip=t}},{key:"flipFaces",get:function(){return this._camera.flipFaces},set:function(t){this._camera.flipFaces=t}},{key:"fov",get:function(){return this._camera.fov},set:function(t){this._camera.fov=t}},{key:"frustum",get:function(){return this._camera.frustum}},{key:"frustumCulling",get:function(){return this._camera.frustumCulling},set:function(t){this._camera.frustumCulling=t}},{key:"horizontalFov",get:function(){return this._camera.horizontalFov},set:function(t){this._camera.horizontalFov=t}},{key:"layers",get:function(){return this._camera.layers},set:function(t){for(var e=this._camera.layers,i=0;i<e.length;i++){var n=this.system.app.scene.layers.getLayerById(e[i]);n&&n.removeCamera(this)}if(this._camera.layers=t,this.enabled&&this.entity.enabled)for(var s=0;s<t.length;s++){var r=this.system.app.scene.layers.getLayerById(t[s]);r&&r.addCamera(this)}}},{key:"layersSet",get:function(){return this._camera.layersSet}},{key:"nearClip",get:function(){return this._camera.nearClip},set:function(t){this._camera.nearClip=t}},{key:"orthoHeight",get:function(){return this._camera.orthoHeight},set:function(t){this._camera.orthoHeight=t}},{key:"postEffects",get:function(){return this._postEffects}},{key:"postEffectsEnabled",get:function(){return this._postEffects.enabled}},{key:"priority",get:function(){return this._priority},set:function(t){this._priority=t,this.dirtyLayerCompositionCameras()}},{key:"projection",get:function(){return this._camera.projection},set:function(t){this._camera.projection=t}},{key:"projectionMatrix",get:function(){return this._camera.projectionMatrix}},{key:"rect",get:function(){return this._camera.rect},set:function(t){this._camera.rect=t,this.fire("set:rect",this._camera.rect)}},{key:"renderSceneColorMap",get:function(){return this._renderSceneColorMap>0},set:function(t){t&&!this._sceneColorMapRequested?(this.requestSceneColorMap(!0),this._sceneColorMapRequested=!0):this._sceneColorMapRequested&&(this.requestSceneColorMap(!1),this._sceneColorMapRequested=!1)}},{key:"renderSceneDepthMap",get:function(){return this._renderSceneDepthMap>0},set:function(t){t&&!this._sceneDepthMapRequested?(this.requestSceneDepthMap(!0),this._sceneDepthMapRequested=!0):this._sceneDepthMapRequested&&(this.requestSceneDepthMap(!1),this._sceneDepthMapRequested=!1)}},{key:"renderTarget",get:function(){return this._camera.renderTarget},set:function(t){this._camera.renderTarget=t,this.dirtyLayerCompositionCameras()}},{key:"scissorRect",get:function(){return this._camera.scissorRect},set:function(t){this._camera.scissorRect=t}},{key:"sensitivity",get:function(){return this._camera.sensitivity},set:function(t){this._camera.sensitivity=t}},{key:"shutter",get:function(){return this._camera.shutter},set:function(t){this._camera.shutter=t}},{key:"viewMatrix",get:function(){return this._camera.viewMatrix}}]),e}(bp),By=function(){this.enabled=!0},Uy=["enabled"],Ny=function(t){function e(e){var i;return(i=t.call(this,e)||this).cameras=[],i.id="camera",i.ComponentType=Fy,i.DataType=By,i.schema=Uy,i.on("beforeremove",i.onBeforeRemove,w(i)),i.app.on("prerender",i.onAppPrerender,w(i)),i.app.systems.on("update",i.onUpdate,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){n=["aspectRatio","aspectRatioMode","calculateProjection","calculateTransform","clearColor","clearColorBuffer","clearDepthBuffer","clearStencilBuffer","renderSceneColorMap","renderSceneDepthMap","cullFaces","farClip","flipFaces","fov","frustumCulling","horizontalFov","layers","renderTarget","nearClip","orthoHeight","projection","priority","rect","scissorRect","aperture","shutter","sensitivity"];for(var s=0;s<n.length;s++){var r=n[s];if(i.hasOwnProperty(r)){var a=i[r];switch(r){case"rect":case"scissorRect":Array.isArray(a)?e[r]=new Pt(a[0],a[1],a[2],a[3]):e[r]=a;break;case"clearColor":Array.isArray(a)?e[r]=new vt(a[0],a[1],a[2],a[3]):e[r]=a;break;default:e[r]=a}}}t.prototype.initializeComponentData.call(this,e,i,["enabled"])},i.cloneComponent=function(t,e){var i=t.camera;return this.addComponent(e,{aspectRatio:i.aspectRatio,aspectRatioMode:i.aspectRatioMode,calculateProjection:i.calculateProjection,calculateTransform:i.calculateTransform,clearColor:i.clearColor,clearColorBuffer:i.clearColorBuffer,clearDepthBuffer:i.clearDepthBuffer,clearStencilBuffer:i.clearStencilBuffer,renderSceneDepthMap:i.renderSceneDepthMap,renderSceneColorMap:i.renderSceneColorMap,cullFaces:i.cullFaces,enabled:i.enabled,farClip:i.farClip,flipFaces:i.flipFaces,fov:i.fov,frustumCulling:i.frustumCulling,horizontalFov:i.horizontalFov,layers:i.layers,renderTarget:i.renderTarget,nearClip:i.nearClip,orthoHeight:i.orthoHeight,projection:i.projection,priority:i.priority,rect:i.rect,scissorRect:i.scissorRect,aperture:i.aperture,sensitivity:i.sensitivity,shutter:i.shutter})},i.onBeforeRemove=function(t,e){this.removeCamera(e),e.onRemove()},i.onUpdate=function(t){},i.onAppPrerender=function(){for(var t=0,e=this.cameras.length;t<e;t++)this.cameras[t].onAppPrerender()},i.addCamera=function(t){this.cameras.push(t),Mu(this.cameras)},i.removeCamera=function(t){var e=this.cameras.indexOf(t);e>=0&&(this.cameras.splice(e,1),Mu(this.cameras))},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},e}(wp);bp._buildAccessors(Fy.prototype,Uy);var zy=[],Vy=[],Gy=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._cookieAsset=null,n._cookieAssetId=null,n._cookieAssetAdd=!1,n._cookieMatrix=null,n}S(e,t);var i=e.prototype;return i.addLightToLayers=function(){for(var t=0;t<this.layers.length;t++){var e=this.system.app.scene.layers.getLayerById(this.layers[t]);e&&(e.addLight(this),this.light.addLayer(e))}},i.removeLightFromLayers=function(){for(var t=0;t<this.layers.length;t++){var e=this.system.app.scene.layers.getLayerById(this.layers[t]);e&&(e.removeLight(this),this.light.removeLayer(e))}},i.onLayersChanged=function(t,e){this.enabled&&this.entity.enabled&&this.addLightToLayers(),t.off("add",this.onLayerAdded,this),t.off("remove",this.onLayerRemoved,this),e.on("add",this.onLayerAdded,this),e.on("remove",this.onLayerRemoved,this)},i.onLayerAdded=function(t){this.layers.indexOf(t.id)>=0&&this.enabled&&this.entity.enabled&&(t.addLight(this),this.light.addLayer(t))},i.onLayerRemoved=function(t){this.layers.indexOf(t.id)>=0&&(t.removeLight(this),this.light.removeLayer(t))},i.refreshProperties=function(){for(var t=0;t<zy.length;t++){var e=zy[t];this[e]=this[e]}this.enabled&&this.entity.enabled&&this.onEnable()},i.onCookieAssetSet=function(){var t=!1;"cubemap"!==this._cookieAsset.type||this._cookieAsset.loadFaces||(this._cookieAsset.loadFaces=!0,t=!0),this._cookieAsset.resource&&!t||this.system.app.assets.load(this._cookieAsset),this._cookieAsset.resource&&this.onCookieAssetLoad()},i.onCookieAssetAdd=function(t){this._cookieAssetId===t.id&&(this._cookieAsset=t,this.light.enabled&&this.onCookieAssetSet(),this._cookieAsset.on("load",this.onCookieAssetLoad,this),this._cookieAsset.on("remove",this.onCookieAssetRemove,this))},i.onCookieAssetLoad=function(){this._cookieAsset&&this._cookieAsset.resource&&(this.cookie=this._cookieAsset.resource)},i.onCookieAssetRemove=function(){this._cookieAssetId&&(this._cookieAssetAdd&&(this.system.app.assets.off("add:"+this._cookieAssetId,this.onCookieAssetAdd,this),this._cookieAssetAdd=!1),this._cookieAsset&&(this._cookieAsset.off("load",this.onCookieAssetLoad,this),this._cookieAsset.off("remove",this.onCookieAssetRemove,this),this._cookieAsset=null),this.cookie=null)},i.onEnable=function(){this.light.enabled=!0,this.system.app.scene.on("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.on("add",this.onLayerAdded,this),this.system.app.scene.layers.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&this.addLightToLayers(),this._cookieAsset&&!this.cookie&&this.onCookieAssetSet()},i.onDisable=function(){this.light.enabled=!1,this.system.app.scene.off("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.off("add",this.onLayerAdded,this),this.system.app.scene.layers.off("remove",this.onLayerRemoved,this)),this.removeLightFromLayers()},i.onRemove=function(){this.onDisable(),this.light.destroy(),this.cookieAsset=null},y(e,[{key:"shadowUpdateOverrides",get:function(){return this.light.shadowUpdateOverrides},set:function(t){this.light.shadowUpdateOverrides=t}},{key:"penumbraSize",get:function(){return this.light.penumbraSize},set:function(t){this.light.penumbraSize=t}}]),e}(bp);function Hy(t,e,i,n){var s=Gy.prototype;zy.push(t),Vy.push(e),Object.defineProperty(s,t,{get:function(){return this.data[t]},set:function(e){var s=this.data,r=s[t];(n||r!==e)&&(s[t]=e,i&&i.call(this,e,r))},configurable:!0})}Hy("enabled",!0,(function(t,e){this.onSetEnabled(null,e,t)})),Hy("light",null),Hy("type","directional",(function(t,e){this.system.changeType(this,e,t),this.refreshProperties()})),Hy("color",new vt(1,1,1),(function(t,e){this.light.setColor(t)}),!0),Hy("intensity",1,(function(t,e){this.light.intensity=t})),Hy("luminance",0,(function(t,e){this.light.luminance=t})),Hy("shape",0,(function(t,e){this.light.shape=t})),Hy("affectSpecularity",!0,(function(t,e){this.light.affectSpecularity=t})),Hy("castShadows",!1,(function(t,e){this.light.castShadows=t})),Hy("shadowDistance",40,(function(t,e){this.light.shadowDistance=t})),Hy("shadowIntensity",1,(function(t,e){this.light.shadowIntensity=t})),Hy("shadowResolution",1024,(function(t,e){this.light.shadowResolution=t})),Hy("shadowBias",.05,(function(t,e){this.light.shadowBias=-.01*_t.clamp(t,0,1)})),Hy("numCascades",1,(function(t,e){this.light.numCascades=_t.clamp(Math.floor(t),1,4)})),Hy("bakeNumSamples",1,(function(t,e){this.light.bakeNumSamples=_t.clamp(Math.floor(t),1,255)})),Hy("bakeArea",0,(function(t,e){this.light.bakeArea=_t.clamp(t,0,180)})),Hy("cascadeDistribution",.5,(function(t,e){this.light.cascadeDistribution=_t.clamp(t,0,1)})),Hy("normalOffsetBias",0,(function(t,e){this.light.normalOffsetBias=_t.clamp(t,0,1)})),Hy("range",10,(function(t,e){this.light.attenuationEnd=t})),Hy("innerConeAngle",40,(function(t,e){this.light.innerConeAngle=t})),Hy("outerConeAngle",45,(function(t,e){this.light.outerConeAngle=t})),Hy("falloffMode",0,(function(t,e){this.light.falloffMode=t})),Hy("shadowType",0,(function(t,e){this.light.shadowType=t})),Hy("vsmBlurSize",11,(function(t,e){this.light.vsmBlurSize=t})),Hy("vsmBlurMode",1,(function(t,e){this.light.vsmBlurMode=t})),Hy("vsmBias",.0025,(function(t,e){this.light.vsmBias=_t.clamp(t,0,1)})),Hy("cookieAsset",null,(function(t,e){if(!this._cookieAssetId||!(t instanceof Vf&&t.id===this._cookieAssetId||t===this._cookieAssetId))if(this.onCookieAssetRemove(),this._cookieAssetId=null,t instanceof Vf)this.data.cookieAsset=t.id,this._cookieAssetId=t.id,this.onCookieAssetAdd(t);else if("number"==typeof t){this._cookieAssetId=t;var i=this.system.app.assets.get(t);i?this.onCookieAssetAdd(i):(this._cookieAssetAdd=!0,this.system.app.assets.on("add:"+this._cookieAssetId,this.onCookieAssetAdd,this))}})),Hy("cookie",null,(function(t,e){this.light.cookie=t})),Hy("cookieIntensity",1,(function(t,e){this.light.cookieIntensity=_t.clamp(t,0,1)})),Hy("cookieFalloff",!0,(function(t,e){this.light.cookieFalloff=t})),Hy("cookieChannel","rgb",(function(t,e){this.light.cookieChannel=t})),Hy("cookieAngle",0,(function(t,e){if(0!==t||null!==this.cookieScale){this._cookieMatrix||(this._cookieMatrix=new Pt);var i=1,n=1;this.cookieScale&&(i=this.cookieScale.x,n=this.cookieScale.y);var s=Math.cos(t*_t.DEG_TO_RAD),r=Math.sin(t*_t.DEG_TO_RAD);this._cookieMatrix.set(s/i,-r/i,r/n,s/n),this.light.cookieTransform=this._cookieMatrix}else this.light.cookieTransform=null})),Hy("cookieScale",null,(function(t,e){if(null!==t||0!==this.cookieAngle){this._cookieMatrix||(this._cookieMatrix=new Pt);var i=t.x,n=t.y,s=Math.cos(this.cookieAngle*_t.DEG_TO_RAD),r=Math.sin(this.cookieAngle*_t.DEG_TO_RAD);this._cookieMatrix.set(s/i,-r/i,r/n,s/n),this.light.cookieTransform=this._cookieMatrix}else this.light.cookieTransform=null}),!0),Hy("cookieOffset",null,(function(t,e){this.light.cookieOffset=t}),!0),Hy("shadowUpdateMode",2,(function(t,e){this.light.shadowUpdateMode=t}),!0),Hy("mask",1,(function(t,e){this.light.mask=t})),Hy("affectDynamic",!0,(function(t,e){t?this.light.mask|=1:this.light.mask&=-2,this.light.layersDirty()})),Hy("affectLightmapped",!1,(function(t,e){t?(this.light.mask|=2,this.bake&&(this.light.mask&=-5)):(this.light.mask&=-3,this.bake&&(this.light.mask|=4))})),Hy("bake",!1,(function(t,e){t?(this.light.mask|=4,this.affectLightmapped&&(this.light.mask&=-3)):(this.light.mask&=-5,this.affectLightmapped&&(this.light.mask|=2)),this.light.layersDirty()})),Hy("bakeDir",!0,(function(t,e){this.light.bakeDir=t})),Hy("isStatic",!1,(function(t,e){this.light.isStatic=t})),Hy("layers",[0],(function(t,e){for(var i=0;i<e.length;i++){var n=this.system.app.scene.layers.getLayerById(e[i]);n&&(n.removeLight(this),this.light.removeLayer(n))}for(var s=0;s<t.length;s++){var r=this.system.app.scene.layers.getLayerById(t[s]);r&&this.enabled&&this.entity.enabled&&(r.addLight(this),this.light.addLayer(r))}})),zy.push("penumbraSize"),Vy.push(1);var Wy=function(){for(var t=zy,e=Vy,i=0;i<t.length;i++){var n=e[i];n&&n.clone?this[t[i]]=n.clone():this[t[i]]=n}},Xy=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="light",i.ComponentType=Gy,i.DataType=Wy,i.on("beforeremove",i._onRemoveComponent,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i){for(var n=zy,s={},r=0,a=n.length;r<a;r++){var o=n[r];s[o]=i[o]}s.type||(s.type=e.data.type),e.data.type=s.type,s.layers&&Array.isArray(s.layers)&&(s.layers=s.layers.slice(0)),s.color&&Array.isArray(s.color)&&(s.color=new vt(s.color[0],s.color[1],s.color[2])),s.cookieOffset&&s.cookieOffset instanceof Array&&(s.cookieOffset=new Et(s.cookieOffset[0],s.cookieOffset[1])),s.cookieScale&&s.cookieScale instanceof Array&&(s.cookieScale=new Et(s.cookieScale[0],s.cookieScale[1])),s.enable&&(console.warn("WARNING: enable: Property is deprecated. Set enabled property instead."),s.enabled=s.enable),s.shape||(s.shape=0);var h=new Uu(this.app.graphicsDevice);h.type=Ou[s.type],h._node=e.entity,e.data.light=h,t.prototype.initializeComponentData.call(this,e,s,n)},i._onRemoveComponent=function(t,e){e.onRemove()},i.cloneComponent=function(t,e){for(var i,n=t.light,s=[],r=zy,a=0;a<r.length;a++)"light"!==(i=r[a])&&(n[i]&&n[i].clone?s[i]=n[i].clone():s[i]=n[i]);return this.addComponent(e,s)},i.changeType=function(t,e,i){e!==i&&(t.light.type=Ou[i])},e}(wp),jy=["x","y","z","w"],qy=[void 0,void 0,Et,wt,Pt];function Yy(t,e,i,n){switch(e.type){case"boolean":return!!i;case"number":if("number"==typeof i)return i;if("string"==typeof i){var s=parseInt(i,10);return isNaN(s)?null:s}return"boolean"==typeof i?0+i:null;case"json":var r={};if(Array.isArray(e.schema)){i&&"object"==typeof i||(i={});for(var a=0;a<e.schema.length;a++){var o=e.schema[a];if(o.name)if(o.array){r[o.name]=[];for(var h=Array.isArray(i[o.name])?i[o.name]:[],l=0;l<h.length;l++)r[o.name].push(Yy(t,o,h[l]))}else{var c=i.hasOwnProperty(o.name)?i[o.name]:o.default;r[o.name]=Yy(t,o,c)}}}return r;case"asset":return i instanceof Vf?i:"number"==typeof i?t.assets.get(i)||null:"string"==typeof i&&t.assets.get(parseInt(i,10))||null;case"entity":return i instanceof hh?i:"string"==typeof i?t.getEntityFromIndex(i):null;case"rgb":case"rgba":if(i instanceof vt)return n instanceof vt?(n.copy(i),n):i.clone();if(i instanceof Array&&i.length>=3&&i.length<=4){for(var u=0;u<i.length;u++)if("number"!=typeof i[u])return null;return n||(n=new vt),n.r=i[0],n.g=i[1],n.b=i[2],n.a=3===i.length?1:i[3],n}return"string"==typeof i&&/#([0-9abcdef]{2}){3,4}/i.test(i)?(n||(n=new vt),n.fromString(i),n):null;case"vec2":case"vec3":case"vec4":var d=parseInt(e.type.slice(3),10),f=qy[d];if(i instanceof f)return n instanceof f?(n.copy(i),n):i.clone();if(i instanceof Array&&i.length===d){for(var p=0;p<i.length;p++)if("number"!=typeof i[p])return null;n||(n=new f);for(var m=0;m<d;m++)n[jy[m]]=i[m];return n}return null;case"curve":if(i){var _;if(i instanceof St||i instanceof bt)_=i.clone();else(_=new(i.keys[0]instanceof Array?bt:St)(i.keys)).type=i.type;return _}}return i}var Ky=function(){function t(t){this.scriptType=t,this.index={}}var e=t.prototype;return e.add=function(e,i){this.index[e]||t.reservedNames.has(e)||(this.index[e]=i,Object.defineProperty(this.scriptType.prototype,e,{get:function(){return this.__attributes[e]},set:function(t){var n="attr",s="attr:"+e,r=this.__attributes[e],a=r;if(r&&"json"!==i.type&&"entity"!==i.type&&r.clone&&(this.hasEvent(n)||this.hasEvent(s))&&(a=r.clone()),i.array){if(this.__attributes[e]=[],t)for(var o=0,h=t.length;o<h;o++)this.__attributes[e].push(Yy(this.app,i,t[o],r?r[o]:null))}else this.__attributes[e]=Yy(this.app,i,t,r);this.fire(n,e,this.__attributes[e],a),this.fire(s,this.__attributes[e],a)}}))},e.remove=function(t){return!!this.index[t]&&(delete this.index[t],delete this.scriptType.prototype[t],!0)},e.has=function(t){return!!this.index[t]},e.get=function(t){return this.index[t]||null},t}();Ky.reservedNames=new Set(["app","entity","enabled","_enabled","_enabledOld","_destroyed","__attributes","__attributesRaw","__scriptType","__executionOrder","_callbacks","_callbackActive","has","get","on","off","fire","once","hasEvent"]);var Zy="initialize",Qy="postInitialize",$y=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._scripts=[],n._updateList=new ct({sortBy:"__executionOrder"}),n._postUpdateList=new ct({sortBy:"__executionOrder"}),n._scriptsIndex={},n._destroyedScripts=[],n._destroyed=!1,n._scriptsData=null,n._oldState=!0,n._enabled=!0,n._beingEnabled=!1,n._isLoopingThroughScripts=!1,n._executionOrder=-1,n.on("set_enabled",n._onSetEnabled,w(n)),n}S(e,t);var i=e.prototype;return i.onEnable=function(){this._beingEnabled=!0,this._checkState(),this.entity._beingEnabled||this.onPostStateChange(),this._beingEnabled=!1},i.onDisable=function(){this._checkState()},i.onPostStateChange=function(){for(var t=this._beginLooping(),e=0,i=this.scripts.length;e<i;e++){var n=this.scripts[e];n._initialized&&!n._postInitialized&&n.enabled&&(n._postInitialized=!0,n.postInitialize&&this._scriptMethod(n,Qy))}this._endLooping(t)},i._beginLooping=function(){var t=this._isLoopingThroughScripts;return this._isLoopingThroughScripts=!0,t},i._endLooping=function(t){this._isLoopingThroughScripts=t,this._isLoopingThroughScripts||this._removeDestroyedScripts()},i._onSetEnabled=function(t,e,i){this._beingEnabled=!0,this._checkState(),this._beingEnabled=!1},i._checkState=function(){var t=this.enabled&&this.entity.enabled;if(t!==this._oldState){this._oldState=t,this.fire(t?"enable":"disable"),this.fire("state",t),t?this.system._addComponentToEnabled(this):this.system._removeComponentFromEnabled(this);for(var e=this._beginLooping(),i=0,n=this.scripts.length;i<n;i++){var s=this.scripts[i];s.enabled=s._enabled}this._endLooping(e)}},i._onBeforeRemove=function(){this.fire("remove");for(var t=this._beginLooping(),e=0;e<this.scripts.length;e++){var i=this.scripts[e];i&&this.destroy(i.__scriptType.__name)}this._endLooping(t)},i._removeDestroyedScripts=function(){var t=this._destroyedScripts.length;if(t){for(var e=0;e<t;e++){var i=this._destroyedScripts[e];this._removeScriptInstance(i)}this._destroyedScripts.length=0,this._resetExecutionOrder(0,this._scripts.length)}},i._onInitializeAttributes=function(){for(var t=0,e=this.scripts.length;t<e;t++)this.scripts[t].__initializeAttributes()},i._scriptMethod=function(t,e,i){t[e](i)},i._onInitialize=function(){for(var t=this._scripts,e=this._beginLooping(),i=0,n=t.length;i<n;i++){var s=t[i];!s._initialized&&s.enabled&&(s._initialized=!0,s.initialize&&this._scriptMethod(s,Zy))}this._endLooping(e)},i._onPostInitialize=function(){this.onPostStateChange()},i._onUpdate=function(t){var e=this._updateList;if(e.length){var i=this._beginLooping();for(e.loopIndex=0;e.loopIndex<e.length;e.loopIndex++){var n=e.items[e.loopIndex];n.enabled&&this._scriptMethod(n,"update",t)}this._endLooping(i)}},i._onPostUpdate=function(t){var e=this._postUpdateList;if(e.length){var i=this._beginLooping();for(e.loopIndex=0;e.loopIndex<e.length;e.loopIndex++){var n=e.items[e.loopIndex];n.enabled&&this._scriptMethod(n,"postUpdate",t)}this._endLooping(i)}},i._insertScriptInstance=function(t,e,i){-1===e?(this._scripts.push(t),t.__executionOrder=i,t.update&&this._updateList.append(t),t.postUpdate&&this._postUpdateList.append(t)):(this._scripts.splice(e,0,t),t.__executionOrder=e,this._resetExecutionOrder(e+1,i+1),t.update&&this._updateList.insert(t),t.postUpdate&&this._postUpdateList.insert(t))},i._removeScriptInstance=function(t){var e=this._scripts.indexOf(t);return-1===e||(this._scripts.splice(e,1),t.update&&this._updateList.remove(t),t.postUpdate&&this._postUpdateList.remove(t)),e},i._resetExecutionOrder=function(t,e){for(var i=t;i<e;i++)this._scripts[i].__executionOrder=i},i._resolveEntityScriptAttribute=function(t,e,i,n,s,r){if(t.array){var a=i.length;if(!a)return;for(var o=i.slice(),h=0;h<a;h++){var l=o[h]instanceof ip?o[h].getGuid():o[h];r[l]&&(o[h]=n?r[l].getGuid():r[l])}s[e]=o}else{if(i instanceof ip)i=i.getGuid();else if("string"!=typeof i)return;r[i]&&(s[e]=r[i])}},i.has=function(t){if("string"==typeof t)return!!this._scriptsIndex[t];if(!t)return!1;var e=t,i=e.__name,n=this._scriptsIndex[i];return(n&&n.instance)instanceof e},i.get=function(t){if("string"==typeof t){var e=this._scriptsIndex[t];return e?e.instance:null}if(!t)return null;var i=t,n=i.__name,s=this._scriptsIndex[n],r=s&&s.instance;return r instanceof i?r:null},i.create=function(t,e){void 0===e&&(e={});var i=this,n=t,s=t;if("string"==typeof n?n=this.system.app.scripts.get(n):n&&(s=n.__name),n){if(!this._scriptsIndex[s]||!this._scriptsIndex[s].instance){var r=new n({app:this.system.app,entity:this.entity,enabled:!e.hasOwnProperty("enabled")||e.enabled,attributes:e.attributes}),a=this._scripts.length,o=-1;return"number"==typeof e.ind&&-1!==e.ind&&a>e.ind&&(o=e.ind),this._insertScriptInstance(r,o,a),this._scriptsIndex[s]={instance:r,onSwap:function(){i.swap(s)}},this[s]=r,e.preloading||r.__initializeAttributes(),this.fire("create",s,r),this.fire("create:"+s,r),this.system.app.scripts.on("swap:"+s,this._scriptsIndex[s].onSwap),e.preloading||(r.enabled&&!r._initialized&&(r._initialized=!0,r.initialize&&this._scriptMethod(r,Zy)),r.enabled&&!r._postInitialized&&(r._postInitialized=!0,r.postInitialize&&this._scriptMethod(r,Qy))),r}}else this._scriptsIndex[s]={awaiting:!0,ind:this._scripts.length};return null},i.destroy=function(t){var e=t,i=t;"string"==typeof i?i=this.system.app.scripts.get(i):i&&(e=i.__name);var n=this._scriptsIndex[e];if(delete this._scriptsIndex[e],!n)return!1;var s=n.instance;if(s&&!s._destroyed)if(s.enabled=!1,s._destroyed=!0,this._isLoopingThroughScripts)this._destroyedScripts.push(s);else{var r=this._removeScriptInstance(s);r>=0&&this._resetExecutionOrder(r,this._scripts.length)}return this.system.app.scripts.off("swap:"+e,n.onSwap),delete this[e],this.fire("destroy",e,s||null),this.fire("destroy:"+e,s||null),s&&s.fire("destroy"),!0},i.swap=function(t){var e=t,i=t;"string"==typeof i?i=this.system.app.scripts.get(i):i&&(e=i.__name);var n=this._scriptsIndex[e];if(!n||!n.instance)return!1;var s=n.instance,r=this._scripts.indexOf(s),a=new i({app:this.system.app,entity:this.entity,enabled:s.enabled,attributes:s.__attributes});return!!a.swap&&(a.__initializeAttributes(),this._scripts[r]=a,this._scriptsIndex[e].instance=a,this[e]=a,a.__executionOrder=r,s.update&&this._updateList.remove(s),s.postUpdate&&this._postUpdateList.remove(s),a.update&&this._updateList.insert(a),a.postUpdate&&this._postUpdateList.insert(a),this._scriptMethod(a,"swap",s),this.fire("swap",e,a),this.fire("swap:"+e,a),!0)},i.resolveDuplicatedEntityReferenceProperties=function(t,e){var i=this.entity.script;for(var n in t._scriptsIndex){var s=this.system.app.scripts.get(n);if(s){var r=t._scriptsIndex[n];if(r&&r.instance){var a=i[n].__attributesRaw,o=i[n].__attributes;if(a||o){var h=!!a,l=r.instance.__attributes;for(var c in l)if(l[c]){var u=s.attributes.get(c);if(u)if("entity"===u.type)this._resolveEntityScriptAttribute(u,c,l[c],h,a||o,e);else if("json"===u.type&&Array.isArray(u.schema))for(var d=l[c],f=a?a[c]:o[c],p=0;p<u.schema.length;p++){var m=u.schema[p];if("entity"===m.type)if(u.array)for(var _=0;_<d.length;_++)this._resolveEntityScriptAttribute(m,m.name,d[_][m.name],h,f[_],e);else this._resolveEntityScriptAttribute(m,m.name,d[m.name],h,f,e)}}}}}}},i.move=function(t,e){var i=this._scripts.length;if(e>=i||e<0)return!1;var n=t,s=t;"string"!=typeof s?s=t.__name:n=null;var r=this._scriptsIndex[s];if(!r||!r.instance)return!1;var a=r.instance;if(n&&!(a instanceof n))return!1;var o=this._scripts.indexOf(a);return-1!==o&&o!==e&&(this._scripts.splice(e,0,this._scripts.splice(o,1)[0]),this._resetExecutionOrder(0,i),this._updateList.sort(),this._postUpdateList.sort(),this.fire("move",s,a,e,o),this.fire("move:"+s,a,e,o),!0)},y(e,[{key:"scripts",get:function(){return this._scripts},set:function(t){for(var e in this._scriptsData=t,t)if(t.hasOwnProperty(e)){var i=this._scriptsIndex[e];if(i){if("boolean"==typeof t[e].enabled&&(i.enabled=!!t[e].enabled),"object"==typeof t[e].attributes)for(var n in t[e].attributes)if(!Ky.reservedNames.has(n)){if(!i.__attributes.hasOwnProperty(n)){var s=this.system.app.scripts.get(e);s&&s.attributes.add(n,{})}i[n]=t[e].attributes[n]}}else console.log(this.order)}}},{key:"enabled",get:function(){return this._enabled},set:function(t){var e=this._enabled;this._enabled=t,this.fire("set","enabled",e,t)}}]),e}(bp),Jy=function(){this.enabled=!0},tx=0,ex=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="script",i.ComponentType=$y,i.DataType=Jy,i._components=new ct({sortBy:"_executionOrder"}),i._enabledComponents=new ct({sortBy:"_executionOrder"}),i.preloading=!0,i.on("beforeremove",i._onBeforeRemove,w(i)),i.app.systems.on("initialize",i._onInitialize,w(i)),i.app.systems.on("postInitialize",i._onPostInitialize,w(i)),i.app.systems.on("update",i._onUpdate,w(i)),i.app.systems.on("postUpdate",i._onPostUpdate,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(t,e){if(t._executionOrder=tx++,this._components.append(t),tx>Number.MAX_SAFE_INTEGER&&this._resetExecutionOrder(),t.enabled=!e.hasOwnProperty("enabled")||!!e.enabled,t.enabled&&t.entity.enabled&&this._enabledComponents.append(t),e.hasOwnProperty("order")&&e.hasOwnProperty("scripts")){t._scriptsData=e.scripts;for(var i=0;i<e.order.length;i++)t.create(e.order[i],{enabled:e.scripts[e.order[i]].enabled,attributes:e.scripts[e.order[i]].attributes,preloading:this.preloading})}},i.cloneComponent=function(t,e){for(var i=[],n={},s=0;s<t.script._scripts.length;s++){var r=t.script._scripts[s],a=r.__scriptType.__name;i.push(a);var o={};for(var h in r.__attributes)o[h]=r.__attributes[h];n[a]={enabled:r._enabled,attributes:o}}for(var l in t.script._scriptsIndex)l.awaiting&&i.splice(l.ind,0,l);var c={enabled:t.script.enabled,order:i,scripts:n};return this.addComponent(e,c)},i._resetExecutionOrder=function(){tx=0;for(var t=0,e=this._components.length;t<e;t++)this._components.items[t]._executionOrder=tx++},i._callComponentMethod=function(t,e,i){for(t.loopIndex=0;t.loopIndex<t.length;t.loopIndex++)t.items[t.loopIndex][e](i)},i._onInitialize=function(){this.preloading=!1,this._callComponentMethod(this._components,"_onInitializeAttributes"),this._callComponentMethod(this._enabledComponents,"_onInitialize")},i._onPostInitialize=function(){this._callComponentMethod(this._enabledComponents,"_onPostInitialize")},i._onUpdate=function(t){this._callComponentMethod(this._enabledComponents,"_onUpdate",t)},i._onPostUpdate=function(t){this._callComponentMethod(this._enabledComponents,"_onPostUpdate",t)},i._addComponentToEnabled=function(t){this._enabledComponents.insert(t)},i._removeComponentFromEnabled=function(t){this._enabledComponents.remove(t)},i._onBeforeRemove=function(t,e){this._components.items.indexOf(e)>=0&&e._onBeforeRemove(),this._removeComponentFromEnabled(e),this._components.remove(e)},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("initialize",this._onInitialize,this),this.app.systems.off("postInitialize",this._onPostInitialize,this),this.app.systems.off("update",this._onUpdate,this),this.app.systems.off("postUpdate",this._onPostUpdate,this)},e}(wp),ix=function(t){function e(){var e;return(e=t.call(this)||this)._meshes=null,e}S(e,t);var i=e.prototype;return i.destroy=function(){this.meshes=null},i.decRefMeshes=function(){if(this._meshes)for(var t=this._meshes.length,e=0;e<t;e++){var i=this._meshes[e];i&&(i.decRefCount(),i.refCount<1&&(i.destroy(),this._meshes[e]=null))}},i.incRefMeshes=function(){if(this._meshes)for(var t=this._meshes.length,e=0;e<t;e++)this._meshes[e]&&this._meshes[e].incRefCount()},y(e,[{key:"meshes",get:function(){return this._meshes},set:function(t){this.decRefMeshes(),this._meshes=t,this.incRefMeshes(),this.fire("set:meshes",t)}}]),e}(P);function nx(t){var e=this;if(e.resource){var i=t.resource,n=i.renders&&i.renders[e.data.renderIndex];n&&(e.resource.meshes=n.resource.meshes)}}function sx(t){var e=this;e.registry.off("load:"+t.id,nx,e),e.registry.on("load:"+t.id,nx,e),e.registry.off("remove:"+t.id,rx,e),e.registry.once("remove:"+t.id,rx,e),t.resource?nx.call(e,t):e.registry.load(t)}function rx(t){var e=this;e.registry.off("load:"+t.id,nx,e),e.resource&&e.resource.destroy()}var ax=function(){function t(t){this.handlerType="render",this._registry=t.assets}var e=t.prototype;return e.load=function(t,e,i){},e.open=function(t,e){return new ix},e.patch=function(t,e){if(t.data.containerAsset){var i=e.get(t.data.containerAsset);i?sx.call(t,i):e.once("add:"+t.data.containerAsset,sx,t)}},t}(),ox=function(){function t(t,e,i,n){this._paths=t,this._input=e,this._output=i,this._interpolation=n}return y(t,[{key:"paths",get:function(){return this._paths}},{key:"input",get:function(){return this._input}},{key:"output",get:function(){return this._output}},{key:"interpolation",get:function(){return this._interpolation}}]),t}(),hx=function(){function t(t,e){this._components=t,this._data=e}return y(t,[{key:"components",get:function(){return this._components}},{key:"data",get:function(){return this._data}}]),t}();function lx(t,e){var i,n=function(t,e){switch(e){case i.DT_INT8:return new Int8Array(t.buffer,t.byteOffset,t.byteLength);case i.DT_INT16:return new Int16Array(t.buffer,t.byteOffset,t.byteLength/2);case i.DT_INT32:return new Int32Array(t.buffer,t.byteOffset,t.byteLength/4);case i.DT_UINT8:return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);case i.DT_UINT16:return new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2);case i.DT_UINT32:return new Uint32Array(t.buffer,t.byteOffset,t.byteLength/4);case i.DT_FLOAT32:return new Float32Array(t.buffer,t.byteOffset,t.byteLength/4)}return null},s=function(t){return t.num_components()*function(t){switch(t){case i.DT_INT8:return 1;case i.DT_INT16:return 2;case i.DT_INT32:return 4;case i.DT_UINT8:return 1;case i.DT_UINT16:return 2;case i.DT_UINT32:case i.DT_FLOAT32:return 4}return 1}(t.data_type())},r={0:0,1:1,5:2,2:3,7:4,8:5,4:6,3:7},a=function(t,e){for(var i=function(t,e,i){t[0]=e[0]-i[0],t[1]=e[1]-i[1],t[2]=e[2]-i[2]},n=function(t,e,i){t[0]=e[1]*i[2]-i[1]*e[2],t[1]=e[2]*i[0]-i[2]*e[0],t[2]=e[0]*i[1]-i[0]*e[1]},s=function(t,e){var i=t[e+0],n=t[e+1],s=t[e+2],r=1/Math.sqrt(i*i+n*n+s*s);t[e+0]*=r,t[e+1]*=r,t[e+2]*=r},r=function(t,e,i){for(var n=0;n<3;++n)t[n]=e[i+n]},a=e.length/3,o=t.length/3,h=new Float32Array(t.length),l=[0,0,0],c=[0,0,0],u=[0,0,0],d=[0,0,0],f=[0,0,0],p=[0,0,0],m=0;m<a;++m){var _=3*e[3*m+0],v=3*e[3*m+1],g=3*e[3*m+2];r(l,t,_),r(c,t,v),r(u,t,g),i(d,c,l),i(f,u,l),n(p,d,f),s(p,0);for(var y=0;y<3;++y)h[_+y]+=p[y],h[v+y]+=p[y],h[g+y]+=p[y]}for(var x=0;x<o;++x)s(h,3*x);return new Uint8Array(h.buffer)},o=function(t){var e=function(t){var e={},o=new i.DecoderBuffer;o.Init(t,t.length);var h=new i.Decoder;if(h.GetEncodedGeometryType(o)!==i.TRIANGULAR_MESH)return e.error="Failed to decode draco mesh: not a mesh",e;var l=new i.Mesh,c=h.DecodeBufferToMesh(o,l);if(!c||!c.ok()||0===l.ptr)return e.error="Failed to decode draco asset",e;var u=3*l.num_faces(),d=l.num_points()<=65535,f=u*(d?2:4),p=i._malloc(f);d?(h.GetTrianglesUInt16Array(l,f,p),e.indices=new Uint16Array(i.HEAPU16.buffer,p,u).slice().buffer):(h.GetTrianglesUInt32Array(l,f,p),e.indices=new Uint32Array(i.HEAPU32.buffer,p,u).slice().buffer),i._free(p);for(var m=[],_=0;_<l.num_attributes();++_)m.push(h.GetAttribute(l,_));m.sort((function(t,e){var i,n;return(null!=(i=r[t.attribute_type()])?i:r.length)-(null!=(n=r[e.attribute_type()])?n:r.length)})),e.attributes=m.map((function(t){return t.unique_id()}));var v=0,g=m.map((function(t){var e=v;return v+=4*Math.ceil(s(t)/4),e})),y=m.some((function(t){return 1===t.attribute_type()})),x=g[1];if(!y){for(var S=1;S<g.length;++S)g[S]+=12;v+=12}e.vertices=new ArrayBuffer(l.num_points()*v);for(var b=new Uint8Array(e.vertices),w=0;w<l.num_attributes();++w){var T=m[w],A=s(T),C=l.num_points()*A,E=i._malloc(C);h.GetAttributeDataArrayForAllPoints(l,T,T.data_type(),C,E);for(var M=new Uint8Array(i.HEAPU8.buffer,E,C),P=0;P<l.num_points();++P)for(var R=0;R<A;++R)b[P*v+g[w]+R]=M[P*A+R];if(!y&&0===T.attribute_type())for(var I=a(n(M,T.data_type()),d?new Uint16Array(e.indices):new Uint32Array(e.indices)),L=0;L<l.num_points();++L)for(var D=0;D<12;++D)b[L*v+x+D]=I[12*L+D];i._free(E)}return i.destroy(l),i.destroy(h),i.destroy(o),e}(new Uint8Array(t.buffer));self.postMessage({jobId:t.jobId,error:e.error,indices:e.indices,vertices:e.vertices,attributes:e.attributes},[e.indices,e.vertices].filter((function(t){return null!=t})))},h=[];self.onmessage=function(t){var e=t.data;switch(e.type){case"init":self.DracoDecoderModule({instantiateWasm:function(t,i){return WebAssembly.instantiate(e.module,t).then((function(t){return i(t)})).catch((function(t){return console.error("instantiate failed + "+t)})),{}}}).then((function(t){i=t,h.forEach((function(t){return o(t)}))}));break;case"decodeMesh":i?o(e):h.push(e)}}}var cx,ux,dx,fx,px=function(){function t(){this.workers=[[],[],[]],this.jobId=0,this.jobQueue=[],this.jobCallbacks=new Map,this.run=function(t,e){t.postMessage({type:"decodeMesh",jobId:e.jobId,buffer:e.buffer},[e.buffer])}}var e=t.prototype;return e.init=function(t){var e=this;for(t.forEach((function(t){t.addEventListener("message",(function(i){var n=i.data,s=e.jobCallbacks.get(n.jobId);if(s&&s(n.error,{indices:n.indices,vertices:n.vertices,attributes:n.attributes}),e.jobCallbacks.delete(n.jobId),e.jobQueue.length>0){var r=e.jobQueue.shift();e.run(t,r)}else{var a=e.workers[2].indexOf(t);if(-1!==a)e.workers[2].splice(a,1),e.workers[1].push(t);else{var o=e.workers[1].indexOf(t);-1!==o&&(e.workers[1].splice(o,1),e.workers[0].push(t))}}}))})),this.workers[0]=t;this.jobQueue.length&&(this.workers[0].length||this.workers[1].length);){var i=this.jobQueue.shift();if(this.workers[0].length>0){var n=this.workers[0].shift();this.workers[1].push(n),this.run(n,i)}else{var s=this.workers[1].shift();this.workers[2].push(s),this.run(s,i)}}},e.enqueueJob=function(t,e){var i={jobId:this.jobId++,buffer:t};if(this.jobCallbacks.set(i.jobId,e),this.workers[0].length>0){var n=this.workers[0].shift();this.workers[1].push(n),this.run(n,i)}else if(this.workers[1].length>0){var s=this.workers[1].shift();this.workers[2].push(s),this.run(s,i)}else this.jobQueue.push(i)},t}(),mx=function(t){var e=function(){return fetch(t).then((function(t){return t.arrayBuffer()})).then((function(t){return WebAssembly.compile(t)}))};return WebAssembly.compileStreaming?WebAssembly.compileStreaming(fetch(t)).catch((function(t){return e()})):e()},_x=function(t){if(cx)return!0;if(!t)if(ux)t=ux;else{var e=ht.getConfig("DracoDecoderModule");t=e?{jsUrl:e.glueUrl,wasmUrl:e.wasmUrl,numWorkers:e.numWorkers}:{jsUrl:"draco.wasm.js",wasmUrl:"draco.wasm.wasm",numWorkers:1}}return!(!t.jsUrl||!t.wasmUrl)&&(cx=new px,Promise.all([(i=t.jsUrl,new Promise((function(t,e){var n={cache:!0,responseType:"text",retry:!0,maxRetries:3};_a.get(i,n,(function(i,n){i?e(i):t(n)}))}))),mx(t.wasmUrl)]).then((function(e){for(var i=e[0],n=e[1],s=["/* draco */",i,"/* worker */","(\n"+lx.toString()+"\n)()\n\n"].join("\n"),r=new Blob([s],{type:"application/javascript"}),a=URL.createObjectURL(r),o=Math.max(1,Math.min(16,t.numWorkers||1)),h=[],l=0;l<o;++l){var c=new Worker(a);c.postMessage({type:"init",module:n}),h.push(c)}cx.init(h)})),!0);var i},vx=function(){function t(){this.gltf=void 0,this.nodes=void 0,this.scenes=void 0,this.animations=void 0,this.textures=void 0,this.materials=void 0,this.variants=void 0,this.meshVariants=void 0,this.meshDefaultMaterials=void 0,this.renders=void 0,this.skins=void 0,this.lights=void 0,this.cameras=void 0}return t.prototype.destroy=function(){this.renders&&this.renders.forEach((function(t){t.meshes=null}))},t}(),gx=function(t){return/^data:.*,.*$/i.test(t)},yx=function(t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":default:return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}},xx=function(t){switch(t){case 5120:default:return 0;case 5121:return mi;case 5122:return 2;case 5123:return 3;case 5124:return 4;case 5125:return 5;case 5126:return 6}},Sx=function(t){switch(t){case 5120:case 5121:return 1;case 5122:case 5123:return 2;case 5124:case 5125:case 5126:return 4;default:return 0}},bx={POSITION:we,NORMAL:Te,TANGENT:Ae,COLOR_0:Me,JOINTS_0:Ee,WEIGHTS_0:Ce,TEXCOORD_0:Re,TEXCOORD_1:Ie,TEXCOORD_2:Le,TEXCOORD_3:De,TEXCOORD_4:Oe,TEXCOORD_5:ke,TEXCOORD_6:Fe,TEXCOORD_7:Be},wx=((dx={})[we]=0,dx[Te]=1,dx[Ae]=2,dx[Me]=3,dx[Ee]=4,dx[Ce]=5,dx[Re]=6,dx[Ie]=7,dx[Le]=8,dx[De]=9,dx[Oe]=10,dx[ke]=11,dx[Fe]=12,dx[Be]=13,dx),Tx=function(t,e,i){for(var n=function(t){switch(t){case 0:return function(t){return Math.max(t/127,-1)};case mi:return function(t){return t/255};case 2:return function(t){return Math.max(t/32767,-1)};case 3:return function(t){return t/65535};default:return function(t){return t}}}(i),s=e.length,r=0;r<s;++r)t[r]=n(e[r]);return t},Ax=function t(e,i,n){void 0===n&&(n=!1);var s,r=yx(e.type),a=function(t){switch(t){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5124:return Int32Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:return null}}(e.componentType);if(!a)return null;if(e.sparse){var o=e.sparse,h={count:o.count,type:"SCALAR"},l=t(Object.assign(h,o.indices),i,!0),c={count:o.count,type:e.type,componentType:e.componentType},u=t(Object.assign(c,o.values),i,!0);if(e.hasOwnProperty("bufferView"))s=t({bufferView:e.bufferView,byteOffset:e.byteOffset,componentType:e.componentType,count:e.count,type:e.type},i,!0).slice();else s=new a(e.count*r);for(var d=0;d<o.count;++d)for(var f=l[d],p=0;p<r;++p)s[f*r+p]=u[d*r+p]}else if(e.hasOwnProperty("bufferView")){var m=i[e.bufferView];if(n&&m.hasOwnProperty("byteStride")){for(var _=r*a.BYTES_PER_ELEMENT,v=new ArrayBuffer(e.count*_),g=new Uint8Array(v),y=0,x=0;x<e.count;++x)for(var S=(e.byteOffset||0)+x*m.byteStride,b=0;b<_;++b)g[y++]=m[S++];s=new a(v)}else s=new a(m.buffer,m.byteOffset+(e.byteOffset||0),e.count*r)}else s=new a(e.count*r);return s},Cx=function(t,e){var i=Ax(t,e,!0);if(i instanceof Float32Array||!t.normalized)return i;var n=new Float32Array(i.length);return Tx(n,i,xx(t.componentType)),n},Ex=function(t){var e=t.min,i=t.max;if(!e||!i)return null;if(t.normalized){var n=xx(t.componentType);e=Tx([],e,n),i=Tx([],i,n)}return new Ht(new wt(.5*(i[0]+e[0]),.5*(i[1]+e[1]),.5*(i[2]+e[2])),new wt(.5*(i[0]-e[0]),.5*(i[1]-e[1]),.5*(i[2]-e[2])))},Mx=function(t){if(!t.hasOwnProperty("mode"))return 4;switch(t.mode){case 0:return 0;case 1:return 1;case 2:return 2;case 3:return 3;case 4:default:return 4;case 5:return be;case 6:return 6}},Px=function(t,e){var i=t[we];if(i&&3===i.components){var n;if(i.size!==i.stride){var s=i.stride/Ci[i.type],r=new Ai[i.type](i.buffer,i.offset,i.count*s);n=new Ai[i.type](3*i.count);for(var a=0;a<i.count;++a)n[3*a+0]=r[a*s+0],n[3*a+1]=r[a*s+1],n[3*a+2]=r[a*s+2]}else n=new Ai[i.type](i.buffer,i.offset,3*i.count);var o=i.count;e||(e=function(t){for(var e=new Uint16Array(t),i=0;i<t;i++)e[i]=i;return e}(o));var h=Qa(n,e),l=new Float32Array(h.length);l.set(h),t[Te]={buffer:l.buffer,size:12,offset:0,stride:12,count:o,components:3,type:6}}},Rx=function(t){var e=new Vf(t.name+"_clone",t.type,t.file,t.data,t.options);return e.loaded=!0,e.resource=function(t){var e=new Ls(t.device,t);return e._levels=function(t){for(var e=[],i=0;i<t._levels.length;++i){var n=[];if(t.cubemap)for(var s=0;s<6;++s)n.push(t._levels[i][s]);else n=t._levels[i];e.push(n)}return e}(t),e}(t.resource),t.registry.add(e),e},Ix=function(t,e,i){var n=e[we];if(!n)return null;var s,r,a,o,h,l,c=n.count,u=[];for(var d in e)if(e.hasOwnProperty(d)){var f={semantic:d,components:e[d].components,type:e[d].type,normalize:!!e[d].normalize};Ji.isElementValid(t,f)||f.components++,u.push(f)}u.sort((function(t,e){return wx[t.semantic]-wx[e.semantic]}));var p=new Ji(t,u),m=!0;for(s=0;s<p.elements.length;++s)if(l=(o=e[(h=p.elements[s]).name]).offset-n.offset,o.buffer!==n.buffer||o.stride!==h.stride||o.size!==h.size||l!==h.offset){m=!1;break}var _,v,g,y=new ji(t,p,c,0),x=y.lock(),S=new Uint32Array(x);if(m)_=new Uint32Array(n.buffer,n.offset,c*y.format.size/4),S.set(_);else for(s=0;s<y.format.elements.length;++s){v=(h=y.format.elements[s]).stride/4,g=(o=e[h.name]).stride/4,_=new Uint32Array(o.buffer,o.offset,(o.count-1)*g+(o.size+3)/4);var b=0,w=h.offset/4,T=Math.floor((o.size+3)/4);for(r=0;r<c;++r){for(a=0;a<T;++a)S[w+a]=_[b+a];b+=g,w+=v}}return i&&function(t){var e,i,n=[],s=[],r=[];for(e=0;e<t.format.elements.length;++e){var a=t.format.elements[e];if(a.name===Re||a.name===Ie)switch(a.dataType){case 6:n.push({offset:a.offset/4+1,stride:a.stride/4});break;case 3:s.push({offset:a.offset/2+1,stride:a.stride/2});break;case mi:r.push({offset:a.offset+1,stride:a.stride})}}var o=function(n,s,r){var a=new s(t.storage);for(e=0;e<n.length;++e){var o=n[e].offset,h=n[e].stride;for(i=0;i<t.numVertices;++i)a[o]=r-a[o],o+=h}};n.length>0&&o(n,Float32Array,1),s.length>0&&o(s,Uint16Array,65535),r.length>0&&o(r,Uint8Array,255)}(y),y.unlock(),y},Lx=function(t,e,i,n,s,r,a){var o,h=new qa(t);h.aabb=Ex(i[e.attributes.POSITION]);for(var l=[],c=0,u=Object.entries(e.attributes);c<u.length;c++){var d,f=u[c],p=f[0],m=i[f[1]],_=bx[p],v=xx(m.componentType);l.push({semantic:_,components:yx(m.type),type:v,normalize:null!=(d=m.normalized)?d:_===Me&&(v===mi||3===v)})}if(a.push(new Promise((function(i,s){var r,a,o=e.extensions.KHR_draco_mesh_compression;r=n[o.bufferView].slice().buffer,a=function(n,r){if(n)console.log(n),s(n);else{for(var a,c={},u=0,d=Object.entries(o.attributes);u<d.length;u++){var f=d[u],p=f[0],m=f[1];c[bx[p]]=r.attributes.indexOf(m)}l.sort((function(t,e){return c[t.semantic]-c[e.semantic]})),null!=(a=e.attributes)&&a.NORMAL||l.splice(1,0,{semantic:"NORMAL",components:3,type:6});var _=new Ji(t,l),v=r.vertices.byteLength/_.size,g=v<=65535?1:2,y=r.indices.byteLength/(v<=65535?2:4),x=new ji(t,_,v,0,r.vertices),S=new vr(t,g,y,0,r.indices);h.vertexBuffer=x,h.indexBuffer[0]=S,h.primitive[0].type=Mx(e),h.primitive[0].base=0,h.primitive[0].count=S?y:v,h.primitive[0].indexed=!!S,i()}},_x()&&cx.enqueueJob(r,a)}))),null!=e&&null!=(o=e.extensions)&&o.KHR_materials_variants){var g=e.extensions.KHR_materials_variants,y={};g.mappings.forEach((function(t){t.variants.forEach((function(e){y[e]=t.material}))})),s[h.id]=y}return r[h.id]=e.material,h},Dx=function(t,e,i,n,s,r,a,o,h,l){var c=[];return e.primitives.forEach((function(u){var d;if(null!=(d=u.extensions)&&d.KHR_draco_mesh_compression)c.push(Lx(t,u,i,n,a,o,l));else{var f=u.hasOwnProperty("indices")?Ax(i[u.indices],n,!0):null,p=function(t,e,i,n,s,r,a){var o={},h=[];for(var l in e)e.hasOwnProperty(l)&&bx.hasOwnProperty(l)&&(o[l]=e[l],h.push(l+":"+e[l]));h.sort();var c=h.join(),u=a[c];if(!u){var d={};for(var f in o){var p=n[e[f]],m=Ax(p,s),_=s[p.bufferView],v=bx[f],g=yx(p.type)*Sx(p.componentType),y=_&&_.hasOwnProperty("byteStride")?_.byteStride:g;d[v]={buffer:m.buffer,size:g,offset:m.byteOffset,stride:y,count:p.count,components:yx(p.type),type:xx(p.componentType),normalize:p.normalized}}d.hasOwnProperty(Te)||Px(d,i),u=Ix(t,d,r),a[c]=u}return u}(t,u.attributes,f,i,n,s,r),m=Mx(u),_=new qa(t);if(_.vertexBuffer=p,_.primitive[0].type=m,_.primitive[0].base=0,_.primitive[0].indexed=null!==f,null!==f){var v;2!==(v=f instanceof Uint8Array?0:f instanceof Uint16Array?1:2)||t.extUintElement||(v=1,f=new Uint16Array(f)),0===v&&t.isWebGPU&&(v=1,f=new Uint16Array(f));var g=new vr(t,v,f.length,0,f);_.indexBuffer[0]=g,_.primitive[0].count=f.length}else _.primitive[0].count=p.numVertices;if(u.hasOwnProperty("extensions")&&u.extensions.hasOwnProperty("KHR_materials_variants")){var y=u.extensions.KHR_materials_variants,x={};y.mappings.forEach((function(t){t.variants.forEach((function(e){x[e]=t.material}))})),a[_.id]=x}o[_.id]=u.material;var S=i[u.attributes.POSITION];if(_.aabb=Ex(S),u.hasOwnProperty("targets")){var b=[];u.targets.forEach((function(t,s){var r={};t.hasOwnProperty("POSITION")&&(S=i[t.POSITION],r.deltaPositions=Cx(S,n),r.deltaPositionsType=6,r.aabb=Ex(S)),t.hasOwnProperty("NORMAL")&&(S=i[t.NORMAL],r.deltaNormals=Cx(S,n),r.deltaNormalsType=6),e.hasOwnProperty("extras")&&e.extras.hasOwnProperty("targetNames")?r.name=e.extras.targetNames[s]:r.name=s.toString(10),e.hasOwnProperty("weights")&&(r.defaultWeight=e.weights[s]),r.preserveData=h.morphPreserveData,b.push(new Wu(r))})),_.morph=new Hu(b,t,{preferHighPrecision:h.morphPreferHighPrecision})}c.push(_)}})),c},Ox=function(t,e,i){var n,s,r=t.texCoord;if(r)for(s=0;s<i.length;++s)e[i[s]+"MapUv"]=r;var a=null==(n=t.extensions)?void 0:n.KHR_texture_transform;if(a){var o=a.offset||[0,0],h=a.scale||[1,1],l=a.rotation?-a.rotation*_t.RAD_TO_DEG:0,c=new Et(h[0],h[1]),u=new Et(o[0],1-h[1]-o[1]);for(s=0;s<i.length;++s)e[i[s]+"MapTiling"]=c,e[i[s]+"MapOffset"]=u,e[i[s]+"MapRotation"]=l}},kx=function(t,e,i){var n,s;if(t.hasOwnProperty("diffuseFactor")?(n=t.diffuseFactor,e.diffuse.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2)),e.opacity=n[3]):(e.diffuse.set(1,1,1),e.opacity=1),t.hasOwnProperty("diffuseTexture")){var r=t.diffuseTexture;s=i[r.index],e.diffuseMap=s,e.diffuseMapChannel="rgb",e.opacityMap=s,e.opacityMapChannel="a",Ox(r,e,["diffuse","opacity"])}if(e.useMetalness=!1,t.hasOwnProperty("specularFactor")?(n=t.specularFactor,e.specular.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2))):e.specular.set(1,1,1),t.hasOwnProperty("glossinessFactor")?e.gloss=t.glossinessFactor:e.gloss=1,t.hasOwnProperty("specularGlossinessTexture")){var a=t.specularGlossinessTexture;e.specularEncoding="srgb",e.specularMap=e.glossMap=i[a.index],e.specularMapChannel="rgb",e.glossMapChannel="a",Ox(a,e,["gloss","metalness"])}},Fx=function(t,e,i){if(t.hasOwnProperty("clearcoatFactor")?e.clearCoat=.25*t.clearcoatFactor:e.clearCoat=0,t.hasOwnProperty("clearcoatTexture")){var n=t.clearcoatTexture;e.clearCoatMap=i[n.index],e.clearCoatMapChannel="r",Ox(n,e,["clearCoat"])}if(t.hasOwnProperty("clearcoatRoughnessFactor")?e.clearCoatGloss=t.clearcoatRoughnessFactor:e.clearCoatGloss=0,t.hasOwnProperty("clearcoatRoughnessTexture")){var s=t.clearcoatRoughnessTexture;e.clearCoatGlossMap=i[s.index],e.clearCoatGlossMapChannel="g",Ox(s,e,["clearCoatGloss"])}if(t.hasOwnProperty("clearcoatNormalTexture")){var r=t.clearcoatNormalTexture;e.clearCoatNormalMap=i[r.index],Ox(r,e,["clearCoatNormal"]),r.hasOwnProperty("scale")&&(e.clearCoatBumpiness=r.scale)}e.clearCoatGlossInvert=!0},Bx=function(t,e,i){e.useLighting=!1,e.emissive.copy(e.diffuse),e.emissiveTint=e.diffuseTint,e.emissiveMap=e.diffuseMap,e.emissiveMapUv=e.diffuseMapUv,e.emissiveMapTiling.copy(e.diffuseMapTiling),e.emissiveMapOffset.copy(e.diffuseMapOffset),e.emissiveMapRotation=e.diffuseMapRotation,e.emissiveMapChannel=e.diffuseMapChannel,e.emissiveVertexColor=e.diffuseVertexColor,e.emissiveVertexColorChannel=e.diffuseVertexColorChannel,e.useLighting=!1,e.useSkybox=!1,e.diffuse.set(0,0,0),e.diffuseTint=!1,e.diffuseMap=null,e.diffuseVertexColor=!1},Ux=function(t,e,i){if(e.useMetalnessSpecularColor=!0,t.hasOwnProperty("specularColorTexture")&&(e.specularEncoding="srgb",e.specularMap=i[t.specularColorTexture.index],e.specularMapChannel="rgb",Ox(t.specularColorTexture,e,["specular"])),t.hasOwnProperty("specularColorFactor")){var n=t.specularColorFactor;e.specular.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2))}else e.specular.set(1,1,1);t.hasOwnProperty("specularFactor")?e.specularityFactor=t.specularFactor:e.specularityFactor=1,t.hasOwnProperty("specularTexture")&&(e.specularityFactorMapChannel="a",e.specularityFactorMap=i[t.specularTexture.index],Ox(t.specularTexture,e,["specularityFactor"]))},Nx=function(t,e,i){t.hasOwnProperty("ior")&&(e.refractionIndex=1/t.ior)},zx=function(t,e,i){e.blendType=2,e.useDynamicRefraction=!0,t.hasOwnProperty("transmissionFactor")&&(e.refraction=t.transmissionFactor),t.hasOwnProperty("transmissionTexture")&&(e.refractionMapChannel="r",e.refractionMap=i[t.transmissionTexture.index],Ox(t.transmissionTexture,e,["refraction"]))},Vx=function(t,e,i){if(e.useSheen=!0,t.hasOwnProperty("sheenColorFactor")){var n=t.sheenColorFactor;e.sheen.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2))}else e.sheen.set(1,1,1);t.hasOwnProperty("sheenColorTexture")&&(e.sheenMap=i[t.sheenColorTexture.index],e.sheenEncoding="srgb",Ox(t.sheenColorTexture,e,["sheen"])),t.hasOwnProperty("sheenRoughnessFactor")?e.sheenGloss=t.sheenRoughnessFactor:e.sheenGloss=0,t.hasOwnProperty("sheenRoughnessTexture")&&(e.sheenGlossMap=i[t.sheenRoughnessTexture.index],e.sheenGlossMapChannel="a",Ox(t.sheenRoughnessTexture,e,["sheenGloss"])),e.sheenGlossInvert=!0},Gx=function(t,e,i){if(e.blendType=2,e.useDynamicRefraction=!0,t.hasOwnProperty("thicknessFactor")&&(e.thickness=t.thicknessFactor),t.hasOwnProperty("thicknessTexture")&&(e.thicknessMap=i[t.thicknessTexture.index],e.thicknessMapChannel="g",Ox(t.thicknessTexture,e,["thickness"])),t.hasOwnProperty("attenuationDistance")&&(e.attenuationDistance=t.attenuationDistance),t.hasOwnProperty("attenuationColor")){var n=t.attenuationColor;e.attenuation.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2))}},Hx=function(t,e,i){t.hasOwnProperty("emissiveStrength")&&(e.emissiveIntensity=t.emissiveStrength)},Wx=function(t,e,i){e.useIridescence=!0,t.hasOwnProperty("iridescenceFactor")&&(e.iridescence=t.iridescenceFactor),t.hasOwnProperty("iridescenceTexture")&&(e.iridescenceMapChannel="r",e.iridescenceMap=i[t.iridescenceTexture.index],Ox(t.iridescenceTexture,e,["iridescence"])),t.hasOwnProperty("iridescenceIor")&&(e.iridescenceRefractionIndex=t.iridescenceIor),t.hasOwnProperty("iridescenceThicknessMinimum")&&(e.iridescenceThicknessMin=t.iridescenceThicknessMinimum),t.hasOwnProperty("iridescenceThicknessMaximum")&&(e.iridescenceThicknessMax=t.iridescenceThicknessMaximum),t.hasOwnProperty("iridescenceThicknessTexture")&&(e.iridescenceThicknessMapChannel="g",e.iridescenceThicknessMap=i[t.iridescenceThicknessTexture.index],Ox(t.iridescenceThicknessTexture,e,["iridescenceThickness"]))},Xx=function(t,e,i){var n,s,r=new lu;if(r.occludeSpecular=1,r.diffuseTint=!0,r.diffuseVertexColor=!0,r.specularTint=!0,r.specularVertexColor=!0,t.hasOwnProperty("name")&&(r.name=t.name),t.hasOwnProperty("pbrMetallicRoughness")){var a=t.pbrMetallicRoughness;if(a.hasOwnProperty("baseColorFactor")?(n=a.baseColorFactor,r.diffuse.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2)),r.opacity=n[3]):(r.diffuse.set(1,1,1),r.opacity=1),a.hasOwnProperty("baseColorTexture")){var o=a.baseColorTexture;s=e[o.index],r.diffuseMap=s,r.diffuseMapChannel="rgb",r.opacityMap=s,r.opacityMapChannel="a",Ox(o,r,["diffuse","opacity"])}if(r.useMetalness=!0,r.specular.set(1,1,1),a.hasOwnProperty("metallicFactor")?r.metalness=a.metallicFactor:r.metalness=1,a.hasOwnProperty("roughnessFactor")?r.gloss=a.roughnessFactor:r.gloss=1,r.glossInvert=!0,a.hasOwnProperty("metallicRoughnessTexture")){var h=a.metallicRoughnessTexture;r.metalnessMap=r.glossMap=e[h.index],r.metalnessMapChannel="b",r.glossMapChannel="g",Ox(h,r,["gloss","metalness"])}}if(t.hasOwnProperty("normalTexture")){var l=t.normalTexture;r.normalMap=e[l.index],Ox(l,r,["normal"]),l.hasOwnProperty("scale")&&(r.bumpiness=l.scale)}if(t.hasOwnProperty("occlusionTexture")){var c=t.occlusionTexture;r.aoMap=e[c.index],r.aoMapChannel="r",Ox(c,r,["ao"])}if(t.hasOwnProperty("emissiveFactor")?(n=t.emissiveFactor,r.emissive.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2)),r.emissiveTint=!0):(r.emissive.set(0,0,0),r.emissiveTint=!1),t.hasOwnProperty("emissiveTexture")){var u=t.emissiveTexture;r.emissiveMap=e[u.index],Ox(u,r,["emissive"])}if(t.hasOwnProperty("alphaMode"))switch(t.alphaMode){case"MASK":r.blendType=3,t.hasOwnProperty("alphaCutoff")?r.alphaTest=t.alphaCutoff:r.alphaTest=.5;break;case"BLEND":r.blendType=2,r.alphaTest=1/255;break;default:r.blendType=3}else r.blendType=3;t.hasOwnProperty("doubleSided")?(r.twoSidedLighting=t.doubleSided,r.cull=t.doubleSided?se:1):(r.twoSidedLighting=!1,r.cull=1);var d={KHR_materials_clearcoat:Fx,KHR_materials_emissive_strength:Hx,KHR_materials_ior:Nx,KHR_materials_iridescence:Wx,KHR_materials_pbrSpecularGlossiness:kx,KHR_materials_sheen:Vx,KHR_materials_specular:Ux,KHR_materials_transmission:zx,KHR_materials_unlit:Bx,KHR_materials_volume:Gx};if(t.hasOwnProperty("extensions"))for(var f in t.extensions){var p=d[f];void 0!==p&&p(t.extensions[f],r,e)}return r.update(),r},jx=new Ft,qx=new wt,Yx=function(t,e){var i=new hh;if(t.hasOwnProperty("name")&&t.name.length>0?i.name=t.name:i.name="node_"+e,t.hasOwnProperty("matrix")&&(jx.data.set(t.matrix),jx.getTranslation(qx),i.setLocalPosition(qx),jx.getEulerAngles(qx),i.setLocalEulerAngles(qx),jx.getScale(qx),i.setLocalScale(qx)),t.hasOwnProperty("rotation")){var n=t.rotation;i.setLocalRotation(n[0],n[1],n[2],n[3])}if(t.hasOwnProperty("translation")){var s=t.translation;i.setLocalPosition(s[0],s[1],s[2])}if(t.hasOwnProperty("scale")){var r=t.scale;i.setLocalScale(r[0],r[1],r[2])}return i},Kx=function(t,e){var i="orthographic"===t.type?1:0,n=1===i?t.orthographic:t.perspective,s={enabled:!1,projection:i,nearClip:n.znear,aspectRatioMode:0};n.zfar&&(s.farClip=n.zfar),1===i?(s.orthoHeight=.5*n.ymag,n.ymag&&(s.aspectRatioMode=1,s.aspectRatio=n.xmag/n.ymag)):(s.fov=n.yfov*_t.RAD_TO_DEG,n.aspectRatio&&(s.aspectRatioMode=1,s.aspectRatio=n.aspectRatio));var r=new ip(t.name);return r.addComponent("camera",s),r},Zx=function(t,e){var i={enabled:!1,type:"point"===t.type?"omni":t.type,color:t.hasOwnProperty("color")?new vt(t.color):vt.WHITE,range:t.hasOwnProperty("range")?t.range:9999,falloffMode:1,intensity:t.hasOwnProperty("intensity")?_t.clamp(t.intensity,0,2):1};t.hasOwnProperty("spot")&&(i.innerConeAngle=t.spot.hasOwnProperty("innerConeAngle")?t.spot.innerConeAngle*_t.RAD_TO_DEG:0,i.outerConeAngle=t.spot.hasOwnProperty("outerConeAngle")?t.spot.outerConeAngle*_t.RAD_TO_DEG:Math.PI/4),t.hasOwnProperty("intensity")&&(i.luminance=t.intensity*Uu.getLightUnitConversion(Ou[i.type],i.outerConeAngle,i.innerConeAngle));var n=new ip(e.name);return n.rotateLocal(90,0,0),n.addComponent("light",i),n},Qx=function(t,e,i,n){if(!e.hasOwnProperty("skins")||0===e.skins.length)return[];var s=new Map;return e.skins.map((function(r){return function(t,e,i,n,s,r){var a,o,h,l=e.joints,c=l.length,u=[];if(e.hasOwnProperty("inverseBindMatrices")){var d=e.inverseBindMatrices,f=Ax(i[d],n,!0),p=[];for(a=0;a<c;a++){for(o=0;o<16;o++)p[o]=f[16*a+o];(h=new Ft).set(p),u.push(h)}}else for(a=0;a<c;a++)h=new Ft,u.push(h);var m=[];for(a=0;a<c;a++)m[a]=s[l[a]].name;var _=m.join("#"),v=r.get(_);return v||(v=new Kd(t,u,m),r.set(_,v)),v}(t,r,e.accessors,n,i,s)}))},$x=function(t,e,i,n,s){var r,a,o,h={},l={},c={},u=[];return{meshes:!s.skipMeshes&&(null==e||null==(r=e.meshes)?void 0:r.length)&&(null==e||null==(a=e.accessors)?void 0:a.length)&&(null==e||null==(o=e.bufferViews)?void 0:o.length)?e.meshes.map((function(r){return Dx(t,r,e.accessors,i,n,h,l,c,s,u)})):[],meshVariants:l,meshDefaultMaterials:c,promises:u}},Jx=function(t,e,i,n){var s,r,a,o;if(!t.hasOwnProperty("materials")||0===t.materials.length)return[];var h=null==i||null==(s=i.material)?void 0:s.preprocess,l=null!=(r=null==i||null==(a=i.material)?void 0:a.process)?r:Xx,c=null==i||null==(o=i.material)?void 0:o.postprocess;return t.materials.map((function(t){h&&h(t);var i=l(t,e,n);return c&&c(t,i),i}))},tS=function(t){if(!t.hasOwnProperty("extensions")||!t.extensions.hasOwnProperty("KHR_materials_variants"))return null;for(var e=t.extensions.KHR_materials_variants.variants,i={},n=0;n<e.length;n++)i[e[n].name]=n;return i},eS=function(t,e,i,n){var s,r;if(!t.hasOwnProperty("animations")||0===t.animations.length)return[];var a=null==n||null==(s=n.animation)?void 0:s.preprocess,o=null==n||null==(r=n.animation)?void 0:r.postprocess;return t.animations.map((function(n,s){a&&a(n);var r=function(t,e,i,n,s,r,a){var o,h=function(t){return new hx(yx(t.type),Cx(t,n))},l={STEP:0,LINEAR:1,CUBICSPLINE:2},c={},u={},d={},f=1;for(o=0;o<t.samplers.length;++o){var p=t.samplers[o];c.hasOwnProperty(p.input)||(c[p.input]=h(i[p.input])),u.hasOwnProperty(p.output)||(u[p.output]=h(i[p.output]));var m=p.hasOwnProperty("interpolation")&&l.hasOwnProperty(p.interpolation)?l[p.interpolation]:1,_={paths:[],input:p.input,output:p.output,interpolation:m};d[o]=_}var v=[],g={translation:"localPosition",rotation:"localRotation",scale:"localScale"},y=function(t){for(var e=[];t;)e.unshift(t.name),t=t.parent;return e},x=function(t,e,i){var n=u[t.output];if(n){var s;if(r&&r[e.mesh]){var a=r[e.mesh];a.hasOwnProperty("extras")&&a.extras.hasOwnProperty("targetNames")&&(s=a.extras.targetNames)}for(var h=n.data,l=h.length/c[t.input].data.length,p=h.length/l,m=4*p,_=new ArrayBuffer(m*l),v=0;v<l;v++){for(var g,y=new Float32Array(_,m*v,p),x=0;x<p;x++)y[x]=h[x*l+v];var S=new hx(1,y),b=null!=(g=s)&&g[v]?"name."+s[v]:v;u[-f]=S;var w={paths:[{entityPath:i,component:"graph",propertyPath:["weight."+b]}],input:t.input,output:-f,interpolation:t.interpolation};f++,d["morphCurve-"+o+"-"+v]=w}}};for(o=0;o<t.channels.length;++o){var S=t.channels[o],b=S.target,w=d[S.sampler],T=s[b.node],A=a[b.node],C=y(T);b.path.startsWith("weights")?(x(w,A,C),d[S.sampler].morphCurve=!0):w.paths.push({entityPath:C,component:"graph",propertyPath:[g[b.path]]})}var E=[],M=[],P=[];for(var R in c)E.push(c[R]),c[R]=E.length-1;for(var I in u)M.push(u[I]),u[I]=M.length-1;for(var L in d){var D=d[L];D.morphCurve||(P.push(new ox(D.paths,c[D.input],u[D.output],D.interpolation)),D.paths.length>0&&"localRotation"===D.paths[0].propertyPath[0]&&2!==D.interpolation&&v.push(P[P.length-1].output))}v.sort();var O,k=null;for(o=0;o<v.length;++o){var F=v[o];if(0===o||F!==k){if(4===(O=M[F]).components)for(var B=O.data,U=B.length-4,N=0;N<U;N+=4)B[N+0]*B[N+4]+B[N+1]*B[N+5]+B[N+2]*B[N+6]+B[N+3]*B[N+7]<0&&(B[N+4]*=-1,B[N+5]*=-1,B[N+6]*=-1,B[N+7]*=-1);k=F}}var z=0;for(o=0;o<E.length;o++)O=E[o]._data,z=Math.max(z,0===O.length?0:O[O.length-1]);return new nm(t.hasOwnProperty("name")?t.name:"animation_"+e,z,E,M,P)}(n,s,t.accessors,i,e,t.meshes,t.nodes);return o&&o(n,r),r}))},iS=function(t,e){var i,n,s,r;if(!t.hasOwnProperty("nodes")||0===t.nodes.length)return[];for(var a=null==e||null==(i=e.node)?void 0:i.preprocess,o=null!=(n=null==e||null==(s=e.node)?void 0:s.process)?n:Yx,h=null==e||null==(r=e.node)?void 0:r.postprocess,l=t.nodes.map((function(t,e){a&&a(t);var i=o(t,e);return h&&h(t,i),i})),c=0;c<t.nodes.length;++c){var u=t.nodes[c];if(u.hasOwnProperty("children"))for(var d=l[c],f={},p=0;p<u.children.length;++p){var m=l[u.children[p]];m.parent||(f.hasOwnProperty(m.name)?m.name+=f[m.name]++:f[m.name]=1,d.addChild(m))}}return l},nS=function(t,e){var i,n=[],s=t.scenes.length;if(1===s&&1===(null==(i=t.scenes[0].nodes)?void 0:i.length)){var r=t.scenes[0].nodes[0];n.push(e[r])}else for(var a=0;a<s;a++){var o=t.scenes[a];if(o.nodes){for(var h=new hh(o.name),l=0;l<o.nodes.length;l++){var c=e[o.nodes[l]];h.addChild(c)}n.push(h)}}return n},sS=function(t,e,i){var n=null;if(t.hasOwnProperty("nodes")&&t.hasOwnProperty("cameras")&&t.cameras.length>0){var s,r,a,o,h=null==i||null==(s=i.camera)?void 0:s.preprocess,l=null!=(r=null==i||null==(a=i.camera)?void 0:a.process)?r:Kx,c=null==i||null==(o=i.camera)?void 0:o.postprocess;t.nodes.forEach((function(i,s){if(i.hasOwnProperty("camera")){var r=t.cameras[i.camera];if(r){h&&h(r);var a=l(r,e[s]);c&&c(r,a),a&&(n||(n=new Map),n.set(i,a))}}}))}return n},rS=function(t,e,i){var n=null;if(t.hasOwnProperty("nodes")&&t.hasOwnProperty("extensions")&&t.extensions.hasOwnProperty("KHR_lights_punctual")&&t.extensions.KHR_lights_punctual.hasOwnProperty("lights")){var s=t.extensions.KHR_lights_punctual.lights;if(s.length){var r,a,o,h,l=null==i||null==(r=i.light)?void 0:r.preprocess,c=null!=(a=null==i||null==(o=i.light)?void 0:o.process)?a:Zx,u=null==i||null==(h=i.light)?void 0:h.postprocess;t.nodes.forEach((function(t,i){if(t.hasOwnProperty("extensions")&&t.extensions.hasOwnProperty("KHR_lights_punctual")&&t.extensions.KHR_lights_punctual.hasOwnProperty("light")){var r=t.extensions.KHR_lights_punctual.light,a=s[r];if(a){l&&l(a);var o=c(a,e[i]);u&&u(a,o),o&&(n||(n=new Map),n.set(t,o))}}}))}}return n},aS=function(t,e,i){t.nodes.forEach((function(t){t.hasOwnProperty("mesh")&&t.hasOwnProperty("skin")&&e[t.mesh].meshes.forEach((function(e){e.skin=i[t.skin]}))}))},oS=(fx=v(m().mark((function t(e,i,n,s,r){var a,o,h,l,c,u,d,f,p,_,v,g,y,x,S,b,w,T,A,C,E,M,P,R;return m().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return h=null==r||null==(a=r.global)?void 0:a.preprocess,l=null==r||null==(o=r.global)?void 0:o.postprocess,h&&h(i),c=i.asset&&"PlayCanvas"===i.asset.generator,u=iS(i,r),d=nS(i,u),f=rS(i,u,r),p=sS(i,u,r),_=tS(i),t.next=12,Promise.all(n);case 12:return v=t.sent,g=$x(e,i,v,c,r),y=g.meshes,x=g.meshVariants,S=g.meshDefaultMaterials,b=g.promises,w=eS(i,u,v,r),t.next=17,Promise.all(s);case 17:for(T=t.sent,A=T.map((function(t){return t.resource})),C=Jx(i,A,r,c),E=Qx(e,i,u,v),M=[],P=0;P<y.length;P++)M[P]=new ix,M[P].meshes=y[P];return aS(i,M,E),(R=new vx).gltf=i,R.nodes=u,R.scenes=d,R.animations=w,R.textures=T,R.materials=C,R.variants=_,R.meshVariants=x,R.meshDefaultMaterials=S,R.renders=M,R.skins=E,R.lights=f,R.cameras=p,l&&l(i,R),t.next=41,Promise.all(b);case 41:return t.abrupt("return",R);case 42:case"end":return t.stop()}}),t)}))),function(t,e,i,n,s){return fx.apply(this,arguments)}),hS=0,lS=function(t,e,i){var n;t&&t.toLowerCase().endsWith(".glb")||103===(n=new Uint8Array(e))[0]&&108===n[1]&&84===n[2]&&70===n[3]?function(t,e){var i=t instanceof ArrayBuffer?new DataView(t):new DataView(t.buffer,t.byteOffset,t.byteLength),n=i.getUint32(0,!0),s=i.getUint32(4,!0),r=i.getUint32(8,!0);if(1179937895===n)if(2===s)if(r<=0||r>i.byteLength)e("Invalid length found in glb header. Found "+r);else{for(var a=[],o=12;o<r;){var h=i.getUint32(o,!0);o+h+8>i.byteLength&&e("Invalid chunk length found in glb. Found "+h);var l=i.getUint32(o+4,!0),c=new Uint8Array(i.buffer,i.byteOffset+o+8,h);a.push({length:h,type:l,data:c}),o+=h+8}1===a.length||2===a.length?1313821514===a[0].type?a.length>1&&5130562!==a[1].type?e("Invalid chunk type found in glb file. Expected 0x004E4942, found 0x"+a[1].type.toString(16)):e(null,{gltfChunk:a[0].data,binaryChunk:2===a.length?a[1].data:null}):e("Invalid chunk type found in glb file. Expected 0x4E4F534A, found 0x"+a[0].type.toString(16)):e("Invalid number of chunks found in glb file.")}else e("Invalid version number found in glb header. Expected 2, found "+s);else e("Invalid magic number found in glb header. Expected 0x46546C67, found 0x"+n.toString(16))}(e,i):i(null,{gltfChunk:e,binaryChunk:null})},cS=function(){function t(){}return t.parse=function(t,e,i,n,s,r,a){lS(t,i,(function(t,i){t?a(t):function(t,e){var i=JSON.parse(function(t){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(t);for(var e="",i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return decodeURIComponent(escape(e))}(t));i.asset&&i.asset.version&&parseFloat(i.asset.version)<2?e("Invalid gltf version. Expected version 2.0 or above but found version '"+i.asset.version+"'."):e(null,i)}(i.gltfChunk,(function(t,o){if(t)a(t);else{var h=function(t,e,i,n){var s,r,a;if(!t.buffers||0===t.buffers.length)return[];var o=null==n||null==(s=n.buffer)?void 0:s.preprocess,h=null==n||null==(r=n.buffer)?void 0:r.processAsync,l=null==n||null==(a=n.buffer)?void 0:a.postprocess;return t.buffers.map((function(n,s){var r;return o&&o(n),r=(r=new Promise(h?function(t,e){h(n,(function(i,n){i?e(i):t(n)}))}:function(t){t(null)})).then((function(t){if(t)return t;if(n.hasOwnProperty("uri")){if(gx(n.uri)){for(var s=atob(n.uri.split(",")[1]),r=new Uint8Array(s.length),a=0;a<s.length;a++)r[a]=s.charCodeAt(a);return r}return new Promise((function(t,e){_a.get(Ff.test(n.uri)?n.uri:L.join(i,n.uri),{cache:!0,responseType:"arraybuffer",retry:!1},(function(i,n){i?e(i):t(new Uint8Array(n))}))}))}return e})),l&&(r=r.then((function(e){return l(t.buffers[s],e),e}))),r}))}(o,i.binaryChunk,e,r),l=function(t,e,i){var n,s,r,a,o=[],h=null==i||null==(n=i.bufferView)?void 0:n.preprocess,l=null==i||null==(s=i.bufferView)?void 0:s.processAsync,c=null==i||null==(r=i.bufferView)?void 0:r.postprocess;if(null==(a=t.bufferViews)||!a.length)return o;for(var u=function(){var i,n=t.bufferViews[d];h&&h(n),i=new Promise(l?function(t,i){l(n,e,(function(e,n){e?i(e):t(n)}))}:function(t){t(null)}),i=i.then((function(t){return t||e[n.buffer].then((function(t){return new Uint8Array(t.buffer,t.byteOffset+(n.byteOffset||0),n.byteLength)}))})),n.hasOwnProperty("byteStride")&&(i=i.then((function(t){return t.byteStride=n.byteStride,t}))),c&&(i=i.then((function(t){return c(n,t),t}))),o.push(i)},d=0;d<t.bufferViews.length;++d)u();return o}(o,h,r),c=function(t,e,i,n,s){var r,a,o;if(!t.images||0===t.images.length)return[];var h=null==s||null==(r=s.image)?void 0:r.preprocess,l=null==s||null==(a=s.image)?void 0:a.processAsync,c=null==s||null==(o=s.image)?void 0:o.postprocess,u={"image/png":"png","image/jpeg":"jpg","image/basis":"basis","image/ktx":"ktx","image/ktx2":"ktx2","image/vnd-ms.dds":"dds"},d=function(t,e,i,s,r){return new Promise((function(a,o){var h=function(i){var h=(t.name||"gltf-texture")+"-"+hS++,l={url:e||h};if(i&&(l.contents=i.slice(0).buffer),s){var c=u[s];c&&(l.filename=l.url+"."+c)}var d=new Vf(h,"texture",l,null,r);d.on("load",(function(t){return a(t)})),d.on("error",(function(t){return o(t)})),n.add(d),n.load(d)};i?i.then((function(t){return h(t)})):h(null)}))};return t.images.map((function(t,n){var s;return h&&h(t),s=(s=new Promise(l?function(e,i){l(t,(function(t,n){t?i(t):e(n)}))}:function(t){t(null)})).then((function(s){return s||(t.hasOwnProperty("uri")?gx(t.uri)?d(t,t.uri,null,(r=t.uri).substring(r.indexOf(":")+1,r.indexOf(";")),null):d(t,Ff.test(t.uri)?t.uri:L.join(i,t.uri),null,null,{crossOrigin:"anonymous"}):t.hasOwnProperty("bufferView")&&t.hasOwnProperty("mimeType")?d(t,null,e[t.bufferView],t.mimeType,null):Promise.reject(new Error("Invalid image found in gltf (neither uri or bufferView found). index="+n)));var r})),c&&(s=s.then((function(e){return c(t,e),e}))),s}))}(o,l,e,s,r),u=function(t,e,i){var n,s,r,a,o;if(null==t||null==(n=t.images)||!n.length||null==t||null==(s=t.textures)||!s.length)return[];var h=null==i||null==(r=i.texture)?void 0:r.preprocess,l=null==i||null==(a=i.texture)?void 0:a.processAsync,c=null==i||null==(o=i.texture)?void 0:o.postprocess,u=new Set;return t.textures.map((function(i){var n;return h&&h(i),n=(n=new Promise(l?function(e,n){l(i,t.images,(function(t,i){t?n(t):e(i)}))}:function(t){t(null)})).then((function(n){var s,r,a,o,h;n=null!=(s=null!=(r=null!=(a=n)?a:null==i||null==(o=i.extensions)||null==(o=o.KHR_texture_basisu)?void 0:o.source)?r:null==i||null==(h=i.extensions)||null==(h=h.EXT_texture_webp)?void 0:h.source)?s:i.source;var l=u.has(n);return u.add(n),e[n].then((function(e){var n,s,r,a,o,h,c=l?Rx(e):e;return s=c.resource,r=(null!=(n=t.samplers)?n:[])[i.sampler],o=function(t,e){switch(t){case 9728:return 0;case 9729:return 1;case 9984:return 2;case 9985:return 4;case 9986:return 3;case 9987:return 5;default:return e}},h=function(t,e){switch(t){case 33071:return 1;case 33648:return 2;case 10497:return 0;default:return e}},s&&(r=null!=(a=r)?a:{},s.minFilter=o(r.minFilter,5),s.magFilter=o(r.magFilter,1),s.addressU=h(r.wrapS,0),s.addressV=h(r.wrapT,0)),c}))})),c&&(n=n.then((function(t){return c(i,t),t}))),n}))}(o,c,r);oS(n,o,l,u,r).then((function(t){return a(null,t)})).catch((function(t){return a(t)}))}}))}))},t.createDefaultMaterial=function(){return Xx({name:"defaultGlbMaterial"},[])},t}(),uS=function(){function t(t){this.handlerType="animation",this.device=t.graphicsDevice,this.assets=t.assets,this.maxRetries=0}var e=t.prototype;return e.load=function(t,e,i){var n=this;"string"==typeof t&&(t={load:t,original:t});var s={retry:this.maxRetries>0,maxRetries:this.maxRetries};(t.load.startsWith("blob:")||t.load.startsWith("data:"))&&(".glb"===L.getExtension(t.original).toLowerCase()?s.responseType=ma.ResponseType.ARRAY_BUFFER:s.responseType=ma.ResponseType.JSON),_a.get(t.load,s,(function(s,r){var a;s?e("Error loading animation resource: "+t.original+" ["+s+"]"):".glb"===L.getExtension(t.original).toLowerCase()?cS.parse("filename.glb","",r,n.device,n.assets,null!=(a=null==i?void 0:i.options)?a:{},(function(t,n){if(t)e(t);else{var s,r=n.animations;if(null!=i&&null!=(s=i.data)&&s.events)for(var a=0;a<r.length;a++)r[a].events=new im(Object.values(i.data.events));n.destroy(),e(null,r)}})):e(null,n["_parseAnimationV"+r.animation.version](r))}))},e.open=function(t,e,i){return e},e.patch=function(t,e){},e._parseAnimationV3=function(t){var e=t.animation,i=new nf;i.name=e.name,i.duration=e.duration;for(var n=0;n<e.nodes.length;n++){var s=new ef,r=e.nodes[n];s._name=r.name;for(var a=0;a<r.keys.length;a++){var o=r.keys[a],h=o.time,l=o.pos,c=o.rot,u=o.scale,d=new wt(l[0],l[1],l[2]),f=(new Bt).setFromEulerAngles(c[0],c[1],c[2]),p=new wt(u[0],u[1],u[2]),m=new tf(h,d,f,p);s._keys.push(m)}i.addNode(s)}return i},e._parseAnimationV4=function(t){var e=t.animation,i=new nf;i.name=e.name,i.duration=e.duration;for(var n=0;n<e.nodes.length;n++){var s=new ef,r=e.nodes[n];s._name=r.name;for(var a=r.defaults.p,o=r.defaults.r,h=r.defaults.s,l=0;l<r.keys.length;l++){var c=r.keys[l],u=c.t,d=a||c.p,f=o||c.r,p=h||c.s,m=new wt(d[0],d[1],d[2]),_=(new Bt).setFromEulerAngles(f[0],f[1],f[2]),v=new wt(p[0],p[1],p[2]),g=new tf(u,m,_,v);s._keys.push(g)}i.addNode(s)}return i},t}(),dS=function(){function t(t){this.handlerType="animclip",this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};t.load.startsWith("blob:")&&(i.responseType=ma.ResponseType.JSON),_a.get(t.load,i,(function(i,n){i?e("Error loading animation clip resource: "+t.original+" ["+i+"]"):e(null,n)}))},e.open=function(t,e){var i=e.name,n=e.duration,s=e.inputs.map((function(t){return new hx(1,t)})),r=e.outputs.map((function(t){return new hx(t.components,t.data)})),a=e.curves.map((function(t){return new ox([t.path],t.inputIndex,t.outputIndex,t.interpolation)}));return new nm(i,n,s,r,a)},e.patch=function(t,e){},t}(),fS=function(){function t(t){this.handlerType="animstategraph",this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};t.load.startsWith("blob:")&&(i.responseType=ma.ResponseType.JSON),_a.get(t.load,i,(function(i,n){i?e("Error loading animation state graph resource: "+t.original+" ["+i+"]"):e(null,n)}))},e.open=function(t,e){return new Em(e)},e.patch=function(t,e){},t}(),pS=function(){if("undefined"==typeof window)return!1;var t=window.navigator.userAgent,e=t.indexOf("MSIE ");if(e>0)return parseInt(t.substring(e+5,t.indexOf(".",e)),10);if(t.indexOf("Trident/")>0){var i=t.indexOf("rv:");return parseInt(t.substring(i+3,t.indexOf(".",i)),10)}return!1}(),mS=[".ogg",".mp3",".wav",".mp4a",".m4a",".mp4",".aac",".opus"],_S=function(){function t(t){this.handlerType="audio",this.manager=t.soundManager,this.maxRetries=0}var e=t.prototype;return e._isSupported=function(t){var e=L.getExtension(t);return mS.indexOf(e)>-1},e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t});var i=function(i){var n="Error loading audio url: "+t.original;i&&(n+=": "+(i.message||i)),console.warn(n),e(n)};if(this._createSound){if(!this._isSupported(t.original))return void i("Audio format for "+t.original+" not supported");this._createSound(t.load,(function(t){e(null,new Aa(t))}),i)}else i(null)},e.open=function(t,e){return e},e.patch=function(t,e){},e._createSound=function(t,e,i){if(va()){var n=this.manager;if(!n.context)return void i("Audio manager has no audio context");var s={retry:this.maxRetries>0,maxRetries:this.maxRetries};(t.startsWith("blob:")||t.startsWith("data:"))&&(s.responseType=ma.ResponseType.ARRAY_BUFFER),_a.get(t,s,(function(t,s){t?i(t):n.context.decodeAudioData(s,e,i)}))}else{var r=null;try{r=new Audio}catch(t){return void i("No support for Audio element")}pS&&document.body.appendChild(r);r.onerror=function(){r.onerror=null,pS&&document.body.removeChild(r),i()},r.addEventListener("canplaythrough",(function t(){r.removeEventListener("canplaythrough",t),pS&&document.body.removeChild(r),e(r)})),r.src=t}},t}(),vS=function(){function t(t){this.handlerType="binary",this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t}),_a.get(t.load,{responseType:ma.ResponseType.ARRAY_BUFFER,retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?e("Error loading binary resource: "+t.original+" ["+i+"]"):e(null,n)}))},e.open=function(t,e){return e},e.patch=function(t,e){},t}(),gS=function(){function t(e,i,n,s){for(var r=function(e,s,r){var a=t.createAsset(i.name,e,s,r);return n.add(a),a},a=[],o=0;o<e.renders.length;++o)a.push(r("render",e.renders[o],o));for(var h=[],l=0;l<e.materials.length;++l)h.push(r("material",e.materials[l],l));for(var c=[],u=0;u<e.animations.length;++u)c.push(r("animation",e.animations[u],u));this.data=e,this._model=null,this._assetName=i.name,this._assets=n,this._defaultMaterial=s,this.renders=a,this.materials=h,this.textures=e.textures,this.animations=c}t.createAsset=function(t,e,i,n){var s=new Vf(t+"/"+e+"/"+n,e,{url:""});return s.resource=i,s.loaded=!0,s};var e=t.prototype;return e.instantiateModelEntity=function(t){var e=new ip;return e.addComponent("model",Object.assign({type:"asset",asset:this.model},t)),e},e.instantiateRenderEntity=function(e){for(var i,n=this,s=this._defaultMaterial,r=[],a=function(t,e,i,n,a,o,h){var l=a[i.id],c=void 0===l?s:n[l],u=new yh(i,c);return i.morph&&(u.morphInstance=new Vu(i.morph)),h.hasOwnProperty("skin")&&r.push({meshInstance:u,rootBone:t,entity:e}),u},o=function t(i,s,r){var o=new ip;s._cloneInternal(o),i||(i=o);for(var h=null,l=null,c=0;c<r.nodes.length;c++){if(r.nodes[c]===s){var u=r.gltf.nodes[c];if(u.hasOwnProperty("mesh")){var d=r.renders[u.mesh].meshes;l=n.renders[u.mesh];for(var f=0;f<d.length;f++){var p=d[f];if(p){var m=a(i,o,p,r.materials,r.meshDefaultMaterials,r.skins,u);h||(h=[]),h.push(m)}}}if(r.lights){var _=r.lights.get(u);_&&o.addChild(_.clone())}if(r.cameras){var v=r.cameras.get(u);v&&v.camera.system.cloneComponent(v,o)}}}h&&(o.addComponent("render",Object.assign({type:"asset",meshInstances:h,rootBone:i},e)),o.render.assignAsset(l));for(var g=s.children,y=0;y<g.length;y++){var x=t(i,g[y],r);o.addChild(x)}return o},h=[],l=A(this.data.scenes);!(i=l()).done;){var c=i.value;h.push(o(null,c,this.data))}return r.forEach((function(t){t.meshInstance.skinInstance=og.createCachedSkinInstance(t.meshInstance.mesh.skin,t.rootBone,t.entity)})),t.createSceneHierarchy(h,"Entity")},e.getMaterialVariants=function(){return this.data.variants?Object.keys(this.data.variants):[]},e.applyMaterialVariant=function(t,e){var i=e?this.data.variants[e]:null;if(void 0!==i)for(var n=t.findComponents("render"),s=0;s<n.length;s++){var r=n[s];this._applyMaterialVariant(i,r.meshInstances)}},e.applyMaterialVariantInstances=function(t,e){var i=e?this.data.variants[e]:null;void 0!==i&&this._applyMaterialVariant(i,t)},e._applyMaterialVariant=function(t,e){var i=this;e.forEach((function(e){if(null===t)e.material=i._defaultMaterial;else{var n=i.data.meshVariants[e.mesh.id];n&&(e.material=i.data.materials[n[t]])}}))},t.createSceneHierarchy=function(t,e){var i=null;if(1===t.length)i=t[0];else{i=new e("SceneGroup");for(var n,s=A(t);!(n=s()).done;){var r=n.value;i.addChild(r)}}return i},t.createModel=function(e,i){for(var n,s=function(t,n,s,r,a,o,h){var l=e.meshDefaultMaterials[n.id],c=void 0===l?i:a[l],u=new yh(n,c,o);if(n.morph){var d=new Vu(n.morph);u.morphInstance=d,t.morphInstances.push(d)}if(h.hasOwnProperty("skin")){var f=h.skin,p=s[f];n.skin=p;var m=r[f];u.skinInstance=m,t.skinInstances.push(m)}t.meshInstances.push(u)},r=new Gu,a=[],o=A(e.skins);!(n=o()).done;){var h=n.value,l=new Xo(h);l.bones=h.bones,a.push(l)}r.graph=t.createSceneHierarchy(e.scenes,"GraphNode");for(var c=0;c<e.nodes.length;c++){var u=e.nodes[c];if(u.root===r.graph){var d=e.gltf.nodes[c];if(d.hasOwnProperty("mesh"))for(var f=e.renders[d.mesh].meshes,p=0;p<f.length;p++){var m=f[p];m&&s(r,m,e.skins,a,e.materials,u,d)}}}return r},e.destroy=function(){var t=this._assets,e=function(e){t.remove(e),e.unload()},i=function(t){t.forEach((function(t){e(t)}))};this.animations&&(i(this.animations),this.animations=null),this.textures&&(i(this.textures),this.textures=null),this.materials&&(i(this.materials),this.materials=null),this.renders&&(i(this.renders),this.renders=null),this._model&&(e(this._model),this._model=null),this.data=null,this.assets=null},y(t,[{key:"model",get:function(){if(!this._model){var e=t.createModel(this.data,this._defaultMaterial),i=t.createAsset(this._assetName,"model",e,0);this._assets.add(i),this._model=i}return this._model}}]),t}(),yS=function(){function t(t,e,i){this._device=t,this._assets=e,this._defaultMaterial=cS.createDefaultMaterial(),this.maxRetries=i}var e=t.prototype;return e._getUrlWithoutParams=function(t){return t.indexOf("?")>=0?t.split("?")[0]:t},e.load=function(t,e,i){var n=this;Vf.fetchArrayBuffer(t.load,(function(s,r){s?e(s):cS.parse(n._getUrlWithoutParams(t.original),L.extractPath(t.load),r,n._device,i.registry,i.options,(function(t,s){t?e(t):e(null,new gS(s,i,n._assets,n._defaultMaterial))}))}),i,this.maxRetries)},e.open=function(t,e,i){return e},e.patch=function(t,e){},t}(),xS=function(){function t(){}var e=t.prototype;return e.instantiateModelEntity=function(t){return null},e.instantiateRenderEntity=function(t){return null},e.getMaterialVariants=function(){return null},e.applyMaterialVariant=function(t,e){},e.applyMaterialVariantInstances=function(t,e){},t}(),SS=function(){function t(t){this.handlerType="container",this.glbContainerParser=new yS(t.graphicsDevice,t.assets,0),this.parsers={}}var e=t.prototype;return e._getUrlWithoutParams=function(t){return t.indexOf("?")>=0?t.split("?")[0]:t},e._getParser=function(t){var e=t?L.getExtension(this._getUrlWithoutParams(t)).toLowerCase().replace(".",""):null;return this.parsers[e]||this.glbContainerParser},e.load=function(t,e,i){"string"==typeof t&&(t={load:t,original:t}),this._getParser(t.original).load(t,e,i)},e.open=function(t,e,i){return this._getParser(t).open(t,e,i)},e.patch=function(t,e){},y(t,[{key:"maxRetries",get:function(){return this.glbContainerParser.maxRetries},set:function(t){for(var e in this.glbContainerParser.maxRetries=t,this.parsers)this.parsers.hasOwnProperty(e)&&(this.parsers[e].maxRetries=t)}}]),t}(),bS=function(){function t(t){this.handlerType="css",this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t}),_a.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?e("Error loading css resource: "+t.original+" ["+i+"]"):e(null,n)}))},e.open=function(t,e){return e},e.patch=function(t,e){},t}(),wS=function(){function t(t){this.handlerType="cubemap",this._device=t.graphicsDevice,this._registry=t.assets,this._loader=t.loader}var e=t.prototype;return e.load=function(t,e,i){this.loadAssets(i,e)},e.open=function(t,e,i){return i?i.resource:null},e.patch=function(t,e){this.loadAssets(t,(function(i,n){i&&(e.fire("error",t),e.fire("error:"+t.id,i,t),t.fire("error",t))}))},e.getAssetIds=function(t){var e=[];if(e[0]=t.file,(t.loadFaces||!t.file)&&t.data&&t.data.textures)for(var i=0;i<6;++i)e[i+1]=t.data.textures[i];else e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=null;return e},e.compareAssetIds=function(t,e){return t&&e?parseInt(t,10)===t||"string"==typeof t?t===e:t.url===e.url:null!==t==(null!==e)},e.update=function(t,e,i){var n,s,r,a=t.data||{},o=t._handlerState.assets,h=t._resources,l=[null,null,null,null,null,null,null],c=function(){return a.hasOwnProperty("type")?a.type:a.hasOwnProperty("rgbm")?a.rgbm?ii:ei:null};if(t.loaded&&i[0]===o[0])l[1]=h[1]||null,l[2]=h[2]||null,l[3]=h[3]||null,l[4]=h[4]||null,l[5]=h[5]||null,l[6]=h[6]||null;else if(i[0])if((n=i[0].resource).cubemap)for(r=0;r<6;++r)l[r+1]=new Ls(this._device,{name:t.name+"_prelitCubemap"+(n.width>>r),cubemap:!0,type:c()||n.type,width:n.width>>r,height:n.height>>r,format:n.format,levels:[n._levels[r]],fixCubemapSeams:!0,addressU:1,addressV:1,mipmaps:0===r});else n.type=si,n.addressU=1,n.addressV=1,n.mipmaps=!1,l[1]=n;var u=i.slice(1);if(t.loaded&&this.cmpArrays(u,o.slice(1)))l[0]=h[0]||null;else if(-1===u.indexOf(null)){var d,f=u.map((function(t){return t.resource})),p=[];for(s=0;s<f[0]._levels.length;++s)p.push(f.map((function(t){return t._levels[s]})));var m=f[0].format,_=new Ls(this._device,{name:t.name+"_faces",cubemap:!0,type:c()||f[0].type,width:f[0].width,height:f[0].height,format:6===m?7:m,mipmaps:null==(d=a.mipmaps)||d,levels:p,minFilter:a.hasOwnProperty("minFilter")?a.minFilter:f[0].minFilter,magFilter:a.hasOwnProperty("magFilter")?a.magFilter:f[0].magFilter,anisotropy:a.hasOwnProperty("anisotropy")?a.anisotropy:1,addressU:1,addressV:1,fixCubemapSeams:!!i[0]});l[0]=_}if(!this.cmpArrays(l,h))for(t.resources=l,t._handlerState.assetIds=e,t._handlerState.assets=i,r=0;r<h.length;++r)null!==h[r]&&-1===l.indexOf(h[r])&&h[r].destroy();for(r=0;r<o.length;++r)null!==o[r]&&-1===i.indexOf(o[r])&&o[r].unload()},e.cmpArrays=function(t,e){if(t.length!==e.length)return!1;for(var i=0;i<t.length;++i)if(t[i]!==e[i])return!1;return!0},e.resolveId=function(t){var e=parseInt(t,10);return e===t||e.toString()===t?e:t},e.loadAssets=function(t,e){t.hasOwnProperty("_handlerState")||(t._handlerState={assetIds:[null,null,null,null,null,null,null],assets:[null,null,null,null,null,null,null]});for(var i,n=this,s=n.getAssetIds(t),r=[null,null,null,null,null,null,null],a=t._handlerState.assetIds,o=t._handlerState.assets,h=n._registry,l=7,c=function(i,a){r[i]=a,0===--l&&(n.update(t,s,r),e(null,t.resources))},u=function(t,i,n){e(i)},d=function(t,e){e.loaded?c(t,e):(h.once("load:"+e.id,c.bind(n,t)),h.once("error:"+e.id,u.bind(n,t)),e.loading||h.load(e))},f=0;f<7;++f){var p=this.resolveId(s[f]);if(p)if(n.compareAssetIds(p,a[f]))c(f,o[f]);else if(parseInt(p,10)===p)(i=h.get(p))?d(f,i):setTimeout(function(t,e){var i=h.get(e);i?d(t,i):u(0,"failed to find dependent cubemap asset="+e)}.bind(null,f,p));else{var m="string"==typeof p?{url:p,filename:p}:p;i=new Vf(t.name+"_part_"+f,"texture",m),h.add(i),h.once("load:"+i.id,c.bind(n,f)),h.once("error:"+i.id,u.bind(n,f)),h.load(i)}else c(f,null)}},t}(),TS=function(){function t(){this.handlerType="folder"}var e=t.prototype;return e.load=function(t,e){e(null,null)},e.open=function(t,e){return e},t}(),AS=function(){function t(t,e){this.type=e&&e.type||B_,this.em=1,this.textures=t,this.intensity=0,this._data=null,this.data=e}return y(t,[{key:"data",get:function(){return this._data},set:function(t){if(this._data=t,t&&(void 0!==this._data.intensity&&(this.intensity=this._data.intensity),this._data.info||(this._data.info={}),(!this._data.version||this._data.version<2)&&(this._data.info.maps=[{width:this._data.info.width,height:this._data.info.height}],this._data.chars)))for(var e in this._data.chars)this._data.chars[e].map=0}}]),t}();function CS(t){return t.version<3&&(t.version<2&&(t.info.maps=t.info.maps||[{width:t.info.width,height:t.info.height}]),t.chars=Object.keys(t.chars||{}).reduce((function(e,i){var n=t.chars[i],s=void 0!==n.letter?n.letter:rt.fromCodePoint(i);return t.version<2&&(n.map=n.map||0),e[s]=n,e}),{}),t.version=3),t}var ES=function(){function t(t){this.handlerType="font",this._loader=t.loader,this.maxRetries=0}var e=t.prototype;return e.load=function(t,e,i){"string"==typeof t&&(t={load:t,original:t});var n=this;".json"===L.getExtension(t.original)?_a.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,s){if(i)e("Error loading font resource: "+t.original+" ["+i+"]");else{var r=CS(s);n._loadTextures(t.load.replace(".json",".png"),r,(function(t,i){t?e(t):e(null,{data:r,textures:i})}))}})):(i&&i.data&&(i.data=CS(i.data)),this._loadTextures(t.load,i&&i.data,e))},e._loadTextures=function(t,e,i){for(var n=e.info.maps.length,s=0,r=null,a=new Array(n),o=this._loader,h=function(e){var h=function(t,o){if(!r){if(t)return r=t,void i(t);o.upload(),a[e]=o,++s===n&&i(null,a)}};0===e?o.load(t,"texture",h):o.load(t.replace(".png",e+".png"),"texture",h)},l=0;l<n;l++)h(l)},e.open=function(t,e,i){return e.textures?new AS(e.textures,e.data):new AS(e,null)},e.patch=function(t,e){var i=t.resource;!i.data&&t.data?i.data=t.data:!t.data&&i.data&&(t.data=i.data),t.data&&(t.data=CS(t.data))},t}(),MS=function(){function t(){}return t.setCompressedPRS=function(t,e,i){var n,s,r=i.singleVecs,a=e.___1;a||(n=i.tripleVecs,s=e.___2);var o=a?a[0]:n[s];t.setLocalPosition(r[o],r[o+1],r[o+2]),o=a?a[1]:n[s+1],t.setLocalEulerAngles(r[o],r[o+1],r[o+2]),o=a?a[2]:n[s+2],t.setLocalScale(r[o],r[o+1],r[o+2])},t.oneCharToKey=function(t,e){var i=t.charCodeAt(0)-e.fieldFirstCode;return e.fieldArray[i]},t.multCharToKey=function(t,e){for(var i=0,n=0;n<t.length;n++)i=i*e.fieldCodeBase+t.charCodeAt(n)-e.fieldFirstCode;return e.fieldArray[i]},t}(),PS=function(){function t(t,e){this._node=t,this._data=e}var e=t.prototype;return e.run=function(){var t=Object.prototype.toString.call(this._node);return"[object Object]"===t?this._handleMap():"[object Array]"===t?this._handleArray():this._result=this._node,this._result},e._handleMap=function(){this._result={},Object.keys(this._node).forEach(this._handleKey,this)},e._handleKey=function(e){var i=e,n=e.length;1===n?i=MS.oneCharToKey(e,this._data):2===n&&(i=MS.multCharToKey(e,this._data)),this._result[i]=new t(this._node[e],this._data).run()},e._handleArray=function(){this._result=[],this._node.forEach(this._handleArElt,this)},e._handleArElt=function(e){var i=new t(e,this._data).run();this._result.push(i)},t}(),RS=function(){function t(t,e){this._app=t,this._isTemplate=e}var e=t.prototype;return e.parse=function(t){var e={},i=null,n=t.compressedFormat;for(var s in n&&!t.entDecompressed&&(t.entDecompressed=!0,t.entities=new PS(t.entities,n).run()),t.entities){var r=t.entities[s],a=this._createEntity(r,n);e[s]=a,null===r.parent&&(i=a)}for(var o in t.entities)for(var h=e[o],l=t.entities[o].children,c=l.length,u=0;u<c;u++){var d=e[l[u]];d&&h.addChild(d)}return this._openComponentData(i,t.entities),i},e._createEntity=function(t,e){var i,n=new ip(t.name,this._app);if(n.setGuid(t.resource_id),this._setPosRotScale(n,t,e),n._enabled=null==(i=t.enabled)||i,this._isTemplate?n._template=!0:n._enabledInHierarchy=n._enabled,n.template=t.template,t.tags)for(var s=0;s<t.tags.length;s++)n.tags.add(t.tags[s]);return t.labels&&t.labels.forEach((function(t){n.addLabel(t)})),n},e._setPosRotScale=function(t,e,i){if(i)MS.setCompressedPRS(t,e,i);else{var n=e.position,s=e.rotation,r=e.scale;t.setLocalPosition(n[0],n[1],n[2]),t.setLocalEulerAngles(s[0],s[1],s[2]),t.setLocalScale(r[0],r[1],r[2])}},e._openComponentData=function(t,e){for(var i=this._app.systems.list,n=i.length,s=e[t.getGuid()],r=0;r<n;r++){var a=i[r],o=s.components[a.id];o&&a.addComponent(t,o)}n=s.children.length;for(var h=t._children,l=0;l<n;l++)h[l]&&(h[l]=this._openComponentData(h[l],e));return t},t}(),IS=function(){function t(){}return t.load=function(t,e,i){"string"==typeof t&&(t={load:t,original:t}),_a.get(t.load,{retry:e>0,maxRetries:e},(function(e,n){if(e){var s="Error while loading scene JSON "+t.original;e.message?(s+=": "+e.message,e.stack&&(s+="\n"+e.stack)):s+=": "+e,i(s)}else i(e,n)}))},t}(),LS=function(){function t(t){this.handlerType="hierarchy",this._app=t,this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){IS.load(t,this.maxRetries,e)},e.open=function(t,e){this._app.systems.script.preloading=!0;var i=new RS(this._app,!1).parse(e);return this._app.systems.script.preloading=!1,i},t}(),DS=function(){function t(t){this.handlerType="html",this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t}),_a.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?e("Error loading html resource: "+t.original+" ["+i+"]"):e(null,n)}))},e.open=function(t,e){return e},e.patch=function(t,e){},t}(),OS=function(){function t(t){this.handlerType="json",this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};t.load.startsWith("blob:")&&(i.responseType=ma.ResponseType.JSON),_a.get(t.load,i,(function(i,n){i?e("Error loading JSON resource: "+t.original+" ["+i+"]"):e(null,n)}))},e.open=function(t,e){return e},e.patch=function(t,e){},t}(),kS=function(){function t(){this.removeInvalid=!0,this.valid=!0,this.enumValidators={occludeSpecular:this._createEnumValidator([0,1,2]),cull:this._createEnumValidator([se,1,2,3]),blendType:this._createEnumValidator([0,1,2,3,4,5,6,7,8,9,10]),depthFunc:this._createEnumValidator([0,1,2,3,4,5,6,7]),shadingModel:this._createEnumValidator([0,1])}}var e=t.prototype;return e.setInvalid=function(t,e){this.valid=!1,this.removeInvalid&&delete e[t]},e.validate=function(t){var e=tu,i=ru,n="path"===t.mappingFormat;for(var s in t){var r=e[s];if(r)if(r.startsWith("enum")){var a=r.split(":")[1];this.enumValidators[a]&&(this.enumValidators[a](t[s])||this.setInvalid(s,t))}else if("number"===r)"number"!=typeof t[s]&&this.setInvalid(s,t);else if("boolean"===r)"boolean"!=typeof t[s]&&this.setInvalid(s,t);else if("string"===r)"string"!=typeof t[s]&&this.setInvalid(s,t);else if("vec2"===r)t[s]instanceof Array&&2===t[s].length||this.setInvalid(s,t);else if("rgb"===r)t[s]instanceof Array&&3===t[s].length||this.setInvalid(s,t);else if("texture"===r)n?"string"!=typeof t[s]&&null!==t[s]&&(t[s]instanceof Ls||this.setInvalid(s,t)):"number"!=typeof t[s]&&null!==t[s]&&(t[s]instanceof Ls||this.setInvalid(s,t));else if("boundingbox"===r)t[s].center&&t[s].center instanceof Array&&3===t[s].center.length||this.setInvalid(s,t),t[s].halfExtents&&t[s].halfExtents instanceof Array&&3===t[s].halfExtents.length||this.setInvalid(s,t);else if("cubemap"===r)"number"!=typeof t[s]&&null!==t[s]&&void 0!==t[s]&&(t[s]instanceof Ls&&t[s].cubemap||this.setInvalid(s,t));else if("chunks"===r)for(var o=Object.keys(t[s]),h=0;h<o.length;h++)"string"!=typeof t[s][o[h]]&&this.setInvalid(o[h],t[s]);else console.error("Unknown material type: "+r);else i[s]?delete t[s]:this.valid=!1}return t.validated=!0,this.valid},e._createEnumValidator=function(t){return function(e){return t.indexOf(e)>=0}},t}(),FS=function(){function t(){this._validator=null}var e=t.prototype;return e.parse=function(t){var e=this.migrate(t),i=this._validate(e),n=new lu;return this.initialize(n,i),n},e.initialize=function(t,e){for(var i in e.validated||(e=this._validate(e)),e.chunks&&(t.chunks=x({},e.chunks)),e){var n=tu[i],s=e[i];if("vec2"===n)t[i]=new Et(s[0],s[1]);else if("rgb"===n)t[i]=new vt(s[0],s[1],s[2]);else if("texture"===n)s instanceof Ls?t[i]=s:t[i]instanceof Ls&&"number"==typeof s&&s>0||(t[i]=null);else if("cubemap"===n)s instanceof Ls?t[i]=s:t[i]instanceof Ls&&"number"==typeof s&&s>0||(t[i]=null),"cubeMap"!==i||s||(t.prefilteredCubemaps=null);else if("boundingbox"===n){var r=new wt(s.center[0],s.center[1],s.center[2]),a=new wt(s.halfExtents[0],s.halfExtents[1],s.halfExtents[2]);t[i]=new Ht(r,a)}else t[i]=e[i]}t.update()},e.migrate=function(t){var e;void 0===t.shadingModel&&("blinn"===t.shader?t.shadingModel=1:t.shadingModel=0),t.shader&&delete t.shader,t.mapping_format&&(t.mappingFormat=t.mapping_format,delete t.mapping_format);var i=[["bumpMapFactor","bumpiness"],["aoUvSet","aoMapUv"],["aoMapVertexColor","aoVertexColor"],["diffuseMapVertexColor","diffuseVertexColor"],["emissiveMapVertexColor","emissiveVertexColor"],["specularMapVertexColor","specularVertexColor"],["metalnessMapVertexColor","metalnessVertexColor"],["opacityMapVertexColor","opacityVertexColor"],["glossMapVertexColor","glossVertexColor"],["lightMapVertexColor","lightVertexColor"],["diffuseMapTint","diffuseTint"],["specularMapTint","specularTint"],["emissiveMapTint","emissiveTint"],["metalnessMapTint","metalnessTint"],["clearCoatGlossiness","clearCoatGloss"]];for(e=0;e<i.length;e++){var n=i[e][0],s=i[e][1];void 0!==t[n]&&(void 0===t[s]&&(t[s]=t[n]),delete t[n])}var r=["fresnelFactor","shadowSampleType"];for(e=0;e<r.length;e++){var a=r[e];t.hasOwnProperty(a)&&delete t[a]}return t},e._validate=function(t){return t.validated||(this._validator||(this._validator=new kS),this._validator.validate(t)),t},t}(),BS={aoMap:"white",diffuseMap:"gray",specularMap:"gray",specularityFactorMap:"white",metalnessMap:"black",glossMap:"gray",sheenMap:"black",sheenGlossinessMap:"gray",clearCoatMap:"black",clearCoatGlossMap:"gray",clearCoatNormalMap:"normal",refractionMap:"white",emissiveMap:"gray",normalMap:"normal",heightMap:"gray",opacityMap:"gray",sphereMap:"gray",lightMap:"white"},US=function(){function t(t){this.handlerType="material",this._assets=t.assets,this._device=t.graphicsDevice,this._placeholderTextures=null,this._parser=new FS,this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t}),_a.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?e&&e("Error loading material: "+t.original+" ["+i+"]"):e&&(n._engine=!0,e(null,n))}))},e.open=function(t,e){var i=this._parser.parse(e);return e._engine&&(i._data=e,delete e._engine),i},e._createPlaceholders=function(){this._placeholderTextures={};var t={white:[255,255,255,255],gray:[128,128,128,255],black:[0,0,0,255],normal:[128,128,255,255]};for(var e in t)if(t.hasOwnProperty(e)){this._placeholderTextures[e]=new Ls(this._device,{width:2,height:2,format:7,name:"material_placeholder"});for(var i=this._placeholderTextures[e].lock(),n=0;n<4;n++)for(var s=0;s<4;s++)i[4*n+s]=t[e][s];this._placeholderTextures[e].unlock()}},e.patch=function(t,e){t.resource._data&&(t._data=t.resource._data,delete t.resource._data),t.data.name=t.name,t.resource.name=t.name,this._bindAndAssignAssets(t,e),t.off("unload",this._onAssetUnload,this),t.on("unload",this._onAssetUnload,this)},e._onAssetUnload=function(t){delete t.data.parameters,delete t.data.chunks,delete t.data.name},e._assignTexture=function(t,e,i){e.resource[t]=i},e._getPlaceholderTexture=function(t){this._placeholderTextures||this._createPlaceholders();var e=BS[t];return this._placeholderTextures[e]},e._assignPlaceholderTexture=function(t,e){e.resource[t]=this._getPlaceholderTexture(t)},e._onTextureLoad=function(t,e,i){this._assignTexture(t,e,i.resource),e.resource.update()},e._onTextureAdd=function(t,e,i){this._assets.load(i)},e._onTextureRemoveOrUnload=function(t,e,i){var n=e.resource;n&&e.resource[t]===i.resource&&(this._assignPlaceholderTexture(t,e),n.update())},e._assignCubemap=function(t,e,i){if(e.resource[t]=i[0],"cubeMap"===t){var n=i.slice(1);n.every((function(t){return t}))?e.resource.prefilteredCubemaps=n:n[0]&&(e.resource.envAtlas=n[0])}},e._onCubemapLoad=function(t,e,i){this._assignCubemap(t,e,i.resources),this._parser.initialize(e.resource,e.data)},e._onCubemapAdd=function(t,e,i){0===e.data.shadingModel&&(e.loadFaces=!0),this._assets.load(i)},e._onCubemapRemoveOrUnload=function(t,e,i){var n=e.resource;e.data.prefilteredCubeMap128===i.resources[1]&&(this._assignCubemap(t,e,[null,null,null,null,null,null,null]),n.update())},e._bindAndAssignAssets=function(t,e){var i,n,s,r=this._parser.migrate(t.data),a=t.resource,o="path"===r.mappingFormat,h=eu;for(i=0;i<h.length;i++){n=h[i],s=a._assetReferences[n];var l=r[n],c=a[n],u=c===this._getPlaceholderTexture(n),d=r.validated;!l||c&&d&&!u?s&&(o?s.url=null:s.id=null):(s||(s=new hg(n,t,e,{load:this._onTextureLoad,add:this._onTextureAdd,remove:this._onTextureRemoveOrUnload,unload:this._onTextureRemoveOrUnload},this),a._assetReferences[n]=s),o?s.url=t.getAbsoluteUrl(l):s.id=l,s.asset&&(s.asset.resource?this._assignTexture(n,t,s.asset.resource):this._assignPlaceholderTexture(n,t),e.load(s.asset)))}var f=nu;for(i=0;i<f.length;i++)n=f[i],s=a._assetReferences[n],r[n]&&!t.data.prefilteredCubeMap128&&(s||(s=new hg(n,t,e,{load:this._onCubemapLoad,add:this._onCubemapAdd,remove:this._onCubemapRemoveOrUnload,unload:this._onCubemapRemoveOrUnload},this),a._assetReferences[n]=s),o?s.url=r[n]:s.id=r[n],s.asset&&(s.asset.loaded&&this._assignCubemap(n,t,s.asset.resources),e.load(s.asset)));this._parser.initialize(a,r)},t}(),NS=function(){function t(t){this._device=t.device,this._defaultMaterial=t.defaultMaterial,this._assets=t.assets}return t.prototype.parse=function(t,e,i){var n,s=this;cS.parse("filename.glb","",t,this._device,this._assets,null!=(n=null==i?void 0:i.options)?n:{},(function(t,i){if(t)e(t);else{var n=gS.createModel(i,s._defaultMaterial);i.destroy(),e(null,n)}}))},t}(),zS=function(){this.index=0,this.boneIndices=[0,0,0,0]},VS=function(){function t(){this.partition=0,this.vertexStart=0,this.vertexCount=0,this.indexStart=0,this.indexCount=0,this.boneIndices=[],this.vertices=[],this.indices=[],this.indexMap={},this.originalMesh=null}var e=t.prototype;return e.addVertex=function(t,e,i){var n=-1;if(void 0!==this.indexMap[e])n=this.indexMap[e],this.indices.push(n);else{for(var s=0;s<4;s++)if(0!==i.blendWeight.data[4*e+s]){var r=i.blendIndices.data[4*t.index+s];t.boneIndices[s]=this.getBoneRemap(r)}n=this.vertices.length,this.indices.push(n),this.vertices.push(t),this.indexMap[e]=n}},e.addPrimitive=function(t,e,i,n){for(var s=[],r=0,a=t.length,o=0;o<a;o++)for(var h=t[o].index,l=0;l<4;l++)if(i.blendWeight.data[4*h+l]>0){for(var c=i.blendIndices.data[4*h+l],u=!0,d=0;d<r;d++)if(s[d]===c){u=!1;break}if(u)s[r]=c,r+=-1===this.getBoneRemap(c)?1:0}if(this.boneIndices.length+r>n)return!1;for(var f=0;f<r;f++)this.boneIndices.push(s[f]);for(var p=0;p<a;p++)this.addVertex(t[p],e[p],i);return!0},e.getBoneRemap=function(t){for(var e=0;e<this.boneIndices.length;e++)if(this.boneIndices[e]===t)return e;return-1},t}();function GS(t,e,i){var n,s,r,a;!function(t){for(var e=t.vertices,i=t.skins,n=t.meshes,s=t.meshInstances,r=0;r<n.length;r++)n[r].vertices=e[n[r].vertices],void 0!==n[r].skin&&(n[r].skin=i[n[r].skin]);for(var a=0;a<s.length;a++)s[a].mesh=n[s[a].mesh]}(t);var o,h=t.vertices,l=t.skins,c=t.meshes,u=t.meshInstances,d=function(t){var e=new zS;return e.index=t,e};for(n=l.length-1;n>=0;n--)if(l[n].boneNames.length>i){var f=l.splice(n,1)[0],p=[];for(s=0;s<c.length;s++)c[s].skin===f&&p.push(c[s]);for(s=0;s<p.length;s++)-1!==(a=c.indexOf(p[s]))&&c.splice(a,1);if(0===p.length)throw new Error("partitionSkin: There should be at least one mesh that references a skin");var m=p[0].vertices;for(s=1;s<p.length;s++)if(p[s].vertices!==m)throw new Error("partitionSkin: All meshes that share a skin should also share the same vertex buffer");var _=void 0,v=[],g=[],y=[],x=0;for(s=0;s<p.length;s++){for(var S=(o=p[s]).indices,b=o.base;b<o.base+o.count;){a=S[b++],g[0]=d(a),y[0]=a,a=S[b++],g[1]=d(a),y[1]=a,a=S[b++],g[2]=d(a),y[2]=a;for(var w=!1,T=x;T<v.length;T++)if((_=v[T]).addPrimitive(g,y,m,i)){w=!0;break}w||((_=new VS).originalMesh=o,_.addPrimitive(g,y,m,i),v.push(_))}x=v.length}var A=[],C=[];for(s=0;s<v.length;s++)if((_=v[s]).vertices.length&&_.indices.length){var E=A.length,M=_.vertices.length,P=C.length,R=_.indices.length;_.partition=s,_.vertexStart=E,_.vertexCount=M,_.indexStart=P,_.indexCount=R;var I=void 0,L=void 0;for(I=0,L=E;I<M;)A[L++]=_.vertices[I++];for(I=0,L=P;I<R;)C[L++]=_.indices[I++]+E}var D=[];for(s=0;s<v.length;s++){_=v[s];var O=[],k=[];for(r=0;r<_.boneIndices.length;r++)O.push(f.inverseBindMatrices[_.boneIndices[r]]),k.push(f.boneNames[_.boneIndices[r]]);var F={inverseBindMatrices:O,boneNames:k};D.push(F),l.push(F)}var B=void 0,U=void 0,N=void 0,z=void 0,V={};for(U in m)V[U]={components:m[U].components,data:[],type:m[U].type};for(U in m)if("blendIndices"===U){var G=V[U].data;for(s=0;s<A.length;s++){var H=A[s].boneIndices;G.push(H[0],H[1],H[2],H[3])}}else for(N=(B=m[U]).data,z=B.components,s=0;s<A.length;s++)for(a=A[s].index,r=0;r<z;r++)V[U].data.push(N[a*z+r]);for(h[h.indexOf(m)]=V,s=0;s<v.length;s++)for(_=v[s],o={aabb:{min:[0,0,0],max:[0,0,0]},vertices:V,skin:D[s],indices:C.splice(0,_.indexCount),type:"triangles",base:0,count:_.indexCount},c.push(o),r=u.length-1;r>=0;r--)u[r].mesh===_.originalMesh&&(u.push({mesh:o,node:u[r].node}),e&&e.push({material:e[r].material,path:e[r].path}));for(s=0;s<v.length;s++)for(_=v[s],r=u.length-1;r>=0;r--)u[r].mesh===_.originalMesh&&(u.splice(r,1),e&&e.splice(r,1))}!function(t){for(var e=t.vertices,i=t.skins,n=t.meshes,s=t.meshInstances,r=0;r<n.length;r++)n[r].vertices=e.indexOf(n[r].vertices),void 0!==n[r].skin&&(n[r].skin=i.indexOf(n[r].skin));for(var a=0;a<s.length;a++)s[a].mesh=n.indexOf(s[a].mesh)}(t)}var HS={points:0,lines:1,lineloop:2,linestrip:3,triangles:4,trianglestrip:be,trianglefan:6},WS={int8:0,uint8:mi,int16:2,uint16:3,int32:4,uint32:5,float32:6},XS=function(){function t(t){this._device=t.device,this._defaultMaterial=t.defaultMaterial}var e=t.prototype;return e.parse=function(t,e){var i=t.model;if(i)if(i.version<=1)e("JsonModelParser#parse: Trying to parse unsupported model format.");else{var n=this._parseNodes(t),s=this._parseSkins(t,n),r=this._parseVertexBuffers(t),a=this._parseIndexBuffers(t,r),o=this._parseMorphs(t,n,r),h=this._parseMeshes(t,s.skins,o.morphs,r,a.buffer,a.data),l=this._parseMeshInstances(t,n,h,s.skins,s.instances,o.morphs,o.instances),c=new Gu;c.graph=n[0],c.meshInstances=l,c.skinInstances=s.instances,c.morphInstances=o.instances,c.getGraph().syncHierarchy(),e(null,c)}else e(null,null)},e._parseNodes=function(t){var e,i=t.model,n=[];for(e=0;e<i.nodes.length;e++){var s=i.nodes[e],r=new hh(s.name);r.setLocalPosition(s.position[0],s.position[1],s.position[2]),r.setLocalEulerAngles(s.rotation[0],s.rotation[1],s.rotation[2]),r.setLocalScale(s.scale[0],s.scale[1],s.scale[2]),r.scaleCompensation=!!s.scaleCompensation,n.push(r)}for(e=1;e<i.parents.length;e++)n[i.parents[e]].addChild(n[e]);return n},e._parseSkins=function(t,e){var i,n,s=t.model,r=[],a=[];!this._device.supportsBoneTextures&&s.skins.length>0&&GS(s,null,this._device.getBoneLimit());for(i=0;i<s.skins.length;i++){var o=s.skins[i],h=[];for(n=0;n<o.inverseBindMatrices.length;n++){var l=o.inverseBindMatrices[n];h[n]=(new Ft).set(l)}var c=new Kd(this._device,h,o.boneNames);r.push(c);var u=new Xo(c),d=[];for(n=0;n<c.boneNames.length;n++){var f=c.boneNames[n],p=e[0].findByName(f);d.push(p)}u.bones=d,a.push(u)}return{skins:r,instances:a}},e._getMorphVertexCount=function(t,e,i){for(var n=0;n<t.meshes.length;n++){var s=t.meshes[n];if(s.morph===e)return i[s.vertices].numVertices}},e._parseMorphs=function(t,e,i){var n,s,r,a,o,h,l=t.model,c=[],u=[];if(l.morphs){var d=function(t,e,i){for(var n=new Float32Array(3*i),s=0;s<e.length;s++){var r=3*e[s];n[r]=t[3*s],n[r+1]=t[3*s+1],n[r+2]=t[3*s+2]}return n};for(n=0;n<l.morphs.length;n++){for(a=l.morphs[n].targets,h=[],r=this._getMorphVertexCount(l,n,i),s=0;s<a.length;s++){var f=a[s].aabb,p=f.min,m=f.max,_=new Ht(new wt(.5*(m[0]+p[0]),.5*(m[1]+p[1]),.5*(m[2]+p[2])),new wt(.5*(m[0]-p[0]),.5*(m[1]-p[1]),.5*(m[2]-p[2]))),v=a[s].indices,g=a[s].deltaPositions,y=a[s].deltaNormals;v&&(g=d(g,v,r),y=d(y,v,r)),o=new Wu({deltaPositions:g,deltaNormals:y,name:a[s].name,aabb:_}),h.push(o)}var x=new Hu(h,this._device);c.push(x);var S=new Vu(x);u.push(S)}}return{morphs:c,instances:u}},e._parseVertexBuffers=function(t){for(var e=t.model,i=[],n={position:we,normal:Te,tangent:Ae,blendWeight:Ce,blendIndices:Ee,color:Me,texCoord0:Re,texCoord1:Ie,texCoord2:Le,texCoord3:De,texCoord4:Oe,texCoord5:ke,texCoord6:Fe,texCoord7:Be},s=0;s<e.vertices.length;s++){var r=e.vertices[s],a=[];for(var o in r){var h=r[o];a.push({semantic:n[o],components:h.components,type:WS[h.type],normalize:n[o]===Me})}for(var l=new Ji(this._device,a),c=r.position.data.length/r.position.components,u=new ji(this._device,l,c),d=new Lr(u),f=0;f<c;f++){for(var p in r){var m=r[p];switch(m.components){case 1:d.element[n[p]].set(m.data[f]);break;case 2:d.element[n[p]].set(m.data[2*f],1-m.data[2*f+1]);break;case 3:d.element[n[p]].set(m.data[3*f],m.data[3*f+1],m.data[3*f+2]);break;case 4:d.element[n[p]].set(m.data[4*f],m.data[4*f+1],m.data[4*f+2],m.data[4*f+3])}}d.next()}d.end(),i.push(u)}return i},e._parseIndexBuffers=function(t,e){var i,n=t.model,s=null,r=null,a=0;for(i=0;i<n.meshes.length;i++){var o=n.meshes[i];void 0!==o.indices&&(a+=o.indices.length)}var h=0;for(i=0;i<e.length;i++)h=Math.max(h,e[i].numVertices);return a>0&&(h>65535&&this._device.extUintElement?(s=new vr(this._device,2,a),r=new Uint32Array(s.lock())):(s=new vr(this._device,1,a),r=new Uint16Array(s.lock()))),{buffer:s,data:r}},e._parseMeshes=function(t,e,i,n,s,r){for(var a=t.model,o=[],h=0,l=0;l<a.meshes.length;l++){var c=a.meshes[l],u=c.aabb,d=u.min,f=u.max,p=new Ht(new wt(.5*(f[0]+d[0]),.5*(f[1]+d[1]),.5*(f[2]+d[2])),new wt(.5*(f[0]-d[0]),.5*(f[1]-d[1]),.5*(f[2]-d[2]))),m=void 0!==c.indices,_=new qa(this._device);_.vertexBuffer=n[c.vertices],_.indexBuffer[0]=m?s:null,_.primitive[0].type=HS[c.type],_.primitive[0].base=m?c.base+h:c.base,_.primitive[0].count=c.count,_.primitive[0].indexed=m,_.skin=void 0!==c.skin?e[c.skin]:null,_.morph=void 0!==c.morph?i[c.morph]:null,_.aabb=p,m&&(r.set(c.indices,h),h+=c.indices.length),o.push(_)}return null!==s&&s.unlock(),o},e._parseMeshInstances=function(t,e,i,n,s,r,a){var o,h=t.model,l=[];for(o=0;o<h.meshInstances.length;o++){var c=h.meshInstances[o],u=e[c.node],d=i[c.mesh],f=new yh(d,this._defaultMaterial,u);if(d.skin){var p=n.indexOf(d.skin);f.skinInstance=s[p]}if(d.morph){var m=r.indexOf(d.morph);f.morphInstance=a[m]}l.push(f)}return l},t}(),jS=function(){function t(t){this.handlerType="model",this._parsers=[],this.device=t.graphicsDevice,this.assets=t.assets,this.defaultMaterial=Bo(this.device),this.maxRetries=0,this.addParser(new XS(this),(function(t,e){return".json"===L.getExtension(t)})),this.addParser(new NS(this),(function(t,e){return".glb"===L.getExtension(t)}))}var e=t.prototype;return e.load=function(t,e,i){var n=this;"string"==typeof t&&(t={load:t,original:t});var s={retry:this.maxRetries>0,maxRetries:this.maxRetries};(t.load.startsWith("blob:")||t.load.startsWith("data:"))&&(".glb"===L.getExtension(t.original).toLowerCase()?s.responseType=ma.ResponseType.ARRAY_BUFFER:s.responseType=ma.ResponseType.JSON),_a.get(t.load,s,(function(s,r){if(e)if(s)e("Error loading model: "+t.original+" ["+s+"]");else{for(var a=0;a<n._parsers.length;a++){var o=n._parsers[a];if(o.decider(t.original,r))return void o.parser.parse(r,(function(t,i){t?e(t):e(null,i)}),i)}e("No parsers found")}}))},e.open=function(t,e){return e},e.patch=function(t,e){if(t.resource){var i=t.data,n=this;t.resource.meshInstances.forEach((function(s,r){if(i.mapping){var a=function t(i){i.resource?s.material=i.resource:(i.once("load",t),e.load(i)),i.once("remove",(function(t){s.material===t.resource&&(s.material=n.defaultMaterial)}))};if(!i.mapping[r])return void(s.material=n.defaultMaterial);var o,h=i.mapping[r].material,l=i.mapping[r].path;if(void 0!==h)h?(o=e.get(h))?a(o):e.once("add:"+h,a):s.material=n.defaultMaterial;else if(l){var c=t.getAbsoluteUrl(i.mapping[r].path);(o=e.getByUrl(c))?a(o):e.once("add:url:"+c,a)}}}))}},e.addParser=function(t,e){this._parsers.push({parser:t,decider:e})},t}(),qS=function(){function t(t){this.handlerType="scene",this._app=t,this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){IS.load(t,this.maxRetries,e)},e.open=function(t,e){this._app.systems.script.preloading=!0;var i=new RS(this._app,!1).parse(e),n=this._app.scene;return n.root=i,this._app.applySceneSettings(e.settings),this._app.systems.script.preloading=!1,n},e.patch=function(t,e){},t}(),YS=function(){function t(t){this.handlerType="script",this._app=t,this._scripts={},this._cache={}}var e=t.prototype;return e.clearCache=function(){for(var t in this._cache){var e=this._cache[t],i=e.parentNode;i&&i.removeChild(e)}this._cache={}},e.load=function(t,e){var i=this;"string"==typeof t&&(t={load:t,original:t});var n=this;bf.app=this._app,this._loadScript(t.load,(function(t,s,r){if(t)e(t);else if(bf.legacy){var a=null;yf._types.length&&(a=yf._types.pop()),a?i._scripts[s]=a:a=null,e(null,a,r)}else{for(var o={},h=0;h<yf._types.length;h++)o[yf._types[h].name]=yf._types[h];yf._types.length=0,e(null,o,r),delete n._loader._cache[Qf.makeKey(s,"script")]}}))},e.open=function(t,e){return e},e.patch=function(t,e){},e._loadScript=function(t,e){var i=document.head,n=document.createElement("script");this._cache[t]=n,n.async=!1,n.addEventListener("error",(function(t){e("Script: "+t.target.src+" failed to load")}),!1);var s=!1;n.onload=n.onreadystatechange=function(){s||this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState||(s=!0,e(null,t,n))},n.src=t,i.appendChild(n)},t}(),KS=function(){function t(t){this.handlerType="shader",this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t}),_a.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?e("Error loading shader resource: "+t.original+" ["+i+"]"):e(null,n)}))},e.open=function(t,e){return e},e.patch=function(t,e){},t}();function ZS(t){this.resource&&(this.resource.atlas=t.resource)}function QS(t){this.registry.load(t)}var $S=function(){function t(t){this.handlerType="sprite",this._assets=t.assets,this._device=t.graphicsDevice,this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t}),".json"===L.getExtension(t.original)&&_a.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(t,i){t?e(t):e(null,i)}))},e.open=function(t,e){var i=new $d(this._device);return t&&(i.__data=e),i},e.patch=function(t,e){var i=t.resource;if(i.__data&&(t.data.pixelsPerUnit=i.__data.pixelsPerUnit,t.data.renderMode=i.__data.renderMode,t.data.frameKeys=i.__data.frameKeys,i.__data.textureAtlasAsset)){var n=e.getByUrl(i.__data.textureAtlasAsset);n?t.data.textureAtlasAsset=n.id:console.warn("Could not find textureatlas with url: "+i.__data.textureAtlasAsset)}i.startUpdate(),i.renderMode=t.data.renderMode,i.pixelsPerUnit=t.data.pixelsPerUnit,i.frameKeys=t.data.frameKeys,this._updateAtlas(t),i.endUpdate(),t.off("change",this._onAssetChange,this),t.on("change",this._onAssetChange,this)},e._updateAtlas=function(t){var e=t.resource;if(t.data.textureAtlasAsset){this._assets.off("load:"+t.data.textureAtlasAsset,ZS,t),this._assets.on("load:"+t.data.textureAtlasAsset,ZS,t);var i=this._assets.get(t.data.textureAtlasAsset);i&&i.resource?e.atlas=i.resource:i?this._assets.load(i):(this._assets.off("add:"+t.data.textureAtlasAsset,QS,t),this._assets.on("add:"+t.data.textureAtlasAsset,QS,t))}else e.atlas=null},e._onAssetChange=function(t,e,i,n){"data"===e&&i&&i.textureAtlasAsset&&n&&i.textureAtlasAsset!==n.textureAtlasAsset&&(this._assets.off("load:"+n.textureAtlasAsset,ZS,t),this._assets.off("add:"+n.textureAtlasAsset,QS,t))},t}(),JS=function(){function t(t,e){this._app=void 0,this._data=void 0,this._templateRoot=null,this._app=t,this._data=e}var e=t.prototype;return e.instantiate=function(){return this._templateRoot||this._parseTemplate(),this._templateRoot.clone()},e._parseTemplate=function(){var t=new RS(this._app,!0);this._templateRoot=t.parse(this._data)},t}(),tb=function(){function t(t){this.handlerType="template",this._app=t,this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};_a.get(t.load,i,(function(i,n){i?e("Error requesting template: "+t.original):e(i,n)}))},e.open=function(t,e){return new JS(this._app,e)},t}(),eb=function(){function t(t){this.handlerType="text",this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t}),_a.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?e("Error loading text resource: "+t.original+" ["+i+"]"):e(null,n)}))},e.open=function(t,e){return e},e.patch=function(t,e){},t}(),ib={repeat:0,clamp:1,mirror:2},nb={nearest:0,linear:1,nearest_mip_nearest:2,linear_mip_nearest:4,nearest_mip_linear:3,linear_mip_linear:5},sb=/^data\.frames\.(\d+)$/,rb=function(){function t(t){this.handlerType="textureatlas",this._loader=t.loader,this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t});var i=this,n=this._loader.getHandler("texture");".json"===L.getExtension(t.original)?_a.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(n,s){if(n)e(n);else{var r=t.original.replace(".json",".png");i._loader.load(r,"texture",(function(t,i){t?e(t):e(null,{data:s,texture:i})}))}})):n.load(t,e)},e.open=function(t,e){var i=new Jd;if(e.texture&&e.data)i.texture=e.texture,i.__data=e.data;else{var n=this._loader.getHandler("texture").open(t,e);if(!n)return null;i.texture=n}return i},e.patch=function(t,e){if(t.resource){t.resource.__data&&(void 0!==t.resource.__data.minfilter&&(t.data.minfilter=t.resource.__data.minfilter),void 0!==t.resource.__data.magfilter&&(t.data.magfilter=t.resource.__data.magfilter),void 0!==t.resource.__data.addressu&&(t.data.addressu=t.resource.__data.addressu),void 0!==t.resource.__data.addressv&&(t.data.addressv=t.resource.__data.addressv),void 0!==t.resource.__data.mipmaps&&(t.data.mipmaps=t.resource.__data.mipmaps),void 0!==t.resource.__data.anisotropy&&(t.data.anisotropy=t.resource.__data.anisotropy),void 0!==t.resource.__data.rgbm&&(t.data.rgbm=!!t.resource.__data.rgbm),t.data.frames=t.resource.__data.frames,delete t.resource.__data);var i=t.resource.texture;if(i&&(i.name=t.name,t.data.hasOwnProperty("minfilter")&&i.minFilter!==nb[t.data.minfilter]&&(i.minFilter=nb[t.data.minfilter]),t.data.hasOwnProperty("magfilter")&&i.magFilter!==nb[t.data.magfilter]&&(i.magFilter=nb[t.data.magfilter]),t.data.hasOwnProperty("addressu")&&i.addressU!==ib[t.data.addressu]&&(i.addressU=ib[t.data.addressu]),t.data.hasOwnProperty("addressv")&&i.addressV!==ib[t.data.addressv]&&(i.addressV=ib[t.data.addressv]),t.data.hasOwnProperty("mipmaps")&&i.mipmaps!==t.data.mipmaps&&(i.mipmaps=t.data.mipmaps),t.data.hasOwnProperty("anisotropy")&&i.anisotropy!==t.data.anisotropy&&(i.anisotropy=t.data.anisotropy),t.data.hasOwnProperty("rgbm"))){var n=t.data.rgbm?ii:ei;i.type!==n&&(i.type=n)}t.resource.texture=i;var s={};for(var r in t.data.frames){var a=t.data.frames[r];s[r]={rect:new Pt(a.rect),pivot:new Et(a.pivot),border:new Pt(a.border)}}t.resource.frames=s,t.off("change",this._onAssetChange,this),t.on("change",this._onAssetChange,this)}},e._onAssetChange=function(t,e,i){var n;if("data"===e||"data.frames"===e){var s={};for(var r in i.frames)n=i.frames[r],s[r]={rect:new Pt(n.rect),pivot:new Et(n.pivot),border:new Pt(n.border)};t.resource.frames=s}else{var a=e.match(sb);if(a){var o=a[1];i?(t.resource.frames[o]?((n=t.resource.frames[o]).rect.set(i.rect[0],i.rect[1],i.rect[2],i.rect[3]),n.pivot.set(i.pivot[0],i.pivot[1]),n.border.set(i.border[0],i.border[1],i.border[2],i.border[3])):t.resource.frames[o]={rect:new Pt(i.rect),pivot:new Et(i.pivot),border:new Pt(i.border)},t.resource.fire("set:frame",o,t.resource.frames[o])):t.resource.frames[o]&&(delete t.resource.frames[o],t.resource.fire("remove:frame",o))}}},t}();function ab(){var t,e,i,n=0,s=1,r=2,a=3,o=8,h=9,l=10,c=11,u=12,d=13,f=14,p=16,m={astc:l,dxt:r,etc1:n,etc2:n,pvr:o,atc:c,none:f},_={astc:l,dxt:a,etc1:p,etc2:s,pvr:h,atc:u,none:p},v=21,g=22,y=23,x=8,S=10,b=26,w=27,T=28,A=29,C=30,E=7,M=3,P=5,R=function(t,e){switch(t){case n:return e.formats.etc1?v:g;case s:return y;case r:return x;case a:return S;case o:return b;case h:return w;case l:return T;case c:return A;case u:return C;case d:return E;case f:return M;case p:return P}},I=function(t){for(var e=function(t,e){var i=t*(2/255)-1,n=e*(2/255)-1,s=Math.sqrt(1-Math.min(1,i*i+n*n));return Math.max(0,Math.min(255,Math.floor(.5*(s+1)*255)))},i=0;i<t.length;i+=4){var n=t[i+3],s=t[i+1];t[i+0]=n,t[i+2]=e(n,s),t[i+3]=255}return t},L=function(t){for(var e=new Uint16Array(t.length/4),i=0;i<t.length;i+=4){var n=t[i+0],s=t[i+1],r=t[i+2];e[i/4]=(248&n)<<8|(252&s)<<3|r>>3}return e},D=function(){return"undefined"!=typeof performance?performance.now():0},O=function(t,n,s){if(s){if(t.formats.astc)return"astc"}else if(n){if(t.formats.etc2)return"etc2"}else if(t.formats.etc1||t.formats.etc2)return"etc1";return function(e){for(var i=0;i<e.length;++i){var n=e[i];if(t.formats[n])return n}return"none"}(n?i:e)},k=function(t,e,i,d){switch(i){case n:case s:return!0;case r:case a:return 0==(3&t)&&0==(3&e);case o:case h:return function(t,e){return 0==(t&t-1)&&0==(e&e-1)}(t,e)&&(t===e||d);case l:case c:case u:return!0}return!1},F=function(e,i,n){return n.isKTX2?function(e,i,n){if(!t.KTX2File)throw new Error("Basis transcoder module does not include support for KTX2.");var s=D(),r=new t.KTX2File(new Uint8Array(i)),a=r.getWidth(),o=r.getHeight(),h=r.getLevels(),l=!!r.getHasAlpha(),c=r.isUASTC&&r.isUASTC();if(!a||!o||!h)throw r.close(),r.delete(),new Error("Invalid image dimensions url="+e+" width="+a+" height="+o+" levels="+h);var u,v,g=O(n.deviceDetails,l,c),y=!!n.isGGGR&&"pvr"===g;if(y?u=d:k(a,o,u=l?_[g]:m[g],n.deviceDetails.webgl2)||(u=l?d:f),!r.startTranscoding())throw r.close(),r.delete(),new Error("Failed to start transcoding url="+e);for(var x=[],S=0;S<h;++S){var b=r.getImageTranscodedSizeInBytes(S,0,0,u),w=new Uint8Array(b);if(!r.transcodeImage(w,S,0,0,u,0,-1,-1))throw r.close(),r.delete(),new Error("Failed to transcode image url="+e);var T=u===f||u===p;x.push(T?new Uint16Array(w.buffer):w)}if(r.close(),r.delete(),y)for(u=f,v=0;v<x.length;++v)x[v]=L(I(x[v]));return{format:R(u,n.deviceDetails),width:a,height:o,levels:x,cubemap:!1,transcodeTime:D()-s,url:e,unswizzledGGGR:y}}(e,i,n):function(e,i,n){var s=D(),r=new t.BasisFile(new Uint8Array(i)),a=r.getImageWidth(0,0),o=r.getImageHeight(0,0),h=r.getNumImages(),l=r.getNumLevels(0),c=!!r.getHasAlpha(),u=r.isUASTC&&r.isUASTC();if(!(a&&o&&h&&l))throw r.close(),r.delete(),new Error("Invalid image dimensions url="+e+" width="+a+" height="+o+" images="+h+" levels="+l);var v,g,y=O(n.deviceDetails,c,u),x=!!n.isGGGR&&"pvr"===y;if(x?v=d:k(a,o,v=c?_[y]:m[y],n.deviceDetails.webgl2)||(v=c?d:f),!r.startTranscoding())throw r.close(),r.delete(),new Error("Failed to start transcoding url="+e);for(var S=[],b=0;b<l;++b){var w=r.getImageTranscodedSizeInBytes(0,b,v),T=new Uint8Array(w);if(!r.transcodeImage(T,0,b,v,0,0)){if(b!==l-1||w!==S[b-1].buffer.byteLength)throw r.close(),r.delete(),new Error("Failed to transcode image url="+e);T.set(new Uint8Array(S[b-1].buffer)),console.warn("Failed to transcode last mipmap level, using previous level instead url="+e)}var A=v===f||v===p;S.push(A?new Uint16Array(T.buffer):T)}if(r.close(),r.delete(),x)for(v=f,g=0;g<S.length;++g)S[g]=L(I(S[g]));return{format:R(v,n.deviceDetails),width:a,height:o,levels:S,cubemap:!1,transcodeTime:D()-s,url:e,unswizzledGGGR:x}}(e,i,n)},B=function(t,e,i){try{var n=F(t,e,i);n.levels=n.levels.map((function(t){return t.buffer})),self.postMessage({url:t,data:n},n.levels)}catch(e){self.postMessage({url:t,err:e},null)}},U=[];self.onmessage=function(n){var s=n.data;switch(s.type){case"init":!function(n,s){self.BASIS(n.module?{instantiateWasm:function(t,e){return WebAssembly.instantiate(n.module,t).then((function(t){e(t)})).catch((function(t){console.error("instantiate failed + "+t)})),{}}}:null).then((function(r){r.initializeBasis(),t=r,e=n.rgbPriority,i=n.rgbaPriority,s(null)}))}(s.config,(function(){for(var t=0;t<U.length;++t)B(U[t].url,U[t].data,U[t].options);U.length=0}));break;case"transcode":t?B(s.url,s.data,s.options):U.push(s)}}}var ob=function(t){return{astc:!!t.extCompressedTextureASTC,atc:!!t.extCompressedTextureATC,dxt:!!t.extCompressedTextureS3TC,etc1:!!t.extCompressedTextureETC1,etc2:!!t.extCompressedTextureETC,pvr:!!t.extCompressedTexturePVRTC}},hb=function(t,e){var i=function(t){var e=["/* basis */",t,"","("+ab.toString()+")()\n\n"].join("\n");return new Blob([e],{type:"application/javascript"})},n=function(n,s){e(null,{workerUrl:URL.createObjectURL(i(n)),module:s,rgbPriority:t.rgbPriority,rgbaPriority:t.rgbaPriority})},s={cache:!0,responseType:"text",retry:t.maxRetries>0,maxRetries:t.maxRetries};if(t.glueUrl&&t.wasmUrl&&function(){try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){var t=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(t instanceof WebAssembly.Module)return new WebAssembly.Instance(t)instanceof WebAssembly.Instance}}catch(t){}return!1}()){var r=null,a=null;_a.get(t.glueUrl,s,(function(t,i){t?e(t):a?n(i,a):r=i}));var o=fetch(t.wasmUrl),h=function(){o.then((function(t){return t.arrayBuffer()})).then((function(t){return WebAssembly.compile(t)})).then((function(t){r?n(r,t):a=t})).catch((function(t){e(t,null)}))};WebAssembly.compileStreaming?WebAssembly.compileStreaming(o).then((function(t){r?n(r,t):a=t})).catch((function(t){h()})):h()}else _a.get(t.fallbackUrl,s,(function(t,i){t?e(t,null):n(i,null)}))},lb=function(){function t(){this.callbacks={},this.queue=[],this.clients=[]}var e=t.prototype;return e.enqueueJob=function(t,e,i,n){if(this.callbacks.hasOwnProperty(t))this.callbacks[t].push(i);else{this.callbacks[t]=[i];var s={url:t,data:e,options:n};this.clients.length>0?this.clients.shift().run(s):this.queue.push(s)}},e.enqueueClient=function(t){this.queue.length>0?t.run(this.queue.shift()):this.clients.push(t)},e.handleResponse=function(t,e,i){var n=this.callbacks[t];if(e)for(var s=0;s<n.length;++s)n[s](e);else{3===i.format||5===i.format?i.levels=i.levels.map((function(t){return new Uint16Array(t)})):i.levels=i.levels.map((function(t){return new Uint8Array(t)}));for(var r=0;r<n.length;++r)n[r](null,i)}delete this.callbacks[t]},t}(),cb=function(){function t(t,e,i){var n=this;this.queue=t,this.worker=new Worker(e.workerUrl),this.worker.addEventListener("message",(function(t){var e=t.data;n.queue.handleResponse(e.url,e.err,e.data),n.eager||n.queue.enqueueClient(n)})),this.worker.postMessage({type:"init",config:e}),this.eager=i}return t.prototype.run=function(t){var e=[];t.data instanceof ArrayBuffer&&e.push(t.data),this.worker.postMessage({type:"transcode",url:t.url,format:t.format,data:t.data,options:t.options},e),this.eager&&this.queue.enqueueClient(this)},t}(),ub=1,db=["etc1","etc2","astc","dxt","pvr","atc"],fb=["astc","dxt","etc2","pvr","atc"],pb=5,mb=new lb,_b=null,vb=!1;function gb(t){if(!vb){if(t){if(t.lazyInit)return void(_b=t)}else t=_b||{};if(!t.glueUrl||!t.wasmUrl||!t.fallbackUrl){var e=ht.getConfig("BASIS");e&&(t={glueUrl:e.glueUrl,wasmUrl:e.wasmUrl,fallbackUrl:e.fallbackUrl,numWorkers:e.numWorkers})}if(t.glueUrl||t.wasmUrl||t.fallbackUrl){vb=!0;var i=Math.max(1,Math.min(16,t.numWorkers||ub)),n=1===t.numWorkers||!t.hasOwnProperty("eagerWorkers")||t.eagerWorkers;t.rgbPriority=t.rgbPriority||db,t.rgbaPriority=t.rgbaPriority||fb,t.maxRetries=t.hasOwnProperty("maxRetries")?t.maxRetries:pb,hb(t,(function(t,e){if(t)console.error("failed to initialize basis worker: "+t);else for(var s=0;s<i;++s)mb.enqueueClient(new cb(mb,e,n))}))}}}var yb=null;function xb(t,e,i,n,s){return gb(),yb||(yb={webgl2:t.isWebGL2,formats:ob(t)}),mb.enqueueJob(e,i,n,{deviceDetails:yb,isGGGR:!(null==s||!s.isGGGR),isKTX2:!(null==s||!s.isKTX2)}),vb}var Sb=function(){function t(t,e){this.device=e,this.maxRetries=0}var e=t.prototype;return e.load=function(t,e,i){var n=this.device;Vf.fetchArrayBuffer(t.load,(function(s,r){s?e(s):function(s){var r;xb(n,t.load,s,e,{isGGGR:0!=(8&(null==i||null==(r=i.file)||null==(r=r.variants)||null==(r=r.basis)?void 0:r.opt))})||e("Basis module not found. Asset '"+i.name+"' basis texture variant will not be loaded.")}(r)}),i,this.maxRetries)},e.open=function(t,e,i,n){void 0===n&&(n={});var s=new Ls(i,x({name:t,addressU:e.cubemap?1:0,addressV:e.cubemap?1:0,width:e.width,height:e.height,format:e.format,cubemap:e.cubemap,levels:e.levels},n));return s.upload(),s},t}(),bb=function(){function t(t,e){this.crossOrigin=t.prefix?"anonymous":null,this.maxRetries=0,this.device=e}var e=t.prototype;return e.load=function(t,e,i){var n,s=!(null==i||null==(n=i.file)||!n.contents);if(s){if(this.device.supportsImageBitmap)return void this._loadImageBitmapFromBlob(new Blob([i.file.contents]),e);t={load:URL.createObjectURL(new Blob([i.file.contents])),original:t.original}}var r,a=function(i,n){s&&URL.revokeObjectURL(t.load),e(i,n)};i&&i.options&&i.options.hasOwnProperty("crossOrigin")?r=i.options.crossOrigin:Ff.test(t.load)&&(r=this.crossOrigin),this.device.supportsImageBitmap?this._loadImageBitmap(t.load,t.original,r,a):this._loadImage(t.load,t.original,r,a)},e.open=function(t,e,i,n){void 0===n&&(n={});var s=new Ls(i,x({name:t,width:e.width,height:e.height,format:7},n));return s.setSource(e),s},e._loadImage=function(t,e,i,n){var s=new Image;i&&(s.crossOrigin=i);var r,a=0,o=this.maxRetries;s.onload=function(){n(null,s)},s.onerror=function(){if(!r)if(o>0&&++a<=o){var i=100*Math.pow(2,a);console.log("Error loading Texture from: '"+e+"' - Retrying in "+i+"ms...");var h=t.indexOf("?")>=0?"&":"?";r=setTimeout((function(){s.src=t+h+"retry="+Date.now(),r=null}),i)}else n("Error loading Texture from: '"+e+"'")},s.src=t},e._loadImageBitmap=function(t,e,i,n){var s=this,r={cache:!0,responseType:"blob",retry:this.maxRetries>0,maxRetries:this.maxRetries};_a.get(t,r,(function(t,e){t?n(t):s._loadImageBitmapFromBlob(e,n)}))},e._loadImageBitmapFromBlob=function(t,e){createImageBitmap(t,{premultiplyAlpha:"none",colorSpaceConversion:"none"}).then((function(t){return e(null,t)})).catch((function(t){return e(t)}))},t}(),wb=[1481919403,3140563232,169478669],Tb={33776:8,33778:9,33779:re,36196:pe,37492:22,37496:23,35840:ve,35841:me,35842:ge,35843:_e,32849:6,32856:7,35905:19,35907:20,35898:fe,34843:ae,34842:oe};for(var Ab=function(){function t(t){this.maxRetries=0}var e=t.prototype;return e.load=function(t,e,i){Vf.fetchArrayBuffer(t.load,e,i,this.maxRetries)},e.open=function(t,e,i,n){void 0===n&&(n={});var s=this.parse(e);if(!s)return null;var r=new Ls(i,x({name:t,addressU:s.cubemap?1:0,addressV:s.cubemap?1:0,width:s.width,height:s.height,format:s.format,cubemap:s.cubemap,levels:s.levels},n));return r.upload(),r},e.parse=function(t){var e=new Uint32Array(t);if(wb[0]!==e[0]||wb[1]!==e[1]||wb[2]!==e[2])return null;var i={endianness:e[3],glType:e[4],glTypeSize:e[5],glFormat:e[6],glInternalFormat:e[7],glBaseInternalFormat:e[8],pixelWidth:e[9],pixelHeight:e[10],pixelDepth:e[11],numberOfArrayElements:e[12],numberOfFaces:e[13],numberOfMipmapLevels:e[14],bytesOfKeyValueData:e[15]};if(i.pixelDepth>1)return null;if(0!==i.numberOfArrayElements)return null;var n=Tb[i.glInternalFormat];if(void 0===n)return null;for(var s,r,a,o=16+i.bytesOfKeyValueData/4,h=i.numberOfFaces>1,l=[],c=0;c<(i.numberOfMipmapLevels||1);c++){var u=e[o++];h&&l.push([]);for(var d=h?l[c]:l,f=0;f<(h?6:1);++f)d.push((s=t,r=4*o,a=u,n===fe?new Uint32Array(s,r,a/4):new Uint8Array(s,r,a))),o+=u+3>>2}return{format:n,width:i.pixelWidth,height:i.pixelHeight,levels:l,cubemap:h}},t}(),Cb=166,Eb=function(){function t(t,e){this.maxRetries=0,this.device=e}var e=t.prototype;return e.load=function(t,e,i){var n=this;Vf.fetchArrayBuffer(t.load,(function(s,r){s?e(s,r):n.parse(r,t,e,i)}),i,this.maxRetries)},e.open=function(t,e,i,n){void 0===n&&(n={});var s=new Ls(i,x({name:t,addressU:e.cubemap?1:0,addressV:e.cubemap?1:0,width:e.width,height:e.height,format:e.format,cubemap:e.cubemap,levels:e.levels},n));return s.upload(),s},e.parse=function(t,e,i,n){var s=new lt(t),r=[s.readU32be(),s.readU32be(),s.readU32be()];if(2873840728!==r[0]||540160187!==r[1]||218765834!==r[2])return null;for(var a={vkFormat:s.readU32(),typeSize:s.readU32(),pixelWidth:s.readU32(),pixelHeight:s.readU32(),pixelDepth:s.readU32(),layerCount:s.readU32(),faceCount:s.readU32(),levelCount:s.readU32(),supercompressionScheme:s.readU32()},o={dfdByteOffset:s.readU32(),dfdByteLength:s.readU32(),kvdByteOffset:s.readU32(),kvdByteLength:s.readU32(),sgdByteOffset:s.readU64(),sgdByteLength:s.readU64()},h=[],l=0;l<Math.max(1,a.levelCount);++l)h.push({byteOffset:s.readU64(),byteLength:s.readU64(),uncompressedByteLength:s.readU64()});if(s.readU32()!==o.kvdByteOffset-o.dfdByteOffset)return null;s.skip(8);var c,u=s.readU8();(s.skip(o.dfdByteLength-9),s.skip(o.kvdByteLength),1===a.supercompressionScheme||u===Cb)?xb(this.device,e.load,t,i,{isGGGR:0!=(8&(null==n||null==(c=n.file)||null==(c=c.variants)||null==(c=c.basis)?void 0:c.opt)),isKTX2:!0})||i('Basis module not found. Asset "'+n.name+'" basis texture variant will not be loaded.'):i("unsupported KTX2 pixel format")},t}(),Mb=function(){function t(t){this.maxRetries=0}var e=t.prototype;return e.load=function(t,e,i){Vf.fetchArrayBuffer(t.load,e,i,this.maxRetries)},e.open=function(t,e,i,n){void 0===n&&(n={});var s,r=new Uint32Array(e,0,32),a=r[4],o=r[3],h=Math.max(r[7],1),l=4===r[20],c=r[21],u=r[22],d=65024===r[28],f=827611204,p=825438800,m=825439312,_=!1,v=!1,g=!1,y=!1,S=null,b=1;if(l?c===f?(S=8,_=!0):894720068===c?(S=re,_=!0):113===c?(S=oe,b=2):116===c?(S=le,b=4):826496069===c?(S=pe,_=!0,v=!0):c===p||825504336===c?(S=c===p?me:_e,_=!0,g=!0):c!==m&&825504848!==c||(S=c===m?ve:ge,_=!0,y=!0):32===u&&(S=7),!S)return s=new Ls(i,{width:4,height:4,format:6,name:"dds-legacy-empty"});s=new Ls(i,x({name:t,addressU:d?1:0,addressV:d?1:0,width:a,height:o,format:S,cubemap:d,mipmaps:h>1},n));for(var w,T=128,A=d?6:1,C=c===f?8:16,E=0;E<A;E++)for(var M=a,P=o,R=0;R<h;R++){w=_?v?Math.floor((M+3)/4)*Math.floor((P+3)/4)*8:g?Math.max(M,16)*Math.max(P,8)/4:y?Math.max(M,8)*Math.max(P,8)/2:Math.floor((M+4-1)/4)*Math.floor((P+4-1)/4)*C:M*P*4;var I=S===le?new Float32Array(e,T,w):S===oe?new Uint16Array(e,T,w):new Uint8Array(e,T,w);d?(s._levels[R]||(s._levels[R]=[]),s._levels[R][E]=I):s._levels[R]=I,T+=w*b,M=Math.max(.5*M,1),P=Math.max(.5*P,1)}return s.upload(),s},t}(),Pb=function(){function t(t){this.maxRetries=0}var e=t.prototype;return e.load=function(t,e,i){Vf.fetchArrayBuffer(t.load,e,i,this.maxRetries)},e.open=function(t,e,i,n){void 0===n&&(n={});var s=this.parse(e);if(!s)return null;var r=new Ls(i,x({name:t,addressU:0,addressV:1,minFilter:0,magFilter:0,width:s.width,height:s.height,levels:s.levels,format:7,type:ni,mipmaps:!1},n));return r.upload(),r},e.parse=function(t){var e=new lt(t);if(!e.readLine().startsWith("#?RADIANCE"))return null;for(var i={};;){var n=e.readLine();if(0===n.length)break;var s=n.split("=");2===s.length&&(i[s[0]]=s[1])}if(!i.hasOwnProperty("FORMAT"))return null;var r=e.readLine().split(" ");if(4!==r.length)return null;var a=parseInt(r[1],10),o=parseInt(r[3],10),h=this._readPixels(e,o,a,"-Y"===r[0]);return h?{width:o,height:a,levels:[h]}:null},e._readPixels=function(t,e,i,n){if(e<8||e>32767)return this._readPixelsFlat(t,e,i);var s=[0,0,0,0];if(t.readArray(s),2!==s[0]||2!==s[1]||0!=(128&s[2]))return t.skip(-4),this._readPixelsFlat(t,e,i);var r,a,o,h,l,c,u=new ArrayBuffer(e*i*4),d=new Uint8Array(u),f=n?0:4*e*(i-1);for(a=0;a<i;++a){if(a&&t.readArray(s),(s[2]<<8)+s[3]!==e)return null;for(h=0;h<4;++h)for(r=0;r<e;)if((l=t.readU8())>128){if(r+(l-=128)>e)return null;for(c=t.readU8(),o=0;o<l;++o)d[f+h+4*r++]=c}else{if(0===l||r+l>e)return null;for(o=0;o<l;++o)d[f+h+4*r++]=t.readU8()}f+=4*e*(n?1:-1)}return d},e._readPixelsFlat=function(t,e,i){return t.remainingBytes===e*i*4?new Uint8Array(t.arraybuffer,t.offset):null},t}(),Rb={repeat:0,clamp:1,mirror:2},Ib={nearest:0,linear:1,nearest_mip_nearest:2,linear_mip_nearest:4,nearest_mip_linear:3,linear_mip_linear:5},Lb={default:ei,rgbm:ii,rgbe:ni,rgbp:si,swizzleGGGR:ri},Db=function(){function t(){}var e=t.prototype;return e.load=function(t,e,i){throw new Error("not implemented")},e.open=function(t,e,i){throw new Error("not implemented")},t}(),Ob=function(){function t(t){this.handlerType="texture";var e=t.assets,i=t.graphicsDevice;this._device=i,this._assets=e,this.imgParser=new bb(e,i),this.parsers={dds:new Mb(e),ktx:new Ab(e),ktx2:new Eb(e,i),basis:new Sb(e,i),hdr:new Pb(e)}}var e=t.prototype;return e._getUrlWithoutParams=function(t){return t.indexOf("?")>=0?t.split("?")[0]:t},e._getParser=function(t){var e=L.getExtension(this._getUrlWithoutParams(t)).toLowerCase().replace(".","");return this.parsers[e]||this.imgParser},e._getTextureOptions=function(t){var e={};if(t){var i;(null==(i=t.name)?void 0:i.length)>0&&(e.name=t.name);var n=t.data;n.hasOwnProperty("minfilter")&&(e.minFilter=Ib[n.minfilter]),n.hasOwnProperty("magfilter")&&(e.magFilter=Ib[n.magfilter]),n.hasOwnProperty("addressu")&&(e.addressU=Rb[n.addressu]),n.hasOwnProperty("addressv")&&(e.addressV=Rb[n.addressv]),n.hasOwnProperty("mipmaps")&&(e.mipmaps=n.mipmaps),n.hasOwnProperty("anisotropy")&&(e.anisotropy=n.anisotropy),n.hasOwnProperty("flipY")&&(e.flipY=!!n.flipY),n.hasOwnProperty("type")?e.type=Lb[n.type]:n.hasOwnProperty("rgbm")&&n.rgbm?e.type=ii:t.file&&0!=(8&t.file.opt)&&(e.type=ri)}return e},e.load=function(t,e,i){"string"==typeof t&&(t={load:t,original:t}),this._getParser(t.original).load(t,e,i)},e.open=function(t,e,i){if(t){var n=this._getTextureOptions(i),s=this._getParser(t).open(t,e,this._device,n);return null===s?s=new Ls(this._device,{width:4,height:4,format:6}):(!function(t){var e=Math.log2(Math.max(t._width,t._height))+1;if(!(7!==t._format&&t._format!==le||t._volume||t._compressed||1===t._levels.length||t._levels.length===e||(i=t._cubemap?t._levels[0][0]:t._levels[0],i instanceof HTMLCanvasElement||i instanceof HTMLImageElement||i instanceof HTMLVideoElement))){for(var i,n=function(t,e,i){for(var n=Math.max(1,t>>1),s=Math.max(1,e>>1),r=new i.constructor(n*s*4),a=Math.floor(t/n),o=Math.floor(e/s),h=a*o,l=0;l<s;++l)for(var c=0;c<n;++c)for(var u=0;u<4;++u){for(var d=0,f=0;f<o;++f)for(var p=0;p<a;++p)d+=i[4*(c*a+p+(l*o+f)*t)+u];r[4*(c+l*n)+u]=d/h}return r},s=t._levels.length;s<e;++s){var r=Math.max(1,t._width>>s-1),a=Math.max(1,t._height>>s-1);if(t._cubemap){for(var o=[],h=0;h<6;++h)o.push(n(r,a,t._levels[s-1][h]));t._levels.push(o)}else t._levels.push(n(r,a,t._levels[s-1]))}t._levelsUpdated=t._cubemap?[[!0,!0,!0,!0,!0,!0]]:[!0]}}(s),e.unswizzledGGGR&&(i.file.variants.basis.opt&=-9)),s}},e.patch=function(t,e){var i=t.resource;if(i)for(var n=this._getTextureOptions(t),s=0,r=Object.keys(n);s<r.length;s++){var a=r[s];i[a]=n[a]}},y(t,[{key:"crossOrigin",get:function(){return this.imgParser.crossOrigin},set:function(t){this.imgParser.crossOrigin=t}},{key:"maxRetries",get:function(){return this.imgParser.maxRetries},set:function(t){for(var e in this.imgParser.maxRetries=t,this.parsers)this.parsers.hasOwnProperty(e)&&(this.parsers[e].maxRetries=t)}}]),t}(),kb="inline",Fb="immersive-vr",Bb="immersive-ar",Ub="viewer",Nb="left",zb="cpu-optimized",Vb="gpu-optimized",Gb="luminance-alpha",Hb=function(t){function e(e){var i;return(i=t.call(this)||this)._manager=void 0,i._available=!1,i._depthInfoCpu=null,i._depthInfoGpu=null,i._usage=null,i._dataFormat=null,i._matrixDirty=!1,i._matrix=new Ft,i._emptyBuffer=new Uint8Array(32),i._depthBuffer=null,i._texture=void 0,i._manager=e,i._texture=new Ls(i._manager.app.graphicsDevice,{format:2,mipmaps:!1,addressU:1,addressV:1,minFilter:1,magFilter:1,name:"XRDepthSensing"}),i.supported&&(i._manager.on("start",i._onSessionStart,w(i)),i._manager.on("end",i._onSessionEnd,w(i))),i}S(e,t);var i=e.prototype;return i.destroy=function(){this._texture.destroy(),this._texture=null},i._onSessionStart=function(){var t=this._manager.session;try{this._usage=t.depthUsage,this._dataFormat=t.depthDataFormat}catch(t){this._usage=null,this._dataFormat=null,this._available=!1,this.fire("error",t)}},i._onSessionEnd=function(){this._depthInfoCpu=null,this._depthInfoGpu=null,this._usage=null,this._dataFormat=null,this._available&&(this._available=!1,this.fire("unavailable")),this._depthBuffer=null,this._texture._width=4,this._texture._height=4,this._texture._levels[0]=this._emptyBuffer,this._texture.upload()},i._updateTexture=function(){var t=this._depthInfoCpu||this._depthInfoGpu;if(t){var e=!1;if(t.width===this._texture.width&&t.height===this._texture.height||(this._texture._width=t.width,this._texture._height=t.height,this._matrixDirty=!0,e=!0),this._depthInfoCpu){var i=this._depthInfoCpu.data;this._depthBuffer=new Uint8Array(i),this._texture._levels[0]=this._depthBuffer,this._texture.upload()}else this._depthInfoGpu&&(this._texture._levels[0]=this._depthInfoGpu.texture,this._texture.upload());e&&this.fire("resize",t.width,t.height)}else this._depthBuffer&&(this._depthBuffer=null,this._texture._width=4,this._texture._height=4,this._texture._levels[0]=this._emptyBuffer,this._texture.upload())},i.update=function(t,e){if(this._usage){var i=null,n=null;if(this._usage===zb&&e?i=t.getDepthInformation(e):this._usage===Vb&&e&&(n=t.getDepthInformation(e)),(this._depthInfoCpu&&!i||!this._depthInfoCpu&&i||this.depthInfoGpu&&!n||!this._depthInfoGpu&&n)&&(this._matrixDirty=!0),this._depthInfoCpu=i,this._depthInfoGpu=n,this._updateTexture(),this._matrixDirty){this._matrixDirty=!1;var s=this._depthInfoCpu||this._depthInfoGpu;s?this._matrix.data.set(s.normDepthBufferFromNormView.matrix):this._matrix.setIdentity()}!this._depthInfoCpu&&!this._depthInfoGpu||this._available?this._depthInfoCpu||this._depthInfoGpu||!this._available||(this._available=!1,this.fire("unavailable")):(this._available=!0,this.fire("available"))}},i.getDepth=function(t,e){return this._depthInfoCpu?this._depthInfoCpu.getDepthInMeters(t,e):null},y(e,[{key:"supported",get:function(){return G.browser&&!!window.XRDepthInformation}},{key:"available",get:function(){return this._available}},{key:"usage",get:function(){return this._usage}},{key:"dataFormat",get:function(){return this._dataFormat}},{key:"width",get:function(){var t=this._depthInfoCpu||this._depthInfoGpu;return t&&t.width||0}},{key:"height",get:function(){var t=this._depthInfoCpu||this._depthInfoGpu;return t&&t.height||0}},{key:"texture",get:function(){return this._texture}},{key:"uvMatrix",get:function(){return this._matrix}},{key:"rawValueToMeters",get:function(){var t=this._depthInfoCpu||this._depthInfoGpu;return t&&t.rawValueToMeters||0}}]),e}(P),Wb=function(){function t(t){this._manager=void 0,this._supported=G.browser&&!!window.XRDOMOverlayState,this._root=null,this._manager=t}return y(t,[{key:"supported",get:function(){return this._supported}},{key:"available",get:function(){return this._supported&&this._manager.active&&null!==this._manager._session.domOverlayState}},{key:"state",get:function(){return this._supported&&this._manager.active&&this._manager._session.domOverlayState?this._manager._session.domOverlayState.type:null}},{key:"root",get:function(){return this._root},set:function(t){this._supported&&!this._manager.active&&(this._root=t)}}]),t}(),Xb=[],jb=[],qb=function(t){function e(e,i,n){var s;return(s=t.call(this)||this).manager=void 0,s._xrHitTestSource=void 0,s._transient=void 0,s.manager=e,s._xrHitTestSource=i,s._transient=n,s}S(e,t);var i=e.prototype;return i.remove=function(){if(this._xrHitTestSource){var t=this.manager.hitTest.sources,e=t.indexOf(this);-1!==e&&t.splice(e,1),this.onStop()}},i.onStop=function(){this._xrHitTestSource.cancel(),this._xrHitTestSource=null,this.fire("remove"),this.manager.hitTest.fire("remove",this)},i.update=function(t){if(this._transient)for(var e=t.getHitTestResultsForTransientInput(this._xrHitTestSource),i=0;i<e.length;i++){var n=e[i],s=void 0;n.inputSource&&(s=this.manager.input._getByInputSource(n.inputSource)),this.updateHitResults(n.results,s)}else this.updateHitResults(t.getHitTestResults(this._xrHitTestSource))},i.updateHitResults=function(t,e){for(var i=0;i<t.length;i++){var n=t[i].getPose(this.manager._referenceSpace),s=Xb.pop();s||(s=new wt),s.copy(n.transform.position);var r=jb.pop();r||(r=new Bt),r.copy(n.transform.orientation),this.fire("result",s,r,e),this.manager.hitTest.fire("result",this,s,r,e),Xb.push(s),jb.push(r)}},e}(P),Yb=function(t){function e(e){var i;return(i=t.call(this)||this).manager=void 0,i._supported=G.browser&&!(!window.XRSession||!window.XRSession.prototype.requestHitTestSource),i._session=null,i.sources=[],i.manager=e,i._supported&&(i.manager.on("start",i._onSessionStart,w(i)),i.manager.on("end",i._onSessionEnd,w(i))),i}S(e,t);var i=e.prototype;return i._onSessionStart=function(){this.manager.type===Bb&&(this._session=this.manager.session)},i._onSessionEnd=function(){if(this._session){this._session=null;for(var t=0;t<this.sources.length;t++)this.sources[t].onStop();this.sources=[]}},i.isAvailable=function(t,e){var i;return this._supported||(i=new Error("XR HitTest is not supported")),this._session||(i=new Error("XR Session is not started (1)")),this.manager.type!==Bb&&(i=new Error("XR HitTest is available only for AR")),!i||(t&&t(i),e&&e.fire("error",i),!1)},i.start=function(t){var e=this;if(void 0===t&&(t={}),this.isAvailable(t.callback,this)){var i;t.profile||t.spaceType||(t.spaceType=Ub);var n=t.offsetRay;if(n){var s=new DOMPoint(n.origin.x,n.origin.y,n.origin.z,1),r=new DOMPoint(n.direction.x,n.direction.y,n.direction.z,0);i=new XRRay(s,r)}var a=t.callback;t.spaceType?this._session.requestReferenceSpace(t.spaceType).then((function(n){if(!e._session){var s=new Error("XR Session is not started (2)");return a&&a(s),void e.fire("error",s)}e._session.requestHitTestSource({space:n,entityTypes:t.entityTypes||void 0,offsetRay:i}).then((function(t){e._onHitTestSource(t,!1,a)})).catch((function(t){a&&a(t),e.fire("error",t)}))})).catch((function(t){a&&a(t),e.fire("error",t)})):this._session.requestHitTestSourceForTransientInput({profile:t.profile,entityTypes:t.entityTypes||void 0,offsetRay:i}).then((function(t){e._onHitTestSource(t,!0,a)})).catch((function(t){a&&a(t),e.fire("error",t)}))}},i._onHitTestSource=function(t,e,i){if(!this._session){t.cancel();var n=new Error("XR Session is not started (3)");return i&&i(n),void this.fire("error",n)}var s=new qb(this.manager,t,e);this.sources.push(s),i&&i(null,s),this.fire("add",s)},i.update=function(t){for(var e=0;e<this.sources.length;e++)this.sources[e].update(t)},y(e,[{key:"supported",get:function(){return this._supported}}]),e}(P),Kb=function(t){function e(e,i){var n;return(n=t.call(this)||this)._image=void 0,n._width=void 0,n._bitmap=null,n._measuredWidth=0,n._trackable=!1,n._tracking=!1,n._emulated=!1,n._pose=null,n._position=new wt,n._rotation=new Bt,n._image=e,n._width=i,n}S(e,t);var i=e.prototype;return i.prepare=function(){var t=this;return this._bitmap?{image:this._bitmap,widthInMeters:this._width}:createImageBitmap(this._image).then((function(e){return t._bitmap=e,{image:t._bitmap,widthInMeters:t._width}}))},i.destroy=function(){this._image=null,this._pose=null,this._bitmap&&(this._bitmap.close(),this._bitmap=null)},i.getPosition=function(){return this._pose&&this._position.copy(this._pose.transform.position),this._position},i.getRotation=function(){return this._pose&&this._rotation.copy(this._pose.transform.orientation),this._rotation},y(e,[{key:"image",get:function(){return this._image}},{key:"width",get:function(){return this._width},set:function(t){this._width=t}},{key:"trackable",get:function(){return this._trackable}},{key:"tracking",get:function(){return this._tracking}},{key:"emulated",get:function(){return this._emulated}}]),e}(P),Zb=function(t){function e(e){var i;return(i=t.call(this)||this)._manager=void 0,i._supported=G.browser&&!!window.XRImageTrackingResult,i._available=!1,i._images=[],i._manager=e,i._supported&&(i._manager.on("start",i._onSessionStart,w(i)),i._manager.on("end",i._onSessionEnd,w(i))),i}S(e,t);var i=e.prototype;return i.add=function(t,e){if(!this._supported||this._manager.active)return null;var i=new Kb(t,e);return this._images.push(i),i},i.remove=function(t){if(!this._manager.active){var e=this._images.indexOf(t);-1!==e&&(t.destroy(),this._images.splice(e,1))}},i._onSessionStart=function(){var t=this;this._manager.session.getTrackedImageScores().then((function(e){t._available=!0;for(var i=0;i<e.length;i++)t._images[i]._trackable="trackable"===e[i]})).catch((function(e){t._available=!1,t.fire("error",e)}))},i._onSessionEnd=function(){this._available=!1;for(var t=0;t<this._images.length;t++){var e=this._images[t];e._pose=null,e._measuredWidth=0,e._tracking&&(e._tracking=!1,e.fire("untracked"))}},i.prepareImages=function(t){this._images.length?Promise.all(this._images.map((function(t){return t.prepare()}))).then((function(e){t(null,e)})).catch((function(e){t(e,null)})):t(null,null)},i.update=function(t){if(this._available){for(var e=t.getImageTrackingResults(),i={},n=0;n<e.length;n++){i[e[n].index]=e[n];var s=this._images[e[n].index];s._emulated="emulated"===e[n].trackingState,s._measuredWidth=e[n].measuredWidthInMeters,s._pose=t.getPose(e[n].imageSpace,this._manager._referenceSpace)}for(var r=0;r<this._images.length;r++)this._images[r]._tracking&&!i[r]?(this._images[r]._tracking=!1,this._images[r].fire("untracked")):!this._images[r]._tracking&&i[r]&&(this._images[r]._tracking=!0,this._images[r].fire("tracked"))}},y(e,[{key:"supported",get:function(){return this._supported}},{key:"available",get:function(){return this._available}},{key:"images",get:function(){return this._images}}]),e}(P),Qb=function(){function t(t,e){this._index=void 0,this._hand=void 0,this._joints=[],this._tip=null,this._index=t,this._hand=e,this._hand._fingers.push(this)}return y(t,[{key:"index",get:function(){return this._index}},{key:"hand",get:function(){return this._hand}},{key:"joints",get:function(){return this._joints}},{key:"tip",get:function(){return this._tip}}]),t}(),$b=G.browser&&window.XRHand?["thumb-tip","index-finger-tip","middle-finger-tip","ring-finger-tip","pinky-finger-tip"]:[],Jb={},tw=0;tw<$b.length;tw++)Jb[$b[tw]]=!0;var ew=function(){function t(t,e,i,n){void 0===n&&(n=null),this._index=void 0,this._id=void 0,this._hand=void 0,this._finger=void 0,this._wrist=void 0,this._tip=void 0,this._radius=null,this._localTransform=new Ft,this._worldTransform=new Ft,this._localPosition=new wt,this._localRotation=new Bt,this._position=new wt,this._rotation=new Bt,this._dirtyLocal=!0,this._index=t,this._id=e,this._hand=i,this._finger=n,this._wrist="wrist"===e,this._tip=this._finger&&!!Jb[e]}var e=t.prototype;return e.update=function(t){this._dirtyLocal=!0,this._radius=t.radius,this._localPosition.copy(t.transform.position),this._localRotation.copy(t.transform.orientation)},e._updateTransforms=function(){this._dirtyLocal&&(this._dirtyLocal=!1,this._localTransform.setTRS(this._localPosition,this._localRotation,wt.ONE));var t=this._hand._manager.camera.parent;t?this._worldTransform.mul2(t.getWorldTransform(),this._localTransform):this._worldTransform.copy(this._localTransform)},e.getPosition=function(){return this._updateTransforms(),this._worldTransform.getTranslation(this._position),this._position},e.getRotation=function(){return this._updateTransforms(),this._rotation.setFromMat4(this._worldTransform),this._rotation},y(t,[{key:"index",get:function(){return this._index}},{key:"hand",get:function(){return this._hand}},{key:"finger",get:function(){return this._finger}},{key:"wrist",get:function(){return this._wrist}},{key:"tip",get:function(){return this._tip}},{key:"radius",get:function(){return this._radius||.005}}]),t}(),iw=[],nw=new wt,sw=new wt,rw=new wt;G.browser&&window.XRHand&&(iw=[["thumb-metacarpal","thumb-phalanx-proximal","thumb-phalanx-distal","thumb-tip"],["index-finger-metacarpal","index-finger-phalanx-proximal","index-finger-phalanx-intermediate","index-finger-phalanx-distal","index-finger-tip"],["middle-finger-metacarpal","middle-finger-phalanx-proximal","middle-finger-phalanx-intermediate","middle-finger-phalanx-distal","middle-finger-tip"],["ring-finger-metacarpal","ring-finger-phalanx-proximal","ring-finger-phalanx-intermediate","ring-finger-phalanx-distal","ring-finger-tip"],["pinky-finger-metacarpal","pinky-finger-phalanx-proximal","pinky-finger-phalanx-intermediate","pinky-finger-phalanx-distal","pinky-finger-tip"]]);var aw,ow,hw=function(t){function e(e){var i;(i=t.call(this)||this)._manager=void 0,i._inputSource=void 0,i._tracking=!1,i._fingers=[],i._joints=[],i._jointsById={},i._tips=[],i._wrist=null;var n=e._xrInputSource.hand;if(i._manager=e._manager,i._inputSource=e,n.get("wrist")){var s=new ew(0,"wrist",w(i),null);i._wrist=s,i._joints.push(s),i._jointsById.wrist=s}for(var r=0;r<iw.length;r++)for(var a=new Qb(r,w(i)),o=0;o<iw[r].length;o++){var h=iw[r][o];if(n.get(h)){var l=new ew(o,h,w(i),a);i._joints.push(l),i._jointsById[h]=l,l.tip&&(i._tips.push(l),a._tip=l),a._joints.push(l)}}return i}S(e,t);var i=e.prototype;return i.update=function(t){for(var e=this._inputSource._xrInputSource,i=0;i<this._joints.length;i++){var n=this._joints[i],s=e.hand.get(n._id);if(s){var r=void 0;if("hidden"!==t.session.visibilityState&&(r=t.getJointPose(s,this._manager._referenceSpace)),r)n.update(r),n.wrist&&!this._tracking&&(this._tracking=!0,this.fire("tracking"));else if(n.wrist){this._tracking&&(this._tracking=!1,this.fire("trackinglost"));break}}}var a=this._jointsById["thumb-metacarpal"],o=this._jointsById["thumb-tip"],h=this._jointsById["index-finger-phalanx-proximal"],l=this._jointsById["index-finger-tip"],c=this._jointsById["ring-finger-phalanx-proximal"],u=this._jointsById["pinky-finger-phalanx-proximal"];if(a&&o&&h&&l&&c&&u){this._inputSource._dirtyRay=!0,this._inputSource._rayLocal.origin.lerp(o._localPosition,l._localPosition,.5);var d=a,f=u;if(this._inputSource.handedness===Nb){var p=d;d=f,f=p}nw.sub2(d._localPosition,this._wrist._localPosition),sw.sub2(f._localPosition,this._wrist._localPosition),rw.cross(nw,sw).normalize(),nw.lerp(h._localPosition,c._localPosition,.5),nw.sub(this._wrist._localPosition).normalize(),this._inputSource._rayLocal.direction.lerp(rw,nw,.5).normalize()}this._fingerIsClosed(1)&&this._fingerIsClosed(2)&&this._fingerIsClosed(3)&&this._fingerIsClosed(4)?this._inputSource._squeezing||(this._inputSource._squeezing=!0,this._inputSource.fire("squeezestart"),this._manager.input.fire("squeezestart",this._inputSource)):this._inputSource._squeezing&&(this._inputSource._squeezing=!1,this._inputSource.fire("squeeze"),this._manager.input.fire("squeeze",this._inputSource),this._inputSource.fire("squeezeend"),this._manager.input.fire("squeezeend",this._inputSource))},i._fingerIsClosed=function(t){var e=this._fingers[t];return nw.sub2(e.joints[0]._localPosition,e.joints[1]._localPosition).normalize(),sw.sub2(e.joints[2]._localPosition,e.joints[3]._localPosition).normalize(),nw.dot(sw)<-.8},i.getJointById=function(t){return this._jointsById[t]||null},y(e,[{key:"fingers",get:function(){return this._fingers}},{key:"joints",get:function(){return this._joints}},{key:"tips",get:function(){return this._tips}},{key:"wrist",get:function(){return this._wrist}},{key:"tracking",get:function(){return this._tracking}}]),e}(P),lw=new Bt,cw=0,uw=function(t){function e(e,i){var n;return(n=t.call(this)||this)._id=void 0,n._manager=void 0,n._xrInputSource=void 0,n._ray=new Yt,n._rayLocal=new Yt,n._grip=!1,n._hand=null,n._localTransform=null,n._worldTransform=null,n._position=new wt,n._rotation=new Bt,n._localPosition=null,n._localRotation=null,n._dirtyLocal=!0,n._dirtyRay=!1,n._selecting=!1,n._squeezing=!1,n._elementInput=!0,n._elementEntity=null,n._hitTestSources=[],n._id=++cw,n._manager=e,n._xrInputSource=i,i.hand&&(n._hand=new hw(w(n))),n}S(e,t);var i=e.prototype;return i.update=function(t){if(this._hand)this._hand.update(t);else{if(this._xrInputSource.gripSpace){var e=t.getPose(this._xrInputSource.gripSpace,this._manager._referenceSpace);e&&(this._grip||(this._grip=!0,this._localTransform=new Ft,this._worldTransform=new Ft,this._localPosition=new wt,this._localRotation=new Bt),this._dirtyLocal=!0,this._localPosition.copy(e.transform.position),this._localRotation.copy(e.transform.orientation))}var i=t.getPose(this._xrInputSource.targetRaySpace,this._manager._referenceSpace);i&&(this._dirtyRay=!0,this._rayLocal.origin.copy(i.transform.position),this._rayLocal.direction.set(0,0,-1),lw.copy(i.transform.orientation),lw.transformVector(this._rayLocal.direction,this._rayLocal.direction))}},i._updateTransforms=function(){this._dirtyLocal&&(this._dirtyLocal=!1,this._localTransform.setTRS(this._localPosition,this._localRotation,wt.ONE));var t=this._manager.camera.parent;t?this._worldTransform.mul2(t.getWorldTransform(),this._localTransform):this._worldTransform.copy(this._localTransform)},i._updateRayTransforms=function(){var t=this._dirtyRay;if(this._dirtyRay=!1,this._manager.camera.parent){var e=this._manager.camera.parent.getWorldTransform();e.getTranslation(this._position),this._rotation.setFromMat4(e),this._rotation.transformVector(this._rayLocal.origin,this._ray.origin),this._ray.origin.add(this._position),this._rotation.transformVector(this._rayLocal.direction,this._ray.direction)}else t&&(this._ray.origin.copy(this._rayLocal.origin),this._ray.direction.copy(this._rayLocal.direction))},i.getPosition=function(){return this._position?(this._updateTransforms(),this._worldTransform.getTranslation(this._position),this._position):null},i.getLocalPosition=function(){return this._localPosition},i.getRotation=function(){return this._rotation?(this._updateTransforms(),this._rotation.setFromMat4(this._worldTransform),this._rotation):null},i.getLocalRotation=function(){return this._localRotation},i.getOrigin=function(){return this._updateRayTransforms(),this._ray.origin},i.getDirection=function(){return this._updateRayTransforms(),this._ray.direction},i.hitTestStart=function(t){var e=this;void 0===t&&(t={}),t.profile=this._xrInputSource.profiles[0];var i=t.callback;t.callback=function(t,n){n&&e.onHitTestSourceAdd(n),i&&i(t,n)},this._manager.hitTest.start(t)},i.onHitTestSourceAdd=function(t){this._hitTestSources.push(t),this.fire("hittest:add",t),t.on("result",(function(e,i,n){n===this&&this.fire("hittest:result",t,e,i)}),this),t.once("remove",(function(){this.onHitTestSourceRemove(t),this.fire("hittest:remove",t)}),this)},i.onHitTestSourceRemove=function(t){var e=this._hitTestSources.indexOf(t);-1!==e&&this._hitTestSources.splice(e,1)},y(e,[{key:"id",get:function(){return this._id}},{key:"inputSource",get:function(){return this._xrInputSource}},{key:"targetRayMode",get:function(){return this._xrInputSource.targetRayMode}},{key:"handedness",get:function(){return this._xrInputSource.handedness}},{key:"profiles",get:function(){return this._xrInputSource.profiles}},{key:"grip",get:function(){return this._grip}},{key:"hand",get:function(){return this._hand}},{key:"gamepad",get:function(){return this._xrInputSource.gamepad||null}},{key:"selecting",get:function(){return this._selecting}},{key:"squeezing",get:function(){return this._squeezing}},{key:"elementInput",get:function(){return this._elementInput},set:function(t){this._elementInput!==t&&(this._elementInput=t,this._elementInput||(this._elementEntity=null))}},{key:"elementEntity",get:function(){return this._elementEntity}},{key:"hitTestSources",get:function(){return this._hitTestSources}}]),e}(P),dw=function(t){function e(e){var i;return(i=t.call(this)||this).manager=void 0,i._inputSources=[],i._onInputSourcesChangeEvt=void 0,i.manager=e,i._onInputSourcesChangeEvt=function(t){i._onInputSourcesChange(t)},i.manager.on("start",i._onSessionStart,w(i)),i.manager.on("end",i._onSessionEnd,w(i)),i}S(e,t);var i=e.prototype;return i._onSessionStart=function(){var t=this,e=this.manager.session;e.addEventListener("inputsourceschange",this._onInputSourcesChangeEvt),e.addEventListener("select",(function(e){var i=t._getByInputSource(e.inputSource);i.update(e.frame),i.fire("select",e),t.fire("select",i,e)})),e.addEventListener("selectstart",(function(e){var i=t._getByInputSource(e.inputSource);i.update(e.frame),i._selecting=!0,i.fire("selectstart",e),t.fire("selectstart",i,e)})),e.addEventListener("selectend",(function(e){var i=t._getByInputSource(e.inputSource);i.update(e.frame),i._selecting=!1,i.fire("selectend",e),t.fire("selectend",i,e)})),e.addEventListener("squeeze",(function(e){var i=t._getByInputSource(e.inputSource);i.update(e.frame),i.fire("squeeze",e),t.fire("squeeze",i,e)})),e.addEventListener("squeezestart",(function(e){var i=t._getByInputSource(e.inputSource);i.update(e.frame),i._squeezing=!0,i.fire("squeezestart",e),t.fire("squeezestart",i,e)})),e.addEventListener("squeezeend",(function(e){var i=t._getByInputSource(e.inputSource);i.update(e.frame),i._squeezing=!1,i.fire("squeezeend",e),t.fire("squeezeend",i,e)}));for(var i=e.inputSources,n=0;n<i.length;n++)this._addInputSource(i[n])},i._onSessionEnd=function(){for(var t=this._inputSources.length;t--;){var e=this._inputSources[t];this._inputSources.splice(t,1),e.fire("remove"),this.fire("remove",e)}this.manager.session.removeEventListener("inputsourceschange",this._onInputSourcesChangeEvt)},i._onInputSourcesChange=function(t){for(var e=0;e<t.removed.length;e++)this._removeInputSource(t.removed[e]);for(var i=0;i<t.added.length;i++)this._addInputSource(t.added[i])},i._getByInputSource=function(t){for(var e=0;e<this._inputSources.length;e++)if(this._inputSources[e].inputSource===t)return this._inputSources[e];return null},i._addInputSource=function(t){if(!this._getByInputSource(t)){var e=new uw(this.manager,t);this._inputSources.push(e),this.fire("add",e)}},i._removeInputSource=function(t){for(var e=0;e<this._inputSources.length;e++)if(this._inputSources[e].inputSource===t){var i=this._inputSources[e];this._inputSources.splice(e,1);for(var n=i.hitTestSources.length;n--;)i.hitTestSources[n].remove();return i.fire("remove"),void this.fire("remove",i)}},i.update=function(t){for(var e=0;e<this._inputSources.length;e++)this._inputSources[e].update(t)},y(e,[{key:"inputSources",get:function(){return this._inputSources}}]),e}(P),fw=new wt,pw=new wt,mw=new Ft,_w=new Ft,vw=function(t){function e(e){var i;return(i=t.call(this)||this)._manager=void 0,i._supported=!1,i._available=!1,i._lightProbeRequested=!1,i._lightProbe=null,i._intensity=0,i._rotation=new Bt,i._color=new vt,i._sphericalHarmonics=new Float32Array(27),i._manager=e,i._manager.on("start",i._onSessionStart,w(i)),i._manager.on("end",i._onSessionEnd,w(i)),i}S(e,t);var i=e.prototype;return i._onSessionStart=function(){!!this._manager.session.requestLightProbe&&(this._supported=!0)},i._onSessionEnd=function(){this._supported=!1,this._available=!1,this._lightProbeRequested=!1,this._lightProbe=null},i.start=function(){var t,e=this;this._manager.session||(t=new Error("XR session is not running")),t||this._manager.type===Bb||(t=new Error("XR session type is not AR")),t||this._supported||(t=new Error("light-estimation is not supported")),(!t&&this._lightProbe||this._lightProbeRequested)&&(t=new Error("light estimation is already requested")),t?this.fire("error",t):(this._lightProbeRequested=!0,this._manager.session.requestLightProbe().then((function(t){var i=e._lightProbeRequested;e._lightProbeRequested=!1,e._manager.active?i&&(e._lightProbe=t):e.fire("error",new Error("XR session is not active"))})).catch((function(t){e._lightProbeRequested=!1,e.fire("error",t)})))},i.end=function(){this._lightProbeRequested=!1,this._lightProbe=null,this._available=!1},i.update=function(t){if(this._lightProbe){var e=t.getLightEstimate(this._lightProbe);if(e){this._available||(this._available=!0,this.fire("available"));var i=e.primaryLightIntensity;this._intensity=Math.max(1,Math.max(i.x,Math.max(i.y,i.z))),fw.copy(i).mulScalar(1/this._intensity),this._color.set(fw.x,fw.y,fw.z),fw.set(0,0,0),pw.copy(e.primaryLightDirection),mw.setLookAt(pw,fw,wt.UP),_w.setFromAxisAngle(wt.RIGHT,90),mw.mul(_w),this._rotation.setFromMat4(mw),this._sphericalHarmonics.set(e.sphericalHarmonicsCoefficients)}}},y(e,[{key:"supported",get:function(){return this._supported}},{key:"available",get:function(){return this._available}},{key:"intensity",get:function(){return this._available?this._intensity:null}},{key:"color",get:function(){return this._available?this._color:null}},{key:"rotation",get:function(){return this._available?this._rotation:null}},{key:"sphericalHarmonics",get:function(){return this._available?this._sphericalHarmonics:null}}]),e}(P),gw=0,yw=function(t){function e(e,i){var n;return(n=t.call(this)||this)._id=void 0,n._planeDetection=void 0,n._xrPlane=void 0,n._lastChangedTime=void 0,n._orientation=void 0,n._position=new wt,n._rotation=new Bt,n._id=++gw,n._planeDetection=e,n._xrPlane=i,n._lastChangedTime=i.lastChangedTime,n._orientation=i.orientation,n}S(e,t);var i=e.prototype;return i.destroy=function(){this.fire("remove")},i.update=function(t){var e=this._planeDetection._manager,i=t.getPose(this._xrPlane.planeSpace,e._referenceSpace);i&&(this._position.copy(i.transform.position),this._rotation.copy(i.transform.orientation)),this._lastChangedTime!==this._xrPlane.lastChangedTime&&(this._lastChangedTime=this._xrPlane.lastChangedTime,this.fire("change"))},i.getPosition=function(){return this._position},i.getRotation=function(){return this._rotation},y(e,[{key:"id",get:function(){return this._id}},{key:"orientation",get:function(){return this._orientation}},{key:"points",get:function(){return this._xrPlane.polygon}}]),e}(P),xw=function(t){function e(e){var i;return(i=t.call(this)||this)._manager=void 0,i._supported=G.browser&&!!window.XRPlane,i._available=!1,i._planesIndex=new Map,i._planes=null,i._manager=e,i._supported&&i._manager.on("end",i._onSessionEnd,w(i)),i}S(e,t);var i=e.prototype;return i._onSessionEnd=function(){if(this._planes)for(var t=0;t<this._planes.length;t++)this._planes[t].destroy();this._planesIndex.clear(),this._planes=null,this._available&&(this._available=!1,this.fire("unavailable"))},i.update=function(t){var e;if(this._available)e=t.detectedPlanes;else try{e=t.detectedPlanes,this._planes=[],this._available=!0,this.fire("available")}catch(t){return}for(var i,n=A(this._planesIndex);!(i=n()).done;){var s=i.value,r=s[0],a=s[1];e.has(r)||(this._planesIndex.delete(r),this._planes.splice(this._planes.indexOf(a),1),a.destroy(),this.fire("remove",a))}for(var o,h=A(e);!(o=h()).done;){var l=o.value,c=this._planesIndex.get(l);c?c.update(t):(c=new yw(this,l),this._planesIndex.set(l,c),this._planes.push(c),c.update(t),this.fire("add",c))}},y(e,[{key:"supported",get:function(){return this._supported}},{key:"available",get:function(){return this._available}},{key:"planes",get:function(){return this._planes}}]),e}(P),Sw=function(t){function e(e,i){var n;return(n=t.call(this)||this)._position=new wt,n._rotation=new Bt,n._anchors=e,n._xrAnchor=i,n}S(e,t);var i=e.prototype;return i.destroy=function(){if(this._xrAnchor){this._anchors._index.delete(this._xrAnchor);var t=this._anchors._list.indexOf(this);-1!==t&&this._anchors._list.splice(t,1),this._xrAnchor.delete(),this._xrAnchor=null,this.fire("destroy"),this._anchors.fire("destroy",this)}},i.update=function(t){if(this._xrAnchor){var e=t.getPose(this._xrAnchor.anchorSpace,this._anchors.manager._referenceSpace);if(e){if(this._position.equals(e.transform.position)&&this._rotation.equals(e.transform.orientation))return;this._position.copy(e.transform.position),this._rotation.copy(e.transform.orientation),this.fire("change")}}},i.getPosition=function(){return this._position},i.getRotation=function(){return this._rotation},e}(P),bw=function(t){function e(e){var i;return(i=t.call(this)||this)._supported=G.browser&&!!window.XRAnchor,i._creationQueue=[],i._index=new Map,i._list=[],i._callbacksAnchors=new Map,i.manager=e,i._supported&&i.manager.on("end",i._onSessionEnd,w(i)),i}S(e,t);var i=e.prototype;return i._onSessionEnd=function(){for(var t=0;t<this._creationQueue.length;t++)this._creationQueue[t].callback&&this._creationQueue[t].callback(new Error("session ended"),null);if(this._creationQueue.length=0,this._list){for(var e=this._list.length;e--;)this._list[e].destroy();this._list.length=0}},i.create=function(t,e,i){this._creationQueue.push({transform:new XRRigidTransform(t,e),callback:i})},i.update=function(t){var e=this;if(this._creationQueue.length){for(var i=function(){var i=e._creationQueue[n];t.createAnchor(i.transform,e.manager._referenceSpace).then((function(t){i.callback&&e._callbacksAnchors.set(t,i.callback)})).catch((function(t){i.callback&&i.callback(t,null),e.fire("error",t)}))},n=0;n<this._creationQueue.length;n++)i();this._creationQueue.length=0}for(var s,r=A(this._index);!(s=r()).done;){var a=s.value,o=a[0],h=a[1];t.trackedAnchors.has(o)||h.destroy()}for(var l=0;l<this._list.length;l++)this._list[l].update(t);for(var c,u=A(t.trackedAnchors);!(c=u()).done;){var d=c.value;if(!this._index.has(d)){try{d.anchorSpace}catch(t){continue}var f=new Sw(this,d);this._index.set(d,f),this._list.push(f),f.update(t);var p=this._callbacksAnchors.get(d);p&&(this._callbacksAnchors.delete(d),p(null,f)),this.fire("add",f)}}},y(e,[{key:"supported",get:function(){return this._supported}},{key:"list",get:function(){return this._list}}]),e}(P),ww=function(t){function e(e){var i;return(i=t.call(this)||this).app=void 0,i._supported=G.browser&&!!navigator.xr,i._available={},i._type=null,i._spaceType=null,i._session=null,i._baseLayer=null,i._referenceSpace=null,i.depthSensing=void 0,i.domOverlay=void 0,i.hitTest=void 0,i.imageTracking=void 0,i.planeDetection=void 0,i.input=void 0,i.lightEstimation=void 0,i._camera=null,i.views=[],i.viewsPool=[],i._localPosition=new wt,i._localRotation=new Bt,i._depthNear=.1,i._depthFar=1e3,i._width=0,i._height=0,i.app=e,i._available[kb]=!1,i._available[Fb]=!1,i._available[Bb]=!1,i.depthSensing=new Hb(w(i)),i.domOverlay=new Wb(w(i)),i.hitTest=new Yb(w(i)),i.imageTracking=new Zb(w(i)),i.planeDetection=new xw(w(i)),i.input=new dw(w(i)),i.lightEstimation=new vw(w(i)),i.anchors=new bw(w(i)),i._supported&&(navigator.xr.addEventListener("devicechange",(function(){i._deviceAvailabilityCheck()})),i._deviceAvailabilityCheck()),i}S(e,t);var i=e.prototype;return i.destroy=function(){this.depthSensing.destroy(),this.depthSensing=null},i.start=function(t,e,i,n){var s=this,r=n;if("object"==typeof n&&(r=n.callback),this._available[e])if(this._session)r&&r(new Error("XR session is already started"));else{this._camera=t,this._camera.camera.xr=this,this._type=e,this._spaceType=i,this._setClipPlanes(t.nearClip,t.farClip);var a={requiredFeatures:[i],optionalFeatures:[]};if(e===Bb){if(a.optionalFeatures.push("light-estimation"),a.optionalFeatures.push("hit-test"),n&&(n.imageTracking&&this.imageTracking.supported&&a.optionalFeatures.push("image-tracking"),n.planeDetection&&a.optionalFeatures.push("plane-detection")),this.domOverlay.supported&&this.domOverlay.root&&(a.optionalFeatures.push("dom-overlay"),a.domOverlay={root:this.domOverlay.root}),n&&n.anchors&&this.anchors.supported&&a.optionalFeatures.push("anchors"),n&&n.depthSensing&&this.depthSensing.supported){a.optionalFeatures.push("depth-sensing");var o=[zb],h=[Gb];if(n.depthSensing.usagePreference){var l=o.indexOf(n.depthSensing.usagePreference);-1!==l&&o.splice(l,1),o.unshift(n.depthSensing.usagePreference)}if(n.depthSensing.dataFormatPreference){var c=h.indexOf(n.depthSensing.dataFormatPreference);-1!==c&&h.splice(c,1),h.unshift(n.depthSensing.dataFormatPreference)}a.depthSensing={usagePreference:o,dataFormatPreference:h}}}else e===Fb&&a.optionalFeatures.push("hand-tracking");n&&n.optionalFeatures&&(a.optionalFeatures=a.optionalFeatures.concat(n.optionalFeatures)),this.imageTracking.supported&&this.imageTracking.images.length?this.imageTracking.prepareImages((function(t,n){if(t)return r&&r(t),void s.fire("error",t);null!==n&&(a.trackedImages=n),s._onStartOptionsReady(e,i,a,r)})):this._onStartOptionsReady(e,i,a,r)}else r&&r(new Error("XR is not available"))},i._onStartOptionsReady=function(t,e,i,n){var s=this;navigator.xr.requestSession(t,i).then((function(t){s._onSessionStart(t,e,n)})).catch((function(t){s._camera.camera.xr=null,s._camera=null,s._type=null,s._spaceType=null,n&&n(t),s.fire("error",t)}))},i.end=function(t){this._session?(t&&this.once("end",t),this._session.end()):t&&t(new Error("XR Session is not initialized"))},i.isAvailable=function(t){return this._available[t]},i._deviceAvailabilityCheck=function(){for(var t in this._available)this._sessionSupportCheck(t)},i._sessionSupportCheck=function(t){var e=this;navigator.xr.isSessionSupported(t).then((function(i){e._available[t]!==i&&(e._available[t]=i,e.fire("available",t,i),e.fire("available:"+t,i))})).catch((function(t){e.fire("error",t)}))},i._onSessionStart=function(t,e,i){var n=this,s=!1;this._session=t;var r=function(){n.fire("visibility:change",t.visibilityState)},a=function(){n._setClipPlanes(n._camera.nearClip,n._camera.farClip)};t.addEventListener("end",(function e(){n._camera&&(n._camera.off("set_nearClip",a),n._camera.off("set_farClip",a),n._camera.camera.xr=null,n._camera=null),t.removeEventListener("end",e),t.removeEventListener("visibilitychange",r),s||n.fire("end"),n._session=null,n._referenceSpace=null,n.views=[],n._width=0,n._height=0,n._type=null,n._spaceType=null,n.app.tick()})),t.addEventListener("visibilitychange",r),this._camera.on("set_nearClip",a),this._camera.on("set_farClip",a);var o=this.app.graphicsDevice.maxPixelRatio/window.devicePixelRatio;this._baseLayer=new XRWebGLLayer(t,this.app.graphicsDevice.gl,{alpha:!0,depth:!0,stencil:!0,framebufferScaleFactor:o,antialias:!1}),t.updateRenderState({baseLayer:this._baseLayer,depthNear:this._depthNear,depthFar:this._depthFar}),t.requestReferenceSpace(e).then((function(t){n._referenceSpace=t,n.app.tick(),i&&i(null),n.fire("start")})).catch((function(e){s=!0,t.end(),i&&i(e),n.fire("error",e)}))},i._setClipPlanes=function(t,e){this._depthNear===t&&this._depthFar===e||(this._depthNear=t,this._depthFar=e,this._session&&this._session.updateRenderState({depthNear:this._depthNear,depthFar:this._depthFar}))},i.update=function(t){if(!this._session)return!1;var e=t.session.renderState.baseLayer.framebufferWidth,i=t.session.renderState.baseLayer.framebufferHeight;this._width===e&&this._height===i||(this._width=e,this._height=i,this.app.graphicsDevice.setResolution(e,i));var n=t.getViewerPose(this._referenceSpace);if(!n)return!1;for(var s=this.views.length,r=n.views.length;r>this.views.length;){var a=this.viewsPool.pop();a||(a={viewport:new Pt,projMat:new Ft,viewMat:new Ft,viewOffMat:new Ft,viewInvMat:new Ft,viewInvOffMat:new Ft,projViewOffMat:new Ft,viewMat3:new At,position:new Float32Array(3),rotation:new Bt}),this.views.push(a)}for(;r<this.views.length;)this.viewsPool.push(this.views.pop());var o=n.transform.position,h=n.transform.orientation;this._localPosition.set(o.x,o.y,o.z),this._localRotation.set(h.x,h.y,h.z,h.w);for(var l=t.session.renderState.baseLayer,c=0;c<n.views.length;c++){var u=n.views[c],d=this.views[c],f=l.getViewport(u);d.viewport.x=f.x,d.viewport.y=f.y,d.viewport.z=f.width,d.viewport.w=f.height,d.projMat.set(u.projectionMatrix),d.viewMat.set(u.transform.inverse.matrix),d.viewInvMat.set(u.transform.matrix)}if(0===s&&this.views.length>0){var p=new Ft,m=this.views[0];p.copy(m.projMat);var _=p.data,v=2*Math.atan(1/_[5])*180/Math.PI,g=_[5]/_[0],y=_[14]/(_[10]+1),x=_[14]/(_[10]-1);this._camera.camera.setXrProperties({aspectRatio:g,farClip:y,fov:v,horizontalFov:!1,nearClip:x})}return this._camera.camera._node.setLocalPosition(this._localPosition),this._camera.camera._node.setLocalRotation(this._localRotation),this.input.update(t),this._type===Bb&&(this.hitTest.supported&&this.hitTest.update(t),this.lightEstimation.supported&&this.lightEstimation.update(t),this.depthSensing.supported&&this.depthSensing.update(t,n&&n.views[0]),this.imageTracking.supported&&this.imageTracking.update(t),this.anchors.supported&&this.anchors.update(t),this.planeDetection.supported&&this.planeDetection.update(t)),this.fire("update",t),!0},y(e,[{key:"supported",get:function(){return this._supported}},{key:"active",get:function(){return!!this._session}},{key:"type",get:function(){return this._type}},{key:"spaceType",get:function(){return this._spaceType}},{key:"session",get:function(){return this._session}},{key:"camera",get:function(){return this._camera?this._camera.entity:null}},{key:"visibilityState",get:function(){return this._session?this._session.visibilityState:null}}]),e}(P),Tw=function(t){function e(e,i){var n;void 0===i&&(i={}),n=t.call(this,e)||this;var s=new up;return s.graphicsDevice=n.createDevice(e,i),n.addComponentSystems(s),n.addResourceHandles(s),s.elementInput=i.elementInput,s.keyboard=i.keyboard,s.mouse=i.mouse,s.touch=i.touch,s.gamepads=i.gamepads,s.scriptPrefix=i.scriptPrefix,s.assetPrefix=i.assetPrefix,s.scriptsOrder=i.scriptsOrder,s.soundManager=new Ta,s.lightmapper=Sp,s.batchManager=Eh,s.xr=ww,n.init(s),n}S(e,t);var i=e.prototype;return i.createDevice=function(t,e){return e.graphicsDeviceOptions||(e.graphicsDeviceOptions={}),G.browser&&navigator.xr&&(e.graphicsDeviceOptions.xrCompatible=!0),e.graphicsDeviceOptions.alpha=e.graphicsDeviceOptions.alpha||!1,new lr(t,e.graphicsDeviceOptions)},i.addComponentSystems=function(t){t.componentSystems=[Ig,L_,Cv,cm,Im,Zv,fg,Ny,Xy,bf.legacy?Yg:ex,Nm,gy,km,rg,Ug,vv,s_,hy,dy,Py,jv,Rv,Dy]},i.addResourceHandles=function(t){t.resourceHandlers=[ax,uS,dS,fS,jS,US,Ob,eb,OS,_S,YS,qS,wS,DS,bS,KS,LS,TS,ES,vS,rb,$S,tb,SS]},e}(hp),Aw=function(t){function e(e,i){var n;return(n=t.call(this)||this)._assets=new Set,n._loadingAssets=new Set,n._waitingAssets=new Set,n._registry=i,n._loading=!1,n._loaded=!1,n._failed=[],e.forEach((function(t){if(t instanceof Vf)t.registry||(t.registry=i),n._assets.add(t);else{var e=i.get(t);e?n._assets.add(e):n._waitForAsset(t)}})),n}S(e,t);var i=e.prototype;return i.destroy=function(){var t=this;this._registry.off("load",this._onLoad),this._registry.off("error",this._onError),this._waitingAssets.forEach((function(e){t._registry.off("add:"+e,this._onAddAsset)})),this.off("progress"),this.off("load")},i._assetHasDependencies=function(t){var e;return"model"===t.type&&(null==(e=t.file)?void 0:e.url)&&t.file.url&&t.file.url.match(/.json$/g)},i.load=function(t,e){var i=this;if(!this._loading){this._loading=!0,this._callback=t,this._scope=e,this._registry.on("load",this._onLoad,this),this._registry.on("error",this._onError,this);var n=!1;this._assets.forEach((function(t){t.loaded||(n=!0,i._assetHasDependencies(t)&&i._registry.loadFromUrl(t.file.url,t.type,(function(e,n){e?i._onError(e,t):i._onLoad(t)})),i._loadingAssets.add(t),i._registry.add(t))})),this._loadingAssets.forEach((function(t){i._assetHasDependencies(t)||i._registry.load(t)})),n||0!==this._waitingAssets.size||this._loadingComplete()}},i.ready=function(t,e){void 0===e&&(e=this),this._loaded?t.call(e,Array.from(this._assets)):this.once("load",(function(i){t.call(e,i)}))},i._loadingComplete=function(){this._loaded||(this._loaded=!0,this._registry.off("load",this._onLoad,this),this._registry.off("error",this._onError,this),this._failed.length?(this._callback&&this._callback.call(this._scope,"Failed to load some assets",this._failed),this.fire("error",this._failed)):(this._callback&&this._callback.call(this._scope),this.fire("load",Array.from(this._assets))))},i._onLoad=function(t){var e=this;this._loadingAssets.has(t)&&(this.fire("progress",t),this._loadingAssets.delete(t)),0===this._loadingAssets.size&&setTimeout((function(){e._loadingComplete(e._failed)}),0)},i._onError=function(t,e){var i=this;this._loadingAssets.has(e)&&(this._failed.push(e),this._loadingAssets.delete(e)),0===this._loadingAssets.size&&setTimeout((function(){i._loadingComplete(i._failed)}),0)},i._onAddAsset=function(t){this._waitingAssets.delete(t),this._assets.add(t),t.loaded||(this._loadingAssets.add(t),this._registry.load(t))},i._waitForAsset=function(t){this._waitingAssets.add(t),this._registry.once("add:"+t,this._onAddAsset,this)},e}(P),Cw=function(){function t(t,e,i,n){this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=i,this.texture=new Ls(t,{name:n,format:7,width:e,height:i,mipmaps:!0,minFilter:5,magFilter:1,addressU:1,addressV:1,levels:[this.canvas]}),this.ctx=this.canvas.getContext("2d",{alpha:!0})}var e=t.prototype;return e.destroy=function(){this.texture.destroy()},e.clear=function(t){var e=this.canvas,i=e.width,n=e.height;this.ctx.clearRect(0,0,i,n),this.ctx.fillStyle=t,this.ctx.fillRect(0,0,i,n)},t}(),Ew=function(t){function e(e,i){var n;return void 0===i&&(i={}),(n=t.call(this)||this).type="bitmap",n.app=e,n.intensity=0,n.fontWeight=i.fontWeight||"normal",n.fontSize=parseInt(i.fontSize,10),n.glyphSize=n.fontSize,n.fontName=i.fontName||"Arial",n.color=i.color||new vt(1,1,1),n.padding=i.padding||0,n.width=Math.min(4096,i.width||512),n.height=Math.min(4096,i.height||512),n.atlases=[],n.chars="",n.data={},n}S(e,t);var i=e.prototype;return i.createTextures=function(t){var e=this._normalizeCharsSet(t);if(e.length===this.chars.length){for(var i=0;i<e.length;i++)if(e[i]!==this.chars[i])return void this._renderAtlas(e)}else this._renderAtlas(e)},i.updateTextures=function(t){for(var e=this._normalizeCharsSet(t),i=[],n=0;n<e.length;n++){var s=e[n];this.data.chars[s]||i.push(s)}i.length>0&&this._renderAtlas(this.chars.concat(i))},i.destroy=function(){this.atlases.forEach((function(t){return t.destroy()})),this.chars=null,this.color=null,this.data=null,this.fontName=null,this.fontSize=null,this.glyphSize=null,this.intensity=null,this.atlases=null,this.type=null,this.fontWeight=null},i._colorToRgbString=function(t,e){var i=Math.round(255*t.r),n=Math.round(255*t.g),s=Math.round(255*t.b);return e?"rgba("+i+", "+n+", "+s+", "+t.a+")":"rgb("+i+", "+n+", "+s+")"},i.renderCharacter=function(t,e,i,n,s){t.fillStyle=s,t.fillText(e,i,n)},i._getAtlas=function(t){return t>=this.atlases.length&&(this.atlases[t]=new Cw(this.app.graphicsDevice,this.width,this.height,"font-atlas-"+this.fontName+"-"+t)),this.atlases[t]},i._renderAtlas=function(t){this.chars=t;var e=this.width,i=this.height,n=this._colorToRgbString(this.color,!1),s=this.color.a;this.color.a=1/255;var r=this._colorToRgbString(this.color,!0);this.color.a=s;var a=0,o=this._getAtlas(a++);o.clear(r),this.data=this._createJson(this.chars,this.fontName,e,i);for(var h=rt.getSymbols(this.chars.join("")),l=0,c=0,u={},d=0;d<h.length;d++){var f=h[d];u[f]=this._getTextMetrics(f),l=Math.max(l,u[f].height),c=Math.max(c,u[f].descent)}this.glyphSize=Math.max(this.glyphSize,l);for(var p=this.glyphSize+2*this.padding,m=this.glyphSize+2*this.padding,_=this.glyphSize/2+this.padding,v=m-c-this.padding,g=0,y=0,x=0;x<h.length;x++){var S=h[x],b=rt.getCodePoint(h[x]),w=this.fontSize;o.ctx.font=this.fontWeight+" "+w.toString()+"px "+this.fontName,o.ctx.textAlign="center",o.ctx.textBaseline="alphabetic";var T=o.ctx.measureText(S).width;T>w&&(w=this.fontSize*this.fontSize/T,o.ctx.font=this.fontWeight+" "+w.toString()+"px "+this.fontName,T=this.fontSize),this.renderCharacter(o.ctx,S,g+_,y+v,n);var A=this.padding+(this.glyphSize-T)/2,C=-this.padding+u[S].descent-c,E=T;this._addChar(this.data,S,b,g,y,p,m,A,C,E,a-1,e,i),(g+=p)+p>e&&(g=0,(y+=m)+m>i&&((o=this._getAtlas(a++)).clear(r),y=0))}this.atlases.splice(a).forEach((function(t){return t.destroy()})),this.atlases.forEach((function(t){return t.texture.upload()})),this.fire("render")},i._createJson=function(t,e,i,n){return{version:3,intensity:this.intensity,info:{face:e,width:i,height:n,maps:[{width:i,height:n}]},chars:{}}},i._addChar=function(t,e,i,n,s,r,a,o,h,l,c,u,d){t.info.maps.length<c+1&&t.info.maps.push({width:u,height:d});var f=this.fontSize/32;t.chars[e]={id:i,letter:e,x:n,y:s,width:r,height:a,xadvance:l/f,xoffset:o/f,yoffset:(h+this.padding)/f,scale:f,range:1,map:c,bounds:[0,0,r/f,a/f]}},i._normalizeCharsSet=function(t){var e=this.app.systems.element.getUnicodeConverter();e&&(t=e(t));for(var i={},n=rt.getSymbols(t),s=0;s<n.length;s++){var r=n[s];i[r]||(i[r]=r)}return Object.keys(i).sort()},i._getTextMetrics=function(t){var e=document.createElement("span");e.id="content-span",e.innerHTML=t;var i=document.createElement("div");i.id="content-block",i.style.display="inline-block",i.style.width="1px",i.style.height="0px";var n=document.createElement("div");n.appendChild(e),n.appendChild(i),n.style.font=this.fontSize+"px "+this.fontName,document.body.appendChild(n);var s=-1,r=-1,a=-1;try{i.style["vertical-align"]="baseline",s=i.offsetTop-e.offsetTop,i.style["vertical-align"]="bottom",r=(a=i.offsetTop-e.offsetTop)-s}finally{document.body.removeChild(n)}return{ascent:s,descent:r,height:a}},y(e,[{key:"textures",get:function(){return this.atlases.map((function(t){return t.texture}))}}]),e}(P),Mw=[],Pw=[[],[],[]],Rw=function(t){function e(e,i){var n;return(n=t.call(this,e)||this).pickColor=new Float32Array(4),n.renderer=i,n}S(e,t);var i=e.prototype;return i.update=function(t,e,i,n){this.camera=t,this.scene=e,this.layers=i,this.mapping=n},i.execute=function(){for(var t=this.device,e=this.renderer,i=this.camera,n=this.scene,s=this.layers,r=this.mapping,a=this.renderTarget,o=n.layers.layerList,h=n.layers.subLayerEnabled,l=n.layers.subLayerList,c=t.scope.resolve("uColor"),u=this.pickColor,d=0;d<o.length;d++){var f=o[d];if(!(s&&s.indexOf(f)<0)&&(f.enabled&&h[d]&&f.camerasSet.has(i.camera))){var p=l[d];f._clearDepthBuffer&&e.clear(i.camera,!1,!0,!1);for(var m=f.meshInstances,_=0;_<m.length;_++){var v=m[_];v.pick&&v.transparent===p&&(Mw.push(v),r.set(v.id,v))}Mw.length>0&&(e.setCameraUniforms(i.camera,a),e.renderForward(i.camera,Mw,Pw,3,(function(e){var i=e.id;u[0]=(i>>16&255)/255,u[1]=(i>>8&255)/255,u[2]=(255&i)/255,u[3]=(i>>24&255)/255,c.setValue(u),t.setBlendState(Ui.NOBLEND)})),Mw.length=0)}}},e}(uo),Iw=new Set,Lw=function(){function t(t,e,i){this.renderTarget=null,this.mapping=new Map,t instanceof nn&&(t=vf()),this.renderer=t.renderer,this.device=t.graphicsDevice,this.renderPass=new Rw(this.device,t.renderer),this.width=0,this.height=0,this.resize(e,i)}var e=t.prototype;return e.getSelection=function(t,e,i,n){var s=this.device;if("object"==typeof t){var r=t;t=r.x,e=r.y,i=r.width,n=r.height}else e=this.renderTarget.height-(e+(n||1));t=Math.floor(t),e=Math.floor(e),i=Math.floor(Math.max(i||1,1)),n=Math.floor(Math.max(n||1,1)),s.setRenderTarget(this.renderTarget),s.updateBegin();var a=new Uint8Array(4*i*n);s.readPixels(t,e,i,n,a),s.updateEnd();for(var o=this.mapping,h=0;h<i*n;h++){var l=a[4*h+0],c=a[4*h+1],u=a[4*h+2],d=a[4*h+3]<<24|l<<16|c<<8|u;-1!==d&&Iw.add(o.get(d))}var f=[];return Iw.forEach((function(t){return f.push(t)})),Iw.clear(),f},e.allocateRenderTarget=function(){var t=new Ls(this.device,{format:7,width:this.width,height:this.height,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1,name:"pick"});this.renderTarget=new rn({colorBuffer:t,depth:!0})},e.releaseRenderTarget=function(){this.renderTarget&&(this.renderTarget.destroyTextureBuffers(),this.renderTarget.destroy(),this.renderTarget=null)},e.prepare=function(t,e,i){t instanceof Gh&&(t=t.node.camera),i instanceof Cu&&(i=[i]),this.renderTarget&&this.width===this.renderTarget.width&&this.height===this.renderTarget.height||(this.releaseRenderTarget(),this.allocateRenderTarget()),this.mapping.clear();var n=this.renderPass;n.init(this.renderTarget),n.colorOps.clearValue=vt.WHITE,n.colorOps.clear=!0,n.depthStencilOps.clearDepth=!0,n.update(t,e,i,this.mapping),n.render()},e.resize=function(t,e){this.width=Math.floor(t),this.height=Math.floor(e)},t}(),Dw=function(){function t(){}var e=t.prototype;return e.load=function(t,e,i){throw new Error("not implemented")},e.open=function(t,e,i){throw new Error("not implemented")},e.patch=function(t,e){},t}(),Ow=function(){function t(t){this._app=t,this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){IS.load(t,this.maxRetries,e)},e.open=function(t,e){return e.settings},t}(),kw=new wt,Fw=new wt,Bw=new Yt,Uw=new Yt,Nw=new Yt;Bw.end=new wt,Uw.end=new wt,Nw.end=new wt;var zw=new wt,Vw=new wt,Gw=new wt,Hw=new wt,Ww=new wt,Xw=new wt,jw=new wt,qw=new wt,Yw=new wt,Kw=new wt,Zw=new wt,Qw=new wt,$w=new wt,Jw=new wt,tT=new wt,eT=new wt,iT=new wt,nT=new wt,sT=new wt,rT=new wt,aT=new Pt;function oT(t,e,i){return Zw.cross(t,e).dot(i)}var hT=function(){function t(t,e,i){this.event=t,this.element=e,this.camera=i,this._stopPropagation=!1}return t.prototype.stopPropagation=function(){this._stopPropagation=!0,this.event&&(this.event.stopImmediatePropagation(),this.event.stopPropagation())},t}(),lT=function(t){function e(e,i,n,s,r,a,o){var h;return(h=t.call(this,e,i,n)||this).x=s,h.y=r,h.ctrlKey=e.ctrlKey||!1,h.altKey=e.altKey||!1,h.shiftKey=e.shiftKey||!1,h.metaKey=e.metaKey||!1,h.button=e.button,Zr.isPointerLocked()?(h.dx=e.movementX||e.webkitMovementX||e.mozMovementX||0,h.dy=e.movementY||e.webkitMovementY||e.mozMovementY||0):(h.dx=s-a,h.dy=r-o),h.wheelDelta=0,"wheel"===e.type&&(e.deltaY>0?h.wheelDelta=1:e.deltaY<0&&(h.wheelDelta=-1)),h}return S(e,t),e}(hT),cT=function(t){function e(e,i,n,s,r,a){var o;return(o=t.call(this,e,i,n)||this).touches=e.touches,o.changedTouches=e.changedTouches,o.x=s,o.y=r,o.touch=a,o}return S(e,t),e}(hT),uT=function(t){function e(e,i,n,s){var r;return(r=t.call(this,e,i,n)||this).inputSource=s,r}return S(e,t),e}(hT),dT=function(){function t(t,e){this._app=null,this._attached=!1,this._target=null,this._enabled=!0,this._lastX=0,this._lastY=0,this._upHandler=this._handleUp.bind(this),this._downHandler=this._handleDown.bind(this),this._moveHandler=this._handleMove.bind(this),this._wheelHandler=this._handleWheel.bind(this),this._touchstartHandler=this._handleTouchStart.bind(this),this._touchendHandler=this._handleTouchEnd.bind(this),this._touchcancelHandler=this._touchendHandler,this._touchmoveHandler=this._handleTouchMove.bind(this),this._sortHandler=this._sortElements.bind(this),this._elements=[],this._hoveredElement=null,this._pressedElement=null,this._touchedElements={},this._touchesForWhichTouchLeaveHasFired={},this._selectedElements={},this._selectedPressedElements={},this._useMouse=!e||!1!==e.useMouse,this._useTouch=!e||!1!==e.useTouch,this._useXr=!e||!1!==e.useXr,this._selectEventsAttached=!1,G.touch&&(this._clickedEntities={}),this.attach(t)}var e=t.prototype;return e.attach=function(t){this._attached&&(this._attached=!1,this.detach()),this._target=t,this._attached=!0;var e=!!G.passiveEvents&&{passive:!0};this._useMouse&&(window.addEventListener("mouseup",this._upHandler,e),window.addEventListener("mousedown",this._downHandler,e),window.addEventListener("mousemove",this._moveHandler,e),window.addEventListener("wheel",this._wheelHandler,e)),this._useTouch&&G.touch&&(this._target.addEventListener("touchstart",this._touchstartHandler,e),this._target.addEventListener("touchend",this._touchendHandler,!1),this._target.addEventListener("touchmove",this._touchmoveHandler,!1),this._target.addEventListener("touchcancel",this._touchcancelHandler,!1)),this.attachSelectEvents()},e.attachSelectEvents=function(){!this._selectEventsAttached&&this._useXr&&this.app&&this.app.xr&&this.app.xr.supported&&(this._clickedEntities||(this._clickedEntities={}),this._selectEventsAttached=!0,this.app.xr.on("start",this._onXrStart,this))},e.detach=function(){if(this._attached){this._attached=!1;var t=!!G.passiveEvents&&{passive:!0};this._useMouse&&(window.removeEventListener("mouseup",this._upHandler,t),window.removeEventListener("mousedown",this._downHandler,t),window.removeEventListener("mousemove",this._moveHandler,t),window.removeEventListener("wheel",this._wheelHandler,t)),this._useTouch&&(this._target.removeEventListener("touchstart",this._touchstartHandler,t),this._target.removeEventListener("touchend",this._touchendHandler,!1),this._target.removeEventListener("touchmove",this._touchmoveHandler,!1),this._target.removeEventListener("touchcancel",this._touchcancelHandler,!1)),this._selectEventsAttached&&(this._selectEventsAttached=!1,this.app.xr.off("start",this._onXrStart,this),this.app.xr.off("end",this._onXrEnd,this),this.app.xr.off("update",this._onXrUpdate,this),this.app.xr.input.off("selectstart",this._onSelectStart,this),this.app.xr.input.off("selectend",this._onSelectEnd,this),this.app.xr.input.off("remove",this._onXrInputRemove,this)),this._target=null}},e.addElement=function(t){-1===this._elements.indexOf(t)&&this._elements.push(t)},e.removeElement=function(t){var e=this._elements.indexOf(t);-1!==e&&this._elements.splice(e,1)},e._handleUp=function(t){this._enabled&&(Zr.isPointerLocked()||(this._calcMouseCoords(t),this._onElementMouseEvent("mouseup",t)))},e._handleDown=function(t){this._enabled&&(Zr.isPointerLocked()||(this._calcMouseCoords(t),this._onElementMouseEvent("mousedown",t)))},e._handleMove=function(t){this._enabled&&(this._calcMouseCoords(t),this._onElementMouseEvent("mousemove",t),this._lastX=aw,this._lastY=ow)},e._handleWheel=function(t){this._enabled&&(this._calcMouseCoords(t),this._onElementMouseEvent("mousewheel",t))},e._determineTouchedElements=function(t){for(var e={},i=this.app.systems.camera.cameras,n=i.length-1;n>=0;n--){for(var s=i[n],r=0,a=t.changedTouches.length,o=0;o<a;o++)if(e[t.changedTouches[o].identifier])r++;else{var h=this._calcTouchCoords(t.changedTouches[o]),l=this._getTargetElementByCoords(s,h.x,h.y);l&&(r++,e[t.changedTouches[o].identifier]={element:l,camera:s,x:h.x,y:h.y})}if(r===a)break}return e},e._handleTouchStart=function(t){if(this._enabled){for(var e=this._determineTouchedElements(t),i=0,n=t.changedTouches.length;i<n;i++){var s=t.changedTouches[i],r=e[s.identifier],a=this._touchedElements[s.identifier];!r||a&&r.element===a.element||(this._fireEvent(t.type,new cT(t,r.element,r.camera,r.x,r.y,s)),this._touchesForWhichTouchLeaveHasFired[s.identifier]=!1)}for(var o in e)this._touchedElements[o]=e[o]}},e._handleTouchEnd=function(t){if(this._enabled){var e=this.app.systems.camera.cameras;for(var i in this._clickedEntities)delete this._clickedEntities[i];for(var n=0,s=t.changedTouches.length;n<s;n++){var r=t.changedTouches[n],a=this._touchedElements[r.identifier];if(a){var o=a.element,h=a.camera,l=a.x,c=a.y;delete this._touchedElements[r.identifier],delete this._touchesForWhichTouchLeaveHasFired[r.identifier];for(var u=this._calcTouchCoords(r),d=e.length-1;d>=0;d--){this._getTargetElementByCoords(e[d],u.x,u.y)===o&&(this._clickedEntities[o.entity.getGuid()]||(this._fireEvent("click",new cT(t,o,h,l,c,r)),this._clickedEntities[o.entity.getGuid()]=Date.now()))}this._fireEvent(t.type,new cT(t,o,h,l,c,r))}}}},e._handleTouchMove=function(t){if(t.preventDefault(),this._enabled)for(var e=this._determineTouchedElements(t),i=0,n=t.changedTouches.length;i<n;i++){var s=t.changedTouches[i],r=e[s.identifier],a=this._touchedElements[s.identifier];if(a){var o=this._calcTouchCoords(s);r&&r.element===a.element||this._touchesForWhichTouchLeaveHasFired[s.identifier]||(this._fireEvent("touchleave",new cT(t,a.element,a.camera,o.x,o.y,s)),this._touchesForWhichTouchLeaveHasFired[s.identifier]=!0),this._fireEvent("touchmove",new cT(t,a.element,a.camera,o.x,o.y,s))}}},e._onElementMouseEvent=function(t,e){var i=null,n=this._hoveredElement;this._hoveredElement=null;for(var s,r=this.app.systems.camera.cameras,a=r.length-1;a>=0&&(s=r[a],!(i=this._getTargetElementByCoords(s,aw,ow)));a--);if(this._hoveredElement=i,"mousemove"!==t&&"mouseup"!==t||!this._pressedElement?i&&(this._fireEvent(t,new lT(e,i,s,aw,ow,this._lastX,this._lastY)),"mousedown"===t&&(this._pressedElement=i)):this._fireEvent(t,new lT(e,this._pressedElement,s,aw,ow,this._lastX,this._lastY)),n!==this._hoveredElement&&(n&&this._fireEvent("mouseleave",new lT(e,n,s,aw,ow,this._lastX,this._lastY)),this._hoveredElement&&this._fireEvent("mouseenter",new lT(e,this._hoveredElement,s,aw,ow,this._lastX,this._lastY))),"mouseup"===t&&this._pressedElement){if(this._pressedElement===this._hoveredElement){var o=this._hoveredElement.entity.getGuid(),h=!this._clickedEntities;if(this._clickedEntities){var l=this._clickedEntities[o]||0;h=Date.now()-l>300,delete this._clickedEntities[o]}h&&this._fireEvent("click",new lT(e,this._hoveredElement,s,aw,ow,this._lastX,this._lastY))}this._pressedElement=null}},e._onXrStart=function(){this.app.xr.on("end",this._onXrEnd,this),this.app.xr.on("update",this._onXrUpdate,this),this.app.xr.input.on("selectstart",this._onSelectStart,this),this.app.xr.input.on("selectend",this._onSelectEnd,this),this.app.xr.input.on("remove",this._onXrInputRemove,this)},e._onXrEnd=function(){this.app.xr.off("update",this._onXrUpdate,this),this.app.xr.input.off("selectstart",this._onSelectStart,this),this.app.xr.input.off("selectend",this._onSelectEnd,this),this.app.xr.input.off("remove",this._onXrInputRemove,this)},e._onXrUpdate=function(){if(this._enabled)for(var t=this.app.xr.input.inputSources,e=0;e<t.length;e++)this._onElementSelectEvent("selectmove",t[e],null)},e._onXrInputRemove=function(t){var e=this._selectedElements[t.id];e&&(t._elementEntity=null,this._fireEvent("selectleave",new uT(null,e,null,t))),delete this._selectedElements[t.id],delete this._selectedPressedElements[t.id]},e._onSelectStart=function(t,e){this._enabled&&this._onElementSelectEvent("selectstart",t,e)},e._onSelectEnd=function(t,e){this._enabled&&this._onElementSelectEvent("selectend",t,e)},e._onElementSelectEvent=function(t,e,i){var n,s,r,a=this._selectedElements[e.id],o=this.app.systems.camera.cameras;if(e.elementInput){Nw.set(e.getOrigin(),e.getDirection());for(var h=o.length-1;h>=0&&(r=o[h],!(n=this._getTargetElementByRay(Nw,r)));h--);}e._elementEntity=n||null,n?(this._selectedElements[e.id]=n,s=n):delete this._selectedElements[e.id],a!==s&&(a&&this._fireEvent("selectleave",new uT(i,a,r,e)),s&&this._fireEvent("selectenter",new uT(i,s,r,e)));var l=this._selectedPressedElements[e.id];"selectmove"===t&&l&&this._fireEvent("selectmove",new uT(i,l,r,e)),"selectstart"===t&&(this._selectedPressedElements[e.id]=s,s&&this._fireEvent("selectstart",new uT(i,s,r,e))),!e.elementInput&&l&&(delete this._selectedPressedElements[e.id],a&&this._fireEvent("selectend",new uT(i,l,r,e))),"selectend"===t&&e.elementInput&&(delete this._selectedPressedElements[e.id],l&&this._fireEvent("selectend",new uT(i,l,r,e)),l&&l===a&&this._fireEvent("click",new uT(i,l,r,e)))},e._fireEvent=function(t,e){for(var i=e.element;i.fire(t,e),!e._stopPropagation&&i.entity.parent&&(i=i.entity.parent.element););},e._calcMouseCoords=function(t){var e=this._target.getBoundingClientRect(),i=Math.floor(e.left),n=Math.floor(e.top);aw=t.clientX-i,ow=t.clientY-n},e._calcTouchCoords=function(t){for(var e=0,i=0,n=t.target;!(n instanceof HTMLElement);)n=n.parentNode;var s=n;do{e+=s.offsetLeft-s.scrollLeft,i+=s.offsetTop-s.scrollTop,s=s.offsetParent}while(s);return{x:t.pageX-e,y:t.pageY-i}},e._sortElements=function(t,e){var i=this.app.scene.layers.sortTransparentLayers(t.layers,e.layers);return 0!==i?i:t.screen&&!e.screen?-1:!t.screen&&e.screen?1:t.screen||e.screen?t.screen.screen.screenSpace&&!e.screen.screen.screenSpace?-1:e.screen.screen.screenSpace&&!t.screen.screen.screenSpace?1:e.drawOrder-t.drawOrder:0},e._getTargetElementByCoords=function(t,e,i){var n=this._calculateRayScreen(e,i,t,Bw)?Bw:null,s=this._calculateRay3d(e,i,t,Uw)?Uw:null;return this._getTargetElement(t,n,s)},e._getTargetElementByRay=function(t,e){Bw.origin.copy(t.origin),Bw.direction.copy(t.direction),Bw.end.copy(Bw.direction).mulScalar(2*e.farClip).add(Bw.origin);var i=Bw,n=e.worldToScreen(i.origin,kw),s=this._calculateRayScreen(n.x,n.y,e,Uw)?Uw:null;return this._getTargetElement(e,s,i)},e._getTargetElement=function(t,e,i){var n=null,s=1/0;this._elements.sort(this._sortHandler);for(var r=0,a=this._elements.length;r<a;r++){var o=this._elements[r];if(o.layers.some((function(e){return t.layersSet.has(e)})))if(o.screen&&o.screen.screen.screenSpace){if(!e)continue;if(this._checkElement(e,o,!0)>=0){n=o;break}}else{if(!i)continue;var h=this._checkElement(i,o,!1);if(h>=0&&(h<s&&(n=o,s=h),o.screen)){n=o;break}}}return n},e._calculateRayScreen=function(t,e,i,n){var s=this.app.graphicsDevice.width,r=this.app.graphicsDevice.height,a=i.rect.z*s,o=i.rect.w*r,h=i.rect.x*s,l=h+a,c=(1-i.rect.y)*r,u=c-o,d=t*s/this._target.clientWidth,f=e*r/this._target.clientHeight;return d>=h&&d<=l&&f<=c&&f>=u&&(d=s*(d-h)/a,f=r-(f=r*(f-u)/o),n.origin.set(d,f,1),n.direction.set(0,0,-1),n.end.copy(n.direction).mulScalar(2).add(n.origin),!0)},e._calculateRay3d=function(t,e,i,n){var s=this._target.clientWidth,r=this._target.clientHeight,a=i.rect.z*s,o=i.rect.w*r,h=i.rect.x*s,l=h+a,c=(1-i.rect.y)*r,u=c-o,d=t,f=e;return t>=h&&t<=l&&e<=c&&f>=u&&(d=s*(d-h)/a,f=r*(f-u)/o,i.screenToWorld(d,f,i.nearClip,kw),i.screenToWorld(d,f,i.farClip,Fw),n.origin.copy(kw),n.direction.set(0,0,-1),n.end.copy(Fw),!0)},e._checkElement=function(e,i,n){if(i.maskedBy&&this._checkElement(e,i.maskedBy.element,n)<0)return-1;var s;s=n?t.calculateScaleToScreen(i):t.calculateScaleToWorld(i);var r=t.buildHitCorners(i,n?i.screenCorners:i.worldCorners,s);return function(t,e,i){zw.sub2(e,t),Vw.sub2(i[0],t),Gw.sub2(i[1],t),Hw.sub2(i[2],t),Xw.cross(Hw,zw);var n,s,r=Vw.dot(Xw);if(r>=0){if((n=-Gw.dot(Xw))<0)return-1;if((s=oT(zw,Gw,Vw))<0)return-1;var a=1/(n+r+s);jw.copy(i[0]).mulScalar(n*a),qw.copy(i[1]).mulScalar(r*a),Yw.copy(i[2]).mulScalar(s*a),Kw.copy(jw).add(qw).add(Yw)}else{if(Ww.sub2(i[3],t),(n=Ww.dot(Xw))<0)return-1;if((s=oT(zw,Vw,Ww))<0)return-1;var o=1/(n+(r=-r)+s);jw.copy(i[0]).mulScalar(n*o),qw.copy(i[3]).mulScalar(r*o),Yw.copy(i[2]).mulScalar(s*o),Kw.copy(jw).add(qw).add(Yw)}return zw.sub2(i[0],i[2]).lengthSq()<1e-8||zw.sub2(i[1],i[3]).lengthSq()<1e-8?-1:Kw.sub(t).lengthSq()}(e.origin,e.end,r)},t.buildHitCorners=function(t,e,i){var n=e;if(t.entity&&t.entity.button){var s=t.entity.button.hitPadding||aT;$w.copy(t.entity.up),Jw.copy($w).mulScalar(-1),eT.copy(t.entity.right),tT.copy(eT).mulScalar(-1),$w.mulScalar(s.w*i.y),Jw.mulScalar(s.y*i.y),eT.mulScalar(s.z*i.x),tT.mulScalar(s.x*i.x),iT.copy(n[0]).add(Jw).add(tT),nT.copy(n[1]).add(Jw).add(eT),sT.copy(n[2]).add($w).add(eT),rT.copy(n[3]).add($w).add(tT),n=[iT,nT,sT,rT]}if(i.x<0){var r=n[2].x,a=n[0].x;n[0].x=r,n[1].x=a,n[2].x=a,n[3].x=r}if(i.y<0){var o=n[2].y,h=n[0].y;n[0].y=o,n[1].y=o,n[2].y=h,n[3].y=h}if(i.z<0){var l=n[2].x,c=n[2].y,u=n[2].z;n[2].x=n[0].x,n[2].y=n[0].y,n[2].z=n[0].z,n[0].x=l,n[0].y=c,n[0].z=u}return n},t.calculateScaleToScreen=function(t){var e=t.entity,i=t.screen.screen.scale;for(Qw.set(i,i,i);e&&!e.screen;)Qw.mul(e.getLocalScale()),e=e.parent;return Qw},t.calculateScaleToWorld=function(t){var e=t.entity;for(Qw.set(1,1,1);e;)Qw.mul(e.getLocalScale()),e=e.parent;return Qw},y(t,[{key:"enabled",get:function(){return this._enabled},set:function(t){this._enabled=t}},{key:"app",get:function(){return this._app||vf()},set:function(t){this._app=t}}]),t}(),fT=new RegExp("^\\s*function(?:\\s|\\s*\\/\\*.*\\*\\/\\s*)+([^\\(\\s\\/]*)\\s*"),pT=function(t){function e(e){var i;return(i=t.call(this)||this).app=void 0,i.entity=void 0,i._enabled=void 0,i._enabledOld=void 0,i._initialized=void 0,i._postInitialized=void 0,i.__destroyed=void 0,i.__attributes=void 0,i.__attributesRaw=void 0,i.__scriptType=void 0,i.__executionOrder=void 0,i.initScriptType(e),i}S(e,t);var i=e.prototype;return i.initScriptType=function(t){var e=this.constructor;this.app=t.app,this.entity=t.entity,this._enabled="boolean"!=typeof t.enabled||t.enabled,this._enabledOld=this.enabled,this.__destroyed=!1,this.__attributes={},this.__attributesRaw=t.attributes||{},this.__scriptType=e,this.__executionOrder=-1},e.__getScriptName=function(t){if("function"==typeof t){if("name"in Function.prototype)return t.name;if(t===Function||t===Function.prototype.constructor)return"Function";var e=(""+t).match(fT);return e?e[1]:void 0}},i.__initializeAttributes=function(t){if(t||this.__attributesRaw){for(var e in this.__scriptType.attributes.index)this.__attributesRaw&&this.__attributesRaw.hasOwnProperty(e)?this[e]=this.__attributesRaw[e]:this.__attributes.hasOwnProperty(e)||(this.__scriptType.attributes.index[e].hasOwnProperty("default")?this[e]=this.__scriptType.attributes.index[e].default:this[e]=null);this.__attributesRaw=null}},e.extend=function(t){for(var e in t)t.hasOwnProperty(e)&&(this.prototype[e]=t[e])},y(e,[{key:"enabled",get:function(){return this._enabled&&!this._destroyed&&this.entity.script.enabled&&this.entity.enabled},set:function(t){this._enabled=!!t,this.enabled!==this._enabledOld&&(this._enabledOld=this.enabled,this.fire(this.enabled?"enable":"disable"),this.fire("state",this.enabled),!this._initialized&&this.enabled&&(this._initialized=!0,this.__initializeAttributes(!0),this.initialize&&this.entity.script._scriptMethod(this,Zy)),this._initialized&&!this._postInitialized&&this.enabled&&!this.entity.script._beingEnabled&&(this._postInitialized=!0,this.postInitialize&&this.entity.script._scriptMethod(this,Qy)))}}],[{key:"scriptName",get:function(){return this.__name}},{key:"attributes",get:function(){return this.hasOwnProperty("__attributes")||(this.__attributes=new Ky(this)),this.__attributes}}]),e}(P);pT.__name=null;var mT=new Set(["system","entity","create","destroy","swap","move","data","scripts","_scripts","_scriptsIndex","_scriptsData","enabled","_oldState","onEnable","onDisable","onPostStateChange","_onSetEnabled","_checkState","_onBeforeRemove","_onInitializeAttributes","_onInitialize","_onPostInitialize","_onUpdate","_onPostUpdate","_callbacks","_callbackActive","has","get","on","off","fire","once","hasEvent"]);function _T(t,e){if(bf.legacy)return null;if(mT.has(t))throw new Error("Script name '"+t+"' is reserved, please rename the script");var i=function(t){P.prototype.initEventHandler.call(this),pT.prototype.initScriptType.call(this,t)};return(i.prototype=Object.create(pT.prototype)).constructor=i,i.extend=pT.extend,i.attributes=new Ky(i),gT(i,t,e),i}var vT={};function gT(t,e,i){if(!t.legacy){if("function"!=typeof t)throw new Error("script class: '"+t+"' must be a constructor function (i.e. class).");if(!(t.prototype instanceof pT))throw new Error("script class: '"+pT.__getScriptName(t)+"' does not extend pc.ScriptType.");if(e=e||t.__name||pT.__getScriptName(t),mT.has(e))throw new Error("script name: '"+e+"' is reserved, please change script name");t.__name=e,(i?i.scripts:hp.getApplication().scripts).add(t),yf.push(t,t.legacy)}}Ky.reservedNames.forEach((function(t,e,i){vT[t]=1})),_T.reservedAttributes=vT;var yT={write:function(t){console.log(t)},open:function(){yT.write("Powered by PlayCanvas "+c+" "+u)},info:function(t){console.info("INFO: "+t)},debug:function(t){console.debug("DEBUG: "+t)},error:function(t){console.error("ERROR: "+t)},warning:function(t){console.warn("WARNING: "+t)},alert:function(t){function e(e){return t.apply(this,arguments)}return e.toString=function(){return t.toString()},e}((function(t){yT.write("ALERT: "+t),alert(t)})),assert:function(t,e){!1===t&&yT.write("ASSERT: "+e)}};rt.endsWith=function(t,e){return t.endsWith(e)},rt.startsWith=function(t,e){return t.startsWith(e)};var xT=function(){function t(){this._isRunning=!1,this._a=0,this._b=0}var e=t.prototype;return e.start=function(){this._isRunning=!0,this._a=dt()},e.stop=function(){this._isRunning=!1,this._b=dt()},e.getMilliseconds=function(){return this._b-this._a},t}(),ST={now:dt,Timer:xT};Object.defineProperty(vt.prototype,"data",{get:function(){return this._data||(this._data=new Float32Array(4)),this._data[0]=this.r,this._data[1]=this.g,this._data[2]=this.b,this._data[3]=this.a,this._data}}),Object.defineProperty(vt.prototype,"data3",{get:function(){return this._data3||(this._data3=new Float32Array(3)),this._data3[0]=this.r,this._data3[1]=this.g,this._data3[2]=this.b,this._data3}}),_t.INV_LOG2=Math.LOG2E,_t.intToBytes=_t.intToBytes32,_t.bytesToInt=_t.bytesToInt32,Object.defineProperty(Et.prototype,"data",{get:function(){return this._data||(this._data=new Float32Array(2)),this._data[0]=this.x,this._data[1]=this.y,this._data}}),Et.prototype.scale=Et.prototype.mulScalar,Object.defineProperty(wt.prototype,"data",{get:function(){return this._data||(this._data=new Float32Array(3)),this._data[0]=this.x,this._data[1]=this.y,this._data[2]=this.z,this._data}}),wt.prototype.scale=wt.prototype.mulScalar,Object.defineProperty(Pt.prototype,"data",{get:function(){return this._data||(this._data=new Float32Array(4)),this._data[0]=this.x,this._data[1]=this.y,this._data[2]=this.z,this._data[3]=this.w,this._data}}),Pt.prototype.scale=Pt.prototype.mulScalar;var bT={Aabb:Ht,Sphere:jt,Plane:te};jt.prototype.intersectRay=jt.prototype.intersectsRay,qt.prototype.update=function(t,e){var i=new Ft;i.mul2(t,e),this.setFromMat4(i)};var wT=mi;function TT(t){this.name="UnsupportedBrowserError",this.message=t||""}function AT(t){this.name="ContextCreationError",this.message=t||""}TT.prototype=Error.prototype,AT.prototype=Error.prototype;var CT={begin:xo.begin,dummyFragmentCode:ir.dummyFragmentCode,end:xo.end,fogCode:xo.fogCode,gammaCode:xo.gammaCode,precisionCode:ir.precisionCode,skinCode:xo.skinCode,tonemapCode:xo.tonemapCode,versionCode:ir.versionCode},ET={ADDRESS_CLAMP_TO_EDGE:1,ADDRESS_MIRRORED_REPEAT:2,ADDRESS_REPEAT:0,BLENDMODE_ZERO:0,BLENDMODE_ONE:1,BLENDMODE_SRC_COLOR:2,BLENDMODE_ONE_MINUS_SRC_COLOR:3,BLENDMODE_DST_COLOR:4,BLENDMODE_ONE_MINUS_DST_COLOR:5,BLENDMODE_SRC_ALPHA:6,BLENDMODE_SRC_ALPHA_SATURATE:7,BLENDMODE_ONE_MINUS_SRC_ALPHA:8,BLENDMODE_DST_ALPHA:9,BLENDMODE_ONE_MINUS_DST_ALPHA:10,BUFFER_STATIC:0,BUFFER_DYNAMIC:1,BUFFER_STREAM:2,CULLFACE_NONE:se,CULLFACE_BACK:1,CULLFACE_FRONT:2,CULLFACE_FRONTANDBACK:3,ELEMENTTYPE_INT8:0,ELEMENTTYPE_UINT8:mi,ELEMENTTYPE_INT16:2,ELEMENTTYPE_UINT16:3,ELEMENTTYPE_INT32:4,ELEMENTTYPE_UINT32:5,ELEMENTTYPE_FLOAT32:6,FILTER_NEAREST:0,FILTER_LINEAR:1,FILTER_NEAREST_MIPMAP_NEAREST:2,FILTER_NEAREST_MIPMAP_LINEAR:3,FILTER_LINEAR_MIPMAP_NEAREST:4,FILTER_LINEAR_MIPMAP_LINEAR:5,INDEXFORMAT_UINT8:0,INDEXFORMAT_UINT16:1,INDEXFORMAT_UINT32:2,PIXELFORMAT_RGB565:3,PIXELFORMAT_RGB8:6,PIXELFORMAT_RGBA8:7,PRIMITIVE_POINTS:0,PRIMITIVE_LINES:1,PRIMITIVE_LINELOOP:2,PRIMITIVE_LINESTRIP:3,PRIMITIVE_TRIANGLES:4,PRIMITIVE_TRISTRIP:be,PRIMITIVE_TRIFAN:6,SEMANTIC_POSITION:we,SEMANTIC_NORMAL:Te,SEMANTIC_COLOR:Me,SEMANTIC_TEXCOORD:Pe,SEMANTIC_TEXCOORD0:Re,SEMANTIC_TEXCOORD1:Ie,SEMANTIC_ATTR0:Ne,SEMANTIC_ATTR1:ze,SEMANTIC_ATTR2:Ve,SEMANTIC_ATTR3:Ge,TEXTURELOCK_READ:1,TEXTURELOCK_WRITE:2,drawQuadWithShader:Ro,programlib:CT,shaderChunks:_o,ContextCreationError:AT,Device:nn,IndexBuffer:vr,ProgramLibrary:uf,RenderTarget:rn,ScopeId:Hi,Shader:fs,ShaderInput:Fs,Texture:Ls,UnsupportedBrowserError:TT,VertexBuffer:ji,VertexFormat:Ji,VertexIterator:Lr},MT=new Pt;function PT(t,e,i,n,s){var r;if(s){var a=e?e.width:t.width,o=e?e.height:t.height;r=MT.set(s.x*a,s.y*o,s.z*a,s.w*o)}Ro(t,e,n,r)}var RT={createFullscreenQuad:function(t){return t.quadVertexBuffer},drawFullscreenQuad:PT,PostEffect:of,PostEffectQueue:ky};Object.defineProperty(_o,"transformSkinnedVS",{get:function(){return"#define SKIN\n"+_o.transformVS}});Object.keys({"ambientPrefilteredCube.frag":"ambientEnv.frag","ambientPrefilteredCubeLod.frag":"ambientEnv.frag","dpAtlasQuad.frag":null,"genParaboloid.frag":null,"prefilterCubemap.frag":null,"reflectionDpAtlas.frag":"reflectionEnv.frag","reflectionPrefilteredCube.frag":"reflectionEnv.frag","reflectionPrefilteredCubeLod.frag":"reflectionEnv.frag"}).forEach((function(t){Object.defineProperty(_o,t,{get:function(){return null},set:function(){}})})),Object.defineProperties(rn.prototype,{_glFrameBuffer:{get:function(){return this.impl._glFrameBuffer},set:function(t){}}}),Object.defineProperty(Ji,"defaultInstancingFormat",{get:function(){return Ji.getDefaultInstancingFormat(Ha.get())}}),Object.defineProperties(Ls.prototype,{rgbm:{get:function(){return this.type===ii},set:function(t){this.type=t?ii:ei}},swizzleGGGR:{get:function(){return this.type===ri},set:function(t){this.type=t?ri:ei}},_glTexture:{get:function(){return this.impl._glTexture}},autoMipmap:{get:function(){return this._mipmaps},set:function(t){this._mipmaps=t}}}),Object.defineProperty(nn.prototype,"webgl2",{get:function(){return this.isWebGL2}}),nn.prototype.getProgramLibrary=function(){return go(this)},nn.prototype.setProgramLibrary=function(t){yo(this,t)},nn.prototype.removeShaderFromCache=function(t){go(this).removeFromCache(t)},Ui.DEFAULT=Object.freeze(new Ui);var IT=new Ui,LT=new Ni;nn.prototype.setBlendFunction=function(t,e){var i=this.blendState;IT.copy(i),IT.setColorBlend(i.colorOp,t,e),IT.setAlphaBlend(i.alphaOp,t,e),this.setBlendState(IT)},nn.prototype.setBlendFunctionSeparate=function(t,e,i,n){var s=this.blendState;IT.copy(s),IT.setColorBlend(s.colorOp,t,e),IT.setAlphaBlend(s.alphaOp,i,n),this.setBlendState(IT)},nn.prototype.setBlendEquation=function(t){var e=this.blendState;IT.copy(e),IT.setColorBlend(t,e.colorSrcFactor,e.colorDstFactor),IT.setAlphaBlend(t,e.alphaSrcFactor,e.alphaDstFactor),this.setBlendState(IT)},nn.prototype.setBlendEquationSeparate=function(t,e){var i=this.blendState;IT.copy(i),IT.setColorBlend(t,i.colorSrcFactor,i.colorDstFactor),IT.setAlphaBlend(e,i.alphaSrcFactor,i.alphaDstFactor),this.setBlendState(IT)},nn.prototype.setColorWrite=function(t,e,i,n){var s=this.blendState;IT.copy(s),IT.setColorWrite(t,e,i,n),this.setBlendState(IT)},nn.prototype.getBlending=function(){return this.blendState.blend},nn.prototype.setBlending=function(t){IT.copy(this.blendState),IT.blend=t,this.setBlendState(IT)},nn.prototype.setDepthWrite=function(t){LT.copy(this.depthState),LT.write=t,this.setDepthState(LT)},nn.prototype.setDepthFunc=function(t){LT.copy(this.depthState),LT.func=t,this.setDepthState(LT)},nn.prototype.setDepthTest=function(t){LT.copy(this.depthState),LT.test=t,this.setDepthState(LT)},nn.prototype.getCullMode=function(){return this.cullMode};var DT=lu,OT=Hh,kT={partitionSkin:GS,procedural:{calculateTangents:$a,createMesh:Ja,createTorus:to,createCylinder:io,createCapsule:no,createCone:so,createSphere:ro,createPlane:ao,createBox:oo},BasicMaterial:Vo,ForwardRenderer:yu,GraphNode:hh,Material:zo,Mesh:qa,MeshInstance:yh,Model:Gu,ParticleEmitter:Nd,PhongMaterial:lu,Picker:Lw,Projection:{ORTHOGRAPHIC:1,PERSPECTIVE:0},Scene:Yd,Skin:Kd,SkinInstance:Xo};function FT(t,e){Object.defineProperty(lu.prototype,e,{get:function(){return this[t]},set:function(e){this[t]=e}})}function BT(t,e){"pass"!==t&&Object.defineProperty(Xc.prototype,t,{get:function(){return this.litOptions[e||t]},set:function(i){this.litOptions[e||t]=i}})}Object.defineProperty(Yd.prototype,"defaultMaterial",{get:function(){return Bo(vf().graphicsDevice)}}),Object.defineProperty(Ru.prototype,"_meshInstances",{get:function(){return null}}),Object.defineProperty(Yd.prototype,"drawCalls",{get:function(){return null}}),["128","64","32","16","8","4"].forEach((function(t,e){Object.defineProperty(Yd.prototype,"skyboxPrefiltered"+t,{get:function(){return this._prefilteredCubemaps[e]},set:function(t){this._prefilteredCubemaps[e]=t,this.updateShaders=!0}})})),Object.defineProperty(Yd.prototype,"models",{get:function(){return this._models||(this._models=[]),this._models}}),Object.defineProperty(Cu.prototype,"renderTarget",{set:function(t){this._renderTarget=t,this._dirtyCameras=!0},get:function(){return this._renderTarget}}),Yd.prototype._updateSkybox=function(t){this._updateSky(t)},Yd.prototype.addModel=function(t){if(!this.containsModel(t)){var e=this.layers.getLayerById(0);e&&(e.addMeshInstances(t.meshInstances),this.models.push(t))}},Yd.prototype.addShadowCaster=function(t){var e=this.layers.getLayerById(0);e&&e.addShadowCasters(t.meshInstances)},Yd.prototype.removeModel=function(t){var e=this.models.indexOf(t);if(-1!==e){var i=this.layers.getLayerById(0);if(!i)return;i.removeMeshInstances(t.meshInstances),this.models.splice(e,1)}},Yd.prototype.removeShadowCasters=function(t){var e=this.layers.getLayerById(0);e&&e.removeShadowCasters(t.meshInstances)},Yd.prototype.containsModel=function(t){return this.models.indexOf(t)>=0},Yd.prototype.getModels=function(t){return this.models},Object.defineProperty(Go.prototype,"model",{get:function(){return null}}),yu.prototype.renderComposition=function(t){vf().renderComposition(t)},yh.prototype.syncAabb=function(){},Hu.prototype.getTarget=function(t){return this.targets[t]},hh.prototype._dirtify=function(t){t?this._dirtifyLocal():this._dirtifyWorld()},hh.prototype.addLabel=function(t){this._labels[t]=!0},hh.prototype.getLabels=function(){return Object.keys(this._labels)},hh.prototype.hasLabel=function(t){return!!this._labels[t]},hh.prototype.removeLabel=function(t){delete this._labels[t]},hh.prototype.findByLabel=function(t,e){void 0===e&&(e=[]),this.hasLabel(t)&&e.push(this);for(var i=0;i<this._children.length;++i)e=this._children[i].findByLabel(t,e);return e},hh.prototype.getChildren=function(){return this.children},hh.prototype.getName=function(){return this.name},hh.prototype.getPath=function(){return this.path},hh.prototype.getRoot=function(){return this.root},hh.prototype.getParent=function(){return this.parent},hh.prototype.setName=function(t){this.name=t},zo.prototype.getName=function(){return this.name},zo.prototype.setName=function(t){this.name=t},zo.prototype.getShader=function(){return this.shader},zo.prototype.setShader=function(t){this.shader=t},Object.defineProperty(zo.prototype,"blend",{set:function(t){this.blendState.blend=t},get:function(){return this.blendState.blend}}),Object.defineProperty(zo.prototype,"blendSrc",{set:function(t){var e=this.blendState;IT.copy(e),IT.setColorBlend(e.colorOp,t,e.colorDstFactor),IT.setAlphaBlend(e.alphaOp,t,e.alphaDstFactor),this.blendState=IT},get:function(){return this.blendState.colorSrcFactor}}),Object.defineProperty(zo.prototype,"blendDst",{set:function(t){var e=this.blendState;IT.copy(e),IT.setColorBlend(e.colorOp,e.colorSrcFactor,t),IT.setAlphaBlend(e.alphaOp,e.alphaSrcFactor,t),this.blendState=IT},get:function(){return this.blendState.colorDstFactor}}),Object.defineProperty(lu.prototype,"shininess",{get:function(){return 100*this.gloss},set:function(t){this.gloss=.01*t}}),FT("diffuseTint","diffuseMapTint"),FT("specularTint","specularMapTint"),FT("emissiveTint","emissiveMapTint"),FT("aoVertexColor","aoMapVertexColor"),FT("diffuseVertexColor","diffuseMapVertexColor"),FT("specularVertexColor","specularMapVertexColor"),FT("emissiveVertexColor","emissiveMapVertexColor"),FT("metalnessVertexColor","metalnessMapVertexColor"),FT("glossVertexColor","glossMapVertexColor"),FT("opacityVertexColor","opacityMapVertexColor"),FT("lightVertexColor","lightMapVertexColor"),FT("sheenGloss","sheenGlossiess"),FT("clearCoatGloss","clearCostGlossiness"),BT("refraction","useRefraction");var UT=new Hh,NT=Object.getOwnPropertyNames(UT);for(var zT in NT)BT(NT[zT]);var VT={Animation:nf,Key:tf,Node:ef,Skeleton:rf};nf.prototype.getDuration=function(){return this.duration},nf.prototype.getName=function(){return this.name},nf.prototype.getNodes=function(){return this.nodes},nf.prototype.setDuration=function(t){this.duration=t},nf.prototype.setName=function(t){this.name=t},rf.prototype.getAnimation=function(){return this.animation},rf.prototype.getCurrentTime=function(){return this.currentTime},rf.prototype.getLooping=function(){return this.looping},rf.prototype.getNumNodes=function(){return this.numNodes},rf.prototype.setAnimation=function(t){this.animation=t},rf.prototype.setCurrentTime=function(t){this.currentTime=t},rf.prototype.setLooping=function(t){this.looping=t};var GT={AudioManager:Ta,Channel:ga,Channel3d:ya,Listener:Sa,Sound:Aa};Ta.prototype.getListener=function(){return this.listener},Ta.prototype.getVolume=function(){return this.volume},Ta.prototype.setVolume=function(t){this.volume=t};Hf.prototype.getAssetById=function(t){return this.get(t)},Object.defineProperty(uw.prototype,"ray",{get:function(){return this._rayLocal}}),Object.defineProperty(uw.prototype,"position",{get:function(){return this._localPosition}}),Object.defineProperty(uw.prototype,"rotation",{get:function(){return this._localRotation}});var HT={getTouchTargetCoords:ua,Controller:Qr,GamePads:ca,Keyboard:qr,KeyboardEvent:Gr,Mouse:Zr,MouseEvent:Kr,Touch:da,TouchDevice:pa,TouchEvent:fa};Object.defineProperty(dT.prototype,"wheel",{get:function(){return-2*this.wheelDelta}}),Object.defineProperty(Kr.prototype,"wheel",{get:function(){return-2*this.wheelDelta}});var WT=d_,XT=f_,jT=p_;hp.prototype.isFullscreen=function(){return!!document.fullscreenElement},hp.prototype.enableFullscreen=function(t,e,i){t=t||this.graphicsDevice.canvas;e&&document.addEventListener("fullscreenchange",(function t(){e(),document.removeEventListener("fullscreenchange",t)}),!1),i&&document.addEventListener("fullscreenerror",(function t(){i(),document.removeEventListener("fullscreenerror",t)}),!1),t.requestFullscreen?t.requestFullscreen(Element.ALLOW_KEYBOARD_INPUT):i()},hp.prototype.disableFullscreen=function(t){t&&document.addEventListener("fullscreenchange",(function e(){t(),document.removeEventListener("fullscreenchange",e)}),!1),document.exitFullscreen()},hp.prototype.getSceneUrl=function(t){var e=this.scenes.find(t);return e?e.url:null},hp.prototype.loadScene=function(t,e){this.scenes.loadScene(t,e)},hp.prototype.loadSceneHierarchy=function(t,e){this.scenes.loadSceneHierarchy(t,e)},hp.prototype.loadSceneSettings=function(t,e){this.scenes.loadSceneSettings(t,e)},hp.prototype.renderMeshInstance=function(t,e){var i=null!=e&&e.layer?e.layer:this.scene.defaultDrawLayer;this.scene.immediate.drawMesh(null,null,null,t,i)},hp.prototype.renderMesh=function(t,e,i,n){var s=null!=n&&n.layer?n.layer:this.scene.defaultDrawLayer;this.scene.immediate.drawMesh(e,i,t,null,s)},hp.prototype._addLines=function(t,e,i){var n=i&&i.layer?i.layer:this.scene.layers.getLayerById(3),s=!i||void 0===i.depthTest||i.depthTest;this.scene.immediate.getBatch(n,s).addLines(t,e)},hp.prototype.renderLine=function(t,e,i){var n,s=i,r=arguments[3],a=arguments[4];r instanceof vt?(s=r,n="number"==typeof a?1===a?{layer:this.scene.layers.getLayerById(3),depthTest:!1}:{layer:this.scene.layers.getLayerById(3),depthTest:!0}:a):"number"==typeof r?(s=i,n=1===r?{layer:this.scene.layers.getLayerById(3),depthTest:!1}:{layer:this.scene.layers.getLayerById(3),depthTest:!0}):r&&(n=r),this._addLines([t,e],[i,s],n)},hp.prototype.renderLines=function(t,e,i){i?"number"==typeof i&&(i=1===i?{layer:this.scene.layers.getLayerById(3),depthTest:!1}:{layer:this.scene.layers.getLayerById(3),depthTest:!0}):i={layer:this.scene.layers.getLayerById(3),depthTest:!0},!e.length||t.length===e.length?t.length%2==0?this._addLines(t,e,i):console.error("renderLines: array length is not divisible by 2"):console.error("renderLines: position/color arrays have different lengths")},hp.prototype.enableVr=function(){},Object.defineProperty(Fy.prototype,"node",{get:function(){return this.entity}}),Object.defineProperty(Gy.prototype,"enable",{get:function(){return this.enabled},set:function(t){this.enabled=t}}),qv.prototype.setVisible=function(t){this.enabled=t},Object.defineProperty(qv.prototype,"aabb",{get:function(){return null},set:function(t){}}),Object.defineProperty(lg.prototype,"aabb",{get:function(){return null},set:function(t){}}),Object.defineProperty(Tg.prototype,"bodyType",{get:function(){return this.type},set:function(t){this.type=t}}),Tg.prototype.syncBodyToEntity=function(){this._updateDynamic()},Ig.prototype.setGravity=function(){1===arguments.length?this.gravity.copy(arguments[0]):this.gravity.set(arguments[0],arguments[1],arguments[2])},t.ABSOLUTE_URL=Ff,t.ACTION_GAMEPAD=kr,t.ACTION_KEYBOARD=Or,t.ACTION_MOUSE=Dr,t.ADDRESS_CLAMP_TO_EDGE=1,t.ADDRESS_MIRRORED_REPEAT=2,t.ADDRESS_REPEAT=0,t.ANIM_BLEND_1D="1D",t.ANIM_BLEND_2D_CARTESIAN=Wp,t.ANIM_BLEND_2D_DIRECTIONAL=Hp,t.ANIM_BLEND_DIRECT=Xp,t.ANIM_CONTROL_STATES=Kp,t.ANIM_EQUAL_TO=Bp,t.ANIM_GREATER_THAN=Dp,t.ANIM_GREATER_THAN_EQUAL_TO=kp,t.ANIM_INTERRUPTION_NEXT=Rp,t.ANIM_INTERRUPTION_NEXT_PREV=Lp,t.ANIM_INTERRUPTION_NONE=Mp,t.ANIM_INTERRUPTION_PREV=Pp,t.ANIM_INTERRUPTION_PREV_NEXT=Ip,t.ANIM_LAYER_ADDITIVE=Qp,t.ANIM_LAYER_OVERWRITE=Zp,t.ANIM_LESS_THAN=Op,t.ANIM_LESS_THAN_EQUAL_TO=Fp,t.ANIM_NOT_EQUAL_TO=Up,t.ANIM_PARAMETER_BOOLEAN=Vp,t.ANIM_PARAMETER_FLOAT=zp,t.ANIM_PARAMETER_INTEGER=Np,t.ANIM_PARAMETER_TRIGGER=Gp,t.ANIM_STATE_ANY=Yp,t.ANIM_STATE_END=qp,t.ANIM_STATE_START=jp,t.ASPECT_AUTO=0,t.ASPECT_MANUAL=1,t.ASSET_ANIMATION="animation",t.ASSET_AUDIO="audio",t.ASSET_CONTAINER="container",t.ASSET_CSS="css",t.ASSET_CUBEMAP="cubemap",t.ASSET_HTML="html",t.ASSET_IMAGE="image",t.ASSET_JSON="json",t.ASSET_MATERIAL="material",t.ASSET_MODEL="model",t.ASSET_SCRIPT="script",t.ASSET_SHADER="shader",t.ASSET_TEXT="text",t.ASSET_TEXTURE="texture",t.ASSET_TEXTUREATLAS="textureatlas",t.AXIS_KEY="key",t.AXIS_MOUSE_X="mousex",t.AXIS_MOUSE_Y="mousey",t.AXIS_PAD_L_X="padlx",t.AXIS_PAD_L_Y="padly",t.AXIS_PAD_R_X="padrx",t.AXIS_PAD_R_Y="padry",t.AnimBinder=sm,t.AnimClip=Ep,t.AnimClipHandler=dS,t.AnimComponent=Mm,t.AnimComponentLayer=Cm,t.AnimComponentSystem=Im,t.AnimController=ym,t.AnimCurve=ox,t.AnimData=hx,t.AnimEvaluator=em,t.AnimEvents=im,t.AnimSnapshot=Cp,t.AnimStateGraph=Em,t.AnimStateGraphHandler=fS,t.AnimTarget=rm,t.AnimTrack=nm,t.Animation=nf,t.AnimationComponent=om,t.AnimationComponentSystem=cm,t.AnimationHandler=uS,t.AppBase=hp,t.AppOptions=up,t.Application=Tw,t.Asset=Vf,t.AssetListLoader=Aw,t.AssetReference=hg,t.AssetRegistry=Hf,t.AudioHandler=_S,t.AudioListenerComponent=Lm,t.AudioListenerComponentSystem=km,t.AudioSourceComponent=Fm,t.AudioSourceComponentSystem=Nm,t.BAKE_COLOR=0,t.BAKE_COLORDIR=1,t.BINDGROUP_MESH=0,t.BINDGROUP_VIEW=1,t.BLENDEQUATION_ADD=0,t.BLENDEQUATION_MAX=4,t.BLENDEQUATION_MIN=3,t.BLENDEQUATION_REVERSE_SUBTRACT=2,t.BLENDEQUATION_SUBTRACT=1,t.BLENDMODE_CONSTANT=11,t.BLENDMODE_CONSTANT_ALPHA=11,t.BLENDMODE_CONSTANT_COLOR=11,t.BLENDMODE_DST_ALPHA=9,t.BLENDMODE_DST_COLOR=4,t.BLENDMODE_ONE=1,t.BLENDMODE_ONE_MINUS_CONSTANT=12,t.BLENDMODE_ONE_MINUS_CONSTANT_ALPHA=12,t.BLENDMODE_ONE_MINUS_CONSTANT_COLOR=12,t.BLENDMODE_ONE_MINUS_DST_ALPHA=10,t.BLENDMODE_ONE_MINUS_DST_COLOR=5,t.BLENDMODE_ONE_MINUS_SRC_ALPHA=8,t.BLENDMODE_ONE_MINUS_SRC_COLOR=3,t.BLENDMODE_SRC_ALPHA=6,t.BLENDMODE_SRC_ALPHA_SATURATE=7,t.BLENDMODE_SRC_COLOR=2,t.BLENDMODE_ZERO=0,t.BLEND_ADDITIVE=1,t.BLEND_ADDITIVEALPHA=6,t.BLEND_MAX=10,t.BLEND_MIN=9,t.BLEND_MULTIPLICATIVE=5,t.BLEND_MULTIPLICATIVE2X=7,t.BLEND_NONE=3,t.BLEND_NORMAL=2,t.BLEND_PREMULTIPLIED=4,t.BLEND_SCREEN=8,t.BLEND_SUBTRACTIVE=0,t.BLUR_BOX=0,t.BLUR_GAUSSIAN=1,t.BODYFLAG_KINEMATIC_OBJECT=2,t.BODYFLAG_NORESPONSE_OBJECT=4,t.BODYFLAG_STATIC_OBJECT=1,t.BODYGROUP_DEFAULT=1,t.BODYGROUP_DYNAMIC=1,t.BODYGROUP_ENGINE_1=8,t.BODYGROUP_ENGINE_2=32,t.BODYGROUP_ENGINE_3=64,t.BODYGROUP_KINEMATIC=4,t.BODYGROUP_NONE=0,t.BODYGROUP_STATIC=2,t.BODYGROUP_TRIGGER=16,t.BODYGROUP_USER_1=128,t.BODYGROUP_USER_2=256,t.BODYGROUP_USER_3=512,t.BODYGROUP_USER_4=1024,t.BODYGROUP_USER_5=2048,t.BODYGROUP_USER_6=4096,t.BODYGROUP_USER_7=8192,t.BODYGROUP_USER_8=16384,t.BODYMASK_ALL=m_,t.BODYMASK_NONE=0,t.BODYMASK_NOT_STATIC=__,t.BODYMASK_NOT_STATIC_KINEMATIC=65529,t.BODYMASK_STATIC=2,t.BODYSTATE_ACTIVE_TAG=1,t.BODYSTATE_DISABLE_DEACTIVATION=4,t.BODYSTATE_DISABLE_SIMULATION=5,t.BODYSTATE_ISLAND_SLEEPING=2,t.BODYSTATE_WANTS_DEACTIVATION=3,t.BODYTYPE_DYNAMIC=f_,t.BODYTYPE_KINEMATIC=p_,t.BODYTYPE_STATIC=d_,t.BUFFER_DYNAMIC=1,t.BUFFER_GPUDYNAMIC=3,t.BUFFER_STATIC=0,t.BUFFER_STREAM=2,t.BUTTON_TRANSITION_MODE_SPRITE_CHANGE=1,t.BUTTON_TRANSITION_MODE_TINT=0,t.BasicMaterial=Vo,t.Batch=Go,t.BatchGroup=Ho,t.BatchManager=Eh,t.BinaryHandler=vS,t.BlendState=Ui,t.BoundingBox=Ht,t.BoundingSphere=jt,t.Bundle=jf,t.BundleHandler=Zf,t.BundleRegistry=Wf,t.ButtonComponent=t_,t.ButtonComponentSystem=s_,t.CHUNKAPI_1_51="1.51",t.CHUNKAPI_1_55="1.55",t.CHUNKAPI_1_56="1.56",t.CHUNKAPI_1_57="1.57",t.CHUNKAPI_1_58="1.58",t.CHUNKAPI_1_60="1.60",t.CHUNKAPI_1_62="1.62",t.CHUNKAPI_1_65=Di,t.CLEARFLAG_COLOR=1,t.CLEARFLAG_DEPTH=2,t.CLEARFLAG_STENCIL=4,t.CUBEFACE_NEGX=1,t.CUBEFACE_NEGY=3,t.CUBEFACE_NEGZ=5,t.CUBEFACE_POSX=0,t.CUBEFACE_POSY=2,t.CUBEFACE_POSZ=4,t.CUBEPROJ_BOX=1,t.CUBEPROJ_NONE=0,t.CULLFACE_BACK=1,t.CULLFACE_FRONT=2,t.CULLFACE_FRONTANDBACK=3,t.CULLFACE_NONE=se,t.CURVE_CARDINAL=3,t.CURVE_CATMULL=2,t.CURVE_LINEAR=0,t.CURVE_SMOOTHSTEP=1,t.CURVE_SPLINE=4,t.CURVE_STEP=5,t.Camera=Gh,t.CameraComponent=Fy,t.CameraComponentSystem=Ny,t.CanvasFont=Ew,t.ChunkBuilder=Xh,t.CollisionComponent=c_,t.CollisionComponentSystem=L_,t.Color=vt,t.Component=bp,t.ComponentSystem=wp,t.ComponentSystemRegistry=Xf,t.ContactPoint=Mg,t.ContactResult=Pg,t.ContainerHandler=SS,t.ContainerResource=xS,t.ContextCreationError=AT,t.Controller=Qr,t.CssHandler=bS,t.CubemapHandler=wS,t.Curve=St,t.CurveSet=bt,t.DETAILMODE_ADD="add",t.DETAILMODE_MAX="max",t.DETAILMODE_MIN="min",t.DETAILMODE_MUL=Da,t.DETAILMODE_OVERLAY="overlay",t.DETAILMODE_SCREEN="screen",t.DEVICETYPE_NULL=bi,t.DEVICETYPE_WEBGL1=yi,t.DEVICETYPE_WEBGL2=xi,t.DEVICETYPE_WEBGPU=Si,t.DISTANCE_EXPONENTIAL=ne,t.DISTANCE_INVERSE=ie,t.DISTANCE_LINEAR=ee,t.DefaultAnimBinder=am,t.DepthState=Ni,t.ELEMENTTYPE_FLOAT32=6,t.ELEMENTTYPE_GROUP=Vm,t.ELEMENTTYPE_IMAGE=Gm,t.ELEMENTTYPE_INT16=2,t.ELEMENTTYPE_INT32=4,t.ELEMENTTYPE_INT8=0,t.ELEMENTTYPE_TEXT=Hm,t.ELEMENTTYPE_UINT16=3,t.ELEMENTTYPE_UINT32=5,t.ELEMENTTYPE_UINT8=wT,t.EMITTERSHAPE_BOX=0,t.EMITTERSHAPE_SPHERE=1,t.EVENT_GAMEPADCONNECTED=zr,t.EVENT_GAMEPADDISCONNECTED=Vr,t.EVENT_KEYDOWN="keydown",t.EVENT_KEYUP="keyup",t.EVENT_MOUSEDOWN=Fr,t.EVENT_MOUSEMOVE=Br,t.EVENT_MOUSEUP=Ur,t.EVENT_MOUSEWHEEL=Nr,t.EVENT_SELECT="select",t.EVENT_SELECTEND="selectend",t.EVENT_SELECTSTART="selectstart",t.EVENT_TOUCHCANCEL="touchcancel",t.EVENT_TOUCHEND="touchend",t.EVENT_TOUCHMOVE="touchmove",t.EVENT_TOUCHSTART="touchstart",t.ElementComponent=fv,t.ElementComponentSystem=vv,t.ElementDragHelper=ny,t.ElementInput=dT,t.ElementInputEvent=hT,t.ElementMouseEvent=lT,t.ElementSelectEvent=uT,t.ElementTouchEvent=cT,t.Entity=ip,t.EntityReference=zm,t.EnvLighting=Wc,t.EventHandler=P,t.FILLMODE_FILL_WINDOW=ff,t.FILLMODE_KEEP_ASPECT=pf,t.FILLMODE_NONE="NONE",t.FILTER_LINEAR=1,t.FILTER_LINEAR_MIPMAP_LINEAR=5,t.FILTER_LINEAR_MIPMAP_NEAREST=4,t.FILTER_NEAREST=0,t.FILTER_NEAREST_MIPMAP_LINEAR=3,t.FILTER_NEAREST_MIPMAP_NEAREST=2,t.FITMODE_CONTAIN=Xm,t.FITMODE_COVER=jm,t.FITMODE_STRETCH=Wm,t.FITTING_BOTH=3,t.FITTING_NONE=0,t.FITTING_SHRINK=2,t.FITTING_STRETCH=1,t.FOG_EXP="exp",t.FOG_EXP2="exp2",t.FOG_LINEAR=Ia,t.FOG_NONE=Ra,t.FONT_BITMAP=U_,t.FONT_MSDF=B_,t.FRESNEL_NONE=0,t.FRESNEL_SCHLICK=2,t.FUNC_ALWAYS=7,t.FUNC_EQUAL=2,t.FUNC_GREATER=4,t.FUNC_GREATEREQUAL=6,t.FUNC_LESS=1,t.FUNC_LESSEQUAL=3,t.FUNC_NEVER=0,t.FUNC_NOTEQUAL=5,t.FolderHandler=TS,t.Font=AS,t.FontHandler=ES,t.ForwardRenderer=yu,t.Frustum=qt,t.GAMMA_NONE=0,t.GAMMA_SRGB=1,t.GAMMA_SRGBFAST=2,t.GAMMA_SRGBHDR=3,t.GamePads=ca,t.GraphNode=hh,t.GraphicsDevice=nn,t.HierarchyHandler=LS,t.HtmlHandler=DS,t.Http=ma,t.I18n=Jf,t.INDEXFORMAT_UINT16=1,t.INDEXFORMAT_UINT32=2,t.INDEXFORMAT_UINT8=0,t.INTERPOLATION_CUBIC=2,t.INTERPOLATION_LINEAR=1,t.INTERPOLATION_STEP=0,t.ImageElement=k_,t.IndexBuffer=vr,t.IndexedList=at,t.JointComponent=bv,t.JointComponentSystem=Cv,t.JsonHandler=OS,t.JsonStandardMaterialParser=FS,t.KEY_0=48,t.KEY_1=49,t.KEY_2=50,t.KEY_3=51,t.KEY_4=52,t.KEY_5=53,t.KEY_6=54,t.KEY_7=55,t.KEY_8=56,t.KEY_9=57,t.KEY_A=65,t.KEY_ADD=107,t.KEY_ALT=18,t.KEY_B=66,t.KEY_BACKSPACE=8,t.KEY_BACK_SLASH=220,t.KEY_C=67,t.KEY_CAPS_LOCK=20,t.KEY_CLOSE_BRACKET=221,t.KEY_COMMA=188,t.KEY_CONTEXT_MENU=93,t.KEY_CONTROL=17,t.KEY_D=68,t.KEY_DECIMAL=110,t.KEY_DELETE=46,t.KEY_DIVIDE=111,t.KEY_DOWN=40,t.KEY_E=69,t.KEY_END=35,t.KEY_ENTER=13,t.KEY_EQUAL=61,t.KEY_ESCAPE=27,t.KEY_F=70,t.KEY_F1=112,t.KEY_F10=121,t.KEY_F11=122,t.KEY_F12=123,t.KEY_F2=113,t.KEY_F3=114,t.KEY_F4=115,t.KEY_F5=116,t.KEY_F6=117,t.KEY_F7=118,t.KEY_F8=119,t.KEY_F9=120,t.KEY_G=71,t.KEY_H=72,t.KEY_HOME=36,t.KEY_I=73,t.KEY_INSERT=45,t.KEY_J=74,t.KEY_K=75,t.KEY_L=76,t.KEY_LEFT=37,t.KEY_M=77,t.KEY_META=224,t.KEY_MULTIPLY=106,t.KEY_N=78,t.KEY_NUMPAD_0=96,t.KEY_NUMPAD_1=97,t.KEY_NUMPAD_2=98,t.KEY_NUMPAD_3=99,t.KEY_NUMPAD_4=100,t.KEY_NUMPAD_5=101,t.KEY_NUMPAD_6=102,t.KEY_NUMPAD_7=103,t.KEY_NUMPAD_8=104,t.KEY_NUMPAD_9=105,t.KEY_O=79,t.KEY_OPEN_BRACKET=219,t.KEY_P=80,t.KEY_PAGE_DOWN=34,t.KEY_PAGE_UP=33,t.KEY_PAUSE=19,t.KEY_PERIOD=190,t.KEY_PRINT_SCREEN=44,t.KEY_Q=81,t.KEY_R=82,t.KEY_RETURN=13,t.KEY_RIGHT=39,t.KEY_S=83,t.KEY_SEMICOLON=59,t.KEY_SEPARATOR=108,t.KEY_SHIFT=16,t.KEY_SLASH=191,t.KEY_SPACE=32,t.KEY_SUBTRACT=109,t.KEY_T=84,t.KEY_TAB=9,t.KEY_U=85,t.KEY_UP=38,t.KEY_V=86,t.KEY_W=87,t.KEY_WINDOWS=91,t.KEY_X=88,t.KEY_Y=89,t.KEY_Z=90,t.Key=tf,t.Keyboard=qr,t.KeyboardEvent=Gr,t.LAYERID_DEPTH=1,t.LAYERID_IMMEDIATE=3,t.LAYERID_SKYBOX=2,t.LAYERID_UI=4,t.LAYERID_WORLD=0,t.LAYER_FX=2,t.LAYER_GIZMO=1,t.LAYER_HUD=0,t.LAYER_WORLD=15,t.LIGHTFALLOFF_INVERSESQUARED=1,t.LIGHTFALLOFF_LINEAR=0,t.LIGHTSHAPE_DISK=2,t.LIGHTSHAPE_PUNCTUAL=0,t.LIGHTSHAPE_RECT=1,t.LIGHTSHAPE_SPHERE=3,t.LIGHTTYPE_COUNT=3,t.LIGHTTYPE_DIRECTIONAL=0,t.LIGHTTYPE_OMNI=1,t.LIGHTTYPE_POINT=1,t.LIGHTTYPE_SPOT=2,t.LINEBATCH_GIZMO=2,t.LINEBATCH_OVERLAY=1,t.LINEBATCH_WORLD=0,t.Layer=Cu,t.LayerComposition=Ru,t.LayoutCalculator=zv,t.LayoutChildComponent=Ev,t.LayoutChildComponentSystem=Rv,t.LayoutGroupComponent=Hv,t.LayoutGroupComponentSystem=jv,t.Light=Uu,t.LightComponent=Gy,t.LightComponentSystem=Xy,t.LightingParams=Nu,t.Lightmapper=Sp,t.LitMaterial=gl,t.LitOptions=OT,t.LitShaderOptions=Hh,t.LocalizedAsset=F_,t.MASK_AFFECT_DYNAMIC=1,t.MASK_AFFECT_LIGHTMAPPED=2,t.MASK_BAKE=4,t.MOTION_FREE=gv,t.MOTION_LIMITED=yv,t.MOTION_LOCKED=xv,t.MOUSEBUTTON_LEFT=0,t.MOUSEBUTTON_MIDDLE=1,t.MOUSEBUTTON_NONE=-1,t.MOUSEBUTTON_RIGHT=2,t.Mat3=At,t.Mat4=Ft,t.Material=zo,t.MaterialHandler=US,t.Mesh=qa,t.MeshInstance=yh,t.Model=Gu,t.ModelComponent=qv,t.ModelComponentSystem=Zv,t.ModelHandler=jS,t.Morph=Hu,t.MorphInstance=Vu,t.MorphTarget=Wu,t.Mouse=Zr,t.MouseEvent=Kr,t.Node=ef,t.NullGraphicsDevice=mr,t.ORIENTATION_HORIZONTAL=0,t.ORIENTATION_VERTICAL=1,t.OrientedBox=Jt,t.PAD_1=0,t.PAD_2=1,t.PAD_3=2,t.PAD_4=3,t.PAD_DOWN=13,t.PAD_FACE_1=0,t.PAD_FACE_2=1,t.PAD_FACE_3=2,t.PAD_FACE_4=3,t.PAD_LEFT=14,t.PAD_L_SHOULDER_1=4,t.PAD_L_SHOULDER_2=6,t.PAD_L_STICK_BUTTON=10,t.PAD_L_STICK_X=0,t.PAD_L_STICK_Y=1,t.PAD_RIGHT=15,t.PAD_R_SHOULDER_1=5,t.PAD_R_SHOULDER_2=7,t.PAD_R_STICK_BUTTON=11,t.PAD_R_STICK_X=2,t.PAD_R_STICK_Y=3,t.PAD_SELECT=8,t.PAD_START=9,t.PAD_UP=12,t.PAD_VENDOR=16,t.PARTICLEMODE_CPU=1,t.PARTICLEMODE_GPU=0,t.PARTICLEORIENTATION_EMITTER=2,t.PARTICLEORIENTATION_SCREEN=0,t.PARTICLEORIENTATION_WORLD=1,t.PARTICLESORT_DISTANCE=1,t.PARTICLESORT_NEWER_FIRST=2,t.PARTICLESORT_NONE=0,t.PARTICLESORT_OLDER_FIRST=3,t.PIXELFORMAT_111110F=fe,t.PIXELFORMAT_A8=0,t.PIXELFORMAT_ASTC_4x4=28,t.PIXELFORMAT_ATC_RGB=29,t.PIXELFORMAT_ATC_RGBA=30,t.PIXELFORMAT_BGRA8=31,t.PIXELFORMAT_DEPTH=ue,t.PIXELFORMAT_DEPTHSTENCIL=de,t.PIXELFORMAT_DXT1=8,t.PIXELFORMAT_DXT3=9,t.PIXELFORMAT_DXT5=re,t.PIXELFORMAT_ETC1=pe,t.PIXELFORMAT_ETC2_RGB=22,t.PIXELFORMAT_ETC2_RGBA=23,t.PIXELFORMAT_L8=1,t.PIXELFORMAT_L8_A8=2,t.PIXELFORMAT_LA8=2,t.PIXELFORMAT_PVRTC_2BPP_RGBA_1=_e,t.PIXELFORMAT_PVRTC_2BPP_RGB_1=me,t.PIXELFORMAT_PVRTC_4BPP_RGBA_1=ge,t.PIXELFORMAT_PVRTC_4BPP_RGB_1=ve,t.PIXELFORMAT_R32F=ce,t.PIXELFORMAT_R4_G4_B4_A4=5,t.PIXELFORMAT_R5_G5_B5_A1=4,t.PIXELFORMAT_R5_G6_B5=3,t.PIXELFORMAT_R8_G8_B8=6,t.PIXELFORMAT_R8_G8_B8_A8=7,t.PIXELFORMAT_RGB16F=ae,t.PIXELFORMAT_RGB32F=he,t.PIXELFORMAT_RGB565=3,t.PIXELFORMAT_RGB8=6,t.PIXELFORMAT_RGBA16F=oe,t.PIXELFORMAT_RGBA32F=le,t.PIXELFORMAT_RGBA4=5,t.PIXELFORMAT_RGBA5551=4,t.PIXELFORMAT_RGBA8=7,t.PIXELFORMAT_SRGB=19,t.PIXELFORMAT_SRGBA=20,t.PRIMITIVE_LINELOOP=2,t.PRIMITIVE_LINES=1,t.PRIMITIVE_LINESTRIP=3,t.PRIMITIVE_POINTS=0,t.PRIMITIVE_TRIANGLES=4,t.PRIMITIVE_TRIFAN=6,t.PRIMITIVE_TRISTRIP=be,t.PROJECTION_ORTHOGRAPHIC=1,t.PROJECTION_PERSPECTIVE=0,t.ParticleEmitter=Nd,t.ParticleSystemComponent=ig,t.ParticleSystemComponentSystem=rg,t.PhongMaterial=DT,t.Picker=Lw,t.Plane=te,t.PostEffect=of,t.PostEffectQueue=ky,t.ProgramLibrary=uf,t.QuadRender=Mo,t.Quat=Bt,t.RENDERSTYLE_POINTS=2,t.RENDERSTYLE_SOLID=0,t.RENDERSTYLE_WIREFRAME=1,t.RESOLUTION_AUTO=mf,t.RESOLUTION_FIXED=_f,t.RIGIDBODY_ACTIVE_TAG=1,t.RIGIDBODY_CF_KINEMATIC_OBJECT=2,t.RIGIDBODY_CF_NORESPONSE_OBJECT=4,t.RIGIDBODY_CF_STATIC_OBJECT=1,t.RIGIDBODY_DISABLE_DEACTIVATION=4,t.RIGIDBODY_DISABLE_SIMULATION=5,t.RIGIDBODY_ISLAND_SLEEPING=2,t.RIGIDBODY_TYPE_DYNAMIC=XT,t.RIGIDBODY_TYPE_KINEMATIC=jT,t.RIGIDBODY_TYPE_STATIC=WT,t.RIGIDBODY_WANTS_DEACTIVATION=3,t.Ray=Yt,t.RaycastResult=Cg,t.ReadStream=lt,t.RenderComponent=lg,t.RenderComponentSystem=fg,t.RenderHandler=ax,t.RenderTarget=rn,t.ResourceHandler=Dw,t.ResourceLoader=Qf,t.RigidBodyComponent=Tg,t.RigidBodyComponentSystem=Ig,t.SAMPLETYPE_DEPTH=2,t.SAMPLETYPE_FLOAT=0,t.SAMPLETYPE_UNFILTERABLE_FLOAT=1,t.SCALEMODE_BLEND=Dg,t.SCALEMODE_NONE=Lg,t.SCROLLBAR_VISIBILITY_SHOW_ALWAYS=0,t.SCROLLBAR_VISIBILITY_SHOW_WHEN_REQUIRED=1,t.SCROLL_MODE_BOUNCE=1,t.SCROLL_MODE_CLAMP=0,t.SCROLL_MODE_INFINITE=2,t.SEMANTIC_ATTR=Ue,t.SEMANTIC_ATTR0=Ne,t.SEMANTIC_ATTR1=ze,t.SEMANTIC_ATTR10=Ke,t.SEMANTIC_ATTR11=Ze,t.SEMANTIC_ATTR12=Qe,t.SEMANTIC_ATTR13=$e,t.SEMANTIC_ATTR14=Je,t.SEMANTIC_ATTR15=ti,t.SEMANTIC_ATTR2=Ve,t.SEMANTIC_ATTR3=Ge,t.SEMANTIC_ATTR4=He,t.SEMANTIC_ATTR5=We,t.SEMANTIC_ATTR6=Xe,t.SEMANTIC_ATTR7=je,t.SEMANTIC_ATTR8=qe,t.SEMANTIC_ATTR9=Ye,t.SEMANTIC_BLENDINDICES=Ee,t.SEMANTIC_BLENDWEIGHT=Ce,t.SEMANTIC_COLOR=Me,t.SEMANTIC_NORMAL=Te,t.SEMANTIC_POSITION=we,t.SEMANTIC_TANGENT=Ae,t.SEMANTIC_TEXCOORD=Pe,t.SEMANTIC_TEXCOORD0=Re,t.SEMANTIC_TEXCOORD1=Ie,t.SEMANTIC_TEXCOORD2=Le,t.SEMANTIC_TEXCOORD3=De,t.SEMANTIC_TEXCOORD4=Oe,t.SEMANTIC_TEXCOORD5=ke,t.SEMANTIC_TEXCOORD6=Fe,t.SEMANTIC_TEXCOORD7=Be,t.SHADERDEF_DIRLM=ka,t.SHADERDEF_INSTANCING=Oa,t.SHADERDEF_LM=64,t.SHADERDEF_LMAMBIENT=Va,t.SHADERDEF_MORPH_NORMAL=Na,t.SHADERDEF_MORPH_POSITION=Ua,t.SHADERDEF_MORPH_TEXTURE_BASED=za,t.SHADERDEF_NOSHADOW=1,t.SHADERDEF_SCREENSPACE=Fa,t.SHADERDEF_SKIN=2,t.SHADERDEF_TANGENTS=Ba,t.SHADERDEF_UV0=4,t.SHADERDEF_UV1=8,t.SHADERDEF_VCOLOR=16,t.SHADERLANGUAGE_GLSL="glsl",t.SHADERLANGUAGE_WGSL=pi,t.SHADERPASS_ALBEDO="debug_albedo",t.SHADERPASS_AO="debug_ao",t.SHADERPASS_EMISSION="debug_emission",t.SHADERPASS_FORWARD="forward",t.SHADERPASS_GLOSS="debug_gloss",t.SHADERPASS_LIGHTING="debug_lighting",t.SHADERPASS_METALNESS="debug_metalness",t.SHADERPASS_OPACITY="debug_opacity",t.SHADERPASS_SPECULARITY="debug_specularity",t.SHADERPASS_UV0="debug_uv0",t.SHADERPASS_WORLDNORMAL="debug_world_normal",t.SHADERSTAGE_COMPUTE=4,t.SHADERSTAGE_FRAGMENT=2,t.SHADERSTAGE_VERTEX=1,t.SHADERTAG_MATERIAL=1,t.SHADER_DEPTH=2,t.SHADER_FORWARD=0,t.SHADER_FORWARDHDR=1,t.SHADER_PICK=3,t.SHADER_SHADOW=4,t.SHADOWUPDATE_NONE=0,t.SHADOWUPDATE_REALTIME=2,t.SHADOWUPDATE_THISFRAME=1,t.SHADOW_DEPTH=0,t.SHADOW_PCF1=5,t.SHADOW_PCF3=0,t.SHADOW_PCF5=4,t.SHADOW_PCSS=6,t.SHADOW_VSM16=2,t.SHADOW_VSM32=3,t.SHADOW_VSM8=1,t.SORTKEY_DEPTH=1,t.SORTKEY_FORWARD=0,t.SORTMODE_BACK2FRONT=3,t.SORTMODE_CUSTOM=5,t.SORTMODE_FRONT2BACK=4,t.SORTMODE_MANUAL=1,t.SORTMODE_MATERIALMESH=2,t.SORTMODE_NONE=0,t.SPECOCC_AO=1,t.SPECOCC_GLOSSDEPENDENT=2,t.SPECOCC_NONE=0,t.SPECULAR_BLINN=1,t.SPECULAR_PHONG=0,t.SPRITETYPE_ANIMATED=xy,t.SPRITETYPE_SIMPLE=yy,t.SPRITE_RENDERMODE_SIMPLE=0,t.SPRITE_RENDERMODE_SLICED=1,t.SPRITE_RENDERMODE_TILED=2,t.STENCILOP_DECREMENT=5,t.STENCILOP_DECREMENTWRAP=6,t.STENCILOP_INCREMENT=3,t.STENCILOP_INCREMENTWRAP=4,t.STENCILOP_INVERT=7,t.STENCILOP_KEEP=0,t.STENCILOP_REPLACE=2,t.STENCILOP_ZERO=1,t.Scene=Yd,t.SceneHandler=qS,t.SceneRegistry=rp,t.SceneRegistryItem=sp,t.SceneSettingsHandler=Ow,t.ScopeId=Hi,t.ScopeSpace=Wi,t.ScreenComponent=kg,t.ScreenComponentSystem=Ug,t.ScriptAttributes=Ky,t.ScriptComponent=$y,t.ScriptComponentSystem=ex,t.ScriptHandler=YS,t.ScriptLegacyComponent=Ng,t.ScriptLegacyComponentSystem=Yg,t.ScriptRegistry=tp,t.ScriptType=pT,t.ScrollViewComponent=ry,t.ScrollViewComponentSystem=hy,t.ScrollbarComponent=ly,t.ScrollbarComponentSystem=dy,t.Shader=fs,t.ShaderHandler=KS,t.ShaderPass=Do,t.SingleContactResult=Eg,t.Skeleton=rf,t.Skin=Kd,t.SkinBatchInstance=jo,t.SkinInstance=Xo,t.SortedLoopArray=ct,t.Sound=Aa,t.SoundComponent=my;t.SoundComponentSystem=gy,t.SoundInstance=Ea,t.SoundInstance3d=Ma,t.SoundManager=Ta,t.SoundSlot=py,t.Sprite=$d,t.SpriteAnimationClip=Sy,t.SpriteComponent=Cy,t.SpriteComponentSystem=Py,t.SpriteHandler=$S,t.StandardMaterial=lu,t.StandardMaterialOptions=Xc,t.StencilParameters=en,t.TEXHINT_ASSET=2,t.TEXHINT_LIGHTMAP=3,t.TEXHINT_NONE=0,t.TEXHINT_SHADOWMAP=1,t.TEXTUREDIMENSION_1D="1d",t.TEXTUREDIMENSION_2D=ai,t.TEXTUREDIMENSION_2D_ARRAY=oi,t.TEXTUREDIMENSION_3D=li,t.TEXTUREDIMENSION_CUBE=hi,t.TEXTUREDIMENSION_CUBE_ARRAY="cube-array",t.TEXTURELOCK_READ=1,t.TEXTURELOCK_WRITE=2,t.TEXTUREPROJECTION_CUBE=ui,t.TEXTUREPROJECTION_EQUIRECT=di,t.TEXTUREPROJECTION_NONE=ci,t.TEXTUREPROJECTION_OCTAHEDRAL=fi,t.TEXTURETYPE_DEFAULT=ei,t.TEXTURETYPE_RGBE=ni,t.TEXTURETYPE_RGBM=ii,t.TEXTURETYPE_RGBP=si,t.TEXTURETYPE_SWIZZLEGGGR=ri,t.TONEMAP_ACES=3,t.TONEMAP_ACES2=4,t.TONEMAP_FILMIC=1,t.TONEMAP_HEJL=2,t.TONEMAP_LINEAR=0,t.TRACEID_BINDGROUPFORMAT_ALLOC="BindGroupFormatAlloc",t.TRACEID_BINDGROUP_ALLOC="BindGroupAlloc",t.TRACEID_GPU_TIMINGS=l,t.TRACEID_PIPELINELAYOUT_ALLOC="PipelineLayoutAlloc",t.TRACEID_RENDERPIPELINE_ALLOC="RenderPipelineAlloc",t.TRACEID_RENDER_ACTION="RenderAction",t.TRACEID_RENDER_FRAME="RenderFrame",t.TRACEID_RENDER_FRAME_TIME="RenderFrameTime",t.TRACEID_RENDER_PASS="RenderPass",t.TRACEID_RENDER_PASS_DETAIL="RenderPassDetail",t.TRACEID_RENDER_QUEUE="RenderQueue",t.TRACEID_RENDER_TARGET_ALLOC="RenderTargetAlloc",t.TRACEID_SHADER_ALLOC="ShaderAlloc",t.TRACEID_SHADER_COMPILE="ShaderCompile",t.TRACEID_TEXTURES="Textures",t.TRACEID_TEXTURE_ALLOC="TextureAlloc",t.TRACEID_VRAM_IB="VRAM.Ib",t.TRACEID_VRAM_TEXTURE="VRAM.Texture",t.TRACEID_VRAM_VB="VRAM.Vb",t.TRACE_ID_ELEMENT="Element",t.TYPE_FLOAT32=6,t.TYPE_INT16=2,t.TYPE_INT32=4,t.TYPE_INT8=0,t.TYPE_UINT16=3,t.TYPE_UINT32=5,t.TYPE_UINT8=mi,t.Tags=ut,t.Template=JS,t.TemplateHandler=tb,t.TextElement=sv,t.TextHandler=eb,t.Texture=Ls,t.TextureAtlas=Jd,t.TextureAtlasHandler=rb,t.TextureHandler=Ob,t.TextureParser=Db,t.TextureUtils=Kn,t.Touch=da,t.TouchDevice=pa,t.TouchEvent=fa,t.Tracing=E,t.TransformFeedback=gr,t.UNIFORMTYPE_BOOL=0,t.UNIFORMTYPE_BVEC2=9,t.UNIFORMTYPE_BVEC3=10,t.UNIFORMTYPE_BVEC4=11,t.UNIFORMTYPE_FLOAT=2,t.UNIFORMTYPE_FLOATARRAY=17,t.UNIFORMTYPE_INT=1,t.UNIFORMTYPE_IVEC2=6,t.UNIFORMTYPE_IVEC3=7,t.UNIFORMTYPE_IVEC4=8,t.UNIFORMTYPE_MAT2=12,t.UNIFORMTYPE_MAT3=_i,t.UNIFORMTYPE_MAT4=vi,t.UNIFORMTYPE_MAT4ARRAY=24,t.UNIFORMTYPE_TEXTURE2D=15,t.UNIFORMTYPE_TEXTURE2D_SHADOW=18,t.UNIFORMTYPE_TEXTURE3D=20,t.UNIFORMTYPE_TEXTURECUBE=16,t.UNIFORMTYPE_TEXTURECUBE_SHADOW=19,t.UNIFORMTYPE_VEC2=3,t.UNIFORMTYPE_VEC2ARRAY=21,t.UNIFORMTYPE_VEC3=4,t.UNIFORMTYPE_VEC3ARRAY=22,t.UNIFORMTYPE_VEC4=5,t.UNIFORMTYPE_VEC4ARRAY=23,t.UNIFORM_BUFFER_DEFAULT_SLOT_NAME=Ti,t.URI=mt,t.UnsupportedBrowserError=TT,t.VIEW_CENTER=0,t.VIEW_LEFT=1,t.VIEW_RIGHT=2,t.Vec2=Et,t.Vec3=wt,t.Vec4=Pt,t.VertexBuffer=ji,t.VertexFormat=Ji,t.VertexIterator=Lr,t.WasmModule=ht,t.WebglGraphicsDevice=lr,t.WebgpuGraphicsDevice=Rs,t.WorldClusters=Al,t.XRDEPTHSENSINGFORMAT_F32="float32",t.XRDEPTHSENSINGFORMAT_L8A8=Gb,t.XRDEPTHSENSINGUSAGE_CPU=zb,t.XRDEPTHSENSINGUSAGE_GPU=Vb,t.XRHAND_LEFT=Nb,t.XRHAND_NONE="none",t.XRHAND_RIGHT="right",t.XRPAD_A=4,t.XRPAD_B=5,t.XRPAD_SQUEEZE=1,t.XRPAD_STICK_BUTTON=3,t.XRPAD_STICK_X=2,t.XRPAD_STICK_Y=3,t.XRPAD_TOUCHPAD_BUTTON=2,t.XRPAD_TOUCHPAD_X=0,t.XRPAD_TOUCHPAD_Y=1,t.XRPAD_TRIGGER=0,t.XRSPACE_BOUNDEDFLOOR="bounded-floor",t.XRSPACE_LOCAL="local",t.XRSPACE_LOCALFLOOR="local-floor",t.XRSPACE_UNBOUNDED="unbounded",t.XRSPACE_VIEWER=Ub,t.XRTARGETRAY_GAZE="gaze",t.XRTARGETRAY_POINTER="tracked-pointer",t.XRTARGETRAY_SCREEN="screen",t.XRTRACKABLE_MESH="mesh",t.XRTRACKABLE_PLANE="plane",t.XRTRACKABLE_POINT="point",t.XRTYPE_AR=Bb,t.XRTYPE_INLINE=kb,t.XRTYPE_VR=Fb,t.XrAnchor=Sw,t.XrAnchors=bw,t.XrDepthSensing=Hb,t.XrDomOverlay=Wb,t.XrHitTest=Yb,t.XrHitTestSource=qb,t.XrImageTracking=Zb,t.XrInput=dw,t.XrInputSource=uw,t.XrLightEstimation=vw,t.XrManager=ww,t.XrPlane=yw,t.XrPlaneDetection=xw,t.XrTrackedImage=Kb,t.ZoneComponent=Ry,t.ZoneComponentSystem=Dy,t.anim=VT,t.apps={},t.asset={ASSET_ANIMATION:"animation",ASSET_AUDIO:"audio",ASSET_IMAGE:"image",ASSET_JSON:"json",ASSET_MODEL:"model",ASSET_MATERIAL:"material",ASSET_TEXT:"text",ASSET_TEXTURE:"texture",ASSET_CUBEMAP:"cubemap",ASSET_SCRIPT:"script"},t.audio=GT,t.basisInitialize=gb,t.basisSetDownloadConfig=function(t,e,i){gb({glueUrl:t,wasmUrl:e,fallbackUrl:i,lazyInit:!0})},t.bindGroupNames=wi,t.calculateNormals=Qa,t.calculateTangents=$a,t.common={},t.config={},t.createBox=oo,t.createCapsule=no,t.createCone=so,t.createCylinder=io,t.createGraphicsDevice=function(t,e){var i;void 0===e&&(e={});var n,s=null!=(i=e.deviceTypes)?i:[];s.includes(xi)||s.push(xi),s.includes(yi)||s.push(yi),s.includes(bi)||s.push(bi),G.browser&&navigator.xr&&(null!=(n=e).xrCompatible||(n.xrCompatible=!0));for(var r=[],a=function(){var i,n=s[o];n===Si&&null!=(i=window)&&null!=(i=i.navigator)&&i.gpu&&r.push((function(){return new Rs(t,e).initWebGpu(e.glslangUrl,e.twgslUrl)})),n!==yi&&n!==xi||r.push((function(){return e.preferWebGl2=n===xi,new lr(t,e)})),n===bi&&r.push((function(){return new mr(t,e)}))},o=0;o<s.length;o++)a();return new Promise((function(t,e){var i=0;!function n(){i>=r.length?e(new Error("Failed to create a graphics device")):Promise.resolve(r[i++]()).then((function(e){e?t(e):n()})).catch((function(t){console.log(t),n()}))}()}))},t.createMesh=Ja,t.createPlane=ao,t.createScript=_T,t.createShader=So,t.createShaderFromCode=bo,t.createSphere=ro,t.createStyle=function(t){var e=document.createElement("style");return e.type="text/css",e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t)),e},t.createTorus=to,t.createURI=function(t){var e="";if((t.authority||t.scheme)&&(t.host||t.hostpath))throw new Error("Can't have 'scheme' or 'authority' and 'host' or 'hostpath' option");if(t.host&&t.hostpath)throw new Error("Can't have 'host' and 'hostpath' option");if(t.path&&t.hostpath)throw new Error("Can't have 'path' and 'hostpath' option");return t.scheme&&(e+=t.scheme+":"),t.authority&&(e+="//"+t.authority),t.host&&(e+=t.host),t.path&&(e+=t.path),t.hostpath&&(e+=t.hostpath),t.query&&(e+="?"+t.query),t.fragment&&(e+="#"+t.fragment),e},t.data={},t.dracoInitialize=function(t){null!=t&&t.lazyInit?ux=t:_x(t)},t.drawFullscreenQuad=PT,t.drawQuadWithShader=Ro,t.drawTexture=function(t,e,i,n,s,r){n=n||t.getCopyShader(),t.constantTexSource.setValue(e),Ro(t,i,n,s,r)},t.events=R,t.extend=p,t.getPixelFormatArrayType=Se,t.getReservedScriptNames=function(){return mT},t.getTouchTargetCoords=ua,t.gfx=ET,t.guid=I,t.http=_a,t.inherits=function(t,e){var i=function(){},n=function(i,n,s,r,a,o,h,l){e.call(this,i,n,s,r,a,o,h,l),t.call(this,i,n,s,r,a,o,h,l)};return n._super=e.prototype,i.prototype=e.prototype,n.prototype=new i,n},t.input=HT,t.isCompressedPixelFormat=xe,t.log=yT,t.makeArray=function(t){return Array.prototype.slice.call(t)},t.math=_t,t.now=dt,t.path=L,t.pixelFormatInfo=ye,t.platform=G,t.posteffect=RT,t.prefilterCubemap=function(t){},t.programlib=CT,t.registerScript=gT,t.reprojectTexture=Gc,t.revision=u,t.scene=kT,t.script=bf,t.semanticToLocation=Ri,t.shFromCubemap=function(t,e,i){if(7!==e.format)return null;if(!e._levels[0]||!e._levels[0][0])return null;var n=e.width;if(!e._levels[0][0].length){if(!(e._levels[0][0]instanceof HTMLImageElement))return null;for(var s=bo(t,_o.fullscreenQuadVS,_o.fullscreenQuadPS,"fsQuadSimple"),r=t.scope.resolve("source"),a=0;a<6;a++){var o=e._levels[0][a],h=new Ls(t,{name:"prefiltered-cube",cubemap:!1,type:ei,format:e.format,width:n,height:n,mipmaps:!1});h._levels[0]=o,h.upload();var l=new Ls(t,{name:"prefiltered-cube",cubemap:!1,type:ei,format:e.format,width:n,height:n,mipmaps:!1}),c=new rn({colorBuffer:l,depth:!1});r.setValue(h),t.setBlendState(Ui.NOBLEND),Ro(t,c,s);var u=t.gl;u.bindFramebuffer(u.FRAMEBUFFER,c.impl._glFrameBuffer);var d=new Uint8Array(n*n*4);u.readPixels(0,0,h.width,h.height,u.RGBA,u.UNSIGNED_BYTE,d),e._levels[0][a]=d}}for(var f=[],p=0;p<n;p++)for(var m=0;m<n;m++){var _=m/(n-1)*2-1,v=p/(n-1)*2-1;f[p*n+m]=new wt(_,v,1).normalize()}for(var g=new Float32Array(27),y=0,x=0;x<6;x++)for(var S=0;S<n;S++)for(var b=0;b<n;b++){var w=S*n+b,T=lf(b,S,n),A=4*T/17,C=8*T/17,E=15*T/17,M=5*T/68,P=15*T/68,R=f[w],I=void 0,L=void 0,D=void 0;0===x?(I=R.z,L=-R.y,D=-R.x):1===x?(I=-R.z,L=-R.y,D=R.x):2===x?(I=R.x,L=R.z,D=R.y):3===x?(I=R.x,L=-R.z,D=-R.y):4===x?(I=R.x,L=-R.y,D=R.z):5===x&&(I=-R.x,L=-R.y,D=-R.z),i||(I=-I);for(var O=e._levels[0][x][4*w+3]/255,k=0;k<3;k++){var F=e._levels[0][x][4*w+k]/255;e.type===ii?(F*=8*O,F*=F):F=Math.pow(F,2.2),g[0+k]+=F*A,g[3+k]+=F*C*I,g[6+k]+=F*C*L,g[9+k]+=F*C*D,g[12+k]+=F*E*I*D,g[15+k]+=F*E*D*L,g[18+k]+=F*E*L*I,g[21+k]+=F*M*(3*D*D-1),g[24+k]+=F*P*(I*I-L*L),y+=T}}for(var B=0;B<g.length;B++)g[B]*=4*Math.PI/y;return g},t.shaderChunks=_o,t.shaderChunksLightmapper=df,t.shadowTypeToString=La,t.shape=bT,t.string=rt,t.time=ST,t.type=f,t.typedArrayIndexFormats=Mi,t.typedArrayIndexFormatsByteSize=Pi,t.typedArrayToType=Ei,t.typedArrayTypes=Ai,t.typedArrayTypesByteSize=Ci,t.uniformTypeToName=gi,t.version=c,t.vertexTypesNames=["INT8","UINT8","INT16","UINT16","INT32","UINT32","FLOAT32"]}));
|