/** * @license * PlayCanvas Engine v1.51.5 revision 5a9a2396d * Copyright 2011-2022 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";Array.prototype.fill||Object.defineProperty(Array.prototype,"fill",{value: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],s=n>>0,a=s<0?Math.max(i+s,0):Math.min(s,i),r=arguments[2],o=void 0===r?i:r>>0,h=o<0?Math.max(i+o,0):Math.min(o,i);a>>0;if("function"!=typeof t)throw TypeError("predicate must be a function");for(var n=arguments[1],s=0;s>>0;if("function"!=typeof t)throw new TypeError("predicate must be a function");for(var n=arguments[1],s=0;s0)-(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;nthis.length)&&(e=this.length),this.substring(e-t.length,e)===t}),String.prototype.includes||(String.prototype.includes=function(t,e){return"number"!=typeof e&&(e=0),!(e+t.length>this.length)&&-1!==this.indexOf(t,e)}),String.prototype.startsWith||(String.prototype.startsWith=function(t,e){return this.substr(!e||e<0?0:+e,t.length)===t}),Int8Array.prototype.fill||(Int8Array.prototype.fill=Array.prototype.fill),Uint8Array.prototype.fill||(Uint8Array.prototype.fill=Array.prototype.fill),Uint8ClampedArray.prototype.fill||(Uint8ClampedArray.prototype.fill=Array.prototype.fill),Int16Array.prototype.fill||(Int16Array.prototype.fill=Array.prototype.fill),Uint16Array.prototype.fill||(Uint16Array.prototype.fill=Array.prototype.fill),Int32Array.prototype.fill||(Int32Array.prototype.fill=Array.prototype.fill),Uint32Array.prototype.fill||(Uint32Array.prototype.fill=Array.prototype.fill),Float32Array.prototype.fill||(Float32Array.prototype.fill=Array.prototype.fill);var e={};function i(t,i){var n;e[t]=!0,void 0!==i&&(n=i,window.console&&window.console.error&&window.console.error(n))}var n=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;n0?a=a.slice(0,a.length-2):(r>0&&a.push(p.delimiter),a.push(n[r])));return s=a.join(""),e||s[0]!==p.delimiter||(s=s.slice(1)),i&&s[s.length-1]!==p.delimiter&&(s+=p.delimiter),s},split:function(t){var e=t.split(p.delimiter),i=e.slice(e.length-1)[0];return[e.slice(0,e.length-1).join(p.delimiter),i]},getBasename:function(t){return p.split(t)[1]},getDirectory:function(t){var e=t.split(p.delimiter);return e.slice(0,e.length-1).join(p.delimiter)},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(p.isRelativePath(t))if("."===i[0])for(n=0;n0),S="getGamepads"in navigator,w="undefined"!=typeof Worker;try{var M=Object.defineProperty({},"passive",{get:function(){return T=!0,!1}});window.addEventListener("testpassive",null,M),window.removeEventListener("testpassive",null,M)}catch(t){}}var C="undefined"!=typeof window?"browser":"node",E={environment:C,global:"browser"===C?window:global,browser:"browser"===C,desktop:m,mobile:_,ios:x,android:y,windows:g,xbox:v,gamepads:S,touch:b,workers:w,passiveEvents:T},P="abcdefghijklmnopqrstuvwxyz",R="ABCDEFGHIJKLMNOPQRSTUVWXYZ",I=55296,L=127462,D=127487,O=65024,k=65039;function F(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>=I&&n<=56319){var s=t.charCodeAt(e+1);if(s>=56320&&s<=57343)return{code:1024*(n-I)+s-56320+65536,long:!0}}return{code:n,long:!1}}function B(t,e,i){if(!t)return!1;var n=F(t);if(n){var s=n.code;return s>=e&&s<=i}return!1}function N(t,e){if(e===t.length-1)return 1;if(B(t[e],I,56319)){var i=t.substring(e,e+2),n=t.substring(e+2,e+4);return B(n,127995,127999)||B(i,L,D)&&B(n,L,D)?4:B(n,O,k)?3:2}return B(t[e+1],O,k)?2:1}var U={ASCII_LOWERCASE:P,ASCII_UPPERCASE:R,ASCII_LETTERS:"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",format:function(t){for(var e=1;e65535?[55296+(e>>10),e%1024+56320]:[t],n.push(String.fromCharCode.apply(null,i));return n.join("")}},z=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}();function V(t,e){for(var i=0;it.length)&&(e=t.length);for(var i=0,n=new Array(e);i=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.")}var K=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.byteLength);){var i=String.fromCharCode(this.readU8());if("\n"===i)break;e+=i}return e},G(t,[{key:"remainingBytes",get:function(){return this.dataView.byteLength-this.offset}}]),t}(),Z=function(){function t(t){this._sortBy=t.sortBy,this.items=[],this.length=0,this.loopIndex=-1,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,a=t[this._sortBy];n<=s;)e=Math.floor((n+s)/2),(i=this.items[e][this._sortBy])<=a?n=e+1:i>a&&(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}(),$=function(t){function e(e){var i;return(i=t.call(this)||this)._index={},i._list=[],i._parent=e,i}H(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=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)>>>32},lerp:function(t,e,i){return t+(e-t)*it.clamp(i,0,1)},lerpAngle:function(t,e,i){return e-t>180&&(e-=360),e-t<-180&&(e+=360),it.lerp(t,e,it.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},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),a=Math.max(e,i);return n?t>=s&&t<=a:t>s&&t=0?t.ResponseType.ARRAY_BUFFER:".xml"===n?t.ResponseType.DOCUMENT:t.ResponseType.TEXT},e._isBinaryContentType=function(e){return[t.ContentType.MP4,t.ContentType.WAV,t.ContentType.OGG,t.ContentType.MP3,t.ContentType.BIN,t.ContentType.DDS,t.ContentType.BASIS,t.ContentType.GLB].indexOf(e)>=0},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 a,r,o=s.getResponseHeader("Content-Type");o&&(r=o.split(";")[0].trim());try{a=r===t.ContentType.JSON||i.split("?")[0].endsWith(".json")?JSON.parse(s.responseText):this._isBinaryContentType(r)||s.responseType===t.ResponseType.ARRAY_BUFFER||s.responseType===t.ResponseType.BLOB||s.responseType===t.ResponseType.JSON?s.response:s.responseType===t.ResponseType.DOCUMENT||r===t.ContentType.XML?s.responseXML:s.responseText,n.callback(null,a)}catch(t){n.callback(t)}},e._onError=function(e,i,n,s){var a=this;if(!n.retrying)if(n.retry&&n.retries7?e=it.intToBytes32(i):(e=it.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}();at.BLACK=Object.freeze(new at(0,0,0,1)),at.BLUE=Object.freeze(new at(0,0,1,1)),at.CYAN=Object.freeze(new at(0,1,1,1)),at.GRAY=Object.freeze(new at(.5,.5,.5,1)),at.GREEN=Object.freeze(new at(0,1,0,1)),at.MAGENTA=Object.freeze(new at(1,0,1,1)),at.RED=Object.freeze(new at(1,0,0,1)),at.WHITE=Object.freeze(new at(1,1,1,1)),at.YELLOW=Object.freeze(new at(1,1,0,1));var rt=function(){function t(t,e){void 0===e&&(e=0),this._curve=t,this._left=-1/0,this._right=1/0,this._recip=0,this._p0=0,this._p1=0,this._m0=0,this._m1=0,this._reset(e)}var e=t.prototype;return e.evaluate=function(t,e){var i;(e||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?it.lerp(this._p0,this._p1,s):1===n?it.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[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],a=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 r=2*(a[0]-s[0])/(a[0]-i[0]),o=2*(a[0]-s[0])/(n[0]-s[0]);this._m0=this._curve.tension*(isFinite(r)?r:0)*(a[1]-i[1]),this._m1=this._curve.tension*(isFinite(o)?o:0)*(n[1]-s[1])}else{var h=(a[0]-s[0])/(s[0]-i[0]),l=(a[0]-s[0])/(n[0]-a[0]),c=s[1]+(i[1]-s[1])*(isFinite(h)?h:0),u=a[1]+(n[1]-a[1])*(isFinite(l)?l:0),d=2===this._curve.type?.5:this._curve.tension;this._m0=d*(a[1]-c),this._m1=d*(u-s[1])}},e._evaluateHermite=function(t,e,i,n,s){var a=s*s,r=s+s,o=1-s,h=o*o;return t*((1+r)*h)+i*(s*h)+e*(a*(3-r))+n*(a*(s-1))},t}(),ot=function(){function t(t){if(this.keys=[],this.type=1,this.tension=.5,this._eval=new rt(this),t)for(var e=0;et);s++);var a=[t,e];return this.keys.splice(s,0,a),a},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,a=0;a=r))break;n=r,s=e[a]}return s},e.clone=function(){var e=new t;return e.keys=l(e.keys,this.keys),e.type=this.type,e.tension=this.tension,e},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;n1)for(var t=0;t0){var e=1/Math.sqrt(t);this.x*=e,this.y*=e,this.z*=e}return this},e.floor=function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this},e.ceil=function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this},e.round=function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this},e.min=function(t){return t.xthis.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}();lt.ZERO=Object.freeze(new lt(0,0,0)),lt.ONE=Object.freeze(new lt(1,1,1)),lt.UP=Object.freeze(new lt(0,1,0)),lt.DOWN=Object.freeze(new lt(0,-1,0)),lt.RIGHT=Object.freeze(new lt(1,0,0)),lt.LEFT=Object.freeze(new lt(-1,0,0)),lt.FORWARD=Object.freeze(new lt(0,0,-1)),lt.BACK=Object.freeze(new lt(0,0,1));var ct=function(){function t(){var t=new Float32Array(9);t[0]=t[4]=t[8]=1,this.data=t}var e=t.prototype;return e.clone=function(){return(new t).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(){for(var t="[",e=0;e<9;e++)t+=this.data[e],t+=8!==e?", ":"";return t+="]"},e.transpose=function(){var t,e=this.data;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,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.transformVector=function(t,e){void 0===e&&(e=new lt);var i=this.data,n=t.x,s=t.y,a=t.z;return e.x=n*i[0]+s*i[3]+a*i[6],e.y=n*i[1]+s*i[4]+a*i[7],e.z=n*i[2]+s*i[5]+a*i[8],e},t}();ct.IDENTITY=Object.freeze(new ct),ct.ZERO=Object.freeze((new ct).set([0,0,0,0,0,0,0,0,0]));var ut=function(){function t(t,e){void 0===t&&(t=0),void 0===e&&(e=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.clone=function(){return new t(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.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(){var t=this.x*this.x+this.y*this.y;if(t>0){var e=1/Math.sqrt(t);this.x*=e,this.y*=e}return this},e.floor=function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},e.ceil=function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},e.round=function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},e.min=function(t){return t.xthis.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}();ut.ZERO=Object.freeze(new ut(0,0)),ut.ONE=Object.freeze(new ut(1,1)),ut.UP=Object.freeze(new ut(0,1)),ut.DOWN=Object.freeze(new ut(0,-1)),ut.RIGHT=Object.freeze(new ut(1,0)),ut.LEFT=Object.freeze(new ut(-1,0));var dt=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),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.clone=function(){return new t(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.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(){var t=this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w;if(t>0){var e=1/Math.sqrt(t);this.x*=e,this.y*=e,this.z*=e,this.w*=e}return this},e.floor=function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this},e.ceil=function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this},e.round=function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this},e.min=function(t){return t.xthis.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}();dt.ZERO=Object.freeze(new dt(0,0,0,0)),dt.ONE=Object.freeze(new dt(1,1,1,1));var ft=new ut,pt=new lt,mt=new lt,_t=new lt,gt=new lt,vt=function(){function t(){var t=new Float32Array(16);t[0]=t[5]=t[10]=t[15]=1,this.data=t}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 t).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,a,r=t.data,o=e.data,h=this.data,l=r[0],c=r[1],u=r[2],d=r[3],f=r[4],p=r[5],m=r[6],_=r[7],g=r[8],v=r[9],y=r[10],x=r[11],b=r[12],S=r[13],w=r[14],T=r[15];return i=o[0],n=o[1],s=o[2],a=o[3],h[0]=l*i+f*n+g*s+b*a,h[1]=c*i+p*n+v*s+S*a,h[2]=u*i+m*n+y*s+w*a,h[3]=d*i+_*n+x*s+T*a,i=o[4],n=o[5],s=o[6],a=o[7],h[4]=l*i+f*n+g*s+b*a,h[5]=c*i+p*n+v*s+S*a,h[6]=u*i+m*n+y*s+w*a,h[7]=d*i+_*n+x*s+T*a,i=o[8],n=o[9],s=o[10],a=o[11],h[8]=l*i+f*n+g*s+b*a,h[9]=c*i+p*n+v*s+S*a,h[10]=u*i+m*n+y*s+w*a,h[11]=d*i+_*n+x*s+T*a,i=o[12],n=o[13],s=o[14],a=o[15],h[12]=l*i+f*n+g*s+b*a,h[13]=c*i+p*n+v*s+S*a,h[14]=u*i+m*n+y*s+w*a,h[15]=d*i+_*n+x*s+T*a,this},e.mulAffine2=function(t,e){var i,n,s,a=t.data,r=e.data,o=this.data,h=a[0],l=a[1],c=a[2],u=a[4],d=a[5],f=a[6],p=a[8],m=a[9],_=a[10],g=a[12],v=a[13],y=a[14];return i=r[0],n=r[1],s=r[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=r[4],n=r[5],s=r[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=r[8],n=r[9],s=r[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=r[12],n=r[13],s=r[14],o[12]=h*i+u*n+p*s+g,o[13]=l*i+d*n+m*s+v,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 lt);var i=this.data,n=t.x,s=t.y,a=t.z;return e.x=n*i[0]+s*i[4]+a*i[8]+i[12],e.y=n*i[1]+s*i[5]+a*i[9]+i[13],e.z=n*i[2]+s*i[6]+a*i[10]+i[14],e},e.transformVector=function(t,e){void 0===e&&(e=new lt);var i=this.data,n=t.x,s=t.y,a=t.z;return e.x=n*i[0]+s*i[4]+a*i[8],e.y=n*i[1]+s*i[5]+a*i[9],e.z=n*i[2]+s*i[6]+a*i[10],e},e.transformVec4=function(t,e){void 0===e&&(e=new dt);var i=this.data,n=t.x,s=t.y,a=t.z,r=t.w;return e.x=n*i[0]+s*i[4]+a*i[8]+r*i[12],e.y=n*i[1]+s*i[5]+a*i[9]+r*i[13],e.z=n*i[2]+s*i[6]+a*i[10]+r*i[14],e.w=n*i[3]+s*i[7]+a*i[11]+r*i[15],e},e.setLookAt=function(t,e,i){_t.sub2(t,e).normalize(),mt.copy(i).normalize(),pt.cross(mt,_t).normalize(),mt.cross(_t,pt);var n=this.data;return n[0]=pt.x,n[1]=pt.y,n[2]=pt.z,n[3]=0,n[4]=mt.x,n[5]=mt.y,n[6]=mt.z,n[7]=0,n[8]=_t.x,n[9]=_t.y,n[10]=_t.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,a){var r=2*s,o=e-t,h=n-i,l=a-s,c=this.data;return c[0]=r/o,c[1]=0,c[2]=0,c[3]=0,c[4]=0,c[5]=r/h,c[6]=0,c[7]=0,c[8]=(e+t)/o,c[9]=(n+i)/h,c[10]=(-a-s)/l,c[11]=-1,c[12]=0,c[13]=0,c[14]=-r*a/l,c[15]=0,this},e.setPerspective=function(e,i,n,s,a){return t._getPerspectiveHalfSize(ft,e,i,n,a),this.setFrustum(-ft.x,ft.x,-ft.y,ft.y,n,s)},e.setOrtho=function(t,e,i,n,s,a){var r=this.data;return r[0]=2/(e-t),r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=2/(n-i),r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=-2/(a-s),r[11]=0,r[12]=-(e+t)/(e-t),r[13]=-(n+i)/(n-i),r[14]=-(a+s)/(a-s),r[15]=1,this},e.setFromAxisAngle=function(t,e){e*=it.DEG_TO_RAD;var i=t.x,n=t.y,s=t.z,a=Math.cos(e),r=Math.sin(e),o=1-a,h=o*i,l=o*n,c=this.data;return c[0]=h*i+a,c[1]=h*n+r*s,c[2]=h*s-r*n,c[3]=0,c[4]=h*n-r*s,c[5]=l*n+a,c[6]=l*s+r*i,c[7]=0,c[8]=h*s+r*n,c[9]=l*s-i*r,c[10]=o*s*s+a,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.invert=function(){var t=this.data,e=t[0],i=t[1],n=t[2],s=t[3],a=t[4],r=t[5],o=t[6],h=t[7],l=t[8],c=t[9],u=t[10],d=t[11],f=t[12],p=t[13],m=t[14],_=t[15],g=e*r-i*a,v=e*o-n*a,y=e*h-s*a,x=i*o-n*r,b=i*h-s*r,S=n*h-s*o,w=l*p-c*f,T=l*m-u*f,A=l*_-d*f,M=c*m-u*p,C=c*_-d*p,E=u*_-d*m,P=g*E-v*C+y*M+x*A-b*T+S*w;if(0===P)this.setIdentity();else{var R=1/P;t[0]=(r*E-o*C+h*M)*R,t[1]=(-i*E+n*C-s*M)*R,t[2]=(p*S-m*b+_*x)*R,t[3]=(-c*S+u*b-d*x)*R,t[4]=(-a*E+o*A-h*T)*R,t[5]=(e*E-n*A+s*T)*R,t[6]=(-f*S+m*y-_*v)*R,t[7]=(l*S-u*y+d*v)*R,t[8]=(a*C-r*A+h*w)*R,t[9]=(-e*C+i*A-s*w)*R,t[10]=(f*b-p*y+_*g)*R,t[11]=(-l*b+c*y-d*g)*R,t[12]=(-a*M+r*T-o*w)*R,t[13]=(e*M-i*T+n*w)*R,t[14]=(-f*x+p*v-m*g)*R,t[15]=(l*x-c*v+u*g)*R}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,a=e.z,r=e.w,o=i.x,h=i.y,l=i.z,c=n+n,u=s+s,d=a+a,f=n*c,p=n*u,m=n*d,_=s*u,g=s*d,v=a*d,y=r*c,x=r*u,b=r*d,S=this.data;return S[0]=(1-(_+v))*o,S[1]=(p+b)*o,S[2]=(m-x)*o,S[3]=0,S[4]=(p-b)*h,S[5]=(1-(f+v))*h,S[6]=(g+y)*h,S[7]=0,S[8]=(m+x)*l,S[9]=(g-y)*l,S[10]=(1-(f+_))*l,S[11]=0,S[12]=t.x,S[13]=t.y,S[14]=t.z,S[15]=1,this},e.transpose=function(){var t,e=this.data;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this},e.invertTo3x3=function(t){var e=this.data,i=t.data,n=e[0],s=e[1],a=e[2],r=e[4],o=e[5],h=e[6],l=e[8],c=e[9],u=e[10],d=u*o-h*c,f=-u*s+a*c,p=h*s-a*o,m=-u*r+h*l,_=u*n-a*l,g=-h*n+a*r,v=c*r-o*l,y=-c*n+s*l,x=o*n-s*r,b=n*d+s*m+a*v;if(0===b)return this;var S=1/b;return i[0]=S*d,i[1]=S*f,i[2]=S*p,i[3]=S*m,i[4]=S*_,i[5]=S*g,i[6]=S*v,i[7]=S*y,i[8]=S*x,this},e.getTranslation=function(t){return void 0===t&&(t=new lt),t.set(this.data[12],this.data[13],this.data[14])},e.getX=function(t){return void 0===t&&(t=new lt),t.set(this.data[0],this.data[1],this.data[2])},e.getY=function(t){return void 0===t&&(t=new lt),t.set(this.data[4],this.data[5],this.data[6])},e.getZ=function(t){return void 0===t&&(t=new lt),t.set(this.data[8],this.data[9],this.data[10])},e.getScale=function(t){return void 0===t&&(t=new lt),this.getX(pt),this.getY(mt),this.getZ(_t),t.set(pt.length(),mt.length(),_t.length()),t},e.setFromEulerAngles=function(t,e,i){t*=it.DEG_TO_RAD,e*=it.DEG_TO_RAD,i*=it.DEG_TO_RAD;var n=Math.sin(-t),s=Math.cos(-t),a=Math.sin(-e),r=Math.cos(-e),o=Math.sin(-i),h=Math.cos(-i),l=this.data;return l[0]=r*h,l[1]=-r*o,l[2]=a,l[3]=0,l[4]=s*o+h*n*a,l[5]=s*h-n*a*o,l[6]=-r*n,l[7]=0,l[8]=n*o-s*h*a,l[9]=h*n+s*a*o,l[10]=s*r,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 lt),this.getScale(gt);var e=gt.x,i=gt.y,n=gt.z;if(0===e||0===i||0===n)return t.set(0,0,0);var s,a,r=this.data,o=Math.asin(-r[2]/e),h=.5*Math.PI;return o-h?(s=Math.atan2(r[6]/i,r[10]/n),a=Math.atan2(r[1]/e,r[0]/e)):(a=0,s=-Math.atan2(r[4]/i,r[5]/i)):(a=0,s=Math.atan2(r[4]/i,r[5]/i)),t.set(s,o,a).mulScalar(it.RAD_TO_DEG)},e.toString=function(){for(var t="[",e=0;e<16;e+=1)t+=this.data[e],t+=15!==e?", ":"";return t+="]"},t}();vt.IDENTITY=Object.freeze(new vt),vt.ZERO=Object.freeze((new vt).set([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]));var yt=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),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 t(this.x,this.y,this.z,this.w)},e.conjugate=function(){return this.x*=-1,this.y*=-1,this.z*=-1,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.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*it.RAD_TO_DEG},e.getEulerAngles=function(t){var e,i,n;void 0===t&&(t=new lt);var s=this.x,a=this.y,r=this.z,o=this.w,h=2*(o*a-s*r);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+a*r),1-2*(s*s+a*a)),i=Math.asin(h),n=Math.atan2(2*(o*r+s*a),1-2*(a*a+r*r))),t.set(e,i,n).mulScalar(it.RAD_TO_DEG)},e.invert=function(){return this.conjugate().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,a=t.x,r=t.y,o=t.z,h=t.w;return this.x=s*a+e*h+i*o-n*r,this.y=s*r+i*h+n*a-e*o,this.z=s*o+n*h+e*r-i*a,this.w=s*h-e*a-i*r-n*o,this},e.mul2=function(t,e){var i=t.x,n=t.y,s=t.z,a=t.w,r=e.x,o=e.y,h=e.z,l=e.w;return this.x=a*r+i*l+n*h-s*o,this.y=a*o+n*l+s*r-i*h,this.z=a*h+s*l+i*o-n*r,this.w=a*l-i*r-n*o-s*h,this},e.normalize=function(){var t=this.length();return 0===t?(this.x=this.y=this.z=0,this.w=1):(t=1/t,this.x*=t,this.y*=t,this.z*=t,this.w*=t),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*it.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){var n=.5*it.DEG_TO_RAD;t*=n,e*=n,i*=n;var s=Math.sin(t),a=Math.cos(t),r=Math.sin(e),o=Math.cos(e),h=Math.sin(i),l=Math.cos(i);return this.x=s*o*l-a*r*h,this.y=a*r*l+s*o*h,this.z=a*o*h-s*r*l,this.w=a*o*l+s*r*h,this},e.setFromMat4=function(t){var e,i,n,s,a,r,o,h,l,c,u,d,f,p;if(e=(t=t.data)[0],i=t[1],n=t[2],s=t[4],a=t[5],r=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+a*a+r*r))return this;if(f=1/Math.sqrt(f),0===(p=o*o+h*h+l*l))return this;i*=d,n*=d,s*=f,r*=f,o*=p=1/Math.sqrt(p),h*=p;var m=(e*=d)+(a*=f)+(l*=p);return m>=0?(c=Math.sqrt(m+1),this.w=.5*c,c=.5/c,this.x=(r-h)*c,this.y=(o-n)*c,this.z=(i-s)*c):e>a?e>l?(u=e-(a+l)+1,u=Math.sqrt(u),this.x=.5*u,u=.5/u,this.w=(r-h)*u,this.y=(i+s)*u,this.z=(n+o)*u):(u=l-(e+a)+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+r)*u):a>l?(u=a-(l+e)+1,u=Math.sqrt(u),this.y=.5*u,u=.5/u,this.w=(o-n)*u,this.z=(r+h)*u,this.x=(s+i)*u):(u=l-(e+a)+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+r)*u),this},e.slerp=function(t,e,i){var n=t.x,s=t.y,a=t.z,r=t.w,o=e.x,h=e.y,l=e.z,c=e.w,u=r*c+n*o+s*h+a*l;if(u<0&&(c=-c,o=-o,h=-h,l=-l,u=-u),Math.abs(u)>=1)return this.w=r,this.x=n,this.y=s,this.z=a,this;var d=Math.acos(u),f=Math.sqrt(1-u*u);if(Math.abs(f)<.001)return this.w=.5*r+.5*c,this.x=.5*n+.5*o,this.y=.5*s+.5*h,this.z=.5*a+.5*l,this;var p=Math.sin((1-i)*d)/f,m=Math.sin(i*d)/f;return this.w=r*p+c*m,this.x=n*p+o*m,this.y=s*p+h*m,this.z=a*p+l*m,this},e.transformVector=function(t,e){void 0===e&&(e=new lt);var i=t.x,n=t.y,s=t.z,a=this.x,r=this.y,o=this.z,h=this.w,l=h*i+r*s-o*n,c=h*n+o*i-a*s,u=h*s+a*n-r*i,d=-a*i-r*n-o*s;return e.x=l*h+d*-a+c*-o-u*-r,e.y=c*h+d*-r+u*-a-l*-o,e.z=u*h+d*-o+l*-r-c*-a,e},e.toString=function(){return"["+this.x+", "+this.y+", "+this.z+", "+this.w+"]"},t}();yt.IDENTITY=Object.freeze(new yt(0,0,0,1)),yt.ZERO=Object.freeze(new yt(0,0,0,0));var xt=new lt,bt=new lt,St=new lt,wt=new lt,Tt=new lt,At=function(){function t(t,e){void 0===t&&(t=new lt),void 0===e&&(e=new lt(.5,.5,.5)),this.center=t,this.halfExtents=e,this._min=new lt,this._max=new lt}var e=t.prototype;return e.add=function(t){var e=this.center,i=e.x,n=e.y,s=e.z,a=this.halfExtents,r=a.x,o=a.y,h=a.z,l=i-r,c=i+r,u=n-o,d=n+o,f=s-h,p=s+h,m=t.center,_=m.x,g=m.y,v=m.z,y=t.halfExtents,x=y.x,b=y.y,S=y.z,w=_-x,T=_+x,A=g-b,M=g+b,C=v-S,E=v+S;wc&&(c=T),Ad&&(d=M),Cp&&(p=E),e.x=.5*(l+c),e.y=.5*(u+d),e.z=.5*(f+p),a.x=.5*(c-l),a.y=.5*(d-u),a.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=xt.copy(this.getMin()).sub(t.origin),n=bt.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 a=St.set(Math.min(i.x,n.x),Math.min(i.y,n.y),Math.min(i.z,n.z)),r=wt.set(Math.max(i.x,n.x),Math.max(i.y,n.y),Math.max(i.z,n.z)),o=Math.min(Math.min(r.x,r.y),r.z),h=Math.max(Math.max(a.x,a.y),a.z),l=o>=h&&h>=0;return l&&e.copy(t.direction).mulScalar(h).add(t.origin),l},e._fastIntersectsRay=function(t){var e=xt,i=bt,n=St,s=wt,a=Tt,r=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,r),!(s.x>this.halfExtents.x&&n.x>=0)&&(!(s.y>this.halfExtents.y&&n.y>=0)&&(!(s.z>this.halfExtents.z&&n.z>=0)&&(a.set(Math.abs(r.x),Math.abs(r.y),Math.abs(r.z)),i.cross(r,e),i.set(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z)),!(i.x>this.halfExtents.y*a.z+this.halfExtents.z*a.y)&&(!(i.y>this.halfExtents.x*a.z+this.halfExtents.z*a.x)&&!(i.z>this.halfExtents.x*a.y+this.halfExtents.y*a.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.xi.x||t.yi.y||t.zi.z)},e.setFromTransformedAabb=function(t,e){var i=t.center,n=t.halfExtents,s=e.data,a=s[0],r=s[4],o=s[8],h=s[1],l=s[5],c=s[9],u=s[2],d=s[6],f=s[10];this.center.set(s[12]+a*i.x+r*i.y+o*i.z,s[13]+h*i.x+l*i.y+c*i.z,s[14]+u*i.x+d*i.y+f*i.z),this.halfExtents.set(Math.abs(a)*n.x+Math.abs(r)*n.y+Math.abs(o)*n.z,Math.abs(h)*n.x+Math.abs(l)*n.y+Math.abs(c)*n.z,Math.abs(u)*n.x+Math.abs(d)*n.y+Math.abs(f)*n.z)},e.compute=function(t,e){if((e=void 0===e?t.length/3:e)>0){for(var i=xt.set(t[0],t[1],t[2]),n=bt.set(t[0],t[1],t[2]),s=1;sn.x&&(n.x=a),r>n.y&&(n.y=r),o>n.z&&(n.z=o)}this.setMinMax(i,n)}},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"],a=0;a<3;++a){var r=0,o=t.center[s[a]],h=e[s[a]],l=i[s[a]],c=0;ol&&(r+=(c=o-l)*c),n+=r}return n},e._expand=function(t,e){xt.add2(this.getMin(),t),bt.add2(this.getMax(),e),this.setMinMax(xt,bt)},t}(),Mt=new lt,Ct=new lt,Et=function(){function t(t,e){void 0===t&&(t=new lt),void 0===e&&(e=.5),this.center=t,this.radius=e}var e=t.prototype;return e.containsPoint=function(t){var e=Mt.sub2(t,this.center).lengthSq(),i=this.radius;return e0&&n>0)return null;var a=n*n-s;if(a<0)return!1;var r=Math.abs(-n-Math.sqrt(a));return e&&e.copy(t.direction).mulScalar(r).add(t.origin),!0},e.intersectsBoundingSphere=function(t){Mt.sub2(t.center,this.center);var e=t.radius+this.radius;return Mt.lengthSq()<=e*e},t}(),Pt="none",Rt="linear",It={0:"PCF3",1:"VSM8",2:"VSM16",3:"VSM32",4:"PCF5",5:"PCF1"},Lt=128,Dt=256,Ot=1024,kt=2048,Ft=4096,Bt=8192,Nt=18,Ut=[new lt,new lt,new lt,new lt,new lt,new lt,new lt,new lt],zt=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,a=t.radius,r=t.center,o=r.x,h=r.y,l=r.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])<=-a)return 0;e>a&&s++}return 6===s?2:1},t.getPoints=function(t,e,i){e=e||t._nearClip,i=i||t._farClip;var n=t._fov*Math.PI/180,s=0===t._projection?Math.tan(n/2)*e:t._orthoHeight,a=s*t._aspectRatio,r=Ut;return r[0].x=a,r[0].y=-s,r[0].z=-e,r[1].x=a,r[1].y=s,r[1].z=-e,r[2].x=-a,r[2].y=s,r[2].z=-e,r[3].x=-a,r[3].y=-s,r[3].z=-e,0===t._projection&&(a=(s=Math.tan(n/2)*i)*t._aspectRatio),r[4].x=a,r[4].y=-s,r[4].z=-i,r[5].x=a,r[5].y=s,r[5].z=-i,r[6].x=-a,r[6].y=s,r[6].z=-i,r[7].x=-a,r[7].y=-s,r[7].z=-i,r},t}(),Vt=function(){function t(t,e){void 0===t&&(t=new lt),void 0===e&&(e=new lt(0,0,-1)),this.origin=t,this.direction=e}return t.prototype.set=function(t,e){return this.origin.copy(t),this.direction.copy(e),this},t}(),Gt=new Vt,Wt=new lt,Ht=new Et,Xt=new vt,jt=function(){function t(t,e){void 0===t&&(t=new vt),void 0===e&&(e=new lt(.5,.5,.5)),this.halfExtents=e,this._modelTransform=t.clone().invert(),this._worldTransform=t.clone(),this._aabb=new At(new lt,this.halfExtents)}var e=t.prototype;return e.intersectsRay=function(t,e){if(this._modelTransform.transformPoint(t.origin,Gt.origin),this._modelTransform.transformVector(t.direction,Gt.direction),e){var i=this._aabb._intersectsRay(Gt,e);return Xt.copy(this._modelTransform).invert().transformPoint(e,e),i}return this._aabb._fastIntersectsRay(Gt)},e.containsPoint=function(t){return this._modelTransform.transformPoint(t,Wt),this._aabb.containsPoint(Wt)},e.intersectsBoundingSphere=function(t){return this._modelTransform.transformPoint(t.center,Ht.center),Ht.radius=t.radius,!!this._aabb.intersectsBoundingSphere(Ht)},G(t,[{key:"worldTransform",get:function(){return this._worldTransform},set:function(t){this._worldTransform.copy(t),this._modelTransform.copy(t).invert()}}]),t}(),qt=new lt,Yt=function(){function t(t,e){void 0===t&&(t=new lt),void 0===e&&(e=new lt(0,0,1)),this.normal=e,this.point=t}var e=t.prototype;return e.intersectsLine=function(t,e,i){var n=-this.normal.dot(this.point),s=this.normal.dot(t)+n,a=s/(s-(this.normal.dot(e)+n)),r=a>=0&&a<=1;return r&&i&&i.lerp(t,e,a),r},e.intersectsRay=function(t,e){var i=qt.sub2(this.point,t.origin),n=this.normal.dot(i)/this.normal.dot(t.direction),s=n>=0;return s&&e&&e.copy(t.direction).mulScalar(n).add(t.origin),s},t}(),Kt=10,Zt=11,$t=12,Qt=13,Jt=14,te=16,ee=17,ie=21,ne=24,se=25,ae="POSITION",re="NORMAL",oe="TANGENT",he="BLENDWEIGHT",le="BLENDINDICES",ce="COLOR",ue="TEXCOORD",de="TEXCOORD0",fe="TEXCOORD1",pe="TEXCOORD2",me="TEXCOORD3",_e="TEXCOORD4",ge="TEXCOORD5",ve="TEXCOORD6",ye="TEXCOORD7",xe="ATTR",be="ATTR0",Se="ATTR1",we="ATTR2",Te="ATTR3",Ae="ATTR4",Me="ATTR5",Ce="ATTR6",Ee="ATTR7",Pe="ATTR8",Re="ATTR9",Ie="ATTR10",Le="ATTR11",De="ATTR12",Oe="ATTR13",ke="ATTR14",Fe="ATTR15",Be="default",Ne="rgbm",Ue="rgbe",ze="swizzleGGGR",Ve="none",Ge="cube",We="equirect",He="octahedral",Xe=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array],je=[1,1,2,2,4,4,4],qe={Int8Array:0,Uint8Array:1,Int16Array:2,Uint16Array:3,Int32Array:4,Uint32Array:5,Float32Array:6},Ye=[Uint8Array,Uint16Array,Uint32Array],Ke={POSITION:0,NORMAL:1,BLENDWEIGHT:2,BLENDINDICES:3,COLOR:4,TEXCOORD0:5,TEXCOORD1:6,TEXCOORD2:7,TEXCOORD3:8,TEXCOORD4:9,TEXCOORD5:10,TEXCOORD6:11,TEXCOORD7:12,TANGENT:13,ATTR0:0,ATTR1:1,ATTR2:2,ATTR3:3,ATTR4:4,ATTR5:5,ATTR6:6,ATTR7:7,ATTR8:8,ATTR9:9,ATTR10:10,ATTR11:11,ATTR12:12,ATTR13:13,ATTR14:14,ATTR15:15},Ze=0,$e=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=Ze++,this._vao=null,this.instancing=!1,this.numBytes=e.verticesByteSize?e.verticesByteSize:e.size*i,t._vram.vb+=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);if(-1!==e&&t.buffers.splice(e,1),this.bufferId){var i=t.gl;t.boundVao=null,i.bindVertexArray(null),i.deleteBuffer(this.bufferId),t._vram.vb-=this.storage.byteLength,this.bufferId=null}},e.loseContext=function(){this.bufferId=void 0,this._vao=null},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(){var t,e=this.device.gl;switch(this.bufferId||(this.bufferId=e.createBuffer()),this.usage){case 0:t=e.STATIC_DRAW;break;case 1:t=e.DYNAMIC_DRAW;break;case 2:t=e.STREAM_DRAW;break;case 3:t=this.device.webgl2?e.DYNAMIC_COPY:e.STATIC_DRAW}e.bindBuffer(e.ARRAY_BUFFER,this.bufferId),e.bufferData(e.ARRAY_BUFFER,this.storage,t)},e.setData=function(t){return t.byteLength===this.numBytes&&(this.storage=t,this.unlock(),!0)},t}();function Qe(t){for(var e=0,i=0,n=t.length;i 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:"\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",basePS:"uniform 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:"attribute 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:"#define NINESLICED\nvarying vec2 vMask;\nvarying vec2 vTiledUv;\nuniform mediump vec4 innerOffset;\nuniform mediump vec2 outerScale;\nuniform mediump vec4 atlasRect;\nvec2 nineSlicedUv;\n",baseNineSlicedVS:"#define NINESLICED\nvarying vec2 vMask;\nvarying vec2 vTiledUv;\nuniform mediump vec4 innerOffset;\nuniform mediump vec2 outerScale;\nuniform mediump vec4 atlasRect;\n",baseNineSlicedTiledPS:"#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:"#define SHADOWBIAS\nfloat getShadowBias(float resolution, float maxBias) {\n\treturn maxBias;\n}\n",blurVSMPS:"varying 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 shadowZ ? 1.0 : 0.0;\n\t}\n\t#endif\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF3) || defined(CLUSTER_SHADOW_TYPE_PCF5)\n\tfloat getShadowOmniClusteredPCF3(sampler2D shadowMap, vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 dir) {\n\t\tfloat shadowTextureResolution = shadowParams.x;\n\t\tvec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir);\n\t\tfloat shadowZ = length(dir) * shadowParams.w + shadowParams.z;\n\t\tdShadowCoord = vec3(uv, shadowZ);\n\t\treturn getShadowPCF3x3(shadowMap, shadowParams.xyz);\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 dir) {\n\t\treturn getShadowOmniClusteredPCF3(shadowMap, shadowParams, omniAtlasViewport, shadowEdgePixels, dir);\n\t}\n\t#endif\n#endif\n#ifdef GL2\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\tfloat getShadowSpotClusteredPCF1(sampler2DShadow shadowMap, vec4 shadowParams) {\n\t\treturn texture(shadowMap, dShadowCoord);\n\t}\n\t#endif\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF3)\n\tfloat getShadowSpotClusteredPCF3(sampler2DShadow shadowMap, vec4 shadowParams) {\n\t\treturn getShadowSpotPCF3x3(shadowMap, shadowParams);\n\t}\n\t#endif\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\tfloat getShadowSpotClusteredPCF5(sampler2DShadow shadowMap, vec4 shadowParams) {\n\t\treturn getShadowPCF5x5(shadowMap, shadowParams.xyz);\n\t}\n\t#endif\n#else\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\tfloat getShadowSpotClusteredPCF1(sampler2D shadowMap, vec4 shadowParams) {\n\t\tfloat depth = unpackFloat(texture2D(shadowMap, dShadowCoord.xy));\n\t\treturn depth > dShadowCoord.z ? 1.0 : 0.0;\n\t}\n\t#endif\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF3) || defined(CLUSTER_SHADOW_TYPE_PCF5)\n\tfloat getShadowSpotClusteredPCF3(sampler2D shadowMap, vec4 shadowParams) {\n\t\treturn getShadowSpotPCF3x3(shadowMap, shadowParams);\n\t}\n\t#endif\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\tfloat getShadowSpotClusteredPCF5(sampler2D shadowMap, vec4 shadowParams) {\n\t\treturn getShadowSpotClusteredPCF3(shadowMap, 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:"uniform sampler2D clusterWorldTexture;\nuniform sampler2D lightsTexture8;\nuniform highp sampler2D lightsTextureFloat;\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\nuniform float clusterPixelsPerCell;\nuniform vec3 clusterCellsCountByBoundsSize;\nuniform vec4 lightsTextureInvSize;\nuniform vec3 clusterTextureSize;\nuniform vec3 clusterBoundsMin;\nuniform vec3 clusterBoundsDelta;\nuniform vec3 clusterCellsDot;\nuniform vec3 clusterCellsMax;\nuniform vec2 clusterCompressionLimit0;\nuniform vec2 shadowAtlasParams;\nfloat LTCLightValuesEvaluated = 0.0;\nstruct ClusterLightData {\n\tfloat lightV;\n\tfloat type;\n\tfloat shape;\n\tvec3 halfWidth;\n\tvec3 halfHeight;\n\tfloat falloffMode;\n\tfloat castShadows;\n\tfloat shadowBias;\n\tfloat shadowNormalBias;\n\tvec3 position;\n\tvec3 direction;\n\tfloat range;\n\tfloat innerConeAngleCos;\n\tfloat outerConeAngleCos;\n\tvec3 color;\n\tvec3 omniAtlasViewport;\n\tfloat cookie;\n\tfloat cookieRgb;\n\tfloat cookieIntensity;\n\tvec4 cookieChannelMask;\n};\nmat4 lightProjectionMatrix;\n#define isClusteredLightCastShadow(light) ( light.castShadows > 0.5 )\n#define isClusteredLightCookie(light) (light.cookie > 0.5 )\n#define isClusteredLightCookieRgb(light) (light.cookieRgb > 0.5 )\n#define isClusteredLightSpot(light) ( light.type > 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 )\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 SUPPORTS_TEXLOD\n\t#define textureData(texture, uv) texture2DLodEXT(texture, uv, 0.0)\n#else\n\t#define textureData(texture, uv) texture2D(texture, uv)\n#endif\nvec4 sampleLightsTexture8(const ClusterLightData clusterLightData, float index) {\n\treturn textureData(lightsTexture8, vec2(index * lightsTextureInvSize.z, clusterLightData.lightV));\n}\nvec4 sampleLightTextureF(const ClusterLightData clusterLightData, float index) {\n\treturn textureData(lightsTextureFloat, vec2(index * lightsTextureInvSize.x, clusterLightData.lightV));\n}\nvoid decodeClusterLightCore(inout ClusterLightData clusterLightData, float lightIndex) {\n\tclusterLightData.lightV = (lightIndex + 0.5) * lightsTextureInvSize.w;\n\tvec4 lightInfo = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_FLAGS);\n\tclusterLightData.type = lightInfo.x;\n\tclusterLightData.shape = lightInfo.y;\n\tclusterLightData.falloffMode = lightInfo.z;\n\tclusterLightData.castShadows = 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\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(mantisaExponent2Float(areaWidthX), mantisaExponent2Float(areaWidthY), mantisaExponent2Float(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(mantisaExponent2Float(areaHeightX), mantisaExponent2Float(areaHeightY), mantisaExponent2Float(areaHeightZ));\n\t#endif\n}\nvoid decodeClusterLightProjectionMatrixData(inout ClusterLightData clusterLightData) {\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(mantisaExponent2Float(m30), mantisaExponent2Float(m31), mantisaExponent2Float(m32), mantisaExponent2Float(m33));\n\t#endif\n\tlightProjectionMatrix = mat4(m0, m1, m2, m3);\n}\nvoid decodeClusterLightShadowData(inout ClusterLightData clusterLightData) {\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(ClusterLightData light) {\n\tdAtten3 = vec3(1.0);\n\tgetLightDirPoint(light.position);\n\t#ifdef CLUSTER_AREALIGHTS\n\tif (isClusteredLightArea(light)) {\n\t\tdecodeClusterLightAreaData(light);\n\t\tif (LTCLightValuesEvaluated < 0.5) {\n\t\t\tLTCLightValuesEvaluated = 1.0;\n\t\t\tcalcLTCLightValues();\n\t\t}\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\tdAtten = getFalloffWindow(light.range);\n\t} else\n\t#endif\n\t{\n\t\tif (isClusteredLightFalloffLinear(light))\n\t\t\tdAtten = getFalloffLinear(light.range);\n\t\telse\n\t\t\tdAtten = getFalloffInvSquared(light.range);\n\t}\n\tif (dAtten > 0.00001) {\n\t\t#ifdef CLUSTER_AREALIGHTS\n\t\tif (isClusteredLightArea(light)) {\n\t\t\tif (isClusteredLightRect(light)) {\n\t\t\t\tdAttenD = getRectLightDiffuse() * 16.0;\n\t\t\t} else if (isClusteredLightDisk(light)) {\n\t\t\t\tdAttenD = getDiskLightDiffuse() * 16.0;\n\t\t\t} else {\n\t\t\t\tdAttenD = getSphereLightDiffuse() * 16.0;\n\t\t\t}\n\t\t} else\n\t\t#endif\n\t\t{\n\t\t\tdAtten *= getLightDiffuse();\n\t\t}\n\t\tif (isClusteredLightSpot(light)) {\n\t\t\tdecodeClusterLightSpot(light);\n\t\t\tdAtten *= getSpotEffect(light.direction, light.innerConeAngleCos, light.outerConeAngleCos);\n\t\t}\n\t\t#if defined(CLUSTER_COOKIES) || defined(CLUSTER_SHADOWS)\n\t\tif (dAtten > 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\tdAtten3 = getCookie2DClustered(cookieAtlasTexture, lightProjectionMatrix, vPositionW, light.cookieIntensity, isClusteredLightCookieRgb(light), light.cookieChannelMask);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdAtten3 = getCookieCubeClustered(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);\n\t\t\t\t\t\t#if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\t\t\t\t\t\t\tdAtten *= getShadowSpotClusteredPCF1(shadowAtlasTexture, shadowParams);\n\t\t\t\t\t\t#elif defined(CLUSTER_SHADOW_TYPE_PCF3)\n\t\t\t\t\t\t\tdAtten *= getShadowSpotClusteredPCF3(shadowAtlasTexture, shadowParams);\n\t\t\t\t\t\t#elif defined(CLUSTER_SHADOW_TYPE_PCF5)\n\t\t\t\t\t\t\tdAtten *= getShadowSpotClusteredPCF5(shadowAtlasTexture, shadowParams);\n\t\t\t\t\t\t#endif\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnormalOffsetPointShadow(shadowParams);\n\t\t\t\t\t\t#if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\t\t\t\t\t\t\tdAtten *= getShadowOmniClusteredPCF1(shadowAtlasTexture, shadowParams, light.omniAtlasViewport, shadowEdgePixels, dLightDirW);\n\t\t\t\t\t\t#elif defined(CLUSTER_SHADOW_TYPE_PCF3)\n\t\t\t\t\t\t\tdAtten *= getShadowOmniClusteredPCF3(shadowAtlasTexture, shadowParams, light.omniAtlasViewport, shadowEdgePixels, dLightDirW);\n\t\t\t\t\t\t#elif defined(CLUSTER_SHADOW_TYPE_PCF5)\n\t\t\t\t\t\t\tdAtten *= getShadowOmniClusteredPCF5(shadowAtlasTexture, shadowParams, light.omniAtlasViewport, shadowEdgePixels, dLightDirW);\n\t\t\t\t\t\t#endif\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 = (dAttenD * dAtten) * light.color * dAtten3;\n\t\t\t\t#if defined(CLUSTER_SPECULAR) && defined(CLUSTER_CONSERVE_ENERGY)\n\t\t\t\t\tareaDiffuse = mix(areaDiffuse, vec3(0), dLTCSpecFres);\n\t\t\t\t#endif\n\t\t\t\tdDiffuseLight += areaDiffuse;\n\t\t\t}\n\t\t\t#ifdef CLUSTER_SPECULAR\n\t\t\t\tfloat areaLightSpecular;\n\t\t\t\tif (isClusteredLightRect(light)) {\n\t\t\t\t\tareaLightSpecular = getRectLightSpecular();\n\t\t\t\t} else if (isClusteredLightDisk(light)) {\n\t\t\t\t\tareaLightSpecular = getDiskLightSpecular();\n\t\t\t\t} else {\n\t\t\t\t\tareaLightSpecular = getSphereLightSpecular();\n\t\t\t\t}\n\t\t\t\tdSpecularLight += dLTCSpecFres * areaLightSpecular * dAtten * light.color * dAtten3;\n\t\t\t\t#ifdef CLUSTER_CLEAR_COAT\n\t\t\t\t\tfloat areaLightSpecularCC;\n\t\t\t\t\tif (isClusteredLightRect(light)) {\n\t\t\t\t\t\tareaLightSpecularCC = getRectLightSpecularCC();\n\t\t\t\t\t} else if (isClusteredLightDisk(light)) {\n\t\t\t\t\t\tareaLightSpecularCC = getDiskLightSpecularCC();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tareaLightSpecularCC = getSphereLightSpecularCC();\n\t\t\t\t\t}\n\t\t\t\t\tccSpecularLight += ccLTCSpecFres * areaLightSpecularCC * dAtten * light.color * dAtten3;\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 = dAtten * light.color * dAtten3;\n\t\t\t\t#if defined(CLUSTER_AREALIGHTS) && defined(CLUSTER_SPECULAR) && defined(CLUSTER_CONSERVE_ENERGY)\n\t\t\t\t\tpunctualDiffuse = mix(punctualDiffuse, vec3(0), dSpecularity);\n\t\t\t\t#endif\n\t\t\t\tdDiffuseLight += punctualDiffuse;\n\t\t\t}\n\t\t\t#ifdef CLUSTER_SPECULAR\n\t\t\t\t{\n\t\t\t\t\tvec3 punctualSpecular = getLightSpecular() * dAtten * light.color * dAtten3;\n\t\t\t\t\t#if defined(CLUSTER_AREALIGHTS)\n\t\t\t\t\t\tpunctualSpecular *= dSpecularity;\n\t\t\t\t\t#endif\n\t\t\t\t\tdSpecularLight += punctualSpecular;\n\t\t\t\t}\n\t\t\t\t#ifdef CLUSTER_CLEAR_COAT\n\t\t\t\t\tvec3 punctualCC = getLightSpecularCC() * dAtten * light.color * dAtten3;\n\t\t\t\t\t#if defined(CLUSTER_AREALIGHTS)\n\t\t\t\t\t\tpunctualCC *= ccSpecularity;\n\t\t\t\t\t#endif\n\t\t\t\t\tccSpecularLight += punctualCC;\n\t\t\t\t#endif\n\t\t\t#endif\n\t\t}\n\t}\n}\nvoid evaluateClusterLight(float lightIndex) {\n\tClusterLightData clusterLightData;\n\tdecodeClusterLightCore(clusterLightData, lightIndex);\n\tevaluateLight(clusterLightData);\n}\nvoid addClusteredLights() {\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\tclusterV = (clusterV + 0.5) * clusterTextureSize.z;\n\t\tconst float maxLightCells = 256.0 / 4.0;\n\t\tfor (float lightCellIndex = 0.5; lightCellIndex < maxLightCells; lightCellIndex++) {\n\t\t\tvec4 lightIndices = textureData(clusterWorldTexture, vec2(clusterTextureSize.y * (clusterU + lightCellIndex), clusterV));\n\t\t\tvec4 indices = lightIndices * 255.0;\n\t\t\tfor (int i = 0; i < 4; i++) {\n\t\t\t\tif (indices.x <= 0.0)\n\t\t\t\t\treturn;\n\t\t\t\tevaluateClusterLight(indices.x);\n\t\t\t\tindices = indices.yzwx;\n\t\t\t}\n\t\t\tif (lightCellIndex > clusterPixelsPerCell) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n",combineClearCoatPS:"vec3 combineColorCC() {\n\treturn combineColor()+(ccSpecularLight*ccSpecularity+ccReflection.rgb*ccSpecularity*ccReflection.a);\n}\n",combineDiffusePS:"vec3 combineColor() {\n\treturn dAlbedo * dDiffuseLight;\n}\n",combineDiffuseSpecularPS:"vec3 combineColor() {\n\treturn mix(dAlbedo * dDiffuseLight, dSpecularLight + dReflection.rgb * dReflection.a, dSpecularity);\n}\n",combineDiffuseSpecularNoConservePS:"vec3 combineColor() {\n\treturn dAlbedo * dDiffuseLight + (dSpecularLight + dReflection.rgb * dReflection.a) * dSpecularity;\n}\n",combineDiffuseSpecularNoReflPS:"vec3 combineColor() {\n\treturn dAlbedo * dDiffuseLight + dSpecularLight * dSpecularity;\n}\n",combineDiffuseSpecularNoReflSeparateAmbientPS:"uniform vec3 material_ambient;\nvec3 combineColor() {\n\treturn (dDiffuseLight - light_globalAmbient) * dAlbedo + dSpecularLight * dSpecularity + material_ambient * light_globalAmbient;\n}\n",combineDiffuseSpecularOldPS:"vec3 combineColor() {\n\treturn mix(dAlbedo * dDiffuseLight + dSpecularLight * dSpecularity, dReflection.rgb, dReflection.a);\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:"uniform vec3 envBoxMin, 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:"vec3 cubeMapProject(vec3 dir) {\n\treturn cubeMapRotate(dir);\n}\n",cubeMapRotatePS:"#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",detailModesPS:"vec3 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:"#ifdef MAPCOLOR\nuniform vec3 material_diffuse;\n#endif\n#ifdef MAPTEXTURE\nuniform sampler2D texture_diffuseMap;\n#endif\nvoid getAlbedo() {\n\tdAlbedo = vec3(1.0);\n\t#ifdef MAPCOLOR\n\tdAlbedo *= material_diffuse.rgb;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tdAlbedo *= gammaCorrectInput(addAlbedoDetail(texture2D(texture_diffuseMap, $UV).$CH));\n\t#endif\n\t#ifdef MAPVERTEX\n\tdAlbedo *= gammaCorrectInput(saturate(vVertexColor.$VC));\n\t#endif\n}\n",diffuseDetailMapPS:"#ifdef MAPTEXTURE\nuniform sampler2D texture_diffuseDetailMap;\n#endif\nvec3 addAlbedoDetail(vec3 albedo) {\n\t#ifdef MAPTEXTURE\n\tvec3 albedoDetail = vec3(texture2D(texture_diffuseDetailMap, $UV).$CH);\n\treturn detailMode_$DETAILMODE(albedo, albedoDetail);\n\t#else\n\treturn albedo;\n\t#endif\n}\n",dilatePS:"#define SHADER_NAME Dilate\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:"\n#define SHADER_NAME BilateralDeNoise\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\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\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",decodePS:"vec3 decodeLinear(vec4 raw) {\n\treturn raw.rgb;\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 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}\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}\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 mapMip(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",emissivePS:"#ifdef MAPCOLOR\nuniform vec3 material_emissive;\n#endif\n#ifdef MAPFLOAT\nuniform float material_emissiveIntensity;\n#endif\n#ifdef MAPTEXTURE\nuniform sampler2D texture_emissiveMap;\n#endif\nvec3 getEmission() {\n\tvec3 emission = vec3(1.0);\n\t#ifdef MAPFLOAT\n\temission *= material_emissiveIntensity;\n\t#endif\n\t#ifdef MAPCOLOR\n\temission *= material_emissive;\n\t#endif\n\t#ifdef MAPTEXTURE\n\temission *= $texture2DSAMPLE(texture_emissiveMap, $UV).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\temission *= gammaCorrectInput(saturate(vVertexColor.$VC));\n\t#endif\n\treturn emission;\n}\n",endPS:"\t#ifdef CLEARCOAT\n\tgl_FragColor.rgb = combineColorCC();\n\t#else\n\tgl_FragColor.rgb = combineColor();\n\t#endif\n\tgl_FragColor.rgb += getEmission();\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",envConstPS:"vec3 processEnvironment(vec3 color) {\n\treturn color;\n}\n",envMultiplyPS:"uniform float skyboxIntensity;\nvec3 processEnvironment(vec3 color) {\n\treturn color * skyboxIntensity;\n}\n",extensionPS:"\n",extensionVS:"\n",falloffInvSquaredPS:"float getFalloffWindow(float lightRadius) {\n\tfloat sqrDist = dot(dLightDirW, dLightDirW);\n\tfloat invRadius = 1.0 / lightRadius;\n\treturn square( saturate( 1.0 - square( sqrDist * square(invRadius) ) ) );\n}\nfloat getFalloffInvSquared(float lightRadius) {\n\tfloat sqrDist = dot(dLightDirW, dLightDirW);\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:"float getFalloffLinear(float lightRadius) {\n\tfloat d = length(dLightDirW);\n\treturn max(((lightRadius - d) / lightRadius), 0.0);\n}\n",fixCubemapSeamsNonePS:"vec3 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:"vec3 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 mantisaExponent2Float(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:"uniform 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:"uniform 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:"uniform 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\tfogFactor = gammaCorrectInput(fogFactor);\n\treturn mix(fog_color * dBlendModeFogFactor, color, fogFactor);\n}\n",fogNonePS:"float dBlendModeFogFactor = 1.0;\nvec3 addFog(vec3 color) {\n\treturn color;\n}\n",fresnelSchlickPS:"\nuniform float material_fresnelFactor;\nvoid getFresnel() {\n\tfloat fresnel = 1.0 - max(dot(dNormalW, dViewDirW), 0.0);\n\tfloat fresnel2 = fresnel * fresnel;\n\tfresnel *= fresnel2 * fresnel2;\n\tfresnel *= dGlossiness * dGlossiness;\n\tdSpecularity = dSpecularity + (1.0 - dSpecularity) * fresnel;\n\t#ifdef CLEARCOAT\n\tfresnel = 1.0 - max(dot(ccNormalW, dViewDirW), 0.0);\n\tfresnel2 = fresnel * fresnel;\n\tfresnel *= fresnel2 * fresnel2;\n\tfresnel *= ccGlossiness * ccGlossiness;\n\tccSpecularity = ccSpecularity + (1.0 - ccSpecularity) * fresnel;\n\t#endif\n}\n",fullscreenQuadPS:"varying vec2 vUv0;\nuniform sampler2D source;\nvoid main(void) {\n\tgl_FragColor = texture2D(source, vUv0);\n}\n",fullscreenQuadVS:"attribute 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:"vec4 texture2DSRGB(sampler2D tex, vec2 uv) {\n\treturn texture2D(tex, uv);\n}\nvec4 texture2DSRGB(sampler2D tex, vec2 uv, float bias) {\n\treturn texture2D(tex, uv, bias);\n}\nvec4 textureCubeSRGB(samplerCube tex, vec3 uvw) {\n\treturn textureCube(tex, uvw);\n}\nvec3 gammaCorrectOutput(vec3 color) {\n\treturn color;\n}\nvec3 gammaCorrectInput(vec3 color) {\n\treturn color;\n}\nfloat gammaCorrectInput(float color) {\n\treturn color;\n}\nvec4 gammaCorrectInput(vec4 color) {\n\treturn color;\n}\n",gamma2_2PS:"vec3 gammaCorrectInput(vec3 color) {\n\treturn pow(color, vec3(2.2));\n}\nfloat gammaCorrectInput(float color) {\n\treturn pow(color, 2.2);\n}\nvec4 gammaCorrectInput(vec4 color) {\n\treturn vec4(pow(color.rgb, vec3(2.2)), color.a);\n}\nvec4 texture2DSRGB(sampler2D tex, vec2 uv) {\n\tvec4 rgba = texture2D(tex, uv);\n\trgba.rgb = gammaCorrectInput(rgba.rgb);\n\treturn rgba;\n}\nvec4 texture2DSRGB(sampler2D tex, vec2 uv, float bias) {\n\tvec4 rgba = texture2D(tex, uv, bias);\n\trgba.rgb = gammaCorrectInput(rgba.rgb);\n\treturn rgba;\n}\nvec4 textureCubeSRGB(samplerCube tex, vec3 uvw) {\n\tvec4 rgba = textureCube(tex, uvw);\n\trgba.rgb = gammaCorrectInput(rgba.rgb);\n\treturn rgba;\n}\nvec3 gammaCorrectOutput(vec3 color) {\n\t#ifdef HDR\n\treturn color;\n\t#else\n\tcolor += vec3(0.0000001);\n\treturn pow(color, vec3(0.45));\n\t#endif\n}\n",gles3PS:"#define varying in\nout highp vec4 pc_fragColor;\n#define gl_FragColor pc_fragColor\n#define texture2D 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 GL2\n#define SUPPORTS_TEXLOD\n",gles3VS:"#define attribute in\n#define varying out\n#define texture2D texture\n#define GL2\n#define VERTEXSHADER\n",glossPS:"#ifdef MAPFLOAT\nuniform float material_shininess;\n#endif\n#ifdef MAPTEXTURE\nuniform sampler2D texture_glossMap;\n#endif\nvoid getGlossiness() {\n\tdGlossiness = 1.0;\n\t#ifdef MAPFLOAT\n\tdGlossiness *= material_shininess;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tdGlossiness *= texture2D(texture_glossMap, $UV).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tdGlossiness *= saturate(vVertexColor.$VC);\n\t#endif\n\tdGlossiness += 0.0000001;\n}\n",instancingVS:"attribute vec4 instance_line1;\nattribute vec4 instance_line2;\nattribute vec4 instance_line3;\nattribute vec4 instance_line4;\n",lightDiffuseLambertPS:"float getLightDiffuse() {\n\treturn max(dot(dNormalW, -dLightDirNormW), 0.0);\n}\n",lightDirPointPS:"void getLightDirPoint(vec3 lightPosW) {\n\tdLightDirW = vPositionW - lightPosW;\n\tdLightDirNormW = normalize(dLightDirW);\n\tdLightPosW = lightPosW;\n}\n",lightmapDirPS:"uniform sampler2D texture_lightMap;\nuniform sampler2D texture_dirLightMap;\nvoid addLightMap() {\n\tvec3 color = $texture2DSAMPLE(texture_lightMap, $UV).$CH;\n\tvec3 dir = texture2D(texture_dirLightMap, $UV).xyz;\n\tif (dot(dir, vec3(1.0)) < 0.00001) {\n\t\tdDiffuseLight += color;\n\t} else {\n\t\tdLightDirNormW = normalize(dir * 2.0 - vec3(1.0));\n\t\tfloat vlight = saturate(dot(dLightDirNormW, -dVertexNormalW));\n\t\tfloat flight = saturate(dot(dLightDirNormW, -dNormalW));\n\t\tfloat nlight = (flight / max(vlight, 0.01)) * 0.5;\n\t\tdDiffuseLight += color * nlight * 2.0;\n\t}\n\tdSpecularLight += color * getLightSpecular();\n}\n",lightmapSinglePS:"#ifdef MAPTEXTURE\nuniform sampler2D texture_lightMap;\n#endif\nvoid addLightMap() {\n\tvec3 lm = vec3(1.0);\n\t#ifdef MAPTEXTURE\n\tlm *= $texture2DSAMPLE(texture_lightMap, $UV).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tlm *= saturate(vVertexColor.$VC);\n\t#endif\n\tdDiffuseLight += lm;\n}\n",lightmapSingleVertPS:"void addLightMap() {\n\tdDiffuseLight += saturate(vVertexColor.$CH);\n}\n",lightSpecularAnisoGGXPS:"\nfloat calcLightSpecular(float tGlossiness, vec3 tNormalW) {\n\tfloat PI = 3.141592653589793;\n\tfloat roughness = max((1.0 - tGlossiness) * (1.0 - tGlossiness), 0.001);\n\tfloat anisotropy = material_anisotropy * roughness;\n\tfloat at = max((roughness + anisotropy), roughness / 4.0);\n\tfloat ab = max((roughness - anisotropy), roughness / 4.0);\n\tvec3 h = normalize(normalize(-dLightDirNormW) + normalize(dViewDirW));\n\tfloat NoH = dot(tNormalW, h);\n\tfloat ToH = dot(dTBN[0], h);\n\tfloat BoH = dot(dTBN[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(dTBN[0], dViewDirW);\n\tfloat BoV = dot(dTBN[1], dViewDirW);\n\tfloat ToL = dot(dTBN[0], -dLightDirNormW);\n\tfloat BoL = dot(dTBN[1], -dLightDirNormW);\n\tfloat NoV = dot(tNormalW, dViewDirW);\n\tfloat NoL = dot(tNormalW, -dLightDirNormW);\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() {\n\treturn calcLightSpecular(dGlossiness, dNormalW);\n}\nfloat getLightSpecularCC() {\n\treturn calcLightSpecular(ccGlossiness, ccNormalW);\n}\n",lightSpecularBlinnPS:"\nfloat calcLightSpecular(float tGlossiness, vec3 tNormalW) {\n\tvec3 h = normalize( -dLightDirNormW + dViewDirW );\n\tfloat nh = max( dot( h, tNormalW ), 0.0 );\n\tfloat specPow = exp2(tGlossiness * 11.0);\n\tspecPow = antiAliasGlossiness(specPow);\n\tspecPow = max(specPow, 0.0001);\n\treturn pow(nh, specPow) * (specPow + 2.0) / 8.0;\n}\nfloat getLightSpecular() {\n\treturn calcLightSpecular(dGlossiness, dNormalW);\n}\nfloat getLightSpecularCC() {\n\treturn calcLightSpecular(ccGlossiness, ccNormalW);\n}\n",lightSpecularPhongPS:"float calcLightSpecular(float tGlossiness, vec3 tReflDirW) {\n\tfloat specPow = tGlossiness;\n\tspecPow = antiAliasGlossiness(specPow);\n\treturn pow(max(dot(tReflDirW, -dLightDirNormW), 0.0), specPow + 0.0001);\n}\nfloat getLightSpecular() {\n\treturn calcLightSpecular(dGlossiness, dReflDirW);\n}\nfloat getLightSpecularCC() {\n\treturn calcLightSpecular(ccGlossiness, ccReflDirW);\n}\n",ltc:"\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\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 CLEARCOAT\nvec2 ccLTCUV;\n#endif\nvec2 getLTCLightUV(float tGlossiness, vec3 tNormalW)\n{\n\tfloat roughness = max((1.0 - tGlossiness) * (1.0 - tGlossiness), 0.001);\n\treturn LTC_Uv( tNormalW, dViewDirW, roughness );\n}\nvec3 dLTCSpecFres;\n#ifdef CLEARCOAT\nvec3 ccLTCSpecFres;\n#endif\nvec3 getLTCLightSpecFres(vec2 uv, vec3 tSpecularity)\n{\n\tvec4 t2 = texture2D( areaLightsLutTex2, uv );\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 tSpecularity * t2.x + ( vec3( 1.0 ) - tSpecularity) * t2.y;\n}\nvoid calcLTCLightValues()\n{\n\tdLTCUV = getLTCLightUV(dGlossiness, dNormalW);\n\tdLTCSpecFres = getLTCLightSpecFres(dLTCUV, dSpecularityNoFres);\n#ifdef CLEARCOAT\n\tccLTCUV = getLTCLightUV(ccGlossiness, ccNormalW);\n\tccLTCSpecFres = getLTCLightSpecFres(ccLTCUV, vec3(ccSpecularityNoFres));\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\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 = texture2D( areaLightsLutTex2, uv ).w;\n\treturn formFactor*scale;\n}\nfloat getRectLightDiffuse() {\n\treturn LTC_EvaluateRect( dNormalW, dViewDirW, vPositionW, mat3( 1.0 ), dLTCCoords );\n}\nfloat getDiskLightDiffuse() {\n\treturn LTC_EvaluateDisk( dNormalW, dViewDirW, vPositionW, mat3( 1.0 ), dLTCCoords );\n}\nfloat getSphereLightDiffuse() {\n\tfloat falloff = dSphereRadius / (dot(dLightDirW, dLightDirW) + dSphereRadius);\n\treturn getLightDiffuse()*falloff;\n}\nmat3 getLTCLightInvMat(vec2 uv)\n{\n\tvec4 t1 = texture2D( areaLightsLutTex1, uv );\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 tNormalW, vec2 uv) {\n\tmat3 mInv = getLTCLightInvMat(uv);\n\treturn LTC_EvaluateRect( tNormalW, dViewDirW, vPositionW, mInv, dLTCCoords );\n}\nfloat getRectLightSpecular() {\n\treturn calcRectLightSpecular(dNormalW, dLTCUV);\n}\n#ifdef CLEARCOAT\nfloat getRectLightSpecularCC() {\n\treturn calcRectLightSpecular(ccNormalW, ccLTCUV);\n}\n#endif\nfloat calcDiskLightSpecular(vec3 tNormalW, vec2 uv) {\n\tmat3 mInv = getLTCLightInvMat(uv);\n\treturn LTC_EvaluateDisk( tNormalW, dViewDirW, vPositionW, mInv, dLTCCoords );\n}\nfloat getDiskLightSpecular() {\n\treturn calcDiskLightSpecular(dNormalW, dLTCUV);\n}\n#ifdef CLEARCOAT\nfloat getDiskLightSpecularCC() {\n\treturn calcDiskLightSpecular(ccNormalW, ccLTCUV);\n}\n#endif\nfloat getSphereLightSpecular() {\n\treturn calcDiskLightSpecular(dNormalW, dLTCUV);\n}\n#ifdef CLEARCOAT\nfloat getSphereLightSpecularCC() {\n\treturn calcDiskLightSpecular(ccNormalW, ccLTCUV);\n}\n#endif\n",metalnessPS:"void processMetalness(float metalness) {\n\tconst float dielectricF0 = 0.04;\n\tdSpecularity = mix(vec3(dielectricF0), dAlbedo, metalness);\n\tdAlbedo *= 1.0 - metalness;\n}\n#ifdef MAPFLOAT\nuniform float material_metalness;\n#endif\n#ifdef MAPTEXTURE\nuniform sampler2D texture_metalnessMap;\n#endif\nvoid getSpecularity() {\n\tfloat metalness = 1.0;\n\t#ifdef MAPFLOAT\n\tmetalness *= material_metalness;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tmetalness *= texture2D(texture_metalnessMap, $UV).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tmetalness *= saturate(vVertexColor.$VC);\n\t#endif\n\tprocessMetalness(metalness);\n}\n",msdfPS:"uniform 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;\nuniform vec4 outline_color;\nuniform float outline_thickness;\nuniform vec4 shadow_color;\nuniform vec2 shadow_offset;\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\treturn tcolor;\n}\n",normalVS:"#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\tvec2 morphUV = getTextureMorphCoords();\n\tvec3 morphNormal = texture2D(morphNormalTex, morphUV).xyz;\n\ttempNormal += morphNormal;\n\t#endif\n\treturn normalize(dNormalMatrix * tempNormal);\n}\n",normalDetailMapPS:"#ifdef MAPTEXTURE\nuniform sampler2D texture_normalDetailMap;\nuniform float material_normalDetailMapBumpiness;\nvec3 blendNormals(vec3 n1, vec3 n2) {\n\tn1 += vec3(0, 0, 1);\n\tn2 *= vec3(-1, -1, 1);\n\treturn normalize(n1*dot(n1, n2)/n1.z - n2);\n}\n#endif\nvec3 addNormalDetail(vec3 normalMap) {\n\t#ifdef MAPTEXTURE\n\tvec3 normalDetailMap = unpackNormal(texture2D(texture_normalDetailMap, $UV));\n\tnormalDetailMap = normalize(mix(vec3(0.0, 0.0, 1.0), normalDetailMap, material_normalDetailMapBumpiness));\n\treturn blendNormals(normalMap, normalDetailMap);\n\t#else\n\treturn normalMap;\n\t#endif\n}\n",normalInstancedVS:"vec3 getNormal() {\n\tdNormalMatrix = mat3(instance_line1.xyz, instance_line2.xyz, instance_line3.xyz);\n\treturn normalize(dNormalMatrix * vertex_normal);\n}\n",normalMapPS:"uniform sampler2D texture_normalMap;\nuniform float material_bumpiness;\nvoid getNormal() {\n\tvec3 normalMap = unpackNormal(texture2D(texture_normalMap, $UV));\n\tnormalMap = normalize(mix(vec3(0.0, 0.0, 1.0), normalMap, material_bumpiness));\n\tdNormalMap = addNormalDetail(normalMap);\n\tdNormalW = dTBN * dNormalMap;\n}\n",normalMapFastPS:"uniform sampler2D texture_normalMap;\nvoid getNormal() {\n\tvec3 normalMap = unpackNormal(texture2D(texture_normalMap, $UV));\n\tdNormalMap = addNormalDetail(normalMap);\n\tdNormalW = dTBN * dNormalMap;\n}\n",normalSkinnedVS:"vec3 getNormal() {\n\tdNormalMatrix = mat3(dModelMatrix[0].xyz, dModelMatrix[1].xyz, dModelMatrix[2].xyz);\n\treturn normalize(dNormalMatrix * vertex_normal);\n}\n",normalVertexPS:"void getNormal() {\n\tdNormalW = normalize(dVertexNormalW);\n}\n",normalXYPS:"vec3 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:"vec3 unpackNormal(vec4 nmap) {\n\treturn nmap.xyz * 2.0 - 1.0;\n}\n",opacityPS:"#ifdef MAPFLOAT\nuniform float material_opacity;\n#endif\n#ifdef MAPTEXTURE\nuniform sampler2D texture_opacityMap;\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 *= texture2D(texture_opacityMap, $UV).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tdAlpha *= clamp(vVertexColor.$VC, 0.0, 1.0);\n\t#endif\n}\n",outputAlphaPS:"gl_FragColor.a = dAlpha;\n",outputAlphaOpaquePS:"gl_FragColor.a = 1.0;\n",outputAlphaPremulPS:"gl_FragColor.rgb *= dAlpha;\ngl_FragColor.a = dAlpha;\n",outputCubemapPS:"varying vec2 vUv0;\nuniform samplerCube source;\nuniform vec4 params;\nfloat saturate(float x) {\n\treturn clamp(x, 0.0, 1.0);\n}\nvec4 encodeRGBM(vec4 color) {\n\tcolor.rgb = pow(color.rgb, vec3(0.5));\n\tcolor.rgb *= 1.0 / 8.0;\n\tcolor.a = saturate( max( max( color.r, color.g ), max( color.b, 1.0 / 255.0 ) ) );\n\tcolor.a = ceil(color.a * 255.0) / 255.0;\n\tcolor.rgb /= color.a;\n\treturn color;\n}\nvoid main(void) {\n\tvec2 st = vUv0 * 2.0 - 1.0;\n\tfloat face = params.x;\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\tgl_FragColor = textureCube(source, vec);\n\tif (params.w >= 2.0) gl_FragColor = encodeRGBM(gl_FragColor);\n}\n",outputTex2DPS:"varying 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",packDepthMaskPS:"vec4 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.x = 0.0;\n\tres -= res.xxyz * bit_mask;\n\treturn res;\n}\n",parallaxPS:"uniform sampler2D texture_heightMap;\nuniform float material_heightMapFactor;\nvoid getParallax() {\n\tfloat parallaxScale = material_heightMapFactor;\n\tfloat height = texture2D(texture_heightMap, $UV).$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:"varying 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 = texture2DSRGB(colorMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y));\n\tvec4 ramp = texture2DSRGB(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:"vec3 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:"\tfloat animFrame = min(floor(texCoordsAlphaLife.w * animTexParams.y) + animTexParams.x, animTexParams.z);\n",particleAnimFrameLoopVS:"\tfloat animFrame = floor(mod(texCoordsAlphaLife.w * animTexParams.y + animTexParams.x, animTexParams.z + 1.0));\n",particleAnimTexVS:"\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:"void 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:"void 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:"uniform 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:"uniform 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:"\twriteOutput();\n}\n",particleUpdaterInitPS:"varying 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:"\tif (outLife >= lifetime) {\n\t\toutLife -= max(lifetime, (numParticles - 1.0) * particleRate);\n\t\tvisMode = -1.0;\n\t}\n",particleUpdaterOnStopPS:"\tvisMode = outLife < 0.0? -1.0: visMode;\n",particleUpdaterRespawnPS:"\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:"uniform 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:"float 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:"\tquadXY = rotate(quadXY, inAngle, rotMatrix);\n\tvec3 localPos = billboard(particlePos, quadXY);\n",particle_blendAddPS:"\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:"\trgb = mix(vec3(1.0), rgb, vec3(a));\n\tif (rgb.r + rgb.g + rgb.b > 2.99) discard;\n",particle_blendNormalPS:"\tif (a < 0.01) discard;\n",particle_cpuVS:"attribute vec4 particle_vertexData;\nattribute vec4 particle_vertexData2;\nattribute vec4 particle_vertexData3;\nattribute float particle_vertexData4;\n#ifndef USE_MESH\n#define VDATA5TYPE vec2\n#else\n#define VDATA5TYPE vec4\n#endif\nattribute VDATA5TYPE particle_vertexData5;\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, emitterScale, faceTangent, faceBinorm;\nuniform sampler2D texLifeAndSourcePosOUT;\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:"\tlocalPos *= particle_vertexData2.y * emitterScale;\n\tlocalPos += particlePos;\n\tgl_Position = matrix_viewProjection * vec4(localPos, 1.0);\n",particle_customFaceVS:"\tquadXY = rotate(quadXY, inAngle, rotMatrix);\n\tvec3 localPos = customFace(particlePos, quadXY);\n",particle_endPS:"\trgb = addFog(rgb);\n\trgb = toneMap(rgb);\n\trgb = gammaCorrectOutput(rgb);\n\tgl_FragColor = vec4(rgb, a);\n}\n",particle_endVS:"\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:"\tvec3 negNormal = normal*0.5+0.5;\n\tvec3 posNormal = -normal*0.5+0.5;\n\tnegNormal *= negNormal;\n\tposNormal *= posNormal;\n",particle_initVS:"attribute 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:"\tvec3 negNormal = max(normal, vec3(0.0));\n\tvec3 posNormal = max(-normal, vec3(0.0));\n",particle_lightingPS:"\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:"\tparticlePos = (matrix_model * vec4(particlePos, 1.0)).xyz;\n",particle_meshVS:"\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:"\tNormal = normalize(localPos + matrix_viewInverse[2].xyz);\n",particle_normalMapPS:"\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:"\tinAngle = atan(velocityV.x, velocityV.y);\n",particle_softPS:"\tfloat depth = getLinearScreenDepth();\n\tfloat particleDepth = vDepth;\n\tfloat depthDiff = saturate(abs(particleDepth - depth) * softening);\n\ta *= depthDiff;\n",particle_softVS:"\tvDepth = getLinearDepth(localPos);\n",particle_stretchVS:"\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:"\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:"\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",precisionTestPS:"void main(void) {\n\tgl_FragColor = vec4(2147483648.0);\n}\n",precisionTest2PS:"uniform 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",reflDirPS:"void getReflDir() {\n\tdReflDirW = normalize(-reflect(dViewDirW, dNormalW));\n}\n",reflDirAnisoPS:"void getReflDir() {\n\tfloat roughness = sqrt(1.0 - min(dGlossiness, 1.0));\n\tfloat anisotropy = material_anisotropy * roughness;\n\tvec3 anisotropicDirection = anisotropy >= 0.0 ? dTBN[1] : dTBN[0];\n\tvec3 anisotropicTangent = cross(anisotropicDirection, dViewDirW);\n\tvec3 anisotropicNormal = cross(anisotropicTangent, anisotropicDirection);\n\tvec3 bentNormal = normalize(mix(normalize(dNormalW), normalize(anisotropicNormal), anisotropy));\n\tdReflDirW = reflect(-dViewDirW, bentNormal);\n}\n",reflectionCCPS:"#ifdef CLEARCOAT\nuniform float material_clearCoatReflectivity;\nvoid addReflectionCC() {\n\tccReflection += vec4(calcReflection(ccReflDirW, ccGlossiness), material_clearCoatReflectivity);\n}\n#endif\n",reflectionCubePS:"uniform samplerCube texture_cubeMap;\nuniform float material_reflectivity;\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n\tvec3 lookupVec = fixSeams(cubeMapProject(tReflDirW));\n\tlookupVec.x *= -1.0;\n\treturn $DECODE(textureCube(texture_cubeMap, lookupVec));\n}\nvoid addReflection() {\n\tdReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",reflectionEnvPS:"#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, 0.0, 6.0);\n}\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n\tvec3 dir = cubeMapProject(tReflDirW) * vec3(-1.0, 1.0, 1.0);\n\tvec2 uv = toSphericalUv(dir);\n\tfloat level = saturate(1.0 - tGlossiness) * 5.0;\n\tfloat ilevel = floor(level);\n\tvec2 uv0, uv1;\n\tfloat weight;\n\tif (ilevel == 0.0) {\n\t\tfloat level2 = shinyMipLevel(uv * atlasSize);\n\t\tfloat ilevel2 = floor(level2);\n\t\tuv0 = mapMip(uv, ilevel2);\n\t\tuv1 = mapMip(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() {\n\tdReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",reflectionSpherePS:"#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nuniform sampler2D texture_sphereMap;\nuniform float material_reflectivity;\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n\tvec3 reflDirV = (mat3(matrix_view) * tReflDirW).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() {\n\tdReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",reflectionSphereLowPS:"uniform sampler2D texture_sphereMap;\nuniform float material_reflectivity;\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n\tvec3 reflDirV = vNormalV;\n\tvec2 sphereMapUv = reflDirV.xy * 0.5 + 0.5;\n\treturn $DECODE(texture2D(texture_sphereMap, sphereMapUv));\n}\nvoid addReflection() {\n\tdReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",refractionPS:"uniform float material_refraction, material_refractionIndex;\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 tmp = dReflDirW;\n\tvec4 tmp2 = dReflection;\n\tdReflection = vec4(0.0);\n\tdReflDirW = refract2(-dViewDirW, dNormalW, material_refractionIndex);\n\taddReflection();\n\tdDiffuseLight = mix(dDiffuseLight, dReflection.rgb * dAlbedo, material_refraction);\n\tdReflDirW = tmp;\n\tdReflection = tmp2;\n}\n",reprojectPS:"\nvarying vec2 vUv0;\nuniform sampler2D sourceTex;\nuniform samplerCube sourceCube;\nuniform sampler2D samplesTex;\nuniform vec2 samplesTexInverseSize;\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}\nvec3 decodeLinear(vec4 source) {\n\treturn source.rgb;\n}\nvec4 encodeLinear(vec3 source) {\n\treturn vec4(source, 1.0);\n}\nvec3 decodeGamma(vec4 source) {\n\treturn pow(source.xyz, vec3(2.2));\n}\nvec4 encodeGamma(vec3 source) {\n\treturn vec4(pow(source + 0.0000001, vec3(1.0 / 2.2)), 1.0);\n}\nvec3 decodeRGBM(vec4 rgbm) {\n\tvec3 color = (8.0 * rgbm.a) * rgbm.rgb;\n\treturn color * color;\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}\nvec3 decodeRGBE(vec4 source) {\n\tif (source.a == 0.0) {\n\t\treturn vec3(0.0, 0.0, 0.0);\n\t} else {\n\t\treturn source.xyz * pow(2.0, source.w * 255.0 - 128.0);\n\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}\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}\nvec4 sampleEquirect(vec2 sph) {\n\tvec2 uv = sph / vec2(PI * 2.0, PI) + 0.5;\n\treturn texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n}\nvec4 sampleEquirect(vec3 dir) {\n\treturn sampleEquirect(toSpherical(dir));\n}\nvec4 sampleCubemap(vec3 dir) {\n\treturn textureCube(sourceCube, modifySeams(dir, 1.0 - sourceCubeSeamScale()));\n}\nvec4 sampleCubemap(vec2 sph) {\n\treturn sampleCubemap(fromSpherical(sph));\n}\nvec4 sampleEquirect(vec2 sph, float mipLevel) {\n\tvec2 uv = sph / vec2(PI * 2.0, PI) + 0.5;\n#ifdef SUPPORTS_TEXLOD\n\treturn texture2DLodEXT(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel);\n#else\n\treturn texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n#endif\n}\nvec4 sampleEquirect(vec3 dir, float mipLevel) {\n\treturn sampleEquirect(toSpherical(dir), mipLevel);\n}\nvec4 sampleCubemap(vec3 dir, float mipLevel) {\n#ifdef SUPPORTS_TEXLOD\n\treturn textureCubeLodEXT(sourceCube, modifySeams(dir, 1.0 - exp2(mipLevel) * sourceCubeSeamScale()), mipLevel);\n#else\n\treturn textureCube(sourceCube, modifySeams(dir, 1.0 - exp2(mipLevel) * sourceCubeSeamScale()));\n#endif\n}\nvec4 sampleCubemap(vec2 sph, float mipLevel) {\n\treturn sampleCubemap(fromSpherical(sph), mipLevel);\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}\nvec4 sampleOctahedral(vec3 dir) {\n\tvec2 uv = octEncode(dir) * 0.5 + 0.5;\n\treturn texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n}\nvec4 sampleOctahedral(vec2 sph) {\n\treturn sampleOctahedral(fromSpherical(sph));\n}\nvec4 sampleOctahedral(vec3 dir, float mipLevel) {\n\tvec2 uv = octEncode(dir) * 0.5 + 0.5;\n#ifdef SUPPORTS_TEXLOD\n\treturn texture2DLodEXT(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel);\n#else\n\treturn texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n#endif\n}\nvec4 sampleOctahedral(vec2 sph, float mipLevel) {\n\treturn sampleOctahedral(fromSpherical(sph), mipLevel);\n}\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\tvec2 sph = toSpherical(TARGET_FUNC());\n\t\tvec2 sphu = dFdx(sph);\n\t\tvec2 sphv = dFdy(sph);\n\t\tconst float NUM_SAMPLES_SQRT = sqrt(float(NUM_SAMPLES));\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(sph +\n\t\t\t\t\t\t\t\t\t\t\t\t sphu * (u / NUM_SAMPLES_SQRT - 0.5) +\n\t\t\t\t\t\t\t\t\t\t\t\t sphv * (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);\nvoid unpackSample(int i, out vec3 L, out float mipLevel) {\n\tfloat u = (float(i * 4) + 0.5) * samplesTexInverseSize.x;\n\tfloat v = (floor(u) + 0.5) * samplesTexInverseSize.y;\n\tvec4 raw;\n\traw.x = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n\traw.y = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n\traw.z = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n\traw.w = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat);\n\tL.xyz = raw.xyz * 2.0 - 1.0;\n\tmipLevel = raw.w * 8.0;\n}\nvec4 prefilterSamples() {\n\tmat3 vecSpace = matrixFromVectorSlow(TARGET_FUNC());\n\tvec3 L;\n\tfloat mipLevel;\n\tvec3 result = vec3(0.0);\n\tfloat totalWeight = 0.0;\n\tfor (int i = 0; i < NUM_SAMPLES; ++i) {\n\t\tunpackSample(i, L, mipLevel);\n\t\tresult += DECODE_FUNC(SOURCE_FUNC(vecSpace * L, mipLevel)) * L.z;\n\t\ttotalWeight += L.z;\n\t}\n\treturn ENCODE_FUNC(result / totalWeight);\n}\nvec4 prefilterSamplesUnweighted() {\n\tmat3 vecSpace = matrixFromVectorSlow(TARGET_FUNC());\n\tvec3 L;\n\tfloat mipLevel;\n\tvec3 result = vec3(0.0);\n\tfloat totalWeight = 0.0;\n\tfor (int i = 0; i < NUM_SAMPLES; ++i) {\n\t\tunpackSample(i, L, mipLevel);\n\t\tresult += DECODE_FUNC(SOURCE_FUNC(vecSpace * L, mipLevel));\n\t}\n\treturn ENCODE_FUNC(result / float(NUM_SAMPLES));\n}\nvoid main(void) {\n\tgl_FragColor = PROCESS_FUNC();\n}\n",rgbmPS:"vec3 texture2DRGBM(sampler2D tex, vec2 uv) {\n\treturn decodeRGBM(texture2D(tex, uv));\n}\nvec3 textureCubeRGBM(samplerCube tex, vec3 uvw) {\n\treturn decodeRGBM(textureCube(tex, uvw));\n}\n",screenDepthPS:"uniform highp sampler2D uDepthMap;\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 CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params;\n#endif\n#ifdef GL2\nfloat linearizeDepth(float z) {\n\tz = z * 2.0 - 1.0;\n\treturn 1.0 / (camera_params.z * z + camera_params.w);\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\nfloat getLinearScreenDepth(vec2 uv) {\n\t#ifdef GL2\n\treturn linearizeDepth(texture2D(uDepthMap, uv).r) * camera_params.y;\n\t#else\n\treturn unpackFloat(texture2D(uDepthMap, 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:"const 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]) {\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",shadowCommonPS:"void normalOffsetPointShadow(vec4 shadowParams) {\n\tfloat distScale = length(dLightDirW);\n\tvec3 wPos = vPositionW + dVertexNormalW * shadowParams.y * clamp(1.0 - dot(dVertexNormalW, -dLightDirNormW), 0.0, 1.0) * distScale;\n\tvec3 dir = wPos - dLightPosW;\n\tdLightDirW = dir;\n}\n",shadowCoordPS:"void _getShadowCoordOrtho(mat4 shadowMatrix, vec3 shadowParams, vec3 wPos) {\n\tdShadowCoord = (shadowMatrix * vec4(wPos, 1.0)).xyz;\n\tdShadowCoord.z = saturate(dShadowCoord.z) - 0.0001;\n\t#ifdef SHADOWBIAS\n\tdShadowCoord.z += getShadowBias(shadowParams.x, shadowParams.z);\n\t#endif\n}\nvoid _getShadowCoordPersp(mat4 shadowMatrix, vec4 shadowParams, vec3 wPos) {\n\tvec4 projPos = shadowMatrix * vec4(wPos, 1.0);\n\tprojPos.xy /= projPos.w;\n\tdShadowCoord.xy = projPos.xy;\n\tdShadowCoord.z = length(dLightDirW) * shadowParams.w;\n\t#ifdef SHADOWBIAS\n\tdShadowCoord.z += getShadowBias(shadowParams.x, shadowParams.z);\n\t#endif\n}\nvoid getShadowCoordOrtho(mat4 shadowMatrix, vec3 shadowParams) {\n\t_getShadowCoordOrtho(shadowMatrix, shadowParams, vPositionW);\n}\nvoid getShadowCoordPersp(mat4 shadowMatrix, vec4 shadowParams) {\n\t_getShadowCoordPersp(shadowMatrix, shadowParams, vPositionW);\n}\nvoid getShadowCoordPerspNormalOffset(mat4 shadowMatrix, vec4 shadowParams) {\n\tfloat distScale = abs(dot(vPositionW - dLightPosW, dLightDirNormW));\n\tvec3 wPos = vPositionW + dVertexNormalW * shadowParams.y * clamp(1.0 - dot(dVertexNormalW, -dLightDirNormW), 0.0, 1.0) * distScale;\n\t_getShadowCoordPersp(shadowMatrix, shadowParams, wPos);\n}\nvoid getShadowCoordOrthoNormalOffset(mat4 shadowMatrix, vec3 shadowParams) {\n\tvec3 wPos = vPositionW + dVertexNormalW * shadowParams.y * clamp(1.0 - dot(dVertexNormalW, -dLightDirNormW), 0.0, 1.0);\n\t_getShadowCoordOrtho(shadowMatrix, shadowParams, wPos);\n}\n",shadowCoordPerspZbufferPS:"void _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) {\n\tfloat distScale = abs(dot(vPositionW - dLightPosW, dLightDirNormW));\n\tvec3 wPos = vPositionW + dVertexNormalW * shadowParams.y * clamp(1.0 - dot(dVertexNormalW, -dLightDirNormW), 0.0, 1.0) * distScale;\n\t_getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, wPos);\n}\nvoid getShadowCoordPerspZbuffer(mat4 shadowMatrix, vec4 shadowParams) {\n\t_getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, vPositionW);\n}\n",shadowEVSMPS:"float 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 shadowParams, float exponent) {\n\treturn VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, dShadowCoord.z, shadowParams.y, exponent);\n}\nfloat getShadowSpotVSM$(sampler2D shadowMap, vec4 shadowParams, float exponent) {\n\treturn VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, length(dLightDirW) * shadowParams.w + shadowParams.z, shadowParams.y, exponent);\n}\n",shadowEVSMnPS:"float VSM$(sampler2D 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$(sampler2D shadowMap, vec3 shadowParams, float exponent) {\n\treturn VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, dShadowCoord.z, shadowParams.y, exponent);\n}\nfloat getShadowSpotVSM$(sampler2D shadowMap, vec4 shadowParams, float exponent) {\n\treturn VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, length(dLightDirW) * shadowParams.w + shadowParams.z, shadowParams.y, exponent);\n}\n",shadowStandardPS:"vec3 lessThan2(vec3 a, vec3 b) {\n\treturn clamp((b - a)*1000.0, 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\treturn dot(rgbaDepth, bitShift);\n}\n#endif\n#ifdef GL2\nfloat _getShadowPCF3x3(sampler2DShadow shadowMap, vec3 shadowParams) {\n\tfloat z = dShadowCoord.z;\n\tvec2 uv = dShadowCoord.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 * texture(shadowMap, vec3(u0, v0, z));\n\tsum += uw1 * vw0 * texture(shadowMap, vec3(u1, v0, z));\n\tsum += uw0 * vw1 * texture(shadowMap, vec3(u0, v1, z));\n\tsum += uw1 * vw1 * texture(shadowMap, vec3(u1, v1, z));\n\tsum *= 1.0f / 16.0;\n\treturn sum;\n}\nfloat getShadowPCF3x3(sampler2DShadow shadowMap, vec3 shadowParams) {\n\treturn _getShadowPCF3x3(shadowMap, shadowParams);\n}\nfloat getShadowSpotPCF3x3(sampler2DShadow shadowMap, vec4 shadowParams) {\n\treturn _getShadowPCF3x3(shadowMap, shadowParams.xyz);\n}\n#else\nfloat _xgetShadowPCF3x3(mat3 depthKernel, sampler2D shadowMap, vec3 shadowParams) {\n\tmat3 shadowKernel;\n\tvec3 shadowCoord = dShadowCoord;\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 shadowParams) {\n\tvec3 shadowCoord = dShadowCoord;\n\tfloat xoffset = 1.0 / shadowParams.x;\n\tfloat dx0 = -xoffset;\n\tfloat dx1 = xoffset;\n\tmat3 depthKernel;\n\tdepthKernel[0][0] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx0, dx0)));\n\tdepthKernel[0][1] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx0, 0.0)));\n\tdepthKernel[0][2] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx0, dx1)));\n\tdepthKernel[1][0] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(0.0, dx0)));\n\tdepthKernel[1][1] = unpackFloat(texture2D(shadowMap, shadowCoord.xy));\n\tdepthKernel[1][2] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(0.0, dx1)));\n\tdepthKernel[2][0] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx1, dx0)));\n\tdepthKernel[2][1] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx1, 0.0)));\n\tdepthKernel[2][2] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx1, dx1)));\n\treturn _xgetShadowPCF3x3(depthKernel, shadowMap, shadowParams);\n}\nfloat getShadowPCF3x3(sampler2D shadowMap, vec3 shadowParams) {\n\treturn _getShadowPCF3x3(shadowMap, shadowParams);\n}\nfloat getShadowSpotPCF3x3(sampler2D shadowMap, vec4 shadowParams) {\n\treturn _getShadowPCF3x3(shadowMap, shadowParams.xyz);\n}\n#endif\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, vec4 shadowParams) {\n\treturn _getShadowPoint(shadowMap, shadowParams, dLightDirW);\n}\n",shadowStandardGL2PS:"float _getShadowPCF5x5(sampler2DShadow shadowMap, vec3 shadowParams) {\n\tfloat z = dShadowCoord.z;\n\tvec2 uv = dShadowCoord.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 * texture(shadowMap, vec3(u0, v0, z));\n\tsum += uw1 * vw0 * texture(shadowMap, vec3(u1, v0, z));\n\tsum += uw2 * vw0 * texture(shadowMap, vec3(u2, v0, z));\n\tsum += uw0 * vw1 * texture(shadowMap, vec3(u0, v1, z));\n\tsum += uw1 * vw1 * texture(shadowMap, vec3(u1, v1, z));\n\tsum += uw2 * vw1 * texture(shadowMap, vec3(u2, v1, z));\n\tsum += uw0 * vw2 * texture(shadowMap, vec3(u0, v2, z));\n\tsum += uw1 * vw2 * texture(shadowMap, vec3(u1, v2, z));\n\tsum += uw2 * vw2 * texture(shadowMap, vec3(u2, v2, z));\n\tsum *= 1.0f / 144.0;\n\tsum = gammaCorrectInput(sum);\n\tsum = saturate(sum);\n\treturn sum;\n}\nfloat getShadowPCF5x5(sampler2DShadow shadowMap, vec3 shadowParams) {\n\treturn _getShadowPCF5x5(shadowMap, shadowParams);\n}\nfloat getShadowSpotPCF5x5(sampler2DShadow shadowMap, vec4 shadowParams) {\n\treturn _getShadowPCF5x5(shadowMap, shadowParams.xyz);\n}\n",shadowVSM8PS:"float 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(sampler2D 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(sampler2D shadowMap, vec3 shadowParams, float exponent) {\n\treturn VSM8(shadowMap, dShadowCoord.xy, shadowParams.x, dShadowCoord.z, shadowParams.y, 0.0);\n}\nfloat getShadowSpotVSM8(sampler2D shadowMap, vec4 shadowParams, float exponent) {\n\treturn VSM8(shadowMap, dShadowCoord.xy, shadowParams.x, length(dLightDirW) * shadowParams.w + shadowParams.z, shadowParams.y, 0.0);\n}\n",shadowVSM_commonPS:"float 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:"attribute 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:"attribute 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:"attribute 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:"attribute vec4 vertex_boneWeights;\nattribute vec4 vertex_boneIndices;\nuniform highp sampler2D texture_poseMap;\nuniform vec4 texture_poseMapSize;\nvoid getBoneMatrix(const in float i, out vec4 v1, out vec4 v2, out vec4 v3) {\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\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:"varying 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:"varying vec3 vViewDir;\nuniform samplerCube texture_cubeMap;\nvoid main(void) {\n\tvec3 dir=vViewDir;\n\tdir.x *= -1.0;\n\tvec3 color = processEnvironment($textureCubeSAMPLE(texture_cubeMap, fixSeamsStatic(dir, $FIXCONST)).rgb);\n\tcolor = toneMap(color);\n\tcolor = gammaCorrectOutput(color);\n\tgl_FragColor = vec4(color, 1.0);\n}\n",skyboxVS:"attribute 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:"#ifdef MAPCOLOR\nuniform vec3 material_specular;\n#endif\n#ifdef MAPTEXTURE\nuniform sampler2D texture_specularMap;\n#endif\nvoid getSpecularity() {\n\tdSpecularity = vec3(1.0);\n\t#ifdef MAPCOLOR\n\tdSpecularity *= material_specular;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tdSpecularity *= texture2D(texture_specularMap, $UV).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tdSpecularity *= saturate(vVertexColor.$VC);\n\t#endif\n}\n",specularAaNonePS:"float antiAliasGlossiness(float power) {\n\treturn power;\n}\n",specularAaToksvigPS:"float antiAliasGlossiness(float power) {\n\tfloat rlen = 1.0 / saturate(length(dNormalMap));\n\tfloat toksvig = 1.0 / (1.0 + power * (rlen - 1.0));\n\treturn power * mix(1.0, toksvig, material_bumpiness);\n}\n",specularAaToksvigFastPS:"float antiAliasGlossiness(float power) {\n\tfloat rlen = 1.0 / saturate(length(dNormalMap));\n\tfloat toksvig = 1.0 / (1.0 + power * (rlen - 1.0));\n\treturn power * toksvig;\n}\n",spotPS:"float getSpotEffect(vec3 lightSpotDirW, float lightInnerConeAngle, float lightOuterConeAngle) {\n\tfloat cosAngle = dot(dLightDirNormW, lightSpotDirW);\n\treturn smoothstep(lightOuterConeAngle, lightInnerConeAngle, cosAngle);\n}\n",startPS:"void main(void) {\n\tdDiffuseLight = vec3(0);\n\tdSpecularLight = vec3(0);\n\tdReflection = vec4(0);\n\tdSpecularity = vec3(0);\n\t#ifdef CLEARCOAT\n\tccSpecularLight = vec3(0);\n\tccReflection = vec4(0);\n\t#endif\n",startVS:"void main(void) {\n\tgl_Position = getPosition();\n",startNineSlicedPS:"\tnineSlicedUv = vUv0;\n\tnineSlicedUv.y = 1.0 - nineSlicedUv.y;\n",startNineSlicedTiledPS:"\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",storeEVSMPS:"float 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:"vec3 getTangent() {\n\treturn normalize(dNormalMatrix * vertex_tangent.xyz);\n}\nvec3 getBinormal() {\n\treturn cross(vNormalW, vTangentW) * vertex_tangent.w;\n}\nvec3 getObjectSpaceUp() {\n\treturn normalize(dNormalMatrix * vec3(0, 1, 0));\n}\n",TBNPS:"void getTBN() {\n\tdTBN = mat3(normalize(dTangentW), normalize(dBinormalW), normalize(dVertexNormalW));\n}\n",TBNderivativePS:"uniform float tbnBasis;\nvoid getTBN() {\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, dVertexNormalW );\n\tvec3 dp1perp = cross( dVertexNormalW, 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, dVertexNormalW );\n}\n",TBNfastPS:"void getTBN() {\n\tdTBN = mat3(dTangentW, dBinormalW, dVertexNormalW);\n}\n",TBNObjectSpacePS:"void getTBN() {\n\tvec3 B = cross(dVertexNormalW, vObjectSpaceUpW);\n\tvec3 T = cross(dVertexNormalW, B);\n\tif (dot(B,B)==0.0)\n\t{\n\t\tfloat major=max(max(dVertexNormalW.x, dVertexNormalW.y),dVertexNormalW.z);\n\t\tif (dVertexNormalW.x==major)\n\t\t{\n\t\t\tB=cross(dVertexNormalW, vec3(0,1,0));\n\t\t\tT=cross(dVertexNormalW, B);\n\t\t}\n\t\telse if (dVertexNormalW.y==major)\n\t\t{\n\t\t\tB=cross(dVertexNormalW, vec3(0,0,1));\n\t\t\tT=cross(dVertexNormalW, B);\n\t\t}\n\t\telse if (dVertexNormalW.z==major)\n\t\t{\n\t\t\tB=cross(dVertexNormalW, vec3(1,0,0));\n\t\t\tT=cross(dVertexNormalW, B);\n\t\t}\n\t}\n\tdTBN = mat3(normalize(T), normalize(B), normalize(dVertexNormalW));\n}\n",tonemappingAcesPS:"uniform 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:"uniform 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;\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:"const 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:"uniform 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:"uniform float exposure;\nvec3 toneMap(vec3 color) {\n\treturn color * exposure;\n}\n",tonemappingNonePS:"vec3 toneMap(vec3 color) {\n\treturn color;\n}\n",transformVS:"#ifdef PIXELSNAP\nuniform vec4 uScreenSize;\n#endif\n#ifdef MORPHING\nuniform vec4 morph_weights_a;\nuniform vec4 morph_weights_b;\n#endif\n#ifdef MORPHING_TEXTURE_BASED\nuniform vec4 morph_tex_params;\nvec2 getTextureMorphCoords() {\n\tfloat vertexId = morph_vertex_id;\n\tvec2 textureSize = morph_tex_params.xy;\n\tvec2 invTextureSize = morph_tex_params.zw;\n\tfloat morphGridV = floor(vertexId * invTextureSize.x);\n\tfloat morphGridU = vertexId - (morphGridV * textureSize.x);\n\treturn (vec2(morphGridU, morphGridV) * invTextureSize) + (0.5 * invTextureSize);\n}\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\tvec2 morphUV = getTextureMorphCoords();\n\tvec3 morphPos = texture2D(morphPositionTex, morphUV).xyz;\n\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\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:"attribute vec3 vertex_position;\nuniform mat4 matrix_model;\nuniform mat4 matrix_viewProjection;\nvec3 dPositionW;\nmat4 dModelMatrix;\n",uv0VS:"#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:"vec2 getUv1() {\n\treturn vertex_texCoord1;\n}\n",viewDirPS:"void getViewDir() {\n\tdViewDirW = normalize(view_position - vPositionW);\n}\n",viewNormalVS:"#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nvec3 getViewNormal() {\n\treturn mat3(matrix_view) * vNormalW;\n}\n"};function ai(t,e){return e||(e=si),1===t||2===t?e.gamma2_2PS?e.gamma2_2PS:si.gamma2_2PS:3===t?"#define HDR\n"+(e.gamma2_2PS?e.gamma2_2PS:si.gamma2_2PS):e.gamma1_0PS?e.gamma1_0PS:si.gamma1_0PS}function ri(t,e){return e||(e=si),1===t?e.tonemappingFilmicPS?e.tonemappingFilmicPS:si.tonemappingFilmicPS:0===t?e.tonemappingLinearPS?e.tonemappingLinearPS:si.tonemappingLinearPS:2===t?e.tonemappingHejlPS?e.tonemappingHejlPS:si.tonemappingHejlPS:3===t?e.tonemappingAcesPS?e.tonemappingAcesPS:si.tonemappingAcesPS:4===t?e.tonemappingAces2PS?e.tonemappingAces2PS:si.tonemappingAces2PS:e.tonemapingNonePS?e.tonemapingNonePS:si.tonemappingNonePS}function oi(t,e){return e||(e=si),"linear"===t?e.fogLinearPS?e.fogLinearPS:si.fogLinearPS:"exp"===t?e.fogExpPS?e.fogExpPS:si.fogExpPS:"exp2"===t?e.fogExp2PS?e.fogExp2PS:si.fogExp2PS:e.fogNonePS?e.fogNonePS:si.fogNonePS}function hi(t,e){return e||(e=si),t.supportsBoneTextures?e.skinTexVS:"#define BONE_LIMIT "+t.getBoneLimit()+"\n"+e.skinConstVS}function li(t){var e="precision "+t.precision+" float;\n";return t.webgl2&&(e+="#ifdef GL2\nprecision "+t.precision+" sampler2DShadow;\n#endif\n"),e}function ci(t){return t.webgl2?"#version 300 es\n":""}function ui(){return"void main(void) {gl_FragColor = vec4(0.0);}"}function di(){return"void main(void)\n{\n"}function fi(){return"}\n"}var pi={vertex_position:ae,vertex_normal:re,vertex_tangent:oe,vertex_texCoord0:de,vertex_texCoord1:fe,vertex_texCoord2:pe,vertex_texCoord3:me,vertex_texCoord4:_e,vertex_texCoord5:ge,vertex_texCoord6:ve,vertex_texCoord7:ye,vertex_color:ce,vertex_boneIndices:le,vertex_boneWeights:he};function mi(t){for(var e={},i=0,n=t.indexOf("attribute");n>=0&&!(n>0&&"/"===t[n-1]);){var s=t.indexOf(";",n),a=t.lastIndexOf(" ",s),r=t.substr(a+1,s-(a+1)),o=pi[r];void 0!==o?e[r]=o:(e[r]="ATTR"+i,i++),n=t.indexOf("attribute",n+1)}return e}function _i(t,e,i,n,s,a){var r=t.programLib._cache,o=r[n];if(void 0!==o)return o;i=li(t)+"\n"+(i||"void main(void) {gl_FragColor = vec4(0.0);}");var h=mi(e);return t.webgl2&&(e=ci(t)+si.gles3VS+e,i=ci(t)+si.gles3PS+i),r[n]=new ni(t,{attributes:h,vshader:e,fshader:(a||"")+i,useTransformFeedback:s}),r[n]}si.collectAttribs=mi,si.createShader=function(t,e,i,n){var s=si[e],a=li(t)+"\n"+si[i],r=mi(s);return t.webgl2&&(s=ci(t)+si.gles3VS+s,a=ci(t)+si.gles3PS+a),new ni(t,{attributes:r,vshader:s,fshader:a,useTransformFeedback:n})},si.createShaderFromCode=_i;var gi={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},createShaderDefinition:function(t,e){var i={vertex_position:ae};e.skin&&(i.vertex_boneWeights=he,i.vertex_boneIndices=le),e.vertexColors&&(i.vertex_color=ce),e.diffuseMap&&(i.vertex_texCoord0=de);var n="";n+=si.transformDeclVS,e.skin?(n+=hi(t),n+=si.transformSkinnedVS):n+=si.transformVS,e.vertexColors&&(n+="attribute vec4 vertex_color;\n",n+="varying vec4 vColor;\n"),e.diffuseMap&&(n+="attribute vec2 vertex_texCoord0;\n",n+="varying vec2 vUv0;\n"),2===e.pass&&(n+="varying float vDepth;\n",n+="#ifndef VIEWMATRIX\n",n+="#define VIEWMATRIX\n",n+="uniform mat4 matrix_view;\n",n+="#endif\n",n+="#ifndef CAMERAPLANES\n",n+="#define CAMERAPLANES\n",n+="uniform vec4 camera_params;\n\n",n+="#endif\n"),n+="void main(void)\n{\n",n+=" gl_Position = getPosition();\n",2===e.pass&&(n+=" vDepth = -(matrix_view * vec4(getWorldPosition(),1.0)).z * camera_params.x;\n"),e.vertexColors&&(n+=" vColor = vertex_color;\n"),e.diffuseMap&&(n+=" vUv0 = vertex_texCoord0;\n");var s=n+="}\n";return n=li(t),e.vertexColors?n+="varying vec4 vColor;\n":n+="uniform vec4 uColor;\n",e.diffuseMap&&(n+="varying vec2 vUv0;\n",n+="uniform sampler2D texture_diffuseMap;\n"),e.fog&&(n+=oi(e.fog)),e.alphatest&&(n+=si.alphaTestPS),2===e.pass&&(n+="varying float vDepth;\n",n+=si.packDepthPS),n+="void main(void)\n{\n",e.vertexColors?n+=" gl_FragColor = vColor;\n":n+=" gl_FragColor = uColor;\n",e.diffuseMap&&(n+=" gl_FragColor *= texture2D(texture_diffuseMap, vUv0);\n"),e.alphatest&&(n+=" alphaTest(gl_FragColor.a);\n"),e.pass!==Nt&&(2===e.pass?n+=" gl_FragColor = packFloat(vDepth);\n":e.fog&&(n+=" glFragColor.rgb = addFog(gl_FragColor.rgb);\n")),{attributes:i,vshader:s,fshader:n+="}\n"}}},vi={generateKey:function(t){var e="particle";for(var i in t)t.hasOwnProperty(i)&&(e+=t[i]);return e},_animTex:function(t){var e="";return e+=t.animTexLoop?si.particleAnimFrameLoopVS:si.particleAnimFrameClampVS,e+=si.particleAnimTexVS},createShaderDefinition:function(t,e){var i="",n=li(t)+"\n";n+="#define PARTICLE\n",t.webgl2&&(i+="#define GL2\n",n+="#define GL2\n"),i+="#define VERTEXSHADER\n",e.mesh&&(i+="#define USE_MESH\n"),e.localSpace&&(i+="#define LOCAL_SPACE\n"),e.screenSpace&&(i+="#define SCREEN_SPACE\n"),e.animTex&&(i+="\nuniform vec2 animTexTilesParams;\n"),e.animTex&&(i+="\nuniform vec4 animTexParams;\n"),e.animTex&&(i+="\nuniform vec2 animTexIndexParams;\n"),2===e.normal&&(i+="\nvarying mat3 ParticleMat;\n"),1===e.normal&&(i+="\nvarying vec3 Normal;\n"),e.soft&&(i+="\nvarying float vDepth;\n");var s=e.customFace?si.particle_customFaceVS:si.particle_billboardVS;return e.useCpu?(e.soft>0&&(i+=si.screenDepthPS),i+=si.particle_cpuVS,e.localSpace&&(i+=si.particle_localShiftVS),e.animTex&&(i+=this._animTex(e)),e.alignToMotion&&(i+=si.particle_pointAlongVS),i+=e.mesh?si.particle_meshVS:s,1===e.normal&&(i+=si.particle_normalVS),2===e.normal&&(i+=si.particle_TBNVS),e.stretch>0&&(i+=si.particle_stretchVS),i+=si.particle_cpu_endVS,e.soft>0&&(i+=si.particle_softVS)):(i+=si.particle_initVS,i+=e.pack8?si.particleInputRgba8PS:si.particleInputFloatPS,e.soft>0&&(i+=si.screenDepthPS),i+=si.particleVS,e.localSpace&&(i+=si.particle_localShiftVS),e.animTex&&(i+=this._animTex(e)),e.wrap&&(i+=si.particle_wrapVS),e.alignToMotion&&(i+=si.particle_pointAlongVS),i+=e.mesh?si.particle_meshVS:s,1===e.normal&&(i+=si.particle_normalVS),2===e.normal&&(i+=si.particle_TBNVS),e.stretch>0&&(i+=si.particle_stretchVS),i+=si.particle_endVS,e.soft>0&&(i+=si.particle_softVS)),i+="}\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+=ai(e.gamma),n+=ri(e.toneMap),"linear"===e.fog?n+=si.fogLinearPS:"exp"===e.fog?n+=si.fogExpPS:"exp2"===e.fog?n+=si.fogExp2PS:n+=si.fogNonePS,2===e.normal&&(n+="\nuniform sampler2D normalMap;\n"),e.soft>0&&(n+=si.screenDepthPS),n+=si.particlePS,e.soft>0&&(n+=si.particle_softPS),1===e.normal&&(n+="\nvec3 normal = Normal;\n"),2===e.normal&&(n+=si.particle_normalMapPS),e.normal>0&&(n+=e.halflambert?si.particle_halflambertPS:si.particle_lambertPS),e.normal>0&&(n+=si.particle_lightingPS),2===e.blend?n+=si.particle_blendNormalPS:1===e.blend?n+=si.particle_blendAddPS:5===e.blend&&(n+=si.particle_blendMultiplyPS),n+=si.particle_endPS,{attributes:mi(i),vshader:i,fshader:n}}},yi={generateKey:function(t){return"cubemap"===t.type?"skybox-"+t.type+"-"+t.rgbm+"-"+t.hdr+"-"+t.fixSeams+"-"+t.toneMapping+"-"+t.gamma+"-"+t.useIntensity+"-"+t.mip:"skybox-"+t.type+"-"+t.encoding+"-"+t.useIntensity+"-"+t.gamma+"-"+t.toneMapping},createShaderDefinition:function(t,e){var i;if("cubemap"===e.type){i=li(t),i+=e.mip?si.fixCubemapSeamsStretchPS:si.fixCubemapSeamsNonePS,i+=e.useIntensity?si.envMultiplyPS:si.envConstPS,i+=ai(e.gamma),i+=ri(e.toneMapping),i+=si.decodePS,i+=si.rgbmPS,i+=si.skyboxHDRPS.replace(/\$textureCubeSAMPLE/g,e.rgbm?"textureCubeRGBM":e.hdr?"textureCube":"textureCubeSRGB").replace(/\$FIXCONST/g,1-1/[128,64,16,8,4,2][e.mip]+"")}else{i=li(t),i+=e.useIntensity?si.envMultiplyPS:si.envConstPS,i+=ai(e.gamma),i+=ri(e.toneMapping),i+=si.decodePS,i+=si.skyboxEnvPS.replace(/\$DECODE/g,{rgbm:"decodeRGBM",rgbe:"decodeRGBE",linear:"decodeLinear"}[e.encoding]||"decodeGamma")}return{attributes:{aPosition:ae},vshader:si.skyboxVS,fshader:i}}},xi=1/255,bi=new Float32Array(1),Si=new Int32Array(bi.buffer),wi=function(){function t(){}return t.float2Half=function(t){bi[0]=t;var e=Si[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-xi*s)),n>1){var a=65025*t%1;if(e[i+1]=Math.round(255*(s-xi*a)),n>2){var r=16581375*t%1;e[i+2]=Math.round(255*(a-xi*r)),n>3&&(e[i+3]=Math.round(255*r))}}},t.float2BytesRange=function(e,i,n,s,a,r){e=it.clamp((e-s)/(a-s),0,1),t.float2Bytes(e,i,n,r)},t.float2MantisaExponent=function(e,i,n,s){var a=Math.floor(Math.log2(Math.abs(e)))+1;e/=Math.pow(2,a),t.float2BytesRange(e,i,n,-1,1,s-1),i[n+s-1]=Math.round(a+127)},t}(),Ti=null,Ai=null,Mi=function(){function t(t,e){this.device=t,this.name=null,this._width=4,this._height=4,this._depth=1,this._format=7,this.type=Be,this.projection=Ve,this._cubemap=!1,this._volume=!1,this.fixCubemapSeams=!1,this._flipY=!1,this._premultiplyAlpha=!1,this._isRenderTarget=!1,this._mipmaps=!0,this._minFilter=5,this._magFilter=1,this._anisotropy=1,this._addressU=0,this._addressV=0,this._addressW=0,this._compareOnRead=!1,this._compareFunc=1,void 0!==e&&(void 0!==e.name&&(this.name=e.name),this._width=void 0!==e.width?e.width:this._width,this._height=void 0!==e.height?e.height:this._height,this._format=void 0!==e.format?e.format:this._format,e.hasOwnProperty("type")?this.type=e.type:e.hasOwnProperty("rgbm")?this.type=e.rgbm?Ne:Be:e.hasOwnProperty("swizzleGGGR")&&(this.type=e.swizzleGGGR?ze:Be),void 0!==e.mipmaps?this._mipmaps=e.mipmaps:this._mipmaps=void 0!==e.autoMipmap?e.autoMipmap:this._mipmaps,this._levels=e.levels,this._cubemap=void 0!==e.cubemap?e.cubemap:this._cubemap,this.fixCubemapSeams=void 0!==e.fixCubemapSeams?e.fixCubemapSeams:this.fixCubemapSeams,this._cubemap?this.projection=Ge:e.projection&&e.projection!==Ge&&(this.projection=e.projection),this._minFilter=void 0!==e.minFilter?e.minFilter:this._minFilter,this._magFilter=void 0!==e.magFilter?e.magFilter:this._magFilter,this._anisotropy=void 0!==e.anisotropy?e.anisotropy:this._anisotropy,this._addressU=void 0!==e.addressU?e.addressU:this._addressU,this._addressV=void 0!==e.addressV?e.addressV:this._addressV,this._compareOnRead=void 0!==e.compareOnRead?e.compareOnRead:this._compareOnRead,this._compareFunc=void 0!==e._compareFunc?e._compareFunc:this._compareFunc,this._flipY=void 0!==e.flipY?e.flipY:this._flipY,this._premultiplyAlpha=void 0!==e.premultiplyAlpha?e.premultiplyAlpha:this._premultiplyAlpha,t.webgl2&&(this._depth=void 0!==e.depth?e.depth:this._depth,this._volume=void 0!==e.volume?e.volume:this._volume,this._addressW=void 0!==e.addressW?e.addressW:this._addressW)),this._compressed=8===this._format||9===this._format||this._format===Kt||this._format>=ie,this._invalid=!1,this._lockedLevel=-1,this._levels||(this._levels=this._cubemap?[[null,null,null,null,null,null]]:[null]),this.dirtyAll(),this._gpuSize=0}t.calcGpuSize=function(t,e,i,n,s,a){Ti||((Ti=[])[0]=1,Ti[1]=1,Ti[2]=2,Ti[3]=2,Ti[4]=2,Ti[5]=2,Ti[6]=4,Ti[7]=4,Ti[11]=8,Ti[12]=8,Ti[13]=16,Ti[14]=16,Ti[15]=4,Ti[16]=4,Ti[17]=4,Ti[18]=4,Ti[19]=4,Ti[20]=4),Ai||((Ai=[])[21]=8,Ai[22]=8,Ai[24]=8,Ai[25]=8,Ai[26]=8,Ai[27]=8,Ai[8]=8,Ai[29]=8,Ai[23]=16,Ai[9]=16,Ai[10]=16,Ai[28]=16,Ai[30]=16);for(var r=Ti.hasOwnProperty(n)?Ti[n]:0,o=Ai.hasOwnProperty(n)?Ai[n]:0,h=0;;){if(r>0)h+=t*e*i*r;else{var l=Math.floor((t+3)/4),c=Math.floor((e+3)/4),u=Math.floor((i+3)/4);n!==ne&&n!==se||(l=Math.max(Math.floor(l/2),1)),h+=l*c*u*o}if(!s||1===t&&1===e&&1===i)break;t=Math.max(Math.floor(t/2),1),e=Math.max(Math.floor(e/2),1),i=Math.max(Math.floor(i/2),1)}return h*(a?6:1)};var e=t.prototype;return e.destroy=function(){this.device&&this.device.destroyTexture(this),this.device=null,this._levels=this._cubemap?[[null,null,null,null,null,null]]:[null]},e.dirtyAll=function(){this._levelsUpdated=this._cubemap?[[!0,!0,!0,!0,!0,!0]]:[!0],this._needsUpload=!0,this._needsMipmapsUpload=this._mipmaps,this._mipmapsUploaded=!1,this._parameterFlags=255},e.lock=function(t){if(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,null===this._levels[t.level])switch(this._format){case 0:case 1:this._levels[t.level]=new Uint8Array(this._width*this._height*this._depth);break;case 2:this._levels[t.level]=new Uint8Array(this._width*this._height*this._depth*2);break;case 3:case 4:case 5:this._levels[t.level]=new Uint16Array(this._width*this._height*this._depth);break;case 6:this._levels[t.level]=new Uint8Array(this._width*this._height*this._depth*3);break;case 7:this._levels[t.level]=new Uint8Array(this._width*this._height*this._depth*4);break;case 8:this._levels[t.level]=new Uint8Array(Math.floor((this._width+3)/4)*Math.floor((this._height+3)/4)*8*this._depth);break;case 9:case Kt:this._levels[t.level]=new Uint8Array(Math.floor((this._width+3)/4)*Math.floor((this._height+3)/4)*16*this._depth);break;case Zt:this._levels[t.level]=new Uint16Array(this._width*this._height*this._depth*3);break;case Qt:this._levels[t.level]=new Float32Array(this._width*this._height*this._depth*3);break;case $t:this._levels[t.level]=new Uint16Array(this._width*this._height*this._depth*4);break;case Jt:this._levels[t.level]=new Float32Array(this._width*this._height*this._depth*4)}return this._levels[t.level]},e.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 a=0;a<6;a++){var r=t[a];if(!r||r.width!==i||r.height!==n||!this.device._isBrowserInterface(r)){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())},e.getSource=function(t){return void 0===t&&(t=0),this._levels[t]},e.unlock=function(){this._lockedLevel,this.upload(),this._lockedLevel=-1},e.upload=function(){this._needsUpload=!0,this._needsMipmapsUpload=this._mipmaps},e.getDds=function(){for(var t=128,e=0;this._levels[e];){if(this.cubemap)for(var i=0;i<6;i++){if(!this._levels[e][i])return;var n=this._levels[e][i].length;if(!n)return;t+=n}else{var s=this._levels[e].length;if(!s)return;t+=s}t+=this._levels[e].length,e++}var a=new ArrayBuffer(t),r=new Uint32Array(a,0,32),o=528391;this._levels.length>1&&(o|=131072);var h=4096;this._levels.length>1&&(h|=4194304),(this._levels.length>1||this.cubemap)&&(h|=8);var l=this.cubemap?65024:0;r[0]=542327876,r[1]=124,r[2]=o,r[3]=this.height,r[4]=this.width,r[5]=this.width*this.height*4,r[6]=0,r[7]=this._levels.length;for(var c=0;c<11;c++)r[8+c]=0;r[19]=32,r[20]=65,r[21]=0,r[22]=32,r[23]=16711680,r[24]=65280,r[25]=255,r[26]=4278190080,r[27]=h,r[28]=l,r[29]=0,r[30]=0,r[31]=0;var u=128;if(this.cubemap)for(var d=0;d<6;d++)for(var f=0;f=0?t.insertChild(this,e):t.addChild(this))},i.setLocalEulerAngles=function(t,e,i){t instanceof lt?this.localRotation.setFromEulerAngles(t.x,t.y,t.z):this.localRotation.setFromEulerAngles(t,e,i),this._dirtyLocal||this._dirtifyLocal()},i.setLocalPosition=function(t,e,i){t instanceof lt?this.localPosition.copy(t):this.localPosition.set(t,e,i),this._dirtyLocal||this._dirtifyLocal()},i.setLocalRotation=function(t,e,i,n){t instanceof yt?this.localRotation.copy(t):this.localRotation.set(t,e,i,n),this._dirtyLocal||this._dirtifyLocal()},i.setLocalScale=function(t,e,i){t instanceof lt?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;t8?t.FORMAT_FLOAT:t.FORMAT_8BIT,t.initShaderDefines()},t.createTexture=function(t,e,i,n){return new Mi(t,{width:e,height:i,mipmaps:!1,format:n,addressU:1,addressV:1,type:Be,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(tn,Qi),Ji[0]=Qi.x,Ji[1]=Qi.y,Ji[2]=Qi.z,e.transformVector(en,Qi),Ji[3]=Qi.x,Ji[4]=Qi.y,Ji[5]=Qi.z,Ji},e.addLightDataFlags=function(t,e,i,n){t[e+0]=n?255:0,t[e+1]=64*i._shape,t[e+2]=255*i._falloffMode,t[e+3]=i.castShadows?255:0},e.addLightDataColor=function(t,e,i,n,s){var a=this.invMaxColorValue,r=n?i._linearFinalColor:i._finalColor;wi.float2Bytes(r[0]*a,t,e+0,2),wi.float2Bytes(r[1]*a,t,e+2,2),wi.float2Bytes(r[2]*a,t,e+4,2),t[e+6]=s?255:0},e.addLightDataSpotAngles=function(t,e,i){wi.float2Bytes(.499999*i._innerConeAngleCos+.5,t,e+0,2),wi.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);wi.float2BytesRange(s.bias,t,e,-1,20,2),wi.float2Bytes(s.normalBias,t,e+2,2)},e.addLightDataPositionRange=function(t,e,i,n){var s=Qi.sub2(n,this.boundsMin).div(this.boundsDelta);wi.float2Bytes(s.x,t,e+0,4),wi.float2Bytes(s.y,t,e+4,4),wi.float2Bytes(s.z,t,e+8,4),wi.float2Bytes(i.attenuationEnd*this.invMaxAttenuation,t,e+12,4)},e.addLightDataSpotDirection=function(t,e,i){this.getSpotDirection(Qi,i),wi.float2Bytes(.499999*Qi.x+.5,t,e+0,4),wi.float2Bytes(.499999*Qi.y+.5,t,e+4,4),wi.float2Bytes(.499999*Qi.z+.5,t,e+8,4)},e.addLightDataLightProjMatrix=function(t,e,i){for(var n=i.data,s=0;s<12;s++)wi.float2BytesRange(n[s],t,e+4*s,-2,2,4);for(var a=12;a<16;a++)wi.float2MantisaExponent(n[a],t,e+4*a,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){wi.float2Bytes(i.x,t,e+0,2),wi.float2Bytes(i.y,t,e+2,2),wi.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++)wi.float2MantisaExponent(n[s],t,e+4*s,4)},e.addLightData=function(e,i,n){var s=2===e._type,a=this.cookiesEnabled&&!!e._cookie,r=this.areaLightsEnabled&&0!==e.shape,o=this.shadowsEnabled&&e.castShadows,h=e._node.getPosition(),l=null,c=null;s?o?l=e.getRenderData(null,0).shadowMatrix:a&&(l=$i.evalSpotCookieMatrix(e)):(o||a)&&(c=e.atlasViewport);var u=this.lights8,d=i*this.lightsTexture8.width*4;if(this.addLightDataFlags(u,d+4*nn.FLAGS,e,s),this.addLightDataColor(u,d+4*nn.COLOR_A,e,n,a),s&&this.addLightDataSpotAngles(u,d+4*nn.SPOT_ANGLES,e),e.castShadows&&this.addLightDataShadowBias(u,d+4*nn.SHADOW_BIAS,e),a&&this.addLightDataCookies(u,d+4*nn.COOKIE_A,e),t.lightTextureFormat===t.FORMAT_FLOAT){var f=this.lightsFloat,p=i*this.lightsTextureFloat.width*4;if(f[p+4*sn.POSITION_RANGE+0]=h.x,f[p+4*sn.POSITION_RANGE+1]=h.y,f[p+4*sn.POSITION_RANGE+2]=h.z,f[p+4*sn.POSITION_RANGE+3]=e.attenuationEnd,s&&(this.getSpotDirection(Qi,e),f[p+4*sn.SPOT_DIRECTION+0]=Qi.x,f[p+4*sn.SPOT_DIRECTION+1]=Qi.y,f[p+4*sn.SPOT_DIRECTION+2]=Qi.z),l)for(var m=l.data,_=0;_<16;_++)f[p+4*sn.PROJ_MAT_0+_]=m[_];if(c&&(f[p+4*sn.ATLAS_VIEWPORT+0]=c.x,f[p+4*sn.ATLAS_VIEWPORT+1]=c.y,f[p+4*sn.ATLAS_VIEWPORT+2]=c.z/3),r){var g=this.getLightAreaSizes(e);f[p+4*sn.AREA_DATA_WIDTH+0]=g[0],f[p+4*sn.AREA_DATA_WIDTH+1]=g[1],f[p+4*sn.AREA_DATA_WIDTH+2]=g[2],f[p+4*sn.AREA_DATA_HEIGHT+0]=g[3],f[p+4*sn.AREA_DATA_HEIGHT+1]=g[4],f[p+4*sn.AREA_DATA_HEIGHT+2]=g[5]}}else this.addLightDataPositionRange(u,d+4*nn.POSITION_X,e,h),s&&this.addLightDataSpotDirection(u,d+4*nn.SPOT_DIRECTION_X,e),l&&this.addLightDataLightProjMatrix(u,d+4*nn.PROJ_MAT_00,l),c&&this.addLightAtlasViewport(u,d+4*nn.ATLAS_VIEWPORT_A,c),r&&this.addLightAreaSizes(u,d+4*nn.AREA_DATA_WIDTH_X,e)},t}();an.FORMAT_FLOAT=0,an.FORMAT_8BIT=1,an.lightTextureFormat=an.FORMAT_8BIT,an.shaderDefines="";var rn=[],on={rgbm:"decodeRGBM",rgbe:"decodeRGBE",linear:"decodeLinear"},hn={optionsContext:{},optionsContextMin:{},generateKey:function(t){var e,i=function(t){var e=[];for(var i in t)t.hasOwnProperty(i)&&"chunks"!==i&&"lights"!==i&&e.push(i);return e.sort()};t===this.optionsContextMin?(this.propsMin||(this.propsMin=i(t)),e=this.propsMin):t===this.optionsContext?(this.props||(this.props=i(t)),e=this.props):e=i(t);for(var n="standard",s=0;s0){if(rn[t]e.length){for(var i=e,n=i.charAt(i.length-1),s=rn[t]-i.length,a=0;a1&&(a+="getShadowCascadeMatrix(light"+n+"_shadowMatrixPalette, light"+n+"_shadowCascadeDistances, light"+n+"_shadowCascadeCount);\n",e="(cascadeShadowMat, "+i+");\n"),a+=s+e,a+="fadeShadow(light"+n+"_shadowCascadeDistances);\n"},_nonPointShadowMapProjection:function(t,e,i,n,s){var a="("+i+", "+n+");\n";return!e._normalOffsetBias||e._isVsm?2===e._type?e._isPcf&&(t.webgl2||t.extStandardDerivatives)?" getShadowCoordPerspZbuffer"+a:" getShadowCoordPersp"+a:this._directionalShadowMapProjection(e,a,n,s,"getShadowCoordOrtho"):2===e._type?e._isPcf&&(t.webgl2||t.extStandardDerivatives)?" getShadowCoordPerspZbufferNormalOffset"+a:" getShadowCoordPerspNormalOffset"+a:this._directionalShadowMapProjection(e,a,n,s,"getShadowCoordOrthoNormalOffset")},_addVaryingIfNeeded:function(t,e,i){return t.indexOf(i)>=0?"varying "+e+" "+i+";\n":""},_getLightSourceShapeString:function(t){switch(t){case 1:return"Rect";case 2:return"Disk";case 3:return"Sphere";default:return""}},_getPassDefineString:function(t){return t===Nt?"#define PICK_PASS\n":2===t?"#define DEPTH_PASS\n":t>=3&&t<=17?"#define SHADOW_PASS\n":""},_vsAddTransformCode:function(t,e,i,n){return t+=i.transformVS},_vsAddBaseCode:function(t,e,i,n){return t+=i.baseVS,1!==n.nineSlicedMode&&2!==n.nineSlicedMode||(t+=i.baseNineSlicedVS),t},_fsAddBaseCode:function(t,e,i,n){return t+=i.basePS,1===n.nineSlicedMode?t+=i.baseNineSlicedPS:2===n.nineSlicedMode&&(t+=i.baseNineSlicedTiledPS),t},_decodeFunc:function(t){return on[t]||"decodeGamma"},_fsAddStartCode:function(t,e,i,n){return t+=i.startPS,1===n.nineSlicedMode?t+=i.startNineSlicedPS:2===n.nineSlicedMode&&(t+=i.startNineSlicedTiledPS),t},_buildShadowPassFragmentCode:function(t,e,i,n,s){var a=n.pass-3,r=Math.floor(a/6),o=a-6*r;return e.extStandardDerivatives&&!e.webgl2&&(t+="uniform vec2 polygonOffset;\n"),3===o?e.textureFloatHighPrecision?t+="#define VSM_EXPONENT 15.0\n\n":t+="#define VSM_EXPONENT 5.54\n\n":2===o&&(t+="#define VSM_EXPONENT 5.54\n\n"),0!==r&&(t+="uniform vec3 view_position;\n",t+="uniform float light_radius;\n"),t+=s,n.alphaTest&&(t+="float dAlpha;\n",t+=this._addMap("opacity","opacityPS",n,i),t+=i.alphaTestPS),0!==o||e.webgl2&&1!==r?1===o&&(t+="vec2 encodeFloatRG( float v ) {\n",t+=" vec2 enc = vec2(1.0, 255.0) * v;\n",t+=" enc = fract(enc);\n",t+=" enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n",t+=" return enc;\n",t+="}\n\n"):t+=i.packDepthPS,t+="void main(void)\n{\n",n.alphaTest&&(t+=" getOpacity();\n",t+=" alphaTest(dAlpha);\n"),t+=1===r||(1===o||2===o||3===o)&&0!==r?" float depth = min(distance(view_position, vPositionW) / light_radius, 0.99999);\n":" float depth = gl_FragCoord.z;\n",0!==o||e.webgl2&&(1!==r||n.clusteredLightingEnabled)?0===o||4===o?(t+=" gl_FragColor = vec4(1.0);\n",n.clusteredLightingEnabled&&1===r&&e.webgl2&&(t+=" gl_FragDepth = depth;\n")):t+=1===o?" gl_FragColor = vec4(encodeFloatRG(depth), encodeFloatRG(depth*depth));\n":i.storeEVSMPS:e.extStandardDerivatives&&!e.webgl2?(t+=" float minValue = 2.3374370500153186e-10; //(1.0 / 255.0) / (256.0 * 256.0 * 256.0);\n",t+=" depth += polygonOffset.x * max(abs(dFdx(depth)), abs(dFdy(depth))) + minValue * polygonOffset.y;\n",t+=" gl_FragColor = packFloat(depth);\n"):t+=" gl_FragColor = packFloat(depth);\n",t+="}\n"},createShaderDefinition:function(t,e){var i=e.lights.length>0;e.dirLightMap&&(i=!0),e.clusteredLightingEnabled&&e.useLighting&&(i=!0),0===e.shadingModel?(e.fresnelModel=0,e.specularAntialias=!1,e.ambientSH=!1):e.fresnelModel=0===e.fresnelModel?2:e.fresnelModel;var n=!!e.reflectionSource;e.useSpecular||(e.specularMap=e.glossMap=null);var s=e.pass>=3&&e.pass<=17,a=i||n||e.ambientSH||e.heightMap||e.enableGGXSpecular||e.clusteredLightingEnabled&&!s||e.clearCoatNormalMap;this.options=e;var r,o,h="",l="",c="",u=si,d={vertex_position:ae};if(e.chunks){var f={};for(var p in u)u.hasOwnProperty(p)&&(e.chunks[p]?((o=e.chunks[p]).indexOf("vertex_normal")>=0&&(d.vertex_normal=re),o.indexOf("vertex_tangent")>=0&&(d.vertex_tangent=oe),o.indexOf("vertex_texCoord0")>=0&&(d.vertex_texCoord0=de),o.indexOf("vertex_texCoord1")>=0&&(d.vertex_texCoord1=fe),o.indexOf("vertex_color")>=0&&(d.vertex_color=ce),o.indexOf("vertex_boneWeights")>=0&&(d.vertex_boneWeights=he),o.indexOf("vertex_boneIndices")>=0&&(d.vertex_boneIndices=le),f[p]=o):f[p]=u[p]);u=f}h+=this._getPassDefineString(e.pass),h=this._vsAddBaseCode(h,t,u,e),l+=" vPositionW = getWorldPosition();\n",2===e.pass&&(h+="varying float vDepth;\n",h+="#ifndef VIEWMATRIX\n",h+="#define VIEWMATRIX\n",h+="uniform mat4 matrix_view;\n",h+="#endif\n",h+="#ifndef CAMERAPLANES\n",h+="#define CAMERAPLANES\n",h+="uniform vec4 camera_params;\n\n",h+="#endif\n",l+=" vDepth = -(matrix_view * vec4(vPositionW,1.0)).z * camera_params.x;\n"),e.useInstancing&&(d.instance_line1=De,d.instance_line2=Oe,d.instance_line3=ke,d.instance_line4=Fe,h+=u.instancingVS),a&&(d.vertex_normal=re,l+=" vNormalW = getNormal();\n","sphereMap"===e.reflectionSource&&t.fragmentUniformsCount<=16&&(h+=u.viewNormalVS,l+=" vNormalV = getViewNormal();\n"),(e.heightMap||e.normalMap||e.enableGGXSpecular)&&e.hasTangents?(d.vertex_tangent=oe,h+=u.tangentBinormalVS,l+=" vTangentW = getTangent();\n",l+=" vBinormalW = getBinormal();\n"):e.enableGGXSpecular&&(h+=u.tangentBinormalVS,l+=" vObjectSpaceUpW = getObjectSpaceUp();\n"));var m=[],_=[];for(var g in rn){var v=g+"Map";if(e[g+"VertexColor"]){var y=g+"VertexColorChannel";e[y]=this._correctChannel(g,e[y])}if(e[v]){var x=v+"Channel",b=v+"Transform",S=v+"Uv";e[S]=Math.min(e[S],1),e[x]=this._correctChannel(g,e[x]);var w=e[S];m[w]=!0,_[w]=_[w]||e[v]&&!e[b]}}e.forceUv1&&(m[1]=!0,_[1]=void 0===_[1]||_[1]);for(var T=0;T<2;T++)m[T]&&(d["vertex_texCoord"+T]="TEXCOORD"+T,h+=u["uv"+T+"VS"],l+=" vec2 uv"+T+" = getUv"+T+"();\n"),_[T]&&(l+=" vUv"+T+" = uv"+T+";\n");var A=[h,c,l,[]];for(var M in rn){var C=M+"Map";if(e[C]){var E=C+"Transform";if(e[E]){var P=C+"Uv";this._setMapTransform(A,M,e[E],e[P])}}}h=A[0],c=A[1],l=A[2],e.vertexColors&&(d.vertex_color=ce,l+=" vVertexColor = vertex_color;\n"),(e.useMorphPosition||e.useMorphNormal)&&(e.useMorphTextureBased?(h+="#define MORPHING_TEXTURE_BASED\n",e.useMorphPosition&&(h+="#define MORPHING_TEXTURE_BASED_POSITION\n"),e.useMorphNormal&&(h+="#define MORPHING_TEXTURE_BASED_NORMAL\n"),d.morph_vertex_id=Fe,h+="attribute float morph_vertex_id;\n"):(h+="#define MORPHING\n",e.useMorphPosition?(d.morph_pos0=Pe,d.morph_pos1=Re,d.morph_pos2=Ie,d.morph_pos3=Le,h+="#define MORPHING_POS03\n",h+="attribute vec3 morph_pos0;\n",h+="attribute vec3 morph_pos1;\n",h+="attribute vec3 morph_pos2;\n",h+="attribute vec3 morph_pos3;\n"):e.useMorphNormal&&(d.morph_nrm0=Pe,d.morph_nrm1=Re,d.morph_nrm2=Ie,d.morph_nrm3=Le,h+="#define MORPHING_NRM03\n",h+="attribute vec3 morph_nrm0;\n",h+="attribute vec3 morph_nrm1;\n",h+="attribute vec3 morph_nrm2;\n",h+="attribute vec3 morph_nrm3;\n"),e.useMorphNormal?(d.morph_nrm4=De,d.morph_nrm5=Oe,d.morph_nrm6=ke,d.morph_nrm7=Fe,h+="#define MORPHING_NRM47\n",h+="attribute vec3 morph_nrm4;\n",h+="attribute vec3 morph_nrm5;\n",h+="attribute vec3 morph_nrm6;\n",h+="attribute vec3 morph_nrm7;\n"):(d.morph_pos4=De,d.morph_pos5=Oe,d.morph_pos6=ke,d.morph_pos7=Fe,h+="#define MORPHING_POS47\n",h+="attribute vec3 morph_pos4;\n",h+="attribute vec3 morph_pos5;\n",h+="attribute vec3 morph_pos6;\n",h+="attribute vec3 morph_pos7;\n"))),e.skin?(d.vertex_boneWeights=he,d.vertex_boneIndices=le,h+=hi(t,u),h+="#define SKIN\n"):e.useInstancing&&(h+="#define INSTANCING\n"),e.screenSpace&&(h+="#define SCREENSPACE\n"),e.pixelSnap&&(h+="#define PIXELSNAP\n"),h=this._vsAddTransformCode(h,t,u,e),a&&(h+=u.normalVS),h+="\n",h+=u.startVS,h+=l,h+=u.endVS;var R=h+="}",I=c;c="",c+=this._addVaryingIfNeeded(h,"vec4","vVertexColor"),c+=this._addVaryingIfNeeded(h,"vec3","vPositionW"),c+=this._addVaryingIfNeeded(h,"vec3","vNormalV"),c+=this._addVaryingIfNeeded(h,"vec3","vNormalW"),c+=this._addVaryingIfNeeded(h,"vec3","vTangentW"),c+=this._addVaryingIfNeeded(h,"vec3","vBinormalW"),c+=this._addVaryingIfNeeded(h,"vec3","vObjectSpaceUpW"),c+=this._addVaryingIfNeeded(h,"vec2","vUv0"),c+=this._addVaryingIfNeeded(h,"vec2","vUv1"),R=(c+=I)+R;var L="";if(t.webgl2?(L=ci(t),u.extensionVS&&(L+=u.extensionVS+"\n"),R=L+u.gles3VS+R):(u.extensionVS&&(L=u.extensionVS+"\n"),R=L+R),e.forceFragmentPrecision&&"highp"!==e.forceFragmentPrecision&&"mediump"!==e.forceFragmentPrecision&&"lowp"!==e.forceFragmentPrecision&&(e.forceFragmentPrecision=null),e.forceFragmentPrecision&&("highp"===e.forceFragmentPrecision&&"highp"!==t.maxPrecision&&(e.forceFragmentPrecision="mediump"),"mediump"===e.forceFragmentPrecision&&"lowp"===t.maxPrecision&&(e.forceFragmentPrecision="lowp")),h="",t.webgl2&&(h+=ci(t)),t.webgl2||(t.extStandardDerivatives&&(h+="#extension GL_OES_standard_derivatives : enable\n"),t.extTextureLod&&(h+="#extension GL_EXT_shader_texture_lod : enable\n",h+="#define SUPPORTS_TEXLOD\n")),u.extensionPS&&(h+=u.extensionPS+"\n"),t.webgl2&&(h+=u.gles3PS),h+=e.forceFragmentPrecision?"precision "+e.forceFragmentPrecision+" float;\n\n":li(t),h+=this._getPassDefineString(e.pass),e.pass===Nt)return h+="uniform vec4 uColor;\n",h+=c,e.alphaTest&&(h+="float dAlpha;\n",h+=this._addMap("opacity","opacityPS",e,u),h+=u.alphaTestPS),h+="void main(void)\n{\n",e.alphaTest&&(h+=" getOpacity();\n",h+=" alphaTest(dAlpha);\n"),h+=" gl_FragColor = uColor;\n",{attributes:d,vshader:R,fshader:h+="}\n"};if(2===e.pass)return h+="varying float vDepth;\n",h+=c,h+=u.packDepthPS,e.alphaTest&&(h+="float dAlpha;\n",h+=this._addMap("opacity","opacityPS",e,u),h+=u.alphaTestPS),h+="void main(void)\n{\n",e.alphaTest&&(h+=" getOpacity();\n",h+=" alphaTest(dAlpha);\n"),h+=" gl_FragColor = packFloat(vDepth);\n",{attributes:d,vshader:R,fshader:h+="}\n"};if(s)return{attributes:d,vshader:R,fshader:this._buildShadowPassFragmentCode(h,t,u,e,c)};if(e.customFragmentShader)return{attributes:d,vshader:R,fshader:h+e.customFragmentShader,tag:1};h+=c,h=this._fsAddBaseCode(h,t,u,e),e.detailModes&&(h+=u.detailModesPS);var D=h;h="",e.clearCoat>0&&(h+="#define CLEARCOAT\n",h+="#define CLUSTER_CLEAR_COAT\n"),!1===e.opacityFadesSpecular&&(h+="uniform float material_alphaFade;\n");var O=0,k=[],F=!1,B=!1,N=!1,U=e.lights.some((function(t){return t._shape&&0!==t._shape}));e.clusteredLightingEnabled&&e.clusteredLightingAreaLightsEnabled&&(U=!0),7===t.areaLightLutFormat?(h+="#define AREA_R8_G8_B8_A8_LUTS\n",h+="#define AREA_LUTS_PRECISION lowp\n"):h+="#define AREA_LUTS_PRECISION highp\n",(U||e.clusteredLightingEnabled)&&(h+="#define AREA_LIGHTS\n",h+="uniform AREA_LUTS_PRECISION sampler2D areaLightsLutTex1;\n",h+="uniform AREA_LUTS_PRECISION sampler2D areaLightsLutTex2;\n");for(var z,V=0,G=0;G0?u.cubeMapProjectBoxPS:u.cubeMapProjectNonePS,h+=e.skyboxIntensity?u.envMultiplyPS:u.envConstPS),e.diffuseDetail&&(h+=this._addMap("diffuseDetail","diffuseDetailMapPS",e,u)),h+=this._addMap("diffuse","diffusePS",e,u),(3!==e.blendType||e.alphaTest||e.alphaToCoverage)&&(h+=this._addMap("opacity","opacityPS",e,u)),h+=this._addMap("emissive","emissivePS",e,u,e.emissiveFormat),i&&e.useSpecular||n){e.specularAntialias&&e.normalMap?e.normalizeNormalMap&&a?h+=u.specularAaToksvigPS:h+=u.specularAaToksvigFastPS:h+=u.specularAaNonePS;var Y=e.useMetalness?"metalness":"specular";h+=this._addMap(Y,Y+"PS",e,u),h+=this._addMap("gloss","glossPS",e,u),2===e.fresnelModel&&(h+=u.fresnelSchlickPS)}if(e.clearCoat>0&&(h+=this._addMap("clearCoat","clearCoatPS",e,u),h+=this._addMap("clearCoatGloss","clearCoatGlossPS",e,u),h+=this._addMap("clearCoatNormal","clearCoatNormalPS",e,u)),e.heightMap){if(!e.normalMap){var K=this._getUvSourceExpression("heightMapTransform","heightMapUv",e);e.hasTangents||(z=z.replace(/\$UV/g,K)),h+=z}h+=this._addMap("height","parallaxPS",e,u)}var Z=e.aoMap||e.aoVertexColor;if(Z&&(h+=this._addMap("ao","aoPS",e,u),e.occludeSpecular&&(1===e.occludeSpecular?h+=e.occludeSpecularFloat?u.aoSpecOccSimplePS:u.aoSpecOccConstSimplePS:h+=e.occludeSpecularFloat?u.aoSpecOccPS:u.aoSpecOccConstPS)),"envAtlas"===e.reflectionSource)h+=u.reflectionEnvPS.replace(/\$DECODE/g,this._decodeFunc(e.reflectionEncoding));else if("cubeMap"===e.reflectionSource)h+=e.fixSeams?u.fixCubemapSeamsStretchPS:u.fixCubemapSeamsNonePS,h+=u.reflectionCubePS.replace(/\$DECODE/g,this._decodeFunc(e.reflectionEncoding));else if("sphereMap"===e.reflectionSource){h+=(t.fragmentUniformsCount>16?u.reflectionSpherePS:u.reflectionSphereLowPS).replace(/\$DECODE/g,this._decodeFunc(e.reflectionEncoding))}n&&(e.clearCoat>0&&(h+=u.reflectionCCPS),e.refraction&&(h+=u.refractionPS)),e.clusteredLightingEnabled&&(h+=u.clusteredLightUtilsPS,h+=u.clusteredLightCookiesPS,k[0]=!0,k[4]=!0,N=!0),(O>0||e.clusteredLightingEnabled)&&(F&&(h+=u.shadowCascadesPS),k[0]&&(h+=u.shadowStandardPS),k[4]&&t.webgl2&&(h+=u.shadowStandardGL2PS),B&&(h+=u.shadowVSM_commonPS,k[1]&&(h+=u.shadowVSM8PS),k[2]&&(h+=t.extTextureHalfFloatLinear?u.shadowEVSMPS.replace(/\$/g,"16"):u.shadowEVSMnPS.replace(/\$/g,"16")),k[3]&&(h+=t.extTextureFloatLinear?u.shadowEVSMPS.replace(/\$/g,"32"):u.shadowEVSMnPS.replace(/\$/g,"32"))),t.webgl2||t.extStandardDerivatives||(h+=u.biasConstPS),h+=u.shadowCoordPS+u.shadowCommonPS,N&&(h+=u.shadowCoordPerspZbufferPS)),e.enableGGXSpecular&&(h+="uniform float material_anisotropy;\n"),i&&(h+=u.lightDiffuseLambertPS,(U||e.clusteredLightingEnabled)&&(h+=u.ltc)),h+="\n";var $=!1;e.useSpecular?(h+="#define CLUSTER_SPECULAR\n",e.conserveEnergy&&(h+="#define CLUSTER_CONSERVE_ENERGY\n"),i&&(h+=0===e.shadingModel?u.lightSpecularPhongPS:e.enableGGXSpecular?u.lightSpecularAnisoGGXPS:u.lightSpecularBlinnPS),e.fresnelModel>0?e.conserveEnergy&&!U?h+=u.combineDiffuseSpecularPS:h+=u.combineDiffuseSpecularNoConservePS:n?h+=u.combineDiffuseSpecularOldPS:e.diffuseMap?h+=u.combineDiffuseSpecularNoReflPS:(h+=u.combineDiffuseSpecularNoReflSeparateAmbientPS,$=!0)):h+=u.combineDiffusePS,e.clearCoat>0&&(h+=u.combineClearCoatPS);var Q=!0;if(e.lightMap||e.lightVertexColor){var J=e.dirLightMap&&e.useSpecular?"lightmapDirPS":"lightmapSinglePS";h+=this._addMap("light",J,e,u,e.lightMapFormat),Q=e.lightMapWithoutAmbient}Q&&("ambientSH"===e.ambientSource?h+=u.ambientSHPS:"envAtlas"===e.ambientSource?h+=u.ambientEnvPS.replace(/\$DECODE/g,this._decodeFunc(e.ambientEncoding)):h+=u.ambientConstantPS),e.ambientTint&&!$&&(h+="uniform vec3 material_ambient;\n"),e.alphaTest&&(h+=u.alphaTestPS),e.msdf&&(h+=u.msdfPS),a&&(h+=u.viewDirPS,e.useSpecular&&(h+=e.enableGGXSpecular?u.reflDirAnisoPS:u.reflDirPS));var tt,et=!1,it=!1,nt=!1,st=!1,at=!1;e.clusteredLightingEnabled&&i&&(st=!0,et=!0,it=!0,at=!0,h+=u.floatUnpackingPS,e.clusteredLightingCookiesEnabled&&(h+="\n#define CLUSTER_COOKIES"),e.clusteredLightingShadowsEnabled&&!e.noShadow&&(h+="\n#define CLUSTER_SHADOWS",h+="\n#define CLUSTER_SHADOW_TYPE_"+It[e.clusteredLightingShadowType]),e.clusteredLightingAreaLightsEnabled&&(h+="\n#define CLUSTER_AREALIGHTS"),h+=an.shaderDefines,h+=u.clusteredLightShadowsPS,h+=u.clusteredLightPS),e.twoSidedLighting&&(h+="uniform float twoSidedLightingNegScaleFactor;\n"),h=this._fsAddStartCode(h,t,u,e),a&&(e.hasTangents||!t.extStandardDerivatives||e.fastTbn?e.twoSidedLighting?h+=" dVertexNormalW = gl_FrontFacing ? vNormalW * twoSidedLightingNegScaleFactor : -vNormalW * twoSidedLightingNegScaleFactor;\n":h+=" dVertexNormalW = vNormalW;\n":e.twoSidedLighting?h+=" dVertexNormalW = normalize(gl_FrontFacing ? vNormalW * twoSidedLightingNegScaleFactor : -vNormalW * twoSidedLightingNegScaleFactor);\n":h+=" dVertexNormalW = normalize(vNormalW);\n",(e.heightMap||e.normalMap)&&e.hasTangents&&(e.twoSidedLighting?(h+=" dTangentW = gl_FrontFacing ? vTangentW * twoSidedLightingNegScaleFactor : -vTangentW * twoSidedLightingNegScaleFactor;\n",h+=" dBinormalW = gl_FrontFacing ? vBinormalW * twoSidedLightingNegScaleFactor : -vBinormalW * twoSidedLightingNegScaleFactor;\n"):(h+=" dTangentW = vTangentW;\n",h+=" dBinormalW = vBinormalW;\n")));var rt=!1;3!==e.blendType||e.alphaTest||e.alphaToCoverage?e.heightMap&&e.opacityMap?rt=!0:(h+=" getOpacity();\n",e.alphaTest&&(h+=" alphaTest(dAlpha);\n")):h+=" dAlpha = 1.0;\n";var ot=!1;if(a&&(h+=" getViewDir();\n",(e.heightMap||e.normalMap||e.clearCoatNormalMap||e.enableGGXSpecular)&&(h+=" getTBN();\n"),e.heightMap&&(h+=" getParallax();\n"),rt&&(h+=" getOpacity();\n",e.alphaTest&&(h+=" alphaTest(dAlpha);\n")),h+=" getNormal();\n",e.useSpecular&&(i&&e.enableGGXSpecular&&(h+=" getGlossiness();\n",ot=!0),h+=" getReflDir();\n")),h+=" getAlbedo();\n",e.clearCoat>0&&(h+=" getClearCoat();\n",h+=" getClearCoatGlossiness();\n",h+=" getClearCoatNormal();\n"),(i&&e.useSpecular||n)&&(h+=" getSpecularity();\n",ot||(h+=" getGlossiness();\n"),U&&(h+=" #ifdef AREA_LIGHTS\n",h+=" dSpecularityNoFres = dSpecularity;\n",h+=" #ifdef CLEARCOAT\n",h+=" ccSpecularityNoFres = ccSpecularity;\n",h+=" #endif\n",h+=" #endif\n"),e.fresnelModel>0&&(h+=" getFresnel();\n")),Q&&(h+=" addAmbient();\n",e.separateAmbient&&(h+="\n vec3 dAmbientLight = dDiffuseLight;\n dDiffuseLight = vec3(0);\n ")),e.ambientTint&&!$&&(h+=" dDiffuseLight *= material_ambient;\n"),Z&&!e.occludeDirect&&(h+=" applyAO();\n"),(e.lightMap||e.lightVertexColor)&&(h+=" addLightMap();\n"),i||n){n&&(e.clearCoat>0&&(h+=" addReflectionCC();\n"),h+=" addReflection();\n"),U&&(h+=" ccReflection.rgb *= ccSpecularity;\n",h+=" dReflection.rgb *= dSpecularity;\n",h+=" dSpecularLight *= dSpecularity;\n",h+=" float roughness = max((1.0 - dGlossiness) * (1.0 - dGlossiness), 0.001);\n",h+=" calcLTCLightValues();\n");for(var ht="",lt=0;lt 0.00001) {\n",2===ut&&(tt&&!ct._cookieFalloff||(h+=" dAtten *= getSpotEffect(light"+lt+"_direction, light"+lt+"_innerConeAngle, light"+lt+"_outerConeAngle);\n",st=!0))),h+=0!==V?0===ut?" dAttenD = getLightDiffuse();\n":" dAttenD = get"+ht+"LightDiffuse() * 16.0;\n":" dAtten *= getLightDiffuse();\n",ct.castShadows&&!e.noShadow){var dt=null,ft=void 0;if(1===ct._shadowType?(dt="VSM8",ft="0.0"):2===ct._shadowType?(dt="VSM16",ft="5.54"):3===ct._shadowType?(dt="VSM32",ft=t.textureFloatHighPrecision?"15.0":"5.54"):dt=4===ct._shadowType?"PCF5x5":"PCF3x3",null!==dt)if(1===ut)r="(light"+lt+"_shadowMap, light"+lt+"_shadowParams);\n",ct._normalOffsetBias&&(h+=" normalOffsetPointShadow(light"+lt+"_shadowParams);\n"),h+=" dAtten *= getShadowPoint"+dt+r;else{var pt="light"+lt+"_shadowMatrix",mt="light"+lt+"_shadowParams";h+=this._nonPointShadowMapProjection(t,e.lights[lt],pt,mt,lt),2===ut&&(dt="Spot"+dt),h+=" dAtten *= getShadow"+dt+"(light"+lt+"_shadowMap, light"+lt+"_shadowParams"+(ct._isVsm?", "+ft:"")+");\n"}}0!==V?e.conserveEnergy&&e.useSpecular?h+=" dDiffuseLight += mix((dAttenD * dAtten) * light"+lt+"_color"+(tt?" * dAtten3":"")+", vec3(0), dLTCSpecFres);\n":h+=" dDiffuseLight += (dAttenD * dAtten) * light"+lt+"_color"+(tt?" * dAtten3":"")+";\n":U&&e.conserveEnergy&&e.useSpecular?h+=" dDiffuseLight += mix(dAtten * light"+lt+"_color"+(tt?" * dAtten3":"")+", vec3(0), dSpecularity);\n":h+=" dDiffuseLight += dAtten * light"+lt+"_color"+(tt?" * dAtten3":"")+";\n",0!==V?(e.clearCoat>0&&(h+=" ccSpecularLight += ccLTCSpecFres * get"+ht+"LightSpecularCC() * dAtten * light"+lt+"_color"+(tt?" * dAtten3":"")+";\n"),e.useSpecular&&(h+=" dSpecularLight += dLTCSpecFres * get"+ht+"LightSpecular() * dAtten * light"+lt+"_color"+(tt?" * dAtten3":"")+";\n")):U?(e.clearCoat>0&&(h+=" ccSpecularLight += ccSpecularity * getLightSpecularCC() * dAtten * light"+lt+"_color"+(tt?" * dAtten3":"")+";\n"),e.useSpecular&&(h+=" dSpecularLight += dSpecularity * getLightSpecular() * dAtten * light"+lt+"_color"+(tt?" * dAtten3":"")+";\n")):(e.clearCoat>0&&(h+=" ccSpecularLight += getLightSpecularCC() * dAtten * light"+lt+"_color"+(tt?" * dAtten3":"")+";\n"),e.useSpecular&&(h+=" dSpecularLight += getLightSpecular() * dAtten * light"+lt+"_color"+(tt?" * dAtten3":"")+";\n")),0!==ut&&(h+=" }\n"),h+="\n"}}e.clusteredLightingEnabled&&i&&(it=!0,nt=!0,et=!0,h+=" addClusteredLights();\n"),U&&(e.clearCoat>0&&(h+=" ccSpecularity = 1.0;\n"),e.useSpecular&&(h+=" dSpecularity = vec3(1);\n")),n&&e.refraction&&(h+=" addRefraction();\n")}h+="\n",Z&&(e.occludeDirect&&(h+=" applyAO();\n"),e.occludeSpecular&&(h+=" occludeSpecular();\n")),!1===e.opacityFadesSpecular&&(2!==e.blendType&&4!==e.blendType||(h+="float specLum = dot((dSpecularLight + dReflection.rgb * dReflection.a) * dSpecularity, vec3( 0.2126, 0.7152, 0.0722 ));\n",h+="#ifdef CLEARCOAT\n specLum += dot(ccSpecularLight * ccSpecularity + ccReflection.rgb * ccReflection.a * ccSpecularity, vec3( 0.2126, 0.7152, 0.0722 ));\n#endif\n",h+="dAlpha = clamp(dAlpha + gammaCorrectInput(specLum), 0.0, 1.0);\n"),h+="dAlpha *= material_alphaFade;\n"),h+=u.endPS,2===e.blendType||6===e.blendType||e.alphaToCoverage?h+=u.outputAlphaPS:4===e.blendType?h+=u.outputAlphaPremulPS:h+=u.outputAlphaOpaquePS,e.msdf&&(h+=" gl_FragColor = applyMsdf(gl_FragColor);\n"),h+="\n",h+="}\n",et&&(h=u.lightDirPointPS+h),it&&(h=u.falloffLinearPS+h),nt&&(h=u.falloffInvSquaredPS+h),st&&(h=u.spotPS+h),at&&(h=u.cookiePS+h);var _t="";return h.includes("dReflection")&&(_t+="vec4 dReflection;\n"),h.includes("dTBN")&&(_t+="mat3 dTBN;\n"),h.includes("dAlbedo")&&(_t+="vec3 dAlbedo;\n"),h.includes("dEmission")&&(_t+="vec3 dEmission;\n"),h.includes("dNormalW")&&(_t+="vec3 dNormalW;\n"),h.includes("dVertexNormalW")&&(_t+="vec3 dVertexNormalW;\n"),h.includes("dTangentW")&&(_t+="vec3 dTangentW;\n"),h.includes("dBinormalW")&&(_t+="vec3 dBinormalW;\n"),h.includes("dViewDirW")&&(_t+="vec3 dViewDirW;\n"),h.includes("dReflDirW")&&(_t+="vec3 dReflDirW;\n"),h.includes("dDiffuseLight")&&(_t+="vec3 dDiffuseLight;\n"),h.includes("dSpecularLight")&&(_t+="vec3 dSpecularLight;\n"),h.includes("dLightDirNormW")&&(_t+="vec3 dLightDirNormW;\n"),h.includes("dLightDirW")&&(_t+="vec3 dLightDirW;\n"),h.includes("dLightPosW")&&(_t+="vec3 dLightPosW;\n"),h.includes("dShadowCoord")&&(_t+="vec3 dShadowCoord;\n"),h.includes("dNormalMap")&&(_t+="vec3 dNormalMap;\n"),h.includes("dSpecularity")&&(_t+="vec3 dSpecularity;\n"),h.includes("dSpecularityNoFres")&&(_t+="vec3 dSpecularityNoFres;\n"),h.includes("dUvOffset")&&(_t+="vec2 dUvOffset;\n"),h.includes("dGlossiness")&&(_t+="float dGlossiness;\n"),h.includes("dAlpha")&&(_t+="float dAlpha;\n"),h.includes("dAtten")&&(_t+="float dAtten;\n"),h.includes("dAttenD")&&(_t+="float dAttenD;\n"),h.includes("dAtten3")&&(_t+="vec3 dAtten3;\n"),h.includes("dAo")&&(_t+="float dAo;\n"),h.includes("dMsdf")&&(_t+="vec4 dMsdf;\n"),h.includes("ccReflection")&&(_t+="vec4 ccReflection;\n"),h.includes("ccNormalW")&&(_t+="vec3 ccNormalW;\n"),h.includes("ccReflDirW")&&(_t+="vec3 ccReflDirW;\n"),h.includes("ccSpecularLight")&&(_t+="vec3 ccSpecularLight;\n"),h.includes("ccSpecularity")&&(_t+="float ccSpecularity;\n"),h.includes("ccSpecularityNoFres")&&(_t+="float ccSpecularityNoFres;\n"),h.includes("ccGlossiness")&&(_t+="float ccGlossiness;\n"),{attributes:d,vshader:R,fshader:h=D+_t+h,tag:1}}},ln={begin:di,dummyFragmentCode:ui,end:fi,fogCode:oi,gammaCode:ai,precisionCode:li,skinCode:hi,tonemapCode:ri,versionCode:ci,basic:gi,particle:vi,skybox:yi,standard:hn},cn=2.399963229728653,un=function(t,e,i){var n=e*cn,s=Math.sqrt(e)/Math.sqrt(i);t.x=s*Math.cos(n),t.y=s*Math.sin(n)},dn=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 a=it.lerp(n,s,e/i),r=Math.sqrt(1-a*a),o=cn*e;t.x=Math.cos(o)*r,t.y=a,t.z=Math.sin(o)*r},fn=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)},pn=function(t){switch(t.type){case Ne:return"RGBM";case Ue:return"RGBE";default:switch(t.format){case Zt:case Qt:case $t:case Jt:return"Linear";default:return"Gamma"}}},mn=function(t){switch(t===Ve&&(t=We),t){case Ge:return"Cubemap";case We:return"Equirect";case He:return"Octahedral"}},_n=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,a=65025*t%1,r=16581375*t%1;n-=s/255,s-=a/255,a-=r/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*a)),e[i+3]=Math.min(255,Math.floor(256*r))}},gn=function(t,e,i,n){var s=2*i*Math.PI,a=Math.pow(1-e,1/(n+1)),r=Math.sqrt(1-a*a);t.set(Math.cos(s)*r,Math.sin(s)*r,a).normalize()},vn=function(t,e,i){var n=2*i*Math.PI,s=Math.sqrt(1-e),a=Math.sqrt(e);t.set(Math.cos(n)*a,Math.sin(n)*a,s).normalize()},yn=function(t,e,i,n){var s=2*i*Math.PI,a=Math.sqrt((1-e)/(1+(n*n-1)*e)),r=Math.sqrt(1-a*a);t.set(Math.cos(s)*r,Math.sin(s)*r,a).normalize()},xn=function(t,e){var i=t*e,n=e/(1-t*t+i*i);return n*n*(1/Math.PI)},bn={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}},Sn=function(t,e,i){for(var n=i/t,s=1-Math.log2(e)/11,a=s*s,r=new lt,o=new lt,h=new lt(0,0,1),l=[],c=function(t,e){var i=bn[t];return i&&i[e]||t}(t,e),u=0;u0){var f=xn(Math.min(1,d),a)/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},wn=function(t,e,i){for(var n=i.length,s=Math.min(n,512),a=Math.ceil(n/s),r=new Uint8ClampedArray(s*a*4),o=0,h=0;h>2*o),rect:s,seamPixels:1}),s.y+=s.w,s.z=Math.max(1,Math.floor(.5*s.z)),s.w=Math.max(1,Math.floor(.5*s.w));return s.set(128,384,64,32),Pn(t,n,{numSamples:(null==e?void 0:e.numSamples)||2048,distribution:"lambert",rect:s,seamPixels:1}),n},t.generatePrefilteredAtlas=function(t,e){for(var i=t[0].device,n=(null==e?void 0:e.target)||new Mi(i,{width:512,height:512,format:7,type:Ne,projection:We,addressU:1,addressV:1,mipmaps:!1}),s=new dt(0,0,512,256),a=Rn(n.width,n.height),r=0;r0,t.forceFragmentPrecision=i.forceFragmentPrecision||"",t.chunks=i.chunks||"",t.blendType=i.blendType,t.forceUv1=i.forceUv1,t.separateAmbient=!1,t.screenSpace=n&&0!=(n&Dt),t.skin=n&&0!=(2&n),t.useInstancing=n&&0!=(32&n),t.useMorphPosition=n&&0!=(n&Ot),t.useMorphNormal=n&&0!=(n&kt),t.useMorphTextureBased=n&&0!=(n&Ft),t.nineSlicedMode=i.nineSlicedMode||0,e.clusteredLightingEnabled&&(t.clusteredLightingEnabled=!0,t.clusteredLightingCookiesEnabled=e.lighting.cookiesEnabled,t.clusteredLightingShadowsEnabled=e.lighting.shadowsEnabled,t.clusteredLightingShadowType=e.lighting.shadowType,t.clusteredLightingAreaLightsEnabled=e.lighting.areaLightsEnabled)},e._updateUVOptions=function(t,e,i,n){var s=!1,a=!1,r=!1;for(var o in i&&(s=0!=(4&i),a=0!=(8&i),r=0!=(16&i)),t.vertexColors=!1,this._mapXForms=[],rn)this._updateTexOptions(t,e,o,s,a,r,n);this._mapXForms=null},e._updateMinOptions=function(t,e){t.opacityTint=1!==e.opacity&&3!==e.blendType,t.lights=[]},e._updateMaterialOptions=function(t,e){var i,n=(e.diffuseTint||!e.diffuseMap&&!e.diffuseVertexColor)&&Fn(e.diffuse),s=!!(e.useMetalness||e.specularMap||e.sphereMap||e.cubeMap||(i=e.specular,0!==i.r||0!==i.g||0!==i.b)||e.enableGGXSpecular||e.clearCoat>0),a=s&&!e.useMetalness&&(e.specularTint||!e.specularMap&&!e.specularVertexColor)&&Fn(e.specular),r=!e.emissiveMap||Fn(e.emissive)&&e.emissiveTint,o=1!==e.emissiveIntensity,h=!!e.normalMap&&(e.normalMap.format===Kt||e.normalMap.type===ze);t.opacityTint=1!==e.opacity&&3!==e.blendType?1:0,t.blendMapsWithColors=!0,t.ambientTint=e.ambientTint,t.diffuseTint=n?2:0,t.specularTint=a?2:0,t.metalnessTint=e.useMetalness&&e.metalness<1?1:0,t.glossTint=1,t.emissiveTint=(r?2:0)+(o?1:0),t.alphaToCoverage=e.alphaToCoverage,t.normalizeNormalMap=e.normalizeNormalMap,t.ambientSH=!!e.ambientSH,t.useSpecular=s,t.emissiveFormat=e.emissiveMap?e.emissiveMap.type===Ne?1:e.emissiveMap.format===Jt?2:0:null,t.lightMapFormat=e.lightMap?e.lightMap.type===Ne?1:e.lightMap.format===Jt?2:0:null,t.specularAntialias=e.specularAntialias&&!!e.normalMap&&!!e.normalMap.mipmaps&&!h,t.conserveEnergy=e.conserveEnergy,t.opacityFadesSpecular=e.opacityFadesSpecular,t.alphaFade=e.alphaFade,t.occludeSpecular=e.occludeSpecular,t.occludeSpecularFloat=1!==e.occludeSpecularIntensity,t.occludeDirect=e.occludeDirect,t.shadingModel=e.shadingModel,t.fresnelModel=e.fresnelModel,t.packedNormal=h,t.fastTbn=e.fastTbn,t.cubeMapProjection=e.cubeMapProjection,t.customFragmentShader=e.customFragmentShader,t.refraction=!!e.refraction,t.useMetalness=e.useMetalness,t.enableGGXSpecular=e.enableGGXSpecular,t.msdf=!!e.msdfMap,t.twoSidedLighting=e.twoSidedLighting,t.pixelSnap=e.pixelSnap,t.aoMapUv=e.aoUvSet,t.diffuseDetail=!!e.diffuseMap,t.normalDetail=!!e.normalMap,t.diffuseDetailMode=e.diffuseDetailMode,t.detailModes=!!t.diffuseDetail,t.clearCoat=!!e.clearCoat,t.clearCoatTint=1!==e.clearCoat?1:0,t.clearCoatGlossiness=!!e.clearCoatGlossiness,t.clearCoatGlossTint=1!==e.clearCoatGlossiness?1:0},e._updateEnvOptions=function(t,e,i,n){t.fog=i.useFog?n.fog:"none",t.gamma=i.useGammaTonemap?n.gammaCorrection:0,t.toneMap=i.useGammaTonemap?n.toneMapping:-1,t.useRgbm=i.emissiveMap&&i.emissiveMap.type===Ne||i.lightMap&&i.lightMap.type===Ne,t.fixSeams=!!i.cubeMap&&i.cubeMap.fixCubemapSeams,t.skyboxIntensity=1!==n.skyboxIntensity,t.useCubeMapRotation=!i.cubeMap&&i.useSkybox&&n&&n.skyboxRotation&&!n.skyboxRotation.equals(yt.IDENTITY);var s=0===i.shadingModel;if(i.envAtlas&&!s?(t.reflectionSource="envAtlas",t.reflectionEncoding=i.envAtlas.encoding):i.cubeMap?(t.reflectionSource="cubeMap",t.reflectionEncoding=i.cubeMap.encoding):i.sphereMap?(t.reflectionSource="sphereMap",t.reflectionEncoding=i.sphereMap.encoding):i.useSkybox&&n.envAtlas&&!s?(t.reflectionSource="envAtlas",t.reflectionEncoding=n.envAtlas.encoding):(t.reflectionSource=null,t.reflectionEncoding=null),i.ambientSH&&!s)t.ambientSource="ambientSH",t.ambientEncoding=null;else{var a=i.envAtlas||(i.useSkybox&&n.envAtlas?n.envAtlas:null);a&&!s?(t.ambientSource="envAtlas",t.ambientEncoding=a.encoding):(t.ambientSource="constant",t.ambientEncoding=null)}},e._updateLightOptions=function(t,e,i,n,s){if(t.lightMap=!1,t.lightMapChannel="",t.lightMapUv=0,t.lightMapTransform=0,t.lightMapWithoutAmbient=!1,t.dirLightMap=!1,i&&(t.noShadow=0!=(1&i),0!=(64&i)&&(t.lightMapFormat=1,t.lightMap=!0,t.lightMapChannel="rgb",t.lightMapUv=1,t.lightMapTransform=0,t.lightMapWithoutAmbient=!e.lightMap,t.useRgbm=!0,0!=(i&Lt)&&(t.dirLightMap=!0),0!=(i&Bt)&&(t.lightMapWithoutAmbient=!1))),e.useLighting){var a=[],r=i?i>>16:1;n&&(this._collectLights(0,n[0],a,r),this._collectLights(1,n[1],a,r,s),this._collectLights(2,n[2],a,r,s)),t.lights=a}else t.lights=[];0===t.lights.length&&(t.noShadow=!0)},e._updateTexOptions=function(t,e,i,n,s,a,r){var o=i+"Map",h=i+"VertexColor",l=i+"VertexColorChannel",c=o+"Channel",u=o+"Transform",d=o+"Uv";"light"!==i&&(t[o]=!1,t[c]="",t[u]=0,t[d]=0),t[h]=!1,t[l]="";var f="opacity"===i;if(f&&3===e.blendType&&0===e.alphaTest&&!e.alphaToCoverage)return t;if((!r||f)&&("height"!==i&&e[h]&&a&&(t[h]=e[h],t[l]=e[l],t.vertexColors=!0),e[o])){var p=!0;0!==e[d]||n||(p=!1),1!==e[d]||s||(p=!1),p&&(t[o]=!!e[o],t[u]=this._getMapTransformID(e.getUniform(u),e[d]),t[c]=e[c],t[d]=e[d])}},e._collectLights=function(t,e,i,n,s){for(var a=0;a0&&(this._setParameter("material_clearCoat",this.clearCoat),this._setParameter("material_clearCoatGlossiness",this.clearCoatGlossiness),this._setParameter("material_clearCoatReflectivity",this.clearCoat),this._setParameter("material_clearCoatBumpiness",this.clearCoatBumpiness)),this._setParameter("material_shininess",n("shininess")),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._setParameter("material_refractionIndex",this.refractionIndex)),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")),rn)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")),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.shader=null,this.clearVariants())},i.updateEnvUniforms=function(t,e){var i=this.envAtlas||(this.useSkybox?e.envAtlas:null);i&&(this._setParameter("texture_envAtlas",i),this.useSkybox&&!e.skyboxRotation.equals(yt.IDENTITY)&&e._skyboxRotationMat3&&this._setParameter("cubeMapRotationMatrix",e._skyboxRotationMat3.data)),this._processParameters("_activeLightingParams")},i.updateShader=function(t,e,i,n,s,a){this.updateEnvUniforms(t,e);var r=s>1&&s<=Nt,o=r?hn.optionsContextMin:hn.optionsContext;r?this.shaderOptBuilder.updateMinRef(o,t,e,this,i,n,s,a):this.shaderOptBuilder.updateRef(o,t,e,this,i,n,s,a),this.onUpdateShader&&(o=this.onUpdateShader(o));var h=t.getProgramLibrary();this.shader=h.getProgram("standard",o),i||(this.clearVariants(),this.variants[0]=this.shader),this._dirtyShader=!1},i.destroy=function(){for(var e in this._assetReferences)this._assetReferences[e]._unbind();this._assetReferences=null,this._validator=null,t.prototype.destroy.call(this)},e}(On);jn.TEXTURE_PARAMETERS=Un,jn.CUBEMAP_PARAMETERS=Vn;var qn=function(t,e){Hn[t]=e},Yn=function(t,e,i,n){Object.defineProperty(jn.prototype,t,{get:n||function(){return this["_"+t]},set:i}),Wn[t]={value:e}},Kn=function(t){return t.defaultValue&&t.defaultValue.clone?function(t){var e="_"+t.name,i=t.dirtyShaderFunc||function(){return!0};Yn(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};Yn(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 Zn(t,e,i,n,s,a){rn[t]=i,Kn({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)}}),Kn({name:t+"MapTiling",defaultValue:new ut(1,1)}),Kn({name:t+"MapOffset",defaultValue:new ut(0,0)}),Kn({name:t+"MapRotation",defaultValue:0}),Kn({name:t+"MapUv",defaultValue:e}),i>0&&Kn({name:t+"MapChannel",defaultValue:n||(i>1?"rgb":"g")}),s&&(Kn({name:t+"VertexColor",defaultValue:!1}),i>0&&Kn({name:t+"VertexColorChannel",defaultValue:n||(i>1?"rgb":"g")})),a&&Kn({name:t+"Mode",defaultValue:"mul"});var r=t+"MapTiling",o=t+"MapOffset",h=t+"MapRotation",l=t+"MapTransform";qn(l,(function(t,e,i){var n=t[r],s=t[o],a=t[h];if(1===n.x&&1===n.y&&0===s.x&&0===s.y&&0===a)return null;var c=t._allocUniform(l,(function(){return[{name:"texture_"+l+"0",value:new Float32Array(3)},{name:"texture_"+l+"1",value:new Float32Array(3)}]})),u=Math.cos(a*it.DEG_TO_RAD),d=Math.sin(a*it.DEG_TO_RAD),f=c[0].value;f[0]=u*n.x,f[1]=-d*n.y,f[2]=s.x;var p=c[1].value;return p[0]=d*n.x,p[1]=u*n.y,p[2]=1-n.y-s.y,c}))}function $n(t,e){Kn({name:t,defaultValue:e,getterFunc:function(){return this._dirtyShader=!0,this["_"+t]}}),qn(t,(function(e,i,n){var s=e._allocUniform(t,(function(){return new Float32Array(3)})),a=e[t];return e.useGammaTonemap&&n.gammaCorrection?(s[0]=Math.pow(a.r,2.2),s[1]=Math.pow(a.g,2.2),s[2]=Math.pow(a.b,2.2)):(s[0]=a.r,s[1]=a.g,s[2]=a.b),s}))}function Qn(t,e,i){Kn({name:t,defaultValue:e,dirtyShaderFunc:function(t,e){return(0===t||1===t)!=(0===e||1===e)}}),qn(t,i)}function Jn(t,e){Kn({name:t,defaultValue:null,dirtyShaderFunc:function(t,e){return!!t==!!e}}),qn(t,e)}function ts(t,e){Object.defineProperty(jn.prototype,e,{get:function(){return this[t]},set:function(e){this[t]=e}})}function es(t,e){Kn({name:t,defaultValue:e})}!function(){$n("ambient",new at(.7,.7,.7)),$n("diffuse",new at(1,1,1)),$n("specular",new at(0,0,0)),$n("emissive",new at(0,0,0)),Qn("emissiveIntensity",1),Qn("shininess",25,(function(t,e,i){return 0===t.shadingModel?Math.pow(2,.01*t.shininess*11):.01*t.shininess})),Qn("heightMapFactor",1,(function(t,e,i){return.025*t.heightMapFactor})),Qn("opacity",1),Qn("alphaFade",1),Qn("alphaTest",0),Qn("bumpiness",1),Qn("normalDetailMapBumpiness",1),Qn("reflectivity",1),Qn("occludeSpecularIntensity",1),Qn("refraction",0),Qn("refractionIndex",1/1.5),Qn("metalness",1),Qn("anisotropy",0),Qn("clearCoat",0),Qn("clearCoatGlossiness",1),Qn("clearCoatBumpiness",1),Qn("aoUvSet",0,null),Jn("ambientSH"),Jn("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(),a=n[0].value;a[0]=s.x,a[1]=s.y,a[2]=s.z;var r=t.cubeMapProjectionBox.getMax(),o=n[1].value;return o[0]=r.x,o[1]=r.y,o[2]=r.z,n})),Object.defineProperty(jn.prototype,"chunks",{get:function(){return this._dirtyShader=!0,this._chunks},set:function(t){this._dirtyShader=!0,this._chunks=t}}),es("ambientTint",!1),es("diffuseTint",!1),es("specularTint",!1),es("emissiveTint",!1),es("fastTbn",!1),es("specularAntialias",!1),es("useMetalness",!1),es("enableGGXSpecular",!1),es("occludeDirect",!1),es("normalizeNormalMap",!0),es("conserveEnergy",!0),es("opacityFadesSpecular",!0),es("occludeSpecular",1),es("shadingModel",1),es("fresnelModel",2),es("cubeMapProjection",0),es("customFragmentShader",null),es("forceFragmentPrecision",null),es("useFog",!0),es("useLighting",!0),es("useGammaTonemap",!0),es("useSkybox",!0),es("forceUv1",!1),es("pixelSnap",!1),es("twoSidedLighting",!1),es("nineSlicedMode",void 0),Zn("diffuse",0,3,"",!0),Zn("specular",0,3,"",!0),Zn("emissive",0,3,"",!0),Zn("normal",0,-1,"",!1),Zn("metalness",0,1,"",!0),Zn("gloss",0,1,"",!0),Zn("opacity",0,1,"a",!0),Zn("height",0,1,"",!1),Zn("ao",0,1,"",!0),Zn("light",1,3,"",!0),Zn("msdf",0,3,"",!1),Zn("diffuseDetail",0,3,"",!1,!0),Zn("normalDetail",0,-1,"",!1),Zn("clearCoat",0,1,"",!0),Zn("clearCoatGloss",0,1,"",!0),Zn("clearCoatNormal",0,-1,"",!1),Jn("cubeMap"),Jn("sphereMap"),Jn("envAtlas"),ts("diffuseTint","diffuseMapTint"),ts("specularTint","specularMapTint"),ts("emissiveTint","emissiveMapTint"),ts("aoVertexColor","aoMapVertexColor"),ts("diffuseVertexColor","diffuseMapVertexColor"),ts("specularVertexColor","specularMapVertexColor"),ts("emissiveVertexColor","emissiveMapVertexColor"),ts("metalnessVertexColor","metalnessMapVertexColor"),ts("glossVertexColor","glossMapVertexColor"),ts("opacityVertexColor","opacityMapVertexColor"),ts("lightVertexColor","lightMapVertexColor");var t=[null,null,null,null,null,null];Yn("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 a=t[s]||null;e[s]!==a&&(e[s]=a,i=!0),n=n&&!!e[s]}i&&(n?this.envAtlas=In.generatePrefilteredAtlas(e,{target:this.envAtlas}):this.envAtlas&&(this.envAtlas.destroy(),this.envAtlas=null),this._dirtyShader=!0)}),(function(){return this._prefilteredCubemaps}))}();var is=function(){function t(t){this._device=t,this._cache={},this._generators={},this._isClearingCache=!1,this._precached=!1,this._programsCollection=[],this._defaultStdMatOption={},this._defaultStdMatOptionMin={};var e=new jn;e.shaderOptBuilder.updateRef(this._defaultStdMatOption,t,{},e,null,[],0,null,null),e.shaderOptBuilder.updateMinRef(this._defaultStdMatOptionMin,t,{},e,null,[],3,null,null)}var e=t.prototype;return e.register=function(t,e){this.isRegistered(t)||(this._generators[t]=e)},e.unregister=function(t){this.isRegistered(t)&&delete this._generators[t]},e.isRegistered=function(t){return void 0!==this._generators[t]},e.getProgram=function(t,e){var i=this._generators[t];if(void 0===i)return null;var n=this._device,s=i.generateKey(e),a=this._cache[s];if(!a){var r;e.lights&&(r=e.lights,e.lights=r.map((function(t){var e=t.clone?t.clone():t;return e.key=t.key,e}))),this.storeNewProgram(t,e),e.lights&&(e.lights=r),this._precached&&console.warn("ProgramLibrary#getProgram: Cache miss for shader "+t+" key "+s+" after shaders precaching");var o=i.createShaderDefinition(n,e);a=this._cache[s]=new ni(n,o)}return a},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])}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;e1&&t<=Nt?this._defaultStdMatOptionMin:this._defaultStdMatOption},e.precompile=function(t){if(t)for(var e=new Array(t.length),i=0;ie||n>e){var s=e/Math.max(i,n),a=Math.floor(i*s),r=Math.floor(n*s),o=document.createElement("canvas");return o.width=a,o.height=r,o.getContext("2d").drawImage(t,0,0,i,n,0,0,a,r),o}return t}function ds(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 fs=function(t){function e(e,i){var n;void 0===i&&(i={}),(n=t.call(this)||this).canvas=e,n._enableAutoInstancing=!1,n.autoInstancingMaxObjects=16384,n.defaultFramebuffer=null,n._maxPixelRatio=1,n._width=0,n._height=0,n.updateClientRect(),n.shaders=[],n.buffers=[],n.textures=[],n.targets=[],n.contextLost=!1,n._contextLostHandler=function(t){t.preventDefault(),n.contextLost=!0,n.loseContext(),n.fire("devicelost")},n._contextRestoredHandler=function(){n.restoreContext(),n.contextLost=!1,n.fire("devicerestored")};var a=void 0===i.preferWebGl2||i.preferWebGl2?["webgl2","webgl","experimental-webgl"]:["webgl","experimental-webgl"],r=null;i.stencil=!0;for(var o=0;o0;var _=n.vertexUniformsCount;_-=16,_-=8,_-=1,_-=16,n.boneLimit=Math.floor(_/3),n.boneLimit=Math.min(n.boneLimit,128),"Mali-450 MP"===n.unmaskedRenderer&&(n.boneLimit=34),n._drawCallsPerFrame=0,n._shaderSwitchesPerFrame=0,n._primsPerFrame=[];for(var g=0;g<=6;g++)n._primsPerFrame[g]=0;return n._renderTargetCreationTime=0,n._vram={tex:0,vb:0,ib:0},n._shaderStats={vsCompiled:0,fsCompiled:0,linked:0,materialShaders:0,compileTime:0},n.constantTexSource=n.scope.resolve("source"),n.extTextureFloat?n.webgl2?n.textureFloatRenderable=!!n.extColorBufferFloat:n.textureFloatRenderable=ds(r,r.FLOAT):n.textureFloatRenderable=!1,n.extColorBufferHalfFloat?n.textureHalfFloatRenderable=!!n.extColorBufferHalfFloat:n.extTextureHalfFloat?n.webgl2?n.textureHalfFloatRenderable=!!n.extColorBufferFloat:n.textureHalfFloatRenderable=ds(r,n.extTextureHalfFloat.HALF_FLOAT_OES):n.textureHalfFloatRenderable=!1,n.supportsMorphTargetTexturesCore="highp"===n.maxPrecision&&n.maxVertexTextures>=2,n._textureFloatHighPrecision=void 0,n._textureHalfFloatUpdatable=void 0,n.grabPassAvailable=!0,n.grabPass=new ls(j(n),i.alpha),n.grabPass.create(),Je.init(j(n)),n.areaLightLutFormat=7,n.extTextureHalfFloat&&n.textureHalfFloatUpdatable&&n.extTextureHalfFloatLinear?n.areaLightLutFormat=$t:n.extTextureFloat&&n.extTextureFloatLinear&&(n.areaLightLutFormat=Jt),n}H(e,t);var i=e.prototype;return i.destroy=function(){var t=this.gl;this.grabPass.destroy(),this.webgl2&&this.feedback&&t.deleteTransformFeedback(this.feedback),this.clearShaderCache(),this.clearVertexArrayObjectCache(),this.canvas.removeEventListener("webglcontextlost",this._contextLostHandler,!1),this.canvas.removeEventListener("webglcontextrestored",this._contextRestoredHandler,!1),this._contextLostHandler=null,this._contextRestoredHandler=null,this.scope=null,this.canvas=null,this.gl=null},i.toJSON=function(t){},i.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),a=t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT),r=i.precision>0&&s.precision>0,o=n.precision>0&&a.precision>0;r||(e=o?"mediump":"lowp")}return e},i.initializeExtensions=function(){var t,e=this.gl,i={};e.getSupportedExtensions().forEach((function(t){i[t]=!0}));var n=function(){for(var t=0;t0;){var i=this.textures[0];this.destroyTexture(i),i.dirtyAll()}for(var n,s=Y(this.buffers);!(n=s()).done;){n.value.loseContext()}for(var a,r=Y(this.targets);!(a=r()).done;){a.value.loseContext()}},i.restoreContext=function(){this.initializeExtensions(),this.initializeCapabilities(),this.initializeRenderState(),this.initializeContextCaches();for(var t,e=Y(this.shaders);!(t=e()).done;){var i=t.value;this.compileAndLinkShader(i)}for(var n,s=Y(this.buffers);!(n=s()).done;){n.value.unlock()}this.grabPass.create()},i.updateClientRect=function(){this.clientRect=this.canvas.getBoundingClientRect()},i.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)},i.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)},i.getProgramLibrary=function(){return this.programLib},i.setProgramLibrary=function(t){this.programLib=t},i.setFramebuffer=function(t){this.activeFramebuffer!==t&&(this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,t),this.activeFramebuffer=t)},i._checkFbo=function(){var t=this.gl;switch(t.checkFramebufferStatus(t.FRAMEBUFFER)){case t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:console.error("ERROR: FRAMEBUFFER_INCOMPLETE_ATTACHMENT");break;case t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:console.error("ERROR: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT");break;case t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:console.error("ERROR: FRAMEBUFFER_INCOMPLETE_DIMENSIONS");break;case t.FRAMEBUFFER_UNSUPPORTED:console.error("ERROR: FRAMEBUFFER_UNSUPPORTED");break;case t.FRAMEBUFFER_COMPLETE:}},i.copyRenderTarget=function(t,e,i,n){var s=this.gl;if(!this.webgl2&&n)return!1;if(i)if(e){if(!t._colorBuffer||!e._colorBuffer)return!1;if(t._colorBuffer._format!==e._colorBuffer._format)return!1}else if(!t._colorBuffer)return!1;if(n){if(!t._depthBuffer||!e._depthBuffer)return!1;if(t._depthBuffer._format!==e._depthBuffer._format)return!1}if(this.webgl2&&e){var a=this.renderTarget;this.renderTarget=e,this.updateBegin(),s.bindFramebuffer(s.READ_FRAMEBUFFER,t?t._glFrameBuffer:null),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,e._glFrameBuffer);var r=t?t.width:e.width,o=t?t.height:e.height;s.blitFramebuffer(0,0,r,o,0,0,r,o,(i?s.COLOR_BUFFER_BIT:0)|(n?s.DEPTH_BUFFER_BIT:0),s.NEAREST),this.renderTarget=a,s.bindFramebuffer(s.FRAMEBUFFER,a?a._glFrameBuffer:null)}else{var h=this.getCopyShader();this.constantTexSource.setValue(t._colorBuffer),ii(this,e,h)}return!0},i.initRenderTarget=function(t){if(!t._glFrameBuffer){t._device=this;var e=this.gl;t._glFrameBuffer=e.createFramebuffer(),this.setFramebuffer(t._glFrameBuffer);var i=t._colorBuffer;i&&(i._glTexture||(i._width=Math.min(i.width,this.maxRenderBufferSize),i._height=Math.min(i.height,this.maxRenderBufferSize),this.setTexture(i,0)),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,i._cubemap?e.TEXTURE_CUBE_MAP_POSITIVE_X+t._face:e.TEXTURE_2D,i._glTexture,0));var n=t._depthBuffer;if(n&&this.webgl2)n._glTexture||(n._width=Math.min(n.width,this.maxRenderBufferSize),n._height=Math.min(n.height,this.maxRenderBufferSize),this.setTexture(n,0)),t._stencil?e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,n._cubemap?e.TEXTURE_CUBE_MAP_POSITIVE_X+t._face:e.TEXTURE_2D,t._depthBuffer._glTexture,0):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,n._cubemap?e.TEXTURE_CUBE_MAP_POSITIVE_X+t._face:e.TEXTURE_2D,t._depthBuffer._glTexture,0);else if(t._depth){t._samples>1&&this.webgl2||(t._glDepthBuffer||(t._glDepthBuffer=e.createRenderbuffer()),e.bindRenderbuffer(e.RENDERBUFFER,t._glDepthBuffer),t._stencil?(e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_STENCIL,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.RENDERBUFFER,t._glDepthBuffer)):(e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_COMPONENT16,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t._glDepthBuffer)),e.bindRenderbuffer(e.RENDERBUFFER,null))}this.webgl2&&t._samples>1&&(t._glResolveFrameBuffer=t._glFrameBuffer,t._glFrameBuffer=e.createFramebuffer(),this.setFramebuffer(t._glFrameBuffer),i&&(t._glMsaaColorBuffer||(t._glMsaaColorBuffer=e.createRenderbuffer()),e.bindRenderbuffer(e.RENDERBUFFER,t._glMsaaColorBuffer),e.renderbufferStorageMultisample(e.RENDERBUFFER,t._samples,i._glInternalFormat,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,t._glMsaaColorBuffer)),t._depth&&(t._glMsaaDepthBuffer||(t._glMsaaDepthBuffer=e.createRenderbuffer()),e.bindRenderbuffer(e.RENDERBUFFER,t._glMsaaDepthBuffer),t._stencil?(e.renderbufferStorageMultisample(e.RENDERBUFFER,t._samples,e.DEPTH24_STENCIL8,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.RENDERBUFFER,t._glMsaaDepthBuffer)):(e.renderbufferStorageMultisample(e.RENDERBUFFER,t._samples,e.DEPTH_COMPONENT32F,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t._glMsaaDepthBuffer)))),this.targets.push(t)}},i.getCopyShader=function(){return this._copyShader||(this._copyShader=_i(this,si.fullscreenQuadVS,si.outputTex2DPS,"outputTex2D")),this._copyShader},i.updateBegin=function(){if(this.boundVao=null,this._tempEnableSafariTextureUnitWorkaround)for(var t=0;t1&&e.autoResolve&&e.resolve()}},i.initializeTexture=function(t){var e,i=this.gl;switch(t._glTexture=i.createTexture(),t._glTarget=t._cubemap?i.TEXTURE_CUBE_MAP:t._volume?i.TEXTURE_3D:i.TEXTURE_2D,t._format){case 0:t._glFormat=i.ALPHA,t._glInternalFormat=i.ALPHA,t._glPixelType=i.UNSIGNED_BYTE;break;case 1:t._glFormat=i.LUMINANCE,t._glInternalFormat=i.LUMINANCE,t._glPixelType=i.UNSIGNED_BYTE;break;case 2:t._glFormat=i.LUMINANCE_ALPHA,t._glInternalFormat=i.LUMINANCE_ALPHA,t._glPixelType=i.UNSIGNED_BYTE;break;case 3:t._glFormat=i.RGB,t._glInternalFormat=i.RGB,t._glPixelType=i.UNSIGNED_SHORT_5_6_5;break;case 4:t._glFormat=i.RGBA,t._glInternalFormat=i.RGBA,t._glPixelType=i.UNSIGNED_SHORT_5_5_5_1;break;case 5:t._glFormat=i.RGBA,t._glInternalFormat=i.RGBA,t._glPixelType=i.UNSIGNED_SHORT_4_4_4_4;break;case 6:t._glFormat=i.RGB,t._glInternalFormat=this.webgl2?i.RGB8:i.RGB,t._glPixelType=i.UNSIGNED_BYTE;break;case 7:t._glFormat=i.RGBA,t._glInternalFormat=this.webgl2?i.RGBA8:i.RGBA,t._glPixelType=i.UNSIGNED_BYTE;break;case 8:e=this.extCompressedTextureS3TC,t._glFormat=i.RGB,t._glInternalFormat=e.COMPRESSED_RGB_S3TC_DXT1_EXT;break;case 9:e=this.extCompressedTextureS3TC,t._glFormat=i.RGBA,t._glInternalFormat=e.COMPRESSED_RGBA_S3TC_DXT3_EXT;break;case Kt:e=this.extCompressedTextureS3TC,t._glFormat=i.RGBA,t._glInternalFormat=e.COMPRESSED_RGBA_S3TC_DXT5_EXT;break;case ie:e=this.extCompressedTextureETC1,t._glFormat=i.RGB,t._glInternalFormat=e.COMPRESSED_RGB_ETC1_WEBGL;break;case ne:e=this.extCompressedTexturePVRTC,t._glFormat=i.RGB,t._glInternalFormat=e.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;break;case se:e=this.extCompressedTexturePVRTC,t._glFormat=i.RGBA,t._glInternalFormat=e.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;break;case 26:e=this.extCompressedTexturePVRTC,t._glFormat=i.RGB,t._glInternalFormat=e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;break;case 27:e=this.extCompressedTexturePVRTC,t._glFormat=i.RGBA,t._glInternalFormat=e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;break;case 22:e=this.extCompressedTextureETC,t._glFormat=i.RGB,t._glInternalFormat=e.COMPRESSED_RGB8_ETC2;break;case 23:e=this.extCompressedTextureETC,t._glFormat=i.RGBA,t._glInternalFormat=e.COMPRESSED_RGBA8_ETC2_EAC;break;case 28:e=this.extCompressedTextureASTC,t._glFormat=i.RGBA,t._glInternalFormat=e.COMPRESSED_RGBA_ASTC_4x4_KHR;break;case 29:e=this.extCompressedTextureATC,t._glFormat=i.RGB,t._glInternalFormat=e.COMPRESSED_RGB_ATC_WEBGL;break;case 30:e=this.extCompressedTextureATC,t._glFormat=i.RGBA,t._glInternalFormat=e.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL;break;case Zt:e=this.extTextureHalfFloat,t._glFormat=i.RGB,this.webgl2?(t._glInternalFormat=i.RGB16F,t._glPixelType=i.HALF_FLOAT):(t._glInternalFormat=i.RGB,t._glPixelType=e.HALF_FLOAT_OES);break;case $t:e=this.extTextureHalfFloat,t._glFormat=i.RGBA,this.webgl2?(t._glInternalFormat=i.RGBA16F,t._glPixelType=i.HALF_FLOAT):(t._glInternalFormat=i.RGBA,t._glPixelType=e.HALF_FLOAT_OES);break;case Qt:t._glFormat=i.RGB,this.webgl2?t._glInternalFormat=i.RGB32F:t._glInternalFormat=i.RGB,t._glPixelType=i.FLOAT;break;case Jt:t._glFormat=i.RGBA,this.webgl2?t._glInternalFormat=i.RGBA32F:t._glInternalFormat=i.RGBA,t._glPixelType=i.FLOAT;break;case 15:t._glFormat=i.RED,t._glInternalFormat=i.R32F,t._glPixelType=i.FLOAT;break;case te:this.webgl2?(t._glFormat=i.DEPTH_COMPONENT,t._glInternalFormat=i.DEPTH_COMPONENT32F,t._glPixelType=i.FLOAT):(t._glFormat=i.DEPTH_COMPONENT,t._glInternalFormat=i.DEPTH_COMPONENT,t._glPixelType=i.UNSIGNED_SHORT);break;case ee:t._glFormat=i.DEPTH_STENCIL,t._glInternalFormat=i.DEPTH24_STENCIL8,t._glPixelType=i.UNSIGNED_INT_24_8;break;case 18:t._glFormat=i.RGB,t._glInternalFormat=i.R11F_G11F_B10F,t._glPixelType=i.UNSIGNED_INT_10F_11F_11F_REV;break;case 19:t._glFormat=i.RGB,t._glInternalFormat=i.SRGB8,t._glPixelType=i.UNSIGNED_BYTE;break;case 20:t._glFormat=i.RGBA,t._glInternalFormat=i.SRGB8_ALPHA8,t._glPixelType=i.UNSIGNED_BYTE}this.textures.push(t)},i.destroyTexture=function(t){if(t._glTexture){var e=this.textures.indexOf(t);-1!==e&&this.textures.splice(e,1),this.scope.removeValue(t);for(var i=0;ithis.maxCubeMapSize||o.height>this.maxCubeMapSize)&&(o=us(o,this.maxCubeMapSize),0===s&&(t._width=o.width,t._height=o.height)),this.setUnpackFlipY(!1),this.setUnpackPremultiplyAlpha(t._premultiplyAlpha),e.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+r,s,t._glInternalFormat,t._glFormat,t._glPixelType,o)}}else for(n=1/Math.pow(2,s),r=0;r<6;r++)if(t._levelsUpdated[0][r]){var h=i[r];t._compressed?e.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+r,s,t._glInternalFormat,Math.max(t._width*n,1),Math.max(t._height*n,1),0,h):(this.setUnpackFlipY(!1),this.setUnpackPremultiplyAlpha(t._premultiplyAlpha),e.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+r,s,t._glInternalFormat,Math.max(t._width*n,1),Math.max(t._height*n,1),0,t._glFormat,t._glPixelType,h))}}else t._volume?(n=1/Math.pow(2,s),t._compressed?e.compressedTexImage3D(e.TEXTURE_3D,s,t._glInternalFormat,Math.max(t._width*n,1),Math.max(t._height*n,1),Math.max(t._depth*n,1),0,i):(this.setUnpackFlipY(!1),this.setUnpackPremultiplyAlpha(t._premultiplyAlpha),e.texImage3D(e.TEXTURE_3D,s,t._glInternalFormat,Math.max(t._width*n,1),Math.max(t._height*n,1),Math.max(t._depth*n,1),0,t._glFormat,t._glPixelType,i))):(this._isBrowserInterface(i)?(i instanceof HTMLImageElement&&(i.width>this.maxTextureSize||i.height>this.maxTextureSize)&&(i=us(i,this.maxTextureSize),0===s&&(t._width=i.width,t._height=i.height)),this.setUnpackFlipY(t._flipY),this.setUnpackPremultiplyAlpha(t._premultiplyAlpha),e.texImage2D(e.TEXTURE_2D,s,t._glInternalFormat,t._glFormat,t._glPixelType,i)):(n=1/Math.pow(2,s),t._compressed?e.compressedTexImage2D(e.TEXTURE_2D,s,t._glInternalFormat,Math.max(Math.floor(t._width*n),1),Math.max(Math.floor(t._height*n),1),0,i):(this.setUnpackFlipY(!1),this.setUnpackPremultiplyAlpha(t._premultiplyAlpha),e.texImage2D(e.TEXTURE_2D,s,t._glInternalFormat,Math.max(t._width*n,1),Math.max(t._height*n,1),0,t._glFormat,t._glPixelType,i))),t._mipmapsUploaded=0!==s);s++}else s++;if(t._needsUpload)if(t._cubemap)for(var l=0;l<6;l++)t._levelsUpdated[0][l]=!1;else t._levelsUpdated[0]=!1;!t._compressed&&t._mipmaps&&t._needsMipmapsUpload&&(t.pot||this.webgl2)&&1===t._levels.length&&(e.generateMipmap(t._glTarget),t._mipmapsUploaded=!0),t._gpuSize&&(this._vram.tex-=t._gpuSize),t._gpuSize=t.gpuSize,this._vram.tex+=t._gpuSize}},i.activeTexture=function(t){this.textureUnit!==t&&(this.gl.activeTexture(this.gl.TEXTURE0+t),this.textureUnit=t)},i.bindTexture=function(t){var e=t._glTarget,i=t._glTexture,n=this.textureUnit,s=this.targetToSlot[e];this.textureUnits[n][s]!==i&&(this.gl.bindTexture(e,i),this.textureUnits[n][s]=i)},i.bindTextureOnUnit=function(t,e){var i=t._glTarget,n=t._glTexture,s=this.targetToSlot[i];this.textureUnits[e][s]!==n&&(this.activeTexture(e),this.gl.bindTexture(i,n),this.textureUnits[e][s]=n)},i.setTextureParameters=function(t){var e=this.gl,i=t._parameterFlags,n=t._glTarget;if(1&i){var s=t._minFilter;(!t.pot&&!this.webgl2||!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.webgl2?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.webgl2?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.webgl2&&e.texParameteri(n,e.TEXTURE_WRAP_R,this.glAddress[t._addressW]),32&i&&this.webgl2&&e.texParameteri(n,e.TEXTURE_COMPARE_MODE,t._compareOnRead?e.COMPARE_REF_TO_TEXTURE:e.NONE),64&i&&this.webgl2&&e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,this.glComparison[t._compareFunc]),128&i){var a=this.extTextureFilterAnisotropic;a&&e.texParameterf(n,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.max(1,Math.min(Math.round(t._anisotropy),this.maxAnisotropy)))}},i.setTexture=function(t,e){(t._glTexture||this.initializeTexture(t),t._parameterFlags>0||t._needsUpload||t._needsMipmapsUpload||t===this.grabPass.texture)?(this.activeTexture(e),this.bindTexture(t),t._parameterFlags&&(this.setTextureParameters(t),t._parameterFlags=0),t===this.grabPass.texture&&this.grabPass.prepareTexture()||!t._needsUpload&&!t._needsMipmapsUpload||(this.uploadTexture(t),t._needsUpload=!1,t._needsMipmapsUpload=!1)):this.bindTextureOnUnit(t,e)},i.createVertexArray=function(t){var e,i,n=t.length>1;if(n){e="";for(var s=0;s0?u.drawElementsInstanced(b,S,T,A,e):u.drawElements(b,S,T,A)}else{var M=t.base;e>0?u.drawArraysInstanced(b,M,S,e):u.drawArrays(b,M,S)}this.webgl2&&this.transformFeedbackBuffer&&(u.endTransformFeedback(),u.bindBufferBase(u.TRANSFORM_FEEDBACK_BUFFER,0,null)),this._drawCallsPerFrame++}},i.clear=function(t){var e=this.defaultClearOptions,i=null==(t=t||e).flags?e.flags:t.flags;if(0!==i){var n=this.gl;if(1&i){var s=null==t.color?e.color:t.color;this.setClearColor(s[0],s[1],s[2],s[3])}if(2&i){var a=null==t.depth?e.depth:t.depth;this.setClearDepth(a),this.depthWrite||n.depthMask(!0)}if(4&i){var r=null==t.stencil?e.stencil:t.stencil;this.setClearStencil(r)}n.clear(this.glClearFlag[i]),2&i&&(this.depthWrite||n.depthMask(!1))}},i.readPixels=function(t,e,i,n,s){var a=this.gl;a.readPixels(t,e,i,n,a.RGBA,a.UNSIGNED_BYTE,s)},i.setClearDepth=function(t){t!==this.clearDepth&&(this.gl.clearDepth(t),this.clearDepth=t)},i.setClearColor=function(t,e,i,n){t===this.clearRed&&e===this.clearGreen&&i===this.clearBlue&&n===this.clearAlpha||(this.gl.clearColor(t,e,i,n),this.clearRed=t,this.clearGreen=e,this.clearBlue=i,this.clearAlpha=n)},i.setClearStencil=function(t){t!==this.clearStencil&&(this.gl.clearStencil(t),this.clearStencil=t)},i.setRenderTarget=function(t){this.renderTarget=t},i.getRenderTarget=function(){return this.renderTarget},i.getDepthTest=function(){return this.depthTest},i.setDepthTest=function(t){if(this.depthTest!==t){var e=this.gl;t?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this.depthTest=t}},i.setDepthFunc=function(t){this.depthFunc!==t&&(this.gl.depthFunc(this.glComparison[t]),this.depthFunc=t)},i.getDepthWrite=function(){return this.depthWrite},i.setDepthWrite=function(t){this.depthWrite!==t&&(this.gl.depthMask(t),this.depthWrite=t)},i.setColorWrite=function(t,e,i,n){this.writeRed===t&&this.writeGreen===e&&this.writeBlue===i&&this.writeAlpha===n||(this.gl.colorMask(t,e,i,n),this.writeRed=t,this.writeGreen=e,this.writeBlue=i,this.writeAlpha=n)},i.setAlphaToCoverage=function(t){this.webgl2&&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))},i.setTransformFeedbackBuffer=function(t){if(this.transformFeedbackBuffer!==t&&(this.transformFeedbackBuffer=t,this.webgl2)){var e=this.gl;t?(this.feedback||(this.feedback=e.createTransformFeedback()),e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,this.feedback)):e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,null)}},i.setRaster=function(t){this.raster!==t&&(this.raster=t,this.webgl2&&(t?this.gl.disable(this.gl.RASTERIZER_DISCARD):this.gl.enable(this.gl.RASTERIZER_DISCARD)))},i.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))},i.setDepthBiasValues=function(t,e){this.gl.polygonOffset(e,t)},i.getBlending=function(){return this.blending},i.setBlending=function(t){if(this.blending!==t){var e=this.gl;t?e.enable(e.BLEND):e.disable(e.BLEND),this.blending=t}},i.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}},i.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)},i.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}},i.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}},i.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)},i.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)},i.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)},i.setBlendFunction=function(t,e){(this.blendSrc!==t||this.blendDst!==e||this.separateAlphaBlend)&&(this.gl.blendFunc(this.glBlendFunction[t],this.glBlendFunction[e]),this.blendSrc=t,this.blendDst=e,this.separateAlphaBlend=!1)},i.setBlendFunctionSeparate=function(t,e,i,n){this.blendSrc===t&&this.blendDst===e&&this.blendSrcAlpha===i&&this.blendDstAlpha===n&&this.separateAlphaBlend||(this.gl.blendFuncSeparate(this.glBlendFunction[t],this.glBlendFunction[e],this.glBlendFunction[i],this.glBlendFunction[n]),this.blendSrc=t,this.blendDst=e,this.blendSrcAlpha=i,this.blendDstAlpha=n,this.separateAlphaBlend=!0)},i.setBlendEquation=function(t){(this.blendEquation!==t||this.separateAlphaEquation)&&(this.gl.blendEquation(this.glBlendEquation[t]),this.blendEquation=t,this.separateAlphaEquation=!1)},i.setBlendEquationSeparate=function(t,e){this.blendEquation===t&&this.blendAlphaEquation===e&&this.separateAlphaEquation||(this.gl.blendEquationSeparate(this.glBlendEquation[t],this.glBlendEquation[e]),this.blendEquation=t,this.blendAlphaEquation=e,this.separateAlphaEquation=!0)},i.setCullMode=function(t){if(this.cullMode!==t){if(0===t)this.gl.disable(this.gl.CULL_FACE);else{0===this.cullMode&&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}},i.getCullMode=function(){return this.cullMode},i.setIndexBuffer=function(t){this.indexBuffer=t},i.setVertexBuffer=function(t){t&&this.vertexBuffers.push(t)},i.compileShaderSource=function(t,e){var i=this.gl,n=e?this.vertexShaderCache[t]:this.fragmentShaderCache[t];return n||(n=i.createShader(e?i.VERTEX_SHADER:i.FRAGMENT_SHADER),i.shaderSource(n,t),i.compileShader(n),e?this.vertexShaderCache[t]=n:this.fragmentShaderCache[t]=n),n},i.compileAndLinkShader=function(t){var e=t.definition,i=this.compileShaderSource(e.vshader,!0),n=this.compileShaderSource(e.fshader,!1),s=this.gl,a=s.createProgram();s.attachShader(a,i),s.attachShader(a,n);var r=e.attributes;if(this.webgl2&&e.useTransformFeedback){var o=[];for(var h in r)r.hasOwnProperty(h)&&o.push("out_"+h);s.transformFeedbackVaryings(a,o,s.INTERLEAVED_ATTRIBS)}var l={};for(var c in r)if(r.hasOwnProperty(c)){var u=r[c],d=Ke[u];l[d]=c,s.bindAttribLocation(a,d,c)}s.linkProgram(a),t._glVertexShader=i,t._glFragmentShader=n,t._glProgram=a},i.createShader=function(t){this.compileAndLinkShader(t),this.shaders.push(t)},i.destroyShader=function(t){var e=this.shaders.indexOf(t);-1!==e&&this.shaders.splice(e,1),t._glProgram&&(this.gl.deleteProgram(t._glProgram),t._glProgram=null,this.removeShaderFromCache(t))},i._isShaderCompiled=function(t,e,i,n){var s=this.gl;if(!s.getShaderParameter(e,s.COMPILE_STATUS)){var a=s.getShaderInfoLog(e),r=this._processError(i,a),o=r[0];r[1];var h="Failed to compile "+n+" shader:\n\n"+a+"\n"+o;return console.error(h),!1}return!0},i._processError=function(t,e){if(!t)return"";var i=t.split("\n"),n={},s="",a=0,r=i.length;if(e&&e.startsWith("ERROR:")){var o=e.match(/^ERROR:\s([0-9]+):([0-9]+):\s*(.+)/);o&&(n.message=o[3],n.line=parseInt(o[2],10),a=Math.max(0,n.line-6),r=Math.min(i.length,n.line+5))}for(var h=a;he)if(ArrayBuffer.isView(t))t=t.subarray(0,e),i.set(t);else for(var n=0;nthis.vertexBuffer.numVertices&&(i=this.vertexBuffer.numVertices);var s=n.numComponents;if(this.vertexBuffer.getFormat().interleaved)for(var a=0,r=0;ri*s){var o=i*s;if(ArrayBuffer.isView(e))e=e.subarray(0,o),n.array.set(e);else for(var h=0;h0){var b=g.array[g.index+x];if(u[b]=!0,e=m.array[m.index],i=m.array[m.index+1],n=m.array[m.index+2],s=c[b],(a=l[b]).x>e&&(a.x=e),a.y>i&&(a.y=i),a.z>n&&(a.z=n),s.xS&&(a.x=S),a.y>w&&(a.y=w),a.z>T&&(a.z=T),s.x0&&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,a){void 0===s&&(s=6),void 0===a&&(a=!1),this._initGeometryData();var r=n||e.length/i;this._geometryData._changeVertexCount(r,t),this._geometryData.vertexStreamsUpdated=!0,this._geometryData.vertexStreamDictionary[t]=new Hs(e,i,s,a)},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 Ls(this.vertexBuffer).readData(t,e));return i},i.setPositions=function(t,e,i){void 0===e&&(e=Ws.DEFAULT_COMPONENTS_POSITION),this.setVertexStream(ae,t,e,i,6,!1)},i.setNormals=function(t,e,i){void 0===e&&(e=Ws.DEFAULT_COMPONENTS_NORMAL),this.setVertexStream(re,t,e,i,6,!1)},i.setUvs=function(t,e,i,n){void 0===i&&(i=Ws.DEFAULT_COMPONENTS_UV),this.setVertexStream(ue+t,e,i,n,6,!1)},i.setColors=function(t,e,i){void 0===e&&(e=Ws.DEFAULT_COMPONENTS_COLORS),this.setVertexStream(ce,t,e,i,6,!1)},i.setColors32=function(t,e){this.setVertexStream(ce,t,Ws.DEFAULT_COMPONENTS_COLORS,e,1,!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(ae,t)},i.getNormals=function(t){return this.getVertexStream(re,t)},i.getUvs=function(t,e){return this.getVertexStream(ue+t,e)},i.getColors=function(t){return this.getVertexStream(ce,t)},i.getIndices=function(t){var e=0;if(this._geometryData&&this._geometryData.indices){var i=this._geometryData.indices;e=this._geometryData.indexCount,ArrayBuffer.isView(t)?t.set(i):(t.length=0,t.push(i))}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.POSITION;i&&3===i.componentCount&&this._aabb.compute(i.data,this._geometryData.vertexCount)}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 Je(this.device,e,t)},i._updateVertexBuffer=function(){if(!this.vertexBuffer){var t=this._geometryData.maxVertices,e=this._buildVertexFormat(t);this.vertexBuffer=new $e(this.device,e,t,this._geometryData.verticesUsage)}var i=new Ls(this.vertexBuffer),n=this._geometryData.vertexCount;for(var s in this._geometryData.vertexStreamDictionary){var a=this._geometryData.vertexStreamDictionary[s];i.writeData(s,a.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 vs(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=[];if(this.indexBuffer.length>0&&this.indexBuffer[0]){for(var i=[[0,1],[1,2],[2,0]],n=this.primitive[0].base,s=this.primitive[0].count,a=this.indexBuffer[0],r=new Ye[a.format](a.storage),o={},h=n;hu?u<<16|c:c<<16|u;void 0===o[d]&&(o[d]=0,e.push(c,u))}t=a.format}else{for(var f=0;f65535?2:1}var p=new vs(this.vertexBuffer.device,t,e.length);new Ye[p.format](p.storage).set(e),p.unlock(),this.primitive[1]={type:1,base:0,count:e.length,indexed:!0},this.indexBuffer[1]=p},G(e,[{key:"aabb",get:function(){return this._aabb},set:function(t){this._aabb=t}}]),e}(Us),js=4/64,qs=.875,Ys=[];function Ks(t,e){for(var i=e.length/3,n=t.length/3,s=new lt,a=new lt,r=new lt,o=new lt,h=new lt,l=new lt,c=[],u=0;u0)for(var v=0;v<=n;v++)for(var y=0;y<=s;y++){var x=y/s*2*Math.PI-Math.PI,b=Math.sin(x),S=Math.cos(x);u.set(b*t,-i/2,S*t),c.set(b*e,i/2,S*e),o.lerp(u,c,v/n),h.sub2(c,u).normalize(),d.set(S,0,-b),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=v/n;m.push(w,1-T);var A=T;if(T=w,w=(w=A)*qs+js,T=T*qs+js,w/=3,_.push(w,1-T),v0)for(var dt=0;dt1&&g.push(r,r+dt,r+dt-1)}if(r+=s,e>0)for(var yt=0;yt1&&g.push(r,r+yt-1,r+yt)}}return{positions:f,normals:p,uvs:m,uvs1:_,indices:g}}function ta(t,e){var i=e&&(e.radius||e.baseRadius);i=void 0!==i?i:.5;var n=e&&void 0!==e.height?e.height:1,s=e&&void 0!==e.heightSegments?e.heightSegments:5,a=e&&void 0!==e.capSegments?e.capSegments:20,r=!(!e||void 0===e.calculateTangents)&&e.calculateTangents,o=Js(i,i,n,s,a,!1);return r&&(o.tangents=Zs(o.positions,o.normals,o.uvs,o.indices)),$s(t,o.positions,o)}function ea(t,e){var i=e&&void 0!==e.radius?e.radius:.3,n=e&&void 0!==e.height?e.height:1,s=e&&void 0!==e.heightSegments?e.heightSegments:1,a=e&&void 0!==e.sides?e.sides:20,r=!(!e||void 0===e.calculateTangents)&&e.calculateTangents,o=Js(i,i,n-2*i,s,a,!0);return r&&(o.tangents=Zs(o.positions,o.normals,o.uvs,o.indices)),$s(t,o.positions,o)}function ia(t,e){var i=e&&void 0!==e.baseRadius?e.baseRadius:.5,n=e&&void 0!==e.peakRadius?e.peakRadius:0,s=e&&void 0!==e.height?e.height:1,a=e&&void 0!==e.heightSegments?e.heightSegments:5,r=e&&void 0!==e.capSegments?e.capSegments:18,o=!(!e||void 0===e.calculateTangents)&&e.calculateTangents,h=Js(i,n,s,a,r,!1);return o&&(h.tangents=Zs(h.positions,h.normals,h.uvs,h.indices)),$s(t,h.positions,h)}function na(t,e){for(var i=e&&void 0!==e.radius?e.radius:.5,n=e&&void 0!==e.latitudeBands?e.latitudeBands:16,s=e&&void 0!==e.longitudeBands?e.longitudeBands:16,a=!(!e||void 0===e.calculateTangents)&&e.calculateTangents,r=[],o=[],h=[],l=[],c=0;c<=n;c++)for(var u=c*Math.PI/n,d=Math.sin(u),f=Math.cos(u),p=0;p<=s;p++){var m=2*p*Math.PI/s-Math.PI/2,_=Math.sin(m),g=Math.cos(m)*d,v=f,y=_*d,x=1-p/s,b=1-c/n;r.push(g*i,v*i,y*i),o.push(g,v,y),h.push(x,1-b)}for(var S=0;S=0;i--)this.matrices[i].mulAffine2(ca,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>16},set:function(t){var e=65535&this._shaderDefs;this._shaderDefs=e|t<<16,this._shader[0]=null,this._shader[1]=null}},{key:"instancingCount",get:function(){return this.instancingData?this.instancingData.count:0},set:function(t){this.instancingData&&(this.instancingData.count=t)}}]),t}();function Sa(t,e,i,n){return(15&t)<<27|(3===e?1:0)<<26|(i?1:0)<<25|(33554431&n)<<0}function wa(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=0?1:-1}var Ia=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 a=new la(n,t,e,i,s);return this._batchGroups[n]=a,a}},e.removeGroup=function(t){if(this._batchGroups[t]){for(var e=[],i=0;i=0&&(n._obj[t].splice(s,1),this.markGroupDirty(e))}},e._extractRender=function(t,e,i,n){if(t.render){if(t.render.isStatic){for(var s=this.scene.drawCalls,a=t.render.meshInstances,r=0;r=0&&e.push(a[o])}else e=n[t.render.batchGroupId]=e.concat(t.render.meshInstances);t.render.removeFromLayers()}return e},e._extractModel=function(t,e,i,n){if(t.model&&t.model.model){if(t.model.isStatic){for(var s=this.scene.drawCalls,a=t.model.meshInstances,r=0;r=0&&e.push(a[o])}else e=n[t.model.batchGroupId]=e.concat(t.model.meshInstances);t.model.removeModelFromLayers()}return 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;i0;){u[d]=[p[0]],f=[];var _=p[0].material,g=p[0].layer,v=p[0]._shaderDefs,y=p[0].parameters,x=p[0].stencilFront,b=p[0]._staticLightList,S=p[0].mesh.vertexBuffer.getNumVertices(),w=p[0].drawOrder;h.copy(p[0].aabb);var T=Ra(p[0]),A=p[0].mesh.vertexBuffer.format.batchingHash,M=p[0].mesh.primitive[0].indexed;c=null;for(var C=1;C=r){f=f.concat(p.slice(C));break}if(_!==E.material||g!==E.layer||A!==E.mesh.vertexBuffer.format.batchingHash||M!==E.mesh.primitive[0].indexed||v!==E._shaderDefs||S+E.mesh.vertexBuffer.getNumVertices()>o)m(E);else if(l.copy(h),l.add(E.aabb),l.halfExtents.x>a||l.halfExtents.y>a||l.halfExtents.z>a)m(E);else if(!x||(s=E.stencilFront)&&x.func===s.func&&x.zpass===s.zpass)if(T===Ra(E))if(Ta(y,E.parameters)){var P=E._staticLightList;if(b&&P){if(!Aa(b,P)){m(E);continue}}else if(b||P){m(E);continue}n&&c&&c.intersects(E.aabb)&&E.drawOrder!==w?m(E):(h.add(E.aabb),S+=E.mesh.vertexBuffer.getNumVertices(),u[d].push(E))}else m(E);else m(E);else m(E)}d++,p=f}return u},e.collectBatchedMeshData=function(t,e){for(var i=null,n=0,s=0,a=null,r=0;r=3)if(s===ae)for(var A=0;A0&&a.setIndices(b),a.update(4,!1),e&&((p=p.clone()).chunks.transformVS=this.transformVS,p.chunks.skinTexVS=this.skinTexVS,p.chunks.skinConstVS=this.skinConstVS,p.update());var R=new ba(a,p,this.rootNode);R.castShadow=h.origMeshInstances[0].castShadow,R.parameters=h.origMeshInstances[0].parameters,R.isStatic=h.origMeshInstances[0].isStatic,R.layer=h.origMeshInstances[0].layer,R._staticLightList=h.origMeshInstances[0]._staticLightList,R._shaderDefs=h.origMeshInstances[0]._shaderDefs,R.cull=h.origMeshInstances[0].cull;var I=this._batchGroups[i];if(I&&I._ui&&(R.cull=!1),e){for(var L=[],D=0;D0&&this.generate(this._dirtyGroups);for(var t=0;t0){if(!(n1){e.copy(t[1].min),i.copy(t[1].max);for(var n=2;n1?this.shaderCube:this.shader2d,a=this.device;n>1&&this.initInvViewProjMatrices(),this.blitTextureId.setValue(e.cookie);for(var r=0;r1){var o=za.z/3,h=this.lightTextureAtlas.cubeSlotsOffsets[r];za.x+=o*h.x,za.y+=o*h.y,za.z=o,za.w=o,this.invViewProjId.setValue(t._invViewProjMatrices[r].data)}za.mulScalar(i.colorBuffer.width),ii(a,i,s,za)}}},G(t,[{key:"shader2d",get:function(){return this.getShader("blitShader2d","\n varying vec2 uv0;\n uniform sampler2D blitTexture;\n void main(void) {\n gl_FragColor = texture2D(blitTexture, uv0);\n }")}},{key:"shaderCube",get:function(){return this.getShader("blitShaderCube","\n varying vec2 uv0;\n uniform samplerCube blitTexture;\n uniform mat4 invViewProj;\n void main(void) {\n vec4 projPos = vec4(uv0 * 2.0 - 1.0, 0.5, 1.0);\n vec4 worldPos = invViewProj * projPos;\n gl_FragColor = textureCube(blitTexture, worldPos.xyz);\n }")}}]),t}();Va._invViewProjMatrices=null;var Ga=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;e0)for(var s=4/this.shadowAtlasResolution,a=new dt(s,s,-2*s,-2*s),r=0,o=0;os&&(s=r)}return Ka.min=n,Ka.max=s,Ka}function $a(t,e){return Math.exp(-t*t/(2*e*e))}var Qa=new At,Ja=new vt,tr=new vt,er=new Float32Array(2),ir={x:1,y:1,z:0,w:0},nr={r:1,g:2,b:3,a:4},sr=new lt,ar=new vt;function rr(t){var e=t.material,i=t.skinInstance?10:0,n=0;if(e.opacityMap){var s=e.opacityMapChannel;s&&(n=nr[s])}return i+n}var or,hr,lr,cr,ur,dr,fr,pr,mr,_r,gr,vr,yr,xr=function(){function t(t,e){this.device=t.device,this.forwardRenderer=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=[si.blurVSMPS,"#define GAUSS\n"+si.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.shadowMapCache=new qa}var e=t.prototype;return e.destroy=function(){this.shadowMapCache.destroy(),this.shadowMapCache=null},t.createShadowCamera=function(t,e,i,n){var s=$i.create("ShadowCamera",i,n);return s.clearColor=e>=1&&e<=3?new at(0,0,0,0):new at(1,1,1,1),s.clearDepthBuffer=!0,s.clearStencilBuffer=!1,s},t.setShadowCameraSettings=function(t,e,i,n,s){var a=4===i||0===i&&e.webgl2;1!==n||s||(a=!1),t.clearColorBuffer=!a},e.cullShadowCasters=function(t,e,i){for(var n=0,s=t.length,a=0;ap&&(p=_)}var g=o.right,v=o.up,y=o.forward,x=.25*t._shadowResolution/p,b=Math.ceil(sr.dot(v)*x)/x,S=Math.ceil(sr.dot(g)*x)/x,w=v.mulScalar(b),T=g.mulScalar(S),A=sr.dot(y),M=y.mulScalar(A);sr.add2(w,T).add(M),o.setPosition(sr),o.translateLocal(0,0,1e6),r.nearClip=0,r.farClip=2e6,r.orthoHeight=p,this.forwardRenderer.updateCameraFrustum(r),this.cullShadowCasters(e,a.visibleCasters,r);for(var C=!0,E=a.visibleCasters,P=0;P1&&this.applyVsmBlur(e,i),this.restoreRenderState(n)}},e.getVsmBlurShader=function(t,e,i){var n=(t?this.blurPackedVsmShader:this.blurVsmShader)[e][i];if(!n){this.blurVsmWeights[i]=function(t){t>25&&(t=25);for(var e=(t-1)/6,i=.5*(t-1),n=new Array(t),s=0,a=0;aC&&(C=b),S>E&&(E=S),w>P&&(P=w);$[c=6*o]=T,$[c+1]=A,$[c+2]=M,$[c+3]=C,$[c+4]=E,$[c+5]=P}for(l=0;l=R.x&&$[c+1]<=I.y&&$[c+4]>=R.y&&$[c+2]<=I.z&&$[c+5]>=R.z&&(K[o]|=z,L=!0);if(L){for(k={},o=0;o<_;o++)r=3*o+x,k[F=K[o]]||(k[F]=[]),(B=k[F]).push(p[r]),B.push(p[r+1]),B.push(p[r+2]);for(F in k){B=k[F];var J=new vs(e,D.format,B.length,D.usage);for((2===J.bytesPerIndex?new Uint16Array(J.lock()):new Uint32Array(J.lock())).set(B),J.unlock(),T=Number.MAX_VALUE,A=Number.MAX_VALUE,M=Number.MAX_VALUE,C=-Number.MAX_VALUE,E=-Number.MAX_VALUE,P=-Number.MAX_VALUE,o=0;oC&&(C=b),S>E&&(E=S),w>P&&(P=w);X.set(T,A,M),j.set(C,E,P);var tt=new At;tt.setMinMax(X,j);var et=new Xs(e);et.vertexBuffer=O,et.indexBuffer[0]=J,et.primitive[0].type=4,et.primitive[0].base=0,et.primitive[0].count=B.length,et.primitive[0].indexed=!0,et.aabb=tt;var it=new ba(et,u.material,u.node);for(it.isStatic=u.isStatic,it.visible=u.visible,it.layer=u.layer,it.castShadow=u.castShadow,it._receiveShadow=u._receiveShadow,it.cull=u.cull,it.pick=u.pick,it.mask=u.mask,it.parameters=u.parameters,it._shaderDefs=u._shaderDefs,it._staticSource=u,u._staticLightList?it._staticLightList=u._staticLightList:it._staticLightList=[],o=0;o0&&(this._instancedDrawCalls++,t.setVertexBuffer(ur.vertexBuffer),t.draw(i.primitive[n],ur.count),ur.vertexBuffer===Xr))return this._removedByInstancing+=ur.count,e.instancingData=null,ur.count-1}else dr=e.node.worldTransform,this.modelMatrixId.setValue(dr.data),s&&(fr=e.node.normalMatrix,e.node._dirtyNormal&&(dr.invertTo3x3(fr),fr.transpose(),e.node._dirtyNormal=!1),this.normalMatrixId.setValue(fr.data)),t.draw(i.primitive[n]);return 0},e.drawInstance2=function(t,e,i,n){if(ur=e.instancingData){if(ur.count>0&&(this._instancedDrawCalls++,t.draw(i.primitive[n],ur.count,!0),ur.vertexBuffer===Xr))return this._removedByInstancing+=ur.count,e.instancingData=null,ur.count-1}else t.draw(i.primitive[n],void 0,!0);return 0},e.renderShadows=function(t,e){var i=this.device;i.grabPassAvailable=!1;for(var n=0;n0&&n.cull<3){i.flipFaces&&(a*=-1),e&&(a*=-1);var r=i.node.worldTransform;r.getX(zr),r.getY(Vr),r.getZ(Gr),zr.cross(zr,Vr),zr.dot(Gr)<0&&(a*=-1)}s=a<0?2===n.cull?1:2:n.cull}if(this.device.setCullMode(s),0===s&&0===n.cull){var o=i.node.worldTransform;o.getX(zr),o.getY(Vr),o.getZ(Gr),zr.cross(zr,Vr),zr.dot(Gr)<0?this.twoSidedLightingNegScaleFactorId.setValue(-1):this.twoSidedLightingNegScaleFactorId.setValue(1)}},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;i0&&this.renderShadows(o.directionalLights,d.camera),l.enabled&&t.subLayerEnabled[h]){if(d&&(d.frameBegin(o.renderTarget),o.firstCameraUse&&d.onPreRender&&d.onPreRender()),!c&&l.onPreRenderOpaque?l.onPreRenderOpaque(u):c&&l.onPreRenderTransparent&&l.onPreRenderTransparent(u),l._preRenderCalledForCameras&1<=0&&r._shaderVersion!==i&&(r.updateShader!==On.prototype.updateShader&&(r.clearVariants(),r.shader=null),r._shaderVersion=i)}this.passThrough||(this._dirty=!0)},e.removeMeshInstanceFromArray=function(t,e){for(var i=-1,n=0,s=e.length,a=0;a=0)break}i>=0&&e.splice(i,n)},e.removeMeshInstances=function(t,e){for(var i=this.opaqueMeshInstances,n=this.transparentMeshInstances,s=this.shadowCasters,a=0;a=0&&s.splice(o,1)}}this._dirty=!0},e.clearMeshInstances=function(t){(0!==this.opaqueMeshInstances.length||0!==this.transparentMeshInstances.length||!t&&0!==this.shadowCasters.length)&&(this.opaqueMeshInstances.length=0,this.transparentMeshInstances.length=0,t||(this.shadowCasters.length=0),this.passThrough||(this._dirty=!0))},e.addLight=function(t){var e=t.light;this._lightsSet.has(e)||(this._lightsSet.add(e),0!==e.type&&this._clusteredLightsSet.add(e),this._lights.push(e),this._dirtyLights=!0,this._generateLightHash())},e.removeLight=function(t){var e=t.light;this._lightsSet.has(e)&&(this._lightsSet.delete(e),0!==e.type&&this._clusteredLightsSet.delete(e),this._lights.splice(this._lights.indexOf(e),1),this._dirtyLights=!0,this._generateLightHash())},e.clearLights=function(){this._lightsSet.clear(),this._clusteredLightsSet.clear(),this._lights.length=0,this._dirtyLights=!0},e.addShadowCasters=function(t){for(var e=this.shadowCasters,i=0;i=0&&e.splice(n,1)}this._dirtyLights=!0},e._generateLightHash=function(){if(this._lights.length>0){this._lights.sort($r);for(var t="",e="",i=0;i=0||(this.cameras.push(t),this._dirtyCameras=!0)},e.removeCamera=function(t){var e=this.cameras.indexOf(t);e>=0&&(this.cameras.splice(e,1),this._dirtyCameras=!0,this.instances.delete(e))},e.clearCameras=function(){this.cameras.length=0,this._dirtyCameras=!0},e._calculateSortDistances=function(t,e,i,n){for(var s=0;s=0&&!this.directionalLightsSet.has(s)){this.directionalLightsSet.add(s),this.directionalLights.push(s);var r=i.indexOf(s);this.directionalLightsIndices.push(r)}}},t}(),ao=function(){function t(){this.shadowCastersSet=new Set,this.shadowCastersList=[]}var e=t.prototype;return e.clearShadowCasters=function(){this.shadowCastersSet.clear(),this.shadowCastersList.length=0},e.addShadowCasters=function(t){for(var e=0;e1&&this.cameras.sort((function(t,e){return t.priority-e.priority}));for(var m=[],_=0,g=0;g0&&v.layers.indexOf(T.id)>=0){m.push(T),S||T.id!==v.disablePostEffectsLayer||(S=!0,b&&(b.triggerPostprocess=!0));var A=T.cameras.indexOf(v);A>=0&&(b=this.addRenderAction(this._renderActions,_,T,w,A,y,S),_++,y=!1)}}x<_&&(this._renderActions[x].collectDirectionalLights(m,this._splitLights[0],this._lights),b.lastCameraUse=!0),!S&&b&&(b.triggerPostprocess=!0),v.renderTarget&&v.postEffectsEnabled&&this.propagateRenderTarget(x-1,v)}this._renderActions.length=_,t&&this.allocateLightClusters()}return(2&i||4&i)&&this._logRenderActions(),i},i.updateShadowCasters=function(){for(var t=this._lights.length,e=0;e=0;u--)if(t[u].camera===l&&t[u].renderTarget===h){c=!0;break}var d=a||!c,f=!!d&&l.clearColorBuffer,p=!!d&&l.clearDepthBuffer,m=!!d&&l.clearStencilBuffer;return f|=i.clearColorBuffer,p|=i.clearDepthBuffer,m|=i.clearStencilBuffer,r&&l.postEffectsEnabled&&(h=null),o.reset(),o.triggerPostprocess=!1,o.layerIndex=n,o.cameraIndex=s,o.camera=l,o.renderTarget=h,o.clearColor=f,o.clearDepth=p,o.clearStencil=m,o.firstCameraUse=a,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 a=null==n?void 0:n.camera.camera;if(a&&(!e.camera.rect.equals(a.rect)||!e.camera.scissorRect.equals(a.scissorRect)))break;n.renderTarget=e.renderTarget}}},i._logRenderActions=function(){},i._isLayerAdded=function(t){return this.layerList.indexOf(t)>=0},i._isSublayerAdded=function(t,e){for(var i=0;i=0;)this.layerList.splice(e,1),this.subLayerList.splice(e,1),this.subLayerEnabled.splice(e,1),e=this.layerList.indexOf(t),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,this.fire("remove",t);var i=this.layerList.length;this._updateOpaqueOrder(0,i-1),this._updateTransparentOrder(0,i-1)},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._dirty=!0,this._dirtyLights=!0,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._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,this.fire("add",t)}},i.removeOpaque=function(t){for(var e=0,i=this.layerList.length;e=1?(r[0]=Math.pow(e,2.2)*s,r[1]=Math.pow(i,2.2)*s,r[2]=Math.pow(n,2.2)*s):(r[0]=Math.pow(a[0],2.2),r[1]=Math.pow(a[1],2.2),r[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.updateShadow=function(){2!==this.shadowUpdateMode&&(this.shadowUpdateMode=1)},e.layersDirty=function(){var t;null!=(t=this._scene)&&t.layers&&(this._scene.layers._dirtyLights=!0)},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|po[this._cookieChannel.charAt(0)]<<18|(this._cookieTransform?1:0)<<12|this._shape<<10|this.numCascades-1<<8;3===this._cookieChannel.length&&(t|=po[this._cookieChannel.charAt(1)]<<16,t|=po[this._cookieChannel.charAt(2)]<<14),t!==this.key&&null!==this._scene&&this.layersDirty(),this.key=t},G(t,[{key:"numCascades",get:function(){return this.cascades.length},set:function(t){this.cascades&&this.numCascades==t||(this.cascades=mo[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:"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.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:"shadowType",get:function(){return this._shadowType},set:function(t){if(this._shadowType!==t){var e=this.device;1===this._type&&(t=0),4!==t||e.webgl2||(t=0),3!==t||e.textureFloatRenderable||(t=2),2!==t||e.textureHalfFloatRenderable||(t=1),this._isVsm=t>=1&&t<=3,this._isPcf=4===t||0===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))}},{key:"outerConeAngle",get:function(){return this._outerConeAngle},set:function(t){this._outerConeAngle!==t&&(this._outerConeAngle=t,this._outerConeAngleCos=Math.cos(t*Math.PI/180))}},{key:"intensity",get:function(){return this._intensity},set:function(t){this._intensity!==t&&(this._intensity=t,this._updateFinalColor())}},{key:"cookieMatrix",get:function(){return this._cookieMatrix||(this._cookieMatrix=new vt),this._cookieMatrix}},{key:"atlasViewport",get:function(){return this._atlasViewport||(this._atlasViewport=new dt(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;n0){var n=i.bakeArea;un(bo,t,e),bo.mulScalar(.5*n),i._node.rotateLocal(bo.x,0,bo.y)}i._node.getWorldTransform();var s=this.scene.gammaCorrection?2.2:1,a=Math.pow(this.intensity,s);i.intensity=Math.pow(a/e,1/s)},G(e,[{key:"numVirtualLights",get:function(){return 0===this.light.type?this.light.bakeNumSamples:1}}]),e}(xo),wo=new qi,To=function(){function t(t,e,i){this.material=e,this.layer=i,this.positions=[],this.colors=[],this.mesh=new Xs(t),this.meshInstance=null}var e=t.prototype;return e.addLines=function(t,e){for(var i=this.positions,n=t.length,s=0;s0&&(this.mesh.setPositions(this.positions),this.mesh.setColors(this.colors),this.mesh.update(1,!1),this.meshInstance||(wo.worldTransform=vt.IDENTITY,wo._dirtyWorld=wo._dirtyNormal=!1,this.meshInstance=new ba(this.mesh,this.material,wo),this.meshInstance.cull=!1,this.layer.addMeshInstances([this.meshInstance],!0)),this.meshInstance.visible=!0)},e.onPostRender=function(){this.positions.length=0,this.colors.length=0,this.meshInstance.visible=!1},t}(),Ao=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 To(this.device,t,e),this.map.set(t,i)),i},e.onPreRender=function(){this.map.forEach((function(t){t.onPreRender()}))},e.onPostRender=function(){this.map.forEach((function(t){t.onPostRender()}))},t}(),Mo=[],Co=function(){function t(t,e){this.device=t,this.quadMesh=null,this.textureShader=null,this.depthTextureShader=null,this.cubeLocalPos=null,this.cubeWorldPos=null,this.usedGraphNodes=[],this.freeGraphNodes=[],this.batchesMap=new Map,this.allBatches=new Set,this._materialDepth=null,this._materialNoDepth=null,this.layerMeshInstances=new Map,e.on("prerender",this.onPreRender,this),e.on("postrender",this.onPostRender,this)}var e=t.prototype;return e.createMaterial=function(t){var e=new oa;return e.vertexColors=!0,e.blend=!0,e.blendType=2,e.depthTest=t,e.update(),e},e.getBatch=function(t,e){var i=this.batchesMap.get(t);i||(i=new Ao(this.device),this.batchesMap.set(t,i)),this.allBatches.add(i);var n=e?this.materialDepth:this.materialNoDepth;return i.getBatch(n,t)},t.getTextureVS=function(){return"\n attribute vec2 aPosition;\n uniform mat4 matrix_model;\n varying vec2 uv0;\n void main(void) {\n gl_Position = matrix_model * vec4(aPosition, 0, 1);\n uv0 = aPosition.xy + 0.5;\n }\n "},e.getTextureShader=function(){if(!this.textureShader){var e={attributes:{aPosition:ae},vshader:t.getTextureVS(),fshader:"\n precision lowp float;\n varying vec2 uv0;\n uniform sampler2D colorMap;\n void main (void) {\n gl_FragColor = vec4(texture2D(colorMap, uv0).xyz, 1);\n }\n "};this.textureShader=new ni(this.device,e)}return this.textureShader},e.getDepthTextureShader=function(){if(!this.depthTextureShader){var e=this.device.webgl2?"#define GL2":"",i={attributes:{aPosition:ae},vshader:t.getTextureVS(),fshader:"\n precision "+this.device.precision+" float;\n "+e+"\n "+si.screenDepthPS+"\n varying vec2 uv0;\n void main() {\n float depth = getLinearScreenDepth(uv0) * camera_params.x;\n gl_FragColor = vec4(vec3(depth), 1.0);\n }\n "};this.depthTextureShader=new ni(this.device,i)}return this.depthTextureShader},e.getQuadMesh=function(){return this.quadMesh||(this.quadMesh=new Xs(this.device),this.quadMesh.setPositions([-.5,-.5,0,.5,-.5,0,-.5,.5,0,.5,.5,0]),this.quadMesh.update(5)),this.quadMesh},e.drawMesh=function(t,e,i,n,s){if(!n){var a=this.getGraphNode(e);(n=new ba(i,t,a)).cull=!1}var r=this.layerMeshInstances.get(s);r||(r=[],this.layerMeshInstances.set(s,r)),r.push(n)},e.drawWireAlignedBox=function(t,e,i,n,s){Mo.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(Mo,i),Mo.length=0},e.drawWireSphere=function(t,e,i,n,s,a){for(var r=2*Math.PI/n,o=0,h=0;h0?this.freeGraphNodes.pop():new qi,this.usedGraphNodes.push(e),e.worldTransform=t,e._dirtyWorld=e._dirtyNormal=!1,e},e.onPreRender=function(){this.allBatches.forEach((function(t){t.onPreRender()})),this.layerMeshInstances.forEach((function(t,e){e.addMeshInstances(t,!0)}))},e.onPostRender=function(){this.allBatches.forEach((function(t){t.onPostRender()})),this.allBatches.clear(),this.layerMeshInstances.forEach((function(t,e){e.removeMeshInstances(t,!0),t.length=0}));var t=this.freeGraphNodes;this.freeGraphNodes=this.usedGraphNodes,this.usedGraphNodes=t},G(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}(),Eo=function(){function t(){}return t.createTexture=function(t,e,i){var n=new Mi(t,{width:i,height:i,format:e,addressU:1,addressV:1,type:Be,magFilter:1,minFilter:0,anisotropy:1});return n.name="AreaLightLUT",n},t.setUniforms=function(t,e,i){t.scope.resolve("areaLightsLutTex1").setValue(e),t.scope.resolve("areaLightsLutTex2").setValue(i)},t.createPlaceholder=function(e){var i=t.createTexture(e,7,2);i.lock().fill(0),i.unlock(),t.setUniforms(e,i,i)},t.set=function(e,i){function n(e,i,n){var s=t.createTexture(e,n,64);return s.lock().set(i),s.unlock(),s.upload(),s}function s(t,e,i){for(var n=t.length,s=new Float32Array(n),a=0;a=P)&&this.calcSpawnPosition(i,n,s,a,M);var O=R>0&&R0&&(1===u.emitterShape?(Do.copy(Oo).mulScalar(2).sub(lt.ONE).normalize(),Bo.add(Do.mulScalar(u.initialVelocity))):Bo.add(lt.FORWARD.mulScalar(u.initialVelocity))),Fo.x+=(No.x-Fo.x)*Oo.x,Fo.y+=(No.y-Fo.y)*Oo.y,Fo.z+=(No.z-Fo.z)*Oo.z,_+=(g-_)*Oo.y,L=(L+1e4*C%1*(v-L))*Po,D=1e3*C%1*(x-y),u.meshInstance.node&&(u.localSpace?(Bo.x/=Qr.x,Bo.y/=Qr.y,Bo.z/=Qr.z):Ro.transformPoint(Bo,Bo)),u.localSpace?(Io.transformPoint(Fo,Fo),Bo.add(Fo).add(zo)):(Bo.add(Fo.mul(Qr)),Bo.add(zo.mul(Qr))),Wo.copy(Bo),Vo.copy(ko).add(Bo.mulScalar(r)),Go.copy(Vo),i[4*M]=Go.x,i[4*M+1]=Go.y,i[4*M+2]=Go.z,i[4*M+3]+=_*r,u.wrap&&u.wrapBounds&&(u.localSpace||Go.sub(a),Go.x=qo(Go.x,u.wrapBounds.x)-.5*u.wrapBounds.x,Go.y=qo(Go.y,u.wrapBounds.y)-.5*u.wrapBounds.y,Go.z=qo(Go.z,u.wrapBounds.z)-.5*u.wrapBounds.z,u.localSpace||Go.add(a)),u.sort>0&&(1===u.sort?(Ho.copy(Go).sub(S),u.particleDistance[M]=-(Ho.x*Ho.x+Ho.y*Ho.y+Ho.z*Ho.z)):2===u.sort?u.particleDistance[M]=R:3===u.sort&&(u.particleDistance[M]=-R))),o?R<0&&(i[4*M+3+2*u.numParticlesPot*4]=-1):(R>=P&&(R-=Math.max(P,(u.numParticles-1)*E),i[4*M+3+2*u.numParticlesPot*4]=u.loop?1:-1),R<0&&u.loop&&(i[4*M+3+2*u.numParticlesPot*4]=1)),i[4*M+3+2*u.numParticlesPot*4]<0&&(O=!1),i[4*M+3+4*u.numParticlesPot]=R;for(var k=0;k0&&u.camera){for(var V=u.useMesh?6:4,G=u.particleDistance,W=0;We.maxTextureSize&&(this.numParticles=e.maxTextureSize),mh("rate",1),mh("rate2",this.rate),mh("lifetime",50),mh("emitterExtents",new lt(0,0,0)),mh("emitterExtentsInner",new lt(0,0,0)),mh("emitterRadius",0),mh("emitterRadiusInner",0),mh("emitterShape",0),mh("initialVelocity",1),mh("wrap",!1),mh("localSpace",!1),mh("screenSpace",!1),mh("wrapBounds",null),mh("colorMap",t.DEFAULT_PARAM_TEXTURE),mh("normalMap",null),mh("loop",!0),mh("preWarm",!1),mh("sort",0),mh("mode",0),mh("scene",null),mh("lighting",!1),mh("halfLambert",!1),mh("intensity",1),mh("stretch",0),mh("alignToMotion",!1),mh("depthSoftening",0),mh("mesh",null),mh("particleNormal",new lt(0,1,0)),mh("orientation",0),mh("depthWrite",!1),mh("noFog",!1),mh("blendType",2),mh("node",null),mh("startAngle",0),mh("startAngle2",this.startAngle),mh("animTilesX",1),mh("animTilesY",1),mh("animStartFrame",0),mh("animNumFrames",1),mh("animNumAnimations",1),mh("animIndex",0),mh("randomizeAnimIndex",!1),mh("animSpeed",1),mh("animLoop",!0),this._gpuUpdater=new Jo(this,n),this._cpuUpdater=new Ko(this),this.constantLightCube=n.scope.resolve("lightCube[0]"),this.emitterPosUniform=new Float32Array(3),this.wrapBoundsUniform=new Float32Array(3),this.emitterScaleUniform=new Float32Array([1,1,1]),mh("colorGraph",hh),mh("colorGraph2",this.colorGraph),mh("scaleGraph",rh),mh("scaleGraph2",this.scaleGraph),mh("alphaGraph",rh),mh("alphaGraph2",this.alphaGraph),mh("localVelocityGraph",oh),mh("localVelocityGraph2",this.localVelocityGraph),mh("velocityGraph",oh),mh("velocityGraph2",this.velocityGraph),mh("rotationSpeedGraph",ah),mh("rotationSpeedGraph2",this.rotationSpeedGraph),mh("radialSpeedGraph",ah),mh("radialSpeedGraph2",this.radialSpeedGraph),this.lightCube=new Float32Array(18),this.lightCubeDir=new Array(6),this.lightCubeDir[0]=new lt(-1,0,0),this.lightCubeDir[1]=new lt(1,0,0),this.lightCubeDir[2]=new lt(0,-1,0),this.lightCubeDir[3]=new lt(0,1,0),this.lightCubeDir[4]=new lt(0,0,-1),this.lightCubeDir[5]=new lt(0,0,1),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=!1,this.pack8=!0,this.localBounds=new At,this.worldBoundsNoTrail=new At,this.worldBoundsTrail=[new At,new At],this.worldBounds=new At,this.worldBoundsSize=new lt,this.prevWorldBoundsSize=new lt,this.prevWorldBoundsCenter=new lt,this.prevEmitterExtents=this.emitterExtents,this.prevEmitterRadius=this.emitterRadius,this.worldBoundsMul=new lt,this.worldBoundsAdd=new lt,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()}t.staticInit=function(e){if(!t.DEFAULT_PARAM_TEXTURE){for(var i=16,n=new Float32Array(1024),s=0;s=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?vt.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,a=Number.MAX_VALUE,r=-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],g=[0,0],v=[0,0],y=0;y0||e.maxVertexTextures<=1||e.fragmentUniformsCount<64||e.forceCpuParticles||!e.extTextureFloat,this._destroyResources(),this.pack8=(this.pack8||!e.textureFloatRenderable)&&!this.useCpu,lh=this.useCpu||this.pack8?4:2,this.useMesh=!1,this.mesh)&&(this.numParticles*this.mesh.vertexBuffer.numVertices>65535||(this.useMesh=!0));this.numParticlesPot=it.nextPowerOfTwo(this.numParticles),this.rebuildGraphs(),this.calculateLocalBounds(),this.resetWorldBounds(),this.node&&(this.worldBounds.setFromTransformedAabb(this.localBounds,this.localSpace?vt.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 i=0;i=1&&(this.animTilesX>1||this.animTilesY>1)&&(this.colorMap&&this.colorMap!==t.DEFAULT_PARAM_TEXTURE||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;i0&&t.setParameter("softening",1/(this.depthSoftening*this.depthSoftening*100)),this.stretch>0&&(t.cull=0),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?vt.IDENTITY:this.node.getWorldTransform()).transformVector(this.particleNormal).normalize();var n=new lt(1,0,0);1===Math.abs(n.dot(i))&&n.set(0,0,1);var s=(new lt).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:be,components:4,type:6},{semantic:Se,components:4,type:6},{semantic:we,components:4,type:6},{semantic:Te,components:1,type:6},{semantic:Ae,components:this.useMesh?4:2,type:6}],s=new Je(this.graphicsDevice,n);this.vertexBuffer=new $e(this.graphicsDevice,s,e,1),this.indexBuffer=new vs(this.graphicsDevice,1,i)}else{var a=[{semantic:be,components:4,type:6}];this.useMesh&&a.push({semantic:Se,components:2,type:6});var r=new Je(this.graphicsDevice,a);this.vertexBuffer=new $e(this.graphicsDevice,r,e,1),this.indexBuffer=new vs(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;uthis.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()},t}();xh.DEFAULT_PARAM_TEXTURE=null;var bh=function(t){function e(i,n){var s;return(s=t.call(this)||this).device=n||zs().graphicsDevice,s._targets=i,s.device.supportsMorphTargetTexturesCore&&(s.device.extTextureHalfFloat&&s.device.textureHalfFloatRenderable?s._renderTextureFormat=e.FORMAT_HALF_FLOAT:s.device.extTextureFloat&&s.device.textureFloatRenderable&&(s._renderTextureFormat=e.FORMAT_FLOAT),s.device.extTextureHalfFloat&&s.device.textureHalfFloatUpdatable?s._textureFormat=e.FORMAT_HALF_FLOAT:s.device.extTextureFloat&&(s._textureFormat=e.FORMAT_FLOAT),void 0!==s._renderTextureFormat&&void 0!==s._textureFormat&&(s._useTextureMorph=!0)),s._init(),s._updateMorphFlags(),s._calculateAabb(),s}H(e,t);var i=e.prototype;return i._init=function(){if(this._useTextureMorph&&(this._useTextureMorph=this._initTextureBased()),!this._useTextureMorph)for(var t=0;tf)return!1;this.morphTextureWidth=p,this.morphTextureHeight=m;var _=!1,g=3,v=wi.float2Half;this._textureFormat===e.FORMAT_HALF_FLOAT&&(_=!0,g=4);for(var y=this.morphTextureWidth*this.morphTextureHeight*g,x=_?new Uint16Array(y):new Float32Array(y),b=0;b0&&(e+="varying vec2 uv0;\nuniform highp float morphFactor["+t+"];\n");for(var i=0;i=this.maxSubmitCount&&(s(a,r),a=0,r=!0))}(a>0||0===o&&!this.zeroTextures)&&s(a,r)},e._updateTextureMorph=function(){this.device,(this._activeTargets.length>0||!this.zeroTextures)&&(this._updateTextureRenderTarget(this.rtPositions,"texturePositions"),this._updateTextureRenderTarget(this.rtNormals,"textureNormals"),this.zeroTextures=0===this._activeTargets.length)},e._updateVertexMorph=function(){for(var t=this.maxSubmitCount,e=0;e1e-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 a=this.morph.maxActiveTargets;this._activeTargets.length>a&&(this._activeTargets.sort((function(t,e){return t.absWeight=0},i.getModels=function(t){return this._models},G(e,[{key:"clusteredLightingEnabled",get:function(){return this._clusteredLightingEnabled},set:function(t){!this._clusteredLightingEnabled||t?this._clusteredLightingEnabled=t:console.error("Turning off enabled clustered lighting is not currently supported")}},{key:"lighting",get:function(){return this._lightingParams}},{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:"toneMapping",get:function(){return this._toneMapping},set:function(t){t!==this._toneMapping&&(this._toneMapping=t,this.updateShaders=!0)}},{key:"skybox",get:function(){return this._skyboxCubeMap},set:function(t){t!==this._skyboxCubeMap&&(this._skyboxCubeMap=t,this._resetSkyboxModel())}},{key:"skyboxIntensity",get:function(){return this._skyboxIntensity},set:function(t){t!==this._skyboxIntensity&&(this._skyboxIntensity=t,this._resetSkyboxModel())}},{key:"ambientBake",get:function(){return this._ambientBake},set:function(t){this._ambientBake=t}},{key:"ambientBakeNumSamples",get:function(){return this._ambientBakeNumSamples},set:function(t){this._ambientBakeNumSamples=it.clamp(Math.floor(t),1,255)}},{key:"ambientBakeSpherePart",get:function(){return this._ambientBakeSpherePart},set:function(t){this._ambientBakeSpherePart=it.clamp(t,.001,1)}},{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:"skyboxRotation",get:function(){return this._skyboxRotation},set:function(t){this._skyboxRotation.equals(t)||(this._skyboxRotation.copy(t),this._resetSkyboxModel())}},{key:"skyboxMip",get:function(){return this._skyboxMip},set:function(t){t!==this._skyboxMip&&(this._skyboxMip=t,this._resetSkyboxModel())}},{key:"prefilteredCubemaps",get:function(){return this._prefilteredCubemaps},set:function(t){var e=this._prefilteredCubemaps;t=t||[];for(var i=!1,n=!0,s=0;s<6;++s){var a=t[s]||null;e[s]!==a&&(e[s]=a,i=!0),n=n&&!!e[s]}i&&(this._resetSkyboxModel(),n?(this._internalEnvAtlas=In.generatePrefilteredAtlas(e,{target:this._internalEnvAtlas}),this._envAtlas||(this.envAtlas=this._internalEnvAtlas)):this._internalEnvAtlas&&(this._envAtlas===this._internalEnvAtlas&&(this.envAtlas=null),this._internalEnvAtlas.destroy(),this._internalEnvAtlas=null))}},{key:"envAtlas",get:function(){return this._envAtlas},set:function(t){t!==this._envAtlas&&(this._envAtlas=t,this.updateShaders=!0)}},{key:"drawCalls",get:function(){var t=this.layers._meshInstances;return t.length||(this.layers._update(),t=this.layers._meshInstances),t},set:function(t){}},{key:"layers",get:function(){return this._layers},set:function(t){var e=this._layers;this._layers=t,this.fire("set:layers",e,t)}}]),e}(u);function Ah(){return!("undefined"==typeof AudioContext&&"undefined"==typeof webkitAudioContext)}var Mh=function(){function t(t,e,i){if(void 0===i&&(i={}),this.volume=void 0===i.volume?1:i.volume,this.loop=void 0!==i.loop&&i.loop,this.pitch=void 0===i.pitch?1:i.pitch,this.sound=e,this.paused=!1,this.suspended=!1,this.manager=t,this.source=null,Ah()){this.startTime=0,this.startOffset=0;var n=t.context;this.gain=n.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())},t}();Ah()?Object.assign(Mh.prototype,{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())},pause:function(){this.source&&(this.paused=!0,this.startOffset+=this.manager.context.currentTime-this.startTime,this.source.stop(0),this.source=null)},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.")},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)},setVolume:function(t){t=it.clamp(t,0,1),this.volume=t,this.gain&&(this.gain.gain.value=t*this.manager.volume)},setPitch:function(t){this.pitch=t,this.source&&(this.source.playbackRate.value=t)},isPlaying:function(){return!this.paused&&this.source.playbackState===this.source.PLAYING_STATE},getDuration:function(){return this.source?this.source.buffer.duration:0},_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)))}}):Object.assign(Mh.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=it.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 Ch="linear",Eh="inverse",Ph="exponential",Rh=function(t){function e(e,i,n){var s;return(s=t.call(this,e,i,n)||this).position=new lt,s.velocity=new lt,Ah()?s.panner=e.context.createPanner():(s.maxDistance=1e4,s.minDistance=1,s.rollOffFactor=1,s.distanceModel=Eh),s}H(e,t);var i=e.prototype;return i.getPosition=function(){return this.position},i.getVelocity=function(){return this.velocity},e}(Mh);if(Ah())Object.assign(Rh.prototype,{setPosition:function(t){this.position.copy(t),this.panner.setPosition(t.x,t.y,t.z)},setVelocity:function(t){this.velocity.copy(t),this.panner.setVelocity(t.x,t.y,t.z)},getMaxDistance:function(){return this.panner.maxDistance},setMaxDistance:function(t){this.panner.maxDistance=t},getMinDistance:function(){return this.panner.refDistance},setMinDistance:function(t){this.panner.refDistance=t},getRollOffFactor:function(){return this.panner.rolloffFactor},setRollOffFactor:function(t){this.panner.rolloffFactor=t},getDistanceModel:function(){return this.pannel.distanceModel},setDistanceModel:function(t){this.panner.distanceModel=t},_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))}});else{var Ih=new lt;Object.assign(Rh.prototype,{setPosition:function(t){if(this.position.copy(t),this.source){var e=function(t,e,i,n,s,a){var r=(Ih=Ih.sub2(t,e)).length();if(rn)return 0;var o=0;return a===Ch?o=1-s*(r-i)/(n-i):a===Eh?o=i/(i+s*(r-i)):a===Ph&&(o=Math.pow(r/i,-s)),it.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}},setVelocity:function(t){this.velocity.copy(t)},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 Lh=function(){function t(t){this._manager=t,this.position=new lt,this.velocity=new lt,this.orientation=new vt}var e=t.prototype;return e.getPosition=function(){return this.position},e.setPosition=function(t){this.position.copy(t);var e=this.listener;e&&e.setPosition(t.x,t.y,t.z)},e.getVelocity=function(){return this.velocity},e.setVelocity=function(t){this.velocity.copy(t);var e=this.listener;e&&e.setPosition(t.x,t.y,t.z)},e.setOrientation=function(t){this.orientation.copy(t);var e=this.listener;e&&e.setOrientation(-t.data[8],-t.data[9],-t.data[10],t.data[4],t.data[5],t.data[6])},e.getOrientation=function(){return this.orientation},G(t,[{key:"listener",get:function(){var t=this._manager.context;return t?t.listener:null}}]),t}(),Dh=function(t){function e(e){var i;return(i=t.call(this)||this)._context=null,i._forceWebAudioApi=e.forceWebAudioApi,i._resumeContext=null,i._unlock=null,Ah()||i._forceWebAudioApi?(i._resumeContext=function(){window.removeEventListener("mousedown",i._resumeContext),window.removeEventListener("touchend",i._resumeContext),i.context&&i.context.resume()},window.addEventListener("mousedown",i._resumeContext),window.addEventListener("touchend",i._resumeContext),E.ios&&(i._unlock=function(){window.removeEventListener("touchend",i._unlock);var t=i.context;if(t){var e=t.createBuffer(1,1,44100),n=t.createBufferSource();n.buffer=e,n.connect(t.destination),n.start(0),n.disconnect()}},window.addEventListener("touchend",i._unlock))):console.warn("No support for 3D audio found"),i.listener=new Lh(j(i)),i._volume=1,i.suspended=!1,i}H(e,t);var i=e.prototype;return i.suspend=function(){this.suspended=!0,this.fire("suspend")},i.resume=function(){var t=this,e=function(){t.suspended=!1,t.fire("resume")};!Ah()&&!this._forceWebAudioApi||"interrupted"!==this.context.state&&"suspended"!==this.context.state?e():this.context.resume().then(e)},i.destroy=function(){this._resumeContext&&(window.removeEventListener("mousedown",this._resumeContext),window.removeEventListener("touchend",this._resumeContext)),this._unlock&&window.removeEventListener("touchend",this._unlock),this.fire("destroy"),this._context&&this._context.close&&(this._context.close(),this._context=null)},i.playSound=function(t,e){void 0===e&&(e={});var i=null;return Mh&&(i=new Mh(this,t,e)).play(),i},i.playSound3d=function(t,e,i){void 0===i&&(i={});var n=null;return Rh&&((n=new Rh(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},G(e,[{key:"volume",get:function(){return this._volume},set:function(t){t=it.clamp(t,0,1),this._volume=t,this.fire("volumechange",t)}},{key:"context",get:function(){return this._context||(Ah()||this._forceWebAudioApi)&&("undefined"!=typeof AudioContext?this._context=new AudioContext:"undefined"!=typeof webkitAudioContext&&(this._context=new webkitAudioContext)),this._context}}]),e}(u),Oh=function(t,e,i,n){this.time=t,this.position=e,this.rotation=i,this.scale=n},kh=function(){this._name="",this._keys=[]},Fh=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},G(t,[{key:"nodes",get:function(){return this._nodes}}]),t}(),Bh=function(){function t(t){2===arguments.length&&(t=arguments[1]),this.options=t,this._name=t.name,this._defaultWeight=t.defaultWeight||0,this.aabb=t.aabb,this.aabb||(this.aabb=new At,t.deltaPositions&&this.aabb.compute(t.deltaPositions)),this.deltaPositions=t.deltaPositions}var e=t.prototype;return e._postInit=function(){this.options=null},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 $e(t,new Je(t,[{semantic:be,components:3,type:i}]),e.length/3,0,e):null},e._setTexture=function(t,e){this[t]=e},e.destroy=function(){this._vertexBufferPositions&&(this._vertexBufferPositions.destroy(),this._vertexBufferPositions=null),this._vertexBufferNormals&&(this._vertexBufferNormals.destroy(),this._vertexBufferNormals=null),this.texturePositions&&(this.texturePositions.destroy(),this.texturePositions=null),this.textureNormals&&(this.textureNormals.destroy(),this.textureNormals=null)},G(t,[{key:"name",get:function(){return this._name}},{key:"defaultWeight",get:function(){return this._defaultWeight}},{key:"morphPositions",get:function(){return!!this._vertexBufferPositions||!!this.texturePositions}},{key:"morphNormals",get:function(){return!!this._vertexBufferNormals||!!this.textureNormals}}]),t}(),Nh=function(t,e,i){this.device=t,this.inverseBindPose=e,this.boneNames=i},Uh=function(t){function e(){var e;return(e=t.call(this)||this)._meshes=null,e}H(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=0&&t<=1?0:1})),qh(["fr","pt"],(function(t){return t>=0&&t<2?0:1})),qh(["da"],(function(t){return 1===t||!Number.isInteger(t)&&t>=0&&t<=1?0:1})),qh(["de","en","it","el","es","tr","fi","sv","nb","no","ur"],(function(t){return 1===t?0:1})),qh(["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})),qh(["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})),qh(["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 Zh=jh[Yh(Hh)];function $h(t){return jh[t]||Zh}var Qh=new RegExp("^\\s*(?:(?:[a-z]+[a-z0-9\\-\\+\\.]*:)?//|data:|blob:)","i"),Jh=function(){function t(t,e,i,n,s,a){this.url=t||"",this.filename=e||"",this.hash=void 0===i?null:i,this.size=void 0===n?null:n,this.opt=void 0===s?null:s,this.contents=a||null}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}(),tl=-1,el={pvr:"extCompressedTexturePVRTC",dxt:"extCompressedTextureS3TC",etc2:"extCompressedTextureETC",etc1:"extCompressedTextureETC1",basis:"canvas"},il=["pvr","dxt","etc2","etc1","basis"],nl=function(t){function e(e,i,n,s,a){var r;return(r=t.call(this)||this)._id=tl--,r.name=e||"",r.type=i,r.tags=new $(j(r)),r._preload=!1,r._file=null,r._data=s||{},r.options=a||{},r._resources=[],r._i18n={},r.loaded=!1,r.loading=!1,r.registry=null,n&&(r.file=n),r}H(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&&!Qh.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=p.getDirectory(this.file.url);return p.join(e,t)},i.getLocalizedAssetId=function(t){return t=Kh(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.resource?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;e0,maxRetries:n},e)},G(e,[{key:"id",get:function(){return this._id},set:function(t){this._id=t}},{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,s=(null==(i=this.registry)||null==(n=i._loader)?void 0:n._app)||zs(),a=null==s?void 0:s.graphicsDevice;if(a)for(var r=function(i,n){var r=il[i];if(t.variants[r]&&a[el[r]])return t=t.variants[r],"break";if(s.enableBundles){var o=s.bundles.listBundlesForAsset(e);if(o&&o.find((function(t){var e;return null==t||null==(e=t.file)?void 0:e.variants[r]})))return"break"}},o=0,h=il.length;o=0){var a=n[s];a.decRefCount(),0===a.getRefCount()&&(n.splice(s,1),n.length||t._skinInstanceCache.delete(i),e&&(e.destroy(),a.skinInstance=null))}}}}},t}();al._skinInstanceCache=new Map;var rl,ol=function(){function t(e,i,n,s){for(var a=function(e,s,a){var r=t.createAsset(i.name,e,s,a);return n.add(r),r},r=[],o=0;o0&&o(n,Float32Array,1),s.length>0&&o(s,Uint16Array,65535),a.length>0&&o(a,Uint8Array,255)}(y),y.unlock(),y},bl=new vt,Sl=new lt,wl=function(t,e,i,n,s,a,r){var o=[];return e.primitives.forEach((function(h){var l,c,u,d=null,f=!0;if(h.hasOwnProperty("extensions")){var p=h.extensions;if(p.hasOwnProperty("KHR_draco_mesh_compression")){var m=window.DracoDecoderModule;if(m){var _=p.KHR_draco_mesh_compression;if(_.hasOwnProperty("attributes")){var g=n[_.bufferView],v=new m.DecoderBuffer;v.Init(g,g.length);var y,x,b=new m.Decoder,S=b.GetEncodedGeometryType(v);switch(S){case m.POINT_CLOUD:l=0,y=new m.PointCloud,x=b.DecodeBufferToPointCloud(v,y);break;case m.TRIANGULAR_MESH:l=4,y=new m.Mesh,x=b.DecodeBufferToMesh(v,y);break;case m.INVALID_GEOMETRY_TYPE:}if(!x||!x.ok()||0==y.ptr)return void s("Failed to decode draco compressed asset: "+(x?x.error_msg():"Mesh asset - invalid draco compressed geometry type: "+S));var w=y.num_faces();if(S===m.TRIANGULAR_MESH){var T=y.num_points()>65535,A=(u=3*w)*(T?4:2),M=m._malloc(A);T?(b.GetTrianglesUInt32Array(y,A,M),d=new Uint32Array(m.HEAPU32.buffer,M,u).slice()):(b.GetTrianglesUInt16Array(y,A,M),d=new Uint16Array(m.HEAPU16.buffer,M,u).slice()),m._free(M)}c=function(t,e,i,n,s,a,r){var o=e.num_points(),h=function(t){var i,a,r,h,l=n.GetAttributeByUniqueId(e,t),c=o*l.num_components();switch(l.data_type()){case s.DT_UINT8:h=1,r=1,i=s._malloc(c*r),n.GetAttributeDataArrayForAllPoints(e,l,s.DT_UINT8,c*r,i),a=new Uint8Array(s.HEAPU8.buffer,i,c).slice();break;case s.DT_UINT16:h=3,r=2,i=s._malloc(c*r),n.GetAttributeDataArrayForAllPoints(e,l,s.DT_UINT16,c*r,i),a=new Uint16Array(s.HEAPU16.buffer,i,c).slice();break;case s.DT_FLOAT32:default:h=6,r=4,i=s._malloc(c*r),n.GetAttributeDataArrayForAllPoints(e,l,s.DT_FLOAT32,c*r,i),a=new Float32Array(s.HEAPF32.buffer,i,c).slice()}return s._free(i),{values:a,numComponents:l.num_components(),componentSizeInBytes:r,storageType:h,normalized:l.normalized()}},l={},c=i.attributes;for(var u in c)if(c.hasOwnProperty(u)&&fl.hasOwnProperty(u)){var d=fl[u],f=h(c[u]),p=f.numComponents*f.componentSizeInBytes;l[d]={values:f.values,buffer:f.values.buffer,size:p,offset:0,stride:p,count:o,components:f.numComponents,type:f.storageType,normalize:f.normalized}}return l.hasOwnProperty(re)||vl(l,a),xl(t,l,r)}(t,y,_,b,m,d,a),m.destroy(y),m.destroy(b),m.destroy(v),f=!1}}}}c||(d=h.hasOwnProperty("indices")?ml(i[h.indices],n,!0):null,c=function(t,e,i,n,s,a,r){var o={},h=[];for(var l in e)e.hasOwnProperty(l)&&fl.hasOwnProperty(l)&&(o[l]=e[l],h.push(l+":"+e[l]));h.sort();var c=h.join(),u=r[c];if(!u){var d={};for(var f in o){var p=n[e[f]],m=ml(p,s),_=s[p.bufferView],g=fl[f],v=cl(p.type)*dl(p.componentType),y=_.hasOwnProperty("byteStride")?_.byteStride:v;d[g]={buffer:m.buffer,size:v,offset:m.byteOffset,stride:y,count:p.count,components:cl(p.type),type:ul(p.componentType),normalize:p.normalized}}d.hasOwnProperty(re)||vl(d,i),u=xl(t,d,a),r[c]=u}return u}(t,h.attributes,d,i,n,a,r),l=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:return 4;case 5:return 5;case 6:return 6;default:return 4}}(h));var C=null;if(c){if((C=new Xs(t)).vertexBuffer=c,C.primitive[0].type=l,C.primitive[0].base=0,C.primitive[0].indexed=null!==d,null!==d){var E;2!==(E=d instanceof Uint8Array?0:d instanceof Uint16Array?1:2)||t.extUintElement||(E=1,d=new Uint16Array(d));var P=new vs(t,E,d.length,0,d);C.indexBuffer[0]=P,C.primitive[0].count=d.length}else C.primitive[0].count=c.numVertices;C.materialIndex=h.material;var R=i[h.attributes.POSITION];if(C.aabb=gl(R),f&&h.hasOwnProperty("targets")){var I=[];h.targets.forEach((function(t,s){var a={};t.hasOwnProperty("POSITION")&&(R=i[t.POSITION],a.deltaPositions=_l(R,n),a.deltaPositionsType=6,a.aabb=gl(R)),t.hasOwnProperty("NORMAL")&&(R=i[t.NORMAL],a.deltaNormals=_l(R,n),a.deltaNormalsType=6),e.hasOwnProperty("extras")&&e.extras.hasOwnProperty("targetNames")?a.name=e.extras.targetNames[s]:a.name=s.toString(10),e.hasOwnProperty("weights")&&(a.defaultWeight=e.weights[s]),I.push(new Bh(a))})),C.morph=new bh(I,t)}}o.push(C)})),o},Tl=function(t,e,i){var n,s,a=["#ifdef MAPFLOAT","uniform float material_shininess;","#endif","","#ifdef MAPTEXTURE","uniform sampler2D texture_glossMap;","#endif","","void getGlossiness() {"," dGlossiness = 1.0;","","#ifdef MAPFLOAT"," dGlossiness *= material_shininess;","#endif","","#ifdef MAPTEXTURE"," dGlossiness *= texture2D(texture_glossMap, $UV).$CH;","#endif","","#ifdef MAPVERTEX"," dGlossiness *= saturate(vVertexColor.$VC);","#endif",""," dGlossiness = 1.0 - dGlossiness;",""," dGlossiness += 0.0000001;","}"].join("\n"),r=["#ifdef MAPCOLOR","uniform vec3 material_specular;","#endif","","#ifdef MAPTEXTURE","uniform sampler2D texture_specularMap;","#endif","","void getSpecularity() {"," dSpecularity = vec3(1.0);",""," #ifdef MAPCOLOR"," dSpecularity *= material_specular;"," #endif",""," #ifdef MAPTEXTURE"," vec3 srgb = texture2D(texture_specularMap, $UV).$CH;"," dSpecularity *= vec3(pow(srgb.r, 2.2), pow(srgb.g, 2.2), pow(srgb.b, 2.2));"," #endif",""," #ifdef MAPVERTEX"," dSpecularity *= saturate(vVertexColor.$VC);"," #endif","}"].join("\n"),o=["#ifdef MAPFLOAT","uniform float material_clearCoatGlossiness;","#endif","","#ifdef MAPTEXTURE","uniform sampler2D texture_clearCoatGlossMap;","#endif","","void getClearCoatGlossiness() {"," ccGlossiness = 1.0;","","#ifdef MAPFLOAT"," ccGlossiness *= material_clearCoatGlossiness;","#endif","","#ifdef MAPTEXTURE"," ccGlossiness *= texture2D(texture_clearCoatGlossMap, $UV).$CH;","#endif","","#ifdef MAPVERTEX"," ccGlossiness *= saturate(vVertexColor.$VC);","#endif",""," ccGlossiness = 1.0 - ccGlossiness;",""," ccGlossiness += 0.0000001;","}"].join("\n"),h=[0,0],l=[1,1],c=function(t,e,i){var n,s,a=t.texCoord;if(a)for(s=0;s0?i.name=t.name:i.name="node_"+e,t.hasOwnProperty("matrix")&&(bl.data.set(t.matrix),bl.getTranslation(Sl),i.setLocalPosition(Sl),bl.getEulerAngles(Sl),i.setLocalEulerAngles(Sl),bl.getScale(Sl),i.setLocalScale(Sl)),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 a=t.scale;i.setLocalScale(a[0],a[1],a[2])}return i},Ml=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*it.RAD_TO_DEG,n.aspectRatio&&(s.aspectRatioMode=1,s.aspectRatio=n.aspectRatio));var a=new uv(t.name);return a.addComponent("camera",s),a},Cl=function(t,e){var i={enabled:!1,type:"point"===t.type?"omni":t.type,color:t.hasOwnProperty("color")?new at(t.color):at.WHITE,range:t.hasOwnProperty("range")?t.range:9999,falloffMode:1,intensity:t.hasOwnProperty("intensity")?it.clamp(t.intensity,0,2):1};t.hasOwnProperty("spot")&&(i.innerConeAngle=t.spot.hasOwnProperty("innerConeAngle")?t.spot.innerConeAngle*it.RAD_TO_DEG:0,i.outerConeAngle=t.spot.hasOwnProperty("outerConeAngle")?t.spot.outerConeAngle*it.RAD_TO_DEG:Math.PI/4);var n=new uv(e.name);return n.rotateLocal(90,0,0),n.addComponent("light",i),n},El=function(t,e,i,n){if(!e.hasOwnProperty("skins")||0===e.skins.length)return[];var s=new Map;return e.skins.map((function(a){return function(t,e,i,n,s,a){var r,o,h,l=e.joints,c=l.length,u=[];if(e.hasOwnProperty("inverseBindMatrices")){var d=e.inverseBindMatrices,f=ml(i[d],n,!0),p=[];for(r=0;r0){var s=i&&i.camera&&i.camera.preprocess,a=i&&i.camera&&i.camera.process||Ml,r=i&&i.camera&&i.camera.postprocess;t.nodes.forEach((function(i,o){if(i.hasOwnProperty("camera")){var h=t.cameras[i.camera];if(h){s&&s(h);var l=a(h,e[o]);r&&r(h,l),l&&(n||(n=new Map),n.set(i,l))}}}))}return n}(e,l,s),f=Pl(e,l,i,s),p=function(t,e,i,n){if(!t.hasOwnProperty("materials")||0===t.materials.length)return[];var s=i&&i.material&&i.material.preprocess,a=i&&i.material&&i.material.process||Tl,r=i&&i.material&&i.material.postprocess;return t.materials.map((function(t){s&&s(t);var i=a(t,e,n);return r&&r(t,i),i}))}(e,n.map((function(t){return t.resource})),s,h),m=function(t,e,i,n,s){if(!e.hasOwnProperty("meshes")||0===e.meshes.length||!e.hasOwnProperty("accessors")||0===e.accessors.length||!e.hasOwnProperty("bufferViews")||0===e.bufferViews.length)return[];var a={};return e.meshes.map((function(r){return wl(t,r,e.accessors,i,n,s,a)}))}(t,e,i,a,h),_=El(t,e,l,i),g=[],v=0;vi.byteLength)e("Invalid length found in glb header. Found "+a);else{for(var r=[],o=12;oi.byteLength)throw new Error("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);r.push({length:h,type:l,data:c}),o+=h+8}1===r.length||2===r.length?1313821514===r[0].type?r.length>1&&5130562!==r[1].type?e("Invalid chunk type found in glb file. Expected 0x004E4942, found 0x"+r[1].type.toString(16)):e(null,{gltfChunk:r[0].data,binaryChunk:2===r.length?r[1].data:null}):e("Invalid chunk type found in glb file. Expected 0x4E4F534A, found 0x"+r[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})},kl=function(t,e,i,n){var s=[],a=i&&i.bufferView&&i.bufferView.preprocess,r=i&&i.bufferView&&i.bufferView.processAsync||function(t,e,i){i(null,null)},o=i&&i.bufferView&&i.bufferView.postprocess,h=t.bufferViews?t.bufferViews.length:0;if(h)for(var l=function(e,i){var a=t.bufferViews[e];a.hasOwnProperty("byteStride")&&(i.byteStride=a.byteStride),s[e]=i,o&&o(a,i),0==--h&&n(null,s)},c=0;c=0?t.split("?")[0]:t},e.load=function(e,i,n){var s=this;nl.fetchArrayBuffer(e.load,(function(a,r){a?i(a):t.parseAsync(s._getUrlWithoutParams(e.original),p.extractPath(e.load),r,s._device,n.registry,n.options,(function(t,e){t?i(t):i(null,new ol(e,n,s._assets,s._defaultMaterial))}))}),n,this._maxRetries)},e.open=function(t,e,i){return e},e.patch=function(t,e){},t}(),Bl=function(){function 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};(t.load.startsWith("blob:")||t.load.startsWith("data:"))&&(".glb"===p.getExtension(t.original).toLowerCase()?i.responseType=nt.ResponseType.ARRAY_BUFFER:i.responseType=nt.ResponseType.JSON),st.get(t.load,i,(function(i,n){i?e("Error loading animation resource: "+t.original+" ["+i+"]"):e(null,n)}))},e.open=function(t,e){if(".glb"===p.getExtension(t).toLowerCase()){var i=Fl.parse("filename.glb",e,null);if(i){var n=i.animations;return i.destroy(),n}return null}return this["_parseAnimationV"+e.animation.version](e)},e._parseAnimationV3=function(t){var e=t.animation,i=new Fh;i.name=e.name,i.duration=e.duration;for(var n=0;n0,maxRetries:this.maxRetries};t.load.startsWith("blob:")&&(i.responseType=nt.ResponseType.JSON),st.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 Vh(1,t)})),a=e.outputs.map((function(t){return new Vh(t.components,t.data)})),r=e.curves.map((function(t){return new zh([t.path],t.inputIndex,t.outputIndex,t.interpolation)}));return new Wh(i,n,s,a,r)},t}(),Ul=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;s0,maxRetries:this.maxRetries};t.load.startsWith("blob:")&&(i.responseType=nt.ResponseType.JSON),st.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 Ul(e)},t}(),Vl=function(){function t(t){t instanceof Audio?this.audio=t:this.buffer=t}return G(t,[{key:"duration",get:function(){var t=0;return this.buffer?t=this.buffer.duration:this.audio&&(t=this.audio.duration),t||0}}]),t}(),Gl=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}(),Wl={".ogg":"audio/ogg",".mp3":"audio/mpeg",".wav":"audio/x-wav",".mp4a":"audio/mp4",".m4a":"audio/mp4",".mp4":"audio/mp4",".aac":"audio/aac"},Hl=function(){function t(t){this.manager=t,this.maxRetries=0}var e=t.prototype;return e._isSupported=function(t){var e=p.getExtension(t);return!!Wl[e]},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 Vl(t))}),i)}else i(null)},e.open=function(t,e){return e},e._createSound=function(t,e,i){if(Ah()){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=nt.ResponseType.ARRAY_BUFFER),st.get(t,s,(function(t,s){t?i(t):n.context.decodeAudioData(s,e,i)}))}else{var a=null;try{a=new Audio}catch(t){return void i("No support for Audio element")}Gl&&document.body.appendChild(a);a.onerror=function(){a.onerror=null,Gl&&document.body.removeChild(a),i()},a.addEventListener("canplaythrough",(function t(){a.removeEventListener("canplaythrough",t),Gl&&document.body.removeChild(a),e(a)})),a.src=t}},t}(),Xl=function(){function t(){this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t}),st.get(t.load,{responseType:nt.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}(),jl=function(){function t(t){this._blobUrls={};for(var e=0,i=t.length;e=s)throw new Error("Invalid PAX header data format.");var l=parseInt(e.decode(new Uint8Array(t,i+r,h-r)),10),c=e.decode(new Uint8Array(t,i+h+1,l-(h-r)-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]}),r+=l}return new n(o)},n.prototype.applyHeader=function(t){for(var e=0;e0&&(a=p.trim()+a.trim())}var m={name:a,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 Yl=null;var Kl=function(){function t(t){this._requestId=0,this._pendingRequests={},this._filenamePrefix=t,this._worker=new Worker(function(){if(!Yl){var t="("+ql.toString()+")(true)\n\n",e=new Blob([t],{type:"application/javascript"});Yl=URL.createObjectURL(e)}return Yl}()),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,a=t.data.files.length;s0},e.destroy=function(){this._worker&&(this._worker.terminate(),this._worker=null,this._pendingRequests=null)},t}();ql();var Zl=function(){function t(t){this._assets=t,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;st.get(t.load,{responseType:nt.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(E.workers)i._worker||(i._worker=new Kl(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 rl(t).untar(i._assets.prefix);e(null,n)}},e.open=function(t,e){return new jl(e)},e.patch=function(t,e){},t}(),$l=function(){function t(){}var e=t.prototype;return e.instantiateModelEntity=function(t){return null},e.instantiateRenderEntity=function(t){return null},t}(),Ql=function(){function t(t,e){this.glbParser=new Fl(t,e,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=p.getExtension(this._getUrlWithoutParams(t)).toLowerCase().replace(".","");return this.parsers[e]||this.glbParser},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){},t}(),Jl=function(){function t(){this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t}),st.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}();var tc=function(){function t(t,e,i){this._device=t,this._registry=e,this._loader=i}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,a,r=t.data||{},o=t._handlerState.assets,h=t._resources,l=[null,null,null,null,null,null,null],c=function(){return r.hasOwnProperty("type")?r.type:r.hasOwnProperty("rgbm")?r.rgbm?Ne:Be: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])for(n=i[0].resource,a=0;a<6;++a)l[a+1]=new Mi(this._device,{name:t.name+"_prelitCubemap"+(n.width>>a),cubemap:!0,type:c()||n.type,width:n.width>>a,height:n.height>>a,format:n.format,levels:[n._levels[a]],fixCubemapSeams:!0,addressU:1,addressV:1,mipmaps:0===a});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=u.map((function(t){return t.resource})),f=[];for(s=0;s0,maxRetries:this.maxRetries},(function(i,s){if(i)e("Error loading font resource: "+t.original+" ["+i+"]");else{var a=ac(s);n._loadTextures(t.load.replace(".json",".png"),a,(function(t,i){if(t)return e(t);e(null,{data:a,textures:i})}))}})):(i&&i.data&&(i.data=ac(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,a=null,r=new Array(n),o=this._loader,h=function(e){var h=function(t,o){if(!a){if(t)return a=t,i(t);o.upload(),r[e]=o,++s===n&&i(null,r)}};0===e?o.load(t,"texture",h):o.load(t.replace(".png",e+".png"),"texture",h)},l=0;l0,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)}))},fc=function(){function t(t){this._app=t,this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){dc(t,this.maxRetries,e)},e.open=function(t,e){this._app.systems.script.preloading=!0;var i=new uc(this._app,!1).parse(e);return this._app.systems.script.preloading=!1,i},t}(),mc=function(){function t(){this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t}),st.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}(),_c=function(){function 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};t.load.startsWith("blob:")&&(i.responseType=nt.ResponseType.JSON),st.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}(),gc=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)},G(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}(),vc=function(){function t(){this.removeInvalid=!0,this.valid=!0,this.enumValidators={occludeSpecular:this._createEnumValidator([0,1,2]),cull:this._createEnumValidator([0,1,2,3]),blendType:this._createEnumValidator([0,1,2,3,4,5,6,7,8,9,10]),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=Nn,i="path"===t.mappingFormat;for(var n in t){var s=e[n];if(s)if(s.startsWith("enum")){var a=s.split(":")[1];this.enumValidators[a]&&(this.enumValidators[a](t[n])||this.setInvalid(n,t))}else if("number"===s)"number"!=typeof t[n]&&this.setInvalid(n,t);else if("boolean"===s)"boolean"!=typeof t[n]&&this.setInvalid(n,t);else if("string"===s)"string"!=typeof t[n]&&this.setInvalid(n,t);else if("vec2"===s)t[n]instanceof Array&&2===t[n].length||this.setInvalid(n,t);else if("rgb"===s)t[n]instanceof Array&&3===t[n].length||this.setInvalid(n,t);else if("texture"===s)i?"string"==typeof t[n]||t[null===n]||t[n]instanceof Mi||this.setInvalid(n,t):"number"!=typeof t[n]&&null!==t[n]&&(t[n]instanceof Mi||this.setInvalid(n,t));else if("boundingbox"===s)t[n].center&&t[n].center instanceof Array&&3===t[n].center.length||this.setInvalid(n,t),t[n].halfExtents&&t[n].halfExtents instanceof Array&&3===t[n].halfExtents.length||this.setInvalid(n,t);else if("cubemap"===s)"number"!=typeof t[n]&&null!==t[n]&&void 0!==t[n]&&(t[n]instanceof Mi&&t[n].cubemap||this.setInvalid(n,t));else if("chunks"===s)for(var r=Object.keys(t[n]),o=0;o=0}},t}(),yc=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 jn;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=W({},e.chunks)),e){var n=Nn[i],s=e[i];if("vec2"===n)t[i]=new ut(s[0],s[1]);else if("rgb"===n)t[i]=new at(s[0],s[1],s[2]);else if("texture"===n)s instanceof Mi?t[i]=s:t[i]instanceof Mi&&"number"==typeof s&&s>0||(t[i]=null);else if("cubemap"===n)s instanceof Mi?t[i]=s:t[i]instanceof Mi&&"number"==typeof s&&s>0||(t[i]=null),"cubeMap"!==i||s||(t.prefilteredCubemaps=null);else if("boundingbox"===n){var a=new lt(s.center[0],s.center[1],s.center[2]),r=new lt(s.halfExtents[0],s.halfExtents[1],s.halfExtents[2]);t[i]=new At(a,r)}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"]];for(e=0;e0,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 Mi(this._device,{width:2,height:2,format:7}),this._placeholderTextures[e].name="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=xc[t];return this._placeholderTextures[e]},e._assignPlaceholderTexture=function(t,e){e.resource[t]=this._getPlaceholderTexture(t,e)},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){e.resource[t]=i[0],"cubeMap"===t&&(e.resource.prefilteredCubemaps=i.slice(1))},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,a=this._parser.migrate(t.data),r=t.resource,o="path"===a.mappingFormat,h=Un;for(i=0;i0){for(var c=i.blendIndices.data[4*h+l],u=!0,d=0;dn)return!1;for(var f=0;f=0;n--)if(l[n].boneNames.length>i){var f=l.splice(n,1)[0],p=[];for(s=0;s=0;a--)u[a].mesh===_.originalMesh&&(u.push({mesh:o,node:u[a].node}),e&&e.push({material:e[a].material,path:e[a].path}));for(s=0;s=0;a--)u[a].mesh===_.originalMesh&&(u.splice(a,1),e&&e.splice(a,1))}!function(t){for(var e=t.vertices,i=t.skins,n=t.meshes,s=t.meshInstances,a=0;a0&&Ac(s,null,this._device.getBoneLimit());for(i=0;i0&&(h>65535&&this._device.extUintElement?(s=new vs(this._device,2,r),a=new Uint32Array(s.lock())):(s=new vs(this._device,1,r),a=new Uint16Array(s.lock()))),{buffer:s,data:a}},e._parseMeshes=function(t,e,i,n,s,a){for(var r=t.model,o=[],h=0,l=0;l0,maxRetries:this.maxRetries};(t.load.startsWith("blob:")||t.load.startsWith("data:"))&&(".glb"===p.getExtension(t.original).toLowerCase()?i.responseType=nt.ResponseType.ARRAY_BUFFER:i.responseType=nt.ResponseType.JSON),st.get(t.load,i,(function(i,n){e&&(i?e("Error loading model: "+t.original+" ["+i+"]"):e(null,n))}))},e.open=function(t,e){for(var i=0;i0?console.assert("Script Ordering Error. Contact support@playcanvas.com"):t._types.push(e)};var e=t.prototype;return e.load=function(e,i){var n=this;"string"==typeof e&&(e={load:e,original:e});var s=this;Nc.app=this._app,this._loadScript(e.load,(function(e,a,r){if(e)i(e);else if(Nc.legacy){var o=null;t._types.length&&(o=t._types.pop()),o?n._scripts[a]=o:o=null,i(null,o,r)}else{for(var h={},l=0;l0,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}(),Vc=[0,0,1,0,0,1,0,0,1,0,0,1],Gc=[0,1,3,2,3,1],Wc=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}H(e,t);var i=e.prototype;return i._createMeshes=function(){for(var t=this._meshes.length,e=0;e0,maxRetries:this.maxRetries},(function(t,i){t?e(t):e(null,i)}))},e.open=function(t,e){var i=new Wc(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,Hc,t),this._assets.on("load:"+t.data.textureAtlasAsset,Hc,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,Xc,t),this._assets.on("add:"+t.data.textureAtlasAsset,Xc,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,Hc,t),this._assets.off("add:"+n.textureAtlasAsset,Xc,t))},t}(),qc=function(){function t(t,e){this._app=t,this._data=e,this._templateRoot=null}var e=t.prototype;return e.instantiate=function(){return this._templateRoot||this._parseTemplate(),this._templateRoot.clone()},e._parseTemplate=function(){var t=new uc(this._app,!0);this._templateRoot=t.parse(this._data)},t}(),Yc=function(){function t(t){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};st.get(t.load,i,(function(i,n){i?e("Error requesting template: "+t.original):e(i,n)}))},e.open=function(t,e){return new qc(this._app,e)},t}(),Kc=function(){function t(){this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t}),st.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}(),Zc=function(t){function e(){var e;return(e=t.call(this)||this)._texture=null,e._frames=null,e}H(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()},G(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}(u),$c={repeat:0,clamp:1,mirror:2},Qc={nearest:0,linear:1,nearest_mip_nearest:2,linear_mip_nearest:4,nearest_mip_linear:3,linear_mip_linear:5},Jc=/^data\.frames\.(\d+)$/,tu=function(){function t(t){this._loader=t,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");if(".json"!==p.getExtension(t.original))return n.load(t,e);st.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(n,s){if(n)e(n);else{var a=t.original.replace(".json",".png");i._loader.load(a,"texture",(function(t,i){t?e(t):e(null,{data:s,texture:i})}))}}))},e.open=function(t,e){var i=new Zc;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){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!==Qc[t.data.minfilter]&&(i.minFilter=Qc[t.data.minfilter]),t.data.hasOwnProperty("magfilter")&&i.magFilter!==Qc[t.data.magfilter]&&(i.magFilter=Qc[t.data.magfilter]),t.data.hasOwnProperty("addressu")&&i.addressU!==$c[t.data.addressu]&&(i.addressU=$c[t.data.addressu]),t.data.hasOwnProperty("addressv")&&i.addressV!==$c[t.data.addressv]&&(i.addressV=$c[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?Ne:Be;i.type!==n&&(i.type=n)}t.resource.texture=i;var s={};for(var a in t.data.frames){var r=t.data.frames[a];s[a]={rect:new dt(r.rect),pivot:new ut(r.pivot),border:new dt(r.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 a in i.frames)n=i.frames[a],s[a]={rect:new dt(n.rect),pivot:new ut(n.pivot),border:new dt(n.border)};t.resource.frames=s}else{var r=e.match(Jc);if(r){var o=r[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 dt(i.rect),pivot:new ut(i.pivot),border:new dt(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 eu(){var t,e,i,n=0,s=1,a=2,r=3,o=8,h=9,l=10,c=11,u=12,d=13,f=14,p=16,m={astc:l,dxt:a,etc1:n,etc2:n,pvr:o,atc:c,none:f},_={astc:l,dxt:r,etc1:p,etc2:s,pvr:h,atc:u,none:p},g=21,v=22,y=23,x=8,b=10,S=26,w=27,T=28,A=29,M=30,C=7,E=3,P=5,R=function(t,e){switch(t){case n:return e.formats.etc1?g:v;case s:return y;case a:return x;case r:return b;case o:return S;case h:return w;case l:return T;case c:return A;case u:return M;case d:return C;case f:return E;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>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;i0?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;s0&&++r<=o){var i=100*Math.pow(2,r);console.log("Error loading Texture from: '"+e+"' - Retrying in "+i+"ms...");var h=t.indexOf("?")>=0?"&":"?";a=setTimeout((function(){s.src=t+h+"retry="+Date.now(),a=null}),i)}else n("Error loading Texture from: '"+e+"'")},s.src=t},e._loadImageBitmap=function(t,e,i,n){var s={cache:!0,responseType:"blob",retry:this.maxRetries>0,maxRetries:this.maxRetries};st.get(t,s,(function(t,e){t?n(t):createImageBitmap(e,{premultiplyAlpha:"none"}).then((function(t){n(null,t)})).catch((function(t){n(t)}))}))},t}(),mu=[1481919403,3140563232,169478669],_u={33776:8,33778:9,33779:Kt,36196:ie,37492:22,37496:23,35840:26,35841:ne,35842:27,35843:se,32849:6,32856:7,35905:19,35907:20,35898:18,34843:Zt,34842:$t};var gu=function(){function t(t){this.maxRetries=0}var e=t.prototype;return e.load=function(t,e,i){nl.fetchArrayBuffer(t.load,e,i,this.maxRetries)},e.open=function(t,e,i){var n=this.parse(e);if(!n)return null;var s=new Mi(i,{name:t,addressU:n.cubemap?1:0,addressV:n.cubemap?1:0,width:n.width,height:n.height,format:n.format,cubemap:n.cubemap,levels:n.levels});return s.upload(),s},e.parse=function(t){var e=new Uint32Array(t);if(mu[0]!==e[0]||mu[1]!==e[1]||mu[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=_u[i.glInternalFormat];if(void 0===n)return null;for(var s,a,r,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,a=4*o,r=u,18===n?new Uint32Array(s,a,r/4):new Uint8Array(s,a,r))),o+=u+3>>2}return{format:n,width:i.pixelWidth,height:i.pixelHeight,levels:l,cubemap:h}},t}(),vu=166,yu=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;nl.fetchArrayBuffer(t.load,(function(s,a){s?e(s,a):n.parse(a,t,e,i)}),i,this.maxRetries)},e.open=function(t,e,i){var n=new Mi(i,{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});return n.upload(),n},e.parse=function(t,e,i,n){var s=new K(t),a=[s.readU32be(),s.readU32be(),s.readU32be()];if(2873840728!==a[0]||540160187!==a[1]||218765834!==a[2])return null;for(var r={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;l1});for(var b,S=128,w=u?6:1,T=l===d?8:16,A=0;A32767)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 a,r,o,h,l,c,u=new ArrayBuffer(e*i*4),d=new Uint8Array(u),f=n?0:4*e*(i-1);for(r=0;r128){if(a+(l-=128)>e)return null;for(c=t.readU8(),o=0;oe)return null;for(o=0;o=0?t.split("?")[0]:t},e._getParser=function(t){var e=p.getExtension(this._getUrlWithoutParams(t)).toLowerCase().replace(".","");return this.parsers[e]||this.imgParser},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._getParser(t).open(t,e,this._device);return null===n?n=new Mi(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!==Jt||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),a=new i.constructor(n*s*4),r=Math.floor(t/n),o=Math.floor(e/s),h=r*o,l=0;l>s-1),r=Math.max(1,t._height>>s-1);if(t._cubemap){for(var o=[],h=0;h<6;++h)o.push(n(a,r,t._levels[s-1][h]));t._levels.push(o)}else t._levels.push(n(a,r,t._levels[s-1]))}t._levelsUpdated=t._cubemap?[[!0,!0,!0,!0,!0,!0]]:[!0]}}(n),e.unswizzledGGGR&&(i.file.variants.basis.opt&=-9)),n}},e.patch=function(t,e){var i=t.resource;if(i){t.name&&t.name.length>0&&(i.name=t.name);var n=t.data;n.hasOwnProperty("minfilter")&&(i.minFilter=wu[n.minfilter]),n.hasOwnProperty("magfilter")&&(i.magFilter=wu[n.magfilter]),i.cubemap||(n.hasOwnProperty("addressu")&&(i.addressU=Su[n.addressu]),n.hasOwnProperty("addressv")&&(i.addressV=Su[n.addressv])),n.hasOwnProperty("mipmaps")&&(i.mipmaps=n.mipmaps),n.hasOwnProperty("anisotropy")&&(i.anisotropy=n.anisotropy),n.hasOwnProperty("flipY")&&(i.flipY=!!n.flipY),n.hasOwnProperty("type")?i.type=Tu[n.type]:n.hasOwnProperty("rgbm")&&n.rgbm?i.type=Ne:t.file&&0!=(8&t.file.opt)&&(i.type=ze)}},G(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}(),Cu=function(){function t(t){void 0===t&&(t=null),this._index={},this._key=t}var e=t.prototype;return e.addItem=function(t){for(var e,i=Y(t.tags._list);!(e=i()).done;){var n=e.value;this.add(n,t)}},e.removeItem=function(t){for(var e,i=Y(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,a,r=this,o={},h=[],l=function(t,e){return r._index[t].list.length-r._index[e].list.length},c=0;c0?i[0]:null},e}(u),Pu=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;ethis.views.length)for(var a=0;a<=s-this.views.length;a++){var r=this.viewsPool.pop();r||(r={viewport:new dt,projMat:new vt,viewMat:new vt,viewOffMat:new vt,viewInvMat:new vt,viewInvOffMat:new vt,projViewOffMat:new vt,viewMat3:new ct,position:new Float32Array(3),rotation:new yt}),this.views.push(r)}else if(s<=this.views.length)for(var o=0;o=this._right){var i=e.length;if(i)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,a=this._p0*s;if(0===e)for(var r=0;rthis.track.duration&&(i=e-this.track.duration,e=this.track.duration);this.track.events[this.eventCursor]&&this.track.events[this.eventCursor].time>=t&&(e===this.track.duration?this.track.events[this.eventCursor].time<=e:this.track.events[this.eventCursor].time0&&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},G(t,[{key:"name",get:function(){return this._name},set:function(t){this._name=t}},{key:"track",get:function(){return this._track}},{key:"snapshot",get:function(){return this._snapshot}},{key:"time",get:function(){return this._time},set:function(t){this._time=t}},{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:"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}}]),t}(),Id="NONE",Ld="PREV_STATE",Dd="NEXT_STATE",Od="PREV_STATE_NEXT_STATE",kd="NEXT_STATE_PREV_STATE",Fd="GREATER_THAN",Bd="LESS_THAN",Nd="GREATER_THAN_EQUAL_TO",Ud="LESS_THAN_EQUAL_TO",zd="EQUAL_TO",Vd="NOT_EQUAL_TO",Gd="INTEGER",Wd="FLOAT",Hd="BOOLEAN",Xd="TRIGGER",jd="2D_DIRECTIONAL",qd="2D_CARTESIAN",Yd="DIRECT",Kd="START",Zd="END",$d="ANY",Qd=[Kd,Zd,$d],Jd="OVERWRITE",tf=function(){function t(t,e){this._component=t,this.mask=new Int8Array(t.layers.length),this.weights=new Float32Array(t.layers.length),this.totalWeight=0,this.counter=0,this.layerCounter=0,this.valueType=e,this.dirty=!0,this.value=[0,0,0,1]}var e=t.prototype;return e.getWeight=function(t){return this.dirty&&this.updateWeights(),0!==this.totalWeight&&this.mask[t]?this.weights[t]/this.totalWeight:0},e.setMask=function(t,e){this.mask[t]=e,this._component.layers[t].blendType===Jd&&(this.mask=this.mask.fill(0,0,t)),this.dirty=!0},e.updateWeights=function(){this.totalWeight=0;for(var t=0;t0){i=1/Math.sqrt(i);for(var n=e.length,s=0;s0&&(a=1/Math.sqrt(a));for(var r=0;r0;)this.removeClip(0)},e.findClip=function(t){for(var e=this._clips,i=0;i0&&r._update(e);var c=void 0,u=void 0,d=void 0;if(l>=1)for(var f=0;f0)for(var p=0;p0&&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}(),sf=function(){function t(t,e,i,n){this._func=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 G(t,[{key:"func",get:function(){return this._func}},{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}(),af=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;i0){return t.createAnimTarget((function(t){for(var e=0;ei){this._time=this.looping?0:i;for(var n=0;n=0?1:-1,l=0;l=0;m+=h){var _=d[m],g=d[m+1];if(_.time<=this._time&&g.time>=this._time){var v=(this._time-_.time)/(g.time-_.time);f._pos.lerp(_.position,g.position,v),f._quat.slerp(_.rotation,g.rotation,v),f._scale.lerp(_.scale,g.scale,v),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;s0&&i.prevAnim,i.blending&&(i.blend=0,i.blendSpeed=1/e),i.skeleton&&(i.blending?(i.fromSkel.animation=n,i.fromSkel.addTime(i.skeleton._time),i.toSkel.animation=s):i.skeleton.animation=s),i.animEvaluator){var a=i.animEvaluator;if(i.blending)for(;a.clips.length>1;)a.removeClip(0);else i.animEvaluator.removeClips();var r=new Rd(i.animations[i.currAnim],0,1,!0,i.loop);r.name=i.currAnim,r.blendWeight=i.blending?0:1,r.reset(),i.animEvaluator.addClip(r)}}i.playing=!0}}},i.getAnimation=function(t){return this.data.animations[t]},i.setModel=function(t){var e=this.data;t!==e.model&&(this._resetAnimationController(),e.model=t,e.animations&&e.currAnim&&e.animations[e.currAnim]&&this.play(e.currAnim))},i._resetAnimationController=function(){var t=this.data;t.skeleton=null,t.fromSkel=null,t.toSkel=null,t.animEvaluator=null},i._createAnimationController=function(){var t=this.data,e=t.model,i=t.animations,n=!1,s=!1;for(var a in i){if(i.hasOwnProperty(a))i[a].constructor===Wh?s=!0:n=!0}var r=e.getGraph();n?(t.fromSkel=new of(r),t.toSkel=new of(r),t.skeleton=new of(r),t.skeleton.looping=t.loop,t.skeleton.setGraph(r)):s&&(t.animEvaluator=new ef(new af(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;i1){if(n&&n.length>1)for(var a=0;a1)for(var o=0;o1)for(var h=0;h1)for(var e=0;e0&&this.play(r[0])}},i.onSetAssets=function(t,e,i){if(e&&e.length)for(var n=0;n0&&this.play(o[0])}},i.onBeforeRemove=function(){for(var t=0;t0)return e[e.length-1].time}return 0},set:function(t){var e=this.data;if(e.skeleton){var i=e.skeleton;i.currentTime=t,i.addTime(0),i.updateGraph()}if(e.animEvaluator)for(var n=e.animEvaluator,s=0;s=1&&(s.blend=1)),s.playing){var a=s.skeleton;if(null!==a&&null!==s.model){if(s.blending)a.blend(s.fromSkel,s.toSkel,s.blend);else{var r=t*s.speed;a.addTime(r),(s.speed>0&&a._time===a._animation.duration&&!s.loop||s.speed<0&&0===a._time&&!s.loop)&&(s.playing=!1)}s.blending&&1===s.blend&&(a.animation=s.toSkel._animation),a.updateGraph()}}var o=s.animEvaluator;if(o){for(var h=0;h1&&(o.clips[1].blendWeight=s.blend),o.update(t)}s.blending&&1===s.blend&&(s.blending=!1)}}},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},e}(Md);Ad._buildAccessors(hf.prototype,cf);var df=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 ut(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 G(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}(),ff=function(t){function e(e,i,n,s,a,r,o,h,l){var c;(c=t.call(this,e,i,n,s)||this)._parameters=a,c._parameterValues=new Array(a.length),c._children=[],c._findParameter=l,c._syncAnimations=!1!==o,c._pointCache={};for(var u=0;u=0)this._animationList[n].animTrack=e;else{var s=this._getNodeFromPath(t);s.animTrack=e,this._animationList.push(s)}},G(t,[{key:"name",get:function(){return this._name}},{key:"animations",get:function(){return this._animationList},set:function(t){this._animationList=t}},{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!==df?this._blendTree.getNodeCount():1}},{key:"playable",get:function(){return-1!==Qd.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;et&&(t=i.animTrack.duration)}return t}}]),t}(),yf=function(){function t(t){var e=t.from,i=t.to,n=t.time,s=void 0===n?0:n,a=t.priority,r=void 0===a?0:a,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?Id:f;this._from=e,this._to=i,this._time=s,this._priority=r,this._conditions=h,this._exitTime=c,this._transitionOffset=d,this._interruptionSource=p}return G(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}(),xf=function(){function t(t,e,i,n,s,a,r){this._animEvaluator=t,this._states={},this._stateNames=[],this._eventHandler=a,this._consumedTriggers=r;for(var o=0;o"+e];return i||((i=this._transitions.filter((function(i){return i.from===t&&i.to===e}))).sort((function(t,e){return t.priority"+e]=i),i},e._transitionHasConditionsMet=function(t){for(var e=!0,i=0;in.value;break;case Bd:e=e&&s.value=n.value;break;case Ud:e=e&&s.value<=n.value;break;case zd:e=e&&s.value===n.value;break;case Vd:e=e&&s.value!==n.value}if(!e)return e}return e},e._findTransition=function(t,e){var i=this,n=[];if(t&&e)n.concat(this._findTransitionsBetweenStates(t,e));else if(this._isTransitioning)switch(this._transitionInterruptionSource){case Ld:n=(n=n.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState($d));break;case Dd:n=(n=n.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState($d));break;case Od:n=(n=(n=n.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState($d));break;case kd:n=(n=(n=n.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState($d))}else n=(n=n.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState($d));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)),!(t.exitTime>e&&t.exitTime<=n))return null}return i._transitionHasConditionsMet(t)}))).length>0){var s=n[0];if(s.to===Zd){var a=this._findTransitionsFromState(Kd)[0];s.to=a.to}return s}return null},e.updateStateFromTransition=function(t){var e,i,n;this.previousState=t.from?this.activeStateName:null,this.activeState=t.to;for(var s=0;s0&&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;p0?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 yf({from:null,to:t})),this.updateStateFromTransition(e)}},e.assignAnimation=function(t,e,i,n){var s=t.split("."),a=this._findState(s[0]);a||(a=new vf(this,s[0],1),this._states[s[0]]=a,this._stateNames.push(s[0])),a.addAnimation(s,e),void 0!==i&&(a.speed=i),void 0!==n&&(a.loop=n),!this._playing&&this._activate&&this.playable&&this.play()},e.removeNodeAnimations=function(t){if(-1===Qd.indexOf(t)){var e=this._findState(t);if(e)return 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=Kd,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._timeInStateBefore=this._timeInState,this._timeInState+=t;var s=this._findTransition(this._activeStateName);if(s&&this.updateStateFromTransition(s),this._isTransitioning)if(this._currTransitionTime+=t,this._currTransitionTime<=this._totalTransitionTime){for(var a=0!==this._totalTransitionTime?this._currTransitionTime/this._totalTransitionTime:1,r=0;r1){var h=e.length>2?this._resolvePath(t,e.slice(0,-1)):t,l=e[e.length-2];return function(t){n[s]=i(t),h[l]=n}}return function(t){n[s]=i(t)}},i._createAnimTargetForProperty=function(t,i,n){if(this.handlers&&"weights"===i[0])return this.handlers.weights(t);if(this.handlers&&"material"===i[0]&&2===i.length){var s=i[1];if(s.indexOf("Map")===s.length-3)return this.handlers.materialTexture(t,s)}var a,r,o,h=this._resolvePath(t,i,!0);if(void 0===h)return null;if("number"==typeof h)a=this._setter(t,i,e._packFloat),r="vector",o=1;else if("boolean"==typeof h)a=this._setter(t,i,e._packBoolean),r="vector",o=1;else if("object"==typeof h)switch(h.constructor){case ut:a=this._setter(t,i,e._packVec2),r="vector",o=2;break;case lt:a=this._setter(t,i,e._packVec3),r="vector",o=3;break;case dt:a=this._setter(t,i,e._packVec4),r="vector",o=4;break;case at:a=this._setter(t,i,e._packColor),r="vector",o=4;break;case yt:a=this._setter(t,i,e._packQuat),r="quaternion",o=4;break;default:return null}return-1!==i.indexOf("material")?new sf((function(e){a(e),t.material.update()}),r,o,n):new sf(a,r,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;n0?this._layers[0]:null}}]),e}(Ad),Pf=function(){this.enabled=!0},Rf=["enabled"],If=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="anim",i.ComponentType=Ef,i.DataType=Pf,i.schema=Rf,i.on("beforeremove",i.onBeforeRemove,j(i)),i.app.systems.on("animationUpdate",i.onAnimationUpdate,j(i)),i}H(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){t.prototype.initializeComponentData.call(this,e,i,Rf);var s=["animationAssets","stateGraph","layers","masks"];Object.keys(i).forEach((function(t){s.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(t){e.layers[i].assignAnimation(t.name,t.animTrack)}))}))})):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].assignMask(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={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};this.addComponent(e,i)},i.onBeforeRemove=function(t,e){e.onBeforeRemove()},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("animationUpdate",this.onAnimationUpdate,this)},e}(Md);Ad._buildAccessors(Ef.prototype,Rf);var Lf=function(t){function e(){return t.apply(this,arguments)||this}H(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}(Ad),Df=function(){this.enabled=!0},Of=["enabled"],kf=function(t){function e(e,i){var n;return(n=t.call(this,e)||this).id="audiolistener",n.ComponentType=Lf,n.DataType=Df,n.schema=Of,n.manager=i,n.current=null,n.app.systems.on("update",n.onUpdate,j(n)),n}H(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}(Md);Ad._buildAccessors(Lf.prototype,Of);var Ff=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this).on("set_assets",n.onSetAssets,j(n)),n.on("set_loop",n.onSetLoop,j(n)),n.on("set_volume",n.onSetVolume,j(n)),n.on("set_pitch",n.onSetPitch,j(n)),n.on("set_minDistance",n.onSetMinDistance,j(n)),n.on("set_maxDistance",n.onSetMaxDistance,j(n)),n.on("set_rollOffFactor",n.onSetRollOffFactor,j(n)),n.on("set_distanceModel",n.onSetDistanceModel,j(n)),n.on("set_3d",n.onSet3d,j(n)),n}H(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 a=0;a1e-5){var i=this._tweenInfo.lerpColor;i.lerp(this._tweenInfo.from,this._tweenInfo.to,e),this._applyTintImmediately(new at(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}(Ad);function Qf(t){return new at(t.r,t.g,t.b)}var Jf,tp=function(){this.enabled=!0,this.active=!0,this.imageEntity=null,this.hitPadding=new dt,this.transitionMode=0,this.hoverTint=new at(.75,.75,.75),this.pressedTint=new at(.5,.5,.5),this.inactiveTint=new at(.25,.25,.25),this.fadeDuration=0,this.hoverSpriteAsset=null,this.hoverSpriteFrame=0,this.pressedSpriteAsset=null,this.pressedSpriteFrame=0,this.inactiveSpriteAsset=null,this.inactiveSpriteFrame=0},ep=["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"],ip=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="button",i.ComponentType=$f,i.DataType=tp,i.schema=ep,i.on("beforeremove",i._onRemoveComponent,j(i)),i.app.systems.on("update",i.onUpdate,j(i)),i}H(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){t.prototype.initializeComponentData.call(this,e,i,ep)},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}(Md);Ad._buildAccessors($f.prototype,ep);var np=function(t,e){this.effect=t,this.inputTarget=e,this.outputTarget=null,this.name=t.constructor.name},sp=function(){function t(t,e){var i=this;this.app=t,this.camera=e,this.destinationRenderTarget=null,this.effects=[],this.enabled=!1,this.depthTarget=null,this.renderTargetScale=1,this.resizeTimeout=null,this.resizeLast=0,this._resizeTimeoutCallback=function(){i.resizeRenderTargets()},e.on("set:rect",this.onCameraRectChanged,this)}var e=t.prototype;return e._allocateColorBuffer=function(t,e){var i=this.camera.rect,n=Math.floor(i.z*this.app.graphicsDevice.width*this.renderTargetScale),s=Math.floor(i.w*this.app.graphicsDevice.height*this.renderTargetScale),a=new Mi(this.app.graphicsDevice,{format:t,width:n,height:s,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1});return a.name=e,a},e._createOffscreenTarget=function(t,e){var i=this.app.graphicsDevice,n=e?i.getHdrFormat():7,s=this.camera.entity.name+"-posteffect-"+this.effects.length,a=this._allocateColorBuffer(n,s),r=this.app.graphicsDevice.supportsStencil,o=t?i.samples:1;return new ms({colorBuffer:a,depth:t,stencil:r,samples:o})},e._resizeOffscreenTarget=function(t){var e=t.colorBuffer.format,i=t.colorBuffer.name;t.destroyFrameBuffers(),t.destroyTextureBuffers(),t._colorBuffer=this._allocateColorBuffer(e,i)},e._destroyOffscreenTarget=function(t){t.destroyTextureBuffers(),t.destroy()},e.setRenderTargetScale=function(t){this.renderTargetScale=t,this.resizeRenderTargets()},e.addEffect=function(t){var e=this.effects,i=0===e.length,n=this._createOffscreenTarget(i,t.hdr),s=new np(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=0&&(e>0?this.effects[e-1].outputTarget=e+11&&(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;t100?this.resizeRenderTargets():this.resizeTimeout=setTimeout(this._resizeTimeoutCallback,100))},e.resizeRenderTargets=function(){this.resizeTimeout&&(clearTimeout(this.resizeTimeout),this.resizeTimeout=null),this.resizeLast=Q();for(var t=this.camera.rect,e=Math.floor(t.z*this.app.graphicsDevice.width*this.renderTargetScale),i=Math.floor(t.w*this.app.graphicsDevice.height*this.renderTargetScale),n=this.effects,s=0,a=n.length;s=0&&(this.cameras.splice(e,1),this.sortCamerasByPriority())},i.sortCamerasByPriority=function(){this.cameras.sort((function(t,e){return t.priority-e.priority}))},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},e}(Md);Ad._buildAccessors(rp.prototype,hp);var cp,up,dp,fp=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._compoundParent=null,n.entity.on("insert",n._onInsert,j(n)),n.on("set_type",n.onSetType,j(n)),n.on("set_halfExtents",n.onSetHalfExtents,j(n)),n.on("set_radius",n.onSetRadius,j(n)),n.on("set_height",n.onSetHeight,j(n)),n.on("set_axis",n.onSetAxis,j(n)),n.on("set_asset",n.onSetAsset,j(n)),n.on("set_renderAsset",n.onSetRenderAsset,j(n)),n.on("set_model",n.onSetModel,j(n)),n.on("set_render",n.onSetRender,j(n)),n}H(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.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 nl&&(this.data.asset=i.id);var a=n.get(this.data.asset);a&&(a.off("remove",this.onAssetRemoved,this),a.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 nl&&(this.data.renderAsset=i.id);var a=n.get(this.data.renderAsset);a&&(a.off("remove",this.onRenderAssetRemoved,this),a.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-1&&e.rigidbody._triggers.splice(i,1),e.rigidbody.removeBody(t),t.forceActivationState(5)}},t}(),bp=new vt,Sp=new lt,wp=new yt,Tp=new qi,Ap=["enabled","type","halfExtents","radius","axis","height","asset","renderAsset","shape","model","render"],Mp=function(){function t(t){this.system=t}var e=t.prototype;return e.beforeInitialize=function(t,e){e.shape=null,e.model=new wh,e.model.graph=new qi},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()),Ammo.destroy(i.shape),i.shape=null),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 xp(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.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,Ammo.destroy(e.data.shape),e.data.shape=null)},e.remove=function(t,e){var i=this.system.app;t.rigidbody&&t.rigidbody.body&&t.rigidbody.disableSimulation(),t.trigger&&(t.trigger.destroy(),delete t.trigger),i.scene.containsModel(e.model)&&(i.root.removeChild(e.model.graph),i.scene.removeModel(e.model))},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],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}(),Cp=function(t){function e(){return t.apply(this,arguments)||this}return H(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}(Mp),Ep=function(t){function e(){return t.apply(this,arguments)||this}return H(e,t),e.prototype.createPhysicalShape=function(t,e){if("undefined"!=typeof Ammo)return new Ammo.btSphereShape(e.radius)},e}(Mp),Pp=function(t){function e(){return t.apply(this,arguments)||this}return H(e,t),e.prototype.createPhysicalShape=function(t,e){var i=void 0!==e.axis?e.axis:1,n=e.radius||.5,s=Math.max((e.height||2)-2*n,0),a=null;if("undefined"!=typeof Ammo)switch(i){case 0:a=new Ammo.btCapsuleShapeX(n,s);break;case 1:a=new Ammo.btCapsuleShape(n,s);break;case 2:a=new Ammo.btCapsuleShapeZ(n,s)}return a},e}(Mp),Rp=function(t){function e(){return t.apply(this,arguments)||this}return H(e,t),e.prototype.createPhysicalShape=function(t,e){var i=void 0!==e.axis?e.axis:1,n=void 0!==e.radius?e.radius:.5,s=void 0!==e.height?e.height:1,a=null,r=null;if("undefined"!=typeof Ammo)switch(i){case 0:a=new Ammo.btVector3(.5*s,n,n),r=new Ammo.btCylinderShapeX(a);break;case 1:a=new Ammo.btVector3(n,.5*s,n),r=new Ammo.btCylinderShape(a);break;case 2:a=new Ammo.btVector3(n,n,.5*s),r=new Ammo.btCylinderShapeZ(a)}return a&&Ammo.destroy(a),r},e}(Mp),Ip=function(t){function e(){return t.apply(this,arguments)||this}return H(e,t),e.prototype.createPhysicalShape=function(t,e){var i=void 0!==e.axis?e.axis:1,n=void 0!==e.radius?e.radius:.5,s=void 0!==e.height?e.height:1,a=null;if("undefined"!=typeof Ammo)switch(i){case 0:a=new Ammo.btConeShapeX(n,s);break;case 1:a=new Ammo.btConeShape(n,s);break;case 2:a=new Ammo.btConeShapeZ(n,s)}return a},e}(Mp),Lp=function(t){function e(){return t.apply(this,arguments)||this}H(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,a,r=t.vertexBuffer,o=r.getFormat(),h=0;h=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 a=0;a0?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"\\":switch(this._next(),this._cur){case"[":this._store();break;default: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(zp)},e._eof=function(){return null===this._cur},e._next=function(){return this._eof()||(this._index++,this._cur=this._index=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 a={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;a.value=this._scanner.buf().join(""),i=this._scanner.read()}for(;;){switch(i){case 4:return e.push(a),!0;case 7:var r=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("");a.attributes[r]=o;break;default:return this._error="expected close bracket or identifier",!1}i=this._scanner.read()}},t}();function Wp(t,e){for(var i in e)if(e.hasOwnProperty(i)){var n=e[i];n instanceof Object?(t.hasOwnProperty(i)||(t[i]={}),Wp(t[i],e[i])):t[i]=n}}function Hp(t){if(0===t.length)return null;for(var e={},i=0;i=1e-4,v=this._element.calculatedWidth;(this.autoWidth&&!g||!this._wrapLines)&&(v=Number.POSITIVE_INFINITY);var y,x,b,S,w=0,T=0,A=1;function M(t,i,n){e._lineWidths.push(Math.abs(n));var s=f>i?i+1:f,a=f>i?f+1:i,h=t.slice(s,a);if(_)for(var l=h.length;l--&&_>0;)Yp.test(h[l])&&(h.splice(l,1),_--);e._lineContents.push(h.join("")),r=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=[],r=0,o=0,h=0,l=0,c=1,u=0,d=0,f=0,p=0,m=0,_=0,A=this._fontSize/32,w=this._fontMinY*A,T=this._fontMaxY*A;for(var E=0;E=a?null:this._symbols[L+1],Yp.test(y))_++,(!this._wrapLines||this._maxLines<0||c0){var V=this._font.data.kerning;if(V){var G=V[U.getCodePoint(this._symbols[L-1])||0];G&&(z=G[U.getCodePoint(this._symbols[L])||0]||0)}}B=x.scale||1,F=A*((x.width+x.height)/2)/B,k=(x.xadvance+z)*A,D=(x.xoffset-z)*A,O=x.yoffset*A}else console.error("Couldn't substitute missing character: '"+y+"'");var W=Kp.test(y),H=this._meshInfo[x&&x.map||0],X=r+this._spacing*k;if(X>v&&m>0&&!W&&(this._maxLines<0||cthis._element.calculatedWidth&&(st=Math.floor(this._element.fontSize*this._element.calculatedWidth/(this.width||1e-4)),(st=it.clamp(st,i,n))!==this._element.fontSize)){this._fontSize=st,C=!0;break}if(this.height=Math.max(this.height,T-(o+w)),this._shouldAutoFitHeight()&&this.height>this._element.calculatedHeight&&(st=it.clamp(this._fontSize-1,i,n))!==this._element.fontSize){this._fontSize=st,C=!0;break}r+=this._spacing*k,W||(l=r),(this._isWordBoundary(y)||this._isValidNextChar(S)&&(this._isNextCJKBoundary(y,S)||this._isNextCJKWholeWord(S)))&&(p++,u=l,d=L+1),m++;var at=this._getUv(y);if(H.uvs[4*b*2+0]=at[0],H.uvs[4*b*2+1]=1-at[1],H.uvs[4*b*2+2]=at[2],H.uvs[4*b*2+3]=1-at[1],H.uvs[4*b*2+4]=at[2],H.uvs[4*b*2+5]=1-at[3],H.uvs[4*b*2+6]=at[0],H.uvs[4*b*2+7]=1-at[3],this._symbolColors){var rt=3*this._symbolColors[L];P=this._colorPalette[rt],R=this._colorPalette[rt+1],I=this._colorPalette[rt+2]}H.colors[4*b*4+0]=P,H.colors[4*b*4+1]=R,H.colors[4*b*4+2]=I,H.colors[4*b*4+3]=255,H.colors[4*b*4+4]=P,H.colors[4*b*4+5]=R,H.colors[4*b*4+6]=I,H.colors[4*b*4+7]=255,H.colors[4*b*4+8]=P,H.colors[4*b*4+9]=R,H.colors[4*b*4+10]=I,H.colors[4*b*4+11]=255,H.colors[4*b*4+12]=P,H.colors[4*b*4+13]=R,H.colors[4*b*4+14]=I,H.colors[4*b*4+15]=255,H.quad++}}C||f=At?(Mt.element.POSITION.set(0,0,0),Mt.element.TEXCOORD0.set(0,0),Mt.element.COLOR.set(0,0,0,0)):(Mt.element.POSITION.set(this._meshInfo[ut].positions[3*Ct+0],this._meshInfo[ut].positions[3*Ct+1],this._meshInfo[ut].positions[3*Ct+2]),Mt.element.TEXCOORD0.set(this._meshInfo[ut].uvs[2*Ct+0],this._meshInfo[ut].uvs[2*Ct+1]),Mt.element.COLOR.set(this._meshInfo[ut].colors[4*Ct+0],this._meshInfo[ut].colors[4*Ct+1],this._meshInfo[ut].colors[4*Ct+2],this._meshInfo[ut].colors[4*Ct+3])),Mt.next();Mt.end(),this._meshInfo[ut].meshInstance.mesh.aabb.compute(this._meshInfo[ut].positions),this._meshInfo[ut].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,a=0;athis._font.textures.length&&(this._meshInfo.length=this._font.textures.length),this._updateText()}}},{key:"alignment",get:function(){return this._alignment},set:function(t){t instanceof ut?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=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=0&&this.system.app.batcher.insert(la.ELEMENT,this.batchGroupId,this.entity),this.fire("enableelement")},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._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&&this.system.app.batcher.remove(la.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=0&&this._addedModels.splice(e,1);for(var i=0;ii||f>n||p16777215&&(t=16777215),this._drawOrder=(e<<24)+t,this.fire("set:draworder",this._drawOrder)}}),Object.defineProperty(um.prototype,"_absLeft",{get:function(){return this._localAnchor.x+this._margin.x}}),Object.defineProperty(um.prototype,"_absRight",{get:function(){return this._localAnchor.z-this._margin.z}}),Object.defineProperty(um.prototype,"_absTop",{get:function(){return this._localAnchor.w-this._margin.w}}),Object.defineProperty(um.prototype,"_absBottom",{get:function(){return this._localAnchor.y+this._margin.y}}),Object.defineProperty(um.prototype,"margin",{get:function(){return this._margin},set:function(t){this._margin.copy(t),this._calculateSize(!0,!0),this.fire("set:margin",this._margin)}}),Object.defineProperty(um.prototype,"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)}}),Object.defineProperty(um.prototype,"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)}}),Object.defineProperty(um.prototype,"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)}}),Object.defineProperty(um.prototype,"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)}}),Object.defineProperty(um.prototype,"width",{get:function(){return this._width},set:function(t){this._width=t,this._hasSplitAnchorsX||this._setCalculatedWidth(t,!0),this.fire("set:width",this._width)}}),Object.defineProperty(um.prototype,"height",{get:function(){return this._height},set:function(t){this._height=t,this._hasSplitAnchorsY||this._setCalculatedHeight(t,!0),this.fire("set:height",this._height)}}),Object.defineProperty(um.prototype,"calculatedWidth",{get:function(){return this._calculatedWidth},set:function(t){this._setCalculatedWidth(t,!0)}}),Object.defineProperty(um.prototype,"calculatedHeight",{get:function(){return this._calculatedHeight},set:function(t){this._setCalculatedHeight(t,!0)}}),Object.defineProperty(um.prototype,"pivot",{get:function(){return this._pivot},set:function(t){var e=this._pivot.x,i=this._pivot.y;t instanceof ut?this._pivot.set(t.x,t.y):this._pivot.set(t[0],t[1]);var n=this._margin.x+this._margin.z,s=this._pivot.x-e;this._margin.x+=n*s,this._margin.z-=n*s;var a=this._margin.y+this._margin.w,r=this._pivot.y-i;this._margin.y+=a*r,this._margin.w-=a*r,this._anchorDirty=!0,this._cornersDirty=!0,this._worldCornersDirty=!0,this._calculateSize(!1,!1),this._flagChildrenAsDirty(),this.fire("set:pivot",this._pivot)}}),Object.defineProperty(um.prototype,"anchor",{get:function(){return this._anchor},set:function(t){t instanceof dt?this._anchor.set(t.x,t.y,t.z,t.w):this._anchor.set(t[0],t[1],t[2],t[3]),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)}}),Object.defineProperty(um.prototype,"_hasSplitAnchorsX",{get:function(){return Math.abs(this._anchor.x-this._anchor.z)>.001}}),Object.defineProperty(um.prototype,"_hasSplitAnchorsY",{get:function(){return Math.abs(this._anchor.y-this._anchor.w)>.001}}),Object.defineProperty(um.prototype,"aabb",{get:function(){return this._image?this._image.aabb:this._text?this._text.aabb:null}}),Object.defineProperty(um.prototype,"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}}),Object.defineProperty(um.prototype,"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}}),Object.defineProperty(um.prototype,"worldCorners",{get:function(){if(!this._worldCornersDirty)return this._worldCorners;if(this.screen){var t=this.screenCorners;if(!this.screen.screen.screenSpace){om.copy(this.screen.screen._screenMatrix),om.data[13]=-om.data[13],om.mul2(this.screen.getWorldTransform(),om);for(var e=0;e<4;e++)om.transformPoint(t[e],this._worldCorners[e])}}else{var i=this.entity.getLocalPosition();om.setTranslate(-i.x,-i.y,-i.z),hm.setTRS(lt.ZERO,this.entity.getLocalRotation(),this.entity.getLocalScale()),lm.setTranslate(i.x,i.y,i.z);var n=this.entity.parent?this.entity.parent:this.entity;cm.copy(n.getWorldTransform()),cm.mul(lm).mul(hm).mul(om),am.set(i.x-this.pivot.x*this.calculatedWidth,i.y-this.pivot.y*this.calculatedHeight,i.z),cm.transformPoint(am,this._worldCorners[0]),am.set(i.x+(1-this.pivot.x)*this.calculatedWidth,i.y-this.pivot.y*this.calculatedHeight,i.z),cm.transformPoint(am,this._worldCorners[1]),am.set(i.x+(1-this.pivot.x)*this.calculatedWidth,i.y+(1-this.pivot.y)*this.calculatedHeight,i.z),cm.transformPoint(am,this._worldCorners[2]),am.set(i.x-this.pivot.x*this.calculatedWidth,i.y+(1-this.pivot.y)*this.calculatedHeight,i.z),cm.transformPoint(am,this._worldCorners[3])}return this._worldCornersDirty=!1,this._worldCorners}}),Object.defineProperty(um.prototype,"textWidth",{get:function(){return this._text?this._text.width:0}}),Object.defineProperty(um.prototype,"textHeight",{get:function(){return this._text?this._text.height:0}}),Object.defineProperty(um.prototype,"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):!0===this._useInput&&console.warn("Elements will not get any input events because this.system.app.elementInput is not created"),this.fire("set:useInput",t))}}),Object.defineProperty(um.prototype,"batchGroupId",{get:function(){return this._batchGroupId},set:function(t){this._batchGroupId!==t&&(this.entity.enabled&&this._batchGroupId>=0&&this.system.app.batcher.remove(la.ELEMENT,this.batchGroupId,this.entity),this.entity.enabled&&t>=0&&this.system.app.batcher.insert(la.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)}}),Object.defineProperty(um.prototype,"maskedBy",{get:function(){return this._maskedBy}}),dm("fontSize"),dm("minFontSize"),dm("maxFontSize"),dm("maxLines"),dm("autoFitWidth"),dm("autoFitHeight"),dm("color"),dm("font"),dm("fontAsset"),dm("spacing"),dm("lineHeight"),dm("wrapLines"),dm("lines"),dm("alignment"),dm("autoWidth"),dm("autoHeight"),dm("rtlReorder"),dm("unicodeConverter"),dm("text"),dm("key"),dm("texture"),dm("textureAsset"),dm("material"),dm("materialAsset"),dm("sprite"),dm("spriteAsset"),dm("spriteFrame"),dm("pixelsPerUnit"),dm("opacity"),dm("rect"),dm("mask"),dm("outlineColor"),dm("outlineThickness"),dm("shadowColor"),dm("shadowOffset"),dm("enableMarkup"),dm("rangeStart"),dm("rangeEnd");var fm=function(){this.enabled=!0},pm=["enabled"],mm=function(t){function e(e){var i;(i=t.call(this,e)||this).id="element",i.ComponentType=um,i.DataType=fm,i.schema=pm,i._unicodeConverter=null,i._rtlReorder=null,i._defaultTexture=new Mi(e.graphicsDevice,{width:1,height:1,format:7}),i._defaultTexture.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.defaultTextMaterial=null,i.defaultBitmapTextMaterial=null,i.defaultScreenSpaceTextMaterial=null,i.defaultScreenSpaceBitmapTextMaterial=null,i.defaultImageMaterials=[],i.on("beforeremove",i.onRemoveComponent,j(i)),i}H(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 dt?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 ut?e.pivot.copy(i.pivot):e.pivot.set(i.pivot[0],i.pivot[1]));var s,a=Math.abs(e.anchor.x-e.anchor.z)>.001,r=Math.abs(e.anchor.y-e.anchor.w)>.001,o=!1;void 0!==i.margin&&(i.margin instanceof dt?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||a?a&&(h=!0):e.width=i.width,void 0===i.height||r?r&&(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),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===Gf?(void 0!==i.rect&&(e.rect=i.rect),void 0!==i.color&&((s=i.color)instanceof at||(s=new at(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===Wf&&(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 at||(s=new at(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===Gf&&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,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){return t?e?(this.defaultScreenSpaceTextMaterial||(this.defaultScreenSpaceTextMaterial=new jn,this.defaultScreenSpaceTextMaterial.name="defaultScreenSpaceTextMaterial",this.defaultScreenSpaceTextMaterial.msdfMap=this._defaultTexture,this.defaultScreenSpaceTextMaterial.useLighting=!1,this.defaultScreenSpaceTextMaterial.useGammaTonemap=!1,this.defaultScreenSpaceTextMaterial.useFog=!1,this.defaultScreenSpaceTextMaterial.useSkybox=!1,this.defaultScreenSpaceTextMaterial.diffuse.set(0,0,0),this.defaultScreenSpaceTextMaterial.emissive.set(1,1,1),this.defaultScreenSpaceTextMaterial.opacity=.5,this.defaultScreenSpaceTextMaterial.blendType=4,this.defaultScreenSpaceTextMaterial.depthWrite=!1,this.defaultScreenSpaceTextMaterial.depthTest=!1,this.defaultScreenSpaceTextMaterial.emissiveVertexColor=!0,this.defaultScreenSpaceTextMaterial.update()),this.defaultScreenSpaceTextMaterial):(this.defaultScreenSpaceBitmapTextMaterial||(this.defaultScreenSpaceBitmapTextMaterial=new jn,this.defaultScreenSpaceBitmapTextMaterial.name="defaultScreenSpaceBitmapTextMaterial",this.defaultScreenSpaceBitmapTextMaterial.emissive.set(.5,.5,.5),this.defaultScreenSpaceBitmapTextMaterial.emissiveMap=this._defaultTexture,this.defaultScreenSpaceBitmapTextMaterial.emissiveTint=!0,this.defaultScreenSpaceBitmapTextMaterial.opacity=.5,this.defaultScreenSpaceBitmapTextMaterial.opacityMap=this._defaultTexture,this.defaultScreenSpaceBitmapTextMaterial.opacityMapChannel="a",this.defaultScreenSpaceBitmapTextMaterial.useLighting=!1,this.defaultScreenSpaceBitmapTextMaterial.useGammaTonemap=!1,this.defaultScreenSpaceBitmapTextMaterial.useFog=!1,this.defaultScreenSpaceBitmapTextMaterial.useSkybox=!1,this.defaultScreenSpaceBitmapTextMaterial.diffuse.set(0,0,0),this.defaultScreenSpaceBitmapTextMaterial.blendType=4,this.defaultScreenSpaceBitmapTextMaterial.depthWrite=!1,this.defaultScreenSpaceBitmapTextMaterial.depthTest=!1,this.defaultScreenSpaceBitmapTextMaterial.emissiveVertexColor=!0,this.defaultScreenSpaceBitmapTextMaterial.update()),this.defaultScreenSpaceBitmapTextMaterial):e?(this.defaultTextMaterial||(this.defaultTextMaterial=new jn,this.defaultTextMaterial.name="defaultTextMaterial",this.defaultTextMaterial.msdfMap=this._defaultTexture,this.defaultTextMaterial.useLighting=!1,this.defaultTextMaterial.useGammaTonemap=!1,this.defaultTextMaterial.useFog=!1,this.defaultTextMaterial.useSkybox=!1,this.defaultTextMaterial.diffuse.set(0,0,0),this.defaultTextMaterial.emissive.set(1,1,1),this.defaultTextMaterial.opacity=.5,this.defaultTextMaterial.blendType=4,this.defaultTextMaterial.depthWrite=!1,this.defaultTextMaterial.emissiveVertexColor=!0,this.defaultTextMaterial.update()),this.defaultTextMaterial):(this.defaultBitmapTextMaterial||(this.defaultBitmapTextMaterial=new jn,this.defaultBitmapTextMaterial.name="defaultBitmapTextMaterial",this.defaultBitmapTextMaterial.emissive.set(.5,.5,.5),this.defaultBitmapTextMaterial.emissiveTint=!0,this.defaultBitmapTextMaterial.emissiveMap=this._defaultTexture,this.defaultBitmapTextMaterial.opacity=.5,this.defaultBitmapTextMaterial.opacityMap=this._defaultTexture,this.defaultBitmapTextMaterial.opacityMapChannel="a",this.defaultBitmapTextMaterial.useLighting=!1,this.defaultBitmapTextMaterial.useGammaTonemap=!1,this.defaultBitmapTextMaterial.useFog=!1,this.defaultBitmapTextMaterial.useSkybox=!1,this.defaultBitmapTextMaterial.diffuse.set(0,0,0),this.defaultBitmapTextMaterial.blendType=4,this.defaultBitmapTextMaterial.depthWrite=!1,this.defaultBitmapTextMaterial.emissiveVertexColor=!0,this.defaultBitmapTextMaterial.update()),this.defaultBitmapTextMaterial)},i._createBaseImageMaterial=function(){var t=new jn;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}(Md);Ad._buildAccessors(um.prototype,pm);var _m="free",gm="limited",vm="locked",ym=["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"],xm=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=vm,n._linearLimitsX=new ut(0,0),n._linearSpringX=!1,n._linearStiffnessX=0,n._linearDampingX=1,n._linearEquilibriumX=0,n._linearMotionY=vm,n._linearLimitsY=new ut(0,0),n._linearSpringY=!1,n._linearStiffnessY=0,n._linearDampingY=1,n._linearEquilibriumY=0,n._linearMotionZ=vm,n._linearLimitsZ=new ut(0,0),n._linearSpringZ=!1,n._linearStiffnessZ=0,n._linearDampingZ=1,n._linearEquilibriumZ=0,n._angularMotionX=vm,n._angularLimitsX=new ut(0,0),n._angularSpringX=!1,n._angularStiffnessX=0,n._angularDampingX=1,n._angularEquilibriumX=0,n._angularMotionY=vm,n._angularLimitsY=new ut(0,0),n._angularSpringY=!1,n._angularStiffnessY=0,n._angularDampingY=1,n._angularEquilibriumY=0,n._angularMotionZ=vm,n._angularLimitsZ=new ut(0,0),n._angularSpringZ=!1,n._angularEquilibriumZ=0,n._angularDampingZ=1,n._angularStiffnessZ=0,n.on("set_enabled",n._onSetEnabled,j(n)),n}H(e,t);var i=e.prototype;return i._convertTransform=function(t,e){var i=t.getTranslation(),n=new yt;n.setFromMat4(t);var s=new Ammo.btVector3(i.x,i.y,i.z),a=new Ammo.btQuaternion(n.x,n.y,n.z,n.w);e.setOrigin(s),e.setRotation(a),Ammo.destroy(s),Ammo.destroy(a)},i._updateAngularLimits=function(){var t=this._constraint;if(t){var e,i,n,s,a,r;this._angularMotionX===gm?(e=this._angularLimitsX.x*it.DEG_TO_RAD,s=this._angularLimitsX.y*it.DEG_TO_RAD):this._angularMotionX===_m?(e=1,s=0):e=s=0,this._angularMotionY===gm?(i=this._angularLimitsY.x*it.DEG_TO_RAD,a=this._angularLimitsY.y*it.DEG_TO_RAD):this._angularMotionY===_m?(i=1,a=0):i=a=0,this._angularMotionZ===gm?(n=this._angularLimitsZ.x*it.DEG_TO_RAD,r=this._angularLimitsZ.y*it.DEG_TO_RAD):this._angularMotionZ===_m?(n=1,r=0):n=r=0;var o=new Ammo.btVector3(e,i,n);t.setAngularLowerLimit(o),o.setValue(s,a,r),t.setAngularUpperLimit(o),Ammo.destroy(o)}},i._updateLinearLimits=function(){var t=this._constraint;if(t){var e,i,n,s,a,r;this._linearMotionX===gm?(e=this._linearLimitsX.x,s=this._linearLimitsX.y):this._linearMotionX===_m?(e=1,s=0):e=s=0,this._linearMotionY===gm?(i=this._linearLimitsY.x,a=this._linearLimitsY.y):this._linearMotionY===_m?(i=1,a=0):i=a=0,this._linearMotionZ===gm?(n=this._linearLimitsZ.x,r=this._linearLimitsZ.y):this._linearMotionZ===_m?(n=1,r=0):n=r=0;var o=new Ammo.btVector3(e,i,n);t.setLinearLowerLimit(o),o.setValue(s,a,r),t.setLinearUpperLimit(o),Ammo.destroy(o)}},i._createConstraint=function(){if(this._entityA&&this._entityA.rigidbody){this._destroyConstraint();var t=new vt,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 a=this._entityB.rigidbody.body;a.activate();var r=this._entityB.getWorldTransform().clone().invert();t.mul2(r,i);var o=new Ammo.btTransform;this._convertTransform(t,o),this._constraint=new Ammo.btGeneric6DofSpringConstraint(e,a,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,i=Y(ym);!(e=i()).done;){var n=e.value;t.hasOwnProperty(n)&&(t[n]instanceof ut?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")},G(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}(Ad),bm={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,a="linear"===t?0:3;"Y"===i&&(a+=1),"Z"===i&&(a+=2),Object.defineProperty(xm.prototype,n,{get:function(){return this[s]},set:function(t){this[s]!==t&&(this[s]=t,this._constraint[bm[e]](a,t))}})}))}))}));var Sm=function(){this.enabled=!0},wm=["enabled"],Tm=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="joint",i.app=e,i.ComponentType=xm,i.DataType=Sm,i.schema=wm,i}return H(e,t),e.prototype.initializeComponentData=function(t,e,i){t.initFromData(e)},e}(Md);Ad._buildAccessors(xm.prototype,wm);var Am=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 H(e,t),e}(Ad);function Mm(t){var e="_"+t;Object.defineProperty(Am.prototype,t,{get:function(){return this[e]},set:function(t){this[e]!==t&&(this[e]=t,this.fire("resize"))}})}Mm("minWidth"),Mm("minHeight"),Mm("maxWidth"),Mm("maxHeight"),Mm("fitWidthProportion"),Mm("fitHeightProportion"),Mm("excludeFromLayout");var Cm=function(){this.enabled=!0},Em=["enabled"],Pm=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="layoutchild",i.ComponentType=Am,i.DataType=Cm,i.schema=Em,i}H(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}(Md);Ad._buildAccessors(Am.prototype,Em);var Rm={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"}},Im={0:1,1:0},Lm={minWidth:0,minHeight:0,maxWidth:Number.POSITIVE_INFINITY,maxHeight:Number.POSITIVE_INFINITY,width:null,height:null,fitWidthProportion:0,fitHeightProportion:0},Dm="NONE",Om="APPLY_STRETCHING",km="APPLY_SHRINKING",Fm=new ut;function Bm(t){var e,i=Rm[t],n=Rm[Im[t]];function s(t,e){return-e[i.size]*t.pivot[i.axis]}function a(t,e){return-e[n.size]*t.pivot[n.axis]}function r(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 Dm;case 1:return e=i?km:Dm;case 3:return e=i?km:Dm;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=v(t,i.maxSize),s=g(t,i.fittingProportion),a=b(s,n),r=Fm[i.axis]-e,o=0;o=0;--n)i[e[n]]=i[e[n+1]]+t[e[n]];return i}return function(t,d){t=t.filter(o),e=d,Fm.x=e.containerSize.x-e.padding.x-e.padding.z,Fm.y=e.containerSize.y-e.padding.y-e.padding.w,function(t){for(var e=0;e0&&(a+=e.spacing[i.axis]);var h=s[o][i.size];a+=h,!r&&a>Fm[i.axis]&&0!==n[n.length-1].length&&(a=h,n.push([])),n[n.length-1].push(t[o]),r&&a>Fm[i.axis]&&o!==t.length-1&&(a=0,n.push([]))}return n}(t)),m=function(t,i){for(var s=[],a=[],r=0;ro.largestSize[n.size]&&(o.largestElement=o[d],o.largestSize=f)}s.push(o.largestElement),a.push(o.largestSize)}var p=l(a,n),m=h(e[n.fitting],p,Fm[n.axis]);m===Om?c(a,p,n):m===km&&u(a,p,n);for(var _=0;_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=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}(Md);Ad._buildAccessors(Gm.prototype,Xm);var qm=[],Ym=[],Km=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}H(e,t);var i=e.prototype;return i.addLightToLayers=function(){for(var t=0;t=0&&this.enabled&&this.entity.enabled&&t.addLight(this)},i.onLayerRemoved=function(t){this.layers.indexOf(t.id)>=0&&t.removeLight(this)},i.refreshProperties=function(){for(var t=0;t=0&&t.batcher.insert(la.MODEL,this.batchGroupId,this.entity)},i.onDisable=function(){var t=this.system.app,e=t.scene;e.off("set:layers",this.onLayersChanged,this),e.layers&&(e.layers.off("add",this.onLayerAdded,this),e.layers.off("remove",this.onLayerRemoved,this)),this._batchGroupId>=0&&t.batcher.remove(la.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=0&&e.remove(la.MODEL,this.batchGroupId,this.entity),this.entity.enabled&&t>=0&&e.insert(la.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 nl&&(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,a=0,r=e.length;a=0&&t.batcher.insert(la.RENDER,this.batchGroupId,this.entity)},i.onDisable=function(){var t=this.system.app,e=t.scene;e.off("set:layers",this.onLayersChanged,this),e.layers&&(e.layers.off("add",this.onLayerAdded,this),e.layers.off("remove",this.onLayerRemoved,this)),this._batchGroupId>=0&&t.batcher.remove(la.RENDER,this.batchGroupId,this.entity),this.removeFromLayers()},i.hide=function(){if(this._meshInstances)for(var t=0;t=0&&e.remove(la.RENDER,this.batchGroupId,this.entity),this.entity.enabled&&t>=0&&e.insert(la.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;et.length){for(var e=t.length;e=0))continue;n=this.system.app.assets.get(n)}n&&!n.resource&&this.system.app.assets.load(n)}}if(!this.emitter){var s=t.mesh;s instanceof Xs||(s=null),this.emitter=new xh(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,this.psys=new wh,this.psys.graph=this.entity,this.psys.emitter=this.emitter,this.psys.meshInstances=[this.emitter.meshInstance],t.model=this.psys,this.emitter.psys=this.psys,t.autoPlay||(this.pause(),this.emitter.meshInstance.visible=!1)}t.model&&this.emitter.colorMap&&this.addModelToLayers(),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.data.model&&(this.removeModelFromLayers(),this.data.depthSoftening&&this._releaseDepth()),this.emitter&&(this.emitter.camera=null)},i.onBeforeRemove=function(){this.enabled&&(this.enabled=!1);var t=this.data;t.model&&(this.entity.removeChild(t.model.getGraph()),t.model.destroy(),t.model=null),this.emitter&&(this.emitter.destroy(),this.emitter=null);for(var e=0;eh.fixedTimeStep&&(e=Math.floor(h.simTime/h.fixedTimeStep),h.simTime-=e*h.fixedTimeStep),e){e=Math.min(e,h.maxSubSteps);for(var v=0;vthis._pool.length)for(var e=this._pool.length;e=this._pool.length&&this._resize(2*this._pool.length),this._pool[this._count++]},e.freeAll=function(){this._count=0},t}(),M_=function(t){function e(e,i){var n;return n=t.call(this,e,i)||this,"undefined"==typeof Ammo||v_||(v_=new Ammo.btTransform,y_=new Ammo.btVector3,x_=new Ammo.btVector3,b_=new Ammo.btQuaternion,S_=new Ammo.btVector3(0,0,0)),n._angularDamping=0,n._angularFactor=new lt(1,1,1),n._angularVelocity=new lt,n._body=null,n._friction=.5,n._group=2,n._linearDamping=0,n._linearFactor=new lt(1,1,1),n._linearVelocity=new lt,n._mask=yp,n._mass=1,n._restitution=0,n._rollingFriction=0,n._simulationEnabled=!1,n._type=mp,n}H(e,t);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===_p?this._mass:0;this._getEntityTransform(v_);var n=this.system.createBody(i,t,v_);if(n.setRestitution(this._restitution),n.setFriction(this._friction),n.setRollingFriction(this._rollingFriction),n.setDamping(this._linearDamping,this._angularDamping),this._type===_p){var s=this._linearFactor;y_.setValue(s.x,s.y,s.z),n.setLinearFactor(y_);var a=this._angularFactor;y_.setValue(a.x,a.y,a.z),n.setAngularFactor(y_)}else this._type===gp&&(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 _p:this.system._dynamic.push(this),e.forceActivationState(1),this.syncEntityToBody();break;case gp:this.system._kinematic.push(this),e.forceActivationState(4);break;case mp: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(){var t,e,i,n,s,a;switch(arguments.length){case 1:t=arguments[0].x,e=arguments[0].y,i=arguments[0].z;break;case 2:t=arguments[0].x,e=arguments[0].y,i=arguments[0].z,n=arguments[1].x,s=arguments[1].y,a=arguments[1].z;break;case 3:t=arguments[0],e=arguments[1],i=arguments[2];break;case 6:t=arguments[0],e=arguments[1],i=arguments[2],n=arguments[3],s=arguments[4],a=arguments[5]}var r=this._body;r&&(r.activate(),y_.setValue(t,e,i),void 0!==n?(x_.setValue(n,s,a),r.applyForce(y_,x_)):r.applyForce(y_,S_))},i.applyTorque=function(){var t,e,i;switch(arguments.length){case 1:t=arguments[0].x,e=arguments[0].y,i=arguments[0].z;break;case 3:t=arguments[0],e=arguments[1],i=arguments[2];break;default:return}var n=this._body;n&&(n.activate(),y_.setValue(t,e,i),n.applyTorque(y_))},i.applyImpulse=function(){var t,e,i,n,s,a;switch(arguments.length){case 1:t=arguments[0].x,e=arguments[0].y,i=arguments[0].z;break;case 2:t=arguments[0].x,e=arguments[0].y,i=arguments[0].z,n=arguments[1].x,s=arguments[1].y,a=arguments[1].z;break;case 3:t=arguments[0],e=arguments[1],i=arguments[2];break;case 6:t=arguments[0],e=arguments[1],i=arguments[2],n=arguments[3],s=arguments[4],a=arguments[5];break;default:return}var r=this._body;r&&(r.activate(),y_.setValue(t,e,i),void 0!==n?(x_.setValue(n,s,a),r.applyImpulse(y_,x_)):r.applyImpulse(y_,S_))},i.applyTorqueImpulse=function(){var t,e,i;switch(arguments.length){case 1:t=arguments[0].x,e=arguments[0].y,i=arguments[0].z;break;case 3:t=arguments[0],e=arguments[1],i=arguments[2];break;default:return}var n=this._body;n&&(n.activate(),y_.setValue(t,e,i),n.applyTorqueImpulse(y_))},i.isStatic=function(){return this._type===mp},i.isStaticOrKinematic=function(){return this._type===mp||this._type===gp},i.isKinematic=function(){return this._type===gp},i._getEntityTransform=function(t){var e=this.entity,i=e.getPosition(),n=e.getRotation();y_.setValue(i.x,i.y,i.z),b_.setValue(n.x,n.y,n.z,n.w),t.setOrigin(y_),t.setRotation(b_)},i.syncEntityToBody=function(){var t=this._body;if(t){if(this._getEntityTransform(v_),t.setWorldTransform(v_),this._type===gp){var e=t.getMotionState();e&&e.setWorldTransform(v_)}t.activate()}},i._updateDynamic=function(){var t=this._body;if(t.isActive()){var e=t.getMotionState();if(e){e.getWorldTransform(v_);var i=v_.getOrigin(),n=v_.getRotation();this.entity.setPosition(i.x(),i.y(),i.z()),this.entity.setRotation(n.x(),n.y(),n.z(),n.w())}}},i._updateKinematic=function(){var t=this._body.getMotionState();t&&(this._getEntityTransform(v_),t.setWorldTransform(v_))},i.teleport=function(){arguments.length<3?(arguments[0]&&this.entity.setPosition(arguments[0]),arguments[1]&&(arguments[1]instanceof yt?this.entity.setRotation(arguments[1]):this.entity.setEulerAngles(arguments[1]))):(6===arguments.length&&this.entity.setEulerAngles(arguments[3],arguments[4],arguments[5]),this.entity.setPosition(arguments[0],arguments[1],arguments[2])),this.syncEntityToBody()},i.onEnable=function(){this._body||this.createBody(),this.enableSimulation()},i.onDisable=function(){this.disableSimulation()},G(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===_p&&(y_.setValue(t.x,t.y,t.z),this._body.setAngularFactor(y_)))}},{key:"angularVelocity",get:function(){if(this._body&&this._type===_p){var t=this._body.getAngularVelocity();this._angularVelocity.set(t.x(),t.y(),t.z())}return this._angularVelocity},set:function(t){this._body&&this._type===_p&&(this._body.activate(),y_.setValue(t.x,t.y,t.z),this._body.setAngularVelocity(y_),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===_p&&(y_.setValue(t.x,t.y,t.z),this._body.setLinearFactor(y_)))}},{key:"linearVelocity",get:function(){if(this._body&&this._type===_p){var t=this._body.getLinearVelocity();this._linearVelocity.set(t.x(),t.y(),t.z())}return this._linearVelocity},set:function(t){this._body&&this._type===_p&&(this._body.activate(),y_.setValue(t.x,t.y,t.z),this._body.setLinearVelocity(y_),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===_p)){var e=this.enabled&&this.entity.enabled;e&&this.disableSimulation(),this._body.getCollisionShape().calculateLocalInertia(t,y_),this._body.setMassProps(t,y_),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 _p:this._group=1,this._mask=vp;break;case gp:this._group=4,this._mask=vp;break;case mp:default:this._group=2,this._mask=yp}this.createBody()}}}]),e}(Ad),C_=function(){this.enabled=!0},E_=function(t,e,i){this.entity=t,this.point=e,this.normal=i},P_=function(t,e,i){0===arguments.length?(this.a=null,this.b=null,this.impulse=0,this.localPointA=new lt,this.localPointB=new lt,this.pointA=new lt,this.pointB=new lt,this.normal=new lt):(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)},R_=function(t,e,i,n,s,a){void 0===t&&(t=new lt),void 0===e&&(e=new lt),void 0===i&&(i=new lt),void 0===n&&(n=new lt),void 0===s&&(s=new lt),void 0===a&&(a=0),this.localPoint=t,this.localPointOther=e,this.point=i,this.pointOther=n,this.normal=s,this.impulse=a},I_=function(t,e){this.other=t,this.contacts=e},L_=["enabled"],D_=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="rigidbody",i._stats=e.stats.frame,i.ComponentType=M_,i.DataType=C_,i.contactPointPool=null,i.contactResultPool=null,i.singleContactResultPool=null,i.schema=L_,i.maxSubSteps=10,i.fixedTimeStep=1/60,i.gravity=new lt(0,-9.81,0),i._dynamic=[],i._kinematic=[],i._triggers=[],i._compounds=[],i.collisions={},i.frameCollisions={},i.on("beforeremove",i.onBeforeRemove,j(i)),i.on("remove",i.onRemove,j(i)),i}H(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)}w_=new Ammo.btVector3,T_=new Ammo.btVector3,this.contactPointPool=new A_(R_,1),this.contactResultPool=new A_(I_,1),this.singleContactResultPool=new A_(P_,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,a=["mass","linearDamping","angularDamping","linearFactor","angularFactor","friction","rollingFriction","restitution","type","group","mask"];s2){var h=arguments[2];h(i)}}}return Ammo.destroy(n),i},i.raycastAll=function(t,e){var i=[];w_.setValue(t.x,t.y,t.z),T_.setValue(e.x,e.y,e.z);var n=new Ammo.AllHitsRayResultCallback(w_,T_);if(this.dynamicsWorld.rayTest(w_,T_,n),n.hasHit())for(var s=n.get_m_collisionObjects(),a=n.get_m_hitPointWorld(),r=n.get_m_hitNormalWorld(),o=s.size(),h=0;h0)if(4&d||4&f){var v=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")),b=u.rigidbody&&(u.rigidbody.hasEvent("triggerenter")||u.rigidbody.hasEvent("triggerleave"));v&&(!(g=this._storeCollision(c,u))||4&f||c.collision.fire("triggerenter",u)),y&&(!(g=this._storeCollision(u,c))||4&d||u.collision.fire("triggerenter",c)),x&&(g||(g=this._storeCollision(u,c)),g&&c.rigidbody.fire("triggerenter",u)),b&&(g||(g=this._storeCollision(c,u)),g&&u.rigidbody.fire("triggerenter",c))}else{var S=this._hasContactEvent(c),w=this._hasContactEvent(u),T=this.hasEvent("contact");if(T||S||w){for(var A=0;A=0&&i!==t.element.drawOrder&&this.system.app.batcher.markGroupDirty(t.element._batchGroupId)}t.particlesystem&&(t.particlesystem.drawOrder=e++);for(var n=t.children,s=0;s255&&(t=255),this._priority=t}}]),e}(Ad),N_=function(){this.enabled=!0},U_=["enabled"],z_=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="screen",i.ComponentType=B_,i.DataType=N_,i.schema=U_,i.windowResolution=new ut,i._drawOrderSyncQueue=new z,i.app.graphicsDevice.on("resizecanvas",i._onResize,j(i)),i.app.systems.on("update",i._onUpdate,j(i)),i.on("beforeremove",i.onRemoveComponent,j(i)),i}H(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 ut?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 ut?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=3&&i.length<=4){for(var u=0;ui.ind&&(h=i.ind),this._insertScriptInstance(r,h,o),this._scriptsIndex[a]={instance:r,onSwap:function(){n.swap(a)}},this[a]=r,i.preloading||r.__initializeAttributes(),this.fire("create",a,r),this.fire("create:"+a,r),this.system.app.scripts.on("swap:"+a,this._scriptsIndex[a].onSwap),i.preloading||(r.enabled&&!r._initialized&&(r._initialized=!0,r.initialize&&this._scriptMethod(r,e.scriptMethods.initialize)),r.enabled&&!r._postInitialized&&(r._postInitialized=!0,r.postInitialize&&this._scriptMethod(r,e.scriptMethods.postInitialize))),r}console.warn("script '"+a+"' is already added to entity '"+this.entity.name+"'")}else this._scriptsIndex[a]={awaiting:!0,ind:this._scripts.length},console.warn("script '"+a+"' is not found, awaiting it to be added to registry");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 a=this._removeScriptInstance(s);a>=0&&this._resetExecutionOrder(a,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 i=t,n=t;"string"==typeof n?n=this.system.app.scripts.get(n):n&&(i=n.__name);var s=this._scriptsIndex[i];if(!s||!s.instance)return!1;var a=s.instance,r=this._scripts.indexOf(a),o=new n({app:this.system.app,entity:this.entity,enabled:a.enabled,attributes:a.__attributes});return!!o.swap&&(o.__initializeAttributes(),this._scripts[r]=o,this._scriptsIndex[i].instance=o,this[i]=o,o.__executionOrder=r,a.update&&this._updateList.remove(a),a.postUpdate&&this._postUpdateList.remove(a),o.update&&this._updateList.insert(o),o.postUpdate&&this._postUpdateList.insert(o),this._scriptMethod(o,e.scriptMethods.swap,a),this.fire("swap",i,o),this.fire("swap:"+i,o),!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 a=t._scriptsIndex[n];if(a&&a.instance){var r=i[n].__attributesRaw,o=i[n].__attributes;if(r||o){var h=!!r,l=a.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,r||o,e);else if("json"===u.type&&Array.isArray(u.schema))for(var d=l[c],f=r?r[c]:o[c],p=0;p=i||e<0)return!1;var n=t,s=t;"string"!=typeof s?s=t.__name:n=null;var a=this._scriptsIndex[s];if(!a||!a.instance)return!1;var r=a.instance;if(n&&!(r instanceof n))return!1;var o=this._scripts.indexOf(r);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,r,e,o),this.fire("move:"+s,r,e,o),!0)},G(e,[{key:"enabled",get:function(){return this._enabled},set:function(t){var e=this._enabled;this._enabled=t,this.fire("set","enabled",e,t)}},{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(!H_.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)}}}]),e}(Ad);X_.scriptMethods={initialize:"initialize",postInitialize:"postInitialize",update:"update",postUpdate:"postUpdate",swap:"swap"};var j_=function(){this.enabled=!0},q_=0,Y_=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="script",i.ComponentType=X_,i.DataType=j_,i._components=new Z({sortBy:"_executionOrder"}),i._enabledComponents=new Z({sortBy:"_executionOrder"}),i.preloading=!0,i.on("beforeremove",i._onBeforeRemove,j(i)),i.app.systems.on("initialize",i._onInitialize,j(i)),i.app.systems.on("postInitialize",i._onPostInitialize,j(i)),i.app.systems.on("update",i._onUpdate,j(i)),i.app.systems.on("postUpdate",i._onPostUpdate,j(i)),i}H(e,t);var i=e.prototype;return i.initializeComponentData=function(t,e){if(t._executionOrder=q_++,this._components.append(t),q_>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=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}(Md),K_=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this).on("set_scripts",n.onSetScripts,j(n)),n}H(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=0&&this.instancesWithUpdate.splice(s,1)}if(n.fixedUpdate){var a=this.instancesWithFixedUpdate.indexOf(n);a>=0&&this.instancesWithFixedUpdate.splice(a,1)}if(n.postUpdate){var r=this.instancesWithPostUpdate.indexOf(n);r>=0&&this.instancesWithPostUpdate.splice(r,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,J_),t.data.postInitialized=!0},i._updateInstances=function(t,e,i){for(var n=0,s=e.length;n0){var i=lg.sub(og).dot(cg)/e,n=og.add(hg.mulScalar(i));return ug.copy(this._element.entity.getRotation()).invert().transformVector(n,n),n.mul(this._dragScale),n}return null},i._determineInputPosition=function(t){var e=this._app.graphicsDevice.maxPixelRatio;void 0!==t.x&&void 0!==t.y?(ag.x=t.x*e,ag.y=t.y*e):t.changedTouches?(ag.x=t.changedTouches[0].x*e,ag.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?(og.set(ag.x,-ag.y,0),hg.set(0,0,-1)):(rg.copy(this._dragCamera.screenToWorld(ag.x,ag.y,1)),og.copy(this._dragCamera.entity.getPosition()),hg.copy(rg).sub(og).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=1/s.z},i._onMove=function(t){if(this._element&&this._isDragging&&this.enabled&&this._element.enabled&&this._element.entity.enabled){var e=this._screenToLocal(t);if(this._dragStartMousePosition&&e){if(this._deltaMousePosition.copy(e).sub(this._dragStartMousePosition),this._deltaHandlePosition.copy(this._dragStartHandlePosition).add(this._deltaMousePosition),this._axis){var i=this._element.entity.getLocalPosition(),n=dg[this._axis];this._deltaHandlePosition[n]=i[n]}this._element.entity.setLocalPosition(this._deltaHandlePosition),this.fire("drag:move",this._deltaHandlePosition)}}},i.destroy=function(){this._toggleLifecycleListeners("off"),this._toggleDragListeners("off")},G(e,[{key:"enabled",get:function(){return this._enabled},set:function(t){this._enabled=t}},{key:"isDragging",get:function(){return this._isDragging}}]),e}(u),pg="mouse",mg="keyboard",_g="gamepad",gg="mousedown",vg="mousemove",yg="mouseup",xg="mousewheel",bg=new ut,Sg=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._viewportReference=new zf(j(n),"viewportEntity",{"element#gain":n._onViewportElementGain,"element#resize":n._onSetContentOrViewportSize}),n._contentReference=new zf(j(n),"contentEntity",{"element#gain":n._onContentElementGain,"element#lose":n._onContentElementLose,"element#resize":n._onSetContentOrViewportSize}),n._scrollbarUpdateFlags={},n._scrollbarReferences={},n._scrollbarReferences[0]=new zf(j(n),"horizontalScrollbarEntity",{"scrollbar#set:value":n._onSetHorizontalScrollbarValue,"scrollbar#gain":n._onHorizontalScrollbarGain}),n._scrollbarReferences[1]=new zf(j(n),"verticalScrollbarEntity",{"scrollbar#set:value":n._onSetVerticalScrollbarValue,"scrollbar#gain":n._onVerticalScrollbarGain}),n._prevContentSizes={},n._prevContentSizes[0]=null,n._prevContentSizes[1]=null,n._scroll=new ut,n._velocity=new lt,n._dragStartPosition=new lt,n._disabledContentInput=!1,n._disabledContentInputEntities=[],n._toggleLifecycleListeners("on",e),n._toggleElementListeners("on"),n}H(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](xg,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 fg(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=!1;n|=this._updateAxis(t,"x",0),(n|=this._updateAxis(e,"y",1))&&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 it.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],a=this._getContentSize(t);if(null!==s&&Math.abs(s-a)>1e-4){var r=this._getMaxOffset(t,s),o=this._getMaxOffset(t,a);this._scroll[e]=0===o?1:it.clamp(this._scroll[e]*r/o,0,1)}var h=this._scroll[e]*this._getMaxOffset(t),l=n.getLocalPosition();l[e]=h*i,n.setLocalPosition(l),this._prevContentSizes[t]=a}},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 bg.x=0===e?0:t.x/e,bg.y=0===i?0:t.y/-i,bg},i._getMaxOffset=function(t,e){e=void 0===e?this._getContentSize(t):e;var i=this._getViewportSize(t);return e1e-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=it.clamp(this._scroll.x+i,0,this._getMaxScrollValue(0)),a=it.clamp(this._scroll.y+n,0,this._getMaxScrollValue(1));this.scroll=new ut(s,a)}},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,a=n.length;s1e-5&&(this.data.value=it.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=it.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}(Ad),Cg=function(){this.enabled=!0},Eg=[{name:"enabled",type:"boolean"},{name:"orientation",type:"number"},{name:"value",type:"number"},{name:"handleSize",type:"number"},{name:"handleEntity",type:"entity"}],Pg=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="scrollbar",i.ComponentType=Mg,i.DataType=Cg,i.schema=Eg,i.on("beforeremove",i._onRemoveComponent,j(i)),i}H(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){t.prototype.initializeComponentData.call(this,e,i,Eg)},i._onRemoveComponent=function(t,e){e.onRemove()},e}(Md);Ad._buildAccessors(Mg.prototype,Eg);function Rg(t,e){return t%e||0}var Ig=function(t){function e(e,i,n){var s;return(s=t.call(this)||this)._manager=e,s._volume=void 0!==n.volume?it.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=!1,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.source=null,s._onPlayCallback=n.onPlay,s._onPauseCallback=n.onPause,s._onResumeCallback=n.onResume,s._onStopCallback=n.onStop,s._onEndCallback=n.onEnd,Ah()?(s._startedAt=0,s._currentTime=0,s._currentOffset=0,s._inputNode=null,s._connectorNode=null,s._firstNode=null,s._lastNode=null,s._initializeNodes(),s._endedHandler=s._onEnded.bind(j(s))):(s._isReady=!1,s._loadedMetadataHandler=s._onLoadedMetadata.bind(j(s)),s._timeUpdateHandler=s._onTimeUpdate.bind(j(s)),s._endedHandler=s._onEnded.bind(j(s)),s._createSource()),s}H(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?this._suspendEndEvent=!1:(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())},G(e,[{key:"loop",get:function(){return this._loop},set:function(t){this._loop=!!t,this.source&&(this.source.loop=this._loop)}},{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:"duration",get:function(){return this._sound?this._duration?Rg(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:"isPlaying",get:function(){return 0===this._state}},{key:"isPaused",get:function(){return 1===this._state}},{key:"isStopped",get:function(){return 2===this._state}},{key:"isSuspended",get:function(){return this._suspended}}]),e}(u);Ah()?(Object.assign(Ig.prototype,{_initializeNodes:function(){this.gain=this._manager.context.createGain(),this._inputNode=this.gain,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination)},play:function(){2!==this._state&&this.stop(),this.source||this._createSource();var t=Rg(this._startOffset,this.duration);return t=Rg(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._state=0,this._playWhenLoaded=!1,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._manager.suspended&&this._onManagerSuspend(),this._suspendInstanceEvents||this._onPlay(),!0},pause:function(){return this._playWhenLoaded=!1,!(0!==this._state||!this.source)&&(this._updateCurrentTime(),this._state=1,this._suspendEndEvent=!0,this.source.stop(0),this.source=null,this._startOffset=null,this._suspendInstanceEvents||this._onPause(),!0)},resume:function(){if(1!==this._state)return!1;this.source||this._createSource();var t=this.currentTime;return null!==this._startOffset&&(t=Rg(this._startOffset,this.duration),t=Rg(this._startTime+t,this._sound.duration),this._startOffset=null),this._duration?this.source.start(0,t,this._duration):this.source.start(0,t),this._state=0,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},stop:function(){return this._playWhenLoaded=!1,!(2===this._state||!this.source)&&(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=!0,0===this._state&&this.source.stop(0),this.source=null,this._state=2,this._suspendInstanceEvents||this._onStop(),!0)},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")},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)},getExternalNodes:function(){return[this._firstNode,this._lastNode]},_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=Rg(this._startTime,this.source.buffer.duration),this._duration&&(this.source.loopEnd=Math.max(this.source.loopStart,Rg(this._startTime+this._duration,this.source.buffer.duration)))),this.source},_updateCurrentTime:function(){this._currentTime=Rg((this._manager.context.currentTime-this._startedAt)*this._pitch+this._currentOffset,this.duration)},_onManagerDestroy:function(){this.source&&0===this._state&&(this.source.stop(0),this.source=null)}}),Object.defineProperty(Ig.prototype,"volume",{get:function(){return this._volume},set:function(t){t=it.clamp(t,0,1),this._volume=t,this.gain&&(this.gain.gain.value=t*this._manager.volume)}}),Object.defineProperty(Ig.prototype,"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)}}),Object.defineProperty(Ig.prototype,"sound",{get:function(){return this._sound},set:function(t){this._sound=t,2!==this._state?this.stop():this._createSource()}}),Object.defineProperty(Ig.prototype,"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}})):(Object.assign(Ig.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=!0,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=!0,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=Rg(this._startOffset,this.duration);t=Rg(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>Rg(this._startTime+this._duration,this.source.duration)&&(this.loop?this.source.currentTime=Rg(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(Ig.prototype,"volume",{get:function(){return this._volume},set:function(t){t=it.clamp(t,0,1),this._volume=t,this.source&&(this.source.volume=t*this._manager.volume)}}),Object.defineProperty(Ig.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(Ig.prototype,"sound",{get:function(){return this._sound},set:function(t){this.stop(),this._sound=t}}),Object.defineProperty(Ig.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=Rg(this._startTime+Rg(t,this.duration),this._sound.duration),this._startOffset=null))}}));var Lg=function(t){function e(e,i,n){var s;return s=t.call(this,e,i,n)||this,n=n||{},s._position=new lt,n.position&&(s.position=n.position),s._velocity=new lt,n.velocity&&(s.velocity=n.velocity),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:Ch,s}return H(e,t),e}(Ig);if(Ah())Object.assign(Lg.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)}}),Object.defineProperty(Lg.prototype,"position",{get:function(){return this._position},set:function(t){this._position.copy(t),this.panner.setPosition(t.x,t.y,t.z)}}),Object.defineProperty(Lg.prototype,"velocity",{get:function(){return this._velocity},set:function(t){this._velocity.copy(t),this.panner.setVelocity(t.x,t.y,t.z)}}),Object.defineProperty(Lg.prototype,"maxDistance",{get:function(){return this.panner.maxDistance},set:function(t){this.panner.maxDistance=t}}),Object.defineProperty(Lg.prototype,"refDistance",{get:function(){return this.panner.refDistance},set:function(t){this.panner.refDistance=t}}),Object.defineProperty(Lg.prototype,"rollOffFactor",{get:function(){return this.panner.rolloffFactor},set:function(t){this.panner.rolloffFactor=t}}),Object.defineProperty(Lg.prototype,"distanceModel",{get:function(){return this.panner.distanceModel},set:function(t){this.panner.distanceModel=t}});else{var Dg=new lt;Object.defineProperty(Lg.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,a){var r=(Dg=Dg.sub2(t,e)).length();if(rn)return 0;var o=0;return a===Ch?o=1-s*(r-i)/(n-i):a===Eh?o=i/(i+s*(r-i)):a===Ph&&(o=Math.pow(r/i,-s)),it.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(Lg.prototype,"velocity",{get:function(){return this._velocity},set:function(t){this._velocity.copy(t)}}),Object.defineProperty(Lg.prototype,"maxDistance",{get:function(){return this._maxDistance},set:function(t){this._maxDistance=t}}),Object.defineProperty(Lg.prototype,"refDistance",{get:function(){return this._refDistance},set:function(t){this._refDistance=t}}),Object.defineProperty(Lg.prototype,"rollOffFactor",{get:function(){return this._rollOffFactor},set:function(t){this._rollOffFactor=t}}),Object.defineProperty(Lg.prototype,"distanceModel",{get:function(){return this._distanceModel},set:function(t){this._distanceModel=t}})}var Og={volume:0,pitch:0,loop:!1,startTime:0,duration:0,position:new lt,maxDistance:0,refDistance:0,rollOffFactor:0,distanceModel:0,onPlay:null,onPause:null,onResume:null,onStop:null,onEnd:null},kg=function(t){function e(e,i,n){var s;return void 0===i&&(i="Untitled"),void 0===n&&(n={}),(s=t.call(this)||this)._component=e,s._assets=e.system.app.assets,s._manager=e.system.manager,s.name=i,s._volume=void 0!==n.volume?it.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 nl&&(s._asset=s._asset.id),s._onInstancePlayHandler=s._onInstancePlay.bind(j(s)),s._onInstancePauseHandler=s._onInstancePause.bind(j(s)),s._onInstanceResumeHandler=s._onInstanceResume.bind(j(s)),s._onInstanceStopHandler=s._onInstanceStop.bind(j(s)),s._onInstanceEndHandler=s._onInstanceEnd.bind(j(s)),s.instances=[],s}H(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=0;a--){var r=s[a].isPlaying||s[a].isSuspended,o=s[a].currentTime;r&&s[a].stop();var h=n._createInstance();r&&(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 kg?n[t[s].name]=t[s]:t[s].name&&(n[t[s].name]=new kg(this,t[s].name,t[s]));this._slots=n,this.enabled&&this.entity.enabled&&this.onEnable()}}]),e}(Ad);function Bg(t,e){Object.defineProperty(Fg.prototype,t,{get:function(){return this[e]},set:function(i){this[e]=i;var n=this._slots;for(var s in n){var a=n[s];if(!a.overlap)for(var r=a.instances,o=0,h=r.length;on||i<0;this._setTime(i);var a=this.frame;(a=this._sprite?Math.floor(this._sprite.frameKeys.length*this._time/n):0)!==this._frame&&this._setFrame(a),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=it.clamp(t,0,this._sprite.frameKeys.length-1):this._frame=t,this._component.currentClip===this&&this._component._showFrame(this._frame)},i._destroy=function(){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))},G(e,[{key:"spriteAsset",get:function(){return this._spriteAsset},set:function(t){var e=this._component.system.app.assets,i=t;if(t instanceof nl&&(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:"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:"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:"isPlaying",get:function(){return this._playing}},{key:"isPaused",get:function(){return this._paused}},{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:"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}(u),Xg="texture_emissiveMap",jg="texture_opacityMap",qg="material_emissive",Yg="material_opacity",Kg=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._type=Gg,n._material=e.defaultMaterial,n._color=new at(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 ut(1,1),n._outerScaleUniform=new Float32Array(2),n._innerOffset=new dt,n._innerOffsetUniform=new Float32Array(4),n._atlasRect=new dt,n._atlasRectUniform=new Float32Array(4),n._batchGroupId=-1,n._batchGroup=null,n._node=new qi,n._model=new wh,n._model.graph=n._node,n._meshInstance=null,i.addChild(n._model.graph),n._model._entity=i,n._updateAabbFunc=n._updateAabb.bind(j(n)),n._addedModel=!1,n._autoPlayClip=null,n._clips={},n._defaultClip=new Hg(j(n),{name:n.entity.name,fps:0,loop:!1,spriteAsset:null}),n._currentClip=n._defaultClip,n}H(e,t);var i=e.prototype;return 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)),this._showModel(),this._autoPlayClip&&this._tryAutoPlay(),this._batchGroupId>=0&&t.batcher.insert(la.SPRITE,this._batchGroupId,this.entity)},i.onDisable=function(){var t=this.system.app,e=t.scene;e.off("set:layers",this._onLayersChanged,this),e.layers&&(e.layers.off("add",this._onLayerAdded,this),e.layers.off("remove",this._onLayerRemoved,this)),this.stop(),this._hideModel(),this._batchGroupId>=0&&t.batcher.remove(la.SPRITE,this._batchGroupId,this.entity)},i.onDestroy=function(){for(var t in this._currentClip=null,this._defaultClip&&(this._defaultClip._destroy(),this._defaultClip=null),this._clips)this._clips[t]._destroy();this._clips=null,this._hideModel(),this._model=null,this._node&&(this._node.parent&&this._node.parent.removeChild(this._node),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=0&&this.system.app.batcher.remove(la.SPRITE,e,this.entity),this.entity.enabled&&t>=0?this.system.app.batcher.insert(la.SPRITE,t,this.entity):e>=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 Hg?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}(Ad),Zg=function(){this.enabled=!0},$g=["enabled"],Qg=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="sprite",i.ComponentType=Kg,i.DataType=Zg,i.schema=$g,i._defaultTexture=null,i._defaultMaterial=null,i._default9SlicedMaterialSlicedMode=null,i._default9SlicedMaterialTiledMode=null,i.app.systems.on("update",i.onUpdate,j(i)),i.on("beforeremove",i.onBeforeRemove,j(i)),i}H(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&&(i.color instanceof at?e.color.set(i.color.r,i.color.g,i.color.b,void 0!==i.opacity?i.opacity:1):e.color.set(i.color[0],i.color[1],i.color[2],void 0!==i.opacity?i.opacity:1),e.color=e.color),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 s in i.clips)e.addClip(i.clips[s]);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,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()},G(e,[{key:"defaultMaterial",get:function(){if(!this._defaultMaterial){var t=new Mi(this.app.graphicsDevice,{width:1,height:1,format:7}),e=new Uint8Array(t.lock());e[0]=e[1]=e[2]=e[3]=255,t.name="sprite",t.unlock();var i=new jn;i.diffuse.set(0,0,0),i.emissive.set(.5,.5,.5),i.emissiveMap=t,i.emissiveMapTint=!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=0,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}(Md);Ad._buildAccessors(Kg.prototype,$g);var Jg=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._oldState=!0,n._size=new lt,n.on("set_enabled",n._onSetEnabled,j(n)),n}H(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")},G(e,[{key:"size",get:function(){return this._size},set:function(t){t instanceof lt?this._size.copy(t):t instanceof Array&&t.length>=3&&this.size.set(t[0],t[1],t[2])}}]),e}(Ad),tv=function(){this.enabled=!0},ev=["enabled"],iv=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="zone",i.ComponentType=Jg,i.DataType=tv,i.schema=ev,i.on("beforeremove",i._onBeforeRemove,j(i)),i}H(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 lt?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}(Md);Ad._buildAccessors(Jg.prototype,ev);var nv=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 G(t,[{key:"scene",get:function(){return zs().scene._stats}},{key:"lightmapper",get:function(){return zs().lightmapper.stats}},{key:"batcher",get:function(){return zs().batcher._stats}}]),t}(),sv=function(){function t(t,e){this.name=t,this.url=e,this.data=null,this._loading=!1,this._onLoadedCallbacks=[]}return G(t,[{key:"loaded",get:function(){return!!this.data}},{key:"loading",get:function(){return this._loading}}]),t}(),av=function(){function t(t){this._app=t,this._list=[],this._index={},this._urlIndex={}}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 sv(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;n0&&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 ho(this.graphicsDevice,"application"),n={};for(var s in t.layers){var a=t.layers[s];a.id=parseInt(s,10),a.enabled=1!==a.id,n[s]=new io(a)}for(var r=0,o=t.layerOrder.length;r0,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;sn._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[5]-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.instancingTime=this.renderer._instancingTime,t.lightClusters=this.renderer._lightClusters,t.lightClustersTime=this.renderer._lightClustersTime,t.otherPrimitives=0;for(var i=0;ii/n?e=(t=i)/s:t=(e=n)*s}else this._fillMode===Ou&&(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(){if(this._allowResize&&!this.xr.active&&this._resolutionMode===Fu){var t=this.graphicsDevice.canvas;this.graphicsDevice.resizeCanvas(t.clientWidth,t.clientHeight)}},n.onLibrariesLoaded=function(){this._librariesLoaded=!0,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){if(t){var e=this.graphicsDevice;t.ready((function(t){Eo.set(e,t.resource)})),this.assets.load(t)}},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.enableVr=function(){this.vr||(this.vr=new Uu(this))},n.disableVr=function(){this.vr&&(this.vr.destroy(),this.vr=null)},n._firstBake=function(){this.lightmapper.bake(null,this.scene.lightmapMode)},n._firstBatch=function(){this.batcher.generate()},n._processTimestamp=function(t){return t},n._getDefaultDrawLayer=function(){return this.scene.layers.getLayerById(3)},n.drawLine=function(t,e,i,n,s){void 0===i&&(i=at.WHITE),void 0===n&&(n=!0),void 0===s&&(s=this._getDefaultDrawLayer()),this._immediate.getBatch(s,n).addLines([t,e],[i,i])},n.drawLines=function(t,e,i,n){void 0===i&&(i=!0),void 0===n&&(n=this._getDefaultDrawLayer()),this._immediate.getBatch(n,i).addLines(t,e)},n.drawLineArrays=function(t,e,i,n){void 0===i&&(i=!0),void 0===n&&(n=this._getDefaultDrawLayer()),this._immediate.getBatch(n,i).addLinesArrays(t,e)},n.drawWireSphere=function(t,e,i,n,s,a){void 0===i&&(i=at.WHITE),void 0===n&&(n=20),void 0===s&&(s=!0),void 0===a&&(a=this._getDefaultDrawLayer()),this._immediate.drawWireSphere(t,e,i,n,s,a)},n.drawWireAlignedBox=function(t,e,i,n,s){void 0===i&&(i=at.WHITE),void 0===n&&(n=!0),void 0===s&&(s=this._getDefaultDrawLayer()),this._immediate.drawWireAlignedBox(t,e,i,n,s)},n.drawMeshInstance=function(t,e){void 0===e&&(e=this._getDefaultDrawLayer()),this._immediate.drawMesh(null,null,null,t,e)},n.drawMesh=function(t,e,i,n){void 0===n&&(n=this._getDefaultDrawLayer()),this._immediate.drawMesh(e,i,t,null,n)},n.drawQuad=function(t,e,i){void 0===i&&(i=this._getDefaultDrawLayer()),this._immediate.drawMesh(e,t,this._immediate.getQuadMesh(),null,i)},n.drawTexture=function(t,e,i,n,s,a,r){void 0===r&&(r=this._getDefaultDrawLayer());var o=new vt;o.setTRS(new lt(t,e,0),yt.IDENTITY,new lt(i,n,0)),a||((a=new On).setParameter("colorMap",s),a.shader=this._immediate.getTextureShader(),a.update()),this.drawQuad(o,a,r)},n.drawDepthTexture=function(t,e,i,n,s){void 0===s&&(s=this._getDefaultDrawLayer());var a=new On;a.shader=this._immediate.getDepthTextureShader(),a.update(),this.drawTexture(t,e,i,n,null,a,s)},n.destroy=function(){if(this._inFrameUpdate)this._destroyRequested=!0;else{var t=this.graphicsDevice.canvas.id;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.controller&&(this.controller=null),this.systems.destroy(),this.scene.layers&&this.scene.layers.destroy();for(var e=this.assets.list(),n=0;n0&&e.push(new mv(t,l))}}for(var d=0;d0){var c=1===e?2:1;this.setLightmaping(o,!1,c),this.initBake(i),this.bakeInternal(c,o,h);var u=64;1===e&&(u|=Lt),this.scene.ambientBake&&(u|=Bt),this.setLightmaping(o,!0,c,u),this.finishBake(o)}var d=Q();this.stats.totalRenderTime=d-n,this.stats.shadersLinked=i._shaderStats.linked-s,this.stats.compileTime=i._shaderStats.compileTime-r,this.stats.fboTime=i._renderTargetCreationTime-a,this.stats.lightmapCount=o.length},e.allocateTextures=function(t,e){for(var i=0;i0){e.copy(t[0].aabb);for(var i=1;i1&&y>1&&(y=1);for(var x=0;x1&&g.prepareVirtualLight(x,y),g.startBake();var b=!1,S=this.lightCameraPrepare(s,g);for(p=0;p0&&x>0)&&!(v&&f>0);f++){var T=w.renderTargets[f],A=w.renderTargets[f].colorBuffer.width,M=this.renderTargets.get(A),C=M.colorBuffer;0===f?_=n.updateShaders:_&&(n.updateShaders=!0);var E=this.passMaterials[f];for(v&&x+1===y&&0===f&&(E=this.ambientAOMaterial),l=0;l>16&255)/255,e.pickColor[1]=(s>>8&255)/255,e.pickColor[2]=(255&s)/255,i.setValue(e.pickColor),t.setBlending(!1),e.mapping[s]=n}}),this.layer.addCamera(this.cameraEntity.camera),this.layerComp=new ho("picker"),this.layerComp.pushOpaque(this.layer)},e.prepare=function(t,e,i){t instanceof Ii&&(t=t.node.camera),i instanceof io&&(i=[i]),this.layer.clearMeshInstances();for(var n=this.layer.opaqueMeshInstances,s=e.layers.layerList,a=e.layers.subLayerEnabled,r=e.layers.subLayerList,o=0;o=0){h._clearDepthBuffer&&n.push(this.clearDepthCommand);for(var l=r[o]?h.instances.transparentMeshInstances:h.instances.opaqueMeshInstances,c=0;cSv?Sv:i.width||512,a=i.height>Sv?Sv:i.height||512,r=document.createElement("canvas");r.height=a,r.width=s;var o=new Mi(n.app.graphicsDevice,{format:7,mipmaps:!0});return o.name="font",o.setSource(r),o.minFilter=5,o.magFilter=1,o.addressU=1,o.addressV=1,n.textures=[o],n.chars="",n.data={},n}H(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;i0&&this._renderAtlas(this.chars.concat(i))},i.destroy=function(){for(var t=0;tC&&(C=this.fontSize*this.fontSize/E,c.font=this.fontWeight+" "+C.toString()+"px "+this.fontName,E=this.fontSize),this.renderCharacter(c,A,S+x,w+b,a);var P=this.padding+(this.glyphSize-E)/2,R=-this.padding+m[A].descent-p,I=E;if(this._addChar(this.data,A,M,S,w,v,y,P,R,I,e-1,n,s),(S+=v)+v>n&&(S=0,(w+=y)+y>s))if(this.textures[e-1].upload(),w=0,++e>d){(i=document.createElement("canvas")).height=s,i.width=n,c=this._getAndClearContext(i,o);var L=new Mi(this.app.graphicsDevice,{format:7,mipmaps:!0});L.name="font-atlas",L.setSource(i),L.minFilter=5,L.magFilter=1,L.addressU=1,L.addressV=1,this.textures.push(L)}else i=this.textures[e-1].getSource(),c=this._getAndClearContext(i,o)}if(this.textures[e-1].upload(),e0?this.wheelDelta=1:i.deltaY<0&&(this.wheelDelta=-1)),Nv()?(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},Gv=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(j(i)),i._downHandler=i._handleDown.bind(j(i)),i._moveHandler=i._handleMove.bind(j(i)),i._wheelHandler=i._handleWheel.bind(j(i)),i._contextMenuHandler=function(t){t.preventDefault()},i._target=null,i._attached=!1,i.attach(e),i}H(e,t),e.isPointerLocked=function(){return Nv()};var i=e.prototype;return i.attach=function(t){if(this._target=t,!this._attached){this._attached=!0;var e=!!E.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=!!E.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 Vv(this,t);e.event&&this.fire(yg,e)},i._handleDown=function(t){this._buttons[t.button]=!0;var e=new Vv(this,t);e.event&&this.fire(gg,e)},i._handleMove=function(t){var e=new Vv(this,t);e.event&&(this.fire(vg,e),this._lastX=e.x,this._lastY=e.y)},i._handleWheel=function(t){var e=new Vv(this,t);e.event&&this.fire(xg,e)},i._getTargetCoords=function(t){var e=this._target.getBoundingClientRect(),i=Math.floor(e.left),n=Math.floor(e.top);return t.clientX=i+this._target.clientWidth||t.clientY=n+this._target.clientHeight?null:{x:t.clientX-i,y:t.clientY-n}},e}(u),Wv=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(t),this._mouse&&this._mouse.update(t),this._gamepads&&this._gamepads.update(t),this._axesValues={},this._axes)this._axesValues[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._actions[t]?this._actions[t].push({type:mg,keys:e}):this._actions[t]=[{type:mg,keys:e}]},e.registerMouse=function(t,e){if(this._mouse||this._enableMouse(),void 0===e)throw new Error("Invalid button");this._actions[t]?this._actions[t].push({type:pg,button:e}):this._actions[t]=[{type:pg,button:-e}]},e.registerPadButton=function(t,e,i){if(void 0===i)throw new Error("Invalid button");this._actions[t]?this._actions[t].push({type:_g,button:i,pad:e}):this._actions[t]=[{type:_g,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,a,r){switch(s){case"mousex":n._mouse.on(vg,(function(t){n._axesValues[e][i]=t.dx/10}));break;case"mousey":n._mouse.on(vg,(function(t){n._axesValues[e][i]=t.dy/10}));break;case"key":n._axes[e].push((function(){return n._keyboard.isPressed(r)?a: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;iMath.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 Gv,!this._element)throw new Error("Controller must be attached to an Element");this._mouse.attach(this._element)},e._enableKeyboard=function(){if(this._keyboard=new Bv,!this._element)throw new Error("Controller must be attached to an Element");this._keyboard.attach(this._element)},t}(),Hv=new lt,Xv=new lt,jv=new Vt,qv=new Vt,Yv=new Vt;jv.end=new lt,qv.end=new lt,Yv.end=new lt;var Kv=new lt,Zv=new lt,$v=new lt,Qv=new lt,Jv=new lt,ty=new lt,ey=new lt,iy=new lt,ny=new lt,sy=new lt,ay=new lt,ry=new lt,oy=new lt,hy=new lt,ly=new lt,cy=new lt,uy=new lt,dy=new lt,fy=new lt,py=new lt,my=new dt;function _y(t,e,i){return ay.cross(t,e).dot(i)}var gy=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}(),vy=function(t){function e(e,i,n,s,a,r,o){var h;return(h=t.call(this,e,i,n)||this).x=s,h.y=a,h.ctrlKey=e.ctrlKey||!1,h.altKey=e.altKey||!1,h.shiftKey=e.shiftKey||!1,h.metaKey=e.metaKey||!1,h.button=e.button,Gv.isPointerLocked()?(h.dx=e.movementX||e.webkitMovementX||e.mozMovementX||0,h.dy=e.movementY||e.webkitMovementY||e.mozMovementY||0):(h.dx=s-r,h.dy=a-o),h.wheelDelta=0,"wheel"===e.type&&(e.deltaY>0?h.wheelDelta=1:e.deltaY<0&&(h.wheelDelta=-1)),h}return H(e,t),e}(gy),yy=function(t){function e(e,i,n,s,a,r){var o;return(o=t.call(this,e,i,n)||this).touches=e.touches,o.changedTouches=e.changedTouches,o.x=s,o.y=a,o.touch=r,o}return H(e,t),e}(gy),xy=function(t){function e(e,i,n,s){var a;return(a=t.call(this,e,i,n)||this).inputSource=s,a}return H(e,t),e}(gy),by=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,E.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=!!E.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&&E.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=!!E.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&&(Gv.isPointerLocked()||(this._calcMouseCoords(t),null!==Uv&&this._onElementMouseEvent("mouseup",t)))},e._handleDown=function(t){this._enabled&&(Gv.isPointerLocked()||(this._calcMouseCoords(t),null!==Uv&&this._onElementMouseEvent("mousedown",t)))},e._handleMove=function(t){this._enabled&&(this._calcMouseCoords(t),null!==Uv&&(this._onElementMouseEvent("mousemove",t),this._lastX=Uv,this._lastY=zv))},e._handleWheel=function(t){this._enabled&&(this._calcMouseCoords(t),null!==Uv&&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],a=0,r=t.changedTouches.length,o=0;o=0;d--){this._getTargetElement(e[d],u.x,u.y)===o&&(this._clickedEntities[o.entity.getGuid()]||(this._fireEvent("click",new yy(t,o,h,l,c,a)),this._clickedEntities[o.entity.getGuid()]=!0))}}}}},e._handleTouchMove=function(t){if(t.preventDefault(),this._enabled)for(var e=this._determineTouchedElements(t),i=0,n=t.changedTouches.length;i=0&&(s=a[r],!(i=this._getTargetElement(s,Uv,zv)));r--);i&&(this._fireEvent(t,new vy(e,i,s,Uv,zv,this._lastX,this._lastY)),this._hoveredElement=i,"mousedown"===t&&(this._pressedElement=i)),n!==this._hoveredElement&&(n&&this._fireEvent("mouseleave",new vy(e,n,s,Uv,zv,this._lastX,this._lastY)),this._hoveredElement&&this._fireEvent("mouseenter",new vy(e,this._hoveredElement,s,Uv,zv,this._lastX,this._lastY))),"mouseup"===t&&this._pressedElement&&(this._pressedElement===this._hoveredElement?(this._pressedElement=null,this._clickedEntities&&this._clickedEntities[this._hoveredElement.entity.getGuid()]||this._fireEvent("click",new vy(e,this._hoveredElement,s,Uv,zv,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=0&&(a=o[h],!(n=this._getTargetElementByRay(Yv,a)));h--);}e._elementEntity=n||null,n?(this._selectedElements[e.id]=n,s=n):delete this._selectedElements[e.id],r!==s&&(r&&this._fireEvent("selectleave",new xy(i,r,a,e)),s&&this._fireEvent("selectenter",new xy(i,s,a,e))),"selectstart"===t&&(this._selectedPressedElements[e.id]=s,s&&this._fireEvent("selectstart",new xy(i,s,a,e)));var l=this._selectedPressedElements[e.id];!e.elementInput&&l&&(delete this._selectedPressedElements[e.id],r&&this._fireEvent("selectend",new xy(i,r,a,e))),"selectend"===t&&e.elementInput&&(delete this._selectedPressedElements[e.id],r&&this._fireEvent("selectend",new xy(i,r,a,e)),l&&l===r&&this._fireEvent("click",new xy(i,l,a,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);t.clientX=i+this._target.clientWidth||t.clientY=n+this._target.clientHeight?(Uv=null,zv=null):(Uv=t.clientX-i,zv=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._getTargetElement=function(t,e,i){var n,s,a=null,r=1/0;this._elements.sort(this._sortHandler);for(var o=0,h=this._elements.length;o=0){a=l;break}}else{if(void 0===s&&(s=this._calculateRay3d(e,i,t,qv)?qv:null),!s)continue;var c=this._checkElement(s,l,!1);if(c>=0&&(c=0){i=a;break}}return i},e._buildHitCorners=function(t,e,i,n,s){var a=e;if(t.entity&&t.entity.button){var r=t.entity.button.hitPadding||my;oy.copy(t.entity.up),hy.copy(oy).mulScalar(-1),cy.copy(t.entity.right),ly.copy(cy).mulScalar(-1),oy.mulScalar(r.w*n),hy.mulScalar(r.y*n),cy.mulScalar(r.z*i),ly.mulScalar(r.x*i),uy.copy(a[0]).add(hy).add(ly),dy.copy(a[1]).add(hy).add(cy),fy.copy(a[2]).add(oy).add(cy),py.copy(a[3]).add(oy).add(ly),a=[uy,dy,fy,py]}if(i<0){var o=a[2].x,h=a[0].x;a[0].x=o,a[1].x=h,a[2].x=h,a[3].x=o}if(n<0){var l=a[2].y,c=a[0].y;a[0].y=l,a[1].y=l,a[2].y=c,a[3].y=c}if(s<0){var u=a[2].x,d=a[2].y,f=a[2].z;a[2].x=a[0].x,a[2].y=a[0].y,a[2].z=a[0].z,a[0].x=u,a[0].y=d,a[0].z=f}return a},e._calculateScaleToScreen=function(t){var e=t.entity,i=t.screen.screen.scale;for(ry.set(i,i,i);e&&!e.screen;)ry.mul(e.getLocalScale()),e=e.parent;return ry},e._calculateScaleToWorld=function(t){var e=t.entity;for(ry.set(1,1,1);e;)ry.mul(e.getLocalScale()),e=e.parent;return ry},e._calculateRayScreen=function(t,e,i,n){var s=this.app.graphicsDevice.width,a=this.app.graphicsDevice.height,r=i.rect.z*s,o=i.rect.w*a,h=i.rect.x*s,l=h+r,c=(1-i.rect.y)*a,u=c-o,d=t*s/this._target.clientWidth,f=e*a/this._target.clientHeight;return d>=h&&d<=l&&f<=c&&f>=u&&(d=s*(d-h)/r,f=a-(f=a*(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,a=this._target.clientHeight,r=i.rect.z*s,o=i.rect.w*a,h=i.rect.x*s,l=h+r,c=(1-i.rect.y)*a,u=c-o,d=t,f=e;return t>=h&&t<=l&&e<=c&&f>=u&&(d=s*(d-h)/r,f=a*(f-u)/o,i.screenToWorld(d,f,i.nearClip,Hv),i.screenToWorld(d,f,i.farClip,Xv),n.origin.copy(Hv),n.direction.set(0,0,-1),n.end.copy(Xv),!0)},e._checkElement=function(t,e,i){if(e.maskedBy&&this._checkElement(t,e.maskedBy.element,i)<0)return-1;var n;n=i?this._calculateScaleToScreen(e):this._calculateScaleToWorld(e);var s=this._buildHitCorners(e,i?e.screenCorners:e.worldCorners,n.x,n.y,n.z);return function(t,e,i){Kv.sub2(e,t),Zv.sub2(i[0],t),$v.sub2(i[1],t),Qv.sub2(i[2],t),ty.cross(Qv,Kv);var n,s,a=Zv.dot(ty);if(a>=0){if((n=-$v.dot(ty))<0)return-1;if((s=_y(Kv,$v,Zv))<0)return-1;var r=1/(n+a+s);ey.copy(i[0]).mulScalar(n*r),iy.copy(i[1]).mulScalar(a*r),ny.copy(i[2]).mulScalar(s*r),sy.copy(ey).add(iy).add(ny)}else{if(Jv.sub2(i[3],t),(n=Jv.dot(ty))<0)return-1;if((s=_y(Kv,Zv,Jv))<0)return-1;var o=1/(n+(a=-a)+s);ey.copy(i[0]).mulScalar(n*o),iy.copy(i[3]).mulScalar(a*o),ny.copy(i[2]).mulScalar(s*o),sy.copy(ey).add(iy).add(ny)}return Kv.sub2(i[0],i[2]).lengthSq()<1e-8||Kv.sub2(i[1],i[3]).lengthSq()<1e-8?-1:sy.sub(t).lengthSq()}(t.origin,t.end,s)},G(t,[{key:"enabled",get:function(){return this._enabled},set:function(t){this._enabled=t}},{key:"app",get:function(){return this._app||zs()},set:function(t){this._app=t}}]),t}(),Sy={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"]},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"]}},wy={"Product: 0268":"PS3"},Ty=function(){function t(){this.gamepadsSupported=!!navigator.getGamepads||!!navigator.webkitGetGamepads,this.current=[],this.previous=[],this.deadZone=.25}var e=t.prototype;return e.update=function(){for(var t=0,e=this.current.length;t0&&(t.length=0),this.gamepadsSupported)for(var e=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads(),i=0,n=e.length;i=0)return Sy[wy[e]];return Sy.DEFAULT},e.isPressed=function(t,e){if(!this.current[t])return!1;var i=this.current[t].map.buttons[e];return this.current[t].pad.buttons[pc[i]].pressed},e.wasPressed=function(t,e){if(!this.current[t])return!1;var i=this.current[t].map.buttons[e],n=pc[i];return this.current[t].pad.buttons[n].pressed&&!(this.previous[t]&&this.previous[t][n])},e.wasReleased=function(t,e){if(!this.current[t])return!1;var i=this.current[t].map.buttons[e],n=pc[i];return!this.current[t].pad.buttons[n].pressed&&this.previous[t]&&this.previous[t][n]},e.getAxis=function(t,e){if(!this.current[t])return 0;var i=this.current[t].map.axes[e],n=this.current[t].pad.axes[pc[i]];return Math.abs(n)=0&&(this._count++,this.fire("progress",t)),this._count===this._total&&setTimeout((function(){e._loadingComplete(e._failed)}),0)},i._onError=function(t,e){var i=this;this._assets.indexOf(e)>=0&&(this._count++,this._failed.push(e)),this._count===this._total&&setTimeout((function(){i._loadingComplete(i._failed)}),0)},i._onAddAsset=function(t){var e=this._waitingAssets.indexOf(t);e>=0&&this._waitingAssets.splice(e,1),this._assets.push(t);for(var i=0,n=this._assets.length;i