new file: Files/flashplayer_32_sa.exe new file: favicon.ico new file: globe.gif new file: imgs/download.png new file: imgs/zuck.jpg new file: index.html new file: other.ico new file: script.js new file: site.webmanifest new file: sitemap.html new file: styles/backround.css new file: styles/border.css new file: styles/fonts/Titillium_Web/OFL.txt new file: styles/fonts/Titillium_Web/TitilliumWeb-Black.ttf new file: styles/fonts/Titillium_Web/TitilliumWeb-Bold.ttf new file: styles/fonts/Titillium_Web/TitilliumWeb-BoldItalic.ttf new file: styles/fonts/Titillium_Web/TitilliumWeb-ExtraLight.ttf new file: styles/fonts/Titillium_Web/TitilliumWeb-ExtraLightItalic.ttf new file: styles/fonts/Titillium_Web/TitilliumWeb-Italic.ttf new file: styles/fonts/Titillium_Web/TitilliumWeb-Light.ttf new file: styles/fonts/Titillium_Web/TitilliumWeb-LightItalic.ttf new file: styles/fonts/Titillium_Web/TitilliumWeb-Regular.ttf new file: styles/fonts/Titillium_Web/TitilliumWeb-SemiBold.ttf new file: styles/fonts/Titillium_Web/TitilliumWeb-SemiBoldItalic.ttf new file: styles/fonts/webfontkit-20221027-163353/generator_config.txt new file: styles/fonts/webfontkit-20221027-163353/specimen_files/grid_12-825-55-15.css new file: styles/fonts/webfontkit-20221027-163353/specimen_files/specimen_stylesheet.css new file: styles/fonts/webfontkit-20221027-163353/stylesheet.css new file: styles/fonts/webfontkit-20221027-163353/titilliumweb-extralight-demo.html new file: styles/fonts/webfontkit-20221027-163353/titilliumweb-extralight-webfont.woff new file: styles/fonts/webfontkit-20221027-163353/titilliumweb-extralight-webfont.woff2 new file: styles/fonts/webfontkit-20221027-165950/generator_config.txt new file: styles/fonts/webfontkit-20221027-165950/specimen_files/grid_12-825-55-15.css new file: styles/fonts/webfontkit-20221027-165950/specimen_files/specimen_stylesheet.css new file: styles/fonts/webfontkit-20221027-165950/stylesheet.css new file: styles/fonts/webfontkit-20221027-165950/titilliumweb-bold-demo.html new file: styles/fonts/webfontkit-20221027-165950/titilliumweb-bold-webfont.woff new file: styles/fonts/webfontkit-20221027-165950/titilliumweb-bold-webfont.woff2 new file: styles/style.css new file: tools/2048/.gitignore new file: tools/2048/.jshintrc new file: tools/2048/CONTRIBUTING.md new file: tools/2048/LICENSE.txt new file: tools/2048/README.md new file: tools/2048/Rakefile new file: tools/2048/favicon.ico new file: tools/2048/index.html new file: tools/2048/js/animframe_polyfill.js new file: tools/2048/js/application.js new file: tools/2048/js/bind_polyfill.js new file: tools/2048/js/classlist_polyfill.js new file: tools/2048/js/game_manager.js new file: tools/2048/js/grid.js new file: tools/2048/js/html_actuator.js new file: tools/2048/js/keyboard_input_manager.js new file: tools/2048/js/local_storage_manager.js new file: tools/2048/js/tile.js new file: tools/2048/meta/apple-touch-icon.png new file: tools/webretro/cores/neocd_libretro.js new file: tools/webretro/cores/neocd_libretro.wasm new file: tools/webretro/cores/nestopia_libretro.js new file: tools/webretro/cores/nestopia_libretro.wasm new file: tools/webretro/cores/o2em_libretro.js new file: tools/webretro/cores/o2em_libretro.wasm new file: tools/webretro/cores/opera_libretro.js new file: tools/webretro/cores/opera_libretro.wasm
1781 lines
986 KiB
JavaScript
1781 lines
986 KiB
JavaScript
;(function (root, factory) {
|
|
if (typeof define === 'function' && define.amd) {
|
|
define([], factory);
|
|
} else if (typeof module === 'object' && module.exports) {
|
|
try {
|
|
var JSDOM = require("jsdom").JSDOM;
|
|
var DOM = new JSDOM();
|
|
var window = DOM.window;
|
|
var navigator = window.navigator;
|
|
module.exports = factory(window, navigator);
|
|
} catch (error) {
|
|
module.exports = factory();
|
|
}
|
|
} else {
|
|
root.pc = factory(root, root.navigator);
|
|
}
|
|
}(this, function (_window, _navigator) {
|
|
window = _window || window;
|
|
navigator = _navigator || navigator;
|
|
|
|
/*
|
|
PlayCanvas Engine v1.16.1 revision d53fd63
|
|
http://playcanvas.com
|
|
Copyright 2011-2018 PlayCanvas Ltd. All rights reserved.
|
|
*/
|
|
var _typeLookup=function(){for(var e={},b="Array Object Function Date RegExp Float32Array".split(" "),a=0;a<b.length;a++)e["[object "+b[a]+"]"]=b[a].toLowerCase();return e}(),pc={version:"1.16.1",revision:"d53fd63",config:{},common:{},apps:{},data:{},unpack:function(){console.warn("pc.unpack has been deprecated and will be removed shortly. Please update your code.")},makeArray:function(e){var b,a=[],c=e.length;for(b=0;b<c;++b)a.push(e[b]);return a},type:function(e){if(null===
|
|
e)return"null";var b=typeof e;return"undefined"===b||"number"===b||"string"===b||"boolean"===b?b:_typeLookup[Object.prototype.toString.call(e)]},extend:function(e,b){var a,c;for(a in b)c=b[a],"object"==pc.type(c)?e[a]=pc.extend({},c):"array"==pc.type(c)?e[a]=pc.extend([],c):e[a]=c;return e},isDefined:function(e){return void 0!==e}};"undefined"!==typeof exports&&(exports.pc=pc);(function(){if("undefined"!==typeof document){var e=function(a){var b=document.createEvent("CustomEvent");b.initCustomEvent("fullscreenchange",!0,!1,null);a.target.dispatchEvent(b)},b=function(a){var b=document.createEvent("CustomEvent");b.initCustomEvent("fullscreenerror",!0,!1,null);a.target.dispatchEvent(b)};document.addEventListener("webkitfullscreenchange",e,!1);document.addEventListener("mozfullscreenchange",e,!1);document.addEventListener("MSFullscreenChange",e,!1);document.addEventListener("webkitfullscreenerror",
|
|
b,!1);document.addEventListener("mozfullscreenerror",b,!1);document.addEventListener("MSFullscreenError",b,!1);Element.prototype.requestFullscreen=Element.prototype.mozRequestFullScreen?function(){this.mozRequestFullScreen()}:Element.prototype.requestFullscreen||Element.prototype.webkitRequestFullscreen||Element.prototype.msRequestFullscreen;document.exitFullscreen=document.exitFullscreen||document.webkitExitFullscreen||document.mozCancelFullScreen||document.msExitFullscreen;document.hasOwnProperty("fullscreenElement")||
|
|
Object.defineProperty(document,"fullscreenElement",{enumerable:!0,configurable:!1,get:function(){return document.webkitCurrentFullScreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement}});document.hasOwnProperty("fullscreenEnabled")||Object.defineProperty(document,"fullscreenEnabled",{enumerable:!0,configurable:!1,get:function(){return document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled}})}})();Math.log2=Math.log2||function(e){return Math.log(e)*Math.LOG2E};"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(e,b){if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var a=Object(e),c=1;c<arguments.length;c++){var d=arguments[c];if(null!=d)for(var f in d)Object.prototype.hasOwnProperty.call(d,f)&&(a[f]=d[f])}return a},writable:!0,configurable:!0});(function(){if("undefined"!==typeof navigator&&"undefined"!==typeof document){navigator.pointer=navigator.pointer||navigator.webkitPointer||navigator.mozPointer;var e=function(){var a=document.createEvent("CustomEvent");a.initCustomEvent("pointerlockchange",!0,!1,null);document.dispatchEvent(a)},b=function(){var a=document.createEvent("CustomEvent");a.initCustomEvent("pointerlockerror",!0,!1,null);document.dispatchEvent(a)};document.addEventListener("webkitpointerlockchange",e,!1);document.addEventListener("webkitpointerlocklost",
|
|
e,!1);document.addEventListener("mozpointerlockchange",e,!1);document.addEventListener("mozpointerlocklost",e,!1);document.addEventListener("webkitpointerlockerror",b,!1);document.addEventListener("mozpointerlockerror",b,!1);Element.prototype.requestPointerLock=Element.prototype.mozRequestPointerLock?function(){this.mozRequestPointerLock()}:Element.prototype.requestPointerLock||Element.prototype.webkitRequestPointerLock||Element.prototype.mozRequestPointerLock;!Element.prototype.requestPointerLock&&
|
|
navigator.pointer&&(Element.prototype.requestPointerLock=function(){document.pointerLockElement=this;navigator.pointer.lock(this,e,b)});document.exitPointerLock=document.exitPointerLock||document.webkitExitPointerLock||document.mozExitPointerLock;document.exitPointerLock||(document.exitPointerLock=function(){navigator.pointer&&(document.pointerLockElement=null,navigator.pointer.unlock())})}})();(function(){for(var e=0,b=["ms","moz","webkit","o"],a=0;a<b.length&&!window.requestAnimationFrame;++a)window.requestAnimationFrame=window[b[a]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[b[a]+"CancelAnimationFrame"]||window[b[a]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(a,b){var c=(new Date).getTime(),d=Math.max(0,16-(c-e)),l=window.setTimeout(function(){a(c+d)},d);e=c+d;return l});window.cancelAnimationFrame||(window.cancelAnimationFrame=
|
|
function(a){clearTimeout(a)})})();String.prototype.endsWith||(String.prototype.endsWith=function(e,b){if(void 0===b||b>this.length)b=this.length;return this.substring(b-e.length,b)===e});String.prototype.includes||(String.prototype.includes=function(e,b){"number"!==typeof b&&(b=0);return b+e.length>this.length?!1:-1!==this.indexOf(e,b)});String.prototype.startsWith||(String.prototype.startsWith=function(e,b){return this.substr(!b||0>b?0:+b,e.length)===e});Object.assign(pc,function(){var e=function(b,a,c,d){var f=b&&b.length;3===f||4===f?(this.r=b[0],this.g=b[1],this.b=b[2],this.a=void 0!==b[3]?b[3]:1):(this.r=b||0,this.g=a||0,this.b=c||0,this.a=void 0!==d?d:1)};Object.assign(e.prototype,{clone:function(){return new pc.Color(this.r,this.g,this.b,this.a)},copy:function(b){this.r=b.r;this.g=b.g;this.b=b.b;this.a=b.a;return this},set:function(b,a,c,d){this.r=b;this.g=a;this.b=c;this.a=void 0===d?1:d;return this},lerp:function(b,a,c){this.r=b.r+c*(a.r-
|
|
b.r);this.g=b.g+c*(a.g-b.g);this.b=b.b+c*(a.b-b.b);this.a=b.a+c*(a.a-b.a);return this},fromString:function(b){var a=parseInt(b.replace("#","0x"),16);7<b.length?b=pc.math.intToBytes32(a):(b=pc.math.intToBytes24(a),b[3]=255);this.set(b[0]/255,b[1]/255,b[2]/255,b[3]/255);return this},toString:function(b){var a="#"+(16777216+(Math.round(255*this.r)<<16)+(Math.round(255*this.g)<<8)+Math.round(255*this.b)).toString(16).slice(1);!0===b&&(b=Math.round(255*this.a).toString(16),a=this.a<16/255?a+("0"+b):a+
|
|
b);return a}});return{Color:e}}());pc.guid=function(){return{create:function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var b=16*Math.random()|0;return("x"==e?b:b&3|8).toString(16)})}}}();Object.assign(pc,function(){var e=function(){this._isRunning=!1;this._b=this._a=0};Object.assign(e.prototype,{start:function(){this._isRunning=!0;this._a=pc.now()},stop:function(){this._isRunning=!1;this._b=pc.now()},getMilliseconds:function(){return this._b-this._a}});return{Timer:e,now:window.performance&&window.performance.now&&window.performance.timing?function(){return window.performance.now()}:Date.now}}());Object.assign(pc,function(){return{hashCode:function(e){for(var b=0,a=0,c=e.length;a<c;a++)b=(b<<5)-b+e.charCodeAt(a),b|=0;return b}}}());Object.assign(pc,function(){return{createURI:function(e){var b="";if((e.authority||e.scheme)&&(e.host||e.hostpath))throw Error("Can't have 'scheme' or 'authority' and 'host' or 'hostpath' option");if(e.host&&e.hostpath)throw Error("Can't have 'host' and 'hostpath' option");if(e.path&&e.hostpath)throw Error("Can't have 'path' and 'hostpath' option");e.scheme&&(b+=e.scheme+":");e.authority&&(b+="//"+e.authority);e.host&&(b+=e.host);e.path&&(b+=e.path);e.hostpath&&(b+=e.hostpath);e.query&&(b+="?"+e.query);
|
|
e.fragment&&(b+="#"+e.fragment);return b},URI:function(e){e=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/);this.scheme=e[2];this.authority=e[4];this.path=e[5];this.query=e[7];this.fragment=e[9];this.toString=function(){var b="";this.scheme&&(b+=this.scheme+":");this.authority&&(b+="//"+this.authority);b+=this.path;this.query&&(b+="?"+this.query);this.fragment&&(b+="#"+this.fragment);return b};this.getQuery=function(){var b,a,c={};this.query&&(b=decodeURIComponent(this.query).split("&"),
|
|
b.forEach(function(b,f,g){a=b.split("=");c[a[0]]=a[1]},this));return c};this.setQuery=function(b){var a="",c;for(c in b)b.hasOwnProperty(c)&&(""!==a&&(a+="&"),a+=encodeURIComponent(c)+"="+encodeURIComponent(b[c]));this.query=a}}}}());Object.assign(pc,function(){return{log:{write:function(e){console.log(e)},open:function(){pc.log.write("Powered by PlayCanvas "+pc.version+" "+pc.revision)},info:function(e){console.info("INFO: "+e)},debug:function(e){console.debug("DEBUG: "+e)},error:function(e){console.error("ERROR: "+e)},warning:function(e){console.warn("WARNING: "+e)},alert:function(e){pc.log.write("ALERT: "+e);alert(e)},assert:function(e,b){!1===e&&pc.log.write("ASSERT: "+b)}}}}());
|
|
var logINFO=pc.log.info,logDEBUG=pc.log.debug,logWARNING=pc.log.warning,logERROR=pc.log.error,logALERT=pc.log.alert,logASSERT=pc.log.assert;pc.path=function(){return{delimiter:"/",join:function(){var e,b=arguments.length,a=arguments[0];for(e=0;e<b-1;++e){var c=arguments[e],d=arguments[e+1];if(!pc.isDefined(c)||!pc.isDefined(d))throw Error("undefined argument to pc.path.join");a=d[0]===pc.path.delimiter?d:c&&d&&c[c.length-1]!==pc.path.delimiter&&d[0]!==pc.path.delimiter?a+(pc.path.delimiter+d):a+d}return a},normalize:function(e){var b=e.startsWith(pc.path.delimiter),a=e.endsWith(pc.path.delimiter);e=e.split("/");for(var c=[],d=0;d<e.length;d++)""!==
|
|
e[d]&&"."!==e[d]&&(".."===e[d]&&0<c.length?c=c.slice(0,c.length-2):(0<d&&c.push(pc.path.delimiter),c.push(e[d])));e=c.join("");b||e[0]!==pc.path.delimiter||(e=e.slice(1));a&&e[e.length-1]!==pc.path.delimiter&&(e+=pc.path.delimiter);return e},split:function(e){e=e.split(pc.path.delimiter);var b=e.slice(e.length-1)[0];return[e.slice(0,e.length-1).join(pc.path.delimiter),b]},getBasename:function(e){return pc.path.split(e)[1]},getDirectory:function(e){e=e.split(pc.path.delimiter);return e.slice(0,e.length-
|
|
1).join(pc.path.delimiter)},getExtension:function(e){var b=e.split("?")[0].split(".").pop();return b!==e?"."+b:""},isRelativePath:function(e){return"/"!==e.charAt(0)&&null===e.match(/:\/\//)},extractPath:function(e){var b=".",a=e.split("/");if(1<a.length)for(!1===pc.path.isRelativePath(e)&&(b=""),e=0;e<a.length-1;++e)b+="/"+a[e];return b}}}();pc.string=function(){function e(a,b){var c=a.length;b=b||0;if(0>b||b>=c)return null;var f=a.charCodeAt(b);return 1<c&&55296<=f&&56319>=f&&(c=a.charCodeAt(b+1),56320<=c&&57343>=c)?{code:1024*(f-55296)+c-56320+65536,"long":!0}:{code:f,"long":!1}}function b(a,b,d){return a?(a=e(a))?(a=a.code,a>=b&&a<=d):!1:!1}return{ASCII_LOWERCASE:"abcdefghijklmnopqrstuvwxyz",ASCII_UPPERCASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",ASCII_LETTERS:"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",format:function(a){var b,d,
|
|
f=pc.makeArray(arguments);f.shift();for(b=0;b<f.length;b++)d=new RegExp("\\{"+b+"\\}","gi"),a=a.replace(d,f[b]);return a},startsWith:function(a,b){console.warn("WARNING: startsWith: Function is deprecated. Use String.startsWith instead.");return a.startsWith(b)},endsWith:function(a,b){console.warn("WARNING: endsWith: Function is deprecated. Use String.endsWith instead.");return a.endsWith(b)},toBool:function(a,b){if("true"===a)return!0;if(b){if("false"===a)return!1;throw new TypeError("Not a boolean string");
|
|
}return!1},getCodePoint:function(a,b){var c=e(a,b);return c&&c.code},getCodePoints:function(a){if("string"!==typeof a)throw new TypeError("Not a string");for(var b=0,d=[],f;f=e(a,b);)d.push(f.code),b+=f["long"]?2:1;return d},getSymbols:function(a){if("string"!==typeof a)throw new TypeError("Not a string");for(var c=0,d=a.length,f=[],g=0,l;c<d;){l=g;var h=a,e=c+g;e===h.length-1?g=1:b(h[e],55296,56319)?(g=h.substring(e,e+2),h=h.substring(e+2,e+4),g=b(h,127995,127999)||b(g,127462,127487)&&b(h,127462,
|
|
127487)?4:b(h,65024,65039)?3:2):g=b(h[e+1],65024,65039)?2:1;g=l+g;l=a[c+g];b(l,8400,8447)&&(l=a[c+g++]);b(l,65024,65039)&&(l=a[c+g++]);l&&8205===l.charCodeAt(0)?g++:(l=a.substring(c,c+g),f.push(l),c+=g,g=0)}return f},fromCodePoint:function(){for(var a=[],b,d,f=0;f<arguments.length;++f)b=Number(arguments[f]),d=b-65536,b=65535<b?[(d>>10)+55296,d%1024+56320]:[b],a.push(String.fromCharCode.apply(null,b));return a.join("")}}}();pc.debug=function(){var e=null,b=null,a=null,c=null;return{display:function(d){e||(e=document.createElement("table"),b=document.createElement("tr"),a=document.createElement("td"),c=document.createElement("td"),e.style.cssText="position:absolute;font-family:sans-serif;font-size:12px;color:#cccccc",e.style.top="0px",e.style.left="0px",e.style.border="thin solid #cccccc",document.body.appendChild(e));e.innerHTML="";for(var f in d){var g=b.cloneNode(),l=a.cloneNode(),h=c.cloneNode();l.textContent=f;h.textContent=
|
|
d[f];g.appendChild(l);g.appendChild(h);e.appendChild(g)}}}}();pc.events={attach:function(e){var b=pc.events;e.on=b.on;e.off=b.off;e.fire=b.fire;e.once=b.once;e.hasEvent=b.hasEvent;e._callbackActive={};return e},on:function(e,b,a){if(!e||"string"!==typeof e||!b)return this;this._callbacks||(this._callbacks={});this._callbacks[e]||(this._callbacks[e]=[]);this._callbackActive||(this._callbackActive={});this._callbackActive[e]&&this._callbackActive[e]===this._callbacks[e]&&(this._callbackActive[e]=this._callbackActive[e].slice());this._callbacks[e].push({callback:b,
|
|
scope:a||this});return this},off:function(e,b,a){if(!this._callbacks)return this;if(this._callbackActive)if(e)this._callbackActive[e]&&this._callbackActive[e]===this._callbacks[e]&&(this._callbackActive[e]=this._callbackActive[e].slice());else for(var c in this._callbackActive)this._callbacks[c]&&this._callbacks[c]===this._callbackActive[c]&&(this._callbackActive[c]=this._callbackActive[c].slice());if(e)if(b){e=this._callbacks[e];if(!e)return this;for(c=e.length;c--;)e[c].callback===b&&(a&&e[c].scope!==
|
|
a||e.splice(c,1))}else this._callbacks[e]&&delete this._callbacks[e];else this._callbacks=null;return this},fire:function(e,b,a,c,d,f,g,l,h){if(!e||!this._callbacks||!this._callbacks[e])return this;var p;this._callbackActive||(this._callbackActive={});this._callbackActive[e]?(this._callbackActive[e]===this._callbacks[e]&&(this._callbackActive[e]=this._callbackActive[e].slice()),p=this._callbacks[e].slice()):this._callbackActive[e]=this._callbacks[e];for(var k=0;(p||this._callbackActive[e])&&k<(p||
|
|
this._callbackActive[e]).length;k++){var n=(p||this._callbackActive[e])[k];n.callback.call(n.scope,b,a,c,d,f,g,l,h);n.callback.once&&(n=this._callbacks[e].indexOf(n),-1!==n&&(this._callbackActive[e]===this._callbacks[e]&&(this._callbackActive[e]=this._callbackActive[e].slice()),this._callbacks[e].splice(n,1)))}p||(this._callbackActive[e]=null);return this},once:function(e,b,a){b.once=!0;this.on(e,b,a);return this},hasEvent:function(e){return this._callbacks&&this._callbacks[e]&&0!==this._callbacks[e].length||
|
|
!1}};Object.assign(pc,function(){var e=function(a){this._index={};this._key=a||null};Object.assign(e.prototype,{addItem:function(a){for(var b=a.tags._list,d=0;d<b.length;d++)this.add(b[d],a)},removeItem:function(a){for(var b=a.tags._list,d=0;d<b.length;d++)this.remove(b[d],a)},add:function(a,b){this._index[a]&&-1!==this._index[a].list.indexOf(b)||(this._index[a]||(this._index[a]={list:[]},this._key&&(this._index[a].keys={})),this._index[a].list.push(b),this._key&&(this._index[a].keys[b[this._key]]=b))},
|
|
remove:function(a,b){if(this._index[a]&&(!this._key||this._index[a].keys[b[this._key]])){var c=this._index[a].indexOf(b);-1!==c&&(this._index[a].list.splice(c,1),this._key&&delete this._index[a].keys[b[this._key]],0===this._index[a].list.length&&delete this._index[a])}},find:function(a){var b=this,d={},f=[],g,l,h,e,k,n=function(a,c){return b._index[a].list.length-b._index[c].list.length};for(g=0;g<a.length;g++){e=a[g];if(e instanceof Array){if(0===e.length)continue;if(1===e.length)e=e[0];else{h=!1;
|
|
for(l=0;l<e.length;l++)if(!this._index[e[l]]){h=!0;break}if(h)continue;e=e.slice(0).sort(n);k=e.slice(1);1===k.length&&(k=k[0]);for(l=0;l<this._index[e[0]].list.length;l++)h=this._index[e[0]].list[l],(this._key?!d[h[this._key]]:-1===f.indexOf(h))&&h.tags.has(k)&&(this._key&&(d[h[this._key]]=!0),f.push(h));continue}}if(e&&"string"===typeof e&&this._index[e])for(l=0;l<this._index[e].list.length;l++)h=this._index[e].list[l],this._key?d[h[this._key]]||(d[h[this._key]]=!0,f.push(h)):-1===f.indexOf(h)&&
|
|
f.push(h)}return f}});var b=function(a){this._index={};this._list=[];this._parent=a;pc.events.attach(this)};Object.assign(b.prototype,{add:function(){var a=!1,b=this._processArguments(arguments,!0);if(!b.length)return a;for(var d=0;d<b.length;d++)this._index[b[d]]||(a=!0,this._index[b[d]]=!0,this._list.push(b[d]),this.fire("add",b[d],this._parent));a&&this.fire("change",this._parent);return a},remove:function(){var a=!1;if(!this._list.length)return a;var b=this._processArguments(arguments,!0);if(!b.length)return a;
|
|
for(var d=0;d<b.length;d++)this._index[b[d]]&&(a=!0,delete this._index[b[d]],this._list.splice(this._list.indexOf(b[d]),1),this.fire("remove",b[d],this._parent));a&&this.fire("change",this._parent);return a},clear:function(){if(this._list.length){var a=this._list.slice(0);this._list=[];this._index={};for(var b=0;b<a.length;b++)this.fire("remove",a[b],this._parent);this.fire("change",this._parent)}},has:function(){return this._list.length?this._has(this._processArguments(arguments)):!1},_has:function(a){if(!this._list.length||
|
|
!a.length)return!1;for(var b=0;b<a.length;b++)if(1===a[b].length){if(this._index[a[b][0]])return!0}else{for(var d=!0,f=0;f<a[b].length;f++)if(!this._index[a[b][f]]){d=!1;break}if(d)return!0}return!1},list:function(){return this._list.slice(0)},_processArguments:function(a,b){var c=[],f=[];if(!a||!a.length)return c;for(var g=0;g<a.length;g++)if(a[g]instanceof Array){b||(f=[]);for(var l=0;l<a[g].length;l++)"string"===typeof a[g][l]&&(b?c.push(a[g][l]):f.push(a[g][l]));!b&&f.length&&c.push(f)}else"string"===
|
|
typeof a[g]&&(b?c.push(a[g]):c.push([a[g]]));return c}});Object.defineProperty(b.prototype,"size",{get:function(){return this._list.length}});return{TagsCache:e,Tags:b}}());Object.assign(pc,function(){var e=function(b,a){this._constructor=b;this._pool=[];this._count=0;this._resize(a)};Object.assign(e.prototype,{_resize:function(b){if(b>this._pool.length)for(var a=this._pool.length;a<b;a++)this._pool[a]=new this._constructor},allocate:function(){this._count>=this._pool.length&&this._resize(2*this._pool.length);return this._pool[this._count++]},freeAll:function(){this._count=0}});return{AllocatePool:e}}());Object.assign(pc,function(){var e={desktop:!1,mobile:!1,ios:!1,android:!1,windows:!1,cocoonjs:!1,xbox:!1,gamepads:!1,touch:!1,workers:!1},b=navigator.userAgent;/(windows|mac os|linux|cros)/i.test(b)&&(e.desktop=!0);/xbox/i.test(b)&&(e.xbox=!0);/(windows phone|iemobile|wpdesktop)/i.test(b)?(e.desktop=!1,e.mobile=!0,e.windows=!0):/android/i.test(b)?(e.desktop=!1,e.mobile=!0,e.android=!0):/ip([ao]d|hone)/i.test(b)&&(e.desktop=!1,e.mobile=!0,e.ios=!0);navigator.isCocoonJS&&(e.cocoonjs=!0);e.touch="ontouchstart"in
|
|
window||"maxTouchPoints"in navigator&&0<navigator.maxTouchPoints;e.gamepads="getGamepads"in navigator;e.workers="undefined"!==typeof Worker;return{platform:e}}());Object.assign(pc,function(){var e=function(){this._list=[];this._index={}};Object.assign(e.prototype,{push:function(b,a){if(this._index[b])throw Error("Key already in index "+b);var c=this._list.push(a)-1;this._index[b]=c},has:function(b){return void 0!==this._index[b]},get:function(b){b=this._index[b];return void 0!==b?this._list[b]:null},remove:function(b){var a=this._index[b];if(void 0!==a){this._list.splice(a,1);delete this._index[b];for(b in this._index){var c=this._index[b];c>a&&(this._index[b]=
|
|
c-1)}return!0}return!1},list:function(){return this._list},clear:function(){this._list.length=0;for(var b in this._index)delete this._index[b]}});return{IndexedList:e}}());pc.math={DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,clamp:function(e,b,a){return e>=a?a:e<=b?b:e},intToBytes24:function(e){return[e>>16&255,e>>8&255,e&255]},intToBytes32:function(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]},bytesToInt24:function(e,b,a){e.length&&(a=e[2],b=e[1],e=e[0]);return e<<16|b<<8|a},bytesToInt32:function(e,b,a,c){e.length&&(c=e[3],a=e[2],b=e[1],e=e[0]);return(e<<24|b<<16|a<<8|c)>>>32},lerp:function(e,b,a){return e+(b-e)*pc.math.clamp(a,0,1)},lerpAngle:function(e,b,a){180<
|
|
b-e&&(b-=360);-180>b-e&&(b+=360);return pc.math.lerp(e,b,pc.math.clamp(a,0,1))},powerOfTwo:function(e){return 0!==e&&!(e&e-1)},nextPowerOfTwo:function(e){e--;e|=e>>1;e|=e>>2;e|=e>>4;e|=e>>8;e|=e>>16;e++;return e},random:function(e,b){return Math.random()*(b-e)+e},smoothstep:function(e,b,a){if(a<=e)return 0;if(a>=b)return 1;a=(a-e)/(b-e);return a*a*(3-2*a)},smootherstep:function(e,b,a){if(a<=e)return 0;if(a>=b)return 1;a=(a-e)/(b-e);return a*a*a*(a*(6*a-15)+10)}};Object.assign(pc,function(){var e=function(b,a){b&&2===b.length?(this.x=b[0],this.y=b[1]):(this.x=b||0,this.y=a||0)};Object.assign(e.prototype,{add:function(b){this.x+=b.x;this.y+=b.y;return this},add2:function(b,a){this.x=b.x+a.x;this.y=b.y+a.y;return this},clone:function(){return(new e).copy(this)},copy:function(b){this.x=b.x;this.y=b.y;return this},dot:function(b){return this.x*b.x+this.y*b.y},equals:function(b){return this.x===b.x&&this.y===b.y},length:function(){return Math.sqrt(this.x*this.x+
|
|
this.y*this.y)},lengthSq:function(){return this.x*this.x+this.y*this.y},lerp:function(b,a,c){this.x=b.x+c*(a.x-b.x);this.y=b.y+c*(a.y-b.y);return this},mul:function(b){this.x*=b.x;this.y*=b.y;return this},mul2:function(b,a){this.x=b.x*a.x;this.y=b.y*a.y;return this},normalize:function(){var b=this.x*this.x+this.y*this.y;0<b&&(b=1/Math.sqrt(b),this.x*=b,this.y*=b);return this},scale:function(b){this.x*=b;this.y*=b;return this},set:function(b,a){this.x=b;this.y=a;return this},sub:function(b){this.x-=
|
|
b.x;this.y-=b.y;return this},sub2:function(b,a){this.x=b.x-a.x;this.y=b.y-a.y;return this},toString:function(){return"["+this.x+", "+this.y+"]"}});Object.defineProperty(e,"ONE",{get:function(){var b=new e(1,1);return function(){return b}}()});Object.defineProperty(e,"RIGHT",{get:function(){var b=new e(1,0);return function(){return b}}()});Object.defineProperty(e,"UP",{get:function(){var b=new e(0,1);return function(){return b}}()});Object.defineProperty(e,"ZERO",{get:function(){var b=new e(0,0);return function(){return b}}()});
|
|
return{Vec2:e}}());Object.assign(pc,function(){var e=function(b,a,c){b&&3===b.length?(this.x=b[0],this.y=b[1],this.z=b[2]):(this.x=b||0,this.y=a||0,this.z=c||0)};Object.assign(e.prototype,{add:function(b){this.x+=b.x;this.y+=b.y;this.z+=b.z;return this},add2:function(b,a){this.x=b.x+a.x;this.y=b.y+a.y;this.z=b.z+a.z;return this},clone:function(){return(new e).copy(this)},copy:function(b){this.x=b.x;this.y=b.y;this.z=b.z;return this},cross:function(b,a){var c=b.x,d=b.y,f=b.z,g=a.x,l=a.y,h=a.z;this.x=d*h-l*f;this.y=f*
|
|
g-h*c;this.z=c*l-g*d;return this},dot:function(b){return this.x*b.x+this.y*b.y+this.z*b.z},equals:function(b){return this.x===b.x&&this.y===b.y&&this.z===b.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},lerp:function(b,a,c){this.x=b.x+c*(a.x-b.x);this.y=b.y+c*(a.y-b.y);this.z=b.z+c*(a.z-b.z);return this},mul:function(b){this.x*=b.x;this.y*=b.y;this.z*=b.z;return this},mul2:function(b,a){this.x=
|
|
b.x*a.x;this.y=b.y*a.y;this.z=b.z*a.z;return this},normalize:function(){var b=this.x*this.x+this.y*this.y+this.z*this.z;0<b&&(b=1/Math.sqrt(b),this.x*=b,this.y*=b,this.z*=b);return this},project:function(b){var a=(this.x*b.x+this.y*b.y+this.z*b.z)/(b.x*b.x+b.y*b.y+b.z*b.z);this.x=b.x*a;this.y=b.y*a;this.z=b.z*a;return this},scale:function(b){this.x*=b;this.y*=b;this.z*=b;return this},set:function(b,a,c){this.x=b;this.y=a;this.z=c;return this},sub:function(b){this.x-=b.x;this.y-=b.y;this.z-=b.z;return this},
|
|
sub2:function(b,a){this.x=b.x-a.x;this.y=b.y-a.y;this.z=b.z-a.z;return this},toString:function(){return"["+this.x+", "+this.y+", "+this.z+"]"}});Object.defineProperty(e,"BACK",{get:function(){var b=new e(0,0,1);return function(){return b}}()});Object.defineProperty(e,"DOWN",{get:function(){var b=new e(0,-1,0);return function(){return b}}()});Object.defineProperty(e,"FORWARD",{get:function(){var b=new e(0,0,-1);return function(){return b}}()});Object.defineProperty(e,"LEFT",{get:function(){var b=new e(-1,
|
|
0,0);return function(){return b}}()});Object.defineProperty(e,"ONE",{get:function(){var b=new e(1,1,1);return function(){return b}}()});Object.defineProperty(e,"RIGHT",{get:function(){var b=new e(1,0,0);return function(){return b}}()});Object.defineProperty(e,"UP",{get:function(){var b=new e(0,1,0);return function(){return b}}()});Object.defineProperty(e,"ZERO",{get:function(){var b=new e(0,0,0);return function(){return b}}()});return{Vec3:e}}());Object.assign(pc,function(){var e=function(b,a,c,d){b&&4===b.length?(this.x=b[0],this.y=b[1],this.z=b[2],this.w=b[3]):(this.x=b||0,this.y=a||0,this.z=c||0,this.w=d||0)};Object.assign(e.prototype,{add:function(b){this.x+=b.x;this.y+=b.y;this.z+=b.z;this.w+=b.w;return this},add2:function(b,a){this.x=b.x+a.x;this.y=b.y+a.y;this.z=b.z+a.z;this.w=b.w+a.w;return this},clone:function(){return(new e).copy(this)},copy:function(b){this.x=b.x;this.y=b.y;this.z=b.z;this.w=b.w;return this},dot:function(b){return this.x*
|
|
b.x+this.y*b.y+this.z*b.z+this.w*b.w},equals:function(b){return this.x===b.x&&this.y===b.y&&this.z===b.z&&this.w===b.w},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},lerp:function(b,a,c){this.x=b.x+c*(a.x-b.x);this.y=b.y+c*(a.y-b.y);this.z=b.z+c*(a.z-b.z);this.w=b.w+c*(a.w-b.w);return this},mul:function(b){this.x*=b.x;this.y*=b.y;this.z*=b.z;this.w*=b.w;return this},mul2:function(b,
|
|
a){this.x=b.x*a.x;this.y=b.y*a.y;this.z=b.z*a.z;this.w=b.w*a.w;return this},normalize:function(){var b=this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w;0<b&&(b=1/Math.sqrt(b),this.x*=b,this.y*=b,this.z*=b,this.w*=b);return this},scale:function(b){this.x*=b;this.y*=b;this.z*=b;this.w*=b;return this},set:function(b,a,c,d){this.x=b;this.y=a;this.z=c;this.w=d;return this},sub:function(b){this.x-=b.x;this.y-=b.y;this.z-=b.z;this.w-=b.w;return this},sub2:function(b,a){this.x=b.x-a.x;this.y=b.y-a.y;
|
|
this.z=b.z-a.z;this.w=b.w-a.w;return this},toString:function(){return"["+this.x+", "+this.y+", "+this.z+", "+this.w+"]"}});Object.defineProperty(e,"ONE",{get:function(){var b=new e(1,1,1,1);return function(){return b}}()});Object.defineProperty(e,"ZERO",{get:function(){var b=new e(0,0,0,0);return function(){return b}}()});return{Vec4:e}}());Object.assign(pc,function(){var e=function(){var b;b=new Float32Array(9);b[0]=b[4]=b[8]=1;this.data=b};Object.assign(e.prototype,{clone:function(){return(new pc.Mat3).copy(this)},copy:function(b){b=b.data;var a=this.data;a[0]=b[0];a[1]=b[1];a[2]=b[2];a[3]=b[3];a[4]=b[4];a[5]=b[5];a[6]=b[6];a[7]=b[7];a[8]=b[8];return this},set:function(b){var a=this.data;a[0]=b[0];a[1]=b[1];a[2]=b[2];a[3]=b[3];a[4]=b[4];a[5]=b[5];a[6]=b[6];a[7]=b[7];a[8]=b[8];return this},equals:function(b){var a=this.data;b=b.data;
|
|
return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]},isIdentity:function(){var b=this.data;return 1===b[0]&&0===b[1]&&0===b[2]&&0===b[3]&&1===b[4]&&0===b[5]&&0===b[6]&&0===b[7]&&1===b[8]},setIdentity:function(){var b=this.data;b[0]=1;b[1]=0;b[2]=0;b[3]=0;b[4]=1;b[5]=0;b[6]=0;b[7]=0;b[8]=1;return this},toString:function(){for(var b="[",a=0;9>a;a++)b+=this.data[a],b+=8!==a?", ":"";return b+"]"},transpose:function(){var b=this.data,
|
|
a;a=b[1];b[1]=b[3];b[3]=a;a=b[2];b[2]=b[6];b[6]=a;a=b[5];b[5]=b[7];b[7]=a;return this}});Object.defineProperty(e,"IDENTITY",{get:function(){var b=new e;return function(){return b}}()});Object.defineProperty(e,"ZERO",{get:function(){var b=(new e).set([0,0,0,0,0,0,0,0,0]);return function(){return b}}()});return{Mat3:e}}());Object.assign(pc,function(){var e=function(){var b=new Float32Array(16);b[0]=b[5]=b[10]=b[15]=1;this.data=b};Object.assign(e.prototype,{add2:function(b,a){var c=b.data,d=a.data,f=this.data;f[0]=c[0]+d[0];f[1]=c[1]+d[1];f[2]=c[2]+d[2];f[3]=c[3]+d[3];f[4]=c[4]+d[4];f[5]=c[5]+d[5];f[6]=c[6]+d[6];f[7]=c[7]+d[7];f[8]=c[8]+d[8];f[9]=c[9]+d[9];f[10]=c[10]+d[10];f[11]=c[11]+d[11];f[12]=c[12]+d[12];f[13]=c[13]+d[13];f[14]=c[14]+d[14];f[15]=c[15]+d[15];return this},add:function(b){return this.add2(this,b)},
|
|
clone:function(){return(new pc.Mat4).copy(this)},copy:function(b){b=b.data;var a=this.data;a[0]=b[0];a[1]=b[1];a[2]=b[2];a[3]=b[3];a[4]=b[4];a[5]=b[5];a[6]=b[6];a[7]=b[7];a[8]=b[8];a[9]=b[9];a[10]=b[10];a[11]=b[11];a[12]=b[12];a[13]=b[13];a[14]=b[14];a[15]=b[15];return this},equals:function(b){var a=this.data;b=b.data;return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&
|
|
a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15]},isIdentity:function(){var b=this.data;return 1===b[0]&&0===b[1]&&0===b[2]&&0===b[3]&&0===b[4]&&1===b[5]&&0===b[6]&&0===b[7]&&0===b[8]&&0===b[9]&&1===b[10]&&0===b[11]&&0===b[12]&&0===b[13]&&0===b[14]&&1===b[15]},mul2:function(b,a){var c,d,f,g,l,h,e,k,n,q,m,r,t,u,x,v,w,y,D,B;v=b.data;var z=a.data,A=this.data;c=v[0];d=v[1];f=v[2];g=v[3];l=v[4];h=v[5];e=v[6];k=v[7];n=v[8];q=v[9];m=v[10];r=v[11];t=v[12];u=v[13];x=v[14];v=v[15];w=z[0];y=z[1];D=z[2];B=z[3];A[0]=
|
|
c*w+l*y+n*D+t*B;A[1]=d*w+h*y+q*D+u*B;A[2]=f*w+e*y+m*D+x*B;A[3]=g*w+k*y+r*D+v*B;w=z[4];y=z[5];D=z[6];B=z[7];A[4]=c*w+l*y+n*D+t*B;A[5]=d*w+h*y+q*D+u*B;A[6]=f*w+e*y+m*D+x*B;A[7]=g*w+k*y+r*D+v*B;w=z[8];y=z[9];D=z[10];B=z[11];A[8]=c*w+l*y+n*D+t*B;A[9]=d*w+h*y+q*D+u*B;A[10]=f*w+e*y+m*D+x*B;A[11]=g*w+k*y+r*D+v*B;w=z[12];y=z[13];D=z[14];B=z[15];A[12]=c*w+l*y+n*D+t*B;A[13]=d*w+h*y+q*D+u*B;A[14]=f*w+e*y+m*D+x*B;A[15]=g*w+k*y+r*D+v*B;return this},mul:function(b){return this.mul2(this,b)},transformPoint:function(b,
|
|
a){var c,d,f,g;g=this.data;c=b.x;d=b.y;f=b.z;a=void 0===a?new pc.Vec3:a;a.x=c*g[0]+d*g[4]+f*g[8]+g[12];a.y=c*g[1]+d*g[5]+f*g[9]+g[13];a.z=c*g[2]+d*g[6]+f*g[10]+g[14];return a},transformVector:function(b,a){var c,d,f,g;g=this.data;c=b.x;d=b.y;f=b.z;a=void 0===a?new pc.Vec3:a;a.x=c*g[0]+d*g[4]+f*g[8];a.y=c*g[1]+d*g[5]+f*g[9];a.z=c*g[2]+d*g[6]+f*g[10];return a},transformVec4:function(b,a){var c,d,f,g,l;l=this.data;c=b.x;d=b.y;f=b.z;g=b.w;a=void 0===a?new pc.Vec4:a;a.x=c*l[0]+d*l[4]+f*l[8]+g*l[12];a.y=
|
|
c*l[1]+d*l[5]+f*l[9]+g*l[13];a.z=c*l[2]+d*l[6]+f*l[10]+g*l[14];a.w=c*l[3]+d*l[7]+f*l[11]+g*l[15];return a},setLookAt:function(){var b,a,c;b=new pc.Vec3;a=new pc.Vec3;c=new pc.Vec3;return function(d,f,g){c.sub2(d,f).normalize();a.copy(g).normalize();b.cross(a,c).normalize();a.cross(c,b);f=this.data;f[0]=b.x;f[1]=b.y;f[2]=b.z;f[3]=0;f[4]=a.x;f[5]=a.y;f[6]=a.z;f[7]=0;f[8]=c.x;f[9]=c.y;f[10]=c.z;f[11]=0;f[12]=d.x;f[13]=d.y;f[14]=d.z;f[15]=1;return this}}(),setFrustum:function(b,a,c,d,f,g){var l,h,e,k,
|
|
n;l=2*f;h=a-b;e=d-c;k=g-f;n=this.data;n[0]=l/h;n[1]=0;n[2]=0;n[3]=0;n[4]=0;n[5]=l/e;n[6]=0;n[7]=0;n[8]=(a+b)/h;n[9]=(d+c)/e;n[10]=(-g-f)/k;n[11]=-1;n[12]=0;n[13]=0;n[14]=-l*g/k;n[15]=0;return this},setPerspective:function(b,a,c,d,f){f?(b=c*Math.tan(b*Math.PI/360),f=b/a):(f=c*Math.tan(b*Math.PI/360),b=f*a);return this.setFrustum(-b,b,-f,f,c,d)},setOrtho:function(b,a,c,d,f,g){var l=this.data;l[0]=2/(a-b);l[1]=0;l[2]=0;l[3]=0;l[4]=0;l[5]=2/(d-c);l[6]=0;l[7]=0;l[8]=0;l[9]=0;l[10]=-2/(g-f);l[11]=0;l[12]=
|
|
-(a+b)/(a-b);l[13]=-(d+c)/(d-c);l[14]=-(g+f)/(g-f);l[15]=1;return this},setFromAxisAngle:function(b,a){var c,d,f,g,l,h,e,k,n;a*=pc.math.DEG_TO_RAD;c=b.x;d=b.y;f=b.z;g=Math.cos(a);l=Math.sin(a);h=1-g;e=h*c;k=h*d;n=this.data;n[0]=e*c+g;n[1]=e*d+l*f;n[2]=e*f-l*d;n[3]=0;n[4]=e*d-l*f;n[5]=k*d+g;n[6]=k*f+l*c;n[7]=0;n[8]=e*f+l*d;n[9]=k*f-c*l;n[10]=h*f*f+g;n[11]=0;n[12]=0;n[13]=0;n[14]=0;n[15]=1;return this},setTranslate:function(b,a,c){var d=this.data;d[0]=1;d[1]=0;d[2]=0;d[3]=0;d[4]=0;d[5]=1;d[6]=0;d[7]=
|
|
0;d[8]=0;d[9]=0;d[10]=1;d[11]=0;d[12]=b;d[13]=a;d[14]=c;d[15]=1;return this},setScale:function(b,a,c){var d=this.data;d[0]=b;d[1]=0;d[2]=0;d[3]=0;d[4]=0;d[5]=a;d[6]=0;d[7]=0;d[8]=0;d[9]=0;d[10]=c;d[11]=0;d[12]=0;d[13]=0;d[14]=0;d[15]=1;return this},invert:function(){var b,a,c,d,f,g,l,h,e,k,n,q,m,r,t,u,x,v,w,y,D,B,z,A,F,I,G,H,C,E;E=this.data;b=E[0];a=E[1];c=E[2];d=E[3];f=E[4];g=E[5];l=E[6];h=E[7];e=E[8];k=E[9];n=E[10];q=E[11];m=E[12];r=E[13];t=E[14];u=E[15];x=b*g-a*f;v=b*l-c*f;w=b*h-d*f;y=a*l-c*g;
|
|
D=a*h-d*g;B=c*h-d*l;z=e*r-k*m;A=e*t-n*m;F=e*u-q*m;I=k*t-n*r;G=k*u-q*r;H=n*u-q*t;C=x*H-v*G+w*I+y*F-D*A+B*z;0===C?this.setIdentity():(C=1/C,E[0]=(g*H-l*G+h*I)*C,E[1]=(-a*H+c*G-d*I)*C,E[2]=(r*B-t*D+u*y)*C,E[3]=(-k*B+n*D-q*y)*C,E[4]=(-f*H+l*F-h*A)*C,E[5]=(b*H-c*F+d*A)*C,E[6]=(-m*B+t*w-u*v)*C,E[7]=(e*B-n*w+q*v)*C,E[8]=(f*G-g*F+h*z)*C,E[9]=(-b*G+a*F-d*z)*C,E[10]=(m*D-r*w+u*x)*C,E[11]=(-e*D+k*w-q*x)*C,E[12]=(-f*I+g*A-l*z)*C,E[13]=(b*I-a*A+c*z)*C,E[14]=(-m*y+r*v-t*x)*C,E[15]=(e*y-k*v+n*x)*C);return this},
|
|
set:function(b){var a=this.data;a[0]=b[0];a[1]=b[1];a[2]=b[2];a[3]=b[3];a[4]=b[4];a[5]=b[5];a[6]=b[6];a[7]=b[7];a[8]=b[8];a[9]=b[9];a[10]=b[10];a[11]=b[11];a[12]=b[12];a[13]=b[13];a[14]=b[14];a[15]=b[15];return this},setIdentity:function(){var b=this.data;b[0]=1;b[1]=0;b[2]=0;b[3]=0;b[4]=0;b[5]=1;b[6]=0;b[7]=0;b[8]=0;b[9]=0;b[10]=1;b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return this},setTRS:function(b,a,c){var d,f,g,l,h,e,k,n,q,m,r,t,u;d=b.x;f=b.y;b=b.z;g=a.x;l=a.y;h=a.z;e=a.w;a=c.x;k=c.y;c=c.z;n=
|
|
g+g;q=l+l;m=h+h;r=g*n;t=g*q;g*=m;u=l*q;l*=m;h*=m;n*=e;q*=e;e*=m;m=this.data;m[0]=(1-(u+h))*a;m[1]=(t+e)*a;m[2]=(g-q)*a;m[3]=0;m[4]=(t-e)*k;m[5]=(1-(r+h))*k;m[6]=(l+n)*k;m[7]=0;m[8]=(g+q)*c;m[9]=(l-n)*c;m[10]=(1-(r+u))*c;m[11]=0;m[12]=d;m[13]=f;m[14]=b;m[15]=1;return this},transpose:function(){var b,a=this.data;b=a[1];a[1]=a[4];a[4]=b;b=a[2];a[2]=a[8];a[8]=b;b=a[3];a[3]=a[12];a[12]=b;b=a[6];a[6]=a[9];a[9]=b;b=a[7];a[7]=a[13];a[13]=b;b=a[11];a[11]=a[14];a[14]=b;return this},invertTo3x3:function(b){var a,
|
|
c,d,f;a=this.data;b=b.data;var g=a[0],l=a[1],h=a[2],e=a[4],k=a[5],n=a[6],q=a[8],m=a[9],r=a[10];a=r*k-n*m;c=-r*e+n*q;d=m*e-k*q;f=g*a+l*c+h*d;if(0===f)return this;f=1/f;b[0]=f*a;b[1]=f*(-r*l+h*m);b[2]=f*(n*l-h*k);b[3]=f*c;b[4]=f*(r*g-h*q);b[5]=f*(-n*g+h*e);b[6]=f*d;b[7]=f*(-m*g+l*q);b[8]=f*(k*g-l*e);return this},getTranslation:function(b){b=void 0===b?new pc.Vec3:b;return b.set(this.data[12],this.data[13],this.data[14])},getX:function(b){b=void 0===b?new pc.Vec3:b;return b.set(this.data[0],this.data[1],
|
|
this.data[2])},getY:function(b){b=void 0===b?new pc.Vec3:b;return b.set(this.data[4],this.data[5],this.data[6])},getZ:function(b){b=void 0===b?new pc.Vec3:b;return b.set(this.data[8],this.data[9],this.data[10])},getScale:function(){var b,a,c;b=new pc.Vec3;a=new pc.Vec3;c=new pc.Vec3;return function(d){d=void 0===d?new pc.Vec3:d;this.getX(b);this.getY(a);this.getZ(c);d.set(b.length(),a.length(),c.length());return d}}(),setFromEulerAngles:function(b,a,c){var d,f,g,l;b*=pc.math.DEG_TO_RAD;a*=pc.math.DEG_TO_RAD;
|
|
c*=pc.math.DEG_TO_RAD;d=Math.sin(-b);b=Math.cos(-b);f=Math.sin(-a);a=Math.cos(-a);g=Math.sin(-c);c=Math.cos(-c);l=this.data;l[0]=a*c;l[1]=-a*g;l[2]=f;l[3]=0;l[4]=b*g+c*d*f;l[5]=b*c-d*f*g;l[6]=-a*d;l[7]=0;l[8]=d*g-b*c*f;l[9]=c*d+b*f*g;l[10]=b*a;l[11]=0;l[12]=0;l[13]=0;l[14]=0;l[15]=1;return this},getEulerAngles:function(){var b=new pc.Vec3;return function(a){var c,d,f,g,l,h;a=void 0===a?new pc.Vec3:a;this.getScale(b);f=b.x;c=b.y;g=b.z;l=this.data;d=Math.asin(-l[2]/f);h=.5*Math.PI;d<h?d>-h?(c=Math.atan2(l[6]/
|
|
c,l[10]/g),f=Math.atan2(l[1]/f,l[0]/f)):(f=0,c=-Math.atan2(l[4]/c,l[5]/c)):(f=0,c=Math.atan2(l[4]/c,l[5]/c));return a.set(c,d,f).scale(pc.math.RAD_TO_DEG)}}(),toString:function(){var b,a;a="[";for(b=0;16>b;b+=1)a+=this.data[b],a+=15!==b?", ":"";return a+"]"}});Object.defineProperty(e,"IDENTITY",{get:function(){var b=new e;return function(){return b}}()});Object.defineProperty(e,"ZERO",{get:function(){var b=(new e).set([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);return function(){return b}}()});return{Mat4:e}}());Object.assign(pc,function(){var e=function(b,a,c,d){b&&4===b.length?(this.x=b[0],this.y=b[1],this.z=b[2],this.w=b[3]):(this.x=void 0===b?0:b,this.y=void 0===a?0:a,this.z=void 0===c?0:c,this.w=void 0===d?1:d)};Object.assign(e.prototype,{clone:function(){return new pc.Quat(this.x,this.y,this.z,this.w)},conjugate:function(){this.x*=-1;this.y*=-1;this.z*=-1;return this},copy:function(b){this.x=b.x;this.y=b.y;this.z=b.z;this.w=b.w;return this},equals:function(b){return this.x===b.x&&this.y===b.y&&this.z===
|
|
b.z&&this.w===b.w},getAxisAngle:function(b){var a=2*Math.acos(this.w),c=Math.sin(a/2);if(0!==c){if(b.x=this.x/c,b.y=this.y/c,b.z=this.z/c,0>b.x||0>b.y||0>b.z)b.x*=-1,b.y*=-1,b.z*=-1,a*=-1}else b.x=1,b.y=0,b.z=0;return a*pc.math.RAD_TO_DEG},getEulerAngles:function(b){var a,c,d,f,g,l;b=void 0===b?new pc.Vec3:b;d=this.x;f=this.y;g=this.z;l=this.w;c=2*(l*f-d*g);-.99999>=c?(a=2*Math.atan2(d,l),c=-Math.PI/2,d=0):.99999<=c?(a=2*Math.atan2(d,l),c=Math.PI/2,d=0):(a=Math.atan2(2*(l*d+f*g),1-2*(d*d+f*f)),c=
|
|
Math.asin(c),d=Math.atan2(2*(l*g+d*f),1-2*(f*f+g*g)));return b.set(a,c,d).scale(pc.math.RAD_TO_DEG)},invert:function(){return this.conjugate().normalize()},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},mul:function(b){var a,c,d,f,g,l,h;a=this.x;c=this.y;d=this.z;f=this.w;g=b.x;l=b.y;h=b.z;b=b.w;this.x=f*g+a*b+c*h-d*l;this.y=f*l+c*b+d*g-a*h;this.z=f*h+d*b+a*l-c*g;this.w=
|
|
f*b-a*g-c*l-d*h;return this},mul2:function(b,a){var c,d,f,g,l,h,e,k;c=b.x;d=b.y;f=b.z;g=b.w;l=a.x;h=a.y;e=a.z;k=a.w;this.x=g*l+c*k+d*e-f*h;this.y=g*h+d*k+f*l-c*e;this.z=g*e+f*k+c*h-d*l;this.w=g*k-c*l-d*h-f*e;return this},normalize:function(){var b=this.length();0===b?(this.x=this.y=this.z=0,this.w=1):(b=1/b,this.x*=b,this.y*=b,this.z*=b,this.w*=b);return this},set:function(b,a,c,d){this.x=b;this.y=a;this.z=c;this.w=d;return this},setFromAxisAngle:function(b,a){var c,d;a*=.5*pc.math.DEG_TO_RAD;c=Math.sin(a);
|
|
d=Math.cos(a);this.x=c*b.x;this.y=c*b.y;this.z=c*b.z;this.w=d;return this},setFromEulerAngles:function(b,a,c){var d,f,g;d=.5*pc.math.DEG_TO_RAD;b*=d;a*=d;c*=d;d=Math.sin(b);b=Math.cos(b);f=Math.sin(a);a=Math.cos(a);g=Math.sin(c);c=Math.cos(c);this.x=d*a*c-b*f*g;this.y=b*f*c+d*a*g;this.z=b*a*g-d*f*c;this.w=b*a*c+d*f*g;return this},setFromMat4:function(b){var a,c,d,f,g,l,h,e,k,n,q;b=b.data;a=b[0];c=b[1];d=b[2];f=b[4];g=b[5];l=b[6];h=b[8];e=b[9];b=b[10];k=1/Math.sqrt(a*a+c*c+d*d);n=1/Math.sqrt(f*f+g*
|
|
g+l*l);q=1/Math.sqrt(h*h+e*e+b*b);a*=k;c*=k;d*=k;f*=n;g*=n;l*=n;h*=q;e*=q;b*=q;k=a+g+b;0<=k?(a=Math.sqrt(k+1),this.w=.5*a,a=.5/a,this.x=(l-e)*a,this.y=(h-d)*a,this.z=(c-f)*a):a>g?a>b?(a=Math.sqrt(a-(g+b)+1),this.x=.5*a,a=.5/a,this.w=(l-e)*a,this.y=(c+f)*a,this.z=(d+h)*a):(a=Math.sqrt(b-(a+g)+1),this.z=.5*a,a=.5/a,this.w=(c-f)*a,this.x=(h+d)*a,this.y=(e+l)*a):g>b?(a=Math.sqrt(g-(b+a)+1),this.y=.5*a,a=.5/a,this.w=(h-d)*a,this.z=(l+e)*a,this.x=(f+c)*a):(a=Math.sqrt(b-(a+g)+1),this.z=.5*a,a=.5/a,this.w=
|
|
(c-f)*a,this.x=(h+d)*a,this.y=(e+l)*a);return this},slerp:function(b,a,c){var d,f,g,l,h,e;d=b.x;f=b.y;g=b.z;b=b.w;l=a.x;h=a.y;e=a.z;a=a.w;var k=b*a+d*l+f*h+g*e;0>k&&(a=-a,l=-l,h=-h,e=-e,k=-k);if(1<=Math.abs(k))return this.w=b,this.x=d,this.y=f,this.z=g,this;var n=Math.acos(k),q=Math.sqrt(1-k*k);if(.001>Math.abs(q))return this.w=.5*b+.5*a,this.x=.5*d+.5*l,this.y=.5*f+.5*h,this.z=.5*g+.5*e,this;k=Math.sin((1-c)*n)/q;c=Math.sin(c*n)/q;this.w=b*k+a*c;this.x=d*k+l*c;this.y=f*k+h*c;this.z=g*k+e*c;return this},
|
|
transformVector:function(b,a){void 0===a&&(a=new pc.Vec3);var c=b.x,d=b.y,f=b.z,g=this.x,l=this.y,h=this.z,e=this.w,k=e*c+l*f-h*d,n=e*d+h*c-g*f,q=e*f+g*d-l*c,c=-g*c-l*d-h*f;a.x=k*e+c*-g+n*-h-q*-l;a.y=n*e+c*-l+q*-g-k*-h;a.z=q*e+c*-h+k*-l-n*-g;return a},toString:function(){return"["+this.x+", "+this.y+", "+this.z+", "+this.w+"]"}});Object.defineProperty(e,"IDENTITY",{get:function(){var b=new e;return function(){return b}}()});Object.defineProperty(e,"ZERO",{get:function(){var b=new e(0,0,0,0);return function(){return b}}()});
|
|
return{Quat:e}}());Object.assign(pc,function(){var e=function(b){this.keys=[];this.type=1;this.tension=.5;if(b)for(var a=0;a<b.length-1;a+=2)this.keys.push([b[a],b[a+1]]);this.sort()};Object.assign(e.prototype,{add:function(b,a){for(var c=this.keys,d=c.length,f=0;f<d&&!(c[f][0]>b);f++);c=[b,a];this.keys.splice(f,0,c);return c},get:function(b){return this.keys[b]},sort:function(){this.keys.sort(function(b,a){return b[0]-a[0]})},value:function(b){var a,c=this.keys,d=c.length;if(!d)return 0;if(b<c[0][0])return c[0][1];
|
|
if(b>c[d-1][0])return c[d-1][1];var f=0,g=d?c[0][1]:0,l=1,h=0;for(a=0;a<d;a++){if(c[a][0]===b)return c[a][1];h=c[a][1];if(b<c[a][0]){l=c[a][0];break}f=c[a][0];g=c[a][1]}var e=l-f;b=0===e?0:(b-f)/e;if(1===this.type)b*=b*(3-2*b);else if(2===this.type||3===this.type){var e=g+(g-h),k=h+(h-g),n=l=f=l-f;0<a&&a--;0<a&&(e=c[a-1][1],l=c[a][0]-c[a-1][0]);d>a+1&&(f=c[a+1][0]-c[a][0]);d>a+2&&(n=c[a+2][0]-c[a+1][0],k=c[a+2][1]);e=g+(e-g)*f/l;k=h+(k-h)*f/n;return 2===this.type?this._interpolateCatmullRom(e,g,h,
|
|
k,b):this._interpolateCardinal(e,g,h,k,b,this.tension)}return pc.math.lerp(g,h,b)},_interpolateHermite:function(b,a,c,d,f){var g=f*f,l=f*f*f;return b*(2*l-3*g+1)+a*(-2*l+3*g)+c*(l-2*g+f)+d*(l-g)},_interpolateCardinal:function(b,a,c,d,f,g){return this._interpolateHermite(a,c,g*(c-b),g*(d-a),f)},_interpolateCatmullRom:function(b,a,c,d,f){return this._interpolateCardinal(b,a,c,d,f,.5)},closest:function(b){for(var a=this.keys,c=a.length,d=2,f=null,g=0;g<c;g++){var l=Math.abs(b-a[g][0]);if(d>=l)d=l,f=
|
|
a[g];else break}return f},clone:function(){var b=new pc.Curve;b.keys=pc.extend(b.keys,this.keys);b.type=this.type;return b},quantize:function(b){b=Math.max(b,2);for(var a=new Float32Array(b),c=1/(b-1),d=0;d<b;d++){var f=this.value(c*d);a[d]=f}return a}});Object.defineProperty(e.prototype,"length",{get:function(){return this.keys.length}});return{Curve:e,CURVE_LINEAR:0,CURVE_SMOOTHSTEP:1,CURVE_CATMULL:2,CURVE_CARDINAL:3}}());Object.assign(pc,function(){var e=function(){var b;this.curves=[];this._type=pc.CURVE_SMOOTHSTEP;if(1<arguments.length)for(b=0;b<arguments.length;b++)this.curves.push(new pc.Curve(arguments[b]));else if(0===arguments.length)this.curves.push(new pc.Curve);else{var a=arguments[0];if("number"===pc.type(a))for(b=0;b<a;b++)this.curves.push(new pc.Curve);else for(b=0;b<a.length;b++)this.curves.push(new pc.Curve(a[b]))}};Object.assign(e.prototype,{get:function(b){return this.curves[b]},value:function(b,
|
|
a){var c=this.curves.length;a=a||[];a.length=c;for(var d=0;d<c;d++)a[d]=this.curves[d].value(b);return a},clone:function(){var b=new pc.CurveSet;b.curves=[];for(var a=0;a<this.curves.length;a++)b.curves.push(this.curves[a].clone());b._type=this._type;return b},quantize:function(b){b=Math.max(b,2);for(var a=this.curves.length,c=new Float32Array(b*a),d=1/(b-1),f=[],g=0;g<b;g++){var l=this.value(d*g,f);if(1==a)c[g]=l[0];else for(var h=0;h<a;h++)c[g*a+h]=l[h]}return c}});Object.defineProperty(e.prototype,
|
|
"length",{get:function(){return this.curves.length}});Object.defineProperty(e.prototype,"type",{get:function(){return this._type},set:function(b){this._type=b;for(var a=0;a<this.curves.length;a++)this.curves[a].type=b}});return{CurveSet:e}}());Object.assign(pc,function(){var e=new pc.Vec3,b=new pc.Vec3,a=new pc.Vec3,c=new pc.Vec3,d=new pc.Vec3,f=function(a,b){this.center=a||new pc.Vec3(0,0,0);this.halfExtents=b||new pc.Vec3(.5,.5,.5);this._min=new pc.Vec3;this._max=new pc.Vec3};Object.assign(f.prototype,{add:function(a){var b=this.center,c=b.x,d=b.y,f=b.z,g=this.halfExtents,e=g.x,m=g.y,r=g.z,t=c-e,c=c+e,e=d-m,d=d+m,m=f-r,f=f+r,r=a.center,u=r.x,x=r.y,r=r.z;a=a.halfExtents;var v=a.x,w=a.y,y=a.z;a=u-v;u+=v;v=x-w;x+=w;w=r-y;r+=y;a<t&&(t=a);
|
|
u>c&&(c=u);v<e&&(e=v);x>d&&(d=x);w<m&&(m=w);r>f&&(f=r);b.x=.5*(t+c);b.y=.5*(e+d);b.z=.5*(m+f);g.x=.5*(c-t);g.y=.5*(d-e);g.z=.5*(f-m)},copy:function(a){this.center.copy(a.center);this.halfExtents.copy(a.halfExtents);this.type=a.type},clone:function(){return new pc.BoundingBox(this.center.clone(),this.halfExtents.clone())},intersects:function(a){var b=this.getMax(),c=this.getMin(),d=a.getMax();a=a.getMin();return c.x<=d.x&&b.x>=a.x&&c.y<=d.y&&b.y>=a.y&&c.z<=d.z&&b.z>=a.z},_intersectsRay:function(d,
|
|
f){var g=e.copy(this.getMin()).sub(d.origin),l=b.copy(this.getMax()).sub(d.origin),k=d.direction;0===k.x?(g.x=0>g.x?-Number.MAX_VALUE:Number.MAX_VALUE,l.x=0>l.x?-Number.MAX_VALUE:Number.MAX_VALUE):(g.x/=k.x,l.x/=k.x);0===k.y?(g.y=0>g.y?-Number.MAX_VALUE:Number.MAX_VALUE,l.y=0>l.y?-Number.MAX_VALUE:Number.MAX_VALUE):(g.y/=k.y,l.y/=k.y);0===k.z?(g.z=0>g.z?-Number.MAX_VALUE:Number.MAX_VALUE,l.z=0>l.z?-Number.MAX_VALUE:Number.MAX_VALUE):(g.z/=k.z,l.z/=k.z);k=a.set(Math.min(g.x,l.x),Math.min(g.y,l.y),
|
|
Math.min(g.z,l.z));g=c.set(Math.max(g.x,l.x),Math.max(g.y,l.y),Math.max(g.z,l.z));l=Math.max(Math.max(k.x,k.y),k.z);(g=Math.min(Math.min(g.x,g.y),g.z)>=l&&0<=l)&&f.copy(d.direction).scale(l).add(d.origin);return g},_fastIntersectsRay:function(f){var g=f.direction;e.sub2(f.origin,this.center);c.set(Math.abs(e.x),Math.abs(e.y),Math.abs(e.z));a.mul2(e,g);if(c.x>this.halfExtents.x&&0<=a.x||c.y>this.halfExtents.y&&0<=a.y||c.z>this.halfExtents.z&&0<=a.z)return!1;d.set(Math.abs(g.x),Math.abs(g.y),Math.abs(g.z));
|
|
b.cross(g,e);b.set(Math.abs(b.x),Math.abs(b.y),Math.abs(b.z));return b.x>this.halfExtents.y*d.z+this.halfExtents.z*d.y||b.y>this.halfExtents.x*d.z+this.halfExtents.z*d.x||b.z>this.halfExtents.x*d.y+this.halfExtents.y*d.x?!1:!0},intersectsRay:function(a,b){return b?this._intersectsRay(a,b):this._fastIntersectsRay(a)},setMinMax:function(a,b){this.center.add2(b,a).scale(.5);this.halfExtents.sub2(b,a).scale(.5)},getMin:function(){return this._min.copy(this.center).sub(this.halfExtents)},getMax:function(){return this._max.copy(this.center).add(this.halfExtents)},
|
|
containsPoint:function(a){var b=this.getMin(),c=this.getMax();return a.x<b.x||a.x>c.x||a.y<b.y||a.y>c.y||a.z<b.z||a.z>c.z?!1:!0},setFromTransformedAabb:function(a,b){var c=this.center,d=this.halfExtents,f=a.center,g=a.halfExtents;b=b.data;var l=b[0],e=b[4],r=b[8],t=b[1],u=b[5],x=b[9],v=b[2],w=b[6],y=b[10],D=Math.abs(l),B=Math.abs(e),z=Math.abs(r),A=Math.abs(t),F=Math.abs(u),I=Math.abs(x),G=Math.abs(v),H=Math.abs(w),C=Math.abs(y);c.set(b[12]+l*f.x+e*f.y+r*f.z,b[13]+t*f.x+u*f.y+x*f.z,b[14]+v*f.x+w*
|
|
f.y+y*f.z);d.set(D*g.x+B*g.y+z*g.z,A*g.x+F*g.y+I*g.z,G*g.x+H*g.y+C*g.z)},compute:function(a){for(var c=e.set(a[0],a[1],a[2]),d=b.set(a[0],a[1],a[2]),f=a.length/3,g=1;g<f;g++){var n=a[3*g+0],q=a[3*g+1],m=a[3*g+2];n<c.x&&(c.x=n);q<c.y&&(c.y=q);m<c.z&&(c.z=m);n>d.x&&(d.x=n);q>d.y&&(d.y=q);m>d.z&&(d.z=m)}this.setMinMax(c,d)},intersectsBoundingSphere:function(a){return this._distanceToBoundingSphereSq(a)<=a.radius*a.radius?!0:!1},_distanceToBoundingSphereSq:function(a){for(var b=this.getMin(),c=this.getMax(),
|
|
d=0,f=["x","y","z"],g=0;3>g;++g){var e=0,m=a.center[f[g]],r=b[f[g]],t=c[f[g]];m<r&&(r-=m,e+=r*r);m>t&&(r=m-t,e+=r*r);d+=e}return d}});return{BoundingBox:f}}());Object.assign(pc,function(){function e(a,b){this.center=a||new pc.Vec3(0,0,0);this.radius=void 0===b?.5:b}var b=new pc.Vec3,a=new pc.Vec3,c=new pc.Vec3,d=new pc.Vec3;Object.assign(e.prototype,{containsPoint:function(a){a=b.sub2(a,this.center).lengthSq();var c=this.radius;return a<c*c},compute:function(f){var g,l=f.length/3;for(g=0;g<l;g++)b.set(f[3*g],f[3*g+1],f[3*g+2]),c.addSelf(b),0===g%100&&(c.scale(1/l),a.add(c),c.set(0,0,0));c.scale(1/l);a.add(c);this.center.copy(a);var h=0;for(g=0;g<l;g++)b.set(f[3*
|
|
g],f[3*g+1],f[3*g+2]),d.sub2(b,this.center),h=Math.max(d.lengthSq(),h);this.radius=Math.sqrt(h)},intersectsRay:function(c,d){var f=b.copy(c.origin).sub(this.center),g=f.dot(a.copy(c.direction).normalize()),f=f.dot(f)-this.radius*this.radius;if(0<f&&0<g)return null;f=g*g-f;if(0>f)return!1;g=Math.abs(-g-Math.sqrt(f));d&&d.copy(c.direction).scale(g).add(c.origin);return!0},intersectsBoundingSphere:function(a){b.sub2(a.center,this.center);a=a.radius+this.radius;return b.lengthSq()<=a*a?!0:!1}});return{BoundingSphere:e}}());Object.assign(pc,function(){var e=new pc.Mat4,b=function(a,b){a=a||(new pc.Mat4).setPerspective(90,16/9,.1,1E3);b=b||new pc.Mat4;this.planes=[];for(var c=0;6>c;c++)this.planes[c]=[];this.update(a,b)};Object.assign(b.prototype,{update:function(a,b){e.mul2(a,b);var c=e.data;this.planes[0][0]=c[3]-c[0];this.planes[0][1]=c[7]-c[4];this.planes[0][2]=c[11]-c[8];this.planes[0][3]=c[15]-c[12];var f=Math.sqrt(this.planes[0][0]*this.planes[0][0]+this.planes[0][1]*this.planes[0][1]+this.planes[0][2]*this.planes[0][2]);
|
|
this.planes[0][0]/=f;this.planes[0][1]/=f;this.planes[0][2]/=f;this.planes[0][3]/=f;this.planes[1][0]=c[3]+c[0];this.planes[1][1]=c[7]+c[4];this.planes[1][2]=c[11]+c[8];this.planes[1][3]=c[15]+c[12];f=Math.sqrt(this.planes[1][0]*this.planes[1][0]+this.planes[1][1]*this.planes[1][1]+this.planes[1][2]*this.planes[1][2]);this.planes[1][0]/=f;this.planes[1][1]/=f;this.planes[1][2]/=f;this.planes[1][3]/=f;this.planes[2][0]=c[3]+c[1];this.planes[2][1]=c[7]+c[5];this.planes[2][2]=c[11]+c[9];this.planes[2][3]=
|
|
c[15]+c[13];f=Math.sqrt(this.planes[2][0]*this.planes[2][0]+this.planes[2][1]*this.planes[2][1]+this.planes[2][2]*this.planes[2][2]);this.planes[2][0]/=f;this.planes[2][1]/=f;this.planes[2][2]/=f;this.planes[2][3]/=f;this.planes[3][0]=c[3]-c[1];this.planes[3][1]=c[7]-c[5];this.planes[3][2]=c[11]-c[9];this.planes[3][3]=c[15]-c[13];f=Math.sqrt(this.planes[3][0]*this.planes[3][0]+this.planes[3][1]*this.planes[3][1]+this.planes[3][2]*this.planes[3][2]);this.planes[3][0]/=f;this.planes[3][1]/=f;this.planes[3][2]/=
|
|
f;this.planes[3][3]/=f;this.planes[4][0]=c[3]-c[2];this.planes[4][1]=c[7]-c[6];this.planes[4][2]=c[11]-c[10];this.planes[4][3]=c[15]-c[14];f=Math.sqrt(this.planes[4][0]*this.planes[4][0]+this.planes[4][1]*this.planes[4][1]+this.planes[4][2]*this.planes[4][2]);this.planes[4][0]/=f;this.planes[4][1]/=f;this.planes[4][2]/=f;this.planes[4][3]/=f;this.planes[5][0]=c[3]+c[2];this.planes[5][1]=c[7]+c[6];this.planes[5][2]=c[11]+c[10];this.planes[5][3]=c[15]+c[14];f=Math.sqrt(this.planes[5][0]*this.planes[5][0]+
|
|
this.planes[5][1]*this.planes[5][1]+this.planes[5][2]*this.planes[5][2]);this.planes[5][0]/=f;this.planes[5][1]/=f;this.planes[5][2]/=f;this.planes[5][3]/=f},containsPoint:function(a){for(var b=0;6>b;b++)if(0>=this.planes[b][0]*a.x+this.planes[b][1]*a.y+this.planes[b][2]*a.z+this.planes[b][3])return!1;return!0},containsSphere:function(a){var b=0,d,f,g=a.radius;f=a.center;a=f.x;var l=f.y,h=f.z,e=this.planes;for(f=0;6>f;f++){d=e[f];d=d[0]*a+d[1]*l+d[2]*h+d[3];if(d<=-g)return 0;d>g&&b++}return 6===b?
|
|
2:1}});return{Frustum:b}}());Object.assign(pc,function(){var e=new pc.Vec3,b=function(a,b){this.normal=b||new pc.Vec3(0,0,1);this.point=a||new pc.Vec3(0,0,0)};Object.assign(b.prototype,{intersectsLine:function(a,b,d){var c=-this.normal.dot(this.point),g=this.normal.dot(a)+c,c=this.normal.dot(b)+c,g=g/(g-c);(c=0<=g&&1>=g)&&d&&d.lerp(a,b,g);return c},intersectsRay:function(a,b){var c=e.sub2(this.point,a.origin),c=this.normal.dot(c)/this.normal.dot(a.direction),f=0<=c;f&&b&&b.copy(a.direction).scale(c).add(a.origin);return f}});
|
|
return{Plane:b}}());Object.assign(pc,function(){return{Ray:function(e,b){this.origin=e||new pc.Vec3(0,0,0);this.direction=b||new pc.Vec3(0,0,-1)}}}());Object.assign(pc,function(){var e=new pc.Ray,b=new pc.Vec3,a=new pc.BoundingSphere,c=new pc.Mat4,d=function(a,b){this.halfExtents=b||new pc.Vec3(.5,.5,.5);a=a||c.setIdentity();this._modelTransform=a.clone().invert();this._worldTransform=a.clone();this._aabb=new pc.BoundingBox(new pc.Vec3,this.halfExtents)};Object.assign(d.prototype,{intersectsRay:function(a,b){this._modelTransform.transformPoint(a.origin,e.origin);this._modelTransform.transformVector(a.direction,e.direction);if(b){var d=this._aabb._intersectsRay(e,
|
|
b);c.copy(this._modelTransform).invert().transformPoint(b,b);return d}return this._aabb._fastIntersectsRay(e)},containsPoint:function(a){this._modelTransform.transformPoint(a,b);return this._aabb.containsPoint(b)},intersectsBoundingSphere:function(b){this._modelTransform.transformPoint(b.center,a.center);a.radius=b.radius;return this._aabb.intersectsBoundingSphere(a)?!0:!1}});Object.defineProperty(d.prototype,"worldTransform",{get:function(){return this._worldTransform},set:function(a){this._worldTransform.copy(a);
|
|
this._modelTransform.copy(a).invert()}});return{OrientedBox:d}}());(function(){var e={ADDRESS_REPEAT:0,ADDRESS_CLAMP_TO_EDGE:1,ADDRESS_MIRRORED_REPEAT:2,BLENDMODE_ZERO:0,BLENDMODE_ONE:1,BLENDMODE_SRC_COLOR:2,BLENDMODE_ONE_MINUS_SRC_COLOR:3,BLENDMODE_DST_COLOR:4,BLENDMODE_ONE_MINUS_DST_COLOR:5,BLENDMODE_SRC_ALPHA:6,BLENDMODE_SRC_ALPHA_SATURATE:7,BLENDMODE_ONE_MINUS_SRC_ALPHA:8,BLENDMODE_DST_ALPHA:9,BLENDMODE_ONE_MINUS_DST_ALPHA:10,BLENDEQUATION_ADD:0,BLENDEQUATION_SUBTRACT:1,BLENDEQUATION_REVERSE_SUBTRACT:2,BLENDEQUATION_MIN:3,BLENDEQUATION_MAX:4,BUFFER_STATIC:0,
|
|
BUFFER_DYNAMIC:1,BUFFER_STREAM:2,BUFFER_GPUDYNAMIC:3,CLEARFLAG_COLOR:1,CLEARFLAG_DEPTH:2,CLEARFLAG_STENCIL:4,CUBEFACE_POSX:0,CUBEFACE_NEGX:1,CUBEFACE_POSY:2,CUBEFACE_NEGY:3,CUBEFACE_POSZ:4,CUBEFACE_NEGZ:5,CULLFACE_NONE:0,CULLFACE_BACK:1,CULLFACE_FRONT:2,CULLFACE_FRONTANDBACK:3,TYPE_INT8:0,TYPE_UINT8:1,TYPE_INT16:2,TYPE_UINT16:3,TYPE_INT32:4,TYPE_UINT32:5,TYPE_FLOAT32:6,FILTER_NEAREST:0,FILTER_LINEAR:1,FILTER_NEAREST_MIPMAP_NEAREST:2,FILTER_NEAREST_MIPMAP_LINEAR:3,FILTER_LINEAR_MIPMAP_NEAREST:4,FILTER_LINEAR_MIPMAP_LINEAR:5,
|
|
FUNC_NEVER:0,FUNC_LESS:1,FUNC_EQUAL:2,FUNC_LESSEQUAL:3,FUNC_GREATER:4,FUNC_NOTEQUAL:5,FUNC_GREATEREQUAL:6,FUNC_ALWAYS:7,INDEXFORMAT_UINT8:0,INDEXFORMAT_UINT16:1,INDEXFORMAT_UINT32:2,PIXELFORMAT_A8:0,PIXELFORMAT_L8:1,PIXELFORMAT_L8_A8:2,PIXELFORMAT_R5_G6_B5:3,PIXELFORMAT_R5_G5_B5_A1:4,PIXELFORMAT_R4_G4_B4_A4:5,PIXELFORMAT_R8_G8_B8:6,PIXELFORMAT_R8_G8_B8_A8:7,PIXELFORMAT_DXT1:8,PIXELFORMAT_DXT3:9,PIXELFORMAT_DXT5:10,PIXELFORMAT_RGB16F:11,PIXELFORMAT_RGBA16F:12,PIXELFORMAT_RGB32F:13,PIXELFORMAT_RGBA32F:14,
|
|
PIXELFORMAT_R32F:15,PIXELFORMAT_DEPTH:16,PIXELFORMAT_DEPTHSTENCIL:17,PIXELFORMAT_111110F:18,PIXELFORMAT_SRGB:19,PIXELFORMAT_SRGBA:20,PIXELFORMAT_ETC1:21,PIXELFORMAT_ETC2_RGB:22,PIXELFORMAT_ETC2_RGBA:23,PIXELFORMAT_PVRTC_2BPP_RGB_1:24,PIXELFORMAT_PVRTC_2BPP_RGBA_1:25,PIXELFORMAT_PVRTC_4BPP_RGB_1:26,PIXELFORMAT_PVRTC_4BPP_RGBA_1:27,PRIMITIVE_POINTS:0,PRIMITIVE_LINES:1,PRIMITIVE_LINELOOP:2,PRIMITIVE_LINESTRIP:3,PRIMITIVE_TRIANGLES:4,PRIMITIVE_TRISTRIP:5,PRIMITIVE_TRIFAN:6,SEMANTIC_POSITION:"POSITION",
|
|
SEMANTIC_NORMAL:"NORMAL",SEMANTIC_TANGENT:"TANGENT",SEMANTIC_BLENDWEIGHT:"BLENDWEIGHT",SEMANTIC_BLENDINDICES:"BLENDINDICES",SEMANTIC_COLOR:"COLOR",SEMANTIC_TEXCOORD0:"TEXCOORD0",SEMANTIC_TEXCOORD1:"TEXCOORD1",SEMANTIC_TEXCOORD2:"TEXCOORD2",SEMANTIC_TEXCOORD3:"TEXCOORD3",SEMANTIC_TEXCOORD4:"TEXCOORD4",SEMANTIC_TEXCOORD5:"TEXCOORD5",SEMANTIC_TEXCOORD6:"TEXCOORD6",SEMANTIC_TEXCOORD7:"TEXCOORD7",SEMANTIC_ATTR0:"ATTR0",SEMANTIC_ATTR1:"ATTR1",SEMANTIC_ATTR2:"ATTR2",SEMANTIC_ATTR3:"ATTR3",SEMANTIC_ATTR4:"ATTR4",
|
|
SEMANTIC_ATTR5:"ATTR5",SEMANTIC_ATTR6:"ATTR6",SEMANTIC_ATTR7:"ATTR7",SEMANTIC_ATTR8:"ATTR8",SEMANTIC_ATTR9:"ATTR9",SEMANTIC_ATTR10:"ATTR10",SEMANTIC_ATTR11:"ATTR11",SEMANTIC_ATTR12:"ATTR12",SEMANTIC_ATTR13:"ATTR13",SEMANTIC_ATTR14:"ATTR14",SEMANTIC_ATTR15:"ATTR15",SHADERTAG_MATERIAL:1,STENCILOP_KEEP:0,STENCILOP_ZERO:1,STENCILOP_REPLACE:2,STENCILOP_INCREMENT:3,STENCILOP_INCREMENTWRAP:4,STENCILOP_DECREMENT:5,STENCILOP_DECREMENTWRAP:6,STENCILOP_INVERT:7,TEXTURELOCK_READ:1,TEXTURELOCK_WRITE:2,TEXHINT_NONE:0,
|
|
TEXHINT_SHADOWMAP:1,TEXHINT_ASSET:2,TEXHINT_LIGHTMAP:3,UNIFORMTYPE_BOOL:0,UNIFORMTYPE_INT:1,UNIFORMTYPE_FLOAT:2,UNIFORMTYPE_VEC2:3,UNIFORMTYPE_VEC3:4,UNIFORMTYPE_VEC4:5,UNIFORMTYPE_IVEC2:6,UNIFORMTYPE_IVEC3:7,UNIFORMTYPE_IVEC4:8,UNIFORMTYPE_BVEC2:9,UNIFORMTYPE_BVEC3:10,UNIFORMTYPE_BVEC4:11,UNIFORMTYPE_MAT2:12,UNIFORMTYPE_MAT3:13,UNIFORMTYPE_MAT4:14,UNIFORMTYPE_TEXTURE2D:15,UNIFORMTYPE_TEXTURECUBE:16,UNIFORMTYPE_FLOATARRAY:17,UNIFORMTYPE_TEXTURE2D_SHADOW:18,UNIFORMTYPE_TEXTURECUBE_SHADOW:19,UNIFORMTYPE_TEXTURE3D:20};
|
|
Object.assign(pc,e);pc.gfx={};Object.assign(pc.gfx,e)})();Object.assign(pc,function(){var e=function(b){this.name=b;this.value=null;this.versionObject=new pc.VersionedObject};Object.assign(e.prototype,{setValue:function(b){this.value=b;this.versionObject.increment()},getValue:function(b){return this.value}});return{ScopeId:e}}());Object.assign(pc,function(){var e=function(b){this.name=b;this.variables={};this.namespaces={}};Object.assign(e.prototype,{resolve:function(b){this.variables.hasOwnProperty(b)||(this.variables[b]=new pc.ScopeId(b));return this.variables[b]},getSubSpace:function(b){this.namespaces.hasOwnProperty(b)||(this.namespaces[b]=new pc.ScopeSpace(b));return this.namespaces[b]}});return{ScopeSpace:e}}());Object.assign(pc,function(){var e=function(){this.revision=this.globalId=0};Object.assign(e.prototype,{equals:function(b){return this.globalId===b.globalId&&this.revision===b.revision},notequals:function(b){return this.globalId!==b.globalId||this.revision!==b.revision},copy:function(b){this.globalId=b.globalId;this.revision=b.revision},reset:function(){this.revision=this.globalId=0}});return{Version:e}}());Object.assign(pc,function(){var e=0,b=function(){e++;this.version=new pc.Version;this.version.globalId=e};Object.assign(b.prototype,{increment:function(){this.version.revision++}});return{VersionedObject:b}}());Object.assign(pc,function(){function e(f,l){this.index=0;switch(l.dataType){case pc.TYPE_INT8:this.array=new Int8Array(f,l.offset);break;case pc.TYPE_UINT8:this.array=new Uint8Array(f,l.offset);break;case pc.TYPE_INT16:this.array=new Int16Array(f,l.offset);break;case pc.TYPE_UINT16:this.array=new Uint16Array(f,l.offset);break;case pc.TYPE_INT32:this.array=new Int32Array(f,l.offset);break;case pc.TYPE_UINT32:this.array=new Uint32Array(f,l.offset);break;case pc.TYPE_FLOAT32:this.array=new Float32Array(f,
|
|
l.offset)}switch(l.numComponents){case 1:this.set=b;break;case 2:this.set=a;break;case 3:this.set=c;break;case 4:this.set=d}}function b(a){this.array[this.index]=a}function a(a,b){this.array[this.index]=a;this.array[this.index+1]=b}function c(a,b,c){this.array[this.index]=a;this.array[this.index+1]=b;this.array[this.index+2]=c}function d(a,b,c,d){this.array[this.index]=a;this.array[this.index+1]=b;this.array[this.index+2]=c;this.array[this.index+3]=d}function f(a){this.vertexBuffer=a;this.buffer=
|
|
this.vertexBuffer.lock();this.accessors=[];this.element={};a=this.vertexBuffer.getFormat();for(var b=0;b<a.elements.length;b++){var c=a.elements[b];this.accessors[b]=new e(this.buffer,c);this.element[c.name]=this.accessors[b]}}e.prototype.get=function(a){return this.array[this.index+a]};Object.assign(f.prototype,{next:function(a){void 0===a&&(a=1);for(var b=0,c=this.accessors,d=this.accessors.length,f=this.vertexBuffer.getFormat();b<d;){var g=c[b++];g.index+=a*f.size/g.array.constructor.BYTES_PER_ELEMENT}},
|
|
end:function(){this.vertexBuffer.unlock()}});return{VertexIterator:f}}());Object.assign(pc,function(){var e=[];e[pc.TYPE_INT8]=1;e[pc.TYPE_UINT8]=1;e[pc.TYPE_INT16]=2;e[pc.TYPE_UINT16]=2;e[pc.TYPE_INT32]=4;e[pc.TYPE_UINT32]=4;e[pc.TYPE_FLOAT32]=4;return{VertexFormat:function(b,a){var c,d,f;this.elements=[];this.hasTangents=this.hasColor=this.hasUv1=this.hasUv0=!1;c=this.size=0;for(d=a.length;c<d;c++){var g=a[c];f={name:g.semantic,offset:0,stride:0,stream:-1,scopeId:b.scope.resolve(g.semantic),dataType:g.type,numComponents:g.components,normalize:void 0===g.normalize?!1:
|
|
g.normalize,size:g.components*e[g.type]};this.elements.push(f);this.size+=4*Math.ceil(f.size/4);g.semantic===pc.SEMANTIC_TEXCOORD0?this.hasUv0=!0:g.semantic===pc.SEMANTIC_TEXCOORD1?this.hasUv1=!0:g.semantic===pc.SEMANTIC_COLOR?this.hasColor=!0:g.semantic===pc.SEMANTIC_TANGENT&&(this.hasTangents=!0)}c=g=0;for(d=this.elements.length;c<d;c++)f=this.elements[c],f.offset=g,f.stride=this.size,g+=f.size}}}());Object.assign(pc,function(){var e=function(b,a,c,d,f){this.usage=d||pc.BUFFER_STATIC;this.format=a;this.numVertices=c;this.numBytes=a.size*c;b._vram.vb+=this.numBytes;this.device=b;f?this.setData(f):this.storage=new ArrayBuffer(this.numBytes);this.device.buffers.push(this)};Object.assign(e.prototype,{destroy:function(){var b=this.device,a=b.buffers.indexOf(this);-1!==a&&b.buffers.splice(a,1);if(this.bufferId){a=b.gl;a.deleteBuffer(this.bufferId);b._vram.vb-=this.storage.byteLength;this.bufferId=null;
|
|
b.boundBuffer=null;b.vertexBuffers.length=0;b.vbOffsets.length=0;b.attributesInvalidated=!0;for(var c in b.enabledAttributes)a.disableVertexAttribArray(c);b.enabledAttributes={}}},getFormat:function(){return this.format},getUsage:function(){return this.usage},getNumVertices:function(){return this.numVertices},lock:function(){return this.storage},unlock:function(){var b=this.device.gl;this.bufferId||(this.bufferId=b.createBuffer());var a;switch(this.usage){case pc.BUFFER_STATIC:a=b.STATIC_DRAW;break;
|
|
case pc.BUFFER_DYNAMIC:a=b.DYNAMIC_DRAW;break;case pc.BUFFER_STREAM:a=b.STREAM_DRAW;break;case pc.BUFFER_GPUDYNAMIC:a=this.device.webgl2?b.DYNAMIC_COPY:b.STATIC_DRAW}b.bindBuffer(b.ARRAY_BUFFER,this.bufferId);b.bufferData(b.ARRAY_BUFFER,this.storage,a)},setData:function(b){if(b.byteLength!==this.numBytes)return console.error("VertexBuffer: wrong initial data size: expected "+this.numBytes+", got "+b.byteLength),!1;this.storage=b;this.unlock();return!0}});return{VertexBuffer:e}}());Object.assign(pc,function(){var e=function(b,a,c,d,f){this.usage=d||pc.BUFFER_STATIC;this.format=a;this.numIndices=c;this.device=b;c=this.device.gl;var g;a===pc.INDEXFORMAT_UINT8?(g=1,this.glFormat=c.UNSIGNED_BYTE):a===pc.INDEXFORMAT_UINT16?(g=2,this.glFormat=c.UNSIGNED_SHORT):a===pc.INDEXFORMAT_UINT32&&(g=4,this.glFormat=c.UNSIGNED_INT);this.bytesPerIndex=g;this.numBytes=this.numIndices*g;f?this.setData(f):this.storage=new ArrayBuffer(this.numBytes);b._vram.ib+=this.numBytes;this.device.buffers.push(this)};
|
|
Object.assign(e.prototype,{destroy:function(){var b=this.device,a=b.buffers.indexOf(this);-1!==a&&b.buffers.splice(a,1);this.bufferId&&(this.device.gl.deleteBuffer(this.bufferId),this.device._vram.ib-=this.storage.byteLength,this.bufferId=null,this.device.indexBuffer===this&&(this.device.indexBuffer=null))},getFormat:function(){return this.format},getNumIndices:function(){return this.numIndices},lock:function(){return this.storage},unlock:function(){var b=this.device.gl;this.bufferId||(this.bufferId=
|
|
b.createBuffer());var a;switch(this.usage){case pc.BUFFER_STATIC:a=b.STATIC_DRAW;break;case pc.BUFFER_DYNAMIC:a=b.DYNAMIC_DRAW;break;case pc.BUFFER_STREAM:a=b.STREAM_DRAW;break;case pc.BUFFER_GPUDYNAMIC:a=this.device.webgl2?b.DYNAMIC_COPY:b.STATIC_DRAW}b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,this.bufferId);b.bufferData(b.ELEMENT_ARRAY_BUFFER,this.storage,a)},setData:function(b){if(b.byteLength!==this.numBytes)return console.error("IndexBuffer: wrong initial data size: expected "+this.numBytes+", got "+
|
|
b.byteLength),!1;this.storage=b;this.unlock();return!0}});return{IndexBuffer:e}}());Object.assign(pc,function(){var e=function(b,a){a=a||pc.BUFFER_GPUDYNAMIC;this.device=b.device;var c=this.device.gl;this._inputBuffer=b;a===pc.BUFFER_GPUDYNAMIC&&b.usage!==a&&(c.bindBuffer(c.ARRAY_BUFFER,b.bufferId),c.bufferData(c.ARRAY_BUFFER,b.storage,c.DYNAMIC_COPY));this._outputBuffer=new pc.VertexBuffer(b.device,b.format,b.numVertices,a,b.storage)};e.createShader=function(b,a,c){return pc.shaderChunks.createShaderFromCode(b,a,null,c,!0)};Object.assign(e.prototype,{destroy:function(){this._outputBuffer.destroy()},
|
|
process:function(b,a){void 0===a&&(a=!0);var c=this.device;c.setRenderTarget(null);c.updateBegin();c.setVertexBuffer(this._inputBuffer,0);c.setRaster(!1);c.setTransformFeedbackBuffer(this._outputBuffer);c.setShader(b);c.draw({type:pc.PRIMITIVE_POINTS,base:0,count:this._inputBuffer.numVertices,indexed:!1});c.setTransformFeedbackBuffer(null);c.setRaster(!0);c.updateEnd();a&&(c=this._inputBuffer.bufferId,this._inputBuffer.bufferId=this._outputBuffer.bufferId,this._outputBuffer.bufferId=c)}});Object.defineProperty(e.prototype,
|
|
"inputBuffer",{get:function(){return this._inputBuffer}});Object.defineProperty(e.prototype,"outputBuffer",{get:function(){return this._outputBuffer}});return{TransformFeedback:e}}());Object.assign(pc,function(){var e=function(a,b){this.device=a;this.name=null;this._height=this._width=4;this._depth=1;this._pot=!0;this._format=pc.PIXELFORMAT_R8_G8_B8_A8;this.fixCubemapSeams=this._volume=this._cubemap=this.rgbm=!1;this._flipY=!0;this._premultiplyAlpha=!1;this._mipmaps=!0;this._minFilter=pc.FILTER_LINEAR_MIPMAP_LINEAR;this._magFilter=pc.FILTER_LINEAR;this._anisotropy=1;this._addressW=this._addressV=this._addressU=pc.ADDRESS_REPEAT;this._compareOnRead=!1;this._compareFunc=pc.FUNC_LESS;
|
|
void 0!==b&&(this._width=void 0!==b.width?b.width:this._width,this._height=void 0!==b.height?b.height:this._height,this._pot=pc.math.powerOfTwo(this._width)&&pc.math.powerOfTwo(this._height),this._format=void 0!==b.format?b.format:this._format,this.rgbm=void 0!==b.rgbm?b.rgbm:this.rgbm,this._mipmaps=void 0!==b.mipmaps?b.mipmaps:void 0!==b.autoMipmap?b.autoMipmap:this._mipmaps,this._levels=b.levels,this._cubemap=void 0!==b.cubemap?b.cubemap:this._cubemap,this.fixCubemapSeams=void 0!==b.fixCubemapSeams?
|
|
b.fixCubemapSeams:this.fixCubemapSeams,this._minFilter=void 0!==b.minFilter?b.minFilter:this._minFilter,this._magFilter=void 0!==b.magFilter?b.magFilter:this._magFilter,this._anisotropy=void 0!==b.anisotropy?b.anisotropy:this._anisotropy,this._addressU=void 0!==b.addressU?b.addressU:this._addressU,this._addressV=void 0!==b.addressV?b.addressV:this._addressV,this._compareOnRead=void 0!==b.compareOnRead?b.compareOnRead:this._compareOnRead,this._compareFunc=void 0!==b._compareFunc?b._compareFunc:this._compareFunc,
|
|
this._flipY=void 0!==b.flipY?b.flipY:this._flipY,this._premultiplyAlpha=void 0!==b.premultiplyAlpha?b.premultiplyAlpha:this._premultiplyAlpha,a.webgl2&&(this._depth=void 0!==b.depth?b.depth:this._depth,this._volume=void 0!==b.volume?b.volume:this._volume,this._addressW=void 0!==b.addressW?b.addressW:this._addressW));this._compressed=this._format===pc.PIXELFORMAT_DXT1||this._format===pc.PIXELFORMAT_DXT3||this._format===pc.PIXELFORMAT_DXT5||this._format>=pc.PIXELFORMAT_ETC1;this._invalid=!1;this._lockedLevel=
|
|
-1;this._levels||(this._levels=this._cubemap?[[null,null,null,null,null,null]]:[null]);this.dirtyAll();this._gpuSize=0};Object.defineProperty(e.prototype,"minFilter",{get:function(){return this._minFilter},set:function(a){this._minFilter!==a&&(this._minFilter=a,this._parameterFlags|=1)}});Object.defineProperty(e.prototype,"magFilter",{get:function(){return this._magFilter},set:function(a){this._magFilter!==a&&(this._magFilter=a,this._parameterFlags|=2)}});Object.defineProperty(e.prototype,"addressU",
|
|
{get:function(){return this._addressU},set:function(a){this._addressU!==a&&(this._addressU=a,this._parameterFlags|=4)}});Object.defineProperty(e.prototype,"addressV",{get:function(){return this._addressV},set:function(a){this._addressV!==a&&(this._addressV=a,this._parameterFlags|=8)}});Object.defineProperty(e.prototype,"addressW",{get:function(){return this._addressW},set:function(a){this.device.webgl2&&this._volume&&a!==this._addressW&&(this._addressW=a,this._parameterFlags|=16)}});Object.defineProperty(e.prototype,
|
|
"compareOnRead",{get:function(){return this._compareOnRead},set:function(a){this._compareOnRead!==a&&(this._compareOnRead=a,this._parameterFlags|=32)}});Object.defineProperty(e.prototype,"compareFunc",{get:function(){return this._compareFunc},set:function(a){this._compareFunc!==a&&(this._compareFunc=a,this._parameterFlags|=64)}});Object.defineProperty(e.prototype,"anisotropy",{get:function(){return this._anisotropy},set:function(a){this._anisotropy!==a&&(this._anisotropy=a,this._parameterFlags|=128)}});
|
|
Object.defineProperty(e.prototype,"autoMipmap",{get:function(){return this._mipmaps},set:function(a){this._mipmaps=a}});Object.defineProperty(e.prototype,"mipmaps",{get:function(){return this._mipmaps},set:function(a){this._mipmaps!==a&&(this._mipmaps=a,this._minFilterDirty=!0,a&&(this._needsMipmapsUpload=!0))}});Object.defineProperty(e.prototype,"width",{get:function(){return this._width}});Object.defineProperty(e.prototype,"height",{get:function(){return this._height}});Object.defineProperty(e.prototype,
|
|
"depth",{get:function(){return this._depth}});Object.defineProperty(e.prototype,"format",{get:function(){return this._format}});Object.defineProperty(e.prototype,"cubemap",{get:function(){return this._cubemap}});var b=null;Object.defineProperty(e.prototype,"gpuSize",{get:function(){b||(b=[],b[pc.PIXELFORMAT_A8]=1,b[pc.PIXELFORMAT_L8]=1,b[pc.PIXELFORMAT_L8_A8]=1,b[pc.PIXELFORMAT_R5_G6_B5]=2,b[pc.PIXELFORMAT_R5_G5_B5_A1]=2,b[pc.PIXELFORMAT_R4_G4_B4_A4]=2,b[pc.PIXELFORMAT_R8_G8_B8]=4,b[pc.PIXELFORMAT_R8_G8_B8_A8]=
|
|
4,b[pc.PIXELFORMAT_RGB16F]=8,b[pc.PIXELFORMAT_RGBA16F]=8,b[pc.PIXELFORMAT_RGB32F]=16,b[pc.PIXELFORMAT_RGBA32F]=16,b[pc.PIXELFORMAT_R32F]=4,b[pc.PIXELFORMAT_DEPTH]=4,b[pc.PIXELFORMAT_DEPTHSTENCIL]=4,b[pc.PIXELFORMAT_111110F]=4,b[pc.PIXELFORMAT_SRGB]=4,b[pc.PIXELFORMAT_SRGBA]=4);var a=1;!this._pot||!this._mipmaps&&this._minFilter!==pc.FILTER_NEAREST_MIPMAP_NEAREST&&this._minFilter!==pc.FILTER_NEAREST_MIPMAP_LINEAR&&this._minFilter!==pc.FILTER_LINEAR_MIPMAP_NEAREST&&this._minFilter!==pc.FILTER_LINEAR_MIPMAP_LINEAR||
|
|
this._compressed&&1===this._levels.length||(a=Math.round(Math.log2(Math.max(this._width,this._height))+1));for(var c=this._width,d=this._height,f=this._depth,g=0,l=0;l<a;l++)g=this._compressed?this._format===pc.PIXELFORMAT_ETC1?g+Math.floor((c+3)/4)*Math.floor((d+3)/4)*8*f:this._format===pc.PIXELFORMAT_PVRTC_2BPP_RGB_1||this._format===pc.PIXELFORMAT_PVRTC_2BPP_RGBA_1?g+Math.max(c,16)*Math.max(d,8)/4*f:this._format===pc.PIXELFORMAT_PVRTC_4BPP_RGB_1||this._format===pc.PIXELFORMAT_PVRTC_4BPP_RGBA_1?
|
|
g+Math.max(c,8)*Math.max(d,8)/2*f:g+Math.floor((c+4-1)/4)*Math.floor((d+4-1)/4)*(this._format===pc.PIXELFORMAT_DXT1?8:16)*f:g+c*d*f*b[this._format],c=Math.max(.5*c,1),d=Math.max(.5*d,1),f=Math.max(.5*f,1);this._cubemap&&(g*=6);return g}});Object.defineProperty(e.prototype,"volume",{get:function(){return this._volume}});Object.defineProperty(e.prototype,"flipY",{get:function(){return this._flipY},set:function(a){this._flipY!==a&&(this._flipY=a,this._needsUpload=!0)}});Object.defineProperty(e.prototype,
|
|
"premultiplyAlpha",{get:function(){return this._premultiplyAlpha},set:function(a){this._premultiplyAlpha!==a&&(this._premultiplyAlpha=a,this._needsUpload=!0)}});Object.assign(e.prototype,{destroy:function(){this.device&&this.device.destroyTexture(this);this._levels=this.device=null},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},lock:function(a){a=a||{level:0,
|
|
face:0,mode:pc.TEXTURELOCK_WRITE};void 0===a.level&&(a.level=0);void 0===a.face&&(a.face=0);void 0===a.mode&&(a.mode=pc.TEXTURELOCK_WRITE);this._lockedLevel=a.level;if(null===this._levels[a.level])switch(this._format){case pc.PIXELFORMAT_A8:case pc.PIXELFORMAT_L8:this._levels[a.level]=new Uint8Array(this._width*this._height*this._depth);break;case pc.PIXELFORMAT_L8_A8:this._levels[a.level]=new Uint8Array(this._width*this._height*this._depth*2);break;case pc.PIXELFORMAT_R5_G6_B5:case pc.PIXELFORMAT_R5_G5_B5_A1:case pc.PIXELFORMAT_R4_G4_B4_A4:this._levels[a.level]=
|
|
new Uint16Array(this._width*this._height*this._depth);break;case pc.PIXELFORMAT_R8_G8_B8:this._levels[a.level]=new Uint8Array(this._width*this._height*this._depth*3);break;case pc.PIXELFORMAT_R8_G8_B8_A8:this._levels[a.level]=new Uint8Array(this._width*this._height*this._depth*4);break;case pc.PIXELFORMAT_DXT1:this._levels[a.level]=new Uint8Array(Math.floor((this._width+3)/4)*Math.floor((this._height+3)/4)*8*this._depth);break;case pc.PIXELFORMAT_DXT3:case pc.PIXELFORMAT_DXT5:this._levels[a.level]=
|
|
new Uint8Array(Math.floor((this._width+3)/4)*Math.floor((this._height+3)/4)*16*this._depth);break;case pc.PIXELFORMAT_RGB16F:this._levels[a.level]=new Uint16Array(this._width*this._height*this._depth*3);break;case pc.PIXELFORMAT_RGB32F:this._levels[a.level]=new Float32Array(this._width*this._height*this._depth*3);break;case pc.PIXELFORMAT_RGBA16F:this._levels[a.level]=new Uint16Array(this._width*this._height*this._depth*4);break;case pc.PIXELFORMAT_RGBA32F:this._levels[a.level]=new Float32Array(this._width*
|
|
this._height*this._depth*4)}return this._levels[a.level]},setSource:function(a){var b,d=!1,f,g;if(this._cubemap){if(a[0])for(f=a[0].width||0,g=a[0].height||0,b=0;6>b;b++){if(!a[b]||a[b].width!==f||a[b].height!==g||!(a[b]instanceof HTMLImageElement||a[b]instanceof HTMLCanvasElement||a[b]instanceof HTMLVideoElement)){d=!0;break}}else d=!0;if(!d)for(b=0;6>b;b++)this._levels[0][b]!==a[b]&&(this._levelsUpdated[0][b]=!0)}else a instanceof HTMLImageElement||a instanceof HTMLCanvasElement||a instanceof HTMLVideoElement||
|
|
(d=!0),d||(a!==this._levels[0]&&(this._levelsUpdated[0]=!0),f=a.width,g=a.height);if(d)if(this._height=this._width=4,this._pot=!0,this._cubemap)for(b=0;6>b;b++)this._levels[0][b]=null,this._levelsUpdated[0][b]=!0;else this._levels[0]=null,this._levelsUpdated[0]=!0;else this._width=f,this._height=g,this._pot=pc.math.powerOfTwo(this._width)&&pc.math.powerOfTwo(this._height),this._levels[0]=a;this._invalid===d&&d||(this._invalid=d,this.upload())},getSource:function(){return this._levels[0]},unlock:function(){this.upload();
|
|
this._lockedLevel=-1},upload:function(){this._needsUpload=!0;this._needsMipmapsUpload=this._mipmaps},getDds:function(){this.format!==pc.PIXELFORMAT_R8_G8_B8_A8&&console.error("This format is not implemented yet");for(var a=128,b=0,d,f;this._levels[b];){if(this.cubemap)for(f=0;6>f;f++){if(!this._levels[b][f]){console.error("No level data for mip "+b+", face "+f);return}d=this._levels[b][f].length;if(!d){console.error("No byte array for mip "+b+", face "+f);return}a+=d}else{d=this._levels[b].length;
|
|
if(!d){console.error("No byte array for mip "+b);return}a+=d}a+=this._levels[b].length;b++}a=new ArrayBuffer(a);f=new Uint32Array(a,0,32);b=528391;1<this._levels.length&&(b|=131072);d=4096;1<this._levels.length&&(d|=4194304);if(1<this._levels.length||this.cubemap)d|=8;var g=this.cubemap?65024:0;f[0]=542327876;f[1]=124;f[2]=b;f[3]=this.height;f[4]=this.width;f[5]=this.width*this.height*4;f[6]=0;f[7]=this._levels.length;for(b=0;11>b;b++)f[8+b]=0;f[19]=32;f[20]=65;f[21]=0;f[22]=32;f[23]=16711680;f[24]=
|
|
65280;f[25]=255;f[26]=4278190080;f[27]=d;f[28]=g;f[29]=0;f[30]=0;f[31]=0;var g=128,l,h;if(this.cubemap)for(f=0;6>f;f++)for(b=0;b<this._levels.length;b++){l=this._levels[b][f];h=new Uint8Array(a,g,l.length);for(d=0;d<l.length;d++)h[d]=l[d];g+=l.length}else for(b=0;b<this._levels.length;b++){l=this._levels[b];h=new Uint8Array(a,g,l.length);for(d=0;d<l.length;d++)h[d]=l[d];g+=l.length}return a}});return{Texture:e}}());Object.assign(pc,function(){var e={depth:!0,face:0},b=function(a,b,d){a instanceof pc.GraphicsDevice?(this._colorBuffer=b,a=d):this._colorBuffer=a.colorBuffer;this._glDepthBuffer=this._glFrameBuffer=null;a=void 0!==a?a:e;this._depthBuffer=a.depthBuffer;this._face=void 0!==a.face?a.face:0;this._depthBuffer?(b=this._depthBuffer._format,b===pc.PIXELFORMAT_DEPTH?(this._depth=!0,this._stencil=!1):this._stencil=b===pc.PIXELFORMAT_DEPTHSTENCIL?this._depth=!0:this._depth=!1):(this._depth=void 0!==a.depth?
|
|
a.depth:!0,this._stencil=void 0!==a.stencil?a.stencil:!1);this._samples=void 0!==a.samples?a.samples:1;this.autoResolve=void 0!==a.autoResolve?a.autoResolve:!0;this._glMsaaDepthBuffer=this._glMsaaColorBuffer=this._glResolveFrameBuffer=null};Object.assign(b.prototype,{destroy:function(){if(this._device){var a=this._device,b=a.targets.indexOf(this);-1!==b&&a.targets.splice(b,1);a=a.gl;this._glFrameBuffer&&(a.deleteFramebuffer(this._glFrameBuffer),this._glFrameBuffer=null);this._glDepthBuffer&&(a.deleteRenderbuffer(this._glDepthBuffer),
|
|
this._glDepthBuffer=null);this._glResolveFrameBuffer&&(a.deleteFramebuffer(this._glResolveFrameBuffer),this._glResolveFrameBuffer=null);this._glMsaaColorBuffer&&(a.deleteRenderbuffer(this._glMsaaColorBuffer),this._glMsaaColorBuffer=null);this._glMsaaDepthBuffer&&(a.deleteRenderbuffer(this._glMsaaDepthBuffer),this._glMsaaDepthBuffer=null)}},resolve:function(a,b){if(this._device&&this._device.webgl2){var c=this._device.gl;void 0===a&&(a=!0);void 0===b&&this._depthBuffer&&(b=!0);c.bindFramebuffer(c.READ_FRAMEBUFFER,
|
|
this._glFrameBuffer);c.bindFramebuffer(c.DRAW_FRAMEBUFFER,this._glResolveFrameBuffer);c.blitFramebuffer(0,0,this.width,this.height,0,0,this.width,this.height,(a?c.COLOR_BUFFER_BIT:0)|(b?c.DEPTH_BUFFER_BIT:0),c.NEAREST);c.bindFramebuffer(c.FRAMEBUFFER,this._glFrameBuffer)}},copy:function(a,b,d){if(!this._device)if(a._device)this._device=a._device;else return!1;return this._device.copyRenderTarget(a,this,b,d)}});Object.defineProperty(b.prototype,"colorBuffer",{get:function(){return this._colorBuffer}});
|
|
Object.defineProperty(b.prototype,"depthBuffer",{get:function(){return this._depthBuffer}});Object.defineProperty(b.prototype,"face",{get:function(){return this._face}});Object.defineProperty(b.prototype,"width",{get:function(){return this._colorBuffer?this._colorBuffer.width:this._depthBuffer.width}});Object.defineProperty(b.prototype,"height",{get:function(){return this._colorBuffer?this._colorBuffer.height:this._depthBuffer.height}});return{RenderTarget:b}}());Object.assign(pc,function(){return{ShaderInput:function(e,b,a,c){this.locationId=c;this.scopeId=e.scope.resolve(b);this.version=new pc.Version;a===pc.UNIFORMTYPE_FLOAT&&"[0]"===b.substr(b.length-3)&&(a=pc.UNIFORMTYPE_FLOATARRAY);this.dataType=a;this.value=[null,null,null,null];this.array=[]}}}());Object.assign(pc,function(){var e=function(b,a){this.device=b;this.definition=a;this.attributes=[];this.uniforms=[];this.samplers=[];this.ready=!1;this.device.createShader(this)};Object.assign(e.prototype,{destroy:function(){this.device.destroyShader(this)}});return{Shader:e}}());Object.assign(pc,function(){var e=function(b){this._device=b;this._cache={};this._generators={};this._precached=this._isClearingCache=!1;this._programsCollection=[];this._defaultStdMatOption={};this._defaultStdMatOptionMin={};var a=new pc.StandardMaterial;a.shaderOptBuilder.updateRef(this._defaultStdMatOption,b,{},a,null,[],pc.SHADER_FORWARD,null,null);a.shaderOptBuilder.updateMinRef(this._defaultStdMatOptionMin,b,{},a,null,[],pc.SHADER_SHADOW,null,null)};e.prototype.register=function(b,a){this.isRegistered(b)||
|
|
(this._generators[b]=a)};e.prototype.unregister=function(b){this.isRegistered(b)&&delete this._generators[b]};e.prototype.isRegistered=function(b){return void 0!==this._generators[b]};e.prototype.getProgram=function(b,a){var c=this._generators[b];if(void 0===c)return null;var d=this._device,f=c.generateKey(a),g=this._cache[f];if(!g){var l;a.lights&&(l=a.lights,a.lights=l.map(function(a){var b=a.clone?a.clone():a;b.key=a.key;return b}));this.storeNewProgram(b,a);a.lights&&(a.lights=l);this._precached&&
|
|
console.warn("ProgramLibrary#getProgram: Cache miss for shader",b,"key",f,"after shaders precaching");c=c.createShaderDefinition(d,a);g=this._cache[f]=new pc.Shader(d,c)}return g};e.prototype.storeNewProgram=function(b,a){var c={};if("standard"===b){var d=this._getDefaultStdMatOptions(a.pass),f;for(f in a)if(a.hasOwnProperty(f)&&d[f]!==a[f]||"pass"===f)c[f]=a[f]}else c=a;this._programsCollection.push(JSON.stringify({name:b,options:c}))};e.prototype.dumpPrograms=function(){var b;b="var device = pc.app ? pc.app.graphicsDevice : pc.Application.getApplication().graphicsDevice;\nvar shaders = [";
|
|
this._programsCollection[0]&&(b+="\n\t"+this._programsCollection[0]);for(var a=1;a<this._programsCollection.length;++a)b+=",\n\t"+this._programsCollection[a];b=b+"\n];\ndevice.programLib.precompile(shaders);\n"+('if (pc.version != "'+pc.version+'" || pc.revision != "'+pc.revision+'")\n');b+='\tconsole.warn("precompile-shaders.js: engine version mismatch, rebuild shaders lib with current engine");';a=document.createElement("a");a.setAttribute("href","data:text/plain;charset=utf-8,"+encodeURIComponent(b));
|
|
a.setAttribute("download","precompile-shaders.js");a.style.display="none";document.body.appendChild(a);a.click();document.body.removeChild(a)};e.prototype.clearCache=function(){var b=this._cache;this._isClearingCache=!0;for(var a in b)b.hasOwnProperty(a)&&b[a].destroy();this._cache={};this._isClearingCache=!1};e.prototype.removeFromCache=function(b){if(!this._isClearingCache){var a=this._cache,c;for(c in a)if(a.hasOwnProperty(c)&&a[c]===b){delete a[c];break}}};e.prototype._getDefaultStdMatOptions=
|
|
function(b){return b>pc.SHADER_FORWARDHDR&&b<=pc.SHADER_PICK?this._defaultStdMatOptionMin:this._defaultStdMatOption};e.prototype.precompile=function(b){if(b)for(var a=Array(b.length),c=0;c<b.length;c++){if("standard"===b[c].name){var d=b[c].options,f=this._getDefaultStdMatOptions(d.pass),g;for(g in f)f.hasOwnProperty(g)&&void 0===d[g]&&(d[g]=f[g]);d.useTexCubeLod=this._device.useTexCubeLod}a[c]=this.getProgram(b[c].name,b[c].options)}this._precached=!0};return{ProgramLibrary:e}}());Object.assign(pc,function(){function e(a,b){var c=!0,d=a.createTexture();a.bindTexture(a.TEXTURE_2D,d);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.NEAREST);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.NEAREST);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE);a.texImage2D(a.TEXTURE_2D,0,a.RGBA,2,2,0,a.RGBA,b,null);var l=a.createFramebuffer();a.bindFramebuffer(a.FRAMEBUFFER,l);a.framebufferTexture2D(a.FRAMEBUFFER,
|
|
a.COLOR_ATTACHMENT0,a.TEXTURE_2D,d,0);a.checkFramebufferStatus(a.FRAMEBUFFER)!==a.FRAMEBUFFER_COMPLETE&&(c=!1);a.bindTexture(a.TEXTURE_2D,null);a.deleteTexture(d);a.bindFramebuffer(a.FRAMEBUFFER,null);a.deleteFramebuffer(l);return c}var b=function(a,b){var c=a.width,d=a.height;if(c>b||d>b){var l=b/Math.max(c,d),h=Math.floor(c*l),l=Math.floor(d*l);console.warn("Image dimensions larger than max supported texture size of "+b+". Resizing from "+c+", "+d+" to "+h+", "+l+".");var e=document.createElement("canvas");
|
|
e.width=h;e.height=l;e.getContext("2d").drawImage(a,0,0,c,d,0,0,h,l);return e}return a},a=function(a,b){var c;this.canvas=a;this.indexBuffer=this.shader=null;this.vertexBuffers=[];this.vbOffsets=[];this._enableAutoInstancing=!1;this.autoInstancingMaxObjects=16384;this.attributesInvalidated=!0;this.boundElementBuffer=this.boundBuffer=null;this.instancedAttribs={};this.enabledAttributes={};this.activeFramebuffer=this.transformFeedbackBuffer=null;this.textureUnit=0;this.textureUnits=[];this._maxPixelRatio=
|
|
1;this.feedback=this.renderTarget=null;this._height=this._width=0;this.updateClientRect();this.vertexShaderCache={};this.fragmentShaderCache={};this.shaders=[];this.buffers=[];this.textures=[];this.targets=[];this.contextLost=!1;this._contextLostHandler=function(a){a.preventDefault();this.contextLost=!0;this.fire("devicelost")}.bind(this);this._contextRestoredHandler=function(){this.initializeContext();this.contextLost=!1;this.fire("devicerestored")}.bind(this);a.addEventListener("webglcontextlost",
|
|
this._contextLostHandler,!1);a.addEventListener("webglcontextrestored",this._contextRestoredHandler,!1);var d=b&&void 0!==b.preferWebGl2?b.preferWebGl2:!0,l=d?["webgl2","experimental-webgl2","webgl","experimental-webgl"]:["webgl","experimental-webgl"],h=null;b=b||{};b.stencil=!0;for(c=0;c<l.length;c++){try{h=a.getContext(l[c],b)}catch(t){}if(h){this.webgl2=d&&2>c;break}}if(!h)throw Error("WebGL not supported");this.gl=h;this.initializeExtensions();this.initializeCapabilities();this.initializeRenderState();
|
|
for(c=0;c<this.maxCombinedTextures;c++)this.textureUnits.push([null,null,null]);this.defaultClearOptions={color:[0,0,0,1],depth:1,stencil:0,flags:pc.CLEARFLAG_COLOR|pc.CLEARFLAG_DEPTH};this.glAddress=[h.REPEAT,h.CLAMP_TO_EDGE,h.MIRRORED_REPEAT];this.glBlendEquation=[h.FUNC_ADD,h.FUNC_SUBTRACT,h.FUNC_REVERSE_SUBTRACT,this.webgl2?h.MIN:this.extBlendMinmax?this.extBlendMinmax.MIN_EXT:h.FUNC_ADD,this.webgl2?h.MAX:this.extBlendMinmax?this.extBlendMinmax.MAX_EXT:h.FUNC_ADD];this.glBlendFunction=[h.ZERO,
|
|
h.ONE,h.SRC_COLOR,h.ONE_MINUS_SRC_COLOR,h.DST_COLOR,h.ONE_MINUS_DST_COLOR,h.SRC_ALPHA,h.SRC_ALPHA_SATURATE,h.ONE_MINUS_SRC_ALPHA,h.DST_ALPHA,h.ONE_MINUS_DST_ALPHA];this.glComparison=[h.NEVER,h.LESS,h.EQUAL,h.LEQUAL,h.GREATER,h.NOTEQUAL,h.GEQUAL,h.ALWAYS];this.glStencilOp=[h.KEEP,h.ZERO,h.REPLACE,h.INCR,h.INCR_WRAP,h.DECR,h.DECR_WRAP,h.INVERT];this.glClearFlag=[0,h.COLOR_BUFFER_BIT,h.DEPTH_BUFFER_BIT,h.COLOR_BUFFER_BIT|h.DEPTH_BUFFER_BIT,h.STENCIL_BUFFER_BIT,h.STENCIL_BUFFER_BIT|h.COLOR_BUFFER_BIT,
|
|
h.STENCIL_BUFFER_BIT|h.DEPTH_BUFFER_BIT,h.STENCIL_BUFFER_BIT|h.COLOR_BUFFER_BIT|h.DEPTH_BUFFER_BIT];this.glCull=[0,h.BACK,h.FRONT,h.FRONT_AND_BACK];this.glFilter=[h.NEAREST,h.LINEAR,h.NEAREST_MIPMAP_NEAREST,h.NEAREST_MIPMAP_LINEAR,h.LINEAR_MIPMAP_NEAREST,h.LINEAR_MIPMAP_LINEAR];this.glPrimitive=[h.POINTS,h.LINES,h.LINE_LOOP,h.LINE_STRIP,h.TRIANGLES,h.TRIANGLE_STRIP,h.TRIANGLE_FAN];this.glType=[h.BYTE,h.UNSIGNED_BYTE,h.SHORT,h.UNSIGNED_SHORT,h.INT,h.UNSIGNED_INT,h.FLOAT];this.pcUniformType={};this.pcUniformType[h.BOOL]=
|
|
pc.UNIFORMTYPE_BOOL;this.pcUniformType[h.INT]=pc.UNIFORMTYPE_INT;this.pcUniformType[h.FLOAT]=pc.UNIFORMTYPE_FLOAT;this.pcUniformType[h.FLOAT_VEC2]=pc.UNIFORMTYPE_VEC2;this.pcUniformType[h.FLOAT_VEC3]=pc.UNIFORMTYPE_VEC3;this.pcUniformType[h.FLOAT_VEC4]=pc.UNIFORMTYPE_VEC4;this.pcUniformType[h.INT_VEC2]=pc.UNIFORMTYPE_IVEC2;this.pcUniformType[h.INT_VEC3]=pc.UNIFORMTYPE_IVEC3;this.pcUniformType[h.INT_VEC4]=pc.UNIFORMTYPE_IVEC4;this.pcUniformType[h.BOOL_VEC2]=pc.UNIFORMTYPE_BVEC2;this.pcUniformType[h.BOOL_VEC3]=
|
|
pc.UNIFORMTYPE_BVEC3;this.pcUniformType[h.BOOL_VEC4]=pc.UNIFORMTYPE_BVEC4;this.pcUniformType[h.FLOAT_MAT2]=pc.UNIFORMTYPE_MAT2;this.pcUniformType[h.FLOAT_MAT3]=pc.UNIFORMTYPE_MAT3;this.pcUniformType[h.FLOAT_MAT4]=pc.UNIFORMTYPE_MAT4;this.pcUniformType[h.SAMPLER_2D]=pc.UNIFORMTYPE_TEXTURE2D;this.pcUniformType[h.SAMPLER_CUBE]=pc.UNIFORMTYPE_TEXTURECUBE;this.webgl2&&(this.pcUniformType[h.SAMPLER_2D_SHADOW]=pc.UNIFORMTYPE_TEXTURE2D_SHADOW,this.pcUniformType[h.SAMPLER_CUBE_SHADOW]=pc.UNIFORMTYPE_TEXTURECUBE_SHADOW,
|
|
this.pcUniformType[h.SAMPLER_3D]=pc.UNIFORMTYPE_TEXTURE3D);this.targetToSlot={};this.targetToSlot[h.TEXTURE_2D]=0;this.targetToSlot[h.TEXTURE_CUBE_MAP]=1;this.targetToSlot[h.TEXTURE_3D]=2;var p,k,n,q,m;this.commitFunction=[];this.commitFunction[pc.UNIFORMTYPE_BOOL]=function(a,b){a.value!==b&&(h.uniform1i(a.locationId,b),a.value=b)};this.commitFunction[pc.UNIFORMTYPE_INT]=this.commitFunction[pc.UNIFORMTYPE_BOOL];this.commitFunction[pc.UNIFORMTYPE_FLOAT]=function(a,b){a.value!==b&&(h.uniform1f(a.locationId,
|
|
b),a.value=b)};this.commitFunction[pc.UNIFORMTYPE_VEC2]=function(a,b){m=a.value;p=b[0];k=b[1];if(m[0]!==p||m[1]!==k)h.uniform2fv(a.locationId,b),m[0]=p,m[1]=k};this.commitFunction[pc.UNIFORMTYPE_VEC3]=function(a,b){m=a.value;p=b[0];k=b[1];n=b[2];if(m[0]!==p||m[1]!==k||m[2]!==n)h.uniform3fv(a.locationId,b),m[0]=p,m[1]=k,m[2]=n};this.commitFunction[pc.UNIFORMTYPE_VEC4]=function(a,b){m=a.value;p=b[0];k=b[1];n=b[2];q=b[3];if(m[0]!==p||m[1]!==k||m[2]!==n||m[3]!==q)h.uniform4fv(a.locationId,b),m[0]=p,m[1]=
|
|
k,m[2]=n,m[3]=q};this.commitFunction[pc.UNIFORMTYPE_IVEC2]=function(a,b){m=a.value;p=b[0];k=b[1];if(m[0]!==p||m[1]!==k)h.uniform2iv(a.locationId,b),m[0]=p,m[1]=k};this.commitFunction[pc.UNIFORMTYPE_BVEC2]=this.commitFunction[pc.UNIFORMTYPE_IVEC2];this.commitFunction[pc.UNIFORMTYPE_IVEC3]=function(a,b){m=a.value;p=b[0];k=b[1];n=b[2];if(m[0]!==p||m[1]!==k||m[2]!==n)h.uniform3iv(a.locationId,b),m[0]=p,m[1]=k,m[2]=n};this.commitFunction[pc.UNIFORMTYPE_BVEC3]=this.commitFunction[pc.UNIFORMTYPE_IVEC3];
|
|
this.commitFunction[pc.UNIFORMTYPE_IVEC4]=function(a,b){m=a.value;p=b[0];k=b[1];n=b[2];q=b[3];if(m[0]!==p||m[1]!==k||m[2]!==n||m[3]!==q)h.uniform4iv(a.locationId,b),m[0]=p,m[1]=k,m[2]=n,m[3]=q};this.commitFunction[pc.UNIFORMTYPE_BVEC4]=this.commitFunction[pc.UNIFORMTYPE_IVEC4];this.commitFunction[pc.UNIFORMTYPE_MAT2]=function(a,b){h.uniformMatrix2fv(a.locationId,!1,b)};this.commitFunction[pc.UNIFORMTYPE_MAT3]=function(a,b){h.uniformMatrix3fv(a.locationId,!1,b)};this.commitFunction[pc.UNIFORMTYPE_MAT4]=
|
|
function(a,b){h.uniformMatrix4fv(a.locationId,!1,b)};this.commitFunction[pc.UNIFORMTYPE_FLOATARRAY]=function(a,b){h.uniform1fv(a.locationId,b)};this.scope=new pc.ScopeSpace("Device");this.programLib=new pc.ProgramLibrary(this);for(var r in pc.programlib)this.programLib.register(r,pc.programlib[r]);pc.events.attach(this);this.supportsBoneTextures=this.extTextureFloat&&0<this.maxVertexTextures;this.useTexCubeLod=this.extTextureLod&&16>this.maxTextures;this.boneLimit=Math.floor((this.vertexUniformsCount-
|
|
16-8-1-16)/4);this.boneLimit=Math.min(this.boneLimit,128);"Mali-450 MP"===this.unmaskedRenderer&&(this.boneLimit=34);"Apple A8 GPU"===this.unmaskedRenderer&&(this.forceCpuParticles=!0);this._shaderSwitchesPerFrame=this._drawCallsPerFrame=0;this._primsPerFrame=[];for(c=pc.PRIMITIVE_POINTS;c<=pc.PRIMITIVE_TRIFAN;c++)this._primsPerFrame[c]=0;this._renderTargetCreationTime=0;this._vram={tex:0,vb:0,ib:0};this._shaderStats={vsCompiled:0,fsCompiled:0,linked:0,materialShaders:0,compileTime:0};this.constantTexSource=
|
|
this.scope.resolve("source");this.textureFloatRenderable=this.extTextureFloat?this.webgl2?!!this.extColorBufferFloat:e(h,h.FLOAT):!1;this.textureHalfFloatRenderable=this.extTextureHalfFloat?this.webgl2?!!this.extColorBufferFloat:e(h,this.extTextureHalfFloat.HALF_FLOAT_OES):!1;this._textureFloatHighPrecision=void 0;this.initializeGrabPassTexture()};Object.assign(a.prototype,{getPrecision:function(){var a=this.gl,b="highp";if(a.getShaderPrecisionFormat){var f=a.getShaderPrecisionFormat(a.VERTEX_SHADER,
|
|
a.HIGH_FLOAT),g=a.getShaderPrecisionFormat(a.VERTEX_SHADER,a.MEDIUM_FLOAT),l=a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,a.HIGH_FLOAT),a=a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,a.MEDIUM_FLOAT),g=0<g.precision&&0<a.precision;0<f.precision&&0<l.precision||(b=g?"mediump":"lowp")}return b},initializeExtensions:function(){var a=this.gl,b,f=a.getSupportedExtensions(),g=function(){for(var b=null,c=0;c<arguments.length;c++)-1!==f.indexOf(arguments[c])&&(b=a.getExtension(arguments[c]));return b};if(this.webgl2)this.extVertexArrayObject=
|
|
this.extUintElement=this.extTextureLod=this.extTextureHalfFloatLinear=this.extTextureHalfFloat=this.extTextureFloat=this.extStandardDerivatives=this.extInstancing=this.extDrawBuffers=this.extBlendMinmax=!0,this.extColorBufferFloat=g("EXT_color_buffer_float");else{this.extBlendMinmax=g("EXT_blend_minmax");this.extDrawBuffers=g("EXT_draw_buffers");if(this.extInstancing=g("ANGLE_instanced_arrays"))b=this.extInstancing,a.drawArraysInstanced=b.drawArraysInstancedANGLE.bind(b),a.drawElementsInstanced=b.drawElementsInstancedANGLE.bind(b),
|
|
a.vertexAttribDivisor=b.vertexAttribDivisorANGLE.bind(b);this.extStandardDerivatives=g("OES_standard_derivatives");this.extTextureFloat=g("OES_texture_float");this.extTextureHalfFloat=g("OES_texture_half_float");this.extTextureHalfFloatLinear=g("OES_texture_half_float_linear");this.extTextureLod=g("EXT_shader_texture_lod");this.extUintElement=g("OES_element_index_uint");if(this.extVertexArrayObject=g("OES_vertex_array_object"))b=this.extVertexArrayObject,a.createVertexArray=b.createVertexArrayOES.bind(b),
|
|
a.deleteVertexArray=b.deleteVertexArrayOES.bind(b),a.isVertexArray=b.isVertexArrayOES.bind(b),a.bindVertexArray=b.bindVertexArrayOES.bind(b);this.extColorBufferFloat=null}this.extDebugRendererInfo=g("WEBGL_debug_renderer_info");this.extTextureFloatLinear=g("OES_texture_float_linear");this.extTextureFilterAnisotropic=g("EXT_texture_filter_anisotropic","WEBKIT_EXT_texture_filter_anisotropic");this.extCompressedTextureETC1=g("WEBGL_compressed_texture_etc1");this.extCompressedTextureETC=g("WEBGL_compressed_texture_etc");
|
|
this.extCompressedTexturePVRTC=g("WEBGL_compressed_texture_pvrtc","WEBKIT_WEBGL_compressed_texture_pvrtc");this.extCompressedTextureS3TC=g("WEBGL_compressed_texture_s3tc","WEBKIT_WEBGL_compressed_texture_s3tc");this.extParallelShaderCompile=g("KHR_parallel_shader_compile")},initializeCapabilities:function(){var a=this.gl,b;this.maxPrecision=this.precision=this.getPrecision();b=a.getContextAttributes();this.supportsMsaa=b.antialias;this.supportsStencil=b.stencil;this.maxTextureSize=a.getParameter(a.MAX_TEXTURE_SIZE);
|
|
this.maxCubeMapSize=a.getParameter(a.MAX_CUBE_MAP_TEXTURE_SIZE);this.maxRenderBufferSize=a.getParameter(a.MAX_RENDERBUFFER_SIZE);this.maxTextures=a.getParameter(a.MAX_TEXTURE_IMAGE_UNITS);this.maxCombinedTextures=a.getParameter(a.MAX_COMBINED_TEXTURE_IMAGE_UNITS);this.maxVertexTextures=a.getParameter(a.MAX_VERTEX_TEXTURE_IMAGE_UNITS);this.vertexUniformsCount=a.getParameter(a.MAX_VERTEX_UNIFORM_VECTORS);this.fragmentUniformsCount=a.getParameter(a.MAX_FRAGMENT_UNIFORM_VECTORS);this.webgl2?(this.maxDrawBuffers=
|
|
a.getParameter(a.MAX_DRAW_BUFFERS),this.maxColorAttachments=a.getParameter(a.MAX_COLOR_ATTACHMENTS),this.maxVolumeSize=a.getParameter(a.MAX_3D_TEXTURE_SIZE)):(this.maxDrawBuffers=(b=this.extDrawBuffers)?a.getParameter(b.MAX_DRAW_BUFFERS_EXT):1,this.maxColorAttachments=b?a.getParameter(b.MAX_COLOR_ATTACHMENTS_EXT):1,this.maxVolumeSize=1);this.unmaskedRenderer=(b=this.extDebugRendererInfo)?a.getParameter(b.UNMASKED_RENDERER_WEBGL):"";this.unmaskedVendor=b?a.getParameter(b.UNMASKED_VENDOR_WEBGL):"";
|
|
this.maxAnisotropy=(b=this.extTextureFilterAnisotropic)?a.getParameter(b.MAX_TEXTURE_MAX_ANISOTROPY_EXT):1},initializeRenderState:function(){var a=this.gl;this.blending=!1;a.disable(a.BLEND);this.blendSrc=pc.BLENDMODE_ONE;this.blendDst=pc.BLENDMODE_ZERO;this.blendSrcAlpha=pc.BLENDMODE_ONE;this.blendDstAlpha=pc.BLENDMODE_ZERO;this.separateAlphaBlend=!1;this.blendAlphaEquation=this.blendEquation=pc.BLENDEQUATION_ADD;this.separateAlphaEquation=!1;a.blendFunc(a.ONE,a.ZERO);a.blendEquation(a.FUNC_ADD);
|
|
this.writeAlpha=this.writeBlue=this.writeGreen=this.writeRed=!0;a.colorMask(!0,!0,!0,!0);this.cullMode=pc.CULLFACE_BACK;a.enable(a.CULL_FACE);a.cullFace(a.BACK);this.depthTest=!0;a.enable(a.DEPTH_TEST);this.depthFunc=pc.FUNC_LESSEQUAL;a.depthFunc(a.LEQUAL);this.depthWrite=!0;a.depthMask(!0);this.stencil=!1;a.disable(a.STENCIL_TEST);this.stencilFuncFront=this.stencilFuncBack=pc.FUNC_ALWAYS;this.stencilRefFront=this.stencilRefBack=0;this.stencilMaskFront=this.stencilMaskBack=255;a.stencilFunc(a.ALWAYS,
|
|
0,255);this.stencilZpassFront=this.stencilZpassBack=this.stencilZfailFront=this.stencilZfailBack=this.stencilFailFront=this.stencilFailBack=pc.STENCILOP_KEEP;this.stencilWriteMaskBack=this.stencilWriteMaskFront=255;a.stencilOp(a.KEEP,a.KEEP,a.KEEP);a.stencilMask(255);this.alphaToCoverage=!1;this.raster=!0;this.webgl2&&(a.disable(a.SAMPLE_ALPHA_TO_COVERAGE),a.disable(a.RASTERIZER_DISCARD));this.depthBiasEnabled=!1;a.disable(a.POLYGON_OFFSET_FILL);this.clearDepth=1;a.clearDepth(1);this.clearAlpha=this.clearGreen=
|
|
this.clearBlue=this.clearRed=0;a.clearColor(0,0,0,0);this.clearStencil=0;a.clearStencil(0);this.sx=this.sy=this.sw=this.sh=this.vx=this.vy=this.vw=this.vh=0;this.webgl2?a.hint(a.FRAGMENT_SHADER_DERIVATIVE_HINT,a.NICEST):this.extStandardDerivatives&&a.hint(this.extStandardDerivatives.FRAGMENT_SHADER_DERIVATIVE_HINT_OES,a.NICEST);a.enable(a.SCISSOR_TEST);a.pixelStorei(a.UNPACK_COLORSPACE_CONVERSION_WEBGL,a.NONE);this.unpackFlipY=!1;a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,!1);this.unpackPremultiplyAlpha=
|
|
!1;a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1)},initializeContext:function(){this.initializeExtensions();this.initializeCapabilities();this.initializeRenderState();var a,b;a=0;for(b=this.shaders.length;a<b;a++)this.compileAndLinkShader(this.shaders[a]);this.shader=null;a=0;for(b=this.buffers.length;a<b;a++)this.buffers[a].bufferId=void 0,this.buffers[a].unlock();this.indexBuffer=this.boundElementBuffer=this.boundBuffer=null;this.attributesInvalidated=!0;this.enabledAttributes={};this.vertexBuffers=
|
|
[];a=0;for(b=this.textures.length;a<b;a++){var f=this.textures[a];this.destroyTexture(f);f.dirtyAll()}this.textureUnit=0;for(a=this.textureUnits.length=0;a<this.maxCombinedTextures;a++)this.textureUnits.push([null,null,null]);a=0;for(b=this.targets.length;a<b;a++)this.targets[a]._glFrameBuffer=void 0,this.targets[a]._glDepthBuffer=void 0,this.targets[a]._glResolveFrameBuffer=void 0,this.targets[a]._glMsaaColorBuffer=void 0,this.targets[a]._glMsaaDepthBuffer=void 0;this.transformFeedbackBuffer=this.feedback=
|
|
this.activeFramebuffer=this.renderTarget=null},initializeGrabPassTexture:function(){if(!this.grabPassTexture){var a=new pc.Texture(this,{format:pc.PIXELFORMAT_R8_G8_B8_A8,autoMipmap:!1});a.minFilter=pc.FILTER_LINEAR;a.magFilter=pc.FILTER_LINEAR;a.addressU=pc.ADDRESS_CLAMP_TO_EDGE;a.addressV=pc.ADDRESS_CLAMP_TO_EDGE;a.name="texture_grabPass";a.setSource(this.canvas);var b=this.scope.resolve(a.name);b.setValue(a);this.grabPassTextureId=b;this.grabPassTexture=a}},updateClientRect:function(){this.clientRect=
|
|
this.canvas.getBoundingClientRect()},setViewport:function(a,b,f,g){if(this.vx!==a||this.vy!==b||this.vw!==f||this.vh!==g)this.gl.viewport(a,b,f,g),this.vx=a,this.vy=b,this.vw=f,this.vh=g},setScissor:function(a,b,f,g){if(this.sx!==a||this.sy!==b||this.sw!==f||this.sh!==g)this.gl.scissor(a,b,f,g),this.sx=a,this.sy=b,this.sw=f,this.sh=g},getProgramLibrary:function(){return this.programLib},setProgramLibrary:function(a){this.programLib=a},setFramebuffer:function(a){this.activeFramebuffer!==a&&(this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,
|
|
a),this.activeFramebuffer=a)},_checkFbo:function(){var a=this.gl;switch(a.checkFramebufferStatus(a.FRAMEBUFFER)){case a.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:console.error("ERROR: FRAMEBUFFER_INCOMPLETE_ATTACHMENT");break;case a.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:console.error("ERROR: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT");break;case a.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:console.error("ERROR: FRAMEBUFFER_INCOMPLETE_DIMENSIONS");break;case a.FRAMEBUFFER_UNSUPPORTED:console.error("ERROR: FRAMEBUFFER_UNSUPPORTED")}},
|
|
copyRenderTarget:function(a,b,f,g){var c=this.gl;if(!this.webgl2&&g)return!1;if(f)if(!b){if(!a._colorBuffer)return!1}else if(!a._colorBuffer||!b._colorBuffer||a._colorBuffer._format!==b._colorBuffer._format)return!1;if(g&&(!a._depthBuffer||!b._depthBuffer||a._depthBuffer._format!==b._depthBuffer._format))return!1;if(this.webgl2&&b){var d=this.renderTarget;this.renderTarget=b;this.updateBegin();c.bindFramebuffer(c.READ_FRAMEBUFFER,a?a._glFrameBuffer:null);c.bindFramebuffer(c.DRAW_FRAMEBUFFER,b._glFrameBuffer);
|
|
var e=a?a.width:b.width;a=a?a.height:b.height;c.blitFramebuffer(0,0,e,a,0,0,e,a,(f?c.COLOR_BUFFER_BIT:0)|(g?c.DEPTH_BUFFER_BIT:0),c.NEAREST);this.renderTarget=d;c.bindFramebuffer(c.FRAMEBUFFER,d?d._glFrameBuffer:null)}else this._copyShader||(f=pc.shaderChunks,this._copyShader=f.createShaderFromCode(this,f.fullscreenQuadVS,f.outputTex2DPS,"outputTex2D")),this.constantTexSource.setValue(a._colorBuffer),pc.drawQuadWithShader(this,b,this._copyShader);return!0},updateBegin:function(){var a=this.gl;this.boundElementBuffer=
|
|
this.boundBuffer=null;var b=this.renderTarget;if(b)if(b._glFrameBuffer)this.setFramebuffer(b._glFrameBuffer);else{b._device=this;b._glFrameBuffer=a.createFramebuffer();this.setFramebuffer(b._glFrameBuffer);var f=b._colorBuffer;f&&(f._glTexture||(f._width=Math.min(f.width,this.maxRenderBufferSize),f._height=Math.min(f.height,this.maxRenderBufferSize),this.setTexture(f,0)),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,f._cubemap?a.TEXTURE_CUBE_MAP_POSITIVE_X+b._face:a.TEXTURE_2D,f._glTexture,
|
|
0));var g=b._depthBuffer;g&&this.webgl2?(g._glTexture||(g._width=Math.min(g.width,this.maxRenderBufferSize),g._height=Math.min(g.height,this.maxRenderBufferSize),this.setTexture(g,0)),b._stencil?a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,g._cubemap?a.TEXTURE_CUBE_MAP_POSITIVE_X+b._face:a.TEXTURE_2D,b._depthBuffer._glTexture,0):a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,g._cubemap?a.TEXTURE_CUBE_MAP_POSITIVE_X+b._face:a.TEXTURE_2D,b._depthBuffer._glTexture,0)):!b._depth||
|
|
1<b._samples&&this.webgl2||(b._glDepthBuffer||(b._glDepthBuffer=a.createRenderbuffer()),a.bindRenderbuffer(a.RENDERBUFFER,b._glDepthBuffer),b._stencil?(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_STENCIL,b.width,b.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.RENDERBUFFER,b._glDepthBuffer)):(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_COMPONENT16,b.width,b.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.RENDERBUFFER,b._glDepthBuffer)),a.bindRenderbuffer(a.RENDERBUFFER,
|
|
null));this.webgl2&&1<b._samples&&(b._glResolveFrameBuffer=b._glFrameBuffer,b._glFrameBuffer=a.createFramebuffer(),this.setFramebuffer(b._glFrameBuffer),f&&(b._glMsaaColorBuffer||(b._glMsaaColorBuffer=a.createRenderbuffer()),a.bindRenderbuffer(a.RENDERBUFFER,b._glMsaaColorBuffer),a.renderbufferStorageMultisample(a.RENDERBUFFER,b._samples,f._glInternalFormat,b.width,b.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.RENDERBUFFER,b._glMsaaColorBuffer)),b._depth&&(b._glMsaaDepthBuffer||
|
|
(b._glMsaaDepthBuffer=a.createRenderbuffer()),a.bindRenderbuffer(a.RENDERBUFFER,b._glMsaaDepthBuffer),b._stencil?(a.renderbufferStorageMultisample(a.RENDERBUFFER,b._samples,a.DEPTH24_STENCIL8,b.width,b.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.RENDERBUFFER,b._glMsaaDepthBuffer)):(a.renderbufferStorageMultisample(a.RENDERBUFFER,b._samples,a.DEPTH_COMPONENT32F,b.width,b.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.RENDERBUFFER,b._glMsaaDepthBuffer))));
|
|
this.targets.push(b)}else this.setFramebuffer(null)},updateEnd:function(){var a=this.gl,b=this.renderTarget;if(b){var f=b._colorBuffer;f&&f._glTexture&&f.mipmaps&&f._pot&&(this.activeTexture(this.maxCombinedTextures-1),this.bindTexture(f),a.generateMipmap(f._glTarget));this.webgl2&&1<b._samples&&b.autoResolve&&b.resolve()}},initializeTexture:function(a){var b=this.gl,c;a._glTexture=b.createTexture();a._glTarget=a._cubemap?b.TEXTURE_CUBE_MAP:a._volume?b.TEXTURE_3D:b.TEXTURE_2D;switch(a._format){case pc.PIXELFORMAT_A8:a._glFormat=
|
|
b.ALPHA;a._glInternalFormat=b.ALPHA;a._glPixelType=b.UNSIGNED_BYTE;break;case pc.PIXELFORMAT_L8:a._glFormat=b.LUMINANCE;a._glInternalFormat=b.LUMINANCE;a._glPixelType=b.UNSIGNED_BYTE;break;case pc.PIXELFORMAT_L8_A8:a._glFormat=b.LUMINANCE_ALPHA;a._glInternalFormat=b.LUMINANCE_ALPHA;a._glPixelType=b.UNSIGNED_BYTE;break;case pc.PIXELFORMAT_R5_G6_B5:a._glFormat=b.RGB;a._glInternalFormat=b.RGB;a._glPixelType=b.UNSIGNED_SHORT_5_6_5;break;case pc.PIXELFORMAT_R5_G5_B5_A1:a._glFormat=b.RGBA;a._glInternalFormat=
|
|
b.RGBA;a._glPixelType=b.UNSIGNED_SHORT_5_5_5_1;break;case pc.PIXELFORMAT_R4_G4_B4_A4:a._glFormat=b.RGBA;a._glInternalFormat=b.RGBA;a._glPixelType=b.UNSIGNED_SHORT_4_4_4_4;break;case pc.PIXELFORMAT_R8_G8_B8:a._glFormat=b.RGB;a._glInternalFormat=this.webgl2?b.RGB8:b.RGB;a._glPixelType=b.UNSIGNED_BYTE;break;case pc.PIXELFORMAT_R8_G8_B8_A8:a._glFormat=b.RGBA;a._glInternalFormat=this.webgl2?b.RGBA8:b.RGBA;a._glPixelType=b.UNSIGNED_BYTE;break;case pc.PIXELFORMAT_DXT1:c=this.extCompressedTextureS3TC;a._glFormat=
|
|
b.RGB;a._glInternalFormat=c.COMPRESSED_RGB_S3TC_DXT1_EXT;break;case pc.PIXELFORMAT_DXT3:c=this.extCompressedTextureS3TC;a._glFormat=b.RGBA;a._glInternalFormat=c.COMPRESSED_RGBA_S3TC_DXT3_EXT;break;case pc.PIXELFORMAT_DXT5:c=this.extCompressedTextureS3TC;a._glFormat=b.RGBA;a._glInternalFormat=c.COMPRESSED_RGBA_S3TC_DXT5_EXT;break;case pc.PIXELFORMAT_ETC1:c=this.extCompressedTextureETC1;a._glFormat=b.RGB;a._glInternalFormat=c.COMPRESSED_RGB_ETC1_WEBGL;break;case pc.PIXELFORMAT_PVRTC_2BPP_RGB_1:c=this.extCompressedTexturePVRTC;
|
|
a._glFormat=b.RGB;a._glInternalFormat=c.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;break;case pc.PIXELFORMAT_PVRTC_2BPP_RGBA_1:c=this.extCompressedTexturePVRTC;a._glFormat=b.RGBA;a._glInternalFormat=c.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;break;case pc.PIXELFORMAT_PVRTC_4BPP_RGB_1:c=this.extCompressedTexturePVRTC;a._glFormat=b.RGB;a._glInternalFormat=c.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;break;case pc.PIXELFORMAT_PVRTC_4BPP_RGBA_1:c=this.extCompressedTexturePVRTC;a._glFormat=b.RGBA;a._glInternalFormat=c.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
|
|
break;case pc.PIXELFORMAT_ETC2_RGB:c=this.extCompressedTextureETC;a._glFormat=b.RGB;a._glInternalFormat=c.COMPRESSED_RGB8_ETC2;break;case pc.PIXELFORMAT_ETC2_RGBA:c=this.extCompressedTextureETC;a._glFormat=b.RGBA;a._glInternalFormat=c.COMPRESSED_RGBA8_ETC2_EAC;break;case pc.PIXELFORMAT_RGB16F:c=this.extTextureHalfFloat;a._glFormat=b.RGB;this.webgl2?(a._glInternalFormat=b.RGB16F,a._glPixelType=b.HALF_FLOAT):(a._glInternalFormat=b.RGB,a._glPixelType=c.HALF_FLOAT_OES);break;case pc.PIXELFORMAT_RGBA16F:c=
|
|
this.extTextureHalfFloat;a._glFormat=b.RGBA;this.webgl2?(a._glInternalFormat=b.RGBA16F,a._glPixelType=b.HALF_FLOAT):(a._glInternalFormat=b.RGBA,a._glPixelType=c.HALF_FLOAT_OES);break;case pc.PIXELFORMAT_RGB32F:a._glFormat=b.RGB;a._glInternalFormat=this.webgl2?b.RGB32F:b.RGB;a._glPixelType=b.FLOAT;break;case pc.PIXELFORMAT_RGBA32F:a._glFormat=b.RGBA;a._glInternalFormat=this.webgl2?b.RGBA32F:b.RGBA;a._glPixelType=b.FLOAT;break;case pc.PIXELFORMAT_R32F:a._glFormat=b.RED;a._glInternalFormat=b.R32F;a._glPixelType=
|
|
b.FLOAT;break;case pc.PIXELFORMAT_DEPTH:this.webgl2?(a._glFormat=b.DEPTH_COMPONENT,a._glInternalFormat=b.DEPTH_COMPONENT32F,a._glPixelType=b.FLOAT):(a._glFormat=b.DEPTH_COMPONENT,a._glInternalFormat=b.DEPTH_COMPONENT,a._glPixelType=b.UNSIGNED_SHORT);break;case pc.PIXELFORMAT_DEPTHSTENCIL:a._glFormat=b.DEPTH_STENCIL;a._glInternalFormat=b.DEPTH24_STENCIL8;a._glPixelType=b.UNSIGNED_INT_24_8;break;case pc.PIXELFORMAT_111110F:a._glFormat=b.RGB;a._glInternalFormat=b.R11F_G11F_B10F;a._glPixelType=b.FLOAT;
|
|
break;case pc.PIXELFORMAT_SRGB:a._glFormat=b.RGB;a._glInternalFormat=b.SRGB8;a._glPixelType=b.UNSIGNED_BYTE;break;case pc.PIXELFORMAT_SRGBA:a._glFormat=b.RGBA,a._glInternalFormat=b.SRGB8_ALPHA8,a._glPixelType=b.UNSIGNED_BYTE}this.textures.push(a)},destroyTexture:function(a){if(a._glTexture){var b=this.textures.indexOf(a);-1!==b&&this.textures.splice(b,1);for(var c in this.scope.variables)b=this.scope.variables[c],b.value===a&&(b.value=null);for(c=0;c<this.textureUnits.length;c++)for(var b=this.textureUnits[c],
|
|
g=0;g<b.length;g++)b[g]===a._glTexture&&(b[g]=null);this.gl.deleteTexture(a._glTexture);delete a._glTexture;delete a._glTarget;delete a._glFormat;delete a._glInternalFormat;delete a._glPixelType;this._vram.tex-=a._gpuSize}},setUnpackFlipY:function(a){if(this.unpackFlipY!==a){this.unpackFlipY=a;var b=this.gl;b.pixelStorei(b.UNPACK_FLIP_Y_WEBGL,a)}},setUnpackPremultiplyAlpha:function(a){if(this.unpackPremultiplyAlpha!==a){this.unpackPremultiplyAlpha=a;var b=this.gl;b.pixelStorei(b.UNPACK_PREMULTIPLY_ALPHA_WEBGL,
|
|
a)}},uploadTexture:function(a){var c=this.gl;if(a._needsUpload||!(a._needsMipmapsUpload&&a._mipmapsUploaded||!a._pot)){for(var f=0,g,l;a._levels[f]||0===f;){if(a._needsUpload||0!==f){if(f&&(!a._needsMipmapsUpload||!a._mipmaps))break;g=a._levels[f];1!=f||a._compressed||(c.generateMipmap(a._glTarget),a._mipmapsUploaded=!0);if(a._cubemap){var h;if(g[0]instanceof HTMLCanvasElement||g[0]instanceof HTMLImageElement||g[0]instanceof HTMLVideoElement)for(h=0;6>h;h++)a._levelsUpdated[0][h]&&(l=g[h],l instanceof
|
|
HTMLImageElement&&(l.width>this.maxCubeMapSize||l.height>this.maxCubeMapSize)&&(l=b(l,this.maxCubeMapSize),0===f&&(a.width=l.width,a.height=l.height)),this.setUnpackFlipY(!1),this.setUnpackPremultiplyAlpha(a._premultiplyAlpha),c.texImage2D(c.TEXTURE_CUBE_MAP_POSITIVE_X+h,f,a._glInternalFormat,a._glFormat,a._glPixelType,l));else for(l=1/Math.pow(2,f),h=0;6>h;h++)if(a._levelsUpdated[0][h]){var e=g[h];a._compressed?c.compressedTexImage2D(c.TEXTURE_CUBE_MAP_POSITIVE_X+h,f,a._glInternalFormat,Math.max(a._width*
|
|
l,1),Math.max(a._height*l,1),0,e):(this.setUnpackFlipY(!1),this.setUnpackPremultiplyAlpha(a._premultiplyAlpha),c.texImage2D(c.TEXTURE_CUBE_MAP_POSITIVE_X+h,f,a._glInternalFormat,Math.max(a._width*l,1),Math.max(a._height*l,1),0,a._glFormat,a._glPixelType,e))}}else a._volume?(l=1/Math.pow(2,f),a._compressed?c.compressedTexImage3D(c.TEXTURE_3D,f,a._glInternalFormat,Math.max(a._width*l,1),Math.max(a._height*l,1),Math.max(a._depth*l,1),0,g):(this.setUnpackFlipY(!1),this.setUnpackPremultiplyAlpha(a._premultiplyAlpha),
|
|
c.texImage3D(c.TEXTURE_3D,f,a._glInternalFormat,Math.max(a._width*l,1),Math.max(a._height*l,1),Math.max(a._depth*l,1),0,a._glFormat,a._glPixelType,g))):(g instanceof HTMLCanvasElement||g instanceof HTMLImageElement||g instanceof HTMLVideoElement?(g instanceof HTMLImageElement&&(g.width>this.maxTextureSize||g.height>this.maxTextureSize)&&(g=b(g,this.maxTextureSize),0===f&&(a.width=g.width,a.height=g.height)),this.setUnpackFlipY(a._flipY),this.setUnpackPremultiplyAlpha(a._premultiplyAlpha),c.texImage2D(c.TEXTURE_2D,
|
|
f,a._glInternalFormat,a._glFormat,a._glPixelType,g)):(l=1/Math.pow(2,f),a._compressed?c.compressedTexImage2D(c.TEXTURE_2D,f,a._glInternalFormat,Math.max(a._width*l,1),Math.max(a._height*l,1),0,g):(this.setUnpackFlipY(!1),this.setUnpackPremultiplyAlpha(a._premultiplyAlpha),c.texImage2D(c.TEXTURE_2D,f,a._glInternalFormat,Math.max(a._width*l,1),Math.max(a._height*l,1),0,a._glFormat,a._glPixelType,g))),a._mipmapsUploaded=0===f?!1:!0)}f++}if(a._needsUpload)if(a._cubemap)for(f=0;6>f;f++)a._levelsUpdated[0][f]=
|
|
!1;else a._levelsUpdated[0]=!1;!a._compressed&&a._mipmaps&&a._needsMipmapsUpload&&a._pot&&1===a._levels.length&&(c.generateMipmap(a._glTarget),a._mipmapsUploaded=!0);a._gpuSize&&(this._vram.tex-=a._gpuSize);a._gpuSize=a.gpuSize;this._vram.tex+=a._gpuSize}},activeTexture:function(a){this.textureUnit!==a&&(this.gl.activeTexture(this.gl.TEXTURE0+a),this.textureUnit=a)},bindTexture:function(a){var b=a._glTarget;a=a._glTexture;var c=this.textureUnit,g=this.targetToSlot[b];this.textureUnits[c][g]!==a&&
|
|
(this.gl.bindTexture(b,a),this.textureUnits[c][g]=a)},bindTextureOnUnit:function(a,b){var c=a._glTarget,d=a._glTexture,l=this.targetToSlot[c];this.textureUnits[b][l]!==d&&(this.activeTexture(b),this.gl.bindTexture(c,d),this.textureUnits[b][l]=d)},setTextureParameters:function(a){var b=this.gl,c=a._parameterFlags,g=a._glTarget;if(c&1){var l=a._minFilter;if(!a._pot||!a._mipmaps||a._compressed&&1===a._levels.length)if(l===pc.FILTER_NEAREST_MIPMAP_NEAREST||l===pc.FILTER_NEAREST_MIPMAP_LINEAR)l=pc.FILTER_NEAREST;
|
|
else if(l===pc.FILTER_LINEAR_MIPMAP_NEAREST||l===pc.FILTER_LINEAR_MIPMAP_LINEAR)l=pc.FILTER_LINEAR;b.texParameteri(g,b.TEXTURE_MIN_FILTER,this.glFilter[l])}c&2&&b.texParameteri(g,b.TEXTURE_MAG_FILTER,this.glFilter[a._magFilter]);c&4&&(this.webgl2?b.texParameteri(g,b.TEXTURE_WRAP_S,this.glAddress[a._addressU]):b.texParameteri(g,b.TEXTURE_WRAP_S,this.glAddress[a._pot?a._addressU:pc.ADDRESS_CLAMP_TO_EDGE]));c&8&&(this.webgl2?b.texParameteri(g,b.TEXTURE_WRAP_T,this.glAddress[a._addressV]):b.texParameteri(g,
|
|
b.TEXTURE_WRAP_T,this.glAddress[a._pot?a._addressV:pc.ADDRESS_CLAMP_TO_EDGE]));c&16&&this.webgl2&&b.texParameteri(g,b.TEXTURE_WRAP_R,this.glAddress[a._addressW]);c&32&&this.webgl2&&b.texParameteri(g,b.TEXTURE_COMPARE_MODE,a._compareOnRead?b.COMPARE_REF_TO_TEXTURE:b.NONE);c&64&&this.webgl2&&b.texParameteri(g,b.TEXTURE_COMPARE_FUNC,this.glComparison[a._compareFunc]);c&128&&(c=this.extTextureFilterAnisotropic)&&b.texParameterf(g,c.TEXTURE_MAX_ANISOTROPY_EXT,Math.max(1,Math.min(Math.round(a._anisotropy),
|
|
this.maxAnisotropy)))},setTexture:function(a,b){a._glTexture||this.initializeTexture(a);if(0<a._parameterFlags||a._needsUpload||a._needsMipmapsUpload){if(this.activeTexture(b),this.bindTexture(a),a._parameterFlags&&(this.setTextureParameters(a),a._parameterFlags=0),a._needsUpload||a._needsMipmapsUpload)this.uploadTexture(a),a!==this.grabPassTexture&&(a._needsUpload=!1,a._needsMipmapsUpload=!1)}else this.bindTextureOnUnit(a,b)},setBuffers:function(a){var b=this.gl,c,g,l,h,e=this.shader.attributes;
|
|
if(this.attributesInvalidated){for(var k=0,n=e.length;k<n;k++)c=e[k],g=c.scopeId.value,null!==g&&(l=this.vertexBuffers[g.stream],h=this.vbOffsets[g.stream]||0,l=l.bufferId,this.boundBuffer!==l&&(b.bindBuffer(b.ARRAY_BUFFER,l),this.boundBuffer=l),c=c.locationId,this.enabledAttributes[c]||(b.enableVertexAttribArray(c),this.enabledAttributes[c]=!0),b.vertexAttribPointer(c,g.numComponents,this.glType[g.dataType],g.normalize,g.stride,g.offset+h),1===g.stream&&1<a?this.instancedAttribs[c]||(b.vertexAttribDivisor(c,
|
|
1),this.instancedAttribs[c]=!0):this.instancedAttribs[c]&&(b.vertexAttribDivisor(c,0),this.instancedAttribs[c]=!1));this.attributesInvalidated=!1}l=this.indexBuffer?this.indexBuffer.bufferId:null;this.boundElementBuffer!==l&&(b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,l),this.boundElementBuffer=l)},draw:function(a,b){var c=this.gl,d,l,h,e,k,n,q,m;d=this.shader;m=d.samplers;var r=d.uniforms;1<b&&(this.boundBuffer=null,this.attributesInvalidated=!0);this.setBuffers(b);var t=0;d=0;for(h=m.length;d<h;d++)if(e=
|
|
m[d],k=e.scopeId.value)if(k instanceof pc.Texture)n=k,this.setTexture(n,t),e.slot!==t&&(c.uniform1i(e.locationId,t),e.slot=t),t++;else{e.array.length=0;q=k.length;for(l=0;l<q;l++)n=k[l],this.setTexture(n,t),e.array[l]=t,t++;c.uniform1iv(e.locationId,e.array)}d=0;for(h=r.length;d<h;d++)if(m=r[d],l=m.scopeId,e=m.version,k=l.versionObject.version,e.globalId!==k.globalId||e.revision!==k.revision)if(e.globalId=k.globalId,e.revision=k.revision,null!==l.value)this.commitFunction[m.dataType](m,l.value);this.webgl2&&
|
|
this.transformFeedbackBuffer&&(c.bindBufferBase(c.TRANSFORM_FEEDBACK_BUFFER,0,this.transformFeedbackBuffer.bufferId),c.beginTransformFeedback(c.POINTS));d=this.glPrimitive[a.type];h=a.count;a.indexed?(m=this.indexBuffer,r=m.glFormat,m=a.base*m.bytesPerIndex,1<b?c.drawElementsInstanced(d,h,r,m,b):c.drawElements(d,h,r,m)):(r=a.base,1<b?c.drawArraysInstanced(d,r,h,b):c.drawArrays(d,r,h));this.webgl2&&this.transformFeedbackBuffer&&(c.endTransformFeedback(),c.bindBufferBase(c.TRANSFORM_FEEDBACK_BUFFER,
|
|
0,null))},clear:function(a){var b=this.defaultClearOptions;a=a||b;var c=void 0==a.flags?b.flags:a.flags;if(0!==c){var g=this.gl;if(c&pc.CLEARFLAG_COLOR){var l=void 0==a.color?b.color:a.color;this.setClearColor(l[0],l[1],l[2],l[3])}c&pc.CLEARFLAG_DEPTH&&(this.setClearDepth(void 0==a.depth?b.depth:a.depth),this.depthWrite||g.depthMask(!0));c&pc.CLEARFLAG_STENCIL&&this.setClearStencil(void 0==a.stencil?b.stencil:a.stencil);g.clear(this.glClearFlag[c]);c&pc.CLEARFLAG_DEPTH&&(this.depthWrite||g.depthMask(!1))}},
|
|
readPixels:function(a,b,f,g,l){var c=this.gl;c.readPixels(a,b,f,g,c.RGBA,c.UNSIGNED_BYTE,l)},setClearDepth:function(a){a!==this.clearDepth&&(this.gl.clearDepth(a),this.clearDepth=a)},setClearColor:function(a,b,f,g){if(a!==this.clearRed||b!==this.clearGreen||f!==this.clearBlue||g!==this.clearAlpha)this.gl.clearColor(a,b,f,g),this.clearRed=a,this.clearGreen=b,this.clearBlue=f,this.clearAlpha=g},setClearStencil:function(a){a!==this.clearStencil&&(this.gl.clearStencil(a),this.clearStencil=a)},setRenderTarget:function(a){this.renderTarget=
|
|
a},getRenderTarget:function(){return this.renderTarget},getDepthTest:function(){return this.depthTest},setDepthTest:function(a){if(this.depthTest!==a){var b=this.gl;a?b.enable(b.DEPTH_TEST):b.disable(b.DEPTH_TEST);this.depthTest=a}},setDepthFunc:function(a){this.depthFunc!==a&&(this.gl.depthFunc(this.glComparison[a]),this.depthFunc=a)},getDepthWrite:function(){return this.depthWrite},setDepthWrite:function(a){this.depthWrite!==a&&(this.gl.depthMask(a),this.depthWrite=a)},setColorWrite:function(a,
|
|
b,f,g){if(this.writeRed!==a||this.writeGreen!==b||this.writeBlue!==f||this.writeAlpha!==g)this.gl.colorMask(a,b,f,g),this.writeRed=a,this.writeGreen=b,this.writeBlue=f,this.writeAlpha=g},setAlphaToCoverage:function(a){this.webgl2&&this.alphaToCoverage!==a&&((this.alphaToCoverage=a)?this.gl.enable(this.gl.SAMPLE_ALPHA_TO_COVERAGE):this.gl.disable(this.gl.SAMPLE_ALPHA_TO_COVERAGE))},setTransformFeedbackBuffer:function(a){if(this.transformFeedbackBuffer!==a&&(this.transformFeedbackBuffer=a,this.webgl2)){var b=
|
|
this.gl;a?(this.feedback||(this.feedback=b.createTransformFeedback()),b.bindTransformFeedback(b.TRANSFORM_FEEDBACK,this.feedback)):b.bindTransformFeedback(b.TRANSFORM_FEEDBACK,null)}},setRaster:function(a){this.raster!==a&&(this.raster=a,this.webgl2&&(a?this.gl.disable(this.gl.RASTERIZER_DISCARD):this.gl.enable(this.gl.RASTERIZER_DISCARD)))},setDepthBias:function(a){this.depthBiasEnabled!==a&&((this.depthBiasEnabled=a)?this.gl.enable(this.gl.POLYGON_OFFSET_FILL):this.gl.disable(this.gl.POLYGON_OFFSET_FILL))},
|
|
setDepthBiasValues:function(a,b){this.gl.polygonOffset(b,a)},getBlending:function(){return this.blending},setBlending:function(a){if(this.blending!==a){var b=this.gl;a?b.enable(b.BLEND):b.disable(b.BLEND);this.blending=a}},setStencilTest:function(a){if(this.stencil!==a){var b=this.gl;a?b.enable(b.STENCIL_TEST):b.disable(b.STENCIL_TEST);this.stencil=a}},setStencilFunc:function(a,b,f){if(this.stencilFuncFront!==a||this.stencilRefFront!==b||this.stencilMaskFront!==f||this.stencilFuncBack!==a||this.stencilRefBack!==
|
|
b||this.stencilMaskBack!==f)this.gl.stencilFunc(this.glComparison[a],b,f),this.stencilFuncFront=this.stencilFuncBack=a,this.stencilRefFront=this.stencilRefBack=b,this.stencilMaskFront=this.stencilMaskBack=f},setStencilFuncFront:function(a,b,f){if(this.stencilFuncFront!==a||this.stencilRefFront!==b||this.stencilMaskFront!==f){var c=this.gl;c.stencilFuncSeparate(c.FRONT,this.glComparison[a],b,f);this.stencilFuncFront=a;this.stencilRefFront=b;this.stencilMaskFront=f}},setStencilFuncBack:function(a,b,
|
|
f){if(this.stencilFuncBack!==a||this.stencilRefBack!==b||this.stencilMaskBack!==f){var c=this.gl;c.stencilFuncSeparate(c.BACK,this.glComparison[a],b,f);this.stencilFuncBack=a;this.stencilRefBack=b;this.stencilMaskBack=f}},setStencilOperation:function(a,b,f,g){if(this.stencilFailFront!==a||this.stencilZfailFront!==b||this.stencilZpassFront!==f||this.stencilFailBack!==a||this.stencilZfailBack!==b||this.stencilZpassBack!==f)this.gl.stencilOp(this.glStencilOp[a],this.glStencilOp[b],this.glStencilOp[f]),
|
|
this.stencilFailFront=this.stencilFailBack=a,this.stencilZfailFront=this.stencilZfailBack=b,this.stencilZpassFront=this.stencilZpassBack=f;if(this.stencilWriteMaskFront!==g||this.stencilWriteMaskBack!==g)this.gl.stencilMask(g),this.stencilWriteMaskBack=this.stencilWriteMaskFront=g},setStencilOperationFront:function(a,b,f,g){if(this.stencilFailFront!==a||this.stencilZfailFront!==b||this.stencilZpassFront!==f)this.gl.stencilOpSeparate(this.gl.FRONT,this.glStencilOp[a],this.glStencilOp[b],this.glStencilOp[f]),
|
|
this.stencilFailFront=a,this.stencilZfailFront=b,this.stencilZpassFront=f;this.stencilWriteMaskFront!==g&&(this.gl.stencilMaskSeparate(this.gl.FRONT,g),this.stencilWriteMaskFront=g)},setStencilOperationBack:function(a,b,f,g){if(this.stencilFailBack!==a||this.stencilZfailBack!==b||this.stencilZpassBack!==f)this.gl.stencilOpSeparate(this.gl.BACK,this.glStencilOp[a],this.glStencilOp[b],this.glStencilOp[f]),this.stencilFailBack=a,this.stencilZfailBack=b,this.stencilZpassBack=f;this.stencilWriteMaskBack!==
|
|
g&&(this.gl.stencilMaskSeparate(this.gl.BACK,g),this.stencilWriteMaskBack=g)},setBlendFunction:function(a,b){if(this.blendSrc!==a||this.blendDst!==b||this.separateAlphaBlend)this.gl.blendFunc(this.glBlendFunction[a],this.glBlendFunction[b]),this.blendSrc=a,this.blendDst=b,this.separateAlphaBlend=!1},setBlendFunctionSeparate:function(a,b,f,g){this.blendSrc===a&&this.blendDst===b&&this.blendSrcAlpha===f&&this.blendDstAlpha===g&&this.separateAlphaBlend||(this.gl.blendFuncSeparate(this.glBlendFunction[a],
|
|
this.glBlendFunction[b],this.glBlendFunction[f],this.glBlendFunction[g]),this.blendSrc=a,this.blendDst=b,this.blendSrcAlpha=f,this.blendDstAlpha=g,this.separateAlphaBlend=!0)},setBlendEquation:function(a){if(this.blendEquation!==a||this.separateAlphaEquation)this.gl.blendEquation(this.glBlendEquation[a]),this.blendEquation=a,this.separateAlphaEquation=!1},setBlendEquationSeparate:function(a,b){this.blendEquation===a&&this.blendAlphaEquation===b&&this.separateAlphaEquation||(this.gl.blendEquationSeparate(this.glBlendEquation[a],
|
|
this.glBlendEquation[b]),this.blendEquation=a,this.blendAlphaEquation=b,this.separateAlphaEquation=!0)},setCullMode:function(a){if(this.cullMode!==a){if(a===pc.CULLFACE_NONE)this.gl.disable(this.gl.CULL_FACE);else{this.cullMode===pc.CULLFACE_NONE&&this.gl.enable(this.gl.CULL_FACE);var b=this.glCull[a];this.cullFace!==b&&(this.gl.cullFace(b),this.cullFace=b)}this.cullMode=a}},getCullMode:function(){return this.cullMode},setIndexBuffer:function(a){this.indexBuffer=a},setVertexBuffer:function(a,b,f){if(this.vertexBuffers[b]!==
|
|
a||this.vbOffsets[b]!==f){this.vertexBuffers[b]=a;this.vbOffsets[b]=f;f=0;a=a.getFormat().elements;for(var c=a.length;f<c;){var d=a[f++];d.stream=b;d.scopeId.setValue(d)}this.attributesInvalidated=!0}},compileShaderSource:function(a,b){var c=this.gl,d=b?this.vertexShaderCache[a]:this.fragmentShaderCache[a];d||(d=c.createShader(b?c.VERTEX_SHADER:c.FRAGMENT_SHADER),c.shaderSource(d,a),c.compileShader(d),b?this.vertexShaderCache[a]=d:this.fragmentShaderCache[a]=d);return d},compileAndLinkShader:function(a){var b=
|
|
this.gl,c=a.definition,g=this.compileShaderSource(c.vshader,!0),l=this.compileShaderSource(c.fshader,!1),h=b.createProgram();b.attachShader(h,g);b.attachShader(h,l);if(this.webgl2&&c.useTransformFeedback){var c=c.attributes,e=[],k;for(k in c)c.hasOwnProperty(k)&&e.push("out_"+k);b.transformFeedbackVaryings(h,e,b.INTERLEAVED_ATTRIBS)}b.linkProgram(h);a._glVertexShader=g;a._glFragmentShader=l;a._glProgram=h},createShader:function(a){this.compileAndLinkShader(a);this.shaders.push(a)},destroyShader:function(a){var b=
|
|
this.shaders.indexOf(a);-1!==b&&this.shaders.splice(b,1);a._glProgram&&(this.gl.deleteProgram(a._glProgram),a._glProgram=null,this.removeShaderFromCache(a))},_addLineNumbers:function(a){a=a.split("\n");for(var b=0,c=a.length;b<c;b++)a[b]=b+1+":\t"+a[b];return a.join("\n")},postLink:function(a){var b=this.gl,c=a._glVertexShader,g=a._glFragmentShader,l=a._glProgram,h=a.definition;if(!b.getShaderParameter(c,b.COMPILE_STATUS))return console.error("Failed to compile vertex shader:\n\n"+this._addLineNumbers(h.vshader)+
|
|
"\n\n"+b.getShaderInfoLog(c)),!1;if(!b.getShaderParameter(g,b.COMPILE_STATUS))return console.error("Failed to compile fragment shader:\n\n"+this._addLineNumbers(h.fshader)+"\n\n"+b.getShaderInfoLog(g)),!1;if(!b.getProgramParameter(l,b.LINK_STATUS))return console.error("Failed to link shader program. Error: "+b.getProgramInfoLog(l)),!1;for(var e,c=0,k=b.getProgramParameter(l,b.ACTIVE_ATTRIBUTES);c<k;)g=b.getActiveAttrib(l,c++),e=b.getAttribLocation(l,g.name),void 0===h.attributes[g.name]&&console.error('Vertex shader attribute "'+
|
|
g.name+'" is not mapped to a semantic in shader definition.'),e=new pc.ShaderInput(this,h.attributes[g.name],this.pcUniformType[g.type],e),a.attributes.push(e);c=0;for(h=b.getProgramParameter(l,b.ACTIVE_UNIFORMS);c<h;)g=b.getActiveUniform(l,c++),e=b.getUniformLocation(l,g.name),e=new pc.ShaderInput(this,g.name,this.pcUniformType[g.type],e),g.type===b.SAMPLER_2D||g.type===b.SAMPLER_CUBE||this.webgl2&&(g.type===b.SAMPLER_2D_SHADOW||g.type===b.SAMPLER_CUBE_SHADOW||g.type===b.SAMPLER_3D)?a.samplers.push(e):
|
|
a.uniforms.push(e);return a.ready=!0},setShader:function(a){if(a!==this.shader){if(!a.ready&&!this.postLink(a))return!1;this.shader=a;this.gl.useProgram(a._glProgram);this.attributesInvalidated=!0}return!0},getHdrFormat:function(){return this.textureHalfFloatRenderable?pc.PIXELFORMAT_RGB16F:this.textureFloatRenderable?pc.PIXELFORMAT_RGB32F:pc.PIXELFORMAT_R8_G8_B8_A8},getBoneLimit:function(){return this.boneLimit},setBoneLimit:function(a){this.boneLimit=a},resizeCanvas:function(a,b){this._width=a;
|
|
this._height=b;var c=Math.min(this._maxPixelRatio,window.devicePixelRatio);a*=c;b*=c;this.canvas.width=a;this.canvas.height=b;this.fire("resizecanvas",a,b)},setResolution:function(a,b){this._width=a;this._height=b;this.canvas.width=a;this.canvas.height=b;this.fire("resizecanvas",a,b)},clearShaderCache:function(){var a=this.gl,b;for(b in this.fragmentShaderCache)a.deleteShader(this.fragmentShaderCache[b]),delete this.fragmentShaderCache[b];for(b in this.vertexShaderCache)a.deleteShader(this.vertexShaderCache[b]),
|
|
delete this.vertexShaderCache[b];this.programLib.clearCache()},removeShaderFromCache:function(a){this.programLib.removeFromCache(a)},destroy:function(){var a=this.gl;this.grabPassTexture.destroy();this.webgl2&&this.feedback&&a.deleteTransformFeedback(this.feedback);this.clearShaderCache();this.canvas.removeEventListener("webglcontextlost",this._contextLostHandler,!1);this.canvas.removeEventListener("webglcontextrestored",this._contextRestoredHandler,!1);this.gl=this.canvas=this._contextRestoredHandler=
|
|
this._contextLostHandler=null}});Object.defineProperty(a.prototype,"width",{get:function(){return this.gl.drawingBufferWidth||this.canvas.width}});Object.defineProperty(a.prototype,"height",{get:function(){return this.gl.drawingBufferHeight||this.canvas.height}});Object.defineProperty(a.prototype,"fullscreen",{get:function(){return!!document.fullscreenElement},set:function(a){a?this.gl.canvas.requestFullscreen():document.exitFullscreen()}});Object.defineProperty(a.prototype,"enableAutoInstancing",
|
|
{get:function(){return this._enableAutoInstancing},set:function(a){this._enableAutoInstancing=a&&this.extInstancing}});Object.defineProperty(a.prototype,"maxPixelRatio",{get:function(){return this._maxPixelRatio},set:function(a){this._maxPixelRatio=a;this.resizeCanvas(this._width,this._height)}});Object.defineProperty(a.prototype,"textureFloatHighPrecision",{get:function(){if(void 0===this._textureFloatHighPrecision){var a;if(this.textureFloatRenderable){a=pc.shaderChunks;var b=a.createShaderFromCode(this,
|
|
a.fullscreenQuadVS,a.precisionTestPS,"ptest1"),f=a.createShaderFromCode(this,a.fullscreenQuadVS,a.precisionTest2PS,"ptest2"),g={format:pc.PIXELFORMAT_RGBA32F,width:1,height:1,mipmaps:!1,minFilter:pc.FILTER_NEAREST,magFilter:pc.FILTER_NEAREST};a=new pc.Texture(this,g);a.name="testFHP";var l=new pc.RenderTarget(this,a,{depth:!1});pc.drawQuadWithShader(this,l,b);g.format=pc.PIXELFORMAT_R8_G8_B8_A8;b=new pc.Texture(this,g);b.name="testFHP";g=new pc.RenderTarget(this,b,{depth:!1});this.constantTexSource.setValue(a);
|
|
pc.drawQuadWithShader(this,g,f);f=this.activeFramebuffer;this.setFramebuffer(g._glFrameBuffer);var h=new Uint8Array(4);this.readPixels(0,0,1,1,h);this.setFramebuffer(f);f=h[0]/255/16777216+h[1]/255/65536+h[2]/255/256+h[3]/255;a.destroy();l.destroy();b.destroy();g.destroy();a=0===f}else a=!1;this._textureFloatHighPrecision=a}return this._textureFloatHighPrecision}});return{GraphicsDevice:a}}());Object.assign(pc,function(){var e={},b={vertex_position:pc.SEMANTIC_POSITION,vertex_normal:pc.SEMANTIC_NORMAL,vertex_tangent:pc.SEMANTIC_TANGENT,vertex_texCoord0:pc.SEMANTIC_TEXCOORD0,vertex_texCoord1:pc.SEMANTIC_TEXCOORD1,vertex_texCoord2:pc.SEMANTIC_TEXCOORD2,vertex_texCoord3:pc.SEMANTIC_TEXCOORD3,vertex_texCoord4:pc.SEMANTIC_TEXCOORD4,vertex_texCoord5:pc.SEMANTIC_TEXCOORD5,vertex_texCoord6:pc.SEMANTIC_TEXCOORD6,vertex_texCoord7:pc.SEMANTIC_TEXCOORD7,vertex_color:pc.SEMANTIC_COLOR,vertex_boneIndices:pc.SEMANTIC_BLENDINDICES,
|
|
vertex_boneWeights:pc.SEMANTIC_BLENDWEIGHT};e.collectAttribs=function(a){for(var c={},d=0,f=a.indexOf("attribute");0<=f&&!(0<f&&"/"===a[f-1]);){var g=a.indexOf(";",f),l=a.lastIndexOf(" ",g),g=a.substr(l+1,g-(l+1)),l=b[g];void 0!==l?c[g]=l:(c[g]="ATTR"+d,d++);f=a.indexOf("attribute",f+1)}return c};e.createShader=function(a,b,d,f){b=e[b];d=pc.programlib.precisionCode(a)+"\n"+e[d];var c=this.collectAttribs(b);a.webgl2&&(b=pc.programlib.versionCode(a)+this.gles3VS+b,d=pc.programlib.versionCode(a)+this.gles3PS+
|
|
d);return new pc.Shader(a,{attributes:c,vshader:b,fshader:d,useTransformFeedback:f})};e.createShaderFromCode=function(a,b,d,f,g){var c=a.programLib._cache,h=c[f];if(void 0!==h)return h;d=pc.programlib.precisionCode(a)+"\n"+(d||pc.programlib.dummyFragmentCode());h=this.collectAttribs(b);a.webgl2&&(b=pc.programlib.versionCode(a)+this.gles3VS+b,d=pc.programlib.versionCode(a)+this.gles3PS+d);c[f]=new pc.Shader(a,{attributes:h,vshader:b,fshader:d,useTransformFeedback:g});return c[f]};return{shaderChunks:e}}());Object.assign(pc,function(){var e=null,b={type:pc.PRIMITIVE_TRISTRIP,base:0,count:4,indexed:!1};return{drawQuadWithShader:function(a,c,d,f,g,l){if(null===e){var h=new pc.VertexFormat(a,[{semantic:pc.SEMANTIC_POSITION,components:2,type:pc.TYPE_FLOAT32}]);e=new pc.VertexBuffer(a,h,4);h=new pc.VertexIterator(e);h.element[pc.SEMANTIC_POSITION].set(-1,-1);h.next();h.element[pc.SEMANTIC_POSITION].set(1,-1);h.next();h.element[pc.SEMANTIC_POSITION].set(-1,1);h.next();h.element[pc.SEMANTIC_POSITION].set(1,
|
|
1);h.end()}h=a.renderTarget;a.setRenderTarget(c);a.updateBegin();var p,k,n,q,m,r,t,u;f?(p=f.x,k=f.y,n=f.z,q=f.w):(n=c?c.width:a.width,q=c?c.height:a.height,k=p=0);g?(m=g.x,r=g.y,t=g.z,u=g.w):(m=p,r=k,t=n,u=q);g=a.vx;f=a.vy;c=a.vw;var x=a.vh;a.setViewport(p,k,n,q);n=a.sx;p=a.sy;k=a.sw;q=a.sh;a.setScissor(m,r,t,u);m=a.getDepthTest();r=a.getDepthWrite();t=a.getCullMode();u=a.writeRed;var v=a.writeGreen,w=a.writeBlue,y=a.writeAlpha;a.setDepthTest(!1);a.setDepthWrite(!1);a.setCullMode(pc.CULLFACE_NONE);
|
|
a.setColorWrite(!0,!0,!0,!0);l||a.setBlending(!1);a.setVertexBuffer(e,0);a.setShader(d);a.draw(b);a.setDepthTest(m);a.setDepthWrite(r);a.setCullMode(t);a.setColorWrite(u,v,w,y);a.updateEnd();a.setRenderTarget(h);a.updateBegin();a.setViewport(g,f,c,x);a.setScissor(n,p,k,q)},destroyPostEffectQuad:function(){e&&(e.destroy(),e=null)}}}());Object.assign(pc,function(){function e(a,b,d){var c=b._colorBuffer;if(c.format==pc.PIXELFORMAT_R8_G8_B8_A8){var g=new Uint8Array(c.width*c.height*4),l=a.gl;a.setFramebuffer(b._glFrameBuffer);l.readPixels(0,0,c.width,c.height,l.RGBA,l.UNSIGNED_BYTE,g);c._levels||(c._levels=[]);c._levels[0]||(c._levels[0]=[]);c._levels[0][d]=g}}function b(a,b){return Math.atan2(a*b,Math.sqrt(a*a+b*b+1))}return{prefilterCubemap:function(a){var b=a.device,d=a.sourceCubemap,f=a.method,g=a.samples,l=a.cpuSync;if(l&&!d._levels[0])console.error("ERROR: prefilter: cubemap must have _levels");
|
|
else{var h=pc.shaderChunks,p=d.rgbm,g=h.createShaderFromCode(b,h.fullscreenQuadVS,h.rgbmPS+h.prefilterCubemapPS.replace(/\$METHOD/g,0===f?"cos":"phong").replace(/\$NUMSAMPLES/g,g).replace(/\$textureCube/g,p?"textureCubeRGBM":"textureCube"),"prefilter"+f+""+g+""+p),k=h.createShaderFromCode(b,h.fullscreenQuadVS,h.outputCubemapPS,"outputCubemap"),n=b.scope.resolve("source"),q=b.scope.resolve("params"),m=new pc.Vec4,r=d.width,h=d.format,t=[[],a.filteredFixed,a.filteredRgbm,a.filteredFixedRgbm],u=0===
|
|
f?[.9,.85,.7,.4,.25]:[512,128,32,8,2],x=[64,32,16,8,4],v,w,y;w=h===pc.PIXELFORMAT_R8_G8_B8;v=!1;var D;l&&(v=d._levels[0][0]instanceof HTMLImageElement);if((w||v)&&l){h=pc.PIXELFORMAT_R8_G8_B8_A8;D=new pc.Texture(b,{cubemap:!0,rgbm:p,format:h,width:r,height:r,mipmaps:!1});D.name="prefiltered-cube";for(y=0;6>y;y++)v=new pc.RenderTarget(b,D,{face:y,depth:!1}),m.x=y,m.y=0,n.setValue(d),q.setValue(m.data),pc.drawQuadWithShader(b,v,k),e(b,v,y);d=D}if(128<r){var B=Math.round(Math.log2(r))-Math.round(Math.log2(128));
|
|
for(w=0;w<B;w++){var r=.5*d.width,z=0===f?1:Math.pow(2,Math.round(Math.log2(u[0])+2*(B-w)));D=new pc.Texture(b,{cubemap:!0,rgbm:p,format:h,width:r,height:r,mipmaps:!1});D.name="prefiltered-cube";for(y=0;6>y;y++)v=new pc.RenderTarget(b,D,{face:y,depth:!1}),m.x=y,m.y=z,m.z=r,m.w=p?3:0,n.setValue(d),q.setValue(m.data),pc.drawQuadWithShader(b,v,k),w===B-1&&l&&e(b,v,y);d=D}}a.sourceCubemap=d;D=null;if(!p&&a.filteredFixedRgbm)for(D=new pc.Texture(b,{cubemap:!0,rgbm:!0,format:pc.PIXELFORMAT_R8_G8_B8_A8,
|
|
width:r,height:r,mipmaps:!1}),D.name="prefiltered-cube",y=0;6>y;y++)v=new pc.RenderTarget(b,D,{face:y,depth:!1}),m.x=y,m.w=2,n.setValue(d),q.setValue(m.data),pc.drawQuadWithShader(b,v,k),e(b,v,y);r=0===f?1:2048;v=0===f?0:-1;t[v]=[];for(w=0;5>w;w++)for(k=v;k<t.length;k++)null!=t[k]&&(t[k][w]=new pc.Texture(b,{cubemap:!0,rgbm:2>k?p:!0,format:2>k?h:pc.PIXELFORMAT_R8_G8_B8_A8,fixCubemapSeams:1===k||3===k,width:x[w],height:x[w],mipmaps:!1}),t[k][w].name="prefiltered-cube");for(k=v;k<t.length;k++)if(null!=
|
|
t[k])if(1<k&&p)t[k]=t[k-2];else for(w=0;5>w;w++)for(y=0;6>y;y++)v=new pc.RenderTarget(b,t[k][w],{face:y,depth:!1}),m.x=y,m.y=0>k?r:u[w],m.z=x[w],m.w=p?3:k,n.setValue(0===w?d:0===f?t[0][w-1]:t[-1][w-1]),q.setValue(m.data),pc.drawQuadWithShader(b,v,g),l&&e(b,v,y);a.filtered=t[0];if(l&&a.singleFilteredFixed){d=[d,a.filteredFixed[0],a.filteredFixed[1],a.filteredFixed[2],a.filteredFixed[3],a.filteredFixed[4],a.filteredFixed[5]];p=new pc.Texture(b,{cubemap:!0,rgbm:p,fixCubemapSeams:!0,format:h,width:128,
|
|
height:128,addressU:pc.ADDRESS_CLAMP_TO_EDGE,addressV:pc.ADDRESS_CLAMP_TO_EDGE});p.name="prefiltered-cube";for(w=0;6>w;w++)p._levels[w]=d[w]._levels[0];p.upload();p._prefilteredMips=!0;a.singleFilteredFixed=p}if(l&&a.singleFilteredFixedRgbm&&a.filteredFixedRgbm){d=[D,a.filteredFixedRgbm[0],a.filteredFixedRgbm[1],a.filteredFixedRgbm[2],a.filteredFixedRgbm[3],a.filteredFixedRgbm[4],a.filteredFixedRgbm[5]];p=new pc.Texture(b,{cubemap:!0,rgbm:!0,fixCubemapSeams:!0,format:pc.PIXELFORMAT_R8_G8_B8_A8,width:128,
|
|
height:128,addressU:pc.ADDRESS_CLAMP_TO_EDGE,addressV:pc.ADDRESS_CLAMP_TO_EDGE});p.name="prefiltered-cube";for(w=0;6>w;w++)p._levels[w]=d[w]._levels[0];p.upload();p._prefilteredMips=!0;a.singleFilteredFixedRgbm=p}}},shFromCubemap:function(a,c){var d,f=a.width,g,l;if(a.format!=pc.PIXELFORMAT_R8_G8_B8_A8)console.error("ERROR: SH: cubemap must be RGBA8");else{if(a._levels[0]){if(!a._levels[0][0].length)if(a._levels[0][0]instanceof HTMLImageElement){g=pc.Application.getApplication().graphicsDevice;l=
|
|
g.gl;d=pc.shaderChunks;var h=d.createShaderFromCode(g,d.fullscreenQuadVS,d.fullscreenQuadPS,"fsQuadSimple"),e=g.scope.resolve("source");for(d=0;6>d;d++){var k=a._levels[0][d],n=new pc.Texture(g,{cubemap:!1,rgbm:!1,format:a.format,width:f,height:f,mipmaps:!1});n.name="prefiltered-cube";n._levels[0]=k;n.upload();k=new pc.Texture(g,{cubemap:!1,rgbm:!1,format:a.format,width:f,height:f,mipmaps:!1});k.name="prefiltered-cube";k=new pc.RenderTarget(g,k,{depth:!1});e.setValue(n);pc.drawQuadWithShader(g,k,
|
|
h);var q=new Uint8Array(f*f*4);l.bindFramebuffer(l.FRAMEBUFFER,k._glFrameBuffer);l.readPixels(0,0,n.width,n.height,l.RGBA,l.UNSIGNED_BYTE,q);a._levels[0][d]=q}}else{console.error("ERROR: SH: cubemap must be composed of arrays or images");return}h=[];for(l=0;l<f;l++)for(g=0;g<f;g++)h[l*f+g]=(new pc.Vec3(g/(f-1)*2-1,l/(f-1)*2-1,1)).normalize();var e=new Float32Array(27),m,r,t,u,x,v,w,y,D,B,z;for(d=k=0;6>d;d++)for(l=0;l<f;l++)for(g=0;g<f;g++){n=l*f+g;q=g;w=l;y=f;r=(2*(q+.5)/y-1)*(1-1/y);z=(2*(w+.5)/
|
|
y-1)*(1-1/y);m=1/y;D=r-m;B=z-m;r+=m;z+=m;D=b(D,B)-b(D,z)-b(r,B)+b(r,z);if(0===q&&0===w||q===y-1&&0===w||0===q&&w===y-1||q===y-1&&w===y-1)D/=3;else if(0===q||0===w||q===y-1||w===y-1)D*=.5;q=D;w=4*q/17;y=8*q/17;D=15*q/17;B=5*q/68;z=15*q/68;m=h[n];0==d?(u=m.z,x=-m.y,v=-m.x):1==d?(u=-m.z,x=-m.y,v=m.x):2==d?(u=m.x,x=m.z,v=m.y):3==d?(u=m.x,x=-m.z,v=-m.y):4==d?(u=m.x,x=-m.y,v=m.z):5==d&&(u=-m.x,x=-m.y,v=-m.z);c||(u=-u);r=a._levels[0][d][4*n+3]/255;for(m=0;3>m;m++)t=a._levels[0][d][4*n+m]/255,a.rgbm?(t*=
|
|
8*r,t*=t):t=Math.pow(t,2.2),e[0+m]+=t*w,e[3+m]+=t*y*u,e[6+m]+=t*y*x,e[9+m]+=t*y*v,e[12+m]+=t*D*u*v,e[15+m]+=t*D*v*x,e[18+m]+=t*D*x*u,e[21+m]+=t*B*(3*v*v-1),e[24+m]+=t*z*(u*u-x*x),k+=q}for(m=0;m<e.length;m++)e[m]*=4*Math.PI/k;return e}console.error("ERROR: SH: cubemap must be synced to CPU")}}}}());Object.assign(pc,function(){return{paraboloidFromCubemap:function(e,b,a,c){var d=pc.shaderChunks,d=d.createShaderFromCode(e,d.fullscreenQuadVS,(b.fixCubemapSeams?d.fixCubemapSeamsStretchPS:d.fixCubemapSeamsNonePS)+d.genParaboloidPS,"genParaboloid"),f=e.scope.resolve("source"),g=e.scope.resolve("params"),l=new pc.Vec4,h=b.width,p=b.rgbm,k=b.format,h=2*Math.max(h,8),h=new pc.Texture(e,{rgbm:p,format:k,width:2*h,height:h,mipmaps:!1});h.name="paraboloid";p=new pc.RenderTarget(e,h,{depth:!1});l.x=a;l.y=
|
|
c?-1:1;f.setValue(b);g.setValue(l.data);pc.drawQuadWithShader(e,p,d);return h},generateDpAtlas:function(e,b,a){var c,d;d=new pc.Vec4;var f=new pc.Vec4,g=4*b[0].width,l=pc.shaderChunks,l=l.createShaderFromCode(e,l.fullscreenQuadVS,l.dpAtlasQuadPS,"dpAtlasQuad"),h=e.scope.resolve("source"),p=e.scope.resolve("params"),k=new pc.Texture(e,{rgbm:b[0].rgbm,format:b[0].format,width:g,height:g,mipmaps:!1});k.name="paraboloid";for(var n=new pc.RenderTarget(e,k,{depth:!1}),q=(g+2)/g-1,m=0;6>m;m++){c=pc.paraboloidFromCubemap(e,
|
|
b[m],m,a);h.setValue(c);c=d;var r=m;c.x=.5*pc.math.clamp(r-2,0,1);var r=r-6*c.x,t=1-c.x;c.y=Math.min(.5*r,.75)*t+c.x;c.z=(1-.5*pc.math.clamp(r,0,1))*t;c.w=.5*c.z;c=1/c.z;f.x=c*q;f.y=2*f.x;f.x+=1;f.y+=1;p.setValue(f.data);d.x*=g;d.y*=g;d.z*=g;d.w*=g;pc.drawQuadWithShader(e,n,l,d)}return k}}}());pc.shaderChunks.TBNPS="void getTBN() {\n dTBN = mat3(normalize(dTangentW), normalize(dBinormalW), normalize(dVertexNormalW));\n}\n";pc.shaderChunks.TBNderivativePS="// http://www.thetenthplanet.de/archives/1180\nvoid getTBN() {\n vec2 uv = $UV;\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx( vPositionW );\n vec3 dp2 = dFdy( vPositionW );\n vec2 duv1 = dFdx( uv );\n vec2 duv2 = dFdy( uv );\n // solve the linear system\n vec3 dp2perp = cross( dp2, dVertexNormalW );\n vec3 dp1perp = cross( dVertexNormalW, dp1 );\n vec3 T = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 B = dp2perp * duv1.y + dp1perp * duv2.y;\n // construct a scale-invariant frame\n float invmax = 1.0 / sqrt( max( dot(T,T), dot(B,B) ) );\n dTBN = mat3( T * invmax, B * invmax, dVertexNormalW );\n}\n";
|
|
pc.shaderChunks.TBNfastPS="void getTBN() {\n dTBN = mat3(dTangentW, dBinormalW, dVertexNormalW);\n}\n";pc.shaderChunks.alphaTestPS="uniform float alpha_ref;\nvoid alphaTest(float a) {\n if (a < alpha_ref) discard;\n}\n";pc.shaderChunks.ambientConstantPS="\nvoid addAmbient() {\n dDiffuseLight += light_globalAmbient;\n}\n";pc.shaderChunks.ambientPrefilteredCubePS="#ifndef PMREM4\n#define PMREM4\nuniform samplerCube texture_prefilteredCubeMap4;\n#endif\nvoid addAmbient() {\n vec3 fixedReflDir = fixSeamsStatic(dNormalW, 1.0 - 1.0 / 4.0);\n fixedReflDir.x *= -1.0;\n dDiffuseLight += processEnvironment($DECODE(textureCube(texture_prefilteredCubeMap4, fixedReflDir)).rgb);\n}\n";
|
|
pc.shaderChunks.ambientPrefilteredCubeLodPS="#ifndef PMREM4\n#define PMREM4\n#extension GL_EXT_shader_texture_lod : enable\nuniform samplerCube texture_prefilteredCubeMap128;\n#endif\nvoid addAmbient() {\n vec3 fixedReflDir = fixSeamsStatic(dNormalW, 1.0 - 1.0 / 4.0);\n fixedReflDir.x *= -1.0;\n dDiffuseLight += processEnvironment($DECODE( textureCubeLodEXT(texture_prefilteredCubeMap128, fixedReflDir, 5.0) ).rgb);\n}\n";pc.shaderChunks.ambientSHPS="uniform vec3 ambientSH[9];\nvoid addAmbient() {\n vec3 n = dNormalW;\n vec3 color =\n ambientSH[0] +\n ambientSH[1] * n.x +\n ambientSH[2] * n.y +\n ambientSH[3] * n.z +\n ambientSH[4] * n.x * n.z +\n ambientSH[5] * n.z * n.y +\n ambientSH[6] * n.y * n.x +\n ambientSH[7] * (3.0 * n.z * n.z - 1.0) +\n ambientSH[8] * (n.x * n.x - n.y * n.y);\n dDiffuseLight += processEnvironment(max(color, vec3(0.0)));\n}\n";
|
|
pc.shaderChunks.aoPS="#ifdef MAPTEXTURE\nuniform sampler2D texture_aoMap;\n#endif\nvoid applyAO() {\n dAo = 1.0;\n #ifdef MAPTEXTURE\n dAo *= texture2D(texture_aoMap, $UV).$CH;\n #endif\n #ifdef MAPVERTEX\n dAo *= saturate(vVertexColor.$VC);\n #endif\n dDiffuseLight *= dAo;\n}\n";pc.shaderChunks.aoSpecOccPS="uniform float material_occludeSpecularIntensity;\nvoid occludeSpecular() {\n // approximated specular occlusion from AO\n float specPow = exp2(dGlossiness * 11.0);\n // http://research.tri-ace.com/Data/cedec2011_RealtimePBR_Implementation_e.pptx\n float specOcc = saturate(pow(dot(dNormalW, dViewDirW) + dAo, 0.01*specPow) - 1.0 + dAo);\n specOcc = mix(1.0, specOcc, material_occludeSpecularIntensity);\n dSpecularLight *= specOcc;\n dReflection *= specOcc;\n}\n";
|
|
pc.shaderChunks.aoSpecOccConstPS="void occludeSpecular() {\n // approximated specular occlusion from AO\n float specPow = exp2(dGlossiness * 11.0);\n // http://research.tri-ace.com/Data/cedec2011_RealtimePBR_Implementation_e.pptx\n float specOcc = saturate(pow(dot(dNormalW, dViewDirW) + dAo, 0.01*specPow) - 1.0 + dAo);\n dSpecularLight *= specOcc;\n dReflection *= specOcc;\n}\n";pc.shaderChunks.aoSpecOccConstSimplePS="void occludeSpecular() {\n float specOcc = dAo;\n dSpecularLight *= specOcc;\n dReflection *= specOcc;\n}\n";
|
|
pc.shaderChunks.aoSpecOccSimplePS="uniform float material_occludeSpecularIntensity;\nvoid occludeSpecular() {\n float specOcc = mix(1.0, dAo, material_occludeSpecularIntensity);\n dSpecularLight *= specOcc;\n dReflection *= specOcc;\n}\n";pc.shaderChunks.bakeDirLmEndPS="\n vec4 dirLm = texture2D(texture_dirLightMap, vUv1);\n if (bakeDir > 0.5) {\n if (dAtten > 0.00001) {\n dirLm.xyz = dirLm.xyz * 2.0 - vec3(1.0);\n dAtten = saturate(dAtten);\n gl_FragColor.rgb = normalize(dLightDirNormW.xyz*dAtten + dirLm.xyz*dirLm.w) * 0.5 + vec3(0.5);\n gl_FragColor.a = dirLm.w + dAtten;\n gl_FragColor.a = max(gl_FragColor.a, 1.0 / 255.0);\n } else {\n gl_FragColor = dirLm;\n }\n } else {\n gl_FragColor.rgb = dirLm.xyz;\n gl_FragColor.a = max(dirLm.w, dAtten > 0.00001? (1.0/255.0) : 0.0);\n }\n";
|
|
pc.shaderChunks.bakeLmEndPS="\ngl_FragColor.rgb = dDiffuseLight;\ngl_FragColor.rgb = pow(gl_FragColor.rgb, vec3(0.5));\ngl_FragColor.rgb /= 8.0;\ngl_FragColor.a = clamp( max( max( gl_FragColor.r, gl_FragColor.g ), max( gl_FragColor.b, 1.0 / 255.0 ) ), 0.0,1.0 );\ngl_FragColor.a = ceil(gl_FragColor.a * 255.0) / 255.0;\ngl_FragColor.rgb /= gl_FragColor.a;\n";pc.shaderChunks.basePS="\nuniform vec3 view_position;\nuniform vec3 light_globalAmbient;\nfloat square(float x) {\n return x*x;\n}\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\nvec3 saturate(vec3 x) {\n return clamp(x, vec3(0.0), vec3(1.0));\n}\n";
|
|
pc.shaderChunks.baseVS="\nattribute vec3 vertex_position;\nattribute vec3 vertex_normal;\nattribute vec4 vertex_tangent;\nattribute vec2 vertex_texCoord0;\nattribute vec2 vertex_texCoord1;\nattribute vec4 vertex_color;\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\nuniform mat3 matrix_normal;\nvec3 dPositionW;\nmat4 dModelMatrix;\nmat3 dNormalMatrix;\nvec3 dLightPosW;\nvec3 dLightDirNormW;\nvec3 dNormalW;\n";pc.shaderChunks.baseNineSlicedPS="#define NINESLICED\nvarying vec2 vMask;\nvarying vec2 vTiledUv;\nuniform mediump vec4 innerOffset;\nuniform mediump vec2 outerScale;\nuniform mediump vec4 atlasRect;\nvec2 nineSlicedUv;\n";
|
|
pc.shaderChunks.baseNineSlicedVS="#define NINESLICED\nvarying vec2 vMask;\nvarying vec2 vTiledUv;\nuniform mediump vec4 innerOffset;\nuniform mediump vec2 outerScale;\nuniform mediump vec4 atlasRect;\n";pc.shaderChunks.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";pc.shaderChunks.biasConstPS="#define SHADOWBIAS\nfloat getShadowBias(float resolution, float maxBias) {\n return maxBias;\n}\n";
|
|
pc.shaderChunks.blurVSMPS="\nvarying vec2 vUv0;\nuniform sampler2D source;\nuniform vec2 pixelOffset;\n#ifdef GAUSS\nuniform float weight[SAMPLES];\n#endif\n#ifdef PACKED\nfloat decodeFloatRG(vec2 rg) {\n return rg.y*(1.0/255.0) + rg.x;\n}\nvec2 encodeFloatRG( float v ) {\n vec2 enc = vec2(1.0, 255.0) * v;\n enc = fract(enc);\n enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n return enc;\n}\n#endif\nvoid main(void) {\n vec3 moments = vec3(0.0);\n vec2 uv = vUv0 - pixelOffset * (float(SAMPLES) * 0.5);\n for(int i=0; i<SAMPLES; i++) {\n vec4 c = texture2D(source, uv + pixelOffset * float(i));\n #ifdef PACKED\n c.xy = vec2(decodeFloatRG(c.xy), decodeFloatRG(c.zw));\n #endif\n #ifdef GAUSS\n moments += c.xyz * weight[i];\n #else\n moments += c.xyz;\n #endif\n }\n #ifndef GAUSS\n moments /= float(SAMPLES);\n #endif\n #ifdef PACKED\n gl_FragColor = vec4(encodeFloatRG(moments.x), encodeFloatRG(moments.y));\n #else\n gl_FragColor = vec4(moments.x, moments.y, moments.z, 1.0);\n #endif\n}\n";
|
|
pc.shaderChunks.combineDiffusePS="vec3 combineColor() {\n return dAlbedo * dDiffuseLight;\n}\n";pc.shaderChunks.combineDiffuseSpecularPS="vec3 combineColor() {\n return mix(dAlbedo * dDiffuseLight, dSpecularLight + dReflection.rgb * dReflection.a, dSpecularity);\n}\n";pc.shaderChunks.combineDiffuseSpecularNoConservePS="vec3 combineColor() {\n return dAlbedo * dDiffuseLight + (dSpecularLight + dReflection.rgb * dReflection.a) * dSpecularity;\n}\n";
|
|
pc.shaderChunks.combineDiffuseSpecularNoReflPS="vec3 combineColor() {\n return dAlbedo * dDiffuseLight + dSpecularLight * dSpecularity;\n}\n";pc.shaderChunks.combineDiffuseSpecularNoReflSeparateAmbientPS="uniform vec3 material_ambient;\nvec3 combineColor() {\n return (dDiffuseLight - light_globalAmbient) * dAlbedo + dSpecularLight * dSpecularity + material_ambient * light_globalAmbient;\n}\n";pc.shaderChunks.combineDiffuseSpecularOldPS="vec3 combineColor() {\n return mix(dAlbedo * dDiffuseLight + dSpecularLight * dSpecularity, dReflection.rgb, dReflection.a);\n}\n";
|
|
pc.shaderChunks.cookiePS="vec4 getCookie2D(sampler2D tex, mat4 transform, float intensity) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n return mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);\n}\nvec4 getCookie2DClip(sampler2D tex, mat4 transform, float intensity) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n if (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 return mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);\n}\nvec4 getCookie2DXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n projPos.xy += cookieOffset;\n vec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);\n return mix(vec4(1.0), texture2D(tex, uv), intensity);\n}\nvec4 getCookie2DClipXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n projPos.xy += cookieOffset;\n if (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 vec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);\n return mix(vec4(1.0), texture2D(tex, uv), intensity);\n}\nvec4 getCookieCube(samplerCube tex, mat4 transform, float intensity) {\n return mix(vec4(1.0), textureCube(tex, dLightDirNormW * mat3(transform)), intensity);\n}\n";
|
|
pc.shaderChunks.cubeMapProjectBoxPS="uniform vec3 envBoxMin, envBoxMax;\nvec3 cubeMapProject(vec3 nrdir) {\n vec3 rbmax = (envBoxMax - vPositionW) / nrdir;\n vec3 rbmin = (envBoxMin - vPositionW) / nrdir;\n vec3 rbminmax;\n rbminmax.x = nrdir.x>0.0? rbmax.x : rbmin.x;\n rbminmax.y = nrdir.y>0.0? rbmax.y : rbmin.y;\n rbminmax.z = nrdir.z>0.0? rbmax.z : rbmin.z;\n float fa = min(min(rbminmax.x, rbminmax.y), rbminmax.z);\n vec3 posonbox = vPositionW + nrdir * fa;\n vec3 envBoxPos = (envBoxMin + envBoxMax) * 0.5;\n return posonbox - envBoxPos;\n}\n";
|
|
pc.shaderChunks.cubeMapProjectNonePS="vec3 cubeMapProject(vec3 dir) {\n return dir;\n}\n";pc.shaderChunks.diffusePS="#ifdef MAPCOLOR\nuniform vec3 material_diffuse;\n#endif\n#ifdef MAPTEXTURE\nuniform sampler2D texture_diffuseMap;\n#endif\nvoid getAlbedo() {\n dAlbedo = vec3(1.0);\n #ifdef MAPCOLOR\n dAlbedo *= material_diffuse.rgb;\n #endif\n #ifdef MAPTEXTURE\n dAlbedo *= texture2DSRGB(texture_diffuseMap, $UV).$CH;\n #endif\n #ifdef MAPVERTEX\n dAlbedo *= gammaCorrectInput(saturate(vVertexColor.$VC));\n #endif\n}\n";
|
|
pc.shaderChunks.dilatePS="varying vec2 vUv0;\nuniform sampler2D source;\nuniform vec2 pixelOffset;\nvoid main(void) {\n vec4 c = texture2D(source, vUv0);\n c = c.a>0.0? c : texture2D(source, vUv0 - pixelOffset);\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(0, -pixelOffset.y));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(pixelOffset.x, -pixelOffset.y));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(-pixelOffset.x, 0));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(pixelOffset.x, 0));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(-pixelOffset.x, pixelOffset.y));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(0, pixelOffset.y));\n c = c.a>0.0? c : texture2D(source, vUv0 + pixelOffset);\n gl_FragColor = c;\n}\n";
|
|
pc.shaderChunks.dpAtlasQuadPS="varying vec2 vUv0;\nuniform sampler2D source;\nuniform vec4 params;\nvoid main(void) {\n vec2 uv = vUv0;\n uv = uv * 2.0 - vec2(1.0);\n uv *= params.xy;\n uv = uv * 0.5 + 0.5;\n gl_FragColor = texture2D(source, uv);\n}\n";pc.shaderChunks.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 vec3 emission = vec3(1.0);\n #ifdef MAPFLOAT\n emission *= material_emissiveIntensity;\n #endif\n #ifdef MAPCOLOR\n emission *= material_emissive;\n #endif\n #ifdef MAPTEXTURE\n emission *= $texture2DSAMPLE(texture_emissiveMap, $UV).$CH;\n #endif\n #ifdef MAPVERTEX\n emission *= gammaCorrectInput(saturate(vVertexColor.$VC));\n #endif\n return emission;\n}\n";
|
|
pc.shaderChunks.endPS=" gl_FragColor.rgb = combineColor();\n gl_FragColor.rgb += getEmission();\n gl_FragColor.rgb = addFog(gl_FragColor.rgb);\n #ifndef HDR\n gl_FragColor.rgb = toneMap(gl_FragColor.rgb);\n gl_FragColor.rgb = gammaCorrectOutput(gl_FragColor.rgb);\n #endif\n";pc.shaderChunks.envConstPS="vec3 processEnvironment(vec3 color) {\n return color;\n}\n";pc.shaderChunks.envMultiplyPS="uniform float skyboxIntensity;\nvec3 processEnvironment(vec3 color) {\n return color * skyboxIntensity;\n}\n";
|
|
pc.shaderChunks.extensionPS="";pc.shaderChunks.extensionVS="\n";pc.shaderChunks.falloffInvSquaredPS="float getFalloffInvSquared(float lightRadius) {\n float sqrDist = dot(dLightDirW, dLightDirW);\n float falloff = 1.0 / (sqrDist + 1.0);\n float invRadius = 1.0 / lightRadius;\n falloff *= 16.0;\n falloff *= square( saturate( 1.0 - square( sqrDist * square(invRadius) ) ) );\n return falloff;\n}\n";pc.shaderChunks.falloffLinearPS="float getFalloffLinear(float lightRadius) {\n float d = length(dLightDirW);\n return max(((lightRadius - d) / lightRadius), 0.0);\n}\n";
|
|
pc.shaderChunks.fixCubemapSeamsNonePS="vec3 fixSeams(vec3 vec, float mipmapIndex) {\n return vec;\n}\nvec3 fixSeams(vec3 vec) {\n return vec;\n}\nvec3 fixSeamsStatic(vec3 vec, float invRecMipSize) {\n return vec;\n}\n";pc.shaderChunks.fixCubemapSeamsStretchPS="vec3 fixSeams(vec3 vec, float mipmapIndex) {\n float scale = 1.0 - exp2(mipmapIndex) / 128.0;\n float M = max(max(abs(vec.x), abs(vec.y)), abs(vec.z));\n if (abs(vec.x) != M) vec.x *= scale;\n if (abs(vec.y) != M) vec.y *= scale;\n if (abs(vec.z) != M) vec.z *= scale;\n return vec;\n}\nvec3 fixSeams(vec3 vec) {\n float scale = 1.0 - 1.0 / 128.0;\n float M = max(max(abs(vec.x), abs(vec.y)), abs(vec.z));\n if (abs(vec.x) != M) vec.x *= scale;\n if (abs(vec.y) != M) vec.y *= scale;\n if (abs(vec.z) != M) vec.z *= scale;\n return vec;\n}\nvec3 fixSeamsStatic(vec3 vec, float invRecMipSize) {\n float scale = invRecMipSize;\n float M = max(max(abs(vec.x), abs(vec.y)), abs(vec.z));\n if (abs(vec.x) != M) vec.x *= scale;\n if (abs(vec.y) != M) vec.y *= scale;\n if (abs(vec.z) != M) vec.z *= scale;\n return vec;\n}\n";
|
|
pc.shaderChunks.fogExpPS="uniform vec3 fog_color;\nuniform float fog_density;\nvec3 addFog(vec3 color) {\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n float fogFactor = exp(-depth * fog_density);\n fogFactor = clamp(fogFactor, 0.0, 1.0);\n return mix(fog_color, color, fogFactor);\n}\n";pc.shaderChunks.fogExp2PS="uniform vec3 fog_color;\nuniform float fog_density;\nvec3 addFog(vec3 color) {\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n float fogFactor = exp(-depth * depth * fog_density * fog_density);\n fogFactor = clamp(fogFactor, 0.0, 1.0);\n return mix(fog_color, color, fogFactor);\n}\n";
|
|
pc.shaderChunks.fogLinearPS="uniform vec3 fog_color;\nuniform float fog_start;\nuniform float fog_end;\nvec3 addFog(vec3 color) {\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n float fogFactor = (fog_end - depth) / (fog_end - fog_start);\n fogFactor = clamp(fogFactor, 0.0, 1.0);\n fogFactor = gammaCorrectInput(fogFactor);\n return mix(fog_color, color, fogFactor);\n}\n";pc.shaderChunks.fogNonePS="vec3 addFog(vec3 color) {\n return color;\n}\n";
|
|
pc.shaderChunks.fresnelSchlickPS="// Schlick's approximation\nuniform float material_fresnelFactor; // unused\nvoid getFresnel() {\n float fresnel = 1.0 - max(dot(dNormalW, dViewDirW), 0.0);\n float fresnel2 = fresnel * fresnel;\n fresnel *= fresnel2 * fresnel2;\n fresnel *= dGlossiness * dGlossiness;\n dSpecularity = dSpecularity + (1.0 - dSpecularity) * fresnel;\n}\n";pc.shaderChunks.fullscreenQuadPS="varying vec2 vUv0;\nuniform sampler2D source;\nvoid main(void) {\n gl_FragColor = texture2D(source, vUv0);\n}\n";
|
|
pc.shaderChunks.fullscreenQuadVS="attribute vec2 vertex_position;\nvarying vec2 vUv0;\nvoid main(void)\n{\n gl_Position = vec4(vertex_position, 0.5, 1.0);\n vUv0 = vertex_position.xy*0.5+0.5;\n}\n";pc.shaderChunks.gamma1_0PS="vec4 texture2DSRGB(sampler2D tex, vec2 uv) {\n return texture2D(tex, uv);\n}\nvec4 texture2DSRGB(sampler2D tex, vec2 uv, float bias) {\n return texture2D(tex, uv, bias);\n}\nvec4 textureCubeSRGB(samplerCube tex, vec3 uvw) {\n return textureCube(tex, uvw);\n}\nvec3 gammaCorrectOutput(vec3 color) {\n return color;\n}\nvec3 gammaCorrectInput(vec3 color) {\n return color;\n}\nfloat gammaCorrectInput(float color) {\n return color;\n}\nvec4 gammaCorrectInput(vec4 color) {\n return color;\n}\n";
|
|
pc.shaderChunks.gamma2_2PS="vec3 gammaCorrectInput(vec3 color) {\n return pow(color, vec3(2.2));\n}\nfloat gammaCorrectInput(float color) {\n return pow(color, 2.2);\n}\nvec4 gammaCorrectInput(vec4 color) {\n return vec4(pow(color.rgb, vec3(2.2)), color.a);\n}\nvec4 texture2DSRGB(sampler2D tex, vec2 uv) {\n vec4 rgba = texture2D(tex, uv);\n rgba.rgb = gammaCorrectInput(rgba.rgb);\n return rgba;\n}\nvec4 texture2DSRGB(sampler2D tex, vec2 uv, float bias) {\n vec4 rgba = texture2D(tex, uv, bias);\n rgba.rgb = gammaCorrectInput(rgba.rgb);\n return rgba;\n}\nvec4 textureCubeSRGB(samplerCube tex, vec3 uvw) {\n vec4 rgba = textureCube(tex, uvw);\n rgba.rgb = gammaCorrectInput(rgba.rgb);\n return rgba;\n}\nvec3 gammaCorrectOutput(vec3 color) {\n#ifdef HDR\n return color;\n#else\n color += vec3(0.0000001);\n return pow(color, vec3(0.45));\n#endif\n}\n";
|
|
pc.shaderChunks.genParaboloidPS="varying vec2 vUv0;\nuniform samplerCube source;\nuniform vec4 params; // x = mip\nvoid main(void) {\n vec2 uv = vUv0;\n float side = uv.x < 0.5? 1.0 : -1.0;\n vec2 tc;\n tc.x = fract(uv.x * 2.0) * 2.0 - 1.0;\n tc.y = uv.y * 2.0 - 1.0;\n // scale projection a bit to have a little overlap for filtering\n const float scale = 1.1;\n tc *= scale;\n vec3 dir;\n dir.y = (dot(tc, tc) - 1.0) * side; // from 1.0 center to 0.0 borders quadratically\n dir.xz = tc * -2.0;\n dir.x *= -side * params.y; // flip original cubemap x instead of doing it at runtime\n dir = fixSeams(dir, params.x);\n vec4 color = textureCube(source, dir, -100.0);\n gl_FragColor = color;\n}\n";
|
|
pc.shaderChunks.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";pc.shaderChunks.gles3VS="#define attribute in\n#define varying out\n#define texture2D texture\n#define GL2\n#define VERTEXSHADER\n";
|
|
pc.shaderChunks.glossPS="#ifdef MAPFLOAT\nuniform float material_shininess;\n#endif\n#ifdef MAPTEXTURE\nuniform sampler2D texture_glossMap;\n#endif\nvoid getGlossiness() {\n dGlossiness = 1.0;\n #ifdef MAPFLOAT\n dGlossiness *= material_shininess;\n #endif\n #ifdef MAPTEXTURE\n dGlossiness *= texture2D(texture_glossMap, $UV).$CH;\n #endif\n #ifdef MAPVERTEX\n dGlossiness *= saturate(vVertexColor.$VC);\n #endif\n dGlossiness += 0.0000001;\n}\n";
|
|
pc.shaderChunks.instancingVS="\nattribute vec4 instance_line1;\nattribute vec4 instance_line2;\nattribute vec4 instance_line3;\nattribute vec4 instance_line4;\n";pc.shaderChunks.lightDiffuseLambertPS="float getLightDiffuse() {\n return max(dot(dNormalW, -dLightDirNormW), 0.0);\n}\n";pc.shaderChunks.lightDirPointPS="void getLightDirPoint(vec3 lightPosW) {\n dLightDirW = vPositionW - lightPosW;\n dLightDirNormW = normalize(dLightDirW);\n dLightPosW = lightPosW;\n}\n";
|
|
pc.shaderChunks.lightSpecularBlinnPS="// Energy-conserving (hopefully) Blinn-Phong\nfloat getLightSpecular() {\n vec3 h = normalize( -dLightDirNormW + dViewDirW );\n float nh = max( dot( h, dNormalW ), 0.0 );\n float specPow = exp2(dGlossiness * 11.0); // glossiness is linear, power is not; 0 - 2048\n specPow = antiAliasGlossiness(specPow);\n // Hack: On Mac OS X, calling pow with zero for the exponent generates hideous artifacts so bias up a little\n specPow = max(specPow, 0.0001);\n return pow(nh, specPow) * (specPow + 2.0) / 8.0;\n}\n";
|
|
pc.shaderChunks.lightSpecularPhongPS="float getLightSpecular() {\n float specPow = dGlossiness;\n specPow = antiAliasGlossiness(specPow);\n // Hack: On Mac OS X, calling pow with zero for the exponent generates hideous artifacts so bias up a little\n return pow(max(dot(dReflDirW, -dLightDirNormW), 0.0), specPow + 0.0001);\n}\n";pc.shaderChunks.lightmapDirPS="uniform sampler2D texture_lightMap;\nuniform sampler2D texture_dirLightMap;\nvoid addLightMap() {\n vec3 color = $texture2DSAMPLE(texture_lightMap, $UV).$CH;\n vec4 dir = texture2D(texture_dirLightMap, $UV);\n if (dot(dir.xyz,vec3(1.0)) < 0.00001) {\n dDiffuseLight += color;\n return;\n }\n dLightDirNormW = normalize(dir.xyz * 2.0 - vec3(1.0));\n float vlight = saturate(dot(dLightDirNormW, -dVertexNormalW));\n float flight = saturate(dot(dLightDirNormW, -dNormalW));\n float nlight = (flight / max(vlight,0.01)) * 0.5;\n dDiffuseLight += color * nlight * 2.0;\n}\nvoid addDirLightMap() {\n vec4 dir = texture2D(texture_dirLightMap, $UV);\n if (dot(dir.xyz,vec3(1.0)) < 0.00001) return;\n vec3 color = $texture2DSAMPLE(texture_lightMap, $UV).$CH;\n dLightDirNormW = normalize(dir.xyz * 2.0 - vec3(1.0));\n dSpecularLight += vec3(getLightSpecular()) * color;\n}\n";
|
|
pc.shaderChunks.lightmapSinglePS="#ifdef MAPTEXTURE\nuniform sampler2D texture_lightMap;\n#endif\nvoid addLightMap() {\n vec3 lm = vec3(1.0);\n #ifdef MAPTEXTURE\n lm *= $texture2DSAMPLE(texture_lightMap, $UV).$CH;\n #endif\n #ifdef MAPVERTEX\n lm *= saturate(vVertexColor.$VC);\n #endif\n \n dDiffuseLight += lm;\n}\n";pc.shaderChunks.lightmapSingleVertPS="void addLightMap() {\n dDiffuseLight += saturate(vVertexColor.$CH);\n}\n";pc.shaderChunks.metalnessPS="void processMetalness(float metalness) {\n const float dielectricF0 = 0.04;\n dSpecularity = mix(vec3(dielectricF0), dAlbedo, metalness);\n dAlbedo *= 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 float metalness = 1.0;\n #ifdef MAPFLOAT\n metalness *= material_metalness;\n #endif\n #ifdef MAPTEXTURE\n metalness *= texture2D(texture_metalnessMap, $UV).$CH;\n #endif\n #ifdef MAPVERTEX\n metalness *= saturate(vVertexColor.$VC);\n #endif\n processMetalness(metalness);\n}\n";
|
|
pc.shaderChunks.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 return max(min(r, g), min(max(r, g), b));\n}\nfloat map (float min, float max, float v) {\n return (v - min) / (max - min);\n}\nuniform float font_sdfIntensity; // intensity is used to boost the value read from the SDF, 0 is no boost, 1.0 is max boost\nuniform float font_pxrange; // the number of pixels between inside and outside the font in SDF\nuniform float font_textureWidth; // the width of the texture atlas\nuniform vec4 outline_color;\nuniform float outline_thickness;\nuniform vec4 shadow_color;\nuniform vec2 shadow_offset;\nvec4 applyMsdf(vec4 color) {\n // sample the field\n vec3 tsample = texture2D(texture_msdfMap, vUv0).rgb;\n vec2 uvShdw = vUv0 - shadow_offset;\n vec3 ssample = texture2D(texture_msdfMap, uvShdw).rgb;\n // get the signed distance value\n float sigDist = median(tsample.r, tsample.g, tsample.b);\n float sigDistShdw = median(ssample.r, ssample.g, ssample.b);\n #ifdef USE_FWIDTH\n // smoothing depends on size of texture on screen\n vec2 w = fwidth(vUv0);\n float smoothing = clamp(w.x * font_textureWidth / font_pxrange, 0.0, 0.5);\n #else\n float font_size = 16.0; // TODO fix this\n // smoothing gets smaller as the font size gets bigger\n // don't have fwidth we can approximate from font size, this doesn't account for scaling\n // so a big font scaled down will be wrong...\n float smoothing = clamp(font_pxrange / font_size, 0.0, 0.5);\n #endif\n float mapMin = 0.05;\n float mapMax = clamp(1.0 - font_sdfIntensity, mapMin, 1.0);\n // remap to a smaller range (used on smaller font sizes)\n float sigDistInner = map(mapMin, mapMax, sigDist);\n float sigDistOutline = map(mapMin, mapMax, sigDist + outline_thickness);\n sigDistShdw = map(mapMin, mapMax, sigDistShdw + outline_thickness);\n float center = 0.5;\n // calculate smoothing and use to generate opacity\n float inside = smoothstep(center-smoothing, center+smoothing, sigDistInner);\n float outline = smoothstep(center-smoothing, center+smoothing, sigDistOutline);\n float shadow = smoothstep(center-smoothing, center+smoothing, sigDistShdw);\n vec4 tcolor = (outline > inside) ? outline * vec4(outline_color.a * outline_color.rgb, outline_color.a) : vec4(0.0);\n tcolor = mix(tcolor, color, inside);\n vec4 scolor = (shadow > outline) ? shadow * vec4(shadow_color.a * shadow_color.rgb, shadow_color.a) : tcolor;\n tcolor = mix(scolor, tcolor, outline);\n \n return tcolor;\n}";
|
|
pc.shaderChunks.normalVS="vec3 getNormal() {\n #ifdef SKIN\n dNormalMatrix = mat3(dModelMatrix[0].xyz, dModelMatrix[1].xyz, dModelMatrix[2].xyz);\n #elif defined(INSTANCING)\n dNormalMatrix = mat3(instance_line1.xyz, instance_line2.xyz, instance_line3.xyz);\n #else\n dNormalMatrix = matrix_normal;\n #endif\n return normalize(dNormalMatrix * vertex_normal);\n}\n";pc.shaderChunks.normalInstancedVS="vec3 getNormal() {\n dNormalMatrix = mat3(instance_line1.xyz, instance_line2.xyz, instance_line3.xyz);\n return normalize(dNormalMatrix * vertex_normal);\n}\n";
|
|
pc.shaderChunks.normalMapPS="uniform sampler2D texture_normalMap;\nuniform float material_bumpiness;\nvoid getNormal() {\n vec3 normalMap = unpackNormal(texture2D(texture_normalMap, $UV));\n dNormalMap = normalMap;\n dNormalW = dTBN * normalMap;\n}\n";pc.shaderChunks.normalMapFloatPS="uniform sampler2D texture_normalMap;\nuniform float material_bumpiness;\nvoid getNormal() {\n vec3 normalMap = unpackNormal(texture2D(texture_normalMap, $UV));\n dNormalMap = normalMap;\n normalMap = normalize(mix(vec3(0.0, 0.0, 1.0), normalMap, material_bumpiness));\n dNormalW = dTBN * normalMap;\n}\n";
|
|
pc.shaderChunks.normalMapFloatTBNfastPS="uniform sampler2D texture_normalMap;\nuniform float material_bumpiness;\nvoid getNormal() {\n vec3 normalMap = unpackNormal(texture2D(texture_normalMap, $UV));\n dNormalMap = normalMap;\n normalMap = mix(vec3(0.0, 0.0, 1.0), normalMap, material_bumpiness);\n dNormalW = normalize(dTBN * normalMap);\n}\n";pc.shaderChunks.normalSkinnedVS="vec3 getNormal() {\n dNormalMatrix = mat3(dModelMatrix[0].xyz, dModelMatrix[1].xyz, dModelMatrix[2].xyz);\n return normalize(dNormalMatrix * vertex_normal);\n}\n";
|
|
pc.shaderChunks.normalVertexPS="void getNormal() {\n dNormalW = normalize(dVertexNormalW);\n}\n";pc.shaderChunks.normalXYPS="vec3 unpackNormal(vec4 nmap) {\n vec3 normal;\n normal.xy = nmap.wy * 2.0 - 1.0;\n normal.z = sqrt(1.0 - saturate(dot(normal.xy, normal.xy)));\n return normal;\n}\n";pc.shaderChunks.normalXYZPS="vec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\n";pc.shaderChunks.opacityPS="#ifdef MAPFLOAT\nuniform float material_opacity;\n#endif\n#ifdef MAPTEXTURE\nuniform sampler2D texture_opacityMap;\n#endif\nvoid getOpacity() {\n dAlpha = 1.0;\n #ifdef MAPFLOAT\n dAlpha *= material_opacity;\n #endif\n #ifdef MAPTEXTURE\n dAlpha *= texture2D(texture_opacityMap, $UV).$CH;\n #endif\n #ifdef MAPVERTEX\n dAlpha *= saturate(vVertexColor.$VC);\n #endif\n}\n";
|
|
pc.shaderChunks.outputAlphaPS="gl_FragColor.a = dAlpha;\n";pc.shaderChunks.outputAlphaOpaquePS="gl_FragColor.a = 1.0;\n";pc.shaderChunks.outputAlphaPremulPS="gl_FragColor.rgb *= dAlpha;\ngl_FragColor.a = dAlpha;\n";pc.shaderChunks.outputCubemapPS="varying vec2 vUv0;\nuniform samplerCube source;\nuniform vec4 params;\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\nvec4 encodeRGBM(vec4 color) { // modified RGBM\n color.rgb = pow(color.rgb, vec3(0.5));\n color.rgb *= 1.0 / 8.0;\n color.a = saturate( max( max( color.r, color.g ), max( color.b, 1.0 / 255.0 ) ) );\n color.a = ceil(color.a * 255.0) / 255.0;\n color.rgb /= color.a;\n return color;\n}\nvoid main(void) {\n vec2 st = vUv0 * 2.0 - 1.0;\n float face = params.x;\n vec3 vec;\n if (face==0.0) {\n vec = vec3(1, -st.y, -st.x);\n } else if (face==1.0) {\n vec = vec3(-1, -st.y, st.x);\n } else if (face==2.0) {\n vec = vec3(st.x, 1, st.y);\n } else if (face==3.0) {\n vec = vec3(st.x, -1, -st.y);\n } else if (face==4.0) {\n vec = vec3(st.x, -st.y, 1);\n } else {\n vec = vec3(-st.x, -st.y, -1);\n }\n gl_FragColor = textureCube(source, vec);\n if (params.w >= 2.0) gl_FragColor = encodeRGBM(gl_FragColor);\n}\n";
|
|
pc.shaderChunks.outputTex2DPS="varying vec2 vUv0;\nuniform sampler2D source;\nvoid main(void) {\n gl_FragColor = texture2D(source, vUv0);\n}\n";pc.shaderChunks.packDepthPS="// Packing a float in GLSL with multiplication and mod\n// http://blog.gradientstudios.com/2012/08/23/shadow-map-improvement\nvec4 packFloat(float depth) {\n const vec4 bit_shift = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);\n const vec4 bit_mask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);\n // combination of mod and multiplication and division works better\n vec4 res = mod(depth * bit_shift * vec4(255), vec4(256) ) / vec4(255);\n res -= res.xxyz * bit_mask;\n return res;\n}\n";
|
|
pc.shaderChunks.packDepthMaskPS="vec4 packFloat(float depth) {\n const vec4 bit_shift = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);\n const vec4 bit_mask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);\n // combination of mod and multiplication and division works better\n vec4 res = mod(depth * bit_shift * vec4(255), vec4(256) ) / vec4(255);\n res.x = 0.0;\n res -= res.xxyz * bit_mask;\n return res;\n}\n";pc.shaderChunks.parallaxPS="uniform sampler2D texture_heightMap;\nuniform float material_heightMapFactor;\nvoid getParallax() {\n float parallaxScale = material_heightMapFactor;\n float height = texture2D(texture_heightMap, $UV).$CH;\n height = height * parallaxScale - parallaxScale*0.5;\n vec3 viewDirT = dViewDirW * dTBN;\n viewDirT.z += 0.42;\n dUvOffset = height * (viewDirT.xy / viewDirT.z);\n}\n";
|
|
pc.shaderChunks.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 return clamp(x, 0.0, 1.0);\n}\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n const vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n float depth = dot(rgbaDepth, bitShift);\n return depth;\n}\n#endif\nvoid main(void) {\n vec4 tex = texture2DSRGB(colorMap, texCoordsAlphaLife.xy);\n vec4 ramp = texture2DSRGB(colorParam, vec2(texCoordsAlphaLife.w, 0.0));\n ramp.rgb *= colorMult;\n ramp.a += texCoordsAlphaLife.z;\n vec3 rgb = tex.rgb * ramp.rgb;\n float a = tex.a * ramp.a;\n";
|
|
pc.shaderChunks.particleVS="\nvec3 unpack3NFloats(float src) {\n float r = fract(src);\n float g = fract(src * 256.0);\n float b = fract(src * 65536.0);\n return vec3(r, g, b);\n}\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\nvec4 tex1Dlod_lerp(sampler2D tex, vec2 tc) {\n return mix( texture2D(tex,tc), texture2D(tex,tc + graphSampleSize), fract(tc.x*graphNumSamples) );\n}\nvec4 tex1Dlod_lerp(sampler2D tex, vec2 tc, out vec3 w) {\n vec4 a = texture2D(tex,tc);\n vec4 b = texture2D(tex,tc + graphSampleSize);\n float c = fract(tc.x*graphNumSamples);\n vec3 unpackedA = unpack3NFloats(a.w);\n vec3 unpackedB = unpack3NFloats(b.w);\n w = mix(unpackedA, unpackedB, c);\n return mix(a, b, c);\n}\nvec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix) {\n float c = cos(pRotation);\n float s = sin(pRotation);\n mat2 m = mat2(c, -s, s, c);\n rotMatrix = m;\n return m * quadXY;\n}\nvec3 billboard(vec3 InstanceCoords, vec2 quadXY) {\n vec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y;\n return pos;\n}\nvec3 customFace(vec3 InstanceCoords, vec2 quadXY) {\n vec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y;\n return pos;\n}\nvoid main(void) {\n vec3 meshLocalPos = particle_vertexData.xyz;\n float id = floor(particle_vertexData.w);\n float rndFactor = fract(sin(id + 1.0 + seed));\n vec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));\n float uv = id / numParticlesPot;\n readInput(uv);\n#ifdef LOCAL_SPACE\n inVel = mat3(matrix_model) * inVel;\n#endif\n vec2 velocityV = normalize((mat3(matrix_view) * inVel).xy); // should be removed by compiler if align/stretch is not used\n float particleLifetime = lifetime;\n if (inLife <= 0.0 || inLife > particleLifetime || !inShow) meshLocalPos = vec3(0.0);\n vec2 quadXY = meshLocalPos.xy;\n float nlife = clamp(inLife / particleLifetime, 0.0, 1.0);\n vec3 paramDiv;\n vec4 params = tex1Dlod_lerp(internalTex2, vec2(nlife, 0), paramDiv);\n float scale = params.y;\n float scaleDiv = paramDiv.x;\n float alphaDiv = paramDiv.z;\n scale += (scaleDiv * 2.0 - 1.0) * scaleDivMult * fract(rndFactor*10000.0);\n#ifndef USE_MESH\n texCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);\n#else\n texCoordsAlphaLife = vec4(particle_uv, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);\n#endif\n vec3 particlePos = inPos;\n vec3 particlePosMoved = vec3(0.0);\n mat2 rotMatrix;\n";
|
|
pc.shaderChunks.particleAnimFrameClampVS="\n float animFrame = min(floor(texCoordsAlphaLife.w * animTexParams.z), animTexParams.w);\n";pc.shaderChunks.particleAnimFrameLoopVS="\n float animFrame = floor(texCoordsAlphaLife.w * animTexParams.z);\n";pc.shaderChunks.particleAnimTexVS="\n float atlasX = animFrame * animTexParams.x;\n float atlasY = 1.0 - floor(atlasX) * animTexParams.y;\n atlasX = fract(atlasX);\n texCoordsAlphaLife.xy *= animTexParams.xy;\n texCoordsAlphaLife.xy += vec2(atlasX, atlasY);\n";
|
|
pc.shaderChunks.particleInputFloatPS="void readInput(float uv) {\n vec4 tex = texture2D(particleTexIN, vec2(uv, 0.25));\n vec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.75));\n inPos = tex.xyz;\n inVel = tex2.xyz;\n inAngle = (tex.w < 0.0? -tex.w : tex.w) - 1000.0;\n inShow = tex.w >= 0.0;\n inLife = tex2.w;\n}\n";pc.shaderChunks.particleInputRgba8PS="//RG=X, BA=Y\n//RG=Z, BA=A\n//RGB=V, A=visMode\n//RGBA=life\n#define PI2 6.283185307179586\nuniform vec3 inBoundsSize;\nuniform vec3 inBoundsCenter;\nuniform float maxVel;\nfloat decodeFloatRG(vec2 rg) {\n return 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 vec4 tex0 = texture2D(particleTexIN, vec2(uv, 0.125));\n vec4 tex1 = texture2D(particleTexIN, vec2(uv, 0.375));\n vec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.625));\n vec4 tex3 = texture2D(particleTexIN, vec2(uv, 0.875));\n inPos = vec3(decodeFloatRG(tex0.rg), decodeFloatRG(tex0.ba), decodeFloatRG(tex1.rg));\n inPos = (inPos - vec3(0.5)) * inBoundsSize + inBoundsCenter;\n inVel = tex2.xyz;\n inVel = (inVel - vec3(0.5)) * maxVel;\n inAngle = decodeFloatRG(tex1.ba) * PI2;\n inShow = tex2.a > 0.5;\n inLife = decodeFloatRGBA(tex3);\n float maxNegLife = max(lifetime, (numParticles - 1.0) * (rate+rateDiv));\n float maxPosLife = lifetime+1.0;\n inLife = inLife * (maxNegLife + maxPosLife) - maxNegLife;\n}\n";
|
|
pc.shaderChunks.particleOutputFloatPS="void writeOutput() {\n if (gl_FragCoord.y<1.0) {\n gl_FragColor = vec4(outPos, (outAngle + 1000.0) * visMode);\n } else {\n gl_FragColor = vec4(outVel, outLife);\n }\n}\n";pc.shaderChunks.particleOutputRgba8PS="uniform vec3 outBoundsMul;\nuniform vec3 outBoundsAdd;\nvec2 encodeFloatRG( float v ) {\n vec2 enc = vec2(1.0, 255.0) * v;\n enc = fract(enc);\n enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n return enc;\n}\nvec4 encodeFloatRGBA( float v ) {\n vec4 enc = vec4(1.0, 255.0, 65025.0, 160581375.0) * v;\n enc = fract(enc);\n enc -= enc.yzww * vec4(1.0/255.0,1.0/255.0,1.0/255.0,0.0);\n return enc;\n}\nvoid writeOutput() {\n //outPos = (outPos - outBoundsCenter) / outBoundsSize + vec3(0.5);\n outPos = outPos * outBoundsMul + outBoundsAdd;\n outAngle = fract(outAngle / PI2);\n outVel = (outVel / maxVel) + vec3(0.5); // TODO: mul\n float maxNegLife = max(lifetime, (numParticles - 1.0) * (rate+rateDiv));\n float maxPosLife = lifetime+1.0;\n outLife = (outLife + maxNegLife) / (maxNegLife + maxPosLife);\n if (gl_FragCoord.y < 1.0) {\n gl_FragColor = vec4(encodeFloatRG(outPos.x), encodeFloatRG(outPos.y));\n } else if (gl_FragCoord.y < 2.0) {\n gl_FragColor = vec4(encodeFloatRG(outPos.z), encodeFloatRG(outAngle));\n } else if (gl_FragCoord.y < 3.0) {\n gl_FragColor = vec4(outVel, visMode*0.5+0.5);\n } else {\n gl_FragColor = encodeFloatRGBA(outLife);\n }\n}\n";
|
|
pc.shaderChunks.particleUpdaterAABBPS="uniform mat3 spawnBounds;\nuniform vec3 spawnPosInnerRatio;\nvec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {\n vec3 pos = inBounds - vec3(0.5);\n vec3 posAbs = abs(pos);\n vec3 maxPos = vec3(max(posAbs.x, max(posAbs.y, posAbs.z)));\n vec3 edge = maxPos + (vec3(0.5) - maxPos) * spawnPosInnerRatio;\n //pos = edge * mix(2.0 * pos, sign(pos), equal(maxPos, posAbs));\n pos.x = edge.x * (maxPos.x == posAbs.x ? sign(pos.x) : 2.0 * pos.x);\n pos.y = edge.y * (maxPos.y == posAbs.y ? sign(pos.y) : 2.0 * pos.y);\n pos.z = edge.z * (maxPos.z == posAbs.z ? sign(pos.z) : 2.0 * pos.z);\n#ifndef LOCAL_SPACE\n return emitterPos + spawnBounds * pos;\n#else\n return spawnBounds * pos;\n#endif\n}\nvoid addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {\n localVelocity -= vec3(0, 0, initialVelocity);\n}\n";
|
|
pc.shaderChunks.particleUpdaterEndPS="\n writeOutput();\n}\n";pc.shaderChunks.particleUpdaterInitPS="varying vec2 vUv0;\nuniform sampler2D particleTexIN;\nuniform sampler2D internalTex0;\nuniform sampler2D internalTex1;\nuniform sampler2D internalTex2;\nuniform 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";
|
|
pc.shaderChunks.particleUpdaterNoRespawnPS=" if (outLife >= lifetime) {\n outLife -= max(lifetime, (numParticles - 1.0) * particleRate);\n visMode = -1.0;\n }\n";pc.shaderChunks.particleUpdaterOnStopPS=" visMode = outLife < 0.0? -1.0: visMode;\n";pc.shaderChunks.particleUpdaterRespawnPS=" if (outLife >= lifetime) {\n outLife -= max(lifetime, (numParticles - 1.0) * particleRate);\n visMode = 1.0;\n }\n visMode = outLife < 0.0? 1.0: visMode;\n";
|
|
pc.shaderChunks.particleUpdaterSpherePS="uniform float spawnBoundsSphere;\nuniform float spawnBoundsSphereInnerRatio;\nvec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {\n float rnd4 = fract(rndFactor * 1000.0);\n vec3 norm = normalize(inBounds.xyz - vec3(0.5));\n float r = rnd4 * (1.0 - spawnBoundsSphereInnerRatio) + spawnBoundsSphereInnerRatio;\n#ifndef LOCAL_SPACE\n return emitterPos + norm * r * spawnBoundsSphere;\n#else\n return norm * r * spawnBoundsSphere;\n#endif\n}\nvoid addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {\n localVelocity += normalize(inBounds - vec3(0.5)) * initialVelocity;\n}\n";
|
|
pc.shaderChunks.particleUpdaterStartPS="float saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\nvec3 unpack3NFloats(float src) {\n float r = fract(src);\n float g = fract(src * 256.0);\n float b = fract(src * 65536.0);\n return vec3(r, g, b);\n}\nvec3 tex1Dlod_lerp(sampler2D tex, vec2 tc, out vec3 w) {\n vec4 a = texture2D(tex, tc);\n vec4 b = texture2D(tex, tc + graphSampleSize);\n float c = fract(tc.x * graphNumSamples);\n vec3 unpackedA = unpack3NFloats(a.w);\n vec3 unpackedB = unpack3NFloats(b.w);\n w = mix(unpackedA, unpackedB, c);\n return mix(a.xyz, b.xyz, c);\n}\n#define HASHSCALE4 vec4(1031, .1030, .0973, .1099)\nvec4 hash41(float p) {\n vec4 p4 = fract(vec4(p) * HASHSCALE4);\n p4 += dot(p4, p4.wzxy+19.19);\n return 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{\n if (gl_FragCoord.x > numParticles) discard;\n readInput(vUv0.x);\n visMode = inShow? 1.0 : -1.0;\n vec4 rndFactor = hash41(gl_FragCoord.x + seed);\n float particleRate = rate + rateDiv * rndFactor.x;\n outLife = inLife + delta;\n float nlife = clamp(outLife / lifetime, 0.0, 1.0);\n vec3 localVelocityDiv;\n vec3 velocityDiv;\n vec3 paramDiv;\n vec3 localVelocity = tex1Dlod_lerp(internalTex0, vec2(nlife, 0), localVelocityDiv);\n vec3 velocity = tex1Dlod_lerp(internalTex1, vec2(nlife, 0), velocityDiv);\n vec3 params = tex1Dlod_lerp(internalTex2, vec2(nlife, 0), paramDiv);\n float rotSpeed = params.x;\n float rotSpeedDiv = paramDiv.y;\n vec3 radialParams = tex1Dlod_lerp(internalTex3, vec2(nlife, 0), paramDiv);\n float radialSpeed = radialParams.x;\n float radialSpeedDiv = radialParams.y;\n#ifndef LOCAL_SPACE\n vec3 radialVel = radialSpeed * normalize(inPos - emitterPos);\n#else\n vec3 radialVel = radialSpeed * normalize(inPos);\n#endif\n radialVel += (radialSpeedDiv * vec3(2.0) - vec3(1.0)) * radialSpeedDivMult * rndFactor.xyz;\n localVelocity += (localVelocityDiv * vec3(2.0) - vec3(1.0)) * localVelocityDivMult * rndFactor.xyz;\n velocity += (velocityDiv * vec3(2.0) - vec3(1.0)) * velocityDivMult * rndFactor.xyz;\n rotSpeed += (rotSpeedDiv * 2.0 - 1.0) * rotSpeedDivMult * rndFactor.y;\n addInitialVelocity(localVelocity, rndFactor.xyz);\n#ifndef LOCAL_SPACE\n outVel = emitterMatrix * localVelocity + (radialVel + velocity) * emitterScale;\n#else\n outVel = (localVelocity + radialVel) / emitterScale + emitterMatrixInv * velocity;\n#endif\n outPos = inPos + outVel * delta;\n outAngle = inAngle + rotSpeed * delta;\n bool respawn = outLife <= 0.0 || outLife >= lifetime;\n outPos = respawn? calcSpawnPosition(rndFactor.xyz, rndFactor.x) : outPos;\n outAngle = respawn? mix(startAngle, startAngle2, rndFactor.x) : outAngle;\n outVel = respawn? vec3(0.0) : outVel;\n";
|
|
pc.shaderChunks.particle_TBNVS="\n mat3 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 ParticleMat = mat3(-matrix_viewInverse[0].xyz, -matrix_viewInverse[1].xyz, matrix_viewInverse[2].xyz) * rot3;\n";pc.shaderChunks.particle_billboardVS="\n quadXY = rotate(quadXY, inAngle, rotMatrix);\n vec3 localPos = billboard(particlePos, quadXY);\n";pc.shaderChunks.particle_blendAddPS="\n rgb *= saturate(gammaCorrectInput(a));\n if ((rgb.r + rgb.g + rgb.b) < 0.000001) discard;\n";
|
|
pc.shaderChunks.particle_blendMultiplyPS="\n rgb = mix(vec3(1.0), rgb, vec3(a));\n if (rgb.r + rgb.g + rgb.b > 2.99) discard;\n";pc.shaderChunks.particle_blendNormalPS="\n if (a < 0.01) discard;\n";pc.shaderChunks.particle_cpuVS="attribute vec4 particle_vertexData; // XYZ = world pos, W = life\nattribute vec4 particle_vertexData2; // X = angle, Y = scale, Z = alpha, W = velocity.x\nattribute vec4 particle_vertexData3; // XYZ = particle local pos, W = velocity.y\n#ifndef USE_MESH\n#define VDATA4TYPE vec2\n#else\n#define VDATA4TYPE vec4\n#endif\nattribute VDATA4TYPE particle_vertexData4; // VDATA4TYPE depends on useMesh property. Start with X = velocity.z, Y = particle ID and for mesh particles proceeds with Z = mesh UV.x, W = mesh UV.y\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;\n//uniform float graphSampleSize;\n//uniform float graphNumSamples;\nuniform vec3 wrapBounds, emitterScale, faceTangent, faceBinorm;\nuniform sampler2D texLifeAndSourcePosOUT;\nuniform sampler2D internalTex0;\nuniform sampler2D internalTex1;\nuniform sampler2D internalTex2;\nuniform vec3 emitterPos;\nvarying vec4 texCoordsAlphaLife;\nvec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix)\n{\n float c = cos(pRotation);\n float s = sin(pRotation);\n //vec4 rotationMatrix = vec4(c, -s, s, c);\n mat2 m = mat2(c, -s, s, c);\n rotMatrix = m;\n return m * quadXY;\n}\nvec3 billboard(vec3 InstanceCoords, vec2 quadXY)\n{\n vec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y;\n return pos;\n}\nvec3 customFace(vec3 InstanceCoords, vec2 quadXY)\n{\n vec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y;\n return pos;\n}\nvoid main(void)\n{\n vec3 particlePos = particle_vertexData.xyz;\n vec3 inPos = particlePos;\n vec3 vertPos = particle_vertexData3.xyz;\n vec3 inVel = vec3(particle_vertexData2.w, particle_vertexData3.w, particle_vertexData4.x);\n#ifdef LOCAL_SPACE\n inVel = mat3(matrix_model) * inVel;\n#endif\n vec2 velocityV = normalize((mat3(matrix_view) * inVel).xy); // should be removed by compiler if align/stretch is not used\n vec2 quadXY = vertPos.xy;\n \n#ifndef USE_MESH\n texCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, particle_vertexData2.z, particle_vertexData.w);\n#else\n texCoordsAlphaLife = vec4(particle_vertexData4.zw, particle_vertexData2.z, particle_vertexData.w);\n#endif\n mat2 rotMatrix;\n float inAngle = particle_vertexData2.x;\n vec3 particlePosMoved = vec3(0.0);\n vec3 meshLocalPos = particle_vertexData3.xyz;\n";
|
|
pc.shaderChunks.particle_cpu_endVS="\n localPos *= particle_vertexData2.y * emitterScale;\n localPos += particlePos;\n gl_Position = matrix_viewProjection * vec4(localPos, 1.0);\n";pc.shaderChunks.particle_customFaceVS="\n quadXY = rotate(quadXY, inAngle, rotMatrix);\n vec3 localPos = customFace(particlePos, quadXY);\n";pc.shaderChunks.particle_endPS=" rgb = addFog(rgb);\n rgb = toneMap(rgb);\n rgb = gammaCorrectOutput(rgb);\n gl_FragColor = vec4(rgb, a);\n}\n";
|
|
pc.shaderChunks.particle_endVS="\n localPos *= scale * emitterScale;\n localPos += particlePos;\n gl_Position = matrix_viewProjection * vec4(localPos.xyz, 1.0);\n";pc.shaderChunks.particle_halflambertPS="\n vec3 negNormal = normal*0.5+0.5;\n vec3 posNormal = -normal*0.5+0.5;\n negNormal *= negNormal;\n posNormal *= posNormal;\n";pc.shaderChunks.particle_initVS="attribute vec4 particle_vertexData; // XYZ = particle position, W = particle ID + random factor\n#ifdef USE_MESH\nattribute vec2 particle_uv; // mesh 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 sampler2D internalTex0;\nuniform sampler2D internalTex1;\nuniform 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";
|
|
pc.shaderChunks.particle_lambertPS="\n vec3 negNormal = max(normal, vec3(0.0));\n vec3 posNormal = max(-normal, vec3(0.0));\n";pc.shaderChunks.particle_lightingPS="\n vec3 light = negNormal.x*lightCube[0] + posNormal.x*lightCube[1] +\n negNormal.y*lightCube[2] + posNormal.y*lightCube[3] +\n negNormal.z*lightCube[4] + posNormal.z*lightCube[5];\n rgb *= light;\n";pc.shaderChunks.particle_localShiftVS=" particlePos = (matrix_model * vec4(particlePos, 1.0)).xyz;\n";
|
|
pc.shaderChunks.particle_meshVS="\n vec3 localPos = meshLocalPos;\n localPos.xy = rotate(localPos.xy, inAngle, rotMatrix);\n localPos.yz = rotate(localPos.yz, inAngle, rotMatrix);\n billboard(particlePos, quadXY);\n";pc.shaderChunks.particle_normalVS="\n Normal = normalize(localPos + matrix_viewInverse[2].xyz);\n";pc.shaderChunks.particle_normalMapPS="\n vec3 normalMap = normalize( texture2D(normalMap, texCoordsAlphaLife.xy).xyz * 2.0 - 1.0 );\n vec3 normal = ParticleMat * normalMap;\n";
|
|
pc.shaderChunks.particle_pointAlongVS=" inAngle = atan(velocityV.x, velocityV.y); // not the fastest way, but easier to plug in; TODO: create rot matrix right from vectors\n";pc.shaderChunks.particle_softPS="\n float depth = getLinearScreenDepth();\n float particleDepth = vDepth;\n float depthDiff = saturate(abs(particleDepth - depth) * softening);\n a *= depthDiff;\n";pc.shaderChunks.particle_softVS="\n vDepth = getLinearDepth(localPos);\n";pc.shaderChunks.particle_stretchVS=" vec3 moveDir = inVel * stretch;\n vec3 posPrev = particlePos - moveDir;\n posPrev += particlePosMoved;\n vec2 centerToVertexV = normalize((mat3(matrix_view) * localPos).xy);\n float interpolation = dot(-velocityV, centerToVertexV) * 0.5 + 0.5;\n particlePos = mix(particlePos, posPrev, interpolation);\n";
|
|
pc.shaderChunks.particle_wrapVS="\n vec3 origParticlePos = particlePos;\n particlePos -= matrix_model[3].xyz;\n particlePos = mod(particlePos, wrapBounds) - wrapBounds * 0.5;\n particlePos += matrix_model[3].xyz;\n particlePosMoved = particlePos - origParticlePos;\n";pc.shaderChunks.precisionTestPS="void main(void) {\n gl_FragColor = vec4(2147483648.0);\n}\n";pc.shaderChunks.precisionTest2PS="uniform sampler2D source;\nvec4 packFloat(float depth) {\n const vec4 bit_shift = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);\n const vec4 bit_mask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);\n vec4 res = mod(depth * bit_shift * vec4(255), vec4(256) ) / vec4(255);\n res -= res.xxyz * bit_mask;\n return res;\n}\nvoid main(void) {\n float c = texture2D(source, vec2(0.0)).r;\n float diff = abs(c - 2147483648.0) / 2147483648.0;\n gl_FragColor = packFloat(diff);\n}\n";
|
|
pc.shaderChunks.prefilterCubemapPS="varying vec2 vUv0;\nuniform samplerCube source;\nuniform vec4 params;\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\nfloat rnd(vec2 uv) {\n return fract(sin(dot(uv, vec2(12.9898, 78.233) * 2.0)) * 43758.5453);\n}\nconst float PI = 3.14159265358979;\nvec3 hemisphereSample_cos(vec2 uv, mat3 vecSpace, vec3 cubeDir, float gloss) { // cos + lerped cone size (better than just lerped)\n float phi = uv.y * 2.0 * PI;\n float cosTheta = sqrt(1.0 - uv.x);\n float sinTheta = sqrt(1.0 - cosTheta * cosTheta);\n vec3 sampleDir = vec3(cos(phi) * sinTheta, sin(phi) * sinTheta, cosTheta);\n return normalize(mix(vecSpace * sampleDir, cubeDir, params.y));\n}\nvec3 hemisphereSample_phong(vec2 uv, mat3 vecSpace, vec3 cubeDir, float specPow) {\n float phi = uv.y * 2.0 * PI;\n float cosTheta = pow(1.0 - uv.x, 1.0 / (specPow + 1.0));\n float sinTheta = sqrt(1.0 - cosTheta * cosTheta);\n vec3 sampleDir = vec3(cos(phi) * sinTheta, sin(phi) * sinTheta, cosTheta);\n return vecSpace * sampleDir;\n}\nmat3 matrixFromVector(vec3 n) { // frisvad\n float a = 1.0 / (1.0 + n.z);\n float b = -n.x * n.y * a;\n vec3 b1 = vec3(1.0 - n.x * n.x * a, b, -n.x);\n vec3 b2 = vec3(b, 1.0 - n.y * n.y * a, -n.y);\n return mat3(b1, b2, n);\n}\nvec4 encodeRGBM(vec3 color) { // modified RGBM\n vec4 encoded;\n encoded.rgb = pow(color.rgb, vec3(0.5));\n encoded.rgb *= 1.0 / 8.0;\n encoded.a = saturate( max( max( encoded.r, encoded.g ), max( encoded.b, 1.0 / 255.0 ) ) );\n encoded.a = ceil(encoded.a * 255.0) / 255.0;\n encoded.rgb /= encoded.a;\n return encoded;\n}\nvoid main(void) {\n vec2 st = vUv0 * 2.0 - 1.0;\n if (params.w==1.0 || params.w==3.0) {\n st = 2.0 * floor(gl_FragCoord.xy) / (params.z - 1.0) - 1.0;\n }\n float face = params.x;\n vec3 vec;\n if (face==0.0) {\n vec = vec3(1, -st.y, -st.x);\n } else if (face==1.0) {\n vec = vec3(-1, -st.y, st.x);\n } else if (face==2.0) {\n vec = vec3(st.x, 1, st.y);\n } else if (face==3.0) {\n vec = vec3(st.x, -1, -st.y);\n } else if (face==4.0) {\n vec = vec3(st.x, -st.y, 1);\n } else {\n vec = vec3(-st.x, -st.y, -1);\n }\n mat3 vecSpace = matrixFromVector(normalize(vec));\n vec3 color = vec3(0.0);\n const int samples = $NUMSAMPLES;\n vec3 vect;\n for(int i=0; i<samples; i++) {\n float sini = sin(float(i));\n float cosi = cos(float(i));\n float rand = rnd(vec2(sini, cosi));\n vect = hemisphereSample_$METHOD(vec2(float(i) / float(samples), rand), vecSpace, vec, params.y);\n color += $textureCube(source, vect).rgb;\n }\n color /= float(samples);\n gl_FragColor = params.w < 2.0? vec4(color, 1.0) : encodeRGBM(color);\n}\n";
|
|
pc.shaderChunks.reflDirPS="void getReflDir() {\n dReflDirW = normalize(-reflect(dViewDirW, dNormalW));\n}\n";pc.shaderChunks.reflectionCubePS="uniform samplerCube texture_cubeMap;\nuniform float material_reflectivity;\nvoid addReflection() {\n vec3 lookupVec = fixSeams(cubeMapProject(dReflDirW));\n lookupVec.x *= -1.0;\n dReflection += vec4($textureCubeSAMPLE(texture_cubeMap, lookupVec).rgb, material_reflectivity);\n}\n";pc.shaderChunks.reflectionDpAtlasPS="uniform sampler2D texture_sphereMap;\nuniform float material_reflectivity;\nvec2 getDpAtlasUv(vec2 uv, float mip) {\n vec4 rect;\n float sx = saturate(mip - 2.0);\n rect.x = sx * 0.5;\n float t = mip - rect.x * 6.0;\n float i = 1.0 - rect.x;\n rect.y = min(t * 0.5, 0.75) * i + rect.x;\n float st = saturate(t);\n rect.z = (1.0 - st * 0.5) * i;\n rect.w = rect.z * 0.5;\n float rcRectZ = 1.0 / rect.z;\n float scaleFactor = 0.00390625 * rcRectZ; // 0.0078125 = (256 + 2) / 256 - 1, 0.00390625 same for 512\n vec2 scale = vec2(scaleFactor, scaleFactor * 2.0);\n uv = uv * (vec2(1.0) - scale) + scale * 0.5;\n uv = uv * rect.zw + rect.xy;\n return uv;\n}\nvoid addReflection() {\n vec3 reflDir = normalize(cubeMapProject(dReflDirW));\n // Convert vector to DP coords\n bool up = reflDir.y > 0.0;\n float scale = 0.90909090909090909090909090909091;// 1.0 / 1.1;\n vec3 reflDirWarp = reflDir.xzx * vec3(-0.25, 0.5, 0.25);\n float reflDirVer = abs(reflDir.y) + 1.0;\n reflDirWarp /= reflDirVer;\n reflDirWarp *= scale;\n reflDirWarp = vec3(0.75, 0.5, 0.25) - reflDirWarp;\n vec2 tc = up? reflDirWarp.xy : reflDirWarp.zy;\n float bias = saturate(1.0 - dGlossiness) * 5.0; // multiply by max mip level\n float mip = floor(bias);\n vec3 tex1 = $texture2DSAMPLE(texture_sphereMap, getDpAtlasUv(tc, mip)).rgb;\n mip = min(mip + 1.0, 5.0);\n vec3 tex2 = $texture2DSAMPLE(texture_sphereMap, getDpAtlasUv(tc, mip)).rgb;\n tex1 = mix(tex1, tex2, fract(bias));\n tex1 = processEnvironment(tex1);\n dReflection += vec4(tex1, material_reflectivity);\n}\n";
|
|
pc.shaderChunks.reflectionPrefilteredCubePS="uniform samplerCube texture_prefilteredCubeMap128;\nuniform samplerCube texture_prefilteredCubeMap64;\nuniform samplerCube texture_prefilteredCubeMap32;\nuniform samplerCube texture_prefilteredCubeMap16;\nuniform samplerCube texture_prefilteredCubeMap8;\n#ifndef PMREM4\n#define PMREM4\nuniform samplerCube texture_prefilteredCubeMap4;\n#endif\nuniform float material_reflectivity;\nvoid addReflection() {\n // Unfortunately, WebGL doesn't allow us using textureCubeLod. Therefore bunch of nasty workarounds is required.\n // We fix mip0 to 128x128, so code is rather static.\n // Mips smaller than 4x4 aren't great even for diffuse. Don't forget that we don't have bilinear filtering between different faces.\n float bias = saturate(1.0 - dGlossiness) * 5.0; // multiply by max mip level\n int index1 = int(bias);\n int index2 = int(min(bias + 1.0, 7.0));\n vec3 fixedReflDir = fixSeams(cubeMapProject(dReflDirW), bias);\n fixedReflDir.x *= -1.0;\n vec4 cubes[6];\n cubes[0] = textureCube(texture_prefilteredCubeMap128, fixedReflDir);\n cubes[1] = textureCube(texture_prefilteredCubeMap64, fixedReflDir);\n cubes[2] = textureCube(texture_prefilteredCubeMap32, fixedReflDir);\n cubes[3] = textureCube(texture_prefilteredCubeMap16, fixedReflDir);\n cubes[4] = textureCube(texture_prefilteredCubeMap8, fixedReflDir);\n cubes[5] = textureCube(texture_prefilteredCubeMap4, fixedReflDir);\n // Also we don't have dynamic indexing in PS, so...\n vec4 cube[2];\n for(int i = 0; i < 6; i++) {\n if (i == index1) {\n cube[0] = cubes[i];\n }\n if (i == index2) {\n cube[1] = cubes[i];\n }\n }\n // another variant\n /*if (index1==0){ cube[0]=cubes[0];\n }else if (index1==1){ cube[0]=cubes[1];\n }else if (index1==2){ cube[0]=cubes[2];\n }else if (index1==3){ cube[0]=cubes[3];\n }else if (index1==4){ cube[0]=cubes[4];\n }else if (index1==5){ cube[0]=cubes[5];}\n if (index2==0){ cube[1]=cubes[0];\n }else if (index2==1){ cube[1]=cubes[1];\n }else if (index2==2){ cube[1]=cubes[2];\n }else if (index2==3){ cube[1]=cubes[3];\n }else if (index2==4){ cube[1]=cubes[4];\n }else if (index2==5){ cube[1]=cubes[5];}*/\n vec4 cubeFinal = mix(cube[0], cube[1], fract(bias));\n vec3 refl = processEnvironment($DECODE(cubeFinal).rgb);\n dReflection += vec4(refl, material_reflectivity);\n}\n";
|
|
pc.shaderChunks.reflectionPrefilteredCubeLodPS="\n#ifndef PMREM4\n#define PMREM4\n#extension GL_EXT_shader_texture_lod : enable\nuniform samplerCube texture_prefilteredCubeMap128;\n#endif\nuniform float material_reflectivity;\nvoid addReflection() {\n float bias = saturate(1.0 - dGlossiness) * 5.0; // multiply by max mip level\n vec3 fixedReflDir = fixSeams(cubeMapProject(dReflDirW), bias);\n fixedReflDir.x *= -1.0;\n vec3 refl = processEnvironment($DECODE( textureCubeLodEXT(texture_prefilteredCubeMap128, fixedReflDir, bias) ).rgb);\n dReflection += vec4(refl, material_reflectivity);\n}\n";
|
|
pc.shaderChunks.reflectionSpherePS="#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nuniform sampler2D texture_sphereMap;\nuniform float material_reflectivity;\nvoid addReflection() {\n vec3 reflDirV = (mat3(matrix_view) * dReflDirW).xyz;\n float m = 2.0 * sqrt( dot(reflDirV.xy, reflDirV.xy) + (reflDirV.z+1.0)*(reflDirV.z+1.0) );\n vec2 sphereMapUv = reflDirV.xy / m + 0.5;\n dReflection += vec4($texture2DSAMPLE(texture_sphereMap, sphereMapUv).rgb, material_reflectivity);\n}\n";
|
|
pc.shaderChunks.reflectionSphereLowPS="uniform sampler2D texture_sphereMap;\nuniform float material_reflectivity;\nvoid addReflection() {\n vec3 reflDirV = vNormalV;\n vec2 sphereMapUv = reflDirV.xy * 0.5 + 0.5;\n dReflection += vec4($texture2DSAMPLE(texture_sphereMap, sphereMapUv).rgb, material_reflectivity);\n}\n";pc.shaderChunks.refractionPS="uniform float material_refraction, material_refractionIndex;\nvec3 refract2(vec3 viewVec, vec3 Normal, float IOR) {\n float vn = dot(viewVec, Normal);\n float k = 1.0 - IOR * IOR * (1.0 - vn * vn);\n vec3 refrVec = IOR * viewVec - (IOR * vn + sqrt(k)) * Normal;\n return refrVec;\n}\nvoid addRefraction() {\n // use same reflection code with refraction vector\n vec3 tmp = dReflDirW;\n vec4 tmp2 = dReflection;\n dReflection = vec4(0.0);\n dReflDirW = refract2(-dViewDirW, dNormalW, material_refractionIndex);\n addReflection();\n dDiffuseLight = mix(dDiffuseLight, dReflection.rgb * dAlbedo, material_refraction);\n dReflDirW = tmp;\n dReflection = tmp2;\n}\n";
|
|
pc.shaderChunks.rgbmPS="vec3 decodeRGBM(vec4 rgbm) {\n vec3 color = (8.0 * rgbm.a) * rgbm.rgb;\n return color * color;\n}\nvec3 texture2DRGBM(sampler2D tex, vec2 uv) {\n return decodeRGBM(texture2D(tex, uv));\n}\nvec3 textureCubeRGBM(samplerCube tex, vec3 uvw) {\n return decodeRGBM(textureCube(tex, uvw));\n}\n";pc.shaderChunks.screenDepthPS="uniform 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; // 1 / camera_far, camera_far, (1 - f / n) / 2, (1 + f / n) / 2\n#endif\n#ifdef GL2\n float linearizeDepth(float z) {\n z = z * 2.0 - 1.0;\n return 1.0 / (camera_params.z * z + camera_params.w);\n }\n#else\n #ifndef UNPACKFLOAT\n #define UNPACKFLOAT\n float unpackFloat(vec4 rgbaDepth) {\n const vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n return dot(rgbaDepth, bitShift);\n }\n #endif\n#endif\n// Retrieves rendered linear camera depth by UV\nfloat getLinearScreenDepth(vec2 uv) {\n #ifdef GL2\n return linearizeDepth(texture2D(uDepthMap, uv).r) * camera_params.y;\n #else\n return unpackFloat(texture2D(uDepthMap, uv)) * camera_params.y;\n #endif\n}\n#ifndef VERTEXSHADER\n// Retrieves rendered linear camera depth under the current pixel\nfloat getLinearScreenDepth() {\n vec2 uv = gl_FragCoord.xy * uScreenSize.zw;\n return getLinearScreenDepth(uv);\n}\n#endif\n// Generates linear camera depth for the given world position\nfloat getLinearDepth(vec3 pos) {\n return -(matrix_view * vec4(pos, 1.0)).z;\n}\n";
|
|
pc.shaderChunks.shadowCommonPS="void normalOffsetPointShadow(vec4 shadowParams) {\n float distScale = length(dLightDirW);\n vec3 wPos = vPositionW + dVertexNormalW * shadowParams.y * clamp(1.0 - dot(dVertexNormalW, -dLightDirNormW), 0.0, 1.0) * distScale; //0.02\n vec3 dir = wPos - dLightPosW;\n dLightDirW = dir;\n}\n";pc.shaderChunks.shadowCoordPS="void _getShadowCoordOrtho(mat4 shadowMatrix, vec3 shadowParams, vec3 wPos) {\n dShadowCoord = (shadowMatrix * vec4(wPos, 1.0)).xyz;\n dShadowCoord.z = saturate(dShadowCoord.z) - 0.0001;\n #ifdef SHADOWBIAS\n dShadowCoord.z += getShadowBias(shadowParams.x, shadowParams.z);\n #endif\n}\nvoid _getShadowCoordPersp(mat4 shadowMatrix, vec4 shadowParams, vec3 wPos) {\n vec4 projPos = shadowMatrix * vec4(wPos, 1.0);\n projPos.xy /= projPos.w;\n dShadowCoord.xy = projPos.xy;\n dShadowCoord.z = length(dLightDirW) * shadowParams.w;\n #ifdef SHADOWBIAS\n dShadowCoord.z += getShadowBias(shadowParams.x, shadowParams.z);\n #endif\n}\nvoid getShadowCoordOrtho(mat4 shadowMatrix, vec3 shadowParams) {\n _getShadowCoordOrtho(shadowMatrix, shadowParams, vPositionW);\n}\nvoid getShadowCoordPersp(mat4 shadowMatrix, vec4 shadowParams) {\n _getShadowCoordPersp(shadowMatrix, shadowParams, vPositionW);\n}\nvoid getShadowCoordPerspNormalOffset(mat4 shadowMatrix, vec4 shadowParams) {\n float distScale = abs(dot(vPositionW - dLightPosW, dLightDirNormW)); // fov?\n vec3 wPos = vPositionW + dVertexNormalW * shadowParams.y * clamp(1.0 - dot(dVertexNormalW, -dLightDirNormW), 0.0, 1.0) * distScale;\n _getShadowCoordPersp(shadowMatrix, shadowParams, wPos);\n}\nvoid getShadowCoordOrthoNormalOffset(mat4 shadowMatrix, vec3 shadowParams) {\n vec3 wPos = vPositionW + dVertexNormalW * shadowParams.y * clamp(1.0 - dot(dVertexNormalW, -dLightDirNormW), 0.0, 1.0); //0.08\n _getShadowCoordOrtho(shadowMatrix, shadowParams, wPos);\n}\n";
|
|
pc.shaderChunks.shadowCoordVS="void getLightDirPoint(vec3 lightPosW) {\n vec3 lightDirW = vPositionW - lightPosW;\n dLightDirNormW = normalize(lightDirW);\n dLightPosW = lightPosW;\n}\nvoid _getShadowCoordOrtho(mat4 shadowMatrix, vec3 shadowParams, vec3 wPos) {\n vec4 projPos = shadowMatrix * vec4(wPos, 1.0);\n vMainShadowUv = projPos;\n}\nvoid _getShadowCoordPersp(mat4 shadowMatrix, vec3 shadowParams, vec3 wPos) {\n vec4 projPos = shadowMatrix * vec4(wPos, 1.0);\n vMainShadowUv = projPos;\n}\nvoid getShadowCoordOrtho(mat4 shadowMatrix, vec3 shadowParams) {\n _getShadowCoordOrtho(shadowMatrix, shadowParams, vPositionW);\n}\nvoid getShadowCoordPersp(mat4 shadowMatrix, vec3 shadowParams) {\n _getShadowCoordPersp(shadowMatrix, shadowParams, vPositionW);\n}\nvoid getShadowCoordPerspNormalOffset(mat4 shadowMatrix, vec3 shadowParams) {\n float distScale = abs(dot(vPositionW - dLightPosW, dLightDirNormW)); // fov?\n vec3 wPos = vPositionW + dNormalW * shadowParams.y * clamp(1.0 - dot(dNormalW, -dLightDirNormW), 0.0, 1.0) * distScale;\n _getShadowCoordPersp(shadowMatrix, shadowParams, wPos);\n}\nvoid getShadowCoordOrthoNormalOffset(mat4 shadowMatrix, vec3 shadowParams) {\n vec3 wPos = vPositionW + dNormalW * shadowParams.y * clamp(1.0 - dot(dNormalW, -dLightDirNormW), 0.0, 1.0); //0.08\n _getShadowCoordOrtho(shadowMatrix, shadowParams, wPos);\n}\n";
|
|
pc.shaderChunks.shadowCoordPerspZbufferPS="void _getShadowCoordPerspZbuffer(mat4 shadowMatrix, vec4 shadowParams, vec3 wPos) {\n vec4 projPos = shadowMatrix * vec4(wPos, 1.0);\n projPos.xyz /= projPos.w;\n dShadowCoord = projPos.xyz;\n // depth bias is already applied on render\n}\nvoid getShadowCoordPerspZbufferNormalOffset(mat4 shadowMatrix, vec4 shadowParams) {\n float distScale = abs(dot(vPositionW - dLightPosW, dLightDirNormW)); // fov?\n vec3 wPos = vPositionW + dVertexNormalW * shadowParams.y * clamp(1.0 - dot(dVertexNormalW, -dLightDirNormW), 0.0, 1.0) * distScale;\n _getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, wPos);\n}\nvoid getShadowCoordPerspZbuffer(mat4 shadowMatrix, vec4 shadowParams) {\n _getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, vPositionW);\n}\n";
|
|
pc.shaderChunks.shadowEVSMPS="float VSM$(sampler2D tex, vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n vec3 moments = texture2D(tex, texCoords).xyz;\n return calculateEVSM(moments, Z, vsmBias, exponent);\n}\nfloat getShadowVSM$(sampler2D shadowMap, vec3 shadowParams, float exponent) {\n return VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, dShadowCoord.z, shadowParams.y, exponent);\n}\nfloat getShadowSpotVSM$(sampler2D shadowMap, vec4 shadowParams, float exponent) {\n return VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, length(dLightDirW) * shadowParams.w + shadowParams.z, shadowParams.y, exponent);\n}\n";
|
|
pc.shaderChunks.shadowEVSMnPS="float VSM$(sampler2D tex, vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n float pixelSize = 1.0 / resolution;\n texCoords -= vec2(pixelSize);\n vec3 s00 = texture2D(tex, texCoords).xyz;\n vec3 s10 = texture2D(tex, texCoords + vec2(pixelSize, 0)).xyz;\n vec3 s01 = texture2D(tex, texCoords + vec2(0, pixelSize)).xyz;\n vec3 s11 = texture2D(tex, texCoords + vec2(pixelSize)).xyz;\n vec2 fr = fract(texCoords * resolution);\n vec3 h0 = mix(s00, s10, fr.x);\n vec3 h1 = mix(s01, s11, fr.x);\n vec3 moments = mix(h0, h1, fr.y);\n return calculateEVSM(moments, Z, vsmBias, exponent);\n}\nfloat getShadowVSM$(sampler2D shadowMap, vec3 shadowParams, float exponent) {\n return VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, dShadowCoord.z, shadowParams.y, exponent);\n}\nfloat getShadowSpotVSM$(sampler2D shadowMap, vec4 shadowParams, float exponent) {\n return VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, length(dLightDirW) * shadowParams.w + shadowParams.z, shadowParams.y, exponent);\n}\n";
|
|
pc.shaderChunks.shadowStandardPS="vec3 lessThan2(vec3 a, vec3 b) {\n return clamp((b - a)*1000.0, 0.0, 1.0); // softer version\n}\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n const vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n return dot(rgbaDepth, bitShift);\n}\n#endif\n// ----- Direct/Spot Sampling -----\n#ifdef GL2\n float _getShadowPCF3x3(sampler2DShadow shadowMap, vec3 shadowParams) {\n float z = dShadowCoord.z;\n vec2 uv = dShadowCoord.xy * shadowParams.x; // 1 unit - 1 texel\n float shadowMapSizeInv = 1.0 / shadowParams.x;\n vec2 base_uv = floor(uv + 0.5);\n float s = (uv.x + 0.5 - base_uv.x);\n float t = (uv.y + 0.5 - base_uv.y);\n base_uv -= vec2(0.5);\n base_uv *= shadowMapSizeInv;\n float sum = 0.0;\n float uw0 = (3.0 - 2.0 * s);\n float uw1 = (1.0 + 2.0 * s);\n float u0 = (2.0 - s) / uw0 - 1.0;\n float u1 = s / uw1 + 1.0;\n float vw0 = (3.0 - 2.0 * t);\n float vw1 = (1.0 + 2.0 * t);\n float v0 = (2.0 - t) / vw0 - 1.0;\n float v1 = t / vw1 + 1.0;\n u0 = u0 * shadowMapSizeInv + base_uv.x;\n v0 = v0 * shadowMapSizeInv + base_uv.y;\n u1 = u1 * shadowMapSizeInv + base_uv.x;\n v1 = v1 * shadowMapSizeInv + base_uv.y;\n sum += uw0 * vw0 * texture(shadowMap, vec3(u0, v0, z));\n sum += uw1 * vw0 * texture(shadowMap, vec3(u1, v0, z));\n sum += uw0 * vw1 * texture(shadowMap, vec3(u0, v1, z));\n sum += uw1 * vw1 * texture(shadowMap, vec3(u1, v1, z));\n sum *= 1.0f / 16.0;\n return sum;\n }\n float getShadowPCF3x3(sampler2DShadow shadowMap, vec3 shadowParams) {\n return _getShadowPCF3x3(shadowMap, shadowParams);\n }\n float getShadowSpotPCF3x3(sampler2DShadow shadowMap, vec4 shadowParams) {\n return _getShadowPCF3x3(shadowMap, shadowParams.xyz);\n }\n#else\n float _xgetShadowPCF3x3(mat3 depthKernel, sampler2D shadowMap, vec3 shadowParams) {\n mat3 shadowKernel;\n vec3 shadowCoord = dShadowCoord;\n vec3 shadowZ = vec3(shadowCoord.z);\n shadowKernel[0] = vec3(greaterThan(depthKernel[0], shadowZ));\n shadowKernel[1] = vec3(greaterThan(depthKernel[1], shadowZ));\n shadowKernel[2] = vec3(greaterThan(depthKernel[2], shadowZ));\n vec2 fractionalCoord = fract( shadowCoord.xy * shadowParams.x );\n shadowKernel[0] = mix(shadowKernel[0], shadowKernel[1], fractionalCoord.x);\n shadowKernel[1] = mix(shadowKernel[1], shadowKernel[2], fractionalCoord.x);\n vec4 shadowValues;\n shadowValues.x = mix(shadowKernel[0][0], shadowKernel[0][1], fractionalCoord.y);\n shadowValues.y = mix(shadowKernel[0][1], shadowKernel[0][2], fractionalCoord.y);\n shadowValues.z = mix(shadowKernel[1][0], shadowKernel[1][1], fractionalCoord.y);\n shadowValues.w = mix(shadowKernel[1][1], shadowKernel[1][2], fractionalCoord.y);\n return dot( shadowValues, vec4( 1.0 ) ) * 0.25;\n }\n float _getShadowPCF3x3(sampler2D shadowMap, vec3 shadowParams) {\n vec3 shadowCoord = dShadowCoord;\n float xoffset = 1.0 / shadowParams.x; // 1/shadow map width\n float dx0 = -xoffset;\n float dx1 = xoffset;\n mat3 depthKernel;\n depthKernel[0][0] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx0, dx0)));\n depthKernel[0][1] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx0, 0.0)));\n depthKernel[0][2] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx0, dx1)));\n depthKernel[1][0] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(0.0, dx0)));\n depthKernel[1][1] = unpackFloat(texture2D(shadowMap, shadowCoord.xy));\n depthKernel[1][2] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(0.0, dx1)));\n depthKernel[2][0] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx1, dx0)));\n depthKernel[2][1] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx1, 0.0)));\n depthKernel[2][2] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx1, dx1)));\n return _xgetShadowPCF3x3(depthKernel, shadowMap, shadowParams);\n }\n float getShadowPCF3x3(sampler2D shadowMap, vec3 shadowParams) {\n return _getShadowPCF3x3(shadowMap, shadowParams);\n }\n float getShadowSpotPCF3x3(sampler2D shadowMap, vec4 shadowParams) {\n return _getShadowPCF3x3(shadowMap, shadowParams.xyz);\n }\n#endif\n// ----- Point Sampling -----\nfloat _getShadowPoint(samplerCube shadowMap, vec4 shadowParams, vec3 dir) {\n vec3 tc = normalize(dir);\n vec3 tcAbs = abs(tc);\n vec4 dirX = vec4(1,0,0, tc.x);\n vec4 dirY = vec4(0,1,0, tc.y);\n float majorAxisLength = tc.z;\n if ((tcAbs.x > tcAbs.y) && (tcAbs.x > tcAbs.z)) {\n dirX = vec4(0,0,1, tc.z);\n dirY = vec4(0,1,0, tc.y);\n majorAxisLength = tc.x;\n } else if ((tcAbs.y > tcAbs.x) && (tcAbs.y > tcAbs.z)) {\n dirX = vec4(1,0,0, tc.x);\n dirY = vec4(0,0,1, tc.z);\n majorAxisLength = tc.y;\n }\n float shadowParamsInFaceSpace = ((1.0/shadowParams.x) * 2.0) * abs(majorAxisLength);\n vec3 xoffset = (dirX.xyz * shadowParamsInFaceSpace);\n vec3 yoffset = (dirY.xyz * shadowParamsInFaceSpace);\n vec3 dx0 = -xoffset;\n vec3 dy0 = -yoffset;\n vec3 dx1 = xoffset;\n vec3 dy1 = yoffset;\n mat3 shadowKernel;\n mat3 depthKernel;\n depthKernel[0][0] = unpackFloat(textureCube(shadowMap, tc + dx0 + dy0));\n depthKernel[0][1] = unpackFloat(textureCube(shadowMap, tc + dx0));\n depthKernel[0][2] = unpackFloat(textureCube(shadowMap, tc + dx0 + dy1));\n depthKernel[1][0] = unpackFloat(textureCube(shadowMap, tc + dy0));\n depthKernel[1][1] = unpackFloat(textureCube(shadowMap, tc));\n depthKernel[1][2] = unpackFloat(textureCube(shadowMap, tc + dy1));\n depthKernel[2][0] = unpackFloat(textureCube(shadowMap, tc + dx1 + dy0));\n depthKernel[2][1] = unpackFloat(textureCube(shadowMap, tc + dx1));\n depthKernel[2][2] = unpackFloat(textureCube(shadowMap, tc + dx1 + dy1));\n vec3 shadowZ = vec3(length(dir) * shadowParams.w + shadowParams.z);\n shadowKernel[0] = vec3(lessThan2(depthKernel[0], shadowZ));\n shadowKernel[1] = vec3(lessThan2(depthKernel[1], shadowZ));\n shadowKernel[2] = vec3(lessThan2(depthKernel[2], shadowZ));\n vec2 uv = (vec2(dirX.w, dirY.w) / abs(majorAxisLength)) * 0.5;\n vec2 fractionalCoord = fract( uv * shadowParams.x );\n shadowKernel[0] = mix(shadowKernel[0], shadowKernel[1], fractionalCoord.x);\n shadowKernel[1] = mix(shadowKernel[1], shadowKernel[2], fractionalCoord.x);\n vec4 shadowValues;\n shadowValues.x = mix(shadowKernel[0][0], shadowKernel[0][1], fractionalCoord.y);\n shadowValues.y = mix(shadowKernel[0][1], shadowKernel[0][2], fractionalCoord.y);\n shadowValues.z = mix(shadowKernel[1][0], shadowKernel[1][1], fractionalCoord.y);\n shadowValues.w = mix(shadowKernel[1][1], shadowKernel[1][2], fractionalCoord.y);\n return 1.0 - dot( shadowValues, vec4( 1.0 ) ) * 0.25;\n}\nfloat getShadowPointPCF3x3(samplerCube shadowMap, vec4 shadowParams) {\n return _getShadowPoint(shadowMap, shadowParams, dLightDirW);\n}\n";
|
|
pc.shaderChunks.shadowStandardGL2PS="float _getShadowPCF5x5(sampler2DShadow shadowMap, vec3 shadowParams) {\n // http://the-witness.net/news/2013/09/shadow-mapping-summary-part-1/\n float z = dShadowCoord.z;\n vec2 uv = dShadowCoord.xy * shadowParams.x; // 1 unit - 1 texel\n float shadowMapSizeInv = 1.0 / shadowParams.x;\n vec2 base_uv = floor(uv + 0.5);\n float s = (uv.x + 0.5 - base_uv.x);\n float t = (uv.y + 0.5 - base_uv.y);\n base_uv -= vec2(0.5);\n base_uv *= shadowMapSizeInv;\n float uw0 = (4.0 - 3.0 * s);\n float uw1 = 7.0;\n float uw2 = (1.0 + 3.0 * s);\n float u0 = (3.0 - 2.0 * s) / uw0 - 2.0;\n float u1 = (3.0 + s) / uw1;\n float u2 = s / uw2 + 2.0;\n float vw0 = (4.0 - 3.0 * t);\n float vw1 = 7.0;\n float vw2 = (1.0 + 3.0 * t);\n float v0 = (3.0 - 2.0 * t) / vw0 - 2.0;\n float v1 = (3.0 + t) / vw1;\n float v2 = t / vw2 + 2.0;\n float sum = 0.0;\n u0 = u0 * shadowMapSizeInv + base_uv.x;\n v0 = v0 * shadowMapSizeInv + base_uv.y;\n u1 = u1 * shadowMapSizeInv + base_uv.x;\n v1 = v1 * shadowMapSizeInv + base_uv.y;\n u2 = u2 * shadowMapSizeInv + base_uv.x;\n v2 = v2 * shadowMapSizeInv + base_uv.y;\n sum += uw0 * vw0 * texture(shadowMap, vec3(u0, v0, z));\n sum += uw1 * vw0 * texture(shadowMap, vec3(u1, v0, z));\n sum += uw2 * vw0 * texture(shadowMap, vec3(u2, v0, z));\n sum += uw0 * vw1 * texture(shadowMap, vec3(u0, v1, z));\n sum += uw1 * vw1 * texture(shadowMap, vec3(u1, v1, z));\n sum += uw2 * vw1 * texture(shadowMap, vec3(u2, v1, z));\n sum += uw0 * vw2 * texture(shadowMap, vec3(u0, v2, z));\n sum += uw1 * vw2 * texture(shadowMap, vec3(u1, v2, z));\n sum += uw2 * vw2 * texture(shadowMap, vec3(u2, v2, z));\n sum *= 1.0f / 144.0;\n sum = gammaCorrectInput(sum); // gives softer gradient\n sum = saturate(sum);\n return sum;\n}\nfloat getShadowPCF5x5(sampler2DShadow shadowMap, vec3 shadowParams) {\n return _getShadowPCF5x5(shadowMap, shadowParams);\n}\nfloat getShadowSpotPCF5x5(sampler2DShadow shadowMap, vec4 shadowParams) {\n return _getShadowPCF5x5(shadowMap, shadowParams.xyz);\n}\n";
|
|
pc.shaderChunks.shadowStandardGL2VSPS="float getShadowPCF5x5VS(sampler2DShadow shadowMap, vec3 shadowParams) {\n dShadowCoord = vMainShadowUv.xyz;\n dShadowCoord.z = saturate(dShadowCoord.z) - 0.0001; // prevent going to dark after the far plane\n return _getShadowPCF5x5(shadowMap, shadowParams);\n}\n";pc.shaderChunks.shadowStandardVSPS="#ifdef GL2\n#define SHADOW_SAMPLERVS sampler2DShadow\n#else\n#define SHADOW_SAMPLERVS sampler2D\n#endif\nfloat getShadowPCF3x3VS(SHADOW_SAMPLERVS shadowMap, vec3 shadowParams) {\n dShadowCoord = vMainShadowUv.xyz;\n dShadowCoord.z = saturate(dShadowCoord.z) - 0.0001;\n #ifdef SHADOWBIAS\n dShadowCoord.z += getShadowBias(shadowParams.x, shadowParams.z);\n #endif\n return _getShadowPCF3x3(shadowMap, shadowParams);\n}\n";
|
|
pc.shaderChunks.shadowVSM8PS="float calculateVSM8(vec3 moments, float Z, float vsmBias) {\n float VSMBias = vsmBias;//0.01 * 0.25;\n float depthScale = VSMBias * Z;\n float minVariance1 = depthScale * depthScale;\n return chebyshevUpperBound(moments.xy, Z, minVariance1, 0.1);\n}\nfloat decodeFloatRG(vec2 rg) {\n return rg.y*(1.0/255.0) + rg.x;\n}\nfloat VSM8(sampler2D tex, vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n vec4 c = texture2D(tex, texCoords);\n vec3 moments = vec3(decodeFloatRG(c.xy), decodeFloatRG(c.zw), 0.0);\n return calculateVSM8(moments, Z, vsmBias);\n}\nfloat getShadowVSM8(sampler2D shadowMap, vec3 shadowParams, float exponent) {\n return VSM8(shadowMap, dShadowCoord.xy, shadowParams.x, dShadowCoord.z, shadowParams.y, 0.0);\n}\nfloat getShadowSpotVSM8(sampler2D shadowMap, vec4 shadowParams, float exponent) {\n return VSM8(shadowMap, dShadowCoord.xy, shadowParams.x, length(dLightDirW) * shadowParams.w + shadowParams.z, shadowParams.y, 0.0);\n}\n";
|
|
pc.shaderChunks.shadowVSMVSPS="float getShadowVSM$VS(sampler2D shadowMap, vec3 shadowParams, float exponent) {\n dShadowCoord = vMainShadowUv.xyz;\n dShadowCoord.z += shadowParams.z;\n dShadowCoord.xyz /= vMainShadowUv.w;\n dShadowCoord.z = min(dShadowCoord.z, 1.0);\n return $VSM(shadowMap, dShadowCoord.xy, shadowParams.x, dShadowCoord.z, shadowParams.y, exponent);\n}\n";pc.shaderChunks.shadowVSM_commonPS="float linstep(float a, float b, float v) {\n return saturate((v - a) / (b - a));\n}\nfloat reduceLightBleeding(float pMax, float amount) {\n // Remove the [0, amount] tail and linearly rescale (amount, 1].\n return linstep(amount, 1.0, pMax);\n}\nfloat chebyshevUpperBound(vec2 moments, float mean, float minVariance, float lightBleedingReduction) {\n // Compute variance\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, minVariance);\n // Compute probabilistic upper bound\n float d = mean - moments.x;\n float pMax = variance / (variance + (d * d));\n pMax = reduceLightBleeding(pMax, lightBleedingReduction);\n // One-tailed Chebyshev\n return (mean <= moments.x ? 1.0 : pMax);\n}\nfloat calculateEVSM(vec3 moments, float Z, float vsmBias, float exponent) {\n Z = 2.0 * Z - 1.0;\n float warpedDepth = exp(exponent * Z);\n moments.xy += vec2(warpedDepth, warpedDepth*warpedDepth) * (1.0 - moments.z);\n float VSMBias = vsmBias;//0.01 * 0.25;\n float depthScale = VSMBias * exponent * warpedDepth;\n float minVariance1 = depthScale * depthScale;\n return chebyshevUpperBound(moments.xy, warpedDepth, minVariance1, 0.1);\n}\n";
|
|
pc.shaderChunks.skinBatchConstVS="attribute float vertex_boneIndices;\nuniform mat4 matrix_pose[BONE_LIMIT];\nmat4 getBoneMatrix(const in float i) {\n mat4 bone = matrix_pose[int(i)];\n return bone;\n}\n";pc.shaderChunks.skinBatchTexVS="attribute float vertex_boneIndices;\nuniform sampler2D texture_poseMap;\nuniform vec2 texture_poseMapSize;\nmat4 getBoneMatrix(const in float i) {\n float j = i * 4.0;\n float x = mod(j, float(texture_poseMapSize.x));\n float y = floor(j / float(texture_poseMapSize.x));\n float dx = 1.0 / float(texture_poseMapSize.x);\n float dy = 1.0 / float(texture_poseMapSize.y);\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(texture_poseMap, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(texture_poseMap, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(texture_poseMap, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(texture_poseMap, vec2(dx * (x + 3.5), y));\n mat4 bone = mat4(v1, v2, v3, v4);\n return bone;\n}\n";
|
|
pc.shaderChunks.skinConstVS="attribute vec4 vertex_boneWeights;\nattribute vec4 vertex_boneIndices;\nuniform mat4 matrix_pose[BONE_LIMIT];\nmat4 getBoneMatrix(const in float i)\n{\n mat4 bone = matrix_pose[int(i)];\n return bone;\n}\n";pc.shaderChunks.skinTexVS="attribute vec4 vertex_boneWeights;\nattribute vec4 vertex_boneIndices;\nuniform sampler2D texture_poseMap;\nuniform vec2 texture_poseMapSize;\nmat4 getBoneMatrix(const in float i)\n{\n float j = i * 4.0;\n float x = mod(j, float(texture_poseMapSize.x));\n float y = floor(j / float(texture_poseMapSize.x));\n float dx = 1.0 / float(texture_poseMapSize.x);\n float dy = 1.0 / float(texture_poseMapSize.y);\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(texture_poseMap, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(texture_poseMap, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(texture_poseMap, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(texture_poseMap, vec2(dx * (x + 3.5), y));\n mat4 bone = mat4(v1, v2, v3, v4);\n return bone;\n}\n";
|
|
pc.shaderChunks.skyboxPS="varying vec3 vViewDir;\nuniform samplerCube texture_cubeMap;\nvoid main(void) {\n gl_FragColor = textureCube(texture_cubeMap, fixSeams(vViewDir));\n}\n";pc.shaderChunks.skyboxVS="attribute vec3 aPosition;\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nuniform mat4 matrix_projection;\nvarying vec3 vViewDir;\nvoid main(void)\n{\n mat4 view = matrix_view;\n view[3][0] = view[3][1] = view[3][2] = 0.0;\n gl_Position = matrix_projection * view * vec4(aPosition, 1.0);\n // Force skybox to far Z, regardless of the clip planes on the camera\n // Subtract a tiny fudge factor to ensure floating point errors don't\n // still push pixels beyond far Z. See:\n // http://www.opengl.org/discussion_boards/showthread.php/171867-skybox-problem\n gl_Position.z = gl_Position.w - 0.00001;\n vViewDir = aPosition;\n vViewDir.x *= -1.0;\n}\n";
|
|
pc.shaderChunks.skyboxHDRPS="varying vec3 vViewDir;\nuniform samplerCube texture_cubeMap;\nvoid main(void) {\n vec3 color = processEnvironment($textureCubeSAMPLE(texture_cubeMap, fixSeamsStatic(vViewDir, $FIXCONST)).rgb);\n color = toneMap(color);\n color = gammaCorrectOutput(color);\n gl_FragColor = vec4(color, 1.0);\n}\n";pc.shaderChunks.skyboxPrefilteredCubePS="varying vec3 vViewDir;\nuniform samplerCube texture_cubeMap;\nvec3 fixSeamsStretch(vec3 vec, float mipmapIndex, float cubemapSize) {\n float scale = 1.0 - exp2(mipmapIndex) / cubemapSize;\n float M = max(max(abs(vec.x), abs(vec.y)), abs(vec.z));\n if (abs(vec.x) != M) vec.x *= scale;\n if (abs(vec.y) != M) vec.y *= scale;\n if (abs(vec.z) != M) vec.z *= scale;\n return vec;\n}\nvoid main(void) {\n vec3 color = textureCubeRGBM(texture_cubeMap, fixSeamsStretch(vViewDir, 0.0, 128.0));\n color = toneMap(color);\n color = gammaCorrectOutput(color);\n gl_FragColor = vec4(color, 1.0);\n}\n";
|
|
pc.shaderChunks.specularPS="#ifdef MAPCOLOR\nuniform vec3 material_specular;\n#endif\n#ifdef MAPTEXTURE\nuniform sampler2D texture_specularMap;\n#endif\nvoid getSpecularity() {\n dSpecularity = vec3(1.0);\n #ifdef MAPCOLOR\n dSpecularity *= material_specular;\n #endif\n #ifdef MAPTEXTURE\n dSpecularity *= texture2D(texture_specularMap, $UV).$CH;\n #endif\n #ifdef MAPVERTEX\n dSpecularity *= saturate(vVertexColor.$VC);\n #endif\n}\n";
|
|
pc.shaderChunks.specularAaNonePS="float antiAliasGlossiness(float power) {\n return power;\n}\n";pc.shaderChunks.specularAaToksvigPS="float antiAliasGlossiness(float power) {\n float rlen = 1.0 / saturate(length(dNormalMap));\n float toksvig = 1.0 / (1.0 + power * (rlen - 1.0));\n return power * toksvig;\n}\n";pc.shaderChunks.specularAaToksvigFloatPS="float antiAliasGlossiness(float power) {\n float rlen = 1.0 / saturate(length(dNormalMap));\n float toksvig = 1.0 / (1.0 + power * (rlen - 1.0));\n return power * mix(1.0, toksvig, material_bumpiness);\n}\n";
|
|
pc.shaderChunks.spotPS="float getSpotEffect(vec3 lightSpotDirW, float lightInnerConeAngle, float lightOuterConeAngle) {\n float cosAngle = dot(dLightDirNormW, lightSpotDirW);\n return smoothstep(lightOuterConeAngle, lightInnerConeAngle, cosAngle);\n}\n";pc.shaderChunks.startPS="\nvoid main(void) {\n dDiffuseLight = vec3(0);\n dSpecularLight = vec3(0);\n dReflection = vec4(0);\n dSpecularity = vec3(0);\n";pc.shaderChunks.startVS="\nvoid main(void) {\n gl_Position = getPosition();\n";
|
|
pc.shaderChunks.startNineSlicedPS=" nineSlicedUv = vUv0;\n";pc.shaderChunks.startNineSlicedTiledPS="\n vec2 tileMask = step(vMask, vec2(0.99999));\n vec2 clampedUv = mix(innerOffset.xy*0.5, vec2(1.0) - innerOffset.zw*0.5, fract(vTiledUv));\n clampedUv = clampedUv * atlasRect.zw + atlasRect.xy;\n nineSlicedUv = vUv0 * tileMask + clampedUv * (vec2(1.0) - tileMask);\n";pc.shaderChunks.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";
|
|
pc.shaderChunks.tangentBinormalVS="\nvec3 getTangent() {\n return normalize(dNormalMatrix * vertex_tangent.xyz);\n}\nvec3 getBinormal() {\n return cross(vNormalW, vTangentW) * vertex_tangent.w;\n}\n";pc.shaderChunks.tonemappingAcesPS="uniform float exposure;\nvec3 toneMap(vec3 color) {\n float tA = 2.51;\n float tB = 0.03;\n float tC = 2.43;\n float tD = 0.59;\n float tE = 0.14;\n vec3 x = color * exposure;\n return (x*(tA*x+tB))/(x*(tC*x+tD)+tE);\n}\n";
|
|
pc.shaderChunks.tonemappingAces2PS="uniform float exposure;\n// ACES approximation by Stephen Hill\n// sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT\nconst mat3 ACESInputMat = mat3(\n 0.59719, 0.35458, 0.04823,\n 0.07600, 0.90834, 0.01566,\n 0.02840, 0.13383, 0.83777\n);\n// ODT_SAT => XYZ => D60_2_D65 => sRGB\nconst mat3 ACESOutputMat = mat3(\n 1.60475, -0.53108, -0.07367,\n -0.10208, 1.10813, -0.00605,\n -0.00327, -0.07276, 1.07602\n);\nvec3 RRTAndODTFit(vec3 v) {\n vec3 a = v * (v + 0.0245786) - 0.000090537;\n vec3 b = v * (0.983729 * v + 0.4329510) + 0.238081;\n return a / b;\n}\nvec3 toneMap(vec3 color) {\n color *= exposure;\n color = color * ACESInputMat;\n // Apply RRT and ODT\n color = RRTAndODTFit(color);\n color = color * ACESOutputMat;\n // Clamp to [0, 1]\n color = clamp(color, 0.0, 1.0);\n return color;\n}\n";
|
|
pc.shaderChunks.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 color = uncharted2Tonemap(color * exposure);\n vec3 whiteScale = 1.0 / uncharted2Tonemap(vec3(W,W,W));\n color = color * whiteScale;\n return color;\n}\n";
|
|
pc.shaderChunks.tonemappingHejlPS="uniform float exposure;\nvec3 toneMap(vec3 color) {\n color *= exposure;\n const float A = 0.22, B = 0.3, C = .1, D = 0.2, E = .01, F = 0.3;\n const float Scl = 1.25;\n vec3 h = max( vec3(0.0), color - vec3(0.004) );\n return (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";pc.shaderChunks.tonemappingLinearPS="uniform float exposure;\nvec3 toneMap(vec3 color) {\n return color * exposure;\n}\n";
|
|
pc.shaderChunks.tonemappingNonePS="vec3 toneMap(vec3 color) {\n return color;\n}\n";pc.shaderChunks.transformVS="#ifdef PIXELSNAP\n uniform vec4 uScreenSize;\n#endif\nmat4 getModelMatrix() {\n #ifdef DYNAMICBATCH\n return getBoneMatrix(vertex_boneIndices);\n #elif defined(SKIN)\n return matrix_model * (getBoneMatrix(vertex_boneIndices.x) * vertex_boneWeights.x +\n getBoneMatrix(vertex_boneIndices.y) * vertex_boneWeights.y +\n getBoneMatrix(vertex_boneIndices.z) * vertex_boneWeights.z +\n getBoneMatrix(vertex_boneIndices.w) * vertex_boneWeights.w);\n #elif defined(INSTANCING)\n return mat4(instance_line1, instance_line2, instance_line3, instance_line4);\n #else\n return matrix_model;\n #endif\n}\nvec4 getPosition() {\n dModelMatrix = getModelMatrix();\n vec3 localPos = vertex_position;\n #ifdef NINESLICED\n // outer and inner vertices are at the same position, scale both\n localPos.xz *= outerScale;\n // offset inner vertices inside\n // (original vertices must be in [-1;1] range)\n vec2 positiveUnitOffset = clamp(vertex_position.xz, vec2(0.0), vec2(1.0));\n vec2 negativeUnitOffset = clamp(-vertex_position.xz, vec2(0.0), vec2(1.0));\n localPos.xz += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;\n vTiledUv = (localPos.xz - outerScale + innerOffset.xy) * -0.5 + 1.0; // uv = local pos - inner corner\n localPos.xz *= -0.5; // move from -1;1 to -0.5;0.5\n localPos = localPos.xzy;\n #endif\n vec4 posW = dModelMatrix * vec4(localPos, 1.0);\n #ifdef SCREENSPACE\n posW.zw = vec2(0.0, 1.0);\n #endif\n dPositionW = posW.xyz;\n vec4 screenPos;\n #ifdef UV1LAYOUT\n screenPos = vec4(vertex_texCoord1.xy * 2.0 - 1.0, 0.5, 1);\n #else\n #ifdef SCREENSPACE\n screenPos = posW;\n #else\n screenPos = matrix_viewProjection * posW;\n #endif\n #ifdef PIXELSNAP\n // snap vertex to a pixel boundary\n screenPos.xy = (screenPos.xy * 0.5) + 0.5;\n screenPos.xy *= uScreenSize.xy;\n screenPos.xy = floor(screenPos.xy);\n screenPos.xy *= uScreenSize.zw;\n screenPos.xy = (screenPos.xy * 2.0) - 1.0;\n #endif\n #endif\n return screenPos;\n}\nvec3 getWorldPosition() {\n return dPositionW;\n}\n";
|
|
pc.shaderChunks.transformDeclVS="attribute vec3 vertex_position;\nuniform mat4 matrix_model;\nuniform mat4 matrix_viewProjection;\nvec3 dPositionW;\nmat4 dModelMatrix;\n";pc.shaderChunks.uv0VS="#ifdef NINESLICED\nvec2 getUv0() {\n vec2 uv = vertex_position.xz;\n // offset inner vertices inside\n // (original vertices must be in [-1;1] range)\n vec2 positiveUnitOffset = clamp(vertex_position.xz, vec2(0.0), vec2(1.0));\n vec2 negativeUnitOffset = clamp(-vertex_position.xz, vec2(0.0), vec2(1.0));\n uv += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;\n uv = uv * -0.5 + 0.5;\n uv = uv * atlasRect.zw + atlasRect.xy;\n vMask = vertex_texCoord0.xy;\n return uv;\n}\n#else\nvec2 getUv0() {\n return vertex_texCoord0;\n}\n#endif\n";
|
|
pc.shaderChunks.uv1VS="\nvec2 getUv1() {\n return vertex_texCoord1;\n}\n";pc.shaderChunks.viewDirPS="void getViewDir() {\n dViewDirW = normalize(view_position - vPositionW);\n}\n";pc.shaderChunks.viewNormalVS="\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nvec3 getViewNormal() {\n return mat3(matrix_view) * vNormalW;\n}\n";pc.programlib={gammaCode:function(e){return e===pc.GAMMA_SRGB||e===pc.GAMMA_SRGBFAST?pc.shaderChunks.gamma2_2PS:e===pc.GAMMA_SRGBHDR?"#define HDR\n"+pc.shaderChunks.gamma2_2PS:pc.shaderChunks.gamma1_0PS},tonemapCode:function(e){return e===pc.TONEMAP_FILMIC?pc.shaderChunks.tonemappingFilmicPS:e===pc.TONEMAP_LINEAR?pc.shaderChunks.tonemappingLinearPS:e===pc.TONEMAP_HEJL?pc.shaderChunks.tonemappingHejlPS:e===pc.TONEMAP_ACES?pc.shaderChunks.tonemappingAcesPS:e===pc.TONEMAP_ACES2?pc.shaderChunks.tonemappingAces2PS:
|
|
pc.shaderChunks.tonemappingNonePS},fogCode:function(e){return"linear"===e?pc.shaderChunks.fogLinearPS:"exp"===e?pc.shaderChunks.fogExpPS:"exp2"===e?pc.shaderChunks.fogExp2PS:pc.shaderChunks.fogNonePS},skinCode:function(e,b){b||(b=pc.shaderChunks);return e.supportsBoneTextures?b.skinTexVS:"#define BONE_LIMIT "+e.getBoneLimit()+"\n"+b.skinConstVS},precisionCode:function(e){var b="precision "+e.precision+" float;\n";e.webgl2&&(b+="#ifdef GL2\nprecision "+e.precision+" sampler2DShadow;\n#endif\n");return b},
|
|
versionCode:function(e){return e.webgl2?"#version 300 es\n":""},dummyFragmentCode:function(){return"void main(void) {gl_FragColor = vec4(0.0);}"},begin:function(){return"void main(void)\n{\n"},end:function(){return"}\n"}};pc.programlib.basic={generateKey:function(e){var b="basic";e.fog&&(b+="_fog");e.alphaTest&&(b+="_atst");e.vertexColors&&(b+="_vcol");e.diffuseMap&&(b+="_diff");return b+="_"+e.pass},createShaderDefinition:function(e,b){var a={vertex_position:pc.SEMANTIC_POSITION};b.skin&&(a.vertex_boneWeights=pc.SEMANTIC_BLENDWEIGHT,a.vertex_boneIndices=pc.SEMANTIC_BLENDINDICES);b.vertexColors&&(a.vertex_color=pc.SEMANTIC_COLOR);b.diffuseMap&&(a.vertex_texCoord0=pc.SEMANTIC_TEXCOORD0);var c=pc.shaderChunks,d;d=""+
|
|
c.transformDeclVS;b.skin?(d+=pc.programlib.skinCode(e),d+=c.transformSkinnedVS):d+=c.transformVS;b.vertexColors&&(d+="attribute vec4 vertex_color;\nvarying vec4 vColor;\n");b.diffuseMap&&(d+="attribute vec2 vertex_texCoord0;\nvarying vec2 vUv0;\n");b.pass===pc.SHADER_DEPTH&&(d+="varying float vDepth;\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params;\n\n#endif\n");d+=pc.programlib.begin();d+=" gl_Position = getPosition();\n";
|
|
b.pass===pc.SHADER_DEPTH&&(d+=" vDepth = -(matrix_view * vec4(getWorldPosition(),1.0)).z * camera_params.x;\n");b.vertexColors&&(d+=" vColor = vertex_color;\n");b.diffuseMap&&(d+=" vUv0 = vertex_texCoord0;\n");var f=d+=pc.programlib.end();d=pc.programlib.precisionCode(e);d=b.vertexColors?d+"varying vec4 vColor;\n":d+"uniform vec4 uColor;\n";b.diffuseMap&&(d+="varying vec2 vUv0;\nuniform sampler2D texture_diffuseMap;\n");b.fog&&(d+=pc.programlib.fogCode(b.fog));b.alphatest&&(d+=c.alphaTestPS);
|
|
b.pass===pc.SHADER_DEPTH&&(d=d+"varying float vDepth;\n"+c.packDepthPS);d+=pc.programlib.begin();d=b.vertexColors?d+" gl_FragColor = vColor;\n":d+" gl_FragColor = uColor;\n";b.diffuseMap&&(d+=" gl_FragColor *= texture2D(texture_diffuseMap, vUv0);\n");b.alphatest&&(d+=" alphaTest(gl_FragColor.a);\n");b.pass!==pc.SHADER_PICK&&(b.pass===pc.SHADER_DEPTH?d+=" gl_FragColor = packFloat(vDepth);\n":b.fog&&(d+=" glFragColor.rgb = addFog(gl_FragColor.rgb);\n"));d+=pc.programlib.end();return{attributes:a,
|
|
vshader:f,fshader:d}}};pc.programlib.particle={generateKey:function(e){var b="particle",a;for(a in e)e.hasOwnProperty(a)&&(b+=e[a]);return b},_animTex:function(e,b){var a;a=""+(e.animTexLoop?b.particleAnimFrameLoopVS:b.particleAnimFrameClampVS);return a+=b.particleAnimTexVS},createShaderDefinition:function(e,b){var a=pc.shaderChunks,c="",d=pc.programlib.precisionCode(e)+"\n";e.webgl2&&(c+="#define GL2\n",d+="#define GL2\n");c+="#define VERTEXSHADER\n";b.mesh&&(c+="#define USE_MESH\n");b.localSpace&&(c+="#define LOCAL_SPACE\n");
|
|
b.animTex&&(c+="\nuniform vec4 animTexParams;\n");2==b.normal&&(c+="\nvarying mat3 ParticleMat;\n");1==b.normal&&(c+="\nvarying vec3 Normal;\n");b.soft&&(c+="\nvarying float vDepth;\n");var f=b.customFace?a.particle_customFaceVS:a.particle_billboardVS;b.useCpu?(0<b.soft&&(c+=a.screenDepthPS),c+=a.particle_cpuVS,b.localSpace&&(c+=a.particle_localShiftVS),b.animTex&&(c+=this._animTex(b,a)),b.alignToMotion&&(c+=a.particle_pointAlongVS),c+=b.mesh?a.particle_meshVS:f,1==b.normal&&(c+=a.particle_normalVS),
|
|
2==b.normal&&(c+=a.particle_TBNVS),0<b.stretch&&(c+=a.particle_stretchVS),c+=a.particle_cpu_endVS):(c+=a.particle_initVS,c+=b.pack8?a.particleInputRgba8PS:a.particleInputFloatPS,0<b.soft&&(c+=a.screenDepthPS),c+=a.particleVS,b.localSpace&&(c+=a.particle_localShiftVS),b.animTex&&(c+=this._animTex(b,a)),b.wrap&&(c+=a.particle_wrapVS),b.alignToMotion&&(c+=a.particle_pointAlongVS),c+=b.mesh?a.particle_meshVS:f,1==b.normal&&(c+=a.particle_normalVS),2==b.normal&&(c+=a.particle_TBNVS),0<b.stretch&&(c+=a.particle_stretchVS),
|
|
c+=a.particle_endVS);0<b.soft&&(c+=a.particle_softVS);c+="}\n";0<b.normal&&(1==b.normal?d+="\nvarying vec3 Normal;\n":2==b.normal&&(d+="\nvarying mat3 ParticleMat;\n"),d+="\nuniform vec3 lightCube[6];\n");b.soft&&(d+="\nvarying float vDepth;\n");0===b.normal&&"none"===b.fog&&(b.srgb=!1);d+=pc.programlib.gammaCode(b.gamma);d+=pc.programlib.tonemapCode(b.toneMap);d="linear"===b.fog?d+a.fogLinearPS:"exp"===b.fog?d+a.fogExpPS:"exp2"===b.fog?d+a.fogExp2PS:d+a.fogNonePS;2==b.normal&&(d+="\nuniform sampler2D normalMap;\n");
|
|
0<b.soft&&(d+=a.screenDepthPS);d+=a.particlePS;0<b.soft&&(d+=a.particle_softPS);1==b.normal&&(d+="\nvec3 normal = Normal;\n");2==b.normal&&(d+=a.particle_normalMapPS);0<b.normal&&(d+=b.halflambert?a.particle_halflambertPS:a.particle_lambertPS);0<b.normal&&(d+=a.particle_lightingPS);b.blend==pc.BLEND_NORMAL?d+=a.particle_blendNormalPS:b.blend==pc.BLEND_ADDITIVE?d+=a.particle_blendAddPS:b.blend==pc.BLEND_MULTIPLICATIVE&&(d+=a.particle_blendMultiplyPS);d+=a.particle_endPS;return{attributes:pc.shaderChunks.collectAttribs(c),
|
|
vshader:c,fshader:d}}};var _oldChunkWarn=function(e,b){},_oldChunkFloat=function(e,b,a){_oldChunkWarn(a,b);return"\n#ifdef MAPFLOAT\n"+e+"\n#else\n"+pc.shaderChunks[b]+"\n#endif\n"},_oldChunkColor=function(e,b,a){_oldChunkWarn(a,b);return"\n#ifdef MAPCOLOR\n"+e+"\n#else\n"+pc.shaderChunks[b]+"\n#endif\n"},_oldChunkTex=function(e,b,a){_oldChunkWarn(a,b);return"\n#ifdef MAPTEXTURE\n"+e+"\n#else\n"+pc.shaderChunks[b]+"\n#endif\n"},_oldChunkTexColor=function(e,b,a){_oldChunkWarn(a,b);return"#undef MAPTEXTURECOLOR\n#ifdef MAPTEXTURE\n#ifdef MAPCOLOR\n#define MAPTEXTURECOLOR\n#endif\n#endif\n#ifdef MAPTEXTURECOLOR\n"+
|
|
e+"\n#else\n"+pc.shaderChunks[b]+"\n#endif\n"},_oldChunkTexFloat=function(e,b,a){_oldChunkWarn(a,b);return"#undef MAPTEXTUREFLOAT\n#ifdef MAPTEXTURE\n#ifdef MAPFLOAT\n#define MAPTEXTUREFLOAT\n#endif\n#endif\n#ifdef MAPTEXTUREFLOAT\n"+e+"\n#else\n"+pc.shaderChunks[b]+"\n#endif\n"},_oldChunkVert=function(e,b,a){_oldChunkWarn(a,b);return"\n#ifdef MAPVERTEX\n"+e+"\n#else\n"+pc.shaderChunks[b]+"\n#endif\n"},_oldChunkVertColor=function(e,b,a){_oldChunkWarn(a,b);return"#undef MAPVERTEXCOLOR\n#ifdef MAPVERTEX\n#ifdef MAPCOLOR\n#define MAPVERTEXCOLOR\n#endif\n#endif\n#ifdef MAPVERTEXCOLOR\n"+
|
|
e+"\n#else\n"+pc.shaderChunks[b]+"\n#endif\n"},_oldChunkVertFloat=function(e,b,a){_oldChunkWarn(a,b);return"#undef MAPVERTEXFLOAT\n#ifdef MAPVERTEX\n#ifdef MAPFLOAT\n#define MAPVERTEXFLOAT\n#endif\n#endif\n#ifdef MAPVERTEXFLOAT\n"+e+"\n#else\n"+pc.shaderChunks[b]+"\n#endif\n"},_oldChunkTransformSkin=function(e,b,a){_oldChunkWarn(a,b);return"\n#ifdef SKIN\n"+e+"\n#else\n"+pc.shaderChunks[b]+"\n#endif\n"},_oldChunkTransformDynbatch=function(e,b,a){_oldChunkWarn(a,b);return"\n#ifdef DYNAMICBATCH\n"+
|
|
e+"\n#else\n"+pc.shaderChunks[b]+"\n#endif\n"},_oldChunkTransformInstanced=function(e,b,a){_oldChunkWarn(a,b);return"\n#ifdef INSTANCING\n"+e+"\n#else\n"+pc.shaderChunks[b]+"\n#endif\n"},_oldChunkTransformPixelSnap=function(e,b,a){_oldChunkWarn(a,b);return"\n#ifdef PIXELSNAP\n"+e+"\n#else\n"+pc.shaderChunks[b]+"\n#endif\n"},_oldChunkTransformScreenSpace=function(e,b,a){_oldChunkWarn(a,b);return"\n#ifdef SCREENSPACE\n"+e+"\n#else\n"+pc.shaderChunks[b]+"\n#endif\n"},_oldChunkTransformScreenSpaceBatch=
|
|
function(e,b,a){_oldChunkWarn(a,b);return"#undef SCREENSPACEBATCH\n#ifdef SCREENSPACE\n#ifdef BATCH\n#define SCREENSPACEBATCH\n#endif\n#endif\n#ifdef SCREENSPACEBATCH\n"+e+"\n#else\n"+pc.shaderChunks[b]+"\n#endif\n"},_oldChunkTransformUv1=function(e,b,a){_oldChunkWarn(a,b);return"\n#ifdef UV1LAYOUT\n"+e+"\n#else\n"+pc.shaderChunks[b]+"\n#endif\n"};
|
|
pc.programlib.standard={_oldChunkToNew:{aoTexPS:{n:"aoPS",f:_oldChunkTex},aoVertPS:{n:"aoPS",f:_oldChunkVert},diffuseConstPS:{n:"diffusePS",f:_oldChunkColor},diffuseTexPS:{n:"diffusePS",f:_oldChunkTex},diffuseTexConstPS:{n:"diffusePS",f:_oldChunkTexColor},diffuseVertPS:{n:"diffusePS",f:_oldChunkVert},diffuseVertConstPS:{n:"diffusePS",f:_oldChunkVertColor},emissiveConstPS:{n:"emissivePS",f:_oldChunkColor},emissiveTexPS:{n:"emissivePS",f:_oldChunkTex},emissiveTexConstPS:{n:"emissivePS",f:_oldChunkTexColor},
|
|
emissiveTexConstFloatPS:{n:"emissivePS",f:_oldChunkTexFloat},emissiveVertPS:{n:"emissivePS",f:_oldChunkVert},emissiveVertConstPS:{n:"emissivePS",f:_oldChunkVertColor},emissiveVertConstFloatPS:{n:"emissivePS",f:_oldChunkVertFloat},glossConstPS:{n:"glossPS",f:_oldChunkFloat},glossTexPS:{n:"glossPS",f:_oldChunkTex},glossTexConstPS:{n:"glossPS",f:_oldChunkTexFloat},glossVertPS:{n:"glossPS",f:_oldChunkVert},glossVertConstPS:{n:"glossPS",f:_oldChunkVertFloat},metalnessConstPS:{n:"metalnessPS",f:_oldChunkFloat},
|
|
metalnessTexPS:{n:"metalnessPS",f:_oldChunkTex},metalnessTexConstPS:{n:"metalnessPS",f:_oldChunkTexFloat},metalnessVertPS:{n:"metalnessPS",f:_oldChunkVert},metalnessVertConstPS:{n:"metalnessPS",f:_oldChunkVertFloat},opacityConstPS:{n:"opacityPS",f:_oldChunkFloat},opacityTexPS:{n:"opacityPS",f:_oldChunkTex},opacityTexConstPS:{n:"opacityPS",f:_oldChunkTexFloat},opacityVertPS:{n:"opacityPS",f:_oldChunkVert},opacityVertConstPS:{n:"opacityPS",f:_oldChunkVertFloat},specularConstPS:{n:"specularPS",f:_oldChunkColor},
|
|
specularTexPS:{n:"specularPS",f:_oldChunkTex},specularTexConstPS:{n:"specularPS",f:_oldChunkTexColor},specularVertPS:{n:"specularPS",f:_oldChunkVert},specularVertConstPS:{n:"specularPS",f:_oldChunkVertColor},transformBatchSkinnedVS:{n:"transformVS",f:_oldChunkTransformDynbatch},transformInstancedVS:{n:"transformVS",f:_oldChunkTransformInstanced},transformPixelSnapVS:{n:"transformVS",f:_oldChunkTransformPixelSnap},transformScreenSpaceVS:{n:"transformVS",f:_oldChunkTransformScreenSpace},transformScreenSpaceBatchSkinned:{n:"transformVS",
|
|
f:_oldChunkTransformScreenSpaceBatch},transformSkinned:{n:"transformVS",f:_oldChunkTransformSkin},transformUv1:{n:"transformVS",f:_oldChunkTransformUv1}},optionsContext:{},optionsContextMin:{},generateKey:function(e){var b=function(a){var b=[],c;for(c in a)a.hasOwnProperty(c)&&"chunks"!==c&&"lights"!==c&&b.push(c);return b.sort()},a;e===this.optionsContextMin?(this.propsMin||(this.propsMin=b(e)),a=this.propsMin):e===this.optionsContext?(this.props||(this.props=b(e)),a=this.props):a=b(e);var b="standard",
|
|
c;for(c=0;c<a.length;c++)e[a[c]]&&(b+=a[c]+e[a[c]]);if(e.chunks){a=[];for(var d in e.chunks)e.chunks.hasOwnProperty(d)&&a.push(d+e.chunks[d]);a.sort();b+=a}if(e.lights)for(c=0;c<e.lights.length;c++)b+=e.lights[c].key;return pc.hashCode(b)},_correctChannel:function(e,b){if(0<pc._matTex2D[e]){if(pc._matTex2D[e]<b.length)return b.substring(0,pc._matTex2D[e]);if(pc._matTex2D[e]>b.length){for(var a=b,c=a.charAt(a.length-1),d=pc._matTex2D[e]-a.length,f=0;f<d;f++)a+=c;return a}return b}},_setMapTransform:function(e,
|
|
b,a,c){e[0]+="uniform vec4 texture_"+b+"MapTransform;\n";var d=a+100*c;e[3][d]||(e[1]+="varying vec2 vUV"+c+"_"+a+";\n",e[2]+=" vUV"+c+"_"+a+" = uv"+c+" * texture_"+b+"MapTransform.xy + texture_"+b+"MapTransform.zw;\n",e[3][d]=!0);return e},_getUvSourceExpression:function(e,b,a){var c=a[e];b=a[b];a.nineSlicedMode===pc.SPRITE_RENDERMODE_SLICED?c="nineSlicedUv":a.nineSlicedMode===pc.SPRITE_RENDERMODE_TILED?c="nineSlicedUv, -1000.0":(c=0===c?"vUv"+b:"vUV"+b+"_"+c,a.heightMap&&"heightMapTransform"!==
|
|
e&&(c+=" + dUvOffset"));return c},_addMapDef:function(e,b){var a="\n#undef "+e+"\n";b&&(a+=" #define "+e+"\n");return a},_addMapDefs:function(e,b,a,c){e=""+this._addMapDef("MAPFLOAT",e);e+=this._addMapDef("MAPCOLOR",b);e+=this._addMapDef("MAPVERTEX",a);return e+=this._addMapDef("MAPTEXTURE",c)},_addMap:function(e,b,a,c,d){var f=e+"Map",g=f+"Uv",l=f+"Transform",h=f+"Channel",p=e+"VertexColorChannel",k=a[e+"Tint"];e=a[e+"VertexColor"];f=a[f];b=c[b];f&&(g=this._getUvSourceExpression(l,g,a),b=b.replace(/\$UV/g,
|
|
g).replace(/\$CH/g,a[h]),void 0!==d&&(b=b.replace(/\$texture2DSAMPLE/g,0===d?"texture2DSRGB":1===d?"texture2DRGBM":"texture2D")));e&&(b=b.replace(/\$VC/g,a[p]));b=this._addMapDefs(1===k,3===k,e,f)+b;return b.replace(/\$/g,"")},_nonPointShadowMapProjection:function(e,b,a){return!b._normalOffsetBias||b._isVsm?b._type===pc.LIGHTTYPE_SPOT?b._isPcf&&(e.webgl2||e.extStandardDerivatives)?" getShadowCoordPerspZbuffer"+a:" getShadowCoordPersp"+a:" getShadowCoordOrtho"+a:b._type===pc.LIGHTTYPE_SPOT?
|
|
b._isPcf&&(e.webgl2||e.extStandardDerivatives)?" getShadowCoordPerspZbufferNormalOffset"+a:" getShadowCoordPerspNormalOffset"+a:" getShadowCoordOrthoNormalOffset"+a},_addVaryingIfNeeded:function(e,b,a){return 0<=e.indexOf(a)?"varying "+b+" "+a+";\n":""},_vsAddTransformCode:function(e,b,a,c){return e+=a.transformVS},_vsAddBaseCode:function(e,b,a,c){e+=a.baseVS;if(c.nineSlicedMode===pc.SPRITE_RENDERMODE_SLICED||c.nineSlicedMode===pc.SPRITE_RENDERMODE_TILED)e+=a.baseNineSlicedVS;return e},
|
|
_fsAddBaseCode:function(e,b,a,c){e+=a.basePS;c.nineSlicedMode===pc.SPRITE_RENDERMODE_SLICED?e+=a.baseNineSlicedPS:c.nineSlicedMode===pc.SPRITE_RENDERMODE_TILED&&(e+=a.baseNineSlicedTiledPS);return e},_fsAddStartCode:function(e,b,a,c){e+=a.startPS;c.nineSlicedMode===pc.SPRITE_RENDERMODE_SLICED?e+=a.startNineSlicedPS:c.nineSlicedMode===pc.SPRITE_RENDERMODE_TILED&&(e+=a.startNineSlicedTiledPS);return e},createShaderDefinition:function(e,b){var a,c,d=0<b.lights.length;b.dirLightMap&&(d=!0,b.useSpecular=
|
|
!0);b.shadingModel===pc.SPECULAR_PHONG?(b.fresnelModel=0,b.specularAntialias=!1,b.prefilteredCubemap=!1,b.dpAtlas=!1,b.ambientSH=!1):b.fresnelModel=0===b.fresnelModel?pc.FRESNEL_SCHLICK:b.fresnelModel;var f=(b.cubeMap||b.prefilteredCubemap&&b.useSpecular)&&!b.sphereMap&&!b.dpAtlas,g=b.sphereMap||f||b.dpAtlas,l=b.useTexCubeLod;b.cubeMap&&(b.sphereMap=null);b.dpAtlas&&(b.prefilteredCubemap=null);b.useSpecular||(b.specularMap=b.glossMap=null);var h=d||g||b.ambientSH||b.prefilteredCubemap||b.heightMap,
|
|
p=b.pass>=pc.SHADER_SHADOW&&17>=b.pass;this.options=b;var k="",n="",q="",m=pc.shaderChunks,r,t={vertex_position:pc.SEMANTIC_POSITION};if(b.chunks){var u={};for(c in m)m.hasOwnProperty(c)&&(b.chunks[c]?(r=b.chunks[c],0<=r.indexOf("vertex_normal")&&(t.vertex_normal=pc.SEMANTIC_NORMAL),0<=r.indexOf("vertex_tangent")&&(t.vertex_tangent=pc.SEMANTIC_TANGENT),0<=r.indexOf("vertex_texCoord0")&&(t.vertex_texCoord0=pc.SEMANTIC_TEXCOORD0),0<=r.indexOf("vertex_texCoord1")&&(t.vertex_texCoord1=pc.SEMANTIC_TEXCOORD1),
|
|
0<=r.indexOf("vertex_color")&&(t.vertex_color=pc.SEMANTIC_COLOR),0<=r.indexOf("vertex_boneWeights")&&(t.vertex_boneWeights=pc.SEMANTIC_BLENDWEIGHT),0<=r.indexOf("vertex_boneIndices")&&(t.vertex_boneIndices=pc.SEMANTIC_BLENDINDICES),u[c]=r):u[c]=m[c]);for(c in b.chunks)(m=this._oldChunkToNew[c])&&(u[m.n]=m.f(b.chunks[c],m.n,c));m=u}k=this._vsAddBaseCode(k,e,m,b);u=-1;if(!b.noShadow&&!b.twoSidedLighting){for(a=0;a<b.lights.length;a++)if(r=b.lights[a]._type,b.lights[a].castShadows&&r===pc.LIGHTTYPE_DIRECTIONAL){k+=
|
|
"uniform mat4 light"+a+"_shadowMatrixVS;\n";k+="uniform vec3 light"+a+"_shadowParamsVS;\n";k+="uniform vec3 light"+a+(r===pc.LIGHTTYPE_DIRECTIONAL?"_directionVS":"_positionVS")+";\n";u=a;break}0<=u&&(k+=m.shadowCoordVS)}n+=" vPositionW = getWorldPosition();\n";b.pass===pc.SHADER_DEPTH&&(k+="varying float vDepth;\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params;\n\n#endif\n",n+=" vDepth = -(matrix_view * vec4(vPositionW,1.0)).z * camera_params.x;\n");
|
|
b.useInstancing&&(t.instance_line1=pc.SEMANTIC_TEXCOORD2,t.instance_line2=pc.SEMANTIC_TEXCOORD3,t.instance_line3=pc.SEMANTIC_TEXCOORD4,t.instance_line4=pc.SEMANTIC_TEXCOORD5,k+=m.instancingVS);h&&(t.vertex_normal=pc.SEMANTIC_NORMAL,n+=" vNormalW = dNormalW = getNormal();\n",b.sphereMap&&16>=e.fragmentUniformsCount&&(k+=m.viewNormalVS,n+=" vNormalV = getViewNormal();\n"),(b.heightMap||b.normalMap)&&b.hasTangents&&(t.vertex_tangent=pc.SEMANTIC_TANGENT,k+=m.tangentBinormalVS,n+=" vTangentW = getTangent();\n vBinormalW = getBinormal();\n"),
|
|
0<=u&&(r=b.lights[u]._type,n=r===pc.LIGHTTYPE_DIRECTIONAL?n+(" dLightDirNormW = light"+u+"_directionVS;\n"):n+(" getLightDirPoint(light"+u+"_positionVS);\n"),n+=this._nonPointShadowMapProjection(e,b.lights[u],"(light"+u+"_shadowMatrixVS, light"+u+"_shadowParamsVS);\n")));r=[];var x=[],v,w,y;for(c in pc._matTex2D)a=c+"Map",b[c+"VertexColor"]&&(v=c+"VertexColorChannel",b[v]=this._correctChannel(c,b[v])),b[a]&&(v=a+"Channel",w=a+"Transform",y=a+"Uv",b[y]=Math.min(b[y],1),b[v]=this._correctChannel(c,
|
|
b[v]),y=b[y],r[y]=!0,x[y]=x[y]||b[a]&&!b[w]);b.forceUv1&&(r[1]=!0);for(a=0;2>a;a++)r[a]&&(t["vertex_texCoord"+a]=pc["SEMANTIC_TEXCOORD"+a],k+=m["uv"+a+"VS"],n+=" vec2 uv"+a+" = getUv"+a+"();\n"),x[a]&&(n+=" vUv"+a+" = uv"+a+";\n");r=[k,q,n,[]];for(c in pc._matTex2D)a=c+"Map",b[a]&&(w=a+"Transform",b[w]&&(y=a+"Uv",this._setMapTransform(r,c,b[w],b[y])));k=r[0];q=r[1];n=r[2];b.vertexColors&&(t.vertex_color=pc.SEMANTIC_COLOR,n+=" vVertexColor = vertex_color;\n");b.skin?(t.vertex_boneWeights=pc.SEMANTIC_BLENDWEIGHT,
|
|
t.vertex_boneIndices=pc.SEMANTIC_BLENDINDICES,k+=pc.programlib.skinCode(e,m),k+="#define SKIN\n"):b.useInstancing&&(k+="#define INSTANCING\n");b.screenSpace&&(k+="#define SCREENSPACE\n");b.pixelSnap&&(k+="#define PIXELSNAP\n");k=this._vsAddTransformCode(k,e,m,b);h&&(k+=m.normalVS);k=k+"\n"+m.startVS;c=k=k+n+"}";r=q;q=""+this._addVaryingIfNeeded(k,"vec4","vMainShadowUv");q+=this._addVaryingIfNeeded(k,"vec4","vVertexColor");q+=this._addVaryingIfNeeded(k,"vec3","vPositionW");q+=this._addVaryingIfNeeded(k,
|
|
"vec3","vNormalV");q+=this._addVaryingIfNeeded(k,"vec3","vNormalW");q+=this._addVaryingIfNeeded(k,"vec3","vTangentW");q+=this._addVaryingIfNeeded(k,"vec3","vBinormalW");q+=this._addVaryingIfNeeded(k,"vec2","vUv0");q+=this._addVaryingIfNeeded(k,"vec2","vUv1");q+=r;c=q+c;k="";e.webgl2?(k=pc.programlib.versionCode(e),m.extensionVS&&(k+=m.extensionVS+"\n"),c=k+m.gles3VS+c):(m.extensionVS&&(k=m.extensionVS+"\n"),c=k+c);b.forceFragmentPrecision&&"highp"!=b.forceFragmentPrecision&&"mediump"!==b.forceFragmentPrecision&&
|
|
"lowp"!==b.forceFragmentPrecision&&(b.forceFragmentPrecision=null);b.forceFragmentPrecision&&("highp"===b.forceFragmentPrecision&&"highp"!==e.maxPrecision&&(b.forceFragmentPrecision="mediump"),"mediump"===b.forceFragmentPrecision&&"lowp"===e.maxPrecision&&(b.forceFragmentPrecision="lowp"));k="";e.webgl2&&(k+=pc.programlib.versionCode(e));e.extStandardDerivatives&&!e.webgl2&&(k+="#extension GL_OES_standard_derivatives : enable\n\n");m.extensionPS&&(k+=m.extensionPS+"\n");e.webgl2&&(k+=m.gles3PS);k+=
|
|
b.forceFragmentPrecision?"precision "+b.forceFragmentPrecision+" float;\n\n":pc.programlib.precisionCode(e);if(b.pass===pc.SHADER_PICK)return k=k+"uniform vec4 uColor;"+q,b.alphaTest&&(k=k+"float dAlpha;\n"+this._addMap("opacity","opacityPS",b,m),k+=m.alphaTestPS),k+=pc.programlib.begin(),b.alphaTest&&(k+=" getOpacity();\n alphaTest(dAlpha);\n"),k=k+" gl_FragColor = uColor;\n"+pc.programlib.end(),{attributes:t,vshader:c,fshader:k};if(b.pass===pc.SHADER_DEPTH)return k=k+"varying float vDepth;\n"+
|
|
q+m.packDepthPS,b.alphaTest&&(k+="float dAlpha;\n",k+=this._addMap("opacity","opacityPS",b,m),k+=m.alphaTestPS),k+=pc.programlib.begin(),b.alphaTest&&(k+=" getOpacity();\n",k+=" alphaTest(dAlpha);\n"),k+=" gl_FragColor = packFloat(vDepth);\n",k+=pc.programlib.end(),{attributes:t,vshader:c,fshader:k};if(p){f=b.pass-pc.SHADER_SHADOW;r=Math.floor(f/5);f-=5*r;e.extStandardDerivatives&&!e.webgl2&&(k+="uniform vec2 polygonOffset;\n");f===pc.SHADOW_VSM32?k=e.textureFloatHighPrecision?k+"#define VSM_EXPONENT 15.0\n\n":
|
|
k+"#define VSM_EXPONENT 5.54\n\n":f===pc.SHADOW_VSM16&&(k+="#define VSM_EXPONENT 5.54\n\n");r!==pc.LIGHTTYPE_DIRECTIONAL&&(k+="uniform vec3 view_position;\n",k+="uniform float light_radius;\n");k+=q;b.alphaTest&&(k+="float dAlpha;\n",k+=this._addMap("opacity","opacityPS",b,m),k+=m.alphaTestPS);f!==pc.SHADOW_PCF3||e.webgl2&&r!==pc.LIGHTTYPE_POINT?f===pc.SHADOW_VSM8&&(k+="vec2 encodeFloatRG( float v ) {\n",k+=" vec2 enc = vec2(1.0, 255.0) * v;\n",k+=" enc = fract(enc);\n",k+=" enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n",
|
|
k+=" return enc;\n",k+="}\n\n"):k+=m.packDepthPS;k+=pc.programlib.begin();b.alphaTest&&(k+=" getOpacity();\n",k+=" alphaTest(dAlpha);\n");var D=f===pc.SHADOW_VSM8||f===pc.SHADOW_VSM16||f===pc.SHADOW_VSM32,k=r===pc.LIGHTTYPE_POINT||D&&r!==pc.LIGHTTYPE_DIRECTIONAL?k+" float depth = min(distance(view_position, vPositionW) / light_radius, 0.99999);\n":k+" float depth = gl_FragCoord.z;\n";f!==pc.SHADOW_PCF3||e.webgl2&&r!==pc.LIGHTTYPE_POINT?k=f===pc.SHADOW_PCF3||f===pc.SHADOW_PCF5?k+" gl_FragColor = vec4(1.0);\n":
|
|
f===pc.SHADOW_VSM8?k+" gl_FragColor = vec4(encodeFloatRG(depth), encodeFloatRG(depth*depth));\n":k+m.storeEVSMPS:(e.extStandardDerivatives&&!e.webgl2&&(k+=" float minValue = 2.3374370500153186e-10; //(1.0 / 255.0) / (256.0 * 256.0 * 256.0);\n",k+=" depth += polygonOffset.x * max(abs(dFdx(depth)), abs(dFdy(depth))) + minValue * polygonOffset.y;\n"),k+=" gl_FragColor = packFloat(depth);\n");k+=pc.programlib.end();return{attributes:t,vshader:c,fshader:k}}if(b.customFragmentShader)return k+=b.customFragmentShader,
|
|
{attributes:t,vshader:c,fshader:k,tag:pc.SHADERTAG_MATERIAL};q=k=this._fsAddBaseCode(k+q,e,m,b);k="";x=0;w=[];v=y=!1;for(a=0;a<b.lights.length;a++)if(n=b.lights[a],r=n._type,k+="uniform vec3 light"+a+"_color;\n",r===pc.LIGHTTYPE_DIRECTIONAL?k+="uniform vec3 light"+a+"_direction;\n":(k+="uniform vec3 light"+a+"_position;\n",k+="uniform float light"+a+"_radius;\n",r===pc.LIGHTTYPE_SPOT&&(k+="uniform vec3 light"+a+"_direction;\n",k+="uniform float light"+a+"_innerConeAngle;\n",k+="uniform float light"+
|
|
a+"_outerConeAngle;\n")),n.castShadows&&!b.noShadow&&(k+="uniform mat4 light"+a+"_shadowMatrix;\n",k=r!==pc.LIGHTTYPE_DIRECTIONAL?k+("uniform vec4 light"+a+"_shadowParams;\n"):k+("uniform vec3 light"+a+"_shadowParams;\n"),k=r===pc.LIGHTTYPE_POINT?k+("uniform samplerCube light"+a+"_shadowMap;\n"):n._isPcf&&e.webgl2?k+("uniform sampler2DShadow light"+a+"_shadowMap;\n"):k+("uniform sampler2D light"+a+"_shadowMap;\n"),x++,w[n._shadowType]=!0,n._isVsm&&(y=!0),n._isPcf&&(e.webgl2||e.extStandardDerivatives)&&
|
|
r===pc.LIGHTTYPE_SPOT&&(v=!0)),n._cookie)if(n._cookie._cubemap)r===pc.LIGHTTYPE_POINT&&(k+="uniform samplerCube light"+a+"_cookie;\n",k+="uniform float light"+a+"_cookieIntensity;\n",!n.castShadows||b.noShadow)&&(k+="uniform mat4 light"+a+"_shadowMatrix;\n");else if(r===pc.LIGHTTYPE_SPOT){k+="uniform sampler2D light"+a+"_cookie;\n";k+="uniform float light"+a+"_cookieIntensity;\n";if(!n.castShadows||b.noShadow)k+="uniform mat4 light"+a+"_shadowMatrix;\n";n._cookieTransform&&(k+="uniform vec4 light"+
|
|
a+"_cookieMatrix;\n",k+="uniform vec2 light"+a+"_cookieOffset;\n")}k+="\n";r=b.hasTangents?b.fastTbn?m.TBNfastPS:m.TBNPS:m.TBNderivativePS;h&&(b.normalMap?(k+=b.packedNormal?m.normalXYPS:m.normalXYZPS,a=this._getUvSourceExpression("normalMapTransform","normalMapUv",b),k=b.needsNormalFloat?k+(b.fastTbn?m.normalMapFloatTBNfastPS:m.normalMapFloatPS).replace(/\$UV/g,a):k+m.normalMapPS.replace(/\$UV/g,a),b.hasTangents||(r=r.replace(/\$UV/g,a)),k+=r):k+=m.normalVertexPS);k+=pc.programlib.gammaCode(b.gamma);
|
|
k+=pc.programlib.tonemapCode(b.toneMap);k+=pc.programlib.fogCode(b.fog);b.useRgbm&&(k+=m.rgbmPS);if(f||b.prefilteredCubemap)k+=b.fixSeams?m.fixCubemapSeamsStretchPS:m.fixCubemapSeamsNonePS;h&&(k+=0<b.cubeMapProjection?m.cubeMapProjectBoxPS:m.cubeMapProjectNonePS,k+=b.skyboxIntensity?m.envMultiplyPS:m.envConstPS);k+=this._addMap("diffuse","diffusePS",b,m);if(b.blendType!==pc.BLEND_NONE||b.alphaTest||b.alphaToCoverage)k+=this._addMap("opacity","opacityPS",b,m);k+=this._addMap("emissive","emissivePS",
|
|
b,m,b.emissiveFormat);b.useSpecular&&(d||g)&&(k=b.specularAntialias&&b.normalMap?b.needsNormalFloat&&h?k+m.specularAaToksvigFloatPS:k+m.specularAaToksvigPS:k+m.specularAaNonePS,a=b.useMetalness?"metalness":"specular",k+=this._addMap(a,a+"PS",b,m),k+=this._addMap("gloss","glossPS",b,m),0<b.fresnelModel&&(b.fresnelModel===pc.FRESNEL_SIMPLE?k+=m.fresnelSimplePS:b.fresnelModel===pc.FRESNEL_SCHLICK?k+=m.fresnelSchlickPS:b.fresnelModel===pc.FRESNEL_COMPLEX&&(k+=m.fresnelComplexPS)));b.heightMap&&(b.normalMap||
|
|
(a=this._getUvSourceExpression("heightMapTransform","heightMapUv",b),b.hasTangents||(r=r.replace(/\$UV/g,a)),k+=r),k+=this._addMap("height","parallaxPS",b,m));if(p=b.aoMap||b.aoVertexColor)k+=this._addMap("ao","aoPS",b,m),b.occludeSpecular&&(k=b.occludeSpecular===pc.SPECOCC_AO?k+(b.occludeSpecularFloat?m.aoSpecOccSimplePS:m.aoSpecOccConstSimplePS):k+(b.occludeSpecularFloat?m.aoSpecOccPS:m.aoSpecOccConstPS));r=b.rgbmReflection?"decodeRGBM":b.hdrReflection?"":"gammaCorrectInput";b.sphereMap?(r=16<e.fragmentUniformsCount?
|
|
m.reflectionSpherePS:m.reflectionSphereLowPS,r=r.replace(/\$texture2DSAMPLE/g,b.rgbmReflection?"texture2DRGBM":b.hdrReflection?"texture2D":"texture2DSRGB"),k+=r):f?k=b.prefilteredCubemap?l?k+m.reflectionPrefilteredCubeLodPS.replace(/\$DECODE/g,r):k+m.reflectionPrefilteredCubePS.replace(/\$DECODE/g,r):k+m.reflectionCubePS.replace(/\$textureCubeSAMPLE/g,b.rgbmReflection?"textureCubeRGBM":b.hdrReflection?"textureCube":"textureCubeSRGB"):b.dpAtlas&&(k+=m.reflectionDpAtlasPS.replace(/\$texture2DSAMPLE/g,
|
|
b.rgbmReflection?"texture2DRGBM":b.hdrReflection?"texture2D":"texture2DSRGB"));(f||b.sphereMap||b.dpAtlas)&&b.refraction&&(k+=m.refractionPS);0<x&&(w[pc.SHADOW_PCF3]&&(k+=m.shadowStandardPS),w[pc.SHADOW_PCF5]&&(k+=m.shadowStandardGL2PS),y&&(k+=m.shadowVSM_commonPS,w[pc.SHADOW_VSM8]&&(k+=m.shadowVSM8PS),w[pc.SHADOW_VSM16]&&(k+=e.extTextureHalfFloatLinear?m.shadowEVSMPS.replace(/\$/g,"16"):m.shadowEVSMnPS.replace(/\$/g,"16")),w[pc.SHADOW_VSM32]&&(k+=e.extTextureFloatLinear?m.shadowEVSMPS.replace(/\$/g,
|
|
"32"):m.shadowEVSMnPS.replace(/\$/g,"32"))),e.webgl2||e.extStandardDerivatives||(k+=m.biasConstPS),k+=m.shadowCoordPS+m.shadowCommonPS,v&&(k+=m.shadowCoordPerspZbufferPS),0<=u&&(w[pc.SHADOW_PCF3]&&(k+=m.shadowStandardVSPS),w[pc.SHADOW_PCF5]&&(k+=m.shadowStandardGL2VSPS),y&&(w[pc.SHADOW_VSM8]&&(k+=m.shadowVSMVSPS.replace(/\$VSM/g,"VSM8").replace(/\$/g,"8")),w[pc.SHADOW_VSM16]&&(k+=m.shadowVSMVSPS.replace(/\$VSM/g,"VSM16").replace(/\$/g,"16")),w[pc.SHADOW_VSM32]&&(k+=m.shadowVSMVSPS.replace(/\$VSM/g,
|
|
"VSM32").replace(/\$/g,"32")))));d&&(k+=m.lightDiffuseLambertPS);r=!1;b.useSpecular?(d&&(k+=b.shadingModel===pc.SPECULAR_PHONG?m.lightSpecularPhongPS:m.lightSpecularBlinnPS),b.sphereMap||f||b.dpAtlas||0<b.fresnelModel?k=0<b.fresnelModel?b.conserveEnergy?k+m.combineDiffuseSpecularPS:k+m.combineDiffuseSpecularNoConservePS:k+m.combineDiffuseSpecularOldPS:b.diffuseMap?k+=m.combineDiffuseSpecularNoReflPS:(k+=m.combineDiffuseSpecularNoReflSeparateAmbientPS,r=!0)):k+=m.combineDiffusePS;a=!0;if(b.lightMap||
|
|
b.lightVertexColor)k+=this._addMap("light",b.dirLightMap?"lightmapDirPS":"lightmapSinglePS",b,m,b.lightMapFormat),a=b.lightMapWithoutAmbient;a&&(n=b.rgbmAmbient?"decodeRGBM":b.hdrAmbient?"":"gammaCorrectInput",k=b.ambientSH?k+m.ambientSHPS:b.prefilteredCubemap?l?k+m.ambientPrefilteredCubeLodPS.replace(/\$DECODE/g,n):k+m.ambientPrefilteredCubePS.replace(/\$DECODE/g,n):k+m.ambientConstantPS);b.ambientTint&&!r&&(k+="uniform vec3 material_ambient;\n");b.alphaTest&&(k+=m.alphaTestPS);b.msdf&&(k+=m.msdfPS);
|
|
h&&(k+=m.viewDirPS,b.useSpecular&&(k+=m.reflDirPS));v=y=w=x=l=!1;k=this._fsAddStartCode(k,e,m,b);h&&(k=b.twoSidedLighting?k+" dVertexNormalW = gl_FrontFacing ? vNormalW : -vNormalW;\n":k+" dVertexNormalW = vNormalW;\n",(b.heightMap||b.normalMap)&&b.hasTangents&&(b.twoSidedLighting?(k+=" dTangentW = gl_FrontFacing ? vTangentW : -vTangentW;\n",k+=" dBinormalW = gl_FrontFacing ? vBinormalW : -vBinormalW;\n"):(k+=" dTangentW = vTangentW;\n",k+=" dBinormalW = vBinormalW;\n")));n=!1;b.blendType!==
|
|
pc.BLEND_NONE||b.alphaTest||b.alphaToCoverage?b.heightMap&&b.opacityMap?n=!0:(k+=" getOpacity();\n",b.alphaTest&&(k+=" alphaTest(dAlpha);\n")):k+=" dAlpha = 1.0;\n";if(h){k+=" getViewDir();\n";if(b.heightMap||b.normalMap)k+=" getTBN();\n";b.heightMap&&(k+=" getParallax();\n");n&&(k+=" getOpacity();\n",b.alphaTest&&(k+=" alphaTest(dAlpha);\n"));k+=" getNormal();\n";b.useSpecular&&(k+=" getReflDir();\n")}k+=" getAlbedo();\n";if(d&&b.useSpecular||g)k+=" getSpecularity();\n",k+=
|
|
" getGlossiness();\n",0<b.fresnelModel&&(k+=" getFresnel();\n");a&&(k+=" addAmbient();\n");b.ambientTint&&!r&&(k+=" dDiffuseLight *= material_ambient;\n");p&&!b.occludeDirect&&(k+=" applyAO();\n");if(b.lightMap||b.lightVertexColor)k+=" addLightMap();\n";if(d||g){if(f||b.sphereMap||b.dpAtlas)k+=" addReflection();\n";b.dirLightMap&&(k+=" addDirLightMap();\n");for(a=0;a<b.lights.length;a++)n=b.lights[a],r=n._type,g=!1,r===pc.LIGHTTYPE_DIRECTIONAL?(k+=" dLightDirNormW = light"+a+"_direction;\n",
|
|
k+=" dAtten = 1.0;\n"):(n._cookie&&(r!==pc.LIGHTTYPE_SPOT||n._cookie._cubemap?r===pc.LIGHTTYPE_POINT&&n._cookie._cubemap&&(g=v=!0):g=v=!0),k+=" getLightDirPoint(light"+a+"_position);\n",l=!0,g&&(k=r===pc.LIGHTTYPE_SPOT?k+(" dAtten3 = getCookie2D"+(n._cookieFalloff?"":"Clip")+(n._cookieTransform?"Xform":"")+"(light"+a+"_cookie, light"+a+"_shadowMatrix, light"+a+"_cookieIntensity"+(n._cookieTransform?", light"+a+"_cookieMatrix, light"+a+"_cookieOffset":"")+")."+n._cookieChannel+";\n"):k+(" dAtten3 = getCookieCube(light"+
|
|
a+"_cookie, light"+a+"_shadowMatrix, light"+a+"_cookieIntensity)."+n._cookieChannel+";\n")),n._falloffMode===pc.LIGHTFALLOFF_LINEAR?(k+=" dAtten = getFalloffLinear(light"+a+"_radius);\n",x=!0):(k+=" dAtten = getFalloffInvSquared(light"+a+"_radius);\n",w=!0),k+=" if (dAtten > 0.00001) {\n",r!==pc.LIGHTTYPE_SPOT||g&&!n._cookieFalloff||(k+=" dAtten *= getSpotEffect(light"+a+"_direction, light"+a+"_innerConeAngle, light"+a+"_outerConeAngle);\n",y=!0)),k+=" dAtten *= getLightDiffuse();\n",
|
|
n.castShadows&&!b.noShadow&&(n._shadowType===pc.SHADOW_VSM8?(h="VSM8",D="0.0"):n._shadowType===pc.SHADOW_VSM16?(h="VSM16",D="5.54"):n._shadowType===pc.SHADOW_VSM32?(h="VSM32",D=e.textureFloatHighPrecision?"15.0":"5.54"):h=n._shadowType===pc.SHADOW_PCF5?"PCF5x5":"PCF3x3",null!==h&&(r===pc.LIGHTTYPE_POINT?(d="(light"+a+"_shadowMap, light"+a+"_shadowParams);\n",n._normalOffsetBias&&(k+=" normalOffsetPointShadow(light"+a+"_shadowParams);\n"),k+=" dAtten *= getShadowPoint"+h+d):(u===a?h+="VS":
|
|
(d="(light"+a+"_shadowMatrix, light"+a+"_shadowParams);\n",k+=this._nonPointShadowMapProjection(e,b.lights[a],d)),r===pc.LIGHTTYPE_SPOT&&(h="Spot"+h),k+=" dAtten *= getShadow"+h+"(light"+a+"_shadowMap, light"+a+"_shadowParams"+(n._isVsm?", "+D:"")+");\n"))),k+=" dDiffuseLight += dAtten * light"+a+"_color"+(g?" * dAtten3":"")+";\n",b.useSpecular&&(k+=" dAtten *= getLightSpecular();\n",k+=" dSpecularLight += dAtten * light"+a+"_color"+(g?" * dAtten3":"")+";\n"),r!==pc.LIGHTTYPE_DIRECTIONAL&&
|
|
(k+=" }\n"),k+="\n";(f||b.sphereMap||b.dpAtlas)&&b.refraction&&(k+=" addRefraction();\n")}k+="\n";p&&(b.occludeDirect&&(k+=" applyAO();\n"),b.occludeSpecular&&(k+=" occludeSpecular();\n"));k+=m.endPS;k=b.blendType===pc.BLEND_NORMAL||b.blendType===pc.BLEND_ADDITIVEALPHA||b.alphaToCoverage?k+m.outputAlphaPS:b.blendType===pc.BLEND_PREMULTIPLIED?k+m.outputAlphaPremulPS:k+m.outputAlphaOpaquePS;b.msdf&&(k+=" gl_FragColor = applyMsdf(gl_FragColor);\n");k+="\n";k+=pc.programlib.end();l&&(k=m.lightDirPointPS+
|
|
k);x&&(k=m.falloffLinearPS+k);w&&(k=m.falloffInvSquaredPS+k);y&&(k=m.spotPS+k);v&&(k=m.cookiePS+k);m="";k.includes("dReflection")&&(m+="vec4 dReflection;\n");k.includes("dTBN")&&(m+="mat3 dTBN;\n");k.includes("dAlbedo")&&(m+="vec3 dAlbedo;\n");k.includes("dEmission")&&(m+="vec3 dEmission;\n");k.includes("dNormalW")&&(m+="vec3 dNormalW;\n");k.includes("dVertexNormalW")&&(m+="vec3 dVertexNormalW;\n");k.includes("dTangentW")&&(m+="vec3 dTangentW;\n");k.includes("dBinormalW")&&(m+="vec3 dBinormalW;\n");
|
|
k.includes("dViewDirW")&&(m+="vec3 dViewDirW;\n");k.includes("dReflDirW")&&(m+="vec3 dReflDirW;\n");k.includes("dDiffuseLight")&&(m+="vec3 dDiffuseLight;\n");k.includes("dSpecularLight")&&(m+="vec3 dSpecularLight;\n");k.includes("dLightDirNormW")&&(m+="vec3 dLightDirNormW;\n");k.includes("dLightDirW")&&(m+="vec3 dLightDirW;\n");k.includes("dLightPosW")&&(m+="vec3 dLightPosW;\n");k.includes("dShadowCoord")&&(m+="vec3 dShadowCoord;\n");k.includes("dNormalMap")&&(m+="vec3 dNormalMap;\n");k.includes("dSpecularity")&&
|
|
(m+="vec3 dSpecularity;\n");k.includes("dUvOffset")&&(m+="vec2 dUvOffset;\n");k.includes("dGlossiness")&&(m+="float dGlossiness;\n");k.includes("dAlpha")&&(m+="float dAlpha;\n");k.includes("dAtten")&&(m+="float dAtten;\n");k.includes("dAtten3")&&(m+="vec3 dAtten3;\n");k.includes("dAo")&&(m+="float dAo;\n");k.includes("dMsdf")&&(m+="vec4 dMsdf;\n");k=q+m+k;return{attributes:t,vshader:c,fshader:k,tag:pc.SHADERTAG_MATERIAL}}};pc.programlib.skybox={generateKey:function(e){return"skybox"+e.rgbm+" "+e.hdr+" "+e.fixSeams+""+e.toneMapping+""+e.gamma+""+e.useIntensity+""+e.mip},createShaderDefinition:function(e,b){var a=pc.shaderChunks;return{attributes:{aPosition:pc.SEMANTIC_POSITION},vshader:a.skyboxVS,fshader:pc.programlib.precisionCode(e)+(b.mip?a.fixCubemapSeamsStretchPS:a.fixCubemapSeamsNonePS)+(b.useIntensity?a.envMultiplyPS:a.envConstPS)+pc.programlib.gammaCode(b.gamma)+pc.programlib.tonemapCode(b.toneMapping)+a.rgbmPS+
|
|
a.skyboxHDRPS.replace(/\$textureCubeSAMPLE/g,b.rgbm?"textureCubeRGBM":b.hdr?"textureCube":"textureCubeSRGB").replace(/\$FIXCONST/g,1-1/[128,64,16,8,4,2][b.mip]+"")}}};Object.assign(pc,function(){var e={type:pc.PRIMITIVE_TRISTRIP,base:0,count:4,indexed:!1},b=function(a){this.device=a;this.depthMap=this.shader=null;this.vertexBuffer=pc.createFullscreenQuad(a);this.needsDepthBuffer=!1};Object.assign(b.prototype,{render:function(a,b,d){}});return{PostEffect:b,createFullscreenQuad:function(a){var b=new pc.VertexFormat(a,[{semantic:pc.SEMANTIC_POSITION,components:2,type:pc.TYPE_FLOAT32}]);a=new pc.VertexBuffer(a,b,4);b=new pc.VertexIterator(a);b.element[pc.SEMANTIC_POSITION].set(-1,
|
|
-1);b.next();b.element[pc.SEMANTIC_POSITION].set(1,-1);b.next();b.element[pc.SEMANTIC_POSITION].set(-1,1);b.next();b.element[pc.SEMANTIC_POSITION].set(1,1);b.end();return a},drawFullscreenQuad:function(a,b,d,f,g){var c=a.getRenderTarget();a.setRenderTarget(b);a.updateBegin();var h=null!==b?b.width:a.width,p=null!==b?b.height:a.height,k=0,n=0;g&&(k=g.x*h,n=g.y*p,h*=g.z,p*=g.w);g=a.vx;b=a.vy;var q=a.vw,m=a.vh;a.setViewport(k,n,h,p);var r=a.sx,t=a.sy,u=a.sw,x=a.sh;a.setScissor(k,n,h,p);var h=a.getBlending(),
|
|
p=a.getDepthTest(),k=a.getDepthWrite(),n=a.getCullMode(),v=a.writeRed,w=a.writeGreen,y=a.writeBlue,D=a.writeAlpha;a.setBlending(!1);a.setDepthTest(!1);a.setDepthWrite(!1);a.setCullMode(pc.CULLFACE_NONE);a.setColorWrite(!0,!0,!0,!0);a.setVertexBuffer(d,0);a.setShader(f);a.draw(e);a.setBlending(h);a.setDepthTest(p);a.setDepthWrite(k);a.setCullMode(n);a.setColorWrite(v,w,y,D);a.updateEnd();a.setRenderTarget(c);a.updateBegin();a.setViewport(g,b,q,m);a.setScissor(r,t,u,x)}}}());(function(){var e={BLEND_SUBTRACTIVE:0,BLEND_ADDITIVE:1,BLEND_NORMAL:2,BLEND_NONE:3,BLEND_PREMULTIPLIED:4,BLEND_MULTIPLICATIVE:5,BLEND_ADDITIVEALPHA:6,BLEND_MULTIPLICATIVE2X:7,BLEND_SCREEN:8,BLEND_MIN:9,BLEND_MAX:10,FOG_NONE:"none",FOG_LINEAR:"linear",FOG_EXP:"exp",FOG_EXP2:"exp2",FRESNEL_NONE:0,FRESNEL_SCHLICK:2,LAYER_HUD:0,LAYER_GIZMO:1,LAYER_FX:2,LAYER_WORLD:15,LAYERID_WORLD:0,LAYERID_DEPTH:1,LAYERID_SKYBOX:2,LAYERID_IMMEDIATE:3,LAYERID_UI:4,LIGHTTYPE_DIRECTIONAL:0,LIGHTTYPE_POINT:1,LIGHTTYPE_SPOT:2,
|
|
LIGHTFALLOFF_LINEAR:0,LIGHTFALLOFF_INVERSESQUARED:1,SHADOW_PCF3:0,SHADOW_DEPTH:0,SHADOW_VSM8:1,SHADOW_VSM16:2,SHADOW_VSM32:3,SHADOW_PCF5:4,BLUR_BOX:0,BLUR_GAUSSIAN:1,PARTICLESORT_NONE:0,PARTICLESORT_DISTANCE:1,PARTICLESORT_NEWER_FIRST:2,PARTICLESORT_OLDER_FIRST:3,PARTICLEMODE_GPU:0,PARTICLEMODE_CPU:1,EMITTERSHAPE_BOX:0,EMITTERSHAPE_SPHERE:1,PARTICLEORIENTATION_SCREEN:0,PARTICLEORIENTATION_WORLD:1,PARTICLEORIENTATION_EMITTER:2,PROJECTION_PERSPECTIVE:0,PROJECTION_ORTHOGRAPHIC:1,RENDERSTYLE_SOLID:0,
|
|
RENDERSTYLE_WIREFRAME:1,RENDERSTYLE_POINTS:2,CUBEPROJ_NONE:0,CUBEPROJ_BOX:1,SPECULAR_PHONG:0,SPECULAR_BLINN:1,GAMMA_NONE:0,GAMMA_SRGB:1,GAMMA_SRGBFAST:2,GAMMA_SRGBHDR:3,TONEMAP_LINEAR:0,TONEMAP_FILMIC:1,TONEMAP_HEJL:2,TONEMAP_ACES:3,TONEMAP_ACES2:4,SPECOCC_NONE:0,SPECOCC_AO:1,SPECOCC_GLOSSDEPENDENT:2,SHADERDEF_NOSHADOW:1,SHADERDEF_SKIN:2,SHADERDEF_UV0:4,SHADERDEF_UV1:8,SHADERDEF_VCOLOR:16,SHADERDEF_INSTANCING:32,SHADERDEF_LM:64,SHADERDEF_DIRLM:128,SHADERDEF_SCREENSPACE:256,SHADERDEF_TANGENTS:512,
|
|
LINEBATCH_WORLD:0,LINEBATCH_OVERLAY:1,LINEBATCH_GIZMO:2,SHADOWUPDATE_NONE:0,SHADOWUPDATE_THISFRAME:1,SHADOWUPDATE_REALTIME:2,SORTKEY_FORWARD:0,SORTKEY_DEPTH:1,MASK_DYNAMIC:1,MASK_BAKED:2,MASK_LIGHTMAP:4,SHADER_FORWARD:0,SHADER_FORWARDHDR:1,SHADER_DEPTH:2,SHADER_SHADOW:3,SHADER_PICK:18,BAKE_COLOR:0,BAKE_COLORDIR:1,VIEW_CENTER:0,VIEW_LEFT:1,VIEW_RIGHT:2,SORTMODE_NONE:0,SORTMODE_MANUAL:1,SORTMODE_MATERIALMESH:2,SORTMODE_BACK2FRONT:3,SORTMODE_FRONT2BACK:4,SORTMODE_CUSTOM:5,COMPUPDATED_INSTANCES:1,COMPUPDATED_LIGHTS:2,
|
|
COMPUPDATED_CAMERAS:4,COMPUPDATED_BLEND:8,ASPECT_AUTO:0,ASPECT_MANUAL:1,ORIENTATION_HORIZONTAL:0,ORIENTATION_VERTICAL:1};Object.assign(pc,e);pc.scene={};Object.assign(pc.scene,e)})();
|
|
Object.assign(pc,function(){var e=function(){this.root=null;this._gravity=new pc.Vec3(0,-9.8,0);this._layers=null;this._fog=pc.FOG_NONE;this.fogColor=new pc.Color(0,0,0);this.fogStart=1;this.fogEnd=1E3;this.fogDensity=0;this.ambientLight=new pc.Color(0,0,0);this._gammaCorrection=pc.GAMMA_NONE;this._toneMapping=0;this.exposure=1;this._skyboxPrefiltered=[null,null,null,null,null,null];this.skyboxModel=this._skyboxCubeMap=null;this._skyboxIntensity=1;this._skyboxMip=0;this.lightmapSizeMultiplier=1;this.lightmapMaxResolution=
|
|
2048;this.lightmapMode=pc.BAKE_COLORDIR;this._stats={meshInstances:0,lights:0,dynamicLights:0,bakedLights:0,lastStaticPrepareFullTime:0,lastStaticPrepareSearchTime:0,lastStaticPrepareWriteTime:0,lastStaticPrepareTriAabbTime:0,lastStaticPrepareCombineTime:0,updateShadersTime:0};this.updateSkybox=this.updateShaders=!0;this._shaderVersion=0;this._statsUpdated=!1;this._models=[];this.defaultMaterial=new pc.StandardMaterial;this.defaultMaterial.name="Default Material";this.defaultMaterial.shadingModel=
|
|
pc.SPECULAR_BLINN;pc.events.attach(this)};e.prototype.destroy=function(){this.root=null;this.defaultMaterial.destroy();this.defaultMaterial=null;this.off()};Object.defineProperty(e.prototype,"fog",{get:function(){return this._fog},set:function(b){b!==this._fog&&(this._fog=b,this.updateShaders=!0)}});Object.defineProperty(e.prototype,"gammaCorrection",{get:function(){return this._gammaCorrection},set:function(b){b!==this._gammaCorrection&&(this._gammaCorrection=b,this.updateShaders=!0)}});Object.defineProperty(e.prototype,
|
|
"toneMapping",{get:function(){return this._toneMapping},set:function(b){b!==this._toneMapping&&(this._toneMapping=b,this.updateShaders=!0)}});Object.defineProperty(e.prototype,"skybox",{get:function(){return this._skyboxCubeMap},set:function(b){this._skyboxCubeMap=b;this._resetSkyboxModel();this.updateShaders=!0}});Object.defineProperty(e.prototype,"skyboxIntensity",{get:function(){return this._skyboxIntensity},set:function(b){this._skyboxIntensity=b;this._resetSkyboxModel();this.updateShaders=!0}});
|
|
Object.defineProperty(e.prototype,"skyboxMip",{get:function(){return this._skyboxMip},set:function(b){this._skyboxMip=b;this._resetSkyboxModel();this.updateShaders=!0}});Object.defineProperty(e.prototype,"skyboxPrefiltered128",{get:function(){return this._skyboxPrefiltered[0]},set:function(b){this._skyboxPrefiltered[0]!==b&&(this._skyboxPrefiltered[0]=b,this.updateShaders=!0)}});Object.defineProperty(e.prototype,"skyboxPrefiltered64",{get:function(){return this._skyboxPrefiltered[1]},set:function(b){this._skyboxPrefiltered[1]!==
|
|
b&&(this._skyboxPrefiltered[1]=b,this.updateShaders=!0)}});Object.defineProperty(e.prototype,"skyboxPrefiltered32",{get:function(){return this._skyboxPrefiltered[2]},set:function(b){this._skyboxPrefiltered[2]!==b&&(this._skyboxPrefiltered[2]=b,this.updateShaders=!0)}});Object.defineProperty(e.prototype,"skyboxPrefiltered16",{get:function(){return this._skyboxPrefiltered[3]},set:function(b){this._skyboxPrefiltered[3]!==b&&(this._skyboxPrefiltered[3]=b,this.updateShaders=!0)}});Object.defineProperty(e.prototype,
|
|
"skyboxPrefiltered8",{get:function(){return this._skyboxPrefiltered[4]},set:function(b){this._skyboxPrefiltered[4]!==b&&(this._skyboxPrefiltered[4]=b,this.updateShaders=!0)}});Object.defineProperty(e.prototype,"skyboxPrefiltered4",{get:function(){return this._skyboxPrefiltered[5]},set:function(b){this._skyboxPrefiltered[5]!==b&&(this._skyboxPrefiltered[5]=b,this.updateShaders=!0)}});Object.defineProperty(e.prototype,"drawCalls",{get:function(){var b=this.layers._meshInstances;b.length||(this.layers._update(),
|
|
b=this.layers._meshInstances);return b},set:function(b){}});Object.defineProperty(e.prototype,"layers",{get:function(){return this._layers},set:function(b){var a=this._layers;this._layers=b;this.fire("set:layers",a,b)}});e.prototype.applySettings=function(b){this._gravity.set(b.physics.gravity[0],b.physics.gravity[1],b.physics.gravity[2]);this.ambientLight.set(b.render.global_ambient[0],b.render.global_ambient[1],b.render.global_ambient[2]);this._fog=b.render.fog;this.fogColor.set(b.render.fog_color[0],
|
|
b.render.fog_color[1],b.render.fog_color[2]);this.fogStart=b.render.fog_start;this.fogEnd=b.render.fog_end;this.fogDensity=b.render.fog_density;this._gammaCorrection=b.render.gamma_correction;this._toneMapping=b.render.tonemapping;this.lightmapSizeMultiplier=b.render.lightmapSizeMultiplier;this.lightmapMaxResolution=b.render.lightmapMaxResolution;this.lightmapMode=b.render.lightmapMode;this.exposure=b.render.exposure;this._skyboxIntensity=void 0===b.render.skyboxIntensity?1:b.render.skyboxIntensity;
|
|
this._skyboxMip=void 0===b.render.skyboxMip?0:b.render.skyboxMip;this._resetSkyboxModel();this.updateShaders=!0};e.prototype._updateSkybox=function(b){if(this._skyboxCubeMap&&!this.skyboxModel){var a=new pc.Material,c=this;a.updateShader=function(a,d,f,g,l){this.shader=b.getProgramLibrary().getProgram("skybox",{rgbm:c._skyboxCubeMap.rgbm,hdr:c._skyboxCubeMap.rgbm||c._skyboxCubeMap.format===pc.PIXELFORMAT_RGBA32F,useIntensity:1!==c.skyboxIntensity,mip:c._skyboxCubeMap.fixCubemapSeams?c.skyboxMip:0,
|
|
fixSeams:c._skyboxCubeMap.fixCubemapSeams,gamma:l===pc.SHADER_FORWARDHDR?c.gammaCorrection?pc.GAMMA_SRGBHDR:pc.GAMMA_NONE:c.gammaCorrection,toneMapping:l===pc.SHADER_FORWARDHDR?pc.TONEMAP_LINEAR:c.toneMapping})};a.updateShader();var d;if(this._skyboxCubeMap.fixCubemapSeams&&c._skyboxMip){var f=this["skyboxPrefiltered"+[null,"64","16","8","4"][c._skyboxMip]];f&&(d=f)}else d=this._skyboxCubeMap;a.setParameter("texture_cubeMap",d);a.cull=pc.CULLFACE_NONE;if(f=this.layers.getLayerById(pc.LAYERID_SKYBOX)){var g=
|
|
new pc.GraphNode,l=pc.createBox(b),a=new pc.MeshInstance(g,l,a);a.cull=!1;a._noDepthDrawGl1=!0;l=new pc.Model;l.graph=g;l.meshInstances=[a];this.skyboxModel=l;f.addMeshInstances(l.meshInstances);f.enabled=!0;this.skyLayer=f;this.fire("set:skybox",d)}}};e.prototype._resetSkyboxModel=function(){this.skyboxModel&&(this.skyLayer.removeMeshInstances(this.skyboxModel.meshInstances),this.skyLayer.enabled=!1);this.skyboxModel=null;this.updateSkybox=!0};e.prototype.setSkybox=function(b){var a;b||(b=[null,
|
|
null,null,null,null,null,null]);var c=!1;this._skyboxCubeMap!==b[0]&&(c=!0);if(!c)for(a=0;6>a&&!c;a++)this._skyboxPrefiltered[a]!==b[a+1]&&(c=!0);if(c){for(a=0;6>a;a++)this._skyboxPrefiltered[a]=b[a+1];this.skybox=b[0]}};e.prototype.destroy=function(){this.skybox=null};e.prototype.addModel=function(b){if(!this.containsModel(b)){var a=this.layers.getLayerById(pc.LAYERID_WORLD);a&&(a.addMeshInstances(b.meshInstances),this._models.push(b))}};e.prototype.addShadowCaster=function(b){var a=this.layers.getLayerById(pc.LAYERID_WORLD);
|
|
a&&a.addShadowCasters(b.meshInstances)};e.prototype.removeModel=function(b){var a=this._models.indexOf(b);if(-1!==a){var c=this.layers.getLayerById(pc.LAYERID_WORLD);c&&(c.removeMeshInstances(b.meshInstances),this._models.splice(a,1))}};e.prototype.removeShadowCasters=function(b){var a=this.layers.getLayerById(pc.LAYERID_WORLD);a&&a.removeShadowCasters(b.meshInstances)};e.prototype.containsModel=function(b){return 0<=this._models.indexOf(b)};e.prototype.getModels=function(b){return this._models};
|
|
return{Scene:e}}());Object.assign(pc,function(){function e(a,b){if(b!==pc.SHADOW_PCF3||a.webgl2){if(b===pc.SHADOW_VSM32)return a.extTextureFloatLinear?pc.FILTER_LINEAR:pc.FILTER_NEAREST;if(b===pc.SHADOW_VSM16)return a.extTextureHalfFloatLinear?pc.FILTER_LINEAR:pc.FILTER_NEAREST}else return pc.FILTER_NEAREST;return pc.FILTER_LINEAR}function b(a,b,c,d){var f=d===pc.SHADOW_VSM32?pc.PIXELFORMAT_RGBA32F:d===pc.SHADOW_VSM16?pc.PIXELFORMAT_RGBA16F:d===pc.SHADOW_PCF5||d===pc.SHADOW_PCF3&&a.webgl2?pc.PIXELFORMAT_DEPTH:pc.PIXELFORMAT_R8_G8_B8_A8,
|
|
g=e(a,d);b=new pc.Texture(a,{format:f,width:b,height:c,mipmaps:!1,minFilter:g,magFilter:g,addressU:pc.ADDRESS_CLAMP_TO_EDGE,addressV:pc.ADDRESS_CLAMP_TO_EDGE});b.name="shadowmap";return d===pc.SHADOW_PCF5||d===pc.SHADOW_PCF3&&a.webgl2?(b.compareOnRead=!0,b.compareFunc=pc.FUNC_LESS,new pc.RenderTarget({depthBuffer:b})):new pc.RenderTarget({colorBuffer:b,depth:!0})}function a(a,b){var c=new pc.Texture(a,{format:pc.PIXELFORMAT_R8_G8_B8_A8,width:b,height:b,cubemap:!0,mipmaps:!1,minFilter:pc.FILTER_NEAREST,
|
|
magFilter:pc.FILTER_NEAREST,addressU:pc.ADDRESS_CLAMP_TO_EDGE,addressV:pc.ADDRESS_CLAMP_TO_EDGE});c.name="shadowcube";for(var d=[],f,g=0;6>g;g++)f=new pc.RenderTarget({colorBuffer:c,face:g,depth:!0}),d.push(f);return d}function c(a){25<a&&(a=25);var b=(a-1)/6,c,d,f,g;g=.5*(a-1);d=Array(a);for(c=f=0;c<a;++c){var l=c-g;d[c]=Math.exp(-(l*l)/(2*b*b));f+=d[c]}for(c=0;c<a;++c)d[c]/=f;return d}function d(a,c,d,f){f||(f=0);f=1E4*f+c;var g=n[d][f];g||(g=b(a,c,c,d?d:pc.SHADOW_PCF3),n[d][f]=g);return g}function f(c,
|
|
f){var g;f._type===pc.LIGHTTYPE_POINT?(f._shadowType>pc.SHADOW_PCF3&&(f._shadowType=pc.SHADOW_PCF3),f._cacheShadowMap?(g=O[f._shadowResolution],g||(g=a(c,f._shadowResolution),O[f._shadowResolution]=g)):g=a(c,f._shadowResolution),f._shadowCamera.renderTarget=g[0],f._shadowCubeMap=g):(g=f._cacheShadowMap?d(c,f._shadowResolution,f._shadowType):b(c,f._shadowResolution,f._shadowResolution,f._shadowType),f._shadowCamera.renderTarget=g);f._isCachedShadowMap=f._cacheShadowMap}function g(a){a=this.device=
|
|
a;this._instancingTime=this._morphTime=this._skinTime=this._sortTime=this._cullTime=this._forwardTime=this._depthMapTime=this._shadowMapTime=this._shadowMapUpdates=this._materialSwitches=this._camerasRendered=this._skinDrawCalls=this._forwardDrawCalls=this._shadowDrawCalls=0;this.library=a.getProgramLibrary();a=a.scope;this.projId=a.resolve("matrix_projection");this.viewId=a.resolve("matrix_view");this.viewId3=a.resolve("matrix_view3");this.viewInvId=a.resolve("matrix_viewInverse");this.viewProjId=
|
|
a.resolve("matrix_viewProjection");this.viewPos=new Float32Array(3);this.viewPosId=a.resolve("view_position");this.nearClipId=a.resolve("camera_near");this.farClipId=a.resolve("camera_far");this.cameraParamsId=a.resolve("camera_params");this.shadowMapLightRadiusId=a.resolve("light_radius");this.fogColorId=a.resolve("fog_color");this.fogStartId=a.resolve("fog_start");this.fogEndId=a.resolve("fog_end");this.fogDensityId=a.resolve("fog_density");this.modelMatrixId=a.resolve("matrix_model");this.normalMatrixId=
|
|
a.resolve("matrix_normal");this.poseMatrixId=a.resolve("matrix_pose[0]");this.boneTextureId=a.resolve("texture_poseMap");this.boneTextureSizeId=a.resolve("texture_poseMapSize");this.alphaTestId=a.resolve("alpha_ref");this.opacityMapId=a.resolve("texture_opacityMap");this.ambientId=a.resolve("light_globalAmbient");this.exposureId=a.resolve("exposure");this.skyboxIntensityId=a.resolve("skyboxIntensity");this.lightColorId=[];this.lightDir=[];this.lightDirId=[];this.lightShadowMapId=[];this.lightShadowMatrixId=
|
|
[];this.lightShadowParamsId=[];this.lightShadowMatrixVsId=[];this.lightShadowParamsVsId=[];this.lightDirVs=[];this.lightDirVsId=[];this.lightRadiusId=[];this.lightPos=[];this.lightPosId=[];this.lightInAngleId=[];this.lightOutAngleId=[];this.lightPosVsId=[];this.lightCookieId=[];this.lightCookieIntId=[];this.lightCookieMatrixId=[];this.lightCookieOffsetId=[];this.depthMapId=a.resolve("uDepthMap");this.screenSizeId=a.resolve("uScreenSize");this._screenSize=new Float32Array(4);this.sourceId=a.resolve("source");
|
|
this.pixelOffsetId=a.resolve("pixelOffset");this.weightId=a.resolve("weight[0]");var b=pc.shaderChunks;this.blurVsmShaderCode=[b.blurVSMPS,"#define GAUSS\n"+b.blurVSMPS];this.blurPackedVsmShaderCode=["#define PACKED\n"+this.blurVsmShaderCode[0],"#define PACKED\n"+this.blurVsmShaderCode[1]];this.blurVsmShader=[{},{}];this.blurPackedVsmShader=[{},{}];this.blurVsmWeights={};this.polygonOffsetId=a.resolve("polygonOffset");this.polygonOffset=new Float32Array(2);this.fogColor=new Float32Array(3);this.ambientColor=
|
|
new Float32Array(3)}function l(a,b){a.data[0]=b.data[0];a.data[1]=b.data[1];a.data[2]=b.data[2];a.data[3]=b.data[4];a.data[4]=b.data[5];a.data[5]=b.data[6];a.data[6]=b.data[8];a.data[7]=b.data[9];a.data[8]=b.data[10]}for(var h=(new pc.Mat4).mul2((new pc.Mat4).setTranslate(.5,.5,.5),(new pc.Mat4).setScale(.5,.5,.5)),p={r:1,g:2,b:3,a:4},k=[(new pc.Quat).setFromEulerAngles(0,90,180),(new pc.Quat).setFromEulerAngles(0,-90,180),(new pc.Quat).setFromEulerAngles(90,0,0),(new pc.Quat).setFromEulerAngles(-90,
|
|
0,0),(new pc.Quat).setFromEulerAngles(0,180,180),(new pc.Quat).setFromEulerAngles(0,0,180)],n=[{},{},{},{},{}],q=new Float32Array(2),m={x:1,y:1,z:0,w:0},r=new pc.Mat4,t=new pc.Mat4,u=new pc.Mat4,x=new pc.Mat4,v=new pc.Mat4,w=new pc.Mat3,y=new pc.Mat4,D,B=new pc.Mat4,z=new pc.Mat4,A=new pc.Mat4,F=new pc.Mat4,I=new pc.Vec3,G=new pc.Vec3,H,C,E=new pc.Mat4,K=new pc.Mat4,N=new pc.Mat4,X=new pc.Mat4,M=new pc.Vec3,U={center:null,radius:0},aa,V=new pc.BoundingBox,P=[0,0],T,Y,L,Q,O={},J,ba,R=[],ca=0;8>ca;ca++)R.push(new pc.Vec3);
|
|
var S=[new pc.Vec3,new pc.Vec3,new pc.Vec3,new pc.Vec3,new pc.Vec3,new pc.Vec3,new pc.Vec3,new pc.Vec3];Object.assign(g.prototype,{sortCompare:function(a,b){if(a.layer===b.layer){if(a.drawOrder&&b.drawOrder)return a.drawOrder-b.drawOrder;if(a.zdist&&b.zdist)return b.zdist-a.zdist;if(a.zdist2&&b.zdist2)return a.zdist2-b.zdist2}return b._key[pc.SORTKEY_FORWARD]-a._key[pc.SORTKEY_FORWARD]},sortCompareMesh:function(a,b){if(a.layer===b.layer){if(a.drawOrder&&b.drawOrder)return a.drawOrder-b.drawOrder;
|
|
if(a.zdist&&b.zdist)return b.zdist-a.zdist}J=a._key[pc.SORTKEY_FORWARD];ba=b._key[pc.SORTKEY_FORWARD];return J===ba&&a.mesh&&b.mesh?b.mesh.id-a.mesh.id:ba-J},depthSortCompare:function(a,b){J=a._key[pc.SORTKEY_DEPTH];ba=b._key[pc.SORTKEY_DEPTH];return J===ba&&a.mesh&&b.mesh?b.mesh.id-a.mesh.id:ba-J},lightCompare:function(a,b){return a.key-b.key},_isVisible:function(a,b){if(!b.visible)return!1;if(b.isVisibleFunc)return b.isVisibleFunc(a);aa=b.aabb.center;b._aabb._radiusVer!==b._aabbVer&&(b._aabb._radius=
|
|
b._aabb.halfExtents.length(),b._aabb._radiusVer=b._aabbVer);U.radius=b._aabb._radius;U.center=aa;return a.frustum.containsSphere(U)},getShadowCamera:function(a,b){var c=b._shadowCamera,d;if(null===c){c=b._shadowType;d=pc.CLEARFLAG_DEPTH;var g=c===pc.SHADOW_PCF5||c===pc.SHADOW_PCF3&&a.webgl2;b._type===pc.LIGHTTYPE_POINT&&(g=!1);g||(d|=pc.CLEARFLAG_COLOR);g=new pc.Camera;c>=pc.SHADOW_VSM8&&c<=pc.SHADOW_VSM32?(g.clearColor[0]=0,g.clearColor[1]=0,g.clearColor[2]=0,g.clearColor[3]=0):(g.clearColor[0]=
|
|
1,g.clearColor[1]=1,g.clearColor[2]=1,g.clearColor[3]=1);g.clearDepth=1;g.clearFlags=d;g.clearStencil=null;g._node=new pc.GraphNode;c=b._shadowCamera=g;f(a,b)}else d=c.renderTarget,d.width===b._shadowResolution&&d.height===b._shadowResolution||f(a,b);return c},updateCameraFrustum:function(a){if(a.vrDisplay&&a.vrDisplay.presenting){D=a.vrDisplay.combinedProj;var b=a._node.getParent();b?v.copy(b.getWorldTransform()).mul(a.vrDisplay.combinedViewInv).invert():v.copy(a.vrDisplay.combinedView);x.copy(v).invert();
|
|
this.viewInvId.setValue(x.data)}else{D=a.getProjectionMatrix();a.overrideCalculateProjection&&a.calculateProjection(D,pc.VIEW_CENTER);if(a.overrideCalculateTransform)a.calculateTransform(x,pc.VIEW_CENTER);else{var b=a._node.getPosition(),c=a._node.getRotation();x.setTRS(b,c,pc.Vec3.ONE);this.viewInvId.setValue(x.data)}v.copy(x).invert()}a.frustum.update(D,v)},setCamera:function(a,b,c,d){var f=a.vrDisplay;if(f&&f.presenting){H=f.leftProj;C=f.rightProj;D=f.combinedProj;a.overrideCalculateProjection&&
|
|
(a.calculateProjection(H,pc.VIEW_LEFT),a.calculateProjection(C,pc.VIEW_RIGHT),a.calculateProjection(D,pc.VIEW_CENTER));if(a.overrideCalculateTransform)a.calculateTransform(B,pc.VIEW_LEFT),a.calculateTransform(z,pc.VIEW_RIGHT),a.calculateTransform(x,pc.VIEW_CENTER),A.copy(B).invert(),F.copy(z).invert(),v.copy(x).invert();else{var g=a._node.getParent();if(g){var h=g.getWorldTransform();B.mul2(h,f.leftViewInv);z.mul2(h,f.rightViewInv);A.copy(B).invert();F.copy(z).invert();v.copy(g.getWorldTransform()).mul(f.combinedViewInv).invert()}else B.copy(f.leftViewInv),
|
|
z.copy(f.rightViewInv),A.copy(f.leftView),F.copy(f.rightView),v.copy(f.combinedView)}l(E,A);l(K,F);N.mul2(H,A);X.mul2(C,F);I.x=B.data[12];I.y=B.data[13];I.z=B.data[14];G.x=z.data[12];G.y=z.data[13];G.z=z.data[14]}else D=a.getProjectionMatrix(),a.overrideCalculateProjection&&a.calculateProjection(D,pc.VIEW_CENTER),this.projId.setValue(D.data),a.overrideCalculateTransform?a.calculateTransform(x,pc.VIEW_CENTER):(f=a._node.getPosition(),g=a._node.getRotation(),x.setTRS(f,g,pc.Vec3.ONE)),this.viewInvId.setValue(x.data),
|
|
v.copy(x).invert(),this.viewId.setValue(v.data),l(w,v),this.viewId3.setValue(w.data),y.mul2(D,v),this.viewProjId.setValue(y.data),f=a._node.getPosition(),this.viewPos[0]=f.x,this.viewPos[1]=f.y,this.viewPos[2]=f.z,this.viewPosId.setValue(this.viewPos);a.frustum.update(D,v);this.nearClipId.setValue(a._nearClip);this.farClipId.setValue(a._farClip);this.cameraParamsId.setValue(a._shaderParams);f=this.device;f.setRenderTarget(b);f.updateBegin();h=a.getRect();g=b?b.width:f.width;b=b?b.height:f.height;
|
|
var e=Math.floor(h.x*g),k=Math.floor(h.y*b),p=Math.floor(h.width*g),h=Math.floor(h.height*b);f.setViewport(e,k,p,h);f.setScissor(e,k,p,h);c&&f.clear(a._clearOptions);h=a._scissorRect;e=Math.floor(h.x*g);k=Math.floor(h.y*b);p=Math.floor(h.width*g);h=Math.floor(h.height*b);f.setScissor(e,k,p,h);d&&f.setScissor(1,1,g-2,b-2)},dispatchGlobalLights:function(a){var b;this.mainLight=-1;this.ambientColor[0]=a.ambientLight.r;this.ambientColor[1]=a.ambientLight.g;this.ambientColor[2]=a.ambientLight.b;if(a.gammaCorrection)for(b=
|
|
0;3>b;b++)this.ambientColor[b]=Math.pow(this.ambientColor[b],2.2);this.ambientId.setValue(this.ambientColor);this.exposureId.setValue(a.exposure);a.skyboxModel&&this.skyboxIntensityId.setValue(a.skyboxIntensity)},_resolveLight:function(a,b){var c="light"+b;this.lightColorId[b]=a.resolve(c+"_color");this.lightDir[b]=new Float32Array(3);this.lightDirId[b]=a.resolve(c+"_direction");this.lightShadowMapId[b]=a.resolve(c+"_shadowMap");this.lightShadowMatrixId[b]=a.resolve(c+"_shadowMatrix");this.lightShadowParamsId[b]=
|
|
a.resolve(c+"_shadowParams");this.lightShadowMatrixVsId[b]=a.resolve(c+"_shadowMatrixVS");this.lightShadowParamsVsId[b]=a.resolve(c+"_shadowParamsVS");this.lightDirVs[b]=new Float32Array(3);this.lightDirVsId[b]=a.resolve(c+"_directionVS");this.lightRadiusId[b]=a.resolve(c+"_radius");this.lightPos[b]=new Float32Array(3);this.lightPosId[b]=a.resolve(c+"_position");this.lightInAngleId[b]=a.resolve(c+"_innerConeAngle");this.lightOutAngleId[b]=a.resolve(c+"_outerConeAngle");this.lightPosVsId[b]=a.resolve(c+
|
|
"_positionVS");this.lightCookieId[b]=a.resolve(c+"_cookie");this.lightCookieIntId[b]=a.resolve(c+"_cookieIntensity");this.lightCookieMatrixId[b]=a.resolve(c+"_cookieMatrix");this.lightCookieOffsetId[b]=a.resolve(c+"_cookieOffset")},dispatchDirectLights:function(a,b,c){var d=a.length,f,g,l,h=0;this.mainLight=-1;var e=this.device.scope;for(f=0;f<d;f++)if(a[f]._mask&c){g=a[f];l=g._node.getWorldTransform();this.lightColorId[h]||this._resolveLight(e,h);this.lightColorId[h].setValue(b.gammaCorrection?g._linearFinalColor:
|
|
g._finalColor);l.getY(g._direction).scale(-1);g._direction.normalize();this.lightDir[h][0]=g._direction.x;this.lightDir[h][1]=g._direction.y;this.lightDir[h][2]=g._direction.z;this.lightDirId[h].setValue(this.lightDir[h]);if(g.castShadows){var k=g._isPcf&&this.device.webgl2?g._shadowCamera.renderTarget.depthBuffer:g._shadowCamera.renderTarget.colorBuffer;g._isVsm?l=-2E-4:(l=g.shadowBias/g._shadowCamera._farClip*100,!this.device.webgl2&&this.device.extStandardDerivatives&&(l*=-100));var p=g._isVsm?
|
|
g.vsmBias/(g._shadowCamera._farClip/7):g._normalOffsetBias;this.lightShadowMapId[h].setValue(k);this.lightShadowMatrixId[h].setValue(g._shadowMatrix.data);k=g._rendererParams;3!==k.length&&(k.length=3);k[0]=g._shadowResolution;k[1]=p;k[2]=l;this.lightShadowParamsId[h].setValue(k);0>this.mainLight&&(this.lightShadowMatrixVsId[h].setValue(g._shadowMatrix.data),this.lightShadowParamsVsId[h].setValue(k),g._direction.normalize(),this.lightDirVs[h][0]=g._direction.x,this.lightDirVs[h][1]=g._direction.y,
|
|
this.lightDirVs[h][2]=g._direction.z,this.lightDirVsId[h].setValue(this.lightDirVs[h]),this.mainLight=f)}h++}return h},dispatchPointLight:function(a,b,c,d){var f=c._node.getWorldTransform();this.lightColorId[d]||this._resolveLight(b,d);this.lightRadiusId[d].setValue(c.attenuationEnd);this.lightColorId[d].setValue(a.gammaCorrection?c._linearFinalColor:c._finalColor);f.getTranslation(c._position);this.lightPos[d][0]=c._position.x;this.lightPos[d][1]=c._position.y;this.lightPos[d][2]=c._position.z;this.lightPosId[d].setValue(this.lightPos[d]);
|
|
c.castShadows&&(this.lightShadowMapId[d].setValue(c._shadowCamera.renderTarget.colorBuffer),a=c._rendererParams,4!==a.length&&(a.length=4),a[0]=c._shadowResolution,a[1]=c._normalOffsetBias,a[2]=c.shadowBias,a[3]=1/c.attenuationEnd,this.lightShadowParamsId[d].setValue(a));c._cookie&&(this.lightCookieId[d].setValue(c._cookie),this.lightShadowMatrixId[d].setValue(f.data),this.lightCookieIntId[d].setValue(c.cookieIntensity))},dispatchSpotLight:function(a,b,c,d){var f=c._node.getWorldTransform();this.lightColorId[d]||
|
|
this._resolveLight(b,d);this.lightInAngleId[d].setValue(c._innerConeAngleCos);this.lightOutAngleId[d].setValue(c._outerConeAngleCos);this.lightRadiusId[d].setValue(c.attenuationEnd);this.lightColorId[d].setValue(a.gammaCorrection?c._linearFinalColor:c._finalColor);f.getTranslation(c._position);this.lightPos[d][0]=c._position.x;this.lightPos[d][1]=c._position.y;this.lightPos[d][2]=c._position.z;this.lightPosId[d].setValue(this.lightPos[d]);f.getY(c._direction).scale(-1);c._direction.normalize();this.lightDir[d][0]=
|
|
c._direction.x;this.lightDir[d][1]=c._direction.y;this.lightDir[d][2]=c._direction.z;this.lightDirId[d].setValue(this.lightDir[d]);c.castShadows&&(c._isVsm?a=-2E-4:(a=20*c.shadowBias,!this.device.webgl2&&this.device.extStandardDerivatives&&(a*=-100)),b=c._isVsm?c.vsmBias/(c.attenuationEnd/7):c._normalOffsetBias,this.lightShadowMapId[d].setValue(c._isPcf&&this.device.webgl2?c._shadowCamera.renderTarget.depthBuffer:c._shadowCamera.renderTarget.colorBuffer),this.lightShadowMatrixId[d].setValue(c._shadowMatrix.data),
|
|
f=c._rendererParams,4!==f.length&&(f.length=4),f[0]=c._shadowResolution,f[1]=b,f[2]=a,f[3]=1/c.attenuationEnd,this.lightShadowParamsId[d].setValue(f));c._cookie&&(this.lightCookieId[d].setValue(c._cookie),c.castShadows||(a=this.getShadowCamera(this.device,c),b=a._node,b.setPosition(c._node.getPosition()),b.setRotation(c._node.getRotation()),b.rotateLocal(-90,0,0),a.projection=pc.PROJECTION_PERSPECTIVE,a.aspectRatio=1,a.fov=2*c._outerConeAngle,r.setTRS(b.getPosition(),b.getRotation(),pc.Vec3.ONE).invert(),
|
|
t.mul2(a.getProjectionMatrix(),r),c._shadowMatrix.mul2(h,t)),this.lightShadowMatrixId[d].setValue(c._shadowMatrix.data),this.lightCookieIntId[d].setValue(c.cookieIntensity),c._cookieTransform&&(c._cookieTransformUniform[0]=c._cookieTransform.x,c._cookieTransformUniform[1]=c._cookieTransform.y,c._cookieTransformUniform[2]=c._cookieTransform.z,c._cookieTransformUniform[3]=c._cookieTransform.w,this.lightCookieMatrixId[d].setValue(c._cookieTransformUniform),c._cookieOffsetUniform[0]=c._cookieOffset.x,
|
|
c._cookieOffsetUniform[1]=c._cookieOffset.y,this.lightCookieOffsetId[d].setValue(c._cookieOffsetUniform)))},dispatchLocalLights:function(a,b,c,d,f){var g,l=a[pc.LIGHTTYPE_POINT];a=a[pc.LIGHTTYPE_SPOT];var h=l.length,e=a.length,k=d,p=this.device.scope;for(d=0;d<h;d++)g=l[d],g._mask&c&&!g.isStatic&&(this.dispatchPointLight(b,p,g,k),k++);l=0;if(f)for(g=f[l];g&&g._type===pc.LIGHTTYPE_POINT;)this.dispatchPointLight(b,p,g,k),k++,l++,g=f[l];for(d=0;d<e;d++)g=a[d],g._mask&c&&!g.isStatic&&(this.dispatchSpotLight(b,
|
|
p,g,k),k++);if(f)for(g=f[l];g&&g._type===pc.LIGHTTYPE_SPOT;)this.dispatchSpotLight(b,p,g,k),k++,l++,g=f[l]},cull:function(a,b,c){var d=0,f,g,l,h=b.length,e=a.cullingMask||4294967295;if(!a.frustumCulling){for(f=0;f<h;f++)if(g=b[f],g.visible||g.command)g.mask&&0===(g.mask&e)||(c[d]=g,d++,g.visibleThisFrame=!0);return d}for(f=0;f<h;f++)g=b[f],g.command?(c[d]=g,d++,g.visibleThisFrame=!0):g.visible&&(l=!0,g.mask&&0===(g.mask&e)||(g.cull&&(l=this._isVisible(a,g)),l&&(c[d]=g,d++,g.visibleThisFrame=!0)));
|
|
return d},cullLights:function(a,b){var c,d,f;for(c=0;c<b.length;c++)d=b[c],f=d._type,d.castShadows&&d._enabled&&d.shadowUpdateMode!==pc.SHADOWUPDATE_NONE&&f!==pc.LIGHTTYPE_DIRECTIONAL&&(d.getBoundingSphere(U),a.frustum.containsSphere(U)&&(d.visibleThisFrame=!0))},updateCpuSkinMatrices:function(a){var b=a.length;if(0!==b){var c,d;for(c=0;c<b;c++)if(d=a[c].skinInstance)d.updateMatrices(a[c].node),d._dirty=!0}},updateGpuSkinMatrices:function(a){var b,c,d=a.length;for(b=0;b<d;b++)a[b].visibleThisFrame&&
|
|
(c=a[b].skinInstance)&&c._dirty&&(c.updateMatrixPalette(),c._dirty=!1)},updateMorphedBounds:function(a){var b,c,d=a.length;for(b=0;b<d;b++)(c=a[b].morphInstance)&&c._dirty&&c.updateBounds(a[b].mesh)},updateMorphing:function(a){var b,c,d=a.length;for(b=0;b<d;b++)a[b].visibleThisFrame&&(c=a[b].morphInstance)&&c._dirty&&(c.update(a[b].mesh),c._dirty=!1)},setBaseConstants:function(a,b){a.setCullMode(b.cull);b.opacityMap&&(this.opacityMapId.setValue(b.opacityMap),this.alphaTestId.setValue(b.alphaTest))},
|
|
setSkinning:function(a,b,c){b.skinInstance&&(this._skinDrawCalls++,a.supportsBoneTextures?(T=b.skinInstance.boneTexture,this.boneTextureId.setValue(T),P[0]=T.width,P[1]=T.height,this.boneTextureSizeId.setValue(P)):this.poseMatrixId.setValue(b.skinInstance.matrixPalette))},drawInstance:function(a,b,c,d,f){if(Y=b.instancingData){if(this._instancedDrawCalls++,this._removedByInstancing+=Y.count,a.setVertexBuffer(Y._buffer,1,Y.offset),a.draw(c.primitive[d],Y.count),Y._buffer===pc._autoInstanceBuffer)return b.instancingData=
|
|
null,Y.count-1}else return L=b.node.worldTransform,this.modelMatrixId.setValue(L.data),f&&(Q=b.node.normalMatrix,b.node._dirtyNormal&&(L.invertTo3x3(Q),Q.transpose(),b.node._dirtyNormal=!1),this.normalMatrixId.setValue(Q.data)),a.draw(c.primitive[d]),0},drawInstance2:function(a,b,c,d){if(Y=b.instancingData){if(this._instancedDrawCalls++,this._removedByInstancing+=Y.count,a.setVertexBuffer(Y._buffer,1,Y.offset),a.draw(c.primitive[d],Y.count),Y._buffer===pc._autoInstanceBuffer)return b.instancingData=
|
|
null,Y.count-1}else return a.draw(c.primitive[d]),0},renderShadows:function(a,b){var f=this.device,g,l,e,n,u,v,C,x,w,H,E,I,G,y,Q=1<<pc.SHADER_SHADOW,z,J;for(g=0;g<a.length;g++)if(e=a[g],u=e._type,e.castShadows&&e._enabled&&(e._shadowCamera||this.getShadowCamera(f,e),e.shadowUpdateMode!==pc.SHADOWUPDATE_NONE&&e.visibleThisFrame)){v=this.getShadowCamera(f,e);C=v._node;x=0;w=1;if(u===pc.LIGHTTYPE_DIRECTIONAL){if(0>e._visibleLength[b])continue;x=e._visibleCameraSettings[b];C.setPosition(x.x,x.y,x.z);
|
|
v.orthoHeight=x.orthoHeight;v.farClip=x.farClip;x=b}else u===pc.LIGHTTYPE_SPOT?(y=C.getPosition(),this.viewPos[0]=y.x,this.viewPos[1]=y.y,this.viewPos[2]=y.z,this.viewPosId.setValue(this.viewPos),this.shadowMapLightRadiusId.setValue(e.attenuationEnd)):u===pc.LIGHTTYPE_POINT&&(y=C.getPosition(),this.viewPos[0]=y.x,this.viewPos[1]=y.y,this.viewPos[2]=y.z,this.viewPosId.setValue(this.viewPos),this.shadowMapLightRadiusId.setValue(e.attenuationEnd),w=6);u!==pc.LIGHTTYPE_POINT&&(r.setTRS(C.getPosition(),
|
|
C.getRotation(),pc.Vec3.ONE).invert(),t.mul2(v.getProjectionMatrix(),r),e._shadowMatrix.mul2(h,t));f.webgl2?u===pc.LIGHTTYPE_POINT?f.setDepthBias(!1):(f.setDepthBias(!0),f.setDepthBiasValues(-1E3*e.shadowBias,-1E3*e.shadowBias)):f.extStandardDerivatives&&(u===pc.LIGHTTYPE_POINT?(this.polygonOffset[0]=0,this.polygonOffset[1]=0):(this.polygonOffset[0]=-1E3*e.shadowBias,this.polygonOffset[1]=-1E3*e.shadowBias),this.polygonOffsetId.setValue(this.polygonOffset));e.shadowUpdateMode===pc.SHADOWUPDATE_THISFRAME&&
|
|
(e.shadowUpdateMode=pc.SHADOWUPDATE_NONE);this._shadowMapUpdates+=w;f.setBlending(!1);f.setDepthWrite(!0);f.setDepthTest(!0);e._isPcf&&f.webgl2&&u!==pc.LIGHTTYPE_POINT?f.setColorWrite(!1,!1,!1,!1):f.setColorWrite(!0,!0,!0,!0);for(x?w=x+1:x=0;x<w;){u===pc.LIGHTTYPE_POINT&&(C.setRotation(k[x]),v.renderTarget=e._shadowCubeMap[x]);this.setCamera(v,v.renderTarget,!0,u!==pc.LIGHTTYPE_POINT);y=e._visibleList[x];E=e._visibleLength[x];l=e._shadowType;H=l+5*u;for(l=0;l<E;l++){I=y[l];G=I.mesh;n=I.material;this.setBaseConstants(f,
|
|
n);this.setSkinning(f,I,n);n.dirty&&(n.updateUniforms(),n.dirty=!1);if(n.chunks){J=n.parameters;for(z in J)n=J[z],n.passFlags&Q&&(n.scopeId||(n.scopeId=f.scope.resolve(z)),n.scopeId.setValue(n.data));J=I.parameters;for(z in J)n=J[z],n.passFlags&Q&&(n.scopeId||(n.scopeId=f.scope.resolve(z)),n.scopeId.setValue(n.data))}n=I._shader[pc.SHADER_SHADOW+H];if(!n){this.updateShader(I,I._shaderDefs,null,pc.SHADER_SHADOW+H);n=I._shader[pc.SHADER_SHADOW+H];J=I._key;var A=pc.SORTKEY_DEPTH,D=I.material,B=I.skinInstance?
|
|
10:0,W=0;D.opacityMap&&(D=D.opacityMapChannel)&&(W=p[D]);J[A]=B+W}f.setShader(n);n=I.renderStyle;f.setVertexBuffer(I.morphInstance&&I.morphInstance._vertexBuffer?I.morphInstance._vertexBuffer:G.vertexBuffer,0);f.setIndexBuffer(G.indexBuffer[n]);l+=this.drawInstance(f,I,G,n);this._shadowDrawCalls++}x++;u===pc.LIGHTTYPE_DIRECTIONAL&&(e._visibleLength[b]=-1)}e._isVsm&&(u=e._vsmBlurSize,1<u&&(v=v.renderTarget,C=d(f,e._shadowResolution,e._shadowType,1),w=e._shadowType===pc.SHADOW_VSM8,x=e.vsmBlurMode,
|
|
y=(w?this.blurPackedVsmShader:this.blurVsmShader)[x][u],y||(this.blurVsmWeights[u]=c(u),y=pc.shaderChunks.fullscreenQuadVS,l="#define SAMPLES "+u+"\n",l=w?l+this.blurPackedVsmShaderCode[x]:l+this.blurVsmShaderCode[x],y=pc.shaderChunks.createShaderFromCode(this.device,y,l,"blurVsm"+x+""+u+""+w),w?this.blurPackedVsmShader[x][u]=y:this.blurVsmShader[x][u]=y),m.z=e._shadowResolution-2,m.w=m.z,this.sourceId.setValue(v.colorBuffer),q[0]=1/e._shadowResolution,q[1]=0,this.pixelOffsetId.setValue(q),x===pc.BLUR_GAUSSIAN&&
|
|
this.weightId.setValue(this.blurVsmWeights[u]),pc.drawQuadWithShader(f,C,y,null,m),this.sourceId.setValue(C.colorBuffer),q[1]=q[0],q[0]=0,this.pixelOffsetId.setValue(q),pc.drawQuadWithShader(f,v,y,null,m)))}f.webgl2?f.setDepthBias(!1):f.extStandardDerivatives&&(this.polygonOffset[0]=0,this.polygonOffset[1]=0,this.polygonOffsetId.setValue(this.polygonOffset))},updateShader:function(a,b,c,d,f){a.material._scene=this.scene;a.material.updateShader(this.device,this.scene,b,c,d,f);a._shader[d]=a.material.shader},
|
|
renderForward:function(a,b,c,d,f,g,l,h){var e=this.device,k=this.scene,p=a.vrDisplay,n=1<<f;h=h?h._lightHash:0;var m,q,t,r,u,v,x,w,y=null,Q,J,D=.5*e.width;for(m=0;m<c;m++)if(q=b[m],!g||!q.mask||g&q.mask)if(q.command)q.command();else{t=q.mesh;r=q.material;u=q._shaderDefs;x=q.mask;this.setSkinning(e,q,r);r&&r===y&&u!==v&&(y=null);if(q.isStatic||Q)y=null;if(r!==y){this._materialSwitches++;r.dirty&&(r.updateUniforms(),r.dirty=!1);q._shader[f]&&q._shaderDefs===u&&q._lightHash===h||(q.isStatic?this.updateShader(q,
|
|
u,q._staticLightList,f,d):(v=f+"_"+u+"_"+h,q._shader[f]=r.variants[v],q._shader[f]||(this.updateShader(q,u,null,f,d),r.variants[v]=q._shader[f])),q._shaderDefs=u,q._lightHash=h);e.setShader(q._shader[f]);v=r.parameters;for(J in v)Q=v[J],Q.passFlags&n&&(Q.scopeId||(Q.scopeId=e.scope.resolve(J)),Q.scopeId.setValue(Q.data));y&&x===w||(w=this.dispatchDirectLights(d[pc.LIGHTTYPE_DIRECTIONAL],k,x),this.dispatchLocalLights(d,k,x,w,q._staticLightList));this.alphaTestId.setValue(r.alphaTest);e.setBlending(r.blend);
|
|
r.blend&&(r.separateAlphaBlend?(e.setBlendFunctionSeparate(r.blendSrc,r.blendDst,r.blendSrcAlpha,r.blendDstAlpha),e.setBlendEquationSeparate(r.blendEquation,r.blendAlphaEquation)):(e.setBlendFunction(r.blendSrc,r.blendDst),e.setBlendEquation(r.blendEquation)));e.setColorWrite(r.redWrite,r.greenWrite,r.blueWrite,r.alphaWrite);a._cullFaces?a._flipFaces?e.setCullMode(0<r.cull?r.cull===pc.CULLFACE_FRONT?pc.CULLFACE_BACK:pc.CULLFACE_FRONT:0):e.setCullMode(r.cull):e.setCullMode(pc.CULLFACE_NONE);e.setDepthWrite(r.depthWrite);
|
|
e.setDepthTest(r.depthTest);e.setAlphaToCoverage(r.alphaToCoverage);r.depthBias||r.slopeDepthBias?(e.setDepthBias(!0),e.setDepthBiasValues(r.depthBias,r.slopeDepthBias)):e.setDepthBias(!1)}w=q.stencilFront||r.stencilFront;y=q.stencilBack||r.stencilBack;w||y?(e.setStencilTest(!0),w===y?(e.setStencilFunc(w.func,w.ref,w.readMask),e.setStencilOperation(w.fail,w.zfail,w.zpass,w.writeMask)):(w?(e.setStencilFuncFront(w.func,w.ref,w.readMask),e.setStencilOperationFront(w.fail,w.zfail,w.zpass,w.writeMask)):
|
|
(e.setStencilFuncFront(pc.FUNC_ALWAYS,0,255),e.setStencilOperationFront(pc.STENCILOP_KEEP,pc.STENCILOP_KEEP,pc.STENCILOP_KEEPP,255)),y?(e.setStencilFuncBack(y.func,y.ref,y.readMask),e.setStencilOperationBack(y.fail,y.zfail,y.zpass,y.writeMask)):(e.setStencilFuncBack(pc.FUNC_ALWAYS,0,255),e.setStencilOperationBack(pc.STENCILOP_KEEP,pc.STENCILOP_KEEP,pc.STENCILOP_KEEP,255)))):e.setStencilTest(!1);v=q.parameters;for(J in v)Q=v[J],Q.passFlags&n&&(Q.scopeId||(Q.scopeId=e.scope.resolve(J)),Q.scopeId.setValue(Q.data));
|
|
e.setVertexBuffer(q.morphInstance&&q.morphInstance._vertexBuffer?q.morphInstance._vertexBuffer:t.vertexBuffer,0);w=q.renderStyle;e.setIndexBuffer(t.indexBuffer[w]);l&&l(q,m);p&&p.presenting?(e.setViewport(0,0,D,e.height),this.projId.setValue(H.data),this.viewInvId.setValue(B.data),this.viewId.setValue(A.data),this.viewId3.setValue(E.data),this.viewProjId.setValue(N.data),this.viewPos[0]=I.x,this.viewPos[1]=I.y,this.viewPos[2]=I.z,this.viewPosId.setValue(this.viewPos),m+=this.drawInstance(e,q,t,w,
|
|
!0),this._forwardDrawCalls++,e.setViewport(D,0,D,e.height),this.projId.setValue(C.data),this.viewInvId.setValue(z.data),this.viewId.setValue(F.data),this.viewId3.setValue(K.data),this.viewProjId.setValue(X.data),this.viewPos[0]=G.x,this.viewPos[1]=G.y,this.viewPos[2]=G.z,this.viewPosId.setValue(this.viewPos),m+=this.drawInstance2(e,q,t,w)):m+=this.drawInstance(e,q,t,w,!0);this._forwardDrawCalls++;if(m<c-1&&b[m+1].material===r)for(J in v)if(Q=r.parameters[J])Q.scopeId||(Q.scopeId=e.scope.resolve(J)),
|
|
Q.scopeId.setValue(Q.data);y=r;v=u;w=x;Q=q.isStatic}e.updateEnd()},setupInstancing:function(a){pc._instanceVertexFormat||(pc._instanceVertexFormat=new pc.VertexFormat(a,[{semantic:pc.SEMANTIC_TEXCOORD2,components:4,type:pc.TYPE_FLOAT32},{semantic:pc.SEMANTIC_TEXCOORD3,components:4,type:pc.TYPE_FLOAT32},{semantic:pc.SEMANTIC_TEXCOORD4,components:4,type:pc.TYPE_FLOAT32},{semantic:pc.SEMANTIC_TEXCOORD5,components:4,type:pc.TYPE_FLOAT32}]));a.enableAutoInstancing&&!pc._autoInstanceBuffer&&(pc._autoInstanceBuffer=
|
|
new pc.VertexBuffer(a,pc._instanceVertexFormat,a.autoInstancingMaxObjects,pc.BUFFER_DYNAMIC),pc._autoInstanceBufferData=new Float32Array(pc._autoInstanceBuffer.lock()))},revertStaticMeshes:function(a){var b,c=a.length,d,f=[],g;for(b=0;b<c;b++)d=a[b],d._staticSource?d._staticSource!==g&&(f.push(d._staticSource),g=d._staticSource):f.push(d);a.length=f.length;for(b=0;b<f.length;b++)a[b]=f[b]},prepareStaticMeshes:function(a,b){var c,d,f,g,l,h=this.device,e=a.length,k,p,n=[],m,q,t,r,u,v,w,x,C,H,E,I,y,
|
|
G,Q=new pc.Vec3,z=new pc.Vec3,J=new pc.BoundingBox,A=new pc.Mat4,D=[],B,O,F=[],W=[],R=[];for(c=0;c<e;c++)if(k=a[c],k.isStatic){m=k.aabb;R.length=0;for(B=pc.LIGHTTYPE_POINT;B<=pc.LIGHTTYPE_SPOT;B++)for(d=0;d<b.length;d++)p=b[d],p._type===B&&p._enabled&&p._mask&k.mask&&p.isStatic&&(F[d]||(F[d]=new pc.BoundingBox,p._node.getWorldTransform(),p.getBoundingSphere(U),F[d].center.copy(U.center),F[d].halfExtents.x=U.radius,F[d].halfExtents.y=U.radius,F[d].halfExtents.z=U.radius),F[d].intersects(m)&&R.push(d));
|
|
if(0===R.length)n.push(k);else{m=k.mesh;B=m.vertexBuffer;p=m.indexBuffer[k.renderStyle];q=2===p.bytesPerIndex?new Uint16Array(p.lock()):new Uint32Array(p.lock());t=m.primitive[k.renderStyle].count/3;w=m.primitive[k.renderStyle].base;r=B.format.elements;u=B.format.size/4;m=new Float32Array(B.storage);for(f=0;f<r.length;f++)r[f].name===pc.SEMANTIC_POSITION&&(v=r[f].offset/4);D.length=t;for(f=0;f<t;f++)D[f]=0;r=!1;W.length=6*t;for(f=0;f<t;f++){E=H=C=Number.MAX_VALUE;I=-Number.MAX_VALUE;y=-Number.MAX_VALUE;
|
|
G=-Number.MAX_VALUE;for(g=0;3>g;g++)d=q[3*f+g+w],d=d*u+v,l=m[d],x=m[d+1],d=m[d+2],l<C&&(C=l),x<H&&(H=x),d<E&&(E=d),l>I&&(I=l),x>y&&(y=x),d>G&&(G=d);d=6*f;W[d]=C;W[d+1]=H;W[d+2]=E;W[d+3]=I;W[d+4]=y;W[d+5]=G}for(l=0;l<R.length;l++)for(d=R[l],A.copy(k.node.worldTransform).invert(),J.setFromTransformedAabb(F[d],A),x=J.getMin(),C=J.getMax(),g=1<<l,f=0;f<t;f++)d=6*f,W[d]<=C.x&&W[d+3]>=x.x&&W[d+1]<=C.y&&W[d+4]>=x.y&&W[d+2]<=C.z&&W[d+5]>=x.z&&(D[f]|=g,r=!0);if(r){r={};for(f=0;f<t;f++)d=3*f+w,O=D[f],r[O]||
|
|
(r[O]=[]),g=r[O],g.push(q[d]),g.push(q[d+1]),g.push(q[d+2]);for(O in r){g=r[O];q=new pc.IndexBuffer(h,p.format,g.length,p.usage);(2===q.bytesPerIndex?new Uint16Array(q.lock()):new Uint32Array(q.lock())).set(g);q.unlock();E=H=C=Number.MAX_VALUE;I=-Number.MAX_VALUE;y=-Number.MAX_VALUE;G=-Number.MAX_VALUE;for(f=0;f<g.length;f++)d=g[f],l=m[d*u+v],x=m[d*u+v+1],d=m[d*u+v+2],l<C&&(C=l),x<H&&(H=x),d<E&&(E=d),l>I&&(I=l),x>y&&(y=x),d>G&&(G=d);Q.set(C,H,E);z.set(I,y,G);f=new pc.BoundingBox;f.setMinMax(Q,z);
|
|
t=new pc.Mesh;t.vertexBuffer=B;t.indexBuffer[0]=q;t.primitive[0].type=pc.PRIMITIVE_TRIANGLES;t.primitive[0].base=0;t.primitive[0].count=g.length;t.primitive[0].indexed=!0;t.aabb=f;q=new pc.MeshInstance(k.node,t,k.material);q.isStatic=k.isStatic;q.visible=k.visible;q.layer=k.layer;q.castShadow=k.castShadow;q._receiveShadow=k._receiveShadow;q.cull=k.cull;q.pick=k.pick;q.mask=k.mask;q.parameters=k.parameters;q._shaderDefs=k._shaderDefs;q._staticSource=k;q._staticLightList=k._staticLightList?k._staticLightList:
|
|
[];for(f=0;f<R.length;f++)g=1<<f,O&g&&(t=b[R[f]],0>q._staticLightList.indexOf(t)&&q._staticLightList.push(t));q._staticLightList.sort(this.lightCompare);n.push(q)}}else n.push(k)}}else n.push(k);a.length=n.length;for(c=0;c<n.length;c++)a[c]=n[c]},updateShaders:function(a){var b,c=[];for(b=0;b<a.length;b++){var d=a[b];void 0!==d.material&&-1===c.indexOf(d.material)&&c.push(d.material)}for(b=0;b<c.length;b++)a=c[b],a.updateShader!==pc.Material.prototype.updateShader&&(a.clearVariants(),a.shader=null)},
|
|
updateLitShaders:function(a){for(var b=0;b<a.length;b++){var c=a[b];void 0!==c.material&&(c=c.material,c.updateShader===pc.Material.prototype.updateShader||!1===c.useLighting||c.emitter&&!c.emitter.lighting||(c.clearVariants(),c.shader=null))}},beginFrame:function(a){var b=this.device,c=this.scene,d=a._meshInstances;a=a._lights;c.updateSkybox&&(c._updateSkybox(b),c.updateSkybox=!1);c.updateShaders?(this.updateShaders(d),c.updateShaders=!1,c.updateLitShaders=!1,c._shaderVersion++):c.updateLitShaders&&
|
|
(this.updateLitShaders(d),c.updateLitShaders=!1,c._shaderVersion++);this.updateCpuSkinMatrices(d);this.updateMorphedBounds(d);c=d.length;for(b=0;b<c;b++)d[b].visibleThisFrame=!1;c=a.length;for(b=0;b<c;b++)a[b].visibleThisFrame=a[b]._type===pc.LIGHTTYPE_DIRECTIONAL},beginLayers:function(a){var b=this.scene,c=a.layerList.length,d,f,g,l=this.scene._shaderVersion;for(f=0;f<c;f++)a.layerList[f]._postRenderCounter=0;for(f=0;f<c;f++){d=a.layerList[f];d._shaderVersion=l;d._preRenderCalledForCameras=0;d._postRenderCalledForCameras=
|
|
0;g=a.subLayerList[f];d._postRenderCounter=g?d._postRenderCounter|2:d._postRenderCounter|1;d._postRenderCounterMax=d._postRenderCounter;for(g=0;g<d.cameras.length;g++)d.instances.visibleOpaque[g]||(d.instances.visibleOpaque[g]=new pc.VisibleInstanceList),d.instances.visibleTransparent[g]||(d.instances.visibleTransparent[g]=new pc.VisibleInstanceList),d.instances.visibleOpaque[g].done=!1,d.instances.visibleTransparent[g].done=!1;d.cameras.length<d.instances.visibleOpaque.length&&d.instances.visibleOpaque.splice(d.cameras.length,
|
|
1);d.cameras.length<d.instances.visibleTransparent.length&&d.instances.visibleTransparent.splice(d.cameras.length,1);d._needsStaticPrepare&&d._staticLightHash&&(d._staticPrepareDone&&(this.revertStaticMeshes(d.opaqueMeshInstances),this.revertStaticMeshes(d.transparentMeshInstances)),this.prepareStaticMeshes(d.opaqueMeshInstances,d._lights),this.prepareStaticMeshes(d.transparentMeshInstances,d._lights),a._dirty=!0,b.updateShaders=!0,d._needsStaticPrepare=!1,d._staticPrepareDone=!0)}},cullLocalShadowmap:function(a,
|
|
b){var c,d,f,g,l,h,e,p,n,m,q;d=a._type;if(d!==pc.LIGHTTYPE_DIRECTIONAL)for(a.visibleThisFrame=!0,f=this.getShadowCamera(this.device,a),f.projection=pc.PROJECTION_PERSPECTIVE,f.nearClip=a.attenuationEnd/1E3,f.farClip=a.attenuationEnd,f.aspectRatio=1,d===pc.LIGHTTYPE_SPOT?(f.fov=2*a._outerConeAngle,l=1):(f.fov=90,l=6),g=f._node,c=a._node,g.setPosition(c.getPosition()),d===pc.LIGHTTYPE_SPOT&&(g.setRotation(c.getRotation()),g.rotateLocal(-90,0,0)),h=0;h<l;h++){d===pc.LIGHTTYPE_POINT&&(g.setRotation(k[h]),
|
|
f.renderTarget=a._shadowCubeMap[h]);this.updateCameraFrustum(f);(n=a._visibleList[h])||(n=a._visibleList[h]=[]);c=m=a._visibleLength[h]=0;for(e=b.length;c<e;c++)p=b[c],q=!0,p.cull&&(q=this._isVisible(f,p)),q&&(n[m]=p,m++,p.visibleThisFrame=!0);a._visibleLength[h]=m;n.length!==m&&(n.length=m);n.sort(this.depthSortCompare)}},cullDirectionalShadowmap:function(a,b,c,d){var f,g,l,h,e,k,p,n,m,q,t,v;g=this.device;a.visibleThisFrame=!0;g=this.getShadowCamera(g,a);l=g._node;h=a._node;l.setPosition(h.getPosition());
|
|
l.setRotation(h.getRotation());l.rotateLocal(-90,0,0);n=a.shadowDistance||c._farClip;m=c._nearClip;f=c._fov*Math.PI/180;e=c._aspect;k=c._projection;t=k===pc.PROJECTION_PERSPECTIVE?Math.tan(f/2)*m:c._orthoHeight;q=t*e;R[0].x=q;R[0].y=-t;R[0].z=-m;R[1].x=q;R[1].y=t;R[1].z=-m;R[2].x=-q;R[2].y=t;R[2].z=-m;R[3].x=-q;R[3].y=-t;R[3].z=-m;k===pc.PROJECTION_PERSPECTIVE&&(t=Math.tan(f/2)*n,q=t*e);R[4].x=q;R[4].y=-t;R[4].z=-n;R[5].x=q;R[5].y=t;R[5].z=-n;R[6].x=-q;R[6].y=t;R[6].z=-n;R[7].x=-q;R[7].y=-t;R[7].z=
|
|
-n;e=M.sub2(R[0],R[6]).length();e=Math.max(e,M.sub2(R[4],R[6]).length());r.copy(l.getWorldTransform()).invert();u.copy(r).mul(c._node.worldTransform);for(f=0;8>f;f++)u.transformPoint(R[f],R[f]);n=m=c=1E6;q=t=k=-1E6;for(f=0;8>f;f++)p=R[f],p.x<n&&(n=p.x),p.x>q&&(q=p.x),p.y<m&&(m=p.y),p.y>t&&(t=p.y),p.z<c&&(c=p.z),p.z>k&&(k=p.z);f=e/a._shadowResolution;n=Math.floor((n-.5*(e-(q-n)))/f)*f;m=Math.floor((m-.5*(e-(t-m)))/f)*f;n=.5*(n+e+n);m=.5*(m+e+m);l.translateLocal(n,m,1E5);g.projection=pc.PROJECTION_ORTHOGRAPHIC;
|
|
g.nearClip=0;g.farClip=2E5;g.aspectRatio=1;g.orthoHeight=.5*e;this.updateCameraFrustum(g);t=!0;(k=a._visibleList[d])||(k=a._visibleList[d]=[]);f=e=a._visibleLength[d]=0;for(q=b.length;f<q;f++)v=b[f],p=!0,v.cull&&(p=this._isVisible(g,v)),p&&(k[e]=v,e++,v.visibleThisFrame=!0,p=v.aabb,t?(V.copy(p),t=!1):V.add(p));a._visibleLength[d]=e;k.length!==e&&(k.length=e);k.sort(this.depthSortCompare);b=V.getMin();f=V.getMax();S[0].x=S[1].x=S[2].x=S[3].x=b.x;S[1].y=S[3].y=S[7].y=S[5].y=b.y;S[2].z=S[3].z=S[6].z=
|
|
S[7].z=b.z;S[4].x=S[5].x=S[6].x=S[7].x=f.x;S[0].y=S[2].y=S[4].y=S[6].y=f.y;S[0].z=S[1].z=S[4].z=S[5].z=f.z;f=9999999999;b=-9999999999;for(k=0;8>k;++k)r.transformPoint(S[k],S[k]),e=S[k].z,e<f&&(f=e),e>b&&(b=e);k=b;f>c&&(c=f);l.setPosition(h.getPosition());l.translateLocal(n,m,k+.01);g.farClip=k-c;(h=a._visibleCameraSettings[d])||(h=a._visibleCameraSettings[d]={});a=l.getPosition();h.x=a.x;h.y=a.y;h.z=a.z;h.orthoHeight=g.orthoHeight;h.farClip=g.farClip},gpuUpdate:function(a){this.updateGpuSkinMatrices(a);
|
|
this.updateMorphing(a)},clearView:function(a,b,c){a=a.camera;var d=this.device;d.setRenderTarget(b);d.updateBegin();d.setColorWrite(!0,!0,!0,!0);d.setDepthWrite(!0);var f=a.getRect(),g=b?b.width:d.width,l=b?b.height:d.height;b=Math.floor(f.x*g);var h=Math.floor(f.y*l),g=Math.floor(f.width*g),f=Math.floor(f.height*l);d.setViewport(b,h,g,f);d.setScissor(b,h,g,f);d.clear(c?c:a._clearOptions)},setSceneConstants:function(){var a,b=this.device,c=this.scene;this.dispatchGlobalLights(c);if(c.fog!==pc.FOG_NONE){this.fogColor[0]=
|
|
c.fogColor.r;this.fogColor[1]=c.fogColor.g;this.fogColor[2]=c.fogColor.b;if(c.gammaCorrection)for(a=0;3>a;a++)this.fogColor[a]=Math.pow(this.fogColor[a],2.2);this.fogColorId.setValue(this.fogColor);c.fog===pc.FOG_LINEAR?(this.fogStartId.setValue(c.fogStart),this.fogEndId.setValue(c.fogEnd)):this.fogDensityId.setValue(c.fogDensity)}this._screenSize[0]=b.width;this._screenSize[1]=b.height;this._screenSize[2]=1/b.width;this._screenSize[3]=1/b.height;this.screenSizeId.setValue(this._screenSize)},renderComposition:function(a){var b=
|
|
this.device,c,d=a._renderedRt,f=a._renderedByCam,g=a._renderedLayer,l,h,e,k,p,n,m,q;this.beginLayers(a);a._update()&pc.COMPUPDATED_LIGHTS&&(this.scene.updateLitShaders=!0);this.beginFrame(a);this.setSceneConstants();var t=0,r,u;for(l=0;l<a.layerList.length;l++)if(h=a.layerList[l],h.enabled&&a.subLayerEnabled[l])for(e=a.subLayerList[l],r=h.instances,k=h.cameras,p=0;p<k.length;p++)if(c=k[p]){c.frameBegin(h.renderTarget);u=e?h.transparentMeshInstances:h.opaqueMeshInstances;q=m=!1;for(n=0;n<t;n++)if(f[n]===
|
|
c&&(m=!0,g[n]===h)){q=!0;break}m||(this.updateCameraFrustum(c.camera),this._camerasRendered++);q||this.cullLights(c.camera,h._lights);m&&q||(f[t]=c,g[t]=h,t++);n=e?r.visibleTransparent[p]:r.visibleOpaque[p];if(!n.done){if(h.onPreCull)h.onPreCull(p);n.length=this.cull(c.camera,u,n.list);n.done=!0;if(h.onPostCull)h.onPostCull(p)}c.frameEnd()}for(l=0;l<a._lights.length;l++)c=a._lights[l],c.visibleThisFrame&&c._type!==pc.LIGHTTYPE_DIRECTIONAL&&c.castShadows&&c._enabled&&c.shadowUpdateMode!==pc.SHADOWUPDATE_NONE&&
|
|
(h=a._lightShadowCasters[l],this.cullLocalShadowmap(c,h));e=-1;for(l=0;l<a._lights.length;l++)if(c=a._lights[l],c._type===pc.LIGHTTYPE_DIRECTIONAL&&(e++,c.castShadows&&c._enabled&&c.shadowUpdateMode!==pc.SHADOWUPDATE_NONE))for(h=a._lightShadowCasters[l],k=a._globalLightCameras[e],p=0;p<k.length;p++)this.cullDirectionalShadowmap(c,h,k[p].camera,a._globalLightCameraIds[e][p]);this.gpuUpdate(a._meshInstances);this.renderShadows(a._sortedLights[pc.LIGHTTYPE_SPOT]);this.renderShadows(a._sortedLights[pc.LIGHTTYPE_POINT]);
|
|
for(l=t=0;l<a._renderList.length;l++)if(h=a.layerList[a._renderList[l]],h.enabled&&a.subLayerEnabled[a._renderList[l]]){r=h.instances;e=a.subLayerList[a._renderList[l]];k=a._renderListCamera[l];(c=h.cameras[k])&&c.frameBegin(h.renderTarget);if(!e&&h.onPreRenderOpaque)h.onPreRenderOpaque(k);else if(e&&h.onPreRenderTransparent)h.onPreRenderTransparent(k);if(!(h._preRenderCalledForCameras&1<<k)){if(h.onPreRender)h.onPreRender(k);h._preRenderCalledForCameras|=1<<k;h.overrideClear&&this.clearView(c,h.renderTarget,
|
|
h._clearOptions)}if(c){p=h.renderTarget;g=!1;for(n=0;n<t;n++)if(d[n]===p&&f[n]===c){g=!0;break}g||(h.overrideClear||this.clearView(c,h.renderTarget),d[t]=p,f[t]=c,t++);this.renderShadows(h._sortedLights[pc.LIGHTTYPE_DIRECTIONAL],k);h._sortVisible(e,c.node,k);n=e?r.visibleTransparent[k]:r.visibleOpaque[k];this.scene._activeCamera=c.camera;this.setCamera(c.camera,h.renderTarget);this.renderForward(c.camera,n.list,n.length,h._sortedLights,h.shaderPass,h.cullingMask,h.onDrawCall,h);b.setColorWrite(!0,
|
|
!0,!0,!0);b.setStencilTest(!1);b.setAlphaToCoverage(!1);b.setDepthBias(!1);c.frameEnd()}if(!e&&h.onPostRenderOpaque)h.onPostRenderOpaque(k);else if(e&&h.onPostRenderTransparent)h.onPostRenderTransparent(k);!h.onPostRender||h._postRenderCalledForCameras&1<<k||(h._postRenderCounter&=~(e?2:1),0===h._postRenderCounter&&(h.onPostRender(k),h._postRenderCalledForCameras|=1<<k,h._postRenderCounter=h._postRenderCounterMax))}}});return{ForwardRenderer:g,gaussWeights:c}}());Object.assign(pc,function(){var e=new pc.Mat4,b=new pc.Vec3,a=new pc.Quat,c=new pc.Quat,d=new pc.Vec3,f=new pc.Vec3,g=function(a){this.name="string"===typeof a?a:"Untitled";this.tags=new pc.Tags(this);this._labels={};this.localPosition=new pc.Vec3(0,0,0);this.localRotation=new pc.Quat(0,0,0,1);this.localScale=new pc.Vec3(1,1,1);this.localEulerAngles=new pc.Vec3(0,0,0);this.position=new pc.Vec3(0,0,0);this.rotation=new pc.Quat(0,0,0,1);this.eulerAngles=new pc.Vec3(0,0,0);this.localTransform=new pc.Mat4;
|
|
this._dirtyLocal=!1;this._aabbVer=0;this.worldTransform=new pc.Mat4;this._dirtyWorld=!1;this.normalMatrix=new pc.Mat3;this._dirtyNormal=!0;this._parent=this._forward=this._up=this._right=null;this._children=[];this._graphDepth=0;this._enabled=!0;this.scaleCompensation=this._enabledInHierarchy=!1};Object.defineProperty(g.prototype,"right",{get:function(){this._right||(this._right=new pc.Vec3);return this.getWorldTransform().getX(this._right).normalize()}});Object.defineProperty(g.prototype,"up",{get:function(){this._up||
|
|
(this._up=new pc.Vec3);return this.getWorldTransform().getY(this._up).normalize()}});Object.defineProperty(g.prototype,"forward",{get:function(){this._forward||(this._forward=new pc.Vec3);return this.getWorldTransform().getZ(this._forward).normalize().scale(-1)}});Object.defineProperty(g.prototype,"enabled",{get:function(){return this._enabled&&this._enabledInHierarchy},set:function(a){this._enabled!==a&&(this._enabled=a,this._parent&&!this._parent.enabled||this._notifyHierarchyStateChanged(this,
|
|
a))}});Object.defineProperty(g.prototype,"parent",{get:function(){return this._parent}});Object.defineProperty(g.prototype,"root",{get:function(){var a=this._parent;if(!a)return this;for(;a._parent;)a=a._parent;return a}});Object.defineProperty(g.prototype,"children",{get:function(){return this._children}});Object.defineProperty(g.prototype,"graphDepth",{get:function(){return this._graphDepth}});Object.assign(g.prototype,{_notifyHierarchyStateChanged:function(a,b){a._onHierarchyStateChanged(b);for(var c=
|
|
a._children,d=0,f=c.length;d<f;d++)c[d]._enabled&&this._notifyHierarchyStateChanged(c[d],b)},_onHierarchyStateChanged:function(a){this._enabledInHierarchy=a},_cloneInternal:function(a){a.name=this.name;for(var b=this.tags._list,c=0;c<b.length;c++)a.tags.add(b[c]);a._labels=Object.assign({},this._labels);a.localPosition.copy(this.localPosition);a.localRotation.copy(this.localRotation);a.localScale.copy(this.localScale);a.localEulerAngles.copy(this.localEulerAngles);a.position.copy(this.position);a.rotation.copy(this.rotation);
|
|
a.eulerAngles.copy(this.eulerAngles);a.localTransform.copy(this.localTransform);a._dirtyLocal=this._dirtyLocal;a.worldTransform.copy(this.worldTransform);a._dirtyWorld=this._dirtyWorld;a._dirtyNormal=this._dirtyNormal;a._aabbVer=this._aabbVer+1;a._enabled=this._enabled;a.scaleCompensation=this.scaleCompensation;a._enabledInHierarchy=!1},clone:function(){var a=new pc.GraphNode;this._cloneInternal(a);return a},find:function(a,b){var c=[],d=this._children.length,f,g;if(a instanceof Function)for(f=0;f<
|
|
d;f++)a(this._children[f])&&c.push(this._children[f]),g=this._children[f].find(a),g.length&&(c=c.concat(g));else for(this[a]&&(f=this[a]instanceof Function?this[a]():this[a],f===b&&c.push(this)),f=0;f<d;++f)g=this._children[f].find(a,b),g.length&&(c=c.concat(g));return c},findOne:function(a,b){var c,d=this._children.length,f;if(a instanceof Function){if(f=a(this))return this;for(c=0;c<d;c++)if(f=this._children[c].findOne(a))return this._children[c]}else{if(this[a]&&(c=this[a]instanceof Function?this[a]():
|
|
this[a],c===b))return this;for(c=0;c<d;c++)if(f=this._children[c].findOne(a,b),null!==f)return f}return null},findByTag:function(){var a=this.tags._processArguments(arguments);return this._findByTag(a)},_findByTag:function(a){var b=[],c,d=this._children.length,f;for(c=0;c<d;c++)this._children[c].tags._has(a)&&b.push(this._children[c]),f=this._children[c]._findByTag(a),f.length&&(b=b.concat(f));return b},findByName:function(a){if(this.name===a)return this;for(var b=0;b<this._children.length;b++){var c=
|
|
this._children[b].findByName(a);if(null!==c)return c}return null},findByPath:function(a){a=a.split("/");for(var b=this,c=null,d=0,f=a.length;d<f&&b;d++){for(var g=a[d],c=null,b=b._children,l=0,e=b.length;l<e;l++)if(b[l].name==g){c=b[l];break}b=c}return c},getPath:function(){var a=this._parent;if(a){for(var b=this.name;a&&a._parent;)b=pc.string.format("{0}/{1}",a.name,b),a=a._parent;return b}return""},getRoot:function(){var a=this._parent;if(!a)return this;for(;a._parent;)a=a._parent;return a},getParent:function(){return this._parent},
|
|
isDescendantOf:function(a){for(var b=this._parent;b;){if(b===a)return!0;b=b._parent}return!1},isAncestorOf:function(a){return a.isDescendantOf(this)},getChildren:function(){return this._children},getEulerAngles:function(){this.getWorldTransform().getEulerAngles(this.eulerAngles);return this.eulerAngles},getLocalEulerAngles:function(){this.localRotation.getEulerAngles(this.localEulerAngles);return this.localEulerAngles},getLocalPosition:function(){return this.localPosition},getLocalRotation:function(){return this.localRotation},
|
|
getLocalScale:function(){return this.localScale},getLocalTransform:function(){this._dirtyLocal&&(this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale),this._dirtyLocal=!1);return this.localTransform},getName:function(){return this.name},getPosition:function(){this.getWorldTransform().getTranslation(this.position);return this.position},getRotation:function(){this.rotation.setFromMat4(this.getWorldTransform());return this.rotation},getWorldTransform:function(){if(!this._dirtyLocal&&
|
|
!this._dirtyWorld)return this.worldTransform;this._parent&&this._parent.getWorldTransform();this._sync();return this.worldTransform},reparent:function(a,b){var c=this._parent;c&&c.removeChild(this);a&&(0<=b?a.insertChild(this,b):a.addChild(this))},setLocalEulerAngles:function(a,b,c){a instanceof pc.Vec3?this.localRotation.setFromEulerAngles(a.x,a.y,a.z):this.localRotation.setFromEulerAngles(a,b,c);this._dirtyLocal||this._dirtifyLocal()},setLocalPosition:function(a,b,c){a instanceof pc.Vec3?this.localPosition.copy(a):
|
|
this.localPosition.set(a,b,c);this._dirtyLocal||this._dirtifyLocal()},setLocalRotation:function(a,b,c,d){a instanceof pc.Quat?this.localRotation.copy(a):this.localRotation.set(a,b,c,d);this._dirtyLocal||this._dirtifyLocal()},setLocalScale:function(a,b,c){a instanceof pc.Vec3?this.localScale.copy(a):this.localScale.set(a,b,c);this._dirtyLocal||this._dirtifyLocal()},setName:function(a){this.name=a},_dirtifyLocal:function(){this._dirtyLocal||(this._dirtyLocal=!0,this._dirtyWorld||this._dirtifyWorld())},
|
|
_dirtifyWorld:function(){if(!this._dirtyWorld){this._dirtyWorld=!0;for(var a=0;a<this._children.length;a++)this._children[a]._dirtyWorld||this._children[a]._dirtifyWorld()}this._dirtyNormal=!0;this._aabbVer++},setPosition:function(){var a=new pc.Vec3,b=new pc.Mat4;return function(c,d,f){c instanceof pc.Vec3?a.copy(c):a.set(c,d,f);null===this._parent?this.localPosition.copy(a):(b.copy(this._parent.getWorldTransform()).invert(),b.transformPoint(a,this.localPosition));this._dirtyLocal||this._dirtifyLocal()}}(),
|
|
setRotation:function(){var a=new pc.Quat,b=new pc.Quat;return function(c,d,f,g){c instanceof pc.Quat?a.copy(c):a.set(c,d,f,g);null===this._parent?this.localRotation.copy(a):(c=this._parent.getRotation(),b.copy(c).invert(),this.localRotation.copy(b).mul(a));this._dirtyLocal||this._dirtifyLocal()}}(),setEulerAngles:function(){var a=new pc.Quat;return function(b,c,d){b instanceof pc.Vec3?this.localRotation.setFromEulerAngles(b.x,b.y,b.z):this.localRotation.setFromEulerAngles(b,c,d);null!==this._parent&&
|
|
(b=this._parent.getRotation(),a.copy(b).invert(),this.localRotation.mul2(a,this.localRotation));this._dirtyLocal||this._dirtifyLocal()}}(),addChild:function(a){if(null!==a._parent)throw Error("GraphNode is already parented");this._children.push(a);this._onInsertChild(a)},addChildAndSaveTransform:function(a){var b=a.getPosition(),c=a.getRotation(),d=a._parent;d&&d.removeChild(a);void 0===this.tmpMat4&&(this.tmpMat4=new pc.Mat4,this.tmpQuat=new pc.Quat);a.setPosition(this.tmpMat4.copy(this.worldTransform).invert().transformPoint(b));
|
|
a.setRotation(this.tmpQuat.copy(this.getRotation()).invert().mul(c));this._children.push(a);this._onInsertChild(a)},insertChild:function(a,b){if(null!==a._parent)throw Error("GraphNode is already parented");this._children.splice(b,0,a);this._onInsertChild(a)},_onInsertChild:function(a){a._parent=this;var b=a._enabled&&this.enabled;a._enabledInHierarchy!==b&&(a._enabledInHierarchy=b,a._notifyHierarchyStateChanged(a,b));a._updateGraphDepth();a._dirtifyWorld();a.fire&&a.fire("insert",this);this.fire&&
|
|
this.fire("childinsert",a)},_updateGraphDepth:function(){this._graphDepth=this._parent?this._parent._graphDepth+1:0;for(var a=0,b=this._children.length;a<b;a++)this._children[a]._updateGraphDepth()},removeChild:function(a){var b,c=this._children.length;for(b=0;b<c;++b)if(this._children[b]===a){this._children.splice(b,1);a._parent=null;this.fire&&this.fire("childremove",a);break}},addLabel:function(a){this._labels[a]=!0},getLabels:function(){return Object.keys(this._labels)},hasLabel:function(a){return!!this._labels[a]},
|
|
removeLabel:function(a){delete this._labels[a]},findByLabel:function(a,b){var c,d=this._children.length;b=b||[];this.hasLabel(a)&&b.push(this);for(c=0;c<d;++c)b=this._children[c].findByLabel(a,b);return b},_sync:function(){this._dirtyLocal&&(this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale),this._dirtyLocal=!1);if(this._dirtyWorld){if(null===this._parent)this.worldTransform.copy(this.localTransform);else if(this.scaleCompensation){var g,h=this._parent,p=this.localScale,
|
|
k=h;if(k){for(;k&&k.scaleCompensation;)k=k._parent;k&&(k=k._parent)&&(g=k.worldTransform.getScale(),d.mul2(g,this.localScale),p=d)}c.setFromMat4(h.worldTransform);a.mul2(c,this.localRotation);k=h.worldTransform;h.scaleCompensation&&(f.mul2(g,h.getLocalScale()),e.setTRS(h.worldTransform.getTranslation(b),c,f),k=e);k.transformPoint(this.localPosition,b);this.worldTransform.setTRS(b,a,p)}else this.worldTransform.mul2(this._parent.worldTransform,this.localTransform);this._dirtyWorld=!1}},syncHierarchy:function(){if(this._enabled){(this._dirtyLocal||
|
|
this._dirtyWorld)&&this._sync();for(var a=this._children,b=0,c=a.length;b<c;b++)a[b].syncHierarchy()}},lookAt:function(){var a=new pc.Mat4,b=new pc.Vec3,c=new pc.Vec3,d=new pc.Quat;return function(f,g,l,h,e,k){if(f instanceof pc.Vec3)b.copy(f),g instanceof pc.Vec3?c.copy(g):c.copy(pc.Vec3.UP);else{if(void 0===l)return;b.set(f,g,l);void 0!==h?c.set(h,e,k):c.copy(pc.Vec3.UP)}a.setLookAt(this.getPosition(),b,c);d.setFromMat4(a);this.setRotation(d)}}(),translate:function(){var a=new pc.Vec3;return function(b,
|
|
c,d){b instanceof pc.Vec3?a.copy(b):a.set(b,c,d);a.add(this.getPosition());this.setPosition(a)}}(),translateLocal:function(){var a=new pc.Vec3;return function(b,c,d){b instanceof pc.Vec3?a.copy(b):a.set(b,c,d);this.localRotation.transformVector(a,a);this.localPosition.add(a);this._dirtyLocal||this._dirtifyLocal()}}(),rotate:function(){var a=new pc.Quat,b=new pc.Quat;return function(c,d,f){c instanceof pc.Vec3?a.setFromEulerAngles(c.x,c.y,c.z):a.setFromEulerAngles(c,d,f);null===this._parent?this.localRotation.mul2(a,
|
|
this.localRotation):(c=this.getRotation(),d=this._parent.getRotation(),b.copy(d).invert(),a.mul2(b,a),this.localRotation.mul2(a,c));this._dirtyLocal||this._dirtifyLocal()}}(),rotateLocal:function(){var a=new pc.Quat;return function(b,c,d){b instanceof pc.Vec3?a.setFromEulerAngles(b.x,b.y,b.z):a.setFromEulerAngles(b,c,d);this.localRotation.mul(a);this._dirtyLocal||this._dirtifyLocal()}}()});return{GraphNode:g}}());Object.assign(pc,function(){var e=new pc.Vec3,b=new pc.Vec3,a=new pc.Vec3,c=new pc.Mat4,d=function(){this._projection=pc.PROJECTION_PERSPECTIVE;this._nearClip=.1;this._farClip=1E4;this._shaderParams=new Float32Array(4);this._fov=45;this._orthoHeight=10;this._aspect=16/9;this._aspectRatioMode=pc.ASPECT_AUTO;this.frustumCulling=this._horizontalFov=!1;this.cullingMask=4294967295;this._renderDepthRequests=0;this._projMatDirty=!0;this._projMat=new pc.Mat4;this._viewMatDirty=!0;this._viewMat=new pc.Mat4;
|
|
this._viewProjMatDirty=!0;this._viewProjMat=new pc.Mat4;this.vrDisplay=null;this._rect={x:0,y:0,width:1,height:1};this._scissorRect={x:0,y:0,width:1,height:1};this.frustum=new pc.Frustum(this._projMat,this._viewMat);this._depthTarget=this.renderTarget=null;this._clearOptions={color:[.5,.5,.5,1],depth:1,stencil:0,flags:pc.CLEARFLAG_COLOR|pc.CLEARFLAG_DEPTH|pc.CLEARFLAG_STENCIL};this.calculateTransform=this._node=null;this.overrideCalculateTransform=!1;this.calculateProjection=null;this.overrideCalculateProjection=
|
|
!1;this._cullFaces=!0;this._flipFaces=!1;this._component=null};Object.assign(d.prototype,{clone:function(){var a=new pc.Camera;a.projection=this._projection;a.nearClip=this._nearClip;a.farClip=this._farClip;a._shaderParams=this._shaderParams.slice();a.fov=this._fov;a.aspectRatio=this._aspect;a._aspectRatioMode=this._aspectRatioMode;a.renderTarget=this.renderTarget;a.setClearOptions(this.getClearOptions());a.frustumCulling=this.frustumCulling;a.cullingMask=this.cullingMask;return a},worldToScreen:function(a,
|
|
b,c,d){void 0===d&&(d=new pc.Vec3);if(this._projMatDirty||this._viewMatDirty||this._viewProjMatDirty){var f=this.getProjectionMatrix(),g=this.getViewMatrix();this._viewProjMat.mul2(f,g);this._viewProjMatDirty=!1}this._viewProjMat.transformPoint(a,d);f=this._viewProjMat.data;a=a.x*f[3]+a.y*f[7]+a.z*f[11]+1*f[15];d.x=.5*(d.x/a+1)*b;d.y=.5*(1-d.y/a)*c;return d},screenToWorld:function(d,g,l,h,p,k){void 0===k&&(k=new pc.Vec3);if(this._projMatDirty||this._viewMatDirty||this._viewProjMatDirty){var f=this.getProjectionMatrix(),
|
|
q=this.getViewMatrix();this._viewProjMat.mul2(f,q);this._viewProjMatDirty=!1}c.copy(this._viewProjMat).invert();this._projection===pc.PROJECTION_PERSPECTIVE?(b.set(d/h*2-1,(p-g)/p*2-1,1),c.transformPoint(b,a),a.scale(1/(b.x*c.data[3]+b.y*c.data[7]+b.z*c.data[11]+c.data[15])),d=l/this._farClip,k.lerp(this._node.getPosition(),a,d)):(e.set(d/h,(p-g)/p,l/(this._farClip-this._nearClip)),e.scale(2),e.sub(pc.Vec3.ONE),c.transformPoint(e,k));return k},getClearOptions:function(){return this._clearOptions},
|
|
getProjectionMatrix:function(){if(this._projMatDirty){if(this._projection===pc.PROJECTION_PERSPECTIVE)this._projMat.setPerspective(this._fov,this._aspect,this._nearClip,this._farClip,this._horizontalFov);else{var a=this._orthoHeight,b=a*this._aspect;this._projMat.setOrtho(-b,b,-a,a,this._nearClip,this._farClip)}a=this._nearClip;b=this._farClip;this._shaderParams[0]=1/b;this._shaderParams[1]=b;this._shaderParams[2]=(1-b/a)/2;this._shaderParams[3]=(1+b/a)/2;this._projMatDirty=!1}return this._projMat},
|
|
getViewMatrix:function(){if(this._viewMatDirty){var a=this._node.getWorldTransform();this._viewMat.copy(a).invert();this._viewMatDirty=!1}return this._viewMat},getRect:function(){return this._rect},setClearOptions:function(a){this._clearOptions.color[0]=a.color[0];this._clearOptions.color[1]=a.color[1];this._clearOptions.color[2]=a.color[2];this._clearOptions.color[3]=a.color[3];this._clearOptions.depth=a.depth;this._clearOptions.stencil=a.stencil;this._clearOptions.flags=a.flags},setRect:function(a,
|
|
b,c,d){this._rect.x=a;this._rect.y=b;this._rect.width=c;this._rect.height=d},setScissorRect:function(a,b,c,d){this._scissorRect.x=a;this._scissorRect.y=b;this._scissorRect.width=c;this._scissorRect.height=d},requestDepthMap:function(){this._renderDepthRequests++},releaseDepthMap:function(){this._renderDepthRequests--}});Object.defineProperty(d.prototype,"aspectRatio",{get:function(){return this._aspect},set:function(a){this._aspect!==a&&(this._aspect=a,this._projMatDirty=!0)}});Object.defineProperty(d.prototype,
|
|
"projection",{get:function(){return this._projection},set:function(a){this._projection!==a&&(this._projection=a,this._projMatDirty=!0)}});Object.defineProperty(d.prototype,"nearClip",{get:function(){return this._nearClip},set:function(a){this._nearClip!==a&&(this._nearClip=a,this._projMatDirty=!0)}});Object.defineProperty(d.prototype,"farClip",{get:function(){return this._farClip},set:function(a){this._farClip!==a&&(this._farClip=a,this._projMatDirty=!0)}});Object.defineProperty(d.prototype,"fov",
|
|
{get:function(){return this._fov},set:function(a){this._fov!==a&&(this._fov=a,this._projMatDirty=!0)}});Object.defineProperty(d.prototype,"horizontalFov",{get:function(){return this._horizontalFov},set:function(a){this._horizontalFov!==a&&(this._horizontalFov=a,this._projMatDirty=!0)}});Object.defineProperty(d.prototype,"orthoHeight",{get:function(){return this._orthoHeight},set:function(a){this._orthoHeight!==a&&(this._orthoHeight=a,this._projMatDirty=!0)}});Object.defineProperty(d.prototype,"clearColor",
|
|
{get:function(){return this._clearOptions.color},set:function(a){this._clearOptions.color[0]=a[0];this._clearOptions.color[1]=a[1];this._clearOptions.color[2]=a[2];this._clearOptions.color[3]=a[3]}});Object.defineProperty(d.prototype,"clearDepth",{get:function(){return this._clearOptions.depth},set:function(a){this._clearOptions.depth=a}});Object.defineProperty(d.prototype,"clearStencil",{get:function(){return this._clearOptions.stencil},set:function(a){this._clearOptions.stencil=a}});Object.defineProperty(d.prototype,
|
|
"clearFlags",{get:function(){return this._clearOptions.flags},set:function(a){this._clearOptions.flags=a}});return{Camera:d}}());Object.assign(pc,function(){var e=new pc.Vec3,b=new pc.Vec3,a=new pc.Vec3,c={r:0,g:1,b:2,a:3},d=function(){this._type=pc.LIGHTTYPE_DIRECTIONAL;this._color=new pc.Color(.8,.8,.8);this._intensity=1;this._enabled=this._castShadows=!1;this._mask=1;this.isStatic=!1;this.key=0;this.bakeDir=!0;this.attenuationEnd=this.attenuationStart=10;this._falloffMode=0;this._shadowType=pc.SHADOW_PCF3;this._vsmBlurSize=11;this.vsmBlurMode=pc.BLUR_GAUSSIAN;this.vsmBias=.0025;this._cookie=null;this.cookieIntensity=1;this._cookieFalloff=
|
|
!0;this._cookieChannel="rgb";this._cookieTransform=null;this._cookieTransformUniform=new Float32Array(4);this._cookieOffset=null;this._cookieOffsetUniform=new Float32Array(2);this._cookieOffsetSet=this._cookieTransformSet=!1;this._innerConeAngle=40;this._outerConeAngle=45;this._finalColor=new Float32Array([.8,.8,.8]);var a=Math.pow(this._finalColor[0],2.2);this._linearFinalColor=new Float32Array([a,a,a]);this._position=new pc.Vec3(0,0,0);this._direction=new pc.Vec3(0,0,0);this._innerConeAngleCos=
|
|
Math.cos(this._innerConeAngle*Math.PI/180);this._outerConeAngleCos=Math.cos(this._outerConeAngle*Math.PI/180);this._shadowCamera=null;this._shadowMatrix=new pc.Mat4;this.shadowDistance=40;this._shadowResolution=1024;this.shadowBias=-5E-4;this._normalOffsetBias=0;this.shadowUpdateMode=pc.SHADOWUPDATE_REALTIME;this._node=this._scene=null;this._rendererParams=[];this._isVsm=!1;this._isPcf=!0;this._isCachedShadowMap=this._cacheShadowMap=!1;this._visibleLength=[0];this._visibleList=[[]];this._visibleCameraSettings=
|
|
[]};Object.assign(d.prototype,{destroy:function(){this._destroyShadowMap()},clone:function(){var a=new pc.Light;a.type=this._type;a.setColor(this._color);a.intensity=this._intensity;a.castShadows=this.castShadows;a.enabled=this._enabled;a.attenuationStart=this.attenuationStart;a.attenuationEnd=this.attenuationEnd;a.falloffMode=this._falloffMode;a.shadowType=this._shadowType;a.vsmBlurSize=this._vsmBlurSize;a.vsmBlurMode=this.vsmBlurMode;a.vsmBias=this.vsmBias;a.shadowUpdateMode=this.shadowUpdateMode;
|
|
a.mask=this._mask;a.innerConeAngle=this._innerConeAngle;a.outerConeAngle=this._outerConeAngle;a.shadowBias=this.shadowBias;a.normalOffsetBias=this._normalOffsetBias;a.shadowResolution=this._shadowResolution;a.shadowDistance=this.shadowDistance;return a},getColor:function(){return this._color},getBoundingSphere:function(c){if(this._type===pc.LIGHTTYPE_SPOT){var d=this.attenuationEnd,f=this._outerConeAngle,h=Math.cos(f*pc.math.DEG_TO_RAD),p=this._node;e.copy(p.up);e.scale(.5*-d*h);e.add(p.getPosition());
|
|
c.center=e;b.copy(p.up);b.scale(-d);a.copy(p.right);a.scale(Math.sin(f*pc.math.DEG_TO_RAD)*d);b.add(a);c.radius=.5*b.length()}else this._type===pc.LIGHTTYPE_POINT&&(c.center=this._node.getPosition(),c.radius=this.attenuationEnd)},getBoundingBox:function(a){if(this._type===pc.LIGHTTYPE_SPOT){var b=this.attenuationEnd,c=this._node,d=Math.abs(Math.sin(this._outerConeAngle*pc.math.DEG_TO_RAD)*b);a.center.set(0,.5*-b,0);a.halfExtents.set(d,.5*b,d);a.setFromTransformedAabb(a,c.getWorldTransform())}else this._type===
|
|
pc.LIGHTTYPE_POINT&&(a.center.copy(this._node.getPosition()),a.halfExtents.set(this.attenuationEnd,this.attenuationEnd,this.attenuationEnd))},_updateFinalColor:function(){var a=this._color,b=a.r,c=a.g,a=a.b,d=this._intensity,e=this._finalColor,k=this._linearFinalColor;e[0]=b*d;e[1]=c*d;e[2]=a*d;1<=d?(k[0]=Math.pow(b,2.2)*d,k[1]=Math.pow(c,2.2)*d,k[2]=Math.pow(a,2.2)*d):(k[0]=Math.pow(e[0],2.2),k[1]=Math.pow(e[1],2.2),k[2]=Math.pow(e[2],2.2))},setColor:function(){var a,b,c;1===arguments.length?(a=
|
|
arguments[0].r,b=arguments[0].g,c=arguments[0].b):3===arguments.length&&(a=arguments[0],b=arguments[1],c=arguments[2]);this._color.set(a,b,c);this._updateFinalColor()},_destroyShadowMap:function(){if(this._shadowCamera){if(!this._isCachedShadowMap){var a=this._shadowCamera.renderTarget,b;if(a)if(a.length)for(b=0;b<a.length;b++)a[b].colorBuffer&&a[b].colorBuffer.destroy(),a[b].destroy();else a.colorBuffer&&a.colorBuffer.destroy(),a.depthBuffer&&a.depthBuffer.destroy(),a.destroy()}this._shadowCubeMap=
|
|
this._shadowCamera=this._shadowCamera.renderTarget=null;this.shadowUpdateMode===pc.SHADOWUPDATE_NONE&&(this.shadowUpdateMode=pc.SHADOWUPDATE_THISFRAME)}},updateShadow:function(){this.shadowUpdateMode!==pc.SHADOWUPDATE_REALTIME&&(this.shadowUpdateMode=pc.SHADOWUPDATE_THISFRAME)},updateKey:function(){var a=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|c[this._cookieChannel.charAt(0)]<<
|
|
18|(this._cookieTransform?1:0)<<12;3===this._cookieChannel.length&&(a|=c[this._cookieChannel.charAt(1)]<<16,a|=c[this._cookieChannel.charAt(2)]<<14);a!==this.key&&null!==this._scene&&(this._scene.layers._dirtyLights=!0);this.key=a}});Object.defineProperty(d.prototype,"enabled",{get:function(){return this._type},set:function(a){this._type!==a&&(this._enabled=a)}});Object.defineProperty(d.prototype,"type",{get:function(){return this._type},set:function(a){this._type!==a&&(this._type=a,this._destroyShadowMap(),
|
|
this.updateKey(),a=this._shadowType,this._shadowType=null,this.shadowType=a)}});Object.defineProperty(d.prototype,"mask",{get:function(){return this._mask},set:function(a){this._mask!==a&&(this._mask=a)}});Object.defineProperty(d.prototype,"shadowType",{get:function(){return this._shadowType},set:function(a){if(this._shadowType!==a){var b=pc.Application.getApplication().graphicsDevice;this._type===pc.LIGHTTYPE_POINT&&(a=pc.SHADOW_PCF3);a!==pc.SHADOW_PCF5||b.webgl2||(a=pc.SHADOW_PCF3);a!==pc.SHADOW_VSM32||
|
|
b.textureFloatRenderable||(a=pc.SHADOW_VSM16);a!==pc.SHADOW_VSM16||b.textureHalfFloatRenderable||(a=pc.SHADOW_VSM8);this._isVsm=a>=pc.SHADOW_VSM8&&a<=pc.SHADOW_VSM32;this._isPcf=a===pc.SHADOW_PCF5||a===pc.SHADOW_PCF3;this._shadowType=a;this._destroyShadowMap();this.updateKey()}}});Object.defineProperty(d.prototype,"castShadows",{get:function(){return this._castShadows&&this._mask!==pc.MASK_LIGHTMAP&&0!==this._mask},set:function(a){this._castShadows!==a&&(this._castShadows=a,this.updateKey())}});Object.defineProperty(d.prototype,
|
|
"shadowResolution",{get:function(){return this._shadowResolution},set:function(a){if(this._shadowResolution!==a){var b=pc.Application.getApplication().graphicsDevice;this._shadowResolution=a=this._type===pc.LIGHTTYPE_POINT?Math.min(a,b.maxCubeMapSize):Math.min(a,b.maxTextureSize)}}});Object.defineProperty(d.prototype,"vsmBlurSize",{get:function(){return this._vsmBlurSize},set:function(a){this._vsmBlurSize!==a&&(0===a%2&&a++,this._vsmBlurSize=a)}});Object.defineProperty(d.prototype,"normalOffsetBias",
|
|
{get:function(){return this._normalOffsetBias},set:function(a){this._normalOffsetBias!==a&&((!this._normalOffsetBias&&a||this._normalOffsetBias&&!a)&&this.updateKey(),this._normalOffsetBias=a)}});Object.defineProperty(d.prototype,"falloffMode",{get:function(){return this._falloffMode},set:function(a){this._falloffMode!==a&&(this._falloffMode=a,this.updateKey())}});Object.defineProperty(d.prototype,"innerConeAngle",{get:function(){return this._innerConeAngle},set:function(a){this._innerConeAngle!==
|
|
a&&(this._innerConeAngle=a,this._innerConeAngleCos=Math.cos(a*Math.PI/180))}});Object.defineProperty(d.prototype,"outerConeAngle",{get:function(){return this._outerConeAngle},set:function(a){this._outerConeAngle!==a&&(this._outerConeAngle=a,this._outerConeAngleCos=Math.cos(a*Math.PI/180))}});Object.defineProperty(d.prototype,"intensity",{get:function(){return this._intensity},set:function(a){this._intensity!==a&&(this._intensity=a,this._updateFinalColor())}});Object.defineProperty(d.prototype,"cookie",
|
|
{get:function(){return this._cookie},set:function(a){this._cookie!==a&&(this._cookie=a,this.updateKey())}});Object.defineProperty(d.prototype,"cookieFalloff",{get:function(){return this._cookieFalloff},set:function(a){this._cookieFalloff!==a&&(this._cookieFalloff=a,this.updateKey())}});Object.defineProperty(d.prototype,"cookieChannel",{get:function(){return this._cookieChannel},set:function(a){if(this._cookieChannel!==a){if(3>a.length)for(var b=a.charAt(a.length-1),c=3-a.length,d=0;d<c;d++)a+=b;this._cookieChannel=
|
|
a;this.updateKey()}}});Object.defineProperty(d.prototype,"cookieTransform",{get:function(){return this._cookieTransform},set:function(a){this._cookieTransform!==a&&(this._cookieTransform=a,this._cookieTransformSet=!!a,a&&!this._cookieOffset&&(this.cookieOffset=new pc.Vec2,this._cookieOffsetSet=!1),this.updateKey())}});Object.defineProperty(d.prototype,"cookieOffset",{get:function(){return this._cookieOffset},set:function(a){this._cookieOffset!==a&&((this._cookieTransformSet||a)&&!a&&this._cookieOffset?
|
|
this._cookieOffset.set(0,0):this._cookieOffset=a,this._cookieOffsetSet=!!a,a&&!this._cookieTransform&&(this.cookieTransform=new pc.Vec4(1,1,0,0),this._cookieTransformSet=!1),this.updateKey())}});return{Light:d}}());Object.assign(pc,function(){var e=0,b=function(){this.name="Untitled";this.id=e++;this._shader=null;this.variants={};this.parameters={};this.alphaTest=0;this.blend=this.alphaToCoverage=!1;this.blendSrc=pc.BLENDMODE_ONE;this.blendDst=pc.BLENDMODE_ZERO;this.blendEquation=pc.BLENDEQUATION_ADD;this.separateAlphaBlend=!1;this.blendSrcAlpha=pc.BLENDMODE_ONE;this.blendDstAlpha=pc.BLENDMODE_ZERO;this.blendAlphaEquation=pc.BLENDEQUATION_ADD;this.cull=pc.CULLFACE_BACK;this.depthWrite=this.depthTest=!0;this.stencilBack=
|
|
this.stencilFront=null;this.slopeDepthBias=this.depthBias=0;this.alphaWrite=this.blueWrite=this.greenWrite=this.redWrite=!0;this.meshInstances=[];this._shaderVersion=0;this._scene=null;this._dirtyBlend=!1;this.dirty=!0};Object.defineProperty(b.prototype,"shader",{get:function(){return this._shader},set:function(a){this._shader=a}});Object.defineProperty(b.prototype,"blendType",{get:function(){if(!this.blend&&this.blendSrc===pc.BLENDMODE_ONE&&this.blendDst===pc.BLENDMODE_ZERO&&this.blendEquation===
|
|
pc.BLENDEQUATION_ADD)return pc.BLEND_NONE;if(!this.blend||this.blendSrc!==pc.BLENDMODE_SRC_ALPHA||this.blendDst!==pc.BLENDMODE_ONE_MINUS_SRC_ALPHA||this.blendEquation!==pc.BLENDEQUATION_ADD){if(this.blend&&this.blendSrc===pc.BLENDMODE_ONE&&this.blendDst===pc.BLENDMODE_ONE&&this.blendEquation===pc.BLENDEQUATION_ADD)return pc.BLEND_ADDITIVE;if(this.blend&&this.blendSrc===pc.BLENDMODE_SRC_ALPHA&&this.blendDst===pc.BLENDMODE_ONE&&this.blendEquation===pc.BLENDEQUATION_ADD)return pc.BLEND_ADDITIVEALPHA;
|
|
if(this.blend&&this.blendSrc===pc.BLENDMODE_DST_COLOR&&this.blendDst===pc.BLENDMODE_SRC_COLOR&&this.blendEquation===pc.BLENDEQUATION_ADD)return pc.BLEND_MULTIPLICATIVE2X;if(this.blend&&this.blendSrc===pc.BLENDMODE_ONE_MINUS_DST_COLOR&&this.blendDst===pc.BLENDMODE_ONE&&this.blendEquation===pc.BLENDEQUATION_ADD)return pc.BLEND_SCREEN;if(this.blend&&this.blendSrc===pc.BLENDMODE_ONE&&this.blendDst===pc.BLENDMODE_ONE&&this.blendEquation===pc.BLENDEQUATION_MIN)return pc.BLEND_MIN;if(this.blend&&this.blendSrc===
|
|
pc.BLENDMODE_ONE&&this.blendDst===pc.BLENDMODE_ONE&&this.blendEquation===pc.BLENDEQUATION_MAX)return pc.BLEND_MAX;if(this.blend&&this.blendSrc===pc.BLENDMODE_DST_COLOR&&this.blendDst===pc.BLENDMODE_ZERO&&this.blendEquation===pc.BLENDEQUATION_ADD)return pc.BLEND_MULTIPLICATIVE;if(this.blend&&this.blendSrc===pc.BLENDMODE_ONE&&this.blendDst===pc.BLENDMODE_ONE_MINUS_SRC_ALPHA&&this.blendEquation===pc.BLENDEQUATION_ADD)return pc.BLEND_PREMULTIPLIED}return pc.BLEND_NORMAL},set:function(a){var b=this.blend!==
|
|
pc.BLEND_NONE;switch(a){case pc.BLEND_NONE:this.blend=!1;this.blendSrc=pc.BLENDMODE_ONE;this.blendDst=pc.BLENDMODE_ZERO;this.blendEquation=pc.BLENDEQUATION_ADD;break;case pc.BLEND_NORMAL:this.blend=!0;this.blendSrc=pc.BLENDMODE_SRC_ALPHA;this.blendDst=pc.BLENDMODE_ONE_MINUS_SRC_ALPHA;this.blendEquation=pc.BLENDEQUATION_ADD;break;case pc.BLEND_PREMULTIPLIED:this.blend=!0;this.blendSrc=pc.BLENDMODE_ONE;this.blendDst=pc.BLENDMODE_ONE_MINUS_SRC_ALPHA;this.blendEquation=pc.BLENDEQUATION_ADD;break;case pc.BLEND_ADDITIVE:this.blend=
|
|
!0;this.blendDst=this.blendSrc=pc.BLENDMODE_ONE;this.blendEquation=pc.BLENDEQUATION_ADD;break;case pc.BLEND_ADDITIVEALPHA:this.blend=!0;this.blendSrc=pc.BLENDMODE_SRC_ALPHA;this.blendDst=pc.BLENDMODE_ONE;this.blendEquation=pc.BLENDEQUATION_ADD;break;case pc.BLEND_MULTIPLICATIVE2X:this.blend=!0;this.blendSrc=pc.BLENDMODE_DST_COLOR;this.blendDst=pc.BLENDMODE_SRC_COLOR;this.blendEquation=pc.BLENDEQUATION_ADD;break;case pc.BLEND_SCREEN:this.blend=!0;this.blendSrc=pc.BLENDMODE_ONE_MINUS_DST_COLOR;this.blendDst=
|
|
pc.BLENDMODE_ONE;this.blendEquation=pc.BLENDEQUATION_ADD;break;case pc.BLEND_MULTIPLICATIVE:this.blend=!0;this.blendSrc=pc.BLENDMODE_DST_COLOR;this.blendDst=pc.BLENDMODE_ZERO;this.blendEquation=pc.BLENDEQUATION_ADD;break;case pc.BLEND_MIN:this.blend=!0;this.blendDst=this.blendSrc=pc.BLENDMODE_ONE;this.blendEquation=pc.BLENDEQUATION_MIN;break;case pc.BLEND_MAX:this.blend=!0,this.blendDst=this.blendSrc=pc.BLENDMODE_ONE,this.blendEquation=pc.BLENDEQUATION_MAX}b!==(this.blend!==pc.BLEND_NONE)&&(this._scene?
|
|
this._scene.layers._dirtyBlend=!0:this._dirtyBlend=!0);this._updateMeshInstanceKeys()}});b.prototype._cloneInternal=function(a){a.name=this.name;a.shader=this.shader;a.alphaTest=this.alphaTest;a.alphaToCoverage=this.alphaToCoverage;a.blend=this.blend;a.blendSrc=this.blendSrc;a.blendDst=this.blendDst;a.blendEquation=this.blendEquation;a.separateAlphaBlend=this.separateAlphaBlend;a.blendSrcAlpha=this.blendSrcAlpha;a.blendDstAlpha=this.blendDstAlpha;a.blendAlphaEquation=this.blendAlphaEquation;a.cull=
|
|
this.cull;a.depthTest=this.depthTest;a.depthWrite=this.depthWrite;a.depthBias=this.depthBias;a.slopeDepthBias=this.slopeDepthBias;this.stencilFront&&(a.stencilFront=this.stencilFront.clone());this.stencilBack&&(a.stencilBack=this.stencilFront===this.stencilBack?a.stencilFront:this.stencilBack.clone());a.redWrite=this.redWrite;a.greenWrite=this.greenWrite;a.blueWrite=this.blueWrite;a.alphaWrite=this.alphaWrite};b.prototype.clone=function(){var a=new pc.Material;this._cloneInternal(a);return a};b.prototype._updateMeshInstanceKeys=
|
|
function(){var a,b=this.meshInstances;for(a=0;a<b.length;a++)b[a].updateKey()};b.prototype.updateUniforms=function(){};b.prototype.updateShader=function(a,b,d){};b.prototype.update=function(){this.dirty=!0};b.prototype.clearParameters=function(){this.parameters={}};b.prototype.getParameters=function(){return this.parameters};b.prototype.clearVariants=function(){var a;this.variants={};for(var b,d=0;d<this.meshInstances.length;d++)for(a=this.meshInstances[d],b=0;b<a._shader.length;b++)a._shader[b]=
|
|
null};b.prototype.getParameter=function(a){return this.parameters[a]};b.prototype.setParameter=function(a,b,d){void 0===d&&(d=-524285);if(void 0===b&&"object"===typeof a){b=a;if(b.length){for(a=0;a<b.length;a++)this.setParameter(b[a]);return}a=b.name;b=b.value}var c=this.parameters[a];c?(c.data=b,c.passFlags=d):this.parameters[a]={scopeId:null,data:b,passFlags:d}};b.prototype.deleteParameter=function(a){this.parameters[a]&&delete this.parameters[a]};b.prototype.setParameters=function(){for(var a in this.parameters){var b=
|
|
this.parameters[a];b.scopeId.setValue(b.data)}};b.prototype.destroy=function(){this.variants={};this.shader=null;for(var a,b,d=0;d<this.meshInstances.length;d++){a=this.meshInstances[d];for(b=0;b<a._shader.length;b++)a._shader[b]=null;a._material=null;b=pc.getDefaultMaterial();this!==b&&(a.material=b)}};return{Material:b}}());Object.assign(pc,function(){var e=function(){pc.Material.call(this);this.color=new pc.Color(1,1,1,1);this.colorUniform=new Float32Array(4);this.colorMap=null;this.vertexColors=!1};e.prototype=Object.create(pc.Material.prototype);e.prototype.constructor=e;Object.assign(e.prototype,{clone:function(){var b=new pc.BasicMaterial;pc.Material.prototype._cloneInternal.call(this,b);b.color.copy(this.color);b.colorMap=this.colorMap;b.vertexColors=this.vertexColors;return b},updateUniforms:function(){this.clearParameters();
|
|
this.colorUniform[0]=this.color.r;this.colorUniform[1]=this.color.g;this.colorUniform[2]=this.color.b;this.colorUniform[3]=this.color.a;this.setParameter("uColor",this.colorUniform);this.colorMap&&this.setParameter("texture_diffuseMap",this.colorMap)},updateShader:function(b,a,c,d,f,g){a={skin:!!this.meshInstances[0].skinInstance,vertexColors:this.vertexColors,diffuseMap:this.colorMap,pass:f};this.shader=b.getProgramLibrary().getProgram("basic",a)}});return{BasicMaterial:e}}());Object.assign(pc,function(){var e=function(){pc.Material.call(this)};e.prototype=Object.create(pc.Material.prototype);e.prototype.constructor=e;Object.assign(e.prototype,{clone:function(){var b=new pc.DepthMaterial;pc.Material.prototype._cloneInternal.call(this,b);return b},updateShader:function(b){var a={skin:!!this.meshInstances[0].skinInstance};this.shader=b.getProgramLibrary().getProgram("depth",a)}});return{DepthMaterial:e}}());Object.assign(pc,function(){var e=function(){pc.Material.call(this);this._assetReferences={};this._validator=null;this.shaderOptBuilder=new pc.StandardMaterialOptionsBuilder;this.reset()};e.prototype=Object.create(pc.Material.prototype);e.prototype.constructor=e;var b=[],a=[],c=[],d=[],f={},g=function(a,d,g,l,h){var k="_"+d+"Map",p=k+"Tiling",n=k+"Offset",m=k.substring(1)+"Transform",q=m+"Uniform",t=k+"Uv",r=k+"Channel",u="_"+d+"VertexColor",v="_"+d+"VertexColorChannel";a[k]=null;a[p]=new pc.Vec2(1,
|
|
1);a[n]=new pc.Vec2(0,0);a[m]=null;a[q]=null;a[t]=g;0<l&&(g=h?h:1<l?"rgb":"g",a[r]=g,a[v]=g);a[u]=!1;pc._matTex2D||(pc._matTex2D=[]);pc._matTex2D[d]=l;Object.defineProperty(e.prototype,k.substring(1),{get:function(){return this[k]},set:function(a){var b=this[k];!!b^!!a&&(this.dirtyShader=!0);b&&a&&(b.rgbm!==a.rgbm||b.fixCubemapSeams!==a.fixCubemapSeams||b.format!==a.format)&&(this.dirtyShader=!0);this[k]=a}});a=p.substring(1);d=n.substring(1);Object.defineProperty(e.prototype,a,{get:function(){return this[p]},
|
|
set:function(a){this.dirtyShader=!0;this[p]=a}});f[a]=function(a,b,c){a=a._updateMapTransform(c?a[m]:null,b,a[n]);return{name:"texture_"+m,value:a.data}};Object.defineProperty(e.prototype,d,{get:function(){return this[n]},set:function(a){this.dirtyShader=!0;this[n]=a}});f[d]=function(a,b,c){a=a._updateMapTransform(c?a[m]:null,a[p],b);return{name:"texture_"+m,value:a.data}};Object.defineProperty(e.prototype,t.substring(1),{get:function(){return this[t]},set:function(a){this[t]!==a&&(this.dirtyShader=
|
|
!0);this[t]=a}});Object.defineProperty(e.prototype,r.substring(1),{get:function(){return this[r]},set:function(a){this[r]!==a&&(this.dirtyShader=!0);this[r]=a}});Object.defineProperty(e.prototype,u.substring(1),{get:function(){return this[u]},set:function(a){this.dirtyShader=!0;this[u]=a}});Object.defineProperty(e.prototype,v.substring(1),{get:function(){return this[v]},set:function(a){this[v]!==a&&(this.dirtyShader=!0);this[v]=a}});b.push(k.substring(1));b.push(p.substring(1));b.push(n.substring(1));
|
|
b.push(t.substring(1));b.push(r.substring(1));b.push(u.substring(1));b.push(v.substring(1));c.push(m)},l=[],h=function(a,c,g,h){var k="_"+c,p=c+"Uniform",n=c+"Intensity",m="_"+n;a[k]=g;a[p]=new Float32Array(3);Object.defineProperty(e.prototype,c,{get:function(){this.dirtyShader=this.dirtyColor=!0;return this[k]},set:function(a){var b=this[k];(0===b.r&&0===b.g&&0===b.b||1===b.r&&1===b.g&&1===b.b)^(0===a.r&&0===a.g&&0===a.b||1===a.r&&1===a.g&&1===a.b)&&(this.dirtyShader=!0);this.dirtyColor=!0;this[k]=
|
|
a}});b.push(c);d.push(p);l.push(c);f[c]=function(a,b,d){d=d?a[p]:new Float32Array(3);var f=!1;a.useGammaTonemap&&(f=(a._scene||pc.Application.getApplication().scene).gammaCorrection);for(var g=0;3>g;g++)d[g]=f?Math.pow(b.data[g],2.2):b.data[g],h&&(d[g]*=a[m]);return{name:"material_"+c,value:d}};h&&(a[m]=1,Object.defineProperty(e.prototype,n,{get:function(){return this[m]},set:function(a){var b=this[m];(0===b||1===b)^(0===a||1===a)&&(this.dirtyShader=!0);this.dirtyColor=!0;this[m]=a}}),b.push(n),f[n]=
|
|
function(a,b,d){b=d?a[p]:new Float32Array(3);d=!1;a.useGammaTonemap&&(d=(a._scene||pc.Application.getApplication().scene).gammaCorrection);for(var f=0;3>f;f++)b[f]=d?Math.pow(a[k].data[f],2.2):a[k].data[f],b[f]*=a[m];return{name:"material_"+c,value:b}})},p=function(a,c,d,g){var l="_"+c;a[l]=d;Object.defineProperty(e.prototype,c,{get:function(){return this[l]},set:function(a){var b=this[l];b!==a&&(this[l]=a,0===b||1===b||0===a||1===a)&&(this.dirtyShader=!0)}});b.push(c);f[c]=void 0!==g?g:function(a,
|
|
b,d){return{name:"material_"+c,value:b}}},k=function(a,c,d){var g="_"+c;a[g]=null;Object.defineProperty(e.prototype,c,{get:function(){return this[g]},set:function(a){!!this[g]^!!a&&(this.dirtyShader=!0);this[g]=a}});b.push(c);f[c]=d},n=function(a,b,c){Object.defineProperty(e.prototype,c,{get:function(){return this[b]},set:function(a){this[b]=a}})},q=function(a){Object.defineProperty(e.prototype,"chunks",{get:function(){this.dirtyShader=!0;return this._chunks},set:function(a){this.dirtyShader=!0;this._chunks=
|
|
a}});b.push("chunks")},m=function(a,c,d){var f="_"+c;a[f]=d;Object.defineProperty(e.prototype,c,{get:function(){return this[f]},set:function(a){this[f]!==a&&(this.dirtyShader=!0);this[f]=a}});b.push(c)},r=function(){};r.prototype.copy=function(a){for(var b in a)a.hasOwnProperty(b)&&"copy"!==b&&(this[b]=a[b])};Object.assign(e.prototype,{reset:function(){var f;for(f=0;f<b.length;f++){var g=a[f];this[b[f]]=g?g.clone?g.clone():g:g}for(f=0;f<c.length;f++)this[c[f]]=null;for(f=0;f<d.length;f++)this[d[f]]=
|
|
new Float32Array(3);this._chunks=new r;this.cubeMapMinUniform=new Float32Array(3);this.cubeMapMaxUniform=new Float32Array(3)},clone:function(){var a=new pc.StandardMaterial;pc.Material.prototype._cloneInternal.call(this,a);for(var c,d=0;d<b.length;d++)c=b[d],void 0!==this[c]&&(this[c]&&this[c].copy?a[c]?a[c].copy(this[c]):a[c]=this[c].clone():a[c]=this[c]);return a},_updateMapTransform:function(a,b,c){a=a||new pc.Vec4;a.set(b.x,b.y,c.x,c.y);return 1===a.x&&1===a.y&&0===a.z&&0===a.w?null:a},_setParameter:function(a,
|
|
b){this.parameters[a]||this._propsSet.push(a);this.setParameter(a,b)},_clearParameters:function(){for(var a=this._propsSet,b=0;b<a.length;b++)delete this.parameters[a[b]];this._propsSet=[]},_updateMap:function(a){a+="Map";if(this[a]){this._setParameter("texture_"+a,this[a]);var b=a+"Transform",c=a+"TransformUniform";this[b]||(this[c]=new Float32Array(4));this[b]=this._updateMapTransform(this[b],this[a+"Tiling"],this[a+"Offset"]);this[b]&&(this[c][0]=this[b].x,this[c][1]=this[b].y,this[c][2]=this[b].z,
|
|
this[c][3]=this[b].w,this._setParameter("texture_"+b,this[c]))}},getUniform:function(a,b,c){return(a=f[a])?a(this,b,c):null},updateUniforms:function(){var a;this._clearParameters();this._setParameter("material_ambient",this.ambientUniform);this.diffuseMap&&!this.diffuseTint||this._setParameter("material_diffuse",this.diffuseUniform);this.useMetalness?(!this.metalnessMap||1>this.metalness)&&this._setParameter("material_metalness",this.metalness):this.specularMap&&!this.specularTint||this._setParameter("material_specular",
|
|
this.specularUniform);a=this.getUniform("shininess",this.shininess,!0);this._setParameter(a.name,a.value);this.emissiveMap&&!this.emissiveTint||this._setParameter("material_emissive",this.emissiveUniform);this.emissiveMap&&this._setParameter("material_emissiveIntensity",this.emissiveIntensity);0<this.refraction&&(this._setParameter("material_refraction",this.refraction),this._setParameter("material_refractionIndex",this.refractionIndex));this._setParameter("material_opacity",this.opacity);this.occludeSpecular&&
|
|
this._setParameter("material_occludeSpecularIntensity",this.occludeSpecularIntensity);this.cubeMapProjection===pc.CUBEPROJ_BOX&&this._setParameter(this.getUniform("cubeMapProjectionBox",this.cubeMapProjectionBox,!0));for(var b in pc._matTex2D)this._updateMap(b);this.ambientSH&&this._setParameter("ambientSH[0]",this.ambientSH);this.normalMap&&this._setParameter("material_bumpiness",this.bumpiness);this.heightMap&&(a=this.getUniform("heightMapFactor",this.heightMapFactor,!0),this._setParameter(a.name,
|
|
a.value));this.cubeMap&&this._setParameter("texture_cubeMap",this.cubeMap);this.prefilteredCubeMap128?this._setParameter("texture_prefilteredCubeMap128",this.prefilteredCubeMap128):this._scene&&this._scene._skyboxPrefiltered[0]&&this._setParameter("texture_prefilteredCubeMap128",this._scene._skyboxPrefiltered[0]);this.prefilteredCubeMap64?this._setParameter("texture_prefilteredCubeMap64",this.prefilteredCubeMap64):this._scene&&this._scene._skyboxPrefiltered[1]&&this._setParameter("texture_prefilteredCubeMap64",
|
|
this._scene._skyboxPrefiltered[1]);this.prefilteredCubeMap32?this._setParameter("texture_prefilteredCubeMap32",this.prefilteredCubeMap32):this._scene&&this._scene._skyboxPrefiltered[2]&&this._setParameter("texture_prefilteredCubeMap32",this._scene._skyboxPrefiltered[2]);this.prefilteredCubeMap16?this._setParameter("texture_prefilteredCubeMap16",this.prefilteredCubeMap16):this._scene&&this._scene._skyboxPrefiltered[3]&&this._setParameter("texture_prefilteredCubeMap16",this._scene._skyboxPrefiltered[3]);
|
|
this.prefilteredCubeMap8?this._setParameter("texture_prefilteredCubeMap8",this.prefilteredCubeMap8):this._scene&&this._scene._skyboxPrefiltered[4]&&this._setParameter("texture_prefilteredCubeMap8",this._scene._skyboxPrefiltered[4]);this.prefilteredCubeMap4?this._setParameter("texture_prefilteredCubeMap4",this.prefilteredCubeMap4):this._scene&&this._scene._skyboxPrefiltered[5]&&this._setParameter("texture_prefilteredCubeMap4",this._scene._skyboxPrefiltered[5]);this.sphereMap&&this._setParameter("texture_sphereMap",
|
|
this.sphereMap);this.dpAtlas&&this._setParameter("texture_sphereMap",this.dpAtlas);this._setParameter("material_reflectivity",this.reflectivity);if(this.dirtyShader||!this._scene)this.shader=null,this.clearVariants();this._processColor()},_processColor:function(){var a;if(this.dirtyColor&&(this._scene||!this.useGammaTonemap)){var b=!1;this.useGammaTonemap&&(b=this._scene.gammaCorrection);for(a=0;a<l.length;a++){var c=this["_"+l[a]],d=this[l[a]+"Uniform"];b?(d[0]=Math.pow(c.r,2.2),d[1]=Math.pow(c.g,
|
|
2.2),d[2]=Math.pow(c.b,2.2)):(d[0]=c.r,d[1]=c.g,d[2]=c.b)}for(a=0;3>a;a++)this.emissiveUniform[a]*=this.emissiveIntensity;this.dirtyColor=!1}},updateShader:function(a,b,c,d,f,g){!this._colorProcessed&&this._scene&&(this._colorProcessed=!0,this._processColor());var l=a.useTexCubeLod,h=!a.extTextureLod,e,k,p,n,m,q;this.useSkybox&&(e=b._skyboxPrefiltered[0],k=b._skyboxPrefiltered[1],p=b._skyboxPrefiltered[2],n=b._skyboxPrefiltered[3],m=b._skyboxPrefiltered[4],q=b._skyboxPrefiltered[5]);e=this.prefilteredCubeMap128||
|
|
e;k=this.prefilteredCubeMap64||k;p=this.prefilteredCubeMap32||p;n=this.prefilteredCubeMap16||n;m=this.prefilteredCubeMap8||m;q=this.prefilteredCubeMap4||q;if(e){var r=e&&k&&p&&n&&m&&q;h&&r?(e.dpAtlas||(e.dpAtlas=pc.generateDpAtlas(a,[e,k,p,n,m,q]),e.sh=pc.shFromCubemap(n)),this.dpAtlas=e.dpAtlas,this.ambientSH=e.sh,this._setParameter("ambientSH[0]",this.ambientSH),this._setParameter("texture_sphereMap",this.dpAtlas)):l?6>e._levels.length?r?this._setParameter("texture_prefilteredCubeMap128",e):console.log("Can't use prefiltered cubemap: "+
|
|
r+", "+l+", "+e._levels):this._setParameter("texture_prefilteredCubeMap128",e):r?(this._setParameter("texture_prefilteredCubeMap128",e),this._setParameter("texture_prefilteredCubeMap64",k),this._setParameter("texture_prefilteredCubeMap32",p),this._setParameter("texture_prefilteredCubeMap16",n),this._setParameter("texture_prefilteredCubeMap8",m),this._setParameter("texture_prefilteredCubeMap4",q)):console.log("Can't use prefiltered cubemap: "+r+", "+l+", "+e._levels)}h=pc.programlib.standard;h=(l=
|
|
f>pc.SHADER_FORWARDHDR&&f<=pc.SHADER_PICK)?h.optionsContextMin:h.optionsContext;l?this.shaderOptBuilder.updateMinRef(h,a,b,this,c,d,f,g,e):this.shaderOptBuilder.updateRef(h,a,b,this,c,d,f,g,e);this.onUpdateShader&&(h=this.onUpdateShader(h));this.shader=a.getProgramLibrary().getProgram("standard",h);c||(this.clearVariants(),this.variants[0]=this.shader);this.dirtyShader=!1}});(function(c){c.dirtyShader=!0;c.dirtyColor=!0;c._scene=null;c._colorProcessed=!1;h(c,"ambient",new pc.Color(.7,.7,.7));h(c,
|
|
"diffuse",new pc.Color(1,1,1));h(c,"specular",new pc.Color(0,0,0));h(c,"emissive",new pc.Color(0,0,0),!0);p(c,"shininess",25,function(a,b){return{name:"material_shininess",value:a.shadingModel===pc.SPECULAR_PHONG?Math.pow(2,.11*b):.01*b}});p(c,"heightMapFactor",1,function(a,b){return{name:"material_heightMapFactor",value:.025*b}});p(c,"opacity",1);p(c,"alphaTest",0);p(c,"bumpiness",1);p(c,"reflectivity",1);p(c,"occludeSpecularIntensity",1);p(c,"refraction",0);p(c,"refractionIndex",1/1.5);p(c,"metalness",
|
|
1);p(c,"aoUvSet",0,null);k(c,"ambientSH",function(a,b,c){return{name:"ambientSH[0]",value:b}});k(c,"cubeMapProjectionBox",function(a,b,c){var d=c?a.cubeMapMinUniform:new Float32Array(3);a=c?a.cubeMapMaxUniform:new Float32Array(3);d[0]=b.center.x-b.halfExtents.x;d[1]=b.center.y-b.halfExtents.y;d[2]=b.center.z-b.halfExtents.z;a[0]=b.center.x+b.halfExtents.x;a[1]=b.center.y+b.halfExtents.y;a[2]=b.center.z+b.halfExtents.z;return[{name:"envBoxMin",value:d},{name:"envBoxMax",value:a}]});q(c);m(c,"ambientTint",
|
|
!1);m(c,"diffuseTint",!1);m(c,"specularTint",!1);m(c,"emissiveTint",!1);m(c,"fastTbn",!1);m(c,"specularAntialias",!1);m(c,"useMetalness",!1);m(c,"occludeDirect",!1);m(c,"normalizeNormalMap",!0);m(c,"conserveEnergy",!0);m(c,"occludeSpecular",pc.SPECOCC_AO);m(c,"shadingModel",pc.SPECULAR_BLINN);m(c,"fresnelModel",pc.FRESNEL_NONE);m(c,"cubeMapProjection",pc.CUBEPROJ_NONE);m(c,"customFragmentShader",null);m(c,"forceFragmentPrecision",null);m(c,"useFog",!0);m(c,"useLighting",!0);m(c,"useGammaTonemap",
|
|
!0);m(c,"useSkybox",!0);m(c,"forceUv1",!1);m(c,"pixelSnap",!1);m(c,"twoSidedLighting",!1);m(c,"nineSlicedMode",pc.SPRITE_RENDERMODE_SLICED);g(c,"diffuse",0,3);g(c,"specular",0,3);g(c,"emissive",0,3);g(c,"normal",0,-1);g(c,"metalness",0,1);g(c,"gloss",0,1);g(c,"opacity",0,1,"a");g(c,"height",0,1);g(c,"ao",0,1);g(c,"light",1,3);g(c,"msdf",0,3);k(c,"cubeMap");k(c,"sphereMap");k(c,"dpAtlas");k(c,"prefilteredCubeMap128");k(c,"prefilteredCubeMap64");k(c,"prefilteredCubeMap32");k(c,"prefilteredCubeMap16");
|
|
k(c,"prefilteredCubeMap8");k(c,"prefilteredCubeMap4");n(c,"diffuseTint","diffuseMapTint");n(c,"specularTint","specularMapTint");n(c,"emissiveTint","emissiveMapTint");n(c,"aoVertexColor","aoMapVertexColor");n(c,"diffuseVertexColor","diffuseMapVertexColor");n(c,"specularVertexColor","specularMapVertexColor");n(c,"emissiveVertexColor","emissiveMapVertexColor");n(c,"metalnessVertexColor","metalnessMapVertexColor");n(c,"glossVertexColor","glossMapVertexColor");n(c,"opacityVertexColor","opacityMapVertexColor");
|
|
n(c,"lightVertexColor","lightMapVertexColor");for(var d=0;d<b.length;d++)a[d]=c[b[d]];c._propsSet=[]})(e.prototype);return{StandardMaterial:e}}());(function(){pc.StandardMaterial.PARAMETER_TYPES={name:"string",chunks:"chunks",mappingFormat:"string",_engine:"boolean",ambient:"rgb",ambientTint:"boolean",aoVertexColor:"boolean",aoVertexColorChannel:"string",aoMap:"texture",aoMapChannel:"string",aoMapUv:"number",aoMapTiling:"vec2",aoMapOffset:"vec2",diffuse:"rgb",diffuseTint:"boolean",diffuseVertexColor:"boolean",diffuseVertexColorChannel:"string",diffuseMap:"texture",diffuseMapChannel:"string",diffuseMapUv:"number",diffuseMapTiling:"vec2",diffuseMapOffset:"vec2",
|
|
specular:"rgb",specularTint:"boolean",specularVertexColor:"boolean",specularVertexColorChannel:"string",specularMap:"texture",specularMapChannel:"string",specularMapUv:"number",specularMapTiling:"vec2",specularMapOffset:"vec2",specularAntialias:"boolean",occludeSpecular:"enum:occludeSpecular",useMetalness:"boolean",metalness:"number",metalnessTint:"boolean",metalnessVertexColor:"boolean",metalnessVertexColorChannel:"string",metalnessMap:"texture",metalnessMapChannel:"string",metalnessMapUv:"number",
|
|
metalnessMapTiling:"vec2",metalnessMapOffset:"vec2",conserveEnergy:"boolean",shininess:"number",glossVertexColor:"boolean",glossVertexColorChannel:"string",glossMap:"texture",glossMapChannel:"string",glossMapUv:"number",glossMapTiling:"vec2",glossMapOffset:"vec2",fresnelModel:"number",emissive:"rgb",emissiveTint:"boolean",emissiveVertexColor:"boolean",emissiveVertexColorChannel:"string",emissiveMap:"texture",emissiveMapChannel:"string",emissiveMapUv:"number",emissiveMapTiling:"vec2",emissiveMapOffset:"vec2",
|
|
emissiveIntensity:"number",normalMap:"texture",normalMapTiling:"vec2",normalMapOffset:"vec2",normalMapUv:"number",bumpiness:"number",heightMap:"texture",heightMapChannel:"string",heightMapUv:"number",heightMapTiling:"vec2",heightMapOffset:"vec2",heightMapFactor:"number",alphaToCoverage:"boolean",alphaTest:"number",opacity:"number",opacityVertexColor:"boolean",opacityVertexColorChannel:"string",opacityMap:"texture",opacityMapChannel:"string",opacityMapUv:"number",opacityMapTiling:"vec2",opacityMapOffset:"vec2",
|
|
reflectivity:"number",refraction:"number",refractionIndex:"number",sphereMap:"texture",cubeMap:"cubemap",cubeMapProjection:"number",cubeMapProjectionBox:"boundingbox",lightVertexColor:"boolean",lightVertexColorChannel:"string",lightMap:"texture",lightMapChannel:"string",lightMapUv:"number",lightMapTiling:"vec2",lightMapOffset:"vec2",depthTest:"boolean",depthWrite:"boolean",depthBias:"number",slopeDepthBias:"number",cull:"enum:cull",blendType:"enum:blendType",shadingModel:"enum:shadingModel",useFog:"boolean",
|
|
useLighting:"boolean",useSkybox:"boolean",useGammaTonemap:"boolean",prefilteredCubeMap128:"texture",prefilteredCubeMap64:"texture",prefilteredCubeMap32:"texture",prefilteredCubeMap16:"texture",prefilteredCubeMap8:"texture",prefilteredCubeMap4:"texture"};var e,b;pc.StandardMaterial.TEXTURE_PARAMETERS=[];for(e in pc.StandardMaterial.PARAMETER_TYPES)b=pc.StandardMaterial.PARAMETER_TYPES[e],"texture"===b&&pc.StandardMaterial.TEXTURE_PARAMETERS.push(e);pc.StandardMaterial.CUBEMAP_PARAMETERS=[];for(e in pc.StandardMaterial.PARAMETER_TYPES)b=
|
|
pc.StandardMaterial.PARAMETER_TYPES[e],"cubemap"===b&&pc.StandardMaterial.CUBEMAP_PARAMETERS.push(e)})();Object.assign(pc,function(){var e=function(){this.valid=this.removeInvalid=!0;this.enumValidators={occludeSpecular:this._createEnumValidator([pc.SPECOCC_NONE,pc.SPECOCC_AO,pc.SPECOCC_GLOSSDEPENDENT]),cull:this._createEnumValidator([pc.CULLFACE_NONE,pc.CULLFACE_BACK,pc.CULLFACE_FRONT,pc.CULLFACE_FRONTANDBACK]),blendType:this._createEnumValidator([pc.BLEND_SUBTRACTIVE,pc.BLEND_ADDITIVE,pc.BLEND_NORMAL,pc.BLEND_NONE,pc.BLEND_PREMULTIPLIED,pc.BLEND_MULTIPLICATIVE,pc.BLEND_ADDITIVEALPHA,pc.BLEND_MULTIPLICATIVE2X,
|
|
pc.BLEND_SCREEN,pc.BLEND_MIN,pc.BLEND_MAX]),shadingModel:this._createEnumValidator([pc.SPECULAR_PHONG,pc.SPECULAR_BLINN])}};e.prototype.setInvalid=function(b,a){this.valid=!1;this.removeInvalid&&delete a[b]};e.prototype.validate=function(b){var a=pc.StandardMaterial.PARAMETER_TYPES,c,d="path"===b.mappingFormat,f;for(f in b)if(c=a[f])if(c.startsWith("enum"))c=c.split(":")[1],this.enumValidators[c]&&(this.enumValidators[c](b[f])||this.setInvalid(f,b));else if("number"===c)"number"!==typeof b[f]&&this.setInvalid(f,
|
|
b);else if("boolean"===c)"boolean"!==typeof b[f]&&this.setInvalid(f,b);else if("string"===c)"string"!==typeof b[f]&&this.setInvalid(f,b);else if("vec2"===c)b[f]instanceof Array&&2===b[f].length||this.setInvalid(f,b);else if("rgb"===c)b[f]instanceof Array&&3===b[f].length||this.setInvalid(f,b);else if("texture"===c)d?"string"===typeof b[f]||b[null===f]||b[f]instanceof pc.Texture||this.setInvalid(f,b):"number"!==typeof b[f]&&null!==b[f]&&(b[f]instanceof pc.Texture||this.setInvalid(f,b));else if("boundingbox"===
|
|
c)b[f].center&&b[f].center instanceof Array&&3===b[f].center.length||this.setInvalid(f,b),b[f].halfExtents&&b[f].halfExtents instanceof Array&&3===b[f].halfExtents.length||this.setInvalid(f,b);else if("cubemap"===c)"number"!==typeof b[f]&&null!==b[f]&&void 0!==b[f]&&(b[f]instanceof pc.Texture&&b[f].cubemap||this.setInvalid(f,b));else if("chunks"===c){var g=Object.keys(b[f]);for(c=0;c<g.length;c++)"string"!==typeof b[f][g[c]]&&this.setInvalid(g[c],b[f])}else console.error("Unknown material type: "+
|
|
c);else this.valid=!1;b.validated=!0;return this.valid};e.prototype._createEnumValidator=function(b){return function(a){return 0<=b.indexOf(a)}};return{StandardMaterialValidator:e}}());Object.assign(pc,function(){var e=function(){this._mapXForms=null};e.prototype.updateMinRef=function(b,a,c,d,f,g,l,h,e){this._updateSharedOptions(b,d,f,l);this._updateMinOptions(b,d);this._updateUVOptions(b,d,f,!0)};e.prototype.updateRef=function(b,a,c,d,f,g,l,h,e){this._updateSharedOptions(b,d,f,l);b.useTexCubeLod=a.useTexCubeLod;this._updateEnvOptions(b,d,c,e);this._updateMaterialOptions(b,d);l===pc.SHADER_FORWARDHDR&&(b.gamma&&(b.gamma=pc.GAMMA_SRGBHDR),b.toneMap=pc.TONEMAP_LINEAR);b.hasTangents=
|
|
f&&d.normalMap&&0!==(f&pc.SHADERDEF_TANGENTS);this._updateLightOptions(b,d,f,h,g);this._updateUVOptions(b,d,f,!1)};e.prototype._updateSharedOptions=function(b,a,c,d){b.pass=d;b.alphaTest=0<a.alphaTest;b.forceFragmentPrecision=a.forceFragmentPrecision||"";b.chunks=a.chunks||"";b.blendType=a.blendType;b.forceUv1=a.forceUv1;b.screenSpace=c&&0!==(c&pc.SHADERDEF_SCREENSPACE);b.skin=c&&0!==(c&pc.SHADERDEF_SKIN);b.useInstancing=c&&0!==(c&pc.SHADERDEF_INSTANCING)};e.prototype._updateUVOptions=function(b,
|
|
a,c,d){var f=!1,g=!1,l=!1;c&&(f=0!==(c&pc.SHADERDEF_UV0),g=0!==(c&pc.SHADERDEF_UV1),l=0!==(c&pc.SHADERDEF_VCOLOR));b.vertexColors=!1;this._mapXForms=[];for(var h in pc._matTex2D)this._updateTexOptions(b,a,h,f,g,l,d);this._mapXForms=null};e.prototype._updateMinOptions=function(b,a){b.opacityTint=1!==a.opacity&&a.blendType!==pc.BLEND_NONE;b.lights=[]};e.prototype._updateMaterialOptions=function(b,a){var c=1===a.diffuse.r&&1===a.diffuse.g&&1===a.diffuse.b||!a.diffuseTint&&(a.diffuseMap||a.diffuseVertexColor)?
|
|
0:3,d=!1,f=(a.useMetalness?!0:!!a.specularMap)||!!a.sphereMap||!!a.cubeMap||!!a.dpAtlas;(f=f||(a.useMetalness?!0:!(0===a.specular.r&&0===a.specular.g&&0===a.specular.b)))&&(!a.specularTint&&(a.specularMap||a.specularVertexColor)||a.useMetalness||(d=1!==a.specular.r||1!==a.specular.g||1!==a.specular.b));var g=a.emissiveMap?0:3;g||(g=(g=(1!==a.emissive.r||1!==a.emissive.g||1!==a.emissive.b||1!==a.emissiveIntensity)&&a.emissiveTint)?3:1!==a.emissiveIntensity?1:0);b.opacityTint=1!==a.opacity&&a.blendType!==
|
|
pc.BLEND_NONE?1:0;b.blendMapsWithColors=!0;b.ambientTint=a.ambientTint;b.diffuseTint=c;b.specularTint=d?3:0;b.metalnessTint=a.useMetalness&&1>a.metalness?1:0;b.glossTint=1;b.emissiveTint=g;b.alphaToCoverage=a.alphaToCoverage;b.needsNormalFloat=a.normalizeNormalMap;b.sphereMap=!!a.sphereMap;b.cubeMap=!!a.cubeMap;b.dpAtlas=!!a.dpAtlas;b.ambientSH=!!a.ambientSH;b.useSpecular=f;b.emissiveFormat=a.emissiveMap?a.emissiveMap.rgbm?1:a.emissiveMap.format===pc.PIXELFORMAT_RGBA32F?2:0:null;b.lightMapFormat=
|
|
a.lightMap?a.lightMap.rgbm?1:a.lightMap.format===pc.PIXELFORMAT_RGBA32F?2:0:null;b.specularAntialias=a.specularAntialias;b.conserveEnergy=a.conserveEnergy;b.occludeSpecular=a.occludeSpecular;b.occludeSpecularFloat=1!==a.occludeSpecularIntensity;b.occludeDirect=a.occludeDirect;b.shadingModel=a.shadingModel;b.fresnelModel=a.fresnelModel;b.packedNormal=a.normalMap?a.normalMap.format===pc.PIXELFORMAT_DXT5:!1;b.fastTbn=a.fastTbn;b.cubeMapProjection=a.cubeMapProjection;b.customFragmentShader=a.customFragmentShader;
|
|
b.refraction=!!a.refraction;b.useMetalness=a.useMetalness;b.msdf=!!a.msdfMap;b.twoSidedLighting=a.twoSidedLighting;b.pixelSnap=a.pixelSnap;b.nineSlicedMode=a.nineSlicedMode||0;b.aoMapUv=a.aoUvSet};e.prototype._updateEnvOptions=function(b,a,c,d){var f=(d?d.rgbm:!1)||(a.cubeMap?a.cubeMap.rgbm:!1)||(a.dpAtlas?a.dpAtlas.rgbm:!1),g=(d?d.rgbm||d.format===pc.PIXELFORMAT_RGBA32F:!1)||(a.cubeMap?a.cubeMap.rgbm||a.cubeMap.format===pc.PIXELFORMAT_RGBA32F:!1)||(a.dpAtlas?a.dpAtlas.rgbm||a.dpAtlas.format===pc.PIXELFORMAT_RGBA32F:
|
|
!1),l=(!d||a.cubeMap||a.sphereMap||a.dpAtlas?!1:d.rgbm)||(a.cubeMap?a.cubeMap.rgbm:!1)||(a.sphereMap?a.sphereMap.rgbm:!1)||(a.dpAtlas?a.dpAtlas.rgbm:!1),h=(!d||a.cubeMap||a.sphereMap||a.dpAtlas?!1:d.rgbm||d.format===pc.PIXELFORMAT_RGBA32F)||(a.cubeMap?a.cubeMap.rgbm||a.cubeMap.format===pc.PIXELFORMAT_RGBA32F:!1)||(a.sphereMap?a.sphereMap.rgbm||a.sphereMap.format===pc.PIXELFORMAT_RGBA32F:!1)||(a.dpAtlas?a.dpAtlas.rgbm||a.dpAtlas.format===pc.PIXELFORMAT_RGBA32F:!1),e;a.useSkybox&&c._skyboxPrefiltered&&
|
|
(e=c._skyboxPrefiltered[0]);b.fog=a.useFog?c.fog:"none";b.gamma=a.useGammaTonemap?c.gammaCorrection:pc.GAMMA_NONE;b.toneMap=a.useGammaTonemap?c.toneMapping:-1;b.rgbmAmbient=f;b.hdrAmbient=g;b.rgbmReflection=l;b.hdrReflection=h;b.useRgbm=l||f||(a.emissiveMap?a.emissiveMap.rgbm:!1)||(a.lightMap?a.lightMap.rgbm:!1);b.fixSeams=d?d.fixCubemapSeams:a.cubeMap?a.cubeMap.fixCubemapSeams:!1;b.prefilteredCubemap=!!d;b.skyboxIntensity=d&&e&&d===e&&1!==c.skyboxIntensity};e.prototype._updateLightOptions=function(b,
|
|
a,c,d,f){b.lightMap=!1;b.lightMapChannel="";b.lightMapUv=0;b.lightMapTransform=0;b.lightMapWithoutAmbient=!1;b.dirLightMap=!1;c&&(b.noShadow=0!==(c&pc.SHADERDEF_NOSHADOW),0!==(c&pc.SHADERDEF_LM)&&(b.lightMapFormat=1,b.lightMap=!0,b.lightMapChannel="rgb",b.lightMapUv=1,b.lightMapTransform=0,b.lightMapWithoutAmbient=!a.lightMap,b.useRgbm=!0,0!==(c&pc.SHADERDEF_DIRLM)&&(b.dirLightMap=!0)));a.useLighting?(a=[],c=c?c>>16:1,d&&(this._collectLights(pc.LIGHTTYPE_DIRECTIONAL,d[pc.LIGHTTYPE_DIRECTIONAL],a,
|
|
c),this._collectLights(pc.LIGHTTYPE_POINT,d[pc.LIGHTTYPE_POINT],a,c,f),this._collectLights(pc.LIGHTTYPE_SPOT,d[pc.LIGHTTYPE_SPOT],a,c,f)),b.lights=a):b.lights=[];0===b.lights.length&&(b.noShadow=!0)};e.prototype._updateTexOptions=function(b,a,c,d,f,g,l){var h=c+"Map",e=c+"VertexColor",k=c+"VertexColorChannel",n=h+"Channel",q=h+"Transform",m=h+"Uv";"light"!==c&&(b[h]=!1,b[n]="",b[q]=0,b[m]=0);b[e]=!1;b[k]="";var r="opacity"===c;if(r&&a.blendType===pc.BLEND_NONE&&0===a.alphaTest&&!a.alphaToCoverage)return b;
|
|
if(!l||r)"height"!==c&&a[e]&&g&&(b[e]=a[e],b[k]=a[k],b.vertexColors=!0),a[h]&&(c=!0,0!==a[m]||d||(c=!1),1!==a[m]||f||(c=!1),c&&(b[h]=!!a[h],b[q]=this._getMapTransformID(a[q],a[m]),b[n]=a[n],b[m]=a[m]))};e.prototype._collectLights=function(b,a,c,d,f){var g,l;for(l=0;l<a.length;l++)g=a[l],g._enabled&&g._mask&d&&(b===pc.LIGHTTYPE_DIRECTIONAL||!g.isStatic)&&c.push(g);if(f)for(l=0;l<f.length;l++)g=f[l],g._type===b&&c.push(g)};e.prototype._getMapTransformID=function(b,a){if(!b)return 0;this._mapXForms[a]||
|
|
(this._mapXForms[a]=[]);var c;for(c=0;c<this._mapXForms[a].length&&this._mapXForms[a][c][0]==b.x&&this._mapXForms[a][c][1]==b.y&&this._mapXForms[a][c][2]==b.z&&this._mapXForms[a][c][3]==b.w;)return c+1;c=this._mapXForms[a].length;this._mapXForms[a][c]=[];this._mapXForms[a][c][0]=b.x;this._mapXForms[a][c][1]=b.y;this._mapXForms[a][c][2]=b.z;this._mapXForms[a][c][3]=b.w;return c+1};return{StandardMaterialOptionsBuilder:e}}());Object.assign(pc,function(){function e(a,b,c,d){return(a&15)<<27|(b===pc.BLEND_NONE?1:0)<<26|(c?1:0)<<25|(d&33554431)<<0}var b=0,a=new pc.BoundingBox,c=function(){this._refCount=0;this.id=b++;this.vertexBuffer=null;this.indexBuffer=[null];this.primitive=[{type:0,base:0,count:0}];this.morph=this.skin=null;this._aabb=new pc.BoundingBox;this.boneAabb=null};Object.defineProperty(c.prototype,"aabb",{get:function(){return this.morph?this.morph.aabb:this._aabb},set:function(a){this.morph?(this._aabb=this.morph._baseAabb=
|
|
a,this.morph._calculateAabb()):this._aabb=a}});var d=function(a,b,c){this._key=[0,0];this._shader=[null,null,null];this.isStatic=!1;this._staticSource=this._staticLightList=null;this.node=a;this._mesh=b;b._refCount++;this.material=c;this._shaderDefs=pc.MASK_DYNAMIC<<16;this._shaderDefs|=b.vertexBuffer.format.hasUv0?pc.SHADERDEF_UV0:0;this._shaderDefs|=b.vertexBuffer.format.hasUv1?pc.SHADERDEF_UV1:0;this._shaderDefs|=b.vertexBuffer.format.hasColor?pc.SHADERDEF_VCOLOR:0;this._shaderDefs|=b.vertexBuffer.format.hasTangents?
|
|
pc.SHADERDEF_TANGENTS:0;this._lightHash=0;this.visible=!0;this.layer=pc.LAYER_WORLD;this.renderStyle=pc.RENDERSTYLE_SOLID;this.castShadow=!1;this._receiveShadow=!0;this._noDepthDrawGl1=this._screenSpace=!1;this._updateAabb=this.pick=this.cull=!0;this._updateAabbFunc=null;this.updateKey();this.instancingData=this.morphInstance=this._skinInstance=null;this.aabb=new pc.BoundingBox;this._boneAabb=null;this._aabbVer=-1;this.visibleThisFrame=this.drawOrder=0;this.isVisibleFunc=null;this.parameters={};this.stencilBack=
|
|
this.stencilFront=null};Object.defineProperty(d.prototype,"mesh",{get:function(){return this._mesh},set:function(a){this._mesh&&this._mesh._refCount--;(this._mesh=a)&&a._refCount++}});Object.defineProperty(d.prototype,"aabb",{get:function(){var b;if(!this._updateAabb)return this._aabb;if(this._updateAabbFunc)return this._updateAabbFunc(this._aabb);if(this.skinInstance){var c=this.mesh.skin.boneNames.length,d,f;if(!this.mesh.boneAabb){this.mesh.boneAabb=[];this.mesh.boneUsed=[];var g=this.mesh.vertexBuffer.format.elements,
|
|
e=this.mesh.vertexBuffer.numVertices;b=this.mesh.vertexBuffer.format.size;var m,r,t,u,x;for(f=0;f<g.length;f++)g[f].name===pc.SEMANTIC_POSITION?r=g[f].offset:g[f].name===pc.SEMANTIC_BLENDINDICES?t=g[f].offset:g[f].name===pc.SEMANTIC_BLENDWEIGHT&&(u=g[f].offset);var g=new Uint8Array(this.mesh.vertexBuffer.storage),v=new Float32Array(this.mesh.vertexBuffer.storage),w=r/4,y=u/4,D=b/4,B,z,A,F,I;u=[];r=[];d=this.mesh.boneUsed;for(f=0;f<c;f++)u[f]=new pc.Vec3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),
|
|
r[f]=new pc.Vec3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(x=0;x<e;x++)for(f=0;4>f;f++)0<v[x*D+y+f]&&(m=g[x*b+t+f],A=v[x*D+w],F=v[x*D+w+1],I=v[x*D+w+2],B=r[m],z=u[m],z.x>A&&(z.x=A),z.y>F&&(z.y=F),z.z>I&&(z.z=I),B.x<A&&(B.x=A),B.y<F&&(B.y=F),B.z<I&&(B.z=I),d[m]=!0);if(this.morphInstance){var G;d=this.morphInstance.morph._targets;var H=new Float32Array(3*e),C=new Float32Array(3*e),E;for(x=0;x<e;x++)H[3*x]=C[3*x]=v[x*D+w],H[3*x+1]=C[3*x+1]=v[x*D+w+1],H[3*x+2]=C[3*x+2]=v[x*D+w+2];for(e=
|
|
0;e<d.length;e++)for(f=d[e],w=f.indices,x=w.length,A=f.deltaPositions,f=0;f<x;f++)G=w[f],m=A[3*f],B=A[3*f+1],z=A[3*f+2],0>m?H[3*G]+=m:C[3*G]+=m,0>B?H[3*G+1]+=B:C[3*G+1]+=B,0>z?H[3*G+2]+=z:C[3*G+2]+=z;for(e=0;e<d.length;e++)for(f=d[e],w=f.indices,x=w.length,f=0;f<x;f++)for(G=w[f],E=0;4>E;E++)0<v[G*D+y+E]&&(m=g[G*b+t+E],B=r[m],z=u[m],A=H[3*G],F=H[3*G+1],I=H[3*G+2],z.x>A&&(z.x=A),z.y>F&&(z.y=F),z.z>I&&(z.z=I),A=C[3*G],F=C[3*G+1],I=C[3*G+2],B.x<A&&(B.x=A),B.y<F&&(B.y=F),B.z<I&&(B.z=I))}for(f=0;f<c;f++)b=
|
|
new pc.BoundingBox,b.setMinMax(u[f],r[f]),this.mesh.boneAabb.push(b)}if(!this._boneAabb)for(this._boneAabb=[],f=0;f<this.mesh.boneAabb.length;f++)this._boneAabb[f]=new pc.BoundingBox;d=this.mesh.boneUsed;for(f=0;f<this.mesh.boneAabb.length;f++)d[f]&&this._boneAabb[f].setFromTransformedAabb(this.mesh.boneAabb[f],this.skinInstance.matrices[f]);c=this.node.getWorldTransform();b=!0;for(f=0;f<this.mesh.boneAabb.length;f++)d[f]&&(b?(a.center.copy(this._boneAabb[f].center),a.halfExtents.copy(this._boneAabb[f].halfExtents),
|
|
b=!1):a.add(this._boneAabb[f]));this._aabb.setFromTransformedAabb(a,c)}else this.node._aabbVer!==this._aabbVer&&(b=this.mesh?this.mesh.aabb:this._aabb,this.mesh||(b.center.set(0,0,0),b.halfExtents.set(0,0,0)),this._aabb.setFromTransformedAabb(b,this.node.getWorldTransform()),this._aabbVer=this.node._aabbVer);return this._aabb},set:function(a){this._aabb=a}});Object.defineProperty(d.prototype,"material",{get:function(){return this._material},set:function(a){var b;for(b=0;b<this._shader.length;b++)this._shader[b]=
|
|
null;if(this._material){var c=this._material.meshInstances;b=c.indexOf(this);-1!==b&&c.splice(b,1)}c=this._material?this._material.blendType!==pc.BLEND_NONE:!1;b=this._material;if(this._material=a)this._material.meshInstances.push(this),this.updateKey();a&&a.blendType!==pc.BLEND_NONE!==c&&(c=a._scene,!c&&b&&b._scene&&(c=b._scene),c?c.layers._dirtyBlend=!0:a._dirtyBlend=!0)}});Object.defineProperty(d.prototype,"layer",{get:function(){return this._layer},set:function(a){this._layer=a;this.updateKey()}});
|
|
Object.defineProperty(d.prototype,"receiveShadow",{get:function(){return this._receiveShadow},set:function(a){this._shaderDefs=(this._receiveShadow=a)?this._shaderDefs&~pc.SHADERDEF_NOSHADOW:this._shaderDefs|pc.SHADERDEF_NOSHADOW;this._shader[pc.SHADER_FORWARD]=null;this._shader[pc.SHADER_FORWARDHDR]=null}});Object.defineProperty(d.prototype,"skinInstance",{get:function(){return this._skinInstance},set:function(a){this._shaderDefs=(this._skinInstance=a)?this._shaderDefs|pc.SHADERDEF_SKIN:this._shaderDefs&
|
|
~pc.SHADERDEF_SKIN;for(a=0;a<this._shader.length;a++)this._shader[a]=null}});Object.defineProperty(d.prototype,"screenSpace",{get:function(){return this._screenSpace},set:function(a){this._shaderDefs=(this._screenSpace=a)?this._shaderDefs|pc.SHADERDEF_SCREENSPACE:this._shaderDefs&~pc.SHADERDEF_SCREENSPACE;this._shader[pc.SHADER_FORWARD]=null}});Object.defineProperty(d.prototype,"key",{get:function(){return this._key[pc.SORTKEY_FORWARD]},set:function(a){this._key[pc.SORTKEY_FORWARD]=a}});Object.defineProperty(d.prototype,
|
|
"mask",{get:function(){return this._shaderDefs>>16},set:function(a){this._shaderDefs=this._shaderDefs&65535|a<<16;this._shader[pc.SHADER_FORWARD]=null;this._shader[pc.SHADER_FORWARDHDR]=null}});Object.assign(d.prototype,{syncAabb:function(){},updateKey:function(){var a=this.material;this._key[pc.SORTKEY_FORWARD]=e(this.layer,a.alphaToCoverage||a.alphaTest?pc.BLEND_NORMAL:a.blendType,!1,a.id)},setParameter:pc.Material.prototype.setParameter,setParameters:pc.Material.prototype.setParameters,deleteParameter:pc.Material.prototype.deleteParameter,
|
|
getParameter:pc.Material.prototype.getParameter,getParameters:pc.Material.prototype.getParameters,clearParameters:pc.Material.prototype.clearParameters});var f=function(a,b,c){this._key=[];this._key[pc.SORTKEY_FORWARD]=e(a,b,!0,0);this.command=c};Object.defineProperty(f.prototype,"key",{get:function(){return this._key[pc.SORTKEY_FORWARD]},set:function(a){this._key[pc.SORTKEY_FORWARD]=a}});var g=function(a,b,c){this.buffer=new Float32Array(a*(c||16));this.count=a;this.offset=0;this.usage=b?pc.BUFFER_DYNAMIC:
|
|
pc.BUFFER_STATIC;this._buffer=null};Object.assign(g.prototype,{update:function(){this._buffer&&this._buffer.setData(this.buffer)}});return{Command:f,Mesh:c,MeshInstance:d,InstancingData:g,_getDrawcallSortKey:e}}());Object.assign(pc,function(){var e=new pc.Mat4,b=function(a){this.skin=a;this._dirty=!0;this.bones=[];var b=a.inverseBindPose.length;a=a.device;if(a.supportsBoneTextures){var d;d=256<b?64:64<b?32:16<b?16:8;this.boneTexture=new pc.Texture(a,{width:d,height:d,format:pc.PIXELFORMAT_RGBA32F,mipmaps:!1,minFilter:pc.FILTER_NEAREST,magFilter:pc.FILTER_NEAREST});this.boneTexture.name="skin";this.matrixPalette=this.boneTexture.lock()}else this.matrixPalette=new Float32Array(16*b);this.matrices=[];for(a=0;a<
|
|
b;a++)this.matrices[a]=new pc.Mat4};Object.assign(b.prototype,{updateMatrices:function(a){e.copy(a.getWorldTransform()).invert();for(a=this.bones.length-1;0<=a;a--)this.matrices[a].mul2(e,this.bones[a].getWorldTransform()),this.matrices[a].mul2(this.matrices[a],this.skin.inverseBindPose[a])},updateMatrixPalette:function(){for(var a,b=this.matrixPalette,d,f=this.bones.length-1;0<=f;f--)a=this.matrices[f].data,d=16*f,b[d]=a[0],b[d+1]=a[1],b[d+2]=a[2],b[d+3]=a[3],b[d+4]=a[4],b[d+5]=a[5],b[d+6]=a[6],
|
|
b[d+7]=a[7],b[d+8]=a[8],b[d+9]=a[9],b[d+10]=a[10],b[d+11]=a[11],b[d+12]=a[12],b[d+13]=a[13],b[d+14]=a[14],b[d+15]=a[15];this.skin.device.supportsBoneTextures&&(this.boneTexture.lock(),this.boneTexture.unlock())}});return{Skin:function(a,b,d){this.device=a;this.inverseBindPose=b;this.boneNames=d},SkinInstance:b}}());Object.assign(pc,function(){function e(){this.index=0;this.boneIndices=[0,0,0,0]}function b(){this.indexCount=this.indexStart=this.vertexCount=this.vertexStart=this.partition=0;this.boneIndices=[];this.vertices=[];this.indices=[];this.indexMap={}}function a(a){var b=a.vertices,c=a.skins,d=a.meshes,h=a.meshInstances;for(a=0;a<d.length;a++)d[a].vertices=b[d[a].vertices],void 0!==d[a].skin&&(d[a].skin=c[d[a].skin]);for(a=0;a<h.length;a++)h[a].mesh=d[h[a].mesh]}function c(a){var b=a.vertices,c=a.skins,
|
|
d=a.meshes,h=a.meshInstances;for(a=0;a<d.length;a++)d[a].vertices=b.indexOf(d[a].vertices),void 0!==d[a].skin&&(d[a].skin=c.indexOf(d[a].skin));for(a=0;a<h.length;a++)h[a].mesh=d.indexOf(h[a].mesh)}Object.assign(b.prototype,{addVertex:function(a,b,c){if(void 0!==this.indexMap[b])c=this.indexMap[b],this.indices.push(c);else{for(var d=0;4>d;d++)0!==c.blendWeight.data[4*b+d]&&(a.boneIndices[d]=this.getBoneRemap(c.blendIndices.data[4*a.index+d]));c=this.vertices.length;this.indices.push(c);this.vertices.push(a);
|
|
this.indexMap[b]=c}},addPrimitive:function(a,b,c,l){var d,f,g=[],e=0,q=a.length;for(d=0;d<q;d++)for(var m=a[d].index,r=0;4>r;r++)if(0<c.blendWeight.data[4*m+r]){var t=c.blendIndices.data[4*m+r],u=!0;for(f=0;f<e;f++)if(g[f]==t){u=!1;break}u&&(g[e]=t,f=this.getBoneRemap(t),e+=-1===f?1:0)}if(this.boneIndices.length+e>l)return!1;for(d=0;d<e;d++)this.boneIndices.push(g[d]);for(d=0;d<q;d++)this.addVertex(a[d],b[d],c);return!0},getBoneRemap:function(a){for(var b=0;b<this.boneIndices.length;b++)if(this.boneIndices[b]===
|
|
a)return b;return-1}});return{partitionSkin:function(d,f,g){var l,h,p,k;a(d);var n=d.vertices,q=d.skins,m,r=d.meshes,t=d.meshInstances,u=function(a){var b=new e;b.index=a;return b};for(l=q.length-1;0<=l;l--)if(q[l].boneNames.length>g){var x=q.splice(l,1)[0],v=[];for(h=0;h<r.length;h++)r[h].skin===x&&v.push(r[h]);for(h=0;h<v.length;h++)k=r.indexOf(v[h]),-1!==k&&r.splice(k,1);if(0===v.length)throw Error("partitionSkin: There should be at least one mesh that references a skin");var w=v[0].vertices;for(h=
|
|
1;h<v.length;h++)if(v[h].vertices!==w)throw Error("partitionSkin: All meshes that share a skin should also share the same vertex buffer");var y=[],D=[];p=[];var B=0;for(h=0;h<v.length;h++){m=v[h];for(var z=m.indices,A=m.base;A<m.base+m.count;){k=z[A++];D[0]=u(k);p[0]=k;k=z[A++];D[1]=u(k);p[1]=k;k=z[A++];D[2]=u(k);p[2]=k;for(var F=!1,I=B;I<y.length;I++)if(k=y[I],k.addPrimitive(D,p,w,g)){F=!0;break}F||(k=new b,k.originalMesh=m,k.addPrimitive(D,p,w,g),y.push(k))}B=y.length}m=[];v=[];for(h=0;h<y.length;h++)if(k=
|
|
y[h],k.vertices.length&&k.indices.length){D=m.length;p=k.vertices.length;B=v.length;z=k.indices.length;k.partition=h;k.vertexStart=D;k.vertexCount=p;k.indexStart=B;k.indexCount=z;A=0;for(F=D;A<p;)m[F++]=k.vertices[A++];A=0;for(F=B;A<z;)v[F++]=k.indices[A++]+D}D=[];for(h=0;h<y.length;h++){k=y[h];B=[];z=[];for(p=0;p<k.boneIndices.length;p++)B.push(x.inverseBindMatrices[k.boneIndices[p]]),z.push(x.boneNames[k.boneIndices[p]]);k={inverseBindMatrices:B,boneNames:z};D.push(k);q.push(k)}var G,x={};for(G in w)x[G]=
|
|
{components:w[G].components,data:[],type:w[G].type};for(G in w)if("blendIndices"===G)for(k=x[G].data,h=0;h<m.length;h++)p=m[h].boneIndices,k.push(p[0],p[1],p[2],p[3]);else for(h=w[G],B=h.data,z=h.components,h=0;h<m.length;h++)for(k=m[h].index,p=0;p<z;p++)x[G].data.push(B[k*z+p]);n[n.indexOf(w)]=x;for(h=0;h<y.length;h++)for(k=y[h],m={aabb:{min:[0,0,0],max:[0,0,0]},vertices:x,skin:D[h],indices:v.splice(0,k.indexCount),type:"triangles",base:0,count:k.indexCount},r.push(m),p=t.length-1;0<=p;p--)t[p].mesh===
|
|
k.originalMesh&&(t.push({mesh:m,node:t[p].node}),f&&f.push({material:f[p].material,path:f[p].path}));for(h=0;h<y.length;h++)for(k=y[h],p=t.length-1;0<=p;p--)t[p].mesh===k.originalMesh&&(t.splice(p,1),f&&f.splice(p,1))}c(d)}}}());Object.assign(pc,function(){var e=new pc.Vec3,b=new pc.Vec3,a=function(a){this.aabb=new pc.BoundingBox;this._baseAabb=this._baseBuffer=null;this._targets=a;this._aabbDirty=this._dirty=!0;this._baseData=null;this._vertSizeF=this._offsetTF=this._offsetNF=this._offsetPF=0};Object.assign(a.prototype,{_setBaseMesh:function(a){this._baseBuffer=a.vertexBuffer;this._baseAabb=a._aabb;this._baseData=new Float32Array(this._baseBuffer.storage);for(var b=a=-1,c=-1,d=this._baseBuffer.format.elements,h=this._baseBuffer.format.size,
|
|
e=0;e<d.length;e++)d[e].name===pc.SEMANTIC_POSITION?a=d[e].offset:d[e].name===pc.SEMANTIC_NORMAL?b=d[e].offset:d[e].name===pc.SEMANTIC_TANGENT&&(c=d[e].offset);this._offsetPF=a/4;this._offsetNF=b/4;this._offsetTF=c/4;this._vertSizeF=h/4;this._dirty=!0},_calculateAabb:function(){if(this._baseBuffer){this.aabb.copy(this._baseAabb);var a,c,g,l,h,p,k,n=this._vertSizeF,q=this._offsetPF,m=this._baseData;for(c=0;c<this._targets.length;c++){l=this._targets[c];if(!l.aabb&&0<l.indices.length){l.aabb=this.aabb.clone();
|
|
e.set(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);b.set(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);a=l.indices.length;for(g=0;g<a;g++)h=l.indices[g],p=h*n+q,h=m[p]+l.deltaPositions[3*g],k=m[p+1]+l.deltaPositions[3*g+1],p=m[p+2]+l.deltaPositions[3*g+2],e.x>h&&(e.x=h),e.y>k&&(e.y=k),e.z>p&&(e.z=p),b.x<h&&(b.x=h),b.y<k&&(b.y=k),b.z<p&&(b.z=p);l.aabb.setMinMax(e,b)}l.aabb&&this.aabb.add(l.aabb)}this._aabbDirty=!1}},addTarget:function(a){this._targets.push(a);this._aabbDirty=!0},removeTarget:function(a){a=
|
|
this._targets.indexOf(a);-1!==a&&(this._targets.splice(a,1),this._aabbDirty=!0)},getTarget:function(a){return this._targets[a]}});var c=function(a){this.morph=a;this._vertexData=this._vertexBuffer=null;this._weights=[];this._dirty=!0};Object.assign(c.prototype,{_setBaseMesh:function(a){this.destroy();this._vertexBuffer=new pc.VertexBuffer(this.morph._baseBuffer.device,this.morph._baseBuffer.format,this.morph._baseBuffer.numVertices,pc.BUFFER_DYNAMIC,this.morph._baseBuffer.storage.slice(0));this._vertexData=
|
|
new Float32Array(this._vertexBuffer.storage);this._weights=[];this._weights.length=this.morph._targets.length;for(a=0;a<this.morph._targets.length;a++)this._weights[a]=0;this._dirty=!0},destroy:function(){this._vertexBuffer&&(this._vertexBuffer.destroy(),this._vertexBuffer=null)},getWeight:function(a){return this._weights[a]},setWeight:function(a,b){this._weights[a]=b;this._dirty=!0},updateBounds:function(a){this.morph._baseBuffer!==a.vertexBuffer&&this.morph._setBaseMesh(a);this._vertexData||this._setBaseMesh(a);
|
|
this.morph._aabbDirty&&this.morph._calculateAabb()},update:function(a){this.morph._baseBuffer!==a.vertexBuffer&&this.morph._setBaseMesh(a);this._vertexData||this._setBaseMesh(a);var b,c=this.morph._targets,d=this._weights,e,p,k,n,q,m=this.morph._vertSizeF,r=this.morph._offsetPF,t=this.morph._offsetNF,u=this.morph._offsetTF,x=this._vertexData;x.set(this.morph._baseData);for(var v=0;v<c.length;v++)if(p=d[v],0!==p)for(e=c[v],a=e.indices.length,k=0;k<a;k++)q=3*k,b=e.indices[k],n=b*m+r,x[n]+=e.deltaPositions[q]*
|
|
p,x[n+1]+=e.deltaPositions[q+1]*p,x[n+2]+=e.deltaPositions[q+2]*p,e.deltaNormals&&(n=b*m+t,x[n]+=e.deltaNormals[q]*p,x[n+1]+=e.deltaNormals[q+1]*p,x[n+2]+=e.deltaNormals[q+2]*p,e.deltaTangents&&(q=4*k,n=b*m+u,x[n]+=e.deltaTangents[q]*p,x[n+1]+=e.deltaTangents[q+1]*p,x[n+2]+=e.deltaTangents[q+2]*p,x[n+3]+=e.deltaTangents[q+3]*p,x[n+3]=0<x[n+3]?1:-1));this._vertexBuffer.unlock()}});return{MorphTarget:function(a){if(a.indices)this.indices=a.indices;else{var b=a.deltaPositions;this.indices=[];this.indices.length=
|
|
b.length;for(var c=0;c<b.length;c++)this.indices[c]=c}this.deltaPositions=a.deltaPositions;this.deltaNormals=a.deltaNormals;this.deltaTangents=a.deltaTangents;this.name=a.name;this.aabb=a.aabb},Morph:a,MorphInstance:c}}());Object.assign(pc,function(){var e=function(){this.graph=null;this.meshInstances=[];this.skinInstances=[];this.morphInstances=[];this.cameras=[];this.lights=[];this._shadersVersion=0};Object.assign(e.prototype,{getGraph:function(){return this.graph},setGraph:function(b){this.graph=b},getCameras:function(){return this.cameras},setCameras:function(b){this.cameras=b},getLights:function(){return this.lights},setLights:function(b){this.lights=b},getMaterials:function(){var b,a=[];for(b=0;b<this.meshInstances.length;b++){var c=
|
|
this.meshInstances[b];-1===a.indexOf(c.material)&&a.push(c.material)}return a},clone:function(){var b,a,c=[],d=[],f=function(a){var b=a.clone();c.push(a);d.push(b);for(var g=0;g<a._children.length;g++)b.addChild(f(a._children[g]));return b},g=f(this.graph),e=[],h=[],p=[];for(b=0;b<this.skinInstances.length;b++){var k=this.skinInstances[b].skin,n=new pc.SkinInstance(k),q=[];for(a=0;a<k.boneNames.length;a++){var m=g.findByName(k.boneNames[a]);q.push(m)}n.bones=q;h.push(n)}for(b=0;b<this.morphInstances.length;b++)a=
|
|
new pc.MorphInstance(this.morphInstances[b].morph),p.push(a);for(b=0;b<this.meshInstances.length;b++)a=this.meshInstances[b],k=c.indexOf(a.node),k=new pc.MeshInstance(d[k],a.mesh,a.material),a.skinInstance&&(n=this.skinInstances.indexOf(a.skinInstance),k.skinInstance=h[n]),a.morphInstance&&(a=this.morphInstances.indexOf(a.morphInstance),k.morphInstance=p[a]),e.push(k);b=new pc.Model;b.graph=g;b.meshInstances=e;b.skinInstances=h;b.morphInstances=p;b.getGraph().syncHierarchy();return b},destroy:function(){for(var b=
|
|
this.meshInstances,a,c,d,f,g=0;g<b.length;g++){a=b[g];if(c=a.mesh)if(c._refCount--,1>c._refCount){c.vertexBuffer&&(c.vertexBuffer.destroy(),c.vertexBuffer=null);for(f=0;f<c.indexBuffer.length;f++)(d=c.indexBuffer[f])&&d.destroy();c.indexBuffer.length=0}(c=a.skinInstance)&&(c=c.boneTexture)&&c.destroy();a.skinInstance=null;(c=a.morphInstance)&&c.destroy();a.morphInstance=null;a.material=null}},generateWireframe:function(){var b,a,c,d,f,g,e,h,p,k,n=[];for(b=0;b<this.meshInstances.length;b++)g=this.meshInstances[b].mesh,
|
|
-1===n.indexOf(g)&&n.push(g);var q=[[0,1],[1,2],[2,0]];for(b=0;b<n.length;b++){g=n[b];e=g.primitive[pc.RENDERSTYLE_SOLID].base;h=g.primitive[pc.RENDERSTYLE_SOLID].count;p=g.indexBuffer[pc.RENDERSTYLE_SOLID];k=new Uint16Array(p.lock());var m={},r=[];for(a=e;a<e+h;a+=3)for(c=0;3>c;c++){d=k[a+q[c][0]];f=k[a+q[c][1]];var t=d>f?f<<16|d:d<<16|f;void 0===m[t]&&(m[t]=0,r.push(d,f))}p.unlock();a=new pc.IndexBuffer(p.device,pc.INDEXFORMAT_UINT16,r.length);c=new Uint16Array(a.lock());c.set(r);a.unlock();g.primitive[pc.RENDERSTYLE_WIREFRAME]=
|
|
{type:pc.PRIMITIVE_LINES,base:0,count:r.length,indexed:!0};g.indexBuffer[pc.RENDERSTYLE_WIREFRAME]=a}}});return{Model:e}}());Object.assign(pc,function(){function e(a){return a-Math.floor(a)}function b(a){var b=e(a);a=e(255*a);return[b-a/255,a-a/255]}function a(a,b){return a-b*Math.floor(a/b)}function c(a,b){T[a]=void 0!==Y[a]&&null!==Y[a]?Y[a]:b}function d(a,b){for(var c=a.length/3,d=Array(4*c),f=0;f<c;f++)d[4*f]=a[3*f],d[4*f+1]=a[3*f+1],d[4*f+2]=a[3*f+2],d[4*f+3]=(255*b[3*f]<<16|255*b[3*f+1]<<8|255*b[3*f+2])/16777216;return d}function f(a,b){var c,d,f=b.length,g=a.length/f;for(c=0;c<g;c++)for(d=0;d<f;d++)b[d]=Math.max(b[d],
|
|
Math.abs(a[c*f+d]))}function g(a,b,c){for(var d=new Float32Array(b.length),g=0;g<b.length;g++)d[g]=b[g]-a[g];f(d,c);a=c.length;var e=d.length/a;for(b=0;b<e;b++)for(g=0;g<a;g++)d[b*a+g]/=0===c[g]?1:c[g],d[b*a+g]*=.5,d[b*a+g]+=.5;return d}function l(a,b){b.data[0]=a.data[0];b.data[1]=a.data[1];b.data[2]=a.data[2];b.data[3]=a.data[4];b.data[4]=a.data[5];b.data[5]=a.data[6];b.data[6]=a.data[8];b.data[7]=a.data[9];b.data[8]=a.data[10]}var h=[[-1,-1],[1,-1],[1,1],[-1,1]],p=function(a,b,c,d,f,g,e){f||(f=
|
|
pc.PIXELFORMAT_RGBA32F);var h=pc.FILTER_NEAREST;e&&f===pc.PIXELFORMAT_R8_G8_B8_A8&&(h=pc.FILTER_LINEAR);a=new pc.Texture(a,{width:b,height:c,format:f,cubemap:!1,mipmaps:!1,minFilter:h,magFilter:h,addressU:pc.ADDRESS_CLAMP_TO_EDGE,addressV:pc.ADDRESS_CLAMP_TO_EDGE});a.name="PSTexture";b=a.lock();if(f===pc.PIXELFORMAT_R8_G8_B8_A8){f=new Uint8Array(d.length);for(c=0;c<d.length;c++)f[c]=d[c]*g*255;d=f}b.set(d);a.unlock();return a},k=new pc.Curve([0,0,1,0]),n=new pc.Curve([0,1,1,1]),q=new pc.CurveSet([0,
|
|
0,1,0],[0,0,1,0],[0,0,1,0]),m=new pc.CurveSet([0,1,1,1],[0,1,1,1],[0,1,1,1]),r=2,t=new pc.Vec3,u=new pc.Vec3,x=new pc.Vec3,v=new pc.Vec3,w=new pc.Vec3,y=new pc.Vec3,D=new pc.Vec3,B=new pc.Vec3,z=new pc.Vec3,A=new pc.Vec3,F=new pc.Mat4,I=new pc.Mat4,G=new pc.Mat3,H=new Float32Array(3),C=new pc.Mat3,E=new pc.Mat3,K=1,N,X=new pc.Mat4,M=new pc.Vec3,U=new pc.Vec3,aa=new pc.Vec3,V=new pc.Vec3,P=new pc.Vec3,T,Y,L=function(a,b){this.graphicsDevice=a;this.precision=32;this._addTimeTime=0;if(!L.DEFAULT_PARAM_TEXTURE){var d=
|
|
new Float32Array(1024),f,g,e,h;for(g=0;16>g;g++)for(f=0;16>f;f++)e=f+1-8.5,h=g+1-8.5,h=Math.max(Math.min(1-Math.max(Math.min(Math.sqrt(e*e+h*h)/16,1),0)-.5,1),0),e=16*g+f,d[4*e]=1,d[4*e+1]=1,d[4*e+2]=1,d[4*e+3]=h;L.DEFAULT_PARAM_TEXTURE=p(a,16,16,d,pc.PIXELFORMAT_R8_G8_B8_A8,1,!0);L.DEFAULT_PARAM_TEXTURE.minFilter=pc.FILTER_LINEAR;L.DEFAULT_PARAM_TEXTURE.magFilter=pc.FILTER_LINEAR}T=this;Y=b;c("numParticles",1);this.numParticles>a.maxTextureSize&&(console.warn("WARNING: can't create more than "+a.maxTextureSize+
|
|
" particles on this device."),this.numParticles=a.maxTextureSize);c("rate",1);c("rate2",this.rate);c("lifetime",50);c("emitterExtents",new pc.Vec3(0,0,0));c("emitterExtentsInner",new pc.Vec3(0,0,0));c("emitterRadius",0);c("emitterRadiusInner",0);c("emitterShape",pc.EMITTERSHAPE_BOX);c("initialVelocity",1);c("wrap",!1);c("localSpace",!1);c("wrapBounds",null);c("colorMap",L.DEFAULT_PARAM_TEXTURE);c("normalMap",null);c("loop",!0);c("preWarm",!1);c("sort",pc.PARTICLESORT_NONE);c("mode",pc.PARTICLEMODE_GPU);
|
|
c("scene",null);c("lighting",!1);c("halfLambert",!1);c("intensity",1);c("stretch",0);c("alignToMotion",!1);c("depthSoftening",0);c("mesh",null);c("particleNormal",new pc.Vec3(0,1,0));c("orientation",pc.PARTICLEORIENTATION_SCREEN);c("depthWrite",!1);c("noFog",!1);c("blendType",pc.BLEND_NORMAL);c("node",null);c("startAngle",0);c("startAngle2",this.startAngle);c("animTilesX",1);c("animTilesY",1);c("animNumFrames",1);c("animSpeed",1);c("animLoop",!0);this.frameRandomUniform=new Float32Array(3);this.emitterPosUniform=
|
|
new Float32Array(3);this.wrapBoundsUniform=new Float32Array(3);this.emitterScaleUniform=new Float32Array([1,1,1]);c("colorGraph",m);c("colorGraph2",this.colorGraph);c("scaleGraph",n);c("scaleGraph2",this.scaleGraph);c("alphaGraph",n);c("alphaGraph2",this.alphaGraph);c("localVelocityGraph",q);c("localVelocityGraph2",this.localVelocityGraph);c("velocityGraph",q);c("velocityGraph2",this.velocityGraph);c("rotationSpeedGraph",k);c("rotationSpeedGraph2",this.rotationSpeedGraph);c("radialSpeedGraph",k);
|
|
c("radialSpeedGraph2",this.radialSpeedGraph);this.constantParticleTexIN=a.scope.resolve("particleTexIN");this.constantParticleTexOUT=a.scope.resolve("particleTexOUT");this.constantEmitterPos=a.scope.resolve("emitterPos");this.constantEmitterScale=a.scope.resolve("emitterScale");this.constantSpawnBounds=a.scope.resolve("spawnBounds");this.constantSpawnPosInnerRatio=a.scope.resolve("spawnPosInnerRatio");this.constantSpawnBoundsSphere=a.scope.resolve("spawnBoundsSphere");this.constantSpawnBoundsSphereInnerRatio=
|
|
a.scope.resolve("spawnBoundsSphereInnerRatio");this.constantInitialVelocity=a.scope.resolve("initialVelocity");this.constantFrameRandom=a.scope.resolve("frameRandom");this.constantDelta=a.scope.resolve("delta");this.constantRate=a.scope.resolve("rate");this.constantRateDiv=a.scope.resolve("rateDiv");this.constantLifetime=a.scope.resolve("lifetime");this.constantLightCube=a.scope.resolve("lightCube[0]");this.constantGraphSampleSize=a.scope.resolve("graphSampleSize");this.constantGraphNumSamples=a.scope.resolve("graphNumSamples");
|
|
this.constantInternalTex0=a.scope.resolve("internalTex0");this.constantInternalTex1=a.scope.resolve("internalTex1");this.constantInternalTex2=a.scope.resolve("internalTex2");this.constantInternalTex3=a.scope.resolve("internalTex3");this.constantEmitterMatrix=a.scope.resolve("emitterMatrix");this.constantEmitterMatrixInv=a.scope.resolve("emitterMatrixInv");this.constantNumParticles=a.scope.resolve("numParticles");this.constantNumParticlesPot=a.scope.resolve("numParticlesPot");this.constantLocalVelocityDivMult=
|
|
a.scope.resolve("localVelocityDivMult");this.constantVelocityDivMult=a.scope.resolve("velocityDivMult");this.constantRotSpeedDivMult=a.scope.resolve("rotSpeedDivMult");this.constantSeed=a.scope.resolve("seed");this.constantStartAngle=a.scope.resolve("startAngle");this.constantStartAngle2=a.scope.resolve("startAngle2");this.constantOutBoundsMul=a.scope.resolve("outBoundsMul");this.constantOutBoundsAdd=a.scope.resolve("outBoundsAdd");this.constantInBoundsSize=a.scope.resolve("inBoundsSize");this.constantInBoundsCenter=
|
|
a.scope.resolve("inBoundsCenter");this.constantMaxVel=a.scope.resolve("maxVel");this.constantFaceTangent=a.scope.resolve("faceTangent");this.constantFaceBinorm=a.scope.resolve("faceBinorm");this.lightCube=new Float32Array(18);this.lightCubeDir=Array(6);this.lightCubeDir[0]=new pc.Vec3(-1,0,0);this.lightCubeDir[1]=new pc.Vec3(1,0,0);this.lightCubeDir[2]=new pc.Vec3(0,-1,0);this.lightCubeDir[3]=new pc.Vec3(0,1,0);this.lightCubeDir[4]=new pc.Vec3(0,0,-1);this.lightCubeDir[5]=new pc.Vec3(0,0,1);this.animParams=
|
|
new Float32Array(4);this.camera=this.particleDistance=this.vbOld=this.vbToSort=this.colorParam=this.internalTex2=this.internalTex1=this.internalTex0=null;this.swapTex=!1;this.useMesh=!0;this.useCpu=!1;this.pack8=!0;this.localBounds=new pc.BoundingBox;this.worldBoundsNoTrail=new pc.BoundingBox;this.worldBoundsTrail=[new pc.BoundingBox,new pc.BoundingBox];this.worldBounds=new pc.BoundingBox;this.inBoundsCenterUniform=new Float32Array(3);this.worldBoundsSize=new pc.Vec3;this.inBoundsSizeUniform=new Float32Array(3);
|
|
this.prevWorldBoundsSize=new pc.Vec3;this.prevWorldBoundsCenter=new pc.Vec3;this.worldBoundsMul=new pc.Vec3;this.worldBoundsMulUniform=new Float32Array(3);this.worldBoundsAdd=new pc.Vec3;this.worldBoundsAddUniform=new Float32Array(3);this.timeToSwitchBounds=0;this.shaderParticleUpdateOnStop=this.shaderParticleUpdateNoRespawn=this.shaderParticleUpdateRespawn=null;this.numParticleIndices=this.numParticleVerts=0;this.meshInstance=this.material=null;this.seed=0;this.fixedTimeStep=1/60;this.maxSubSteps=
|
|
10;this.simTimeTotal=this.simTime=0;this.beenReset=!1;this._layer=null;this.rebuild()};Object.assign(L.prototype,{onChangeCamera:function(){this.regenShader();this.resetMaterial()},calculateBoundsMad:function(){this.worldBoundsMul.x=1/this.worldBoundsSize.x;this.worldBoundsMul.y=1/this.worldBoundsSize.y;this.worldBoundsMul.z=1/this.worldBoundsSize.z;this.worldBoundsAdd.copy(this.worldBounds.center).mul(this.worldBoundsMul).scale(-1);this.worldBoundsAdd.x+=.5;this.worldBoundsAdd.y+=.5;this.worldBoundsAdd.z+=
|
|
.5},calculateWorldBounds:function(){if(this.node){this.prevWorldBoundsSize.copy(this.worldBoundsSize);this.prevWorldBoundsCenter.copy(this.worldBounds.center);this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,this.localSpace?pc.Mat4.IDENTITY:this.node.getWorldTransform());this.worldBoundsTrail[0].add(this.worldBoundsNoTrail);this.worldBoundsTrail[1].add(this.worldBoundsNoTrail);var a=this.simTimeTotal;a>this.timeToSwitchBounds&&(this.worldBoundsTrail[0].copy(this.worldBoundsTrail[1]),
|
|
this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.timeToSwitchBounds=a+this.lifetime);this.worldBounds.copy(this.worldBoundsTrail[0]);this.worldBoundsSize.copy(this.worldBounds.halfExtents).scale(2);this.meshInstance.mesh.aabb=this.worldBounds;this.meshInstance._aabbVer=1-this.meshInstance._aabbVer;this.pack8&&this.calculateBoundsMad()}},calculateLocalBounds:function(){var a=Number.MAX_VALUE,b=Number.MAX_VALUE,c=Number.MAX_VALUE,d=-Number.MAX_VALUE,f=-Number.MAX_VALUE,g=-Number.MAX_VALUE,
|
|
e=0,h=0,l=this.lifetime/this.precision,k=[this.qVelocity,this.qVelocity2,this.qLocalVelocity,this.qLocalVelocity2],p=[0,0,0,0],m=[0,0,0,0],n=[0,0,0,0],q=[0,0],r,t,u,v,w,x;for(r=0;r<this.precision+1;r++){u=Math.min(r,this.precision-1);for(t=0;4>t;t++)v=k[t][3*u]*l+p[t],w=k[t][3*u+1]*l+m[t],x=k[t][3*u+2]*l+n[t],a>v&&(a=v),b>w&&(b=w),c>x&&(c=x),d<v&&(d=v),f<w&&(f=w),g<x&&(g=x),p[t]=v,m[t]=w,n[t]=x;q[0]+=this.qRadialSpeed[u]*l;q[1]+=this.qRadialSpeed2[u]*l;e=Math.max(e,Math.max(Math.abs(q[0]),Math.abs(q[1])));
|
|
h=Math.max(h,this.qScale[u])}this.emitterShape===pc.EMITTERSHAPE_BOX?(v=.5*this.emitterExtents.x,w=.5*this.emitterExtents.y,x=.5*this.emitterExtents.z):x=w=v=this.emitterRadius;V.x=a-h-v-e;V.y=b-h-w-e;V.z=c-h-x-e;P.x=d+h+v+e;P.y=f+h+w+e;P.z=g+h+x+e;this.localBounds.setMinMax(V,P)},rebuild:function(){var a,b=this.graphicsDevice;null===this.colorMap&&(this.colorMap=L.DEFAULT_PARAM_TEXTURE);this.spawnBounds=this.emitterShape===pc.EMITTERSHAPE_BOX?this.emitterExtents:this.emitterRadius;this.useCpu=this.useCpu||
|
|
this.sort>pc.PARTICLESORT_NONE||1>=b.maxVertexTextures||64>b.fragmentUniformsCount||b.forceCpuParticles||!b.extTextureFloat;this._destroyResources();this.pack8=(this.pack8||!b.textureFloatRenderable)&&!this.useCpu;r=this.useCpu||this.pack8?4:2;this.useMesh=!1;this.mesh&&(65535<this.numParticles*this.mesh.vertexBuffer.numVertices?console.warn("WARNING: particle system can't render mesh particles because numParticles * numVertices is more than 65k. Reverting to quad particles."):this.useMesh=!0);this.numParticlesPot=
|
|
pc.math.nextPowerOfTwo(this.numParticles);this.rebuildGraphs();this.calculateLocalBounds();this.node&&(this.worldBounds.setFromTransformedAabb(this.localBounds,this.localSpace?pc.Mat4.IDENTITY:this.node.getWorldTransform()),this.worldBoundsTrail[0].copy(this.worldBounds),this.worldBoundsTrail[1].copy(this.worldBounds),this.worldBoundsSize.copy(this.worldBounds.halfExtents).scale(2),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.pack8&&
|
|
this.calculateBoundsMad());this.vbToSort=Array(this.numParticles);this.particleDistance=new Float32Array(this.numParticles);this.frameRandomUniform[0]=Math.random();this.frameRandomUniform[1]=Math.random();this.frameRandomUniform[2]=Math.random();this.particleTex=new Float32Array(this.numParticlesPot*r*4);var c=null===this.node||this.localSpace?pc.Vec3.ZERO:this.node.getPosition();this.emitterShape===pc.EMITTERSHAPE_BOX&&(null===this.node||this.localSpace?X.setTRS(pc.Vec3.ZERO,pc.Quat.IDENTITY,this.spawnBounds):
|
|
X.setTRS(pc.Vec3.ZERO,this.node.getRotation(),aa.copy(this.spawnBounds).mul(this.node.localScale)),H[0]=0!=this.emitterExtents.x?this.emitterExtentsInner.x/this.emitterExtents.x:0,H[1]=0!=this.emitterExtents.y?this.emitterExtentsInner.y/this.emitterExtents.y:0,H[2]=0!=this.emitterExtents.z?this.emitterExtentsInner.z/this.emitterExtents.z:0);for(a=0;a<this.numParticles;a++)this.calcSpawnPosition(c,a),this.useCpu&&(this.particleTex[4*a+3+8*this.numParticlesPot]=1);this.particleTexStart=new Float32Array(this.numParticlesPot*
|
|
r*4);for(a=0;a<this.particleTexStart.length;a++)this.particleTexStart[a]=this.particleTex[a];this.useCpu||(this.pack8?(this.particleTexIN=p(b,this.numParticlesPot,r,this.particleTex,pc.PIXELFORMAT_R8_G8_B8_A8,1,!1),this.particleTexOUT=p(b,this.numParticlesPot,r,this.particleTex,pc.PIXELFORMAT_R8_G8_B8_A8,1,!1),this.particleTexStart=p(b,this.numParticlesPot,r,this.particleTexStart,pc.PIXELFORMAT_R8_G8_B8_A8,1,!1)):(this.particleTexIN=p(b,this.numParticlesPot,r,this.particleTex),this.particleTexOUT=
|
|
p(b,this.numParticlesPot,r,this.particleTex),this.particleTexStart=p(b,this.numParticlesPot,r,this.particleTexStart)),this.rtParticleTexIN=new pc.RenderTarget(b,this.particleTexIN,{depth:!1}),this.rtParticleTexOUT=new pc.RenderTarget(b,this.particleTexOUT,{depth:!1}),this.swapTex=!1);a=pc.shaderChunks;var c=(this.localSpace?"#define LOCAL_SPACE\n":"")+a.particleUpdaterInitPS+(this.pack8?a.particleInputRgba8PS+a.particleOutputRgba8PS:a.particleInputFloatPS+a.particleOutputFloatPS)+(this.emitterShape===
|
|
pc.EMITTERSHAPE_BOX?a.particleUpdaterAABBPS:a.particleUpdaterSpherePS)+a.particleUpdaterStartPS,d=c+a.particleUpdaterNoRespawnPS+a.particleUpdaterEndPS,f=c+a.particleUpdaterOnStopPS+a.particleUpdaterEndPS;this.shaderParticleUpdateRespawn=a.createShaderFromCode(b,a.fullscreenQuadVS,c+a.particleUpdaterRespawnPS+a.particleUpdaterEndPS,"fsQuad0"+this.emitterShape+""+this.pack8);this.shaderParticleUpdateNoRespawn=a.createShaderFromCode(b,a.fullscreenQuadVS,d,"fsQuad1"+this.emitterShape+""+this.pack8);
|
|
this.shaderParticleUpdateOnStop=a.createShaderFromCode(b,a.fullscreenQuadVS,f,"fsQuad2"+this.emitterShape+""+this.pack8);this.numParticleVerts=this.useMesh?this.mesh.vertexBuffer.numVertices:4;this.numParticleIndices=this.useMesh?this.mesh.indexBuffer[0].numIndices:6;this._allocate(this.numParticles);b=new pc.Mesh;b.vertexBuffer=this.vertexBuffer;b.indexBuffer[0]=this.indexBuffer;b.primitive[0].type=pc.PRIMITIVE_TRIANGLES;b.primitive[0].base=0;b.primitive[0].count=this.numParticles*this.numParticleIndices;
|
|
b.primitive[0].indexed=!0;this.material=new pc.Material;this.material.name=this.node.name;this.material.cull=pc.CULLFACE_NONE;this.material.alphaWrite=!1;this.material.blend=!0;this.material.blendType=this.blendType;this.material.depthWrite=this.depthWrite;this.material.emitter=this;this.regenShader();this.resetMaterial();a=this.meshInstance?this.meshInstance.visible:!0;this.meshInstance=new pc.MeshInstance(this.node,b,this.material);this.meshInstance.pick=!1;this.meshInstance.updateKey();this.meshInstance.cull=
|
|
!0;this.meshInstance._noDepthDrawGl1=!0;this.meshInstance.aabb=this.worldBounds;this.meshInstance._updateAabb=!1;this.meshInstance.visible=a;this._initializeTextures();this.addTime(0,!1);this.preWarm&&this.prewarm(this.lifetime);this.resetTime()},_isAnimated:function(){return 1<=this.animNumFrames&&(1<this.animTilesX||1<this.animTilesY)&&(this.colorMap&&this.colorMap!==L.DEFAULT_PARAM_TEXTURE||this.normalMap)},calcSpawnPosition:function(a,c){var d=Math.random(),f=Math.random(),g=Math.random(),h=Math.random();
|
|
this.useCpu&&(this.particleTex[4*c+0+8*this.numParticlesPot]=d,this.particleTex[4*c+1+8*this.numParticlesPot]=f,this.particleTex[4*c+2+8*this.numParticlesPot]=g);M.x=d-.5;M.y=f-.5;M.z=g-.5;this.emitterShape===pc.EMITTERSHAPE_BOX?(h=Math.max(Math.abs(M.x),Math.max(Math.abs(M.y),Math.abs(M.z))),f=h+(.5-h)*H[1],g=h+(.5-h)*H[2],M.x=(h+(.5-h)*H[0])*(h==Math.abs(M.x)?Math.sign(M.x):2*M.x),M.y=f*(h==Math.abs(M.y)?Math.sign(M.y):2*M.y),M.z=g*(h==Math.abs(M.z)?Math.sign(M.z):2*M.z),this.localSpace?U.copy(X.transformPoint(M)):
|
|
U.copy(a).add(X.transformPoint(M))):(M.normalize(),f=this.emitterRadiusInner/this.emitterRadius,h=h*(1-f)+f,this.localSpace?U.copy(M.scale(h*this.emitterRadius)):U.copy(a).add(M.scale(h*this.emitterRadius)));if(this.pack8){var l=(U.x-this.worldBounds.center.x)/this.worldBoundsSize.x+.5,g=(U.y-this.worldBounds.center.y)/this.worldBoundsSize.y+.5,f=(U.z-this.worldBounds.center.z)/this.worldBoundsSize.z+.5,h=pc.math.lerp(this.startAngle*pc.math.DEG_TO_RAD,this.startAngle2*pc.math.DEG_TO_RAD,d),h=h%(2*
|
|
Math.PI)/(2*Math.PI),l=b(l);this.particleTex[4*c]=l[0];this.particleTex[4*c+1]=l[1];g=b(g);this.particleTex[4*c+2]=g[0];this.particleTex[4*c+3]=g[1];f=b(f);this.particleTex[4*c+0+4*this.numParticlesPot]=f[0];this.particleTex[4*c+1+4*this.numParticlesPot]=f[1];h=b(h);this.particleTex[4*c+2+4*this.numParticlesPot]=h[0];this.particleTex[4*c+3+4*this.numParticlesPot]=h[1];this.particleTex[4*c+3+8*this.numParticlesPot]=1;d=pc.math.lerp(this.rate,this.rate2,d);h=Math.max(this.lifetime,(this.numParticles-
|
|
1)*Math.max(this.rate,this.rate2));g=(-d*c+h)/(h+(this.lifetime+1));d=e(g);h=e(255*g);f=e(65025*g);g=e(160581375*g);d-=h/255;h-=f/255;d=[d,h,f-g/255,g-g/255];this.particleTex[4*c+0+12*this.numParticlesPot]=d[0];this.particleTex[4*c+1+12*this.numParticlesPot]=d[1];this.particleTex[4*c+2+12*this.numParticlesPot]=d[2];this.particleTex[4*c+3+12*this.numParticlesPot]=d[3]}else this.particleTex[4*c]=U.x,this.particleTex[4*c+1]=U.y,this.particleTex[4*c+2]=U.z,this.particleTex[4*c+3]=pc.math.lerp(this.startAngle*
|
|
pc.math.DEG_TO_RAD,this.startAngle2*pc.math.DEG_TO_RAD,d),d=pc.math.lerp(this.rate,this.rate2,d),this.particleTex[4*c+3+4*this.numParticlesPot]=-d*c},rebuildGraphs:function(){var a=this.precision,b=this.graphicsDevice,c;this.qLocalVelocity=this.localVelocityGraph.quantize(a);this.qVelocity=this.velocityGraph.quantize(a);this.qColor=this.colorGraph.quantize(a);this.qRotSpeed=this.rotationSpeedGraph.quantize(a);this.qScale=this.scaleGraph.quantize(a);this.qAlpha=this.alphaGraph.quantize(a);this.qRadialSpeed=
|
|
this.radialSpeedGraph.quantize(a);this.qLocalVelocity2=this.localVelocityGraph2.quantize(a);this.qVelocity2=this.velocityGraph2.quantize(a);this.qColor2=this.colorGraph2.quantize(a);this.qRotSpeed2=this.rotationSpeedGraph2.quantize(a);this.qScale2=this.scaleGraph2.quantize(a);this.qAlpha2=this.alphaGraph2.quantize(a);this.qRadialSpeed2=this.radialSpeedGraph2.quantize(a);for(c=0;c<a;c++)this.qRotSpeed[c]*=pc.math.DEG_TO_RAD,this.qRotSpeed2[c]*=pc.math.DEG_TO_RAD;this.localVelocityUMax=new Float32Array(3);
|
|
this.velocityUMax=new Float32Array(3);this.colorUMax=new Float32Array(3);this.rotSpeedUMax=[0];this.scaleUMax=[0];this.alphaUMax=[0];this.radialSpeedUMax=[0];this.qLocalVelocityDiv=g(this.qLocalVelocity,this.qLocalVelocity2,this.localVelocityUMax);this.qVelocityDiv=g(this.qVelocity,this.qVelocity2,this.velocityUMax);this.qColorDiv=g(this.qColor,this.qColor2,this.colorUMax);this.qRotSpeedDiv=g(this.qRotSpeed,this.qRotSpeed2,this.rotSpeedUMax);this.qScaleDiv=g(this.qScale,this.qScale2,this.scaleUMax);
|
|
this.qAlphaDiv=g(this.qAlpha,this.qAlpha2,this.alphaUMax);this.qRadialSpeedDiv=g(this.qRadialSpeed,this.qRadialSpeed2,this.radialSpeedUMax);if(this.pack8){var e=[0,0,0];f(this.qVelocity,e);var h=[0,0,0];f(this.qVelocity2,h);c=[0,0,0];f(this.qLocalVelocity,c);var l=[0,0,0];f(this.qLocalVelocity2,l);var k=[0];f(this.qRadialSpeed,k);var m=[0];f(this.qRadialSpeed2,m);var n=Math.max(e[0],h[0]),n=Math.max(n,e[1]),n=Math.max(n,h[1]),n=Math.max(n,e[2]),n=Math.max(n,h[2]),e=Math.max(c[0],l[0]),e=Math.max(e,
|
|
c[1]),e=Math.max(e,l[1]),e=Math.max(e,c[2]),e=Math.max(e,l[2]);this.maxVel=n+e+Math.max(k[0],m[0])}if(!this.useCpu){this.internalTex0=p(b,a,1,d(this.qLocalVelocity,this.qLocalVelocityDiv));this.internalTex1=p(b,a,1,d(this.qVelocity,this.qVelocityDiv));c=this.qRotSpeed;l=this.qScale;k=this.qScaleDiv;m=this.qRotSpeedDiv;n=this.qAlphaDiv;e=Array(4*c.length);for(h=0;h<c.length;h++)e[4*h]=c[h],e[4*h+1]=l[h],e[4*h+2]=0,e[4*h+3]=(255*k[h]<<16|255*m[h]<<8|255*n[h])/16777216;this.internalTex2=p(b,a,1,e);c=
|
|
this.qRadialSpeed;l=this.qRadialSpeedDiv;k=Array(4*c.length);for(m=0;m<c.length;m++)k[4*m]=c[m],k[4*m+1]=l[m],k[4*m+2]=0,k[4*m+3]=0;this.internalTex3=p(b,a,1,k)}c=this.qColor;l=this.qAlpha;k=Array(4*l.length);for(m=0;m<l.length;m++)k[4*m]=c[3*m],k[4*m+1]=c[3*m+1],k[4*m+2]=c[3*m+2],k[4*m+3]=l[m];this.colorParam=p(b,a,1,k,pc.PIXELFORMAT_R8_G8_B8_A8,1,!0)},_initializeTextures:function(){this.colorMap&&(this.material.setParameter("colorMap",this.colorMap),this.lighting&&this.normalMap&&this.material.setParameter("normalMap",
|
|
this.normalMap))},regenShader:function(){var a=this.graphicsDevice.getProgramLibrary(),b=null!==this.normalMap;this.normalOption=0;this.lighting&&(this.normalOption=b?2:1);this.material.updateShader=function(){this.emitter.scene&&this.emitter.camera!=this.emitter.scene._activeCamera&&(this.emitter.camera=this.emitter.scene._activeCamera,this.emitter.onChangeCamera());this.shader=a.getProgram("particle",{useCpu:this.emitter.useCpu,normal:this.emitter.normalOption,halflambert:this.emitter.halfLambert,
|
|
stretch:this.emitter.stretch,alignToMotion:this.emitter.alignToMotion,soft:this.emitter.depthSoftening,mesh:this.emitter.useMesh,gamma:this.emitter.scene?this.emitter.scene.gammaCorrection:0,toneMap:this.emitter.scene?this.emitter.scene.toneMapping:0,fog:this.emitter.scene&&!this.emitter.noFog?this.emitter.scene.fog:"none",wrap:this.emitter.wrap&&this.emitter.wrapBounds,localSpace:this.emitter.localSpace,blend:this.blendType,animTex:this.emitter._isAnimated(),animTexLoop:this.emitter.animLoop,pack8:this.emitter.pack8,
|
|
customFace:this.emitter.orientation!=pc.PARTICLEORIENTATION_SCREEN})};this.material.updateShader()},resetMaterial:function(){var a=this.material;a.setParameter("stretch",this.stretch);this._isAnimated()&&a.setParameter("animTexParams",this.animParams);a.setParameter("colorMult",this.intensity);this.useCpu||(a.setParameter("internalTex0",this.internalTex0),a.setParameter("internalTex1",this.internalTex1),a.setParameter("internalTex2",this.internalTex2),a.setParameter("internalTex3",this.internalTex3));
|
|
a.setParameter("colorParam",this.colorParam);a.setParameter("numParticles",this.numParticles);a.setParameter("numParticlesPot",this.numParticlesPot);a.setParameter("lifetime",this.lifetime);a.setParameter("rate",this.rate);a.setParameter("rateDiv",this.rate2-this.rate);a.setParameter("seed",this.seed);a.setParameter("scaleDivMult",this.scaleUMax[0]);a.setParameter("alphaDivMult",this.alphaUMax[0]);a.setParameter("radialSpeedDivMult",this.radialSpeedUMax[0]);a.setParameter("graphNumSamples",this.precision);
|
|
a.setParameter("graphSampleSize",1/this.precision);a.setParameter("emitterScale",new Float32Array([1,1,1]));this.pack8&&(this.inBoundsSizeUniform[0]=this.worldBoundsSize.x,this.inBoundsSizeUniform[1]=this.worldBoundsSize.y,this.inBoundsSizeUniform[2]=this.worldBoundsSize.z,a.setParameter("inBoundsSize",this.inBoundsSizeUniform),this.inBoundsCenterUniform[0]=this.worldBounds.center.x,this.inBoundsCenterUniform[1]=this.worldBounds.center.y,this.inBoundsCenterUniform[2]=this.worldBounds.center.z,a.setParameter("inBoundsCenter",
|
|
this.inBoundsCenterUniform),a.setParameter("maxVel",this.maxVel));this.wrap&&this.wrapBounds&&(this.wrapBoundsUniform[0]=this.wrapBounds.x,this.wrapBoundsUniform[1]=this.wrapBounds.y,this.wrapBoundsUniform[2]=this.wrapBounds.z,a.setParameter("wrapBounds",this.wrapBoundsUniform));this.colorMap&&a.setParameter("colorMap",this.colorMap);this.lighting&&this.normalMap&&a.setParameter("normalMap",this.normalMap);0<this.depthSoftening&&a.setParameter("softening",1/(this.depthSoftening*this.depthSoftening*
|
|
100));0<this.stretch&&(a.cull=pc.CULLFACE_NONE);this._compParticleFaceParams()},_compParticleFaceParams:function(){var a,b;if(this.orientation==pc.PARTICLEORIENTATION_SCREEN)a=new Float32Array([1,0,0]),b=new Float32Array([0,0,1]);else{a=this.orientation==pc.PARTICLEORIENTATION_WORLD?this.particleNormal.normalize():(null===this.node?pc.Mat4.IDENTITY:this.node.getWorldTransform()).transformVector(this.particleNormal).normalize();var c=new pc.Vec3(1,0,0);1==Math.abs(c.dot(a))&&c.set(0,0,1);b=(new pc.Vec3).cross(a,
|
|
c).normalize();c.cross(b,a).normalize();a=new Float32Array([c.x,c.y,c.z]);b=new Float32Array([b.x,b.y,b.z])}this.material.setParameter("faceTangent",a);this.material.setParameter("faceBinorm",b)},_allocate:function(a){var b=a*this.numParticleVerts,c=a*this.numParticleIndices,d;if(void 0===this.vertexBuffer||this.vertexBuffer.getNumVertices()!==b){this.useCpu?d=[{semantic:pc.SEMANTIC_ATTR0,components:4,type:pc.TYPE_FLOAT32},{semantic:pc.SEMANTIC_ATTR1,components:4,type:pc.TYPE_FLOAT32},{semantic:pc.SEMANTIC_ATTR2,
|
|
components:4,type:pc.TYPE_FLOAT32},{semantic:pc.SEMANTIC_ATTR3,components:this.useMesh?4:2,type:pc.TYPE_FLOAT32}]:(d=[{semantic:pc.SEMANTIC_ATTR0,components:4,type:pc.TYPE_FLOAT32}],this.useMesh&&d.push({semantic:pc.SEMANTIC_ATTR1,components:2,type:pc.TYPE_FLOAT32}));d=new pc.VertexFormat(this.graphicsDevice,d);this.vertexBuffer=new pc.VertexBuffer(this.graphicsDevice,d,b,pc.BUFFER_DYNAMIC);this.indexBuffer=new pc.IndexBuffer(this.graphicsDevice,pc.INDEXFORMAT_UINT16,c);d=new Float32Array(this.vertexBuffer.lock());
|
|
var f,g,e;if(this.useMesh)for(f=new Float32Array(this.mesh.vertexBuffer.lock()),g=f.length/this.mesh.vertexBuffer.numVertices,c=0;c<this.mesh.vertexBuffer.format.elements.length;c++)if(this.mesh.vertexBuffer.format.elements[c].name===pc.SEMANTIC_TEXCOORD0){e=this.mesh.vertexBuffer.format.elements[c].offset/4;break}for(var l,c=0;c<b;c++)if(l=Math.floor(c/this.numParticleVerts),this.useMesh){var k=c%this.numParticleVerts;d[6*c]=f[k*g];d[6*c+1]=f[k*g+1];d[6*c+2]=f[k*g+2];d[6*c+3]=l;d[6*c+4]=f[k*g+e+
|
|
0];d[6*c+5]=f[k*g+e+1]}else k=c%4,d[4*c]=h[k][0],d[4*c+1]=h[k][1],d[4*c+2]=0,d[4*c+3]=l;this.useCpu&&(this.vbCPU=new Float32Array(d),this.vbOld=new Float32Array(this.vbCPU.length));this.vertexBuffer.unlock();this.useMesh&&this.mesh.vertexBuffer.unlock();b=0;g=new Uint16Array(this.indexBuffer.lock());this.useMesh&&(f=new Uint16Array(this.mesh.indexBuffer[0].lock()));for(c=0;c<a;c++)if(this.useMesh)for(e=0;e<this.numParticleIndices;e++)g[c*this.numParticleIndices+e]=f[e]+c*this.numParticleVerts;else e=
|
|
4*c,g[b++]=e,g[b++]=e+1,g[b++]=e+2,g[b++]=e,g[b++]=e+2,g[b++]=e+3;this.indexBuffer.unlock();this.useMesh&&this.mesh.indexBuffer[0].unlock()}},reset:function(){this.beenReset=!0;this.seed=Math.random();this.material.setParameter("seed",this.seed);if(this.useCpu)for(var a=0;a<this.particleTexStart.length;a++)this.particleTex[a]=this.particleTexStart[a];else this._initializeTextures();this.resetTime();a=this.loop;this.loop=!0;this.addTime(0,!1);this.loop=a;this.preWarm&&this.prewarm(this.lifetime)},
|
|
prewarm:function(a){var b=Math.min(Math.floor(a/this.lifetime*this.precision),this.precision);a/=b;for(var c=0;c<b;c++)this.addTime(a,!1)},resetTime:function(){var a=Math.max(this.rate,this.rate2)*this.numParticles+this.lifetime;this.endTime=Date.now()+1E3*a},finishFrame:function(){this.useCpu&&this.vertexBuffer.unlock()},_setInputBounds:function(){this.inBoundsSizeUniform[0]=this.prevWorldBoundsSize.x;this.inBoundsSizeUniform[1]=this.prevWorldBoundsSize.y;this.inBoundsSizeUniform[2]=this.prevWorldBoundsSize.z;
|
|
this.constantInBoundsSize.setValue(this.inBoundsSizeUniform);this.inBoundsCenterUniform[0]=this.prevWorldBoundsCenter.x;this.inBoundsCenterUniform[1]=this.prevWorldBoundsCenter.y;this.inBoundsCenterUniform[2]=this.prevWorldBoundsCenter.z;this.constantInBoundsCenter.setValue(this.inBoundsCenterUniform)},addTime:function(b,c){var d,f,g,e,h;e=this.graphicsDevice;this.simTimeTotal+=b;this.calculateWorldBounds();this._isAnimated()&&(h=this.animParams,h[0]=1/this.animTilesX,h[1]=1/this.animTilesY,h[2]=
|
|
this.animNumFrames*this.animSpeed,h[3]=this.animNumFrames-1);this.scene&&this.camera!=this.scene._activeCamera&&(this.camera=this.scene._activeCamera,this.onChangeCamera());this.emitterShape===pc.EMITTERSHAPE_BOX&&(H[0]=0!=this.emitterExtents.x?this.emitterExtentsInner.x/this.emitterExtents.x:0,H[1]=0!=this.emitterExtents.y?this.emitterExtentsInner.y/this.emitterExtents.y:0,H[2]=0!=this.emitterExtents.z?this.emitterExtentsInner.z/this.emitterExtents.z:0,null===this.meshInstance.node?X.setTRS(pc.Vec3.ZERO,
|
|
pc.Quat.IDENTITY,this.emitterExtents):X.setTRS(pc.Vec3.ZERO,this.meshInstance.node.getRotation(),aa.copy(this.emitterExtents).mul(this.meshInstance.node.localScale)));var k=null===this.meshInstance.node?pc.Vec3.ONE:this.meshInstance.node.localScale;this.emitterScaleUniform[0]=k.x;this.emitterScaleUniform[1]=k.y;this.emitterScaleUniform[2]=k.z;this.material.setParameter("emitterScale",this.emitterScaleUniform);this.localSpace&&this.meshInstance.node&&(h=this.meshInstance.node.getPosition(),this.emitterPosUniform[0]=
|
|
h.x,this.emitterPosUniform[1]=h.y,this.emitterPosUniform[2]=h.z,this.material.setParameter("emitterPos",this.emitterPosUniform));this._compParticleFaceParams();if(this.useCpu){k=new Float32Array(this.vertexBuffer.lock());if(this.meshInstance.node){e=this.meshInstance.node.worldTransform;for(h=0;12>h;h++)F.data[h]=e.data[h];I.copy(F);I.invert();N=this.meshInstance.node.localScale;K=Math.max(Math.max(N.x,N.y),N.z)}h=null===this.meshInstance.node||this.localSpace?pc.Vec3.ZERO:this.meshInstance.node.getPosition();
|
|
var p=this.camera?this.camera._node.getPosition():pc.Vec3.ZERO,m=this.useMesh?16:14,n,q,r,U,O,L,Q,P,Y=this.precision-1;for(e=0;e<this.numParticles;e++){var T=Math.floor(this.vbCPU[e*this.numParticleVerts*(this.useMesh?6:4)+3]),V=this.particleTex[4*T+0+8*this.numParticlesPot];y.x=V;y.y=this.particleTex[4*T+1+8*this.numParticlesPot];y.z=this.particleTex[4*T+2+8*this.numParticlesPot];var ja=this.rate+(this.rate2-this.rate)*V,ha=this.lifetime,ga=this.particleTex[4*T+3+4*this.numParticlesPot]+b,na=Math.max(Math.min(ga/
|
|
ha,1),0),ia=0;g=0;var ma=0<ga&&ga<ha;ma?(g=na*Y,n=Math.floor(g),q=Math.ceil(g),g%=1,d=this.qRotSpeed[n],f=this.qRotSpeed[q],r=d+(f-d)*g,d=this.qRotSpeed2[n],f=this.qRotSpeed2[q],U=d+(f-d)*g,d=this.qScale[n],f=this.qScale[q],ia=d+(f-d)*g,d=this.qScale2[n],f=this.qScale2[q],O=d+(f-d)*g,d=this.qAlpha[n],f=this.qAlpha[q],L=d+(f-d)*g,d=this.qAlpha2[n],f=this.qAlpha2[q],Q=d+(f-d)*g,d=this.qRadialSpeed[n],f=this.qRadialSpeed[q],P=d+(f-d)*g,d=this.qRadialSpeed2[n],f=this.qRadialSpeed2[q],d+=(f-d)*g,P+=100*
|
|
V%1*(d-P),D.x=this.particleTex[4*T],D.y=this.particleTex[4*T+1],D.z=this.particleTex[4*T+2],this.localSpace?w.copy(D):w.copy(D).sub(h),w.normalize().scale(P),n*=3,q*=3,d=this.qLocalVelocity[n],f=this.qLocalVelocity[q],u.x=d+(f-d)*g,d=this.qLocalVelocity[n+1],f=this.qLocalVelocity[q+1],u.y=d+(f-d)*g,d=this.qLocalVelocity[n+2],f=this.qLocalVelocity[q+2],u.z=d+(f-d)*g,d=this.qLocalVelocity2[n],f=this.qLocalVelocity2[q],v.x=d+(f-d)*g,d=this.qLocalVelocity2[n+1],f=this.qLocalVelocity2[q+1],v.y=d+(f-d)*
|
|
g,d=this.qLocalVelocity2[n+2],f=this.qLocalVelocity2[q+2],v.z=d+(f-d)*g,d=this.qVelocity[n],f=this.qVelocity[q],t.x=d+(f-d)*g,d=this.qVelocity[n+1],f=this.qVelocity[q+1],t.y=d+(f-d)*g,d=this.qVelocity[n+2],f=this.qVelocity[q+2],t.z=d+(f-d)*g,d=this.qVelocity2[n],f=this.qVelocity2[q],x.x=d+(f-d)*g,d=this.qVelocity2[n+1],f=this.qVelocity2[q+1],x.y=d+(f-d)*g,d=this.qVelocity2[n+2],f=this.qVelocity2[q+2],x.z=d+(f-d)*g,u.x+=(v.x-u.x)*y.x,u.y+=(v.y-u.y)*y.y,u.z+=(v.z-u.z)*y.z,0<this.initialVelocity&&(this.emitterShape===
|
|
pc.EMITTERSHAPE_SPHERE?(M.copy(y).scale(2).sub(pc.Vec3.ONE).normalize(),u.add(M.scale(this.initialVelocity))):u.add(pc.Vec3.FORWARD.scale(this.initialVelocity))),t.x+=(x.x-t.x)*y.x,t.y+=(x.y-t.y)*y.y,t.z+=(x.z-t.z)*y.z,r+=(U-r)*y.y,ia=(ia+1E4*V%1*(O-ia))*K,g=1E3*V%1*(Q-L),this.meshInstance.node&&(this.localSpace?(u.x/=N.x,u.y/=N.y,u.z/=N.z):F.transformPoint(u,u)),this.localSpace?(I.transformPoint(t,t),u.add(t).add(w)):(u.add(t.mul(N)),u.add(w.mul(N))),A.copy(u),B.copy(D).add(u.scale(b)),z.copy(B),
|
|
this.particleTex[4*T]=z.x,this.particleTex[4*T+1]=z.y,this.particleTex[4*T+2]=z.z,this.particleTex[4*T+3]+=r*b,this.wrap&&this.wrapBounds&&(this.localSpace||z.sub(h),z.x=a(z.x,this.wrapBounds.x)-.5*this.wrapBounds.x,z.y=a(z.y,this.wrapBounds.y)-.5*this.wrapBounds.y,z.z=a(z.z,this.wrapBounds.z)-.5*this.wrapBounds.z,this.localSpace||z.add(h)),0<this.sort&&(1===this.sort?(aa.copy(z).sub(p),this.particleDistance[T]=-(aa.x*aa.x+aa.y*aa.y+aa.z*aa.z)):2===this.sort?this.particleDistance[T]=ga:3===this.sort&&
|
|
(this.particleDistance[T]=-ga))):this.calcSpawnPosition(h,T);c?0>ga&&(this.particleTex[4*T+3+8*this.numParticlesPot]=-1):(ga>=ha&&(ga-=Math.max(ha,(this.numParticles-1)*ja),this.particleTex[4*T+3+8*this.numParticlesPot]=this.loop?1:-1),0>ga&&this.loop&&(this.particleTex[4*T+3+8*this.numParticlesPot]=1));0>this.particleTex[4*T+3+8*this.numParticlesPot]&&(ma=!1);this.particleTex[4*T+3+4*this.numParticlesPot]=ga;for(r=0;r<this.numParticleVerts;r++)V=(e*this.numParticleVerts+r)*(this.useMesh?6:4),ja=
|
|
this.vbCPU[V],ha=this.vbCPU[V+1],ga=this.vbCPU[V+2],ma||(ja=ha=ga=0),n=e*this.numParticleVerts*m+r*m,k[n]=z.x,k[n+1]=z.y,k[n+2]=z.z,k[n+3]=na,k[n+4]=this.alignToMotion?0:this.particleTex[4*T+3],k[n+5]=ia,k[n+6]=g,k[n+7]=A.x,k[n+8]=ja,k[n+9]=ha,k[n+10]=ga,k[n+11]=A.y,k[n+12]=A.z,k[n+13]=this.vbCPU[V+3],this.useMesh&&(k[n+14]=this.vbCPU[V+4],k[n+15]=this.vbCPU[V+5])}if(this.sort>pc.PARTICLESORT_NONE&&this.camera){k=this.useMesh?6:4;h=this.particleDistance;for(e=0;e<this.numParticles;e++)this.vbToSort[e]=
|
|
[e,h[Math.floor(this.vbCPU[e*this.numParticleVerts*k+3])]];this.vbOld.set(this.vbCPU);this.vbToSort.sort(function(a,b){return a[1]-b[1]});for(e=0;e<this.numParticles;e++)for(p=this.vbToSort[e][0]*this.numParticleVerts*k,m=e*this.numParticleVerts*k,h=0;h<this.numParticleVerts*k;h++)this.vbCPU[m+h]=this.vbOld[p+h]}}else e.setBlending(!1),e.setColorWrite(!0,!0,!0,!0),e.setCullMode(pc.CULLFACE_NONE),e.setDepthTest(!1),e.setDepthWrite(!1),this.frameRandomUniform[0]=Math.random(),this.frameRandomUniform[1]=
|
|
Math.random(),this.frameRandomUniform[2]=Math.random(),this.constantGraphSampleSize.setValue(1/this.precision),this.constantGraphNumSamples.setValue(this.precision),this.constantNumParticles.setValue(this.numParticles),this.constantNumParticlesPot.setValue(this.numParticlesPot),this.constantInternalTex0.setValue(this.internalTex0),this.constantInternalTex1.setValue(this.internalTex1),this.constantInternalTex2.setValue(this.internalTex2),this.constantInternalTex3.setValue(this.internalTex3),this.pack8&&
|
|
(this.worldBoundsMulUniform[0]=this.worldBoundsMul.x,this.worldBoundsMulUniform[1]=this.worldBoundsMul.y,this.worldBoundsMulUniform[2]=this.worldBoundsMul.z,this.constantOutBoundsMul.setValue(this.worldBoundsMulUniform),this.worldBoundsAddUniform[0]=this.worldBoundsAdd.x,this.worldBoundsAddUniform[1]=this.worldBoundsAdd.y,this.worldBoundsAddUniform[2]=this.worldBoundsAdd.z,this.constantOutBoundsAdd.setValue(this.worldBoundsAddUniform),this._setInputBounds(),h=this.maxVel*Math.max(Math.max(k.x,k.y),
|
|
k.z),h=Math.max(h,1),this.constantMaxVel.setValue(h)),h=null===this.meshInstance.node||this.localSpace?pc.Vec3.ZERO:this.meshInstance.node.getPosition(),p=null===this.meshInstance.node?pc.Mat4.IDENTITY:this.meshInstance.node.getWorldTransform(),this.emitterShape===pc.EMITTERSHAPE_BOX?(l(X,G),this.constantSpawnBounds.setValue(G.data),this.constantSpawnPosInnerRatio.setValue(H)):(this.constantSpawnBoundsSphere.setValue(this.emitterRadius),this.constantSpawnBoundsSphereInnerRatio.setValue(this.emitterRadiusInner/
|
|
this.emitterRadius)),this.constantInitialVelocity.setValue(this.initialVelocity),l(p,C),p.invertTo3x3(E),this.emitterPosUniform[0]=h.x,this.emitterPosUniform[1]=h.y,this.emitterPosUniform[2]=h.z,this.constantEmitterPos.setValue(this.emitterPosUniform),this.constantFrameRandom.setValue(this.frameRandomUniform),this.constantDelta.setValue(b),this.constantRate.setValue(this.rate),this.constantRateDiv.setValue(this.rate2-this.rate),this.constantStartAngle.setValue(this.startAngle*pc.math.DEG_TO_RAD),
|
|
this.constantStartAngle2.setValue(this.startAngle2*pc.math.DEG_TO_RAD),this.constantSeed.setValue(this.seed),this.constantLifetime.setValue(this.lifetime),this.emitterScaleUniform[0]=k.x,this.emitterScaleUniform[1]=k.y,this.emitterScaleUniform[2]=k.z,this.constantEmitterScale.setValue(this.emitterScaleUniform),this.constantEmitterMatrix.setValue(C.data),this.constantEmitterMatrixInv.setValue(E.data),this.constantLocalVelocityDivMult.setValue(this.localVelocityUMax),this.constantVelocityDivMult.setValue(this.velocityUMax),
|
|
this.constantRotSpeedDivMult.setValue(this.rotSpeedUMax[0]),h=this.swapTex?this.particleTexOUT:this.particleTexIN,h=this.beenReset?this.particleTexStart:h,k=this.swapTex?this.particleTexIN:this.particleTexOUT,this.constantParticleTexIN.setValue(h),c?pc.drawQuadWithShader(e,this.swapTex?this.rtParticleTexIN:this.rtParticleTexOUT,this.shaderParticleUpdateOnStop):pc.drawQuadWithShader(e,this.swapTex?this.rtParticleTexIN:this.rtParticleTexOUT,this.loop?this.shaderParticleUpdateRespawn:this.shaderParticleUpdateNoRespawn),
|
|
this.constantParticleTexOUT.setValue(k),this.material.setParameter("particleTexOUT",h),this.material.setParameter("particleTexIN",k),this.beenReset=!1,this.swapTex=!this.swapTex,e.setDepthTest(!0),e.setDepthWrite(!0),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.pack8&&this._setInputBounds();if(!this.loop&&Date.now()>this.endTime){if(this.onFinished)this.onFinished();this.meshInstance.visible=!1}},_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)},destroy:function(){this.camera=null;
|
|
this._destroyResources()}});return{ParticleEmitter:L}}());Object.assign(pc,function(){var e=!1,b=function(a,b,d){a instanceof pc.GraphicsDevice&&(a=pc.Application.getApplication(),e||(e=!0));this.app=a;var c=this.device=a.graphicsDevice;this.library=c.getProgramLibrary();this.pickColor=new Float32Array(4);this.pickColor[3]=1;this.scene=null;this.drawCalls=[];this.layerComp=this.layer=null;this.clearOptions={color:[1,1,1,1],depth:1,flags:pc.CLEARFLAG_COLOR|pc.CLEARFLAG_DEPTH};var g=this;this._clearDepthOptions={depth:1,flags:pc.CLEARFLAG_DEPTH};this.clearDepthCommand=
|
|
new pc.Command(0,0,function(){c.clear(g._clearDepthOptions)});this.resize(b,d);this._ignoreOpacityFor=null};b.prototype.getSelection=function(a,b,d,f){var c=this.device;"object"===typeof a?(f=a,a=f.x,b=f.y,d=f.width,f=f.height):b=this.layer.renderTarget.height-(b+(f||1));d=d||1;f=f||1;var e=c.renderTarget;c.setRenderTarget(this.layer.renderTarget);c.updateBegin();var h=new Uint8Array(4*d*f);c.readPixels(a,b,d,f,h);c.updateEnd();c.setRenderTarget(e);a=[];b=this.layer.instances.visibleOpaque[0].list;
|
|
for(var p,k,c=0;c<d*f;c++)e=h[4*c+0],p=h[4*c+1],k=h[4*c+2],e=e<<16|p<<8|k,16777215!==e&&(e=b[e],-1===a.indexOf(e)&&a.push(e));return a};b.prototype.prepare=function(a,b,d){var c=this.device,g,e=this;a instanceof pc.Camera&&(a=a._component);this.scene=b;var h=null,p=null;d instanceof pc.Layer?h=d:p=d;if(!this.layer){var k=c.scope.resolve("uColor");this.layer=new pc.Layer({name:"Picker",shaderPass:pc.SHADER_PICK,opaqueSortMode:pc.SORTMODE_NONE,onEnable:function(){if(!this.renderTarget){var a=new pc.Texture(c,
|
|
{format:pc.PIXELFORMAT_R8_G8_B8_A8,width:e.width,height:e.height});a.name="pick";a.minFilter=pc.FILTER_NEAREST;a.magFilter=pc.FILTER_NEAREST;a.addressU=pc.ADDRESS_CLAMP_TO_EDGE;a.addressV=pc.ADDRESS_CLAMP_TO_EDGE;this.renderTarget=new pc.RenderTarget(c,a,{depth:!0})}},onDisable:function(){this.renderTarget&&(this.renderTarget._colorBuffer.destroy(),this.renderTarget.destroy(),this.renderTarget=null)},onDrawCall:function(a,b){e.pickColor[0]=(b>>16&255)/255;e.pickColor[1]=(b>>8&255)/255;e.pickColor[2]=
|
|
(b&255)/255;k.setValue(e.pickColor);c.setBlending(!1)}});this.layerComp=new pc.LayerComposition;this.layerComp.pushOpaque(this.layer);this.meshInstances=this.layer.opaqueMeshInstances;this._instancesVersion=-1}var n,q,m;if(!h){this.layer.clearMeshInstances();d=b.layers.layerList;var r=b.layers.subLayerEnabled,t=b.layers.subLayerList;for(b=0;b<d.length;b++)d[b].overrideClear&&d[b]._clearDepthBuffer&&(d[b]._pickerCleared=!1);for(b=0;b<d.length;b++)if(g=d[b],g.renderTarget===p&&g.enabled&&r[b]&&(n=g.cameras.indexOf(a),
|
|
!(0>n)))for(g.overrideClear&&g._clearDepthBuffer&&!g._pickerCleared&&(this.meshInstances.push(this.clearDepthCommand),g._pickerCleared=!0),n=(n=t[b])?g.instances.transparentMeshInstances:g.instances.opaqueMeshInstances,q=n.length,g=0;g<q;g++)m=n[g],m.pick&&this.meshInstances.push(m)}else if(this._instancesVersion!==h._version){this.layer.clearMeshInstances();n=h.instances.opaqueMeshInstances;q=n.length;for(g=0;g<q;g++)m=n[g],m.pick&&this.meshInstances.push(m);n=h.instances.transparentMeshInstances;
|
|
q=n.length;for(g=0;g<q;g++)m=n[g],m.pick&&this.meshInstances.push(m);this._instancesVersion=h._version}this.layer.cameras[0]!==a&&(this.layer.clearCameras(),this.layer.addCamera(a));this.onLayerPreRender(this.layer,h,p);this.app.renderer.renderComposition(this.layerComp);this.onLayerPostRender(this.layer)};b.prototype.onLayerPreRender=function(a,b,d){if(this.width!==a.renderTarget.width||this.height!==a.renderTarget.height)a.onDisable(),a.onEnable();a.oldClear=a.cameras[0].camera._clearOptions;a.oldAspectMode=
|
|
a.cameras[0].aspectRatioMode;a.oldAspect=a.cameras[0].aspectRatio;a.cameras[0].camera._clearOptions=this.clearOptions;a.cameras[0].aspectRatioMode=pc.ASPECT_MANUAL;a.cameras[0].aspectRatio=a.cameras[0].calculateAspectRatio(d?d:b?b.renderTarget:null);this.app.renderer.updateCameraFrustum(a.cameras[0].camera)};b.prototype.onLayerPostRender=function(a){a.cameras[0].camera._clearOptions=a.oldClear;a.cameras[0].aspectRatioMode=a.oldAspectMode;a.cameras[0].aspectRatio=a.oldAspect};b.prototype.resize=function(a,
|
|
b){this.width=a;this.height=b};Object.defineProperty(b.prototype,"renderTarget",{get:function(){return this.layer.renderTarget}});return{Picker:b}}());var primitiveUv1Padding=.0625,primitiveUv1PaddingScale=1-2*primitiveUv1Padding;
|
|
pc.calculateNormals=function(e,b){var a=b.length/3,c=e.length/3,d,f,g,l,h=new pc.Vec3,p=new pc.Vec3,k=new pc.Vec3,n=new pc.Vec3,q=new pc.Vec3,m=new pc.Vec3,r=[];for(l=0;l<e.length;l++)r[l]=0;for(l=0;l<a;l++)d=b[3*l],f=b[3*l+1],g=b[3*l+2],h.set(e[3*d],e[3*d+1],e[3*d+2]),p.set(e[3*f],e[3*f+1],e[3*f+2]),k.set(e[3*g],e[3*g+1],e[3*g+2]),n.sub2(p,h),q.sub2(k,h),m.cross(n,q).normalize(),r[3*d]+=m.x,r[3*d+1]+=m.y,r[3*d+2]+=m.z,r[3*f]+=m.x,r[3*f+1]+=m.y,r[3*f+2]+=m.z,r[3*g]+=m.x,r[3*g+1]+=m.y,r[3*g+2]+=m.z;
|
|
for(l=0;l<c;l++)a=r[3*l],d=r[3*l+1],f=r[3*l+2],a=1/Math.sqrt(a*a+d*d+f*f),r[3*l]*=a,r[3*l+1]*=a,r[3*l+2]*=a;return r};
|
|
pc.calculateTangents=function(e,b,a,c){var d=c.length/3,f=e.length/3,g,l,h,p,k,n,q,m,r,t,u,x,v,w,y=new pc.Vec3,D=new pc.Vec3,B=new pc.Vec3,z=new pc.Vec3,A=new pc.Vec3,F=new pc.Vec2,I=new pc.Vec2,G=new pc.Vec2,H,C=new Float32Array(3*f),E=new Float32Array(3*f),K=[];for(H=0;H<d;H++)g=c[3*H],l=c[3*H+1],h=c[3*H+2],B.set(e[3*g],e[3*g+1],e[3*g+2]),z.set(e[3*l],e[3*l+1],e[3*l+2]),A.set(e[3*h],e[3*h+1],e[3*h+2]),F.set(a[2*g],a[2*g+1]),I.set(a[2*l],a[2*l+1]),G.set(a[2*h],a[2*h+1]),p=z.x-B.x,k=A.x-B.x,n=z.y-
|
|
B.y,q=A.y-B.y,m=z.z-B.z,r=A.z-B.z,t=I.x-F.x,u=G.x-F.x,x=I.y-F.y,v=G.y-F.y,w=t*v-u*x,0==w?(y.set(0,1,0),D.set(1,0,0)):(w=1/w,y.set((v*p-x*k)*w,(v*n-x*q)*w,(v*m-x*r)*w),D.set((t*k-u*p)*w,(t*q-u*n)*w,(t*r-u*m)*w)),C[3*g+0]+=y.x,C[3*g+1]+=y.y,C[3*g+2]+=y.z,C[3*l+0]+=y.x,C[3*l+1]+=y.y,C[3*l+2]+=y.z,C[3*h+0]+=y.x,C[3*h+1]+=y.y,C[3*h+2]+=y.z,E[3*g+0]+=D.x,E[3*g+1]+=D.y,E[3*g+2]+=D.z,E[3*l+0]+=D.x,E[3*l+1]+=D.y,E[3*l+2]+=D.z,E[3*h+0]+=D.x,E[3*h+1]+=D.y,E[3*h+2]+=D.z;x=new pc.Vec3;v=new pc.Vec3;e=new pc.Vec3;
|
|
a=new pc.Vec3;for(H=0;H<f;H++)e.set(b[3*H],b[3*H+1],b[3*H+2]),x.set(C[3*H],C[3*H+1],C[3*H+2]),v.set(E[3*H],E[3*H+1],E[3*H+2]),c=e.dot(x),a.copy(e).scale(c),a.sub2(x,a).normalize(),K[4*H]=a.x,K[4*H+1]=a.y,K[4*H+2]=a.z,a.cross(e,x),K[4*H+3]=0>a.dot(v)?-1:1;return K};
|
|
pc.createMesh=function(e,b,a){var c=a&&void 0!==a.normals?a.normals:null,d=a&&void 0!==a.tangents?a.tangents:null,f=a&&void 0!==a.colors?a.colors:null,g=a&&void 0!==a.uvs?a.uvs:null,l=a&&void 0!==a.uvs1?a.uvs1:null,h=a&&void 0!==a.indices?a.indices:null,p=a&&void 0!==a.blendIndices?a.blendIndices:null,k=a&&void 0!==a.blendWeights?a.blendWeights:null;a=[{semantic:pc.SEMANTIC_POSITION,components:3,type:pc.TYPE_FLOAT32}];null!==c&&a.push({semantic:pc.SEMANTIC_NORMAL,components:3,type:pc.TYPE_FLOAT32});
|
|
null!==d&&a.push({semantic:pc.SEMANTIC_TANGENT,components:4,type:pc.TYPE_FLOAT32});null!==f&&a.push({semantic:pc.SEMANTIC_COLOR,components:4,type:pc.TYPE_UINT8,normalize:!0});null!==g&&a.push({semantic:pc.SEMANTIC_TEXCOORD0,components:2,type:pc.TYPE_FLOAT32});null!==l&&a.push({semantic:pc.SEMANTIC_TEXCOORD1,components:2,type:pc.TYPE_FLOAT32});null!==p&&a.push({semantic:pc.SEMANTIC_BLENDINDICES,components:2,type:pc.TYPE_UINT8});null!==k&&a.push({semantic:pc.SEMANTIC_BLENDWEIGHT,components:2,type:pc.TYPE_FLOAT32});
|
|
var n=new pc.VertexFormat(e,a);a=b.length/3;for(var n=new pc.VertexBuffer(e,n,a),q=new pc.VertexIterator(n),m=0;m<a;m++)q.element[pc.SEMANTIC_POSITION].set(b[3*m],b[3*m+1],b[3*m+2]),null!==c&&q.element[pc.SEMANTIC_NORMAL].set(c[3*m],c[3*m+1],c[3*m+2]),null!==d&&q.element[pc.SEMANTIC_TANGENT].set(d[4*m],d[4*m+1],d[4*m+2],d[4*m+3]),null!==f&&q.element[pc.SEMANTIC_COLOR].set(f[4*m],f[4*m+1],f[4*m+2],f[4*m+3]),null!==g&&q.element[pc.SEMANTIC_TEXCOORD0].set(g[2*m],g[2*m+1]),null!==l&&q.element[pc.SEMANTIC_TEXCOORD1].set(l[2*
|
|
m],l[2*m+1]),null!==p&&q.element[pc.SEMANTIC_BLENDINDICES].set(p[2*m],p[2*m+1]),null!==k&&q.element[pc.SEMANTIC_BLENDWEIGHT].set(k[2*m],k[2*m+1]),q.next();q.end();c=null;if(d=null!==h)c=new pc.IndexBuffer(e,pc.INDEXFORMAT_UINT16,h.length),(new Uint16Array(c.lock())).set(h),c.unlock();e=new pc.BoundingBox;e.compute(b);b=new pc.Mesh;b.vertexBuffer=n;b.indexBuffer[0]=c;b.primitive[0].type=pc.PRIMITIVE_TRIANGLES;b.primitive[0].base=0;b.primitive[0].count=d?h.length:a;b.primitive[0].indexed=d;b.aabb=e;
|
|
return b};
|
|
pc.createTorus=function(e,b){var a=b&&void 0!==b.tubeRadius?b.tubeRadius:.2,c=b&&void 0!==b.ringRadius?b.ringRadius:.3,d=b&&void 0!==b.segments?b.segments:30,f=b&&void 0!==b.sides?b.sides:20,g=b&&void 0!==b.calculateTangents?b.calculateTangents:!1,l,h,p,k,n,q,m,r,t,u,x=[],v=[],w=[],y=[];for(l=0;l<=f;l++)for(h=0;h<=d;h++)p=Math.cos(2*Math.PI*h/d)*(c+a*Math.cos(2*Math.PI*l/f)),k=Math.sin(2*Math.PI*l/f)*a,n=Math.sin(2*Math.PI*h/d)*(c+a*Math.cos(2*Math.PI*l/f)),q=Math.cos(2*Math.PI*h/d)*Math.cos(2*Math.PI*
|
|
l/f),m=Math.sin(2*Math.PI*l/f),r=Math.sin(2*Math.PI*h/d)*Math.cos(2*Math.PI*l/f),t=l/f,u=1-h/d,x.push(p,k,n),v.push(q,m,r),w.push(t,u),l<f&&h<d&&(p=l*(d+1)+h,k=(l+1)*(d+1)+h,n=l*(d+1)+(h+1),q=(l+1)*(d+1)+(h+1),y.push(p,k,n),y.push(k,q,n));a={normals:v,uvs:w,indices:y};g&&(a.tangents=pc.calculateTangents(x,v,w,y));return pc.createMesh(e,x,a)};
|
|
pc._createConeData=function(e,b,a,c,d,f){var g,l,h,p,k,n=new pc.Vec3,q=new pc.Vec3;h=new pc.Vec3;var m,r=[],t=[],u=[],x=[],v=[],w;if(0<a)for(g=0;g<=c;g++)for(l=0;l<=d;l++)w=l/d*2*Math.PI-Math.PI,m=Math.sin(w),w=Math.cos(w),k=new pc.Vec3(m*e,-a/2,w*e),p=new pc.Vec3(m*b,a/2,w*b),n.lerp(k,p,g/c),q.sub2(p,k).normalize(),m=new pc.Vec3(w,0,-m),h.cross(m,q).normalize(),r.push(n.x,n.y,n.z),t.push(h.x,h.y,h.z),p=l/d,k=g/c,u.push(p,k),m=k,k=p,p=m,p/=3,p=p*primitiveUv1PaddingScale+primitiveUv1Padding,k=k*primitiveUv1PaddingScale+
|
|
primitiveUv1Padding,x.push(p,k),g<c&&l<d&&(m=g*(d+1)+l,w=g*(d+1)+(l+1),p=(g+1)*(d+1)+l,k=(g+1)*(d+1)+(l+1),v.push(m,w,p),v.push(w,k,p));if(f){e=Math.floor(d/2);g=a/2;for(a=0;a<=e;a++)for(w=a*Math.PI*.5/e,m=Math.sin(w),w=Math.cos(w),n=0;n<=d;n++)f=2*n*Math.PI/d-Math.PI/2,p=Math.sin(f),f=Math.cos(f),f*=m,l=w,h=p*m,p=1-n/d,k=1-a/e,r.push(f*b,l*b+g,h*b),t.push(f,l,h),u.push(p,k),p/=3,k/=3,p=p*primitiveUv1PaddingScale+primitiveUv1Padding,k=k*primitiveUv1PaddingScale+primitiveUv1Padding,p+=1/3,x.push(p,
|
|
k);q=(c+1)*(d+1);for(a=0;a<e;++a)for(n=0;n<d;++n)m=a*(d+1)+n,w=m+d+1,v.push(q+m+1,q+w,q+m),v.push(q+m+1,q+w+1,q+w);for(a=0;a<=e;a++)for(w=.5*Math.PI+a*Math.PI*.5/e,m=Math.sin(w),w=Math.cos(w),n=0;n<=d;n++)f=2*n*Math.PI/d-Math.PI/2,p=Math.sin(f),f=Math.cos(f),f*=m,l=w,h=p*m,p=1-n/d,k=1-a/e,r.push(f*b,l*b-g,h*b),t.push(f,l,h),u.push(p,k),p/=3,k/=3,p=p*primitiveUv1PaddingScale+primitiveUv1Padding,k=k*primitiveUv1PaddingScale+primitiveUv1Padding,p+=2/3,x.push(p,k);q=(c+1)*(d+1)+(d+1)*(e+1);for(a=0;a<
|
|
e;++a)for(n=0;n<d;++n)m=a*(d+1)+n,w=m+d+1,v.push(q+m+1,q+w,q+m),v.push(q+m+1,q+w+1,q+w)}else{q=(c+1)*(d+1);if(0<e)for(g=0;g<d;g++)w=g/d*2*Math.PI,f=Math.sin(w),l=-a/2,h=Math.cos(w),p=1-(f+1)/2,k=(h+1)/2,r.push(f*e,l,h*e),t.push(0,-1,0),u.push(p,k),p/=3,k/=3,p=p*primitiveUv1PaddingScale+primitiveUv1Padding,k=k*primitiveUv1PaddingScale+primitiveUv1Padding,p+=1/3,x.push(p,k),1<g&&v.push(q,q+g,q+g-1);q+=d;if(0<b)for(g=0;g<d;g++)w=g/d*2*Math.PI,f=Math.sin(w),l=a/2,h=Math.cos(w),p=1-(f+1)/2,k=(h+1)/2,r.push(f*
|
|
b,l,h*b),t.push(0,1,0),u.push(p,k),p/=3,k/=3,p=p*primitiveUv1PaddingScale+primitiveUv1Padding,k=k*primitiveUv1PaddingScale+primitiveUv1Padding,p+=2/3,x.push(p,k),1<g&&v.push(q,q+g-1,q+g)}return{positions:r,normals:t,uvs:u,uvs1:x,indices:v}};
|
|
pc.createCylinder=function(e,b){var a=b&&(b.radius||b.baseRadius),a=void 0!==a?a:.5,c=b&&void 0!==b.calculateTangents?b.calculateTangents:!1,a=pc._createConeData(a,a,b&&void 0!==b.height?b.height:1,b&&void 0!==b.heightSegments?b.heightSegments:5,b&&void 0!==b.capSegments?b.capSegments:20,!1);c&&(a.tangents=pc.calculateTangents(a.positions,a.normals,a.uvs,a.indices));return pc.createMesh(e,a.positions,a)};
|
|
pc.createCapsule=function(e,b){var a=b&&void 0!==b.radius?b.radius:.3,c=b&&void 0!==b.calculateTangents?b.calculateTangents:!1,a=pc._createConeData(a,a,(b&&void 0!==b.height?b.height:1)-2*a,b&&void 0!==b.heightSegments?b.heightSegments:1,b&&void 0!==b.sides?b.sides:20,!0);c&&(a.tangents=pc.calculateTangents(a.positions,a.normals,a.uvs,a.indices));return pc.createMesh(e,a.positions,a)};
|
|
pc.createCone=function(e,b){var a=b&&void 0!==b.calculateTangents?b.calculateTangents:!1,c=pc._createConeData(b&&void 0!==b.baseRadius?b.baseRadius:.5,b&&void 0!==b.peakRadius?b.peakRadius:0,b&&void 0!==b.height?b.height:1,b&&void 0!==b.heightSegments?b.heightSegments:5,b&&void 0!==b.capSegments?b.capSegments:18,!1);a&&(c.tangents=pc.calculateTangents(c.positions,c.normals,c.uvs,c.indices));return pc.createMesh(e,c.positions,c)};
|
|
pc.createSphere=function(e,b){var a=b&&void 0!==b.radius?b.radius:.5,c=b&&void 0!==b.latitudeBands?b.latitudeBands:16,d=b&&void 0!==b.longitudeBands?b.longitudeBands:16,f=b&&void 0!==b.calculateTangents?b.calculateTangents:!1,g,l,h,p,k,n,q,m,r,t=[],u=[],x=[],v=[];for(l=0;l<=c;l++)for(g=l*Math.PI/c,h=Math.sin(g),p=Math.cos(g),g=0;g<=d;g++)k=2*g*Math.PI/d-Math.PI/2,n=Math.sin(k),k=Math.cos(k),k*=h,q=p,n*=h,m=1-g/d,r=1-l/c,t.push(k*a,q*a,n*a),u.push(k,q,n),x.push(m,r);for(l=0;l<c;++l)for(g=0;g<d;++g)a=
|
|
l*(d+1)+g,h=a+d+1,v.push(a+1,h,a),v.push(a+1,h+1,h);c={normals:u,uvs:x,uvs1:x,indices:v};f&&(c.tangents=pc.calculateTangents(t,u,x,v));return pc.createMesh(e,t,c)};
|
|
pc.createPlane=function(e,b){var a=b&&void 0!==b.halfExtents?b.halfExtents:new pc.Vec2(.5,.5),c=b&&void 0!==b.widthSegments?b.widthSegments:5,d=b&&void 0!==b.lengthSegments?b.lengthSegments:5,f=b&&void 0!==b.calculateTangents?b.calculateTangents:!1,g,l,h,p,k,n,q=[],m=[],r=[],t=[],u=0;for(g=0;g<=c;g++)for(l=0;l<=d;l++)h=-a.x+2*a.x*g/c,p=-(-a.y+2*a.y*l/d),k=g/c,n=l/d,q.push(h,0,p),m.push(0,1,0),r.push(k,n),g<c&&l<d&&(t.push(u+d+1,u+1,u),t.push(u+d+1,u+d+2,u+1)),u++;a={normals:m,uvs:r,uvs1:r,indices:t};
|
|
f&&(a.tangents=pc.calculateTangents(q,m,r,t));return pc.createMesh(e,q,a)};
|
|
pc.createBox=function(e,b){var a=b&&void 0!==b.halfExtents?b.halfExtents:new pc.Vec3(.5,.5,.5),c=b&&void 0!==b.widthSegments?b.widthSegments:1,d=b&&void 0!==b.lengthSegments?b.lengthSegments:1,f=b&&void 0!==b.heightSegments?b.heightSegments:1,g=b&&void 0!==b.calculateTangents?b.calculateTangents:!1,l=[new pc.Vec3(-a.x,-a.y,a.z),new pc.Vec3(a.x,-a.y,a.z),new pc.Vec3(a.x,a.y,a.z),new pc.Vec3(-a.x,a.y,a.z),new pc.Vec3(a.x,-a.y,-a.z),new pc.Vec3(-a.x,-a.y,-a.z),new pc.Vec3(-a.x,a.y,-a.z),new pc.Vec3(a.x,
|
|
a.y,-a.z)],h=[[0,1,3],[4,5,7],[3,2,6],[1,0,4],[1,4,2],[5,0,6]],p=[[0,0,1],[0,0,-1],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0]],k=[],n=[],q=[],m=[],r=[],t=0,a=function(a,b,c){var d,f,g,e;for(g=0;g<=b;g++)for(e=0;e<=c;e++){d=new pc.Vec3;f=new pc.Vec3;var u=new pc.Vec3,v=new pc.Vec3;d.lerp(l[h[a][0]],l[h[a][1]],g/b);f.lerp(l[h[a][0]],l[h[a][2]],e/c);u.sub2(f,l[h[a][0]]);v.add2(d,u);d=g/b;f=e/c;k.push(v.x,v.y,v.z);n.push(p[a][0],p[a][1],p[a][2]);q.push(d,f);d/=3;f/=3;d=d*primitiveUv1PaddingScale+primitiveUv1Padding;
|
|
f=f*primitiveUv1PaddingScale+primitiveUv1Padding;d+=a%3/3;f+=Math.floor(a/3)/3;m.push(d,f);g<b&&e<c&&(r.push(t+c+1,t+1,t),r.push(t+c+1,t+c+2,t+1));t++}};a(0,c,f);a(1,c,f);a(2,c,d);a(3,c,d);a(4,d,f);a(5,d,f);c={normals:n,uvs:q,uvs1:m,indices:r};g&&(c.tangents=pc.calculateTangents(k,n,q,r));return pc.createMesh(e,k,c)};pc.getDefaultMaterial=function(){return pc.Application.getApplication().scene.defaultMaterial};Object.assign(pc,function(){function e(a,b){return a.priority-b.priority}function b(a,b){return b.key-a.key}var a,c,d,f,g=[null,function(a,b){return a.drawOrder-b.drawOrder},function(b,d){a=b._key[pc.SORTKEY_FORWARD];c=d._key[pc.SORTKEY_FORWARD];return a===c&&b.mesh&&d.mesh?d.mesh.id-b.mesh.id:c-a},function(a,b){return b.zdist-a.zdist},function(a,b){return a.zdist-b.zdist}],l=0,h=function(){this.opaqueMeshInstances=[];this.transparentMeshInstances=[];this.shadowCasters=[];this.visibleOpaque=[];this.visibleTransparent=
|
|
[]};h.prototype.clearVisibleLists=function(a){this.visibleOpaque[a]&&(this.visibleOpaque[a].length=0,this.visibleOpaque[a].list.length=0);this.visibleTransparent[a]&&(this.visibleTransparent[a].length=0,this.visibleTransparent[a].list.length=0)};var p=function(a){a=a||{};void 0!==a.id?(this.id=a.id,l=Math.max(this.id+1,l)):this.id=l++;this.name=a.name;this._refCounter=(this._enabled=void 0===a.enabled?!0:a.enabled)?1:0;this.opaqueSortMode=void 0===a.opaqueSortMode?pc.SORTMODE_MATERIALMESH:a.opaqueSortMode;
|
|
this.transparentSortMode=void 0===a.transparentSortMode?pc.SORTMODE_BACK2FRONT:a.transparentSortMode;this.renderTarget=a.renderTarget;this.shaderPass=void 0===a.shaderPass?pc.SHADER_FORWARD:a.shaderPass;this.passThrough=void 0===a.passThrough?!1:a.passThrough;this.overrideClear=void 0===a.overrideClear?!1:a.overrideClear;this._clearColor=new pc.Color(0,0,0,1);a.clearColor&&this._clearColor.copy(a.clearColor);this._clearColorBuffer=void 0===a.clearColorBuffer?!1:a.clearColorBuffer;this._clearDepthBuffer=
|
|
void 0===a.clearDepthBuffer?!1:a.clearDepthBuffer;this._clearStencilBuffer=void 0===a.clearStencilBuffer?!1:a.clearStencilBuffer;this._clearOptions={color:[this._clearColor.r,this._clearColor.g,this._clearColor.b,this._clearColor.a],depth:1,stencil:0,flags:(this._clearColorBuffer?pc.CLEARFLAG_COLOR:0)|(this._clearDepthBuffer?pc.CLEARFLAG_DEPTH:0)|(this._clearStencilBuffer?pc.CLEARFLAG_STENCIL:0)};this.onPreCull=a.onPreCull;this.onPreRender=a.onPreRender;this.onPreRenderOpaque=a.onPreRenderOpaque;
|
|
this.onPreRenderTransparent=a.onPreRenderTransparent;this.onPostCull=a.onPostCull;this.onPostRender=a.onPostRender;this.onPostRenderOpaque=a.onPostRenderOpaque;this.onPostRenderTransparent=a.onPostRenderTransparent;this.onDrawCall=a.onDrawCall;this.onEnable=a.onEnable;this.onDisable=a.onDisable;if(this._enabled&&this.onEnable)this.onEnable();this.instances=(this.layerReference=a.layerReference)?a.layerReference.instances:new h;this.cullingMask=a.cullingMask?a.cullingMask:4294967295;this.opaqueMeshInstances=
|
|
this.instances.opaqueMeshInstances;this.transparentMeshInstances=this.instances.transparentMeshInstances;this.shadowCasters=this.instances.shadowCasters;this.customCalculateSortValues=this.customSortCallback=null;this._lightComponents=[];this._lights=[];this._sortedLights=[[],[],[]];this.cameras=[];this._dirtyCameras=this._dirtyLights=this._dirty=!1;this._staticLightHash=this._lightHash=this._cameraHash=0;this._needsStaticPrepare=!0;this._staticPrepareDone=!1;this._shaderVersion=-1;this._version=
|
|
0;this._lightCube=null};Object.defineProperty(p.prototype,"enabled",{get:function(){return this._enabled},set:function(a){if(a!==this._enabled)if(this._enabled=a){if(this.incrementCounter(),this.onEnable)this.onEnable()}else if(this.decrementCounter(),this.onDisable)this.onDisable()}});Object.defineProperty(p.prototype,"clearColor",{get:function(){return this._clearColor},set:function(a){this._clearColor.copy(a)}});p.prototype._updateClearFlags=function(){var a=0;this._clearColorBuffer&&(a|=pc.CLEARFLAG_COLOR);
|
|
this._clearDepthBuffer&&(a|=pc.CLEARFLAG_DEPTH);this._clearStencilBuffer&&(a|=pc.CLEARFLAG_STENCIL);this._clearOptions.flags=a};Object.defineProperty(p.prototype,"clearColorBuffer",{get:function(){return this._clearColorBuffer},set:function(a){this._clearColorBuffer=a;this._updateClearFlags()}});Object.defineProperty(p.prototype,"clearDepthBuffer",{get:function(){return this._clearDepthBuffer},set:function(a){this._clearDepthBuffer=a;this._updateClearFlags()}});Object.defineProperty(p.prototype,"clearStencilBuffer",
|
|
{get:function(){return this._clearStencilBuffer},set:function(a){this._clearStencilBuffer=a;this._updateClearFlags()}});p.prototype.incrementCounter=function(){if(0===this._refCounter&&(this._enabled=!0,this.onEnable))this.onEnable();this._refCounter++};p.prototype.decrementCounter=function(){if(1===this._refCounter){if(this._enabled=!1,this.onDisable)this.onDisable()}else if(0===this._refCounter)return;this._refCounter--};p.prototype.addMeshInstances=function(a,b){for(var c=this._shaderVersion,d,
|
|
f,g,e=this.shadowCasters,h=0;h<a.length;h++)d=a[h],g=d.material,f=g.blendType===pc.BLEND_NONE?this.opaqueMeshInstances:this.transparentMeshInstances,0>f.indexOf(d)&&f.push(d),!b&&d.castShadow&&0>e.indexOf(d)&&e.push(d),!this.passThrough&&0<=c&&g._shaderVersion!==c&&(g.updateShader!==pc.Material.prototype.updateShader&&(g.clearVariants(),g.shader=null),g._shaderVersion=c);this.passThrough||(this._dirty=!0)};p.prototype.removeMeshInstances=function(a,b){var c,d,f,g,e,h,l,k=this.opaqueMeshInstances,
|
|
p=this.transparentMeshInstances,n=this.shadowCasters;for(c=0;c<a.length;c++){f=a[c];g=-1;e=0;h=k.length;for(d=0;d<h;d++){l=k[d];if(l===f){g=d;e=1;break}if(l._staticSource===f)0>g&&(g=d),e++;else if(0<=g)break}0<=g&&k.splice(g,e);g=-1;e=0;h=p.length;for(d=0;d<h;d++){l=p[d];if(l===f){g=d;e=1;break}if(l._staticSource===f)0>g&&(g=d),e++;else if(0<=g)break}0<=g&&p.splice(g,e);b||(d=n.indexOf(f),0<=d&&n.splice(d,1))}this._dirty=!0};p.prototype.clearMeshInstances=function(a){if(0!==this.opaqueMeshInstances.length||
|
|
0!==this.transparentMeshInstances.length||!a&&0!==this.shadowCasters.length)this.opaqueMeshInstances.length=0,this.transparentMeshInstances.length=0,a||(this.shadowCasters.length=0),this.passThrough||(this._dirty=!0)};p.prototype.addLight=function(a){0<=this._lightComponents.indexOf(a)||(this._lightComponents.push(a),this._lights.push(a.light),this._dirtyLights=!0,this._generateLightHash())};p.prototype.removeLight=function(a){var b=this._lightComponents.indexOf(a);0>b||(this._lightComponents.splice(b,
|
|
1),b=this._lights.indexOf(a.light),this._lights.splice(b,1),this._dirtyLights=!0,this._generateLightHash())};p.prototype.clearLights=function(){this._lightComponents.length=0;this._lights.length=0;this._dirtyLights=!0};p.prototype.addShadowCasters=function(a){for(var b,c=this.shadowCasters,d=0;d<a.length;d++)b=a[d],b.castShadow&&0>c.indexOf(b)&&c.push(b);this._dirtyLights=!0};p.prototype.removeShadowCasters=function(a){for(var b,c=this.shadowCasters,d=0;d<a.length;d++)b=c.indexOf(a[d]),0<=b&&c.splice(b,
|
|
1);this._dirtyLights=!0};p.prototype._generateLightHash=function(){if(0<this._lights.length){this._lights.sort(b);for(var a="",c="",d=0;d<this._lights.length;d++)this._lights[d].isStatic?c+=this._lights[d].key:a+=this._lights[d].key;this._lightHash=0===a.length?0:pc.hashCode(a);this._staticLightHash=0===c.length?0:pc.hashCode(c)}else this._staticLightHash=this._lightHash=0};p.prototype._generateCameraHash=function(){if(1<this.cameras.length){this.cameras.sort(e);for(var a="",b=0;b<this.cameras.length;b++)a+=
|
|
this.cameras[b].entity.getGuid();this._cameraHash=pc.hashCode(a)}else this._cameraHash=0;this._dirtyCameras=!0};p.prototype.addCamera=function(a){0<=this.cameras.indexOf(a)||(this.cameras.push(a),this._generateCameraHash())};p.prototype.removeCamera=function(a){a=this.cameras.indexOf(a);0>a||(this.cameras.splice(a,1),this._generateCameraHash(),this.instances.clearVisibleLists(a))};p.prototype.clearCameras=function(){this._cameraHash=this.cameras.length=0;this._dirtyCameras=!0};p.prototype._sortCameras=
|
|
function(){this._generateCameraHash()};p.prototype._calculateSortDistances=function(a,b,c,d){var f,g,e,h,l;for(f=0;f<b;f++)g=a[f],g.command||g.layer<=pc.LAYER_FX||(e=g.aabb.center,h=e.x-c.x,l=e.y-c.y,e=e.z-c.z,g.zdist=h*d.x+l*d.y+e*d.z)};p.prototype._sortVisible=function(a,b,c){var e=this.instances,h=a?this.transparentSortMode:this.opaqueSortMode;if(h!==pc.SORTMODE_NONE)if(a=a?e.visibleTransparent[c]:e.visibleOpaque[c],h===pc.SORTMODE_CUSTOM)d=b.getPosition(),f=b.forward,this.customCalculateSortValues&&
|
|
this.customCalculateSortValues(a.list,a.length,d,f),a.list.length!==a.length&&(a.list.length=a.length),this.customSortCallback&&a.list.sort(this.customSortCallback);else{if(h===pc.SORTMODE_BACK2FRONT||h===pc.SORTMODE_FRONT2BACK)d=b.getPosition(),f=b.forward,this._calculateSortDistances(a.list,a.length,d,f);a.list.length!==a.length&&(a.list.length=a.length);a.list.sort(g[h])}};return{Layer:p,InstanceList:h,VisibleInstanceList:function(){this.list=[];this.length=0;this.done=!1}}}());Object.assign(pc,function(){var e=function(){this.layerList=[];this.subLayerList=[];this.subLayerEnabled=[];this._opaqueOrder={};this._transparentOrder={};this._dirtyCameras=this._dirtyLights=this._dirtyBlend=this._dirty=!1;this._meshInstances=[];this._lights=[];this.cameras=[];this._sortedLights=[[],[],[]];this._lightShadowCasters=[];this._globalLightCameras=[];this._globalLightCameraIds=[];this._renderedRt=[];this._renderedByCam=[];this._renderedLayer=[];this._renderList=[];this._renderListCamera=
|
|
[];pc.events.attach(this)};e.prototype._sortLights=function(b){var a,c=b._lights;b._sortedLights[pc.LIGHTTYPE_DIRECTIONAL].length=0;b._sortedLights[pc.LIGHTTYPE_POINT].length=0;for(var d=b._sortedLights[pc.LIGHTTYPE_SPOT].length=0;d<c.length;d++)a=c[d],a._enabled&&b._sortedLights[a._type].push(a)};e.prototype._update=function(){var b,a,c,d,f=this.layerList.length,g=0;if(!this._dirty||!this._dirtyLights||!this._dirtyCameras)for(b=0;b<f;b++)d=this.layerList[b],d._dirty&&(this._dirty=!0),d._dirtyLights&&
|
|
(this._dirtyLights=!0),d._dirtyCameras&&(this._dirtyCameras=!0);var e;if(this._dirty){g|=pc.COMPUPDATED_INSTANCES;for(b=this._meshInstances.length=0;b<f;b++)if(d=this.layerList[b],!d.passThrough){e=d.opaqueMeshInstances;for(a=0;a<e.length;a++)c=e[a],0>this._meshInstances.indexOf(c)&&(this._meshInstances.push(c),c.material&&c.material._dirtyBlend&&(this._dirtyBlend=!0,c.material._dirtyBlend=!1));e=d.transparentMeshInstances;for(a=0;a<e.length;a++)c=e[a],0>this._meshInstances.indexOf(c)&&(this._meshInstances.push(c),
|
|
c.material&&c.material._dirtyBlend&&(this._dirtyBlend=!0,c.material._dirtyBlend=!1))}for(b=0;b<f;b++)this.layerList[b]._dirty=!1,this.layerList[b]._version++}if(this._dirtyBlend){var g=g|pc.COMPUPDATED_BLEND,h,p;for(b=0;b<f;b++)if(d=this.layerList[b],!d.passThrough){e=d.opaqueMeshInstances;c=d.transparentMeshInstances;h=[];p=[];for(a=0;a<e.length;a++)e[a].material&&e[a].material.blendType!==pc.BLEND_NONE?p.push(e[a]):h.push(e[a]);for(a=0;a<c.length;a++)c[a].material&&c[a].material.blendType!==pc.BLEND_NONE?
|
|
p.push(c[a]):h.push(c[a]);d.opaqueMeshInstances.length=h.length;for(a=0;a<h.length;a++)d.opaqueMeshInstances[a]=h[a];d.transparentMeshInstances.length=p.length;for(a=0;a<p.length;a++)d.transparentMeshInstances[a]=p[a]}this._dirtyBlend=!1}this._dirty=!1;if(this._dirtyLights)for(g|=pc.COMPUPDATED_LIGHTS,this._lights.length=0,b=this._lightShadowCasters.length=0;b<f;b++)for(d=this.layerList[b],e=d._lights,a=0;a<e.length;a++)h=e[a],c=this._lights.indexOf(h),0>c&&(this._lights.push(h),c=this._lights.length-
|
|
1),(h=this._lightShadowCasters[c])||(this._lightShadowCasters[c]=[]);if(this._dirtyLights)for(this._sortLights(this),this._dirtyLights=!1,b=0;b<f;b++)d=this.layerList[b],this._sortLights(d),d._dirtyLights=!1;if(g)for(b=0;b<f;b++)for(d=this.layerList[b],e=d._lights,a=0;a<e.length;a++){h=e[a];c=this._lights.indexOf(h);h=this._lightShadowCasters[c];p=d.shadowCasters;for(c=0;c<h.length;)0>this._meshInstances.indexOf(h[c])?(h[c]=h[h.length-1],--h.length):c++;for(c=0;c<p.length;c++)0>h.indexOf(p[c])&&h.push(p[c])}if(g&
|
|
pc.COMPUPDATED_LIGHTS||this._dirtyCameras)for(this._globalLightCameras.length=0,e=this._sortedLights[pc.LIGHTTYPE_DIRECTIONAL],a=0;a<e.length;a++)for(h=e[a],this._globalLightCameras[a]=[],b=0;b<f;b++)if(d=this.layerList[b],!(0>d._sortedLights[pc.LIGHTTYPE_DIRECTIONAL].indexOf(h)))for(c=0;c<d.cameras.length;c++)0<=this._globalLightCameras[a].indexOf(d.cameras[c])||this._globalLightCameras[a].push(d.cameras[c]);if(this._dirtyCameras){g|=pc.COMPUPDATED_CAMERAS;for(b=this.cameras.length=0;b<f;b++)for(d=
|
|
this.layerList[b],a=0;a<d.cameras.length;a++)e=d.cameras[a],c=this.cameras.indexOf(e),0>c&&this.cameras.push(e);this._renderList.length=0;for(b=c=this._renderListCamera.length=0;b<f;b++)if(c)c--;else if(d=this.layerList[b],0!==d.cameras.length||d.isPostEffect)if(h=d._cameraHash,0===h)this._renderList.push(b),this._renderListCamera.push(0);else{e=1;for(a=b+1;a<f;a++)if(p=this.layerList[a]._cameraHash,h!==p){e=a-b-1;break}else a===f-1&&(e=a-b);if(1===e)for(h=0;h<d.cameras.length;h++)this._renderList.push(b),
|
|
this._renderListCamera.push(h);else{for(h=0;h<d.cameras.length;h++)for(a=0;a<=e;a++)this._renderList.push(b+a),this._renderListCamera.push(h);c=e}}this._dirtyCameras=!1;for(b=0;b<f;b++)this.layerList[b]._dirtyCameras=!1}if(g&pc.COMPUPDATED_LIGHTS||g&pc.COMPUPDATED_CAMERAS)for(a=this._globalLightCameraIds.length=0;a<this._globalLightCameras.length;a++){e=[];for(b=0;b<this._globalLightCameras[a].length;b++)c=this.cameras.indexOf(this._globalLightCameras[a][b]),0>c||e.push(c);this._globalLightCameraIds.push(e)}return g};
|
|
e.prototype._isLayerAdded=function(b){return 0<=this.layerList.indexOf(b)?!0:!1};e.prototype._isSublayerAdded=function(b,a){for(var c=0;c<this.layerList.length;c++)if(this.layerList[c]===b&&this.subLayerList[c]===a)return!0;return!1};e.prototype.push=function(b){this._isLayerAdded(b)||(this.layerList.push(b),this.layerList.push(b),this._opaqueOrder[b.id]=this.subLayerList.push(!1)-1,this._transparentOrder[b.id]=this.subLayerList.push(!0)-1,this.subLayerEnabled.push(!0),this.subLayerEnabled.push(!0),
|
|
this._dirtyCameras=this._dirtyLights=this._dirty=!0,this.fire("add",b))};e.prototype.insert=function(b,a){if(!this._isLayerAdded(b)){this.layerList.splice(a,0,b,b);this.subLayerList.splice(a,0,!1,!0);var c=this.layerList.length;this._updateOpaqueOrder(a,c-1);this._updateTransparentOrder(a,c-1);this.subLayerEnabled.splice(a,0,!0,!0);this._dirtyCameras=this._dirtyLights=this._dirty=!0;this.fire("add",b)}};e.prototype.remove=function(b){var a=this.layerList.indexOf(b);delete this._opaqueOrder[a];for(delete this._transparentOrder[a];0<=
|
|
a;)this.layerList.splice(a,1),this.subLayerList.splice(a,1),this.subLayerEnabled.splice(a,1),a=this.layerList.indexOf(b),this._dirtyCameras=this._dirtyLights=this._dirty=!0,this.fire("remove",b);b=this.layerList.length;this._updateOpaqueOrder(0,b-1);this._updateTransparentOrder(0,b-1)};e.prototype.pushOpaque=function(b){this._isSublayerAdded(b,!1)||(this.layerList.push(b),this._opaqueOrder[b.id]=this.subLayerList.push(!1)-1,this.subLayerEnabled.push(!0),this._dirtyCameras=this._dirtyLights=this._dirty=
|
|
!0,this.fire("add",b))};e.prototype.insertOpaque=function(b,a){this._isSublayerAdded(b,!1)||(this.layerList.splice(a,0,b),this.subLayerList.splice(a,0,!1),this._updateOpaqueOrder(a,this.subLayerList.length-1),this.subLayerEnabled.splice(a,0,!0),this._dirtyCameras=this._dirtyLights=this._dirty=!0,this.fire("add",b))};e.prototype.removeOpaque=function(b){for(var a=0,c=this.layerList.length;a<c;a++)if(this.layerList[a]===b&&!this.subLayerList[a]){this.layerList.splice(a,1);this.subLayerList.splice(a,
|
|
1);c--;this._updateOpaqueOrder(a,c-1);this.subLayerEnabled.splice(a,1);this._dirtyCameras=this._dirtyLights=this._dirty=!0;0>this.layerList.indexOf(b)&&this.fire("remove",b);break}};e.prototype.pushTransparent=function(b){this._isSublayerAdded(b,!0)||(this.layerList.push(b),this._transparentOrder[b.id]=this.subLayerList.push(!0)-1,this.subLayerEnabled.push(!0),this._dirtyCameras=this._dirtyLights=this._dirty=!0,this.fire("add",b))};e.prototype.insertTransparent=function(b,a){this._isSublayerAdded(b,
|
|
!0)||(this.layerList.splice(a,0,b),this.subLayerList.splice(a,0,!0),this._updateTransparentOrder(a,this.subLayerList.length-1),this.subLayerEnabled.splice(a,0,!0),this._dirtyCameras=this._dirtyLights=this._dirty=!0,this.fire("add",b))};e.prototype.removeTransparent=function(b){for(var a=0,c=this.layerList.length;a<c;a++)if(this.layerList[a]===b&&this.subLayerList[a]){this.layerList.splice(a,1);this.subLayerList.splice(a,1);c--;this._updateTransparentOrder(a,c-1);this.subLayerEnabled.splice(a,1);this._dirtyCameras=
|
|
this._dirtyLights=this._dirty=!0;0>this.layerList.indexOf(b)&&this.fire("remove",b);break}};e.prototype._getSublayerIndex=function(b,a){var c=this.layerList.indexOf(b);return 0>c||this.subLayerList[c]!==a&&(c=this.layerList.indexOf(b,c+1),0>c||this.subLayerList[c]!==a)?-1:c};e.prototype.getOpaqueIndex=function(b){return this._getSublayerIndex(b,!1)};e.prototype.getTransparentIndex=function(b){return this._getSublayerIndex(b,!0)};e.prototype.getLayerById=function(b){for(var a=0;a<this.layerList.length;a++)if(this.layerList[a].id===
|
|
b)return this.layerList[a];return null};e.prototype.getLayerByName=function(b){for(var a=0;a<this.layerList.length;a++)if(this.layerList[a].name===b)return this.layerList[a];return null};e.prototype._updateOpaqueOrder=function(b,a){for(var c=b;c<=a;c++)!1===this.subLayerList[c]&&(this._opaqueOrder[this.layerList[c].id]=c)};e.prototype._updateTransparentOrder=function(b,a){for(var c=b;c<=a;c++)!0===this.subLayerList[c]&&(this._transparentOrder[this.layerList[c].id]=c)};e.prototype._sortLayersDescending=
|
|
function(b,a,c){var d,f,g,e=-1,h=-1;d=0;for(f=b.length;d<f;d++)g=b[d],c.hasOwnProperty(g)&&(e=Math.max(e,c[g]));d=0;for(f=a.length;d<f;d++)g=a[d],c.hasOwnProperty(g)&&(h=Math.max(h,c[g]));return-1===e&&-1!==h?1:-1===h&&-1!==e?-1:h-e};e.prototype.sortTransparentLayers=function(b,a){return this._sortLayersDescending(b,a,this._transparentOrder)};e.prototype.sortOpaqueLayers=function(b,a){return this._sortLayersDescending(b,a,this._opaqueOrder)};return{LayerComposition:e}}());Object.assign(pc,function(){pc.SPRITE_RENDERMODE_SIMPLE=0;pc.SPRITE_RENDERMODE_SLICED=1;pc.SPRITE_RENDERMODE_TILED=2;var e=[0,0,1,0,0,1,0,0,1,0,0,1],b=[0,1,3,2,3,1],a=function(a,b){this._device=a;this._pixelsPerUnit=b&&void 0!==b.pixelsPerUnit?b.pixelsPerUnit:1;this._renderMode=b&&void 0!==b.renderMode?b.renderMode:pc.SPRITE_RENDERMODE_SIMPLE;this._atlas=b&&void 0!==b.atlas?b.atlas:null;this._frameKeys=b&&void 0!==b.frameKeys?b.frameKeys:null;this._meshes=[];this._meshesDirty=this._updatingProperties=
|
|
!1;pc.events.attach(this);this._atlas&&this._frameKeys&&this._createMeshes()};a.prototype._createMeshes=function(){var a,b;a=0;for(b=this._meshes.length;a<b;a++){var f=this._meshes[a];if(f){f.vertexBuffer.destroy();for(var g=0,e=f.indexBuffer.length;g<e;g++)f.indexBuffer[g].destroy()}}b=this._frameKeys.length;this._meshes=Array(b);f=this.renderMode===pc.SPRITE_RENDERMODE_SLICED||this._renderMode===pc.SPRITE_RENDERMODE_TILED?this._create9SliceMesh:this._createSimpleMesh;for(a=0;a<b;a++)g=this._atlas.frames[this._frameKeys[a]],
|
|
this._meshes[a]=g?f.call(this,g):null;this.fire("set:meshes")};a.prototype._createSimpleMesh=function(a){var c=a.rect,f=this._atlas.texture.width,g=this._atlas.texture.height,l=c.z/this._pixelsPerUnit,h=c.w/this._pixelsPerUnit,p=a.pivot.x;a=a.pivot.y;var k=c.x/f,n=c.y/g,f=(c.x+c.z)/f,c=(c.y+c.w)/g;return pc.createMesh(this._device,[-p*l,-a*h,0,(1-p)*l,-a*h,0,(1-p)*l,(1-a)*h,0,-p*l,(1-a)*h,0],{uvs:[k,n,f,n,f,c,k,c],normals:e,indices:b})};a.prototype._create9SliceMesh=function(){var a=pc.Vec2.ONE,b,
|
|
f,g,e,h,p,k=[],n=[],q=[],m=[],r=0;for(b=0;3>=b;b++)for(h=0===b||3===b?0:1,f=0;3>=f;f++)g=-a.x+2*a.x*(1>=b?0:3)/3,e=-(-a.y+2*a.y*(1>=f?0:3)/3),p=0===f||3===f?0:1,k.push(-g,0,e),n.push(0,1,0),q.push(h,p),3>b&&3>f&&(m.push(r+3+1,r+1,r),m.push(r+3+1,r+3+2,r+1)),r++;return pc.createMesh(this._device,k,{normals:n,uvs:q,indices:m})};a.prototype._onSetFrames=function(a){this._updatingProperties?this._meshesDirty=!0:this._createMeshes()};a.prototype._onFrameChanged=function(a,b){var c=this._frameKeys.indexOf(a);
|
|
0>c||(b?this.renderMode===pc.SPRITE_RENDERMODE_SIMPLE&&(this._meshes[c]=this._createSimpleMesh(b)):this._meshes[c]=null,this.fire("set:meshes"))};a.prototype._onFrameRemoved=function(a){a=this._frameKeys.indexOf(a);0>a||(this._meshes[a]=null,this.fire("set:meshes"))};a.prototype.startUpdate=function(){this._updatingProperties=!0;this._meshesDirty=!1};a.prototype.endUpdate=function(){this._updatingProperties=!1;this._meshesDirty&&this._atlas&&this._frameKeys&&this._createMeshes();this._meshesDirty=
|
|
!1};a.prototype.destroy=function(){var a,b;a=0;for(b=this._meshes.length;a<b;a++){var f=this._meshes[a];if(f){f.vertexBuffer.destroy();for(var g=0,e=f.indexBuffer.length;g<e;g++)f.indexBuffer[g].destroy()}}this._meshes.length=0};Object.defineProperty(a.prototype,"frameKeys",{get:function(){return this._frameKeys},set:function(a){this._frameKeys=a;this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes());this.fire("set:frameKeys",a)}});Object.defineProperty(a.prototype,
|
|
"atlas",{get:function(){return this._atlas},set:function(a){a!==this._atlas&&(this._atlas&&(this._atlas.off("set:frames",this._onSetFrames,this),this._atlas.off("set:frame",this._onFrameChanged,this),this._atlas.off("remove:frame",this._onFrameRemoved,this)),(this._atlas=a)&&this._frameKeys&&(this._atlas.on("set:frames",this._onSetFrames,this),this._atlas.on("set:frame",this._onFrameChanged,this),this._atlas.on("remove:frame",this._onFrameRemoved,this),this._updatingProperties?this._meshesDirty=!0:
|
|
this._createMeshes()),this.fire("set:atlas",a))}});Object.defineProperty(a.prototype,"pixelsPerUnit",{get:function(){return this._pixelsPerUnit},set:function(a){this._pixelsPerUnit!==a&&(this._pixelsPerUnit=a,this.fire("set:pixelsPerUnit",a),this._atlas&&this._frameKeys&&this.renderMode===pc.SPRITE_RENDERMODE_SIMPLE&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes()))}});Object.defineProperty(a.prototype,"renderMode",{get:function(){return this._renderMode},set:function(a){if(this._renderMode!==
|
|
a){var b=this._renderMode;this._renderMode=a;this.fire("set:renderMode",a);(b===pc.SPRITE_RENDERMODE_SIMPLE||a===pc.SPRITE_RENDERMODE_SIMPLE)&&this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes())}}});Object.defineProperty(a.prototype,"meshes",{get:function(){return this._meshes}});return{Sprite:a}}());Object.assign(pc,function(){var e=function(){this._index=[];this._values=[]};e.prototype.runSync=function(){for(var a=0,b=this._values.length;a<b;a++)this._values[a].syncHierarchy();this._values.length=0;this._index.length=0};e.prototype.erase=function(a){a=this._values.indexOf(a);0<=a&&(this._index.splice(a,1),this._values.splice(a,1))};var b=function(a,c,d,f){if(c===d)return c;var g=Math.floor((c+d)/2);return a[g]>f?b(a,c,g,f):a[g]<f?b(a,g+1,d,f):g};e.prototype.push=function(a,c){var d=b(this._index,
|
|
0,this._index.length,a);this._values.splice(d,0,c);this._index.splice(d,0,a)};return{SyncQueue:e}}());Object.assign(pc,function(){var e=function(){this._frames=this._texture=null;pc.events.attach(this)};e.prototype.setFrame=function(b,a){var c=this._frames[b];c?(c.rect.copy(a.rect),c.pivot.copy(a.pivot),c.border.copy(a.border)):(c={rect:a.rect.clone(),pivot:a.pivot.clone(),border:a.border.clone()},this._frames[b]=c);this.fire("set:frame",b.toString(),c)};e.prototype.removeFrame=function(b){var a=this._frames[b];a&&(delete this._frames[b],this.fire("remove:frame",b.toString(),a))};e.prototype.destroy=
|
|
function(){this._texture&&this._texture.destroy()};Object.defineProperty(e.prototype,"texture",{get:function(){return this._texture},set:function(b){this._texture=b;this.fire("set:texture",b)}});Object.defineProperty(e.prototype,"frames",{get:function(){return this._frames},set:function(b){this._frames=b;this.fire("set:frames",b)}});return{TextureAtlas:e}}());Object.assign(pc,function(){var e=function(b){this.func=void 0===b.func?pc.FUNC_ALWAYS:b.func;this.ref=b.ref||0;this.readMask=void 0===b.readMask?255:b.readMask;this.writeMask=void 0===b.writeMask?255:b.writeMask;this.fail=b.fail||pc.STENCILOP_KEEP;this.zfail=b.zfail||pc.STENCILOP_KEEP;this.zpass=b.zpass||pc.STENCILOP_KEEP};e.prototype.clone=function(){return new pc.StencilParameters({func:this.func,ref:this.ref,readMask:this.readMask,writeMask:this.writeMask,fail:this.fail,zfail:this.zfail,zpass:this.zpass})};
|
|
return{StencilParameters:e}}());Object.assign(pc,function(){var e=function(){this.name="";this.duration=0;this._nodes=[];this._nodeDict={}};e.prototype.getDuration=function(){return this.duration};e.prototype.getName=function(){return this.name};e.prototype.getNode=function(b){return this._nodeDict[b]};Object.defineProperty(e.prototype,"nodes",{get:function(){return this._nodes}});e.prototype.getNodes=function(){return this._nodes};e.prototype.setDuration=function(b){this.duration=b};e.prototype.setName=function(b){this.name=b};
|
|
e.prototype.addNode=function(b){this._nodes.push(b);this._nodeDict[b._name]=b};return{Animation:e,Key:function(b,a,c,d){this.time=b;this.position=a;this.rotation=c;this.scale=d},Node:function(){this._name="";this._keys=[]}}}());Object.assign(pc,function(){function e(){this._written=!1;this._name="";this._keyFrames=[];this._quat=new pc.Quat;this._pos=new pc.Vec3;this._scale=new pc.Vec3;this._targetNode=null}Object.assign(e.prototype,{getTarget:function(){return this._targetNode},setTarget:function(a){this._targetNode=a}});var b=function(a){function b(a){var c=new e;c._name=a.name;d._interpolatedKeys.push(c);d._interpolatedKeyDict[a.name]=c;for(c=d._currKeyIndices[a.name]=0;c<a._children.length;c++)b(a._children[c])}this._animation=
|
|
null;this._time=0;this.looping=!0;this._interpolatedKeys=[];this._interpolatedKeyDict={};this._currKeyIndices={};this.graph=null;var d=this;b(a)};b.prototype.addTime=function(a){if(null!==this._animation){var b,d,f,g,e,h,p,k=this._animation._nodes;b=this._animation.duration;if(this._time!==b||this.looping){this._time+=a;if(this._time>b)for(this._time=this.looping?0:b,b=0;b<k.length;b++)d=k[b],f=d._name,this._currKeyIndices[f]=0;else if(0>this._time)for(this._time=this.looping?b:0,b=0;b<k.length;b++)d=
|
|
k[b],f=d._name,this._currKeyIndices[f]=d._keys.length-2;a=0<=a?1:-1;for(b=0;b<k.length;b++)if(d=k[b],f=d._name,d=d._keys,g=this._interpolatedKeyDict[f],void 0!==g){p=!1;if(1!==d.length)for(var n=this._currKeyIndices[f];n<d.length-1&&0<=n;n+=a)if(e=d[n],h=d[n+1],e.time<=this._time&&h.time>=this._time){p=(this._time-e.time)/(h.time-e.time);g._pos.lerp(e.position,h.position,p);g._quat.slerp(e.rotation,h.rotation,p);g._scale.lerp(e.scale,h.scale,p);g._written=!0;this._currKeyIndices[f]=n;p=!0;break}if(1===
|
|
d.length||!p&&0===this._time&&this.looping)g._pos.copy(d[0].position),g._quat.copy(d[0].rotation),g._scale.copy(d[0].scale),g._written=!0}}}};b.prototype.blend=function(a,b,d){for(var c=this._interpolatedKeys.length,g=0;g<c;g++){var e=a._interpolatedKeys[g],h=b._interpolatedKeys[g],p=this._interpolatedKeys[g];e._written&&h._written?(p._quat.slerp(e._quat,b._interpolatedKeys[g]._quat,d),p._pos.lerp(e._pos,b._interpolatedKeys[g]._pos,d),p._scale.lerp(e._scale,h._scale,d),p._written=!0):e._written?(p._quat.copy(e._quat),
|
|
p._pos.copy(e._pos),p._scale.copy(e._scale),p._written=!0):h._written&&(p._quat.copy(h._quat),p._pos.copy(h._pos),p._scale.copy(h._scale),p._written=!0)}};Object.defineProperty(b.prototype,"animation",{get:function(){return this._animation},set:function(a){this._animation=a;this.currentTime=0}});b.prototype.getAnimation=function(){return this._animation};Object.defineProperty(b.prototype,"currentTime",{get:function(){return this._time},set:function(a){this._time=a;a=this._interpolatedKeys.length;
|
|
for(var b=0;b<a;b++)this._currKeyIndices[this._interpolatedKeys[b]._name]=0;this.addTime(0);this.updateGraph()}});b.prototype.getCurrentTime=function(){return this._time};b.prototype.setCurrentTime=function(a){this.currentTime=a};Object.defineProperty(b.prototype,"numNodes",{get:function(){return this._interpolatedKeys.length}});b.prototype.getNumNodes=function(){return this._interpolatedKeys.length};b.prototype.setAnimation=function(a){this.animation=a};b.prototype.setGraph=function(a){var b;if(this.graph=
|
|
a)for(b=0;b<this._interpolatedKeys.length;b++){var d=a.findByName(this._interpolatedKeys[b]._name);this._interpolatedKeys[b].setTarget(d)}else for(b=0;b<this._interpolatedKeys.length;b++)this._interpolatedKeys[b].setTarget(null)};b.prototype.updateGraph=function(){if(this.graph)for(var a=0;a<this._interpolatedKeys.length;a++){var b=this._interpolatedKeys[a];if(b._written){var d=b.getTarget();d.localPosition.copy(b._pos);d.localRotation.copy(b._quat);d.localScale.copy(b._scale);d._dirtyLocal||d._dirtifyLocal();
|
|
b._written=!1}}};b.prototype.setLooping=function(a){this.looping=a};b.prototype.getLooping=function(){return this.looping};return{Skeleton:b}}());Object.assign(pc,function(){function e(){return"undefined"!==typeof Audio}function b(){return!("undefined"===typeof AudioContext&&"undefined"===typeof webkitAudioContext)}var a=function(a){if(b()||a.forceWebAudioApi){if("undefined"!==typeof AudioContext?this.context=new AudioContext:"undefined"!==typeof webkitAudioContext&&(this.context=new webkitAudioContext),this.context){var c=this.context;this.resumeContext=function(){this.context.resume();window.removeEventListener("mousedown",this.resumeContext);
|
|
window.removeEventListener("touchend",this.resumeContext)}.bind(this);window.addEventListener("mousedown",this.resumeContext);window.addEventListener("touchend",this.resumeContext);if(pc.platform.ios){var f=function(){var a=c.createBuffer(1,1,44100),b=c.createBufferSource();b.buffer=a;b.connect(c.destination);b.start(0);b.disconnect();window.removeEventListener("touchend",f)};window.addEventListener("touchend",f)}}}else console.warn("No support for 3D audio found");e()||console.warn("No support for 2D audio found");
|
|
this.listener=new pc.Listener(this);this._volume=1;this.suspended=!1;pc.events.attach(this)};a.hasAudio=e;a.hasAudioContext=b;Object.assign(a.prototype,{suspend:function(){this.suspended=!0;this.fire("suspend")},resume:function(){this.suspended=!1;this.fire("resume")},destroy:function(){window.removeEventListener("mousedown",this.resumeContext);window.removeEventListener("touchend",this.resumeContext);this.fire("destroy");this.context&&this.context.close&&(this.context.close(),this.context=null)},
|
|
getListener:function(){console.warn('DEPRECATED: getListener is deprecated. Get the "listener" field instead.');return this.listener},getVolume:function(){console.warn('DEPRECATED: getVolume is deprecated. Get the "volume" property instead.');return this.volume},setVolume:function(a){console.warn('DEPRECATED: setVolume is deprecated. Set the "volume" property instead.');this.volume=a},playSound:function(a,b){b=b||{};var c=null;pc.Channel&&(c=new pc.Channel(this,a,b),c.play());return c},playSound3d:function(a,
|
|
b,f){f=f||{};var c=null;pc.Channel3d&&(c=new pc.Channel3d(this,a,f),c.setPosition(b),f.volume&&c.setVolume(f.volume),f.loop&&c.setLoop(f.loop),f.maxDistance&&c.setMaxDistance(f.maxDistance),f.minDistance&&c.setMinDistance(f.minDistance),f.rollOffFactor&&c.setRollOffFactor(f.rollOffFactor),f.distanceModel&&c.setDistanceModel(f.distanceModel),c.play());return c}});Object.defineProperty(a.prototype,"volume",{get:function(){return this._volume},set:function(a){this._volume=a=pc.math.clamp(a,0,1);this.fire("volumechange",
|
|
a)}});pc.AudioManager=a;return{SoundManager:a}}());Object.assign(pc,function(){var e=function(b){b instanceof Audio?this.audio=b:this.buffer=b};Object.defineProperty(e.prototype,"duration",{get:function(){var b=0;this.buffer?b=this.buffer.duration:this.audio&&(b=this.audio.duration);return b||0}});return{Sound:e}}());Object.assign(pc,function(){var e=function(b){this.position=new pc.Vec3;this.velocity=new pc.Vec3;this.orientation=new pc.Mat4;pc.AudioManager.hasAudioContext()&&(this.listener=b.context.listener)};Object.assign(e.prototype,{getPosition:function(){return this.position},setPosition:function(b){this.position.copy(b);this.listener&&this.listener.setPosition(b.x,b.y,b.z)},getVelocity:function(){return this.velocity},setVelocity:function(b){this.velocity.copy(b);this.listener&&this.listener.setPosition(b.x,
|
|
b.y,b.z)},setOrientation:function(b){this.orientation.copy(b);this.listener&&this.listener.setOrientation(-b.data[8],-b.data[9],-b.data[10],b.data[4],b.data[5],b.data[6])},getOrientation:function(){return this.orientation}});return{Listener:e}}());Object.assign(pc,function(){var e;pc.SoundManager.hasAudioContext()?(e=function(b,a,c){pc.events.attach(this);c=c||{};this._volume=void 0!==c.volume?pc.math.clamp(Number(c.volume)||0,0,1):1;this._pitch=void 0!==c.pitch?Math.max(.01,Number(c.pitch)||0):1;this._loop=!(void 0===c.loop||!c.loop);this._sound=a;this._state=2;this._suspendInstanceEvents=this._suspendEndEvent=this._suspended=!1;this._startTime=Math.max(0,Number(c.startTime)||0);this._duration=Math.max(0,Number(c.duration)||0);this._startedAt=
|
|
0;this._startOffset=null;this._currentOffset=this._currentTime=0;this._playWhenLoaded=!0;this._manager=b;this._lastNode=this._firstNode=this._connectorNode=this._inputNode=null;this._initializeNodes();this._onPlayCallback=c.onPlay;this._onPauseCallback=c.onPause;this._onResumeCallback=c.onResume;this._onStopCallback=c.onStop;this._onEndCallback=c.onEnd;this._endedHandler=this._onEnded.bind(this);this.source=null},Object.assign(e.prototype,{_initializeNodes:function(){this._connectorNode=this._inputNode=
|
|
this.gain=this._manager.context.createGain();this._connectorNode.connect(this._manager.context.destination)},play:function(){2!==this._state&&this.stop();this.source||this._createSource();var b=this._startOffset%this.duration||0,b=(this._startTime+b)%this._sound.duration||0;this._startOffset=null;this._duration?this.source.start(0,b,this._duration):this.source.start(0,b);this._startedAt=this._manager.context.currentTime;this._currentTime=0;this._currentOffset=b;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();return!0},pause:function(){if(0!==this._state||!this.source)return!1;this._updateCurrentTime();this._state=
|
|
1;this._suspendEndEvent=!0;this.source.stop(0);this.source=null;this._playWhenLoaded=!1;this._startOffset=null;this._suspendInstanceEvents||this._onPause();return!0},resume:function(){if(1!==this._state)return!1;this.source||this._createSource();var b=this.currentTime;null!==this._startOffset&&(b=this._startOffset%this.duration||0,b=(this._startTime+b)%this._sound.duration||0,this._startOffset=null);this._duration?this.source.start(0,b,this._duration):this.source.start(0,b);this._state=0;this._startedAt=
|
|
this._manager.context.currentTime;this._currentOffset=b;this.volume=this._volume;this.loop=this._loop;this.pitch=this._pitch;this._playWhenLoaded=!1;this._suspendInstanceEvents||this._onResume();return!0},stop:function(){if(2===this._state||!this.source)return!1;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._currentOffset=
|
|
this._currentTime=this._startedAt=0;this._startOffset=null;this._playWhenLoaded=!1;this._suspendEndEvent=!0;0===this._state&&this.source.stop(0);this.source=null;this._state=2;this._suspendInstanceEvents||this._onStop();return!0},setExternalNodes:function(b,a){if(b){a||(a=b);var c=this._manager.context.destination;this._firstNode!==b&&(this._firstNode?this._connectorNode.disconnect(this._firstNode):this._connectorNode.disconnect(c),this._firstNode=b,this._connectorNode.connect(b));this._lastNode!==
|
|
a&&(this._lastNode&&this._lastNode.disconnect(c),this._lastNode=a,this._lastNode.connect(c))}else console.error("The firstNode must be a valid Audio Node")},clearExternalNodes:function(){var b=this._manager.context.destination;this._firstNode&&(this._connectorNode.disconnect(this._firstNode),this._firstNode=null);this._lastNode&&(this._lastNode.disconnect(b),this._lastNode=null);this._connectorNode.connect(b)},getExternalNodes:function(){return[this._firstNode,this._lastNode]},_createSource:function(){if(!this._sound)return null;
|
|
var b=this._manager.context;this._sound.buffer&&(this.source=b.createBufferSource(),this.source.buffer=this._sound.buffer,this.source.connect(this._inputNode),this.source.onended=this._endedHandler,this.source.loopStart=this._startTime%this.source.buffer.duration||0,this._duration&&(this.source.loopEnd=Math.max(this.source.loopStart,(this._startTime+this._duration)%this.source.buffer.duration||0)));return this.source},_updateCurrentTime:function(){this._currentTime=((this._manager.context.currentTime-
|
|
this._startedAt)*this._pitch+this._currentOffset)%this.duration||0},_onManagerDestroy:function(){this.source&&0===this._state&&(this.source.stop(0),this.source=null)}}),Object.defineProperty(e.prototype,"volume",{get:function(){return this._volume},set:function(b){this._volume=b=pc.math.clamp(b,0,1);this.gain&&(this.gain.gain.value=b*this._manager.volume)}}),Object.defineProperty(e.prototype,"pitch",{get:function(){return this._pitch},set:function(b){this._currentOffset=this.currentTime;this._startedAt=
|
|
this._manager.context.currentTime;this._pitch=Math.max(Number(b)||0,.01);this.source&&(this.source.playbackRate.value=this._pitch)}}),Object.defineProperty(e.prototype,"loop",{get:function(){return this._loop},set:function(b){this._loop=!!b;this.source&&(this.source.loop=this._loop)}}),Object.defineProperty(e.prototype,"sound",{get:function(){return this._sound},set:function(b){this._sound=b;2!==this._state?this.stop():this._createSource()}}),Object.defineProperty(e.prototype,"currentTime",{get:function(){if(null!==
|
|
this._startOffset)return this._startOffset;if(1===this._state)return this._currentTime;if(2===this._state||!this.source)return 0;this._updateCurrentTime();return this._currentTime},set:function(b){if(!(0>b))if(0===this._state){this.stop();var a=this._suspendInstanceEvents;this._suspendInstanceEvents=!0;this._startOffset=b;this.play();this._suspendInstanceEvents=a}else this._currentTime=this._startOffset=b}})):pc.SoundManager.hasAudio()?(e=function(b,a,c){pc.events.attach(this);c=c||{};this._volume=
|
|
void 0!==c.volume?pc.math.clamp(Number(c.volume)||0,0,1):1;this._pitch=void 0!==c.pitch?Math.max(.01,Number(c.pitch)||0):1;this._loop=!(void 0===c.loop||!c.loop);this._sound=a;this._state=2;this._suspendInstanceEvents=this._suspendEndEvent=this._suspended=!1;this._playWhenLoaded=!0;this._startTime=Math.max(0,Number(c.startTime)||0);this._duration=Math.max(0,Number(c.duration)||0);this._startOffset=null;this._isReady=!1;this._manager=b;this._loadedMetadataHandler=this._onLoadedMetadata.bind(this);
|
|
this._timeUpdateHandler=this._onTimeUpdate.bind(this);this._endedHandler=this._onEnded.bind(this);this._onPlayCallback=c.onPlay;this._onPauseCallback=c.onPause;this._onResumeCallback=c.onResume;this._onStopCallback=c.onStop;this._onEndCallback=c.onEnd;this.source=null;this._createSource()},Object.assign(e.prototype,{play:function(){2!==this._state&&this.stop();if(!this.source&&!this._createSource())return!1;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();return!0},pause:function(){if(!this.source||0!==this._state)return!1;this._suspendEndEvent=!0;this.source.pause();this._playWhenLoaded=!1;this._state=
|
|
1;this._startOffset=null;this._suspendInstanceEvents||this._onPause();return!0},resume:function(){if(!this.source||1!==this._state)return!1;this._state=0;this._playWhenLoaded=!1;this.source.paused&&(this.source.play(),this._suspendInstanceEvents||this._onResume());return!0},stop:function(){if(!this.source||2===this._state)return!1;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();return!0},setExternalNodes:function(){},clearExternalNodes:function(){},getExternalNodes:function(){return[null,null]},_onLoadedMetadata:function(){this.source.removeEventListener("loadedmetadata",this._loadedMetadataHandler);this._isReady=!0;var b=this._startOffset%this.duration||0,b=(this._startTime+
|
|
b)%this._sound.duration||0;this._startOffset=null;this.source.currentTime=b},_createSource:function(){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);return this.source},_onTimeUpdate:function(){this._duration&&this.source.currentTime>((this._startTime+this._duration)%this.source.duration||
|
|
0)&&(this.loop?this.source.currentTime=this._startTime%this.source.duration||0:(this.source.removeEventListener("timeupdate",this._timeUpdateHandler),this.source.pause(),this._onEnded()))},_onManagerDestroy:function(){this.source&&this.source.pause()}}),Object.defineProperty(e.prototype,"volume",{get:function(){return this._volume},set:function(b){this._volume=b=pc.math.clamp(b,0,1);this.source&&(this.source.volume=b*this._manager.volume)}}),Object.defineProperty(e.prototype,"pitch",{get:function(){return this._pitch},
|
|
set:function(b){this._pitch=Math.max(Number(b)||0,.01);this.source&&(this.source.playbackRate=this._pitch)}}),Object.defineProperty(e.prototype,"loop",{get:function(){return this._loop},set:function(b){this._loop=!!b;this.source&&(this.source.loop=this._loop)}}),Object.defineProperty(e.prototype,"sound",{get:function(){return this._sound},set:function(b){this.stop();this._sound=b}}),Object.defineProperty(e.prototype,"currentTime",{get:function(){return null!==this._startOffset?this._startOffset:2!==
|
|
this._state&&this.source?this.source.currentTime-this._startTime:0},set:function(b){0>b||(this._startOffset=b,this.source&&this._isReady&&(this.source.currentTime=(this._startTime+(b%this.duration||0))%this._sound.duration||0,this._startOffset=null))}})):e=function(){};Object.assign(e.prototype,{_onPlay:function(){this.fire("play");this._onPlayCallback&&this._onPlayCallback(this)},_onPause:function(){this.fire("pause");this._onPauseCallback&&this._onPauseCallback(this)},_onResume:function(){this.fire("resume");
|
|
this._onResumeCallback&&this._onResumeCallback(this)},_onStop:function(){this.fire("stop");this._onStopCallback&&this._onStopCallback(this)},_onEnded:function(){this._suspendEndEvent?this._suspendEndEvent=!1:(this.fire("end"),this._onEndCallback&&this._onEndCallback(this),this.stop())},_onManagerVolumeChange:function(){this.volume=this._volume},_onManagerSuspend:function(){0!==this._state||this._suspended||(this._suspended=!0,this.pause())},_onManagerResume:function(){this._suspended&&(this._suspended=
|
|
!1,this.resume())}});Object.defineProperty(e.prototype,"startTime",{get:function(){return this._startTime},set:function(b){this._startTime=Math.max(0,Number(b)||0);b=0===this._state;this.stop();b&&this.play()}});Object.defineProperty(e.prototype,"duration",{get:function(){return this._sound?this._duration?this._duration%this._sound.duration||0:this._sound.duration:0},set:function(b){this._duration=Math.max(0,Number(b)||0);b=0===this._state;this.stop();b&&this.play()}});Object.defineProperty(e.prototype,
|
|
"isPlaying",{get:function(){return 0===this._state}});Object.defineProperty(e.prototype,"isPaused",{get:function(){return 1===this._state}});Object.defineProperty(e.prototype,"isStopped",{get:function(){return 2===this._state}});Object.defineProperty(e.prototype,"isSuspended",{get:function(){return this._suspended}});return{SoundInstance:e}}());Object.assign(pc,function(){var e;if(pc.SoundManager.hasAudioContext())e=function(a,b,d){pc.SoundInstance.call(this,a,b,d);d=d||{};this._position=new pc.Vec3;d.position&&(this.position=d.position);this._velocity=new pc.Vec3;d.velocity&&(this.velocity=d.velocity);this.maxDistance=void 0!==d.maxDistance?Number(d.maxDistance):1E4;this.refDistance=void 0!==d.refDistance?Number(d.refDistance):1;this.rollOffFactor=void 0!==d.rollOffFactor?Number(d.rollOffFactor):1;this.distanceModel=void 0!==d.distanceModel?
|
|
d.distanceModel:pc.DISTANCE_LINEAR},e.prototype=Object.create(pc.SoundInstance.prototype),e.prototype.constructor=e,Object.assign(e.prototype,{_initializeNodes:function(){this.gain=this._manager.context.createGain();this.panner=this._manager.context.createPanner();this.panner.connect(this.gain);this._inputNode=this.panner;this._connectorNode=this.gain;this._connectorNode.connect(this._manager.context.destination)}}),Object.defineProperty(e.prototype,"position",{get:function(){return this._position},
|
|
set:function(a){this._position.copy(a);this.panner.setPosition(a.x,a.y,a.z)}}),Object.defineProperty(e.prototype,"velocity",{get:function(){return this._velocity},set:function(a){this._velocity.copy(a);this.panner.setVelocity(a.x,a.y,a.z)}}),Object.defineProperty(e.prototype,"maxDistance",{get:function(){return this.panner.maxDistance},set:function(a){this.panner.maxDistance=a}}),Object.defineProperty(e.prototype,"refDistance",{get:function(){return this.panner.refDistance},set:function(a){this.panner.refDistance=
|
|
a}}),Object.defineProperty(e.prototype,"rollOffFactor",{get:function(){return this.panner.rolloffFactor},set:function(a){this.panner.rolloffFactor=a}}),Object.defineProperty(e.prototype,"distanceModel",{get:function(){return this.panner.distanceModel},set:function(a){this.panner.distanceModel=a}});else if(pc.SoundManager.hasAudio()){var b=new pc.Vec3;e=function(a,b,d){pc.SoundInstance.call(this,a,b,d);d=d||{};this._position=new pc.Vec3;d.position&&(this.position=d.position);this._velocity=new pc.Vec3;
|
|
d.velocity&&(this.velocity=d.velocity);this._maxDistance=void 0!==d.maxDistance?Number(d.maxDistance):1E4;this._refDistance=void 0!==d.refDistance?Number(d.refDistance):1;this._rollOffFactor=void 0!==d.rollOffFactor?Number(d.rollOffFactor):1;this._distanceModel=void 0!==d.distanceModel?d.distanceModel:pc.DISTANCE_LINEAR};e.prototype=Object.create(pc.SoundInstance.prototype);e.prototype.constructor=e;Object.defineProperty(e.prototype,"position",{get:function(){return this._position},set:function(a){this._position.copy(a);
|
|
if(this.source){var c=this._manager.listener.getPosition();a=this.refDistance;var d=this.maxDistance,f=this.rollOffFactor,g=this.distanceModel;b=b.sub2(c,this._position);c=b.length();if(c<a)a=1;else if(c>d)a=0;else{var e=0;g===pc.DISTANCE_LINEAR?e=1-f*(c-a)/(d-a):g===pc.DISTANCE_INVERSE?e=a/(a+f*(c-a)):g===pc.DISTANCE_EXPONENTIAL&&(e=Math.pow(c/a,-f));a=pc.math.clamp(e,0,1)}this.source.volume=this.volume*a*this._manager.volume}}});Object.defineProperty(e.prototype,"velocity",{get:function(){return this._velocity},
|
|
set:function(a){this._velocity.copy(a)}});Object.defineProperty(e.prototype,"maxDistance",{get:function(){return this._maxDistance},set:function(a){this._maxDistance=a}});Object.defineProperty(e.prototype,"refDistance",{get:function(){return this._refDistance},set:function(a){this._refDistance=a}});Object.defineProperty(e.prototype,"rollOffFactor",{get:function(){return this._rollOffFactor},set:function(a){this._rollOffFactor=a}});Object.defineProperty(e.prototype,"distanceModel",{get:function(){return this._distanceModel},
|
|
set:function(a){this._distanceModel=a}})}else e=function(){};return{SoundInstance3d:e}}());Object.assign(pc,function(){var e;pc.AudioManager.hasAudioContext()?(e=function(b,a,c){c=c||{};this.volume=void 0===c.volume?1:c.volume;this.loop=void 0===c.loop?!1:c.loop;this.pitch=void 0===c.pitch?1:c.pitch;this.sound=a;this.suspended=this.paused=!1;this.startOffset=this.startTime=0;this.manager=b;this.source=null;this.gain=b.context.createGain()},Object.assign(e.prototype,{play:function(){if(this.source)throw Error("Call stop() before calling play()");this._createSource();if(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?console.warn("Call pause() before unpausing."):(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))},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)},setLoop:function(b){this.loop=b;this.source&&(this.source.loop=b)},setVolume:function(b){this.volume=b=pc.math.clamp(b,0,1);this.gain&&(this.gain.gain.value=b*this.manager.volume)},setPitch:function(b){this.pitch=b;this.source&&(this.source.playbackRate.value=b)},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 b=this.manager.context;this.sound.buffer&&(this.source=b.createBufferSource(),this.source.buffer=this.sound.buffer,this.source.connect(this.gain),this.gain.connect(b.destination),this.loop||(this.source.onended=this.pause.bind(this)))}})):pc.AudioManager.hasAudio()?(e=function(b,a,c){this.volume=c.volume||1;this.loop=c.loop||!1;this.sound=a;this.pitch=void 0!==c.pitch?c.pitch:1;this.suspended=this.paused=!1;this.manager=b;a.audio&&(this.source=
|
|
a.audio.cloneNode(!1),this.source.pause())},Object.assign(e.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);if(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(b){this.volume=b=pc.math.clamp(b,0,1);this.source&&(this.source.volume=b*this.manager.volume)},setLoop:function(b){this.loop=b;this.source&&(this.source.loop=b)},setPitch:function(b){this.pitch=
|
|
b;this.source&&(this.source.playbackRate=b)},getDuration:function(){return this.source&&!isNaN(this.source.duration)?this.source.duration:0},isPlaying:function(){return!this.source.paused}})):e=function(){};Object.assign(e.prototype,{getVolume:function(){return this.volume},getLoop:function(){return this.loop},getPitch:function(){return this.pitch},onManagerVolumeChange:function(){this.setVolume(this.getVolume())},onManagerSuspend:function(){this.isPlaying()&&!this.suspended&&(this.suspended=!0,this.pause())},
|
|
onManagerResume:function(){this.suspended&&(this.suspended=!1,this.unpause())}});return{Channel:e}}());Object.assign(pc,function(){var e;if(pc.AudioManager.hasAudioContext())e=function(a,b,d){pc.Channel.call(this,a,b,d);this.position=new pc.Vec3;this.velocity=new pc.Vec3;this.panner=a.context.createPanner()},e.prototype=Object.create(pc.Channel.prototype),e.prototype.constructor=e,Object.assign(e.prototype,{getPosition:function(){return this.position},setPosition:function(a){this.position.copy(a);this.panner.setPosition(a.x,a.y,a.z)},getVelocity:function(){return this.velocity},setVelocity:function(a){this.velocity.copy(a);
|
|
this.panner.setVelocity(a.x,a.y,a.z)},getMaxDistance:function(){return this.panner.maxDistance},setMaxDistance:function(a){this.panner.maxDistance=a},getMinDistance:function(){return this.panner.refDistance},setMinDistance:function(a){this.panner.refDistance=a},getRollOffFactor:function(){return this.panner.rolloffFactor},setRollOffFactor:function(a){this.panner.rolloffFactor=a},getDistanceModel:function(){return this.pannel.distanceModel},setDistanceModel:function(a){this.panner.distanceModel=a},
|
|
_createSource:function(){var a=this.manager.context;this.source=a.createBufferSource();this.source.buffer=this.sound.buffer;this.source.connect(this.panner);this.panner.connect(this.gain);this.gain.connect(a.destination);this.loop||(this.source.onended=this.pause.bind(this))}});else if(pc.AudioManager.hasAudio()){var b=new pc.Vec3;e=function(a,b){pc.Channel.call(this,a,b);this.position=new pc.Vec3;this.velocity=new pc.Vec3;this.maxDistance=1E4;this.rollOffFactor=this.minDistance=1;this.distanceModel=
|
|
pc.DISTANCE_INVERSE};e.prototype=Object.create(pc.Channel.prototype);e.prototype.constructor=e;Object.assign(e.prototype,{getPosition:function(){return this.position},setPosition:function(a){this.position.copy(a);if(this.source){var c=this.manager.listener.getPosition();a=this.minDistance;var d=this.maxDistance,f=this.rollOffFactor,g=this.distanceModel;b=b.sub2(c,this.position);c=b.length();if(c<a)a=1;else if(c>d)a=0;else{var e=0;g===pc.DISTANCE_LINEAR?e=1-f*(c-a)/(d-a):g===pc.DISTANCE_INVERSE?e=
|
|
a/(a+f*(c-a)):g===pc.DISTANCE_EXPONENTIAL&&(e=Math.pow(c/a,-f));a=pc.math.clamp(e,0,1)}d=this.getVolume();this.source.volume=d*a}},getVelocity:function(){return this.velocity},setVelocity:function(a){this.velocity.copy(a)},getMaxDistance:function(){return this.maxDistance},setMaxDistance:function(a){this.maxDistance=a},getMinDistance:function(){return this.minDistance},setMinDistance:function(a){this.minDistance=a},getRollOffFactor:function(){return this.rollOffFactor},setRollOffFactor:function(a){this.rollOffFactor=
|
|
a},getDistanceModel:function(){return this.distanceModel},setDistanceModel:function(a){this.distanceModel=a}})}else e=function(){};return{Channel3d:e}}());(function(){var e={ACTION_MOUSE:"mouse",ACTION_KEYBOARD:"keyboard",ACTION_GAMEPAD:"gamepad",AXIS_MOUSE_X:"mousex",AXIS_MOUSE_Y:"mousey",AXIS_PAD_L_X:"padlx",AXIS_PAD_L_Y:"padly",AXIS_PAD_R_X:"padrx",AXIS_PAD_R_Y:"padry",AXIS_KEY:"key",EVENT_KEYDOWN:"keydown",EVENT_KEYUP:"keyup",EVENT_MOUSEDOWN:"mousedown",EVENT_MOUSEMOVE:"mousemove",EVENT_MOUSEUP:"mouseup",EVENT_MOUSEWHEEL:"mousewheel",EVENT_TOUCHSTART:"touchstart",EVENT_TOUCHEND:"touchend",EVENT_TOUCHMOVE:"touchmove",EVENT_TOUCHCANCEL:"touchcancel",
|
|
KEY_BACKSPACE:8,KEY_TAB:9,KEY_RETURN:13,KEY_ENTER:13,KEY_SHIFT:16,KEY_CONTROL:17,KEY_ALT:18,KEY_PAUSE:19,KEY_CAPS_LOCK:20,KEY_ESCAPE:27,KEY_SPACE:32,KEY_PAGE_UP:33,KEY_PAGE_DOWN:34,KEY_END:35,KEY_HOME:36,KEY_LEFT:37,KEY_UP:38,KEY_RIGHT:39,KEY_DOWN:40,KEY_PRINT_SCREEN:44,KEY_INSERT:45,KEY_DELETE:46,KEY_0:48,KEY_1:49,KEY_2:50,KEY_3:51,KEY_4:52,KEY_5:53,KEY_6:54,KEY_7:55,KEY_8:56,KEY_9:57,KEY_SEMICOLON:59,KEY_EQUAL:61,KEY_A:65,KEY_B:66,KEY_C:67,KEY_D:68,KEY_E:69,KEY_F:70,KEY_G:71,KEY_H:72,KEY_I:73,KEY_J:74,
|
|
KEY_K:75,KEY_L:76,KEY_M:77,KEY_N:78,KEY_O:79,KEY_P:80,KEY_Q:81,KEY_R:82,KEY_S:83,KEY_T:84,KEY_U:85,KEY_V:86,KEY_W:87,KEY_X:88,KEY_Y:89,KEY_Z:90,KEY_WINDOWS:91,KEY_CONTEXT_MENU:93,KEY_NUMPAD_0:96,KEY_NUMPAD_1:97,KEY_NUMPAD_2:98,KEY_NUMPAD_3:99,KEY_NUMPAD_4:100,KEY_NUMPAD_5:101,KEY_NUMPAD_6:102,KEY_NUMPAD_7:103,KEY_NUMPAD_8:104,KEY_NUMPAD_9:105,KEY_MULTIPLY:106,KEY_ADD:107,KEY_SEPARATOR:108,KEY_SUBTRACT:109,KEY_DECIMAL:110,KEY_DIVIDE:111,KEY_F1:112,KEY_F2:113,KEY_F3:114,KEY_F4:115,KEY_F5:116,KEY_F6:117,
|
|
KEY_F7:118,KEY_F8:119,KEY_F9:120,KEY_F10:121,KEY_F11:122,KEY_F12:123,KEY_COMMA:188,KEY_PERIOD:190,KEY_SLASH:191,KEY_OPEN_BRACKET:219,KEY_BACK_SLASH:220,KEY_CLOSE_BRACKET:221,KEY_META:224,MOUSEBUTTON_NONE:-1,MOUSEBUTTON_LEFT:0,MOUSEBUTTON_MIDDLE:1,MOUSEBUTTON_RIGHT:2,PAD_1:0,PAD_2:1,PAD_3:2,PAD_4:3,PAD_FACE_1:0,PAD_FACE_2:1,PAD_FACE_3:2,PAD_FACE_4:3,PAD_L_SHOULDER_1:4,PAD_R_SHOULDER_1:5,PAD_L_SHOULDER_2:6,PAD_R_SHOULDER_2:7,PAD_SELECT:8,PAD_START:9,PAD_L_STICK_BUTTON:10,PAD_R_STICK_BUTTON:11,PAD_UP:12,
|
|
PAD_DOWN:13,PAD_LEFT:14,PAD_RIGHT:15,PAD_VENDOR:16,PAD_L_STICK_X:0,PAD_L_STICK_Y:1,PAD_R_STICK_X:2,PAD_R_STICK_Y:3};Object.assign(pc,e);pc.input={};Object.assign(pc.input,e)})();Object.assign(pc,function(){var e=function(a,b){var c={x:0,y:0};if(b){if(b instanceof e)throw Error("Expected MouseEvent");c=a._getTargetCoords(b)}else b={};if(c)this.x=c.x,this.y=c.y;else if(pc.Mouse.isPointerLocked())this.y=this.x=0;else return;this.wheel=b.detail?-1*b.detail:b.wheelDelta?b.wheelDelta/120:0;pc.Mouse.isPointerLocked()?(this.dx=b.movementX||b.webkitMovementX||b.mozMovementX||0,this.dy=b.movementY||b.webkitMovementY||b.mozMovementY||0):(this.dx=this.x-a._lastX,this.dy=this.y-a._lastY);
|
|
this.button="mousedown"===b.type||"mouseup"===b.type?b.button:pc.MOUSEBUTTON_NONE;this.buttons=a._buttons.slice(0);this.element=b.target;this.ctrlKey=b.ctrlKey||!1;this.altKey=b.altKey||!1;this.shiftKey=b.shiftKey||!1;this.metaKey=b.metaKey||!1;this.event=b},b=function(a){this._lastY=this._lastX=0;this._buttons=[!1,!1,!1];this._lastbuttons=[!1,!1,!1];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._contextMenuHandler=function(a){a.preventDefault()};this._target=null;this._attached=!1;this.attach(a);pc.events.attach(this)};b.isPointerLocked=function(){return!!(document.pointerLockElement||document.mozPointerLockElement||document.webkitPointerLockElement)};Object.assign(b.prototype,{attach:function(a){this._target=a;this._attached||(this._attached=!0,window.addEventListener("mouseup",this._upHandler,!1),window.addEventListener("mousedown",this._downHandler,!1),
|
|
window.addEventListener("mousemove",this._moveHandler,!1),window.addEventListener("mousewheel",this._wheelHandler,!1),window.addEventListener("DOMMouseScroll",this._wheelHandler,!1))},detach:function(){this._attached&&(this._attached=!1,this._target=null,window.removeEventListener("mouseup",this._upHandler),window.removeEventListener("mousedown",this._downHandler),window.removeEventListener("mousemove",this._moveHandler),window.removeEventListener("mousewheel",this._wheelHandler),window.removeEventListener("DOMMouseScroll",
|
|
this._wheelHandler))},disableContextMenu:function(){this._target&&this._target.addEventListener("contextmenu",this._contextMenuHandler)},enableContextMenu:function(){this._target&&this._target.removeEventListener("contextmenu",this._contextMenuHandler)},enablePointerLock:function(a,b){if(document.body.requestPointerLock){var c=function(){a();document.removeEventListener("pointerlockchange",c)},f=function(){b();document.removeEventListener("pointerlockerror",f)};a&&document.addEventListener("pointerlockchange",
|
|
c,!1);b&&document.addEventListener("pointerlockerror",f,!1);document.body.requestPointerLock()}else b&&b()},disablePointerLock:function(a){if(document.exitPointerLock){var b=function(){a();document.removeEventListener("pointerlockchange",b)};a&&document.addEventListener("pointerlockchange",b,!1);document.exitPointerLock()}},update:function(){this._lastbuttons[0]=this._buttons[0];this._lastbuttons[1]=this._buttons[1];this._lastbuttons[2]=this._buttons[2]},isPressed:function(a){return this._buttons[a]},
|
|
wasPressed:function(a){return this._buttons[a]&&!this._lastbuttons[a]},wasReleased:function(a){return!this._buttons[a]&&this._lastbuttons[a]},_handleUp:function(a){this._buttons[a.button]=!1;a=new e(this,a);a.event&&this.fire(pc.EVENT_MOUSEUP,a)},_handleDown:function(a){this._buttons[a.button]=!0;a=new e(this,a);a.event&&this.fire(pc.EVENT_MOUSEDOWN,a)},_handleMove:function(a){a=new e(this,a);a.event&&(this.fire(pc.EVENT_MOUSEMOVE,a),this._lastX=a.x,this._lastY=a.y)},_handleWheel:function(a){a=new e(this,
|
|
a);a.event&&this.fire(pc.EVENT_MOUSEWHEEL,a)},_getTargetCoords:function(a){var b=this._target.getBoundingClientRect(),d=Math.floor(b.left),b=Math.floor(b.top);return a.clientX<d||a.clientX>=d+this._target.clientWidth||a.clientY<b||a.clientY>=b+this._target.clientHeight?null:{x:a.clientX-d,y:a.clientY-b}}});return{Mouse:b,MouseEvent:e}}());Object.assign(pc,function(){function e(a){c.key=a.keyCode;c.element=a.target;c.event=a;return c}function b(a){return"string"===typeof a?a.toUpperCase().charCodeAt(0):a}var a=function(a,b){b?(this.key=b.keyCode,this.element=b.target,this.event=b):this.event=this.element=this.key=null},c=new a,d={9:"Tab",13:"Enter",16:"Shift",17:"Control",18:"Alt",27:"Escape",37:"Left",38:"Up",39:"Right",40:"Down",46:"Delete",91:"Win"},f=function(a,b){b=b||{};this._element=null;this._keyDownHandler=this._handleKeyDown.bind(this);
|
|
this._keyUpHandler=this._handleKeyUp.bind(this);this._keyPressHandler=this._handleKeyPress.bind(this);pc.events.attach(this);this._keymap={};this._lastmap={};a&&this.attach(a);this.preventDefault=b.preventDefault||!1;this.stopPropagation=b.stopPropagation||!1};f.prototype.attach=function(a){this._element&&this.detach();this._element=a;this._element.addEventListener("keydown",this._keyDownHandler,!1);this._element.addEventListener("keypress",this._keyPressHandler,!1);this._element.addEventListener("keyup",
|
|
this._keyUpHandler,!1)};f.prototype.detach=function(){this._element.removeEventListener("keydown",this._keyDownHandler);this._element.removeEventListener("keypress",this._keyPressHandler);this._element.removeEventListener("keyup",this._keyUpHandler);this._element=null};f.prototype.toKeyIdentifier=function(a){a=b(a);var c,f;if(c=d[a.toString()])return c;c=a.toString(16).toUpperCase();f=c.length;for(a=0;a<4-f;a++)c="0"+c;return"U+"+c};f.prototype._handleKeyDown=function(a){var b=a.keyCode||a.charCode;
|
|
void 0!==b&&(b=this.toKeyIdentifier(b),this._keymap[b]=!0,this.fire("keydown",e(a)),this.preventDefault&&a.preventDefault(),this.stopPropagation&&a.stopPropagation())};f.prototype._handleKeyUp=function(a){var b=a.keyCode||a.charCode;void 0!==b&&(b=this.toKeyIdentifier(b),delete this._keymap[b],this.fire("keyup",e(a)),this.preventDefault&&a.preventDefault(),this.stopPropagation&&a.stopPropagation())};f.prototype._handleKeyPress=function(a){this.fire("keypress",e(a));this.preventDefault&&a.preventDefault();
|
|
this.stopPropagation&&a.stopPropagation()};f.prototype.update=function(){for(var a in this._lastmap)delete this._lastmap[a];for(a in this._keymap)this._keymap.hasOwnProperty(a)&&(this._lastmap[a]=this._keymap[a])};f.prototype.isPressed=function(a){a=b(a);a=this.toKeyIdentifier(a);return!!this._keymap[a]};f.prototype.wasPressed=function(a){a=b(a);a=this.toKeyIdentifier(a);return!!this._keymap[a]&&!this._lastmap[a]};f.prototype.wasReleased=function(a){a=b(a);a=this.toKeyIdentifier(a);return!this._keymap[a]&&
|
|
!!this._lastmap[a]};return{Keyboard:f,KeyboardEvent:a}}());Object.assign(pc,function(){var e=function(){this.gamepadsSupported=!!navigator.getGamepads||!!navigator.webkitGetGamepads;this.current=[];this.previous=[];this.deadZone=.25},b={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".split(" "),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".split(" "),
|
|
axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"]}},a={"Product: 0268":"PS3"};Object.assign(e.prototype,{update:function(){var a,b,f,g,e;a=0;for(f=this.current.length;a<f;a++)for(g=this.current[a].pad.buttons,e=g.length,b=0;b<e;b++)void 0===this.previous[a]&&(this.previous[a]=[]),this.previous[a][b]=g[b].pressed;b=this.poll();a=0;for(f=b.length;a<f;a++)this.current[a]=b[a]},poll:function(){var a=[];if(this.gamepadsSupported){var b=navigator.getGamepads?navigator.getGamepads():
|
|
navigator.webkitGetGamepads(),f,g=b.length;for(f=0;f<g;f++)b[f]&&a.push({map:this.getMap(b[f]),pad:b[f]})}return a},getMap:function(c){for(var d in a)if(0<=c.id.indexOf(d))return b[a[d]];return b.DEFAULT},isPressed:function(a,b){return this.current[a]?this.current[a].pad.buttons[pc[this.current[a].map.buttons[b]]].pressed:!1},wasPressed:function(a,b){if(!this.current[a])return!1;var c=pc[this.current[a].map.buttons[b]];return this.current[a].pad.buttons[c].pressed&&!this.previous[a][c]},getAxis:function(a,
|
|
b){if(!this.current[a])return!1;var c=this.current[a].pad.axes[pc[this.current[a].map.axes[b]]];Math.abs(c)<this.deadZone&&(c=0);return c}});return{GamePads:e}}());Object.assign(pc,function(){var e=function(a){var b=pc.getTouchTargetCoords(a);this.id=a.identifier;this.x=b.x;this.y=b.y;this.target=a.target;this.touch=a},b=function(a,b){this.element=b.target;this.event=b;this.touches=[];this.changedTouches=[];if(b){var c,d=b.touches.length;for(c=0;c<d;c++)this.touches.push(new e(b.touches[c]));d=b.changedTouches.length;for(c=0;c<d;c++)this.changedTouches.push(new e(b.changedTouches[c]))}};Object.assign(b.prototype,{getTouchById:function(a,b){var c,d=b.length;
|
|
for(c=0;c<d;c++)if(b[c].id===a)return b[c];return null}});var a=function(a){this._element=null;this._startHandler=this._handleTouchStart.bind(this);this._endHandler=this._handleTouchEnd.bind(this);this._moveHandler=this._handleTouchMove.bind(this);this._cancelHandler=this._handleTouchCancel.bind(this);this.attach(a);pc.events.attach(this)};Object.assign(a.prototype,{attach:function(a){this._element&&this.detach();this._element=a;this._element.addEventListener("touchstart",this._startHandler,!1);this._element.addEventListener("touchend",
|
|
this._endHandler,!1);this._element.addEventListener("touchmove",this._moveHandler,!1);this._element.addEventListener("touchcancel",this._cancelHandler,!1)},detach:function(){this._element&&(this._element.removeEventListener("touchstart",this._startHandler,!1),this._element.removeEventListener("touchend",this._endHandler,!1),this._element.removeEventListener("touchmove",this._moveHandler,!1),this._element.removeEventListener("touchcancel",this._cancelHandler,!1));this._element=null},_handleTouchStart:function(a){this.fire("touchstart",
|
|
new b(this,a))},_handleTouchEnd:function(a){this.fire("touchend",new b(this,a))},_handleTouchMove:function(a){a.preventDefault();this.fire("touchmove",new b(this,a))},_handleTouchCancel:function(a){this.fire("touchcancel",new b(this,a))}});return{getTouchTargetCoords:function(a){for(var b=0,c=0,g=a.target;!(g instanceof HTMLElement);)g=g.parentNode;do b+=g.offsetLeft-g.scrollLeft,c+=g.offsetTop-g.scrollTop,g=g.offsetParent;while(g);return{x:a.pageX-b,y:a.pageY-c}},TouchDevice:a,TouchEvent:b}}());Object.assign(pc,function(){var e=function(b,a){a=a||{};this._keyboard=a.keyboard||null;this._mouse=a.mouse||null;this._gamepads=a.gamepads||null;this._element=null;this._actions={};this._axes={};this._axesValues={};b&&this.attach(b)};e.prototype.attach=function(b){this._element=b;this._keyboard&&this._keyboard.attach(b);this._mouse&&this._mouse.attach(b)};e.prototype.detach=function(){this._keyboard&&this._keyboard.detach();this._mouse&&this._mouse.detach();this._element=null};e.prototype.disableContextMenu=
|
|
function(){this._mouse||this._enableMouse();this._mouse.disableContextMenu()};e.prototype.enableContextMenu=function(){this._mouse||this._enableMouse();this._mouse.enableContextMenu()};e.prototype.update=function(b){this._keyboard&&this._keyboard.update(b);this._mouse&&this._mouse.update(b);this._gamepads&&this._gamepads.update(b);this._axesValues={};for(var a in this._axes)this._axesValues[a]=[]};e.prototype.registerKeys=function(b,a){this._keyboard||this._enableKeyboard();if(this._actions[b])throw Error(pc.string.format("Action: {0} already registered",
|
|
b));if(void 0===a)throw Error("Invalid button");a.length||(a=[a]);this._actions[b]?this._actions[b].push({type:pc.ACTION_KEYBOARD,keys:a}):this._actions[b]=[{type:pc.ACTION_KEYBOARD,keys:a}]};e.prototype.registerMouse=function(b,a){this._mouse||this._enableMouse();if(void 0===a)throw Error("Invalid button");this._actions[b]?this._actions[b].push({type:pc.ACTION_MOUSE,button:a}):this._actions[b]=[{type:pc.ACTION_MOUSE,button:-a}]};e.prototype.registerPadButton=function(b,a,c){if(void 0===c)throw Error("Invalid button");
|
|
this._actions[b]?this._actions[b].push({type:pc.ACTION_GAMEPAD,button:c,pad:a}):this._actions[b]=[{type:pc.ACTION_GAMEPAD,button:c,pad:a}]};e.prototype.registerAxis=function(b){var a=b.name;this._axes[a]||(this._axes[a]=[]);var c=this._axes[a].push(a);b=b||{};b.pad=b.pad||pc.PAD_1;var d=function(d,g,e,h){switch(g){case "mousex":d._mouse.on(pc.EVENT_MOUSEMOVE,function(b){d._axesValues[a][c]=b.dx/10});break;case "mousey":d._mouse.on(pc.EVENT_MOUSEMOVE,function(b){d._axesValues[a][c]=b.dy/10});break;
|
|
case "key":d._axes[a].push(function(){return d._keyboard.isPressed(h)?e:0});break;case "padrx":d._axes[a].push(function(){return d._gamepads.getAxis(b.pad,pc.PAD_R_STICK_X)});break;case "padry":d._axes[a].push(function(){return d._gamepads.getAxis(b.pad,pc.PAD_R_STICK_Y)});break;case "padlx":d._axes[a].push(function(){return d._gamepads.getAxis(b.pad,pc.PAD_L_STICK_X)});break;case "padly":d._axes[a].push(function(){return d._gamepads.getAxis(b.pad,pc.PAD_L_STICK_Y)});break;default:throw Error("Unknown axis");
|
|
}};d(this,b.positive,1,b.positiveKey);(b.negativeKey||b.negative!==b.positive)&&d(this,b.negative,-1,b.negativeKey)};e.prototype.isPressed=function(b){if(!this._actions[b])return!1;var a,c,d=this._actions[b].length;for(c=0;c<d;++c)switch(a=this._actions[b][c],a.type){case pc.ACTION_KEYBOARD:if(this._keyboard){var f,g=a.keys.length;for(f=0;f<g;f++)if(this._keyboard.isPressed(a.keys[f]))return!0}break;case pc.ACTION_MOUSE:if(this._mouse&&this._mouse.isPressed(a.button))return!0;break;case pc.ACTION_GAMEPAD:if(this._gamepads&&
|
|
this._gamepads.isPressed(a.pad,a.button))return!0}return!1};e.prototype.wasPressed=function(b){if(!this._actions[b])return!1;var a,c=this._actions[b].length;for(a=0;a<c;++a){var d=this._actions[b][a];switch(d.type){case pc.ACTION_KEYBOARD:if(this._keyboard){var f,g=d.keys.length;for(f=0;f<g;f++)if(this._keyboard.wasPressed(d.keys[f]))return!0}break;case pc.ACTION_MOUSE:if(this._mouse&&this._mouse.wasPressed(d.button))return!0;break;case pc.ACTION_GAMEPAD:if(this._gamepads&&this._gamepads.wasPressed(d.pad,
|
|
d.button))return!0}}return!1};e.prototype.getAxis=function(b){var a=0;if(this._axes[b]){var c,d=this._axes[b].length;for(c=0;c<d;c++)if("function"===pc.type(this._axes[b][c])){var f=this._axes[b][c]();Math.abs(f)>Math.abs(a)&&(a=f)}else this._axesValues[b]&&Math.abs(this._axesValues[b][c])>Math.abs(a)&&(a=this._axesValues[b][c])}return a};e.prototype._enableMouse=function(){this._mouse=new pc.Mouse;if(!this._element)throw Error("Controller must be attached to an Element");this._mouse.attach(this._element)};
|
|
e.prototype._enableKeyboard=function(){this._keyboard=new pc.Keyboard;if(!this._element)throw Error("Controller must be attached to an Element");this._keyboard.attach(this._element)};return{Controller:e}}());Object.assign(pc,function(){var e,b,a=new pc.Vec3,c=new pc.Vec3,d=new pc.Vec3,f=new pc.Vec3,g=new pc.Vec3,l=new pc.Vec3,h=new pc.Vec3,p=new pc.Vec3,k=new pc.Vec3,n=new pc.Vec2,q=new pc.Vec3,m=new pc.Vec3,r=new pc.Vec3,t=new pc.Vec3,u=new pc.Vec3,x=new pc.Vec3,v=new pc.Vec3,w=new pc.Vec3,y=new pc.Vec4,D=function(a,b,c){d.sub2(b,a);f.sub2(c[0],a);g.sub2(c[1],a);l.sub2(c[2],a);p.cross(l,d);if(0<=f.dot(p)){if(0>-g.dot(p)||0>k.cross(d,g).dot(f))return!1}else if(h.sub2(c[3],a),0>h.dot(p)||0>k.cross(d,f).dot(h))return!1;
|
|
return 1E-8>d.sub2(c[0],c[2]).lengthSq()||1E-8>d.sub2(c[1],c[3]).lengthSq()?!1:!0},B=function(a,b,c){this.event=a;this.element=b;this.camera=c;this._stopPropagation=!1};Object.assign(B.prototype,{stopPropagation:function(){this._stopPropagation=!0;this.event.stopImmediatePropagation();this.event.stopPropagation()}});var z=function(a,b,c,d,f,g,e){B.call(this,a,b,c);this.x=d;this.y=f;this.ctrlKey=a.ctrlKey||!1;this.altKey=a.altKey||!1;this.shiftKey=a.shiftKey||!1;this.metaKey=a.metaKey||!1;this.button=
|
|
a.button;pc.Mouse.isPointerLocked()?(this.dx=a.movementX||a.webkitMovementX||a.mozMovementX||0,this.dy=a.movementY||a.webkitMovementY||a.mozMovementY||0):(this.dx=d-g,this.dy=f-e);this.wheel=a.detail?-1*a.detail:a.wheelDelta?a.wheelDelta/120:0};z.prototype=Object.create(B.prototype);z.prototype.constructor=z;var A=function(a,b,c,d,f,g){B.call(this,a,b,c);this.touches=a.touches;this.changedTouches=a.changedTouches;this.x=d;this.y=f};A.prototype=Object.create(B.prototype);A.prototype.constructor=A;
|
|
var F=function(a,b){this._app=null;this._attached=!1;this._target=null;this._enabled=!0;this._lastY=this._lastX=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._touchcancelHandler=this._touchendHandler=this._handleTouchEnd.bind(this);this._touchmoveHandler=this._handleTouchMove.bind(this);this._sortHandler=
|
|
this._sortElements.bind(this);this._elements=[];this._pressedElement=this._hoveredElement=null;this._touchedElements={};this._touchesForWhichTouchLeaveHasFired={};this._useMouse=!b||!1!==b.useMouse;this._useTouch=!b||!1!==b.useTouch;pc.platform.touch&&(this._clickedEntities={});this.attach(a,b)};Object.assign(F.prototype,{attach:function(a){this._attached&&(this._attached=!1,this.detach());this._target=a;this._attached=!0;this._useMouse&&(window.addEventListener("mouseup",this._upHandler,{passive:!0}),
|
|
window.addEventListener("mousedown",this._downHandler,{passive:!0}),window.addEventListener("mousemove",this._moveHandler,{passive:!0}),window.addEventListener("mousewheel",this._wheelHandler,{passive:!0}),window.addEventListener("DOMMouseScroll",this._wheelHandler,{passive:!0}));this._useTouch&&pc.platform.touch&&(this._target.addEventListener("touchstart",this._touchstartHandler,{passive:!0}),this._target.addEventListener("touchend",this._touchendHandler,!1),this._target.addEventListener("touchmove",
|
|
this._touchmoveHandler,!1),this._target.addEventListener("touchcancel",this._touchcancelHandler,!1))},detach:function(){this._attached&&(this._attached=!1,this._useMouse&&(window.removeEventListener("mouseup",this._upHandler,!1),window.removeEventListener("mousedown",this._downHandler,!1),window.removeEventListener("mousemove",this._moveHandler,!1),window.removeEventListener("mousewheel",this._wheelHandler,!1),window.removeEventListener("DOMMouseScroll",this._wheelHandler,!1)),this._useTouch&&(this._target.removeEventListener("touchstart",
|
|
this._touchstartHandler,!1),this._target.removeEventListener("touchend",this._touchendHandler,!1),this._target.removeEventListener("touchmove",this._touchmoveHandler,!1),this._target.removeEventListener("touchcancel",this._touchcancelHandler,!1)),this._target=null)},addElement:function(a){-1===this._elements.indexOf(a)&&this._elements.push(a)},removeElement:function(a){a=this._elements.indexOf(a);-1!==a&&this._elements.splice(a,1)},_handleUp:function(a){this._enabled&&!pc.Mouse.isPointerLocked()&&
|
|
(this._calcMouseCoords(a),null!==e&&this._onElementMouseEvent(a))},_handleDown:function(a){this._enabled&&!pc.Mouse.isPointerLocked()&&(this._calcMouseCoords(a),null!==e&&this._onElementMouseEvent(a))},_handleMove:function(a){this._enabled&&(this._calcMouseCoords(a),null!==e&&(this._onElementMouseEvent(a),this._lastX=e,this._lastY=b))},_handleWheel:function(a){this._enabled&&(this._calcMouseCoords(a),null!==e&&this._onElementMouseEvent(a))},_determineTouchedElements:function(a){var b={},c=this.app.systems.camera.cameras,
|
|
d,f,g;for(d=c.length-1;0<=d;d--){var e=c[d],h=0;f=0;for(g=a.changedTouches.length;f<g;f++)if(b[a.changedTouches[f].identifier])h++;else{var l=this._calcTouchCoords(a.changedTouches[f]),k=this._getTargetElement(e,l.x,l.y);k&&(h++,b[a.changedTouches[f].identifier]={element:k,camera:e,x:l.x,y:l.y})}if(h===g)break}return b},_handleTouchStart:function(a){if(this._enabled){for(var b=this._determineTouchedElements(a),c=0,d=a.changedTouches.length;c<d;c++){var f=a.changedTouches[c],g=b[f.identifier],e=this._touchedElements[f.identifier];
|
|
!g||e&&g.element===e.element||(this._fireEvent(a.type,new A(a,g.element,g.camera,g.x,g.y,this)),this._touchesForWhichTouchLeaveHasFired[f.identifier]=!1)}for(var h in b)this._touchedElements[h]=b[h]}},_handleTouchEnd:function(a){if(this._enabled){var b=this.app.systems.camera.cameras,c;for(c in this._clickedEntities)delete this._clickedEntities[c];c=0;for(var d=a.changedTouches.length;c<d;c++){var f=a.changedTouches[c],g=this._touchedElements[f.identifier];if(g){var e=g.element,h=g.camera,l=g.x,g=
|
|
g.y;delete this._touchedElements[f.identifier];delete this._touchesForWhichTouchLeaveHasFired[f.identifier];this._fireEvent(a.type,new A(a,e,h,l,g,this));if(0===a.touches.length)for(var f=this._calcTouchCoords(f),k=b.length-1;0<=k;k--)this._getTargetElement(b[k],f.x,f.y)!==e||this._clickedEntities[e.entity.getGuid()]||(this._fireEvent("click",new A(a,e,h,l,g,this)),this._clickedEntities[e.entity.getGuid()]=!0)}}}},_handleTouchMove:function(a){a.preventDefault();if(this._enabled)for(var b=this._determineTouchedElements(a),
|
|
c=0,d=a.changedTouches.length;c<d;c++){var f=a.changedTouches[c],g=b[f.identifier],e=this._touchedElements[f.identifier];if(e){var h=this._calcTouchCoords(f);g&&g.element===e.element||this._touchesForWhichTouchLeaveHasFired[f.identifier]||(this._fireEvent("touchleave",new A(a,e.element,e.camera,h.x,h.y,this)),this._touchesForWhichTouchLeaveHasFired[f.identifier]=!0);this._fireEvent("touchmove",new A(a,e.element,e.camera,h.x,h.y,this))}}},_onElementMouseEvent:function(a){var c,d=this._hoveredElement;
|
|
this._hoveredElement=null;for(var f=this.app.systems.camera.cameras,g,h=f.length-1;0<=h&&!(g=f[h],c=this._getTargetElement(g,e,b));h--);c&&(this._fireEvent(a.type,new z(a,c,g,e,b,this._lastX,this._lastY)),this._hoveredElement=c,a.type===pc.EVENT_MOUSEDOWN&&(this._pressedElement=c));d!==this._hoveredElement&&(d&&this._fireEvent("mouseleave",new z(a,d,g,e,b,this._lastX,this._lastY)),this._hoveredElement&&this._fireEvent("mouseenter",new z(a,this._hoveredElement,g,e,b,this._lastX,this._lastY)));a.type===
|
|
pc.EVENT_MOUSEUP&&this._pressedElement&&(this._pressedElement===this._hoveredElement?(this._pressedElement=null,this._clickedEntities&&this._clickedEntities[this._hoveredElement.entity.getGuid()]||this._fireEvent("click",new z(a,this._hoveredElement,g,e,b,this._lastX,this._lastY))):this._pressedElement=null)},_fireEvent:function(a,b){for(var c=b.element;;){c.fire(a,b);if(b._stopPropagation)break;if(!c.entity.parent)break;c=c.entity.parent.element;if(!c)break}},_calcMouseCoords:function(a){var c=this._target.getBoundingClientRect(),
|
|
d=Math.floor(c.left),c=Math.floor(c.top);a.clientX<d||a.clientX>=d+this._target.clientWidth||a.clientY<c||a.clientY>=c+this._target.clientHeight?b=e=null:(e=a.clientX-d,b=a.clientY-c)},_calcTouchCoords:function(a){for(var b=0,c=0,d=a.target;!(d instanceof HTMLElement);)d=d.parentNode;do b+=d.offsetLeft-d.scrollLeft,c+=d.offsetTop-d.scrollTop,d=d.offsetParent;while(d);return{x:a.pageX-b,y:a.pageY-c}},_sortElements:function(a,b){var c=this.app.scene.layers.sortTransparentLayers(a.layers,b.layers);return 0!==
|
|
c?c:a.screen&&!b.screen?-1:!a.screen&&b.screen?1:a.screen||b.screen?a.screen.screen.screenSpace&&!b.screen.screen.screenSpace?-1:b.screen.screen.screenSpace&&!a.screen.screen.screenSpace?1:b.drawOrder-a.drawOrder:0},_getTargetElement:function(a,b,c){var d=null;this._elements.sort(this._sortHandler);for(var f=0,g=this._elements.length;f<g;f++){var e=this._elements[f];if(e.screen&&e.screen.screen.screenSpace){if(this._checkElement2d(b,c,e,a)){d=e;break}}else if(this._checkElement3d(b,c,e,a)){d=e;break}}return d},
|
|
_buildHitCorners:function(a,b,c,d){if(a.entity&&a.entity.button){var f=a.entity.button.hitPadding||y;q.copy(a.entity.up);m.copy(q).scale(-1);t.copy(a.entity.right);r.copy(t).scale(-1);q.scale(f.w*d);m.scale(f.y*d);t.scale(f.z*c);r.scale(f.x*c);u.copy(b[0]).add(m).add(r);x.copy(b[1]).add(m).add(t);v.copy(b[2]).add(q).add(t);w.copy(b[3]).add(q).add(r);b=[u,x,v,w]}return b},_calculateScaleToScreen:function(a){var b=a.entity;a=a.screen.screen.scale;for(n.set(a,a);b&&!b.screen;)n.mul(b.getLocalScale()),
|
|
b=b.parent;return n},_checkElement2d:function(b,d,f,g){if(f.maskedBy&&!this._checkElement2d(b,d,f.maskedBy.element,g))return!1;var e=this.app.graphicsDevice.width,h=this.app.graphicsDevice.height,l=g.rect.z*e,k=g.rect.w*h,p=g.rect.x*e;g=(1-g.rect.y)*h;var n=g-k;b=b*e/this._target.clientWidth;d=d*h/this._target.clientHeight;return b>=p&&b<=p+l&&d<=g&&d>=n&&(b=e*(b-p)/l,d=h-h*(d-n)/k,e=this._calculateScaleToScreen(f),f=this._buildHitCorners(f,f.screenCorners,e.x,e.y),a.set(b,d,1),c.set(b,d,-1),D(a,
|
|
c,f))?!0:!1},_checkElement3d:function(b,d,f,g){if(f.maskedBy&&!this._checkElement3d(b,d,f.maskedBy.element,g))return!1;var e=this._target.clientWidth,h=this._target.clientHeight,l=g.rect.z*e,k=g.rect.w*h,p=g.rect.x*e,n=(1-g.rect.y)*h,m=n-k,q=d;return b>=p&&b<=p+l&&d<=n&&q>=m&&(b=e*(b-p)/l,q=h*(q-m)/k,h=f.entity.getWorldTransform().getScale(),f=this._buildHitCorners(f,f.worldCorners,h.x,h.y),g.screenToWorld(b,q,g.nearClip,a),g.screenToWorld(b,q,g.farClip,c),D(a,c,f))?!0:!1}});Object.defineProperty(F.prototype,
|
|
"enabled",{get:function(){return this._enabled},set:function(a){this._enabled=a}});Object.defineProperty(F.prototype,"app",{get:function(){return this._app||pc.app},set:function(a){this._app=a}});return{ElementInput:F,ElementInputEvent:B,ElementMouseEvent:z,ElementTouchEvent:A}}());Object.assign(pc,function(){var e=function(b){pc.events.attach(this);var a=this;this.isSupported=e.isSupported;this.usesPolyfill=e.usesPolyfill;window.InitializeWebVRPolyfill&&window.InitializeWebVRPolyfill();this._index={};this.displays=[];this.display=null;this._app=b;this._onDisplayConnect=this._onDisplayConnect.bind(this);this._onDisplayDisconnect=this._onDisplayDisconnect.bind(this);a._attach();this._getDisplays(function(b,d){if(b)a.fire("error",b);else{for(var c=0;c<d.length;c++)a._addDisplay(d[c]);
|
|
a.fire("ready",a.displays)}})};e.isSupported=!!navigator.getVRDisplays;e.usesPolyfill=!!window.InitializeWebVRPolyfill;Object.assign(e.prototype,{_attach:function(){window.addEventListener("vrdisplayconnect",this._onDisplayConnect);window.addEventListener("vrdisplaydisconnect",this._onDisplayDisconnect)},_detach:function(){window.removeEventListener("vrdisplayconnect",this._onDisplayConnect);window.removeEventListener("vrdisplaydisconnect",this._onDisplayDisconnect)},destroy:function(){this._detach()},
|
|
poll:function(){var b=this.displays.length;if(b)for(var a=0;a<b;a++)this.displays[a]._camera&&this.displays[a].poll()},_getDisplays:function(b){navigator.getVRDisplays?navigator.getVRDisplays().then(function(a){b&&b(null,a)}):b&&b(Error("WebVR not supported"))},_addDisplay:function(b){this._index[b.displayId]||(b=new pc.VrDisplay(this._app,b),this._index[b.id]=b,this.displays.push(b),this.display||(this.display=b),this.fire("displayconnect",b))},_onDisplayConnect:function(b){b.detail&&b.detail.display?
|
|
this._addDisplay(b.detail.display):this._addDisplay(b.display)},_onDisplayDisconnect:function(b){if(b=this._index[b.detail&&b.detail.display?b.detail.display.displayId:b.display.displayId]){b.destroy();delete this._index[b.id];var a=this.displays.indexOf(b);this.displays.splice(a,1);this.display===b&&(this.display=this.displays.length?this.displays[0]:null);this.fire("displaydisconnect",b)}}});return{VrManager:e}}());Object.assign(pc,function(){var e=function(b,a){var c=this;this._app=b;this._device=b.graphicsDevice;this.id=a.displayId;this._frameData=null;window.VRFrameData&&(this._frameData=new window.VRFrameData);this.display=a;this._camera=null;this.sitToStandInv=new pc.Mat4;this.leftView=new pc.Mat4;this.leftProj=new pc.Mat4;this.leftViewInv=new pc.Mat4;this.leftPos=new pc.Vec3;this.rightView=new pc.Mat4;this.rightProj=new pc.Mat4;this.rightViewInv=new pc.Mat4;this.rightPos=new pc.Vec3;this.combinedPos=new pc.Vec3;
|
|
this.combinedView=new pc.Mat4;this.combinedProj=new pc.Mat4;this.combinedViewInv=new pc.Mat4;this.combinedAspect=this.combinedFov=0;this.presenting=!1;c._presentChange=function(a){if((a.display?a.display:a.detail&&a.detail.display?a.detail.display:a.detail&&a.detail.vrdisplay?a.detail.vrdisplay:c.display)===c.display){c.presenting=c.display&&c.display.isPresenting;if(c.presenting){a=c.display.getEyeParameters("left");var b=c.display.getEyeParameters("right");c._app.graphicsDevice.setResolution(2*
|
|
Math.max(a.renderWidth,b.renderWidth),Math.max(a.renderHeight,b.renderHeight));c._app._allowResize=!1}else c._app.setCanvasResolution(pc.RESOLUTION_AUTO),c._app._allowResize=!0;c.fire("beforepresentchange",c);c.fire("presentchange",c)}};window.addEventListener("vrdisplaypresentchange",c._presentChange,!1);pc.events.attach(this)};Object.assign(e.prototype,{destroy:function(){window.removeEventListener("vrdisplaypresentchange",self._presentChange);this._camera&&(this._camera.vrDisplay=null);this._camera=
|
|
null},poll:function(){if(this.display){this.display.getFrameData(this._frameData);this.leftProj.data=this._frameData.leftProjectionMatrix;this.rightProj.data=this._frameData.rightProjectionMatrix;var b=this.display.stageParameters;b?(this.sitToStandInv.set(b.sittingToStandingTransform).invert(),this.combinedView.set(this._frameData.leftViewMatrix),this.leftView.mul2(this.combinedView,this.sitToStandInv),this.combinedView.set(this._frameData.rightViewMatrix),this.rightView.mul2(this.combinedView,this.sitToStandInv)):
|
|
(this.leftView.set(this._frameData.leftViewMatrix),this.rightView.set(this._frameData.rightViewMatrix));var a=this.leftProj.data[3]+this.leftProj.data[0],c=this.leftProj.data[11]+this.leftProj.data[8],d=1/Math.sqrt(a*a+c*c),b=-Math.atan2(c*d,a*d),a=this.rightProj.data[3]+this.rightProj.data[0],c=this.rightProj.data[11]+this.rightProj.data[8],d=1/Math.sqrt(a*a+c*c),b=Math.max(b,-Math.atan2(c*d,a*d));this.combinedFov=b*=2;this.combinedAspect=a=this.rightProj.data[5]/this.rightProj.data[0];c=this.combinedView;
|
|
c.copy(this.leftView);c.invert();this.leftViewInv.copy(c);d=this.combinedPos;d.x=this.leftPos.x=c.data[12];d.y=this.leftPos.y=c.data[13];d.z=this.leftPos.z=c.data[14];c.copy(this.rightView);c.invert();this.rightViewInv.copy(c);var f=d.x-c.data[12],g=d.y-c.data[13],e=d.z-c.data[14],f=Math.sqrt(f*f+g*g+e*e);this.rightPos.x=c.data[12];this.rightPos.y=c.data[13];this.rightPos.z=c.data[14];d.x+=c.data[12];d.y+=c.data[13];d.z+=c.data[14];d.x*=.5;d.y*=.5;d.z*=.5;f=.5*f*Math.sin(Math.PI-(.5*Math.PI+.5*b));
|
|
g=c.data[9];e=c.data[10];c.data[12]=d.x+c.data[8]*f;c.data[13]=d.y+g*f;c.data[14]=d.z+e*f;this.combinedViewInv.copy(c);c.invert();this.combinedProj.setPerspective(b*pc.math.RAD_TO_DEG,a,this.display.depthNear+f,this.display.depthFar+f,!0)}},requestPresent:function(b){this.display?this.presenting?b&&b(Error("VrDisplay already presenting")):this.display.requestPresent([{source:this._device.canvas}]).then(function(){b&&b()},function(a){b&&b(a)}):b&&b(Error("No VrDisplay to requestPresent"))},exitPresent:function(b){this.display||
|
|
b&&b(Error("No VrDisplay to exitPresent"));this.presenting?this.display.exitPresent().then(function(){b&&b()},function(){b&&b(Error("exitPresent failed"))}):b&&b(Error("VrDisplay not presenting"))},requestAnimationFrame:function(b){this.display&&this.display.requestAnimationFrame(b)},submitFrame:function(){this.display&&this.display.submitFrame()},reset:function(){this.display&&this.display.resetPose()},setClipPlanes:function(b,a){this.display&&(this.display.depthNear=b,this.display.depthFar=a)},
|
|
getFrameData:function(){if(this.display)return this._frameData}});Object.defineProperty(e.prototype,"capabilities",{get:function(){return this.display?this.display.capabilities:{}}});return{VrDisplay:e}}());Object.assign(pc,function(){var e=function(){};e.ContentType={FORM_URLENCODED:"application/x-www-form-urlencoded",GIF:"image/gif",JPEG:"image/jpeg",DDS:"image/dds",JSON:"application/json",PNG:"image/png",TEXT:"text/plain",XML:"application/xml",WAV:"audio/x-wav",OGG:"audio/ogg",MP3:"audio/mpeg",MP4:"audio/mp4",AAC:"audio/aac",BIN:"application/octet-stream"};e.ResponseType={TEXT:"text",ARRAY_BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json"};e.binaryExtensions=".model .wav .ogg .mp3 .mp4 .m4a .aac .dds".split(" ");
|
|
Object.assign(e.prototype,{ContentType:e.ContentType,ResponseType:e.ResponseType,binaryExtensions:e.binaryExtensions,get:function(b,a,c){"function"===typeof a&&(c=a,a={});return this.request("GET",b,a,c)},post:function(b,a,c,d){"function"===typeof c&&(d=c,c={});c.postdata=a;return this.request("POST",b,c,d)},put:function(b,a,c,d){"function"===typeof c&&(d=c,c={});c.postdata=a;return this.request("PUT",b,c,d)},del:function(b,a,c){"function"===typeof a&&(c=a,a={});return this.request("DELETE",b,a,c)},
|
|
request:function(b,a,c,d){var f,g,l,h=!1;"function"===typeof c&&(d=c,c={});c.callback=d;null==c.async&&(c.async=!0);null==c.headers&&(c.headers={});if(null!=c.postdata)if(c.postdata instanceof Document)g=c.postdata;else if(c.postdata instanceof FormData)g=c.postdata;else if(c.postdata instanceof Object)switch(g=c.headers["Content-Type"],void 0===g&&(c.headers["Content-Type"]=e.ContentType.FORM_URLENCODED,g=c.headers["Content-Type"]),g){case e.ContentType.FORM_URLENCODED:g="";d=!0;for(f in c.postdata)c.postdata.hasOwnProperty(f)&&
|
|
(d?d=!1:g+="&",g+=escape(f)+"="+escape(c.postdata[f]));break;default:case e.ContentType.JSON:null==g&&(c.headers["Content-Type"]=e.ContentType.JSON),g=JSON.stringify(c.postdata)}else g=c.postdata;l||(l=new XMLHttpRequest);!1===c.cache&&(d=pc.time.now(),f=new pc.URI(a),f.query=f.query?f.query+"&ts="+d:"ts="+d,a=f.toString());c.query&&(f=new pc.URI(a),d=pc.extend(f.getQuery(),c.query),f.setQuery(d),a=f.toString());l.open(b,a,c.async);l.withCredentials=void 0!==c.withCredentials?c.withCredentials:!1;
|
|
l.responseType=c.responseType||this._guessResponseType(a);for(var p in c.headers)c.headers.hasOwnProperty(p)&&l.setRequestHeader(p,c.headers[p]);l.onreadystatechange=function(){this._onReadyStateChange(b,a,c,l)}.bind(this);l.onerror=function(){this._onError(b,a,c,l);h=!0}.bind(this);try{l.send(g)}catch(k){h||c.error(l.status,l,k)}return l},_guessResponseType:function(b){b=new pc.URI(b);b=pc.path.getExtension(b.path);return 0<=e.binaryExtensions.indexOf(b)?e.ResponseType.ARRAY_BUFFER:".xml"===b?e.ResponseType.DOCUMENT:
|
|
e.ResponseType.TEXT},_isBinaryContentType:function(b){return 0<=[e.ContentType.MP4,e.ContentType.WAV,e.ContentType.OGG,e.ContentType.MP3,e.ContentType.BIN,e.ContentType.DDS].indexOf(b)?!0:!1},_onReadyStateChange:function(b,a,c,d){if(4===d.readyState)switch(d.status){case 0:"/"!=a[0]?this._onSuccess(b,a,c,d):this._onError(b,a,c,d);break;case 200:case 201:case 206:case 304:this._onSuccess(b,a,c,d);break;default:this._onError(b,a,c,d)}},_onSuccess:function(b,a,c,d){var f,g;if(b=d.getResponseHeader("Content-Type"))g=
|
|
b.split(";"),g=g[0].trim();try{g===this.ContentType.JSON||a.split("?")[0].endsWith(".json")?f=JSON.parse(d.responseText):this._isBinaryContentType(g)?f=d.response:(g&&logWARNING(pc.string.format("responseType: {0} being served with Content-Type: {1}",d.responseType,g)),f=d.responseType===e.ResponseType.ARRAY_BUFFER?d.response:d.responseType===e.ResponseType.BLOB||d.responseType===e.ResponseType.JSON?d.response:d.responseType===e.ResponseType.DOCUMENT||g===this.ContentType.XML?d.responseXML:d.responseText),
|
|
c.callback(null,f)}catch(l){c.callback(l)}},_onError:function(b,a,c,d){c.callback(d.status,null)}});return{Http:e,http:new e}}());Object.assign(pc,function(){var e=function(b){pc.events.attach(this);this.app=b;this._scripts={};this._list=[]};e.prototype.destroy=function(){this.app=null;this.off()};e.prototype.add=function(b){var a=this;if(this._scripts.hasOwnProperty(b.__name))return setTimeout(function(){if(b.prototype.swap){var c=a._list.indexOf(a._scripts[b.__name]);a._list[c]=b;a._scripts[b.__name]=b;a.fire("swap",b.__name,b);a.fire("swap:"+b.__name,b)}else console.warn("script registry already has '"+b.__name+"' script, define 'swap' method for new script type to enable code hot swapping")}),
|
|
!1;this._scripts[b.__name]=b;this._list.push(b);this.fire("add",b.__name,b);this.fire("add:"+b.__name,b);setTimeout(function(){if(a._scripts.hasOwnProperty(b.__name)&&a.app&&a.app.systems&&a.app.systems.script){var c=a.app.systems.script._components,d,f,g=[],e=[];for(c.loopIndex=0;c.loopIndex<c.length;c.loopIndex++)d=c.items[c.loopIndex],d._scriptsIndex[b.__name]&&d._scriptsIndex[b.__name].awaiting&&(d._scriptsData&&d._scriptsData[b.__name]&&(f=d._scriptsData[b.__name].attributes),(d=d.create(b.__name,
|
|
{preloading:!0,ind:d._scriptsIndex[b.__name].ind,attributes:f}))&&g.push(d));for(c=0;c<g.length;c++)g[c].__initializeAttributes();for(c=0;c<g.length;c++)g[c].enabled&&(g[c]._initialized=!0,e.push(g[c]),g[c].initialize&&g[c].initialize());for(c=0;c<e.length;c++)e[c].enabled&&!e[c]._postInitialized&&(e[c]._postInitialized=!0,e[c].postInitialize&&e[c].postInitialize())}});return!0};e.prototype.remove=function(b){"function"===typeof b&&(b=b.__name);if(!this._scripts.hasOwnProperty(b))return!1;var a=this._scripts[b];
|
|
delete this._scripts[b];var c=this._list.indexOf(a);this._list.splice(c,1);this.fire("remove",b,a);this.fire("remove:"+b,a);return!0};e.prototype.get=function(b){return this._scripts[b]||null};e.prototype.has=function(b){return this._scripts.hasOwnProperty(b)};e.prototype.list=function(){return this._list};return{ScriptRegistry:e}}());Object.assign(pc,function(){var e=["x","y","z","w"],b=function(a,b,c,d){switch(b.type){case "boolean":return!!c;case "number":if("number"===typeof c)break;else{if("string"===typeof c)return c=parseInt(c,10),isNaN(c)?null:c;if("boolean"===typeof c)return 0+c}return null;case "json":if("object"===typeof c)break;try{return JSON.parse(c)}catch(k){return null}case "asset":if(c instanceof pc.Asset)break;else{if("number"===typeof c)return a.assets.get(c)||null;if("string"===typeof c)return a.assets.get(parseInt(c,
|
|
10))||null}return null;case "entity":if(c instanceof pc.GraphNode)break;else if("string"===typeof c)return a.root.findByGuid(c);return null;case "rgb":case "rgba":if(c instanceof pc.Color)return d instanceof pc.Color?(d.copy(c),d):c.clone();if(c instanceof Array&&3<=c.length&&4>=c.length){for(a=0;a<c.length;a++)if("number"!==typeof c[a])return null;d||(d=new pc.Color);d.r=c[0];d.g=c[1];d.b=c[2];d.a=3===c.length?1:c[3];return d}return"string"===typeof c&&/#([0-9abcdef]{2}){3,4}/i.test(c)?(d||(d=new pc.Color),
|
|
d.fromString(c),d):null;case "vec2":case "vec3":case "vec4":b=parseInt(b.type.slice(3),10);if(c instanceof pc["Vec"+b])return d instanceof pc["Vec"+b]?(d.copy(c),d):c.clone();if(c instanceof Array&&c.length===b){for(a=0;a<c.length;a++)if("number"!==typeof c[a])return null;d||(d=new pc["Vec"+b]);for(a=0;a<b;a++)d[e[a]]=c[a];return d}return null;case "curve":if(c)return c instanceof pc.Curve||c instanceof pc.CurveSet?d=c.clone():(d=new (c.keys[0]instanceof Array?pc.CurveSet:pc.Curve)(c.keys),d.type=
|
|
c.type),d}return c},a=function(a){this.scriptType=a;this.index={}};a.prototype.add=function(a,c){this.index[a]||pc.createScript.reservedAttributes[a]||(this.index[a]=c,Object.defineProperty(this.scriptType.prototype,a,{get:function(){return this.__attributes[a]},set:function(d){var f=this.__attributes[a];if(c.array){if(this.__attributes[a]=[],d){var g,e;g=0;for(e=d.length;g<e;g++)this.__attributes[a].push(b(this.app,c,d[g],f?f[g]:null))}}else this.__attributes[a]=b(this.app,c,d,f);this.fire("attr",
|
|
a,this.__attributes[a],f);this.fire("attr:"+a,this.__attributes[a],f)}}))};a.prototype.remove=function(a){if(!this.index[a])return!1;delete this.index[a];delete this.scriptType.prototype[a];return!0};a.prototype.has=function(a){return!!this.index[a]};a.prototype.get=function(a){return this.index[a]||null};var c=function(b,d){if(pc.script.legacy)return null;if(c.reservedScripts[b])throw Error("script name: '"+b+"' is reserved, please change script name");var f=function(a){pc.events.attach(this);this.app=
|
|
a.app;this.entity=a.entity;this._enabled="boolean"===typeof a.enabled?a.enabled:!0;this._enabledOld=this.enabled;this.__destroyed=!1;this.__attributes={};this.__attributesRaw=a.attributes||null;this.__scriptType=f;this.__executionOrder=-1};f.__name=b;f.attributes=new a(f);f.prototype.__initializeAttributes=function(a){if(a||this.__attributesRaw){for(var b in f.attributes.index)this.__attributesRaw&&this.__attributesRaw.hasOwnProperty(b)?this[b]=this.__attributesRaw[b]:this.__attributes.hasOwnProperty(b)||
|
|
(f.attributes.index[b].hasOwnProperty("default")?this[b]=f.attributes.index[b]["default"]:this[b]=null);this.__attributesRaw=null}};f.extend=function(a){for(var b in a)a.hasOwnProperty(b)&&(f.prototype[b]=a[b])};Object.defineProperty(f.prototype,"enabled",{get:function(){return this._enabled&&!this._destroyed&&this.entity.script.enabled&&this.entity.enabled},set:function(a){this._enabled=!!a;this.enabled!==this._enabledOld&&(this._enabledOld=this.enabled,this.fire(this.enabled?"enable":"disable"),
|
|
this.fire("state",this.enabled),!this._initialized&&this.enabled&&(this._initialized=!0,this.__initializeAttributes(!0),this.initialize&&this.entity.script._scriptMethod(this,pc.ScriptComponent.scriptMethods.initialize)),this._initialized&&!this._postInitialized&&this.enabled&&!this.entity.script._beingEnabled&&(this._postInitialized=!0,this.postInitialize&&this.entity.script._scriptMethod(this,pc.ScriptComponent.scriptMethods.postInitialize)))}});(d?d.scripts:pc.Application.getApplication().scripts).add(f);
|
|
pc.ScriptHandler._push(f);return f};c.reservedScripts="system entity create destroy swap move scripts _scripts _scriptsIndex _scriptsData enabled _oldState onEnable onDisable onPostStateChange _onSetEnabled _checkState _onBeforeRemove _onInitializeAttributes _onInitialize _onPostInitialize _onUpdate _onPostUpdate _callbacks has on off fire once hasEvent".split(" ");var d={},f;for(f=0;f<c.reservedScripts.length;f++)d[c.reservedScripts[f]]=1;c.reservedScripts=d;c.reservedAttributes="app entity enabled _enabled _enabledOld _destroyed __attributes __attributesRaw __scriptType __executionOrder _callbacks has on off fire once hasEvent".split(" ");
|
|
d={};for(f=0;f<c.reservedAttributes.length;f++)d[c.reservedAttributes[f]]=1;c.reservedAttributes=d;return{createScript:c}}());Object.assign(pc,function(){var e=function(b){this._blobUrls={};for(var a=0,c=b.length;a<c;a++)b[a].url&&(this._blobUrls[b[a].name]=b[a].url)};e.prototype.hasBlobUrl=function(b){return!!this._blobUrls[b]};e.prototype.getBlobUrl=function(b){return this._blobUrls[b]};e.prototype.destroy=function(){for(var b in this._blobUrls)URL.revokeObjectURL(this._blobUrls[b]);this._blobUrls=null};return{Bundle:e}}());Object.assign(pc,function(){var e=function(b){this._assets=b;this._bundleAssets={};this._assetsInBundles={};this._urlsInBundles={};this._fileRequests={};this._assets.on("add",this._onAssetAdded,this);this._assets.on("remove",this._onAssetRemoved,this)};Object.assign(e.prototype,{_onAssetAdded:function(b){if("bundle"===b.type){this._bundleAssets[b.id]=b;this._registerBundleEventListeners(b.id);for(var a=0,c=b.data.assets.length;a<c;a++)this._indexAssetInBundle(b.data.assets[a],b)}else this._assetsInBundles[b.id]&&
|
|
this._indexAssetFileUrls(b)},_registerBundleEventListeners:function(b){this._assets.on("load:"+b,this._onBundleLoaded,this);this._assets.on("error:"+b,this._onBundleError,this)},_unregisterBundleEventListeners:function(b){this._assets.off("load:"+b,this._onBundleLoaded,this);this._assets.off("error:"+b,this._onBundleError,this)},_indexAssetInBundle:function(b,a){if(this._assetsInBundles[b]){var c=this._assetsInBundles[b];-1===c.indexOf(a)&&c.push(a)}else this._assetsInBundles[b]=[a];(c=this._assets.get(b))&&
|
|
this._indexAssetFileUrls(c)},_indexAssetFileUrls:function(b){var a=this._getAssetFileUrls(b);if(a)for(var c=0,d=a.length;c<d;c++)this._urlsInBundles[a[c]]=this._assetsInBundles[b.id]},_getAssetFileUrls:function(b){var a=b.getFileUrl();if(!a)return null;var a=this._normalizeUrl(a),c=[a];if("font"===b.type){b=b.data.info.maps.length;for(var d=1;d<b;d++)c.push(a.replace(".png",d+".png"))}return c},_normalizeUrl:function(b){return b&&b.split("?")[0]},_onAssetRemoved:function(b){if("bundle"===b.type){delete this._bundleAssets[b.id];
|
|
this._unregisterBundleEventListeners(b.id);var a,c;for(c in this._assetsInBundles){var d=this._assetsInBundles[c];a=d.indexOf(b);if(-1!==a&&(d.splice(a,1),!d.length)){delete this._assetsInBundles[c];for(var f in this._urlsInBundles)this._urlsInBundles[f]===d&&delete this._urlsInBundles[f]}}this._onBundleError("Bundle "+b.id+" was removed",b)}else if(this._assetsInBundles[b.id])for(delete this._assetsInBundles[b.id],b=this._getAssetFileUrls(b),a=0,c=b.length;a<c;a++)delete this._urlsInBundles[b[a]]},
|
|
_onBundleLoaded:function(b){b.resource?requestAnimationFrame(function(){if(this._fileRequests)for(var a in this._fileRequests){var c=this._urlsInBundles[a];if(c&&-1!==c.indexOf(b)){var c=decodeURIComponent(a),d=null;b.resource.hasBlobUrl(c)||(d="Bundle "+b.id+" does not contain URL "+a);for(var f=this._fileRequests[a],g=0,e=f.length;g<e;g++)if(d)f[g](d);else f[g](null,b.resource.getBlobUrl(c));delete this._fileRequests[a]}}}.bind(this)):this._onBundleError("Bundle "+b.id+" failed to load",b)},_onBundleError:function(b,
|
|
a){for(var c in this._fileRequests)if(!this._findLoadedOrLoadingBundleForUrl(c)){for(var d=this._fileRequests[c],f=0,g=d.length;f<g;f++)d[f](b);delete this._fileRequests[c]}},_findLoadedOrLoadingBundleForUrl:function(b){b=this._urlsInBundles[b];if(!b)return null;var a=b.length,c;for(c=0;c<a;c++)if(b[c].loaded&&b[c].resource)return b[c];for(c=0;c<a;c++)if(b[c].loading)return b[c];return null},listBundlesForAsset:function(b){return this._assetsInBundles[b.id]||null},list:function(){var b=[],a;for(a in this._bundleAssets)b.push(this._bundleAssets[a]);
|
|
return b},hasUrl:function(b){return!!this._urlsInBundles[b]},canLoadUrl:function(b){return!!this._findLoadedOrLoadingBundleForUrl(b)},loadUrl:function(b,a){var c=this._findLoadedOrLoadingBundleForUrl(b);if(c)if(c.loaded){var d=decodeURIComponent(b);c.resource.hasBlobUrl(d)?a(null,c.resource.getBlobUrl(d)):a("Bundle "+c.id+" does not contain URL "+b)}else this._fileRequests.hasOwnProperty(b)?this._fileRequests[b].push(a):this._fileRequests[b]=[a];else a("URL "+b+" not found in any bundles")},destroy:function(){this._assets.off("add",
|
|
this._onAssetAdded,this);this._assets.off("remove",this._onAssetRemoved,this);for(var b in this._bundleAssets)this._unregisterBundleEventListeners(b);this._fileRequests=this._urlsInBundles=this._assetsInBundles=this._bundleAssets=this._assets=null}});return{BundleRegistry:e}}());Object.assign(pc,function(){var e=function(){};e.prototype._validate=function(b){if(!b.header)throw Error('pc.I18n#addData: Missing "header" field');if(!b.header.version)throw Error('pc.I18n#addData: Missing "header.version" field');if(1!==b.header.version)throw Error('pc.I18n#addData: Invalid "header.version" field');if(!b.data)throw Error('pc.I18n#addData: Missing "data" field');if(!Array.isArray(b.data))throw Error('pc.I18n#addData: "data" field must be an array');for(var a=0,c=b.data.length;a<
|
|
c;a++){var d=b.data[a];if(!d.info)throw Error('pc.I18n#addData: missing "data['+a+'].info" field');if(!d.info.locale)throw Error('pc.I18n#addData: missing "data['+a+'].info.locale" field');if("string"!==typeof d.info.locale)throw Error('pc.I18n#addData: "data['+a+'].info.locale" must be a string');if(!d.messages)throw Error('pc.I18n#addData: missing "data['+a+'].messages" field');}};e.prototype.parse=function(b){return b.data};return{I18nParser:e}}());Object.assign(pc,function(){var e={},b=function(a,b){for(var c=0,d=a.length;c<d;c++)e[a[c]]=b},a=function(a){var b=a.indexOf("-");return-1!==b?a.substring(0,b):a},c={en:"en-US",es:"en-ES",zh:"zh-CN",fr:"fr-FR",de:"de-DE",it:"it-IT",ru:"ru-RU",ja:"ja-JP"};b(["ja","ko","th","vi","zh"],function(a){return 0});b(["fa","hi"],function(a){return 0<=a&&1>=a?0:1});b(["fr"],function(a){return 0<=a&&2>a?0:1});b("de en it el es tr".split(" "),function(a){return 1===a?0:1});b(["ru","uk"],function(a){if(Number.isInteger(a)){var b=
|
|
a%10;a%=100;if(1===b&&11!==a)return 0;if(2<=b&&4>=b&&(12>a||14<a))return 1;if(0===b||5<=b&&9>=b||11<=a&&14>=a)return 2}return 3});b(["ar"],function(a){if(0===a)return 0;if(1===a)return 1;if(2===a)return 2;if(Number.isInteger(a)){a%=100;if(3<=a&&10>=a)return 3;if(11<=a&&99>=a)return 4}return 5});var d=e[a("en-US")],b=function(a){pc.events.attach(this);this.locale="en-US";this._translations={};this._availableLangs={};this._app=a;this._assets=[];this._parser=new pc.I18nParser};b.prototype.getText=function(b,
|
|
c){var d=b,f;c||(c=this._locale,f=this._lang);var g=this._translations[c];g||(f||(f=a(c)),c=this._findFallbackLocale(f),g=this._translations[c]);g&&g.hasOwnProperty(b)&&(d=g[b],Array.isArray(d)&&(d=d[0]),null===d||void 0===d)&&(d=b);return d};b.prototype.getPluralText=function(b,c,l){var f=b,g,k;l?(k=a(l),g=e[k]||d):(l=this._locale,k=this._lang,g=this._pluralFn);l=this._translations[l];l||(l=this._findFallbackLocale(k),k=a(l),g=e[k]||d,l=this._translations[l]);l&&l[b]&&g&&(c=g(c),f=l[b][c],null===
|
|
f||void 0===f)&&(f=b);return f};b.prototype.addData=function(b){var c;try{c=this._parser.parse(b)}catch(n){console.error(n);return}b=0;for(var d=c.length;b<d;b++){var f=c[b],e=f.info.locale,f=f.messages;if(!this._translations[e]){this._translations[e]={};var k=a(e);this._availableLangs[k]||(this._availableLangs[k]=e)}Object.assign(this._translations[e],f);this.fire("data:add",e,f)}};b.prototype.removeData=function(b){var c,d;try{c=this._parser.parse(b)}catch(m){console.error(m);return}b=0;for(var f=
|
|
c.length;b<f;b++){var e=c[b],k=e.info.locale,n=this._translations[k];if(n){e=e.messages;for(d in e)delete n[d];var q=!1;for(d in n){q=!0;break}q||(delete this._translations[k],delete this._availableLangs[a(k)]);this.fire("data:remove",k,e)}}};b.prototype.destroy=function(){this._parser=this._assets=this._availableLangs=this._translations=null;this.off()};Object.defineProperty(b.prototype,"locale",{get:function(){return this._locale},set:function(b){if(this._locale!==b){var c=this._locale;this._locale=
|
|
b;this._lang=a(b);this._pluralFn=e[this._lang]||d;this.fire("set:locale",b,c)}}});Object.defineProperty(b.prototype,"assets",{get:function(){return this._assets},set:function(a){var b,c,d,f={};b=0;for(c=a.length;b<c;b++)d=a[b]instanceof pc.Asset?a[b].id:a[b],f[d]=!0;for(b=this._assets.length;b--;)d=this._assets[b],f[d]||(this._app.assets.off("add:"+d,this._onAssetAdd,this),(a=this._app.assets.get(d))&&this._onAssetRemove(a),this._assets.splice(b,1));for(d in f)if(d=parseInt(d,10),-1===this._assets.indexOf(d))if(this._assets.push(d),
|
|
a=this._app.assets.get(d))this._onAssetAdd(a);else this._app.assets.once("add:"+d,this._onAssetAdd,this)}});b.prototype._findFallbackLocale=function(a){var b=c[a];return b&&this._translations[b]?b:(b=this._availableLangs[a])&&this._translations[b]?b:"en-US"};b.prototype._onAssetAdd=function(a){a.on("load",this._onAssetLoad,this);a.on("change",this._onAssetChange,this);a.on("remove",this._onAssetRemove,this);a.on("unload",this._onAssetUnload,this);a.resource&&this._onAssetLoad(a)};b.prototype._onAssetLoad=
|
|
function(a){this.addData(a.resource)};b.prototype._onAssetChange=function(a){a.resource&&this.addData(a.resource)};b.prototype._onAssetRemove=function(a){a.off("load",this._onAssetLoad,this);a.off("change",this._onAssetChange,this);a.off("remove",this._onAssetRemove,this);a.off("unload",this._onAssetUnload,this);a.resource&&this.removeData(a.resource);this._app.assets.once("add:"+a.id,this._onAssetAdd,this)};b.prototype._onAssetUnload=function(a){a.resource&&this.removeData(a.resource)};return{I18n:b}}());pc.script=function(){var e=!1,b=!1,a={app:null,create:function(a,b){if(e){var c=b(pc.script.app);c._pcScriptName=a;pc.ScriptHandler._push(c);this.fire("created",a,b)}},attribute:function(a,b,f,g){},createLoadingScreen:function(a){if(!b){b=!0;var c=pc.Application.getApplication();a(c)}}};Object.defineProperty(a,"legacy",{get:function(){return e},set:function(a){e=a}});pc.events.attach(a);return a}();Object.assign(pc,function(){var e=function(a,b){b=b||{};pc.log.open();pc.events.attach(this);e._applications[a.id]=this;e._currentApplication=this;pc.app=this;this._time=0;this.timeScale=1;this.maxDeltaTime=.1;this.frame=0;this.autoRender=!0;this.renderNextFrame=!1;this.useLegacyScriptAttributeCloning=pc.script.legacy;this._librariesLoaded=!1;this._fillMode=pc.FILLMODE_KEEP_ASPECT;this._resolutionMode=pc.RESOLUTION_FIXED;this._allowResize=!0;this.context=this;this.graphicsDevice=new pc.GraphicsDevice(a,
|
|
b.graphicsDeviceOptions);this.stats=new pc.ApplicationStats(this.graphicsDevice);this._audioManager=new pc.SoundManager(b);this.loader=new pc.ResourceLoader(this);this._entityIndex={};this.scene=new pc.Scene;this.root=new pc.Entity(this);this.root._enabledInHierarchy=!0;this._enableList=[];this._enableList.size=0;this.assets=new pc.AssetRegistry(this.loader);b.assetPrefix&&(this.assets.prefix=b.assetPrefix);this.bundles=new pc.BundleRegistry(this.assets);this.enableBundles="undefined"!==typeof TextDecoder;
|
|
this.scriptsOrder=b.scriptsOrder||[];this.scripts=new pc.ScriptRegistry(this);this.i18n=new pc.I18n(this);this._sceneRegistry=new pc.SceneRegistry(this);var d=this;this.defaultLayerWorld=new pc.Layer({name:"World",id:pc.LAYERID_WORLD});this.graphicsDevice.webgl2?(this.defaultLayerDepth=new pc.Layer({enabled:!1,name:"Depth",id:pc.LAYERID_DEPTH,onEnable:function(){if(!this.renderTarget){var a=new pc.Texture(d.graphicsDevice,{format:pc.PIXELFORMAT_DEPTHSTENCIL,width:d.graphicsDevice.width,height:d.graphicsDevice.height});
|
|
a.name="rt-depth2";a.minFilter=pc.FILTER_NEAREST;a.magFilter=pc.FILTER_NEAREST;a.addressU=pc.ADDRESS_CLAMP_TO_EDGE;a.addressV=pc.ADDRESS_CLAMP_TO_EDGE;this.renderTarget=new pc.RenderTarget({colorBuffer:null,depthBuffer:a,autoResolve:!1});d.graphicsDevice.scope.resolve("uDepthMap").setValue(a)}},onDisable:function(){this.renderTarget&&(this.renderTarget._depthBuffer.destroy(),this.renderTarget.destroy(),this.renderTarget=null)},onPreRenderOpaque:function(a){var b=d.graphicsDevice.gl;this.srcFbo=b.getParameter(b.FRAMEBUFFER_BINDING);
|
|
this.renderTarget&&this.renderTarget.width===d.graphicsDevice.width&&this.renderTarget.height===d.graphicsDevice.height||(this.onDisable(),this.onEnable());this.oldClear=this.cameras[a].camera._clearOptions;this.cameras[a].camera._clearOptions=this.depthClearOptions},onPostRenderOpaque:function(a){this.renderTarget&&(this.cameras[a].camera._clearOptions=this.oldClear,a=d.graphicsDevice.gl,d.graphicsDevice.setRenderTarget(this.renderTarget),d.graphicsDevice.updateBegin(),a.bindFramebuffer(a.READ_FRAMEBUFFER,
|
|
this.srcFbo),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,this.renderTarget._glFrameBuffer),a.blitFramebuffer(0,0,this.renderTarget.width,this.renderTarget.height,0,0,this.renderTarget.width,this.renderTarget.height,a.DEPTH_BUFFER_BIT,a.NEAREST))}}),this.defaultLayerDepth.depthClearOptions={flags:0}):(this.defaultLayerDepth=new pc.Layer({enabled:!1,name:"Depth",id:pc.LAYERID_DEPTH,shaderPass:pc.SHADER_DEPTH,onEnable:function(){if(!this.renderTarget){var a=new pc.Texture(d.graphicsDevice,{format:pc.PIXELFORMAT_R8_G8_B8_A8,
|
|
width:d.graphicsDevice.width,height:d.graphicsDevice.height});a.name="rt-depth1";a.minFilter=pc.FILTER_NEAREST;a.magFilter=pc.FILTER_NEAREST;a.addressU=pc.ADDRESS_CLAMP_TO_EDGE;a.addressV=pc.ADDRESS_CLAMP_TO_EDGE;this.renderTarget=new pc.RenderTarget(d.graphicsDevice,a,{depth:!0,stencil:d.graphicsDevice.supportsStencil});d.graphicsDevice.scope.resolve("uDepthMap").setValue(a)}},onDisable:function(){this.renderTarget&&(this.renderTarget._colorBuffer.destroy(),this.renderTarget.destroy(),this.renderTarget=
|
|
null)},onPostCull:function(a){var b=this.instances.visibleOpaque[a],c=b.list,f=0,g=d.scene.layers.layerList,e=d.scene.layers.subLayerEnabled,l=d.scene.layers.subLayerList,r=d.defaultLayerWorld.renderTarget;a=this.cameras[a];for(var t,u,x,v,w=0;w<g.length;w++){t=g[w];if(t===this)break;if(t.renderTarget===r&&t.enabled&&e[w]&&(u=t.cameras.indexOf(a),!(0>u)))for(u=(x=l[w])?t.instances.visibleTransparent[u]:t.instances.visibleOpaque[u],x=u.length,u=u.list,t=0;t<x;t++)v=u[t],v.material&&v.material.depthWrite&&
|
|
!v._noDepthDrawGl1&&(c[f]=v,f++)}b.length=f},onPreRenderOpaque:function(a){this.renderTarget&&this.renderTarget.width===d.graphicsDevice.width&&this.renderTarget.height===d.graphicsDevice.height||(this.onDisable(),this.onEnable());this.oldClear=this.cameras[a].camera._clearOptions;this.cameras[a].camera._clearOptions=this.rgbaDepthClearOptions},onDrawCall:function(){d.graphicsDevice.setColorWrite(!0,!0,!0,!0)},onPostRenderOpaque:function(a){this.renderTarget&&(this.cameras[a].camera._clearOptions=
|
|
this.oldClear)}}),this.defaultLayerDepth.rgbaDepthClearOptions={color:[254/255,254/255,254/255,254/255],depth:1,flags:pc.CLEARFLAG_COLOR|pc.CLEARFLAG_DEPTH});this.defaultLayerSkybox=new pc.Layer({enabled:!1,name:"Skybox",id:pc.LAYERID_SKYBOX,opaqueSortMode:pc.SORTMODE_NONE});this.defaultLayerUi=new pc.Layer({enabled:!0,name:"UI",id:pc.LAYERID_UI,transparentSortMode:pc.SORTMODE_MANUAL,passThrough:!1});this.defaultLayerImmediate=new pc.Layer({enabled:!0,name:"Immediate",id:pc.LAYERID_IMMEDIATE,opaqueSortMode:pc.SORTMODE_NONE,
|
|
passThrough:!0});this.defaultLayerComposition=new pc.LayerComposition;this.defaultLayerComposition.pushOpaque(this.defaultLayerWorld);this.defaultLayerComposition.pushOpaque(this.defaultLayerDepth);this.defaultLayerComposition.pushOpaque(this.defaultLayerSkybox);this.defaultLayerComposition.pushTransparent(this.defaultLayerWorld);this.defaultLayerComposition.pushOpaque(this.defaultLayerImmediate);this.defaultLayerComposition.pushTransparent(this.defaultLayerImmediate);this.defaultLayerComposition.pushTransparent(this.defaultLayerUi);
|
|
this.scene.layers=this.defaultLayerComposition;this._immediateLayer=this.defaultLayerImmediate;this.scene.on("set:layers",function(a,b){for(var c=b.layerList,f,g=0;g<c.length;g++)switch(f=c[g],f.id){case pc.LAYERID_DEPTH:f.onEnable=d.defaultLayerDepth.onEnable;f.onDisable=d.defaultLayerDepth.onDisable;f.onPreRenderOpaque=d.defaultLayerDepth.onPreRenderOpaque;f.onPostRenderOpaque=d.defaultLayerDepth.onPostRenderOpaque;f.depthClearOptions=d.defaultLayerDepth.depthClearOptions;f.rgbaDepthClearOptions=
|
|
d.defaultLayerDepth.rgbaDepthClearOptions;f.shaderPass=d.defaultLayerDepth.shaderPass;f.onPostCull=d.defaultLayerDepth.onPostCull;f.onDrawCall=d.defaultLayerDepth.onDrawCall;break;case pc.LAYERID_UI:f.passThrough=d.defaultLayerUi.passThrough;break;case pc.LAYERID_IMMEDIATE:f.passThrough=d.defaultLayerImmediate.passThrough}});this.renderer=new pc.ForwardRenderer(this.graphicsDevice);this.renderer.scene=this.scene;this.lightmapper=new pc.Lightmapper(this.graphicsDevice,this.root,this.scene,this.renderer,
|
|
this.assets);this.once("prerender",this._firstBake,this);this.batcher=new pc.BatchManager(this.graphicsDevice,this.root,this.scene);this.once("prerender",this._firstBatch,this);this.keyboard=b.keyboard||null;this.mouse=b.mouse||null;this.touch=b.touch||null;this.gamepads=b.gamepads||null;if(this.elementInput=b.elementInput||null)this.elementInput.app=this;this.vr=null;b.vr&&this._onVrChange(b.vr);this._inTools=!1;this._skyboxLast=0;this._scriptPrefix=b.scriptPrefix||"";this.enableBundles&&this.loader.addHandler("bundle",
|
|
new pc.BundleHandler(this.assets));this.loader.addHandler("animation",new pc.AnimationHandler);this.loader.addHandler("model",new pc.ModelHandler(this.graphicsDevice,this.scene.defaultMaterial));this.loader.addHandler("material",new pc.MaterialHandler(this));this.loader.addHandler("texture",new pc.TextureHandler(this.graphicsDevice,this.assets,this.loader));this.loader.addHandler("text",new pc.TextHandler);this.loader.addHandler("json",new pc.JsonHandler);this.loader.addHandler("audio",new pc.AudioHandler(this._audioManager));
|
|
this.loader.addHandler("script",new pc.ScriptHandler(this));this.loader.addHandler("scene",new pc.SceneHandler(this));this.loader.addHandler("cubemap",new pc.CubemapHandler(this.graphicsDevice,this.assets,this.loader));this.loader.addHandler("html",new pc.HtmlHandler);this.loader.addHandler("css",new pc.CssHandler);this.loader.addHandler("shader",new pc.ShaderHandler);this.loader.addHandler("hierarchy",new pc.HierarchyHandler(this));this.loader.addHandler("scenesettings",new pc.SceneSettingsHandler(this));
|
|
this.loader.addHandler("folder",new pc.FolderHandler);this.loader.addHandler("font",new pc.FontHandler(this.loader));this.loader.addHandler("binary",new pc.BinaryHandler);this.loader.addHandler("textureatlas",new pc.TextureAtlasHandler(this.loader));this.loader.addHandler("sprite",new pc.SpriteHandler(this.assets,this.graphicsDevice));this.systems=new pc.ComponentSystemRegistry;this.systems.add(new pc.RigidBodyComponentSystem(this));this.systems.add(new pc.CollisionComponentSystem(this));this.systems.add(new pc.AnimationComponentSystem(this));
|
|
this.systems.add(new pc.ModelComponentSystem(this));this.systems.add(new pc.CameraComponentSystem(this));this.systems.add(new pc.LightComponentSystem(this));pc.script.legacy?this.systems.add(new pc.ScriptLegacyComponentSystem(this)):this.systems.add(new pc.ScriptComponentSystem(this));this.systems.add(new pc.AudioSourceComponentSystem(this,this._audioManager));this.systems.add(new pc.SoundComponentSystem(this,this._audioManager));this.systems.add(new pc.AudioListenerComponentSystem(this,this._audioManager));
|
|
this.systems.add(new pc.ParticleSystemComponentSystem(this));this.systems.add(new pc.ScreenComponentSystem(this));this.systems.add(new pc.ElementComponentSystem(this));this.systems.add(new pc.ButtonComponentSystem(this));this.systems.add(new pc.ScrollViewComponentSystem(this));this.systems.add(new pc.ScrollbarComponentSystem(this));this.systems.add(new pc.SpriteComponentSystem(this));this.systems.add(new pc.LayoutGroupComponentSystem(this));this.systems.add(new pc.LayoutChildComponentSystem(this));
|
|
this.systems.add(new pc.ZoneComponentSystem(this));this._visibilityChangeHandler=this.onVisibilityChange.bind(this);void 0!==document.hidden?(this._hiddenAttr="hidden",document.addEventListener("visibilitychange",this._visibilityChangeHandler,!1)):void 0!==document.mozHidden?(this._hiddenAttr="mozHidden",document.addEventListener("mozvisibilitychange",this._visibilityChangeHandler,!1)):void 0!==document.msHidden?(this._hiddenAttr="msHidden",document.addEventListener("msvisibilitychange",this._visibilityChangeHandler,
|
|
!1)):void 0!==document.webkitHidden&&(this._hiddenAttr="webkitHidden",document.addEventListener("webkitvisibilitychange",this._visibilityChangeHandler,!1));this.tick=c(this)};e._currentApplication=null;e._applications={};e.getApplication=function(a){return a?e._applications[a]:e._currentApplication};var b=function(a){this.length=a;this.count=0;this.inc=function(){this.count++};this.done=function(){return this.count===this.length}};Object.assign(e.prototype,{configure:function(a,b){var c=this;pc.http.get(a,
|
|
function(a,d){if(a)b(a);else{var f=d.application_properties,g=d.scenes,e=d.assets;c._parseApplicationProperties(f,function(a){c._onVrChange(f.vr);c._parseScenes(g);c._parseAssets(e);a?b(a):b(null)})}})},preload:function(a){var c=this,d,e;c.fire("preload:start");var h=this.assets.list({preload:!0}),p=new b(h.length),k=!1,n=function(){c.graphicsDevice&&!k&&p.done()&&(k=!0,c.fire("preload:end"),a())};e=h.length;if(p.length){var q=function(a){p.inc();c.fire("preload:progress",p.count/e);p.done()&&n()},
|
|
m=function(a,b){p.inc();c.fire("preload:progress",p.count/e);p.done()&&n()};for(d=0;d<h.length;d++)h[d].loaded?(p.inc(),c.fire("preload:progress",p.count/e),p.done()&&n()):(h[d].once("load",q),h[d].once("error",m),this.assets.load(h[d]))}else n()},getSceneUrl:function(a){return(a=this._sceneRegistry.find(a))?a.url:null},loadSceneHierarchy:function(a,b){this._sceneRegistry.loadSceneHierarchy(a,b)},loadSceneSettings:function(a,b){this._sceneRegistry.loadSceneSettings(a,b)},loadScene:function(a,b){this._sceneRegistry.loadScene(a,
|
|
b)},_preloadScripts:function(a,c){if(pc.script.legacy){var d=this;d.systems.script.preloading=!0;var f=this._getScriptReferences(a),e=0,p=f.length,k=new b(p),n,q=/^http(s)?:\/\//;if(p)for(var m=function(a,b){a&&console.error(a);k.inc();k.done()&&(d.systems.script.preloading=!1,c())},e=0;e<p;e++)n=f[e],!q.test(n.toLowerCase())&&d._scriptPrefix&&(n=pc.path.join(d._scriptPrefix,f[e])),this.loader.load(n,"script",m);else d.systems.script.preloading=!1,c()}else c()},_parseApplicationProperties:function(a,
|
|
b){var c,d;a.useDevicePixelRatio||(a.useDevicePixelRatio=a.use_device_pixel_ratio);a.resolutionMode||(a.resolutionMode=a.resolution_mode);a.fillMode||(a.fillMode=a.fill_mode);a.vrPolyfillUrl||(a.vrPolyfillUrl=a.vr_polyfill_url);this._width=a.width;this._height=a.height;a.useDevicePixelRatio&&(this.graphicsDevice.maxPixelRatio=window.devicePixelRatio);this.setCanvasResolution(a.resolutionMode,this._width,this._height);this.setCanvasFillMode(a.fillMode,this._width,this._height);a.vr&&a.vrPolyfillUrl&&
|
|
(pc.VrManager.isSupported&&!pc.platform.android||a.libraries.push(a.vrPolyfillUrl));if(a.layers&&a.layerOrder){var f=new pc.LayerComposition,e={};for(c in a.layers)d=a.layers[c],d.id=parseInt(c,10),d.enabled=d.id!==pc.LAYERID_DEPTH,e[c]=new pc.Layer(d);c=0;for(d=a.layerOrder.length;c<d;c++){var k=a.layerOrder[c],n=e[k.layer];n&&(k.transparent?f.pushTransparent(n):f.pushOpaque(n),f.subLayerEnabled[c]=k.enabled)}this.scene.layers=f}if(a.batchGroups)for(c=0,d=a.batchGroups.length;c<d;c++)f=a.batchGroups[c],
|
|
this.batcher.addGroup(f.name,f.dynamic,f.maxAabbSize,f.id,f.layers);a.i18nAssets&&(this.i18n.assets=a.i18nAssets);this._loadLibraries(a.libraries,b)},_loadLibraries:function(a,b){var c=a.length,d=c,f=this,e=/^http(s)?:\/\//;if(c)for(var k=function(a,c){d--;a?b(a):0===d&&(f.onLibrariesLoaded(),b(null))},n=0;n<c;++n){var q=a[n];!e.test(q.toLowerCase())&&f._scriptPrefix&&(q=pc.path.join(f._scriptPrefix,q));this.loader.load(q,"script",k)}else b(null)},_parseScenes:function(a){if(a)for(var b=0;b<a.length;b++)this._sceneRegistry.add(a[b].name,
|
|
a[b].url)},_parseAssets:function(a){var b,c,d=[],e={},p={};if(pc.script.legacy){if(this.enableBundles)for(c in a)"bundle"===a[c].type&&(p[c]=!0,d.push(a[c]));for(c in a)p[c]||d.push(a[c])}else{for(b=0;b<this.scriptsOrder.length;b++)c=this.scriptsOrder[b],a[c]&&(e[c]=!0,d.push(a[c]));if(this.enableBundles)for(c in a)"bundle"===a[c].type&&(p[c]=!0,d.push(a[c]));for(c in a)e[c]||p[c]||d.push(a[c])}for(b=0;b<d.length;b++)a=d[b],c=new pc.Asset(a.name,a.type,a.file,a.data),c.id=parseInt(a.id,10),c.preload=
|
|
a.preload?a.preload:!1,c.tags.add(a.tags),this.assets.add(c)},_getScriptReferences:function(a){var b,c,d=[];a.settings.priority_scripts&&(d=a.settings.priority_scripts);var e=[],p={};for(b=0;b<d.length;b++)e.push(d[b]),p[d[b]]=!0;a=a.entities;for(c in a)if(a[c].components.script)for(d=a[c].components.script.scripts,b=0;b<d.length;b++)p[d[b].url]||(e.push(d[b].url),p[d[b].url]=!0);return e},start:function(){this.frame=0;this.fire("start",{timestamp:pc.now(),target:this});if(!this._librariesLoaded)this.onLibrariesLoaded();
|
|
pc.ComponentSystem.initialize(this.root);this.fire("initialize");pc.ComponentSystem.postInitialize(this.root);this.fire("postinitialize");this.tick()},update:function(a){this.frame++;this.graphicsDevice.updateClientRect();this.vr&&this.vr.poll();pc.script.legacy&&pc.ComponentSystem.fixedUpdate(1/60,this._inTools);pc.ComponentSystem.update(a,this._inTools);pc.ComponentSystem.postUpdate(a,this._inTools);this.fire("update",a);this.controller&&this.controller.update(a);this.mouse&&this.mouse.update(a);
|
|
this.keyboard&&this.keyboard.update(a);this.gamepads&&this.gamepads.update(a)},render:function(){this.fire("prerender");this.root.syncHierarchy();this.batcher.updateAll();pc._skipRenderCounter=0;this.renderer.renderComposition(this.scene.layers);this.fire("postrender")},_fillFrameStats:function(a,b,c){var d=this.stats.frame;d.dt=b;d.ms=c;a>d._timeToCountFrames?(d.fps=d._fpsAccum,d._fpsAccum=0,d._timeToCountFrames=a+1E3):d._fpsAccum++;d.cameras=this.renderer._camerasRendered;d.materials=this.renderer._materialSwitches;
|
|
d.shaders=this.graphicsDevice._shaderSwitchesPerFrame;d.shadowMapUpdates=this.renderer._shadowMapUpdates;d.shadowMapTime=this.renderer._shadowMapTime;d.depthMapTime=this.renderer._depthMapTime;d.forwardTime=this.renderer._forwardTime;a=this.graphicsDevice._primsPerFrame;d.triangles=a[pc.PRIMITIVE_TRIANGLES]/3+Math.max(a[pc.PRIMITIVE_TRISTRIP]-2,0)+Math.max(a[pc.PRIMITIVE_TRIFAN]-2,0);d.cullTime=this.renderer._cullTime;d.sortTime=this.renderer._sortTime;d.skinTime=this.renderer._skinTime;d.morphTime=
|
|
this.renderer._morphTime;d.instancingTime=this.renderer._instancingTime;for(b=d.otherPrimitives=0;b<a.length;b++)b<pc.PRIMITIVE_TRIANGLES&&(d.otherPrimitives+=a[b]),a[b]=0;this.renderer._camerasRendered=0;this.renderer._materialSwitches=0;this.renderer._shadowMapUpdates=0;this.graphicsDevice._shaderSwitchesPerFrame=0;this.renderer._cullTime=0;this.renderer._sortTime=0;this.renderer._skinTime=0;this.renderer._morphTime=0;this.renderer._instancingTime=0;this.renderer._shadowMapTime=0;this.renderer._depthMapTime=
|
|
0;this.renderer._forwardTime=0;d=this.stats.drawCalls;d.forward=this.renderer._forwardDrawCalls;d.culled=this.renderer._numDrawCallsCulled;d.depth=0;d.shadow=this.renderer._shadowDrawCalls;d.skinned=this.renderer._skinDrawCalls;d.immediate=0;d.instanced=0;d.removedByInstancing=0;d.total=this.graphicsDevice._drawCallsPerFrame;d.misc=d.total-(d.forward+d.shadow);this.renderer._depthDrawCalls=0;this.renderer._shadowDrawCalls=0;this.renderer._forwardDrawCalls=0;this.renderer._numDrawCallsCulled=0;this.renderer._skinDrawCalls=
|
|
0;this.renderer._immediateRendered=0;this.renderer._instancedDrawCalls=0;this.renderer._removedByInstancing=0;this.graphicsDevice._drawCallsPerFrame=0;this.stats.misc.renderTargetCreationTime=this.graphicsDevice.renderTargetCreationTime;d=this.stats.particles;d.updatesPerFrame=d._updatesPerFrame;d.frameTime=d._frameTime;d._updatesPerFrame=0;d._frameTime=0},setCanvasFillMode:function(a,b,c){this._fillMode=a;this.resizeCanvas(b,c)},setCanvasResolution:function(a,b,c){this._resolutionMode=a;a===pc.RESOLUTION_AUTO&&
|
|
void 0===b&&(b=this.graphicsDevice.canvas.clientWidth,c=this.graphicsDevice.canvas.clientHeight);this.graphicsDevice.resizeCanvas(b,c)},isFullscreen:function(){return!!document.fullscreenElement},enableFullscreen:function(a,b,c){a=a||this.graphicsDevice.canvas;var d=function(){b();document.removeEventListener("fullscreenchange",d)},f=function(){c();document.removeEventListener("fullscreenerror",f)};b&&document.addEventListener("fullscreenchange",d,!1);c&&document.addEventListener("fullscreenerror",
|
|
f,!1);a.requestFullscreen?a.requestFullscreen(Element.ALLOW_KEYBOARD_INPUT):c()},disableFullscreen:function(a){var b=function(){a();document.removeEventListener("fullscreenchange",b)};a&&document.addEventListener("fullscreenchange",b,!1);document.exitFullscreen()},isHidden:function(){return document[this._hiddenAttr]},onVisibilityChange:function(){this.isHidden()?this._audioManager.suspend():this._audioManager.resume()},resizeCanvas:function(a,b){if(this._allowResize){var c=window.innerWidth,d=window.innerHeight;
|
|
if(navigator.isCocoonJS)a=c,b=d,this.graphicsDevice.resizeCanvas(a,b);else{if(this._fillMode===pc.FILLMODE_KEEP_ASPECT){var f=this.graphicsDevice.canvas.width/this.graphicsDevice.canvas.height;f>c/d?(a=c,b=a/f):(b=d,a=b*f)}else this._fillMode===pc.FILLMODE_FILL_WINDOW&&(a=c,b=d);this.graphicsDevice.canvas.style.width=a+"px";this.graphicsDevice.canvas.style.height=b+"px";this._resolutionMode===pc.RESOLUTION_AUTO&&this.setCanvasResolution(pc.RESOLUTION_AUTO)}return{width:a,height:b}}},onLibrariesLoaded:function(){this._librariesLoaded=
|
|
!0;this.systems.rigidbody.onLibraryLoaded();this.systems.collision.onLibraryLoaded()},applySceneSettings:function(a){var b;this.systems.rigidbody&&"undefined"!==typeof Ammo&&(b=a.physics.gravity,this.systems.rigidbody.setGravity(b[0],b[1],b[2]));this.scene.applySettings(a);if(a.render.hasOwnProperty("skybox"))if(a.render.skybox)if(b=this.assets.get(a.render.skybox))this.setSkybox(b);else this.assets.once("add:"+a.render.skybox,this.setSkybox,this);else this.setSkybox(null)},setSkybox:function(a){a?
|
|
this._skyboxLast===a.id?0!==this.scene.skyboxMip||a.loadFaces?this._onSkyboxChange(a):this._skyboxLoad(a):(this._skyboxLast&&(this.assets.off("add:"+this._skyboxLast,this.setSkybox,this),this.assets.off("load:"+this._skyboxLast,this._onSkyboxChange,this),this.assets.off("remove:"+this._skyboxLast,this._skyboxRemove,this)),this._skyboxLast=a.id,this.assets.on("load:"+a.id,this._onSkyboxChange,this),this.assets.once("remove:"+a.id,this._skyboxRemove,this),a.resource&&this.scene.setSkybox(a.resources),
|
|
this._skyboxLoad(a)):this._skyboxLast&&this._skyboxRemove({id:this._skyboxLast})},_onVrChange:function(a){a?this.vr||(this.vr=new pc.VrManager(this)):this.vr&&(this.vr.destroy(),this.vr=null)},_onSkyboxChange:function(a){this.scene.setSkybox(a.resources)},_skyboxLoad:function(a){0===this.scene.skyboxMip&&(a.loadFaces=!0);this.assets.load(a);this._onSkyboxChange(a)},_skyboxRemove:function(a){this._skyboxLast&&(this.assets.off("add:"+a.id,this.setSkybox,this),this.assets.off("load:"+a.id,this._onSkyboxChange,
|
|
this),this.assets.off("remove:"+a.id,this._skyboxRemove,this),this.scene.setSkybox(null),this._skyboxLast=null)},_firstBake:function(){this.lightmapper.bake(null,this.scene.lightmapMode)},_firstBatch:function(){this.scene._needsStaticPrepare&&(this.renderer.prepareStaticMeshes(this.graphicsDevice,this.scene),this.scene._needsStaticPrepare=!1);this.batcher.generate()},destroy:function(){var a,b,c=this.graphicsDevice.canvas.id;this.off("librariesloaded");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.onVisibilityChange=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);var l=this.systems.list;a=0;for(b=l.length;a<b;a++)l[a].destroy();pc.ComponentSystem.destroy();b=this.assets.list();for(a=0;a<b.length;a++)b[a].unload(),b[a].off();this.assets.off();this.bundles.destroy();this.bundles=null;this.i18n.destroy();this.i18n=null;for(var h in this.loader.getHandler("script")._cache)a=
|
|
this.loader.getHandler("script")._cache[h],(b=a.parentNode)&&b.removeChild(a);this.loader.getHandler("script")._cache={};this.loader.destroy();this.loader=null;this.scene.destroy();this.scene=null;this.systems=[];this.context=null;this.scripts.destroy();this.scripts=null;this._sceneRegistry.destroy();this._sceneRegistry=null;this.lightmapper.destroy();this.lightmapper=null;this.batcher.destroyManager();this.batcher=null;this._entityIndex={};this.defaultLayerDepth.onPreRenderOpaque=null;this.defaultLayerDepth.onPostRenderOpaque=
|
|
null;this.defaultLayerDepth.onDisable=null;this.defaultLayerWorld=this.defaultLayerDepth=this.defaultLayerDepth.onEnable=null;pc.destroyPostEffectQuad();this.graphicsDevice.destroy();this.tick=this.renderer=this.graphicsDevice=null;this.off();this._audioManager&&(this._audioManager.destroy(),this._audioManager=null);pc.http=new pc.Http;pc.script.app=null;pc.ParticleEmitter.DEFAULT_PARAM_TEXTURE=null;e._applications[c]=null;e._currentApplication===this&&(e._currentApplication=null)}});var a={},c=function(b){return function(c){if(b.graphicsDevice){e._currentApplication=
|
|
b;pc.app=b;c=c||pc.now();var d;d=pc.math.clamp((c-(b._time||c))/1E3,0,b.maxDeltaTime);d*=b.timeScale;b._time=c;b.vr&&b.vr.display?b.vr.display.requestAnimationFrame(b.tick):window.requestAnimationFrame(b.tick);if(!b.graphicsDevice.contextLost){b.update(d);if(b.autoRender||b.renderNextFrame)b.render(),b.renderNextFrame=!1;a.timestamp=pc.now();a.target=b;b.fire("frameend",a);b.fire("frameEnd",a);b.vr&&b.vr.display&&b.vr.display.presenting&&b.vr.display.submitFrame()}}}};return{FILLMODE_NONE:"NONE",
|
|
FILLMODE_FILL_WINDOW:"FILL_WINDOW",FILLMODE_KEEP_ASPECT:"KEEP_ASPECT",RESOLUTION_AUTO:"AUTO",RESOLUTION_FIXED:"FIXED",Application:e}}());pc.ApplicationStats=function(e){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,_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.vram=e._vram;this.shaders=e._shaderStats;Object.defineProperty(this.vram,"totalUsed",{get:function(){return this.tex+this.vb+this.ib}});Object.defineProperty(this,"scene",{get:function(){return pc.Application._currentApplication.scene._stats}});Object.defineProperty(this,"lightmapper",{get:function(){return pc.Application._currentApplication.lightmapper._stats}});Object.defineProperty(this,"batcher",{get:function(){return pc.Application._currentApplication.batcher._stats}});
|
|
pc.events.attach(this)};Object.assign(pc,function(){var e=function(b){this._app=b;this._list=[];this._index={};this._urlIndex={}};e.prototype.destroy=function(){this._app=null};e.prototype.list=function(){return this._list};e.prototype.add=function(b,a){if(this._index.hasOwnProperty(b))return!1;var c=new pc.SceneRegistryItem(b,a),d=this._list.push(c);this._index[c.name]=d-1;this._urlIndex[c.url]=d-1;return!0};e.prototype.find=function(b){return this._index.hasOwnProperty(b)?this._list[this._index[b]]:null};e.prototype.findByUrl=
|
|
function(b){return this._urlIndex.hasOwnProperty(b)?this._list[this._urlIndex[b]]:null};e.prototype.remove=function(b){if(this._index.hasOwnProperty(b)){var a=this._index[b],c=this._list[a];delete this._urlIndex[c.url];delete this._index[b];this._list.splice(a,1);for(a=0;a<this._list.length;a++)c=this._list[a],this._index[c.name]=a,this._urlIndex[c.url]=a}};e.prototype.loadSceneHierarchy=function(b,a){var c=this,d=this._app.loader.getHandler("hierarchy");this._app.assets&&this._app.assets.prefix&&
|
|
!pc.ABSOLUTE_URL.test(b)&&(b=pc.path.join(this._app.assets.prefix,b));d.load(b,function(f,g){f?a&&a(f):c._app._preloadScripts(g,function(){c._app.systems.script.preloading=!0;var e=d.open(b,g);c._app.systems.script.preloading=!1;c._app.loader.clearCache(b,"hierarchy");c._app.root.addChild(e);pc.ComponentSystem.initialize(e);pc.ComponentSystem.postInitialize(e);a&&a(f,e)})})};e.prototype.loadSceneSettings=function(b,a){var c=this;this._app.assets&&this._app.assets.prefix&&!pc.ABSOLUTE_URL.test(b)&&
|
|
(b=pc.path.join(this._app.assets.prefix,b));this._app.loader.load(b,"scenesettings",function(b,f){b?a&&a(b):(c._app.applySceneSettings(f),a&&a(null))})};e.prototype.loadScene=function(b,a){var c=this,d=this._app.loader.getHandler("scene");this._app.assets&&this._app.assets.prefix&&!pc.ABSOLUTE_URL.test(b)&&(b=pc.path.join(this._app.assets.prefix,b));d.load(b,function(f,g){f?a&&a(f):c._app._preloadScripts(g,function(){c._app.systems.script.preloading=!0;var f=d.open(b,g);c._app.systems.script.preloading=
|
|
!1;c._app.loader.clearCache(b,"scene");c._app.loader.patch({resource:f,type:"scene"},c._app.assets);c._app.root.addChild(f.root);c._app.systems.rigidbody&&"undefined"!==typeof Ammo&&c._app.systems.rigidbody.setGravity(f._gravity.x,f._gravity.y,f._gravity.z);a&&a(null,f)})})};return{SceneRegistry:e,SceneRegistryItem:function(b,a){this.name=b;this.url=a}}}());Object.assign(pc,function(){var e=function(){this.list=[]};Object.assign(e.prototype,{add:function(b){var a=b.id;if(this[a])throw Error(pc.string.format("ComponentSystem name '{0}' already registered or not allowed",a));this[a]=b;this.list.push(b)},remove:function(b){b=b.id;if(!this[b])throw Error(pc.string.format("No ComponentSystem named '{0}' registered",b));delete this[b];b=this.list.indexOf(this[b]);-1!==b&&this.list.splice(b,1)}});return{ComponentSystemRegistry:e}}());Object.assign(pc,function(){function e(a,b){if(!a)return a;switch(b){case "rgb":return a instanceof pc.Color?a.clone():new pc.Color(a[0],a[1],a[2]);case "rgba":return a instanceof pc.Color?a.clone():new pc.Color(a[0],a[1],a[2],a[3]);case "vec2":return a instanceof pc.Vec2?a.clone():new pc.Vec2(a[0],a[1]);case "vec3":return a instanceof pc.Vec3?a.clone():new pc.Vec3(a[0],a[1],a[2]);case "vec4":return a instanceof pc.Vec4?a.clone():new pc.Vec4(a[0],a[1],a[2],a[3]);case "boolean":case "number":case "string":return a;
|
|
case "entity":return a;default:throw Error("Could not convert unhandled type: "+b);}}var b=function(a){this.app=a;this.store={};this.schema=[];pc.events.attach(this)};Object.assign(b,{_helper:function(a,b){for(var c=0,f=a.length;c<f;c++)a[c].f.call(a[c].s,b)},initialize:function(a){this._helper(this._init,a)},postInitialize:function(a){this._helper(this._postInit,a);this.fire("postinitialize",a)},update:function(a,b){this._helper(b?this._toolsUpdate:this._update,a)},fixedUpdate:function(a,b){this._helper(this._fixedUpdate,
|
|
a)},postUpdate:function(a,b){this._helper(this._postUpdate,a)},_init:[],_postInit:[],_toolsUpdate:[],_update:[],_fixedUpdate:[],_postUpdate:[],bind:function(a,b,d){switch(a){case "initialize":this._init.push({f:b,s:d});break;case "postInitialize":this._postInit.push({f:b,s:d});break;case "update":this._update.push({f:b,s:d});break;case "postUpdate":this._postUpdate.push({f:b,s:d});break;case "fixedUpdate":this._fixedUpdate.push({f:b,s:d});break;case "toolsUpdate":this._toolsUpdate.push({f:b,s:d});
|
|
break;default:console.error("Component System does not support event",a)}},_erase:function(a,b,d){for(var c=0;c<a.length;c++)a[c].f===b&&a[c].s===d&&a.splice(c--,1)},unbind:function(a,b,d){switch(a){case "initialize":this._erase(this._init,b,d);break;case "postInitialize":this._erase(this._postInit,b,d);break;case "update":this._erase(this._update,b,d);break;case "postUpdate":this._erase(this._postUpdate,b,d);break;case "fixedUpdate":this._erase(this._fixedUpdate,b,d);break;case "toolsUpdate":this._erase(this._toolsUpdate,
|
|
b,d);break;default:console.error("Component System does not support event",a)}}});b.prototype={addComponent:function(a,b){var c=new this.ComponentType(this,a),f=new this.DataType;b=b||{};this.store[a.getGuid()]={entity:a,data:f};a[this.id]=c;a.c[this.id]=c;this.initializeComponentData(c,b,[]);this.fire("add",a,c);return c},removeComponent:function(a){var b=this.store[a.getGuid()];this.fire("beforeremove",a,a.c[this.id]);delete this.store[a.getGuid()];delete a[this.id];delete a.c[this.id];this.fire("remove",
|
|
a,b.data)},cloneComponent:function(a,b){var c=this.store[a.getGuid()];return this.addComponent(b,c.data)},initializeComponentData:function(a,b,d){b=b||{};for(var c,g,l,h=0,p=d.length;h<p;h++)c=d[h],"object"===typeof c?(g=c.name,c=c.type):(g=c,c=void 0),l=b[g],void 0!==l?(void 0!==c&&(l=e(l,c)),a[g]=l):a[g]=a.data[g];if(a.enabled&&a.entity.enabled)a.onEnable()},getPropertiesOfType:function(a){var b=[];(this.schema||[]).forEach(function(c){c&&"object"===typeof c&&c.type===a&&b.push(c)});return b},destroy:function(){this.off()}};
|
|
pc.events.attach(b);b.destroy=function(){b.off("initialize");b.off("postInitialize");b.off("toolsUpdate");b.off("update");b.off("fixedUpdate");b.off("postUpdate")};return{ComponentSystem:b}}());Object.assign(pc,function(){var e=function(b,a){this.system=b;this.entity=a;pc.events.attach(this);this.system.schema&&!this._accessorsBuilt&&this.buildAccessors(this.system.schema);this.on("set",function(a,b,f){this.fire("set_"+a,a,b,f)});this.on("set_enabled",this.onSetEnabled,this)};e._buildAccessors=function(b,a){a.forEach(function(a){var c="object"===typeof a?a.name:a;Object.defineProperty(b,c,{get:function(){return this.data[c]},set:function(a){var b=this.data,d=b[c];b[c]=a;this.fire("set",
|
|
c,d,a)},configurable:!0})});b._accessorsBuilt=!0};e.prototype={buildAccessors:function(b){e._buildAccessors(this,b)},onSetEnabled:function(b,a,c){if(a!==c&&this.entity.enabled)if(c)this.onEnable();else this.onDisable()},onEnable:function(){},onDisable:function(){},onPostStateChange:function(){}};Object.defineProperty(e.prototype,"data",{get:function(){var b=this.system.store[this.entity.getGuid()];return b?b.data:null}});return{Component:e}}());Object.assign(pc,function(){return{ComponentData:function(){}}}());Object.assign(pc,function(){var e=function(b,a){pc.Component.call(this,b,a);this.animationsIndex={};this.on("set_animations",this.onSetAnimations,this);this.on("set_assets",this.onSetAssets,this);this.on("set_loop",this.onSetLoop,this)};e.prototype=Object.create(pc.Component.prototype);e.prototype.constructor=e;Object.assign(e.prototype,{play:function(b,a){if(!this.data.animations[b])console.error(pc.string.format("Trying to play animation '{0}' which doesn't exist",b));else if(this.enabled&&this.entity.enabled){a=
|
|
a||0;var c=this.data;c.prevAnim=c.currAnim;c.currAnim=b;c.model&&(c.blending=0<a&&c.prevAnim,c.blending?(c.blendTime=a,c.blendTimeRemaining=a,c.fromSkel.animation=c.animations[c.prevAnim],c.fromSkel.addTime(c.skeleton._time),c.toSkel.animation=c.animations[c.currAnim]):c.skeleton.animation=c.animations[c.currAnim]);c.playing=!0}},getAnimation:function(b){return this.data.animations[b]},setModel:function(b){var a=this.data;if(b){var c=b.getGraph();a.fromSkel=new pc.Skeleton(c);a.toSkel=new pc.Skeleton(c);
|
|
a.skeleton=new pc.Skeleton(c);a.skeleton.looping=a.loop;a.skeleton.setGraph(c)}a.model=b;a.animations&&a.currAnim&&a.animations[a.currAnim]&&this.play(a.currAnim)},loadAnimationAssets:function(b){if(b&&b.length){var a=this,c=this.system.app.assets,d,f=b.length,g=function(b){a.animations[b.name]=b.resource;a.animationsIndex[b.id]=b.name;a.animations=a.animations},e=function(b){b.off("change",a.onAssetChanged,a);b.on("change",a.onAssetChanged,a);b.off("remove",a.onAssetRemoved,a);b.on("remove",a.onAssetRemoved,
|
|
a);b.resource?g(b):(b.once("load",g,a),a.enabled&&a.entity.enabled&&c.load(b))};for(d=0;d<f;d++){var h=c.get(b[d]);if(h)e(h);else c.on("add:"+b[d],e)}}},onAssetChanged:function(b,a,c,d){"resource"===a&&(c?(this.animations[b.name]=c,this.animationsIndex[b.id]=b.name,this.data.currAnim===b.name&&this.data.playing&&this.data.enabled&&this.entity.enabled&&this.play(b.name,0)):(delete this.animations[b.name],delete this.animationsIndex[b.id]))},onAssetRemoved:function(b){b.off("remove",this.onAssetRemoved,
|
|
this);this.animations&&this.animations[b.name]&&(delete this.animations[b.name],delete this.animationsIndex[b.id],this.data.currAnim===b.name&&this._stopCurrentAnimation())},_stopCurrentAnimation:function(){this.data.currAnim=null;this.data.playing=!1;this.data.skeleton&&(this.data.skeleton.currentTime=0,this.data.skeleton.animation=null)},onSetAnimations:function(b,a,c){b=this.data;(a=this.entity.model)&&(a=a.model)&&a!==b.model&&this.entity.animation.setModel(a);if(!b.currAnim&&b.activate&&b.enabled&&
|
|
this.entity.enabled)for(var d in b.animations){this.play(d,0);break}},onSetAssets:function(b,a,c){if(a&&a.length)for(b=0;b<a.length;b++)if(a[b]){var d=this.system.app.assets.get(a[b]);if(d){d.off("change",this.onAssetChanged,this);d.off("remove",this.onAssetRemoved,this);var f=this.animationsIndex[d.id];this.data.currAnim===f&&this._stopCurrentAnimation();delete this.animations[f];delete this.animationsIndex[d.id]}}a=c.map(function(a){return a instanceof pc.Asset?a.id:a});this.loadAnimationAssets(a)},
|
|
onSetLoop:function(b,a,c){this.data.skeleton&&(this.data.skeleton.looping=this.data.loop)},onSetCurrentTime:function(b,a,c){this.data.skeleton.currentTime=c;this.data.skeleton.addTime(0);this.data.skeleton.updateGraph()},onEnable:function(){pc.Component.prototype.onEnable.call(this);var b=this.data.assets,a=this.system.app.assets;if(b)for(var c=0,d=b.length;c<d;c++){var f=b[c];f instanceof pc.Asset||(f=a.get(f));f&&!f.resource&&a.load(f)}if(this.data.activate&&!this.data.currAnim)for(var g in this.data.animations){this.play(g,
|
|
0);break}},onBeforeRemove:function(){for(var b=0;b<this.assets.length;b++){var a=this.system.app.assets.get(this.assets[b]);a&&(a.off("change",this.onAssetChanged,this),a.off("remove",this.onAssetRemoved,this))}delete this.data.animation;delete this.data.skeleton;delete this.data.fromSkel;delete this.data.toSkel}});Object.defineProperties(e.prototype,{currentTime:{get:function(){return this.data.skeleton._time},set:function(b){this.data.skeleton.currentTime=b;this.data.skeleton.addTime(0);this.data.skeleton.updateGraph()}},
|
|
duration:{get:function(){return this.data.animations[this.data.currAnim].duration}}});return{AnimationComponent:e}}());Object.assign(pc,function(){var e="enabled assets speed loop activate animations skeleton model prevAnim currAnim fromSkel toSkel blending blendTimeRemaining playing".split(" "),b=function(a){pc.ComponentSystem.call(this,a);this.id="animation";this.description="Specifies the animation assets that can run on the model specified by the Entity's model Component.";this.ComponentType=pc.AnimationComponent;this.DataType=pc.AnimationComponentData;this.schema=e;this.on("beforeremove",this.onBeforeRemove,
|
|
this);this.on("update",this.onUpdate,this);pc.ComponentSystem.bind("update",this.onUpdate,this)};b.prototype=Object.create(pc.ComponentSystem.prototype);b.prototype.constructor=b;pc.Component._buildAccessors(pc.AnimationComponent.prototype,e);Object.assign(b.prototype,{initializeComponentData:function(a,b,d){d=["activate","enabled","loop","speed","assets"];pc.ComponentSystem.prototype.initializeComponentData.call(this,a,b,d)},cloneComponent:function(a,b){var c;this.addComponent(b,{});b.animation.assets=
|
|
a.animation.assets.slice();b.animation.data.speed=a.animation.speed;b.animation.data.loop=a.animation.loop;b.animation.data.activate=a.animation.activate;b.animation.data.enabled=a.animation.enabled;var f={},g=a.animation.animations;for(c in g)g.hasOwnProperty(c)&&(f[c]=g[c]);b.animation.animations=f;f={};g=a.animation.animationsIndex;for(c in g)g.hasOwnProperty(c)&&(f[c]=g[c]);b.animation.animationsIndex=f},onBeforeRemove:function(a,b){b.onBeforeRemove()},onUpdate:function(a){var b=this.store,d;
|
|
for(d in b)if(b.hasOwnProperty(d)){var f=b[d],g=f.data;g.enabled&&g.playing&&f.entity.enabled&&(f=g.skeleton,null!==f&&null!==g.model&&(g.blending?(g.blendTimeRemaining-=a,0>g.blendTimeRemaining&&(g.blendTimeRemaining=0),f.blend(g.fromSkel,g.toSkel,1-g.blendTimeRemaining/g.blendTime)):(f.addTime(a*g.speed),f._time!==f._animation.duration||g.loop||(g.playing=!1)),g.blending&&0===g.blendTimeRemaining&&(g.blending=!1,f.animation=g.toSkel._animation),f.updateGraph()))}}});return{AnimationComponentSystem:b}}());Object.assign(pc,function(){return{AnimationComponentData:function(){this.assets=[];this.speed=1;this.enabled=this.activate=this.loop=!0;this.animations={};this.toSkel=this.fromSkel=this.currAnim=this.prevAnim=this.model=this.skeleton=null;this.blending=!1;this.blendTimeRemaining=this.blendTime=0;this.playing=!1}}}());Object.assign(pc,function(){var e=function(b,a){pc.Component.call(this,b,a);this._type="asset";this._model=this._asset=null;this._mapping={};this._receiveShadows=this._castShadows=!0;this._materialAsset=null;this._material=b.defaultMaterial;this._castShadowsLightmap=!0;this._lightmapped=!1;this._lightmapSizeMultiplier=1;this._isStatic=!1;this._layers=[pc.LAYERID_WORLD];this._batchGroupId=-1;this._area=null;this._assetOld=0;this._materialEvents=null;this._clonedModel=this._dirtyMaterialAsset=this._dirtyModelAsset=
|
|
!1};e.prototype=Object.create(pc.Component.prototype);e.prototype.constructor=e;Object.assign(e.prototype,{setVisible:function(b){console.warn("WARNING: setVisible: Function is deprecated. Set enabled property instead.");this.enabled=b},addModelToLayers:function(){for(var b,a=this.system.app.scene.layers,c=0;c<this._layers.length;c++)(b=a.getLayerById(this._layers[c]))&&b.addMeshInstances(this.meshInstances)},removeModelFromLayers:function(b){for(var a,c=this.system.app.scene.layers,d=0;d<this._layers.length;d++)(a=
|
|
c.getLayerById(this._layers[d]))&&a.removeMeshInstances(b.meshInstances)},onRemove:function(){this.materialAsset=this.asset=null;this._unsetMaterialEvents()},onLayersChanged:function(b,a){this.addModelToLayers();b.off("add",this.onLayerAdded,this);b.off("remove",this.onLayerRemoved,this);a.on("add",this.onLayerAdded,this);a.on("remove",this.onLayerRemoved,this)},onLayerAdded:function(b){0>this.layers.indexOf(b.id)||b.addMeshInstances(this.meshInstances)},onLayerRemoved:function(b){0>this.layers.indexOf(b.id)||
|
|
b.removeMeshInstances(this.meshInstances)},_setMaterialEvent:function(b,a,c,d){a=a+":"+c;this.system.app.assets.on(a,d,this);this._materialEvents||(this._materialEvents=[]);this._materialEvents[b]||(this._materialEvents[b]={});this._materialEvents[b][a]={id:c,handler:d}},_unsetMaterialEvents:function(){var b=this.system.app.assets,a=this._materialEvents;if(a){for(var c=0,d=a.length;c<d;c++)if(a[c]){var f=a[c],g;for(g in f)b.off(g,f[g].handler,this)}this._materialEvents=null}},_getAssetByIdOrPath:function(b){var a=
|
|
null;isNaN(parseInt(b,10))?this.asset&&(b=this._getMaterialAssetUrl(b))&&(a=this.system.app.assets.getByUrl(b)):a=this.system.app.assets.get(b);return a},_getMaterialAssetUrl:function(b){if(!this.asset)return null;var a=this.system.app.assets.get(this.asset);if(!a)return null;a=a.getFileUrl();a=pc.path.getDirectory(a);return pc.path.join(a,b)},_loadAndSetMeshInstanceMaterial:function(b,a,c){var d=this.system.app.assets;b&&b&&(b.resource?(a.material=b.resource,this._setMaterialEvent(c,"remove",b.id,
|
|
function(){a.material=this.system.defaultMaterial})):(this._setMaterialEvent(c,"load",b.id,function(d){a.material=d.resource;this._setMaterialEvent(c,"remove",b.id,function(){a.material=this.system.defaultMaterial})}),this.enabled&&this.entity.enabled&&d.load(b)))},onEnable:function(){var b=this.system.app,a=b.scene;a.on("set:layers",this.onLayersChanged,this);a.layers&&(a.layers.on("add",this.onLayerAdded,this),a.layers.on("remove",this.onLayerRemoved,this));var a="asset"===this._type,c;this._model?
|
|
this.addModelToLayers():a&&this._asset&&(c=b.assets.get(this._asset))&&c.resource!==this._model&&this._bindModelAsset(c);this._materialAsset&&(c=b.assets.get(this._materialAsset))&&c.resource!==this._material&&this._bindMaterialAsset(c);if(a&&this._mapping)for(var d in this._mapping)this._mapping[d]&&(c=this._getAssetByIdOrPath(this._mapping[d]))&&!c.resource&&b.assets.load(c);0<=this._batchGroupId&&b.batcher.insert(pc.BatchGroup.MODEL,this.batchGroupId,this.entity)},onDisable:function(){var b=this.system.app,
|
|
a=b.scene;a.off("set:layers",this.onLayersChanged,this);a.layers&&(a.layers.off("add",this.onLayerAdded,this),a.layers.off("remove",this.onLayerRemoved,this));0<=this._batchGroupId&&b.batcher.remove(pc.BatchGroup.MODEL,this.batchGroupId,this.entity);this._model&&this.removeModelFromLayers(this._model)},hide:function(){if(this._model){var b,a,c=this._model.meshInstances;b=0;for(a=c.length;b<a;b++)c[b].visible=!1}},show:function(){if(this._model){var b,a,c=this._model.meshInstances;b=0;for(a=c.length;b<
|
|
a;b++)c[b].visible=!0}},_bindMaterialAsset:function(b){b.on("load",this._onMaterialAssetLoad,this);b.on("unload",this._onMaterialAssetUnload,this);b.on("remove",this._onMaterialAssetRemove,this);b.on("change",this._onMaterialAssetChange,this);b.resource?this._onMaterialAssetLoad(b):this.enabled&&this.entity.enabled&&this.system.app.assets.load(b)},_unbindMaterialAsset:function(b){b.off("load",this._onMaterialAssetLoad,this);b.off("unload",this._onMaterialAssetUnload,this);b.off("remove",this._onMaterialAssetRemove,
|
|
this);b.off("change",this._onMaterialAssetChange,this)},_onMaterialAssetAdd:function(b){this.system.app.assets.off("add:"+b.id,this._onMaterialAssetAdd,this);this._materialAsset===b.id&&this._bindMaterialAsset(b)},_onMaterialAssetLoad:function(b){this.material=b.resource},_onMaterialAssetUnload:function(b){this.material=this.system.defaultMaterial},_onMaterialAssetRemove:function(b){this._onMaterialAssetUnload(b)},_onMaterialAssetChange:function(b){},_bindModelAsset:function(b){this._unbindModelAsset(b);
|
|
b.on("load",this._onModelAssetLoad,this);b.on("unload",this._onModelAssetUnload,this);b.on("change",this._onModelAssetChange,this);b.on("remove",this._onModelAssetRemove,this);b.resource?this._onModelAssetLoad(b):this.enabled&&this.entity.enabled&&this.system.app.assets.load(b)},_unbindModelAsset:function(b){b.off("load",this._onModelAssetLoad,this);b.off("unload",this._onModelAssetUnload,this);b.off("change",this._onModelAssetChange,this);b.off("remove",this._onModelAssetRemove,this)},_onModelAssetAdded:function(b){this.system.app.assets.off("add:"+
|
|
b.id,this._onModelAssetAdd,this);b.id===this._asset&&this._bindModelAsset(b)},_onModelAssetLoad:function(b){this.model=b.resource.clone();this._clonedModel=!0},_onModelAssetUnload:function(b){this.model=null},_onModelAssetChange:function(b,a,c,d){"data"===a&&(this.mapping=this._mapping)},_onModelAssetRemove:function(b){this.model=null}});Object.defineProperty(e.prototype,"meshInstances",{get:function(){return this._model?this._model.meshInstances:null},set:function(b){this._model&&(this._model.meshInstances=
|
|
b)}});Object.defineProperty(e.prototype,"type",{get:function(){return this._type},set:function(b){if(this._type!==b)if(this._area=null,this._type=b,"asset"===b)null!==this._asset?this._bindModelAsset(this._asset):this.model=null;else{var a=this.system,c=a.app.graphicsDevice;switch(b){case "box":a.box||(a.box=pc.createBox(c,{halfExtents:new pc.Vec3(.5,.5,.5)}));b=a.box;this._area={x:2,y:2,z:2,uv:2/3};break;case "capsule":a.capsule||(a.capsule=pc.createCapsule(c,{radius:.5,height:2}));b=a.capsule;this._area=
|
|
{x:2*Math.PI,y:Math.PI,z:2*Math.PI,uv:1/3+1/3/3*2};break;case "cone":a.cone||(a.cone=pc.createCone(c,{baseRadius:.5,peakRadius:0,height:1}));b=a.cone;this._area={x:2.54,y:2.54,z:2.54,uv:1/3+1/3/3};break;case "cylinder":a.cylinder||(a.cylinder=pc.createCylinder(c,{radius:.5,height:1}));b=a.cylinder;this._area={x:Math.PI,y:1.58,z:Math.PI,uv:1/3+1/3/3*2};break;case "plane":a.plane||(a.plane=pc.createPlane(c,{halfExtents:new pc.Vec2(.5,.5),widthSegments:1,lengthSegments:1}));b=a.plane;this._area={x:0,
|
|
y:1,z:0,uv:1};break;case "sphere":a.sphere||(a.sphere=pc.createSphere(c,{radius:.5}));b=a.sphere;this._area={x:Math.PI,y:Math.PI,z:Math.PI,uv:1};break;default:throw Error("Invalid model type: "+b);}var c=new pc.GraphNode,d=new pc.Model;d.graph=c;d.meshInstances=[new pc.MeshInstance(c,b,this._material)];a._inTools&&d.generateWireframe();this.model=d;this._asset=null}}});Object.defineProperty(e.prototype,"asset",{get:function(){return this._asset},set:function(b){var a=this.system.app.assets,c=b;b instanceof
|
|
pc.Asset&&(c=b.id);this._asset!==c&&(this._asset&&(a.off("add:"+this._asset,this._onModelAssetAdded,this),(b=a.get(this._asset))&&this._unbindModelAsset(b)),(this._asset=c)?(c=a.get(this._asset))?this._bindModelAsset(c):(this.model=null,a.on("add:"+this._asset,this._onModelAssetAdded,this)):this.model=null)}});Object.defineProperty(e.prototype,"model",{get:function(){return this._model},set:function(b){if(this._model!==b&&(this._model&&(this.removeModelFromLayers(this._model),this.entity.removeChild(this._model.getGraph()),
|
|
delete this._model._entity,this._clonedModel&&(this._model.destroy(),this._clonedModel=!1)),this._model=b)){b=this._model.meshInstances;for(var a=0;a<b.length;a++)b[a].castShadow=this._castShadows,b[a].receiveShadow=this._receiveShadows,b[a].isStatic=this._isStatic;this.lightmapped=this._lightmapped;this.entity.addChild(this._model.graph);this.enabled&&this.entity.enabled&&this.addModelToLayers();this._model._entity=this.entity;this.entity.animation&&this.entity.animation.setModel(this._model);"asset"===
|
|
this.type?this.mapping=this._mapping:this._unsetMaterialEvents()}}});Object.defineProperty(e.prototype,"lightmapped",{get:function(){return this._lightmapped},set:function(b){if(b!==this._lightmapped){var a,c;this._lightmapped=b;if(this._model){var d=this._model.meshInstances;if(b)for(b=0;b<d.length;b++)a=d[b],c=a.mask,a.mask=(c|pc.MASK_BAKED)&~(pc.MASK_DYNAMIC|pc.MASK_LIGHTMAP);else for(b=0;b<d.length;b++)a=d[b],a.deleteParameter("texture_lightMap"),a.deleteParameter("texture_dirLightMap"),a._shaderDefs&=
|
|
~pc.SHADERDEF_LM,c=a.mask,a.mask=(c|pc.MASK_DYNAMIC)&~(pc.MASK_BAKED|pc.MASK_LIGHTMAP)}}}});Object.defineProperty(e.prototype,"castShadows",{get:function(){return this._castShadows},set:function(b){if(this._castShadows!==b){var a,c,d=this._model;if(d){var f=this.layers,g=this.system.app.scene;if(this._castShadows&&!b)for(c=0;c<f.length;c++)(a=this.system.app.scene.layers.getLayerById(this.layers[c]))&&a.removeShadowCasters(d.meshInstances);a=d.meshInstances;for(c=0;c<a.length;c++)a[c].castShadow=
|
|
b;if(!this._castShadows&&b)for(c=0;c<f.length;c++)(a=g.layers.getLayerById(f[c]))&&a.addShadowCasters(d.meshInstances)}this._castShadows=b}}});Object.defineProperty(e.prototype,"receiveShadows",{get:function(){return this._receiveShadows},set:function(b){if(this._receiveShadows!==b&&(this._receiveShadows=b,this._model))for(var a=this._model.meshInstances,c=0,d=a.length;c<d;c++)a[c].receiveShadow=b}});Object.defineProperty(e.prototype,"castShadowsLightmap",{get:function(){return this._castShadowsLightmap},
|
|
set:function(b){this._castShadowsLightmap=b}});Object.defineProperty(e.prototype,"lightmapSizeMultiplier",{get:function(){return this._lightmapSizeMultiplier},set:function(b){this._lightmapSizeMultiplier=b}});Object.defineProperty(e.prototype,"isStatic",{get:function(){return this._isStatic},set:function(b){if(this._isStatic!==b){this._isStatic=b;var a,c;if(this._model){var d=this._model.meshInstances;for(a=0;a<d.length;a++)c=d[a],c.isStatic=b}}}});Object.defineProperty(e.prototype,"layers",{get:function(){return this._layers},
|
|
set:function(b){var a,c,d=this.system.app.scene.layers;if(this.meshInstances)for(a=0;a<this._layers.length;a++)(c=d.getLayerById(this._layers[a]))&&c.removeMeshInstances(this.meshInstances);for(a=this._layers.length=0;a<b.length;a++)this._layers[a]=b[a];if(this.enabled&&this.entity.enabled&&this.meshInstances)for(a=0;a<this._layers.length;a++)(c=d.getLayerById(this._layers[a]))&&c.addMeshInstances(this.meshInstances)}});Object.defineProperty(e.prototype,"batchGroupId",{get:function(){return this._batchGroupId},
|
|
set:function(b){if(this._batchGroupId!==b){var a=this.system.app.batcher;this.entity.enabled&&0<=this._batchGroupId&&a.remove(pc.BatchGroup.MODEL,this.batchGroupId,this.entity);this.entity.enabled&&0<=b&&a.insert(pc.BatchGroup.MODEL,b,this.entity);0>b&&0<=this._batchGroupId&&this.enabled&&this.entity.enabled&&this.addModelToLayers();this._batchGroupId=b}}});Object.defineProperty(e.prototype,"materialAsset",{get:function(){return this._materialAsset},set:function(b){var a=b;b instanceof pc.Asset&&
|
|
(a=b.id);b=this.system.app.assets;if(a!==this._materialAsset){if(this._materialAsset){b.off("add:"+this._materialAsset,this._onMaterialAdded,this);var c=b.get(this._materialAsset);c&&this._unbindMaterialAsset(c)}(this._materialAsset=a)?(a=b.get(this._materialAsset))?this._bindMaterialAsset(a):(this.material=this.system.defaultMaterial,b.on("add:"+this._materialAsset,this._onMaterialAdded,this)):this.material=this.system.defaultMaterial}}});Object.defineProperty(e.prototype,"material",{get:function(){return this._material},
|
|
set:function(b){if(this._material!==b){this._material=b;var a=this._model;if(a&&"asset"!==this._type)for(var a=a.meshInstances,c=0,d=a.length;c<d;c++)a[c].material=b}}});Object.defineProperty(e.prototype,"mapping",{get:function(){return this._mapping},set:function(b){if("asset"===this._type&&(this._unsetMaterialEvents(),b||(b={}),this._mapping=b,this._model))for(var a=this._model.meshInstances,c=this.asset?this.system.app.assets.get(this.asset):null,c=c?c.data.mapping:null,d=null,f=0,g=a.length;f<
|
|
g;f++)if(void 0!==b[f])b[f]?(d=this.system.app.assets.get(b[f]),this._loadAndSetMeshInstanceMaterial(d,a[f],f)):a[f].material=this.system.defaultMaterial;else if(c)if(c[f]&&(c[f].material||c[f].path)){if(void 0!==c[f].material)d=this.system.app.assets.get(c[f].material);else if(void 0!==c[f].path){var e=this._getMaterialAssetUrl(c[f].path);e&&(d=this.system.app.assets.getByUrl(e))}this._loadAndSetMeshInstanceMaterial(d,a[f],f)}else a[f].material=this.system.defaultMaterial}});return{ModelComponent:e}}());Object.assign(pc,function(){var e=["enabled"],b=function(a){pc.ComponentSystem.call(this,a);this.id="model";this.description="Renders a 3D model at the location of the Entity.";this.ComponentType=pc.ModelComponent;this.DataType=pc.ModelComponentData;this.schema=e;this.sphere=this.plane=this.cylinder=this.cone=this.capsule=this.box=null;this.defaultMaterial=a.scene.defaultMaterial;this.on("beforeremove",this.onRemove,this)};b.prototype=Object.create(pc.ComponentSystem.prototype);b.prototype.constructor=
|
|
b;pc.Component._buildAccessors(pc.ModelComponent.prototype,e);Object.assign(b.prototype,{initializeComponentData:function(a,b,d){d="material materialAsset asset castShadows receiveShadows castShadowsLightmap lightmapped lightmapSizeMultiplier type mapping layers isStatic batchGroupId".split(" ");if(null===b.batchGroupId||void 0===b.batchGroupId)b.batchGroupId=-1;b.layers&&b.layers.length&&(b.layers=b.layers.slice(0));for(var c=0;c<d.length;c++)b.hasOwnProperty(d[c])&&(a[d[c]]=b[d[c]]);pc.ComponentSystem.prototype.initializeComponentData.call(this,
|
|
a,b,["enabled"])},cloneComponent:function(a,b){var c={type:a.model.type,asset:a.model.asset,castShadows:a.model.castShadows,receiveShadows:a.model.receiveShadows,castShadowsLightmap:a.model.castShadowsLightmap,lightmapped:a.model.lightmapped,lightmapSizeMultiplier:a.model.lightmapSizeMultiplier,isStatic:a.model.isStatic,enabled:a.model.enabled,layers:a.model.layers,batchGroupId:a.model.batchGroupId,mapping:pc.extend({},a.model.mapping)},f=a.model.materialAsset;f instanceof pc.Asset||null==f||(f=this.app.assets.get(f));
|
|
var g=a.model.material;g&&g!==this.defaultMaterial&&f&&g!==f.resource||(c.materialAsset=f);f=this.addComponent(b,c);a.model.model&&"asset"===a.model.type&&!a.model.asset&&(f.model=a.model.model.clone(),f._clonedModel=!0);c.materialAsset||(f.material=g);if(a.model.model)for(c=a.model.model.meshInstances,g=f.model.meshInstances,f=0;f<c.length;f++)g[f].mask=c[f].mask,g[f].material=c[f].material,g[f].layer=c[f].layer,g[f].receiveShadow=c[f].receiveShadow},onRemove:function(a,b){b.onRemove()}});return{ModelComponentSystem:b}}());Object.assign(pc,function(){return{ModelComponentData:function(){this.enabled=!0}}}());Object.assign(pc,function(){var e=function(b,a){pc.Component.call(this,b,a);this.on("set_aspectRatioMode",this.onSetAspectRatioMode,this);this.on("set_aspectRatio",this.onSetAspectRatio,this);this.on("set_camera",this.onSetCamera,this);this.on("set_clearColor",this.onSetClearColor,this);this.on("set_fov",this.onSetFov,this);this.on("set_orthoHeight",this.onSetOrthoHeight,this);this.on("set_nearClip",this.onSetNearClip,this);this.on("set_farClip",this.onSetFarClip,this);this.on("set_projection",this.onSetProjection,
|
|
this);this.on("set_priority",this.onSetPriority,this);this.on("set_clearColorBuffer",this.updateClearFlags,this);this.on("set_clearDepthBuffer",this.updateClearFlags,this);this.on("set_clearStencilBuffer",this.updateClearFlags,this);this.on("set_renderTarget",this.onSetRenderTarget,this);this.on("set_rect",this.onSetRect,this);this.on("set_scissorRect",this.onSetScissorRect,this);this.on("set_horizontalFov",this.onSetHorizontalFov,this);this.on("set_frustumCulling",this.onSetFrustumCulling,this);
|
|
this.on("set_calculateTransform",this.onSetCalculateTransform,this);this.on("set_calculateProjection",this.onSetCalculateProjection,this);this.on("set_cullFaces",this.onSetCullFaces,this);this.on("set_flipFaces",this.onSetFlipFaces,this);this.on("set_layers",this.onSetLayers,this)};e.prototype=Object.create(pc.Component.prototype);e.prototype.constructor=e;Object.defineProperty(e.prototype,"projectionMatrix",{get:function(){return this.data.camera.getProjectionMatrix()}});Object.defineProperty(e.prototype,
|
|
"viewMatrix",{get:function(){return this.data.camera.getViewMatrix()}});Object.defineProperty(e.prototype,"frustum",{get:function(){return this.data.camera.frustum}});Object.defineProperty(e.prototype,"vrDisplay",{get:function(){return this.data.camera.vrDisplay},set:function(b){if(this.data.camera.vrDisplay=b)b._camera=this.data.camera}});Object.defineProperty(e.prototype,"node",{get:function(){return this.data.camera._node}});Object.assign(e.prototype,{screenToWorld:function(b,a,c,d){var f=this.system.app.graphicsDevice;
|
|
return this.data.camera.screenToWorld(b,a,c,f.clientRect.width,f.clientRect.height,d)},onPrerender:function(){this.data.camera._viewMatDirty=!0;this.data.camera._viewProjMatDirty=!0},worldToScreen:function(b,a){var c=this.system.app.graphicsDevice;return this.data.camera.worldToScreen(b,c.clientRect.width,c.clientRect.height,a)},onSetAspectRatioMode:function(b,a,c){this.data.camera.aspectRatioMode=c},onSetAspectRatio:function(b,a,c){this.data.camera.aspectRatio=c},onSetCamera:function(b,a,c){a&&(a._node=
|
|
null);c._node=this.entity},onSetClearColor:function(b,a,c){b=this.data.camera.clearColor;b[0]=c.r;b[1]=c.g;b[2]=c.b;b[3]=c.a},onSetFov:function(b,a,c){this.data.camera.fov=c},onSetOrthoHeight:function(b,a,c){this.data.camera.orthoHeight=c},onSetNearClip:function(b,a,c){this.data.camera.nearClip=c},onSetFarClip:function(b,a,c){this.data.camera.farClip=c},onSetHorizontalFov:function(b,a,c){this.data.camera.horizontalFov=c},onSetFrustumCulling:function(b,a,c){this.data.camera.frustumCulling=c},onSetCalculateTransform:function(b,
|
|
a,c){this._calculateTransform=c;this.camera.overrideCalculateTransform=!!c},onSetCalculateProjection:function(b,a,c){this._calculateProjection=c;this.camera._projMatDirty=!0;this.camera.overrideCalculateProjection=!!c},onSetCullFaces:function(b,a,c){this.camera._cullFaces=c},onSetFlipFaces:function(b,a,c){this.camera._flipFaces=c},onSetProjection:function(b,a,c){this.data.camera.projection=c},onSetPriority:function(b,a,c){for(a=0;a<this.layers.length;a++)(b=this.system.app.scene.layers.getLayerById(this.layers[a]))&&
|
|
b._sortCameras()},onSetLayers:function(b,a,c){var d;for(b=0;b<a.length;b++)(d=this.system.app.scene.layers.getLayerById(a[b]))&&d.removeCamera(this);if(this.enabled&&this.entity.enabled)for(b=0;b<c.length;b++)(d=this.system.app.scene.layers.getLayerById(c[b]))&&d.addCamera(this)},addCameraToLayers:function(){for(var b,a=0;a<this.layers.length;a++)(b=this.system.app.scene.layers.getLayerById(this.layers[a]))&&b.addCamera(this)},removeCameraFromLayers:function(){for(var b,a=0;a<this.layers.length;a++)(b=
|
|
this.system.app.scene.layers.getLayerById(this.layers[a]))&&b.removeCamera(this)},onLayersChanged:function(b,a){this.addCameraToLayers();b.off("add",this.onLayerAdded,this);b.off("remove",this.onLayerRemoved,this);a.on("add",this.onLayerAdded,this);a.on("remove",this.onLayerRemoved,this)},onLayerAdded:function(b){0>this.layers.indexOf(b.id)||b.addCamera(this)},onLayerRemoved:function(b){0>this.layers.indexOf(b.id)||b.removeCamera(this)},updateClearFlags:function(){var b=0;this.clearColorBuffer&&(b|=
|
|
pc.CLEARFLAG_COLOR);this.clearDepthBuffer&&(b|=pc.CLEARFLAG_DEPTH);this.clearStencilBuffer&&(b|=pc.CLEARFLAG_STENCIL);this.data.camera.clearFlags=b},onSetRenderTarget:function(b,a,c){this.data.camera.renderTarget=c},onSetRect:function(b,a,c){this.data.camera.setRect(c.x,c.y,c.z,c.w)},onSetScissorRect:function(b,a,c){this.data.camera.setScissorRect(c.x,c.y,c.z,c.w)},onEnable:function(){this.system.addCamera(this);this.system.app.scene.on("set:layers",this.onLayersChanged,this);this.system.app.scene.layers&&
|
|
(this.system.app.scene.layers.on("add",this.onLayerAdded,this),this.system.app.scene.layers.on("remove",this.onLayerRemoved,this));this.enabled&&this.entity.enabled&&this.addCameraToLayers();this.postEffects.enable()},onDisable:function(){this.postEffects.disable();this.removeCameraFromLayers();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.system.removeCamera(this)},onRemove:function(){this.off()},calculateAspectRatio:function(b){b=b?b:this.system.app.graphicsDevice;var a=this.rect;return b.width*a.z/(b.height*a.w)},frameBegin:function(b){this.aspectRatioMode===pc.ASPECT_AUTO&&(this.aspectRatio=this.calculateAspectRatio(b));this.data.isRendering=!0},frameEnd:function(){this.data.isRendering=!1},enterVr:function(b,a){b instanceof Function&&!a&&(a=b,b=null);if(this.system.app.vr)if(b||(b=this.system.app.vr.display),b){var c=
|
|
this;b.capabilities.canPresent?b.requestPresent(function(d){d||(c.vrDisplay=b,c.vrDisplay.once("beforepresentchange",function(a){a.presenting||(c.vrDisplay=null)}));a(d)}):(c.vrDisplay=b,a())}else a("No pc.VrDisplay to present");else a("VrManager not created. Enable VR in project settings.")},exitVr:function(b){if(this.vrDisplay)if(this.vrDisplay.capabilities.canPresent){var a=this.vrDisplay;this.vrDisplay=null;a.exitPresent(b)}else this.vrDisplay=null,b();else b("Not presenting VR")}});return{CameraComponent:e}}());Object.assign(pc,function(){var e="enabled clearColorBuffer clearColor clearDepthBuffer clearStencilBuffer frustumCulling projection fov orthoHeight nearClip farClip priority rect scissorRect camera aspectRatio aspectRatioMode horizontalFov model renderTarget calculateTransform calculateProjection cullFaces flipFaces layers".split(" "),b=function(a){pc.ComponentSystem.call(this,a);this.id="camera";this.description="Renders the scene from the location of the Entity.";this.ComponentType=pc.CameraComponent;
|
|
this.DataType=pc.CameraComponentData;this.schema=e;this.cameras=[];this.on("beforeremove",this.onBeforeRemove,this);this.on("remove",this.onRemove,this);this.app.on("prerender",this.onPrerender,this);pc.ComponentSystem.bind("update",this.onUpdate,this)};b.prototype=Object.create(pc.ComponentSystem.prototype);b.prototype.constructor=b;pc.Component._buildAccessors(pc.CameraComponent.prototype,e);Object.assign(b.prototype,{initializeComponentData:function(a,b,d){d="postEffects enabled model camera aspectRatio aspectRatioMode horizontalFov renderTarget clearColor fov orthoHeight nearClip farClip projection priority clearColorBuffer clearDepthBuffer clearStencilBuffer frustumCulling rect scissorRect calculateTransform calculateProjection cullFaces flipFaces layers".split(" ");
|
|
for(var c={},g=0,e=d.length;g<e;g++){var h=d[g];c[h]=b[h]}c.layers&&"array"===pc.type(c.layers)&&(c.layers=c.layers.slice(0));c.clearColor&&"array"===pc.type(c.clearColor)&&(b=c.clearColor,c.clearColor=new pc.Color(b[0],b[1],b[2],b[3]));c.rect&&"array"===pc.type(c.rect)&&(b=c.rect,c.rect=new pc.Vec4(b[0],b[1],b[2],b[3]));c.scissorRect&&"array"===pc.type(c.scissorRect)&&(b=c.scissorRect,c.scissorRect=new pc.Vec4(b[0],b[1],b[2],b[3]));c.activate&&(console.warn("WARNING: activate: Property is deprecated. Set enabled property instead."),
|
|
c.enabled=c.activate);c.camera=new pc.Camera;c._node=a.entity;c.camera._component=a;c.camera.calculateTransform=function(b,c){return a._calculateTransform?a._calculateTransform(b,c):null};c.camera.calculateProjection=function(b,c){return a._calculateProjection?a._calculateProjection(b,c):null};c.postEffects=new pc.PostEffectQueue(this.app,a);pc.ComponentSystem.prototype.initializeComponentData.call(this,a,c,d)},onBeforeRemove:function(a,b){this.removeCamera(b);b.onRemove()},onRemove:function(a,b){b.camera=
|
|
null},onUpdate:function(a){a=this.store;var b,d,f,g;if(this.app.vr)for(var e in a)b=a[e],d=b.data,f=d.camera,g=f.vrDisplay,d.enabled&&b.entity.enabled&&g&&(g.setClipPlanes(f._nearClip,f._farClip),f._node&&(f._node.localTransform.copy(g.combinedViewInv),f._node._dirtyLocal=!1,f._node._dirtifyWorld()))},onPrerender:function(){for(var a=0,b=this.cameras.length;a<b;a++)this.cameras[a].onPrerender()},addCamera:function(a){this.cameras.push(a);this.sortCamerasByPriority()},removeCamera:function(a){a=this.cameras.indexOf(a);
|
|
0<=a&&(this.cameras.splice(a,1),this.sortCamerasByPriority())},sortCamerasByPriority:function(){this.cameras.sort(function(a,b){return a.priority-b.priority})}});return{CameraComponentSystem:b}}());Object.assign(pc,function(){return{CameraComponentData:function(){this.clearColor=new pc.Color(.722,.722,.722,1);this.clearStencilBuffer=this.clearDepthBuffer=this.clearColorBuffer=!0;this.nearClip=.1;this.farClip=1E3;this.fov=45;this.orthoHeight=100;this.projection=pc.PROJECTION_PERSPECTIVE;this.priority=0;this.rect=new pc.Vec4(0,0,1,1);this.scissorRect=new pc.Vec4(0,0,1,1);this.enabled=!0;this.frustumCulling=!1;this.cullFaces=!0;this.flipFaces=!1;this.layers=[pc.LAYERID_WORLD,pc.LAYERID_DEPTH,pc.LAYERID_SKYBOX,
|
|
pc.LAYERID_UI,pc.LAYERID_IMMEDIATE];this.camera=null;this.aspectRatio=16/9;this.aspectRatioMode=pc.ASPECT_AUTO;this.postEffects=this.renderTarget=null;this.isRendering=!1;this.calculateProjection=this.calculateTransform=null}}}());Object.assign(pc,function(){function e(a,b){var c=this;this.app=a;this.camera=b;this.effects=[];this.enabled=!1;this.depthTarget=null;this.renderTargetScale=1;this.resizeTimeout=null;this.resizeLast=0;this._resizeTimeoutCallback=function(){c.resizeRenderTargets()};b.on("set_rect",this.onCameraRectChanged,this);this._origStencilColorBuffer=this._origDepthColorBuffer=this._origClearColorBuffer=this._origOverrideClear=!1}var b;Object.assign(e.prototype,{_createOffscreenTarget:function(a,b){var c=this.camera.rect,
|
|
f=Math.floor(c.z*this.app.graphicsDevice.width*this.renderTargetScale),g=Math.floor(c.w*this.app.graphicsDevice.height*this.renderTargetScale),e=this.app.graphicsDevice,h=b?e.getHdrFormat():pc.PIXELFORMAT_R8_G8_B8_A8,c=this.app.graphicsDevice.supportsStencil,f=new pc.Texture(e,{format:h,width:f,height:g});f.name="posteffect #"+this.effects.length;f.minFilter=pc.FILTER_NEAREST;f.magFilter=pc.FILTER_NEAREST;f.addressU=pc.ADDRESS_CLAMP_TO_EDGE;f.addressV=pc.ADDRESS_CLAMP_TO_EDGE;return new pc.RenderTarget(this.app.graphicsDevice,
|
|
f,{depth:a,stencil:c})},_resizeOffscreenTarget:function(a){var b=this.camera.rect,d=Math.floor(b.z*this.app.graphicsDevice.width*this.renderTargetScale),b=Math.floor(b.w*this.app.graphicsDevice.height*this.renderTargetScale),f=this.app.graphicsDevice,g=a.colorBuffer.format;a._colorBuffer.destroy();d=new pc.Texture(f,{format:g,width:d,height:b});d.name="posteffect";d.minFilter=pc.FILTER_NEAREST;d.magFilter=pc.FILTER_NEAREST;d.addressU=pc.ADDRESS_CLAMP_TO_EDGE;d.addressV=pc.ADDRESS_CLAMP_TO_EDGE;a._colorBuffer=
|
|
d;a.destroy()},_destroyOffscreenTarget:function(a){a._colorBuffer&&a._colorBuffer.destroy();a._depthBuffer&&a._depthBuffer.destroy();a.destroy()},setRenderTargetScale:function(a){this.renderTargetScale=a;this.resizeRenderTargets()},addEffect:function(a){var b=this.effects,d={effect:a,inputTarget:this._createOffscreenTarget(0===this.effects.length,a.hdr),outputTarget:null};if(!this.layer){this.layer=new pc.Layer({opaqueSortMode:pc.SORTMODE_NONE,transparentSortMode:pc.SORTMODE_NONE,passThrough:!0,name:"PostEffectQueue",
|
|
renderTarget:this.camera.renderTarget,clear:!1,onPostRender:function(){for(var a=0;a<this._commandList.length;a++)this._commandList[a]()}});var f=this.app.scene.layers.layerList,g=0,e,h=f.length-1;for(e=h;0<=e;e--)if(f[e].id===pc.LAYERID_UI){h=e-1;this._origOverrideClear=f[e].overrideClear;this._origClearColorBuffer=f[e].clearColorBuffer;this._origDepthColorBuffer=f[e].clearDepthBuffer;this._origStencilColorBuffer=f[e].clearStencilBuffer;f[e].overrideClear=!0;f[e].clearColorBuffer=!1;f[e].clearDepthBuffer=
|
|
this.camera.clearDepthBuffer;f[e].clearStencilBuffer=this.camera.clearStencilBuffer;break}this._sourceLayers=[];for(e=0;e<this.camera.layers.length;e++){var f=this.camera.layers[e],p=this.app.scene.layers.getLayerById(f),k=this.app.scene.layers.layerList.indexOf(p);k<=h&&(f!=pc.LAYERID_DEPTH&&(p.renderTarget=d.inputTarget,this._sourceLayers.push(p)),k>g&&(g=k))}this.app.scene.layers.insertOpaque(this.layer,g+1);this._sourceTarget=d.inputTarget;this.layer._commandList=[];this.layer.isPostEffect=!0}b.push(d);
|
|
g=b.length;1<g&&(b[g-2].outputTarget=d.inputTarget);this._newPostEffect=a;a.needsDepthBuffer&&this._requestDepthMap();this.enable();this._newPostEffect=void 0},removeEffect:function(a){var b,d,f=-1;b=0;for(d=this.effects.length;b<d;b++)if(this.effects[b].effect===a){f=b;break}if(0<=f){if(0<f)this.effects[f-1].outputTarget=f+1<this.effects.length?this.effects[f+1].inputTarget:null;else if(1<this.effects.length)for(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),b=0;b<this._sourceLayers.length;b++)this._sourceLayers[b].renderTarget=this.effects[1].inputTarget;this._destroyOffscreenTarget(this.effects[f].inputTarget);this.effects.splice(f,1)}this.enabled&&a.needsDepthBuffer&&this._releaseDepthMap();0===this.effects.length&&this.disable()},_requestDepthMaps:function(){for(var a=0,b=this.effects.length;a<b;a++){var d=this.effects[a].effect;
|
|
this._newPostEffect!==d&&d.needsDepthBuffer&&this._requestDepthMap()}},_releaseDepthMaps:function(){for(var a=0,b=this.effects.length;a<b;a++)this.effects[a].effect.needsDepthBuffer&&this._releaseDepthMap()},_requestDepthMap:function(){b||(b=this.app.scene.layers.getLayerById(pc.LAYERID_DEPTH));b&&b.incrementCounter()},_releaseDepthMap:function(){b&&b.decrementCounter()},destroy:function(){for(var a=0,b=this.effects.length;a<b;a++)this.effects[a].inputTarget.destroy();this.effects.length=0;this.disable()},
|
|
enable:function(){if(!this.enabled&&this.effects.length){this.enabled=!0;var a=this;this._requestDepthMaps();this.app.graphicsDevice.on("resizecanvas",this._onCanvasResized,this);this.command=function(){if(a.enabled){var b=null,d=a.effects.length;if(d){a.layer.renderTarget=a.effects[0].inputTarget;for(var f=0;f<d;f++){var g=a.effects[f];f===d-1&&(b=a.camera.rect);g.effect.render(g.inputTarget,g.outputTarget,b)}}}};this.layer._commandList.push(this.command)}},disable:function(){if(this.enabled){this.enabled=
|
|
!1;this.app.graphicsDevice.off("resizecanvas",this._onCanvasResized,this);this._releaseDepthMaps();this._destroyOffscreenTarget(this._sourceTarget);var a=this.layer._commandList.indexOf(this.command);0<=a&&this.layer._commandList.splice(a,1);for(var b=this.app.scene.layers.layerList,d=b.length-1,a=0;a<=b.length;a++)if(b[a].id===pc.LAYERID_UI){d=a-1;b[a].overrideClear=this._origOverrideClear;b[a].clearColorBuffer=this._origClearColorBuffer;b[a].clearDepthBuffer=this._origDepthColorBuffer;b[a].clearStencilBuffer=
|
|
this._origStencilColorBuffer;break}for(a=d;0<=a;a--)0<=b[a].cameras.indexOf(this.camera)&&(b[a].renderTarget=void 0);this.app.scene.layers.removeOpaque(this.layer);this.layer=null}},_onCanvasResized:function(a,b){var c=this.camera.rect,f=this.app.graphicsDevice;this.camera.camera.aspectRatio=f.width*c.z/(f.height*c.w);this.resizeTimeout||(100<pc.now()-this.resizeLast?this.resizeRenderTargets():this.resizeTimeout=setTimeout(this._resizeTimeoutCallback,100))},resizeRenderTargets:function(){this.resizeTimeout&&
|
|
(clearTimeout(this.resizeTimeout),this.resizeTimeout=null);this.resizeLast=pc.now();for(var a=this.camera.rect,b=Math.floor(a.z*this.app.graphicsDevice.width*this.renderTargetScale),a=Math.floor(a.w*this.app.graphicsDevice.height*this.renderTargetScale),d=this.effects,f=0,g=d.length;f<g;f++){var e=d[f];e.inputTarget.width===b&&e.inputTarget.height===a||this._resizeOffscreenTarget(e.inputTarget)}},onCameraRectChanged:function(a,b,d){this.enabled&&this.resizeRenderTargets()}});return{PostEffectQueue:e}}());Object.assign(pc,function(){function e(e,k){this.app=e;this.srcRenderTarget=k.srcRenderTarget;this.hdr=k.hdr;this.blending=k.blending;this.shader=k.shader;this.setup=k.setup;var n=this,q=e.graphicsDevice;this.layer=new pc.Layer({opaqueSortMode:pc.SORTMODE_NONE,transparentSortMode:pc.SORTMODE_NONE,passThrough:!0,name:k.name,onPostRender:function(){n.srcRenderTarget?(d.x=n.srcRenderTarget.width,d.y=n.srcRenderTarget.height,d.z=1/n.srcRenderTarget.width,d.w=1/n.srcRenderTarget.height):(d.x=q.width,d.y=
|
|
q.height,d.z=1/q.width,d.w=1/q.height);f[0]=d.x;f[1]=d.y;f[2]=d.z;f[3]=d.w;c.setValue(f);if(this._postEffectCombined&&0>this._postEffectCombined)n.setup&&n.setup(q,n,d,null,this.renderTarget);else{var g;g=this._postEffectCombinedSrc?this._postEffectCombinedSrc:n.srcRenderTarget?n.srcRenderTarget:b[this._backbufferRtId];1<g._samples&&g.resolve(!0,!1);var h=g._colorBuffer;h.magFilter=(this._postEffectCombinedShader?this._postEffectCombinedBilinear:this.postEffectBilinear)?pc.FILTER_LINEAR:pc.FILTER_NEAREST;
|
|
a.setValue(h);n.setup&&n.setup(q,n,d,g,this.renderTarget);(g=this._postEffectCombinedShader?this._postEffectCombinedShader:this.shader)&&pc.drawQuadWithShader(q,this.renderTarget,g,null,null,n.blending);if(!n.srcRenderTarget)for(g=e.scene.layers.layerList,h=0;h<g.length&&g[h]!==n.layer;h++)if(g[h].renderTarget===b[0]||g[h].renderTarget===b[1])g[h].renderTarget=null}}});this.layer._generateCameraHash();this.layer.isPostEffect=!0;this.layer.unmodifiedUvs=k.unmodifiedUvs;this.layer.postEffectBilinear=
|
|
k.bilinear;this.layer.postEffect=this;this.layer.shader=k.shader;this.layer.renderTarget=k.destRenderTarget;if(!a){a=q.scope.resolve("uColorBuffer");c=q.scope.resolve("uScreenSize");for(var H=q.supportsMsaa?4:1,G=0;2>G;G++)b[G]=new pc.RenderTarget({depth:!0,stencil:q.supportsStencil,samples:H,autoResolve:!1}),b[G].name="backbuffer"+G;e.on("prerender",function(){var a=e.scene.layers.layerList,c,d,f=0,k=0;p=h=l=!1;var n=pc.PIXELFORMAT_R8_G8_B8_A8;if(e.scene.layers._dirty){var C=0,E,H;for(c=0;c<a.length;c++){d=
|
|
!1;var G;if((G=a[c].isPostEffect)&&!(G=0===C)&&(G=a[c].unmodifiedUvs&&a[c].shader)){a:{var K,N,ba,R;E=a;H=g;var ca=C,S=I(a[c].shader.definition.fshader);if(0!==S.length)for(R=0;R<ca;R++)for(ba=0;ba<S.length;ba++)for(G=S[ba],K=I(E[H[R]].shader.definition.fshader),N=0;N<K.length;N++)if(K[N]===G){G=!0;break a}G=!1}G=!G}G?(g[C]=c,C++,c===a.length-1&&(d=!0)):0<C&&(d=!0);if(d){if(1<C){G="post_";for(d=0;d<C;d++)K=a[g[d]],G+=K.name?K.name:K.id,d<C-1&&(G+="_");K=q.programLib._cache[G];if(!K){N="vec4 shaderOutput;\n";
|
|
ba="void main() {\n";R=[];for(d=0;d<C;d++){K=a[g[d]].shader.definition.fshader+"\n";K=K.replace(x,"//").replace(v,"//").replace(w,"//").replace(y,"shaderOutput");0<d&&(K=K.replace(D,"//").replace(B,"//").replace(z,"shaderOutput;//"));K=K.replace(A,"void main"+d);var W,da,ea,S=K;H=R;da=S.length;var fa=0,Z=W=0,ca="";for(E=0;E<da;E++)ea=S.charAt(E),"{"===ea?(0===W&&(fa=E),W++):"}"===ea&&(1===W&&(ea=E,ca+=S.substr(Z,fa-Z+1),Z=ea),W--);ca+=S.substr(Z,S.length-Z+1);fa=null;Z=ca.match(m)||[];for(E=0;E<Z.length;E++)for(S=
|
|
Z[E].split(","),da=0;da<S.length;da++)W=S[da].replace(r,"").trim(),0<=H.indexOf(W)?(fa||(fa=[]),fa.push(W)):H.push(W);ca=ca.match(t)||[];for(E=0;E<ca.length;E++)for(S=ca[E].split(","),da=0;da<S.length;da++)W=S[da].replace(u,"").trim(),W=H.indexOf(W),0<=W&&H.splice(W,1);if(E=fa)for(H=0;H<E.length;H++)K=K.replace(new RegExp("\\b"+E[H]+"\\b","g"),E[H]+"NNNN"+d);N+=K;ba+="main"+d+"();\n"}ba+="gl_FragColor = shaderOutput;\n}\n";K=pc.shaderChunks.createShaderFromCode(q,pc.shaderChunks.fullscreenQuadVS,
|
|
N+ba,G)}for(d=0;d<C;d++)a[g[d]]._postEffectCombined=d===C-1?1:-1;a[g[C-1]]._postEffectCombinedShader=K;a[g[C-1]]._postEffectCombinedBilinear=a[g[0]].postEffectBilinear;a[g[C-1]]._postEffectCombinedSrc=a[g[0]].postEffect.srcRenderTarget}g[0]=c;C=1}}}for(c=0;c<a.length;c++){if(a[c].isPostEffect&&(!a[c].postEffect.srcRenderTarget&&!a[c]._postEffectCombined||!a[c].postEffect._postEffectCombinedSrc&&0<=a[c]._postEffectCombined)){for(d=c-1;d>=f;d--)a[d].renderTarget||(a[d].renderTarget=b[k]);a[c]._backbufferRtId=
|
|
k;f=c;l=!0;1===k&&(h=!0);a[c].postEffect.hdr&&(n=q.webgl2&&q.textureFloatRenderable?pc.PIXELFORMAT_111110F:q.extTextureHalfFloatLinear&&q.textureHalfFloatRenderable?pc.PIXELFORMAT_RGBA16F:pc.PIXELFORMAT_R8_G8_B8_A8);a[c].postEffect.shader&&!a[c].renderTarget&&(k=1-k)}else a[c].isPostEffect||a[c].renderTarget||!l||(a[c].renderTarget=b[k]);a[c].isPostEffect&&!a[c].renderTarget&&(p=!0)}if(l)if(!b[0].colorBuffer)F(0,q,n);else if(b[0].width!==q.width||b[0].height!==q.height||b[0]._colorBuffer._format!==
|
|
n)b[0].colorBuffer.destroy(),b[0].destroy(),F(0,q,n);if(h)if(!b[1].colorBuffer)F(1,q,n);else if(b[1].width!==q.width||b[1].height!==q.height||b[1]._colorBuffer._format!==n)b[1].colorBuffer.destroy(),b[1].destroy(),F(1,q,n)},this);e.on("postrender",function(){var a=e.graphicsDevice;if(l&&!p){for(var c=e.scene.layers.layerList,d,f=c.length-1;0<=f&&(d=c[f].renderTarget,d!==b[0]&&d!==b[1]);f--);d&&(1<d._samples&&d.resolve(!0,!1),a.copyRenderTarget(d,null,!0,!1))}},this)}}var b=[null,null],a=null,c,d=
|
|
new pc.Vec4,f=new Float32Array(4),g=[],l=!1,h=!1,p=!1,k=/uniform[ \t\n\r]+\S+[ \t\n\r]+\S+[ \t\n\r]*\;/g,n=/\S+[ \t\n\r]*\;/,q=/[ \t\n\r]*\;/,m=/(float|int|bool|vec2|vec3|vec4|struct)([ \t\n\r]+[^\;]+[ \t\n\r]*\,*)+\;/g,r=/(float|int|bool|vec2|vec3|vec4|struct|\,|\;|\{|\})/g,t=/(uniform|varying|in|out)[ \t\n\r]+(float|int|bool|vec2|vec3|vec4|struct)([ \t\n\r]+[^\;]+[ \t\n\r]*\,*)+\;/g,u=/(float|int|bool|vec2|vec3|vec4|struct|uniform|varying|in|out|\,|\;|\{|\})/g,x=/#version/g,v=/out highp vec4 pc_fragColor;/g,
|
|
w=/#define gl_FragColor/g,y=/gl_FragColor/g,D=/uniform[ \t\n\r]+sampler2D[ \t\n\r]+uColorBuffer;/g,B=/(varying|in)[ \t\n\r]+vec2[ \t\n\r]+vUv0;/g,z=/(texture2D|texture)[ \t\n\r]*\([ \t\n\r]*uColorBuffer/g,A=/void[ \t\n\r]+main/g,F=function(a,c,d){c=new pc.Texture(c,{format:d,width:c.width,height:c.height});c.name="posteffect-pass";c.minFilter=pc.FILTER_NEAREST;c.magFilter=pc.FILTER_NEAREST;c.addressU=pc.ADDRESS_CLAMP_TO_EDGE;c.addressV=pc.ADDRESS_CLAMP_TO_EDGE;b[a]._colorBuffer=c},I=function(a){a=
|
|
a.match(k)||[];for(var b,c,d=[],f=0;f<a.length;f++)b=a[f].search(n),c=a[f].search(q),b=a[f].substr(b,c-b),"uColorBuffer"!==b&&d.push(b);return d};e.prototype.addToComposition=function(a){this.app.scene.layers.insertTransparent(this.layer,a)};return{PostEffectPass:e}}());Object.assign(pc,function(){var e=function(a,b){pc.Component.call(this,a,b);this._cookieAssetId=this._cookieAsset=null;this._cookieAssetAdd=!1;this._cookieMatrix=null};e.prototype=Object.create(pc.Component.prototype);e.prototype.constructor=e;var b=[],a=[],c=function(c,f,g,l){var d=e.prototype;b.push(c);a.push(f);Object.defineProperty(d,c,{get:function(){return this.data[c]},set:function(a){var b=this.data,d=b[c];if(l||d!==a)b[c]=a,g&&g.call(this,a,d)},configurable:!0})};(function(){c("enabled",
|
|
!0,function(a,b){this.onSetEnabled(null,b,a)});c("light",null);c("type","directional",function(a,b){this.system.changeType(this,b,a);this.refreshProperties()});c("color",new pc.Color(1,1,1),function(a,b){this.light.setColor(a)},!0);c("intensity",1,function(a,b){this.light.intensity=a});c("castShadows",!1,function(a,b){this.light.castShadows=a});c("shadowDistance",40,function(a,b){this.light.shadowDistance=a});c("shadowResolution",1024,function(a,b){this.light.shadowResolution=a});c("shadowBias",.05,
|
|
function(a,b){this.light.shadowBias=-.01*a});c("normalOffsetBias",0,function(a,b){this.light.normalOffsetBias=a});c("range",10,function(a,b){this.light.attenuationEnd=a});c("innerConeAngle",40,function(a,b){this.light.innerConeAngle=a});c("outerConeAngle",45,function(a,b){this.light.outerConeAngle=a});c("falloffMode",pc.LIGHTFALLOFF_LINEAR,function(a,b){this.light.falloffMode=a});c("shadowType",pc.SHADOW_PCF3,function(a,b){this.light.shadowType=a});c("vsmBlurSize",11,function(a,b){this.light.vsmBlurSize=
|
|
a});c("vsmBlurMode",pc.BLUR_GAUSSIAN,function(a,b){this.light.vsmBlurMode=a});c("vsmBias",.0025,function(a,b){this.light.vsmBias=a});c("cookieAsset",null,function(a,b){if(!this._cookieAssetId||!(a instanceof pc.Asset&&a.id===this._cookieAssetId||a===this._cookieAssetId))if(this.onCookieAssetRemove(),this._cookieAssetId=null,a instanceof pc.Asset)this._cookieAssetId=this.data.cookieAsset=a.id,this.onCookieAssetAdd(a);else if("number"===typeof a){this._cookieAssetId=a;var c=this.system.app.assets.get(a);
|
|
if(c)this.onCookieAssetAdd(c);else this._cookieAssetAdd=!0,this.system.app.assets.on("add:"+this._cookieAssetId,this.onCookieAssetAdd,this)}});c("cookie",null,function(a,b){this.light.cookie=a});c("cookieIntensity",1,function(a,b){this.light.cookieIntensity=a});c("cookieFalloff",!0,function(a,b){this.light.cookieFalloff=a});c("cookieChannel","rgb",function(a,b){this.light.cookieChannel=a});c("cookieAngle",0,function(a,b){if(0!==a||null!==this.cookieScale){this._cookieMatrix||(this._cookieMatrix=new pc.Vec4);
|
|
var c=1,d=1;this.cookieScale&&(c=this.cookieScale.x,d=this.cookieScale.y);var f=Math.cos(a*pc.math.DEG_TO_RAD),e=Math.sin(a*pc.math.DEG_TO_RAD);this._cookieMatrix.set(f/c,-e/c,e/d,f/d);this.light.cookieTransform=this._cookieMatrix}else this.light.cookieTransform=null});c("cookieScale",null,function(a,b){if(null!==a||0!==this.cookieAngle){this._cookieMatrix||(this._cookieMatrix=new pc.Vec4);var c=a.x,d=a.y,f=Math.cos(this.cookieAngle*pc.math.DEG_TO_RAD),e=Math.sin(this.cookieAngle*pc.math.DEG_TO_RAD);
|
|
this._cookieMatrix.set(f/c,-e/c,e/d,f/d);this.light.cookieTransform=this._cookieMatrix}else this.light.cookieTransform=null},!0);c("cookieOffset",null,function(a,b){this.light.cookieOffset=a},!0);c("shadowUpdateMode",pc.SHADOWUPDATE_REALTIME,function(a,b){this.light.shadowUpdateMode=a});c("mask",1,function(a,b){this.light.mask=a});c("affectDynamic",!0,function(a,b){this.light.mask=a?this.light.mask|pc.MASK_DYNAMIC:this.light.mask&~pc.MASK_DYNAMIC;this.light.mask=this.light._mask});c("affectLightmapped",
|
|
!1,function(a,b){a?(this.light.mask|=pc.MASK_BAKED,this.bake&&(this.light.mask&=~pc.MASK_LIGHTMAP)):(this.light.mask&=~pc.MASK_BAKED,this.bake&&(this.light.mask|=pc.MASK_LIGHTMAP));this.light.mask=this.light._mask});c("bake",!1,function(a,b){a?(this.light.mask|=pc.MASK_LIGHTMAP,this.affectLightmapped&&(this.light.mask&=~pc.MASK_BAKED)):(this.light.mask&=~pc.MASK_LIGHTMAP,this.affectLightmapped&&(this.light.mask|=pc.MASK_BAKED));this.light.mask=this.light._mask});c("bakeDir",!0,function(a,b){this.light.bakeDir=
|
|
a});c("isStatic",!1,function(a,b){this.light.isStatic=a});c("layers",[pc.LAYERID_WORLD],function(a,b){var c,d;for(c=0;c<b.length;c++)(d=this.system.app.scene.layers.getLayerById(b[c]))&&d.removeLight(this);for(c=0;c<a.length;c++)(d=this.system.app.scene.layers.getLayerById(a[c]))&&this.enabled&&this.entity.enabled&&d.addLight(this)})})();Object.defineProperty(e.prototype,"enable",{get:function(){console.warn("WARNING: enable: Property is deprecated. Query enabled property instead.");return this.enabled},
|
|
set:function(a){console.warn("WARNING: enable: Property is deprecated. Set enabled property instead.");this.enabled=a}});Object.assign(e.prototype,{addLightToLayers:function(){for(var a,b=0;b<this.layers.length;b++)(a=this.system.app.scene.layers.getLayerById(this.layers[b]))&&a.addLight(this)},removeLightFromLayers:function(){for(var a,b=0;b<this.layers.length;b++)(a=this.system.app.scene.layers.getLayerById(this.layers[b]))&&a.removeLight(this)},onLayersChanged:function(a,b){this.enabled&&this.entity.enabled&&
|
|
this.addLightToLayers();a.off("add",this.onLayerAdded,this);a.off("remove",this.onLayerRemoved,this);b.on("add",this.onLayerAdded,this);b.on("remove",this.onLayerRemoved,this)},onLayerAdded:function(a){0>this.layers.indexOf(a.id)||this.enabled&&this.entity.enabled&&a.addLight(this)},onLayerRemoved:function(a){0>this.layers.indexOf(a.id)||a.removeLight(this)},refreshProperties:function(){for(var a,c=0;c<b.length;c++)a=b[c],this[a]=this[a];if(this.enabled&&this.entity.enabled)this.onEnable()},updateShadow:function(){this.light.updateShadow()},
|
|
onCookieAssetSet:function(){var a=!1;"cubemap"!==this._cookieAsset.type||this._cookieAsset.loadFaces||(a=this._cookieAsset.loadFaces=!0);this._cookieAsset.resource&&!a||this.system.app.assets.load(this._cookieAsset);if(this._cookieAsset.resource)this.onCookieAssetLoad()},onCookieAssetAdd:function(a){if(this._cookieAssetId===a.id){this._cookieAsset=a;if(this.light._enabled)this.onCookieAssetSet();this._cookieAsset.on("load",this.onCookieAssetLoad,this);this._cookieAsset.on("remove",this.onCookieAssetRemove,
|
|
this)}},onCookieAssetLoad:function(){this._cookieAsset&&this._cookieAsset.resource&&(this.cookie=this._cookieAsset.resource)},onCookieAssetRemove:function(){this._cookieAssetId&&(this._cookieAssetAdd&&(this.system.app.assets.off("add:"+this._cookieAssetId,this.onCookieAssetAdd,this),this._cookieAssetAdd=!1),this._cookieAsset&&(this._cookieAsset.off("load",this.onCookieAssetLoad,this),this._cookieAsset.off("remove",this.onCookieAssetRemove,this),this._cookieAsset=null),this.cookie=null)},onEnable:function(){this.light.enabled=
|
|
!0;this.system.app.scene.on("set:layers",this.onLayersChanged,this);this.system.app.scene.layers&&(this.system.app.scene.layers.on("add",this.onLayerAdded,this),this.system.app.scene.layers.on("remove",this.onLayerRemoved,this));this.enabled&&this.entity.enabled&&this.addLightToLayers();if(this._cookieAsset&&!this.cookie)this.onCookieAssetSet()},onDisable:function(){this.light.enabled=!1;this.system.app.scene.off("set:layers",this.onLayersChanged,this);this.system.app.scene.layers&&(this.system.app.scene.layers.off("add",
|
|
this.onLayerAdded,this),this.system.app.scene.layers.off("remove",this.onLayerRemoved,this));this.removeLightFromLayers()}});return{LightComponent:e,_lightProps:b,_lightPropsDefault:a}}());Object.assign(pc,function(){var e={directional:pc.LIGHTTYPE_DIRECTIONAL,point:pc.LIGHTTYPE_POINT,spot:pc.LIGHTTYPE_SPOT},b=function(a){pc.ComponentSystem.call(this,a);this.id="light";this.description="Enables the Entity to emit light.";this.ComponentType=pc.LightComponent;this.DataType=pc.LightComponentData};b.prototype=Object.create(pc.ComponentSystem.prototype);b.prototype.constructor=b;Object.assign(b.prototype,{initializeComponentData:function(a,b){for(var c=pc._lightProps,f={},g=0,l=c.length;g<
|
|
l;g++){var h=c[g];f[h]=b[h]}f.type||(f.type=a.data.type);a.data.type=f.type;f.layers&&"array"===pc.type(f.layers)&&(f.layers=f.layers.slice(0));f.color&&"array"===pc.type(f.color)&&(f.color=new pc.Color(f.color[0],f.color[1],f.color[2]));f.cookieOffset&&f.cookieOffset instanceof Array&&(f.cookieOffset=new pc.Vec2(f.cookieOffset[0],f.cookieOffset[1]));f.cookieScale&&f.cookieScale instanceof Array&&(f.cookieScale=new pc.Vec2(f.cookieScale[0],f.cookieScale[1]));f.enable&&(console.warn("WARNING: enable: Property is deprecated. Set enabled property instead."),
|
|
f.enabled=f.enable);g=new pc.Light;g.type=e[f.type];g._node=a.entity;g._scene=this.app.scene;a.data.light=g;pc.ComponentSystem.prototype.initializeComponentData.call(this,a,f,c)},removeComponent:function(a){a.light.data.light.destroy();pc.ComponentSystem.prototype.removeComponent.call(this,a)},cloneComponent:function(a,b){for(var c=a.light,f=[],g,e=pc._lightProps,h=0;h<e.length;h++)g=e[h],"light"!==g&&(f[g]=c[g]&&c[g].clone?c[g].clone():c[g]);this.addComponent(b,f)},changeType:function(a,b,d){b!==
|
|
d&&(a.light.type=e[d])}});return{LightComponentSystem:b}}());Object.assign(pc,function(){return{LightComponentData:function(){for(var e=pc._lightProps,b=pc._lightPropsDefault,a,c=0;c<e.length;c++)a=b[c],this[e[c]]=a&&a.clone?a.clone():a}}}());Object.assign(pc,function(){var e=function(b,a){pc.Component.call(this,b,a);this._scripts=[];this._updateList=new pc.SortedLoopArray({sortBy:"__executionOrder"});this._postUpdateList=new pc.SortedLoopArray({sortBy:"__executionOrder"});this._scriptsIndex={};this._destroyedScripts=[];this._destroyed=!1;this._scriptsData=null;this._enabled=this._oldState=!0;this._isLoopingThroughScripts=this._beingEnabled=!1;this._executionOrder=-1;this.on("set_enabled",this._onSetEnabled,this)};e.prototype=Object.create(pc.Component.prototype);
|
|
e.prototype.constructor=e;e.scriptMethods={initialize:"initialize",postInitialize:"postInitialize",update:"update",postUpdate:"postUpdate",swap:"swap"};Object.assign(e.prototype,{onEnable:function(){this._beingEnabled=!0;this._checkState();if(!this.entity._beingEnabled)this.onPostStateChange();this._beingEnabled=!1},onDisable:function(){this._checkState()},onPostStateChange:function(){for(var b,a=this._beginLooping(),c=0,d=this.scripts.length;c<d;c++)b=this.scripts[c],b._initialized&&!b._postInitialized&&
|
|
b.enabled&&(b._postInitialized=!0,b.postInitialize&&this._scriptMethod(b,e.scriptMethods.postInitialize));this._endLooping(a)},_beginLooping:function(){var b=this._isLoopingThroughScripts;this._isLoopingThroughScripts=!0;return b},_endLooping:function(b){(this._isLoopingThroughScripts=b)||this._removeDestroyedScripts()},_onSetEnabled:function(b,a,c){this._beingEnabled=!0;this._checkState();this._beingEnabled=!1},_checkState:function(){var b=this.enabled&&this.entity.enabled;if(b!==this._oldState){this._oldState=
|
|
b;this.fire(b?"enable":"disable");this.fire("state",b);b?this.system._addComponentToEnabled(this):this.system._removeComponentFromEnabled(this);for(var b=this._beginLooping(),a,c=0,d=this.scripts.length;c<d;c++)a=this.scripts[c],a.enabled=a._enabled;this._endLooping(b)}},_onBeforeRemove:function(){this.fire("remove");for(var b=this._beginLooping(),a=0;a<this.scripts.length;a++){var c=this.scripts[a];c&&this.destroy(c.__scriptType.__name)}this._endLooping(b)},_removeDestroyedScripts:function(){var b=
|
|
this._destroyedScripts.length;if(b){var a;for(a=0;a<b;a++)this._removeScriptInstance(this._destroyedScripts[a]);this._destroyedScripts.length=0;this._resetExecutionOrder(0,this._scripts.length)}},_onInitializeAttributes:function(){for(var b=0,a=this.scripts.length;b<a;b++)this.scripts[b].__initializeAttributes()},_scriptMethod:function(b,a,c){b[a](c)},_onInitialize:function(){for(var b,a=this._scripts,c=this._beginLooping(),d=0,f=a.length;d<f;d++)b=a[d],!b._initialized&&b.enabled&&(b._initialized=
|
|
!0,b.initialize&&this._scriptMethod(b,e.scriptMethods.initialize));this._endLooping(c)},_onPostInitialize:function(){this.onPostStateChange()},_onUpdate:function(b){var a=this._updateList;if(a.length){var c,d=this._beginLooping();for(a.loopIndex=0;a.loopIndex<a.length;a.loopIndex++)c=a.items[a.loopIndex],c.enabled&&this._scriptMethod(c,e.scriptMethods.update,b);this._endLooping(d)}},_onPostUpdate:function(b){var a=this._postUpdateList;if(a.length){var c=this._beginLooping(),d;for(a.loopIndex=0;a.loopIndex<
|
|
a.length;a.loopIndex++)d=a.items[a.loopIndex],d.enabled&&this._scriptMethod(d,e.scriptMethods.postUpdate,b);this._endLooping(c)}},_insertScriptInstance:function(b,a,c){-1===a?(this._scripts.push(b),b.__executionOrder=c,b.update&&this._updateList.append(b),b.postUpdate&&this._postUpdateList.append(b)):(this._scripts.splice(a,0,b),b.__executionOrder=a,this._resetExecutionOrder(a+1,c+1),b.update&&this._updateList.insert(b),b.postUpdate&&this._postUpdateList.insert(b))},_removeScriptInstance:function(b){var a=
|
|
this._scripts.indexOf(b);if(-1===a)return a;this._scripts.splice(a,1);b.update&&this._updateList.remove(b);b.postUpdate&&this._postUpdateList.remove(b);return a},_resetExecutionOrder:function(b,a){for(var c=b;c<a;c++)this._scripts[c].__executionOrder=c},has:function(b){"string"===typeof b&&(b=this.system.app.scripts.get(b));return!!this._scriptsIndex[b.__name]},create:function(b,a){var c=this;a=a||{};var d=b,f=b;"string"===typeof d?d=this.system.app.scripts.get(d):d&&(f=d.__name);if(d){if(!this._scriptsIndex[d.__name]||
|
|
!this._scriptsIndex[d.__name].instance){var f=new d({app:this.system.app,entity:this.entity,enabled:a.hasOwnProperty("enabled")?a.enabled:!0,attributes:a.attributes||null}),g=this._scripts.length,l=-1;"number"===typeof a.ind&&-1!==a.ind&&g>a.ind&&(l=a.ind);this._insertScriptInstance(f,l,g);this._scriptsIndex[d.__name]={instance:f,onSwap:function(){c.swap(d.__name)}};this[d.__name]=f;a.preloading||f.__initializeAttributes();this.fire("create",d.__name,f);this.fire("create:"+d.__name,f);this.system.app.scripts.on("swap:"+
|
|
d.__name,this._scriptsIndex[d.__name].onSwap);a.preloading||(f.enabled&&!f._initialized&&(f._initialized=!0,f.initialize&&this._scriptMethod(f,e.scriptMethods.initialize)),f.enabled&&!f._postInitialized&&(f._postInitialized=!0,f.postInitialize&&this._scriptMethod(f,e.scriptMethods.postInitialize)));return f}console.warn("script '"+f+"' is already added to entity '"+this.entity.name+"'")}else this._scriptsIndex[f]={awaiting:!0,ind:this._scripts.length},console.warn("script '"+f+"' is not found, awaiting it to be added to registry");
|
|
return null},destroy:function(b){var a=b;"string"===typeof b&&(b=this.system.app.scripts.get(b))&&(a=b.__name);b=this._scriptsIndex[a];delete this._scriptsIndex[a];if(!b)return!1;if(b.instance&&!b.instance._destroyed)if(b.instance.enabled=!1,b.instance._destroyed=!0,this._isLoopingThroughScripts)this._destroyedScripts.push(b.instance);else{var c=this._removeScriptInstance(b.instance);0<=c&&this._resetExecutionOrder(c,this._scripts.length)}this.system.app.scripts.off("swap:"+a,b.onSwap);delete this[a];
|
|
this.fire("destroy",a,b.instance||null);this.fire("destroy:"+a,b.instance||null);b.instance&&b.instance.fire("destroy");return!0},swap:function(b){"string"===typeof b&&(b=this.system.app.scripts.get(b));var a=this._scriptsIndex[b.__name];if(!a||!a.instance)return!1;var a=a.instance,c=this._scripts.indexOf(a),d=new b({app:this.system.app,entity:this.entity,enabled:a.enabled,attributes:a.__attributes});if(!d.swap)return!1;d.__initializeAttributes();this._scripts[c]=d;this._scriptsIndex[b.__name].instance=
|
|
d;this[b.__name]=d;d.__executionOrder=c;a.update&&this._updateList.remove(a);a.postUpdate&&this._postUpdateList.remove(a);d.update&&this._updateList.insert(d);d.postUpdate&&this._postUpdateList.insert(d);this._scriptMethod(d,e.scriptMethods.swap,a);this.fire("swap",b.__name,d);this.fire("swap:"+b.__name,d);return!0},resolveDuplicatedEntityReferenceProperties:function(b,a){var c=this.entity.script,d;for(d in b._scriptsIndex){var f=this.system.app.scripts.get(d);if(f){var g=b._scriptsIndex[d];if(g&&
|
|
g.instance){var e=c[d].__attributesRaw,h=c[d].__attributes;if(e||h){var g=g.instance.__attributes,p;for(p in g)if(g[p]){var k=f.attributes.get(p);if(k&&"entity"===k.type)if(k.array){var n=g[p];if(k=n.length){for(var n=n.slice(),q=0;q<k;q++){var m=n[q]instanceof pc.Entity?n[q].getGuid():n[q];a[m]&&(n[q]=e?a[m].getGuid():a[m])}e?e[p]=n:h[p]=n}}else{k=g[p];if(k instanceof pc.Entity)k=k.getGuid();else if("string"!==typeof k)continue;a[k]&&(e?e[p]=a[k].getGuid():h[p]=a[k])}}}}}}},move:function(b,a){var c=
|
|
this._scripts.length;if(a>=c||0>a)return!1;var d=b;"string"!==typeof d&&(d=b.__name);var f=this._scriptsIndex[d];if(!f||!f.instance)return!1;var g=this._scripts.indexOf(f.instance);if(-1===g||g===a)return!1;this._scripts.splice(a,0,this._scripts.splice(g,1)[0]);this._resetExecutionOrder(0,c);this._updateList.sort();this._postUpdateList.sort();this.fire("move",d,f.instance,a,g);this.fire("move:"+d,f.instance,a,g);return!0}});Object.defineProperty(e.prototype,"enabled",{get:function(){return this._enabled},
|
|
set:function(b){var a=this._enabled;this._enabled=b;this.fire("set","enabled",a,b)}});Object.defineProperty(e.prototype,"scripts",{get:function(){return this._scripts},set:function(b){this._scriptsData=b;for(var a in b)if(b.hasOwnProperty(a)){var c=this._scriptsIndex[a];if(c){if("boolean"===typeof b[a].enabled&&(c.enabled=!!b[a].enabled),"object"===typeof b[a].attributes)for(var d in b[a].attributes)if(!pc.createScript.reservedAttributes[d]){if(!c.__attributes.hasOwnProperty(d)){var f=this.system.app.scripts.get(a);
|
|
f&&f.attributes.add(d,{})}c[d]=b[a].attributes[d]}}else console.log(this.order)}}});return{ScriptComponent:e}}());Object.assign(pc,function(){var e=0,b=function(a){pc.ComponentSystem.call(this,a);this.id="script";this.app=a;this.ComponentType=pc.ScriptComponent;this.DataType=pc.ScriptComponentData;this._components=new pc.SortedLoopArray({sortBy:"_executionOrder"});this._enabledComponents=new pc.SortedLoopArray({sortBy:"_executionOrder"});this.preloading=!0;this.on("beforeremove",this._onBeforeRemove,this);pc.ComponentSystem.bind("initialize",this._onInitialize,this);pc.ComponentSystem.bind("postInitialize",this._onPostInitialize,
|
|
this);pc.ComponentSystem.bind("update",this._onUpdate,this);pc.ComponentSystem.bind("postUpdate",this._onPostUpdate,this)};b.prototype=Object.create(pc.ComponentSystem.prototype);b.prototype.constructor=b;Object.assign(b.prototype,{initializeComponentData:function(a,b){a._executionOrder=e++;this._components.append(a);e>Number.MAX_SAFE_INTEGER&&this._resetExecutionOrder();a.enabled=b.hasOwnProperty("enabled")?!!b.enabled:!0;a.enabled&&a.entity.enabled&&this._enabledComponents.append(a);if(b.hasOwnProperty("order")&&
|
|
b.hasOwnProperty("scripts")){a._scriptsData=b.scripts;for(var c=0;c<b.order.length;c++)a.create(b.order[c],{enabled:b.scripts[b.order[c]].enabled,attributes:b.scripts[b.order[c]].attributes,preloading:this.preloading})}},cloneComponent:function(a,b){var c,f,g=[],e={};for(c=0;c<a.script._scripts.length;c++){var h=a.script._scripts[c],p=h.__scriptType.__name;g.push(p);var k={};for(f in h.__attributes)k[f]=h.__attributes[f];e[p]={enabled:h._enabled,attributes:k}}for(f in a.script._scriptsIndex)f.awaiting&&
|
|
g.splice(f.ind,0,f);return this.addComponent(b,{enabled:a.script.enabled,order:g,scripts:e})},_resetExecutionOrder:function(){for(var a=e=0,b=this._components.length;a<b;a++)this._components.items[a]._executionOrder=e++},_callComponentMethod:function(a,b,d){for(a.loopIndex=0;a.loopIndex<a.length;a.loopIndex++)a.items[a.loopIndex][b](d)},_onInitialize:function(){this.preloading=!1;this._callComponentMethod(this._components,"_onInitializeAttributes");this._callComponentMethod(this._enabledComponents,
|
|
"_onInitialize")},_onPostInitialize:function(){this._callComponentMethod(this._enabledComponents,"_onPostInitialize")},_onUpdate:function(a){this._callComponentMethod(this._enabledComponents,"_onUpdate",a)},_onPostUpdate:function(a){this._callComponentMethod(this._enabledComponents,"_onPostUpdate",a)},_addComponentToEnabled:function(a){this._enabledComponents.insert(a)},_removeComponentFromEnabled:function(a){this._enabledComponents.remove(a)},_onBeforeRemove:function(a,b){0<=this._components.items.indexOf(b)&&
|
|
b._onBeforeRemove();this._removeComponentFromEnabled(b);this._components.remove(b)}});return{ScriptComponentSystem:b}}());Object.assign(pc,function(){return{ScriptComponentData:function(){this.enabled=!0}}}());Object.assign(pc,function(){var e=function(b,a){pc.Component.call(this,b,a);this.on("set_scripts",this.onSetScripts,this)};e.prototype=Object.create(pc.Component.prototype);e.prototype.constructor=e;Object.assign(e.prototype,{send:function(b,a){console.warn("DEPRECATED: ScriptLegacyComponent.send() is deprecated and will be removed soon. Please use: http://developer.playcanvas.com/user-manual/scripting/communication/");var c=pc.makeArray(arguments).slice(2),d=this.entity.script.instances,f;if(d&&
|
|
d[b]&&(f=d[b].instance[a]))return f.apply(d[b].instance,c)},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))},onDisable:function(){this.system._disableScriptComponent(this)},onSetScripts:function(b,a,c){this.system._inTools&&!this.runInTools||this._updateScriptAttributes(a,c)||(this.enabled&&
|
|
this.system._disableScriptComponent(this),this.system._destroyScriptComponent(this),this.data.areScriptsLoaded=!1,b=c.map(function(a){return a.url}),this._loadFromCache(b)||this._loadScripts(b))},_updateScriptAttributes:function(b,a){var c=!0;if(b.length!==a.length)c=!1;else{var d,f=a.length;for(d=0;d<f;d++)if(b[d].url!==a[d].url){c=!1;break}}if(c)for(var g in this.instances)this.instances.hasOwnProperty(g)&&this.system._updateAccessors(this.entity,this.instances[g]);return c},_loadFromCache:function(b){var a,
|
|
c,d=[],f=this.system.app._scriptPrefix||"",g=/^http(s)?:\/\//i;a=0;for(c=b.length;a<c;a++){var e=b[a];g.test(e)||(e=pc.path.join(f,e));e=this.system.app.loader.getFromCache(e,"script");if(!e)return!1;d.push(e)}a=0;for(c=d.length;a<c;a++)f=d[a],!0!==f&&f&&this.entity.script&&!this.entity.script.instances[f._pcScriptName]&&(g=new f(this.entity),this.system._preRegisterInstance(this.entity,b[a],f._pcScriptName,g));this.data&&(this.data.areScriptsLoaded=!0);this.system.preloading||(this.system.onInitialize(this.entity),
|
|
this.system.onPostInitialize(this.entity));return!0},_loadScripts:function(b){var a=b.length,c=this.system.app._scriptPrefix||"";b.forEach(function(b){var d=null,g=null;b.toLowerCase().startsWith("http://")||b.toLowerCase().startsWith("https://")?d=g=b:(g=b,d=pc.path.join(c,b));this.system.app.loader.load(d,"script",function(b,c){a--;if(b)console.error(b);else if(c&&this.entity.script&&!this.entity.script.instances[c._pcScriptName]){var d=new c(this.entity);this.system._preRegisterInstance(this.entity,
|
|
g,c._pcScriptName,d)}0===a&&(this.data.areScriptsLoaded=!0,this.system.preloading||(this.system.onInitialize(this.entity),this.system.onPostInitialize(this.entity)))}.bind(this))}.bind(this))}});return{ScriptLegacyComponent:e}}());Object.assign(pc,function(){var e=["enabled","scripts","instances","runInTools"],b=function(a){pc.ComponentSystem.call(this,a);this.id="script";this.description="Allows the Entity to run JavaScript fragments to implement custom behavior.";this.ComponentType=pc.ScriptLegacyComponent;this.DataType=pc.ScriptLegacyComponentData;this.schema=e;this.preloading=!1;this.instancesWithUpdate=[];this.instancesWithFixedUpdate=[];this.instancesWithPostUpdate=[];this.instancesWithToolsUpdate=[];this.on("beforeremove",
|
|
this.onBeforeRemove,this);pc.ComponentSystem.bind("initialize",this.onInitialize,this);pc.ComponentSystem.bind("postInitialize",this.onPostInitialize,this);pc.ComponentSystem.bind("update",this.onUpdate,this);pc.ComponentSystem.bind("fixedUpdate",this.onFixedUpdate,this);pc.ComponentSystem.bind("postUpdate",this.onPostUpdate,this);pc.ComponentSystem.bind("toolsUpdate",this.onToolsUpdate,this)};b.prototype=Object.create(pc.ComponentSystem.prototype);b.prototype.constructor=b;pc.Component._buildAccessors(pc.ScriptLegacyComponent.prototype,
|
|
e);Object.assign(b.prototype,{initializeComponentData:function(a,b,d){d=["runInTools","enabled","scripts"];b.scripts&&b.scripts.length&&b.scripts.forEach(function(a){if(a.attributes&&"array"===pc.type(a.attributes)){for(var b={},c=0;c<a.attributes.length;c++)b[a.attributes[c].name]=a.attributes[c];a.attributes=b}});pc.ComponentSystem.prototype.initializeComponentData.call(this,a,b,d)},cloneComponent:function(a,b){for(var c=this.store[a.getGuid()],f={runInTools:c.data.runInTools,scripts:[],enabled:c.data.enabled},
|
|
c=c.data.scripts,g=0,e=c.length;g<e;g++){var h=c[g].attributes;h&&delete c[g].attributes;f.scripts.push(pc.extend({},c[g]));h&&(f.scripts[g].attributes=this._cloneAttributes(h),c[g].attributes=h)}return this.addComponent(b,f)},onBeforeRemove:function(a,b){b.enabled&&this._disableScriptComponent(b);this._destroyScriptComponent(b)},onInitialize:function(a){this._registerInstances(a);if(a.enabled){a.script&&a.script.enabled&&this._initializeScriptComponent(a.script);a=a._children;var b,d=a.length;for(b=
|
|
0;b<d;b++)if(a[b]instanceof pc.Entity)this.onInitialize(a[b])}},onPostInitialize:function(a){if(a.enabled){a.script&&a.script.enabled&&this._postInitializeScriptComponent(a.script);a=a._children;var b,d=a.length;for(b=0;b<d;b++)if(a[b]instanceof pc.Entity)this.onPostInitialize(a[b])}},_callInstancesMethod:function(a,b){var c=a.data.instances,f;for(f in c)if(c.hasOwnProperty(f)){var g=c[f].instance;if(g[b])g[b]()}},_initializeScriptComponent:function(a){this._callInstancesMethod(a,"initialize");a.data.initialized=
|
|
!0;a.enabled&&a.entity.enabled&&this._enableScriptComponent(a)},_enableScriptComponent:function(a){this._callInstancesMethod(a,"onEnable")},_disableScriptComponent:function(a){this._callInstancesMethod(a,"onDisable")},_destroyScriptComponent:function(a){var b,d=a.data.instances,f;for(f in d)if(d.hasOwnProperty(f)){var g=d[f].instance;g.destroy&&g.destroy();g.update&&(b=this.instancesWithUpdate.indexOf(g),0<=b&&this.instancesWithUpdate.splice(b,1));g.fixedUpdate&&(b=this.instancesWithFixedUpdate.indexOf(g),
|
|
0<=b&&this.instancesWithFixedUpdate.splice(b,1));g.postUpdate&&(b=this.instancesWithPostUpdate.indexOf(g),0<=b&&this.instancesWithPostUpdate.splice(b,1));g.toolsUpdate&&(b=this.instancesWithToolsUpdate.indexOf(g),0<=b&&this.instancesWithToolsUpdate.splice(b,1));a.instances[f].instance===a[f]&&delete a[f];delete a.instances[f]}},_postInitializeScriptComponent:function(a){this._callInstancesMethod(a,"postInitialize");a.data.postInitialized=!0},_updateInstances:function(a,b,d){for(var c,g=0,e=b.length;g<
|
|
e;g++)if((c=b[g])&&c.entity&&c.entity.enabled&&c.entity.script.enabled)c[a](d)},onUpdate:function(a){this._updateInstances("update",this.instancesWithUpdate,a)},onFixedUpdate:function(a){this._updateInstances("fixedUpdate",this.instancesWithFixedUpdate,a)},onPostUpdate:function(a){this._updateInstances("postUpdate",this.instancesWithPostUpdate,a)},onToolsUpdate:function(a){this._updateInstances("toolsUpdate",this.instancesWithToolsUpdate,a)},broadcast:function(a,b){console.warn("DEPRECATED: ScriptLegacyComponentSystem.broadcast() is deprecated and will be removed soon. Please use: http://developer.playcanvas.com/user-manual/scripting/communication/");
|
|
var c=pc.makeArray(arguments).slice(2),f,g,e,h=this.store;for(f in h)h.hasOwnProperty(f)&&(g=h[f].data,g.instances[a]&&(e=g.instances[a].instance[b])&&e.apply(g.instances[a].instance,c))},_preRegisterInstance:function(a,b,d,f){if(a.script){a.script.data._instances=a.script.data._instances||{};if(a.script.data._instances[d])throw Error(pc.string.format("Script name collision '{0}'. Scripts from '{1}' and '{2}' {{3}}",d,b,a.script.data._instances[d].url,a.getGuid()));a.script.data._instances[d]={url:b,
|
|
name:d,instance:f}}},_registerInstances:function(a){var b,d,f;if(a.script&&a.script.data._instances){a.script.instances=a.script.data._instances;for(f in a.script.instances){b=a.script.instances[f];d=b.instance;pc.events.attach(d);d.update&&this.instancesWithUpdate.push(d);d.fixedUpdate&&this.instancesWithFixedUpdate.push(d);d.postUpdate&&this.instancesWithPostUpdate.push(d);d.toolsUpdate&&this.instancesWithToolsUpdate.push(d);a.script.scripts&&this._createAccessors(a,b);if(a.script[f])throw Error(pc.string.format("Script with name '{0}' is already attached to Script Component",
|
|
f));a.script[f]=d}delete a.script.data._instances}a=a._children;d=a.length;for(b=0;b<d;b++)a[b]instanceof pc.Entity&&this._registerInstances(a[b])},_cloneAttributes:function(a){var b={},d;for(d in a)if(a.hasOwnProperty(d))if("entity"!==a[d].type)b[d]=pc.extend({},a[d]);else{var f=a[d].value;delete a[d].value;b[d]=pc.extend({},a[d]);b[d].value=f;a[d].value=f}return b},_createAccessors:function(a,b){var c,f=a.script.scripts.length,g=b.url;for(c=0;c<f;c++){var e=a.script.scripts[c];if(e.url===g){c=e.attributes;
|
|
if(e.name&&c){for(var h in c)c.hasOwnProperty(h)&&this._createAccessor(c[h],b);a.script.data.attributes[e.name]=this._cloneAttributes(c)}break}}},_createAccessor:function(a,b){var c=this;a={name:a.name,value:a.value,type:a.type};c._convertAttributeValue(a);Object.defineProperty(b.instance,a.name,{get:function(){return a.value},set:function(d){var f=a.value;a.value=d;c._convertAttributeValue(a);b.instance.fire("set",a.name,f,a.value)},configurable:!0})},_updateAccessors:function(a,b){var c,f=a.script.scripts.length,
|
|
g,e=b.url,h,p;for(c=0;c<f;c++)if(h=a.script,p=h.scripts[c],p.url===e){c=p.name;p=p.attributes;if(c){if(p)for(g in p)p.hasOwnProperty(g)&&this._createAccessor(p[g],b);if(f=h.data.attributes[c])for(g in f)if(e=f[g],!(g in p))delete b.instance[e.name];else if(p[g].value!==e.value&&b.instance.onAttributeChanged)b.instance.onAttributeChanged(e.name,e.value,p[g].value);p?h.data.attributes[c]=this._cloneAttributes(p):delete h.data.attributes[c]}break}},_convertAttributeValue:function(a){if("rgb"===a.type||
|
|
"rgba"===a.type)"array"===pc.type(a.value)&&(a.value=3===a.value.length?new pc.Color(a.value[0],a.value[1],a.value[2]):new pc.Color(a.value[0],a.value[1],a.value[2],a.value[3]));else if("vec2"===a.type)"array"===pc.type(a.value)&&(a.value=new pc.Vec2(a.value[0],a.value[1]));else if("vec3"===a.type||"vector"===a.type)"array"===pc.type(a.value)&&(a.value=new pc.Vec3(a.value[0],a.value[1],a.value[2]));else if("vec4"===a.type)"array"===pc.type(a.value)&&(a.value=new pc.Vec4(a.value[0],a.value[1],a.value[2],
|
|
a.value[3]));else if("entity"===a.type)null!==a.value&&"string"===typeof a.value&&(a.value=this.app.root.findByGuid(a.value));else if("curve"===a.type||"colorcurve"===a.type)a.value=new (a.value.keys[0]instanceof Array?pc.CurveSet:pc.Curve)(a.value.keys),a.value.type=a.value.type}});return{ScriptLegacyComponentSystem:b}}());Object.assign(pc,function(){return{ScriptLegacyComponentData:function(){this.scripts=[];this.enabled=!0;this.instances={};this._instances={};this.runInTools=!1;this.attributes={};this.areScriptsLoaded=this.postInitialized=this.initialized=!1}}}());Object.assign(pc,{DISTANCE_LINEAR:"linear",DISTANCE_INVERSE:"inverse",DISTANCE_EXPONENTIAL:"exponential"});Object.assign(pc,function(){var e={volume:0,pitch:0,loop:!1,startTime:0,duration:0,position:new pc.Vec3,maxDistance:0,refDistance:0,rollOffFactor:0,distanceModel:0,onPlay:null,onPause:null,onResume:null,onStop:null,onEnd:null},b=function(a,b,d){d=d||{};this._component=a;this._assets=a.system.app.assets;this._manager=a.system.manager;this._name=b||"Untitled";this._volume=void 0!==d.volume?pc.math.clamp(Number(d.volume)||0,0,1):1;this._pitch=void 0!==d.pitch?Math.max(.01,Number(d.pitch)||0):1;this._loop=
|
|
!(void 0===d.loop||!d.loop);this._duration=0<d.duration?d.duration:null;this._startTime=Math.max(0,Number(d.startTime)||0);this._overlap=!!d.overlap;this._autoPlay=!!d.autoPlay;this._lastNode=this._firstNode=null;this._asset=d.asset;this._asset instanceof pc.Asset&&(this._asset=this._asset.id);this._onInstancePlayHandler=this._onInstancePlay.bind(this);this._onInstancePauseHandler=this._onInstancePause.bind(this);this._onInstanceResumeHandler=this._onInstanceResume.bind(this);this._onInstanceStopHandler=
|
|
this._onInstanceStop.bind(this);this._onInstanceEndHandler=this._onInstanceEnd.bind(this);this.instances=[];pc.events.attach(this)};Object.assign(b.prototype,{play:function(){this.overlap||!this.isPlaying&&!this.isPaused||this.stop();var a=this._createInstance();this.instances.push(a);if(this.isLoaded)a.play();else{var b=function(b){var c=a._playWhenLoaded;a.sound=b;c&&a.play()};this.off("load",b);this.once("load",b);this.load()}return a},pause:function(){for(var a=!1,b=this.instances,d=0,f=b.length;d<
|
|
f;d++)b[d].pause()&&(a=!0);return a},resume:function(){for(var a=!1,b=this.instances,d=0,f=b.length;d<f;d++)b[d].resume()&&(a=!0);return a},stop:function(){for(var a=!1,b=this.instances,d=0,f=b.length;d<f;d++)b[d].stop()&&(a=!0);b.length=0;return a},load:function(){if(this._hasAsset()){var a=this._assets.get(this._asset);a?(a.off("remove",this._onAssetRemoved,this),a.on("remove",this._onAssetRemoved,this),a.resource?this.fire("load",a.resource):(a.off("load",this._onAssetLoad,this),a.once("load",
|
|
this._onAssetLoad,this),this._assets.load(a))):(this._assets.off("add:"+this._asset,this._onAssetAdd,this),this._assets.once("add:"+this._asset,this._onAssetAdd,this))}},setExternalNodes:function(a,b){if(a){if(b||(b=a),this._firstNode=a,this._lastNode=b,!this._overlap)for(var c=this.instances,f=0,g=c.length;f<g;f++)c[f].setExternalNodes(a,b)}else console.error("The firstNode must have a valid AudioNode")},clearExternalNodes:function(){this._lastNode=this._firstNode=null;if(!this._overlap)for(var a=
|
|
this.instances,b=0,d=a.length;b<d;b++)a[b].clearExternalNodes()},getExternalNodes:function(){return[this._firstNode,this._lastNode]},_hasAsset:function(){return null!=this._asset},_createInstance:function(){var a;a=this._component;var b=null;if(this._hasAsset()){var d=this._assets.get(this._asset);d&&(b=d.resource)}e.volume=this._volume*a.volume;e.pitch=this._pitch*a.pitch;e.loop=this._loop;e.startTime=this._startTime;e.duration=this._duration;e.onPlay=this._onInstancePlayHandler;e.onPause=this._onInstancePauseHandler;
|
|
e.onResume=this._onInstanceResumeHandler;e.onStop=this._onInstanceStopHandler;e.onEnd=this._onInstanceEndHandler;a.positional?(e.position.copy(a.entity.getPosition()),e.maxDistance=a.maxDistance,e.refDistance=a.refDistance,e.rollOffFactor=a.rollOffFactor,e.distanceModel=a.distanceModel,a=new pc.SoundInstance3d(this._manager,b,e)):a=new pc.SoundInstance(this._manager,b,e);this._firstNode&&a.setExternalNodes(this._firstNode,this._lastNode);return a},_onInstancePlay:function(a){this.fire("play",a);this._component.fire("play",
|
|
this,a)},_onInstancePause:function(a){this.fire("pause",a);this._component.fire("pause",this,a)},_onInstanceResume:function(a){this.fire("resume",a);this._component.fire("resume",this,a)},_onInstanceStop:function(a){this.fire("stop",a);this._component.fire("stop",this,a)},_onInstanceEnd:function(a){var b=this.instances.indexOf(a);-1!==b&&this.instances.splice(b,1);this.fire("end",a);this._component.fire("end",this,a)},_onAssetAdd:function(a){this.load()},_onAssetLoad:function(a){this.load()},_onAssetRemoved:function(a){a.off("remove",
|
|
this._onAssetRemoved,this);this._assets.off("add:"+a.id,this._onAssetAdd,this);this.stop()},updatePosition:function(a){for(var b=this.instances,d=0,f=b.length;d<f;d++)b[d].position=a}});Object.defineProperty(b.prototype,"name",{get:function(){return this._name},set:function(a){this._name=a}});Object.defineProperty(b.prototype,"volume",{get:function(){return this._volume},set:function(a){this._volume=pc.math.clamp(Number(a)||0,0,1);if(!this._overlap){a=this.instances;for(var b=0,d=a.length;b<d;b++)a[b].volume=
|
|
this._volume*this._component.volume}}});Object.defineProperty(b.prototype,"pitch",{get:function(){return this._pitch},set:function(a){this._pitch=Math.max(Number(a)||0,.01);if(!this._overlap){a=this.instances;for(var b=0,d=a.length;b<d;b++)a[b].pitch=this.pitch*this._component.pitch}}});Object.defineProperty(b.prototype,"loop",{get:function(){return this._loop},set:function(a){this._loop=!!a;a=this.instances;for(var b=0,d=a.length;b<d;b++)a[b].loop=this._loop}});Object.defineProperty(b.prototype,
|
|
"autoPlay",{get:function(){return this._autoPlay},set:function(a){this._autoPlay=!!a}});Object.defineProperty(b.prototype,"overlap",{get:function(){return this._overlap},set:function(a){this._overlap=!!a}});Object.defineProperty(b.prototype,"startTime",{get:function(){return this._startTime},set:function(a){this._startTime=Math.max(0,Number(a)||0);if(!this._overlap){a=this.instances;for(var b=0,d=a.length;b<d;b++)a[b].startTime=this._startTime}}});Object.defineProperty(b.prototype,"duration",{get:function(){var a=
|
|
0;this._hasAsset()&&(a=this._assets.get(this._asset),a=a.resource?a.resource.duration:0);return null!=this._duration?this._duration%(a||1):a},set:function(a){this._duration=Math.max(0,Number(a)||0)||null;if(!this._overlap){a=this.instances;for(var b=0,d=a.length;b<d;b++)a[b].duration=this._duration}}});Object.defineProperty(b.prototype,"asset",{get:function(){return this._asset},set:function(a){var b=this._asset;b&&(this._assets.off("add:"+b,this._onAssetAdd,this),(b=this._assets.get(b))&&b.off("remove",
|
|
this._onAssetRemoved,this));this._asset=a;this._asset instanceof pc.Asset&&(this._asset=this._asset.id);this._hasAsset()&&this._component.enabled&&this._component.entity.enabled&&this.load()}});Object.defineProperty(b.prototype,"isLoaded",{get:function(){if(this._hasAsset()){var a=this._assets.get(this._asset);if(a)return!!a.resource}return!1}});Object.defineProperty(b.prototype,"isPlaying",{get:function(){for(var a=this.instances,b=0,d=a.length;b<d;b++)if(a[b].isPlaying)return!0;return!1}});Object.defineProperty(b.prototype,
|
|
"isPaused",{get:function(){var a=this.instances,b=a.length;if(0===b)return!1;for(var d=0;d<b;d++)if(!a[d].isPaused)return!1;return!0}});Object.defineProperty(b.prototype,"isStopped",{get:function(){for(var a=this.instances,b=0,d=a.length;b<d;b++)if(!a[b].isStopped)return!1;return!0}});return{SoundSlot:b}}());Object.assign(pc,function(){var e=function(b,a){pc.Component.call(this,b,a);this.on("set_slots",this.onSetSlots,this);this.on("set_volume",this.onSetVolume,this);this.on("set_pitch",this.onSetPitch,this);this.on("set_refDistance",this.onSetRefDistance,this);this.on("set_maxDistance",this.onSetMaxDistance,this);this.on("set_rollOffFactor",this.onSetRollOffFactor,this);this.on("set_distanceModel",this.onSetDistanceModel,this);this.on("set_positional",this.onSetPositional,this)};e.prototype=Object.create(pc.Component.prototype);
|
|
e.prototype.constructor=e;Object.assign(e.prototype,{onSetSlots:function(b,a,c){var d;if(a)for(d in a)a[d].stop();b={};for(d in c)c[d]instanceof pc.SoundSlot?b[c[d].name]=c[d]:c[d].name&&(b[c[d].name]=new pc.SoundSlot(this,c[d].name,c[d]));this.data.slots=b;if(this.enabled&&this.entity.enabled)this.onEnable()},onSetVolume:function(b,a,c){b=this.data.slots;for(var d in b)if(a=b[d],!a.overlap)for(var f=a.instances,g=0,e=f.length;g<e;g++)f[g].volume=a.volume*c},onSetPitch:function(b,a,c){b=this.data.slots;
|
|
for(var d in b)if(a=b[d],!a.overlap)for(var f=a.instances,g=0,e=f.length;g<e;g++)f[g].pitch=a.pitch*c},onSetRefDistance:function(b,a,c){b=this.data.slots;for(var d in b)if(a=b[d],!a.overlap){a=a.instances;for(var f=0,g=a.length;f<g;f++)a[f].refDistance=c}},onSetMaxDistance:function(b,a,c){b=this.data.slots;for(var d in b)if(a=b[d],!a.overlap){a=a.instances;for(var f=0,g=a.length;f<g;f++)a[f].maxDistance=c}},onSetRollOffFactor:function(b,a,c){b=this.data.slots;for(var d in b)if(a=b[d],!a.overlap){a=
|
|
a.instances;for(var f=0,g=a.length;f<g;f++)a[f].rollOffFactor=c}},onSetDistanceModel:function(b,a,c){b=this.data.slots;for(var d in b)if(a=b[d],!a.overlap){a=a.instances;for(var f=0,g=a.length;f<g;f++)a[f].distanceModel=c}},onSetPositional:function(b,a,c){b=this.data.slots;for(var d in b)if(a=b[d],!a.overlap){c=a.instances;for(var f=0,g=c.length;f<g;f++){var e=c[f].isPlaying||c[f].isSuspended,h=c[f].currentTime;e&&c[f].stop();c[f]=a._createInstance();e&&(c[f].play(),c[f].currentTime=h)}}},onEnable:function(){if(!this.system._inTools){var b=
|
|
this.data.slots,a=this.data.playingBeforeDisable,c;for(c in b){var d=b[c];d.autoPlay&&d.isStopped?d.play():a[c]?d.resume():d.isLoaded||d.load()}}},onDisable:function(){var b=this.data.slots,a={},c;for(c in b)!b[c].overlap&&b[c].isPlaying&&(b[c].pause(),a[c]=!0);this.data.playingBeforeDisable=a},onRemove:function(){this.off()},addSlot:function(b,a){var c=this.data.slots;if(c[b])return logWARNING("A sound slot with name "+b+" already exists on Entity "+this.entity.getPath()),null;var d=new pc.SoundSlot(this,
|
|
b,a);c[b]=d;d.autoPlay&&this.enabled&&this.entity.enabled&&d.play();return d},removeSlot:function(b){var a=this.data.slots;a[b]&&(a[b].stop(),delete a[b])},slot:function(b){return this.data.slots[b]},play:function(b){if(!this.enabled||!this.entity.enabled)return null;var a=this.slots[b];return a?a.play():(logWARNING("Trying to play sound slot with name "+b+" which does not exist"),null)},pause:function(b){var a;a=this.data.slots;if(b)(a=a[b])?a.pause():logWARNING("Trying to pause sound slot with name "+
|
|
b+" which does not exist");else for(var c in a)a[c].pause()},resume:function(b){var a;a=this.data.slots;if(b)(a=a[b])?a.isPaused&&a.resume():logWARNING("Trying to resume sound slot with name "+b+" which does not exist");else for(var c in a)a[c].resume()},stop:function(b){var a;a=this.data.slots;if(b)(a=a[b])?a.stop():logWARNING("Trying to stop sound slot with name "+b+" which does not exist");else for(var c in a)a[c].stop()}});return{SoundComponent:e}}());Object.assign(pc,function(){var e="enabled volume pitch positional refDistance maxDistance rollOffFactor distanceModel slots".split(" "),b=function(a,b){pc.ComponentSystem.call(this,a);this.id="sound";this.description="Allows an Entity to play sounds";this.ComponentType=pc.SoundComponent;this.DataType=pc.SoundComponentData;this.schema=e;this.manager=b;pc.ComponentSystem.bind("update",this.onUpdate,this);this.on("beforeremove",this.onBeforeRemove,this)};b.prototype=Object.create(pc.ComponentSystem.prototype);
|
|
b.prototype.constructor=b;pc.Component._buildAccessors(pc.SoundComponent.prototype,e);Object.assign(b.prototype,{initializeComponentData:function(a,b,d){d="volume pitch positional refDistance maxDistance rollOffFactor distanceModel slots enabled".split(" ");pc.ComponentSystem.prototype.initializeComponentData.call(this,a,b,d)},cloneComponent:function(a,b){var c,f=a.sound.data,g={};for(c in f)f.hasOwnProperty(c)&&(g[c]=f[c]);g.slots={};for(c in f.slots){var e=f.slots[c];g.slots[c]=e instanceof pc.SoundSlot?
|
|
{name:e.name,volume:e.volume,pitch:e.pitch,loop:e.loop,duration:e.duration,startTime:e.startTime,overlap:e.overlap,autoPlay:e.autoPlay,asset:e.asset}:e}g.playingBeforeDisable={};return this.addComponent(b,g)},onUpdate:function(a){a=this.store;for(var b in a)if(a.hasOwnProperty(b)){var d=a[b],f=d.entity,d=d.data;if(d.enabled&&f.enabled&&d.positional){var f=f.getPosition(),d=d.slots,g;for(g in d)d[g].updatePosition(f)}}},onBeforeRemove:function(a,b){var c=b.slots,f;for(f in c)c[f].overlap||c[f].stop();
|
|
b.onRemove()}});Object.defineProperty(b.prototype,"volume",{get:function(){return this.manager.volume},set:function(a){this.manager.volume=a}});Object.defineProperty(b.prototype,"context",{get:function(){return pc.SoundManager.hasAudioContext()?this.manager.context:(console.warn("WARNING: Audio context is not supported on this browser"),null)}});return{SoundComponentSystem:b}}());pc.SoundComponentData=function(){this.enabled=!0;this.pitch=this.volume=1;this.positional=!0;this.refDistance=1;this.maxDistance=1E4;this.rollOffFactor=1;this.distanceModel=pc.DISTANCE_LINEAR;this.slots={};this.playingBeforeDisable={}};Object.assign(pc,function(){var e=function(b,a){pc.Component.call(this,b,a);this.on("set_assets",this.onSetAssets,this);this.on("set_loop",this.onSetLoop,this);this.on("set_volume",this.onSetVolume,this);this.on("set_pitch",this.onSetPitch,this);this.on("set_minDistance",this.onSetMinDistance,this);this.on("set_maxDistance",this.onSetMaxDistance,this);this.on("set_rollOffFactor",this.onSetRollOffFactor,this);this.on("set_distanceModel",this.onSetDistanceModel,this);this.on("set_3d",this.onSet3d,this)};
|
|
e.prototype=Object.create(pc.Component.prototype);e.prototype.constructor=e;Object.assign(e.prototype,{play:function(b){if(this.enabled&&this.entity.enabled){this.channel&&this.stop();var a,c=this.data;c.sources[b]&&(c["3d"]?(a=this.entity.getPosition(),a=this.system.manager.playSound3d(c.sources[b],a,c)):a=this.system.manager.playSound(c.sources[b],c),c.currentSource=b,c.channel=a)}},pause:function(){this.channel&&this.channel.pause()},unpause:function(){this.channel&&this.channel.paused&&this.channel.unpause()},
|
|
stop:function(){this.channel&&(this.channel.stop(),this.channel=null)},onSetAssets:function(b,a,c){b=[];var d,f=c.length;if(a&&a.length)for(d=0;d<a.length;d++)if(a[d]){var g=this.system.app.assets.get(a[d]);g&&(g.off("change",this.onAssetChanged,this),g.off("remove",this.onAssetRemoved,this),this.currentSource===g.name&&this.stop())}if(f)for(d=0;d<f;d++)0>a.indexOf(c[d])&&(c[d]instanceof pc.Asset?b.push(c[d].id):b.push(c[d]));!this.system._inTools&&b.length&&this.loadAudioSourceAssets(b)},onAssetChanged:function(b,
|
|
a,c,d){"resource"===a&&this.data.sources&&(this.data.sources[b.name]=c,this.data.currentSource===b.name&&this.channel&&(this.channel.paused?(this.play(b.name),this.pause()):this.play(b.name)))},onAssetRemoved:function(b){b.off("remove",this.onAssetRemoved,this);this.data.sources[b.name]&&(delete this.data.sources[b.name],this.data.currentSource===b.name&&(this.stop(),this.data.currentSource=null))},onSetLoop:function(b,a,c){a!=c&&this.channel&&this.channel.setLoop(c)},onSetVolume:function(b,a,c){a!=
|
|
c&&this.channel&&this.channel.setVolume(c)},onSetPitch:function(b,a,c){a!=c&&this.channel&&this.channel.setPitch(c)},onSetMaxDistance:function(b,a,c){a!=c&&this.channel instanceof pc.Channel3d&&this.channel.setMaxDistance(c)},onSetMinDistance:function(b,a,c){a!=c&&this.channel instanceof pc.Channel3d&&this.channel.setMinDistance(c)},onSetRollOffFactor:function(b,a,c){a!=c&&this.channel instanceof pc.Channel3d&&this.channel.setRollOffFactor(c)},onSetDistanceModel:function(b,a,c){a!==c&&this.channel instanceof
|
|
pc.Channel3d&&this.channel.setDistanceModel(c)},onSet3d:function(b,a,c){a!==c&&this.system.initialized&&this.currentSource&&(a=b=!1,this.channel&&(b=this.channel.paused,a=this.channel.suspended),this.play(this.currentSource),this.channel&&(this.channel.paused=b,this.channel.suspended=a))},onEnable:function(){var b=this.data.assets;if(b)for(var a=this.system.app.assets,c=0,d=b.length;c<d;c++){var f=b[c];f instanceof pc.Asset||(f=a.get(f));f&&!f.resource&&a.load(f)}this.system.initialized&&(this.data.activate&&
|
|
!this.channel?this.play(this.currentSource):this.unpause())},onDisable:function(){this.pause()},loadAudioSourceAssets:function(b){var a=this,c=b.map(function(a){return this.system.app.assets.get(a)},this),d={},f=null,g=c.length,e=function(a){g--},h=function(){this.data.sources=d;this.data.currentSource=f;if(this.enabled&&this.activate&&f)this.onEnable()}.bind(this);c.forEach(function(c,l){c?(f=f||c.name,c.off("change",this.onAssetChanged,this),c.on("change",this.onAssetChanged,this),c.off("remove",
|
|
this.onAssetRemoved,this),c.on("remove",this.onAssetRemoved,this),c.off("error",e,this),c.on("error",e,this),c.ready(function(a){d[a.name]=a.resource;g--;0===g&&h()}),!c.resource&&a.enabled&&a.entity.enabled&&this.system.app.assets.load(c)):(g--,0===g&&h(),this.system.app.assets.on("add:"+b[l],function(b){b.ready(function(b){a.data.sources[b.name]=b.resource});b.resource||a.system.app.assets.load(b)}))},this)}});return{AudioSourceComponent:e}}());Object.assign(pc,function(){var e="enabled assets volume pitch loop activate 3d minDistance maxDistance rollOffFactor distanceModel sources currentSource channel".split(" "),b=function(a,b){pc.ComponentSystem.call(this,a);this.id="audiosource";this.description="Specifies audio assets that can be played at the position of the Entity.";this.ComponentType=pc.AudioSourceComponent;this.DataType=pc.AudioSourceComponentData;this.schema=e;this.manager=b;this.initialized=!1;pc.ComponentSystem.bind("initialize",
|
|
this.onInitialize,this);pc.ComponentSystem.bind("update",this.onUpdate,this);this.on("remove",this.onRemove,this)};b.prototype=Object.create(pc.ComponentSystem.prototype);b.prototype.constructor=b;pc.Component._buildAccessors(pc.AudioSourceComponent.prototype,e);Object.assign(b.prototype,{initializeComponentData:function(a,b,d){d="activate volume pitch loop 3d minDistance maxDistance rollOffFactor distanceModel enabled assets".split(" ");pc.ComponentSystem.prototype.initializeComponentData.call(this,
|
|
a,b,d);a.paused=!(a.enabled&&a.activate)},onInitialize:function(a){a.audiosource&&a.enabled&&a.audiosource.enabled&&a.audiosource.activate&&a.audiosource.play(a.audiosource.currentSource);a=a._children;var b,d=a.length;for(b=0;b<d;b++)if(a[b]instanceof pc.Entity)this.onInitialize(a[b]);this.initialized=!0},onUpdate:function(a){a=this.store;for(var b in a)if(a.hasOwnProperty(b)){var d=a[b],f=d.entity,d=d.data;d.enabled&&f.enabled&&d.channel instanceof pc.Channel3d&&(f=f.getPosition(),d.channel.setPosition(f))}},
|
|
onRemove:function(a,b){b.channel&&(b.channel.stop(),b.channel=null)},setVolume:function(a){this.manager.setVolume(a)}});return{AudioSourceComponentSystem:b}}());pc.AudioSourceComponentData=function(){this.enabled=!0;this.assets=[];this.activate=!0;this.pitch=this.volume=1;this.loop=!1;this["3d"]=!0;this.minDistance=1;this.maxDistance=1E4;this.rollOffFactor=1;this.distanceModel=pc.DISTANCE_INVERSE;this.paused=!0;this.sources={};this.channel=this.currentSource=null};Object.assign(pc,function(){var e=function(b,a){pc.Component.call(this,b,a)};e.prototype=Object.create(pc.Component.prototype);e.prototype.constructor=e;Object.assign(e.prototype,{setCurrentListener:function(){if(this.enabled&&this.entity.audiolistener&&this.entity.enabled){this.system.current=this.entity;var b=this.system.current.getPosition();this.system.manager.listener.setPosition(b)}},onEnable:function(){this.setCurrentListener()},onDisable:function(){this.system.current===this.entity&&(this.system.current=
|
|
null)}});return{AudioListenerComponent:e}}());Object.assign(pc,function(){var e=["enabled"],b=function(a,b){pc.ComponentSystem.call(this,a);this.id="audiolistener";this.description="Specifies the location of the listener for 3D audio playback.";this.ComponentType=pc.AudioListenerComponent;this.DataType=pc.AudioListenerComponentData;this.schema=e;this.manager=b;this.current=null;pc.ComponentSystem.bind("update",this.onUpdate,this)};b.prototype=Object.create(pc.ComponentSystem.prototype);b.prototype.constructor=b;pc.Component._buildAccessors(pc.AudioListenerComponent.prototype,
|
|
e);Object.assign(b.prototype,{initializeComponentData:function(a,b,d){d=["enabled"];pc.ComponentSystem.prototype.initializeComponentData.call(this,a,b,d)},onUpdate:function(a){this.current&&(a=this.current.getPosition(),this.manager.listener.setPosition(a),a=this.current.getWorldTransform(),this.manager.listener.setOrientation(a))}});return{AudioListenerComponentSystem:b}}());Object.assign(pc,function(){return{AudioListenerComponentData:function(){this.enabled=!0}}}());Object.assign(pc,{BODYTYPE_STATIC:"static",BODYTYPE_DYNAMIC:"dynamic",BODYTYPE_KINEMATIC:"kinematic",BODYFLAG_STATIC_OBJECT:1,BODYFLAG_KINEMATIC_OBJECT:2,BODYFLAG_NORESPONSE_OBJECT:4,BODYSTATE_ACTIVE_TAG:1,BODYSTATE_ISLAND_SLEEPING:2,BODYSTATE_WANTS_DEACTIVATION:3,BODYSTATE_DISABLE_DEACTIVATION:4,BODYSTATE_DISABLE_SIMULATION:5,BODYGROUP_NONE:0,BODYGROUP_DEFAULT:1,BODYGROUP_DYNAMIC:1,BODYGROUP_STATIC:2,BODYGROUP_KINEMATIC:4,BODYGROUP_ENGINE_1:8,BODYGROUP_TRIGGER:16,BODYGROUP_ENGINE_2:32,BODYGROUP_ENGINE_3:64,
|
|
BODYGROUP_USER_1:128,BODYGROUP_USER_2:256,BODYGROUP_USER_3:512,BODYGROUP_USER_4:1024,BODYGROUP_USER_5:2048,BODYGROUP_USER_6:4096,BODYGROUP_USER_7:8192,BODYGROUP_USER_8:16384,BODYMASK_NONE:0,BODYMASK_ALL:65535,BODYMASK_STATIC:2,BODYMASK_NOT_STATIC:65533,BODYMASK_NOT_STATIC_KINEMATIC:65529});Object.assign(pc,function(){var e,b,a,c,d,f=function(f,l){pc.Component.call(this,f,l);"undefined"===typeof Ammo||e||(e=new Ammo.btTransform,b=new Ammo.btVector3,a=new Ammo.btVector3,c=new Ammo.btQuaternion,d=new Ammo.btVector3(0,0,0));this.on("set_mass",this.onSetMass,this);this.on("set_linearDamping",this.onSetLinearDamping,this);this.on("set_angularDamping",this.onSetAngularDamping,this);this.on("set_linearFactor",this.onSetLinearFactor,this);this.on("set_angularFactor",this.onSetAngularFactor,
|
|
this);this.on("set_friction",this.onSetFriction,this);this.on("set_restitution",this.onSetRestitution,this);this.on("set_type",this.onSetType,this);this.on("set_group",this.onSetGroupOrMask,this);this.on("set_mask",this.onSetGroupOrMask,this);this.on("set_body",this.onSetBody,this);this._displacement=new pc.Vec3(0,0,0);this._linearVelocity=new pc.Vec3(0,0,0);this._angularVelocity=new pc.Vec3(0,0,0)};f.prototype=Object.create(pc.Component.prototype);f.prototype.constructor=f;Object.defineProperty(f.prototype,
|
|
"bodyType",{get:function(){console.warn("WARNING: bodyType: Function is deprecated. Query type property instead.");return this.type},set:function(a){console.warn("WARNING: bodyType: Function is deprecated. Set type property instead.");this.type=a}});Object.defineProperty(f.prototype,"linearVelocity",{get:function(){if(!this.isKinematic()&&this.body){var a=this.body.getLinearVelocity();this._linearVelocity.set(a.x(),a.y(),a.z())}return this._linearVelocity},set:function(a){this.activate();!this.isKinematic()&&
|
|
this.body&&(b.setValue(a.x,a.y,a.z),this.body.setLinearVelocity(b));this._linearVelocity.copy(a)}});Object.defineProperty(f.prototype,"angularVelocity",{get:function(){if(!this.isKinematic()&&this.body){var a=this.body.getAngularVelocity();this._angularVelocity.set(a.x(),a.y(),a.z())}return this._angularVelocity},set:function(a){this.activate();!this.isKinematic()&&this.body&&(b.setValue(a.x,a.y,a.z),this.body.setAngularVelocity(b));this._angularVelocity.copy(a)}});Object.assign(f.prototype,{createBody:function(){var a=
|
|
this.entity,d;a.collision&&(d=a.collision.shape,a.trigger&&(a.trigger.destroy(),delete a.trigger));if(d){this.body&&(this.system.removeBody(this.body),Ammo.destroy(this.body));var f=this.isStaticOrKinematic(),e=f?0:this.mass,k=new Ammo.btVector3(0,0,0);f||d.calculateLocalInertia(e,k);var f=a.getPosition(),n=a.getRotation();c.setValue(n.x,n.y,n.z,n.w);n=new Ammo.btTransform;n.setIdentity();n.getOrigin().setValue(f.x,f.y,f.z);n.setRotation(c);f=new Ammo.btDefaultMotionState(n);d=new Ammo.btRigidBodyConstructionInfo(e,
|
|
f,d,k);d=new Ammo.btRigidBody(d);d.setRestitution(this.restitution);d.setFriction(this.friction);d.setDamping(this.linearDamping,this.angularDamping);e=this.linearFactor;b.setValue(e.x,e.y,e.z);d.setLinearFactor(b);e=this.angularFactor;b.setValue(e.x,e.y,e.z);d.setAngularFactor(b);d.entity=a;this.isKinematic()&&(d.setCollisionFlags(d.getCollisionFlags()|pc.BODYFLAG_KINEMATIC_OBJECT),d.setActivationState(pc.BODYSTATE_DISABLE_DEACTIVATION));a.rigidbody.body=d;this.enabled&&this.entity.enabled&&this.enableSimulation()}},
|
|
isActive:function(){return this.body?this.body.isActive():!1},activate:function(){this.body&&this.body.activate()},enableSimulation:function(){if(this.entity.collision&&this.entity.collision.enabled&&!this.data.simulationEnabled){var a=this.body;a&&(this.system.addBody(a,this.group,this.mask),this.isKinematic()?(a.forceActivationState(pc.BODYSTATE_DISABLE_DEACTIVATION),a.activate()):(a.forceActivationState(pc.BODYFLAG_ACTIVE_TAG),this.syncEntityToBody()),this.data.simulationEnabled=!0)}},disableSimulation:function(){var a=
|
|
this.body;a&&this.data.simulationEnabled&&(this.system.removeBody(a),a.forceActivationState(pc.BODYSTATE_DISABLE_SIMULATION),this.data.simulationEnabled=!1)},applyForce:function(){var c,f,e,p,k,n;switch(arguments.length){case 1:c=arguments[0].x;f=arguments[0].y;e=arguments[0].z;break;case 2:c=arguments[0].x;f=arguments[0].y;e=arguments[0].z;p=arguments[1].x;k=arguments[1].y;n=arguments[1].z;break;case 3:c=arguments[0];f=arguments[1];e=arguments[2];break;case 6:c=arguments[0],f=arguments[1],e=arguments[2],
|
|
p=arguments[3],k=arguments[4],n=arguments[5]}var q=this.body;q&&(q.activate(),b.setValue(c,f,e),void 0!==p?(a.setValue(p,k,n),q.applyForce(b,a)):q.applyForce(b,d))},applyTorque:function(){var a,c,d;switch(arguments.length){case 1:a=arguments[0].x;c=arguments[0].y;d=arguments[0].z;break;case 3:a=arguments[0];c=arguments[1];d=arguments[2];break;default:return}var f=this.body;f&&(f.activate(),b.setValue(a,c,d),f.applyTorque(b))},applyImpulse:function(){var c,f,e,p,k,n;switch(arguments.length){case 1:c=
|
|
arguments[0].x;f=arguments[0].y;e=arguments[0].z;break;case 2:c=arguments[0].x;f=arguments[0].y;e=arguments[0].z;p=arguments[1].x;k=arguments[1].y;n=arguments[1].z;break;case 3:c=arguments[0];f=arguments[1];e=arguments[2];break;case 6:c=arguments[0];f=arguments[1];e=arguments[2];p=arguments[3];k=arguments[4];n=arguments[5];break;default:return}var q=this.body;q&&(q.activate(),b.setValue(c,f,e),void 0!==p?(a.setValue(p,k,n),q.applyImpulse(b,a)):q.applyImpulse(b,d))},applyTorqueImpulse:function(){var a,
|
|
c,d;switch(arguments.length){case 1:a=arguments[0].x;c=arguments[0].y;d=arguments[0].z;break;case 3:a=arguments[0];c=arguments[1];d=arguments[2];break;default:return}var f=this.body;f&&(f.activate(),b.setValue(a,c,d),f.applyTorqueImpulse(b))},isStatic:function(){return this.type===pc.BODYTYPE_STATIC},isStaticOrKinematic:function(){return this.type===pc.BODYTYPE_STATIC||this.type===pc.BODYTYPE_KINEMATIC},isKinematic:function(){return this.type===pc.BODYTYPE_KINEMATIC},syncEntityToBody:function(){var a=
|
|
this.body;if(a){var b=this.entity.getPosition(),d=this.entity.getRotation(),f=a.getWorldTransform();f.getOrigin().setValue(b.x,b.y,b.z);c.setValue(d.x,d.y,d.z,d.w);f.setRotation(c);this.isKinematic()&&(b=this.body.getMotionState())&&b.setWorldTransform(f);a.activate()}},syncBodyToEntity:function(){var a=this.body;if(a.isActive()&&(a=a.getMotionState())){a.getWorldTransform(e);var a=e.getOrigin(),b=e.getRotation();this.entity.setPosition(a.x(),a.y(),a.z());this.entity.setRotation(b.x(),b.y(),b.z(),
|
|
b.w())}},teleport:function(){3>arguments.length?(arguments[0]&&this.entity.setPosition(arguments[0]),arguments[1]&&(arguments[1]instanceof pc.Quat?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()},_updateKinematic:function(a){this._displacement.copy(this._linearVelocity).scale(a);this.entity.translate(this._displacement);
|
|
this._displacement.copy(this._angularVelocity).scale(a);this.entity.rotate(this._displacement.x,this._displacement.y,this._displacement.z);if(this.body.getMotionState()){a=this.entity.getPosition();var b=this.entity.getRotation();e.getOrigin().setValue(a.x,a.y,a.z);c.setValue(b.x,b.y,b.z,b.w);e.setRotation(c);this.body.getMotionState().setWorldTransform(e)}},onEnable:function(){this.body||this.createBody();this.enableSimulation()},onDisable:function(){this.disableSimulation()},onSetMass:function(a,
|
|
b,c){if(a=this.data.body){(b=this.enabled&&this.entity.enabled)&&this.disableSimulation();var d=new Ammo.btVector3(0,0,0);a.getCollisionShape().calculateLocalInertia(c,d);a.setMassProps(c,d);a.updateInertiaTensor();b&&this.enableSimulation()}},onSetLinearDamping:function(a,b,c){(a=this.data.body)&&a.setDamping(c,this.data.angularDamping)},onSetAngularDamping:function(a,b,c){(a=this.data.body)&&a.setDamping(this.data.linearDamping,c)},onSetLinearFactor:function(a,c,d){if(a=this.data.body)b.setValue(d.x,
|
|
d.y,d.z),a.setLinearFactor(b)},onSetAngularFactor:function(a,c,d){if(a=this.data.body)b.setValue(d.x,d.y,d.z),a.setAngularFactor(b)},onSetFriction:function(a,b,c){(a=this.data.body)&&a.setFriction(c)},onSetRestitution:function(a,b,c){(a=this.data.body)&&a.setRestitution(c)},onSetType:function(a,b,c){c!==b&&(this.disableSimulation(),c===pc.BODYTYPE_DYNAMIC?(this.data.group=pc.BODYGROUP_DYNAMIC,this.data.mask=pc.BODYMASK_ALL):c===pc.BODYTYPE_KINEMATIC?(this.data.group=pc.BODYGROUP_KINEMATIC,this.data.mask=
|
|
pc.BODYMASK_ALL):(this.data.group=pc.BODYGROUP_STATIC,this.data.mask=pc.BODYMASK_NOT_STATIC),this.createBody())},onSetGroupOrMask:function(a,b,c){c!==b&&this.enabled&&this.entity.enabled&&(this.disableSimulation(),this.enableSimulation())},onSetBody:function(a,b,c){this.body&&this.data.simulationEnabled&&this.body.activate()}});return{RigidBodyComponent:f}}());Object.assign(pc,function(){var e,b,a={},c={},d=!1,f=function(a,b,c){this.entity=a;this.point=b;this.normal=c},g=function(a,b,c){0===arguments.length?(this.b=this.a=null,this.localPointA=new pc.Vec3,this.localPointB=new pc.Vec3,this.pointA=new pc.Vec3,this.pointB=new pc.Vec3,this.normal=new pc.Vec3):(this.a=a,this.b=b,this.localPointA=c.localPoint,this.localPointB=c.localPointOther,this.pointA=c.point,this.pointB=c.pointOther,this.normal=c.normal)},l=function(a,b,c,d,f){0===arguments.length?(this.localPoint=
|
|
new pc.Vec3,this.localPointOther=new pc.Vec3,this.point=new pc.Vec3,this.pointOther=new pc.Vec3,this.normal=new pc.Vec3):(this.localPoint=a,this.localPointOther=b,this.point=c,this.pointOther=d,this.normal=f)},h=function(a,b){this.other=a;this.contacts=b},p="enabled type mass linearDamping angularDamping linearFactor angularFactor friction restitution group mask body".split(" "),k=function(a){pc.ComponentSystem.call(this,a);this.id="rigidbody";this.description="Adds the entity to the scene's physical simulation.";
|
|
this._stats=a.stats.frame;this.ComponentType=pc.RigidBodyComponent;this.DataType=pc.RigidBodyComponentData;this.contactPointPool=new pc.AllocatePool(l,1);this.contactResultPool=new pc.AllocatePool(h,1);this.singleContactResultPool=new pc.AllocatePool(g,1);this.schema=p;this.maxSubSteps=10;this.fixedTimeStep=1/60;this.on("remove",this.onRemove,this)};k.prototype=Object.create(pc.ComponentSystem.prototype);k.prototype.constructor=k;pc.Component._buildAccessors(pc.RigidBodyComponent.prototype,p);Object.assign(k.prototype,
|
|
{onLibraryLoaded:function(){if("undefined"!==typeof Ammo){var a=new Ammo.btDefaultCollisionConfiguration,c=new Ammo.btCollisionDispatcher(a),d=new Ammo.btDbvtBroadphase,f=new Ammo.btSequentialImpulseConstraintSolver;this.dynamicsWorld=new Ammo.btDiscreteDynamicsWorld(c,d,f,a);this._ammoGravity=new Ammo.btVector3(0,-9.82,0);this.dynamicsWorld.setGravity(this._ammoGravity);e=new Ammo.btVector3;b=new Ammo.btVector3;pc.ComponentSystem.bind("update",this.onUpdate,this)}else pc.ComponentSystem.unbind("update",
|
|
this.onUpdate,this)},initializeComponentData:function(a,b,c){c="enabled mass linearDamping angularDamping linearFactor angularFactor friction restitution type group mask".split(" ");for(var d={},f=0,g=c.length;f<g;f++){var e=c[f];d[e]=b[e]}b.bodyType&&(d.type=b.bodyType,console.warn("WARNING: rigidbody.bodyType: Property is deprecated. Use type instead."));d.linearFactor&&"array"===pc.type(d.linearFactor)&&(d.linearFactor=new pc.Vec3(d.linearFactor[0],d.linearFactor[1],d.linearFactor[2]));d.angularFactor&&
|
|
"array"===pc.type(d.angularFactor)&&(d.angularFactor=new pc.Vec3(d.angularFactor[0],d.angularFactor[1],d.angularFactor[2]));pc.ComponentSystem.prototype.initializeComponentData.call(this,a,d,c)},cloneComponent:function(a,b){this.addComponent(b,{enabled:a.rigidbody.enabled,mass:a.rigidbody.mass,linearDamping:a.rigidbody.linearDamping,angularDamping:a.rigidbody.angularDamping,linearFactor:[a.rigidbody.linearFactor.x,a.rigidbody.linearFactor.y,a.rigidbody.linearFactor.z],angularFactor:[a.rigidbody.angularFactor.x,
|
|
a.rigidbody.angularFactor.y,a.rigidbody.angularFactor.z],friction:a.rigidbody.friction,restitution:a.rigidbody.restitution,type:a.rigidbody.type,group:a.rigidbody.group,mask:a.rigidbody.mask})},onRemove:function(a,b){b.body&&(this.removeBody(b.body),Ammo.destroy(b.body));b.body=null},addBody:function(a,b,c){void 0!==b&&void 0!==c?this.dynamicsWorld.addRigidBody(a,b,c):this.dynamicsWorld.addRigidBody(a);return a},removeBody:function(a){this.dynamicsWorld.removeRigidBody(a)},addConstraint:function(a){this.dynamicsWorld.addConstraint(a);
|
|
return a},removeConstraint:function(a){this.dynamicsWorld.removeConstraint(a)},setGravity:function(){var a,b,c;1===arguments.length?(a=arguments[0].x,b=arguments[0].y,c=arguments[0].z):(a=arguments[0],b=arguments[1],c=arguments[2]);this._ammoGravity.setValue(a,b,c);this.dynamicsWorld.setGravity(this._ammoGravity)},raycastFirst:function(a,c){var g=null;e.setValue(a.x,a.y,a.z);b.setValue(c.x,c.y,c.z);var h=new Ammo.ClosestRayResultCallback(e,b);this.dynamicsWorld.rayTest(e,b,h);if(h.hasHit()){var l=
|
|
h.get_m_collisionObject();if(l=Ammo.castObject(l,Ammo.btRigidBody)){var g=h.get_m_hitPointWorld(),k=h.get_m_hitNormalWorld(),g=new f(l.entity,new pc.Vec3(g.x(),g.y(),g.z()),new pc.Vec3(k.x(),k.y(),k.z()));2<arguments.length&&((0,arguments[2])(g),d||(console.warn("[DEPRECATED]: pc.RigidBodyComponentSystem#rayCastFirst no longer requires a callback. The result of the raycast is returned by the function instead."),d=!0))}}Ammo.destroy(h);return g},_storeCollision:function(b,d){var f=!1,g=b.getGuid();
|
|
a[g]=a[g]||{others:[],entity:b};0>a[g].others.indexOf(d)&&(a[g].others.push(d),f=!0);c[g]=c[g]||{others:[],entity:b};c[g].others.push(d);return f},_createContactPointFromAmmo:function(a){var b=this.contactPointPool.allocate();b.localPoint.set(a.get_m_localPointA().x(),a.get_m_localPointA().y(),a.get_m_localPointA().z());b.localPointOther.set(a.get_m_localPointB().x(),a.get_m_localPointB().y(),a.get_m_localPointB().z());b.point.set(a.getPositionWorldOnA().x(),a.getPositionWorldOnA().y(),a.getPositionWorldOnA().z());
|
|
b.pointOther.set(a.getPositionWorldOnB().x(),a.getPositionWorldOnB().y(),a.getPositionWorldOnB().z());b.normal.set(a.get_m_normalWorldOnB().x(),a.get_m_normalWorldOnB().y(),a.get_m_normalWorldOnB().z());return b},_createReverseContactPointFromAmmo:function(a){var b=this.contactPointPool.allocate();b.localPointOther.set(a.get_m_localPointA().x(),a.get_m_localPointA().y(),a.get_m_localPointA().z());b.localPoint.set(a.get_m_localPointB().x(),a.get_m_localPointB().y(),a.get_m_localPointB().z());b.pointOther.set(a.getPositionWorldOnA().x(),
|
|
a.getPositionWorldOnA().y(),a.getPositionWorldOnA().z());b.point.set(a.getPositionWorldOnB().x(),a.getPositionWorldOnB().y(),a.getPositionWorldOnB().z());b.normal.set(a.get_m_normalWorldOnB().x(),a.get_m_normalWorldOnB().y(),a.get_m_normalWorldOnB().z());return b},_createSingleContactResult:function(a,b,c){var d=this.singleContactResultPool.allocate();d.a=a;d.b=b;d.localPointA=c.localPoint;d.localPointB=c.localPointOther;d.pointA=c.point;d.pointB=c.pointOther;d.normal=c.normal;return d},_createContactResult:function(a,
|
|
b){var c=this.contactResultPool.allocate();c.other=a;c.contacts=b;return c},_cleanOldCollisions:function(){for(var b in a)if(a.hasOwnProperty(b)){for(var d=a[b].entity,f=d.collision,g=a[b].others,e=g.length;e--;){var h=g[e];if(!c[b]||0>c[b].others.indexOf(h))g.splice(e,1),f&&h.collision&&(d.rigidbody&&h.rigidbody?f.fire("collisionend",h):d.trigger&&f.fire("triggerleave",h))}0===g.length&&delete a[b]}},onUpdate:function(a){this.dynamicsWorld.stepSimulation(a,this.maxSubSteps,this.fixedTimeStep);var b=
|
|
this.store,d;for(d in b)if(b.hasOwnProperty(d)){var f=b[d].entity,g=b[d].data;g.body&&g.body.isActive()&&g.enabled&&f.enabled&&(g.type===pc.BODYTYPE_DYNAMIC?f.rigidbody.syncBodyToEntity():g.type===pc.BODYTYPE_KINEMATIC&&f.rigidbody._updateKinematic(a))}a=this.dynamicsWorld.getDispatcher();var b=a.getNumManifolds(),e;c={};for(d=0;d<b;d++){var h=a.getManifoldByIndexInternal(d),l=h.getBody0(),k=h.getBody1(),f=Ammo.castObject(l,Ammo.btRigidBody),g=Ammo.castObject(k,Ammo.btRigidBody),f=f.entity,g=g.entity;
|
|
if(f&&g){e=l.getCollisionFlags();var p=k.getCollisionFlags(),n=h.getNumContacts(),B=[],k=[],z;if(0<n)if(e&pc.BODYFLAG_NORESPONSE_OBJECT||p&pc.BODYFLAG_NORESPONSE_OBJECT)z=f.collision?f.collision.hasEvent("triggerenter")||f.collision.hasEvent("triggerleave"):!1,l=g.collision?g.collision.hasEvent("triggerenter")||g.collision.hasEvent("triggerleave"):!1,z&&(h=this._storeCollision(f,g))&&(!f.collision||p&pc.BODYFLAG_NORESPONSE_OBJECT||f.collision.fire("triggerenter",g)),l&&(h=this._storeCollision(g,f))&&
|
|
(!g.collision||e&pc.BODYFLAG_NORESPONSE_OBJECT||g.collision.fire("triggerenter",f));else if(z=f.collision?f.collision.hasEvent("collisionstart")||f.collision.hasEvent("collisionend")||f.collision.hasEvent("contact"):!1,l=g.collision?g.collision.hasEvent("collisionstart")||g.collision.hasEvent("collisionend")||g.collision.hasEvent("contact"):!1,(p=this.hasEvent("contact"))||z||l){for(e=0;e<n;e++){var A=h.getContactPoint(e),F=this._createContactPointFromAmmo(A);if(z||l)A=this._createReverseContactPointFromAmmo(A),
|
|
B.push(F),k.push(A);p&&(F=this._createSingleContactResult(f,g,F),this.fire("contact",F))}z&&(n=this._createContactResult(g,B),f.collision&&f.collision.fire("contact",n),(h=this._storeCollision(f,g))&&f.collision&&f.collision.fire("collisionstart",n));l&&(k=this._createContactResult(f,k),g.collision&&g.collision.fire("contact",k),(h=this._storeCollision(g,f))&&g.collision&&g.collision.fire("collisionstart",k))}}}this._cleanOldCollisions();this.contactPointPool.freeAll();this.contactResultPool.freeAll();
|
|
this.singleContactResultPool.freeAll()}});return{RIGIDBODY_TYPE_STATIC:"static",RIGIDBODY_TYPE_DYNAMIC:"dynamic",RIGIDBODY_TYPE_KINEMATIC:"kinematic",RIGIDBODY_CF_STATIC_OBJECT:1,RIGIDBODY_CF_KINEMATIC_OBJECT:2,RIGIDBODY_CF_NORESPONSE_OBJECT:4,RIGIDBODY_ACTIVE_TAG:1,RIGIDBODY_ISLAND_SLEEPING:2,RIGIDBODY_WANTS_DEACTIVATION:3,RIGIDBODY_DISABLE_DEACTIVATION:4,RIGIDBODY_DISABLE_SIMULATION:5,RigidBodyComponentSystem:k}}());Object.assign(pc,function(){return{RigidBodyComponentData:function(){this.enabled=!0;this.mass=1;this.angularDamping=this.linearDamping=0;this.linearFactor=new pc.Vec3(1,1,1);this.angularFactor=new pc.Vec3(1,1,1);this.friction=.5;this.restitution=0;this.type=pc.BODYTYPE_STATIC;this.group=pc.BODYGROUP_STATIC;this.mask=pc.BODYMASK_NOT_STATIC;this.body=null;this.simulationEnabled=!1}}}());Object.assign(pc,function(){var e,b,a=function(a,d,f){this.entity=d.entity;this.component=d;this.app=a;"undefined"!==typeof Ammo&&(e=new Ammo.btVector3,b=new Ammo.btQuaternion);this.initialize(f)};Object.assign(a.prototype,{initialize:function(a){var c=this.entity;if((a=a.shape)&&"undefined"!==typeof Ammo){c.trigger&&c.trigger.destroy();var f=new Ammo.btVector3(0,0,0);a.calculateLocalInertia(1,f);var g=c.getPosition(),l=c.getRotation();b.setValue(l.x,l.y,l.z,l.w);l=new Ammo.btTransform;l.setIdentity();
|
|
l.getOrigin().setValue(g.x,g.y,g.z);l.setRotation(b);g=new Ammo.btDefaultMotionState(l);a=new Ammo.btRigidBodyConstructionInfo(1,g,a,f);this.body=a=new Ammo.btRigidBody(a);a.setRestitution(0);a.setFriction(0);a.setDamping(0,0);e.setValue(0,0,0);a.setLinearFactor(e);a.setAngularFactor(e);a.setCollisionFlags(a.getCollisionFlags()|pc.BODYFLAG_NORESPONSE_OBJECT);a.entity=c;this.component.enabled&&c.enabled&&this.enable()}},destroy:function(){this.body&&this.app.systems.rigidbody.removeBody(this.body)},
|
|
syncEntityToBody:function(){var a=this.body;if(a){var d=this.entity.getPosition(),f=this.entity.getRotation(),g=a.getWorldTransform();g.getOrigin().setValue(d.x,d.y,d.z);b.setValue(f.x,f.y,f.z,f.w);g.setRotation(b);a.activate()}},enable:function(){var a=this.body;a&&(this.app.systems.rigidbody.addBody(a,pc.BODYGROUP_TRIGGER,pc.BODYMASK_NOT_STATIC^pc.BODYGROUP_TRIGGER),a.forceActivationState(pc.BODYSTATE_ACTIVE_TAG),a.activate(),this.syncEntityToBody())},disable:function(){var a=this.body;a&&(this.app.systems.rigidbody.removeBody(a),
|
|
a.forceActivationState(pc.BODYSTATE_DISABLE_SIMULATION))}});return{Trigger:a}}());Object.assign(pc,function(){var e=function(b,a){pc.Component.call(this,b,a);this.on("set_type",this.onSetType,this);this.on("set_halfExtents",this.onSetHalfExtents,this);this.on("set_radius",this.onSetRadius,this);this.on("set_height",this.onSetHeight,this);this.on("set_axis",this.onSetAxis,this);this.on("set_asset",this.onSetAsset,this);this.on("set_model",this.onSetModel,this)};e.prototype=Object.create(pc.Component.prototype);e.prototype.constructor=e;Object.assign(e.prototype,{onSetType:function(b,
|
|
a,c){a!==c&&this.system.changeType(this,a,c)},onSetHalfExtents:function(b,a,c){this.data.initialized&&"box"===this.data.type&&this.system.recreatePhysicalShapes(this)},onSetRadius:function(b,a,c){!this.data.initialized||"sphere"!==this.data.type&&"capsule"!==this.data.type&&"cylinder"!==this.data.type||this.system.recreatePhysicalShapes(this)},onSetHeight:function(b,a,c){!this.data.initialized||"capsule"!==this.data.type&&"cylinder"!==this.data.type||this.system.recreatePhysicalShapes(this)},onSetAxis:function(b,
|
|
a,c){!this.data.initialized||"capsule"!==this.data.type&&"cylinder"!==this.data.type||this.system.recreatePhysicalShapes(this)},onSetAsset:function(b,a,c){b=this.system.app.assets;a&&(a=b.get(a))&&a.off("remove",this.onAssetRemoved,this);c&&(c instanceof pc.Asset&&(this.data.asset=c.id),a=b.get(this.data.asset))&&(a.off("remove",this.onAssetRemoved,this),a.on("remove",this.onAssetRemoved,this));this.data.initialized&&"mesh"===this.data.type&&(c||(this.data.model=null),this.system.recreatePhysicalShapes(this))},
|
|
onSetModel:function(b,a,c){this.data.initialized&&"mesh"===this.data.type&&this.system.implementations.mesh.doRecreatePhysicalShape(this)},onAssetRemoved:function(b){b.off("remove",this.onAssetRemoved,this);this.data.asset===b.id&&(this.asset=null)},onEnable:function(){if("mesh"===this.data.type&&this.data.asset&&this.data.initialized){var b=this.system.app.assets.get(this.data.asset);if(b&&(!b.resource||!this.data.shape)){this.system.recreatePhysicalShapes(this);return}}this.entity.trigger?this.entity.trigger.enable():
|
|
this.entity.rigidbody&&this.entity.rigidbody.enabled&&this.entity.rigidbody.enableSimulation()},onDisable:function(){this.entity.trigger?this.entity.trigger.disable():this.entity.rigidbody&&this.entity.rigidbody.disableSimulation()}});return{CollisionComponent:e}}());Object.assign(pc,function(){var e="enabled type halfExtents radius axis height asset shape model".split(" "),b=function(a){this.system=a};Object.assign(b.prototype,{beforeInitialize:function(a,b){b.shape=this.createPhysicalShape(a.entity,b);b.model=new pc.Model;b.model.graph=new pc.GraphNode},afterInitialize:function(a,b){this.recreatePhysicalShapes(a);a.data.initialized=!0},reset:function(a,b){this.beforeInitialize(a,b);this.afterInitialize(a,b)},recreatePhysicalShapes:function(a){var b=a.entity,
|
|
c=a.data;"undefined"!==typeof Ammo&&(c.shape=this.createPhysicalShape(a.entity,c),b.rigidbody?(b.rigidbody.disableSimulation(),b.rigidbody.createBody()):b.trigger?b.trigger.initialize(c):b.trigger=new pc.Trigger(this.system.app,a,c))},createPhysicalShape:function(a,b){},updateTransform:function(a,b,c,d){a.entity.trigger&&a.entity.trigger.syncEntityToBody()},remove:function(a,b){var c=this.system.app;a.rigidbody&&a.rigidbody.body&&(c.systems.rigidbody.removeBody(a.rigidbody.body),a.rigidbody.disableSimulation());
|
|
a.trigger&&(a.trigger.destroy(),delete a.trigger);c.scene.containsModel(b.model)&&(c.root.removeChild(b.model.graph),c.scene.removeModel(b.model))},clone:function(a,b){var c=this.system.store[a.getGuid()];return this.system.addComponent(b,{enabled:c.data.enabled,type:c.data.type,halfExtents:[c.data.halfExtents.x,c.data.halfExtents.y,c.data.halfExtents.z],radius:c.data.radius,axis:c.data.axis,height:c.data.height,asset:c.data.asset,model:c.data.model})}});var a=function(a){this.system=a};a.prototype=
|
|
Object.create(b.prototype);a.prototype.constructor=a;Object.assign(a.prototype,{createPhysicalShape:function(a,b){if("undefined"!==typeof Ammo){var c=b.halfExtents,c=new Ammo.btVector3(c?c.x:.5,c?c.y:.5,c?c.z:.5);return new Ammo.btBoxShape(c)}}});var c=function(a){this.system=a};c.prototype=Object.create(b.prototype);c.prototype.constructor=c;Object.assign(c.prototype,{createPhysicalShape:function(a,b){if("undefined"!==typeof Ammo)return new Ammo.btSphereShape(b.radius)}});var d=function(a){this.system=
|
|
a};d.prototype=Object.create(b.prototype);d.prototype.constructor=d;Object.assign(d.prototype,{createPhysicalShape:function(a,b){var c=null,d=void 0!==b.axis?b.axis:1,f=b.radius||.5,g=Math.max((b.height||2)-2*f,0);if("undefined"!==typeof Ammo)switch(d){case 0:c=new Ammo.btCapsuleShapeX(f,g);break;case 1:c=new Ammo.btCapsuleShape(f,g);break;case 2:c=new Ammo.btCapsuleShapeZ(f,g)}return c}});var f=function(a){this.system=a};f.prototype=Object.create(b.prototype);f.prototype.constructor=f;Object.assign(f.prototype,
|
|
{createPhysicalShape:function(a,b){var c;c=null;var d=void 0!==b.axis?b.axis:1,f=void 0!==b.radius?b.radius:.5,g=void 0!==b.height?b.height:1;if("undefined"!==typeof Ammo)switch(d){case 0:c=new Ammo.btVector3(.5*g,f,f);c=new Ammo.btCylinderShapeX(c);break;case 1:c=new Ammo.btVector3(f,.5*g,f);c=new Ammo.btCylinderShape(c);break;case 2:c=new Ammo.btVector3(f,f,.5*g),c=new Ammo.btCylinderShapeZ(c)}return c}});var g=function(a){this.system=a};g.prototype=Object.create(b.prototype);g.prototype.constructor=
|
|
g;Object.assign(g.prototype,{beforeInitialize:function(a,b){},createPhysicalShape:function(a,b){if("undefined"!==typeof Ammo&&b.model){var c=b.model,d=new Ammo.btCompoundShape,f,g;for(f=0;f<c.meshInstances.length;f++){var e=c.meshInstances[f],h=e.mesh,l=h.indexBuffer[pc.RENDERSTYLE_SOLID],u=h.vertexBuffer,x=u.getFormat(),v=x.size/4,w;for(g=0;g<x.elements.length;g++){var y=x.elements[g];y.name===pc.SEMANTIC_POSITION&&(w=new Float32Array(u.lock(),y.offset))}var l=new Uint16Array(l.lock()),u=h.primitive[0].count/
|
|
3,x=new Ammo.btVector3,y=new Ammo.btVector3,D=new Ammo.btVector3,B,z,A=h.primitive[0].base,F=new Ammo.btTriangleMesh;for(g=0;g<u;g++)h=l[A+3*g]*v,B=l[A+3*g+1]*v,z=l[A+3*g+2]*v,x.setValue(w[h],w[h+1],w[h+2]),y.setValue(w[B],w[B+1],w[B+2]),D.setValue(w[z],w[z+1],w[z+2]),F.addTriangle(x,y,D,!0);g=new Ammo.btBvhTriangleMeshShape(F,!0);v=e.node.getWorldTransform().getScale();g.setLocalScaling(new Ammo.btVector3(v.x,v.y,v.z));v=e.node.getPosition();e=e.node.getRotation();l=new Ammo.btTransform;l.setIdentity();
|
|
l.getOrigin().setValue(v.x,v.y,v.z);v=new Ammo.btQuaternion;v.setValue(e.x,e.y,e.z,e.w);l.setRotation(v);d.addChildShape(l,g)}c=a.getWorldTransform().getScale();f=new Ammo.btVector3;f.setValue(c.x,c.y,c.z);d.setLocalScaling(f);return d}},recreatePhysicalShapes:function(a){null!==a.data.asset&&a.enabled&&a.entity.enabled?this.loadModelAsset(a):this.doRecreatePhysicalShape(a)},loadModelAsset:function(a){var b=this,c=a.data.asset,d=a.data,f=this.system.app.assets,g=f.get(c);if(g)g.ready(function(c){d.model=
|
|
c.resource;b.doRecreatePhysicalShape(a)}),f.load(g);else f.once("add:"+c,function(c){c.ready(function(c){d.model=c.resource;b.doRecreatePhysicalShape(a)});f.load(c)})},doRecreatePhysicalShape:function(a){var b=a.entity,c=a.data;c.model?(c.shape&&Ammo.destroy(c.shape),c.shape=this.createPhysicalShape(b,c),b.rigidbody?b.rigidbody.createBody():b.trigger?b.trigger.initialize(c):b.trigger=new pc.Trigger(this.system.app,a,c)):this.remove(b,c)},updateTransform:function(a,b,c,d){if(a.shape){var f=a.entity.getWorldTransform().getScale(),
|
|
g=a.shape.getLocalScaling();f.x===g.x()&&f.y===g.y()&&f.z===g.z()||this.doRecreatePhysicalShape(a)}pc.CollisionSystemImpl.prototype.updateTransform.call(this,a,b,c,d)}});b=function(a){pc.ComponentSystem.call(this,a);this.id="collision";this.description="Specifies a collision volume.";this.ComponentType=pc.CollisionComponent;this.DataType=pc.CollisionComponentData;this.schema=e;this.implementations={};this.on("remove",this.onRemove,this);pc.ComponentSystem.bind("update",this.onUpdate,this)};b.prototype=
|
|
Object.create(pc.ComponentSystem.prototype);b.prototype.constructor=b;pc.Component._buildAccessors(pc.CollisionComponent.prototype,e);Object.assign(b.prototype,{onLibraryLoaded:function(){"undefined"===typeof Ammo&&pc.ComponentSystem.unbind("update",this.onUpdate,this)},initializeComponentData:function(a,b,c){c="type halfExtents radius axis height shape model asset enabled".split(" ");for(var d={},f=0,g=c.length;f<g;f++){var e=c[f];d[e]=b[e]}b.hasOwnProperty("asset")?(b=c.indexOf("model"),-1!==b&&
|
|
c.splice(b,1)):b.hasOwnProperty("model")&&(b=c.indexOf("asset"),-1!==b&&c.splice(b,1));d.type||(d.type=a.data.type);a.data.type=d.type;d.halfExtents&&"array"===pc.type(d.halfExtents)&&(d.halfExtents=new pc.Vec3(d.halfExtents[0],d.halfExtents[1],d.halfExtents[2]));b=this._createImplementation(d.type);b.beforeInitialize(a,d);pc.ComponentSystem.prototype.initializeComponentData.call(this.system,a,d,c);b.afterInitialize(a,d)},_createImplementation:function(b){if(void 0===this.implementations[b]){var e;
|
|
switch(b){case "box":e=new a(this);break;case "sphere":e=new c(this);break;case "capsule":e=new d(this);break;case "cylinder":e=new f(this);break;case "mesh":e=new g(this)}this.implementations[b]=e}return this.implementations[b]},_getImplementation:function(a){return this.implementations[a.collision.data.type]},cloneComponent:function(a,b){return this._getImplementation(a).clone(a,b)},onRemove:function(a,b){this.implementations[b.type].remove(a,b)},onUpdate:function(a){var b,c,d=this.store;for(b in d)a=
|
|
d[b].entity,c=d[b].data,c.enabled&&a.enabled&&!a.rigidbody&&a.trigger&&a.trigger.syncEntityToBody()},onTransformChanged:function(a,b,c,d){this.implementations[a.data.type].updateTransform(a,b,c,d)},changeType:function(a,b,c){this.implementations[b].remove(a.entity,a.data);this._createImplementation(c).reset(a,a.data)},recreatePhysicalShapes:function(a){this.implementations[a.data.type].recreatePhysicalShapes(a)}});return{CollisionComponentSystem:b}}());Object.assign(pc,function(){return{CollisionComponentData:function(){this.enabled=!0;this.type="box";this.halfExtents=new pc.Vec3(.5,.5,.5);this.radius=.5;this.axis=1;this.height=2;this.model=this.shape=this.asset=null;this.initialized=!1}}}());Object.assign(pc,function(){var e="emitterExtents emitterRadius emitterExtentsInner emitterRadiusInner loop initialVelocity animSpeed normalMap particleNormal".split(" "),b="numParticles lifetime rate rate2 startAngle startAngle2 lighting halfLambert intensity wrap wrapBounds depthWrite noFog sort stretch alignToMotion preWarm emitterShape animTilesX animTilesY animNumFrames animLoop colorMap localSpace orientation".split(" "),a="scaleGraph scaleGraph2 colorGraph colorGraph2 alphaGraph alphaGraph2 velocityGraph velocityGraph2 localVelocityGraph localVelocityGraph2 rotationSpeedGraph rotationSpeedGraph2 radialSpeedGraph radialSpeedGraph2".split(" "),
|
|
c=["colorMapAsset","normalMapAsset","meshAsset"],d,f=function(c,d){pc.Component.call(this,c,d);this.on("set_colorMapAsset",this.onSetColorMapAsset,this);this.on("set_normalMapAsset",this.onSetNormalMapAsset,this);this.on("set_meshAsset",this.onSetMeshAsset,this);this.on("set_mesh",this.onSetMesh,this);this.on("set_loop",this.onSetLoop,this);this.on("set_blendType",this.onSetBlendType,this);this.on("set_depthSoftening",this.onSetDepthSoftening,this);this.on("set_layers",this.onSetLayers,this);e.forEach(function(a){this.on("set_"+
|
|
a,this.onSetSimpleProperty,this)}.bind(this));b.forEach(function(a){this.on("set_"+a,this.onSetComplexProperty,this)}.bind(this));a.forEach(function(a){this.on("set_"+a,this.onSetGraphProperty,this)}.bind(this));this._requestedDepth=!1};f.prototype=Object.create(pc.Component.prototype);f.prototype.constructor=f;Object.assign(f.prototype,{addModelToLayers:function(){if(this.data.model)for(var a,b=0;b<this.layers.length;b++)if(a=this.system.app.scene.layers.getLayerById(this.layers[b]))a.addMeshInstances(this.data.model.meshInstances),
|
|
this.emitter._layer=a},removeModelFromLayers:function(a){if(this.data.model)for(var b=0;b<this.layers.length;b++)(a=this.system.app.scene.layers.getLayerById(this.layers[b]))&&a.removeMeshInstances(this.data.model.meshInstances)},onSetLayers:function(a,b,c){if(this.data.model){var d;for(a=0;a<b.length;a++)(d=this.system.app.scene.layers.getLayerById(b[a]))&&d.removeMeshInstances(this.data.model.meshInstances);if(this.enabled&&this.entity.enabled)for(a=0;a<c.length;a++)(d=this.system.app.scene.layers.getLayerById(c[a]))&&
|
|
d.addMeshInstances(this.data.model.meshInstances)}},onLayersChanged:function(a,b){this.addModelToLayers();a.off("add",this.onLayerAdded,this);a.off("remove",this.onLayerRemoved,this);b.on("add",this.onLayerAdded,this);b.on("remove",this.onLayerRemoved,this)},onLayerAdded:function(a){this.data.model&&(0>this.layers.indexOf(a.id)||a.addMeshInstances(this.data.model.meshInstances))},onLayerRemoved:function(a){this.data.model&&(0>this.layers.indexOf(a.id)||a.removeMeshInstances(this.data.model.meshInstances))},
|
|
_bindColorMapAsset:function(a){a.once("remove",this._onColorMapRemoved,this);a.resource?this.colorMap=a.resource:(a.once("load",this._onColorMapLoad,this),this.enabled&&this.entity.enabled&&this.system.app.assets.load(a))},_unbindColorMapAsset:function(a){a.off("remove",this._onColorMapRemoved,this);a.off("load",this._onColorMapLoad,this)},_onColorMapLoad:function(a){this.colorMap=a.resource},_onColorMapRemoved:function(a){this.colorMapAsset=null},onSetColorMapAsset:function(a,b,c){var d=this;a=this.system.app.assets;
|
|
b&&(b=a.get(b))&&this._unbindColorMapAsset(b);if(c)if(c instanceof pc.Asset&&(c=this.data.colorMapAsset=c.id),b=a.get(c))d._bindColorMapAsset(b);else a.once("add:"+c,function(a){d._bindColorMapAsset(a)});else this.colorMap=null},_bindNormalMapAsset:function(a){a.once("remove",this._onNormalMapRemoved,this);a.resource?this.normalMap=a.resource:(a.once("load",this._onNormalMapLoad,this),this.enabled&&this.entity.enabled&&this.system.app.assets.load(a))},_unbindNormalMapAsset:function(a){a.off("remove",
|
|
this._onNormalMapRemoved,this);a.off("load",this._onNormalMapLoad,this)},_onNormalMapLoad:function(a){this.normalMap=a.resource},_onNormalMapRemoved:function(a){this.normalMapAsset=null},onSetNormalMapAsset:function(a,b,c){var d=this;a=this.system.app.assets;b&&(b=a.get(b))&&this._unbindNormalMapAsset(b);if(c)if(c instanceof pc.Asset&&(c=this.data.normalMapAsset=c.id),b=a.get(c))d._bindNormalMapAsset(b);else a.once("add:"+c,function(a){d._bindNormalMapAsset(a)});else this.normalMap=null},_bindMeshAsset:function(a){a.on("remove",
|
|
this._onMeshAssetRemoved,this);a.on("load",this._onMeshAssetLoad,this)},_unbindMeshAsset:function(a){a.off("remove",this._onMeshAssetRemoved,this);a.off("load",this._onMeshAssetLoad,this)},_onMeshAssetLoad:function(a){this._onMeshChanged(a.resource)},onSetMeshAsset:function(a,b,c){a=this.system.app.assets;b&&(b=a.get(b))&&this._unbindMeshAsset(b);if(c){if(c instanceof pc.Asset&&(c=this.data.meshAsset=c.id),b=a.get(c))this._bindMeshAsset(b),b.resource?this._onMeshChanged(b.resource):a.load(b)}else this._onMeshChanged(null)},
|
|
onSetMesh:function(a,b,c){!c||c instanceof pc.Asset||"number"===typeof c?this.meshAsset=c:this._onMeshChanged(c)},_onMeshChanged:function(a){!a||a instanceof pc.Mesh||(a=a.meshInstances[0]?a.meshInstances[0].mesh:null);this.data.mesh=a;this.emitter&&(this.emitter.mesh=a,this.emitter.resetMaterial(),this.rebuild())},onMeshAssetRemoved:function(a){a.off("remove",this.onMeshAssetRemoved,this);this.mesh=null},onSetLoop:function(a,b,c){this.emitter&&(this.emitter[a]=c,this.emitter.resetTime())},onSetBlendType:function(a,
|
|
b,c){this.emitter&&(this.emitter[a]=c,this.emitter.material.blendType=c,this.emitter.resetMaterial(),this.rebuild())},_requestDepth:function(){this._requestedDepth||(d||(d=this.system.app.scene.layers.getLayerById(pc.LAYERID_DEPTH)),d&&(d.incrementCounter(),this._requestedDepth=!0))},_releaseDepth:function(){this._requestedDepth&&d&&(d.decrementCounter(),this._requestedDepth=!1)},onSetDepthSoftening:function(a,b,c){b!==c&&(c?this.enabled&&this.entity.enabled&&this._requestDepth():this.enabled&&this.entity.enabled&&
|
|
this._releaseDepth(),this.emitter&&(this.emitter[a]=c),this.emitter&&(this.reset(),this.emitter.resetMaterial(),this.rebuild()))},onSetSimpleProperty:function(a,b,c){this.emitter&&(this.emitter[a]=c,this.emitter.resetMaterial())},onSetComplexProperty:function(a,b,c){this.emitter&&(this.emitter[a]=c,this.reset(),this.emitter.resetMaterial(),this.rebuild())},onSetGraphProperty:function(a,b,c){this.emitter&&(this.emitter[a]=c,this.emitter.rebuildGraphs(),this.emitter.resetMaterial())},onEnable:function(){for(var a=
|
|
this.data,b=0,d=c.length;b<d;b++){var f=a[c[b]];if(f){if(!(f instanceof pc.Asset))if(0<=parseInt(f,10))f=this.system.app.assets.get(f);else continue;f&&!f.resource&&this.system.app.assets.load(f)}}this.emitter||(b=a.mesh,b instanceof pc.Mesh||(b=null),this.emitter=new pc.ParticleEmitter(this.system.app.graphicsDevice,{numParticles:a.numParticles,emitterExtents:a.emitterExtents,emitterExtentsInner:a.emitterExtentsInner,emitterRadius:a.emitterRadius,emitterRadiusInner:a.emitterRadiusInner,emitterShape:a.emitterShape,
|
|
initialVelocity:a.initialVelocity,wrap:a.wrap,localSpace:a.localSpace,wrapBounds:a.wrapBounds,lifetime:a.lifetime,rate:a.rate,rate2:a.rate2,orientation:a.orientation,particleNormal:a.particleNormal,animTilesX:a.animTilesX,animTilesY:a.animTilesY,animNumFrames:a.animNumFrames,animSpeed:a.animSpeed,animLoop:a.animLoop,startAngle:a.startAngle,startAngle2:a.startAngle2,scaleGraph:a.scaleGraph,scaleGraph2:a.scaleGraph2,colorGraph:a.colorGraph,colorGraph2:a.colorGraph2,alphaGraph:a.alphaGraph,alphaGraph2:a.alphaGraph2,
|
|
localVelocityGraph:a.localVelocityGraph,localVelocityGraph2:a.localVelocityGraph2,velocityGraph:a.velocityGraph,velocityGraph2:a.velocityGraph2,rotationSpeedGraph:a.rotationSpeedGraph,rotationSpeedGraph2:a.rotationSpeedGraph2,radialSpeedGraph:a.radialSpeedGraph,radialSpeedGraph2:a.radialSpeedGraph2,colorMap:a.colorMap,normalMap:a.normalMap,loop:a.loop,preWarm:a.preWarm,sort:a.sort,stretch:a.stretch,alignToMotion:a.alignToMotion,lighting:a.lighting,halfLambert:a.halfLambert,intensity:a.intensity,depthSoftening:a.depthSoftening,
|
|
scene:this.system.app.scene,mesh:b,depthWrite:a.depthWrite,noFog:a.noFog,node:this.entity,blendType:a.blendType}),this.emitter.meshInstance.node=this.entity,this.psys=new pc.Model,this.psys.graph=this.entity,this.psys.emitter=this.emitter,this.psys.meshInstances=[this.emitter.meshInstance],a.model=this.psys,this.emitter.psys=this.psys,a.autoPlay||(this.pause(),this.emitter.meshInstance.visible=!1));a.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&&a.depthSoftening&&this._requestDepth()},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)},reset:function(){this.emitter&&this.emitter.reset()},stop:function(){this.emitter&&(this.emitter.loop=!1,this.emitter.resetTime(),this.emitter.addTime(0,!0))},pause:function(){this.data.paused=!0},unpause:function(){this.data.paused=!1},play:function(){this.data.paused=!1;this.emitter&&(this.emitter.meshInstance.visible=!0,this.emitter.loop=this.data.loop,this.emitter.resetTime())},
|
|
isPlaying:function(){return this.data.paused?!1:this.emitter&&this.emitter.loop?!0:Date.now()<=this.emitter.endTime},rebuild:function(){var a=this.enabled;this.enabled=!1;this.emitter&&(this.emitter.rebuild(),this.emitter.meshInstance.node=this.entity,this.data.model.meshInstances=[this.emitter.meshInstance]);this.enabled=a},onRemove:function(){var a=this.data;a.model&&(this.entity.removeChild(a.model.getGraph()),a.model.destroy(),a.model=null);this.emitter&&(this.emitter.destroy(),this.emitter=null);
|
|
for(var b=0;b<c.length;b++){var d=c[b];a[d]&&(this[d]=null)}this.off()}});return{ParticleSystemComponent:f}}());Object.assign(pc,function(){var e="enabled autoPlay numParticles lifetime rate rate2 startAngle startAngle2 loop preWarm lighting halfLambert intensity depthWrite noFog depthSoftening sort blendType stretch alignToMotion emitterShape emitterExtents emitterExtentsInner emitterRadius emitterRadiusInner initialVelocity wrap wrapBounds localSpace colorMapAsset normalMapAsset mesh meshAsset orientation particleNormal localVelocityGraph localVelocityGraph2 velocityGraph velocityGraph2 rotationSpeedGraph rotationSpeedGraph2 radialSpeedGraph radialSpeedGraph2 scaleGraph scaleGraph2 colorGraph colorGraph2 alphaGraph alphaGraph2 colorMap normalMap animTilesX animTilesY animNumFrames animSpeed animLoop layers".split(" "),
|
|
b=function(a){pc.ComponentSystem.call(this,a);this.id="particlesystem";this.description="Updates and renders particle system in the scene.";this.ComponentType=pc.ParticleSystemComponent;this.DataType=pc.ParticleSystemComponentData;this.schema=e;this.propertyTypes={emitterExtents:"vec3",emitterExtentsInner:"vec3",particleNormal:"vec3",wrapBounds:"vec3",localVelocityGraph:"curveset",localVelocityGraph2:"curveset",velocityGraph:"curveset",velocityGraph2:"curveset",colorGraph:"curveset",colorGraph2:"curveset",
|
|
alphaGraph:"curve",alphaGraph2:"curve",rotationSpeedGraph:"curve",rotationSpeedGraph2:"curve",radialSpeedGraph:"curve",radialSpeedGraph2:"curve",scaleGraph:"curve",scaleGraph2:"curve"};this.on("beforeremove",this.onRemove,this);pc.ComponentSystem.bind("update",this.onUpdate,this)};b.prototype=Object.create(pc.ComponentSystem.prototype);b.prototype.constructor=b;pc.Component._buildAccessors(pc.ParticleSystemComponent.prototype,e);Object.assign(b.prototype,{initializeComponentData:function(a,b,d){var c=
|
|
{};d=[];var g=this.propertyTypes,e;if(b.mesh instanceof pc.Asset||"number"===typeof b.mesh)b.meshAsset=b.mesh,delete b.mesh;for(var h in b)b.hasOwnProperty(h)&&(d.push(h),c[h]=b[h]),"vec3"===g[h]?"array"===pc.type(c[h])&&(c[h]=new pc.Vec3(c[h][0],c[h][1],c[h][2])):"curve"===g[h]?c[h]instanceof pc.Curve||(e=c[h].type,c[h]=new pc.Curve(c[h].keys),c[h].type=e):"curveset"!==g[h]||c[h]instanceof pc.CurveSet||(e=c[h].type,c[h]=new pc.CurveSet(c[h].keys),c[h].type=e),c.layers&&"array"===pc.type(c.layers)&&
|
|
(c.layers=c.layers.slice(0));pc.ComponentSystem.prototype.initializeComponentData.call(this,a,c,d)},cloneComponent:function(a,b){for(var c=a.particlesystem.data,f=this.schema,g={},e=0,h=f.length;e<h;e++){var p=f[e],k=c[p];k instanceof pc.Vec3||k instanceof pc.Curve||k instanceof pc.CurveSet?(k=k.clone(),g[p]=k):"layers"===p?g.layers=c.layers.slice(0):null!==k&&void 0!==k&&(g[p]=k)}return this.addComponent(b,g)},onUpdate:function(a){var b=this.store,d,f,g,e,h=this.app.stats.particles,p;for(p in b)if(b.hasOwnProperty(p)){e=
|
|
b[p];f=e.entity;var k=e.data;if(k.enabled&&f.enabled){var n=k.model.emitter;if(n.meshInstance.visible){if(n.lighting){var q,m=k.layers;for(f=0;f<m.length;f++)if(e=this.app.scene.layers.getLayerById(m[f])){e._lightCube||(e._lightCube=new Float32Array(18));q=e._lightCube;for(f=0;6>f;f++)q[3*f]=this.app.scene.ambientLight.r,q[3*f+1]=this.app.scene.ambientLight.g,q[3*f+2]=this.app.scene.ambientLight.b;var r=e._sortedLights[pc.LIGHTTYPE_DIRECTIONAL];for(g=0;g<r.length;g++)for(e=0;6>e;e++){var t=Math.max(n.lightCubeDir[e].dot(r[g]._direction),
|
|
0)*r[g]._intensity;q[3*e]+=r[g]._color.r*t;q[3*e+1]+=r[g]._color.g*t;q[3*e+2]+=r[g]._color.b*t}}n.constantLightCube.setValue(q)}if(!k.paused){n.simTime+=a;n.simTime>n.fixedTimeStep&&(d=Math.floor(n.simTime/n.fixedTimeStep),n.simTime-=d*n.fixedTimeStep);if(d){d=Math.min(d,n.maxSubSteps);for(f=0;f<d;f++)n.addTime(n.fixedTimeStep,!1);h._updatesPerFrame+=d;h._frameTime+=n._addTimeTime;n._addTimeTime=0}n.finishFrame()}}}}},onRemove:function(a,b){b.onRemove()}});return{ParticleSystemComponentSystem:b}}());Object.assign(pc,function(){return{ParticleSystemComponentData:function(){this.rate=this.numParticles=1;this.rate2=null;this.startAngle=0;this.startAngle2=null;this.lifetime=50;this.emitterExtents=new pc.Vec3;this.emitterExtentsInner=new pc.Vec3;this.emitterRadiusInner=this.emitterRadius=0;this.emitterShape=pc.EMITTERSHAPE_BOX;this.initialVelocity=0;this.wrapBounds=new pc.Vec3;this.localSpace=!1;this.normalMapAsset=this.normalMap=this.colorMapAsset=this.colorMap=null;this.loop=!0;this.preWarm=!1;
|
|
this.sort=0;this.mode=pc.PARTICLEMODE_GPU;this.scene=null;this.halfLambert=this.lighting=!1;this.intensity=1;this.stretch=0;this.alignToMotion=!1;this.depthSoftening=0;this.mesh=this.meshAsset=null;this.noFog=this.depthWrite=!1;this.orientation=pc.PARTICLEORIENTATION_SCREEN;this.particleNormal=new pc.Vec3(0,1,0);this.animSpeed=this.animNumFrames=this.animTilesY=this.animTilesX=1;this.animLoop=!0;this.radialSpeedGraph2=this.radialSpeedGraph=this.rotationSpeedGraph2=this.rotationSpeedGraph=this.velocityGraph2=
|
|
this.velocityGraph=this.localVelocityGraph2=this.localVelocityGraph=this.alphaGraph2=this.alphaGraph=this.colorGraph2=this.colorGraph=this.scaleGraph2=this.scaleGraph=null;this.blendType=pc.BLEND_NORMAL;this.model=null;this.enabled=!0;this.paused=!1;this.autoPlay=!0;this.layers=[pc.LAYERID_WORLD]}}}());Object.assign(pc,function(){var e=function(b,a){this._component=b;this._frame=0;this._spriteAsset=this._sprite=null;this.spriteAsset=a.spriteAsset;this.name=a.name;this.fps=a.fps||0;this.loop=a.loop||!1;this._paused=this._playing=!1;this._time=0;pc.events.attach(this)};Object.assign(e.prototype,{_onSpriteAssetAdded:function(b){this._component.system.app.assets.off("add:"+b.id,this._onSpriteAssetAdded,this);this._spriteAsset===b.id&&this._bindSpriteAsset(b)},_bindSpriteAsset:function(b){b.on("load",
|
|
this._onSpriteAssetLoad,this);b.on("remove",this._onSpriteAssetRemove,this);b.resource?this._onSpriteAssetLoad(b):this._component.system.app.assets.load(b)},_unbindSpriteAsset:function(b){b.off("load",this._onSpriteAssetLoad,this);b.off("remove",this._onSpriteAssetRemove,this);b.resource&&b.resource.atlas&&this._component.system.app.assets.off("load:"+b.data.textureAtlasAsset,this._onTextureAtlasLoad,this)},_onSpriteAssetLoad:function(b){if(b.resource)if(b.resource.atlas)this.sprite=b.resource;else{b=
|
|
b.data.textureAtlasAsset;var a=this._component.system.app.assets;a.off("load:"+b,this._onTextureAtlasLoad,this);a.once("load:"+b,this._onTextureAtlasLoad,this)}else this.sprite=null},_onTextureAtlasLoad:function(b){b=this._spriteAsset;b instanceof pc.Asset?this._onSpriteAssetLoad(b):this._onSpriteAssetLoad(this._component.system.app.assets.get(b))},_onSpriteAssetRemove:function(b){this.sprite=null},_onSpriteMeshesChange:function(){this._component.currentClip===this&&this._component._showFrame(this.frame)},
|
|
_onSpritePpuChanged:function(){this._component.currentClip===this&&this.sprite.renderMode!==pc.SPRITE_RENDERMODE_SIMPLE&&this._component._showFrame(this.frame)},_update:function(b){if(0!==this.fps&&this._playing&&!this._paused&&this._sprite){var a=this._time+b*this._component.speed*(0>this.fps?-1:1),c=this.duration;b=a>c||0>a;this._setTime(a);a=this._sprite?Math.floor(this._sprite.frameKeys.length*this._time/c):0;a!==this._frame&&this._setFrame(a);b&&(this.loop?(this.fire("loop"),this._component.fire("loop",
|
|
this)):(this._paused=this._playing=!1,this.fire("end"),this._component.fire("end",this)))}},_setTime:function(b){this._time=b;b=this.duration;0>this._time?this._time=this.loop?this._time%b+b:0:this._time>b&&(this._time=this.loop?this._time%b:b)},_setFrame:function(b){this._frame=this._sprite?pc.math.clamp(b,0,this._sprite.frameKeys.length-1):b;this._component.currentClip===this&&this._component._showFrame(this._frame)},_destroy:function(){this._sprite&&(this.sprite=null);this._spriteAsset&&(this.spriteAsset=
|
|
null)},play:function(){this._playing||(this._playing=!0,this._paused=!1,this.frame=0,this.fire("play"),this._component.fire("play",this))},pause:function(){this._playing&&!this._paused&&(this._paused=!0,this.fire("pause"),this._component.fire("pause",this))},resume:function(){this._paused&&(this._paused=!1,this.fire("resume"),this._component.fire("resume",this))},stop:function(){this._playing&&(this._paused=this._playing=!1,this.frame=this._time=0,this.fire("stop"),this._component.fire("stop",this))}});
|
|
Object.defineProperty(e.prototype,"spriteAsset",{get:function(){return this._spriteAsset},set:function(b){var a=this._component.system.app.assets,c=b;b instanceof pc.Asset&&(c=b.id);this._spriteAsset!==c&&(this._spriteAsset&&(b=a.get(this._spriteAsset))&&this._unbindSpriteAsset(b),(this._spriteAsset=c)?(c=a.get(this._spriteAsset))?this._bindSpriteAsset(c):(this.sprite=null,a.on("add:"+this._spriteAsset,this._onSpriteAssetAdded,this)):this.sprite=null)}});Object.defineProperty(e.prototype,"sprite",
|
|
{get:function(){return this._sprite},set:function(b){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));if(this._sprite=b)if(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);if(this._component.currentClip===this){var a;if(b&&b.atlas){if(b.atlas.texture){if(a=this._component._meshInstance)a.setParameter("texture_emissiveMap",b.atlas.texture),a.setParameter("texture_opacityMap",b.atlas.texture);this._component.enabled&&this._component.entity.enabled&&this._component._showModel()}this.time&&this.fps?this.time=this.time:this.frame=
|
|
this.frame}else{if(a=this._component._meshInstance)a.deleteParameter("texture_emissiveMap"),a.deleteParameter("texture_opacityMap");this._component._hideModel()}}}});Object.defineProperty(e.prototype,"frame",{get:function(){return this._frame},set:function(b){this._setFrame(b);this._setTime(this._frame/(this.fps||Number.MIN_VALUE))}});Object.defineProperty(e.prototype,"isPlaying",{get:function(){return this._playing}});Object.defineProperty(e.prototype,"isPaused",{get:function(){return this._paused}});
|
|
Object.defineProperty(e.prototype,"duration",{get:function(){return this._sprite?this._sprite.frameKeys.length/Math.abs(this.fps||Number.MIN_VALUE):0}});Object.defineProperty(e.prototype,"time",{get:function(){return this._time},set:function(b){this._setTime(b);this.frame=this._sprite?Math.min(this._sprite.frameKeys.length-1,Math.floor(this._time*Math.abs(this.fps))):0}});return{SpriteAnimationClip:e}}());Object.assign(pc,function(){pc.SPRITETYPE_SIMPLE="simple";pc.SPRITETYPE_ANIMATED="animated";var e=function(b,a){pc.Component.call(this,b,a);this._type=pc.SPRITETYPE_SIMPLE;this._material=b.defaultMaterial;this._color=new pc.Color(1,1,1,1);this._colorUniform=new Float32Array(3);this._speed=1;this._flipY=this._flipX=!1;this._height=this._width=1;this._drawOrder=0;this._layers=[pc.LAYERID_WORLD];this._outerScale=new pc.Vec2(1,1);this._outerScaleUniform=new Float32Array(2);this._innerOffset=new pc.Vec4;
|
|
this._innerOffsetUniform=new Float32Array(4);this._atlasRect=new pc.Vec4;this._atlasRectUniform=new Float32Array(4);this._batchGroupId=-1;this._batchGroup=null;this._node=new pc.GraphNode;this._model=new pc.Model;this._model.graph=this._node;this._meshInstance=null;a.addChild(this._model.graph);this._model._entity=a;this._updateAabbFunc=this._updateAabb.bind(this);this._addedModel=!1;this._autoPlayClip=null;this._clips={};this._currentClip=this._defaultClip=new pc.SpriteAnimationClip(this,{name:this.entity.name,
|
|
fps:0,loop:!1,spriteAsset:null})};e.prototype=Object.create(pc.Component.prototype);e.prototype.constructor=e;Object.assign(e.prototype,{onEnable:function(){var b=this.system.app,a=b.scene;a.on("set:layers",this._onLayersChanged,this);a.layers&&(a.layers.on("add",this._onLayerAdded,this),a.layers.on("remove",this._onLayerRemoved,this));this._showModel();this._autoPlayClip&&this._tryAutoPlay();0<=this._batchGroupId&&b.batcher.insert(pc.BatchGroup.SPRITE,this._batchGroupId,this.entity)},onDisable:function(){var b=
|
|
this.system.app,a=b.scene;a.off("set:layers",this._onLayersChanged,this);a.layers&&(a.layers.off("add",this._onLayerAdded,this),a.layers.off("remove",this._onLayerRemoved,this));this.stop();this._hideModel();0<=this._batchGroupId&&b.batcher.remove(pc.BatchGroup.SPRITE,this._batchGroupId,this.entity)},onDestroy:function(){this._currentClip=null;this._defaultClip&&(this._defaultClip._destroy(),this._defaultClip=null);for(var b in this._clips)this._clips[b]._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=this._meshInstance.mesh=null)},_showModel:function(){if(!this._addedModel&&this._meshInstance){var b,a,c=[this._meshInstance];b=0;for(a=this._layers.length;b<a;b++){var d=this.system.app.scene.layers.getLayerById(this._layers[b]);d&&d.addMeshInstances(c)}this._addedModel=!0}},_hideModel:function(){if(this._addedModel&&
|
|
this._meshInstance){var b,a,c=[this._meshInstance];b=0;for(a=this._layers.length;b<a;b++){var d=this.system.app.scene.layers.getLayerById(this._layers[b]);d&&d.removeMeshInstances(c)}this._addedModel=!1}},_showFrame:function(b){if(this.sprite){var a=this.sprite.meshes[b];if(a){var c=this.system.defaultMaterial;this.sprite.renderMode===pc.SPRITE_RENDERMODE_SLICED?c=this.system.default9SlicedMaterialSlicedMode:this.sprite.renderMode===pc.SPRITE_RENDERMODE_TILED&&(c=this.system.default9SlicedMaterialTiledMode);
|
|
this._meshInstance||(this._meshInstance=new pc.MeshInstance(this._node,a,this._material),this._meshInstance.castShadow=!1,this._meshInstance.receiveShadow=!1,this._meshInstance.drawOrder=this._drawOrder,this._model.meshInstances.push(this._meshInstance),this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._meshInstance.setParameter("material_emissive",this._colorUniform),this._meshInstance.setParameter("material_opacity",this._color.a),this.enabled&&
|
|
this.entity.enabled&&this._showModel());this._meshInstance.material!==c&&(this._meshInstance.material=c);this._meshInstance.mesh!==a&&(this._meshInstance.mesh=a,this._meshInstance.visible=!0,this._meshInstance._aabbVer=-1);this.sprite.atlas&&this.sprite.atlas.texture?(this._meshInstance.setParameter("texture_emissiveMap",this.sprite.atlas.texture),this._meshInstance.setParameter("texture_opacityMap",this.sprite.atlas.texture)):(this._meshInstance.deleteParameter("texture_emissiveMap"),this._meshInstance.deleteParameter("texture_opacityMap"));
|
|
!this.sprite.atlas||this.sprite.renderMode!==pc.SPRITE_RENDERMODE_SLICED&&this.sprite.renderMode!==pc.SPRITE_RENDERMODE_TILED?this._meshInstance._updateAabbFunc=null:(this._meshInstance._updateAabbFunc=this._updateAabbFunc,(b=this.sprite.atlas.frames[this.sprite.frameKeys[b]])?(a=2/b.rect.z,c=2/b.rect.w,this._innerOffset.set(b.border.x*a,b.border.y*c,b.border.z*a,b.border.w*c),a=this.sprite.atlas.texture,this._atlasRect.set(b.rect.x/a.width,b.rect.y/a.height,b.rect.z/a.width,b.rect.w/a.height)):this._innerOffset.set(0,
|
|
0,0,0),this._innerOffsetUniform[0]=this._innerOffset.x,this._innerOffsetUniform[1]=this._innerOffset.y,this._innerOffsetUniform[2]=this._innerOffset.z,this._innerOffsetUniform[3]=this._innerOffset.w,this._meshInstance.setParameter("innerOffset",this._innerOffsetUniform),this._atlasRectUniform[0]=this._atlasRect.x,this._atlasRectUniform[1]=this._atlasRect.y,this._atlasRectUniform[2]=this._atlasRect.z,this._atlasRectUniform[3]=this._atlasRect.w,this._meshInstance.setParameter("atlasRect",this._atlasRectUniform));
|
|
this._updateTransform()}else this._meshInstance&&(this._meshInstance.mesh=null,this._meshInstance.visible=!1)}},_updateTransform:function(){var b=this.flipX?-1:1,a=this.flipY?-1:1,c=0,d=0;if(this.sprite&&(this.sprite.renderMode===pc.SPRITE_RENDERMODE_SLICED||this.sprite.renderMode===pc.SPRITE_RENDERMODE_TILED)){var f=1,g=1;if(this.sprite.atlas){var e=this.sprite.atlas.frames[this.sprite.frameKeys[this.frame]];e&&(f=e.rect.z,g=e.rect.w,c=(.5-e.pivot.x)*this._width,d=(.5-e.pivot.y)*this._height)}f/=
|
|
this.sprite.pixelsPerUnit;g/=this.sprite.pixelsPerUnit;this._outerScale.set(Math.max(this._width,this._innerOffset.x*f),Math.max(this._height,this._innerOffset.y*g));a*=g;this._outerScale.x/=f;this._outerScale.y/=g;b=b*f*pc.math.clamp(this._width/(this._innerOffset.x*f),1E-4,1);a*=pc.math.clamp(this._height/(this._innerOffset.y*g),1E-4,1);this._meshInstance&&(this._outerScaleUniform[0]=this._outerScale.x,this._outerScaleUniform[1]=this._outerScale.y,this._meshInstance.setParameter("outerScale",this._outerScaleUniform,
|
|
4294967295))}this._node.setLocalScale(b,a,1);this._node.setLocalPosition(c,d,0)},_updateAabb:function(b){b.center.set(0,0,0);b.halfExtents.set(.5*this._outerScale.x,.5*this._outerScale.y,.001);b.setFromTransformedAabb(b,this._node.getWorldTransform());return b},_tryAutoPlay:function(){if(this._autoPlayClip&&this.type===pc.SPRITETYPE_ANIMATED){var b=this._clips[this._autoPlayClip];!b||b.isPlaying||this._currentClip&&this._currentClip.isPlaying||this.enabled&&this.entity.enabled&&this.play(b.name)}},
|
|
_onLayersChanged:function(b,a){b.off("add",this.onLayerAdded,this);b.off("remove",this.onLayerRemoved,this);a.on("add",this.onLayerAdded,this);a.on("remove",this.onLayerRemoved,this);this.enabled&&this.entity.enabled&&this._showModel()},_onLayerAdded:function(b){0>this.layers.indexOf(b.id)||this._addedModel&&this.enabled&&this.entity.enabled&&this._meshInstance&&b.addMeshInstances([this._meshInstance])},_onLayerRemoved:function(b){this._meshInstance&&(0>this.layers.indexOf(b.id)||b.removeMeshInstances([this._meshInstance]))},
|
|
addClip:function(b){var a=new pc.SpriteAnimationClip(this,{name:b.name,fps:b.fps,loop:b.loop,spriteAsset:b.spriteAsset});this._clips[b.name]=a;a.name&&a.name===this._autoPlayClip&&this._tryAutoPlay();return a},removeClip:function(b){delete this._clips[b]},clip:function(b){return this._clips[b]},play:function(b){var a=this._clips[b],c=this._currentClip;c&&c!==a&&(c._playing=!1);(this._currentClip=a)?(this._currentClip=a,this._currentClip.play()):logWARNING("Trying to play sprite animation "+b+" which does not exist.");
|
|
return a},pause:function(){this._currentClip!==this._defaultClip&&this._currentClip.isPlaying&&this._currentClip.pause()},resume:function(){this._currentClip!==this._defaultClip&&this._currentClip.isPaused&&this._currentClip.resume()},stop:function(){this._currentClip!==this._defaultClip&&this._currentClip.stop()}});Object.defineProperty(e.prototype,"type",{get:function(){return this._type},set:function(b){this._type!==b&&(this._type=b,this._type===pc.SPRITETYPE_SIMPLE?(this.stop(),this._currentClip=
|
|
this._defaultClip,this.enabled&&this.entity.enabled&&(this._currentClip.frame=this.frame,this._currentClip.sprite?this._showModel():this._hideModel())):this._type===pc.SPRITETYPE_ANIMATED&&(this.stop(),this._autoPlayClip&&this._tryAutoPlay(),this._currentClip&&this._currentClip.isPlaying&&this.enabled&&this.entity.enabled?this._showModel():this._hideModel()))}});Object.defineProperty(e.prototype,"frame",{get:function(){return this._currentClip.frame},set:function(b){this._currentClip.frame=b}});Object.defineProperty(e.prototype,
|
|
"spriteAsset",{get:function(){return this._defaultClip._spriteAsset},set:function(b){this._defaultClip.spriteAsset=b}});Object.defineProperty(e.prototype,"sprite",{get:function(){return this._currentClip.sprite},set:function(b){this._currentClip.sprite=b}});Object.defineProperty(e.prototype,"material",{get:function(){return this._material},set:function(b){this._material=b;this._meshInstance&&(this._meshInstance.material=b)}});Object.defineProperty(e.prototype,"color",{get:function(){return this._color},
|
|
set:function(b){this._color.r=b.r;this._color.g=b.g;this._color.b=b.b;this._meshInstance&&(this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._meshInstance.setParameter("material_emissive",this._colorUniform))}});Object.defineProperty(e.prototype,"opacity",{get:function(){return this._color.a},set:function(b){this._color.a=b;this._meshInstance&&this._meshInstance.setParameter("material_opacity",b)}});Object.defineProperty(e.prototype,"clips",
|
|
{get:function(){return this._clips},set:function(b){var a,c;if(b){for(a in this._clips){var d=!1;for(c in b)if(b[c].name===a){d=!0;this._clips[a].fps=b[c].fps;this._clips[a].loop=b[c].loop;b[c].hasOwnProperty("sprite")?this._clips[a].sprite=b[c].sprite:b[c].hasOwnProperty("spriteAsset")&&(this._clips[a].spriteAsset=b[c].spriteAsset);break}d||this.removeClip(a)}for(c in b)this._clips[b[c].name]||this.addClip(b[c]);this._autoPlayClip&&this._tryAutoPlay();this._currentClip&&this._currentClip.sprite||
|
|
this._hideModel()}else for(a in this._clips)this.removeClip(a)}});Object.defineProperty(e.prototype,"currentClip",{get:function(){return this._currentClip}});Object.defineProperty(e.prototype,"speed",{get:function(){return this._speed},set:function(b){this._speed=b}});Object.defineProperty(e.prototype,"flipX",{get:function(){return this._flipX},set:function(b){this._flipX!==b&&(this._flipX=b,this._updateTransform())}});Object.defineProperty(e.prototype,"flipY",{get:function(){return this._flipY},
|
|
set:function(b){this._flipY!==b&&(this._flipY=b,this._updateTransform())}});Object.defineProperty(e.prototype,"width",{get:function(){return this._width},set:function(b){b!==this._width&&(this._width=b,this._outerScale.x=this._width,!this.sprite||this.sprite.renderMode!==pc.SPRITE_RENDERMODE_TILED&&this.sprite.renderMode!==pc.SPRITE_RENDERMODE_SLICED||this._updateTransform())}});Object.defineProperty(e.prototype,"height",{get:function(){return this._height},set:function(b){b!==this._height&&(this._height=
|
|
b,this._outerScale.y=this.height,!this.sprite||this.sprite.renderMode!==pc.SPRITE_RENDERMODE_TILED&&this.sprite.renderMode!==pc.SPRITE_RENDERMODE_SLICED||this._updateTransform())}});Object.defineProperty(e.prototype,"batchGroupId",{get:function(){return this._batchGroupId},set:function(b){if(this._batchGroupId!==b){var a=this._batchGroupId;this._batchGroupId=b;this.entity.enabled&&0<=a&&this.system.app.batcher.remove(pc.BatchGroup.SPRITE,a,this.entity);this.entity.enabled&&0<=b?this.system.app.batcher.insert(pc.BatchGroup.SPRITE,
|
|
b,this.entity):0<=a&&this._currentClip&&this._currentClip.sprite&&this.enabled&&this.entity.enabled&&this._showModel()}}});Object.defineProperty(e.prototype,"autoPlayClip",{get:function(){return this._autoPlayClip},set:function(b){this._autoPlayClip=b instanceof pc.SpriteAnimationClip?b.name:b;this._tryAutoPlay()}});Object.defineProperty(e.prototype,"drawOrder",{get:function(){return this._drawOrder},set:function(b){this._drawOrder=b;this._meshInstance&&(this._meshInstance.drawOrder=b)}});Object.defineProperty(e.prototype,
|
|
"layers",{get:function(){return this._layers},set:function(b){this._addedModel&&this._hideModel();this._layers=b;this._meshInstance&&this.enabled&&this.entity.enabled&&this._showModel()}});Object.defineProperty(e.prototype,"aabb",{get:function(){return this._meshInstance?this._meshInstance.aabb:null}});return{SpriteComponent:e}}());Object.assign(pc,function(){var e=["enabled"],b=function(a){pc.ComponentSystem.call(this,a);this.id="sprite";this.app=a;this.ComponentType=pc.SpriteComponent;this.DataType=pc.SpriteComponentData;this.schema=e;this._defaultTexture=new pc.Texture(a.graphicsDevice,{width:1,height:1,format:pc.PIXELFORMAT_R8_G8_B8_A8});a=this._defaultTexture.lock();var b=new Uint8Array(4);b[0]=255;b[1]=255;b[2]=255;b[3]=255;a.set(b);this._defaultTexture.name="sprite";this._defaultTexture.unlock();this.defaultMaterial=
|
|
new pc.StandardMaterial;this.defaultMaterial.diffuse=new pc.Color(0,0,0,1);this.defaultMaterial.emissive=new pc.Color(.5,.5,.5,1);this.defaultMaterial.emissiveMap=this._defaultTexture;this.defaultMaterial.emissiveMapTint=!0;this.defaultMaterial.opacityMap=this._defaultTexture;this.defaultMaterial.opacityMapChannel="a";this.defaultMaterial.opacityTint=!0;this.defaultMaterial.opacity=0;this.defaultMaterial.useLighting=!1;this.defaultMaterial.useGammaTonemap=!1;this.defaultMaterial.useFog=!1;this.defaultMaterial.useSkybox=
|
|
!1;this.defaultMaterial.blendType=pc.BLEND_PREMULTIPLIED;this.defaultMaterial.depthWrite=!1;this.defaultMaterial.pixelSnap=!1;this.defaultMaterial.cull=pc.CULLFACE_NONE;this.defaultMaterial.update();this.default9SlicedMaterialSlicedMode=this.defaultMaterial.clone();this.default9SlicedMaterialSlicedMode.nineSlicedMode=pc.SPRITE_RENDERMODE_SLICED;this.default9SlicedMaterialSlicedMode.update();this.default9SlicedMaterialTiledMode=this.defaultMaterial.clone();this.default9SlicedMaterialTiledMode.nineSlicedMode=
|
|
pc.SPRITE_RENDERMODE_TILED;this.default9SlicedMaterialTiledMode.update();pc.ComponentSystem.bind("update",this.onUpdate,this);this.on("beforeremove",this.onBeforeRemove,this)};b.prototype=Object.create(pc.ComponentSystem.prototype);b.prototype.constructor=b;pc.Component._buildAccessors(pc.SpriteComponent.prototype,e);Object.assign(b.prototype,{destroy:function(){this._defaultTexture.destroy();this._defaultTexture=null},initializeComponentData:function(a,b,d){void 0!==b.enabled&&(a.enabled=b.enabled);
|
|
a.type=b.type;b.layers&&"array"===pc.type(b.layers)&&(a.layers=b.layers.slice(0));void 0!==b.drawOrder&&(a.drawOrder=b.drawOrder);void 0!==b.color&&(b.color instanceof pc.Color?a.color.set(b.color.r,b.color.g,b.color.b,void 0!==b.opacity?b.opacity:1):a.color.set(b.color[0],b.color[1],b.color[2],void 0!==b.opacity?b.opacity:1),a.color=a.color);void 0!==b.opacity&&(a.opacity=b.opacity);void 0!==b.flipX&&(a.flipX=b.flipX);void 0!==b.flipY&&(a.flipY=b.flipY);void 0!==b.width&&(a.width=b.width);void 0!==
|
|
b.height&&(a.height=b.height);void 0!==b.spriteAsset&&(a.spriteAsset=b.spriteAsset);b.sprite&&(a.sprite=b.sprite);void 0!==b.frame&&(a.frame=b.frame);if(b.clips)for(var c in b.clips)a.addClip(b.clips[c]);void 0!==b.speed&&(a.speed=b.speed);b.autoPlayClip&&(a.autoPlayClip=b.autoPlayClip);a.batchGroupId=void 0===b.batchGroupId||null===b.batchGroupId?-1:b.batchGroupId;pc.ComponentSystem.prototype.initializeComponentData.call(this,a,b,d)},cloneComponent:function(a,b){var c=a.sprite;return this.addComponent(b,
|
|
{enabled:c.enabled,type:c.type,spriteAsset:c.spriteAsset,sprite:c.sprite,frame:c.frame,color:c.color.clone(),opacity:c.opacity,flipX:c.flipX,flipY:c.flipY,speed:c.speed,clips:c.clips,autoPlayClip:c.autoPlayClip,batchGroupId:c.batchGroupId,drawOrder:c.drawOrder,layers:c.layers.slice(0)})},onUpdate:function(a){var b=this.store,d;for(d in b)if(b.hasOwnProperty(d)){var f=b[d];f.data.enabled&&f.entity.enabled&&(f=f.entity.sprite,f._currentClip&&f._currentClip._update(a))}},onBeforeRemove:function(a,b){b.onDestroy()}});
|
|
return{SpriteComponentSystem:b}}());Object.assign(pc,function(){return{SpriteComponentData:function(){this.enabled=!0}}}());Object.assign(pc,function(){pc.SCALEMODE_NONE="none";pc.SCALEMODE_BLEND="blend";var e=function(a,b){pc.Component.call(this,a,b);this._resolution=new pc.Vec2(640,320);this._referenceResolution=new pc.Vec2(640,320);this._scaleMode=pc.SCALEMODE_NONE;this.scale=1;this._scaleBlend=.5;this._priority=0;this.cull=this._screenSpace=!1;this._screenMatrix=new pc.Mat4;a.app.graphicsDevice.on("resizecanvas",this._onResize,this)};e.prototype=Object.create(pc.Component.prototype);e.prototype.constructor=e;var b=
|
|
new pc.Mat4;Object.assign(e.prototype,{syncDrawOrder:function(){this.system.queueDrawOrderSync(this.entity.getGuid(),this._processDrawOrderSync,this)},_recurseDrawOrderSync:function(a,b){if(!(a instanceof pc.Entity))return b;if(a.element){var c=a.element.drawOrder;a.element.drawOrder=b++;0<=a.element._batchGroupId&&c!=a.element.drawOrder&&this.system.app.batcher.markGroupDirty(a.element._batchGroupId)}for(var c=a.getChildren(),f=0;f<c.length;f++)b=this._recurseDrawOrderSync(c[f],b);return b},_processDrawOrderSync:function(){this._recurseDrawOrderSync(this.entity,
|
|
1);this.fire("syncdraworder")},_calcProjectionMatrix:function(){var a=this._resolution.x/this.scale,c=this._resolution.y/this.scale;this._screenMatrix.setOrtho(0,a,-c,0,1,-1);this._screenSpace||(b.setScale(.5*a,.5*c,1),this._screenMatrix.mul2(b,this._screenMatrix))},_updateScale:function(){this.scale=this._calcScale(this._resolution,this.referenceResolution)},_calcScale:function(a,b){return Math.pow(2,Math.log2(a.x/b.x)*(1-this._scaleBlend)+Math.log2(a.y/b.y)*this._scaleBlend)},_onResize:function(a,
|
|
b){this._screenSpace&&(this._resolution.set(a,b),this.resolution=this._resolution)},onRemove:function(){this.system.app.graphicsDevice.off("resizecanvas",this._onResize,this);this.fire("remove");this.off()}});Object.defineProperty(e.prototype,"resolution",{set:function(a){this._screenSpace?this._resolution.set(this.system.app.graphicsDevice.width,this.system.app.graphicsDevice.height):this._resolution.set(a.x,a.y);this._updateScale();this._calcProjectionMatrix();this.entity._dirtyLocal||this.entity._dirtifyLocal();
|
|
this.fire("set:resolution",this._resolution)},get:function(){return this._resolution}});Object.defineProperty(e.prototype,"referenceResolution",{set:function(a){this._referenceResolution.set(a.x,a.y);this._updateScale();this._calcProjectionMatrix();this.entity._dirtyLocal||this.entity._dirtifyLocal();this.fire("set:referenceresolution",this._resolution)},get:function(){return this._scaleMode===pc.SCALEMODE_NONE?this._resolution:this._referenceResolution}});Object.defineProperty(e.prototype,"screenSpace",
|
|
{set:function(a){(this._screenSpace=a)&&this._resolution.set(this.system.app.graphicsDevice.width,this.system.app.graphicsDevice.height);this.resolution=this._resolution;this.entity._dirtyLocal||this.entity._dirtifyLocal();this.fire("set:screenspace",this._screenSpace)},get:function(){return this._screenSpace}});Object.defineProperty(e.prototype,"scaleMode",{set:function(a){a!==pc.SCALEMODE_NONE&&a!==pc.SCALEMODE_BLEND&&(a=pc.SCALEMODE_NONE);this._screenSpace||a===pc.SCALEMODE_NONE||(a=pc.SCALEMODE_NONE);
|
|
this._scaleMode=a;this.resolution=this._resolution;this.fire("set:scalemode",this._scaleMode)},get:function(){return this._scaleMode}});Object.defineProperty(e.prototype,"scaleBlend",{set:function(a){this._scaleBlend=a;this._updateScale();this._calcProjectionMatrix();this.entity._dirtyLocal||this.entity._dirtifyLocal();this.fire("set:scaleblend",this._scaleBlend)},get:function(){return this._scaleBlend}});Object.defineProperty(e.prototype,"priority",{get:function(){return this._priority},set:function(a){255<
|
|
a&&(a=255);this._priority=a}});return{ScreenComponent:e}}());Object.assign(pc,function(){var e=["enabled"],b=function(a){pc.ComponentSystem.call(this,a);this.id="screen";this.app=a;this.ComponentType=pc.ScreenComponent;this.DataType=pc.ScreenComponentData;this.schema=e;this.windowResolution=new pc.Vec2;this._drawOrderSyncQueue=new pc.IndexedList;this.app.graphicsDevice.on("resizecanvas",this._onResize,this);pc.ComponentSystem.bind("update",this._onUpdate,this);this.on("beforeremove",this.onRemoveComponent,this)};b.prototype=Object.create(pc.ComponentSystem.prototype);
|
|
b.prototype.constructor=b;pc.Component._buildAccessors(pc.ScreenComponent.prototype,e);Object.assign(b.prototype,{initializeComponentData:function(a,b,d){void 0!==b.priority&&(a.priority=b.priority);void 0!==b.screenSpace&&(a.screenSpace=b.screenSpace);a.cull=a.screenSpace;void 0!==b.scaleMode&&(a.scaleMode=b.scaleMode);void 0!==b.scaleBlend&&(a.scaleBlend=b.scaleBlend);void 0!==b.resolution&&(b.resolution instanceof pc.Vec2?a._resolution.copy(b.resolution):a._resolution.set(b.resolution[0],b.resolution[1]),
|
|
a.resolution=a._resolution);void 0!==b.referenceResolution&&(b.referenceResolution instanceof pc.Vec2?a._referenceResolution.copy(b.referenceResolution):a._referenceResolution.set(b.referenceResolution[0],b.referenceResolution[1]),a.referenceResolution=a._referenceResolution);a.syncDrawOrder();pc.ComponentSystem.prototype.initializeComponentData.call(this,a,b,d)},destroy:function(){this.off();this.app.graphicsDevice.off("resizecanvas",this._onResize,this)},_onUpdate:function(a){var b=this.store,d;
|
|
for(d in b)b[d].entity.screen.update&&b[d].entity.screen.update(a)},_onResize:function(a,b){this.windowResolution.x=a;this.windowResolution.y=b},cloneComponent:function(a,b){var c=a.screen;return this.addComponent(b,{enabled:c.enabled,screenSpace:c.screenSpace,scaleMode:c.scaleMode,resolution:c.resolution.clone(),referenceResolution:c.referenceResolution.clone()})},onRemoveComponent:function(a,b){b.onRemove()},processDrawOrderSyncQueue:function(){for(var a=this._drawOrderSyncQueue.list(),b=0;b<a.length;b++){var d=
|
|
a[b];d.callback.call(d.scope)}this._drawOrderSyncQueue.clear()},queueDrawOrderSync:function(a,b,d){if(!this._drawOrderSyncQueue.list().length)this.app.once("prerender",this.processDrawOrderSyncQueue,this);this._drawOrderSyncQueue.has(a)||this._drawOrderSyncQueue.push(a,{callback:b,scope:d})}});return{ScreenComponentSystem:b}}());Object.assign(pc,function(){return{ScreenComponentData:function(){this.enabled=!0}}}());Object.assign(pc,function(){pc.ELEMENTTYPE_GROUP="group";pc.ELEMENTTYPE_IMAGE="image";pc.ELEMENTTYPE_TEXT="text";var e=new pc.Vec3,b=new pc.Vec3,a=new pc.Mat4,c=new pc.Mat4,d=new pc.Mat4,f=new pc.Mat4,g=function(a,b){pc.Component.call(this,a,b);this._beingInitialized=!1;this._anchor=new pc.Vec4;this._localAnchor=new pc.Vec4;this._pivot=new pc.Vec2;this._height=this._calculatedHeight=this._width=this._calculatedWidth=32;this._margin=new pc.Vec4(0,0,-32,-32);this._modelTransform=new pc.Mat4;this._screenToWorld=
|
|
new pc.Mat4;this._anchorTransform=new pc.Mat4;this._anchorDirty=!0;this._parentWorldTransform=new pc.Mat4;this._screenTransform=new pc.Mat4;this._screenCorners=[new pc.Vec3,new pc.Vec3,new pc.Vec3,new pc.Vec3];this._canvasCorners=[new pc.Vec2,new pc.Vec2,new pc.Vec2,new pc.Vec2];this._worldCorners=[new pc.Vec3,new pc.Vec3,new pc.Vec3,new pc.Vec3];this._worldCornersDirty=this._canvasCornersDirty=this._cornersDirty=!0;this.entity.on("insert",this._onInsert,this);this._patch();this.screen=null;this._type=
|
|
pc.ELEMENTTYPE_GROUP;this._group=this._text=this._image=null;this._drawOrder=0;this._useInput=!1;this._layers=[pc.LAYERID_UI];this._addedModels=[];this._batchGroupId=-1;this._offsetReadAt=0;this._maskOffset=.5;this._maskedBy=null};g.prototype=Object.create(pc.Component.prototype);g.prototype.constructor=g;Object.assign(g.prototype,{_patch:function(){this.entity._sync=this._sync;this.entity.setPosition=this._setPosition;this.entity.setLocalPosition=this._setLocalPosition},_unpatch:function(){this.entity._sync=
|
|
pc.Entity.prototype._sync;this.entity.setPosition=pc.Entity.prototype.setPosition;this.entity.setLocalPosition=pc.Entity.prototype.setLocalPosition},_setPosition:function(){var a=new pc.Vec3,b=new pc.Mat4;return function(c,d,f){if(!this.element.screen)return pc.Entity.prototype.setPosition.call(this,c,d,f);c instanceof pc.Vec3?a.copy(c):a.set(c,d,f);this.getWorldTransform();b.copy(this.element._screenToWorld).invert();b.transformPoint(a,this.localPosition);this._dirtyLocal||this._dirtifyLocal()}}(),
|
|
_setLocalPosition:function(a,b,c){a instanceof pc.Vec3?this.localPosition.copy(a):this.localPosition.set(a,b,c);a=this.element;b=this.localPosition;c=a._pivot;a._margin.x=b.x-a._calculatedWidth*c.x;a._margin.z=a._localAnchor.z-a._localAnchor.x-a._calculatedWidth-a._margin.x;a._margin.y=b.y-a._calculatedHeight*c.y;a._margin.w=a._localAnchor.w-a._localAnchor.y-a._calculatedHeight-a._margin.y;this._dirtyLocal||this._dirtifyLocal()},_sync:function(){var f=this.element,g=f.screen;if(g){if(f._anchorDirty){var k,
|
|
l,q=0,m=1;this._parent&&this._parent.element?(k=this._parent.element.calculatedWidth,l=this._parent.element.calculatedHeight,q=this._parent.element.pivot.x,m=this._parent.element.pivot.y):(l=g.screen.resolution,k=l.x/g.screen.scale,l=l.y/g.screen.scale);f._anchorTransform.setTranslate(k*(f.anchor.x-q),-(l*(m-f.anchor.y)),0);f._anchorDirty=!1;f._calculateLocalAnchors()}f._sizeDirty&&f._calculateSize(!1,!1)}this._dirtyLocal&&(this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale),
|
|
k=this.localPosition,q=f._pivot,f._margin.x=k.x-f._calculatedWidth*q.x,f._margin.z=f._localAnchor.z-f._localAnchor.x-f._calculatedWidth-f._margin.x,f._margin.y=k.y-f._calculatedHeight*q.y,f._margin.w=f._localAnchor.w-f._localAnchor.y-f._calculatedHeight-f._margin.y,this._dirtyLocal=!1);if(!g)return this._dirtyWorld&&(f._cornersDirty=!0,f._canvasCornersDirty=!0,f._worldCornersDirty=!0),pc.Entity.prototype._sync.call(this);this._dirtyWorld&&(null===this._parent?this.worldTransform.copy(this.localTransform):
|
|
(this._parent.element?f._screenToWorld.mul2(this._parent.element._modelTransform,f._anchorTransform):f._screenToWorld.copy(f._anchorTransform),f._modelTransform.mul2(f._screenToWorld,this.localTransform),g?(f._screenToWorld.mul2(g.screen._screenMatrix,f._screenToWorld),g.screen.screenSpace||f._screenToWorld.mul2(g.worldTransform,f._screenToWorld),this.worldTransform.mul2(f._screenToWorld,this.localTransform),k=f._parentWorldTransform,k.setIdentity(),(q=this._parent)&&q.element&&q!==g&&(a.setTRS(pc.Vec3.ZERO,
|
|
q.getLocalRotation(),q.getLocalScale()),k.mul2(q.element._parentWorldTransform,a)),e.set(0,0,this.localPosition.z),b.set(f._absLeft+f._pivot.x*f.calculatedWidth,f._absBottom+f._pivot.y*f.calculatedHeight,0),a.setTranslate(-b.x,-b.y,-b.z),c.setTRS(e,this.getLocalRotation(),this.getLocalScale()),d.setTranslate(b.x,b.y,b.z),f._screenTransform.mul2(f._parentWorldTransform,d).mul(c).mul(a),f._cornersDirty=!0,f._canvasCornersDirty=!0,f._worldCornersDirty=!0):this.worldTransform.copy(f._modelTransform)),
|
|
this._dirtyWorld=!1)},_onInsert:function(a){a=this._parseUpToScreen();this.entity._dirtifyWorld();this._updateScreen(a.screen);this._dirtifyMask()},_dirtifyMask:function(){for(var a=this.entity;a;){var b=a.getParent();if((null===b||b.screen)&&a.element){this.system._prerender&&this.system._prerender.length||(this.system._prerender=[],this.system.app.once("prerender",this._onPrerender,this));var c=this.system._prerender.indexOf(this.entity);0<=c&&this.system._prerender.splice(c,1);0>this.system._prerender.indexOf(a)&&
|
|
this.system._prerender.push(a)}a=b}},_onPrerender:function(){for(var a=0;a<this.system._prerender.length;a++){var b=this.system._prerender[a];b.element&&b.element.syncMask(1)}this.system._prerender.length=0},_bindScreen:function(a){a.on("set:resolution",this._onScreenResize,this);a.on("set:referenceresolution",this._onScreenResize,this);a.on("set:scaleblend",this._onScreenResize,this);a.on("set:screenspace",this._onScreenSpaceChange,this);a.on("remove",this._onScreenRemove,this)},_unbindScreen:function(a){a.off("set:resolution",
|
|
this._onScreenResize,this);a.off("set:referenceresolution",this._onScreenResize,this);a.off("set:scaleblend",this._onScreenResize,this);a.off("set:screenspace",this._onScreenSpaceChange,this);a.off("remove",this._onScreenRemove,this)},_updateScreen:function(a){this.screen&&this.screen!==a&&this._unbindScreen(this.screen.screen);var b=this.screen;(this.screen=a)&&this._bindScreen(this.screen.screen);this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY);this.fire("set:screen",this.screen,
|
|
b);this._anchorDirty=!0;for(var b=this.entity.getChildren(),c=0,d=b.length;c<d;c++)b[c].element&&b[c].element._updateScreen(a);this.screen&&this.screen.screen.syncDrawOrder()},syncMask:function(a){var b=this._parseUpToScreen();this._updateMask(b.mask,a)},_setMaskedBy:function(a){var b=this._image||this._text;if(a){var c=new pc.StencilParameters({ref:a.element._image._maskRef,func:pc.FUNC_EQUAL});b&&b._setStencil&&b._setStencil(c);this._maskedBy=a}else b&&b._setStencil&&b._setStencil(null),this._maskedBy=
|
|
null},_updateMask:function(a,b){var c,d,f;a?(this._setMaskedBy(a),this.mask&&(c=new pc.StencilParameters({ref:a.element._image._maskRef,func:pc.FUNC_EQUAL,zpass:pc.STENCILOP_INCREMENT}),this._image._setStencil(c),this._image._maskRef=b,b++,a=this.entity)):(this._setMaskedBy(null),this.mask&&(c=new pc.StencilParameters({ref:b,func:pc.FUNC_ALWAYS,zpass:pc.STENCILOP_REPLACE}),this._image._setStencil(c),this._image._maskRef=b,b++,a=this.entity));f=this.entity.getChildren();c=0;for(d=f.length;c<d;c++)f[c].element&&
|
|
f[c].element._updateMask(a,b)},_parseUpToScreen:function(){for(var a={screen:null,mask:null},b=this.entity._parent;b&&!b.screen;)b.element&&b.element.mask&&!a.mask&&(a.mask=b),b=b.parent;b&&b.screen&&(a.screen=b);return a},_onScreenResize:function(a){this._worldCornersDirty=this._cornersDirty=this._anchorDirty=!0;this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY);this.fire("screen:set:resolution",a)},_onScreenSpaceChange:function(){this.fire("screen:set:screenspace",this.screen.screen.screenSpace)},
|
|
_onScreenRemove:function(){this.screen&&!this.screen._destroying&&this._updateScreen(null)},_calculateLocalAnchors:function(){var a=1E3,b=1E3,c=this.entity._parent;c&&c.element?(a=c.element.calculatedWidth,b=c.element.calculatedHeight):this.screen&&(b=this.screen.screen.resolution,c=this.screen.screen.scale,a=b.x/c,b=b.y/c);this._localAnchor.set(this._anchor.x*a,this._anchor.y*b,this._anchor.z*a,this._anchor.w*b)},getOffsetPosition:function(a,b){var c=this.entity.getLocalPosition().clone();c.x+=a;
|
|
c.y+=b;this._screenToWorld.transformPoint(c,c);return c},onLayersChanged:function(a,b){this.addModelToLayers(this._image?this._image._model:this._text._model);a.off("add",this.onLayerAdded,this);a.off("remove",this.onLayerRemoved,this);b.on("add",this.onLayerAdded,this);b.on("remove",this.onLayerRemoved,this)},onLayerAdded:function(a){0>this.layers.indexOf(a.id)||(this._image?a.addMeshInstances(this._image._model.meshInstances):this._text&&a.addMeshInstances(this._text._model.meshInstances))},onLayerRemoved:function(a){0>
|
|
this.layers.indexOf(a.id)||(this._image?a.removeMeshInstances(this._image._model.meshInstances):this._text&&a.removeMeshInstances(this._text._model.meshInstances))},onEnable:function(){if(this._image)this._image.onEnable();if(this._text)this._text.onEnable();if(this._group)this._group.onEnable();this.useInput&&this.system.app.elementInput&&this.system.app.elementInput.addElement(this);this.system.app.scene.on("set:layers",this.onLayersChanged,this);this.system.app.scene.layers&&(this.system.app.scene.layers.on("add",
|
|
this.onLayerAdded,this),this.system.app.scene.layers.on("remove",this.onLayerRemoved,this));0<=this._batchGroupId&&this.system.app.batcher.insert(pc.BatchGroup.ELEMENT,this.batchGroupId,this.entity);this.fire("enableelement")},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));if(this._image)this._image.onDisable();
|
|
if(this._text)this._text.onDisable();if(this._group)this._group.onDisable();this.system.app.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this);0<=this._batchGroupId&&this.system.app.batcher.remove(pc.BatchGroup.ELEMENT,this.batchGroupId,this.entity);this.fire("disableelement")},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()},_calculateSize:function(a,b){if(this.entity._parent||this.screen){this._calculateLocalAnchors();var c=this._absRight-this._absLeft,d=this._absTop-this._absBottom;a?this._setWidth(c):this._setCalculatedWidth(c,!1);b?this._setHeight(d):this._setCalculatedHeight(d,!1);c=this.entity.getLocalPosition();c.x=this._margin.x+this._calculatedWidth*
|
|
this._pivot.x;c.y=this._margin.y+this._calculatedHeight*this._pivot.y;this.entity.setLocalPosition(c);this._sizeDirty=!1}},_setWidth:function(a){this._width=a;this._setCalculatedWidth(a,!1);this.fire("set:width",this._width)},_setHeight:function(a){this._height=a;this._setCalculatedHeight(a,!1);this.fire("set:height",this._height)},_setCalculatedWidth:function(a,b){if(!(1E-4>=Math.abs(a-this._calculatedWidth))){this._calculatedWidth=a;this.entity._dirtifyLocal();if(b){var c=this.entity.getLocalPosition();
|
|
this._margin.x=c.x-this._calculatedWidth*this._pivot.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)}},_setCalculatedHeight:function(a,b){if(!(1E-4>=Math.abs(a-this._calculatedHeight))){this._calculatedHeight=a;this.entity._dirtifyLocal();if(b){var c=this.entity.getLocalPosition();this._margin.y=c.y-this._calculatedHeight*
|
|
this._pivot.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)}},_flagChildrenAsDirty:function(){var a,b,c=this.entity._children;a=0;for(b=c.length;a<b;a++)c[a].element&&(c[a].element._anchorDirty=!0,c[a].element._sizeDirty=!0)},addModelToLayers:function(a){var b;this._addedModels.push(a);for(var c=0;c<this.layers.length;c++)(b=
|
|
this.system.app.scene.layers.getLayerById(this.layers[c]))&&b.addMeshInstances(a.meshInstances)},removeModelFromLayers:function(a){var b;b=this._addedModels.indexOf(a);0<=b&&this._addedModels.splice(b,1);for(var c=0;c<this.layers.length;c++)(b=this.system.app.scene.layers.getLayerById(this.layers[c]))&&b.removeMeshInstances(a.meshInstances)},getMaskOffset:function(){var a=this.system.app.frame;this._offsetReadAt!==a&&(this._maskOffset=.5,this._offsetReadAt=a);a=this._maskOffset;this._maskOffset-=
|
|
.001;return a},isVisibleForCamera:function(a){var b,c,d;if(this.maskedBy)a=this.maskedBy.element.screenCorners,b=Math.min(Math.min(a[0].x,a[1].x),Math.min(a[2].x,a[3].x)),c=Math.max(Math.max(a[0].x,a[1].x),Math.max(a[2].x,a[3].x)),d=Math.min(Math.min(a[0].y,a[1].y),Math.min(a[2].y,a[3].y)),a=Math.max(Math.max(a[0].y,a[1].y),Math.max(a[2].y,a[3].y));else{b=this.system.app.graphicsDevice.width;var f=this.system.app.graphicsDevice.height;c=a._rect.width*b;d=a._rect.height*f;b*=a._rect.x;c=b+c;a=(1-a._rect.y)*
|
|
f;d=a-d}var f=this.screenCorners,g=Math.min(Math.min(f[0].x,f[1].x),Math.min(f[2].x,f[3].x)),e=Math.min(Math.min(f[0].y,f[1].y),Math.min(f[2].y,f[3].y)),h=Math.max(Math.max(f[0].y,f[1].y),Math.max(f[2].y,f[3].y));return Math.max(Math.max(f[0].x,f[1].x),Math.max(f[2].x,f[3].x))<b||g>c||e>a||h<d?!1:!0},_isScreenSpace:function(){return this.screen&&this.screen.screen?this.screen.screen.screenSpace:!1},_isScreenCulled:function(){return this.screen&&this.screen.screen?this.screen.screen.cull:!1}});Object.defineProperty(g.prototype,
|
|
"type",{get:function(){return this._type},set:function(a){a!==this._type&&(this._type=a,this._image&&(this._image.destroy(),this._image=null),this._text&&(this._text.destroy(),this._text=null),a===pc.ELEMENTTYPE_IMAGE?this._image=new pc.ImageElement(this):a===pc.ELEMENTTYPE_TEXT&&(this._text=new pc.TextElement(this)))}});Object.defineProperty(g.prototype,"layers",{get:function(){return this._layers},set:function(a){var b,c,d;if(this._addedModels.length)for(b=0;b<this._layers.length;b++)if(d=this.system.app.scene.layers.getLayerById(this._layers[b]))for(c=
|
|
0;c<this._addedModels.length;c++)d.removeMeshInstances(this._addedModels[c].meshInstances);this._layers=a;if(this.enabled&&this.entity.enabled&&this._addedModels.length)for(b=0;b<this._layers.length;b++)if(d=this.system.app.scene.layers.getLayerById(this._layers[b]))for(c=0;c<this._addedModels.length;c++)d.addMeshInstances(this._addedModels[c].meshInstances)}});Object.defineProperty(g.prototype,"drawOrder",{get:function(){return this._drawOrder},set:function(a){var b=0;this.screen&&(b=this.screen.screen.priority);
|
|
16777215<a&&(a=16777215);this._drawOrder=(b<<24)+a;this.fire("set:draworder",this._drawOrder)}});Object.defineProperty(g.prototype,"_absLeft",{get:function(){return this._localAnchor.x+this._margin.x}});Object.defineProperty(g.prototype,"_absRight",{get:function(){return this._localAnchor.z-this._margin.z}});Object.defineProperty(g.prototype,"_absTop",{get:function(){return this._localAnchor.w-this._margin.w}});Object.defineProperty(g.prototype,"_absBottom",{get:function(){return this._localAnchor.y+
|
|
this._margin.y}});Object.defineProperty(g.prototype,"margin",{get:function(){return this._margin},set:function(a){this._margin.copy(a);this._calculateSize(!0,!0);this.fire("set:margin",this._margin)}});Object.defineProperty(g.prototype,"left",{get:function(){return this._margin.x},set:function(a){this._margin.x=a;var b=this.entity.getLocalPosition();this._setWidth(this._absRight-(this._localAnchor.x+a));b.x=a+this._calculatedWidth*this._pivot.x;this.entity.setLocalPosition(b)}});Object.defineProperty(g.prototype,
|
|
"right",{get:function(){return this._margin.z},set:function(a){this._margin.z=a;var b=this.entity.getLocalPosition();this._setWidth(this._localAnchor.z-a-this._absLeft);b.x=this._localAnchor.z-this._localAnchor.x-a-this._calculatedWidth*(1-this._pivot.x);this.entity.setLocalPosition(b)}});Object.defineProperty(g.prototype,"top",{get:function(){return this._margin.w},set:function(a){this._margin.w=a;var b=this.entity.getLocalPosition();this._setHeight(this._localAnchor.w-a-this._absBottom);b.y=this._localAnchor.w-
|
|
this._localAnchor.y-a-this._calculatedHeight*(1-this._pivot.y);this.entity.setLocalPosition(b)}});Object.defineProperty(g.prototype,"bottom",{get:function(){return this._margin.y},set:function(a){this._margin.y=a;var b=this.entity.getLocalPosition();this._setHeight(this._absTop-(this._localAnchor.y+a));b.y=a+this._calculatedHeight*this._pivot.y;this.entity.setLocalPosition(b)}});Object.defineProperty(g.prototype,"width",{get:function(){return this._width},set:function(a){this._width=a;this._hasSplitAnchorsX||
|
|
this._setCalculatedWidth(a,!0);this.fire("set:width",this._width)}});Object.defineProperty(g.prototype,"height",{get:function(){return this._height},set:function(a){this._height=a;this._hasSplitAnchorsY||this._setCalculatedHeight(a,!0);this.fire("set:height",this._height)}});Object.defineProperty(g.prototype,"calculatedWidth",{get:function(){return this._calculatedWidth},set:function(a){this._setCalculatedWidth(a,!0)}});Object.defineProperty(g.prototype,"calculatedHeight",{get:function(){return this._calculatedHeight},
|
|
set:function(a){this._setCalculatedHeight(a,!0)}});Object.defineProperty(g.prototype,"pivot",{get:function(){return this._pivot},set:function(a){var b=this._pivot.x,c=this._pivot.y;a instanceof pc.Vec2?this._pivot.set(a.x,a.y):this._pivot.set(a[0],a[1]);a=this._margin.x+this._margin.z;b=this._pivot.x-b;this._margin.x+=a*b;this._margin.z-=a*b;b=this._margin.y+this._margin.w;c=this._pivot.y-c;this._margin.y+=b*c;this._margin.w-=b*c;this._worldCornersDirty=this._cornersDirty=this._anchorDirty=!0;this._calculateSize(!1,
|
|
!1);this.fire("set:pivot",this._pivot)}});Object.defineProperty(g.prototype,"anchor",{get:function(){return this._anchor},set:function(a){a instanceof pc.Vec4?this._anchor.set(a.x,a.y,a.z,a.w):this._anchor.set(a[0],a[1],a[2],a[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(g.prototype,
|
|
"_hasSplitAnchorsX",{get:function(){return.001<Math.abs(this._anchor.x-this._anchor.z)}});Object.defineProperty(g.prototype,"_hasSplitAnchorsY",{get:function(){return.001<Math.abs(this._anchor.y-this._anchor.w)}});Object.defineProperty(g.prototype,"aabb",{get:function(){return this._image?this._image.aabb:this._text?this._text.aabb:null}});Object.defineProperty(g.prototype,"screenCorners",{get:function(){if(!this._cornersDirty||!this.screen)return this._screenCorners;var a=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 b=this.screen.screen.screenSpace,c=0;4>c;c++)this._screenTransform.transformPoint(this._screenCorners[c],this._screenCorners[c]),b&&this._screenCorners[c].scale(this.screen.screen.scale),a&&this._screenCorners[c].add(a);
|
|
this._cornersDirty=!1;this._worldCornersDirty=this._canvasCornersDirty=!0;return this._screenCorners}});Object.defineProperty(g.prototype,"canvasCorners",{get:function(){if(!this._canvasCornersDirty||!this.screen||!this.screen.screen.screenSpace)return this._canvasCorners;for(var a=this.system.app.graphicsDevice,b=this.screenCorners,c=a.canvas.clientWidth/a.width,d=a.canvas.clientHeight/a.height,f=0;4>f;f++)this._canvasCorners[f].set(b[f].x*c,(a.height-b[f].y)*d);this._canvasCornersDirty=!1;return this._canvasCorners}});
|
|
Object.defineProperty(g.prototype,"worldCorners",{get:function(){if(!this._worldCornersDirty)return this._worldCorners;if(this.screen){var b=this.screenCorners;if(!this.screen.screen.screenSpace){a.copy(this.screen.screen._screenMatrix);a.data[13]=-a.data[13];a.mul2(this.screen.getWorldTransform(),a);for(var g=0;4>g;g++)a.transformPoint(b[g],this._worldCorners[g])}}else b=this.entity.getLocalPosition(),a.setTranslate(-b.x,-b.y,-b.z),c.setTRS(pc.Vec3.ZERO,this.entity.getLocalRotation(),this.entity.getLocalScale()),
|
|
d.setTranslate(b.x,b.y,b.z),f.copy(this.entity.parent.getWorldTransform()),f.mul(d).mul(c).mul(a),e.set(b.x-this.pivot.x*this.calculatedWidth,b.y-this.pivot.y*this.calculatedHeight,b.z),f.transformPoint(e,this._worldCorners[0]),e.set(b.x+(1-this.pivot.x)*this.calculatedWidth,b.y-this.pivot.y*this.calculatedHeight,b.z),f.transformPoint(e,this._worldCorners[1]),e.set(b.x+(1-this.pivot.x)*this.calculatedWidth,b.y+(1-this.pivot.y)*this.calculatedHeight,b.z),f.transformPoint(e,this._worldCorners[2]),e.set(b.x-
|
|
this.pivot.x*this.calculatedWidth,b.y+(1-this.pivot.y)*this.calculatedHeight,b.z),f.transformPoint(e,this._worldCorners[3]);this._worldCornersDirty=!1;return this._worldCorners}});Object.defineProperty(g.prototype,"textWidth",{get:function(){return this._text?this._text.width:0}});Object.defineProperty(g.prototype,"textHeight",{get:function(){return this._text?this._text.height:0}});Object.defineProperty(g.prototype,"useInput",{get:function(){return this._useInput},set:function(a){this._useInput!==
|
|
a&&(this._useInput=a,this.system.app.elementInput&&(a?this.enabled&&this.entity.enabled&&this.system.app.elementInput.addElement(this):this.system.app.elementInput.removeElement(this)),this.fire("set:useInput",a))}});Object.defineProperty(g.prototype,"batchGroupId",{get:function(){return this._batchGroupId},set:function(a){this._batchGroupId!==a&&(this.entity.enabled&&0<=this._batchGroupId&&this.system.app.batcher.remove(pc.BatchGroup.ELEMENT,this.batchGroupId,this.entity),this.entity.enabled&&0<=
|
|
a&&this.system.app.batcher.insert(pc.BatchGroup.ELEMENT,a,this.entity),0>a&&0<=this._batchGroupId&&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=a)}});Object.defineProperty(g.prototype,"maskedBy",{get:function(){return this._maskedBy}});var l=function(a){Object.defineProperty(g.prototype,a,{get:function(){return this._text?
|
|
this._text[a]:this._image?this._image[a]:null},set:function(b){this._text?this._text[a]=b:this._image&&(this._image[a]=b)}})};l("fontSize");l("minFontSize");l("maxFontSize");l("maxLines");l("autoFitWidth");l("autoFitHeight");l("color");l("font");l("fontAsset");l("spacing");l("lineHeight");l("wrapLines");l("lines");l("alignment");l("autoWidth");l("autoHeight");l("rtlReorder");l("unicodeConverter");l("text");l("key");l("texture");l("textureAsset");l("material");l("materialAsset");l("sprite");l("spriteAsset");
|
|
l("spriteFrame");l("pixelsPerUnit");l("opacity");l("rect");l("mask");l("outlineColor");l("outlineThickness");l("shadowColor");l("shadowOffset");return{ElementComponent:g}}());Object.assign(pc,function(){var e=["enabled"],b=function(a){pc.ComponentSystem.call(this,a);this.id="element";this.app=a;this.ComponentType=pc.ElementComponent;this.DataType=pc.ElementComponentData;this.schema=e;this._rtlReorder=this._unicodeConverter=null;this._defaultTexture=new pc.Texture(a.graphicsDevice,{width:1,height:1,format:pc.PIXELFORMAT_R8_G8_B8_A8});this._defaultTexture.name="element-system";a=this._defaultTexture.lock();var b=new Uint8Array(4);b[0]=255;b[1]=255;b[2]=255;b[3]=255;a.set(b);
|
|
this._defaultTexture.unlock();this.defaultScreenSpaceBitmapTextMaterial=this.defaultScreenSpaceTextMaterial=this.defaultBitmapTextMaterial=this.defaultTextMaterial=this.defaultScreenSpaceImageMaskMaterial=this.defaultScreenSpaceImageMask9TiledMaterial=this.defaultScreenSpaceImageMask9SlicedMaterial=this.defaultScreenSpaceImage9TiledMaterial=this.defaultScreenSpaceImage9SlicedMaterial=this.defaultScreenSpaceImageMaterial=this.defaultImage9TiledMaskMaterial=this.defaultImage9SlicedMaskMaterial=this.defaultImageMaskMaterial=
|
|
this.defaultImage9TiledMaterial=this.defaultImage9SlicedMaterial=this.defaultImageMaterial=null;this.defaultImageMaterials=[];this.on("beforeremove",this.onRemoveComponent,this)};b.prototype=Object.create(pc.ComponentSystem.prototype);b.prototype.constructor=b;pc.Component._buildAccessors(pc.ElementComponent.prototype,e);Object.assign(b.prototype,{destroy:function(){this._defaultTexture.destroy()},initializeComponentData:function(a,b,d){a._beingInitialized=!0;void 0!==b.anchor&&(b.anchor instanceof
|
|
pc.Vec4?a.anchor.copy(b.anchor):a.anchor.set(b.anchor[0],b.anchor[1],b.anchor[2],b.anchor[3]));void 0!==b.pivot&&(b.pivot instanceof pc.Vec2?a.pivot.copy(b.pivot):a.pivot.set(b.pivot[0],b.pivot[1]));var c=.001<Math.abs(a.anchor.x-a.anchor.z),g=.001<Math.abs(a.anchor.y-a.anchor.w),e=!1;void 0!==b.margin&&(b.margin instanceof pc.Vec4?a.margin.copy(b.margin):a._margin.set(b.margin[0],b.margin[1],b.margin[2],b.margin[3]),e=!0);void 0!==b.left&&(a._margin.x=b.left,e=!0);void 0!==b.bottom&&(a._margin.y=
|
|
b.bottom,e=!0);void 0!==b.right&&(a._margin.z=b.right,e=!0);void 0!==b.top&&(a._margin.w=b.top,e=!0);e&&(a.margin=a._margin);e=!1;void 0===b.width||c?c&&(e=!0):a.width=b.width;void 0===b.height||g?g&&(e=!0):a.height=b.height;e&&(a.anchor=a.anchor);void 0!==b.enabled&&(a.enabled=b.enabled);void 0!==b.useInput&&(a.useInput=b.useInput);a.batchGroupId=void 0===b.batchGroupId||null===b.batchGroupId?-1:b.batchGroupId;b.layers&&"array"===pc.type(b.layers)&&(a.layers=b.layers.slice(0));a.type=b.type;a.type===
|
|
pc.ELEMENTTYPE_IMAGE?(void 0!==b.rect&&(a.rect=b.rect),void 0!==b.color&&(c=b.color,c instanceof pc.Color||(c=new pc.Color(b.color[0],b.color[1],b.color[2])),a.color=c),void 0!==b.opacity&&(a.opacity=b.opacity),void 0!==b.textureAsset&&(a.textureAsset=b.textureAsset),b.texture&&(a.texture=b.texture),void 0!==b.spriteAsset&&(a.spriteAsset=b.spriteAsset),b.sprite&&(a.sprite=b.sprite),void 0!==b.spriteFrame&&(a.spriteFrame=b.spriteFrame),void 0!==b.pixelsPerUnit&&null!==b.pixelsPerUnit&&(a.pixelsPerUnit=
|
|
b.pixelsPerUnit),void 0!==b.materialAsset&&(a.materialAsset=b.materialAsset),b.material&&(a.material=b.material),void 0!==b.mask&&(a.mask=b.mask)):a.type===pc.ELEMENTTYPE_TEXT&&(void 0!==b.autoWidth&&(a.autoWidth=b.autoWidth),void 0!==b.autoHeight&&(a.autoHeight=b.autoHeight),void 0!==b.rtlReorder&&(a.rtlReorder=b.rtlReorder),void 0!==b.unicodeConverter&&(a.unicodeConverter=b.unicodeConverter),null!==b.text&&void 0!==b.text?a.text=b.text:null!==b.key&&void 0!==b.key&&(a.key=b.key),void 0!==b.color&&
|
|
(c=b.color,c instanceof pc.Color||(c=new pc.Color(c[0],c[1],c[2])),a.color=c),void 0!==b.opacity&&(a.opacity=b.opacity),void 0!==b.spacing&&(a.spacing=b.spacing),void 0!==b.fontSize&&(a.fontSize=b.fontSize,b.lineHeight||(a.lineHeight=b.fontSize)),void 0!==b.lineHeight&&(a.lineHeight=b.lineHeight),void 0!==b.maxLines&&(a.maxLines=b.maxLines),void 0!==b.wrapLines&&(a.wrapLines=b.wrapLines),void 0!==b.minFontSize&&(a.minFontSize=b.minFontSize),void 0!==b.maxFontSize&&(a.maxFontSize=b.maxFontSize),b.autoFitWidth&&
|
|
(a.autoFitWidth=b.autoFitWidth),b.autoFitHeight&&(a.autoFitHeight=b.autoFitHeight),void 0!==b.fontAsset&&(a.fontAsset=b.fontAsset),void 0!==b.font&&(a.font=b.font),void 0!==b.alignment&&(a.alignment=b.alignment),void 0!==b.outlineColor&&(a.outlineColor=b.outlineColor),void 0!==b.outlineThickness&&(a.outlineThickness=b.outlineThickness),void 0!==b.shadowColor&&(a.shadowColor=b.shadowColor),void 0!==b.shadowOffset&&(a.shadowOffset=b.shadowOffset));c=a._parseUpToScreen();c.screen&&a._updateScreen(c.screen);
|
|
pc.ComponentSystem.prototype.initializeComponentData.call(this,a,b,d);a._beingInitialized=!1;a.type===pc.ELEMENTTYPE_IMAGE&&a._image._meshDirty&&a._image._updateMesh(a._image.mesh)},onRemoveComponent:function(a,b){b.onRemove()},cloneComponent:function(a,b){var c=a.element,f={enabled:c.enabled,width:c.width,height:c.height,anchor:c.anchor.clone(),pivot:c.pivot.clone(),margin:c.margin.clone(),alignment:c.alignment&&c.alignment.clone()||c.alignment,autoWidth:c.autoWidth,autoHeight:c.autoHeight,type:c.type,
|
|
rect:c.rect&&c.rect.clone()||c.rect,rtlReorder:c.rtlReorder,unicodeConverter:c.unicodeConverter,materialAsset:c.materialAsset,material:c.material,color:c.color&&c.color.clone()||c.color,opacity:c.opacity,textureAsset:c.textureAsset,texture:c.texture,spriteAsset:c.spriteAsset,sprite:c.sprite,spriteFrame:c.spriteFrame,pixelsPerUnit:c.pixelsPerUnit,spacing:c.spacing,lineHeight:c.lineHeight,wrapLines:c.wrapLines,layers:c.layers,fontSize:c.fontSize,minFontSize:c.minFontSize,maxFontSize:c.maxFontSize,autoFitWidth:c.autoFitWidth,
|
|
autoFitHeight:c.autoFitHeight,maxLines:c.maxLines,fontAsset:c.fontAsset,font:c.font,useInput:c.useInput,batchGroupId:c.batchGroupId,mask:c.mask,outlineColor:c.outlineColor&&c.outlineColor.clone()||c.outlineColor,outlineThickness:c.outlineThickness,shadowColor:c.shadowColor&&c.shadowColor.clone()||c.shadowColor,shadowOffset:c.shadowOffset&&c.shadowOffset.clone()||c.shadowOffset};void 0!==c.key&&null!==c.key?f.key=c.key:f.text=c.text;return this.addComponent(b,f)},getTextElementMaterial:function(a,
|
|
b){if(a){if(b)return this.defaultScreenSpaceTextMaterial||(this.defaultScreenSpaceTextMaterial=new pc.StandardMaterial,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=pc.BLEND_PREMULTIPLIED,this.defaultScreenSpaceTextMaterial.depthWrite=!1,this.defaultScreenSpaceTextMaterial.depthTest=!1,this.defaultScreenSpaceTextMaterial.update()),this.defaultScreenSpaceTextMaterial;this.defaultScreenSpaceBitmapTextMaterial||(this.defaultScreenSpaceBitmapTextMaterial=new pc.StandardMaterial,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=pc.BLEND_PREMULTIPLIED,this.defaultScreenSpaceBitmapTextMaterial.depthWrite=!1,this.defaultScreenSpaceBitmapTextMaterial.depthTest=!1,this.defaultScreenSpaceBitmapTextMaterial.update());return this.defaultScreenSpaceBitmapTextMaterial}if(b)return this.defaultTextMaterial||(this.defaultTextMaterial=
|
|
new pc.StandardMaterial,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=pc.BLEND_PREMULTIPLIED,this.defaultTextMaterial.depthWrite=
|
|
!1,this.defaultTextMaterial.update()),this.defaultTextMaterial;this.defaultBitmapTextMaterial||(this.defaultBitmapTextMaterial=new pc.StandardMaterial,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=pc.BLEND_PREMULTIPLIED,this.defaultBitmapTextMaterial.depthWrite=!1,this.defaultBitmapTextMaterial.update());return this.defaultBitmapTextMaterial},_createBaseImageMaterial:function(){var a=new pc.StandardMaterial;a.diffuse.set(0,
|
|
0,0);a.emissive.set(.5,.5,.5);a.emissiveMap=this._defaultTexture;a.emissiveTint=!0;a.opacityMap=this._defaultTexture;a.opacityMapChannel="a";a.opacityTint=!0;a.opacity=0;a.useLighting=!1;a.useGammaTonemap=!1;a.useFog=!1;a.useSkybox=!1;a.blendType=pc.BLEND_PREMULTIPLIED;a.depthWrite=!1;return a},getImageElementMaterial:function(a,b,d,f){if(a){if(b){if(d)return this.defaultScreenSpaceImageMask9SlicedMaterial||(this.defaultScreenSpaceImageMask9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMask9SlicedMaterial.name=
|
|
"defaultScreenSpaceImageMask9SlicedMaterial",this.defaultScreenSpaceImageMask9SlicedMaterial.nineSlicedMode=pc.SPRITE_RENDERMODE_SLICED,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;if(f)return this.defaultScreenSpaceImageMask9TiledMaterial||(this.defaultScreenSpaceImageMask9TiledMaterial=this.defaultScreenSpaceImage9TiledMaterial.clone(),this.defaultScreenSpaceImageMask9TiledMaterial.name="defaultScreenSpaceImageMask9TiledMaterial",this.defaultScreenSpaceImageMask9TiledMaterial.nineSlicedMode=
|
|
pc.SPRITE_RENDERMODE_TILED,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));return this.defaultScreenSpaceImageMaskMaterial}if(d)return this.defaultScreenSpaceImage9SlicedMaterial||(this.defaultScreenSpaceImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9SlicedMaterial.name="defaultScreenSpaceImage9SlicedMaterial",this.defaultScreenSpaceImage9SlicedMaterial.nineSlicedMode=
|
|
pc.SPRITE_RENDERMODE_SLICED,this.defaultScreenSpaceImage9SlicedMaterial.depthTest=!1,this.defaultScreenSpaceImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9SlicedMaterial)),this.defaultScreenSpaceImage9SlicedMaterial;if(f)return this.defaultScreenSpaceImage9TiledMaterial||(this.defaultScreenSpaceImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9TiledMaterial.name="defaultScreenSpaceImage9TiledMaterial",this.defaultScreenSpaceImage9TiledMaterial.nineSlicedMode=
|
|
pc.SPRITE_RENDERMODE_TILED,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));return this.defaultScreenSpaceImageMaterial}if(b){if(d)return this.defaultImage9SlicedMaskMaterial||(this.defaultImage9SlicedMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaskMaterial.name="defaultImage9SlicedMaskMaterial",this.defaultImage9SlicedMaskMaterial.nineSlicedMode=pc.SPRITE_RENDERMODE_SLICED,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;if(f)return this.defaultImage9TiledMaskMaterial||(this.defaultImage9TiledMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaskMaterial.name="defaultImage9TiledMaskMaterial",this.defaultImage9TiledMaskMaterial.nineSlicedMode=
|
|
pc.SPRITE_RENDERMODE_TILED,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));return this.defaultImageMaskMaterial}if(d)return this.defaultImage9SlicedMaterial||(this.defaultImage9SlicedMaterial=this._createBaseImageMaterial(),
|
|
this.defaultImage9SlicedMaterial.name="defaultImage9SlicedMaterial",this.defaultImage9SlicedMaterial.nineSlicedMode=pc.SPRITE_RENDERMODE_SLICED,this.defaultImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaterial)),this.defaultImage9SlicedMaterial;if(f)return this.defaultImage9TiledMaterial||(this.defaultImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaterial.name="defaultImage9TiledMaterial",this.defaultImage9TiledMaterial.nineSlicedMode=
|
|
pc.SPRITE_RENDERMODE_TILED,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));return this.defaultImageMaterial},registerUnicodeConverter:function(a){this._unicodeConverter=a},registerRtlReorder:function(a){this._rtlReorder=
|
|
a},getUnicodeConverter:function(){return this._unicodeConverter},getRtlReorder:function(){return this._rtlReorder}});return{ElementComponentSystem:b}}());Object.assign(pc,function(){return{ElementComponentData:function(){this.enabled=!0}}}());Object.assign(pc,function(){var e=function(a,b,d){this._entity=a;this._element=a.element;this.model=new pc.Model;this.node=new pc.GraphNode;this.model.graph=this.node;this.mesh=b;this.meshInstance=new pc.MeshInstance(this.node,this.mesh,d);this.meshInstance.name="ImageElement: "+a.name;this.meshInstance.castShadow=!1;this._meshDirty=this.meshInstance.receiveShadow=!1;this.model.meshInstances.push(this.meshInstance);this._entity.addChild(this.model.graph);this.model._entity=this._entity;this.unmaskMeshInstance=
|
|
null};e.prototype.destroy=function(){this.setMaterial(null);this._element.removeModelFromLayers(this.model);this.model.destroy();this._element=this._entity=this.meshInstance=this.mesh=this.node=this.model=null};e.prototype.setMesh=function(a){this.meshInstance&&(this.mesh=a,this.meshInstance.mesh=a,this.meshInstance.visible=!!a,this.unmaskMeshInstance&&(this.unmaskMeshInstance.mesh=a),this.forceUpdateAabb())};e.prototype.setMask=function(a){if(this.meshInstance){if(a){this.unmaskMeshInstance=new pc.MeshInstance(this.node,
|
|
this.mesh,this.meshInstance.material);this.unmaskMeshInstance.name="Unmask: "+this._entity.name;this.unmaskMeshInstance.castShadow=!1;this.unmaskMeshInstance.receiveShadow=!1;this.unmaskMeshInstance.pick=!1;this.model.meshInstances.push(this.unmaskMeshInstance);for(var b in this.meshInstance.parameters)this.unmaskMeshInstance.setParameter(b,this.meshInstance.parameters[b].data)}else a=this.model.meshInstances.indexOf(this.unmaskMeshInstance),0<=a&&this.model.meshInstances.splice(a,1),this.unmaskMeshInstance=
|
|
null;this._entity.enabled&&this._element.enabled&&(this._element.removeModelFromLayers(this.model),this._element.addModelToLayers(this.model))}};e.prototype.setMaterial=function(a){this.meshInstance&&(this.meshInstance.material=a,this.unmaskMeshInstance&&(this.unmaskMeshInstance.material=a))};e.prototype.setParameter=function(a,b){this.meshInstance&&(this.meshInstance.setParameter(a,b),this.unmaskMeshInstance&&this.unmaskMeshInstance.setParameter(a,b))};e.prototype.deleteParameter=function(a){this.meshInstance&&
|
|
(this.meshInstance.deleteParameter(a),this.unmaskMeshInstance&&this.unmaskMeshInstance.deleteParameter(a))};e.prototype.setUnmaskDrawOrder=function(){if(this.meshInstance){var a=function(b){var c;b=b.getChildren();var d=b.length;if(d){for(var e=0;e<d;e++)b[e].element&&(c=b[e]);return c?(b=a(c))?b:c:null}return null};if(this.unmaskMeshInstance){var b=a(this._entity);this.unmaskMeshInstance.drawOrder=b&&b.element?b.element.drawOrder+b.element.getMaskOffset():this.meshInstance.drawOrder+this._element.getMaskOffset()}}};
|
|
e.prototype.setDrawOrder=function(a){this.meshInstance&&(this.meshInstance.drawOrder=a)};e.prototype.setCull=function(a){if(this.meshInstance){var b=this._element,d=null;a&&b._isScreenCulled()&&(d=function(a){return b.isVisibleForCamera(a)});this.meshInstance.cull=a;this.meshInstance.isVisibleFunc=d;this.unmaskMeshInstance&&(this.unmaskMeshInstance.cull=a,this.unmaskMeshInstance.isVisibleFunc=d)}};e.prototype.setScreenSpace=function(a){this.meshInstance&&(this.meshInstance.screenSpace=a,this.unmaskMeshInstance&&
|
|
(this.unmaskMeshInstance.screenSpace=a))};e.prototype.setLayer=function(a){this.meshInstance&&(this.meshInstance.layer=a,this.unmaskMeshInstance&&(this.unmaskMeshInstance.layer=a))};e.prototype.forceUpdateAabb=function(a){this.meshInstance&&(this.meshInstance._aabbVer=-1,this.unmaskMeshInstance&&(this.unmaskMeshInstance._aabbVer=-1))};e.prototype.setAabbFunc=function(a){this.meshInstance&&(this.meshInstance._updateAabbFunc=a,this.unmaskMeshInstance&&(this.unmaskMeshInstance._updateAabbFunc=a))};var b=
|
|
function(a){this._element=a;this._entity=a.entity;this._system=a.system;this._sprite=this._spriteAsset=this._material=this._materialAsset=this._texture=this._textureAsset=null;this._spriteFrame=0;this._pixelsPerUnit=null;this._rect=new pc.Vec4(0,0,1,1);this._mask=!1;this._maskRef=0;this._outerScale=new pc.Vec2;this._outerScaleUniform=new Float32Array(2);this._innerOffset=new pc.Vec4;this._innerOffsetUniform=new Float32Array(4);this._atlasRect=new pc.Vec4;this._atlasRectUniform=new Float32Array(4);
|
|
this._defaultMesh=this._createMesh();this._renderable=new e(this._entity,this._defaultMesh,this._material);this._color=new pc.Color(1,1,1,1);this._colorUniform=new Float32Array([1,1,1]);this._renderable.setParameter("material_emissive",this._colorUniform);this._renderable.setParameter("material_opacity",1);this._updateAabbFunc=this._updateAabb.bind(this);this._onScreenChange(this._element.screen);this._element.on("resize",this._onParentResizeOrPivotChange,this);this._element.on("set:pivot",this._onParentResizeOrPivotChange,
|
|
this);this._element.on("screen:set:screenspace",this._onScreenSpaceChange,this);this._element.on("set:screen",this._onScreenChange,this);this._element.on("set:draworder",this._onDrawOrderChange,this);this._element.on("screen:set:resolution",this._onResolutionChange,this)};Object.assign(b.prototype,{destroy:function(){this.materialAsset=this.spriteAsset=this.textureAsset=null;this._renderable.setMesh(this._defaultMesh);this._renderable.destroy();this._defaultMesh=null;this._element.off("resize",this._onParentResizeOrPivotChange,
|
|
this);this._element.off("set:pivot",this._onParentResizeOrPivotChange,this);this._element.off("screen:set:screenspace",this._onScreenSpaceChange,this);this._element.off("set:screen",this._onScreenChange,this);this._element.off("set:draworder",this._onDrawOrderChange,this);this._element.off("screen:set:resolution",this._onResolutionChange,this)},_onResolutionChange:function(a){},_onParentResizeOrPivotChange:function(){this._renderable.mesh&&this._updateMesh(this._renderable.mesh)},_onScreenSpaceChange:function(a){this._updateMaterial(a)},
|
|
_onScreenChange:function(a,b){a?this._updateMaterial(a.screen.screenSpace):this._updateMaterial(!1)},_onDrawOrderChange:function(a){this._renderable.setDrawOrder(a);if(this.mask&&this._element.screen)this._element.screen.screen.once("syncdraworder",function(){this._renderable.setUnmaskDrawOrder()},this)},_hasUserMaterial:function(){return!!this._materialAsset||!!this._material&&-1===this._system.defaultImageMaterials.indexOf(this._material)},_use9Slicing:function(){return this.sprite&&(this.sprite.renderMode===
|
|
pc.SPRITE_RENDERMODE_SLICED||this.sprite.renderMode===pc.SPRITE_RENDERMODE_TILED)},_updateMaterial:function(a){var b=!!this._mask,d=!(!this.sprite||this.sprite.renderMode!==pc.SPRITE_RENDERMODE_SLICED),f=!(!this.sprite||this.sprite.renderMode!==pc.SPRITE_RENDERMODE_TILED);this._hasUserMaterial()||(this._material=this._system.getImageElementMaterial(a,b,d,f));this._renderable&&(this._renderable.setCull(!0),this._renderable.setMaterial(this._material),this._renderable.setScreenSpace(a),this._renderable.setLayer(a?
|
|
pc.LAYER_HUD:pc.LAYER_WORLD))},_createMesh:function(){var a=this._element,b=a.calculatedWidth,a=a.calculatedHeight,d=this._rect,f=new ArrayBuffer(128),e=new Float32Array(f);e[5]=1;e[6]=d.x;e[7]=d.y;e[8]=b;e[13]=1;e[14]=d.x+d.z;e[15]=d.y;e[16]=b;e[17]=a;e[21]=1;e[22]=d.x+d.z;e[23]=d.y+d.w;e[25]=a;e[29]=1;e[30]=d.x;e[31]=d.y+d.w;d=this._system.app.graphicsDevice;e=new pc.VertexFormat(d,[{semantic:pc.SEMANTIC_POSITION,components:3,type:pc.TYPE_FLOAT32},{semantic:pc.SEMANTIC_NORMAL,components:3,type:pc.TYPE_FLOAT32},
|
|
{semantic:pc.SEMANTIC_TEXCOORD0,components:2,type:pc.TYPE_FLOAT32}]);f=new pc.VertexBuffer(d,e,4,pc.BUFFER_STATIC,f);d=new pc.Mesh;d.vertexBuffer=f;d.primitive[0].type=pc.PRIMITIVE_TRIFAN;d.primitive[0].base=0;d.primitive[0].count=4;d.primitive[0].indexed=!1;d.aabb.setMinMax(pc.Vec3.ZERO,new pc.Vec3(b,a,0));this._updateMesh(d);return d},_updateMesh:function(a){var b=this._element,d=b.calculatedWidth,f=b.calculatedHeight,e=b._isScreenSpace();this._updateMaterial(e);this._renderable&&this._renderable.forceUpdateAabb();
|
|
if(!this.sprite||this.sprite.renderMode!==pc.SPRITE_RENDERMODE_SLICED&&this.sprite.renderMode!==pc.SPRITE_RENDERMODE_TILED){var l=a.vertexBuffer,h=new Float32Array(l.lock()),e=b.pivot.x,b=b.pivot.y;h[0]=0-e*d;h[1]=0-b*f;h[8]=d-e*d;h[9]=0-b*f;h[16]=d-e*d;h[17]=f-b*f;h[24]=0-e*d;h[25]=f-b*f;var f=d=1,p=this._rect;if(this._sprite&&this._sprite.frameKeys[this._spriteFrame]&&this._sprite.atlas){var k=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]];k&&(p=k.rect,d=this._sprite.atlas.texture.width,
|
|
f=this._sprite.atlas.texture.height)}h[6]=p.x/d;h[7]=p.y/f;h[14]=(p.x+p.z)/d;h[15]=p.y/f;h[22]=(p.x+p.z)/d;h[23]=(p.y+p.w)/f;h[30]=p.x/d;h[31]=(p.y+p.w)/f;l.unlock();l=new pc.Vec3(0-e*d,0-b*f,0);d=new pc.Vec3(d-e*d,f-b*f,0);a.aabb.setMinMax(l,d);this._renderable&&(this._renderable.node.setLocalScale(1,1,1),this._renderable.node.setLocalPosition(0,0,0),this._renderable.setAabbFunc(null))}else a=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]],e=2/a.rect.z,l=2/a.rect.w,this._innerOffset.set(a.border.x*
|
|
e,a.border.y*l,a.border.z*e,a.border.w*l),e=this.sprite.atlas.texture,this._atlasRect.set(a.rect.x/e.width,a.rect.y/e.height,a.rect.z/e.width,a.rect.w/e.height),l=null!==this._pixelsPerUnit?this._pixelsPerUnit:this.sprite.pixelsPerUnit,e=a.rect.z/l,a=a.rect.w/l,this._outerScale.set(Math.max(d,this._innerOffset.x*e),Math.max(f,this._innerOffset.y*a)),l=a,this._outerScale.x/=e,this._outerScale.y/=a,e*=pc.math.clamp(d/(this._innerOffset.x*e),1E-4,1),l*=pc.math.clamp(f/(this._innerOffset.y*a),1E-4,1),
|
|
this._renderable&&(this._innerOffsetUniform[0]=this._innerOffset.x,this._innerOffsetUniform[1]=this._innerOffset.y,this._innerOffsetUniform[2]=this._innerOffset.z,this._innerOffsetUniform[3]=this._innerOffset.w,this._renderable.setParameter("innerOffset",this._innerOffsetUniform),this._atlasRectUniform[0]=this._atlasRect.x,this._atlasRectUniform[1]=this._atlasRect.y,this._atlasRectUniform[2]=this._atlasRect.z,this._atlasRectUniform[3]=this._atlasRect.w,this._renderable.setParameter("atlasRect",this._atlasRectUniform),
|
|
this._outerScaleUniform[0]=this._outerScale.x,this._outerScaleUniform[1]=this._outerScale.y,this._renderable.setParameter("outerScale",this._outerScaleUniform),this._renderable.setAabbFunc(this._updateAabbFunc),this._renderable.node.setLocalScale(e,l,1),this._renderable.node.setLocalPosition((.5-b.pivot.x)*d,(.5-b.pivot.y)*f,0));this._meshDirty=!1},_updateSprite:function(){var a=!1,b=null;this._sprite&&this._sprite.atlas&&(b=this._sprite.meshes[this.spriteFrame],a=this._sprite.renderMode===pc.SPRITE_RENDERMODE_SLICED||
|
|
this._sprite.renderMode===pc.SPRITE_RENDERMODE_TILED);if(this.mesh=a?b:this._defaultMesh)this._element._beingInitialized?this._meshDirty=!0:this._updateMesh(this.mesh)},_updateAabb:function(a){a.center.set(0,0,0);a.halfExtents.set(.5*this._outerScale.x,.5*this._outerScale.y,.001);a.setFromTransformedAabb(a,this._renderable.node.getWorldTransform());return a},_toggleMask:function(){this._element._dirtifyMask();var a=this._element._isScreenSpace();this._updateMaterial(a);this._renderable.setMask(!!this._mask)},
|
|
_onMaterialLoad:function(a){this.material=a.resource},_onMaterialAdded:function(a){this._system.app.assets.off("add:"+a.id,this._onMaterialAdded,this);this._materialAsset===a.id&&this._bindMaterialAsset(a)},_bindMaterialAsset:function(a){this._entity.enabled&&(a.on("load",this._onMaterialLoad,this),a.on("change",this._onMaterialChange,this),a.on("remove",this._onMaterialRemove,this),a.resource?this._onMaterialLoad(a):this._system.app.assets.load(a))},_unbindMaterialAsset:function(a){a.off("load",
|
|
this._onMaterialLoad,this);a.off("change",this._onMaterialChange,this);a.off("remove",this._onMaterialRemove,this)},_onMaterialChange:function(){},_onMaterialRemove:function(){},_onTextureAdded:function(a){this._system.app.assets.off("add:"+a.id,this._onTextureAdded,this);this._textureAsset===a.id&&this._bindTextureAsset(a)},_bindTextureAsset:function(a){this._entity.enabled&&(a.on("load",this._onTextureLoad,this),a.on("change",this._onTextureChange,this),a.on("remove",this._onTextureRemove,this),
|
|
a.resource?this._onTextureLoad(a):this._system.app.assets.load(a))},_unbindTextureAsset:function(a){a.off("load",this._onTextureLoad,this);a.off("change",this._onTextureChange,this);a.off("remove",this._onTextureRemove,this)},_onTextureLoad:function(a){this.texture=a.resource},_onTextureChange:function(a){},_onTextureRemove:function(a){},_onSpriteAssetAdded:function(a){this._system.app.assets.off("add:"+a.id,this._onSpriteAssetAdded,this);this._spriteAsset===a.id&&this._bindSpriteAsset(a)},_bindSpriteAsset:function(a){this._entity.enabled&&
|
|
(a.on("load",this._onSpriteAssetLoad,this),a.on("change",this._onSpriteAssetChange,this),a.on("remove",this._onSpriteAssetRemove,this),a.resource?this._onSpriteAssetLoad(a):this._system.app.assets.load(a))},_unbindSpriteAsset:function(a){a.off("load",this._onSpriteAssetLoad,this);a.off("change",this._onSpriteAssetChange,this);a.off("remove",this._onSpriteAssetRemove,this);a.data.textureAtlasAsset&&this._system.app.assets.off("load:"+a.data.textureAtlasAsset,this._onTextureAtlasLoad,this)},_onSpriteAssetLoad:function(a){if(a&&
|
|
a.resource)if(a.resource.atlas)this.sprite=a.resource;else{if(a=a.data.textureAtlasAsset){var b=this._system.app.assets;b.off("load:"+a,this._onTextureAtlasLoad,this);b.once("load:"+a,this._onTextureAtlasLoad,this)}}else this.sprite=null},_onSpriteAssetChange:function(a){this._onSpriteAssetLoad(a)},_onSpriteAssetRemove:function(a){},_bindSprite:function(a){a.on("set:meshes",this._onSpriteMeshesChange,this);a.on("set:pixelsPerUnit",this._onSpritePpuChange,this);a.on("set:atlas",this._onAtlasTextureChange,
|
|
this);if(a.atlas)a.atlas.on("set:texture",this._onAtlasTextureChange,this)},_unbindSprite:function(a){a.off("set:meshes",this._onSpriteMeshesChange,this);a.off("set:pixelsPerUnit",this._onSpritePpuChange,this);a.off("set:atlas",this._onAtlasTextureChange,this);a.atlas&&a.atlas.off("set:texture",this._onAtlasTextureChange,this)},_onSpriteMeshesChange:function(){this._sprite&&(this._spriteFrame=pc.math.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1));this._updateSprite()},_onSpritePpuChange:function(){this.sprite.renderMode!==
|
|
pc.SPRITE_RENDERMODE_SIMPLE&&null===this._pixelsPerUnit&&this._updateSprite()},_onAtlasTextureChange:function(){this.sprite&&this.sprite.atlas&&this.sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"))},_onTextureAtlasLoad:function(a){a=this._spriteAsset;a instanceof
|
|
pc.Asset?this._onSpriteAssetLoad(a):this._onSpriteAssetLoad(this._system.app.assets.get(a))},onEnable:function(){var a;this._materialAsset&&(a=this._system.app.assets.get(this._materialAsset))&&a.resource!==this._material&&this._bindMaterialAsset(a);this._textureAsset&&(a=this._system.app.assets.get(this._textureAsset))&&a.resource!==this._texture&&this._bindTextureAsset(a);this._spriteAsset&&(a=this._system.app.assets.get(this._spriteAsset))&&a.resource!==this._sprite&&this._bindSpriteAsset(a);this._element.addModelToLayers(this._renderable.model)},
|
|
onDisable:function(){this._element.removeModelFromLayers(this._renderable.model)},_setStencil:function(a){this._renderable.meshInstance.stencilFront=a;this._renderable.meshInstance.stencilBack=a;a=0;this._element.maskedBy&&(a=this._element.maskedBy.element._image._maskRef);this._renderable.unmaskMeshInstance&&(a=new pc.StencilParameters({ref:a+1,func:pc.FUNC_EQUAL,zpass:pc.STENCILOP_DECREMENT}),this._renderable.unmaskMeshInstance.stencilFront=a,this._renderable.unmaskMeshInstance.stencilBack=a)}});
|
|
Object.defineProperty(b.prototype,"color",{get:function(){return this._color},set:function(a){var b=a.r,d=a.g;a=a.b;if(this._color.r!==b||this._color.g!==d||this._color.b!==a)this._color.r=b,this._color.g=d,this._color.b=a,this._colorUniform[0]=b,this._colorUniform[1]=d,this._colorUniform[2]=a,this._renderable.setParameter("material_emissive",this._colorUniform),this._element&&this._element.fire("set:color",this._color)}});Object.defineProperty(b.prototype,"opacity",{get:function(){return this._color.a},
|
|
set:function(a){a!==this._color.a&&(this._color.a=a,this._renderable.setParameter("material_opacity",a),this._element&&this._element.fire("set:opacity",a))}});Object.defineProperty(b.prototype,"rect",{get:function(){return this._rect},set:function(a){var b,d,f;a instanceof pc.Vec4?(b=a.x,d=a.y,f=a.z,a=a.w):(b=a[0],d=a[1],f=a[2],a=a[3]);if(b!==this._rect.x||d!==this._rect.y||f!==this._rect.z||a!==this._rect.w)this._rect.set(b,d,f,a),this._renderable.mesh&&(this._element._beingInitialized?this._meshDirty=
|
|
!0:this._updateMesh(this._renderable.mesh))}});Object.defineProperty(b.prototype,"material",{get:function(){return this._material},set:function(a){this._material!==a&&(a||(a=this._element._isScreenSpace(),a=this.mask?a?this._system.defaultScreenSpaceImageMaskMaterial:this._system.defaultImageMaskMaterial:a?this._system.defaultScreenSpaceImageMaterial:this._system.defaultImageMaterial),this._material=a)&&(this._renderable.setMaterial(a),this._hasUserMaterial()?(this._renderable.deleteParameter("material_opacity"),
|
|
this._renderable.deleteParameter("material_emissive")):(this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._renderable.setParameter("material_emissive",this._colorUniform),this._renderable.setParameter("material_opacity",this._color.a)))}});Object.defineProperty(b.prototype,"materialAsset",{get:function(){return this._materialAsset},set:function(a){var b=this._system.app.assets,d=a;a instanceof pc.Asset&&(d=a.id);this._materialAsset!==
|
|
d&&(this._materialAsset&&(b.off("add:"+this._materialAsset,this._onMaterialAdded,this),a=b.get(this._materialAsset))&&(a.off("load",this._onMaterialLoad,this),a.off("change",this._onMaterialChange,this),a.off("remove",this._onMaterialRemove,this)),(this._materialAsset=d)?(d=b.get(this._materialAsset))?this._bindMaterialAsset(d):(this.material=null,b.on("add:"+this._materialAsset,this._onMaterialAdded,this)):this.material=null)}});Object.defineProperty(b.prototype,"texture",{get:function(){return this._texture},
|
|
set:function(a){if(this._texture!==a){if(this._textureAsset){var b=this._system.app.assets.get(this._textureAsset);b&&b.resource!==a&&(this.textureAsset=null)}(this._texture=a)?(this._spriteAsset&&(this.spriteAsset=null),this._renderable.setParameter("texture_emissiveMap",this._texture),this._renderable.setParameter("texture_opacityMap",this._texture),this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._renderable.setParameter("material_emissive",
|
|
this._colorUniform),this._renderable.setParameter("material_opacity",this._color.a)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"))}}});Object.defineProperty(b.prototype,"textureAsset",{get:function(){return this._textureAsset},set:function(a){var b=this._system.app.assets,d=a;a instanceof pc.Asset&&(d=a.id);this._textureAsset!==d&&(this._textureAsset&&(b.off("add:"+this._textureAsset,this._onTextureAdded,this),a=b.get(this._textureAsset))&&
|
|
(a.off("load",this._onTextureLoad,this),a.off("change",this._onTextureChange,this),a.off("remove",this._onTextureRemove,this)),(this._textureAsset=d)?(d=b.get(this._textureAsset))?this._bindTextureAsset(d):(this.texture=null,b.on("add:"+this._textureAsset,this._onTextureAdded,this)):this.texture=null)}});Object.defineProperty(b.prototype,"spriteAsset",{get:function(){return this._spriteAsset},set:function(a){var b=this._system.app.assets,d=a;a instanceof pc.Asset&&(d=a.id);this._spriteAsset!==d&&
|
|
(this._spriteAsset&&(b.off("add:"+this._spriteAsset,this._onSpriteAssetAdded,this),(a=b.get(this._spriteAsset))&&this._unbindSpriteAsset(a)),(this._spriteAsset=d)?(a=b.get(this._spriteAsset))?this._bindSpriteAsset(a):(this.sprite=null,b.on("add:"+this._spriteAsset,this._onSpriteAssetAdded,this)):this.sprite=null,this._element&&this._element.fire("set:spriteAsset",d))}});Object.defineProperty(b.prototype,"sprite",{get:function(){return this._sprite},set:function(a){if(this._sprite!==a){this._sprite&&
|
|
this._unbindSprite(this._sprite);if(this._spriteAsset){var b=this._system.app.assets.get(this._spriteAsset);b&&b.resource!==a&&(this.spriteAsset=null)}if(this._sprite=a)this._bindSprite(this._sprite),this._textureAsset&&(this.textureAsset=null);this._sprite&&this._sprite.atlas&&this._sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),
|
|
this._renderable.deleteParameter("texture_opacityMap"));this._sprite&&(this._spriteFrame=pc.math.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1));this._updateSprite()}}});Object.defineProperty(b.prototype,"spriteFrame",{get:function(){return this._spriteFrame},set:function(a){var b=this._spriteFrame;this._spriteFrame=this._sprite?pc.math.clamp(a,0,this._sprite.frameKeys.length-1):a;this._spriteFrame!==b&&(this._updateSprite(),this._element&&this._element.fire("set:spriteFrame",a))}});Object.defineProperty(b.prototype,
|
|
"mesh",{get:function(){return this._renderable.mesh},set:function(a){this._renderable.setMesh(a);this._defaultMesh===a?this._renderable.setAabbFunc(null):this._renderable.setAabbFunc(this._updateAabbFunc)}});Object.defineProperty(b.prototype,"mask",{get:function(){return this._mask},set:function(a){this._mask!==a&&(this._mask=a,this._toggleMask())}});Object.defineProperty(b.prototype,"pixelsPerUnit",{get:function(){return this._pixelsPerUnit},set:function(a){this._pixelsPerUnit!==a&&(this._pixelsPerUnit=
|
|
a,!this._sprite||this._sprite.renderMode!==pc.SPRITE_RENDERMODE_SLICED&&this._sprite.renderMode!==pc.SPRITE_RENDERMODE_TILED||this._updateSprite())}});Object.defineProperty(b.prototype,"aabb",{get:function(){return this._renderable.meshInstance?this._renderable.meshInstance.aabb:null}});return{ImageElement:b}}());Object.assign(pc,function(){var e=function(){this.quad=this.count=0;this.lines={};this.positions=[];this.normals=[];this.uvs=[];this.indices=[];this.meshInstance=null},b=function(a){this._element=a;this._system=a.system;this._entity=a.entity;this._text="";this._font=this._fontAsset=this._i18nKey=null;this._color=new pc.Color(1,1,1,1);this._colorUniform=new Float32Array(3);this._spacing=1;this._fontSize=32;this._fontMaxY=this._fontMinY=0;this._maxFontSize=this._originalFontSize=32;this._minFontSize=
|
|
8;this._autoFitHeight=this._autoFitWidth=!1;this._maxLines=-1;this._scaledLineHeight=this._lineHeight=32;this._wrapLines=!1;this._drawOrder=0;this._alignment=new pc.Vec2(.5,.5);this._autoHeight=this._autoWidth=!0;this.height=this.width=0;this._node=new pc.GraphNode;this._model=new pc.Model;this._model.graph=this._node;this._entity.addChild(this._node);this._meshInfo=[];this._material=null;this._aabbDirty=!0;this._aabb=new pc.BoundingBox;this._noResize=!1;this._maskedMaterialSrc=this._currentMaterialType=
|
|
null;this._unicodeConverter=this._rtlReorder=!1;this._outlineColor=new pc.Color(0,0,0,1);this._outlineColorUniform=new Float32Array(4);this._outlineThicknessScale=.2;this._outlineThickness=0;this._shadowColor=new pc.Color(0,0,0,1);this._shadowColorUniform=new Float32Array(4);this._shadowOffsetScale=.005;this._shadowOffset=new pc.Vec2(0,0);this._shadowOffsetUniform=new Float32Array(2);this._onScreenChange(this._element.screen);a.on("resize",this._onParentResize,this);a.on("set:screen",this._onScreenChange,
|
|
this);a.on("screen:set:screenspace",this._onScreenSpaceChange,this);a.on("set:draworder",this._onDrawOrderChange,this);a.on("set:pivot",this._onPivotChange,this);this._system.app.i18n.on("set:locale",this._resetLocalizedText,this);this._system.app.i18n.on("data:add",this._onLocalizationData,this);this._system.app.i18n.on("data:remove",this._onLocalizationData,this)},a=/^[\r\n]$/,c=/^[ \t]$/,d=/^[ \t\-]$/;Object.assign(b.prototype,{destroy:function(){this._setMaterial(null);this._model&&(this._element.removeModelFromLayers(this._model),
|
|
this._model.destroy(),this._model=null);this.font=this.fontAsset=null;this._element.off("resize",this._onParentResize,this);this._element.off("set:screen",this._onScreenChange,this);this._element.off("screen:set:screenspace",this._onScreenSpaceChange,this);this._element.off("set:draworder",this._onDrawOrderChange,this);this._element.off("set:pivot",this._onPivotChange,this);this._system.app.i18n.off("set:locale",this._resetLocalizedText,this);this._system.app.i18n.off("data:add",this._onLocalizationData,
|
|
this);this._system.app.i18n.off("data:remove",this._onLocalizationData,this)},_onParentResize:function(a,b){this._noResize||this._font&&this._updateText(this._text)},_onScreenChange:function(a){a?this._updateMaterial(a.screen.screenSpace):this._updateMaterial(!1)},_onScreenSpaceChange:function(a){this._updateMaterial(a)},_onDrawOrderChange:function(a){this._drawOrder=a;if(this._model){var b,c;b=0;for(c=this._model.meshInstances.length;b<c;b++)this._model.meshInstances[b].drawOrder=a}},_onPivotChange:function(a){this._font&&
|
|
this._updateText()},_onLocalizationData:function(a,b){this._i18nKey&&b[this._i18nKey]&&this._resetLocalizedText()},_resetLocalizedText:function(){this._i18nKey&&this._setText(this._system.app.i18n.getText(this._i18nKey))},_setText:function(a){if(this.unicodeConverter){var b=this._system.getUnicodeConverter();b?a=b(a):console.warn("Element created with unicodeConverter option but no unicodeConverter function registered")}this._text!==a&&(this._font&&this._updateText(a),this._text=a)},_updateText:function(a){var b,
|
|
c;void 0===a&&(a=this._text);a=pc.string.getSymbols(a);this.rtlReorder&&((b=this._system.app.systems.element.getRtlReorder())?a=b(a):console.warn("Element created with rtlReorder option but no rtlReorder function registered"));c=a.length;0===c&&(c=1,a=[" "]);var d={},f;for(b=0;b<c;b++)f=a[b],(f=this._font.data.chars[f])||(f=this._font.data.chars[" "]?this._font.data.chars[" "]:this._font.data.chars[Object.keys(this._font.data.chars)[0]]),f=f.map,d[f]||(d[f]=0),d[f]++;f=!1;var e=this._element,n=e._isScreenSpace(),
|
|
q=e._isScreenCulled(),m=function(a){return e.isVisibleForCamera(a)};b=0;for(c=this._meshInfo.length;b<c;b++){var r=d[b]||0,t=this._meshInfo[b];if(t.count!==r)if(f||(e.removeModelFromLayers(this._model),f=!0),t.count=r,t.positions.length=t.normals.length=12*r,t.indices.length=6*r,t.uvs.length=8*r,t.meshInstance&&(this._removeMeshInstance(t.meshInstance),t.meshInstance.material=null),0===r)t.meshInstance=null;else{for(var u=0;u<r;u++)t.indices[6*u+0]=4*u,t.indices[6*u+1]=4*u+1,t.indices[6*u+2]=4*u+
|
|
3,t.indices[6*u+3]=4*u+2,t.indices[6*u+4]=4*u+3,t.indices[6*u+5]=4*u+1,t.normals[12*u+0]=0,t.normals[12*u+1]=0,t.normals[12*u+2]=-1,t.normals[12*u+3]=0,t.normals[12*u+4]=0,t.normals[12*u+5]=-1,t.normals[12*u+6]=0,t.normals[12*u+7]=0,t.normals[12*u+8]=-1,t.normals[12*u+9]=0,t.normals[12*u+10]=0,t.normals[12*u+11]=-1;r=pc.createMesh(this._system.app.graphicsDevice,t.positions,{uvs:t.uvs,normals:t.normals,indices:t.indices});r=new pc.MeshInstance(this._node,r,this._material);r.name="Text Element: "+
|
|
this._entity.name;r.castShadow=!1;r.receiveShadow=!1;r.cull=!n;r.screenSpace=n;r.drawOrder=this._drawOrder;q&&(r.cull=!0,r.isVisibleFunc=m);this._setTextureParams(r,this._font.textures[b]);this._colorUniform[0]=this._color.r;this._colorUniform[1]=this._color.g;this._colorUniform[2]=this._color.b;r.setParameter("material_emissive",this._colorUniform);r.setParameter("material_opacity",this._color.a);r.setParameter("font_sdfIntensity",this._font.intensity);r.setParameter("font_pxrange",this._getPxRange(this._font));
|
|
r.setParameter("font_textureWidth",this._font.data.info.maps[b].width);this._outlineColorUniform[0]=this._outlineColor.r;this._outlineColorUniform[1]=this._outlineColor.g;this._outlineColorUniform[2]=this._outlineColor.b;this._outlineColorUniform[3]=this._outlineColor.a;r.setParameter("outline_color",this._outlineColorUniform);r.setParameter("outline_thickness",this._outlineThicknessScale*this._outlineThickness);this._shadowColorUniform[0]=this._shadowColor.r;this._shadowColorUniform[1]=this._shadowColor.g;
|
|
this._shadowColorUniform[2]=this._shadowColor.b;this._shadowColorUniform[3]=this._shadowColor.a;r.setParameter("shadow_color",this._shadowColorUniform);u=this._font.data.info.maps[b].width/this._font.data.info.maps[b].height;this._shadowOffsetUniform[0]=this._shadowOffsetScale*this._shadowOffset.x;this._shadowOffsetUniform[1]=u*this._shadowOffsetScale*this._shadowOffset.y;r.setParameter("shadow_offset",this._shadowOffsetUniform);t.meshInstance=r;this._model.meshInstances.push(r)}}this._element.maskedBy&&
|
|
this._element._setMaskedBy(this._element.maskedBy);f&&this._element.enabled&&this._entity.enabled&&this._element.addModelToLayers(this._model);this._updateMeshes(a)},_removeMeshInstance:function(a){var b,c,d=a.mesh;if(d&&(d.vertexBuffer&&d.vertexBuffer.destroy(),d.indexBuffer))for(b=0,c=d.indexBuffer.length;b<c;b++)d.indexBuffer[b].destroy();a=this._model.meshInstances.indexOf(a);-1!==a&&this._model.meshInstances.splice(a,1)},_setMaterial:function(a){var b,c;this._material=a;if(this._model)for(b=
|
|
0,c=this._model.meshInstances.length;b<c;b++)this._model.meshInstances[b].material=a},_updateMaterial:function(a){var b=this._element,c=b._isScreenCulled(),d=function(a){return b.isVisibleForCamera(a)};this._material=this._system.getTextElementMaterial(a,this._font&&this._font.type===pc.FONT_MSDF);if(this._model)for(var f=0,e=this._model.meshInstances.length;f<e;f++){var n=this._model.meshInstances[f];n.cull=!a;n.material=this._material;n.screenSpace=a;c?(n.cull=!0,n.isVisibleFunc=d):n.isVisibleFunc=
|
|
null}},_updateMeshes:function(b){function f(c,d){h._lineWidths.push(d);var f=b.slice(y,c);if(z)for(var e=f.length;e--&&0<z;)a.test(f[e])&&(f.splice(e,1),z--);f=f.join("");h._lineContents.push(f);m=0;t-=h._scaledLineHeight;x++;v=z=B=D=0;y=c}var e=this._font.data,h=this,p=Math.min(this._minFontSize,this._maxFontSize),k=this._maxFontSize,n=this._shouldAutoFit();n&&(this._fontSize=this._maxFontSize);var q=b.length,m=0,r=0,t=0,u=0,x=1,v=0,w=0,y=0,D=0,B=0,z=0,A=1E-4<=Math.abs(this._element.anchor.x-this._element.anchor.z),
|
|
F=this._element.calculatedWidth;if(this.autoWidth&&!A||!this._wrapLines)F=Number.POSITIVE_INFINITY;for(var I=0,A=0,G=1,H,C,E,K=!0;K;){K=!1;this._scaledLineHeight=n?this._lineHeight*this._fontSize/(this._maxFontSize||1E-4):this._lineHeight;this.height=this.width=0;this._lineWidths=[];this._lineContents=[];u=t=r=m=0;x=1;z=B=D=y=w=v=0;G=this._fontSize/32;I=this._fontMinY*G;A=this._fontMaxY*G;for(E=0;E<this._meshInfo.length;E++)this._meshInfo[E].quad=0,this._meshInfo[E].lines={};for(E=0;E<q;E++){H=b[E];
|
|
var N=0,X=0,M=0,U=1,aa=0,V=0,P;C=e.chars[H];if(!C)if(e.chars[" "])C=e.chars[" "];else for(var T in e.chars){C=e.chars[T];break}C?(P=C.scale||1,M=(C.width+C.height)/2,U=G*M/P,M=C.xadvance*G,N=C.xoffset*G,X=C.yoffset*G,C.bounds?(V=(C.bounds[2]-C.bounds[0])*G,aa=C.bounds[0]*G):(V=N,aa=0)):console.error("Couldn't substitute missing character: '"+H+"'");var Y=a.test(H);if(Y){if(z++,0>this._maxLines||x<this._maxLines)f(E,r),w=E+1,y=E+1}else{var L=c.test(H);P=this._meshInfo[C&&C.map||0];if(m+V+aa>=F&&0<
|
|
B&&!L&&(0>this._maxLines||x<this._maxLines))if(0===D)w=E,f(E,r);else{C=Math.max(E-w,0);if(1>=this._meshInfo.length)P.lines[x-1]-=C,P.quad-=C;else for(H=w;H<E;H++)P=e.chars[b[H]],P=this._meshInfo[P&&P.map||0],--P.lines[x-1],--P.quad;E-=C+1;f(w,v);continue}C=P.quad;P.lines[x-1]=C;P.positions[12*C+0]=m-N;P.positions[12*C+1]=t-X;P.positions[12*C+2]=u;P.positions[12*C+3]=m-N+U;P.positions[12*C+4]=t-X;P.positions[12*C+5]=u;P.positions[12*C+6]=m-N+U;P.positions[12*C+7]=t-X+U;P.positions[12*C+8]=u;P.positions[12*
|
|
C+9]=m-N;P.positions[12*C+10]=t-X+U;P.positions[12*C+11]=u;this.width=Math.max(this.width,m+V+aa);if(this._shouldAutoFitWidth()&&this.width>this._element.calculatedWidth&&(N=Math.floor(this._element.fontSize*this._element.calculatedWidth/(this.width||1E-4)),N=pc.math.clamp(N,p,k),N!==this._element.fontSize)){this._fontSize=N;K=!0;break}this.height=Math.max(this.height,A-(t+I));if(this._shouldAutoFitHeight()&&this.height>this._element.calculatedHeight&&(N=pc.math.clamp(this._fontSize-1,p,k),N!==this._element.fontSize)){this._fontSize=
|
|
N;K=!0;break}m+=this._spacing*M;L||Y||(r=m);d.test(H)&&(D++,v=r,w=E+1);B++;H=this._getUv(H);P.uvs[8*C+0]=H[0];P.uvs[8*C+1]=H[1];P.uvs[8*C+2]=H[2];P.uvs[8*C+3]=H[1];P.uvs[8*C+4]=H[2];P.uvs[8*C+5]=H[3];P.uvs[8*C+6]=H[0];P.uvs[8*C+7]=H[3];P.quad++}}K||y<q&&f(q,m)}this._noResize=!0;this.autoWidth=this._autoWidth;this.autoHeight=this._autoHeight;this._noResize=!1;e=this._element.pivot.x;p=this._element.pivot.y;k=this._alignment.x;n=this._alignment.y;for(E=0;E<this._meshInfo.length;E++)if(0!==this._meshInfo[E].count){var r=
|
|
0,Q;for(Q in this._meshInfo[E].lines){q=this._meshInfo[E].lines[Q];F=-e*this._element.calculatedWidth+k*(this._element.calculatedWidth-this._lineWidths[parseInt(Q,10)]);T=(1-p)*this._element.calculatedHeight-A-(1-n)*(this._element.calculatedHeight-this.height);for(C=r;C<=q;C++)this._meshInfo[E].positions[12*C]+=F,this._meshInfo[E].positions[12*C+3]+=F,this._meshInfo[E].positions[12*C+6]+=F,this._meshInfo[E].positions[12*C+9]+=F,this._meshInfo[E].positions[12*C+1]+=T,this._meshInfo[E].positions[12*
|
|
C+4]+=T,this._meshInfo[E].positions[12*C+7]+=T,this._meshInfo[E].positions[12*C+10]+=T;r=q+1}q=4*this._meshInfo[E].count;F=4*this._meshInfo[E].quad;T=new pc.VertexIterator(this._meshInfo[E].meshInstance.mesh.vertexBuffer);for(r=0;r<q;r++)r>=F?(T.element[pc.SEMANTIC_POSITION].set(0,0,0),T.element[pc.SEMANTIC_TEXCOORD0].set(0,0)):(T.element[pc.SEMANTIC_POSITION].set(this._meshInfo[E].positions[3*r+0],this._meshInfo[E].positions[3*r+1],this._meshInfo[E].positions[3*r+2]),T.element[pc.SEMANTIC_TEXCOORD0].set(this._meshInfo[E].uvs[2*
|
|
r+0],this._meshInfo[E].uvs[2*r+1])),T.next();T.end();this._meshInfo[E].meshInstance.mesh.aabb.compute(this._meshInfo[E].positions);this._meshInfo[E].meshInstance._aabbVer=-1}this._aabbDirty=!0},_onFontAdded:function(a){this._system.app.assets.off("add:"+a.id,this._onFontAdded,this);a.id===this._fontAsset&&this._bindFont(a)},_bindFont:function(a){this._entity.enabled&&(a.on("load",this._onFontLoad,this),a.on("change",this._onFontChange,this),a.on("remove",this._onFontRemove,this),a.resource?this._onFontLoad(a):
|
|
this._system.app.assets.load(a))},_unbindFont:function(a){a.off("load",this._onFontLoad,this);a.off("change",this._onFontChange,this);a.off("remove",this._onFontRemove,this)},_onFontRender:function(){this.font=this._font},_onFontLoad:function(a){this.font!==a.resource&&(this.font=a.resource)},_onFontChange:function(a,b,c,d){if("data"===b)for(this._font.data=c,a=this._font.data.info.maps.length,b=0;b<a;b++)this._meshInfo[b]&&(c=this._meshInfo[b].meshInstance)&&(c.setParameter("font_sdfIntensity",this._font.intensity),
|
|
c.setParameter("font_pxrange",this._getPxRange(this._font)),c.setParameter("font_textureWidth",this._font.data.info.maps[b].width))},_onFontRemove:function(a){},_setTextureParams:function(a,b){this._font&&(this._font.type===pc.FONT_MSDF?(a.deleteParameter("texture_emissiveMap"),a.deleteParameter("texture_opacityMap"),a.setParameter("texture_msdfMap",b)):this._font.type===pc.FONT_BITMAP&&(a.deleteParameter("texture_msdfMap"),a.setParameter("texture_emissiveMap",b),a.setParameter("texture_opacityMap",
|
|
b)))},_getPxRange:function(a){a=Object.keys(this._font.data.chars);for(var b=0;b<a.length;b++){var c=this._font.data.chars[a[b]];if(c.range)return(c.scale||1)*c.range}return 2},_getUv:function(a){var b=this._font.data;if(!b.chars[a])return b.chars[" "]?this._getUv(" "):[0,0,0,0];var c=b.chars[a].map,d=b.info.maps[c].width,c=b.info.maps[c].height,f=b.chars[a].x,e=b.chars[a].y,n=1-b.chars[a].height/c;return[f/d,n-e/c,(f+b.chars[a].width)/d,n-(e-b.chars[a].height)/c]},onEnable:function(){if(this._fontAsset){var a=
|
|
this._system.app.assets.get(this._fontAsset);a&&a.resource!==this._font&&(this._unbindFont(a),this._bindFont(a))}this._model&&this._element.addModelToLayers(this._model)},onDisable:function(){this._model&&this._element.removeModelFromLayers(this._model)},_setStencil:function(a){if(this._model)for(var b=this._model.meshInstances,c=0;c<b.length;c++)b[c].stencilFront=a,b[c].stencilBack=a},_shouldAutoFitWidth:function(){return this._autoFitWidth&&!this._autoWidth},_shouldAutoFitHeight:function(){return this._autoFitHeight&&
|
|
!this._autoHeight},_shouldAutoFit:function(){return this._autoFitWidth&&!this._autoWidth||this._autoFitHeight&&!this._autoHeight}});Object.defineProperty(b.prototype,"text",{get:function(){return this._text},set:function(a){this._i18nKey=null;this._setText(a&&a.toString()||"")}});Object.defineProperty(b.prototype,"key",{get:function(){return this._i18nKey},set:function(a){a=null!==a?a.toString():null;this._i18nKey!==a&&(this._i18nKey=a,this._resetLocalizedText())}});Object.defineProperty(b.prototype,
|
|
"color",{get:function(){return this._color},set:function(a){var b=a.r,c=a.g;a=a.b;if(this._color.r!==b||this._color.g!==c||this._color.b!==a)if(this._color.r=b,this._color.g=c,this._color.b=a,this._model)for(this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,b=0,c=this._model.meshInstances.length;b<c;b++)this._model.meshInstances[b].setParameter("material_emissive",this._colorUniform)}});Object.defineProperty(b.prototype,"opacity",{get:function(){return this._color.a},
|
|
set:function(a){if(this._color.a!==a&&(this._color.a=a,this._model))for(var b=0,c=this._model.meshInstances.length;b<c;b++)this._model.meshInstances[b].setParameter("material_opacity",a)}});Object.defineProperty(b.prototype,"lineHeight",{get:function(){return this._lineHeight},set:function(a){var b=this._lineHeight;this._scaledLineHeight=this._lineHeight=a;b!==a&&this._font&&this._updateText()}});Object.defineProperty(b.prototype,"wrapLines",{get:function(){return this._wrapLines},set:function(a){var b=
|
|
this._wrapLines;this._wrapLines=a;b!==a&&this._font&&this._updateText()}});Object.defineProperty(b.prototype,"lines",{get:function(){return this._lineContents}});Object.defineProperty(b.prototype,"spacing",{get:function(){return this._spacing},set:function(a){var b=this._spacing;this._spacing=a;b!==a&&this._font&&this._updateText()}});Object.defineProperty(b.prototype,"fontSize",{get:function(){return this._fontSize},set:function(a){var b=this._fontSize;this._originalFontSize=this._fontSize=a;b!==
|
|
a&&this._font&&this._updateText()}});Object.defineProperty(b.prototype,"fontAsset",{get:function(){return this._fontAsset},set:function(a){var b=this._system.app.assets,c=a;a instanceof pc.Asset&&(c=a.id);if(this._fontAsset!==c&&(this._fontAsset&&(b.off("add:"+this._fontAsset,this._onFontAdded,this),(a=b.get(this._fontAsset))&&this._unbindFont(a)),this._fontAsset=c))if(c=b.get(this._fontAsset))this._bindFont(c);else b.on("add:"+this._fontAsset,this._onFontAdded,this)}});Object.defineProperty(b.prototype,
|
|
"font",{get:function(){return this._font},set:function(a){var b;this._font&&(b=this._font.type,this._font.off&&this._font.off("render",this._onFontRender,this));this._font=a;this._fontMaxY=this._fontMinY=0;if(a){var c=this._font.data,d;for(d in c.chars){var f=c.chars[d];f.bounds&&(this._fontMinY=Math.min(this._fontMinY,f.bounds[1]),this._fontMaxY=Math.max(this._fontMaxY,f.bounds[3]))}if(this._font.on)this._font.on("render",this._onFontRender,this);this._fontAsset&&(c=this._system.app.assets.get(this._fontAsset),
|
|
c.resource!==this._font&&(this._unbindFont(c),this._fontAsset=null));a.type!==b&&(a=this._element._isScreenSpace(),this._updateMaterial(a));a=0;for(b=this._font.textures.length;a<b;a++)if(this._meshInfo[a]){if(c=this._meshInfo[a].meshInstance)c.setParameter("font_sdfIntensity",this._font.intensity),c.setParameter("font_pxrange",this._getPxRange(this._font)),c.setParameter("font_textureWidth",this._font.data.info.maps[a].width),this._setTextureParams(c,this._font.textures[a])}else this._meshInfo[a]=
|
|
new e;b=!1;for(a=this._font.textures.length;a<this._meshInfo.length;a++)this._meshInfo[a].meshInstance&&(b||(this._element.removeModelFromLayers(this._model),b=!0),this._removeMeshInstance(this._meshInfo[a].meshInstance));this._meshInfo.length>this._font.textures.length&&(this._meshInfo.length=this._font.textures.length);this._updateText()}}});Object.defineProperty(b.prototype,"alignment",{get:function(){return this._alignment},set:function(a){a instanceof pc.Vec2?this._alignment.set(a.x,a.y):this._alignment.set(a[0],
|
|
a[1]);this._font&&this._updateText()}});Object.defineProperty(b.prototype,"autoWidth",{get:function(){return this._autoWidth},set:function(a){var b=this._autoWidth;(this._autoWidth=a)&&1E-4>Math.abs(this._element.anchor.x-this._element.anchor.z)&&(this._element.width=this.width);b!==a&&(a=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize,a!==this._fontSize&&(this._fontSize=a,this._font&&this._updateText()))}});Object.defineProperty(b.prototype,"autoHeight",{get:function(){return this._autoHeight},
|
|
set:function(a){var b=this._autoHeight;(this._autoHeight=a)&&1E-4>Math.abs(this._element.anchor.y-this._element.anchor.w)&&(this._element.height=this.height);b!==a&&(a=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize,a!==this._fontSize&&(this._fontSize=a,this._font&&this._updateText()))}});Object.defineProperty(b.prototype,"rtlReorder",{get:function(){return this._rtlReorder},set:function(a){this._rtlReorder!==a&&(this._rtlReorder=a,this._font&&this._updateText())}});Object.defineProperty(b.prototype,
|
|
"unicodeConverter",{get:function(){return this._unicodeConverter},set:function(a){this._unicodeConverter!==a&&(this._unicodeConverter=a,this.text=this._text)}});Object.defineProperty(b.prototype,"aabb",{get:function(){if(this._aabbDirty){for(var a=!1,b=0;b<this._meshInfo.length;b++)this._meshInfo[b].meshInstance&&(a?this._aabb.add(this._meshInfo[b].meshInstance.aabb):(this._aabb.copy(this._meshInfo[b].meshInstance.aabb),a=!0));this._aabbDirty=!1}return this._aabb}});Object.defineProperty(b.prototype,
|
|
"outlineColor",{get:function(){return this._outlineColor},set:function(a){var b=a instanceof pc.Color?a.r:a[0],c=a instanceof pc.Color?a.g:a[1],d=a instanceof pc.Color?a.b:a[2];a=a instanceof pc.Color?a.a:a[3];if(this._outlineColor.r!==b||this._outlineColor.g!==c||this._outlineColor.b!==d||this._outlineColor.a!==a)if(this._outlineColor.r=b,this._outlineColor.g=c,this._outlineColor.b=d,this._outlineColor.a=a,this._model)for(this._outlineColorUniform[0]=this._outlineColor.r,this._outlineColorUniform[1]=
|
|
this._outlineColor.g,this._outlineColorUniform[2]=this._outlineColor.b,this._outlineColorUniform[3]=this._outlineColor.a,b=0,c=this._model.meshInstances.length;b<c;b++)this._model.meshInstances[b].setParameter("outline_color",this._outlineColorUniform)}});Object.defineProperty(b.prototype,"outlineThickness",{get:function(){return this._outlineThickness},set:function(a){var b=this._outlineThickness;this._outlineThickness=a;if(b!==a&&this._font&&this._model)for(a=0,b=this._model.meshInstances.length;a<
|
|
b;a++)this._model.meshInstances[a].setParameter("outline_thickness",this._outlineThicknessScale*this._outlineThickness)}});Object.defineProperty(b.prototype,"shadowColor",{get:function(){return this._shadowColor},set:function(a){var b=a instanceof pc.Color?a.r:a[0],c=a instanceof pc.Color?a.g:a[1],d=a instanceof pc.Color?a.b:a[2];a=a instanceof pc.Color?a.a:a[3];if(this._shadowColor.r!==b||this._shadowColor.g!==c||this._shadowColor.b!==d||this._shadowColor.a!==a)if(this._shadowColor.r=b,this._shadowColor.g=
|
|
c,this._shadowColor.b=d,this._shadowColor.a=a,this._model)for(this._shadowColorUniform[0]=this._shadowColor.r,this._shadowColorUniform[1]=this._shadowColor.g,this._shadowColorUniform[2]=this._shadowColor.b,this._shadowColorUniform[3]=this._shadowColor.a,b=0,c=this._model.meshInstances.length;b<c;b++)this._model.meshInstances[b].setParameter("shadow_color",this._shadowColorUniform)}});Object.defineProperty(b.prototype,"shadowOffset",{get:function(){return this._shadowOffset},set:function(a){var b=
|
|
a instanceof pc.Vec2?a.x:a[0];a=a instanceof pc.Vec2?a.y:a[1];if(this._shadowOffset.x!==b||this._shadowOffset.y!==a)if(this._shadowOffset.set(b,a),this._font&&this._model)for(b=0,a=this._model.meshInstances.length;b<a;b++){var c=this._font.data.info.maps[b].width/this._font.data.info.maps[b].height;this._shadowOffsetUniform[0]=this._shadowOffsetScale*this._shadowOffset.x;this._shadowOffsetUniform[1]=c*this._shadowOffsetScale*this._shadowOffset.y;this._model.meshInstances[b].setParameter("shadow_offset",
|
|
this._shadowOffsetUniform)}}});Object.defineProperty(b.prototype,"minFontSize",{get:function(){return this._minFontSize},set:function(a){this._minFontSize!==a&&(this._minFontSize=a,this.font&&this._shouldAutoFit()&&this._updateText())}});Object.defineProperty(b.prototype,"maxFontSize",{get:function(){return this._maxFontSize},set:function(a){this._maxFontSize!==a&&(this._maxFontSize=a,this.font&&this._shouldAutoFit()&&this._updateText())}});Object.defineProperty(b.prototype,"autoFitWidth",{get:function(){return this._autoFitWidth},
|
|
set:function(a){this._autoFitWidth!==a&&(this._autoFitWidth=a,this._fontSize=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize,this.font&&this._updateText())}});Object.defineProperty(b.prototype,"autoFitHeight",{get:function(){return this._autoFitHeight},set:function(a){this._autoFitHeight!==a&&(this._autoFitHeight=a,this._fontSize=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize,this.font&&this._updateText())}});Object.defineProperty(b.prototype,"maxLines",{get:function(){return this._maxLines},
|
|
set:function(a){this._maxLines===a||null===a&&-1===this._maxLines||(this._maxLines=null===a?-1:a,this.font&&this._wrapLines&&this._updateText())}});return{TextElement:b}}());Object.assign(pc,function(){var e=new pc.Vec2,b=new pc.Vec3,a=new pc.Vec3,c=new pc.Vec3,d=new pc.Vec3,f=new pc.Vec3,g=new pc.Quat,l={x:"y",y:"x"},h=function(a,b){if(!(a&&a instanceof pc.ElementComponent))throw Error("Element was null or not an ElementComponent");if(b&&"x"!==b&&"y"!==b)throw Error("Unrecognized axis: "+b);this._element=a;this._app=a.system.app;this._axis=b||null;this._enabled=!0;this._dragScale=new pc.Vec3;this._dragStartMousePosition=new pc.Vec3;this._dragStartHandlePosition=new pc.Vec3;
|
|
this._deltaMousePosition=new pc.Vec3;this._deltaHandlePosition=new pc.Vec3;this._isDragging=!1;pc.events.attach(this);this._toggleLifecycleListeners("on")};Object.assign(h.prototype,{_toggleLifecycleListeners:function(a){this._element[a]("mousedown",this._onMouseDownOrTouchStart,this);this._element[a]("touchstart",this._onMouseDownOrTouchStart,this)},_toggleDragListeners:function(a){var b="on"===a,c=b?"addEventListener":"removeEventListener";this._hasDragListeners&&b||(this._handleMouseUpOrTouchEnd||
|
|
(this._handleMouseUpOrTouchEnd=this._onMouseUpOrTouchEnd.bind(this)),this._app.mouse[a]("mousemove",this._onMove,this),window[c]("mouseup",this._handleMouseUpOrTouchEnd,!1),pc.platform.touch&&(this._app.touch[a]("touchmove",this._onMove,this),window[c]("touchend",this._handleMouseUpOrTouchEnd,!1),window[c]("touchcancel",this._handleMouseUpOrTouchEnd,!1)),this._hasDragListeners=b)},_onMouseDownOrTouchStart:function(a){this._element&&!this._isDragging&&this.enabled&&(this._dragCamera=a.camera,this._calculateDragScale(),
|
|
a=this._screenToLocal(a))&&(this._toggleDragListeners("on"),this._isDragging=!0,this._dragStartMousePosition.copy(a),this._dragStartHandlePosition.copy(this._element.entity.getLocalPosition()),this.fire("drag:start"))},_onMouseUpOrTouchEnd:function(){this._isDragging&&(this._isDragging=!1,this._toggleDragListeners("off"),this.fire("drag:end"))},_screenToLocal:function(b){this._determineInputPosition(b);this._chooseRayOriginAndDirection();d.copy(this._element.entity.getPosition());f.copy(this._element.entity.forward).scale(-1);
|
|
b=f.dot(c);return 0<Math.abs(b)?(b=d.sub(a).dot(f)/b,b=a.add(c.scale(b)),g.copy(this._element.entity.getRotation()).invert().transformVector(b,b),b.mul(this._dragScale),b):null},_determineInputPosition:function(a){var b=this._app.graphicsDevice.maxPixelRatio;"undefined"!==typeof a.x&&"undefined"!==typeof a.y?(e.x=a.x*b,e.y=a.y*b):a.changedTouches?(e.x=a.changedTouches[0].x*b,e.y=a.changedTouches[0].y*b):console.warn("Could not determine position from input event")},_chooseRayOriginAndDirection:function(){this._element.screen&&
|
|
this._element.screen.screen.screenSpace?(a.set(e.x,-e.y,0),c.set(0,0,-1)):(b.copy(this._dragCamera.screenToWorld(e.x,e.y,1)),a.copy(this._dragCamera.entity.getPosition()),c.copy(b).sub(a).normalize())},_calculateDragScale:function(){var a=this._element.entity.parent,b=this._element.screen&&this._element.screen.screen,c=b&&b.screenSpace,b=c?b.scale:1,d=this._dragScale;for(d.set(b,b,b);a&&(d.mul(a.getLocalScale()),a=a.parent,!c||!a.screen););d.x=1/d.x;d.y=1/d.y;d.z=1/d.z},_onMove:function(a){if(this._element&&
|
|
this._isDragging&&this.enabled&&this._element.enabled&&this._element.entity.enabled&&(a=this._screenToLocal(a),this._dragStartMousePosition&&a)){this._deltaMousePosition.copy(a).sub(this._dragStartMousePosition);this._deltaHandlePosition.copy(this._dragStartHandlePosition).add(this._deltaMousePosition);if(this._axis){a=this._element.entity.getLocalPosition();var b=l[this._axis];this._deltaHandlePosition[b]=a[b]}this._element.entity.setLocalPosition(this._deltaHandlePosition);this.fire("drag:move",
|
|
this._deltaHandlePosition)}},destroy:function(){this._toggleLifecycleListeners("off");this._toggleDragListeners("off")}});Object.defineProperty(h.prototype,"enabled",{get:function(){return this._enabled},set:function(a){this._enabled=a}});Object.defineProperty(h.prototype,"isDragging",{get:function(){return this._isDragging}});return{ElementDragHelper:h}}());Object.assign(pc,{BUTTON_TRANSITION_MODE_TINT:0,BUTTON_TRANSITION_MODE_SPRITE_CHANGE:1});Object.assign(pc,function(){var e={DEFAULT:"_defaultTint",HOVER:"hoverTint",PRESSED:"pressedTint",INACTIVE:"inactiveTint"},b={DEFAULT:"_defaultSpriteAsset",HOVER:"hoverSpriteAsset",PRESSED:"pressedSpriteAsset",INACTIVE:"inactiveSpriteAsset"},a={DEFAULT:"_defaultSpriteFrame",HOVER:"hoverSpriteFrame",PRESSED:"pressedSpriteFrame",INACTIVE:"inactiveSpriteFrame"},c=function(a,b){pc.Component.call(this,a,b);this._visualState="DEFAULT";this._isPressed=this._isHovering=!1;this._defaultTint=new pc.Color(1,
|
|
1,1,1);this._defaultSpriteAsset=null;this._defaultSpriteFrame=0;this._imageReference=new pc.EntityReference(this,"imageEntity",{"element#gain":this._onImageElementGain,"element#lose":this._onImageElementLose,"element#set:color":this._onSetColor,"element#set:opacity":this._onSetOpacity,"element#set:spriteAsset":this._onSetSpriteAsset,"element#set:spriteFrame":this._onSetSpriteFrame});this._toggleLifecycleListeners("on",a)};c.prototype=Object.create(pc.Component.prototype);c.prototype.constructor=c;
|
|
Object.assign(c.prototype,{_toggleLifecycleListeners:function(a,b){this[a]("set_active",this._onSetActive,this);this[a]("set_transitionMode",this._onSetTransitionMode,this);this[a]("set_hoverTint",this._onSetTransitionValue,this);this[a]("set_pressedTint",this._onSetTransitionValue,this);this[a]("set_inactiveTint",this._onSetTransitionValue,this);this[a]("set_hoverSpriteAsset",this._onSetTransitionValue,this);this[a]("set_hoverSpriteFrame",this._onSetTransitionValue,this);this[a]("set_pressedSpriteAsset",
|
|
this._onSetTransitionValue,this);this[a]("set_pressedSpriteFrame",this._onSetTransitionValue,this);this[a]("set_inactiveSpriteAsset",this._onSetTransitionValue,this);this[a]("set_inactiveSpriteFrame",this._onSetTransitionValue,this);b.app.systems.element[a]("add",this._onElementComponentAdd,this);b.app.systems.element[a]("beforeremove",this._onElementComponentRemove,this)},_onSetActive:function(a,b,c){b!==c&&this._updateVisualState()},_onSetTransitionMode:function(a,b,c){b!==c&&(this._cancelTween(),
|
|
this._resetToDefaultVisualState(b),this._forceReapplyVisualState())},_onSetTransitionValue:function(a,b,c){b!==c&&this._forceReapplyVisualState()},_onElementComponentRemove:function(a){this.entity===a&&this._toggleHitElementListeners("off")},_onElementComponentAdd:function(a){this.entity===a&&this._toggleHitElementListeners("on")},_onImageElementLose:function(){this._cancelTween();this._resetToDefaultVisualState(this.transitionMode)},_onImageElementGain:function(){this._storeDefaultVisualState();
|
|
this._forceReapplyVisualState()},_toggleHitElementListeners:function(a){if(this.entity.element){var b="on"===a;b&&this._hasHitElementListeners||(this.entity.element[a]("mouseenter",this._onMouseEnter,this),this.entity.element[a]("mouseleave",this._onMouseLeave,this),this.entity.element[a]("mousedown",this._onMouseDown,this),this.entity.element[a]("mouseup",this._onMouseUp,this),this.entity.element[a]("touchstart",this._onTouchStart,this),this.entity.element[a]("touchend",this._onTouchEnd,this),this.entity.element[a]("touchleave",
|
|
this._onTouchLeave,this),this.entity.element[a]("touchcancel",this._onTouchCancel,this),this.entity.element[a]("click",this._onClick,this),this._hasHitElementListeners=b)}},_storeDefaultVisualState:function(){this._imageReference.hasComponent("element")&&(this._storeDefaultColor(this._imageReference.entity.element.color),this._storeDefaultOpacity(this._imageReference.entity.element.opacity),this._storeDefaultSpriteAsset(this._imageReference.entity.element.spriteAsset),this._storeDefaultSpriteFrame(this._imageReference.entity.element.spriteFrame))},
|
|
_storeDefaultColor:function(a){this._defaultTint.r=a.r;this._defaultTint.g=a.g;this._defaultTint.b=a.b},_storeDefaultOpacity:function(a){this._defaultTint.a=a},_storeDefaultSpriteAsset:function(a){this._defaultSpriteAsset=a},_storeDefaultSpriteFrame:function(a){this._defaultSpriteFrame=a},_onSetColor:function(a){this._isApplyingTint||(this._storeDefaultColor(a),this._forceReapplyVisualState())},_onSetOpacity:function(a){this._isApplyingTint||(this._storeDefaultOpacity(a),this._forceReapplyVisualState())},
|
|
_onSetSpriteAsset:function(a){this._isApplyingSprite||(this._storeDefaultSpriteAsset(a),this._forceReapplyVisualState())},_onSetSpriteFrame:function(a){this._isApplyingSprite||(this._storeDefaultSpriteFrame(a),this._forceReapplyVisualState())},_onMouseEnter:function(a){this._isHovering=!0;this._updateVisualState();this._fireIfActive("mouseenter",a)},_onMouseLeave:function(a){this._isPressed=this._isHovering=!1;this._updateVisualState();this._fireIfActive("mouseleave",a)},_onMouseDown:function(a){this._isPressed=
|
|
!0;this._updateVisualState();this._fireIfActive("mousedown",a)},_onMouseUp:function(a){this._isPressed=!1;this._updateVisualState();this._fireIfActive("mouseup",a)},_onTouchStart:function(a){this._isPressed=!0;this._updateVisualState();this._fireIfActive("touchstart",a)},_onTouchEnd:function(a){a.event.preventDefault();this._isPressed=!1;this._updateVisualState();this._fireIfActive("touchend",a)},_onTouchLeave:function(a){this._isPressed=!1;this._updateVisualState();this._fireIfActive("touchleave",
|
|
a)},_onTouchCancel:function(a){this._isPressed=!1;this._updateVisualState();this._fireIfActive("touchcancel",a)},_onClick:function(a){this._fireIfActive("click",a)},_fireIfActive:function(a,b){this.data.active&&this.fire(a,b)},_updateVisualState:function(c){var d=this._visualState,g=this._determineVisualState();if((d!==g||c)&&this.enabled)switch(this._visualState=g,"HOVER"===d&&this._fireIfActive("hoverend"),"PRESSED"===d&&this._fireIfActive("pressedend"),"HOVER"===g&&this._fireIfActive("hoverstart"),
|
|
"PRESSED"===g&&this._fireIfActive("pressedstart"),this.transitionMode){case pc.BUTTON_TRANSITION_MODE_TINT:this._applyTint(this[e[this._visualState]]);break;case pc.BUTTON_TRANSITION_MODE_SPRITE_CHANGE:this._applySprite(this[b[this._visualState]],this[a[this._visualState]])}},_forceReapplyVisualState:function(){this._updateVisualState(!0)},_resetToDefaultVisualState:function(a){if(this._imageReference.hasComponent("element"))switch(a){case pc.BUTTON_TRANSITION_MODE_TINT:this._cancelTween();this._applyTintImmediately(this._defaultTint);
|
|
break;case pc.BUTTON_TRANSITION_MODE_SPRITE_CHANGE:this._applySprite(this._defaultSpriteAsset,this._defaultSpriteFrame)}},_determineVisualState:function(){if(this.active){if(this._isPressed)return"PRESSED";if(this._isHovering)return"HOVER"}else return"INACTIVE";return"DEFAULT"},_applySprite:function(a,b){b=b||0;this._imageReference.hasComponent("element")&&(this._isApplyingSprite=!0,this._imageReference.entity.element.spriteAsset=a,this._imageReference.entity.element.spriteFrame=b,this._isApplyingSprite=
|
|
!1)},_applyTint:function(a){this._cancelTween();0===this.fadeDuration?this._applyTintImmediately(a):this._applyTintWithTween(a)},_applyTintImmediately:function(a){this._imageReference.hasComponent("element")&&a&&(this._isApplyingTint=!0,this._imageReference.entity.element.color=new pc.Color(a.r,a.g,a.b),this._imageReference.entity.element.opacity=a.a,this._isApplyingTint=!1)},_applyTintWithTween:function(a){if(this._imageReference.hasComponent("element")&&a){var b=this._imageReference.entity.element.color,
|
|
c=this._imageReference.entity.element.opacity;this._tweenInfo={startTime:pc.now(),from:new pc.Color(b.r,b.g,b.b,c),to:a.clone(),lerpColor:new pc.Color}}},_updateTintTween:function(){var a=pc.now()-this._tweenInfo.startTime,a=0===this.fadeDuration?1:a/this.fadeDuration,a=pc.math.clamp(a,0,1);if(1E-5<Math.abs(a-1)){var b=this._tweenInfo.lerpColor;b.lerp(this._tweenInfo.from,this._tweenInfo.to,a);this._applyTintImmediately(new pc.Color(b.r,b.g,b.b,b.a))}else this._applyTintImmediately(this._tweenInfo.to),
|
|
this._cancelTween()},_cancelTween:function(){delete this._tweenInfo},onUpdate:function(){this._tweenInfo&&this._updateTintTween()},onEnable:function(){this._imageReference.onParentComponentEnable();this._toggleHitElementListeners("on");this._forceReapplyVisualState()},onDisable:function(){this._toggleHitElementListeners("off");this._resetToDefaultVisualState(this.transitionMode)},onRemove:function(){this._toggleLifecycleListeners("off",this.system);this.onDisable()}});return{ButtonComponent:c}}());Object.assign(pc,function(){var e=["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"],b=function(a){pc.ComponentSystem.call(this,a);this.id="button";this.app=a;this.ComponentType=pc.ButtonComponent;this.DataType=
|
|
pc.ButtonComponentData;this.schema=e;this.on("beforeremove",this._onRemoveComponent,this);pc.ComponentSystem.bind("update",this.onUpdate,this)};b.prototype=Object.create(pc.ComponentSystem.prototype);b.prototype.constructor=b;pc.Component._buildAccessors(pc.ButtonComponent.prototype,e);Object.assign(b.prototype,{initializeComponentData:function(a,b,d){pc.ComponentSystem.prototype.initializeComponentData.call(this,a,b,e)},onUpdate:function(a){a=this.store;for(var b in a){var d=a[b].entity,f=d.button;
|
|
if(f.enabled&&d.enabled)f.onUpdate()}},_onRemoveComponent:function(a,b){b.onRemove()}});return{ButtonComponentSystem:b}}());Object.assign(pc,function(){return{ButtonComponentData:function(){this.active=this.enabled=!0;this.imageEntity=null;this.hitPadding=new pc.Vec4;this.transitionMode=pc.BUTTON_TRANSITION_MODE_TINT;this.hoverTint=new pc.Color(.75,.75,.75);this.pressedTint=new pc.Color(.5,.5,.5);this.inactiveTint=new pc.Color(.25,.25,.25);this.fadeDuration=0;this.hoverSpriteAsset=null;this.hoverSpriteFrame=0;this.pressedSpriteAsset=null;this.pressedSpriteFrame=0;this.inactiveSpriteAsset=null;this.inactiveSpriteFrame=
|
|
0}}}());Object.assign(pc,{SCROLL_MODE_CLAMP:0,SCROLL_MODE_BOUNCE:1,SCROLL_MODE_INFINITE:2,SCROLLBAR_VISIBILITY_SHOW_ALWAYS:0,SCROLLBAR_VISIBILITY_SHOW_WHEN_REQUIRED:1});Object.assign(pc,function(){var e=new pc.Vec2,b=function(a,b){pc.Component.call(this,a,b);this._viewportReference=new pc.EntityReference(this,"viewportEntity",{"element#gain":this._onViewportElementGain,"element#resize":this._onSetContentOrViewportSize});this._contentReference=new pc.EntityReference(this,"contentEntity",{"element#gain":this._onContentElementGain,"element#lose":this._onContentElementLose,"element#resize":this._onSetContentOrViewportSize});this._scrollbarUpdateFlags={};this._scrollbarReferences=
|
|
{};this._scrollbarReferences[pc.ORIENTATION_HORIZONTAL]=new pc.EntityReference(this,"horizontalScrollbarEntity",{"scrollbar#set:value":this._onSetHorizontalScrollbarValue,"scrollbar#gain":this._onHorizontalScrollbarGain});this._scrollbarReferences[pc.ORIENTATION_VERTICAL]=new pc.EntityReference(this,"verticalScrollbarEntity",{"scrollbar#set:value":this._onSetVerticalScrollbarValue,"scrollbar#gain":this._onVerticalScrollbarGain});this._prevContentSizes={};this._prevContentSizes[pc.ORIENTATION_HORIZONTAL]=
|
|
null;this._prevContentSizes[pc.ORIENTATION_VERTICAL]=null;this._scroll=new pc.Vec2;this._velocity=new pc.Vec3;this._dragStartPosition=new pc.Vec3;this._disabledContentInput=!1;this._disabledContentInputEntities=[];this._toggleLifecycleListeners("on",a);this._toggleElementListeners("on")};b.prototype=Object.create(pc.Component.prototype);b.prototype.constructor=b;Object.assign(b.prototype,{_toggleLifecycleListeners:function(a,b){this[a]("set_horizontal",this._onSetHorizontalScrollingEnabled,this);
|
|
this[a]("set_vertical",this._onSetVerticalScrollingEnabled,this);b.app.systems.element[a]("add",this._onElementComponentAdd,this);b.app.systems.element[a]("beforeremove",this._onElementComponentRemove,this)},_toggleElementListeners:function(a){!this.entity.element||"on"===a&&this._hasElementListeners||(this.entity.element[a]("resize",this._onSetContentOrViewportSize,this),this._hasElementListeners="on"===a)},_onElementComponentAdd:function(a){this.entity===a&&this._toggleElementListeners("on")},_onElementComponentRemove:function(a){this.entity===
|
|
a&&this._toggleElementListeners("off")},_onViewportElementGain:function(){this._syncAll()},_onContentElementGain:function(){this._destroyDragHelper();this._contentDragHelper=new pc.ElementDragHelper(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[pc.ORIENTATION_HORIZONTAL]=null;this._prevContentSizes[pc.ORIENTATION_VERTICAL]=
|
|
null;this._syncAll()},_onContentElementLose:function(){this._destroyDragHelper()},_onContentDragStart:function(){this._contentReference.entity&&this.enabled&&this.entity.enabled&&this._dragStartPosition.copy(this._contentReference.entity.getLocalPosition())},_onContentDragEnd:function(){this._prevContentDragPosition=null;this._enableContentInput()},_onContentDragMove:function(a){if(this._contentReference.entity&&this.enabled&&this.entity.enabled&&(this._wasDragged=!0,this._setScrollFromContentPosition(a),
|
|
this._setVelocityFromContentPositionDelta(a),!this._disabledContentInput)){var b=a.y-this._dragStartPosition.y;(Math.abs(a.x-this._dragStartPosition.x)>this.dragThreshold||Math.abs(b)>this.dragThreshold)&&this._disableContentInput()}},_onSetContentOrViewportSize:function(){this._syncAll()},_onSetHorizontalScrollbarValue:function(a){!this._scrollbarUpdateFlags[pc.ORIENTATION_HORIZONTAL]&&this.enabled&&this.entity.enabled&&this._onSetScroll(a,null)},_onSetVerticalScrollbarValue:function(a){!this._scrollbarUpdateFlags[pc.ORIENTATION_VERTICAL]&&
|
|
this.enabled&&this.entity.enabled&&this._onSetScroll(null,a)},_onSetHorizontalScrollingEnabled:function(){this._syncScrollbarEnabledState(pc.ORIENTATION_HORIZONTAL)},_onSetVerticalScrollingEnabled:function(){this._syncScrollbarEnabledState(pc.ORIENTATION_VERTICAL)},_onHorizontalScrollbarGain:function(){this._syncScrollbarEnabledState(pc.ORIENTATION_HORIZONTAL);this._syncScrollbarPosition(pc.ORIENTATION_HORIZONTAL)},_onVerticalScrollbarGain:function(){this._syncScrollbarEnabledState(pc.ORIENTATION_VERTICAL);
|
|
this._syncScrollbarPosition(pc.ORIENTATION_VERTICAL)},_onSetScroll:function(a,b,d){!1!==d&&this._velocity.set(0,0,0);a=0|this._updateAxis(a,"x",pc.ORIENTATION_HORIZONTAL);(a|=this._updateAxis(b,"y",pc.ORIENTATION_VERTICAL))&&this.fire("set:scroll",this._scroll)},_updateAxis:function(a,b,d){var c=null!==a&&1E-5<Math.abs(a-this._scroll[b]);if(c||this._isDragging()||0===a)this._scroll[b]=this._determineNewScrollValue(a,b,d),this._syncContentPosition(d),this._syncScrollbarPosition(d);return c},_determineNewScrollValue:function(a,
|
|
b,d){if(!this._getScrollingEnabled(d))return this._scroll[b];switch(this.scrollMode){case pc.SCROLL_MODE_CLAMP:return pc.math.clamp(a,0,this._getMaxScrollValue(d));case pc.SCROLL_MODE_BOUNCE:return this._setVelocityFromOvershoot(a,b,d),a;case pc.SCROLL_MODE_INFINITE:return a;default:return console.warn("Unhandled scroll mode:"+this.scrollMode),a}},_syncAll:function(){this._syncContentPosition(pc.ORIENTATION_HORIZONTAL);this._syncContentPosition(pc.ORIENTATION_VERTICAL);this._syncScrollbarPosition(pc.ORIENTATION_HORIZONTAL);
|
|
this._syncScrollbarPosition(pc.ORIENTATION_VERTICAL);this._syncScrollbarEnabledState(pc.ORIENTATION_HORIZONTAL);this._syncScrollbarEnabledState(pc.ORIENTATION_VERTICAL)},_syncContentPosition:function(a){var b=this._getAxis(a),d=this._getSign(a),f=this._contentReference.entity;if(f){var e=this._prevContentSizes[a],l=this._getContentSize(a);if(null!==e&&1E-4<Math.abs(e-l)){var e=this._getMaxOffset(a,e),h=this._getMaxOffset(a,l);this._scroll[b]=0===h?1:pc.math.clamp(this._scroll[b]*e/h,0,1)}e=this._scroll[b]*
|
|
this._getMaxOffset(a);h=f.getLocalPosition();h[b]=e*d;f.setLocalPosition(h);this._prevContentSizes[a]=l}},_syncScrollbarPosition:function(a){var b=this._getAxis(a),d=this._scrollbarReferences[a].entity;d&&d.scrollbar&&(this._scrollbarUpdateFlags[a]=!0,d.scrollbar.value=this._scroll[b],d.scrollbar.handleSize=this._getScrollbarHandleSize(b,a),this._scrollbarUpdateFlags[a]=!1)},_syncScrollbarEnabledState:function(a){var b=this._scrollbarReferences[a].entity;if(b){var d=this._getScrollingEnabled(a),f=
|
|
this._getScrollbarVisibility(a);switch(f){case pc.SCROLLBAR_VISIBILITY_SHOW_ALWAYS:b.enabled=d;break;case pc.SCROLLBAR_VISIBILITY_SHOW_WHEN_REQUIRED:b.enabled=d&&this._contentIsLargerThanViewport(a);break;default:console.warn("Unhandled scrollbar visibility:"+f),b.enabled=d}}},_contentIsLargerThanViewport:function(a){return this._getContentSize(a)>this._getViewportSize(a)},_contentPositionToScrollValue:function(a){var b=this._getMaxOffset(pc.ORIENTATION_HORIZONTAL),d=this._getMaxOffset(pc.ORIENTATION_VERTICAL);
|
|
e.x=0===b?0:a.x/b;e.y=0===d?0:a.y/-d;return e},_getMaxOffset:function(a,b){b=void 0===b?this._getContentSize(a):b;var c=this._getViewportSize(a);return b<c?-this._getViewportSize(a):c-b},_getMaxScrollValue:function(a){return this._contentIsLargerThanViewport(a)?1:0},_getScrollbarHandleSize:function(a,b){var c=this._getViewportSize(b),f=this._getContentSize(b);if(.001>Math.abs(f))return 1;c=Math.min(c/f,1);f=this._toOvershoot(this._scroll[a],b);return 0===f?c:c/(1+Math.abs(f))},_getViewportSize:function(a){return this._getSize(a,
|
|
this._viewportReference)},_getContentSize:function(a){return this._getSize(a,this._contentReference)},_getSize:function(a,b){return b.entity&&b.entity.element?b.entity.element[this._getCalculatedDimension(a)]:0},_getScrollingEnabled:function(a){if(a===pc.ORIENTATION_HORIZONTAL)return this.horizontal;if(a===pc.ORIENTATION_VERTICAL)return this.vertical;console.warn("Unrecognized orientation: "+a)},_getScrollbarVisibility:function(a){if(a===pc.ORIENTATION_HORIZONTAL)return this.horizontalScrollbarVisibility;
|
|
if(a===pc.ORIENTATION_VERTICAL)return this.verticalScrollbarVisibility;console.warn("Unrecognized orientation: "+a)},_getSign:function(a){return a===pc.ORIENTATION_HORIZONTAL?1:-1},_getAxis:function(a){return a===pc.ORIENTATION_HORIZONTAL?"x":"y"},_getCalculatedDimension:function(a){return a===pc.ORIENTATION_HORIZONTAL?"calculatedWidth":"calculatedHeight"},_destroyDragHelper:function(){this._contentDragHelper&&this._contentDragHelper.destroy()},onUpdate:function(){this._contentReference.entity&&(this._updateVelocity(),
|
|
this._syncScrollbarEnabledState(pc.ORIENTATION_HORIZONTAL),this._syncScrollbarEnabledState(pc.ORIENTATION_VERTICAL))},_updateVelocity:function(){if(!this._isDragging()&&(this.scrollMode===pc.SCROLL_MODE_BOUNCE&&(this._hasOvershoot("x",pc.ORIENTATION_HORIZONTAL)&&this._setVelocityFromOvershoot(this.scroll.x,"x",pc.ORIENTATION_HORIZONTAL),this._hasOvershoot("y",pc.ORIENTATION_VERTICAL)&&this._setVelocityFromOvershoot(this.scroll.y,"y",pc.ORIENTATION_VERTICAL)),this._velocity.x*=1-this.friction,this._velocity.y*=
|
|
1-this.friction,1E-4<Math.abs(this._velocity.x)||1E-4<Math.abs(this._velocity.y))){var a=this._contentReference.entity.getLocalPosition();a.x+=this._velocity.x;a.y+=this._velocity.y;this._contentReference.entity.setLocalPosition(a);this._setScrollFromContentPosition(a)}},_hasOvershoot:function(a,b){return.001<Math.abs(this._toOvershoot(this.scroll[a],b))},_toOvershoot:function(a,b){var c=this._getMaxScrollValue(b);return 0>a?a:a>c?a-c:0},_setVelocityFromOvershoot:function(a,b,d){a=this._toOvershoot(a,
|
|
d)*this._getMaxOffset(d)*this._getSign(d);0<Math.abs(a)&&(this._velocity[b]=-a/(50*this.bounceAmount+1))},_setVelocityFromContentPositionDelta:function(a){this._prevContentDragPosition?(this._velocity.sub2(a,this._prevContentDragPosition),this._prevContentDragPosition.copy(a)):(this._velocity.set(0,0,0),this._prevContentDragPosition=a.clone())},_setScrollFromContentPosition:function(a){a=this._contentPositionToScrollValue(a);this._isDragging()&&(a=this._applyScrollValueTension(a));this._onSetScroll(a.x,
|
|
a.y,!1)},_applyScrollValueTension:function(a){var b,d;b=this._getMaxScrollValue(pc.ORIENTATION_HORIZONTAL);d=this._toOvershoot(a.x,pc.ORIENTATION_HORIZONTAL);0<d?a.x=b+1*Math.log10(1+d):0>d&&(a.x=-1*Math.log10(1-d));b=this._getMaxScrollValue(pc.ORIENTATION_VERTICAL);d=this._toOvershoot(a.y,pc.ORIENTATION_VERTICAL);0<d?a.y=b+1*Math.log10(1+d):0>d&&(a.y=-1*Math.log10(1-d));return a},_isDragging:function(){return this._contentDragHelper&&this._contentDragHelper.isDragging},_setScrollbarComponentsEnabled:function(a){this._scrollbarReferences[pc.ORIENTATION_HORIZONTAL].hasComponent("scrollbar")&&
|
|
(this._scrollbarReferences[pc.ORIENTATION_HORIZONTAL].entity.scrollbar.enabled=a);this._scrollbarReferences[pc.ORIENTATION_VERTICAL].hasComponent("scrollbar")&&(this._scrollbarReferences[pc.ORIENTATION_VERTICAL].entity.scrollbar.enabled=a)},_setContentDraggingEnabled:function(a){this._contentDragHelper&&(this._contentDragHelper.enabled=a)},_enableContentInput:function(){for(;this._disabledContentInputEntities.length;){var a=this._disabledContentInputEntities.pop();a.element&&(a.element.useInput=!0)}this._disabledContentInput=
|
|
!1},_disableContentInput:function(){var a=this,b=function(c){c.element&&c.element.useInput&&(a._disabledContentInputEntities.push(c),c.element.useInput=!1);c=c.children;var d,f;d=0;for(f=c.length;d<f;d++)b(c[d])},d=this._contentReference.entity;if(d){var d=d.children,f,e=d.length;for(f=0;f<e;f++)b(d[f])}this._disabledContentInput=!0},onEnable:function(){this._viewportReference.onParentComponentEnable();this._contentReference.onParentComponentEnable();this._scrollbarReferences[pc.ORIENTATION_HORIZONTAL].onParentComponentEnable();
|
|
this._scrollbarReferences[pc.ORIENTATION_VERTICAL].onParentComponentEnable();this._setScrollbarComponentsEnabled(!0);this._setContentDraggingEnabled(!0);this._syncAll()},onDisable:function(){this._setScrollbarComponentsEnabled(!1);this._setContentDraggingEnabled(!1)},onRemove:function(){this._toggleLifecycleListeners("off",this.system);this._toggleElementListeners("off");this._destroyDragHelper()}});Object.defineProperty(b.prototype,"scroll",{get:function(){return this._scroll},set:function(a){this._onSetScroll(a.x,
|
|
a.y)}});return{ScrollViewComponent:b}}());Object.assign(pc,function(){var e=[{name:"enabled",type:"boolean"},{name:"horizontal",type:"boolean"},{name:"vertical",type:"boolean"},{name:"scrollMode",type:"number"},{name:"bounceAmount",type:"number"},{name:"friction",type:"number"},{name:"dragThreshold",type:"number"},{name:"horizontalScrollbarVisibility",type:"number"},{name:"verticalScrollbarVisibility",type:"number"},{name:"viewportEntity",type:"entity"},{name:"contentEntity",type:"entity"},{name:"horizontalScrollbarEntity",type:"entity"},
|
|
{name:"verticalScrollbarEntity",type:"entity"}],b=function(a){pc.ComponentSystem.call(this,a);this.id="scrollview";this.app=a;this.ComponentType=pc.ScrollViewComponent;this.DataType=pc.ScrollViewComponentData;this.schema=e;this.on("beforeremove",this._onRemoveComponent,this);pc.ComponentSystem.bind("update",this.onUpdate,this)};b.prototype=Object.create(pc.ComponentSystem.prototype);b.prototype.constructor=b;pc.Component._buildAccessors(pc.ScrollViewComponent.prototype,e);Object.assign(b.prototype,
|
|
{initializeComponentData:function(a,b,d){void 0===b.dragThreshold&&(b.dragThreshold=10);pc.ComponentSystem.prototype.initializeComponentData.call(this,a,b,e)},onUpdate:function(a){a=this.store;for(var b in a){var d=a[b].entity,f=d.scrollview;if(f.enabled&&d.enabled)f.onUpdate()}},_onRemoveComponent:function(a,b){b.onRemove()}});return{ScrollViewComponentSystem:b}}());Object.assign(pc,function(){return{ScrollViewComponentData:function(){this.enabled=!0}}}());Object.assign(pc,function(){var e=function(b,a){pc.Component.call(this,b,a);this._app=b.app;this._handleReference=new pc.EntityReference(this,"handleEntity",{"element#gain":this._onHandleElementGain,"element#lose":this._onHandleElementLose,"element#set:anchor":this._onSetHandleAlignment,"element#set:margin":this._onSetHandleAlignment,"element#set:pivot":this._onSetHandleAlignment});this._toggleLifecycleListeners("on")};e.prototype=Object.create(pc.Component.prototype);e.prototype.constructor=e;Object.assign(e.prototype,
|
|
{_toggleLifecycleListeners:function(b){this[b]("set_value",this._onSetValue,this);this[b]("set_handleSize",this._onSetHandleSize,this);this[b]("set_orientation",this._onSetOrientation,this)},_onHandleElementGain:function(){this._destroyDragHelper();this._handleDragHelper=new pc.ElementDragHelper(this._handleReference.entity.element,this._getAxis());this._handleDragHelper.on("drag:move",this._onHandleDrag,this);this._updateHandlePositionAndSize()},_onHandleElementLose:function(){this._destroyDragHelper()},
|
|
_onHandleDrag:function(b){this._handleReference.entity&&this.enabled&&this.entity.enabled&&(this.value=this._handlePositionToScrollValue(b[this._getAxis()]))},_onSetValue:function(b,a,c){1E-5<Math.abs(c-a)&&(this.data.value=pc.math.clamp(c,0,1),this._updateHandlePositionAndSize(),this.fire("set:value",this.data.value))},_onSetHandleSize:function(b,a,c){1E-5<Math.abs(c-a)&&(this.data.handleSize=pc.math.clamp(c,0,1),this._updateHandlePositionAndSize())},_onSetHandleAlignment:function(){this._updateHandlePositionAndSize()},
|
|
_onSetOrientation:function(b,a,c){c!==a&&this._handleReference.hasComponent("element")&&(this._handleReference.entity.element[this._getOppositeDimension()]=0)},_updateHandlePositionAndSize:function(){var b=this._handleReference.entity,a=b&&b.element;b&&(b=b.getLocalPosition(),b[this._getAxis()]=this._getHandlePosition(),this._handleReference.entity.setLocalPosition(b));a&&(a[this._getDimension()]=this._getHandleLength())},_handlePositionToScrollValue:function(b){return b*this._getSign()/this._getUsableTrackLength()},
|
|
_scrollValueToHandlePosition:function(b){return b*this._getSign()*this._getUsableTrackLength()},_getUsableTrackLength:function(){return Math.max(this._getTrackLength()-this._getHandleLength(),.001)},_getTrackLength:function(){return this.entity.element?this.orientation===pc.ORIENTATION_HORIZONTAL?this.entity.element.calculatedWidth:this.entity.element.calculatedHeight:0},_getHandleLength:function(){return this._getTrackLength()*this.handleSize},_getHandlePosition:function(){return this._scrollValueToHandlePosition(this.value)},
|
|
_getSign:function(){return this.orientation===pc.ORIENTATION_HORIZONTAL?1:-1},_getAxis:function(){return this.orientation===pc.ORIENTATION_HORIZONTAL?"x":"y"},_getDimension:function(){return this.orientation===pc.ORIENTATION_HORIZONTAL?"width":"height"},_getOppositeDimension:function(){return this.orientation===pc.ORIENTATION_HORIZONTAL?"height":"width"},_destroyDragHelper:function(){this._handleDragHelper&&this._handleDragHelper.destroy()},_setHandleDraggingEnabled:function(b){this._handleDragHelper&&
|
|
(this._handleDragHelper.enabled=b)},onEnable:function(){this._handleReference.onParentComponentEnable();this._setHandleDraggingEnabled(!0)},onDisable:function(){this._setHandleDraggingEnabled(!1)},onRemove:function(){this._destroyDragHelper();this._toggleLifecycleListeners("off")}});return{ScrollbarComponent:e}}());Object.assign(pc,function(){var e=[{name:"enabled",type:"boolean"},{name:"orientation",type:"number"},{name:"value",type:"number"},{name:"handleSize",type:"number"},{name:"handleEntity",type:"entity"}],b=function(a){pc.ComponentSystem.call(this,a);this.id="scrollbar";this.app=a;this.ComponentType=pc.ScrollbarComponent;this.DataType=pc.ScrollbarComponentData;this.schema=e;this.on("beforeremove",this._onRemoveComponent,this)};b.prototype=Object.create(pc.ComponentSystem.prototype);b.prototype.constructor=
|
|
b;pc.Component._buildAccessors(pc.ScrollbarComponent.prototype,e);Object.assign(b.prototype,{initializeComponentData:function(a,b,d){pc.ComponentSystem.prototype.initializeComponentData.call(this,a,b,e)},_onRemoveComponent:function(a,b){b.onRemove()}});return{ScrollbarComponentSystem:b}}());Object.assign(pc,function(){return{ScrollbarComponentData:function(){this.enabled=!0}}}());Object.assign(pc,{FITTING_NONE:0,FITTING_STRETCH:1,FITTING_SHRINK:2,FITTING_BOTH:3});Object.assign(pc,function(){function e(a){return a.element}function b(a){return a.enabled&&a.element&&a.element.enabled}function a(a){var b="_"+a;Object.defineProperty(c.prototype,a,{get:function(){return this[b]},set:function(a){this[b]!==a&&(this[b]=a,this._scheduleReflow())}})}var c=function(a,b){pc.Component.call(this,a,b);this._orientation=pc.ORIENTATION_HORIZONTAL;this._reverseX=!1;this._reverseY=!0;this._alignment=new pc.Vec2(0,1);this._padding=new pc.Vec4;this._spacing=new pc.Vec2;this._heightFitting=
|
|
this._widthFitting=pc.FITTING_NONE;this._wrap=!1;this._layoutCalculator=new pc.LayoutCalculator;this._listenForReflowEvents(this.entity,"on");this.entity.children.forEach(function(a){this._listenForReflowEvents(a,"on")}.bind(this));this.entity.on("childinsert",this._onChildInsert,this);this.entity.on("childremove",this._onChildRemove,this);a.app.systems.element.on("add",this._onElementOrLayoutComponentAdd,this);a.app.systems.element.on("beforeremove",this._onElementOrLayoutComponentRemove,this);a.app.systems.layoutchild.on("add",
|
|
this._onElementOrLayoutComponentAdd,this);a.app.systems.layoutchild.on("beforeremove",this._onElementOrLayoutComponentRemove,this)};c.prototype=Object.create(pc.Component.prototype);c.prototype.constructor=c;Object.assign(c.prototype,{_isSelfOrChild:function(a){return a===this.entity||-1!==this.entity.children.indexOf(a)},_listenForReflowEvents:function(a,b){a.element&&(a.element[b]("enableelement",this._scheduleReflow,this),a.element[b]("disableelement",this._scheduleReflow,this),a.element[b]("resize",
|
|
this._scheduleReflow,this),a.element[b]("set:pivot",this._scheduleReflow,this));a.layoutchild&&(a.layoutchild[b]("set_enabled",this._scheduleReflow,this),a.layoutchild[b]("resize",this._scheduleReflow,this))},_onElementOrLayoutComponentAdd:function(a){this._isSelfOrChild(a)&&(this._listenForReflowEvents(a,"on"),this._scheduleReflow())},_onElementOrLayoutComponentRemove:function(a){this._isSelfOrChild(a)&&(this._listenForReflowEvents(a,"off"),this._scheduleReflow())},_onChildInsert:function(a){this._listenForReflowEvents(a,
|
|
"on");this._scheduleReflow()},_onChildRemove:function(a){this._listenForReflowEvents(a,"off");this._scheduleReflow()},_scheduleReflow:function(){this.enabled&&this.entity&&this.entity.enabled&&!this._isPerformingReflow&&this.system.scheduleReflow(this)},reflow:function(){var a=this.entity.element,c=this.entity.children.filter(b).map(e);a&&0!==c.length&&(a={orientation:this._orientation,reverseX:this._reverseX,reverseY:this._reverseY,alignment:this._alignment,padding:this._padding,spacing:this._spacing,
|
|
widthFitting:this._widthFitting,heightFitting:this._heightFitting,wrap:this._wrap,containerSize:new pc.Vec2(Math.max(a.calculatedWidth,0),Math.max(a.calculatedHeight,0))},this._isPerformingReflow=!0,c=this._layoutCalculator.calculateLayout(c,a),this._isPerformingReflow=!1,this.fire("reflow",c))},onEnable:function(){this._scheduleReflow()},onRemove:function(){this.entity.off("childinsert",this._onChildInsert,this);this.entity.off("childremove",this._onChildRemove,this);this._listenForReflowEvents(this.entity,
|
|
"off");this.entity.children.forEach(function(a){this._listenForReflowEvents(a,"off")}.bind(this));this.system.app.systems.element.off("add",this._onElementOrLayoutComponentAdd,this);this.system.app.systems.element.off("beforeremove",this._onElementOrLayoutComponentRemove,this);this.system.app.systems.layoutchild.off("add",this._onElementOrLayoutComponentAdd,this);this.system.app.systems.layoutchild.off("beforeremove",this._onElementOrLayoutComponentRemove,this)}});a("orientation");a("reverseX");a("reverseY");
|
|
a("alignment");a("padding");a("spacing");a("widthFitting");a("heightFitting");a("wrap");return{LayoutGroupComponent:c}}());Object.assign(pc,function(){var e=["enabled"],b=function(a){pc.ComponentSystem.call(this,a);this.id="layoutgroup";this.app=a;this.ComponentType=pc.LayoutGroupComponent;this.DataType=pc.LayoutGroupComponentData;this.schema=e;this._reflowQueue=[];this.on("beforeremove",this._onRemoveComponent,this);pc.ComponentSystem.bind("postUpdate",this._onPostUpdate,this)};b.prototype=Object.create(pc.ComponentSystem.prototype);b.prototype.constructor=b;pc.Component._buildAccessors(pc.LayoutGroupComponent.prototype,
|
|
e);Object.assign(b.prototype,{initializeComponentData:function(a,b,d){void 0!==b.enabled&&(a.enabled=b.enabled);void 0!==b.orientation&&(a.orientation=b.orientation);void 0!==b.reverseX&&(a.reverseX=b.reverseX);void 0!==b.reverseY&&(a.reverseY=b.reverseY);void 0!==b.alignment&&(b.alignment instanceof pc.Vec2?a.alignment.copy(b.alignment):a.alignment.set(b.alignment[0],b.alignment[1]),a.alignment=a.alignment);void 0!==b.padding&&(b.padding instanceof pc.Vec4?a.padding.copy(b.padding):a.padding.set(b.padding[0],
|
|
b.padding[1],b.padding[2],b.padding[3]),a.padding=a.padding);void 0!==b.spacing&&(b.spacing instanceof pc.Vec2?a.spacing.copy(b.spacing):a.spacing.set(b.spacing[0],b.spacing[1]),a.spacing=a.spacing);void 0!==b.widthFitting&&(a.widthFitting=b.widthFitting);void 0!==b.heightFitting&&(a.heightFitting=b.heightFitting);void 0!==b.wrap&&(a.wrap=b.wrap);pc.ComponentSystem.prototype.initializeComponentData.call(this,a,b,d)},cloneComponent:function(a,b){var c=a.layoutgroup;return this.addComponent(b,{enabled:c.enabled,
|
|
orientation:c.orientation,reverseX:c.reverseX,reverseY:c.reverseY,alignment:c.alignment,padding:c.padding,spacing:c.spacing,widthFitting:c.widthFitting,heightFitting:c.heightFitting,wrap:c.wrap})},scheduleReflow:function(a){-1===this._reflowQueue.indexOf(a)&&this._reflowQueue.push(a)},_onPostUpdate:function(){this._processReflowQueue()},_processReflowQueue:function(){if(0!==this._reflowQueue.length)for(var a=0;0<this._reflowQueue.length;){var b=this._reflowQueue.slice();this._reflowQueue.length=0;
|
|
b.sort(function(a,b){return a.entity.graphDepth-b.entity.graphDepth});for(var d=0;d<b.length;++d)b[d].reflow();if(100<=++a){console.warn("Max reflow iterations limit reached, bailing.");break}}},_onRemoveComponent:function(a,b){b.onRemove()}});return{LayoutGroupComponentSystem:b}}());Object.assign(pc,function(){return{LayoutGroupComponentData:function(){this.enabled=!0}}}());Object.assign(pc,function(){function e(){}function b(b){function e(a){a=a.entity.layoutchild;return!a||!a.enabled||!a.excludeFromLayout}function h(a,b,c){switch(a){case pc.FITTING_NONE:return f.NONE;case pc.FITTING_STRETCH:return b<c?f.APPLY_STRETCHING:f.NONE;case pc.FITTING_SHRINK:return b>=c?f.APPLY_SHRINKING:f.NONE;case pc.FITTING_BOTH:return b<c?f.APPLY_STRETCHING:b>=c?f.APPLY_SHRINKING:f.NONE;default:throw Error("Unrecognized fitting mode: "+a);}}function l(a,b){return x(a,b.size)+(a.length-
|
|
1)*z.spacing[b.axis]}function q(a,b,c){var d=w(a,c.maxSize),f=v(a,c.fittingProportion),e=B(f,d);b=g[c.axis]-b;for(var h=0;h<a.length;++h){var k=d[h],l=r(k,b,f,e),m=a[k][c.size]+l,n=Math.min(m,a[k][c.maxSize]);a[k][c.size]=n;b-=l-Math.max(m-n,0)}}function m(a,b,c){var d=w(a,c.minSize,!0),f;f=v(a,c.fittingProportion);if(1===f.length)f=[1];else{for(var e=[],h=f.length,k=0;k<h;++k)e.push((1-f[k])/(h-1));f=e}e=B(f,d);b-=g[c.axis];for(h=0;h<a.length;++h){var k=d[h],l=r(k,b,f,e),m=a[k][c.size]-l,n=Math.max(m,
|
|
a[k][c.minSize]);a[k][c.size]=n;b-=l-Math.max(n-m,0)}}function r(a,b,c,d){c=c[a];a=d[a];return 1E-5>Math.abs(c)&&1E-5>Math.abs(a)?b:b*c/a}function t(a){for(var b=[],c=0;c<a.length;++c){var d=a[c],f=Math.max(u(d,"minWidth"),0),e=Math.max(u(d,"minHeight"),0),g=Math.max(u(d,"maxWidth"),f),h=Math.max(u(d,"maxHeight"),e),k;k=u(d,"width");k=Math.min(Math.max(k,f),g);var l;l=u(d,"height");l=Math.min(Math.max(l,e),h);var m=u(d,"fitWidthProportion"),d=u(d,"fitHeightProportion");b.push({minWidth:f,minHeight:e,
|
|
maxWidth:g,maxHeight:h,width:k,height:l,fitWidthProportion:m,fitHeightProportion:d})}return b}function u(a,b){var c=a.entity.layoutchild;return c&&c.enabled&&void 0!==c[b]&&null!==c[b]?c[b]:void 0!==a[b]?a[b]:d[b]}function x(a,b){return a.reduce(function(a,c){return a+c[b]},0)}function v(a,b){var c=x(a,b),d=[],f=a.length,e;if(0===c)for(e=0;e<f;++e)d.push(1/f);else for(e=0;e<f;++e)d.push(a[e][b]/c);return d}function w(a,b,c){a.forEach(y);return a.slice().sort(function(a,d){return c?d[b]-a[b]:a[b]-
|
|
d[b]}).map(D)}function y(a,b){a.index=b}function D(a){return a.index}function B(a,b){var c=[];c[b[a.length-1]]=a[b[a.length-1]];for(var d=a.length-2;0<=d;--d)c[b[d]]=c[b[d+1]]+a[b[d]];return c}var z,A=a[b],F=a[c[b]];return function(a,b){a=a.filter(e);z=b;g.x=z.containerSize.x-z.padding.x-z.padding.z;g.y=z.containerSize.y-z.padding.y-z.padding.w;for(var c=a,d=0;d<c.length;++d){var k=c[d],n=k.anchor;if(0!==n.x||0!==n.y||0!==n.z||0!==n.w)k.anchor=pc.Vec4.ZERO}c=a;if(z.wrap){for(var d=[[]],k=t(c),n=0,
|
|
p=z[A.fitting]===pc.FITTING_SHRINK,r=0;r<c.length;++r){0<d[d.length-1].length&&(n+=z.spacing[A.axis]);var u=k[r][A.size],n=n+u;!p&&n>g[A.axis]&&0!==d[d.length-1].length&&(n=u,d.push([]));d[d.length-1].push(c[r]);p&&n>g[A.axis]&&r!==c.length-1&&(n=0,d.push([]))}c=d}else c=[c];d=z.orientation===pc.ORIENTATION_HORIZONTAL&&z.reverseX||z.orientation===pc.ORIENTATION_VERTICAL&&z.reverseY;k=z.orientation===pc.ORIENTATION_HORIZONTAL&&z.reverseY||z.orientation===pc.ORIENTATION_VERTICAL&&z.reverseX;if(d)for(n=
|
|
0;n<c.length;++n)d&&c[n].reverse();k&&c.reverse();d=[];for(k=0;k<c.length;++k)n=t(c[k]),p=l(n,A),r=h(z[A.fitting],p,g[A.axis]),r===f.APPLY_STRETCHING?q(n,p,A):r===f.APPLY_SHRINKING&&m(n,p,A),d.push(n);u=[];r=[];for(n=0;n<c.length;++n){p=c[n];p.largestElement=null;p.largestSize={width:Number.NEGATIVE_INFINITY,height:Number.NEGATIVE_INFINITY};for(k=0;k<p.length;++k){var v=d[n][k];v[F.size]>p.largestSize[F.size]&&(p.largestElement=p[k],p.largestSize=v)}u.push(p.largestElement);r.push(p.largestSize)}k=
|
|
l(r,F);n=h(z[F.fitting],k,g[F.axis]);n===f.APPLY_STRETCHING?q(r,k,F):n===f.APPLY_SHRINKING&&m(r,k,F);for(n=0;n<c.length;++n)for(p=c[n],k=0;k<p.length;++k)r=d[n][k],u=1===c.length?g[F.axis]:p.largestSize[F.size],v=h(z[F.fitting],r[F.size],u),v===f.APPLY_STRETCHING?r[F.size]=Math.min(u,r[F.maxSize]):v===f.APPLY_SHRINKING&&(r[F.size]=Math.max(u,r[F.minSize]));a:{k={};k[A.axis]=0;k[F.axis]=0;c[A.size]=Number.NEGATIVE_INFINITY;n=[];for(p=0;p<c.length;++p){r=c[p];if(0===r.length){k=void 0;break a}for(var u=
|
|
[],v=d[p],w=0;w<r.length;++w){var x=r[w],y=v[w];k[F.axis]-=-y[F.size]*x.pivot[F.axis];k[A.axis]-=-y[A.size]*x.pivot[A.axis];u[w]={};u[w][A.axis]=k[A.axis];u[w][F.axis]=k[F.axis];k[F.axis]+=-y[F.size]*x.pivot[F.axis];k[A.axis]+=y[A.size]*(1-x.pivot[A.axis])+z.spacing[A.axis]}r[A.size]=k[A.axis]-z.spacing[A.axis];r[F.size]=r.largestSize[F.size];c[A.size]=Math.max(c[A.size],r[A.size]);k[A.axis]=0;k[F.axis]+=r[F.size]+z.spacing[F.axis];n.push(u)}c[F.size]=k[F.axis]-z.spacing[F.axis];k=n}n=k;p=z.alignment[A.axis];
|
|
r=z.alignment[F.axis];u=z.padding[A.axis];v=z.padding[F.axis];for(w=0;w<c.length;++w)for(var x=c[w],y=d[w],B=n[w],D=(g[A.axis]-x[A.size])*p+u,G=(g[F.axis]-c[F.size])*r+v,I=0;I<x.length;++I){var O=(x[F.size]-y[I][F.size])*z.alignment[F.axis];B[I][A.axis]+=D;B[I][F.axis]+=G+O}for(n=0;n<c.length;++n)for(p=c[n],r=d[n],u=k[n],v=0;v<p.length;++v)w=p[v],w[A.calculatedSize]=r[v][A.size],w[F.calculatedSize]=r[v][F.size],z.orientation===pc.ORIENTATION_HORIZONTAL?w.entity.setLocalPosition(u[v][A.axis],u[v][F.axis],
|
|
w.entity.getLocalPosition().z):w.entity.setLocalPosition(u[v][F.axis],u[v][A.axis],w.entity.getLocalPosition().z);d=c.width;c=c.height;return{bounds:new pc.Vec4((g.x-d)*z.alignment.x+z.padding.x,(g.y-c)*z.alignment.y+z.padding.y,d,c)}}}var a={};a[pc.ORIENTATION_HORIZONTAL]={axis:"x",size:"width",calculatedSize:"calculatedWidth",minSize:"minWidth",maxSize:"maxWidth",fitting:"widthFitting",fittingProportion:"fitWidthProportion"};a[pc.ORIENTATION_VERTICAL]={axis:"y",size:"height",calculatedSize:"calculatedHeight",
|
|
minSize:"minHeight",maxSize:"maxHeight",fitting:"heightFitting",fittingProportion:"fitHeightProportion"};var c={};c[pc.ORIENTATION_HORIZONTAL]=pc.ORIENTATION_VERTICAL;c[pc.ORIENTATION_VERTICAL]=pc.ORIENTATION_HORIZONTAL;var d={minWidth:0,minHeight:0,maxWidth:Number.POSITIVE_INFINITY,maxHeight:Number.POSITIVE_INFINITY,width:null,height:null,fitWidthProportion:0,fitHeightProportion:0},f={NONE:"NONE",APPLY_STRETCHING:"APPLY_STRETCHING",APPLY_SHRINKING:"APPLY_SHRINKING"},g=new pc.Vec2,l={};l[pc.ORIENTATION_HORIZONTAL]=
|
|
b(pc.ORIENTATION_HORIZONTAL);l[pc.ORIENTATION_VERTICAL]=b(pc.ORIENTATION_VERTICAL);Object.assign(e.prototype,{calculateLayout:function(a,b){var c=l[b.orientation];if(c)return c(a,b);throw Error("Unrecognized orientation value: "+b.orientation);}});return{LayoutCalculator:e}}());Object.assign(pc,function(){function e(a){var c="_"+a;Object.defineProperty(b.prototype,a,{get:function(){return this[c]},set:function(a){this[c]!==a&&(this[c]=a,this.fire("resize"))}})}var b=function(a,b){pc.Component.call(this,a,b);this._minHeight=this._minWidth=0;this._maxHeight=this._maxWidth=null;this._fitHeightProportion=this._fitWidthProportion=0;this._excludeFromLayout=!1};b.prototype=Object.create(pc.Component.prototype);b.prototype.constructor=b;e("minWidth");e("minHeight");e("maxWidth");
|
|
e("maxHeight");e("fitWidthProportion");e("fitHeightProportion");e("excludeFromLayout");return{LayoutChildComponent:b}}());Object.assign(pc,function(){var e=["enabled"],b=function(a){pc.ComponentSystem.call(this,a);this.id="layoutchild";this.app=a;this.ComponentType=pc.LayoutChildComponent;this.DataType=pc.LayoutChildComponentData;this.schema=e};b.prototype=Object.create(pc.ComponentSystem.prototype);b.prototype.constructor=b;pc.Component._buildAccessors(pc.LayoutChildComponent.prototype,e);Object.assign(b.prototype,{initializeComponentData:function(a,b,d){void 0!==b.enabled&&(a.enabled=b.enabled);void 0!==b.minWidth&&
|
|
(a.minWidth=b.minWidth);void 0!==b.minHeight&&(a.minHeight=b.minHeight);void 0!==b.maxWidth&&(a.maxWidth=b.maxWidth);void 0!==b.maxHeight&&(a.maxHeight=b.maxHeight);void 0!==b.fitWidthProportion&&(a.fitWidthProportion=b.fitWidthProportion);void 0!==b.fitHeightProportion&&(a.fitHeightProportion=b.fitHeightProportion);void 0!==b.excludeFromLayout&&(a.excludeFromLayout=b.excludeFromLayout);pc.ComponentSystem.prototype.initializeComponentData.call(this,a,b,d)},cloneComponent:function(a,b){var c=a.layoutchild;
|
|
return this.addComponent(b,{enabled:c.enabled,minWidth:c.minWidth,minHeight:c.minHeight,maxWidth:c.maxWidth,maxHeight:c.maxHeight,fitWidthProportion:c.fitWidthProportion,fitHeightProportion:c.fitHeightProportion,excludeFromLayout:c.excludeFromLayout})}});return{LayoutChildComponentSystem:b}}());Object.assign(pc,function(){return{LayoutChildComponentData:function(){this.enabled=!0}}}());Object.assign(pc,function(){pc.FONT_MSDF="msdf";pc.FONT_BITMAP="bitmap";var e=function(b,a){this.type=a?a.type||pc.FONT_MSDF:pc.FONT_MSDF;this.em=1;this.textures=b;this.intensity=0;this._data=null;this.data=a};Object.defineProperty(e.prototype,"data",{get:function(){return this._data},set:function(b){if(this._data=b)if(void 0!==this._data.intensity&&(this.intensity=this._data.intensity),this._data.info||(this._data.info={}),!this._data.version||2>this._data.version)if(this._data.info.maps=[{width:this._data.info.width,
|
|
height:this._data.info.height}],this._data.chars)for(var a in this._data.chars)this._data.chars[a].map=0}});return{FONT_MSDF:pc.FONT_MSDF,Font:e}}());Object.assign(pc,function(){var e=function(b,a){this.type="bitmap";this.app=b;this.intensity=0;a=a||{};this.fontWeight=a.fontWeight||"normal";this.glyphSize=this.fontSize=parseInt(a.fontSize,10);this.fontName=a.fontName||"Arial";this.color=a.color||new pc.Color(1,1,1);var c=4096<a.width?4096:a.width||512,d=4096<a.height?4096:a.height||512,f=document.createElement("canvas");f.height=d;f.width=c;c=new pc.Texture(this.app.graphicsDevice,{format:pc.PIXELFORMAT_R8_G8_B8_A8,autoMipmap:!0});c.name="font";
|
|
c.setSource(f);c.minFilter=pc.FILTER_LINEAR_MIPMAP_LINEAR;c.magFilter=pc.FILTER_LINEAR;c.addressU=pc.ADDRESS_CLAMP_TO_EDGE;c.addressV=pc.ADDRESS_CLAMP_TO_EDGE;this.textures=[c];this.chars="";this.data={};pc.events.attach(this)};e.prototype.createTextures=function(b){b=this._normalizeCharsSet(b);if(b.length!==this.chars.length)this._renderAtlas(b);else for(var a=0;a<b.length;a++)if(b[a]!==this.chars[a]){this._renderAtlas(b);break}};e.prototype.updateTextures=function(b){b=this._normalizeCharsSet(b);
|
|
for(var a=[],c=0;c<b.length;c++){var d=b[c];this.data.chars[d]||a.push(d)}0<a.length&&this._renderAtlas(this.chars.concat(a))};e.prototype.destroy=function(){for(var b=0;b<this.textures.length;b++)this.textures[b].destroy();this.fontWeight=this.type=this.textures=this.intensity=this.glyphSize=this.fontSize=this.fontName=this.data=this.color=this.chars=null};e.prototype._getAndClearContext=function(b,a){var c=b.width,d=b.height,f=b.getContext("2d",{alpha:!0});f.clearRect(0,0,c,d);f.fillStyle=a;f.fillRect(0,
|
|
0,c,d);return f};e.prototype._colorToRgbString=function(b,a){var c=Math.round(255*b.r),d=Math.round(255*b.g),f=Math.round(255*b.b);return a?"rgba("+c+", "+d+", "+f+", "+b.a+")":"rgb("+c+", "+d+", "+f+")"};e.prototype.renderCharacter=function(b,a,c,d,f){b.fillStyle=f;b.fillText(a,c,d)};e.prototype._renderAtlas=function(b){this.chars=b;b=1;var a=this.textures[b-1].getSource(),c=a.width,d=a.height,f=this._colorToRgbString(this.color,!1),e=this.color.a;this.color.a=1/255;var l=this._colorToRgbString(this.color,
|
|
!0);this.color.a=e;e=this._getAndClearContext(a,l);e.font=this.fontWeight+" "+this.fontSize.toString()+"px "+this.fontName;e.textAlign="center";e.textBaseline="bottom";this.data=this._createJson(this.chars,this.fontName,c,d);var h=pc.string.getSymbols(this.chars.join("")),p=this.textures.length,k=0,n=0,q={},m;for(m=0;m<h.length;m++)a=h[m],q[a]=this._getTextMetrics(a),k=Math.max(k,q[a].height),n=Math.max(n,q[a].descent);var r=k=this.glyphSize=Math.max(this.glyphSize,k),t=k/2,u=t,x=r;for(m=0;m<h.length;m++){var a=
|
|
h[m],v=pc.string.getCodePoint(h[m]),w=this.fontSize;e.font=this.fontWeight+" "+w.toString()+"px "+this.fontName;e.textAlign="center";e.textBaseline="bottom";var y=e.measureText(a).width;y>w&&(w=this.fontSize*this.fontSize/y,e.font=this.fontWeight+" "+w.toString()+"px "+this.fontName,y=this.fontSize);this.renderCharacter(e,a,u,x,f);this._addChar(this.data,a,v,u-t,x-r,k,r,(k-y)/2,q[a].descent-n,y,b-1,c,d);u+=k;u+t>c&&(u=t,x+=r,x>d&&(this.textures[b-1].upload(),b++,x=r,b>p?(a=document.createElement("canvas"),
|
|
a.height=d,a.width=c,e=this._getAndClearContext(a,l),v=new pc.Texture(this.app.graphicsDevice,{format:pc.PIXELFORMAT_R8_G8_B8_A8,autoMipmap:!0}),v.name="font-atlas",v.setSource(a),v.minFilter=pc.FILTER_LINEAR_MIPMAP_LINEAR,v.magFilter=pc.FILTER_LINEAR,v.addressU=pc.ADDRESS_CLAMP_TO_EDGE,v.addressV=pc.ADDRESS_CLAMP_TO_EDGE,this.textures.push(v)):(a=this.textures[b-1].getSource(),e=this._getAndClearContext(a,l))))}this.textures[b-1].upload();if(b<p){for(m=b;m<p;m++)this.textures[m].destroy();this.textures.splice(b)}this.fire("render")};
|
|
e.prototype._createJson=function(b,a,c,d){return{version:3,intensity:this.intensity,info:{face:a,width:c,height:d,maps:[{width:c,height:d}]},chars:{}}};e.prototype._addChar=function(b,a,c,d,f,e,l,h,p,k,n,q,m){b.info.maps.length<n+1&&b.info.maps.push({width:q,height:m});q=this.fontSize/32;b.chars[a]={id:c,letter:a,x:d,y:f,width:e,height:l,xadvance:k/q,xoffset:h/q,yoffset:p/q,scale:q,range:1,map:n,bounds:[0,0,e/q,l/q]}};e.prototype._normalizeCharsSet=function(b){var a=this.app.systems.element.getUnicodeConverter();
|
|
a&&(b=a(b));a={};b=pc.string.getSymbols(b);var c;for(c=0;c<b.length;c++){var d=b[c];a[d]||(a[d]=d)}return Object.keys(a).sort()};e.prototype._getTextMetrics=function(b){var a=document.createElement("span");a.id="content-span";a.innerHTML=b;b=document.createElement("div");b.id="content-block";b.style.display="inline-block";b.style.width="1px";b.style.height="0px";var c=document.createElement("div");c.appendChild(a);c.appendChild(b);c.style.font=this.fontName;c.style.fontSize=this.fontSize+"px";document.body.appendChild(c);
|
|
var d=-1,f=-1,e=-1;try{b.style["vertical-align"]="baseline",d=b.offsetTop-a.offsetTop,b.style["vertical-align"]="bottom",e=b.offsetTop-a.offsetTop,f=e-d}finally{document.body.removeChild(c)}return{ascent:d,descent:f,height:e}};return{CanvasFont:e}}());Object.assign(pc,function(){var e=function(b,a){pc.Component.call(this,b,a);this._oldState=!0;this._size=new pc.Vec3;this.on("set_enabled",this._onSetEnabled,this)};e.prototype=Object.create(pc.Component.prototype);e.prototype.constructor=e;Object.assign(e.prototype,{onEnable:function(){this._checkState()},onDisable:function(){this._checkState()},_onSetEnabled:function(b,a,c){this._checkState()},_checkState:function(){var b=this.enabled&&this.entity.enabled;b!==this._oldState&&(this._oldState=b,this.fire("enable"),
|
|
this.fire("state",this.enabled))},_onBeforeRemove:function(){this.fire("remove")}});Object.defineProperty(e.prototype,"size",{set:function(b){b instanceof pc.Vec3?this._size.copy(b):b instanceof Array&&3<=b.length&&this.size.set(b[0],b[1],b[2])},get:function(){return this._size}});return{ZoneComponent:e}}());Object.assign(pc,function(){var e=["enabled"],b=function(a){pc.ComponentSystem.call(this,a);this.id="zone";this.app=a;this.ComponentType=pc.ZoneComponent;this.DataType=pc.ZoneComponentData;this.schema=e;this.on("beforeremove",this._onBeforeRemove,this)};b.prototype=Object.create(pc.ComponentSystem.prototype);b.prototype.constructor=b;pc.Component._buildAccessors(pc.ZoneComponent.prototype,e);Object.assign(b.prototype,{initializeComponentData:function(a,b,d){a.enabled=b.hasOwnProperty("enabled")?!!b.enabled:
|
|
!0;b.size&&(b.size instanceof pc.Vec3?a.size.copy(b.size):b.size instanceof Array&&3<=b.size.length&&a.size.set(b.size[0],b.size[1],b.size[2]))},cloneComponent:function(a,b){return this.addComponent(b,{size:a.zone.size})},_onBeforeRemove:function(a,b){b._onBeforeRemove()}});return{ZoneComponentSystem:b}}());Object.assign(pc,function(){return{ZoneComponentData:function(){this.enabled=!0}}}());Object.assign(pc,function(){function e(a,b,d,f){var c,l;if(b instanceof pc.Entity){var h=b.c,p;for(p in h){var k=h[p],n=k.system.getPropertiesOfType("entity");c=0;for(l=n.length;c<l;c++){var q=n[c].name,m=k[q];a.findByGuid(m)&&((m=f[m].getGuid())?d.c[p][q]=m:console.warn("Could not find corresponding entity id when resolving duplicated entity references"))}}h.script&&!d._app.useLegacyScriptAttributeCloning&&d.script.resolveDuplicatedEntityReferenceProperties(h.script,f);b=b.children.filter(function(a){return a instanceof
|
|
pc.Entity});d=d.children.filter(function(a){return a instanceof pc.Entity});c=0;for(l=b.length;c<l;c++)e(a,b[c],d[c],f)}}var b=function(a,b){pc.GraphNode.call(this,a);a instanceof pc.Application&&(b=a);this._batchHandle=null;this.c={};this._app=b;if(!b&&(this._app=pc.Application.getApplication(),!this._app))throw Error("Couldn't find current application");this._guid=null;this._destroying=!1;pc.events.attach(this)};b.prototype=Object.create(pc.GraphNode.prototype);b.prototype.constructor=b;b.prototype.addComponent=
|
|
function(a,b){var c=this._app.systems[a];return!c||this.c[a]?null:c.addComponent(this,b)};b.prototype.removeComponent=function(a){var b=this._app.systems[a];b&&this.c[a]&&b.removeComponent(this)};b.prototype.getGuid=function(){this._guid||this.setGuid(pc.guid.create());return this._guid};b.prototype.setGuid=function(a){var b=this._app._entityIndex;this._guid&&delete b[this._guid];this._guid=a;b[this._guid]=this};b.prototype._notifyHierarchyStateChanged=function(a,b){var c=!1;a===this&&0===this._app._enableList.length&&
|
|
(c=!0);a._beingEnabled=!0;a._onHierarchyStateChanged(b);a._onHierarchyStatePostChanged&&this._app._enableList.push(a);var f,e,l=a._children;f=0;for(e=l.length;f<e;f++)l[f]._enabled&&this._notifyHierarchyStateChanged(l[f],b);a._beingEnabled=!1;if(c){f=0;for(e=this._app._enableList.length;f<e;f++)this._app._enableList[f]._onHierarchyStatePostChanged();this._app._enableList.length=0}};b.prototype._onHierarchyStateChanged=function(a){pc.GraphNode.prototype._onHierarchyStateChanged.call(this,a);var b,
|
|
d=this.c,f;for(f in d)if(d.hasOwnProperty(f)&&(b=d[f],b.enabled))if(a)b.onEnable();else b.onDisable()};b.prototype._onHierarchyStatePostChanged=function(){var a=this.c,b;for(b in a)if(a.hasOwnProperty(b))a[b].onPostStateChange()};b.prototype.setRequest=function(a){this._request=a};b.prototype.getRequest=function(){return this._request};b.prototype.findByGuid=function(a){return this._guid===a?this:(a=this._app._entityIndex[a])&&(a===this||a.isDescendantOf(this))?a:null};b.prototype.destroy=function(){var a;
|
|
this._destroying=!0;for(a in this.c)this.c[a].enabled=!1;for(a in this.c)this.c[a].system.removeComponent(this);this._parent&&this._parent.removeChild(this);a=this._children;for(var b=a.shift();b;)b instanceof pc.Entity&&b.destroy(),b._parent=null,b=a.shift();this.fire("destroy",this);this.off();this._guid&&delete this._app._entityIndex[this._guid];this._destroying=!1};b.prototype.clone=function(){var a={},b=this._cloneRecursively(a);a[this.getGuid()]=b;e(this,this,b,a);return b};b.prototype._cloneRecursively=
|
|
function(a){var b=new pc.Entity(this._app);pc.GraphNode.prototype._cloneInternal.call(this,b);for(var d in this.c)this.c[d].system.cloneComponent(this,b);for(d=0;d<this._children.length;d++){var f=this._children[d];if(f instanceof pc.Entity){var e=f._cloneRecursively(a);b.addChild(e);a[f.getGuid()]=e}}return b};return{Entity:b}}());Object.assign(pc,function(){function e(b,a,c){if(b&&b instanceof pc.Component){if(!a||"string"!==typeof a)throw Error("The propertyName argument is required and must be a string");if(c&&"object"!==typeof c)throw Error("If provided, the eventConfig argument must be an object");}else throw Error("The parentComponent argument is required and must be a Component");this._parentComponent=b;this._entityPropertyName=a;this._entity=null;this._app=b.system.app;this._configureEventListeners(c||{},{"entity#destroy":this._onEntityDestroy});
|
|
this._toggleLifecycleListeners("on")}Object.assign(e.prototype,{_configureEventListeners:function(b,a){var c=this._parseEventListenerConfig(b,"external",this._parentComponent),d=this._parseEventListenerConfig(a,"internal",this);this._eventListenerConfigs=c.concat(d);this._listenerStatusFlags={};this._gainListeners={};this._loseListeners={}},_parseEventListenerConfig:function(b,a,c){return Object.keys(b).map(function(d,f){var e=d.split("#"),l=e[0],h=e[1],p=b[d];if(2!==e.length||"string"!==typeof l||
|
|
0===l.length||"string"!==typeof h||0===h.length)throw Error("Invalid event listener description: `"+d+"`");if("function"!==typeof p)throw Error("Invalid or missing callback for event listener `"+d+"`");return{id:a+"_"+f+"_"+d,sourceName:l,eventName:h,callback:p,scope:c}},this)},_toggleLifecycleListeners:function(b){this._parentComponent[b]("set_"+this._entityPropertyName,this._onSetEntity,this);this._parentComponent.system[b]("beforeremove",this._onParentComponentRemove,this);pc.ComponentSystem[b]("postinitialize",
|
|
this._onPostInitialize,this);this._app[b]("tools:sceneloaded",this._onSceneLoaded,this);for(var a=[],c=0;c<this._eventListenerConfigs.length;++c){var d=this._eventListenerConfigs[c],f=this._app.systems[d.sourceName];f&&(-1===a.indexOf(f)&&a.push(f),f&&"gain"===d.eventName&&(this._gainListeners[d.sourceName]=d),f&&"lose"===d.eventName&&(this._loseListeners[d.sourceName]=d))}for(c=0;c<a.length;++c)a[c][b]("add",this._onComponentAdd,this),a[c][b]("beforeremove",this._onComponentRemove,this)},_onSetEntity:function(b,
|
|
a,c){c instanceof pc.Entity?this._updateEntityReference():null!==c&&void 0!==c&&"string"!==typeof c?console.warn("Entity field `"+this._entityPropertyName+"` was set to unexpected type '"+typeof c+"'"):a!==c&&this._updateEntityReference()},_onPostInitialize:function(){this._updateEntityReference()},onParentComponentEnable:function(){this._entity||this._updateEntityReference()},_onSceneLoaded:function(){this._updateEntityReference()},_updateEntityReference:function(){var b=this._parentComponent.data[this._entityPropertyName],
|
|
a;b instanceof pc.Entity?(a=b,b=a.getGuid(),this._parentComponent.data[this._entityPropertyName]=b):(a=this._parentComponent.system.app.root,a=this._parentComponent.entity.isDescendantOf(a)&&b?a.findByGuid(b):null);this._entity!==a&&(this._entity&&this._onBeforeEntityChange(),(this._entity=a)&&this._onAfterEntityChange())},_onBeforeEntityChange:function(){this._toggleEntityListeners("off");this._callAllGainOrLoseListeners(this._loseListeners)},_onAfterEntityChange:function(){this._toggleEntityListeners("on");
|
|
this._callAllGainOrLoseListeners(this._gainListeners)},_onComponentAdd:function(b,a){var c=a.system.id;b===this._entity&&(this._callGainOrLoseListener(c,this._gainListeners),this._toggleComponentListeners("on",c))},_onComponentRemove:function(b,a){var c=a.system.id;b===this._entity&&(this._callGainOrLoseListener(c,this._loseListeners),this._toggleComponentListeners("off",c,!0))},_callAllGainOrLoseListeners:function(b){for(var a in this._entity.c)this._callGainOrLoseListener(a,b)},_callGainOrLoseListener:function(b,
|
|
a){if(this._entity.c.hasOwnProperty(b)&&a[b]){var c=a[b];c.callback.call(c.scope)}},_toggleEntityListeners:function(b,a){if(this._entity)for(var c=0;c<this._eventListenerConfigs.length;++c)this._safeToggleListener(b,this._eventListenerConfigs[c],a)},_toggleComponentListeners:function(b,a,c){for(var d=0;d<this._eventListenerConfigs.length;++d){var f=this._eventListenerConfigs[d];f.sourceName===a&&this._safeToggleListener(b,f,c)}},_safeToggleListener:function(b,a,c){var d="on"===b;if(!d||!this._listenerStatusFlags[a.id])if(c=
|
|
this._getEventSource(a.sourceName,c))c[b](a.eventName,a.callback,a.scope),this._listenerStatusFlags[a.id]=d},_getEventSource:function(b,a){if("entity"===b)return this._entity;var c=this._entity[b];if(c)return c;a||console.warn("Entity has no component with name "+b);return null},_onEntityDestroy:function(b){this._entity===b&&(this._toggleEntityListeners("off",!0),this._entity=null)},_onParentComponentRemove:function(b,a){a===this._parentComponent&&(this._toggleLifecycleListeners("off"),this._toggleEntityListeners("off",
|
|
!0))},hasComponent:function(b){return this._entity&&this._entity.c?!!this._entity.c[b]:!1}});Object.defineProperty(e.prototype,"entity",{get:function(){return this._entity}});return{EntityReference:e}}());Object.assign(pc,function(){var e=function(b){this._sortBy=b.sortBy;this.items=[];this.length=0;this.loopIndex=-1;this._sortHandler=this._doSort.bind(this)};e.prototype._binarySearch=function(b){var a=0,c=this.items.length-1;b=b[this._sortBy];for(var d,f;a<=c;)d=Math.floor((a+c)/2),f=this.items[d][this._sortBy],f<=b?a=d+1:f>b&&(c=d-1);return a};e.prototype._doSort=function(b,a){var c=this._sortBy;return b[c]-a[c]};e.prototype.insert=function(b){var a=this._binarySearch(b);this.items.splice(a,0,b);
|
|
this.length++;this.loopIndex>=a&&this.loopIndex++};e.prototype.append=function(b){this.items.push(b);this.length++};e.prototype.remove=function(b){b=this.items.indexOf(b);0>b||(this.items.splice(b,1),this.length--,this.loopIndex>=b&&this.loopIndex--)};e.prototype.sort=function(){var b=0<=this.loopIndex?this.items[this.loopIndex]:null;this.items.sort(this._sortHandler);null!==b&&(this.loopIndex=this.items.indexOf(b))};return{SortedLoopArray:e}}());Object.assign(pc,function(){var e=function(b){this._handlers={};this._requests={};this._cache={};this._app=b};Object.assign(e.prototype,{addHandler:function(b,a){this._handlers[b]=a;a._loader=this},removeHandler:function(b){delete this._handlers[b]},getHandler:function(b){return this._handlers[b]},load:function(b,a,c,d){var f=this._handlers[a];if(f){var e=b+a;if(void 0!==this._cache[e])c(null,this._cache[e]);else if(this._requests[e])this._requests[e].push(c);else{this._requests[e]=[c];var l=function(a,
|
|
b){if(a){console.error(a);if(this._requests[e])for(var c=0,g=this._requests[e].length;c<g;c++)this._requests[e][c](a);delete this._requests[e]}else f.load(b,function(a,c,g){if(this._requests[e]){var h=this._requests[e].length,k;if(!a)try{k=f.open(b.original,c,d)}catch(x){a=x}if(a)for(console.error(a),c=0;c<h;c++)this._requests[e][c](a);else for(this._cache[e]=k,c=0;c<h;c++)this._requests[e][c](null,k,g);delete this._requests[e]}}.bind(this),d)}.bind(this);a=b.split("?")[0];this._app.enableBundles&&
|
|
this._app.bundles.hasUrl(a)?this._app.bundles.canLoadUrl(a)?this._app.bundles.loadUrl(a,function(a,c){l(a,{load:c,original:b})}):l("Bundle for "+b+" not loaded yet"):l(null,{load:b,original:b})}}else c("No handler for asset type: "+a)},open:function(b,a){var c=this._handlers[b];return c?c.open(null,a):(console.warn("No resource handler found for: "+b),a)},patch:function(b,a){var c=this._handlers[b.type];c?c.patch&&c.patch(b,a):console.warn("No resource handler found for: "+b.type)},clearCache:function(b,
|
|
a){delete this._cache[b+a]},getFromCache:function(b,a){if(this._cache[b+a])return this._cache[b+a]},destroy:function(){this._handlers={};this._requests={};this._cache={}}});return{ResourceLoader:e}}());Object.assign(pc,function(){var e=function(b){this._assets=b;this._worker=null};Object.assign(e.prototype,{load:function(b,a){"string"===typeof b&&(b={load:b,original:b});var c=this;pc.http.get(b.load,{responseType:pc.Http.ResponseType.ARRAY_BUFFER},function(d,f){if(d)a("Error loading bundle resource "+b.original+": "+d);else try{c._untar(f,a)}catch(g){a("Error loading bundle resource "+b.original+": "+g)}})},_untar:function(b,a){var c=this;if(pc.platform.workers)c._worker||(c._worker=new pc.UntarWorker(c._assets.prefix)),
|
|
c._worker.untar(b,function(b,d){a(b,d);c._worker.hasPendingRequests()||(c._worker.destroy(),c._worker=null)});else{var d=(new pc.Untar(b)).untar(c._assets.prefix);a(null,d)}},open:function(b,a){return new pc.Bundle(a)},patch:function(b,a){}});return{BundleHandler:e}}());Object.assign(pc,function(){function e(a){function c(a){this._fields=a}var d,e;"undefined"!==typeof TextDecoder?(d=new TextDecoder("utf-8"),e=new TextDecoder("windows-1252")):console.warn("TextDecoder not supported - pc.Untar module will not work");c.parse=function(a,b,f){for(var e=new Uint8Array(a,b,f),g=0,h=[];g<f;){var k;for(k=g;k<f&&32!=e[k];k++);if(k>=f)throw Error("Invalid PAX header data format.");var l=parseInt(d.decode(new Uint8Array(a,b+g,k-g)),10);k=d.decode(new Uint8Array(a,b+k+1,l-(k-
|
|
g)-2)).split("=");if(2!==k.length)throw Error("Invalid PAX header data format.");0===k[1].length&&(k[1]=null);h.push({name:k[0],value:k[1]});g+=l}return new c(h)};c.prototype.applyHeader=function(a){for(var b=0;b<this._fields.length;b++){var c=this._fields[b].name,d=this._fields[b].value;"path"===c&&(c="name");null===d?delete a[c]:a[c]=d}};var h=function(a){this._arrayBuffer=a||new ArrayBuffer(0);this._bufferView=new DataView(this._arrayBuffer);this._globalPaxHeader=null;this._bytesRead=0};a||(b=
|
|
h);h.prototype._hasNext=function(){return this._bytesRead+4<this._arrayBuffer.byteLength&&0!==this._bufferView.getUint32(this._bytesRead)};h.prototype._readNextFile=function(){var b=new DataView(this._arrayBuffer,this._bytesRead,512),d=e.decode(b);this._bytesRead+=512;var b=d.substr(0,100).replace(/\0/g,""),f=d.substr(257,6),g=parseInt(d.substr(124,12),8),h=d.substr(156,1),l=this._bytesRead,t=null,u,x=!1;switch(h){case "0":case "":x=!0;a||(t=new Blob([this._arrayBuffer.slice(this._bytesRead,this._bytesRead+
|
|
g)]),t=URL.createObjectURL(t));break;case "g":this._globalPaxHeader=c.parse(this._arrayBuffer,this._bytesRead,g);break;case "x":u=c.parse(this._arrayBuffer,this._bytesRead,g)}this._bytesRead+=g;h=g%512;0!==h&&(this._bytesRead+=512-h);if(!x)return null;-1!==f.indexOf("ustar")&&(d=d.substr(345,155).replace(/\0/g,""),0<d.length&&(b=d.trim()+b.trim()));b={name:b,start:l,size:g,url:t};this._globalPaxHeader&&this._globalPaxHeader.applyHeader(b);u&&u.applyHeader(b);return b};h.prototype.untar=function(a){if(!d)return console.error("Cannot untar because TextDecoder interface is not available for this platform."),
|
|
[];for(var b=[];this._hasNext();){var c=this._readNextFile();c&&(a&&c.name&&(c.name=a+c.name),b.push(c))}return b};a&&(self.onmessage=function(a){var b=a.data.id;try{var c=(new h(a.data.arrayBuffer)).untar(a.data.prefix);postMessage({id:b,files:c,arrayBuffer:a.data.arrayBuffer},[a.data.arrayBuffer])}catch(q){postMessage({id:b,error:q.toString()})}})}var b,a=function(){var a=new Blob(["("+e.toString()+")(true)\n\n"],{type:"application/javascript"});return URL.createObjectURL(a)}(),c=function(b){this._requestId=
|
|
0;this._pendingRequests={};this._filenamePrefix=b;this._worker=new Worker(a);this._worker.addEventListener("message",this._onMessage.bind(this))};c.prototype._onMessage=function(a){var b=a.data.id;if(this._pendingRequests[b]){var c=this._pendingRequests[b];delete this._pendingRequests[b];if(a.data.error)c(a.data.error);else{for(var b=a.data.arrayBuffer,d=0,e=a.data.files.length;d<e;d++){var p=a.data.files[d],k=new Blob([b.slice(p.start,p.start+p.size)]);p.url=URL.createObjectURL(k)}c(null,a.data.files)}}};
|
|
c.prototype.untar=function(a,b){var c=this._requestId++;this._pendingRequests[c]=b;this._worker.postMessage({id:c,prefix:this._filenamePrefix,arrayBuffer:a},[a])};c.prototype.hasPendingRequests=function(){for(var a in this._pendingRequests)return!0;return!1};c.prototype.destroy=function(){this._worker&&(this._worker.terminate(),this._pendingRequests=this._worker=null)};e();return{Untar:b,UntarWorker:c}}());Object.assign(pc,function(){var e=function(){};Object.assign(e.prototype,{load:function(b,a){"string"===typeof b&&(b={load:b,original:b});var c={};b.load.startsWith("blob:")&&(c.responseType=pc.Http.ResponseType.JSON);pc.http.get(b.load,c,function(c,f){c?a(pc.string.format("Error loading animation resource: {0} [{1}]",b.original,c)):a(null,f)})},open:function(b,a){return this["_parseAnimationV"+a.animation.version](a)},_parseAnimationV3:function(b){b=b.animation;var a=new pc.Animation;a.setName(b.name);
|
|
a.duration=b.duration;for(var c=0;c<b.nodes.length;c++){var d=new pc.Node,f=b.nodes[c];d._name=f.name;for(var e=0;e<f.keys.length;e++){var l=f.keys[e],h=l.time,p=l.pos,k=l.rot,l=l.scale,p=new pc.Vec3(p[0],p[1],p[2]),k=(new pc.Quat).setFromEulerAngles(k[0],k[1],k[2]),l=new pc.Vec3(l[0],l[1],l[2]),h=new pc.Key(h,p,k,l);d._keys.push(h)}a.addNode(d)}return a},_parseAnimationV4:function(b){b=b.animation;var a=new pc.Animation;a.setName(b.name);a.duration=b.duration;for(var c=0;c<b.nodes.length;c++){var d=
|
|
new pc.Node,f=b.nodes[c];d._name=f.name;for(var e=f.defaults.p,l=f.defaults.r,h=f.defaults.s,p=0;p<f.keys.length;p++){var k=f.keys[p],n=k.t,q=e?e:k.p,m=l?l:k.r,k=h?h:k.s,q=new pc.Vec3(q[0],q[1],q[2]),m=(new pc.Quat).setFromEulerAngles(m[0],m[1],m[2]),k=new pc.Vec3(k[0],k[1],k[2]),n=new pc.Key(n,q,m,k);d._keys.push(n)}a.addNode(d)}return a}});return{AnimationHandler:e}}());Object.assign(pc,function(){var e=function(){var a=window.navigator.userAgent,b=a.indexOf("MSIE ");return 0<b?parseInt(a.substring(b+5,a.indexOf(".",b)),10):0<a.indexOf("Trident/")?(b=a.indexOf("rv:"),parseInt(a.substring(b+3,a.indexOf(".",b)),10)):!1}(),b=function(a){this.manager=a};Object.assign(b.prototype,{_isSupported:function(a){return{".ogg":"audio/ogg",".mp3":"audio/mpeg",".wav":"audio/x-wav",".mp4a":"audio/mp4",".m4a":"audio/mp4",".mp4":"audio/mp4",".aac":"audio/aac"}[pc.path.getExtension(a)]?
|
|
!0:!1},load:function(a,b){"string"===typeof a&&(a={load:a,original:a});var c=function(a){b(null,new pc.Sound(a))},f=function(c){c=c||"Error loading audio url: "+a.original;console.warn(c);b(c)};this._createSound?this._isSupported(a.original)?this._createSound(a.load,c,f):f(pc.string.format("Audio format for {0} not supported",a.original)):f(null)},open:function(a,b){return b}});pc.SoundManager.hasAudioContext()?b.prototype._createSound=function(a,b,d){var c=this.manager;if(c.context){var e={};a.startsWith("blob:")&&
|
|
(e.responseType=pc.Http.ResponseType.ARRAY_BUFFER);pc.http.get(a,e,function(a,f){a?d(a):c.context.decodeAudioData(f,b,d)})}else d("Audio manager has no audio context")}:pc.SoundManager.hasAudio()&&(b.prototype._createSound=function(a,b,d){var c=null;try{c=new Audio}catch(l){d("No support for Audio element");return}e&&document.body.appendChild(c);var g=function(){c.removeEventListener("canplaythrough",g);e&&document.body.removeChild(c);b(c)};c.onerror=function(){c.onerror=null;e&&document.body.removeChild(c);
|
|
d()};c.addEventListener("canplaythrough",g);c.src=a});return{AudioHandler:b}}());Object.assign(pc,function(){var e=function(b,a,c){this._device=b;this._assets=a;this._loader=c};Object.assign(e.prototype,{load:function(b,a){},open:function(b,a){},patch:function(b,a){var c=this,d=!1;b.resources[0]||(b.resources[0]=new pc.Texture(this._device,{format:pc.PIXELFORMAT_R8_G8_B8_A8,cubemap:!0,mipmaps:!0,fixCubemapSeams:!!b._dds}),b.resources[0].name="cubemap",d=!0);if(!b.file)delete b._dds;else if(b.file&&!b._dds){var f=b.getFileUrl();a._loader.load(f+"?t="+b.file.hash,"texture",function(d,
|
|
f){d?(a.fire("error",d,b),a.fire("error:"+b.id,d,b),b.fire("error",d,b)):(a._loader.patch({resource:f,type:"texture",data:b.data},a),b._dds=f,c.patch(b,a))})}if((!b.file||!b._dds)&&b.resources[1])b.resources=[b.resources[0]],d=!0;else if(b._dds&&!b.resources[1]){b.resources=[b.resources[0]];b._dds.fixCubemapSeams=!0;b._dds.addressU=pc.ADDRESS_CLAMP_TO_EDGE;b._dds.addressV=pc.ADDRESS_CLAMP_TO_EDGE;d=0;this._device.useTexCubeLod&&(b.resources.push(b._dds),d=1);for(;6>d;d++)f=new pc.Texture(this._device,
|
|
{cubemap:!0,fixCubemapSeams:!0,mipmaps:!0,format:b._dds.format,rgbm:b._dds.rgbm,width:Math.pow(2,7-d),height:Math.pow(2,7-d)}),f.name="cubemap-mip",f._levels[0]=b._dds._levels[d],f.upload(),b.resources.push(f);d=!0}f=b.resource;f.name!==b.name&&(f.name=b.name);var e=!!b.data.rgbm;b.data.hasOwnProperty("rgbm")&&f.rgbm!==e&&(f.rgbm=e);f.fixCubemapSeams=!!b._dds;b.data.hasOwnProperty("minFilter")&&f.minFilter!==b.data.minFilter&&(f.minFilter=b.data.minFilter);b.data.hasOwnProperty("magFilter")&&f.magFilter!==
|
|
b.data.magFilter&&(f.magFilter=b.data.magFilter);b.data.hasOwnProperty("anisotropy")&&f.anisotropy!==b.data.anisotropy&&(f.anisotropy=b.data.anisotropy);f.addressU!==pc.ADDRESS_CLAMP_TO_EDGE&&(f.addressU=pc.ADDRESS_CLAMP_TO_EDGE);f.addressV!==pc.ADDRESS_CLAMP_TO_EDGE&&(f.addressV=pc.ADDRESS_CLAMP_TO_EDGE);this._patchTextureFaces(b,a);d&&(a.fire("load",b),a.fire("load:"+b.id,b),b.fire("load",b))},_patchTexture:function(){this.registry._loader._handlers.cubemap._patchTextureFaces(this,this.registry)},
|
|
_patchTextureFaces:function(b,a){if(b.loadFaces||!b.file){var c=b.resource,d=[],f=0,e=!1,l=this;b._levelsEvents||(b._levelsEvents=[null,null,null,null,null,null]);b.data.textures.forEach(function(g,p){var h=function(g){f++;d[p]=g&&g.resource.getSource()||null;var h=b._levelsEvents[p];if(h!==g){h&&h.off("load",l._patchTexture,b);if(g)g.on("load",l._patchTexture,b);b._levelsEvents[p]=g||null}d[p]!==c._levels[0][p]&&(e=!0);6===f&&e&&(c.setSource(d),a.fire("load",b),a.fire("load:"+b.id,b),b.fire("load",
|
|
b))},n=function(b){b.ready(h);a.load(b)},q=a.get(g);q?(q.ready(h),a.load(q)):g?(a.once("load:"+g,h),a.once("add:"+g,n)):h(null)})}}});return{CubemapHandler:e}}());Object.assign(pc,function(){var e=function(){};Object.assign(e.prototype,{load:function(b,a){"string"===typeof b&&(b={load:b,original:b});var c={};b.load.startsWith("blob:")&&(c.responseType=pc.Http.ResponseType.JSON);pc.http.get(b.load,c,function(c,f){c?a(pc.string.format("Error loading JSON resource: {0} [{1}]",b.original,c)):a(null,f)})},open:function(b,a){return a},patch:function(b,a){}});return{JsonHandler:e}}());Object.assign(pc,function(){var e={aoMap:"white",diffuseMap:"gray",specularMap:"gray",metalnessMap:"black",glossMap:"gray",emissiveMap:"gray",normalMap:"normal",heightMap:"gray",opacityMap:"gray",sphereMap:"gray",lightMap:"white"},b=function(a){this._assets=a.assets;this._device=a.graphicsDevice;this._placeholderTextures=null;this._parser=new pc.JsonStandardMaterialParser};Object.assign(b.prototype,{load:function(a,b){"string"===typeof a&&(a={load:a,original:a});pc.http.get(a.load,function(c,f){c?
|
|
b&&b(pc.string.format("Error loading material: {0} [{1}]",a.original,c)):b&&(f._engine=!0,b(null,f))})},open:function(a,b){var c=this._parser.parse(b);b._engine&&(c._data=b,delete b._engine);return c},_createPlaceholders:function(){this._placeholderTextures={};var a={white:[255,255,255,255],gray:[128,128,128,255],black:[0,0,0,255],normal:[128,128,255,255]},b;for(b in a)if(a.hasOwnProperty(b)){this._placeholderTextures[b]=new pc.Texture(this._device,{width:2,height:2,format:pc.PIXELFORMAT_R8_G8_B8_A8});
|
|
this._placeholderTextures[b].name="placeholder";for(var d=this._placeholderTextures[b].lock(),f=0;4>f;f++)for(var e=0;4>e;e++)d[4*f+e]=a[b][e];this._placeholderTextures[b].unlock()}},patch:function(a,b){a.resource._data&&(a._data=a.resource._data,delete a.resource._data);a.data.name=a.name;a.resource.name=a.name;this._bindAndAssignAssets(a,b);a.off("unload",this._onAssetUnload,this);a.on("unload",this._onAssetUnload,this)},_onAssetUnload:function(a){delete a.data.parameters;delete a.data.chunks;delete a.data.name},
|
|
_assignTexture:function(a,b,d){b.data[a]=d;b.resource[a]=d},_assignPlaceholderTexture:function(a,b){this._placeholderTextures||this._createPlaceholders();b.resource[a]=this._placeholderTextures[e[a]]},_onTextureLoad:function(a,b,d){this._assignTexture(a,b,d.resource);b.resource.update()},_onTextureAdd:function(a,b,d){this._assets.load(d)},_onTextureRemove:function(a,b,d){var c=b.resource;c[a]===d.resource&&(this._assignTexture(a,b,null),c.update())},_assignCubemap:function(a,b,d){b.data[a]=d[0];7===
|
|
d.length&&(b.data.prefilteredCubeMap128=d[1],b.data.prefilteredCubeMap64=d[2],b.data.prefilteredCubeMap32=d[3],b.data.prefilteredCubeMap16=d[4],b.data.prefilteredCubeMap8=d[5],b.data.prefilteredCubeMap4=d[6])},_onCubemapLoad:function(a,b,d){this._assignCubemap(a,b,d.resources);this._parser.initialize(b.resource,b.data)},_onCubemapAdd:function(a,b,d){b.data.shadingModel===pc.SPECULAR_PHONG&&(b.loadFaces=!0);this._assets.load(d)},_onCubemapRemove:function(a,b,d){var c=b.resource;c[a]===d.resource&&
|
|
(this._assignCubemap(a,b,[null,null,null,null,null,null,null]),c.update())},_bindAndAssignAssets:function(a,b){var c=this._parser.migrate(a.data),f=a.resource,e="path"===c.mappingFormat,l=pc.StandardMaterial.TEXTURE_PARAMETERS,h;e&&(h=pc.path.getDirectory(a.getFileUrl()));var p,k,n;for(p=0;p<l.length;p++)(k=l[p],n=f._assetReferences[k],!c[k]||c[k]instanceof pc.Texture)?n&&(e?n.url=null:n.id=null):(n||(n=new pc.AssetReference(k,a,b,{load:this._onTextureLoad,add:this._onTextureAdd,remove:this._onTextureRemove},
|
|
this),f._assetReferences[k]=n),e?n.url=pc.path.join(h,c[k]):n.id=c[k],n.asset&&(n.asset.resource?this._assignTexture(k,a,n.asset.resource):this._assignPlaceholderTexture(k,a),b.load(n.asset)));l=pc.StandardMaterial.CUBEMAP_PARAMETERS;for(p=0;p<l.length;p++)k=l[p],n=f._assetReferences[k],!c[k]||c[k]instanceof pc.Texture||(n||(n=new pc.AssetReference(k,a,b,{load:this._onCubemapLoad,add:this._onCubemapAdd,remove:this._onCubemapRemove},this),f._assetReferences[k]=n),e?n.url=c[k]:n.id=c[k],n.asset&&(n.asset.resource&&
|
|
this._assignCubemap(k,a,n.asset.resources),b.load(n.asset)));this._parser.initialize(f,c)}});return{MaterialHandler:b}}());Object.assign(pc,function(){var e=function(b,a){this._device=b;this._parsers=[];this._defaultMaterial=a;this.addParser(new pc.JsonModelParser(this._device),function(a,b){return".json"===pc.path.getExtension(a)})};Object.assign(e.prototype,{load:function(b,a){"string"===typeof b&&(b={load:b,original:b});var c={};b.load.startsWith("blob:")&&(c.responseType=pc.Http.ResponseType.JSON);pc.http.get(b.load,c,function(c,f){a&&(c?a(pc.string.format("Error loading model: {0} [{1}]",b.original,c)):a(null,f))})},
|
|
open:function(b,a){for(var c=0;c<this._parsers.length;c++){var d=this._parsers[c];if(d.decider(b,a))return d.parser.parse(a)}logWARNING(pc.string.format("No model parser found for: {0}",b));return null},patch:function(b,a){if(b.resource){var c=b.data,d=this;b.resource.meshInstances.forEach(function(f,e){if(c.mapping){var g=function(b){b.resource?f.material=b.resource:(b.once("load",g),a.load(b));b.once("remove",function(a){f.material===a.resource&&(f.material=d._defaultMaterial)})};if(c.mapping[e]){var h=
|
|
c.mapping[e].material,p=c.mapping[e].path;if(void 0!==h)if(h)if(p=a.get(h))g(p);else a.once("add:"+h,g);else f.material=d._defaultMaterial;else if(p)if(h=b.getFileUrl(),h=pc.path.getDirectory(h),h=pc.path.join(h,c.mapping[e].path),p=a.getByUrl(h))g(p);else a.once("add:url:"+h,g)}else f.material=d._defaultMaterial}})}},addParser:function(b,a){this._parsers.push({parser:b,decider:a})}});return{ModelHandler:e}}());Object.assign(pc,function(){var e=function(b){this._app=b;this._scripts={};this._cache={}};e._types=[];e._push=function(b){pc.script.legacy&&0<e._types.length?console.assert("Script Ordering Error. Contact support@playcanvas.com"):e._types.push(b)};Object.assign(e.prototype,{load:function(b,a){"string"===typeof b&&(b={load:b,original:b});var c=this;pc.script.app=this._app;this._loadScript(b.original,function(b,f,g){if(b)a(b);else if(pc.script.legacy)b=null,e._types.length&&(b=e._types.pop()),b?this._scripts[f]=
|
|
b:b=null,a(null,b,g);else{b={};for(var d=0;d<e._types.length;d++)b[e._types[d].name]=e._types[d];e._types.length=0;a(null,b,g);delete c._loader._cache[f+"script"]}}.bind(this))},open:function(b,a){return a},patch:function(b,a){},_loadScript:function(b,a){var c=document.head,d=document.createElement("script");this._cache[b]=d;d.async=!1;d.addEventListener("error",function(b){a(pc.string.format("Script: {0} failed to load",b.target.src))},!1);var f=!1;d.onload=d.onreadystatechange=function(){f||this.readyState&&
|
|
"loaded"!=this.readyState&&"complete"!=this.readyState||(f=!0,a(null,b,d))};d.src=b;c.appendChild(d)}});return{ScriptHandler:e}}());Object.assign(pc,function(){var e=function(){};Object.assign(e.prototype,{load:function(b,a){"string"===typeof b&&(b={load:b,original:b});pc.http.get(b.load,function(c,d){c?a(pc.string.format("Error loading text resource: {0} [{1}]",b.original,c)):a(null,d)})},open:function(b,a){return a},patch:function(b,a){}});return{TextHandler:e}}());Object.assign(pc,function(){var e=function(){};Object.assign(e.prototype,{load:function(b,a){"string"===typeof b&&(b={load:b,original:b});pc.http.get(b.load,{responseType:pc.Http.ResponseType.ARRAY_BUFFER},function(c,d){c?a(pc.string.format("Error loading binary resource: {0} [{1}]",b.original,c)):a(null,d)})},open:function(b,a){return a},patch:function(b,a){}});return{BinaryHandler:e}}());Object.assign(pc,function(){var e=function(a){return a.charCodeAt(0)+(a.charCodeAt(1)<<8)+(a.charCodeAt(2)<<16)+(a.charCodeAt(3)<<24)},b=e("DDS "),a=e("DXT1"),c=e("DXT5"),d=e("DX10"),f=e("ETC1"),g=e("P231"),l=e("P241"),h=e("P431"),p=e("P441"),k={};k[116]=pc.PIXELFORMAT_RGBA32F;k[a]=pc.PIXELFORMAT_DXT1;k[c]=pc.PIXELFORMAT_DXT5;k[f]=pc.PIXELFORMAT_ETC1;k[g]=pc.PIXELFORMAT_PVRTC_2BPP_RGB_1;k[l]=pc.PIXELFORMAT_PVRTC_2BPP_RGBA_1;k[h]=pc.PIXELFORMAT_PVRTC_4BPP_RGB_1;k[p]=pc.PIXELFORMAT_PVRTC_4BPP_RGBA_1;
|
|
return{DdsParser:function(e){var n=new Uint32Array(e,0,32);if(n[0]!==b)return null;var m=n[1],r=n[2],t=n[3],u=n[4],x=Math.max(n[7],1),v=n[22],w=n[28];if(124!==m)return null;var m=4+m,y=n[21];n[20]&4&&y===d&&(new Uint32Array(e,128,5),m+=20);w=(n=65024===w)?6:1;r=r&131072?x:1;x=[];if(n)for(var D=0;D<r;D++)x.push([]);for(D=0;D<w;D++)for(var B=u,z=t,A=0;A<r;A++){var F;if(y===a||y===c||y===f)F=Math.floor((B+3)/4)*Math.floor((z+3)/4)*(y===c?16:8);else if(y===g||y===l)F=Math.max(B,16)*Math.max(z,8)/4;else if(y===
|
|
h||y===p)F=Math.max(B,8)*Math.max(z,8)/2;else if(32===v)F=B*z*4;else return null;var I=116===y?new Float32Array(e,m,F):new Uint8Array(e,m,F);n?x[A][D]=I:x.push(I);m+=116===y?4*F:F;B=Math.max(.5*B,1);z=Math.max(.5*z,1)}this.format=k[y]||pc.PIXELFORMAT_R8_G8_B8_A8;this.width=u;this.height=t;this.levels=x;this.cubemap=n}}}());Object.assign(pc,function(){var e=[1481919403,3140563232,169478669],b={33776:pc.PIXELFORMAT_DXT1,33778:pc.PIXELFORMAT_DXT3,33779:pc.PIXELFORMAT_DXT5,36196:pc.PIXELFORMAT_ETC1,37492:pc.PIXELFORMAT_ETC2_RGB,37496:pc.PIXELFORMAT_ETC2_RGBA,35840:pc.PIXELFORMAT_PVRTC_4BPP_RGB_1,35841:pc.PIXELFORMAT_PVRTC_2BPP_RGB_1,35842:pc.PIXELFORMAT_PVRTC_4BPP_RGBA_1,35843:pc.PIXELFORMAT_PVRTC_2BPP_RGBA_1};return{KtxParser:function(a){var c=new Uint32Array(a,0,16);if(e[0]!==c[0]||e[1]!==c[1]||e[2]!==c[2])return null;
|
|
var d=c[6],f=c[7],g=c[9],l=c[10],h=c[12],p=c[13],k=c[14];if(1<c[11]||1<h||0!==d||!b[f])return null;for(var c=64+c[15],d=[],h=!1,n=0;n<(k||1);n++){var q=(new Uint32Array(a.slice(c,c+4)))[0],c=c+4,q=q/(p||1);1<p&&(h=!0,d.push([]));for(var m=0;m<p;m++){var r=new Uint8Array(a,c,q);1<p?d[n].push(r):d.push(r);c+=q}c+=3-(c+3)%4}this.format=b[f];this.width=g;this.height=l;this.levels=d;this.cubemap=h}}}());Object.assign(pc,function(){var e={repeat:pc.ADDRESS_REPEAT,clamp:pc.ADDRESS_CLAMP_TO_EDGE,mirror:pc.ADDRESS_MIRRORED_REPEAT},b={nearest:pc.FILTER_NEAREST,linear:pc.FILTER_LINEAR,nearest_mip_nearest:pc.FILTER_NEAREST_MIPMAP_NEAREST,linear_mip_nearest:pc.FILTER_LINEAR_MIPMAP_NEAREST,nearest_mip_linear:pc.FILTER_NEAREST_MIPMAP_LINEAR,linear_mip_linear:pc.FILTER_LINEAR_MIPMAP_LINEAR},a=function(a,b,f){this._device=a;this._assets=b;this._loader=f;this.crossOrigin=void 0;b.prefix&&(this.crossOrigin="anonymous")};
|
|
Object.assign(a.prototype,{load:function(a,b){"string"===typeof a&&(a={load:a,original:a});var c,d=0<=a.original.indexOf("?")?a.original.split("?")[0]:a.original,e=pc.path.getExtension(d).toLowerCase();if(".dds"===e||".ktx"===e)pc.http.get(a.load,{cache:!0,responseType:"arraybuffer"},function(a,c){a?b(a):b(null,c)});else if(".jpg"===e||".jpeg"===e||".gif"===e||".png"===e)c=new Image,void 0!==this.crossOrigin&&pc.ABSOLUTE_URL.test(a.original)&&(c.crossOrigin=this.crossOrigin),c.onload=function(){b(null,
|
|
c)},c.onerror=function(c){b(pc.string.format("Error loading Texture from: '{0}'",a.original))},c.src=a.load;else{var h=d.indexOf("blob:");0<=h?(a=d=d.substr(h),c=new Image,c.onload=function(){b(null,c)},c.onerror=function(c){b(pc.string.format("Error loading Texture from: '{0}'",a))},c.src=a):setTimeout(function(){b(pc.string.format("Error loading Texture: format not supported: '{0}'",e))},0)}},open:function(a,b){if(a){var c,d=pc.path.getExtension(a).toLowerCase();if(b instanceof Image||b instanceof
|
|
HTMLImageElement)c=".jpg"===d||".jpeg"===d?pc.PIXELFORMAT_R8_G8_B8:pc.PIXELFORMAT_R8_G8_B8_A8,c=new pc.Texture(this._device,{width:b.width,height:b.height,format:c}),c.name=a,c.setSource(b);else if(b instanceof ArrayBuffer)if(".dds"===d){c=b;var e=this._device;if(".crn"===pc.path.getExtension(a).toLowerCase()){var d=c.byteLength,h=new Uint8Array(c);c=Module._malloc(d);var p=Module.HEAPU8,k,n=c/4,q=d%4,m=new Uint32Array(h.buffer,0,(d-q)/4),r=new Uint32Array(p.buffer);for(k=0;k<m.length;k++)r[n+k]=
|
|
m[k];for(k=d-q;k<d;k++)p[c+k]=h[k];h=Module._crn_decompress_get_data(c,d);c=Module._crn_decompress_get_size(c,d);c=Module.HEAPU8.buffer.slice(h,h+c)}var t=new Uint32Array(c,0,32),d=t[4],h=t[3],p=Math.max(t[7],1),u=t[21],x=t[22];k=65024===t[28];var v=r=m=q=n=!1,w=null;if(4===t[20])if(827611204===u)w=pc.PIXELFORMAT_DXT1,n=!0;else if(894720068===u)w=pc.PIXELFORMAT_DXT5,n=!0;else if(116===u)w=pc.PIXELFORMAT_RGBA32F,q=!0;else if(826496069===u)w=pc.PIXELFORMAT_ETC1,m=n=!0;else if(825438800===u||825504336===
|
|
u)w=825438800===u?pc.PIXELFORMAT_PVRTC_2BPP_RGB_1:pc.PIXELFORMAT_PVRTC_2BPP_RGBA_1,r=n=!0;else{if(825439312===u||825504848===u)w=825439312===u?pc.PIXELFORMAT_PVRTC_4BPP_RGB_1:pc.PIXELFORMAT_PVRTC_4BPP_RGBA_1,v=n=!0}else 32===x&&(w=pc.PIXELFORMAT_R8_G8_B8_A8);if(w){e=new pc.Texture(e,{width:d,height:h,format:w,cubemap:k});k&&(e.addressU=pc.ADDRESS_CLAMP_TO_EDGE,e.addressV=pc.ADDRESS_CLAMP_TO_EDGE);for(var t=128,x=k?6:1,y,u=827611204===u?8:16,D,w=0;w<x;w++)for(var B=d,z=h,A=0;A<p;A++)n?m?y=Math.floor((B+
|
|
3)/4)*Math.floor((z+3)/4)*8:r?y=Math.max(B,16)*Math.max(z,8)/4:v?y=Math.max(B,8)*Math.max(z,8)/2:(y=Math.floor((B+4-1)/4),D=Math.floor((z+4-1)/4),y*=D,y*=u):y=B*z*4,D=q?new Float32Array(c,t,y):new Uint8Array(c,t,y),k?(e._levels[A]||(e._levels[A]=[]),e._levels[A][w]=D):e._levels[A]=D,t+=q?4*y:y,B=Math.max(.5*B,1),z=Math.max(.5*z,1);e.name=a;e.upload()}else e=new pc.Texture(e,{width:4,height:4,format:pc.PIXELFORMAT_R8_G8_B8}),e.name="dds-legacy-empty";c=e}else{switch(d){case ".dds":h=new pc.DdsParser(b);
|
|
break;case ".ktx":h=new pc.KtxParser(b);break;case ".pvr":console.warn("PVR container not supported.")}if(!h)return c=new pc.Texture(this._device,{width:4,height:4,format:pc.PIXELFORMAT_R8_G8_B8}),c.name="unsupported-empty",c;c=new pc.Texture(this._device,{addressU:h.cubemap?pc.ADDRESS_CLAMP_TO_EDGE:pc.ADDRESS_REPEAT,addressV:h.cubemap?pc.ADDRESS_CLAMP_TO_EDGE:pc.ADDRESS_REPEAT,width:h.width,height:h.height,format:h.format,cubemap:h.cubemap,levels:h.levels});c.name=a;c.upload()}return c}},patch:function(a,
|
|
d){var c=a.resource;if(c){c.name!==a.name&&(c.name=a.name);a.data.hasOwnProperty("minfilter")&&c.minFilter!==b[a.data.minfilter]&&(c.minFilter=b[a.data.minfilter]);a.data.hasOwnProperty("magfilter")&&c.magFilter!==b[a.data.magfilter]&&(c.magFilter=b[a.data.magfilter]);a.data.hasOwnProperty("addressu")&&c.addressU!==e[a.data.addressu]&&(c.addressU=e[a.data.addressu]);a.data.hasOwnProperty("addressv")&&c.addressV!==e[a.data.addressv]&&(c.addressV=e[a.data.addressv]);a.data.hasOwnProperty("mipmaps")&&
|
|
c.mipmaps!==a.data.mipmaps&&(c.mipmaps=a.data.mipmaps);a.data.hasOwnProperty("anisotropy")&&c.anisotropy!==a.data.anisotropy&&(c.anisotropy=a.data.anisotropy);var g=!!a.data.rgbm;a.data.hasOwnProperty("rgbm")&&c.rgbm!==g&&(c.rgbm=g)}}});return{TextureHandler:a}}());Object.assign(pc,function(){var e=function(){};Object.assign(e.prototype,{load:function(b,a){"string"===typeof b&&(b={load:b,original:b});pc.http.get(b.load,function(c,d){c?a(pc.string.format("Error loading html resource: {0} [{1}]",b.original,c)):a(null,d)})},open:function(b,a){return a},patch:function(b,a){}});return{HtmlHandler:e}}());Object.assign(pc,function(){var e=function(){};Object.assign(e.prototype,{load:function(b,a){"string"===typeof b&&(b={load:b,original:b});pc.http.get(b.load,function(c,d){c?a(pc.string.format("Error loading css resource: {0} [{1}]",b.original,c)):a(null,d)})},open:function(b,a){return a},patch:function(b,a){}});return{CssHandler:e,createStyle:function(b){var a=document.createElement("style");a.type="text/css";a.styleSheet?a.styleSheet.cssText=b:a.appendChild(document.createTextNode(b));return a}}}());Object.assign(pc,function(){var e=function(){};Object.assign(e.prototype,{load:function(b,a){"string"===typeof b&&(b={load:b,original:b});pc.http.get(b.load,function(c,d){c?a(pc.string.format("Error loading shader resource: {0} [{1}]",b.original,c)):a(null,d)})},open:function(b,a){return a},patch:function(b,a){}});return{ShaderHandler:e}}());Object.assign(pc,function(){var e=function(b){this._app=b};Object.assign(e.prototype,{load:function(b,a){"string"===typeof b&&(b={load:b,original:b});pc.http.get(b.load,function(c,d){c?a("Error requesting scene: "+b.original):a(null,d)})},open:function(b,a){this._app.systems.script.preloading=!0;var c=(new pc.SceneParser(this._app)).parse(a),d=this._app.scene;d.root=c;this._app.applySceneSettings(a.settings);this._app.systems.script.preloading=!1;return d},patch:function(b,a){}});return{SceneHandler:e}}());Object.assign(pc,function(){var e=function(b){this._app=b};Object.assign(e.prototype,{load:function(b,a){"string"===typeof b&&(b={load:b,original:b});pc.http.get(b.load,function(c,d){if(c){var f="Error while loading scene "+b.original;c.message?(f+=": "+c.message,c.stack&&(f+="\n"+c.stack)):f+=": "+c;a(f)}else a(null,d)})},open:function(b,a){this._app.systems.script.preloading=!0;var c=(new pc.SceneParser(this._app)).parse(a);this._app.systems.script.preloading=!1;return c}});return{HierarchyHandler:e}}());Object.assign(pc,function(){var e=function(b){this._app=b};Object.assign(e.prototype,{load:function(b,a){"string"===typeof b&&(b={load:b,original:b});pc.http.get(b.load,function(c,d){c?a("Error requesting scene: "+b.original):a(null,d)})},open:function(b,a){return a.settings}});return{SceneSettingsHandler:e}}());Object.assign(pc,function(){var e=function(){};Object.assign(e.prototype,{load:function(b,a){a(null,null)},open:function(b,a){return a}});return{FolderHandler:e}}());Object.assign(pc,function(){function e(a){3>a.version&&(2>a.version&&(a.info.maps=a.info.maps||[{width:a.info.width,height:a.info.height}]),a.chars=Object.keys(a.chars||{}).reduce(function(b,d){var c=a.chars[d],e=void 0!==c.letter?c.letter:pc.string.fromCodePoint(d);2>a.version&&(c.map=c.map||0);b[e]=c;return b},{}),a.version=3);return a}var b=function(a){this._loader=a};Object.assign(b.prototype,{load:function(a,b,d){"string"===typeof a&&(a={load:a,original:a});var c=this;".json"===pc.path.getExtension(a.original)?
|
|
pc.http.get(a.load,function(d,f){var g=e(f);d?b(pc.string.format("Error loading font resource: {0} [{1}]",a.original,d)):c._loadTextures(a.original.replace(".json",".png"),g,function(a,c){if(a)return b(a);b(null,{data:g,textures:c})})}):(d&&d.data&&(d.data=e(d.data)),this._loadTextures(a.original,d&&d.data,b))},_loadTextures:function(a,b,d){var c=b.info.maps.length,e=0,l=null,h=Array(c),p=this._loader;b=function(b){var f=function(a,f){if(!l){if(a)return l=a,d(a);f.upload();h[b]=f;e++;e===c&&d(null,
|
|
h)}};0===b?p.load(a,"texture",f):p.load(a.replace(".png",b+".png"),"texture",f)};for(var k=0;k<c;k++)b(k)},open:function(a,b,d){return b.textures?new pc.Font(b.textures,b.data):new pc.Font(b,null)},patch:function(a,b){var c=a.resource;!c.data&&a.data?c.data=a.data:!a.data&&c.data&&(a.data=c.data)}});return{FontHandler:b}}());Object.assign(pc,function(){var e={repeat:pc.ADDRESS_REPEAT,clamp:pc.ADDRESS_CLAMP_TO_EDGE,mirror:pc.ADDRESS_MIRRORED_REPEAT},b={nearest:pc.FILTER_NEAREST,linear:pc.FILTER_LINEAR,nearest_mip_nearest:pc.FILTER_NEAREST_MIPMAP_NEAREST,linear_mip_nearest:pc.FILTER_LINEAR_MIPMAP_NEAREST,nearest_mip_linear:pc.FILTER_NEAREST_MIPMAP_LINEAR,linear_mip_linear:pc.FILTER_LINEAR_MIPMAP_LINEAR},a=/^data\.frames\.(\d+)$/,c=function(a){this._loader=a};Object.assign(c.prototype,{load:function(a,b){"string"===typeof a&&
|
|
(a={load:a,original:a});var c=this,d=this._loader.getHandler("texture");if(".json"===pc.path.getExtension(a.original))pc.http.get(a.load,function(d,f){if(d)b(d);else{var e=a.original.replace(".json",".png");c._loader.load(e,"texture",function(a,c){a?b(a):b(null,{data:f,texture:c})})}});else return d.load(a,b)},open:function(a,b){var c=new pc.TextureAtlas;if(b.texture&&b.data)c.texture=b.texture,c.__data=b.data;else{var d=this._loader.getHandler("texture").open(a,b);if(!d)return null;c.texture=d}return c},
|
|
patch:function(a,c){a.resource.__data&&(void 0!==a.resource.__data.minfilter&&(a.data.minfilter=a.resource.__data.minfilter),void 0!==a.resource.__data.magfilter&&(a.data.magfilter=a.resource.__data.magfilter),void 0!==a.resource.__data.addressu&&(a.data.addressu=a.resource.__data.addressu),void 0!==a.resource.__data.addressv&&(a.data.addressv=a.resource.__data.addressv),void 0!==a.resource.__data.mipmaps&&(a.data.mipmaps=a.resource.__data.mipmaps),void 0!==a.resource.__data.anisotropy&&(a.data.anisotropy=
|
|
a.resource.__data.anisotropy),void 0!==a.resource.__data.rgbm&&(a.data.rgbm=!!a.resource.__data.rgbm),a.data.frames=a.resource.__data.frames,delete a.resource.__data);var d=a.resource.texture;if(d){d.name=a.name;a.data.hasOwnProperty("minfilter")&&d.minFilter!==b[a.data.minfilter]&&(d.minFilter=b[a.data.minfilter]);a.data.hasOwnProperty("magfilter")&&d.magFilter!==b[a.data.magfilter]&&(d.magFilter=b[a.data.magfilter]);a.data.hasOwnProperty("addressu")&&d.addressU!==e[a.data.addressu]&&(d.addressU=
|
|
e[a.data.addressu]);a.data.hasOwnProperty("addressv")&&d.addressV!==e[a.data.addressv]&&(d.addressV=e[a.data.addressv]);a.data.hasOwnProperty("mipmaps")&&d.mipmaps!==a.data.mipmaps&&(d.mipmaps=a.data.mipmaps);a.data.hasOwnProperty("anisotropy")&&d.anisotropy!==a.data.anisotropy&&(d.anisotropy=a.data.anisotropy);var f=!!a.data.rgbm;a.data.hasOwnProperty("rgbm")&&d.rgbm!==f&&(d.rgbm=f)}a.resource.texture=d;var d={},h;for(h in a.data.frames)f=a.data.frames[h],d[h]={rect:new pc.Vec4(f.rect),pivot:new pc.Vec2(f.pivot),
|
|
border:new pc.Vec4(f.border)};a.resource.frames=d;a.off("change",this._onAssetChange,this);a.on("change",this._onAssetChange,this)},_onAssetChange:function(b,c,e){if("data"===c||"data.frames"===c){var d={},f;for(f in e.frames)c=e.frames[f],d[f]={rect:new pc.Vec4(c.rect),pivot:new pc.Vec2(c.pivot),border:new pc.Vec4(c.border)};b.resource.frames=d}else if(c=c.match(a))f=c[1],e?(b.resource.frames[f]?(c=b.resource.frames[f],c.rect.set(e.rect[0],e.rect[1],e.rect[2],e.rect[3]),c.pivot.set(e.pivot[0],e.pivot[1]),
|
|
c.border.set(e.border[0],e.border[1],e.border[2],e.border[3])):b.resource.frames[f]={rect:new pc.Vec4(e.rect),pivot:new pc.Vec2(e.pivot),border:new pc.Vec4(e.border)},b.resource.fire("set:frame",f,b.resource.frames[f])):b.resource.frames[f]&&(delete b.resource.frames[f],b.resource.fire("remove:frame",f))}});return{TextureAtlasHandler:c}}());Object.assign(pc,function(){var e=function(a,b){this._assets=a;this._device=b},b=function(a){this.resource&&(this.resource.atlas=a.resource)},a=function(a){this.registry.load(a)};Object.assign(e.prototype,{load:function(a,b){"string"===typeof a&&(a={load:a,original:a});".json"===pc.path.getExtension(a.original)&&pc.http.get(a.load,function(a,c){a?b(a):b(null,c)})},open:function(a,b){var c=new pc.Sprite(this._device);a&&(c.__data=b);return c},patch:function(a,b){var c=a.resource;if(c.__data&&(a.data.pixelsPerUnit=
|
|
c.__data.pixelsPerUnit,a.data.renderMode=c.__data.renderMode,a.data.frameKeys=c.__data.frameKeys,c.__data.textureAtlasAsset)){var d=b.getByUrl(c.__data.textureAtlasAsset);d?a.data.textureAtlasAsset=d.id:console.warn("Could not find textureatlas with url: "+c.__data.textureAtlasAsset)}c.startUpdate();c.renderMode=a.data.renderMode;c.pixelsPerUnit=a.data.pixelsPerUnit;c.frameKeys=a.data.frameKeys;this._updateAtlas(a);c.endUpdate();a.off("change",this._onAssetChange,this);a.on("change",this._onAssetChange,
|
|
this)},_updateAtlas:function(c){var d=c.resource;if(c.data.textureAtlasAsset){this._assets.off("load:"+c.data.textureAtlasAsset,b,c);this._assets.on("load:"+c.data.textureAtlasAsset,b,c);var f=this._assets.get(c.data.textureAtlasAsset);f&&f.resource?d.atlas=f.resource:f?this._assets.load(f):(this._assets.off("add:"+c.data.textureAtlasAsset,a,c),this._assets.on("add:"+c.data.textureAtlasAsset,a,c))}else d.atlas=null},_onAssetChange:function(c,d,f,e){"data"===d&&f&&f.textureAtlasAsset&&e&&f.textureAtlasAsset!==
|
|
e.textureAtlasAsset&&(this._assets.off("load:"+e.textureAtlasAsset,b,c),this._assets.off("add:"+e.textureAtlasAsset,a,c))}});return{SpriteHandler:e}}());Object.assign(pc,function(){var e={points:pc.PRIMITIVE_POINTS,lines:pc.PRIMITIVE_LINES,lineloop:pc.PRIMITIVE_LINELOOP,linestrip:pc.PRIMITIVE_LINESTRIP,triangles:pc.PRIMITIVE_TRIANGLES,trianglestrip:pc.PRIMITIVE_TRISTRIP,trianglefan:pc.PRIMITIVE_TRIFAN},b={int8:pc.TYPE_INT8,uint8:pc.TYPE_UINT8,int16:pc.TYPE_INT16,uint16:pc.TYPE_UINT16,int32:pc.TYPE_INT32,uint32:pc.TYPE_UINT32,float32:pc.TYPE_FLOAT32},a=function(a){this._device=a;this._defaultMaterial=pc.getDefaultMaterial()};Object.assign(a.prototype,
|
|
{parse:function(a){var b=a.model;if(!b||1>=b.version)return null;var b=this._parseNodes(a),c=this._parseSkins(a,b),e=this._parseMorphs(a,b),l=this._parseVertexBuffers(a),h=this._parseIndexBuffers(a,l),h=this._parseMeshes(a,c.skins,e.morphs,l,h.buffer,h.data);this._initMorphs(a,e.morphs,l,h);a=this._parseMeshInstances(a,b,h,c.skins,c.instances,e.morphs,e.instances);l=new pc.Model;l.graph=b[0];l.meshInstances=a;l.skinInstances=c.instances;l.morphInstances=e.instances;l.getGraph().syncHierarchy();return l},
|
|
_parseNodes:function(a){a=a.model;var b=[],c;for(c=0;c<a.nodes.length;c++){var e=a.nodes[c],l=new pc.GraphNode;l.setName(e.name);l.setLocalPosition(e.position[0],e.position[1],e.position[2]);l.setLocalEulerAngles(e.rotation[0],e.rotation[1],e.rotation[2]);l.setLocalScale(e.scale[0],e.scale[1],e.scale[2]);l.scaleCompensation=!!e.scaleCompensation;b.push(l)}for(c=1;c<a.parents.length;c++)b[a.parents[c]].addChild(b[c]);return b},_parseSkins:function(a,b){var c=a.model,d=[],e=[],h,p;!this._device.supportsBoneTextures&&
|
|
0<c.skins.length&&(h=this._device.getBoneLimit(),pc.partitionSkin(c,null,h));for(h=0;h<c.skins.length;h++){var k=c.skins[h],n=[];for(p=0;p<k.inverseBindMatrices.length;p++){var q=k.inverseBindMatrices[p];n[p]=(new pc.Mat4).set(q)}k=new pc.Skin(this._device,n,k.boneNames);d.push(k);n=new pc.SkinInstance(k);q=[];for(p=0;p<k.boneNames.length;p++){var m=b[0].findByName(k.boneNames[p]);q.push(m)}n.bones=q;e.push(n)}return{skins:d,instances:e}},_parseMorphs:function(a,b){var c=a.model,d=[],e=[],h,p,k,n,
|
|
q;if(c.morphs)for(h=0;h<c.morphs.length;h++){k=c.morphs[h].targets;q=[];for(p=0;p<k.length;p++){var m=k[p].aabb;n=m.min;m=m.max;n=new pc.BoundingBox(new pc.Vec3(.5*(m[0]+n[0]),.5*(m[1]+n[1]),.5*(m[2]+n[2])),new pc.Vec3(.5*(m[0]-n[0]),.5*(m[1]-n[1]),.5*(m[2]-n[2])));n=new pc.MorphTarget({indices:k[p].indices,deltaPositions:k[p].deltaPositions,deltaNormals:k[p].deltaNormals,name:k[p].name,aabb:n});q.push(n)}p=new pc.Morph(q);d.push(p);p=new pc.MorphInstance(p);e.push(p)}return{morphs:d,instances:e}},
|
|
_calculateTangentsMorphTarget:function(a,b,f,e,l,h,p,k){var c,d,g,r,t,u,x,v,w,y,D,B,z,A,F,I,G,H,C,E;I=e.length/3;for(E=0;E<I;E++)G=e[3*E],H=e[3*E+1],C=e[3*E+2],x=a[3*G],t=a[3*G+1],u=a[3*G+2],r=a[3*H],v=a[3*H+1],w=a[3*H+2],y=a[3*C],D=a[3*C+1],B=a[3*C+2],z=f[2*G],c=f[2*G+1],A=f[2*H],g=f[2*H+1],F=f[2*C],d=f[2*C+1],r-=x,x=y-x,v-=t,t=D-t,w-=u,u=B-u,A-=z,z=F-z,g-=c,B=d-c,c=A*B-z*g,0==c?(c=0,d=1,g=0,r=1,u=t=0):(F=1/c,c=(B*r-g*x)*F,d=(B*v-g*t)*F,g=(B*w-g*u)*F,r=(A*x-z*r)*F,t=(A*t-z*v)*F,u=(A*u-z*w)*F),l[3*
|
|
G+0]+=c,l[3*G+1]+=d,l[3*G+2]+=g,l[3*H+0]+=c,l[3*H+1]+=d,l[3*H+2]+=g,l[3*C+0]+=c,l[3*C+1]+=d,l[3*C+2]+=g,h[3*G+0]+=r,h[3*G+1]+=t,h[3*G+2]+=u,h[3*H+0]+=r,h[3*H+1]+=t,h[3*H+2]+=u,h[3*C+0]+=r,h[3*C+1]+=t,h[3*C+2]+=u;c=p.length;for(C=0;C<c;C++)E=p[C],w=b[3*E],d=b[3*E+1],v=b[3*E+2],a=l[3*E],f=l[3*E+1],e=l[3*E+2],I=h[3*E],G=h[3*E+1],H=h[3*E+2],u=w*a+d*f+v*e,x=w*u,t=d*u,u*=v,r=d*e-f*v,v=v*a-e*w,w=w*f-a*d,a-=x,f-=t,e-=u,u=1/Math.sqrt(a*a+f*f+e*e),a*=u,f*=u,e*=u,k[4*E]=a,k[4*E+1]=f,k[4*E+2]=e,k[4*E+3]=0>r*
|
|
I+v*G+w*H?-1:1;return k},_initMorphs:function(a,b,f,e){a=a.model;var c,d,g,k,n,q,m,r,t,u,x,v,w,y,D,B=[],z=[];for(f=0;f<e.length;f++)if(t=a.meshes[f].vertices,!z[t]&&(d=a.vertices[t],d.tangent)){var A=new Float32Array(d.tangent.data);z[t]=!0;if(d.position&&d.normal&&d.texCoord0){var F=[];for(c=0;c<a.meshes.length;c++)a.meshes[c].vertices===t&&(F=F.concat(a.meshes[c].indices));t=d.position.data;u=d.normal.data;x=d.texCoord0.data;v=t.length/3;w=F.length;var I=new Float32Array(4*v),G=new Float32Array(3*
|
|
v),H=new Float32Array(3*v);y=new Float32Array(3*v);y.set(t);D=new Float32Array(3*v);D.set(u);for(c=0;c<b.length;c++)if(a.meshes[f].morph===c)for(g=0;g<b[c]._targets.length;g++){d=b[c]._targets[g];var C=d.indices,E=C.length;if(0!==E){d.deltaTangents=new Float32Array(4*E);if(!r||r.length<v)r=new Uint8Array(v);else for(k=0;k<v;k++)r[k]=0;for(k=0;k<E;k++)n=C[k],r[n]=1;var K=0;for(k=0;k<w;k+=3)if(n=F[k],q=F[k+1],m=F[k+2],r[n]||r[q]||r[m])B[K]=n,B[K+1]=q,B[K+2]=m,K+=3;B.length=K;q=d.deltaPositions;m=d.deltaNormals;
|
|
for(k=0;k<E;k++)n=C[k],y[3*n]+=q[3*k],y[3*n+1]+=q[3*k+1],y[3*n+2]+=q[3*k+2],D[3*n]+=m[3*k],D[3*n+1]+=m[3*k+1],D[3*n+2]+=m[3*k+2];this._calculateTangentsMorphTarget(y,D,x,B,G,H,C,I);q=d.deltaTangents;for(k=0;k<E;k++)n=C[k],q[4*k]=I[4*k]-A[4*n],q[4*k+1]=I[4*k+1]-A[4*n+1],q[4*k+2]=I[4*k+2]-A[4*n+2],q[4*k+3]=I[4*k+3]-A[4*n+3];if(g!==b[c]._targets.length-1){for(k=0;k<w;k+=3)n=F[k],q=F[k+1],m=F[k+2],G[3*n+0]=0,G[3*n+1]=0,G[3*n+2]=0,G[3*q+0]=0,G[3*q+1]=0,G[3*q+2]=0,G[3*m+0]=0,G[3*m+1]=0,G[3*m+2]=0,H[3*n+
|
|
0]=0,H[3*n+1]=0,H[3*n+2]=0,H[3*q+0]=0,H[3*q+1]=0,H[3*q+2]=0,H[3*m+0]=0,H[3*m+1]=0,H[3*m+2]=0;for(k=0;k<E;k++)n=d.indices[k],y[3*n]=t[3*n],y[3*n+1]=t[3*n+1],y[3*n+2]=t[3*n+2],D[3*n]=u[3*n],D[3*n+1]=u[3*n+1],D[3*n+2]=u[3*n+2]}}}}}},_parseVertexBuffers:function(a){a=a.model;var c=[],f,e,l={position:pc.SEMANTIC_POSITION,normal:pc.SEMANTIC_NORMAL,tangent:pc.SEMANTIC_TANGENT,blendWeight:pc.SEMANTIC_BLENDWEIGHT,blendIndices:pc.SEMANTIC_BLENDINDICES,color:pc.SEMANTIC_COLOR,texCoord0:pc.SEMANTIC_TEXCOORD0,
|
|
texCoord1:pc.SEMANTIC_TEXCOORD1,texCoord2:pc.SEMANTIC_TEXCOORD2,texCoord3:pc.SEMANTIC_TEXCOORD3,texCoord4:pc.SEMANTIC_TEXCOORD4,texCoord5:pc.SEMANTIC_TEXCOORD5,texCoord6:pc.SEMANTIC_TEXCOORD6,texCoord7:pc.SEMANTIC_TEXCOORD7},h,p;for(h=0;h<a.vertices.length;h++){var k=a.vertices[h],n=[];for(e in k)f=k[e],n.push({semantic:l[e],components:f.components,type:b[f.type],normalize:l[e]===pc.SEMANTIC_COLOR});f=new pc.VertexFormat(this._device,n);var n=k.position.data.length/k.position.components,q=new pc.VertexBuffer(this._device,
|
|
f,n),m=new pc.VertexIterator(q);for(p=0;p<n;p++){for(e in k)switch(f=k[e],f.components){case 1:m.element[l[e]].set(f.data[p]);break;case 2:m.element[l[e]].set(f.data[2*p],f.data[2*p+1]);break;case 3:m.element[l[e]].set(f.data[3*p],f.data[3*p+1],f.data[3*p+2]);break;case 4:m.element[l[e]].set(f.data[4*p],f.data[4*p+1],f.data[4*p+2],f.data[4*p+3])}m.next()}m.end();c.push(q)}return c},_parseIndexBuffers:function(a,b){var c=a.model,d=null,e=null,h,p=0;for(h=0;h<c.meshes.length;h++){var k=c.meshes[h];
|
|
void 0!==k.indices&&(p+=k.indices.length)}for(h=c=0;h<b.length;h++)c=Math.max(c,b[h].numVertices);0<p&&(65535<c&&this._device.extUintElement?(d=new pc.IndexBuffer(this._device,pc.INDEXFORMAT_UINT32,p),e=new Uint32Array(d.lock())):(d=new pc.IndexBuffer(this._device,pc.INDEXFORMAT_UINT16,p),e=new Uint16Array(d.lock())));return{buffer:d,data:e}},_parseMeshes:function(a,b,f,g,l,h){a=a.model;var c=[],d=0,n;for(n=0;n<a.meshes.length;n++){var q=a.meshes[n],m=q.aabb,r=m.min,m=m.max,r=new pc.BoundingBox(new pc.Vec3(.5*
|
|
(m[0]+r[0]),.5*(m[1]+r[1]),.5*(m[2]+r[2])),new pc.Vec3(.5*(m[0]-r[0]),.5*(m[1]-r[1]),.5*(m[2]-r[2]))),m=void 0!==q.indices,t=new pc.Mesh;t.vertexBuffer=g[q.vertices];t.indexBuffer[0]=m?l:null;t.primitive[0].type=e[q.type];t.primitive[0].base=m?q.base+d:q.base;t.primitive[0].count=q.count;t.primitive[0].indexed=m;t.skin=void 0!==q.skin?b[q.skin]:null;t.morph=void 0!==q.morph?f[q.morph]:null;t.aabb=r;m&&(h.set(q.indices,d),d+=q.indices.length);c.push(t)}null!==l&&l.unlock();return c},_parseMeshInstances:function(a,
|
|
b,f,e,l,h,p){a=a.model;var c=[],d;for(d=0;d<a.meshInstances.length;d++){var g=a.meshInstances[d],m=f[g.mesh],g=new pc.MeshInstance(b[g.node],m,this._defaultMaterial);if(m.skin){var r=e.indexOf(m.skin);g.skinInstance=l[r]}m.morph&&(m=h.indexOf(m.morph),g.morphInstance=p[m]);c.push(g)}return c}});return{JsonModelParser:a}}());Object.assign(pc,function(){var e=function(b){this._app=b};Object.assign(e.prototype,{parse:function(b){var a={},c,d,e=null;for(c in b.entities)a[c]=this._createEntity(b.entities[c]),null===b.entities[c].parent&&(e=a[c]);for(c in b.entities){var g=b.entities[c].children.length;for(d=0;d<g;d++){var l=b.entities[c].children[d];a[l]&&a[c].addChild(a[l])}}this._openComponentData(e,b.entities);return e},_createEntity:function(b){var a=new pc.Entity,c=b.position,d=b.rotation,e=b.scale;a.name=b.name;a.setGuid(b.resource_id);
|
|
a.setLocalPosition(c[0],c[1],c[2]);a.setLocalEulerAngles(d[0],d[1],d[2]);a.setLocalScale(e[0],e[1],e[2]);a._enabled=void 0!==b.enabled?b.enabled:!0;a._enabledInHierarchy=a._enabled;a.template=b.template;if(b.tags)for(c=0;c<b.tags.length;c++)a.tags.add(b.tags[c]);b.labels&&b.labels.forEach(function(b){a.addLabel(b)});return a},_openComponentData:function(b,a){var c=this._app.systems.list,d,e=c.length,g=a[b.getGuid()];for(d=0;d<e;d++){var l=c[d],h=g.components[l.id];h&&l.addComponent(b,h)}e=g.children.length;
|
|
c=b._children;for(d=0;d<e;d++)c[d]=this._openComponentData(c[d],a);return b}});return{SceneParser:e}}());Object.assign(pc,function(){var e=function(){this._validator=null};e.prototype.parse=function(b){b=this.migrate(b);b=this._validate(b);var a=new pc.StandardMaterial;this.initialize(a,b);return a};e.prototype.initialize=function(b,a){a.validated||(this._validator||(this._validator=new pc.StandardMaterialValidator),this._validator.validate(a));a.chunks&&b.chunks.copy(a.chunks);for(var c in a){var d=pc.StandardMaterial.PARAMETER_TYPES[c],e=a[c];"vec2"===d?b[c]=new pc.Vec2(e[0],e[1]):"rgb"===d?b[c]=new pc.Color(e[0],
|
|
e[1],e[2]):"texture"===d?e instanceof pc.Texture?b[c]=e:b[c]instanceof pc.Texture&&"number"===typeof e&&0<e||(b[c]=null):"cubemap"===d?e instanceof pc.Texture?b[c]=e:b[c]instanceof pc.Texture&&"number"===typeof e&&0<e||(b[c]=null):"boundingbox"===d?(d=new pc.Vec3(e.center[0],e.center[1],e.center[2]),e=new pc.Vec3(e.halfExtents[0],e.halfExtents[1],e.halfExtents[2]),b[c]=new pc.BoundingBox(d,e)):b[c]=a[c]}b.update()};e.prototype.migrate=function(b){void 0===b.shadingModel&&(b.shadingModel="blinn"===
|
|
b.shader?pc.SPECULAR_BLINN:pc.SPECULAR_PHONG);b.shader&&delete b.shader;b.mapping_format&&(b.mappingFormat=b.mapping_format,delete b.mapping_format);var a,c=[["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(a=0;a<c.length;a++){var d=c[a][0],e=c[a][1];void 0!==b[d]&&void 0===b[e]&&(b[e]=b[d],delete b[d])}c=["fresnelFactor","shadowSampleType"];for(a=0;a<c.length;a++)d=c[a],b.hasOwnProperty(d)&&delete b[d];return b};e.prototype._validate=function(b){this._validator||(this._validator=new pc.StandardMaterialValidator);
|
|
this._validator.validate(b);return b};return{JsonStandardMaterialParser:e}}());Object.assign(pc,function(){var e=0,b=/^\s*(?:[a-z]+[a-z0-9\-\+\.]*:)?\/\//i,a={pvr:"extCompressedTexturePVRTC",dxt:"extCompressedTextureS3TC",etc2:"extCompressedTextureETC",etc1:"extCompressedTextureETC1"},c=["pvr","dxt","etc2","etc1"],d=function(a,b,c,d){this._id=++e;this.name=a||"";this.type=b;this.tags=new pc.Tags(this);this._preload=!1;this.variants=new pc.AssetVariants(this);this._file=null;this._data=d||{};this._resources=[];this.loading=this.loaded=!1;this.registry=null;pc.events.attach(this);
|
|
c&&(this.file=c)};Object.assign(d.prototype,{getFileUrl:function(){var a=this.getPreferredFile();if(!a||!a.url)return null;var c=a.url;this.registry&&this.registry.prefix&&!b.test(c)&&(c=this.registry.prefix+c);if("script"!==this.type&&a.hash)var d=-1!==c.indexOf("?")?"&":"?",c=c+(d+"t="+a.hash);return c},getPreferredFile:function(){if(!this.file)return null;if("texture"===this.type||"textureatlas"===this.type||"bundle"===this.type)for(var b=this.registry._loader._app,d=b.graphicsDevice,e=0,h=c.length;e<
|
|
h;e++){var p=c[e];if(d[a[p]]){if(this.file.variants[p])return this.file.variants[p];if(b.enableBundles){var k=b.bundles.listBundlesForAsset(this);if(k)for(var n=0,q=k.length;n<q;n++)if(k[n].file&&k[n].file.variants&&k[n].file.variants[p])return this.file}}}return this.file},ready:function(a,b){b=b||this;if(this.resource)a.call(b,this);else this.once("load",function(c){a.call(b,c)})},reload:function(){this.loaded&&("cubemap"===this.type?this.registry._loader.patch(this,this.registry):(this.loaded=
|
|
!1,this.registry.load(this)))},unload:function(){if(this.loaded||this.resource)this.fire("unload",this),this.registry.fire("unload:"+this.id,this),this.resource&&this.resource.destroy&&this.resource.destroy(),this.resource=null,this.loaded=!1,this.file&&this.registry._loader.clearCache(this.getFileUrl(),this.type)}});Object.defineProperty(d.prototype,"id",{get:function(){return this._id},set:function(a){this._id=a;a>e&&(e=a)}});Object.defineProperty(d.prototype,"file",{get:function(){return this._file},
|
|
set:function(a){var b;if(!!a!==!!this._file||a&&this._file&&a.hash!==this._file)if(a){this._file||(this._file={});this._file.url=a.url;this._file.filename=a.filename;this._file.hash=a.hash;this._file.size=a.size;this._file.variants=this.variants;if(a.hasOwnProperty("variants")&&(this.variants.clear(),a.variants))for(b in a.variants)a.variants[b]&&(this.variants[b]=a.variants[b]);this.fire("change",this,"file",this._file,this._file);this.reload()}else this._file=null,this.variants.clear();else if(a&&
|
|
this._file&&a.hasOwnProperty("variants")&&(this.variants.clear(),a.variants))for(b in a.variants)a.variants[b]&&(this.variants[b]=a.variants[b])}});Object.defineProperty(d.prototype,"data",{get:function(){return this._data},set:function(a){var b=this._data;this._data=a;a!==b&&(this.fire("change",this,"data",a,b),this.loaded&&this.registry._loader.patch(this,this.registry))}});Object.defineProperty(d.prototype,"resource",{get:function(){return this._resources[0]},set:function(a){var b=this._resources[0];
|
|
this._resources[0]=a;this.fire("change",this,"resource",a,b)}});Object.defineProperty(d.prototype,"resources",{get:function(){return this._resources},set:function(a){var b=this._resources;this._resources=a;this.fire("change",this,"resources",a,b)}});Object.defineProperty(d.prototype,"preload",{get:function(){return this._preload},set:function(a){a=!!a;this._preload!==a&&(this._preload=a)&&!this.loaded&&!this.loading&&this.registry&&this.registry.load(this)}});return{Asset:d,ASSET_ANIMATION:"animation",
|
|
ASSET_AUDIO:"audio",ASSET_IMAGE:"image",ASSET_JSON:"json",ASSET_MODEL:"model",ASSET_MATERIAL:"material",ASSET_TEXT:"text",ASSET_TEXTURE:"texture",ASSET_CUBEMAP:"cubemap",ASSET_SHADER:"shader",ASSET_CSS:"css",ASSET_HTML:"html",ASSET_SCRIPT:"script",ABSOLUTE_URL:b}}());Object.assign(pc,function(){var e=[],b=function(a){this.asset=a},a=function(a){var c="_"+a;e.push(c);Object.defineProperty(b.prototype,a,{get:function(){return this[c]||null},set:function(a){if(!!this[c]!==!!a||this[c]&&a&&this[c].hash!==a.hash)this[c]=a?{url:a.url,filename:a.filename,size:a.size,hash:a.hash,opt:a.opt||0}:null,this.asset.file&&(this.asset.fire("change",this.asset,"file",this.asset._file,this.asset._file),this.asset.reload())}})};a("dxt");a("pvr");a("etc1");a("etc2");b.prototype.clear=
|
|
function(){for(var a=0;a<e.length;a++)this[e[a]]=null};return{AssetVariants:b}}());Object.assign(pc,function(){var e=function(b){this._loader=b;this._assets=[];this._cache={};this._names={};this._tags=new pc.TagsCache("_id");this._urls={};this.prefix=null;Object.assign(this,pc.events)};Object.assign(e.prototype,{list:function(b){b=b||{};return this._assets.filter(function(a){var c=!0;void 0!==b.preload&&(c=a.preload===b.preload);return c})},add:function(b){var a=this._assets.push(b)-1,c;this._cache[b.id]=a;this._names[b.name]||(this._names[b.name]=[]);this._names[b.name].push(a);
|
|
b.file&&(c=b.file.url,this._urls[c]=a);b.registry=this;this._tags.addItem(b);b.tags.on("add",this._onTagAdd,this);b.tags.on("remove",this._onTagRemove,this);this.fire("add",b);this.fire("add:"+b.id,b);c&&this.fire("add:url:"+c,b);b.preload&&this.load(b)},remove:function(b){var a=this._cache[b.id],c=b.file?b.file.url:null;if(void 0!==a){this._assets.splice(a,1);delete this._cache[b.id];this._names={};this._urls=[];for(var a=0,d=this._assets.length;a<d;a++){var e=this._assets[a];this._cache[e.id]=a;
|
|
this._names[e.name]||(this._names[e.name]=[]);this._names[e.name].push(a);e.file&&(this._urls[e.file.url]=a)}this._tags.removeItem(b);b.tags.off("add",this._onTagAdd,this);b.tags.off("remove",this._onTagRemove,this);b.fire("remove",b);this.fire("remove",b);this.fire("remove:"+b.id,b);c&&this.fire("remove:url:"+c,b);return!0}return!1},get:function(b){return this._assets[this._cache[b]]},getByUrl:function(b){return this._assets[this._urls[b]]},load:function(b){if(!b.loading){var a=this;if(b.loaded)"cubemap"===
|
|
b.type&&a._loader.patch(b,this);else{var c=!!b.file,d=b.getPreferredFile(),e=function(){var c=b.getFileUrl();b.loading=!0;a._loader.load(c,b.type,function(c,e,f){b.loaded=!0;b.loading=!1;c?(a.fire("error",c,b),a.fire("error:"+b.id,c,b),b.fire("error",c,b)):(e instanceof Array?b.resources=e:b.resource=e,pc.script.legacy||"script"!==b.type||(c=a._loader.getHandler("script"),c._cache[b.id]&&c._cache[b.id].parentNode===document.head&&document.head.removeChild(c._cache[b.id]),c._cache[b.id]=f),a._loader.patch(b,
|
|
a),a.fire("load",b),a.fire("load:"+b.id,b),d&&d.url&&a.fire("load:url:"+d.url,b),b.fire("load",b))},b)},g=function(){var c=a._loader.open(b.type,b.data);c instanceof Array?b.resources=c:b.resource=c;b.loaded=!0;a._loader.patch(b,a);a.fire("load",b);a.fire("load:"+b.id,b);d&&d.url&&a.fire("load:url:"+d.url,b);b.fire("load",b)};if(d&&"cubemap"===b.type){var c=!1,l=b.getFileUrl();this._loader.load(l,"texture",function(c,d){c?(a.fire("error",c,b),a.fire("error:"+b.id,c,b),b.fire("error",c,b)):(a._loader.patch({resource:d,
|
|
type:"texture",data:b.data},a),b._dds=d,g())})}d?c&&(this.fire("load:start",b),this.fire("load:"+b.id+":start",b),e()):g()}}},loadFromUrl:function(b,a,c){var d=pc.path.getBasename(b),e={url:b},g={};b=this.getByUrl(b);b||(b=new pc.Asset(d,a,e,g),this.add(b));"model"===a?this._loadModel(b,c):(b.once("load",function(a){c(null,a)}),b.once("error",function(a){c(a)}),this.load(b))},_loadModel:function(b,a){var c=this,d=b.getFileUrl(),e=pc.path.getDirectory(d),g=pc.path.getBasename(d),l=function(d){b.once("load",
|
|
function(b){a(null,b)});b.once("error",function(b){a(b)});c.load(d)};".json"===pc.path.getExtension(d)?(d=pc.path.join(e,g.replace(".json",".mapping.json")),this._loader.load(d,"json",function(a,d){a?(b.data={mapping:[]},l(b)):c._loadMaterials(e,d,function(a,c){b.data=d;l(b)})})):l(b)},_loadMaterials:function(b,a,c){var d=this,e,g=a.mapping.length,l=[],h=function(a,b){d._loadTextures(b,function(a,d){c(null,b)})};0===g&&c(null,l);var p=function(a,b){l.push(b);g--;0===g&&h(null,l)};for(e=0;e<a.mapping.length;e++){var k=
|
|
a.mapping[e].path;k?(k=pc.path.join(b,k),d.loadFromUrl(k,"material",p)):g--}},_loadTextures:function(b,a){var c,d={},e=[],g=[],l=0;for(c=0;c<b.length;c++){var h=b[c].data;if("path"!==h.mappingFormat)console.warn("Skipping: "+b[c].name+', material files must be mappingFormat: "path" to be loaded from URL');else for(var p=b[c].getFileUrl(),p=pc.path.getDirectory(p),k,n=0;n<pc.StandardMaterial.TEXTURE_PARAMETERS.length;n++)k=pc.StandardMaterial.TEXTURE_PARAMETERS[n],h[k]&&(k=pc.path.join(p,h[k]),d[k]||
|
|
(d[k]=!0,e.push(k),l++))}if(l)for(d=function(b,c){g.push(c);l--;b&&console.error(b);0===l&&a(null,g)},c=0;c<e.length;c++)this.loadFromUrl(e[c],"texture",d);else a(null,g)},findAll:function(b,a){var c=this,d=this._names[b];return d?(d=d.map(function(a){return c._assets[a]}),a?d.filter(function(b){return b.type===a}):d):[]},_onTagAdd:function(b,a){this._tags.add(b,a)},_onTagRemove:function(b,a){this._tags.remove(b,a)},findByTag:function(){return this._tags.find(arguments)},filter:function(b){for(var a=
|
|
[],c=0,d=this._assets.length;c<d;c++)b(this._assets[c])&&a.push(this._assets[c]);return a},find:function(b,a){var c=this.findAll(b,a);return c?c[0]:null},getAssetById:function(b){console.warn("DEPRECATED: getAssetById() use get() instead");return this.get(b)}});return{AssetRegistry:e}}());Object.assign(pc,function(){var e=function(b,a,c,d,e){this.propertyName=b;this.parent=a;this._scope=e;this._registry=c;this.asset=this.url=this.id=null;this._onAssetLoad=d.load;this._onAssetAdd=d.add;this._onAssetRemove=d.remove};e.prototype._bind=function(){if(this.id){if(this._onAssetLoad)this._registry.on("load:"+this.id,this._onLoad,this);if(this._onAssetAdd)this._registry.once("add:"+this.id,this._onAdd,this);if(this._onAssetRemove)this._registry.on("remove:"+this.id,this._onRemove,this)}if(this.url){if(this._onAssetLoad)this._registry.on("load:url:"+
|
|
this.url,this._onLoad,this);if(this._onAssetAdd)this._registry.once("add:url:"+this.url,this._onAdd,this);if(this._onAssetRemove)this._registry.on("remove:url:"+this.url,this._onRemove,this)}};e.prototype._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.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.prototype._onLoad=function(b){this._onAssetLoad.call(this._scope,this.propertyName,this.parent,b)};e.prototype._onAdd=function(b){this._onAssetAdd.call(this._scope,this.propertyName,this.parent,b)};e.prototype._onRemove=function(b){this._onAssetRemove.call(this._scope,this.propertyName,this.parent,b)};Object.defineProperty(e.prototype,
|
|
"id",{get:function(){return this._id},set:function(b){if(this.url)throw Error("Can't set id and url");this._unbind();this._id=b;this.asset=this._registry.get(this._id);this._bind()}});Object.defineProperty(e.prototype,"url",{get:function(){return this._url},set:function(b){if(this.id)throw Error("Can't set id and url");this._unbind();this._url=b;this.asset=this._registry.getByUrl(this._url);this._bind()}});return{AssetReference:e}}());Object.assign(pc,function(){return{inherits:function(e,b){var a=function(){},c=function(a,c,g,l,h,p,k,n){b.call(this,a,c,g,l,h,p,k,n);e.call(this,a,c,g,l,h,p,k,n)};c._super=b.prototype;a.prototype=b.prototype;c.prototype=new a;return c}}}());pc.anim={Animation:pc.Animation,Key:pc.Key,Node:pc.Node,Skeleton:pc.Skeleton};
|
|
pc.asset={ASSET_ANIMATION:"animation",ASSET_AUDIO:"audio",ASSET_IMAGE:"image",ASSET_JSON:"json",ASSET_MODEL:"model",ASSET_MATERIAL:"material",ASSET_TEXT:"text",ASSET_TEXTURE:"texture",ASSET_CUBEMAP:"cubemap",ASSET_SCRIPT:"script"};pc.audio={AudioManager:pc.SoundManager,Channel:pc.Channel,Channel3d:pc.Channel3d,Listener:pc.Listener,Sound:pc.Sound};
|
|
pc.fw={Application:pc.Application,Component:pc.Component,ComponentData:pc.ComponentData,ComponentSystem:pc.ComponentSystem,Entity:pc.Entity,FillMode:{NONE:pc.FILLMODE_NONE,FILL_WINDOW:pc.FILLMODE_FILL_WINDOW,KEEP_ASPECT:pc.FILLMODE_KEEP_ASPECT},ResolutionMode:{AUTO:pc.RESOLUTION_AUTO,FIXED:pc.RESOLUTION_FIXED}};
|
|
Object.assign(pc.gfx,{drawQuadWithShader:pc.drawQuadWithShader,programlib:pc.programlib,shaderChunks:pc.shaderChunks,ContextCreationError:pc.ContextCreationError,Device:pc.GraphicsDevice,IndexBuffer:pc.IndexBuffer,ProgramLibrary:pc.ProgramLibrary,RenderTarget:pc.RenderTarget,ScopeId:pc.ScopeId,Shader:pc.Shader,ShaderInput:pc.ShaderInput,Texture:pc.Texture,UnsupportedBrowserError:pc.UnsupportedBrowserError,VertexBuffer:pc.VertexBuffer,VertexFormat:pc.VertexFormat,VertexIterator:pc.VertexIterator});
|
|
(function(){function e(a){this.name="UnsupportedBrowserError";this.message=a||""}function b(a){this.name="ContextCreationError";this.message=a||""}e.prototype=Error.prototype;b.prototype=Error.prototype;pc.ContextCreationError=b;pc.UnsupportedBrowserError=e})();
|
|
Object.assign(pc.input,{getTouchTargetCoords:pc.getTouchTargetCoords,Controller:pc.Controller,GamePads:pc.GamePads,Keyboard:pc.Keyboard,KeyboardEvent:pc.KeyboardEvent,Mouse:pc.Mouse,MouseEvent:pc.MouseEvent,Touch:pc.Touch,TouchDevice:pc.TouchDevice,TouchEvent:pc.TouchEvent});pc.math.INV_LOG2=Math.LOG2E;pc.math.intToBytes=pc.math.intToBytes32;pc.math.bytesToInt=pc.math.bytesToInt32;
|
|
pc.posteffect={createFullscreenQuad:pc.createFullscreenQuad,drawFullscreenQuad:pc.drawFullscreenQuad,PostEffect:pc.PostEffect,PostEffectQueue:pc.PostEffectQueue};
|
|
Object.assign(pc.scene,{partitionSkin:pc.partitionSkin,procedural:{calculateTangents:pc.calculateTangents,createMesh:pc.createMesh,createTorus:pc.createTorus,createCylinder:pc.createCylinder,createCapsule:pc.createCapsule,createCone:pc.createCone,createSphere:pc.createSphere,createPlane:pc.createPlane,createBox:pc.createBox},BasicMaterial:pc.BasicMaterial,DepthMaterial:pc.DepthMaterial,ForwardRenderer:pc.ForwardRenderer,GraphNode:pc.GraphNode,Material:pc.Material,Command:pc.Command,Mesh:pc.Mesh,MeshInstance:pc.MeshInstance,
|
|
Model:pc.Model,ParticleEmitter:pc.ParticleEmitter,PhongMaterial:pc.StandardMaterial,Picker:pc.Picker,PickMaterial:pc.PickMaterial,Projection:{ORTHOGRAPHIC:pc.PROJECTION_ORTHOGRAPHIC,PERSPECTIVE:pc.PROJECTION_PERSPECTIVE},Scene:pc.Scene,Skin:pc.Skin,SkinInstance:pc.SkinInstance});pc.shape={Aabb:pc.BoundingBox,Sphere:pc.BoundingSphere,Plane:pc.Plane};pc.time={now:pc.now,Timer:pc.Timer};pc.PhongMaterial=pc.StandardMaterial;pc.BoundingSphere.prototype.intersectRay=pc.BoundingSphere.prototype.intersectsRay;
|
|
pc.ELEMENTTYPE_INT8=pc.TYPE_INT8;pc.ELEMENTTYPE_UINT8=pc.TYPE_UINT8;pc.ELEMENTTYPE_INT16=pc.TYPE_INT16;pc.ELEMENTTYPE_UINT16=pc.TYPE_UINT16;pc.ELEMENTTYPE_INT32=pc.TYPE_INT32;pc.ELEMENTTYPE_UINT32=pc.TYPE_UINT32;pc.ELEMENTTYPE_FLOAT32=pc.TYPE_FLOAT32;Object.defineProperty(pc.shaderChunks,"transformSkinnedVS",{get:function(){return"#define SKIN\n"+pc.shaderChunks.transformVS}});
|
|
Object.defineProperty(pc.Vec2.prototype,"data",{get:function(){this._data||(this._data=new Float32Array(2));this._data[0]=this.x;this._data[1]=this.y;return this._data}});Object.defineProperty(pc.Vec3.prototype,"data",{get:function(){this._data||(this._data=new Float32Array(3));this._data[0]=this.x;this._data[1]=this.y;this._data[2]=this.z;return this._data}});
|
|
Object.defineProperty(pc.Vec4.prototype,"data",{get:function(){this._data||(this._data=new Float32Array(4));this._data[0]=this.x;this._data[1]=this.y;this._data[2]=this.z;this._data[3]=this.w;return this._data}});Object.defineProperty(pc.Color.prototype,"data",{get:function(){this._data||(this._data=new Float32Array(4));this._data[0]=this.r;this._data[1]=this.g;this._data[2]=this.b;this._data[3]=this.a;return this._data}});
|
|
Object.defineProperty(pc.Color.prototype,"data3",{get:function(){this._data3||(this._data3=new Float32Array(3));this._data3[0]=this.r;this._data3[1]=this.g;this._data3[2]=this.b;return this._data3}});pc.Material.prototype.getName=function(){return this.name};pc.Material.prototype.setName=function(e){this.name=e};pc.Material.prototype.getShader=function(){return this.shader};pc.Material.prototype.setShader=function(e){this.shader=e};
|
|
pc.GraphNode.prototype._dirtify=function(e){e?this._dirtifyLocal():this._dirtifyWorld()};Object.assign(pc.Application.prototype,function(){var e=new pc.GraphNode,b=new pc.GraphNode,a=[],c=!1,d=function(a){this.lineVertexFormat=new pc.VertexFormat(a,[{semantic:pc.SEMANTIC_POSITION,components:3,type:pc.TYPE_FLOAT32},{semantic:pc.SEMANTIC_COLOR,components:4,type:pc.TYPE_UINT8,normalize:!0}]);this.lineBatches=[];this.layers=[];this.layerToBatch={};this.cubeWorldPos=this.cubeLocalPos=this.quadMesh=null;this.identityGraphNode=new pc.GraphNode};d.prototype.addLayer=function(a){0>this.layers.indexOf(a)&&
|
|
this.layers.push(a)};d.prototype.getLayerIdx=function(a){return this.layerToBatch[a.id]};d.prototype.addLayerIdx=function(a,b){this.layerToBatch[b.id]=a};var f=function(){this.numLinesAllocated=128;this.mesh=this.vbRam=this.vb=null;this.linesUsed=0;this.layer=this.meshInstance=this.material=null};Object.assign(f.prototype,{init:function(a,c,d,e){this.mesh||(this.mesh=new pc.Mesh,this.mesh.primitive[0].type=pc.PRIMITIVE_LINES,this.mesh.primitive[0].base=0,this.mesh.primitive[0].indexed=!1,this.material=
|
|
new pc.BasicMaterial,this.material.vertexColors=!0,this.material.blend=!0,this.material.blendType=pc.BLEND_NORMAL,this.material.update());for(this.layer=d;this.linesUsed+e>this.numLinesAllocated;)this.vb&&(this.vb.destroy(),this.vb=null),this.numLinesAllocated*=2;this.vertexFormat=c;this.vb||(this.vb=new pc.VertexBuffer(a,c,2*this.numLinesAllocated,pc.BUFFER_DYNAMIC),this.mesh.vertexBuffer=this.vb,this.vbRam=new DataView(this.vb.lock()),this.meshInstance||(b.worldTransform=pc.Mat4.IDENTITY,b._dirtyWorld=
|
|
b._dirtyNormal=!1,this.meshInstance=new pc.MeshInstance(b,this.mesh,this.material),this.meshInstance.cull=!1))},addLines:function(a,b){for(var c=!!b.length,d=2*this.linesUsed*this.vertexFormat.size,e,f=0;f<a.length;f++)this.vbRam.setFloat32(d,a[f].x,!0),d+=4,this.vbRam.setFloat32(d,a[f].y,!0),d+=4,this.vbRam.setFloat32(d,a[f].z,!0),d+=4,e=c?b[f]:b,this.vbRam.setUint8(d,255*e.r),d+=1,this.vbRam.setUint8(d,255*e.g),d+=1,this.vbRam.setUint8(d,255*e.b),d+=1,this.vbRam.setUint8(d,255*e.a),d+=1;this.linesUsed+=
|
|
a.length/2},finalize:function(){0<this.linesUsed&&(this.vb.setData(this.vbRam.buffer),this.mesh.primitive[0].count=2*this.linesUsed,a[0]=this.meshInstance,this.layer.addMeshInstances(a,!0),this.linesUsed=0)}});return{renderMeshInstance:function(b,c){c||(c={layer:this.scene.layers.getLayerById(pc.LAYERID_IMMEDIATE)});this._initImmediate();this._immediateData.addLayer(c.layer);a[0]=b;c.layer.addMeshInstances(a,!0)},renderMesh:function(b,c,d,f){f||(f={layer:this.scene.layers.getLayerById(pc.LAYERID_IMMEDIATE)});
|
|
this._initImmediate();e.worldTransform=d;e._dirtyWorld=e._dirtyNormal=!1;b=new pc.MeshInstance(e,b,c);b.cull=!1;f.mask&&(b.mask=f.mask);this._immediateData.addLayer(f.layer);a[0]=b;f.layer.addMeshInstances(a,!0)},renderLine:function(a,b,d,e,f){var g=d;e instanceof pc.Color?(g=e,"number"===typeof f?(c||(console.warn("lineBatch argument is deprecated for renderLine. Use options.layer instead"),c=!0),e=f===pc.LINEBATCH_OVERLAY?{layer:this.scene.layers.getLayerById(pc.LAYERID_IMMEDIATE),depthTest:!1}:
|
|
{layer:this.scene.layers.getLayerById(pc.LAYERID_IMMEDIATE),depthTest:!0}):e=f):"number"===typeof e?(c||(console.warn("lineBatch argument is deprecated for renderLine. Use options.layer instead"),c=!0),g=d,e=e===pc.LINEBATCH_OVERLAY?{layer:this.scene.layers.getLayerById(pc.LAYERID_IMMEDIATE),depthTest:!1}:{layer:this.scene.layers.getLayerById(pc.LAYERID_IMMEDIATE),depthTest:!0}):e=e?e:{layer:this.scene.layers.getLayerById(pc.LAYERID_IMMEDIATE),depthTest:!0};this._addLines([a,b],[d,g],e)},renderLines:function(a,
|
|
b,d){d?"number"===typeof d&&(c||(console.warn("lineBatch argument is deprecated for renderLine. Use options.layer instead"),c=!0),d=d===pc.LINEBATCH_OVERLAY?{layer:this.scene.layers.getLayerById(pc.LAYERID_IMMEDIATE),depthTest:!1}:{layer:this.scene.layers.getLayerById(pc.LAYERID_IMMEDIATE),depthTest:!0}):d={layer:this.scene.layers.getLayerById(pc.LAYERID_IMMEDIATE),depthTest:!0};b.length&&a.length!==b.length?pc.log.error("renderLines: position/color arrays have different lengths"):0!==a.length%2?
|
|
pc.log.error("renderLines: array length is not divisible by 2"):this._addLines(a,b,d)},renderQuad:function(b,c,d){d||(d={layer:this.scene.layers.getLayerById(pc.LAYERID_IMMEDIATE)});this._initImmediate();if(!this._immediateData.quadMesh){var f=new pc.VertexFormat(this.graphicsDevice,[{semantic:pc.SEMANTIC_POSITION,components:3,type:pc.TYPE_FLOAT32}]),f=new pc.VertexBuffer(this.graphicsDevice,f,4),g=new pc.VertexIterator(f);g.element[pc.SEMANTIC_POSITION].set(-.5,-.5,0);g.next();g.element[pc.SEMANTIC_POSITION].set(.5,
|
|
-.5,0);g.next();g.element[pc.SEMANTIC_POSITION].set(-.5,.5,0);g.next();g.element[pc.SEMANTIC_POSITION].set(.5,.5,0);g.end();this._immediateData.quadMesh=new pc.Mesh;this._immediateData.quadMesh.vertexBuffer=f;this._immediateData.quadMesh.primitive[0].type=pc.PRIMITIVE_TRISTRIP;this._immediateData.quadMesh.primitive[0].base=0;this._immediateData.quadMesh.primitive[0].count=4;this._immediateData.quadMesh.primitive[0].indexed=!1}e.worldTransform=b;e._dirtyWorld=e._dirtyNormal=!1;b=new pc.MeshInstance(e,
|
|
this._immediateData.quadMesh,c);b.cull=!1;a[0]=b;this._immediateData.addLayer(d.layer);d.layer.addMeshInstances(a,!0)},renderWireCube:function(a,b,c){var d;this._initImmediate();this._immediateData.cubeLocalPos||(this._immediateData.cubeLocalPos=[new pc.Vec3(-.5,-.5,-.5),new pc.Vec3(-.5,.5,-.5),new pc.Vec3(.5,.5,-.5),new pc.Vec3(.5,-.5,-.5),new pc.Vec3(-.5,-.5,.5),new pc.Vec3(-.5,.5,.5),new pc.Vec3(.5,.5,.5),new pc.Vec3(.5,-.5,.5)],this._immediateData.cubeWorldPos=[new pc.Vec3,new pc.Vec3,new pc.Vec3,
|
|
new pc.Vec3,new pc.Vec3,new pc.Vec3,new pc.Vec3,new pc.Vec3]);var e=this._immediateData.cubeLocalPos,f=this._immediateData.cubeWorldPos;for(d=0;8>d;d++)a.transformPoint(e[d],f[d]);this.renderLines([f[0],f[1],f[1],f[2],f[2],f[3],f[3],f[0],f[4],f[5],f[5],f[6],f[6],f[7],f[7],f[4],f[0],f[4],f[1],f[5],f[2],f[6],f[3],f[7]],b,c)},_addLines:function(a,b,c){void 0===c.layer&&(c.layer=this.scene.layers.getLayerById(pc.LAYERID_IMMEDIATE));void 0===c.depthTest&&(c.depthTest=!0);this._initImmediate();var d=c.layer;
|
|
this._immediateData.addLayer(d);var e=this._immediateData.getLayerIdx(d);void 0===e?(e=new f,e.init(this.graphicsDevice,this._immediateData.lineVertexFormat,d,a.length/2),e.material.depthTest=c.depthTest,c.mask&&(e.meshInstance.mask=c.mask),e=this._immediateData.lineBatches.push(e)-1,this._immediateData.addLayerIdx(e,d)):(this._immediateData.lineBatches[e].init(this.graphicsDevice,this._immediateData.lineVertexFormat,d,a.length/2),this._immediateData.lineBatches[e].material.depthTest=c.depthTest,
|
|
c.mask&&(this._immediateData.lineBatches[e].meshInstance.mask=c.mask));this._immediateData.lineBatches[e].addLines(a,b)},_initImmediate:function(){this._immediateData||(this._immediateData=new d(this.graphicsDevice),this.on("prerender",this._preRenderImmediate,this),this.on("postrender",this._postRenderImmediate,this))},_preRenderImmediate:function(){for(var a=0;a<this._immediateData.lineBatches.length;a++)this._immediateData.lineBatches[a]&&this._immediateData.lineBatches[a].finalize()},_postRenderImmediate:function(){for(var a=
|
|
0;a<this._immediateData.layers.length;a++)this._immediateData.layers[a].clearMeshInstances(!0);this._immediateData.layers.length=0}}}());Object.assign(pc,function(){function e(a,b,c,d){if(a.enabled){var f;if(a.model&&a.model.model&&a.model.enabled&&(d&&d.push(a),a.model.lightmapped&&b)){var g=!0,h=a.model.model.meshInstances;for(f=0;f<h.length;f++)if(!h[f].mesh.vertexBuffer.format.hasUv1){g=!1;break}if(g){var k,l=[];for(f=0;f<h.length;f++){k=!1;for(g=0;g<h.length;g++)f!==g&&h[f].mesh===h[g].mesh&&(k=!0);k?(b.push(a),c.push([h[f]])):l.push(h[f])}0<l.length&&(b.push(a),c.push(l))}}for(f=0;f<a._children.length;f++)e(a._children[f],b,
|
|
c,d)}}var b=[],a=[],c,d=new pc.Vec3,f=new pc.BoundingBox,g=new pc.BoundingBox,l={},h=["texture_lightMap","texture_dirLightMap"],p=[],k=function(a,b,c,d,e){this.device=a;this.root=b;this.scene=c;this.renderer=d;this.assets=e};Object.assign(k.prototype,{destroy:function(){this.assets=this.renderer=this.scene=this.root=this.device=null},calculateLightmapSize:function(a){var b,c=this.scene.lightmapSizeMultiplier||16,e=1,f=1,g=1,h=1;a.model.asset?(b=this.assets.get(a.model.asset).data,b.area&&(e=b.area.x,
|
|
f=b.area.y,g=b.area.z,h=b.area.uv)):a.model._area&&(b=a.model,b._area&&(e=b._area.x,f=b._area.y,g=b._area.z,h=b._area.uv));b=a.model.lightmapSizeMultiplier||1;e*=b;f*=b;g*=b;d.copy(a.localScale);for(a=a._parent;a;)d.mul(a.localScale),a=a._parent;d.x=Math.abs(d.x);d.y=Math.abs(d.y);d.z=Math.abs(d.z);e=e*d.y*d.z+f*d.x*d.z+g*d.x*d.y;e=Math.sqrt(e/h);return Math.min(pc.math.nextPowerOfTwo(e*c),this.scene.lightmapMaxResolution||2048)},bake:function(k,q){var m,n,t=this.device,u=this.scene,x=1;void 0===
|
|
q&&(q=pc.BAKE_COLORDIR);q===pc.BAKE_COLORDIR&&(x=2);var v,w=[],y=[];if(k){var D;for(m=a.length-1;0<=m;m--)for(n=0;n<k.length;n++)if(a[m]===k[n]){for(D=0;D<b[m].length;D++)b[m][D].destroy();b.splice(m,1);a.splice(m,1)}D=[];for(m=0;m<k.length;m++)e(k[m],D,y);k=D;e(this.root,null,null,w)}else{for(m=0;m<b.length;m++)for(n=0;n<b[m].length;n++)b[m][n].destroy();b=[];a=[];k=[];e(this.root,k,y,w)}if(0===k.length)t.fire("lightmapper:end",{timestamp:pc.now(),target:this});else{D=!1;u._needsStaticPrepare&&(u._needsStaticPrepare=
|
|
!1,D=!0);var B=[],z=[[],[]],A={},F,I;n=new pc.Texture(this.device,{width:4,height:4,format:pc.PIXELFORMAT_R8_G8_B8_A8,rgbm:!0});n.name="lightmap";for(m=0;m<k.length;m++){F=this.calculateLightmapSize(k[m]);B.push(F);for(v=0;v<x;v++)I=new pc.Texture(t,{width:F,height:F,format:pc.PIXELFORMAT_R8_G8_B8_A8,mipmaps:!1,rgbm:0===v,minFilter:pc.FILTER_NEAREST,magFilter:pc.FILTER_NEAREST}),I.name="lightmap",z[v].push(I);if(!A[F]){var G=new pc.Texture(t,{width:F,height:F,format:pc.PIXELFORMAT_R8_G8_B8_A8,mipmaps:!1,
|
|
rgbm:!0,minFilter:pc.FILTER_NEAREST,magFilter:pc.FILTER_NEAREST});G.name="lightmap";G=new pc.RenderTarget(t,G,{depth:!1});A[F]=G}}var H=u.layers;H._update();B=[];F=[];var G=[],C=[],E=H._lights;for(m=0;m<E.length;m++)E[m]._enabled&&(I=E[m]._mask,0!==(I&4)&&(F.push(I),G.push(E[m].shadowUpdateMode),E[m]._mask=4294967295,E[m].shadowUpdateMode=E[m]._type===pc.LIGHTTYPE_DIRECTIONAL?pc.SHADOWUPDATE_REALTIME:pc.SHADOWUPDATE_THISFRAME,B.push(E[m]),E[m].isStatic=!1)),C.push(E[m]._enabled),E[m].enabled=!1;var K=
|
|
pc.shaderChunks,N="#define UV1LAYOUT\n"+K.transformVS,X=K.bakeLmEndPS;I=K.createShaderFromCode(t,K.fullscreenQuadVS,K.dilatePS,"lmDilate");var M=t.scope.resolve("source"),U=t.scope.resolve("pixelOffset"),aa=t.scope.resolve("bakeDir"),V=new Float32Array(2),H=H._meshInstances;for(m=0;m<H.length;m++)H[m].node&&H[m].node.getWorldTransform();var H=u.fog,P=u.ambientLight.r,T=u.ambientLight.g,Y=u.ambientLight.b;u.fog=pc.FOG_NONE;u.ambientLight.set(0,0,0);c||(c=new pc.Camera,c._node=new pc.GraphNode,c.clearColor[0]=
|
|
0,c.clearColor[1]=0,c.clearColor[2]=0,c.clearColor[3]=0,c.clearDepth=1,c.clearFlags=pc.CLEARFLAG_COLOR,c.clearStencil=null,c.frustumCulling=!1);var L,Q,O,J,ba=[];ba.length=a.length;var R;for(L=0;L<w.length;L++){O=w[L].model.model.meshInstances;R=[];for(m=0;m<O.length;m++)R.push(O[m]._shaderDefs),O[m]._shaderDefs&=~(pc.SHADERDEF_LM|pc.SHADERDEF_DIRLM);for(m=0;m<a.length;m++)if(a[m]===w[L]){ba[m]=R;break}}R=[];var ca=[],S;for(L=0;L<w.length;L++)if(R[L]=w[L].model.castShadows,w[L].model.castShadows=
|
|
w[L].model.castShadowsLightmap,w[L].model.castShadowsLightmap)for(S=w[L].model.meshInstances,m=0;m<S.length;m++)S[m].visibleThisFrame=!0,ca.push(S[m]);this.renderer.updateCpuSkinMatrices(ca);this.renderer.gpuUpdate(ca);var W=[],da=[];S=[[],[]];var ea,fa,Z,ka=[];ka.length=k.length;for(v=0;v<x;v++)p[v]||(m=new pc.StandardMaterial,m.chunks.transformVS=N,0===v?(m.chunks.endPS=X,m.ambient=new pc.Color(0,0,0),m.ambientTint=!0,m.lightMap=n):(m.chunks.basePS=K.basePS+"\nuniform sampler2D texture_dirLightMap;\nuniform float bakeDir;\n",
|
|
m.chunks.endPS=K.bakeDirLmEndPS),m.chunks.outputAlphaPS="\n",m.chunks.outputAlphaOpaquePS="\n",m.chunks.outputAlphaPremulPS="\n",m.cull=pc.CULLFACE_NONE,m.forceUv1=!0,m.update(),m.updateShader(t,u),m.name="lmMaterial"+v,p[v]=m);for(L=0;L<k.length;L++){O=y[L];ka[L]=0;if(0<O.length)for(f.copy(O[0].aabb),m=0;m<O.length;m++)O[m].node.getWorldTransform(),f.add(O[m].aabb);m=new pc.BoundingBox;m.copy(f);da.push(m);for(m=0;m<O.length;m++)J=O[m],J._shaderDefs&=~(pc.SHADERDEF_LM|pc.SHADERDEF_DIRLM),J.mask=
|
|
4,J.deleteParameter("texture_lightMap"),J.deleteParameter("texture_dirLightMap"),J.setParameter("texture_lightMap",J.material.lightMap?J.material.lightMap:n),J.setParameter("texture_dirLightMap",n);for(v=0;v<x;v++)Q=z[v][L],ea=new pc.RenderTarget(t,Q,{depth:!1}),S[v].push(ea)}for(n=0;n<B.length;n++)B[n].enabled=!1;K=[[],[],[]];N=!1;for(m=0;m<B.length;m++){B[m].enabled=!0;X=!1;B[m]._cacheShadowMap=!0;B[m]._type!==pc.LIGHTTYPE_DIRECTIONAL&&(B[m]._node.getWorldTransform(),B[m].getBoundingSphere(l),g.center=
|
|
l.center,g.halfExtents.x=l.radius,g.halfExtents.y=l.radius,g.halfExtents.z=l.radius);B[m]._type===pc.LIGHTTYPE_SPOT&&(n=B[m],Z=this.renderer.getShadowCamera(t,n),Z._node.setPosition(n._node.getPosition()),Z._node.setRotation(n._node.getRotation()),Z._node.rotateLocal(-90,0,0),Z.projection=pc.PROJECTION_PERSPECTIVE,Z.nearClip=n.attenuationEnd/1E3,Z.farClip=n.attenuationEnd,Z.aspectRatio=1,Z.fov=2*n._outerConeAngle,this.renderer.updateCameraFrustum(Z));0<y.length&&this.renderer.updateShaders(y[0]);
|
|
for(L=0;L<k.length;L++){O=y[L];f=da[L];if(B[m]._type===pc.LIGHTTYPE_DIRECTIONAL)d.copy(f.center),d.y+=f.halfExtents.y,c._node.setPosition(d),c._node.setEulerAngles(-90,0,0),n=Math.max(f.halfExtents.x,f.halfExtents.z),c.projection=pc.PROJECTION_ORTHOGRAPHIC,c.nearClip=0,c.farClip=2*f.halfExtents.y,c.aspectRatio=1,c.orthoHeight=n;else if(!g.intersects(f))continue;if(B[m]._type===pc.LIGHTTYPE_SPOT){v=!1;for(n=0;n<O.length;n++)if(this.renderer._isVisible(Z,O[n])){v=!0;break}if(!v)continue}B[m]._type===
|
|
pc.LIGHTTYPE_DIRECTIONAL?(K[pc.LIGHTTYPE_DIRECTIONAL][0]=B[m],K[pc.LIGHTTYPE_POINT].length=0,K[pc.LIGHTTYPE_SPOT].length=0,!X&&B[m].castShadows&&(this.renderer.cullDirectionalShadowmap(B[m],ca,c,0),this.renderer.renderShadows(K[pc.LIGHTTYPE_DIRECTIONAL],0),X=!0)):(K[pc.LIGHTTYPE_DIRECTIONAL].length=0,B[m]._type===pc.LIGHTTYPE_POINT?(K[pc.LIGHTTYPE_POINT][0]=B[m],K[pc.LIGHTTYPE_SPOT].length=0,!X&&B[m].castShadows&&(this.renderer.cullLocalShadowmap(B[m],ca),this.renderer.renderShadows(K[pc.LIGHTTYPE_POINT]),
|
|
X=!0)):(K[pc.LIGHTTYPE_POINT].length=0,K[pc.LIGHTTYPE_SPOT][0]=B[m],!X&&B[m].castShadows&&(this.renderer.cullLocalShadowmap(B[m],ca),this.renderer.renderShadows(K[pc.LIGHTTYPE_SPOT]),X=!0)));for(n=0;n<O.length;n++)W[n]=O[n].material;for(v=0;v<x;v++){Q=z[v][L];ea=S[v][L];J=A[Q.width];fa=J.colorBuffer;0===v?N=u.updateShaders:N&&(u.updateShaders=!0);for(n=0;n<O.length;n++)O[n].material=p[v];1<x&&this.renderer.updateShaders(O);this.renderer.setCamera(c,J,!0);1===v&&aa.setValue(B[m].bakeDir?1:0);this.renderer._forwardTime=
|
|
0;this.renderer._shadowMapTime=0;this.renderer.renderForward(c,O,O.length,K,pc.SHADER_FORWARDHDR);z[v][L]=fa;S[v][L]=J;A[Q.width]=ea;for(n=0;n<O.length;n++)J=O[n],J.setParameter(h[v],fa),J._shaderDefs|=pc.SHADERDEF_LM}ka[L]++;for(n=0;n<O.length;n++)O[n].material=W[n]}B[m].enabled=!1;B[m]._cacheShadowMap=!1;B[m]._isCachedShadowMap&&B[m]._destroyShadowMap()}for(L=0;L<k.length;L++){O=y[L];Z=[];for(v=0;v<x;v++){Q=z[v][L];ea=S[v][L];J=A[Q.width];fa=J.colorBuffer;V[0]=1/Q.width;V[1]=1/Q.height;U.setValue(V);
|
|
for(m=0;4>m;m++)M.setValue(Q),pc.drawQuadWithShader(t,J,I),M.setValue(fa),pc.drawQuadWithShader(t,ea,I);for(m=0;m<O.length;m++)J=O[m],J.mask=2,O[m].setParameter(h[v],Q),1===v&&(O[m]._shaderDefs|=pc.SHADERDEF_DIRLM);Z[v]=Q;v===x-1&&ea.destroy()}b.push(Z);a.push(k[L])}for(var la in A)A.hasOwnProperty(la)&&(A[la].colorBuffer.destroy(),A[la].destroy());for(m=0;m<b.length;m++)for(n=0;n<b[m].length;n++)I=b[m][n],I.minFilter=pc.FILTER_LINEAR,I.magFilter=pc.FILTER_LINEAR;for(L=0;L<w.length;L++)w[L].model.castShadows=
|
|
R[L];for(m=0;m<ba.length;m++)if(ba[m])for(O=a[m].model.model.meshInstances,n=0;n<O.length;n++)O[n]._shaderDefs|=ba[m][n]&(pc.SHADERDEF_LM|pc.SHADERDEF_DIRLM);for(m=0;m<B.length;m++)B[m]._mask=F[m],B[m].shadowUpdateMode=G[m];for(m=0;m<E.length;m++)E[m].enabled=C[m];u.fog=H;u.ambientLight.set(P,T,Y);D&&(u._needsStaticPrepare=!0)}}});return{Lightmapper:k}}());Object.assign(pc,function(){function e(a,b){if(a&&!b||!a&&b)return!1;a=a.data;b=b.data;if(a===b)return!0;if(a instanceof Float32Array&&b instanceof Float32Array){if(a.length!==b.length)return!1;for(var c=0;c<a.length;c++)if(a[c]!==b[c])return!1;return!0}return!1}function b(a,b){for(var c in a)if(a.hasOwnProperty(c)&&!e(a[c],b[c]))return!1;for(c in b)if(b.hasOwnProperty(c)&&!e(b[c],a[c]))return!1;return!0}function a(a,b){var c;for(c=0;c<a.length;c++)if(0>b.indexOf(a[c]))return!1;for(c=0;c<b.length;c++)if(0>
|
|
a.indexOf(b[c]))return!1;return!0}var c=function(a,b,c,d,e){this.dynamic=c;this.maxAabbSize=d;this.id=a;this.name=b;this.layers=void 0===e?[pc.LAYERID_WORLD]:e;this._ui=!1;this._obj={model:[],element:[],sprite:[]}};c.MODEL="model";c.ELEMENT="element";c.SPRITE="sprite";var d=function(a,b,c){this.device=a;this.rootNode=c;this._dirty=!0;this.bones=b;b=b.length;a.supportsBoneTextures?(b=256<b?64:64<b?32:16<b?16:8,this.boneTexture=new pc.Texture(a,{width:b,height:b,format:pc.PIXELFORMAT_RGBA32F,mipmaps:!1,
|
|
minFilter:pc.FILTER_NEAREST,magFilter:pc.FILTER_NEAREST}),this.boneTexture.name="batching",this.matrixPalette=this.boneTexture.lock()):this.matrixPalette=new Float32Array(16*b)};Object.assign(d.prototype,{updateMatrices:function(a){},updateMatrixPalette:function(){for(var a,b=this.matrixPalette,c,d=this.bones.length-1;0<=d;d--)a=this.bones[d].getWorldTransform().data,c=16*d,b[c]=a[0],b[c+1]=a[1],b[c+2]=a[2],b[c+3]=a[3],b[c+4]=a[4],b[c+5]=a[5],b[c+6]=a[6],b[c+7]=a[7],b[c+8]=a[8],b[c+9]=a[9],b[c+10]=
|
|
a[10],b[c+11]=a[11],b[c+12]=a[12],b[c+13]=a[13],b[c+14]=a[14],b[c+15]=a[15];this.device.supportsBoneTextures&&(this.boneTexture.lock(),this.boneTexture.unlock())}});var f=function(a,b,c){this.device=a;this.rootNode=b;this.scene=c;this._init=!1;this._batchGroups={};this._batchGroupCounter=0;this._batchList=[];this._dirtyGroups=[]};f.prototype.destroyManager=function(){this.scene=this.rootNode=this.device=null;this._batchGroups={};this._batchList=[];this._dirtyGroups=[]};f.prototype.addGroup=function(a,
|
|
b,c,d,e){void 0===d&&(d=this._batchGroupCounter,this._batchGroupCounter++);if(!this._batchGroups[d])return this._batchGroups[d]=a=new pc.BatchGroup(d,a,b,c,e)};f.prototype.removeGroup=function(a){if(this._batchGroups[a]){for(var b=[],c=0;c<this._batchList.length;c++)this._batchList[c].batchGroupId!==a?b.push(this._batchList[c]):this.destroy(this._batchList[c]);this._batchList=b;this._removeModelsFromBatchGroup(this.rootNode,a);delete this._batchGroups[a]}};f.prototype.markGroupDirty=function(a){0>
|
|
this._dirtyGroups.indexOf(a)&&this._dirtyGroups.push(a)};f.prototype.getGroupByName=function(a){var b=this._batchGroups,c;for(c in b)if(b.hasOwnProperty(c)&&b[c].name===a)return b[c];return null};f.prototype.getBatches=function(a){for(var b=[],c=this._batchList.length,d=0;d<c;d++){var e=this._batchList[d];e.batchGroupId===a&&b.push(e)}return b};f.prototype._removeModelsFromBatchGroup=function(a,b){if(a.enabled){a.model&&a.model.batchGroupId===b&&(a.model.batchGroupId=-1);a.element&&a.element.batchGroupId===
|
|
b&&(a.element.batchGroupId=-1);a.sprite&&a.sprite.batchGroupId===b&&(a.sprite.batchGroupId=-1);for(var c=0;c<a._children.length;c++)this._removeModelsFromBatchGroup(a._children[c],b)}};f.prototype.insert=function(a,b,c){var d=this._batchGroups[b];d&&0>d._obj[a].indexOf(c)&&(d._obj[a].push(c),this.markGroupDirty(b))};f.prototype.remove=function(a,b,c){var d=this._batchGroups[b];d&&(c=d._obj[a].indexOf(c),0<=c&&(d._obj[a].splice(c,1),this.markGroupDirty(b)))};f.prototype._extractModel=function(a,b,
|
|
c,d){if(!a.model||!a.model.model)return b;if(a.model.isStatic){d=this.scene.drawCalls;var e=a.model.meshInstances;for(c=0;c<d.length;c++)d[c]._staticSource&&(0>e.indexOf(d[c]._staticSource)||b.push(d[c]));for(c=0;c<e.length;c++)0<=d.indexOf(e[c])&&b.push(e[c])}else b=d[a.model.batchGroupId]=b.concat(a.model.meshInstances);a.model.removeModelFromLayers(a.model.model);return b};f.prototype._extractElement=function(a,b,c){if(a.element){var d=!1;a.element._text&&0<a.element._text._model.meshInstances.length?
|
|
(b.push(a.element._text._model.meshInstances[0]),a.element.removeModelFromLayers(a.element._text._model),d=!0):a.element._image&&(b.push(a.element._image._renderable.meshInstance),a.element.removeModelFromLayers(a.element._image._renderable.model),a.element._image._renderable.unmaskMeshInstance&&(b.push(a.element._image._renderable.unmaskMeshInstance),a.element._image._renderable.unmaskMeshInstance.stencilFront&&a.element._image._renderable.unmaskMeshInstance.stencilBack||(a.element._dirtifyMask(),
|
|
a.element._onPrerender())),d=!0);d&&(c._ui=!0)}};f.prototype._collectAndRemoveModels=function(a,b){for(var c,d,e,f=0;f<b.length;f++)if(c=b[f],d=this._batchGroups[c]){(e=a[c])||(e=a[c]=[]);for(c=0;c<d._obj.model.length;c++)e=this._extractModel(d._obj.model[c],e,d,a);for(c=0;c<d._obj.element.length;c++)this._extractElement(d._obj.element[c],e,d);for(var g=0;g<d._obj.sprite.length;g++)c=d._obj.sprite[g],c.sprite&&c.sprite._meshInstance&&(e.push(c.sprite._meshInstance),this.scene.removeModel(c.sprite._model),
|
|
c.sprite._batchGroup=d)}};f.prototype.generate=function(a){var b,c,d={};a||(a=Object.keys(this._batchGroups));c=[];for(b=0;b<this._batchList.length;b++)0>a.indexOf(this._batchList[b].batchGroupId)?c.push(this._batchList[b]):this.destroy(this._batchList[b]);this._batchList=c;this._collectAndRemoveModels(d,a);if(a===this._dirtyGroups)this._dirtyGroups.length=0;else{c=[];for(b=0;b<this._dirtyGroups.length;b++)0>a.indexOf(this._dirtyGroups[b])&&c.push(this._dirtyGroups[b]);this._dirtyGroups=c}var e,f,
|
|
g;for(g in d)if(d.hasOwnProperty(g)&&(b=d[g],a=this._batchGroups[g]))for(e=this.prepare(b,a.dynamic,a.maxAabbSize,a._ui),b=0;b<e.length;b++)if(f=this.create(e[b],a.dynamic,parseInt(g,10)))for(c=0;c<a.layers.length;c++)this.scene.layers.getLayerById(a.layers[c]).addMeshInstances(f.model.meshInstances)};f.prototype.prepare=function(c,d,e,f){if(0===c.length)return[];void 0===e&&(e=Number.POSITIVE_INFINITY);e*=.5;var g=this.device.supportsBoneTextures?1024:this.device.boneLimit,h,l,m,p,t,u,x,v,w=new pc.BoundingBox,
|
|
y=new pc.BoundingBox,D=null,B=[],z=0;f&&c.sort(function(a,b){return a.drawOrder-b.drawOrder});for(var A=c,F,I=f?function(a){D?D.add(a.aabb):D=a.aabb.clone();F.push(a)}:function(a){F.push(a)},G,H;0<A.length;){B[z]=[A[0]];F=[];h=A[0].material;l=A[0].layer;u=A[0]._shaderDefs;p=A[0].parameters;x=A[0].stencilFront;t=A[0]._staticLightList;m=A[0].mesh.vertexBuffer.getNumVertices();w.copy(A[0].aabb);D=null;for(c=1;c<A.length;c++){G=A[c];if(d&&B[z].length>=g){F=F.concat(A.slice(c));break}if(h!==G.material||
|
|
l!==G.layer||u!==G._shaderDefs||65535<m+G.mesh.vertexBuffer.getNumVertices())I(G);else if(y.copy(w),y.add(G.aabb),y.halfExtents.x>e||y.halfExtents.y>e||y.halfExtents.z>e)I(G);else if(!x||(H=G.stencilFront)&&x.func==H.func&&x.zpass==H.zpass)if(b(p,G.parameters)){v=G._staticLightList;if(t&&v){if(!a(t,v)){I(G);continue}}else if(t||v){I(G);continue}f&&D&&D.intersects(G.aabb)?I(G):(w.add(G.aabb),m+=G.mesh.vertexBuffer.getNumVertices(),B[z].push(G))}else I(G);else I(G)}z++;A=F}return B};f.prototype.create=
|
|
function(a,b,c){this._init||(this.transformVS="#define BONE_LIMIT "+this.device.getBoneLimit()+"\n#define DYNAMICBATCH\n"+pc.shaderChunks.transformVS,this.skinTexVS=pc.shaderChunks.skinBatchTexVS,this.skinConstVS=pc.shaderChunks.skinBatchConstVS,this.vertexFormats={},this._init=!0);var e,f,g=null,h,l,r,t,u,x,v,w,y,D=0,B=0,z=0;for(e=0;e<a.length;e++)if(a[e].visible){z++;if(!g)g=a[e].material;else if(g!==a[e].material)return;h=a[e].mesh;l=h.vertexBuffer.format.elements;r=h.vertexBuffer.numVertices;
|
|
D+=r;for(f=0;f<l.length;f++)l[f].name===pc.SEMANTIC_POSITION?t=!0:l[f].name===pc.SEMANTIC_NORMAL?u=!0:l[f].name===pc.SEMANTIC_TEXCOORD0?x=!0:l[f].name===pc.SEMANTIC_TEXCOORD1?v=!0:l[f].name===pc.SEMANTIC_TANGENT?w=!0:l[f].name===pc.SEMANTIC_COLOR&&(y=!0);B+=h.primitive[0].count}if(z&&t){c=new pc.Batch(a,b,c);this._batchList.push(c);var A=3+(u?3:0)+(x?2:0)+(v?2:0)+(w?4:0)+(y?1:0)+(b?1:0),F=u?6:3,I=(u?6:3)+(x?2:0),G=(u?6:3)+(x?2:0)+(v?2:0),H=(u?6:3)+(x?2:0)+(v?2:0)+(w?4:0),C=(u?6:3)+(x?2:0)+(v?2:0)+
|
|
(w?4:0)+(y?1:0);e=new ArrayBuffer(D*A*4);t=new Float32Array(e);var E=new Uint8Array(e),z=new pc.IndexBuffer(this.device,pc.INDEXFORMAT_UINT16,B,pc.BUFFER_STATIC),K=new Uint16Array(z.lock()),N,X,M,U=0,aa=0;M=0;var V,P,T,Y,L,Q,O,J=new pc.Vec3;for(e=0;e<a.length;e++)if(a[e].visible){h=a[e].mesh;l=h.vertexBuffer.format.elements;r=h.vertexBuffer.numVertices;f=h.vertexBuffer.format.size;N=f/4;for(f=0;f<l.length;f++)l[f].name===pc.SEMANTIC_POSITION?V=l[f].offset/4:l[f].name===pc.SEMANTIC_NORMAL?P=l[f].offset/
|
|
4:l[f].name===pc.SEMANTIC_TEXCOORD0?T=l[f].offset/4:l[f].name===pc.SEMANTIC_TEXCOORD1?Y=l[f].offset/4:l[f].name===pc.SEMANTIC_TANGENT?L=l[f].offset/4:l[f].name===pc.SEMANTIC_COLOR&&(Q=l[f].offset/4);l=new Float32Array(h.vertexBuffer.storage);X=new Uint8Array(h.vertexBuffer.storage);O=a[e].node.getWorldTransform();for(f=0;f<r;f++)J.set(l[f*N+V],l[f*N+V+1],l[f*N+V+2]),b||O.transformPoint(J,J),t[f*A+M]=J.x,t[f*A+M+1]=J.y,t[f*A+M+2]=J.z,u&&(J.set(l[f*N+P],l[f*N+P+1],l[f*N+P+2]),b||O.transformVector(J,
|
|
J),t[f*A+M+3]=J.x,t[f*A+M+3+1]=J.y,t[f*A+M+3+2]=J.z),x&&(t[f*A+M+F]=l[f*N+T],t[f*A+M+F+1]=l[f*N+T+1]),v&&(t[f*A+M+I]=l[f*N+Y],t[f*A+M+I+1]=l[f*N+Y+1]),w&&(J.set(l[f*N+L],l[f*N+L+1],l[f*N+L+2]),b||O.transformVector(J,J),t[f*A+M+G]=J.x,t[f*A+M+G+1]=J.y,t[f*A+M+G+2]=J.z,t[f*A+M+G+3]=l[f*N+L+3]),y&&(E[f*A*4+4*M+4*H]=X[f*N*4+4*Q],E[f*A*4+4*M+4*H+1]=X[f*N*4+4*Q+1],E[f*A*4+4*M+4*H+2]=X[f*N*4+4*Q+2],E[f*A*4+4*M+4*H+3]=X[f*N*4+4*Q+3]),b&&(t[f*A+C+M]=e);l=h.primitive[0].base;M=h.primitive[0].count;h=new Uint16Array(h.indexBuffer[0].storage);
|
|
for(f=0;f<M;f++)K[f+aa]=h[l+f]+U;aa+=M;U+=r;M=U*A}e=0;u&&(e|=2);x&&(e|=4);v&&(e|=8);w&&(e|=16);y&&(e|=32);b&&(e|=64);a=this.vertexFormats[e];a||(a=[],a.push({semantic:pc.SEMANTIC_POSITION,components:3,type:pc.ELEMENTTYPE_FLOAT32,normalize:!1}),u&&a.push({semantic:pc.SEMANTIC_NORMAL,components:3,type:pc.ELEMENTTYPE_FLOAT32,normalize:!1}),x&&a.push({semantic:pc.SEMANTIC_TEXCOORD0,components:2,type:pc.ELEMENTTYPE_FLOAT32,normalize:!1}),v&&a.push({semantic:pc.SEMANTIC_TEXCOORD1,components:2,type:pc.ELEMENTTYPE_FLOAT32,
|
|
normalize:!1}),w&&a.push({semantic:pc.SEMANTIC_TANGENT,components:4,type:pc.ELEMENTTYPE_FLOAT32,normalize:!1}),y&&a.push({semantic:pc.SEMANTIC_COLOR,components:4,type:pc.ELEMENTTYPE_UINT8,normalize:!0}),b&&a.push({semantic:pc.SEMANTIC_BLENDINDICES,components:1,type:pc.ELEMENTTYPE_FLOAT32,normalize:!1}),a=this.vertexFormats[e]=new pc.VertexFormat(this.device,a));u=new pc.VertexBuffer(this.device,a,D,pc.BUFFER_STATIC,t.buffer);z.unlock();h=new pc.Mesh;h.vertexBuffer=u;h.indexBuffer[0]=z;h.primitive[0].type=
|
|
c.origMeshInstances[0].mesh.primitive[0].type;h.primitive[0].base=0;h.primitive[0].count=B;h.primitive[0].indexed=!0;h.cull=!1;b&&(g=g.clone(),g.chunks.transformVS=this.transformVS,g.chunks.skinTexVS=this.skinTexVS,g.chunks.skinConstVS=this.skinConstVS,g.update());g=new pc.MeshInstance(this.rootNode,h,g);g.castShadow=c.origMeshInstances[0].castShadow;g.parameters=c.origMeshInstances[0].parameters;g.isStatic=c.origMeshInstances[0].isStatic;g.cull=c.origMeshInstances[0].cull;g.layer=c.origMeshInstances[0].layer;
|
|
g._staticLightList=c.origMeshInstances[0]._staticLightList;g._shaderDefs=c.origMeshInstances[0]._shaderDefs;if(b){b=[];for(e=0;e<c.origMeshInstances.length;e++)b.push(c.origMeshInstances[e].node);g.skinInstance=new d(this.device,b,this.rootNode)}g._updateAabb=!1;g.drawOrder=c.origMeshInstances[0].drawOrder;g.stencilFront=c.origMeshInstances[0].stencilFront;g.stencilBack=c.origMeshInstances[0].stencilBack;c.meshInstance=g;this.update(c);b=new pc.Model;b.meshInstances=[c.meshInstance];b.castShadows=
|
|
c.origMeshInstances[0].castShadows;c.model=b;return c}};f.prototype.update=function(a){a._aabb.copy(a.origMeshInstances[0].aabb);for(var b=1;b<a.origMeshInstances.length;b++)a._aabb.add(a.origMeshInstances[b].aabb);a.meshInstance.aabb=a._aabb;a._aabb._radiusVer=-1;a.meshInstance._aabbVer=0};f.prototype.updateAll=function(){0<this._dirtyGroups.length&&this.generate(this._dirtyGroups);for(var a=0;a<this._batchList.length;a++)this._batchList[a].dynamic&&this.update(this._batchList[a])};f.prototype.clone=
|
|
function(a,b){var c=new pc.Batch(b,a.dynamic,a.batchGroupId);this._batchList.push(c);for(var e=[],f=0;f<b.length;f++)e.push(b[f].node);c.meshInstance=new pc.MeshInstance(a.meshInstance.node,a.meshInstance.mesh,a.meshInstance.material);c.meshInstance._updateAabb=!1;c.meshInstance.parameters=b[0].parameters;c.meshInstance.isStatic=b[0].isStatic;c.meshInstance.cull=b[0].cull;c.meshInstance.layer=b[0].layer;c.meshInstance._staticLightList=b[0]._staticLightList;a.dynamic&&(c.meshInstance.skinInstance=
|
|
new d(this.device,e,this.rootNode));c.meshInstance.castShadow=a.meshInstance.castShadow;c.meshInstance._shader=a.meshInstance._shader;e=new pc.Model;e.meshInstances=[c.meshInstance];e.castShadows=a.origMeshInstances[0].castShadows;c.model=e;return c};f.prototype.destroy=function(a){a.refCounter=0;if(a.model){for(var b=this._batchGroups[a.batchGroupId].layers,c=0;c<b.length;c++)this.scene.layers.getLayerById(b[c]).removeMeshInstances(a.model.meshInstances);a.model.destroy()}};f.prototype.decrement=
|
|
function(a){a.refCounter--;0===a.refCounter&&this.destroy(a)};return{Batch:function(a,b,c){this.origMeshInstances=a;this._aabb=new pc.BoundingBox;this.model=this.meshInstance=null;this.dynamic=b;this.batchGroupId=c;this.refCounter=0},BatchGroup:c,BatchManager:f}}());
|
|
return pc;
|
|
}));
|
|
|