@xeokit/xeokit-sdk 2.6.86 → 2.6.87
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/xeokit-sdk.cjs.js +10 -9
- package/dist/xeokit-sdk.es.js +10 -9
- package/dist/xeokit-sdk.es5.js +5 -5
- package/dist/xeokit-sdk.min.cjs.js +4 -4
- package/dist/xeokit-sdk.min.es.js +4 -4
- package/dist/xeokit-sdk.min.es5.js +4 -4
- package/package.json +1 -1
- package/src/viewer/scene/CameraControl/lib/handlers/TouchPickHandler.js +7 -6
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* xeokit-sdk v2.6.
|
|
3
|
-
* Commit:
|
|
4
|
-
* Built: 2025-07-
|
|
2
|
+
* xeokit-sdk v2.6.87
|
|
3
|
+
* Commit: 8fcdaeda55a3bd75b49a6cc6fe5d950fa3251f38
|
|
4
|
+
* Built: 2025-07-31T17:46:22.388Z
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
var e,t,i,r=l().mark(HP),n=l().mark(jP),s=l().mark(CE);function o(e){var t="function"==typeof Map?new Map:void 0;return o=function(e){if(null===e||(i=e,-1===Function.toString.call(i).indexOf("[native code]")))return e;var i;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return a(e,arguments,x(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),_(r,e)},o(e)}function a(e,t,i){return a=B()?Reflect.construct.bind():function(e,t,i){var r=[null];r.push.apply(r,t);var n=new(Function.bind.apply(e,r));return i&&_(n,i.prototype),n},a.apply(null,arguments)}function l(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */l=function(){return e};var e={},t=Object.prototype,i=t.hasOwnProperty,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",s=r.asyncIterator||"@@asyncIterator",o=r.toStringTag||"@@toStringTag";function a(e,t,i){return Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{a({},"")}catch(e){a=function(e,t,i){return e[t]=i}}function u(e,t,i,r){var n=t&&t.prototype instanceof h?t:h,s=Object.create(n.prototype),o=new x(r||[]);return s._invoke=function(e,t,i){var r="suspendedStart";return function(n,s){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===n)throw s;return M()}for(i.method=n,i.arg=s;;){var o=i.delegate;if(o){var a=b(o,i);if(a){if(a===A)continue;return a}}if("next"===i.method)i.sent=i._sent=i.arg;else if("throw"===i.method){if("suspendedStart"===r)throw r="completed",i.arg;i.dispatchException(i.arg)}else"return"===i.method&&i.abrupt("return",i.arg);r="executing";var l=c(e,t,i);if("normal"===l.type){if(r=i.done?"completed":"suspendedYield",l.arg===A)continue;return{value:l.arg,done:i.done}}"throw"===l.type&&(r="completed",i.method="throw",i.arg=l.arg)}}}(e,i,o),s}function c(e,t,i){try{return{type:"normal",arg:e.call(t,i)}}catch(e){return{type:"throw",arg:e}}}e.wrap=u;var A={};function h(){}function d(){}function p(){}var f={};a(f,n,(function(){return this}));var v=Object.getPrototypeOf,g=v&&v(v(C([])));g&&g!==t&&i.call(g,n)&&(f=g);var m=p.prototype=h.prototype=Object.create(f);function _(e){["next","throw","return"].forEach((function(t){a(e,t,(function(e){return this._invoke(t,e)}))}))}function y(e,t){function r(n,s,o,a){var l=c(e[n],e,s);if("throw"!==l.type){var u=l.arg,A=u.value;return A&&"object"==P(A)&&i.call(A,"__await")?t.resolve(A.__await).then((function(e){r("next",e,o,a)}),(function(e){r("throw",e,o,a)})):t.resolve(A).then((function(e){u.value=e,o(u)}),(function(e){return r("throw",e,o,a)}))}a(l.arg)}var n;this._invoke=function(e,i){function s(){return new t((function(t,n){r(e,i,t,n)}))}return n=n?n.then(s,s):s()}}function b(e,t){var i=e.iterator[t.method];if(void 0===i){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,b(e,t),"throw"===t.method))return A;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return A}var r=c(i,e.iterator,t.arg);if("throw"===r.type)return t.method="throw",t.arg=r.arg,t.delegate=null,A;var n=r.arg;return n?n.done?(t[e.resultName]=n.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,A):n:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,A)}function w(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function B(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function x(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(w,this),this.reset(!0)}function C(e){if(e){var t=e[n];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,s=function t(){for(;++r<e.length;)if(i.call(e,r))return t.value=e[r],t.done=!1,t;return t.value=void 0,t.done=!0,t};return s.next=s}}return{next:M}}function M(){return{value:void 0,done:!0}}return d.prototype=p,a(m,"constructor",p),a(p,"constructor",d),d.displayName=a(p,o,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===d||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,a(e,o,"GeneratorFunction")),e.prototype=Object.create(m),e},e.awrap=function(e){return{__await:e}},_(y.prototype),a(y.prototype,s,(function(){return this})),e.AsyncIterator=y,e.async=function(t,i,r,n,s){void 0===s&&(s=Promise);var o=new y(u(t,i,r,n),s);return e.isGeneratorFunction(i)?o:o.next().then((function(e){return e.done?e.value:o.next()}))},_(m),a(m,o,"Generator"),a(m,n,(function(){return this})),a(m,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=[];for(var i in e)t.push(i);return t.reverse(),function i(){for(;t.length;){var r=t.pop();if(r in e)return i.value=r,i.done=!1,i}return i.done=!0,i}},e.values=C,x.prototype={constructor:x,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(B),!e)for(var t in this)"t"===t.charAt(0)&&i.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function r(i,r){return o.type="throw",o.arg=e,t.next=i,r&&(t.method="next",t.arg=void 0),!!r}for(var n=this.tryEntries.length-1;n>=0;--n){var s=this.tryEntries[n],o=s.completion;if("root"===s.tryLoc)return r("end");if(s.tryLoc<=this.prev){var a=i.call(s,"catchLoc"),l=i.call(s,"finallyLoc");if(a&&l){if(this.prev<s.catchLoc)return r(s.catchLoc,!0);if(this.prev<s.finallyLoc)return r(s.finallyLoc)}else if(a){if(this.prev<s.catchLoc)return r(s.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<s.finallyLoc)return r(s.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&i.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var s=n;break}}s&&("break"===e||"continue"===e)&&s.tryLoc<=t&&t<=s.finallyLoc&&(s=null);var o=s?s.completion:{};return o.type=e,o.arg=t,s?(this.method="next",this.next=s.finallyLoc,A):this.complete(o)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),A},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),B(i),A}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var r=i.completion;if("throw"===r.type){var n=r.arg;B(i)}return n}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,i){return this.delegate={iterator:C(e),resultName:t,nextLoc:i},"next"===this.method&&(this.arg=void 0),A}},e}function u(e,t,i,r,n,s,o){try{var a=e[s](o),l=a.value}catch(e){return void i(e)}a.done?t(l):Promise.resolve(l).then(r,n)}function c(e){return function(){var t=this,i=arguments;return new Promise((function(r,n){var s=e.apply(t,i);function o(e){u(s,r,n,o,a,"next",e)}function a(e){u(s,r,n,o,a,"throw",e)}o(void 0)}))}}function A(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,r)}return i}function h(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?A(Object(i),!0).forEach((function(t){d(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):A(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function d(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function p(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=M(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var r=0,n=function(){};return{s:n,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,o=!0,a=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return o=e.done,e},e:function(e){a=!0,s=e},f:function(){try{o||null==i.return||i.return()}finally{if(a)throw s}}}}function f(e){return function(e){if(Array.isArray(e))return k(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||M(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function v(){return v="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,i){var r=g(e,t);if(r){var n=Object.getOwnPropertyDescriptor(r,t);return n.get?n.get.call(arguments.length<3?e:i):n.value}},v.apply(this,arguments)}function g(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=x(e)););return e}function m(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&_(e,t)}function _(e,t){return _=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},_(e,t)}function y(e){var t=B();return function(){var i,r=x(e);if(t){var n=x(this).constructor;i=Reflect.construct(r,arguments,n)}else i=r.apply(this,arguments);return b(this,i)}}function b(e,t){if(t&&("object"===P(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return w(e)}function w(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function B(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function x(e){return x=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},x(e)}function P(e){return P="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},P(e)}function C(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==i)return;var r,n,s=[],o=!0,a=!1;try{for(i=i.call(e);!(o=(r=i.next()).done)&&(s.push(r.value),!t||s.length!==t);o=!0);}catch(e){a=!0,n=e}finally{try{o||null==i.return||i.return()}finally{if(a)throw n}}return s}(e,t)||M(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function M(e,t){if(e){if("string"==typeof e)return k(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?k(e,t):void 0}}function k(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,r=new Array(t);i<t;i++)r[i]=e[i];return r}function E(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function F(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function I(e,t,i){return t&&F(e.prototype,t),i&&F(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}function T(e){return new R(e)}function D(e){return function(){return new S(e.apply(this,arguments))}}function S(e){var t,i;function r(t,i){try{var s=e[t](i),o=s.value,a=o instanceof R;Promise.resolve(a?o.wrapped:o).then((function(e){a?r("return"===t?"return":"next",e):n(s.done?"return":"normal",e)}),(function(e){r("throw",e)}))}catch(e){n("throw",e)}}function n(e,n){switch(e){case"return":t.resolve({value:n,done:!0});break;case"throw":t.reject(n);break;default:t.resolve({value:n,done:!1})}(t=t.next)?r(t.key,t.arg):i=null}this._invoke=function(e,n){return new Promise((function(s,o){var a={key:e,arg:n,resolve:s,reject:o,next:null};i?i=i.next=a:(t=i=a,r(e,n))}))},"function"!=typeof e.return&&(this.return=void 0)}function R(e){this.wrapped=e}function U(e){var t,i,r,n=2;for("undefined"!=typeof Symbol&&(i=Symbol.asyncIterator,r=Symbol.iterator);n--;){if(i&&null!=(t=e[i]))return t.call(e);if(r&&null!=(t=e[r]))return new L(t.call(e));i="@@asyncIterator",r="@@iterator"}throw new TypeError("Object is not async iterable")}function L(e){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then((function(e){return{value:e,done:t}}))}return L=function(e){this.s=e,this.n=e.next},L.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?Promise.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?Promise.reject(e):t(i.apply(this.s,arguments))}},new L(e)}S.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},S.prototype.next=function(e){return this._invoke("next",e)},S.prototype.throw=function(e){return this._invoke("throw",e)},S.prototype.return=function(e){return this._invoke("return",e)};var O,N,V,Q,H,j,G,z,W,X,K,Z=function(){function e(t,i){E(this,e),this.items=t||[],this._lastUniqueId=(i||0)+1}return I(e,[{key:"addItem",value:function(){var e;if(2===arguments.length){var t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){var i=this._lastUniqueId++;if(!this.items[i])return this.items[i]=e,i}}},{key:"removeItem",value:function(e){var t=this.items[e];return delete this.items[e],t}}]),e}(),J=new Z,Y=I((function e(t){E(this,e),this.id=t,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0})),q=I((function e(){E(this,e),this.items=[]})),$=I((function e(t,i,r,n,s){E(this,e),this.id=t,this.getTitle=i,this.doAction=r,this.getEnabled=n,this.getShown=s,this.itemElement=null,this.subMenu=null,this.enabled=!0})),ee=function(){function e(){var t=this,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};E(this,e),this._id=J.addItem(),this._context=null,this._enabled=!1,this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={},this._shown=!1,this._nextId=0,this._parentNode=i.parentNode||document.body,this._offsetParent=this._parentNode instanceof ShadowRoot?this._parentNode.host:this._parentNode,this._eventSubs={},!1!==i.hideOnMouseDown&&(this._parentNode.addEventListener("mousedown",(function(e){e.target.classList.contains("xeokit-context-menu-item")||t.hide()})),this._parentNode.addEventListener("touchstart",this._canvasTouchStartHandler=function(e){e.target.classList.contains("xeokit-context-menu-item")||t.hide()})),i.items&&(this.items=i.items),this._hideOnAction=!1!==i.hideOnAction,this.context=i.context,this.enabled=!1!==i.enabled,this.hide()}return I(e,[{key:"on",value:function(e,t){var i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}},{key:"fire",value:function(e,t){var i=this._eventSubs[e];if(i)for(var r=0,n=i.length;r<n;r++)i[r](t)}},{key:"items",get:function(){return this._itemsCfg},set:function(e){this._clear(),this._itemsCfg=e||[],this._parseItems(e),this._createUI()}},{key:"enabled",get:function(){return this._enabled},set:function(e){(e=!!e)!==this._enabled&&(this._enabled=e,this._enabled||this.hide())}},{key:"context",get:function(){return this._context},set:function(e){this._context=e}},{key:"show",value:function(e,t){this._context?this._enabled&&(this._shown||(this._hideAllMenus(),this._updateItemsTitles(),this._updateItemsEnabledStatus(),this._showMenu(this._rootMenu.id,e,t),this._updateSubMenuInfo(),this._shown=!0,this.fire("shown",{}))):console.error("ContextMenu cannot be shown without a context - set context first")}},{key:"shown",get:function(){return this._shown}},{key:"hide",value:function(){this._enabled&&this._shown&&(this._hideAllMenus(),this._shown=!1,this.fire("hidden",{}))}},{key:"destroy",value:function(){this._context=null,this._clear(),null!==this._id&&(J.removeItem(this._id),this._id=null)}},{key:"_clear",value:function(){for(var e=0,t=this._menuList.length;e<t;e++){this._menuList[e].menuElement.remove()}this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={}}},{key:"_parseItems",value:function(e){var t=this;this._rootMenu=function e(i){for(var r=t._getNextId(),n=new Y(r),s=0,o=i.length;s<o;s++){var a=i[s],l=new q;n.groups.push(l);for(var u=function(i,r){var s=a[i],o=s.items,u=o&&o.length>0,c=t._getNextId(),A=s.getTitle||function(){return s.title||""},h=s.doAction||s.callback||function(){},d=s.getEnabled||function(){return!0},p=s.getShown||function(){return!0},f=new $(c,A,h,d,p);if(f.parentMenu=n,l.items.push(f),u){var v=e(o);f.subMenu=v,v.parentItem=f}t._itemList.push(f),t._itemMap[f.id]=f},c=0,A=a.length;c<A;c++)u(c)}return t._menuList.push(n),t._menuMap[n.id]=n,n}(e)}},{key:"_getNextId",value:function(){return"ContextMenu_"+this._id+"_"+this._nextId++}},{key:"_createUI",value:function(){var e=this;!function t(i){e._createMenuUI(i);for(var r=i.groups,n=0,s=r.length;n<s;n++)for(var o=r[n].items,a=0,l=o.length;a<l;a++){var u=o[a].subMenu;u&&t(u)}}(this._rootMenu)}},{key:"_createMenuUI",value:function(e){var t=this,i=e.groups,r=[],n=document.createElement("div");if(n.classList.add("xeokit-context-menu",e.id),n.style.zIndex=3e5,n.style.position="absolute",r.push("<ul>"),i)for(var s=0,o=i.length;s<o;s++){var a=s,l=o,u=i[s].items;if(u)for(var c=0,A=u.length;c<A;c++){var h=u[c],d=h.subMenu,p=h.title||"";d?(r.push('<li id="'+h.id+'" class="xeokit-context-menu-item xeokit-context-menu-submenu">'+p+"</li>"),a===l-1||c<A-1||r.push('<li id="'+h.id+'" class="xeokit-context-menu-item-separator"></li>')):(r.push('<li id="'+h.id+'" class="xeokit-context-menu-item">'+p+"</li>"),a===l-1||c<A-1||r.push('<li id="'+h.id+'" class="xeokit-context-menu-item-separator"></li>'))}}r.push("</ul>");var f=r.join("");n.innerHTML=f,this._parentNode.appendChild(n),e.menuElement=n,n.style["border-radius"]="4px",n.style.display="none",n.style["z-index"]=3e5,n.style.background="white",n.style.border="1px solid black",n.style["box-shadow"]="0 4px 5px 0 gray",n.oncontextmenu=function(e){e.preventDefault()};var v=this,g=null;if(i)for(var m=0,_=i.length;m<_;m++){var y=i[m].items;if(y)for(var b=function(e,i){var r=y[e],n=r.subMenu;if(r.itemElement=t._parentNode.querySelector("#".concat(r.id)),!r.itemElement)return console.error("ContextMenu item element not found: "+r.id),"continue";r.itemElement.addEventListener("mouseenter",(function(e){e.preventDefault();var t=r.subMenu;if(t){if(g&&g.id!==t.id&&(v._hideMenu(g.id),g=null),!1!==r.enabled){var i=r.itemElement,n=t.menuElement,s=i.getBoundingClientRect();n.getBoundingClientRect();var o=v._offsetParent.getBoundingClientRect(),a=200,l=s.right+a<o.right,u=s.left-a>o.left;if(l)v._showMenu(t.id,s.right+window.scrollX-5,s.top+window.scrollY-1);else if(u)v._showMenu(t.id,s.left-a+window.scrollX,s.top+window.scrollY-1);else{var c=s.left-o.left,A=o.right-s.right;A>c?v._showMenu(t.id,s.right-5-(a-A),s.top+window.scrollY-1):v._showMenu(t.id,s.left-c,s.top+window.scrollY-1)}g=t}}else g&&(v._hideMenu(g.id),g=null)})),n||(r.itemElement.addEventListener("click",(function(e){e.preventDefault(),v._context&&!1!==r.enabled&&(r.doAction&&r.doAction(v._context),t._hideOnAction?v.hide():(v._updateItemsTitles(),v._updateItemsEnabledStatus()))})),r.itemElement.addEventListener("mouseup",(function(e){3===e.which&&(e.preventDefault(),v._context&&!1!==r.enabled&&(r.doAction&&r.doAction(v._context),t._hideOnAction?v.hide():(v._updateItemsTitles(),v._updateItemsEnabledStatus())))})),r.itemElement.addEventListener("mouseenter",(function(e){e.preventDefault(),!1!==r.enabled&&r.doHover&&r.doHover(v._context)})))},w=0,B=y.length;w<B;w++)b(w)}}},{key:"_updateItemsTitles",value:function(){if(this._context)for(var e=0,t=this._itemList.length;e<t;e++){var i=this._itemList[e],r=i.itemElement;if(r){var n=i.getShown;if(n&&n(this._context)){var s=i.getTitle(this._context);i.subMenu,r.innerText=s}}}}},{key:"_updateItemsEnabledStatus",value:function(){if(this._context)for(var e=0,t=this._itemList.length;e<t;e++){var i=this._itemList[e],r=i.itemElement;if(r){var n=i.getEnabled;if(n){var s=i.getShown;if(s){var o=s(this._context);if(i.shown=o,o){r.style.display="";var a=n(this._context);i.enabled=a,a?r.classList.remove("disabled"):r.classList.add("disabled")}else r.style.display="none"}}}}}},{key:"_updateSubMenuInfo",value:function(){var e,t,i,r,n,s;this._context&&this._itemList.forEach((function(o){o.subMenu&&(e=o.itemElement,t=e.getBoundingClientRect(),i=o.subMenu.menuElement,r={visibility:i.style.visibility,display:i.style.display},i.style.display="block",i.style.visibility="hidden",s=o.subMenu.menuElement.getBoundingClientRect().width,i.style.visibility=r.visibility,i.style.display=r.display,n=t.right+s>window.innerWidth,e.setAttribute("data-submenuposition",n?"left":"right"))}))}},{key:"_showMenu",value:function(e,t,i){var r=this._menuMap[e];if(r){if(!r.shown){var n=r.menuElement;n&&(this._showMenuElement(n,t,i),r.shown=!0)}}else console.error("Menu not found: "+e)}},{key:"_hideMenu",value:function(e){var t=this._menuMap[e];if(t){if(t.shown){var i=t.menuElement;i&&(this._hideMenuElement(i),t.shown=!1)}}else console.error("Menu not found: "+e)}},{key:"_hideAllMenus",value:function(){for(var e=0,t=this._menuList.length;e<t;e++){var i=this._menuList[e];this._hideMenu(i.id)}}},{key:"_showMenuElement",value:function(e,t,i){e.style.display="block";var r=e.offsetHeight,n=e.offsetWidth,s=this._offsetParent.getBoundingClientRect(),o=this._offsetParent===window.document.body&&0===s.bottom?window.innerHeight:s.bottom+window.scrollY,a=s.right+window.scrollX;i+r>o&&(i=o-r),t+n>a&&(t=a-n),e.style.left=t-s.left-window.scrollX+"px",e.style.top=i-s.top-window.scrollY+"px"}},{key:"_hideMenuElement",value:function(e){e.style.display="none"}}]),e}(),te=function(){function e(t){var i=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E(this,e),this.viewer=t,this.scene=this.viewer.scene,this._lensCursorDiv=document.createElement("div"),this._lensParams={canvasSize:300,cursorBorder:2,cursorSize:10},this._lensCursorDiv.style.borderRadius="50%",this._lensCursorDiv.style.width=this._lensParams.cursorSize+"px",this._lensCursorDiv.style.height=this._lensParams.cursorSize+"px",this._lensCursorDiv.style.zIndex="100000",this._lensCursorDiv.style.position="absolute",this._lensCursorDiv.style.pointerEvents="none",this._lensContainer=document.createElement("div"),this._lensContainerId=r.containerId||"xeokit-lens",this._lensContainer.setAttribute("id",this._lensContainerId),this._lensContainer.style.border="1px solid black",this._lensContainer.style.background="white",this._lensContainer.style.borderRadius="50%",this._lensContainer.style.width=this._lensParams.canvasSize+"px",this._lensContainer.style.height=this._lensParams.canvasSize+"px",this._lensContainer.style.zIndex="15000",this._lensContainer.style.position="absolute",this._lensContainer.style.pointerEvents="none",this._lensContainer.style.visibility="hidden",this._lensCanvas=document.createElement("canvas"),this._lensCanvas.id="".concat(this._lensContainerId,"-canvas"),this._lensCanvas.style.borderRadius="50%",this._lensCanvas.style.width=this._lensParams.canvasSize+"px",this._lensCanvas.style.height=this._lensParams.canvasSize+"px",this._lensCanvas.style.zIndex="15000",this._lensCanvas.style.pointerEvents="none",document.body.appendChild(this._lensContainer),this._lensContainer.appendChild(this._lensCanvas),this._lensContainer.appendChild(this._lensCursorDiv),this._lensCanvasContext=this._lensCanvas.getContext("2d"),this._canvasElement=this.viewer.scene.canvas.canvas,this._canvasPos=null,this._snappedCanvasPos=null,this._lensPosToggle=r.lensPosToggle||!0,this._lensPosToggleAmount=r.lensPosToggleAmount||85,this._lensPosMarginLeft=r.lensPosMarginLeft||85,this._lensPosMarginTop=r.lensPosMarginTop||25,this._lensContainer.style.marginTop="".concat(this._lensPosMarginTop,"px"),this._lensContainer.style.marginLeft="".concat(this._lensPosMarginLeft,"px"),this._zoomLevel=r.zoomLevel||2,this._active=!1!==r.active,this._visible=!1,this.snapped=!1,this._onViewerRendering=this.viewer.scene.on("rendering",(function(){i._active&&i._visible&&i.update()}))}return I(e,[{key:"update",value:function(){if(this._active&&this._visible&&this._canvasPos){var e=this._lensContainer.getBoundingClientRect(),t=this._canvasElement.getBoundingClientRect(),i=this._canvasPos[0]<e.right&&this._canvasPos[0]>e.left&&this._canvasPos[1]<e.bottom&&this._canvasPos[1]>e.top;this._lensContainer.style.marginLeft="".concat(this._lensPosMarginLeft,"px"),i&&(this._lensPosToggle?this._lensContainer.style.marginTop="".concat(t.bottom-t.top-this._lensCanvas.height-this._lensPosToggleAmount,"px"):this._lensContainer.style.marginTop="".concat(this._lensPosMarginTop,"px"),this._lensPosToggle=!this._lensPosToggle),this._lensCanvasContext.clearRect(0,0,this._lensCanvas.width,this._lensCanvas.height);var r=Math.max(this._lensCanvas.width,this._lensCanvas.height)/this._zoomLevel;this._lensCanvasContext.drawImage(this._canvasElement,this._canvasPos[0]-r/2,this._canvasPos[1]-r/2,r,r,0,0,this._lensCanvas.width,this._lensCanvas.height);var n=this._lensParams.canvasSize/2-this._lensParams.cursorSize/2-this._lensParams.cursorBorder,s=this._snappedCanvasPos?this._snappedCanvasPos[0]-this._canvasPos[0]:0,o=this._snappedCanvasPos?this._snappedCanvasPos[1]-this._canvasPos[1]:0;this._lensCursorDiv.style.left="".concat(n+s*this._zoomLevel,"px"),this._lensCursorDiv.style.top="".concat(n+o*this._zoomLevel,"px")}}},{key:"zoomFactor",get:function(){return this._zoomFactor},set:function(e){this._zoomFactor=e,this.update()}},{key:"canvasPos",get:function(){return this._canvasPos},set:function(e){this._canvasPos=e,this.update()}},{key:"snappedCanvasPos",get:function(){return this._snappedCanvasPos},set:function(e){this._snappedCanvasPos=e,this.update()}},{key:"snapped",get:function(){return this._snapped},set:function(e){this._snapped=e;var t=C(e?["greenyellow","green"]:["pink","red"],2),i=t[0],r=t[1];this._lensCursorDiv.style.background=i,this._lensCursorDiv.style.border=this._lensParams.cursorBorder+"px solid "+r}},{key:"_updateActiveVisible",value:function(){this._lensContainer.style.visibility=this._active&&this._visible?"visible":"hidden",this.update()}},{key:"active",get:function(){return this._active},set:function(e){this._active=e,this._updateActiveVisible()}},{key:"visible",get:function(){return this._visible},set:function(e){this._visible=e,this._updateActiveVisible()}},{key:"destroy",value:function(){this._destroyed||(this.viewer.scene.off(this._onViewerRendering),this._lensContainer.removeChild(this._lensCanvas),document.body.removeChild(this._lensContainer),this._destroyed=!0)}}]),e}(),ie=!0,re=ie?Float64Array:Float32Array,ne=new re(3),se=new re(16),oe=new re(16),ae=new re(4),le={setDoublePrecisionEnabled:function(e){re=(ie=e)?Float64Array:Float32Array},getDoublePrecisionEnabled:function(){return ie},MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId:function(e,t){var i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:function(e,t){return e+"#"+t},safeInv:function(e){var t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:function(e){return new re(e||2)},vec3:function(e){return new re(e||3)},vec4:function(e){return new re(e||4)},mat3:function(e){return new re(e||9)},mat3ToMat4:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new re(16);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},mat4:function(e){return new re(e||16)},mat4ToMat3:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new re(9);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[4],t[4]=e[5],t[5]=e[6],t[6]=e[8],t[7]=e[9],t[8]=e[10],t},doublesToFloats:function(e,t,i){for(var r=new re(2),n=0,s=e.length;n<s;n++)le.splitDouble(e[n],r),t[n]=r[0],i[n]=r[1]},splitDouble:function(e,t){var i=re.from([e])[0],r=e-i;t[0]=i,t[1]=r},createUUID:function(){for(var e=[],t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return function(){var t=4294967295*Math.random()|0,i=4294967295*Math.random()|0,r=4294967295*Math.random()|0,n=4294967295*Math.random()|0;return"".concat(e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255],"-").concat(e[255&i]).concat(e[i>>8&255],"-").concat(e[i>>16&15|64]).concat(e[i>>24&255],"-").concat(e[63&r|128]).concat(e[r>>8&255],"-").concat(e[r>>16&255]).concat(e[r>>24&255]).concat(e[255&n]).concat(e[n>>8&255]).concat(e[n>>16&255]).concat(e[n>>24&255])}}(),clamp:function(e,t,i){return Math.max(t,Math.min(i,e))},fmod:function(e,t){if(e<t)return console.error("math.fmod : Attempting to find modulus within negative range - would be infinite loop - ignoring"),e;for(;t<=e;)e-=t;return e},compareVec3:function(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]},compareVec4:function(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]},negateVec3:function(e,t){return t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t},negateVec4:function(e,t){return t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t},addVec4:function(e,t,i){return i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i},addVec4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i},addVec3:function(e,t,i){return i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i},addVec3Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i},subVec4:function(e,t,i){return i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i},subVec3:function(e,t,i){return i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i},subVec2:function(e,t,i){return i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i},geometricMeanVec2:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];for(var r=new re(t[0]),n=1;n<t.length;n++)r[0]+=t[n][0],r[1]+=t[n][1];return r[0]/=t.length,r[1]/=t.length,r},subVec4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i},subScalarVec4:function(e,t,i){return i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i},mulVec4:function(e,t,i){return i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i},mulVec4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i},mulVec3Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i},mulVec2Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i},divVec3:function(e,t,i){return i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i},divVec4:function(e,t,i){return i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i},divScalarVec3:function(e,t,i){return i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i},divVec3Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i},divVec4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i},divScalarVec4:function(e,t,i){return i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i},dotVec4:function(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]},cross3Vec4:function(e,t){var i=e[0],r=e[1],n=e[2],s=t[0],o=t[1],a=t[2];return[r*a-n*o,n*s-i*a,i*o-r*s,0]},cross3Vec3:function(e,t,i){i||(i=e);var r=e[0],n=e[1],s=e[2],o=t[0],a=t[1],l=t[2];return i[0]=n*l-s*a,i[1]=s*o-r*l,i[2]=r*a-n*o,i},sqLenVec4:function(e){return le.dotVec4(e,e)},lenVec4:function(e){return Math.sqrt(le.sqLenVec4(e))},dotVec3:function(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]},dotVec2:function(e,t){return e[0]*t[0]+e[1]*t[1]},sqLenVec3:function(e){return le.dotVec3(e,e)},sqLenVec2:function(e){return le.dotVec2(e,e)},lenVec3:function(e){return Math.sqrt(le.sqLenVec3(e))},distVec3:(K=new re(3),function(e,t){return le.lenVec3(le.subVec3(e,t,K))}),lenVec2:function(e){return Math.sqrt(le.sqLenVec2(e))},distVec2:function(){var e=new re(2);return function(t,i){return le.lenVec2(le.subVec2(t,i,e))}}(),rcpVec3:function(e,t){return le.divScalarVec3(1,e,t)},normalizeVec4:function(e,t){var i=1/le.lenVec4(e);return le.mulVec4Scalar(e,i,t)},normalizeVec3:function(e,t){var i=1/le.lenVec3(e);return le.mulVec3Scalar(e,i,t)},normalizeVec2:function(e,t){var i=1/le.lenVec2(e);return le.mulVec2Scalar(e,i,t)},angleVec3:function(e,t){var i=le.dotVec3(e,t)/Math.sqrt(le.sqLenVec3(e)*le.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:function(){var e=new re(3);return function(t,i){return e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=le.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=le.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=le.lenVec3(e),i}}(),vecToArray:function(){function e(e){return Math.round(1e5*e)/1e5}return function(t){for(var i=0,r=(t=Array.prototype.slice.call(t)).length;i<r;i++)t[i]=e(t[i]);return t}}(),xyzArrayToObject:function(e){return{x:e[0],y:e[1],z:e[2]}},xyzObjectToArray:function(e,t){return(t=t||le.vec3())[0]=e.x,t[1]=e.y,t[2]=e.z,t},dupMat4:function(e){return e.slice(0,16)},mat4To3:function(e){return[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]]},m4s:function(e){return[e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e]},setMat4ToZeroes:function(){return le.m4s(0)},setMat4ToOnes:function(){return le.m4s(1)},diagonalMat4v:function(e){return new re([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]])},diagonalMat4c:function(e,t,i,r){return le.diagonalMat4v([e,t,i,r])},diagonalMat4s:function(e){return le.diagonalMat4c(e,e,e,e)},identityMat4:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new re(16);return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e},identityMat3:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new re(9);return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e},isIdentityMat4:function(e){return 1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]},negateMat4:function(e,t){return t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t},addMat4:function(e,t,i){return i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i},addMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i},addScalarMat4:function(e,t,i){return le.addMat4Scalar(t,e,i)},subMat4:function(e,t,i){return i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i},subMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i},subScalarMat4:function(e,t,i){return i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i},mulMat4:function(e,t,i){i||(i=e);var r=e[0],n=e[1],s=e[2],o=e[3],a=e[4],l=e[5],u=e[6],c=e[7],A=e[8],h=e[9],d=e[10],p=e[11],f=e[12],v=e[13],g=e[14],m=e[15],_=t[0],y=t[1],b=t[2],w=t[3],B=t[4],x=t[5],P=t[6],C=t[7],M=t[8],k=t[9],E=t[10],F=t[11],I=t[12],T=t[13],D=t[14],S=t[15];return i[0]=_*r+y*a+b*A+w*f,i[1]=_*n+y*l+b*h+w*v,i[2]=_*s+y*u+b*d+w*g,i[3]=_*o+y*c+b*p+w*m,i[4]=B*r+x*a+P*A+C*f,i[5]=B*n+x*l+P*h+C*v,i[6]=B*s+x*u+P*d+C*g,i[7]=B*o+x*c+P*p+C*m,i[8]=M*r+k*a+E*A+F*f,i[9]=M*n+k*l+E*h+F*v,i[10]=M*s+k*u+E*d+F*g,i[11]=M*o+k*c+E*p+F*m,i[12]=I*r+T*a+D*A+S*f,i[13]=I*n+T*l+D*h+S*v,i[14]=I*s+T*u+D*d+S*g,i[15]=I*o+T*c+D*p+S*m,i},mulMat3:function(e,t,i){i||(i=new re(9));var r=e[0],n=e[3],s=e[6],o=e[1],a=e[4],l=e[7],u=e[2],c=e[5],A=e[8],h=t[0],d=t[3],p=t[6],f=t[1],v=t[4],g=t[7],m=t[2],_=t[5],y=t[8];return i[0]=r*h+n*f+s*m,i[3]=r*d+n*v+s*_,i[6]=r*p+n*g+s*y,i[1]=o*h+a*f+l*m,i[4]=o*d+a*v+l*_,i[7]=o*p+a*g+l*y,i[2]=u*h+c*f+A*m,i[5]=u*d+c*v+A*_,i[8]=u*p+c*g+A*y,i},mulMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i},mulMat4v4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:le.vec4(),r=t[0],n=t[1],s=t[2],o=t[3];return i[0]=e[0]*r+e[4]*n+e[8]*s+e[12]*o,i[1]=e[1]*r+e[5]*n+e[9]*s+e[13]*o,i[2]=e[2]*r+e[6]*n+e[10]*s+e[14]*o,i[3]=e[3]*r+e[7]*n+e[11]*s+e[15]*o,i},transposeMat4:function(e,t){var i=e[4],r=e[14],n=e[8],s=e[13],o=e[12],a=e[9];if(!t||e===t){var l=e[1],u=e[2],c=e[3],A=e[6],h=e[7],d=e[11];return e[1]=i,e[2]=n,e[3]=o,e[4]=l,e[6]=a,e[7]=s,e[8]=u,e[9]=A,e[11]=r,e[12]=c,e[13]=h,e[14]=d,e}return t[0]=e[0],t[1]=i,t[2]=n,t[3]=o,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=s,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=r,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3:function(e,t){if(t===e){var i=e[1],r=e[2],n=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=r,t[7]=n}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4:function(e){var t=e[0],i=e[1],r=e[2],n=e[3],s=e[4],o=e[5],a=e[6],l=e[7],u=e[8],c=e[9],A=e[10],h=e[11],d=e[12],p=e[13],f=e[14],v=e[15];return d*c*a*n-u*p*a*n-d*o*A*n+s*p*A*n+u*o*f*n-s*c*f*n-d*c*r*l+u*p*r*l+d*i*A*l-t*p*A*l-u*i*f*l+t*c*f*l+d*o*r*h-s*p*r*h-d*i*a*h+t*p*a*h+s*i*f*h-t*o*f*h-u*o*r*v+s*c*r*v+u*i*a*v-t*c*a*v-s*i*A*v+t*o*A*v},inverseMat4:function(e,t){t||(t=e);var i=e[0],r=e[1],n=e[2],s=e[3],o=e[4],a=e[5],l=e[6],u=e[7],c=e[8],A=e[9],h=e[10],d=e[11],p=e[12],f=e[13],v=e[14],g=e[15],m=i*a-r*o,_=i*l-n*o,y=i*u-s*o,b=r*l-n*a,w=r*u-s*a,B=n*u-s*l,x=c*f-A*p,P=c*v-h*p,C=c*g-d*p,M=A*v-h*f,k=A*g-d*f,E=h*g-d*v,F=1/(m*E-_*k+y*M+b*C-w*P+B*x);return t[0]=(a*E-l*k+u*M)*F,t[1]=(-r*E+n*k-s*M)*F,t[2]=(f*B-v*w+g*b)*F,t[3]=(-A*B+h*w-d*b)*F,t[4]=(-o*E+l*C-u*P)*F,t[5]=(i*E-n*C+s*P)*F,t[6]=(-p*B+v*y-g*_)*F,t[7]=(c*B-h*y+d*_)*F,t[8]=(o*k-a*C+u*x)*F,t[9]=(-i*k+r*C-s*x)*F,t[10]=(p*w-f*y+g*m)*F,t[11]=(-c*w+A*y-d*m)*F,t[12]=(-o*M+a*P-l*x)*F,t[13]=(i*M-r*P+n*x)*F,t[14]=(-p*b+f*_-v*m)*F,t[15]=(c*b-A*_+h*m)*F,t},traceMat4:function(e){return e[0]+e[5]+e[10]+e[15]},translationMat4v:function(e,t){var i=t||le.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v:function(e,t){var i=t||le.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(X=new re(3),function(e,t,i,r){return X[0]=e,X[1]=t,X[2]=i,le.translationMat4v(X,r)}),translationMat4s:function(e,t){return le.translationMat4c(e,e,e,t)},translateMat4v:function(e,t){return le.translateMat4c(e[0],e[1],e[2],t)},translateMat4c:function(e,t,i,r){var n=r[3];r[0]+=n*e,r[1]+=n*t,r[2]+=n*i;var s=r[7];r[4]+=s*e,r[5]+=s*t,r[6]+=s*i;var o=r[11];r[8]+=o*e,r[9]+=o*t,r[10]+=o*i;var a=r[15];return r[12]+=a*e,r[13]+=a*t,r[14]+=a*i,r},setMat4Translation:function(e,t,i){return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i},rotationMat4v:function(e,t,i){var r,n,s,o,a,l,u=le.normalizeVec4([t[0],t[1],t[2],0],[]),c=Math.sin(e),A=Math.cos(e),h=1-A,d=u[0],p=u[1],f=u[2];return r=d*p,n=p*f,s=f*d,o=d*c,a=p*c,l=f*c,(i=i||le.mat4())[0]=h*d*d+A,i[1]=h*r+l,i[2]=h*s-a,i[3]=0,i[4]=h*r-l,i[5]=h*p*p+A,i[6]=h*n+o,i[7]=0,i[8]=h*s+a,i[9]=h*n-o,i[10]=h*f*f+A,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:function(e,t,i,r,n){return le.rotationMat4v(e,[t,i,r],n)},scalingMat4v:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:le.identityMat4();return t[0]=e[0],t[5]=e[1],t[10]=e[2],t},scalingMat3v:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:le.identityMat3();return t[0]=e[0],t[4]=e[1],t},scalingMat4c:function(){var e=new re(3);return function(t,i,r,n){return e[0]=t,e[1]=i,e[2]=r,le.scalingMat4v(e,n)}}(),scaleMat4c:function(e,t,i,r){return r[0]*=e,r[4]*=t,r[8]*=i,r[1]*=e,r[5]*=t,r[9]*=i,r[2]*=e,r[6]*=t,r[10]*=i,r[3]*=e,r[7]*=t,r[11]*=i,r},scaleMat4v:function(e,t){var i=e[0],r=e[1],n=e[2];return t[0]*=i,t[4]*=r,t[8]*=n,t[1]*=i,t[5]*=r,t[9]*=n,t[2]*=i,t[6]*=r,t[10]*=n,t[3]*=i,t[7]*=r,t[11]*=n,t},scalingMat4s:function(e){return le.scalingMat4c(e,e,e)},rotationTranslationMat4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:le.mat4(),r=e[0],n=e[1],s=e[2],o=e[3],a=r+r,l=n+n,u=s+s,c=r*a,A=r*l,h=r*u,d=n*l,p=n*u,f=s*u,v=o*a,g=o*l,m=o*u;return i[0]=1-(d+f),i[1]=A+m,i[2]=h-g,i[3]=0,i[4]=A-m,i[5]=1-(c+f),i[6]=p+v,i[7]=0,i[8]=h+g,i[9]=p-v,i[10]=1-(c+d),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:le.vec4(),r=le.clamp,n=e[0],s=e[4],o=e[8],a=e[1],l=e[5],u=e[9],c=e[2],A=e[6],h=e[10];return"XYZ"===t?(i[1]=Math.asin(r(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(-u,h),i[2]=Math.atan2(-s,n)):(i[0]=Math.atan2(A,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-r(u,-1,1)),Math.abs(u)<.99999?(i[1]=Math.atan2(o,h),i[2]=Math.atan2(a,l)):(i[1]=Math.atan2(-c,n),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(r(A,-1,1)),Math.abs(A)<.99999?(i[1]=Math.atan2(-c,h),i[2]=Math.atan2(-s,l)):(i[1]=0,i[2]=Math.atan2(a,n))):"ZYX"===t?(i[1]=Math.asin(-r(c,-1,1)),Math.abs(c)<.99999?(i[0]=Math.atan2(A,h),i[2]=Math.atan2(a,n)):(i[0]=0,i[2]=Math.atan2(-s,l))):"YZX"===t?(i[2]=Math.asin(r(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-u,l),i[1]=Math.atan2(-c,n)):(i[0]=0,i[1]=Math.atan2(o,h))):"XZY"===t&&(i[2]=Math.asin(-r(s,-1,1)),Math.abs(s)<.99999?(i[0]=Math.atan2(A,l),i[1]=Math.atan2(o,n)):(i[0]=Math.atan2(-u,h),i[1]=0)),i[0]*=le.RADTODEG,i[1]*=le.RADTODEG,i[2]*=le.RADTODEG,i},composeMat4:function(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:le.mat4();return le.quaternionToRotationMat4(t,r),le.scaleMat4v(i,r),le.translateMat4v(e,r),r},decomposeMat4:function(){var e=new re(3),t=new re(16);return function(i,r,n,s){e[0]=i[0],e[1]=i[1],e[2]=i[2];var o=le.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];var a=le.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];var l=le.lenVec3(e);le.determinantMat4(i)<0&&(o=-o),r[0]=i[12],r[1]=i[13],r[2]=i[14],t.set(i);var u=1/o,c=1/a,A=1/l;return t[0]*=u,t[1]*=u,t[2]*=u,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=A,t[9]*=A,t[10]*=A,le.mat4ToQuaternion(t,n),s[0]=o,s[1]=a,s[2]=l,this}}(),getColMat4:function(e,t){var i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4:function(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v:function(e,t,i,r){r||(r=le.mat4());var n,s,o,a,l,u,c,A,h,d,p=e[0],f=e[1],v=e[2],g=i[0],m=i[1],_=i[2],y=t[0],b=t[1],w=t[2];return p===y&&f===b&&v===w?le.identityMat4():(n=p-y,s=f-b,o=v-w,a=m*(o*=d=1/Math.sqrt(n*n+s*s+o*o))-_*(s*=d),l=_*(n*=d)-g*o,u=g*s-m*n,(d=Math.sqrt(a*a+l*l+u*u))?(a*=d=1/d,l*=d,u*=d):(a=0,l=0,u=0),c=s*u-o*l,A=o*a-n*u,h=n*l-s*a,(d=Math.sqrt(c*c+A*A+h*h))?(c*=d=1/d,A*=d,h*=d):(c=0,A=0,h=0),r[0]=a,r[1]=c,r[2]=n,r[3]=0,r[4]=l,r[5]=A,r[6]=s,r[7]=0,r[8]=u,r[9]=h,r[10]=o,r[11]=0,r[12]=-(a*p+l*f+u*v),r[13]=-(c*p+A*f+h*v),r[14]=-(n*p+s*f+o*v),r[15]=1,r)},lookAtMat4c:function(e,t,i,r,n,s,o,a,l){return le.lookAtMat4v([e,t,i],[r,n,s],[o,a,l],[])},orthoMat4c:function(e,t,i,r,n,s,o){o||(o=le.mat4());var a=t-e,l=r-i,u=s-n;return o[0]=2/a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2/l,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=-2/u,o[11]=0,o[12]=-(e+t)/a,o[13]=-(r+i)/l,o[14]=-(s+n)/u,o[15]=1,o},frustumMat4v:function(e,t,i){i||(i=le.mat4());var r=[e[0],e[1],e[2],0],n=[t[0],t[1],t[2],0];le.addVec4(n,r,se),le.subVec4(n,r,oe);var s=2*r[2],o=oe[0],a=oe[1],l=oe[2];return i[0]=s/o,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=s/a,i[6]=0,i[7]=0,i[8]=se[0]/o,i[9]=se[1]/a,i[10]=-se[2]/l,i[11]=-1,i[12]=0,i[13]=0,i[14]=-s*n[2]/l,i[15]=0,i},frustumMat4:function(e,t,i,r,n,s,o){o||(o=le.mat4());var a=t-e,l=r-i,u=s-n;return o[0]=2*n/a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2*n/l,o[6]=0,o[7]=0,o[8]=(t+e)/a,o[9]=(r+i)/l,o[10]=-(s+n)/u,o[11]=-1,o[12]=0,o[13]=0,o[14]=-s*n*2/u,o[15]=0,o},perspectiveMat4:function(e,t,i,r,n){var s=[],o=[];return s[2]=i,o[2]=r,o[1]=s[2]*Math.tan(e/2),s[1]=-o[1],o[0]=o[1]*t,s[0]=-o[0],le.frustumMat4v(s,o,n)},compareMat4:function(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15]},transformPoint3:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:le.vec3(),r=t[0],n=t[1],s=t[2];return i[0]=e[0]*r+e[4]*n+e[8]*s+e[12],i[1]=e[1]*r+e[5]*n+e[9]*s+e[13],i[2]=e[2]*r+e[6]*n+e[10]*s+e[14],i},transformPoint4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:le.vec4();return i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i},transformPoints3:function(e,t,i){for(var r,n,s,o,a,l=i||[],u=t.length,c=e[0],A=e[1],h=e[2],d=e[3],p=e[4],f=e[5],v=e[6],g=e[7],m=e[8],_=e[9],y=e[10],b=e[11],w=e[12],B=e[13],x=e[14],P=e[15],C=0;C<u;++C)r=(o=t[C])[0],n=o[1],s=o[2],(a=l[C]||(l[C]=[0,0,0]))[0]=c*r+p*n+m*s+w,a[1]=A*r+f*n+_*s+B,a[2]=h*r+v*n+y*s+x,a[3]=d*r+g*n+b*s+P;return l.length=u,l},transformPositions3:function(e,t){var i,r,n,s,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,l=e[0],u=e[1],c=e[2];e[3];var A=e[4],h=e[5],d=e[6];e[7];var p=e[8],f=e[9],v=e[10];e[11];var g=e[12],m=e[13],_=e[14];for(e[15],i=0;i<a;i+=3)r=t[i+0],n=t[i+1],s=t[i+2],o[i+0]=l*r+A*n+p*s+g,o[i+1]=u*r+h*n+f*s+m,o[i+2]=c*r+d*n+v*s+_;return o},transformPositions4:function(e,t){var i,r,n,s,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,l=e[0],u=e[1],c=e[2],A=e[3],h=e[4],d=e[5],p=e[6],f=e[7],v=e[8],g=e[9],m=e[10],_=e[11],y=e[12],b=e[13],w=e[14],B=e[15];for(i=0;i<a;i+=4)r=t[i+0],n=t[i+1],s=t[i+2],o[i+0]=l*r+h*n+v*s+y,o[i+1]=u*r+d*n+g*s+b,o[i+2]=c*r+p*n+m*s+w,o[i+3]=A*r+f*n+_*s+B;return o},transformVec3:function(e,t,i){var r=t[0],n=t[1],s=t[2];return(i=i||this.vec3())[0]=e[0]*r+e[4]*n+e[8]*s,i[1]=e[1]*r+e[5]*n+e[9]*s,i[2]=e[2]*r+e[6]*n+e[10]*s,i},transformVec4:function(e,t,i){var r=t[0],n=t[1],s=t[2],o=t[3];return(i=i||le.vec4())[0]=e[0]*r+e[4]*n+e[8]*s+e[12]*o,i[1]=e[1]*r+e[5]*n+e[9]*s+e[13]*o,i[2]=e[2]*r+e[6]*n+e[10]*s+e[14]*o,i[3]=e[3]*r+e[7]*n+e[11]*s+e[15]*o,i},rotateVec2:function(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e,n=Math.cos(i),s=Math.sin(i),o=e[0]-t[0],a=e[1]-t[1];return r[0]=o*n-a*s+t[0],r[1]=o*s+a*n+t[1],e},rotateVec3X:function(e,t,i,r){var n=[],s=[];return n[0]=e[0]-t[0],n[1]=e[1]-t[1],n[2]=e[2]-t[2],s[0]=n[0],s[1]=n[1]*Math.cos(i)-n[2]*Math.sin(i),s[2]=n[1]*Math.sin(i)+n[2]*Math.cos(i),r[0]=s[0]+t[0],r[1]=s[1]+t[1],r[2]=s[2]+t[2],r},rotateVec3Y:function(e,t,i,r){var n=[],s=[];return n[0]=e[0]-t[0],n[1]=e[1]-t[1],n[2]=e[2]-t[2],s[0]=n[2]*Math.sin(i)+n[0]*Math.cos(i),s[1]=n[1],s[2]=n[2]*Math.cos(i)-n[0]*Math.sin(i),r[0]=s[0]+t[0],r[1]=s[1]+t[1],r[2]=s[2]+t[2],r},rotateVec3Z:function(e,t,i,r){var n=[],s=[];return n[0]=e[0]-t[0],n[1]=e[1]-t[1],n[2]=e[2]-t[2],s[0]=n[0]*Math.cos(i)-n[1]*Math.sin(i),s[1]=n[0]*Math.sin(i)+n[1]*Math.cos(i),s[2]=n[2],r[0]=s[0]+t[0],r[1]=s[1]+t[1],r[2]=s[2]+t[2],r},projectVec4:function(e,t){var i=1/e[3];return(t=t||le.vec2())[0]=e[0]*i,t[1]=e[1]*i,t},unprojectVec3:(G=new re(16),z=new re(16),W=new re(16),function(e,t,i,r){return this.transformVec3(this.mulMat4(this.inverseMat4(t,G),this.inverseMat4(i,z),W),e,r)}),lerpVec3:function(e,t,i,r,n,s){var o=s||le.vec3(),a=(e-t)/(i-t);return o[0]=r[0]+a*(n[0]-r[0]),o[1]=r[1]+a*(n[1]-r[1]),o[2]=r[2]+a*(n[2]-r[2]),o},lerpMat4:function(e,t,i,r,n,s){var o=s||le.mat4(),a=(e-t)/(i-t);return o[0]=r[0]+a*(n[0]-r[0]),o[1]=r[1]+a*(n[1]-r[1]),o[2]=r[2]+a*(n[2]-r[2]),o[3]=r[3]+a*(n[3]-r[3]),o[4]=r[4]+a*(n[4]-r[4]),o[5]=r[5]+a*(n[5]-r[5]),o[6]=r[6]+a*(n[6]-r[6]),o[7]=r[7]+a*(n[7]-r[7]),o[8]=r[8]+a*(n[8]-r[8]),o[9]=r[9]+a*(n[9]-r[9]),o[10]=r[10]+a*(n[10]-r[10]),o[11]=r[11]+a*(n[11]-r[11]),o[12]=r[12]+a*(n[12]-r[12]),o[13]=r[13]+a*(n[13]-r[13]),o[14]=r[14]+a*(n[14]-r[14]),o[15]=r[15]+a*(n[15]-r[15]),o},flatten:function(e){var t,i,r,n,s,o=[];for(t=0,i=e.length;t<i;t++)for(r=0,n=(s=e[t]).length;r<n;r++)o.push(s[r]);return o},identityQuaternion:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:le.vec4();return e[0]=0,e[1]=0,e[2]=0,e[3]=1,e},eulerToQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:le.vec4(),r=e[0]*le.DEGTORAD/2,n=e[1]*le.DEGTORAD/2,s=e[2]*le.DEGTORAD/2,o=Math.cos(r),a=Math.cos(n),l=Math.cos(s),u=Math.sin(r),c=Math.sin(n),A=Math.sin(s);return"XYZ"===t?(i[0]=u*a*l+o*c*A,i[1]=o*c*l-u*a*A,i[2]=o*a*A+u*c*l,i[3]=o*a*l-u*c*A):"YXZ"===t?(i[0]=u*a*l+o*c*A,i[1]=o*c*l-u*a*A,i[2]=o*a*A-u*c*l,i[3]=o*a*l+u*c*A):"ZXY"===t?(i[0]=u*a*l-o*c*A,i[1]=o*c*l+u*a*A,i[2]=o*a*A+u*c*l,i[3]=o*a*l-u*c*A):"ZYX"===t?(i[0]=u*a*l-o*c*A,i[1]=o*c*l+u*a*A,i[2]=o*a*A-u*c*l,i[3]=o*a*l+u*c*A):"YZX"===t?(i[0]=u*a*l+o*c*A,i[1]=o*c*l+u*a*A,i[2]=o*a*A-u*c*l,i[3]=o*a*l-u*c*A):"XZY"===t&&(i[0]=u*a*l-o*c*A,i[1]=o*c*l-u*a*A,i[2]=o*a*A+u*c*l,i[3]=o*a*l+u*c*A),i},mat4ToQuaternion:function(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:le.vec4(),r=e[0],n=e[4],s=e[8],o=e[1],a=e[5],l=e[9],u=e[2],c=e[6],A=e[10],h=r+a+A;return h>0?(t=.5/Math.sqrt(h+1),i[3]=.25/t,i[0]=(c-l)*t,i[1]=(s-u)*t,i[2]=(o-n)*t):r>a&&r>A?(t=2*Math.sqrt(1+r-a-A),i[3]=(c-l)/t,i[0]=.25*t,i[1]=(n+o)/t,i[2]=(s+u)/t):a>A?(t=2*Math.sqrt(1+a-r-A),i[3]=(s-u)/t,i[0]=(n+o)/t,i[1]=.25*t,i[2]=(l+c)/t):(t=2*Math.sqrt(1+A-r-a),i[3]=(o-n)/t,i[0]=(s+u)/t,i[1]=(l+c)/t,i[2]=.25*t),i},vec3PairToQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:le.vec4(),r=Math.sqrt(le.dotVec3(e,e)*le.dotVec3(t,t)),n=r+le.dotVec3(e,t);return n<1e-8*r?(n=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):le.cross3Vec3(e,t,i),i[3]=n,le.normalizeQuaternion(i)},angleAxisToQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:le.vec4(),i=e[3]/2,r=Math.sin(i);return t[0]=r*e[0],t[1]=r*e[1],t[2]=r*e[2],t[3]=Math.cos(i),t},quaternionToEuler:function(){var e=new re(16);return function(t,i,r){return r=r||le.vec3(),le.quaternionToRotationMat4(t,e),le.mat4ToEuler(e,i,r),r}}(),mulQuaternions:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:le.vec4(),r=e[0],n=e[1],s=e[2],o=e[3],a=t[0],l=t[1],u=t[2],c=t[3];return i[0]=o*a+r*c+n*u-s*l,i[1]=o*l+n*c+s*a-r*u,i[2]=o*u+s*c+r*l-n*a,i[3]=o*c-r*a-n*l-s*u,i},vec3ApplyQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:le.vec3(),r=t[0],n=t[1],s=t[2],o=e[0],a=e[1],l=e[2],u=e[3],c=u*r+a*s-l*n,A=u*n+l*r-o*s,h=u*s+o*n-a*r,d=-o*r-a*n-l*s;return i[0]=c*u+d*-o+A*-l-h*-a,i[1]=A*u+d*-a+h*-o-c*-l,i[2]=h*u+d*-l+c*-a-A*-o,i},quaternionToMat4:function(e,t){t=le.identityMat4(t);var i=e[0],r=e[1],n=e[2],s=e[3],o=2*i,a=2*r,l=2*n,u=o*s,c=a*s,A=l*s,h=o*i,d=a*i,p=l*i,f=a*r,v=l*r,g=l*n;return t[0]=1-(f+g),t[1]=d+A,t[2]=p-c,t[4]=d-A,t[5]=1-(h+g),t[6]=v+u,t[8]=p+c,t[9]=v-u,t[10]=1-(h+f),t},quaternionToRotationMat4:function(e,t){var i=e[0],r=e[1],n=e[2],s=e[3],o=i+i,a=r+r,l=n+n,u=i*o,c=i*a,A=i*l,h=r*a,d=r*l,p=n*l,f=s*o,v=s*a,g=s*l;return t[0]=1-(h+p),t[4]=c-g,t[8]=A+v,t[1]=c+g,t[5]=1-(u+p),t[9]=d-f,t[2]=A-v,t[6]=d+f,t[10]=1-(u+h),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e,i=le.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,t},conjugateQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e;return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t},inverseQuaternion:function(e,t){return le.normalizeQuaternion(le.conjugateQuaternion(e,t))},quaternionToAngleAxis:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:le.vec4(),i=(e=le.normalizeQuaternion(e,ae))[3],r=2*Math.acos(i),n=Math.sqrt(1-i*i);return n<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/n,t[1]=e[1]/n,t[2]=e[2]/n),t[3]=r,t},AABB3:function(e){return new re(e||6)},AABB2:function(e){return new re(e||4)},OBB3:function(e){return new re(e||32)},OBB2:function(e){return new re(e||16)},Sphere3:function(e,t,i,r){return new re([e,t,i,r])},transformOBB3:function(e,t){var i,r,n,s,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,l=e[0],u=e[1],c=e[2],A=e[3],h=e[4],d=e[5],p=e[6],f=e[7],v=e[8],g=e[9],m=e[10],_=e[11],y=e[12],b=e[13],w=e[14],B=e[15];for(i=0;i<a;i+=4)r=t[i+0],n=t[i+1],s=t[i+2],o[i+0]=l*r+h*n+v*s+y,o[i+1]=u*r+d*n+g*s+b,o[i+2]=c*r+p*n+m*s+w,o[i+3]=A*r+f*n+_*s+B;return o},containsAABB3:function(e,t){return e[0]<=t[0]&&t[3]<=e[3]&&e[1]<=t[1]&&t[4]<=e[4]&&e[2]<=t[2]&&t[5]<=e[5]},getAABB3Diag:function(){var e=new re(3),t=new re(3),i=new re(3);return function(r){return e[0]=r[0],e[1]=r[1],e[2]=r[2],t[0]=r[3],t[1]=r[4],t[2]=r[5],le.subVec3(t,e,i),Math.abs(le.lenVec3(i))}}(),getAABB3DiagPoint:function(){var e=new re(3),t=new re(3),i=new re(3);return function(r,n){e[0]=r[0],e[1]=r[1],e[2]=r[2],t[0]=r[3],t[1]=r[4],t[2]=r[5];var s=le.subVec3(t,e,i),o=n[0]-r[0],a=r[3]-n[0],l=n[1]-r[1],u=r[4]-n[1],c=n[2]-r[2],A=r[5]-n[2];return s[0]+=o>a?o:a,s[1]+=l>u?l:u,s[2]+=c>A?c:A,Math.abs(le.lenVec3(s))}}(),getAABB3Area:function(e){return(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2])},getAABB3Center:function(e,t){var i=t||le.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center:function(e,t){var i=t||le.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:le.AABB3();return e[0]=le.MAX_DOUBLE,e[1]=le.MAX_DOUBLE,e[2]=le.MAX_DOUBLE,e[3]=le.MIN_DOUBLE,e[4]=le.MIN_DOUBLE,e[5]=le.MIN_DOUBLE,e},AABB3ToOBB3:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:le.OBB3();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t},positions3ToAABB3:function(){var e=new re(3);return function(t,i,r){i=i||le.AABB3();for(var n,s,o,a=le.MAX_DOUBLE,l=le.MAX_DOUBLE,u=le.MAX_DOUBLE,c=le.MIN_DOUBLE,A=le.MIN_DOUBLE,h=le.MIN_DOUBLE,d=0,p=t.length;d<p;d+=3)r?(e[0]=t[d+0],e[1]=t[d+1],e[2]=t[d+2],le.decompressPosition(e,r,e),n=e[0],s=e[1],o=e[2]):(n=t[d+0],s=t[d+1],o=t[d+2]),n<a&&(a=n),s<l&&(l=s),o<u&&(u=o),n>c&&(c=n),s>A&&(A=s),o>h&&(h=o);return i[0]=a,i[1]=l,i[2]=u,i[3]=c,i[4]=A,i[5]=h,i}}(),OBB3ToAABB3:function(e){for(var t,i,r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:le.AABB3(),s=le.MAX_DOUBLE,o=le.MAX_DOUBLE,a=le.MAX_DOUBLE,l=le.MIN_DOUBLE,u=le.MIN_DOUBLE,c=le.MIN_DOUBLE,A=0,h=e.length;A<h;A+=4)(t=e[A+0])<s&&(s=t),(i=e[A+1])<o&&(o=i),(r=e[A+2])<a&&(a=r),t>l&&(l=t),i>u&&(u=i),r>c&&(c=r);return n[0]=s,n[1]=o,n[2]=a,n[3]=l,n[4]=u,n[5]=c,n},points3ToAABB3:function(e){for(var t,i,r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:le.AABB3(),s=le.MAX_DOUBLE,o=le.MAX_DOUBLE,a=le.MAX_DOUBLE,l=le.MIN_DOUBLE,u=le.MIN_DOUBLE,c=le.MIN_DOUBLE,A=0,h=e.length;A<h;A++)(t=e[A][0])<s&&(s=t),(i=e[A][1])<o&&(o=i),(r=e[A][2])<a&&(a=r),t>l&&(l=t),i>u&&(u=i),r>c&&(c=r);return n[0]=s,n[1]=o,n[2]=a,n[3]=l,n[4]=u,n[5]=c,n},points3ToSphere3:function(){var e=new re(3);return function(t,i){i=i||le.vec4();var r,n=0,s=0,o=0,a=t.length;for(r=0;r<a;r++)n+=t[r][0],s+=t[r][1],o+=t[r][2];i[0]=n/a,i[1]=s/a,i[2]=o/a;var l,u=0;for(r=0;r<a;r++)(l=Math.abs(le.lenVec3(le.subVec3(t[r],i,e))))>u&&(u=l);return i[3]=u,i}}(),positions3ToSphere3:function(){var e=new re(3),t=new re(3);return function(i,r){r=r||le.vec4();var n,s=0,o=0,a=0,l=i.length,u=0;for(n=0;n<l;n+=3)s+=i[n],o+=i[n+1],a+=i[n+2];var c,A=l/3;for(r[0]=s/A,r[1]=o/A,r[2]=a/A,n=0;n<l;n+=3)e[0]=i[n],e[1]=i[n+1],e[2]=i[n+2],(c=Math.abs(le.lenVec3(le.subVec3(e,r,t))))>u&&(u=c);return r[3]=u,r}}(),OBB3ToSphere3:function(){var e=new re(3),t=new re(3);return function(i,r){r=r||le.vec4();var n,s=0,o=0,a=0,l=i.length,u=l/4;for(n=0;n<l;n+=4)s+=i[n+0],o+=i[n+1],a+=i[n+2];r[0]=s/u,r[1]=o/u,r[2]=a/u;var c,A=0;for(n=0;n<l;n+=4)e[0]=i[n+0],e[1]=i[n+1],e[2]=i[n+2],(c=Math.abs(le.lenVec3(le.subVec3(e,r,t))))>A&&(A=c);return r[3]=A,r}}(),getSphere3Center:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:le.vec3();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t},getPositionsCenter:function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:le.vec3(),i=0,r=0,n=0,s=0,o=e.length;s<o;s+=3)i+=e[s+0],r+=e[s+1],n+=e[s+2];var a=e.length/3;return t[0]=i/a,t[1]=r/a,t[2]=n/a,t},expandAABB3:function(e,t){return e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e[4]<t[4]&&(e[4]=t[4]),e[5]<t[5]&&(e[5]=t[5]),e},expandAABB3Point3:function(e,t){return e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[0]&&(e[3]=t[0]),e[4]<t[1]&&(e[4]=t[1]),e[5]<t[2]&&(e[5]=t[2]),e},expandAABB3Points3:function(e,t){for(var i,r,n,s=0,o=t.length;s<o;s+=3)i=t[s],r=t[s+1],n=t[s+2],e[0]>i&&(e[0]=i),e[1]>r&&(e[1]=r),e[2]>n&&(e[2]=n),e[3]<i&&(e[3]=i),e[4]<r&&(e[4]=r),e[5]<n&&(e[5]=n);return e},collapseAABB2:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:le.AABB2();return e[0]=le.MAX_DOUBLE,e[1]=le.MAX_DOUBLE,e[2]=le.MIN_DOUBLE,e[3]=le.MIN_DOUBLE,e},point3AABB3Intersect:function(e,t){return e[0]>t[0]||e[3]<t[0]||e[1]>t[1]||e[4]<t[1]||e[2]>t[2]||e[5]<t[2]},point3AABB3AbsoluteIntersect:function(e,t){return e[0]<=t[0]&&e[3]>=t[0]&&e[1]<=t[1]&&e[4]>=t[1]&&e[2]<=t[2]&&e[5]>=t[2]},planeAABB3Intersect:function(e,t,i){var r,n;return e[0]>0?(r=e[0]*i[0],n=e[0]*i[3]):(r=e[0]*i[3],n=e[0]*i[0]),e[1]>0?(r+=e[1]*i[1],n+=e[1]*i[4]):(r+=e[1]*i[4],n+=e[1]*i[1]),e[2]>0?(r+=e[2]*i[2],n+=e[2]*i[5]):(r+=e[2]*i[5],n+=e[2]*i[2]),r<=-t&&n<=-t?-1:r>=-t&&n>=-t?1:0},OBB3ToAABB2:function(e){for(var t,i,r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:le.AABB2(),s=le.MAX_DOUBLE,o=le.MAX_DOUBLE,a=le.MIN_DOUBLE,l=le.MIN_DOUBLE,u=0,c=e.length;u<c;u+=4)t=e[u+0],i=e[u+1],(t*=r=1/(e[u+3]||1))<s&&(s=t),(i*=r)<o&&(o=i),t>a&&(a=t),i>l&&(l=i);return n[0]=s,n[1]=o,n[2]=a,n[3]=l,n},expandAABB2:function(e,t){return e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e},expandAABB2Point2:function(e,t){return e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[0]&&(e[2]=t[0]),e[3]<t[1]&&(e[3]=t[1]),e},AABB2ToCanvas:function(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e,n=.5*(e[0]+1),s=.5*(e[1]+1),o=.5*(e[2]+1),a=.5*(e[3]+1);return r[0]=Math.floor(n*t),r[1]=i-Math.floor(a*i),r[2]=Math.floor(o*t),r[3]=i-Math.floor(s*i),r},tangentQuadraticBezier:function(e,t,i,r){return 2*(1-e)*(i-t)+2*e*(r-i)},tangentQuadraticBezier3:function(e,t,i,r,n){return-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*r*(1-e)-3*e*e*r+3*e*e*n},tangentSpline:function(e){return 6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e)},catmullRomInterpolate:function(e,t,i,r,n){var s=.5*(i-e),o=.5*(r-t),a=n*n;return(2*t-2*i+s+o)*(n*a)+(-3*t+3*i-2*s-o)*a+s*n+t},b2p0:function(e,t){var i=1-e;return i*i*t},b2p1:function(e,t){return 2*(1-e)*e*t},b2p2:function(e,t){return e*e*t},b2:function(e,t,i,r){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,r)},b3p0:function(e,t){var i=1-e;return i*i*i*t},b3p1:function(e,t){var i=1-e;return 3*i*i*e*t},b3p2:function(e,t){return 3*(1-e)*e*e*t},b3p3:function(e,t){return e*e*e*t},b3:function(e,t,i,r,n){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,r)+this.b3p3(e,n)},triangleNormal:function(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:le.vec3(),n=t[0]-e[0],s=t[1]-e[1],o=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],u=i[2]-e[2],c=s*u-o*l,A=o*a-n*u,h=n*l-s*a,d=Math.sqrt(c*c+A*A+h*h);return 0===d?(r[0]=0,r[1]=0,r[2]=0):(r[0]=c/d,r[1]=A/d,r[2]=h/d),r},rayTriangleIntersect:function(){var e=new re(3),t=new re(3),i=new re(3),r=new re(3),n=new re(3);return function(s,o,a,l,u,c){c=c||le.vec3();var A=le.subVec3(l,a,e),h=le.subVec3(u,a,t),d=le.cross3Vec3(o,h,i),p=le.dotVec3(A,d);if(p<1e-6)return null;var f=le.subVec3(s,a,r),v=le.dotVec3(f,d);if(v<0||v>p)return null;var g=le.cross3Vec3(f,A,n),m=le.dotVec3(o,g);if(m<0||v+m>p)return null;var _=le.dotVec3(h,g)/p;return c[0]=s[0]+_*o[0],c[1]=s[1]+_*o[1],c[2]=s[2]+_*o[2],c}}(),rayPlaneIntersect:function(){var e=new re(3),t=new re(3),i=new re(3),r=new re(3);return function(n,s,o,a,l,u){u=u||le.vec3(),s=le.normalizeVec3(s,e);var c=le.subVec3(a,o,t),A=le.subVec3(l,o,i),h=le.cross3Vec3(c,A,r);le.normalizeVec3(h,h);var d=-le.dotVec3(o,h),p=-(le.dotVec3(n,h)+d)/le.dotVec3(s,h);return u[0]=n[0]+p*s[0],u[1]=n[1]+p*s[1],u[2]=n[2]+p*s[2],u}}(),cartesianToBarycentric:function(){var e=new re(3),t=new re(3),i=new re(3);return function(r,n,s,o,a){var l=le.subVec3(o,n,e),u=le.subVec3(s,n,t),c=le.subVec3(r,n,i),A=le.dotVec3(l,l),h=le.dotVec3(l,u),d=le.dotVec3(l,c),p=le.dotVec3(u,u),f=le.dotVec3(u,c),v=A*p-h*h;if(0===v)return null;var g=1/v,m=(p*d-h*f)*g,_=(A*f-h*d)*g;return a[0]=1-m-_,a[1]=_,a[2]=m,a}}(),barycentricInsideTriangle:function(e){var t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian:function(e,t,i,r){var n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:le.vec3(),s=e[0],o=e[1],a=e[2];return n[0]=t[0]*s+i[0]*o+r[0]*a,n[1]=t[1]*s+i[1]*o+r[1]*a,n[2]=t[2]*s+i[2]*o+r[2]*a,n},mergeVertices:function(e,t,i,r){var n,s,o,a,l,u,c={},A=[],h=[],d=t?[]:null,p=i?[]:null,f=[],v=Math.pow(10,4),g=0;for(l=0,u=e.length;l<u;l+=3)n=e[l],s=e[l+1],o=e[l+2],void 0===c[a="".concat(Math.round(n*v),"_").concat(Math.round(s*v),"_").concat(Math.round(o*v))]&&(c[a]=h.length/3,h.push(n),h.push(s),h.push(o),t&&(d.push(t[l]),d.push(t[l+1]),d.push(t[l+2])),i&&(p.push(i[g]),p.push(i[g+1]))),A[l/3]=c[a],g+=2;for(l=0,u=r.length;l<u;l++)f[l]=A[r[l]];var m={positions:h,indices:f};return d&&(m.normals=d),p&&(m.uv=p),m},buildNormals:function(){var e=new re(3),t=new re(3),i=new re(3),r=new re(3),n=new re(3),s=new re(3);return function(o,a,l){var u,c,A,h,d,p,f,v,g,m=new Array(o.length/3);for(u=0,c=a.length;u<c;u+=3){A=a[u],h=a[u+1],d=a[u+2],e[0]=o[3*A],e[1]=o[3*A+1],e[2]=o[3*A+2],t[0]=o[3*h],t[1]=o[3*h+1],t[2]=o[3*h+2],i[0]=o[3*d],i[1]=o[3*d+1],i[2]=o[3*d+2],le.subVec3(t,e,r),le.subVec3(i,e,n);var _=le.vec3();le.normalizeVec3(le.cross3Vec3(r,n,s),_),m[A]||(m[A]=[]),m[h]||(m[h]=[]),m[d]||(m[d]=[]),m[A].push(_),m[h].push(_),m[d].push(_)}for(l=l&&l.length===o.length?l:new Float32Array(o.length),u=0,c=m.length;u<c;u++){p=m[u].length,f=0,v=0,g=0;for(var y=0;y<p;y++)f+=m[u][y][0],v+=m[u][y][1],g+=m[u][y][2];l[3*u]=f/p,l[3*u+1]=v/p,l[3*u+2]=g/p}return l}}(),buildTangents:function(){var e=new re(3),t=new re(3),i=new re(3),r=new re(3),n=new re(3),s=new re(3),o=new re(3);return function(a,l,u){for(var c=new Float32Array(a.length),A=0;A<l.length;A+=3){var h=l[A],d=a.subarray(3*h,3*h+3),p=u.subarray(2*h,2*h+2);h=l[A+1];var f=a.subarray(3*h,3*h+3),v=u.subarray(2*h,2*h+2);h=l[A+2];for(var g=a.subarray(3*h,3*h+3),m=u.subarray(2*h,2*h+2),_=le.subVec3(f,d,e),y=le.subVec3(g,d,t),b=le.subVec2(v,p,i),w=le.subVec2(m,p,r),B=1/(b[0]*w[1]-b[1]*w[0]),x=le.mulVec3Scalar(le.subVec3(le.mulVec3Scalar(_,w[1],n),le.mulVec3Scalar(y,b[1],s),o),B,s),P=void 0,C=0;C<3;C++)c[P=3*l[A+C]]+=x[0],c[P+1]+=x[1],c[P+2]+=x[2]}return c}}(),buildPickTriangles:function(e,t,i){for(var r,n,s,o,a,l=t.length,u=i?new Uint16Array(9*l):new Float32Array(9*l),c=new Uint8Array(12*l),A=0,h=0,d=0,p=0;p<l;p+=3)a=A>>24&255,o=A>>16&255,s=A>>8&255,n=255&A,r=3*t[p],u[h++]=e[r],u[h++]=e[r+1],u[h++]=e[r+2],c[d++]=n,c[d++]=s,c[d++]=o,c[d++]=a,r=3*t[p+1],u[h++]=e[r],u[h++]=e[r+1],u[h++]=e[r+2],c[d++]=n,c[d++]=s,c[d++]=o,c[d++]=a,r=3*t[p+2],u[h++]=e[r],u[h++]=e[r+1],u[h++]=e[r+2],c[d++]=n,c[d++]=s,c[d++]=o,c[d++]=a,A++;return{positions:u,colors:c}},faceToVertexNormals:function(e,t){var i,r,n,s,o,a,l,u,c,A,h,d=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},p=d.smoothNormalsAngleThreshold||20,f={},v=[],g={},m=4,_=Math.pow(10,m);for(l=0,c=e.length;l<c;l+=3){a=l/3,r=e[l],n=e[l+1],s=e[l+2],void 0===f[o="".concat(Math.round(r*_),"_").concat(Math.round(n*_),"_").concat(Math.round(s*_))]?f[o]=[a]:f[o].push(a);var y=le.normalizeVec3([t[l],t[l+1],t[l+2]]);v[a]=y,i=le.vec4([y[0],y[1],y[2],1]),g[a]=i}for(o in f)if(f.hasOwnProperty(o)){var b=f[o],w=b.length;for(l=0;l<w;l++){var B=b[l];for(i=g[B],u=0;u<w;u++)if(l!==u){var x=b[u];A=v[B],h=v[x];var P=Math.abs(le.angleVec3(A,h)/le.DEGTORAD);P<p&&(i[0]+=h[0],i[1]+=h[1],i[2]+=h[2],i[3]+=1)}}}for(l=0,c=t.length;l<c;l+=3)i=g[l/3],t[l+0]=i[0]/i[3],t[l+1]=i[1]/i[3],t[l+2]=i[2]/i[3]},transformRay:function(){var e=new re(4),t=new re(4);return function(i,r,n,s,o){e[0]=r[0],e[1]=r[1],e[2]=r[2],e[3]=1,le.transformVec4(i,e,t),s[0]=t[0],s[1]=t[1],s[2]=t[2],e[0]=n[0],e[1]=n[1],e[2]=n[2],le.transformVec3(i,e,t),le.normalizeVec3(t),o[0]=t[0],o[1]=t[1],o[2]=t[2]}}(),canvasPosToWorldRay:(V=new re(16),Q=new re(4),H=new re(4),j=function(e,t,i,r,n){n[0]=e,n[1]=t,n[2]=i,n[3]=1,le.transformVec4(V,n,n),r||le.mulVec4Scalar(n,1/n[3])},function(e,t,i,r,n,s,o){var a="ortho"===r;le.mulMat4(i,t,V),le.inverseMat4(V,V);var l=2*n[0]/e.clientWidth-1,u=1-2*n[1]/e.clientHeight;j(l,u,-1,a,Q),j(l,u,1,a,H),s[0]=Q[0],s[1]=Q[1],s[2]=Q[2],le.subVec3(H,Q,o),le.normalizeVec3(o)}),canvasPosToLocalRay:(O=new re(3),N=new re(3),function(e,t,i,r,n,s,o,a){le.canvasPosToWorldRay(e,t,i,r,s,O,N),le.worldRayToLocalRay(n,O,N,o,a)}),worldRayToLocalRay:function(){var e=new re(16),t=new re(4),i=new re(4);return function(r,n,s,o,a){var l=le.inverseMat4(r,e);t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=1,le.transformVec4(l,t,i),o[0]=i[0],o[1]=i[1],o[2]=i[2],le.transformVec3(l,s,a)}}(),buildKDTree:function(){var e=new Float32Array;function t(i,r,n,s){var o,a,l=new re(6),u={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:l};for(l[0]=l[1]=l[2]=Number.POSITIVE_INFINITY,l[3]=l[4]=l[5]=Number.NEGATIVE_INFINITY,o=0,a=i.length;o<a;++o)for(var c=3*i[o],A=0;A<3;++A){var h=3*r[c+A];n[h]<l[0]&&(l[0]=n[h]),n[h]>l[3]&&(l[3]=n[h]),n[h+1]<l[1]&&(l[1]=n[h+1]),n[h+1]>l[4]&&(l[4]=n[h+1]),n[h+2]<l[2]&&(l[2]=n[h+2]),n[h+2]>l[5]&&(l[5]=n[h+2])}if(i.length<20||s>10)return u.triangles=i,u.leaf=!0,u;e[0]=l[3]-l[0],e[1]=l[4]-l[1],e[2]=l[5]-l[2];var d=0;e[1]>e[d]&&(d=1),e[2]>e[d]&&(d=2),u.splitDim=d;var p=(l[d]+l[d+3])/2,f=new Array(i.length),v=0,g=new Array(i.length),m=0;for(o=0,a=i.length;o<a;++o){var _=r[c=3*i[o]],y=3*r[c+1],b=3*r[c+2];n[3*_+d]<=p||n[y+d]<=p||n[b+d]<=p?f[v++]=i[o]:g[m++]=i[o]}return f.length=v,g.length=m,u.left=t(f,r,n,s+1),u.right=t(g,r,n,s+1),u}return function(e,i){for(var r=e.length/3,n=new Array(r),s=0;s<r;++s)n[s]=s;return t(n,e,i,0)}}(),decompressPosition:function(e,t,i){(i=i||e)[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14]},decompressPositions:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),r=0,n=e.length;r<n;r+=3)i[r+0]=e[r+0]*t[0]+t[12],i[r+1]=e[r+1]*t[5]+t[13],i[r+2]=e[r+2]*t[10]+t[14];return i},decompressUV:function(e,t,i){i[0]=e[0]*t[0]+t[6],i[1]=e[1]*t[4]+t[7]},decompressUVs:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),r=0,n=e.length;r<n;r+=3)i[r+0]=e[r+0]*t[0]+t[6],i[r+1]=e[r+1]*t[4]+t[7];return i},octDecodeVec2:function(e,t){var i=e[0],r=e[1];i=(2*i+1)/255,r=(2*r+1)/255;var n=1-Math.abs(i)-Math.abs(r);n<0&&(i=(1-Math.abs(r))*(i>=0?1:-1),r=(1-Math.abs(i))*(r>=0?1:-1));var s=Math.sqrt(i*i+r*r+n*n);return t[0]=i/s,t[1]=r/s,t[2]=n/s,t},octDecodeVec2s:function(e,t){for(var i=0,r=0,n=e.length;i<n;i+=2){var s=e[i+0],o=e[i+1];s=(2*s+1)/255,o=(2*o+1)/255;var a=1-Math.abs(s)-Math.abs(o);a<0&&(s=(1-Math.abs(o))*(s>=0?1:-1),o=(1-Math.abs(s))*(o>=0?1:-1));var l=Math.sqrt(s*s+o*o+a*a);t[r+0]=s/l,t[r+1]=o/l,t[r+2]=a/l,r+=3}return t}};le.buildEdgeIndices=function(){var e=[],t=[],i=[],r=[],n=[],s=0,o=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),u=le.vec3(),c=le.vec3(),A=le.vec3(),h=le.vec3(),d=le.vec3(),p=le.vec3(),f=le.vec3();return function(v,g,m,_){!function(n,s){var o,a,l,u,c,A,h={},d=Math.pow(10,4),p=0;for(c=0,A=n.length;c<A;c+=3)o=n[c],a=n[c+1],l=n[c+2],void 0===h[u=Math.round(o*d)+"_"+Math.round(a*d)+"_"+Math.round(l*d)]&&(h[u]=p/3,e[p++]=o,e[p++]=a,e[p++]=l),t[c/3]=h[u];for(c=0,A=s.length;c<A;c++)r[c]=t[s[c]],i[r[c]]=s[c]}(v,g),function(t,i){s=0;for(var v=0,g=t;v<g;v+=3){var m=3*r[v],_=3*r[v+1],y=3*r[v+2];i?(o[0]=e[m],o[1]=e[m+1],o[2]=e[m+2],a[0]=e[_],a[1]=e[_+1],a[2]=e[_+2],l[0]=e[y],l[1]=e[y+1],l[2]=e[y+2],le.decompressPosition(o,i,u),le.decompressPosition(a,i,c),le.decompressPosition(l,i,A)):(u[0]=e[m],u[1]=e[m+1],u[2]=e[m+2],c[0]=e[_],c[1]=e[_+1],c[2]=e[_+2],A[0]=e[y],A[1]=e[y+1],A[2]=e[y+2]),le.subVec3(A,c,h),le.subVec3(u,c,d),le.cross3Vec3(h,d,p),le.normalizeVec3(p,f);var b=n[s]||(n[s]={normal:le.vec3()});b.normal[0]=f[0],b.normal[1]=f[1],b.normal[2]=f[2],s++}}(g.length,m);for(var y,b,w,B,x,P,C,M,k,E,F=[],I=Math.cos(le.DEGTORAD*_),T={},D=!1,S=0,R=g.length;S<R;S+=3)for(var U=S/3,L=0;L<3;L++)y=r[S+L],b=r[S+(L+1)%3],void 0===T[x=(w=Math.min(y,b))+","+(B=Math.max(y,b))]?T[x]={index1:w,index2:B,face1:U,face2:void 0}:T[x].face2=U;for(x in T)void 0!==(P=T[x]).face2&&(C=n[P.face1].normal,M=n[P.face2].normal,le.dotVec3(C,M)>I)||(k=i[P.index1],E=i[P.index2],(!D&&k>65535||E>65535)&&(D=!0),F.push(k),F.push(E));return D?new Uint32Array(F):new Uint16Array(F)}}(),le.planeClipsPositions3=function(e,t,i){for(var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:3,n=0,s=i.length;n<s;n+=r){ne[0]=i[n+0]-e[0],ne[1]=i[n+1]-e[1],ne[2]=i[n+2]-e[2];var o=ne[0]*t[0]+ne[1]*t[1]+ne[2]*t[2];if(o<0)return!0}return!1};var ue=new Float32Array(3),ce=function(){function e(t){var i=this;if(E(this,e),!t)throw"Parameter expected: cfg";if(!t.viewer)throw"Parameter expected: cfg.viewer";this.viewer=t.viewer,this._maxTreeDepth=t.maxTreeDepth||15,this._root=null,this._needsRebuild=!0,this._onModelLoaded=this.viewer.scene.on("modelLoaded",(function(e){i._needsRebuild=!0})),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",(function(e){i._needsRebuild=!0}))}return I(e,[{key:"root",get:function(){return this._needsRebuild&&this._rebuild(),this._root}},{key:"_rebuild",value:function(){var e=this.viewer.scene;for(var t in this._root={aabb:e.getAABB()},e.objects){var i=e.objects[t];this._insertEntity(this._root,i,1)}this._needsRebuild=!1}},{key:"_insertEntity",value:function(e,t,i){var r=t.aabb;if(i>=this._maxTreeDepth)return e.entities=e.entities||[],void e.entities.push(t);if(e.left&&le.containsAABB3(e.left.aabb,r))this._insertEntity(e.left,t,i+1);else if(e.right&&le.containsAABB3(e.right.aabb,r))this._insertEntity(e.right,t,i+1);else{var n=e.aabb;ue[0]=n[3]-n[0],ue[1]=n[4]-n[1],ue[2]=n[5]-n[2];var s=0;if(ue[1]>ue[s]&&(s=1),ue[2]>ue[s]&&(s=2),!e.left){var o=n.slice();if(o[s+3]=(n[s]+n[s+3])/2,e.left={aabb:o},le.containsAABB3(o,r))return void this._insertEntity(e.left,t,i+1)}if(!e.right){var a=n.slice();if(a[s]=(n[s]+n[s+3])/2,e.right={aabb:a},le.containsAABB3(a,r))return void this._insertEntity(e.right,t,i+1)}e.entities=e.entities||[],e.entities.push(t)}}},{key:"destroy",value:function(){var e=this.viewer.scene;e.off(this._onModelLoaded),e.off(this._onModelUnloaded),this._root=null,this._needsRebuild=!0}}]),e}(),Ae=function(){function e(){E(this,e),this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}return I(e,[{key:"length",get:function(){return this._length}},{key:"shift",value:function(){if(this._index>=this._headLength){var e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}var t=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,t}},{key:"push",value:function(e){return this._length++,this._tail.push(e),this}},{key:"unshift",value:function(e){return this._head[--this._index]=e,this._length++,this}}]),e}(),he={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var de=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),r=i+e[1],n=i;n<r;++n)t.push(n);return String.fromCharCode.apply(null,t)})).join("");function pe(e,t){return(t&&4!==t?[0,6]:[0,6,12,18]).map((function(t){return de.substr(parseInt(e/(1<<t))%64,1)})).reverse().join("")}var fe=function(){for(var e={},t=window.location.search.substring(1).split("&"),i=0;i<t.length;i++){var r=t[i].split("=");if(void 0===e[r[0]])e[r[0]]=decodeURIComponent(r[1]);else if("string"==typeof e[r[0]]){var n=[e[r[0]],decodeURIComponent(r[1])];e[r[0]]=n}else e[r[0]].push(decodeURIComponent(r[1]))}return e}();var ve,ge={xmlToJson:function e(t,i){if(t.nodeType===t.TEXT_NODE){var r=t.nodeValue;if(null===r.match(/^\s+$/))return r}else if(t.nodeType===t.ELEMENT_NODE||t.nodeType===t.DOCUMENT_NODE){var n={type:t.nodeName,children:[]};if(t.nodeType===t.ELEMENT_NODE)for(var s=0;s<t.attributes.length;s++){var o=t.attributes[s];n[i[o.nodeName]||o.nodeName]=o.nodeValue}for(var a=0;a<t.childNodes.length;a++){(s=e(t.childNodes[a],i))&&n.children.push(s)}return n}},clone:function(e){return JSON.parse(JSON.stringify(e))},compressGuid:function(e){var t=[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30].map((function(t){return parseInt(e.substr(t,2),16)}));return pe(t[0],2)+[1,4,7,10,13].map((function(e){return pe((t[e]<<16)+(t[e+1]<<8)+t[e+2])})).join("")},findNodeOfType:function(e,t){var i=[];return function e(r){r.type===t&&i.push(r),(r.children||[]).forEach((function(t){e(t)}))}(e),i},timeout:function(e){return new Promise((function(t,i){setTimeout(t,e)}))},httpRequest:function(e){return new Promise((function(t,i){var r=new XMLHttpRequest;r.open(e.method||"GET",e.url,!0),r.onload=function(e){4===r.readyState&&(200===r.status?t(r.responseXML):i(r.statusText))},r.send(null)}))},loadJSON:function(e,t,i){var r=function(e){};t=t||r,i=i||r;var n=new XMLHttpRequest;n.overrideMimeType("application/json"),n.open("GET",e,!0),n.addEventListener("load",(function(e){var r=e.target.response;if(200===this.status){var n;try{n=JSON.parse(r)}catch(e){i("utils.loadJSON(): Failed to parse JSON response - ".concat(e))}t(n)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(r))}catch(e){i("utils.loadJSON(): Failed to parse JSON response - ".concat(e))}}else i(e)}),!1),n.addEventListener("error",(function(e){i(e)}),!1),n.send(null)},loadArraybuffer:function(e,t,i){var r=function(e){};t=t||r,i=i||r;var n=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(n){var s=!!n[2],o=n[3];o=window.decodeURIComponent(o),s&&(o=window.atob(o));try{for(var a=new ArrayBuffer(o.length),l=new Uint8Array(a),u=0;u<o.length;u++)l[u]=o.charCodeAt(u);ke.scheduleTask((function(){t(a)}))}catch(e){ke.scheduleTask((function(){i(e)}))}}else{var c=new XMLHttpRequest;c.open("GET",e,!0),c.responseType="arraybuffer",c.onreadystatechange=function(){4===c.readyState&&(200===c.status?t(c.response):i("loadArrayBuffer error : "+c.response))},c.send(null)}},queryString:fe,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"===P(e)&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return ge.isString(e)||ge.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(ge.isNumeric(e)||ge.isString(e)?"".concat(e):e.id)===(ge.isNumeric(t)||ge.isString(t)?"".concat(t):t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){var t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return ge.apply(e,{})},apply:function(e,t){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(var i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(var i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return ge.isNumeric(e)?"".concat(e):"'".concat(e,"'")},concat:function(e,t){var i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var r=i.children;if(r)for(var n=0,s=r.length;n<s;n++){r[n].parent=i.id,e(r[n])}i.children=[]}(e),t}},me={},_e=new Z,ye=new Ae,be={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},we=[],Be=0,xe=0;var Pe,Ce,Me,ke=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(ke.scenes[e.id])return void console.error("[ERROR] Scene ".concat(ge.inQuotes(e.id)," already exists"))}else e.id=_e.addItem({});ke.scenes[e.id]=e;var t=e.ticksPerOcclusionTest,i=e.ticksPerRender;me[e.id]={ticksPerOcclusionTest:t,ticksPerRender:i,renderCountdown:i},he.components.scenes++,e.once("destroyed",(function(){_e.removeItem(e.id),delete ke.scenes[e.id],delete me[e.id],he.components.scenes--}))},this.clear=function(){var e;for(var t in ke.scenes)ke.scenes.hasOwnProperty(t)&&(e=ke.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete ke.scenes[e.id]))},this.scheduleTask=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;ye.push(e),ye.push(t)},this.runTasks=function(){for(var e,t,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1,r=(new Date).getTime(),n=0;ye.length>0&&(i<0||r<i);)e=ye.shift(),(t=ye.shift())?e.call(t):e(),r=(new Date).getTime(),n++;return n},this.getNumTasks=function(){return ye.length}},Ee=function(){var e=Date.now();if(ve=e-Be,Be>0&&ve>0){var t=1e3/ve;xe+=t,we.push(t),we.length>=30&&(xe-=we.shift()),he.frame.fps=Math.round(xe/we.length)}for(var i in ke.scenes)ke.scenes[i].compile();Fe(e),Be=e};Pe=function(){Ee()},Ce=100,Me=Date.now()+Ce,function e(){var t=Date.now()-Me;Pe(),Me+=Ce,setTimeout(e,Math.max(0,Ce-t))}();function Fe(e){var t=ke.runTasks(e+10),i=ke.getNumTasks();he.frame.tasksRun=t,he.frame.tasksScheduled=i,he.frame.tasksBudget=10}!function e(){var t=Date.now();if(ve=t-Be,Be>0&&ve>0){var i=1e3/ve;xe+=i,we.push(i),we.length>=30&&(xe-=we.shift()),he.frame.fps=Math.round(xe/we.length)}Fe(t),function(e){for(var t in be.time=e,ke.scenes)if(ke.scenes.hasOwnProperty(t)){var i=ke.scenes[t];be.sceneId=t,be.startTime=i.startTime,be.deltaTime=null!=be.prevTime?be.time-be.prevTime:0,i.fire("tick",be,!0)}be.prevTime=e}(t),function(){var e,t,i,r,n,s=ke.scenes,o=!1;for(n in s)s.hasOwnProperty(n)&&(e=s[n],(t=me[n])||(t=me[n]={}),i=e.ticksPerOcclusionTest,t.ticksPerOcclusionTest!==i&&(t.ticksPerOcclusionTest=i,t.renderCountdown=i),--e.occlusionTestCountdown<=0&&(e.doOcclusionTest(),e.occlusionTestCountdown=i),r=e.ticksPerRender,t.ticksPerRender!==r&&(t.ticksPerRender=r,t.renderCountdown=r),0==--t.renderCountdown&&(e.render(o),t.renderCountdown=r))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(Ee):requestAnimationFrame(e)}();var Ie=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(E(this,e),this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=i.viewer;else{if("Scene"===t.type)this.scene=t;else{if(!(t instanceof e))throw"Invalid param: owner must be a Component";this.scene=t.scene}this._owner=t}this._dontClear=!!i.dontClear,this._renderer=this.scene._renderer,this.meta=i.meta||{},this.id=i.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,t&&t._own(this)}return I(e,[{key:"type",get:function(){return"Component"}},{key:"isComponent",get:function(){return!0}},{key:"glRedraw",value:function(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}},{key:"glResort",value:function(){this._renderer&&this._renderer.needStateSort()}},{key:"owner",get:function(){return this._owner}},{key:"isType",value:function(e){return this.type===e}},{key:"fire",value:function(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);var r,n=this._eventSubs[e];if(n)for(var s in n)n.hasOwnProperty(s)&&(r=n[s],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}},{key:"on",value:function(e,t,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new Z),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});var r=this._eventSubs[e];r?this._eventSubsNum[e]++:(r={},this._eventSubs[e]=r,this._eventSubsNum[e]=1);var n=this._subIdMap.addItem();r[n]={callback:t,scope:i||this},this._subIdEvents[n]=e;var s=this._events[e];return void 0!==s&&t.call(i||this,s),n}},{key:"off",value:function(e){if(null!=e&&this._subIdEvents){var t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];var i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}}},{key:"once",value:function(e,t,i){var r=this,n=this.on(e,(function(e){r.off(n),t.call(i||this,e)}),i)}},{key:"hasSubs",value:function(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}},{key:"log",value:function(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}},{key:"_message",value:function(e){return" ["+this.type+" "+ge.inQuotes(this.id)+"]: "+e}},{key:"warn",value:function(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}},{key:"error",value:function(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}},{key:"_attach",value:function(e){var t=e.name;if(t){var i=e.component,r=e.sceneDefault,n=e.sceneSingleton,s=e.type,o=e.on,a=!1!==e.recompiles;if(i&&(ge.isNumeric(i)||ge.isString(i))){var l=i;if(!(i=this.scene.components[l]))return void this.error("Component not found: "+ge.inQuotes(l))}if(!i)if(!0===n){var u=this.scene.types[s];for(var c in u)if(u.hasOwnProperty){i=u[c];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===r&&!(i=this.scene[t]))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+ge.inQuotes(i.id));if(s&&!i.isType(s))return void this.error("Expected a "+s+" type or subtype: "+i.type+" "+ge.inQuotes(i.id))}this._attachments||(this._attachments={});var A,h,d,p=this._attached[t];if(p){if(i&&p.id===i.id)return;var f=this._attachments[p.id];for(h=0,d=(A=f.subs).length;h<d;h++)p.off(A[h]);delete this._attached[t],delete this._attachments[p.id];var v=f.params.onDetached;v&&(ge.isFunction(v)?v(p):v.scope?v.callback.call(v.scope,p):v.callback(p)),f.managingLifecycle&&p.destroy()}if(i){var g={params:e,component:i,subs:[],managingLifecycle:!1};g.subs.push(i.once("destroyed",(function(){g.params.component=null,this._attach(g.params)}),this)),a&&g.subs.push(i.on("dirty",(function(){this.fire("dirty",this)}),this)),this._attached[t]=i,this._attachments[i.id]=g;var m,_,y,b,w=e.onAttached;if(w&&(ge.isFunction(w)?w(i):w.scope?w.callback.call(w.scope,i):w.callback(i)),o)for(m in o)if(o.hasOwnProperty(m)){if(_=o[m],ge.isFunction(_)?(y=_,b=null):(y=_.callback,b=_.scope),!y)continue;g.subs.push(i.on(m,y,b))}}return a&&this.fire("dirty",this),this.fire(t,i),i}this.error("Component 'name' expected")}},{key:"_checkComponent",value:function(e,t){if(!t.isComponent){if(!ge.isID(t))return void this.error("Expected a Component or ID");var i=t;if(!(t=this.scene.components[i]))return void this.error("Component not found: "+i)}if(e===t.type){if(t.scene.id===this.scene.id)return t;this.error("Not in same scene: "+t.type)}else this.error("Expected a "+e+" Component")}},{key:"_checkComponent2",value:function(e,t){if(!t.isComponent){if(!ge.isID(t))return void this.error("Expected a Component or ID");var i=t;if(!(t=this.scene.components[i]))return void this.error("Component not found: "+i)}if(t.scene.id===this.scene.id){for(var r=0,n=e.length;r<n;r++)if(e[r]===t.type)return t;return this.error("Expected component types: "+e),null}this.error("Not in same scene: "+t.type)}},{key:"_own",value:function(e){var t=this;this._ownedComponents||(this._ownedComponents={}),this._ownedComponents[e.id]||(this._ownedComponents[e.id]=e),e.once("destroyed",(function(){delete t._ownedComponents[e.id]}),this)}},{key:"_needUpdate",value:function(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():ke.scheduleTask(this._doUpdate,this))}},{key:"_doUpdate",value:function(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}},{key:"scheduleTask",value:function(e){ke.scheduleTask(e,null)}},{key:"_update",value:function(){}},{key:"clear",value:function(){if(this._ownedComponents)for(var e in this._ownedComponents){if(this._ownedComponents.hasOwnProperty(e))this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}},{key:"destroy",value:function(){if(!this.destroyed){var e,t,i,r,n,s;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(i=(t=this._attachments[e]).component,n=0,s=(r=t.subs).length;n<s;n++)i.off(r[n]);t.managingLifecycle&&i.destroy()}if(this._ownedComponents)for(e in this._ownedComponents)this._ownedComponents.hasOwnProperty(e)&&((i=this._ownedComponents[e]).destroy(),delete this._ownedComponents[e]);this.scene._removeComponent(this),this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this._updateScheduled=!1}}}]),e}(),Te=le.vec3(),De=le.vec3(),Se=le.mat4(),Re=function(){function e(){E(this,e),this.normal=le.vec3(),this.offset=0,this.testVertex=le.vec3()}return I(e,[{key:"set",value:function(e,t,i,r){var n=1/Math.sqrt(e*e+t*t+i*i);this.normal[0]=e*n,this.normal[1]=t*n,this.normal[2]=i*n,this.offset=r*n,this.testVertex[0]=this.normal[0]>=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}]),e}(),Ue=I((function e(){E(this,e),this.planes=[new Re,new Re,new Re,new Re,new Re,new Re]}));function Le(e,t,i){var r=le.mulMat4(i,t,Se),n=r[0],s=r[1],o=r[2],a=r[3],l=r[4],u=r[5],c=r[6],A=r[7],h=r[8],d=r[9],p=r[10],f=r[11],v=r[12],g=r[13],m=r[14],_=r[15];e.planes[0].set(a-n,A-l,f-h,_-v),e.planes[1].set(a+n,A+l,f+h,_+v),e.planes[2].set(a-s,A-u,f-d,_-g),e.planes[3].set(a+s,A+u,f+d,_+g),e.planes[4].set(a-o,A-c,f-p,_-m),e.planes[5].set(a+o,A+c,f+p,_+m)}function Oe(e,t){var i=Ue.INSIDE,r=Te,n=De;r[0]=t[0],r[1]=t[1],r[2]=t[2],n[0]=t[3],n[1]=t[4],n[2]=t[5];for(var s=[r,n],o=0;o<6;++o){var a=e.planes[o];if(a.normal[0]*s[a.testVertex[0]][0]+a.normal[1]*s[a.testVertex[1]][1]+a.normal[2]*s[a.testVertex[2]][2]+a.offset<0)return Ue.OUTSIDE;a.normal[0]*s[1-a.testVertex[0]][0]+a.normal[1]*s[1-a.testVertex[1]][1]+a.normal[2]*s[1-a.testVertex[2]][2]+a.offset<0&&(i=Ue.INTERSECT)}return i}Ue.INSIDE=0,Ue.INTERSECT=1,Ue.OUTSIDE=2;var Ne=function(e){m(i,Ie);var t=y(i);function i(){var e,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(E(this,i),!r.viewer)throw"[MarqueePicker] Missing config: viewer";if(!r.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";return(e=t.call(this,r.viewer.scene,r)).viewer=r.viewer,e._objectsKdTree3=r.objectsKdTree3,e._canvasMarqueeCorner1=le.vec2(),e._canvasMarqueeCorner2=le.vec2(),e._canvasMarquee=le.AABB2(),e._marqueeFrustum=new Ue,e._marqueeFrustumProjMat=le.mat4(),e._pickMode=!1,e._marqueeElement=document.createElement("div"),document.body.appendChild(e._marqueeElement),e._marqueeElement.style.position="absolute",e._marqueeElement.style["z-index"]="40000005",e._marqueeElement.style.width="8px",e._marqueeElement.style.height="8px",e._marqueeElement.style.visibility="hidden",e._marqueeElement.style.top="0px",e._marqueeElement.style.left="0px",e._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",e._marqueeElement.style.opacity=1,e._marqueeElement.style["pointer-events"]="none",e}return I(i,[{key:"setMarqueeCorner1",value:function(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}},{key:"setMarqueeCorner2",value:function(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}},{key:"setMarquee",value:function(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}},{key:"setMarqueeVisible",value:function(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}},{key:"getMarqueeVisible",value:function(){return this._marqueVisible}},{key:"setPickMode",value:function(e){if(e!==i.PICK_MODE_INSIDE&&e!==i.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===i.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}},{key:"getPickMode",value:function(){return this._pickMode}},{key:"clear",value:function(){this.fire("clear",{})}},{key:"pick",value:function(){var e=this;this._updateMarquee(),this._buildMarqueeFrustum();var t=[];return(this._canvasMarquee[2]-this._canvasMarquee[0]>3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&function r(n){var s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ue.INTERSECT;if(s===Ue.INTERSECT&&(s=Oe(e._marqueeFrustum,n.aabb)),s!==Ue.OUTSIDE){if(n.entities)for(var o=n.entities,a=0,l=o.length;a<l;a++){var u=o[a];if(u.visible){var c=u.aabb;if(e._pickMode===i.PICK_MODE_INSIDE)Oe(e._marqueeFrustum,c)===Ue.INSIDE&&t.push(u.id);else Oe(e._marqueeFrustum,c)!==Ue.OUTSIDE&&t.push(u.id)}}n.left&&r(n.left,s),n.right&&r(n.right,s)}}(this._objectsKdTree3.root),this.fire("picked",t),t}},{key:"_updateMarquee",value:function(){this._canvasMarquee[0]=Math.min(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[1]=Math.min(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._canvasMarquee[2]=Math.max(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[3]=Math.max(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._marqueeElement.style.width="".concat(this._canvasMarquee[2]-this._canvasMarquee[0],"px"),this._marqueeElement.style.height="".concat(this._canvasMarquee[3]-this._canvasMarquee[1],"px"),this._marqueeElement.style.left="".concat(this._canvasMarquee[0],"px"),this._marqueeElement.style.top="".concat(this._canvasMarquee[1],"px")}},{key:"_buildMarqueeFrustum",value:function(){var e=this.viewer.scene.canvas.canvas,t=e.clientWidth,i=e.clientHeight,r=e.clientLeft,n=e.clientTop,s=2/t,o=2/i,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-r)*s-1,u=(this._canvasMarquee[2]-r)*s-1,c=-(this._canvasMarquee[3]-n)*o+1,A=-(this._canvasMarquee[1]-n)*o+1,h=this.viewer.scene.camera.frustum.near*(17*a);le.frustumMat4(l,u,c*a,A*a,h,1e4,this._marqueeFrustumProjMat),Le(this._marqueeFrustum,this.viewer.scene.camera.viewMatrix,this._marqueeFrustumProjMat)}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._marqueeElement.parentElement&&(this._marqueeElement.parentElement.removeChild(this._marqueeElement),this._marqueeElement=null,this._objectsKdTree3=null)}}]),i}();Ne.PICK_MODE_INTERSECTS=0,Ne.PICK_MODE_INSIDE=1;var Ve=function(e){m(i,Ie);var t=y(i);function i(e){var r;E(this,i),r=t.call(this,e.marqueePicker,e);var n,s,o,a,l,u,c,A=e.marqueePicker,h=A.viewer.scene.canvas.canvas,d=!1,p=!1,f=!1;return h.addEventListener("mousedown",(function(e){r.getActive()&&0===e.button&&(c=setTimeout((function(){var t=A.viewer.scene.input;t.keyDown[t.KEY_CTRL]||A.clear(),n=e.pageX,s=e.pageY,l=e.offsetX,A.setMarqueeCorner1([n,s]),d=!0,A.viewer.cameraControl.pointerEnabled=!1,A.setMarqueeVisible(!0),h.style.cursor="crosshair"}),400),p=!0)})),h.addEventListener("mouseup",(function(e){if(r.getActive()&&(d||f)&&0===e.button){clearTimeout(c),o=e.pageX,a=e.pageY;var t=Math.abs(o-n),i=Math.abs(a-s);d=!1,A.viewer.cameraControl.pointerEnabled=!0,f&&(f=!1),(t>3||i>3)&&A.pick()}})),document.addEventListener("mouseup",(function(e){r.getActive()&&0===e.button&&(clearTimeout(c),d&&(A.setMarqueeVisible(!1),d=!1,p=!1,f=!0,A.viewer.cameraControl.pointerEnabled=!0))}),!0),h.addEventListener("mousemove",(function(e){r.getActive()&&0===e.button&&p&&(clearTimeout(c),d&&(o=e.pageX,a=e.pageY,u=e.offsetX,A.setMarqueeVisible(!0),A.setMarqueeCorner2([o,a]),A.setPickMode(l<u?Ne.PICK_MODE_INSIDE:Ne.PICK_MODE_INTERSECTS)))})),r}return I(i,[{key:"setActive",value:function(e){this._active!==e&&(this._active=e,this.fire("active",this._active))}},{key:"getActive",value:function(){return this._active}},{key:"destroy",value:function(){}}]),i}(),Qe=function(){function e(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E(this,e),this.viewer=t,this.scene=this.viewer.scene,this._circleDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._circleDiv,this.viewer.scene.canvas.canvas),this._circleDiv.style.backgroundColor="transparent",this._circleDiv.style.border="2px solid green",this._circleDiv.style.borderRadius="50px",this._circleDiv.style.width="50px",this._circleDiv.style.height="50px",this._circleDiv.style.margin="-200px -200px",this._circleDiv.style.zIndex="100000",this._circleDiv.style.position="absolute",this._circleDiv.style.pointerEvents="none",this._circlePos=null,this._circleMaxRadius=200,this._circleMinRadius=2,this._active=!1!==i.active,this._visible=!1,this._running=!1,this._destroyed=!1}return I(e,[{key:"start",value:function(e){var t=this;if(!this._destroyed){this._circlePos=e,this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius="".concat(this._circleRadius,"px"),this._circleDiv.style.marginLeft="".concat(this._circlePos[0]-this._circleRadius,"px"),this._circleDiv.style.marginTop="".concat(this._circlePos[1]-this._circleRadius,"px");var i,r=this._circleMaxRadius;this._running=!0,requestAnimationFrame((function e(n){if(t._running){i||(i=n);var s=n-i,o=Math.min(s/300,1),a=r+(2-r)*o;t._circleRadius=a,t._circleDiv.style.width="".concat(t._circleRadius,"px"),t._circleDiv.style.height="".concat(t._circleRadius,"px"),t._circleDiv.style.marginLeft="".concat(t._circlePos[0]-t._circleRadius/2,"px"),t._circleDiv.style.marginTop="".concat(t._circlePos[1]-t._circleRadius/2,"px"),o<1&&requestAnimationFrame(e)}})),this._circleDiv.style.visibility="visible"}}},{key:"stop",value:function(){this._destroyed||(this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius="".concat(this._circleRadius,"px"),this._circleDiv.style.visibility="hidden")}},{key:"durationMs",get:function(){return this._durationMs},set:function(e){this.stop(),this._durationMs=e}},{key:"destroy",value:function(){this._destroyed||(this.stop(),this._circleDiv.parentElement.removeChild(this._circleDiv),this._destroyed=!0)}}]),e}(),He=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};E(this,e),this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=t.messages,this.locale=t.locale}return I(e,[{key:"messages",set:function(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}},{key:"loadMessages",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(var t in e)this._messages[t]=e[t];this.messages=this._messages}},{key:"clearMessages",value:function(){this.messages={}}},{key:"locales",get:function(){return this._locales}},{key:"locale",get:function(){return this._locale},set:function(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}},{key:"translate",value:function(e,t){var i=this._messages[this._locale];if(!i)return null;var r=je(e,i);return r?t?Ge(r,t):r:null}},{key:"translatePlurals",value:function(e,t,i){var r=this._messages[this._locale];if(!r)return null;var n=je(e,r);return(n=0===(t=parseInt(""+t,10))?n.zero:t>1?n.other:n.one)?(n=Ge(n,[t]),i&&(n=Ge(n,i)),n):null}},{key:"fire",value:function(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);var r=this._eventSubs[e];if(r)for(var n in r){if(r.hasOwnProperty(n))r[n].callback(t)}}},{key:"on",value:function(e,t){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new Z),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});var i=this._eventSubs[e];i||(i={},this._eventSubs[e]=i);var r=this._eventSubIDMap.addItem();i[r]={callback:t},this._eventSubEvents[r]=e;var n=this._events[e];return void 0!==n&&t(n),r}},{key:"off",value:function(e){if(null!=e&&this._eventSubEvents){var t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];var i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}}]),e}();function je(e,t){if(t[e])return t[e];for(var i=e.split("."),r=t,n=0,s=i.length;r&&n<s;n++){r=r[i[n]]}return r}function Ge(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return e.replace(/\{\{|\}\}|\{(\d+)\}/g,(function(e,i){return"{{"===e?"{":"}}"===e?"}":t[i]}))}var ze=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).t=n.t,r}return I(i,[{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"tangent",get:function(){return this.getTangent(this._t)}},{key:"length",get:function(){var e=this._getLengths();return e[e.length-1]}},{key:"getTangent",value:function(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,r=e+t;i<0&&(i=0),r>1&&(r=1);var n=this.getPoint(i),s=this.getPoint(r),o=le.subVec3(s,n,[]);return le.normalizeVec3(o,[])}},{key:"getPointAt",value:function(e){var t=this.getUToTMapping(e);return this.getPoint(t)}},{key:"getPoints",value:function(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}},{key:"_getLengths",value:function(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,r=[],n=this.getPoint(0),s=0;for(r.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),s+=le.lenVec3(le.subVec3(t,n,[])),r.push(s),n=t;return this.cacheArcLengths=r,r}},{key:"_updateArcLengths",value:function(){this.needsUpdate=!0,this._getLengths()}},{key:"getUToTMapping",value:function(e,t){var i,r=this._getLengths(),n=0,s=r.length;i=t||e*r[s-1];for(var o,a=0,l=s-1;a<=l;)if((o=r[n=Math.floor(a+(l-a)/2)]-i)<0)a=n+1;else{if(!(o>0)){l=n;break}l=n-1}if(r[n=l]===i)return n/(s-1);var u=r[n];return(n+(i-u)/(r[n+1]-u))/(s-1)}}]),i}(),We=function(e){m(i,ze);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).points=n.points,r.t=n.t,r}return I(i,[{key:"points",get:function(){return this._points},set:function(e){this._points=e||[]}},{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"getPoint",value:function(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,r=Math.floor(i),n=i-r,s=t[0===r?r:r-1],o=t[r],a=t[r>t.length-2?t.length-1:r+1],l=t[r>t.length-3?t.length-1:r+2],u=le.vec3();return u[0]=le.catmullRomInterpolate(s[0],o[0],a[0],l[0],n),u[1]=le.catmullRomInterpolate(s[1],o[1],a[1],l[1],n),u[2]=le.catmullRomInterpolate(s[2],o[2],a[2],l[2],n),u}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}},{key:"getJSON",value:function(){return{points:points,t:this._t}}}]),i}(),Xe=le.vec3(),Ke=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._frames=[],r._eyeCurve=new We(w(r)),r._lookCurve=new We(w(r)),r._upCurve=new We(w(r)),n.frames&&(r.addFrames(n.frames),r.smoothFrameTimes(1)),r}return I(i,[{key:"type",get:function(){return"CameraPath"}},{key:"frames",get:function(){return this._frames}},{key:"eyeCurve",get:function(){return this._eyeCurve}},{key:"lookCurve",get:function(){return this._lookCurve}},{key:"upCurve",get:function(){return this._upCurve}},{key:"saveFrame",value:function(e){var t=this.scene.camera;this.addFrame(e,t.eye,t.look,t.up)}},{key:"addFrame",value:function(e,t,i,r){var n={t:e,eye:t.slice(0),look:i.slice(0),up:r.slice(0)};this._frames.push(n),this._eyeCurve.points.push(n.eye),this._lookCurve.points.push(n.look),this._upCurve.points.push(n.up)}},{key:"addFrames",value:function(e){for(var t,i=0,r=e.length;i<r;i++)t=e[i],this.addFrame(t.t||0,t.eye,t.look,t.up)}},{key:"loadFrame",value:function(e){var t=this.scene.camera;e=(e/=this._frames[this._frames.length-1].t-this._frames[0].t)<0?0:e>1?1:e,t.eye=this._eyeCurve.getPoint(e,Xe),t.look=this._lookCurve.getPoint(e,Xe),t.up=this._upCurve.getPoint(e,Xe)}},{key:"sampleFrame",value:function(e,t,i,r){e=e<0?0:e>1?1:e,this._eyeCurve.getPoint(e,t),this._lookCurve.getPoint(e,i),this._upCurve.getPoint(e,r)}},{key:"smoothFrameTimes",value:function(e){if(0!==this._frames.length){var t=le.vec3(),i=0;this._frames[0].t=0;for(var r=[],n=1,s=this._frames.length;n<s;n++){var o=le.lenVec3(le.subVec3(this._frames[n].eye,this._frames[n-1].eye,t));r[n]=o,i+=o}for(var a=1,l=this._frames.length;a<l;a++){var u=r[a]/i*e;this._frames[a].t=this._frames[a-1].t+u}}}},{key:"clearFrames",value:function(){this._frames=[],this._eyeCurve.points=[],this._lookCurve.points=[],this._upCurve.points=[]}}]),i}(),Ze=le.vec3(),Je=le.vec3(),Ye=le.vec3(),qe=le.vec3(),$e=le.vec3(),et=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._look1=le.vec3(),r._eye1=le.vec3(),r._up1=le.vec3(),r._look2=le.vec3(),r._eye2=le.vec3(),r._up2=le.vec3(),r._orthoScale1=1,r._orthoScale2=1,r._flying=!1,r._flyEyeLookUp=!1,r._flyingEye=!1,r._flyingLook=!1,r._callback=null,r._callbackScope=null,r._time1=null,r._time2=null,r.easing=!1!==n.easing,r.duration=n.duration,r.fit=n.fit,r.fitFOV=n.fitFOV,r.trail=n.trail,r}return I(i,[{key:"type",get:function(){return"CameraFlightAnimation"}},{key:"flyTo",value:function(e,t,i){e=e||this.scene,this._flying&&this.stop(),this._flying=!1,this._flyingEye=!1,this._flyingLook=!1,this._flyingEyeLookUp=!1,this._callback=t,this._callbackScope=i;var r,n,s,o,a,l=this.scene.camera,u=!!e.projection&&e.projection!==l.projection;if(this._eye1[0]=l.eye[0],this._eye1[1]=l.eye[1],this._eye1[2]=l.eye[2],this._look1[0]=l.look[0],this._look1[1]=l.look[1],this._look1[2]=l.look[2],this._up1[0]=l.up[0],this._up1[1]=l.up[1],this._up1[2]=l.up[2],this._orthoScale1=l.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)r=e.aabb;else if(6===e.length)r=e;else if(e.eye&&e.look||e.up)n=e.eye,s=e.look,o=e.up;else if(e.eye)n=e.eye;else if(e.look)s=e.look;else{var c=e;if((ge.isNumeric(c)||ge.isString(c))&&(a=c,!(c=this.scene.components[a])))return this.error("Component not found: "+ge.inQuotes(a)),void(t&&(i?t.call(i):t()));u||(r=c.aabb||this.scene.aabb)}var A=e.poi;if(r){if(r[3]<r[0]||r[4]<r[1]||r[5]<r[2])return;if(r[3]===r[0]&&r[4]===r[1]&&r[5]===r[2])return;r=r.slice();var h=le.getAABB3Center(r);this._look2=A||h;var d=le.subVec3(this._eye1,this._look1,Ze),p=le.normalizeVec3(d),f=A?le.getAABB3DiagPoint(r,A):le.getAABB3Diag(r),v=e.fitFOV||this._fitFOV,g=Math.abs(f/Math.tan(v*le.DEGTORAD));this._orthoScale2=1.1*f,this._eye2[0]=this._look2[0]+p[0]*g,this._eye2[1]=this._look2[1]+p[1]*g,this._eye2[2]=this._look2[2]+p[2]*g,this._up2[0]=this._up1[0],this._up2[1]=this._up1[1],this._up2[2]=this._up1[2],this._flyingEyeLookUp=!0}else(n||s||o)&&(this._flyingEyeLookUp=!!n&&!!s&&!!o,this._flyingEye=!!n&&!s,this._flyingLook=!!s&&!n,n&&(this._eye2[0]=n[0],this._eye2[1]=n[1],this._eye2[2]=n[2]),s&&(this._look2[0]=s[0],this._look2[1]=s[1],this._look2[2]=s[2]),o&&(this._up2[0]=o[0],this._up2[1]=o[1],this._up2[2]=o[2]));u?("ortho"===e.projection&&"ortho"!==l.projection&&(this._projection2="ortho",this._projMatrix1=l.projMatrix.slice(),this._projMatrix2=l.ortho.matrix.slice(),l.projection="customProjection"),"perspective"===e.projection&&"perspective"!==l.projection&&(this._projection2="perspective",this._projMatrix1=l.projMatrix.slice(),this._projMatrix2=l.perspective.matrix.slice(),l.projection="customProjection")):this._projection2=null,this.fire("started",e,!0),this._time1=Date.now(),this._time2=this._time1+(Number.isFinite(e.duration)?1e3*e.duration:this._duration),this._flying=!0,ke.scheduleTask(this._update,this)}},{key:"jumpTo",value:function(e){this._jumpTo(e)}},{key:"_jumpTo",value:function(e){this._flying&&this.stop();var t,i,r,n,s,o=this.scene.camera;if(e.aabb)t=e.aabb;else if(6===e.length)t=e;else if(e.eye||e.look||e.up)r=e.eye,n=e.look,s=e.up;else{var a=e;if((ge.isNumeric(a)||ge.isString(a))&&(i=a,!(a=this.scene.components[i])))return void this.error("Component not found: "+ge.inQuotes(i));t=a.aabb||this.scene.aabb}var l=e.poi;if(t){if(t[3]<=t[0]||t[4]<=t[1]||t[5]<=t[2])return;var u,c=l?le.getAABB3DiagPoint(t,l):le.getAABB3Diag(t);n=l||le.getAABB3Center(t,n),this._trail?le.subVec3(o.look,n,$e):le.subVec3(o.eye,o.look,$e),le.normalizeVec3($e),u=(void 0!==e.fit?e.fit:this._fit)?Math.abs(c/Math.tan((e.fitFOV||this._fitFOV)*le.DEGTORAD)):le.lenVec3(le.subVec3(o.eye,o.look,Ze)),le.mulVec3Scalar($e,u),o.eye=le.addVec3(n,$e,Ze),o.look=n,this.scene.camera.ortho.scale=1.1*c}else(r||n||s)&&(r&&(o.eye=r),n&&(o.look=n),s&&(o.up=s));e.projection&&(o.projection=e.projection)}},{key:"_update",value:function(){if(this._flying){var e=(Date.now()-this._time1)/(this._time2-this._time1),t=e>=1;e>1&&(e=1);var r=this.easing?i._ease(e,0,1,1):e,n=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(le.subVec3(n.eye,n.look,$e),n.eye=le.lerpVec3(r,0,1,this._eye1,this._eye2,Ye),n.look=le.subVec3(Ye,$e,Je)):this._flyingLook&&(n.look=le.lerpVec3(r,0,1,this._look1,this._look2,Je),n.up=le.lerpVec3(r,0,1,this._up1,this._up2,qe)):this._flyingEyeLookUp&&(n.eye=le.lerpVec3(r,0,1,this._eye1,this._eye2,Ye),n.look=le.lerpVec3(r,0,1,this._look1,this._look2,Je),n.up=le.lerpVec3(r,0,1,this._up1,this._up2,qe)),this._projection2){var s="ortho"===this._projection2?i._easeOutExpo(e,0,1,1):i._easeInCubic(e,0,1,1);n.customProjection.matrix=le.lerpMat4(s,0,1,this._projMatrix1,this._projMatrix2)}else n.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return n.ortho.scale=this._orthoScale2,void this.stop();ke.scheduleTask(this._update,this)}}},{key:"stop",value:function(){if(this._flying){this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);var e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}}},{key:"cancel",value:function(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}},{key:"duration",get:function(){return this._duration/1e3},set:function(e){this._duration=Number.isFinite(e)?1e3*e:500,this.stop()}},{key:"fit",get:function(){return this._fit},set:function(e){this._fit=!1!==e}},{key:"fitFOV",get:function(){return this._fitFOV},set:function(e){this._fitFOV=e||45}},{key:"trail",get:function(){return this._trail},set:function(e){this._trail=!!e}},{key:"destroy",value:function(){this.stop(),v(x(i.prototype),"destroy",this).call(this)}}],[{key:"_ease",value:function(e,t,i,r){return-i*(e/=r)*(e-2)+t}},{key:"_easeInCubic",value:function(e,t,i,r){return i*(e/=r)*e*e+t}},{key:"_easeOutExpo",value:function(e,t,i,r){return i*(1-Math.pow(2,-10*e/r))+t}}]),i}(),tt=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._cameraFlightAnimation=new et(w(r)),r._t=0,r.state=i.SCRUBBING,r._playingFromT=0,r._playingToT=0,r._playingRate=n.playingRate||1,r._playingDir=1,r._lastTime=null,r.cameraPath=n.cameraPath,r._tick=r.scene.on("tick",r._updateT,w(r)),r}return I(i,[{key:"type",get:function(){return"CameraPathAnimation"}},{key:"_updateT",value:function(){var e=this._cameraPath;if(e){var t,r,n=performance.now(),s=this._lastTime?.001*(n-this._lastTime):0;if(this._lastTime=n,0!==s)switch(this.state){case i.SCRUBBING:return;case i.PLAYING:if(this._t+=this._playingRate*s,0===(t=this._cameraPath.frames.length)||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=i.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case i.PLAYING_TO:r=this._t+this._playingRate*s*this._playingDir,(this._playingDir<0&&r<=this._playingToT||this._playingDir>0&&r>=this._playingToT)&&(r=this._playingToT,this.state=i.SCRUBBING,this.fire("stopped")),this._t=r,e.loadFrame(this._t)}}}},{key:"_ease",value:function(e,t,i,r){return-i*(e/=r)*(e-2)+t}},{key:"cameraPath",get:function(){return this._cameraPath},set:function(e){this._cameraPath=e}},{key:"rate",get:function(){return this._playingRate},set:function(e){this._playingRate=e}},{key:"play",value:function(){this._cameraPath&&(this._lastTime=null,this.state=i.PLAYING)}},{key:"playToT",value:function(e){this._cameraPath&&(this._playingFromT=this._t,this._playingToT=e,this._playingDir=this._playingToT-this._playingFromT<0?-1:1,this._lastTime=null,this.state=i.PLAYING_TO)}},{key:"playToFrame",value:function(e){var t=this._cameraPath;if(t){var i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}}},{key:"flyToFrame",value:function(e,t){var r=this._cameraPath;if(r){var n=r.frames[e];n?(this.state=i.SCRUBBING,this._cameraFlightAnimation.flyTo(n,t)):this.error("flyToFrame - frame index out of range: "+e)}}},{key:"scrubToT",value:function(e){var t=this._cameraPath;t&&(this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=i.SCRUBBING))}},{key:"scrubToFrame",value:function(e){var t=this._cameraPath;t&&(this.scene.camera&&(t.frames[e]?(t.loadFrame(this._t),this.state=i.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)))}},{key:"stop",value:function(){this.state=i.SCRUBBING,this.fire("stopped")}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this.scene.off(this._tick)}}]),i}();tt.STOPPED=0,tt.SCRUBBING=1,tt.PLAYING=2,tt.PLAYING_TO=3;var it=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),r=t.call(this,e,n),he.memory.meshes++,r}return I(i,[{key:"type",get:function(){return"Geometry"}},{key:"isGeometry",get:function(){return!0}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),he.memory.meshes--}}]),i}(),rt=new Z({}),nt=function(){function e(t){for(var i in E(this,e),this.id=rt.addItem({}),t)t.hasOwnProperty(i)&&(this[i]=t[i])}return I(e,[{key:"destroy",value:function(){rt.removeItem(this.id)}}]),e}(),st=function(){function e(t,i,r,n,s,o,a,l,u){switch(E(this,e),this._gl=t,this.type=i,this.allocated=!1,this.ConstructorType=r.constructor,r.constructor){case Uint8Array:this.itemType=t.UNSIGNED_BYTE,this.itemByteSize=1;break;case Int8Array:this.itemType=t.BYTE,this.itemByteSize=1;break;case Uint16Array:this.itemType=t.UNSIGNED_SHORT,this.itemByteSize=2;break;case Int16Array:this.itemType=t.SHORT,this.itemByteSize=2;break;case Uint32Array:this.itemType=t.UNSIGNED_INT,this.itemByteSize=4;break;case Int32Array:this.itemType=t.INT,this.itemByteSize=4;break;default:this.itemType=t.FLOAT,this.itemByteSize=4}this.usage=o,this.length=0,this.dataLength=n,this.numItems=0,this.itemSize=s,this.normalized=!!a,this.stride=l||0,this.offset=u||0,this._allocate(r)}return I(e,[{key:"_allocate",value:function(e){if(this.allocated=!1,this._handle=this._gl.createBuffer(),!this._handle)throw"Failed to allocate WebGL ArrayBuffer";this._handle&&(this._gl.bindBuffer(this.type,this._handle),this._gl.bufferData(this.type,e.length>this.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}},{key:"setData",value:function(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}},{key:"getData",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.numItems-e;if(!this.allocated)return[];var i=new this.ConstructorType(t*this.itemSize);return this._gl.bindBuffer(this.type,this._handle),this._gl.getBufferSubData(this.type,e*this.itemByteSize*this.itemSize,i,0,t*this.itemSize),i}},{key:"bind",value:function(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}},{key:"unbind",value:function(){this.allocated&&this._gl.bindBuffer(this.type,null)}},{key:"destroy",value:function(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}]),e}(),ot=function(){var e=[],t=[],i=[],r=[],n=[],s=0,o=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),u=le.vec3(),c=le.vec3(),A=le.vec3(),h=le.vec3(),d=le.vec3(),p=le.vec3(),f=le.vec3();return function(v,g,m,_){!function(n,s){var o,a,l,u,c,A,h={},d=Math.pow(10,4),p=0;for(c=0,A=n.length;c<A;c+=3)o=n[c],a=n[c+1],l=n[c+2],void 0===h[u=Math.round(o*d)+"_"+Math.round(a*d)+"_"+Math.round(l*d)]&&(h[u]=p/3,e[p++]=o,e[p++]=a,e[p++]=l),t[c/3]=h[u];for(c=0,A=s.length;c<A;c++)r[c]=t[s[c]],i[r[c]]=s[c]}(v,g),function(t,i){s=0;for(var v=0,g=t;v<g;v+=3){var m=3*r[v],_=3*r[v+1],y=3*r[v+2];i?(o[0]=e[m],o[1]=e[m+1],o[2]=e[m+2],a[0]=e[_],a[1]=e[_+1],a[2]=e[_+2],l[0]=e[y],l[1]=e[y+1],l[2]=e[y+2],le.decompressPosition(o,i,u),le.decompressPosition(a,i,c),le.decompressPosition(l,i,A)):(u[0]=e[m],u[1]=e[m+1],u[2]=e[m+2],c[0]=e[_],c[1]=e[_+1],c[2]=e[_+2],A[0]=e[y],A[1]=e[y+1],A[2]=e[y+2]),le.subVec3(A,c,h),le.subVec3(u,c,d),le.cross3Vec3(h,d,p),le.normalizeVec3(p,f);var b=n[s]||(n[s]={normal:le.vec3()});b.normal[0]=f[0],b.normal[1]=f[1],b.normal[2]=f[2],s++}}(g.length,m);for(var y,b,w,B,x,P,C,M,k,E,F=[],I=Math.cos(le.DEGTORAD*_),T={},D=!1,S=0,R=g.length;S<R;S+=3)for(var U=S/3,L=0;L<3;L++)y=r[S+L],b=r[S+(L+1)%3],void 0===T[x=(w=Math.min(y,b))+","+(B=Math.max(y,b))]?T[x]={index1:w,index2:B,face1:U,face2:void 0}:T[x].face2=U;for(x in T)void 0!==(P=T[x]).face2&&(C=n[P.face1].normal,M=n[P.face2].normal,le.dotVec3(C,M)>I)||(k=i[P.index1],E=i[P.index2],(!D&&k>65535||E>65535)&&(D=!0),F.push(k),F.push(E));return D?new Uint32Array(F):new Uint16Array(F)}}();var at,lt,ut=(at=le.mat4(),lt=le.mat4(),function(e,t){t=t||le.mat4();var i=e[0],r=e[1],n=e[2],s=e[3]-i,o=e[4]-r,a=e[5]-n,l=65535;return le.identityMat4(at),le.translationMat4v(e,at),le.identityMat4(lt),le.scalingMat4v([s/l,o/l,a/l],lt),le.mulMat4(at,lt,t),t}),ct=function(){var e=le.mat4(),t=le.mat4();return function(i,r,n){var s,o=new Uint16Array(i.length),a=new Float32Array([n[0]!==r[0]?65535/(n[0]-r[0]):0,n[1]!==r[1]?65535/(n[1]-r[1]):0,n[2]!==r[2]?65535/(n[2]-r[2]):0]);for(s=0;s<i.length;s+=3)o[s+0]=Math.max(0,Math.min(65535,Math.floor((i[s+0]-r[0])*a[0]))),o[s+1]=Math.max(0,Math.min(65535,Math.floor((i[s+1]-r[1])*a[1]))),o[s+2]=Math.max(0,Math.min(65535,Math.floor((i[s+2]-r[2])*a[2])));return le.identityMat4(e),le.translationMat4v(r,e),le.identityMat4(t),le.scalingMat4v([(n[0]-r[0])/65535,(n[1]-r[1])/65535,(n[2]-r[2])/65535],t),{quantized:o,decodeMatrix:le.mulMat4(e,t,le.identityMat4())}}}();var At=function(){var e=le.mat3(),t=le.mat3();return function(i,r,n){var s,o=new Uint16Array(i.length),a=new Float32Array([65535/(n[0]-r[0]),65535/(n[1]-r[1])]);for(s=0;s<i.length;s+=2)o[s+0]=Math.max(0,Math.min(65535,Math.floor((i[s+0]-r[0])*a[0]))),o[s+1]=Math.max(0,Math.min(65535,Math.floor((i[s+1]-r[1])*a[1])));return le.identityMat3(e),le.translationMat3v(r,e),le.identityMat3(t),le.scalingMat3v([(n[0]-r[0])/65535,(n[1]-r[1])/65535],t),{quantized:o,decodeMatrix:le.mulMat3(e,t,le.identityMat3())}}}();function ht(e,t,i,r){var n=e[t]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2])),s=e[t+1]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2]));if(e[t+2]<0){var o=(1-Math.abs(s))*(n>=0?1:-1),a=(1-Math.abs(n))*(s>=0?1:-1);n=o,s=a}return new Int8Array([Math[i](127.5*n+(n<0?-1:0)),Math[r](127.5*s+(s<0?-1:0))])}function dt(e){var t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;var r=1-Math.abs(t)-Math.abs(i);r<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));var n=Math.sqrt(t*t+i*i+r*r);return[t/n,i/n,r/n]}function pt(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}var ft={getPositionsBounds:function(e){var t,i,r=new Float32Array(3),n=new Float32Array(3);for(t=0;t<3;t++)r[t]=Number.MAX_VALUE,n[t]=-Number.MAX_VALUE;for(t=0;t<e.length;t+=3)for(i=0;i<3;i++)r[i]=Math.min(r[i],e[t+i]),n[i]=Math.max(n[i],e[t+i]);return{min:r,max:n}},createPositionsDecodeMatrix:ut,compressPositions:ct,compressPosition:function(e,t,i){var r=new Float32Array([t[3]!==t[0]?65535/(t[3]-t[0]):0,t[4]!==t[1]?65535/(t[4]-t[1]):0,t[5]!==t[2]?65535/(t[5]-t[2]):0]);i[0]=Math.max(0,Math.min(65535,Math.floor((e[0]-t[0])*r[0]))),i[1]=Math.max(0,Math.min(65535,Math.floor((e[1]-t[1])*r[1]))),i[2]=Math.max(0,Math.min(65535,Math.floor((e[2]-t[2])*r[2])))},decompressPositions:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),r=0,n=e.length;r<n;r+=3)i[r+0]=e[r+0]*t[0]+t[12],i[r+1]=e[r+1]*t[5]+t[13],i[r+2]=e[r+2]*t[10]+t[14];return i},decompressPosition:function(e,t,i){return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i},decompressAABB:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e;return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i[3]=e[3]*t[0]+t[12],i[4]=e[4]*t[5]+t[13],i[5]=e[5]*t[10]+t[14],i},getUVBounds:function(e){var t,i,r=new Float32Array(2),n=new Float32Array(2);for(t=0;t<2;t++)r[t]=Number.MAX_VALUE,n[t]=-Number.MAX_VALUE;for(t=0;t<e.length;t+=2)for(i=0;i<2;i++)r[i]=Math.min(r[i],e[t+i]),n[i]=Math.max(n[i],e[t+i]);return{min:r,max:n}},compressUVs:At,decompressUVs:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),r=0,n=e.length;r<n;r+=3)i[r+0]=e[r+0]*t[0]+t[6],i[r+1]=e[r+1]*t[4]+t[7];return i},decompressUV:function(e,t,i){i[0]=e[0]*t[0]+t[6],i[1]=e[1]*t[4]+t[7]},compressNormals:function(e){for(var t,i,r,n,s=new Int8Array(e.length),o=0;o<e.length;o+=3)i=t=ht(e,o,"floor","floor"),r=n=pt(e,o,dt(t)),(r=pt(e,o,dt(t=ht(e,o,"ceil","floor"))))>n&&(i=t,n=r),(r=pt(e,o,dt(t=ht(e,o,"floor","ceil"))))>n&&(i=t,n=r),(r=pt(e,o,dt(t=ht(e,o,"ceil","ceil"))))>n&&(i=t,n=r),s[o]=i[0],s[o+1]=i[1];return s},decompressNormals:function(e,t){for(var i=0,r=0,n=e.length;i<n;i+=2){var s=e[i+0],o=e[i+1];s=(2*s+1)/255,o=(2*o+1)/255;var a=1-Math.abs(s)-Math.abs(o);a<0&&(s=(1-Math.abs(o))*(s>=0?1:-1),o=(1-Math.abs(s))*(o>=0?1:-1));var l=Math.sqrt(s*s+o*o+a*a);t[r+0]=s/l,t[r+1]=o/l,t[r+2]=a/l,r+=3}return t},decompressNormal:function(e,t){var i=e[0],r=e[1];i=(2*i+1)/255,r=(2*r+1)/255;var n=1-Math.abs(i)-Math.abs(r);n<0&&(i=(1-Math.abs(r))*(i>=0?1:-1),r=(1-Math.abs(i))*(r>=0?1:-1));var s=Math.sqrt(i*i+r*r+n*n);return t[0]=i/s,t[1]=r/s,t[2]=n/s,t}},vt=he.memory,gt=le.AABB3(),mt=function(e){m(i,it);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E(this,i),(r=t.call(this,e,n))._state=new nt({compressGeometry:!!n.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),r._numTriangles=0,r._edgeThreshold=n.edgeThreshold||10,r._edgeIndicesBuf=null,r._pickTrianglePositionsBuf=null,r._pickTriangleColorsBuf=null,r._aabbDirty=!0,r._boundingSphere=!0,r._aabb=null,r._aabbDirty=!0,r._obb=null,r._obbDirty=!0;var s=r._state,o=r.scene.canvas.gl;switch(n.primitive=n.primitive||"triangles",n.primitive){case"points":s.primitive=o.POINTS,s.primitiveName=n.primitive;break;case"lines":s.primitive=o.LINES,s.primitiveName=n.primitive;break;case"line-loop":s.primitive=o.LINE_LOOP,s.primitiveName=n.primitive;break;case"line-strip":s.primitive=o.LINE_STRIP,s.primitiveName=n.primitive;break;case"triangles":s.primitive=o.TRIANGLES,s.primitiveName=n.primitive;break;case"triangle-strip":s.primitive=o.TRIANGLE_STRIP,s.primitiveName=n.primitive;break;case"triangle-fan":s.primitive=o.TRIANGLE_FAN,s.primitiveName=n.primitive;break;default:r.error("Unsupported value for 'primitive': '"+n.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),s.primitive=o.TRIANGLES,s.primitiveName=n.primitive}if(n.positions)if(r._state.compressGeometry){var a=ft.getPositionsBounds(n.positions),l=ft.compressPositions(n.positions,a.min,a.max);s.positions=l.quantized,s.positionsDecodeMatrix=l.decodeMatrix}else s.positions=n.positions.constructor===Float32Array?n.positions:new Float32Array(n.positions);if(n.colors&&(s.colors=n.colors.constructor===Float32Array?n.colors:new Float32Array(n.colors)),n.uv)if(r._state.compressGeometry){var u=ft.getUVBounds(n.uv),c=ft.compressUVs(n.uv,u.min,u.max);s.uv=c.quantized,s.uvDecodeMatrix=c.decodeMatrix}else s.uv=n.uv.constructor===Float32Array?n.uv:new Float32Array(n.uv);return n.normals&&(r._state.compressGeometry?s.normals=ft.compressNormals(n.normals):s.normals=n.normals.constructor===Float32Array?n.normals:new Float32Array(n.normals)),n.indices&&(s.indices=n.indices.constructor===Uint32Array||n.indices.constructor===Uint16Array?n.indices:new Uint32Array(n.indices),"triangles"===r._state.primitiveName&&(r._numTriangles=n.indices.length/3)),r._buildHash(),vt.meshes++,r._buildVBOs(),r}return I(i,[{key:"type",get:function(){return"ReadableGeometry"}},{key:"isReadableGeometry",get:function(){return!0}},{key:"_buildVBOs",value:function(){var e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new st(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),vt.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new st(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),vt.positions+=e.positionsBuf.numItems),e.normals){var i=e.compressGeometry;e.normalsBuf=new st(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),vt.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new st(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),vt.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new st(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),vt.uvs+=e.uvBuf.numItems)}},{key:"_buildHash",value:function(){var e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}},{key:"_getEdgeIndices",value:function(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}},{key:"_getPickTrianglePositions",value:function(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}},{key:"_getPickTriangleColors",value:function(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}},{key:"_buildEdgeIndices",value:function(){var e=this._state;if(e.positions&&e.indices){var t=this.scene.canvas.gl,i=ot(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new st(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),vt.indices+=this._edgeIndicesBuf.numItems}}},{key:"_buildPickTriangleVBOs",value:function(){var e=this._state;if(e.positions&&e.indices){var t=this.scene.canvas.gl,i=le.buildPickTriangles(e.positions,e.indices,e.compressGeometry),r=i.positions,n=i.colors;this._pickTrianglePositionsBuf=new st(t,t.ARRAY_BUFFER,r,r.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new st(t,t.ARRAY_BUFFER,n,n.length,4,t.STATIC_DRAW,!0),vt.positions+=this._pickTrianglePositionsBuf.numItems,vt.colors+=this._pickTriangleColorsBuf.numItems}}},{key:"_buildPickVertexVBOs",value:function(){}},{key:"_webglContextLost",value:function(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextLost()}},{key:"_webglContextRestored",value:function(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextRestored(),this._buildVBOs(),this._edgeIndicesBuf=null,this._pickVertexPositionsBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._pickVertexPositionsBuf=null,this._pickVertexColorsBuf=null}},{key:"primitive",get:function(){return this._state.primitiveName}},{key:"compressGeometry",get:function(){return this._state.compressGeometry}},{key:"positions",get:function(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),ft.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null},set:function(e){var t=this._state,i=t.positions;if(i)if(i.length===e.length){if(this._state.compressGeometry){var r=ft.getPositionsBounds(e),n=ft.compressPositions(e,r.min,r.max);e=n.quantized,t.positionsDecodeMatrix=n.decodeMatrix}i.set(e),t.positionsBuf&&t.positionsBuf.setData(i),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}},{key:"normals",get:function(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){var e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),ft.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry normals - quantized geometry is immutable");else{var t=this._state,i=t.normals;i?i.length===e.length?(i.set(e),t.normalsBuf&&t.normalsBuf.setData(i),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}}},{key:"uv",get:function(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),ft.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry UVs - quantized geometry is immutable");else{var t=this._state,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}}},{key:"colors",get:function(){return this._state.colors},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry colors - quantized geometry is immutable");else{var t=this._state,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}}},{key:"indices",get:function(){return this._state.indices}},{key:"aabb",get:function(){return this._aabbDirty&&(this._aabb||(this._aabb=le.AABB3()),le.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}},{key:"obb",get:function(){return this._obbDirty&&(this._obb||(this._obb=le.OBB3()),le.positions3ToAABB3(this._state.positions,gt,this._state.positionsDecodeMatrix),le.AABB3ToOBB3(gt,this._obb),this._obbDirty=!1),this._obb}},{key:"_getMetrics",value:function(){if(!("_metrics"in this))switch(this._state.primitiveName){case"solid":case"surface":case"triangles":for(var e=this._state.indices,t=this._state.positions,i=function(i,r){for(var n=3*e[i],s=0;s<3;++s)r[s]=t[n+s];return r},r=[le.vec3(),le.vec3(),le.vec3(),le.vec3()],n=0,s=le.vec3([0,0,0]),o=0;o<e.length;o+=3){var a=i(o,r[0]),l=i(o+1,r[1]),u=i(o+2,r[2]);le.addVec3(a,l,r[3]),le.addVec3(u,r[3],r[3]);var c=le.lenVec3(le.cross3Vec3(le.subVec3(l,a,r[1]),le.subVec3(u,a,r[2]),r[0]))/2;n+=c,le.mulVec3Scalar(r[3],c,r[3]),le.addVec3(s,r[3],s)}this._metrics={surfaceArea:n,centroid:le.mulVec3Scalar(s,1/n/3,s)};break;default:this._metrics={surfaceArea:0}}return this._metrics}},{key:"surfaceArea",get:function(){return this._getMetrics().surfaceArea}},{key:"centroid",get:function(){return this._getMetrics().centroid}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"_setAABBDirty",value:function(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this);var e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),vt.meshes--}}]),i}(),_t=he.memory,yt=le.AABB3(),bt=function(e){m(i,it);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E(this,i),(r=t.call(this,e,n))._state=new nt({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),r._numTriangles=0,r._edgeThreshold=n.edgeThreshold||10,r._aabb=null,r._obb=le.OBB3();var s,o=r._state,a=r.scene.canvas.gl;switch(n.primitive=n.primitive||"triangles",n.primitive){case"points":o.primitive=a.POINTS,o.primitiveName=n.primitive;break;case"lines":o.primitive=a.LINES,o.primitiveName=n.primitive;break;case"line-loop":o.primitive=a.LINE_LOOP,o.primitiveName=n.primitive;break;case"line-strip":o.primitive=a.LINE_STRIP,o.primitiveName=n.primitive;break;case"triangles":o.primitive=a.TRIANGLES,o.primitiveName=n.primitive;break;case"triangle-strip":o.primitive=a.TRIANGLE_STRIP,o.primitiveName=n.primitive;break;case"triangle-fan":o.primitive=a.TRIANGLE_FAN,o.primitiveName=n.primitive;break;default:r.error("Unsupported value for 'primitive': '"+n.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),o.primitive=a.TRIANGLES,o.primitiveName=n.primitive}if(!n.positions)return r.error("Config expected: positions"),b(r);if(!n.indices)return r.error("Config expected: indices"),b(r);var l=n.positionsDecodeMatrix;if(l);else{var u=ft.getPositionsBounds(n.positions),c=ft.compressPositions(n.positions,u.min,u.max);s=c.quantized,o.positionsDecodeMatrix=c.decodeMatrix,o.positionsBuf=new st(a,a.ARRAY_BUFFER,s,s.length,3,a.STATIC_DRAW),_t.positions+=o.positionsBuf.numItems,le.positions3ToAABB3(n.positions,r._aabb),le.positions3ToAABB3(s,yt,o.positionsDecodeMatrix),le.AABB3ToOBB3(yt,r._obb)}if(n.colors){var A=n.colors.constructor===Float32Array?n.colors:new Float32Array(n.colors);o.colorsBuf=new st(a,a.ARRAY_BUFFER,A,A.length,4,a.STATIC_DRAW),_t.colors+=o.colorsBuf.numItems}if(n.uv){var h=ft.getUVBounds(n.uv),d=ft.compressUVs(n.uv,h.min,h.max),p=d.quantized;o.uvDecodeMatrix=d.decodeMatrix,o.uvBuf=new st(a,a.ARRAY_BUFFER,p,p.length,2,a.STATIC_DRAW),_t.uvs+=o.uvBuf.numItems}if(n.normals){var f=ft.compressNormals(n.normals),v=o.compressGeometry;o.normalsBuf=new st(a,a.ARRAY_BUFFER,f,f.length,3,a.STATIC_DRAW,v),_t.normals+=o.normalsBuf.numItems}var g=n.indices.constructor===Uint32Array||n.indices.constructor===Uint16Array?n.indices:new Uint32Array(n.indices);o.indicesBuf=new st(a,a.ELEMENT_ARRAY_BUFFER,g,g.length,1,a.STATIC_DRAW),_t.indices+=o.indicesBuf.numItems;var m=ot(s,g,o.positionsDecodeMatrix,r._edgeThreshold);return r._edgeIndicesBuf=new st(a,a.ELEMENT_ARRAY_BUFFER,m,m.length,1,a.STATIC_DRAW),"triangles"===r._state.primitiveName&&(r._numTriangles=n.indices.length/3),r._buildHash(),_t.meshes++,r}return I(i,[{key:"type",get:function(){return"VBOGeometry"}},{key:"isVBOGeometry",get:function(){return!0}},{key:"_buildHash",value:function(){var e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positionsBuf&&t.push("p"),e.colorsBuf&&t.push("c"),(e.normalsBuf||e.autoVertexNormals)&&t.push("n"),e.uvBuf&&t.push("u"),t.push("cp"),t.push(";"),e.hash=t.join("")}},{key:"_getEdgeIndices",value:function(){return this._edgeIndicesBuf}},{key:"primitive",get:function(){return this._state.primitiveName}},{key:"aabb",get:function(){return this._aabb}},{key:"obb",get:function(){return this._obb}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this);var e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),e.destroy(),_t.meshes--}}]),i}(),wt={};function Bt(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((function(i,r){t.src||(console.error("load3DSGeometry: Parameter expected: src"),r());var n=e.canvas.spinner;n.processes++,ge.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("load3DSGeometry: no data loaded"),n.processes--,r());var s=wt.parse.from3DS(e).edit.objects[0].mesh,o=s.vertices,a=s.uvt,l=s.indices;n.processes--,i(ge.apply(t,{primitive:"triangles",positions:o,normals:null,uv:a,indices:l}))}),(function(e){console.error("load3DSGeometry: "+e),n.processes--,r()}))}))}function xt(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((function(i,r){t.src||(console.error("loadOBJGeometry: Parameter expected: src"),r());var n=e.canvas.spinner;n.processes++,ge.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("loadOBJGeometry: no data loaded"),n.processes--,r());for(var s=wt.parse.fromOBJ(e),o=wt.edit.unwrap(s.i_verts,s.c_verts,3),a=wt.edit.unwrap(s.i_norms,s.c_norms,3),l=wt.edit.unwrap(s.i_uvt,s.c_uvt,2),u=new Int32Array(s.i_verts.length),c=0;c<s.i_verts.length;c++)u[c]=c;n.processes--,i(ge.apply(t,{primitive:"triangles",positions:o,normals:a.length>0?a:null,autoNormals:0===a.length,uv:l,indices:u}))}),(function(e){console.error("loadOBJGeometry: "+e),n.processes--,r()}))}))}function Pt(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);var i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);var r=e.zSize||1;r<0&&(console.error("negative zSize not allowed - will invert"),r*=-1);var n=e.center,s=n?n[0]:0,o=n?n[1]:0,a=n?n[2]:0,l=-t+s,u=-i+o,c=-r+a,A=t+s,h=i+o,d=r+a;return ge.apply(e,{positions:[A,h,d,l,h,d,l,u,d,A,u,d,A,h,d,A,u,d,A,u,c,A,h,c,A,h,d,A,h,c,l,h,c,l,h,d,l,h,d,l,h,c,l,u,c,l,u,d,l,u,c,A,u,c,A,u,d,l,u,d,A,u,c,l,u,c,l,h,c,A,h,c],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}function Ct(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);var i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);var r=e.zSize||1;r<0&&(console.error("negative zSize not allowed - will invert"),r*=-1);var n=e.center,s=n?n[0]:0,o=n?n[1]:0,a=n?n[2]:0,l=-t+s,u=-i+o,c=-r+a,A=t+s,h=i+o,d=r+a;return ge.apply(e,{primitive:"lines",positions:[l,u,c,l,u,d,l,h,c,l,h,d,A,u,c,A,u,d,A,h,c,A,h,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function Mt(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Ct({id:e.id,center:[(e.aabb[0]+e.aabb[3])/2,(e.aabb[1]+e.aabb[4])/2,(e.aabb[2]+e.aabb[5])/2],xSize:Math.abs(e.aabb[3]-e.aabb[0])/2,ySize:Math.abs(e.aabb[4]-e.aabb[1])/2,zSize:Math.abs(e.aabb[5]-e.aabb[2])/2})}function kt(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);var i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);var r=e.height||1;r<0&&(console.error("negative height not allowed - will invert"),r*=-1);var n=e.radialSegments||32;n<0&&(console.error("negative radialSegments not allowed - will invert"),n*=-1),n<3&&(n=3);var s=e.heightSegments||1;s<0&&(console.error("negative heightSegments not allowed - will invert"),s*=-1),s<1&&(s=1);var o,a,l,u,c,A,h,d,p,f,v,g=!!e.openEnded,m=e.center,_=m?m[0]:0,y=m?m[1]:0,b=m?m[2]:0,w=r/2,B=r/s,x=2*Math.PI/n,P=1/n,C=(t-i)/s,M=[],k=[],E=[],F=[],I=(90-180*Math.atan(r/(i-t))/Math.PI)/90;for(o=0;o<=s;o++)for(c=t-o*C,A=w-o*B,a=0;a<=n;a++)l=Math.sin(a*x),u=Math.cos(a*x),k.push(c*l),k.push(I),k.push(c*u),E.push(a*P),E.push(1*o/s),M.push(c*l+_),M.push(A+y),M.push(c*u+b);for(o=0;o<s;o++)for(a=0;a<=n;a++)d=(h=o*(n+1)+a)+n,F.push(h),F.push(d),F.push(d+1),F.push(h),F.push(d+1),F.push(h+1);if(!g&&t>0){for(p=M.length/3,k.push(0),k.push(1),k.push(0),E.push(.5),E.push(.5),M.push(0+_),M.push(w+y),M.push(0+b),a=0;a<=n;a++)l=Math.sin(a*x),u=Math.cos(a*x),f=.5*Math.sin(a*x)+.5,v=.5*Math.cos(a*x)+.5,k.push(t*l),k.push(1),k.push(t*u),E.push(f),E.push(v),M.push(t*l+_),M.push(w+y),M.push(t*u+b);for(a=0;a<n;a++)m=p,h=p+1+a,F.push(h),F.push(h+1),F.push(m)}if(!g&&i>0){for(p=M.length/3,k.push(0),k.push(-1),k.push(0),E.push(.5),E.push(.5),M.push(0+_),M.push(0-w+y),M.push(0+b),a=0;a<=n;a++)l=Math.sin(a*x),u=Math.cos(a*x),f=.5*Math.sin(a*x)+.5,v=.5*Math.cos(a*x)+.5,k.push(i*l),k.push(-1),k.push(i*u),E.push(f),E.push(v),M.push(i*l+_),M.push(0-w+y),M.push(i*u+b);for(a=0;a<n;a++)m=p,h=p+1+a,F.push(m),F.push(h+1),F.push(h)}return ge.apply(e,{positions:M,normals:k,uv:E,indices:F})}function Et(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);var i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1);for(var r=(t=t||10)/(i=i||10),n=t/2,s=[],o=[],a=0,l=0,u=-n;l<=i;l++,u+=r)s.push(-n),s.push(0),s.push(u),s.push(n),s.push(0),s.push(u),s.push(u),s.push(0),s.push(-n),s.push(u),s.push(0),s.push(n),o.push(a++),o.push(a++),o.push(a++),o.push(a++);return ge.apply(e,{primitive:"lines",positions:s,indices:o})}function Ft(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);var i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);var r=e.xSegments||1;r<0&&(console.error("negative xSegments not allowed - will invert"),r*=-1),r<1&&(r=1);var n=e.xSegments||1;n<0&&(console.error("negative zSegments not allowed - will invert"),n*=-1),n<1&&(n=1);var s,o,a,l,u,c,A,h=e.center,d=h?h[0]:0,p=h?h[1]:0,f=h?h[2]:0,v=t/2,g=i/2,m=Math.floor(r)||1,_=Math.floor(n)||1,y=m+1,b=_+1,w=t/m,B=i/_,x=new Float32Array(y*b*3),P=new Float32Array(y*b*3),C=new Float32Array(y*b*2),M=0,k=0;for(s=0;s<b;s++){var E=s*B-g;for(o=0;o<y;o++)a=o*w-v,x[M]=a+d,x[M+1]=p,x[M+2]=-E+f,P[M+1]=1,C[k]=o/m,C[k+1]=(_-s)/_,M+=3,k+=2}M=0;var F=new(x.length/3>65535?Uint32Array:Uint16Array)(m*_*6);for(s=0;s<_;s++)for(o=0;o<m;o++)l=o+y*s,u=o+y*(s+1),c=o+1+y*(s+1),A=o+1+y*s,F[M]=A,F[M+1]=u,F[M+2]=l,F[M+3]=A,F[M+4]=c,F[M+5]=u,M+=6;return ge.apply(e,{positions:x,normals:P,uv:C,indices:F})}function It(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.lod||1,i=e.center?e.center[0]:0,r=e.center?e.center[1]:0,n=e.center?e.center[2]:0,s=e.radius||1;s<0&&(console.error("negative radius not allowed - will invert"),s*=-1);var o=e.heightSegments||18;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),(o=Math.floor(t*o))<18&&(o=18);var a=e.widthSegments||18;a<0&&(console.error("negative widthSegments not allowed - will invert"),a*=-1),(a=Math.floor(t*a))<18&&(a=18);var l,u,c,A,h,d,p,f,v,g,m,_,y,b,w=[],B=[],x=[],P=[];for(l=0;l<=o;l++)for(c=l*Math.PI/o,A=Math.sin(c),h=Math.cos(c),u=0;u<=a;u++)d=2*u*Math.PI/a,p=Math.sin(d),f=Math.cos(d)*A,v=h,g=p*A,m=1-u/a,_=l/o,B.push(f),B.push(v),B.push(g),x.push(m),x.push(_),w.push(i+s*f),w.push(r+s*v),w.push(n+s*g);for(l=0;l<o;l++)for(u=0;u<a;u++)b=(y=l*(a+1)+u)+a+1,P.push(y+1),P.push(b+1),P.push(b),P.push(y+1),P.push(b),P.push(y);return ge.apply(e,{positions:w,normals:B,uv:x,indices:P})}function Tt(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.radius||1;t<0&&(console.error("negative radius not allowed - will invert"),t*=-1),t*=.5;var i=e.tube||.3;i<0&&(console.error("negative tube not allowed - will invert"),i*=-1);var r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<4&&(r=4);var n=e.tubeSegments||24;n<0&&(console.error("negative tubeSegments not allowed - will invert"),n*=-1),n<4&&(n=4);var s=e.arc||2*Math.PI;s<0&&(console.warn("negative arc not allowed - will invert"),s*=-1),s>360&&(s=360);var o,a,l,u,c,A,h,d,p,f,v,g,m=e.center,_=m?m[0]:0,y=m?m[1]:0,b=m?m[2]:0,w=[],B=[],x=[],P=[];for(d=0;d<=n;d++)for(h=0;h<=r;h++)o=h/r*s,a=.785398+d/n*Math.PI*2,_=t*Math.cos(o),y=t*Math.sin(o),l=(t+i*Math.cos(a))*Math.cos(o),u=(t+i*Math.cos(a))*Math.sin(o),c=i*Math.sin(a),w.push(l+_),w.push(u+y),w.push(c+b),x.push(1-h/r),x.push(d/n),A=le.normalizeVec3(le.subVec3([l,u,c],[_,y,b],[]),[]),B.push(A[0]),B.push(A[1]),B.push(A[2]);for(d=1;d<=n;d++)for(h=1;h<=r;h++)p=(r+1)*d+h-1,f=(r+1)*(d-1)+h-1,v=(r+1)*(d-1)+h,g=(r+1)*d+h,P.push(p),P.push(f),P.push(v),P.push(v),P.push(g),P.push(p);return ge.apply(e,{positions:w,normals:B,uv:x,indices:P})}wt.load=function(e,t){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(e){t(e.target.response)},i.send()},wt.save=function(e,t){var i="data:application/octet-stream;base64,"+btoa(wt.parse._buffToStr(e));window.location.href=i},wt.clone=function(e){return JSON.parse(JSON.stringify(e))},wt.bin={},wt.bin.f=new Float32Array(1),wt.bin.fb=new Uint8Array(wt.bin.f.buffer),wt.bin.rf=function(e,t){for(var i=wt.bin.f,r=wt.bin.fb,n=0;n<4;n++)r[n]=e[t+n];return i[0]},wt.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},wt.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},wt.bin.rASCII0=function(e,t){for(var i="";0!=e[t];)i+=String.fromCharCode(e[t++]);return i},wt.bin.wf=function(e,t,i){new Float32Array(e.buffer,t,1)[0]=i},wt.bin.wsl=function(e,t,i){e[t]=i,e[t+1]=i>>8},wt.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},wt.parse={},wt.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",r=0;r<t.length;r++)i=i.concat(String.fromCharCode(t[r]));return i},wt.parse._strToBuff=function(e){for(var t=new ArrayBuffer(e.length),i=new Uint8Array(t),r=0;r<e.length;r++)i[r]=e.charCodeAt(r);return t},wt.parse._readLine=function(e,t){for(var i="";10!=e[t];)i+=String.fromCharCode(e[t++]);return i},wt.parse.fromJSON=function(e){return JSON.parse(wt.parse._buffToStr(e))},wt.parse.toJSON=function(e){var t=JSON.stringify(e);return wt.parse._strToBuff(t)},wt.parse.fromOBJ=function(e){for(var t={groups:{},c_verts:[],c_uvt:[],c_norms:[],i_verts:[],i_uvt:[],i_norms:[]},i={from:0,to:0},r=0,n=new Uint8Array(e);r<n.length;){var s=wt.parse._readLine(n,r);r+=s.length+1;var o=(s=(s=s.replace(/ +(?= )/g,"")).replace(/(^\s+|\s+$)/g,"")).split(" ");if("g"==o[0]&&(i.to=t.i_verts.length,null==t.groups[o[1]]&&(t.groups[o[1]]={from:t.i_verts.length,to:0}),i=t.groups[o[1]]),"v"==o[0]){var a=parseFloat(o[1]),l=parseFloat(o[2]),u=parseFloat(o[3]);t.c_verts.push(a,l,u)}if("vt"==o[0]){a=parseFloat(o[1]),l=1-parseFloat(o[2]);t.c_uvt.push(a,l)}if("vn"==o[0]){a=parseFloat(o[1]),l=parseFloat(o[2]),u=parseFloat(o[3]);t.c_norms.push(a,l,u)}if("f"==o[0]){var c=o[1].split("/"),A=o[2].split("/"),h=o[3].split("/"),d=parseInt(c[0])-1,p=parseInt(A[0])-1,f=parseInt(h[0])-1,v=parseInt(c[1])-1,g=parseInt(A[1])-1,m=parseInt(h[1])-1,_=parseInt(c[2])-1,y=parseInt(A[2])-1,b=parseInt(h[2])-1,w=t.c_verts.length/3,B=t.c_uvt.length/2,x=t.c_norms.length/3;if(d<0&&(d=w+d+1),p<0&&(p=w+p+1),f<0&&(f=w+f+1),v<0&&(v=B+v+1),g<0&&(g=B+g+1),m<0&&(m=B+m+1),_<0&&(_=x+_+1),y<0&&(y=x+y+1),b<0&&(b=x+b+1),t.i_verts.push(d,p,f),t.i_uvt.push(v,g,m),t.i_norms.push(_,y,b),5==o.length){var P=o[4].split("/"),C=parseInt(P[0])-1,M=parseInt(P[1])-1,k=parseInt(P[2])-1;C<0&&(C=w+C+1),M<0&&(M=B+M+1),k<0&&(k=x+k+1),t.i_verts.push(d,f,C),t.i_uvt.push(v,m,M),t.i_norms.push(_,b,k)}}}return i.to=t.i_verts.length,t},wt.parse.fromMD2=function(e){e=new Uint8Array(e);var t={},i={};i.ident=wt.bin.ril(e,0),i.version=wt.bin.ril(e,4),i.skinwidth=wt.bin.ril(e,8),i.skinheight=wt.bin.ril(e,12),i.framesize=wt.bin.ril(e,16),i.num_skins=wt.bin.ril(e,20),i.num_vertices=wt.bin.ril(e,24),i.num_st=wt.bin.ril(e,28),i.num_tris=wt.bin.ril(e,32),i.num_glcmds=wt.bin.ril(e,36),i.num_frames=wt.bin.ril(e,40),i.offset_skins=wt.bin.ril(e,44),i.offset_st=wt.bin.ril(e,48),i.offset_tris=wt.bin.ril(e,52),i.offset_frames=wt.bin.ril(e,56),i.offset_glcmds=wt.bin.ril(e,60),i.offset_end=wt.bin.ril(e,64);var r=i.offset_st;t.c_uvt=[];for(var n=0;n<i.num_st;n++){var s=wt.bin.rsl(e,r)/i.skinwidth,o=wt.bin.rsl(e,r+2)/i.skinheight;t.c_uvt.push(s,o),r+=4}r=i.offset_tris;var a=[],l=[];t.i_verts=a,t.i_uvt=l;for(n=0;n<i.num_tris;n++)a.push(wt.bin.rsl(e,r),wt.bin.rsl(e,r+2),wt.bin.rsl(e,r+4)),l.push(wt.bin.rsl(e,r+6),wt.bin.rsl(e,r+8),wt.bin.rsl(e,r+10)),r+=12;r=i.offset_skins;t.skins=[];for(n=0;n<i.num_skins;n++)t.skins.push(wt.bin.rASCII0(e,r)),r+=64;r=i.offset_frames;t.frames=[];var u=wt.parse.fromMD2._normals;for(n=0;n<i.num_frames;n++){var c={},A=wt.bin.rf(e,r),h=wt.bin.rf(e,r+4),d=wt.bin.rf(e,r+8);r+=12;var p=wt.bin.rf(e,r),f=wt.bin.rf(e,r+4),v=wt.bin.rf(e,r+8);r+=12,c.name=wt.bin.rASCII0(e,r),r+=16,c.verts=[],c.norms=[];for(var g=0;g<i.num_vertices;g++)c.verts.push(e[r]*A+p,e[r+1]*h+f,e[r+2]*d+v),c.norms.push(u[3*e[r+3]],u[3*e[r+3]+1],u[3*e[r+3]+2]),r+=4;t.frames.push(c)}return t},wt.parse.fromMD2._normals=[-.525731,0,.850651,-.442863,.238856,.864188,-.295242,0,.955423,-.309017,.5,.809017,-.16246,.262866,.951056,0,0,1,0,.850651,.525731,-.147621,.716567,.681718,.147621,.716567,.681718,0,.525731,.850651,.309017,.5,.809017,.525731,0,.850651,.295242,0,.955423,.442863,.238856,.864188,.16246,.262866,.951056,-.681718,.147621,.716567,-.809017,.309017,.5,-.587785,.425325,.688191,-.850651,.525731,0,-.864188,.442863,.238856,-.716567,.681718,.147621,-.688191,.587785,.425325,-.5,.809017,.309017,-.238856,.864188,.442863,-.425325,.688191,.587785,-.716567,.681718,-.147621,-.5,.809017,-.309017,-.525731,.850651,0,0,.850651,-.525731,-.238856,.864188,-.442863,0,.955423,-.295242,-.262866,.951056,-.16246,0,1,0,0,.955423,.295242,-.262866,.951056,.16246,.238856,.864188,.442863,.262866,.951056,.16246,.5,.809017,.309017,.238856,.864188,-.442863,.262866,.951056,-.16246,.5,.809017,-.309017,.850651,.525731,0,.716567,.681718,.147621,.716567,.681718,-.147621,.525731,.850651,0,.425325,.688191,.587785,.864188,.442863,.238856,.688191,.587785,.425325,.809017,.309017,.5,.681718,.147621,.716567,.587785,.425325,.688191,.955423,.295242,0,1,0,0,.951056,.16246,.262866,.850651,-.525731,0,.955423,-.295242,0,.864188,-.442863,.238856,.951056,-.16246,.262866,.809017,-.309017,.5,.681718,-.147621,.716567,.850651,0,.525731,.864188,.442863,-.238856,.809017,.309017,-.5,.951056,.16246,-.262866,.525731,0,-.850651,.681718,.147621,-.716567,.681718,-.147621,-.716567,.850651,0,-.525731,.809017,-.309017,-.5,.864188,-.442863,-.238856,.951056,-.16246,-.262866,.147621,.716567,-.681718,.309017,.5,-.809017,.425325,.688191,-.587785,.442863,.238856,-.864188,.587785,.425325,-.688191,.688191,.587785,-.425325,-.147621,.716567,-.681718,-.309017,.5,-.809017,0,.525731,-.850651,-.525731,0,-.850651,-.442863,.238856,-.864188,-.295242,0,-.955423,-.16246,.262866,-.951056,0,0,-1,.295242,0,-.955423,.16246,.262866,-.951056,-.442863,-.238856,-.864188,-.309017,-.5,-.809017,-.16246,-.262866,-.951056,0,-.850651,-.525731,-.147621,-.716567,-.681718,.147621,-.716567,-.681718,0,-.525731,-.850651,.309017,-.5,-.809017,.442863,-.238856,-.864188,.16246,-.262866,-.951056,.238856,-.864188,-.442863,.5,-.809017,-.309017,.425325,-.688191,-.587785,.716567,-.681718,-.147621,.688191,-.587785,-.425325,.587785,-.425325,-.688191,0,-.955423,-.295242,0,-1,0,.262866,-.951056,-.16246,0,-.850651,.525731,0,-.955423,.295242,.238856,-.864188,.442863,.262866,-.951056,.16246,.5,-.809017,.309017,.716567,-.681718,.147621,.525731,-.850651,0,-.238856,-.864188,-.442863,-.5,-.809017,-.309017,-.262866,-.951056,-.16246,-.850651,-.525731,0,-.716567,-.681718,-.147621,-.716567,-.681718,.147621,-.525731,-.850651,0,-.5,-.809017,.309017,-.238856,-.864188,.442863,-.262866,-.951056,.16246,-.864188,-.442863,.238856,-.809017,-.309017,.5,-.688191,-.587785,.425325,-.681718,-.147621,.716567,-.442863,-.238856,.864188,-.587785,-.425325,.688191,-.309017,-.5,.809017,-.147621,-.716567,.681718,-.425325,-.688191,.587785,-.16246,-.262866,.951056,.442863,-.238856,.864188,.16246,-.262866,.951056,.309017,-.5,.809017,.147621,-.716567,.681718,0,-.525731,.850651,.425325,-.688191,.587785,.587785,-.425325,.688191,.688191,-.587785,.425325,-.955423,.295242,0,-.951056,.16246,.262866,-1,0,0,-.850651,0,.525731,-.955423,-.295242,0,-.951056,-.16246,.262866,-.864188,.442863,-.238856,-.951056,.16246,-.262866,-.809017,.309017,-.5,-.864188,-.442863,-.238856,-.951056,-.16246,-.262866,-.809017,-.309017,-.5,-.681718,.147621,-.716567,-.681718,-.147621,-.716567,-.850651,0,-.525731,-.688191,.587785,-.425325,-.587785,.425325,-.688191,-.425325,.688191,-.587785,-.425325,-.688191,-.587785,-.587785,-.425325,-.688191,-.688191,-.587785,-.425325],wt.parse.fromCollada=function(e){var t=wt.parse._buffToStr(e),i=(new DOMParser).parseFromString(t,"text/xml"),r={},n=(i=i.childNodes[0]).getElementsByTagName("asset")[0],s=i.getElementsByTagName("library_geometries")[0],o=i.getElementsByTagName("library_images")[0],a=i.getElementsByTagName("library_materials")[0],l=i.getElementsByTagName("library_effects")[0];return n&&(r.asset=wt.parse.fromCollada._asset(n)),s&&(r.geometries=wt.parse.fromCollada._libGeometries(s)),o&&(r.images=wt.parse.fromCollada._libImages(o)),a&&(r.materials=wt.parse.fromCollada._libMaterials(a)),l&&(r.effects=wt.parse.fromCollada._libEffects(l)),r},wt.parse.fromCollada._asset=function(e){return{created:e.getElementsByTagName("created")[0].textContent,modified:e.getElementsByTagName("modified")[0].textContent,up_axis:e.getElementsByTagName("up_axis")[0].textContent}},wt.parse.fromCollada._libGeometries=function(e){e=e.getElementsByTagName("geometry");for(var t=[],i=0;i<e.length;i++){var r=e[i],n=wt.parse.fromCollada._getMesh(r.getElementsByTagName("mesh")[0]);t.push(n)}return t},wt.parse.fromCollada._getMesh=function(e){for(var t={},i=e.getElementsByTagName("source"),r=t.sources={},n=0;n<i.length;n++){for(var s=i[n].getElementsByTagName("float_array")[0].textContent.split(" "),o=s.length-(""==s[s.length-1]?1:0),a=new Array(o),l=0;l<o;l++)a[l]=parseFloat(s[l]);r[i[n].getAttribute("id")]=a}t.triangles=[];var u=e.getElementsByTagName("triangles");if(null==u)return t;for(n=0;n<u.length;n++){var c={},A=u[n];c.material=A.getAttribute("material");var h=A.getElementsByTagName("input"),d=[];for(l=0;l<h.length;l++){var p=h[l];a=[];d[parseInt(p.getAttribute("offset"))]=a;var f=p.getAttribute("semantic");c["s_"+f]="VERTEX"==f?e.getElementsByTagName("vertices")[0].getElementsByTagName("input")[0].getAttribute("source").substring(1):p.getAttribute("source").substring(1),c["i_"+f]=a,r[c["s_"+f]]}var v=A.getElementsByTagName("p")[0].textContent.split(" "),g=3*Math.floor(v.length/3);for(l=0;l<g;l++)d[l%h.length].push(parseInt(v[l]));t.triangles.push(c)}return t},wt.parse.fromCollada._libImages=function(e){e=e.getElementsByTagName("image");for(var t={},i=0;i<e.length;i++)t[e[i].getAttribute("id")]=e[i].getElementsByTagName("init_from")[0].textContent;return t},wt.parse.fromCollada._libMaterials=function(e){e=e.getElementsByTagName("material");for(var t={},i=0;i<e.length;i++)t[e[i].getAttribute("name")]=e[i].getElementsByTagName("instance_effect")[0].getAttribute("url").substring(1);return t},wt.parse.fromCollada._libEffects=function(e){e=e.getElementsByTagName("effect");for(var t={},i=0;i<e.length;i++){for(var r={},n=e[i].getElementsByTagName("newparam"),s=0;s<n.length;s++){var o=n[s].getElementsByTagName("surface")[0];o&&(r.surface=o.getElementsByTagName("init_from")[0].textContent)}t[e[i].getAttribute("id")]=r}return t},wt.parse.from3DS=function(e){e=new Uint8Array(e);var t={};if(19789!=wt.bin.rsl(e,0))return null;for(var i=wt.bin.ril(e,2),r=6;r<i;){var n=wt.bin.rsl(e,r),s=wt.bin.ril(e,r+2);15677==n&&(t.edit=wt.parse.from3DS._edit3ds(e,r,s)),45056==n&&(t.keyf=wt.parse.from3DS._keyf3ds(e,r,s)),r+=s}return t},wt.parse.from3DS._edit3ds=function(e,t,i){for(var r={},n=t+6;n<t+i;){var s=wt.bin.rsl(e,n),o=wt.bin.ril(e,n+2);16384==s&&(null==r.objects&&(r.objects=[]),r.objects.push(wt.parse.from3DS._edit_object(e,n,o))),n+=o}return r},wt.parse.from3DS._keyf3ds=function(e,t,i){for(var r={},n=t+6;n<t+i;){var s=wt.bin.rsl(e,n),o=wt.bin.ril(e,n+2);45058==s&&(null==r.desc&&(r.desc=[]),r.desc.push(wt.parse.from3DS._keyf_objdes(e,n,o))),n+=o}return r},wt.parse.from3DS._keyf_objdes=function(e,t,i){for(var r={},n=t+6;n<t+i;){var s=wt.bin.rsl(e,n),o=wt.bin.ril(e,n+2);45072==s&&(r.hierarchy=wt.parse.from3DS._keyf_objhierarch(e,n,o)),45073==s&&(r.dummy_name=wt.bin.rASCII0(e,n+6)),n+=o}return r},wt.parse.from3DS._keyf_objhierarch=function(e,t,i){var r={},n=t+6;return r.name=wt.bin.rASCII0(e,n),n+=r.name.length+1,r.hierarchy=wt.bin.rsl(e,n+4),r},wt.parse.from3DS._edit_object=function(e,t,i){var r={},n=t+6;for(r.name=wt.bin.rASCII0(e,n),n+=r.name.length+1;n<t+i;){var s=wt.bin.rsl(e,n),o=wt.bin.ril(e,n+2);16640==s&&(r.mesh=wt.parse.from3DS._obj_trimesh(e,n,o)),n+=o}return r},wt.parse.from3DS._obj_trimesh=function(e,t,i){for(var r={},n=t+6;n<t+i;){var s=wt.bin.rsl(e,n),o=wt.bin.ril(e,n+2);16656==s&&(r.vertices=wt.parse.from3DS._tri_vertexl(e,n,o)),16672==s&&(r.indices=wt.parse.from3DS._tri_facel1(e,n,o)),16704==s&&(r.uvt=wt.parse.from3DS._tri_mappingcoors(e,n,o)),16736==s&&(r.local=wt.parse.from3DS._tri_local(e,n,o)),n+=o}return r},wt.parse.from3DS._tri_vertexl=function(e,t,i){var r=[],n=t+6,s=wt.bin.rsl(e,n);n+=2;for(var o=0;o<s;o++)r.push(wt.bin.rf(e,n)),r.push(wt.bin.rf(e,n+4)),r.push(wt.bin.rf(e,n+8)),n+=12;return r},wt.parse.from3DS._tri_facel1=function(e,t,i){var r=[],n=t+6,s=wt.bin.rsl(e,n);n+=2;for(var o=0;o<s;o++)r.push(wt.bin.rsl(e,n)),r.push(wt.bin.rsl(e,n+2)),r.push(wt.bin.rsl(e,n+4)),n+=8;return r},wt.parse.from3DS._tri_mappingcoors=function(e,t,i){var r=[],n=t+6,s=wt.bin.rsl(e,n);n+=2;for(var o=0;o<s;o++)r.push(wt.bin.rf(e,n)),r.push(1-wt.bin.rf(e,n+4)),n+=8;return r},wt.parse.from3DS._tri_local=function(e,t,i){var r={},n=t+6;return r.X=[wt.bin.rf(e,n),wt.bin.rf(e,n+4),wt.bin.rf(e,n+8)],n+=12,r.Y=[wt.bin.rf(e,n),wt.bin.rf(e,n+4),wt.bin.rf(e,n+8)],n+=12,r.Z=[wt.bin.rf(e,n),wt.bin.rf(e,n+4),wt.bin.rf(e,n+8)],n+=12,r.C=[wt.bin.rf(e,n),wt.bin.rf(e,n+4),wt.bin.rf(e,n+8)],n+=12,r},wt.parse.fromBIV=function(e){e=new Uint8Array(e);var t={},i={};return i.id=wt.bin.ril(e,0),i.verS=wt.bin.ril(e,4),i.texS=wt.bin.ril(e,8),i.indS=wt.bin.ril(e,12),i.verO=wt.bin.ril(e,16),i.verL=wt.bin.ril(e,20),i.texO=wt.bin.ril(e,24),i.texL=wt.bin.ril(e,28),i.indO=wt.bin.ril(e,32),i.indL=wt.bin.ril(e,36),0!=i.verO&&(t.vertices=wt.parse.fromBIV._readFloats(e,i.verO,i.verL)),0!=i.texO&&(t.uvt=wt.parse.fromBIV._readFloats(e,i.texO,i.texL)),0!=i.indO&&(t.indices=wt.parse.fromBIV._readInts(e,i.indO,i.indL,i.indS)),t},wt.parse.toBIV=function(e){for(var t=0,i=0;i<e.indices.length;i++)t=Math.max(t,e.indices[i]);var r=32;t<=65535&&(r=16);var n=40;e.vertices&&(n+=4*e.vertices.length),e.uvt&&(n+=4*e.uvt.length),e.indices&&(n+=e.indices.length*r/8);var s=new Uint8Array(n);wt.bin.wil(s,0,1769365870),wt.bin.wil(s,4,32),wt.bin.wil(s,8,32),wt.bin.wil(s,12,r);var o=40;return e.vertices&&(wt.bin.wil(s,16,o),wt.bin.wil(s,20,4*e.vertices.length),wt.parse.fromBIV._writeFloats(s,o,e.vertices),o+=4*e.vertices.length),e.uvt&&(wt.bin.wil(s,24,o),wt.bin.wil(s,28,4*e.uvt.length),wt.parse.fromBIV._writeFloats(s,o,e.uvt),o+=4*e.uvt.length),e.indices&&(wt.bin.wil(s,32,o),wt.bin.wil(s,36,4*e.indices.length),wt.parse.fromBIV._writeInts(s,o,e.indices,r)),s.buffer},wt.parse.fromBIV._readFloats=function(e,t,i){for(var r=[],n=0;n<i/4;n++)r.push(wt.bin.rf(e,t+4*n));return r},wt.parse.fromBIV._writeFloats=function(e,t,i){for(var r=0;r<i.length;r++)wt.bin.wf(e,t+4*r,i[r])},wt.parse.fromBIV._readInts=function(e,t,i,r){for(var n=[],s=0;s<i/4;s++)16==r&&n.push(wt.bin.rsl(e,t+2*s)),32==r&&n.push(wt.bin.ril(e,t+4*s));return n},wt.parse.fromBIV._writeInts=function(e,t,i,r){for(var n=0;n<i.length;n++)16==r&&wt.bin.wsl(e,t+2*n,i[n]),32==r&&wt.bin.wil(e,t+4*n,i[n])},wt.gen={},wt.gen.Plane=function(e,t,i,r){i||(i=1),r||(r=1);for(var n={verts:[],inds:[],uvt:[]},s=e+1,o=t+1,a=0;a<o;a++)for(var l=0;l<s;l++){var u=l*(2/e)-1,c=a*(2/t)-1;n.verts.push(u,c,0),n.uvt.push(i*l/e,r*a/t),a<t&&l<e&&n.inds.push(a*s+l,a*s+l+1,(a+1)*s+l,a*s+l+1,(a+1)*s+l,(a+1)*s+l+1)}return n},wt.gen.Cube=function(){return{verts:[-1,1,-1,1,1,-1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,1,-1,1,1,-1,-1,-1,1,-1,1,1,-1,-1,1,1,1,1,1,-1,-1,-1,1,-1,-1,-1,-1,1,1,-1,1],inds:[0,1,2,1,2,3,4,5,6,5,6,7,8,9,10,9,10,11,12,13,14,13,14,15,16,17,18,17,18,19,20,21,22,21,22,23],uvt:[1/4,1/4,.5,1/4,1/4,.5,.5,.5,1,1/4,3/4,1/4,1,.5,3/4,.5,0,1/4,1/4,1/4,0,.5,1/4,.5,3/4,1/4,.5,1/4,3/4,.5,.5,.5,1/4,1/4,.5,1/4,1/4,0,.5,0,1/4,.5,.5,.5,1/4,3/4,.5,3/4]}},wt.gen.Sphere=function(e,t){for(var i={verts:[],inds:[],uvt:[]},r=e+1,n=t+1,s=0;s<n;s++)for(var o=0;o<r;o++){var a=-Math.PI/2+s*Math.PI/t,l=2*o*Math.PI/e,u=Math.cos(a)*Math.cos(l),c=Math.sin(a),A=Math.cos(a)*Math.sin(l);i.verts.push(u,c,A),i.uvt.push(o/e,s/t),s<t&&o<e&&i.inds.push(r*s+o,r*s+o+1,r*(s+1)+o,r*s+o+1,r*(s+1)+o,r*(s+1)+o+1)}return i},wt.mat={},wt.mat.scale=function(e,t,i){return[e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1]},wt.mat.translate=function(e,t,i){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1]},wt.mat.rotateDeg=function(e,t,i){var r=Math.PI/180;return wt.mat.rotate(e*r,t*r,i*r)},wt.mat.rotate=function(e,t,i){var r=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],n=e,s=t,o=i,a=Math.cos(n),l=Math.cos(s),u=Math.cos(o),c=Math.sin(n),A=Math.sin(s),h=Math.sin(o);return r[0]=l*u,r[1]=-l*h,r[2]=A,r[4]=a*h+c*A*u,r[5]=a*u-c*A*h,r[6]=-c*l,r[8]=c*h-a*A*u,r[9]=c*u+a*A*h,r[10]=a*l,r},wt.edit={},wt.edit.interpolate=function(e,t,i,r){for(var n=0;n<e.length;n++)i[n]=e[n]+r*(t[n]-e[n])},wt.edit.transform=function(e,t){for(var i=0;i<e.length;i+=3){var r=e[i],n=e[i+1],s=e[i+2];e[i+0]=t[0]*r+t[4]*n+t[8]*s+t[12],e[i+1]=t[1]*r+t[5]*n+t[9]*s+t[13],e[i+2]=t[2]*r+t[6]*n+t[10]*s+t[14]}},wt.edit.unwrap=function(e,t,i){for(var r=new Array(Math.floor(e.length/3)*i),n=0;n<e.length;n++)for(var s=0;s<i;s++)r[n*i+s]=t[e[n]*i+s];return r},wt.edit.remap=function(e,t,i,r){for(var n=new Array(i.length),s=0;s<e.length;s++)for(var o=0;o<r;o++)n[t[s]*r+o]=i[e[s]*r+o];return n},wt.utils={},wt.utils.getAABB=function(e){var t,i,r,n,s,o;n=s=o=-(t=i=r=999999999);for(var a=0;a<e.length;a+=3){var l=e[a+0],u=e[a+1],c=e[a+2];l<t&&(t=l),l>n&&(n=l),u<i&&(i=u),u>s&&(s=u),c<r&&(r=c),u>o&&(o=c)}return{min:{x:t,y:i,z:r},max:{x:n,y:s,z:o}}};var Dt={" ":{width:16,points:[]},"!":{width:10,points:[[5,21],[5,7],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},'"':{width:16,points:[[4,21],[4,14],[-1,-1],[12,21],[12,14]]},"#":{width:21,points:[[11,25],[4,-7],[-1,-1],[17,25],[10,-7],[-1,-1],[4,12],[18,12],[-1,-1],[3,6],[17,6]]},$:{width:20,points:[[8,25],[8,-4],[-1,-1],[12,25],[12,-4],[-1,-1],[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},"%":{width:24,points:[[21,21],[3,0],[-1,-1],[8,21],[10,19],[10,17],[9,15],[7,14],[5,14],[3,16],[3,18],[4,20],[6,21],[8,21],[10,20],[13,19],[16,19],[19,20],[21,21],[-1,-1],[17,7],[15,6],[14,4],[14,2],[16,0],[18,0],[20,1],[21,3],[21,5],[19,7],[17,7]]},"&":{width:26,points:[[23,12],[23,13],[22,14],[21,14],[20,13],[19,11],[17,6],[15,3],[13,1],[11,0],[7,0],[5,1],[4,2],[3,4],[3,6],[4,8],[5,9],[12,13],[13,14],[14,16],[14,18],[13,20],[11,21],[9,20],[8,18],[8,16],[9,13],[11,10],[16,3],[18,1],[20,0],[22,0],[23,1],[23,2]]},"'":{width:10,points:[[5,19],[4,20],[5,21],[6,20],[6,18],[5,16],[4,15]]},"(":{width:14,points:[[11,25],[9,23],[7,20],[5,16],[4,11],[4,7],[5,2],[7,-2],[9,-5],[11,-7]]},")":{width:14,points:[[3,25],[5,23],[7,20],[9,16],[10,11],[10,7],[9,2],[7,-2],[5,-5],[3,-7]]},"*":{width:16,points:[[8,21],[8,9],[-1,-1],[3,18],[13,12],[-1,-1],[13,18],[3,12]]},"+":{width:26,points:[[13,18],[13,0],[-1,-1],[4,9],[22,9]]},",":{width:10,points:[[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"-":{width:26,points:[[4,9],[22,9]]},".":{width:10,points:[[5,2],[4,1],[5,0],[6,1],[5,2]]},"/":{width:22,points:[[20,25],[2,-7]]},0:{width:20,points:[[9,21],[6,20],[4,17],[3,12],[3,9],[4,4],[6,1],[9,0],[11,0],[14,1],[16,4],[17,9],[17,12],[16,17],[14,20],[11,21],[9,21]]},1:{width:20,points:[[6,17],[8,18],[11,21],[11,0]]},2:{width:20,points:[[4,16],[4,17],[5,19],[6,20],[8,21],[12,21],[14,20],[15,19],[16,17],[16,15],[15,13],[13,10],[3,0],[17,0]]},3:{width:20,points:[[5,21],[16,21],[10,13],[13,13],[15,12],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},4:{width:20,points:[[13,21],[3,7],[18,7],[-1,-1],[13,21],[13,0]]},5:{width:20,points:[[15,21],[5,21],[4,12],[5,13],[8,14],[11,14],[14,13],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},6:{width:20,points:[[16,18],[15,20],[12,21],[10,21],[7,20],[5,17],[4,12],[4,7],[5,3],[7,1],[10,0],[11,0],[14,1],[16,3],[17,6],[17,7],[16,10],[14,12],[11,13],[10,13],[7,12],[5,10],[4,7]]},7:{width:20,points:[[17,21],[7,0],[-1,-1],[3,21],[17,21]]},8:{width:20,points:[[8,21],[5,20],[4,18],[4,16],[5,14],[7,13],[11,12],[14,11],[16,9],[17,7],[17,4],[16,2],[15,1],[12,0],[8,0],[5,1],[4,2],[3,4],[3,7],[4,9],[6,11],[9,12],[13,13],[15,14],[16,16],[16,18],[15,20],[12,21],[8,21]]},9:{width:20,points:[[16,14],[15,11],[13,9],[10,8],[9,8],[6,9],[4,11],[3,14],[3,15],[4,18],[6,20],[9,21],[10,21],[13,20],[15,18],[16,14],[16,9],[15,4],[13,1],[10,0],[8,0],[5,1],[4,3]]},":":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},";":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"<":{width:24,points:[[20,18],[4,9],[20,0]]},"=":{width:26,points:[[4,12],[22,12],[-1,-1],[4,6],[22,6]]},">":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function St(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.origin||[0,0,0],i=t[0],r=t[1],n=t[2],s=e.size||1,o=[],a=[],l=e.text;ge.isNumeric(l)&&(l=""+l);for(var u,c,A,h,d,p,f,v,g,m=(l||"").split("\n"),_=0,y=0,b=.04,w=0;w<m.length;w++){u=0,A=(c=m[w]).length;for(var B=0;B<A;B++)if(h=Dt[c.charAt(B)]){d=1,p=-1,f=-1,v=h.points.length;for(var x=0;x<v;x++)-1!==(g=h.points[x])[0]||-1!==g[1]?(o.push(u+g[0]*s*b+i),o.push(y+g[1]*s*b+r),o.push(0+n),-1===p?p=_:(-1===f||(p=f),f=_),_++,d?d=!1:(a.push(p),a.push(f))):d=1;u+=h.width*b*s}y-=35*b*s}return ge.apply(e,{primitive:"lines",positions:o,indices:a})}function Rt(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";var t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";for(var i=[],r=0;r<t-1;r++)i.push(r),i.push(r+1);return ge.apply(e,{primitive:"lines",positions:e.points,indices:i})}function Ut(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.curve.getPoints(e.divisions).map((function(e){return f(e)})).flat();return Rt({id:e.id,points:t})}function Lt(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(3!==e.startPoint.length)throw"Start point should contain 3 elements in array: x, y and z";if(3!==e.endPoint.length)throw"End point should contain 3 elements in array: x, y and z";var t=[],i=[],r=e.startPoint[0],n=e.startPoint[1],s=e.startPoint[2],o=e.endPoint[0],a=e.endPoint[1],l=e.endPoint[2],u=Math.sqrt(Math.pow(o-r,2)+Math.pow(a-n,2)+Math.pow(l-s,2)),c=[(o-r)/u,(a-n)/u,(l-s)/u];if(e.pattern){var A=e.pattern.length,h=!1,d=0,p=0,f=0,v=[r,n,s],g=e.pattern[p];for(i.push(v[0],v[1],v[2]);g<=u-d;){var m=[c[0]*g,c[1]*g,c[2]*g],_=[v[0]+m[0],v[1]+m[1],v[2]+m[2]];i.push(_[0],_[1],_[2]),h||(t.push(f),t.push(f+1)),h=!h,f+=1,v=_,(p+=1)>=A&&(p=0),d+=g,g=e.pattern[p]}e.extendToEnd&&(i.push(o,a,l),t.push(t.length-2),t.push(t.length-1))}else t.push(0),t.push(1),i.push(r,n,s,o,a,l);return ge.apply(e,{primitive:"lines",positions:i,indices:t})}var Ot=le.vec4(4),Nt=le.vec4(),Vt=le.vec4(),Qt=le.vec3([1,0,0]),Ht=le.vec3([0,1,0]),jt=le.vec3([0,0,1]),Gt=le.vec3(3),zt=le.vec3(3),Wt=le.identityMat4(),Xt=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(E(this,i),(r=t.call(this,e,n))._parentNode=null,r._children=[],r._aabb=null,r._aabbDirty=!0,r.scene._aabbDirty=!0,r._numTriangles=0,r._scale=le.vec3(),r._quaternion=le.identityQuaternion(),r._rotation=le.vec3(),r._position=le.vec3(),r._offset=le.vec3(),r._localMatrix=le.identityMat4(),r._worldMatrix=le.identityMat4(),r._localMatrixDirty=!0,r._worldMatrixDirty=!0,n.matrix?r.matrix=n.matrix:(r.scale=n.scale,r.position=n.position,n.quaternion||(r.rotation=n.rotation)),r._isModel=n.isModel,r._isModel&&r.scene._registerModel(w(r)),r._isObject=n.isObject,r._isObject&&r.scene._registerObject(w(r)),r.origin=n.origin,r.visible=n.visible,r.culled=n.culled,r.pickable=n.pickable,r.clippable=n.clippable,r.collidable=n.collidable,r.castsShadow=n.castsShadow,r.receivesShadow=n.receivesShadow,r.xrayed=n.xrayed,r.highlighted=n.highlighted,r.selected=n.selected,r.edges=n.edges,r.colorize=n.colorize,r.opacity=n.opacity,r.offset=n.offset,n.children)for(var s=n.children,o=0,a=s.length;o<a;o++)r.addChild(s[o],n.inheritStates);if(n.parentId){var l=r.scene.components[n.parentId];l?l.isNode?l.addChild(w(r)):r.error("Parent is not a Node: '"+n.parentId+"'"):r.error("Parent not found: '"+n.parentId+"'")}else n.parent&&(n.parent.isNode||r.error("Parent is not a Node"),n.parent.addChild(w(r)));return r}return I(i,[{key:"isEntity",get:function(){return!0}},{key:"isModel",get:function(){return this._isModel}},{key:"isObject",get:function(){return this._isObject}},{key:"aabb",get:function(){return this._aabbDirty&&this._updateAABB(),this._aabb}},{key:"origin",get:function(){return this._origin},set:function(e){e?(this._origin||(this._origin=le.vec3()),this._origin.set(e)):this._origin&&(this._origin=null);for(var t=0,i=this._children.length;t<i;t++)this._children[t].origin=e;this.glRedraw()}},{key:"rtcCenter",get:function(){return this.origin},set:function(e){this.origin=e}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"visible",get:function(){return this._visible},set:function(e){e=!1!==e,this._visible=e;for(var t=0,i=this._children.length;t<i;t++)this._children[t].visible=e;this._isObject&&this.scene._objectVisibilityUpdated(this,e)}},{key:"xrayed",get:function(){return this._xrayed},set:function(e){e=!!e,this._xrayed=e;for(var t=0,i=this._children.length;t<i;t++)this._children[t].xrayed=e;this._isObject&&this.scene._objectXRayedUpdated(this,e)}},{key:"highlighted",get:function(){return this._highlighted},set:function(e){e=!!e,this._highlighted=e;for(var t=0,i=this._children.length;t<i;t++)this._children[t].highlighted=e;this._isObject&&this.scene._objectHighlightedUpdated(this,e)}},{key:"selected",get:function(){return this._selected},set:function(e){e=!!e,this._selected=e;for(var t=0,i=this._children.length;t<i;t++)this._children[t].selected=e;this._isObject&&this.scene._objectSelectedUpdated(this,e)}},{key:"edges",get:function(){return this._edges},set:function(e){e=!!e,this._edges=e;for(var t=0,i=this._children.length;t<i;t++)this._children[t].edges=e}},{key:"culled",get:function(){return this._culled},set:function(e){e=!!e,this._culled=e;for(var t=0,i=this._children.length;t<i;t++)this._children[t].culled=e}},{key:"clippable",get:function(){return this._clippable},set:function(e){e=!1!==e,this._clippable=e;for(var t=0,i=this._children.length;t<i;t++)this._children[t].clippable=e}},{key:"collidable",get:function(){return this._collidable},set:function(e){e=!1!==e,this._collidable=e;for(var t=0,i=this._children.length;t<i;t++)this._children[t].collidable=e}},{key:"pickable",get:function(){return this._pickable},set:function(e){e=!1!==e,this._pickable=e;for(var t=0,i=this._children.length;t<i;t++)this._children[t].pickable=e}},{key:"colorize",get:function(){return this._colorize.slice(0,3)},set:function(e){var t=this._colorize;t||((t=this._colorize=new Float32Array(4))[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);for(var i=0,r=this._children.length;i<r;i++)this._children[i].colorize=t;if(this._isObject){var n=!!e;this.scene._objectColorizeUpdated(this,n)}}},{key:"opacity",get:function(){return this._colorize[3]},set:function(e){var t=this._colorize;t||((t=this._colorize=new Float32Array(4))[0]=1,t[1]=1,t[2]=1),t[3]=null!=e?e:1;for(var i=0,r=this._children.length;i<r;i++)this._children[i].opacity=e;if(this._isObject){var n=null!=e;this.scene._objectOpacityUpdated(this,n)}}},{key:"castsShadow",get:function(){return this._castsShadow},set:function(e){e=!!e,this._castsShadow=e;for(var t=0,i=this._children.length;t<i;t++)this._children[t].castsShadow=e}},{key:"receivesShadow",get:function(){return this._receivesShadow},set:function(e){e=!!e,this._receivesShadow=e;for(var t=0,i=this._children.length;t<i;t++)this._children[t].receivesShadow=e}},{key:"saoEnabled",get:function(){return!1}},{key:"offset",get:function(){return this._offset},set:function(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(var t=0,i=this._children.length;t<i;t++)this._children[t].offset=this._offset;this._isObject&&this.scene._objectOffsetUpdated(this,e)}},{key:"isNode",get:function(){return!0}},{key:"_setLocalMatrixDirty",value:function(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}},{key:"_setWorldMatrixDirty",value:function(){this._worldMatrixDirty=!0;for(var e=0,t=this._children.length;e<t;e++)this._children[e]._setWorldMatrixDirty()}},{key:"_buildWorldMatrix",value:function(){var e=this.matrix;if(this._parentNode)le.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(var t=0,i=e.length;t<i;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}},{key:"_setSubtreeAABBsDirty",value:function(e){if(e._aabbDirty=!0,e._children)for(var t=0,i=e._children.length;t<i;t++)this._setSubtreeAABBsDirty(e._children[t])}},{key:"_setAABBDirty",value:function(){if(this._setSubtreeAABBsDirty(this),this.collidable)for(var e=this;e;e=e._parentNode)e._aabbDirty=!0}},{key:"_updateAABB",value:function(){if(this.scene._aabbDirty=!0,this._aabb||(this._aabb=le.AABB3()),this._buildAABB)this._buildAABB(this.worldMatrix,this._aabb);else{var e;le.collapseAABB3(this._aabb);for(var t=0,i=this._children.length;t<i;t++)(e=this._children[t]).collidable&&le.expandAABB3(this._aabb,e.aabb)}this._aabbDirty=!1}},{key:"addChild",value:function(e,t){if(ge.isNumeric(e)||ge.isString(e)){var i=e;if(!(e=this.scene.component[i]))return void this.warn("Component not found: "+ge.inQuotes(i));if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+i)}else{if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+e.id);if(e._parentNode){if(e._parentNode.id===this.id)return void this.warn("Already a child: "+e.id);e._parentNode.removeChild(e)}}if(e.id,e.scene.id===this.scene.id)return this._children.push(e),e._parentNode=this,t&&(e.visible=this.visible,e.culled=this.culled,e.xrayed=this.xrayed,e.highlited=this.highlighted,e.selected=this.selected,e.edges=this.edges,e.clippable=this.clippable,e.pickable=this.pickable,e.collidable=this.collidable,e.castsShadow=this.castsShadow,e.receivesShadow=this.receivesShadow,e.colorize=this.colorize,e.opacity=this.opacity,e.offset=this.offset),e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles+=e.numTriangles,e;this.error("Child not in same Scene: "+e.id)}},{key:"removeChild",value:function(e){for(var t=0,i=this._children.length;t<i;t++)if(this._children[t].id===e.id)return e._parentNode=null,this._children=this._children.splice(t,1),e._setWorldMatrixDirty(),e._setAABBDirty(),this._setAABBDirty(),void(this._numTriangles-=e.numTriangles)}},{key:"removeChildren",value:function(){for(var e,t=0,i=this._children.length;t<i;t++)(e=this._children[t])._parentNode=null,e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles-=e.numTriangles;this._children=[],this._setAABBDirty()}},{key:"numChildren",get:function(){return this._children.length}},{key:"children",get:function(){return this._children}},{key:"parent",get:function(){return this._parentNode},set:function(e){if(ge.isNumeric(e)||ge.isString(e)){var t=e;if(!(e=this.scene.components[t]))return void this.warn("Node not found: "+ge.inQuotes(t));if(!e.isNode)return void this.error("Not a Node: "+e.id)}e.scene.id===this.scene.id?this._parentNode&&this._parentNode.id===e.id?this.warn("Already a child of Node: "+e.id):e.addChild(this):this.error("Node not in same Scene: "+e.id)}},{key:"position",get:function(){return this._position},set:function(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"rotation",get:function(){return this._rotation},set:function(e){this._rotation.set(e||[0,0,0]),le.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"quaternion",get:function(){return this._quaternion},set:function(e){this._quaternion.set(e||[0,0,0,1]),le.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"scale",get:function(){return this._scale},set:function(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"matrix",get:function(){return this._localMatrixDirty&&(this._localMatrix||(this._localMatrix=le.identityMat4()),le.composeMat4(this._position,this._quaternion,this._scale,this._localMatrix),this._localMatrixDirty=!1),this._localMatrix},set:function(e){this._localMatrix||(this._localMatrix=le.identityMat4()),this._localMatrix.set(e||Wt),le.decomposeMat4(this._localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"worldMatrix",get:function(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}},{key:"rotate",value:function(e,t){return Ot[0]=e[0],Ot[1]=e[1],Ot[2]=e[2],Ot[3]=t*le.DEGTORAD,le.angleAxisToQuaternion(Ot,Nt),le.mulQuaternions(this.quaternion,Nt,Vt),this.quaternion=Vt,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}},{key:"rotateOnWorldAxis",value:function(e,t){return Ot[0]=e[0],Ot[1]=e[1],Ot[2]=e[2],Ot[3]=t*le.DEGTORAD,le.angleAxisToQuaternion(Ot,Nt),le.mulQuaternions(Nt,this.quaternion,Nt),this}},{key:"rotateX",value:function(e){return this.rotate(Qt,e)}},{key:"rotateY",value:function(e){return this.rotate(Ht,e)}},{key:"rotateZ",value:function(e){return this.rotate(jt,e)}},{key:"translate",value:function(e,t){return le.vec3ApplyQuaternion(this.quaternion,e,Gt),le.mulVec3Scalar(Gt,t,zt),le.addVec3(this.position,zt,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}},{key:"translateX",value:function(e){return this.translate(Qt,e)}},{key:"translateY",value:function(e){return this.translate(Ht,e)}},{key:"translateZ",value:function(e){return this.translate(jt,e)}},{key:"type",get:function(){return"Node"}},{key:"destroy",value:function(){if(v(x(i.prototype),"destroy",this).call(this),this._parentNode&&this._parentNode.removeChild(this),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((function(e){return 0!==e}))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length)for(var e=this._children.splice(0),t=0,r=e.length;t<r;t++)e[t].destroy();this._children=[],this._setAABBDirty(),this.scene._aabbDirty=!0}}]),i}(),Kt=le.vec3(),Zt=le.vec4(),Jt=function(){var e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(r,n,s){return s=s||e,t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=1,le.transformVec4(r,t,i),le.setMat4Translation(r,i,s),s.slice()}}();function Yt(e,t,i){var r=Float32Array.from([e[0]])[0],n=e[0]-r,s=Float32Array.from([e[1]])[0],o=e[1]-s,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=r,t[1]=s,t[2]=a,i[0]=n,i[1]=o,i[2]=l}function qt(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e3,n=le.getPositionsCenter(e,Kt),s=Math.round(n[0]/r)*r,o=Math.round(n[1]/r)*r,a=Math.round(n[2]/r)*r;i[0]=s,i[1]=o,i[2]=a;var l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(var u=0,c=e.length;u<c;u+=3)t[u+0]=e[u+0]-s,t[u+1]=e[u+1]-o,t[u+2]=e[u+2]-a;return l}function $t(e,t,i){return i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i}function ei(e,t,i,r,n){var s=n?(Zt.set(i,0),Zt[3]=1,le.mulMat4v4(n,Zt,Zt)):i,o=le.dotVec3(t,s)+e,a=le.normalizeVec3(t,Kt);return le.mulVec3Scalar(a,-o,r),r}var ti=1e3,ii=1001,ri=1002,ni=1003,si=1004,oi=1004,ai=1005,li=1005,ui=1006,ci=1007,Ai=1007,hi=1008,di=1008,pi=1009,fi=1010,vi=1011,gi=1012,mi=1013,_i=1014,yi=1015,bi=1016,wi=1017,Bi=1018,xi=1020,Pi=1021,Ci=1022,Mi=1023,ki=1024,Ei=1025,Fi=1026,Ii=1027,Ti=1028,Di=1029,Si=1030,Ri=1031,Ui=1033,Li=33776,Oi=33777,Ni=33778,Vi=33779,Qi=35840,Hi=35841,ji=35842,Gi=35843,zi=36196,Wi=37492,Xi=37496,Ki=37808,Zi=37809,Ji=37810,Yi=37811,qi=37812,$i=37813,er=37814,tr=37815,ir=37816,rr=37817,nr=37818,sr=37819,or=37820,ar=37821,lr=36492,ur=3e3,cr=3001,Ar=1e4,hr=10001,dr=10002,pr=10003,fr=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){var t=e.scene,i=e.scene._sectionPlanesState,r=e.scene._lightsState,n=e._geometry._state,s=e._state.billboard,o=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!n.compressGeometry,u=[];u.push("#version 300 es"),u.push("// Lambertian drawing vertex shader"),u.push("in vec3 position;"),u.push("uniform mat4 modelMatrix;"),u.push("uniform mat4 viewMatrix;"),u.push("uniform mat4 projMatrix;"),u.push("uniform vec4 colorize;"),u.push("uniform vec3 offset;"),u.push("uniform vec3 scale;"),l&&u.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(u.push("uniform float logDepthBufFC;"),u.push("out float vFragDepth;"),u.push("bool isPerspectiveMatrix(mat4 m) {"),u.push(" return (m[2][3] == - 1.0);"),u.push("}"),u.push("out float isPerspective;"));a&&u.push("out vec4 vWorldPosition;");if(u.push("uniform vec4 lightAmbient;"),u.push("uniform vec4 materialColor;"),u.push("uniform vec3 materialEmissive;"),n.normalsBuf){u.push("in vec3 normal;"),u.push("uniform mat4 modelNormalMatrix;"),u.push("uniform mat4 viewNormalMatrix;");for(var c=0,A=r.lights.length;c<A;c++){var h=r.lights[c];"ambient"!==h.type&&(u.push("uniform vec4 lightColor"+c+";"),"dir"===h.type&&u.push("uniform vec3 lightDir"+c+";"),"point"===h.type&&u.push("uniform vec3 lightPos"+c+";"),"spot"===h.type&&(u.push("uniform vec3 lightPos"+c+";"),u.push("uniform vec3 lightDir"+c+";")))}l&&(u.push("vec3 octDecode(vec2 oct) {"),u.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),u.push(" if (v.z < 0.0) {"),u.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),u.push(" }"),u.push(" return normalize(v);"),u.push("}"))}u.push("out vec4 vColor;"),"points"===n.primitiveName&&u.push("uniform float pointSize;");"spherical"!==s&&"cylindrical"!==s||(u.push("void billboard(inout mat4 mat) {"),u.push(" mat[0][0] = scale[0];"),u.push(" mat[0][1] = 0.0;"),u.push(" mat[0][2] = 0.0;"),"spherical"===s&&(u.push(" mat[1][0] = 0.0;"),u.push(" mat[1][1] = scale[1];"),u.push(" mat[1][2] = 0.0;")),u.push(" mat[2][0] = 0.0;"),u.push(" mat[2][1] = 0.0;"),u.push(" mat[2][2] =1.0;"),u.push("}"));u.push("void main(void) {"),u.push("vec4 localPosition = vec4(position, 1.0); "),u.push("vec4 worldPosition;"),l&&u.push("localPosition = positionsDecodeMatrix * localPosition;");n.normalsBuf&&(l?u.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):u.push("vec4 localNormal = vec4(normal, 0.0); "),u.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),u.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));u.push("mat4 viewMatrix2 = viewMatrix;"),u.push("mat4 modelMatrix2 = modelMatrix;"),o&&u.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===s||"cylindrical"===s?(u.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),u.push("billboard(modelMatrix2);"),u.push("billboard(viewMatrix2);"),u.push("billboard(modelViewMatrix);"),n.normalsBuf&&(u.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),u.push("billboard(modelNormalMatrix2);"),u.push("billboard(viewNormalMatrix2);"),u.push("billboard(modelViewNormalMatrix);")),u.push("worldPosition = modelMatrix2 * localPosition;"),u.push("worldPosition.xyz = worldPosition.xyz + offset;"),u.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(u.push("worldPosition = modelMatrix2 * localPosition;"),u.push("worldPosition.xyz = worldPosition.xyz + offset;"),u.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n.normalsBuf&&u.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(u.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),u.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),u.push("float lambertian = 1.0;"),n.normalsBuf)for(var d=0,p=r.lights.length;d<p;d++){var f=r.lights[d];if("ambient"!==f.type){if("dir"===f.type)"view"===f.space?u.push("viewLightDir = normalize(lightDir"+d+");"):u.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+d+", 0.0)).xyz);");else if("point"===f.type)"view"===f.space?u.push("viewLightDir = -normalize(lightPos"+d+" - viewPosition.xyz);"):u.push("viewLightDir = -normalize((viewMatrix2 * vec4(lightPos"+d+", 0.0)).xyz);");else{if("spot"!==f.type)continue;"view"===f.space?u.push("viewLightDir = normalize(lightDir"+d+");"):u.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+d+", 0.0)).xyz);")}u.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),u.push("reflectedColor += lambertian * (lightColor"+d+".rgb * lightColor"+d+".a);")}}u.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * materialColor.rgb) + materialEmissive.rgb + (reflectedColor * materialColor.rgb), materialColor.a) * colorize;"),a&&u.push("vWorldPosition = worldPosition;");"points"===n.primitiveName&&u.push("gl_PointSize = pointSize;");u.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(u.push("vFragDepth = 1.0 + clipPos.w;"),u.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return u.push("gl_Position = clipPos;"),u.push("}"),u}(e),this.fragment=function(e){var t=e.scene,i=t._sectionPlanesState;e._material._state;var r=e._geometry._state,n=i.getNumAllocatedSectionPlanes()>0,s=t.gammaOutput,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));if(n){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(var a=0,l=i.getNumAllocatedSectionPlanes();a<l;a++)o.push("uniform bool sectionPlaneActive"+a+";"),o.push("uniform vec3 sectionPlanePos"+a+";"),o.push("uniform vec3 sectionPlaneDir"+a+";")}o.push("in vec4 vColor;"),s&&(o.push("uniform float gammaFactor;"),o.push(" vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(o.push("out vec4 outColor;"),o.push("void main(void) {"),n){o.push("if (clippable) {"),o.push(" float dist = 0.0;");for(var u=0,c=i.getNumAllocatedSectionPlanes();u<c;u++)o.push("if (sectionPlaneActive"+u+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+u+".xyz, vWorldPosition.xyz - sectionPlanePos"+u+".xyz), 0.0, 1000.0);"),o.push("}");o.push(" if (dist > 0.0) { discard; }"),o.push("}")}"points"===r.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)):(this.vertex=function(e){var t=e.scene;e._material;var i,r=e._state,n=t._sectionPlanesState,s=e._geometry._state,o=t._lightsState,a=r.billboard,l=r.background,u=r.stationary,c=function(e){if(!e._geometry._state.uvBuf)return!1;var t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),A=mr(e),h=n.getNumAllocatedSectionPlanes()>0,d=gr(e),p=!!s.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),f.push("uniform vec3 scale;"),h&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));o.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(A){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(var v=0,g=o.lights.length;v<g;v++)"ambient"!==(i=o.lights[v]).type&&("dir"===i.type&&f.push("uniform vec3 lightDir"+v+";"),"point"===i.type&&f.push("uniform vec3 lightPos"+v+";"),"spot"===i.type&&(f.push("uniform vec3 lightPos"+v+";"),f.push("uniform vec3 lightDir"+v+";")),"dir"===i.type&&"view"===i.space||f.push("out vec4 vViewLightReverseDirAndDist"+v+";"));p&&(f.push("vec3 octDecode(vec2 oct) {"),f.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),f.push(" if (v.z < 0.0) {"),f.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}c&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));s.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===s.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = scale[0];"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===a&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = scale[1];"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(var m=0,_=o.lights.length;m<_;m++)o.lights[m].castsShadow&&(f.push("uniform mat4 shadowViewMatrix"+m+";"),f.push("uniform mat4 shadowProjMatrix"+m+";"),f.push("out vec4 vShadowPosFromLight"+m+";"))}f.push("void main(void) {"),f.push("vec4 localPosition = vec4(position, 1.0); "),f.push("vec4 worldPosition;"),p&&f.push("localPosition = positionsDecodeMatrix * localPosition;");A&&(p?f.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):f.push("vec4 localNormal = vec4(normal, 0.0); "),f.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),f.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));f.push("mat4 viewMatrix2 = viewMatrix;"),f.push("mat4 modelMatrix2 = modelMatrix;"),u?f.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"):l&&f.push("viewMatrix2[3] = vec4(0.0, 0.0, 0.0 ,1.0);");"spherical"===a||"cylindrical"===a?(f.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),f.push("billboard(modelMatrix2);"),f.push("billboard(viewMatrix2);"),f.push("billboard(modelViewMatrix);"),A&&(f.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),f.push("billboard(modelNormalMatrix2);"),f.push("billboard(viewNormalMatrix2);"),f.push("billboard(modelViewNormalMatrix);")),f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));if(A){f.push("vec3 worldNormal = (modelNormalMatrix2 * localNormal).xyz; "),o.lightMaps.length>0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(var y=0,b=o.lights.length;y<b;y++)"ambient"!==(i=o.lights[y]).type&&("dir"===i.type&&"world"===i.space&&(f.push("tmpVec3 = vec3(viewMatrix2 * vec4(lightDir"+y+", 0.0) ).xyz;"),f.push("vViewLightReverseDirAndDist"+y+" = vec4(-tmpVec3, 0.0);")),"point"===i.type&&("world"===i.space?(f.push("tmpVec3 = (viewMatrix2 * vec4(lightPos"+y+", 1.0)).xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")):(f.push("tmpVec3 = lightPos"+y+".xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")),f.push("vViewLightReverseDirAndDist"+y+" = vec4(tmpVec3, lightDist);")))}c&&(p?f.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"):f.push("vUV = uv;"));s.colors&&f.push("vColor = color;");"points"===s.primitiveName&&f.push("gl_PointSize = pointSize;");h&&f.push("vWorldPosition = worldPosition;");f.push(" vViewPosition = viewPosition.xyz;"),f.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(f.push("vFragDepth = 1.0 + clipPos.w;"),f.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));l&&f.push("clipPos.z = clipPos.w;");if(f.push("gl_Position = clipPos;"),d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);"),f.push("vec4 tempx; ");for(var w=0,B=o.lights.length;w<B;w++)o.lights[w].castsShadow&&f.push("vShadowPosFromLight"+w+" = texUnitConverter * shadowProjMatrix"+w+" * (shadowViewMatrix"+w+" * worldPosition); ")}return f.push("}"),f}(e),this.fragment=function(e){var t=e.scene;t.canvas.gl;var i=e._material,r=e._geometry._state,n=e.scene._sectionPlanesState,s=e.scene._lightsState,o=e._material._state,a=n.getNumAllocatedSectionPlanes()>0,l=mr(e),u=r.uvBuf,c="PhongMaterial"===o.type,A="MetallicMaterial"===o.type,h="SpecularMaterial"===o.type,d=gr(e);t.gammaInput;var p=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));d&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),p&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var v=0;v<n.getNumAllocatedSectionPlanes();v++)f.push("uniform bool sectionPlaneActive"+v+";"),f.push("uniform vec3 sectionPlanePos"+v+";"),f.push("uniform vec3 sectionPlaneDir"+v+";")}l&&(s.lightMaps.length>0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),s.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),c&&((s.lightMaps.length>0||s.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(f.push(" vec3 irradiance = "+vr[s.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(A||h)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),s.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+vr[s.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),r.colors&&f.push("in vec4 vColor;");u&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(s.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));o.ambient&&f.push("uniform vec3 materialAmbient;");o.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==o.alpha&&null!==o.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");o.emissive&&f.push("uniform vec3 materialEmissive;");o.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==o.glossiness&&null!==o.glossiness&&f.push("uniform float materialGlossiness;");void 0!==o.shininess&&null!==o.shininess&&f.push("uniform float materialShininess;");o.specular&&f.push("uniform vec3 materialSpecular;");void 0!==o.metallic&&null!==o.metallic&&f.push("uniform float materialMetallic;");void 0!==o.roughness&&null!==o.roughness&&f.push("uniform float materialRoughness;");void 0!==o.specularF0&&null!==o.specularF0&&f.push("uniform float materialSpecularF0;");u&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));u&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));u&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));u&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&u&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&u&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&u&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));u&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));u&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&u&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&u&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&u&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(var g=0,m=s.lights.length;g<m;g++){var _=s.lights[g];"ambient"!==_.type&&(f.push("uniform vec4 lightColor"+g+";"),"point"===_.type&&f.push("uniform vec3 lightAttenuation"+g+";"),"dir"===_.type&&"view"===_.space&&f.push("uniform vec3 lightDir"+g+";"),"point"===_.type&&"view"===_.space?f.push("uniform vec3 lightPos"+g+";"):f.push("in vec4 vViewLightReverseDirAndDist"+g+";"))}if(d)for(var y=0,b=s.lights.length;y<b;y++)s.lights[y].castsShadow&&(f.push("in vec4 vShadowPosFromLight"+y+";"),f.push("uniform sampler2D shadowMap"+y+";"));if(f.push("uniform vec4 colorize;"),f.push("out vec4 outColor;"),f.push("void main(void) {"),a){f.push("if (clippable) {"),f.push(" float dist = 0.0;");for(v=0;v<n.getNumAllocatedSectionPlanes();v++)f.push("if (sectionPlaneActive"+v+") {"),f.push(" dist += clamp(dot(-sectionPlaneDir"+v+".xyz, vWorldPosition.xyz - sectionPlanePos"+v+".xyz), 0.0, 1000.0);"),f.push("}");f.push(" if (dist > 0.0) { discard; }"),f.push("}")}"points"===r.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),o.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");o.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):o.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");r.colors&&f.push("diffuseColor *= vColor.rgb;");o.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");o.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==o.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");r.colors&&f.push("alpha *= vColor.a;");void 0!==o.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==o.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==o.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==o.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");u&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));u&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+vr[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));u&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+vr[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));u&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+vr[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));u&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+vr[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));u&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));u&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(s.lights.length>0||s.lightMaps.length>0||s.reflectionMaps.length>0)){u&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),u&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),u&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),u&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),u&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),u&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),u&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),c&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),h&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),A&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),s.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),c&&(s.lightMaps.length>0||s.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(h||A)&&(s.lightMaps.length>0||s.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(var w=0,B=s.lights.length;w<B;w++){var x=s.lights[w];"ambient"!==x.type&&("dir"===x.type&&"view"===x.space?f.push("viewLightDir = -normalize(lightDir"+w+");"):"point"===x.type&&"view"===x.space?f.push("viewLightDir = normalize(lightPos"+w+" - vViewPosition);"):f.push("viewLightDir = normalize(vViewLightReverseDirAndDist"+w+".xyz);"),d&&x.castsShadow?(f.push("shadow = 0.0;"),f.push("fragmentDepth = vShadowPosFromLight"+w+".xyz;"),f.push("fragmentDepth.z -= shadowAcneRemover;"),f.push("for (int x = -3; x <= 3; x++) {"),f.push(" for (int y = -3; y <= 3; y++) {"),f.push(" float texelDepth = unpackDepth(texture(shadowMap"+w+", fragmentDepth.xy + vec2(x, y) * texelSize));"),f.push(" if (fragmentDepth.z < texelDepth) {"),f.push(" shadow += 1.0;"),f.push(" }"),f.push(" }"),f.push("}"),f.push("shadow = shadow / 9.0;"),f.push("light.color = lightColor"+w+".rgb * (lightColor"+w+".a * shadow);")):f.push("light.color = lightColor"+w+".rgb * (lightColor"+w+".a );"),f.push("light.direction = viewLightDir;"),c&&f.push("computePhongLighting(light, geometry, material, reflectedLight);"),(h||A)&&f.push("computePBRLighting(light, geometry, material, reflectedLight);"))}c?f.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * diffuseColor) + ((occlusion * (( reflectedLight.diffuse + reflectedLight.specular)))) + emissiveColor;"):f.push("vec3 outgoingLight = (occlusion * (reflectedLight.diffuse)) + (occlusion * reflectedLight.specular) + emissiveColor;")}else f.push("ambientColor *= (lightAmbient.rgb * lightAmbient.a);"),f.push("vec3 outgoingLight = emissiveColor + ambientColor;");f.push("vec4 fragColor = vec4(outgoingLight, alpha) * colorize;"),p&&f.push("fragColor = linearToGamma(fragColor, gammaFactor);");f.push("outColor = fragColor;"),t.logarithmicDepthBufferEnabled&&f.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return f.push("}"),f}(e))},vr={};function gr(e){if(!e.receivesShadow)return!1;var t=e.scene._lightsState.lights;if(!t||0===t.length)return!1;for(var i=0,r=t.length;i<r;i++)if(t[i].castsShadow)return!0;return!1}function mr(e){var t=e._geometry._state.primitiveName;return!(!e._geometry._state.autoVertexNormals&&!e._geometry._state.normalsBuf||"triangles"!==t&&"triangle-strip"!==t&&"triangle-fan"!==t)}vr[3e3]="linearToLinear",vr[3001]="sRGBToLinear";var _r=function(){function e(t,i,r){if(E(this,e),this.allocated=!1,this.compiled=!1,this.handle=t.createShader(i),this.handle){if(this.allocated=!0,t.shaderSource(this.handle,r),t.compileShader(this.handle),this.compiled=t.getShaderParameter(this.handle,t.COMPILE_STATUS),!this.compiled&&!t.isContextLost()){for(var n=r.split("\n"),s=[],o=0;o<n.length;o++)s.push(o+1+": "+n[o]+"\n");this.errors=[],this.errors.push(""),this.errors.push(t.getShaderInfoLog(this.handle)),this.errors=this.errors.concat(s.join(""))}}else this.errors=["Failed to allocate"]}return I(e,[{key:"destroy",value:function(){}}]),e}(),yr=I((function e(t,i){E(this,e),this.bindTexture=function(e,r){return!!e.bind(r)&&(t.uniform1i(i,r),!0)}})),br=function(){function e(t,i){E(this,e),this._gl=t,this.location=i}return I(e,[{key:"bindArrayBuffer",value:function(e){e&&(e.bind(),this._gl.enableVertexAttribArray(this.location),this._gl.vertexAttribPointer(this.location,e.itemSize,e.itemType,e.normalized,e.stride,e.offset))}}]),e}(),wr=new Z({});function Br(e){for(var t,i,r=[],n=0,s=e.length;n<s;n++)(i=(t=e[n]).indexOf("/"))>0&&"/"===t.charAt(i+1)&&(t=t.substring(0,i)),r.push(t);return r.join("\n")}function xr(e){console.error(e.join("\n"))}var Pr=function(){function e(t,i){E(this,e),this.id=wr.addItem({}),this.source=i,this.init(t)}return I(e,[{key:"init",value:function(e){if(this.gl=e,this.allocated=!1,this.compiled=!1,this.linked=!1,this.validated=!1,this.errors=null,this.uniforms={},this.samplers={},this.attributes={},this._vertexShader=new _r(e,e.VERTEX_SHADER,Br(this.source.vertex)),this._fragmentShader=new _r(e,e.FRAGMENT_SHADER,Br(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void xr(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void xr(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void xr(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void xr(this.errors);var t,i,r,n,s;if(this.compiled=!0,this.handle=e.createProgram(),this.handle){if(e.attachShader(this.handle,this._vertexShader.handle),e.attachShader(this.handle,this._fragmentShader.handle),e.linkProgram(this.handle),this.linked=e.getProgramParameter(this.handle,e.LINK_STATUS),this.validated=!0,!this.linked||!this.validated)return this.errors=[],this.errors.push(""),this.errors.push(e.getProgramInfoLog(this.handle)),this.errors.push("\nVertex shader:\n"),this.errors=this.errors.concat(this.source.vertex),this.errors.push("\nFragment shader:\n"),this.errors=this.errors.concat(this.source.fragment),void xr(this.errors);var o=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;i<o;++i)(r=e.getActiveUniform(this.handle,i))&&("\0"===(n=r.name)[n.length-1]&&(n=n.substr(0,n.length-1)),s=e.getUniformLocation(this.handle,n),r.type===e.SAMPLER_2D||r.type===e.SAMPLER_CUBE||35682===r.type||e instanceof WebGL2RenderingContext&&(r.type===e.UNSIGNED_INT_SAMPLER_2D||r.type===e.INT_SAMPLER_2D)?this.samplers[n]=new yr(e,s):this.uniforms[n]=s);var a=e.getProgramParameter(this.handle,e.ACTIVE_ATTRIBUTES);for(i=0;i<a;i++)(t=e.getActiveAttrib(this.handle,i))&&(s=e.getAttribLocation(this.handle,t.name),this.attributes[t.name]=new br(e,s));this.allocated=!0}else this.errors=["Failed to allocate program"]}},{key:"bind",value:function(){this.allocated&&this.gl.useProgram(this.handle)}},{key:"getLocation",value:function(e){if(this.allocated)return this.uniforms[e]}},{key:"getAttribute",value:function(e){if(this.allocated)return this.attributes[e]}},{key:"bindTexture",value:function(e,t,i){if(!this.allocated)return!1;var r=this.samplers[e];return!!r&&r.bindTexture(t,i)}},{key:"destroy",value:function(){this.allocated&&(wr.removeItem(this.id),this.gl.deleteProgram(this.handle),this.gl.deleteShader(this._vertexShader.handle),this.gl.deleteShader(this._fragmentShader.handle),this.handle=null,this.attributes=null,this.uniforms=null,this.samplers=null,this.allocated=!1)}}]),e}(),Cr={WEBGL:!1,SUPPORTED_EXTENSIONS:{}},Mr=document.createElement("canvas");if(Mr){var kr=Mr.getContext("webgl",{antialias:!0})||Mr.getContext("experimental-webgl",{antialias:!0});Cr.WEBGL=!!kr,Cr.WEBGL&&(Cr.ANTIALIAS=kr.getContextAttributes().antialias,kr.getShaderPrecisionFormat?kr.getShaderPrecisionFormat(kr.FRAGMENT_SHADER,kr.HIGH_FLOAT).precision>0?Cr.FS_MAX_FLOAT_PRECISION="highp":kr.getShaderPrecisionFormat(kr.FRAGMENT_SHADER,kr.MEDIUM_FLOAT).precision>0?Cr.FS_MAX_FLOAT_PRECISION="mediump":Cr.FS_MAX_FLOAT_PRECISION="lowp":Cr.FS_MAX_FLOAT_PRECISION="mediump",Cr.DEPTH_BUFFER_BITS=kr.getParameter(kr.DEPTH_BITS),Cr.MAX_TEXTURE_SIZE=kr.getParameter(kr.MAX_TEXTURE_SIZE),Cr.MAX_CUBE_MAP_SIZE=kr.getParameter(kr.MAX_CUBE_MAP_TEXTURE_SIZE),Cr.MAX_RENDERBUFFER_SIZE=kr.getParameter(kr.MAX_RENDERBUFFER_SIZE),Cr.MAX_TEXTURE_UNITS=kr.getParameter(kr.MAX_COMBINED_TEXTURE_IMAGE_UNITS),Cr.MAX_TEXTURE_IMAGE_UNITS=kr.getParameter(kr.MAX_TEXTURE_IMAGE_UNITS),Cr.MAX_VERTEX_ATTRIBS=kr.getParameter(kr.MAX_VERTEX_ATTRIBS),Cr.MAX_VERTEX_UNIFORM_VECTORS=kr.getParameter(kr.MAX_VERTEX_UNIFORM_VECTORS),Cr.MAX_FRAGMENT_UNIFORM_VECTORS=kr.getParameter(kr.MAX_FRAGMENT_UNIFORM_VECTORS),Cr.MAX_VARYING_VECTORS=kr.getParameter(kr.MAX_VARYING_VECTORS),kr.getSupportedExtensions().forEach((function(e){Cr.SUPPORTED_EXTENSIONS[e]=!0})))}var Er=le.vec3(),Fr=new Z({}),Ir=function(e,t){this.id=Fr.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new fr(t),this._allocate(t)},Tr={};Ir.get=function(e){var t=e.scene,i=[t.canvas.canvas.id,(t.gammaInput?"gi;":";")+(t.gammaOutput?"go":""),t._lightsState.getHash(),t._sectionPlanesState.getHash(),e._geometry._state.hash,e._material._state.hash,e._state.drawHash].join(";"),r=Tr[i];if(!r){if((r=new Ir(i,e)).errors)return console.log(r.errors.join("\n")),null;Tr[i]=r,he.memory.programs++}return r._useCount++,r},Ir.prototype.put=function(){0==--this._useCount&&(Fr.removeItem(this.id),this._program&&this._program.destroy(),delete Tr[this._hash],he.memory.programs--)},Ir.prototype.webglContextRestored=function(){this._program=null},Ir.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=Cr.MAX_TEXTURE_UNITS,r=t.scene,n=t._material,s=r.canvas.gl,o=this._program,a=t._state,l=t._material._state,u=t._geometry._state,c=r.camera,A=t.origin,h=a.background;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,h&&s.depthFunc(s.LEQUAL),this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,A?e.getRTCViewMatrix(a.originHash,A):c.viewMatrix),s.uniformMatrix4fv(this._uViewNormalMatrix,!1,c.viewNormalMatrix),a.clippable){var d=r._sectionPlanesState.getNumAllocatedSectionPlanes(),p=r._sectionPlanesState.sectionPlanes.length;if(d>0)for(var f=r._sectionPlanesState.sectionPlanes,v=t.renderFlags,g=0;g<d;g++){var m=this._uSectionPlanes[g];if(m)if(g<p){var _=v.sectionPlanesActivePerLayer[g];if(s.uniform1i(m.active,_?1:0),_){var y=f[g];if(A){var b=ei(y.dist,y.dir,A,Er);s.uniform3fv(m.pos,b)}else s.uniform3fv(m.pos,y.pos);s.uniform3fv(m.dir,y.dir)}}else s.uniform1i(m.active,0)}}if(l.id!==this._lastMaterialId){e.textureUnit=this._baseTextureUnit;var w=l.backfaces;e.backfaces!==w&&(w?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=w);var B=l.frontface;switch(e.frontface!==B&&(B?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=B),e.lineWidth!==l.lineWidth&&(s.lineWidth(l.lineWidth),e.lineWidth=l.lineWidth),this._uPointSize&&s.uniform1f(this._uPointSize,l.pointSize),l.type){case"LambertMaterial":this._uMaterialAmbient&&s.uniform3fv(this._uMaterialAmbient,l.ambient),this._uMaterialColor&&s.uniform4f(this._uMaterialColor,l.color[0],l.color[1],l.color[2],l.alpha),this._uMaterialEmissive&&s.uniform3fv(this._uMaterialEmissive,l.emissive);break;case"PhongMaterial":this._uMaterialShininess&&s.uniform1f(this._uMaterialShininess,l.shininess),this._uMaterialAmbient&&s.uniform3fv(this._uMaterialAmbient,l.ambient),this._uMaterialDiffuse&&s.uniform3fv(this._uMaterialDiffuse,l.diffuse),this._uMaterialSpecular&&s.uniform3fv(this._uMaterialSpecular,l.specular),this._uMaterialEmissive&&s.uniform3fv(this._uMaterialEmissive,l.emissive),this._uAlphaModeCutoff&&s.uniform4f(this._uAlphaModeCutoff,1*l.alpha,1===l.alphaMode?1:0,l.alphaCutoff,0),n._ambientMap&&n._ambientMap._state.texture&&this._uMaterialAmbientMap&&(o.bindTexture(this._uMaterialAmbientMap,n._ambientMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uMaterialAmbientMapMatrix&&s.uniformMatrix4fv(this._uMaterialAmbientMapMatrix,!1,n._ambientMap._state.matrix)),n._diffuseMap&&n._diffuseMap._state.texture&&this._uDiffuseMap&&(o.bindTexture(this._uDiffuseMap,n._diffuseMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uDiffuseMapMatrix&&s.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,n._diffuseMap._state.matrix)),n._specularMap&&n._specularMap._state.texture&&this._uSpecularMap&&(o.bindTexture(this._uSpecularMap,n._specularMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uSpecularMapMatrix&&s.uniformMatrix4fv(this._uSpecularMapMatrix,!1,n._specularMap._state.matrix)),n._emissiveMap&&n._emissiveMap._state.texture&&this._uEmissiveMap&&(o.bindTexture(this._uEmissiveMap,n._emissiveMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uEmissiveMapMatrix&&s.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,n._emissiveMap._state.matrix)),n._alphaMap&&n._alphaMap._state.texture&&this._uAlphaMap&&(o.bindTexture(this._uAlphaMap,n._alphaMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uAlphaMapMatrix&&s.uniformMatrix4fv(this._uAlphaMapMatrix,!1,n._alphaMap._state.matrix)),n._reflectivityMap&&n._reflectivityMap._state.texture&&this._uReflectivityMap&&(o.bindTexture(this._uReflectivityMap,n._reflectivityMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,this._uReflectivityMapMatrix&&s.uniformMatrix4fv(this._uReflectivityMapMatrix,!1,n._reflectivityMap._state.matrix)),n._normalMap&&n._normalMap._state.texture&&this._uNormalMap&&(o.bindTexture(this._uNormalMap,n._normalMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uNormalMapMatrix&&s.uniformMatrix4fv(this._uNormalMapMatrix,!1,n._normalMap._state.matrix)),n._occlusionMap&&n._occlusionMap._state.texture&&this._uOcclusionMap&&(o.bindTexture(this._uOcclusionMap,n._occlusionMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uOcclusionMapMatrix&&s.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,n._occlusionMap._state.matrix)),n._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias&&s.uniform1f(this._uDiffuseFresnelEdgeBias,n._diffuseFresnel.edgeBias),this._uDiffuseFresnelCenterBias&&s.uniform1f(this._uDiffuseFresnelCenterBias,n._diffuseFresnel.centerBias),this._uDiffuseFresnelEdgeColor&&s.uniform3fv(this._uDiffuseFresnelEdgeColor,n._diffuseFresnel.edgeColor),this._uDiffuseFresnelCenterColor&&s.uniform3fv(this._uDiffuseFresnelCenterColor,n._diffuseFresnel.centerColor),this._uDiffuseFresnelPower&&s.uniform1f(this._uDiffuseFresnelPower,n._diffuseFresnel.power)),n._specularFresnel&&(this._uSpecularFresnelEdgeBias&&s.uniform1f(this._uSpecularFresnelEdgeBias,n._specularFresnel.edgeBias),this._uSpecularFresnelCenterBias&&s.uniform1f(this._uSpecularFresnelCenterBias,n._specularFresnel.centerBias),this._uSpecularFresnelEdgeColor&&s.uniform3fv(this._uSpecularFresnelEdgeColor,n._specularFresnel.edgeColor),this._uSpecularFresnelCenterColor&&s.uniform3fv(this._uSpecularFresnelCenterColor,n._specularFresnel.centerColor),this._uSpecularFresnelPower&&s.uniform1f(this._uSpecularFresnelPower,n._specularFresnel.power)),n._alphaFresnel&&(this._uAlphaFresnelEdgeBias&&s.uniform1f(this._uAlphaFresnelEdgeBias,n._alphaFresnel.edgeBias),this._uAlphaFresnelCenterBias&&s.uniform1f(this._uAlphaFresnelCenterBias,n._alphaFresnel.centerBias),this._uAlphaFresnelEdgeColor&&s.uniform3fv(this._uAlphaFresnelEdgeColor,n._alphaFresnel.edgeColor),this._uAlphaFresnelCenterColor&&s.uniform3fv(this._uAlphaFresnelCenterColor,n._alphaFresnel.centerColor),this._uAlphaFresnelPower&&s.uniform1f(this._uAlphaFresnelPower,n._alphaFresnel.power)),n._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias&&s.uniform1f(this._uReflectivityFresnelEdgeBias,n._reflectivityFresnel.edgeBias),this._uReflectivityFresnelCenterBias&&s.uniform1f(this._uReflectivityFresnelCenterBias,n._reflectivityFresnel.centerBias),this._uReflectivityFresnelEdgeColor&&s.uniform3fv(this._uReflectivityFresnelEdgeColor,n._reflectivityFresnel.edgeColor),this._uReflectivityFresnelCenterColor&&s.uniform3fv(this._uReflectivityFresnelCenterColor,n._reflectivityFresnel.centerColor),this._uReflectivityFresnelPower&&s.uniform1f(this._uReflectivityFresnelPower,n._reflectivityFresnel.power)),n._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias&&s.uniform1f(this._uEmissiveFresnelEdgeBias,n._emissiveFresnel.edgeBias),this._uEmissiveFresnelCenterBias&&s.uniform1f(this._uEmissiveFresnelCenterBias,n._emissiveFresnel.centerBias),this._uEmissiveFresnelEdgeColor&&s.uniform3fv(this._uEmissiveFresnelEdgeColor,n._emissiveFresnel.edgeColor),this._uEmissiveFresnelCenterColor&&s.uniform3fv(this._uEmissiveFresnelCenterColor,n._emissiveFresnel.centerColor),this._uEmissiveFresnelPower&&s.uniform1f(this._uEmissiveFresnelPower,n._emissiveFresnel.power));break;case"MetallicMaterial":this._uBaseColor&&s.uniform3fv(this._uBaseColor,l.baseColor),this._uMaterialMetallic&&s.uniform1f(this._uMaterialMetallic,l.metallic),this._uMaterialRoughness&&s.uniform1f(this._uMaterialRoughness,l.roughness),this._uMaterialSpecularF0&&s.uniform1f(this._uMaterialSpecularF0,l.specularF0),this._uMaterialEmissive&&s.uniform3fv(this._uMaterialEmissive,l.emissive),this._uAlphaModeCutoff&&s.uniform4f(this._uAlphaModeCutoff,1*l.alpha,1===l.alphaMode?1:0,l.alphaCutoff,0);var x=n._baseColorMap;x&&x._state.texture&&this._uBaseColorMap&&(o.bindTexture(this._uBaseColorMap,x._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uBaseColorMapMatrix&&s.uniformMatrix4fv(this._uBaseColorMapMatrix,!1,x._state.matrix));var P=n._metallicMap;P&&P._state.texture&&this._uMetallicMap&&(o.bindTexture(this._uMetallicMap,P._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uMetallicMapMatrix&&s.uniformMatrix4fv(this._uMetallicMapMatrix,!1,P._state.matrix));var C=n._roughnessMap;C&&C._state.texture&&this._uRoughnessMap&&(o.bindTexture(this._uRoughnessMap,C._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uRoughnessMapMatrix&&s.uniformMatrix4fv(this._uRoughnessMapMatrix,!1,C._state.matrix));var M=n._metallicRoughnessMap;M&&M._state.texture&&this._uMetallicRoughnessMap&&(o.bindTexture(this._uMetallicRoughnessMap,M._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uMetallicRoughnessMapMatrix&&s.uniformMatrix4fv(this._uMetallicRoughnessMapMatrix,!1,M._state.matrix)),(I=n._emissiveMap)&&I._state.texture&&this._uEmissiveMap&&(o.bindTexture(this._uEmissiveMap,I._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uEmissiveMapMatrix&&s.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,I._state.matrix)),(T=n._occlusionMap)&&n._occlusionMap._state.texture&&this._uOcclusionMap&&(o.bindTexture(this._uOcclusionMap,T._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uOcclusionMapMatrix&&s.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,T._state.matrix)),(D=n._alphaMap)&&D._state.texture&&this._uAlphaMap&&(o.bindTexture(this._uAlphaMap,D._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uAlphaMapMatrix&&s.uniformMatrix4fv(this._uAlphaMapMatrix,!1,D._state.matrix)),(S=n._normalMap)&&S._state.texture&&this._uNormalMap&&(o.bindTexture(this._uNormalMap,S._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uNormalMapMatrix&&s.uniformMatrix4fv(this._uNormalMapMatrix,!1,S._state.matrix));break;case"SpecularMaterial":this._uMaterialDiffuse&&s.uniform3fv(this._uMaterialDiffuse,l.diffuse),this._uMaterialSpecular&&s.uniform3fv(this._uMaterialSpecular,l.specular),this._uMaterialGlossiness&&s.uniform1f(this._uMaterialGlossiness,l.glossiness),this._uMaterialReflectivity&&s.uniform1f(this._uMaterialReflectivity,l.reflectivity),this._uMaterialEmissive&&s.uniform3fv(this._uMaterialEmissive,l.emissive),this._uAlphaModeCutoff&&s.uniform4f(this._uAlphaModeCutoff,1*l.alpha,1===l.alphaMode?1:0,l.alphaCutoff,0);var k=n._diffuseMap;k&&k._state.texture&&this._uDiffuseMap&&(o.bindTexture(this._uDiffuseMap,k._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uDiffuseMapMatrix&&s.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,k._state.matrix));var E=n._specularMap;E&&E._state.texture&&this._uSpecularMap&&(o.bindTexture(this._uSpecularMap,E._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uSpecularMapMatrix&&s.uniformMatrix4fv(this._uSpecularMapMatrix,!1,E._state.matrix));var F=n._glossinessMap;F&&F._state.texture&&this._uGlossinessMap&&(o.bindTexture(this._uGlossinessMap,F._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uGlossinessMapMatrix&&s.uniformMatrix4fv(this._uGlossinessMapMatrix,!1,F._state.matrix));var I,T,D,S,R=n._specularGlossinessMap;R&&R._state.texture&&this._uSpecularGlossinessMap&&(o.bindTexture(this._uSpecularGlossinessMap,R._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uSpecularGlossinessMapMatrix&&s.uniformMatrix4fv(this._uSpecularGlossinessMapMatrix,!1,R._state.matrix)),(I=n._emissiveMap)&&I._state.texture&&this._uEmissiveMap&&(o.bindTexture(this._uEmissiveMap,I._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uEmissiveMapMatrix&&s.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,I._state.matrix)),(T=n._occlusionMap)&&T._state.texture&&this._uOcclusionMap&&(o.bindTexture(this._uOcclusionMap,T._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uOcclusionMapMatrix&&s.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,T._state.matrix)),(D=n._alphaMap)&&D._state.texture&&this._uAlphaMap&&(o.bindTexture(this._uAlphaMap,D._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uAlphaMapMatrix&&s.uniformMatrix4fv(this._uAlphaMapMatrix,!1,D._state.matrix)),(S=n._normalMap)&&S._state.texture&&this._uNormalMap&&(o.bindTexture(this._uNormalMap,S._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uNormalMapMatrix&&s.uniformMatrix4fv(this._uNormalMapMatrix,!1,S._state.matrix))}this._lastMaterialId=l.id}if(s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),this._uModelNormalMatrix&&s.uniformMatrix4fv(this._uModelNormalMatrix,s.FALSE,t.worldNormalMatrix),this._uClippable&&s.uniform1i(this._uClippable,a.clippable),this._uColorize){var U=a.colorize,L=this._lastColorize;L[0]===U[0]&&L[1]===U[1]&&L[2]===U[2]&&L[3]===U[3]||(s.uniform4fv(this._uColorize,U),L[0]=U[0],L[1]=U[1],L[2]=U[2],L[3]=U[3])}s.uniform3fv(this._uOffset,a.offset),s.uniform3fv(this._uScale,t.scale),u.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,u.positionsDecodeMatrix),this._uUVDecodeMatrix&&s.uniformMatrix3fv(this._uUVDecodeMatrix,!1,u.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(u.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(u.normalsBuf),e.bindArray++),this._aUV&&(this._aUV.bindArrayBuffer(u.uvBuf),e.bindArray++),this._aColor&&(this._aColor.bindArrayBuffer(u.colorsBuf),e.bindArray++),this._aFlags&&(this._aFlags.bindArrayBuffer(u.flagsBuf),e.bindArray++),u.indicesBuf&&(u.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=u.id),u.indicesBuf?(s.drawElements(u.primitive,u.indicesBuf.numItems,u.indicesBuf.itemType,0),e.drawElements++):u.positions&&(s.drawArrays(s.TRIANGLES,0,u.positions.numItems),e.drawArrays++),h&&s.depthFunc(s.LESS)},Ir.prototype._allocate=function(e){var t=e.scene,i=t.canvas.gl,r=e._material,n=t._lightsState,s=t._sectionPlanesState,o=e._material._state;if(this._program=new Pr(i,this._shaderSource),this._program.errors)this.errors=this._program.errors;else{var a=this._program;this._uPositionsDecodeMatrix=a.getLocation("positionsDecodeMatrix"),this._uUVDecodeMatrix=a.getLocation("uvDecodeMatrix"),this._uModelMatrix=a.getLocation("modelMatrix"),this._uModelNormalMatrix=a.getLocation("modelNormalMatrix"),this._uViewMatrix=a.getLocation("viewMatrix"),this._uViewNormalMatrix=a.getLocation("viewNormalMatrix"),this._uProjMatrix=a.getLocation("projMatrix"),this._uGammaFactor=a.getLocation("gammaFactor"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[],this._uShadowViewMatrix=[],this._uShadowProjMatrix=[],t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=a.getLocation("logDepthBufFC"));for(var l,u=n.lights,c=0,A=u.length;c<A;c++){switch((l=u[c]).type){case"ambient":this._uLightAmbient[c]=a.getLocation("lightAmbient");break;case"dir":this._uLightColor[c]=a.getLocation("lightColor"+c),this._uLightPos[c]=null,this._uLightDir[c]=a.getLocation("lightDir"+c);break;case"point":this._uLightColor[c]=a.getLocation("lightColor"+c),this._uLightPos[c]=a.getLocation("lightPos"+c),this._uLightDir[c]=null,this._uLightAttenuation[c]=a.getLocation("lightAttenuation"+c);break;case"spot":this._uLightColor[c]=a.getLocation("lightColor"+c),this._uLightPos[c]=a.getLocation("lightPos"+c),this._uLightDir[c]=a.getLocation("lightDir"+c),this._uLightAttenuation[c]=a.getLocation("lightAttenuation"+c)}l.castsShadow&&(this._uShadowViewMatrix[c]=a.getLocation("shadowViewMatrix"+c),this._uShadowProjMatrix[c]=a.getLocation("shadowProjMatrix"+c))}n.lightMaps.length>0&&(this._uLightMap="lightMap"),n.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(c=0,A=s.sectionPlanes.length;c<A;c++)this._uSectionPlanes.push({active:a.getLocation("sectionPlaneActive"+c),pos:a.getLocation("sectionPlanePos"+c),dir:a.getLocation("sectionPlaneDir"+c)});switch(this._uPointSize=a.getLocation("pointSize"),o.type){case"LambertMaterial":this._uMaterialColor=a.getLocation("materialColor"),this._uMaterialEmissive=a.getLocation("materialEmissive"),this._uAlphaModeCutoff=a.getLocation("materialAlphaModeCutoff");break;case"PhongMaterial":this._uMaterialAmbient=a.getLocation("materialAmbient"),this._uMaterialDiffuse=a.getLocation("materialDiffuse"),this._uMaterialSpecular=a.getLocation("materialSpecular"),this._uMaterialEmissive=a.getLocation("materialEmissive"),this._uAlphaModeCutoff=a.getLocation("materialAlphaModeCutoff"),this._uMaterialShininess=a.getLocation("materialShininess"),r._ambientMap&&(this._uMaterialAmbientMap="ambientMap",this._uMaterialAmbientMapMatrix=a.getLocation("ambientMapMatrix")),r._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=a.getLocation("diffuseMapMatrix")),r._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=a.getLocation("specularMapMatrix")),r._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=a.getLocation("emissiveMapMatrix")),r._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=a.getLocation("alphaMapMatrix")),r._reflectivityMap&&(this._uReflectivityMap="reflectivityMap",this._uReflectivityMapMatrix=a.getLocation("reflectivityMapMatrix")),r._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=a.getLocation("normalMapMatrix")),r._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=a.getLocation("occlusionMapMatrix")),r._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias=a.getLocation("diffuseFresnelEdgeBias"),this._uDiffuseFresnelCenterBias=a.getLocation("diffuseFresnelCenterBias"),this._uDiffuseFresnelEdgeColor=a.getLocation("diffuseFresnelEdgeColor"),this._uDiffuseFresnelCenterColor=a.getLocation("diffuseFresnelCenterColor"),this._uDiffuseFresnelPower=a.getLocation("diffuseFresnelPower")),r._specularFresnel&&(this._uSpecularFresnelEdgeBias=a.getLocation("specularFresnelEdgeBias"),this._uSpecularFresnelCenterBias=a.getLocation("specularFresnelCenterBias"),this._uSpecularFresnelEdgeColor=a.getLocation("specularFresnelEdgeColor"),this._uSpecularFresnelCenterColor=a.getLocation("specularFresnelCenterColor"),this._uSpecularFresnelPower=a.getLocation("specularFresnelPower")),r._alphaFresnel&&(this._uAlphaFresnelEdgeBias=a.getLocation("alphaFresnelEdgeBias"),this._uAlphaFresnelCenterBias=a.getLocation("alphaFresnelCenterBias"),this._uAlphaFresnelEdgeColor=a.getLocation("alphaFresnelEdgeColor"),this._uAlphaFresnelCenterColor=a.getLocation("alphaFresnelCenterColor"),this._uAlphaFresnelPower=a.getLocation("alphaFresnelPower")),r._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias=a.getLocation("reflectivityFresnelEdgeBias"),this._uReflectivityFresnelCenterBias=a.getLocation("reflectivityFresnelCenterBias"),this._uReflectivityFresnelEdgeColor=a.getLocation("reflectivityFresnelEdgeColor"),this._uReflectivityFresnelCenterColor=a.getLocation("reflectivityFresnelCenterColor"),this._uReflectivityFresnelPower=a.getLocation("reflectivityFresnelPower")),r._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias=a.getLocation("emissiveFresnelEdgeBias"),this._uEmissiveFresnelCenterBias=a.getLocation("emissiveFresnelCenterBias"),this._uEmissiveFresnelEdgeColor=a.getLocation("emissiveFresnelEdgeColor"),this._uEmissiveFresnelCenterColor=a.getLocation("emissiveFresnelCenterColor"),this._uEmissiveFresnelPower=a.getLocation("emissiveFresnelPower"));break;case"MetallicMaterial":this._uBaseColor=a.getLocation("materialBaseColor"),this._uMaterialMetallic=a.getLocation("materialMetallic"),this._uMaterialRoughness=a.getLocation("materialRoughness"),this._uMaterialSpecularF0=a.getLocation("materialSpecularF0"),this._uMaterialEmissive=a.getLocation("materialEmissive"),this._uAlphaModeCutoff=a.getLocation("materialAlphaModeCutoff"),r._baseColorMap&&(this._uBaseColorMap="baseColorMap",this._uBaseColorMapMatrix=a.getLocation("baseColorMapMatrix")),r._metallicMap&&(this._uMetallicMap="metallicMap",this._uMetallicMapMatrix=a.getLocation("metallicMapMatrix")),r._roughnessMap&&(this._uRoughnessMap="roughnessMap",this._uRoughnessMapMatrix=a.getLocation("roughnessMapMatrix")),r._metallicRoughnessMap&&(this._uMetallicRoughnessMap="metallicRoughnessMap",this._uMetallicRoughnessMapMatrix=a.getLocation("metallicRoughnessMapMatrix")),r._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=a.getLocation("emissiveMapMatrix")),r._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=a.getLocation("occlusionMapMatrix")),r._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=a.getLocation("alphaMapMatrix")),r._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=a.getLocation("normalMapMatrix"));break;case"SpecularMaterial":this._uMaterialDiffuse=a.getLocation("materialDiffuse"),this._uMaterialSpecular=a.getLocation("materialSpecular"),this._uMaterialGlossiness=a.getLocation("materialGlossiness"),this._uMaterialReflectivity=a.getLocation("reflectivityFresnel"),this._uMaterialEmissive=a.getLocation("materialEmissive"),this._uAlphaModeCutoff=a.getLocation("materialAlphaModeCutoff"),r._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=a.getLocation("diffuseMapMatrix")),r._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=a.getLocation("specularMapMatrix")),r._glossinessMap&&(this._uGlossinessMap="glossinessMap",this._uGlossinessMapMatrix=a.getLocation("glossinessMapMatrix")),r._specularGlossinessMap&&(this._uSpecularGlossinessMap="materialSpecularGlossinessMap",this._uSpecularGlossinessMapMatrix=a.getLocation("materialSpecularGlossinessMapMatrix")),r._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=a.getLocation("emissiveMapMatrix")),r._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=a.getLocation("occlusionMapMatrix")),r._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=a.getLocation("alphaMapMatrix")),r._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=a.getLocation("normalMapMatrix"))}this._aPosition=a.getAttribute("position"),this._aNormal=a.getAttribute("normal"),this._aUV=a.getAttribute("uv"),this._aColor=a.getAttribute("color"),this._aFlags=a.getAttribute("flags"),this._uClippable=a.getLocation("clippable"),this._uColorize=a.getLocation("colorize"),this._uOffset=a.getLocation("offset"),this._uScale=a.getLocation("scale"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize=new Float32Array(4),this._baseTextureUnit=0}},Ir.prototype._bindProgram=function(e){var t,i=Cr.MAX_TEXTURE_UNITS,r=this._scene,n=r.canvas.gl,s=r._lightsState,o=r.camera.project,a=this._program;if(a.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize[0]=-1,this._lastColorize[1]=-1,this._lastColorize[2]=-1,this._lastColorize[3]=-1,n.uniformMatrix4fv(this._uProjMatrix,!1,o.matrix),r.logarithmicDepthBufferEnabled){var l=2/(Math.log(o.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,l)}for(var u=0,c=s.lights.length;u<c;u++)if(t=s.lights[u],this._uLightAmbient[u])n.uniform4f(this._uLightAmbient[u],t.color[0],t.color[1],t.color[2],t.intensity);else if(this._uLightColor[u]&&n.uniform4f(this._uLightColor[u],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[u]&&(n.uniform3fv(this._uLightPos[u],t.pos),this._uLightAttenuation[u]&&n.uniform1f(this._uLightAttenuation[u],t.attenuation)),this._uLightDir[u]&&n.uniform3fv(this._uLightDir[u],t.dir),t.castsShadow){this._uShadowViewMatrix[u]&&n.uniformMatrix4fv(this._uShadowViewMatrix[u],!1,t.getShadowViewMatrix()),this._uShadowProjMatrix[u]&&n.uniformMatrix4fv(this._uShadowProjMatrix[u],!1,t.getShadowProjMatrix());var A=t.getShadowRenderBuf();A&&(a.bindTexture("shadowMap"+u,A.getTexture(),e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++)}s.lightMaps.length>0&&s.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,s.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++),s.reflectionMaps.length>0&&s.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,s.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++),this._uGammaFactor&&n.uniform1f(this._uGammaFactor,r.gammaFactor),this._baseTextureUnit=e.textureUnit};var Dr=I((function e(t){E(this,e),this.vertex=function(e){var t=e.scene,i=t._lightsState,r=function(e){var t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),n=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=!!e._geometry._state.compressGeometry,o=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),l.push("uniform vec3 scale;"),s&&l.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;"));n&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),r){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(var u=0,c=i.lights.length;u<c;u++){var A=i.lights[u];"ambient"!==A.type&&(l.push("uniform vec4 lightColor"+u+";"),"dir"===A.type&&l.push("uniform vec3 lightDir"+u+";"),"point"===A.type&&l.push("uniform vec3 lightPos"+u+";"),"spot"===A.type&&l.push("uniform vec3 lightPos"+u+";"))}s&&(l.push("vec3 octDecode(vec2 oct) {"),l.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),l.push(" if (v.z < 0.0) {"),l.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}l.push("out vec4 vColor;"),("spherical"===o||"cylindrical"===o)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = scale[0];"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===o&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = scale[1];"),l.push(" mat[1][2] = 0.0;")),l.push(" mat[2][0] = 0.0;"),l.push(" mat[2][1] = 0.0;"),l.push(" mat[2][2] =1.0;"),l.push("}"));l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),s&&l.push("localPosition = positionsDecodeMatrix * localPosition;");r&&(s?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),r&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),r)for(var h=0,d=i.lights.length;h<d;h++){var p=i.lights[h];if("ambient"!==p.type){if("dir"===p.type)"view"===p.space?l.push("viewLightDir = normalize(lightDir"+h+");"):l.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+h+", 0.0)).xyz);");else{if("point"!==p.type)continue;"view"===p.space?l.push("viewLightDir = normalize(lightPos"+h+" - viewPosition.xyz);"):l.push("viewLightDir = normalize((viewMatrix2 * vec4(lightPos"+h+", 0.0)).xyz);")}l.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),l.push("reflectedColor += lambertian * (lightColor"+h+".rgb * lightColor"+h+".a);")}}l.push("vColor = vec4(reflectedColor * fillColor.rgb, fillColor.a);"),n&&l.push("vWorldPosition = worldPosition;");"points"===e._geometry._state.primitiveName&&l.push("gl_PointSize = pointSize;");l.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(l.push("vFragDepth = 1.0 + clipPos.w;"),l.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return l.push("gl_Position = clipPos;"),l.push("}"),l}(t),this.fragment=function(e){var t=e.scene,i=e.scene._sectionPlanesState,r=e.scene.gammaOutput,n=i.getNumAllocatedSectionPlanes()>0,s=[];s.push("#version 300 es"),s.push("// Lambertian drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"));r&&(s.push("uniform float gammaFactor;"),s.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),s.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),s.push("}"));if(n){s.push("in vec4 vWorldPosition;"),s.push("uniform bool clippable;");for(var o=0,a=i.getNumAllocatedSectionPlanes();o<a;o++)s.push("uniform bool sectionPlaneActive"+o+";"),s.push("uniform vec3 sectionPlanePos"+o+";"),s.push("uniform vec3 sectionPlaneDir"+o+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),n){s.push("if (clippable) {"),s.push(" float dist = 0.0;");for(var l=0,u=i.getNumAllocatedSectionPlanes();l<u;l++)s.push("if (sectionPlaneActive"+l+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+l+".xyz, vWorldPosition.xyz - sectionPlanePos"+l+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}"points"===e._geometry._state.primitiveName&&(s.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push("float r = dot(cxy, cxy);"),s.push("if (r > 1.0) {"),s.push(" discard;"),s.push("}"));t.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");r?s.push("outColor = linearToGamma(vColor, gammaFactor);"):s.push("outColor = vColor;");return s.push("}"),s}(t)}));var Sr=new Z({}),Rr=le.vec3(),Ur=function(e,t){this.id=Sr.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Dr(t),this._allocate(t)},Lr={};Ur.get=function(e){var t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";"),i=Lr[t];return i||(i=new Ur(t,e),Lr[t]=i,he.memory.programs++),i._useCount++,i},Ur.prototype.put=function(){0==--this._useCount&&(Sr.removeItem(this.id),this._program&&this._program.destroy(),delete Lr[this._hash],he.memory.programs--)},Ur.prototype.webglContextRestored=function(){this._program=null},Ur.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);var r=this._scene,n=r.camera,s=r.canvas.gl,o=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,u=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,u?e.getRTCViewMatrix(a.originHash,u):n.viewMatrix),s.uniformMatrix4fv(this._uViewNormalMatrix,!1,n.viewNormalMatrix),a.clippable){var c=r._sectionPlanesState.getNumAllocatedSectionPlanes(),A=r._sectionPlanesState.sectionPlanes.length;if(c>0)for(var h=r._sectionPlanesState.sectionPlanes,d=t.renderFlags,p=0;p<c;p++){var f=this._uSectionPlanes[p];if(f)if(p<A){var v=d.sectionPlanesActivePerLayer[p];if(s.uniform1i(f.active,v?1:0),v){var g=h[p];if(u){var m=ei(g.dist,g.dir,u,Rr);s.uniform3fv(f.pos,m)}else s.uniform3fv(f.pos,g.pos);s.uniform3fv(f.dir,g.dir)}}else s.uniform1i(f.active,0)}}if(o.id!==this._lastMaterialId){var _=o.fillColor,y=o.backfaces;e.backfaces!==y&&(y?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=y),s.uniform4f(this._uFillColor,_[0],_[1],_[2],o.fillAlpha),this._lastMaterialId=o.id}s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),this._uModelNormalMatrix&&s.uniformMatrix4fv(this._uModelNormalMatrix,s.FALSE,t.worldNormalMatrix),this._uClippable&&s.uniform1i(this._uClippable,a.clippable),s.uniform3fv(this._uOffset,a.offset),l.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,l.positionsDecodeMatrix),this._uUVDecodeMatrix&&s.uniformMatrix3fv(this._uUVDecodeMatrix,!1,l.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(l.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(l.normalsBuf),e.bindArray++),l.indicesBuf?(l.indicesBuf.bind(),e.bindArray++):l.positionsBuf,this._lastGeometryId=l.id),l.indicesBuf?(s.drawElements(l.primitive,l.indicesBuf.numItems,l.indicesBuf.itemType,0),e.drawElements++):l.positionsBuf&&(s.drawArrays(s.TRIANGLES,0,l.positionsBuf.numItems),e.drawArrays++)},Ur.prototype._allocate=function(e){var t=e.scene,i=t._lightsState,r=t._sectionPlanesState,n=t.canvas.gl;if(this._program=new Pr(n,this._shaderSource),this._program.errors)this.errors=this._program.errors;else{var s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uModelNormalMatrix=s.getLocation("modelNormalMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uViewNormalMatrix=s.getLocation("viewNormalMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(var o=0,a=i.lights.length;o<a;o++){switch(i.lights[o].type){case"ambient":this._uLightAmbient[o]=s.getLocation("lightAmbient");break;case"dir":this._uLightColor[o]=s.getLocation("lightColor"+o),this._uLightPos[o]=null,this._uLightDir[o]=s.getLocation("lightDir"+o);break;case"point":this._uLightColor[o]=s.getLocation("lightColor"+o),this._uLightPos[o]=s.getLocation("lightPos"+o),this._uLightDir[o]=null,this._uLightAttenuation[o]=s.getLocation("lightAttenuation"+o)}}this._uSectionPlanes=[];for(var l=0,u=r.getNumAllocatedSectionPlanes();l<u;l++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+l),pos:s.getLocation("sectionPlanePos"+l),dir:s.getLocation("sectionPlaneDir"+l)});this._uFillColor=s.getLocation("fillColor"),this._aPosition=s.getAttribute("position"),this._aNormal=s.getAttribute("normal"),this._uClippable=s.getLocation("clippable"),this._uGammaFactor=s.getLocation("gammaFactor"),this._uOffset=s.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null}},Ur.prototype._bindProgram=function(e){var t=this._scene,i=t.canvas.gl,r=t._lightsState,n=t.camera,s=n.project;if(this._program.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastIndicesBufId=null,i.uniformMatrix4fv(this._uViewNormalMatrix,!1,n.normalMatrix),i.uniformMatrix4fv(this._uProjMatrix,!1,s.matrix),t.logarithmicDepthBufferEnabled){var o=2/(Math.log(s.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,o)}for(var a=0,l=r.lights.length;a<l;a++){var u=r.lights[a];this._uLightAmbient[a]?i.uniform4f(this._uLightAmbient[a],u.color[0],u.color[1],u.color[2],u.intensity):(this._uLightColor[a]&&i.uniform4f(this._uLightColor[a],u.color[0],u.color[1],u.color[2],u.intensity),this._uLightPos[a]&&(i.uniform3fv(this._uLightPos[a],u.pos),this._uLightAttenuation[a]&&i.uniform1f(this._uLightAttenuation[a],u.attenuation)),this._uLightDir[a]&&i.uniform3fv(this._uLightDir[a],u.dir))}this._uGammaFactor&&i.uniform1f(this._uGammaFactor,t.gammaFactor)};var Or=I((function e(t){E(this,e),this.vertex=function(e){var t=e.scene,i=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,r=!!e._geometry._state.compressGeometry,n=e._state.billboard,s=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// Edges drawing vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec4 edgeColor;"),o.push("uniform vec3 offset;"),o.push("uniform vec3 scale;"),r&&o.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;"));i&&o.push("out vec4 vWorldPosition;");o.push("out vec4 vColor;"),("spherical"===n||"cylindrical"===n)&&(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = scale[0];"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===n&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = scale[1];"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}"));o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),o.push("vec4 worldPosition;"),r&&o.push("localPosition = positionsDecodeMatrix * localPosition;");o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),s&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"),o.push("billboard(modelViewMatrix);"),o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));o.push("vColor = edgeColor;"),i&&o.push("vWorldPosition = worldPosition;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = clipPos;"),o.push("}"),o}(t),this.fragment=function(e){var t=e.scene,i=e.scene._sectionPlanesState,r=e.scene.gammaOutput,n=i.getNumAllocatedSectionPlanes()>0,s=[];s.push("#version 300 es"),s.push("// Edges drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"));r&&(s.push("uniform float gammaFactor;"),s.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),s.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),s.push("}"));if(n){s.push("in vec4 vWorldPosition;"),s.push("uniform bool clippable;");for(var o=0,a=i.getNumAllocatedSectionPlanes();o<a;o++)s.push("uniform bool sectionPlaneActive"+o+";"),s.push("uniform vec3 sectionPlanePos"+o+";"),s.push("uniform vec3 sectionPlaneDir"+o+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),n){s.push("if (clippable) {"),s.push(" float dist = 0.0;");for(var l=0,u=i.getNumAllocatedSectionPlanes();l<u;l++)s.push("if (sectionPlaneActive"+l+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+l+".xyz, vWorldPosition.xyz - sectionPlanePos"+l+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}t.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");r?s.push("outColor = linearToGamma(vColor, gammaFactor);"):s.push("outColor = vColor;");return s.push("}"),s}(t)}));var Nr=new Z({}),Vr=le.vec3(),Qr=function(e,t){this.id=Nr.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Or(t),this._allocate(t)},Hr={};Qr.get=function(e){var t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";"),i=Hr[t];return i||(i=new Qr(t,e),Hr[t]=i,he.memory.programs++),i._useCount++,i},Qr.prototype.put=function(){0==--this._useCount&&(Nr.removeItem(this.id),this._program&&this._program.destroy(),delete Hr[this._hash],he.memory.programs--)},Qr.prototype.webglContextRestored=function(){this._program=null},Qr.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);var r,n,s=this._scene,o=s.camera,a=s.canvas.gl,l=t._state,u=t._geometry,c=u._state,A=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,A?e.getRTCViewMatrix(l.originHash,A):o.viewMatrix),l.clippable){var h=s._sectionPlanesState.getNumAllocatedSectionPlanes(),d=s._sectionPlanesState.sectionPlanes.length;if(h>0)for(var p=s._sectionPlanesState.sectionPlanes,f=t.renderFlags,v=0;v<h;v++){var g=this._uSectionPlanes[v];if(g)if(v<d){var m=f.sectionPlanesActivePerLayer[v];if(a.uniform1i(g.active,m?1:0),m){var _=p[v];if(A){var y=ei(_.dist,_.dir,A,Vr);a.uniform3fv(g.pos,y)}else a.uniform3fv(g.pos,_.pos);a.uniform3fv(g.dir,_.dir)}}else a.uniform1i(g.active,0)}}switch(i){case 0:r=t._xrayMaterial._state;break;case 1:r=t._highlightMaterial._state;break;case 2:r=t._selectedMaterial._state;break;default:r=t._edgeMaterial._state}if(r.id!==this._lastMaterialId){var b=r.backfaces;if(e.backfaces!==b&&(b?a.disable(a.CULL_FACE):a.enable(a.CULL_FACE),e.backfaces=b),e.lineWidth!==r.edgeWidth&&(a.lineWidth(r.edgeWidth),e.lineWidth=r.edgeWidth),this._uEdgeColor){var w=r.edgeColor,B=r.edgeAlpha;a.uniform4f(this._uEdgeColor,w[0],w[1],w[2],B)}this._lastMaterialId=r.id}a.uniformMatrix4fv(this._uModelMatrix,a.FALSE,t.worldMatrix),this._uClippable&&a.uniform1i(this._uClippable,l.clippable),a.uniform3fv(this._uOffset,l.offset),c.primitive===a.TRIANGLES?n=u._getEdgeIndices():c.primitive===a.LINES&&(n=c.indicesBuf),n&&(c.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,c.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(c.positionsBuf,c.compressGeometry?a.UNSIGNED_SHORT:a.FLOAT),e.bindArray++),n.bind(),e.bindArray++,this._lastGeometryId=c.id),a.drawElements(a.LINES,n.numItems,n.itemType,0),e.drawElements++)},Qr.prototype._allocate=function(e){var t=e.scene,i=t.canvas.gl,r=t._sectionPlanesState;if(this._program=new Pr(i,this._shaderSource),this._program.errors)this.errors=this._program.errors;else{var n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,o=r.getNumAllocatedSectionPlanes();s<o;s++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+s),pos:n.getLocation("sectionPlanePos"+s),dir:n.getLocation("sectionPlaneDir"+s)});this._uEdgeColor=n.getLocation("edgeColor"),this._aPosition=n.getAttribute("position"),this._uClippable=n.getLocation("clippable"),this._uGammaFactor=n.getLocation("gammaFactor"),this._uOffset=n.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null}},Qr.prototype._bindProgram=function(e){var t=this._program,i=this._scene,r=i.canvas.gl,n=i.camera.project;if(t.bind(),e.useProgram++,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,r.uniformMatrix4fv(this._uProjMatrix,!1,n.matrix),i.logarithmicDepthBufferEnabled){var s=2/(Math.log(n.far+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,s)}this._uGammaFactor&&r.uniform1f(this._uGammaFactor,i.gammaFactor)};var jr=I((function e(t){E(this,e),this.vertex=function(e){var t=e.scene,i=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,r=!!e._geometry._state.compressGeometry,n=e._state.billboard,s=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// Mesh picking vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("out vec4 vViewPosition;"),o.push("uniform vec3 offset;"),o.push("uniform vec3 scale;"),r&&o.push("uniform mat4 positionsDecodeMatrix;");i&&o.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;"));"spherical"!==n&&"cylindrical"!==n||(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = scale[0];"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===n&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = scale[1];"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}"));o.push("uniform vec2 pickClipPos;"),o.push("vec4 remapClipPos(vec4 clipPos) {"),o.push(" clipPos.xy /= clipPos.w;"),o.push(" clipPos.xy -= pickClipPos;"),o.push(" clipPos.xy *= clipPos.w;"),o.push(" return clipPos;"),o.push("}"),o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),r&&o.push("localPosition = positionsDecodeMatrix * localPosition;");o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),s&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==n&&"cylindrical"!==n||(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"));o.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&o.push(" vWorldPosition = worldPosition;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = remapClipPos(clipPos);"),o.push("}"),o}(t),this.fragment=function(e){var t=e.scene,i=t._sectionPlanesState,r=i.getNumAllocatedSectionPlanes()>0,n=[];n.push("#version 300 es"),n.push("// Mesh picking fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));if(n.push("uniform vec4 pickColor;"),r){n.push("uniform bool clippable;"),n.push("in vec4 vWorldPosition;");for(var s=0;s<i.getNumAllocatedSectionPlanes();s++)n.push("uniform bool sectionPlaneActive"+s+";"),n.push("uniform vec3 sectionPlanePos"+s+";"),n.push("uniform vec3 sectionPlaneDir"+s+";")}if(n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push("if (clippable) {"),n.push(" float dist = 0.0;");for(s=0;s<i.getNumAllocatedSectionPlanes();s++)n.push("if (sectionPlaneActive"+s+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return n.push(" outColor = pickColor; "),n.push("}"),n}(t)}));var Gr=le.vec3(),zr=function(e,t){this._hash=e,this._shaderSource=new jr(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Wr={};zr.get=function(e){var t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";"),i=Wr[t];if(!i){if((i=new zr(t,e)).errors)return console.log(i.errors.join("\n")),null;Wr[t]=i,he.memory.programs++}return i._useCount++,i},zr.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Wr[this._hash],he.memory.programs--)},zr.prototype.webglContextRestored=function(){this._program=null},zr.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene,r=i.canvas.gl,n=t._state,s=t._material._state,o=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(n.originHash,a):e.pickViewMatrix),n.clippable){var l=i._sectionPlanesState.getNumAllocatedSectionPlanes(),u=i._sectionPlanesState.sectionPlanes.length;if(l>0)for(var c=i._sectionPlanesState.sectionPlanes,A=t.renderFlags,h=0;h<l;h++){var d=this._uSectionPlanes[h];if(d)if(h<u){var p=A.sectionPlanesActivePerLayer[h];if(r.uniform1i(d.active,p?1:0),p){var f=c[h];if(a){var v=ei(f.dist,f.dir,a,Gr);r.uniform3fv(d.pos,v)}else r.uniform3fv(d.pos,f.pos);r.uniform3fv(d.dir,f.dir)}}else r.uniform1i(d.active,0)}}if(s.id!==this._lastMaterialId){var g=s.backfaces;e.backfaces!==g&&(g?r.disable(r.CULL_FACE):r.enable(r.CULL_FACE),e.backfaces=g);var m=s.frontface;e.frontface!==m&&(m?r.frontFace(r.CCW):r.frontFace(r.CW),e.frontface=m),this._lastMaterialId=s.id}r.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),r.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&r.uniform1i(this._uClippable,t._state.clippable),r.uniform3fv(this._uOffset,t._state.offset),o.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&r.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,o.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(o.positionsBuf,o.compressGeometry?r.UNSIGNED_SHORT:r.FLOAT),e.bindArray++),o.indicesBuf&&(o.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=o.id);var _=t._state.pickID,y=_>>24&255,b=_>>16&255,w=_>>8&255,B=255&_;r.uniform4f(this._uPickColor,B/255,w/255,b/255,y/255),r.uniform2fv(this._uPickClipPos,e.pickClipPos),o.indicesBuf?(r.drawElements(o.primitive,o.indicesBuf.numItems,o.indicesBuf.itemType,0),e.drawElements++):o.positions&&r.drawArrays(r.TRIANGLES,0,o.positions.numItems)},zr.prototype._allocate=function(e){var t=e.scene,i=t.canvas.gl;if(this._program=new Pr(i,this._shaderSource),this._program.errors)this.errors=this._program.errors;else{var r=this._program;this._uPositionsDecodeMatrix=r.getLocation("positionsDecodeMatrix"),this._uModelMatrix=r.getLocation("modelMatrix"),this._uViewMatrix=r.getLocation("viewMatrix"),this._uProjMatrix=r.getLocation("projMatrix"),this._uSectionPlanes=[];for(var n=0,s=t._sectionPlanesState.sectionPlanes.length;n<s;n++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+n),pos:r.getLocation("sectionPlanePos"+n),dir:r.getLocation("sectionPlaneDir"+n)});this._aPosition=r.getAttribute("position"),this._uClippable=r.getLocation("clippable"),this._uPickColor=r.getLocation("pickColor"),this._uPickClipPos=r.getLocation("pickClipPos"),this._uOffset=r.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=r.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastGeometryId=null}},zr.prototype._bindProgram=function(e){var t=this._scene,i=t.canvas.gl,r=t.camera.project;if(this._program.bind(),e.useProgram++,t.logarithmicDepthBufferEnabled){var n=2/(Math.log(r.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,n)}this._lastMaterialId=null,this._lastGeometryId=null};var Xr=I((function e(t){E(this,e),this.vertex=function(e){var t=e.scene,i=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,r=!!e._geometry._state.compressGeometry,n=[];n.push("#version 300 es"),n.push("// Surface picking vertex shader"),n.push("in vec3 position;"),n.push("in vec4 color;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec3 offset;"),i&&(n.push("uniform bool clippable;"),n.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));n.push("uniform vec2 pickClipPos;"),n.push("vec4 remapClipPos(vec4 clipPos) {"),n.push(" clipPos.xy /= clipPos.w;"),n.push(" clipPos.xy -= pickClipPos;"),n.push(" clipPos.xy *= clipPos.w;"),n.push(" return clipPos;"),n.push("}"),n.push("out vec4 vColor;"),r&&n.push("uniform mat4 positionsDecodeMatrix;");n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),r&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push(" vec4 worldPosition = modelMatrix * localPosition; "),n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&n.push(" vWorldPosition = worldPosition;");n.push(" vColor = color;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = remapClipPos(clipPos);"),n.push("}"),n}(t),this.fragment=function(e){var t=e.scene,i=t._sectionPlanesState,r=i.getNumAllocatedSectionPlanes()>0,n=[];n.push("#version 300 es"),n.push("// Surface picking fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),n.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));if(r){n.push("uniform bool clippable;"),n.push("in vec4 vWorldPosition;");for(var s=0;s<i.getNumAllocatedSectionPlanes();s++)n.push("uniform bool sectionPlaneActive"+s+";"),n.push("uniform vec3 sectionPlanePos"+s+";"),n.push("uniform vec3 sectionPlaneDir"+s+";")}if(n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push("if (clippable) {"),n.push(" float dist = 0.0;");for(var o=0;o<i.getNumAllocatedSectionPlanes();o++)n.push("if (sectionPlaneActive"+o+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return n.push(" outColor = vColor;"),n.push("}"),n}(t)}));var Kr=le.vec3(),Zr=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Xr(t),this._allocate(t)},Jr={};Zr.get=function(e){var t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";"),i=Jr[t];if(!i){if((i=new Zr(t,e)).errors)return console.log(i.errors.join("\n")),null;Jr[t]=i,he.memory.programs++}return i._useCount++,i},Zr.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Jr[this._hash],he.memory.programs--)},Zr.prototype.webglContextRestored=function(){this._program=null},Zr.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene,r=i.canvas.gl,n=t._state,s=t._material._state,o=t._geometry,a=t._geometry._state,l=t.origin,u=s.backfaces,c=s.frontface,A=i.camera.project,h=o._getPickTrianglePositions(),d=o._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){var p=2/(Math.log(A.far+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,p)}if(r.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(n.originHash,l):e.pickViewMatrix),n.clippable){var f=i._sectionPlanesState.getNumAllocatedSectionPlanes(),v=i._sectionPlanesState.sectionPlanes.length;if(f>0)for(var g=i._sectionPlanesState.sectionPlanes,m=t.renderFlags,_=0;_<f;_++){var y=this._uSectionPlanes[_];if(y)if(_<v){var b=m.sectionPlanesActivePerLayer[_];if(r.uniform1i(y.active,b?1:0),b){var w=g[_];if(l){var B=ei(w.dist,w.dir,l,Kr);r.uniform3fv(y.pos,B)}else r.uniform3fv(y.pos,w.pos);r.uniform3fv(y.dir,w.dir)}}else r.uniform1i(y.active,0)}}r.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),i.logarithmicDepthBufferEnabled&&r.uniform1f(this._uZFar,i.camera.project.far),e.backfaces!==u&&(u?r.disable(r.CULL_FACE):r.enable(r.CULL_FACE),e.backfaces=u),e.frontface!==c&&(c?r.frontFace(r.CCW):r.frontFace(r.CW),e.frontface=c),r.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&r.uniform1i(this._uClippable,t._state.clippable),r.uniform3fv(this._uOffset,t._state.offset),this._uPositionsDecodeMatrix?(r.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,a.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(h,a.compressGeometry?r.UNSIGNED_SHORT:r.FLOAT)):this._aPosition.bindArrayBuffer(h),r.uniform2fv(this._uPickClipPos,e.pickClipPos),d.bind(),r.enableVertexAttribArray(this._aColor.location),r.vertexAttribPointer(this._aColor.location,d.itemSize,d.itemType,!0,0,0),r.drawArrays(a.primitive,0,h.numItems/3)},Zr.prototype._allocate=function(e){var t=e.scene,i=t.canvas.gl;if(this._program=new Pr(i,this._shaderSource),this._useCount=0,this._program.errors)this.errors=this._program.errors;else{var r=this._program;this._uPositionsDecodeMatrix=r.getLocation("positionsDecodeMatrix"),this._uModelMatrix=r.getLocation("modelMatrix"),this._uViewMatrix=r.getLocation("viewMatrix"),this._uProjMatrix=r.getLocation("projMatrix"),this._uSectionPlanes=[];for(var n=0,s=t._sectionPlanesState.sectionPlanes.length;n<s;n++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+n),pos:r.getLocation("sectionPlanePos"+n),dir:r.getLocation("sectionPlaneDir"+n)});this._aPosition=r.getAttribute("position"),this._aColor=r.getAttribute("color"),this._uPickClipPos=r.getLocation("pickClipPos"),this._uClippable=r.getLocation("clippable"),this._uOffset=r.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=r.getLocation("logDepthBufFC"))}};var Yr=I((function e(t){E(this,e),this.vertex=function(e){var t=e.scene,i=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,r=!!e._geometry._state.compressGeometry,n=e._state.billboard,s=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// Mesh occlusion vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec3 offset;"),o.push("uniform vec3 scale;"),r&&o.push("uniform mat4 positionsDecodeMatrix;");i&&o.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;"));"spherical"!==n&&"cylindrical"!==n||(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = scale[0];"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===n&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = scale[1];"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}"));o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),o.push("vec4 worldPosition;"),r&&o.push("localPosition = positionsDecodeMatrix * localPosition;");o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),s&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"),o.push("billboard(modelViewMatrix);"),o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&o.push(" vWorldPosition = worldPosition;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = clipPos;"),o.push("}"),o}(t),this.fragment=function(e){var t=e.scene,i=t._sectionPlanesState,r=i.getNumAllocatedSectionPlanes()>0,n=[];n.push("#version 300 es"),n.push("// Mesh occlusion fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));if(r){n.push("uniform bool clippable;"),n.push("in vec4 vWorldPosition;");for(var s=0;s<i.getNumAllocatedSectionPlanes();s++)n.push("uniform bool sectionPlaneActive"+s+";"),n.push("uniform vec3 sectionPlanePos"+s+";"),n.push("uniform vec3 sectionPlaneDir"+s+";")}if(n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push("if (clippable) {"),n.push(" float dist = 0.0;");for(s=0;s<i.getNumAllocatedSectionPlanes();s++)n.push("if (sectionPlaneActive"+s+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}n.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return n.push("}"),n}(t)}));var qr=le.vec3(),$r=function(e,t){this._hash=e,this._shaderSource=new Yr(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},en={};$r.get=function(e){var t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";"),i=en[t];if(!i){if((i=new $r(t,e)).errors)return console.log(i.errors.join("\n")),null;en[t]=i,he.memory.programs++}return i._useCount++,i},$r.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete en[this._hash],he.memory.programs--)},$r.prototype.webglContextRestored=function(){this._program=null},$r.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene,r=i.canvas.gl,n=t._material._state,s=t._state,o=t._geometry._state,a=t.origin;if(!(n.alpha<1)){if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),n.id!==this._lastMaterialId){var l=n.backfaces;e.backfaces!==l&&(l?r.disable(r.CULL_FACE):r.enable(r.CULL_FACE),e.backfaces=l);var u=n.frontface;e.frontface!==u&&(u?r.frontFace(r.CCW):r.frontFace(r.CW),e.frontface=u),this._lastMaterialId=n.id}var c=i.camera;if(r.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(s.originHash,a):c.viewMatrix),s.clippable){var A=i._sectionPlanesState.getNumAllocatedSectionPlanes(),h=i._sectionPlanesState.sectionPlanes.length;if(A>0)for(var d=i._sectionPlanesState.sectionPlanes,p=t.renderFlags,f=0;f<A;f++){var v=this._uSectionPlanes[f];if(v)if(f<h){var g=p.sectionPlanesActivePerLayer[f];if(r.uniform1i(v.active,g?1:0),g){var m=d[f];if(a){var _=ei(m.dist,m.dir,a,qr);r.uniform3fv(v.pos,_)}else r.uniform3fv(v.pos,m.pos);r.uniform3fv(v.dir,m.dir)}}else r.uniform1i(v.active,0)}}r.uniformMatrix4fv(this._uProjMatrix,!1,c._project._state.matrix),r.uniformMatrix4fv(this._uModelMatrix,r.FALSE,t.worldMatrix),this._uClippable&&r.uniform1i(this._uClippable,t._state.clippable),r.uniform3fv(this._uOffset,t._state.offset),o.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&r.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,o.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(o.positionsBuf,o.compressGeometry?r.UNSIGNED_SHORT:r.FLOAT),e.bindArray++),o.indicesBuf&&(o.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=o.id),o.indicesBuf?(r.drawElements(o.primitive,o.indicesBuf.numItems,o.indicesBuf.itemType,0),e.drawElements++):o.positions&&r.drawArrays(r.TRIANGLES,0,o.positions.numItems)}},$r.prototype._allocate=function(e){var t=e.scene,i=t.canvas.gl;if(this._program=new Pr(i,this._shaderSource),this._program.errors)this.errors=this._program.errors;else{var r=this._program;this._uPositionsDecodeMatrix=r.getLocation("positionsDecodeMatrix"),this._uModelMatrix=r.getLocation("modelMatrix"),this._uViewMatrix=r.getLocation("viewMatrix"),this._uProjMatrix=r.getLocation("projMatrix"),this._uSectionPlanes=[];for(var n=0,s=t._sectionPlanesState.sectionPlanes.length;n<s;n++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+n),pos:r.getLocation("sectionPlanePos"+n),dir:r.getLocation("sectionPlaneDir"+n)});this._aPosition=r.getAttribute("position"),this._uClippable=r.getLocation("clippable"),this._uOffset=r.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=r.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null}},$r.prototype._bindProgram=function(e){var t=this._scene,i=t.camera.project,r=t.canvas.gl;if(this._program.bind(),e.useProgram++,r.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),t.logarithmicDepthBufferEnabled){var n=2/(Math.log(i.far+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,n)}this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null};var tn=I((function e(t){E(this,e),this.vertex=function(e){var t=e.scene._sectionPlanesState.sectionPlanes.length>0,i=!!e._geometry._state.compressGeometry,r=[];r.push("// Mesh shadow vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 shadowViewMatrix;"),r.push("uniform mat4 shadowProjMatrix;"),r.push("uniform vec3 offset;"),i&&r.push("uniform mat4 positionsDecodeMatrix;");t&&r.push("out vec4 vWorldPosition;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),r.push("vec4 worldPosition;"),i&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("worldPosition = modelMatrix * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&r.push("vWorldPosition = worldPosition;");return r.push(" gl_Position = shadowProjMatrix * viewPosition;"),r.push("}"),r}(t),this.fragment=function(e){var t=e.scene;t.canvas.gl;var i=t._sectionPlanesState,r=i.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("// Mesh shadow fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),r){n.push("uniform bool clippable;"),n.push("in vec4 vWorldPosition;");for(var s=0;s<i.getNumAllocatedSectionPlanes();s++)n.push("uniform bool sectionPlaneActive"+s+";"),n.push("uniform vec3 sectionPlanePos"+s+";"),n.push("uniform vec3 sectionPlaneDir"+s+";")}if(n.push("vec4 encodeFloat( const in float depth ) {"),n.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),n.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),n.push(" vec4 comp = fract(depth * bitShift);"),n.push(" comp -= comp.xxyz * bitMask;"),n.push(" return comp;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push("if (clippable) {"),n.push(" float dist = 0.0;");for(s=0;s<i.getNumAllocatedSectionPlanes();s++)n.push("if (sectionPlaneActive"+s+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return n.push("outColor = encodeFloat(gl_FragCoord.z);"),n.push("}"),n}(t)}));var rn=function(e,t){this._hash=e,this._shaderSource=new tn(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},nn={};rn.get=function(e){var t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";"),r=nn[i];if(!r){if((r=new rn(i,e)).errors)return console.log(r.errors.join("\n")),null;nn[i]=r,he.memory.programs++}return r._useCount++,r},rn.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete nn[this._hash],he.memory.programs--)},rn.prototype.webglContextRestored=function(){this._program=null},rn.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene.canvas.gl,r=t._material._state,n=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){var s=r.backfaces;e.backfaces!==s&&(s?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=s);var o=r.frontface;e.frontface!==o&&(o?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=o),e.lineWidth!==r.lineWidth&&(i.lineWidth(r.lineWidth),e.lineWidth=r.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,r.pointSize),this._lastMaterialId=r.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),n.combineGeometry){var a=t.vertexBufs;a.id!==this._lastVertexBufsId&&(a.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(a.positionsBuf,a.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=a.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),n.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,n.positionsDecodeMatrix),n.combineGeometry?n.indicesBufCombined&&(n.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(n.positionsBuf,n.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),n.indicesBuf&&(n.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=n.id),n.combineGeometry?n.indicesBufCombined&&(i.drawElements(n.primitive,n.indicesBufCombined.numItems,n.indicesBufCombined.itemType,0),e.drawElements++):n.indicesBuf?(i.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&(i.drawArrays(i.TRIANGLES,0,n.positions.numItems),e.drawArrays++)},rn.prototype._allocate=function(e){var t=e.scene,i=t.canvas.gl;if(this._program=new Pr(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)this.errors=this._program.errors;else{var r=this._program;this._uPositionsDecodeMatrix=r.getLocation("positionsDecodeMatrix"),this._uModelMatrix=r.getLocation("modelMatrix"),this._uShadowViewMatrix=r.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=r.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(var n=0,s=t._sectionPlanesState.sectionPlanes.length;n<s;n++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+n),pos:r.getLocation("sectionPlanePos"+n),dir:r.getLocation("sectionPlaneDir"+n)});this._aPosition=r.getAttribute("position"),this._uClippable=r.getLocation("clippable"),this._uOffset=r.getLocation("offset"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null}},rn.prototype._bindProgram=function(e){this._program||this._allocate(mesh);var t=this._scene,i=t.canvas.gl,r=t._sectionPlanesState;if(this._program.bind(),e.useProgram++,i.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),i.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,r.getNumAllocatedSectionPlanes()>0)for(var n,s,o,a=0,l=this._uSectionPlanes.length;a<l;a++)s=(n=this._uSectionPlanes[a]).active,o=r.sectionPlanes[a],s&&i.uniform1i(s,o.active),n.pos&&i.uniform3fv(n.pos,o.pos),n.dir&&i.uniform3fv(n.dir,o.dir)};var sn=function(){function e(){E(this,e),this.visibleLayers=[],this.sectionPlanesActivePerLayer=[],this.reset()}return I(e,[{key:"reset",value:function(){this.culled=!1,this.sectioned=!1,this.numLayers=0,this.numVisibleLayers=0,this.colorOpaque=!1,this.colorTransparent=!1,this.edgesOpaque=!1,this.edgesTransparent=!1,this.xrayedSilhouetteOpaque=!1,this.xrayedEdgesOpaque=!1,this.xrayedSilhouetteTransparent=!1,this.xrayedEdgesTransparent=!1,this.highlightedSilhouetteOpaque=!1,this.highlightedEdgesOpaque=!1,this.highlightedSilhouetteTransparent=!1,this.highlightedEdgesTransparent=!1,this.selectedSilhouetteOpaque=!1,this.selectedEdgesOpaque=!1,this.selectedSilhouetteTransparent=!1,this.selectedEdgesTransparent=!1}}]),e}(),on=le.OBB3(),an=le.vec4(),ln=le.vec4(),un=le.vec4(),cn=le.vec3([1,0,0]),An=le.vec3([0,1,0]),hn=le.vec3([0,0,1]),dn=le.vec3(3),pn=le.vec3(3),fn=le.identityMat4(),vn=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E(this,i),(r=t.call(this,e,n)).renderOrder=n.renderOrder||0,r.originalSystemId=n.originalSystemId||r.id,r.renderFlags=new sn,r._state=new nt({visible:!0,culled:!1,pickable:null,clippable:null,collidable:null,occluder:!1!==n.occluder,castsShadow:null,receivesShadow:null,xrayed:!1,highlighted:!1,selected:!1,edges:!1,stationary:!!n.stationary,background:!!n.background,billboard:r._checkBillboard(n.billboard),layer:null,colorize:null,pickID:r.scene._renderer.getPickID(w(r)),drawHash:"",pickHash:"",offset:le.vec3(),origin:null,originHash:null,isUI:n.isUI}),r._drawRenderer=null,r._shadowRenderer=null,r._emphasisFillRenderer=null,r._emphasisEdgesRenderer=null,r._pickMeshRenderer=null,r._pickTriangleRenderer=null,r._occlusionRenderer=null,r._geometry=n.geometry?r._checkComponent2(["ReadableGeometry","VBOGeometry"],n.geometry):r.scene.geometry,r._material=n.material?r._checkComponent2(["PhongMaterial","MetallicMaterial","SpecularMaterial","LambertMaterial"],n.material):r.scene.material,r._xrayMaterial=n.xrayMaterial?r._checkComponent("EmphasisMaterial",n.xrayMaterial):r.scene.xrayMaterial,r._highlightMaterial=n.highlightMaterial?r._checkComponent("EmphasisMaterial",n.highlightMaterial):r.scene.highlightMaterial,r._selectedMaterial=n.selectedMaterial?r._checkComponent("EmphasisMaterial",n.selectedMaterial):r.scene.selectedMaterial,r._edgeMaterial=n.edgeMaterial?r._checkComponent("EdgeMaterial",n.edgeMaterial):r.scene.edgeMaterial,r._parentNode=null,r._aabb=null,r._aabbDirty=!0,r._numTriangles=r._geometry?r._geometry.numTriangles:0,r.scene._aabbDirty=!0,r._scale=le.vec3(),r._quaternion=le.identityQuaternion(),r._rotation=le.vec3(),r._position=le.vec3(),r._worldMatrix=le.identityMat4(),r._worldNormalMatrix=le.identityMat4(),r._localMatrixDirty=!0,r._worldMatrixDirty=!0,r._worldNormalMatrixDirty=!0;var s=n.origin||n.rtcCenter;if(s&&(r._state.origin=le.vec3(s),r._state.originHash=s.join()),n.matrix?r.matrix=n.matrix:(r.scale=n.scale,r.position=n.position,n.quaternion||(r.rotation=n.rotation)),r._isObject=n.isObject,r._isObject&&r.scene._registerObject(w(r)),r._isModel=n.isModel,r._isModel&&r.scene._registerModel(w(r)),r.visible=n.visible,r.culled=n.culled,r.pickable=n.pickable,r.clippable=n.clippable,r.collidable=n.collidable,r.castsShadow=n.castsShadow,r.receivesShadow=n.receivesShadow,r.xrayed=n.xrayed,r.highlighted=n.highlighted,r.selected=n.selected,r.edges=n.edges,r.layer=n.layer,r.colorize=n.colorize,r.opacity=n.opacity,r.offset=n.offset,n.parentId){var o=r.scene.components[n.parentId];o?o.isNode?o.addChild(w(r)):r.error("Parent is not a Node: '"+n.parentId+"'"):r.error("Parent not found: '"+n.parentId+"'"),r._parentNode=o}else n.parent&&(n.parent.isNode||r.error("Parent is not a Node"),n.parent.addChild(w(r)),r._parentNode=n.parent);return r.compile(),r}return I(i,[{key:"type",get:function(){return"Mesh"}},{key:"isMesh",get:function(){return!0}},{key:"parent",get:function(){return this._parentNode}},{key:"geometry",get:function(){return this._geometry}},{key:"material",get:function(){return this._material}},{key:"position",get:function(){return this._position},set:function(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"rotation",get:function(){return this._rotation},set:function(e){this._rotation.set(e||[0,0,0]),le.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"quaternion",get:function(){return this._quaternion},set:function(e){this._quaternion.set(e||[0,0,0,1]),le.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"scale",get:function(){return this._scale},set:function(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"matrix",get:function(){return this._localMatrixDirty&&(this.__localMatrix||(this.__localMatrix=le.identityMat4()),le.composeMat4(this._position,this._quaternion,this._scale,this.__localMatrix),this._localMatrixDirty=!1),this.__localMatrix},set:function(e){this.__localMatrix||(this.__localMatrix=le.identityMat4()),this.__localMatrix.set(e||fn),le.decomposeMat4(this.__localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"worldMatrix",get:function(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}},{key:"worldNormalMatrix",get:function(){return this._worldNormalMatrixDirty&&this._buildWorldNormalMatrix(),this._worldNormalMatrix}},{key:"isEntity",get:function(){return!0}},{key:"isModel",get:function(){return this._isModel}},{key:"isObject",get:function(){return this._isObject}},{key:"isUI",get:function(){return this._state.isUI}},{key:"aabb",get:function(){return this._aabbDirty&&this._updateAABB(),this._aabb}},{key:"origin",get:function(){return this._state.origin},set:function(e){e?(this._state.origin||(this._state.origin=le.vec3()),this._state.origin.set(e),this._state.originHash=e.join(),this._setAABBDirty(),this.scene._aabbDirty=!0):this._state.origin&&(this._state.origin=null,this._state.originHash=null,this._setAABBDirty(),this.scene._aabbDirty=!0)}},{key:"rtcCenter",get:function(){return this.origin},set:function(e){this.origin=e}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"visible",get:function(){return this._state.visible},set:function(e){e=!1!==e,this._state.visible=e,this._isObject&&this.scene._objectVisibilityUpdated(this,e),this.glRedraw()}},{key:"xrayed",get:function(){return this._state.xrayed},set:function(e){e=!!e,this._state.xrayed!==e&&(this._state.xrayed=e,this._isObject&&this.scene._objectXRayedUpdated(this,e),this.glRedraw())}},{key:"highlighted",get:function(){return this._state.highlighted},set:function(e){(e=!!e)!==this._state.highlighted&&(this._state.highlighted=e,this._isObject&&this.scene._objectHighlightedUpdated(this,e),this.glRedraw())}},{key:"selected",get:function(){return this._state.selected},set:function(e){(e=!!e)!==this._state.selected&&(this._state.selected=e,this._isObject&&this.scene._objectSelectedUpdated(this,e),this.glRedraw())}},{key:"edges",get:function(){return this._state.edges},set:function(e){(e=!!e)!==this._state.edges&&(this._state.edges=e,this.glRedraw())}},{key:"culled",get:function(){return this._state.culled},set:function(e){this._state.culled=!!e,this.glRedraw()}},{key:"clippable",get:function(){return this._state.clippable},set:function(e){e=!1!==e,this._state.clippable!==e&&(this._state.clippable=e,this.glRedraw())}},{key:"collidable",get:function(){return this._state.collidable},set:function(e){(e=!1!==e)!==this._state.collidable&&(this._state.collidable=e,this._setAABBDirty(),this.scene._aabbDirty=!0)}},{key:"pickable",get:function(){return this._state.pickable},set:function(e){e=!1!==e,this._state.pickable!==e&&(this._state.pickable=e)}},{key:"castsShadow",get:function(){return this._state.castsShadow},set:function(e){(e=!1!==e)!==this._state.castsShadow&&(this._state.castsShadow=e,this.glRedraw())}},{key:"receivesShadow",get:function(){return this._state.receivesShadow},set:function(e){(e=!1!==e)!==this._state.receivesShadow&&(this._state.receivesShadow=e,this._state.hash=e?"/mod/rs;":"/mod;",this.fire("dirty",this))}},{key:"saoEnabled",get:function(){return!1}},{key:"colorize",get:function(){return this._state.colorize},set:function(e){var t=this._state.colorize;t||((t=this._state.colorize=new Float32Array(4))[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);var i=!!e;this.scene._objectColorizeUpdated(this,i),this.glRedraw()}},{key:"opacity",get:function(){return this._state.colorize[3]},set:function(e){var t=this._state.colorize;t||((t=this._state.colorize=new Float32Array(4))[0]=1,t[1]=1,t[2]=1);var i=null!=e;t[3]=i?e:1,this.scene._objectOpacityUpdated(this,i),this.glRedraw()}},{key:"transparent",get:function(){return 2===this._material.alphaMode||this._state.colorize[3]<1}},{key:"layer",get:function(){return this._state.layer},set:function(e){e=e||0,(e=Math.round(e))!==this._state.layer&&(this._state.layer=e,this._renderer.needStateSort())}},{key:"stationary",get:function(){return this._state.stationary}},{key:"billboard",get:function(){return this._state.billboard}},{key:"offset",get:function(){return this._state.offset},set:function(e){this._state.offset.set(e||[0,0,0]),this._setAABBDirty(),this.glRedraw()}},{key:"isDrawable",get:function(){return!0}},{key:"isStateSortable",get:function(){return!0}},{key:"xrayMaterial",get:function(){return this._xrayMaterial}},{key:"highlightMaterial",get:function(){return this._highlightMaterial}},{key:"selectedMaterial",get:function(){return this._selectedMaterial}},{key:"edgeMaterial",get:function(){return this._edgeMaterial}},{key:"_checkBillboard",value:function(e){return"spherical"!==(e=e||"none")&&"cylindrical"!==e&&"none"!==e&&(this.error("Unsupported value for 'billboard': "+e+" - accepted values are 'spherical', 'cylindrical' and 'none' - defaulting to 'none'."),e="none"),e}},{key:"compile",value:function(){var e=this._makeDrawHash();this._state.drawHash!==e&&(this._state.drawHash=e,this._putDrawRenderers(),this._drawRenderer=Ir.get(this),this._emphasisFillRenderer=Ur.get(this),this._emphasisEdgesRenderer=Qr.get(this));var t=this._makePickHash();if(this._state.pickHash!==t&&(this._state.pickHash=t,this._putPickRenderers(),this._pickMeshRenderer=zr.get(this)),this._state.occluder){var i=this._makeOcclusionHash();this._state.occlusionHash!==i&&(this._state.occlusionHash=i,this._putOcclusionRenderer(),this._occlusionRenderer=$r.get(this))}}},{key:"_setLocalMatrixDirty",value:function(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}},{key:"_setWorldMatrixDirty",value:function(){this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0}},{key:"_buildWorldMatrix",value:function(){var e=this.matrix;if(this._parentNode)le.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(var t=0,i=e.length;t<i;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}},{key:"_buildWorldNormalMatrix",value:function(){this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldNormalMatrix||(this._worldNormalMatrix=le.mat4()),le.transposeMat4(this._worldMatrix,this._worldNormalMatrix),le.inverseMat4(this._worldNormalMatrix),this._worldNormalMatrixDirty=!1}},{key:"_setAABBDirty",value:function(){if(this.collidable)for(var e=this;e;e=e._parentNode)e._aabbDirty=!0}},{key:"_updateAABB",value:function(){this.scene._aabbDirty=!0,this._aabb||(this._aabb=le.AABB3()),this._buildAABB(this.worldMatrix,this._aabb),this._aabbDirty=!1}},{key:"_webglContextRestored",value:function(){this._drawRenderer&&this._drawRenderer.webglContextRestored(),this._shadowRenderer&&this._shadowRenderer.webglContextRestored(),this._emphasisFillRenderer&&this._emphasisFillRenderer.webglContextRestored(),this._emphasisEdgesRenderer&&this._emphasisEdgesRenderer.webglContextRestored(),this._pickMeshRenderer&&this._pickMeshRenderer.webglContextRestored(),this._pickTriangleRenderer&&this._pickMeshRenderer.webglContextRestored(),this._occlusionRenderer&&this._occlusionRenderer.webglContextRestored()}},{key:"_makeDrawHash",value:function(){var e=this.scene,t=[e.canvas.canvas.id,(e.gammaInput?"gi;":";")+(e.gammaOutput?"go":""),e._lightsState.getHash(),e._sectionPlanesState.getHash()],i=this._state;return i.stationary&&t.push("/s"),"none"===i.billboard?t.push("/n"):"spherical"===i.billboard?t.push("/s"):"cylindrical"===i.billboard&&t.push("/c"),i.receivesShadow&&t.push("/rs"),t.push(";"),t.join("")}},{key:"_makePickHash",value:function(){var e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],i=this._state;return i.stationary&&t.push("/s"),"none"===i.billboard?t.push("/n"):"spherical"===i.billboard?t.push("/s"):"cylindrical"===i.billboard&&t.push("/c"),t.push(";"),t.join("")}},{key:"_makeOcclusionHash",value:function(){var e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],i=this._state;return i.stationary&&t.push("/s"),"none"===i.billboard?t.push("/n"):"spherical"===i.billboard?t.push("/s"):"cylindrical"===i.billboard&&t.push("/c"),t.push(";"),t.join("")}},{key:"_buildAABB",value:function(e,t){le.transformOBB3(e,this._geometry.obb,on),le.OBB3ToAABB3(on,t);var i=this._state.offset;if(t[0]+=i[0],t[1]+=i[1],t[2]+=i[2],t[3]+=i[0],t[4]+=i[1],t[5]+=i[2],this._state.origin){var r=this._state.origin;t[0]+=r[0],t[1]+=r[1],t[2]+=r[2],t[3]+=r[0],t[4]+=r[1],t[5]+=r[2]}}},{key:"rotate",value:function(e,t){return an[0]=e[0],an[1]=e[1],an[2]=e[2],an[3]=t*le.DEGTORAD,le.angleAxisToQuaternion(an,ln),le.mulQuaternions(this.quaternion,ln,un),this.quaternion=un,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}},{key:"rotateOnWorldAxis",value:function(e,t){return an[0]=e[0],an[1]=e[1],an[2]=e[2],an[3]=t*le.DEGTORAD,le.angleAxisToQuaternion(an,ln),le.mulQuaternions(ln,this.quaternion,ln),this}},{key:"rotateX",value:function(e){return this.rotate(cn,e)}},{key:"rotateY",value:function(e){return this.rotate(An,e)}},{key:"rotateZ",value:function(e){return this.rotate(hn,e)}},{key:"translate",value:function(e,t){return le.vec3ApplyQuaternion(this.quaternion,e,dn),le.mulVec3Scalar(dn,t,pn),le.addVec3(this.position,pn,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}},{key:"translateX",value:function(e){return this.translate(cn,e)}},{key:"translateY",value:function(e){return this.translate(An,e)}},{key:"translateZ",value:function(e){return this.translate(hn,e)}},{key:"_putDrawRenderers",value:function(){this._drawRenderer&&(this._drawRenderer.put(),this._drawRenderer=null),this._shadowRenderer&&(this._shadowRenderer.put(),this._shadowRenderer=null),this._emphasisFillRenderer&&(this._emphasisFillRenderer.put(),this._emphasisFillRenderer=null),this._emphasisEdgesRenderer&&(this._emphasisEdgesRenderer.put(),this._emphasisEdgesRenderer=null)}},{key:"_putPickRenderers",value:function(){this._pickMeshRenderer&&(this._pickMeshRenderer.put(),this._pickMeshRenderer=null),this._pickTriangleRenderer&&(this._pickTriangleRenderer.put(),this._pickTriangleRenderer=null)}},{key:"_putOcclusionRenderer",value:function(){this._occlusionRenderer&&(this._occlusionRenderer.put(),this._occlusionRenderer=null)}},{key:"stateSortCompare",value:function(e,t){return e._state.layer-t._state.layer||e._drawRenderer.id-t._drawRenderer.id||e._material._state.id-t._material._state.id||e._geometry._state.id-t._geometry._state.id}},{key:"rebuildRenderFlags",value:function(){this.renderFlags.reset(),this._getActiveSectionPlanes()?(this.renderFlags.numLayers=1,this.renderFlags.numVisibleLayers=1,this.renderFlags.visibleLayers[0]=0,this._updateRenderFlags()):this.renderFlags.culled=!0}},{key:"_updateRenderFlags",value:function(){var e=this.renderFlags,t=this._state;if(t.xrayed){var i=this._xrayMaterial._state;i.fill&&(i.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),i.edges&&(i.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}else{if(this._material._state.alpha<1||t.colorize[3]<1?e.colorTransparent=!0:e.colorOpaque=!0,t.edges)this._edgeMaterial._state.alpha<1?e.edgesTransparent=!0:e.edgesOpaque=!0;if(t.selected){var r=this._selectedMaterial._state;r.fill&&(r.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),r.edges&&(r.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}else if(t.highlighted){var n=this._highlightMaterial._state;n.fill&&(n.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),n.edges&&(n.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}},{key:"_getActiveSectionPlanes",value:function(){if(this._state.clippable){var e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(var i=0;i<t;i++){var r=e[i],n=this.renderFlags;if(r.active)if(this._state.origin){var s=le.planeAABB3Intersect(r.dir,r.dist,this.aabb);if(-1===s)return!1;var o=0===s;n.sectionPlanesActivePerLayer[i]=o}else n.sectionPlanesActivePerLayer[i]=!0;else n.sectionPlanesActivePerLayer[i]=!1}}return!0}},{key:"drawColorOpaque",value:function(e){(this._drawRenderer||(this._drawRenderer=Ir.get(this)))&&this._drawRenderer.drawMesh(e,this)}},{key:"drawColorTransparent",value:function(e){(this._drawRenderer||(this._drawRenderer=Ir.get(this)))&&this._drawRenderer.drawMesh(e,this)}},{key:"drawSilhouetteXRayed",value:function(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=Ur.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,0)}},{key:"drawSilhouetteHighlighted",value:function(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=Ur.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,1)}},{key:"drawSilhouetteSelected",value:function(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=Ur.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,2)}},{key:"drawEdgesColorOpaque",value:function(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Qr.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}},{key:"drawEdgesColorTransparent",value:function(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Qr.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}},{key:"drawEdgesXRayed",value:function(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Qr.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,0)}},{key:"drawEdgesHighlighted",value:function(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Qr.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,1)}},{key:"drawEdgesSelected",value:function(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Qr.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,2)}},{key:"drawOcclusion",value:function(e){(this._state.occluder&&this._occlusionRenderer||(this._occlusionRenderer=$r.get(this)))&&this._occlusionRenderer.drawMesh(e,this)}},{key:"drawShadow",value:function(e){(this._shadowRenderer||(this._shadowRenderer=rn.get(this)))&&this._shadowRenderer.drawMesh(e,this)}},{key:"drawPickMesh",value:function(e){(this._pickMeshRenderer||(this._pickMeshRenderer=zr.get(this)))&&this._pickMeshRenderer.drawMesh(e,this)}},{key:"canPickTriangle",value:function(){return this._geometry.isReadableGeometry}},{key:"drawPickTriangles",value:function(e){(this._pickTriangleRenderer||(this._pickTriangleRenderer=Zr.get(this)))&&this._pickTriangleRenderer.drawMesh(e,this)}},{key:"pickTriangleSurface",value:function(e,t,i,r){gn(this,e,t,i,r)}},{key:"drawPickVertices",value:function(e){}},{key:"delegatePickedEntity",value:function(){return this}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._putDrawRenderers(),this._putPickRenderers(),this._putOcclusionRenderer(),this.scene._renderer.putPickID(this._state.pickID),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((function(e){return 0!==e}))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}]),i}(),gn=function(){var e=le.vec3(),t=le.vec3(),i=le.vec3(),r=le.vec3(),n=le.vec3(),s=le.vec3(),o=le.vec4(),a=le.vec3(),l=le.vec3(),u=le.vec3(),c=le.vec3(),A=le.vec3(),h=le.vec3(),d=le.vec3(),p=le.vec3(),f=le.vec3(),v=le.vec4(),g=le.vec4(),m=le.vec4(),_=le.vec3(),y=le.vec3(),b=le.vec3(),w=le.vec3(),B=le.vec3(),x=le.vec3(),P=le.vec3(),C=le.vec3(),M=le.vec3(),k=le.vec3(),E=le.vec3();return function(F,I,T,D,S){var R=S.primIndex;if(null!=R&&R>-1){var U=F.geometry._state,L=F.scene,O=L.camera,N=L.canvas;if("triangles"===U.primitiveName){S.primitive="triangle";var V,Q,H,j=R,G=U.indices,z=U.positions;if(G){var W=G[j+0],X=G[j+1],K=G[j+2];s[0]=W,s[1]=X,s[2]=K,S.indices=s,V=3*W,Q=3*X,H=3*K}else H=(Q=(V=3*j)+3)+3;if(i[0]=z[V+0],i[1]=z[V+1],i[2]=z[V+2],r[0]=z[Q+0],r[1]=z[Q+1],r[2]=z[Q+2],n[0]=z[H+0],n[1]=z[H+1],n[2]=z[H+2],U.compressGeometry){var Z=U.positionsDecodeMatrix;Z&&(ft.decompressPosition(i,Z,i),ft.decompressPosition(r,Z,r),ft.decompressPosition(n,Z,n))}S.canvasPos?le.canvasPosToLocalRay(N.canvas,F.origin?Jt(I,F.origin):I,T,D,F.worldMatrix,S.canvasPos,e,t):S.origin&&S.direction&&le.worldRayToLocalRay(F.worldMatrix,S.origin,S.direction,e,t),le.normalizeVec3(t),le.rayPlaneIntersect(e,t,i,r,n,o),S.localPos=o,S.position=o,v[0]=o[0],v[1]=o[1],v[2]=o[2],v[3]=1,le.transformVec4(F.worldMatrix,v,g),a[0]=g[0],a[1]=g[1],a[2]=g[2],S.canvasPos&&F.origin&&(a[0]+=F.origin[0],a[1]+=F.origin[1],a[2]+=F.origin[2]),S.worldPos=a,le.transformVec4(O.matrix,g,m),l[0]=m[0],l[1]=m[1],l[2]=m[2],S.viewPos=l,le.cartesianToBarycentric(o,i,r,n,u),S.bary=u;var J=U.normals;if(J){if(U.compressGeometry){var Y=3*W,q=3*X,$=3*K;ft.decompressNormal(J.subarray(Y,Y+2),c),ft.decompressNormal(J.subarray(q,q+2),A),ft.decompressNormal(J.subarray($,$+2),h)}else c[0]=J[V],c[1]=J[V+1],c[2]=J[V+2],A[0]=J[Q],A[1]=J[Q+1],A[2]=J[Q+2],h[0]=J[H],h[1]=J[H+1],h[2]=J[H+2];var ee=le.addVec3(le.addVec3(le.mulVec3Scalar(c,u[0],_),le.mulVec3Scalar(A,u[1],y),b),le.mulVec3Scalar(h,u[2],w),B);S.worldNormal=le.normalizeVec3(le.transformVec3(F.worldNormalMatrix,ee,x))}var te=U.uv;if(te){if(d[0]=te[2*W],d[1]=te[2*W+1],p[0]=te[2*X],p[1]=te[2*X+1],f[0]=te[2*K],f[1]=te[2*K+1],U.compressGeometry){var ie=U.uvDecodeMatrix;ie&&(ft.decompressUV(d,ie,d),ft.decompressUV(p,ie,p),ft.decompressUV(f,ie,f))}S.uv=le.addVec3(le.addVec3(le.mulVec2Scalar(d,u[0],P),le.mulVec2Scalar(p,u[1],C),M),le.mulVec2Scalar(f,u[2],k),E)}}}}}(),mn=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),r=t.call(this,e,n),he.memory.materials++,r}return I(i,[{key:"type",get:function(){return"Material"}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),he.memory.materials--}}]),i}(),_n={opaque:0,mask:1,blend:2},yn=["opaque","mask","blend"],bn=function(e){m(i,mn);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state=new nt({type:"PhongMaterial",ambient:le.vec3([1,1,1]),diffuse:le.vec3([1,1,1]),specular:le.vec3([1,1,1]),emissive:le.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),r.ambient=n.ambient,r.diffuse=n.diffuse,r.specular=n.specular,r.emissive=n.emissive,r.alpha=n.alpha,r.shininess=n.shininess,r.reflectivity=n.reflectivity,r.lineWidth=n.lineWidth,r.pointSize=n.pointSize,n.ambientMap&&(r._ambientMap=r._checkComponent("Texture",n.ambientMap)),n.diffuseMap&&(r._diffuseMap=r._checkComponent("Texture",n.diffuseMap)),n.specularMap&&(r._specularMap=r._checkComponent("Texture",n.specularMap)),n.emissiveMap&&(r._emissiveMap=r._checkComponent("Texture",n.emissiveMap)),n.alphaMap&&(r._alphaMap=r._checkComponent("Texture",n.alphaMap)),n.reflectivityMap&&(r._reflectivityMap=r._checkComponent("Texture",n.reflectivityMap)),n.normalMap&&(r._normalMap=r._checkComponent("Texture",n.normalMap)),n.occlusionMap&&(r._occlusionMap=r._checkComponent("Texture",n.occlusionMap)),n.diffuseFresnel&&(r._diffuseFresnel=r._checkComponent("Fresnel",n.diffuseFresnel)),n.specularFresnel&&(r._specularFresnel=r._checkComponent("Fresnel",n.specularFresnel)),n.emissiveFresnel&&(r._emissiveFresnel=r._checkComponent("Fresnel",n.emissiveFresnel)),n.alphaFresnel&&(r._alphaFresnel=r._checkComponent("Fresnel",n.alphaFresnel)),n.reflectivityFresnel&&(r._reflectivityFresnel=r._checkComponent("Fresnel",n.reflectivityFresnel)),r.alphaMode=n.alphaMode,r.alphaCutoff=n.alphaCutoff,r.backfaces=n.backfaces,r.frontface=n.frontface,r._makeHash(),r}return I(i,[{key:"type",get:function(){return"PhongMaterial"}},{key:"_makeHash",value:function(){var e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}},{key:"ambient",get:function(){return this._state.ambient},set:function(e){var t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"diffuse",get:function(){return this._state.diffuse},set:function(e){var t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"specular",get:function(){return this._state.specular},set:function(e){var t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}},{key:"shininess",get:function(){return this._state.shininess},set:function(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"reflectivity",get:function(){return this._state.reflectivity},set:function(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}},{key:"normalMap",get:function(){return this._normalMap}},{key:"ambientMap",get:function(){return this._ambientMap}},{key:"diffuseMap",get:function(){return this._diffuseMap}},{key:"specularMap",get:function(){return this._specularMap}},{key:"emissiveMap",get:function(){return this._emissiveMap}},{key:"alphaMap",get:function(){return this._alphaMap}},{key:"reflectivityMap",get:function(){return this._reflectivityMap}},{key:"occlusionMap",get:function(){return this._occlusionMap}},{key:"diffuseFresnel",get:function(){return this._diffuseFresnel}},{key:"specularFresnel",get:function(){return this._specularFresnel}},{key:"emissiveFresnel",get:function(){return this._emissiveFresnel}},{key:"alphaFresnel",get:function(){return this._alphaFresnel}},{key:"reflectivityFresnel",get:function(){return this._reflectivityFresnel}},{key:"alphaMode",get:function(){return yn[this._state.alphaMode]},set:function(e){var t=_n[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" - defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}},{key:"alphaCutoff",get:function(){return this._state.alphaCutoff},set:function(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}();function wn(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];var i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}function Bn(e,t){var i,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,n=t;if(1009===n)return e.UNSIGNED_BYTE;if(1017===n)return e.UNSIGNED_SHORT_4_4_4_4;if(1018===n)return e.UNSIGNED_SHORT_5_5_5_1;if(1010===n)return e.BYTE;if(1011===n)return e.SHORT;if(1012===n)return e.UNSIGNED_SHORT;if(1013===n)return e.INT;if(1014===n)return e.UNSIGNED_INT;if(1015===n)return e.FLOAT;if(1016===n)return e.HALF_FLOAT;if(1021===n)return e.ALPHA;if(1023===n)return e.RGBA;if(1024===n)return e.LUMINANCE;if(1025===n)return e.LUMINANCE_ALPHA;if(1026===n)return e.DEPTH_COMPONENT;if(1027===n)return e.DEPTH_STENCIL;if(1028===n)return e.RED;if(1022===n)return e.RGBA;if(1029===n)return e.RED_INTEGER;if(1030===n)return e.RG;if(1031===n)return e.RG_INTEGER;if(1033===n)return e.RGBA_INTEGER;if(33776===n||33777===n||33778===n||33779===n)if(3001===r){var s=wn(e,"WEBGL_compressed_texture_s3tc_srgb");if(null===s)return null;if(33776===n)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(33777===n)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(33778===n)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(33779===n)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(null===(i=wn(e,"WEBGL_compressed_texture_s3tc")))return null;if(33776===n)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===n)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===n)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===n)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===n||35841===n||35842===n||35843===n){var o=wn(e,"WEBGL_compressed_texture_pvrtc");if(null===o)return null;if(35840===n)return o.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===n)return o.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===n)return o.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===n)return o.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===n){var a=wn(e,"WEBGL_compressed_texture_etc1");return null!==a?a.COMPRESSED_RGB_ETC1_WEBGL:null}if(37492===n||37496===n){var l=wn(e,"WEBGL_compressed_texture_etc");if(null===l)return null;if(37492===n)return 3001===r?l.COMPRESSED_SRGB8_ETC2:l.COMPRESSED_RGB8_ETC2;if(37496===n)return 3001===r?l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:l.COMPRESSED_RGBA8_ETC2_EAC}if(37808===n||37809===n||37810===n||37811===n||37812===n||37813===n||37814===n||37815===n||37816===n||37817===n||37818===n||37819===n||37820===n||37821===n){var u=wn(e,"WEBGL_compressed_texture_astc");if(null===u)return null;if(37808===n)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:u.COMPRESSED_RGBA_ASTC_4x4_KHR;if(37809===n)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:u.COMPRESSED_RGBA_ASTC_5x4_KHR;if(37810===n)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:u.COMPRESSED_RGBA_ASTC_5x5_KHR;if(37811===n)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:u.COMPRESSED_RGBA_ASTC_6x5_KHR;if(37812===n)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:u.COMPRESSED_RGBA_ASTC_6x6_KHR;if(37813===n)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:u.COMPRESSED_RGBA_ASTC_8x5_KHR;if(37814===n)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:u.COMPRESSED_RGBA_ASTC_8x6_KHR;if(37815===n)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:u.COMPRESSED_RGBA_ASTC_8x8_KHR;if(37816===n)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:u.COMPRESSED_RGBA_ASTC_10x5_KHR;if(37817===n)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:u.COMPRESSED_RGBA_ASTC_10x6_KHR;if(37818===n)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:u.COMPRESSED_RGBA_ASTC_10x8_KHR;if(37819===n)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:u.COMPRESSED_RGBA_ASTC_10x10_KHR;if(37820===n)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:u.COMPRESSED_RGBA_ASTC_12x10_KHR;if(37821===n)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:u.COMPRESSED_RGBA_ASTC_12x12_KHR}if(36492===n){var c=wn(e,"EXT_texture_compression_bptc");if(null===c)return null;if(36492===n)return 3001===r?c.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:c.COMPRESSED_RGBA_BPTC_UNORM_EXT}return 1020===n?e.UNSIGNED_INT_24_8:1e3===n?e.REPEAT:1001===n?e.CLAMP_TO_EDGE:1004===n||1005===n?e.NEAREST_MIPMAP_LINEAR:1007===n?e.LINEAR_MIPMAP_NEAREST:1008===n?e.LINEAR_MIPMAP_LINEAR:1003===n?e.NEAREST:1006===n?e.LINEAR:null}var xn=new Uint8Array([0,0,0,1]),Pn=function(){function e(t){var i=t.gl,r=t.target,n=t.format,s=t.type,o=t.wrapS,a=t.wrapT,l=t.wrapR,u=t.encoding,c=t.preloadColor,A=t.premultiplyAlpha,h=t.flipY;E(this,e),this.gl=i,this.target=r||i.TEXTURE_2D,this.format=n||1023,this.type=s||1009,this.internalFormat=null,this.premultiplyAlpha=!!A,this.flipY=!!h,this.unpackAlignment=4,this.wrapS=o||1e3,this.wrapT=a||1e3,this.wrapR=l||1e3,this.encoding=u||3001,this.texture=i.createTexture(),c&&this.setPreloadColor(c),this.allocated=!0}return I(e,[{key:"setPreloadColor",value:function(e){e?(xn[0]=Math.floor(255*e[0]),xn[1]=Math.floor(255*e[1]),xn[2]=Math.floor(255*e[2]),xn[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):(xn[0]=0,xn[1]=0,xn[2]=0,xn[3]=255);var t=this.gl;if(t.bindTexture(this.target,this.texture),this.target===t.TEXTURE_CUBE_MAP)for(var i=[t.TEXTURE_CUBE_MAP_POSITIVE_X,t.TEXTURE_CUBE_MAP_NEGATIVE_X,t.TEXTURE_CUBE_MAP_POSITIVE_Y,t.TEXTURE_CUBE_MAP_NEGATIVE_Y,t.TEXTURE_CUBE_MAP_POSITIVE_Z,t.TEXTURE_CUBE_MAP_NEGATIVE_Z],r=0,n=i.length;r<n;r++)t.texImage2D(i[r],0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,xn);else t.texImage2D(this.target,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,xn);t.bindTexture(this.target,null)}},{key:"setTarget",value:function(e){this.target=e||this.gl.TEXTURE_2D}},{key:"setImage",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=this.gl;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR);var r=!1;i.bindTexture(this.target,this.texture);var n=i.getParameter(i.UNPACK_FLIP_Y_WEBGL);i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY);var s=i.getParameter(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL);i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var o=i.getParameter(i.UNPACK_ALIGNMENT);i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment);var a=i.getParameter(i.UNPACK_COLORSPACE_CONVERSION_WEBGL);i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);var l=Bn(i,this.minFilter);i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,l),l!==i.NEAREST_MIPMAP_NEAREST&&l!==i.LINEAR_MIPMAP_NEAREST&&l!==i.NEAREST_MIPMAP_LINEAR&&l!==i.LINEAR_MIPMAP_LINEAR||(r=!0);var u=Bn(i,this.magFilter);u&&i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,u);var c=Bn(i,this.wrapS);c&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,c);var A=Bn(i,this.wrapT);A&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,A);var h=Bn(i,this.format,this.encoding),d=Bn(i,this.type),p=Cn(i,this.internalFormat,h,d,this.encoding,!1);if(this.target===i.TEXTURE_CUBE_MAP){if(ge.isArray(e))for(var f=e,v=[i.TEXTURE_CUBE_MAP_POSITIVE_X,i.TEXTURE_CUBE_MAP_NEGATIVE_X,i.TEXTURE_CUBE_MAP_POSITIVE_Y,i.TEXTURE_CUBE_MAP_NEGATIVE_Y,i.TEXTURE_CUBE_MAP_POSITIVE_Z,i.TEXTURE_CUBE_MAP_NEGATIVE_Z],g=0,m=v.length;g<m;g++)i.texImage2D(v[g],0,p,h,d,f[g])}else i.texImage2D(i.TEXTURE_2D,0,p,h,d,e);r&&i.generateMipmap(this.target),i.bindTexture(this.target,null),i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,n),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,s),i.pixelStorei(i.UNPACK_ALIGNMENT,o),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,a)}},{key:"setCompressedData",value:function(e){var t=e.mipmaps,i=e.props,r=void 0===i?{}:i,n=this.gl,s=t.length;void 0!==r.format&&(this.format=r.format),void 0!==r.internalFormat&&(this.internalFormat=r.internalFormat),void 0!==r.encoding&&(this.encoding=r.encoding),void 0!==r.type&&(this.type=r.type),void 0!==r.flipY&&(this.flipY=r.flipY),void 0!==r.premultiplyAlpha&&(this.premultiplyAlpha=r.premultiplyAlpha),void 0!==r.unpackAlignment&&(this.unpackAlignment=r.unpackAlignment),void 0!==r.minFilter&&(this.minFilter=r.minFilter),void 0!==r.magFilter&&(this.magFilter=r.magFilter),void 0!==r.wrapS&&(this.wrapS=r.wrapS),void 0!==r.wrapT&&(this.wrapT=r.wrapT),void 0!==r.wrapR&&(this.wrapR=r.wrapR),n.activeTexture(n.TEXTURE0+0),n.bindTexture(this.target,this.texture);var o=t.length>1;n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,this.flipY),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),n.pixelStorei(n.UNPACK_ALIGNMENT,this.unpackAlignment),n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,n.NONE);var a=Bn(n,this.wrapS);a&&n.texParameteri(this.target,n.TEXTURE_WRAP_S,a);var l=Bn(n,this.wrapT);if(l&&n.texParameteri(this.target,n.TEXTURE_WRAP_T,l),this.type===n.TEXTURE_3D||this.type===n.TEXTURE_2D_ARRAY){var u=Bn(n,this.wrapR);u&&n.texParameteri(this.target,n.TEXTURE_WRAP_R,u),n.texParameteri(this.type,n.TEXTURE_WRAP_R,u)}o?(n.texParameteri(this.target,n.TEXTURE_MIN_FILTER,Mn(n,this.minFilter)),n.texParameteri(this.target,n.TEXTURE_MAG_FILTER,Mn(n,this.magFilter))):(n.texParameteri(this.target,n.TEXTURE_MIN_FILTER,Bn(n,this.minFilter)),n.texParameteri(this.target,n.TEXTURE_MAG_FILTER,Bn(n,this.magFilter)));var c=Bn(n,this.format,this.encoding),A=Bn(n,this.type),h=Cn(n,this.internalFormat,c,A,this.encoding,!1);n.texStorage2D(n.TEXTURE_2D,s,h,t[0].width,t[0].height);for(var d=0,p=t.length;d<p;d++){var f=t[d];1023!==this.format?null!==c?n.compressedTexSubImage2D(n.TEXTURE_2D,d,0,0,f.width,f.height,c,f.data):console.warn("Attempt to load unsupported compressed texture format in .setCompressedData()"):n.texSubImage2D(n.TEXTURE_2D,d,0,0,f.width,f.height,c,A,f.data)}n.bindTexture(this.target,null)}},{key:"setProps",value:function(e){var t=this.gl;t.bindTexture(this.target,this.texture),this._uploadProps(e),t.bindTexture(this.target,null)}},{key:"_uploadProps",value:function(e){var t=this.gl;if(void 0!==e.format&&(this.format=e.format),void 0!==e.internalFormat&&(this.internalFormat=e.internalFormat),void 0!==e.encoding&&(this.encoding=e.encoding),void 0!==e.type&&(this.type=e.type),void 0!==e.minFilter){var i=Bn(t,e.minFilter);i&&(this.minFilter=e.minFilter,t.texParameteri(this.target,t.TEXTURE_MIN_FILTER,i),i!==t.NEAREST_MIPMAP_NEAREST&&i!==t.LINEAR_MIPMAP_NEAREST&&i!==t.NEAREST_MIPMAP_LINEAR&&i!==t.LINEAR_MIPMAP_LINEAR||t.generateMipmap(this.target))}if(void 0!==e.magFilter){var r=Bn(t,e.magFilter);r&&(this.magFilter=e.magFilter,t.texParameteri(this.target,t.TEXTURE_MAG_FILTER,r))}if(void 0!==e.wrapS){var n=Bn(t,e.wrapS);n&&(this.wrapS=e.wrapS,t.texParameteri(this.target,t.TEXTURE_WRAP_S,n))}if(void 0!==e.wrapT){var s=Bn(t,e.wrapT);s&&(this.wrapT=e.wrapT,t.texParameteri(this.target,t.TEXTURE_WRAP_T,s))}}},{key:"bind",value:function(e){if(this.allocated){if(this.texture){var t=this.gl;return t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,this.texture),!0}return!1}}},{key:"unbind",value:function(e){if(this.allocated&&this.texture){var t=this.gl;t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,null)}}},{key:"destroy",value:function(){this.allocated&&this.texture&&(this.gl.deleteTexture(this.texture),this.texture=null)}}]),e}();function Cn(e,t,i,r,n){var s=arguments.length>5&&void 0!==arguments[5]&&arguments[5];if(null!==t){if(void 0!==e[t])return e[t];console.warn("Attempt to use non-existing WebGL internal format '"+t+"'")}var o=i;return i===e.RED&&(r===e.FLOAT&&(o=e.R32F),r===e.HALF_FLOAT&&(o=e.R16F),r===e.UNSIGNED_BYTE&&(o=e.R8)),i===e.RG&&(r===e.FLOAT&&(o=e.RG32F),r===e.HALF_FLOAT&&(o=e.RG16F),r===e.UNSIGNED_BYTE&&(o=e.RG8)),i===e.RGBA&&(r===e.FLOAT&&(o=e.RGBA32F),r===e.HALF_FLOAT&&(o=e.RGBA16F),r===e.UNSIGNED_BYTE&&(o=3001===n&&!1===s?e.SRGB8_ALPHA8:e.RGBA8),r===e.UNSIGNED_SHORT_4_4_4_4&&(o=e.RGBA4),r===e.UNSIGNED_SHORT_5_5_5_1&&(o=e.RGB5_A1)),o!==e.R16F&&o!==e.R32F&&o!==e.RG16F&&o!==e.RG32F&&o!==e.RGBA16F&&o!==e.RGBA32F||wn(e,"EXT_color_buffer_float"),o}function Mn(e,t){return 1003===t||1004===t||1005===t?e.NEAREST:e.LINEAR}function kn(e){if(!En(e.width)||!En(e.height)){var t=document.createElement("canvas");t.width=Fn(e.width),t.height=Fn(e.height),t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function En(e){return 0==(e&e-1)}function Fn(e){--e;for(var t=1;t<32;t<<=1)e|=e>>t;return e+1}var In=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state=new nt({texture:new Pn({gl:r.scene.canvas.gl}),matrix:le.identityMat4(),hasMatrix:n.translate&&(0!==n.translate[0]||0!==n.translate[1])||!!n.rotate||n.scale&&(0!==n.scale[0]||0!==n.scale[1]),minFilter:r._checkMinFilter(n.minFilter),magFilter:r._checkMagFilter(n.magFilter),wrapS:r._checkWrapS(n.wrapS),wrapT:r._checkWrapT(n.wrapT),flipY:r._checkFlipY(n.flipY),encoding:r._checkEncoding(n.encoding)}),r._src=null,r._image=null,r._translate=le.vec2([0,0]),r._scale=le.vec2([1,1]),r._rotate=le.vec2([0,0]),r._matrixDirty=!1,r.translate=n.translate,r.scale=n.scale,r.rotate=n.rotate,n.src?r.src=n.src:n.image&&(r.image=n.image),he.memory.textures++,r}return I(i,[{key:"type",get:function(){return"Texture"}},{key:"_checkMinFilter",value:function(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}},{key:"_checkMagFilter",value:function(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}},{key:"_checkWrapS",value:function(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}},{key:"_checkWrapT",value:function(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}},{key:"_checkFlipY",value:function(e){return!!e}},{key:"_checkEncoding",value:function(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}},{key:"_webglContextRestored",value:function(){this._state.texture=new Pn({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}},{key:"_update",value:function(){var e,t,i=this._state;this._matrixDirty&&(0===this._translate[0]&&0===this._translate[1]||(e=le.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(t=le.scalingMat4v([this._scale[0],this._scale[1],1]),e=e?le.mulMat4(e,t):t),0!==this._rotate&&(t=le.rotationMat4v(.0174532925*this._rotate,[0,0,1]),e=e?le.mulMat4(e,t):t),e&&(i.matrix=e),this._matrixDirty=!1);this.glRedraw()}},{key:"image",get:function(){return this._image},set:function(e){this._image=kn(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}},{key:"src",get:function(){return this._src},set:function(e){this.scene.loading++,this.scene.canvas.spinner.processes++;var t=this,i=new Image;i.onload=function(){i=kn(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}},{key:"translate",get:function(){return this._translate},set:function(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}},{key:"scale",get:function(){return this._scale},set:function(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}},{key:"rotate",get:function(){return this._rotate},set:function(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}},{key:"minFilter",get:function(){return this._state.minFilter}},{key:"magFilter",get:function(){return this._state.magFilter}},{key:"wrapS",get:function(){return this._state.wrapS}},{key:"wrapT",get:function(){return this._state.wrapT}},{key:"flipY",get:function(){return this._state.flipY}},{key:"encoding",get:function(){return this._state.encoding}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),he.memory.textures--}}]),i}(),Tn=le.vec3(),Dn=le.vec3();le.vec3();var Sn=le.vec3([0,-1,0]),Rn=le.vec4([0,0,0,1]),Un=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._src=null,r._image=null,r._pos=le.vec3(),r._origin=le.vec3(),r._rtcPos=le.vec3(),r._dir=le.vec3(),r._size=1,r._imageSize=le.vec2(),r._texture=new In(w(r)),r._plane=new vn(w(r),{geometry:new mt(w(r),Ft({center:[0,0,0],xSize:1,zSize:1,xSegments:10,zSegments:10})),material:new bn(w(r),{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:r._texture,emissiveMap:r._texture,backfaces:!0}),clippable:n.clippable}),r._grid=new vn(w(r),{geometry:new mt(w(r),Et({size:1,divisions:10})),material:new bn(w(r),{diffuse:[0,0,0],ambient:[0,0,0],emissive:[.2,.8,.2]}),position:[0,.001,0],clippable:n.clippable}),r._node=new Xt(w(r),{rotation:[0,0,0],position:[0,0,0],scale:[1,1,1],clippable:!1,children:[r._plane,r._grid]}),r._gridVisible=!1,r.visible=!0,r.gridVisible=n.gridVisible,r.position=n.position,r.rotation=n.rotation,r.dir=n.dir,r.size=n.size,r.collidable=n.collidable,r.clippable=n.clippable,r.pickable=n.pickable,r.opacity=n.opacity,n.image?r.image=n.image:r.src=n.src,r}return I(i,[{key:"visible",get:function(){return this._plane.visible},set:function(e){this._plane.visible=e,this._grid.visible=this._gridVisible&&e}},{key:"gridVisible",get:function(){return this._gridVisible},set:function(e){e=!1!==e,this._gridVisible=e,this._grid.visible=this._gridVisible&&this.visible}},{key:"image",get:function(){return this._image},set:function(e){this._image=e,this._image&&(this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}},{key:"src",get:function(){return this._src},set:function(e){var t=this;if(this._src=e,this._src){this._image=null;var i=new Image;i.onload=function(){t._texture.image=i,t._imageSize[0]=i.width,t._imageSize[1]=i.height,t._updatePlaneSizeFromImage()},i.src=this._src}}},{key:"position",get:function(){return this._pos},set:function(e){this._pos.set(e||[0,0,0]),Yt(this._pos,this._origin,this._rtcPos),this._node.origin=this._origin,this._node.position=this._rtcPos}},{key:"rotation",get:function(){return this._node.rotation},set:function(e){this._node.rotation=e}},{key:"size",get:function(){return this._size},set:function(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}},{key:"dir",get:function(){return this._dir},set:function(e){if(this._dir.set(e||[0,0,-1]),e){var t=this.scene.center,i=[-this._dir[0],-this._dir[1],-this._dir[2]];le.subVec3(t,this.position,Tn);var r=-le.dotVec3(i,Tn);le.normalizeVec3(i),le.mulVec3Scalar(i,r,Dn),le.vec3PairToQuaternion(Sn,e,Rn),this._node.quaternion=Rn}}},{key:"collidable",get:function(){return this._node.collidable},set:function(e){this._node.collidable=!1!==e}},{key:"clippable",get:function(){return this._node.clippable},set:function(e){this._node.clippable=!1!==e}},{key:"pickable",get:function(){return this._node.pickable},set:function(e){this._node.pickable=!1!==e}},{key:"opacity",get:function(){return this._node.opacity},set:function(e){this._node.opacity=e}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this)}},{key:"_updatePlaneSizeFromImage",value:function(){var e=this._size,t=this._imageSize[0],i=this._imageSize[1];if(t>i){var r=i/t;this._node.scale=[e,1,e*r]}else{var n=t/i;this._node.scale=[e*n,1,e]}}}]),i}(),Ln=function(e){m(i,mn);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state=new nt({type:"LambertMaterial",ambient:le.vec3([1,1,1]),color:le.vec3([1,1,1]),emissive:le.vec3([0,0,0]),alpha:null,alphaMode:0,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:"/lam;"}),r.ambient=n.ambient,r.color=n.color,r.emissive=n.emissive,r.alpha=n.alpha,r.lineWidth=n.lineWidth,r.pointSize=n.pointSize,r.backfaces=n.backfaces,r.frontface=n.frontface,r}return I(i,[{key:"type",get:function(){return"LambertMaterial"}},{key:"ambient",get:function(){return this._state.ambient},set:function(e){var t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"color",get:function(){return this._state.color},set:function(e){var t=this._state.color;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.color=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this._state.alphaMode=e<1?2:0,this.glRedraw())}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),On={opaque:0,mask:1,blend:2},Nn=["opaque","mask","blend"],Vn=function(e){m(i,mn);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state=new nt({type:"MetallicMaterial",baseColor:le.vec4([1,1,1]),emissive:le.vec4([0,0,0]),metallic:null,roughness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),r.baseColor=n.baseColor,r.metallic=n.metallic,r.roughness=n.roughness,r.specularF0=n.specularF0,r.emissive=n.emissive,r.alpha=n.alpha,n.baseColorMap&&(r._baseColorMap=r._checkComponent("Texture",n.baseColorMap)),n.metallicMap&&(r._metallicMap=r._checkComponent("Texture",n.metallicMap)),n.roughnessMap&&(r._roughnessMap=r._checkComponent("Texture",n.roughnessMap)),n.metallicRoughnessMap&&(r._metallicRoughnessMap=r._checkComponent("Texture",n.metallicRoughnessMap)),n.emissiveMap&&(r._emissiveMap=r._checkComponent("Texture",n.emissiveMap)),n.occlusionMap&&(r._occlusionMap=r._checkComponent("Texture",n.occlusionMap)),n.alphaMap&&(r._alphaMap=r._checkComponent("Texture",n.alphaMap)),n.normalMap&&(r._normalMap=r._checkComponent("Texture",n.normalMap)),r.alphaMode=n.alphaMode,r.alphaCutoff=n.alphaCutoff,r.backfaces=n.backfaces,r.frontface=n.frontface,r.lineWidth=n.lineWidth,r.pointSize=n.pointSize,r._makeHash(),r}return I(i,[{key:"type",get:function(){return"MetallicMaterial"}},{key:"_makeHash",value:function(){var e=this._state,t=["/met"];this._baseColorMap&&(t.push("/bm"),this._baseColorMap._state.hasMatrix&&t.push("/mat"),t.push("/"+this._baseColorMap._state.encoding)),this._metallicMap&&(t.push("/mm"),this._metallicMap._state.hasMatrix&&t.push("/mat")),this._roughnessMap&&(t.push("/rm"),this._roughnessMap._state.hasMatrix&&t.push("/mat")),this._metallicRoughnessMap&&(t.push("/mrm"),this._metallicRoughnessMap._state.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap._state.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap._state.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/am"),this._alphaMap._state.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap._state.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}},{key:"baseColor",get:function(){return this._state.baseColor},set:function(e){var t=this._state.baseColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.baseColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"baseColorMap",get:function(){return this._baseColorMap}},{key:"metallic",get:function(){return this._state.metallic},set:function(e){e=null!=e?e:1,this._state.metallic!==e&&(this._state.metallic=e,this.glRedraw())}},{key:"metallicMap",get:function(){return this._attached.metallicMap}},{key:"roughness",get:function(){return this._state.roughness},set:function(e){e=null!=e?e:1,this._state.roughness!==e&&(this._state.roughness=e,this.glRedraw())}},{key:"roughnessMap",get:function(){return this._attached.roughnessMap}},{key:"metallicRoughnessMap",get:function(){return this._attached.metallicRoughnessMap}},{key:"specularF0",get:function(){return this._state.specularF0},set:function(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"emissiveMap",get:function(){return this._attached.emissiveMap}},{key:"occlusionMap",get:function(){return this._attached.occlusionMap}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}},{key:"alphaMap",get:function(){return this._attached.alphaMap}},{key:"normalMap",get:function(){return this._attached.normalMap}},{key:"alphaMode",get:function(){return Nn[this._state.alphaMode]},set:function(e){var t=On[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}},{key:"alphaCutoff",get:function(){return this._state.alphaCutoff},set:function(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Qn={opaque:0,mask:1,blend:2},Hn=["opaque","mask","blend"],jn=function(e){m(i,mn);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state=new nt({type:"SpecularMaterial",diffuse:le.vec3([1,1,1]),emissive:le.vec3([0,0,0]),specular:le.vec3([1,1,1]),glossiness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),r.diffuse=n.diffuse,r.specular=n.specular,r.glossiness=n.glossiness,r.specularF0=n.specularF0,r.emissive=n.emissive,r.alpha=n.alpha,n.diffuseMap&&(r._diffuseMap=r._checkComponent("Texture",n.diffuseMap)),n.emissiveMap&&(r._emissiveMap=r._checkComponent("Texture",n.emissiveMap)),n.specularMap&&(r._specularMap=r._checkComponent("Texture",n.specularMap)),n.glossinessMap&&(r._glossinessMap=r._checkComponent("Texture",n.glossinessMap)),n.specularGlossinessMap&&(r._specularGlossinessMap=r._checkComponent("Texture",n.specularGlossinessMap)),n.occlusionMap&&(r._occlusionMap=r._checkComponent("Texture",n.occlusionMap)),n.alphaMap&&(r._alphaMap=r._checkComponent("Texture",n.alphaMap)),n.normalMap&&(r._normalMap=r._checkComponent("Texture",n.normalMap)),r.alphaMode=n.alphaMode,r.alphaCutoff=n.alphaCutoff,r.backfaces=n.backfaces,r.frontface=n.frontface,r.lineWidth=n.lineWidth,r.pointSize=n.pointSize,r._makeHash(),r}return I(i,[{key:"type",get:function(){return"SpecularMaterial"}},{key:"_makeHash",value:function(){var e=this._state,t=["/spe"];this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat")),this._glossinessMap&&(t.push("/gm"),this._glossinessMap.hasMatrix&&t.push("/mat")),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._specularGlossinessMap&&(t.push("/sgm"),this._specularGlossinessMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}},{key:"diffuse",get:function(){return this._state.diffuse},set:function(e){var t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"diffuseMap",get:function(){return this._diffuseMap}},{key:"specular",get:function(){return this._state.specular},set:function(e){var t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"specularMap",get:function(){return this._specularMap}},{key:"specularGlossinessMap",get:function(){return this._specularGlossinessMap}},{key:"glossiness",get:function(){return this._state.glossiness},set:function(e){e=null!=e?e:1,this._state.glossiness!==e&&(this._state.glossiness=e,this.glRedraw())}},{key:"glossinessMap",get:function(){return this._glossinessMap}},{key:"specularF0",get:function(){return this._state.specularF0},set:function(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"emissiveMap",get:function(){return this._emissiveMap}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}},{key:"alphaMap",get:function(){return this._alphaMap}},{key:"normalMap",get:function(){return this._normalMap}},{key:"occlusionMap",get:function(){return this._occlusionMap}},{key:"alphaMode",get:function(){return Hn[this._state.alphaMode]},set:function(e){var t=Qn[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}},{key:"alphaCutoff",get:function(){return this._state.alphaCutoff},set:function(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Gn={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}},zn=function(e){m(i,mn);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state=new nt({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),r._preset="default",n.preset?(r.preset=n.preset,void 0!==n.fill&&(r.fill=n.fill),n.fillColor&&(r.fillColor=n.fillColor),void 0!==n.fillAlpha&&(r.fillAlpha=n.fillAlpha),void 0!==n.edges&&(r.edges=n.edges),n.edgeColor&&(r.edgeColor=n.edgeColor),void 0!==n.edgeAlpha&&(r.edgeAlpha=n.edgeAlpha),void 0!==n.edgeWidth&&(r.edgeWidth=n.edgeWidth),void 0!==n.backfaces&&(r.backfaces=n.backfaces),void 0!==n.glowThrough&&(r.glowThrough=n.glowThrough)):(r.fill=n.fill,r.fillColor=n.fillColor,r.fillAlpha=n.fillAlpha,r.edges=n.edges,r.edgeColor=n.edgeColor,r.edgeAlpha=n.edgeAlpha,r.edgeWidth=n.edgeWidth,r.backfaces=n.backfaces,r.glowThrough=n.glowThrough),r}return I(i,[{key:"type",get:function(){return"EmphasisMaterial"}},{key:"presets",get:function(){return Gn}},{key:"fill",get:function(){return this._state.fill},set:function(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}},{key:"fillColor",get:function(){return this._state.fillColor},set:function(e){var t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}},{key:"fillAlpha",get:function(){return this._state.fillAlpha},set:function(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}},{key:"edges",get:function(){return this._state.edges},set:function(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}},{key:"edgeColor",get:function(){return this._state.edgeColor},set:function(e){var t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"edgeAlpha",get:function(){return this._state.edgeAlpha},set:function(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}},{key:"edgeWidth",get:function(){return this._state.edgeWidth},set:function(e){this._state.edgeWidth=e||1,this.glRedraw()}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"glowThrough",get:function(){return this._state.glowThrough},set:function(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}},{key:"preset",get:function(){return console.warn("EmphasisMaterial.preset is deprecated and will be removed in future versions."),this._preset},set:function(e){if(console.warn("EmphasisMaterial.preset is deprecated and will be removed in future versions."),e=e||"default",this._preset!==e){var t=Gn[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Gn).join(", "))}}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Wn={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}},Xn=function(e){m(i,mn);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state=new nt({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),r._preset="default",n.preset?(r.preset=n.preset,n.edgeColor&&(r.edgeColor=n.edgeColor),void 0!==n.edgeAlpha&&(r.edgeAlpha=n.edgeAlpha),void 0!==n.edgeWidth&&(r.edgeWidth=n.edgeWidth)):(r.edgeColor=n.edgeColor,r.edgeAlpha=n.edgeAlpha,r.edgeWidth=n.edgeWidth),r.edges=!1!==n.edges,r}return I(i,[{key:"type",get:function(){return"EdgeMaterial"}},{key:"presets",get:function(){return Wn}},{key:"edges",get:function(){return this._state.edges},set:function(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}},{key:"edgeColor",get:function(){return this._state.edgeColor},set:function(e){var t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"edgeAlpha",get:function(){return this._state.edgeAlpha},set:function(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}},{key:"edgeWidth",get:function(){return this._state.edgeWidth},set:function(e){this._state.edgeWidth=e||1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Wn[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Wn).join(", "))}}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Kn=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state=new nt({edgeColor:le.vec3([0,0,0]),centerColor:le.vec3([1,1,1]),edgeBias:0,centerBias:1,power:1}),r.edgeColor=n.edgeColor,r.centerColor=n.centerColor,r.edgeBias=n.edgeBias,r.centerBias=n.centerBias,r.power=n.power,r}return I(i,[{key:"type",get:function(){return"Fresnel"}},{key:"edgeColor",get:function(){return this._state.edgeColor},set:function(e){this._state.edgeColor.set(e||[0,0,0]),this.glRedraw()}},{key:"centerColor",get:function(){return this._state.centerColor},set:function(e){this._state.centerColor.set(e||[1,1,1]),this.glRedraw()}},{key:"edgeBias",get:function(){return this._state.edgeBias},set:function(e){this._state.edgeBias=e||0,this.glRedraw()}},{key:"centerBias",get:function(){return this._state.centerBias},set:function(e){this._state.centerBias=null!=e?e:1,this.glRedraw()}},{key:"power",get:function(){return this._state.power},set:function(e){this._state.power=null!=e?e:1,this.glRedraw()}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Zn=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._type=n.type||(n.src?n.src.split(".").pop():null)||"jpg",r._pos=le.vec3(n.pos||[0,0,0]),r._up=le.vec3(n.up||[0,1,0]),r._normal=le.vec3(n.normal||[0,0,1]),r._height=n.height||1,r._origin=le.vec3(),r._rtcPos=le.vec3(),r._imageSize=le.vec2(),r._texture=new In(w(r),{flipY:!0}),r._image=new Image,"jpg"!==r._type&&"png"!==r._type&&(r.error('Unsupported type - defaulting to "jpg"'),r._type="jpg"),r._node=new Xt(w(r),{matrix:le.inverseMat4(le.lookAtMat4v(r._pos,le.subVec3(r._pos,r._normal,le.mat4()),r._up,le.mat4())),children:[r._bitmapMesh=new vn(w(r),{scale:[1,1,1],rotation:[-90,0,0],collidable:n.collidable,pickable:n.pickable,opacity:n.opacity,clippable:n.clippable,geometry:new mt(w(r),Ft({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new bn(w(r),{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:r._texture,emissiveMap:r._texture,backfaces:!0})})]}),n.image?r.image=n.image:n.src?r.src=n.src:n.imageData&&(r.imageData=n.imageData),r.scene._bitmapCreated(w(r)),r}return I(i,[{key:"visible",get:function(){return this._bitmapMesh.visible},set:function(e){this._bitmapMesh.visible=e}},{key:"image",get:function(){return this._image},set:function(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}},{key:"src",get:function(){return this._image.src},set:function(e){var t=this;if(e)switch(this._image.onload=function(){t._texture.image=t._image,t._imageSize[0]=t._image.width,t._imageSize[1]=t._image.height,t._updateBitmapMeshScale()},this._image.src=e,e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}},{key:"imageData",get:function(){var e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")},set:function(e){var t=this;this._image.onload=function(){t._texture.image=image,t._imageSize[0]=image.width,t._imageSize[1]=image.height,t._updateBitmapMeshScale()},this._image.src=e}},{key:"type",get:function(){return this._type},set:function(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}},{key:"pos",get:function(){return this._pos}},{key:"normal",get:function(){return this._normal}},{key:"up",get:function(){return this._up}},{key:"height",get:function(){return this._height},set:function(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}},{key:"collidable",get:function(){return this._bitmapMesh.collidable},set:function(e){this._bitmapMesh.collidable=!1!==e}},{key:"clippable",get:function(){return this._bitmapMesh.clippable},set:function(e){this._bitmapMesh.clippable=!1!==e}},{key:"pickable",get:function(){return this._bitmapMesh.pickable},set:function(e){this._bitmapMesh.pickable=!1!==e}},{key:"opacity",get:function(){return this._bitmapMesh.opacity},set:function(e){this._bitmapMesh.opacity=e}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this.scene._bitmapDestroyed(this)}},{key:"_updateBitmapMeshScale",value:function(){var e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}]),i}(),Jn=function(e,t){var i=[],r=[];function n(e,i){for(var r,n,s=0;s<3;s++)if((r=t[3*e+s])!==(n=t[3*i+s]))return n-r;return 0}for(var s=e.slice().sort(n),o=null,a=0,l=s.length;a<l;a++)0!==a&&0===n(s[a],s[a-1])||(o=s[a]),i[s[a]]=o;for(var u=0,c=e.length;u<c;u+=3){var A=i[e[u]],h=i[e[u+1]],d=i[e[u+2]],p=A,f=h,v=d;if(A>h&&A>d?h>d?(p=A,f=h,v=d):(p=A,f=d,v=h):h>A&&h>d?A>d?(p=h,f=A,v=d):(p=h,f=d,v=A):d>A&&d>h&&(A>h?(p=d,f=A,v=h):(p=d,f=h,v=A)),r[u+0]=[p,f],r[u+1]=[f,v],p>v){var g=v;v=p,p=g}r[u+2]=[v,p]}function m(e,t){for(var i,r,n=0;n<2;n++)if(i=e[n],(r=t[n])!==i)return r-i;return 0}(r=r.slice(0,e.length)).sort(m);for(var _=0,y=0;y<r.length;y++)if(0===y||0!==m(r[y],r[y-1])){if(0!==y&&2!==_)return!1;_=1}else _++;return!(r.length>0&&2!==_)},Yn=le.vec3(),qn=le.vec3(),$n=le.vec3(),es=function(){function e(){E(this,e),this.vertices=[],this.indices=[],this.reset()}return I(e,[{key:"reset",value:function(){this.lenVertices=0,this.lenIndices=0,this.primitive=null}},{key:"setPrimitive",value:function(e){this.primitive=e}},{key:"addVertex",value:function(e){this.vertices[this.lenVertices++]=e[0],this.vertices[this.lenVertices++]=e[1],this.vertices[this.lenVertices++]=e[2]}},{key:"addIndex",value:function(e){this.indices[this.lenIndices++]=e}},{key:"volume",get:function(){var e=this.vertices,t=this.indices;if("solid"!==this.primitive&&"surface"!==this.primitive&&"triangles"!==this.primitive)return-1;if("solid"!==this.primitive&&!Jn(t,e))return-1;for(var i=0,r=0;r<this.lenIndices;r+=3){var n=3*t[r],s=3*t[r+1],o=3*t[r+2];Yn[0]=e[n],Yn[1]=e[n+1],Yn[2]=e[n+2],qn[0]=e[s],qn[1]=e[s+1],qn[2]=e[s+2],$n[0]=e[o],$n[1]=e[o+1],$n[2]=e[o+2],le.cross3Vec3(Yn,qn,Yn),i+=le.dotVec3(Yn,$n)}return i/6}}]),e}(),ts=new es,is=le.vec3(),rs=le.vec3(),ns=le.vec3(),ss=le.vec3(),os=le.vec3(),as=le.vec3(),ls=function(){function e(){E(this,e),this.vertices=[],this.indices=[],this.reset()}return I(e,[{key:"reset",value:function(){this.lenVertices=0,this.lenIndices=0}},{key:"addVertex",value:function(e){this.vertices[this.lenVertices++]=e[0],this.vertices[this.lenVertices++]=e[1],this.vertices[this.lenVertices++]=e[2]}},{key:"addIndex",value:function(e){this.indices[this.lenIndices++]=e}},{key:"surfaceArea",get:function(){for(var e=this.vertices,t=this.indices,i=0,r=0;r<this.lenIndices;r+=3){var n=3*t[r],s=3*t[r+1],o=3*t[r+2];is[0]=e[n],is[1]=e[n+1],is[2]=e[n+2],rs[0]=e[s],rs[1]=e[s+1],rs[2]=e[s+2],ns[0]=e[o],ns[1]=e[o+1],ns[2]=e[o+2],le.subVec3(is,rs,ss),le.subVec3(ns,rs,os),i+=.5*le.lenVec3(le.cross3Vec3(ss,os,as))}return i}}]),e}(),us=new ls,cs=le.OBB3(),As=le.OBB3(),hs=le.OBB3(),ds=function(){function e(t,i,r,n,s,o){var a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null,l=arguments.length>7&&void 0!==arguments[7]?arguments[7]:0;E(this,e),this.model=t,this.object=null,this.parent=null,this.transform=s,this.textureSet=o,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=i,this.obb=null,this._aabbLocal=null,this._aabbWorld=le.AABB3(),this._aabbWorldDirty=!1,this.layer=a,this.portionId=l,this._color=new Uint8Array([r[0],r[1],r[2],n]),this._colorize=new Uint8Array([r[0],r[1],r[2],n]),this._colorizing=!1,this._transparent=n<255,this.numTriangles=0,this.origin=null,this.entity=null,s&&s._addMesh(this),this._volume=null,this._surfaceArea=null}return I(e,[{key:"_sceneModelDirty",value:function(){this._aabbWorldDirty=!0,this.layer.aabbDirty=!0}},{key:"_transformDirty",value:function(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbWorldDirty=!0,this.layer.aabbDirty=!0,this.entity&&this.entity._transformDirty()}},{key:"_updateMatrix",value:function(){this.transform&&this._matrixDirty&&this.layer.setMatrix(this.portionId,this.transform.worldMatrix),this._matrixDirty=!1,this._matrixUpdateScheduled=!1}},{key:"_finalize",value:function(e){this.layer.initFlags(this.portionId,e,this._transparent)}},{key:"_finalize2",value:function(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}},{key:"_setVisible",value:function(e){this.layer.setVisible(this.portionId,e,this._transparent)}},{key:"_setColor",value:function(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}},{key:"_setColorize",value:function(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}},{key:"_setOpacity",value:function(e,t){var i=e<255,r=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),r&&this.layer.setTransparent(this.portionId,t,i)}},{key:"_setOffset",value:function(e){this.layer.setOffset(this.portionId,e)}},{key:"_setHighlighted",value:function(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}},{key:"_setXRayed",value:function(e){this.layer.setXRayed(this.portionId,e,this._transparent)}},{key:"_setSelected",value:function(e){this.layer.setSelected(this.portionId,e,this._transparent)}},{key:"_setEdges",value:function(e){this.layer.setEdges(this.portionId,e,this._transparent)}},{key:"_setClippable",value:function(e){this.layer.setClippable(this.portionId,e,this._transparent)}},{key:"_setCollidable",value:function(e){this.layer.setCollidable(this.portionId,e)}},{key:"_setPickable",value:function(e){this.layer.setPickable(this.portionId,e,this._transparent)}},{key:"_setCulled",value:function(e){this.layer.setCulled(this.portionId,e,this._transparent)}},{key:"canPickTriangle",value:function(){return!1}},{key:"drawPickTriangles",value:function(e,t){}},{key:"pickTriangleSurface",value:function(e){}},{key:"precisionRayPickSurface",value:function(e,t,i,r){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,i,r)}},{key:"canPickWorldPos",value:function(){return!0}},{key:"drawPickDepths",value:function(e){this.model.drawPickDepths(e)}},{key:"drawPickNormals",value:function(e){this.model.drawPickNormals(e)}},{key:"delegatePickedEntity",value:function(){return this.parent}},{key:"getEachVertex",value:function(e){this.layer.getEachVertex&&this.layer.getEachVertex(this.portionId,e)}},{key:"getEachIndex",value:function(e){this.layer.getEachIndex&&this.layer.getEachIndex(this.portionId,e)}},{key:"isSolid",value:function(){return this.layer.solid}},{key:"volume",get:function(){if(null!==this._volume)return this._volume;switch(this.layer.primitive){case"solid":case"surface":case"triangles":ts.reset(),ts.setPrimitive(this.layer.primitive),this.getEachVertex((function(e){ts.addVertex(e)})),this.getEachIndex((function(e){ts.addIndex(e)})),this._volume=ts.volume;break;default:this._volume=0}return this._volume}},{key:"surfaceArea",get:function(){if(null!==this._surfaceArea)return this._surfaceArea;switch(this.layer.primitive){case"solid":case"surface":case"triangles":us.reset(),this.getEachVertex((function(e){us.addVertex(e)})),this.getEachIndex((function(e){us.addIndex(e)})),this._surfaceArea=us.surfaceArea;break;default:this._surfaceArea=0}return this._surfaceArea}},{key:"aabb",get:function(){return this._aabbWorldDirty&&(le.AABB3ToOBB3(this._aabbLocal,cs),this.transform?(le.transformOBB3(this.transform.worldMatrix,cs,As),le.transformOBB3(this.model.worldMatrix,As,hs),le.OBB3ToAABB3(hs,this._aabbWorld)):(le.transformOBB3(this.model.worldMatrix,cs,As),le.OBB3ToAABB3(As,this._aabbWorld)),this._aabbWorldDirty=!1),this._aabbWorld},set:function(e){if(this._aabbLocal=e,this.origin){this._aabbLocal=e.slice(0);var t=this.origin;this._aabbLocal[0]+=t[0],this._aabbLocal[1]+=t[1],this._aabbLocal[2]+=t[2],this._aabbLocal[3]+=t[0],this._aabbLocal[4]+=t[1],this._aabbLocal[5]+=t[2]}}},{key:"_destroy",value:function(){this.model.scene._renderer.putPickID(this.pickId)}}]),e}(),ps=new(function(){function e(){E(this,e),this._uint8Arrays={},this._float32Arrays={}}return I(e,[{key:"_clear",value:function(){this._uint8Arrays={},this._float32Arrays={}}},{key:"getUInt8Array",value:function(e){var t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}},{key:"getFloat32Array",value:function(e){var t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}}]),e}()),fs=0;function vs(){return fs++,ps}var gs=1,ms=4,_s=8,ys=16,bs=32,ws=256,Bs=512,xs=1024,Ps=2048,Cs={NOT_RENDERED:0,COLOR_OPAQUE:1,COLOR_TRANSPARENT:2,SILHOUETTE_HIGHLIGHTED:3,SILHOUETTE_SELECTED:4,SILHOUETTE_XRAYED:5,EDGES_COLOR_OPAQUE:6,EDGES_COLOR_TRANSPARENT:7,EDGES_HIGHLIGHTED:8,EDGES_SELECTED:9,EDGES_XRAYED:10,PICK:11},Ms=new Float32Array([1,1,1,1]),ks=new Float32Array([0,0,0,1]),Es=le.vec4(),Fs=le.vec3(),Is=le.vec3(),Ts=le.mat4(),Ds=function(){function e(t){var i=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=r.instancing,s=void 0!==n&&n,o=r.edges,a=void 0!==o&&o,l=r.useAlphaCutoff,u=void 0!==l&&l;E(this,e),this._scene=t,this._withSAO=i,this._instancing=s,this._edges=a,this._useAlphaCutoff=u,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}return I(e,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){return[""]}},{key:"_buildFragmentShader",value:function(){return[""]}},{key:"_addMatricesUniformBlockLines",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}},{key:"_addRemapClipPosLines",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(".concat(t,"));")),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}},{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"setSectionPlanesStateUniforms",value:function(e){var t=this._scene,i=t.canvas.gl,r=e.model,n=e.layerIndex,s=t._sectionPlanesState.getNumAllocatedSectionPlanes(),o=t._sectionPlanesState.sectionPlanes.length;if(s>0){var a=t._sectionPlanesState.sectionPlanes,l=n*o,u=r.renderFlags;t.crossSections&&(i.uniform4fv(this._uSliceColor,t.crossSections.sliceColor),i.uniform1f(this._uSliceThickness,t.crossSections.sliceThickness));for(var c=0;c<s;c++){var A=this._uSectionPlanes[c];if(A)if(c<o){var h=u.sectionPlanesActivePerLayer[l+c];if(i.uniform1i(A.active,h?1:0),h){var d=a[c],p=e._state.origin;if(p){var f=ei(d.dist,d.dir,p,Fs,r.matrix);i.uniform3fv(A.pos,f)}else i.uniform3fv(A.pos,d.pos);i.uniform3fv(A.dir,d.dir)}}else i.uniform1i(A.active,0)}}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new Pr(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var r=this._program;this._uRenderPass=r.getLocation("renderPass"),this._uColor=r.getLocation("color"),this._uColor||(this._uColor=r.getLocation("silhouetteColor")),this._uUVDecodeMatrix=r.getLocation("uvDecodeMatrix"),this._uPickInvisible=r.getLocation("pickInvisible"),this._uGammaFactor=r.getLocation("gammaFactor"),t.uniformBlockBinding(r.handle,t.getUniformBlockIndex(r.handle,"Matrices"),this._matricesUniformBlockBufferBindingPoint),this._uShadowViewMatrix=r.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=r.getLocation("shadowProjMatrix"),e.logarithmicDepthBufferEnabled&&(this._uZFar=r.getLocation("zFar")),this._uLightAmbient=r.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(var n=i.lights,s=0,o=n.length;s<o;s++)switch(n[s].type){case"dir":this._uLightColor[s]=r.getLocation("lightColor"+s),this._uLightPos[s]=null,this._uLightDir[s]=r.getLocation("lightDir"+s);break;case"point":this._uLightColor[s]=r.getLocation("lightColor"+s),this._uLightPos[s]=r.getLocation("lightPos"+s),this._uLightDir[s]=null,this._uLightAttenuation[s]=r.getLocation("lightAttenuation"+s);break;case"spot":this._uLightColor[s]=r.getLocation("lightColor"+s),this._uLightPos[s]=r.getLocation("lightPos"+s),this._uLightDir[s]=r.getLocation("lightDir"+s),this._uLightAttenuation[s]=r.getLocation("lightAttenuation"+s)}i.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(var a=0,l=e._sectionPlanesState.getNumAllocatedSectionPlanes();a<l;a++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+a),pos:r.getLocation("sectionPlanePos"+a),dir:r.getLocation("sectionPlaneDir"+a)});this._aPosition=r.getAttribute("position"),this._aOffset=r.getAttribute("offset"),this._aNormal=r.getAttribute("normal"),this._aUV=r.getAttribute("uv"),this._aColor=r.getAttribute("color"),this._aMetallicRoughness=r.getAttribute("metallicRoughness"),this._aFlags=r.getAttribute("flags"),this._aPickColor=r.getAttribute("pickColor"),this._uPickZNear=r.getLocation("pickZNear"),this._uPickZFar=r.getLocation("pickZFar"),this._uPickClipPos=r.getLocation("pickClipPos"),this._uDrawingBufferSize=r.getLocation("drawingBufferSize"),this._uColorMap="uColorMap",this._uMetallicRoughMap="uMetallicRoughMap",this._uEmissiveMap="uEmissiveMap",this._uNormalMap="uNormalMap",this._uAOMap="uAOMap",this._instancing&&(this._aModelMatrix=r.getAttribute("modelMatrix"),this._aModelMatrixCol0=r.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=r.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=r.getAttribute("modelMatrixCol2"),this._aModelNormalMatrixCol0=r.getAttribute("modelNormalMatrixCol0"),this._aModelNormalMatrixCol1=r.getAttribute("modelNormalMatrixCol1"),this._aModelNormalMatrixCol2=r.getAttribute("modelNormalMatrixCol2")),this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=r.getLocation("uSAOParams")),this._useAlphaCutoff&&(this._alphaCutoffLocation=r.getLocation("materialAlphaCutoff")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=r.getLocation("logDepthBufFC")),e.pointsMaterial._state.filterIntensity&&(this._uIntensityRange=r.getLocation("intensityRange")),this._uPointSize=r.getLocation("pointSize"),this._uNearPlaneHeight=r.getLocation("nearPlaneHeight"),e.crossSections&&(this._uSliceColor=r.getLocation("sliceColor"),this._uSliceThickness=r.getLocation("sliceThickness"))}}},{key:"_bindProgram",value:function(e){var t=this._scene,i=t.canvas.gl,r=this._program,n=t._lightsState,s=n.lights;r.bind(),e.textureUnit=0,this._uLightAmbient&&i.uniform4fv(this._uLightAmbient,n.getAmbientColorAndIntensity()),this._uGammaFactor&&i.uniform1f(this._uGammaFactor,t.gammaFactor);for(var o=0,a=s.length;o<a;o++){var l=s[o];this._uLightColor[o]&&i.uniform4f(this._uLightColor[o],l.color[0],l.color[1],l.color[2],l.intensity),this._uLightPos[o]&&(i.uniform3fv(this._uLightPos[o],l.pos),this._uLightAttenuation[o]&&i.uniform1f(this._uLightAttenuation[o],l.attenuation)),this._uLightDir[o]&&i.uniform3fv(this._uLightDir[o],l.dir)}}},{key:"_makeVAO",value:function(e){var t=this._scene.canvas.gl,i=t.createVertexArray();return t.bindVertexArray(i),this._instancing&&(this._aModelMatrixCol0.bindArrayBuffer(e.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(e.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(e.modelMatrixCol2Buf),t.vertexAttribDivisor(this._aModelMatrixCol0.location,1),t.vertexAttribDivisor(this._aModelMatrixCol1.location,1),t.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aModelNormalMatrixCol0&&(this._aModelNormalMatrixCol0.bindArrayBuffer(e.modelNormalMatrixCol0Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol0.location,1)),this._aModelNormalMatrixCol1&&(this._aModelNormalMatrixCol1.bindArrayBuffer(e.modelNormalMatrixCol1Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol1.location,1)),this._aModelNormalMatrixCol2&&(this._aModelNormalMatrixCol2.bindArrayBuffer(e.modelNormalMatrixCol2Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol2.location,1))),this._aPosition.bindArrayBuffer(e.positionsBuf),this._aUV&&this._aUV.bindArrayBuffer(e.uvBuf),this._aNormal&&this._aNormal.bindArrayBuffer(e.normalsBuf),this._aMetallicRoughness&&(this._aMetallicRoughness.bindArrayBuffer(e.metallicRoughnessBuf),this._instancing&&t.vertexAttribDivisor(this._aMetallicRoughness.location,1)),this._aColor&&(this._aColor.bindArrayBuffer(e.colorsBuf),this._instancing&&e.colorsBuf&&t.vertexAttribDivisor(this._aColor.location,1)),this._aFlags&&(this._aFlags.bindArrayBuffer(e.flagsBuf),this._instancing&&t.vertexAttribDivisor(this._aFlags.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(e.offsetsBuf),this._instancing&&t.vertexAttribDivisor(this._aOffset.location,1)),this._aPickColor&&(this._aPickColor.bindArrayBuffer(e.pickColorsBuf),this._instancing&&t.vertexAttribDivisor(this._aPickColor.location,1)),this._instancing,this._edges&&e.edgeIndicesBuf?e.edgeIndicesBuf.bind():e.indicesBuf&&e.indicesBuf.bind(),i}},{key:"drawLayer",value:function(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},n=r.colorUniform,s=void 0!==n&&n,o=r.incrementDrawState,a=void 0!==o&&o,l=Cr.MAX_TEXTURE_IMAGE_UNITS,u=this._scene,c=u.canvas.gl,A=t._state,h=t.model,d=A.textureSet,p=A.origin,f=A.positionsDecodeMatrix,v=u._lightsState,g=u.pointsMaterial,m=h.scene.camera,_=m.viewNormalMatrix,y=m.project,b=e.pickViewMatrix||m.viewMatrix,w=h.position,B=h.rotationMatrix,x=h.worldNormalMatrix;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),this._vaoCache.has(t)?c.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(A));var P=0,C=16;this._matricesUniformBlockBufferData.set(B,0);var M=0!==p[0]||0!==p[1]||0!==p[2],k=0!==w[0]||0!==w[1]||0!==w[2];if(M||k){var E=Fs;if(M){var F=le.transformPoint3(B,p,Is);E[0]=F[0],E[1]=F[1],E[2]=F[2]}else E[0]=0,E[1]=0,E[2]=0;E[0]+=w[0],E[1]+=w[1],E[2]+=w[2],this._matricesUniformBlockBufferData.set(Jt(b,E,Ts),P+=C)}else this._matricesUniformBlockBufferData.set(b,P+=C);if(this._matricesUniformBlockBufferData.set(e.pickProjMatrix||y.matrix,P+=C),this._matricesUniformBlockBufferData.set(f,P+=C),this._matricesUniformBlockBufferData.set(x,P+=C),this._matricesUniformBlockBufferData.set(_,P+=C),c.bindBuffer(c.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),c.bufferData(c.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,c.DYNAMIC_DRAW),c.bindBufferBase(c.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer),c.uniform1i(this._uRenderPass,i),this.setSectionPlanesStateUniforms(t),u.logarithmicDepthBufferEnabled){if(this._uLogDepthBufFC){var I=2/(Math.log(e.pickZFar+1)/Math.LN2);c.uniform1f(this._uLogDepthBufFC,I)}this._uZFar&&c.uniform1f(this._uZFar,u.camera.project.far)}if(this._uPickInvisible&&c.uniform1i(this._uPickInvisible,e.pickInvisible),this._uPickZNear&&c.uniform1f(this._uPickZNear,e.pickZNear),this._uPickZFar&&c.uniform1f(this._uPickZFar,e.pickZFar),this._uPickClipPos&&c.uniform2fv(this._uPickClipPos,e.pickClipPos),this._uDrawingBufferSize&&c.uniform2f(this._uDrawingBufferSize,c.drawingBufferWidth,c.drawingBufferHeight),this._uUVDecodeMatrix&&c.uniformMatrix3fv(this._uUVDecodeMatrix,!1,A.uvDecodeMatrix),this._uIntensityRange&&g.filterIntensity&&c.uniform2f(this._uIntensityRange,g.minIntensity,g.maxIntensity),this._uPointSize&&c.uniform1f(this._uPointSize,g.pointSize),this._uNearPlaneHeight){var T="ortho"===u.camera.projection?1:c.drawingBufferHeight/(2*Math.tan(.5*u.camera.perspective.fov*Math.PI/180));c.uniform1f(this._uNearPlaneHeight,T)}if(d){var D=d.colorTexture,S=d.metallicRoughnessTexture,R=d.emissiveTexture,U=d.normalsTexture,L=d.occlusionTexture;this._uColorMap&&D&&(this._program.bindTexture(this._uColorMap,D.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uMetallicRoughMap&&S&&(this._program.bindTexture(this._uMetallicRoughMap,S.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uEmissiveMap&&R&&(this._program.bindTexture(this._uEmissiveMap,R.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uNormalMap&&U&&(this._program.bindTexture(this._uNormalMap,U.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uAOMap&&L&&(this._program.bindTexture(this._uAOMap,L.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l)}if(v.reflectionMaps.length>0&&v.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,v.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l,e.bindTexture++),v.lightMaps.length>0&&v.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,v.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l,e.bindTexture++),this._withSAO){var O=u.sao,N=O.possible;if(N){var V=c.drawingBufferWidth,Q=c.drawingBufferHeight;Es[0]=V,Es[1]=Q,Es[2]=O.blendCutoff,Es[3]=O.blendFactor,c.uniform4fv(this._uSAOParams,Es),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l,e.bindTexture++}}if(this._useAlphaCutoff&&c.uniform1f(this._alphaCutoffLocation,d.alphaCutoff),s){var H=this._edges?"edgeColor":"fillColor",j=this._edges?"edgeAlpha":"fillAlpha";if(i===Cs["".concat(this._edges?"EDGES":"SILHOUETTE","_XRAYED")]){var G=u.xrayMaterial._state,z=G[H],W=G[j];c.uniform4f(this._uColor,z[0],z[1],z[2],W)}else if(i===Cs["".concat(this._edges?"EDGES":"SILHOUETTE","_HIGHLIGHTED")]){var X=u.highlightMaterial._state,K=X[H],Z=X[j];c.uniform4f(this._uColor,K[0],K[1],K[2],Z)}else if(i===Cs["".concat(this._edges?"EDGES":"SILHOUETTE","_SELECTED")]){var J=u.selectedMaterial._state,Y=J[H],q=J[j];c.uniform4f(this._uColor,Y[0],Y[1],Y[2],q)}else c.uniform4fv(this._uColor,this._edges?ks:Ms)}this._draw({state:A,frameCtx:e,incrementDrawState:a}),c.bindVertexArray(null)}}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null,he.memory.programs--}}]),e}(),Ss=function(e){m(i,Ds);var t=y(i);function i(e,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=n.edges,o=void 0!==s&&s,a=n.useAlphaCutoff,l=void 0!==a&&a;return E(this,i),t.call(this,e,r,{instancing:!1,edges:o,useAlphaCutoff:l})}return I(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,r=e.frameCtx,n=e.incrementDrawState;if(this._edges)i.edgeIndicesBuf&&t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{var s=r.pickElementsCount||i.indicesBuf.numItems,o=r.pickElementsOffset?r.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,s,i.indicesBuf.itemType,o),n&&r.drawElements++}}}]),i}(),Rs=function(e){m(i,Ss);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e,t=this._scene,i=t._sectionPlanesState,r=t._lightsState,n=i.getNumAllocatedSectionPlanes()>0,s=[];s.push("#version 300 es"),s.push("// Triangles batching draw vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),t.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s,!0),t.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("uniform vec4 lightAmbient;");for(var o=0,a=r.lights.length;o<a;o++)"ambient"!==(e=r.lights[o]).type&&(s.push("uniform vec4 lightColor"+o+";"),"dir"===e.type&&s.push("uniform vec3 lightDir"+o+";"),"point"===e.type&&s.push("uniform vec3 lightPos"+o+";"),"spot"===e.type&&(s.push("uniform vec3 lightPos"+o+";"),s.push("uniform vec3 lightDir"+o+";")));s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),n&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),t.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),s.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),s.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),s.push("float lambertian = 1.0;");for(var l=0,u=r.lights.length;l<u;l++)if("ambient"!==(e=r.lights[l]).type){if("dir"===e.type)"view"===e.space?s.push("viewLightDir = normalize(lightDir"+l+");"):s.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+l+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?s.push("viewLightDir = -normalize(lightPos"+l+" - viewPosition.xyz);"):s.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+l+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?s.push("viewLightDir = normalize(lightDir"+l+");"):s.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+l+", 0.0)).xyz);")}s.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),s.push("reflectedColor += lambertian * (lightColor"+l+".rgb * lightColor"+l+".a);")}return s.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));"),s.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0,s=t.getNumAllocatedSectionPlanes();n<s;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";");r.push("uniform float sliceThickness;"),r.push("uniform vec4 sliceColor;")}if(r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),r.push(" vec4 newColor;"),r.push(" newColor = vColor;"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o<a;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > sliceThickness) { "),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" newColor = sliceColor;"),r.push(" }"),r.push("}")}return e.logarithmicDepthBufferEnabled?(r.push(" float dx = dFdx(vFragDepth);"),r.push(" float dy = dFdy(vFragDepth);"),r.push(" float diff = sqrt(dx*dx+dy*dy);"),r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;")):(r.push(" float dx = dFdx(gl_FragCoord.z);"),r.push(" float dy = dFdy(gl_FragCoord.z);"),r.push(" float diff = sqrt(dx*dx+dy*dy);"),r.push(" gl_FragDepth = gl_FragCoord.z + diff;")),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):r.push(" outColor = newColor;"),r.push("}"),r}}]),i}(),Us=function(e){m(i,Ss);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._lightsState,i=e._sectionPlanesState,r=i.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching flat-shading draw fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var s=0,o=i.getNumAllocatedSectionPlanes();s<o;s++)n.push("uniform bool sectionPlaneActive"+s+";"),n.push("uniform vec3 sectionPlanePos"+s+";"),n.push("uniform vec3 sectionPlaneDir"+s+";");n.push("uniform float sliceThickness;"),n.push("uniform vec4 sliceColor;")}this._addMatricesUniformBlockLines(n),n.push("uniform vec4 lightAmbient;");for(var a=0,l=t.lights.length;a<l;a++){var u=t.lights[a];"ambient"!==u.type&&(n.push("uniform vec4 lightColor"+a+";"),"dir"===u.type&&n.push("uniform vec3 lightDir"+a+";"),"point"===u.type&&n.push("uniform vec3 lightPos"+a+";"),"spot"===u.type&&(n.push("uniform vec3 lightPos"+a+";"),n.push("uniform vec3 lightDir"+a+";")))}if(n.push("in vec4 vViewPosition;"),n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),n.push(" vec4 newColor;"),n.push(" newColor = vColor;"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var c=0,A=i.getNumAllocatedSectionPlanes();c<A;c++)n.push("if (sectionPlaneActive"+c+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+c+".xyz, vWorldPosition.xyz - sectionPlanePos"+c+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(var h=0,d=t.lights.length;h<d;h++){var p=t.lights[h];if("ambient"!==p.type){if("dir"===p.type)"view"===p.space?n.push("viewLightDir = normalize(lightDir"+h+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+h+", 0.0)).xyz);");else if("point"===p.type)"view"===p.space?n.push("viewLightDir = -normalize(lightPos"+h+" - vViewPosition.xyz);"):n.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+h+", 0.0)).xyz);");else{if("spot"!==p.type)continue;"view"===p.space?n.push("viewLightDir = normalize(lightDir"+h+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+h+", 0.0)).xyz);")}n.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),n.push("reflectedColor += lambertian * (lightColor"+h+".rgb * lightColor"+h+".a);")}}return n.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.a);"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(fragColor.rgb * ambient, 1.0);")):n.push(" outColor = fragColor;"),e.logarithmicDepthBufferEnabled?n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"):(n.push(" float dx = dFdx(gl_FragCoord.z);"),n.push(" float dy = dFdy(gl_FragCoord.z);"),n.push(" float diff = sqrt(dx*dx+dy*dy);"),n.push(" gl_FragDepth = gl_FragCoord.z + diff;")),n.push("}"),n}}]),i}(),Ls=function(e){m(i,Ss);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,r=i._sectionPlanesState,n=r.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),i.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),n){for(s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;"),e=0,t=r.getNumAllocatedSectionPlanes();e<t;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";");s.push("uniform float sliceThickness;"),s.push("uniform vec4 sliceColor;")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" vec4 newColor;"),s.push(" newColor = vColor;"),n){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=r.getNumAllocatedSectionPlanes();o<a;o++)s.push("if (sectionPlaneActive"+o+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return i.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = newColor;"),s.push("}"),s}}]),i}(),Os=function(e){m(i,Ss);var t=y(i);function i(e){return E(this,i),t.call(this,e,!1,{instancing:!1,edges:!0})}return I(i)}(),Ns=function(e){m(i,Os);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// EdgesEmphasisRenderer fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0,s=t.getNumAllocatedSectionPlanes();n<s;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o<a;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = vColor;"),r.push("}"),r}}]),i}(),Vs=function(e){m(i,Os);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{colorUniform:!1})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry edges drawing fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0,s=t.getNumAllocatedSectionPlanes();n<s;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o<a;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = vColor;"),r.push("}"),r}}]),i}(),Qs=function(e){m(i,Ss);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0;n<t.getNumAllocatedSectionPlanes();n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec4 vPickColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.getNumAllocatedSectionPlanes();s++)r.push(" if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vPickColor; "),r.push("}"),r}}]),i}(),Hs=function(e){m(i,Ss);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching pick depth fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform float pickZNear;"),r.push("uniform float pickZFar;"),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0;n<t.getNumAllocatedSectionPlanes();n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec4 vViewPosition;"),r.push("vec4 packDepth(const in float depth) {"),r.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),r.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),r.push(" vec4 res = fract(depth * bitShift);"),r.push(" res -= res.xxyz * bitMask;"),r.push(" return res;"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.getNumAllocatedSectionPlanes();s++)r.push(" if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),r.push(" outColor = packDepth(zNormalizedDepth); "),r.push("}"),r}}]),i}(),js=function(e){m(i,Ss);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching pick normals fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0;n<t.getNumAllocatedSectionPlanes();n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec3 vWorldNormal;"),r.push("out highp ivec4 outNormal;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.getNumAllocatedSectionPlanes();s++)r.push(" if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outNormal = ivec4(vWorldNormal * float(".concat(le.MAX_INT,"), 1.0);")),r.push("}"),r}}]),i}(),Gs=function(e){m(i,Ss);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r<e.getNumAllocatedSectionPlanes();r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<e.getNumAllocatedSectionPlanes();n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}]),i}(),zs=function(e){m(i,Ss);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching depth fragment shader"),r.push("precision highp float;"),r.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0;n<t.getNumAllocatedSectionPlanes();n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec2 vHighPrecisionZW;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.getNumAllocatedSectionPlanes();s++)r.push(" if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),r.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),r.push("}"),r}}]),i}(),Ws=function(e){m(i,Ss);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry normals fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0;n<t.getNumAllocatedSectionPlanes();n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec3 vViewNormal;"),r.push("vec3 packNormalToRGB( const in vec3 normal ) {"),r.push(" return normalize( normal ) * 0.5 + 0.5;"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.getNumAllocatedSectionPlanes();s++)r.push(" if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),r.push("}"),r}}]),i}(),Xs=function(e){m(i,Ss);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r<e.getNumAllocatedSectionPlanes();r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("in vec4 vViewPosition;"),i.push("vec4 encodeFloat( const in float v ) {"),i.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),i.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),i.push(" vec4 comp = fract(v * bitShift);"),i.push(" comp -= comp.xxyz * bitMask;"),i.push(" return comp;"),i.push("}"),i.push("out vec4 outColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<e.getNumAllocatedSectionPlanes();n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}}]),i}(),Ks=function(e){m(i,Ss);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=e._lightsState,r=t.getNumAllocatedSectionPlanes()>0,n=t.clippingCaps,s=[];return s.push("#version 300 es"),s.push("// Triangles batching quality draw vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in vec2 metallicRoughness;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s,!0),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),s.push("out vec4 vViewPosition;"),s.push("out vec3 vViewNormal;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&s.push("out vec3 vWorldNormal;"),r&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;"),n&&s.push("out vec4 vClipPosition;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("vFragDepth = 1.0 + clipPos.w;")),r&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;"),n&&s.push("vClipPosition = clipPos;")),s.push("vViewPosition = viewPosition;"),s.push("vViewNormal = viewNormal;"),s.push("vColor = color;"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&s.push("vWorldNormal = worldNormal.xyz;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,r=e._lightsState,n=i.getNumAllocatedSectionPlanes()>0,s=i.clippingCaps,o=[];o.push("#version 300 es"),o.push("// Triangles batching quality draw fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),o.push("uniform sampler2D uMetallicRoughMap;"),o.push("uniform sampler2D uEmissiveMap;"),o.push("uniform sampler2D uNormalMap;"),o.push("uniform sampler2D uAOMap;"),o.push("in vec4 vViewPosition;"),o.push("in vec3 vViewNormal;"),o.push("in vec4 vColor;"),o.push("in vec2 vUV;"),o.push("in vec2 vMetallicRoughness;"),r.lightMaps.length>0&&o.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(o,!0),r.reflectionMaps.length>0&&o.push("uniform samplerCube reflectionMap;"),r.lightMaps.length>0&&o.push("uniform samplerCube lightMap;"),o.push("uniform vec4 lightAmbient;");for(var a=0,l=r.lights.length;a<l;a++){var u=r.lights[a];"ambient"!==u.type&&(o.push("uniform vec4 lightColor"+a+";"),"dir"===u.type&&o.push("uniform vec3 lightDir"+a+";"),"point"===u.type&&o.push("uniform vec3 lightPos"+a+";"),"spot"===u.type&&(o.push("uniform vec3 lightPos"+a+";"),o.push("uniform vec3 lightDir"+a+";")))}if(this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),o.push("uniform float gammaFactor;"),o.push("vec4 linearToLinear( in vec4 value ) {"),o.push(" return value;"),o.push("}"),o.push("vec4 sRGBToLinear( in vec4 value ) {"),o.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),o.push("}"),o.push("vec4 gammaToLinear( in vec4 value) {"),o.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),o.push("}"),t&&(o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}")),n){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),s&&o.push("in vec4 vClipPosition;");for(var c=0,A=i.getNumAllocatedSectionPlanes();c<A;c++)o.push("uniform bool sectionPlaneActive"+c+";"),o.push("uniform vec3 sectionPlanePos"+c+";"),o.push("uniform vec3 sectionPlaneDir"+c+";")}if(o.push("#define PI 3.14159265359"),o.push("#define RECIPROCAL_PI 0.31830988618"),o.push("#define RECIPROCAL_PI2 0.15915494"),o.push("#define EPSILON 1e-6"),o.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),o.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),o.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),o.push(" if (texel.x == 0.0 && texel.y == 0.0 && texel.z == 0.0) {"),o.push(" return surf_norm;"),o.push(" }"),o.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),o.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),o.push(" vec2 st0 = dFdx( uv.st );"),o.push(" vec2 st1 = dFdy( uv.st );"),o.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),o.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),o.push(" vec3 N = normalize( surf_norm );"),o.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),o.push(" mat3 tsn = mat3( S, T, N );"),o.push(" return normalize( tsn * mapN );"),o.push("}"),o.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),o.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),o.push("}"),o.push("struct IncidentLight {"),o.push(" vec3 color;"),o.push(" vec3 direction;"),o.push("};"),o.push("struct ReflectedLight {"),o.push(" vec3 diffuse;"),o.push(" vec3 specular;"),o.push("};"),o.push("struct Geometry {"),o.push(" vec3 position;"),o.push(" vec3 viewNormal;"),o.push(" vec3 worldNormal;"),o.push(" vec3 viewEyeDir;"),o.push("};"),o.push("struct Material {"),o.push(" vec3 diffuseColor;"),o.push(" float specularRoughness;"),o.push(" vec3 specularColor;"),o.push(" float shine;"),o.push("};"),o.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),o.push(" float r = ggxRoughness + 0.0001;"),o.push(" return (2.0 / (r * r) - 2.0);"),o.push("}"),o.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),o.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),o.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),o.push("}"),r.reflectionMaps.length>0&&(o.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),o.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),o.push(" return envMapColor;"),o.push("}")),o.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),o.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),o.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),o.push("}"),o.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" return 1.0 / ( gl * gv );"),o.push("}"),o.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" return 0.5 / max( gv + gl, EPSILON );"),o.push("}"),o.push("float D_GGX(const in float alpha, const in float dotNH) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),o.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float alpha = ( roughness * roughness );"),o.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),o.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),o.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),o.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),o.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),o.push(" vec3 F = F_Schlick( specularColor, dotLH );"),o.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),o.push(" float D = D_GGX( alpha, dotNH );"),o.push(" return F * (G * D);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),o.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),o.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),o.push(" vec4 r = roughness * c0 + c1;"),o.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),o.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),o.push(" return specularColor * AB.x + AB.y;"),o.push("}"),(r.lightMaps.length>0||r.reflectionMaps.length>0)&&(o.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),r.lightMaps.length>0&&(o.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),o.push(" irradiance *= PI;"),o.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),r.reflectionMaps.length>0&&(o.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),o.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),o.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),o.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),o.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),o.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),o.push("}")),o.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),o.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),o.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),o.push("}"),o.push("out vec4 outColor;"),o.push("void main(void) {"),n){o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(var h=0,d=i.getNumAllocatedSectionPlanes();h<d;h++)o.push("if (sectionPlaneActive"+h+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+h+".xyz, vWorldPosition.xyz - sectionPlanePos"+h+".xyz), 0.0, 1000.0);"),o.push("}");s?(o.push(" if (dist > (0.002 * vClipPosition.w)) {"),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push(" return;"),o.push("}")):(o.push(" if (dist > 0.0) { "),o.push(" discard;"),o.push(" }")),o.push("}")}o.push("IncidentLight light;"),o.push("Material material;"),o.push("Geometry geometry;"),o.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),o.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),o.push("float opacity = float(vColor.a) / 255.0;"),o.push("vec3 baseColor = rgb;"),o.push("float specularF0 = 1.0;"),o.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),o.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),o.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),o.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),o.push("baseColor *= colorTexel.rgb;"),o.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),o.push("metallic *= metalRoughTexel.b;"),o.push("roughness *= metalRoughTexel.g;"),o.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),o.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),o.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),o.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),o.push("geometry.position = vViewPosition.xyz;"),o.push("geometry.viewNormal = -normalize(viewNormal);"),o.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),r.lightMaps.length>0&&o.push("geometry.worldNormal = normalize(vWorldNormal);"),(r.lightMaps.length>0||r.reflectionMaps.length>0)&&o.push("computePBRLightMapping(geometry, material, reflectedLight);");for(var p=0,f=r.lights.length;p<f;p++){var v=r.lights[p];if("ambient"!==v.type){if("dir"===v.type)"view"===v.space?o.push("light.direction = normalize(lightDir"+p+");"):o.push("light.direction = normalize((viewMatrix * vec4(lightDir"+p+", 0.0)).xyz);");else if("point"===v.type)"view"===v.space?o.push("light.direction = normalize(lightPos"+p+" - vViewPosition.xyz);"):o.push("light.direction = normalize((viewMatrix * vec4(lightPos"+p+", 0.0)).xyz);");else{if("spot"!==v.type)continue;"view"===v.space?o.push("light.direction = normalize(lightDir"+p+");"):o.push("light.direction = normalize((viewMatrix * vec4(lightDir"+p+", 0.0)).xyz);")}o.push("light.color = lightColor"+p+".rgb * lightColor"+p+".a;"),o.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return o.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),o.push("float aoFactor = texture(uAOMap, vUV).r;"),o.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),o.push("vec4 fragColor;"),this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" fragColor = vec4(outgoingLight.rgb * ambient * aoFactor, opacity);")):o.push(" fragColor = vec4(outgoingLight.rgb * aoFactor, opacity);"),t&&o.push("fragColor = linearToGamma(fragColor, gammaFactor);"),o.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}]),i}(),Zs=function(e){m(i,Ss);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching pick flat normals fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("in vec4 vWorldPosition;"),i){r.push("in float vFlags;");for(var n=0;n<t.getNumAllocatedSectionPlanes();n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("out highp ivec4 outNormal;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.getNumAllocatedSectionPlanes();s++)r.push(" if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),r.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),r.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),r.push(" outNormal = ivec4(worldNormal * float(".concat(le.MAX_INT,"), 1.0);")),r.push("}"),r}}]),i}(),Js=function(e){m(i,Ss);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,i=e._lightsState,r=e._sectionPlanesState,n=r.getNumAllocatedSectionPlanes()>0,s=this._useAlphaCutoff,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching color texture fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),o.push("uniform float gammaFactor;"),o.push("vec4 linearToLinear( in vec4 value ) {"),o.push(" return value;"),o.push("}"),o.push("vec4 sRGBToLinear( in vec4 value ) {"),o.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),o.push("}"),o.push("vec4 gammaToLinear( in vec4 value) {"),o.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),o.push("}"),t&&(o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}")),n){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;");for(var a=0,l=r.getNumAllocatedSectionPlanes();a<l;a++)o.push("uniform bool sectionPlaneActive"+a+";"),o.push("uniform vec3 sectionPlanePos"+a+";"),o.push("uniform vec3 sectionPlaneDir"+a+";");o.push("uniform float sliceThickness;"),o.push("uniform vec4 sliceColor;")}this._addMatricesUniformBlockLines(o),o.push("uniform vec4 lightAmbient;");for(var u=0,c=i.lights.length;u<c;u++){var A=i.lights[u];"ambient"!==A.type&&(o.push("uniform vec4 lightColor"+u+";"),"dir"===A.type&&o.push("uniform vec3 lightDir"+u+";"),"point"===A.type&&o.push("uniform vec3 lightPos"+u+";"),"spot"===A.type&&(o.push("uniform vec3 lightPos"+u+";"),o.push("uniform vec3 lightDir"+u+";")))}if(s&&o.push("uniform float materialAlphaCutoff;"),o.push("in vec4 vViewPosition;"),o.push("in vec4 vColor;"),o.push("in vec2 vUV;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),o.push(" vec4 newColor;"),o.push(" newColor = vColor;"),n){o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(var h=0,d=r.getNumAllocatedSectionPlanes();h<d;h++)o.push("if (sectionPlaneActive"+h+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+h+".xyz, vWorldPosition.xyz - sectionPlanePos"+h+".xyz), 0.0, 1000.0);"),o.push("}");o.push(" if (dist > sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;"),o.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),o.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),o.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(var p=0,f=i.lights.length;p<f;p++){var v=i.lights[p];if("ambient"!==v.type){if("dir"===v.type)"view"===v.space?o.push("viewLightDir = normalize(lightDir"+p+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+p+", 0.0)).xyz);");else if("point"===v.type)"view"===v.space?o.push("viewLightDir = -normalize(lightPos"+p+" - vViewPosition.xyz);"):o.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+p+", 0.0)).xyz);");else{if("spot"!==v.type)continue;"view"===v.space?o.push("viewLightDir = normalize(lightDir"+p+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+p+", 0.0)).xyz);")}o.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),o.push("reflectedColor += lambertian * (lightColor"+p+".rgb * lightColor"+p+".a);")}}return o.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.a);"),o.push("vec4 sampleColor = texture(uColorMap, vUV);"),s&&(o.push("if (sampleColor.a < materialAlphaCutoff) {"),o.push(" discard;"),o.push("}")),t&&o.push("sampleColor = sRGBToLinear(sampleColor);"),o.push("vec4 colorTexel = color * sampleColor;"),o.push("float opacity = color.a;"),this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" outColor = vec4(colorTexel.rgb * ambient, opacity);")):o.push(" outColor = vec4(colorTexel.rgb, opacity);"),t&&o.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}]),i}(),Ys=le.vec3(),qs=le.vec3(),$s=le.vec3(),eo=le.vec3(),to=le.mat4(),io=function(e){m(i,Ds);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,n=r.scene,s=n.camera,o=n.canvas.gl,a=t._state,l=t._state.origin,u=r.position,c=r.rotationMatrix,A=t.aabb,h=e.pickViewMatrix||s.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var d,p,f=Ys;if(f[0]=le.safeInv(A[3]-A[0])*le.MAX_INT,f[1]=le.safeInv(A[4]-A[1])*le.MAX_INT,f[2]=le.safeInv(A[5]-A[2])*le.MAX_INT,e.snapPickCoordinateScale[0]=le.safeInv(f[0]),e.snapPickCoordinateScale[1]=le.safeInv(f[1]),e.snapPickCoordinateScale[2]=le.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=qs;if(l){var g=$s;le.transformPoint3(c,l,g),v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],d=Jt(h,v,to),(p=eo)[0]=s.eye[0]-v[0],p[1]=s.eye[1]-v[1],p[2]=s.eye[2]-v[2],e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else d=h,p=s.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,p),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(d,m+=16),this._matricesUniformBlockBufferData.set(s.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),o.drawElements(o.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind(),o.bindVertexArray(null)}}},{key:"_allocate",value:function(){v(x(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var r=0;r<e.getNumAllocatedSectionPlanes();r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<e.getNumAllocatedSectionPlanes();n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat(le.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),ro=le.vec3(),no=le.vec3(),so=le.vec3(),oo=le.vec3(),ao=le.mat4(),lo=function(e){m(i,Ds);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,n=r.scene,s=n.camera,o=n.canvas.gl,a=t._state,l=t._state.origin,u=r.position,c=r.rotationMatrix,A=t.aabb,h=e.pickViewMatrix||s.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var d,p,f=ro;if(f[0]=le.safeInv(A[3]-A[0])*le.MAX_INT,f[1]=le.safeInv(A[4]-A[1])*le.MAX_INT,f[2]=le.safeInv(A[5]-A[2])*le.MAX_INT,e.snapPickCoordinateScale[0]=le.safeInv(f[0]),e.snapPickCoordinateScale[1]=le.safeInv(f[1]),e.snapPickCoordinateScale[2]=le.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=no;if(l){var g=so;le.transformPoint3(c,l,g),v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],d=Jt(h,v,ao),(p=oo)[0]=s.eye[0]-v[0],p[1]=s.eye[1]-v[1],p[2]=s.eye[2]-v[2],e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else d=h,p=s.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,p),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(d,m+=16),this._matricesUniformBlockBufferData.set(s.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?a.edgeIndicesBuf&&(a.edgeIndicesBuf.bind(),o.drawElements(o.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):o.drawArrays(o.POINTS,0,a.positionsBuf.numItems),o.bindVertexArray(null)}}},{key:"_allocate",value:function(){v(x(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;var i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r<e.getNumAllocatedSectionPlanes();r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<e.getNumAllocatedSectionPlanes();n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),uo=function(){function e(t){E(this,e),this._scene=t}return I(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._colorTextureRendererAlphaCutoff&&!this._colorTextureRendererAlphaCutoff.getValid()&&(this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererAlphaCutoff=null),this._colorTextureRendererWithSAOAlphaCutoff&&!this._colorTextureRendererWithSAOAlphaCutoff.getValid()&&(this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._silhouetteRenderer||(this._silhouetteRenderer=new Ls(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Qs(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Hs(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new io(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new lo(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Rs(this._scene,!1)),this._colorRenderer}},{key:"colorRendererWithSAO",get:function(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Rs(this._scene,!0)),this._colorRendererWithSAO}},{key:"flatColorRenderer",get:function(){return this._flatColorRenderer||(this._flatColorRenderer=new Us(this._scene,!1)),this._flatColorRenderer}},{key:"flatColorRendererWithSAO",get:function(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Us(this._scene,!0)),this._flatColorRendererWithSAO}},{key:"colorTextureRenderer",get:function(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Js(this._scene,!1)),this._colorTextureRenderer}},{key:"colorTextureRendererWithSAO",get:function(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Js(this._scene,!0)),this._colorTextureRendererWithSAO}},{key:"colorTextureRendererAlphaCutoff",get:function(){return this._colorTextureRendererAlphaCutoff||(this._colorTextureRendererAlphaCutoff=new Js(this._scene,!1,{useAlphaCutoff:!0})),this._colorTextureRendererAlphaCutoff}},{key:"colorTextureRendererWithSAOAlphaCutoff",get:function(){return this._colorTextureRendererWithSAOAlphaCutoff||(this._colorTextureRendererWithSAOAlphaCutoff=new Js(this._scene,!0,{useAlphaCutoff:!0})),this._colorTextureRendererWithSAOAlphaCutoff}},{key:"pbrRenderer",get:function(){return this._pbrRenderer||(this._pbrRenderer=new Ks(this._scene,!1)),this._pbrRenderer}},{key:"pbrRendererWithSAO",get:function(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Ks(this._scene,!0)),this._pbrRendererWithSAO}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ls(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new zs(this._scene)),this._depthRenderer}},{key:"normalsRenderer",get:function(){return this._normalsRenderer||(this._normalsRenderer=new Ws(this._scene)),this._normalsRenderer}},{key:"edgesRenderer",get:function(){return this._edgesRenderer||(this._edgesRenderer=new Ns(this._scene)),this._edgesRenderer}},{key:"edgesColorRenderer",get:function(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Vs(this._scene)),this._edgesColorRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Qs(this._scene)),this._pickMeshRenderer}},{key:"pickNormalsRenderer",get:function(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new js(this._scene)),this._pickNormalsRenderer}},{key:"pickNormalsFlatRenderer",get:function(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Zs(this._scene)),this._pickNormalsFlatRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Hs(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new Gs(this._scene)),this._occlusionRenderer}},{key:"shadowRenderer",get:function(){return this._shadowRenderer||(this._shadowRenderer=new Xs(this._scene)),this._shadowRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new lo(this._scene)),this._snapRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new io(this._scene)),this._snapInitRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererAlphaCutoff&&this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff&&this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),co={};var Ao=65536,ho=5e6,po=function(){function e(){E(this,e)}return I(e,[{key:"doublePrecisionEnabled",get:function(){return le.getDoublePrecisionEnabled()},set:function(e){le.setDoublePrecisionEnabled(e)}},{key:"maxDataTextureHeight",get:function(){return Ao},set:function(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),Ao=e}},{key:"maxGeometryBatchSize",get:function(){return ho},set:function(e){e<1e5?e=1e5:e>5e6&&(e=5e6),ho=e}}]),e}(),fo=new po,vo=I((function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:fo.maxGeometryBatchSize;E(this,e),this.maxVerts=t,this.maxIndices=3*t,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]})),go=le.mat4(),mo=le.mat4();function _o(e,t,i){for(var r=e.length,n=new Uint16Array(r),s=t[0],o=t[1],a=t[2],l=t[3]-s,u=t[4]-o,c=t[5]-a,A=65525,h=A/l,d=A/u,p=A/c,f=function(e){return e>=0?e:0},v=0;v<r;v+=3)n[v+0]=Math.floor(f(e[v+0]-s)*h),n[v+1]=Math.floor(f(e[v+1]-o)*d),n[v+2]=Math.floor(f(e[v+2]-a)*p);return le.identityMat4(go),le.translationMat4v(t,go),le.identityMat4(mo),le.scalingMat4v([l/A,u/A,c/A],mo),le.mulMat4(go,mo,i),n}function yo(e,t){var i=e[0],r=e[1],n=e[2],s=e[3]-i,o=e[4]-r,a=e[5]-n,l=65525;return le.identityMat4(go),le.translationMat4v(e,go),le.identityMat4(mo),le.scalingMat4v([s/l,o/l,a/l],mo),le.mulMat4(go,mo,t),t}function bo(e,t,i){var r=e[0]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2])),n=e[1]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2]));if(e[2]<0){var s,o;s=(1-Math.abs(n))*(r>=0?1:-1),o=(1-Math.abs(r))*(n>=0?1:-1),r=s,n=o}return new Int8Array([Math[t](127.5*r+(r<0?-1:0)),Math[i](127.5*n+(n<0?-1:0))])}function wo(e){var t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;var r=1-Math.abs(t)-Math.abs(i);r<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));var n=Math.sqrt(t*t+i*i+r*r);return[t/n,i/n,r/n]}var Bo=le.mat4(),xo=le.mat4(),Po=le.vec4([0,0,0,1]),Co=le.vec3(),Mo=le.vec3(),ko=le.vec3(),Eo=le.vec3(),Fo=le.vec3(),Io=le.vec3(),To=le.vec3(),Do=function(){function e(t){E(this,e),this.model=t.model,this.sortId="TrianglesBatchingLayer"+(t.solid?"-solid":"-surface")+(t.autoNormals?"-autonormals":"-normals")+(t.textureSet&&t.textureSet.colorTexture?"-colorTexture":"")+(t.textureSet&&t.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=t.layerIndex,this._renderers=function(e){var t=e.id,i=co[t];return i||(i=new uo(e),co[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(function(){i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(function(){delete co[t],i._destroy()}))),i}(t.model.scene),this._buffer=new vo(t.maxGeometryBatchSize),this._scratchMemory=t.scratchMemory,this._state=new nt({origin:le.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:t.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=le.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=le.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,t.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=le.mat4(t.positionsDecodeMatrix)),t.uvDecodeMatrix?(this._state.uvDecodeMatrix=le.mat3(t.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,t.origin&&this._state.origin.set(t.origin),this.solid=!!t.solid,this.primitive=t.primitive}return I(e,[{key:"aabb",get:function(){if(this.aabbDirty){le.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e<t;e++)le.expandAABB3(this._aabb,this._meshes[e].aabb);this.aabbDirty=!1}return this._aabb}},{key:"canCreatePortion",value:function(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}},{key:"createPortion",value:function(e,t){if(this._finalized)throw"Already finalized";var i,r=t.positions,n=t.positionsCompressed,s=t.normals,o=t.normalsCompressed,a=t.uv,l=t.uvCompressed,u=t.colors,c=t.colorsCompressed,A=t.indices,h=t.edgeIndices,d=t.color,p=t.metallic,f=t.roughness,v=t.opacity,g=t.meshMatrix,m=t.pickColor,_=this.model.scene,y=this._buffer,b=y.positions.length/3;if(le.expandAABB3(this._modelAABB,t.aabb),this._state.positionsDecodeMatrix){if(!n)throw"positionsCompressed expected";i=n.length/3;for(var w=0,B=n.length;w<B;w++)y.positions.push(n[w])}else{if(!r)throw"positions expected";i=r.length/3;for(var x=0,P=r.length;x<P;x++)y.positions.push(r[x])}if(o&&o.length>0)for(var C=0,M=o.length;C<M;C++)y.normals.push(o[C]);else if(s&&s.length>0){var k=Bo;g?le.inverseMat4(le.transposeMat4(g,xo),k):le.identityMat4(k,k),function(e,t,i,r,n){function s(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}var o,a,l,u,c,A=new Float32Array([0,0,0,0]),h=new Float32Array([0,0,0,0]);for(c=0;c<i;c+=3)A[0]=t[c],A[1]=t[c+1],A[2]=t[c+2],le.transformVec3(e,A,h),le.normalizeVec3(h,h),a=o=bo(h,"floor","floor"),l=u=s(h,wo(o)),(l=s(h,wo(o=bo(h,"ceil","floor"))))>u&&(a=o,u=l),(l=s(h,wo(o=bo(h,"floor","ceil"))))>u&&(a=o,u=l),(l=s(h,wo(o=bo(h,"ceil","ceil"))))>u&&(a=o,u=l),r[n+c+0]=a[0],r[n+c+1]=a[1],r[n+c+2]=0}(k,s,s.length,y.normals,y.normals.length)}if(u)for(var E=0,F=u.length;E<F;E+=3)y.colors.push(255*u[E]),y.colors.push(255*u[E+1]),y.colors.push(255*u[E+2]),y.colors.push(255);else if(c)for(var I=0,T=u.length;I<T;I+=3)y.colors.push(u[I]),y.colors.push(u[I+1]),y.colors.push(u[I+2]),y.colors.push(255);else if(d)for(var D=d[0],S=d[1],R=d[2],U=v,L=0;L<i;L++)y.colors.push(D),y.colors.push(S),y.colors.push(R),y.colors.push(U);for(var O=null!=p?p:0,N=null!=f?f:255,V=0;V<i;V++)y.metallicRoughness.push(O),y.metallicRoughness.push(N);if(a&&a.length>0)for(var Q=0,H=a.length;Q<H;Q++)y.uv.push(a[Q]);else if(l&&l.length>0)for(var j=0,G=l.length;j<G;j++)y.uv.push(l[j]);for(var z=0,W=A.length;z<W;z++)y.indices.push(b+A[z]);if(h)for(var X=0,K=h.length;X<K;X++)y.edgeIndices.push(b+h[X]);for(var Z=y.pickColors.length,J=Z,Y=Z+4*i;J<Y;J+=4)y.pickColors.push(m[0]),y.pickColors.push(m[1]),y.pickColors.push(m[2]),y.pickColors.push(m[3]);if(_.entityOffsetsEnabled)for(var q=0;q<i;q++)y.offsets.push(0),y.offsets.push(0),y.offsets.push(0);var $=this._portions.length,ee={vertsBaseIndex:b,numVerts:i,indicesBaseIndex:y.indices.length-A.length,numIndices:A.length};return _.readableGeometryEnabled&&(ee.indices=A,_.entityOffsetsEnabled&&(ee.offset=new Float32Array(3))),this._portions.push(ee),this._numPortions++,this.model.numPortions++,this._numVerts+=ee.numVerts,this._meshes.push(e),$}},{key:"finalize",value:function(){if(!this._finalized){var e=this._state,t=this.model.scene.canvas.gl,i=this._buffer;if(i.positions.length>0){var r=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):_o(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=le.mat4());if(e.positionsBuf=new st(t,t.ARRAY_BUFFER,r,r.length,3,t.STATIC_DRAW),this.model.scene.readableGeometryEnabled)for(var n=0,s=this._portions.length;n<s;n++){var o=this._portions[n],a=3*o.vertsBaseIndex,l=a+3*o.numVerts;o.quantizedPositions=r.slice(a,l)}}if(i.normals.length>0){var u=new Int8Array(i.normals);e.normalsBuf=new st(t,t.ARRAY_BUFFER,u,i.normals.length,3,t.STATIC_DRAW,!0)}if(i.colors.length>0){var c=new Uint8Array(i.colors);e.colorsBuf=new st(t,t.ARRAY_BUFFER,c,i.colors.length,4,t.DYNAMIC_DRAW,!1)}if(i.uv.length>0)if(e.uvDecodeMatrix){e.uvBuf=new st(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,!1)}else{var A=ft.getUVBounds(i.uv),h=ft.compressUVs(i.uv,A.min,A.max),d=h.quantized;e.uvDecodeMatrix=le.mat3(h.decodeMatrix),e.uvBuf=new st(t,t.ARRAY_BUFFER,d,d.length,2,t.STATIC_DRAW,!1)}if(i.metallicRoughness.length>0){var p=new Uint8Array(i.metallicRoughness);e.metallicRoughnessBuf=new st(t,t.ARRAY_BUFFER,p,i.metallicRoughness.length,2,t.STATIC_DRAW,!1)}if(i.positions.length>0){var f=i.positions.length/3,v=new Float32Array(f);e.flagsBuf=new st(t,t.ARRAY_BUFFER,v,v.length,1,t.DYNAMIC_DRAW,!1)}if(i.pickColors.length>0){var g=new Uint8Array(i.pickColors);e.pickColorsBuf=new st(t,t.ARRAY_BUFFER,g,i.pickColors.length,4,t.STATIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){var m=new Float32Array(i.offsets);e.offsetsBuf=new st(t,t.ARRAY_BUFFER,m,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){var _=new Uint32Array(i.indices);e.indicesBuf=new st(t,t.ELEMENT_ARRAY_BUFFER,_,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){var y=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new st(t,t.ELEMENT_ARRAY_BUFFER,y,i.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}}},{key:"isEmpty",value:function(){return!this._state.indicesBuf}},{key:"initFlags",value:function(e,t,i){t&gs&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Bs&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ws&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&xs&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ys&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Ps&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&_s&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ms&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&gs?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Bs?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ws?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&xs?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ps?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&ys?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ms?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&_s?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";for(var i=e,r=this._portions[i],n=4*r.vertsBaseIndex,s=4*r.numVerts,o=this._scratchMemory.getUInt8Array(s),a=t[0],l=t[1],u=t[2],c=t[3],A=0;A<s;A+=4)o[A+0]=a,o[A+1]=l,o[A+2]=u,o[A+3]=c;this._state.colorsBuf&&this._state.colorsBuf.setData(o,n,s)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var n,s,o=e,a=this._portions[o],l=a.vertsBaseIndex,u=a.numVerts,c=l,A=u,h=!!(t&gs),d=!!(t&ws),p=!!(t&Bs),f=!!(t&xs),v=!!(t&Ps),g=!!(t&_s),m=!!(t&ms);n=!h||m||d||p&&!this.model.scene.highlightMaterial.glowThrough||f&&!this.model.scene.selectedMaterial.glowThrough?Cs.NOT_RENDERED:i?Cs.COLOR_TRANSPARENT:Cs.COLOR_OPAQUE,s=!h||m?Cs.NOT_RENDERED:f?Cs.SILHOUETTE_SELECTED:p?Cs.SILHOUETTE_HIGHLIGHTED:d?Cs.SILHOUETTE_XRAYED:Cs.NOT_RENDERED;var _=0;_=!h||m?Cs.NOT_RENDERED:f?Cs.EDGES_SELECTED:p?Cs.EDGES_HIGHLIGHTED:d?Cs.EDGES_XRAYED:v?i?Cs.EDGES_COLOR_TRANSPARENT:Cs.EDGES_COLOR_OPAQUE:Cs.NOT_RENDERED;var y=h&&!m&&g?Cs.PICK:Cs.NOT_RENDERED,b=t&ys?1:0;if(r){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(var w=c,B=c+A;w<B;w++){var x=0;x|=n,x|=s<<4,x|=_<<8,x|=y<<12,x|=b<<16,this._deferredFlagValues[w]=x}}else if(this._state.flagsBuf){for(var P=this._scratchMemory.getFloat32Array(A),C=0;C<A;C++){var M=0;M|=n,M|=s<<4,M|=_<<8,M|=y<<12,M|=b<<16,P[C]=M}this._state.flagsBuf.setData(P,c,A)}}},{key:"_setDeferredFlags",value:function(){this._deferredFlagValues&&(this._state.flagsBuf.setData(this._deferredFlagValues),this._deferredFlagValues=null)}},{key:"setOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";if(this.model.scene.entityOffsetsEnabled){for(var i=e,r=this._portions[i],n=3*r.vertsBaseIndex,s=3*r.numVerts,o=this._scratchMemory.getFloat32Array(s),a=t[0],l=t[1],u=t[2],c=0;c<s;c+=3)o[c+0]=a,o[c+1]=l,o[c+2]=u;this._state.offsetsBuf&&this._state.offsetsBuf.setData(o,n,s),this.model.scene.readableGeometryEnabled&&(r.offset[0]=t[0],r.offset[1]=t[1],r.offset[2]=t[2])}else this.model.error("Entity#offset not enabled for this Viewer")}},{key:"getEachVertex",value:function(e,t){if(this.model.scene.readableGeometryEnabled){var i=this._state,r=this._portions[e];if(r){var n=r.quantizedPositions,s=this.model.matrix,o=le.vec4();o.set(i.origin,0),o[3]=1,le.mulMat4v4(s,o,o);for(var a=o[0],l=o[1],u=o[2],c=Po,A=i.positionsDecodeMatrix,h=0,d=n.length;h<d;h+=3)c[0]=n[h],c[1]=n[h+1],c[2]=n[h+2],c[3]=1,le.decompressPosition(c,A),c[3]=1,le.mulMat4v4(s,c,c),c[0]+=a,c[1]+=l,c[2]+=u,t(c)}else this.model.error("portion not found: "+e)}}},{key:"getEachIndex",value:function(e,t){if(this.model.scene.readableGeometryEnabled){var i=this._portions[e];if(i)for(var r=i.indices,n=0,s=r.length;n<s;n++)t(r[n]);else this.model.error("portion not found: "+e)}}},{key:"getElementsCountAndOffset",value:function(e){var t=null,i=null,r=this._portions[e];return r&&(t=r.numIndices,i=r.indicesBaseIndex),{count:t,offset:i}}},{key:"readGeometryData",value:function(e){if(!this._finalized)throw"Not finalized";var t=this._portions[e],i=this._state,r=this.model.matrix,n=i.positionsDecodeMatrix,s=le.vec4();s.set(i.origin,0),s[3]=1,le.mulMat4v4(r,s,s);var o=i.indicesBuf.getData(t.indicesBaseIndex,t.numIndices).map((function(e){return e-t.vertsBaseIndex})),a=le.mulMat4(r,n,new Array(16));a[12]+=s[0],a[13]+=s[1],a[14]+=s[2];var l=i.positionsBuf.getData(t.vertsBaseIndex,t.numVerts);return{indices:o,positions:le.transformPositions3(a,l,new Array(l.length))}}},{key:"drawColorOpaque",value:function(e,t){if(this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions){this._updateBackfaceCull(e,t);var i=this._state.textureSet&&"number"==typeof this._state.textureSet.alphaCutoff;t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._renderers.pbrRendererWithSAO&&this._renderers.pbrRendererWithSAO.drawLayer(t,this,Cs.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?i?this._renderers.colorTextureRendererWithSAOAlphaCutoff&&this._renderers.colorTextureRendererWithSAOAlphaCutoff.drawLayer(t,this,Cs.COLOR_OPAQUE):this._renderers.colorTextureRendererWithSAO&&this._renderers.colorTextureRendererWithSAO.drawLayer(t,this,Cs.COLOR_OPAQUE):this._state.normalsBuf?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,Cs.COLOR_OPAQUE):this._renderers.flatColorRendererWithSAO&&this._renderers.flatColorRendererWithSAO.drawLayer(t,this,Cs.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._renderers.pbrRenderer&&this._renderers.pbrRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?i?this._renderers.colorTextureRendererAlphaCutoff&&this._renderers.colorTextureRendererAlphaCutoff.drawLayer(t,this,Cs.COLOR_OPAQUE):this._renderers.colorTextureRenderer&&this._renderers.colorTextureRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE):this._state.normalsBuf?this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE):this._renderers.flatColorRenderer&&this._renderers.flatColorRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE)}}},{key:"_updateBackfaceCull",value:function(e,t){if(true!==t.backfaces){var i=t.gl;i.disable(i.CULL_FACE),t.backfaces=true}}},{key:"drawColorTransparent",value:function(e,t){if(this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions)if(this._updateBackfaceCull(e,t),t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported)this._renderers.pbrRenderer&&this._renderers.pbrRenderer.drawLayer(t,this,Cs.COLOR_TRANSPARENT);else if(t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported){this._state.textureSet&&"number"==typeof this._state.textureSet.alphaCutoff?this._renderers.colorTextureRendererAlphaCutoff&&this._renderers.colorTextureRendererAlphaCutoff.drawLayer(t,this,Cs.COLOR_TRANSPARENT):this._renderers.colorTextureRenderer&&this._renderers.colorTextureRenderer.drawLayer(t,this,Cs.COLOR_TRANSPARENT)}else this._state.normalsBuf?this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Cs.COLOR_TRANSPARENT):this._renderers.flatColorRenderer&&this._renderers.flatColorRenderer.drawLayer(t,this,Cs.COLOR_TRANSPARENT)}},{key:"drawDepth",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE))}},{key:"drawNormals",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE))}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_XRAYED))}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_HIGHLIGHTED))}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_SELECTED))}},{key:"drawEdgesColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Cs.EDGES_COLOR_OPAQUE)}},{key:"drawEdgesColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Cs.EDGES_COLOR_TRANSPARENT)}},{key:"drawEdgesHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Cs.EDGES_HIGHLIGHTED)}},{key:"drawEdgesSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Cs.EDGES_SELECTED)}},{key:"drawEdgesXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Cs.EDGES_XRAYED)}},{key:"drawOcclusion",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE))}},{key:"drawShadow",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE))}},{key:"drawPickMesh",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Cs.PICK))}},{key:"drawPickDepths",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Cs.PICK))}},{key:"drawPickNormals",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsFlatRenderer&&this._renderers.pickNormalsFlatRenderer.drawLayer(t,this,Cs.PICK))}},{key:"drawSnapInit",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Cs.PICK))}},{key:"drawSnap",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Cs.PICK))}},{key:"precisionRayPickSurface",value:function(e,t,i,r,n){if(!this.model.scene.readableGeometryEnabled)return!1;var s=this._state,o=this._portions[e];if(!o)return this.model.error("portion not found: "+e),!1;var a=o.quantizedPositions,l=o.indices,u=s.origin,c=o.offset,A=Co,h=Mo;A.set(u?le.subVec3(t,u,ko):t),h.set(i),c&&le.subVec3(A,c),le.transformRay(this.model.worldNormalMatrix,A,h,A,h);for(var d=Eo,p=Fo,f=Io,v=!1,g=0,m=To,_=0,y=l.length;_<y;_+=3){var b=3*l[_],w=3*l[_+1],B=3*l[_+2];if(d[0]=a[b],d[1]=a[b+1],d[2]=a[b+2],p[0]=a[w],p[1]=a[w+1],p[2]=a[w+2],f[0]=a[B],f[1]=a[B+1],f[2]=a[B+2],le.decompressPosition(d,s.positionsDecodeMatrix),le.decompressPosition(p,s.positionsDecodeMatrix),le.decompressPosition(f,s.positionsDecodeMatrix),le.rayTriangleIntersect(A,h,d,p,f,m)){le.transformPoint3(this.model.worldMatrix,m,m),c&&le.addVec3(m,c),u&&le.addVec3(m,u);var x=Math.abs(le.lenVec3(le.subVec3(m,t,[])));(!v||x>g)&&(g=x,r.set(m),n&&le.triangleNormal(d,p,f,n),v=!0)}}return v&&n&&(le.transformVec3(this.model.worldNormalMatrix,n,n),le.normalizeVec3(n)),v}},{key:"destroy",value:function(){var e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}]),e}(),So=function(e){m(i,Ds);var t=y(i);function i(e,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=n.edges,o=void 0!==s&&s,a=n.useAlphaCutoff,l=void 0!==a&&a;return E(this,i),t.call(this,e,r,{instancing:!0,edges:o,useAlphaCutoff:l})}return I(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,r=e.frameCtx,n=e.incrementDrawState;this._edges?i.edgeIndicesBuf&&t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),n&&r.drawElements++)}}]),i}(),Ro=function(e){m(i,So);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e,t,i,r=this._scene,n=r._sectionPlanesState,s=r._lightsState,o=n.getNumAllocatedSectionPlanes()>0,a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),r.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),r.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;"),e=0,t=s.lights.length;e<t;e++)"ambient"!==(i=s.lights[e]).type&&(a.push("uniform vec4 lightColor"+e+";"),"dir"===i.type&&a.push("uniform vec3 lightDir"+e+";"),"point"===i.type&&a.push("uniform vec3 lightPos"+e+";"),"spot"===i.type&&(a.push("uniform vec3 lightPos"+e+";"),a.push("uniform vec3 lightDir"+e+";")));for(a.push("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),o&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),r.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),e=0,t=s.lights.length;e<t;e++)if("ambient"!==(i=s.lights[e]).type){if("dir"===i.type)"view"===i.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===i.type)"view"===i.space?a.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):a.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==i.type)continue;"view"===i.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}a.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),a.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}return a.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));"),a.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),a.push("vec4 clipPos = projMatrix * viewPosition;"),r.logarithmicDepthBufferEnabled&&(a.push("vFragDepth = 1.0 + clipPos.w;"),a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),o&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags = flags;")),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Instancing geometry drawing fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0,s=t.getNumAllocatedSectionPlanes();n<s;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";");r.push("uniform float sliceThickness;"),r.push("uniform vec4 sliceColor;")}if(r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),r.push(" vec4 newColor;"),r.push(" newColor = vColor;"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o<a;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > sliceThickness) { "),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" newColor = sliceColor;"),r.push(" }"),r.push("}")}return e.logarithmicDepthBufferEnabled?(r.push(" float dx = dFdx(vFragDepth);"),r.push(" float dy = dFdy(vFragDepth);"),r.push(" float diff = sqrt(dx*dx+dy*dy);"),r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;")):(r.push(" float dx = dFdx(gl_FragCoord.z);"),r.push(" float dy = dFdy(gl_FragCoord.z);"),r.push(" float diff = sqrt(dx*dx+dy*dy);"),r.push(" gl_FragDepth = gl_FragCoord.z + diff;")),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):r.push(" outColor = newColor;"),r.push("}"),r}}]),i}(),Uo=function(e){m(i,So);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,r=i._sectionPlanesState,n=i._lightsState,s=r.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry flat-shading drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),i.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),s){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;");for(var a=0,l=r.getNumAllocatedSectionPlanes();a<l;a++)o.push("uniform bool sectionPlaneActive"+a+";"),o.push("uniform vec3 sectionPlanePos"+a+";"),o.push("uniform vec3 sectionPlaneDir"+a+";");o.push("uniform float sliceThickness;"),o.push("uniform vec4 sliceColor;")}for(this._addMatricesUniformBlockLines(o),o.push("uniform vec4 lightAmbient;"),e=0,t=n.lights.length;e<t;e++){var u=n.lights[e];"ambient"!==u.type&&(o.push("uniform vec4 lightColor"+e+";"),"dir"===u.type&&o.push("uniform vec3 lightDir"+e+";"),"point"===u.type&&o.push("uniform vec3 lightPos"+e+";"),"spot"===u.type&&(o.push("uniform vec3 lightPos"+e+";"),o.push("uniform vec3 lightDir"+e+";")))}if(o.push("in vec4 vViewPosition;"),o.push("in vec4 vColor;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),o.push(" vec4 newColor;"),o.push(" newColor = vColor;"),s){o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(var c=0,A=r.getNumAllocatedSectionPlanes();c<A;c++)o.push("if (sectionPlaneActive"+c+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+c+".xyz, vWorldPosition.xyz - sectionPlanePos"+c+".xyz), 0.0, 1000.0);"),o.push("}");o.push(" if (dist > sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}for(o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;"),o.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),o.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),o.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),e=0,t=n.lights.length;e<t;e++){var h=n.lights[e];if("ambient"!==h.type){if("dir"===h.type)"view"===h.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===h.type)"view"===h.space?o.push("viewLightDir = -normalize(lightPos"+e+" - vViewPosition.xyz);"):o.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==h.type)continue;"view"===h.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}o.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),o.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return o.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.a);"),this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" outColor = vec4(fragColor.rgb * ambient, 1.0);")):o.push(" outColor = fragColor;"),i.logarithmicDepthBufferEnabled?o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"):(o.push(" float dx = dFdx(gl_FragCoord.z);"),o.push(" float dy = dFdy(gl_FragCoord.z);"),o.push(" float diff = sqrt(dx*dx+dy*dy);"),o.push(" gl_FragDepth = gl_FragCoord.z + diff;")),o.push("}"),o}}]),i}(),Lo=function(e){m(i,So);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Instancing fill fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0,s=t.getNumAllocatedSectionPlanes();n<s;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";");r.push("uniform float sliceThickness;"),r.push("uniform vec4 sliceColor;")}if(r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),r.push(" vec4 newColor;"),r.push(" newColor = vColor;"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o<a;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > sliceThickness) { "),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" newColor = sliceColor;"),r.push(" }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = newColor;"),r.push("}"),r}}]),i}(),Oo=function(e){m(i,So);var t=y(i);function i(e,r){return E(this,i),t.call(this,e,r,{instancing:!0,edges:!0})}return I(i)}(),No=function(e){m(i,Oo);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// EdgesEmphasisRenderer fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0,s=t.getNumAllocatedSectionPlanes();n<s;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o<a;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = vColor;"),r.push("}"),r}}]),i}(),Vo=function(e){m(i,Oo);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{colorUniform:!1})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// EdgesColorRenderer fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0,s=t.getNumAllocatedSectionPlanes();n<s;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o<a;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = vColor;"),r.push("}"),r}}]),i}(),Qo=function(e){m(i,So);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0;n<t.getNumAllocatedSectionPlanes();n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec4 vPickColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.getNumAllocatedSectionPlanes();s++)r.push("if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push("}");r.push("if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = vPickColor; "),r.push("}"),r}}]),i}(),Ho=function(e){m(i,So);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry depth fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform float pickZNear;"),r.push("uniform float pickZFar;"),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0;n<t.getNumAllocatedSectionPlanes();n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec4 vViewPosition;"),r.push("vec4 packDepth(const in float depth) {"),r.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),r.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),r.push(" vec4 res = fract(depth * bitShift);"),r.push(" res -= res.xxyz * bitMask;"),r.push(" return res;"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.getNumAllocatedSectionPlanes();s++)r.push("if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push("}");r.push("if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),r.push(" outColor = packDepth(zNormalizedDepth); "),r.push("}"),r}}]),i}(),jo=function(e){m(i,So);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry normals fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0;n<t.getNumAllocatedSectionPlanes();n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec3 vWorldNormal;"),r.push("out highp ivec4 outNormal;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.getNumAllocatedSectionPlanes();s++)r.push("if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push("}");r.push("if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outNormal = ivec4(vWorldNormal * float(".concat(le.MAX_INT,"), 1.0);")),r.push("}"),r}}]),i}(),Go=function(e){m(i,So);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r<e.getNumAllocatedSectionPlanes();r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<e.getNumAllocatedSectionPlanes();n++)i.push("if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}]),i}(),zo=function(e){m(i,So);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,r=i._sectionPlanesState,n=r.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("precision highp float;"),s.push("precision highp int;"),i.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),n)for(s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;"),e=0,t=r.getNumAllocatedSectionPlanes();e<t;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";");if(s.push("in vec2 vHighPrecisionZW;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),n){for(s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;"),e=0,t=r.getNumAllocatedSectionPlanes();e<t;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return i.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}}]),i}(),Wo=function(e){m(i,So);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Instancing geometry depth drawing fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0,s=t.getNumAllocatedSectionPlanes();n<s;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec3 vViewNormal;"),r.push("vec3 packNormalToRGB( const in vec3 normal ) {"),r.push(" return normalize( normal ) * 0.5 + 0.5;"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o<a;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push("if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),r.push("}"),r}}]),i}(),Xo=function(e){m(i,So);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Instancing geometry depth drawing fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0,s=t.getNumAllocatedSectionPlanes();n<s;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec3 vViewNormal;"),r.push("vec3 packNormalToRGB( const in vec3 normal ) {"),r.push(" return normalize( normal ) * 0.5 + 0.5;"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o<a;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push("if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),r.push("}"),r}}]),i}(),Ko={3e3:"linearToLinear",3001:"sRGBToLinear"},Zo=function(e){m(i,So);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=e._lightsState,r=t.getNumAllocatedSectionPlanes()>0,n=t.clippingCaps,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry quality drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in vec2 metallicRoughness;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("in vec4 modelNormalMatrixCol0;"),s.push("in vec4 modelNormalMatrixCol1;"),s.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(s,!0),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),s.push("out vec4 vViewPosition;"),s.push("out vec3 vViewNormal;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&s.push("out vec3 vWorldNormal;"),r&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;"),n&&s.push("out vec4 vClipPosition;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),s.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),s.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),r&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;"),n&&s.push("vClipPosition = clipPos;")),s.push("vViewPosition = viewPosition;"),s.push("vViewNormal = viewNormal;"),s.push("vColor = color;"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&s.push("vWorldNormal = worldNormal.xyz;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,r=e._lightsState,n=i.getNumAllocatedSectionPlanes()>0,s=i.clippingCaps,o=[];o.push("#version 300 es"),o.push("// Instancing geometry quality drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),o.push("uniform sampler2D uMetallicRoughMap;"),o.push("uniform sampler2D uEmissiveMap;"),o.push("uniform sampler2D uNormalMap;"),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),r.reflectionMaps.length>0&&o.push("uniform samplerCube reflectionMap;"),r.lightMaps.length>0&&o.push("uniform samplerCube lightMap;"),o.push("uniform vec4 lightAmbient;");for(var a=0,l=r.lights.length;a<l;a++){var u=r.lights[a];"ambient"!==u.type&&(o.push("uniform vec4 lightColor"+a+";"),"dir"===u.type&&o.push("uniform vec3 lightDir"+a+";"),"point"===u.type&&o.push("uniform vec3 lightPos"+a+";"),"spot"===u.type&&(o.push("uniform vec3 lightPos"+a+";"),o.push("uniform vec3 lightDir"+a+";")))}if(o.push("uniform float gammaFactor;"),o.push("vec4 linearToLinear( in vec4 value ) {"),o.push(" return value;"),o.push("}"),o.push("vec4 sRGBToLinear( in vec4 value ) {"),o.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),o.push("}"),o.push("vec4 gammaToLinear( in vec4 value) {"),o.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),o.push("}"),t&&(o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}")),n){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),s&&o.push("in vec4 vClipPosition;");for(var c=0,A=i.getNumAllocatedSectionPlanes();c<A;c++)o.push("uniform bool sectionPlaneActive"+c+";"),o.push("uniform vec3 sectionPlanePos"+c+";"),o.push("uniform vec3 sectionPlaneDir"+c+";")}if(o.push("in vec4 vViewPosition;"),o.push("in vec3 vViewNormal;"),o.push("in vec4 vColor;"),o.push("in vec2 vUV;"),o.push("in vec2 vMetallicRoughness;"),r.lightMaps.length>0&&o.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(o,!0),o.push("#define PI 3.14159265359"),o.push("#define RECIPROCAL_PI 0.31830988618"),o.push("#define RECIPROCAL_PI2 0.15915494"),o.push("#define EPSILON 1e-6"),o.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),o.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),o.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),o.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),o.push(" return normalize(surf_norm );"),o.push(" }"),o.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),o.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),o.push(" vec2 st0 = dFdx( uv.st );"),o.push(" vec2 st1 = dFdy( uv.st );"),o.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),o.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),o.push(" vec3 N = normalize( surf_norm );"),o.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),o.push(" mat3 tsn = mat3( S, T, N );"),o.push(" return normalize( tsn * mapN );"),o.push("}"),o.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),o.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),o.push("}"),o.push("struct IncidentLight {"),o.push(" vec3 color;"),o.push(" vec3 direction;"),o.push("};"),o.push("struct ReflectedLight {"),o.push(" vec3 diffuse;"),o.push(" vec3 specular;"),o.push("};"),o.push("struct Geometry {"),o.push(" vec3 position;"),o.push(" vec3 viewNormal;"),o.push(" vec3 worldNormal;"),o.push(" vec3 viewEyeDir;"),o.push("};"),o.push("struct Material {"),o.push(" vec3 diffuseColor;"),o.push(" float specularRoughness;"),o.push(" vec3 specularColor;"),o.push(" float shine;"),o.push("};"),o.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),o.push(" float r = ggxRoughness + 0.0001;"),o.push(" return (2.0 / (r * r) - 2.0);"),o.push("}"),o.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),o.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),o.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),o.push("}"),r.reflectionMaps.length>0&&(o.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),o.push(" vec3 envMapColor = "+Ko[r.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),o.push(" return envMapColor;"),o.push("}")),o.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),o.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),o.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),o.push("}"),o.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" return 1.0 / ( gl * gv );"),o.push("}"),o.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" return 0.5 / max( gv + gl, EPSILON );"),o.push("}"),o.push("float D_GGX(const in float alpha, const in float dotNH) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),o.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float alpha = ( roughness * roughness );"),o.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),o.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),o.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),o.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),o.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),o.push(" vec3 F = F_Schlick( specularColor, dotLH );"),o.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),o.push(" float D = D_GGX( alpha, dotNH );"),o.push(" return F * (G * D);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),o.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),o.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),o.push(" vec4 r = roughness * c0 + c1;"),o.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),o.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),o.push(" return specularColor * AB.x + AB.y;"),o.push("}"),(r.lightMaps.length>0||r.reflectionMaps.length>0)&&(o.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),r.lightMaps.length>0&&(o.push(" vec3 irradiance = "+Ko[r.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),o.push(" irradiance *= PI;"),o.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),r.reflectionMaps.length>0&&(o.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),o.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),o.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),o.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),o.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),o.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),o.push("}")),o.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),o.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),o.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),o.push("}"),o.push("out vec4 outColor;"),o.push("void main(void) {"),n){o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(var h=0,d=i.getNumAllocatedSectionPlanes();h<d;h++)o.push("if (sectionPlaneActive"+h+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+h+".xyz, vWorldPosition.xyz - sectionPlanePos"+h+".xyz), 0.0, 1000.0);"),o.push("}");s?(o.push(" if (dist > (0.002 * vClipPosition.w)) {"),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push(" return;"),o.push("}")):(o.push(" if (dist > 0.0) { "),o.push(" discard;"),o.push(" }")),o.push("}")}o.push("IncidentLight light;"),o.push("Material material;"),o.push("Geometry geometry;"),o.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),o.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),o.push("float opacity = float(vColor.a) / 255.0;"),o.push("vec3 baseColor = rgb;"),o.push("float specularF0 = 1.0;"),o.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),o.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),o.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),o.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),o.push("baseColor *= colorTexel.rgb;"),o.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),o.push("metallic *= metalRoughTexel.b;"),o.push("roughness *= metalRoughTexel.g;"),o.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),o.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),o.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),o.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),o.push("geometry.position = vViewPosition.xyz;"),o.push("geometry.viewNormal = -normalize(viewNormal);"),o.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),r.lightMaps.length>0&&o.push("geometry.worldNormal = normalize(vWorldNormal);"),(r.lightMaps.length>0||r.reflectionMaps.length>0)&&o.push("computePBRLightMapping(geometry, material, reflectedLight);");for(var p=0,f=r.lights.length;p<f;p++){var v=r.lights[p];if("ambient"!==v.type){if("dir"===v.type)"view"===v.space?o.push("light.direction = normalize(lightDir"+p+");"):o.push("light.direction = normalize((viewMatrix * vec4(lightDir"+p+", 0.0)).xyz);");else if("point"===v.type)"view"===v.space?o.push("light.direction = normalize(lightPos"+p+" - vViewPosition.xyz);"):o.push("light.direction = normalize((viewMatrix * vec4(lightPos"+p+", 0.0)).xyz);");else{if("spot"!==v.type)continue;"view"===v.space?o.push("light.direction = normalize(lightDir"+p+");"):o.push("light.direction = normalize((viewMatrix * vec4(lightDir"+p+", 0.0)).xyz);")}o.push("light.color = lightColor"+p+".rgb * lightColor"+p+".a;"),o.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return o.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),o.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),o.push("vec4 fragColor;"),this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" fragColor = vec4(outgoingLight.rgb * ambient, opacity);")):o.push(" fragColor = vec4(outgoingLight.rgb, opacity);"),t&&o.push("fragColor = linearToGamma(fragColor, gammaFactor);"),o.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}]),i}(),Jo=function(e){m(i,So);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry normals fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("in vec4 vWorldPosition;"),i){r.push("in float vFlags;");for(var n=0;n<t.getNumAllocatedSectionPlanes();n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("out highp ivec4 outNormal;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.getNumAllocatedSectionPlanes();s++)r.push("if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push("}");r.push("if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),r.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),r.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),r.push(" outNormal = ivec4(worldNormal * float(".concat(le.MAX_INT,"), 1.0);")),r.push("}"),r}}]),i}(),Yo=function(e){m(i,So);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,i=e._lightsState,r=e._sectionPlanesState,n=r.getNumAllocatedSectionPlanes()>0,s=this._useAlphaCutoff,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),o.push("uniform float gammaFactor;"),o.push("vec4 linearToLinear( in vec4 value ) {"),o.push(" return value;"),o.push("}"),o.push("vec4 sRGBToLinear( in vec4 value ) {"),o.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),o.push("}"),o.push("vec4 gammaToLinear( in vec4 value) {"),o.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),o.push("}"),t&&(o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}")),n){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;");for(var a=0,l=r.getNumAllocatedSectionPlanes();a<l;a++)o.push("uniform bool sectionPlaneActive"+a+";"),o.push("uniform vec3 sectionPlanePos"+a+";"),o.push("uniform vec3 sectionPlaneDir"+a+";");o.push("uniform float sliceThickness;"),o.push("uniform vec4 sliceColor;")}this._addMatricesUniformBlockLines(o),o.push("uniform vec4 lightAmbient;");for(var u=0,c=i.lights.length;u<c;u++){var A=i.lights[u];"ambient"!==A.type&&(o.push("uniform vec4 lightColor"+u+";"),"dir"===A.type&&o.push("uniform vec3 lightDir"+u+";"),"point"===A.type&&o.push("uniform vec3 lightPos"+u+";"),"spot"===A.type&&(o.push("uniform vec3 lightPos"+u+";"),o.push("uniform vec3 lightDir"+u+";")))}if(s&&o.push("uniform float materialAlphaCutoff;"),o.push("in vec4 vViewPosition;"),o.push("in vec4 vColor;"),o.push("in vec2 vUV;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),o.push(" vec4 newColor;"),o.push(" newColor = vColor;"),n){o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(var h=0,d=r.getNumAllocatedSectionPlanes();h<d;h++)o.push("if (sectionPlaneActive"+h+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+h+".xyz, vWorldPosition.xyz - sectionPlanePos"+h+".xyz), 0.0, 1000.0);"),o.push("}");o.push(" if (dist > sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;"),o.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),o.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),o.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(var p=0,f=i.lights.length;p<f;p++){var v=i.lights[p];if("ambient"!==v.type){if("dir"===v.type)"view"===v.space?o.push("viewLightDir = normalize(lightDir"+p+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+p+", 0.0)).xyz);");else if("point"===v.type)"view"===v.space?o.push("viewLightDir = -normalize(lightPos"+p+" - vViewPosition.xyz);"):o.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+p+", 0.0)).xyz);");else{if("spot"!==v.type)continue;"view"===v.space?o.push("viewLightDir = normalize(lightDir"+p+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+p+", 0.0)).xyz);")}o.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),o.push("reflectedColor += lambertian * (lightColor"+p+".rgb * lightColor"+p+".a);")}}return o.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.a);"),o.push("vec4 sampleColor = texture(uColorMap, vUV);"),s&&(o.push("if (sampleColor.a < materialAlphaCutoff) {"),o.push(" discard;"),o.push("}")),t&&o.push("sampleColor = sRGBToLinear(sampleColor);"),o.push("vec4 colorTexel = color * sampleColor;"),o.push("float opacity = color.a;"),this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" outColor = vec4(colorTexel.rgb * ambient, opacity);")):o.push(" outColor = vec4(colorTexel.rgb, opacity);"),t&&o.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}]),i}(),qo=le.vec3(),$o=le.vec3(),ea=le.vec3(),ta=le.vec3(),ia=le.mat4(),ra=function(e){m(i,Ds);var t=y(i);function i(e){return E(this,i),t.call(this,e,!1,{instancing:!0})}return I(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,n=r.scene,s=n.canvas.gl,o=n.camera,a=t._state,l=t._state.origin,u=r.position,c=r.rotationMatrix,A=t.aabb,h=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?s.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var d,p,f=qo;if(f[0]=le.safeInv(A[3]-A[0])*le.MAX_INT,f[1]=le.safeInv(A[4]-A[1])*le.MAX_INT,f[2]=le.safeInv(A[5]-A[2])*le.MAX_INT,e.snapPickCoordinateScale[0]=le.safeInv(f[0]),e.snapPickCoordinateScale[1]=le.safeInv(f[1]),e.snapPickCoordinateScale[2]=le.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=$o;if(l){var g=le.transformPoint3(c,l,ea);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],d=Jt(h,v,ia),(p=ta)[0]=o.eye[0]-v[0],p[1]=o.eye[1]-v[1],p[2]=o.eye[2]-v[2],e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else d=h,p=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;s.uniform3fv(this._uCameraEyeRtc,p),s.uniform2fv(this.uVectorA,e.snapVectorA),s.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),s.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),s.uniform3fv(this._uCoordinateScaler,f),s.uniform1i(this._uRenderPass,i),s.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(d,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),s.bindBuffer(s.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),s.bufferData(s.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,s.DYNAMIC_DRAW),s.bindBufferBase(s.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),s.drawElementsInstanced(s.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),s.bindVertexArray(null)}}},{key:"_allocate",value:function(){v(x(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var r=0;r<e.getNumAllocatedSectionPlanes();r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<e.getNumAllocatedSectionPlanes();n++)i.push("if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat(le.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),na=le.vec3(),sa=le.vec3(),oa=le.vec3(),aa=le.vec3(),la=le.mat4(),ua=function(e){m(i,Ds);var t=y(i);function i(e){return E(this,i),t.call(this,e,!1,{instancing:!0})}return I(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,n=r.scene,s=n.camera,o=n.canvas.gl,a=t._state,l=t._state.origin,u=r.position,c=r.rotationMatrix,A=t.aabb,h=e.pickViewMatrix||s.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var d,p,f=na;if(f[0]=le.safeInv(A[3]-A[0])*le.MAX_INT,f[1]=le.safeInv(A[4]-A[1])*le.MAX_INT,f[2]=le.safeInv(A[5]-A[2])*le.MAX_INT,e.snapPickCoordinateScale[0]=le.safeInv(f[0]),e.snapPickCoordinateScale[1]=le.safeInv(f[1]),e.snapPickCoordinateScale[2]=le.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=sa;if(l){var g=le.transformPoint3(c,l,oa);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],d=Jt(h,v,la),(p=aa)[0]=s.eye[0]-v[0],p[1]=s.eye[1]-v[1],p[2]=s.eye[2]-v[2],e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else d=h,p=s.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,p),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(d,m+=16),this._matricesUniformBlockBufferData.set(s.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?a.edgeIndicesBuf&&(a.edgeIndicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.bindVertexArray(null)}}},{key:"_allocate",value:function(){v(x(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r<e.getNumAllocatedSectionPlanes();r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<e.getNumAllocatedSectionPlanes();n++)i.push("if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),ca=function(){function e(t){E(this,e),this._scene=t}return I(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._colorTextureRendererAlphaCutoff&&!this._colorTextureRendererAlphaCutoff.getValid()&&(this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererAlphaCutoff=null),this._colorTextureRendererWithSAOAlphaCutoff&&!this._colorTextureRendererWithSAOAlphaCutoff.getValid()&&(this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._silhouetteRenderer||(this._silhouetteRenderer=new Lo(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Qo(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Ho(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new ra(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new ua(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Ro(this._scene,!1)),this._colorRenderer}},{key:"colorRendererWithSAO",get:function(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Ro(this._scene,!0)),this._colorRendererWithSAO}},{key:"flatColorRenderer",get:function(){return this._flatColorRenderer||(this._flatColorRenderer=new Uo(this._scene,!1)),this._flatColorRenderer}},{key:"flatColorRendererWithSAO",get:function(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Uo(this._scene,!0)),this._flatColorRendererWithSAO}},{key:"colorTextureRenderer",get:function(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Yo(this._scene,!1)),this._colorTextureRenderer}},{key:"colorTextureRendererWithSAO",get:function(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Yo(this._scene,!0)),this._colorTextureRendererWithSAO}},{key:"colorTextureRendererAlphaCutoff",get:function(){return this._colorTextureRendererAlphaCutoff||(this._colorTextureRendererAlphaCutoff=new Yo(this._scene,!1,{useAlphaCutoff:!0})),this._colorTextureRendererAlphaCutoff}},{key:"colorTextureRendererWithSAOAlphaCutoff",get:function(){return this._colorTextureRendererWithSAOAlphaCutoff||(this._colorTextureRendererWithSAOAlphaCutoff=new Yo(this._scene,!0,{useAlphaCutoff:!0})),this._colorTextureRendererWithSAOAlphaCutoff}},{key:"pbrRenderer",get:function(){return this._pbrRenderer||(this._pbrRenderer=new Zo(this._scene,!1)),this._pbrRenderer}},{key:"pbrRendererWithSAO",get:function(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Zo(this._scene,!0)),this._pbrRendererWithSAO}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Lo(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new zo(this._scene)),this._depthRenderer}},{key:"normalsRenderer",get:function(){return this._normalsRenderer||(this._normalsRenderer=new Wo(this._scene)),this._normalsRenderer}},{key:"edgesRenderer",get:function(){return this._edgesRenderer||(this._edgesRenderer=new No(this._scene)),this._edgesRenderer}},{key:"edgesColorRenderer",get:function(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Vo(this._scene)),this._edgesColorRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Qo(this._scene)),this._pickMeshRenderer}},{key:"pickNormalsRenderer",get:function(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new jo(this._scene)),this._pickNormalsRenderer}},{key:"pickNormalsFlatRenderer",get:function(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Jo(this._scene)),this._pickNormalsFlatRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Ho(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new Go(this._scene)),this._occlusionRenderer}},{key:"shadowRenderer",get:function(){return this._shadowRenderer||(this._shadowRenderer=new Xo(this._scene)),this._shadowRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new ua(this._scene)),this._snapRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new ra(this._scene)),this._snapInitRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererAlphaCutoff&&this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff&&this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Aa={};var ha=new Uint8Array(4),da=new Float32Array(1),pa=le.vec4([0,0,0,1]),fa=new Float32Array(3),va=le.vec3(),ga=le.vec3(),ma=le.vec3(),_a=le.vec3(),ya=le.vec3(),ba=le.vec3(),wa=le.vec3(),Ba=new Float32Array(4),xa=function(){function e(t){E(this,e),this.model=t.model,this.sortId="TrianglesInstancingLayer"+(t.solid?"-solid":"-surface")+(t.normals?"-normals":"-autoNormals"),this.layerIndex=t.layerIndex,this._renderers=function(e){var t=e.id,i=Aa[t];return i||(i=new ca(e),Aa[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(function(){i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(function(){delete Aa[t],i._destroy()}))),i}(t.model.scene),this._aabb=le.collapseAABB3(),this._state=new nt({numInstances:0,obb:le.OBB3(),origin:le.vec3(),geometry:t.geometry,textureSet:t.textureSet,pbrSupported:!1,positionsDecodeMatrix:t.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=t.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=le.collapseAABB3(),this.aabbDirty=!0,t.origin&&this._state.origin.set(t.origin),this._finalized=!1,this.solid=!!t.solid,this.numIndices=t.geometry.numIndices,this.primitive=t.geometry.primitive}return I(e,[{key:"aabb",get:function(){if(this.aabbDirty){le.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e<t;e++)le.expandAABB3(this._aabb,this._meshes[e].aabb);this.aabbDirty=!1}return this._aabb}},{key:"createPortion",value:function(e,t){var i=t.color,r=t.metallic,n=t.roughness,s=null!==t.opacity&&void 0!==t.opacity?t.opacity:255,o=t.meshMatrix,a=t.pickColor;if(this._finalized)throw"Already finalized";var l=i[0],u=i[1],c=i[2];if(this._colors.push(l),this._colors.push(u),this._colors.push(c),this._colors.push(s),this._metallicRoughness.push(null!=r?r:0),this._metallicRoughness.push(null!=n?n:255),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(o[0]),this._modelMatrixCol0.push(o[4]),this._modelMatrixCol0.push(o[8]),this._modelMatrixCol0.push(o[12]),this._modelMatrixCol1.push(o[1]),this._modelMatrixCol1.push(o[5]),this._modelMatrixCol1.push(o[9]),this._modelMatrixCol1.push(o[13]),this._modelMatrixCol2.push(o[2]),this._modelMatrixCol2.push(o[6]),this._modelMatrixCol2.push(o[10]),this._modelMatrixCol2.push(o[14]),this._state.geometry.normals){var A=le.transposeMat4(o,le.mat4()),h=le.inverseMat4(A);this._modelNormalMatrixCol0.push(h[0]),this._modelNormalMatrixCol0.push(h[4]),this._modelNormalMatrixCol0.push(h[8]),this._modelNormalMatrixCol0.push(h[12]),this._modelNormalMatrixCol1.push(h[1]),this._modelNormalMatrixCol1.push(h[5]),this._modelNormalMatrixCol1.push(h[9]),this._modelNormalMatrixCol1.push(h[13]),this._modelNormalMatrixCol2.push(h[2]),this._modelNormalMatrixCol2.push(h[6]),this._modelNormalMatrixCol2.push(h[10]),this._modelNormalMatrixCol2.push(h[14])}this._pickColors.push(a[0]),this._pickColors.push(a[1]),this._pickColors.push(a[2]),this._pickColors.push(a[3]),this._state.numInstances++;var d=this._portions.length,p={};return this.model.scene.readableGeometryEnabled&&(p.matrix=o.slice(),p.inverseMatrix=null,p.normalMatrix=null),this._portions.push(p),this._numPortions++,this.model.numPortions++,this._meshes.push(e),d}},{key:"finalize",value:function(){if(!this._finalized){var e=this._state,t=e.geometry,i=e.textureSet,r=this.model.scene.canvas.gl,n=this._colors.length,s=n/4;if(n>0){e.colorsBuf=new st(r,r.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,r.DYNAMIC_DRAW,!1),this._colors=[]}if(this._metallicRoughness.length>0){var o=new Uint8Array(this._metallicRoughness);e.metallicRoughnessBuf=new st(r,r.ARRAY_BUFFER,o,this._metallicRoughness.length,2,r.STATIC_DRAW,!1)}if(s>0){e.flagsBuf=new st(r,r.ARRAY_BUFFER,new Float32Array(s),s,1,r.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){e.offsetsBuf=new st(r,r.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,r.DYNAMIC_DRAW,!1),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){e.positionsBuf=new st(r,r.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,r.STATIC_DRAW,!1),e.positionsDecodeMatrix=le.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){var a=new Uint8Array(t.colorsCompressed);e.colorsBuf=new st(r,r.ARRAY_BUFFER,a,a.length,4,r.STATIC_DRAW,!1)}if(t.uvCompressed&&t.uvCompressed.length>0){var l=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new st(r,r.ARRAY_BUFFER,l,l.length,2,r.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new st(r,r.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,r.STATIC_DRAW),e.numIndices=t.indices.length),t.edgeIndices&&t.edgeIndices.length>0&&(e.edgeIndicesBuf=new st(r,r.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,r.STATIC_DRAW)),this._modelMatrixCol0.length>0){var u=!1;e.modelMatrixCol0Buf=new st(r,r.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,r.STATIC_DRAW,u),e.modelMatrixCol1Buf=new st(r,r.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,r.STATIC_DRAW,u),e.modelMatrixCol2Buf=new st(r,r.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,r.STATIC_DRAW,u),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new st(r,r.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,r.STATIC_DRAW,u),e.modelNormalMatrixCol1Buf=new st(r,r.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,r.STATIC_DRAW,u),e.modelNormalMatrixCol2Buf=new st(r,r.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,r.STATIC_DRAW,u),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){e.pickColorsBuf=new st(r,r.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,r.STATIC_DRAW,!1),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this.model.scene.readableGeometryEnabled||(this._state.geometry=null),this._finalized=!0}}},{key:"initFlags",value:function(e,t,i){t&gs&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Bs&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ws&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&xs&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ys&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Ps&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&_s&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ms&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&gs?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Bs?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ws?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&xs?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ps?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&ys?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&_s?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ms?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";ha[0]=t[0],ha[1]=t[1],ha[2]=t[2],ha[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(ha,4*e)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){if(!this._finalized)throw"Not finalized";var r=!!(t&gs),n=!!(t&ws),s=!!(t&Bs),o=!!(t&xs),a=!!(t&Ps),l=!!(t&_s),u=!!(t&ms),c=0;c|=!r||u||n||s&&!this.model.scene.highlightMaterial.glowThrough||o&&!this.model.scene.selectedMaterial.glowThrough?Cs.NOT_RENDERED:i?Cs.COLOR_TRANSPARENT:Cs.COLOR_OPAQUE,c|=(!r||u?Cs.NOT_RENDERED:o?Cs.SILHOUETTE_SELECTED:s?Cs.SILHOUETTE_HIGHLIGHTED:n?Cs.SILHOUETTE_XRAYED:Cs.NOT_RENDERED)<<4,c|=(!r||u?Cs.NOT_RENDERED:o?Cs.EDGES_SELECTED:s?Cs.EDGES_HIGHLIGHTED:n?Cs.EDGES_XRAYED:a?i?Cs.EDGES_COLOR_TRANSPARENT:Cs.EDGES_COLOR_OPAQUE:Cs.NOT_RENDERED)<<8,c|=(r&&!u&&l?Cs.PICK:Cs.NOT_RENDERED)<<12,c|=(t&ys?1:0)<<16,da[0]=c,this._state.flagsBuf&&this._state.flagsBuf.setData(da,e)}},{key:"setOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(fa[0]=t[0],fa[1]=t[1],fa[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(fa,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}},{key:"getEachVertex",value:function(e,t){if(!this.model.scene.readableGeometryEnabled)return!1;var i=this._state,r=i.geometry,n=this._portions[e];if(n){var s=r.positionsCompressed,o=this.model.matrix,a=le.vec4();a.set(i.origin,0),a[3]=1,le.mulMat4v4(o,a,a);for(var l=a[0],u=a[1],c=a[2],A=pa,h=n.matrix,d=i.positionsDecodeMatrix,p=0,f=s.length;p<f;p+=3)A[0]=s[p],A[1]=s[p+1],A[2]=s[p+2],le.decompressPosition(A,d),le.transformPoint3(h,A,A),A[3]=1,le.mulMat4v4(o,A,A),A[0]+=l,A[1]+=u,A[2]+=c,t(A)}else this.model.error("portion not found: "+e)}},{key:"getEachIndex",value:function(e,t){if(!this.model.scene.readableGeometryEnabled)return!1;var i=this._state.geometry;if(this._portions[e])for(var r=i.indices,n=0,s=r.length;n<s;n++)t(r[n]);else this.model.error("portion not found: "+e)}},{key:"setMatrix",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=4*e;Ba[0]=t[0],Ba[1]=t[4],Ba[2]=t[8],Ba[3]=t[12],this._state.modelMatrixCol0Buf.setData(Ba,i),Ba[0]=t[1],Ba[1]=t[5],Ba[2]=t[9],Ba[3]=t[13],this._state.modelMatrixCol1Buf.setData(Ba,i),Ba[0]=t[2],Ba[1]=t[6],Ba[2]=t[10],Ba[3]=t[14],this._state.modelMatrixCol2Buf.setData(Ba,i)}},{key:"readGeometryData",value:function(e){if(!this._finalized)throw"Not finalized";var t=this._state,i=this.model.matrix,r=t.modelMatrixCol0Buf.getData(e,1),n=t.modelMatrixCol1Buf.getData(e,1),s=t.modelMatrixCol2Buf.getData(e,1),o=[r[0],n[0],s[0],0,r[1],n[1],s[1],0,r[2],n[2],s[2],0,r[3],n[3],s[3],1],a=t.positionsDecodeMatrix,l=le.vec4();l.set(t.origin,0),l[3]=1,le.mulMat4v4(i,l,l);var u=t.indicesBuf.getData(),c=le.mulMat4(o,a,new Array(16));le.mulMat4(i,c,c),c[12]+=l[0],c[13]+=l[1],c[14]+=l[2];var A=t.positionsBuf.getData();return{indices:u,positions:le.transformPositions3(c,A,new Array(A.length))}}},{key:"drawColorOpaque",value:function(e,t){if(this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions){this._updateBackfaceCull(e,t);var i=this._state.textureSet&&"number"==typeof this._state.textureSet.alphaCutoff;t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._renderers.pbrRendererWithSAO&&this._renderers.pbrRendererWithSAO.drawLayer(t,this,Cs.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?i?this._renderers.colorTextureRendererWithSAOAlphaCutoff&&this._renderers.colorTextureRendererWithSAOAlphaCutoff.drawLayer(t,this,Cs.COLOR_OPAQUE):this._renderers.colorTextureRendererWithSAO&&this._renderers.colorTextureRendererWithSAO.drawLayer(t,this,Cs.COLOR_OPAQUE):this._state.normalsBuf?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,Cs.COLOR_OPAQUE):this._renderers.flatColorRendererWithSAO&&this._renderers.flatColorRendererWithSAO.drawLayer(t,this,Cs.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._renderers.pbrRenderer&&this._renderers.pbrRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?i?this._renderers.colorTextureRendererAlphaCutoff&&this._renderers.colorTextureRendererAlphaCutoff.drawLayer(t,this,Cs.COLOR_OPAQUE):this._renderers.colorTextureRenderer&&this._renderers.colorTextureRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE):this._state.normalsBuf?this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE):this._renderers.flatColorRenderer&&this._renderers.flatColorRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE)}}},{key:"_updateBackfaceCull",value:function(e,t){if(true!==t.backfaces){var i=t.gl;i.disable(i.CULL_FACE),t.backfaces=true}}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._renderers.pbrRenderer&&this._renderers.pbrRenderer.drawLayer(t,this,Cs.COLOR_TRANSPARENT):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._renderers.colorTextureRenderer&&this._renderers.colorTextureRenderer.drawLayer(t,this,Cs.COLOR_TRANSPARENT):this._state.normalsBuf?this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Cs.COLOR_TRANSPARENT):this._renderers.flatColorRenderer&&this._renderers.flatColorRenderer.drawLayer(t,this,Cs.COLOR_TRANSPARENT))}},{key:"drawDepth",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE))}},{key:"drawNormals",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE))}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_XRAYED))}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_HIGHLIGHTED))}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_SELECTED))}},{key:"drawEdgesColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Cs.EDGES_COLOR_OPAQUE)}},{key:"drawEdgesColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Cs.EDGES_COLOR_TRANSPARENT)}},{key:"drawEdgesXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Cs.EDGES_XRAYED)}},{key:"drawEdgesHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Cs.EDGES_HIGHLIGHTED)}},{key:"drawEdgesSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Cs.EDGES_SELECTED)}},{key:"drawOcclusion",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE))}},{key:"drawShadow",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE))}},{key:"drawPickMesh",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Cs.PICK))}},{key:"drawPickDepths",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Cs.PICK))}},{key:"drawPickNormals",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsFlatRenderer&&this._renderers.pickNormalsFlatRenderer.drawLayer(t,this,Cs.PICK))}},{key:"drawSnapInit",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Cs.PICK))}},{key:"drawSnap",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Cs.PICK))}},{key:"precisionRayPickSurface",value:function(e,t,i,r,n){if(!this.model.scene.readableGeometryEnabled)return!1;var s=this._state.geometry,o=this._state,a=this._portions[e];if(!a)return this.model.error("portion not found: "+e),!1;a.inverseMatrix||(a.inverseMatrix=le.inverseMat4(a.matrix,le.mat4())),n&&!a.normalMatrix&&(a.normalMatrix=le.transposeMat4(a.inverseMatrix,le.mat4()));var l=s.quantizedPositions,u=s.indices,c=o.origin,A=a.offset,h=va,d=ga;h.set(c?le.subVec3(t,c,ma):t),d.set(i),A&&le.subVec3(h,A),le.transformRay(this.model.worldNormalMatrix,h,d,h,d),le.transformRay(a.inverseMatrix,h,d,h,d);for(var p=_a,f=ya,v=ba,g=!1,m=0,_=wa,y=0,b=u.length;y<b;y+=3){var w=3*u[y+0],B=3*u[y+1],x=3*u[y+2];p[0]=l[w],p[1]=l[w+1],p[2]=l[w+2],f[0]=l[B],f[1]=l[B+1],f[2]=l[B+2],v[0]=l[x],v[1]=l[x+1],v[2]=l[x+2];var P=o.geometry.positionsDecodeMatrix;if(le.decompressPosition(p,P),le.decompressPosition(f,P),le.decompressPosition(v,P),le.rayTriangleIntersect(h,d,p,f,v,_)){le.transformPoint3(a.matrix,_,_),le.transformPoint3(this.model.worldMatrix,_,_),A&&le.addVec3(_,A),c&&le.addVec3(_,c);var C=Math.abs(le.lenVec3(le.subVec3(_,t,[])));(!g||C>m)&&(m=C,r.set(_),n&&le.triangleNormal(p,f,v,n),g=!0)}}return g&&n&&(le.transformVec3(a.normalMatrix,n,n),le.transformVec3(this.model.worldNormalMatrix,n,n),le.normalizeVec3(n)),g}},{key:"destroy",value:function(){var e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}]),e}(),Pa=function(e){m(i,Ds);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,r=e.frameCtx,n=e.incrementDrawState;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),n&&r.drawElements++}}]),i}(),Ca=function(e){m(i,Pa);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Lines batching color fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0,s=t.getNumAllocatedSectionPlanes();n<s;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o<a;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}return r.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}]),i}(),Ma=function(e){m(i,Pa);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Lines batching silhouette fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0,s=t.getNumAllocatedSectionPlanes();n<s;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("uniform vec4 color;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o<a;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = color;"),r.push("}"),r}}]),i}(),ka=le.vec3(),Ea=le.vec3(),Fa=le.vec3(),Ia=le.vec3(),Ta=le.mat4(),Da=function(e){m(i,Ds);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,n=r.scene,s=n.camera,o=n.canvas.gl,a=t._state,l=t._state.origin,u=r.position,c=r.rotationMatrix,A=t.aabb,h=e.pickViewMatrix||s.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var d,p,f=ka;if(f[0]=le.safeInv(A[3]-A[0])*le.MAX_INT,f[1]=le.safeInv(A[4]-A[1])*le.MAX_INT,f[2]=le.safeInv(A[5]-A[2])*le.MAX_INT,e.snapPickCoordinateScale[0]=le.safeInv(f[0]),e.snapPickCoordinateScale[1]=le.safeInv(f[1]),e.snapPickCoordinateScale[2]=le.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=Ea;if(l){var g=Fa;le.transformPoint3(c,l,g),v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],d=Jt(h,v,Ta),(p=Ia)[0]=s.eye[0]-v[0],p[1]=s.eye[1]-v[1],p[2]=s.eye[2]-v[2],e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else d=h,p=s.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,p),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(d,m+=16),this._matricesUniformBlockBufferData.set(s.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),o.drawElements(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind(),o.bindVertexArray(null)}}},{key:"_allocate",value:function(){v(x(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var r=0;r<e.getNumAllocatedSectionPlanes();r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<e.getNumAllocatedSectionPlanes();n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat(le.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Sa=le.vec3(),Ra=le.vec3(),Ua=le.vec3(),La=le.vec3(),Oa=le.mat4(),Na=function(e){m(i,Ds);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,n=r.scene,s=n.camera,o=n.canvas.gl,a=t._state,l=t._state.origin,u=r.position,c=r.rotationMatrix,A=t.aabb,h=e.pickViewMatrix||s.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var d,p,f=Sa;if(f[0]=le.safeInv(A[3]-A[0])*le.MAX_INT,f[1]=le.safeInv(A[4]-A[1])*le.MAX_INT,f[2]=le.safeInv(A[5]-A[2])*le.MAX_INT,e.snapPickCoordinateScale[0]=le.safeInv(f[0]),e.snapPickCoordinateScale[1]=le.safeInv(f[1]),e.snapPickCoordinateScale[2]=le.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=Ra;if(l){var g=Ua;le.transformPoint3(c,l,g),v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],d=Jt(h,v,Oa),(p=La)[0]=s.eye[0]-v[0],p[1]=s.eye[1]-v[1],p[2]=s.eye[2]-v[2],e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else d=h,p=s.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,p),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(d,m+=16),this._matricesUniformBlockBufferData.set(s.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),o.drawElements(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):o.drawArrays(o.POINTS,0,a.positionsBuf.numItems),o.bindVertexArray(null)}}},{key:"_allocate",value:function(){v(x(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;var i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r<e.getNumAllocatedSectionPlanes();r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<e.getNumAllocatedSectionPlanes();n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Va=function(){function e(t){E(this,e),this._scene=t}return I(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Ca(this._scene,!1)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ma(this._scene)),this._silhouetteRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new Da(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new Na(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Qa={};var Ha=I((function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:5e6;E(this,e),t>5e6&&(t=5e6),this.maxVerts=t,this.maxIndices=3*t,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]})),ja=function(){function e(t){var i,r,n;E(this,e),this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,r=i.id,(n=Qa[r])||(n=new Va(i),Qa[r]=n,n._compile(),i.on("compile",(function(){n._compile()})),i.on("destroyed",(function(){delete Qa[r],n._destroy()}))),n),this.model=t.model,this._buffer=new Ha(t.maxGeometryBatchSize),this._scratchMemory=t.scratchMemory,this._state=new nt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:le.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=le.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=le.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,t.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(t.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,t.origin&&(this._state.origin=le.vec3(t.origin)),this.primitive=t.primitive}return I(e,[{key:"aabb",get:function(){if(this.aabbDirty){le.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e<t;e++)le.expandAABB3(this._aabb,this._meshes[e].aabb);this.aabbDirty=!1}return this._aabb}},{key:"canCreatePortion",value:function(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}},{key:"createPortion",value:function(e,t){if(this._finalized)throw"Already finalized";var i,r=t.positions,n=t.positionsCompressed,s=t.indices,o=t.color,a=t.opacity,l=this._buffer,u=l.positions.length/3;if(le.expandAABB3(this._modelAABB,t.aabb),this._preCompressedPositionsExpected){if(!n)throw"positionsCompressed expected";i=n.length/3;for(var c=0,A=n.length;c<A;c++)l.positions.push(n[c])}else{if(!r)throw"positions expected";i=r.length/3;for(var h=0,d=r.length;h<d;h++)l.positions.push(r[h])}if(o)for(var p=o[0],f=o[1],v=o[2],g=a,m=0;m<i;m++)l.colors.push(p),l.colors.push(f),l.colors.push(v),l.colors.push(g);if(s)for(var _=0,y=s.length;_<y;_++)l.indices.push(s[_]+u);if(this.model.scene.entityOffsetsEnabled)for(var b=0;b<i;b++)l.offsets.push(0),l.offsets.push(0),l.offsets.push(0);var w=this._portions.length/2;return this._portions.push(u),this._portions.push(i),this._numPortions++,this.model.numPortions++,this._numVerts+=i,this._meshes.push(e),w}},{key:"finalize",value:function(){if(!this._finalized){var e=this._state,t=this.model.scene.canvas.gl,i=this._buffer;if(i.positions.length>0)if(this._preCompressedPositionsExpected){var r=new Uint16Array(i.positions);e.positionsBuf=new st(t,t.ARRAY_BUFFER,r,i.positions.length,3,t.STATIC_DRAW)}else{var n=_o(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new st(t,t.ARRAY_BUFFER,n,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){var s=new Uint8Array(i.colors);e.colorsBuf=new st(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,!1)}if(i.colors.length>0){var o=i.colors.length/4,a=new Float32Array(o);e.flagsBuf=new st(t,t.ARRAY_BUFFER,a,a.length,1,t.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){var l=new Float32Array(i.offsets);e.offsetsBuf=new st(t,t.ARRAY_BUFFER,l,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){var u=new Uint32Array(i.indices);e.indicesBuf=new st(t,t.ELEMENT_ARRAY_BUFFER,u,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}}},{key:"initFlags",value:function(e,t,i){t&gs&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Bs&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ws&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&xs&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ys&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Ps&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&_s&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ms&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&gs?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Bs?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ws?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&xs?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ps?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&ys?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ms?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&_s?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";for(var i=2*e,r=4*this._portions[i],n=4*this._portions[i+1],s=this._scratchMemory.getUInt8Array(n),o=t[0],a=t[1],l=t[2],u=t[3],c=0;c<n;c+=4)s[c+0]=o,s[c+1]=a,s[c+2]=l,s[c+3]=u;this._state.colorsBuf.setData(s,r,n)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var n,s,o=2*e,a=this._portions[o],l=this._portions[o+1],u=a,c=l,A=!!(t&gs),h=!!(t&ws),d=!!(t&Bs),p=!!(t&xs),f=!!(t&_s),v=!!(t&ms);n=!A||v||h||d&&!this.model.scene.highlightMaterial.glowThrough||p&&!this.model.scene.selectedMaterial.glowThrough?Cs.NOT_RENDERED:i?Cs.COLOR_TRANSPARENT:Cs.COLOR_OPAQUE,s=!A||v?Cs.NOT_RENDERED:p?Cs.SILHOUETTE_SELECTED:d?Cs.SILHOUETTE_HIGHLIGHTED:h?Cs.SILHOUETTE_XRAYED:Cs.NOT_RENDERED;var g=A&&!v&&f?Cs.PICK:Cs.NOT_RENDERED,m=t&ys?1:0;if(r){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(var _=u,y=u+c;_<y;_++){var b=0;b|=n,b|=s<<4,b|=g<<12,b|=m<<16,this._deferredFlagValues[_]=b}}else if(this._state.flagsBuf){for(var w=this._scratchMemory.getFloat32Array(c),B=0;B<c;B++){var x=0;x|=n,x|=s<<4,x|=g<<12,x|=m<<16,w[B]=x}this._state.flagsBuf.setData(w,u,c)}}},{key:"_setDeferredFlags",value:function(){this._deferredFlagValues&&(this._state.flagsBuf.setData(this._deferredFlagValues),this._deferredFlagValues=null)}},{key:"setOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";if(this.model.scene.entityOffsetsEnabled){for(var i=2*e,r=3*this._portions[i],n=3*this._portions[i+1],s=this._scratchMemory.getFloat32Array(n),o=t[0],a=t[1],l=t[2],u=0;u<n;u+=3)s[u+0]=o,s[u+1]=a,s[u+2]=l;this._state.offsetsBuf.setData(s,r,n)}else this.model.error("Entity#offset not enabled for this Viewer")}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE)}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Cs.COLOR_TRANSPARENT)}},{key:"drawDepth",value:function(e,t){}},{key:"drawNormals",value:function(e,t){}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_XRAYED)}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_HIGHLIGHTED)}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_SELECTED)}},{key:"drawEdgesColorOpaque",value:function(e,t){}},{key:"drawEdgesColorTransparent",value:function(e,t){}},{key:"drawEdgesHighlighted",value:function(e,t){}},{key:"drawEdgesSelected",value:function(e,t){}},{key:"drawEdgesXRayed",value:function(e,t){}},{key:"drawPickMesh",value:function(e){}},{key:"drawPickDepths",value:function(e){}},{key:"drawPickNormals",value:function(e){}},{key:"drawSnapInit",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Cs.PICK)}},{key:"drawSnap",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Cs.PICK)}},{key:"drawOcclusion",value:function(e){}},{key:"drawShadow",value:function(e){}},{key:"destroy",value:function(){var e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicesBuf=null),e.destroy()}}]),e}(),Ga=function(e){m(i,Ds);var t=y(i);function i(e,r){return E(this,i),t.call(this,e,r,{instancing:!0})}return I(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,r=e.frameCtx,n=e.incrementDrawState;t.drawElementsInstanced(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),n&&r.drawElements++}}]),i}(),za=function(e){m(i,Ga);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,r=i._sectionPlanesState,n=r.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines instancing color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),i.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),n)for(s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;"),e=0,t=r.getNumAllocatedSectionPlanes();e<t;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";");if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),n){for(s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;"),e=0,t=r.getNumAllocatedSectionPlanes();e<t;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):s.push(" outColor = vColor;"),i.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}]),i}(),Wa=function(e){m(i,Ga);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Lines instancing silhouette fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0,s=t.getNumAllocatedSectionPlanes();n<s;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("uniform vec4 color;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o<a;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push("if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = color;"),r.push("}"),r}}]),i}(),Xa=le.vec3(),Ka=le.vec3(),Za=le.vec3();le.vec3();var Ja=le.mat4(),Ya=function(e){m(i,Ds);var t=y(i);function i(e){return E(this,i),t.call(this,e,!1,{instancing:!0})}return I(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,n=r.scene,s=n.canvas.gl,o=n.camera,a=t._state,l=t._state.origin,u=r.position,c=r.rotationMatrix,A=t.aabb,h=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?s.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var d,p=Xa;if(p[0]=le.safeInv(A[3]-A[0])*le.MAX_INT,p[1]=le.safeInv(A[4]-A[1])*le.MAX_INT,p[2]=le.safeInv(A[5]-A[2])*le.MAX_INT,e.snapPickCoordinateScale[0]=le.safeInv(p[0]),e.snapPickCoordinateScale[1]=le.safeInv(p[1]),e.snapPickCoordinateScale[2]=le.safeInv(p[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var f=Ka;if(l){var v=le.transformPoint3(c,l,Za);f[0]=v[0],f[1]=v[1],f[2]=v[2]}else f[0]=0,f[1]=0,f[2]=0;f[0]+=u[0],f[1]+=u[1],f[2]+=u[2],d=Jt(h,f,Ja),e.snapPickOrigin[0]=f[0],e.snapPickOrigin[1]=f[1],e.snapPickOrigin[2]=f[2]}else d=h,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;s.uniform2fv(this.uVectorA,e.snapVectorA),s.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),s.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),s.uniform3fv(this._uCoordinateScaler,p),s.uniform1i(this._uRenderPass,i),s.uniform1i(this._uPickInvisible,e.pickInvisible);var g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(d,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),s.bindBuffer(s.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),s.bufferData(s.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,s.DYNAMIC_DRAW),s.bindBufferBase(s.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var m=2/(Math.log(e.pickZFar+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,m),this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),s.drawElementsInstanced(s.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),s.bindVertexArray(null)}}},{key:"_allocate",value:function(){v(x(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var r=0;r<e.getNumAllocatedSectionPlanes();r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<e.getNumAllocatedSectionPlanes();n++)i.push("if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),qa=le.vec3(),$a=le.vec3(),el=le.vec3();le.vec3();var tl=le.mat4(),il=function(e){m(i,Ds);var t=y(i);function i(e){return E(this,i),t.call(this,e,!1,{instancing:!0})}return I(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,n=r.scene,s=n.camera,o=n.canvas.gl,a=t._state,l=t._state.origin,u=r.position,c=r.rotationMatrix,A=t.aabb,h=e.pickViewMatrix||s.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var d,p=qa;if(p[0]=le.safeInv(A[3]-A[0])*le.MAX_INT,p[1]=le.safeInv(A[4]-A[1])*le.MAX_INT,p[2]=le.safeInv(A[5]-A[2])*le.MAX_INT,e.snapPickCoordinateScale[0]=le.safeInv(p[0]),e.snapPickCoordinateScale[1]=le.safeInv(p[1]),e.snapPickCoordinateScale[2]=le.safeInv(p[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var f=$a;if(l){var v=le.transformPoint3(c,l,el);f[0]=v[0],f[1]=v[1],f[2]=v[2]}else f[0]=0,f[1]=0,f[2]=0;f[0]+=u[0],f[1]+=u[1],f[2]+=u[2],d=Jt(h,f,tl),e.snapPickOrigin[0]=f[0],e.snapPickOrigin[1]=f[1],e.snapPickOrigin[2]=f[2]}else d=h,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,p),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(d,g+=16),this._matricesUniformBlockBufferData.set(s.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var m=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,m),this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.bindVertexArray(null)}}},{key:"_allocate",value:function(){v(x(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r<e.getNumAllocatedSectionPlanes();r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<e.getNumAllocatedSectionPlanes();n++)i.push("if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),rl=function(){function e(t){E(this,e),this._scene=t}return I(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._snapInitRenderer||(this._snapInitRenderer=new Ya(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new il(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new za(this._scene)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Wa(this._scene)),this._silhouetteRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new Ya(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new il(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),nl={};var sl=new Uint8Array(4),ol=new Float32Array(1),al=new Float32Array(3),ll=new Float32Array(4),ul=function(){function e(t){var i,r,n;E(this,e),this.model=t.model,this.material=t.material,this.sortId="LinesInstancingLayer",this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,r=i.id,(n=nl[r])||(n=new rl(i),nl[r]=n,n._compile(),i.on("compile",(function(){n._compile()})),i.on("destroyed",(function(){delete nl[r],n._destroy()}))),n),this._aabb=le.collapseAABB3(),this._state=new nt({obb:le.OBB3(),numInstances:0,origin:null,geometry:t.geometry,positionsDecodeMatrix:t.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=t.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=le.collapseAABB3(),this.aabbDirty=!0,t.origin&&(this._state.origin=le.vec3(t.origin)),this._finalized=!1,this.primitive=t.primitive}return I(e,[{key:"aabb",get:function(){if(this.aabbDirty){le.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e<t;e++)le.expandAABB3(this._aabb,this._meshes[e].aabb);this.aabbDirty=!1}return this._aabb}},{key:"createPortion",value:function(e,t){var i=t.color,r=t.opacity,n=t.meshMatrix;if(this._finalized)throw"Already finalized";var s=i[0],o=i[1],a=i[2];i[3],this._colors.push(s),this._colors.push(o),this._colors.push(a),this._colors.push(r),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(n[0]),this._modelMatrixCol0.push(n[4]),this._modelMatrixCol0.push(n[8]),this._modelMatrixCol0.push(n[12]),this._modelMatrixCol1.push(n[1]),this._modelMatrixCol1.push(n[5]),this._modelMatrixCol1.push(n[9]),this._modelMatrixCol1.push(n[13]),this._modelMatrixCol2.push(n[2]),this._modelMatrixCol2.push(n[6]),this._modelMatrixCol2.push(n[10]),this._modelMatrixCol2.push(n[14]),this._state.numInstances++;var l=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,this._meshes.push(e),l}},{key:"finalize",value:function(){if(this._finalized)throw"Already finalized";var e=this.model.scene.canvas.gl,t=this._state,i=t.geometry,r=this._colors.length,n=r/4;if(r>0){this._state.colorsBuf=new st(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,!1),this._colors=[]}if(n>0){this._state.flagsBuf=new st(e,e.ARRAY_BUFFER,new Float32Array(n),n,1,e.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){this._state.offsetsBuf=new st(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,!1),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){var s=new Uint8Array(i.colorsCompressed);t.colorsBuf=new st(e,e.ARRAY_BUFFER,s,s.length,4,e.STATIC_DRAW,!1)}if(i.positionsCompressed&&i.positionsCompressed.length>0){t.positionsBuf=new st(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,!1),t.positionsDecodeMatrix=le.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new st(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){var o=!1;this._state.modelMatrixCol0Buf=new st(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,o),this._state.modelMatrixCol1Buf=new st(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,o),this._state.modelMatrixCol2Buf=new st(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,o),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this.model.scene.readableGeometryEnabled||(this._state.geometry=null),this._finalized=!0}},{key:"initFlags",value:function(e,t,i){t&gs&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Bs&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ws&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&xs&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ys&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Ps&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&_s&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ms&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&gs?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Bs?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ws?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&xs?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ps?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&ys?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&_s?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ms?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";sl[0]=t[0],sl[1]=t[1],sl[2]=t[2],sl[3]=t[3],this._state.colorsBuf.setData(sl,4*e,4)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){if(!this._finalized)throw"Not finalized";var r=!!(t&gs),n=!!(t&ws),s=!!(t&Bs),o=!!(t&xs),a=!!(t&Ps),l=!!(t&_s),u=!!(t&ms),c=0;c|=!r||u||n||s&&!this.model.scene.highlightMaterial.glowThrough||o&&!this.model.scene.selectedMaterial.glowThrough?Cs.NOT_RENDERED:i?Cs.COLOR_TRANSPARENT:Cs.COLOR_OPAQUE,c|=(!r||u?Cs.NOT_RENDERED:o?Cs.SILHOUETTE_SELECTED:s?Cs.SILHOUETTE_HIGHLIGHTED:n?Cs.SILHOUETTE_XRAYED:Cs.NOT_RENDERED)<<4,c|=(!r||u?Cs.NOT_RENDERED:o?Cs.EDGES_SELECTED:s?Cs.EDGES_HIGHLIGHTED:n?Cs.EDGES_XRAYED:a?i?Cs.EDGES_COLOR_TRANSPARENT:Cs.EDGES_COLOR_OPAQUE:Cs.NOT_RENDERED)<<8,c|=(r&&!u&&l?Cs.PICK:Cs.NOT_RENDERED)<<12,c|=(t&ys?1:0)<<16,ol[0]=c,this._state.flagsBuf.setData(ol,e)}},{key:"setOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(al[0]=t[0],al[1]=t[1],al[2]=t[2],this._state.offsetsBuf.setData(al,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}},{key:"setMatrix",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=4*e;ll[0]=t[0],ll[1]=t[4],ll[2]=t[8],ll[3]=t[12],this._state.modelMatrixCol0Buf.setData(ll,i),ll[0]=t[1],ll[1]=t[5],ll[2]=t[9],ll[3]=t[13],this._state.modelMatrixCol1Buf.setData(ll,i),ll[0]=t[2],ll[1]=t[6],ll[2]=t[10],ll[3]=t[14],this._state.modelMatrixCol2Buf.setData(ll,i)}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE)}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Cs.COLOR_TRANSPARENT)}},{key:"drawDepth",value:function(e,t){}},{key:"drawNormals",value:function(e,t){}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_XRAYED)}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_HIGHLIGHTED)}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_SELECTED)}},{key:"drawEdgesColorOpaque",value:function(e,t){}},{key:"drawEdgesColorTransparent",value:function(e,t){}},{key:"drawEdgesXRayed",value:function(e,t){}},{key:"drawEdgesHighlighted",value:function(e,t){}},{key:"drawEdgesSelected",value:function(e,t){}},{key:"drawSnapInit",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Cs.PICK)}},{key:"drawSnap",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Cs.PICK)}},{key:"drawOcclusion",value:function(e,t){}},{key:"drawShadow",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){}},{key:"drawPickDepths",value:function(e,t){}},{key:"drawPickNormals",value:function(e,t){}},{key:"destroy",value:function(){var e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}]),e}(),cl=function(e){m(i,Ds);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,r=e.frameCtx,n=e.incrementDrawState;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),n&&r.drawArrays++}}]),i}(),Al=function(e){m(i,cl);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,r=[];return r.push("#version 300 es"),r.push("// Points batching color vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("in float flags;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),this._addMatricesUniformBlockLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),i.filterIntensity&&r.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("out vec4 vColor;"),r.push("void main(void) {"),r.push("int colorFlag = int(flags) & 0xF;"),r.push("if (colorFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {"),i.filterIntensity&&(r.push("float intensity = float(color.a) / 255.0;"),r.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {")),r.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix * worldPosition; "),r.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(r.push("vWorldPosition = worldPosition;"),r.push("vFlags = flags;")),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("gl_Position = clipPos;"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("}"),i.filterIntensity&&r.push("}"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Points batching color fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0,s=t.getNumAllocatedSectionPlanes();n<s;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),e.pointsMaterial.roundPoints&&(r.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),r.push(" float r = dot(cxy, cxy);"),r.push(" if (r > 1.0) {"),r.push(" discard;"),r.push(" }")),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o<a;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}return r.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}]),i}(),hl=function(e){m(i,cl);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points batching silhouette vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in float flags;"),this._addMatricesUniformBlockLines(r),r.push("uniform vec4 color;"),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("void main(void) {"),r.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),r.push("if (silhouetteFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {"),r.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(r.push("vWorldPosition = worldPosition;"),r.push("vFlags = flags;")),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("gl_Position = clipPos;"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("}"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,r=i._sectionPlanesState,n=r.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching silhouette vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),i.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),n)for(s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;"),e=0,t=r.getNumAllocatedSectionPlanes();e<t;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";");if(s.push("uniform vec4 color;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),n){for(s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;"),e=0,t=r.getNumAllocatedSectionPlanes();e<t;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return i.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}]),i}(),dl=function(e){m(i,cl);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points batching pick mesh vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in float flags;"),r.push("in vec4 pickColor;"),r.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(r),this._addRemapClipPosLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("out vec4 vPickColor;"),r.push("void main(void) {"),r.push("int pickFlag = int(flags) >> 12 & 0xF;"),r.push("if (pickFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push(" } else {"),r.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition; "),r.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(r.push(" vWorldPosition = worldPosition;"),r.push(" vFlags = flags;")),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("gl_PointSize += 10.0;"),r.push(" }"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Points batching pick mesh vertex shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0;n<t.getNumAllocatedSectionPlanes();n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec4 vPickColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),e.pointsMaterial.roundPoints&&(r.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),r.push(" float r = dot(cxy, cxy);"),r.push(" if (r > 1.0) {"),r.push(" discard;"),r.push(" }")),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.getNumAllocatedSectionPlanes();s++)r.push(" if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vPickColor; "),r.push("}"),r}}]),i}(),pl=function(e){m(i,cl);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points batched pick depth vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in float flags;"),r.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(r),this._addRemapClipPosLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("out vec4 vViewPosition;"),r.push("void main(void) {"),r.push("int pickFlag = int(flags) >> 12 & 0xF;"),r.push("if (pickFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push(" } else {"),r.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(r.push(" vWorldPosition = worldPosition;"),r.push(" vFlags = flags;")),r.push("vViewPosition = viewPosition;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("gl_PointSize += 10.0;"),r.push(" }"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Points batched pick depth fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform float pickZNear;"),r.push("uniform float pickZFar;"),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0;n<t.getNumAllocatedSectionPlanes();n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec4 vViewPosition;"),r.push("vec4 packDepth(const in float depth) {"),r.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),r.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),r.push(" vec4 res = fract(depth * bitShift);"),r.push(" res -= res.xxyz * bitMask;"),r.push(" return res;"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),e.pointsMaterial.roundPoints&&(r.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),r.push(" float r = dot(cxy, cxy);"),r.push(" if (r > 1.0) {"),r.push(" discard;"),r.push(" }")),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.getNumAllocatedSectionPlanes();s++)r.push(" if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),r.push(" outColor = packDepth(zNormalizedDepth); "),r.push("}"),r}}]),i}(),fl=function(e){m(i,cl);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points batching occlusion vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in float flags;"),this._addMatricesUniformBlockLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("void main(void) {"),r.push("int colorFlag = int(flags) & 0xF;"),r.push("if (colorFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push(" } else {"),r.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(r.push(" vWorldPosition = worldPosition;"),r.push(" vFlags = flags;")),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push(" gl_Position = clipPos;"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push(" }"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Points batching occlusion fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0;n<t.getNumAllocatedSectionPlanes();n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("out vec4 outColor;"),r.push("void main(void) {"),e.pointsMaterial.roundPoints&&(r.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),r.push(" float r = dot(cxy, cxy);"),r.push(" if (r > 1.0) {"),r.push(" discard;"),r.push(" }")),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.getNumAllocatedSectionPlanes();s++)r.push(" if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push(" }");r.push(" if (dist > 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),r.push("}"),r}}]),i}(),vl=le.vec3(),gl=le.vec3(),ml=le.vec3(),_l=le.vec3(),yl=le.mat4(),bl=function(e){m(i,Ds);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,n=r.scene,s=n.camera,o=n.canvas.gl,a=t._state,l=t._state.origin,u=r.position,c=r.rotationMatrix,A=t.aabb,h=e.pickViewMatrix||s.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var d,p,f=vl;if(f[0]=le.safeInv(A[3]-A[0])*le.MAX_INT,f[1]=le.safeInv(A[4]-A[1])*le.MAX_INT,f[2]=le.safeInv(A[5]-A[2])*le.MAX_INT,e.snapPickCoordinateScale[0]=le.safeInv(f[0]),e.snapPickCoordinateScale[1]=le.safeInv(f[1]),e.snapPickCoordinateScale[2]=le.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=gl;if(l){var g=ml;le.transformPoint3(c,l,g),v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],d=Jt(h,v,yl),(p=_l)[0]=s.eye[0]-v[0],p[1]=s.eye[1]-v[1],p[2]=s.eye[2]-v[2],e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else d=h,p=s.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,p),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible),o.uniform1f(this._uPointSize,1);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(d,m+=16),this._matricesUniformBlockBufferData.set(s.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),o.drawArrays(o.POINTS,0,a.positionsBuf.numItems),o.bindVertexArray(null)}}},{key:"_allocate",value:function(){v(x(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler"),this._uPointSize=e.getLocation("pointSize")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float pointSize;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = pointSize;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var r=0;r<e.getNumAllocatedSectionPlanes();r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<e.getNumAllocatedSectionPlanes();n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),wl=le.vec3(),Bl=le.vec3(),xl=le.vec3(),Pl=le.vec3(),Cl=le.mat4(),Ml=function(e){m(i,Ds);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,n=r.scene,s=n.camera,o=n.canvas.gl,a=t._state,l=t._state.origin,u=r.position,c=r.rotationMatrix,A=t.aabb,h=e.pickViewMatrix||s.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var d,p,f=wl;if(f[0]=le.safeInv(A[3]-A[0])*le.MAX_INT,f[1]=le.safeInv(A[4]-A[1])*le.MAX_INT,f[2]=le.safeInv(A[5]-A[2])*le.MAX_INT,e.snapPickCoordinateScale[0]=le.safeInv(f[0]),e.snapPickCoordinateScale[1]=le.safeInv(f[1]),e.snapPickCoordinateScale[2]=le.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=Bl;if(l){var g=xl;le.transformPoint3(c,l,g),v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],d=Jt(h,v,Cl),(p=Pl)[0]=s.eye[0]-v[0],p[1]=s.eye[1]-v[1],p[2]=s.eye[2]-v[2],e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else d=h,p=s.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,p),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(d,m+=16),this._matricesUniformBlockBufferData.set(s.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),o.drawArrays(o.POINTS,0,a.positionsBuf.numItems),o.bindVertexArray(null)}}},{key:"_allocate",value:function(){v(x(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;var i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r<e.getNumAllocatedSectionPlanes();r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<e.getNumAllocatedSectionPlanes();n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),kl=function(){function e(t){E(this,e),this._scene=t}return I(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Al(this._scene)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new hl(this._scene)),this._silhouetteRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new dl(this._scene)),this._pickMeshRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new pl(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new fl(this._scene)),this._occlusionRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new bl(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new Ml(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),El={};var Fl=function(){function e(t){E(this,e),this.model=t.model,this.sortId="PointsBatchingLayer",this.layerIndex=t.layerIndex,this._renderers=function(e){var t=e.id,i=El[t];return i||(i=new kl(e),El[t]=i,i._compile(),e.on("compile",(function(){i._compile()})),e.on("destroyed",(function(){delete El[t],i._destroy()}))),i}(t.model.scene);var i=t.maxGeometryBatchSize||5e6,r=function(){var e=[];return{append:function(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;e.push({data:t,times:i,denormalizeScale:r})},compileBuffer:function(t){var i=0;e.forEach((function(e){i+=e.times*e.data.length}));var r=new t(i),n=0;return e.forEach((function(e){var t=e.data,i=e.denormalizeScale,s=r.subarray(n);if(1===i)s.set(t,0);else for(var o=0;o<t.length;++o)s[o]=t[o]*i;for(var a=t.length,l=e.times*t.length;a<l;){var u=Math.min(a,l-a);s.set(s.subarray(0,u),a),a+=u}n+=a})),r}}};this._buffer={maxVerts:i,positions:r(),colors:r(),pickColors:r(),vertsIndex:0},this._scratchMemory=t.scratchMemory,this._state=new nt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:le.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=le.collapseAABB3(),this._portions=[],this._meshes=[],this._aabb=le.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,t.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(t.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,t.origin&&(this._state.origin=le.vec3(t.origin))}return I(e,[{key:"aabb",get:function(){if(this.aabbDirty){le.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e<t;e++)le.expandAABB3(this._aabb,this._meshes[e].aabb);this.aabbDirty=!1}return this._aabb}},{key:"canCreatePortion",value:function(e){if(this._finalized)throw"Already finalized";return this._buffer.vertsIndex+e/3<=this._buffer.maxVerts}},{key:"createPortion",value:function(e,t){if(this._finalized)throw"Already finalized";var i=this._buffer,r=this._preCompressedPositionsExpected?t.positionsCompressed:t.positions;if(!r)throw(this._preCompressedPositionsExpected?"positionsCompressed":"positions")+" expected";i.positions.append(r);var n=r.length/3,s=t.color,o=t.colorsCompressed,a=t.colors,l=t.pickColor;o?i.colors.append(o):a?i.colors.append(a,1,255):s&&i.colors.append([s[0],s[1],s[2],1],n),i.pickColors.append(l.slice(0,4),n),le.expandAABB3(this._modelAABB,t.aabb);var u=this._portions.length/2;return this._portions.push(this._buffer.vertsIndex),this._portions.push(n),this._buffer.vertsIndex+=n,this._numPortions++,this.model.numPortions++,this._meshes.push(e),u}},{key:"finalize",value:function(){if(!this._finalized){var e=this._state,t=this.model.scene.canvas.gl,i=this._buffer,r=function(e,i,r){return e.length>0?new st(t,t.ARRAY_BUFFER,e,e.length,i,r):null},n=this._preCompressedPositionsExpected?i.positions.compileBuffer(Uint16Array):_o(i.positions.compileBuffer(Float32Array),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=r(n,3,t.STATIC_DRAW),e.flagsBuf=r(new Float32Array(this._buffer.vertsIndex),1,t.DYNAMIC_DRAW),e.colorsBuf=r(i.colors.compileBuffer(Uint8Array),4,t.STATIC_DRAW),e.pickColorsBuf=r(i.pickColors.compileBuffer(Uint8Array),4,t.STATIC_DRAW),e.offsetsBuf=this.model.scene.entityOffsetsEnabled?r(new Float32Array(3*this._buffer.vertsIndex),3,t.DYNAMIC_DRAW):null,this._buffer=null,this._finalized=!0}}},{key:"initFlags",value:function(e,t,i){t&gs&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Bs&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ws&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&xs&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ys&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&_s&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ms&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&gs?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Bs?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ws?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&xs?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized"}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&ys?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ms?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&_s?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";for(var i=2*e,r=4*this._portions[i],n=4*this._portions[i+1],s=this._scratchMemory.getUInt8Array(n),o=t[0],a=t[1],l=t[2],u=0;u<n;u+=4)s[u+0]=o,s[u+1]=a,s[u+2]=l;this._state.colorsBuf.setData(s,r,n)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){if(!this._finalized)throw"Not finalized";var r,n,s=2*e,o=this._portions[s],a=this._portions[s+1],l=this._scratchMemory.getFloat32Array(a),u=!!(t&gs),c=!!(t&ws),A=!!(t&Bs),h=!!(t&xs),d=!!(t&_s),p=!!(t&ms);r=!u||p||c||A&&!this.model.scene.highlightMaterial.glowThrough||h&&!this.model.scene.selectedMaterial.glowThrough?Cs.NOT_RENDERED:i?Cs.COLOR_TRANSPARENT:Cs.COLOR_OPAQUE,n=!u||p?Cs.NOT_RENDERED:h?Cs.SILHOUETTE_SELECTED:A?Cs.SILHOUETTE_HIGHLIGHTED:c?Cs.SILHOUETTE_XRAYED:Cs.NOT_RENDERED;for(var f=u&&!p&&d?Cs.PICK:Cs.NOT_RENDERED,v=t&ys?1:0,g=0;g<a;g++){var m=0;m|=r,m|=n<<4,m|=f<<12,m|=v<<16,l[g]=m}this._state.flagsBuf.setData(l,o)}},{key:"setOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";if(this.model.scene.entityOffsetsEnabled){for(var i=2*e,r=3*this._portions[i],n=3*this._portions[i+1],s=this._scratchMemory.getFloat32Array(n),o=t[0],a=t[1],l=t[2],u=0;u<n;u+=3)s[u+0]=o,s[u+1]=a,s[u+2]=l;this._state.offsetsBuf.setData(s,r,n)}else this.model.error("Entity#offset not enabled for this Viewer")}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE)}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Cs.COLOR_TRANSPARENT)}},{key:"drawDepth",value:function(e,t){}},{key:"drawNormals",value:function(e,t){}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_XRAYED)}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_HIGHLIGHTED)}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_SELECTED)}},{key:"drawEdgesColorOpaque",value:function(e,t){}},{key:"drawEdgesColorTransparent",value:function(e,t){}},{key:"drawEdgesHighlighted",value:function(e,t){}},{key:"drawEdgesSelected",value:function(e,t){}},{key:"drawEdgesXRayed",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Cs.PICK)}},{key:"drawPickDepths",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Cs.PICK)}},{key:"drawPickNormals",value:function(e,t){}},{key:"drawSnapInit",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Cs.PICK)}},{key:"drawSnap",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Cs.PICK)}},{key:"drawOcclusion",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE)}},{key:"drawShadow",value:function(e,t){}},{key:"destroy",value:function(){var e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}]),e}(),Il=function(e){m(i,Ds);var t=y(i);function i(e,r){return E(this,i),t.call(this,e,r,{instancing:!0})}return I(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,r=e.frameCtx,n=e.incrementDrawState;t.drawArraysInstanced(t.POINTS,0,i.positionsBuf.numItems,i.numInstances),n&&r.drawArrays++}}]),i}(),Tl=function(e){m(i,Il);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points instancing color vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("in float flags;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in vec4 modelMatrixCol0;"),r.push("in vec4 modelMatrixCol1;"),r.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),i.filterIntensity&&r.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("out vec4 vColor;"),r.push("void main(void) {"),r.push("int colorFlag = int(flags) & 0xF;"),r.push("if (colorFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {"),i.filterIntensity&&(r.push("float intensity = float(color.a) / 255.0;"),r.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {")),r.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),r.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix * worldPosition; "),r.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(r.push("vWorldPosition = worldPosition;"),r.push("vFlags = flags;")),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("gl_Position = clipPos;"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("}"),i.filterIntensity&&r.push("}"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Points instancing color fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0,s=t.getNumAllocatedSectionPlanes();n<s;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),e.pointsMaterial.roundPoints&&(r.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),r.push(" float r = dot(cxy, cxy);"),r.push(" if (r > 1.0) {"),r.push(" discard;"),r.push(" }")),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o<a;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push("if (dist > 0.0) { discard; }"),r.push("}")}return r.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}]),i}(),Dl=function(e){m(i,Il);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,r){v(x(i.prototype),"drawLayer",this).call(this,e,t,r,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points instancing silhouette vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in float flags;"),r.push("in vec4 color;"),r.push("in vec4 modelMatrixCol0;"),r.push("in vec4 modelMatrixCol1;"),r.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),r.push("uniform vec4 silhouetteColor;"),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("out vec4 vColor;"),r.push("void main(void) {"),r.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),r.push("if (silhouetteFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {"),r.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),r.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(r.push("vWorldPosition = worldPosition;"),r.push("vFlags = flags;")),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),r.push("gl_Position = clipPos;"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("}"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Points instancing silhouette fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0,s=t.getNumAllocatedSectionPlanes();n<s;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),e.pointsMaterial.roundPoints&&(r.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),r.push(" float r = dot(cxy, cxy);"),r.push(" if (r > 1.0) {"),r.push(" discard;"),r.push(" }")),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o<a;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push("if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = vColor;"),r.push("}"),r}}]),i}(),Sl=function(e){m(i,Il);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points instancing pick mesh vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in float flags;"),r.push("in vec4 pickColor;"),r.push("in vec4 modelMatrixCol0;"),r.push("in vec4 modelMatrixCol1;"),r.push("in vec4 modelMatrixCol2;"),r.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(r),this._addRemapClipPosLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("out vec4 vPickColor;"),r.push("void main(void) {"),r.push("int pickFlag = int(flags) >> 12 & 0xF;"),r.push("if (pickFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {"),r.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),r.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition; "),r.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(r.push(" vWorldPosition = worldPosition;"),r.push(" vFlags = flags;")),r.push("vec4 clipPos = projMatrix * viewPosition;"),r.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("}"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Points instancing pick mesh fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0;n<t.getNumAllocatedSectionPlanes();n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec4 vPickColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),e.pointsMaterial.roundPoints&&(r.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),r.push(" float r = dot(cxy, cxy);"),r.push(" if (r > 1.0) {"),r.push(" discard;"),r.push(" }")),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.getNumAllocatedSectionPlanes();s++)r.push("if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push("}");r.push("if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = vPickColor; "),r.push("}"),r}}]),i}(),Rl=function(e){m(i,Il);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points instancing pick depth vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in float flags;"),r.push("in vec4 modelMatrixCol0;"),r.push("in vec4 modelMatrixCol1;"),r.push("in vec4 modelMatrixCol2;"),r.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(r),this._addRemapClipPosLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("out vec4 vViewPosition;"),r.push("void main(void) {"),r.push("int pickFlag = int(flags) >> 12 & 0xF;"),r.push("if (pickFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {"),r.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),r.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(r.push(" vWorldPosition = worldPosition;"),r.push(" vFlags = flags;")),r.push(" vViewPosition = viewPosition;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),r.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("}"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Points instancing pick depth fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform float pickZNear;"),r.push("uniform float pickZFar;"),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0;n<t.getNumAllocatedSectionPlanes();n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec4 vViewPosition;"),r.push("vec4 packDepth(const in float depth) {"),r.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),r.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),r.push(" vec4 res = fract(depth * bitShift);"),r.push(" res -= res.xxyz * bitMask;"),r.push(" return res;"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),e.pointsMaterial.roundPoints&&(r.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),r.push(" float r = dot(cxy, cxy);"),r.push(" if (r > 1.0) {"),r.push(" discard;"),r.push(" }")),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.getNumAllocatedSectionPlanes();s++)r.push("if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push("}");r.push("if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),r.push(" outColor = packDepth(zNormalizedDepth); "),r.push("}"),r}}]),i}(),Ul=function(e){m(i,Il);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points instancing occlusion vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in vec4 color;"),r.push("in float flags;"),r.push("in vec4 modelMatrixCol0;"),r.push("in vec4 modelMatrixCol1;"),r.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("void main(void) {"),r.push("int colorFlag = int(flags) & 0xF;"),r.push("if (colorFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {"),r.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),r.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(r.push(" vWorldPosition = worldPosition;"),r.push("vFlags = flags;")),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("gl_Position = clipPos;"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("}"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Points instancing occlusion vertex shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0;n<t.getNumAllocatedSectionPlanes();n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("out vec4 outColor;"),r.push("void main(void) {"),e.pointsMaterial.roundPoints&&(r.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),r.push(" float r = dot(cxy, cxy);"),r.push(" if (r > 1.0) {"),r.push(" discard;"),r.push(" }")),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var s=0;s<t.getNumAllocatedSectionPlanes();s++)r.push("if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push("}");r.push("if (dist > 0.0) { discard; }"),r.push("}")}return r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}]),i}(),Ll=function(e){m(i,Il);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points instancing depth vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in float flags;"),r.push("in vec4 modelMatrixCol0;"),r.push("in vec4 modelMatrixCol1;"),r.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("void main(void) {"),r.push("int colorFlag = int(flags) & 0xF;"),r.push("if (colorFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {"),r.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),r.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(r.push("vWorldPosition = worldPosition;"),r.push("vFlags = flags;")),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("gl_Position = clipPos;"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("}"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,r=i._sectionPlanesState,n=r.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing depth vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),i.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),n)for(s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;"),e=0,t=r.getNumAllocatedSectionPlanes();e<t;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";");if(s.push("const float packUpScale = 256. / 255.;"),s.push("const float unpackDownscale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. );"),s.push("const float shiftRight8 = 1.0 / 256.;"),s.push("vec4 packDepthToRGBA( const in float v ) {"),s.push(" vec4 r = vec4( fract( v * packFactors ), v );"),s.push(" r.yzw -= r.xyz * shiftRight8;"),s.push(" return r * packUpScale;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),n){for(s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;"),e=0,t=r.getNumAllocatedSectionPlanes();e<t;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return s.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),i.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}]),i}(),Ol=function(e){m(i,Il);var t=y(i);function i(){return E(this,i),t.apply(this,arguments)}return I(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Instancing geometry depth drawing fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0,s=t.getNumAllocatedSectionPlanes();n<s;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec3 vViewNormal;"),r.push("vec3 packNormalToRGB( const in vec3 normal ) {"),r.push(" return normalize( normal ) * 0.5 + 0.5;"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),r.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),r.push(" float r = dot(cxy, cxy);"),r.push(" if (r > 1.0) {"),r.push(" discard;"),r.push(" }"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o<a;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push("if (dist > 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),r.push("}"),r}}]),i}(),Nl=le.vec3(),Vl=le.vec3(),Ql=le.vec3();le.vec3();var Hl=le.mat4(),jl=function(e){m(i,Ds);var t=y(i);function i(e){return E(this,i),t.call(this,e,!1,{instancing:!0})}return I(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,n=r.scene,s=n.canvas.gl,o=n.camera,a=t._state,l=t._state.origin,u=r.position,c=r.rotationMatrix,A=t.aabb,h=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?s.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var d,p=Nl;if(p[0]=le.safeInv(A[3]-A[0])*le.MAX_INT,p[1]=le.safeInv(A[4]-A[1])*le.MAX_INT,p[2]=le.safeInv(A[5]-A[2])*le.MAX_INT,e.snapPickCoordinateScale[0]=le.safeInv(p[0]),e.snapPickCoordinateScale[1]=le.safeInv(p[1]),e.snapPickCoordinateScale[2]=le.safeInv(p[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var f=Vl;if(l){var v=le.transformPoint3(c,l,Ql);f[0]=v[0],f[1]=v[1],f[2]=v[2]}else f[0]=0,f[1]=0,f[2]=0;f[0]+=u[0],f[1]+=u[1],f[2]+=u[2],d=Jt(h,f,Hl),e.snapPickOrigin[0]=f[0],e.snapPickOrigin[1]=f[1],e.snapPickOrigin[2]=f[2]}else d=h,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;s.uniform2fv(this.uVectorA,e.snapVectorA),s.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),s.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),s.uniform3fv(this._uCoordinateScaler,p),s.uniform1i(this._uRenderPass,i),s.uniform1i(this._uPickInvisible,e.pickInvisible);var g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(d,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),s.bindBuffer(s.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),s.bufferData(s.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,s.DYNAMIC_DRAW),s.bindBufferBase(s.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var m=2/(Math.log(e.pickZFar+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,m),this.setSectionPlanesStateUniforms(t),s.drawArraysInstanced(s.POINTS,0,a.positionsBuf.numItems,a.numInstances),s.bindVertexArray(null)}}},{key:"_allocate",value:function(){v(x(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var r=0;r<e.getNumAllocatedSectionPlanes();r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<e.getNumAllocatedSectionPlanes();n++)i.push("if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Gl=le.vec3(),zl=le.vec3(),Wl=le.vec3();le.vec3();var Xl=le.mat4(),Kl=function(e){m(i,Ds);var t=y(i);function i(e){return E(this,i),t.call(this,e,!1,{instancing:!0})}return I(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,n=r.scene,s=n.camera,o=n.canvas.gl,a=t._state,l=t._state.origin,u=r.position,c=r.rotationMatrix,A=t.aabb,h=e.pickViewMatrix||s.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var d,p=Gl;if(p[0]=le.safeInv(A[3]-A[0])*le.MAX_INT,p[1]=le.safeInv(A[4]-A[1])*le.MAX_INT,p[2]=le.safeInv(A[5]-A[2])*le.MAX_INT,e.snapPickCoordinateScale[0]=le.safeInv(p[0]),e.snapPickCoordinateScale[1]=le.safeInv(p[1]),e.snapPickCoordinateScale[2]=le.safeInv(p[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var f=zl;if(l){var v=le.transformPoint3(c,l,Wl);f[0]=v[0],f[1]=v[1],f[2]=v[2]}else f[0]=0,f[1]=0,f[2]=0;f[0]+=u[0],f[1]+=u[1],f[2]+=u[2],d=Jt(h,f,Xl),e.snapPickOrigin[0]=f[0],e.snapPickOrigin[1]=f[1],e.snapPickOrigin[2]=f[2]}else d=h,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,p),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(d,g+=16),this._matricesUniformBlockBufferData.set(s.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var m=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,m),this.setSectionPlanesStateUniforms(t),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.bindVertexArray(null)}}},{key:"_allocate",value:function(){v(x(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r<e.getNumAllocatedSectionPlanes();r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<e.getNumAllocatedSectionPlanes();n++)i.push("if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Zl=function(){function e(t){E(this,e),this._scene=t}return I(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Tl(this._scene,!1)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Dl(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new Ll(this._scene)),this._depthRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Sl(this._scene)),this._pickMeshRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Rl(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new Ul(this._scene)),this._occlusionRenderer}},{key:"shadowRenderer",get:function(){return this._shadowRenderer||(this._shadowRenderer=new Ol(this._scene)),this._shadowRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new jl(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new Kl(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Jl={};var Yl=new Uint8Array(4),ql=new Float32Array(1),$l=new Float32Array(3),eu=new Float32Array(4),tu=function(){function e(t){var i,r,n;E(this,e),this.model=t.model,this.material=t.material,this.sortId="PointsInstancingLayer",this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,r=i.id,(n=Jl[r])||(n=new Zl(i),Jl[r]=n,n._compile(),i.on("compile",(function(){n._compile()})),i.on("destroyed",(function(){delete Jl[r],n._destroy()}))),n),this._aabb=le.collapseAABB3(),this._state=new nt({obb:le.OBB3(),numInstances:0,origin:t.origin?le.vec3(t.origin):null,geometry:t.geometry,positionsDecodeMatrix:t.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=t.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=le.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,this.primitive=t.geometry.primitive}return I(e,[{key:"aabb",get:function(){if(this.aabbDirty){le.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e<t;e++)le.expandAABB3(this._aabb,this._meshes[e].aabb);this.aabbDirty=!1}return this._aabb}},{key:"createPortion",value:function(e,t){var i=t.meshMatrix,r=t.pickColor;if(this._finalized)throw"Already finalized";this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(i[0]),this._modelMatrixCol0.push(i[4]),this._modelMatrixCol0.push(i[8]),this._modelMatrixCol0.push(i[12]),this._modelMatrixCol1.push(i[1]),this._modelMatrixCol1.push(i[5]),this._modelMatrixCol1.push(i[9]),this._modelMatrixCol1.push(i[13]),this._modelMatrixCol2.push(i[2]),this._modelMatrixCol2.push(i[6]),this._modelMatrixCol2.push(i[10]),this._modelMatrixCol2.push(i[14]),this._pickColors.push(r[0]),this._pickColors.push(r[1]),this._pickColors.push(r[2]),this._pickColors.push(r[3]),this._state.numInstances++;var n=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,this._meshes.push(e),n}},{key:"finalize",value:function(){if(this._finalized)throw"Already finalized";var e=this.model.scene.canvas.gl,t=this._pickColors.length/4,i=this._state,r=i.geometry;if(t>0){i.flagsBuf=new st(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){i.offsetsBuf=new st(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,!1),this._offsets=[]}if(r.positionsCompressed&&r.positionsCompressed.length>0){i.positionsBuf=new st(e,e.ARRAY_BUFFER,r.positionsCompressed,r.positionsCompressed.length,3,e.STATIC_DRAW,!1),i.positionsDecodeMatrix=le.mat4(r.positionsDecodeMatrix)}if(r.colorsCompressed&&r.colorsCompressed.length>0){var n=new Uint8Array(r.colorsCompressed);i.colorsBuf=new st(e,e.ARRAY_BUFFER,n,n.length,4,e.STATIC_DRAW,!1)}if(this._modelMatrixCol0.length>0){var s=!1;i.modelMatrixCol0Buf=new st(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,s),i.modelMatrixCol1Buf=new st(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,s),i.modelMatrixCol2Buf=new st(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,s),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){i.pickColorsBuf=new st(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,!1),this._pickColors=[]}i.geometry=null,this._finalized=!0}},{key:"initFlags",value:function(e,t,i){t&gs&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Bs&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ws&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&xs&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ys&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Ps&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&_s&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ms&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&gs?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Bs?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ws?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&xs?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ps?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&ys?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&_s?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ms?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";Yl[0]=t[0],Yl[1]=t[1],Yl[2]=t[2],this._state.colorsBuf.setData(Yl,3*e)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){if(!this._finalized)throw"Not finalized";var r=!!(t&gs),n=!!(t&ws),s=!!(t&Bs),o=!!(t&xs),a=!!(t&Ps),l=!!(t&_s),u=!!(t&ms),c=0;c|=!r||u||n||s&&!this.model.scene.highlightMaterial.glowThrough||o&&!this.model.scene.selectedMaterial.glowThrough?Cs.NOT_RENDERED:i?Cs.COLOR_TRANSPARENT:Cs.COLOR_OPAQUE,c|=(!r||u?Cs.NOT_RENDERED:o?Cs.SILHOUETTE_SELECTED:s?Cs.SILHOUETTE_HIGHLIGHTED:n?Cs.SILHOUETTE_XRAYED:Cs.NOT_RENDERED)<<4,c|=(!r||u?Cs.NOT_RENDERED:o?Cs.EDGES_SELECTED:s?Cs.EDGES_HIGHLIGHTED:n?Cs.EDGES_XRAYED:a?i?Cs.EDGES_COLOR_TRANSPARENT:Cs.EDGES_COLOR_OPAQUE:Cs.NOT_RENDERED)<<8,c|=(r&&!u&&l?Cs.PICK:Cs.NOT_RENDERED)<<12,c|=(t&ys?255:0)<<16,ql[0]=c,this._state.flagsBuf.setData(ql,e)}},{key:"setOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?($l[0]=t[0],$l[1]=t[1],$l[2]=t[2],this._state.offsetsBuf.setData($l,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}},{key:"setMatrix",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=4*e;eu[0]=t[0],eu[1]=t[4],eu[2]=t[8],eu[3]=t[12],this._state.modelMatrixCol0Buf.setData(eu,i),eu[0]=t[1],eu[1]=t[5],eu[2]=t[9],eu[3]=t[13],this._state.modelMatrixCol1Buf.setData(eu,i),eu[0]=t[2],eu[1]=t[6],eu[2]=t[10],eu[3]=t[14],this._state.modelMatrixCol2Buf.setData(eu,i)}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE)}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Cs.COLOR_TRANSPARENT)}},{key:"drawDepth",value:function(e,t){}},{key:"drawNormals",value:function(e,t){}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_XRAYED)}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_HIGHLIGHTED)}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_SELECTED)}},{key:"drawEdgesColorOpaque",value:function(e,t){}},{key:"drawEdgesColorTransparent",value:function(e,t){}},{key:"drawEdgesHighlighted",value:function(e,t){}},{key:"drawEdgesSelected",value:function(e,t){}},{key:"drawEdgesXRayed",value:function(e,t){}},{key:"drawOcclusion",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE)}},{key:"drawShadow",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Cs.PICK)}},{key:"drawPickDepths",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Cs.PICK)}},{key:"drawPickNormals",value:function(e,t){}},{key:"drawSnapInit",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Cs.PICK)}},{key:"drawSnap",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Cs.PICK)}},{key:"destroy",value:function(){var e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}]),e}(),iu=le.vec3(),ru=le.vec3(),nu=le.mat4(),su=function(){function e(t){E(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var r=this._scene,n=r.camera,s=t.model,o=r.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,c=s.position,A=s.rotationMatrix,h=n.viewMatrix;if(this._program||(this._allocate(),!this.errors)){var d;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);var p=0!==u[0]||0!==u[1]||0!==u[2],f=0!==c[0]||0!==c[1]||0!==c[2];if(p||f){var v=iu;if(p){var g=le.transformPoint3(A,u,ru);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=c[0],v[1]+=c[1],v[2]+=c[2],d=Jt(h,v,nu)}else d=h;if(o.uniformMatrix4fv(this._uSceneModelMatrix,!1,A),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix),o.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){var m=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,m)}var _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),y=r._sectionPlanesState.sectionPlanes.length;if(_>0)for(var b=r._sectionPlanesState.sectionPlanes,w=t.layerIndex*y,B=s.renderFlags,x=0;x<_;x++){var P=this._uSectionPlanes[x];if(P)if(x<y){var C=B.sectionPlanesActivePerLayer[w+x];if(o.uniform1i(P.active,C?1:0),C){var M=b[x];if(u){var k=ei(M.dist,M.dir,u,iu,s.matrix);o.uniform3fv(P.pos,k)}else o.uniform3fv(P.pos,M.pos);o.uniform3fv(P.dir,M.dir)}}else o.uniform1i(P.active,0)}a.numIndices8Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),o.drawArrays(o.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),o.drawArrays(o.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),o.drawArrays(o.LINES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Pr(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=e._sectionPlanesState.getNumAllocatedSectionPlanes();r<n;r++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+r),pos:i.getLocation("sectionPlanePos"+r),dir:i.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uPerObjectDecodeMatrix="uPerObjectDecodeMatrix",this.uPerObjectColorAndFlags="uPerObjectColorAndFlags",this._uPerVertexPosition="uPerVertexPosition",this._uPerLineIndices="uPerLineIndices",this._uPerLineObject="uPerLineObject",this._uPerObjectMatrix="uPerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}},{key:"_bindProgram",value:function(e){var t=this._scene,i=t.canvas.gl,r=this._program,n=t.camera.project;if(r.bind(),t.logarithmicDepthBufferEnabled){var s=2/(Math.log(n.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,s)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// LinesDataTextureColorRenderer fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var n=0,s=t.getNumAllocatedSectionPlanes();n<s;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o<a;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vColor;"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),ou=function(){function e(t){E(this,e),this._scene=t}return I(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}},{key:"eagerCreateRenders",value:function(){}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new su(this._scene,!1)),this._colorRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy()}}]),e}(),au={};var lu=I((function e(){E(this,e),this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]})),uu=function(){function e(){E(this,e),this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}return I(e,[{key:"finalize",value:function(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}},{key:"bindCommonTextures",value:function(e,t,i,r,n){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,r,3),this.texturePerObjectInstanceMatrices.bindTexture(e,n,4)}},{key:"bindLineIndicesTextures",value:function(e,t,i,r){this.indicesPortionIdsPerBitnessTextures[r].bindTexture(e,t,5),this.indicesPerBitnessTextures[r].bindTexture(e,i,6)}}]),e}(),cu=function(){function e(t,i,r,n){var s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;E(this,e),this._gl=t,this._texture=i,this._textureWidth=r,this._textureHeight=n,this._textureData=s}return I(e,[{key:"bindTexture",value:function(e,t,i){return e.bindTexture(t,this,i)}},{key:"bind",value:function(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}},{key:"unbind",value:function(e){}}]),e}(),Au={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Au,null,4));var e=0;Object.keys(Au).forEach((function(t){t.startsWith("size")&&(e+=Au[t])})),console.log("Total size ".concat(e," bytes (").concat((e/1e3/1e3).toFixed(2)," MB)")),console.log("Avg bytes / triangle: ".concat((e/Au.totalLines).toFixed(2)));var t={};Object.keys(Au).forEach((function(i){i.startsWith("size")&&(t[i]="".concat((Au[i]/e*100).toFixed(2)," % of total"))})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};var hu=function(){function e(){E(this,e)}return I(e,[{key:"disableBindedTextureFiltering",value:function(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}},{key:"generateTextureForColorsAndFlags",value:function(e,t,i,r,n){var s=t.length;this.numPortions=s;var o=4096,a=Math.ceil(s/512);if(0===a)throw"texture height===0";var l=new Uint8Array(16384*a);Au.sizeDataColorsAndFlags+=l.byteLength,Au.numberOfTextures++;for(var u=0;u<s;u++)l.set(t[u],32*u+0),l.set(i[u],32*u+4),l.set([0,0,0,0],32*u+8),l.set([0,0,0,0],32*u+12),l.set([r[u]>>24&255,r[u]>>16&255,r[u]>>8&255,255&r[u]],32*u+16),l.set([n[u]>>24&255,n[u]>>16&255,n[u]>>8&255,255&n[u]],32*u+20);var c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,o,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,o,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new cu(e,c,o,a,l)}},{key:"generateTextureForObjectOffsets",value:function(e,t){var i=512,r=Math.ceil(t/i);if(0===r)throw"texture height===0";var n=new Float32Array(1536*r).fill(0);Au.sizeDataTextureOffsets+=n.byteLength,Au.numberOfTextures++;var s=e.createTexture();return e.bindTexture(e.TEXTURE_2D,s),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,r,e.RGB,e.FLOAT,n,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new cu(e,s,i,r,n)}},{key:"generateTextureForInstancingMatrices",value:function(e,t){var i=t.length;if(0===i)throw"num instance matrices===0";var r=2048,n=Math.ceil(i/512),s=new Float32Array(8192*n);Au.numberOfTextures++;for(var o=0;o<t.length;o++)s.set(t[o],16*o);var a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,r,n),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RGBA,e.FLOAT,s,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new cu(e,a,r,n,s)}},{key:"generateTextureForPositionsDecodeMatrices",value:function(e,t){var i=t.length;if(0===i)throw"num decode+entity matrices===0";var r=2048,n=Math.ceil(i/512),s=new Float32Array(8192*n);Au.sizeDataPositionDecodeMatrices+=s.byteLength,Au.numberOfTextures++;for(var o=0;o<t.length;o++)s.set(t[o],16*o);var a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,r,n),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RGBA,e.FLOAT,s,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new cu(e,a,r,n)}},{key:"generateTextureFor8BitIndices",value:function(e,t,i){if(0===i)return{texture:null,textureHeight:0};var r=4096,n=Math.ceil(i/3/r);if(0===n)throw"texture height===0";var s=new Uint8Array(r*n*3);Au.sizeDataTextureIndices+=s.byteLength,Au.numberOfTextures++;for(var o=0,a=0,l=t.length;o<l;o++){var u=t[o];s.set(u,a),a+=u.length}var c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RGB8UI,r,n),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RGB_INTEGER,e.UNSIGNED_BYTE,s,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new cu(e,c,r,n)}},{key:"generateTextureFor16BitIndices",value:function(e,t,i){if(0===i)return{texture:null,textureHeight:0};var r=4096,n=Math.ceil(i/3/r);if(0===n)throw"texture height===0";var s=new Uint16Array(r*n*3);Au.sizeDataTextureIndices+=s.byteLength,Au.numberOfTextures++;for(var o=0,a=0,l=t.length;o<l;o++){var u=t[o];s.set(u,a),a+=u.length}var c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,r,n),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RGB_INTEGER,e.UNSIGNED_SHORT,s,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new cu(e,c,r,n)}},{key:"generateTextureFor32BitIndices",value:function(e,t,i){if(0===i)return{texture:null,textureHeight:0};var r=4096,n=Math.ceil(i/3/r);if(0===n)throw"texture height===0";var s=new Uint32Array(r*n*3);Au.sizeDataTextureIndices+=s.byteLength,Au.numberOfTextures++;for(var o=0,a=0,l=t.length;o<l;o++){var u=t[o];s.set(u,a),a+=u.length}var c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32UI,r,n),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RGB_INTEGER,e.UNSIGNED_INT,s,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new cu(e,c,r,n)}},{key:"generateTextureForPositions",value:function(e,t,i){var r=i/3,n=4096,s=Math.ceil(r/n);if(0===s)throw"texture height===0";var o=new Uint16Array(n*s*3);Au.sizeDataTexturePositions+=o.byteLength,Au.numberOfTextures++;for(var a=0,l=0,u=t.length;a<u;a++){var c=t[a];o.set(c,l),l+=c.length}var A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,n,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,s,e.RGB_INTEGER,e.UNSIGNED_SHORT,o,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new cu(e,A,n,s)}},{key:"generateTextureForPackedPortionIds",value:function(e,t){if(0===t.length)return{texture:null,textureHeight:0};var i=t.length,r=4096,n=Math.ceil(i/r);if(0===n)throw"texture height===0";var s=new Uint16Array(r*n);s.set(t,0),Au.sizeDataTexturePortionIds+=s.byteLength,Au.numberOfTextures++;var o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.R16UI,r,n),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RED_INTEGER,e.UNSIGNED_SHORT,s,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new cu(e,o,r,n)}}]),e}(),du=new po,pu=du.maxDataTextureHeight,fu=new Float32Array(16),vu=new Uint8Array(4),gu=new Float32Array(3),mu=0,_u=le.identityMat4(),yu=function(){function e(t,i){var r,n,s;E(this,e),Au.numberOfLayers++,this._layerNumber=mu++,this.sortId="TriDTX-".concat(this._layerNumber),this.layerIndex=i.layerIndex,this._renderers=(r=t.scene,n=r.id,(s=au[n])||(s=new ou(r),au[n]=s,s._compile(),s.eagerCreateRenders(),r.on("compile",(function(){s._compile(),s.eagerCreateRenders()})),r.on("destroyed",(function(){delete au[n],s._destroy()}))),s),this.model=t,this._buffer=new lu,this._dataTextureState=new uu,this._dataTextureGenerator=new hu,this._state=new nt({origin:le.vec3(i.origin),textureState:this._dataTextureState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=le.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this.primitive=i.primitive,this._finalized=!1}return I(e,[{key:"aabb",get:function(){if(this.aabbDirty){le.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e<t;e++)le.expandAABB3(this._aabb,this._meshes[e].aabb);this.aabbDirty=!1}return this._aabb}},{key:"canCreatePortion",value:function(e){if(this._finalized)throw"Already finalized";var t=e.buckets.length;this._numPortions+t>65536&&Au.cannotCreatePortion.because10BitsObjectId++;var i=this._numPortions+t<=65536,r=void 0!==e.geometryId&&null!==e.geometryId?"".concat(e.geometryId,"#").concat(0):"".concat(e.id,"#").concat(0);if(!this._bucketGeometries[r]){var n=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits),s=0,o=0;e.buckets.forEach((function(e){s+=e.positionsCompressed.length/3,o+=e.indices.length/2})),(this._state.numVertices+s>4096*pu||n+o>4096*pu)&&Au.cannotCreatePortion.becauseTextureSize++,i&&(i=this._state.numVertices+s<=4096*pu&&n+o<=4096*pu)}return i}},{key:"createPortion",value:function(e,t){var i=this;if(this._finalized)throw"Already finalized";var r=[];t.buckets.forEach((function(e,n){var s=void 0!==t.geometryId&&null!==t.geometryId?"".concat(t.geometryId,"#").concat(n):"".concat(t.id,"#").concat(n),o=i._bucketGeometries[s];o||(o=i._createBucketGeometry(t,e),i._bucketGeometries[s]=o);var a=i._createSubPortion(t,o,e);r.push(a)}));var n=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(r),this.model.numPortions++,this._meshes.push(e),n}},{key:"_createBucketGeometry",value:function(e,t){if(t.indices){var i=8*Math.ceil(t.indices.length/2/8)*2;Au.overheadSizeAlignementIndices+=2*(i-t.indices.length);var r=new Uint32Array(i);r.fill(0),r.set(t.indices),t.indices=r}var n=t.positionsCompressed,s=t.indices,o=this._buffer;o.positionsCompressed.push(n);var a,l=o.lenPositionsCompressed/3,u=n.length/3;o.lenPositionsCompressed+=n.length;var c,A=0;s&&(A=s.length/2,u<=256?(c=o.indices8Bits,a=o.lenIndices8Bits/2,o.lenIndices8Bits+=s.length):u<=65536?(c=o.indices16Bits,a=o.lenIndices16Bits/2,o.lenIndices16Bits+=s.length):(c=o.indices32Bits,a=o.lenIndices32Bits/2,o.lenIndices32Bits+=s.length),c.push(s));return this._state.numVertices+=u,Au.numberOfGeometries++,{vertexBase:l,numVertices:u,numLines:A,indicesBase:a}}},{key:"_createSubPortion",value:function(e,t){var i,r=e.color,n=e.colors,s=e.opacity,o=e.meshMatrix,a=e.pickColor,l=this._buffer,u=this._state;l.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),l.perObjectInstancePositioningMatrices.push(o||_u),l.perObjectSolid.push(!!e.solid),n?l.perObjectColors.push([255*n[0],255*n[1],255*n[2],255]):r&&l.perObjectColors.push([r[0],r[1],r[2],s]),l.perObjectPickColors.push(a),l.perObjectVertexBases.push(t.vertexBase),i=t.numVertices<=256?u.numIndices8Bits:t.numVertices<=65536?u.numIndices16Bits:u.numIndices32Bits,l.perObjectIndexBaseOffsets.push(i/2-t.indicesBase);var c=this._subPortions.length;if(t.numLines>0){var A,h=2*t.numLines;t.numVertices<=256?(A=l.perLineNumberPortionId8Bits,u.numIndices8Bits+=h,Au.totalLines8Bits+=t.numLines):t.numVertices<=65536?(A=l.perLineNumberPortionId16Bits,u.numIndices16Bits+=h,Au.totalLines16Bits+=t.numLines):(A=l.perLineNumberPortionId32Bits,u.numIndices32Bits+=h,Au.totalLines32Bits+=t.numLines),Au.totalLines+=t.numLines;for(var d=0;d<t.numLines;d+=8)A.push(c)}return this._subPortions.push({numVertices:t.numLines}),this._numPortions++,Au.numberOfPortions++,c}},{key:"finalize",value:function(){var e=this;if(!this._finalized){var t=this._state,i=this._dataTextureState,r=this.model.scene.canvas.gl,n=this._buffer;t.gl=r,i.texturePerObjectColorsAndFlags=this._dataTextureGenerator.generateTextureForColorsAndFlags(r,n.perObjectColors,n.perObjectPickColors,n.perObjectVertexBases,n.perObjectIndexBaseOffsets,n.perObjectSolid),i.texturePerObjectInstanceMatrices=this._dataTextureGenerator.generateTextureForInstancingMatrices(r,n.perObjectInstancePositioningMatrices),i.texturePerObjectPositionsDecodeMatrix=this._dataTextureGenerator.generateTextureForPositionsDecodeMatrices(r,n.perObjectPositionsDecodeMatrices),i.texturePerVertexIdCoordinates=this._dataTextureGenerator.generateTextureForPositions(r,n.positionsCompressed,n.lenPositionsCompressed),i.texturePerLineIdPortionIds8Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(r,n.perLineNumberPortionId8Bits),i.texturePerLineIdPortionIds16Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(r,n.perLineNumberPortionId16Bits),i.texturePerLineIdPortionIds32Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(r,n.perLineNumberPortionId32Bits),n.lenIndices8Bits>0&&(i.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(r,n.indices8Bits,n.lenIndices8Bits)),n.lenIndices16Bits>0&&(i.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(r,n.indices16Bits,n.lenIndices16Bits)),n.lenIndices32Bits>0&&(i.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(r,n.indices32Bits,n.lenIndices32Bits)),i.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(function(){e._deferredSetFlagsDirty&&e._uploadDeferredFlags(),e._numUpdatesInFrame=0}))}}},{key:"initFlags",value:function(e,t,i){t&gs&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Bs&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ws&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&xs&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ys&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&_s&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ms&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags(),this._setDeferredFlags2()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&gs?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Bs?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ws?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&xs?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&ys?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}},{key:"_beginDeferredFlags",value:function(){this._deferredSetFlagsActive=!0}},{key:"_uploadDeferredFlags",value:function(){if(this._deferredSetFlagsActive=!1,this._deferredSetFlagsDirty){this._deferredSetFlagsDirty=!1;var e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ms?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&_s?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],r=0,n=i.length;r<n;r++)this._subPortionSetColor(i[r],t)}},{key:"_subPortionSetColor",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=this._dataTextureState,r=this.model.scene.canvas.gl;vu[0]=t[0],vu[1]=t[1],vu[2]=t[2],vu[3]=t[3],i.texturePerObjectColorsAndFlags._textureData.set(vu,32*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),r.bindTexture(r.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),r.texSubImage2D(r.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,r.RGBA_INTEGER,r.UNSIGNED_BYTE,vu))}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){for(var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=this._portionToSubPortionsMap[e],s=0,o=n.length;s<o;s++)this._subPortionSetFlags(n[s],t,i,r)}},{key:"_subPortionSetFlags",value:function(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var n,s,o=!!(t&gs),a=!!(t&ws),l=!!(t&Bs),u=!!(t&xs),c=!!(t&_s),A=!!(t&ms);n=!o||A||a?Cs.NOT_RENDERED:i?Cs.COLOR_TRANSPARENT:Cs.COLOR_OPAQUE,s=!o||A?Cs.NOT_RENDERED:u?Cs.SILHOUETTE_SELECTED:l?Cs.SILHOUETTE_HIGHLIGHTED:a?Cs.SILHOUETTE_XRAYED:Cs.NOT_RENDERED;var h=o&&!A&&c?Cs.PICK:Cs.NOT_RENDERED,d=this._dataTextureState,p=this.model.scene.canvas.gl;vu[0]=n,vu[1]=s,vu[3]=h,d.texturePerObjectColorsAndFlags._textureData.set(vu,32*e+8),this._deferredSetFlagsActive||r?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),p.bindTexture(p.TEXTURE_2D,d.texturePerObjectColorsAndFlags._texture),p.texSubImage2D(p.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,p.RGBA_INTEGER,p.UNSIGNED_BYTE,vu))}},{key:"_setDeferredFlags",value:function(){}},{key:"_setFlags2",value:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=this._portionToSubPortionsMap[e],n=0,s=r.length;n<s;n++)this._subPortionSetFlags2(r[n],t,i)}},{key:"_subPortionSetFlags2",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this._finalized)throw"Not finalized";var r=t&ys?255:0,n=this._dataTextureState,s=this.model.scene.canvas.gl;vu[0]=r,vu[1]=0,vu[2]=1,vu[3]=2,n.texturePerObjectColorsAndFlags._textureData.set(vu,32*e+12),this._deferredSetFlagsActive||i?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,n.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,vu))}},{key:"_setDeferredFlags2",value:function(){}},{key:"setOffset",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],r=0,n=i.length;r<n;r++)this._subPortionSetOffset(i[r],t)}},{key:"_subPortionSetOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=this._dataTextureState,r=this.model.scene.canvas.gl;gu[0]=t[0],gu[1]=t[1],gu[2]=t[2],i.texturePerObjectOffsets._textureData.set(gu,3*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),r.bindTexture(r.TEXTURE_2D,i.texturePerObjectOffsets._texture),r.texSubImage2D(r.TEXTURE_2D,0,0,e,1,1,r.RGB,r.FLOAT,gu))}},{key:"setMatrix",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],r=0,n=i.length;r<n;r++)this._subPortionSetMatrix(i[r],t)}},{key:"_subPortionSetMatrix",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=this._dataTextureState,r=this.model.scene.canvas.gl;fu.set(t),i.texturePerObjectInstanceMatrices._textureData.set(fu,16*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),r.bindTexture(r.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),r.texSubImage2D(r.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,r.RGBA,r.FLOAT,fu))}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE)}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Cs.COLOR_TRANSPARENT)}},{key:"drawDepth",value:function(e,t){}},{key:"drawNormals",value:function(e,t){}},{key:"drawSilhouetteXRayed",value:function(e,t){}},{key:"drawSilhouetteHighlighted",value:function(e,t){}},{key:"drawSilhouetteSelected",value:function(e,t){}},{key:"drawEdgesColorOpaque",value:function(e,t){}},{key:"drawEdgesColorTransparent",value:function(e,t){}},{key:"drawEdgesHighlighted",value:function(e,t){}},{key:"drawEdgesSelected",value:function(e,t){}},{key:"drawEdgesXRayed",value:function(e,t){}},{key:"drawOcclusion",value:function(e,t){}},{key:"drawShadow",value:function(e,t){}},{key:"setPickMatrices",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){}},{key:"drawPickDepths",value:function(e,t){}},{key:"drawSnapInit",value:function(e,t){}},{key:"drawSnap",value:function(e,t){}},{key:"drawPickNormals",value:function(e,t){}},{key:"destroy",value:function(){if(!this._destroyed){var e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}}]),e}(),bu=le.vec3(),wu=le.vec3(),Bu=le.vec3();le.vec3();var xu=le.vec4(),Pu=le.mat4(),Cu=function(){function e(t,i){E(this,e),this._scene=t,this._withSAO=i,this._hash=this._getHash(),this._allocate()}return I(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,i){var r=this._scene,n=r.camera,s=t.model,o=r.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,c=s.position,A=s.rotationMatrix;if(this._program||(this._allocate(),!this.errors)){var h,d;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var p=0!==u[0]||0!==u[1]||0!==u[2],f=0!==c[0]||0!==c[1]||0!==c[2];if(p||f){var v=bu;if(p){var g=le.transformPoint3(A,u,wu);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=c[0],v[1]+=c[1],v[2]+=c[2],h=Jt(n.viewMatrix,v,Pu),(d=Bu)[0]=n.eye[0]-v[0],d[1]=n.eye[1]-v[1],d[2]=n.eye[2]-v[2]}else h=n.viewMatrix,d=n.eye;if(o.uniformMatrix4fv(this._uSceneModelMatrix,!1,A),o.uniformMatrix4fv(this._uViewMatrix,!1,h),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix),o.uniform3fv(this._uCameraEyeRtc,d),o.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){var m=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,m)}var _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),y=r._sectionPlanesState.sectionPlanes.length;if(_>0){var b=r._sectionPlanesState.sectionPlanes,w=t.layerIndex*y,B=s.renderFlags;r.crossSections&&(o.uniform4fv(this._uSliceColor,r.crossSections.sliceColor),o.uniform1f(this._uSliceThickness,r.crossSections.sliceThickness));for(var x=0;x<_;x++){var P=this._uSectionPlanes[x];if(P)if(x<y){var C=B.sectionPlanesActivePerLayer[w+x];if(o.uniform1i(P.active,C?1:0),C){var M=b[x];if(u){var k=ei(M.dist,M.dir,u,bu,s.matrix);o.uniform3fv(P.pos,k)}else o.uniform3fv(P.pos,M.pos);o.uniform3fv(P.dir,M.dir)}}else o.uniform1i(P.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new Pr(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);var r=this._program;this._uRenderPass=r.getLocation("renderPass"),this._uLightAmbient=r.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(var n=i.lights,s=0,o=n.length;s<o;s++)switch(n[s].type){case"dir":this._uLightColor[s]=r.getLocation("lightColor"+s),this._uLightPos[s]=null,this._uLightDir[s]=r.getLocation("lightDir"+s);break;case"point":this._uLightColor[s]=r.getLocation("lightColor"+s),this._uLightPos[s]=r.getLocation("lightPos"+s),this._uLightDir[s]=null,this._uLightAttenuation[s]=r.getLocation("lightAttenuation"+s);break;case"spot":this._uLightColor[s]=r.getLocation("lightColor"+s),this._uLightPos[s]=r.getLocation("lightPos"+s),this._uLightDir[s]=r.getLocation("lightDir"+s),this._uLightAttenuation[s]=r.getLocation("lightAttenuation"+s)}this._uSceneModelMatrix=r.getLocation("sceneModelMatrix"),this._uViewMatrix=r.getLocation("viewMatrix"),this._uProjMatrix=r.getLocation("projMatrix"),this._uSectionPlanes=[];for(var a=0,l=e._sectionPlanesState.getNumAllocatedSectionPlanes();a<l;a++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+a),pos:r.getLocation("sectionPlanePos"+a),dir:r.getLocation("sectionPlaneDir"+a)});this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=r.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=r.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=r.getLocation("uCameraEyeRtc"),e.crossSections&&(this._uSliceColor=r.getLocation("sliceColor"),this._uSliceThickness=r.getLocation("sliceThickness"))}},{key:"_bindProgram",value:function(e){var t=this._scene,i=t.canvas.gl,r=this._program,n=t._lightsState.lights,s=t.camera.project;r.bind(),this._uLightAmbient&&i.uniform4fv(this._uLightAmbient,t._lightsState.getAmbientColorAndIntensity());for(var o=0,a=n.length;o<a;o++){var l=n[o];this._uLightColor[o]&&i.uniform4f(this._uLightColor[o],l.color[0],l.color[1],l.color[2],l.intensity),this._uLightPos[o]&&(i.uniform3fv(this._uLightPos[o],l.pos),this._uLightAttenuation[o]&&i.uniform1f(this._uLightAttenuation[o],l.attenuation)),this._uLightDir[o]&&i.uniform3fv(this._uLightDir[o],l.dir)}if(this._withSAO){var u=t.sao;if(u.possible){var c=i.drawingBufferWidth,A=i.drawingBufferHeight;xu[0]=c,xu[1]=A,xu[2]=u.blendCutoff,xu[3]=u.blendFactor,i.uniform4fv(this._uSAOParams,xu),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,10)}}if(t.logarithmicDepthBufferEnabled){var h=2/(Math.log(s.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,h)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e,t=this._scene,i=t._sectionPlanesState,r=t._lightsState,n=i.getNumAllocatedSectionPlanes()>0,s=[];s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("uniform mat4 sceneModelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectMatrix;"),s.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),t.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("uniform vec4 lightAmbient;");for(var o=0,a=r.lights.length;o<a;o++)"ambient"!==(e=r.lights[o]).type&&(s.push("uniform vec4 lightColor"+o+";"),"dir"===e.type&&s.push("uniform vec3 lightDir"+o+";"),"point"===e.type&&s.push("uniform vec3 lightPos"+o+";"),"spot"===e.type&&(s.push("uniform vec3 lightPos"+o+";"),s.push("uniform vec3 lightDir"+o+";")));n&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.x) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("} else {"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),s.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),s.push("float lambertian = 1.0;");for(var l=0,u=r.lights.length;l<u;l++)if("ambient"!==(e=r.lights[l]).type){if("dir"===e.type)"view"===e.space?s.push("viewLightDir = normalize(lightDir"+l+");"):s.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+l+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?s.push("viewLightDir = -normalize(lightPos"+l+" - viewPosition.xyz);"):s.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+l+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?s.push("viewLightDir = normalize(lightDir"+l+");"):s.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+l+", 0.0)).xyz);")}s.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),s.push("reflectedColor += lambertian * (lightColor"+l+".rgb * lightColor"+l+".a);")}return s.push("vec3 rgb = vec3(color.rgb) / 255.0;"),s.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2.r;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// TrianglesDataTextureColorRenderer fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),i){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var n=0,s=t.getNumAllocatedSectionPlanes();n<s;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";");r.push("uniform float sliceThickness;"),r.push("uniform vec4 sliceColor;")}if(r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),r.push(" vec4 newColor;"),r.push(" newColor = vColor;"),i){r.push(" bool clippable = vFlags2 > 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o<a;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > sliceThickness) { "),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" newColor = sliceColor;"),r.push(" }"),r.push("}")}return e.logarithmicDepthBufferEnabled?r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"):(r.push(" float dx = dFdx(gl_FragCoord.z);"),r.push(" float dy = dFdy(gl_FragCoord.z);"),r.push(" float diff = sqrt(dx*dx+dy*dy);"),r.push(" gl_FragDepth = gl_FragCoord.z + diff;")),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):r.push(" outColor = newColor;"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Mu=new Float32Array([1,1,1]),ku=le.vec3(),Eu=le.vec3(),Fu=le.vec3();le.vec3();var Iu=le.mat4(),Tu=function(){function e(t,i){E(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var r=this._scene,n=r.camera,s=t.model,o=r.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,c=s.position,A=s.rotationMatrix,h=n.viewMatrix;if(this._program||(this._allocate(),!this.errors)){var d,p;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),u||0!==c[0]||0!==c[1]||0!==c[2]){var f=ku;if(u){var v=Eu;le.transformPoint3(A,u,v),f[0]=v[0],f[1]=v[1],f[2]=v[2]}else f[0]=0,f[1]=0,f[2]=0;f[0]+=c[0],f[1]+=c[1],f[2]+=c[2],d=Jt(h,f,Iu),(p=Fu)[0]=n.eye[0]-f[0],p[1]=n.eye[1]-f[1],p[2]=n.eye[2]-f[2]}else d=h,p=n.eye;if(o.uniform3fv(this._uCameraEyeRtc,p),o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uWorldMatrix,!1,A),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix),i===Cs.SILHOUETTE_XRAYED){var g=r.xrayMaterial._state,m=g.fillColor,_=g.fillAlpha;o.uniform4f(this._uColor,m[0],m[1],m[2],_)}else if(i===Cs.SILHOUETTE_HIGHLIGHTED){var y=r.highlightMaterial._state,b=y.fillColor,w=y.fillAlpha;o.uniform4f(this._uColor,b[0],b[1],b[2],w)}else if(i===Cs.SILHOUETTE_SELECTED){var B=r.selectedMaterial._state,x=B.fillColor,P=B.fillAlpha;o.uniform4f(this._uColor,x[0],x[1],x[2],P)}else o.uniform4fv(this._uColor,Mu);if(r.logarithmicDepthBufferEnabled){var C=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,C)}var M=r._sectionPlanesState.getNumAllocatedSectionPlanes(),k=r._sectionPlanesState.sectionPlanes.length;if(M>0)for(var E=r._sectionPlanesState.sectionPlanes,F=t.layerIndex*k,I=s.renderFlags,T=0;T<M;T++){var D=this._uSectionPlanes[T];if(D)if(T<k){var S=I.sectionPlanesActivePerLayer[F+T];if(o.uniform1i(D.active,S?1:0),S){var R=E[T];if(u){var U=ei(R.dist,R.dir,u,ku,s.matrix);o.uniform3fv(D.pos,U)}else o.uniform3fv(D.pos,R.pos);o.uniform3fv(D.dir,R.dir)}}else o.uniform1i(D.active,0)}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Pr(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=e._sectionPlanesState.getNumAllocatedSectionPlanes();r<n;r++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+r),pos:i.getLocation("sectionPlanePos"+r),dir:i.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(e){var t=this._scene,i=t.canvas.gl,r=t.camera.project;if(this._program.bind(),t.logarithmicDepthBufferEnabled){var n=2/(Math.log(r.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,n)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var r=0,n=e._sectionPlanesState.getNumAllocatedSectionPlanes();r<n;r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";");i.push("uniform float sliceThickness;"),i.push("uniform vec4 sliceColor;")}if(i.push("uniform vec4 color;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" vec4 newColor;"),i.push(" newColor = color;"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();s<o;s++)i.push("if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > sliceThickness) { "),i.push(" discard;"),i.push(" }"),i.push(" if (dist > 0.0) { "),i.push(" newColor = sliceColor;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = newColor;"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Du=new Float32Array([0,0,0,1]),Su=le.vec3(),Ru=le.vec3();le.vec3();var Uu=le.mat4(),Lu=function(){function e(t){E(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var r=t.model,n=r.scene,s=n.camera,o=n.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,c=r.position,A=r.rotationMatrix,h=s.viewMatrix;if(this._program||(this._allocate(t),!this.errors)){var d;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var p=0!==u[0]||0!==u[1]||0!==u[2],f=0!==c[0]||0!==c[1]||0!==c[2];if(p||f){var v=Su;if(p){var g=le.transformPoint3(A,u,Ru);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=c[0],v[1]+=c[1],v[2]+=c[2],d=Jt(h,v,Uu)}else d=h;if(o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uSceneModelMatrix,!1,A),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,s.projMatrix),i===Cs.EDGES_XRAYED){var m=n.xrayMaterial._state,_=m.edgeColor,y=m.edgeAlpha;o.uniform4f(this._uColor,_[0],_[1],_[2],y)}else if(i===Cs.EDGES_HIGHLIGHTED){var b=n.highlightMaterial._state,w=b.edgeColor,B=b.edgeAlpha;o.uniform4f(this._uColor,w[0],w[1],w[2],B)}else if(i===Cs.EDGES_SELECTED){var x=n.selectedMaterial._state,P=x.edgeColor,C=x.edgeAlpha;o.uniform4f(this._uColor,P[0],P[1],P[2],C)}else o.uniform4fv(this._uColor,Du);var M=n._sectionPlanesState.getNumAllocatedSectionPlanes(),k=n._sectionPlanesState.sectionPlanes.length;if(M>0)for(var E=n._sectionPlanesState.sectionPlanes,F=t.layerIndex*k,I=r.renderFlags,T=0;T<M;T++){var D=this._uSectionPlanes[T];if(D)if(T<k){var S=I.sectionPlanesActivePerLayer[F+T];if(o.uniform1i(D.active,S?1:0),S){var R=E[T];if(u){var U=ei(R.dist,R.dir,u,Su,r.matrix);o.uniform3fv(D.pos,U)}else o.uniform3fv(D.pos,R.pos);o.uniform3fv(D.dir,R.dir)}}else o.uniform1i(D.active,0)}a.numEdgeIndices8Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),o.drawArrays(o.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),o.drawArrays(o.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),o.drawArrays(o.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Pr(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=e._sectionPlanesState.getNumAllocatedSectionPlanes();r<n;r++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+r),pos:i.getLocation("sectionPlanePos"+r),dir:i.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix"}}},{key:"_bindProgram",value:function(){var e=this._scene,t=e.canvas.gl,i=this._program,r=e.camera.project;if(i.bind(),e.logarithmicDepthBufferEnabled){var n=2/(Math.log(r.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,n)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var r=0,n=e._sectionPlanesState.getNumAllocatedSectionPlanes();r<n;r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";");i.push("uniform float sliceThickness;"),i.push("uniform vec4 sliceColor;")}if(i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" vec4 newColor;"),i.push(" newColor = vColor;"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();s<o;s++)i.push("if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > sliceThickness) { "),i.push(" discard;"),i.push(" }"),i.push(" if (dist > 0.0) { "),i.push(" newColor = sliceColor;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = newColor;"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Ou=le.vec3(),Nu=le.vec3(),Vu=le.mat4(),Qu=function(){function e(t){E(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var r=t.model,n=r.scene,s=n.camera,o=n.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,c=r.position,A=r.rotationMatrix,h=s.viewMatrix;if(this._program||(this._allocate(),!this.errors)){var d;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var p=0!==u[0]||0!==u[1]||0!==u[2],f=0!==c[0]||0!==c[1]||0!==c[2];if(p||f){var v=Ou;if(p){var g=le.transformPoint3(A,u,Nu);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=c[0],v[1]+=c[1],v[2]+=c[2],d=Jt(h,v,Vu)}else d=h;o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uSceneModelMatrix,!1,A),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,s.projMatrix);var m=n._sectionPlanesState.getNumAllocatedSectionPlanes(),_=n._sectionPlanesState.sectionPlanes.length;if(m>0)for(var y=n._sectionPlanesState.sectionPlanes,b=t.layerIndex*_,w=r.renderFlags,B=0;B<m;B++){var x=this._uSectionPlanes[B];if(x)if(B<_){var P=w.sectionPlanesActivePerLayer[b+B];if(o.uniform1i(x.active,P?1:0),P){var C=y[B];if(u){var M=ei(C.dist,C.dir,u,Ou,r.matrix);o.uniform3fv(x.pos,M)}else o.uniform3fv(x.pos,C.pos);o.uniform3fv(x.dir,C.dir)}}else o.uniform1i(x.active,0)}a.numEdgeIndices8Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),o.drawArrays(o.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),o.drawArrays(o.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),o.drawArrays(o.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Pr(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=e._sectionPlanesState.getNumAllocatedSectionPlanes();r<n;r++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+r),pos:i.getLocation("sectionPlanePos"+r),dir:i.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix"}}},{key:"_bindProgram",value:function(){var e=this._scene,t=e.canvas.gl,i=this._program,r=e.camera.project;if(i.bind(),e.logarithmicDepthBufferEnabled){var n=2/(Math.log(r.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,n)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var r=0,n=e._sectionPlanesState.getNumAllocatedSectionPlanes();r<n;r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";");i.push("uniform float sliceThickness;"),i.push("uniform vec4 sliceColor;")}if(i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" vec4 newColor;"),i.push(" newColor = vColor;"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();s<o;s++)i.push("if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > sliceThickness) { "),i.push(" discard;"),i.push(" }"),i.push(" if (dist > 0.0) { "),i.push(" newColor = sliceColor;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = newColor;"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Hu=le.vec3(),ju=le.vec3(),Gu=le.vec3(),zu=le.mat4(),Wu=function(){function e(t){E(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));var r,n,s=t.model,o=s.scene,a=o.camera,l=o.canvas.gl,u=t._state,c=u.textureState,A=t._state.origin,h=s.position,d=s.rotationMatrix,p=e.pickViewMatrix||a.viewMatrix,f=e.pickProjMatrix||a.projMatrix,v=e.pickOrigin||a.eye,g=e.pickProjMatrix?e.pickZFar:a.project.far;c.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var m=0!==A[0]||0!==A[1]||0!==A[2],_=0!==h[0]||0!==h[1]||0!==h[2];if(m||_){var y=Hu;if(m){var b=le.transformPoint3(d,A,ju);y[0]=b[0],y[1]=b[1],y[2]=b[2]}else y[0]=0,y[1]=0,y[2]=0;y[0]+=h[0],y[1]+=h[1],y[2]+=h[2],r=Jt(p,y,zu),(n=Gu)[0]=v[0]-y[0],n[1]=v[1]-y[1],n[2]=v[2]-y[2]}else r=p,n=v;if(l.uniform2fv(this._uPickClipPos,e.pickClipPos),l.uniform2f(this._uDrawingBufferSize,l.drawingBufferWidth,l.drawingBufferHeight),l.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),l.uniformMatrix4fv(this._uViewMatrix,!1,r),l.uniformMatrix4fv(this._uProjMatrix,!1,f),l.uniform3fv(this._uCameraEyeRtc,n),l.uniform1i(this._uRenderPass,i),o.logarithmicDepthBufferEnabled){var w=2/(Math.log(g+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,w)}var B=o._sectionPlanesState.getNumAllocatedSectionPlanes(),x=o._sectionPlanesState.sectionPlanes.length;if(B>0)for(var P=o._sectionPlanesState.sectionPlanes,C=t.layerIndex*x,M=s.renderFlags,k=0;k<B;k++){var E=this._uSectionPlanes[k];if(E)if(k<x){var F=M.sectionPlanesActivePerLayer[C+k];if(l.uniform1i(E.active,F?1:0),F){var I=P[k];if(A){var T=ei(I.dist,I.dir,A,Hu,s.matrix);l.uniform3fv(E.pos,T)}else l.uniform3fv(E.pos,I.pos);l.uniform3fv(E.dir,I.dir)}}else l.uniform1i(E.active,0)}u.numIndices8Bits>0&&(c.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),l.drawArrays(l.TRIANGLES,0,u.numIndices8Bits)),u.numIndices16Bits>0&&(c.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),l.drawArrays(l.TRIANGLES,0,u.numIndices16Bits)),u.numIndices32Bits>0&&(c.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),l.drawArrays(l.TRIANGLES,0,u.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Pr(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=e._sectionPlanesState.getNumAllocatedSectionPlanes();r<n;r++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+r),pos:i.getLocation("sectionPlanePos"+r),dir:i.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(e){var t=this._scene.canvas.gl;this._program.bind(),t.uniform1i(this._uPickInvisible,e.pickInvisible)}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var r=0;r<e._sectionPlanesState.getNumAllocatedSectionPlanes();r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("in vec4 vPickColor;"),i.push("out vec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (float(vFlags2.x) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(r=0;r<e._sectionPlanesState.getNumAllocatedSectionPlanes();r++)i.push(" if (sectionPlaneActive"+r+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Xu=le.vec3(),Ku=le.vec3(),Zu=le.vec3();le.vec3();var Ju=le.mat4(),Yu=function(){function e(t){E(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var r,n,s=t.model,o=s.scene,a=o.camera,l=o.canvas.gl,u=t._state,c=u.textureState,A=t._state.origin,h=s.position,d=s.rotationMatrix,p=e.pickViewMatrix||a.viewMatrix,f=e.pickProjMatrix||a.projMatrix,v=e.pickOrigin||a.eye,g=e.pickProjMatrix?e.pickZFar:a.project.far;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),c.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){var m=Xu;if(A){var _=Ku;le.transformPoint3(d,A,_),m[0]=_[0],m[1]=_[1],m[2]=_[2]}else m[0]=0,m[1]=0,m[2]=0;m[0]+=h[0],m[1]+=h[1],m[2]+=h[2],r=Jt(p,m,Ju),(n=Zu)[0]=v[0]-m[0],n[1]=v[1]-m[1],n[2]=v[2]-m[2],e.snapPickOrigin[0]=m[0],e.snapPickOrigin[1]=m[1],e.snapPickOrigin[2]=m[2]}else r=p,n=v,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(l.uniform3fv(this._uCameraEyeRtc,n),l.uniform1i(this._uRenderPass,i),l.uniform1i(this._uPickInvisible,e.pickInvisible),l.uniform2fv(this._uPickClipPos,e.pickClipPos),l.uniform2f(this._uDrawingBufferSize,l.drawingBufferWidth,l.drawingBufferHeight),l.uniform1f(this._uPickZNear,e.pickZNear),l.uniform1f(this._uPickZFar,e.pickZFar),l.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),l.uniformMatrix4fv(this._uViewMatrix,!1,r),l.uniformMatrix4fv(this._uProjMatrix,!1,f),o.logarithmicDepthBufferEnabled){var y=2/(Math.log(g+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,y)}var b=o._sectionPlanesState.getNumAllocatedSectionPlanes(),w=o._sectionPlanesState.sectionPlanes.length;if(b>0)for(var B=o._sectionPlanesState.sectionPlanes,x=t.layerIndex*w,P=s.renderFlags,C=0;C<b;C++){var M=this._uSectionPlanes[C];if(M)if(C<w){var k=P.sectionPlanesActivePerLayer[x+C];if(l.uniform1i(M.active,k?1:0),k){var E=B[C];if(A){var F=ei(E.dist,E.dir,A,Xu,s.matrix);l.uniform3fv(M.pos,F)}else l.uniform3fv(M.pos,E.pos);l.uniform3fv(M.dir,E.dir)}}else l.uniform1i(M.active,0)}u.numIndices8Bits>0&&(c.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),l.drawArrays(l.TRIANGLES,0,u.numIndices8Bits)),u.numIndices16Bits>0&&(c.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),l.drawArrays(l.TRIANGLES,0,u.numIndices16Bits)),u.numIndices32Bits>0&&(c.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),l.drawArrays(l.TRIANGLES,0,u.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Pr(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=e._sectionPlanesState.getNumAllocatedSectionPlanes();r<n;r++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+r),pos:i.getLocation("sectionPlanePos"+r),dir:i.getLocation("sectionPlaneDir"+r)});this._uPickZNear=i.getLocation("pickZNear"),this._uPickZFar=i.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var r=0;r<e._sectionPlanesState.getNumAllocatedSectionPlanes();r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("in vec4 vViewPosition;"),i.push("vec4 packDepth(const in float depth) {"),i.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),i.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),i.push(" vec4 res = fract(depth * bitShift);"),i.push(" res -= res.xxyz * bitMask;"),i.push(" return res;"),i.push("}"),i.push("out vec4 outPackedDepth;"),i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(r=0;r<e._sectionPlanesState.getNumAllocatedSectionPlanes();r++)i.push(" if (sectionPlaneActive"+r+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outPackedDepth = packDepth(zNormalizedDepth); "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),qu=le.vec3(),$u=le.vec3(),ec=le.vec3(),tc=le.vec3();le.vec3();var ic=le.mat4(),rc=function(){function e(t){E(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r,n,s=t.model,o=s.scene,a=o.camera,l=o.canvas.gl,u=t._state,c=u.textureState,A=t._state.origin,h=s.position,d=s.rotationMatrix,p=t.aabb,f=e.pickViewMatrix||a.viewMatrix,v=qu;v[0]=le.safeInv(p[3]-p[0])*le.MAX_INT,v[1]=le.safeInv(p[4]-p[1])*le.MAX_INT,v[2]=le.safeInv(p[5]-p[2])*le.MAX_INT,e.snapPickCoordinateScale[0]=le.safeInv(v[0]),e.snapPickCoordinateScale[1]=le.safeInv(v[1]),e.snapPickCoordinateScale[2]=le.safeInv(v[2]),c.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){var _=$u;if(g){var y=le.transformPoint3(d,A,ec);_[0]=y[0],_[1]=y[1],_[2]=y[2]}else _[0]=0,_[1]=0,_[2]=0;_[0]+=h[0],_[1]+=h[1],_[2]+=h[2],r=Jt(f,_,ic),(n=tc)[0]=a.eye[0]-_[0],n[1]=a.eye[1]-_[1],n[2]=a.eye[2]-_[2],e.snapPickOrigin[0]=_[0],e.snapPickOrigin[1]=_[1],e.snapPickOrigin[2]=_[2]}else r=f,n=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;l.uniform3fv(this._uCameraEyeRtc,n),l.uniform2fv(this.uVectorA,e.snapVectorA),l.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),l.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),l.uniform3fv(this._uCoordinateScaler,v),l.uniform1i(this._uRenderPass,i),l.uniform1i(this._uPickInvisible,e.pickInvisible),l.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),l.uniformMatrix4fv(this._uViewMatrix,!1,r),l.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix);var b=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,b);var w=o._sectionPlanesState.getNumAllocatedSectionPlanes(),B=o._sectionPlanesState.sectionPlanes.length;if(w>0)for(var x=o._sectionPlanesState.sectionPlanes,P=t.layerIndex*B,C=s.renderFlags,M=0;M<w;M++){var k=this._uSectionPlanes[M];if(k)if(M<B){var E=C.sectionPlanesActivePerLayer[P+M];if(l.uniform1i(k.active,E?1:0),E){var F=x[M];if(A){var I=ei(F.dist,F.dir,A,qu,s.matrix);l.uniform3fv(k.pos,I)}else l.uniform3fv(k.pos,F.pos);l.uniform3fv(k.dir,F.dir)}}else l.uniform1i(k.active,0)}var T="edge"===e.snapMode?l.LINES:l.POINTS;u.numEdgeIndices8Bits>0&&(c.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),l.drawArrays(T,0,u.numEdgeIndices8Bits)),u.numEdgeIndices16Bits>0&&(c.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),l.drawArrays(T,0,u.numEdgeIndices16Bits)),u.numEdgeIndices32Bits>0&&(c.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),l.drawArrays(T,0,u.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Pr(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=e._sectionPlanesState.getNumAllocatedSectionPlanes();r<n;r++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+r),pos:i.getLocation("sectionPlanePos"+r),dir:i.getLocation("sectionPlaneDir"+r)});this._uLogDepthBufFC=i.getLocation("logDepthBufFC"),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc"),this.uVectorA=i.getLocation("uSnapVectorA"),this.uInverseVectorAB=i.getLocation("uSnapInvVectorAB"),this._uLayerNumber=i.getLocation("uLayerNumber"),this._uCoordinateScaler=i.getLocation("uCoordinateScaler")}}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("}"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var r=0,n=e._sectionPlanesState.getNumAllocatedSectionPlanes();r<n;r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),nc=le.vec3(),sc=le.vec3(),oc=le.vec3(),ac=le.vec3();le.vec3();var lc=le.mat4(),uc=function(){function e(t){E(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r,n,s=t.model,o=s.scene,a=o.camera,l=o.canvas.gl,u=t._state,c=u.textureState,A=t._state.origin,h=s.position,d=s.rotationMatrix,p=t.aabb,f=e.pickViewMatrix||a.viewMatrix,v=nc;v[0]=le.safeInv(p[3]-p[0])*le.MAX_INT,v[1]=le.safeInv(p[4]-p[1])*le.MAX_INT,v[2]=le.safeInv(p[5]-p[2])*le.MAX_INT,e.snapPickCoordinateScale[0]=le.safeInv(v[0]),e.snapPickCoordinateScale[1]=le.safeInv(v[1]),e.snapPickCoordinateScale[2]=le.safeInv(v[2]),c.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){var _=sc;if(g){var y=oc;le.transformPoint3(d,A,y),_[0]=y[0],_[1]=y[1],_[2]=y[2]}else _[0]=0,_[1]=0,_[2]=0;_[0]+=h[0],_[1]+=h[1],_[2]+=h[2],r=Jt(f,_,lc),(n=ac)[0]=a.eye[0]-_[0],n[1]=a.eye[1]-_[1],n[2]=a.eye[2]-_[2],e.snapPickOrigin[0]=_[0],e.snapPickOrigin[1]=_[1],e.snapPickOrigin[2]=_[2]}else r=f,n=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;l.uniform3fv(this._uCameraEyeRtc,n),l.uniform2fv(this._uVectorA,e.snapVectorA),l.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),l.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),l.uniform3fv(this._uCoordinateScaler,v),l.uniform1i(this._uRenderPass,i),l.uniform1i(this._uPickInvisible,e.pickInvisible),l.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,d),l.uniformMatrix4fv(this._uViewMatrix,!1,r),l.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix);var b=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,b);var w=o._sectionPlanesState.getNumAllocatedSectionPlanes(),B=o._sectionPlanesState.sectionPlanes.length;if(w>0)for(var x=o._sectionPlanesState.sectionPlanes,P=t.layerIndex*B,C=s.renderFlags,M=0;M<w;M++){var k=this._uSectionPlanes[M];if(k)if(M<B){var E=C.sectionPlanesActivePerLayer[P+M];if(l.uniform1i(k.active,E?1:0),E){var F=x[M];if(A){var I=ei(F.dist,F.dir,A,nc,s.matrix);l.uniform3fv(k.pos,I)}else l.uniform3fv(k.pos,F.pos);l.uniform3fv(k.dir,F.dir)}}else l.uniform1i(k.active,0)}u.numIndices8Bits>0&&(c.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),l.drawArrays(l.TRIANGLES,0,u.numIndices8Bits)),u.numIndices16Bits>0&&(c.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),l.drawArrays(l.TRIANGLES,0,u.numIndices16Bits)),u.numIndices32Bits>0&&(c.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),l.drawArrays(l.TRIANGLES,0,u.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Pr(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=e._sectionPlanesState.getNumAllocatedSectionPlanes();r<n;r++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+r),pos:i.getLocation("sectionPlanePos"+r),dir:i.getLocation("sectionPlaneDir"+r)});this._uLogDepthBufFC=i.getLocation("logDepthBufFC"),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc"),this._uVectorA=i.getLocation("uVectorAB"),this._uInverseVectorAB=i.getLocation("uInverseVectorAB"),this._uLayerNumber=i.getLocation("uLayerNumber"),this._uCoordinateScaler=i.getLocation("uCoordinateScaler")}}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("}"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(var r=0,n=e._sectionPlanesState.getNumAllocatedSectionPlanes();r<n;r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat(le.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),cc=le.vec3(),Ac=le.vec3(),hc=le.vec3();le.vec3();var dc=le.mat4(),pc=function(){function e(t){E(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var r=t.model,n=r.scene,s=n.camera,o=n.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,c=r.position,A=r.rotationMatrix,h=e.pickViewMatrix||s.viewMatrix;if(this._program||(this._allocate(t),!this.errors)){var d,p;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),u||0!==c[0]||0!==c[1]||0!==c[2]){var f=cc;if(u){var v=Ac;le.transformPoint3(A,u,v),f[0]=v[0],f[1]=v[1],f[2]=v[2]}else f[0]=0,f[1]=0,f[2]=0;f[0]+=c[0],f[1]+=c[1],f[2]+=c[2],d=Jt(h,f,dc),(p=hc)[0]=s.eye[0]-f[0],p[1]=s.eye[1]-f[1],p[2]=s.eye[2]-f[2]}else d=h,p=s.eye;o.uniform3fv(this._uCameraEyeRtc,p),o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uWorldMatrix,!1,A),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,s.projMatrix);var g=n._sectionPlanesState.getNumAllocatedSectionPlanes(),m=n._sectionPlanesState.sectionPlanes.length;if(g>0)for(var _=n._sectionPlanesState.sectionPlanes,y=t.layerIndex*m,b=r.renderFlags,w=0;w<g;w++){var B=this._uSectionPlanes[w];if(B)if(w<m){var x=b.sectionPlanesActivePerLayer[y+w];if(o.uniform1i(B.active,x?1:0),x){var P=_[w];if(u){var C=ei(P.dist,P.dir,u,cc,r.matrix);o.uniform3fv(B.pos,C)}else o.uniform3fv(B.pos,P.pos);o.uniform3fv(B.dir,P.dir)}}else o.uniform1i(B.active,0)}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Pr(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=e._sectionPlanesState.getNumAllocatedSectionPlanes();r<n;r++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+r),pos:i.getLocation("sectionPlanePos"+r),dir:i.getLocation("sectionPlaneDir"+r)});this._uPickZNear=i.getLocation("pickZNear"),this._uPickZFar=i.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(){var e=this._scene;e.canvas.gl,e.camera.project,this._program.bind()}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var r=0;r<e.getNumAllocatedSectionPlanes();r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (float(vFlags2) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<e.getNumAllocatedSectionPlanes();n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),fc=le.vec3(),vc=le.vec3(),gc=le.vec3();le.vec3();var mc=le.mat4(),_c=function(){function e(t){E(this,e),this._scene=t,this._allocate(),this._hash=this._getHash()}return I(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var r=this._scene,n=r.camera,s=t.model,o=r.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,c=s.position,A=s.rotationMatrix;if(this._program||(this._allocate(),!this.errors)){var h,d;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var p=0!==u[0]||0!==u[1]||0!==u[2],f=0!==c[0]||0!==c[1]||0!==c[2];if(p||f){var v=fc;if(p){var g=le.transformPoint3(A,u,vc);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=c[0],v[1]+=c[1],v[2]+=c[2],h=Jt(n.viewMatrix,v,mc),(d=gc)[0]=n.eye[0]-v[0],d[1]=n.eye[1]-v[1],d[2]=n.eye[2]-v[2]}else h=n.viewMatrix,d=n.eye;if(o.uniformMatrix4fv(this._uSceneModelMatrix,!1,A),o.uniformMatrix4fv(this._uViewMatrix,!1,h),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix),o.uniform3fv(this._uCameraEyeRtc,d),o.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){var m=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,m)}var _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),y=r._sectionPlanesState.sectionPlanes.length;if(_>0)for(var b=r._sectionPlanesState.sectionPlanes,w=t.layerIndex*y,B=s.renderFlags,x=0;x<_;x++){var P=this._uSectionPlanes[x];if(P)if(x<y){var C=B.sectionPlanesActivePerLayer[w+x];if(o.uniform1i(P.active,C?1:0),C){var M=b[x];if(u){var k=ei(M.dist,M.dir,u,fc,s.matrix);o.uniform3fv(P.pos,k)}else o.uniform3fv(P.pos,M.pos);o.uniform3fv(P.dir,M.dir)}}else o.uniform1i(P.active,0)}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Pr(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=e._sectionPlanesState.getNumAllocatedSectionPlanes();r<n;r++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+r),pos:i.getLocation("sectionPlanePos"+r),dir:i.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(e){var t=this._scene,i=t.canvas.gl,r=this._program,n=t.camera.project;if(r.bind(),i.uniformMatrix4fv(this._uProjMatrix,!1,n.matrix),t.logarithmicDepthBufferEnabled){var s=2/(Math.log(n.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,s)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var r=0,n=e._sectionPlanesState.getNumAllocatedSectionPlanes();r<n;r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();s<o;s++)i.push("if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),yc=le.vec3(),bc=le.vec3(),wc=le.vec3();le.vec3();var Bc=le.mat4(),xc=function(){function e(t){E(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return I(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var r=t.model,n=r.scene,s=n.camera,o=n.canvas.gl,a=t._state,l=t._state.origin,u=r.position,c=r.rotationMatrix,A=s.viewMatrix;if(this._program||(this._allocate(t),!this.errors)){var h,d;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));var p=0!==l[0]||0!==l[1]||0!==l[2],f=0!==u[0]||0!==u[1]||0!==u[2];if(p||f){var v=yc;if(p){var g=bc;le.transformPoint3(c,l,g),v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],h=Jt(A,v,Bc),(d=wc)[0]=s.eye[0]-v[0],d[1]=s.eye[1]-v[1],d[2]=s.eye[2]-v[2]}else h=A,d=s.eye;o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uWorldMatrix,!1,c),o.uniformMatrix4fv(this._uViewMatrix,!1,h),o.uniformMatrix4fv(this._uProjMatrix,!1,s.projMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,s.viewNormalMatrix),o.uniformMatrix4fv(this._uWorldNormalMatrix,!1,r.worldNormalMatrix);var m=n._sectionPlanesState.getNumAllocatedSectionPlanes(),_=n._sectionPlanesState.sectionPlanes.length;if(m>0)for(var y=n._sectionPlanesState.sectionPlanes,b=t.layerIndex*_,w=r.renderFlags,B=0;B<m;B++){var x=this._uSectionPlanes[B];if(x)if(B<_){var P=w.sectionPlanesActivePerLayer[b+B];if(o.uniform1i(x.active,P?1:0),P){var C=y[B];if(l){var M=ei(C.dist,C.dir,l,yc,r.matrix);o.uniform3fv(x.pos,M)}else o.uniform3fv(x.pos,C.pos);o.uniform3fv(x.dir,C.dir)}}else o.uniform1i(x.active,0)}o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.objectDecodeAndInstanceMatrix),this._aPosition.bindArrayBuffer(a.positionsBuf),this._aOffset.bindArrayBuffer(a.offsetsBuf),this._aNormal.bindArrayBuffer(a.normalsBuf),this._aColor.bindArrayBuffer(a.colorsBuf),this._aFlags.bindArrayBuffer(a.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(a.flags2Buf),a.indicesBuf.bind(),o.drawElements(o.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0)}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Pr(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uWorldNormalMatrix=i.getLocation("worldNormalMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uViewNormalMatrix=i.getLocation("viewNormalMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=e._sectionPlanesState.getNumAllocatedSectionPlanes();r<n;r++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+r),pos:i.getLocation("sectionPlanePos"+r),dir:i.getLocation("sectionPlaneDir"+r)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aNormal=i.getAttribute("normal"),this._aColor=i.getAttribute("color"),this._aFlags=i.getAttribute("flags"),this._aFlags2&&(this._aFlags2=i.getAttribute("flags2")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}}},{key:"_bindProgram",value:function(){var e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){var r=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,r)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&Cr.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),Cr.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(Cr.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&Cr.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&Cr.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(var r=0;r<e._sectionPlanesState.getNumAllocatedSectionPlanes();r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("in vec3 vViewNormal;"),i.push("vec3 packNormalToRGB( const in vec3 normal ) {"),i.push(" return normalize( normal ) * 0.5 + 0.5;"),i.push("}"),i.push("void main(void) {"),t){i.push(" bool clippable = (float(vFlags2.x) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n<e._sectionPlanesState.getNumAllocatedSectionPlanes();n++)i.push(" if (sectionPlaneActive"+n+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&Cr.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Pc=le.vec3(),Cc=le.vec3(),Mc=le.vec3();le.vec3(),le.vec4();var kc=le.mat4(),Ec=function(){function e(t,i){E(this,e),this._scene=t,this._withSAO=i,this._hash=this._getHash(),this._allocate()}return I(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,i){var r=this._scene,n=r.camera,s=t.model,o=r.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,c=s.position,A=s.rotationMatrix;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a));var h,d,p=e.pickViewMatrix||n.viewMatrix,f=e.pickProjMatrix||n.projMatrix,v=e.pickOrigin||n.eye,g=e.pickProjMatrix?e.pickZFar:n.project.far;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var m=0!==u[0]||0!==u[1]||0!==u[2],_=0!==c[0]||0!==c[1]||0!==c[2];if(m||_){var y=Pc;if(m){var b=le.transformPoint3(A,u,Cc);y[0]=b[0],y[1]=b[1],y[2]=b[2]}else y[0]=0,y[1]=0,y[2]=0;y[0]+=c[0],y[1]+=c[1],y[2]+=c[2],h=Jt(p,y,kc),(d=Mc)[0]=v[0]-y[0],d[1]=v[1]-y[1],d[2]=v[2]-y[2]}else h=p,d=v;if(o.uniform2fv(this._uPickClipPos,e.pickClipPos),o.uniform2f(this._uDrawingBufferSize,o.drawingBufferWidth,o.drawingBufferHeight),o.uniformMatrix4fv(this._uSceneModelMatrix,!1,A),o.uniformMatrix4fv(this._uViewMatrix,!1,h),o.uniformMatrix4fv(this._uProjMatrix,!1,f),o.uniform3fv(this._uCameraEyeRtc,d),o.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){var w=2/(Math.log(g+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,w)}var B=r._sectionPlanesState.getNumAllocatedSectionPlanes(),x=r._sectionPlanesState.sectionPlanes.length;if(B>0)for(var P=r._sectionPlanesState.sectionPlanes,C=t.layerIndex*x,M=s.renderFlags,k=0;k<B;k++){var E=this._uSectionPlanes[k];if(E)if(k<x){var F=M.sectionPlanesActivePerLayer[C+k];if(o.uniform1i(E.active,F?1:0),F){var I=P[k];if(u){var T=ei(I.dist,I.dir,u,Pc,s.matrix);o.uniform3fv(E.pos,T)}else o.uniform3fv(E.pos,I.pos);o.uniform3fv(E.dir,I.dir)}}else o.uniform1i(E.active,0)}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Pr(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=e._sectionPlanesState.getNumAllocatedSectionPlanes();r<n;r++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+r),pos:i.getLocation("sectionPlanePos"+r),dir:i.getLocation("sectionPlaneDir"+r)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}}},{key:"_bindProgram",value:function(e){var t=this._scene,i=t.canvas.gl,r=this._program,n=t.camera.project;if(r.bind(),t.logarithmicDepthBufferEnabled){var s=2/(Math.log(n.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,s)}}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(var r=0,n=e._sectionPlanesState.getNumAllocatedSectionPlanes();r<n;r++)i.push("uniform bool sectionPlaneActive"+r+";"),i.push("uniform vec3 sectionPlanePos"+r+";"),i.push("uniform vec3 sectionPlaneDir"+r+";")}if(i.push("out highp ivec4 outNormal;"),i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();s<o;s++)i.push("if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(" outNormal = ivec4(worldNormal * float(".concat(le.MAX_INT,"), 1.0);")),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Fc=function(){function e(t){E(this,e),this._scene=t}return I(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._silhouetteRenderer||(this._silhouetteRenderer=new Tu(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Wu(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Yu(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new Ec(this._scene)),this._snapRenderer||(this._snapRenderer=new rc(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new uc(this._scene)),this._snapRenderer||(this._snapRenderer=new rc(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Cu(this._scene,!1)),this._colorRenderer}},{key:"colorRendererWithSAO",get:function(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Cu(this._scene,!0)),this._colorRendererWithSAO}},{key:"colorQualityRendererWithSAO",get:function(){return this._colorQualityRendererWithSAO}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Tu(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new _c(this._scene)),this._depthRenderer}},{key:"normalsRenderer",get:function(){return this._normalsRenderer||(this._normalsRenderer=new xc(this._scene)),this._normalsRenderer}},{key:"edgesRenderer",get:function(){return this._edgesRenderer||(this._edgesRenderer=new Lu(this._scene)),this._edgesRenderer}},{key:"edgesColorRenderer",get:function(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Qu(this._scene)),this._edgesColorRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Wu(this._scene)),this._pickMeshRenderer}},{key:"pickNormalsRenderer",get:function(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Ec(this._scene)),this._pickNormalsRenderer}},{key:"pickNormalsFlatRenderer",get:function(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Ec(this._scene)),this._pickNormalsFlatRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Yu(this._scene)),this._pickDepthRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new rc(this._scene)),this._snapRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new uc(this._scene)),this._snapInitRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new pc(this._scene)),this._occlusionRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}]),e}(),Ic={};var Tc=I((function e(){E(this,e),this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]})),Dc=function(){function e(){E(this,e),this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}return I(e,[{key:"finalize",value:function(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}},{key:"bindCommonTextures",value:function(e,t,i,r,n){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,r,3),this.texturePerObjectInstanceMatrices.bindTexture(e,n,4)}},{key:"bindTriangleIndicesTextures",value:function(e,t,i,r){this.indicesPortionIdsPerBitnessTextures[r].bindTexture(e,t,5),this.indicesPerBitnessTextures[r].bindTexture(e,i,6)}},{key:"bindEdgeIndicesTextures",value:function(e,t,i,r){this.edgeIndicesPortionIdsPerBitnessTextures[r].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[r].bindTexture(e,i,6)}}]),e}(),Sc={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Sc,null,4));var e=0;Object.keys(Sc).forEach((function(t){t.startsWith("size")&&(e+=Sc[t])})),console.log("Total size ".concat(e," bytes (").concat((e/1e3/1e3).toFixed(2)," MB)")),console.log("Avg bytes / triangle: ".concat((e/Sc.totalPolygons).toFixed(2)));var t={};Object.keys(Sc).forEach((function(i){i.startsWith("size")&&(t[i]="".concat((Sc[i]/e*100).toFixed(2)," % of total"))})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};var Rc=function(){function e(){E(this,e)}return I(e,[{key:"disableBindedTextureFiltering",value:function(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}},{key:"createTextureForColorsAndFlags",value:function(e,t,i,r,n,s,o){var a=t.length;this.numPortions=a;var l=4096,u=Math.ceil(a/512);if(0===u)throw"texture height===0";var c=new Uint8Array(16384*u);Sc.sizeDataColorsAndFlags+=c.byteLength,Sc.numberOfTextures++;for(var A=0;A<a;A++)c.set(t[A],32*A+0),c.set(i[A],32*A+4),c.set([0,0,0,0],32*A+8),c.set([0,0,0,0],32*A+12),c.set([r[A]>>24&255,r[A]>>16&255,r[A]>>8&255,255&r[A]],32*A+16),c.set([n[A]>>24&255,n[A]>>16&255,n[A]>>8&255,255&n[A]],32*A+20),c.set([s[A]>>24&255,s[A]>>16&255,s[A]>>8&255,255&s[A]],32*A+24),c.set([o[A]?1:0,0,0,0],32*A+28);var h=e.createTexture();return e.bindTexture(e.TEXTURE_2D,h),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,u),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,u,e.RGBA_INTEGER,e.UNSIGNED_BYTE,c,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new cu(e,h,l,u,c)}},{key:"createTextureForObjectOffsets",value:function(e,t){var i=512,r=Math.ceil(t/i);if(0===r)throw"texture height===0";var n=new Float32Array(1536*r).fill(0);Sc.sizeDataTextureOffsets+=n.byteLength,Sc.numberOfTextures++;var s=e.createTexture();return e.bindTexture(e.TEXTURE_2D,s),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,r,e.RGB,e.FLOAT,n,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new cu(e,s,i,r,n)}},{key:"createTextureForInstancingMatrices",value:function(e,t){var i=t.length;if(0===i)throw"num instance matrices===0";var r=2048,n=Math.ceil(i/512),s=new Float32Array(8192*n);Sc.numberOfTextures++;for(var o=0;o<t.length;o++)s.set(t[o],16*o);var a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,r,n),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RGBA,e.FLOAT,s,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new cu(e,a,r,n,s)}},{key:"createTextureForPositionsDecodeMatrices",value:function(e,t){var i=t.length;if(0===i)throw"num decode+entity matrices===0";var r=2048,n=Math.ceil(i/512),s=new Float32Array(8192*n);Sc.sizeDataPositionDecodeMatrices+=s.byteLength,Sc.numberOfTextures++;for(var o=0;o<t.length;o++)s.set(t[o],16*o);var a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,r,n),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RGBA,e.FLOAT,s,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new cu(e,a,r,n)}},{key:"createTextureFor8BitIndices",value:function(e,t,i){if(0===i)return{texture:null,textureHeight:0};var r=4096,n=Math.ceil(i/3/r);if(0===n)throw"texture height===0";var s=new Uint8Array(r*n*3);Sc.sizeDataTextureIndices+=s.byteLength,Sc.numberOfTextures++;for(var o=0,a=0,l=t.length;o<l;o++){var u=t[o];s.set(u,a),a+=u.length}var c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RGB8UI,r,n),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RGB_INTEGER,e.UNSIGNED_BYTE,s,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new cu(e,c,r,n)}},{key:"createTextureFor16BitIndices",value:function(e,t,i){if(0===i)return{texture:null,textureHeight:0};var r=4096,n=Math.ceil(i/3/r);if(0===n)throw"texture height===0";var s=new Uint16Array(r*n*3);Sc.sizeDataTextureIndices+=s.byteLength,Sc.numberOfTextures++;for(var o=0,a=0,l=t.length;o<l;o++){var u=t[o];s.set(u,a),a+=u.length}var c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,r,n),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RGB_INTEGER,e.UNSIGNED_SHORT,s,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new cu(e,c,r,n)}},{key:"createTextureFor32BitIndices",value:function(e,t,i){if(0===i)return{texture:null,textureHeight:0};var r=4096,n=Math.ceil(i/3/r);if(0===n)throw"texture height===0";var s=new Uint32Array(r*n*3);Sc.sizeDataTextureIndices+=s.byteLength,Sc.numberOfTextures++;for(var o=0,a=0,l=t.length;o<l;o++){var u=t[o];s.set(u,a),a+=u.length}var c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32UI,r,n),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RGB_INTEGER,e.UNSIGNED_INT,s,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new cu(e,c,r,n)}},{key:"createTextureFor8BitsEdgeIndices",value:function(e,t,i){if(0===i)return{texture:null,textureHeight:0};var r=4096,n=Math.ceil(i/2/r);if(0===n)throw"texture height===0";var s=new Uint8Array(r*n*2);Sc.sizeDataTextureEdgeIndices+=s.byteLength,Sc.numberOfTextures++;for(var o=0,a=0,l=t.length;o<l;o++){var u=t[o];s.set(u,a),a+=u.length}var c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RG8UI,r,n),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RG_INTEGER,e.UNSIGNED_BYTE,s,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new cu(e,c,r,n)}},{key:"createTextureFor16BitsEdgeIndices",value:function(e,t,i){if(0===i)return{texture:null,textureHeight:0};var r=4096,n=Math.ceil(i/2/r);if(0===n)throw"texture height===0";var s=new Uint16Array(r*n*2);Sc.sizeDataTextureEdgeIndices+=s.byteLength,Sc.numberOfTextures++;for(var o=0,a=0,l=t.length;o<l;o++){var u=t[o];s.set(u,a),a+=u.length}var c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RG16UI,r,n),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RG_INTEGER,e.UNSIGNED_SHORT,s,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new cu(e,c,r,n)}},{key:"createTextureFor32BitsEdgeIndices",value:function(e,t,i){if(0===i)return{texture:null,textureHeight:0};var r=4096,n=Math.ceil(i/2/r);if(0===n)throw"texture height===0";var s=new Uint32Array(r*n*2);Sc.sizeDataTextureEdgeIndices+=s.byteLength,Sc.numberOfTextures++;for(var o=0,a=0,l=t.length;o<l;o++){var u=t[o];s.set(u,a),a+=u.length}var c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RG32UI,r,n),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RG_INTEGER,e.UNSIGNED_INT,s,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new cu(e,c,r,n)}},{key:"createTextureForPositions",value:function(e,t,i){var r=i/3,n=4096,s=Math.ceil(r/n);if(0===s)throw"texture height===0";var o=new Uint16Array(n*s*3);Sc.sizeDataTexturePositions+=o.byteLength,Sc.numberOfTextures++;for(var a=0,l=0,u=t.length;a<u;a++){var c=t[a];o.set(c,l),l+=c.length}var A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,n,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,s,e.RGB_INTEGER,e.UNSIGNED_SHORT,o,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new cu(e,A,n,s)}},{key:"createTextureForPackedPortionIds",value:function(e,t){if(0===t.length)return{texture:null,textureHeight:0};var i=t.length,r=4096,n=Math.ceil(i/r);if(0===n)throw"texture height===0";var s=new Uint16Array(r*n);s.set(t,0),Sc.sizeDataTexturePortionIds+=s.byteLength,Sc.numberOfTextures++;var o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.R16UI,r,n),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RED_INTEGER,e.UNSIGNED_SHORT,s,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new cu(e,o,r,n)}}]),e}(),Uc=new po,Lc=Uc.maxDataTextureHeight,Oc=le.vec4(),Nc=new Float32Array(16),Vc=new Uint8Array(4),Qc=new Float32Array(3),Hc=0,jc=le.identityMat4(),Gc=function(){function e(t,i){var r,n,s;E(this,e),Sc.numberOfLayers++,this._layerNumber=Hc++,this.sortId="TriDTX-".concat(this._layerNumber),this.layerIndex=i.layerIndex,this._renderers=(r=t.scene,n=r.id,(s=Ic[n])||(s=new Fc(r),Ic[n]=s,s._compile(),s.eagerCreateRenders(),r.on("compile",(function(){s._compile(),s.eagerCreateRenders()})),r.on("destroyed",(function(){delete Ic[n],s._destroy()}))),s),this.model=t,this._buffer=new Tc,this._dtxState=new Dc,this._dtxTextureFactory=new Rc,this._state=new nt({origin:le.vec3(i.origin),metallicRoughnessBuf:null,textureState:this._dtxState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numEdgeIndices8Bits:0,numEdgeIndices16Bits:0,numEdgeIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this.model.scene.readableGeometryEnabled&&(this._subPortionReadableGeometries={}),this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=le.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this.primitive=i.primitive,this._finalized=!1}return I(e,[{key:"aabb",get:function(){if(this.aabbDirty){le.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e<t;e++)le.expandAABB3(this._aabb,this._meshes[e].aabb);this.aabbDirty=!1}return this._aabb}},{key:"canCreatePortion",value:function(e){if(this._finalized)throw"Already finalized";var t=e.buckets.length;this._numPortions+t>65536&&Sc.cannotCreatePortion.because10BitsObjectId++;var i=this._numPortions+t<=65536,r=void 0!==e.geometryId&&null!==e.geometryId?"".concat(e.geometryId,"#").concat(0):"".concat(e.id,"#").concat(0);if(!this._bucketGeometries[r]){var n=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits),s=0,o=0;e.buckets.forEach((function(e){s+=e.positionsCompressed.length/3,o+=e.indices.length/3})),(this._state.numVertices+s>4096*Lc||n+o>4096*Lc)&&Sc.cannotCreatePortion.becauseTextureSize++,i&&(i=this._state.numVertices+s<=4096*Lc&&n+o<=4096*Lc)}return i}},{key:"createPortion",value:function(e,t){var i=this;if(this._finalized)throw"Already finalized";var r=[];t.buckets.forEach((function(e,n){var s=void 0!==t.geometryId&&null!==t.geometryId?"".concat(t.geometryId,"#").concat(n):"".concat(t.id,"#").concat(n),o=i._bucketGeometries[s];o||(o=i._createBucketGeometry(t,e),i._bucketGeometries[s]=o);var a=i._createSubPortion(t,o,e);r.push(a)}));var n=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(r),this.model.numPortions++,this._meshes.push(e),n}},{key:"_createBucketGeometry",value:function(e,t){if(t.indices){var i=8*Math.ceil(t.indices.length/3/8)*3;Sc.overheadSizeAlignementIndices+=2*(i-t.indices.length);var r=new Uint32Array(i);r.fill(0),r.set(t.indices),t.indices=r}if(t.edgeIndices){var n=8*Math.ceil(t.edgeIndices.length/2/8)*2;Sc.overheadSizeAlignementEdgeIndices+=2*(n-t.edgeIndices.length);var s=new Uint32Array(n);s.fill(0),s.set(t.edgeIndices),t.edgeIndices=s}var o=t.positionsCompressed,a=t.indices,l=t.edgeIndices,u=this._buffer;u.positionsCompressed.push(o);var c,A=u.lenPositionsCompressed/3,h=o.length/3;u.lenPositionsCompressed+=o.length;var d,p,f=0;a&&(f=a.length/3,h<=256?(d=u.indices8Bits,c=u.lenIndices8Bits/3,u.lenIndices8Bits+=a.length):h<=65536?(d=u.indices16Bits,c=u.lenIndices16Bits/3,u.lenIndices16Bits+=a.length):(d=u.indices32Bits,c=u.lenIndices32Bits/3,u.lenIndices32Bits+=a.length),d.push(a));var v,g=0;l&&(g=l.length/2,h<=256?(v=u.edgeIndices8Bits,p=u.lenEdgeIndices8Bits/2,u.lenEdgeIndices8Bits+=l.length):h<=65536?(v=u.edgeIndices16Bits,p=u.lenEdgeIndices16Bits/2,u.lenEdgeIndices16Bits+=l.length):(v=u.edgeIndices32Bits,p=u.lenEdgeIndices32Bits/2,u.lenEdgeIndices32Bits+=l.length),v.push(l));return this._state.numVertices+=h,Sc.numberOfGeometries++,{vertexBase:A,numVertices:h,numTriangles:f,numEdges:g,indicesBase:c,edgeIndicesBase:p}}},{key:"_createSubPortion",value:function(e,t,i,r){var n=e.color;e.metallic,e.roughness;var s,o,a=e.colors,l=e.opacity,u=e.meshMatrix,c=e.pickColor,A=this._buffer,h=this._state;A.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),A.perObjectInstancePositioningMatrices.push(u||jc),A.perObjectSolid.push(!!e.solid),a?A.perObjectColors.push([255*a[0],255*a[1],255*a[2],255]):n&&A.perObjectColors.push([n[0],n[1],n[2],l]),A.perObjectPickColors.push(c),A.perObjectVertexBases.push(t.vertexBase),s=t.numVertices<=256?h.numIndices8Bits:t.numVertices<=65536?h.numIndices16Bits:h.numIndices32Bits,A.perObjectIndexBaseOffsets.push(s/3-t.indicesBase),o=t.numVertices<=256?h.numEdgeIndices8Bits:t.numVertices<=65536?h.numEdgeIndices16Bits:h.numEdgeIndices32Bits,A.perObjectEdgeIndexBaseOffsets.push(o/2-t.edgeIndicesBase);var d=this._subPortions.length;if(t.numTriangles>0){var p,f=3*t.numTriangles;t.numVertices<=256?(p=A.perTriangleNumberPortionId8Bits,h.numIndices8Bits+=f,Sc.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(p=A.perTriangleNumberPortionId16Bits,h.numIndices16Bits+=f,Sc.totalPolygons16Bits+=t.numTriangles):(p=A.perTriangleNumberPortionId32Bits,h.numIndices32Bits+=f,Sc.totalPolygons32Bits+=t.numTriangles),Sc.totalPolygons+=t.numTriangles;for(var v=0;v<t.numTriangles;v+=8)p.push(d)}if(t.numEdges>0){var g,m=2*t.numEdges;t.numVertices<=256?(g=A.perEdgeNumberPortionId8Bits,h.numEdgeIndices8Bits+=m,Sc.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(g=A.perEdgeNumberPortionId16Bits,h.numEdgeIndices16Bits+=m,Sc.totalEdges16Bits+=t.numEdges):(g=A.perEdgeNumberPortionId32Bits,h.numEdgeIndices32Bits+=m,Sc.totalEdges32Bits+=t.numEdges),Sc.totalEdges+=t.numEdges;for(var _=0;_<t.numEdges;_+=8)g.push(d)}return this._subPortions.push({numVertices:t.numTriangles}),this.model.scene.readableGeometryEnabled&&(this._subPortionReadableGeometries[d]={indices:i.indices,positionsCompressed:i.positionsCompressed,positionsDecodeMatrix:e.positionsDecodeMatrix,meshMatrix:e.meshMatrix}),this._numPortions++,Sc.numberOfPortions++,d}},{key:"finalize",value:function(){var e=this;if(!this._finalized){var t=this._state,i=this._dtxState,r=this.model.scene.canvas.gl,n=this._buffer;t.gl=r,i.texturePerObjectColorsAndFlags=this._dtxTextureFactory.createTextureForColorsAndFlags(r,n.perObjectColors,n.perObjectPickColors,n.perObjectVertexBases,n.perObjectIndexBaseOffsets,n.perObjectEdgeIndexBaseOffsets,n.perObjectSolid),i.texturePerObjectInstanceMatrices=this._dtxTextureFactory.createTextureForInstancingMatrices(r,n.perObjectInstancePositioningMatrices),i.texturePerObjectPositionsDecodeMatrix=this._dtxTextureFactory.createTextureForPositionsDecodeMatrices(r,n.perObjectPositionsDecodeMatrices),i.texturePerVertexIdCoordinates=this._dtxTextureFactory.createTextureForPositions(r,n.positionsCompressed,n.lenPositionsCompressed),i.texturePerPolygonIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(r,n.perTriangleNumberPortionId8Bits),i.texturePerPolygonIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(r,n.perTriangleNumberPortionId16Bits),i.texturePerPolygonIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(r,n.perTriangleNumberPortionId32Bits),n.perEdgeNumberPortionId8Bits.length>0&&(i.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(r,n.perEdgeNumberPortionId8Bits)),n.perEdgeNumberPortionId16Bits.length>0&&(i.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(r,n.perEdgeNumberPortionId16Bits)),n.perEdgeNumberPortionId32Bits.length>0&&(i.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(r,n.perEdgeNumberPortionId32Bits)),n.lenIndices8Bits>0&&(i.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(r,n.indices8Bits,n.lenIndices8Bits)),n.lenIndices16Bits>0&&(i.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(r,n.indices16Bits,n.lenIndices16Bits)),n.lenIndices32Bits>0&&(i.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(r,n.indices32Bits,n.lenIndices32Bits)),n.lenEdgeIndices8Bits>0&&(i.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(r,n.edgeIndices8Bits,n.lenEdgeIndices8Bits)),n.lenEdgeIndices16Bits>0&&(i.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(r,n.edgeIndices16Bits,n.lenEdgeIndices16Bits)),n.lenEdgeIndices32Bits>0&&(i.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(r,n.edgeIndices32Bits,n.lenEdgeIndices32Bits)),i.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(function(){e._deferredSetFlagsDirty&&e._uploadDeferredFlags(),e._numUpdatesInFrame=0}))}}},{key:"isEmpty",value:function(){return 0===this._numPortions}},{key:"initFlags",value:function(e,t,i){t&gs&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Bs&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ws&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&xs&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ys&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Ps&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&_s&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ms&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags(),this._setDeferredFlags2()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&gs?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Bs?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ws?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&xs?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ps?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&ys?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}},{key:"_beginDeferredFlags",value:function(){this._deferredSetFlagsActive=!0}},{key:"_uploadDeferredFlags",value:function(){if(this._deferredSetFlagsActive=!1,this._deferredSetFlagsDirty){this._deferredSetFlagsDirty=!1;var e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ms?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&_s?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],r=0,n=i.length;r<n;r++)this._subPortionSetColor(i[r],t)}},{key:"_subPortionSetColor",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=this._dtxState,r=this.model.scene.canvas.gl;Vc[0]=t[0],Vc[1]=t[1],Vc[2]=t[2],Vc[3]=t[3],i.texturePerObjectColorsAndFlags._textureData.set(Vc,32*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),r.bindTexture(r.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),r.texSubImage2D(r.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,r.RGBA_INTEGER,r.UNSIGNED_BYTE,Vc))}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){for(var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=this._portionToSubPortionsMap[e],s=0,o=n.length;s<o;s++)this._subPortionSetFlags(n[s],t,i,r)}},{key:"_subPortionSetFlags",value:function(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var n,s,o=!!(t&gs),a=!!(t&ws),l=!!(t&Bs),u=!!(t&xs),c=!!(t&Ps),A=!!(t&_s),h=!!(t&ms);n=!o||h||a||l&&!this.model.scene.highlightMaterial.glowThrough||u&&!this.model.scene.selectedMaterial.glowThrough?Cs.NOT_RENDERED:i?Cs.COLOR_TRANSPARENT:Cs.COLOR_OPAQUE,s=!o||h?Cs.NOT_RENDERED:u?Cs.SILHOUETTE_SELECTED:l?Cs.SILHOUETTE_HIGHLIGHTED:a?Cs.SILHOUETTE_XRAYED:Cs.NOT_RENDERED;var d=0;d=!o||h?Cs.NOT_RENDERED:u?Cs.EDGES_SELECTED:l?Cs.EDGES_HIGHLIGHTED:a?Cs.EDGES_XRAYED:c?i?Cs.EDGES_COLOR_TRANSPARENT:Cs.EDGES_COLOR_OPAQUE:Cs.NOT_RENDERED;var p=o&&!h&&A?Cs.PICK:Cs.NOT_RENDERED,f=this._dtxState,v=this.model.scene.canvas.gl;Vc[0]=n,Vc[1]=s,Vc[2]=d,Vc[3]=p,f.texturePerObjectColorsAndFlags._textureData.set(Vc,32*e+8),this._deferredSetFlagsActive||r?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),v.bindTexture(v.TEXTURE_2D,f.texturePerObjectColorsAndFlags._texture),v.texSubImage2D(v.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,v.RGBA_INTEGER,v.UNSIGNED_BYTE,Vc))}},{key:"_setDeferredFlags",value:function(){}},{key:"_setFlags2",value:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=this._portionToSubPortionsMap[e],n=0,s=r.length;n<s;n++)this._subPortionSetFlags2(r[n],t,i)}},{key:"_subPortionSetFlags2",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this._finalized)throw"Not finalized";var r=t&ys?255:0,n=this._dtxState,s=this.model.scene.canvas.gl;Vc[0]=r,Vc[1]=0,Vc[2]=1,Vc[3]=2,n.texturePerObjectColorsAndFlags._textureData.set(Vc,32*e+12),this._deferredSetFlagsActive||i?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,n.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,Vc))}},{key:"_setDeferredFlags2",value:function(){}},{key:"setOffset",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],r=0,n=i.length;r<n;r++)this._subPortionSetOffset(i[r],t)}},{key:"_subPortionSetOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=this._dtxState,r=this.model.scene.canvas.gl;Qc[0]=t[0],Qc[1]=t[1],Qc[2]=t[2],i.texturePerObjectOffsets._textureData.set(Qc,3*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),r.bindTexture(r.TEXTURE_2D,i.texturePerObjectOffsets._texture),r.texSubImage2D(r.TEXTURE_2D,0,0,e,1,1,r.RGB,r.FLOAT,Qc))}},{key:"setMatrix",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],r=0,n=i.length;r<n;r++)this._subPortionSetMatrix(i[r],t)}},{key:"_subPortionSetMatrix",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=this._dtxState,r=this.model.scene.canvas.gl;Nc.set(t),i.texturePerObjectInstanceMatrices._textureData.set(Nc,16*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),r.bindTexture(r.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),r.texSubImage2D(r.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,r.RGBA,r.FLOAT,Nc))}},{key:"getEachVertex",value:function(e,t){if(this.model.scene.readableGeometryEnabled){var i=this._state,r=this._portionToSubPortionsMap[e];if(r)for(var n=0,s=r.length;n<s;n++){var o=r[n],a=this._subPortionReadableGeometries[o],l=a.positionsCompressed,u=a.positionsDecodeMatrix;a.meshMatrix;for(var c=i.origin,A=c[0],h=c[1],d=c[2],p=Oc,f=0,v=l.length;f<v;f+=3)p[0]=l[f],p[1]=l[f+1],p[2]=l[f+2],p[3]=1,le.decompressPosition(p,u),le.mulMat4v4(this.model.worldMatrix,p,p),p[0]+=A,p[1]+=h,p[2]+=d,t(p)}else this.model.error("portion not found: "+e)}}},{key:"getEachIndex",value:function(e,t){if(this.model.scene.readableGeometryEnabled){var i=this._portionToSubPortionsMap[e];if(i)for(var r=0,n=i.length;r<n;r++)for(var s=i[r],o=this._subPortionReadableGeometries[s].indices,a=0,l=o.length;a<l;a++)t(o[a]);else this.model.error("portion not found: "+e)}}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,Cs.COLOR_OPAQUE):this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE))}},{key:"_updateBackfaceCull",value:function(e,t){if(true!==t.backfaces){var i=t.gl;i.disable(i.CULL_FACE),t.backfaces=true}}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Cs.COLOR_TRANSPARENT))}},{key:"drawDepth",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE))}},{key:"drawNormals",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE))}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_XRAYED))}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_HIGHLIGHTED))}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Cs.SILHOUETTE_SELECTED))}},{key:"drawEdgesColorOpaque",value:function(e,t){this.model.scene.logarithmicDepthBufferEnabled?this.model.scene._loggedWarning||(console.log("Edge enhancement for SceneModel data texture layers currently disabled with logarithmic depth buffer"),this.model.scene._loggedWarning=!0):this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Cs.EDGES_COLOR_OPAQUE)}},{key:"drawEdgesColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Cs.EDGES_COLOR_TRANSPARENT)}},{key:"drawEdgesHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Cs.EDGES_HIGHLIGHTED)}},{key:"drawEdgesSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Cs.EDGES_SELECTED)}},{key:"drawEdgesXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Cs.EDGES_XRAYED)}},{key:"drawOcclusion",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE))}},{key:"drawShadow",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,Cs.COLOR_OPAQUE))}},{key:"setPickMatrices",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Cs.PICK))}},{key:"drawPickDepths",value:function(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Cs.PICK))}},{key:"drawSnapInit",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Cs.PICK))}},{key:"drawSnap",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Cs.PICK))}},{key:"drawPickNormals",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsRenderer&&this._renderers.pickNormalsRenderer.drawLayer(t,this,Cs.PICK))}},{key:"destroy",value:function(){if(!this._destroyed){var e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}}]),e}(),zc=function(){function e(t){E(this,e),this.id=t.id,this.colorTexture=t.colorTexture,this.alphaCutoff=t.alphaCutoff,this.metallicRoughnessTexture=t.metallicRoughnessTexture,this.normalsTexture=t.normalsTexture,this.emissiveTexture=t.emissiveTexture,this.occlusionTexture=t.occlusionTexture}return I(e,[{key:"destroy",value:function(){}}]),e}(),Wc=function(){function e(t){E(this,e),this.id=t.id,this.texture=t.texture}return I(e,[{key:"destroy",value:function(){this.texture&&(this.texture.destroy(),this.texture=null)}}]),e}(),Xc={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}},Kc=function(){function e(t,i,r){E(this,e),this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=t,this.onProgress=i,this.onError=r}return I(e,[{key:"itemStart",value:function(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}},{key:"itemEnd",value:function(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}},{key:"itemError",value:function(e){void 0!==this.onError&&this.onError(e)}},{key:"resolveURL",value:function(e){return this.urlModifier?this.urlModifier(e):e}},{key:"setURLModifier",value:function(e){return this.urlModifier=e,this}},{key:"addHandler",value:function(e,t){return this.handlers.push(e,t),this}},{key:"removeHandler",value:function(e){var t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}},{key:"getHandler",value:function(e){for(var t=0,i=this.handlers.length;t<i;t+=2){var r=this.handlers[t],n=this.handlers[t+1];if(r.global&&(r.lastIndex=0),r.test(e))return n}return null}}]),e}(),Zc=new Kc,Jc=function(){function e(t){E(this,e),this.manager=void 0!==t?t:Zc,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}return I(e,[{key:"load",value:function(){}},{key:"loadAsync",value:function(e,t){var i=this;return new Promise((function(r,n){i.load(e,r,t,n)}))}},{key:"parse",value:function(){}},{key:"setCrossOrigin",value:function(e){return this.crossOrigin=e,this}},{key:"setWithCredentials",value:function(e){return this.withCredentials=e,this}},{key:"setPath",value:function(e){return this.path=e,this}},{key:"setResourcePath",value:function(e){return this.resourcePath=e,this}},{key:"setRequestHeader",value:function(e){return this.requestHeader=e,this}}]),e}(),Yc={},qc=function(e){m(i,Jc);var t=y(i);function i(e){return E(this,i),t.call(this,e)}return I(i,[{key:"load",value:function(e,t,i,r){var n=this;void 0===e&&(e=""),void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);var s=Xc.get(e);if(void 0!==s)return this.manager.itemStart(e),ke.scheduleTask((function(){t&&t(s),n.manager.itemEnd(e)}),0),s;if(void 0===Yc[e]){Yc[e]=[],Yc[e].push({onLoad:t,onProgress:i,onError:r});var o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),a=this.mimeType,l=this.responseType;fetch(o).then((function(t){if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;var i=Yc[e],r=t.body.getReader(),n=t.headers.get("Content-Length"),s=n?parseInt(n):0,o=0!==s,a=0,l=new ReadableStream({start:function(e){!function t(){r.read().then((function(r){var n=r.done,l=r.value;if(n)e.close();else{a+=l.byteLength;for(var u=new ProgressEvent("progress",{lengthComputable:o,loaded:a,total:s}),c=0,A=i.length;c<A;c++){var h=i[c];h.onProgress&&h.onProgress(u)}e.enqueue(l),t()}}))}()}});return new Response(l)}throw Error('fetch for "'.concat(t.url,'" responded with ').concat(t.status,": ").concat(t.statusText))})).then((function(e){switch(l){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((function(e){return(new DOMParser).parseFromString(e,a)}));case"json":return e.json();default:if(void 0===a)return e.text();var t=/charset="?([^;"\s]*)"?/i.exec(a),i=t&&t[1]?t[1].toLowerCase():void 0,r=new TextDecoder(i);return e.arrayBuffer().then((function(e){return r.decode(e)}))}})).then((function(t){Xc.add(e,t);var i=Yc[e];delete Yc[e];for(var r=0,n=i.length;r<n;r++){var s=i[r];s.onLoad&&s.onLoad(t)}})).catch((function(t){var i=Yc[e];if(void 0===i)throw n.manager.itemError(e),t;delete Yc[e];for(var r=0,s=i.length;r<s;r++){var o=i[r];o.onError&&o.onError(t)}n.manager.itemError(e)})).finally((function(){n.manager.itemEnd(e)})),this.manager.itemStart(e)}else Yc[e].push({onLoad:t,onProgress:i,onError:r})}},{key:"setResponseType",value:function(e){return this.responseType=e,this}},{key:"setMimeType",value:function(e){return this.mimeType=e,this}}]),i}(),$c=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:4;E(this,e),this.pool=t,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}return I(e,[{key:"_initWorker",value:function(e){if(!this.workers[e]){var t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}},{key:"_getIdleWorker",value:function(){for(var e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return-1}},{key:"_onMessage",value:function(e,t){var i=this.workersResolve[e];if(i&&i(t),this.queue.length){var r=this.queue.shift(),n=r.resolve,s=r.msg,o=r.transfer;this.workersResolve[e]=n,this.workers[e].postMessage(s,o)}else this.workerStatus^=1<<e}},{key:"setWorkerCreator",value:function(e){this.workerCreator=e}},{key:"setWorkerLimit",value:function(e){this.pool=e}},{key:"postMessage",value:function(e,t){var i=this;return new Promise((function(r){var n=i._getIdleWorker();-1!==n?(i._initWorker(n),i.workerStatus|=1<<n,i.workersResolve[n]=r,i.workers[n].postMessage(e,t)):i.queue.push({resolve:r,msg:e,transfer:t})}))}},{key:"destroy",value:function(){this.workers.forEach((function(e){return e.terminate()})),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}]),e}(),eA=0,tA=function(){function e(t){var i=t.viewer,r=t.transcoderPath,n=t.workerLimit;E(this,e),this._transcoderPath=r||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new $c,this._workerSourceURL="",n&&this._workerPool.setWorkerLimit(n);var s=i.capabilities;this._workerConfig={astcSupported:s.astcSupported,etc1Supported:s.etc1Supported,etc2Supported:s.etc2Supported,dxtSupported:s.dxtSupported,bptcSupported:s.bptcSupported,pvrtcSupported:s.pvrtcSupported},this._supportedFileTypes=["xkt2"]}return I(e,[{key:"_init",value:function(){var t=this;if(!this._transcoderPending){var i=new qc;i.setPath(this._transcoderPath),i.setWithCredentials(this.withCredentials);var r=i.loadAsync("basis_transcoder.js"),n=new qc;n.setPath(this._transcoderPath),n.setResponseType("arraybuffer"),n.setWithCredentials(this.withCredentials);var s=n.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([r,s]).then((function(i){var r=C(i,2),n=r[0],s=r[1],o=e.BasisWorker.toString(),a=["/* constants */","let _EngineFormat = "+JSON.stringify(e.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(e.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(e.BasisFormat),"/* basis_transcoder.js */",n,"/* worker */",o.substring(o.indexOf("{")+1,o.lastIndexOf("}"))].join("\n");t._workerSourceURL=URL.createObjectURL(new Blob([a])),t._transcoderBinary=s,t._workerPool.setWorkerCreator((function(){var e=new Worker(t._workerSourceURL),i=t._transcoderBinary.slice(0);return e.postMessage({type:"init",config:t._workerConfig,transcoderBinary:i},[i]),e}))})),eA>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),eA++}return this._transcoderPending}},{key:"transcode",value:function(e,t){var i=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return new Promise((function(n,s){var o=r;i._init().then((function(){return i._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e)})).then((function(e){var i=e.data,r=i.mipmaps,o=(i.width,i.height,i.format),a=i.type,l=i.error,u=i.dfdTransferFn,c=i.dfdFlags;if("error"===a)return s(l);t.setCompressedData({mipmaps:r,props:{format:o,minFilter:1===r.length?1006:1008,magFilter:1===r.length?1006:1008,encoding:2===u?3001:3e3,premultiplyAlpha:!!(1&c)}}),n()}))}))}},{key:"destroy",value:function(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),eA--}}]),e}();tA.BasisFormat={ETC1S:0,UASTC_4x4:1},tA.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16},tA.EngineFormat={RGBAFormat:1023,RGBA_ASTC_4x4_Format:37808,RGBA_BPTC_Format:36492,RGBA_ETC2_EAC_Format:37496,RGBA_PVRTC_4BPPV1_Format:35842,RGBA_S3TC_DXT5_Format:33779,RGB_ETC1_Format:36196,RGB_ETC2_Format:37492,RGB_PVRTC_4BPPV1_Format:35840,RGB_S3TC_DXT1_Format:33776},tA.BasisWorker=function(){var e,t,i,r=_EngineFormat,n=_TranscoderFormat,s=_BasisFormat;self.addEventListener("message",(function(o){var c,A=o.data;switch(A.type){case"init":e=A.config,c=A.transcoderBinary,t=new Promise((function(e){i={wasmBinary:c,onRuntimeInitialized:e},BASIS(i)})).then((function(){i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((function(){try{for(var t=function(t){var o=new i.KTX2File(new Uint8Array(t));function c(){o.close(),o.delete()}if(!o.isValid())throw c(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");var A=o.isUASTC()?s.UASTC_4x4:s.ETC1S,h=o.getWidth(),d=o.getHeight(),p=o.getLevels(),f=o.getHasAlpha(),v=o.getDFDTransferFunc(),g=o.getDFDFlags(),m=function(t,i,o,c){for(var A,h,d=t===s.ETC1S?a:l,p=0;p<d.length;p++){var f=d[p];if(e[f.if]&&(f.basisFormat.includes(t)&&!(c&&f.transcoderFormat.length<2)&&(!f.needsPowerOfTwo||u(i)&&u(o))))return{transcoderFormat:A=f.transcoderFormat[c?1:0],engineFormat:h=f.engineFormat[c?1:0]}}return console.warn("KTX2TextureTranscoder: No suitable compressed texture format found. Decoding to RGBA32."),A=n.RGBA32,h=r.RGBAFormat,{transcoderFormat:A,engineFormat:h}}(A,h,d,f),_=m.transcoderFormat,y=m.engineFormat;if(!h||!d||!p)throw c(),new Error("KTX2TextureTranscoder: Invalid texture");if(!o.startTranscoding())throw c(),new Error("KTX2TextureTranscoder: .startTranscoding failed");for(var b=[],w=0;w<p;w++){var B=o.getImageLevelInfo(w,0,0),x=B.origWidth,P=B.origHeight,C=new Uint8Array(o.getImageTranscodedSizeInBytes(w,0,0,_));if(!o.transcodeImage(C,w,0,0,_,0,-1,-1))throw c(),new Error("KTX2TextureTranscoder: .transcodeImage failed.");b.push({data:C,width:x,height:P})}return c(),{width:h,height:d,hasAlpha:f,mipmaps:b,format:y,dfdTransferFn:v,dfdFlags:g}}(A.buffers[0]),o=t.width,c=t.height,h=t.hasAlpha,d=t.mipmaps,p=t.format,f=t.dfdTransferFn,v=t.dfdFlags,g=[],m=0;m<d.length;++m)g.push(d[m].data.buffer);self.postMessage({type:"transcode",id:A.id,width:o,height:c,hasAlpha:h,mipmaps:d,format:p,dfdTransferFn:f,dfdFlags:v},g)}catch(e){console.error("[KTX2TextureTranscoder.BasisWorker]: ".concat(e)),self.postMessage({type:"error",id:A.id,error:e.message})}}))}}));var o=[{if:"astcSupported",basisFormat:[s.UASTC_4x4],transcoderFormat:[n.ASTC_4x4,n.ASTC_4x4],engineFormat:[r.RGBA_ASTC_4x4_Format,r.RGBA_ASTC_4x4_Format],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[s.ETC1S,s.UASTC_4x4],transcoderFormat:[n.BC7_M5,n.BC7_M5],engineFormat:[r.RGBA_BPTC_Format,r.RGBA_BPTC_Format],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[s.ETC1S,s.UASTC_4x4],transcoderFormat:[n.BC1,n.BC3],engineFormat:[r.RGB_S3TC_DXT1_Format,r.RGBA_S3TC_DXT5_Format],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[s.ETC1S,s.UASTC_4x4],transcoderFormat:[n.ETC1,n.ETC2],engineFormat:[r.RGB_ETC2_Format,r.RGBA_ETC2_EAC_Format],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[s.ETC1S,s.UASTC_4x4],transcoderFormat:[n.ETC1],engineFormat:[r.RGB_ETC1_Format],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[s.ETC1S,s.UASTC_4x4],transcoderFormat:[n.PVRTC1_4_RGB,n.PVRTC1_4_RGBA],engineFormat:[r.RGB_PVRTC_4BPPV1_Format,r.RGBA_PVRTC_4BPPV1_Format],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0}],a=o.sort((function(e,t){return e.priorityETC1S-t.priorityETC1S})),l=o.sort((function(e,t){return e.priorityUASTC-t.priorityUASTC}));function u(e){return e<=2||0==(e&e-1)&&0!==e}};var iA={};function rA(e){var t=e.scene.id,i=iA[t];return i||(i=new tA({viewer:e}),iA[t]=i,e.scene.on("destroyed",(function(){delete iA[t],i.destroy()}))),i}
|
|
@@ -20,7 +20,7 @@ var e,t,i,r=l().mark(HP),n=l().mark(jP),s=l().mark(CE);function o(e){var t="func
|
|
|
20
20
|
/**
|
|
21
21
|
* @author https://github.com/tmarti, with support from https://tribia.com/
|
|
22
22
|
* @license MIT
|
|
23
|
-
**/var lA=null;function uA(e,t){var i,r,n,s,o,a,l=3*e,u=3*t,c=Math.min(i=lA[l],r=lA[l+1],n=lA[l+2]),A=Math.min(s=lA[u],o=lA[u+1],a=lA[u+2]);if(c!==A)return c-A;var h=Math.max(i,r,n),d=Math.max(s,o,a);return h!==d?h-d:0}function cA(e,t){for(var i=new Int32Array(e.length/3),r=0,n=i.length;r<n;r++)i[r]=r;lA=new Int32Array(e.length);for(var s=0,o=e.length;s<o;s++)lA[s]=e[s]>>t;i.sort(uA);for(var a=new Int32Array(e.length),l=0,u=i.length;l<u;l++)a[3*l+0]=e[3*i[l]+0],a[3*l+1]=e[3*i[l]+1],a[3*l+2]=e[3*i[l]+2];return a}var AA=null;function hA(e,t){var i=AA[2*e]-AA[2*t];return 0!==i?i:AA[2*e+1]-AA[2*t+1]}function dA(e){if(0===(e||[]).length)return[];for(var t=new Int32Array(e.length/2),i=0,r=t.length;i<r;i++)t[i]=i;for(var n=0,s=e.length;n<s;n+=2)if(e[n]>e[n+1]){var o=e[n];e[n]=e[n+1],e[n+1]=o}AA=new Int32Array(e),t.sort(hA);for(var a=new Int32Array(e.length),l=0,u=t.length;l<u;l++)a[2*l+0]=e[2*t[l]+0],a[2*l+1]=e[2*t[l]+1];return a}function pA(e,t){var i={},r={};e.forEach((function(e){for(var t=e.indices,n=e.edgeIndices,s=e.positionsCompressed,o=0,a=t.length;o<a;o+=3){var l=s[3*t[o]]+"_"+s[3*t[o]+1]+"_"+s[3*t[o]+2]+"/"+s[3*t[o+1]]+"_"+s[3*t[o+1]+1]+"_"+s[3*t[o+1]+2]+"/"+s[3*t[o+2]]+"_"+s[3*t[o+2]+1]+"_"+s[3*t[o+2]+2];i[l]=!0}e.edgeIndices.length/2;for(var u=0,c=n.length;u<c;u+=2){var A=s[3*n[u]]+"_"+s[3*n[u]+1]+"_"+s[3*n[u]+2]+"/"+s[3*n[u+1]]+"_"+s[3*n[u+1]+1]+"_"+s[3*n[u+1]+2]+"/";r[A]=!0}}));var n=t.indices;t.edgeIndices;for(var s=t.positionsCompressed,o=0,a=n.length;o<a;o+=3){var l=s[3*n[o]]+"_"+s[3*n[o]+1]+"_"+s[3*n[o]+2]+"/"+s[3*n[o+1]]+"_"+s[3*n[o+1]+1]+"_"+s[3*n[o+1]+2]+"/"+s[3*n[o+2]]+"_"+s[3*n[o+2]+1]+"_"+s[3*n[o+2]+2];if(!(l in i))throw console.log("Not found "+l),"Ohhhh!"}}var fA=new Float32Array([0,0,0]),vA=new Uint16Array([0,0,0]);le.OBB3();var gA=function(){function e(t,i,r,n,s,o){E(this,e),this._isObject=i,this.scene=t.scene,this.model=t,this.isSceneModelEntity=!0,this.meshes=n,this._numPrimitives=0,this._capMaterial=null;for(var a=0,l=this.meshes.length;a<l;a++){var u=this.meshes[a];u.parent=this,u.entity=this,this._numPrimitives+=u.numPrimitives}this.id=r,this.originalSystemId=le.unglobalizeObjectId(t.id,r),this._flags=s,this._aabb=le.AABB3(),this._aabbDirty=!0,this._offset=le.vec3(),this._colorizeUpdated=!1,this._opacityUpdated=!1,this._lodCullable=!!o,this._culled=!1,this._culledVFC=!1,this._culledLOD=!1,this._isObject&&t.scene._registerObject(this)}return I(e,[{key:"_transformDirty",value:function(){this._aabbDirty=!0,this.model._transformDirty()}},{key:"_sceneModelDirty",value:function(){this._aabbDirty=!0;for(var e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._sceneModelDirty()}},{key:"aabb",get:function(){if(this._aabbDirty){le.collapseAABB3(this._aabb);for(var e=0,t=this.meshes.length;e<t;e++)le.expandAABB3(this._aabb,this.meshes[e].aabb);this._aabbDirty=!1}return this._aabb}},{key:"isEntity",get:function(){return!0}},{key:"isModel",get:function(){return!1}},{key:"isObject",get:function(){return this._isObject}},{key:"numPrimitives",get:function(){return this._numPrimitives}},{key:"numTriangles",get:function(){return this._numPrimitives}},{key:"visible",get:function(){return this._getFlag(gs)},set:function(e){if(!!(this._flags&gs)!==e){this._flags=e?this._flags|gs:this._flags&~gs;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setVisible(this._flags);this._isObject&&this.model.scene._objectVisibilityUpdated(this),this.model.glRedraw()}}},{key:"highlighted",get:function(){return this._getFlag(Bs)},set:function(e){if(!!(this._flags&Bs)!==e){this._flags=e?this._flags|Bs:this._flags&~Bs;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this),this.model.glRedraw()}}},{key:"xrayed",get:function(){return this._getFlag(ws)},set:function(e){if(!!(this._flags&ws)!==e){this._flags=e?this._flags|ws:this._flags&~ws;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setXRayed(this._flags);this._isObject&&this.model.scene._objectXRayedUpdated(this),this.model.glRedraw()}}},{key:"selected",get:function(){return this._getFlag(xs)},set:function(e){if(!!(this._flags&xs)!==e){this._flags=e?this._flags|xs:this._flags&~xs;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setSelected(this._flags);this._isObject&&this.model.scene._objectSelectedUpdated(this),this.model.glRedraw()}}},{key:"edges",get:function(){return this._getFlag(Ps)},set:function(e){if(!!(this._flags&Ps)!==e){this._flags=e?this._flags|Ps:this._flags&~Ps;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setEdges(this._flags);this.model.glRedraw()}}},{key:"culledVFC",get:function(){return!!this._culledVFC},set:function(e){this._culledVFC=e,this._setCulled()}},{key:"culledLOD",get:function(){return!!this._culledLOD},set:function(e){this._culledLOD=e,this._setCulled()}},{key:"culled",get:function(){return!!this._culled},set:function(e){this._culled=e,this._setCulled()}},{key:"_setCulled",value:function(){var e=!!this._culled||!(!this._culledLOD||!this._lodCullable)||!!this._culledVFC;if(!!(this._flags&ms)!==e){this._flags=e?this._flags|ms:this._flags&~ms;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCulled(this._flags);this.model.glRedraw()}}},{key:"clippable",get:function(){return this._getFlag(ys)},set:function(e){if(!!(this._flags&ys)!==e){this._flags=e?this._flags|ys:this._flags&~ys;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}},{key:"collidable",get:function(){return this._getFlag(bs)},set:function(e){if(!!(this._flags&bs)!==e){this._flags=e?this._flags|bs:this._flags&~bs;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCollidable(this._flags)}}},{key:"pickable",get:function(){return this._getFlag(_s)},set:function(e){if(!!(this._flags&_s)!==e){this._flags=e?this._flags|_s:this._flags&~_s;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setPickable(this._flags)}}},{key:"colorize",get:function(){if(0===this.meshes.length)return null;var e=this.meshes[0]._colorize;return fA[0]=e[0]/255,fA[1]=e[1]/255,fA[2]=e[2]/255,fA},set:function(e){if(e){vA[0]=Math.floor(255*e[0]),vA[1]=Math.floor(255*e[1]),vA[2]=Math.floor(255*e[2]);for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setColorize(vA)}else for(var r=0,n=this.meshes.length;r<n;r++)this.meshes[r]._setColorize(null);if(this._isObject){var s=!!e;this.scene._objectColorizeUpdated(this,s),this._colorizeUpdated=s}this.model.glRedraw()}},{key:"opacity",get:function(){return this.meshes.length>0?this.meshes[0]._colorize[3]/255:1},set:function(e){if(0!==this.meshes.length){var t=null!=e,i=this.meshes[0]._colorize[3],r=255;if(t){if(e<0?e=0:e>1&&(e=1),i===(r=Math.floor(255*e)))return}else if(i===(r=255))return;for(var n=0,s=this.meshes.length;n<s;n++)this.meshes[n]._setOpacity(r,this._flags);this._isObject&&(this.scene._objectOpacityUpdated(this,t),this._opacityUpdated=t),this.model.glRedraw()}}},{key:"offset",get:function(){return this._offset},set:function(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setOffset(this._offset);this._aabbDirty=!0,this.model._aabbDirty=!0,this.scene._aabbDirty=!0,this.scene._objectOffsetUpdated(this,e),this.model.glRedraw()}},{key:"saoEnabled",get:function(){return this.model.saoEnabled}},{key:"capMaterial",get:function(){return this._capMaterial},set:function(e){this.scene.readableGeometryEnabled&&(this._capMaterial=e instanceof mn?e:null,this.scene._capMaterialUpdated(this.id,this.model.id))}},{key:"getEachVertex",value:function(e){for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t].getEachVertex(e)}},{key:"getEachIndex",value:function(e){for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t].getEachIndex(e)}},{key:"getGeometryData",value:function(){for(var e=0,t=[],i=[],r=0,n=this.meshes.length;r<n;r++){var s=this.meshes[r];if(s.layer.readGeometryData){for(var o=s.layer.readGeometryData(s.portionId),a=0,l=o.indices.length;a<l;a++)i.push(o.indices[a]+e);for(var u=0,c=o.positions.length;u<c;u++)t.push(o.positions[u]);e+=o.positions.length/3}}return{indices:i,positions:t}}},{key:"volume",get:function(){for(var e=0,t=0,i=this.meshes.length;t<i;t++){var r=this.meshes[t].volume;if(r<0)return-1;e+=r}return e}},{key:"surfaceArea",get:function(){for(var e=0,t=0,i=this.meshes.length;t<i;t++){var r=this.meshes[t].surfaceArea;r>=0&&(e+=r)}return e>0?e:-1}},{key:"_getFlag",value:function(e){return!!(this._flags&e)}},{key:"_finalize",value:function(){var e=this.model.scene;this._isObject&&(this.visible&&e._objectVisibilityUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this));for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._finalize(this._flags)}},{key:"_finalize2",value:function(){for(var e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize2()}},{key:"_destroy",value:function(){var e=this.model.scene;this._isObject&&(e._deregisterObject(this),this.visible&&e._deRegisterVisibleObject(this),this.xrayed&&e._deRegisterXRayedObject(this),this.selected&&e._deRegisterSelectedObject(this),this.highlighted&&e._deRegisterHighlightedObject(this),this._colorizeUpdated&&this.scene._deRegisterColorizedObject(this),this._opacityUpdated&&this.scene._deRegisterOpacityObject(this),!this._offset||0===this._offset[0]&&0===this._offset[1]&&0===this._offset[2]||this.scene._deRegisterOffsetObject(this));for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._destroy();e._aabbDirty=!0}}]),e}(),mA=le.vec4(4),_A=le.vec4(),yA=le.vec4(),bA=le.vec3([1,0,0]),wA=le.vec3([0,1,0]),BA=le.vec3([0,0,1]);le.vec3(3),le.vec3(3);var xA=le.identityMat4(),PA=function(){function e(t){E(this,e),this._model=t.model,this.id=t.id,this._parentTransform=t.parent,this._childTransforms=[],this._meshes=[],this._scale=new Float32Array([1,1,1]),this._quaternion=le.identityQuaternion(new Float32Array(4)),this._rotation=new Float32Array(3),this._position=new Float32Array(3),this._localMatrix=le.identityMat4(new Float32Array(16)),this._worldMatrix=le.identityMat4(new Float32Array(16)),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),t.parent&&t.parent._addChildTransform(this)}return I(e,[{key:"_addChildTransform",value:function(e){this._childTransforms.push(e),e._parentTransform=this,e._transformDirty(),e._setSubtreeAABBsDirty(this)}},{key:"_addMesh",value:function(e){this._meshes.push(e),e.transform=this}},{key:"parentTransform",get:function(){return this._parentTransform}},{key:"meshes",get:function(){return this._meshes}},{key:"position",get:function(){return this._position},set:function(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._model.glRedraw()}},{key:"rotation",get:function(){return this._rotation},set:function(e){this._rotation.set(e||[0,0,0]),le.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._model.glRedraw()}},{key:"quaternion",get:function(){return this._quaternion},set:function(e){this._quaternion.set(e||[0,0,0,1]),le.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._model.glRedraw()}},{key:"scale",get:function(){return this._scale},set:function(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._model.glRedraw()}},{key:"matrix",get:function(){return this._localMatrixDirty&&(this._localMatrix||(this._localMatrix=le.identityMat4()),le.composeMat4(this._position,this._quaternion,this._scale,this._localMatrix),this._localMatrixDirty=!1),this._localMatrix},set:function(e){this._localMatrix||(this._localMatrix=le.identityMat4()),this._localMatrix.set(e||xA),le.decomposeMat4(this._localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._transformDirty(),this._model.glRedraw()}},{key:"worldMatrix",get:function(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}},{key:"rotate",value:function(e,t){return mA[0]=e[0],mA[1]=e[1],mA[2]=e[2],mA[3]=t*le.DEGTORAD,le.angleAxisToQuaternion(mA,_A),le.mulQuaternions(this.quaternion,_A,yA),this.quaternion=yA,this._setLocalMatrixDirty(),this._model.glRedraw(),this}},{key:"rotateOnWorldAxis",value:function(e,t){return mA[0]=e[0],mA[1]=e[1],mA[2]=e[2],mA[3]=t*le.DEGTORAD,le.angleAxisToQuaternion(mA,_A),le.mulQuaternions(_A,this.quaternion,_A),this}},{key:"rotateX",value:function(e){return this.rotate(bA,e)}},{key:"rotateY",value:function(e){return this.rotate(wA,e)}},{key:"rotateZ",value:function(e){return this.rotate(BA,e)}},{key:"translate",value:function(e){return this._position[0]+=e[0],this._position[1]+=e[1],this._position[2]+=e[2],this._setLocalMatrixDirty(),this._model.glRedraw(),this}},{key:"translateX",value:function(e){return this._position[0]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}},{key:"translateY",value:function(e){return this._position[1]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}},{key:"translateZ",value:function(e){return this._position[2]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}},{key:"_setLocalMatrixDirty",value:function(){this._localMatrixDirty=!0,this._transformDirty()}},{key:"_transformDirty",value:function(){this._worldMatrixDirty=!0;for(var e=0,t=this._childTransforms.length;e<t;e++){var i=this._childTransforms[e];if(i._transformDirty(),i._meshes&&i._meshes.length>0)for(var r=i._meshes,n=0,s=r.length;n<s;n++)r[n]._transformDirty()}if(this._meshes&&this._meshes.length>0)for(var o=this._meshes,a=0,l=o.length;a<l;a++)o[a]._transformDirty()}},{key:"_buildWorldMatrix",value:function(){var e=this.matrix;if(this._parentTransform)le.mulMat4(this._parentTransform.worldMatrix,e,this._worldMatrix);else for(var t=0,i=e.length;t<i;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}},{key:"_setSubtreeAABBsDirty",value:function(e){if(e._aabbDirty=!0,e._childTransforms)for(var t=0,i=e._childTransforms.length;t<i;t++)this._setSubtreeAABBsDirty(e._childTransforms[t])}}]),e}(),CA=le.vec3(),MA=le.OBB3(),kA=le.vec4(),EA=le.vec3([1,1,1]),FA=le.vec3([0,0,0]);le.vec3([0,0,0]);var IA=le.identityQuaternion(),TA=le.identityMat4(),DA=new Uint8Array([255,255,255]),SA=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).renderOrder=n.renderOrder||0,r._dtxEnabled=r.scene.dtxEnabled&&!1!==n.dtxEnabled,r._enableVertexWelding=!1,r._enableIndexBucketing=!1,r._vboBatchingLayerScratchMemory=vs(),r._textureTranscoder=n.textureTranscoder||rA(r.scene.viewer),r._maxGeometryBatchSize=n.maxGeometryBatchSize,r._aabb=le.collapseAABB3(),r._aabbDirty=!0,r._quantizationRanges={},r._vboInstancingLayers={},r._vboBatchingLayers={},r._dtxLayers={},r._meshList=[],r.layerList=[],r._layersToFinalize=[],r._entityList=[],r._entitiesToFinalize=[],r._geometries={},r._dtxBuckets={},r._textures={},r._textureSets={},r._transforms={},r._meshes={},r._unusedMeshes={},r._entities={},r.renderFlags=new sn,r.numGeometries=0,r.numPortions=0,r.numVisibleLayerPortions=0,r.numTransparentLayerPortions=0,r.numXRayedLayerPortions=0,r.numHighlightedLayerPortions=0,r.numSelectedLayerPortions=0,r.numEdgesLayerPortions=0,r.numPickableLayerPortions=0,r.numClippableLayerPortions=0,r.numCulledLayerPortions=0,r.numEntities=0,r._numTriangles=0,r._numLines=0,r._numPoints=0,r._layersFinalized=!1,r._edgeThreshold=n.edgeThreshold||10,r._origin=le.vec3(n.origin||[0,0,0]),r._position=le.vec3(n.position||[0,0,0]),r._rotation=le.vec3(n.rotation||[0,0,0]),r._quaternion=le.vec4(n.quaternion||[0,0,0,1]),r._conjugateQuaternion=le.vec4(n.quaternion||[0,0,0,1]),n.rotation&&le.eulerToQuaternion(r._rotation,"XYZ",r._quaternion),r._scale=le.vec3(n.scale||[1,1,1]),r._worldRotationMatrix=le.mat4(),r._worldRotationMatrixConjugate=le.mat4(),r._matrix=le.mat4(),r._matrixDirty=!0,r._rebuildMatrices(),r._worldNormalMatrix=le.mat4(),le.inverseMat4(r._matrix,r._worldNormalMatrix),le.transposeMat4(r._worldNormalMatrix),(n.matrix||n.position||n.rotation||n.scale||n.quaternion)&&(r._viewMatrix=le.mat4(),r._viewNormalMatrix=le.mat4(),r._viewMatrixDirty=!0,r._matrixNonIdentity=!0),r._opacity=1,r._colorize=[1,1,1],r._saoEnabled=!1!==n.saoEnabled,r._pbrEnabled=!1!==n.pbrEnabled,r._colorTextureEnabled=!1!==n.colorTextureEnabled,r._isModel=n.isModel,r._isModel&&r.scene._registerModel(w(r)),r._onCameraViewMatrix=r.scene.camera.on("matrix",(function(){r._viewMatrixDirty=!0})),r._meshesWithDirtyMatrices=[],r._numMeshesWithDirtyMatrices=0,r._onTick=r.scene.on("tick",(function(){for(;r._numMeshesWithDirtyMatrices>0;)r._meshesWithDirtyMatrices[--r._numMeshesWithDirtyMatrices]._updateMatrix()})),r._createDefaultTextureSet(),r.visible=n.visible,r.culled=n.culled,r.pickable=n.pickable,r.clippable=n.clippable,r.collidable=n.collidable,r.castsShadow=n.castsShadow,r.receivesShadow=n.receivesShadow,r.xrayed=n.xrayed,r.highlighted=n.highlighted,r.selected=n.selected,r.edges=n.edges,r.colorize=n.colorize,r.opacity=n.opacity,r.backfaces=n.backfaces,r}return I(i,[{key:"_meshMatrixDirty",value:function(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}},{key:"_createDefaultTextureSet",value:function(){var e=new Wc({id:"defaultColorTexture",texture:new Pn({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new Wc({id:"defaultMetalRoughTexture",texture:new Pn({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new Wc({id:"defaultNormalsTexture",texture:new Pn({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),r=new Wc({id:"defaultEmissiveTexture",texture:new Pn({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),n=new Wc({id:"defaultOcclusionTexture",texture:new Pn({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=r,this._textures.defaultOcclusionTexture=n,this._textureSets.defaultTextureSet=new zc({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:r,occlusionTexture:n})}},{key:"isPerformanceModel",get:function(){return!0}},{key:"transforms",get:function(){return this._transforms}},{key:"textures",get:function(){return this._textures}},{key:"textureSets",get:function(){return this._textureSets}},{key:"meshes",get:function(){return this._meshes}},{key:"objects",get:function(){return this._entities}},{key:"origin",get:function(){return this._origin}},{key:"position",get:function(){return this._position},set:function(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"rotation",get:function(){return this._rotation},set:function(e){this._rotation.set(e||[0,0,0]),le.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"quaternion",get:function(){return this._quaternion},set:function(e){this._quaternion.set(e||[0,0,0,1]),le.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"scale",get:function(){return this._scale},set:function(e){}},{key:"matrix",get:function(){return this._rebuildMatrices(),this._matrix},set:function(e){this._matrix.set(e||TA),le.decomposeMat4(this._matrix,this._position,this._quaternion,this._scale),le.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"rotationMatrix",get:function(){return this._rebuildMatrices(),this._worldRotationMatrix}},{key:"_rebuildMatrices",value:function(){this._matrixDirty&&(le.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),le.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),le.quaternionToRotationMat4(this._conjugateQuaternion,this._worldRotationMatrixConjugate),le.scaleMat4v(this._scale,this._worldRotationMatrix),le.scaleMat4v(this._scale,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),le.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._viewMatrixDirty=!0)}},{key:"rotationMatrixConjugate",get:function(){return this._rebuildMatrices(),this._worldRotationMatrixConjugate}},{key:"_setWorldMatrixDirty",value:function(){this._matrixDirty=!0,this._aabbDirty=!0}},{key:"_transformDirty",value:function(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}},{key:"_sceneModelDirty",value:function(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(var e=0,t=this._entityList.length;e<t;e++)this._entityList[e]._sceneModelDirty()}},{key:"worldMatrix",get:function(){return this.matrix}},{key:"worldNormalMatrix",get:function(){return this._worldNormalMatrix}},{key:"_rebuildViewMatrices",value:function(){this._rebuildMatrices(),this._viewMatrixDirty&&(le.mulMat4(this.scene.camera.viewMatrix,this._matrix,this._viewMatrix),le.inverseMat4(this._viewMatrix,this._viewNormalMatrix),le.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1)}},{key:"viewMatrix",get:function(){return this._viewMatrix?(this._rebuildViewMatrices(),this._viewMatrix):this.scene.camera.viewMatrix}},{key:"viewNormalMatrix",get:function(){return this._viewNormalMatrix?(this._rebuildViewMatrices(),this._viewNormalMatrix):this.scene.camera.viewNormalMatrix}},{key:"backfaces",get:function(){return this._backfaces},set:function(e){e=!!e,this._backfaces=e,this.glRedraw()}},{key:"entityList",get:function(){return this._entityList}},{key:"isEntity",get:function(){return!0}},{key:"isModel",get:function(){return this._isModel}},{key:"isObject",get:function(){return!1}},{key:"aabb",get:function(){if(this._aabbDirty){le.collapseAABB3(this._aabb);for(var e=0,t=this._entityList.length;e<t;e++)le.expandAABB3(this._aabb,this._entityList[e].aabb);this._aabbDirty=!1}return this._aabb}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"numLines",get:function(){return this._numLines}},{key:"numPoints",get:function(){return this._numPoints}},{key:"visible",get:function(){return this.numVisibleLayerPortions>0},set:function(e){e=!1!==e,this._visible=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].visible=e;this.glRedraw()}},{key:"xrayed",get:function(){return this.numXRayedLayerPortions>0},set:function(e){e=!!e,this._xrayed=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].xrayed=e;this.glRedraw()}},{key:"highlighted",get:function(){return this.numHighlightedLayerPortions>0},set:function(e){e=!!e,this._highlighted=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].highlighted=e;this.glRedraw()}},{key:"selected",get:function(){return this.numSelectedLayerPortions>0},set:function(e){e=!!e,this._selected=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].selected=e;this.glRedraw()}},{key:"edges",get:function(){return this.numEdgesLayerPortions>0},set:function(e){e=!!e,this._edges=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].edges=e;this.glRedraw()}},{key:"culled",get:function(){return this._culled},set:function(e){e=!!e,this._culled=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].culled=e;this.glRedraw()}},{key:"clippable",get:function(){return this._clippable},set:function(e){e=!1!==e,this._clippable=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].clippable=e;this.glRedraw()}},{key:"collidable",get:function(){return this._collidable},set:function(e){e=!1!==e,this._collidable=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].collidable=e}},{key:"pickable",get:function(){return this.numPickableLayerPortions>0},set:function(e){e=!1!==e,this._pickable=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].pickable=e}},{key:"colorize",get:function(){return this._colorize},set:function(e){this._colorize=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].colorize=e}},{key:"opacity",get:function(){return this._opacity},set:function(e){this._opacity=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].opacity=e}},{key:"castsShadow",get:function(){return this._castsShadow},set:function(e){(e=!1!==e)!==this._castsShadow&&(this._castsShadow=e,this.glRedraw())}},{key:"receivesShadow",get:function(){return this._receivesShadow},set:function(e){(e=!1!==e)!==this._receivesShadow&&(this._receivesShadow=e,this.glRedraw())}},{key:"saoEnabled",get:function(){return this._saoEnabled}},{key:"pbrEnabled",get:function(){return this._pbrEnabled}},{key:"colorTextureEnabled",get:function(){return this._colorTextureEnabled}},{key:"isDrawable",get:function(){return!0}},{key:"isStateSortable",get:function(){return!1}},{key:"xrayMaterial",get:function(){return this.scene.xrayMaterial}},{key:"highlightMaterial",get:function(){return this.scene.highlightMaterial}},{key:"selectedMaterial",get:function(){return this.scene.selectedMaterial}},{key:"edgeMaterial",get:function(){return this.scene.edgeMaterial}},{key:"getPickViewMatrix",value:function(e){return this._viewMatrix?this._viewMatrix:e}},{key:"createQuantizationRange",value:function(e){void 0!==e.id&&null!==e.id?e.aabb?this.error("[createQuantizationRange] Config missing: aabb"):this._quantizationRanges[e.id]?this.error("[createQuantizationRange] QuantizationRange already created: "+e.id):this._quantizationRanges[e.id]={id:e.id,aabb:e.aabb,matrix:yo(e.aabb,le.mat4())}:this.error("[createQuantizationRange] Config missing: id")}},{key:"createGeometry",value:function(e){if(void 0!==e.id&&null!==e.id)if(this._geometries[e.id])this.error("[createGeometry] Geometry already created: "+e.id);else if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"===e.primitive||"lines"===e.primitive||"triangles"===e.primitive||"solid"===e.primitive||"surface"===e.primitive){if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("[createGeometry] Param expected: `positions`, `positionsCompressed' or 'buckets"),null;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("[createGeometry] Param expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.positionsDecodeMatrix&&e.positionsDecodeBoundary)return this.error("[createGeometry] Only one of these params expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("[createGeometry] Param expected: `uvDecodeMatrix` (required for `uvCompressed')"),null;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){var t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return this.error("[createGeometry] Param expected: indices (required for '".concat(e.primitive,"' primitive type)")),null;if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=yo(e.positionsDecodeBoundary,le.mat4())),e.positions){var i=le.collapseAABB3();e.positionsDecodeMatrix=le.mat4(),le.expandAABB3Points3(i,e.positions),e.positionsCompressed=_o(e.positions,i,e.positionsDecodeMatrix),e.aabb=i}else if(e.positionsCompressed){var r=le.collapseAABB3();e.positionsDecodeMatrix=new Float64Array(e.positionsDecodeMatrix),e.positionsCompressed=new Uint16Array(e.positionsCompressed),le.expandAABB3Points3(r,e.positionsCompressed),ft.decompressAABB(r,e.positionsDecodeMatrix),e.aabb=r}else if(e.buckets){var n=le.collapseAABB3();this._dtxBuckets[e.id]=e.buckets;for(var s=0,o=e.buckets.length;s<o;s++){var a=e.buckets[s];a.positions?le.expandAABB3Points3(n,a.positions):a.positionsCompressed&&le.expandAABB3Points3(n,a.positionsCompressed)}e.positionsDecodeMatrix&&ft.decompressAABB(n,e.positionsDecodeMatrix),e.aabb=n}if(e.colorsCompressed&&e.colorsCompressed.length>0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){for(var l=e.colors,u=new Uint8Array(l.length),c=0,A=l.length;c<A;c++)u[c]=255*l[c];e.colorsCompressed=u}if(e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=ot(e.positions,e.indices,null,5):e.edgeIndices=ot(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.uv){var h=ft.getUVBounds(e.uv),d=ft.compressUVs(e.uv,h.min,h.max);e.uvCompressed=d.quantized,e.uvDecodeMatrix=d.decodeMatrix}else e.uvCompressed&&(e.uvCompressed=new Uint16Array(e.uvCompressed),e.uvDecodeMatrix=new Float64Array(e.uvDecodeMatrix));e.normals&&(e.normals=null),this._geometries[e.id]=e,this._numTriangles+=e.indices?Math.round(e.indices.length/3):0,this.numGeometries++}else this.error("[createGeometry] Unsupported value for 'primitive': '".concat(e.primitive,"' - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'. Defaulting to 'triangles'."));else this.error("[createGeometry] Config missing: id")}},{key:"createTexture",value:function(e){var t=this,i=e.id;if(null!=i)if(this._textures[i])this.error("[createTexture] Texture already created: "+i);else{if(!e.src&&!e.image&&!e.buffers)return this.error("[createTexture] Param expected: `src`, `image' or 'buffers'"),null;var r=e.minFilter||1008;1006!==r&&1007!==r&&1008!==r&&1005!==r&&1004!==r&&(this.error("[createTexture] Unsupported value for 'minFilter' - \n supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, \n NearestMipMapLinearFilter and LinearMipmapLinearFilter. Defaulting to LinearMipmapLinearFilter."),r=1008);var n=e.magFilter||1006;1006!==n&&1003!==n&&(this.error("[createTexture] Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),n=1006);var s=e.wrapS||1e3;1001!==s&&1002!==s&&1e3!==s&&(this.error("[createTexture] Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),s=1e3);var o=e.wrapT||1e3;1001!==o&&1002!==o&&1e3!==o&&(this.error("[createTexture] Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),o=1e3);var a=e.wrapR||1e3;1001!==a&&1002!==a&&1e3!==a&&(this.error("[createTexture] Unsupported value for 'wrapR' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),a=1e3);var l=e.encoding||3e3;3e3!==l&&3001!==l&&(this.error("[createTexture] Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),l=3e3);var u=new Pn({gl:this.scene.canvas.gl,minFilter:r,magFilter:n,wrapS:s,wrapT:o,wrapR:a,encoding:l});if(e.preloadColor&&u.setPreloadColor(e.preloadColor),e.image){var c=e.image;if(c.crossOrigin="Anonymous",c.compressed){var A=c.data;u.setCompressedData({mipmaps:A,props:{format:A[0].format,minFilter:r,magFilter:n}})}else u.setImage(c,{minFilter:r,magFilter:n,wrapS:s,wrapT:o,wrapR:a,flipY:e.flipY,encoding:l})}else if(e.src){var h=e.src.split(".").pop();switch(h){case"jpeg":case"jpg":case"png":case"gif":var d=new Image;d.onload=function(){u.setImage(d,{minFilter:r,magFilter:n,wrapS:s,wrapT:o,wrapR:a,flipY:e.flipY,encoding:l}),t.glRedraw()},d.src=e.src;break;default:this._textureTranscoder?ge.loadArraybuffer(e.src,(function(e){e.byteLength?t._textureTranscoder.transcode([e],u).then((function(){t.glRedraw()})):t.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error("[createTexture] Can't create texture from 'src': ".concat(e))})):this.error("[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('".concat(h,"')"))}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,u).then((function(){t.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[i]=new Wc({id:i,texture:u})}else this.error("[createTexture] Config missing: id")}},{key:"createTextureSet",value:function(e){var t=e.id;if(null!=t){if(!this._textureSets[t]){var i,r,n,s,o;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(!(i=this._textures[e.colorTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.colorTextureId," - ensure that you create it first with createTexture()"))}else i=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(!(r=this._textures[e.metallicRoughnessTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.metallicRoughnessTextureId," - ensure that you create it first with createTexture()"))}else r=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(!(n=this._textures[e.normalsTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.normalsTextureId," - ensure that you create it first with createTexture()"))}else n=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(!(s=this._textures[e.emissiveTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.emissiveTextureId," - ensure that you create it first with createTexture()"))}else s=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(!(o=this._textures[e.occlusionTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.occlusionTextureId," - ensure that you create it first with createTexture()"))}else o=this._textures.defaultOcclusionTexture;var a=new zc({id:t,model:this,colorTexture:i,alphaCutoff:e.alphaCutoff,metallicRoughnessTexture:r,normalsTexture:n,emissiveTexture:s,occlusionTexture:o});return this._textureSets[t]=a,a}this.error("[createTextureSet] Texture set already created: ".concat(t))}else this.error("[createTextureSet] Config missing: id")}},{key:"createTransform",value:function(e){if(void 0!==e.id&&null!==e.id)if(this._transforms[e.id])this.error("[createTransform] SceneModel already has a transform with this ID: ".concat(e.id));else{var t;if(!e.parentTransformId||(t=this._transforms[e.parentTransformId])){var i=new PA({id:e.id,model:this,parent:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[i.id]=i,i}this.error("[createTransform] SceneModel.createTransform() config missing: id")}else this.error("[createTransform] SceneModel.createTransform() config missing: id")}},{key:"createMesh",value:function(e){if(void 0===e.id||null===e.id)return this.error("[createMesh] SceneModel.createMesh() config missing: id"),!1;if(this._meshes[e.id])return this.error("[createMesh] SceneModel already has a mesh with this ID: ".concat(e.id)),!1;if(!(void 0!==e.geometryId)){if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"!==e.primitive&&"lines"!==e.primitive&&"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)return this.error("Unsupported value for 'primitive': '".concat(primitive,"' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.")),!1;if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),!1;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),!1;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){var t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return e.indices=this._createDefaultIndices(numIndices),this.error("Param expected: indices (required for '".concat(e.primitive,"' primitive type)")),!1;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),!1;var i=!(!this._dtxEnabled||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||e.textureSetId);if(e.origin=e.origin?le.addVec3(this._origin,e.origin,le.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){var r=e.scale||EA,n=e.position||FA;e.rotation?(le.eulerToQuaternion(e.rotation,"XYZ",kA),e.meshMatrix=le.composeMat4(n,kA,r,le.mat4())):e.meshMatrix=le.composeMat4(n,e.quaternion||IA,r,le.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=yo(e.positionsDecodeBoundary,le.mat4())),i){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):DA,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){var s=le.vec3(),o=[];qt(e.positions,o,s)&&(e.positions=o,e.origin=le.addVec3(e.origin,s,s))}if(e.positions){var a=le.collapseAABB3();e.positionsDecodeMatrix=le.mat4(),le.expandAABB3Points3(a,e.positions),e.positionsCompressed=_o(e.positions,a,e.positionsDecodeMatrix),e.aabb=a}else if(e.positionsCompressed){var l=le.collapseAABB3();le.expandAABB3Points3(l,e.positionsCompressed),ft.decompressAABB(l,e.positionsDecodeMatrix),e.aabb=l}if(e.buckets){for(var u=le.collapseAABB3(),c=0,A=e.buckets.length;c<A;c++){var h=e.buckets[c];h.positions?le.expandAABB3Points3(u,h.positions):h.positionsCompressed&&le.expandAABB3Points3(u,h.positionsCompressed)}e.positionsDecodeMatrix&&ft.decompressAABB(u,e.positionsDecodeMatrix),e.aabb=u}e.meshMatrix&&(le.AABB3ToOBB3(e.aabb,MA),le.transformOBB3(e.meshMatrix,MA),le.OBB3ToAABB3(MA,e.aabb)),e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=ot(e.positions,e.indices,null,2):e.edgeIndices=ot(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.buckets||(e.buckets=RA(e,this._enableVertexWelding&&this._enableIndexBucketing))}else{if(e.type=1,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):[255,255,255],e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.positions){var d=[];qt(e.positions,d,CA)&&(e.positions=d,e.origin=le.addVec3(e.origin,CA,le.vec3()))}if(e.positions){var p=le.collapseAABB3();e.meshMatrix&&(le.transformPositions3(e.meshMatrix,e.positions,e.positions),e.meshMatrix=null),le.expandAABB3Points3(p,e.positions),e.aabb=p}else{var f=le.collapseAABB3();le.expandAABB3Points3(f,e.positionsCompressed),ft.decompressAABB(f,e.positionsDecodeMatrix),e.aabb=f}if(e.meshMatrix&&(le.AABB3ToOBB3(e.aabb,MA),le.transformOBB3(e.meshMatrix,MA),le.OBB3ToAABB3(MA,e.aabb)),e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=ot(e.positions,e.indices,null,2):e.edgeIndices=ot(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId],!e.textureSet))return this.error("[createMesh] Texture set not found: ".concat(e.textureSetId," - ensure that you create it first with createTextureSet()")),!1}}else{if(e.positions||e.positionsCompressed||e.indices||e.edgeIndices||e.normals||e.normalsCompressed||e.uv||e.uvCompressed||e.positionsDecodeMatrix)return this.error("Mesh geometry parameters not expected when instancing a geometry (not expected: positions, positionsCompressed, indices, edgeIndices, normals, normalsCompressed, uv, uvCompressed, positionsDecodeMatrix)"),!1;if(e.geometry=this._geometries[e.geometryId],!e.geometry)return this.error("[createMesh] Geometry not found: ".concat(e.geometryId," - ensure that you create it first with createGeometry()")),!1;if(e.origin=e.origin?le.addVec3(this._origin,e.origin,le.vec3()):this._origin,e.positionsDecodeMatrix=e.geometry.positionsDecodeMatrix,e.transformId){if(e.transform=this._transforms[e.transformId],!e.transform)return this.error("[createMesh] Transform not found: ".concat(e.transformId," - ensure that you create it first with createTransform()")),!1;e.aabb=e.geometry.aabb}else{if(e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){var v=e.scale||EA,g=e.position||FA;e.rotation?(le.eulerToQuaternion(e.rotation,"XYZ",kA),e.meshMatrix=le.composeMat4(g,kA,v,le.mat4())):e.meshMatrix=le.composeMat4(g,e.quaternion||IA,v,le.mat4())}le.AABB3ToOBB3(e.geometry.aabb,MA),le.transformOBB3(e.meshMatrix,MA),e.aabb=le.OBB3ToAABB3(MA,le.AABB3())}if(!(!this._dtxEnabled||"triangles"!==e.geometry.primitive&&"solid"!==e.geometry.primitive&&"surface"!==e.geometry.primitive||e.textureSetId)){e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):DA,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255;var m=this._dtxBuckets[e.geometryId];m||(m=RA(e.geometry,this._enableVertexWelding,this._enableIndexBucketing),this._dtxBuckets[e.geometryId]=m),e.buckets=m}else e.type=0,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):DA,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId])}return e.numPrimitives=this._getNumPrimitives(e),this._createMesh(e)}},{key:"_createDefaultIndices",value:function(e){for(var t=[],i=0;i<e;i++)t.push(i);return t}},{key:"_createMesh",value:function(e){var t=new ds(this,e.id,e.color,e.opacity,e.transform,e.textureSet);t.pickId=this.scene._renderer.getPickID(t);var i=t.pickId,r=i>>24&255,n=i>>16&255,s=i>>8&255,o=255&i;switch(e.pickColor=new Uint8Array([o,s,n,r]),e.solid="solid"===e.primitive,t.origin=le.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),t.numPrimitives=e.numPrimitives,this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}},{key:"_getNumPrimitives",value:function(e){var t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(var i=0,r=e.buckets.length;i<r;i++)t+=e.buckets[i].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/3);case"points":switch(e.type){case 2:for(var n=0,s=e.buckets.length;n<s;n++)t+=e.buckets[n].positionsCompressed.length;break;case 1:t+=e.positions?e.positions.length:e.positionsCompressed.length;break;case 0:var o=e.geometry;t+=o.positions?o.positions.length:o.positionsCompressed.length}return Math.round(t);case"lines":case"line-strip":switch(e.type){case 2:for(var a=0,l=e.buckets.length;a<l;a++)t+=e.buckets[a].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/2)}return 0}},{key:"_getDTXLayer",value:function(e){var t=e.origin,i=e.geometry?e.geometry.primitive:e.primitive,r=".".concat(i,".").concat(Math.round(t[0]),".").concat(Math.round(t[1]),".").concat(Math.round(t[2])),n=this._dtxLayers[r];if(n){if(n.canCreatePortion(e))return n;delete this._dtxLayers[r],n=null}switch(i){case"triangles":case"solid":case"surface":n=new Gc(this,{layerIndex:0,origin:t,primitive:i});break;case"lines":n=new yu(this,{layerIndex:0,origin:t,primitive:i});break;default:return}return this._dtxLayers[r]=n,this.layerList.push(n),this._layersToFinalize.push(n),n}},{key:"_getVBOBatchingLayer",value:function(e){var t=this,i=e.origin;e.renderLayer;var r=e.positionsDecodeMatrix||e.positionsDecodeBoundary?this._createHashStringFromMatrix(e.positionsDecodeMatrix||e.positionsDecodeBoundary):"-",n=e.textureSetId||"-",s="".concat(Math.round(i[0]),".").concat(Math.round(i[1]),".").concat(Math.round(i[2]),".").concat(e.primitive,".").concat(r,".").concat(n),o=this._vboBatchingLayers[s];if(o)return o;for(var a=e.textureSet;!o;){switch(e.primitive){case"triangles":case"solid":case"surface":o=new Do({model:t,textureSet:a,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:i,maxGeometryBatchSize:this._maxGeometryBatchSize,solid:"solid"===e.primitive,autoNormals:!0,primitive:e.primitive});break;case"lines":o=new ja({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:i,maxGeometryBatchSize:this._maxGeometryBatchSize,primitive:e.primitive});break;case"points":o=new Fl({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:i,maxGeometryBatchSize:this._maxGeometryBatchSize,primitive:e.primitive})}var l=e.positionsCompressed?e.positionsCompressed.length:e.positions.length;("points"===e.primitive?o.canCreatePortion(l):o.canCreatePortion(l,e.indices.length))||(o.finalize(),delete this._vboBatchingLayers[s],o=null)}return this._vboBatchingLayers[s]=o,this.layerList.push(o),this._layersToFinalize.push(o),o}},{key:"_createHashStringFromMatrix",value:function(e){for(var t=e.join(""),i=0,r=0;r<t.length;r++){i=(i<<5)-i+t.charCodeAt(r),i|=0}return(i>>>0).toString(16)}},{key:"_getVBOInstancingLayer",value:function(e){var t=this,i=e.origin,r=e.textureSetId||"-",n=e.geometryId,s="".concat(Math.round(i[0]),".").concat(Math.round(i[1]),".").concat(Math.round(i[2]),".").concat(r,".").concat(n),o=this._vboInstancingLayers[s];if(o)return o;for(var a=e.textureSet,l=e.geometry;!o;)switch(l.primitive){case"triangles":case"surface":o=new xa({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":o=new xa({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":o=new ul({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":o=new tu({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[s]=o,this.layerList.push(o),this._layersToFinalize.push(o),o}},{key:"createEntity",value:function(e){if(void 0===e.id?e.id=le.createUUID():this.scene.components[e.id]&&(this.error("Scene already has a Component with this ID: ".concat(e.id," - will assign random ID")),e.id=le.createUUID()),void 0!==e.meshIds){var t=0;return this._visible&&!1!==e.visible&&(t|=gs),this._pickable&&!1!==e.pickable&&(t|=_s),this._culled&&!1!==e.culled&&(t|=ms),this._clippable&&!1!==e.clippable&&(t|=ys),this._collidable&&!1!==e.collidable&&(t|=bs),this._edges&&!1!==e.edges&&(t|=Ps),this._xrayed&&!1!==e.xrayed&&(t|=ws),this._highlighted&&!1!==e.highlighted&&(t|=Bs),this._selected&&!1!==e.selected&&(t|=xs),e.flags=t,this._createEntity(e)}this.error("Config missing: meshIds")}},{key:"_createEntity",value:function(e){for(var t=[],i=0,r=e.meshIds.length;i<r;i++){var n=e.meshIds[i],s=this._meshes[n];s?s.parent?this.error('Mesh with ID "'.concat(n,'" already belongs to object with ID "').concat(s.parent.id,'" - ignoring this mesh')):(t.push(s),delete this._unusedMeshes[n]):this.error('Mesh with this ID not found: "'.concat(n,'" - ignoring this mesh'))}var o=new gA(this,e.isObject,e.id,t,e.flags,!0);return this._entityList.push(o),this._entities[e.id]=o,this._entitiesToFinalize.push(o),this.numEntities++,o}},{key:"preFinalize",value:function(){if(this.destroyed)return!1;if(0===this._layersToFinalize.length)return!1;this._createDummyEntityForUnusedMeshes();for(var e=0,t=this._layersToFinalize.length;e<t;e++){this._layersToFinalize[e].finalize()}this._vboBatchingLayers={},this._vboInstancingLayers={},this._dtxLayers={},this._layersToFinalize=[];for(var i=0,r=this._entitiesToFinalize.length;i<r;i++){this._entitiesToFinalize[i]._finalize()}for(var n=0,s=this._entitiesToFinalize.length;n<s;n++){this._entitiesToFinalize[n]._finalize2()}this._entitiesToFinalize=[],this.scene._aabbDirty=!0,this._viewMatrixDirty=!0,this._matrixDirty=!0,this._aabbDirty=!0,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.position=this._position,this.layerList.sort((function(e,t){return e.sortId<t.sortId?-1:e.sortId>t.sortId?1:0}));for(var o=0,a=this.layerList.length;o<a;o++){this.layerList[o].layerIndex=o}this.glRedraw(),this._layersFinalized=!0}},{key:"finalize",value:function(){this.destroyed||(this.preFinalize(),this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={})}},{key:"stateSortCompare",value:function(e,t){}},{key:"rebuildRenderFlags",value:function(){this.renderFlags.reset(),this._updateRenderFlagsVisibleLayers(),this.renderFlags.numLayers>0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}},{key:"_updateRenderFlagsVisibleLayers",value:function(){var e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(var t=0,i=this.layerList.length;t<i;t++){var r=this.layerList[t];this._getActiveSectionPlanesForLayer(r)&&(e.visibleLayers[e.numVisibleLayers++]=t)}}},{key:"_createDummyEntityForUnusedMeshes",value:function(){var e=Object.keys(this._unusedMeshes);if(e.length>0){var t="".concat(this.id,"-").concat(le.createUUID());this.warn('Creating dummy SceneModelEntity "'.concat(t,'" for unused SceneMeshes: [').concat(e.join(","),"]")),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}},{key:"_getActiveSectionPlanesForLayer",value:function(e){var t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,r=i.length,n=e.layerIndex*r;if(r>0)for(var s=0;s<r;s++){i[s].active?(t.sectionPlanesActivePerLayer[n+s]=!0,t.sectioned=!0):t.sectionPlanesActivePerLayer[n+s]=!1}return!0}},{key:"_updateRenderFlags",value:function(){if(0!==this.numVisibleLayerPortions&&this.numCulledLayerPortions!==this.numPortions){var e=this.renderFlags;if(e.colorOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){var t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0)this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.edgesTransparent=!0));if(this.numSelectedLayerPortions>0){var i=this.scene.selectedMaterial._state;i.fill&&(i.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),i.edges&&(i.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){var r=this.scene.highlightMaterial._state;r.fill&&(r.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),r.edges&&(r.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}},{key:"drawColorOpaque",value:function(e,t){for(var i=this.renderFlags,r=0,n=i.visibleLayers.length;r<n;r++){var s=i.visibleLayers[r];this.layerList[s].drawColorOpaque(i,e)}}},{key:"drawColorTransparent",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawColorTransparent(t,e)}}},{key:"drawDepth",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawDepth(t,e)}}},{key:"drawNormals",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawNormals(t,e)}}},{key:"drawSilhouetteXRayed",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawSilhouetteXRayed(t,e)}}},{key:"drawSilhouetteHighlighted",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawSilhouetteHighlighted(t,e)}}},{key:"drawSilhouetteSelected",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawSilhouetteSelected(t,e)}}},{key:"drawEdgesColorOpaque",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawEdgesColorOpaque(t,e)}}},{key:"drawEdgesColorTransparent",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawEdgesColorTransparent(t,e)}}},{key:"drawEdgesXRayed",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawEdgesXRayed(t,e)}}},{key:"drawEdgesHighlighted",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawEdgesHighlighted(t,e)}}},{key:"drawEdgesSelected",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawEdgesSelected(t,e)}}},{key:"drawOcclusion",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawOcclusion(t,e)}}},{key:"drawShadow",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawShadow(t,e)}}},{key:"setPickMatrices",value:function(e,t){if(0!==this._numVisibleLayerPortions)for(var i=this.renderFlags,r=0,n=i.visibleLayers.length;r<n;r++){var s=i.visibleLayers[r],o=this.layerList[s];o.setPickMatrices&&o.setPickMatrices(e,t)}}},{key:"drawPickMesh",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawPickMesh(t,e)}}},{key:"drawPickDepths",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawPickDepths(t,e)}}},{key:"drawPickNormals",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawPickNormals(t,e)}}},{key:"drawSnapInit",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i],s=this.layerList[n];s.drawSnapInit&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,s.drawSnapInit(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}},{key:"drawSnap",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i],s=this.layerList[n];s.drawSnap&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,s.drawSnap(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}},{key:"destroy",value:function(){for(var e in this._vboBatchingLayers)this._vboBatchingLayers.hasOwnProperty(e)&&this._vboBatchingLayers[e].destroy();for(var t in this._vboBatchingLayers={},this._vboInstancingLayers)this._vboInstancingLayers.hasOwnProperty(t)&&this._vboInstancingLayers[t].destroy();this._vboInstancingLayers={},this.scene.camera.off(this._onCameraViewMatrix),this.scene.off(this._onTick);for(var r=0,n=this.layerList.length;r<n;r++)this.layerList[r].destroy();this.layerList=[];for(var s=0,o=this._entityList.length;s<o;s++)this._entityList[s]._destroy();this._layersToFinalize={},this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._meshes={},this._entities={},this.scene._aabbDirty=!0,this._isModel&&this.scene._deregisterModel(this),0!==fs&&0==--fs&&ps._clear(),v(x(i.prototype),"destroy",this).call(this)}}]),i}();function RA(e,t,i){var r,n,s,o;if(t||i){var a=C(aA({positionsCompressed:e.positionsCompressed,indices:e.indices,edgeIndices:e.edgeIndices}),3);r=a[0],n=a[1],s=a[2]}else r=e.positionsCompressed,n=e.indices,s=e.edgeIndices;i?o=function(e,t){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=e.positionsCompressed||[],n=cA(e.indices||[],t),s=dA(e.edgeIndices||[]);function o(e,t){if(e>t){var i=e;e=t,t=i}function r(i,r){return i!==e?e-i:r!==t?t-r:0}for(var n=0,o=(s.length>>1)-1;n<=o;){var a=o+n>>1,l=r(s[2*a],s[2*a+1]);if(l>0)n=a+1;else{if(!(l<0))return a;o=a-1}}return-n-1}var a=new Int32Array(s.length/2);a.fill(0);var l=r.length/3;if(l>8*(1<<t))return[e];var u=new Int32Array(l);u.fill(-1);var c=[];function A(){u.fill(-1);var e={positionsCompressed:[],indices:[],edgeIndices:[],maxNumPositions:(1<<t)-t,numPositions:0,bucketNumber:c.length};return c.push(e),e}for(var h=A(),d=0,p=n.length;d<p;d+=3){var f=0,v=n[d],g=n[d+1],m=n[d+2];if(-1===u[v]&&f++,-1===u[g]&&f++,-1===u[m]&&f++,f+h.numPositions>h.maxNumPositions&&(h=A()),h.bucketNumber>8)return[e];-1===u[v]&&(u[v]=h.numPositions++,h.positionsCompressed.push(r[3*v]),h.positionsCompressed.push(r[3*v+1]),h.positionsCompressed.push(r[3*v+2])),-1===u[g]&&(u[g]=h.numPositions++,h.positionsCompressed.push(r[3*g]),h.positionsCompressed.push(r[3*g+1]),h.positionsCompressed.push(r[3*g+2])),-1===u[m]&&(u[m]=h.numPositions++,h.positionsCompressed.push(r[3*m]),h.positionsCompressed.push(r[3*m+1]),h.positionsCompressed.push(r[3*m+2])),h.indices.push(u[v]),h.indices.push(u[g]),h.indices.push(u[m]);var _=void 0;(_=o(v,g))>=0&&0===a[_]&&(a[_]=1,h.edgeIndices.push(u[s[2*_]]),h.edgeIndices.push(u[s[2*_+1]])),(_=o(v,m))>=0&&0===a[_]&&(a[_]=1,h.edgeIndices.push(u[s[2*_]]),h.edgeIndices.push(u[s[2*_+1]])),(_=o(g,m))>=0&&0===a[_]&&(a[_]=1,h.edgeIndices.push(u[s[2*_]]),h.edgeIndices.push(u[s[2*_+1]]))}var y=t/8*2,b=t/8,w=2*r.length+(n.length+s.length)*y,B=0;return r.length,c.forEach((function(e){B+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*b,e.positionsCompressed.length})),B>w?[e]:(i&&pA(c,e),c)}({positionsCompressed:r,indices:n,edgeIndices:s},r.length/3>65536?16:8):o=[{positionsCompressed:r,indices:n,edgeIndices:s}];return o}var UA=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(E(this,i),(r=t.call(this,e,n))._positions=n.positions||[],n.indices)r._indices=n.indices;else{r._indices=[];for(var s=0,o=r._positions.length/3-1;s<o;s+=2)r._indices.push(s),r._indices.push(s+1)}return r._color=n.color||[1,1,1],r._opacity=n.opacity||1,r._sceneModel=new SA(w(r),{isModel:!1}),r._sceneModel.createMesh({id:"linesMesh",primitive:"lines",positions:r._positions,indices:r._indices,color:r._color,opacity:r._opacity}),r._sceneModel.createEntity({meshIds:["linesMesh"],visible:n.visible,clippable:n.clippable,collidable:n.collidable}),r._sceneModel.finalize(),r.scene._lineSetCreated(w(r)),r}return I(i,[{key:"visible",get:function(){return this._sceneModel.visible},set:function(e){this._sceneModel.visible=e}},{key:"positions",get:function(){return this._positions}},{key:"indices",get:function(){return this._indices}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this.scene._lineSetDestroyed(this)}}]),i}(),LA=function(e){m(i,Ie);var t=y(i);function i(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),t.call(this,e,r)}return I(i,[{key:"type",get:function(){return"Light"}},{key:"isLight",get:function(){return!0}}]),i}(),OA=function(e){m(i,LA);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state={type:"ambient",color:le.vec3([.7,.7,.7]),intensity:1},r.color=n.color,r.intensity=n.intensity,r.scene._lightCreated(w(r)),r}return I(i,[{key:"type",get:function(){return"AmbientLight"}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this.scene._lightDestroyed(this)}}]),i}(),NA=function(){function e(t,i,r){E(this,e),r=r||{},this.gl=i,this.allocated=!1,this.canvas=t,this.buffer=null,this.bound=!1,this.size=r.size,this._hasDepthTexture=!!r.depthTexture}return I(e,[{key:"setSize",value:function(e){this.size=e}},{key:"webglContextRestored",value:function(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}},{key:"bind",value:function(){if(this._touch.apply(this,arguments),!this.bound){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}}},{key:"createTexture",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=this.gl,n=r.createTexture();return r.bindTexture(r.TEXTURE_2D,n),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),i?r.texStorage2D(r.TEXTURE_2D,1,i,e,t):r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null),n}},{key:"_touch",value:function(){var e,t,i=this,r=this.gl;if(this.size?(e=this.size[0],t=this.size[1]):(e=r.drawingBufferWidth,t=r.drawingBufferHeight),this.buffer){if(this.buffer.width===e&&this.buffer.height===t)return;this.buffer.textures.forEach((function(e){return r.deleteTexture(e)})),r.deleteFramebuffer(this.buffer.framebuf),r.deleteRenderbuffer(this.buffer.renderbuf)}for(var n,s=[],o=arguments.length,a=new Array(o),l=0;l<o;l++)a[l]=arguments[l];a.length>0?s.push.apply(s,f(a.map((function(r){return i.createTexture(e,t,r)})))):s.push(this.createTexture(e,t)),this._hasDepthTexture&&(n=r.createTexture(),r.bindTexture(r.TEXTURE_2D,n),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texImage2D(r.TEXTURE_2D,0,r.DEPTH_COMPONENT32F,e,t,0,r.DEPTH_COMPONENT,r.FLOAT,null));var u=r.createRenderbuffer();r.bindRenderbuffer(r.RENDERBUFFER,u),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_COMPONENT32F,e,t);var c=r.createFramebuffer();r.bindFramebuffer(r.FRAMEBUFFER,c);for(var A=0;A<s.length;A++)r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+A,r.TEXTURE_2D,s[A],0);if(a.length>0&&r.drawBuffers(s.map((function(e,t){return r.COLOR_ATTACHMENT0+t}))),this._hasDepthTexture?r.framebufferTexture2D(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.TEXTURE_2D,n,0):r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,u),r.bindTexture(r.TEXTURE_2D,null),r.bindRenderbuffer(r.RENDERBUFFER,null),r.bindFramebuffer(r.FRAMEBUFFER,null),r.bindFramebuffer(r.FRAMEBUFFER,c),!r.isFramebuffer(c))throw"Invalid framebuffer";r.bindFramebuffer(r.FRAMEBUFFER,null);var h=r.checkFramebufferStatus(r.FRAMEBUFFER);switch(h){case r.FRAMEBUFFER_COMPLETE:break;case r.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case r.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+h}this.buffer={framebuf:c,renderbuf:u,texture:s[0],textures:s,depthTexture:n,width:e,height:t},this.bound=!1}},{key:"clear",value:function(){if(!this.bound)throw"Render buffer not bound";var e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}},{key:"read",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:Uint8Array,s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:4,o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,u=new n(s),c=this.gl;return c.readBuffer(c.COLOR_ATTACHMENT0+o),c.readPixels(a,l,1,1,i||c.RGBA,r||c.UNSIGNED_BYTE,u,0),u}},{key:"readArray",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Uint8Array,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:4,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,s=new i(this.buffer.width*this.buffer.height*r),o=this.gl;return o.readBuffer(o.COLOR_ATTACHMENT0+n),o.readPixels(0,0,this.buffer.width,this.buffer.height,e||o.RGBA,t||o.UNSIGNED_BYTE,s,0),s}},{key:"readImageAsCanvas",value:function(){var e=this.gl,t=this._getImageDataCache(),i=t.pixelData,r=t.canvas,n=t.imageData,s=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);for(var o=this.buffer.width,a=this.buffer.height,l=a/2|0,u=4*o,c=new Uint8Array(4*o),A=0;A<l;++A){var h=A*u,d=(a-A-1)*u;c.set(i.subarray(h,h+u)),i.copyWithin(h,d,d+u),i.set(c,d)}return n.data.set(i),s.putImageData(n,0,0),r}},{key:"readImage",value:function(e){var t=this.gl,i=this._getImageDataCache(),r=i.pixelData,n=i.canvas,s=i.imageData,o=i.context,a=this.buffer,l=a.width,u=a.height;t.readPixels(0,0,l,u,t.RGBA,t.UNSIGNED_BYTE,r),s.data.set(r),o.putImageData(s,0,0),o.save(),o.globalCompositeOperation="copy",o.scale(1,-1),o.drawImage(n,0,-u,l,u),o.restore();var c=e.format||"png";return"jpeg"!==c&&"png"!==c&&"bmp"!==c&&(console.error("Unsupported image format: '"+c+"' - supported types are 'jpeg', 'bmp' and 'png' - defaulting to 'png'"),c="png"),n.toDataURL("image/".concat(c))}},{key:"_getImageDataCache",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Uint8Array,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,i=this.buffer.width,r=this.buffer.height,n=this._imageDataCache;if(n&&(n.width===i&&n.height===r||(this._imageDataCache=null,n=null)),!n){var s=document.createElement("canvas"),o=s.getContext("2d");s.width=i,s.height=r,n={pixelData:new e(i*r*t),canvas:s,context:o,imageData:o.createImageData(i,r),width:i,height:r},this._imageDataCache=n}return n.context.resetTransform(),n}},{key:"unbind",value:function(){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),this.bound=!1}},{key:"getTexture",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=this;return this._texture||(this._texture={renderBuffer:this,bind:function(i){return!(!t.buffer||!t.buffer.textures[e])&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),t.gl.bindTexture(t.gl.TEXTURE_2D,t.buffer.textures[e]),!0)},unbind:function(i){t.buffer&&t.buffer.textures[e]&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),t.gl.bindTexture(t.gl.TEXTURE_2D,null))}})}},{key:"hasDepthTexture",value:function(){return this._hasDepthTexture}},{key:"getDepthTexture",value:function(){if(!this._hasDepthTexture)return null;var e=this;return this._depthTexture||(this._dethTexture={renderBuffer:this,bind:function(t){return!(!e.buffer||!e.buffer.depthTexture)&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,e.buffer.depthTexture),!0)},unbind:function(t){e.buffer&&e.buffer.depthTexture&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,null))}})}},{key:"destroy",value:function(){if(this.allocated){var e=this.gl;this.buffer.textures.forEach((function(t){return e.deleteTexture(t)})),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}]),e}(),VA=function(e){m(i,LA);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E(this,i),(r=t.call(this,e,n))._shadowRenderBuf=null,r._shadowViewMatrix=null,r._shadowProjMatrix=null,r._shadowViewMatrixDirty=!0,r._shadowProjMatrixDirty=!0;var s=r.scene.camera,o=r.scene.canvas;return r._onCameraViewMatrix=s.on("viewMatrix",(function(){r._shadowViewMatrixDirty=!0})),r._onCameraProjMatrix=s.on("projMatrix",(function(){r._shadowProjMatrixDirty=!0})),r._onCanvasBoundary=o.on("boundary",(function(){r._shadowProjMatrixDirty=!0})),r._state=new nt({type:"dir",dir:le.vec3([1,1,1]),color:le.vec3([.7,.7,.8]),intensity:1,space:n.space||"view",castsShadow:!1,getShadowViewMatrix:function(){if(r._shadowViewMatrixDirty){r._shadowViewMatrix||(r._shadowViewMatrix=le.identityMat4());var e=r.scene.camera,t=r._state.dir,i=e.look,n=[i[0]-t[0],i[1]-t[1],i[2]-t[2]];le.lookAtMat4v(n,i,[0,1,0],r._shadowViewMatrix),r._shadowViewMatrixDirty=!1}return r._shadowViewMatrix},getShadowProjMatrix:function(){return r._shadowProjMatrixDirty&&(r._shadowProjMatrix||(r._shadowProjMatrix=le.identityMat4()),le.orthoMat4c(-40,40,-40,40,-40,80,r._shadowProjMatrix),r._shadowProjMatrixDirty=!1),r._shadowProjMatrix},getShadowRenderBuf:function(){return r._shadowRenderBuf||(r._shadowRenderBuf=new NA(r.scene.canvas.canvas,r.scene.canvas.gl,{size:[1024,1024]})),r._shadowRenderBuf}}),r.dir=n.dir,r.color=n.color,r.intensity=n.intensity,r.castsShadow=n.castsShadow,r.scene._lightCreated(w(r)),r}return I(i,[{key:"type",get:function(){return"DirLight"}},{key:"dir",get:function(){return this._state.dir},set:function(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}},{key:"castsShadow",get:function(){return this._state.castsShadow},set:function(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}},{key:"destroy",value:function(){var e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),v(x(i.prototype),"destroy",this).call(this),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}]),i}(),QA=function(e){m(i,LA);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E(this,i);var s=w(r=t.call(this,e,n));r._shadowRenderBuf=null,r._shadowViewMatrix=null,r._shadowProjMatrix=null,r._shadowViewMatrixDirty=!0,r._shadowProjMatrixDirty=!0;var o=r.scene.camera,a=r.scene.canvas;return r._onCameraViewMatrix=o.on("viewMatrix",(function(){r._shadowViewMatrixDirty=!0})),r._onCameraProjMatrix=o.on("projMatrix",(function(){r._shadowProjMatrixDirty=!0})),r._onCanvasBoundary=a.on("boundary",(function(){r._shadowProjMatrixDirty=!0})),r._state=new nt({type:"point",pos:le.vec3([1,1,1]),color:le.vec3([.7,.7,.8]),intensity:1,attenuation:[0,0,0],space:n.space||"view",castsShadow:!1,getShadowViewMatrix:function(){if(s._shadowViewMatrixDirty){s._shadowViewMatrix||(s._shadowViewMatrix=le.identityMat4());var e=s._state.pos,t=o.look,i=o.up;le.lookAtMat4v(e,t,i,s._shadowViewMatrix),s._shadowViewMatrixDirty=!1}return s._shadowViewMatrix},getShadowProjMatrix:function(){if(s._shadowProjMatrixDirty){s._shadowProjMatrix||(s._shadowProjMatrix=le.identityMat4());var e=s.scene.canvas.canvas;le.perspectiveMat4(Math.PI/180*70,e.clientWidth/e.clientHeight,.1,500,s._shadowProjMatrix),s._shadowProjMatrixDirty=!1}return s._shadowProjMatrix},getShadowRenderBuf:function(){return s._shadowRenderBuf||(s._shadowRenderBuf=new NA(s.scene.canvas.canvas,s.scene.canvas.gl,{size:[1024,1024]})),s._shadowRenderBuf}}),r.pos=n.pos,r.color=n.color,r.intensity=n.intensity,r.constantAttenuation=n.constantAttenuation,r.linearAttenuation=n.linearAttenuation,r.quadraticAttenuation=n.quadraticAttenuation,r.castsShadow=n.castsShadow,r.scene._lightCreated(w(r)),r}return I(i,[{key:"type",get:function(){return"PointLight"}},{key:"pos",get:function(){return this._state.pos},set:function(e){this._state.pos.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}},{key:"constantAttenuation",get:function(){return this._state.attenuation[0]},set:function(e){this._state.attenuation[0]=e||0,this.glRedraw()}},{key:"linearAttenuation",get:function(){return this._state.attenuation[1]},set:function(e){this._state.attenuation[1]=e||0,this.glRedraw()}},{key:"quadraticAttenuation",get:function(){return this._state.attenuation[2]},set:function(e){this._state.attenuation[2]=e||0,this.glRedraw()}},{key:"castsShadow",get:function(){return this._state.castsShadow},set:function(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}},{key:"destroy",value:function(){var e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),v(x(i.prototype),"destroy",this).call(this),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}]),i}();function HA(e){return 0==(e&e-1)}function jA(e){--e;for(var t=1;t<32;t<<=1)e|=e>>t;return e+1}var GA=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E(this,i);var s=(r=t.call(this,e,n)).scene.canvas.gl;return r._state=new nt({texture:new Pn({gl:s,target:s.TEXTURE_CUBE_MAP}),flipY:r._checkFlipY(n.minFilter),encoding:r._checkEncoding(n.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),r._src=n.src,r._images=[],r._loadSrc(n.src),he.memory.textures++,r}return I(i,[{key:"type",get:function(){return"CubeTexture"}},{key:"_checkFlipY",value:function(e){return!!e}},{key:"_checkEncoding",value:function(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}},{key:"_webglContextRestored",value:function(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}},{key:"_loadSrc",value:function(e){var t=this,i=this.scene.canvas.gl;this._images=[];for(var r=!1,n=0,s=function(s){var o,a,l=new Image;l.onload=(o=l,a=s,function(){if(!r&&(o=function(e){if(!HA(e.width)||!HA(e.height)){var t=document.createElement("canvas");t.width=jA(e.width),t.height=jA(e.height),t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}(o),t._images[a]=o,6==++n)){var e=t._state.texture;e||(e=new Pn({gl:i,target:i.TEXTURE_CUBE_MAP}),t._state.texture=e),e.setImage(t._images,t._state),t.fire("loaded",t._src,!1),t.glRedraw()}}),l.onerror=function(){r=!0},l.src=e[s]},o=0;o<e.length;o++)s(o)}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.texture&&this._state.texture.destroy(),he.memory.textures--,this._state.destroy()}}]),i}(),zA=function(e){m(i,GA);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).scene._lightsState.addReflectionMap(r._state),r.scene._reflectionMapCreated(w(r)),r}return I(i,[{key:"type",get:function(){return"ReflectionMap"}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this.scene._reflectionMapDestroyed(this)}}]),i}(),WA=function(e){m(i,GA);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).scene._lightMapCreated(w(r)),r}return I(i,[{key:"type",get:function(){return"LightMap"}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this.scene._lightMapDestroyed(this)}}]),i}(),XA=le.vec4(),KA=le.vec4(),ZA=function(e){m(i,Ie);var t=y(i);function i(e,r){var n;return E(this,i),(n=t.call(this,e,r))._entity=null,n._visible=null,n._worldPos=le.vec3(),n._origin=le.vec3(),n._rtcPos=le.vec3(),n._viewPos=le.vec3(),n._canvasPos=le.vec2(),n._occludable=!1,n._onCameraViewMatrix=n.scene.camera.on("matrix",(function(){n._viewPosDirty=!0,n._needUpdate()})),n._onCameraProjMatrix=n.scene.camera.on("projMatrix",(function(){n._canvasPosDirty=!0,n._needUpdate()})),n._onEntityDestroyed=null,n._onEntityModelDestroyed=null,n._renderer.addMarker(w(n)),n.entity=r.entity,n.worldPos=r.worldPos,n.occludable=r.occludable,n}return I(i,[{key:"_update",value:function(){if(this._viewPosDirty&&(le.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){XA.set(this._viewPos),XA[3]=1,le.transformPoint4(this.scene.camera.projMatrix,XA,KA);var e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+KA[0]/KA[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-KA[1]/KA[3])*e[3]/2),this._canvasPosDirty=!1,this.fire("canvasPos",this._canvasPos)}}},{key:"_setVisible",value:function(e){this._visible,this._visible=e,this.fire("visible",this._visible)}},{key:"entity",get:function(){return this._entity},set:function(e){var t=this;this._entity!==e&&(this._cleanupDestroyedHandlers(),this._entity=e,this._entity&&(this._entity.isSceneModelEntity?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(function(){t._entity=null,t._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.on("destroyed",(function(){t._entity=null,t._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0))}},{key:"occludable",get:function(){return this._occludable},set:function(e){(e=!!e)!==this._occludable&&(this._occludable=e,this._occludable&&this._renderer.markerWorldPosUpdated(this))}},{key:"worldPos",get:function(){return this._worldPos},set:function(e){this._worldPos.set(e||[0,0,0]),Yt(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}},{key:"origin",get:function(){return this._origin}},{key:"rtcPos",get:function(){return this._rtcPos}},{key:"viewPos",get:function(){return this._update(),this._viewPos}},{key:"canvasPos",get:function(){return this._update(),this._canvasPos}},{key:"visible",get:function(){return!!this._visible}},{key:"destroy",value:function(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._cleanupDestroyedHandlers(),this._renderer.removeMarker(this),v(x(i.prototype),"destroy",this).call(this)}},{key:"_cleanupDestroyedHandlers",value:function(){this._entity&&(null!==this._onEntityDestroyed&&(this._entity.model?this._entity.model.off(this._onEntityDestroyed):this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model&&this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null))}}]),i}(),JA=function(e){m(i,ZA);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,{entity:n.entity,occludable:n.occludable,worldPos:n.worldPos}))._occluded=!1,r._visible=!0,r._src=null,r._image=null,r._pos=le.vec3(),r._origin=le.vec3(),r._rtcPos=le.vec3(),r._dir=le.vec3(),r._size=1,r._imageSize=le.vec2(),r._texture=new In(w(r),{src:n.src}),r._geometry=new mt(w(r),{primitive:"triangles",positions:[3,3,0,-3,3,0,-3,-3,0,3,-3,0],normals:[-1,0,0,-1,0,0,-1,0,0,-1,0,0],uv:[1,-1,0,-1,0,0,1,0],indices:[0,1,2,0,2,3]}),r._mesh=new vn(w(r),{geometry:r._geometry,material:new bn(w(r),{ambient:[.9,.3,.9],shininess:30,diffuseMap:r._texture,backfaces:!0}),scale:[1,1,1],position:n.worldPos,rotation:[90,0,0],billboard:"spherical",occluder:!1}),r.visible=!0,r.collidable=n.collidable,r.clippable=n.clippable,r.pickable=n.pickable,r.opacity=n.opacity,r.size=n.size,n.image?r.image=n.image:r.src=n.src,r}return I(i,[{key:"_setVisible",value:function(e){this._occluded=!e,this._mesh.visible=this._visible&&!this._occluded,v(x(i.prototype),"_setVisible",this).call(this,e)}},{key:"visible",get:function(){return this._visible},set:function(e){this._visible=null==e||e,this._mesh.visible=this._visible&&!this._occluded}},{key:"image",get:function(){return this._image},set:function(e){this._image=e,this._image&&(this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}},{key:"src",get:function(){return this._src},set:function(e){var t=this;if(this._src=e,this._src){this._image=null;var i=new Image;i.onload=function(){t._texture.image=i,t._imageSize[0]=i.width,t._imageSize[1]=i.height,t._updatePlaneSizeFromImage()},i.src=this._src}}},{key:"size",get:function(){return this._size},set:function(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}},{key:"collidable",get:function(){return this._mesh.collidable},set:function(e){this._mesh.collidable=!1!==e}},{key:"clippable",get:function(){return this._mesh.clippable},set:function(e){this._mesh.clippable=!1!==e}},{key:"pickable",get:function(){return this._mesh.pickable},set:function(e){this._mesh.pickable=!1!==e}},{key:"opacity",get:function(){return this._mesh.opacity},set:function(e){this._mesh.opacity=e}},{key:"_updatePlaneSizeFromImage",value:function(){var e=.5*this._size,t=this._imageSize[0],i=this._imageSize[1],r=i/t;this._geometry.positions=t>i?[e,e*r,0,-e,e*r,0,-e,-e*r,0,e,-e*r,0]:[e/r,e,0,-e/r,e,0,-e/r,-e,0,e/r,-e,0]}}]),i}(),YA=function(){function e(t){E(this,e),this._eye=le.vec3(),this._look=le.vec3(),this._up=le.vec3(),this._projection={},t&&this.saveCamera(t)}return I(e,[{key:"saveCamera",value:function(e){var t=e.camera,i=t.project;switch(this._eye.set(t.eye),this._look.set(t.look),this._up.set(t.up),t.projection){case"perspective":this._projection={projection:"perspective",fov:i.fov,fovAxis:i.fovAxis,near:i.near,far:i.far};break;case"ortho":this._projection={projection:"ortho",scale:i.scale,near:i.near,far:i.far};break;case"frustum":this._projection={projection:"frustum",left:i.left,right:i.right,top:i.top,bottom:i.bottom,near:i.near,far:i.far};break;case"custom":this._projection={projection:"custom",matrix:i.matrix.slice()}}}},{key:"restoreCamera",value:function(e,t){var i=e.camera,r=this._projection;function n(){switch(r.type){case"perspective":i.perspective.fov=r.fov,i.perspective.fovAxis=r.fovAxis,i.perspective.near=r.near,i.perspective.far=r.far;break;case"ortho":i.ortho.scale=r.scale,i.ortho.near=r.near,i.ortho.far=r.far;break;case"frustum":i.frustum.left=r.left,i.frustum.right=r.right,i.frustum.top=r.top,i.frustum.bottom=r.bottom,i.frustum.near=r.near,i.frustum.far=r.far;break;case"custom":i.customProjection.matrix=r.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:r.scale,projection:r.projection},(function(){n(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,n(),i.projection=r.projection)}}]),e}(),qA=le.vec3(),$A=function(){function e(t){if(E(this,e),this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,t){var i=t.metaScene.scene;this.saveObjects(i,t)}}return I(e,[{key:"saveObjects",value:function(e,t,i){this.numObjects=0,this._mask=i?ge.apply(i,{}):null;for(var r=!i||i.visible,n=!i||i.edges,s=!i||i.xrayed,o=!i||i.highlighted,a=!i||i.selected,l=!i||i.clippable,u=!i||i.pickable,c=!i||i.colorize,A=!i||i.opacity,h=t.metaObjects,d=e.objects,p=0,f=h.length;p<f;p++){var v=d[h[p].id];if(v){if(r&&(this.objectsVisible[p]=v.visible),n&&(this.objectsEdges[p]=v.edges),s&&(this.objectsXrayed[p]=v.xrayed),o&&(this.objectsHighlighted[p]=v.highlighted),a&&(this.objectsSelected[p]=v.selected),l&&(this.objectsClippable[p]=v.clippable),u&&(this.objectsPickable[p]=v.pickable),c){var g=v.colorize;this.objectsColorize[3*p+0]=g[0],this.objectsColorize[3*p+1]=g[1],this.objectsColorize[3*p+2]=g[2]}A&&(this.objectsOpacity[p]=v.opacity),this.numObjects++}}}},{key:"restoreObjects",value:function(e,t){for(var i=this._mask,r=!i||i.visible,n=!i||i.edges,s=!i||i.xrayed,o=!i||i.highlighted,a=!i||i.selected,l=!i||i.clippable,u=!i||i.pickable,c=!i||i.colorize,A=!i||i.opacity,h=t.metaObjects,d=e.objects,p=0,f=h.length;p<f;p++){var v=d[h[p].id];v&&(r&&(v.visible=this.objectsVisible[p]),n&&(v.edges=this.objectsEdges[p]),s&&(v.xrayed=this.objectsXrayed[p]),o&&(v.highlighted=this.objectsHighlighted[p]),a&&(v.selected=this.objectsSelected[p]),l&&(v.clippable=this.objectsClippable[p]),u&&(v.pickable=this.objectsPickable[p]),c&&(qA[0]=this.objectsColorize[3*p+0],qA[1]=this.objectsColorize[3*p+1],qA[2]=this.objectsColorize[3*p+2],v.colorize=qA),A&&(v.opacity=this.objectsOpacity[p]))}}}]),e}(),eh=le.vec3(),th=function(){function e(){E(this,e),this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsHasColorize=[],this.objectsOpacity=[],this.numObjects=0}return I(e,[{key:"saveObjects",value:function(e,t){this.numObjects=0,this._mask=t?ge.apply(t,{}):null;var i=e.objects,r=!t||t.visible,n=!t||t.edges,s=!t||t.xrayed,o=!t||t.highlighted,a=!t||t.selected,l=!t||t.clippable,u=!t||t.pickable,c=!t||t.colorize,A=!t||t.opacity;for(var h in i)if(i.hasOwnProperty(h)){var d=i[h],p=this.numObjects;if(r&&(this.objectsVisible[p]=d.visible),n&&(this.objectsEdges[p]=d.edges),s&&(this.objectsXrayed[p]=d.xrayed),o&&(this.objectsHighlighted[p]=d.highlighted),a&&(this.objectsSelected[p]=d.selected),l&&(this.objectsClippable[p]=d.clippable),u&&(this.objectsPickable[p]=d.pickable),c){var f=d.colorize;f?(this.objectsColorize[3*p+0]=f[0],this.objectsColorize[3*p+1]=f[1],this.objectsColorize[3*p+2]=f[2],this.objectsHasColorize[p]=!0):this.objectsHasColorize[p]=!1}A&&(this.objectsOpacity[p]=d.opacity),this.numObjects++}}},{key:"restoreObjects",value:function(e){var t=this._mask,i=!t||t.visible,r=!t||t.edges,n=!t||t.xrayed,s=!t||t.highlighted,o=!t||t.selected,a=!t||t.clippable,l=!t||t.pickable,u=!t||t.colorize,c=!t||t.opacity,A=0,h=e.objects;for(var d in h)if(h.hasOwnProperty(d)){var p=h[d];i&&(p.visible=this.objectsVisible[A]),r&&(p.edges=this.objectsEdges[A]),n&&(p.xrayed=this.objectsXrayed[A]),s&&(p.highlighted=this.objectsHighlighted[A]),o&&(p.selected=this.objectsSelected[A]),a&&(p.clippable=this.objectsClippable[A]),l&&(p.pickable=this.objectsPickable[A]),u&&(this.objectsHasColorize[A]?(eh[0]=this.objectsColorize[3*A+0],eh[1]=this.objectsColorize[3*A+1],eh[2]=this.objectsColorize[3*A+2],p.colorize=eh):p.colorize=null),c&&(p.opacity=this.objectsOpacity[A]),A++}}}]),e}(),ih=function(e){m(i,ze);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).v0=n.v0,r.v1=n.v1,r.v2=n.v2,r.v3=n.v3,r.t=n.t,r}return I(i,[{key:"v0",get:function(){return this._v0},set:function(e){this._v0=e||le.vec3([0,0,0])}},{key:"v1",get:function(){return this._v1},set:function(e){this._v1=e||le.vec3([0,0,0])}},{key:"v2",get:function(){return this._v2},set:function(e){this._v2=e||le.vec3([0,0,0])}},{key:"v3",get:function(){return this._v3},set:function(e){this.fire("v3",this._v3=e||le.vec3([0,0,0]))}},{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"getPoint",value:function(e){var t=le.vec3();return t[0]=le.b3(e,this._v0[0],this._v1[0],this._v2[0],this._v3[0]),t[1]=le.b3(e,this._v0[1],this._v1[1],this._v2[1],this._v3[1]),t[2]=le.b3(e,this._v0[2],this._v1[2],this._v2[2],this._v3[2]),t}},{key:"getJSON",value:function(){return{v0:this._v0,v1:this._v1,v2:this._v2,v3:this._v3,t:this._t}}}]),i}(),rh=function(e){m(i,ze);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._cachedLengths=[],r._dirty=!0,r._curves=[],r._t=0,r._dirtySubs=[],r._destroyedSubs=[],r.curves=n.curves||[],r.t=n.t,r}return I(i,[{key:"addCurve",value:function(e){this._curves.push(e),this._dirty=!0}},{key:"curves",get:function(){return this._curves},set:function(e){var t,i,r;for(e=e||[],i=0,r=this._curves.length;i<r;i++)(t=this._curves[i]).off(this._dirtySubs[i]),t.off(this._destroyedSubs[i]);this._curves=[],this._dirtySubs=[],this._destroyedSubs=[];var n=this;function s(){n._dirty=!0}function o(){var e=this.id;for(i=0,r=n._curves.length;i<r;i++)if(n._curves[i].id===e)return n._curves=n._curves.slice(i,i+1),n._dirtySubs=n._dirtySubs.slice(i,i+1),n._destroyedSubs=n._destroyedSubs.slice(i,i+1),void(n._dirty=!0)}for(i=0,r=e.length;i<r;i++){if(t=e[i],ge.isNumeric(t)||ge.isString(t)){var a=t;if(!(t=this.scene.components[a])){this.error("Component not found: "+_inQuotes(a));continue}}var l=t.type;"xeokit.SplineCurve"===l||"xeokit.Path"===l||"xeokit.CubicBezierCurve"===l||"xeokit.QuadraticBezierCurve"===l?(this._curves.push(t),this._dirtySubs.push(t.on("dirty",s)),this._destroyedSubs.push(t.once("destroyed",o))):this.error("Component "+_inQuotes(t.id)+" is not a xeokit.SplineCurve, xeokit.Path or xeokit.QuadraticBezierCurve")}this._dirty=!0}},{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"length",get:function(){var e=this._getCurveLengths();return e[e.length-1]}},{key:"getPoint",value:function(e){for(var t,i=e*this.length,r=this._getCurveLengths(),n=0;n<r.length;){if(r[n]>=i){var s=1-(r[n]-i)/(t=this._curves[n]).length;return t.getPointAt(s)}n++}return null}},{key:"_getCurveLengths",value:function(){if(!this._dirty)return this._cachedLengths;var e,t=[],i=0,r=this._curves.length;for(e=0;e<r;e++)i+=this._curves[e].length,t.push(i);return this._cachedLengths=t,this._dirty=!1,t}},{key:"_getJSON",value:function(){for(var e=[],t=0,i=this._curves.length;t<i;t++)e.push(this._curves[t].id);return{curves:e,t:this._t}}},{key:"destroy",value:function(){var e,t,r;for(v(x(i.prototype),"destroy",this).call(this),e=0,t=this._curves.length;e<t;e++)(r=this._curves[e]).off(this._dirtySubs[e]),r.off(this._destroyedSubs[e])}}]),i}(),nh=function(e){m(i,ze);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).v0=n.v0,r.v1=n.v1,r.v2=n.v2,r.t=n.t,r}return I(i,[{key:"v0",get:function(){return this._v0},set:function(e){this._v0=e||le.vec3([0,0,0])}},{key:"v1",get:function(){return this._v1},set:function(e){this._v1=e||le.vec3([0,0,0])}},{key:"v2",get:function(){return this._v2},set:function(e){this._v2=e||le.vec3([0,0,0])}},{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"getPoint",value:function(e){var t=le.vec3();return t[0]=le.b2(e,this._v0[0],this._v1[0],this._v2[0]),t[1]=le.b2(e,this._v0[1],this._v1[1],this._v2[1]),t[2]=le.b2(e,this._v0[2],this._v1[2],this._v2[2]),t}},{key:"getJSON",value:function(){return{v0:this._v0,v1:this._v1,v2:this._v2,t:this._t}}}]),i}(),sh=function(e){m(i,SA);var t=y(i);function i(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),t.call(this,e,r)}return I(i)}(),oh=le.vec3(),ah=le.vec3(),lh=le.vec4(),uh=le.vec3([0,0,-1]),ch=le.vec3([0,0,1]),Ah=le.vec3([0,1,0]),hh=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state=new nt({active:!0,pos:le.vec3(),quaternion:le.vec4(),roll:0,dir:le.vec3(),dist:0}),r.active=n.active,r.pos=n.pos,r.dir=n.dir,r.scene._sectionPlaneCreated(w(r)),r}return I(i,[{key:"type",get:function(){return"SectionPlane"}},{key:"active",get:function(){return this._state.active},set:function(e){this._state.active=!1!==e,this.glRedraw(),this.fire("active",this._state.active),this.scene.fire("sectionPlaneUpdated",this)}},{key:"pos",get:function(){return this._state.pos},set:function(e){this._state.pos.set(e||[0,0,0]),this._state.dist=-le.dotVec3(this._state.pos,this._state.dir),this.fire("pos",this._state.pos),this.scene.fire("sectionPlaneUpdated",this)}},{key:"quaternion",get:function(){return this._state.quaternion},set:function(e){this._state.quaternion.set(e||[0,0,0,-1]),le.vec3ApplyQuaternion(this._state.quaternion,ch,this._state.dir);var t=le.vec3ApplyQuaternion(this._state.quaternion,Ah,oh),i=le.vec3PairToQuaternion(ch,this._state.dir,lh),r=le.vec3ApplyQuaternion(i,Ah,ah),n=Math.acos(Math.min(1,le.dotVec3(t,r))),s=Math.sign(le.dotVec3(this._state.dir,le.cross3Vec3(t,r,ah)));this._state.roll=s*n,this._onDirUpdated()}},{key:"roll",get:function(){return this._state.roll},set:function(e){this._state.roll=e||0,this._onDirRollUpdated()}},{key:"dir",get:function(){return this._state.dir},set:function(e){this._state.dir.set(e||uh),this._onDirRollUpdated()}},{key:"_onDirRollUpdated",value:function(){le.vec3PairToQuaternion(ch,this._state.dir,this._state.quaternion),lh[0]=0,lh[1]=0,lh[2]=-1,lh[3]=this._state.roll,le.angleAxisToQuaternion(lh,lh),le.mulQuaternions(this._state.quaternion,lh,this._state.quaternion),this._onDirUpdated()}},{key:"_onDirUpdated",value:function(){this._state.dist=-le.dotVec3(this._state.pos,this._state.dir),this.glRedraw(),this.fire("dir",this._state.dir),this.scene.fire("sectionPlaneUpdated",this)}},{key:"dist",get:function(){return this._state.dist}},{key:"flipDir",value:function(){le.mulVec3Scalar(this._state.dir,-1,this._state.dir),this.dir=this._state.dir}},{key:"destroy",value:function(){this._state.destroy(),this.scene._sectionPlaneDestroyed(this),v(x(i.prototype),"destroy",this).call(this)}}]),i}(),dh=function(){function e(){E(this,e)}return I(e,[{key:"transcode",value:function(e,t){}},{key:"destroy",value:function(){}}]),e}(),ph=function(){function e(){E(this,e),this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}return I(e,[{key:"canvasPos",get:function(){return this._gotCanvasPos?this._canvasPos:null},set:function(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}},{key:"origin",get:function(){return this._gotOrigin?this._origin:null},set:function(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}},{key:"direction",get:function(){return this._gotDirection?this._direction:null},set:function(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}},{key:"indices",get:function(){return this.entity&&this._gotIndices?this._indices:null},set:function(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}},{key:"localPos",get:function(){return this.entity&&this._gotLocalPos?this._localPos:null},set:function(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}},{key:"snappedCanvasPos",get:function(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null},set:function(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}},{key:"worldPos",get:function(){return this._gotWorldPos?this._worldPos:null},set:function(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}},{key:"viewPos",get:function(){return this.entity&&this._gotViewPos?this._viewPos:null},set:function(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}},{key:"bary",get:function(){return this.entity&&this._gotBary?this._bary:null},set:function(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}},{key:"worldNormal",get:function(){return this.entity&&this._gotWorldNormal?this._worldNormal:null},set:function(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}},{key:"uv",get:function(){return this.entity&&this._gotUV?this._uv:null},set:function(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}},{key:"snapped",get:function(){return this.snappedToEdge||this.snappedToVertex}},{key:"reset",value:function(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}]),e}(),fh={isIphoneSafari:function(){var e=window.navigator.userAgent,t=/iPhone/i.test(e),i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i},isIphoneOrIpadSafari:function(){var e=window.navigator.userAgent,t=/iPhone|iPad/i.test(e)||/Macintosh/i.test(e)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2,i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i},isTouchDevice:function(){return"ontouchstart"in window||navigator.maxTouchPoints>0||navigator.mxMaxTouchPoints>0}},vh=function(){function e(t,i,r){E(this,e),this.id=r&&r.id?r.id:t,this.viewer=i,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,i.addPlugin(this)}return I(e,[{key:"scheduleTask",value:function(e){ke.scheduleTask(e,null)}},{key:"fire",value:function(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);var r,n=this._eventSubs[e];if(n)for(var s in n)n.hasOwnProperty(s)&&(r=n[s],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}},{key:"on",value:function(e,t,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new Z),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});var r=this._eventSubs[e];r?this._eventSubsNum[e]++:(r={},this._eventSubs[e]=r,this._eventSubsNum[e]=1);var n=this._subIdMap.addItem();r[n]={callback:t,scope:i||this},this._subIdEvents[n]=e;var s=this._events[e];return void 0!==s&&t.call(i||this,s),n}},{key:"off",value:function(e){if(null!=e&&this._subIdEvents){var t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];var i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}}},{key:"once",value:function(e,t,i){var r=this,n=this.on(e,(function(e){r.off(n),t.call(i||this,e)}),i)}},{key:"hasSubs",value:function(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}},{key:"log",value:function(e){console.log("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"warn",value:function(e){console.warn("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"error",value:function(e){console.error("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"send",value:function(e,t){}},{key:"destroy",value:function(){this.viewer.removePlugin(this)}}]),e}(),gh=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._canvas=n.canvas,r._element=null,r._isCustom=!1,n.elementId&&(r._element=document.getElementById(n.elementId),r._element?r._adjustPosition():r.error("Can't find given Spinner HTML element: '"+n.elementId+"' - will automatically create default element")),r._element||r._createDefaultSpinner(),r.processes=0,r}return I(i,[{key:"type",get:function(){return"Spinner"}},{key:"_createDefaultSpinner",value:function(){this._injectDefaultCSS();var e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='<div class="sk-fading-circle"> <div class="sk-circle1 sk-circle"></div> <div class="sk-circle2 sk-circle"></div> <div class="sk-circle3 sk-circle"></div> <div class="sk-circle4 sk-circle"></div> <div class="sk-circle5 sk-circle"></div> <div class="sk-circle6 sk-circle"></div> <div class="sk-circle7 sk-circle"></div> <div class="sk-circle8 sk-circle"></div> <div class="sk-circle9 sk-circle"></div> <div class="sk-circle10 sk-circle"></div> <div class="sk-circle11 sk-circle"></div> <div class="sk-circle12 sk-circle"></div> </div>',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}},{key:"_injectDefaultCSS",value:function(){var e="xeokit-spinner-css";if(!document.getElementById(e)){var t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}}},{key:"_adjustPosition",value:function(){if(!this._isCustom){var e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}}},{key:"processes",get:function(){return this._processes},set:function(e){if(e=e||0,this._processes!==e&&!(e<0)){var t=this._processes;this._processes=e;var i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}}},{key:"_destroy",value:function(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);var e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}]),i}(),mh=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"],_h=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E(this,i),(r=t.call(this,e,n))._backgroundColor=le.vec3([n.backgroundColor?n.backgroundColor[0]:1,n.backgroundColor?n.backgroundColor[1]:1,n.backgroundColor?n.backgroundColor[2]:1]),r._backgroundColorFromAmbientLight=!!n.backgroundColorFromAmbientLight,r.canvas=n.canvas,r.gl=null,r.webgl2=!1,r.transparent=!!n.transparent,r.contextAttr=n.contextAttr||{},r.contextAttr.alpha=r.transparent,r.contextAttr.preserveDrawingBuffer=!!r.contextAttr.preserveDrawingBuffer,r.contextAttr.stencil=!1,r.contextAttr.premultipliedAlpha=!!r.contextAttr.premultipliedAlpha,r.contextAttr.antialias=!1!==r.contextAttr.antialias,r.resolutionScale=n.resolutionScale,r.canvas.width=Math.round(r.canvas.clientWidth*r._resolutionScale),r.canvas.height=Math.round(r.canvas.clientHeight*r._resolutionScale),r.boundary=[r.canvas.offsetLeft,r.canvas.offsetTop,r.canvas.clientWidth,r.canvas.clientHeight],r._initWebGL(n);var s=w(r);r.canvas.addEventListener("webglcontextlost",r._webglcontextlostListener=function(e){console.time("webglcontextrestored"),s.scene._webglContextLost(),s.fire("webglcontextlost"),e.preventDefault()},!1),r.canvas.addEventListener("webglcontextrestored",r._webglcontextrestoredListener=function(e){s._initWebGL(),s.gl&&(s.scene._webglContextRestored(s.gl),s.fire("webglcontextrestored",s.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);var o=!0,a=new ResizeObserver((function(e){var t,i=p(e);try{for(i.s();!(t=i.n()).done;){t.value.contentBoxSize&&(o=!0)}}catch(e){i.e(e)}finally{i.f()}}));return a.observe(r.canvas),r._tick=r.scene.on("tick",(function(){o&&(o=!1,s.canvas.width=Math.round(s.canvas.clientWidth*s._resolutionScale),s.canvas.height=Math.round(s.canvas.clientHeight*s._resolutionScale),s.boundary[0]=s.canvas.offsetLeft,s.boundary[1]=s.canvas.offsetTop,s.boundary[2]=s.canvas.clientWidth,s.boundary[3]=s.canvas.clientHeight,s.fire("boundary",s.boundary))})),r._spinner=new gh(r.scene,{canvas:r.canvas,elementId:n.spinnerElementId}),r}return I(i,[{key:"type",get:function(){return"Canvas"}},{key:"backgroundColorFromAmbientLight",get:function(){return this._backgroundColorFromAmbientLight},set:function(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}},{key:"backgroundColor",get:function(){return this._backgroundColor},set:function(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}},{key:"resolutionScale",get:function(){return this._resolutionScale},set:function(e){if((e=e||1)!==this._resolutionScale){this._resolutionScale=e;var t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}}},{key:"spinner",get:function(){return this._spinner}},{key:"_createCanvas",value:function(){var e="xeokit-canvas-"+le.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),r=i.style;r.height="100%",r.width="100%",r.padding="0",r.margin="0",r.background="rgba(0,0,0,0);",r.float="left",r.left="0",r.top="0",r.position="absolute",r.opacity="1.0",r["z-index"]="-10000",i.innerHTML+='<canvas id="'+e+'" style="width: 100%; height: 100%; float: left; margin: 0; padding: 0;"></canvas>',t.appendChild(i),this.canvas=document.getElementById(e)}},{key:"_getElementXY",value:function(e){for(var t=0,i=0;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}},{key:"_initWebGL",value:function(){if(!this.gl)for(var e=0;!this.gl&&e<mh.length;e++)try{this.gl=this.canvas.getContext(mh[e],this.contextAttr)}catch(e){}this.gl||(this.error("Failed to get a WebGL context"),this.fire("webglContextFailed",!0,!0));var t=this.gl,i="__",r=t.activeTexture;t.activeTexture=function(e){i!==e&&(i=e,r.call(this,e))};var n={},s=t.bindTexture;t.bindTexture=function(e,t){n[i]!==t&&(n[i]=t,s.call(this,e,t))},this.gl&&this.webgl2&&(this.gl.hint(this.gl.FRAGMENT_SHADER_DERIVATIVE_HINT,this.gl.FASTEST),this.gl,WebGL2RenderingContext)}},{key:"getSnapshot",value:function(e){throw"Canvas#getSnapshot() has been replaced by Viewer#getSnapshot() - use that method instead."}},{key:"readPixels",value:function(e,t,i,r){return this.scene._renderer.readPixels(e,t,i,r)}},{key:"loseWebGLContext",value:function(){this.canvas.loseContext&&this.canvas.loseContext()}},{key:"destroy",value:function(){this.scene.off(this._tick),this._spinner._destroy(),this.canvas.removeEventListener("webglcontextlost",this._webglcontextlostListener),this.canvas.removeEventListener("webglcontextrestored",this._webglcontextrestoredListener),this.gl=null,v(x(i.prototype),"destroy",this).call(this)}}]),i}(),yh=function(){function e(t){E(this,e),this._scene=t,this._matPool=[],this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.reset()}return I(e,[{key:"reset",value:function(){this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.gl=this._scene.canvas.gl,this.lastProgramId=null,this.pbrEnabled=!1,this.colorTextureEnabled=!1,this.withSAO=!1,this.backfaces=!1,this.frontface=!0,this.textureUnit=0,this.drawElements=0,this.drawArrays=0,this.useProgram=0,this.bindTexture=0,this.bindArray=0,this.pass=0,this.shadowViewMatrix=null,this.shadowProjMatrix=null,this.pickViewMatrix=null,this.pickProjMatrix=null,this.pickZNear=.01,this.pickZFar=5e3,this.pickInvisible=!1,this.pickElementsCount=null,this.pickElementsOffset=null,this.lineWidth=1,this.snapPickLayerParams={},this.snapPickLayerNumber=0,this.snapPickCoordinateScale=le.vec3(),this.snapPickOrigin=le.vec3()}},{key:"getRTCViewMatrix",value:function(e,t){var i=this._rtcViewMats[e];return i||(i=this._getNewMat(),Jt(this._scene.camera.viewMatrix,t,i),this._rtcViewMats[e]=i),i}},{key:"getRTCPickViewMatrix",value:function(e,t){var i=this._rtcPickViewMats[e];if(!i){i=this._getNewMat();var r=this.pickViewMatrix||this._scene.camera.viewMatrix;Jt(r,t,i),this._rtcPickViewMats[e]=i}return i}},{key:"_getNewMat",value:function(){var e=this._matPool[this._matPoolNextFreeIndex];return e||(e=le.mat4(),this._matPool[this._matPoolNextFreeIndex]=e),this._matPoolNextFreeIndex++,e}}]),e}(),bh=function(){function e(t,i){E(this,e),this.scene=t,this.aabb=le.AABB3(),this.origin=le.vec3(i),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}return I(e,[{key:"addMarker",value:function(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}},{key:"markerWorldPosUpdated",value:function(e){if(this.markers[e.id]){var t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}}},{key:"removeMarker",value:function(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}},{key:"update",value:function(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}},{key:"_buildMarkerList",value:function(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}},{key:"_buildPositions",value:function(){for(var e=0,t=0;t<this.numMarkers;t++)if(this.markerList[t]){var i=this.markerList[t].rtcPos;this.positions[e++]=i[0],this.positions[e++]=i[1],this.positions[e++]=i[2],this.indices[t]=t}this.positions.length=3*this.numMarkers,this.indices.length=this.numMarkers}},{key:"_buildAABB",value:function(){var e=this.aabb;le.collapseAABB3(e),le.expandAABB3Points3(e,this.positions);var t=this.origin;e[0]+=t[0],e[1]+=t[1],e[2]+=t[2],e[3]+=t[0],e[4]+=t[1],e[5]+=t[2]}},{key:"_buildVBOs",value:function(){if(this.positionsBuf){if(this.lenPositionsBuf===this.positions.length)return void this.positionsBuf.setData(new Float32Array(this.positions));this.positionsBuf.destroy(),this.positionsBuf=null,this.indicesBuf.destroy(),this.indicesBuf=null}var e=this.scene.canvas.gl,t=3*this.numMarkers,i=this.numMarkers;this.positionsBuf=new st(e,e.ARRAY_BUFFER,new Float32Array(this.positions),t,3,e.STATIC_DRAW),this.indicesBuf=new st(e,e.ELEMENT_ARRAY_BUFFER,new Uint16Array(this.indices),i,1,e.STATIC_DRAW),this.lenPositionsBuf=this.positions.length}},{key:"_buildOcclusionTestList",value:function(){var e=this.scene.canvas,t=this.scene.camera.perspective.near,i=e.boundary,r=i[2],n=i[3],s=0;this.lenOcclusionTestList=0;for(var o=0;o<this.numMarkers;o++){var a=this.markerList[o];if(a.viewPos[2]>-t)a._setVisible(!1);else{var l=a.canvasPos,u=l[0],c=l[1];u+10<0||c+10<0||u-10>r||c-10>n?a._setVisible(!1):!a.entity||a.entity.visible?a.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=a,this.pixels[s++]=u,this.pixels[s++]=c):a._setVisible(!0):a._setVisible(!1)}}}},{key:"_updateActiveSectionPlanes",value:function(){var e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(var i=0;i<t;i++){var r=e[i];if(r.active){var n=le.planeAABB3Intersect(r.dir,r.dist,this.aabb);if(-1===n)return void(this.culledBySectionPlanes=!0);var s=0===n;this.sectionPlanesActive[i]=s}else this.sectionPlanesActive[i]=!1}this.culledBySectionPlanes=!1}},{key:"destroy",value:function(){this.markers={},this.markerList.length=0,this.positionsBuf&&this.positionsBuf.destroy(),this.indicesBuf&&this.indicesBuf.destroy()}}]),e}(),wh=le.vec3([1,0,0]),Bh=le.vec3(),xh=function(){function e(t,i){var r=this;E(this,e),this._scene=t,this._renderBufferManager=i,this._occlusionLayers={},this._occlusionLayersList=[],this._occlusionLayersListDirty=!1,this._shaderSource=null,this._program=null,this._shaderSourceHash=null,this._shaderSourceDirty=!0,this._programDirty=!1,this._markersToOcclusionLayersMap={},this._onCameraViewMatrix=t.camera.on("viewMatrix",(function(){r._occlusionTestListDirty=!0})),this._onCameraProjMatrix=t.camera.on("projMatrix",(function(){r._occlusionTestListDirty=!0})),this._onCanvasBoundary=t.canvas.on("boundary",(function(){r._occlusionTestListDirty=!0}))}return I(e,[{key:"addMarker",value:function(e){var t=e.origin.join(),i=this._occlusionLayers[t];i||(i=new bh(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}},{key:"markerWorldPosUpdated",value:function(e){var t=this._markersToOcclusionLayersMap[e.id];if(t){var i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);var r=this._occlusionLayers[i];r||(r=new bh(this._scene,e.origin),this._occlusionLayers[i]=r,this._occlusionLayersListDirty=!0),r.addMarker(e),this._markersToOcclusionLayersMap[e.id]=r}else t.markerWorldPosUpdated(e)}}},{key:"removeMarker",value:function(e){var t=e.origin.join(),i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}},{key:"needOcclusionTest",get:function(){return this._occlusionTestListDirty}},{key:"bindRenderBuf",value:function(){var e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(var t=0,i=this._occlusionLayersList.length;t<i;t++){this._occlusionLayersList[t].occlusionTestListDirty=!0}this._occlusionTestListDirty=!1}this._readPixelBuf=this._renderBufferManager.getRenderBuffer("occlusionReadPix"),this._readPixelBuf.bind(),this._readPixelBuf.clear()}},{key:"_buildOcclusionLayersList",value:function(){var e=0;for(var t in this._occlusionLayers)this._occlusionLayers.hasOwnProperty(t)&&(this._occlusionLayersList[e++]=this._occlusionLayers[t]);this._occlusionLayersList.length=e}},{key:"_buildShaderSource",value:function(){this._shaderSource={vertex:this._buildVertexShaderSource(),fragment:this._buildFragmentShaderSource()}}},{key:"_buildVertexShaderSource",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):e.markerZOffset<0&&i.push("clipPos.z += "+e.markerZOffset+";"),i.push(" gl_Position = clipPos;"),i.push("}"),i}},{key:"_buildFragmentShaderSource",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// OcclusionTester fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;");for(var n=0;n<t.sectionPlanes.length;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" float dist = 0.0;");for(var s=0;s<t.sectionPlanes.length;s++)r.push("if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),r.push("}"),r}},{key:"_buildProgram",value:function(){this._program&&this._program.destroy();var e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Pr(t,this._shaderSource),this._program.errors)this.errors=this._program.errors;else{var r=this._program;this._uViewMatrix=r.getLocation("viewMatrix"),this._uProjMatrix=r.getLocation("projMatrix"),this._uSectionPlanes=[];for(var n=0,s=i.sectionPlanes.length;n<s;n++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+n),pos:r.getLocation("sectionPlanePos"+n),dir:r.getLocation("sectionPlaneDir"+n)});this._aPosition=r.getAttribute("position"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=r.getLocation("logDepthBufFC"))}}},{key:"drawMarkers",value:function(){var e=this._scene,t=e.canvas.gl,i=this._program,r=e._sectionPlanesState,n=e.camera,s=e.camera.project;if(i.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,n._project._state.matrix),e.logarithmicDepthBufferEnabled){var o=2/(Math.log(s.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,o)}for(var a=0,l=this._occlusionLayersList.length;a<l;a++){var u=this._occlusionLayersList[a];if(u.update(),!u.culledBySectionPlanes){var c=u.origin;t.uniformMatrix4fv(this._uViewMatrix,!1,Jt(n.viewMatrix,c));var A=r.sectionPlanes.length;if(A>0)for(var h=r.sectionPlanes,d=0;d<A;d++){var p=this._uSectionPlanes[d];if(p){var f=u.sectionPlanesActive[d];if(t.uniform1i(p.active,f?1:0),f){var v=h[d];t.uniform3fv(p.pos,ei(v.dist,v.dir,c,Bh)),t.uniform3fv(p.dir,v.dir)}}}this._aPosition.bindArrayBuffer(u.positionsBuf);var g=u.indicesBuf;g.bind(),t.drawElements(t.POINTS,g.numItems,g.itemType,0)}}}},{key:"doOcclusionTest",value:function(){for(var e=this._scene.canvas.resolutionScale,t=255*wh[0],i=255*wh[1],r=255*wh[2],n=0,s=this._occlusionLayersList.length;n<s;n++)for(var o=this._occlusionLayersList[n],a=0;a<o.lenOcclusionTestList;a++){var l=o.occlusionTestList[a],u=2*a,c=this._readPixelBuf.read(Math.round(o.pixels[u]*e),Math.round(o.pixels[u+1]*e)),A=c[0]===t&&c[1]===i&&c[2]===r;l._setVisible(A)}}},{key:"unbindRenderBuf",value:function(){this._readPixelBuf.unbind()}},{key:"destroy",value:function(){if(!this.destroyed){for(var e=0,t=this._occlusionLayersList.length;e<t;e++){this._occlusionLayersList[e].destroy()}this._program&&this._program.destroy(),this._scene.camera.off(this._onCameraViewMatrix),this._scene.camera.off(this._onCameraProjMatrix),this._scene.canvas.off(this._onCanvasBoundary),this.destroyed=!0}}}]),e}(),Ph=le.vec2(),Ch=function(){function e(t){E(this,e),this._scene=t,this._numSamples=null,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uScale=null,this._uIntensity=null,this._uBias=null,this._uKernelRadius=null,this._uMinResolution=null,this._uRandomSeed=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}return I(e,[{key:"init",value:function(){this._rebuild=!0}},{key:"render",value:function(e){var t=this;if(this._build(),!this._programError){this._getInverseProjectMat||(this._getInverseProjectMat=function(){var e=!0;t._scene.camera.on("projMatrix",(function(){e=!0}));var i=le.mat4();return function(){return e&&le.inverseMat4(n.camera.projMatrix,i),i}}());var i=this._scene.canvas.gl,r=this._program,n=this._scene,s=n.sao,o=i.drawingBufferWidth,a=i.drawingBufferHeight,l=n.camera.project._state,u=l.near,c=l.far,A=l.matrix,h=this._getInverseProjectMat(),d=Math.random(),p="perspective"===n.camera.projection;Ph[0]=o,Ph[1]=a,i.viewport(0,0,o,a),i.clearColor(0,0,0,1),i.disable(i.DEPTH_TEST),i.disable(i.BLEND),i.frontFace(i.CCW),i.clear(i.COLOR_BUFFER_BIT),r.bind(),i.uniform1f(this._uCameraNear,u),i.uniform1f(this._uCameraFar,c),i.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,A),i.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,h),i.uniform1i(this._uPerspective,p),i.uniform1f(this._uScale,s.scale*(c/5)),i.uniform1f(this._uIntensity,s.intensity),i.uniform1f(this._uBias,s.bias),i.uniform1f(this._uKernelRadius,s.kernelRadius),i.uniform1f(this._uMinResolution,s.minResolution),i.uniform2fv(this._uViewport,Ph),i.uniform1f(this._uRandomSeed,d);var f=e.getDepthTexture();r.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),i.drawElements(i.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}}},{key:"_build",value:function(){var e=!1,t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),e||this._rebuild){this._rebuild=!1;var i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new Pr(i,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:["#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ".concat(this._numSamples,"\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }")]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);var r=new Float32Array([1,1,0,1,0,0,1,0]),n=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new st(i,i.ARRAY_BUFFER,n,n.length,3,i.STATIC_DRAW),this._uvBuf=new st(i,i.ARRAY_BUFFER,r,r.length,2,i.STATIC_DRAW),this._indicesBuf=new st(i,i.ELEMENT_ARRAY_BUFFER,s,s.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}}},{key:"destroy",value:function(){this._program&&(this._program.destroy(),this._program=null)}}]),e}(),Mh=new Float32Array(Dh(17,[0,1])),kh=new Float32Array(Dh(17,[1,0])),Eh=new Float32Array(function(e,t){for(var i=[],r=0;r<=e;r++)i.push(Th(r,t));return i}(17,4)),Fh=new Float32Array(2),Ih=function(){function e(t){E(this,e),this._scene=t,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}return I(e,[{key:"init",value:function(){var e=this._scene.canvas.gl;if(this._program=new Pr(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS ".concat(16,"\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }")]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);var t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),r=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new st(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new st(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new st(e,e.ELEMENT_ARRAY_BUFFER,r,r.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}},{key:"render",value:function(e,t,i){var r=this;if(!this._programError){this._getInverseProjectMat||(this._getInverseProjectMat=function(){var e=!0;r._scene.camera.on("projMatrix",(function(){e=!0}));var t=le.mat4();return function(){return e&&le.inverseMat4(o.camera.projMatrix,t),t}}());var n=this._scene.canvas.gl,s=this._program,o=this._scene,a=n.drawingBufferWidth,l=n.drawingBufferHeight,u=o.camera.project._state,c=u.near,A=u.far;n.viewport(0,0,a,l),n.clearColor(0,0,0,1),n.enable(n.DEPTH_TEST),n.disable(n.BLEND),n.frontFace(n.CCW),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),s.bind(),Fh[0]=a,Fh[1]=l,n.uniform2fv(this._uViewport,Fh),n.uniform1f(this._uCameraNear,c),n.uniform1f(this._uCameraFar,A),n.uniform1f(this._uDepthCutoff,.01),0===i?n.uniform2fv(this._uSampleOffsets,kh):n.uniform2fv(this._uSampleOffsets,Mh),n.uniform1fv(this._uSampleWeights,Eh);var h=e.getDepthTexture(),d=t.getTexture();s.bindTexture(this._uDepthTexture,h,0),s.bindTexture(this._uOcclusionTexture,d,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),n.drawElements(n.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}}},{key:"destroy",value:function(){this._program.destroy()}}]),e}();function Th(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function Dh(e,t){for(var i=[],r=0;r<=e;r++)i.push(t[0]*r),i.push(t[1]*r);return i}var Sh=function(){function e(t){E(this,e),this.scene=t,this._renderBuffersBasic={},this._renderBuffersScaled={}}return I(e,[{key:"getRenderBuffer",value:function(e,t){var i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled,r=i[e];return r||(r=new NA(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=r),r}},{key:"destroy",value:function(){for(var e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(var t in this._renderBuffersScaled)this._renderBuffersScaled[t].destroy()}}]),e}(),Rh=le.vec3([0,0,0]),Uh=function(e,t){t=t||{};var i=new yh(e),r=e.canvas.canvas,n=e.canvas.gl,s=!!t.transparent,o=t.alphaDepthMask,a=new Z({}),l={},u={},c=[],A=[],h=[],d=!0,p=!0,f=!0,v=!0,g=!0,m=!0,_=!0,y=!0,b=new Sh(e),w=!1,B=new Ch(e),x=new Ih(e);function P(){d&&(!function(){for(var e in l)if(l.hasOwnProperty(e)){var t=l[e],i=t.drawableMap,r=t.drawableListPreCull,n=0;for(var s in i)i.hasOwnProperty(s)&&(r[n++]=i[s]);r.length=n}}(),d=!1,p=!0),p&&(!function(){var e=0;for(var t in l)if(l.hasOwnProperty(t))for(var i=l[t].drawableListPreCull,r=0,n=i.length;r<n;r++){var s=i[r];c[e++]=s}c.length=e,c.sort((function(e,t){return e.renderOrder-t.renderOrder}))}(),p=!1,f=!0),f&&function(){for(var e=0,t=0,i=0,r=c.length;i<r;i++){var n=c[i];n.rebuildRenderFlags(),n.renderFlags.culled||(n.isUI?h[t++]=n:A[e++]=n)}A.length=e,h.length=t}()}function C(e){if(e.castsShadow){var t=e.getShadowRenderBuf();if(t){for(var r in t.bind(),i.reset(),i.backfaces=!0,i.frontface=!0,i.shadowViewMatrix=e.getShadowViewMatrix(),i.shadowProjMatrix=e.getShadowProjMatrix(),n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),n.clearColor(0,0,0,1),n.enable(n.DEPTH_TEST),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),l)if(l.hasOwnProperty(r))for(var s=l[r].drawableList,o=0,a=s.length;o<a;o++){var u=s[o];!1!==u.visible&&u.castsShadow&&u.drawShadow&&(u.renderFlags.colorOpaque&&u.drawShadow(i))}t.unbind()}}}function M(t,r,s,o,l,u){var c=e.canvas.resolutionScale;i.reset(),i.backfaces=!0,i.frontface=!0,i.pickOrigin=u.origin,i.pickViewMatrix=s,i.pickProjMatrix=o,i.pickInvisible=!!l.pickInvisible,i.pickClipPos=[D(r[0]*c,n.drawingBufferWidth),S(r[1]*c,n.drawingBufferHeight)],n.viewport(0,0,1,1),n.depthMask(!0),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT);var d=l.includeEntityIds,p=l.excludeEntityIds,f=function(e){for(var t=0,r=e.length;t<r;t++){var n=e[t];!0!==n.culled&&!1!==n.visible&&(!n.drawPickMesh||!0!==l.pickInvisible&&!1===n.visible||!1===n.pickable||d&&!d[n.id]||p&&p[n.id]||n.drawPickMesh(i))}};f(A),h.length>0&&(n.clear(n.DEPTH_BUFFER_BIT),f(h));var v=t.read(0,0),g=v[0]+(v[1]<<8)+(v[2]<<16)+(v[3]<<24);if(!(g<0))return a.items[g]}function k(t,r,s,o,a,l){if(r.drawPickTriangles){var u=e.canvas.resolutionScale;i.reset(),i.backfaces=!0,i.frontface=!0,i.pickOrigin=l.origin,i.pickViewMatrix=o,i.pickProjMatrix=a,i.pickClipPos=[D(s[0]*u,n.drawingBufferWidth),S(s[1]*u,n.drawingBufferHeight)],n.viewport(0,0,1,1),n.clearColor(0,0,0,0),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),r.drawPickTriangles(i);var c=t.read(0,0),A=c[0]+256*c[1]+256*c[2]*256+256*c[3]*256*256;A*=3,l.primIndex=A}}this.scene=e,this._occlusionTester=null,this.capabilities={astcSupported:!!wn(n,"WEBGL_compressed_texture_astc"),etc1Supported:!0,etc2Supported:!!wn(n,"WEBGL_compressed_texture_etc"),dxtSupported:!!wn(n,"WEBGL_compressed_texture_s3tc"),bptcSupported:!!wn(n,"EXT_texture_compression_bptc"),pvrtcSupported:!(!wn(n,"WEBGL_compressed_texture_pvrtc")&&!wn(n,"WEBKIT_WEBGL_compressed_texture_pvrtc"))},this.setTransparentEnabled=function(e){v=e,f=!0},this.setEdgesEnabled=function(e){g=e,f=!0},this.setSAOEnabled=function(e){m=e,f=!0},this.setPBREnabled=function(e){_=e,f=!0},this.setColorTextureEnabled=function(e){y=e,f=!0},this.needStateSort=function(){p=!0},this.shadowsDirty=function(){},this.imageDirty=function(){f=!0},this.webglContextLost=function(){},this.webglContextRestored=function(e){B.init(),x.init(),f=!0},this.addDrawable=function(e,t){var i=t.type;if(i){var r=l[i];r||(r={type:t.type,count:0,isStateSortable:t.isStateSortable,stateSortCompare:t.stateSortCompare,drawableMap:{},drawableListPreCull:[],drawableList:[]},l[i]=r),r.count++,r.drawableMap[e]=t,u[e]=t,d=!0}else console.error("Renderer#addDrawable() : drawable with ID "+e+" has no 'type' - ignoring")},this.removeDrawable=function(e){var t=u[e];if(t){var i=t.type,r=l[i];--r.count<=0?delete l[i]:delete r.drawableMap[e],delete u[e],d=!0}else console.error("Renderer#removeDrawable() : drawable not found with ID "+e+" - ignoring")},this.getPickID=function(e){return a.addItem(e)},this.putPickID=function(e){a.removeItem(e)},this.clear=function(t){if(n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),s)n.clearColor(1,1,1,1);else{var i=e.canvas.backgroundColorFromAmbientLight?this.lights.getAmbientColorAndIntensity():e.canvas.backgroundColor;n.clearColor(i[0],i[1],i[2],1)}n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT)},this.needsRender=function(){return f||d||p},this.render=function(t){(t=t||{}).force&&(f=!0),P(),f&&(!function(t){var r=e.sao;m&&r.possible&&function(t){var r=e.sao,s=b.getRenderBuffer("saoDepth",{depthTexture:!0});s.bind(),s.clear(),function(e){i.reset(),i.pass=e.pass,n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),n.clearColor(0,0,0,0),n.enable(n.DEPTH_TEST),n.frontFace(n.CCW),n.enable(n.CULL_FACE),n.depthMask(!0),!1!==e.clear&&n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT);for(var t=0,r=A.length;t<r;t++){var s=A[t];!0!==s.culled&&!1!==s.visible&&s.drawDepth&&s.saoEnabled&&(s.renderFlags.colorOpaque&&s.drawDepth(i))}}(t),s.unbind();var o=b.getRenderBuffer("saoOcclusion");if(o.bind(),o.clear(),B.render(s),o.unbind(),r.blur){var a=b.getRenderBuffer("saoOcclusion2");a.bind(),a.clear(),x.render(s,o,0),a.unbind(),o.bind(),o.clear(),x.render(s,a,1),o.unbind()}}(t);(function(){for(var t=e._lightsState.lights,i=0,r=t.length;i<r;i++){var n=t[i];n.castsShadow&&C(n)}})(),function(t){var r=[],a=[],l=[],u=[],c=[],d=[],p=[],f=[],w=[],B=[],x=[],P=[],C=[],M=[],k=[],E=[],F=e._lightsState.getAmbientColorAndIntensity();if(i.reset(),i.pass=t.pass,i.withSAO=!1,i.pbrEnabled=_&&!!e.pbrEnabled,i.colorTextureEnabled=y&&!!e.colorTextureEnabled,n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),s)n.clearColor(0,0,0,0);else{var I=e.canvas.backgroundColorFromAmbientLight?F:e.canvas.backgroundColor;n.clearColor(I[0],I[1],I[2],1)}n.enable(n.DEPTH_TEST),n.frontFace(n.CCW),n.enable(n.CULL_FACE),n.depthMask(!0),n.lineWidth(1),i.lineWidth=1;var T,D,S=e.sao.possible;if(m&&S){var R=b.getRenderBuffer("saoOcclusion");i.occlusionTexture=R?R.getTexture():null}else i.occlusionTexture=null;var U=Date.now();!1!==t.clear&&n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT);var L=function(t){for(var A=0,h=0,_=0,y=0,b=0,F=0,I=0,R=0,U=0,L=0,O=0,N=0,V=0,Q=0,H=0,j=0,G=0,z=t.length;G<z;G++)if(!0!==(D=t[G]).culled&&!1!==D.visible){var W=D.renderFlags;W.colorOpaque&&(m&&S&&D.saoEnabled?r[A++]=D:D.drawColorOpaque(i)),v&&W.colorTransparent&&(l[_++]=D),W.xrayedSilhouetteTransparent&&(p[I++]=D),W.xrayedSilhouetteOpaque&&(c[b++]=D),W.highlightedSilhouetteTransparent&&(x[O++]=D),W.highlightedSilhouetteOpaque&&(w[U++]=D),W.selectedSilhouetteTransparent&&(k[H++]=D),W.selectedSilhouetteOpaque&&(C[V++]=D),D.edges&&g&&(W.edgesOpaque&&(a[h++]=D),W.edgesTransparent&&(u[y++]=D),W.selectedEdgesTransparent&&(E[j++]=D),W.selectedEdgesOpaque&&(M[Q++]=D),W.xrayedEdgesTransparent&&(f[R++]=D),W.xrayedEdgesOpaque&&(d[F++]=D),W.highlightedEdgesTransparent&&(P[N++]=D),W.highlightedEdgesOpaque&&(B[L++]=D))}if(A>0)for(i.withSAO=!0,T=0;T<A;T++)r[T].drawColorOpaque(i);if(h>0)for(T=0;T<h;T++)a[T].drawEdgesColorOpaque(i);if(b>0)for(T=0;T<b;T++)c[T].drawSilhouetteXRayed(i);if(F>0)for(T=0;T<F;T++)d[T].drawEdgesXRayed(i);if(I>0||R>0||_>0||y>0){if(n.enable(n.CULL_FACE),n.enable(n.BLEND),s?(n.blendEquation(n.FUNC_ADD),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA)):(n.blendEquation(n.FUNC_ADD),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA)),i.backfaces=!1,o||n.depthMask(!1),(_>0||y>0)&&n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),y>0)for(T=0;T<y;T++)(D=u[T]).drawEdgesColorTransparent(i);if(_>0){var X=i.pickOrigin||e.camera.eye,K=l.map((function(e){return{drawable:e,distSq:le.distVec3(e.origin||Rh,X)}}));for(K.sort((function(e,t){return t.distSq-e.distSq})),T=0;T<_;T++)K[T].drawable.drawColorTransparent(i)}if(R>0)for(T=0;T<R;T++)f[T].drawEdgesXRayed(i);if(I>0)for(T=0;T<I;T++)p[T].drawSilhouetteXRayed(i);n.disable(n.BLEND),o||n.depthMask(!0)}if(U>0||L>0){if(i.lastProgramId=null,e.highlightMaterial.glowThrough&&n.clear(n.DEPTH_BUFFER_BIT),L>0)for(T=0;T<L;T++)B[T].drawEdgesHighlighted(i);if(U>0)for(T=0;T<U;T++)w[T].drawSilhouetteHighlighted(i)}if(O>0||N>0||U>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&n.clear(n.DEPTH_BUFFER_BIT),n.enable(n.BLEND),s?(n.blendEquation(n.FUNC_ADD),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA)):n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),n.enable(n.CULL_FACE),N>0)for(T=0;T<N;T++)P[T].drawEdgesHighlighted(i);if(O>0)for(T=0;T<O;T++)x[T].drawSilhouetteHighlighted(i);n.disable(n.BLEND)}if(V>0||Q>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&n.clear(n.DEPTH_BUFFER_BIT),Q>0)for(T=0;T<Q;T++)M[T].drawEdgesSelected(i);if(V>0)for(T=0;T<V;T++)C[T].drawSilhouetteSelected(i)}if(H>0||j>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&n.clear(n.DEPTH_BUFFER_BIT),n.enable(n.CULL_FACE),n.enable(n.BLEND),s?(n.blendEquation(n.FUNC_ADD),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA)):n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),j>0)for(T=0;T<j;T++)E[T].drawEdgesSelected(i);if(H>0)for(T=0;T<H;T++)k[T].drawSilhouetteSelected(i);n.disable(n.BLEND)}};L(A),h.length>0&&(n.clear(n.DEPTH_BUFFER_BIT),L(h));var O=Date.now(),N=he.frame;N.renderTime=(O-U)/1e3,N.drawElements=i.drawElements,N.drawArrays=i.drawArrays,N.useProgram=i.useProgram,N.bindTexture=i.bindTexture,N.bindArray=i.bindArray;for(var V=Cr.MAX_TEXTURE_IMAGE_UNITS,Q=0;Q<V;Q++)n.activeTexture(n.TEXTURE0+Q);n.bindTexture(n.TEXTURE_CUBE_MAP,null),n.bindTexture(n.TEXTURE_2D,null);for(var H=Cr.MAX_VERTEX_ATTRIBS,j=0;j<H;j++)n.disableVertexAttribArray(j)}(t)}(t),he.frame.frameCount++,f=!1)},this.pick=function(){var t=le.vec3();le.mat4();var i=le.mat4(),n=le.vec3(),s=le.vec3([0,1,0]),o=new ph,a=le.vec2(),u=le.vec3(),c=le.vec3(),A=le.vec3();return le.vec3(),le.vec3(),function(h){var d,p=arguments.length>1&&void 0!==arguments[1]?arguments[1]:o;p.reset(),P();var f=null,v=null,g=null;for(var m in p.pickSurface=h.pickSurface,h.canvasPos?(u[0]=h.canvasPos[0],u[1]=h.canvasPos[1],f=e.camera.viewMatrix,v=e.camera.projMatrix,g=e.camera.projection,a[0]=e.camera.project.near,a[1]=e.camera.project.far,p.canvasPos=h.canvasPos):(h.matrix?(f=h.matrix,v=e.camera.projMatrix,g=e.camera.projection,a[0]=e.camera.project.near,a[1]=e.camera.project.far):(c.set(h.origin||[0,0,0]),A.set(h.direction||[0,0,1]),d=le.addVec3(c,A,t),n[0]=Math.random(),n[1]=Math.random(),n[2]=Math.random(),le.normalizeVec3(n),le.cross3Vec3(A,n,s),f=le.lookAtMat4v(c,d,s,i),v=e.camera.ortho.matrix,g="ortho",a[0]=e.camera.ortho.near,a[1]=e.camera.ortho.far,p.origin=c,p.direction=A),u[0]=.5*r.clientWidth,u[1]=.5*r.clientHeight),l)if(l.hasOwnProperty(m))for(var _=l[m].drawableList,y=0,w=_.length;y<w;y++){var B=_[y];B.setPickMatrices&&B.setPickMatrices(f,v)}var x=b.getRenderBuffer("pick",{size:[1,1]});x.bind();var C=M(x,u,f,v,h,p);if(!C)return x.unbind(),null;var E=C.delegatePickedEntity?C.delegatePickedEntity():C;return E?(h.pickSurface&&(C.canPickTriangle&&C.canPickTriangle()?(k(x,C,u,f,v,p),C.pickTriangleSurface(f,v,g,p),p.pickSurfacePrecision=!1):C.canPickWorldPos&&C.canPickWorldPos()&&(F(x,C,u,f,v,a,p),!1!==h.pickSurfaceNormal&&R(x,C,u,f,v,p),p.pickSurfacePrecision=!1)),x.unbind(),p.entity=E,p):(x.unbind(),null)}}();var E,F=function(){var t=le.vec4(),s=le.vec4(),o=le.vec4(),a=le.vec4(),l=le.vec4(),u=le.mat4(),c=le.mat4(),A=le.mat4();return function(h,d,p,f,v,g,m){var _=e.canvas.resolutionScale;i.reset(),i.backfaces=!0,i.frontface=!0,i.pickOrigin=m.origin,i.pickViewMatrix=f,i.pickProjMatrix=v,i.pickZNear=g[0],i.pickZFar=g[1],i.pickElementsCount=d.pickElementsCount,i.pickElementsOffset=d.pickElementsOffset,i.pickClipPos=[D(p[0]*_,n.drawingBufferWidth),S(p[1]*_,n.drawingBufferHeight)],n.viewport(0,0,1,1),n.clearColor(0,0,0,0),n.depthMask(!0),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),d.drawPickDepths(i);var y,b=function(e){var t=[e[0]/256,e[1]/256,e[2]/256,e[3]/256],i=[1/16777216,1/65536,1/256,1];return le.dotVec4(t,i)}(h.read(0,0)),w=(p[0]-r.clientWidth/2)/(r.clientWidth/2),B=-(p[1]-r.clientHeight/2)/(r.clientHeight/2),x=d.origin;if(x){var P=Jt(f,x,u);y=le.mulMat4(v,P,c)}else y=le.mulMat4(v,f,c);var C=le.inverseMat4(y,A);t[0]=w,t[1]=B,t[2]=-1,t[3]=1;var M=le.transformVec4(C,t);M=le.mulVec4Scalar(M,1/M[3]),s[0]=w,s[1]=B,s[2]=1,s[3]=1;var k=le.transformVec4(C,s);k=le.mulVec4Scalar(k,1/k[3]);var E=le.subVec3(k,M,o),F=le.addVec3(M,le.mulVec4Scalar(E,b,a),l);x&&le.addVec3(F,x),m.worldPos=F}}();function I(e){e.snapPickLayerParams=[],e.snapPickLayerNumber=0;for(var t=0,i=A.length;t<i;t++){var r=A[t];r.drawSnapInit&&!r.culled&&r.visible&&r.pickable&&r.drawSnapInit(e)}return e.snapPickLayerParams}function T(e){e.snapPickLayerParams=e.snapPickLayerParams||[],e.snapPickLayerNumber=e.snapPickLayerParams.length;for(var t=0,i=A.length;t<i;t++){var r=A[t];r.drawSnapInit&&r.drawSnap&&!r.culled&&r.visible&&r.pickable&&r.drawSnap(e)}return e.snapPickLayerParams}function D(e,t){return e/t*2-1}function S(e,t){return 1-e/t*2}function R(t,r,s,o,a,l){var u=e.canvas.resolutionScale;i.reset(),i.backfaces=!0,i.frontface=!0,i.pickOrigin=l.origin,i.pickViewMatrix=o,i.pickProjMatrix=a,i.pickClipPos=[D(s[0]*u,n.drawingBufferWidth),S(s[1]*u,n.drawingBufferHeight)];var c=b.getRenderBuffer("pick-normal",{size:[3,3]});c.bind(n.RGBA32I),n.viewport(0,0,c.size[0],c.size[1]),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.DEPTH_BUFFER_BIT),n.clearBufferiv(n.COLOR,0,new Int32Array([0,0,0,0])),r.drawPickNormals(i);var A=c.read(1,1,n.RGBA_INTEGER,n.INT,Int32Array,4);c.unbind();var h=[A[0]/le.MAX_INT,A[1]/le.MAX_INT,A[2]/le.MAX_INT];le.normalizeVec3(h),l.worldNormal=h}this.snapPick=(E=new ph,function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:E,s=t.canvasPos,o=t.origin,u=t.direction,c=t.snapRadius,A=t.snapToVertex,h=t.snapToEdge;if(!A&&!h)return this.pick({canvasPos:s,pickSurface:!0});var d=e.canvas.resolutionScale;i.reset(),i.backfaces=!0,i.frontface=!0,i.pickZNear=e.camera.project.near,i.pickZFar=e.camera.project.far;var p=c||30,f=b.getRenderBuffer("uniquePickColors-aabs-".concat(p),{depthTexture:!0,size:[2*p+1,2*p+1]});i.snapVectorA=[s?D(s[0]*d,n.drawingBufferWidth):0,s?S(s[1]*d,n.drawingBufferHeight):0],i.snapInvVectorAB=[n.drawingBufferWidth/(2*p),n.drawingBufferHeight/(2*p)],f.bind(n.RGBA32I,n.RGBA32I,n.RGBA8UI),n.viewport(0,0,f.size[0],f.size[1]),n.enable(n.DEPTH_TEST),n.frontFace(n.CCW),n.disable(n.CULL_FACE),n.depthMask(!0),n.disable(n.BLEND),n.depthFunc(n.LEQUAL),n.clear(n.DEPTH_BUFFER_BIT),n.clearBufferiv(n.COLOR,0,new Int32Array([0,0,0,0])),n.clearBufferiv(n.COLOR,1,new Int32Array([0,0,0,0])),n.clearBufferuiv(n.COLOR,2,new Uint32Array([0,0,0,0])),i.pickViewMatrix=s?e.camera.viewMatrix:le.lookAtMat4v(o,le.addVec3(o,u,le.vec3()),le.vec3([0,1,0]),le.mat4());var v=e.camera.projMatrix;for(var g in l)if(l.hasOwnProperty(g))for(var m=l[g].drawableList,_=0,y=m.length;_<y;_++){var w=m[_];w.setPickMatrices&&w.setPickMatrices(i.pickViewMatrix,v)}n.drawBuffers([n.COLOR_ATTACHMENT0,n.COLOR_ATTACHMENT1,n.COLOR_ATTACHMENT2]);var B=I(i),x=[];i.snapPickLayerParams=x,n.depthMask(!1),n.drawBuffers([n.COLOR_ATTACHMENT0]),A&&h?(i.snapMode="edge",T(i),i.snapMode="vertex",i.snapPickLayerNumber++,T(i)):(i.snapMode=A?"vertex":"edge",T(i)),n.depthMask(!0);var P=f.readArray(n.RGBA_INTEGER,n.INT,Int32Array,4),C=f.readArray(n.RGBA_INTEGER,n.INT,Int32Array,4,1),M=f.readArray(n.RGBA_INTEGER,n.UNSIGNED_INT,Uint32Array,4,2);f.unbind();var k=null,F=null,R=null,U=p,L=p,O=4*U+L*f.size[0]*4,N=P.slice(O,O+4),V=C.slice(O,O+4),Q=M.slice(O,O+4);if(0!==N[3]){var H=B[Math.abs(N[3])%B.length],j=H.origin,G=H.coordinateScale;k=[N[0]*G[0]+j[0],N[1]*G[1]+j[1],N[2]*G[2]+j[2]],F=le.normalizeVec3([V[0]/le.MAX_INT,V[1]/le.MAX_INT,V[2]/le.MAX_INT]);var z=Q[0]+(Q[1]<<8)+(Q[2]<<16)+(Q[3]<<24);R=a.items[z]}for(var W=[],X=0;X<P.length;X+=4)if(P[X+3]>0){var K=Math.floor(X/4),Z=f.size[0],J=K%Z-Math.floor(Z/2),Y=Math.floor(K/Z)-Math.floor(Z/2),q=Math.sqrt(Math.pow(J,2)+Math.pow(Y,2));W.push({x:J,y:Y,dist:q,isVertex:A&&h?P[X+3]>x.length/2:A,result:[P[X+0],P[X+1],P[X+2],P[X+3]],normal:[C[X+0],C[X+1],C[X+2],C[X+3]],id:[M[X+0],M[X+1],M[X+2],M[X+3]]})}var $=null,ee=null,te=null,ie=null;if(W.length>0){W.sort((function(e,t){return e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist})),ie=W[0].isVertex?"vertex":"edge";var re=W[0].result,ne=W[0].normal,se=W[0].id,oe=x[re[3]],ae=oe.origin,ue=oe.coordinateScale;ee=le.normalizeVec3([ne[0]/le.MAX_INT,ne[1]/le.MAX_INT,ne[2]/le.MAX_INT]),$=[re[0]*ue[0]+ae[0],re[1]*ue[1]+ae[1],re[2]*ue[2]+ae[2]],te=a.items[se[0]+(se[1]<<8)+(se[2]<<16)+(se[3]<<24)]}if(null===k&&null==$)return null;var ce=null;null!==$&&(ce=e.camera.projectWorldPos($));var Ae=te&&te.delegatePickedEntity?te.delegatePickedEntity():te;return!Ae&&R&&(R=R.delegatePickedEntity?R.delegatePickedEntity():R),r.reset(),r.snappedToEdge="edge"===ie,r.snappedToVertex="vertex"===ie,r.worldPos=$||k,r.worldNormal=ee||F,r.entity=Ae||R,r.canvasPos=s||e.camera.projectWorldPos(k||$),r.snappedCanvasPos=ce||s,r}),this.addMarker=function(t){this._occlusionTester=this._occlusionTester||new xh(e,b),this._occlusionTester.addMarker(t),e.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){P(),this._occlusionTester.bindRenderBuf(),i.reset(),i.backfaces=!0,i.frontface=!0,n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),n.clearColor(0,0,0,0),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT);for(var e=0,t=A.length;e<t;e++){var r=A[e];r.drawOcclusion&&!0!==r.culled&&!1!==r.visible&&!1!==r.pickable&&r.drawOcclusion(i)}this._occlusionTester.drawMarkers(i),this._occlusionTester.doOcclusionTest(),this._occlusionTester.unbindRenderBuf()}},this.readPixels=function(e,t,i,r){var n,s,o,a,l=b.getRenderBuffer("snapshot");for(l.bind(),l.clear(),this.render({force:!0,opaqueOnly:r}),s=0;s<i;s++)o=2*s,a=4*s,n=l.read(e[o],e[o+1]),t[a]=n[0],t[a+1]=n[1],t[a+2]=n[2],t[a+3]=n[3];l.unbind(),f=!0},this.beginSnapshot=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=b.getRenderBuffer("snapshot");e.width&&e.height&&t.setSize([e.width,e.height]),t.bind(),t.clear(),w=!0},this.renderSnapshot=function(){w&&(b.getRenderBuffer("snapshot").clear(),this.render({force:!0,opaqueOnly:!1}),f=!0)},this.readSnapshot=function(e){return b.getRenderBuffer("snapshot").readImage(e)},this.readSnapshotAsCanvas=function(){return b.getRenderBuffer("snapshot").readImageAsCanvas()},this.endSnapshot=function(){w&&(b.getRenderBuffer("snapshot").unbind(),w=!1)},this.destroy=function(){l={},u={},b.destroy(),B.destroy(),x.destroy(),this._occlusionTester&&this._occlusionTester.destroy()}},Lh=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).KEY_BACKSPACE=8,r.KEY_TAB=9,r.KEY_ENTER=13,r.KEY_SHIFT=16,r.KEY_CTRL=17,r.KEY_ALT=18,r.KEY_PAUSE_BREAK=19,r.KEY_CAPS_LOCK=20,r.KEY_ESCAPE=27,r.KEY_PAGE_UP=33,r.KEY_PAGE_DOWN=34,r.KEY_END=35,r.KEY_HOME=36,r.KEY_LEFT_ARROW=37,r.KEY_UP_ARROW=38,r.KEY_RIGHT_ARROW=39,r.KEY_DOWN_ARROW=40,r.KEY_INSERT=45,r.KEY_DELETE=46,r.KEY_NUM_0=48,r.KEY_NUM_1=49,r.KEY_NUM_2=50,r.KEY_NUM_3=51,r.KEY_NUM_4=52,r.KEY_NUM_5=53,r.KEY_NUM_6=54,r.KEY_NUM_7=55,r.KEY_NUM_8=56,r.KEY_NUM_9=57,r.KEY_A=65,r.KEY_B=66,r.KEY_C=67,r.KEY_D=68,r.KEY_E=69,r.KEY_F=70,r.KEY_G=71,r.KEY_H=72,r.KEY_I=73,r.KEY_J=74,r.KEY_K=75,r.KEY_L=76,r.KEY_M=77,r.KEY_N=78,r.KEY_O=79,r.KEY_P=80,r.KEY_Q=81,r.KEY_R=82,r.KEY_S=83,r.KEY_T=84,r.KEY_U=85,r.KEY_V=86,r.KEY_W=87,r.KEY_X=88,r.KEY_Y=89,r.KEY_Z=90,r.KEY_LEFT_WINDOW=91,r.KEY_RIGHT_WINDOW=92,r.KEY_SELECT_KEY=93,r.KEY_NUMPAD_0=96,r.KEY_NUMPAD_1=97,r.KEY_NUMPAD_2=98,r.KEY_NUMPAD_3=99,r.KEY_NUMPAD_4=100,r.KEY_NUMPAD_5=101,r.KEY_NUMPAD_6=102,r.KEY_NUMPAD_7=103,r.KEY_NUMPAD_8=104,r.KEY_NUMPAD_9=105,r.KEY_MULTIPLY=106,r.KEY_ADD=107,r.KEY_SUBTRACT=109,r.KEY_DECIMAL_POINT=110,r.KEY_DIVIDE=111,r.KEY_F1=112,r.KEY_F2=113,r.KEY_F3=114,r.KEY_F4=115,r.KEY_F5=116,r.KEY_F6=117,r.KEY_F7=118,r.KEY_F8=119,r.KEY_F9=120,r.KEY_F10=121,r.KEY_F11=122,r.KEY_F12=123,r.KEY_NUM_LOCK=144,r.KEY_SCROLL_LOCK=145,r.KEY_SEMI_COLON=186,r.KEY_EQUAL_SIGN=187,r.KEY_COMMA=188,r.KEY_DASH=189,r.KEY_PERIOD=190,r.KEY_FORWARD_SLASH=191,r.KEY_GRAVE_ACCENT=192,r.KEY_OPEN_BRACKET=219,r.KEY_BACK_SLASH=220,r.KEY_CLOSE_BRACKET=221,r.KEY_SINGLE_QUOTE=222,r.KEY_SPACE=32,r.MOUSE_LEFT_BUTTON=260,r.MOUSE_MIDDLE_BUTTON=261,r.MOUSE_RIGHT_BUTTON=262,r.element=n.element,r.altDown=!1,r.ctrlDown=!1,r.mouseDownLeft=!1,r.mouseDownMiddle=!1,r.mouseDownRight=!1,r.keyDown=[],r.enabled=!0,r.keyboardEnabled=!0,r.mouseover=!1,r.mouseCanvasPos=le.vec2(),r._keyboardEventsElement=n.keyboardEventsElement||document,r._bindEvents(),r}return I(i,[{key:"_bindEvents",value:function(){var e=this;if(!this._eventsBound){this._keyboardEventsElement.addEventListener("keydown",this._keyDownListener=function(t){e.enabled&&e.keyboardEnabled&&"INPUT"!==t.target.tagName&&"TEXTAREA"!==t.target.tagName&&(t.keyCode===e.KEY_CTRL?e.ctrlDown=!0:t.keyCode===e.KEY_ALT?e.altDown=!0:t.keyCode===e.KEY_SHIFT&&(e.shiftDown=!0),e.keyDown[t.keyCode]=!0,e.fire("keydown",t.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=function(t){e.enabled&&e.keyboardEnabled&&"INPUT"!==t.target.tagName&&"TEXTAREA"!==t.target.tagName&&(t.keyCode===e.KEY_CTRL?e.ctrlDown=!1:t.keyCode===e.KEY_ALT?e.altDown=!1:t.keyCode===e.KEY_SHIFT&&(e.shiftDown=!1),e.keyDown[t.keyCode]=!1,e.fire("keyup",t.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=function(t){e.enabled&&(e.mouseover=!0,e._getMouseCanvasPos(t),e.fire("mouseenter",e.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=function(t){e.enabled&&(e.mouseover=!1,e._getMouseCanvasPos(t),e.fire("mouseleave",e.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=function(t){if(e.enabled){switch(t.which){case 1:e.mouseDownLeft=!0;break;case 2:e.mouseDownMiddle=!0;break;case 3:e.mouseDownRight=!0}e._getMouseCanvasPos(t),e.element.focus(),e.fire("mousedown",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=function(t){if(e.enabled){switch(t.which){case 1:e.mouseDownLeft=!1;break;case 2:e.mouseDownMiddle=!1;break;case 3:e.mouseDownRight=!1}e.fire("mouseup",e.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=function(t){if(e.enabled){switch(t.which){case 1:case 3:e.mouseDownLeft=!1,e.mouseDownRight=!1;break;case 2:e.mouseDownMiddle=!1}e._getMouseCanvasPos(t),e.fire("click",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=function(t){if(e.enabled){switch(t.which){case 1:case 3:e.mouseDownLeft=!1,e.mouseDownRight=!1;break;case 2:e.mouseDownMiddle=!1}e._getMouseCanvasPos(t),e.fire("dblclick",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}});var t=this.scene.tickify((function(){return e.fire("mousemove",e.mouseCanvasPos,!0)}));this.element.addEventListener("mousemove",this._mouseMoveListener=function(i){e.enabled&&(e._getMouseCanvasPos(i),t(),e.mouseover&&i.preventDefault())}),this.element.addEventListener("contextmenu",this._contextmenuListener=function(t){e.enabled&&(e._getMouseCanvasPos(t),e.fire("contextmenu",e.mouseCanvasPos,!0))});var i=this.scene.tickify((function(t){e.fire("mousewheel",t,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=function(t,r){if(e.enabled){var n=Math.max(-1,Math.min(1,40*-t.deltaY));i(n)}},{passive:!0});var r,n;this.on("mousedown",(function(e){r=e[0],n=e[1]})),this.on("mouseup",(function(t){r>=t[0]-2&&r<=t[0]+2&&n>=t[1]-2&&n<=t[1]+2&&e.fire("mouseclicked",t,!0)})),this.element.addEventListener("touchstart",this._touchstartListener=function(t){e.enabled&&f(t.changedTouches).forEach((function(t){e.fire("touchstart",[t.identifier,e._getTouchCanvasPos(t)],!0)}))}),this.element.addEventListener("touchend",this._touchendListener=function(t){e.enabled&&f(t.changedTouches).forEach((function(t){e.fire("touchend",[t.identifier,e._getTouchCanvasPos(t)],!0)}))}),this._eventsBound=!0}}},{key:"_unbindEvents",value:function(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("contextmenu",this._contextmenuListener),this.element.removeEventListener("wheel",this._mouseWheelListener),this.element.removeEventListener("touchstart",this._touchstartListener),this.element.removeEventListener("touchend",this._touchendListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}},{key:"_getTouchCanvasPos",value:function(e){for(var t=e.target,i=0,r=0;t.offsetParent;)i+=t.offsetLeft,r+=t.offsetTop,t=t.offsetParent;return[e.pageX-i,e.pageY-r]}},{key:"_getMouseCanvasPos",value:function(e){if(e){var t=e.target.getBoundingClientRect();this.mouseCanvasPos[0]=e.clientX-t.left,this.mouseCanvasPos[1]=e.clientY-t.top}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}},{key:"setEnabled",value:function(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}},{key:"getEnabled",value:function(){return this.enabled}},{key:"setKeyboardEnabled",value:function(e){this.keyboardEnabled=e}},{key:"getKeyboardEnabled",value:function(){return this.keyboardEnabled}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._unbindEvents()}}]),i}(),Oh=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state=new nt({boundary:[0,0,100,100]}),r.boundary=n.boundary,r.autoBoundary=n.autoBoundary,r}return I(i,[{key:"type",get:function(){return"Viewport"}},{key:"boundary",get:function(){return this._state.boundary},set:function(e){if(!this._autoBoundary){if(!e){var t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}},{key:"autoBoundary",get:function(){return this._autoBoundary},set:function(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){var t=e[2],i=e[3];this._state.boundary=[0,0,t,i],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Nh=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).camera=e,r._state=new nt({matrix:le.mat4(),inverseMatrix:le.mat4(),transposedMatrix:le.mat4(),near:.1,far:1e4}),r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!0,r._fov=60,r._canvasResized=r.scene.canvas.on("boundary",r._needUpdate,w(r)),r.fov=n.fov,r.fovAxis=n.fovAxis,r.near=n.near,r.far=n.far,r}return I(i,[{key:"type",get:function(){return"Perspective"}},{key:"_update",value:function(){var e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis,r=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(r/=t),r=Math.min(r,120),le.perspectiveMat4(r*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}},{key:"fov",get:function(){return this._fov},set:function(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}},{key:"fovAxis",get:function(){return this._fovAxis},set:function(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}},{key:"near",get:function(){return this._state.near},set:function(e){var t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}},{key:"far",get:function(){return this._state.far},set:function(e){var t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(le.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(le.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,r,n){var s=this.scene.canvas.canvas,o=s.offsetWidth/2,a=s.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,le.mulMat4v4(this.inverseMatrix,i,r),le.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,le.mulMat4v4(this.camera.inverseViewMatrix,r,n),n}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}]),i}(),Vh=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).camera=e,r._state=new nt({matrix:le.mat4(),inverseMatrix:le.mat4(),transposedMatrix:le.mat4(),near:.1,far:1e4}),r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!0,r.scale=n.scale,r.near=n.near,r.far=n.far,r._onCanvasBoundary=r.scene.canvas.on("boundary",r._needUpdate,w(r)),r}return I(i,[{key:"type",get:function(){return"Ortho"}},{key:"_update",value:function(){var e,t,i,r,n=this.scene,s=.5*this._scale,o=n.canvas.boundary,a=o[2],l=o[3],u=a/l;a>l?(e=-s,t=s,i=s/u,r=-s/u):(e=-s*u,t=s*u,i=s,r=-s),le.orthoMat4c(e,t,r,i,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"scale",get:function(){return this._scale},set:function(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}},{key:"near",get:function(){return this._state.near},set:function(e){var t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}},{key:"far",get:function(){return this._state.far},set:function(e){var t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(le.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(le.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,r,n){var s=this.scene.canvas.canvas,o=s.offsetWidth/2,a=s.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,le.mulMat4v4(this.inverseMatrix,i,r),le.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,le.mulMat4v4(this.camera.inverseViewMatrix,r,n),n}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}]),i}(),Qh=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).camera=e,r._state=new nt({matrix:le.mat4(),inverseMatrix:le.mat4(),transposedMatrix:le.mat4(),near:.1,far:1e4}),r._left=-1,r._right=1,r._bottom=-1,r._top=1,r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!0,r.left=n.left,r.right=n.right,r.bottom=n.bottom,r.top=n.top,r.near=n.near,r.far=n.far,r}return I(i,[{key:"type",get:function(){return"Frustum"}},{key:"_update",value:function(){le.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"left",get:function(){return this._left},set:function(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}},{key:"right",get:function(){return this._right},set:function(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}},{key:"top",get:function(){return this._top},set:function(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}},{key:"bottom",get:function(){return this._bottom},set:function(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}},{key:"near",get:function(){return this._state.near},set:function(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}},{key:"far",get:function(){return this._state.far},set:function(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(le.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(le.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,r,n){var s=this.scene.canvas.canvas,o=s.offsetWidth/2,a=s.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,le.mulMat4v4(this.inverseMatrix,i,r),le.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,le.mulMat4v4(this.camera.inverseViewMatrix,r,n),n}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy(),v(x(i.prototype),"destroy",this).call(this)}}]),i}(),Hh=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).camera=e,r._state=new nt({matrix:le.mat4(),inverseMatrix:le.mat4(),transposedMatrix:le.mat4()}),r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!1,r.matrix=n.matrix,r}return I(i,[{key:"type",get:function(){return"CustomProjection"}},{key:"matrix",get:function(){return this._state.matrix},set:function(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(le.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(le.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,r,n){var s=this.scene.canvas.canvas,o=s.offsetWidth/2,a=s.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,le.mulMat4v4(this.inverseMatrix,i,r),le.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,le.mulMat4v4(this.camera.inverseViewMatrix,r,n),n}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),jh=le.vec3(),Gh=le.vec3(),zh=le.vec3(),Wh=le.vec3(),Xh=le.vec3(),Kh=le.vec3(),Zh=le.vec4(),Jh=le.vec4(),Yh=le.vec4(),qh=le.mat4(),$h=le.mat4(),ed=le.vec3(),td=le.vec3(),id=le.vec3(),rd=le.vec3(),nd=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state=new nt({offsetEyeFromLook:!0,deviceMatrix:le.mat4(),hasDeviceMatrix:!1,matrix:le.mat4(),normalMatrix:le.mat4(),inverseMatrix:le.mat4()}),r._perspective=new Nh(w(r)),r._ortho=new Vh(w(r)),r._frustum=new Qh(w(r)),r._customProjection=new Hh(w(r)),r._project=r._perspective,r._eye=le.vec3([0,0,10]),r._look=le.vec3([0,0,0]),r._up=le.vec3([0,1,0]),r._worldUp=le.vec3([0,1,0]),r._worldRight=le.vec3([1,0,0]),r._worldForward=le.vec3([0,0,-1]),r.deviceMatrix=n.deviceMatrix,r.eye=n.eye,r.look=n.look,r.up=n.up,r.worldAxis=n.worldAxis,r.gimbalLock=n.gimbalLock,r.constrainPitch=n.constrainPitch,r.projection=n.projection,r._perspective.on("matrix",(function(){"perspective"===r._projectionType&&r.fire("projMatrix",r._perspective.matrix)})),r._ortho.on("matrix",(function(){"ortho"===r._projectionType&&r.fire("projMatrix",r._ortho.matrix)})),r._frustum.on("matrix",(function(){"frustum"===r._projectionType&&r.fire("projMatrix",r._frustum.matrix)})),r._customProjection.on("matrix",(function(){"customProjection"===r._projectionType&&r.fire("projMatrix",r._customProjection.matrix)})),r}return I(i,[{key:"type",get:function(){return"Camera"}},{key:"_update",value:function(){var e,t=this._state;"ortho"===this.projection&&this._state.offsetEyeFromLook?(le.subVec3(this._eye,this._look,ed),le.normalizeVec3(ed,td),le.mulVec3Scalar(td,1e3,id),le.addVec3(this._look,id,rd),e=rd):e=this._eye,t.hasDeviceMatrix?(le.lookAtMat4v(e,this._look,this._up,$h),le.mulMat4(t.deviceMatrix,$h,t.matrix)):le.lookAtMat4v(e,this._look,this._up,t.matrix),le.inverseMat4(this._state.matrix,this._state.inverseMatrix),le.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}},{key:"orbitYaw",value:function(e){var t=le.subVec3(this._eye,this._look,jh);le.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,qh),t=le.transformPoint3(qh,t,Gh),this.eye=le.addVec3(this._look,t,zh),this.up=le.transformPoint3(qh,this._up,Wh)}},{key:"orbitPitch",value:function(e){if(!(this._constrainPitch&&(e=le.dotVec3(this._up,this._worldUp)/le.DEGTORAD)<1)){var t=le.subVec3(this._eye,this._look,jh),i=le.cross3Vec3(le.normalizeVec3(t,Gh),le.normalizeVec3(this._up,zh));le.rotationMat4v(.0174532925*e,i,qh),t=le.transformPoint3(qh,t,Wh),this.up=le.transformPoint3(qh,this._up,Xh),this.eye=le.addVec3(t,this._look,Kh)}}},{key:"yaw",value:function(e){var t=le.subVec3(this._look,this._eye,jh);le.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,qh),t=le.transformPoint3(qh,t,Gh),this.look=le.addVec3(t,this._eye,zh),this._gimbalLock&&(this.up=le.transformPoint3(qh,this._up,Wh))}},{key:"pitch",value:function(e){if(!(this._constrainPitch&&(e=le.dotVec3(this._up,this._worldUp)/le.DEGTORAD)<1)){var t=le.subVec3(this._look,this._eye,jh),i=le.cross3Vec3(le.normalizeVec3(t,Gh),le.normalizeVec3(this._up,zh));le.rotationMat4v(.0174532925*e,i,qh),this.up=le.transformPoint3(qh,this._up,Kh),t=le.transformPoint3(qh,t,Wh),this.look=le.addVec3(t,this._eye,Xh)}}},{key:"pan",value:function(e){var t,i=le.subVec3(this._eye,this._look,jh),r=[0,0,0];if(0!==e[0]){var n=le.cross3Vec3(le.normalizeVec3(i,[]),le.normalizeVec3(this._up,Gh));t=le.mulVec3Scalar(n,e[0]),r[0]+=t[0],r[1]+=t[1],r[2]+=t[2]}0!==e[1]&&(t=le.mulVec3Scalar(le.normalizeVec3(this._up,zh),e[1]),r[0]+=t[0],r[1]+=t[1],r[2]+=t[2]),0!==e[2]&&(t=le.mulVec3Scalar(le.normalizeVec3(i,Wh),e[2]),r[0]+=t[0],r[1]+=t[1],r[2]+=t[2]),this.eye=le.addVec3(this._eye,r,Xh),this.look=le.addVec3(this._look,r,Kh)}},{key:"zoom",value:function(e){var t=le.subVec3(this._eye,this._look,jh),i=Math.abs(le.lenVec3(t,Gh)),r=Math.abs(i+e);if(!(r<.5)){var n=le.normalizeVec3(t,zh);this.eye=le.addVec3(this._look,le.mulVec3Scalar(n,r),Wh)}}},{key:"eye",get:function(){return this._eye},set:function(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}},{key:"look",get:function(){return this._look},set:function(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}},{key:"up",get:function(){return this._up},set:function(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}},{key:"deviceMatrix",get:function(){return this._state.deviceMatrix},set:function(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}},{key:"worldAxis",get:function(){return this._worldAxis},set:function(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=le.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}},{key:"worldUp",get:function(){return this._worldUp}},{key:"xUp",get:function(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}},{key:"yUp",get:function(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}},{key:"zUp",get:function(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}},{key:"worldRight",get:function(){return this._worldRight}},{key:"worldForward",get:function(){return this._worldForward}},{key:"gimbalLock",get:function(){return this._gimbalLock},set:function(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}},{key:"constrainPitch",set:function(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}},{key:"eyeLookDist",get:function(){return le.lenVec3(le.subVec3(this._look,this._eye,jh))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"viewMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"normalMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}},{key:"viewNormalMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}},{key:"inverseViewMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}},{key:"projMatrix",get:function(){return this[this.projection].matrix}},{key:"perspective",get:function(){return this._perspective}},{key:"ortho",get:function(){return this._ortho}},{key:"frustum",get:function(){return this._frustum}},{key:"customProjection",get:function(){return this._customProjection}},{key:"projection",get:function(){return this._projectionType},set:function(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}},{key:"project",get:function(){return this._project}},{key:"offsetEyeFromLook",get:function(){return this._state.offsetEyeFromLook},set:function(e){this._state.offsetEyeFromLook=e,this._needUpdate(0)}},{key:"projectWorldPos",value:function(e){var t=Zh,i=Jh,r=Yh;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,le.mulMat4v4(this.viewMatrix,t,i),le.mulMat4v4(this.projMatrix,i,r),le.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1;var n=this.scene.canvas.canvas,s=n.offsetWidth/2,o=n.offsetHeight/2;return[r[0]*s+s,r[1]*o+o]}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),sd={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}},od=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._units="meters",r._scale=1,r._origin=le.vec3([0,0,0]),r.units=n.units,r.scale=n.scale,r.origin=n.origin,r}return I(i,[{key:"unitsInfo",get:function(){return sd}},{key:"units",get:function(){return this._units},set:function(e){e||(e="meters"),sd[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}},{key:"scale",get:function(){return this._scale},set:function(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}},{key:"origin",get:function(){return this._origin},set:function(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}},{key:"worldToRealPos",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:le.vec3(3);t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}},{key:"realToWorldPos",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:le.vec3(3);return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}]),i}(),ad=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._supported=Cr.SUPPORTED_EXTENSIONS.OES_standard_derivatives,r.enabled=n.enabled,r.kernelRadius=n.kernelRadius,r.intensity=n.intensity,r.bias=n.bias,r.scale=n.scale,r.minResolution=n.minResolution,r.numSamples=n.numSamples,r.blur=n.blur,r.blendCutoff=n.blendCutoff,r.blendFactor=n.blendFactor,r}return I(i,[{key:"supported",get:function(){return this._supported}},{key:"enabled",get:function(){return this._enabled},set:function(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}},{key:"possible",get:function(){if(!this._supported)return!1;if(!this._enabled)return!1;var e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}},{key:"active",get:function(){return this._active}},{key:"kernelRadius",get:function(){return this._kernelRadius},set:function(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}},{key:"intensity",get:function(){return this._intensity},set:function(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}},{key:"bias",get:function(){return this._bias},set:function(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}},{key:"scale",get:function(){return this._scale},set:function(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}},{key:"minResolution",get:function(){return this._minResolution},set:function(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}},{key:"numSamples",get:function(){return this._numSamples},set:function(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}},{key:"blur",get:function(){return this._blur},set:function(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}},{key:"blendCutoff",get:function(){return this._blendCutoff},set:function(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}},{key:"blendFactor",get:function(){return this._blendFactor},set:function(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this)}}]),i}(),ld=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).sliceColor=n.sliceColor,r.sliceThickness=n.sliceThickness,r}return I(i,[{key:"sliceThickness",get:function(){return this._sliceThickness},set:function(e){null==e&&(e=0),this._sliceThickness!==e&&(this._sliceThickness=e,this.glRedraw())}},{key:"sliceColor",get:function(){return this._sliceColor},set:function(e){null==e&&(e=[0,0,0,1]),this._sliceColor!==e&&(this._sliceColor=e,this.glRedraw())}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this)}}]),i}(),ud={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}},cd=function(e){m(i,mn);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state=new nt({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),n.preset?(r.preset=n.preset,void 0!==n.pointSize&&(r.pointSize=n.pointSize),void 0!==n.roundPoints&&(r.roundPoints=n.roundPoints),void 0!==n.perspectivePoints&&(r.perspectivePoints=n.perspectivePoints),void 0!==n.minPerspectivePointSize&&(r.minPerspectivePointSize=n.minPerspectivePointSize),void 0!==n.maxPerspectivePointSize&&(r.maxPerspectivePointSize=n.minPerspectivePointSize)):(r._preset="default",r.pointSize=n.pointSize,r.roundPoints=n.roundPoints,r.perspectivePoints=n.perspectivePoints,r.minPerspectivePointSize=n.minPerspectivePointSize,r.maxPerspectivePointSize=n.maxPerspectivePointSize),r.filterIntensity=n.filterIntensity,r.minIntensity=n.minIntensity,r.maxIntensity=n.maxIntensity,r}return I(i,[{key:"type",get:function(){return"PointsMaterial"}},{key:"presets",get:function(){return ud}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||2,this.glRedraw()}},{key:"roundPoints",get:function(){return this._state.roundPoints},set:function(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"perspectivePoints",get:function(){return this._state.perspectivePoints},set:function(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"minPerspectivePointSize",get:function(){return this._state.minPerspectivePointSize},set:function(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}},{key:"maxPerspectivePointSize",get:function(){return this._state.maxPerspectivePointSize},set:function(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}},{key:"filterIntensity",get:function(){return this._state.filterIntensity},set:function(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"minIntensity",get:function(){return this._state.minIntensity},set:function(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}},{key:"maxIntensity",get:function(){return this._state.maxIntensity},set:function(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=ud[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(ud).join(", "))}}},{key:"hash",get:function(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Ad={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}},hd=function(e){m(i,mn);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state=new nt({type:"LinesMaterial",lineWidth:null}),n.preset?(r.preset=n.preset,void 0!==n.lineWidth&&(r.lineWidth=n.lineWidth)):(r._preset="default",r.lineWidth=n.lineWidth),r}return I(i,[{key:"type",get:function(){return"LinesMaterial"}},{key:"presets",get:function(){return Ad}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Ad[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Ad).join(", "))}}},{key:"hash",get:function(){return[""+this.lineWidth].join(";")}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}();function dd(e,t){var i,r,n,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:2,o=t&&t.length,a=o?t[0]*s:e.length,l=pd(e,0,a,s,!0),u=[];if(!l||l.next===l.prev)return u;if(o&&(l=bd(e,t,l,s)),e.length>80*s){i=1/0,r=1/0;for(var c=-1/0,A=-1/0,h=s;h<a;h+=s){var d=e[h],p=e[h+1];d<i&&(i=d),p<r&&(r=p),d>c&&(c=d),p>A&&(A=p)}n=0!==(n=Math.max(c-i,A-r))?32767/n:0}return vd(l,u,s,i,r,n,0),u}function pd(e,t,i,r,n){var s;if(n===function(e,t,i,r){for(var n=0,s=t,o=i-r;s<i;s+=r)n+=(e[o]-e[s])*(e[s+1]+e[o+1]),o=s;return n}(e,t,i,r)>0)for(var o=t;o<i;o+=r)s=Ld(o/r|0,e[o],e[o+1],s);else for(var a=i-r;a>=t;a-=r)s=Ld(a/r|0,e[a],e[a+1],s);return s&&Id(s,s.next)&&(Od(s),s=s.next),s}function fd(e,t){if(!e)return e;t||(t=e);var i,r=e;do{if(i=!1,r.steiner||!Id(r,r.next)&&0!==Fd(r.prev,r,r.next))r=r.next;else{if(Od(r),(r=t=r.prev)===r.next)break;i=!0}}while(i||r!==t);return t}function vd(e,t,i,r,n,s,o){if(e){!o&&s&&function(e,t,i,r){var n=e;do{0===n.z&&(n.z=Pd(n.x,n.y,t,i,r)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next}while(n!==e);n.prevZ.nextZ=null,n.prevZ=null,function(e){var t,i=1;do{var r=e,n=void 0;e=null;var s=null;for(t=0;r;){t++;for(var o=r,a=0,l=0;l<i&&(a++,o=o.nextZ);l++);for(var u=i;a>0||u>0&&o;)0!==a&&(0===u||!o||r.z<=o.z)?(n=r,r=r.nextZ,a--):(n=o,o=o.nextZ,u--),s?s.nextZ=n:e=n,n.prevZ=s,s=n;r=o}s.nextZ=null,i*=2}while(t>1)}(n)}(e,r,n,s);for(var a=e;e.prev!==e.next;){var l=e.prev,u=e.next;if(s?md(e,r,n,s):gd(e))t.push(l.i,e.i,u.i),Od(e),e=u.next,a=u.next;else if((e=u)===a){o?1===o?vd(e=_d(fd(e),t),t,i,r,n,s,2):2===o&&yd(e,t,i,r,n,s):vd(fd(e),t,i,r,n,s,1);break}}}}function gd(e){var t=e.prev,i=e,r=e.next;if(Fd(t,i,r)>=0)return!1;for(var n=t.x,s=i.x,o=r.x,a=t.y,l=i.y,u=r.y,c=Math.min(n,s,o),A=Math.min(a,l,u),h=Math.max(n,s,o),d=Math.max(a,l,u),p=r.next;p!==t;){if(p.x>=c&&p.x<=h&&p.y>=A&&p.y<=d&&kd(n,a,s,l,o,u,p.x,p.y)&&Fd(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function md(e,t,i,r){var n=e.prev,s=e,o=e.next;if(Fd(n,s,o)>=0)return!1;for(var a=n.x,l=s.x,u=o.x,c=n.y,A=s.y,h=o.y,d=Math.min(a,l,u),p=Math.min(c,A,h),f=Math.max(a,l,u),v=Math.max(c,A,h),g=Pd(d,p,t,i,r),m=Pd(f,v,t,i,r),_=e.prevZ,y=e.nextZ;_&&_.z>=g&&y&&y.z<=m;){if(_.x>=d&&_.x<=f&&_.y>=p&&_.y<=v&&_!==n&&_!==o&&kd(a,c,l,A,u,h,_.x,_.y)&&Fd(_.prev,_,_.next)>=0)return!1;if(_=_.prevZ,y.x>=d&&y.x<=f&&y.y>=p&&y.y<=v&&y!==n&&y!==o&&kd(a,c,l,A,u,h,y.x,y.y)&&Fd(y.prev,y,y.next)>=0)return!1;y=y.nextZ}for(;_&&_.z>=g;){if(_.x>=d&&_.x<=f&&_.y>=p&&_.y<=v&&_!==n&&_!==o&&kd(a,c,l,A,u,h,_.x,_.y)&&Fd(_.prev,_,_.next)>=0)return!1;_=_.prevZ}for(;y&&y.z<=m;){if(y.x>=d&&y.x<=f&&y.y>=p&&y.y<=v&&y!==n&&y!==o&&kd(a,c,l,A,u,h,y.x,y.y)&&Fd(y.prev,y,y.next)>=0)return!1;y=y.nextZ}return!0}function _d(e,t){var i=e;do{var r=i.prev,n=i.next.next;!Id(r,n)&&Td(r,i,i.next,n)&&Rd(r,n)&&Rd(n,r)&&(t.push(r.i,i.i,n.i),Od(i),Od(i.next),i=e=n),i=i.next}while(i!==e);return fd(i)}function yd(e,t,i,r,n,s){var o=e;do{for(var a=o.next.next;a!==o.prev;){if(o.i!==a.i&&Ed(o,a)){var l=Ud(o,a);return o=fd(o,o.next),l=fd(l,l.next),vd(o,t,i,r,n,s,0),void vd(l,t,i,r,n,s,0)}a=a.next}o=o.next}while(o!==e)}function bd(e,t,i,r){for(var n=[],s=0,o=t.length;s<o;s++){var a=pd(e,t[s]*r,s<o-1?t[s+1]*r:e.length,r,!1);a===a.next&&(a.steiner=!0),n.push(Cd(a))}n.sort(wd);for(var l=0;l<n.length;l++)i=Bd(n[l],i);return i}function wd(e,t){var i=e.x-t.x;0===i&&(0===(i=e.y-t.y)&&(i=(e.next.y-e.y)/(e.next.x-e.x)-(t.next.y-t.y)/(t.next.x-t.x)));return i}function Bd(e,t){var i=function(e,t){var i,r=t,n=e.x,s=e.y,o=-1/0;if(Id(e,r))return r;do{if(Id(e,r.next))return r.next;if(s<=r.y&&s>=r.next.y&&r.next.y!==r.y){var a=r.x+(s-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=n&&a>o&&(o=a,i=r.x<r.next.x?r:r.next,a===n))return i}r=r.next}while(r!==t);if(!i)return null;var l=i,u=i.x,c=i.y,A=1/0;r=i;do{if(n>=r.x&&r.x>=u&&n!==r.x&&Md(s<c?n:o,s,u,c,s<c?o:n,s,r.x,r.y)){var h=Math.abs(s-r.y)/(n-r.x);Rd(r,e)&&(h<A||h===A&&(r.x>i.x||r.x===i.x&&xd(i,r)))&&(i=r,A=h)}r=r.next}while(r!==l);return i}(e,t);if(!i)return t;var r=Ud(i,e);return fd(r,r.next),fd(i,i.next)}function xd(e,t){return Fd(e.prev,e,t.prev)<0&&Fd(t.next,e,e.next)<0}function Pd(e,t,i,r,n){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-i)*n|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*n|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function Cd(e){var t=e,i=e;do{(t.x<i.x||t.x===i.x&&t.y<i.y)&&(i=t),t=t.next}while(t!==e);return i}function Md(e,t,i,r,n,s,o,a){return(n-o)*(t-a)>=(e-o)*(s-a)&&(e-o)*(r-a)>=(i-o)*(t-a)&&(i-o)*(s-a)>=(n-o)*(r-a)}function kd(e,t,i,r,n,s,o,a){return!(e===o&&t===a)&&Md(e,t,i,r,n,s,o,a)}function Ed(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){var i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&Td(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(Rd(e,t)&&Rd(t,e)&&function(e,t){var i=e,r=!1,n=(e.x+t.x)/2,s=(e.y+t.y)/2;do{i.y>s!=i.next.y>s&&i.next.y!==i.y&&n<(i.next.x-i.x)*(s-i.y)/(i.next.y-i.y)+i.x&&(r=!r),i=i.next}while(i!==e);return r}(e,t)&&(Fd(e.prev,e,t.prev)||Fd(e,t.prev,t))||Id(e,t)&&Fd(e.prev,e,e.next)>0&&Fd(t.prev,t,t.next)>0)}function Fd(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function Id(e,t){return e.x===t.x&&e.y===t.y}function Td(e,t,i,r){var n=Sd(Fd(e,t,i)),s=Sd(Fd(e,t,r)),o=Sd(Fd(i,r,e)),a=Sd(Fd(i,r,t));return n!==s&&o!==a||(!(0!==n||!Dd(e,i,t))||(!(0!==s||!Dd(e,r,t))||(!(0!==o||!Dd(i,e,r))||!(0!==a||!Dd(i,t,r)))))}function Dd(e,t,i){return t.x<=Math.max(e.x,i.x)&&t.x>=Math.min(e.x,i.x)&&t.y<=Math.max(e.y,i.y)&&t.y>=Math.min(e.y,i.y)}function Sd(e){return e>0?1:e<0?-1:0}function Rd(e,t){return Fd(e.prev,e,e.next)<0?Fd(e,t,e.next)>=0&&Fd(e,e.prev,t)>=0:Fd(e,t,e.prev)<0||Fd(e,e.next,t)<0}function Ud(e,t){var i=Nd(e.i,e.x,e.y),r=Nd(t.i,t.x,t.y),n=e.next,s=t.prev;return e.next=t,t.prev=e,i.next=n,n.prev=i,r.next=i,i.prev=r,s.next=r,r.prev=s,r}function Ld(e,t,i,r){var n=Nd(e,t,i);return r?(n.next=r.next,n.prev=r,r.next.prev=n,r.next=n):(n.prev=n,n.next=n),n}function Od(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function Nd(e,t,i){return{i:e,x:t,y:i,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}var Vd=[0,1,0],Qd=[1,0,0],Hd=le.vec3(),jd=le.vec3(),Gd=le.vec3(),zd=le.vec3(),Wd=le.vec3();function Xd(e,t){return Math.abs(e[0]-t[0])<1e-6&&Math.abs(e[1]-t[1])<1e-6&&Math.abs(e[2]-t[2])<1e-6}var Kd=function(){function e(t){E(this,e),this.scene=t,this._resourcesAllocated=!1}return I(e,[{key:"_onCapMaterialUpdated",value:function(e,t){var i=this;if(!this._resourcesAllocated){this._resourcesAllocated=!0,this._sectionPlanes=[],this._sceneModelsData={},this._dirtyMap={},this._prevIntersectionModelsMap={},this._sectionPlaneTimeout=null,this._updateTimeout=null;var r=function(e){var t=function(){i._setAllDirty(!0),i._update()};i._sectionPlanes.push(e),e.on("pos",t),e.on("dir",t),e.on("active",t),e.once("destroyed",function(){var t=e.id;t&&(i._sectionPlanes=i._sectionPlanes.filter((function(e){return e.id!==t})),i._update())}.bind(i))};for(var n in this.scene.sectionPlanes)r(this.scene.sectionPlanes[n]);this._onSectionPlaneCreated=this.scene.on("sectionPlaneCreated",r),this._onTick=this.scene.on("tick",(function(){var e=!1;for(var t in i._sceneModelsData)i.scene.models[t]?i._sceneModelsData[t].visible!==!!i.scene.models[t].visible&&(i._sceneModelsData[t].visible=!!i.scene.models[t].visible,e=!0):(delete i._sceneModelsData[t],e=!0);e&&i._update()}))}this._dirtyMap[t]||(this._dirtyMap[t]=new Map),this._dirtyMap[t].set(e,!0),this._update()}},{key:"_update",value:function(){var e=this;clearTimeout(this._updateTimeout),this._deletePreviousModels(),this._updateTimeout=setTimeout((function(){clearTimeout(e._updateTimeout);var t=Object.values(e.scene.models).filter((function(e){return e.visible}));e._addHatches(t,e._sectionPlanes.filter((function(e){return e.active}))),e._setAllDirty(!1)}),100)}},{key:"_setAllDirty",value:function(e){var t=this,i=function(i){t._dirtyMap[i].forEach((function(r,n){return t._dirtyMap[i].set(n,e)}))};for(var r in this._dirty)i(r)}},{key:"_addHatches",value:function(e,t){var i=this;t.forEach((function(t){e.forEach((function(e){if(i._doesPlaneIntersectBoundingBox(e.aabb,t)&&i._dirtyMap[e.id]){var r=new Map,n=e.objects,s=[le.vec3(),le.vec3(),le.vec3()];i._dirtyMap[e.id].forEach((function(o,a){if(o){var l=n[a];if(i._doesPlaneIntersectBoundingBox(l.aabb,t)){if(!i._sceneModelsData[e.id]){var u=e.aabb;i._sceneModelsData[e.id]={verticesMap:new Map,indicesMap:new Map,modelOrigin:le.vec3([(u[0]+u[3])/2,(u[1]+u[4])/2,(u[2]+u[5])/2])}}var c=i._sceneModelsData[e.id],A=c.modelOrigin;if(!c.verticesMap.has(a)){var h=l.meshes[0].isSolid(),d=[],p=[];h&&l.capMaterial&&(l.getEachVertex((function(e){return d.push(e[0]-A[0],e[1]-A[1],e[2]-A[2])})),l.getEachIndex((function(e){return p.push(e)}))),c.verticesMap.set(a,d),c.indicesMap.set(a,p)}for(var f=c.verticesMap.get(a),v=c.indicesMap.get(a),g=-le.dotVec3(le.subVec3(t.pos,A,Hd),t.dir),m=[],_=v.length,y=0;y<_;y+=3){for(var b=0;b<3;b++){var w=3*v[y+b];s[b][0]=f[w],s[b][1]=f[w+1],s[b][2]=f[w+2]}if(s[0][0]||s[0][1]||s[0][2]){for(var B=[],x=0;x<3;x++){var P=s[x],C=s[(x+1)%3],M=g+le.dotVec3(t.dir,P),k=g+le.dotVec3(t.dir,C);if(!(M*k>0)){var E=-M/(k-M);B.push(le.lerpVec3(E,0,1,P,C,le.vec3()))}}2===B.length&&m.push(B)}}m.length>0&&r.set(a,m)}}}));var o=new Map;r.forEach((function(e,t){o.set(t,[[e[0]]]),e.splice(0,1);for(var i=0;e.length>0;){for(var n=o.get(t)[i][o.get(t)[i].length-1][1],s=!1,a=0;a<e.length;a++){var l=C(e[a],2),u=l[0],c=l[1];if(Xd(n,u)){o.get(t)[i].push(e[a]),e.splice(a,1),s=!0;break}if(Xd(n,c)){o.get(t)[i].push([c,u]),e.splice(a,1),s=!0;break}}if(!s&&Xd(n,o.get(t)[i][0][0])&&e.length>1)o.get(t).push([r.get(t)[0]]),e.splice(0,1),i++;else if(!s)break}}));var a=new Map;o.forEach((function(e,r){for(var n=[],s=function(r){n.push([]),e[r].forEach((function(e){n[r].push([i._projectTo2D(e[0],t.dir),i._projectTo2D(e[1],t.dir)])}))},o=0;o<e.length;o++)s(o);a.set(r,n)}));var l,u=new Map;a.forEach((function(r,n){var s=i._sceneModelsData[e.id].modelOrigin;l=[];for(var o=r,a=[],c=new Set,A=0;A<o.length;A++)if(!c.has(A)){var h=[o[A]];c.add(A);for(var d=A+1;d<o.length;d++)c.has(d)||(i._isLoopInside(o[A],o[d])||i._isLoopInside(o[d],o[A]))&&(h.push(o[d]),c.add(d));a.push(h)}a.forEach((function(e){var r=[],n=[],o=0,a=e.map((function(e){for(var t=0,i=0;i<e.length;i++){var r=(i+1)%e.length;t+=e[i][0][0]*e[r][0][1],t-=e[r][0][0]*e[i][0][1]}return Math.abs(t)/2})),u=a.indexOf(Math.max.apply(Math,f(a)));e[u].forEach((function(e){r.push(e[0][0],e[0][1]),o+=2}));for(var c=0;c<e.length;c++)c!==u&&(n.push(o/2),e[c].forEach((function(e){r.push(e[0][0],e[0][1]),o+=2})));for(var A=dd(r,n),h=[],d=0;d<A.length;d+=3){for(var p=[],v=0;v<3;v++){var g=2*A[d+v],m=[r[g],r[g+1]],_=i._convertTo3D(m,t,s);p.push(_)}h.push(p)}l.push(h)})),u.set(n,l)}));var c=new Map;u.forEach((function(e,t){l=[],e.forEach((function(e){var t=new Map,i=[],r=[],n=0;e.forEach((function(e){var s=[];e.forEach((function(e){var r="".concat(e[0].toFixed(6),",").concat(e[1].toFixed(6),",").concat(e[2].toFixed(6));t.has(r)?s.push(t.get(r)):(i.push(e[0],e[1],e[2]),t.set(r,n),s.push(n),n++)})),r.push.apply(r,s)})),l.push({positions:i,indices:r})})),c.set(t,l)})),i._prevIntersectionModelsMap[e.id]||(i._prevIntersectionModelsMap[e.id]=new Map),le.mulVec3Scalar(t.dir,.001,Wd),c.forEach((function(r,n){var s,o=i._sceneModelsData[e.id].modelOrigin,a=new Array(r.size),l=0;(r.forEach((function(r,s){var u=r.positions,c=r.indices;u.length;var A=le.buildNormals(u,c),h=i._createUVs(u,t,o);a[l++]=new vn(i.scene,{id:"".concat(t.id,"-").concat(n,"-").concat(s),geometry:new mt(i.scene,{primitive:"triangles",positions:u,indices:c,normals:A,uv:h}),origin:le.addVec3(o,Wd,Hd),position:[0,0,0],rotation:[0,0,0],material:e.objects[n].capMaterial})})),i._prevIntersectionModelsMap[e.id].has(n))?(s=i._prevIntersectionModelsMap[e.id].get(n)).push.apply(s,a):i._prevIntersectionModelsMap[e.id].set(n,a)}))}}))}))}},{key:"_doesPlaneIntersectBoundingBox",value:function(e,t){for(var i=[e[0],e[1],e[2]],r=[e[3],e[4],e[5]],n=!1,s=!1,o=0,a=[[i[0],i[1],i[2]],[r[0],i[1],i[2]],[i[0],r[1],i[2]],[r[0],r[1],i[2]],[i[0],i[1],r[2]],[r[0],i[1],r[2]],[i[0],r[1],r[2]],[r[0],r[1],r[2]]];o<a.length;o++){var l=a[o],u=t.dist+le.dotVec3(t.dir,l);if(u>0&&(n=!0),u<0&&(s=!0),n&&s)return!0}return!1}},{key:"_buildLines",value:function(e){var t=this;for(var i in e)for(var r=0;r<e[i].length;r++){var n=e[i][r];n.length<=0||n.forEach((function(e,i){new vn(t.scene,{clippable:!1,geometry:new mt(t.scene,Lt({startPoint:e[0],endPoint:e[1]})),material:new bn(t.scene,{emissive:[1,0,0]})})}))}}},{key:"_projectTo2D",value:function(e,t){var i;i=Math.abs(t[0])>Math.abs(t[1])?[-t[2],0,t[0]]:[0,t[2],-t[1]],i=le.normalizeVec3(i);var r=le.vec3(t),n=le.cross3Vec3(r,i),s=le.normalizeVec3(n);return[le.dotVec3(e,i),le.dotVec3(e,s)]}},{key:"_isLoopInside",value:function(e,t){for(var i=e[0][0],r=!1,n=0,s=t.length-1;n<t.length;s=n++){var o=t[n][0][0],a=t[n][0][1],l=t[s][0][0],u=t[s][0][1];a>i[1]!=u>i[1]&&i[0]<(l-o)*(i[1]-a)/(u-a)+o&&(r=!r)}return r}},{key:"_convertTo3D",value:function(e,t,i){var r,n=t.dir,s=t.pos;r=Math.abs(n[0])>Math.abs(n[1])?[-n[2],0,n[0]]:[0,n[2],-n[1]],r=le.normalizeVec3(r);var o=le.vec3(n),a=le.cross3Vec3(o,r),l=le.normalizeVec3(a),u=e[0],c=e[1],A=[r[0]*u+l[0]*c,r[1]*u+l[1]*c,r[2]*u+l[2]*c],h=le.dotVec3(n,[s[0]-A[0]-i[0],s[1]-A[1]-i[1],s[2]-A[2]-i[2]]);return[A[0]+n[0]*h,A[1]+n[1]*h,A[2]+n[2]*h]}},{key:"_deletePreviousModels",value:function(){var e=this,t=function(t){e._prevIntersectionModelsMap[t].forEach((function(i,r){e._dirtyMap[t].get(r)&&(i.forEach((function(e){e.destroy()})),e._prevIntersectionModelsMap[t].delete(r))})),e._prevIntersectionModelsMap[t].size<=0&&delete e._prevIntersectionModelsMap[t]};for(var i in this._prevIntersectionModelsMap)t(i)}},{key:"_createUVs",value:function(e,t,i){var r=t.pos,n=Hd;n.set(t.dir),le.normalizeVec3(n);for(var s=jd,o=[],a=0;a<e.length;a+=3){s[0]=e[a]+i[0],s[1]=e[a+1]+i[1],s[2]=e[a+2]+i[2];var l=le.subVec3(s,r,Gd),u=le.dotVec3(l,n);le.subVec3(s,le.mulVec3Scalar(n,u,Gd),s);var c=Math.abs(le.dotVec3(n,Vd))<.999?le.cross3Vec3(n,Vd,Gd):Qd,A=le.cross3Vec3(n,c,Gd);le.normalizeVec3(A,A);var h=le.subVec3(s,r,s);o.push(le.dotVec3(h,le.normalizeVec3(le.cross3Vec3(A,n,zd))),le.dotVec3(h,A))}return o}},{key:"destroy",value:function(){this._deletePreviousModels(),this._resourcesAllocated&&(this.scene.off(this._onModelLoaded),this.scene.off(this._onModelUnloaded),this.scene.off(this._onSectionPlaneCreated),this.scene.off(this._onTick))}}]),e}();function Zd(e,t){for(var i,r,n={},s=0,o=t.length;s<o;s++)i=t[s],(r=e.components[i])?r.isEntity?n[i]=!0:e.warn("pick(): Component is not an Entity: "+i):e.warn("pick(): Component not found: "+i);return n}var Jd=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E(this,i),r=t.call(this,null,n);var s=n.canvasElement||document.querySelector("#".concat(n.canvasId));if(!(s instanceof HTMLCanvasElement))throw"Mandatory config expected: valid canvasId or canvasElement";r._tickifiedFunctions={};var o=!!n.transparent,a=!!n.alphaDepthMask;return r._aabbDirty=!0,r._readableGeometry=!!n.readableGeometryEnabled,r.viewer=e,r.occlusionTestCountdown=0,r.loading=0,r.startTime=(new Date).getTime(),r.models={},r.objects={},r._numObjects=0,r.visibleObjects={},r._numVisibleObjects=0,r.xrayedObjects={},r._numXRayedObjects=0,r.highlightedObjects={},r._numHighlightedObjects=0,r.selectedObjects={},r._numSelectedObjects=0,r.colorizedObjects={},r._numColorizedObjects=0,r.opacityObjects={},r._numOpacityObjects=0,r.offsetObjects={},r._numOffsetObjects=0,r._modelIds=null,r._objectIds=null,r._visibleObjectIds=null,r._xrayedObjectIds=null,r._highlightedObjectIds=null,r._selectedObjectIds=null,r._colorizedObjectIds=null,r._opacityObjectIds=null,r._offsetObjectIds=null,r._collidables={},r._compilables={},r._needRecompile=!1,r.types={},r.components={},r.sectionPlanes={},r.lights={},r.lightMaps={},r.reflectionMaps={},r.bitmaps={},r.lineSets={},r.realWorldOffset=n.realWorldOffset||new Float64Array([0,0,0]),r.canvas=new _h(w(r),{dontClear:!0,canvas:s,spinnerElementId:n.spinnerElementId,transparent:o,webgl2:!1!==n.webgl2,contextAttr:n.contextAttr||{},backgroundColor:n.backgroundColor,backgroundColorFromAmbientLight:n.backgroundColorFromAmbientLight,premultipliedAlpha:n.premultipliedAlpha}),r.canvas.on("boundary",(function(){r.glRedraw()})),r.canvas.on("webglContextFailed",(function(){alert("xeokit failed to find WebGL!")})),r._renderer=new Uh(w(r),{transparent:o,alphaDepthMask:a}),r._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;var e=null;this.getHash=function(){if(e)return e;var t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";for(var i=[],r=0,n=t;r<n;r++)i.push("cp");return i.push(";"),e=i.join("")},this.addSectionPlane=function(t){this.sectionPlanes.push(t),e=null},this.removeSectionPlane=function(t){for(var i=0,r=this.sectionPlanes.length;i<r;i++)if(this.sectionPlanes[i].id===t.id)return this.sectionPlanes.splice(i,1),void(e=null)},this.setNumCachedSectionPlanes=function(t){this._numCachedSectionPlanes=t,e=null},this.getNumCachedSectionPlanes=function(){return this._numCachedSectionPlanes},this.getNumAllocatedSectionPlanes=function(){var e=this.sectionPlanes.length;return e>this._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},r._sectionPlanesState.setNumCachedSectionPlanes(n.numCachedSectionPlanes||0),r._lightsState=new function(){var e=le.vec4([0,0,0,0]),t=le.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];var i=null,r=null;this.getHash=function(){if(i)return i;for(var e,t=[],r=this.lights,n=0,s=r.length;n<s;n++)e=r[n],t.push("/"),t.push(e.type),t.push("world"===e.space?"w":"v"),e.castsShadow&&t.push("sh");return this.lightMaps.length>0&&t.push("/lm"),this.reflectionMaps.length>0&&t.push("/rm"),t.push(";"),i=t.join("")},this.addLight=function(e){this.lights.push(e),r=null,i=null},this.removeLight=function(e){for(var t=0,n=this.lights.length;t<n;t++){if(this.lights[t].id===e.id)return this.lights.splice(t,1),r&&r.id===e.id&&(r=null),void(i=null)}},this.addReflectionMap=function(e){this.reflectionMaps.push(e),i=null},this.removeReflectionMap=function(e){for(var t=0,r=this.reflectionMaps.length;t<r;t++)if(this.reflectionMaps[t].id===e.id)return this.reflectionMaps.splice(t,1),void(i=null)},this.addLightMap=function(e){this.lightMaps.push(e),i=null},this.removeLightMap=function(e){for(var t=0,r=this.lightMaps.length;t<r;t++)if(this.lightMaps[t].id===e.id)return this.lightMaps.splice(t,1),void(i=null)},this.getAmbientColorAndIntensity=function(){if(!r)for(var i=0,n=this.lights.length;i<n;i++){var s=this.lights[i];if("ambient"===s.type){r=s;break}}if(r){var o=r.color,a=r.intensity;return t[0]=o[0],t[1]=o[1],t[2]=o[2],t[3]=a,t}return e}},r.input=new Lh(w(r),{dontClear:!0,element:r.canvas.canvas,keyboardEventsElement:n.keyboardEventsElement}),r.metrics=new od(w(r),{units:n.units,scale:n.scale,origin:n.origin}),r.sao=new ad(w(r),{enabled:n.saoEnabled}),r.crossSections=new ld(w(r),{}),r.ticksPerRender=n.ticksPerRender,r.ticksPerOcclusionTest=n.ticksPerOcclusionTest,r.passes=n.passes,r.clearEachPass=n.clearEachPass,r.gammaInput=n.gammaInput,r.gammaOutput=n.gammaOutput,r.gammaFactor=n.gammaFactor,r._entityOffsetsEnabled=!!n.entityOffsetsEnabled,r._logarithmicDepthBufferEnabled=!!n.logarithmicDepthBufferEnabled,r._dtxEnabled=!1!==n.dtxEnabled,r._pbrEnabled=!!n.pbrEnabled,r._colorTextureEnabled=!1!==n.colorTextureEnabled,r._dtxEnabled=!!n.dtxEnabled,r._markerZOffset=n.markerZOffset,ke._addScene(w(r)),r._initDefaults(),r._viewport=new Oh(w(r),{id:"default.viewport",autoBoundary:!0,dontClear:!0}),r._camera=new nd(w(r),{id:"default.camera",dontClear:!0}),r._sectionCaps=new Kd(w(r)),new OA(w(r),{color:[1,1,1],intensity:.7}),new VA(w(r),{dir:[.8,-.5,-.5],color:[.67,.67,1],intensity:.7,space:"world"}),new VA(w(r),{dir:[-.8,-1,.5],color:[1,1,.9],intensity:.9,space:"world"}),r._camera.on("dirty",(function(){r._renderer.imageDirty()})),r}return I(i,[{key:"type",get:function(){return"Scene"}},{key:"_initDefaults",value:function(){}},{key:"_addComponent",value:function(e){if(e.id&&this.components[e.id]&&(this.error("Component "+ge.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=le.createUUID();this.components[e.id]=e;var t=e.type,i=this.types[e.type];i||(i=this.types[t]={}),i[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}},{key:"_removeComponent",value:function(e){var t=e.id,i=e.type;delete this.components[t];var r=this.types[i];r&&(delete r[t],ge.isEmptyObject(r)&&delete this.types[i]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}},{key:"_capMaterialUpdated",value:function(e,t){this._sectionCaps._onCapMaterialUpdated(e,t)}},{key:"_sectionPlaneCreated",value:function(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}},{key:"_bitmapCreated",value:function(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}},{key:"_lineSetCreated",value:function(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}},{key:"_lightCreated",value:function(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}},{key:"_lightMapCreated",value:function(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}},{key:"_reflectionMapCreated",value:function(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}},{key:"_sectionPlaneDestroyed",value:function(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}},{key:"_bitmapDestroyed",value:function(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}},{key:"_lineSetDestroyed",value:function(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}},{key:"_lightDestroyed",value:function(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}},{key:"_lightMapDestroyed",value:function(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}},{key:"_reflectionMapDestroyed",value:function(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}},{key:"_registerModel",value:function(e){this.models[e.id]=e,this._modelIds=null}},{key:"_deregisterModel",value:function(e){var t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}},{key:"_registerObject",value:function(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}},{key:"_deregisterObject",value:function(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}},{key:"_objectVisibilityUpdated",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}},{key:"_deRegisterVisibleObject",value:function(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}},{key:"_objectXRayedUpdated",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}},{key:"_deRegisterXRayedObject",value:function(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}},{key:"_objectHighlightedUpdated",value:function(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}},{key:"_deRegisterHighlightedObject",value:function(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}},{key:"_objectSelectedUpdated",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}},{key:"_deRegisterSelectedObject",value:function(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}},{key:"_objectColorizeUpdated",value:function(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}},{key:"_deRegisterColorizedObject",value:function(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}},{key:"_objectOpacityUpdated",value:function(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}},{key:"_deRegisterOpacityObject",value:function(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}},{key:"_objectOffsetUpdated",value:function(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}},{key:"_deRegisterOffsetObject",value:function(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}},{key:"_webglContextLost",value:function(){for(var e in this.canvas.spinner.processes++,this.components)if(this.components.hasOwnProperty(e)){var t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}},{key:"_webglContextRestored",value:function(){var e=this.canvas.gl;for(var t in this.components)if(this.components.hasOwnProperty(t)){var i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}},{key:"capabilities",get:function(){return this._renderer.capabilities}},{key:"entityOffsetsEnabled",get:function(){return this._entityOffsetsEnabled}},{key:"readableGeometryEnabled",get:function(){return this._readableGeometry}},{key:"pickSurfacePrecisionEnabled",get:function(){return this._readableGeometry}},{key:"logarithmicDepthBufferEnabled",get:function(){return this._logarithmicDepthBufferEnabled}},{key:"numCachedSectionPlanes",get:function(){return this._sectionPlanesState.getNumCachedSectionPlanes()},set:function(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}},{key:"pbrEnabled",get:function(){return this._pbrEnabled},set:function(e){this._pbrEnabled=!!e,this.glRedraw()}},{key:"dtxEnabled",get:function(){return this._dtxEnabled},set:function(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}},{key:"colorTextureEnabled",get:function(){return this._colorTextureEnabled},set:function(e){this._colorTextureEnabled=!!e,this.glRedraw()}},{key:"markerZOffset",get:function(){return null==this._markerZOffset?-.001:this._markerZOffset}},{key:"doOcclusionTest",value:function(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}},{key:"render",value:function(e){e&&ke.runTasks();var t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),e||this._renderer.needsRender()){t.sceneId=this.id;var i,r,n=this._passes,s=this._clearEachPass;for(i=0;i<n;i++)t.pass=i,this.fire("rendering",t,!0),r=s||0===i,this._renderer.render({pass:i,clear:r,force:e}),this.fire("rendered",t,!0);this._saveAmbientColor()}}},{key:"compile",value:function(){this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1)}},{key:"_recompile",value:function(){for(var e in this._compilables)this._compilables.hasOwnProperty(e)&&this._compilables[e].compile();this._renderer.shadowsDirty(),this.fire("compile",this,!0)}},{key:"_saveAmbientColor",value:function(){var e=this.canvas;if(e.transparent||e.backgroundImage||e.backgroundColor)this._lastAmbientColor=null;else{var t=this._lightsState.getAmbientColorAndIntensity();this._lastAmbientColor&&this._lastAmbientColor[0]===t[0]&&this._lastAmbientColor[1]===t[1]&&this._lastAmbientColor[2]===t[2]&&this._lastAmbientColor[3]===t[3]||(e.backgroundColor=t,this._lastAmbientColor||(this._lastAmbientColor=le.vec4([0,0,0,1])),this._lastAmbientColor.set(t))}}},{key:"modelIds",get:function(){return this._modelIds||(this._modelIds=Object.keys(this.models)),this._modelIds}},{key:"numObjects",get:function(){return this._numObjects}},{key:"objectIds",get:function(){return this._objectIds||(this._objectIds=Object.keys(this.objects)),this._objectIds}},{key:"numVisibleObjects",get:function(){return this._numVisibleObjects}},{key:"visibleObjectIds",get:function(){return this._visibleObjectIds||(this._visibleObjectIds=Object.keys(this.visibleObjects)),this._visibleObjectIds}},{key:"numXRayedObjects",get:function(){return this._numXRayedObjects}},{key:"xrayedObjectIds",get:function(){return this._xrayedObjectIds||(this._xrayedObjectIds=Object.keys(this.xrayedObjects)),this._xrayedObjectIds}},{key:"numHighlightedObjects",get:function(){return this._numHighlightedObjects}},{key:"highlightedObjectIds",get:function(){return this._highlightedObjectIds||(this._highlightedObjectIds=Object.keys(this.highlightedObjects)),this._highlightedObjectIds}},{key:"numSelectedObjects",get:function(){return this._numSelectedObjects}},{key:"selectedObjectIds",get:function(){return this._selectedObjectIds||(this._selectedObjectIds=Object.keys(this.selectedObjects)),this._selectedObjectIds}},{key:"numColorizedObjects",get:function(){return this._numColorizedObjects}},{key:"colorizedObjectIds",get:function(){return this._colorizedObjectIds||(this._colorizedObjectIds=Object.keys(this.colorizedObjects)),this._colorizedObjectIds}},{key:"opacityObjectIds",get:function(){return this._opacityObjectIds||(this._opacityObjectIds=Object.keys(this.opacityObjects)),this._opacityObjectIds}},{key:"offsetObjectIds",get:function(){return this._offsetObjectIds||(this._offsetObjectIds=Object.keys(this.offsetObjects)),this._offsetObjectIds}},{key:"ticksPerRender",get:function(){return this._ticksPerRender},set:function(e){null==e?e=1:(!ge.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerRender': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._ticksPerRender&&(this._ticksPerRender=e)}},{key:"ticksPerOcclusionTest",get:function(){return this._ticksPerOcclusionTest},set:function(e){null==e?e=20:(!ge.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerOcclusionTest': '"+e+"' - should be an integer greater than zero."),e=20),e!==this._ticksPerOcclusionTest&&(this._ticksPerOcclusionTest=e)}},{key:"passes",get:function(){return this._passes},set:function(e){null==e?e=1:(!ge.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'passes': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._passes&&(this._passes=e,this.glRedraw())}},{key:"clearEachPass",get:function(){return this._clearEachPass},set:function(e){(e=!!e)!==this._clearEachPass&&(this._clearEachPass=e,this.glRedraw())}},{key:"gammaInput",get:function(){return this._renderer.gammaInput},set:function(e){(e=!1!==e)!==this._renderer.gammaInput&&(this._renderer.gammaInput=e,this._needRecompile=!0,this.glRedraw())}},{key:"gammaOutput",get:function(){return this._renderer.gammaOutput},set:function(e){(e=!!e)!==this._renderer.gammaOutput&&(this._renderer.gammaOutput=e,this._needRecompile=!0,this.glRedraw())}},{key:"gammaFactor",get:function(){return this._renderer.gammaFactor},set:function(e){(e=null==e?2.2:e)!==this._renderer.gammaFactor&&(this._renderer.gammaFactor=e,this.glRedraw())}},{key:"geometry",get:function(){return this.components["default.geometry"]||Pt(mt)}},{key:"material",get:function(){return this.components["default.material"]||new bn(this,{id:"default.material",emissive:[.4,.4,.4],dontClear:!0})}},{key:"xrayMaterial",get:function(){return this.components["default.xrayMaterial"]||new zn(this,{id:"default.xrayMaterial",fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1,dontClear:!0})}},{key:"highlightMaterial",get:function(){return this.components["default.highlightMaterial"]||new zn(this,{id:"default.highlightMaterial",fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1,dontClear:!0})}},{key:"selectedMaterial",get:function(){return this.components["default.selectedMaterial"]||new zn(this,{id:"default.selectedMaterial",fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1,dontClear:!0})}},{key:"edgeMaterial",get:function(){return this.components["default.edgeMaterial"]||new Xn(this,{id:"default.edgeMaterial",fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1,dontClear:!0})}},{key:"pointsMaterial",get:function(){return this.components["default.pointsMaterial"]||new cd(this,{id:"default.pointsMaterial",fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1,dontClear:!0})}},{key:"linesMaterial",get:function(){return this.components["default.linesMaterial"]||new hd(this,{id:"default.linesMaterial",fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1,dontClear:!0})}},{key:"viewport",get:function(){return this._viewport}},{key:"camera",get:function(){return this._camera}},{key:"center",get:function(){if(this._aabbDirty||!this._center){var e=this.aabb;this._center||(this._center=le.vec3()),this._center[0]=(e[0]+e[3])/2,this._center[1]=(e[1]+e[4])/2,this._center[2]=(e[2]+e[5])/2}return this._center}},{key:"aabb",get:function(){if(this._aabbDirty){this._aabb||(this._aabb=le.AABB3());var e,t,i=le.MAX_DOUBLE,r=le.MAX_DOUBLE,n=le.MAX_DOUBLE,s=le.MIN_DOUBLE,o=le.MIN_DOUBLE,a=le.MIN_DOUBLE,l=this._collidables,u=!1;for(var c in l)if(l.hasOwnProperty(c)){if(!1===(t=l[c]).collidable)continue;(e=t.aabb)[0]<i&&(i=e[0]),e[1]<r&&(r=e[1]),e[2]<n&&(n=e[2]),e[3]>s&&(s=e[3]),e[4]>o&&(o=e[4]),e[5]>a&&(a=e[5]),u=!0}u||(i=-100,r=-100,n=-100,s=100,o=100,a=100),this._aabb[0]=i,this._aabb[1]=r,this._aabb[2]=n,this._aabb[3]=s,this._aabb[4]=o,this._aabb[5]=a,this._aabbDirty=!1,this._center=null}return this._aabb}},{key:"_setAABBDirty",value:function(){this._aabbDirty=!0,this.fire("boundary")}},{key:"pick",value:function(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");var i=e.includeEntities||e.include;i&&(e.includeEntityIds=Zd(this,i));var r=e.excludeEntities||e.exclude;return r&&(e.excludeEntityIds=Zd(this,r)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}},{key:"snapPick",value:function(e){if(void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),e.canvasPos)return this._renderer.snapPick(e);this.error("Scene.snapPick() canvasPos parameter expected")}},{key:"clear",value:function(){var e;for(var t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}},{key:"clearLights",value:function(){for(var e=Object.keys(this.lights),t=0,i=e.length;t<i;t++)this.lights[e[t]].destroy()}},{key:"clearSectionPlanes",value:function(){for(var e=Object.keys(this.sectionPlanes),t=0,i=e.length;t<i;t++)this.sectionPlanes[e[t]].destroy()}},{key:"clearBitmaps",value:function(){for(var e=Object.keys(this.bitmaps),t=0,i=e.length;t<i;t++)this.bitmaps[e[t]].destroy()}},{key:"clearLines",value:function(){for(var e=Object.keys(this.lineSets),t=0,i=e.length;t<i;t++)this.lineSets[e[t]].destroy()}},{key:"getAABB",value:function(e){if(void 0===e)return this.aabb;if(ge.isString(e)){var t=this.objects[e];if(t&&t.aabb)return t.aabb;e=[e]}if(0===e.length)return this.aabb;var i,r=le.MAX_DOUBLE,n=le.MAX_DOUBLE,s=le.MAX_DOUBLE,o=le.MIN_DOUBLE,a=le.MIN_DOUBLE,l=le.MIN_DOUBLE;if(this.withObjects(e,(function(e){if(e.collidable){var t=e.aabb;t[0]<r&&(r=t[0]),t[1]<n&&(n=t[1]),t[2]<s&&(s=t[2]),t[3]>o&&(o=t[3]),t[4]>a&&(a=t[4]),t[5]>l&&(l=t[5]),i=!0}})),i){var u=le.AABB3();return u[0]=r,u[1]=n,u[2]=s,u[3]=o,u[4]=a,u[5]=l,u}return this.aabb}},{key:"setObjectsVisible",value:function(e,t){return this.withObjects(e,(function(e){var i=e.visible!==t;return e.visible=t,i}))}},{key:"setObjectsCollidable",value:function(e,t){return this.withObjects(e,(function(e){var i=e.collidable!==t;return e.collidable=t,i}))}},{key:"setObjectsCulled",value:function(e,t){return this.withObjects(e,(function(e){var i=e.culled!==t;return e.culled=t,i}))}},{key:"setObjectsSelected",value:function(e,t){return this.withObjects(e,(function(e){var i=e.selected!==t;return e.selected=t,i}))}},{key:"setObjectsHighlighted",value:function(e,t){return this.withObjects(e,(function(e){var i=e.highlighted!==t;return e.highlighted=t,i}))}},{key:"setObjectsXRayed",value:function(e,t){return this.withObjects(e,(function(e){var i=e.xrayed!==t;return e.xrayed=t,i}))}},{key:"setObjectsEdges",value:function(e,t){return this.withObjects(e,(function(e){var i=e.edges!==t;return e.edges=t,i}))}},{key:"setObjectsColorized",value:function(e,t){return this.withObjects(e,(function(e){e.colorize=t}))}},{key:"setObjectsOpacity",value:function(e,t){return this.withObjects(e,(function(e){var i=e.opacity!==t;return e.opacity=t,i}))}},{key:"setObjectsPickable",value:function(e,t){return this.withObjects(e,(function(e){var i=e.pickable!==t;return e.pickable=t,i}))}},{key:"setObjectsOffset",value:function(e,t){this.withObjects(e,(function(e){e.offset=t}))}},{key:"withObjects",value:function(e,t){ge.isString(e)&&(e=[e]);for(var i=!1,r=0,n=e.length;r<n;r++){var s=e[r],o=this.objects[s];if(o)i=t(o)||i;else for(var a=this.modelIds,l=0,u=a.length;l<u;l++){var c=a[l],A=le.globalizeObjectId(c,s);(o=this.objects[A])&&(i=t(o)||i)}}return i}},{key:"tickify",value:function(e){var t=e.toString();if(t in this._tickifiedFunctions)return this._tickifiedFunctions[t].wrapperFunc;var i,r=0,n=0,s=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];i=t,n++},o=this.on("tick",(function(){n>r&&(r=n,e.apply(void 0,f(i)))}));return this._tickifiedFunctions[t]={tickSubId:o,wrapperFunc:s},s}},{key:"destroy",value:function(){for(var e in v(x(i.prototype),"destroy",this).call(this),this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this._sectionCaps.destroy(),this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this._sectionCaps=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}]),i}(),Yd=le.vec4(),qd=le.vec4(),$d=le.vec3(),ep=le.vec3(),tp=le.vec3(),ip=le.vec4(),rp=le.vec4(),np=le.vec4(),sp=function(){function e(t){E(this,e),this._scene=t}return I(e,[{key:"dollyToCanvasPos",value:function(e,t,i){var r=!1,n=this._scene.camera;if(e){var s=le.subVec3(e,n.eye,$d);r=le.lenVec3(s)<i}if("perspective"===n.projection){n.ortho.scale=n.ortho.scale-i;var o=this._unproject(t,ip),a=le.subVec3(o,n.eye,np),l=le.mulVec3Scalar(le.normalizeVec3(a),-i,[]);if(n.eye=[n.eye[0]-l[0],n.eye[1]-l[1],n.eye[2]-l[2]],n.look=[n.look[0]-l[0],n.look[1]-l[1],n.look[2]-l[2]],e){var u=le.subVec3(e,n.eye,$d),c=le.lenVec3(u),A=le.mulVec3Scalar(le.normalizeVec3(le.subVec3(n.look,n.eye,ep)),c);n.look=[n.eye[0]+A[0],n.eye[1]+A[1],n.eye[2]+A[2]]}}else if("ortho"===n.projection){var h=this._unproject(t,ip);n.ortho.scale=n.ortho.scale-i,n.ortho._update();var d=this._unproject(t,rp),p=le.subVec3(d,h,np),f=le.mulVec3Scalar(le.normalizeVec3(le.subVec3(n.look,n.eye,$d)),-i,ep),v=le.addVec3(p,f,tp);n.eye=[n.eye[0]-v[0],n.eye[1]-v[1],n.eye[2]-v[2]],n.look=[n.look[0]-v[0],n.look[1]-v[1],n.look[2]-v[2]]}return r}},{key:"_unproject",value:function(e,t){var i=this._scene.camera,r=i.project.transposedMatrix,n=r.subarray(8,12),s=r.subarray(12),o=[0,0,-1,1],a=le.dotVec4(o,n)/le.dotVec4(o,s);return i.project.unproject(e,a,Yd,qd,t),t}},{key:"destroy",value:function(){}}]),e}(),op=le.vec3(),ap=le.vec3(),lp=le.vec3(),up=le.vec4(),cp=le.vec4(),Ap=le.vec4(),hp=Math.PI-.001,dp=function(){function e(t,i){var r=this;E(this,e),this._scene=t,this._configs=i,this._pivotWorldPos=le.vec3(),this._cameraOffset=le.vec3(),this._azimuth=0,this._polar=0,this._radius=0,this._pivotPosSet=!1,this._pivoting=!1,this._shown=!1,this._pivotSphereEnabled=!1,this._pivotSphere=null,this._pivotSphereSize=1,this._pivotSphereGeometry=null,this._pivotSphereMaterial=null,this._rtcCenter=le.vec3(),this._rtcPos=le.vec3(),this._pivotViewPos=le.vec4(),this._pivotProjPos=le.vec4(),this._pivotCanvasPos=le.vec2(),this._cameraDirty=!0,this._onViewMatrix=this._scene.camera.on("viewMatrix",(function(){r._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(function(){r._cameraDirty=!0})),this._onTick=this._scene.on("tick",(function(){r.updatePivotElement(),r.updatePivotSphere()}))}return I(e,[{key:"createPivotSphere",value:function(){var e=this.getPivotPos(),t=le.vec3();le.decomposeMat4(le.inverseMat4(this._scene.viewer.camera.viewMatrix,le.mat4()),t,le.vec4(),le.vec3());var i=le.distVec3(t,e),r=Math.tan(Math.PI/500)*i*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(r/=this._scene.camera.ortho.scale/2),Yt(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new bt(this._scene,It({radius:r})),this._pivotSphere=new vn(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}},{key:"destroyPivotSphere",value:function(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}},{key:"updatePivotElement",value:function(){var e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){le.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,le.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);var i=t.boundary,r=i[2],n=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*r/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*n/2);var s=t._lastBoundingClientRect;if(!s||t._canvasSizeChanged){var o=t.canvas;s=t._lastBoundingClientRect=o.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(s.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(s.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}},{key:"updatePivotSphere",value:function(){this._pivoting&&this._pivotSphere&&(Yt(this.getPivotPos(),this._rtcCenter,this._rtcPos),le.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}},{key:"setPivotElement",value:function(e){this._pivotElement=e}},{key:"enablePivotSphere",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);var t=e.color||[1,0,0];this._pivotSphereMaterial=new bn(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}},{key:"disablePivotSphere",value:function(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}},{key:"startPivot",value:function(){var e=this._scene.camera,t=le.lookAtMat4v(e.eye,e.look,e.up);le.transformPoint3(t,this.getPivotPos(),this._cameraOffset);var i=this.getPivotPos();this._cameraOffset[2]+=le.distVec3(e.eye,i),t=le.inverseMat4(t);var r=le.transformVec3(t,this._cameraOffset),n=le.vec3();if(le.subVec3(e.eye,i,n),le.addVec3(n,r),e.zUp){var s=n[1];n[1]=n[2],n[2]=s}this._radius=le.lenVec3(n),this._polar=Math.acos(n[1]/this._radius),this._azimuth=Math.atan2(n[0],n[2]),this._pivoting=!0}},{key:"_cameraLookingDownwards",value:function(){var e=this._scene.camera,t=le.normalizeVec3(le.subVec3(e.look,e.eye,op)),i=le.cross3Vec3(t,e.worldUp,ap);return le.sqLenVec3(i)<=1e-4}},{key:"getPivoting",value:function(){return this._pivoting}},{key:"setPivotPos",value:function(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}},{key:"setCanvasPivotPos",value:function(e){var t=this._scene.camera,i=Math.abs(le.distVec3(this._scene.center,t.eye)),r=t.project.transposedMatrix,n=r.subarray(8,12),s=r.subarray(12),o=[0,0,-1,1],a=le.dotVec4(o,n)/le.dotVec4(o,s),l=up;t.project.unproject(e,a,cp,Ap,l);var u=le.normalizeVec3(le.subVec3(l,t.eye,op)),c=le.addVec3(t.eye,le.mulVec3Scalar(u,i,ap),lp);this.setPivotPos(c)}},{key:"getPivotPos",value:function(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}},{key:"continuePivot",value:function(e,t){if(this._pivoting&&(0!==e||0!==t)){var i=this._scene.camera,r=-e,n=-t;1===i.worldUp[2]&&(r=-r),this._azimuth+=.01*-r;var s=n<0,o=n>0,a=Math.abs(this._polar-.001)<.005,l=Math.abs(this._polar-hp)<.005,u=this._polar+.01*n;u=a&&s?.001:l&&o?hp:le.clamp(u,.001,hp),this._polar=u;var c=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){var A=c[1];c[1]=c[2],c[2]=A}var h=le.lenVec3(le.subVec3(i.look,i.eye,le.vec3())),d=this.getPivotPos();le.addVec3(c,d);var p=le.lookAtMat4v(c,d,i.worldUp);p=le.inverseMat4(p);var f=le.transformVec3(p,this._cameraOffset);p[12]-=f[0],p[13]-=f[1],p[14]-=f[2];var v=[p[8],p[9],p[10]];i.eye=[p[12],p[13],p[14]],le.subVec3(i.eye,le.mulVec3Scalar(v,h),i.look),i.up=[p[4],p[5],p[6]],this.showPivot()}}},{key:"showPivot",value:function(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}},{key:"hidePivot",value:function(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}},{key:"endPivot",value:function(){this._pivoting=!1}},{key:"destroy",value:function(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}]),e}(),pp=function(){function e(t,i){E(this,e),this._scene=t.scene,this._cameraControl=t,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=i,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=le.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}return I(e,[{key:"update",value:function(){if(this._configs.pointerEnabled&&(this.schedulePickEntity||this.schedulePickSurface)){var e="".concat(~~this.pickCursorPos[0],"-").concat(~~this.pickCursorPos[1],"-").concat(this.scheduleSnapOrPick,"-").concat(this.schedulePickSurface,"-").concat(this.schedulePickEntity);if(this._lastHash!==e){this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;var t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){var i=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});i&&(i.snappedToEdge||i.snappedToVertex)?(this.snapPickResult=i,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){var r=this.pickResult.canvasPos;if(r[0]===this.pickCursorPos[0]&&r[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){var n=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(n[0]===this.pickCursorPos[0]&&n[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}}}},{key:"fireEvents",value:function(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){var e=new ph;e.entity=this.snapPickResult.entity,e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){var t=this.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=t)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}]),e}(),fp=le.vec2(),vp=function(){function e(t,i,r,n,s){E(this,e),this._scene=t;var o,a,l,u=i.pickController,c=i.cameraControl,A=0,h=0,d=0,p=0,f=!1,v=le.vec3(),g=!0,m=this._scene.canvas.canvas,_=[];function y(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];b(),e&&w()}function b(){A=n.pointerCanvasPos[0],h=n.pointerCanvasPos[1],d=n.pointerCanvasPos[0],p=n.pointerCanvasPos[1]}function w(){u.pickCursorPos=n.pointerCanvasPos,u.schedulePickSurface=!0,u.update(),u.picked&&u.pickedSurface&&u.pickResult&&u.pickResult.worldPos?(f=!0,v.set(u.pickResult.worldPos)):f=!1}document.addEventListener("keydown",this._documentKeyDownHandler=function(e){if(r.active&&r.pointerEnabled&&t.input.keyboardEnabled){var i=e.keyCode;_[i]=!0}}),document.addEventListener("keyup",this._documentKeyUpHandler=function(e){if(r.active&&r.pointerEnabled&&t.input.keyboardEnabled){var i=e.keyCode;_[i]=!1}}),document.addEventListener("visibilitychange",this._onVisibilityChange=function(){_.splice(0)}),window.addEventListener("blur",this._onBlur=function(){_.splice(0)}),m.addEventListener("mousedown",this._mouseDownHandler=function(e){if(r.active&&r.pointerEnabled)switch(e.which){case 1:_[t.input.KEY_SHIFT]||r.planView?(o=!0,_[t.input.MOUSE_LEFT_BUTTON]=!0,y()):(o=!0,_[t.input.MOUSE_LEFT_BUTTON]=!0,y(!1));break;case 2:a=!0,_[t.input.MOUSE_MIDDLE_BUTTON]=!0,y();break;case 3:l=!0,_[t.input.MOUSE_RIGHT_BUTTON]=!0,r.panRightClick&&y()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=function(e){if(r.active&&r.pointerEnabled&&(o||a||l)){var i=t.canvas.boundary,u=i[2],d=i[3],p=n.pointerCanvasPos[0],g=n.pointerCanvasPos[1],m=r.planView||c._isKeyDownForAction(c.MOUSE_PAN,_),y=c._isKeyDownForAction(c.MOUSE_ROTATE,_),b=document.pointerLockElement?e.movementX:p-A,w=document.pointerLockElement?e.movementY:g-h;if(m){var B=t.camera;if("perspective"===B.projection){var x=Math.abs(f?le.lenVec3(le.subVec3(v,t.camera.eye,[])):t.camera.eyeLookDist)*Math.tan(B.perspective.fov/2*Math.PI/180);s.panDeltaX+=1.5*b*x/d,s.panDeltaY+=1.5*w*x/d}else s.panDeltaX+=.5*B.ortho.scale*(b/d),s.panDeltaY+=.5*B.ortho.scale*(w/d)}else y&&(r.planView||(r.firstPerson?(s.rotateDeltaY-=b/u*r.dragRotationRate/2,s.rotateDeltaX+=w/d*(r.dragRotationRate/4)):(s.rotateDeltaY-=b/u*(1.5*r.dragRotationRate),s.rotateDeltaX+=w/d*(1.5*r.dragRotationRate))));A=p,h=g}}),m.addEventListener("mousemove",this._canvasMouseMoveHandler=function(e){r.active&&r.pointerEnabled&&n.mouseover&&(g=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=function(e){if(r.active&&r.pointerEnabled)switch(e.which){case 1:case 2:case 3:o=!1,a=!1,l=!1,_[t.input.MOUSE_LEFT_BUTTON]=!1,_[t.input.MOUSE_MIDDLE_BUTTON]=!1,_[t.input.MOUSE_RIGHT_BUTTON]=!1}}),m.addEventListener("mouseup",this._mouseUpHandler=function(e){if(r.active&&r.pointerEnabled){if(3===e.which){!function(e,t){if(e){for(var i=e.target,r=0,n=0,s=0,o=0;i.offsetParent;)r+=i.offsetLeft,n+=i.offsetTop,s+=i.scrollLeft,o+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+s-r,t[1]=e.pageY+o-n}else e=window.event,t[0]=e.x,t[1]=e.y}(e,fp);var t=fp[0],n=fp[1];Math.abs(t-d)<3&&Math.abs(n-p)<3&&i.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:fp,event:e},!0)}m.style.removeProperty("cursor")}}),m.addEventListener("mouseenter",this._mouseEnterHandler=function(){r.active&&r.pointerEnabled});var B=1/60,x=null;m.addEventListener("wheel",this._mouseWheelHandler=function(e){if(r.active&&r.pointerEnabled&&r.zoomOnMouseWheel&&c._isKeyDownForAction(c.MOUSE_DOLLY,_)){var t=performance.now()/1e3,i=null!==x?t-x:0;x=t,i>.05&&(i=.05),i<B&&(i=B);var o=Math.max(-1,Math.min(1,40*-e.deltaY));if(0!==o){var a=o/Math.abs(o);s.dollyDelta+=-a*i*r.mouseWheelDollyRate,g&&(n.followPointerDirty=!0,g=!1)}}},{passive:!0})}return I(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;document.removeEventListener("keydown",this._documentKeyDownHandler),document.removeEventListener("keyup",this._documentKeyUpHandler),document.removeEventListener("visibilitychange",this._onVisibilityChange),window.removeEventListener("blur",this._onBlur),e.removeEventListener("mousedown",this._mouseDownHandler),document.removeEventListener("mousemove",this._documentMouseMoveHandler),e.removeEventListener("mousemove",this._canvasMouseMoveHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._mouseUpHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("wheel",this._mouseWheelHandler)}}]),e}(),gp=le.vec3(),mp=le.vec3(),_p=le.vec3(),yp=le.vec3(),bp=le.vec3(),wp={eye:le.vec3(),look:le.vec3(),up:le.vec3()},Bp=function(){function e(t,i,r,n){E(this,e),this._scene=t;var s=i.cameraControl,o=t.camera;this._onSceneKeyDown=t.input.on("keydown",(function(){if(r.active&&r.pointerEnabled&&t.input.keyboardEnabled&&(!r.keyboardEnabledOnlyIfMouseover||n.mouseover)){var e=s._isKeyDownForAction(s.AXIS_VIEW_RIGHT),a=s._isKeyDownForAction(s.AXIS_VIEW_BACK),l=s._isKeyDownForAction(s.AXIS_VIEW_LEFT),u=s._isKeyDownForAction(s.AXIS_VIEW_FRONT),c=s._isKeyDownForAction(s.AXIS_VIEW_TOP),A=s._isKeyDownForAction(s.AXIS_VIEW_BOTTOM);if(e||a||l||u||c||A){var h=t.aabb,d=le.getAABB3Diag(h);le.getAABB3Center(h,gp);var p=Math.abs(d/Math.tan(i.cameraFlight.fitFOV*le.DEGTORAD)),f=1.1*d;wp.orthoScale=f,e?(wp.eye.set(le.addVec3(gp,le.mulVec3Scalar(o.worldRight,p,mp),bp)),wp.look.set(gp),wp.up.set(o.worldUp)):a?(wp.eye.set(le.addVec3(gp,le.mulVec3Scalar(o.worldForward,p,mp),bp)),wp.look.set(gp),wp.up.set(o.worldUp)):l?(wp.eye.set(le.addVec3(gp,le.mulVec3Scalar(o.worldRight,-p,mp),bp)),wp.look.set(gp),wp.up.set(o.worldUp)):u?(wp.eye.set(le.addVec3(gp,le.mulVec3Scalar(o.worldForward,-p,mp),bp)),wp.look.set(gp),wp.up.set(o.worldUp)):c?(wp.eye.set(le.addVec3(gp,le.mulVec3Scalar(o.worldUp,p,mp),bp)),wp.look.set(gp),wp.up.set(le.normalizeVec3(le.mulVec3Scalar(o.worldForward,1,_p),yp))):A&&(wp.eye.set(le.addVec3(gp,le.mulVec3Scalar(o.worldUp,-p,mp),bp)),wp.look.set(gp),wp.up.set(le.normalizeVec3(le.mulVec3Scalar(o.worldForward,-1,_p)))),!r.firstPerson&&r.followPointer&&i.pivotController.setPivotPos(gp),i.cameraFlight.duration>0?i.cameraFlight.flyTo(wp,(function(){i.pivotController.getPivoting()&&r.followPointer&&i.pivotController.showPivot()})):(i.cameraFlight.jumpTo(wp),i.pivotController.getPivoting()&&r.followPointer&&i.pivotController.showPivot())}}}))}return I(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){this._scene.input.off(this._onSceneKeyDown)}}]),e}(),xp=function(){function e(t,i,r,n,s){var o=this;E(this,e),this._scene=t;var a=i.pickController,l=i.pivotController,u=i.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null,this._lastClickedWorldPos=null;var c=!1,A=!1,h=this._scene.canvas.canvas,d=function(e){var r;e&&e.worldPos&&(r=e.worldPos);var n=e&&e.entity?e.entity.aabb:t.aabb;if(r){var s=t.camera;le.subVec3(s.eye,s.look,[]),i.cameraFlight.flyTo({aabb:n})}else i.cameraFlight.flyTo({aabb:n})},p=t.tickify(this._canvasMouseMoveHandler=function(e){if(r.active&&r.pointerEnabled&&!c&&!A){if(u.hasSubs("rayMove")){var i=le.vec3(),s=le.vec3();le.canvasPosToWorldRay(t.canvas.canvas,t.camera.viewMatrix,t.camera.projMatrix,t.camera.projection,n.pointerCanvasPos,i,s),u.fire("rayMove",{canvasPos:n.pointerCanvasPos,ray:{origin:i,direction:s,canvasPos:n.pointerCanvasPos}},!0)}var l=u.hasSubs("hover"),h=u.hasSubs("hoverEnter"),d=u.hasSubs("hoverOut"),p=u.hasSubs("hoverOff"),f=u.hasSubs("hoverSurface"),v=u.hasSubs("hoverSnapOrSurface");if(l||h||d||p||f||v)if(a.pickCursorPos=n.pointerCanvasPos,a.schedulePickEntity=!0,a.schedulePickSurface=f,a.scheduleSnapOrPick=v,a.update(),a.pickResult){if(a.pickResult.entity){var g=a.pickResult.entity.id;o._lastPickedEntityId!==g&&(void 0!==o._lastPickedEntityId&&u.fire("hoverOut",{entity:t.objects[o._lastPickedEntityId]},!0),u.fire("hoverEnter",a.pickResult,!0),o._lastPickedEntityId=g)}u.fire("hover",a.pickResult,!0),(a.pickResult.worldPos||a.pickResult.snappedWorldPos)&&u.fire("hoverSurface",a.pickResult,!0)}else void 0!==o._lastPickedEntityId&&(u.fire("hoverOut",{entity:t.objects[o._lastPickedEntityId]},!0),o._lastPickedEntityId=void 0),u.fire("hoverOff",{canvasPos:a.pickCursorPos},!0)}});h.addEventListener("mousemove",p),h.addEventListener("mousedown",this._canvasMouseDownHandler=function(e){if(1===e.which&&(c=!0),3===e.which&&(A=!0),1===e.which&&r.active&&r.pointerEnabled&&(n.mouseDownClientX=e.clientX,n.mouseDownClientY=e.clientY,n.mouseDownCursorX=n.pointerCanvasPos[0],n.mouseDownCursorY=n.pointerCanvasPos[1],!r.firstPerson&&r.followPointer&&(a.pickCursorPos=n.pointerCanvasPos,a.schedulePickSurface=!0,a.update(),1===e.which))){var i=a.pickResult;i&&i.worldPos?(l.setPivotPos(i.worldPos),l.startPivot(),o._lastClickedWorldPos=i.worldPos.slice()):(r.smartPivot?l.setCanvasPivotPos(n.pointerCanvasPos):o._lastClickedWorldPos?l.setPivotPos(o._lastClickedWorldPos):l.setPivotPos(t.camera.look),l.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=function(e){1===e.which&&(c=!1),3===e.which&&(A=!1),l.getPivoting()&&l.endPivot()}),h.addEventListener("mouseup",this._canvasMouseUpHandler=function(e){if(r.active&&r.pointerEnabled&&(1===e.which&&(l.hidePivot(),!(Math.abs(e.clientX-n.mouseDownClientX)>3||Math.abs(e.clientY-n.mouseDownClientY)>3)))){var s=u.hasSubs("picked"),c=u.hasSubs("pickedNothing"),A=u.hasSubs("pickedSurface"),h=u.hasSubs("doublePicked"),p=u.hasSubs("doublePickedSurface"),f=u.hasSubs("doublePickedNothing");if(!(r.doublePickFlyTo||h||p||f))return(s||c||A)&&(a.pickCursorPos=n.pointerCanvasPos,a.schedulePickEntity=!0,a.schedulePickSurface=A,a.update(),a.pickResult?(u.fire("picked",a.pickResult,!0),a.pickedSurface&&u.fire("pickedSurface",a.pickResult,!0)):u.fire("pickedNothing",{canvasPos:n.pointerCanvasPos},!0)),void(o._clicks=0);if(o._clicks++,1===o._clicks){a.pickCursorPos=n.pointerCanvasPos,a.schedulePickEntity=r.doublePickFlyTo,a.schedulePickSurface=A,a.update();var v=a.pickResult,g=a.pickedSurface;o._timeout=setTimeout((function(){v?(u.fire("picked",v,!0),g&&(u.fire("pickedSurface",v,!0),!r.firstPerson&&r.followPointer&&(i.pivotController.setPivotPos(v.worldPos),i.pivotController.startPivot()&&i.pivotController.showPivot()))):u.fire("pickedNothing",{canvasPos:n.pointerCanvasPos},!0),o._clicks=0}),r.doubleClickTimeFrame)}else{if(null!==o._timeout&&(window.clearTimeout(o._timeout),o._timeout=null),a.pickCursorPos=n.pointerCanvasPos,a.schedulePickEntity=r.doublePickFlyTo||h||p,a.schedulePickSurface=a.schedulePickEntity&&p,a.update(),a.pickResult){if(u.fire("doublePicked",a.pickResult,!0),a.pickedSurface&&u.fire("doublePickedSurface",a.pickResult,!0),r.doublePickFlyTo&&(d(a.pickResult),!r.firstPerson&&r.followPointer)){var m=a.pickResult.entity.aabb,_=le.getAABB3Center(m);i.pivotController.setPivotPos(_),i.pivotController.startPivot()&&i.pivotController.showPivot()}}else if(u.fire("doublePickedNothing",{canvasPos:n.pointerCanvasPos},!0),r.doublePickFlyTo&&(d(),!r.firstPerson&&r.followPointer)){var y=t.aabb,b=le.getAABB3Center(y);i.pivotController.setPivotPos(b),i.pivotController.startPivot()&&i.pivotController.showPivot()}o._clicks=0}}},!1)}return I(e,[{key:"reset",value:function(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}]),e}(),Pp=function(){function e(t,i,r,n,s){E(this,e),this._scene=t;var o=t.input,a=[];t.canvas.canvas;var l=!0;this._onSceneMouseMove=o.on("mousemove",(function(){l=!0})),this._onSceneKeyDown=o.on("keydown",(function(e){r.active&&r.pointerEnabled&&t.input.keyboardEnabled&&(r.keyboardEnabledOnlyIfMouseover&&!n.mouseover||(a[e]=!0))})),this._onSceneKeyUp=o.on("keyup",(function(e){r.active&&r.pointerEnabled&&t.input.keyboardEnabled&&(a[e]=!1,i.pivotController.getPivoting()&&i.pivotController.endPivot())})),document.addEventListener("visibilitychange",this._onVisibilityChange=function(){a.splice(0)}),window.addEventListener("blur",this._onBlur=function(){a.splice(0)}),this._onTick=t.on("tick",(function(e){if(r.active&&r.pointerEnabled&&t.input.keyboardEnabled&&(!r.keyboardEnabledOnlyIfMouseover||n.mouseover)){var u=i.cameraControl,c=e.deltaTime/1e3;if(!r.planView){var A=u._isKeyDownForAction(u.ROTATE_Y_POS,a),h=u._isKeyDownForAction(u.ROTATE_Y_NEG,a),d=u._isKeyDownForAction(u.ROTATE_X_POS,a),p=u._isKeyDownForAction(u.ROTATE_X_NEG,a),f=c*r.keyboardRotationRate;(A||h||d||p)&&(!r.firstPerson&&r.followPointer&&i.pivotController.startPivot(),A?s.rotateDeltaY+=f:h&&(s.rotateDeltaY-=f),d?s.rotateDeltaX+=f:p&&(s.rotateDeltaX-=f),!r.firstPerson&&r.followPointer&&i.pivotController.startPivot())}if(!a[o.KEY_CTRL]&&!a[o.KEY_ALT]){var v=u._isKeyDownForAction(u.DOLLY_BACKWARDS,a),g=u._isKeyDownForAction(u.DOLLY_FORWARDS,a);if(v||g){var m=c*r.keyboardDollyRate;!r.firstPerson&&r.followPointer&&i.pivotController.startPivot(),g?s.dollyDelta-=m:v&&(s.dollyDelta+=m),l&&(n.followPointerDirty=!0,l=!1)}}var _=u._isKeyDownForAction(u.PAN_FORWARDS,a),y=u._isKeyDownForAction(u.PAN_BACKWARDS,a),b=u._isKeyDownForAction(u.PAN_LEFT,a),w=u._isKeyDownForAction(u.PAN_RIGHT,a),B=u._isKeyDownForAction(u.PAN_UP,a),x=u._isKeyDownForAction(u.PAN_DOWN,a),P=(a[o.KEY_ALT]?.3:1)*c*r.keyboardPanRate;(_||y||b||w||B||x)&&(!r.firstPerson&&r.followPointer&&i.pivotController.startPivot(),x?s.panDeltaY+=P:B&&(s.panDeltaY+=-P),w?s.panDeltaX+=-P:b&&(s.panDeltaX+=P),y?s.panDeltaZ+=P:_&&(s.panDeltaZ+=-P))}}))}return I(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),document.removeEventListener("visibilitychange",this._onVisibilityChange),window.removeEventListener("blur",this._onBlur),this._scene.input.off(this._onSceneKeyUp)}}]),e}(),Cp=le.vec3(),Mp=function(){function e(t,i,r,n,s){E(this,e),this._scene=t;var o=t.camera,a=i.pickController,l=i.pivotController,u=i.panController,c=i.cameraControl,A=1,h=1,d=null;this._onTick=t.on("tick",(function(){if(r.active&&r.pointerEnabled){var e="default";if(Math.abs(s.dollyDelta)<.001&&(s.dollyDelta=0),Math.abs(s.rotateDeltaX)<.001&&(s.rotateDeltaX=0),Math.abs(s.rotateDeltaY)<.001&&(s.rotateDeltaY=0),0===s.rotateDeltaX&&0===s.rotateDeltaY||(s.dollyDelta=0),r.followPointer){if(--A<=0&&(A=1,0!==s.dollyDelta)){if(0===s.rotateDeltaY&&0===s.rotateDeltaX&&r.followPointer&&n.followPointerDirty&&(a.pickCursorPos=n.pointerCanvasPos,a.schedulePickSurface=!0,a.update(),a.pickResult&&a.pickResult.worldPos?d=a.pickResult.worldPos:(h=1,d=null),n.followPointerDirty=!1),d){var i=Math.abs(le.lenVec3(le.subVec3(d,t.camera.eye,Cp)));h=i/r.dollyProximityThreshold}h<r.dollyMinSpeed&&(h=r.dollyMinSpeed)}}else h=1,d=null;var p=s.dollyDelta*h;if(0===s.rotateDeltaY&&0===s.rotateDeltaX||(!r.firstPerson&&r.followPointer&&l.getPivoting()?(l.continuePivot(s.rotateDeltaY,s.rotateDeltaX),l.showPivot()):(0!==s.rotateDeltaX&&(r.firstPerson?o.pitch(-s.rotateDeltaX):o.orbitPitch(s.rotateDeltaX)),0!==s.rotateDeltaY&&(r.firstPerson?o.yaw(s.rotateDeltaY):o.orbitYaw(s.rotateDeltaY))),s.rotateDeltaX*=r.rotationInertia,s.rotateDeltaY*=r.rotationInertia,e=c._cursors.rotate),Math.abs(s.panDeltaX)<.001&&(s.panDeltaX=0),Math.abs(s.panDeltaY)<.001&&(s.panDeltaY=0),Math.abs(s.panDeltaZ)<.001&&(s.panDeltaZ=0),0!==s.panDeltaX||0!==s.panDeltaY||0!==s.panDeltaZ){var f,v,g=le.vec3();if(g[0]=s.panDeltaX,g[1]=s.panDeltaY,g[2]=s.panDeltaZ,r.constrainVertical){o.xUp?(f=o.eye[0],v=o.look[0]):o.yUp?(f=o.eye[1],v=o.look[1]):o.zUp&&(f=o.eye[2],v=o.look[2]),o.pan(g);var m=o.eye,_=o.look;o.xUp?(m[0]=f,_[0]=v):o.yUp?(m[1]=f,_[1]=v):o.zUp&&(m[2]=f,_[2]=v),o.eye=m,o.look=_}else o.pan(g);e=c._cursors.pan}if(s.panDeltaX*=r.panInertia,s.panDeltaY*=r.panInertia,s.panDeltaZ*=r.panInertia,0!==p){if(e=p<0?c._cursors.dollyForward:c._cursors.dollyBackward,r.firstPerson){var y,b;if(r.constrainVertical&&(o.xUp?(y=o.eye[0],b=o.look[0]):o.yUp?(y=o.eye[1],b=o.look[1]):o.zUp&&(y=o.eye[2],b=o.look[2])),r.followPointer)u.dollyToCanvasPos(d,n.pointerCanvasPos,-p)&&(n.followPointerDirty=!0);else o.pan([0,0,p]),o.ortho.scale=o.ortho.scale-p;if(r.constrainVertical){var w=o.eye,B=o.look;o.xUp?(w[0]=y,B[0]=b):o.yUp?(w[1]=y,B[1]=b):o.zUp&&(w[2]=y,B[2]=b),o.eye=w,o.look=B}}else if(r.planView){if(r.followPointer)u.dollyToCanvasPos(d,n.pointerCanvasPos,-p)&&(n.followPointerDirty=!0);else o.ortho.scale=o.ortho.scale+p,o.zoom(p)}else{if(r.followPointer)u.dollyToCanvasPos(d,n.pointerCanvasPos,-p)&&(n.followPointerDirty=!0);else o.ortho.scale=o.ortho.scale+p,o.zoom(p)}s.dollyDelta*=r.dollyInertia}a.fireEvents(),document.body.style.cursor=e}}))}return I(e,[{key:"destroy",value:function(){this._scene.off(this._onTick)}}]),e}(),kp=function(){function e(t,i,r,n,s){E(this,e),this._scene=t;var o=this._scene.canvas.canvas;o.addEventListener("mouseenter",this._mouseEnterHandler=function(){n.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=function(){n.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=function(e){Ep(e,o,n.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=function(e){r.active&&r.pointerEnabled&&(Ep(e,o,n.pointerCanvasPos),n.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=function(e){r.active&&r.pointerEnabled})}return I(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}]),e}();function Ep(e,t,i){if(e){var r=t.getBoundingClientRect(),n=r.left,s=r.top;i[0]=e.clientX-n,i[1]=e.clientY-s}else e=window.event,i[0]=e.x,i[1]=e.y;return i}var Fp=function(e,t){if(e){for(var i=e.target,r=0,n=0;i.offsetParent;)r+=i.offsetLeft,n+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-r,t[1]=e.pageY-n}else e=window.event,t[0]=e.x,t[1]=e.y;return t},Ip=function(){function e(t,i,r,n,s){E(this,e),this._scene=t;var o=i.pickController,a=i.pivotController,l=le.vec2(),u=le.vec2(),c=le.vec2(),A=le.vec2(),h=[],d=this._scene.canvas.canvas,p=0,f=!1;this._onTick=t.on("tick",(function(){f=!1})),d.addEventListener("touchstart",this._canvasTouchStartHandler=function(e){if(r.active&&r.pointerEnabled){e.preventDefault();var i=e.touches,s=e.changedTouches;for(n.touchStartTime=Date.now(),1===i.length&&1===s.length&&(Fp(i[0],l),r.followPointer&&(o.pickCursorPos=l,o.schedulePickSurface=!0,o.update(),r.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(a.setPivotPos(o.pickResult.worldPos),!r.firstPerson&&a.startPivot()&&a.showPivot()):(r.smartPivot?a.setCanvasPivotPos(n.pointerCanvasPos):a.setPivotPos(t.camera.look),!r.firstPerson&&a.startPivot()&&a.showPivot()))));h.length<i.length;)h.push(le.vec2());for(var u=0,c=i.length;u<c;++u)Fp(i[u],h[u]);p=i.length}}),d.addEventListener("touchend",this._canvasTouchEndHandler=function(){a.getPivoting()&&(a.endPivot(),a.hidePivot())}),d.addEventListener("touchmove",this._canvasTouchMoveHandler=function(e){if(r.active&&r.pointerEnabled&&(e.stopPropagation(),e.preventDefault(),!f)){f=!0;var i=t.canvas.boundary,a=i[2],l=i[3],d=e.touches;if(e.touches.length===p){if(1===p){Fp(d[0],u),le.subVec2(u,h[0],A);var v=A[0],g=A[1];if(null!==n.longTouchTimeout&&(Math.abs(v)>r.longTapRadius||Math.abs(g)>r.longTapRadius)&&(clearTimeout(n.longTouchTimeout),n.longTouchTimeout=null),r.planView){var m=t.camera;if("perspective"===m.projection){var _=Math.abs(t.camera.eyeLookDist)*Math.tan(m.perspective.fov/2*Math.PI/180);s.panDeltaX+=v*_/l*r.touchPanRate,s.panDeltaY+=g*_/l*r.touchPanRate}else s.panDeltaX+=.5*m.ortho.scale*(v/l)*r.touchPanRate,s.panDeltaY+=.5*m.ortho.scale*(g/l)*r.touchPanRate}else s.rotateDeltaY-=v/a*(1*r.dragRotationRate),s.rotateDeltaX+=g/l*(1.5*r.dragRotationRate)}else if(2===p){var y=d[0],b=d[1];Fp(y,u),Fp(b,c);var w=le.geometricMeanVec2(h[0],h[1]),B=le.geometricMeanVec2(u,c),x=le.vec2();le.subVec2(w,B,x);var P=x[0],C=x[1],M=t.camera,k=le.distVec2([y.pageX,y.pageY],[b.pageX,b.pageY]),E=(le.distVec2(h[0],h[1])-k)*r.touchDollyRate;if(s.dollyDelta=E,Math.abs(E)<1)if("perspective"===M.projection){var F=o.pickResult?o.pickResult.worldPos:t.center,I=Math.abs(le.lenVec3(le.subVec3(F,t.camera.eye,[])))*Math.tan(M.perspective.fov/2*Math.PI/180);s.panDeltaX-=P*I/l*r.touchPanRate,s.panDeltaY-=C*I/l*r.touchPanRate}else s.panDeltaX-=.5*M.ortho.scale*(P/l)*r.touchPanRate,s.panDeltaY-=.5*M.ortho.scale*(C/l)*r.touchPanRate;n.pointerCanvasPos=B}for(var T=0;T<p;++T)Fp(d[T],h[T])}}})}return I(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler),e.removeEventListener("touchmove",this._canvasTouchMoveHandler),this._scene.off(this._onTick)}}]),e}(),Tp=function(e,t){if(e){for(var i=e.target,r=0,n=0;i.offsetParent;)r+=i.offsetLeft,n+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-r,t[1]=e.pageY-n}else e=window.event,t[0]=e.x,t[1]=e.y;return t},Dp=function(){function e(t,i,r,n,s){E(this,e),this._scene=t;var o,a=i.pickController,l=i.cameraControl,u=[],c=new Float32Array(2),A=-1,h=-1,d=this._scene.canvas.canvas,p=function(e){var r;e&&e.worldPos&&(r=e.worldPos);var n=e?e.entity.aabb:t.aabb;if(r){var s=t.camera;le.subVec3(s.eye,s.look,[]),i.cameraFlight.flyTo({aabb:n})}else i.cameraFlight.flyTo({aabb:n})};d.addEventListener("touchstart",this._canvasTouchStartHandler=function(e){if(r.active&&r.pointerEnabled){null!==n.longTouchTimeout&&(clearTimeout(n.longTouchTimeout),n.longTouchTimeout=null);var t=e.touches,s=e.changedTouches;if(o=Date.now(),1===t.length&&1===s.length){A=o,Tp(t[0],c);var a=c[0],l=c[1],h=t[0].pageX,d=t[0].pageY;n.longTouchTimeout=setTimeout((function(){i.cameraControl.fire("rightClick",{pagePos:[Math.round(h),Math.round(d)],canvasPos:[Math.round(a),Math.round(l)],event:e},!0),n.longTouchTimeout=null}),r.longTapTimeout)}else A=-1;for(;u.length<t.length;)u.push(new Float32Array(2));for(var p=0,f=t.length;p<f;++p)Tp(t[p],u[p]);u.length=t.length}},{passive:!0}),d.addEventListener("touchend",this._canvasTouchEndHandler=function(e){if(r.active&&r.pointerEnabled){var t=Date.now(),i=e.touches,s=e.changedTouches,o=l.hasSubs("pickedSurface");null!==n.longTouchTimeout&&(clearTimeout(n.longTouchTimeout),n.longTouchTimeout=null),0===i.length&&1===s.length&&A>-1&&t-A<150&&(h>-1&&A-h<325?(Tp(s[0],a.pickCursorPos),a.schedulePickEntity=!0,a.schedulePickSurface=o,a.update(),a.pickResult?(a.pickResult.touchInput=!0,l.fire("doublePicked",a.pickResult),a.pickedSurface&&l.fire("doublePickedSurface",a.pickResult),r.doublePickFlyTo&&p(a.pickResult)):(l.fire("doublePickedNothing"),r.doublePickFlyTo&&p()),h=-1):le.distVec2(u[0],c)<4&&(Tp(s[0],a.pickCursorPos),a.schedulePickEntity=!0,a.schedulePickSurface=o,a.update(),a.pickResult?(a.pickResult.touchInput=!0,l.fire("picked",a.pickResult),a.pickedSurface&&l.fire("pickedSurface",a.pickResult)):l.fire("pickedNothing"),h=t),A=-1),u.length=i.length;for(var d=0,f=i.length;d<f;++d)u[d][0]=i[d].pageX,u[d][1]=i[d].pageY}},{passive:!0})}return I(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler)}}]),e}(),Sp=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E(this,i),(r=t.call(this,e,n)).PAN_LEFT=0,r.PAN_RIGHT=1,r.PAN_UP=2,r.PAN_DOWN=3,r.PAN_FORWARDS=4,r.PAN_BACKWARDS=5,r.ROTATE_X_POS=6,r.ROTATE_X_NEG=7,r.ROTATE_Y_POS=8,r.ROTATE_Y_NEG=9,r.DOLLY_FORWARDS=10,r.DOLLY_BACKWARDS=11,r.AXIS_VIEW_RIGHT=12,r.AXIS_VIEW_BACK=13,r.AXIS_VIEW_LEFT=14,r.AXIS_VIEW_FRONT=15,r.AXIS_VIEW_TOP=16,r.AXIS_VIEW_BOTTOM=17,r.MOUSE_PAN=18,r.MOUSE_ROTATE=19,r.MOUSE_DOLLY=20,r._keyMap={},r.scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},r._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,zoomOnMouseWheel:!0,snapToVertex:true,snapToEdge:true,snapRadius:30,keyboardEnabledOnlyIfMouseover:!0,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},r._states={pointerCanvasPos:le.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:le.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},r._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};var s=r.scene;return r._controllers={cameraControl:w(r),pickController:new pp(w(r),r._configs),pivotController:new dp(s,r._configs),panController:new sp(s),cameraFlight:new et(w(r),{duration:.5})},r._handlers=[new kp(r.scene,r._controllers,r._configs,r._states,r._updates),new Ip(r.scene,r._controllers,r._configs,r._states,r._updates),new vp(r.scene,r._controllers,r._configs,r._states,r._updates),new Bp(r.scene,r._controllers,r._configs,r._states,r._updates),new xp(r.scene,r._controllers,r._configs,r._states,r._updates),new Dp(r.scene,r._controllers,r._configs,r._states,r._updates),new Pp(r.scene,r._controllers,r._configs,r._states,r._updates)],r._cursors={dollyForward:"zoom-in",dollyBackward:"zoom-out",rotate:"grabbing",pan:"move"},r._cameraUpdater=new Mp(r.scene,r._controllers,r._configs,r._states,r._updates),r.navMode=n.navMode,n.planView&&(r.planView=n.planView),r.constrainVertical=n.constrainVertical,n.keyboardLayout?r.keyboardLayout=n.keyboardLayout:r.keyMap=n.keyMap,r.doublePickFlyTo=n.doublePickFlyTo,r.panRightClick=n.panRightClick,r.active=n.active,r.followPointer=n.followPointer,r.rotationInertia=n.rotationInertia,r.keyboardPanRate=n.keyboardPanRate,r.touchPanRate=n.touchPanRate,r.keyboardRotationRate=n.keyboardRotationRate,r.dragRotationRate=n.dragRotationRate,r.touchDollyRate=n.touchDollyRate,r.dollyInertia=n.dollyInertia,r.dollyProximityThreshold=n.dollyProximityThreshold,r.dollyMinSpeed=n.dollyMinSpeed,r.panInertia=n.panInertia,r.pointerEnabled=!0,r.keyboardDollyRate=n.keyboardDollyRate,r.mouseWheelDollyRate=n.mouseWheelDollyRate,r}return I(i,[{key:"keyMap",get:function(){return this._keyMap},set:function(e){if(e=e||"qwerty",ge.isString(e)){var t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6],i[this.MOUSE_PAN]=[[t.MOUSE_LEFT_BUTTON,t.KEY_SHIFT],this._configs.panRightClick?t.MOUSE_RIGHT_BUTTON:t.MOUSE_MIDDLE_BUTTON],i[this.MOUSE_ROTATE]=[t.MOUSE_LEFT_BUTTON],i[this.MOUSE_DOLLY]=[];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6],i[this.MOUSE_PAN]=[[t.MOUSE_LEFT_BUTTON,t.KEY_SHIFT],this._configs.panRightClick?t.MOUSE_RIGHT_BUTTON:t.MOUSE_MIDDLE_BUTTON],i[this.MOUSE_ROTATE]=[t.MOUSE_LEFT_BUTTON],i[this.MOUSE_DOLLY]=[]}this._keyMap=i}else{var r=e;this._keyMap=r}}},{key:"_areAllKeysDown",value:function(e,t){if(!t||t.length<=0)return!0;if(!e)return!1;for(var i=0,r=t.length;i<r;i++){if(!e[t[i]])return!1}return!0}},{key:"_isAnyOtherKeyDown",value:function(e,t){for(var i=0,r=e.length;i<r;i++)if(e[i])if(Array.isArray(t)){if(t.indexOf(i)<0)return!0}else if(i!==t)return!0;return!1}},{key:"_isMouseAction",value:function(e){switch(e){case this.MOUSE_ROTATE:case this.MOUSE_DOLLY:case this.MOUSE_PAN:return!0;default:return!1}}},{key:"_isKeyDownForAction",value:function(e,t){var i=this._keyMap[e];if(!i)return!1;if(0===i.length&&this._isMouseAction(e))return!0;t||(t=this.scene.input.keyDown);for(var r=0,n=i.length;r<n;r++){var s=i[r];if(Array.isArray(s)){if(this._areAllKeysDown(t,s)&&!this._isAnyOtherKeyDown(t,s))return!0}else if(t[s]&&!this._isAnyOtherKeyDown(t,s))return!0}return!1}},{key:"pivotElement",set:function(e){this._controllers.pivotController.setPivotElement(e)}},{key:"active",get:function(){return this._configs.active},set:function(e){e=!1!==e,this._configs.active=e,this._handlers[1]._active=e,this._handlers[5]._active=e}},{key:"snapToVertex",get:function(){return this._configs.snapToVertex},set:function(e){this._configs.snapToVertex=!!e}},{key:"snapToEdge",get:function(){return this._configs.snapToEdge},set:function(e){this._configs.snapToEdge=!!e}},{key:"snapRadius",get:function(){return this._configs.snapRadius},set:function(e){e=e||30,this._configs.snapRadius=e}},{key:"keyboardEnabledOnlyIfMouseover",get:function(){return this._configs.keyboardEnabledOnlyIfMouseover},set:function(e){this._configs.keyboardEnabledOnlyIfMouseover=!!e}},{key:"navMode",get:function(){return this._configs.navMode},set:function(e){"firstPerson"!==(e=e||"orbit")&&"orbit"!==e&&"planView"!==e&&(this.error("Unsupported value for navMode: "+e+" - supported values are 'orbit', 'firstPerson' and 'planView' - defaulting to 'orbit'"),e="orbit"),this._configs.firstPerson="firstPerson"===e,this._configs.planView="planView"===e,(this._configs.firstPerson||this._configs.planView)&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this._configs.navMode=e}},{key:"pointerEnabled",get:function(){return this._configs.pointerEnabled},set:function(e){this._reset(),this._configs.pointerEnabled=!!e}},{key:"setCursorStyle",value:function(e,t){Object.prototype.hasOwnProperty.call(this._cursors,e)?this._cursors=h(h({},this._cursors),{},d({},e,t)):console.warn("Action '".concat(e,"' is not valid for cursor styles."))}},{key:"getCursorStyle",value:function(e){return this._cursors[e]||null}},{key:"_reset",value:function(){for(var e=0,t=this._handlers.length;e<t;e++){var i=this._handlers[e];i.reset&&i.reset()}this._updates.panDeltaX=0,this._updates.panDeltaY=0,this._updates.rotateDeltaX=0,this._updates.rotateDeltaY=0,this._updates.dolyDelta=0}},{key:"followPointer",get:function(){return this._configs.followPointer},set:function(e){this._configs.followPointer=!1!==e}},{key:"pivotPos",get:function(){return this._controllers.pivotController.getPivotPos()},set:function(e){this._controllers.pivotController.setPivotPos(e)}},{key:"dollyToPointer",get:function(){return this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer},set:function(e){this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer=e}},{key:"panToPointer",get:function(){return this.warn("panToPointer property is deprecated - replaced with followPointer"),!1},set:function(e){this.warn("panToPointer property is deprecated - replaced with followPointer")}},{key:"planView",get:function(){return this.warn("planView property is deprecated - replaced with navMode"),this._configs.planView},set:function(e){this._configs.planView=!!e,this._configs.firstPerson=!1,this._configs.planView&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this.warn("planView property is deprecated - replaced with navMode")}},{key:"firstPerson",get:function(){return this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson},set:function(e){this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson=!!e,this._configs.planView=!1,this._configs.firstPerson&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot())}},{key:"constrainVertical",get:function(){return this._configs.constrainVertical},set:function(e){this._configs.constrainVertical=!!e}},{key:"doublePickFlyTo",get:function(){return this._configs.doublePickFlyTo},set:function(e){this._configs.doublePickFlyTo=!1!==e}},{key:"panRightClick",get:function(){return this._configs.panRightClick},set:function(e){this._configs.panRightClick=!1!==e;var t=this._keyMap[this.MOUSE_PAN];if(t&&t.length>0)for(var i=this.scene.input,r=0,n=t.length;r<n;r++)this._configs.panRightClick&&t[r]===i.MOUSE_MIDDLE_BUTTON?this._keyMap[this.MOUSE_PAN][r]=i.MOUSE_RIGHT_BUTTON:this._configs.panRightClick||t[r]!==i.MOUSE_RIGHT_BUTTON||(this._keyMap[this.MOUSE_PAN][r]=i.MOUSE_MIDDLE_BUTTON)}},{key:"rotationInertia",get:function(){return this._configs.rotationInertia},set:function(e){this._configs.rotationInertia=null!=e?e:0}},{key:"keyboardPanRate",get:function(){return this._configs.keyboardPanRate},set:function(e){this._configs.keyboardPanRate=null!=e?e:5}},{key:"touchPanRate",get:function(){return this._configs.touchPanRate},set:function(e){this._configs.touchPanRate=null!=e?e:1}},{key:"keyboardRotationRate",get:function(){return this._configs.keyboardRotationRate},set:function(e){this._configs.keyboardRotationRate=null!=e?e:90}},{key:"dragRotationRate",get:function(){return this._configs.dragRotationRate},set:function(e){this._configs.dragRotationRate=null!=e?e:360}},{key:"keyboardDollyRate",get:function(){return this._configs.keyboardDollyRate},set:function(e){this._configs.keyboardDollyRate=null!=e?e:15}},{key:"touchDollyRate",get:function(){return this._configs.touchDollyRate},set:function(e){this._configs.touchDollyRate=null!=e?e:.2}},{key:"mouseWheelDollyRate",get:function(){return this._configs.mouseWheelDollyRate},set:function(e){this._configs.mouseWheelDollyRate=null!=e?e:100}},{key:"dollyInertia",get:function(){return this._configs.dollyInertia},set:function(e){this._configs.dollyInertia=null!=e?e:0}},{key:"dollyProximityThreshold",get:function(){return this._configs.dollyProximityThreshold},set:function(e){this._configs.dollyProximityThreshold=null!=e?e:35}},{key:"dollyMinSpeed",get:function(){return this._configs.dollyMinSpeed},set:function(e){this._configs.dollyMinSpeed=null!=e?e:.04}},{key:"panInertia",get:function(){return this._configs.panInertia},set:function(e){this._configs.panInertia=null!=e?e:.5}},{key:"keyboardLayout",get:function(){return this._configs.keyboardLayout},set:function(e){"qwerty"!==(e=e||"qwerty")&&"azerty"!==e&&(this.error("Unsupported value for keyboardLayout - defaulting to 'qwerty'"),e="qwerty"),this._configs.keyboardLayout=e,this.keyMap=this._configs.keyboardLayout}},{key:"enablePivotSphere",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._controllers.pivotController.enablePivotSphere(e)}},{key:"disablePivotSphere",value:function(){this._controllers.pivotController.disablePivotSphere()}},{key:"smartPivot",get:function(){return this._configs.smartPivot},set:function(e){this._configs.smartPivot=!1!==e}},{key:"doubleClickTimeFrame",get:function(){return this._configs.doubleClickTimeFrame},set:function(e){this._configs.doubleClickTimeFrame=null!=e?e:250}},{key:"zoomOnMouseWheel",get:function(){return this._configs.zoomOnMouseWheel},set:function(e){this._configs.zoomOnMouseWheel=!!e}},{key:"destroy",value:function(){this._destroyHandlers(),this._destroyControllers(),this._cameraUpdater.destroy(),v(x(i.prototype),"destroy",this).call(this)}},{key:"_destroyHandlers",value:function(){for(var e=0,t=this._handlers.length;e<t;e++){var i=this._handlers[e];i.destroy&&i.destroy()}}},{key:"_destroyControllers",value:function(){for(var e=0,t=this._controllers.length;e<t;e++){var i=this._controllers[e];i.destroy&&i.destroy()}}}]),i}(),Rp=I((function e(t,i,r,n,s){E(this,e),this.name=t,this.type=r,this.value=i,this.valueType=n,this.description=s})),Up=I((function e(t){if(E(this,e),this.id=t.id,this.originalSystemId=t.originalSystemId,this.metaModels=[],this.name=t.name,this.type=t.type,this.properties=[],t.properties)for(var i=t.properties,r=0,n=i.length;r<n;r++){var s=i[r];Number.isInteger(s)?this.properties.push(s):this.properties.push(new Rp(s.name,s.value,s.type,s.valueType,s.description))}})),Lp=function(){function e(t){E(this,e),this.metaModels=[],this.id=t.id,this.parentId=t.parentId,this.parent=null,this.originalSystemId=t.originalSystemId,this.name=t.name,this.type=t.type,this.propertySetIds=t.propertySetIds,this.propertySets=[],this.attributes=t.attributes||{},void 0!==t.external&&null!==t.external&&(this.external=t.external)}return I(e,[{key:"metaModel",get:function(){return 1==this.metaModels.length?this.metaModels[0]:null}},{key:"getObjectIDsInSubtree",value:function(){var e=[];return function t(i){if(i){e.push(i.id);var r=i.children;if(r)for(var n=0,s=r.length;n<s;n++)t(r[n])}}(this),e}},{key:"withMetaObjectsInSubtree",value:function(e){!function t(i){if(i){e(i);var r=i.children;if(r)for(var n=0,s=r.length;n<s;n++)t(r[n])}}(this)}},{key:"getObjectIDsInSubtreeByType",value:function(e){for(var t={},i=0,r=e.length;i<r;i++)t[e[i]]=e[i];var n=[];return function e(i){if(i){t[i.type]&&n.push(i.id);var r=i.children;if(r)for(var s=0,o=r.length;s<o;s++)e(r[s])}}(this),n}},{key:"getJSON",value:function(){var e={id:this.id,type:this.type,name:this.name};return this.parent&&(e.parent=this.parent.id),e}}]),e}(),Op=function(){function e(t){E(this,e),this.id=t.id,this.projectId=t.projectId,this.revisionId=t.revisionId,this.author=t.author,this.createdAt=t.createdAt,this.creatingApplication=t.creatingApplication,this.schema=t.schema,this.metaScene=t.metaScene,this.propertySets=[],this.rootMetaObjects=[],this.metaObjects={},this.graph=t.graph||{},this.metaScene.metaModels[this.id]=this,this._propertyLookup=[],this.finalized=!1}return I(e,[{key:"rootMetaObject",get:function(){return 1===this.rootMetaObjects.length?this.rootMetaObjects[0]:null}},{key:"loadData",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.finalized)throw"MetaScene already finalized - can't add more data";this._globalizeIDs(e,t);var i=this.metaScene,r=e.properties;if(r)for(var n=0,s=r.length;n<s;n++)this._propertyLookup.push(r[n]);if(e.propertySets)for(var o=0,a=e.propertySets.length;o<a;o++){var l=e.propertySets[o];l.properties||(l.properties=[]);var u=i.propertySets[l.id];u||(u=new Up({id:l.id,originalSystemId:l.originalSystemId||l.id,type:l.type,name:l.name,properties:l.properties}),i.propertySets[u.id]=u),u.metaModels.push(this),this.propertySets.push(u)}if(e.metaObjects)for(var c=0,A=e.metaObjects.length;c<A;c++){var h=e.metaObjects[c],d=h.id,p=i.metaObjects[d];if(!p){var f=h.type,v=h.originalSystemId,g=h.propertySets||h.propertySetIds;p=new Lp({id:d,originalSystemId:v,parentId:h.parent,type:f,name:h.name,attributes:h.attributes,propertySetIds:g,external:h.external}),this.metaScene.metaObjects[d]=p,p.metaModels=[]}this.metaObjects[d]=p,h.parent||(this.rootMetaObjects.push(p),i.rootMetaObjects[d]=p),p.metaModels.push(this)}}},{key:"_decompressProperties",value:function(e,t){for(var i=[],r=0,n=t.length;r<n;r++){var s=t[r];if(Number.isInteger(s)){var o=e[s];o?t[r]=o:i.push(s)}}i.length>0&&console.error("[MetaModel._decompressProperties] Properties not found: ".concat(i))}},{key:"finalize",value:function(){if(this.finalized)throw"MetaScene already finalized - can't re-finalize";var e=this.metaScene;for(var t in e.metaObjects){var i=e.metaObjects[t];if(i.children&&(i.children=[]),i.propertySets&&(i.propertySets=[]),i.propertySetIds)for(var r=0,n=i.propertySetIds.length;r<n;r++){var s=i.propertySetIds[r],o=e.propertySets[s];i.propertySets.push(o)}}for(var a in e.metaObjects){var l=e.metaObjects[a];if(l.parentId){var u=e.metaObjects[l.parentId];u&&(l.parent=u,(u.children||(u.children=[])).push(l))}}for(var c in e.metaObjects){e.metaObjects[c].metaModels=[]}for(var A in e.metaModels){var h=e.metaModels[A];for(var d in h.metaObjects){h.metaObjects[d].metaModels.push(h)}}for(var p in e.metaObjectsByType={},e.metaObjects){var f=e.metaObjects[p],v=f.type;(e.metaObjectsByType[v]||(e.metaObjectsByType[v]={}))[p]=f}if(this.propertySets)for(var g=0,m=this.propertySets.length;g<m;g++){var _=this.propertySets[g];this._decompressProperties(this._propertyLookup,_.properties)}this._propertyLookup=[],this.finalized=!0,this.metaScene.fire("metaModelCreated",this.id)}},{key:"getJSON",value:function(){for(var e={id:this.id,projectId:this.projectId,author:this.author,createdAt:this.createdAt,schema:this.schema,creatingApplication:this.creatingApplication,metaObjects:[],propertySets:[]},t=Object.values(this.metaObjects),i=0,r=t.length;i<r;i++){var n=t[i],s={id:n.id,originalSystemId:n.originalSystemId,extId:n.extId,type:n.type,name:n.name};n.parent&&(s.parent=n.parent.id),n.attributes&&(s.attributes=n.attributes),n.propertySetIds&&(s.propertySetIds=n.propertySetIds),e.metaObjects.push(s)}for(var o=0,a=this.propertySets.length;o<a;o++){for(var l=this.propertySets[o],u={id:l.id,originalSystemId:l.originalSystemId,extId:l.extId,type:l.type,name:l.name,propertyies:[]},c=0,A=l.properties.length;c<A;c++){var h=l.properties[c],d={id:h.id,description:h.description,type:h.type,name:h.name,value:h.value,valueType:h.valueType};u.properties.push(d)}e.propertySets.push(u)}return e}},{key:"_globalizeIDs",value:function(e,t){var i=!!t.globalizeObjectIds;if(e.metaObjects)for(var r=0,n=e.metaObjects.length;r<n;r++){var s=e.metaObjects[r];if(s.originalSystemId=s.id,s.parent&&(s.originalParentSystemId=s.parent),i&&(s.id=le.globalizeObjectId(this.id,s.id),s.parent&&(s.parent=le.globalizeObjectId(this.id,s.parent))),i){var o=s.propertySetIds;if(o){for(var a=[],l=0,u=o.length;l<u;l++)a.push(le.globalizeObjectId(this.id,o[l]));s.propertySetIds=a,s.originalSystemPropertySetIds=o}}else s.originalSystemPropertySetIds=s.propertySetIds}if(e.propertySets)for(var c=0,A=e.propertySets.length;c<A;c++){var h=e.propertySets[c];h.originalSystemId=h.id,i&&(h.id=le.globalizeObjectId(this.id,h.id))}}}]),e}(),Np=function(){function e(t,i){E(this,e),this.viewer=t,this.scene=i,this.metaModels={},this.propertySets={},this.metaObjects={},this.metaObjectsByType={},this.rootMetaObjects={},this._eventSubs={}}return I(e,[{key:"on",value:function(e,t){var i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}},{key:"fire",value:function(e,t){var i=this._eventSubs[e];if(i)for(var r=0,n=i.length;r<n;r++)i[r](t)}},{key:"off",value:function(e){}},{key:"createMetaModel",value:function(e,t){var i=new Op({metaScene:this,id:e,projectId:t.projectId||"none",revisionId:t.revisionId||"none",author:t.author||"none",createdAt:t.createdAt||"none",creatingApplication:t.creatingApplication||"none",schema:t.schema||"none",propertySets:[]});return i.loadData(t),i.finalize(),i}},{key:"destroyMetaModel",value:function(e){var t=this.metaModels[e];if(t){if(t.propertySets)for(var i=0,r=t.propertySets.length;i<r;i++){var n=t.propertySets[i];if(1===n.metaModels.length&&n.metaModels[0].id===e)delete this.propertySets[n.id];else{for(var s=[],o=0,a=n.metaModels.length;o<a;o++)n.metaModels[o].id!==e&&s.push(n.metaModels[o]);n.metaModels=s}}if(t.metaObjects)for(var l in t.metaObjects){var u=t.metaObjects[l];1===u.metaModels.length&&u.metaModels[0].id===e?(delete this.metaObjects[l],u.parent||delete this.rootMetaObjects[l]):u.metaModels=u.metaModels.filter((function(t){return t.id!==e}))}for(var c in this.metaObjects){var A=this.metaObjects[c];if(A.children&&(A.children=[]),A.propertySets&&(A.propertySets=[]),A.propertySetIds)for(var h=0,d=A.propertySetIds.length;h<d;h++){var p=A.propertySetIds[h],f=this.propertySets[p];A.propertySets.push(f)}}for(var v in this.metaObjectsByType={},this.metaObjects){var g=this.metaObjects[v],m=g.type;g.children&&(g.children=null),(this.metaObjectsByType[m]||(this.metaObjectsByType[m]={}))[v]=g}for(var _ in this.metaObjects){var y=this.metaObjects[_];if(y.parentId){var b=this.metaObjects[y.parentId];b&&(y.parent=b,(b.children||(b.children=[])).push(y))}}for(var w in delete this.metaModels[e],this.metaObjects){this.metaObjects[w].metaModels=[]}for(var B in this.metaModels){var x=this.metaModels[B];for(var P in x.metaObjects){x.metaObjects[P].metaModels.push(x)}}this.fire("metaModelDestroyed",e)}}},{key:"getObjectIDsByType",value:function(e){var t=this.metaObjectsByType[e];return t?Object.keys(t):[]}},{key:"getObjectIDsInSubtree",value:function(e,t,i){var r=[],n=this.metaObjects[e],s=t&&t.length>0?Vp(t):null,o=i&&i.length>0?Vp(i):null;return function e(t){if(t){var i=!0;(o&&o[t.type]||s&&!s[t.type])&&(i=!1),i&&r.push(t.id);var n=t.children;if(n)for(var a=0,l=n.length;a<l;a++)e(n[a])}}(n),r}},{key:"withMetaObjectsInSubtree",value:function(e,t){var i=this.metaObjects[e];i&&i.withMetaObjectsInSubtree(t)}}]),e}();function Vp(e){for(var t={},i=0,r=e.length;i<r;i++)t[e[i]]=!0;return t}
|
|
23
|
+
**/var lA=null;function uA(e,t){var i,r,n,s,o,a,l=3*e,u=3*t,c=Math.min(i=lA[l],r=lA[l+1],n=lA[l+2]),A=Math.min(s=lA[u],o=lA[u+1],a=lA[u+2]);if(c!==A)return c-A;var h=Math.max(i,r,n),d=Math.max(s,o,a);return h!==d?h-d:0}function cA(e,t){for(var i=new Int32Array(e.length/3),r=0,n=i.length;r<n;r++)i[r]=r;lA=new Int32Array(e.length);for(var s=0,o=e.length;s<o;s++)lA[s]=e[s]>>t;i.sort(uA);for(var a=new Int32Array(e.length),l=0,u=i.length;l<u;l++)a[3*l+0]=e[3*i[l]+0],a[3*l+1]=e[3*i[l]+1],a[3*l+2]=e[3*i[l]+2];return a}var AA=null;function hA(e,t){var i=AA[2*e]-AA[2*t];return 0!==i?i:AA[2*e+1]-AA[2*t+1]}function dA(e){if(0===(e||[]).length)return[];for(var t=new Int32Array(e.length/2),i=0,r=t.length;i<r;i++)t[i]=i;for(var n=0,s=e.length;n<s;n+=2)if(e[n]>e[n+1]){var o=e[n];e[n]=e[n+1],e[n+1]=o}AA=new Int32Array(e),t.sort(hA);for(var a=new Int32Array(e.length),l=0,u=t.length;l<u;l++)a[2*l+0]=e[2*t[l]+0],a[2*l+1]=e[2*t[l]+1];return a}function pA(e,t){var i={},r={};e.forEach((function(e){for(var t=e.indices,n=e.edgeIndices,s=e.positionsCompressed,o=0,a=t.length;o<a;o+=3){var l=s[3*t[o]]+"_"+s[3*t[o]+1]+"_"+s[3*t[o]+2]+"/"+s[3*t[o+1]]+"_"+s[3*t[o+1]+1]+"_"+s[3*t[o+1]+2]+"/"+s[3*t[o+2]]+"_"+s[3*t[o+2]+1]+"_"+s[3*t[o+2]+2];i[l]=!0}e.edgeIndices.length/2;for(var u=0,c=n.length;u<c;u+=2){var A=s[3*n[u]]+"_"+s[3*n[u]+1]+"_"+s[3*n[u]+2]+"/"+s[3*n[u+1]]+"_"+s[3*n[u+1]+1]+"_"+s[3*n[u+1]+2]+"/";r[A]=!0}}));var n=t.indices;t.edgeIndices;for(var s=t.positionsCompressed,o=0,a=n.length;o<a;o+=3){var l=s[3*n[o]]+"_"+s[3*n[o]+1]+"_"+s[3*n[o]+2]+"/"+s[3*n[o+1]]+"_"+s[3*n[o+1]+1]+"_"+s[3*n[o+1]+2]+"/"+s[3*n[o+2]]+"_"+s[3*n[o+2]+1]+"_"+s[3*n[o+2]+2];if(!(l in i))throw console.log("Not found "+l),"Ohhhh!"}}var fA=new Float32Array([0,0,0]),vA=new Uint16Array([0,0,0]);le.OBB3();var gA=function(){function e(t,i,r,n,s,o){E(this,e),this._isObject=i,this.scene=t.scene,this.model=t,this.isSceneModelEntity=!0,this.meshes=n,this._numPrimitives=0,this._capMaterial=null;for(var a=0,l=this.meshes.length;a<l;a++){var u=this.meshes[a];u.parent=this,u.entity=this,this._numPrimitives+=u.numPrimitives}this.id=r,this.originalSystemId=le.unglobalizeObjectId(t.id,r),this._flags=s,this._aabb=le.AABB3(),this._aabbDirty=!0,this._offset=le.vec3(),this._colorizeUpdated=!1,this._opacityUpdated=!1,this._lodCullable=!!o,this._culled=!1,this._culledVFC=!1,this._culledLOD=!1,this._isObject&&t.scene._registerObject(this)}return I(e,[{key:"_transformDirty",value:function(){this._aabbDirty=!0,this.model._transformDirty()}},{key:"_sceneModelDirty",value:function(){this._aabbDirty=!0;for(var e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._sceneModelDirty()}},{key:"aabb",get:function(){if(this._aabbDirty){le.collapseAABB3(this._aabb);for(var e=0,t=this.meshes.length;e<t;e++)le.expandAABB3(this._aabb,this.meshes[e].aabb);this._aabbDirty=!1}return this._aabb}},{key:"isEntity",get:function(){return!0}},{key:"isModel",get:function(){return!1}},{key:"isObject",get:function(){return this._isObject}},{key:"numPrimitives",get:function(){return this._numPrimitives}},{key:"numTriangles",get:function(){return this._numPrimitives}},{key:"visible",get:function(){return this._getFlag(gs)},set:function(e){if(!!(this._flags&gs)!==e){this._flags=e?this._flags|gs:this._flags&~gs;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setVisible(this._flags);this._isObject&&this.model.scene._objectVisibilityUpdated(this),this.model.glRedraw()}}},{key:"highlighted",get:function(){return this._getFlag(Bs)},set:function(e){if(!!(this._flags&Bs)!==e){this._flags=e?this._flags|Bs:this._flags&~Bs;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this),this.model.glRedraw()}}},{key:"xrayed",get:function(){return this._getFlag(ws)},set:function(e){if(!!(this._flags&ws)!==e){this._flags=e?this._flags|ws:this._flags&~ws;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setXRayed(this._flags);this._isObject&&this.model.scene._objectXRayedUpdated(this),this.model.glRedraw()}}},{key:"selected",get:function(){return this._getFlag(xs)},set:function(e){if(!!(this._flags&xs)!==e){this._flags=e?this._flags|xs:this._flags&~xs;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setSelected(this._flags);this._isObject&&this.model.scene._objectSelectedUpdated(this),this.model.glRedraw()}}},{key:"edges",get:function(){return this._getFlag(Ps)},set:function(e){if(!!(this._flags&Ps)!==e){this._flags=e?this._flags|Ps:this._flags&~Ps;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setEdges(this._flags);this.model.glRedraw()}}},{key:"culledVFC",get:function(){return!!this._culledVFC},set:function(e){this._culledVFC=e,this._setCulled()}},{key:"culledLOD",get:function(){return!!this._culledLOD},set:function(e){this._culledLOD=e,this._setCulled()}},{key:"culled",get:function(){return!!this._culled},set:function(e){this._culled=e,this._setCulled()}},{key:"_setCulled",value:function(){var e=!!this._culled||!(!this._culledLOD||!this._lodCullable)||!!this._culledVFC;if(!!(this._flags&ms)!==e){this._flags=e?this._flags|ms:this._flags&~ms;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCulled(this._flags);this.model.glRedraw()}}},{key:"clippable",get:function(){return this._getFlag(ys)},set:function(e){if(!!(this._flags&ys)!==e){this._flags=e?this._flags|ys:this._flags&~ys;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}},{key:"collidable",get:function(){return this._getFlag(bs)},set:function(e){if(!!(this._flags&bs)!==e){this._flags=e?this._flags|bs:this._flags&~bs;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCollidable(this._flags)}}},{key:"pickable",get:function(){return this._getFlag(_s)},set:function(e){if(!!(this._flags&_s)!==e){this._flags=e?this._flags|_s:this._flags&~_s;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setPickable(this._flags)}}},{key:"colorize",get:function(){if(0===this.meshes.length)return null;var e=this.meshes[0]._colorize;return fA[0]=e[0]/255,fA[1]=e[1]/255,fA[2]=e[2]/255,fA},set:function(e){if(e){vA[0]=Math.floor(255*e[0]),vA[1]=Math.floor(255*e[1]),vA[2]=Math.floor(255*e[2]);for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setColorize(vA)}else for(var r=0,n=this.meshes.length;r<n;r++)this.meshes[r]._setColorize(null);if(this._isObject){var s=!!e;this.scene._objectColorizeUpdated(this,s),this._colorizeUpdated=s}this.model.glRedraw()}},{key:"opacity",get:function(){return this.meshes.length>0?this.meshes[0]._colorize[3]/255:1},set:function(e){if(0!==this.meshes.length){var t=null!=e,i=this.meshes[0]._colorize[3],r=255;if(t){if(e<0?e=0:e>1&&(e=1),i===(r=Math.floor(255*e)))return}else if(i===(r=255))return;for(var n=0,s=this.meshes.length;n<s;n++)this.meshes[n]._setOpacity(r,this._flags);this._isObject&&(this.scene._objectOpacityUpdated(this,t),this._opacityUpdated=t),this.model.glRedraw()}}},{key:"offset",get:function(){return this._offset},set:function(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setOffset(this._offset);this._aabbDirty=!0,this.model._aabbDirty=!0,this.scene._aabbDirty=!0,this.scene._objectOffsetUpdated(this,e),this.model.glRedraw()}},{key:"saoEnabled",get:function(){return this.model.saoEnabled}},{key:"capMaterial",get:function(){return this._capMaterial},set:function(e){this.scene.readableGeometryEnabled&&(this._capMaterial=e instanceof mn?e:null,this.scene._capMaterialUpdated(this.id,this.model.id))}},{key:"getEachVertex",value:function(e){for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t].getEachVertex(e)}},{key:"getEachIndex",value:function(e){for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t].getEachIndex(e)}},{key:"getGeometryData",value:function(){for(var e=0,t=[],i=[],r=0,n=this.meshes.length;r<n;r++){var s=this.meshes[r];if(s.layer.readGeometryData){for(var o=s.layer.readGeometryData(s.portionId),a=0,l=o.indices.length;a<l;a++)i.push(o.indices[a]+e);for(var u=0,c=o.positions.length;u<c;u++)t.push(o.positions[u]);e+=o.positions.length/3}}return{indices:i,positions:t}}},{key:"volume",get:function(){for(var e=0,t=0,i=this.meshes.length;t<i;t++){var r=this.meshes[t].volume;if(r<0)return-1;e+=r}return e}},{key:"surfaceArea",get:function(){for(var e=0,t=0,i=this.meshes.length;t<i;t++){var r=this.meshes[t].surfaceArea;r>=0&&(e+=r)}return e>0?e:-1}},{key:"_getFlag",value:function(e){return!!(this._flags&e)}},{key:"_finalize",value:function(){var e=this.model.scene;this._isObject&&(this.visible&&e._objectVisibilityUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this));for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._finalize(this._flags)}},{key:"_finalize2",value:function(){for(var e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize2()}},{key:"_destroy",value:function(){var e=this.model.scene;this._isObject&&(e._deregisterObject(this),this.visible&&e._deRegisterVisibleObject(this),this.xrayed&&e._deRegisterXRayedObject(this),this.selected&&e._deRegisterSelectedObject(this),this.highlighted&&e._deRegisterHighlightedObject(this),this._colorizeUpdated&&this.scene._deRegisterColorizedObject(this),this._opacityUpdated&&this.scene._deRegisterOpacityObject(this),!this._offset||0===this._offset[0]&&0===this._offset[1]&&0===this._offset[2]||this.scene._deRegisterOffsetObject(this));for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._destroy();e._aabbDirty=!0}}]),e}(),mA=le.vec4(4),_A=le.vec4(),yA=le.vec4(),bA=le.vec3([1,0,0]),wA=le.vec3([0,1,0]),BA=le.vec3([0,0,1]);le.vec3(3),le.vec3(3);var xA=le.identityMat4(),PA=function(){function e(t){E(this,e),this._model=t.model,this.id=t.id,this._parentTransform=t.parent,this._childTransforms=[],this._meshes=[],this._scale=new Float32Array([1,1,1]),this._quaternion=le.identityQuaternion(new Float32Array(4)),this._rotation=new Float32Array(3),this._position=new Float32Array(3),this._localMatrix=le.identityMat4(new Float32Array(16)),this._worldMatrix=le.identityMat4(new Float32Array(16)),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),t.parent&&t.parent._addChildTransform(this)}return I(e,[{key:"_addChildTransform",value:function(e){this._childTransforms.push(e),e._parentTransform=this,e._transformDirty(),e._setSubtreeAABBsDirty(this)}},{key:"_addMesh",value:function(e){this._meshes.push(e),e.transform=this}},{key:"parentTransform",get:function(){return this._parentTransform}},{key:"meshes",get:function(){return this._meshes}},{key:"position",get:function(){return this._position},set:function(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._model.glRedraw()}},{key:"rotation",get:function(){return this._rotation},set:function(e){this._rotation.set(e||[0,0,0]),le.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._model.glRedraw()}},{key:"quaternion",get:function(){return this._quaternion},set:function(e){this._quaternion.set(e||[0,0,0,1]),le.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._model.glRedraw()}},{key:"scale",get:function(){return this._scale},set:function(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._model.glRedraw()}},{key:"matrix",get:function(){return this._localMatrixDirty&&(this._localMatrix||(this._localMatrix=le.identityMat4()),le.composeMat4(this._position,this._quaternion,this._scale,this._localMatrix),this._localMatrixDirty=!1),this._localMatrix},set:function(e){this._localMatrix||(this._localMatrix=le.identityMat4()),this._localMatrix.set(e||xA),le.decomposeMat4(this._localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._transformDirty(),this._model.glRedraw()}},{key:"worldMatrix",get:function(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}},{key:"rotate",value:function(e,t){return mA[0]=e[0],mA[1]=e[1],mA[2]=e[2],mA[3]=t*le.DEGTORAD,le.angleAxisToQuaternion(mA,_A),le.mulQuaternions(this.quaternion,_A,yA),this.quaternion=yA,this._setLocalMatrixDirty(),this._model.glRedraw(),this}},{key:"rotateOnWorldAxis",value:function(e,t){return mA[0]=e[0],mA[1]=e[1],mA[2]=e[2],mA[3]=t*le.DEGTORAD,le.angleAxisToQuaternion(mA,_A),le.mulQuaternions(_A,this.quaternion,_A),this}},{key:"rotateX",value:function(e){return this.rotate(bA,e)}},{key:"rotateY",value:function(e){return this.rotate(wA,e)}},{key:"rotateZ",value:function(e){return this.rotate(BA,e)}},{key:"translate",value:function(e){return this._position[0]+=e[0],this._position[1]+=e[1],this._position[2]+=e[2],this._setLocalMatrixDirty(),this._model.glRedraw(),this}},{key:"translateX",value:function(e){return this._position[0]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}},{key:"translateY",value:function(e){return this._position[1]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}},{key:"translateZ",value:function(e){return this._position[2]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}},{key:"_setLocalMatrixDirty",value:function(){this._localMatrixDirty=!0,this._transformDirty()}},{key:"_transformDirty",value:function(){this._worldMatrixDirty=!0;for(var e=0,t=this._childTransforms.length;e<t;e++){var i=this._childTransforms[e];if(i._transformDirty(),i._meshes&&i._meshes.length>0)for(var r=i._meshes,n=0,s=r.length;n<s;n++)r[n]._transformDirty()}if(this._meshes&&this._meshes.length>0)for(var o=this._meshes,a=0,l=o.length;a<l;a++)o[a]._transformDirty()}},{key:"_buildWorldMatrix",value:function(){var e=this.matrix;if(this._parentTransform)le.mulMat4(this._parentTransform.worldMatrix,e,this._worldMatrix);else for(var t=0,i=e.length;t<i;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}},{key:"_setSubtreeAABBsDirty",value:function(e){if(e._aabbDirty=!0,e._childTransforms)for(var t=0,i=e._childTransforms.length;t<i;t++)this._setSubtreeAABBsDirty(e._childTransforms[t])}}]),e}(),CA=le.vec3(),MA=le.OBB3(),kA=le.vec4(),EA=le.vec3([1,1,1]),FA=le.vec3([0,0,0]);le.vec3([0,0,0]);var IA=le.identityQuaternion(),TA=le.identityMat4(),DA=new Uint8Array([255,255,255]),SA=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).renderOrder=n.renderOrder||0,r._dtxEnabled=r.scene.dtxEnabled&&!1!==n.dtxEnabled,r._enableVertexWelding=!1,r._enableIndexBucketing=!1,r._vboBatchingLayerScratchMemory=vs(),r._textureTranscoder=n.textureTranscoder||rA(r.scene.viewer),r._maxGeometryBatchSize=n.maxGeometryBatchSize,r._aabb=le.collapseAABB3(),r._aabbDirty=!0,r._quantizationRanges={},r._vboInstancingLayers={},r._vboBatchingLayers={},r._dtxLayers={},r._meshList=[],r.layerList=[],r._layersToFinalize=[],r._entityList=[],r._entitiesToFinalize=[],r._geometries={},r._dtxBuckets={},r._textures={},r._textureSets={},r._transforms={},r._meshes={},r._unusedMeshes={},r._entities={},r.renderFlags=new sn,r.numGeometries=0,r.numPortions=0,r.numVisibleLayerPortions=0,r.numTransparentLayerPortions=0,r.numXRayedLayerPortions=0,r.numHighlightedLayerPortions=0,r.numSelectedLayerPortions=0,r.numEdgesLayerPortions=0,r.numPickableLayerPortions=0,r.numClippableLayerPortions=0,r.numCulledLayerPortions=0,r.numEntities=0,r._numTriangles=0,r._numLines=0,r._numPoints=0,r._layersFinalized=!1,r._edgeThreshold=n.edgeThreshold||10,r._origin=le.vec3(n.origin||[0,0,0]),r._position=le.vec3(n.position||[0,0,0]),r._rotation=le.vec3(n.rotation||[0,0,0]),r._quaternion=le.vec4(n.quaternion||[0,0,0,1]),r._conjugateQuaternion=le.vec4(n.quaternion||[0,0,0,1]),n.rotation&&le.eulerToQuaternion(r._rotation,"XYZ",r._quaternion),r._scale=le.vec3(n.scale||[1,1,1]),r._worldRotationMatrix=le.mat4(),r._worldRotationMatrixConjugate=le.mat4(),r._matrix=le.mat4(),r._matrixDirty=!0,r._rebuildMatrices(),r._worldNormalMatrix=le.mat4(),le.inverseMat4(r._matrix,r._worldNormalMatrix),le.transposeMat4(r._worldNormalMatrix),(n.matrix||n.position||n.rotation||n.scale||n.quaternion)&&(r._viewMatrix=le.mat4(),r._viewNormalMatrix=le.mat4(),r._viewMatrixDirty=!0,r._matrixNonIdentity=!0),r._opacity=1,r._colorize=[1,1,1],r._saoEnabled=!1!==n.saoEnabled,r._pbrEnabled=!1!==n.pbrEnabled,r._colorTextureEnabled=!1!==n.colorTextureEnabled,r._isModel=n.isModel,r._isModel&&r.scene._registerModel(w(r)),r._onCameraViewMatrix=r.scene.camera.on("matrix",(function(){r._viewMatrixDirty=!0})),r._meshesWithDirtyMatrices=[],r._numMeshesWithDirtyMatrices=0,r._onTick=r.scene.on("tick",(function(){for(;r._numMeshesWithDirtyMatrices>0;)r._meshesWithDirtyMatrices[--r._numMeshesWithDirtyMatrices]._updateMatrix()})),r._createDefaultTextureSet(),r.visible=n.visible,r.culled=n.culled,r.pickable=n.pickable,r.clippable=n.clippable,r.collidable=n.collidable,r.castsShadow=n.castsShadow,r.receivesShadow=n.receivesShadow,r.xrayed=n.xrayed,r.highlighted=n.highlighted,r.selected=n.selected,r.edges=n.edges,r.colorize=n.colorize,r.opacity=n.opacity,r.backfaces=n.backfaces,r}return I(i,[{key:"_meshMatrixDirty",value:function(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}},{key:"_createDefaultTextureSet",value:function(){var e=new Wc({id:"defaultColorTexture",texture:new Pn({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new Wc({id:"defaultMetalRoughTexture",texture:new Pn({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new Wc({id:"defaultNormalsTexture",texture:new Pn({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),r=new Wc({id:"defaultEmissiveTexture",texture:new Pn({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),n=new Wc({id:"defaultOcclusionTexture",texture:new Pn({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=r,this._textures.defaultOcclusionTexture=n,this._textureSets.defaultTextureSet=new zc({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:r,occlusionTexture:n})}},{key:"isPerformanceModel",get:function(){return!0}},{key:"transforms",get:function(){return this._transforms}},{key:"textures",get:function(){return this._textures}},{key:"textureSets",get:function(){return this._textureSets}},{key:"meshes",get:function(){return this._meshes}},{key:"objects",get:function(){return this._entities}},{key:"origin",get:function(){return this._origin}},{key:"position",get:function(){return this._position},set:function(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"rotation",get:function(){return this._rotation},set:function(e){this._rotation.set(e||[0,0,0]),le.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"quaternion",get:function(){return this._quaternion},set:function(e){this._quaternion.set(e||[0,0,0,1]),le.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"scale",get:function(){return this._scale},set:function(e){}},{key:"matrix",get:function(){return this._rebuildMatrices(),this._matrix},set:function(e){this._matrix.set(e||TA),le.decomposeMat4(this._matrix,this._position,this._quaternion,this._scale),le.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"rotationMatrix",get:function(){return this._rebuildMatrices(),this._worldRotationMatrix}},{key:"_rebuildMatrices",value:function(){this._matrixDirty&&(le.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),le.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),le.quaternionToRotationMat4(this._conjugateQuaternion,this._worldRotationMatrixConjugate),le.scaleMat4v(this._scale,this._worldRotationMatrix),le.scaleMat4v(this._scale,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),le.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._viewMatrixDirty=!0)}},{key:"rotationMatrixConjugate",get:function(){return this._rebuildMatrices(),this._worldRotationMatrixConjugate}},{key:"_setWorldMatrixDirty",value:function(){this._matrixDirty=!0,this._aabbDirty=!0}},{key:"_transformDirty",value:function(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}},{key:"_sceneModelDirty",value:function(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(var e=0,t=this._entityList.length;e<t;e++)this._entityList[e]._sceneModelDirty()}},{key:"worldMatrix",get:function(){return this.matrix}},{key:"worldNormalMatrix",get:function(){return this._worldNormalMatrix}},{key:"_rebuildViewMatrices",value:function(){this._rebuildMatrices(),this._viewMatrixDirty&&(le.mulMat4(this.scene.camera.viewMatrix,this._matrix,this._viewMatrix),le.inverseMat4(this._viewMatrix,this._viewNormalMatrix),le.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1)}},{key:"viewMatrix",get:function(){return this._viewMatrix?(this._rebuildViewMatrices(),this._viewMatrix):this.scene.camera.viewMatrix}},{key:"viewNormalMatrix",get:function(){return this._viewNormalMatrix?(this._rebuildViewMatrices(),this._viewNormalMatrix):this.scene.camera.viewNormalMatrix}},{key:"backfaces",get:function(){return this._backfaces},set:function(e){e=!!e,this._backfaces=e,this.glRedraw()}},{key:"entityList",get:function(){return this._entityList}},{key:"isEntity",get:function(){return!0}},{key:"isModel",get:function(){return this._isModel}},{key:"isObject",get:function(){return!1}},{key:"aabb",get:function(){if(this._aabbDirty){le.collapseAABB3(this._aabb);for(var e=0,t=this._entityList.length;e<t;e++)le.expandAABB3(this._aabb,this._entityList[e].aabb);this._aabbDirty=!1}return this._aabb}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"numLines",get:function(){return this._numLines}},{key:"numPoints",get:function(){return this._numPoints}},{key:"visible",get:function(){return this.numVisibleLayerPortions>0},set:function(e){e=!1!==e,this._visible=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].visible=e;this.glRedraw()}},{key:"xrayed",get:function(){return this.numXRayedLayerPortions>0},set:function(e){e=!!e,this._xrayed=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].xrayed=e;this.glRedraw()}},{key:"highlighted",get:function(){return this.numHighlightedLayerPortions>0},set:function(e){e=!!e,this._highlighted=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].highlighted=e;this.glRedraw()}},{key:"selected",get:function(){return this.numSelectedLayerPortions>0},set:function(e){e=!!e,this._selected=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].selected=e;this.glRedraw()}},{key:"edges",get:function(){return this.numEdgesLayerPortions>0},set:function(e){e=!!e,this._edges=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].edges=e;this.glRedraw()}},{key:"culled",get:function(){return this._culled},set:function(e){e=!!e,this._culled=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].culled=e;this.glRedraw()}},{key:"clippable",get:function(){return this._clippable},set:function(e){e=!1!==e,this._clippable=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].clippable=e;this.glRedraw()}},{key:"collidable",get:function(){return this._collidable},set:function(e){e=!1!==e,this._collidable=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].collidable=e}},{key:"pickable",get:function(){return this.numPickableLayerPortions>0},set:function(e){e=!1!==e,this._pickable=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].pickable=e}},{key:"colorize",get:function(){return this._colorize},set:function(e){this._colorize=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].colorize=e}},{key:"opacity",get:function(){return this._opacity},set:function(e){this._opacity=e;for(var t=0,i=this._entityList.length;t<i;t++)this._entityList[t].opacity=e}},{key:"castsShadow",get:function(){return this._castsShadow},set:function(e){(e=!1!==e)!==this._castsShadow&&(this._castsShadow=e,this.glRedraw())}},{key:"receivesShadow",get:function(){return this._receivesShadow},set:function(e){(e=!1!==e)!==this._receivesShadow&&(this._receivesShadow=e,this.glRedraw())}},{key:"saoEnabled",get:function(){return this._saoEnabled}},{key:"pbrEnabled",get:function(){return this._pbrEnabled}},{key:"colorTextureEnabled",get:function(){return this._colorTextureEnabled}},{key:"isDrawable",get:function(){return!0}},{key:"isStateSortable",get:function(){return!1}},{key:"xrayMaterial",get:function(){return this.scene.xrayMaterial}},{key:"highlightMaterial",get:function(){return this.scene.highlightMaterial}},{key:"selectedMaterial",get:function(){return this.scene.selectedMaterial}},{key:"edgeMaterial",get:function(){return this.scene.edgeMaterial}},{key:"getPickViewMatrix",value:function(e){return this._viewMatrix?this._viewMatrix:e}},{key:"createQuantizationRange",value:function(e){void 0!==e.id&&null!==e.id?e.aabb?this.error("[createQuantizationRange] Config missing: aabb"):this._quantizationRanges[e.id]?this.error("[createQuantizationRange] QuantizationRange already created: "+e.id):this._quantizationRanges[e.id]={id:e.id,aabb:e.aabb,matrix:yo(e.aabb,le.mat4())}:this.error("[createQuantizationRange] Config missing: id")}},{key:"createGeometry",value:function(e){if(void 0!==e.id&&null!==e.id)if(this._geometries[e.id])this.error("[createGeometry] Geometry already created: "+e.id);else if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"===e.primitive||"lines"===e.primitive||"triangles"===e.primitive||"solid"===e.primitive||"surface"===e.primitive){if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("[createGeometry] Param expected: `positions`, `positionsCompressed' or 'buckets"),null;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("[createGeometry] Param expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.positionsDecodeMatrix&&e.positionsDecodeBoundary)return this.error("[createGeometry] Only one of these params expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("[createGeometry] Param expected: `uvDecodeMatrix` (required for `uvCompressed')"),null;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){var t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return this.error("[createGeometry] Param expected: indices (required for '".concat(e.primitive,"' primitive type)")),null;if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=yo(e.positionsDecodeBoundary,le.mat4())),e.positions){var i=le.collapseAABB3();e.positionsDecodeMatrix=le.mat4(),le.expandAABB3Points3(i,e.positions),e.positionsCompressed=_o(e.positions,i,e.positionsDecodeMatrix),e.aabb=i}else if(e.positionsCompressed){var r=le.collapseAABB3();e.positionsDecodeMatrix=new Float64Array(e.positionsDecodeMatrix),e.positionsCompressed=new Uint16Array(e.positionsCompressed),le.expandAABB3Points3(r,e.positionsCompressed),ft.decompressAABB(r,e.positionsDecodeMatrix),e.aabb=r}else if(e.buckets){var n=le.collapseAABB3();this._dtxBuckets[e.id]=e.buckets;for(var s=0,o=e.buckets.length;s<o;s++){var a=e.buckets[s];a.positions?le.expandAABB3Points3(n,a.positions):a.positionsCompressed&&le.expandAABB3Points3(n,a.positionsCompressed)}e.positionsDecodeMatrix&&ft.decompressAABB(n,e.positionsDecodeMatrix),e.aabb=n}if(e.colorsCompressed&&e.colorsCompressed.length>0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){for(var l=e.colors,u=new Uint8Array(l.length),c=0,A=l.length;c<A;c++)u[c]=255*l[c];e.colorsCompressed=u}if(e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=ot(e.positions,e.indices,null,5):e.edgeIndices=ot(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.uv){var h=ft.getUVBounds(e.uv),d=ft.compressUVs(e.uv,h.min,h.max);e.uvCompressed=d.quantized,e.uvDecodeMatrix=d.decodeMatrix}else e.uvCompressed&&(e.uvCompressed=new Uint16Array(e.uvCompressed),e.uvDecodeMatrix=new Float64Array(e.uvDecodeMatrix));e.normals&&(e.normals=null),this._geometries[e.id]=e,this._numTriangles+=e.indices?Math.round(e.indices.length/3):0,this.numGeometries++}else this.error("[createGeometry] Unsupported value for 'primitive': '".concat(e.primitive,"' - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'. Defaulting to 'triangles'."));else this.error("[createGeometry] Config missing: id")}},{key:"createTexture",value:function(e){var t=this,i=e.id;if(null!=i)if(this._textures[i])this.error("[createTexture] Texture already created: "+i);else{if(!e.src&&!e.image&&!e.buffers)return this.error("[createTexture] Param expected: `src`, `image' or 'buffers'"),null;var r=e.minFilter||1008;1006!==r&&1007!==r&&1008!==r&&1005!==r&&1004!==r&&(this.error("[createTexture] Unsupported value for 'minFilter' - \n supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, \n NearestMipMapLinearFilter and LinearMipmapLinearFilter. Defaulting to LinearMipmapLinearFilter."),r=1008);var n=e.magFilter||1006;1006!==n&&1003!==n&&(this.error("[createTexture] Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),n=1006);var s=e.wrapS||1e3;1001!==s&&1002!==s&&1e3!==s&&(this.error("[createTexture] Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),s=1e3);var o=e.wrapT||1e3;1001!==o&&1002!==o&&1e3!==o&&(this.error("[createTexture] Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),o=1e3);var a=e.wrapR||1e3;1001!==a&&1002!==a&&1e3!==a&&(this.error("[createTexture] Unsupported value for 'wrapR' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),a=1e3);var l=e.encoding||3e3;3e3!==l&&3001!==l&&(this.error("[createTexture] Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),l=3e3);var u=new Pn({gl:this.scene.canvas.gl,minFilter:r,magFilter:n,wrapS:s,wrapT:o,wrapR:a,encoding:l});if(e.preloadColor&&u.setPreloadColor(e.preloadColor),e.image){var c=e.image;if(c.crossOrigin="Anonymous",c.compressed){var A=c.data;u.setCompressedData({mipmaps:A,props:{format:A[0].format,minFilter:r,magFilter:n}})}else u.setImage(c,{minFilter:r,magFilter:n,wrapS:s,wrapT:o,wrapR:a,flipY:e.flipY,encoding:l})}else if(e.src){var h=e.src.split(".").pop();switch(h){case"jpeg":case"jpg":case"png":case"gif":var d=new Image;d.onload=function(){u.setImage(d,{minFilter:r,magFilter:n,wrapS:s,wrapT:o,wrapR:a,flipY:e.flipY,encoding:l}),t.glRedraw()},d.src=e.src;break;default:this._textureTranscoder?ge.loadArraybuffer(e.src,(function(e){e.byteLength?t._textureTranscoder.transcode([e],u).then((function(){t.glRedraw()})):t.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error("[createTexture] Can't create texture from 'src': ".concat(e))})):this.error("[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('".concat(h,"')"))}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,u).then((function(){t.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[i]=new Wc({id:i,texture:u})}else this.error("[createTexture] Config missing: id")}},{key:"createTextureSet",value:function(e){var t=e.id;if(null!=t){if(!this._textureSets[t]){var i,r,n,s,o;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(!(i=this._textures[e.colorTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.colorTextureId," - ensure that you create it first with createTexture()"))}else i=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(!(r=this._textures[e.metallicRoughnessTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.metallicRoughnessTextureId," - ensure that you create it first with createTexture()"))}else r=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(!(n=this._textures[e.normalsTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.normalsTextureId," - ensure that you create it first with createTexture()"))}else n=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(!(s=this._textures[e.emissiveTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.emissiveTextureId," - ensure that you create it first with createTexture()"))}else s=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(!(o=this._textures[e.occlusionTextureId]))return void this.error("[createTextureSet] Texture not found: ".concat(e.occlusionTextureId," - ensure that you create it first with createTexture()"))}else o=this._textures.defaultOcclusionTexture;var a=new zc({id:t,model:this,colorTexture:i,alphaCutoff:e.alphaCutoff,metallicRoughnessTexture:r,normalsTexture:n,emissiveTexture:s,occlusionTexture:o});return this._textureSets[t]=a,a}this.error("[createTextureSet] Texture set already created: ".concat(t))}else this.error("[createTextureSet] Config missing: id")}},{key:"createTransform",value:function(e){if(void 0!==e.id&&null!==e.id)if(this._transforms[e.id])this.error("[createTransform] SceneModel already has a transform with this ID: ".concat(e.id));else{var t;if(!e.parentTransformId||(t=this._transforms[e.parentTransformId])){var i=new PA({id:e.id,model:this,parent:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[i.id]=i,i}this.error("[createTransform] SceneModel.createTransform() config missing: id")}else this.error("[createTransform] SceneModel.createTransform() config missing: id")}},{key:"createMesh",value:function(e){if(void 0===e.id||null===e.id)return this.error("[createMesh] SceneModel.createMesh() config missing: id"),!1;if(this._meshes[e.id])return this.error("[createMesh] SceneModel already has a mesh with this ID: ".concat(e.id)),!1;if(!(void 0!==e.geometryId)){if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"!==e.primitive&&"lines"!==e.primitive&&"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)return this.error("Unsupported value for 'primitive': '".concat(primitive,"' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.")),!1;if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),!1;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),!1;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){var t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return e.indices=this._createDefaultIndices(numIndices),this.error("Param expected: indices (required for '".concat(e.primitive,"' primitive type)")),!1;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),!1;var i=!(!this._dtxEnabled||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||e.textureSetId);if(e.origin=e.origin?le.addVec3(this._origin,e.origin,le.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){var r=e.scale||EA,n=e.position||FA;e.rotation?(le.eulerToQuaternion(e.rotation,"XYZ",kA),e.meshMatrix=le.composeMat4(n,kA,r,le.mat4())):e.meshMatrix=le.composeMat4(n,e.quaternion||IA,r,le.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=yo(e.positionsDecodeBoundary,le.mat4())),i){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):DA,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){var s=le.vec3(),o=[];qt(e.positions,o,s)&&(e.positions=o,e.origin=le.addVec3(e.origin,s,s))}if(e.positions){var a=le.collapseAABB3();e.positionsDecodeMatrix=le.mat4(),le.expandAABB3Points3(a,e.positions),e.positionsCompressed=_o(e.positions,a,e.positionsDecodeMatrix),e.aabb=a}else if(e.positionsCompressed){var l=le.collapseAABB3();le.expandAABB3Points3(l,e.positionsCompressed),ft.decompressAABB(l,e.positionsDecodeMatrix),e.aabb=l}if(e.buckets){for(var u=le.collapseAABB3(),c=0,A=e.buckets.length;c<A;c++){var h=e.buckets[c];h.positions?le.expandAABB3Points3(u,h.positions):h.positionsCompressed&&le.expandAABB3Points3(u,h.positionsCompressed)}e.positionsDecodeMatrix&&ft.decompressAABB(u,e.positionsDecodeMatrix),e.aabb=u}e.meshMatrix&&(le.AABB3ToOBB3(e.aabb,MA),le.transformOBB3(e.meshMatrix,MA),le.OBB3ToAABB3(MA,e.aabb)),e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=ot(e.positions,e.indices,null,2):e.edgeIndices=ot(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.buckets||(e.buckets=RA(e,this._enableVertexWelding&&this._enableIndexBucketing))}else{if(e.type=1,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):[255,255,255],e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.positions){var d=[];qt(e.positions,d,CA)&&(e.positions=d,e.origin=le.addVec3(e.origin,CA,le.vec3()))}if(e.positions){var p=le.collapseAABB3();e.meshMatrix&&(le.transformPositions3(e.meshMatrix,e.positions,e.positions),e.meshMatrix=null),le.expandAABB3Points3(p,e.positions),e.aabb=p}else{var f=le.collapseAABB3();le.expandAABB3Points3(f,e.positionsCompressed),ft.decompressAABB(f,e.positionsDecodeMatrix),e.aabb=f}if(e.meshMatrix&&(le.AABB3ToOBB3(e.aabb,MA),le.transformOBB3(e.meshMatrix,MA),le.OBB3ToAABB3(MA,e.aabb)),e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=ot(e.positions,e.indices,null,2):e.edgeIndices=ot(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId],!e.textureSet))return this.error("[createMesh] Texture set not found: ".concat(e.textureSetId," - ensure that you create it first with createTextureSet()")),!1}}else{if(e.positions||e.positionsCompressed||e.indices||e.edgeIndices||e.normals||e.normalsCompressed||e.uv||e.uvCompressed||e.positionsDecodeMatrix)return this.error("Mesh geometry parameters not expected when instancing a geometry (not expected: positions, positionsCompressed, indices, edgeIndices, normals, normalsCompressed, uv, uvCompressed, positionsDecodeMatrix)"),!1;if(e.geometry=this._geometries[e.geometryId],!e.geometry)return this.error("[createMesh] Geometry not found: ".concat(e.geometryId," - ensure that you create it first with createGeometry()")),!1;if(e.origin=e.origin?le.addVec3(this._origin,e.origin,le.vec3()):this._origin,e.positionsDecodeMatrix=e.geometry.positionsDecodeMatrix,e.transformId){if(e.transform=this._transforms[e.transformId],!e.transform)return this.error("[createMesh] Transform not found: ".concat(e.transformId," - ensure that you create it first with createTransform()")),!1;e.aabb=e.geometry.aabb}else{if(e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){var v=e.scale||EA,g=e.position||FA;e.rotation?(le.eulerToQuaternion(e.rotation,"XYZ",kA),e.meshMatrix=le.composeMat4(g,kA,v,le.mat4())):e.meshMatrix=le.composeMat4(g,e.quaternion||IA,v,le.mat4())}le.AABB3ToOBB3(e.geometry.aabb,MA),le.transformOBB3(e.meshMatrix,MA),e.aabb=le.OBB3ToAABB3(MA,le.AABB3())}if(!(!this._dtxEnabled||"triangles"!==e.geometry.primitive&&"solid"!==e.geometry.primitive&&"surface"!==e.geometry.primitive||e.textureSetId)){e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):DA,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255;var m=this._dtxBuckets[e.geometryId];m||(m=RA(e.geometry,this._enableVertexWelding,this._enableIndexBucketing),this._dtxBuckets[e.geometryId]=m),e.buckets=m}else e.type=0,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):DA,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId])}return e.numPrimitives=this._getNumPrimitives(e),this._createMesh(e)}},{key:"_createDefaultIndices",value:function(e){for(var t=[],i=0;i<e;i++)t.push(i);return t}},{key:"_createMesh",value:function(e){var t=new ds(this,e.id,e.color,e.opacity,e.transform,e.textureSet);t.pickId=this.scene._renderer.getPickID(t);var i=t.pickId,r=i>>24&255,n=i>>16&255,s=i>>8&255,o=255&i;switch(e.pickColor=new Uint8Array([o,s,n,r]),e.solid="solid"===e.primitive,t.origin=le.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),t.numPrimitives=e.numPrimitives,this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}},{key:"_getNumPrimitives",value:function(e){var t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(var i=0,r=e.buckets.length;i<r;i++)t+=e.buckets[i].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/3);case"points":switch(e.type){case 2:for(var n=0,s=e.buckets.length;n<s;n++)t+=e.buckets[n].positionsCompressed.length;break;case 1:t+=e.positions?e.positions.length:e.positionsCompressed.length;break;case 0:var o=e.geometry;t+=o.positions?o.positions.length:o.positionsCompressed.length}return Math.round(t);case"lines":case"line-strip":switch(e.type){case 2:for(var a=0,l=e.buckets.length;a<l;a++)t+=e.buckets[a].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/2)}return 0}},{key:"_getDTXLayer",value:function(e){var t=e.origin,i=e.geometry?e.geometry.primitive:e.primitive,r=".".concat(i,".").concat(Math.round(t[0]),".").concat(Math.round(t[1]),".").concat(Math.round(t[2])),n=this._dtxLayers[r];if(n){if(n.canCreatePortion(e))return n;delete this._dtxLayers[r],n=null}switch(i){case"triangles":case"solid":case"surface":n=new Gc(this,{layerIndex:0,origin:t,primitive:i});break;case"lines":n=new yu(this,{layerIndex:0,origin:t,primitive:i});break;default:return}return this._dtxLayers[r]=n,this.layerList.push(n),this._layersToFinalize.push(n),n}},{key:"_getVBOBatchingLayer",value:function(e){var t=this,i=e.origin;e.renderLayer;var r=e.positionsDecodeMatrix||e.positionsDecodeBoundary?this._createHashStringFromMatrix(e.positionsDecodeMatrix||e.positionsDecodeBoundary):"-",n=e.textureSetId||"-",s="".concat(Math.round(i[0]),".").concat(Math.round(i[1]),".").concat(Math.round(i[2]),".").concat(e.primitive,".").concat(r,".").concat(n),o=this._vboBatchingLayers[s];if(o)return o;for(var a=e.textureSet;!o;){switch(e.primitive){case"triangles":case"solid":case"surface":o=new Do({model:t,textureSet:a,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:i,maxGeometryBatchSize:this._maxGeometryBatchSize,solid:"solid"===e.primitive,autoNormals:!0,primitive:e.primitive});break;case"lines":o=new ja({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:i,maxGeometryBatchSize:this._maxGeometryBatchSize,primitive:e.primitive});break;case"points":o=new Fl({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:i,maxGeometryBatchSize:this._maxGeometryBatchSize,primitive:e.primitive})}var l=e.positionsCompressed?e.positionsCompressed.length:e.positions.length;("points"===e.primitive?o.canCreatePortion(l):o.canCreatePortion(l,e.indices.length))||(o.finalize(),delete this._vboBatchingLayers[s],o=null)}return this._vboBatchingLayers[s]=o,this.layerList.push(o),this._layersToFinalize.push(o),o}},{key:"_createHashStringFromMatrix",value:function(e){for(var t=e.join(""),i=0,r=0;r<t.length;r++){i=(i<<5)-i+t.charCodeAt(r),i|=0}return(i>>>0).toString(16)}},{key:"_getVBOInstancingLayer",value:function(e){var t=this,i=e.origin,r=e.textureSetId||"-",n=e.geometryId,s="".concat(Math.round(i[0]),".").concat(Math.round(i[1]),".").concat(Math.round(i[2]),".").concat(r,".").concat(n),o=this._vboInstancingLayers[s];if(o)return o;for(var a=e.textureSet,l=e.geometry;!o;)switch(l.primitive){case"triangles":case"surface":o=new xa({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":o=new xa({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":o=new ul({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":o=new tu({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[s]=o,this.layerList.push(o),this._layersToFinalize.push(o),o}},{key:"createEntity",value:function(e){if(void 0===e.id?e.id=le.createUUID():this.scene.components[e.id]&&(this.error("Scene already has a Component with this ID: ".concat(e.id," - will assign random ID")),e.id=le.createUUID()),void 0!==e.meshIds){var t=0;return this._visible&&!1!==e.visible&&(t|=gs),this._pickable&&!1!==e.pickable&&(t|=_s),this._culled&&!1!==e.culled&&(t|=ms),this._clippable&&!1!==e.clippable&&(t|=ys),this._collidable&&!1!==e.collidable&&(t|=bs),this._edges&&!1!==e.edges&&(t|=Ps),this._xrayed&&!1!==e.xrayed&&(t|=ws),this._highlighted&&!1!==e.highlighted&&(t|=Bs),this._selected&&!1!==e.selected&&(t|=xs),e.flags=t,this._createEntity(e)}this.error("Config missing: meshIds")}},{key:"_createEntity",value:function(e){for(var t=[],i=0,r=e.meshIds.length;i<r;i++){var n=e.meshIds[i],s=this._meshes[n];s?s.parent?this.error('Mesh with ID "'.concat(n,'" already belongs to object with ID "').concat(s.parent.id,'" - ignoring this mesh')):(t.push(s),delete this._unusedMeshes[n]):this.error('Mesh with this ID not found: "'.concat(n,'" - ignoring this mesh'))}var o=new gA(this,e.isObject,e.id,t,e.flags,!0);return this._entityList.push(o),this._entities[e.id]=o,this._entitiesToFinalize.push(o),this.numEntities++,o}},{key:"preFinalize",value:function(){if(this.destroyed)return!1;if(0===this._layersToFinalize.length)return!1;this._createDummyEntityForUnusedMeshes();for(var e=0,t=this._layersToFinalize.length;e<t;e++){this._layersToFinalize[e].finalize()}this._vboBatchingLayers={},this._vboInstancingLayers={},this._dtxLayers={},this._layersToFinalize=[];for(var i=0,r=this._entitiesToFinalize.length;i<r;i++){this._entitiesToFinalize[i]._finalize()}for(var n=0,s=this._entitiesToFinalize.length;n<s;n++){this._entitiesToFinalize[n]._finalize2()}this._entitiesToFinalize=[],this.scene._aabbDirty=!0,this._viewMatrixDirty=!0,this._matrixDirty=!0,this._aabbDirty=!0,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.position=this._position,this.layerList.sort((function(e,t){return e.sortId<t.sortId?-1:e.sortId>t.sortId?1:0}));for(var o=0,a=this.layerList.length;o<a;o++){this.layerList[o].layerIndex=o}this.glRedraw(),this._layersFinalized=!0}},{key:"finalize",value:function(){this.destroyed||(this.preFinalize(),this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={})}},{key:"stateSortCompare",value:function(e,t){}},{key:"rebuildRenderFlags",value:function(){this.renderFlags.reset(),this._updateRenderFlagsVisibleLayers(),this.renderFlags.numLayers>0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}},{key:"_updateRenderFlagsVisibleLayers",value:function(){var e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(var t=0,i=this.layerList.length;t<i;t++){var r=this.layerList[t];this._getActiveSectionPlanesForLayer(r)&&(e.visibleLayers[e.numVisibleLayers++]=t)}}},{key:"_createDummyEntityForUnusedMeshes",value:function(){var e=Object.keys(this._unusedMeshes);if(e.length>0){var t="".concat(this.id,"-").concat(le.createUUID());this.warn('Creating dummy SceneModelEntity "'.concat(t,'" for unused SceneMeshes: [').concat(e.join(","),"]")),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}},{key:"_getActiveSectionPlanesForLayer",value:function(e){var t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,r=i.length,n=e.layerIndex*r;if(r>0)for(var s=0;s<r;s++){i[s].active?(t.sectionPlanesActivePerLayer[n+s]=!0,t.sectioned=!0):t.sectionPlanesActivePerLayer[n+s]=!1}return!0}},{key:"_updateRenderFlags",value:function(){if(0!==this.numVisibleLayerPortions&&this.numCulledLayerPortions!==this.numPortions){var e=this.renderFlags;if(e.colorOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){var t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0)this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.edgesTransparent=!0));if(this.numSelectedLayerPortions>0){var i=this.scene.selectedMaterial._state;i.fill&&(i.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),i.edges&&(i.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){var r=this.scene.highlightMaterial._state;r.fill&&(r.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),r.edges&&(r.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}},{key:"drawColorOpaque",value:function(e,t){for(var i=this.renderFlags,r=0,n=i.visibleLayers.length;r<n;r++){var s=i.visibleLayers[r];this.layerList[s].drawColorOpaque(i,e)}}},{key:"drawColorTransparent",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawColorTransparent(t,e)}}},{key:"drawDepth",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawDepth(t,e)}}},{key:"drawNormals",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawNormals(t,e)}}},{key:"drawSilhouetteXRayed",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawSilhouetteXRayed(t,e)}}},{key:"drawSilhouetteHighlighted",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawSilhouetteHighlighted(t,e)}}},{key:"drawSilhouetteSelected",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawSilhouetteSelected(t,e)}}},{key:"drawEdgesColorOpaque",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawEdgesColorOpaque(t,e)}}},{key:"drawEdgesColorTransparent",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawEdgesColorTransparent(t,e)}}},{key:"drawEdgesXRayed",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawEdgesXRayed(t,e)}}},{key:"drawEdgesHighlighted",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawEdgesHighlighted(t,e)}}},{key:"drawEdgesSelected",value:function(e){for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawEdgesSelected(t,e)}}},{key:"drawOcclusion",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawOcclusion(t,e)}}},{key:"drawShadow",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawShadow(t,e)}}},{key:"setPickMatrices",value:function(e,t){if(0!==this._numVisibleLayerPortions)for(var i=this.renderFlags,r=0,n=i.visibleLayers.length;r<n;r++){var s=i.visibleLayers[r],o=this.layerList[s];o.setPickMatrices&&o.setPickMatrices(e,t)}}},{key:"drawPickMesh",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawPickMesh(t,e)}}},{key:"drawPickDepths",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawPickDepths(t,e)}}},{key:"drawPickNormals",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i];this.layerList[n].drawPickNormals(t,e)}}},{key:"drawSnapInit",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i],s=this.layerList[n];s.drawSnapInit&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,s.drawSnapInit(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}},{key:"drawSnap",value:function(e){if(0!==this.numVisibleLayerPortions)for(var t=this.renderFlags,i=0,r=t.visibleLayers.length;i<r;i++){var n=t.visibleLayers[i],s=this.layerList[n];s.drawSnap&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,s.drawSnap(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}},{key:"destroy",value:function(){for(var e in this._vboBatchingLayers)this._vboBatchingLayers.hasOwnProperty(e)&&this._vboBatchingLayers[e].destroy();for(var t in this._vboBatchingLayers={},this._vboInstancingLayers)this._vboInstancingLayers.hasOwnProperty(t)&&this._vboInstancingLayers[t].destroy();this._vboInstancingLayers={},this.scene.camera.off(this._onCameraViewMatrix),this.scene.off(this._onTick);for(var r=0,n=this.layerList.length;r<n;r++)this.layerList[r].destroy();this.layerList=[];for(var s=0,o=this._entityList.length;s<o;s++)this._entityList[s]._destroy();this._layersToFinalize={},this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._meshes={},this._entities={},this.scene._aabbDirty=!0,this._isModel&&this.scene._deregisterModel(this),0!==fs&&0==--fs&&ps._clear(),v(x(i.prototype),"destroy",this).call(this)}}]),i}();function RA(e,t,i){var r,n,s,o;if(t||i){var a=C(aA({positionsCompressed:e.positionsCompressed,indices:e.indices,edgeIndices:e.edgeIndices}),3);r=a[0],n=a[1],s=a[2]}else r=e.positionsCompressed,n=e.indices,s=e.edgeIndices;i?o=function(e,t){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=e.positionsCompressed||[],n=cA(e.indices||[],t),s=dA(e.edgeIndices||[]);function o(e,t){if(e>t){var i=e;e=t,t=i}function r(i,r){return i!==e?e-i:r!==t?t-r:0}for(var n=0,o=(s.length>>1)-1;n<=o;){var a=o+n>>1,l=r(s[2*a],s[2*a+1]);if(l>0)n=a+1;else{if(!(l<0))return a;o=a-1}}return-n-1}var a=new Int32Array(s.length/2);a.fill(0);var l=r.length/3;if(l>8*(1<<t))return[e];var u=new Int32Array(l);u.fill(-1);var c=[];function A(){u.fill(-1);var e={positionsCompressed:[],indices:[],edgeIndices:[],maxNumPositions:(1<<t)-t,numPositions:0,bucketNumber:c.length};return c.push(e),e}for(var h=A(),d=0,p=n.length;d<p;d+=3){var f=0,v=n[d],g=n[d+1],m=n[d+2];if(-1===u[v]&&f++,-1===u[g]&&f++,-1===u[m]&&f++,f+h.numPositions>h.maxNumPositions&&(h=A()),h.bucketNumber>8)return[e];-1===u[v]&&(u[v]=h.numPositions++,h.positionsCompressed.push(r[3*v]),h.positionsCompressed.push(r[3*v+1]),h.positionsCompressed.push(r[3*v+2])),-1===u[g]&&(u[g]=h.numPositions++,h.positionsCompressed.push(r[3*g]),h.positionsCompressed.push(r[3*g+1]),h.positionsCompressed.push(r[3*g+2])),-1===u[m]&&(u[m]=h.numPositions++,h.positionsCompressed.push(r[3*m]),h.positionsCompressed.push(r[3*m+1]),h.positionsCompressed.push(r[3*m+2])),h.indices.push(u[v]),h.indices.push(u[g]),h.indices.push(u[m]);var _=void 0;(_=o(v,g))>=0&&0===a[_]&&(a[_]=1,h.edgeIndices.push(u[s[2*_]]),h.edgeIndices.push(u[s[2*_+1]])),(_=o(v,m))>=0&&0===a[_]&&(a[_]=1,h.edgeIndices.push(u[s[2*_]]),h.edgeIndices.push(u[s[2*_+1]])),(_=o(g,m))>=0&&0===a[_]&&(a[_]=1,h.edgeIndices.push(u[s[2*_]]),h.edgeIndices.push(u[s[2*_+1]]))}var y=t/8*2,b=t/8,w=2*r.length+(n.length+s.length)*y,B=0;return r.length,c.forEach((function(e){B+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*b,e.positionsCompressed.length})),B>w?[e]:(i&&pA(c,e),c)}({positionsCompressed:r,indices:n,edgeIndices:s},r.length/3>65536?16:8):o=[{positionsCompressed:r,indices:n,edgeIndices:s}];return o}var UA=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(E(this,i),(r=t.call(this,e,n))._positions=n.positions||[],n.indices)r._indices=n.indices;else{r._indices=[];for(var s=0,o=r._positions.length/3-1;s<o;s+=2)r._indices.push(s),r._indices.push(s+1)}return r._color=n.color||[1,1,1],r._opacity=n.opacity||1,r._sceneModel=new SA(w(r),{isModel:!1}),r._sceneModel.createMesh({id:"linesMesh",primitive:"lines",positions:r._positions,indices:r._indices,color:r._color,opacity:r._opacity}),r._sceneModel.createEntity({meshIds:["linesMesh"],visible:n.visible,clippable:n.clippable,collidable:n.collidable}),r._sceneModel.finalize(),r.scene._lineSetCreated(w(r)),r}return I(i,[{key:"visible",get:function(){return this._sceneModel.visible},set:function(e){this._sceneModel.visible=e}},{key:"positions",get:function(){return this._positions}},{key:"indices",get:function(){return this._indices}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this.scene._lineSetDestroyed(this)}}]),i}(),LA=function(e){m(i,Ie);var t=y(i);function i(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),t.call(this,e,r)}return I(i,[{key:"type",get:function(){return"Light"}},{key:"isLight",get:function(){return!0}}]),i}(),OA=function(e){m(i,LA);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state={type:"ambient",color:le.vec3([.7,.7,.7]),intensity:1},r.color=n.color,r.intensity=n.intensity,r.scene._lightCreated(w(r)),r}return I(i,[{key:"type",get:function(){return"AmbientLight"}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this.scene._lightDestroyed(this)}}]),i}(),NA=function(){function e(t,i,r){E(this,e),r=r||{},this.gl=i,this.allocated=!1,this.canvas=t,this.buffer=null,this.bound=!1,this.size=r.size,this._hasDepthTexture=!!r.depthTexture}return I(e,[{key:"setSize",value:function(e){this.size=e}},{key:"webglContextRestored",value:function(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}},{key:"bind",value:function(){if(this._touch.apply(this,arguments),!this.bound){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}}},{key:"createTexture",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=this.gl,n=r.createTexture();return r.bindTexture(r.TEXTURE_2D,n),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),i?r.texStorage2D(r.TEXTURE_2D,1,i,e,t):r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null),n}},{key:"_touch",value:function(){var e,t,i=this,r=this.gl;if(this.size?(e=this.size[0],t=this.size[1]):(e=r.drawingBufferWidth,t=r.drawingBufferHeight),this.buffer){if(this.buffer.width===e&&this.buffer.height===t)return;this.buffer.textures.forEach((function(e){return r.deleteTexture(e)})),r.deleteFramebuffer(this.buffer.framebuf),r.deleteRenderbuffer(this.buffer.renderbuf)}for(var n,s=[],o=arguments.length,a=new Array(o),l=0;l<o;l++)a[l]=arguments[l];a.length>0?s.push.apply(s,f(a.map((function(r){return i.createTexture(e,t,r)})))):s.push(this.createTexture(e,t)),this._hasDepthTexture&&(n=r.createTexture(),r.bindTexture(r.TEXTURE_2D,n),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texImage2D(r.TEXTURE_2D,0,r.DEPTH_COMPONENT32F,e,t,0,r.DEPTH_COMPONENT,r.FLOAT,null));var u=r.createRenderbuffer();r.bindRenderbuffer(r.RENDERBUFFER,u),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_COMPONENT32F,e,t);var c=r.createFramebuffer();r.bindFramebuffer(r.FRAMEBUFFER,c);for(var A=0;A<s.length;A++)r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+A,r.TEXTURE_2D,s[A],0);if(a.length>0&&r.drawBuffers(s.map((function(e,t){return r.COLOR_ATTACHMENT0+t}))),this._hasDepthTexture?r.framebufferTexture2D(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.TEXTURE_2D,n,0):r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,u),r.bindTexture(r.TEXTURE_2D,null),r.bindRenderbuffer(r.RENDERBUFFER,null),r.bindFramebuffer(r.FRAMEBUFFER,null),r.bindFramebuffer(r.FRAMEBUFFER,c),!r.isFramebuffer(c))throw"Invalid framebuffer";r.bindFramebuffer(r.FRAMEBUFFER,null);var h=r.checkFramebufferStatus(r.FRAMEBUFFER);switch(h){case r.FRAMEBUFFER_COMPLETE:break;case r.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case r.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+h}this.buffer={framebuf:c,renderbuf:u,texture:s[0],textures:s,depthTexture:n,width:e,height:t},this.bound=!1}},{key:"clear",value:function(){if(!this.bound)throw"Render buffer not bound";var e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}},{key:"read",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:Uint8Array,s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:4,o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,u=new n(s),c=this.gl;return c.readBuffer(c.COLOR_ATTACHMENT0+o),c.readPixels(a,l,1,1,i||c.RGBA,r||c.UNSIGNED_BYTE,u,0),u}},{key:"readArray",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Uint8Array,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:4,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,s=new i(this.buffer.width*this.buffer.height*r),o=this.gl;return o.readBuffer(o.COLOR_ATTACHMENT0+n),o.readPixels(0,0,this.buffer.width,this.buffer.height,e||o.RGBA,t||o.UNSIGNED_BYTE,s,0),s}},{key:"readImageAsCanvas",value:function(){var e=this.gl,t=this._getImageDataCache(),i=t.pixelData,r=t.canvas,n=t.imageData,s=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);for(var o=this.buffer.width,a=this.buffer.height,l=a/2|0,u=4*o,c=new Uint8Array(4*o),A=0;A<l;++A){var h=A*u,d=(a-A-1)*u;c.set(i.subarray(h,h+u)),i.copyWithin(h,d,d+u),i.set(c,d)}return n.data.set(i),s.putImageData(n,0,0),r}},{key:"readImage",value:function(e){var t=this.gl,i=this._getImageDataCache(),r=i.pixelData,n=i.canvas,s=i.imageData,o=i.context,a=this.buffer,l=a.width,u=a.height;t.readPixels(0,0,l,u,t.RGBA,t.UNSIGNED_BYTE,r),s.data.set(r),o.putImageData(s,0,0),o.save(),o.globalCompositeOperation="copy",o.scale(1,-1),o.drawImage(n,0,-u,l,u),o.restore();var c=e.format||"png";return"jpeg"!==c&&"png"!==c&&"bmp"!==c&&(console.error("Unsupported image format: '"+c+"' - supported types are 'jpeg', 'bmp' and 'png' - defaulting to 'png'"),c="png"),n.toDataURL("image/".concat(c))}},{key:"_getImageDataCache",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Uint8Array,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,i=this.buffer.width,r=this.buffer.height,n=this._imageDataCache;if(n&&(n.width===i&&n.height===r||(this._imageDataCache=null,n=null)),!n){var s=document.createElement("canvas"),o=s.getContext("2d");s.width=i,s.height=r,n={pixelData:new e(i*r*t),canvas:s,context:o,imageData:o.createImageData(i,r),width:i,height:r},this._imageDataCache=n}return n.context.resetTransform(),n}},{key:"unbind",value:function(){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),this.bound=!1}},{key:"getTexture",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=this;return this._texture||(this._texture={renderBuffer:this,bind:function(i){return!(!t.buffer||!t.buffer.textures[e])&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),t.gl.bindTexture(t.gl.TEXTURE_2D,t.buffer.textures[e]),!0)},unbind:function(i){t.buffer&&t.buffer.textures[e]&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),t.gl.bindTexture(t.gl.TEXTURE_2D,null))}})}},{key:"hasDepthTexture",value:function(){return this._hasDepthTexture}},{key:"getDepthTexture",value:function(){if(!this._hasDepthTexture)return null;var e=this;return this._depthTexture||(this._dethTexture={renderBuffer:this,bind:function(t){return!(!e.buffer||!e.buffer.depthTexture)&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,e.buffer.depthTexture),!0)},unbind:function(t){e.buffer&&e.buffer.depthTexture&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,null))}})}},{key:"destroy",value:function(){if(this.allocated){var e=this.gl;this.buffer.textures.forEach((function(t){return e.deleteTexture(t)})),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}]),e}(),VA=function(e){m(i,LA);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E(this,i),(r=t.call(this,e,n))._shadowRenderBuf=null,r._shadowViewMatrix=null,r._shadowProjMatrix=null,r._shadowViewMatrixDirty=!0,r._shadowProjMatrixDirty=!0;var s=r.scene.camera,o=r.scene.canvas;return r._onCameraViewMatrix=s.on("viewMatrix",(function(){r._shadowViewMatrixDirty=!0})),r._onCameraProjMatrix=s.on("projMatrix",(function(){r._shadowProjMatrixDirty=!0})),r._onCanvasBoundary=o.on("boundary",(function(){r._shadowProjMatrixDirty=!0})),r._state=new nt({type:"dir",dir:le.vec3([1,1,1]),color:le.vec3([.7,.7,.8]),intensity:1,space:n.space||"view",castsShadow:!1,getShadowViewMatrix:function(){if(r._shadowViewMatrixDirty){r._shadowViewMatrix||(r._shadowViewMatrix=le.identityMat4());var e=r.scene.camera,t=r._state.dir,i=e.look,n=[i[0]-t[0],i[1]-t[1],i[2]-t[2]];le.lookAtMat4v(n,i,[0,1,0],r._shadowViewMatrix),r._shadowViewMatrixDirty=!1}return r._shadowViewMatrix},getShadowProjMatrix:function(){return r._shadowProjMatrixDirty&&(r._shadowProjMatrix||(r._shadowProjMatrix=le.identityMat4()),le.orthoMat4c(-40,40,-40,40,-40,80,r._shadowProjMatrix),r._shadowProjMatrixDirty=!1),r._shadowProjMatrix},getShadowRenderBuf:function(){return r._shadowRenderBuf||(r._shadowRenderBuf=new NA(r.scene.canvas.canvas,r.scene.canvas.gl,{size:[1024,1024]})),r._shadowRenderBuf}}),r.dir=n.dir,r.color=n.color,r.intensity=n.intensity,r.castsShadow=n.castsShadow,r.scene._lightCreated(w(r)),r}return I(i,[{key:"type",get:function(){return"DirLight"}},{key:"dir",get:function(){return this._state.dir},set:function(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}},{key:"castsShadow",get:function(){return this._state.castsShadow},set:function(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}},{key:"destroy",value:function(){var e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),v(x(i.prototype),"destroy",this).call(this),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}]),i}(),QA=function(e){m(i,LA);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E(this,i);var s=w(r=t.call(this,e,n));r._shadowRenderBuf=null,r._shadowViewMatrix=null,r._shadowProjMatrix=null,r._shadowViewMatrixDirty=!0,r._shadowProjMatrixDirty=!0;var o=r.scene.camera,a=r.scene.canvas;return r._onCameraViewMatrix=o.on("viewMatrix",(function(){r._shadowViewMatrixDirty=!0})),r._onCameraProjMatrix=o.on("projMatrix",(function(){r._shadowProjMatrixDirty=!0})),r._onCanvasBoundary=a.on("boundary",(function(){r._shadowProjMatrixDirty=!0})),r._state=new nt({type:"point",pos:le.vec3([1,1,1]),color:le.vec3([.7,.7,.8]),intensity:1,attenuation:[0,0,0],space:n.space||"view",castsShadow:!1,getShadowViewMatrix:function(){if(s._shadowViewMatrixDirty){s._shadowViewMatrix||(s._shadowViewMatrix=le.identityMat4());var e=s._state.pos,t=o.look,i=o.up;le.lookAtMat4v(e,t,i,s._shadowViewMatrix),s._shadowViewMatrixDirty=!1}return s._shadowViewMatrix},getShadowProjMatrix:function(){if(s._shadowProjMatrixDirty){s._shadowProjMatrix||(s._shadowProjMatrix=le.identityMat4());var e=s.scene.canvas.canvas;le.perspectiveMat4(Math.PI/180*70,e.clientWidth/e.clientHeight,.1,500,s._shadowProjMatrix),s._shadowProjMatrixDirty=!1}return s._shadowProjMatrix},getShadowRenderBuf:function(){return s._shadowRenderBuf||(s._shadowRenderBuf=new NA(s.scene.canvas.canvas,s.scene.canvas.gl,{size:[1024,1024]})),s._shadowRenderBuf}}),r.pos=n.pos,r.color=n.color,r.intensity=n.intensity,r.constantAttenuation=n.constantAttenuation,r.linearAttenuation=n.linearAttenuation,r.quadraticAttenuation=n.quadraticAttenuation,r.castsShadow=n.castsShadow,r.scene._lightCreated(w(r)),r}return I(i,[{key:"type",get:function(){return"PointLight"}},{key:"pos",get:function(){return this._state.pos},set:function(e){this._state.pos.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}},{key:"constantAttenuation",get:function(){return this._state.attenuation[0]},set:function(e){this._state.attenuation[0]=e||0,this.glRedraw()}},{key:"linearAttenuation",get:function(){return this._state.attenuation[1]},set:function(e){this._state.attenuation[1]=e||0,this.glRedraw()}},{key:"quadraticAttenuation",get:function(){return this._state.attenuation[2]},set:function(e){this._state.attenuation[2]=e||0,this.glRedraw()}},{key:"castsShadow",get:function(){return this._state.castsShadow},set:function(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}},{key:"destroy",value:function(){var e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),v(x(i.prototype),"destroy",this).call(this),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}]),i}();function HA(e){return 0==(e&e-1)}function jA(e){--e;for(var t=1;t<32;t<<=1)e|=e>>t;return e+1}var GA=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E(this,i);var s=(r=t.call(this,e,n)).scene.canvas.gl;return r._state=new nt({texture:new Pn({gl:s,target:s.TEXTURE_CUBE_MAP}),flipY:r._checkFlipY(n.minFilter),encoding:r._checkEncoding(n.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),r._src=n.src,r._images=[],r._loadSrc(n.src),he.memory.textures++,r}return I(i,[{key:"type",get:function(){return"CubeTexture"}},{key:"_checkFlipY",value:function(e){return!!e}},{key:"_checkEncoding",value:function(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}},{key:"_webglContextRestored",value:function(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}},{key:"_loadSrc",value:function(e){var t=this,i=this.scene.canvas.gl;this._images=[];for(var r=!1,n=0,s=function(s){var o,a,l=new Image;l.onload=(o=l,a=s,function(){if(!r&&(o=function(e){if(!HA(e.width)||!HA(e.height)){var t=document.createElement("canvas");t.width=jA(e.width),t.height=jA(e.height),t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}(o),t._images[a]=o,6==++n)){var e=t._state.texture;e||(e=new Pn({gl:i,target:i.TEXTURE_CUBE_MAP}),t._state.texture=e),e.setImage(t._images,t._state),t.fire("loaded",t._src,!1),t.glRedraw()}}),l.onerror=function(){r=!0},l.src=e[s]},o=0;o<e.length;o++)s(o)}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.texture&&this._state.texture.destroy(),he.memory.textures--,this._state.destroy()}}]),i}(),zA=function(e){m(i,GA);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).scene._lightsState.addReflectionMap(r._state),r.scene._reflectionMapCreated(w(r)),r}return I(i,[{key:"type",get:function(){return"ReflectionMap"}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this.scene._reflectionMapDestroyed(this)}}]),i}(),WA=function(e){m(i,GA);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).scene._lightMapCreated(w(r)),r}return I(i,[{key:"type",get:function(){return"LightMap"}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this.scene._lightMapDestroyed(this)}}]),i}(),XA=le.vec4(),KA=le.vec4(),ZA=function(e){m(i,Ie);var t=y(i);function i(e,r){var n;return E(this,i),(n=t.call(this,e,r))._entity=null,n._visible=null,n._worldPos=le.vec3(),n._origin=le.vec3(),n._rtcPos=le.vec3(),n._viewPos=le.vec3(),n._canvasPos=le.vec2(),n._occludable=!1,n._onCameraViewMatrix=n.scene.camera.on("matrix",(function(){n._viewPosDirty=!0,n._needUpdate()})),n._onCameraProjMatrix=n.scene.camera.on("projMatrix",(function(){n._canvasPosDirty=!0,n._needUpdate()})),n._onEntityDestroyed=null,n._onEntityModelDestroyed=null,n._renderer.addMarker(w(n)),n.entity=r.entity,n.worldPos=r.worldPos,n.occludable=r.occludable,n}return I(i,[{key:"_update",value:function(){if(this._viewPosDirty&&(le.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){XA.set(this._viewPos),XA[3]=1,le.transformPoint4(this.scene.camera.projMatrix,XA,KA);var e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+KA[0]/KA[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-KA[1]/KA[3])*e[3]/2),this._canvasPosDirty=!1,this.fire("canvasPos",this._canvasPos)}}},{key:"_setVisible",value:function(e){this._visible,this._visible=e,this.fire("visible",this._visible)}},{key:"entity",get:function(){return this._entity},set:function(e){var t=this;this._entity!==e&&(this._cleanupDestroyedHandlers(),this._entity=e,this._entity&&(this._entity.isSceneModelEntity?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(function(){t._entity=null,t._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.on("destroyed",(function(){t._entity=null,t._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0))}},{key:"occludable",get:function(){return this._occludable},set:function(e){(e=!!e)!==this._occludable&&(this._occludable=e,this._occludable&&this._renderer.markerWorldPosUpdated(this))}},{key:"worldPos",get:function(){return this._worldPos},set:function(e){this._worldPos.set(e||[0,0,0]),Yt(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}},{key:"origin",get:function(){return this._origin}},{key:"rtcPos",get:function(){return this._rtcPos}},{key:"viewPos",get:function(){return this._update(),this._viewPos}},{key:"canvasPos",get:function(){return this._update(),this._canvasPos}},{key:"visible",get:function(){return!!this._visible}},{key:"destroy",value:function(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._cleanupDestroyedHandlers(),this._renderer.removeMarker(this),v(x(i.prototype),"destroy",this).call(this)}},{key:"_cleanupDestroyedHandlers",value:function(){this._entity&&(null!==this._onEntityDestroyed&&(this._entity.model?this._entity.model.off(this._onEntityDestroyed):this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model&&this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null))}}]),i}(),JA=function(e){m(i,ZA);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,{entity:n.entity,occludable:n.occludable,worldPos:n.worldPos}))._occluded=!1,r._visible=!0,r._src=null,r._image=null,r._pos=le.vec3(),r._origin=le.vec3(),r._rtcPos=le.vec3(),r._dir=le.vec3(),r._size=1,r._imageSize=le.vec2(),r._texture=new In(w(r),{src:n.src}),r._geometry=new mt(w(r),{primitive:"triangles",positions:[3,3,0,-3,3,0,-3,-3,0,3,-3,0],normals:[-1,0,0,-1,0,0,-1,0,0,-1,0,0],uv:[1,-1,0,-1,0,0,1,0],indices:[0,1,2,0,2,3]}),r._mesh=new vn(w(r),{geometry:r._geometry,material:new bn(w(r),{ambient:[.9,.3,.9],shininess:30,diffuseMap:r._texture,backfaces:!0}),scale:[1,1,1],position:n.worldPos,rotation:[90,0,0],billboard:"spherical",occluder:!1}),r.visible=!0,r.collidable=n.collidable,r.clippable=n.clippable,r.pickable=n.pickable,r.opacity=n.opacity,r.size=n.size,n.image?r.image=n.image:r.src=n.src,r}return I(i,[{key:"_setVisible",value:function(e){this._occluded=!e,this._mesh.visible=this._visible&&!this._occluded,v(x(i.prototype),"_setVisible",this).call(this,e)}},{key:"visible",get:function(){return this._visible},set:function(e){this._visible=null==e||e,this._mesh.visible=this._visible&&!this._occluded}},{key:"image",get:function(){return this._image},set:function(e){this._image=e,this._image&&(this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}},{key:"src",get:function(){return this._src},set:function(e){var t=this;if(this._src=e,this._src){this._image=null;var i=new Image;i.onload=function(){t._texture.image=i,t._imageSize[0]=i.width,t._imageSize[1]=i.height,t._updatePlaneSizeFromImage()},i.src=this._src}}},{key:"size",get:function(){return this._size},set:function(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}},{key:"collidable",get:function(){return this._mesh.collidable},set:function(e){this._mesh.collidable=!1!==e}},{key:"clippable",get:function(){return this._mesh.clippable},set:function(e){this._mesh.clippable=!1!==e}},{key:"pickable",get:function(){return this._mesh.pickable},set:function(e){this._mesh.pickable=!1!==e}},{key:"opacity",get:function(){return this._mesh.opacity},set:function(e){this._mesh.opacity=e}},{key:"_updatePlaneSizeFromImage",value:function(){var e=.5*this._size,t=this._imageSize[0],i=this._imageSize[1],r=i/t;this._geometry.positions=t>i?[e,e*r,0,-e,e*r,0,-e,-e*r,0,e,-e*r,0]:[e/r,e,0,-e/r,e,0,-e/r,-e,0,e/r,-e,0]}}]),i}(),YA=function(){function e(t){E(this,e),this._eye=le.vec3(),this._look=le.vec3(),this._up=le.vec3(),this._projection={},t&&this.saveCamera(t)}return I(e,[{key:"saveCamera",value:function(e){var t=e.camera,i=t.project;switch(this._eye.set(t.eye),this._look.set(t.look),this._up.set(t.up),t.projection){case"perspective":this._projection={projection:"perspective",fov:i.fov,fovAxis:i.fovAxis,near:i.near,far:i.far};break;case"ortho":this._projection={projection:"ortho",scale:i.scale,near:i.near,far:i.far};break;case"frustum":this._projection={projection:"frustum",left:i.left,right:i.right,top:i.top,bottom:i.bottom,near:i.near,far:i.far};break;case"custom":this._projection={projection:"custom",matrix:i.matrix.slice()}}}},{key:"restoreCamera",value:function(e,t){var i=e.camera,r=this._projection;function n(){switch(r.type){case"perspective":i.perspective.fov=r.fov,i.perspective.fovAxis=r.fovAxis,i.perspective.near=r.near,i.perspective.far=r.far;break;case"ortho":i.ortho.scale=r.scale,i.ortho.near=r.near,i.ortho.far=r.far;break;case"frustum":i.frustum.left=r.left,i.frustum.right=r.right,i.frustum.top=r.top,i.frustum.bottom=r.bottom,i.frustum.near=r.near,i.frustum.far=r.far;break;case"custom":i.customProjection.matrix=r.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:r.scale,projection:r.projection},(function(){n(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,n(),i.projection=r.projection)}}]),e}(),qA=le.vec3(),$A=function(){function e(t){if(E(this,e),this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,t){var i=t.metaScene.scene;this.saveObjects(i,t)}}return I(e,[{key:"saveObjects",value:function(e,t,i){this.numObjects=0,this._mask=i?ge.apply(i,{}):null;for(var r=!i||i.visible,n=!i||i.edges,s=!i||i.xrayed,o=!i||i.highlighted,a=!i||i.selected,l=!i||i.clippable,u=!i||i.pickable,c=!i||i.colorize,A=!i||i.opacity,h=t.metaObjects,d=e.objects,p=0,f=h.length;p<f;p++){var v=d[h[p].id];if(v){if(r&&(this.objectsVisible[p]=v.visible),n&&(this.objectsEdges[p]=v.edges),s&&(this.objectsXrayed[p]=v.xrayed),o&&(this.objectsHighlighted[p]=v.highlighted),a&&(this.objectsSelected[p]=v.selected),l&&(this.objectsClippable[p]=v.clippable),u&&(this.objectsPickable[p]=v.pickable),c){var g=v.colorize;this.objectsColorize[3*p+0]=g[0],this.objectsColorize[3*p+1]=g[1],this.objectsColorize[3*p+2]=g[2]}A&&(this.objectsOpacity[p]=v.opacity),this.numObjects++}}}},{key:"restoreObjects",value:function(e,t){for(var i=this._mask,r=!i||i.visible,n=!i||i.edges,s=!i||i.xrayed,o=!i||i.highlighted,a=!i||i.selected,l=!i||i.clippable,u=!i||i.pickable,c=!i||i.colorize,A=!i||i.opacity,h=t.metaObjects,d=e.objects,p=0,f=h.length;p<f;p++){var v=d[h[p].id];v&&(r&&(v.visible=this.objectsVisible[p]),n&&(v.edges=this.objectsEdges[p]),s&&(v.xrayed=this.objectsXrayed[p]),o&&(v.highlighted=this.objectsHighlighted[p]),a&&(v.selected=this.objectsSelected[p]),l&&(v.clippable=this.objectsClippable[p]),u&&(v.pickable=this.objectsPickable[p]),c&&(qA[0]=this.objectsColorize[3*p+0],qA[1]=this.objectsColorize[3*p+1],qA[2]=this.objectsColorize[3*p+2],v.colorize=qA),A&&(v.opacity=this.objectsOpacity[p]))}}}]),e}(),eh=le.vec3(),th=function(){function e(){E(this,e),this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsHasColorize=[],this.objectsOpacity=[],this.numObjects=0}return I(e,[{key:"saveObjects",value:function(e,t){this.numObjects=0,this._mask=t?ge.apply(t,{}):null;var i=e.objects,r=!t||t.visible,n=!t||t.edges,s=!t||t.xrayed,o=!t||t.highlighted,a=!t||t.selected,l=!t||t.clippable,u=!t||t.pickable,c=!t||t.colorize,A=!t||t.opacity;for(var h in i)if(i.hasOwnProperty(h)){var d=i[h],p=this.numObjects;if(r&&(this.objectsVisible[p]=d.visible),n&&(this.objectsEdges[p]=d.edges),s&&(this.objectsXrayed[p]=d.xrayed),o&&(this.objectsHighlighted[p]=d.highlighted),a&&(this.objectsSelected[p]=d.selected),l&&(this.objectsClippable[p]=d.clippable),u&&(this.objectsPickable[p]=d.pickable),c){var f=d.colorize;f?(this.objectsColorize[3*p+0]=f[0],this.objectsColorize[3*p+1]=f[1],this.objectsColorize[3*p+2]=f[2],this.objectsHasColorize[p]=!0):this.objectsHasColorize[p]=!1}A&&(this.objectsOpacity[p]=d.opacity),this.numObjects++}}},{key:"restoreObjects",value:function(e){var t=this._mask,i=!t||t.visible,r=!t||t.edges,n=!t||t.xrayed,s=!t||t.highlighted,o=!t||t.selected,a=!t||t.clippable,l=!t||t.pickable,u=!t||t.colorize,c=!t||t.opacity,A=0,h=e.objects;for(var d in h)if(h.hasOwnProperty(d)){var p=h[d];i&&(p.visible=this.objectsVisible[A]),r&&(p.edges=this.objectsEdges[A]),n&&(p.xrayed=this.objectsXrayed[A]),s&&(p.highlighted=this.objectsHighlighted[A]),o&&(p.selected=this.objectsSelected[A]),a&&(p.clippable=this.objectsClippable[A]),l&&(p.pickable=this.objectsPickable[A]),u&&(this.objectsHasColorize[A]?(eh[0]=this.objectsColorize[3*A+0],eh[1]=this.objectsColorize[3*A+1],eh[2]=this.objectsColorize[3*A+2],p.colorize=eh):p.colorize=null),c&&(p.opacity=this.objectsOpacity[A]),A++}}}]),e}(),ih=function(e){m(i,ze);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).v0=n.v0,r.v1=n.v1,r.v2=n.v2,r.v3=n.v3,r.t=n.t,r}return I(i,[{key:"v0",get:function(){return this._v0},set:function(e){this._v0=e||le.vec3([0,0,0])}},{key:"v1",get:function(){return this._v1},set:function(e){this._v1=e||le.vec3([0,0,0])}},{key:"v2",get:function(){return this._v2},set:function(e){this._v2=e||le.vec3([0,0,0])}},{key:"v3",get:function(){return this._v3},set:function(e){this.fire("v3",this._v3=e||le.vec3([0,0,0]))}},{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"getPoint",value:function(e){var t=le.vec3();return t[0]=le.b3(e,this._v0[0],this._v1[0],this._v2[0],this._v3[0]),t[1]=le.b3(e,this._v0[1],this._v1[1],this._v2[1],this._v3[1]),t[2]=le.b3(e,this._v0[2],this._v1[2],this._v2[2],this._v3[2]),t}},{key:"getJSON",value:function(){return{v0:this._v0,v1:this._v1,v2:this._v2,v3:this._v3,t:this._t}}}]),i}(),rh=function(e){m(i,ze);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._cachedLengths=[],r._dirty=!0,r._curves=[],r._t=0,r._dirtySubs=[],r._destroyedSubs=[],r.curves=n.curves||[],r.t=n.t,r}return I(i,[{key:"addCurve",value:function(e){this._curves.push(e),this._dirty=!0}},{key:"curves",get:function(){return this._curves},set:function(e){var t,i,r;for(e=e||[],i=0,r=this._curves.length;i<r;i++)(t=this._curves[i]).off(this._dirtySubs[i]),t.off(this._destroyedSubs[i]);this._curves=[],this._dirtySubs=[],this._destroyedSubs=[];var n=this;function s(){n._dirty=!0}function o(){var e=this.id;for(i=0,r=n._curves.length;i<r;i++)if(n._curves[i].id===e)return n._curves=n._curves.slice(i,i+1),n._dirtySubs=n._dirtySubs.slice(i,i+1),n._destroyedSubs=n._destroyedSubs.slice(i,i+1),void(n._dirty=!0)}for(i=0,r=e.length;i<r;i++){if(t=e[i],ge.isNumeric(t)||ge.isString(t)){var a=t;if(!(t=this.scene.components[a])){this.error("Component not found: "+_inQuotes(a));continue}}var l=t.type;"xeokit.SplineCurve"===l||"xeokit.Path"===l||"xeokit.CubicBezierCurve"===l||"xeokit.QuadraticBezierCurve"===l?(this._curves.push(t),this._dirtySubs.push(t.on("dirty",s)),this._destroyedSubs.push(t.once("destroyed",o))):this.error("Component "+_inQuotes(t.id)+" is not a xeokit.SplineCurve, xeokit.Path or xeokit.QuadraticBezierCurve")}this._dirty=!0}},{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"length",get:function(){var e=this._getCurveLengths();return e[e.length-1]}},{key:"getPoint",value:function(e){for(var t,i=e*this.length,r=this._getCurveLengths(),n=0;n<r.length;){if(r[n]>=i){var s=1-(r[n]-i)/(t=this._curves[n]).length;return t.getPointAt(s)}n++}return null}},{key:"_getCurveLengths",value:function(){if(!this._dirty)return this._cachedLengths;var e,t=[],i=0,r=this._curves.length;for(e=0;e<r;e++)i+=this._curves[e].length,t.push(i);return this._cachedLengths=t,this._dirty=!1,t}},{key:"_getJSON",value:function(){for(var e=[],t=0,i=this._curves.length;t<i;t++)e.push(this._curves[t].id);return{curves:e,t:this._t}}},{key:"destroy",value:function(){var e,t,r;for(v(x(i.prototype),"destroy",this).call(this),e=0,t=this._curves.length;e<t;e++)(r=this._curves[e]).off(this._dirtySubs[e]),r.off(this._destroyedSubs[e])}}]),i}(),nh=function(e){m(i,ze);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).v0=n.v0,r.v1=n.v1,r.v2=n.v2,r.t=n.t,r}return I(i,[{key:"v0",get:function(){return this._v0},set:function(e){this._v0=e||le.vec3([0,0,0])}},{key:"v1",get:function(){return this._v1},set:function(e){this._v1=e||le.vec3([0,0,0])}},{key:"v2",get:function(){return this._v2},set:function(e){this._v2=e||le.vec3([0,0,0])}},{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"getPoint",value:function(e){var t=le.vec3();return t[0]=le.b2(e,this._v0[0],this._v1[0],this._v2[0]),t[1]=le.b2(e,this._v0[1],this._v1[1],this._v2[1]),t[2]=le.b2(e,this._v0[2],this._v1[2],this._v2[2]),t}},{key:"getJSON",value:function(){return{v0:this._v0,v1:this._v1,v2:this._v2,t:this._t}}}]),i}(),sh=function(e){m(i,SA);var t=y(i);function i(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),t.call(this,e,r)}return I(i)}(),oh=le.vec3(),ah=le.vec3(),lh=le.vec4(),uh=le.vec3([0,0,-1]),ch=le.vec3([0,0,1]),Ah=le.vec3([0,1,0]),hh=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state=new nt({active:!0,pos:le.vec3(),quaternion:le.vec4(),roll:0,dir:le.vec3(),dist:0}),r.active=n.active,r.pos=n.pos,r.dir=n.dir,r.scene._sectionPlaneCreated(w(r)),r}return I(i,[{key:"type",get:function(){return"SectionPlane"}},{key:"active",get:function(){return this._state.active},set:function(e){this._state.active=!1!==e,this.glRedraw(),this.fire("active",this._state.active),this.scene.fire("sectionPlaneUpdated",this)}},{key:"pos",get:function(){return this._state.pos},set:function(e){this._state.pos.set(e||[0,0,0]),this._state.dist=-le.dotVec3(this._state.pos,this._state.dir),this.fire("pos",this._state.pos),this.scene.fire("sectionPlaneUpdated",this)}},{key:"quaternion",get:function(){return this._state.quaternion},set:function(e){this._state.quaternion.set(e||[0,0,0,-1]),le.vec3ApplyQuaternion(this._state.quaternion,ch,this._state.dir);var t=le.vec3ApplyQuaternion(this._state.quaternion,Ah,oh),i=le.vec3PairToQuaternion(ch,this._state.dir,lh),r=le.vec3ApplyQuaternion(i,Ah,ah),n=Math.acos(Math.min(1,le.dotVec3(t,r))),s=Math.sign(le.dotVec3(this._state.dir,le.cross3Vec3(t,r,ah)));this._state.roll=s*n,this._onDirUpdated()}},{key:"roll",get:function(){return this._state.roll},set:function(e){this._state.roll=e||0,this._onDirRollUpdated()}},{key:"dir",get:function(){return this._state.dir},set:function(e){this._state.dir.set(e||uh),this._onDirRollUpdated()}},{key:"_onDirRollUpdated",value:function(){le.vec3PairToQuaternion(ch,this._state.dir,this._state.quaternion),lh[0]=0,lh[1]=0,lh[2]=-1,lh[3]=this._state.roll,le.angleAxisToQuaternion(lh,lh),le.mulQuaternions(this._state.quaternion,lh,this._state.quaternion),this._onDirUpdated()}},{key:"_onDirUpdated",value:function(){this._state.dist=-le.dotVec3(this._state.pos,this._state.dir),this.glRedraw(),this.fire("dir",this._state.dir),this.scene.fire("sectionPlaneUpdated",this)}},{key:"dist",get:function(){return this._state.dist}},{key:"flipDir",value:function(){le.mulVec3Scalar(this._state.dir,-1,this._state.dir),this.dir=this._state.dir}},{key:"destroy",value:function(){this._state.destroy(),this.scene._sectionPlaneDestroyed(this),v(x(i.prototype),"destroy",this).call(this)}}]),i}(),dh=function(){function e(){E(this,e)}return I(e,[{key:"transcode",value:function(e,t){}},{key:"destroy",value:function(){}}]),e}(),ph=function(){function e(){E(this,e),this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}return I(e,[{key:"canvasPos",get:function(){return this._gotCanvasPos?this._canvasPos:null},set:function(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}},{key:"origin",get:function(){return this._gotOrigin?this._origin:null},set:function(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}},{key:"direction",get:function(){return this._gotDirection?this._direction:null},set:function(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}},{key:"indices",get:function(){return this.entity&&this._gotIndices?this._indices:null},set:function(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}},{key:"localPos",get:function(){return this.entity&&this._gotLocalPos?this._localPos:null},set:function(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}},{key:"snappedCanvasPos",get:function(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null},set:function(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}},{key:"worldPos",get:function(){return this._gotWorldPos?this._worldPos:null},set:function(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}},{key:"viewPos",get:function(){return this.entity&&this._gotViewPos?this._viewPos:null},set:function(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}},{key:"bary",get:function(){return this.entity&&this._gotBary?this._bary:null},set:function(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}},{key:"worldNormal",get:function(){return this.entity&&this._gotWorldNormal?this._worldNormal:null},set:function(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}},{key:"uv",get:function(){return this.entity&&this._gotUV?this._uv:null},set:function(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}},{key:"snapped",get:function(){return this.snappedToEdge||this.snappedToVertex}},{key:"reset",value:function(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}]),e}(),fh={isIphoneSafari:function(){var e=window.navigator.userAgent,t=/iPhone/i.test(e),i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i},isIphoneOrIpadSafari:function(){var e=window.navigator.userAgent,t=/iPhone|iPad/i.test(e)||/Macintosh/i.test(e)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2,i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i},isTouchDevice:function(){return"ontouchstart"in window||navigator.maxTouchPoints>0||navigator.mxMaxTouchPoints>0}},vh=function(){function e(t,i,r){E(this,e),this.id=r&&r.id?r.id:t,this.viewer=i,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,i.addPlugin(this)}return I(e,[{key:"scheduleTask",value:function(e){ke.scheduleTask(e,null)}},{key:"fire",value:function(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);var r,n=this._eventSubs[e];if(n)for(var s in n)n.hasOwnProperty(s)&&(r=n[s],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}},{key:"on",value:function(e,t,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new Z),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});var r=this._eventSubs[e];r?this._eventSubsNum[e]++:(r={},this._eventSubs[e]=r,this._eventSubsNum[e]=1);var n=this._subIdMap.addItem();r[n]={callback:t,scope:i||this},this._subIdEvents[n]=e;var s=this._events[e];return void 0!==s&&t.call(i||this,s),n}},{key:"off",value:function(e){if(null!=e&&this._subIdEvents){var t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];var i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}}},{key:"once",value:function(e,t,i){var r=this,n=this.on(e,(function(e){r.off(n),t.call(i||this,e)}),i)}},{key:"hasSubs",value:function(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}},{key:"log",value:function(e){console.log("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"warn",value:function(e){console.warn("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"error",value:function(e){console.error("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"send",value:function(e,t){}},{key:"destroy",value:function(){this.viewer.removePlugin(this)}}]),e}(),gh=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._canvas=n.canvas,r._element=null,r._isCustom=!1,n.elementId&&(r._element=document.getElementById(n.elementId),r._element?r._adjustPosition():r.error("Can't find given Spinner HTML element: '"+n.elementId+"' - will automatically create default element")),r._element||r._createDefaultSpinner(),r.processes=0,r}return I(i,[{key:"type",get:function(){return"Spinner"}},{key:"_createDefaultSpinner",value:function(){this._injectDefaultCSS();var e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='<div class="sk-fading-circle"> <div class="sk-circle1 sk-circle"></div> <div class="sk-circle2 sk-circle"></div> <div class="sk-circle3 sk-circle"></div> <div class="sk-circle4 sk-circle"></div> <div class="sk-circle5 sk-circle"></div> <div class="sk-circle6 sk-circle"></div> <div class="sk-circle7 sk-circle"></div> <div class="sk-circle8 sk-circle"></div> <div class="sk-circle9 sk-circle"></div> <div class="sk-circle10 sk-circle"></div> <div class="sk-circle11 sk-circle"></div> <div class="sk-circle12 sk-circle"></div> </div>',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}},{key:"_injectDefaultCSS",value:function(){var e="xeokit-spinner-css";if(!document.getElementById(e)){var t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}}},{key:"_adjustPosition",value:function(){if(!this._isCustom){var e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}}},{key:"processes",get:function(){return this._processes},set:function(e){if(e=e||0,this._processes!==e&&!(e<0)){var t=this._processes;this._processes=e;var i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}}},{key:"_destroy",value:function(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);var e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}]),i}(),mh=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"],_h=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E(this,i),(r=t.call(this,e,n))._backgroundColor=le.vec3([n.backgroundColor?n.backgroundColor[0]:1,n.backgroundColor?n.backgroundColor[1]:1,n.backgroundColor?n.backgroundColor[2]:1]),r._backgroundColorFromAmbientLight=!!n.backgroundColorFromAmbientLight,r.canvas=n.canvas,r.gl=null,r.webgl2=!1,r.transparent=!!n.transparent,r.contextAttr=n.contextAttr||{},r.contextAttr.alpha=r.transparent,r.contextAttr.preserveDrawingBuffer=!!r.contextAttr.preserveDrawingBuffer,r.contextAttr.stencil=!1,r.contextAttr.premultipliedAlpha=!!r.contextAttr.premultipliedAlpha,r.contextAttr.antialias=!1!==r.contextAttr.antialias,r.resolutionScale=n.resolutionScale,r.canvas.width=Math.round(r.canvas.clientWidth*r._resolutionScale),r.canvas.height=Math.round(r.canvas.clientHeight*r._resolutionScale),r.boundary=[r.canvas.offsetLeft,r.canvas.offsetTop,r.canvas.clientWidth,r.canvas.clientHeight],r._initWebGL(n);var s=w(r);r.canvas.addEventListener("webglcontextlost",r._webglcontextlostListener=function(e){console.time("webglcontextrestored"),s.scene._webglContextLost(),s.fire("webglcontextlost"),e.preventDefault()},!1),r.canvas.addEventListener("webglcontextrestored",r._webglcontextrestoredListener=function(e){s._initWebGL(),s.gl&&(s.scene._webglContextRestored(s.gl),s.fire("webglcontextrestored",s.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);var o=!0,a=new ResizeObserver((function(e){var t,i=p(e);try{for(i.s();!(t=i.n()).done;){t.value.contentBoxSize&&(o=!0)}}catch(e){i.e(e)}finally{i.f()}}));return a.observe(r.canvas),r._tick=r.scene.on("tick",(function(){o&&(o=!1,s.canvas.width=Math.round(s.canvas.clientWidth*s._resolutionScale),s.canvas.height=Math.round(s.canvas.clientHeight*s._resolutionScale),s.boundary[0]=s.canvas.offsetLeft,s.boundary[1]=s.canvas.offsetTop,s.boundary[2]=s.canvas.clientWidth,s.boundary[3]=s.canvas.clientHeight,s.fire("boundary",s.boundary))})),r._spinner=new gh(r.scene,{canvas:r.canvas,elementId:n.spinnerElementId}),r}return I(i,[{key:"type",get:function(){return"Canvas"}},{key:"backgroundColorFromAmbientLight",get:function(){return this._backgroundColorFromAmbientLight},set:function(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}},{key:"backgroundColor",get:function(){return this._backgroundColor},set:function(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}},{key:"resolutionScale",get:function(){return this._resolutionScale},set:function(e){if((e=e||1)!==this._resolutionScale){this._resolutionScale=e;var t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}}},{key:"spinner",get:function(){return this._spinner}},{key:"_createCanvas",value:function(){var e="xeokit-canvas-"+le.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),r=i.style;r.height="100%",r.width="100%",r.padding="0",r.margin="0",r.background="rgba(0,0,0,0);",r.float="left",r.left="0",r.top="0",r.position="absolute",r.opacity="1.0",r["z-index"]="-10000",i.innerHTML+='<canvas id="'+e+'" style="width: 100%; height: 100%; float: left; margin: 0; padding: 0;"></canvas>',t.appendChild(i),this.canvas=document.getElementById(e)}},{key:"_getElementXY",value:function(e){for(var t=0,i=0;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}},{key:"_initWebGL",value:function(){if(!this.gl)for(var e=0;!this.gl&&e<mh.length;e++)try{this.gl=this.canvas.getContext(mh[e],this.contextAttr)}catch(e){}this.gl||(this.error("Failed to get a WebGL context"),this.fire("webglContextFailed",!0,!0));var t=this.gl,i="__",r=t.activeTexture;t.activeTexture=function(e){i!==e&&(i=e,r.call(this,e))};var n={},s=t.bindTexture;t.bindTexture=function(e,t){n[i]!==t&&(n[i]=t,s.call(this,e,t))},this.gl&&this.webgl2&&(this.gl.hint(this.gl.FRAGMENT_SHADER_DERIVATIVE_HINT,this.gl.FASTEST),this.gl,WebGL2RenderingContext)}},{key:"getSnapshot",value:function(e){throw"Canvas#getSnapshot() has been replaced by Viewer#getSnapshot() - use that method instead."}},{key:"readPixels",value:function(e,t,i,r){return this.scene._renderer.readPixels(e,t,i,r)}},{key:"loseWebGLContext",value:function(){this.canvas.loseContext&&this.canvas.loseContext()}},{key:"destroy",value:function(){this.scene.off(this._tick),this._spinner._destroy(),this.canvas.removeEventListener("webglcontextlost",this._webglcontextlostListener),this.canvas.removeEventListener("webglcontextrestored",this._webglcontextrestoredListener),this.gl=null,v(x(i.prototype),"destroy",this).call(this)}}]),i}(),yh=function(){function e(t){E(this,e),this._scene=t,this._matPool=[],this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.reset()}return I(e,[{key:"reset",value:function(){this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.gl=this._scene.canvas.gl,this.lastProgramId=null,this.pbrEnabled=!1,this.colorTextureEnabled=!1,this.withSAO=!1,this.backfaces=!1,this.frontface=!0,this.textureUnit=0,this.drawElements=0,this.drawArrays=0,this.useProgram=0,this.bindTexture=0,this.bindArray=0,this.pass=0,this.shadowViewMatrix=null,this.shadowProjMatrix=null,this.pickViewMatrix=null,this.pickProjMatrix=null,this.pickZNear=.01,this.pickZFar=5e3,this.pickInvisible=!1,this.pickElementsCount=null,this.pickElementsOffset=null,this.lineWidth=1,this.snapPickLayerParams={},this.snapPickLayerNumber=0,this.snapPickCoordinateScale=le.vec3(),this.snapPickOrigin=le.vec3()}},{key:"getRTCViewMatrix",value:function(e,t){var i=this._rtcViewMats[e];return i||(i=this._getNewMat(),Jt(this._scene.camera.viewMatrix,t,i),this._rtcViewMats[e]=i),i}},{key:"getRTCPickViewMatrix",value:function(e,t){var i=this._rtcPickViewMats[e];if(!i){i=this._getNewMat();var r=this.pickViewMatrix||this._scene.camera.viewMatrix;Jt(r,t,i),this._rtcPickViewMats[e]=i}return i}},{key:"_getNewMat",value:function(){var e=this._matPool[this._matPoolNextFreeIndex];return e||(e=le.mat4(),this._matPool[this._matPoolNextFreeIndex]=e),this._matPoolNextFreeIndex++,e}}]),e}(),bh=function(){function e(t,i){E(this,e),this.scene=t,this.aabb=le.AABB3(),this.origin=le.vec3(i),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}return I(e,[{key:"addMarker",value:function(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}},{key:"markerWorldPosUpdated",value:function(e){if(this.markers[e.id]){var t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}}},{key:"removeMarker",value:function(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}},{key:"update",value:function(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}},{key:"_buildMarkerList",value:function(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}},{key:"_buildPositions",value:function(){for(var e=0,t=0;t<this.numMarkers;t++)if(this.markerList[t]){var i=this.markerList[t].rtcPos;this.positions[e++]=i[0],this.positions[e++]=i[1],this.positions[e++]=i[2],this.indices[t]=t}this.positions.length=3*this.numMarkers,this.indices.length=this.numMarkers}},{key:"_buildAABB",value:function(){var e=this.aabb;le.collapseAABB3(e),le.expandAABB3Points3(e,this.positions);var t=this.origin;e[0]+=t[0],e[1]+=t[1],e[2]+=t[2],e[3]+=t[0],e[4]+=t[1],e[5]+=t[2]}},{key:"_buildVBOs",value:function(){if(this.positionsBuf){if(this.lenPositionsBuf===this.positions.length)return void this.positionsBuf.setData(new Float32Array(this.positions));this.positionsBuf.destroy(),this.positionsBuf=null,this.indicesBuf.destroy(),this.indicesBuf=null}var e=this.scene.canvas.gl,t=3*this.numMarkers,i=this.numMarkers;this.positionsBuf=new st(e,e.ARRAY_BUFFER,new Float32Array(this.positions),t,3,e.STATIC_DRAW),this.indicesBuf=new st(e,e.ELEMENT_ARRAY_BUFFER,new Uint16Array(this.indices),i,1,e.STATIC_DRAW),this.lenPositionsBuf=this.positions.length}},{key:"_buildOcclusionTestList",value:function(){var e=this.scene.canvas,t=this.scene.camera.perspective.near,i=e.boundary,r=i[2],n=i[3],s=0;this.lenOcclusionTestList=0;for(var o=0;o<this.numMarkers;o++){var a=this.markerList[o];if(a.viewPos[2]>-t)a._setVisible(!1);else{var l=a.canvasPos,u=l[0],c=l[1];u+10<0||c+10<0||u-10>r||c-10>n?a._setVisible(!1):!a.entity||a.entity.visible?a.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=a,this.pixels[s++]=u,this.pixels[s++]=c):a._setVisible(!0):a._setVisible(!1)}}}},{key:"_updateActiveSectionPlanes",value:function(){var e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(var i=0;i<t;i++){var r=e[i];if(r.active){var n=le.planeAABB3Intersect(r.dir,r.dist,this.aabb);if(-1===n)return void(this.culledBySectionPlanes=!0);var s=0===n;this.sectionPlanesActive[i]=s}else this.sectionPlanesActive[i]=!1}this.culledBySectionPlanes=!1}},{key:"destroy",value:function(){this.markers={},this.markerList.length=0,this.positionsBuf&&this.positionsBuf.destroy(),this.indicesBuf&&this.indicesBuf.destroy()}}]),e}(),wh=le.vec3([1,0,0]),Bh=le.vec3(),xh=function(){function e(t,i){var r=this;E(this,e),this._scene=t,this._renderBufferManager=i,this._occlusionLayers={},this._occlusionLayersList=[],this._occlusionLayersListDirty=!1,this._shaderSource=null,this._program=null,this._shaderSourceHash=null,this._shaderSourceDirty=!0,this._programDirty=!1,this._markersToOcclusionLayersMap={},this._onCameraViewMatrix=t.camera.on("viewMatrix",(function(){r._occlusionTestListDirty=!0})),this._onCameraProjMatrix=t.camera.on("projMatrix",(function(){r._occlusionTestListDirty=!0})),this._onCanvasBoundary=t.canvas.on("boundary",(function(){r._occlusionTestListDirty=!0}))}return I(e,[{key:"addMarker",value:function(e){var t=e.origin.join(),i=this._occlusionLayers[t];i||(i=new bh(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}},{key:"markerWorldPosUpdated",value:function(e){var t=this._markersToOcclusionLayersMap[e.id];if(t){var i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);var r=this._occlusionLayers[i];r||(r=new bh(this._scene,e.origin),this._occlusionLayers[i]=r,this._occlusionLayersListDirty=!0),r.addMarker(e),this._markersToOcclusionLayersMap[e.id]=r}else t.markerWorldPosUpdated(e)}}},{key:"removeMarker",value:function(e){var t=e.origin.join(),i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}},{key:"needOcclusionTest",get:function(){return this._occlusionTestListDirty}},{key:"bindRenderBuf",value:function(){var e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(var t=0,i=this._occlusionLayersList.length;t<i;t++){this._occlusionLayersList[t].occlusionTestListDirty=!0}this._occlusionTestListDirty=!1}this._readPixelBuf=this._renderBufferManager.getRenderBuffer("occlusionReadPix"),this._readPixelBuf.bind(),this._readPixelBuf.clear()}},{key:"_buildOcclusionLayersList",value:function(){var e=0;for(var t in this._occlusionLayers)this._occlusionLayers.hasOwnProperty(t)&&(this._occlusionLayersList[e++]=this._occlusionLayers[t]);this._occlusionLayersList.length=e}},{key:"_buildShaderSource",value:function(){this._shaderSource={vertex:this._buildVertexShaderSource(),fragment:this._buildFragmentShaderSource()}}},{key:"_buildVertexShaderSource",value:function(){var e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):e.markerZOffset<0&&i.push("clipPos.z += "+e.markerZOffset+";"),i.push(" gl_Position = clipPos;"),i.push("}"),i}},{key:"_buildFragmentShaderSource",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// OcclusionTester fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;");for(var n=0;n<t.sectionPlanes.length;n++)r.push("uniform bool sectionPlaneActive"+n+";"),r.push("uniform vec3 sectionPlanePos"+n+";"),r.push("uniform vec3 sectionPlaneDir"+n+";")}if(r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" float dist = 0.0;");for(var s=0;s<t.sectionPlanes.length;s++)r.push("if (sectionPlaneActive"+s+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),r.push("}"),r}},{key:"_buildProgram",value:function(){this._program&&this._program.destroy();var e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Pr(t,this._shaderSource),this._program.errors)this.errors=this._program.errors;else{var r=this._program;this._uViewMatrix=r.getLocation("viewMatrix"),this._uProjMatrix=r.getLocation("projMatrix"),this._uSectionPlanes=[];for(var n=0,s=i.sectionPlanes.length;n<s;n++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+n),pos:r.getLocation("sectionPlanePos"+n),dir:r.getLocation("sectionPlaneDir"+n)});this._aPosition=r.getAttribute("position"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=r.getLocation("logDepthBufFC"))}}},{key:"drawMarkers",value:function(){var e=this._scene,t=e.canvas.gl,i=this._program,r=e._sectionPlanesState,n=e.camera,s=e.camera.project;if(i.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,n._project._state.matrix),e.logarithmicDepthBufferEnabled){var o=2/(Math.log(s.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,o)}for(var a=0,l=this._occlusionLayersList.length;a<l;a++){var u=this._occlusionLayersList[a];if(u.update(),!u.culledBySectionPlanes){var c=u.origin;t.uniformMatrix4fv(this._uViewMatrix,!1,Jt(n.viewMatrix,c));var A=r.sectionPlanes.length;if(A>0)for(var h=r.sectionPlanes,d=0;d<A;d++){var p=this._uSectionPlanes[d];if(p){var f=u.sectionPlanesActive[d];if(t.uniform1i(p.active,f?1:0),f){var v=h[d];t.uniform3fv(p.pos,ei(v.dist,v.dir,c,Bh)),t.uniform3fv(p.dir,v.dir)}}}this._aPosition.bindArrayBuffer(u.positionsBuf);var g=u.indicesBuf;g.bind(),t.drawElements(t.POINTS,g.numItems,g.itemType,0)}}}},{key:"doOcclusionTest",value:function(){for(var e=this._scene.canvas.resolutionScale,t=255*wh[0],i=255*wh[1],r=255*wh[2],n=0,s=this._occlusionLayersList.length;n<s;n++)for(var o=this._occlusionLayersList[n],a=0;a<o.lenOcclusionTestList;a++){var l=o.occlusionTestList[a],u=2*a,c=this._readPixelBuf.read(Math.round(o.pixels[u]*e),Math.round(o.pixels[u+1]*e)),A=c[0]===t&&c[1]===i&&c[2]===r;l._setVisible(A)}}},{key:"unbindRenderBuf",value:function(){this._readPixelBuf.unbind()}},{key:"destroy",value:function(){if(!this.destroyed){for(var e=0,t=this._occlusionLayersList.length;e<t;e++){this._occlusionLayersList[e].destroy()}this._program&&this._program.destroy(),this._scene.camera.off(this._onCameraViewMatrix),this._scene.camera.off(this._onCameraProjMatrix),this._scene.canvas.off(this._onCanvasBoundary),this.destroyed=!0}}}]),e}(),Ph=le.vec2(),Ch=function(){function e(t){E(this,e),this._scene=t,this._numSamples=null,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uScale=null,this._uIntensity=null,this._uBias=null,this._uKernelRadius=null,this._uMinResolution=null,this._uRandomSeed=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}return I(e,[{key:"init",value:function(){this._rebuild=!0}},{key:"render",value:function(e){var t=this;if(this._build(),!this._programError){this._getInverseProjectMat||(this._getInverseProjectMat=function(){var e=!0;t._scene.camera.on("projMatrix",(function(){e=!0}));var i=le.mat4();return function(){return e&&le.inverseMat4(n.camera.projMatrix,i),i}}());var i=this._scene.canvas.gl,r=this._program,n=this._scene,s=n.sao,o=i.drawingBufferWidth,a=i.drawingBufferHeight,l=n.camera.project._state,u=l.near,c=l.far,A=l.matrix,h=this._getInverseProjectMat(),d=Math.random(),p="perspective"===n.camera.projection;Ph[0]=o,Ph[1]=a,i.viewport(0,0,o,a),i.clearColor(0,0,0,1),i.disable(i.DEPTH_TEST),i.disable(i.BLEND),i.frontFace(i.CCW),i.clear(i.COLOR_BUFFER_BIT),r.bind(),i.uniform1f(this._uCameraNear,u),i.uniform1f(this._uCameraFar,c),i.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,A),i.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,h),i.uniform1i(this._uPerspective,p),i.uniform1f(this._uScale,s.scale*(c/5)),i.uniform1f(this._uIntensity,s.intensity),i.uniform1f(this._uBias,s.bias),i.uniform1f(this._uKernelRadius,s.kernelRadius),i.uniform1f(this._uMinResolution,s.minResolution),i.uniform2fv(this._uViewport,Ph),i.uniform1f(this._uRandomSeed,d);var f=e.getDepthTexture();r.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),i.drawElements(i.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}}},{key:"_build",value:function(){var e=!1,t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),e||this._rebuild){this._rebuild=!1;var i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new Pr(i,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:["#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ".concat(this._numSamples,"\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }")]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);var r=new Float32Array([1,1,0,1,0,0,1,0]),n=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new st(i,i.ARRAY_BUFFER,n,n.length,3,i.STATIC_DRAW),this._uvBuf=new st(i,i.ARRAY_BUFFER,r,r.length,2,i.STATIC_DRAW),this._indicesBuf=new st(i,i.ELEMENT_ARRAY_BUFFER,s,s.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}}},{key:"destroy",value:function(){this._program&&(this._program.destroy(),this._program=null)}}]),e}(),Mh=new Float32Array(Dh(17,[0,1])),kh=new Float32Array(Dh(17,[1,0])),Eh=new Float32Array(function(e,t){for(var i=[],r=0;r<=e;r++)i.push(Th(r,t));return i}(17,4)),Fh=new Float32Array(2),Ih=function(){function e(t){E(this,e),this._scene=t,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}return I(e,[{key:"init",value:function(){var e=this._scene.canvas.gl;if(this._program=new Pr(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS ".concat(16,"\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }")]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);var t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),r=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new st(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new st(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new st(e,e.ELEMENT_ARRAY_BUFFER,r,r.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}},{key:"render",value:function(e,t,i){var r=this;if(!this._programError){this._getInverseProjectMat||(this._getInverseProjectMat=function(){var e=!0;r._scene.camera.on("projMatrix",(function(){e=!0}));var t=le.mat4();return function(){return e&&le.inverseMat4(o.camera.projMatrix,t),t}}());var n=this._scene.canvas.gl,s=this._program,o=this._scene,a=n.drawingBufferWidth,l=n.drawingBufferHeight,u=o.camera.project._state,c=u.near,A=u.far;n.viewport(0,0,a,l),n.clearColor(0,0,0,1),n.enable(n.DEPTH_TEST),n.disable(n.BLEND),n.frontFace(n.CCW),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),s.bind(),Fh[0]=a,Fh[1]=l,n.uniform2fv(this._uViewport,Fh),n.uniform1f(this._uCameraNear,c),n.uniform1f(this._uCameraFar,A),n.uniform1f(this._uDepthCutoff,.01),0===i?n.uniform2fv(this._uSampleOffsets,kh):n.uniform2fv(this._uSampleOffsets,Mh),n.uniform1fv(this._uSampleWeights,Eh);var h=e.getDepthTexture(),d=t.getTexture();s.bindTexture(this._uDepthTexture,h,0),s.bindTexture(this._uOcclusionTexture,d,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),n.drawElements(n.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}}},{key:"destroy",value:function(){this._program.destroy()}}]),e}();function Th(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function Dh(e,t){for(var i=[],r=0;r<=e;r++)i.push(t[0]*r),i.push(t[1]*r);return i}var Sh=function(){function e(t){E(this,e),this.scene=t,this._renderBuffersBasic={},this._renderBuffersScaled={}}return I(e,[{key:"getRenderBuffer",value:function(e,t){var i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled,r=i[e];return r||(r=new NA(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=r),r}},{key:"destroy",value:function(){for(var e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(var t in this._renderBuffersScaled)this._renderBuffersScaled[t].destroy()}}]),e}(),Rh=le.vec3([0,0,0]),Uh=function(e,t){t=t||{};var i=new yh(e),r=e.canvas.canvas,n=e.canvas.gl,s=!!t.transparent,o=t.alphaDepthMask,a=new Z({}),l={},u={},c=[],A=[],h=[],d=!0,p=!0,f=!0,v=!0,g=!0,m=!0,_=!0,y=!0,b=new Sh(e),w=!1,B=new Ch(e),x=new Ih(e);function P(){d&&(!function(){for(var e in l)if(l.hasOwnProperty(e)){var t=l[e],i=t.drawableMap,r=t.drawableListPreCull,n=0;for(var s in i)i.hasOwnProperty(s)&&(r[n++]=i[s]);r.length=n}}(),d=!1,p=!0),p&&(!function(){var e=0;for(var t in l)if(l.hasOwnProperty(t))for(var i=l[t].drawableListPreCull,r=0,n=i.length;r<n;r++){var s=i[r];c[e++]=s}c.length=e,c.sort((function(e,t){return e.renderOrder-t.renderOrder}))}(),p=!1,f=!0),f&&function(){for(var e=0,t=0,i=0,r=c.length;i<r;i++){var n=c[i];n.rebuildRenderFlags(),n.renderFlags.culled||(n.isUI?h[t++]=n:A[e++]=n)}A.length=e,h.length=t}()}function C(e){if(e.castsShadow){var t=e.getShadowRenderBuf();if(t){for(var r in t.bind(),i.reset(),i.backfaces=!0,i.frontface=!0,i.shadowViewMatrix=e.getShadowViewMatrix(),i.shadowProjMatrix=e.getShadowProjMatrix(),n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),n.clearColor(0,0,0,1),n.enable(n.DEPTH_TEST),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),l)if(l.hasOwnProperty(r))for(var s=l[r].drawableList,o=0,a=s.length;o<a;o++){var u=s[o];!1!==u.visible&&u.castsShadow&&u.drawShadow&&(u.renderFlags.colorOpaque&&u.drawShadow(i))}t.unbind()}}}function M(t,r,s,o,l,u){var c=e.canvas.resolutionScale;i.reset(),i.backfaces=!0,i.frontface=!0,i.pickOrigin=u.origin,i.pickViewMatrix=s,i.pickProjMatrix=o,i.pickInvisible=!!l.pickInvisible,i.pickClipPos=[D(r[0]*c,n.drawingBufferWidth),S(r[1]*c,n.drawingBufferHeight)],n.viewport(0,0,1,1),n.depthMask(!0),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT);var d=l.includeEntityIds,p=l.excludeEntityIds,f=function(e){for(var t=0,r=e.length;t<r;t++){var n=e[t];!0!==n.culled&&!1!==n.visible&&(!n.drawPickMesh||!0!==l.pickInvisible&&!1===n.visible||!1===n.pickable||d&&!d[n.id]||p&&p[n.id]||n.drawPickMesh(i))}};f(A),h.length>0&&(n.clear(n.DEPTH_BUFFER_BIT),f(h));var v=t.read(0,0),g=v[0]+(v[1]<<8)+(v[2]<<16)+(v[3]<<24);if(!(g<0))return a.items[g]}function k(t,r,s,o,a,l){if(r.drawPickTriangles){var u=e.canvas.resolutionScale;i.reset(),i.backfaces=!0,i.frontface=!0,i.pickOrigin=l.origin,i.pickViewMatrix=o,i.pickProjMatrix=a,i.pickClipPos=[D(s[0]*u,n.drawingBufferWidth),S(s[1]*u,n.drawingBufferHeight)],n.viewport(0,0,1,1),n.clearColor(0,0,0,0),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),r.drawPickTriangles(i);var c=t.read(0,0),A=c[0]+256*c[1]+256*c[2]*256+256*c[3]*256*256;A*=3,l.primIndex=A}}this.scene=e,this._occlusionTester=null,this.capabilities={astcSupported:!!wn(n,"WEBGL_compressed_texture_astc"),etc1Supported:!0,etc2Supported:!!wn(n,"WEBGL_compressed_texture_etc"),dxtSupported:!!wn(n,"WEBGL_compressed_texture_s3tc"),bptcSupported:!!wn(n,"EXT_texture_compression_bptc"),pvrtcSupported:!(!wn(n,"WEBGL_compressed_texture_pvrtc")&&!wn(n,"WEBKIT_WEBGL_compressed_texture_pvrtc"))},this.setTransparentEnabled=function(e){v=e,f=!0},this.setEdgesEnabled=function(e){g=e,f=!0},this.setSAOEnabled=function(e){m=e,f=!0},this.setPBREnabled=function(e){_=e,f=!0},this.setColorTextureEnabled=function(e){y=e,f=!0},this.needStateSort=function(){p=!0},this.shadowsDirty=function(){},this.imageDirty=function(){f=!0},this.webglContextLost=function(){},this.webglContextRestored=function(e){B.init(),x.init(),f=!0},this.addDrawable=function(e,t){var i=t.type;if(i){var r=l[i];r||(r={type:t.type,count:0,isStateSortable:t.isStateSortable,stateSortCompare:t.stateSortCompare,drawableMap:{},drawableListPreCull:[],drawableList:[]},l[i]=r),r.count++,r.drawableMap[e]=t,u[e]=t,d=!0}else console.error("Renderer#addDrawable() : drawable with ID "+e+" has no 'type' - ignoring")},this.removeDrawable=function(e){var t=u[e];if(t){var i=t.type,r=l[i];--r.count<=0?delete l[i]:delete r.drawableMap[e],delete u[e],d=!0}else console.error("Renderer#removeDrawable() : drawable not found with ID "+e+" - ignoring")},this.getPickID=function(e){return a.addItem(e)},this.putPickID=function(e){a.removeItem(e)},this.clear=function(t){if(n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),s)n.clearColor(1,1,1,1);else{var i=e.canvas.backgroundColorFromAmbientLight?this.lights.getAmbientColorAndIntensity():e.canvas.backgroundColor;n.clearColor(i[0],i[1],i[2],1)}n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT)},this.needsRender=function(){return f||d||p},this.render=function(t){(t=t||{}).force&&(f=!0),P(),f&&(!function(t){var r=e.sao;m&&r.possible&&function(t){var r=e.sao,s=b.getRenderBuffer("saoDepth",{depthTexture:!0});s.bind(),s.clear(),function(e){i.reset(),i.pass=e.pass,n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),n.clearColor(0,0,0,0),n.enable(n.DEPTH_TEST),n.frontFace(n.CCW),n.enable(n.CULL_FACE),n.depthMask(!0),!1!==e.clear&&n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT);for(var t=0,r=A.length;t<r;t++){var s=A[t];!0!==s.culled&&!1!==s.visible&&s.drawDepth&&s.saoEnabled&&(s.renderFlags.colorOpaque&&s.drawDepth(i))}}(t),s.unbind();var o=b.getRenderBuffer("saoOcclusion");if(o.bind(),o.clear(),B.render(s),o.unbind(),r.blur){var a=b.getRenderBuffer("saoOcclusion2");a.bind(),a.clear(),x.render(s,o,0),a.unbind(),o.bind(),o.clear(),x.render(s,a,1),o.unbind()}}(t);(function(){for(var t=e._lightsState.lights,i=0,r=t.length;i<r;i++){var n=t[i];n.castsShadow&&C(n)}})(),function(t){var r=[],a=[],l=[],u=[],c=[],d=[],p=[],f=[],w=[],B=[],x=[],P=[],C=[],M=[],k=[],E=[],F=e._lightsState.getAmbientColorAndIntensity();if(i.reset(),i.pass=t.pass,i.withSAO=!1,i.pbrEnabled=_&&!!e.pbrEnabled,i.colorTextureEnabled=y&&!!e.colorTextureEnabled,n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),s)n.clearColor(0,0,0,0);else{var I=e.canvas.backgroundColorFromAmbientLight?F:e.canvas.backgroundColor;n.clearColor(I[0],I[1],I[2],1)}n.enable(n.DEPTH_TEST),n.frontFace(n.CCW),n.enable(n.CULL_FACE),n.depthMask(!0),n.lineWidth(1),i.lineWidth=1;var T,D,S=e.sao.possible;if(m&&S){var R=b.getRenderBuffer("saoOcclusion");i.occlusionTexture=R?R.getTexture():null}else i.occlusionTexture=null;var U=Date.now();!1!==t.clear&&n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT);var L=function(t){for(var A=0,h=0,_=0,y=0,b=0,F=0,I=0,R=0,U=0,L=0,O=0,N=0,V=0,Q=0,H=0,j=0,G=0,z=t.length;G<z;G++)if(!0!==(D=t[G]).culled&&!1!==D.visible){var W=D.renderFlags;W.colorOpaque&&(m&&S&&D.saoEnabled?r[A++]=D:D.drawColorOpaque(i)),v&&W.colorTransparent&&(l[_++]=D),W.xrayedSilhouetteTransparent&&(p[I++]=D),W.xrayedSilhouetteOpaque&&(c[b++]=D),W.highlightedSilhouetteTransparent&&(x[O++]=D),W.highlightedSilhouetteOpaque&&(w[U++]=D),W.selectedSilhouetteTransparent&&(k[H++]=D),W.selectedSilhouetteOpaque&&(C[V++]=D),D.edges&&g&&(W.edgesOpaque&&(a[h++]=D),W.edgesTransparent&&(u[y++]=D),W.selectedEdgesTransparent&&(E[j++]=D),W.selectedEdgesOpaque&&(M[Q++]=D),W.xrayedEdgesTransparent&&(f[R++]=D),W.xrayedEdgesOpaque&&(d[F++]=D),W.highlightedEdgesTransparent&&(P[N++]=D),W.highlightedEdgesOpaque&&(B[L++]=D))}if(A>0)for(i.withSAO=!0,T=0;T<A;T++)r[T].drawColorOpaque(i);if(h>0)for(T=0;T<h;T++)a[T].drawEdgesColorOpaque(i);if(b>0)for(T=0;T<b;T++)c[T].drawSilhouetteXRayed(i);if(F>0)for(T=0;T<F;T++)d[T].drawEdgesXRayed(i);if(I>0||R>0||_>0||y>0){if(n.enable(n.CULL_FACE),n.enable(n.BLEND),s?(n.blendEquation(n.FUNC_ADD),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA)):(n.blendEquation(n.FUNC_ADD),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA)),i.backfaces=!1,o||n.depthMask(!1),(_>0||y>0)&&n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),y>0)for(T=0;T<y;T++)(D=u[T]).drawEdgesColorTransparent(i);if(_>0){var X=i.pickOrigin||e.camera.eye,K=l.map((function(e){return{drawable:e,distSq:le.distVec3(e.origin||Rh,X)}}));for(K.sort((function(e,t){return t.distSq-e.distSq})),T=0;T<_;T++)K[T].drawable.drawColorTransparent(i)}if(R>0)for(T=0;T<R;T++)f[T].drawEdgesXRayed(i);if(I>0)for(T=0;T<I;T++)p[T].drawSilhouetteXRayed(i);n.disable(n.BLEND),o||n.depthMask(!0)}if(U>0||L>0){if(i.lastProgramId=null,e.highlightMaterial.glowThrough&&n.clear(n.DEPTH_BUFFER_BIT),L>0)for(T=0;T<L;T++)B[T].drawEdgesHighlighted(i);if(U>0)for(T=0;T<U;T++)w[T].drawSilhouetteHighlighted(i)}if(O>0||N>0||U>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&n.clear(n.DEPTH_BUFFER_BIT),n.enable(n.BLEND),s?(n.blendEquation(n.FUNC_ADD),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA)):n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),n.enable(n.CULL_FACE),N>0)for(T=0;T<N;T++)P[T].drawEdgesHighlighted(i);if(O>0)for(T=0;T<O;T++)x[T].drawSilhouetteHighlighted(i);n.disable(n.BLEND)}if(V>0||Q>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&n.clear(n.DEPTH_BUFFER_BIT),Q>0)for(T=0;T<Q;T++)M[T].drawEdgesSelected(i);if(V>0)for(T=0;T<V;T++)C[T].drawSilhouetteSelected(i)}if(H>0||j>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&n.clear(n.DEPTH_BUFFER_BIT),n.enable(n.CULL_FACE),n.enable(n.BLEND),s?(n.blendEquation(n.FUNC_ADD),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA)):n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),j>0)for(T=0;T<j;T++)E[T].drawEdgesSelected(i);if(H>0)for(T=0;T<H;T++)k[T].drawSilhouetteSelected(i);n.disable(n.BLEND)}};L(A),h.length>0&&(n.clear(n.DEPTH_BUFFER_BIT),L(h));var O=Date.now(),N=he.frame;N.renderTime=(O-U)/1e3,N.drawElements=i.drawElements,N.drawArrays=i.drawArrays,N.useProgram=i.useProgram,N.bindTexture=i.bindTexture,N.bindArray=i.bindArray;for(var V=Cr.MAX_TEXTURE_IMAGE_UNITS,Q=0;Q<V;Q++)n.activeTexture(n.TEXTURE0+Q);n.bindTexture(n.TEXTURE_CUBE_MAP,null),n.bindTexture(n.TEXTURE_2D,null);for(var H=Cr.MAX_VERTEX_ATTRIBS,j=0;j<H;j++)n.disableVertexAttribArray(j)}(t)}(t),he.frame.frameCount++,f=!1)},this.pick=function(){var t=le.vec3();le.mat4();var i=le.mat4(),n=le.vec3(),s=le.vec3([0,1,0]),o=new ph,a=le.vec2(),u=le.vec3(),c=le.vec3(),A=le.vec3();return le.vec3(),le.vec3(),function(h){var d,p=arguments.length>1&&void 0!==arguments[1]?arguments[1]:o;p.reset(),P();var f=null,v=null,g=null;for(var m in p.pickSurface=h.pickSurface,h.canvasPos?(u[0]=h.canvasPos[0],u[1]=h.canvasPos[1],f=e.camera.viewMatrix,v=e.camera.projMatrix,g=e.camera.projection,a[0]=e.camera.project.near,a[1]=e.camera.project.far,p.canvasPos=h.canvasPos):(h.matrix?(f=h.matrix,v=e.camera.projMatrix,g=e.camera.projection,a[0]=e.camera.project.near,a[1]=e.camera.project.far):(c.set(h.origin||[0,0,0]),A.set(h.direction||[0,0,1]),d=le.addVec3(c,A,t),n[0]=Math.random(),n[1]=Math.random(),n[2]=Math.random(),le.normalizeVec3(n),le.cross3Vec3(A,n,s),f=le.lookAtMat4v(c,d,s,i),v=e.camera.ortho.matrix,g="ortho",a[0]=e.camera.ortho.near,a[1]=e.camera.ortho.far,p.origin=c,p.direction=A),u[0]=.5*r.clientWidth,u[1]=.5*r.clientHeight),l)if(l.hasOwnProperty(m))for(var _=l[m].drawableList,y=0,w=_.length;y<w;y++){var B=_[y];B.setPickMatrices&&B.setPickMatrices(f,v)}var x=b.getRenderBuffer("pick",{size:[1,1]});x.bind();var C=M(x,u,f,v,h,p);if(!C)return x.unbind(),null;var E=C.delegatePickedEntity?C.delegatePickedEntity():C;return E?(h.pickSurface&&(C.canPickTriangle&&C.canPickTriangle()?(k(x,C,u,f,v,p),C.pickTriangleSurface(f,v,g,p),p.pickSurfacePrecision=!1):C.canPickWorldPos&&C.canPickWorldPos()&&(F(x,C,u,f,v,a,p),!1!==h.pickSurfaceNormal&&R(x,C,u,f,v,p),p.pickSurfacePrecision=!1)),x.unbind(),p.entity=E,p):(x.unbind(),null)}}();var E,F=function(){var t=le.vec4(),s=le.vec4(),o=le.vec4(),a=le.vec4(),l=le.vec4(),u=le.mat4(),c=le.mat4(),A=le.mat4();return function(h,d,p,f,v,g,m){var _=e.canvas.resolutionScale;i.reset(),i.backfaces=!0,i.frontface=!0,i.pickOrigin=m.origin,i.pickViewMatrix=f,i.pickProjMatrix=v,i.pickZNear=g[0],i.pickZFar=g[1],i.pickElementsCount=d.pickElementsCount,i.pickElementsOffset=d.pickElementsOffset,i.pickClipPos=[D(p[0]*_,n.drawingBufferWidth),S(p[1]*_,n.drawingBufferHeight)],n.viewport(0,0,1,1),n.clearColor(0,0,0,0),n.depthMask(!0),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),d.drawPickDepths(i);var y,b=function(e){var t=[e[0]/256,e[1]/256,e[2]/256,e[3]/256],i=[1/16777216,1/65536,1/256,1];return le.dotVec4(t,i)}(h.read(0,0)),w=(p[0]-r.clientWidth/2)/(r.clientWidth/2),B=-(p[1]-r.clientHeight/2)/(r.clientHeight/2),x=d.origin;if(x){var P=Jt(f,x,u);y=le.mulMat4(v,P,c)}else y=le.mulMat4(v,f,c);var C=le.inverseMat4(y,A);t[0]=w,t[1]=B,t[2]=-1,t[3]=1;var M=le.transformVec4(C,t);M=le.mulVec4Scalar(M,1/M[3]),s[0]=w,s[1]=B,s[2]=1,s[3]=1;var k=le.transformVec4(C,s);k=le.mulVec4Scalar(k,1/k[3]);var E=le.subVec3(k,M,o),F=le.addVec3(M,le.mulVec4Scalar(E,b,a),l);x&&le.addVec3(F,x),m.worldPos=F}}();function I(e){e.snapPickLayerParams=[],e.snapPickLayerNumber=0;for(var t=0,i=A.length;t<i;t++){var r=A[t];r.drawSnapInit&&!r.culled&&r.visible&&r.pickable&&r.drawSnapInit(e)}return e.snapPickLayerParams}function T(e){e.snapPickLayerParams=e.snapPickLayerParams||[],e.snapPickLayerNumber=e.snapPickLayerParams.length;for(var t=0,i=A.length;t<i;t++){var r=A[t];r.drawSnapInit&&r.drawSnap&&!r.culled&&r.visible&&r.pickable&&r.drawSnap(e)}return e.snapPickLayerParams}function D(e,t){return e/t*2-1}function S(e,t){return 1-e/t*2}function R(t,r,s,o,a,l){var u=e.canvas.resolutionScale;i.reset(),i.backfaces=!0,i.frontface=!0,i.pickOrigin=l.origin,i.pickViewMatrix=o,i.pickProjMatrix=a,i.pickClipPos=[D(s[0]*u,n.drawingBufferWidth),S(s[1]*u,n.drawingBufferHeight)];var c=b.getRenderBuffer("pick-normal",{size:[3,3]});c.bind(n.RGBA32I),n.viewport(0,0,c.size[0],c.size[1]),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.DEPTH_BUFFER_BIT),n.clearBufferiv(n.COLOR,0,new Int32Array([0,0,0,0])),r.drawPickNormals(i);var A=c.read(1,1,n.RGBA_INTEGER,n.INT,Int32Array,4);c.unbind();var h=[A[0]/le.MAX_INT,A[1]/le.MAX_INT,A[2]/le.MAX_INT];le.normalizeVec3(h),l.worldNormal=h}this.snapPick=(E=new ph,function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:E,s=t.canvasPos,o=t.origin,u=t.direction,c=t.snapRadius,A=t.snapToVertex,h=t.snapToEdge;if(!A&&!h)return this.pick({canvasPos:s,pickSurface:!0});var d=e.canvas.resolutionScale;i.reset(),i.backfaces=!0,i.frontface=!0,i.pickZNear=e.camera.project.near,i.pickZFar=e.camera.project.far;var p=c||30,f=b.getRenderBuffer("uniquePickColors-aabs-".concat(p),{depthTexture:!0,size:[2*p+1,2*p+1]});i.snapVectorA=[s?D(s[0]*d,n.drawingBufferWidth):0,s?S(s[1]*d,n.drawingBufferHeight):0],i.snapInvVectorAB=[n.drawingBufferWidth/(2*p),n.drawingBufferHeight/(2*p)],f.bind(n.RGBA32I,n.RGBA32I,n.RGBA8UI),n.viewport(0,0,f.size[0],f.size[1]),n.enable(n.DEPTH_TEST),n.frontFace(n.CCW),n.disable(n.CULL_FACE),n.depthMask(!0),n.disable(n.BLEND),n.depthFunc(n.LEQUAL),n.clear(n.DEPTH_BUFFER_BIT),n.clearBufferiv(n.COLOR,0,new Int32Array([0,0,0,0])),n.clearBufferiv(n.COLOR,1,new Int32Array([0,0,0,0])),n.clearBufferuiv(n.COLOR,2,new Uint32Array([0,0,0,0])),i.pickViewMatrix=s?e.camera.viewMatrix:le.lookAtMat4v(o,le.addVec3(o,u,le.vec3()),le.vec3([0,1,0]),le.mat4());var v=e.camera.projMatrix;for(var g in l)if(l.hasOwnProperty(g))for(var m=l[g].drawableList,_=0,y=m.length;_<y;_++){var w=m[_];w.setPickMatrices&&w.setPickMatrices(i.pickViewMatrix,v)}n.drawBuffers([n.COLOR_ATTACHMENT0,n.COLOR_ATTACHMENT1,n.COLOR_ATTACHMENT2]);var B=I(i),x=[];i.snapPickLayerParams=x,n.depthMask(!1),n.drawBuffers([n.COLOR_ATTACHMENT0]),A&&h?(i.snapMode="edge",T(i),i.snapMode="vertex",i.snapPickLayerNumber++,T(i)):(i.snapMode=A?"vertex":"edge",T(i)),n.depthMask(!0);var P=f.readArray(n.RGBA_INTEGER,n.INT,Int32Array,4),C=f.readArray(n.RGBA_INTEGER,n.INT,Int32Array,4,1),M=f.readArray(n.RGBA_INTEGER,n.UNSIGNED_INT,Uint32Array,4,2);f.unbind();var k=null,F=null,R=null,U=p,L=p,O=4*U+L*f.size[0]*4,N=P.slice(O,O+4),V=C.slice(O,O+4),Q=M.slice(O,O+4);if(0!==N[3]){var H=B[Math.abs(N[3])%B.length],j=H.origin,G=H.coordinateScale;k=[N[0]*G[0]+j[0],N[1]*G[1]+j[1],N[2]*G[2]+j[2]],F=le.normalizeVec3([V[0]/le.MAX_INT,V[1]/le.MAX_INT,V[2]/le.MAX_INT]);var z=Q[0]+(Q[1]<<8)+(Q[2]<<16)+(Q[3]<<24);R=a.items[z]}for(var W=[],X=0;X<P.length;X+=4)if(P[X+3]>0){var K=Math.floor(X/4),Z=f.size[0],J=K%Z-Math.floor(Z/2),Y=Math.floor(K/Z)-Math.floor(Z/2),q=Math.sqrt(Math.pow(J,2)+Math.pow(Y,2));W.push({x:J,y:Y,dist:q,isVertex:A&&h?P[X+3]>x.length/2:A,result:[P[X+0],P[X+1],P[X+2],P[X+3]],normal:[C[X+0],C[X+1],C[X+2],C[X+3]],id:[M[X+0],M[X+1],M[X+2],M[X+3]]})}var $=null,ee=null,te=null,ie=null;if(W.length>0){W.sort((function(e,t){return e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist})),ie=W[0].isVertex?"vertex":"edge";var re=W[0].result,ne=W[0].normal,se=W[0].id,oe=x[re[3]],ae=oe.origin,ue=oe.coordinateScale;ee=le.normalizeVec3([ne[0]/le.MAX_INT,ne[1]/le.MAX_INT,ne[2]/le.MAX_INT]),$=[re[0]*ue[0]+ae[0],re[1]*ue[1]+ae[1],re[2]*ue[2]+ae[2]],te=a.items[se[0]+(se[1]<<8)+(se[2]<<16)+(se[3]<<24)]}if(null===k&&null==$)return null;var ce=null;null!==$&&(ce=e.camera.projectWorldPos($));var Ae=te&&te.delegatePickedEntity?te.delegatePickedEntity():te;return!Ae&&R&&(R=R.delegatePickedEntity?R.delegatePickedEntity():R),r.reset(),r.snappedToEdge="edge"===ie,r.snappedToVertex="vertex"===ie,r.worldPos=$||k,r.worldNormal=ee||F,r.entity=Ae||R,r.canvasPos=s||e.camera.projectWorldPos(k||$),r.snappedCanvasPos=ce||s,r}),this.addMarker=function(t){this._occlusionTester=this._occlusionTester||new xh(e,b),this._occlusionTester.addMarker(t),e.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){P(),this._occlusionTester.bindRenderBuf(),i.reset(),i.backfaces=!0,i.frontface=!0,n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),n.clearColor(0,0,0,0),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT);for(var e=0,t=A.length;e<t;e++){var r=A[e];r.drawOcclusion&&!0!==r.culled&&!1!==r.visible&&!1!==r.pickable&&r.drawOcclusion(i)}this._occlusionTester.drawMarkers(i),this._occlusionTester.doOcclusionTest(),this._occlusionTester.unbindRenderBuf()}},this.readPixels=function(e,t,i,r){var n,s,o,a,l=b.getRenderBuffer("snapshot");for(l.bind(),l.clear(),this.render({force:!0,opaqueOnly:r}),s=0;s<i;s++)o=2*s,a=4*s,n=l.read(e[o],e[o+1]),t[a]=n[0],t[a+1]=n[1],t[a+2]=n[2],t[a+3]=n[3];l.unbind(),f=!0},this.beginSnapshot=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=b.getRenderBuffer("snapshot");e.width&&e.height&&t.setSize([e.width,e.height]),t.bind(),t.clear(),w=!0},this.renderSnapshot=function(){w&&(b.getRenderBuffer("snapshot").clear(),this.render({force:!0,opaqueOnly:!1}),f=!0)},this.readSnapshot=function(e){return b.getRenderBuffer("snapshot").readImage(e)},this.readSnapshotAsCanvas=function(){return b.getRenderBuffer("snapshot").readImageAsCanvas()},this.endSnapshot=function(){w&&(b.getRenderBuffer("snapshot").unbind(),w=!1)},this.destroy=function(){l={},u={},b.destroy(),B.destroy(),x.destroy(),this._occlusionTester&&this._occlusionTester.destroy()}},Lh=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).KEY_BACKSPACE=8,r.KEY_TAB=9,r.KEY_ENTER=13,r.KEY_SHIFT=16,r.KEY_CTRL=17,r.KEY_ALT=18,r.KEY_PAUSE_BREAK=19,r.KEY_CAPS_LOCK=20,r.KEY_ESCAPE=27,r.KEY_PAGE_UP=33,r.KEY_PAGE_DOWN=34,r.KEY_END=35,r.KEY_HOME=36,r.KEY_LEFT_ARROW=37,r.KEY_UP_ARROW=38,r.KEY_RIGHT_ARROW=39,r.KEY_DOWN_ARROW=40,r.KEY_INSERT=45,r.KEY_DELETE=46,r.KEY_NUM_0=48,r.KEY_NUM_1=49,r.KEY_NUM_2=50,r.KEY_NUM_3=51,r.KEY_NUM_4=52,r.KEY_NUM_5=53,r.KEY_NUM_6=54,r.KEY_NUM_7=55,r.KEY_NUM_8=56,r.KEY_NUM_9=57,r.KEY_A=65,r.KEY_B=66,r.KEY_C=67,r.KEY_D=68,r.KEY_E=69,r.KEY_F=70,r.KEY_G=71,r.KEY_H=72,r.KEY_I=73,r.KEY_J=74,r.KEY_K=75,r.KEY_L=76,r.KEY_M=77,r.KEY_N=78,r.KEY_O=79,r.KEY_P=80,r.KEY_Q=81,r.KEY_R=82,r.KEY_S=83,r.KEY_T=84,r.KEY_U=85,r.KEY_V=86,r.KEY_W=87,r.KEY_X=88,r.KEY_Y=89,r.KEY_Z=90,r.KEY_LEFT_WINDOW=91,r.KEY_RIGHT_WINDOW=92,r.KEY_SELECT_KEY=93,r.KEY_NUMPAD_0=96,r.KEY_NUMPAD_1=97,r.KEY_NUMPAD_2=98,r.KEY_NUMPAD_3=99,r.KEY_NUMPAD_4=100,r.KEY_NUMPAD_5=101,r.KEY_NUMPAD_6=102,r.KEY_NUMPAD_7=103,r.KEY_NUMPAD_8=104,r.KEY_NUMPAD_9=105,r.KEY_MULTIPLY=106,r.KEY_ADD=107,r.KEY_SUBTRACT=109,r.KEY_DECIMAL_POINT=110,r.KEY_DIVIDE=111,r.KEY_F1=112,r.KEY_F2=113,r.KEY_F3=114,r.KEY_F4=115,r.KEY_F5=116,r.KEY_F6=117,r.KEY_F7=118,r.KEY_F8=119,r.KEY_F9=120,r.KEY_F10=121,r.KEY_F11=122,r.KEY_F12=123,r.KEY_NUM_LOCK=144,r.KEY_SCROLL_LOCK=145,r.KEY_SEMI_COLON=186,r.KEY_EQUAL_SIGN=187,r.KEY_COMMA=188,r.KEY_DASH=189,r.KEY_PERIOD=190,r.KEY_FORWARD_SLASH=191,r.KEY_GRAVE_ACCENT=192,r.KEY_OPEN_BRACKET=219,r.KEY_BACK_SLASH=220,r.KEY_CLOSE_BRACKET=221,r.KEY_SINGLE_QUOTE=222,r.KEY_SPACE=32,r.MOUSE_LEFT_BUTTON=260,r.MOUSE_MIDDLE_BUTTON=261,r.MOUSE_RIGHT_BUTTON=262,r.element=n.element,r.altDown=!1,r.ctrlDown=!1,r.mouseDownLeft=!1,r.mouseDownMiddle=!1,r.mouseDownRight=!1,r.keyDown=[],r.enabled=!0,r.keyboardEnabled=!0,r.mouseover=!1,r.mouseCanvasPos=le.vec2(),r._keyboardEventsElement=n.keyboardEventsElement||document,r._bindEvents(),r}return I(i,[{key:"_bindEvents",value:function(){var e=this;if(!this._eventsBound){this._keyboardEventsElement.addEventListener("keydown",this._keyDownListener=function(t){e.enabled&&e.keyboardEnabled&&"INPUT"!==t.target.tagName&&"TEXTAREA"!==t.target.tagName&&(t.keyCode===e.KEY_CTRL?e.ctrlDown=!0:t.keyCode===e.KEY_ALT?e.altDown=!0:t.keyCode===e.KEY_SHIFT&&(e.shiftDown=!0),e.keyDown[t.keyCode]=!0,e.fire("keydown",t.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=function(t){e.enabled&&e.keyboardEnabled&&"INPUT"!==t.target.tagName&&"TEXTAREA"!==t.target.tagName&&(t.keyCode===e.KEY_CTRL?e.ctrlDown=!1:t.keyCode===e.KEY_ALT?e.altDown=!1:t.keyCode===e.KEY_SHIFT&&(e.shiftDown=!1),e.keyDown[t.keyCode]=!1,e.fire("keyup",t.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=function(t){e.enabled&&(e.mouseover=!0,e._getMouseCanvasPos(t),e.fire("mouseenter",e.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=function(t){e.enabled&&(e.mouseover=!1,e._getMouseCanvasPos(t),e.fire("mouseleave",e.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=function(t){if(e.enabled){switch(t.which){case 1:e.mouseDownLeft=!0;break;case 2:e.mouseDownMiddle=!0;break;case 3:e.mouseDownRight=!0}e._getMouseCanvasPos(t),e.element.focus(),e.fire("mousedown",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=function(t){if(e.enabled){switch(t.which){case 1:e.mouseDownLeft=!1;break;case 2:e.mouseDownMiddle=!1;break;case 3:e.mouseDownRight=!1}e.fire("mouseup",e.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=function(t){if(e.enabled){switch(t.which){case 1:case 3:e.mouseDownLeft=!1,e.mouseDownRight=!1;break;case 2:e.mouseDownMiddle=!1}e._getMouseCanvasPos(t),e.fire("click",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=function(t){if(e.enabled){switch(t.which){case 1:case 3:e.mouseDownLeft=!1,e.mouseDownRight=!1;break;case 2:e.mouseDownMiddle=!1}e._getMouseCanvasPos(t),e.fire("dblclick",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}});var t=this.scene.tickify((function(){return e.fire("mousemove",e.mouseCanvasPos,!0)}));this.element.addEventListener("mousemove",this._mouseMoveListener=function(i){e.enabled&&(e._getMouseCanvasPos(i),t(),e.mouseover&&i.preventDefault())}),this.element.addEventListener("contextmenu",this._contextmenuListener=function(t){e.enabled&&(e._getMouseCanvasPos(t),e.fire("contextmenu",e.mouseCanvasPos,!0))});var i=this.scene.tickify((function(t){e.fire("mousewheel",t,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=function(t,r){if(e.enabled){var n=Math.max(-1,Math.min(1,40*-t.deltaY));i(n)}},{passive:!0});var r,n;this.on("mousedown",(function(e){r=e[0],n=e[1]})),this.on("mouseup",(function(t){r>=t[0]-2&&r<=t[0]+2&&n>=t[1]-2&&n<=t[1]+2&&e.fire("mouseclicked",t,!0)})),this.element.addEventListener("touchstart",this._touchstartListener=function(t){e.enabled&&f(t.changedTouches).forEach((function(t){e.fire("touchstart",[t.identifier,e._getTouchCanvasPos(t)],!0)}))}),this.element.addEventListener("touchend",this._touchendListener=function(t){e.enabled&&f(t.changedTouches).forEach((function(t){e.fire("touchend",[t.identifier,e._getTouchCanvasPos(t)],!0)}))}),this._eventsBound=!0}}},{key:"_unbindEvents",value:function(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("contextmenu",this._contextmenuListener),this.element.removeEventListener("wheel",this._mouseWheelListener),this.element.removeEventListener("touchstart",this._touchstartListener),this.element.removeEventListener("touchend",this._touchendListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}},{key:"_getTouchCanvasPos",value:function(e){for(var t=e.target,i=0,r=0;t.offsetParent;)i+=t.offsetLeft,r+=t.offsetTop,t=t.offsetParent;return[e.pageX-i,e.pageY-r]}},{key:"_getMouseCanvasPos",value:function(e){if(e){var t=e.target.getBoundingClientRect();this.mouseCanvasPos[0]=e.clientX-t.left,this.mouseCanvasPos[1]=e.clientY-t.top}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}},{key:"setEnabled",value:function(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}},{key:"getEnabled",value:function(){return this.enabled}},{key:"setKeyboardEnabled",value:function(e){this.keyboardEnabled=e}},{key:"getKeyboardEnabled",value:function(){return this.keyboardEnabled}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._unbindEvents()}}]),i}(),Oh=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state=new nt({boundary:[0,0,100,100]}),r.boundary=n.boundary,r.autoBoundary=n.autoBoundary,r}return I(i,[{key:"type",get:function(){return"Viewport"}},{key:"boundary",get:function(){return this._state.boundary},set:function(e){if(!this._autoBoundary){if(!e){var t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}},{key:"autoBoundary",get:function(){return this._autoBoundary},set:function(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){var t=e[2],i=e[3];this._state.boundary=[0,0,t,i],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Nh=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).camera=e,r._state=new nt({matrix:le.mat4(),inverseMatrix:le.mat4(),transposedMatrix:le.mat4(),near:.1,far:1e4}),r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!0,r._fov=60,r._canvasResized=r.scene.canvas.on("boundary",r._needUpdate,w(r)),r.fov=n.fov,r.fovAxis=n.fovAxis,r.near=n.near,r.far=n.far,r}return I(i,[{key:"type",get:function(){return"Perspective"}},{key:"_update",value:function(){var e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis,r=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(r/=t),r=Math.min(r,120),le.perspectiveMat4(r*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}},{key:"fov",get:function(){return this._fov},set:function(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}},{key:"fovAxis",get:function(){return this._fovAxis},set:function(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}},{key:"near",get:function(){return this._state.near},set:function(e){var t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}},{key:"far",get:function(){return this._state.far},set:function(e){var t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(le.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(le.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,r,n){var s=this.scene.canvas.canvas,o=s.offsetWidth/2,a=s.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,le.mulMat4v4(this.inverseMatrix,i,r),le.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,le.mulMat4v4(this.camera.inverseViewMatrix,r,n),n}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}]),i}(),Vh=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).camera=e,r._state=new nt({matrix:le.mat4(),inverseMatrix:le.mat4(),transposedMatrix:le.mat4(),near:.1,far:1e4}),r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!0,r.scale=n.scale,r.near=n.near,r.far=n.far,r._onCanvasBoundary=r.scene.canvas.on("boundary",r._needUpdate,w(r)),r}return I(i,[{key:"type",get:function(){return"Ortho"}},{key:"_update",value:function(){var e,t,i,r,n=this.scene,s=.5*this._scale,o=n.canvas.boundary,a=o[2],l=o[3],u=a/l;a>l?(e=-s,t=s,i=s/u,r=-s/u):(e=-s*u,t=s*u,i=s,r=-s),le.orthoMat4c(e,t,r,i,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"scale",get:function(){return this._scale},set:function(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}},{key:"near",get:function(){return this._state.near},set:function(e){var t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}},{key:"far",get:function(){return this._state.far},set:function(e){var t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(le.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(le.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,r,n){var s=this.scene.canvas.canvas,o=s.offsetWidth/2,a=s.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,le.mulMat4v4(this.inverseMatrix,i,r),le.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,le.mulMat4v4(this.camera.inverseViewMatrix,r,n),n}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}]),i}(),Qh=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).camera=e,r._state=new nt({matrix:le.mat4(),inverseMatrix:le.mat4(),transposedMatrix:le.mat4(),near:.1,far:1e4}),r._left=-1,r._right=1,r._bottom=-1,r._top=1,r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!0,r.left=n.left,r.right=n.right,r.bottom=n.bottom,r.top=n.top,r.near=n.near,r.far=n.far,r}return I(i,[{key:"type",get:function(){return"Frustum"}},{key:"_update",value:function(){le.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"left",get:function(){return this._left},set:function(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}},{key:"right",get:function(){return this._right},set:function(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}},{key:"top",get:function(){return this._top},set:function(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}},{key:"bottom",get:function(){return this._bottom},set:function(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}},{key:"near",get:function(){return this._state.near},set:function(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}},{key:"far",get:function(){return this._state.far},set:function(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(le.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(le.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,r,n){var s=this.scene.canvas.canvas,o=s.offsetWidth/2,a=s.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,le.mulMat4v4(this.inverseMatrix,i,r),le.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,le.mulMat4v4(this.camera.inverseViewMatrix,r,n),n}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy(),v(x(i.prototype),"destroy",this).call(this)}}]),i}(),Hh=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).camera=e,r._state=new nt({matrix:le.mat4(),inverseMatrix:le.mat4(),transposedMatrix:le.mat4()}),r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!1,r.matrix=n.matrix,r}return I(i,[{key:"type",get:function(){return"CustomProjection"}},{key:"matrix",get:function(){return this._state.matrix},set:function(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(le.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(le.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,r,n){var s=this.scene.canvas.canvas,o=s.offsetWidth/2,a=s.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,le.mulMat4v4(this.inverseMatrix,i,r),le.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,le.mulMat4v4(this.camera.inverseViewMatrix,r,n),n}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),jh=le.vec3(),Gh=le.vec3(),zh=le.vec3(),Wh=le.vec3(),Xh=le.vec3(),Kh=le.vec3(),Zh=le.vec4(),Jh=le.vec4(),Yh=le.vec4(),qh=le.mat4(),$h=le.mat4(),ed=le.vec3(),td=le.vec3(),id=le.vec3(),rd=le.vec3(),nd=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state=new nt({offsetEyeFromLook:!0,deviceMatrix:le.mat4(),hasDeviceMatrix:!1,matrix:le.mat4(),normalMatrix:le.mat4(),inverseMatrix:le.mat4()}),r._perspective=new Nh(w(r)),r._ortho=new Vh(w(r)),r._frustum=new Qh(w(r)),r._customProjection=new Hh(w(r)),r._project=r._perspective,r._eye=le.vec3([0,0,10]),r._look=le.vec3([0,0,0]),r._up=le.vec3([0,1,0]),r._worldUp=le.vec3([0,1,0]),r._worldRight=le.vec3([1,0,0]),r._worldForward=le.vec3([0,0,-1]),r.deviceMatrix=n.deviceMatrix,r.eye=n.eye,r.look=n.look,r.up=n.up,r.worldAxis=n.worldAxis,r.gimbalLock=n.gimbalLock,r.constrainPitch=n.constrainPitch,r.projection=n.projection,r._perspective.on("matrix",(function(){"perspective"===r._projectionType&&r.fire("projMatrix",r._perspective.matrix)})),r._ortho.on("matrix",(function(){"ortho"===r._projectionType&&r.fire("projMatrix",r._ortho.matrix)})),r._frustum.on("matrix",(function(){"frustum"===r._projectionType&&r.fire("projMatrix",r._frustum.matrix)})),r._customProjection.on("matrix",(function(){"customProjection"===r._projectionType&&r.fire("projMatrix",r._customProjection.matrix)})),r}return I(i,[{key:"type",get:function(){return"Camera"}},{key:"_update",value:function(){var e,t=this._state;"ortho"===this.projection&&this._state.offsetEyeFromLook?(le.subVec3(this._eye,this._look,ed),le.normalizeVec3(ed,td),le.mulVec3Scalar(td,1e3,id),le.addVec3(this._look,id,rd),e=rd):e=this._eye,t.hasDeviceMatrix?(le.lookAtMat4v(e,this._look,this._up,$h),le.mulMat4(t.deviceMatrix,$h,t.matrix)):le.lookAtMat4v(e,this._look,this._up,t.matrix),le.inverseMat4(this._state.matrix,this._state.inverseMatrix),le.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}},{key:"orbitYaw",value:function(e){var t=le.subVec3(this._eye,this._look,jh);le.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,qh),t=le.transformPoint3(qh,t,Gh),this.eye=le.addVec3(this._look,t,zh),this.up=le.transformPoint3(qh,this._up,Wh)}},{key:"orbitPitch",value:function(e){if(!(this._constrainPitch&&(e=le.dotVec3(this._up,this._worldUp)/le.DEGTORAD)<1)){var t=le.subVec3(this._eye,this._look,jh),i=le.cross3Vec3(le.normalizeVec3(t,Gh),le.normalizeVec3(this._up,zh));le.rotationMat4v(.0174532925*e,i,qh),t=le.transformPoint3(qh,t,Wh),this.up=le.transformPoint3(qh,this._up,Xh),this.eye=le.addVec3(t,this._look,Kh)}}},{key:"yaw",value:function(e){var t=le.subVec3(this._look,this._eye,jh);le.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,qh),t=le.transformPoint3(qh,t,Gh),this.look=le.addVec3(t,this._eye,zh),this._gimbalLock&&(this.up=le.transformPoint3(qh,this._up,Wh))}},{key:"pitch",value:function(e){if(!(this._constrainPitch&&(e=le.dotVec3(this._up,this._worldUp)/le.DEGTORAD)<1)){var t=le.subVec3(this._look,this._eye,jh),i=le.cross3Vec3(le.normalizeVec3(t,Gh),le.normalizeVec3(this._up,zh));le.rotationMat4v(.0174532925*e,i,qh),this.up=le.transformPoint3(qh,this._up,Kh),t=le.transformPoint3(qh,t,Wh),this.look=le.addVec3(t,this._eye,Xh)}}},{key:"pan",value:function(e){var t,i=le.subVec3(this._eye,this._look,jh),r=[0,0,0];if(0!==e[0]){var n=le.cross3Vec3(le.normalizeVec3(i,[]),le.normalizeVec3(this._up,Gh));t=le.mulVec3Scalar(n,e[0]),r[0]+=t[0],r[1]+=t[1],r[2]+=t[2]}0!==e[1]&&(t=le.mulVec3Scalar(le.normalizeVec3(this._up,zh),e[1]),r[0]+=t[0],r[1]+=t[1],r[2]+=t[2]),0!==e[2]&&(t=le.mulVec3Scalar(le.normalizeVec3(i,Wh),e[2]),r[0]+=t[0],r[1]+=t[1],r[2]+=t[2]),this.eye=le.addVec3(this._eye,r,Xh),this.look=le.addVec3(this._look,r,Kh)}},{key:"zoom",value:function(e){var t=le.subVec3(this._eye,this._look,jh),i=Math.abs(le.lenVec3(t,Gh)),r=Math.abs(i+e);if(!(r<.5)){var n=le.normalizeVec3(t,zh);this.eye=le.addVec3(this._look,le.mulVec3Scalar(n,r),Wh)}}},{key:"eye",get:function(){return this._eye},set:function(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}},{key:"look",get:function(){return this._look},set:function(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}},{key:"up",get:function(){return this._up},set:function(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}},{key:"deviceMatrix",get:function(){return this._state.deviceMatrix},set:function(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}},{key:"worldAxis",get:function(){return this._worldAxis},set:function(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=le.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}},{key:"worldUp",get:function(){return this._worldUp}},{key:"xUp",get:function(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}},{key:"yUp",get:function(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}},{key:"zUp",get:function(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}},{key:"worldRight",get:function(){return this._worldRight}},{key:"worldForward",get:function(){return this._worldForward}},{key:"gimbalLock",get:function(){return this._gimbalLock},set:function(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}},{key:"constrainPitch",set:function(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}},{key:"eyeLookDist",get:function(){return le.lenVec3(le.subVec3(this._look,this._eye,jh))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"viewMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"normalMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}},{key:"viewNormalMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}},{key:"inverseViewMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}},{key:"projMatrix",get:function(){return this[this.projection].matrix}},{key:"perspective",get:function(){return this._perspective}},{key:"ortho",get:function(){return this._ortho}},{key:"frustum",get:function(){return this._frustum}},{key:"customProjection",get:function(){return this._customProjection}},{key:"projection",get:function(){return this._projectionType},set:function(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}},{key:"project",get:function(){return this._project}},{key:"offsetEyeFromLook",get:function(){return this._state.offsetEyeFromLook},set:function(e){this._state.offsetEyeFromLook=e,this._needUpdate(0)}},{key:"projectWorldPos",value:function(e){var t=Zh,i=Jh,r=Yh;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,le.mulMat4v4(this.viewMatrix,t,i),le.mulMat4v4(this.projMatrix,i,r),le.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1;var n=this.scene.canvas.canvas,s=n.offsetWidth/2,o=n.offsetHeight/2;return[r[0]*s+s,r[1]*o+o]}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),sd={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}},od=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._units="meters",r._scale=1,r._origin=le.vec3([0,0,0]),r.units=n.units,r.scale=n.scale,r.origin=n.origin,r}return I(i,[{key:"unitsInfo",get:function(){return sd}},{key:"units",get:function(){return this._units},set:function(e){e||(e="meters"),sd[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}},{key:"scale",get:function(){return this._scale},set:function(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}},{key:"origin",get:function(){return this._origin},set:function(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}},{key:"worldToRealPos",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:le.vec3(3);t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}},{key:"realToWorldPos",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:le.vec3(3);return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}]),i}(),ad=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._supported=Cr.SUPPORTED_EXTENSIONS.OES_standard_derivatives,r.enabled=n.enabled,r.kernelRadius=n.kernelRadius,r.intensity=n.intensity,r.bias=n.bias,r.scale=n.scale,r.minResolution=n.minResolution,r.numSamples=n.numSamples,r.blur=n.blur,r.blendCutoff=n.blendCutoff,r.blendFactor=n.blendFactor,r}return I(i,[{key:"supported",get:function(){return this._supported}},{key:"enabled",get:function(){return this._enabled},set:function(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}},{key:"possible",get:function(){if(!this._supported)return!1;if(!this._enabled)return!1;var e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}},{key:"active",get:function(){return this._active}},{key:"kernelRadius",get:function(){return this._kernelRadius},set:function(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}},{key:"intensity",get:function(){return this._intensity},set:function(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}},{key:"bias",get:function(){return this._bias},set:function(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}},{key:"scale",get:function(){return this._scale},set:function(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}},{key:"minResolution",get:function(){return this._minResolution},set:function(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}},{key:"numSamples",get:function(){return this._numSamples},set:function(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}},{key:"blur",get:function(){return this._blur},set:function(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}},{key:"blendCutoff",get:function(){return this._blendCutoff},set:function(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}},{key:"blendFactor",get:function(){return this._blendFactor},set:function(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this)}}]),i}(),ld=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n)).sliceColor=n.sliceColor,r.sliceThickness=n.sliceThickness,r}return I(i,[{key:"sliceThickness",get:function(){return this._sliceThickness},set:function(e){null==e&&(e=0),this._sliceThickness!==e&&(this._sliceThickness=e,this.glRedraw())}},{key:"sliceColor",get:function(){return this._sliceColor},set:function(e){null==e&&(e=[0,0,0,1]),this._sliceColor!==e&&(this._sliceColor=e,this.glRedraw())}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this)}}]),i}(),ud={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}},cd=function(e){m(i,mn);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state=new nt({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),n.preset?(r.preset=n.preset,void 0!==n.pointSize&&(r.pointSize=n.pointSize),void 0!==n.roundPoints&&(r.roundPoints=n.roundPoints),void 0!==n.perspectivePoints&&(r.perspectivePoints=n.perspectivePoints),void 0!==n.minPerspectivePointSize&&(r.minPerspectivePointSize=n.minPerspectivePointSize),void 0!==n.maxPerspectivePointSize&&(r.maxPerspectivePointSize=n.minPerspectivePointSize)):(r._preset="default",r.pointSize=n.pointSize,r.roundPoints=n.roundPoints,r.perspectivePoints=n.perspectivePoints,r.minPerspectivePointSize=n.minPerspectivePointSize,r.maxPerspectivePointSize=n.maxPerspectivePointSize),r.filterIntensity=n.filterIntensity,r.minIntensity=n.minIntensity,r.maxIntensity=n.maxIntensity,r}return I(i,[{key:"type",get:function(){return"PointsMaterial"}},{key:"presets",get:function(){return ud}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||2,this.glRedraw()}},{key:"roundPoints",get:function(){return this._state.roundPoints},set:function(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"perspectivePoints",get:function(){return this._state.perspectivePoints},set:function(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"minPerspectivePointSize",get:function(){return this._state.minPerspectivePointSize},set:function(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}},{key:"maxPerspectivePointSize",get:function(){return this._state.maxPerspectivePointSize},set:function(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}},{key:"filterIntensity",get:function(){return this._state.filterIntensity},set:function(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"minIntensity",get:function(){return this._state.minIntensity},set:function(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}},{key:"maxIntensity",get:function(){return this._state.maxIntensity},set:function(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=ud[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(ud).join(", "))}}},{key:"hash",get:function(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Ad={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}},hd=function(e){m(i,mn);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return E(this,i),(r=t.call(this,e,n))._state=new nt({type:"LinesMaterial",lineWidth:null}),n.preset?(r.preset=n.preset,void 0!==n.lineWidth&&(r.lineWidth=n.lineWidth)):(r._preset="default",r.lineWidth=n.lineWidth),r}return I(i,[{key:"type",get:function(){return"LinesMaterial"}},{key:"presets",get:function(){return Ad}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Ad[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Ad).join(", "))}}},{key:"hash",get:function(){return[""+this.lineWidth].join(";")}},{key:"destroy",value:function(){v(x(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}();function dd(e,t){var i,r,n,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:2,o=t&&t.length,a=o?t[0]*s:e.length,l=pd(e,0,a,s,!0),u=[];if(!l||l.next===l.prev)return u;if(o&&(l=bd(e,t,l,s)),e.length>80*s){i=1/0,r=1/0;for(var c=-1/0,A=-1/0,h=s;h<a;h+=s){var d=e[h],p=e[h+1];d<i&&(i=d),p<r&&(r=p),d>c&&(c=d),p>A&&(A=p)}n=0!==(n=Math.max(c-i,A-r))?32767/n:0}return vd(l,u,s,i,r,n,0),u}function pd(e,t,i,r,n){var s;if(n===function(e,t,i,r){for(var n=0,s=t,o=i-r;s<i;s+=r)n+=(e[o]-e[s])*(e[s+1]+e[o+1]),o=s;return n}(e,t,i,r)>0)for(var o=t;o<i;o+=r)s=Ld(o/r|0,e[o],e[o+1],s);else for(var a=i-r;a>=t;a-=r)s=Ld(a/r|0,e[a],e[a+1],s);return s&&Id(s,s.next)&&(Od(s),s=s.next),s}function fd(e,t){if(!e)return e;t||(t=e);var i,r=e;do{if(i=!1,r.steiner||!Id(r,r.next)&&0!==Fd(r.prev,r,r.next))r=r.next;else{if(Od(r),(r=t=r.prev)===r.next)break;i=!0}}while(i||r!==t);return t}function vd(e,t,i,r,n,s,o){if(e){!o&&s&&function(e,t,i,r){var n=e;do{0===n.z&&(n.z=Pd(n.x,n.y,t,i,r)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next}while(n!==e);n.prevZ.nextZ=null,n.prevZ=null,function(e){var t,i=1;do{var r=e,n=void 0;e=null;var s=null;for(t=0;r;){t++;for(var o=r,a=0,l=0;l<i&&(a++,o=o.nextZ);l++);for(var u=i;a>0||u>0&&o;)0!==a&&(0===u||!o||r.z<=o.z)?(n=r,r=r.nextZ,a--):(n=o,o=o.nextZ,u--),s?s.nextZ=n:e=n,n.prevZ=s,s=n;r=o}s.nextZ=null,i*=2}while(t>1)}(n)}(e,r,n,s);for(var a=e;e.prev!==e.next;){var l=e.prev,u=e.next;if(s?md(e,r,n,s):gd(e))t.push(l.i,e.i,u.i),Od(e),e=u.next,a=u.next;else if((e=u)===a){o?1===o?vd(e=_d(fd(e),t),t,i,r,n,s,2):2===o&&yd(e,t,i,r,n,s):vd(fd(e),t,i,r,n,s,1);break}}}}function gd(e){var t=e.prev,i=e,r=e.next;if(Fd(t,i,r)>=0)return!1;for(var n=t.x,s=i.x,o=r.x,a=t.y,l=i.y,u=r.y,c=Math.min(n,s,o),A=Math.min(a,l,u),h=Math.max(n,s,o),d=Math.max(a,l,u),p=r.next;p!==t;){if(p.x>=c&&p.x<=h&&p.y>=A&&p.y<=d&&kd(n,a,s,l,o,u,p.x,p.y)&&Fd(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function md(e,t,i,r){var n=e.prev,s=e,o=e.next;if(Fd(n,s,o)>=0)return!1;for(var a=n.x,l=s.x,u=o.x,c=n.y,A=s.y,h=o.y,d=Math.min(a,l,u),p=Math.min(c,A,h),f=Math.max(a,l,u),v=Math.max(c,A,h),g=Pd(d,p,t,i,r),m=Pd(f,v,t,i,r),_=e.prevZ,y=e.nextZ;_&&_.z>=g&&y&&y.z<=m;){if(_.x>=d&&_.x<=f&&_.y>=p&&_.y<=v&&_!==n&&_!==o&&kd(a,c,l,A,u,h,_.x,_.y)&&Fd(_.prev,_,_.next)>=0)return!1;if(_=_.prevZ,y.x>=d&&y.x<=f&&y.y>=p&&y.y<=v&&y!==n&&y!==o&&kd(a,c,l,A,u,h,y.x,y.y)&&Fd(y.prev,y,y.next)>=0)return!1;y=y.nextZ}for(;_&&_.z>=g;){if(_.x>=d&&_.x<=f&&_.y>=p&&_.y<=v&&_!==n&&_!==o&&kd(a,c,l,A,u,h,_.x,_.y)&&Fd(_.prev,_,_.next)>=0)return!1;_=_.prevZ}for(;y&&y.z<=m;){if(y.x>=d&&y.x<=f&&y.y>=p&&y.y<=v&&y!==n&&y!==o&&kd(a,c,l,A,u,h,y.x,y.y)&&Fd(y.prev,y,y.next)>=0)return!1;y=y.nextZ}return!0}function _d(e,t){var i=e;do{var r=i.prev,n=i.next.next;!Id(r,n)&&Td(r,i,i.next,n)&&Rd(r,n)&&Rd(n,r)&&(t.push(r.i,i.i,n.i),Od(i),Od(i.next),i=e=n),i=i.next}while(i!==e);return fd(i)}function yd(e,t,i,r,n,s){var o=e;do{for(var a=o.next.next;a!==o.prev;){if(o.i!==a.i&&Ed(o,a)){var l=Ud(o,a);return o=fd(o,o.next),l=fd(l,l.next),vd(o,t,i,r,n,s,0),void vd(l,t,i,r,n,s,0)}a=a.next}o=o.next}while(o!==e)}function bd(e,t,i,r){for(var n=[],s=0,o=t.length;s<o;s++){var a=pd(e,t[s]*r,s<o-1?t[s+1]*r:e.length,r,!1);a===a.next&&(a.steiner=!0),n.push(Cd(a))}n.sort(wd);for(var l=0;l<n.length;l++)i=Bd(n[l],i);return i}function wd(e,t){var i=e.x-t.x;0===i&&(0===(i=e.y-t.y)&&(i=(e.next.y-e.y)/(e.next.x-e.x)-(t.next.y-t.y)/(t.next.x-t.x)));return i}function Bd(e,t){var i=function(e,t){var i,r=t,n=e.x,s=e.y,o=-1/0;if(Id(e,r))return r;do{if(Id(e,r.next))return r.next;if(s<=r.y&&s>=r.next.y&&r.next.y!==r.y){var a=r.x+(s-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=n&&a>o&&(o=a,i=r.x<r.next.x?r:r.next,a===n))return i}r=r.next}while(r!==t);if(!i)return null;var l=i,u=i.x,c=i.y,A=1/0;r=i;do{if(n>=r.x&&r.x>=u&&n!==r.x&&Md(s<c?n:o,s,u,c,s<c?o:n,s,r.x,r.y)){var h=Math.abs(s-r.y)/(n-r.x);Rd(r,e)&&(h<A||h===A&&(r.x>i.x||r.x===i.x&&xd(i,r)))&&(i=r,A=h)}r=r.next}while(r!==l);return i}(e,t);if(!i)return t;var r=Ud(i,e);return fd(r,r.next),fd(i,i.next)}function xd(e,t){return Fd(e.prev,e,t.prev)<0&&Fd(t.next,e,e.next)<0}function Pd(e,t,i,r,n){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-i)*n|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*n|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function Cd(e){var t=e,i=e;do{(t.x<i.x||t.x===i.x&&t.y<i.y)&&(i=t),t=t.next}while(t!==e);return i}function Md(e,t,i,r,n,s,o,a){return(n-o)*(t-a)>=(e-o)*(s-a)&&(e-o)*(r-a)>=(i-o)*(t-a)&&(i-o)*(s-a)>=(n-o)*(r-a)}function kd(e,t,i,r,n,s,o,a){return!(e===o&&t===a)&&Md(e,t,i,r,n,s,o,a)}function Ed(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){var i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&Td(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(Rd(e,t)&&Rd(t,e)&&function(e,t){var i=e,r=!1,n=(e.x+t.x)/2,s=(e.y+t.y)/2;do{i.y>s!=i.next.y>s&&i.next.y!==i.y&&n<(i.next.x-i.x)*(s-i.y)/(i.next.y-i.y)+i.x&&(r=!r),i=i.next}while(i!==e);return r}(e,t)&&(Fd(e.prev,e,t.prev)||Fd(e,t.prev,t))||Id(e,t)&&Fd(e.prev,e,e.next)>0&&Fd(t.prev,t,t.next)>0)}function Fd(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function Id(e,t){return e.x===t.x&&e.y===t.y}function Td(e,t,i,r){var n=Sd(Fd(e,t,i)),s=Sd(Fd(e,t,r)),o=Sd(Fd(i,r,e)),a=Sd(Fd(i,r,t));return n!==s&&o!==a||(!(0!==n||!Dd(e,i,t))||(!(0!==s||!Dd(e,r,t))||(!(0!==o||!Dd(i,e,r))||!(0!==a||!Dd(i,t,r)))))}function Dd(e,t,i){return t.x<=Math.max(e.x,i.x)&&t.x>=Math.min(e.x,i.x)&&t.y<=Math.max(e.y,i.y)&&t.y>=Math.min(e.y,i.y)}function Sd(e){return e>0?1:e<0?-1:0}function Rd(e,t){return Fd(e.prev,e,e.next)<0?Fd(e,t,e.next)>=0&&Fd(e,e.prev,t)>=0:Fd(e,t,e.prev)<0||Fd(e,e.next,t)<0}function Ud(e,t){var i=Nd(e.i,e.x,e.y),r=Nd(t.i,t.x,t.y),n=e.next,s=t.prev;return e.next=t,t.prev=e,i.next=n,n.prev=i,r.next=i,i.prev=r,s.next=r,r.prev=s,r}function Ld(e,t,i,r){var n=Nd(e,t,i);return r?(n.next=r.next,n.prev=r,r.next.prev=n,r.next=n):(n.prev=n,n.next=n),n}function Od(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function Nd(e,t,i){return{i:e,x:t,y:i,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}var Vd=[0,1,0],Qd=[1,0,0],Hd=le.vec3(),jd=le.vec3(),Gd=le.vec3(),zd=le.vec3(),Wd=le.vec3();function Xd(e,t){return Math.abs(e[0]-t[0])<1e-6&&Math.abs(e[1]-t[1])<1e-6&&Math.abs(e[2]-t[2])<1e-6}var Kd=function(){function e(t){E(this,e),this.scene=t,this._resourcesAllocated=!1}return I(e,[{key:"_onCapMaterialUpdated",value:function(e,t){var i=this;if(!this._resourcesAllocated){this._resourcesAllocated=!0,this._sectionPlanes=[],this._sceneModelsData={},this._dirtyMap={},this._prevIntersectionModelsMap={},this._sectionPlaneTimeout=null,this._updateTimeout=null;var r=function(e){var t=function(){i._setAllDirty(!0),i._update()};i._sectionPlanes.push(e),e.on("pos",t),e.on("dir",t),e.on("active",t),e.once("destroyed",function(){var t=e.id;t&&(i._sectionPlanes=i._sectionPlanes.filter((function(e){return e.id!==t})),i._update())}.bind(i))};for(var n in this.scene.sectionPlanes)r(this.scene.sectionPlanes[n]);this._onSectionPlaneCreated=this.scene.on("sectionPlaneCreated",r),this._onTick=this.scene.on("tick",(function(){var e=!1;for(var t in i._sceneModelsData)i.scene.models[t]?i._sceneModelsData[t].visible!==!!i.scene.models[t].visible&&(i._sceneModelsData[t].visible=!!i.scene.models[t].visible,e=!0):(delete i._sceneModelsData[t],e=!0);e&&i._update()}))}this._dirtyMap[t]||(this._dirtyMap[t]=new Map),this._dirtyMap[t].set(e,!0),this._update()}},{key:"_update",value:function(){var e=this;clearTimeout(this._updateTimeout),this._deletePreviousModels(),this._updateTimeout=setTimeout((function(){clearTimeout(e._updateTimeout);var t=Object.values(e.scene.models).filter((function(e){return e.visible}));e._addHatches(t,e._sectionPlanes.filter((function(e){return e.active}))),e._setAllDirty(!1)}),100)}},{key:"_setAllDirty",value:function(e){var t=this,i=function(i){t._dirtyMap[i].forEach((function(r,n){return t._dirtyMap[i].set(n,e)}))};for(var r in this._dirty)i(r)}},{key:"_addHatches",value:function(e,t){var i=this;t.forEach((function(t){e.forEach((function(e){if(i._doesPlaneIntersectBoundingBox(e.aabb,t)&&i._dirtyMap[e.id]){var r=new Map,n=e.objects,s=[le.vec3(),le.vec3(),le.vec3()];i._dirtyMap[e.id].forEach((function(o,a){if(o){var l=n[a];if(i._doesPlaneIntersectBoundingBox(l.aabb,t)){if(!i._sceneModelsData[e.id]){var u=e.aabb;i._sceneModelsData[e.id]={verticesMap:new Map,indicesMap:new Map,modelOrigin:le.vec3([(u[0]+u[3])/2,(u[1]+u[4])/2,(u[2]+u[5])/2])}}var c=i._sceneModelsData[e.id],A=c.modelOrigin;if(!c.verticesMap.has(a)){var h=l.meshes[0].isSolid(),d=[],p=[];h&&l.capMaterial&&(l.getEachVertex((function(e){return d.push(e[0]-A[0],e[1]-A[1],e[2]-A[2])})),l.getEachIndex((function(e){return p.push(e)}))),c.verticesMap.set(a,d),c.indicesMap.set(a,p)}for(var f=c.verticesMap.get(a),v=c.indicesMap.get(a),g=-le.dotVec3(le.subVec3(t.pos,A,Hd),t.dir),m=[],_=v.length,y=0;y<_;y+=3){for(var b=0;b<3;b++){var w=3*v[y+b];s[b][0]=f[w],s[b][1]=f[w+1],s[b][2]=f[w+2]}if(s[0][0]||s[0][1]||s[0][2]){for(var B=[],x=0;x<3;x++){var P=s[x],C=s[(x+1)%3],M=g+le.dotVec3(t.dir,P),k=g+le.dotVec3(t.dir,C);if(!(M*k>0)){var E=-M/(k-M);B.push(le.lerpVec3(E,0,1,P,C,le.vec3()))}}2===B.length&&m.push(B)}}m.length>0&&r.set(a,m)}}}));var o=new Map;r.forEach((function(e,t){o.set(t,[[e[0]]]),e.splice(0,1);for(var i=0;e.length>0;){for(var n=o.get(t)[i][o.get(t)[i].length-1][1],s=!1,a=0;a<e.length;a++){var l=C(e[a],2),u=l[0],c=l[1];if(Xd(n,u)){o.get(t)[i].push(e[a]),e.splice(a,1),s=!0;break}if(Xd(n,c)){o.get(t)[i].push([c,u]),e.splice(a,1),s=!0;break}}if(!s&&Xd(n,o.get(t)[i][0][0])&&e.length>1)o.get(t).push([r.get(t)[0]]),e.splice(0,1),i++;else if(!s)break}}));var a=new Map;o.forEach((function(e,r){for(var n=[],s=function(r){n.push([]),e[r].forEach((function(e){n[r].push([i._projectTo2D(e[0],t.dir),i._projectTo2D(e[1],t.dir)])}))},o=0;o<e.length;o++)s(o);a.set(r,n)}));var l,u=new Map;a.forEach((function(r,n){var s=i._sceneModelsData[e.id].modelOrigin;l=[];for(var o=r,a=[],c=new Set,A=0;A<o.length;A++)if(!c.has(A)){var h=[o[A]];c.add(A);for(var d=A+1;d<o.length;d++)c.has(d)||(i._isLoopInside(o[A],o[d])||i._isLoopInside(o[d],o[A]))&&(h.push(o[d]),c.add(d));a.push(h)}a.forEach((function(e){var r=[],n=[],o=0,a=e.map((function(e){for(var t=0,i=0;i<e.length;i++){var r=(i+1)%e.length;t+=e[i][0][0]*e[r][0][1],t-=e[r][0][0]*e[i][0][1]}return Math.abs(t)/2})),u=a.indexOf(Math.max.apply(Math,f(a)));e[u].forEach((function(e){r.push(e[0][0],e[0][1]),o+=2}));for(var c=0;c<e.length;c++)c!==u&&(n.push(o/2),e[c].forEach((function(e){r.push(e[0][0],e[0][1]),o+=2})));for(var A=dd(r,n),h=[],d=0;d<A.length;d+=3){for(var p=[],v=0;v<3;v++){var g=2*A[d+v],m=[r[g],r[g+1]],_=i._convertTo3D(m,t,s);p.push(_)}h.push(p)}l.push(h)})),u.set(n,l)}));var c=new Map;u.forEach((function(e,t){l=[],e.forEach((function(e){var t=new Map,i=[],r=[],n=0;e.forEach((function(e){var s=[];e.forEach((function(e){var r="".concat(e[0].toFixed(6),",").concat(e[1].toFixed(6),",").concat(e[2].toFixed(6));t.has(r)?s.push(t.get(r)):(i.push(e[0],e[1],e[2]),t.set(r,n),s.push(n),n++)})),r.push.apply(r,s)})),l.push({positions:i,indices:r})})),c.set(t,l)})),i._prevIntersectionModelsMap[e.id]||(i._prevIntersectionModelsMap[e.id]=new Map),le.mulVec3Scalar(t.dir,.001,Wd),c.forEach((function(r,n){var s,o=i._sceneModelsData[e.id].modelOrigin,a=new Array(r.size),l=0;(r.forEach((function(r,s){var u=r.positions,c=r.indices;u.length;var A=le.buildNormals(u,c),h=i._createUVs(u,t,o);a[l++]=new vn(i.scene,{id:"".concat(t.id,"-").concat(n,"-").concat(s),geometry:new mt(i.scene,{primitive:"triangles",positions:u,indices:c,normals:A,uv:h}),origin:le.addVec3(o,Wd,Hd),position:[0,0,0],rotation:[0,0,0],material:e.objects[n].capMaterial})})),i._prevIntersectionModelsMap[e.id].has(n))?(s=i._prevIntersectionModelsMap[e.id].get(n)).push.apply(s,a):i._prevIntersectionModelsMap[e.id].set(n,a)}))}}))}))}},{key:"_doesPlaneIntersectBoundingBox",value:function(e,t){for(var i=[e[0],e[1],e[2]],r=[e[3],e[4],e[5]],n=!1,s=!1,o=0,a=[[i[0],i[1],i[2]],[r[0],i[1],i[2]],[i[0],r[1],i[2]],[r[0],r[1],i[2]],[i[0],i[1],r[2]],[r[0],i[1],r[2]],[i[0],r[1],r[2]],[r[0],r[1],r[2]]];o<a.length;o++){var l=a[o],u=t.dist+le.dotVec3(t.dir,l);if(u>0&&(n=!0),u<0&&(s=!0),n&&s)return!0}return!1}},{key:"_buildLines",value:function(e){var t=this;for(var i in e)for(var r=0;r<e[i].length;r++){var n=e[i][r];n.length<=0||n.forEach((function(e,i){new vn(t.scene,{clippable:!1,geometry:new mt(t.scene,Lt({startPoint:e[0],endPoint:e[1]})),material:new bn(t.scene,{emissive:[1,0,0]})})}))}}},{key:"_projectTo2D",value:function(e,t){var i;i=Math.abs(t[0])>Math.abs(t[1])?[-t[2],0,t[0]]:[0,t[2],-t[1]],i=le.normalizeVec3(i);var r=le.vec3(t),n=le.cross3Vec3(r,i),s=le.normalizeVec3(n);return[le.dotVec3(e,i),le.dotVec3(e,s)]}},{key:"_isLoopInside",value:function(e,t){for(var i=e[0][0],r=!1,n=0,s=t.length-1;n<t.length;s=n++){var o=t[n][0][0],a=t[n][0][1],l=t[s][0][0],u=t[s][0][1];a>i[1]!=u>i[1]&&i[0]<(l-o)*(i[1]-a)/(u-a)+o&&(r=!r)}return r}},{key:"_convertTo3D",value:function(e,t,i){var r,n=t.dir,s=t.pos;r=Math.abs(n[0])>Math.abs(n[1])?[-n[2],0,n[0]]:[0,n[2],-n[1]],r=le.normalizeVec3(r);var o=le.vec3(n),a=le.cross3Vec3(o,r),l=le.normalizeVec3(a),u=e[0],c=e[1],A=[r[0]*u+l[0]*c,r[1]*u+l[1]*c,r[2]*u+l[2]*c],h=le.dotVec3(n,[s[0]-A[0]-i[0],s[1]-A[1]-i[1],s[2]-A[2]-i[2]]);return[A[0]+n[0]*h,A[1]+n[1]*h,A[2]+n[2]*h]}},{key:"_deletePreviousModels",value:function(){var e=this,t=function(t){e._prevIntersectionModelsMap[t].forEach((function(i,r){e._dirtyMap[t].get(r)&&(i.forEach((function(e){e.destroy()})),e._prevIntersectionModelsMap[t].delete(r))})),e._prevIntersectionModelsMap[t].size<=0&&delete e._prevIntersectionModelsMap[t]};for(var i in this._prevIntersectionModelsMap)t(i)}},{key:"_createUVs",value:function(e,t,i){var r=t.pos,n=Hd;n.set(t.dir),le.normalizeVec3(n);for(var s=jd,o=[],a=0;a<e.length;a+=3){s[0]=e[a]+i[0],s[1]=e[a+1]+i[1],s[2]=e[a+2]+i[2];var l=le.subVec3(s,r,Gd),u=le.dotVec3(l,n);le.subVec3(s,le.mulVec3Scalar(n,u,Gd),s);var c=Math.abs(le.dotVec3(n,Vd))<.999?le.cross3Vec3(n,Vd,Gd):Qd,A=le.cross3Vec3(n,c,Gd);le.normalizeVec3(A,A);var h=le.subVec3(s,r,s);o.push(le.dotVec3(h,le.normalizeVec3(le.cross3Vec3(A,n,zd))),le.dotVec3(h,A))}return o}},{key:"destroy",value:function(){this._deletePreviousModels(),this._resourcesAllocated&&(this.scene.off(this._onModelLoaded),this.scene.off(this._onModelUnloaded),this.scene.off(this._onSectionPlaneCreated),this.scene.off(this._onTick))}}]),e}();function Zd(e,t){for(var i,r,n={},s=0,o=t.length;s<o;s++)i=t[s],(r=e.components[i])?r.isEntity?n[i]=!0:e.warn("pick(): Component is not an Entity: "+i):e.warn("pick(): Component not found: "+i);return n}var Jd=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E(this,i),r=t.call(this,null,n);var s=n.canvasElement||document.querySelector("#".concat(n.canvasId));if(!(s instanceof HTMLCanvasElement))throw"Mandatory config expected: valid canvasId or canvasElement";r._tickifiedFunctions={};var o=!!n.transparent,a=!!n.alphaDepthMask;return r._aabbDirty=!0,r._readableGeometry=!!n.readableGeometryEnabled,r.viewer=e,r.occlusionTestCountdown=0,r.loading=0,r.startTime=(new Date).getTime(),r.models={},r.objects={},r._numObjects=0,r.visibleObjects={},r._numVisibleObjects=0,r.xrayedObjects={},r._numXRayedObjects=0,r.highlightedObjects={},r._numHighlightedObjects=0,r.selectedObjects={},r._numSelectedObjects=0,r.colorizedObjects={},r._numColorizedObjects=0,r.opacityObjects={},r._numOpacityObjects=0,r.offsetObjects={},r._numOffsetObjects=0,r._modelIds=null,r._objectIds=null,r._visibleObjectIds=null,r._xrayedObjectIds=null,r._highlightedObjectIds=null,r._selectedObjectIds=null,r._colorizedObjectIds=null,r._opacityObjectIds=null,r._offsetObjectIds=null,r._collidables={},r._compilables={},r._needRecompile=!1,r.types={},r.components={},r.sectionPlanes={},r.lights={},r.lightMaps={},r.reflectionMaps={},r.bitmaps={},r.lineSets={},r.realWorldOffset=n.realWorldOffset||new Float64Array([0,0,0]),r.canvas=new _h(w(r),{dontClear:!0,canvas:s,spinnerElementId:n.spinnerElementId,transparent:o,webgl2:!1!==n.webgl2,contextAttr:n.contextAttr||{},backgroundColor:n.backgroundColor,backgroundColorFromAmbientLight:n.backgroundColorFromAmbientLight,premultipliedAlpha:n.premultipliedAlpha}),r.canvas.on("boundary",(function(){r.glRedraw()})),r.canvas.on("webglContextFailed",(function(){alert("xeokit failed to find WebGL!")})),r._renderer=new Uh(w(r),{transparent:o,alphaDepthMask:a}),r._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;var e=null;this.getHash=function(){if(e)return e;var t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";for(var i=[],r=0,n=t;r<n;r++)i.push("cp");return i.push(";"),e=i.join("")},this.addSectionPlane=function(t){this.sectionPlanes.push(t),e=null},this.removeSectionPlane=function(t){for(var i=0,r=this.sectionPlanes.length;i<r;i++)if(this.sectionPlanes[i].id===t.id)return this.sectionPlanes.splice(i,1),void(e=null)},this.setNumCachedSectionPlanes=function(t){this._numCachedSectionPlanes=t,e=null},this.getNumCachedSectionPlanes=function(){return this._numCachedSectionPlanes},this.getNumAllocatedSectionPlanes=function(){var e=this.sectionPlanes.length;return e>this._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},r._sectionPlanesState.setNumCachedSectionPlanes(n.numCachedSectionPlanes||0),r._lightsState=new function(){var e=le.vec4([0,0,0,0]),t=le.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];var i=null,r=null;this.getHash=function(){if(i)return i;for(var e,t=[],r=this.lights,n=0,s=r.length;n<s;n++)e=r[n],t.push("/"),t.push(e.type),t.push("world"===e.space?"w":"v"),e.castsShadow&&t.push("sh");return this.lightMaps.length>0&&t.push("/lm"),this.reflectionMaps.length>0&&t.push("/rm"),t.push(";"),i=t.join("")},this.addLight=function(e){this.lights.push(e),r=null,i=null},this.removeLight=function(e){for(var t=0,n=this.lights.length;t<n;t++){if(this.lights[t].id===e.id)return this.lights.splice(t,1),r&&r.id===e.id&&(r=null),void(i=null)}},this.addReflectionMap=function(e){this.reflectionMaps.push(e),i=null},this.removeReflectionMap=function(e){for(var t=0,r=this.reflectionMaps.length;t<r;t++)if(this.reflectionMaps[t].id===e.id)return this.reflectionMaps.splice(t,1),void(i=null)},this.addLightMap=function(e){this.lightMaps.push(e),i=null},this.removeLightMap=function(e){for(var t=0,r=this.lightMaps.length;t<r;t++)if(this.lightMaps[t].id===e.id)return this.lightMaps.splice(t,1),void(i=null)},this.getAmbientColorAndIntensity=function(){if(!r)for(var i=0,n=this.lights.length;i<n;i++){var s=this.lights[i];if("ambient"===s.type){r=s;break}}if(r){var o=r.color,a=r.intensity;return t[0]=o[0],t[1]=o[1],t[2]=o[2],t[3]=a,t}return e}},r.input=new Lh(w(r),{dontClear:!0,element:r.canvas.canvas,keyboardEventsElement:n.keyboardEventsElement}),r.metrics=new od(w(r),{units:n.units,scale:n.scale,origin:n.origin}),r.sao=new ad(w(r),{enabled:n.saoEnabled}),r.crossSections=new ld(w(r),{}),r.ticksPerRender=n.ticksPerRender,r.ticksPerOcclusionTest=n.ticksPerOcclusionTest,r.passes=n.passes,r.clearEachPass=n.clearEachPass,r.gammaInput=n.gammaInput,r.gammaOutput=n.gammaOutput,r.gammaFactor=n.gammaFactor,r._entityOffsetsEnabled=!!n.entityOffsetsEnabled,r._logarithmicDepthBufferEnabled=!!n.logarithmicDepthBufferEnabled,r._dtxEnabled=!1!==n.dtxEnabled,r._pbrEnabled=!!n.pbrEnabled,r._colorTextureEnabled=!1!==n.colorTextureEnabled,r._dtxEnabled=!!n.dtxEnabled,r._markerZOffset=n.markerZOffset,ke._addScene(w(r)),r._initDefaults(),r._viewport=new Oh(w(r),{id:"default.viewport",autoBoundary:!0,dontClear:!0}),r._camera=new nd(w(r),{id:"default.camera",dontClear:!0}),r._sectionCaps=new Kd(w(r)),new OA(w(r),{color:[1,1,1],intensity:.7}),new VA(w(r),{dir:[.8,-.5,-.5],color:[.67,.67,1],intensity:.7,space:"world"}),new VA(w(r),{dir:[-.8,-1,.5],color:[1,1,.9],intensity:.9,space:"world"}),r._camera.on("dirty",(function(){r._renderer.imageDirty()})),r}return I(i,[{key:"type",get:function(){return"Scene"}},{key:"_initDefaults",value:function(){}},{key:"_addComponent",value:function(e){if(e.id&&this.components[e.id]&&(this.error("Component "+ge.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=le.createUUID();this.components[e.id]=e;var t=e.type,i=this.types[e.type];i||(i=this.types[t]={}),i[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}},{key:"_removeComponent",value:function(e){var t=e.id,i=e.type;delete this.components[t];var r=this.types[i];r&&(delete r[t],ge.isEmptyObject(r)&&delete this.types[i]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}},{key:"_capMaterialUpdated",value:function(e,t){this._sectionCaps._onCapMaterialUpdated(e,t)}},{key:"_sectionPlaneCreated",value:function(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}},{key:"_bitmapCreated",value:function(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}},{key:"_lineSetCreated",value:function(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}},{key:"_lightCreated",value:function(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}},{key:"_lightMapCreated",value:function(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}},{key:"_reflectionMapCreated",value:function(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}},{key:"_sectionPlaneDestroyed",value:function(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}},{key:"_bitmapDestroyed",value:function(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}},{key:"_lineSetDestroyed",value:function(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}},{key:"_lightDestroyed",value:function(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}},{key:"_lightMapDestroyed",value:function(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}},{key:"_reflectionMapDestroyed",value:function(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}},{key:"_registerModel",value:function(e){this.models[e.id]=e,this._modelIds=null}},{key:"_deregisterModel",value:function(e){var t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}},{key:"_registerObject",value:function(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}},{key:"_deregisterObject",value:function(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}},{key:"_objectVisibilityUpdated",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}},{key:"_deRegisterVisibleObject",value:function(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}},{key:"_objectXRayedUpdated",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}},{key:"_deRegisterXRayedObject",value:function(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}},{key:"_objectHighlightedUpdated",value:function(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}},{key:"_deRegisterHighlightedObject",value:function(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}},{key:"_objectSelectedUpdated",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}},{key:"_deRegisterSelectedObject",value:function(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}},{key:"_objectColorizeUpdated",value:function(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}},{key:"_deRegisterColorizedObject",value:function(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}},{key:"_objectOpacityUpdated",value:function(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}},{key:"_deRegisterOpacityObject",value:function(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}},{key:"_objectOffsetUpdated",value:function(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}},{key:"_deRegisterOffsetObject",value:function(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}},{key:"_webglContextLost",value:function(){for(var e in this.canvas.spinner.processes++,this.components)if(this.components.hasOwnProperty(e)){var t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}},{key:"_webglContextRestored",value:function(){var e=this.canvas.gl;for(var t in this.components)if(this.components.hasOwnProperty(t)){var i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}},{key:"capabilities",get:function(){return this._renderer.capabilities}},{key:"entityOffsetsEnabled",get:function(){return this._entityOffsetsEnabled}},{key:"readableGeometryEnabled",get:function(){return this._readableGeometry}},{key:"pickSurfacePrecisionEnabled",get:function(){return this._readableGeometry}},{key:"logarithmicDepthBufferEnabled",get:function(){return this._logarithmicDepthBufferEnabled}},{key:"numCachedSectionPlanes",get:function(){return this._sectionPlanesState.getNumCachedSectionPlanes()},set:function(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}},{key:"pbrEnabled",get:function(){return this._pbrEnabled},set:function(e){this._pbrEnabled=!!e,this.glRedraw()}},{key:"dtxEnabled",get:function(){return this._dtxEnabled},set:function(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}},{key:"colorTextureEnabled",get:function(){return this._colorTextureEnabled},set:function(e){this._colorTextureEnabled=!!e,this.glRedraw()}},{key:"markerZOffset",get:function(){return null==this._markerZOffset?-.001:this._markerZOffset}},{key:"doOcclusionTest",value:function(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}},{key:"render",value:function(e){e&&ke.runTasks();var t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),e||this._renderer.needsRender()){t.sceneId=this.id;var i,r,n=this._passes,s=this._clearEachPass;for(i=0;i<n;i++)t.pass=i,this.fire("rendering",t,!0),r=s||0===i,this._renderer.render({pass:i,clear:r,force:e}),this.fire("rendered",t,!0);this._saveAmbientColor()}}},{key:"compile",value:function(){this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1)}},{key:"_recompile",value:function(){for(var e in this._compilables)this._compilables.hasOwnProperty(e)&&this._compilables[e].compile();this._renderer.shadowsDirty(),this.fire("compile",this,!0)}},{key:"_saveAmbientColor",value:function(){var e=this.canvas;if(e.transparent||e.backgroundImage||e.backgroundColor)this._lastAmbientColor=null;else{var t=this._lightsState.getAmbientColorAndIntensity();this._lastAmbientColor&&this._lastAmbientColor[0]===t[0]&&this._lastAmbientColor[1]===t[1]&&this._lastAmbientColor[2]===t[2]&&this._lastAmbientColor[3]===t[3]||(e.backgroundColor=t,this._lastAmbientColor||(this._lastAmbientColor=le.vec4([0,0,0,1])),this._lastAmbientColor.set(t))}}},{key:"modelIds",get:function(){return this._modelIds||(this._modelIds=Object.keys(this.models)),this._modelIds}},{key:"numObjects",get:function(){return this._numObjects}},{key:"objectIds",get:function(){return this._objectIds||(this._objectIds=Object.keys(this.objects)),this._objectIds}},{key:"numVisibleObjects",get:function(){return this._numVisibleObjects}},{key:"visibleObjectIds",get:function(){return this._visibleObjectIds||(this._visibleObjectIds=Object.keys(this.visibleObjects)),this._visibleObjectIds}},{key:"numXRayedObjects",get:function(){return this._numXRayedObjects}},{key:"xrayedObjectIds",get:function(){return this._xrayedObjectIds||(this._xrayedObjectIds=Object.keys(this.xrayedObjects)),this._xrayedObjectIds}},{key:"numHighlightedObjects",get:function(){return this._numHighlightedObjects}},{key:"highlightedObjectIds",get:function(){return this._highlightedObjectIds||(this._highlightedObjectIds=Object.keys(this.highlightedObjects)),this._highlightedObjectIds}},{key:"numSelectedObjects",get:function(){return this._numSelectedObjects}},{key:"selectedObjectIds",get:function(){return this._selectedObjectIds||(this._selectedObjectIds=Object.keys(this.selectedObjects)),this._selectedObjectIds}},{key:"numColorizedObjects",get:function(){return this._numColorizedObjects}},{key:"colorizedObjectIds",get:function(){return this._colorizedObjectIds||(this._colorizedObjectIds=Object.keys(this.colorizedObjects)),this._colorizedObjectIds}},{key:"opacityObjectIds",get:function(){return this._opacityObjectIds||(this._opacityObjectIds=Object.keys(this.opacityObjects)),this._opacityObjectIds}},{key:"offsetObjectIds",get:function(){return this._offsetObjectIds||(this._offsetObjectIds=Object.keys(this.offsetObjects)),this._offsetObjectIds}},{key:"ticksPerRender",get:function(){return this._ticksPerRender},set:function(e){null==e?e=1:(!ge.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerRender': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._ticksPerRender&&(this._ticksPerRender=e)}},{key:"ticksPerOcclusionTest",get:function(){return this._ticksPerOcclusionTest},set:function(e){null==e?e=20:(!ge.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerOcclusionTest': '"+e+"' - should be an integer greater than zero."),e=20),e!==this._ticksPerOcclusionTest&&(this._ticksPerOcclusionTest=e)}},{key:"passes",get:function(){return this._passes},set:function(e){null==e?e=1:(!ge.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'passes': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._passes&&(this._passes=e,this.glRedraw())}},{key:"clearEachPass",get:function(){return this._clearEachPass},set:function(e){(e=!!e)!==this._clearEachPass&&(this._clearEachPass=e,this.glRedraw())}},{key:"gammaInput",get:function(){return this._renderer.gammaInput},set:function(e){(e=!1!==e)!==this._renderer.gammaInput&&(this._renderer.gammaInput=e,this._needRecompile=!0,this.glRedraw())}},{key:"gammaOutput",get:function(){return this._renderer.gammaOutput},set:function(e){(e=!!e)!==this._renderer.gammaOutput&&(this._renderer.gammaOutput=e,this._needRecompile=!0,this.glRedraw())}},{key:"gammaFactor",get:function(){return this._renderer.gammaFactor},set:function(e){(e=null==e?2.2:e)!==this._renderer.gammaFactor&&(this._renderer.gammaFactor=e,this.glRedraw())}},{key:"geometry",get:function(){return this.components["default.geometry"]||Pt(mt)}},{key:"material",get:function(){return this.components["default.material"]||new bn(this,{id:"default.material",emissive:[.4,.4,.4],dontClear:!0})}},{key:"xrayMaterial",get:function(){return this.components["default.xrayMaterial"]||new zn(this,{id:"default.xrayMaterial",fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1,dontClear:!0})}},{key:"highlightMaterial",get:function(){return this.components["default.highlightMaterial"]||new zn(this,{id:"default.highlightMaterial",fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1,dontClear:!0})}},{key:"selectedMaterial",get:function(){return this.components["default.selectedMaterial"]||new zn(this,{id:"default.selectedMaterial",fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1,dontClear:!0})}},{key:"edgeMaterial",get:function(){return this.components["default.edgeMaterial"]||new Xn(this,{id:"default.edgeMaterial",fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1,dontClear:!0})}},{key:"pointsMaterial",get:function(){return this.components["default.pointsMaterial"]||new cd(this,{id:"default.pointsMaterial",fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1,dontClear:!0})}},{key:"linesMaterial",get:function(){return this.components["default.linesMaterial"]||new hd(this,{id:"default.linesMaterial",fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1,dontClear:!0})}},{key:"viewport",get:function(){return this._viewport}},{key:"camera",get:function(){return this._camera}},{key:"center",get:function(){if(this._aabbDirty||!this._center){var e=this.aabb;this._center||(this._center=le.vec3()),this._center[0]=(e[0]+e[3])/2,this._center[1]=(e[1]+e[4])/2,this._center[2]=(e[2]+e[5])/2}return this._center}},{key:"aabb",get:function(){if(this._aabbDirty){this._aabb||(this._aabb=le.AABB3());var e,t,i=le.MAX_DOUBLE,r=le.MAX_DOUBLE,n=le.MAX_DOUBLE,s=le.MIN_DOUBLE,o=le.MIN_DOUBLE,a=le.MIN_DOUBLE,l=this._collidables,u=!1;for(var c in l)if(l.hasOwnProperty(c)){if(!1===(t=l[c]).collidable)continue;(e=t.aabb)[0]<i&&(i=e[0]),e[1]<r&&(r=e[1]),e[2]<n&&(n=e[2]),e[3]>s&&(s=e[3]),e[4]>o&&(o=e[4]),e[5]>a&&(a=e[5]),u=!0}u||(i=-100,r=-100,n=-100,s=100,o=100,a=100),this._aabb[0]=i,this._aabb[1]=r,this._aabb[2]=n,this._aabb[3]=s,this._aabb[4]=o,this._aabb[5]=a,this._aabbDirty=!1,this._center=null}return this._aabb}},{key:"_setAABBDirty",value:function(){this._aabbDirty=!0,this.fire("boundary")}},{key:"pick",value:function(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");var i=e.includeEntities||e.include;i&&(e.includeEntityIds=Zd(this,i));var r=e.excludeEntities||e.exclude;return r&&(e.excludeEntityIds=Zd(this,r)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}},{key:"snapPick",value:function(e){if(void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),e.canvasPos)return this._renderer.snapPick(e);this.error("Scene.snapPick() canvasPos parameter expected")}},{key:"clear",value:function(){var e;for(var t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}},{key:"clearLights",value:function(){for(var e=Object.keys(this.lights),t=0,i=e.length;t<i;t++)this.lights[e[t]].destroy()}},{key:"clearSectionPlanes",value:function(){for(var e=Object.keys(this.sectionPlanes),t=0,i=e.length;t<i;t++)this.sectionPlanes[e[t]].destroy()}},{key:"clearBitmaps",value:function(){for(var e=Object.keys(this.bitmaps),t=0,i=e.length;t<i;t++)this.bitmaps[e[t]].destroy()}},{key:"clearLines",value:function(){for(var e=Object.keys(this.lineSets),t=0,i=e.length;t<i;t++)this.lineSets[e[t]].destroy()}},{key:"getAABB",value:function(e){if(void 0===e)return this.aabb;if(ge.isString(e)){var t=this.objects[e];if(t&&t.aabb)return t.aabb;e=[e]}if(0===e.length)return this.aabb;var i,r=le.MAX_DOUBLE,n=le.MAX_DOUBLE,s=le.MAX_DOUBLE,o=le.MIN_DOUBLE,a=le.MIN_DOUBLE,l=le.MIN_DOUBLE;if(this.withObjects(e,(function(e){if(e.collidable){var t=e.aabb;t[0]<r&&(r=t[0]),t[1]<n&&(n=t[1]),t[2]<s&&(s=t[2]),t[3]>o&&(o=t[3]),t[4]>a&&(a=t[4]),t[5]>l&&(l=t[5]),i=!0}})),i){var u=le.AABB3();return u[0]=r,u[1]=n,u[2]=s,u[3]=o,u[4]=a,u[5]=l,u}return this.aabb}},{key:"setObjectsVisible",value:function(e,t){return this.withObjects(e,(function(e){var i=e.visible!==t;return e.visible=t,i}))}},{key:"setObjectsCollidable",value:function(e,t){return this.withObjects(e,(function(e){var i=e.collidable!==t;return e.collidable=t,i}))}},{key:"setObjectsCulled",value:function(e,t){return this.withObjects(e,(function(e){var i=e.culled!==t;return e.culled=t,i}))}},{key:"setObjectsSelected",value:function(e,t){return this.withObjects(e,(function(e){var i=e.selected!==t;return e.selected=t,i}))}},{key:"setObjectsHighlighted",value:function(e,t){return this.withObjects(e,(function(e){var i=e.highlighted!==t;return e.highlighted=t,i}))}},{key:"setObjectsXRayed",value:function(e,t){return this.withObjects(e,(function(e){var i=e.xrayed!==t;return e.xrayed=t,i}))}},{key:"setObjectsEdges",value:function(e,t){return this.withObjects(e,(function(e){var i=e.edges!==t;return e.edges=t,i}))}},{key:"setObjectsColorized",value:function(e,t){return this.withObjects(e,(function(e){e.colorize=t}))}},{key:"setObjectsOpacity",value:function(e,t){return this.withObjects(e,(function(e){var i=e.opacity!==t;return e.opacity=t,i}))}},{key:"setObjectsPickable",value:function(e,t){return this.withObjects(e,(function(e){var i=e.pickable!==t;return e.pickable=t,i}))}},{key:"setObjectsOffset",value:function(e,t){this.withObjects(e,(function(e){e.offset=t}))}},{key:"withObjects",value:function(e,t){ge.isString(e)&&(e=[e]);for(var i=!1,r=0,n=e.length;r<n;r++){var s=e[r],o=this.objects[s];if(o)i=t(o)||i;else for(var a=this.modelIds,l=0,u=a.length;l<u;l++){var c=a[l],A=le.globalizeObjectId(c,s);(o=this.objects[A])&&(i=t(o)||i)}}return i}},{key:"tickify",value:function(e){var t=e.toString();if(t in this._tickifiedFunctions)return this._tickifiedFunctions[t].wrapperFunc;var i,r=0,n=0,s=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];i=t,n++},o=this.on("tick",(function(){n>r&&(r=n,e.apply(void 0,f(i)))}));return this._tickifiedFunctions[t]={tickSubId:o,wrapperFunc:s},s}},{key:"destroy",value:function(){for(var e in v(x(i.prototype),"destroy",this).call(this),this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this._sectionCaps.destroy(),this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this._sectionCaps=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}]),i}(),Yd=le.vec4(),qd=le.vec4(),$d=le.vec3(),ep=le.vec3(),tp=le.vec3(),ip=le.vec4(),rp=le.vec4(),np=le.vec4(),sp=function(){function e(t){E(this,e),this._scene=t}return I(e,[{key:"dollyToCanvasPos",value:function(e,t,i){var r=!1,n=this._scene.camera;if(e){var s=le.subVec3(e,n.eye,$d);r=le.lenVec3(s)<i}if("perspective"===n.projection){n.ortho.scale=n.ortho.scale-i;var o=this._unproject(t,ip),a=le.subVec3(o,n.eye,np),l=le.mulVec3Scalar(le.normalizeVec3(a),-i,[]);if(n.eye=[n.eye[0]-l[0],n.eye[1]-l[1],n.eye[2]-l[2]],n.look=[n.look[0]-l[0],n.look[1]-l[1],n.look[2]-l[2]],e){var u=le.subVec3(e,n.eye,$d),c=le.lenVec3(u),A=le.mulVec3Scalar(le.normalizeVec3(le.subVec3(n.look,n.eye,ep)),c);n.look=[n.eye[0]+A[0],n.eye[1]+A[1],n.eye[2]+A[2]]}}else if("ortho"===n.projection){var h=this._unproject(t,ip);n.ortho.scale=n.ortho.scale-i,n.ortho._update();var d=this._unproject(t,rp),p=le.subVec3(d,h,np),f=le.mulVec3Scalar(le.normalizeVec3(le.subVec3(n.look,n.eye,$d)),-i,ep),v=le.addVec3(p,f,tp);n.eye=[n.eye[0]-v[0],n.eye[1]-v[1],n.eye[2]-v[2]],n.look=[n.look[0]-v[0],n.look[1]-v[1],n.look[2]-v[2]]}return r}},{key:"_unproject",value:function(e,t){var i=this._scene.camera,r=i.project.transposedMatrix,n=r.subarray(8,12),s=r.subarray(12),o=[0,0,-1,1],a=le.dotVec4(o,n)/le.dotVec4(o,s);return i.project.unproject(e,a,Yd,qd,t),t}},{key:"destroy",value:function(){}}]),e}(),op=le.vec3(),ap=le.vec3(),lp=le.vec3(),up=le.vec4(),cp=le.vec4(),Ap=le.vec4(),hp=Math.PI-.001,dp=function(){function e(t,i){var r=this;E(this,e),this._scene=t,this._configs=i,this._pivotWorldPos=le.vec3(),this._cameraOffset=le.vec3(),this._azimuth=0,this._polar=0,this._radius=0,this._pivotPosSet=!1,this._pivoting=!1,this._shown=!1,this._pivotSphereEnabled=!1,this._pivotSphere=null,this._pivotSphereSize=1,this._pivotSphereGeometry=null,this._pivotSphereMaterial=null,this._rtcCenter=le.vec3(),this._rtcPos=le.vec3(),this._pivotViewPos=le.vec4(),this._pivotProjPos=le.vec4(),this._pivotCanvasPos=le.vec2(),this._cameraDirty=!0,this._onViewMatrix=this._scene.camera.on("viewMatrix",(function(){r._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(function(){r._cameraDirty=!0})),this._onTick=this._scene.on("tick",(function(){r.updatePivotElement(),r.updatePivotSphere()}))}return I(e,[{key:"createPivotSphere",value:function(){var e=this.getPivotPos(),t=le.vec3();le.decomposeMat4(le.inverseMat4(this._scene.viewer.camera.viewMatrix,le.mat4()),t,le.vec4(),le.vec3());var i=le.distVec3(t,e),r=Math.tan(Math.PI/500)*i*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(r/=this._scene.camera.ortho.scale/2),Yt(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new bt(this._scene,It({radius:r})),this._pivotSphere=new vn(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}},{key:"destroyPivotSphere",value:function(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}},{key:"updatePivotElement",value:function(){var e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){le.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,le.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);var i=t.boundary,r=i[2],n=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*r/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*n/2);var s=t._lastBoundingClientRect;if(!s||t._canvasSizeChanged){var o=t.canvas;s=t._lastBoundingClientRect=o.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(s.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(s.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}},{key:"updatePivotSphere",value:function(){this._pivoting&&this._pivotSphere&&(Yt(this.getPivotPos(),this._rtcCenter,this._rtcPos),le.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}},{key:"setPivotElement",value:function(e){this._pivotElement=e}},{key:"enablePivotSphere",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);var t=e.color||[1,0,0];this._pivotSphereMaterial=new bn(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}},{key:"disablePivotSphere",value:function(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}},{key:"startPivot",value:function(){var e=this._scene.camera,t=le.lookAtMat4v(e.eye,e.look,e.up);le.transformPoint3(t,this.getPivotPos(),this._cameraOffset);var i=this.getPivotPos();this._cameraOffset[2]+=le.distVec3(e.eye,i),t=le.inverseMat4(t);var r=le.transformVec3(t,this._cameraOffset),n=le.vec3();if(le.subVec3(e.eye,i,n),le.addVec3(n,r),e.zUp){var s=n[1];n[1]=n[2],n[2]=s}this._radius=le.lenVec3(n),this._polar=Math.acos(n[1]/this._radius),this._azimuth=Math.atan2(n[0],n[2]),this._pivoting=!0}},{key:"_cameraLookingDownwards",value:function(){var e=this._scene.camera,t=le.normalizeVec3(le.subVec3(e.look,e.eye,op)),i=le.cross3Vec3(t,e.worldUp,ap);return le.sqLenVec3(i)<=1e-4}},{key:"getPivoting",value:function(){return this._pivoting}},{key:"setPivotPos",value:function(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}},{key:"setCanvasPivotPos",value:function(e){var t=this._scene.camera,i=Math.abs(le.distVec3(this._scene.center,t.eye)),r=t.project.transposedMatrix,n=r.subarray(8,12),s=r.subarray(12),o=[0,0,-1,1],a=le.dotVec4(o,n)/le.dotVec4(o,s),l=up;t.project.unproject(e,a,cp,Ap,l);var u=le.normalizeVec3(le.subVec3(l,t.eye,op)),c=le.addVec3(t.eye,le.mulVec3Scalar(u,i,ap),lp);this.setPivotPos(c)}},{key:"getPivotPos",value:function(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}},{key:"continuePivot",value:function(e,t){if(this._pivoting&&(0!==e||0!==t)){var i=this._scene.camera,r=-e,n=-t;1===i.worldUp[2]&&(r=-r),this._azimuth+=.01*-r;var s=n<0,o=n>0,a=Math.abs(this._polar-.001)<.005,l=Math.abs(this._polar-hp)<.005,u=this._polar+.01*n;u=a&&s?.001:l&&o?hp:le.clamp(u,.001,hp),this._polar=u;var c=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){var A=c[1];c[1]=c[2],c[2]=A}var h=le.lenVec3(le.subVec3(i.look,i.eye,le.vec3())),d=this.getPivotPos();le.addVec3(c,d);var p=le.lookAtMat4v(c,d,i.worldUp);p=le.inverseMat4(p);var f=le.transformVec3(p,this._cameraOffset);p[12]-=f[0],p[13]-=f[1],p[14]-=f[2];var v=[p[8],p[9],p[10]];i.eye=[p[12],p[13],p[14]],le.subVec3(i.eye,le.mulVec3Scalar(v,h),i.look),i.up=[p[4],p[5],p[6]],this.showPivot()}}},{key:"showPivot",value:function(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}},{key:"hidePivot",value:function(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}},{key:"endPivot",value:function(){this._pivoting=!1}},{key:"destroy",value:function(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}]),e}(),pp=function(){function e(t,i){E(this,e),this._scene=t.scene,this._cameraControl=t,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=i,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=le.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}return I(e,[{key:"update",value:function(){if(this._configs.pointerEnabled&&(this.schedulePickEntity||this.schedulePickSurface)){var e="".concat(~~this.pickCursorPos[0],"-").concat(~~this.pickCursorPos[1],"-").concat(this.scheduleSnapOrPick,"-").concat(this.schedulePickSurface,"-").concat(this.schedulePickEntity);if(this._lastHash!==e){this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;var t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){var i=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});i&&(i.snappedToEdge||i.snappedToVertex)?(this.snapPickResult=i,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){var r=this.pickResult.canvasPos;if(r[0]===this.pickCursorPos[0]&&r[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){var n=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(n[0]===this.pickCursorPos[0]&&n[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}}}},{key:"fireEvents",value:function(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){var e=new ph;e.entity=this.snapPickResult.entity,e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){var t=this.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=t)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}]),e}(),fp=le.vec2(),vp=function(){function e(t,i,r,n,s){E(this,e),this._scene=t;var o,a,l,u=i.pickController,c=i.cameraControl,A=0,h=0,d=0,p=0,f=!1,v=le.vec3(),g=!0,m=this._scene.canvas.canvas,_=[];function y(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];b(),e&&w()}function b(){A=n.pointerCanvasPos[0],h=n.pointerCanvasPos[1],d=n.pointerCanvasPos[0],p=n.pointerCanvasPos[1]}function w(){u.pickCursorPos=n.pointerCanvasPos,u.schedulePickSurface=!0,u.update(),u.picked&&u.pickedSurface&&u.pickResult&&u.pickResult.worldPos?(f=!0,v.set(u.pickResult.worldPos)):f=!1}document.addEventListener("keydown",this._documentKeyDownHandler=function(e){if(r.active&&r.pointerEnabled&&t.input.keyboardEnabled){var i=e.keyCode;_[i]=!0}}),document.addEventListener("keyup",this._documentKeyUpHandler=function(e){if(r.active&&r.pointerEnabled&&t.input.keyboardEnabled){var i=e.keyCode;_[i]=!1}}),document.addEventListener("visibilitychange",this._onVisibilityChange=function(){_.splice(0)}),window.addEventListener("blur",this._onBlur=function(){_.splice(0)}),m.addEventListener("mousedown",this._mouseDownHandler=function(e){if(r.active&&r.pointerEnabled)switch(e.which){case 1:_[t.input.KEY_SHIFT]||r.planView?(o=!0,_[t.input.MOUSE_LEFT_BUTTON]=!0,y()):(o=!0,_[t.input.MOUSE_LEFT_BUTTON]=!0,y(!1));break;case 2:a=!0,_[t.input.MOUSE_MIDDLE_BUTTON]=!0,y();break;case 3:l=!0,_[t.input.MOUSE_RIGHT_BUTTON]=!0,r.panRightClick&&y()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=function(e){if(r.active&&r.pointerEnabled&&(o||a||l)){var i=t.canvas.boundary,u=i[2],d=i[3],p=n.pointerCanvasPos[0],g=n.pointerCanvasPos[1],m=r.planView||c._isKeyDownForAction(c.MOUSE_PAN,_),y=c._isKeyDownForAction(c.MOUSE_ROTATE,_),b=document.pointerLockElement?e.movementX:p-A,w=document.pointerLockElement?e.movementY:g-h;if(m){var B=t.camera;if("perspective"===B.projection){var x=Math.abs(f?le.lenVec3(le.subVec3(v,t.camera.eye,[])):t.camera.eyeLookDist)*Math.tan(B.perspective.fov/2*Math.PI/180);s.panDeltaX+=1.5*b*x/d,s.panDeltaY+=1.5*w*x/d}else s.panDeltaX+=.5*B.ortho.scale*(b/d),s.panDeltaY+=.5*B.ortho.scale*(w/d)}else y&&(r.planView||(r.firstPerson?(s.rotateDeltaY-=b/u*r.dragRotationRate/2,s.rotateDeltaX+=w/d*(r.dragRotationRate/4)):(s.rotateDeltaY-=b/u*(1.5*r.dragRotationRate),s.rotateDeltaX+=w/d*(1.5*r.dragRotationRate))));A=p,h=g}}),m.addEventListener("mousemove",this._canvasMouseMoveHandler=function(e){r.active&&r.pointerEnabled&&n.mouseover&&(g=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=function(e){if(r.active&&r.pointerEnabled)switch(e.which){case 1:case 2:case 3:o=!1,a=!1,l=!1,_[t.input.MOUSE_LEFT_BUTTON]=!1,_[t.input.MOUSE_MIDDLE_BUTTON]=!1,_[t.input.MOUSE_RIGHT_BUTTON]=!1}}),m.addEventListener("mouseup",this._mouseUpHandler=function(e){if(r.active&&r.pointerEnabled){if(3===e.which){!function(e,t){if(e){for(var i=e.target,r=0,n=0,s=0,o=0;i.offsetParent;)r+=i.offsetLeft,n+=i.offsetTop,s+=i.scrollLeft,o+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+s-r,t[1]=e.pageY+o-n}else e=window.event,t[0]=e.x,t[1]=e.y}(e,fp);var t=fp[0],n=fp[1];Math.abs(t-d)<3&&Math.abs(n-p)<3&&i.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:fp,event:e},!0)}m.style.removeProperty("cursor")}}),m.addEventListener("mouseenter",this._mouseEnterHandler=function(){r.active&&r.pointerEnabled});var B=1/60,x=null;m.addEventListener("wheel",this._mouseWheelHandler=function(e){if(r.active&&r.pointerEnabled&&r.zoomOnMouseWheel&&c._isKeyDownForAction(c.MOUSE_DOLLY,_)){var t=performance.now()/1e3,i=null!==x?t-x:0;x=t,i>.05&&(i=.05),i<B&&(i=B);var o=Math.max(-1,Math.min(1,40*-e.deltaY));if(0!==o){var a=o/Math.abs(o);s.dollyDelta+=-a*i*r.mouseWheelDollyRate,g&&(n.followPointerDirty=!0,g=!1)}}},{passive:!0})}return I(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;document.removeEventListener("keydown",this._documentKeyDownHandler),document.removeEventListener("keyup",this._documentKeyUpHandler),document.removeEventListener("visibilitychange",this._onVisibilityChange),window.removeEventListener("blur",this._onBlur),e.removeEventListener("mousedown",this._mouseDownHandler),document.removeEventListener("mousemove",this._documentMouseMoveHandler),e.removeEventListener("mousemove",this._canvasMouseMoveHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._mouseUpHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("wheel",this._mouseWheelHandler)}}]),e}(),gp=le.vec3(),mp=le.vec3(),_p=le.vec3(),yp=le.vec3(),bp=le.vec3(),wp={eye:le.vec3(),look:le.vec3(),up:le.vec3()},Bp=function(){function e(t,i,r,n){E(this,e),this._scene=t;var s=i.cameraControl,o=t.camera;this._onSceneKeyDown=t.input.on("keydown",(function(){if(r.active&&r.pointerEnabled&&t.input.keyboardEnabled&&(!r.keyboardEnabledOnlyIfMouseover||n.mouseover)){var e=s._isKeyDownForAction(s.AXIS_VIEW_RIGHT),a=s._isKeyDownForAction(s.AXIS_VIEW_BACK),l=s._isKeyDownForAction(s.AXIS_VIEW_LEFT),u=s._isKeyDownForAction(s.AXIS_VIEW_FRONT),c=s._isKeyDownForAction(s.AXIS_VIEW_TOP),A=s._isKeyDownForAction(s.AXIS_VIEW_BOTTOM);if(e||a||l||u||c||A){var h=t.aabb,d=le.getAABB3Diag(h);le.getAABB3Center(h,gp);var p=Math.abs(d/Math.tan(i.cameraFlight.fitFOV*le.DEGTORAD)),f=1.1*d;wp.orthoScale=f,e?(wp.eye.set(le.addVec3(gp,le.mulVec3Scalar(o.worldRight,p,mp),bp)),wp.look.set(gp),wp.up.set(o.worldUp)):a?(wp.eye.set(le.addVec3(gp,le.mulVec3Scalar(o.worldForward,p,mp),bp)),wp.look.set(gp),wp.up.set(o.worldUp)):l?(wp.eye.set(le.addVec3(gp,le.mulVec3Scalar(o.worldRight,-p,mp),bp)),wp.look.set(gp),wp.up.set(o.worldUp)):u?(wp.eye.set(le.addVec3(gp,le.mulVec3Scalar(o.worldForward,-p,mp),bp)),wp.look.set(gp),wp.up.set(o.worldUp)):c?(wp.eye.set(le.addVec3(gp,le.mulVec3Scalar(o.worldUp,p,mp),bp)),wp.look.set(gp),wp.up.set(le.normalizeVec3(le.mulVec3Scalar(o.worldForward,1,_p),yp))):A&&(wp.eye.set(le.addVec3(gp,le.mulVec3Scalar(o.worldUp,-p,mp),bp)),wp.look.set(gp),wp.up.set(le.normalizeVec3(le.mulVec3Scalar(o.worldForward,-1,_p)))),!r.firstPerson&&r.followPointer&&i.pivotController.setPivotPos(gp),i.cameraFlight.duration>0?i.cameraFlight.flyTo(wp,(function(){i.pivotController.getPivoting()&&r.followPointer&&i.pivotController.showPivot()})):(i.cameraFlight.jumpTo(wp),i.pivotController.getPivoting()&&r.followPointer&&i.pivotController.showPivot())}}}))}return I(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){this._scene.input.off(this._onSceneKeyDown)}}]),e}(),xp=function(){function e(t,i,r,n,s){var o=this;E(this,e),this._scene=t;var a=i.pickController,l=i.pivotController,u=i.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null,this._lastClickedWorldPos=null;var c=!1,A=!1,h=this._scene.canvas.canvas,d=function(e){var r;e&&e.worldPos&&(r=e.worldPos);var n=e&&e.entity?e.entity.aabb:t.aabb;if(r){var s=t.camera;le.subVec3(s.eye,s.look,[]),i.cameraFlight.flyTo({aabb:n})}else i.cameraFlight.flyTo({aabb:n})},p=t.tickify(this._canvasMouseMoveHandler=function(e){if(r.active&&r.pointerEnabled&&!c&&!A){if(u.hasSubs("rayMove")){var i=le.vec3(),s=le.vec3();le.canvasPosToWorldRay(t.canvas.canvas,t.camera.viewMatrix,t.camera.projMatrix,t.camera.projection,n.pointerCanvasPos,i,s),u.fire("rayMove",{canvasPos:n.pointerCanvasPos,ray:{origin:i,direction:s,canvasPos:n.pointerCanvasPos}},!0)}var l=u.hasSubs("hover"),h=u.hasSubs("hoverEnter"),d=u.hasSubs("hoverOut"),p=u.hasSubs("hoverOff"),f=u.hasSubs("hoverSurface"),v=u.hasSubs("hoverSnapOrSurface");if(l||h||d||p||f||v)if(a.pickCursorPos=n.pointerCanvasPos,a.schedulePickEntity=!0,a.schedulePickSurface=f,a.scheduleSnapOrPick=v,a.update(),a.pickResult){if(a.pickResult.entity){var g=a.pickResult.entity.id;o._lastPickedEntityId!==g&&(void 0!==o._lastPickedEntityId&&u.fire("hoverOut",{entity:t.objects[o._lastPickedEntityId]},!0),u.fire("hoverEnter",a.pickResult,!0),o._lastPickedEntityId=g)}u.fire("hover",a.pickResult,!0),(a.pickResult.worldPos||a.pickResult.snappedWorldPos)&&u.fire("hoverSurface",a.pickResult,!0)}else void 0!==o._lastPickedEntityId&&(u.fire("hoverOut",{entity:t.objects[o._lastPickedEntityId]},!0),o._lastPickedEntityId=void 0),u.fire("hoverOff",{canvasPos:a.pickCursorPos},!0)}});h.addEventListener("mousemove",p),h.addEventListener("mousedown",this._canvasMouseDownHandler=function(e){if(1===e.which&&(c=!0),3===e.which&&(A=!0),1===e.which&&r.active&&r.pointerEnabled&&(n.mouseDownClientX=e.clientX,n.mouseDownClientY=e.clientY,n.mouseDownCursorX=n.pointerCanvasPos[0],n.mouseDownCursorY=n.pointerCanvasPos[1],!r.firstPerson&&r.followPointer&&(a.pickCursorPos=n.pointerCanvasPos,a.schedulePickSurface=!0,a.update(),1===e.which))){var i=a.pickResult;i&&i.worldPos?(l.setPivotPos(i.worldPos),l.startPivot(),o._lastClickedWorldPos=i.worldPos.slice()):(r.smartPivot?l.setCanvasPivotPos(n.pointerCanvasPos):o._lastClickedWorldPos?l.setPivotPos(o._lastClickedWorldPos):l.setPivotPos(t.camera.look),l.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=function(e){1===e.which&&(c=!1),3===e.which&&(A=!1),l.getPivoting()&&l.endPivot()}),h.addEventListener("mouseup",this._canvasMouseUpHandler=function(e){if(r.active&&r.pointerEnabled&&(1===e.which&&(l.hidePivot(),!(Math.abs(e.clientX-n.mouseDownClientX)>3||Math.abs(e.clientY-n.mouseDownClientY)>3)))){var s=u.hasSubs("picked"),c=u.hasSubs("pickedNothing"),A=u.hasSubs("pickedSurface"),h=u.hasSubs("doublePicked"),p=u.hasSubs("doublePickedSurface"),f=u.hasSubs("doublePickedNothing");if(!(r.doublePickFlyTo||h||p||f))return(s||c||A)&&(a.pickCursorPos=n.pointerCanvasPos,a.schedulePickEntity=!0,a.schedulePickSurface=A,a.update(),a.pickResult?(u.fire("picked",a.pickResult,!0),a.pickedSurface&&u.fire("pickedSurface",a.pickResult,!0)):u.fire("pickedNothing",{canvasPos:n.pointerCanvasPos},!0)),void(o._clicks=0);if(o._clicks++,1===o._clicks){a.pickCursorPos=n.pointerCanvasPos,a.schedulePickEntity=r.doublePickFlyTo,a.schedulePickSurface=A,a.update();var v=a.pickResult,g=a.pickedSurface;o._timeout=setTimeout((function(){v?(u.fire("picked",v,!0),g&&(u.fire("pickedSurface",v,!0),!r.firstPerson&&r.followPointer&&(i.pivotController.setPivotPos(v.worldPos),i.pivotController.startPivot()&&i.pivotController.showPivot()))):u.fire("pickedNothing",{canvasPos:n.pointerCanvasPos},!0),o._clicks=0}),r.doubleClickTimeFrame)}else{if(null!==o._timeout&&(window.clearTimeout(o._timeout),o._timeout=null),a.pickCursorPos=n.pointerCanvasPos,a.schedulePickEntity=r.doublePickFlyTo||h||p,a.schedulePickSurface=a.schedulePickEntity&&p,a.update(),a.pickResult){if(u.fire("doublePicked",a.pickResult,!0),a.pickedSurface&&u.fire("doublePickedSurface",a.pickResult,!0),r.doublePickFlyTo&&(d(a.pickResult),!r.firstPerson&&r.followPointer)){var m=a.pickResult.entity.aabb,_=le.getAABB3Center(m);i.pivotController.setPivotPos(_),i.pivotController.startPivot()&&i.pivotController.showPivot()}}else if(u.fire("doublePickedNothing",{canvasPos:n.pointerCanvasPos},!0),r.doublePickFlyTo&&(d(),!r.firstPerson&&r.followPointer)){var y=t.aabb,b=le.getAABB3Center(y);i.pivotController.setPivotPos(b),i.pivotController.startPivot()&&i.pivotController.showPivot()}o._clicks=0}}},!1)}return I(e,[{key:"reset",value:function(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}]),e}(),Pp=function(){function e(t,i,r,n,s){E(this,e),this._scene=t;var o=t.input,a=[];t.canvas.canvas;var l=!0;this._onSceneMouseMove=o.on("mousemove",(function(){l=!0})),this._onSceneKeyDown=o.on("keydown",(function(e){r.active&&r.pointerEnabled&&t.input.keyboardEnabled&&(r.keyboardEnabledOnlyIfMouseover&&!n.mouseover||(a[e]=!0))})),this._onSceneKeyUp=o.on("keyup",(function(e){r.active&&r.pointerEnabled&&t.input.keyboardEnabled&&(a[e]=!1,i.pivotController.getPivoting()&&i.pivotController.endPivot())})),document.addEventListener("visibilitychange",this._onVisibilityChange=function(){a.splice(0)}),window.addEventListener("blur",this._onBlur=function(){a.splice(0)}),this._onTick=t.on("tick",(function(e){if(r.active&&r.pointerEnabled&&t.input.keyboardEnabled&&(!r.keyboardEnabledOnlyIfMouseover||n.mouseover)){var u=i.cameraControl,c=e.deltaTime/1e3;if(!r.planView){var A=u._isKeyDownForAction(u.ROTATE_Y_POS,a),h=u._isKeyDownForAction(u.ROTATE_Y_NEG,a),d=u._isKeyDownForAction(u.ROTATE_X_POS,a),p=u._isKeyDownForAction(u.ROTATE_X_NEG,a),f=c*r.keyboardRotationRate;(A||h||d||p)&&(!r.firstPerson&&r.followPointer&&i.pivotController.startPivot(),A?s.rotateDeltaY+=f:h&&(s.rotateDeltaY-=f),d?s.rotateDeltaX+=f:p&&(s.rotateDeltaX-=f),!r.firstPerson&&r.followPointer&&i.pivotController.startPivot())}if(!a[o.KEY_CTRL]&&!a[o.KEY_ALT]){var v=u._isKeyDownForAction(u.DOLLY_BACKWARDS,a),g=u._isKeyDownForAction(u.DOLLY_FORWARDS,a);if(v||g){var m=c*r.keyboardDollyRate;!r.firstPerson&&r.followPointer&&i.pivotController.startPivot(),g?s.dollyDelta-=m:v&&(s.dollyDelta+=m),l&&(n.followPointerDirty=!0,l=!1)}}var _=u._isKeyDownForAction(u.PAN_FORWARDS,a),y=u._isKeyDownForAction(u.PAN_BACKWARDS,a),b=u._isKeyDownForAction(u.PAN_LEFT,a),w=u._isKeyDownForAction(u.PAN_RIGHT,a),B=u._isKeyDownForAction(u.PAN_UP,a),x=u._isKeyDownForAction(u.PAN_DOWN,a),P=(a[o.KEY_ALT]?.3:1)*c*r.keyboardPanRate;(_||y||b||w||B||x)&&(!r.firstPerson&&r.followPointer&&i.pivotController.startPivot(),x?s.panDeltaY+=P:B&&(s.panDeltaY+=-P),w?s.panDeltaX+=-P:b&&(s.panDeltaX+=P),y?s.panDeltaZ+=P:_&&(s.panDeltaZ+=-P))}}))}return I(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),document.removeEventListener("visibilitychange",this._onVisibilityChange),window.removeEventListener("blur",this._onBlur),this._scene.input.off(this._onSceneKeyUp)}}]),e}(),Cp=le.vec3(),Mp=function(){function e(t,i,r,n,s){E(this,e),this._scene=t;var o=t.camera,a=i.pickController,l=i.pivotController,u=i.panController,c=i.cameraControl,A=1,h=1,d=null;this._onTick=t.on("tick",(function(){if(r.active&&r.pointerEnabled){var e="default";if(Math.abs(s.dollyDelta)<.001&&(s.dollyDelta=0),Math.abs(s.rotateDeltaX)<.001&&(s.rotateDeltaX=0),Math.abs(s.rotateDeltaY)<.001&&(s.rotateDeltaY=0),0===s.rotateDeltaX&&0===s.rotateDeltaY||(s.dollyDelta=0),r.followPointer){if(--A<=0&&(A=1,0!==s.dollyDelta)){if(0===s.rotateDeltaY&&0===s.rotateDeltaX&&r.followPointer&&n.followPointerDirty&&(a.pickCursorPos=n.pointerCanvasPos,a.schedulePickSurface=!0,a.update(),a.pickResult&&a.pickResult.worldPos?d=a.pickResult.worldPos:(h=1,d=null),n.followPointerDirty=!1),d){var i=Math.abs(le.lenVec3(le.subVec3(d,t.camera.eye,Cp)));h=i/r.dollyProximityThreshold}h<r.dollyMinSpeed&&(h=r.dollyMinSpeed)}}else h=1,d=null;var p=s.dollyDelta*h;if(0===s.rotateDeltaY&&0===s.rotateDeltaX||(!r.firstPerson&&r.followPointer&&l.getPivoting()?(l.continuePivot(s.rotateDeltaY,s.rotateDeltaX),l.showPivot()):(0!==s.rotateDeltaX&&(r.firstPerson?o.pitch(-s.rotateDeltaX):o.orbitPitch(s.rotateDeltaX)),0!==s.rotateDeltaY&&(r.firstPerson?o.yaw(s.rotateDeltaY):o.orbitYaw(s.rotateDeltaY))),s.rotateDeltaX*=r.rotationInertia,s.rotateDeltaY*=r.rotationInertia,e=c._cursors.rotate),Math.abs(s.panDeltaX)<.001&&(s.panDeltaX=0),Math.abs(s.panDeltaY)<.001&&(s.panDeltaY=0),Math.abs(s.panDeltaZ)<.001&&(s.panDeltaZ=0),0!==s.panDeltaX||0!==s.panDeltaY||0!==s.panDeltaZ){var f,v,g=le.vec3();if(g[0]=s.panDeltaX,g[1]=s.panDeltaY,g[2]=s.panDeltaZ,r.constrainVertical){o.xUp?(f=o.eye[0],v=o.look[0]):o.yUp?(f=o.eye[1],v=o.look[1]):o.zUp&&(f=o.eye[2],v=o.look[2]),o.pan(g);var m=o.eye,_=o.look;o.xUp?(m[0]=f,_[0]=v):o.yUp?(m[1]=f,_[1]=v):o.zUp&&(m[2]=f,_[2]=v),o.eye=m,o.look=_}else o.pan(g);e=c._cursors.pan}if(s.panDeltaX*=r.panInertia,s.panDeltaY*=r.panInertia,s.panDeltaZ*=r.panInertia,0!==p){if(e=p<0?c._cursors.dollyForward:c._cursors.dollyBackward,r.firstPerson){var y,b;if(r.constrainVertical&&(o.xUp?(y=o.eye[0],b=o.look[0]):o.yUp?(y=o.eye[1],b=o.look[1]):o.zUp&&(y=o.eye[2],b=o.look[2])),r.followPointer)u.dollyToCanvasPos(d,n.pointerCanvasPos,-p)&&(n.followPointerDirty=!0);else o.pan([0,0,p]),o.ortho.scale=o.ortho.scale-p;if(r.constrainVertical){var w=o.eye,B=o.look;o.xUp?(w[0]=y,B[0]=b):o.yUp?(w[1]=y,B[1]=b):o.zUp&&(w[2]=y,B[2]=b),o.eye=w,o.look=B}}else if(r.planView){if(r.followPointer)u.dollyToCanvasPos(d,n.pointerCanvasPos,-p)&&(n.followPointerDirty=!0);else o.ortho.scale=o.ortho.scale+p,o.zoom(p)}else{if(r.followPointer)u.dollyToCanvasPos(d,n.pointerCanvasPos,-p)&&(n.followPointerDirty=!0);else o.ortho.scale=o.ortho.scale+p,o.zoom(p)}s.dollyDelta*=r.dollyInertia}a.fireEvents(),document.body.style.cursor=e}}))}return I(e,[{key:"destroy",value:function(){this._scene.off(this._onTick)}}]),e}(),kp=function(){function e(t,i,r,n,s){E(this,e),this._scene=t;var o=this._scene.canvas.canvas;o.addEventListener("mouseenter",this._mouseEnterHandler=function(){n.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=function(){n.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=function(e){Ep(e,o,n.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=function(e){r.active&&r.pointerEnabled&&(Ep(e,o,n.pointerCanvasPos),n.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=function(e){r.active&&r.pointerEnabled})}return I(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}]),e}();function Ep(e,t,i){if(e){var r=t.getBoundingClientRect(),n=r.left,s=r.top;i[0]=e.clientX-n,i[1]=e.clientY-s}else e=window.event,i[0]=e.x,i[1]=e.y;return i}var Fp=function(e,t){if(e){for(var i=e.target,r=0,n=0;i.offsetParent;)r+=i.offsetLeft,n+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-r,t[1]=e.pageY-n}else e=window.event,t[0]=e.x,t[1]=e.y;return t},Ip=function(){function e(t,i,r,n,s){E(this,e),this._scene=t;var o=i.pickController,a=i.pivotController,l=le.vec2(),u=le.vec2(),c=le.vec2(),A=le.vec2(),h=[],d=this._scene.canvas.canvas,p=0,f=!1;this._onTick=t.on("tick",(function(){f=!1})),d.addEventListener("touchstart",this._canvasTouchStartHandler=function(e){if(r.active&&r.pointerEnabled){e.preventDefault();var i=e.touches,s=e.changedTouches;for(n.touchStartTime=Date.now(),1===i.length&&1===s.length&&(Fp(i[0],l),r.followPointer&&(o.pickCursorPos=l,o.schedulePickSurface=!0,o.update(),r.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(a.setPivotPos(o.pickResult.worldPos),!r.firstPerson&&a.startPivot()&&a.showPivot()):(r.smartPivot?a.setCanvasPivotPos(n.pointerCanvasPos):a.setPivotPos(t.camera.look),!r.firstPerson&&a.startPivot()&&a.showPivot()))));h.length<i.length;)h.push(le.vec2());for(var u=0,c=i.length;u<c;++u)Fp(i[u],h[u]);p=i.length}}),d.addEventListener("touchend",this._canvasTouchEndHandler=function(){a.getPivoting()&&(a.endPivot(),a.hidePivot())}),d.addEventListener("touchmove",this._canvasTouchMoveHandler=function(e){if(r.active&&r.pointerEnabled&&(e.stopPropagation(),e.preventDefault(),!f)){f=!0;var i=t.canvas.boundary,a=i[2],l=i[3],d=e.touches;if(e.touches.length===p){if(1===p){Fp(d[0],u),le.subVec2(u,h[0],A);var v=A[0],g=A[1];if(null!==n.longTouchTimeout&&(Math.abs(v)>r.longTapRadius||Math.abs(g)>r.longTapRadius)&&(clearTimeout(n.longTouchTimeout),n.longTouchTimeout=null),r.planView){var m=t.camera;if("perspective"===m.projection){var _=Math.abs(t.camera.eyeLookDist)*Math.tan(m.perspective.fov/2*Math.PI/180);s.panDeltaX+=v*_/l*r.touchPanRate,s.panDeltaY+=g*_/l*r.touchPanRate}else s.panDeltaX+=.5*m.ortho.scale*(v/l)*r.touchPanRate,s.panDeltaY+=.5*m.ortho.scale*(g/l)*r.touchPanRate}else s.rotateDeltaY-=v/a*(1*r.dragRotationRate),s.rotateDeltaX+=g/l*(1.5*r.dragRotationRate)}else if(2===p){var y=d[0],b=d[1];Fp(y,u),Fp(b,c);var w=le.geometricMeanVec2(h[0],h[1]),B=le.geometricMeanVec2(u,c),x=le.vec2();le.subVec2(w,B,x);var P=x[0],C=x[1],M=t.camera,k=le.distVec2([y.pageX,y.pageY],[b.pageX,b.pageY]),E=(le.distVec2(h[0],h[1])-k)*r.touchDollyRate;if(s.dollyDelta=E,Math.abs(E)<1)if("perspective"===M.projection){var F=o.pickResult?o.pickResult.worldPos:t.center,I=Math.abs(le.lenVec3(le.subVec3(F,t.camera.eye,[])))*Math.tan(M.perspective.fov/2*Math.PI/180);s.panDeltaX-=P*I/l*r.touchPanRate,s.panDeltaY-=C*I/l*r.touchPanRate}else s.panDeltaX-=.5*M.ortho.scale*(P/l)*r.touchPanRate,s.panDeltaY-=.5*M.ortho.scale*(C/l)*r.touchPanRate;n.pointerCanvasPos=B}for(var T=0;T<p;++T)Fp(d[T],h[T])}}})}return I(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler),e.removeEventListener("touchmove",this._canvasTouchMoveHandler),this._scene.off(this._onTick)}}]),e}(),Tp=function(e,t){if(e){for(var i=e.target,r=0,n=0;i.offsetParent;)r+=i.offsetLeft,n+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-r,t[1]=e.pageY-n}else e=window.event,t[0]=e.x,t[1]=e.y;return t},Dp=function(){function e(t,i,r,n,s){E(this,e),this._scene=t;var o,a=i.pickController,l=i.cameraControl,u=[],c=new Float32Array(2),A=-1,h=-1,d=this._scene.canvas.canvas,p=function(e){var r;e&&e.worldPos&&(r=e.worldPos);var n=e?e.entity.aabb:t.aabb;if(r){var s=t.camera;le.subVec3(s.eye,s.look,[]),i.cameraFlight.flyTo({aabb:n})}else i.cameraFlight.flyTo({aabb:n})};d.addEventListener("touchstart",this._canvasTouchStartHandler=function(e){if(r.active&&r.pointerEnabled){null!==n.longTouchTimeout&&(clearTimeout(n.longTouchTimeout),n.longTouchTimeout=null);var t=e.touches,s=e.changedTouches;if(o=Date.now(),1===t.length&&1===s.length){A=o,Tp(t[0],c);var a=c[0],l=c[1],h=t[0].pageX,d=t[0].pageY;n.longTouchTimeout=setTimeout((function(){r.active&&r.pointerEnabled&&i.cameraControl.fire("rightClick",{pagePos:[Math.round(h),Math.round(d)],canvasPos:[Math.round(a),Math.round(l)],event:e},!0),n.longTouchTimeout=null}),r.longTapTimeout)}else A=-1;for(;u.length<t.length;)u.push(new Float32Array(2));for(var p=0,f=t.length;p<f;++p)Tp(t[p],u[p]);u.length=t.length}},{passive:!0}),d.addEventListener("touchend",this._canvasTouchEndHandler=function(e){if(r.active&&r.pointerEnabled){var t=Date.now(),i=e.touches,s=e.changedTouches,o=l.hasSubs("pickedSurface");null!==n.longTouchTimeout&&(clearTimeout(n.longTouchTimeout),n.longTouchTimeout=null),0===i.length&&1===s.length&&A>-1&&t-A<150&&(h>-1&&A-h<325?(Tp(s[0],a.pickCursorPos),a.schedulePickEntity=!0,a.schedulePickSurface=o,a.update(),a.pickResult?(a.pickResult.touchInput=!0,l.fire("doublePicked",a.pickResult),a.pickedSurface&&l.fire("doublePickedSurface",a.pickResult),r.doublePickFlyTo&&p(a.pickResult)):(l.fire("doublePickedNothing"),r.doublePickFlyTo&&p()),h=-1):le.distVec2(u[0],c)<4&&(Tp(s[0],a.pickCursorPos),a.schedulePickEntity=!0,a.schedulePickSurface=o,a.update(),a.pickResult?(a.pickResult.touchInput=!0,l.fire("picked",a.pickResult),a.pickedSurface&&l.fire("pickedSurface",a.pickResult)):l.fire("pickedNothing"),h=t),A=-1),u.length=i.length;for(var d=0,f=i.length;d<f;++d)u[d][0]=i[d].pageX,u[d][1]=i[d].pageY}},{passive:!0})}return I(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler)}}]),e}(),Sp=function(e){m(i,Ie);var t=y(i);function i(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E(this,i),(r=t.call(this,e,n)).PAN_LEFT=0,r.PAN_RIGHT=1,r.PAN_UP=2,r.PAN_DOWN=3,r.PAN_FORWARDS=4,r.PAN_BACKWARDS=5,r.ROTATE_X_POS=6,r.ROTATE_X_NEG=7,r.ROTATE_Y_POS=8,r.ROTATE_Y_NEG=9,r.DOLLY_FORWARDS=10,r.DOLLY_BACKWARDS=11,r.AXIS_VIEW_RIGHT=12,r.AXIS_VIEW_BACK=13,r.AXIS_VIEW_LEFT=14,r.AXIS_VIEW_FRONT=15,r.AXIS_VIEW_TOP=16,r.AXIS_VIEW_BOTTOM=17,r.MOUSE_PAN=18,r.MOUSE_ROTATE=19,r.MOUSE_DOLLY=20,r._keyMap={},r.scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},r._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,zoomOnMouseWheel:!0,snapToVertex:true,snapToEdge:true,snapRadius:30,keyboardEnabledOnlyIfMouseover:!0,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},r._states={pointerCanvasPos:le.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:le.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},r._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};var s=r.scene;return r._controllers={cameraControl:w(r),pickController:new pp(w(r),r._configs),pivotController:new dp(s,r._configs),panController:new sp(s),cameraFlight:new et(w(r),{duration:.5})},r._handlers=[new kp(r.scene,r._controllers,r._configs,r._states,r._updates),new Ip(r.scene,r._controllers,r._configs,r._states,r._updates),new vp(r.scene,r._controllers,r._configs,r._states,r._updates),new Bp(r.scene,r._controllers,r._configs,r._states,r._updates),new xp(r.scene,r._controllers,r._configs,r._states,r._updates),new Dp(r.scene,r._controllers,r._configs,r._states,r._updates),new Pp(r.scene,r._controllers,r._configs,r._states,r._updates)],r._cursors={dollyForward:"zoom-in",dollyBackward:"zoom-out",rotate:"grabbing",pan:"move"},r._cameraUpdater=new Mp(r.scene,r._controllers,r._configs,r._states,r._updates),r.navMode=n.navMode,n.planView&&(r.planView=n.planView),r.constrainVertical=n.constrainVertical,n.keyboardLayout?r.keyboardLayout=n.keyboardLayout:r.keyMap=n.keyMap,r.doublePickFlyTo=n.doublePickFlyTo,r.panRightClick=n.panRightClick,r.active=n.active,r.followPointer=n.followPointer,r.rotationInertia=n.rotationInertia,r.keyboardPanRate=n.keyboardPanRate,r.touchPanRate=n.touchPanRate,r.keyboardRotationRate=n.keyboardRotationRate,r.dragRotationRate=n.dragRotationRate,r.touchDollyRate=n.touchDollyRate,r.dollyInertia=n.dollyInertia,r.dollyProximityThreshold=n.dollyProximityThreshold,r.dollyMinSpeed=n.dollyMinSpeed,r.panInertia=n.panInertia,r.pointerEnabled=!0,r.keyboardDollyRate=n.keyboardDollyRate,r.mouseWheelDollyRate=n.mouseWheelDollyRate,r}return I(i,[{key:"keyMap",get:function(){return this._keyMap},set:function(e){if(e=e||"qwerty",ge.isString(e)){var t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6],i[this.MOUSE_PAN]=[[t.MOUSE_LEFT_BUTTON,t.KEY_SHIFT],this._configs.panRightClick?t.MOUSE_RIGHT_BUTTON:t.MOUSE_MIDDLE_BUTTON],i[this.MOUSE_ROTATE]=[t.MOUSE_LEFT_BUTTON],i[this.MOUSE_DOLLY]=[];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6],i[this.MOUSE_PAN]=[[t.MOUSE_LEFT_BUTTON,t.KEY_SHIFT],this._configs.panRightClick?t.MOUSE_RIGHT_BUTTON:t.MOUSE_MIDDLE_BUTTON],i[this.MOUSE_ROTATE]=[t.MOUSE_LEFT_BUTTON],i[this.MOUSE_DOLLY]=[]}this._keyMap=i}else{var r=e;this._keyMap=r}}},{key:"_areAllKeysDown",value:function(e,t){if(!t||t.length<=0)return!0;if(!e)return!1;for(var i=0,r=t.length;i<r;i++){if(!e[t[i]])return!1}return!0}},{key:"_isAnyOtherKeyDown",value:function(e,t){for(var i=0,r=e.length;i<r;i++)if(e[i])if(Array.isArray(t)){if(t.indexOf(i)<0)return!0}else if(i!==t)return!0;return!1}},{key:"_isMouseAction",value:function(e){switch(e){case this.MOUSE_ROTATE:case this.MOUSE_DOLLY:case this.MOUSE_PAN:return!0;default:return!1}}},{key:"_isKeyDownForAction",value:function(e,t){var i=this._keyMap[e];if(!i)return!1;if(0===i.length&&this._isMouseAction(e))return!0;t||(t=this.scene.input.keyDown);for(var r=0,n=i.length;r<n;r++){var s=i[r];if(Array.isArray(s)){if(this._areAllKeysDown(t,s)&&!this._isAnyOtherKeyDown(t,s))return!0}else if(t[s]&&!this._isAnyOtherKeyDown(t,s))return!0}return!1}},{key:"pivotElement",set:function(e){this._controllers.pivotController.setPivotElement(e)}},{key:"active",get:function(){return this._configs.active},set:function(e){e=!1!==e,this._configs.active=e,this._handlers[1]._active=e,this._handlers[5]._active=e}},{key:"snapToVertex",get:function(){return this._configs.snapToVertex},set:function(e){this._configs.snapToVertex=!!e}},{key:"snapToEdge",get:function(){return this._configs.snapToEdge},set:function(e){this._configs.snapToEdge=!!e}},{key:"snapRadius",get:function(){return this._configs.snapRadius},set:function(e){e=e||30,this._configs.snapRadius=e}},{key:"keyboardEnabledOnlyIfMouseover",get:function(){return this._configs.keyboardEnabledOnlyIfMouseover},set:function(e){this._configs.keyboardEnabledOnlyIfMouseover=!!e}},{key:"navMode",get:function(){return this._configs.navMode},set:function(e){"firstPerson"!==(e=e||"orbit")&&"orbit"!==e&&"planView"!==e&&(this.error("Unsupported value for navMode: "+e+" - supported values are 'orbit', 'firstPerson' and 'planView' - defaulting to 'orbit'"),e="orbit"),this._configs.firstPerson="firstPerson"===e,this._configs.planView="planView"===e,(this._configs.firstPerson||this._configs.planView)&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this._configs.navMode=e}},{key:"pointerEnabled",get:function(){return this._configs.pointerEnabled},set:function(e){this._reset(),this._configs.pointerEnabled=!!e}},{key:"setCursorStyle",value:function(e,t){Object.prototype.hasOwnProperty.call(this._cursors,e)?this._cursors=h(h({},this._cursors),{},d({},e,t)):console.warn("Action '".concat(e,"' is not valid for cursor styles."))}},{key:"getCursorStyle",value:function(e){return this._cursors[e]||null}},{key:"_reset",value:function(){for(var e=0,t=this._handlers.length;e<t;e++){var i=this._handlers[e];i.reset&&i.reset()}this._updates.panDeltaX=0,this._updates.panDeltaY=0,this._updates.rotateDeltaX=0,this._updates.rotateDeltaY=0,this._updates.dolyDelta=0}},{key:"followPointer",get:function(){return this._configs.followPointer},set:function(e){this._configs.followPointer=!1!==e}},{key:"pivotPos",get:function(){return this._controllers.pivotController.getPivotPos()},set:function(e){this._controllers.pivotController.setPivotPos(e)}},{key:"dollyToPointer",get:function(){return this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer},set:function(e){this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer=e}},{key:"panToPointer",get:function(){return this.warn("panToPointer property is deprecated - replaced with followPointer"),!1},set:function(e){this.warn("panToPointer property is deprecated - replaced with followPointer")}},{key:"planView",get:function(){return this.warn("planView property is deprecated - replaced with navMode"),this._configs.planView},set:function(e){this._configs.planView=!!e,this._configs.firstPerson=!1,this._configs.planView&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this.warn("planView property is deprecated - replaced with navMode")}},{key:"firstPerson",get:function(){return this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson},set:function(e){this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson=!!e,this._configs.planView=!1,this._configs.firstPerson&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot())}},{key:"constrainVertical",get:function(){return this._configs.constrainVertical},set:function(e){this._configs.constrainVertical=!!e}},{key:"doublePickFlyTo",get:function(){return this._configs.doublePickFlyTo},set:function(e){this._configs.doublePickFlyTo=!1!==e}},{key:"panRightClick",get:function(){return this._configs.panRightClick},set:function(e){this._configs.panRightClick=!1!==e;var t=this._keyMap[this.MOUSE_PAN];if(t&&t.length>0)for(var i=this.scene.input,r=0,n=t.length;r<n;r++)this._configs.panRightClick&&t[r]===i.MOUSE_MIDDLE_BUTTON?this._keyMap[this.MOUSE_PAN][r]=i.MOUSE_RIGHT_BUTTON:this._configs.panRightClick||t[r]!==i.MOUSE_RIGHT_BUTTON||(this._keyMap[this.MOUSE_PAN][r]=i.MOUSE_MIDDLE_BUTTON)}},{key:"rotationInertia",get:function(){return this._configs.rotationInertia},set:function(e){this._configs.rotationInertia=null!=e?e:0}},{key:"keyboardPanRate",get:function(){return this._configs.keyboardPanRate},set:function(e){this._configs.keyboardPanRate=null!=e?e:5}},{key:"touchPanRate",get:function(){return this._configs.touchPanRate},set:function(e){this._configs.touchPanRate=null!=e?e:1}},{key:"keyboardRotationRate",get:function(){return this._configs.keyboardRotationRate},set:function(e){this._configs.keyboardRotationRate=null!=e?e:90}},{key:"dragRotationRate",get:function(){return this._configs.dragRotationRate},set:function(e){this._configs.dragRotationRate=null!=e?e:360}},{key:"keyboardDollyRate",get:function(){return this._configs.keyboardDollyRate},set:function(e){this._configs.keyboardDollyRate=null!=e?e:15}},{key:"touchDollyRate",get:function(){return this._configs.touchDollyRate},set:function(e){this._configs.touchDollyRate=null!=e?e:.2}},{key:"mouseWheelDollyRate",get:function(){return this._configs.mouseWheelDollyRate},set:function(e){this._configs.mouseWheelDollyRate=null!=e?e:100}},{key:"dollyInertia",get:function(){return this._configs.dollyInertia},set:function(e){this._configs.dollyInertia=null!=e?e:0}},{key:"dollyProximityThreshold",get:function(){return this._configs.dollyProximityThreshold},set:function(e){this._configs.dollyProximityThreshold=null!=e?e:35}},{key:"dollyMinSpeed",get:function(){return this._configs.dollyMinSpeed},set:function(e){this._configs.dollyMinSpeed=null!=e?e:.04}},{key:"panInertia",get:function(){return this._configs.panInertia},set:function(e){this._configs.panInertia=null!=e?e:.5}},{key:"keyboardLayout",get:function(){return this._configs.keyboardLayout},set:function(e){"qwerty"!==(e=e||"qwerty")&&"azerty"!==e&&(this.error("Unsupported value for keyboardLayout - defaulting to 'qwerty'"),e="qwerty"),this._configs.keyboardLayout=e,this.keyMap=this._configs.keyboardLayout}},{key:"enablePivotSphere",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._controllers.pivotController.enablePivotSphere(e)}},{key:"disablePivotSphere",value:function(){this._controllers.pivotController.disablePivotSphere()}},{key:"smartPivot",get:function(){return this._configs.smartPivot},set:function(e){this._configs.smartPivot=!1!==e}},{key:"doubleClickTimeFrame",get:function(){return this._configs.doubleClickTimeFrame},set:function(e){this._configs.doubleClickTimeFrame=null!=e?e:250}},{key:"zoomOnMouseWheel",get:function(){return this._configs.zoomOnMouseWheel},set:function(e){this._configs.zoomOnMouseWheel=!!e}},{key:"destroy",value:function(){this._destroyHandlers(),this._destroyControllers(),this._cameraUpdater.destroy(),v(x(i.prototype),"destroy",this).call(this)}},{key:"_destroyHandlers",value:function(){for(var e=0,t=this._handlers.length;e<t;e++){var i=this._handlers[e];i.destroy&&i.destroy()}}},{key:"_destroyControllers",value:function(){for(var e=0,t=this._controllers.length;e<t;e++){var i=this._controllers[e];i.destroy&&i.destroy()}}}]),i}(),Rp=I((function e(t,i,r,n,s){E(this,e),this.name=t,this.type=r,this.value=i,this.valueType=n,this.description=s})),Up=I((function e(t){if(E(this,e),this.id=t.id,this.originalSystemId=t.originalSystemId,this.metaModels=[],this.name=t.name,this.type=t.type,this.properties=[],t.properties)for(var i=t.properties,r=0,n=i.length;r<n;r++){var s=i[r];Number.isInteger(s)?this.properties.push(s):this.properties.push(new Rp(s.name,s.value,s.type,s.valueType,s.description))}})),Lp=function(){function e(t){E(this,e),this.metaModels=[],this.id=t.id,this.parentId=t.parentId,this.parent=null,this.originalSystemId=t.originalSystemId,this.name=t.name,this.type=t.type,this.propertySetIds=t.propertySetIds,this.propertySets=[],this.attributes=t.attributes||{},void 0!==t.external&&null!==t.external&&(this.external=t.external)}return I(e,[{key:"metaModel",get:function(){return 1==this.metaModels.length?this.metaModels[0]:null}},{key:"getObjectIDsInSubtree",value:function(){var e=[];return function t(i){if(i){e.push(i.id);var r=i.children;if(r)for(var n=0,s=r.length;n<s;n++)t(r[n])}}(this),e}},{key:"withMetaObjectsInSubtree",value:function(e){!function t(i){if(i){e(i);var r=i.children;if(r)for(var n=0,s=r.length;n<s;n++)t(r[n])}}(this)}},{key:"getObjectIDsInSubtreeByType",value:function(e){for(var t={},i=0,r=e.length;i<r;i++)t[e[i]]=e[i];var n=[];return function e(i){if(i){t[i.type]&&n.push(i.id);var r=i.children;if(r)for(var s=0,o=r.length;s<o;s++)e(r[s])}}(this),n}},{key:"getJSON",value:function(){var e={id:this.id,type:this.type,name:this.name};return this.parent&&(e.parent=this.parent.id),e}}]),e}(),Op=function(){function e(t){E(this,e),this.id=t.id,this.projectId=t.projectId,this.revisionId=t.revisionId,this.author=t.author,this.createdAt=t.createdAt,this.creatingApplication=t.creatingApplication,this.schema=t.schema,this.metaScene=t.metaScene,this.propertySets=[],this.rootMetaObjects=[],this.metaObjects={},this.graph=t.graph||{},this.metaScene.metaModels[this.id]=this,this._propertyLookup=[],this.finalized=!1}return I(e,[{key:"rootMetaObject",get:function(){return 1===this.rootMetaObjects.length?this.rootMetaObjects[0]:null}},{key:"loadData",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.finalized)throw"MetaScene already finalized - can't add more data";this._globalizeIDs(e,t);var i=this.metaScene,r=e.properties;if(r)for(var n=0,s=r.length;n<s;n++)this._propertyLookup.push(r[n]);if(e.propertySets)for(var o=0,a=e.propertySets.length;o<a;o++){var l=e.propertySets[o];l.properties||(l.properties=[]);var u=i.propertySets[l.id];u||(u=new Up({id:l.id,originalSystemId:l.originalSystemId||l.id,type:l.type,name:l.name,properties:l.properties}),i.propertySets[u.id]=u),u.metaModels.push(this),this.propertySets.push(u)}if(e.metaObjects)for(var c=0,A=e.metaObjects.length;c<A;c++){var h=e.metaObjects[c],d=h.id,p=i.metaObjects[d];if(!p){var f=h.type,v=h.originalSystemId,g=h.propertySets||h.propertySetIds;p=new Lp({id:d,originalSystemId:v,parentId:h.parent,type:f,name:h.name,attributes:h.attributes,propertySetIds:g,external:h.external}),this.metaScene.metaObjects[d]=p,p.metaModels=[]}this.metaObjects[d]=p,h.parent||(this.rootMetaObjects.push(p),i.rootMetaObjects[d]=p),p.metaModels.push(this)}}},{key:"_decompressProperties",value:function(e,t){for(var i=[],r=0,n=t.length;r<n;r++){var s=t[r];if(Number.isInteger(s)){var o=e[s];o?t[r]=o:i.push(s)}}i.length>0&&console.error("[MetaModel._decompressProperties] Properties not found: ".concat(i))}},{key:"finalize",value:function(){if(this.finalized)throw"MetaScene already finalized - can't re-finalize";var e=this.metaScene;for(var t in e.metaObjects){var i=e.metaObjects[t];if(i.children&&(i.children=[]),i.propertySets&&(i.propertySets=[]),i.propertySetIds)for(var r=0,n=i.propertySetIds.length;r<n;r++){var s=i.propertySetIds[r],o=e.propertySets[s];i.propertySets.push(o)}}for(var a in e.metaObjects){var l=e.metaObjects[a];if(l.parentId){var u=e.metaObjects[l.parentId];u&&(l.parent=u,(u.children||(u.children=[])).push(l))}}for(var c in e.metaObjects){e.metaObjects[c].metaModels=[]}for(var A in e.metaModels){var h=e.metaModels[A];for(var d in h.metaObjects){h.metaObjects[d].metaModels.push(h)}}for(var p in e.metaObjectsByType={},e.metaObjects){var f=e.metaObjects[p],v=f.type;(e.metaObjectsByType[v]||(e.metaObjectsByType[v]={}))[p]=f}if(this.propertySets)for(var g=0,m=this.propertySets.length;g<m;g++){var _=this.propertySets[g];this._decompressProperties(this._propertyLookup,_.properties)}this._propertyLookup=[],this.finalized=!0,this.metaScene.fire("metaModelCreated",this.id)}},{key:"getJSON",value:function(){for(var e={id:this.id,projectId:this.projectId,author:this.author,createdAt:this.createdAt,schema:this.schema,creatingApplication:this.creatingApplication,metaObjects:[],propertySets:[]},t=Object.values(this.metaObjects),i=0,r=t.length;i<r;i++){var n=t[i],s={id:n.id,originalSystemId:n.originalSystemId,extId:n.extId,type:n.type,name:n.name};n.parent&&(s.parent=n.parent.id),n.attributes&&(s.attributes=n.attributes),n.propertySetIds&&(s.propertySetIds=n.propertySetIds),e.metaObjects.push(s)}for(var o=0,a=this.propertySets.length;o<a;o++){for(var l=this.propertySets[o],u={id:l.id,originalSystemId:l.originalSystemId,extId:l.extId,type:l.type,name:l.name,propertyies:[]},c=0,A=l.properties.length;c<A;c++){var h=l.properties[c],d={id:h.id,description:h.description,type:h.type,name:h.name,value:h.value,valueType:h.valueType};u.properties.push(d)}e.propertySets.push(u)}return e}},{key:"_globalizeIDs",value:function(e,t){var i=!!t.globalizeObjectIds;if(e.metaObjects)for(var r=0,n=e.metaObjects.length;r<n;r++){var s=e.metaObjects[r];if(s.originalSystemId=s.id,s.parent&&(s.originalParentSystemId=s.parent),i&&(s.id=le.globalizeObjectId(this.id,s.id),s.parent&&(s.parent=le.globalizeObjectId(this.id,s.parent))),i){var o=s.propertySetIds;if(o){for(var a=[],l=0,u=o.length;l<u;l++)a.push(le.globalizeObjectId(this.id,o[l]));s.propertySetIds=a,s.originalSystemPropertySetIds=o}}else s.originalSystemPropertySetIds=s.propertySetIds}if(e.propertySets)for(var c=0,A=e.propertySets.length;c<A;c++){var h=e.propertySets[c];h.originalSystemId=h.id,i&&(h.id=le.globalizeObjectId(this.id,h.id))}}}]),e}(),Np=function(){function e(t,i){E(this,e),this.viewer=t,this.scene=i,this.metaModels={},this.propertySets={},this.metaObjects={},this.metaObjectsByType={},this.rootMetaObjects={},this._eventSubs={}}return I(e,[{key:"on",value:function(e,t){var i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}},{key:"fire",value:function(e,t){var i=this._eventSubs[e];if(i)for(var r=0,n=i.length;r<n;r++)i[r](t)}},{key:"off",value:function(e){}},{key:"createMetaModel",value:function(e,t){var i=new Op({metaScene:this,id:e,projectId:t.projectId||"none",revisionId:t.revisionId||"none",author:t.author||"none",createdAt:t.createdAt||"none",creatingApplication:t.creatingApplication||"none",schema:t.schema||"none",propertySets:[]});return i.loadData(t),i.finalize(),i}},{key:"destroyMetaModel",value:function(e){var t=this.metaModels[e];if(t){if(t.propertySets)for(var i=0,r=t.propertySets.length;i<r;i++){var n=t.propertySets[i];if(1===n.metaModels.length&&n.metaModels[0].id===e)delete this.propertySets[n.id];else{for(var s=[],o=0,a=n.metaModels.length;o<a;o++)n.metaModels[o].id!==e&&s.push(n.metaModels[o]);n.metaModels=s}}if(t.metaObjects)for(var l in t.metaObjects){var u=t.metaObjects[l];1===u.metaModels.length&&u.metaModels[0].id===e?(delete this.metaObjects[l],u.parent||delete this.rootMetaObjects[l]):u.metaModels=u.metaModels.filter((function(t){return t.id!==e}))}for(var c in this.metaObjects){var A=this.metaObjects[c];if(A.children&&(A.children=[]),A.propertySets&&(A.propertySets=[]),A.propertySetIds)for(var h=0,d=A.propertySetIds.length;h<d;h++){var p=A.propertySetIds[h],f=this.propertySets[p];A.propertySets.push(f)}}for(var v in this.metaObjectsByType={},this.metaObjects){var g=this.metaObjects[v],m=g.type;g.children&&(g.children=null),(this.metaObjectsByType[m]||(this.metaObjectsByType[m]={}))[v]=g}for(var _ in this.metaObjects){var y=this.metaObjects[_];if(y.parentId){var b=this.metaObjects[y.parentId];b&&(y.parent=b,(b.children||(b.children=[])).push(y))}}for(var w in delete this.metaModels[e],this.metaObjects){this.metaObjects[w].metaModels=[]}for(var B in this.metaModels){var x=this.metaModels[B];for(var P in x.metaObjects){x.metaObjects[P].metaModels.push(x)}}this.fire("metaModelDestroyed",e)}}},{key:"getObjectIDsByType",value:function(e){var t=this.metaObjectsByType[e];return t?Object.keys(t):[]}},{key:"getObjectIDsInSubtree",value:function(e,t,i){var r=[],n=this.metaObjects[e],s=t&&t.length>0?Vp(t):null,o=i&&i.length>0?Vp(i):null;return function e(t){if(t){var i=!0;(o&&o[t.type]||s&&!s[t.type])&&(i=!1),i&&r.push(t.id);var n=t.children;if(n)for(var a=0,l=n.length;a<l;a++)e(n[a])}}(n),r}},{key:"withMetaObjectsInSubtree",value:function(e,t){var i=this.metaObjects[e];i&&i.withMetaObjectsInSubtree(t)}}]),e}();function Vp(e){for(var t={},i=0,r=e.length;i<r;i++)t[e[i]]=!0;return t}
|
|
24
24
|
/*!
|
|
25
25
|
* html2canvas 1.4.1 <https://html2canvas.hertzen.com>
|
|
26
26
|
* Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
|