babylonjs-loaders 9.16.2 → 9.17.1
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/babylonjs.loaders.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("babylonjs")):"function"==typeof define&&define.amd?define(["exports","babylonjs"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).BABYLON=e.BABYLON||{},e.BABYLON)}(this,function(e,t){"use strict";const n="Xposition",o="Yposition",s="Zposition",r="Xrotation",i="Yrotation",a="Zrotation";class l{constructor(e){this.loopMode=t.Animation.ANIMATIONLOOPMODE_CYCLE,this.list=[],this.root=u(),this.numFrames=0,this.frameRate=0,this.skeleton=e}}function u(){return{name:"",type:"",offset:new t.Vector3,channels:[],children:[],frames:[],parent:null}}function c(e,l,u){const d=function(e){const n=e.offset.x,o=e.offset.y,s=e.offset.z;return t.Matrix.Translation(n,o,s)}(e),h=new t.Bone(e.name,u.skeleton,l,d),m=function(e,l){if(0===e.frames.length)return[];const u=[],c=e.channels.some(e=>e===n||e===o||e===s),d=e.channels.some(e=>e===r||e===i||e===a),h=new t.Animation(`${e.name}_pos`,"position",l.frameRate,t.Animation.ANIMATIONTYPE_VECTOR3,l.loopMode),m=new t.Animation(`${e.name}_rot`,"rotationQuaternion",l.frameRate,t.Animation.ANIMATIONTYPE_QUATERNION,l.loopMode),f=[],p=[];for(let t=0;t<e.frames.length;t++){const n=e.frames[t];c&&n.position&&f.push({frame:n.frame,value:n.position.clone()}),d&&p.push({frame:n.frame,value:n.rotation.clone()})}return f.length>0&&(h.setKeys(f),u.push(h)),p.length>0&&(m.setKeys(p),u.push(m)),u}(e,u);for(const e of m)e.getKeys()&&e.getKeys().length>0&&h.animations.push(e);for(const t of e.children)c(t,h,u)}function d(e,l,u,c){if("ENDSITE"===u.type)return;const h={frame:0,position:new t.Vector3,rotation:new t.Quaternion};h.frame=l,h.position=new t.Vector3,h.rotation=new t.Quaternion,u.frames.push(h);let m=t.Matrix.Identity();for(let l=0;l<u.channels.length;++l){const d=u.channels[l],f=e[c.i++];if(!f)continue;const p=parseFloat(f.trim());if(d.endsWith("position"))switch(d){case n:h.position.x=p;break;case o:h.position.y=p;break;case s:h.position.z=p}else if(d.endsWith("rotation")){const e=t.Tools.ToRadians(p);let n;switch(d){case r:n=t.Matrix.RotationX(e);break;case i:n=t.Matrix.RotationY(e);break;case a:n=t.Matrix.RotationZ(e)}m=n.multiply(m)}}t.Quaternion.FromRotationMatrixToRef(m,h.rotation);for(const t of u.children)d(e,l,t,c)}function h(e,n,o,s){var r,i,a,l;const c=u();c.parent=o,s.list.push(c);let d=n.trim().split(/\s+/);if("END"===d[0].toUpperCase()&&"SITE"===d[1].toUpperCase()?(c.type="ENDSITE",c.name="ENDSITE"):(c.name=d[1],c.type=d[0].toUpperCase()),"{"!=(null===(r=e.shift())||void 0===r?void 0:r.trim()))throw new Error("Expected opening { after type & name");const m=null===(i=e.shift())||void 0===i?void 0:i.trim().split(/\s+/);if(!m)throw new Error("Unexpected end of file: missing OFFSET");if(d=m,"OFFSET"!=d[0].toUpperCase())throw new Error("Expected OFFSET, but got: "+d[0]);if(4!=d.length)throw new Error("OFFSET: Invalid number of values");const f=new t.Vector3(parseFloat(d[1]),parseFloat(d[2]),parseFloat(d[3]));if(isNaN(f.x)||isNaN(f.y)||isNaN(f.z))throw new Error("OFFSET: Invalid values");if(c.offset=f,"ENDSITE"!=c.type){if(d=null===(a=e.shift())||void 0===a?void 0:a.trim().split(/\s+/),!d)throw new Error("Unexpected end of file: missing CHANNELS");if("CHANNELS"!=d[0].toUpperCase())throw new Error("Expected CHANNELS definition");const t=parseInt(d[1]);c.channels=d.splice(2,t),c.children=[]}for(;e.length>0;){const t=null===(l=e.shift())||void 0===l?void 0:l.trim();if("}"===t)return c;t&&c.children.push(h(e,t,c,s))}throw new Error("Unexpected end of file: missing closing brace")}function m(e,n,o,s){const r=e.split("\n"),{loopMode:i}=s;n._blockEntityCollection=!!o;const a=new t.Skeleton("","",n);a._parentContainer=o,n._blockEntityCollection=!1;const u=new l(a);u.loopMode=i;const m=r.shift();if(!m||"HIERARCHY"!==m.trim().toUpperCase())throw new Error("HIERARCHY expected");const f=r.shift();if(!f)throw new Error("Unexpected end of file after HIERARCHY");const p=h(r,f.trim(),null,u),_=r.shift();if(!_||"MOTION"!==_.trim().toUpperCase())throw new Error("MOTION expected");const g=r.shift();if(!g)throw new Error("Unexpected end of file before frame count");const y=g.trim().split(/[\s]+/);if(y.length<2)throw new Error("Invalid frame count line");const v=parseInt(y[1]);if(isNaN(v))throw new Error("Failed to read number of frames.");u.numFrames=v;const b=r.shift();if(!b)throw new Error("Unexpected end of file before frame time");const x=b.trim().split(/[\s]+/);if(x.length<3)throw new Error("Invalid frame time line");const T=parseFloat(x[2]);if(isNaN(T))throw new Error("Failed to read frame time.");if(T<=0)throw new Error("Failed to read frame time. Invalid value "+T);u.frameRate=1/T;for(let e=0;e<v;++e){const t=r.shift();t&&d(t.trim().split(/[\s]+/)||[],e,p,{i:0})}return u.root=p,c(u.root,null,u),u.skeleton.returnToRest(),u.skeleton}const f={name:"bvh",extensions:{".bvh":{isBinary:!1}}};class p{constructor(e){this.name=f.name,this.extensions=f.extensions,this._loadingOptions=Object.assign(Object.assign({},p._DefaultLoadingOptions),null!=e?e:{})}static get _DefaultLoadingOptions(){return{loopMode:t.Animation.ANIMATIONLOOPMODE_CYCLE}}createPlugin(e){return new p(e[f.name])}canDirectLoad(e){return this.isBvhHeader(e)}isBvhHeader(e){return"HIERARCHY"==e.split("\n")[0]}isNotBvhHeader(e){return!this.isBvhHeader(e)}importMeshAsync(e,t,n){if("string"!=typeof n)return Promise.reject("BVH loader expects string data.");if(this.isNotBvhHeader(n))return Promise.reject("BVH loader expects HIERARCHY header.");try{const e=m(n,t,null,this._loadingOptions);return Promise.resolve({meshes:[],particleSystems:[],skeletons:[e],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]})}catch(e){return Promise.reject(e)}}loadAsync(e,t){return"string"!=typeof t?Promise.reject("BVH loader expects string data."):this.isNotBvhHeader(t)?Promise.reject("BVH loader expects HIERARCHY header."):this.importMeshAsync(null,e,t).then(()=>{})}loadAssetContainerAsync(e,n){if("string"!=typeof n)return Promise.reject("BVH loader expects string data.");if(this.isNotBvhHeader(n))return Promise.reject("BVH loader expects HIERARCHY header.");const o=new t.AssetContainer(e);try{const t=m(n,e,o,this._loadingOptions);return o.skeletons.push(t),Promise.resolve(o)}catch(e){return Promise.reject(e)}}}let _=!1;function g(){_||(_=!0,t.RegisterSceneLoaderPlugin(new p))}g();var y={__proto__:null,BVHFileLoader:p,RegisterBVHFileLoader:g},v={__proto__:null,BVHFileLoader:p,ReadBvh:m,RegisterBVHFileLoader:g};function b(e,t,n,o){return new(n||(n=Promise))(function(s,r){function i(e){try{l(o.next(e))}catch(e){r(e)}}function a(e){try{l(o.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(i,a)}l((o=o.apply(e,t||[])).next())})}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;const x=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],T=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],A=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],M=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],w=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];class C{constructor(e,t,n){this.input=e,this.byteOffset=t,this.endOffset=n,this.bitBuffer=0,this.bitCount=0}readBits(e){this.ensureBits(e);const t=this.bitBuffer&(1<<e)-1;return this.bitBuffer>>>=e,this.bitCount-=e,t}readBit(){if(0===this.bitCount){if(this.byteOffset>=this.endOffset)throw new Error("zlib: unexpected end of input");this.bitBuffer=this.input[this.byteOffset++],this.bitCount=8}const e=1&this.bitBuffer;return this.bitBuffer>>>=1,this.bitCount--,e}alignToByte(){this.bitBuffer=0,this.bitCount=0}readUint16LE(){if(this.ensureByteAligned(),this.byteOffset+2>this.endOffset)throw new Error("zlib: unexpected end of input");const e=this.input[this.byteOffset]|this.input[this.byteOffset+1]<<8;return this.byteOffset+=2,e}readByte(){if(this.ensureByteAligned(),this.byteOffset>=this.endOffset)throw new Error("zlib: unexpected end of input");return this.input[this.byteOffset++]}ensureByteAligned(){if(0!==this.bitCount)throw new Error("deflate: expected byte alignment")}ensureBits(e){for(;this.bitCount<e;){if(this.byteOffset>=this.endOffset)throw new Error("zlib: unexpected end of input");this.bitBuffer|=this.input[this.byteOffset++]<<this.bitCount,this.bitCount+=8}}}class R{constructor(e){this.offset=0,this.adlerA=1,this.adlerB=0,this.bytes=new Uint8Array(e)}writeByte(e){if(this.offset>=this.bytes.byteLength)throw new Error("zlib: output length mismatch");const t=255&e;this.bytes[this.offset++]=t,this.adlerA+=t,this.adlerB+=this.adlerA,this.adlerA%=65521,this.adlerB%=65521}copy(e,t){if(e<=0||e>this.offset)throw new Error("deflate: distance out of range");for(let n=0;n<t;n++)this.writeByte(this.bytes[this.offset-e])}finish(){if(this.offset!==this.bytes.byteLength)throw new Error("zlib: output length mismatch")}adler32(){return(this.adlerB<<16|this.adlerA)>>>0}}class O{constructor(e,t={}){const n=new Array(16).fill(0);let o=0,s=0;for(const t of e){if(!Number.isInteger(t)||t<0||t>15)throw new Error("deflate: invalid huffman code lengths");t>0&&(n[t]++,o++,s=Math.max(s,t))}if(0===o){if(t.allowEmpty)return this.symbolsByLength=[],void(this.maxCodeLength=0);throw new Error("deflate: invalid huffman code lengths")}let r=1;for(let e=1;e<=15;e++)if(r=(r<<1)-n[e],r<0)throw new Error("deflate: invalid huffman code lengths");if(0!==r&&1!==o)throw new Error("deflate: invalid huffman code lengths");const i=new Array(16).fill(0);let a=0;for(let e=1;e<=15;e++)a=a+n[e-1]<<1,i[e]=a;this.symbolsByLength=Array.from({length:16},(e,t)=>{if(0===n[t])return;const o=new Int16Array(1<<t);return o.fill(-1),o});for(let t=0;t<e.length;t++){const n=e[t];0!==n&&(this.symbolsByLength[n][i[n]++]=t)}this.maxCodeLength=s}decode(e){var t,n;if(0===this.maxCodeLength)throw new Error("deflate: invalid huffman code");let o=0;for(let s=1;s<=this.maxCodeLength;s++){o=o<<1|e.readBit();const r=null!==(n=null===(t=this.symbolsByLength[s])||void 0===t?void 0:t[o])&&void 0!==n?n:-1;if(r>=0)return r}throw new Error("deflate: invalid huffman code")}}let S,F;function E(){if(!S){const e=new Array(288);for(let t=0;t<=143;t++)e[t]=8;for(let t=144;t<=255;t++)e[t]=9;for(let t=256;t<=279;t++)e[t]=7;for(let t=280;t<=287;t++)e[t]=8;S=new O(e)}return S}function L(){return F||(F=new O(new Array(32).fill(5))),F}function I(e,t){e.alignToByte();const n=e.readUint16LE();if(65535&(n^~e.readUint16LE()))throw new Error("deflate: invalid stored block length");for(let o=0;o<n;o++)t.writeByte(e.readByte())}function N(e,t,n,o){for(;;){const s=n.decode(e);if(s<256){t.writeByte(s);continue}if(256===s)return;if(s>285)throw new Error("deflate: invalid literal/length symbol");const r=s-257,i=x[r]+e.readBits(T[r]),a=o.decode(e);if(a>29)throw new Error("deflate: invalid distance symbol");const l=A[a]+e.readBits(M[a]);t.copy(l,i)}}function P(e){const t=e.readBits(5)+257,n=e.readBits(5)+1,o=e.readBits(4)+4,s=new Array(19).fill(0);for(let t=0;t<o;t++)s[w[t]]=e.readBits(3);const r=function(e,t,n){const o=[];for(;o.length<n;){const s=t.decode(e);if(s<=15){o.push(s);continue}let r,i;switch(s){case 16:if(0===o.length)throw new Error("deflate: invalid code length repeat");i=o[o.length-1],r=e.readBits(2)+3;break;case 17:i=0,r=e.readBits(3)+3;break;case 18:i=0,r=e.readBits(7)+11;break;default:throw new Error("deflate: invalid code length symbol")}if(o.length+r>n)throw new Error("deflate: invalid code length repeat");for(let e=0;e<r;e++)o.push(i)}return o}(e,new O(s),t+n),i=r.slice(0,t),a=r.slice(t);if(0===i[256])throw new Error("deflate: missing end-of-block code");return{literalLengthTree:new O(i),distanceTree:new O(a,{allowEmpty:!0})}}function B(e,t,n,o,s){let r,i,a,l;if(o?(G(t,n,25,s,"FBX node header"),r=V(e,n),i=V(e,n+8),a=V(e,n+16),l=25):(G(t,n,13,s,"FBX node header"),r=e.getUint32(n,!0),i=e.getUint32(n+4,!0),a=e.getUint32(n+8,!0),l=13),0===r)return null;if(r<=n||r>s)throw new Error(`Invalid FBX node end offset ${r} at offset ${n}`);const u=t[n+l-1];G(t,n+l,u,r,"FBX node name");const c=K(t,n+l,u);let d=n+l+u;const h=d+a;if(h>r)throw new Error(`Invalid FBX property list length for node '${c}' at offset ${n}`);const m=[];for(let n=0;n<i;n++){const n=k(e,t,d,h);m.push(n.property),d=n.nextOffset}if(d!==h)throw new Error(`Invalid FBX property list length for node '${c}' at offset ${n}`);const f=[];if(d<r)for(;d<r;){const n=B(e,t,d,o,r);if(null===n)break;if(n.endOffset<=d||n.endOffset>r)throw new Error(`Invalid FBX child node end offset ${n.endOffset} at offset ${d}`);f.push(n.node),d=n.endOffset}return{node:{name:c,properties:m,children:f},endOffset:r}}function k(e,t,n,o){G(t,n,1,o,"FBX property type");const s=String.fromCharCode(t[n]);switch(n+=1,s){case"C":return G(t,n,1,o,"FBX boolean property"),{property:{type:"boolean",value:0!==t[n]},nextOffset:n+1};case"Y":return G(t,n,2,o,"FBX int16 property"),{property:{type:"int16",value:e.getInt16(n,!0)},nextOffset:n+2};case"I":return G(t,n,4,o,"FBX int32 property"),{property:{type:"int32",value:e.getInt32(n,!0)},nextOffset:n+4};case"F":return G(t,n,4,o,"FBX float32 property"),{property:{type:"float32",value:e.getFloat32(n,!0)},nextOffset:n+4};case"D":return G(t,n,8,o,"FBX float64 property"),{property:{type:"float64",value:e.getFloat64(n,!0)},nextOffset:n+8};case"L":return G(t,n,8,o,"FBX int64 property"),{property:{type:"int64",value:H(e,n)},nextOffset:n+8};case"S":{G(t,n,4,o,"FBX string property length");const s=e.getUint32(n,!0);G(t,n+4,s,o,"FBX string property data");const r=function(e,t,n){return new TextDecoder("utf-8").decode(e.subarray(t,t+n))}(t,n+4,s);return{property:{type:"string",value:r},nextOffset:n+4+s}}case"R":{G(t,n,4,o,"FBX raw property length");const s=e.getUint32(n,!0);return G(t,n+4,s,o,"FBX raw property data"),{property:{type:"raw",value:t.slice(n+4,n+4+s)},nextOffset:n+4+s}}case"f":return D(e,t,n,"float32[]",4,o);case"d":return D(e,t,n,"float64[]",8,o);case"i":return D(e,t,n,"int32[]",4,o);case"l":return D(e,t,n,"int64[]",8,o);case"b":return D(e,t,n,"boolean[]",1,o);default:throw new Error(`Unknown FBX property type: '${s}' at offset ${n-1}`)}}function D(e,t,n,o,s,r){G(t,n,12,r,`FBX array property header for ${o}`);const i=e.getUint32(n,!0),a=e.getUint32(n+4,!0),l=e.getUint32(n+8,!0),u=i*s;let c;if(G(t,n+=12,l,r,`FBX array property data for ${o}`),1===a)c=function(e,t){if(!Number.isInteger(t)||t<0)throw new Error("zlib: invalid expected length");if(e.byteLength<6)throw new Error("zlib: unexpected end of input");const n=e[0],o=e[1];if(8!=(15&n)||n>>4>7||((n<<8)+o)%31!=0)throw new Error("zlib: invalid header");if(32&o)throw new Error("zlib: preset dictionary not supported");const s=new C(e,2,e.byteLength-4),r=new R(t);let i=!1;for(;!i;)switch(i=1===s.readBits(1),s.readBits(2)){case 0:I(s,r);break;case 1:N(s,r,E(),L());break;case 2:{const{literalLengthTree:e,distanceTree:t}=P(s);N(s,r,e,t);break}default:throw new Error("deflate: invalid block type")}if(s.byteOffset<e.byteLength-4)throw new Error("zlib: trailing deflate data");r.finish();const a=(e[e.byteLength-4]<<24|e[e.byteLength-3]<<16|e[e.byteLength-2]<<8|e[e.byteLength-1])>>>0;if(r.adler32()!==a)throw new Error("zlib: adler32 mismatch");return r.bytes}(t.subarray(n,n+l),u);else{if(0!==a)throw new Error(`Unsupported FBX array encoding: ${a}`);if(l!==u)throw new Error(`Invalid FBX array byte length for ${o}`);c=t.slice(n,n+l)}const d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);let h;switch(o){case"float32[]":h=new Float32Array(d);break;case"float64[]":h=new Float64Array(d);break;case"int32[]":h=new Int32Array(d);break;case"boolean[]":h=c;break;case"int64[]":h=function(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new Float64Array(e.byteLength/8);for(let e=0;e<n.length;e++)n[e]=H(t,8*e);return n}(c);break;default:throw new Error(`Unexpected array type: ${o}`)}return{property:{type:o,value:h},nextOffset:n+l}}function G(e,t,n,o,s){if(t<0||n<0||t+n>o||t+n>e.byteLength)throw new Error(`${s}: unexpected end of input`)}function V(e,t){const n=e.getUint32(t,!0);return 4294967296*e.getUint32(t+4,!0)+n}function H(e,t){const n=e.getUint32(t,!0);return 4294967296*e.getInt32(t+4,!0)+n}function K(e,t,n){let o="";for(let s=0;s<n;s++)o+=String.fromCharCode(e[t+s]);return o}function U(e){const t=new W(e),n=function(e){const t=e.match(/;\s*FBX\s+(\d+)\.(\d+)\.(\d+)/);if(!t)throw new Error("Cannot determine FBX version from ASCII header");return 1e3*parseInt(t[1])+100*parseInt(t[2])+parseInt(t[3])}(e),o=[];for(;!t.isEOF()&&(t.skipWhitespaceAndComments(),!t.isEOF());){const e=z(t);e&&o.push(e)}return{version:n,nodes:o}}var $;!function(e){e[e.Identifier=0]="Identifier",e[e.Number=1]="Number",e[e.String=2]="String",e[e.OpenBrace=3]="OpenBrace",e[e.CloseBrace=4]="CloseBrace",e[e.Colon=5]="Colon",e[e.Comma=6]="Comma",e[e.Star=7]="Star",e[e.EOF=8]="EOF"}($||($={}));let W=class{constructor(e){this.text=e,this.pos=0,this.len=e.length}isEOF(){return this.skipWhitespaceAndComments(),this.pos>=this.len}peek(){const e=this.pos,t=this.next();return this.pos=e,t}next(){if(this.skipWhitespaceAndComments(),this.pos>=this.len)return{type:8,value:"",pos:this.pos};const e=this.text[this.pos],t=this.pos;switch(e){case"{":return this.pos++,{type:3,value:"{",pos:t};case"}":return this.pos++,{type:4,value:"}",pos:t};case":":return this.pos++,{type:5,value:":",pos:t};case",":return this.pos++,{type:6,value:",",pos:t};case"*":return this.pos++,{type:7,value:"*",pos:t};case'"':return this.readString();default:if(this.isNumberStart(e))return this.readNumber();if(this.isIdentStart(e))return this.readIdentifier();throw new Error(`Unexpected character '${e}' at position ${this.pos}`)}}expect(e){const t=this.next();if(t.type!==e)throw new Error(`Expected token type ${e} but got ${t.type} ('${t.value}') at pos ${t.pos}`);return t}isNextNodeStart(){const e=this.pos;if(this.skipWhitespaceAndComments(),this.pos<this.len&&this.isIdentStart(this.text[this.pos])){for(;this.pos<this.len&&this.isIdentChar(this.text[this.pos]);)this.pos++;for(;this.pos<this.len&&(" "===this.text[this.pos]||"\t"===this.text[this.pos]);)this.pos++;const t=this.pos<this.len&&":"===this.text[this.pos];return this.pos=e,t}return this.pos=e,!1}skipWhitespaceAndComments(){for(;this.pos<this.len;){const e=this.text[this.pos];if(" "===e||"\t"===e||"\r"===e||"\n"===e)this.pos++;else{if(";"!==e)break;for(;this.pos<this.len&&"\n"!==this.text[this.pos];)this.pos++}}}readString(){const e=this.pos;this.pos++;let t="";for(;this.pos<this.len&&'"'!==this.text[this.pos];)"\\"===this.text[this.pos]&&this.pos+1<this.len?(this.pos++,t+=this.text[this.pos]):t+=this.text[this.pos],this.pos++;return this.pos<this.len&&this.pos++,{type:2,value:t,pos:e}}readNumber(){const e=this.pos;for("-"!==this.text[this.pos]&&"+"!==this.text[this.pos]||this.pos++;this.pos<this.len&&this.isDigit(this.text[this.pos]);)this.pos++;if(this.pos<this.len&&"."===this.text[this.pos])for(this.pos++;this.pos<this.len&&this.isDigit(this.text[this.pos]);)this.pos++;if(this.pos<this.len&&("e"===this.text[this.pos]||"E"===this.text[this.pos]))for(this.pos++,this.pos<this.len&&("+"===this.text[this.pos]||"-"===this.text[this.pos])&&this.pos++;this.pos<this.len&&this.isDigit(this.text[this.pos]);)this.pos++;return{type:1,value:this.text.substring(e,this.pos),pos:e}}readIdentifier(){const e=this.pos;for(;this.pos<this.len&&this.isIdentChar(this.text[this.pos]);)this.pos++;return{type:0,value:this.text.substring(e,this.pos),pos:e}}isDigit(e){return e>="0"&&e<="9"}isNumberStart(e){return!!this.isDigit(e)||("-"===e||"+"===e)&&this.pos+1<this.len&&(this.isDigit(this.text[this.pos+1])||"."===this.text[this.pos+1])}isIdentStart(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||"_"===e}isIdentChar(e){return this.isIdentStart(e)||this.isDigit(e)||"|"===e}};function z(e){const t=e.peek();if(4===t.type||8===t.type)return null;const n=e.next();if(0!==n.type)throw new Error(`Expected identifier for node name, got '${n.value}' at pos ${n.pos}`);const o=n.value;e.expect(5);const s=[],r=[];let i=e.peek();if(7===i.type){e.next();const t=e.expect(1),n=parseInt(t.value);e.expect(3);const i=e.next();if(0===i.type&&"a"===i.value){e.expect(5);const t=function(e,t){const n=[];for(;;){const t=e.peek();if(4===t.type||8===t.type)break;if(6!==t.type){if(1!==t.type)break;{const t=e.next();n.push(Number(t.value))}}else e.next()}if(n.length!==t)throw new Error(`ASCII FBX array declared ${t} values but parsed ${n.length}`);return n}(e,n);s.push({type:"float64[]",value:new Float64Array(t)})}return e.expect(4),{name:o,properties:s,children:r}}for(i=e.peek();3!==i.type&&4!==i.type&&8!==i.type;){if(1===i.type){const t=e.next(),n=j(t.value);!Number.isInteger(n)||t.value.includes(".")||t.value.includes("e")||t.value.includes("E")?s.push({type:"float64",value:n}):s.push({type:q(n)?"int32":"int64",value:n})}else if(2===i.type){const t=e.next();s.push({type:"string",value:t.value})}else if(0===i.type){if(e.isNextNodeStart())break;const t=e.next();s.push({type:"string",value:t.value})}else{if(6!==i.type)break;e.next()}i=e.peek()}if(i=e.peek(),3===i.type){for(e.next();i=e.peek(),4!==i.type&&8!==i.type;){const t=z(e);if(!t)break;r.push(t)}e.expect(4)}return{name:o,properties:s,children:r}}function j(e){return Number(e)}function q(e){return e>=-2147483648&&e<=2147483647}function X(e,t){return e.children.find(e=>e.name===t)}function Y(e,t){return e.nodes.find(e=>e.name===t)}function Q(e,t){if(t<e.properties.length)return e.properties[t].value}function Z(e){const t=e.indexOf("\0");t>=0&&(e=e.substring(0,t));const n=e.indexOf("::");return n>=0&&(e=e.substring(n+2)),e}function J(e,t,n){var o;const s=null!==(o=e.childrenOf.get(t))&&void 0!==o?o:[],r=[];for(const t of s){const o=e.objects.get(t.id);!o||n&&o.name!==n||r.push({id:t.id,node:o,propertyName:t.propertyName})}return r}function ee(e){return function(e){if("number"==typeof e){if(!Number.isSafeInteger(e))throw new Error(`Unsafe FBX object ID ${e.toString()}: object IDs must be safe integers.`);return e}}(e)}function te(e,t){const n=ee(e);if(void 0!==n)return n;if("string"!=typeof e)return;const o=Z(e);return"Scene"===o?0:t.get(o)}function ne(e,t,n,o,s,r,i,a,l){e.push({type:s,childId:r,parentId:i,propertyName:a}),t.has(i)||t.set(i,[]),t.get(i).push({id:r,propertyName:a}),n.get(r)&&o.push({reason:"duplicate-parent",message:"FBX object has multiple parents; preserving the existing last-parent behavior.",connectionIndex:l,type:s,childId:r,parentId:i,propertyName:a}),n.set(r,{id:i,propertyName:a})}function oe(e,t){var n,o;const s=Z(null!==(n=Q(e,0))&&void 0!==n?n:e.name),r=null!==(o=Q(e,1))&&void 0!==o?o:"";return Object.assign(Object.assign({},e),{properties:[{type:"int64",value:t},{type:"string",value:s},{type:"string",value:r}]})}function se(e,t){var n;return{name:"Geometry",properties:[{type:"int64",value:t},{type:"string",value:Z(null!==(n=Q(e,0))&&void 0!==n?n:"Geometry")},{type:"string",value:"Mesh"}],children:e.children}}function re(e,t){var n,o,s;const r=Z(null!==(n=Q(e,1))&&void 0!==n?n:"Geometry"),i=X(e,"Vertices");if(!i)throw new Error(`Geometry '${r}' has no Vertices node`);const a=fe(_e(i)),l=X(e,"PolygonVertexIndex");if(!l)throw new Error(`Geometry '${r}' has no PolygonVertexIndex node`);const u=[],c=function(e){const t=[];let n=[],o=0;for(let s=0;s<e.length;s++){const r=e[s];r<0?(n.push(-(r+1)),t.push({indices:n,startIndex:o}),n=[],o=s+1):n.push(r)}return t}(pe(_e(l))),d=function(e,t,n){const o=[];for(let s=0;s<e.length;s++){const r=e[s];o.push(...ie(r,s,t,n))}return o}(c,a,u),h=function(e){const t=[];for(let n=0;n<e.length;n++){const o=e[n];for(let e=0;e<o.indices.length;e++)t.push({polyIndex:n,vertexInPoly:e,controlPointIndex:o.indices[e],globalIndex:o.startIndex+e})}return t}(c),m=X(e,"LayerElementNormal");let f=null;m&&(f=he(m,"Normals","NormalsIndex",h,a.length,3,u));const p=e.children.filter(e=>"LayerElementUV"===e.name),_=[];for(const e of p){const t=X(e,"Name"),n=t&&null!==(o=Q(t,0))&&void 0!==o?o:`UVSet${_.length}`,s=he(e,"UV","UVIndex",h,a.length,2,u);s&&_.push({name:n,data:s})}const g=_.length>0?_[0].data:null,y=X(e,"LayerElementColor");let v=null;if(y){const e=he(y,"Colors","ColorIndex",h,a.length,4,u);if(e){v=new Float32Array(e.length);for(let t=0;t<e.length;t++)v[t]=e[t]}}const b=X(e,"LayerElementTangent"),x=X(e,"LayerElementBinormal"),T=x?he(x,"Binormals","BinormalsIndex",h,a.length,3,u):null,A=b?function(e,t,n,o,s,r){const i=function(e,t,n,o,s,r){var i,a,l,u;const c=X(e,"Tangents");if(!c)return 3;const d=fe(_e(c)),h=null!==(a=Q(null!==(i=X(e,"MappingInformationType"))&&void 0!==i?i:{name:"",properties:[],children:[]},0))&&void 0!==a?a:"",m=null!==(u=Q(null!==(l=X(e,"ReferenceInformationType"))&&void 0!==l?l:{name:"",properties:[],children:[]},0))&&void 0!==u?u:"",f=X(e,"TangentsIndex"),p=f?pe(_e(f)):null,_="IndexToDirect"===m&&p?Math.max(...Array.from(p),0)+1:"ByControlPoint"===h||"ByVertice"===h?s:"AllSame"===h?1:o.length;if(_>0&&d.length%_===0){const e=d.length/_;if(3===e||4===e)return e}return r.push({type:"layer-data-too-short",message:`Could not infer stride for layer '${e.name}', defaulting to 3.`,layerName:e.name}),3}(e,0,0,t,n,r),a=he(e,"Tangents","TangentsIndex",t,0,i,r);if(!a)return null;const l=new Float64Array(4*t.length);for(let e=0;e<t.length;e++){const t=e*i,n=4*e;l[n]=a[t],l[n+1]=a[t+1],l[n+2]=a[t+2],l[n+3]=i>=4?a[t+3]:me(e,l,o,s)}return l}(b,h,a.length/3,f,T,u):null,M=X(e,"LayerElementMaterial");let w=null;M&&(w=function(e,t){var n,o;const s=X(e,"MappingInformationType"),r=X(e,"ReferenceInformationType");if(!s||!r)return null;const i=null!==(n=Q(s,0))&&void 0!==n?n:"",a=null!==(o=Q(r,0))&&void 0!==o?o:"";if("AllSame"===i){const n=X(e,"Materials"),o=n?pe(_e(n)):null,s=o&&o.length>0?o[0]:0,r=new Int32Array(t);return 0!==s&&r.fill(s),r}if("ByPolygon"===i){const t=X(e,"Materials");if(!t)return null;const n=pe(_e(t));if("Direct"===a||"IndexToDirect"===a)return n}return null}(M,c.length));const C=function(e,t,n,o,s,r,i,a,l){const u=n.length,c=new Float64Array(3*u),d=new Uint32Array(u);for(let t=0;t<n.length;t++){const o=n[t].controlPointIndex;c[3*t]=e[3*o],c[3*t+1]=e[3*o+1],c[3*t+2]=e[3*o+2],d[t]=o}const h=3*t.length,m=new Uint32Array(h);for(let e=0;e<t.length;e++)m[3*e]=t[e].vertices[0],m[3*e+1]=t[e].vertices[1],m[3*e+2]=t[e].vertices[2];return{positions:c,indices:m,normals:o,uvs:s,uvSets:r,colors:i,tangents:a,binormals:l,controlPointIndices:d}}(a,d,h,f,g,_,v,A,T);let R=null;if(w){let e=!0;const t=w[0];for(let n=1;n<w.length;n++)if(w[n]!==t){e=!1;break}if(!e||0!==t){const e=C.indices.length/3;R=new Int32Array(e);for(let e=0;e<d.length;e++)R[e]=null!==(s=w[d[e].polyIndex])&&void 0!==s?s:0}}return{id:t,name:r,positions:C.positions,indices:C.indices,normals:C.normals,uvs:C.uvs,uvSets:C.uvSets,colors:C.colors,tangents:C.tangents,binormals:C.binormals,controlPointIndices:C.controlPointIndices,materialIndices:R,diagnostics:u}}function ie(e,t,n,o){if(e.indices.length<3)return o.push({type:"degenerate-polygon",message:`Polygon ${t} has fewer than three vertices.`,polygonIndex:t}),[];if(3===e.indices.length)return[{vertices:[e.startIndex,e.startIndex+1,e.startIndex+2],polyIndex:t}];const s=function(e,t){const n=function(e,t){let n=0,o=0,s=0;for(let r=0;r<e.indices.length;r++){const i=3*e.indices[r],a=3*e.indices[(r+1)%e.indices.length],l=t[i],u=t[i+1],c=t[i+2],d=t[a],h=t[a+1],m=t[a+2];n+=(u-h)*(c+m),o+=(c-m)*(l+d),s+=(l-d)*(u+h)}return[n,o,s]}(e,t),o=Math.abs(n[0]),s=Math.abs(n[1]),r=Math.abs(n[2]);if(o+s+r<1e-12)return null;const i=o>s&&o>r?0:s>r?1:2;return e.indices.map(e=>{const o=t[3*e],s=t[3*e+1],r=t[3*e+2];return 0===i?n[0]>=0?[s,r]:[r,s]:1===i?n[1]>=0?[r,o]:[o,r]:n[2]>=0?[o,s]:[s,o]})}(e,n);if(!s)return o.push({type:"degenerate-polygon",message:`Polygon ${t} has a near-zero normal; using fan triangulation.`,polygonIndex:t}),ae(e,t);const r=function(e){let t=0;for(let n=0;n<e.length;n++){const o=e[n],s=e[(n+1)%e.length];t+=o[0]*s[1]-s[0]*o[1]}return t/2}(s);if(Math.abs(r)<1e-12)return o.push({type:"degenerate-polygon",message:`Polygon ${t} projects to near-zero area; using fan triangulation.`,polygonIndex:t}),ae(e,t);const i=r>0,a=e.indices.map((e,t)=>t),l=[];let u=0;for(;a.length>3&&u++<e.indices.length*e.indices.length;){let n=!1;for(let o=0;o<a.length;o++){const r=a[(o+a.length-1)%a.length],u=a[o],c=a[(o+1)%a.length];if(le(s[r],s[u],s[c],i)&&!ue(s,a,r,u,c)){l.push({vertices:[e.startIndex+r,e.startIndex+u,e.startIndex+c],polyIndex:t}),a.splice(o,1),n=!0;break}}if(!n)return o.push({type:"triangulation-fallback",message:`Polygon ${t} could not be fully ear-clipped; using fan triangulation.`,polygonIndex:t}),ae(e,t)}return l.push({vertices:[e.startIndex+a[0],e.startIndex+a[1],e.startIndex+a[2]],polyIndex:t}),l}function ae(e,t){const n=[];for(let o=1;o<e.indices.length-1;o++)n.push({vertices:[e.startIndex,e.startIndex+o,e.startIndex+o+1],polyIndex:t});return n}function le(e,t,n,o){const s=(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0]);return o?s>1e-12:s<-1e-12}function ue(e,t,n,o,s){for(const r of t)if(r!==n&&r!==o&&r!==s&&ce(e[r],e[n],e[o],e[s]))return!0;return!1}function ce(e,t,n,o){const s=Math.abs(de(t,n,o)),r=Math.abs(de(e,t,n)),i=Math.abs(de(e,n,o)),a=Math.abs(de(e,o,t));return Math.abs(s-(r+i+a))<1e-10}function de(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function he(e,t,n,o,s,r,i){var a,l;const u=X(e,"MappingInformationType"),c=X(e,"ReferenceInformationType");if(!u||!c)return null;const d=null!==(a=Q(u,0))&&void 0!==a?a:"",h=null!==(l=Q(c,0))&&void 0!==l?l:"",m=X(e,t);if(!m)return null;const f=fe(_e(m));let p=null;if("IndexToDirect"===h){const t=X(e,n);t&&(p=pe(_e(t)))}const _=new Float64Array(o.length*r);for(let t=0;t<o.length;t++){const n=o[t];let s;s="ByPolygonVertex"===d?"IndexToDirect"===h&&p?p[n.globalIndex]:n.globalIndex:"ByControlPoint"===d||"ByVertice"===d?"IndexToDirect"===h&&p?p[n.controlPointIndex]:n.controlPointIndex:"ByPolygon"===d?"IndexToDirect"===h&&p?p[n.polyIndex]:n.polyIndex:"AllSame"===d?0:n.globalIndex;for(let n=0;n<r;n++){const o=s*r+n;s<0||o>=f.length?(i.push({type:o>=f.length?"layer-data-too-short":"layer-index-out-of-bounds",message:`Layer '${e.name}' references unavailable element ${s}.`,layerName:e.name,index:s}),_[t*r+n]=0):_[t*r+n]=f[o]}}return _}function me(e,t,n,o){if(!n||!o)return 1;const s=4*e,r=3*e,i=n[r],a=n[r+1],l=n[r+2],u=t[s],c=t[s+1],d=t[s+2];return(a*d-l*c)*o[r]+(l*u-i*d)*o[r+1]+(i*c-a*u)*o[r+2]<0?-1:1}function fe(e){if(e instanceof Float64Array)return e;if(e instanceof Float32Array)return new Float64Array(e);if(e instanceof Int32Array)return new Float64Array(e);if(Array.isArray(e)){const t=new Float64Array(e.length);for(let n=0;n<e.length;n++)t[n]=Number(e[n]);return t}throw new Error(`Cannot convert ${typeof e} to Float64Array`)}function pe(e){if(e instanceof Int32Array)return e;if(e instanceof Float64Array){const t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=Math.round(e[n]);return t}if(e instanceof Float32Array){const t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=Math.round(e[n]);return t}if(Array.isArray(e)){const t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=Math.round(Number(e[n]));return t}throw new Error(`Cannot convert ${typeof e} to Int32Array`)}function _e(e){return 1===e.properties.length?e.properties[0].value:e.properties.map(e=>e.value)}function ge(e,t,n){const o=e.get(t);if(o)return n?o.get(n):o.values().next().value}function ye(e,t,n,o=0){var s;return null===(s=xe(e,t,n))||void 0===s?void 0:s[o]}function ve(e,t,n,o){var s;return null!==(s=Te(ye(e,t,n)))&&void 0!==s?s:o}function be(e,t,n,o){const s=xe(e,t,n);if(!s)return o;const r=Te(s[0]),i=Te(s[1]),a=Te(s[2]);return void 0!==r&&void 0!==i&&void 0!==a?[r,i,a]:o}function xe(e,t,n){var o,s;return null!==(o=function(e,t){const n=[X(e,"Properties70"),X(e,"Properties60")].filter(e=>void 0!==e);for(const e of n)for(const n of e.children)if(("P"===n.name||"Property"===n.name)&&Q(n,0)===t)return n.properties.slice("Property"===n.name?3:4).map(e=>e.value)}(e,n))&&void 0!==o?o:null===(s=null==t?void 0:t.properties.get(n))||void 0===s?void 0:s.values}function Te(e){if("number"==typeof e)return e}function Ae(e,t,n){var o;const s=new Map,r=X(n,"Properties70");for(const e of null!==(o=null==r?void 0:r.children)&&void 0!==o?o:[]){if("P"!==e.name)continue;const t=Me(e);t&&s.set(t.name,t)}return{objectType:e,templateName:t,properties:s}}function Me(e){var t,n,o;const s=Q(e,0);return s?{name:s,propertyType:null!==(t=Q(e,1))&&void 0!==t?t:"",label:null!==(n=Q(e,2))&&void 0!==n?n:"",flags:null!==(o=Q(e,3))&&void 0!==o?o:"",values:e.properties.slice(4).map(e=>e.value)}:null}function we(e,t,n,o){var s,r,i,a;const l=Z(null!==(s=Q(e,1))&&void 0!==s?s:"Material"),u=function(e,t){var n,o;if(!t)return;const s=X(e,"ShadingModel"),r=s?Q(s,0):void 0;return"phong"===(null==r?void 0:r.toLowerCase())?null!==(n=ge(t,"Material","FbxSurfacePhong"))&&void 0!==n?n:ge(t,"Material"):"lambert"===(null==r?void 0:r.toLowerCase())&&null!==(o=ge(t,"Material","FbxSurfaceLambert"))&&void 0!==o?o:ge(t,"Material")}(e,o),c=X(e,"ShadingModel"),d="phong"===(c?null!==(r=Q(c,0))&&void 0!==r?r:"Lambert":null!==(i=ye(e,u,"ShadingModel"))&&void 0!==i?i:"Lambert").toLowerCase()?"Phong":"Lambert",h=function(e,t){var n,o,s,r,i;const a={};return a.diffuseColor=null!==(n=Ce(e,t,"DiffuseColor"))&&void 0!==n?n:Ce(e,t,"Diffuse"),a.diffuseFactor=Re(e,t,"DiffuseFactor"),a.ambientColor=null!==(o=Ce(e,t,"AmbientColor"))&&void 0!==o?o:Ce(e,t,"Ambient"),a.ambientFactor=Re(e,t,"AmbientFactor"),a.specularColor=null!==(s=Ce(e,t,"SpecularColor"))&&void 0!==s?s:Ce(e,t,"Specular"),a.specularFactor=Re(e,t,"SpecularFactor"),a.shininess=null!==(r=Re(e,t,"Shininess"))&&void 0!==r?r:Re(e,t,"ShininessExponent"),a.emissiveColor=null!==(i=Ce(e,t,"EmissiveColor"))&&void 0!==i?i:Ce(e,t,"Emissive"),a.emissiveFactor=Re(e,t,"EmissiveFactor"),a.opacity=Re(e,t,"Opacity"),a.transparencyFactor=Re(e,t,"TransparencyFactor"),a}(e,u),m=function(e,t,n){var o,s,r,i,a;const l=[],u=J(t,e,"Texture");for(const{id:e,node:c,propertyName:d}of u){const u=X(c,"FileName"),h=X(c,"RelativeFilename"),m=u&&null!==(o=Q(u,0))&&void 0!==o?o:"",f=h&&null!==(s=Q(h,0))&&void 0!==s?s:"";let p,_;const g=null!==(r=Re(c,n,"UVRotation"))&&void 0!==r?r:Re(c,n,"Rotation");let y;p=null!==(i=Oe(c,n,"UVTranslation"))&&void 0!==i?i:Oe(c,n,"Translation"),_=null!==(a=Oe(c,n,"UVScaling"))&&void 0!==a?a:Oe(c,n,"Scaling");const v=ye(c,n,"UVSet");v&&v.length>0&&(y=v),null!=p||(p=Fe(c,"ModelUVTranslation")),null!=_||(_=Fe(c,"ModelUVScaling"));let b=null;const x=J(t,e,"Video");for(const{node:e}of x){const t=X(e,"Content");if(t&&t.properties.length>0){const e=t.properties[0].value;e instanceof Uint8Array&&e.length>0?b=e:e instanceof ArrayBuffer&&e.byteLength>0&&(b=new Uint8Array(e))}}l.push({propertyName:null!=d?d:"DiffuseColor",fileName:m,relativeFileName:f,id:e,embeddedData:b,uvTranslation:p,uvScaling:_,uvRotation:g,uvSetName:y})}return l}(t,n,o?null!==(a=ge(o,"Texture","FbxFileTexture"))&&void 0!==a?a:ge(o,"Texture"):void 0);return{id:t,name:l,type:d,properties:h,textures:m}}function Ce(e,t,n){const o=xe(e,t,n);if(!o||o.length<3)return;const s=Se(o[0]),r=Se(o[1]),i=Se(o[2]);return void 0!==s&&void 0!==r&&void 0!==i?[s,r,i]:void 0}function Re(e,t,n){return Se(ye(e,t,n))}function Oe(e,t,n){const o=xe(e,t,n);if(!o)return;const s=Se(o[0]),r=Se(o[1]);return void 0!==s&&void 0!==r?[s,r]:void 0}function Se(e){if("number"==typeof e)return e}function Fe(e,t){var n,o;const s=X(e,t);if(!s)return;const r=Se(null===(n=s.properties[0])||void 0===n?void 0:n.value),i=Se(null===(o=s.properties[1])||void 0===o?void 0:o.value);return void 0!==r&&void 0!==i?[r,i]:void 0}function Ee(e,t,n){var o;const s=n.parentOf.get(e);if(!s)return null;const r=s.id,i=n.objects.get(r);if(!i||"Geometry"!==i.name)return null;const a=n.parentOf.get(r),l=a?n.objects.get(a.id):void 0,u="Model"===(null==l?void 0:l.name)?a.id:void 0,c=J(n,e,"Deformer");if(0===c.length)return null;const d=new Map;for(const{id:e,node:t}of c){if("Cluster"!==Q(t,2))continue;const o=J(n,e,"Model");o.length>0&&d.set(o[0].id,{clusterId:e,clusterNode:t})}const h=function(e,t){var n,o;const s=t.parentOf.get(e),r=s?t.objects.get(s.id):void 0,i="Model"===(null==r?void 0:r.name)?s.id:void 0;if(void 0===i)return new Map;for(const[,e]of Array.from(t.objects)){if("Pose"!==e.name||"BindPose"!==Q(e,2))continue;const t=new Map;for(const s of e.children){if("PoseNode"!==s.name)continue;const e=X(s,"Node"),r=X(s,"Matrix"),i=null===(n=null==e?void 0:e.properties[0])||void 0===n?void 0:n.value,a=null===(o=null==r?void 0:r.properties[0])||void 0===o?void 0:o.value;if("number"!=typeof i)continue;const l=Ge(a);16===(null==l?void 0:l.length)&&t.set(i,l)}if(t.has(i))return t}return new Map}(r,n),m=[],f=function(e,t,n,o){var s,r,i,a,l;const u=[],c=new Set,d=function(e,t){const n=new Set(Array.from(e.keys()));for(const o of Array.from(e.keys())){let e=Le(o,t);for(;void 0!==e;){const o=t.objects.get(e);if(!o||"Model"!==o.name)break;n.add(e),e=Le(e,t)}}return n}(e,n),h=function(e,t){const n=new Map;for(const o of Array.from(e)){let s=Le(o,t);for(;void 0!==s;){if(e.has(s)){n.set(o,s);break}s=Le(s,t)}}return n}(d,n),m=function(e,t){const n=new Map;for(const o of Array.from(e)){const e=t.get(o);void 0!==e&&(n.has(e)||n.set(e,[]),n.get(e).push(o))}return n}(d,h),f=Array.from(d).filter(e=>!h.has(e)).map(e=>({modelId:e,parentIndex:-1}));for(;f.length>0;){const{modelId:d,parentIndex:h}=f.shift();if(c.has(d))continue;c.add(d);const p=n.objects.get(d);if(!p)continue;const _=u.length,g=e.get(d),y=Ne(p),{bindPoseMatrix:v,transformLinkMatrix:b,transformAssociateModelMatrix:x,clusterMode:T}=g?Pe(g.clusterNode):{bindPoseMatrix:null,transformLinkMatrix:null,transformAssociateModelMatrix:null,clusterMode:"Unknown"},A=Be(d,Z(null!==(s=Q(p,1))&&void 0!==s?s:`Bone${_}`),void 0!==g,T,v,b,x,null!==(r=t.get(d))&&void 0!==r?r:null);o.push(...A),u.push({modelId:d,name:Z(null!==(i=Q(p,1))&&void 0!==i?i:`Bone${_}`),index:_,parentIndex:h,isCluster:void 0!==g,translation:y.translation,rotation:y.rotation,preRotation:y.preRotation,postRotation:y.postRotation,rotationPivot:y.rotationPivot,scalingPivot:y.scalingPivot,rotationOffset:y.rotationOffset,scalingOffset:y.scalingOffset,scale:y.scale,rotationOrder:y.rotationOrder,inheritType:y.inheritType,clusterMode:T,bindPoseMatrix:v,transformLinkMatrix:b,transformAssociateModelMatrix:x,modelBindPoseMatrix:null!==(a=t.get(d))&&void 0!==a?a:null,diagnostics:A});for(const e of null!==(l=m.get(d))&&void 0!==l?l:[])c.has(e)||f.push({modelId:e,parentIndex:_})}return u}(d,h,n,m);if(0===f.length)return null;const{boneIndices:p,boneWeights:_}=function(e,t){var n,o,s;let r=0;for(const o of e){const e=t.get(o.modelId);if(!e)continue;const s=X(e.clusterNode,"Indexes");if(!s)continue;const i=De(null===(n=s.properties[0])||void 0===n?void 0:n.value);if(i)for(let e=0;e<i.length;e++)i[e]>r&&(r=i[e])}const i=r+1,a=new Array(i),l=new Array(i);for(let e=0;e<i;e++)a[e]=[],l[e]=[];for(const n of e){const e=t.get(n.modelId);if(!e)continue;const r=X(e.clusterNode,"Indexes"),i=X(e.clusterNode,"Weights");if(!r||!i)continue;const u=De(null===(o=r.properties[0])||void 0===o?void 0:o.value),c=Ge(null===(s=i.properties[0])||void 0===s?void 0:s.value);if(u&&c)for(let e=0;e<u.length;e++){const t=u[e];a[t].push(n.index),l[t].push(c[e])}}for(let e=0;e<i;e++){if(0===a[e].length)continue;const t=a[e].map((t,n)=>({index:t,weight:l[e][n]}));t.sort((e,t)=>t.weight-e.weight);const n=t.slice(0,8);a[e]=n.map(e=>e.index),l[e]=n.map(e=>e.weight)}for(let e=0;e<i;e++){const t=l[e].reduce((e,t)=>e+t,0);if(t>0)for(let n=0;n<l[e].length;n++)l[e][n]/=t}return{boneIndices:a,boneWeights:l}}(f,d);return{id:e,geometryId:r,meshBindPoseMatrix:void 0!==u&&null!==(o=h.get(u))&&void 0!==o?o:null,bones:f,boneIndices:p,boneWeights:_,diagnostics:m}}function Le(e,t){const n=t.connections.find(n=>{var o;return"OO"===n.type&&n.childId===e&&"Model"===(null===(o=t.objects.get(n.parentId))||void 0===o?void 0:o.name)});return null==n?void 0:n.parentId}function Ie(e){const t=Q(e,2);return"Root"===t||"LimbNode"===t}function Ne(e){var t,n,o,s,r,i,a,l,u,c,d,h,m,f,p,_,g,y,v,b,x,T,A,M,w,C,R,O,S,F,E,L,I,N,P,B,k,D,G,V,H,K,U,$,W,z,j,q,Y,Z,J,ee,te,ne,oe,se,re,ie;const ae=[0,0,0],le=[0,0,0],ue=[0,0,0],ce=[0,0,0],de=[0,0,0],he=[0,0,0],me=[0,0,0],fe=[0,0,0],pe=[1,1,1];let _e=0,ge=1;const ye=X(e,"Properties70");if(!ye)return{translation:ae,rotation:le,preRotation:ue,postRotation:ce,rotationPivot:de,scalingPivot:he,rotationOffset:me,scalingOffset:fe,scale:pe,rotationOrder:_e,inheritType:ge};for(const e of ye.children){if("P"!==e.name)continue;const X=Q(e,0);if(X)switch(X){case"Lcl Translation":ae[0]=null!==(n=ke(null===(t=e.properties[4])||void 0===t?void 0:t.value))&&void 0!==n?n:0,ae[1]=null!==(s=ke(null===(o=e.properties[5])||void 0===o?void 0:o.value))&&void 0!==s?s:0,ae[2]=null!==(i=ke(null===(r=e.properties[6])||void 0===r?void 0:r.value))&&void 0!==i?i:0;break;case"Lcl Rotation":le[0]=null!==(l=ke(null===(a=e.properties[4])||void 0===a?void 0:a.value))&&void 0!==l?l:0,le[1]=null!==(c=ke(null===(u=e.properties[5])||void 0===u?void 0:u.value))&&void 0!==c?c:0,le[2]=null!==(h=ke(null===(d=e.properties[6])||void 0===d?void 0:d.value))&&void 0!==h?h:0;break;case"PreRotation":ue[0]=null!==(f=ke(null===(m=e.properties[4])||void 0===m?void 0:m.value))&&void 0!==f?f:0,ue[1]=null!==(_=ke(null===(p=e.properties[5])||void 0===p?void 0:p.value))&&void 0!==_?_:0,ue[2]=null!==(y=ke(null===(g=e.properties[6])||void 0===g?void 0:g.value))&&void 0!==y?y:0;break;case"PostRotation":ce[0]=null!==(b=ke(null===(v=e.properties[4])||void 0===v?void 0:v.value))&&void 0!==b?b:0,ce[1]=null!==(T=ke(null===(x=e.properties[5])||void 0===x?void 0:x.value))&&void 0!==T?T:0,ce[2]=null!==(M=ke(null===(A=e.properties[6])||void 0===A?void 0:A.value))&&void 0!==M?M:0;break;case"RotationPivot":de[0]=null!==(C=ke(null===(w=e.properties[4])||void 0===w?void 0:w.value))&&void 0!==C?C:0,de[1]=null!==(O=ke(null===(R=e.properties[5])||void 0===R?void 0:R.value))&&void 0!==O?O:0,de[2]=null!==(F=ke(null===(S=e.properties[6])||void 0===S?void 0:S.value))&&void 0!==F?F:0;break;case"ScalingPivot":he[0]=null!==(L=ke(null===(E=e.properties[4])||void 0===E?void 0:E.value))&&void 0!==L?L:0,he[1]=null!==(N=ke(null===(I=e.properties[5])||void 0===I?void 0:I.value))&&void 0!==N?N:0,he[2]=null!==(B=ke(null===(P=e.properties[6])||void 0===P?void 0:P.value))&&void 0!==B?B:0;break;case"RotationOffset":me[0]=null!==(D=ke(null===(k=e.properties[4])||void 0===k?void 0:k.value))&&void 0!==D?D:0,me[1]=null!==(V=ke(null===(G=e.properties[5])||void 0===G?void 0:G.value))&&void 0!==V?V:0,me[2]=null!==(K=ke(null===(H=e.properties[6])||void 0===H?void 0:H.value))&&void 0!==K?K:0;break;case"ScalingOffset":fe[0]=null!==($=ke(null===(U=e.properties[4])||void 0===U?void 0:U.value))&&void 0!==$?$:0,fe[1]=null!==(z=ke(null===(W=e.properties[5])||void 0===W?void 0:W.value))&&void 0!==z?z:0,fe[2]=null!==(q=ke(null===(j=e.properties[6])||void 0===j?void 0:j.value))&&void 0!==q?q:0;break;case"Lcl Scaling":pe[0]=null!==(Z=ke(null===(Y=e.properties[4])||void 0===Y?void 0:Y.value))&&void 0!==Z?Z:1,pe[1]=null!==(ee=ke(null===(J=e.properties[5])||void 0===J?void 0:J.value))&&void 0!==ee?ee:1,pe[2]=null!==(ne=ke(null===(te=e.properties[6])||void 0===te?void 0:te.value))&&void 0!==ne?ne:1;break;case"RotationOrder":_e=null!==(se=ke(null===(oe=e.properties[4])||void 0===oe?void 0:oe.value))&&void 0!==se?se:0;break;case"InheritType":ge=null!==(ie=ke(null===(re=e.properties[4])||void 0===re?void 0:re.value))&&void 0!==ie?ie:1}}return{translation:ae,rotation:le,preRotation:ue,postRotation:ce,rotationPivot:de,scalingPivot:he,rotationOffset:me,scalingOffset:fe,scale:pe,rotationOrder:_e,inheritType:ge}}function Pe(e){let t=null,n=null,o=null,s="Normalize";const r=X(e,"Transform");if(r&&r.properties[0]){const e=r.properties[0].value;e instanceof Float64Array&&16===e.length?t=e:e instanceof Float32Array&&16===e.length&&(t=new Float64Array(e))}const i=X(e,"TransformLink");if(i&&i.properties[0]){const e=i.properties[0].value;e instanceof Float64Array&&16===e.length?n=e:e instanceof Float32Array&&16===e.length&&(n=new Float64Array(e))}const a=X(e,"TransformAssociateModel");if(a&&a.properties[0]){const e=a.properties[0].value;e instanceof Float64Array&&16===e.length?o=e:e instanceof Float32Array&&16===e.length&&(o=new Float64Array(e))}const l=X(e,"Mode"),u=l?Q(l,0):void 0;return"Normalize"===u||"Additive"===u||"TotalOne"===u?s=u:u&&(s="Unknown"),{bindPoseMatrix:t,transformLinkMatrix:n,transformAssociateModelMatrix:o,clusterMode:s}}function Be(e,t,n,o,s,r,i,a){if(!n)return[];const l=[];return"Additive"!==o&&"TotalOne"!==o||l.push({type:"cluster-mode-runtime-unsupported",message:`Cluster mode '${o}' is preserved but not applied by Babylon linear blend skinning.`,boneModelId:e,boneName:t,clusterMode:o}),s||l.push({type:"missing-cluster-transform",message:"Cluster is missing Transform matrix; falling back to rest/bind-pose data.",boneModelId:e,boneName:t,clusterMode:o}),r||l.push({type:"missing-cluster-transform-link",message:"Cluster is missing TransformLink matrix; falling back to model bind pose or rest transform.",boneModelId:e,boneName:t,clusterMode:o}),a||l.push({type:"missing-bind-pose-matrix",message:"No BindPose matrix was found for this bone model.",boneModelId:e,boneName:t,clusterMode:o}),i&&l.push({type:"associate-model-present",message:"TransformAssociateModel is preserved for future associate-model skinning semantics.",boneModelId:e,boneName:t,clusterMode:o}),l}function ke(e){if("number"==typeof e)return e}function De(e){if(e instanceof Int32Array)return e;if(e instanceof Float64Array){const t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=Math.round(e[n]);return t}return null}function Ge(e){return e instanceof Float64Array?e:e instanceof Float32Array?new Float64Array(e):null}function Ve(e,t){var n;const o=null!==(n=function(e,t){if(0===e.length)return;const n=e.map(e=>He(e,t)),o=new Set(n[0]);for(const e of n.slice(1))for(const t of Array.from(o))e.includes(t)||o.delete(t);return n[0].find(e=>o.has(e))}(e,t))&&void 0!==n?n:e[0];let s=o,r=Ke(s,t);for(;void 0!==r;){const e=t.objects.get(r);if(!e||"Model"!==e.name||!Ie(e))break;s=r,r=Ke(r,t)}return s}function He(e,t){const n=[];let o=e;for(;void 0!==o;){const e=t.objects.get(o);if(!e||"Model"!==e.name)break;n.push(o),o=Ke(o,t)}return n}function Ke(e,t){const n=t.connections.find(n=>{var o;return"OO"===n.type&&n.childId===e&&"Model"===(null===(o=t.objects.get(n.parentId))||void 0===o?void 0:o.name)});return null==n?void 0:n.parentId}function Ue(e){var t,n,o;return null!==(o=null!==(n=null!==(t=e.find(e=>e.isCluster&&e.transformLinkMatrix))&&void 0!==t?t:e.find(e=>e.isCluster))&&void 0!==n?n:e.find(e=>e.modelBindPoseMatrix))&&void 0!==o?o:e[0]}function $e(e,t,n){if(e.length!==t.length)return!1;for(let o=0;o<e.length;o++)if(Math.abs(e[o]-t[o])>n)return!1;return!0}function We(e,t){var n;const o=t.objects.get(e);if(!o||"Model"!==o.name)return null;const s=Ne(o);return{modelId:e,name:Z(null!==(n=Q(o,1))&&void 0!==n?n:`Bone${e.toString()}`),index:-1,parentIndex:-1,isCluster:!1,translation:s.translation,rotation:s.rotation,preRotation:s.preRotation,postRotation:s.postRotation,rotationPivot:s.rotationPivot,scalingPivot:s.scalingPivot,rotationOffset:s.rotationOffset,scalingOffset:s.scalingOffset,scale:s.scale,rotationOrder:s.rotationOrder,inheritType:s.inheritType,clusterMode:"Unknown",bindPoseMatrix:null,transformLinkMatrix:null,transformAssociateModelMatrix:null,modelBindPoseMatrix:null,diagnostics:[]}}function ze(e,t){return e<t?-1:e>t?1:0}function je(e,t,n){var o,s;return(null!==(o=n.get(e))&&void 0!==o?o:Number.MAX_SAFE_INTEGER)-(null!==(s=n.get(t))&&void 0!==s?s:Number.MAX_SAFE_INTEGER)||ze(e,t)}const qe=46186158e3,Xe=1/23,Ye=1e-5,Qe=[24,25,30,48,50,60,100,120];function Ze(e,t,n){var o,s,r,i;const a=Z(null!==(o=Q(t,1))&&void 0!==o?o:"Animation"),l=function(e){var t,n,o,s;const r=X(e,"Properties70");if(!r)return null;let i=0,a=null;for(const e of r.children){if("P"!==e.name)continue;const r=Q(e,0);"LocalStart"===r||"ReferenceStart"===r?i=null!==(n=lt(null===(t=e.properties[4])||void 0===t?void 0:t.value))&&void 0!==n?n:i:"LocalStop"!==r&&"ReferenceStop"!==r||(a=null!==(s=lt(null===(o=e.properties[4])||void 0===o?void 0:o.value))&&void 0!==s?s:a)}return null!==a?{start:i,stop:a}:null}(t),u=J(n,e,"AnimationLayer");if(0===u.length)return null;const c=[],d=[],h=[],m=[];let f=1/0,p=0;for(const{id:e,node:t}of u){const o=Z(null!==(s=Q(t,1))&&void 0!==s?s:"Layer");let a=100,l=0;const u=X(t,"Properties70");if(u)for(const e of u.children){if("P"!==e.name)continue;const t=Q(e,0);if("Weight"===t){const t=null===(r=e.properties[4])||void 0===r?void 0:r.value;"number"==typeof t&&(a=t)}else if("BlendMode"===t){const t=null===(i=e.properties[4])||void 0===i?void 0:i.value;"number"==typeof t&&(l=t)}}const _=J(n,e,"AnimationCurveNode"),g=[],y=[],v=[];for(const{id:e,node:t}of _){const s=Je(e,t,n);if(!s){const s=et(e,t,n);if(s){tt(s.curves,e=>{e<f&&(f=e),e>p&&(p=e)}),y.push(s),d.push(s);const t={type:"unsupported-curve-node",message:`AnimationCurveNode '${s.type}' is preserved as diagnostic data but not evaluated at runtime.`,layerName:o,curveNodeId:e,curveNodeType:s.type,targetId:s.targetId,propertyName:s.propertyName};v.push(t),m.push(t)}continue}for(const e of s.curves)for(const t of e.keys)t.time<f&&(f=t.time),t.time>p&&(p=t.time);g.push(s),c.push(s)}h.push({name:o,weight:a,normalizedWeight:a/100,blendMode:l,curveNodes:g,unsupportedCurveNodes:y,diagnostics:v})}if(0===c.length&&0===d.length)return null;h.length>1&&m.push({type:"multiple-animation-layers",message:"Multiple animation layers are preserved, but runtime blending is not yet evaluated."});for(const e of h){if(0!==e.blendMode){const t={type:"unsupported-layer-blend-mode",message:`Animation layer blend mode ${e.blendMode} is preserved but not yet blended at runtime.`,layerName:e.name};e.diagnostics.push(t),m.push(t)}if(100!==e.weight){const t={type:"partial-layer-weight",message:`Animation layer weight ${e.weight} is preserved but not yet applied at runtime.`,layerName:e.name};e.diagnostics.push(t),m.push(t)}}const _=f>0&&isFinite(f)?f:0;if(_>0){for(const e of c)for(const t of e.curves)for(const e of t.keys)e.time-=_;for(const e of d)for(const t of e.curves)for(const e of t.keys)e.time-=_;p-=_}const g=l?Math.max(l.start-_,0):0,y=l?Math.max(l.stop-_,g):0,v=y>g,b=v?g:0,x=v?y:p;return{name:a,startTime:b,stopTime:x,duration:Math.max(x-b,0),curveNodes:c,layers:h,unsupportedCurveNodes:d,diagnostics:m}}function Je(e,t,n){var o;const s=Z(null!==(o=Q(t,1))&&void 0!==o?o:"");if("T"===s||"R"===s||"S"===s){const t=function(e,t){for(const n of t.connections)if(n.childId===e&&"OP"===n.type){const e=t.objects.get(n.parentId);if(e&&"Model"===e.name)return n.parentId}return null}(e,n);if(null===t)return null;const o=nt(e,n);return 0===o.length?null:{type:s,targetModelId:t,curves:o}}if("DeformPercent"===s){const t=function(e,t){for(const n of t.connections)if(n.childId===e&&"OP"===n.type){const e=t.objects.get(n.parentId);if(e&&"Deformer"===e.name&&"BlendShapeChannel"===Q(e,2))return n.parentId}for(const n of t.connections)if(n.childId===e&&"OO"===n.type){const e=t.objects.get(n.parentId);if(e&&"Deformer"===e.name&&"BlendShapeChannel"===Q(e,2))return n.parentId}return null}(e,n);if(null===t)return null;const o=nt(e,n);return 0===o.length?null:{type:"DeformPercent",targetModelId:t,curves:o}}return null}function et(e,t,n){var o;const s=Z(null!==(o=Q(t,1))&&void 0!==o?o:""),r=nt(e,n),i=function(e){var t,n;const o={},s=X(e,"Properties70");for(const e of null!==(t=null==s?void 0:s.children)&&void 0!==t?t:[]){if("P"!==e.name)continue;const t=Q(e,0);if(!(null==t?void 0:t.startsWith("d|")))continue;const s=ut(null===(n=e.properties[4])||void 0===n?void 0:n.value);null!==s&&(o[t]=s)}return o}(t);if(0===r.length&&0===Object.keys(i).length)return null;let a,l=null;for(const t of n.connections)if(t.childId===e&&"OP"===t.type){l=t.parentId,a=t.propertyName;break}return{type:s,id:e,targetId:l,propertyName:a,curveCount:r.length,curves:r,defaultValues:i}}function tt(e,t){for(const n of e)for(const e of n.keys)t(e.time)}function nt(e,t){var n;const o=[];for(const s of t.connections)if(s.parentId===e&&"OP"===s.type){const e=t.objects.get(s.childId);if(!e||"AnimationCurve"!==e.name)continue;const r=null!==(n=s.propertyName)&&void 0!==n?n:"d|X",i=ot(e);if(i.length>0){const t=st(e,i);o.push({channel:r,keys:t?rt(i):i,isSampled:t})}}if(0===o.length){const n=J(t,e,"AnimationCurve"),s=["d|X","d|Y","d|Z"];for(let e=0;e<n.length&&e<3;e++){const t=ot(n[e].node);if(t.length>0){const r=st(n[e].node,t);o.push({channel:s[e],keys:r?rt(t):t,isSampled:r})}}}return o}function ot(e){var t,n,o,s,r,i,a,l,u;const c=X(e,"KeyTime"),d=X(e,"KeyValueFloat");if(!c||!d)return[];const h=(g=null===(t=c.properties[0])||void 0===t?void 0:t.value)instanceof Float64Array?g:null,m=ct(null===(n=d.properties[0])||void 0===n?void 0:n.value),f=at(null===(s=null===(o=X(e,"KeyAttrFlags"))||void 0===o?void 0:o.properties[0])||void 0===s?void 0:s.value),p=ct(null===(i=null===(r=X(e,"KeyAttrDataFloat"))||void 0===r?void 0:r.properties[0])||void 0===i?void 0:i.value),_=at(null===(l=null===(a=X(e,"KeyAttrRefCount"))||void 0===a?void 0:a.properties[0])||void 0===l?void 0:l.value);var g;if(!h||!m)return[];if(h.length!==m.length)return[];const y=function(e,t,n){if(!t||0===t.length)return new Array(e).fill(-1);if(n&&n.length>0){let t=0;for(const e of n)t+=e;if(t===e){const e=[];for(let t=0;t<n.length;t++){const o=n[t];for(let n=0;n<o;n++)e.push(t)}return e}}return t.length===e?Array.from({length:e},(e,t)=>t):1===t.length?new Array(e).fill(0):Array.from({length:e},(e,n)=>Math.min(n,t.length-1))}(h.length,f,_),v=[];for(let e=0;e<h.length;e++){const t=y[e],n=t>=0&&null!==(u=null==f?void 0:f[t])&&void 0!==u?u:0,o=4*t;v.push({time:Number(h[e])/qe,value:m[e],interpolation:dt(n),constantMode:256&n?"next":"standard",rightSlope:ht(p,o),nextLeftSlope:ht(p,o+1)})}return v}function st(e,t){var n;return"FbxMayaSample Curve"===Z(null!==(n=Q(e,1))&&void 0!==n?n:"")||function(e){if(e.length<8)return!1;const t=[];for(let n=1;n<e.length;n++){const o=e[n].time-e[n-1].time;if(!(o>0))return!1;t.push(o)}const n=t.reduce((e,t)=>e+t,0)/t.length;if(n>Xe)return!1;const o=Math.max(1e-6,.05*n);if(t.some(e=>Math.abs(e-n)>o))return!1;const s=1/n;return!!Qe.some(e=>Math.abs(s-e)<=Math.max(.25,.02*e))&&!function(e){let t=!1,n=!0,o=!0,s=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,i=0;for(const t of e)s=Math.min(s,t.value),r=Math.max(r,t.value);for(let s=0;s<e.length-1;s++){const r=e[s],a=e[s+1];if("cubic"!==r.interpolation)continue;t=!0;const l=a.time-r.time;if(!(l>0))continue;const u=(a.value-r.value)/l,c=r.rightSlope,d=r.nextLeftSlope;if(void 0!==c&&void 0!==d){(Math.abs(c)>Ye||Math.abs(d)>Ye)&&(o=!1);for(const e of[.25,.5,.75]){const t=mt(r.value,a.value,c,d,l,e),n=r.value+e*l*u;i=Math.max(i,Math.abs(t-n))}}else n=!1}if(!t||!n||o)return!1;const a=r-s;return i>Math.max(1e-4,.01*a)}(e)}(t)}function rt(e){return e.map(e=>({time:e.time,value:e.value,interpolation:"linear"}))}function it(e,t){var n,o;if(!e||0===e.keys.length)return null;const s=e.keys;if(t<=s[0].time)return s[0].value;if(t>=s[s.length-1].time)return s[s.length-1].value;for(let r=0;r<s.length-1;r++){const i=s[r],a=s[r+1];if(t<i.time||t>a.time)continue;if(a.time===i.time)return i.value;if("constant"===i.interpolation)return"next"===i.constantMode?a.value:i.value;const l=a.time-i.time,u=(t-i.time)/l;if("cubic"===i.interpolation&&!e.isSampled){const e=(a.value-i.value)/l,t=null!==(n=i.rightSlope)&&void 0!==n?n:e,s=null!==(o=i.nextLeftSlope)&&void 0!==o?o:e;return mt(i.value,a.value,t,s,l,u)}return i.value+u*(a.value-i.value)}return s[s.length-1].value}function at(e){if(e instanceof Int32Array)return e;if(e instanceof Float32Array||e instanceof Float64Array){const t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}return null}function lt(e){return"number"==typeof e?e/qe:null}function ut(e){return"number"==typeof e?e:null}function ct(e){if(e instanceof Float32Array)return e;if(e instanceof Float64Array){const t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}return null}function dt(e){return 8&e?"cubic":4&e?"linear":2&e?"constant":"linear"}function ht(e,t){if(!e||t<0||t>=e.length)return;const n=e[t];return Number.isFinite(n)?n:void 0}function mt(e,t,n,o,s,r){const i=r*r,a=i*r;return(2*a-3*i+1)*e+(a-2*i+r)*s*n+(-2*a+3*i)*t+(a-i)*s*o}function ft(e,t,n){var o,s;const r=n.parentOf.get(e);if(!r)return null;const i=n.objects.get(r.id);if(!i||"Geometry"!==i.name)return null;const a=r.id,l=[],u=J(n,e,"Deformer");for(const{id:e,node:t}of u){if("BlendShapeChannel"!==Q(t,2))continue;const r=Z(null!==(o=Q(t,1))&&void 0!==o?o:"MorphTarget");let i=0;const a=X(t,"Properties70");if(a)for(const e of a.children)if("P"===e.name&&"DeformPercent"===Q(e,0)){const t=null===(s=e.properties[4])||void 0===s?void 0:s.value;"number"==typeof t&&(i=t)}const u=pt(t),c=[],d=J(n,e,"Geometry");for(const{node:e}of d){if("Shape"!==Q(e,2))continue;const t=yt(e);t&&c.push(t)}if(c.length>0){const t=[],n=_t(u,c,e,r,t);l.push({name:r,id:e,deformPercent:i,shapes:gt(c,n),fullWeights:n?[...n].sort((e,t)=>e-t):null,diagnostics:t})}}return 0===l.length?null:{id:e,geometryId:a,channels:l}}function pt(e){var t;const n=X(e,"FullWeights"),o=null===(t=null==n?void 0:n.properties[0])||void 0===t?void 0:t.value;return o&&(o instanceof Float64Array||o instanceof Float32Array||o instanceof Int32Array)?Array.from(o,e=>Number(e)):null}function _t(e,t,n,o,s){return e?e.length!==t.length?(1===t.length||s.push({type:"full-weights-mismatch",message:`FullWeights length ${e.length} does not match shape count ${t.length}; using the first shape for compatibility.`,channelId:n,channelName:o}),null):e:(t.length>1&&s.push({type:"missing-full-weights",message:"Blend shape channel has multiple shapes but no FullWeights; using the first shape for compatibility.",channelId:n,channelName:o}),null)}function gt(e,t){return t&&t.length===e.length?e.map((e,n)=>({shape:e,weight:t[n]})).sort((e,t)=>e.weight-t.weight).map(e=>e.shape):e.length>1?[e[0]]:e}function yt(e){var t,n,o;const s=X(e,"Indexes"),r=X(e,"Vertices");if(!s||!r)return null;const i=null===(t=s.properties[0])||void 0===t?void 0:t.value,a=null===(n=r.properties[0])||void 0===n?void 0:n.value;if(!i||!a)return null;const l=function(e){if(e instanceof Uint32Array)return e;if(e instanceof Int32Array||e instanceof Float32Array||e instanceof Float64Array){const t=new Uint32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}return null}(i);if(!l)return null;let u;if(a instanceof Float64Array)u=a;else{if(!(a instanceof Float32Array))return null;u=new Float64Array(a)}let c=null;const d=X(e,"Normals");if(d){const e=null===(o=d.properties[0])||void 0===o?void 0:o.value;e instanceof Float64Array?c=e:e instanceof Float32Array&&(c=new Float64Array(e))}return{indices:l,vertices:u,normals:c}}const vt=new Set(["Character","CharacterPose","ControlSet","ControlSetPlug","SelectionSet","CollectionExclusive"]);function bt(e){return"Skin"===e||"Cluster"===e||"BlendShape"===e||"BlendShapeChannel"===e}function xt(e,t,n,o,s){var r,i,a,l;return{type:o,message:s,objectId:t,objectName:Z(null!==(r=Q(n,1))&&void 0!==r?r:n.name),nodeName:n.name,subType:null!==(i=Q(n,2))&&void 0!==i?i:"",parentCount:e.connections.filter(e=>e.childId===t).length,childCount:null!==(l=null===(a=e.childrenOf.get(t))||void 0===a?void 0:a.length)&&void 0!==l?l:0}}function Tt(e){const t=function(e){var t,n;const o=new Map,s=[],r=new Map,i=new Map,a=[],l=[],u=[],c=new Map,d=new Map;let h=-1;const m=e=>{let t=c.get(e);return void 0===t&&(t=h--,c.set(e,t)),t},f=(e,t)=>{let n=d.get(e);n||(n=new Map,d.set(e,n));let o=n.get(t);return void 0===o&&(o=h--,n.set(t,o)),o},p=Y(e,"Objects");if(p)for(const e of p.children){const t=e.properties[0];if(t){const n=ee(t.value);if(void 0!==n)o.set(n,e),s.push({id:n,node:e,source:"Objects",synthetic:!1});else if("string"==typeof t.value){const n=Z(t.value),l=m(n),c=oe(e,l);if(o.set(l,c),s.push({id:l,node:c,source:"Objects",legacyName:n,synthetic:!1}),"Model"===e.name&&"Mesh"===Q(e,1)){const t=f("Geometry",n),c=se(e,t);o.set(t,c),s.push({id:t,node:c,source:"legacySyntheticGeometry",legacyName:n,synthetic:!0}),ne(a,r,i,u,"OO",t,l)}}}}const _=Y(e,"Connections");if(_)for(const e of _.children){if("C"!==e.name&&"Connect"!==e.name)continue;const s=l.length,d=Q(e,0),h=null===(t=e.properties[1])||void 0===t?void 0:t.value,m=null===(n=e.properties[2])||void 0===n?void 0:n.value,f={source:e.name,rawType:d,accepted:!1};if(l.push(f),"OO"!==d&&"OP"!==d){const e=void 0===h?void 0:te(h,c),t=void 0===m?void 0:te(m,c);u.push({reason:"unsupported-connection-type",message:`Unsupported FBX connection type '${null!=d?d:""}' was not added to the graph.`,connectionIndex:s,type:d,childId:e,parentId:t});continue}if(void 0===h||void 0===m){u.push({reason:"missing-connection-endpoint",message:"FBX connection is missing a child or parent endpoint.",connectionIndex:s,type:d});continue}const p=te(h,c),_=te(m,c);if(void 0===p||void 0===_){u.push({reason:"unresolved-legacy-endpoint",message:"FBX connection references a legacy string endpoint that is not present in the object table.",connectionIndex:s,type:d});continue}const g="OP"===d&&e.properties.length>3?Q(e,3):void 0;f.childId=p,f.parentId=_,f.propertyName=g,p===_&&u.push({reason:"self-loop",message:"FBX connection references the same object as child and parent.",connectionIndex:s,type:d,childId:p,parentId:_,propertyName:g}),o.has(p)||u.push({reason:"unresolved-object-reference",message:"FBX connection child ID is not present in the object table.",connectionIndex:s,type:d,childId:p,parentId:_,propertyName:g}),0===_||o.has(_)||u.push({reason:"unresolved-object-reference",message:"FBX connection parent ID is not present in the object table.",connectionIndex:s,type:d,childId:p,parentId:_,propertyName:g}),ne(a,r,i,u,d,p,_,g,s),f.accepted=!0}return{objects:o,objectEntries:s,childrenOf:r,parentOf:i,connections:a,connectionEntries:l,diagnostics:u}}(e),n=function(e){const t=new Map,n=Y(e,"Definitions");if(!n)return t;for(const e of n.children){if("ObjectType"!==e.name)continue;const n=Q(e,0);if(n)for(const o of e.children){if("PropertyTemplate"!==o.name)continue;const e=Q(o,0);if(!e)continue;const s=Ae(n,e,o);let r=t.get(n);r||(r=new Map,t.set(n,r)),r.set(e,s)}}return t}(e),o=function(e){var t;const n={upAxis:1,upAxisSign:1,frontAxis:2,frontAxisSign:1,coordAxis:0,coordAxisSign:1,unitScaleFactor:1},o=Y(e,"GlobalSettings");if(!o)return n;const s=o.children.find(e=>"Properties70"===e.name);if(!s)return n;for(const e of s.children){if("P"!==e.name)continue;const o=Q(e,0),s=Rt(null===(t=e.properties[4])||void 0===t?void 0:t.value);if(o&&void 0!==s)switch(o){case"UpAxis":n.upAxis=s;break;case"UpAxisSign":n.upAxisSign=s;break;case"FrontAxis":n.frontAxis=s;break;case"FrontAxisSign":n.frontAxisSign=s;break;case"CoordAxis":n.coordAxis=s;break;case"CoordAxisSign":n.coordAxisSign=s;break;case"UnitScaleFactor":n.unitScaleFactor=s}}return n}(e),s=[];for(const[e,o]of Array.from(t.objects))"Material"===o.name&&s.push(we(o,e,t,n));const r=[];for(const[e,n]of Array.from(t.objects))"Geometry"===n.name&&"Mesh"===Q(n,2)&&r.push(re(n,e));const i=function(e){const t=[];for(const[n,o]of Array.from(e.objects))if("Deformer"===o.name&&"Skin"===Q(o,2)){const o=Ee(n,0,e);o&&t.push(o)}return t}(t),a=function(e,t){if(0===t.length)return[];const n=new Map;for(const o of t){const t=o.bones.filter(e=>e.isCluster).map(e=>e.modelId);if(0===t.length)continue;const s=Ve(t,e),r=n.get(s);r?r.push(o):n.set(s,[o])}return Array.from(n.entries()).sort(([e],[t])=>ze(e,t)).map(([t,n])=>function(e,t,n){var o,s;const r=new Set,i=new Set,a=new Map,l=new Map;for(const e of t)for(const t of e.bones){l.has(t.modelId)||l.set(t.modelId,l.size);let e=a.get(t.modelId);if(e||(e=[],a.set(t.modelId,e)),e.push(t),t.isCluster){r.add(t.modelId);for(const e of He(t.modelId,n))i.add(e)}}const u=function(e){const t=[];for(const[n,o]of Array.from(e)){const e=o.filter(e=>e.isCluster&&e.transformLinkMatrix).map(e=>e.transformLinkMatrix);if(e.length<2)continue;const s=e[0];e.some(e=>!$e(s,e,1e-5))&&t.push(`Model ${n.toString()} has differing Cluster.TransformLink matrices across skins`)}return t}(a),c=new Map;for(const[e,t]of Array.from(a))c.set(e,Ue(t));const d=function(e,t){const n=new Map;for(const o of Array.from(e)){const s=Ke(o,t);void 0!==s&&e.has(s)&&n.set(o,s)}return n}(i,n),h=function(e,t,n){var o;const s=new Map;for(const n of Array.from(e)){const e=t.get(n);if(void 0===e)continue;let o=s.get(e);o||(o=[],s.set(e,o)),o.push(n)}for(const e of Array.from(s.values()))e.sort((e,t)=>je(e,t,n));const r=[],i=[...Array.from(e).filter(e=>!t.has(e)).sort((e,t)=>je(e,t,n))];for(;i.length>0;){const e=i.shift();r.push(e),i.push(...null!==(o=s.get(e))&&void 0!==o?o:[])}return r}(i,d,l),m=[],f=new Map;for(const e of h){const t=null!==(o=c.get(e))&&void 0!==o?o:We(e,n);if(!t)continue;const i=d.get(e),a=void 0===i?-1:null!==(s=f.get(i))&&void 0!==s?s:-1,l=m.length,u=Object.assign(Object.assign({},t),{index:l,parentIndex:a,isCluster:r.has(e)});m.push(u),f.set(e,l)}const p=t.map(t=>function(e,t,n){const o=e.bones.map(e=>{const o=n.get(e.modelId);if(void 0===o&&e.isCluster)throw new Error(`FBX rig resolver: cluster bone ${e.name} is missing from resolved rig ${t}`);return null!=o?o:-1});return{skinId:e.id,geometryId:e.geometryId,rigId:t,skinBoneIndexToRigBoneIndex:o,clusterModelIds:new Set(e.bones.filter(e=>e.isCluster).map(e=>e.modelId))}}(t,`rig_${e.toString()}`,f));return{id:`rig_${e.toString()}`,rootModelIds:m.filter(e=>e.parentIndex<0).map(e=>e.modelId),bones:m,modelIdToBoneIndex:f,clusterModelIds:r,skinBindings:p,warnings:u}}(t,n,e))}(t,i),l=function(e){const t=[];for(const[n,o]of Array.from(e.objects))if("Deformer"===o.name&&"BlendShape"===Q(o,2)){const o=ft(n,0,e);o&&t.push(o)}return t}(t),u=function(e){const t=[];for(const[n,o]of Array.from(e.objects))if("AnimationStack"===o.name){const s=Ze(n,o,e);s&&t.push(s)}return t}(t),c=function(e,t){var n,o,s,r;const i=[],a=null!==(n=ge(t,"NodeAttribute","FbxCamera"))&&void 0!==n?n:ge(t,"NodeAttribute");for(const[t,n]of Array.from(e.objects)){if("NodeAttribute"!==n.name)continue;if("Camera"!==Q(n,2))continue;const l=e.parentOf.get(t);if(!l)continue;const u=e.objects.get(l.id);if(!u||"Model"!==u.name)continue;const c=Z(null!==(o=Q(u,1))&&void 0!==o?o:"Camera"),d=ve(n,a,"NearPlane",.1),h=ve(n,a,"FarPlane",1e4),m=St(n,a),f=1===ve(n,a,"CameraProjectionType",0)||1===ve(n,a,"ProjectionType",0)?"orthographic":"perspective",p=Rt(ye(n,a,"FocalLength")),_=null!==(s=Rt(ye(n,a,"FilmWidth")))&&void 0!==s?s:Rt(ye(n,a,"ApertureWidth")),g=null!==(r=Rt(ye(n,a,"FilmHeight")))&&void 0!==r?r:Rt(ye(n,a,"ApertureHeight")),y=Rt(ye(n,a,"OrthoZoom")),v=Rt(ye(n,a,"Roll")),b=Ft(n,a,m,p,g),x=[];"orthographic"===f&&void 0===y&&x.push("Orthographic camera has no OrthoZoom; runtime orthographic bounds use a fallback."),void 0!==p&&void 0===g&&void 0===ye(n,a,"FieldOfView")&&x.push("FocalLength is present without FilmHeight; default field of view fallback may be used."),i.push({modelId:l.id,name:c,fieldOfView:b,nearPlane:d,farPlane:h,aspectRatio:m,projectionType:f,focalLength:p,filmWidth:_,filmHeight:g,orthoZoom:y,roll:v,unknownProperties:Et(n,wt),diagnostics:x})}return i}(t,n),d=function(e,t){var n,o,s,r,i;const a=[],l=null!==(n=ge(t,"NodeAttribute","FbxLight"))&&void 0!==n?n:ge(t,"NodeAttribute");for(const[t,n]of Array.from(e.objects)){if("NodeAttribute"!==n.name)continue;if("Light"!==Q(n,2))continue;const u=e.parentOf.get(t);if(!u)continue;const c=e.objects.get(u.id);if(!c||"Model"!==c.name)continue;const d=Z(null!==(o=Q(c,1))&&void 0!==o?o:"Light"),h=ve(n,l,"LightType",0),m=be(n,l,"Color",[1,1,1]),f=ve(n,l,"Intensity",100)/100,p=null!==(s=Rt(ye(n,l,"OuterAngle")))&&void 0!==s?s:Rt(ye(n,l,"ConeAngle")),_=Rt(ye(n,l,"InnerAngle")),g=null!=p?p:45,y=ve(n,l,"DecayType",2),v=Rt(ye(n,l,"DecayStart")),b=Ot(ye(n,l,"EnableNearAttenuation")),x=Ot(ye(n,l,"EnableFarAttenuation")),T=null!==(i=null!==(r=Ot(ye(n,l,"CastShadow")))&&void 0!==r?r:Ot(ye(c,void 0,"CastShadow")))&&void 0!==i?i:Ot(ye(c,void 0,"Shadow")),A=[];2!==y&&A.push(`DecayType ${y} is preserved as metadata; Babylon falloff is not remapped in this pass.`),void 0!==v&&A.push("DecayStart is preserved as metadata and is not mapped to Babylon light range."),a.push({modelId:u.id,name:d,lightType:h,color:m,intensity:f,coneAngle:g,decayType:y,innerAngle:_,outerAngle:p,decayStart:v,enableNearAttenuation:b,enableFarAttenuation:x,castShadows:T,unknownProperties:Et(n,Ct),diagnostics:A})}return a}(t,n),h=function(e){var t,n;const o=e.diagnostics.map(t=>({type:"connection-graph",message:t.message,objectId:t.childId,subType:t.reason,parentCount:void 0===t.childId?void 0:e.connections.filter(e=>e.childId===t.childId).length}));for(const[s,r]of Array.from(e.objects)){const i=null!==(t=Q(r,2))&&void 0!==t?t:"";"Constraint"!==r.name?vt.has(r.name)?o.push(xt(e,s,r,"unsupported-helper",`${r.name} helper data is preserved as diagnostic data but not evaluated at runtime.`)):"LayeredTexture"!==r.name?"Pose"!==r.name||"BindPose"===i?"Deformer"!==r.name||bt(i)?"NodeAttribute"===r.name&&i&&"Camera"!==i&&"Light"!==i&&o.push(xt(e,s,r,"unsupported-node-attribute",`NodeAttribute subtype '${i}' is preserved as diagnostic data but not converted to a Babylon object.`)):o.push(xt(e,s,r,"unsupported-deformer",`Deformer subtype '${i}' is preserved as diagnostic data but not evaluated at runtime.`)):o.push(xt(e,s,r,"unsupported-pose",`Pose subtype '${i}' is preserved as diagnostic data but not evaluated at runtime.`)):o.push(xt(e,s,r,"unsupported-layered-texture","LayeredTexture is preserved as diagnostic data; runtime texture layer blending is not implemented.")):o.push(xt(e,s,r,"unsupported-constraint",`Constraint '${i||Z(null!==(n=Q(r,1))&&void 0!==n?n:"")}' is preserved as diagnostic data but not evaluated at runtime.`))}return o}(t),m=function(e,t,n,o){var s;const r=new Map;for(const e of t)r.set(e.id,e);const i=new Map;for(const e of n)i.set(e.id,e);const a=null!==(s=e.childrenOf.get(0))&&void 0!==s?s:[],l=[];for(const{id:t}of a){const n=e.objects.get(t);n&&"Model"===n.name&&l.push(At(t,n,e,r,i,o))}return l}(t,r,s,n);return Object.assign({rootModels:m,geometries:r,materials:s,skins:i,rigs:a,blendShapes:l,animations:u,cameras:c,lights:d,diagnostics:h},o)}function At(e,t,n,o,s,r){var i,a,l;const u=Z(null!==(i=Q(t,1))&&void 0!==i?i:"Model"),c=null!==(a=Q(t,2))&&void 0!==a?a:"Null",d=J(n,e,"Geometry"),h=d.length>0?o.get(d[0].id):void 0,m=J(n,e,"Material"),f=[];for(const{id:e}of m){const t=s.get(e);t&&f.push(t)}const p=function(e,t){const n=be(e,t,"Lcl Translation",[0,0,0]),o=be(e,t,"Lcl Rotation",[0,0,0]),s=be(e,t,"Lcl Scaling",[1,1,1]),r=be(e,t,"PreRotation",[0,0,0]),i=be(e,t,"PostRotation",[0,0,0]),a=be(e,t,"RotationPivot",[0,0,0]),l=be(e,t,"ScalingPivot",[0,0,0]),u=be(e,t,"RotationOffset",[0,0,0]),c=be(e,t,"ScalingOffset",[0,0,0]),d=be(e,t,"GeometricTranslation",[0,0,0]),h=be(e,t,"GeometricRotation",[0,0,0]),m=be(e,t,"GeometricScaling",[1,1,1]),f=ve(e,t,"RotationOrder",0),p=ve(e,t,"InheritType",1);return{translation:n,rotation:o,scale:s,preRotation:r,postRotation:i,rotationPivot:a,scalingPivot:l,rotationOffset:u,scalingOffset:c,geometricTranslation:d,geometricRotation:h,geometricScaling:m,rotationOrder:f,inheritType:p,diagnostics:1!==p&&2!==p?[`InheritType ${p} is parsed and preserved; runtime parent-scale inheritance remains gated to avoid changing existing visual behavior without a fixture-specific baseline.`]:[]}}(t,null!==(l=ge(r,"Model","FbxNode"))&&void 0!==l?l:ge(r,"Model")),_=J(n,e,"Model"),g=[];for(const{id:e,node:t}of _)g.push(At(e,t,n,o,s,r));const y=t.children.find(e=>"Culling"===e.name),v=!!y&&"CullingOff"===Q(y,0),b=function(e){var t;const n=X(e,"Properties70");if(!n)return;const o={};let s=!1;for(const e of n.children){if("P"!==e.name)continue;const n=Q(e,0);if(!n||Mt.has(n))continue;const r=null===(t=e.properties[4])||void 0===t?void 0:t.value;void 0!==r&&("string"==typeof r||"number"==typeof r||"boolean"==typeof r)&&(o[n]=r,s=!0)}return s?o:void 0}(t);return Object.assign({id:e,name:u,subType:c,geometry:h,materials:f,children:g,cullingOff:v,customProperties:b},p)}const Mt=new Set(["Lcl Translation","Lcl Rotation","Lcl Scaling","PreRotation","PostRotation","RotationPivot","ScalingPivot","RotationOffset","ScalingOffset","RotationOrder","GeometricTranslation","GeometricRotation","GeometricScaling","Visibility","InheritType","ScalingMax","DefaultAttributeIndex","currentUVSet","lockInfluenceWeights"]),wt=new Set(["FieldOfView","FieldOfViewX","FieldOfViewY","NearPlane","FarPlane","AspectWidth","AspectHeight","FilmAspectRatio","FocalLength","FilmWidth","FilmHeight","ApertureWidth","ApertureHeight","CameraProjectionType","ProjectionType","OrthoZoom","Roll","ApertureMode"]),Ct=new Set(["LightType","Color","Intensity","InnerAngle","OuterAngle","ConeAngle","DecayType","DecayStart","EnableNearAttenuation","EnableFarAttenuation","CastShadow","Shadow"]);function Rt(e){if("number"==typeof e)return e}function Ot(e){return"boolean"==typeof e?e:"number"==typeof e?0!==e:void 0}function St(e,t){const n=Rt(ye(e,t,"FilmAspectRatio"));if(void 0!==n&&n>0)return n;const o=Rt(ye(e,t,"AspectWidth")),s=Rt(ye(e,t,"AspectHeight"));return void 0!==o&&void 0!==s&&o>0&&s>0?o/s:0}function Ft(e,t,n,o,s){var r;const i=null!==(r=Rt(ye(e,t,"FieldOfViewY")))&&void 0!==r?r:Rt(ye(e,t,"FieldOfView"));if(void 0!==i)return i;const a=Rt(ye(e,t,"FieldOfViewX"));return void 0!==a?n>0?Lt(2*Math.atan(Math.tan(a*Math.PI/180/2)/n)):a:void 0!==o&&o>0&&void 0!==s&&s>0?Lt(2*Math.atan(25.4*s/(2*o))):45}function Et(e,t){var n;const o=new Set;for(const s of["Properties70","Properties60"]){const r=X(e,s);for(const e of null!==(n=null==r?void 0:r.children)&&void 0!==n?n:[]){if("P"!==e.name&&"Property"!==e.name)continue;const n=Q(e,0);n&&!t.has(n)&&o.add(n)}}return Array.from(o).sort()}function Lt(e){return 180*e/Math.PI}function It(e,n,o){const s=t.Matrix.RotationX(e),r=t.Matrix.RotationY(n),i=t.Matrix.RotationZ(o);return s.multiply(r).multiply(i)}function Nt(e,n,o,s){const r=t.Matrix.RotationX(e),i=t.Matrix.RotationY(n),a=t.Matrix.RotationZ(o);switch(s){case 0:default:return r.multiply(i).multiply(a);case 1:return r.multiply(a).multiply(i);case 2:return i.multiply(a).multiply(r);case 3:return i.multiply(r).multiply(a);case 4:return a.multiply(r).multiply(i);case 5:return a.multiply(i).multiply(r)}}function Pt(e,n){const o=Math.PI/180,s=t.Matrix.Scaling(n[0],n[1],n[2]),r=It(e[0]*o,e[1]*o,e[2]*o);return s.multiply(r)}const Bt={name:"fbx",extensions:{".fbx":{isBinary:!0}}};class kt{constructor(e={}){var t;this.name=Bt.name,this.extensions=Bt.extensions,this._bindRestBones=new WeakSet,this._sourceBonesBySkeleton=new WeakMap,this._scaleCompensationHelpersBySkeleton=new WeakMap,this._options={normalMapCoordinateSystem:null!==(t=e.normalMapCoordinateSystem)&&void 0!==t?t:"y-up"}}createPlugin(e){return new kt(e[Bt.name])}importMeshAsync(e,t,n,o,s,r){return b(this,void 0,void 0,function*(){const s=Tt(this._parse(n));return this._buildScene(s,t,o,e)})}loadAsync(e,t,n,o,s){return b(this,void 0,void 0,function*(){const o=Tt(this._parse(t));this._buildScene(o,e,n,null)})}loadAssetContainerAsync(e,n,o,s,r){return b(this,void 0,void 0,function*(){const s=Tt(this._parse(n)),r=new t.AssetContainer(e),i=this._buildScene(s,e,o,null);for(const e of i.meshes)r.meshes.push(e);for(const e of i.skeletons)r.skeletons.push(e);for(const e of i.animationGroups)r.animationGroups.push(e);for(const e of i.transformNodes)r.transformNodes.push(e);for(const e of i.lights)r.lights.push(e);for(const e of i.cameras)r.cameras.push(e);for(const e of i.materials)this._addMaterialToContainer(e,r);for(const e of i.textures)this._addTextureToContainer(e,r);for(const e of i.meshes)this._addMaterialToContainer(e.material,r);return this._setAssetContainer(r),r.removeAllFromScene(),r})}_parse(e){if(e instanceof ArrayBuffer)return this._parseFromArrayBuffer(e);if(ArrayBuffer.isView(e)){const t=e,n=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);return this._parseFromArrayBuffer(n)}if("string"==typeof e)return U(e);throw new Error("FBXFileLoader: unsupported data type")}_parseFromArrayBuffer(e){const t=new Uint8Array(e,0,Math.min(21,e.byteLength));if(String.fromCharCode(...t).startsWith("Kaydara FBX Binary"))return function(e){const t=new DataView(e),n=new Uint8Array(e);if("Kaydara FBX Binary \0"!==K(n,0,21))throw new Error("Not a valid binary FBX file");if(e.byteLength<27)throw new Error("Truncated binary FBX header");const o=t.getUint32(23,!0),s=o>=7500,r=[];let i=27;for(;i<e.byteLength;){const o=B(t,n,i,s,e.byteLength);if(null===o)break;r.push(o.node),i=o.endOffset}return{version:o,nodes:r}}(e);const n=new TextDecoder("utf-8").decode(e);if(n.trimStart().startsWith("; FBX"))return U(n);throw new Error("FBXFileLoader: unrecognized FBX format")}_buildScene(e,n,o,s){var r;const i=this._buildNameFilter(s),a=new Map;for(const t of e.materials){const e=this._createMaterial(t,n,o);a.set(t.id,e)}const l=[],u=new Map,c=new Map,d=new Map,h=new Map,m=new Map;for(const t of e.skins)m.set(t.id,t);for(const t of e.rigs){const e=this._createSkeleton(t.id,t.bones,n);l.push(e),u.set(t.id,e);for(const n of t.skinBindings){const t=m.get(n.skinId);t&&(c.set(n.geometryId,e),d.set(n.geometryId,t),h.set(n.geometryId,n))}}const f=new Map,p=e=>{for(const t of e)f.set(t.id,t),p(t.children)};p(e.rootModels);const _=kt._collectCullingConflictMaterialIds(e.rootModels),g=new Map,y=new t.TransformNode("__fbx_root__",n);n.useRightHandedSystem||(y.rotation.y=Math.PI,y.scaling.z=-1);const v=[],b=[y];let x=y;const T=kt._computeFBXAxisConversionMatrix(e);T.equals(t.Matrix.Identity())||(x=new t.TransformNode("__fbx_axis_conversion__",n),x.parent=y,kt._applyMatrixToTransform(x,T),b.push(x));const A=new Map,M=t.Matrix.Identity();for(const t of e.rootModels)this._buildModel(t,n,x,x,M,a,i,v,b,c,d,h,A,_,g);for(const n of e.rigs){const e=u.get(n.id);if(!e)continue;const o=new Set(n.bones.map(e=>e.modelId)),s=null!==(r=v.find(t=>t.skeleton===e))&&void 0!==r?r:null,i=null!=s?s:y;for(const r of n.bones){if(!r.isCluster)continue;const n=A.get(r.modelId),a=this._getSourceBone(e,r.index);if(n&&a)for(const r of[...n.getChildren()]){const n=r;let l=!1;for(const[e,t]of Array.from(A))if(t===n&&o.has(e)){l=!0;break}if(!l){const o=n.computeWorldMatrix(!0).clone(),r=kt._getBoneReferenceWorldMatrix(e,a,i,s),l=new t.Matrix;r.invertToRef(l);const u=o.multiply(l);n.parent=null,n.attachToBone(a,i),kt._applyMatrixToTransform(n,u)}}}}e.blendShapes.length>0&&this._applyBlendShapes(e.blendShapes,v,n);const w=[];for(const t of e.animations){const o=this._createAnimationGroup(t,e.rigs,u,n,A,f,v);o&&w.push(o)}const C=[];for(const t of e.cameras){const e=this._createCamera(t,A,n);e&&C.push(e)}const R=[];for(const t of e.lights){const e=this._createLight(t,A,n);e&&R.push(e)}return{meshes:v,particleSystems:[],skeletons:l,animationGroups:w,transformNodes:b,geometries:[],lights:R,spriteManagers:[],materials:Array.from(a.values()),textures:Array.from(new Set(Array.from(a.values()).flatMap(e=>e.getActiveTextures()))),cameras:C}}_addMaterialToContainer(e,n){if(e){if(e instanceof t.MultiMaterial){n.multiMaterials.includes(e)||n.multiMaterials.push(e);for(const t of e.subMaterials)this._addMaterialToContainer(t,n)}else n.materials.includes(e)||n.materials.push(e);for(const t of e.getActiveTextures())this._addTextureToContainer(t,n)}}_addTextureToContainer(e,t){t.textures.includes(e)||t.textures.push(e)}_setAssetContainer(e){for(const t of e.meshes)t._parentContainer=e;for(const t of e.transformNodes)t._parentContainer=e;for(const t of e.skeletons)t._parentContainer=e;for(const t of e.animationGroups)t._parentContainer=e;for(const t of e.lights)t._parentContainer=e;for(const t of e.cameras)t._parentContainer=e;for(const t of e.materials)t._parentContainer=e;for(const t of e.multiMaterials)t._parentContainer=e;for(const t of e.textures)t._parentContainer=e}static _computeFBXAxisConversionMatrix(e){const n=[[0,0,0],[0,0,0],[0,0,0]],o=(e,t,o)=>{if(e<0||e>2)return;const s=[0,0,0];s[o]=t>=0?1:-1,n[e]=s};return o(e.coordAxis,e.coordAxisSign,0),o(e.upAxis,e.upAxisSign,1),o(e.frontAxis,e.frontAxisSign,2),n.some(e=>e.every(e=>0===e))?t.Matrix.Identity():t.Matrix.FromValues(n[0][0],n[0][1],n[0][2],0,n[1][0],n[1][1],n[1][2],0,n[2][0],n[2][1],n[2][2],0,0,0,0,1)}_buildModel(e,n,o,s,r,i,a,l,u,c,d,h,m,f,p){var _,g;const y=kt._computeFBXModelLocalMatrix(e).multiply(r);if(!e.geometry||"Mesh"!==e.subType||a&&!a(e.name)){if(e.geometry&&"Mesh"===e.subType&&a&&!kt._modelSubtreeMatchesNameFilter(e,a))return;const r=new t.TransformNode(e.name,n);o&&(r.parent=o),kt._applyFBXTransform(r,e),u.push(r),m.set(e.id,r),kt._applyModelMetadata(r,e);for(const t of e.children)this._buildModel(t,n,r,s,y,i,a,l,u,c,d,h,m,f,p)}else{const r=c.get(e.geometry.id),v=d.get(e.geometry.id),b=h.get(e.geometry.id);r&&v&&(r.needInitialSkinMatrix=!0);const x=this._createMesh(e,e.geometry,n,r,v,b);if(r&&v){const e=v.meshBindPoseMatrix?t.Matrix.FromArray(v.meshBindPoseMatrix):y;x.parent=s,kt._applyMatrixToTransform(x,e),x.computeWorldMatrix(!0),x.updatePoseMatrix(t.Matrix.Invert(e)),x.alwaysSelectAsActiveMesh=!0}else o&&(x.parent=o),kt._applyFBXTransform(x,e);if(e.materials.length>1&&(null===(_=e.geometry)||void 0===_?void 0:_.materialIndices))this._applyMultiMaterial(x,e,i,n,f,p);else if(e.materials.length>0){const t=i.get(e.materials[0].id);t&&(x.material=kt._getModelMaterial(t,e,p,f.has(e.materials[0].id)))}(null===(g=e.geometry)||void 0===g?void 0:g.colors)&&this._useUnmodulatedVertexColorMaterials(x,n),this._applyMaterialUVSetCoordinates(x.material,e.geometry),l.push(x),m.set(e.id,x),kt._applyModelMetadata(x,e);for(const t of e.children)this._buildModel(t,n,x,s,y,i,a,l,u,c,d,h,m,f,p)}}static _modelSubtreeMatchesNameFilter(e,t){for(const n of e.children){if(n.geometry&&"Mesh"===n.subType&&t(n.name))return!0;if(kt._modelSubtreeMatchesNameFilter(n,t))return!0}return!1}static _applyModelMetadata(e,t){var n;(t.customProperties||0!==t.diagnostics.length)&&(e.metadata=Object.assign(Object.assign(Object.assign({},null!==(n=e.metadata)&&void 0!==n?n:{}),t.customProperties?{fbxCustomProperties:t.customProperties}:{}),t.diagnostics.length>0?{fbxDiagnostics:t.diagnostics}:{}))}_createMesh(e,n,o,s,r,i){var a;const l=new t.Mesh(e.name,o);l.sideOrientation=o.useRightHandedSystem?t.Material.CounterClockWiseSideOrientation:t.Material.ClockWiseSideOrientation;const u=new t.VertexData,c=Dt(n.positions),d=e.geometricTranslation,h=e.geometricRotation,m=e.geometricScaling,f=kt._computeFBXGeometricMatrix(d,h,m),p=kt._computeFBXGeometricDeltaMatrix(h,m),_=kt._computeFBXGeometricNormalMatrix(h,m),g=!f.equals(t.Matrix.Identity()),y=!p.equals(t.Matrix.Identity()),v=!_.equals(t.Matrix.Identity());if(g)for(let e=0;e<c.length;e+=3){const n=t.Vector3.TransformCoordinates(new t.Vector3(c[e],c[e+1],c[e+2]),f);c[e]=n.x,c[e+1]=n.y,c[e+2]=n.z}let b;if(u.positions=c,u.indices=Array.from(n.indices),n.normals){if(b=Dt(n.normals),v)for(let e=0;e<b.length;e+=3){const n=t.Vector3.TransformNormal(new t.Vector3(b[e],b[e+1],b[e+2]),_);n.lengthSquared()>0&&n.normalize(),b[e]=n.x,b[e+1]=n.y,b[e+2]=n.z}u.normals=b}if(n.uvs&&(u.uvs=Dt(n.uvs)),n.uvSets.length>1&&(u.uvs2=Dt(n.uvSets[1].data)),n.uvSets.length>2&&(u.uvs3=Dt(n.uvSets[2].data)),n.uvSets.length>3&&(u.uvs4=Dt(n.uvSets[3].data)),n.uvSets.length>4&&(u.uvs5=Dt(n.uvSets[4].data)),n.uvSets.length>5&&(u.uvs6=Dt(n.uvSets[5].data)),n.tangents){const e=Dt(n.tangents);if(v)for(let n=0;n<e.length;n+=4){const o=t.Vector3.TransformNormal(new t.Vector3(e[n],e[n+1],e[n+2]),_);o.lengthSquared()>0&&o.normalize(),e[n]=o.x,e[n+1]=o.y,e[n+2]=o.z}!function(e,t){if(1!==t)for(let n=3;n<e.length;n+=4)e[n]*=t}(e,this._getNormalMapTangentHandednessScale()),u.tangents=e}else b&&u.uvs&&(u.tangents=function(e,t,n,o,s=1,r=null,i=null){var a,l,u,c,d,h;const m=e.length/3,f=new Map,p=new Array(m).fill(null);for(let s=0;s+2<o.length;s+=3){const a=i?i[s/3]:0,l=o[s],u=o[s+1],c=o[s+2],d=3*l,h=3*u,m=3*c,_=2*l,g=2*u,y=2*c,v=e[h]-e[d],b=e[m]-e[d],x=e[h+1]-e[d+1],T=e[m+1]-e[d+1],A=e[h+2]-e[d+2],M=e[m+2]-e[d+2],w=n[g]-n[_],C=n[y]-n[_],R=n[g+1]-n[_+1],O=n[y+1]-n[_+1],S=w*O-C*R;if(Math.abs(S)<1e-8)continue;const F=1/S,E=(O*v-R*b)*F,L=(O*x-R*T)*F,I=(O*A-R*M)*F,N=(w*b-C*v)*F,P=(w*T-C*x)*F,B=(w*M-C*A)*F;Gt(l,u,c,E,L,I,N,P,B,e,t,n,r,a,f,p),Gt(u,c,l,E,L,I,N,P,B,e,t,n,r,a,f,p),Gt(c,l,u,E,L,I,N,P,B,e,t,n,r,a,f,p)}const _=new Float32Array(4*m);for(let e=0;e<m;e++){const n=3*e,o=4*e,[r,i,m]=Vt(t[n],t[n+1],t[n+2]),g=p[e]?f.get(p[e]):void 0,y=null!==(a=null==g?void 0:g.tx)&&void 0!==a?a:0,v=null!==(l=null==g?void 0:g.ty)&&void 0!==l?l:0,b=null!==(u=null==g?void 0:g.tz)&&void 0!==u?u:0,x=r*y+i*v+m*b;let T=y-r*x,A=v-i*x,M=b-m*x;const w=Math.hypot(T,A,M);w>1e-8?(T/=w,A/=w,M/=w):[T,A,M]=Kt(r,i,m);const C=null!==(c=null==g?void 0:g.bx)&&void 0!==c?c:0,R=null!==(d=null==g?void 0:g.by)&&void 0!==d?d:0,O=null!==(h=null==g?void 0:g.bz)&&void 0!==h?h:0,S=i*M-m*A,F=m*T-r*M,E=r*A-i*T,L=Math.hypot(C,R,O)>1e-8&&S*C+F*R+E*O<0?-1:1;_[o]=T,_[o+1]=A,_[o+2]=M,_[o+3]=L*s}return _}(c,b,u.uvs,n.indices,this._getNormalMapTangentHandednessScale(),n.controlPointIndices,n.materialIndices));if(n.colors){const e=new Float32Array(n.colors.length);for(let t=0;t<e.length;t+=4)e[t]=n.colors[t],e[t+1]=n.colors[t+1],e[t+2]=n.colors[t+2],e[t+3]=1;u.colors=e,l.hasVertexAlpha=!1}if(s&&r){const{matricesIndices:e,matricesWeights:t,matricesIndicesExtra:o,matricesWeightsExtra:s,numBoneInfluencers:a}=this._buildSkinningData(n,r,i);u.matricesIndices=e,u.matricesWeights=t,o&&s&&(u.matricesIndicesExtra=o,u.matricesWeightsExtra=s),l.numBoneInfluencers=a}return u.applyToMesh(l),l.metadata=Object.assign(Object.assign({},null!==(a=l.metadata)&&void 0!==a?a:{}),{fbxGeometryId:n.id,fbxControlPointIndices:n.controlPointIndices,fbxGeometryDeltaMatrix:y?p:null,fbxGeometryNormalMatrix:v?_:null,fbxPreRotMatrix:y?p:null}),s&&(l.skeleton=s),l}_applyMultiMaterial(e,n,o,s,r,i){const a=n.geometry.materialIndices,l=e.getIndices();if(!l)return;const u=l.length/3,c=new Map;for(let e=0;e<u;e++){const t=e<a.length?a[e]:0;let n=c.get(t);n||(n=[],c.set(t,n)),n.push(e)}const d=Array.from(c.keys()).sort((e,t)=>e-t),h=[],m=[];for(const e of d){const t=c.get(e),n=h.length;for(const e of t)h.push(l[3*e],l[3*e+1],l[3*e+2]);m.push({start:n,count:3*t.length,matIdx:e})}e.setIndices(h);const f=new t.MultiMaterial(n.name+"_multi",s);for(const e of m){const t=n.materials[e.matIdx];if(t){const e=o.get(t.id);e?f.subMaterials.push(kt._getModelMaterial(e,n,i,r.has(t.id))):f.subMaterials.push(null)}else f.subMaterials.push(null)}e.material=f,e.subMeshes=[];const p=e.getTotalVertices();for(let n=0;n<m.length;n++){const o=m[n];new t.SubMesh(n,0,p,o.start,o.count,e)}}static _collectCullingConflictMaterialIds(e){const t=new Map,n=e=>{var o;for(const n of e.materials){const s=null!==(o=t.get(n.id))&&void 0!==o?o:{cullingOff:!1,cullingOn:!1};e.cullingOff?s.cullingOff=!0:s.cullingOn=!0,t.set(n.id,s)}for(const t of e.children)n(t)};for(const t of e)n(t);const o=new Set;for(const[e,n]of Array.from(t))n.cullingOff&&n.cullingOn&&o.add(e);return o}static _getModelMaterial(e,t,n,o=!0){if(!t.cullingOff||!e.backFaceCulling)return e;if(!o)return e.backFaceCulling=!1,e;const s=null==n?void 0:n.get(e);if(s)return s;const r=e.clone(`${e.name}_CullingOff`);return r.backFaceCulling=!1,null==n||n.set(e,r),r}_applyMaterialUVSetCoordinates(e,n){if(e)if(e instanceof t.MultiMaterial)for(const o of e.subMaterials)o instanceof t.StandardMaterial&&this._applyStandardMaterialUVSetCoordinates(o,n);else e instanceof t.StandardMaterial&&this._applyStandardMaterialUVSetCoordinates(e,n)}_applyStandardMaterialUVSetCoordinates(e,t){var n;for(const o of[e.diffuseTexture,e.bumpTexture,e.emissiveTexture,e.ambientTexture,e.specularTexture,e.opacityTexture,e.reflectionTexture]){if(!o)continue;const e=null===(n=o.metadata)||void 0===n?void 0:n.fbxUVSetName;if(!e)continue;const s=t.uvSets.findIndex(t=>t.name===e);s>=0&&(o.coordinatesIndex=s)}}_useUnmodulatedVertexColorMaterials(e,n){const o=e.material;if(o)if(o instanceof t.StandardMaterial){if(!o.diffuseTexture){const n=o.clone(`${o.name}_VertexColor`);n.diffuseColor=new t.Color3(1,1,1),e.material=n}}else if(o instanceof t.MultiMaterial){const s=new t.MultiMaterial(`${o.name}_VertexColor`,n);s.subMaterials=o.subMaterials.map(e=>{if(e instanceof t.StandardMaterial&&!e.diffuseTexture){const n=e.clone(`${e.name}_VertexColor`);return n.diffuseColor=new t.Color3(1,1,1),n}return e}),e.material=s}}_buildSkinningData(e,t,n){var o,s,r;const i=e.positions.length/3,a=new Float32Array(4*i),l=new Float32Array(4*i);let u=null,c=null,d=0;if(e.controlPointIndices){for(let n=0;n<i;n++){const s=e.controlPointIndices[n],r=null!==(o=t.boneIndices[s])&&void 0!==o?o:[];d=Math.max(d,Math.min(r.length,8))}d>4&&(u=new Float32Array(4*i),c=new Float32Array(4*i));for(let o=0;o<i;o++){const i=e.controlPointIndices[o],d=null!==(s=t.boneIndices[i])&&void 0!==s?s:[],h=null!==(r=t.boneWeights[i])&&void 0!==r?r:[];for(let e=0;e<8;e++){const t=e<4?a:u,s=e<4?l:c;if(!t||!s)continue;const r=4*o+e%4;if(e<d.length){const o=d[e],s=n?n.skinBoneIndexToRigBoneIndex[o]:o;if(void 0===s||s<0)throw new Error(`FBXFileLoader: missing rig bone mapping for skin bone index ${o}`);t[r]=s}else t[r]=0;s[r]=e<h.length?h[e]:0}}}return{matricesIndices:a,matricesWeights:l,matricesIndicesExtra:u,matricesWeightsExtra:c,numBoneInfluencers:Math.max(d,1)}}_createMaterial(e,n,o){var s,r,i,a,l;const u=new t.StandardMaterial(e.name,n),c=e.properties,d=(...t)=>e.textures.some(e=>t.includes(e.propertyName));if("Lambert"===e.type&&(u.specularColor=t.Color3.Black()),c.diffuseColor){const e=d("DiffuseColor","Diffuse")?1:null!==(s=c.diffuseFactor)&&void 0!==s?s:1;u.diffuseColor=new t.Color3(c.diffuseColor[0]*e,c.diffuseColor[1]*e,c.diffuseColor[2]*e)}if(c.ambientColor){const e=d("AmbientColor","Ambient")?1:null!==(r=c.ambientFactor)&&void 0!==r?r:1;u.ambientColor=new t.Color3(c.ambientColor[0]*e,c.ambientColor[1]*e,c.ambientColor[2]*e)}if("Phong"===e.type&&c.specularColor){const e=d("SpecularColor","Specular","Shininess","ShininessExponent")?1:null!==(i=c.specularFactor)&&void 0!==i?i:1;u.specularColor=new t.Color3(c.specularColor[0]*e,c.specularColor[1]*e,c.specularColor[2]*e)}if(c.emissiveColor){const e=d("EmissiveColor","Emissive")?1:null!==(a=c.emissiveFactor)&&void 0!==a?a:1;u.emissiveColor=new t.Color3(c.emissiveColor[0]*e,c.emissiveColor[1]*e,c.emissiveColor[2]*e)}void 0!==c.opacity?u.alpha=c.opacity:void 0!==c.transparencyFactor&&(u.alpha=1-c.transparencyFactor),u.alpha<1&&(u.transparencyMode=t.Material.MATERIAL_ALPHABLEND),void 0!==c.shininess&&(u.specularPower=c.shininess);for(const s of e.textures){if(!kt._isSupportedMaterialTextureSlot(s.propertyName))continue;const e=kt._createTexture(s,n,o,kt._isNormalMapTextureSlot(s.propertyName));if(e){switch(s.propertyName){case"DiffuseColor":u.diffuseTexture=e,u.diffuseColor=new t.Color3(1,1,1);break;case"NormalMap":case"NormalMapTexture":case"normalCamera":case"Bump":case"BumpFactor":u.bumpTexture=e,this._configureNormalTexture(e,u);break;case"EmissiveColor":u.emissiveTexture=e;break;case"AmbientColor":u.ambientTexture=e;break;case"SpecularColor":u.specularTexture=e;break;case"TransparencyFactor":case"TransparentColor":u.opacityTexture=e,u.transparencyMode=t.Material.MATERIAL_ALPHATESTANDBLEND;break;case"ReflectionColor":case"ReflectionFactor":u.reflectionTexture=e}s.uvTranslation&&(e.uOffset=s.uvTranslation[0],e.vOffset=s.uvTranslation[1]),s.uvScaling&&(e.uScale=s.uvScaling[0],e.vScale=s.uvScaling[1]),void 0!==s.uvRotation&&(e.wAng=s.uvRotation*(Math.PI/180)),void 0!==s.uvSetIndex&&(e.coordinatesIndex=s.uvSetIndex),s.uvSetName&&(e.metadata=Object.assign(Object.assign({},null!==(l=e.metadata)&&void 0!==l?l:{}),{fbxUVSetName:s.uvSetName}))}}return u}_configureNormalTexture(e,t){e.gammaSpace=!1,t.invertNormalMapX=!1,t.invertNormalMapY="y-down"===this._options.normalMapCoordinateSystem}_getNormalMapTangentHandednessScale(){return"y-down"===this._options.normalMapCoordinateSystem?-1:1}static _isSupportedMaterialTextureSlot(e){switch(e){case"DiffuseColor":case"NormalMap":case"NormalMapTexture":case"normalCamera":case"Bump":case"BumpFactor":case"EmissiveColor":case"AmbientColor":case"SpecularColor":case"TransparencyFactor":case"TransparentColor":case"ReflectionColor":case"ReflectionFactor":case"DisplacementColor":case"Displacement":case"DisplacementFactor":case"ShininessExponent":case"Shininess":return!0;default:return!1}}static _isNormalMapTextureSlot(e){switch(e){case"NormalMap":case"NormalMapTexture":case"normalCamera":case"Bump":case"BumpFactor":return!0;default:return!1}}static _createTexture(e,n,o,s){const r=kt._getTextureSourceName(e),i=kt._getTextureCreationOptions(r,s,e.embeddedData);if(e.embeddedData){const o=new t.Texture(null,n,i),s=null!=r?r:`embeddedTexture_${e.id.toString()}`;return o.updateURL(`data:fbx-embedded-texture/${encodeURIComponent(s)}`,new Uint8Array(e.embeddedData),void 0,i.forcedExtension),o.name=s,o}const a=kt._getExternalTextureUrls(e,o),l=a.shift();return l?kt._createExternalTexture(l,a,n,i):null}static _createExternalTexture(e,n,o,s){n.push(...kt._buildTextureFallbackUrls(e));let r=0;const i=new t.Texture(e,o,Object.assign(Object.assign({},s),{onError:()=>{const e=n[r++];e&&i.getScene()&&i.updateURL(e,null,void 0,kt._getForcedExtension(e))}}));return i}static _buildTextureFallbackUrls(e){const t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),n=e.lastIndexOf(".");if(n<=t)return[];const o=e.slice(0,n),s=e.slice(n+1).toLowerCase();return["png","jpg","jpeg","webp","bmp","tga"].filter(e=>e!==s).map(e=>`${o}.${e}`)}static _getTextureCreationOptions(e,t,n){const o=n?e?kt._getMimeType(e):"image/png":void 0;return{buffer:n?new Uint8Array(n):void 0,forcedExtension:e?kt._getForcedExtension(e,o):n?".png":void 0,gammaSpace:!t,mimeType:o}}static _getExternalTextureUrls(e,t){const n=[e.relativeFileName,e.fileName].filter(e=>!!e),o=[];for(const e of n){const n=e.replace(/\\/g,"/");kt._isSafeRelativeTexturePath(n)&&o.push(t+n);const s=kt._getTextureSourceNameFromPath(n);s&&o.push(t+s)}return Array.from(new Set(o))}static _getTextureSourceName(e){const t=e.relativeFileName||e.fileName;if(!t)return null;const n=t.replace(/\\/g,"/");return kt._getTextureSourceNameFromPath(n)}static _getTextureSourceNameFromPath(e){var t;return null!==(t=e.split("/").pop())&&void 0!==t?t:e}static _isSafeRelativeTexturePath(e){return!(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)||e.startsWith("/")||e.startsWith("//")||e.split("/").some(e=>".."===e))}static _getForcedExtension(e,t){const n=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),o=e.lastIndexOf(".");if(o>n)return e.slice(o).toLowerCase();switch(t){case"image/png":return".png";case"image/jpeg":return".jpg";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/gif":return".gif";case"image/x-tga":return".tga";default:return}}static _getMimeType(e){const n=t.GetMimeType(e);if(n)return n;switch(kt._getForcedExtension(e)){case".tga":return"image/x-tga";case".bmp":return"image/bmp";case".gif":return"image/gif";default:return"image/png"}}_applyBlendShapes(e,n,o){var s,r,i,a,l,u,c,d;for(const h of e){const e=n.find(e=>{var t;return(null===(t=e.metadata)||void 0===t?void 0:t.fbxGeometryId)===h.geometryId});if(!e)continue;const m=new t.MorphTargetManager(o);m.optimizeInfluencers=!1;const f=null!==(a=null!==(r=null===(s=e.metadata)||void 0===s?void 0:s.fbxGeometryDeltaMatrix)&&void 0!==r?r:null===(i=e.metadata)||void 0===i?void 0:i.fbxPreRotMatrix)&&void 0!==a?a:null,p=null!==(u=null===(l=e.metadata)||void 0===l?void 0:l.fbxGeometryNormalMatrix)&&void 0!==u?u:f;for(const n of h.channels){const s=null===(c=e.metadata)||void 0===c?void 0:c.fbxControlPointIndices;if(!s)continue;const r=e.getVerticesData("position"),i=e.getVerticesData("normal");if(!r)continue;const a=$t(n.deformPercent,n.fullWeights,n.shapes.length),l=[];for(let e=0;e<n.shapes.length;e++){const u=n.shapes[e];if(!u)continue;const c=Ut(u,s,r,i,f,p);if(!c)continue;const h=n.fullWeights&&n.shapes.length>1?`${n.name}_${n.fullWeights[e]}`:n.name,_=new t.MorphTarget(h,null!==(d=a[e])&&void 0!==d?d:0,o);_.setPositions(c.positions),c.normals&&_.setNormals(c.normals),l.push(m.numTargets),m.addTarget(_)}0!==l.length&&(e.metadata||(e.metadata={}),e.metadata.fbxBlendShapeChannelIds||(e.metadata.fbxBlendShapeChannelIds=new Map),e.metadata.fbxBlendShapeChannelIds.set(n.id,l[0]),e.metadata.fbxBlendShapeChannelTargets||(e.metadata.fbxBlendShapeChannelTargets=new Map),e.metadata.fbxBlendShapeChannelTargets.set(n.id,{targetIndices:l,fullWeights:n.fullWeights}))}m.numTargets>0&&(m.numMaxInfluencers=m.numTargets,e.morphTargetManager=m)}}_createCamera(e,n,o){var s;const r=n.get(e.modelId),i=r?r.computeWorldMatrix(!0):t.Matrix.Identity(),a=t.Vector3.TransformCoordinates(t.Vector3.Zero(),i),l=new t.FreeCamera(e.name,a,o);if(l.fov=e.fieldOfView*(Math.PI/180),l.minZ=e.nearPlane,l.maxZ=e.farPlane,l.metadata=Object.assign(Object.assign({},null!==(s=l.metadata)&&void 0!==s?s:{}),{fbxCamera:{projectionType:e.projectionType,focalLength:e.focalLength,filmWidth:e.filmWidth,filmHeight:e.filmHeight,orthoZoom:e.orthoZoom,roll:e.roll,aspectRatio:e.aspectRatio,unknownProperties:e.unknownProperties,diagnostics:e.diagnostics}}),"orthographic"===e.projectionType){const n=e.orthoZoom&&e.orthoZoom>0?e.orthoZoom:1,o=e.aspectRatio>0?e.aspectRatio:1;l.mode=t.Camera.ORTHOGRAPHIC_CAMERA,l.orthoTop=n/2,l.orthoBottom=-n/2,l.orthoRight=n*o/2,l.orthoLeft=-n*o/2}const u=t.Vector3.TransformCoordinates(new t.Vector3(1,0,0),i);return l.setTarget(u),l}_createLight(e,n,o){var s;const r=n.get(e.modelId),i=r?r.computeWorldMatrix(!0):t.Matrix.Identity(),a=t.Vector3.TransformCoordinates(t.Vector3.Zero(),i),l=new t.Color3(e.color[0],e.color[1],e.color[2]),u=t.Vector3.TransformCoordinates(new t.Vector3(0,0,-1),i).subtract(a).normalize();let c;switch(e.lightType){case 1:c=new t.DirectionalLight(e.name,u,o),c.diffuse=l,c.intensity=e.intensity;break;case 2:{const n=e.coneAngle*(Math.PI/180);c=new t.SpotLight(e.name,a,u,n,2,o),c.diffuse=l,c.intensity=e.intensity;break}default:c=new t.PointLight(e.name,a,o),c.diffuse=l,c.intensity=e.intensity}return c.metadata=Object.assign(Object.assign({},null!==(s=c.metadata)&&void 0!==s?s:{}),{fbxLight:{lightType:e.lightType,decayType:e.decayType,decayStart:e.decayStart,innerAngle:e.innerAngle,outerAngle:e.outerAngle,enableNearAttenuation:e.enableNearAttenuation,enableFarAttenuation:e.enableFarAttenuation,castShadows:e.castShadows,unknownProperties:e.unknownProperties,diagnostics:e.diagnostics}}),c}_createSkeleton(e,n,o){var s;const r=new t.Skeleton("Skeleton",`skeleton_${e}`,o),i=[],a=new Map,l=[],u=[],c=[];for(let e=0;e<n.length;e++){const t=n[e],o=kt._computeFBXLocalMatrix(t.translation,t.rotation,t.scale,t.preRotation,t.postRotation,t.rotationPivot,t.scalingPivot,t.rotationOffset,t.scalingOffset,t.rotationOrder);l[e]=o,c[e]=kt._computeFBXRuntimeLocalMatrix(n,o,e)}u.push(...kt._computeFBXAbsoluteMatrices(n,c));const d=n.map((e,n)=>e.transformLinkMatrix?t.Matrix.FromArray(e.transformLinkMatrix):e.modelBindPoseMatrix?t.Matrix.FromArray(e.modelBindPoseMatrix):u[n]),h=d.map((e,o)=>{const s=n[o].parentIndex;if(s<0)return e;const r=new t.Matrix;return d[s].invertToRef(r),e.multiply(r)}),m=kt._shouldUseBindMatricesAsRest(n,l,h);for(let e=0;e<n.length;e++){let o=m?h[e]:c[e],u=n[e].parentIndex>=0?i[n[e].parentIndex]:null;if(!m&&2===n[e].inheritType&&n[e].parentIndex>=0&&u){const i=kt._splitParentScaleCompensatedLocalMatrix(l[e],n[n[e].parentIndex].scale),c=new t.Bone(`${n[e].name}__fbx_scaleCompensation`,r,u,i.helperLocalMatrix,i.helperLocalMatrix.clone(),t.Matrix.Identity(),-1);c.metadata=Object.assign(Object.assign({},null!==(s=c.metadata)&&void 0!==s?s:{}),{fbxScaleCompensationForBoneIndex:e,fbxScaleCompensationForBoneName:n[e].name}),a.set(e,c),u=c,o=i.boneLocalMatrix}const d=new t.Bone(n[e].name,r,u,o,m?o.clone():null,m?o.clone():null,e);m&&n[e].isCluster&&kt._getMaxScaleRatio(l[e],h[e])>=10&&this._bindRestBones.add(d),i.push(d)}if(this._sourceBonesBySkeleton.set(r,i),this._scaleCompensationHelpersBySkeleton.set(r,a),!m){for(let e=0;e<n.length;e++)i[e].updateMatrix(h[e],!1,!1);for(const e of Array.from(a.values()))e.updateMatrix(t.Matrix.Identity(),!1,!1);for(const e of r.bones)e.getParent()||e._updateAbsoluteBindMatrices(void 0,!0)}return r}_getSourceBone(e,t){var n,o;return null!==(o=null===(n=this._sourceBonesBySkeleton.get(e))||void 0===n?void 0:n[t])&&void 0!==o?o:e.bones[t]}_getScaleCompensationHelper(e,t){var n;return null===(n=this._scaleCompensationHelpersBySkeleton.get(e))||void 0===n?void 0:n.get(t)}static _computeFBXAbsoluteMatrices(e,t){const n=[];for(let o=0;o<e.length;o++){const s=e[o].parentIndex;n[o]=s<0?t[o].clone():t[o].multiply(n[s])}return n}static _computeFBXRuntimeLocalMatrix(e,t,n,o){const s=e[n].parentIndex;if(2!==e[n].inheritType||s<0)return t;const r=null!=o?o:e[s].scale;return kt._applyParentScaleCompensation(t,r)}static _applyParentScaleCompensation(e,t){const n=kt._splitParentScaleCompensatedLocalMatrix(e,t);return n.boneLocalMatrix.multiply(n.helperLocalMatrix)}static _splitParentScaleCompensatedLocalMatrix(e,n){const o=e.getTranslation(),s=e.clone();return s.setTranslation(t.Vector3.Zero()),{boneLocalMatrix:s,helperLocalMatrix:t.Matrix.Compose(kt._getInverseScaleVector(n),t.Quaternion.Identity(),o)}}static _safeInverseScale(e){return Math.abs(e)>1e-8?1/e:1}static _getInverseScaleVector(e){return new t.Vector3(kt._safeInverseScale(e[0]),kt._safeInverseScale(e[1]),kt._safeInverseScale(e[2]))}static _shouldUseBindMatricesAsRest(e,t,n){return e.some((e,o)=>!!e.isCluster&&kt._getMaxScaleRatio(t[o],n[o])>=10)}static _getMaxScaleRatio(e,n){const o=new t.Vector3,s=new t.Quaternion,r=new t.Vector3,i=new t.Vector3,a=new t.Quaternion,l=new t.Vector3;return e.decompose(o,s,r),n.decompose(i,a,l),Math.max(kt._getScaleRatio(o.x,i.x),kt._getScaleRatio(o.y,i.y),kt._getScaleRatio(o.z,i.z))}static _getScaleRatio(e,t){const n=Math.abs(e),o=Math.abs(t);return n<1e-6||o<1e-6?n<1e-6&&o<1e-6?1:Number.POSITIVE_INFINITY:Math.max(n/o,o/n)}static _computeFBXGeometricMatrix(e,n,o){return function(e,n,o){const s=t.Matrix.Translation(e[0],e[1],e[2]);return Pt(n,o).multiply(s)}(e,n,o)}static _computeFBXGeometricDeltaMatrix(e,t){return Pt(e,t)}static _computeFBXGeometricNormalMatrix(e,n){return function(e,n){const o=Math.PI/180,s=t.Matrix.Scaling(0===n[0]?0:1/n[0],0===n[1]?0:1/n[1],0===n[2]?0:1/n[2]),r=It(e[0]*o,e[1]*o,e[2]*o);return s.multiply(r)}(e,n)}static _computeFBXLocalMatrix(e,n,o,s,r,i,a,l,u,c=0){return function(e){const{translation:n,rotation:o,scale:s,preRotation:r,postRotation:i,rotationPivot:a,scalingPivot:l,rotationOffset:u,scalingOffset:c,rotationOrder:d}=e,h=Math.PI/180,m=0!==a[0]||0!==a[1]||0!==a[2]||0!==l[0]||0!==l[1]||0!==l[2],f=0!==u[0]||0!==u[1]||0!==u[2]||0!==c[0]||0!==c[1]||0!==c[2],p=0!==i[0]||0!==i[1]||0!==i[2];if(!m&&!f&&!p){const e=It(r[0]*h,r[1]*h,r[2]*h),i=Nt(o[0]*h,o[1]*h,o[2]*h,d),a=t.Matrix.Translation(n[0],n[1],n[2]),l=i.multiply(e);return t.Matrix.Scaling(s[0],s[1],s[2]).multiply(l).multiply(a)}const _=t.Matrix.Translation(n[0],n[1],n[2]),g=t.Matrix.Translation(u[0],u[1],u[2]),y=t.Matrix.Translation(a[0],a[1],a[2]),v=t.Matrix.Translation(-a[0],-a[1],-a[2]),b=t.Matrix.Translation(c[0],c[1],c[2]),x=t.Matrix.Translation(l[0],l[1],l[2]),T=t.Matrix.Translation(-l[0],-l[1],-l[2]),A=It(r[0]*h,r[1]*h,r[2]*h),M=Nt(o[0]*h,o[1]*h,o[2]*h,d),w=t.Matrix.Scaling(s[0],s[1],s[2]);let C;if(p){const e=It(i[0]*h,i[1]*h,i[2]*h);C=new t.Matrix,e.invertToRef(C)}else C=t.Matrix.Identity();let R=T;return R=R.multiply(w),R=R.multiply(x),R=R.multiply(b),R=R.multiply(v),R=R.multiply(C),R=R.multiply(M),R=R.multiply(A),R=R.multiply(y),R=R.multiply(g),R=R.multiply(_),R}({translation:e,rotation:n,scale:o,preRotation:s,postRotation:r,rotationPivot:i,scalingPivot:a,rotationOffset:l,scalingOffset:u,rotationOrder:c})}static _applyFBXTransform(e,n){const o=kt._computeFBXModelLocalMatrix(n),s=new t.Vector3,r=new t.Quaternion,i=new t.Vector3;o.decompose(s,r,i),e.position=i,e.rotationQuaternion=r,e.scaling=s}static _computeFBXModelLocalMatrix(e){return kt._computeFBXLocalMatrix(e.translation,e.rotation,e.scale,e.preRotation,e.postRotation,e.rotationPivot,e.scalingPivot,e.rotationOffset,e.scalingOffset,e.rotationOrder)}static _getBoneReferenceWorldMatrix(e,t,n,o){return o?e.getTransformMatrices(o):e.prepare(!0),n.computeWorldMatrix(!0),t.getFinalMatrix().multiply(n.getWorldMatrix())}static _applyMatrixToTransform(e,n){const o=new t.Vector3,s=new t.Quaternion,r=new t.Vector3;n.decompose(o,s,r),e.position=r,e.rotationQuaternion=s,e.scaling=o}_createAnimationGroup(e,n,o,s,r,i,a){if(0===e.curveNodes.length)return null;const l=new t.AnimationGroup(e.name,s),u=new Map;for(const e of n){const t=o.get(e.id);if(t)for(const n of e.bones){const e=this._getSourceBone(t,n.index);if(!e)continue;const o=u.get(n.modelId);o?o.push(e):u.set(n.modelId,[e])}}const c=new Map,d=new Map,h=[];for(const t of e.curveNodes)"DeformPercent"!==t.type?u.has(t.targetModelId)?(c.has(t.targetModelId)||c.set(t.targetModelId,[]),c.get(t.targetModelId).push(t)):(d.has(t.targetModelId)||d.set(t.targetModelId,[]),d.get(t.targetModelId).push(t)):h.push(t);const m=new Set;for(const t of n){const n=new Set(t.bones.filter(e=>2===e.inheritType).map(e=>e.modelId));if(0===n.size)continue;const s=o.get(t.id);if(s&&!s.bones.some(e=>this._bindRestBones.has(e))){for(const e of Array.from(n))m.add(e);for(const{bone:o,animations:r}of this._buildInheritedRigBoneAnimations(t,s,c,i,n,e.startTime,e.stopTime))for(const e of r)l.addTargetedAnimation(e,o)}}for(const[t,n]of Array.from(c)){if(m.has(t))continue;const o=u.get(t),s=i.get(t);if(o&&0!==o.length&&s)for(const t of o){const o=this._buildBoneAnimations(n,t.name,s,e.startTime,e.stopTime,this._bindRestBones.has(t)?t.getBindMatrix():void 0);for(const e of o)l.addTargetedAnimation(e,t)}}for(const[t,n]of Array.from(d)){const o=r.get(t);if(!o)continue;const s=i.get(t);if(!s)continue;const a=this._buildNodeAnimations(n,o.name,s,e.startTime,e.stopTime);for(const e of a)l.addTargetedAnimation(e,o)}for(const n of h){const o=n.targetModelId;let s=!1;for(const r of a){if(!r.morphTargetManager||s)continue;const i=r.metadata,a=null==i?void 0:i.fbxBlendShapeChannelTargets,u=null==a?void 0:a.get(o);if(u&&n.curves.length>0){const o=30;for(let s=0;s<u.targetIndices.length;s++){const i=r.morphTargetManager.getTarget(u.targetIndices[s]);if(!i)continue;const a=new t.Animation(`${i.name}_influence`,"influence",o,t.Animation.ANIMATIONTYPE_FLOAT,t.Animation.ANIMATIONLOOPMODE_CYCLE),c=qt(n.curves[0],o,e.startTime,e.stopTime,e=>{var t;return null!==(t=$t(e,u.fullWeights,u.targetIndices.length)[s])&&void 0!==t?t:0});a.setKeys(c),l.addTargetedAnimation(a,i)}s=!0;continue}const c=null==i?void 0:i.fbxBlendShapeChannelIds;if(!c)continue;const d=c.get(o);if(void 0===d)continue;const h=r.morphTargetManager.getTarget(d);if(h&&n.curves.length>0){const o=30,r=new t.Animation(`${h.name}_influence`,"influence",o,t.Animation.ANIMATIONTYPE_FLOAT,t.Animation.ANIMATIONLOOPMODE_CYCLE),i=qt(n.curves[0],o,e.startTime,e.stopTime,e=>e/100);r.setKeys(i),l.addTargetedAnimation(r,h),s=!0}}}return l.targetedAnimations.length>0?(l.normalize(30*e.startTime,30*e.stopTime),l):(l.dispose(),null)}_buildInheritedRigBoneAnimations(e,n,o,s,r,i,a){const l=30,u=new Set;for(let t=0;t<e.bones.length;t++)if(r.has(e.bones[t].modelId))for(let n=t;n>=0;n=e.bones[n].parentIndex)u.add(e.bones[n].modelId);const c=zt(e.bones.filter(e=>u.has(e.modelId)).flatMap(e=>{var t;return null!==(t=o.get(e.modelId))&&void 0!==t?t:[]}),l,i,a);if(0===c.length)return[];const d=e.bones.map(()=>({posKeys:[],rotKeys:[],sclKeys:[],prevQuat:null})),h=e.bones.map(()=>({posKeys:[],rotKeys:[],sclKeys:[],prevQuat:null})),m=e.bones.map((e,o)=>{const r=this._getSourceBone(n,o),i=s.get(e.modelId);if(!r||!i||!this._bindRestBones.has(r))return null;const a=kt._computeFBXModelLocalMatrix(i),l=new t.Matrix;return a.invertToRef(l),l});for(const i of c){const a=e.bones.map((e,r)=>{var a,l;const u=s.get(e.modelId),c=null!==(a=o.get(e.modelId))&&void 0!==a?a:[];let d=u?this._sampleModelLocalMatrix(u,c,i):t.Matrix.Identity();const h=m[r];if(h){const e=this._getSourceBone(n,r);d=(null!==(l=null==e?void 0:e.getBindMatrix())&&void 0!==l?l:t.Matrix.Identity()).multiply(h).multiply(d)}return d}),u=e.bones.map(e=>{var t;const n=s.get(e.modelId),r=null!==(t=o.get(e.modelId))&&void 0!==t?t:[];return n?this._sampleModelScale(n,r,i):e.scale}),c=i*l;for(let t=0;t<a.length;t++){if(!r.has(e.bones[t].modelId))continue;const n=e.bones[t].parentIndex,o=n>=0?u[n]:e.bones[t].scale,s=kt._splitParentScaleCompensatedLocalMatrix(a[t],o);kt._pushMatrixKeys(d[t],c,s.boneLocalMatrix),kt._pushMatrixKeys(h[t],c,s.helperLocalMatrix)}}const f=[];for(let o=0;o<e.bones.length;o++){if(!r.has(e.bones[o].modelId))continue;const s=this._getSourceBone(n,o);if(!s)continue;const{posKeys:i,rotKeys:a,sclKeys:u}=d[o],c=[];if(!this._isVector3KeysConstant(i)){const e=new t.Animation(`${s.name}_position`,"position",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(i),c.push(e)}if(!jt(a)){const e=new t.Animation(`${s.name}_rotation`,"rotationQuaternion",l,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(a),c.push(e)}if(!this._isVector3KeysConstant(u)){const e=new t.Animation(`${s.name}_scaling`,"scaling",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(u),c.push(e)}c.length>0&&f.push({bone:s,animations:c});const m=this._getScaleCompensationHelper(n,o);if(!m)continue;const p=[],{posKeys:_,rotKeys:g,sclKeys:y}=h[o];if(!this._isVector3KeysConstant(_)){const e=new t.Animation(`${m.name}_position`,"position",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(_),p.push(e)}if(!jt(g)){const e=new t.Animation(`${m.name}_rotation`,"rotationQuaternion",l,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(g),p.push(e)}if(!this._isVector3KeysConstant(y)){const e=new t.Animation(`${m.name}_scaling`,"scaling",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(y),p.push(e)}p.length>0&&f.push({bone:m,animations:p})}return f}static _pushMatrixKeys(e,n,o){const s=new t.Vector3,r=new t.Quaternion,i=new t.Vector3;o.decompose(s,r,i),e.prevQuat&&t.Quaternion.Dot(e.prevQuat,r)<0&&r.scaleInPlace(-1),e.prevQuat=r,e.posKeys.push({frame:n,value:i}),e.rotKeys.push({frame:n,value:r}),e.sclKeys.push({frame:n,value:s})}_buildNodeAnimations(e,n,o,s,r){var i,a,l,u,c,d,h,m,f;const p=e.find(e=>"T"===e.type),_=e.find(e=>"R"===e.type),g=e.find(e=>"S"===e.type),y=zt(e,30,s,r);if(0===y.length)return[];const v=null==p?void 0:p.curves.find(e=>"d|X"===e.channel),b=null==p?void 0:p.curves.find(e=>"d|Y"===e.channel),x=null==p?void 0:p.curves.find(e=>"d|Z"===e.channel),T=null==_?void 0:_.curves.find(e=>"d|X"===e.channel),A=null==_?void 0:_.curves.find(e=>"d|Y"===e.channel),M=null==_?void 0:_.curves.find(e=>"d|Z"===e.channel),w=null==g?void 0:g.curves.find(e=>"d|X"===e.channel),C=null==g?void 0:g.curves.find(e=>"d|Y"===e.channel),R=null==g?void 0:g.curves.find(e=>"d|Z"===e.channel),O=[],S=[],F=[];let E=null;for(const e of y){const n=30*e,s=null!==(i=it(v,e))&&void 0!==i?i:o.translation[0],r=null!==(a=it(b,e))&&void 0!==a?a:o.translation[1],p=null!==(l=it(x,e))&&void 0!==l?l:o.translation[2],_=null!==(u=it(T,e))&&void 0!==u?u:o.rotation[0],g=null!==(c=it(A,e))&&void 0!==c?c:o.rotation[1],y=null!==(d=it(M,e))&&void 0!==d?d:o.rotation[2],L=null!==(h=it(w,e))&&void 0!==h?h:o.scale[0],I=null!==(m=it(C,e))&&void 0!==m?m:o.scale[1],N=null!==(f=it(R,e))&&void 0!==f?f:o.scale[2],P=kt._computeFBXLocalMatrix([s,r,p],[_,g,y],[L,I,N],o.preRotation,o.postRotation,o.rotationPivot,o.scalingPivot,o.rotationOffset,o.scalingOffset,o.rotationOrder),B=new t.Vector3,k=new t.Quaternion,D=new t.Vector3;P.decompose(B,k,D),E&&t.Quaternion.Dot(E,k)<0&&k.scaleInPlace(-1),E=k,O.push({frame:n,value:D}),S.push({frame:n,value:k}),F.push({frame:n,value:B})}const L=[];if(!this._isVector3KeysConstant(O)){const e=new t.Animation(`${n}_position`,"position",30,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(O),L.push(e)}if(_){const e=new t.Animation(`${n}_rotation`,"rotationQuaternion",30,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(S),L.push(e)}if(!this._isVector3KeysConstant(F)){const e=new t.Animation(`${n}_scaling`,"scaling",30,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(F),L.push(e)}return L}_isVector3KeysConstant(e){if(e.length<2)return!0;const t=e[0].value;for(let n=1;n<e.length;n++){const o=e[n].value;if(Math.abs(o.x-t.x)>1e-4||Math.abs(o.y-t.y)>1e-4||Math.abs(o.z-t.z)>1e-4)return!1}return!0}_sampleModelLocalMatrix(e,t,n,o){var s,r,i,a,l,u,c,d,h;const m=t.find(e=>"T"===e.type),f=t.find(e=>"R"===e.type),p=t.find(e=>"S"===e.type),_=null==m?void 0:m.curves.find(e=>"d|X"===e.channel),g=null==m?void 0:m.curves.find(e=>"d|Y"===e.channel),y=null==m?void 0:m.curves.find(e=>"d|Z"===e.channel),v=null==f?void 0:f.curves.find(e=>"d|X"===e.channel),b=null==f?void 0:f.curves.find(e=>"d|Y"===e.channel),x=null==f?void 0:f.curves.find(e=>"d|Z"===e.channel),T=null==p?void 0:p.curves.find(e=>"d|X"===e.channel),A=null==p?void 0:p.curves.find(e=>"d|Y"===e.channel),M=null==p?void 0:p.curves.find(e=>"d|Z"===e.channel);return kt._computeFBXLocalMatrix([null!==(s=it(_,n))&&void 0!==s?s:e.translation[0],null!==(r=it(g,n))&&void 0!==r?r:e.translation[1],null!==(i=it(y,n))&&void 0!==i?i:e.translation[2]],[null!==(a=it(v,n))&&void 0!==a?a:e.rotation[0],null!==(l=it(b,n))&&void 0!==l?l:e.rotation[1],null!==(u=it(x,n))&&void 0!==u?u:e.rotation[2]],null!=o?o:[null!==(c=it(T,n))&&void 0!==c?c:e.scale[0],null!==(d=it(A,n))&&void 0!==d?d:e.scale[1],null!==(h=it(M,n))&&void 0!==h?h:e.scale[2]],e.preRotation,e.postRotation,e.rotationPivot,e.scalingPivot,e.rotationOffset,e.scalingOffset,e.rotationOrder)}_sampleModelScale(e,t,n){var o,s,r;const i=t.find(e=>"S"===e.type),a=null==i?void 0:i.curves.find(e=>"d|X"===e.channel),l=null==i?void 0:i.curves.find(e=>"d|Y"===e.channel),u=null==i?void 0:i.curves.find(e=>"d|Z"===e.channel);return[null!==(o=it(a,n))&&void 0!==o?o:e.scale[0],null!==(s=it(l,n))&&void 0!==s?s:e.scale[1],null!==(r=it(u,n))&&void 0!==r?r:e.scale[2]]}_buildBoneAnimations(e,n,o,s,r,i){var a,l,u,c,d,h,m,f,p;const _=e.find(e=>"T"===e.type),g=e.find(e=>"R"===e.type),y=e.find(e=>"S"===e.type),v=zt(e,30,s,r);if(0===v.length)return[];const b=null==_?void 0:_.curves.find(e=>"d|X"===e.channel),x=null==_?void 0:_.curves.find(e=>"d|Y"===e.channel),T=null==_?void 0:_.curves.find(e=>"d|Z"===e.channel),A=null==g?void 0:g.curves.find(e=>"d|X"===e.channel),M=null==g?void 0:g.curves.find(e=>"d|Y"===e.channel),w=null==g?void 0:g.curves.find(e=>"d|Z"===e.channel),C=null==y?void 0:y.curves.find(e=>"d|X"===e.channel),R=null==y?void 0:y.curves.find(e=>"d|Y"===e.channel),O=null==y?void 0:y.curves.find(e=>"d|Z"===e.channel),S=[],F=[],E=[];let L=null,I=null;if(i){const e=kt._computeFBXLocalMatrix(o.translation,o.rotation,o.scale,o.preRotation,o.postRotation,o.rotationPivot,o.scalingPivot,o.rotationOffset,o.scalingOffset,o.rotationOrder);I=new t.Matrix,e.invertToRef(I)}for(const e of v){const n=30*e,s=null!==(a=it(b,e))&&void 0!==a?a:o.translation[0],r=null!==(l=it(x,e))&&void 0!==l?l:o.translation[1],_=null!==(u=it(T,e))&&void 0!==u?u:o.translation[2],g=null!==(c=it(A,e))&&void 0!==c?c:o.rotation[0],y=null!==(d=it(M,e))&&void 0!==d?d:o.rotation[1],v=null!==(h=it(w,e))&&void 0!==h?h:o.rotation[2],N=null!==(m=it(C,e))&&void 0!==m?m:o.scale[0],P=null!==(f=it(R,e))&&void 0!==f?f:o.scale[1],B=null!==(p=it(O,e))&&void 0!==p?p:o.scale[2],k=kt._computeFBXLocalMatrix([s,r,_],[g,y,v],[N,P,B],o.preRotation,o.postRotation,o.rotationPivot,o.scalingPivot,o.rotationOffset,o.scalingOffset,o.rotationOrder),D=I&&i?i.multiply(I).multiply(k):k,G=new t.Vector3,V=new t.Quaternion,H=new t.Vector3;D.decompose(G,V,H),L&&t.Quaternion.Dot(L,V)<0&&V.scaleInPlace(-1),L=V,S.push({frame:n,value:H}),F.push({frame:n,value:V}),E.push({frame:n,value:G})}const N=[];if(!this._isVector3KeysConstant(S)){const e=new t.Animation(`${n}_position`,"position",30,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(S),N.push(e)}if(g){const e=new t.Animation(`${n}_rotation`,"rotationQuaternion",30,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(F),N.push(e)}if(!this._isVector3KeysConstant(E)){const e=new t.Animation(`${n}_scaling`,"scaling",30,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(E),N.push(e)}return N}_buildNameFilter(e){if(!e)return null;if("string"==typeof e)return""===e?null:t=>t===e;if(0===e.length)return null;const t=new Set(e);return e=>t.has(e)}}function Dt(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}function Gt(e,t,n,o,s,r,i,a,l,u,c,d,h,m,f,p){var _;const g=function(e,t,n,o){const s=3*t,r=3*n,i=3*o,a=e[r]-e[s],l=e[r+1]-e[s+1],u=e[r+2]-e[s+2],c=e[i]-e[s],d=e[i+1]-e[s+1],h=e[i+2]-e[s+2],m=Math.hypot(a,l,u),f=Math.hypot(c,d,h);if(m<=1e-8||f<=1e-8)return 0;const p=(a*c+l*d+u*h)/(m*f);return Math.acos(Math.max(-1,Math.min(1,p)))}(u,e,t,n);if(g<=1e-8)return;const y=function(e,t,n,o,s,r,i,a,l,u,c,d){const h=3*e,m=3*e,f=2*e,[p,_,g]=Vt(l[m],l[m+1],l[m+2]),y=function(e,t,n,o,s,r,i,a,l){return(t*r-n*s)*i+(n*o-e*r)*a+(e*s-t*o)*l<0?-1:1}(p,_,g,t,n,o,s,r,i);return[c?`cp:${c[e]}`:`p:${Ht(a[h])},${Ht(a[h+1])},${Ht(a[h+2])}`,Ht(p),Ht(_),Ht(g),Ht(u[f]),Ht(u[f+1]),y,d].join("|")}(e,o,s,r,i,a,l,u,c,d,h,m);let v=f.get(y);v||(v={tx:0,ty:0,tz:0,bx:0,by:0,bz:0},f.set(y,v)),v.tx+=o*g,v.ty+=s*g,v.tz+=r*g,v.bx+=i*g,v.by+=a*g,v.bz+=l*g,null!==(_=p[e])&&void 0!==_||(p[e]=y)}function Vt(e,t,n){const o=Math.hypot(e,t,n);return o>1e-8?[e/o,t/o,n/o]:[0,0,1]}function Ht(e){const t=Math.round(1e6*e);return Object.is(t,-0)?0:t}function Kt(e,t,n){const o=Math.abs(e)<.9?1:0,s=1===o?0:1,r=e*o+t*s;let i=o-e*r,a=s-t*r,l=-n*r;const u=Math.hypot(i,a,l);return u<=1e-8?[1,0,0]:(i/=u,a/=u,l/=u,[i,a,l])}function Ut(e,n,o,s,r,i){const a=o.length/3,l=new Float32Array(3*a),u=null!==e.normals&&null!==s?new Float32Array(3*a):null;for(let e=0;e<l.length;e++)l[e]=o[e];if(u&&s)for(let e=0;e<u.length;e++)u[e]=s[e];const c=new Map;for(let t=0;t<e.indices.length;t++)c.set(e.indices[t],t);for(let o=0;o<a;o++){const s=n[o],a=c.get(s);if(void 0===a)continue;let d=e.vertices[3*a],h=e.vertices[3*a+1],m=e.vertices[3*a+2];if(r){const e=t.Vector3.TransformNormal(new t.Vector3(d,h,m),r);d=e.x,h=e.y,m=e.z}if(l[3*o]+=d,l[3*o+1]+=h,l[3*o+2]+=m,u&&e.normals){let n=e.normals[3*a],s=e.normals[3*a+1],r=e.normals[3*a+2];if(i){const e=t.Vector3.TransformNormal(new t.Vector3(n,s,r),i);e.lengthSquared()>0&&e.normalize(),n=e.x,s=e.y,r=e.z}u[3*o]+=n,u[3*o+1]+=s,u[3*o+2]+=r}}return{positions:l,normals:u}}function $t(e,t,n){if(n<=0)return[];if(!t||t.length!==n||1===n)return[Wt(e/((null==t?void 0:t[0])&&0!==t[0]?t[0]:100))];const o=new Array(n).fill(0);if(e<=t[0])return o[0]=0===t[0]?e<=0?1:0:Wt(e/t[0]),o;for(let n=1;n<t.length;n++){const s=t[n-1],r=t[n];if(e>r)continue;const i=r-s;if(Math.abs(i)<1e-6)return o[n]=1,o;const a=Wt((e-s)/i);return o[n-1]=1-a,o[n]=a,o}return o[n-1]=1,o}function Wt(e){return Math.max(0,Math.min(1,e))}function zt(e,t,n,o){let s=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;const i=new Set;for(const t of e)for(const e of t.curves)for(const t of e.keys)s=Math.min(s,t.time),r=Math.max(r,t.time),t.time>=n&&t.time<=o&&i.add(t.time);if(!Number.isFinite(s)||!Number.isFinite(r))return[];const a=o>n?n:s,l=o>n?o:r,u=new Set([a,l,...Array.from(i)]),c=Math.ceil(a*t),d=Math.floor(l*t);for(let e=c;e<=d;e++)u.add(e/t);return Array.from(u).sort((e,t)=>e-t)}function jt(e){if(e.length<2)return!0;const t=e[0].value;for(let n=1;n<e.length;n++){const o=e[n].value;if(Math.abs(o.x-t.x)>1e-4||Math.abs(o.y-t.y)>1e-4||Math.abs(o.z-t.z)>1e-4||Math.abs(o.w-t.w)>1e-4)return!1}return!0}function qt(e,t,n,o,s){var r,i,a,l,u,c;const d=function(e,t,n){var o,s,r,i;return n>t?{start:t,stop:n}:{start:null!==(s=null===(o=e.keys[0])||void 0===o?void 0:o.time)&&void 0!==s?s:0,stop:null!==(i=null===(r=e.keys[e.keys.length-1])||void 0===r?void 0:r.time)&&void 0!==i?i:0}}(e,n,o),h=e.keys.filter(e=>e.time>=d.start&&e.time<=d.stop).map(e=>({source:e,frame:e.time*t,value:s(e.value)}));h.some(e=>Math.abs(e.source.time-d.start)<1e-6)||h.unshift({source:{time:d.start,value:null!==(r=it(e,d.start))&&void 0!==r?r:0,interpolation:"linear"},frame:d.start*t,value:s(null!==(i=it(e,d.start))&&void 0!==i?i:0)}),h.some(e=>Math.abs(e.source.time-d.stop)<1e-6)||h.push({source:{time:d.stop,value:null!==(a=it(e,d.stop))&&void 0!==a?a:0,interpolation:"linear"},frame:d.stop*t,value:s(null!==(l=it(e,d.stop))&&void 0!==l?l:0)});const m=h.map(e=>({frame:e.frame,value:e.value}));for(let e=0;e<h.length-1;e++){const n=h[e].source,o=m[e+1];if("constant"===n.interpolation){m[e].interpolation=1;continue}if("cubic"!==n.interpolation)continue;const r=h[e+1].source,i=Math.max(r.time-n.time,1e-6),a=(r.value-n.value)/i;m[e].outTangent=Xt(null!==(u=n.rightSlope)&&void 0!==u?u:a,s)/t,o.inTangent=Xt(null!==(c=n.nextLeftSlope)&&void 0!==c?c:a,s)/t}return m}function Xt(e,t){return t(e)-t(0)}let Yt=!1;function Qt(){Yt||(Yt=!0,t.RegisterSceneLoaderPlugin(new kt))}Qt();var Zt={__proto__:null,FBXFileLoader:kt,RegisterFBXFileLoader:Qt};function Jt(e,t,n,o){const s={externalResourceFunction:o};return n&&(s.uri="file:"===t?n:t+n),ArrayBuffer.isView(e)?GLTFValidator.validateBytes(e,s):GLTFValidator.validateString(e,s)}function en(){const e=[];onmessage=t=>{const n=t.data;switch(n.id){case"init":importScripts(n.url);break;case"validate":Jt(n.data,n.rootUrl,n.fileName,t=>new Promise((n,o)=>{const s=e.length;e.push({resolve:n,reject:o}),postMessage({id:"getExternalResource",index:s,uri:t})})).then(e=>{postMessage({id:"validate.resolve",value:e})},e=>{postMessage({id:"validate.reject",reason:e})});break;case"getExternalResource.resolve":e[n.index].resolve(n.value);break;case"getExternalResource.reject":e[n.index].reject(n.reason)}}}class tn{static ValidateAsync(e,n,o,s){return"function"==typeof Worker?new Promise((r,i)=>{const a=`${Jt}(${en})()`,l=URL.createObjectURL(new Blob([a],{type:"application/javascript"})),u=new Worker(l),c=e=>{u.removeEventListener("error",c),u.removeEventListener("message",d),i(e)},d=e=>{const t=e.data;switch(t.id){case"getExternalResource":s(t.uri).then(e=>{u.postMessage({id:"getExternalResource.resolve",index:t.index,value:e},[e.buffer])},e=>{u.postMessage({id:"getExternalResource.reject",index:t.index,reason:e})});break;case"validate.resolve":u.removeEventListener("error",c),u.removeEventListener("message",d),tn._LastResults=t.value,r(t.value),u.terminate();break;case"validate.reject":u.removeEventListener("error",c),u.removeEventListener("message",d),i(t.reason),u.terminate()}};if(u.addEventListener("error",c),u.addEventListener("message",d),u.postMessage({id:"init",url:t.Tools.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){const t=e.slice();u.postMessage({id:"validate",data:t,rootUrl:n,fileName:o},[t.buffer])}else u.postMessage({id:"validate",data:e,rootUrl:n,fileName:o})}):(this._LoadScriptPromise||(this._LoadScriptPromise=t.Tools.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then(()=>Jt(e,n,o,s)))}}tn.Configuration={url:`${t.Tools._DefaultCdnUrl}/gltf_validator.js`},tn._LastResults=null;var nn={__proto__:null,GLTFValidation:tn};const on="Z2xURg",sn={name:"gltf",extensions:{".gltf":{isBinary:!1,mimeType:"model/gltf+json"},".glb":{isBinary:!0,mimeType:"model/gltf-binary"}},canDirectLoad:e=>-1!==e.indexOf("asset")&&-1!==e.indexOf("version")||e.startsWith("data:base64,"+on)||e.startsWith("data:;base64,"+on)||e.startsWith("data:application/octet-stream;base64,"+on)||e.startsWith("data:model/gltf-binary;base64,"+on)};function rn(e,t,n){try{return Promise.resolve(new Uint8Array(e,t,n))}catch(e){return Promise.reject(e)}}var an,ln,un;e.GLTFLoaderCoordinateSystemMode=void 0,(an=e.GLTFLoaderCoordinateSystemMode||(e.GLTFLoaderCoordinateSystemMode={}))[an.AUTO=0]="AUTO",an[an.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED",e.GLTFLoaderAnimationStartMode=void 0,(ln=e.GLTFLoaderAnimationStartMode||(e.GLTFLoaderAnimationStartMode={}))[ln.NONE=0]="NONE",ln[ln.FIRST=1]="FIRST",ln[ln.ALL=2]="ALL",e.GLTFLoaderState=void 0,(un=e.GLTFLoaderState||(e.GLTFLoaderState={}))[un.LOADING=0]="LOADING",un[un.READY=1]="READY",un[un.COMPLETE=2]="COMPLETE";class cn{constructor(){this.alwaysComputeBoundingBox=!1,this.alwaysComputeSkeletonRootNode=!1,this.animationStartMode=e.GLTFLoaderAnimationStartMode.FIRST,this.compileMaterials=!1,this.compileShadowGenerators=!1,this.coordinateSystemMode=e.GLTFLoaderCoordinateSystemMode.AUTO,this.createInstances=!0,this.loadAllMaterials=!1,this.loadMorphTargets=!0,this.useMaxMorphTargetInfluencers=!0,this.loadNodeAnimations=!0,this.loadOnlyMaterials=!1,this.loadSkins=!0,this.skipMaterials=!1,this.targetFps=60,this.transparencyAsCoverage=!1,this.useClipPlane=!1,this.useGltfTextureNames=!1,this.useRangeRequests=!1,this.useSRGBBuffers=!0,this.validate=!1,this.useOpenPBR=!1,this.dontUseTransmissionHelper=!1}}const dn=new cn;class hn extends cn{constructor(){super(...arguments),this.extensionOptions={},this.preprocessUrlAsync=e=>Promise.resolve(e)}copyFrom(e){var t,n,o,s,r,i,a,l,u,c,d,h,m,f,p,_,g,y,v,b,x,T,A,M,w,C,R;e&&(this.alwaysComputeBoundingBox=null!==(t=e.alwaysComputeBoundingBox)&&void 0!==t?t:this.alwaysComputeBoundingBox,this.alwaysComputeSkeletonRootNode=null!==(n=e.alwaysComputeSkeletonRootNode)&&void 0!==n?n:this.alwaysComputeSkeletonRootNode,this.animationStartMode=null!==(o=e.animationStartMode)&&void 0!==o?o:this.animationStartMode,this.capturePerformanceCounters=null!==(s=e.capturePerformanceCounters)&&void 0!==s?s:this.capturePerformanceCounters,this.compileMaterials=null!==(r=e.compileMaterials)&&void 0!==r?r:this.compileMaterials,this.compileShadowGenerators=null!==(i=e.compileShadowGenerators)&&void 0!==i?i:this.compileShadowGenerators,this.coordinateSystemMode=null!==(a=e.coordinateSystemMode)&&void 0!==a?a:this.coordinateSystemMode,this.createInstances=null!==(l=e.createInstances)&&void 0!==l?l:this.createInstances,this.customRootNode=e.customRootNode,this.extensionOptions=null!==(u=e.extensionOptions)&&void 0!==u?u:this.extensionOptions,this.loadAllMaterials=null!==(c=e.loadAllMaterials)&&void 0!==c?c:this.loadAllMaterials,this.loadMorphTargets=null!==(d=e.loadMorphTargets)&&void 0!==d?d:this.loadMorphTargets,this.loadNodeAnimations=null!==(h=e.loadNodeAnimations)&&void 0!==h?h:this.loadNodeAnimations,this.loadOnlyMaterials=null!==(m=e.loadOnlyMaterials)&&void 0!==m?m:this.loadOnlyMaterials,this.loadSkins=null!==(f=e.loadSkins)&&void 0!==f?f:this.loadSkins,this.loggingEnabled=null!==(p=e.loggingEnabled)&&void 0!==p?p:this.loggingEnabled,this.onCameraLoaded=e.onCameraLoaded,this.onMaterialLoaded=e.onMaterialLoaded,this.onMeshLoaded=e.onMeshLoaded,this.onParsed=e.onParsed,this.onSkinLoaded=e.onSkinLoaded,this.onTextureLoaded=e.onTextureLoaded,this.onValidated=e.onValidated,this.preprocessUrlAsync=null!==(_=e.preprocessUrlAsync)&&void 0!==_?_:this.preprocessUrlAsync,this.skipMaterials=null!==(g=e.skipMaterials)&&void 0!==g?g:this.skipMaterials,this.targetFps=null!==(y=e.targetFps)&&void 0!==y?y:this.targetFps,this.transparencyAsCoverage=null!==(v=e.transparencyAsCoverage)&&void 0!==v?v:this.transparencyAsCoverage,this.useClipPlane=null!==(b=e.useClipPlane)&&void 0!==b?b:this.useClipPlane,this.useGltfTextureNames=null!==(x=e.useGltfTextureNames)&&void 0!==x?x:this.useGltfTextureNames,this.useMaxMorphTargetInfluencers=null!==(T=e.useMaxMorphTargetInfluencers)&&void 0!==T?T:this.useMaxMorphTargetInfluencers,this.useOpenPBR=null!==(A=e.useOpenPBR)&&void 0!==A?A:this.useOpenPBR,this.useRangeRequests=null!==(M=e.useRangeRequests)&&void 0!==M?M:this.useRangeRequests,this.useSRGBBuffers=null!==(w=e.useSRGBBuffers)&&void 0!==w?w:this.useSRGBBuffers,this.validate=null!==(C=e.validate)&&void 0!==C?C:this.validate,this.dontUseTransmissionHelper=null!==(R=e.dontUseTransmissionHelper)&&void 0!==R?R:this.dontUseTransmissionHelper)}}class mn extends hn{constructor(e){super(),this.onParsedObservable=new t.Observable,this.onMeshLoadedObservable=new t.Observable,this.onSkinLoadedObservable=new t.Observable,this.onTextureLoadedObservable=new t.Observable,this.onMaterialLoadedObservable=new t.Observable,this.onCameraLoadedObservable=new t.Observable,this.onCompleteObservable=new t.Observable,this.onErrorObservable=new t.Observable,this.onDisposeObservable=new t.Observable,this.onExtensionLoadedObservable=new t.Observable,this.onValidatedObservable=new t.Observable,this._loader=null,this._state=null,this._requests=new Array,this.name=sn.name,this.extensions=sn.extensions,this.onLoaderStateChangedObservable=new t.Observable,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled,this.copyFrom(Object.assign(Object.assign({},dn),e))}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),e&&(this._onParsedObserver=this.onParsedObservable.add(e))}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),e&&(this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e))}set onSkinLoaded(e){this._onSkinLoadedObserver&&this.onSkinLoadedObservable.remove(this._onSkinLoadedObserver),e&&(this._onSkinLoadedObserver=this.onSkinLoadedObservable.add(t=>e(t.node,t.skinnedNode)))}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),e&&(this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e))}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),e&&(this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e))}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),e&&(this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e))}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(const e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,n,o,s,r,i,a,l){if(ArrayBuffer.isView(n))return this._loadBinary(e,n,o,s,a,l),null;this._progressCallback=r;const u=n.name||t.Tools.GetFilename(n);if(i){if(this.useRangeRequests){this.validate&&t.Logger.Warn("glTF validation is not supported when range requests are enabled");const o={abort:()=>{},onCompleteObservable:new t.Observable},r={readAsync:(t,o)=>new Promise((s,r)=>{this._loadFile(e,n,e=>{s(new Uint8Array(e))},!0,e=>{r(e)},e=>{e.setRequestHeader("Range",`bytes=${t}-${t+o-1}`)})}),byteLength:0};return this._unpackBinaryAsync(new t.DataReader(r)).then(e=>{o.onCompleteObservable.notifyObservers(o),s(e)},a?e=>a(void 0,e):void 0),o}return this._loadFile(e,n,n=>{this._validate(e,new Uint8Array(n,0,n.byteLength),o,u),this._unpackBinaryAsync(new t.DataReader({readAsync:(e,t)=>rn(n,e,t),byteLength:n.byteLength})).then(e=>{s(e)},a?e=>a(void 0,e):void 0)},!0,a)}return this._loadFile(e,n,t=>{try{this._validate(e,t,o,u),s({json:this._parseJson(t)})}catch(e){a&&a()}},!1,a)}_loadBinary(e,n,o,s,r,i){this._validate(e,new Uint8Array(n.buffer,n.byteOffset,n.byteLength),o,i),this._unpackBinaryAsync(new t.DataReader({readAsync:(e,t)=>function(e,t,n){try{if(t<0||t>=e.byteLength)throw new RangeError("Offset is out of range.");if(t+n>e.byteLength)throw new RangeError("Length is out of range.");return Promise.resolve(new Uint8Array(e.buffer,e.byteOffset+t,n))}catch(e){return Promise.reject(e)}}(n,e,t),byteLength:n.byteLength})).then(e=>{s(e)},r?e=>r(void 0,e):void 0)}importMeshAsync(e,t,n,o,s,r){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(n),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(n),this._loader.importMeshAsync(e,t,null,n,o,s,r)))}loadAsync(e,t,n,o,s){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,n,o,s)))}loadAssetContainerAsync(e,n,o,s,r){return Promise.resolve().then(()=>{this.onParsedObservable.notifyObservers(n),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(n);const i=new t.AssetContainer(e),a=[];this.onMaterialLoadedObservable.add(e=>{a.push(e)});const l=[];this.onTextureLoadedObservable.add(e=>{l.push(e)});const u=[];this.onCameraLoadedObservable.add(e=>{u.push(e)});const c=[];return this.onMeshLoadedObservable.add(e=>{e.morphTargetManager&&c.push(e.morphTargetManager)}),this._loader.importMeshAsync(null,e,i,n,o,s,r).then(e=>(Array.prototype.push.apply(i.geometries,e.geometries),Array.prototype.push.apply(i.meshes,e.meshes),Array.prototype.push.apply(i.particleSystems,e.particleSystems),Array.prototype.push.apply(i.skeletons,e.skeletons),Array.prototype.push.apply(i.animationGroups,e.animationGroups),Array.prototype.push.apply(i.materials,a),Array.prototype.push.apply(i.textures,l),Array.prototype.push.apply(i.lights,e.lights),Array.prototype.push.apply(i.transformNodes,e.transformNodes),Array.prototype.push.apply(i.cameras,u),Array.prototype.push.apply(i.morphTargetManagers,c),i))})}canDirectLoad(e){return sn.canDirectLoad(e)}directLoad(e,n){if(n.startsWith("base64,"+on)||n.startsWith(";base64,"+on)||n.startsWith("application/octet-stream;base64,"+on)||n.startsWith("model/gltf-binary;base64,"+on)){const o=t.DecodeBase64UrlToBinary(n);return this._validate(e,new Uint8Array(o,0,o.byteLength)),this._unpackBinaryAsync(new t.DataReader({readAsync:(e,t)=>rn(o,e,t),byteLength:o.byteLength}))}return this._validate(e,n),Promise.resolve({json:this._parseJson(n)})}createPlugin(e){return new mn(e[sn.name])}get loaderState(){return this._state}whenCompleteAsync(){return new Promise((e,t)=>{this.onCompleteObservable.addOnce(()=>{e()}),this.onErrorObservable.addOnce(e=>{t(e)})})}_setState(t){this._state!==t&&(this._state=t,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(e.GLTFLoaderState[this._state]))}_loadFile(e,t,n,o,s,r){const i=e._loadFile(t,n,e=>{this._onProgress(e,i)},!0,o,s,r);return i.onCompleteObservable.add(()=>{i._lengthComputable=!0,i._total=i._loaded}),this._requests.push(i),i}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let n=!0,o=0,s=0;for(const e of this._requests){if(void 0===e._lengthComputable||void 0===e._loaded||void 0===e._total)return;n=n&&e._lengthComputable,o+=e._loaded,s+=e._total}this._progressCallback({lengthComputable:n,loaded:o,total:n?s:0})}_validate(e,n,o="",s=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),tn.ValidateAsync(n,o,s,t=>this.preprocessUrlAsync(o+t).then(t=>e._loadFileAsync(t,void 0,!0,!0).then(e=>new Uint8Array(e,0,e.byteLength)))).then(e=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(e),this.onValidatedObservable.clear()},e=>{this._endPerformanceCounter("Validate JSON"),t.Tools.Warn(`Failed to validate: ${e.message}`),this.onValidatedObservable.clear()}))}_getLoader(e){const t=e.json.asset||{};this._log(`Asset version: ${t.version}`),t.minVersion&&this._log(`Asset minimum version: ${t.minVersion}`),t.generator&&this._log(`Asset generator: ${t.generator}`);const n=mn._parseVersion(t.version);if(!n)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=mn._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(mn._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const o={1:mn._CreateGLTF1Loader,2:mn._CreateGLTF2Loader}[n.major];if(!o)throw new Error("Unsupported version: "+t.version);return o(this)}_parseJson(e){this._startPerformanceCounter("Parse JSON"),this._log(`JSON length: ${e.length}`);const t=JSON.parse(e);return this._endPerformanceCounter("Parse JSON"),t}_unpackBinaryAsync(e){return this._startPerformanceCounter("Unpack Binary"),e.loadAsync(20).then(()=>{const n=e.readUint32();if(1179937895!==n)throw new t.RuntimeError("Unexpected magic: "+n,t.ErrorCodes.GLTFLoaderUnexpectedMagicError);const o=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${o}`);const s=e.readUint32();let r;switch(this.useRangeRequests||s===e.buffer.byteLength||t.Logger.Warn(`Length in header does not match actual data length: ${s} != ${e.buffer.byteLength}`),o){case 1:r=this._unpackBinaryV1Async(e,s);break;case 2:r=this._unpackBinaryV2Async(e,s);break;default:throw new Error("Unsupported version: "+o)}return this._endPerformanceCounter("Unpack Binary"),r})}_unpackBinaryV1Async(e,t){const n=e.readUint32(),o=e.readUint32();if(0!==o)throw new Error(`Unexpected content format: ${o}`);const s=t-e.byteOffset,r={json:this._parseJson(e.readString(n)),bin:null};if(0!==s){const t=e.byteOffset;r.bin={readAsync:(n,o)=>e.buffer.readAsync(t+n,o),byteLength:s}}return Promise.resolve(r)}_unpackBinaryV2Async(e,t){const n=1313821514,o=e.readUint32();if(e.readUint32()!==n)throw new Error("First chunk format is not JSON");return e.byteOffset+o===t?e.loadAsync(o).then(()=>({json:this._parseJson(e.readString(o)),bin:null})):e.loadAsync(o+8).then(()=>{const s={json:this._parseJson(e.readString(o)),bin:null},r=()=>{const o=e.readUint32();switch(e.readUint32()){case n:throw new Error("Unexpected JSON chunk");case 5130562:{const t=e.byteOffset;s.bin={readAsync:(n,o)=>e.buffer.readAsync(t+n,o),byteLength:o},e.skipBytes(o);break}default:e.skipBytes(o)}return e.byteOffset!==t?e.loadAsync(8).then(r):Promise.resolve(s)};return r()})}static _parseVersion(e){if("1.0"===e||"1.0.1"===e)return{major:1,minor:0};const t=(e+"").match(/^(\d+)\.(\d+)/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null}static _compareVersion(e,t){return e.major>t.major?1:e.major<t.major?-1:e.minor>t.minor?1:e.minor<t.minor?-1:0}_logOpen(e){this._log(e),this._logIndentLevel++}_logClose(){--this._logIndentLevel}_logEnabled(e){const n=mn._logSpaces.substring(0,2*this._logIndentLevel);t.Logger.Log(`${n}${e}`)}_logDisabled(e){}_startPerformanceCounterEnabled(e){t.Tools.StartPerformanceCounter(e)}_startPerformanceCounterDisabled(e){}_endPerformanceCounterEnabled(e){t.Tools.EndPerformanceCounter(e)}_endPerformanceCounterDisabled(e){}}mn.IncrementalLoading=!0,mn.HomogeneousCoordinates=!1,mn._logSpaces=" ";let fn=!1;function pn(){fn||(fn=!0,t.RegisterSceneLoaderPlugin(new mn))}pn();var _n,gn,yn,vn,bn,xn,Tn,An,Mn,wn={__proto__:null,GLTFFileLoader:mn,get GLTFLoaderAnimationStartMode(){return e.GLTFLoaderAnimationStartMode},get GLTFLoaderCoordinateSystemMode(){return e.GLTFLoaderCoordinateSystemMode},GLTFLoaderDefaultOptions:dn,get GLTFLoaderState(){return e.GLTFLoaderState},RegisterGLTFFileLoader:pn};!function(e){e[e.BYTE=5120]="BYTE",e[e.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",e[e.SHORT=5122]="SHORT",e[e.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",e[e.FLOAT=5126]="FLOAT"}(_n||(_n={})),function(e){e[e.FRAGMENT=35632]="FRAGMENT",e[e.VERTEX=35633]="VERTEX"}(gn||(gn={})),function(e){e[e.BYTE=5120]="BYTE",e[e.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",e[e.SHORT=5122]="SHORT",e[e.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",e[e.INT=5124]="INT",e[e.UNSIGNED_INT=5125]="UNSIGNED_INT",e[e.FLOAT=5126]="FLOAT",e[e.FLOAT_VEC2=35664]="FLOAT_VEC2",e[e.FLOAT_VEC3=35665]="FLOAT_VEC3",e[e.FLOAT_VEC4=35666]="FLOAT_VEC4",e[e.INT_VEC2=35667]="INT_VEC2",e[e.INT_VEC3=35668]="INT_VEC3",e[e.INT_VEC4=35669]="INT_VEC4",e[e.BOOL=35670]="BOOL",e[e.BOOL_VEC2=35671]="BOOL_VEC2",e[e.BOOL_VEC3=35672]="BOOL_VEC3",e[e.BOOL_VEC4=35673]="BOOL_VEC4",e[e.FLOAT_MAT2=35674]="FLOAT_MAT2",e[e.FLOAT_MAT3=35675]="FLOAT_MAT3",e[e.FLOAT_MAT4=35676]="FLOAT_MAT4",e[e.SAMPLER_2D=35678]="SAMPLER_2D"}(yn||(yn={})),function(e){e[e.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",e[e.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",e[e.REPEAT=10497]="REPEAT"}(vn||(vn={})),function(e){e[e.NEAREST=9728]="NEAREST",e[e.LINEAR=9728]="LINEAR",e[e.NEAREST_MIPMAP_NEAREST=9984]="NEAREST_MIPMAP_NEAREST",e[e.LINEAR_MIPMAP_NEAREST=9985]="LINEAR_MIPMAP_NEAREST",e[e.NEAREST_MIPMAP_LINEAR=9986]="NEAREST_MIPMAP_LINEAR",e[e.LINEAR_MIPMAP_LINEAR=9987]="LINEAR_MIPMAP_LINEAR"}(bn||(bn={})),function(e){e[e.ALPHA=6406]="ALPHA",e[e.RGB=6407]="RGB",e[e.RGBA=6408]="RGBA",e[e.LUMINANCE=6409]="LUMINANCE",e[e.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA"}(xn||(xn={})),function(e){e[e.FRONT=1028]="FRONT",e[e.BACK=1029]="BACK",e[e.FRONT_AND_BACK=1032]="FRONT_AND_BACK"}(Tn||(Tn={})),function(e){e[e.ZERO=0]="ZERO",e[e.ONE=1]="ONE",e[e.SRC_COLOR=768]="SRC_COLOR",e[e.ONE_MINUS_SRC_COLOR=769]="ONE_MINUS_SRC_COLOR",e[e.DST_COLOR=774]="DST_COLOR",e[e.ONE_MINUS_DST_COLOR=775]="ONE_MINUS_DST_COLOR",e[e.SRC_ALPHA=770]="SRC_ALPHA",e[e.ONE_MINUS_SRC_ALPHA=771]="ONE_MINUS_SRC_ALPHA",e[e.DST_ALPHA=772]="DST_ALPHA",e[e.ONE_MINUS_DST_ALPHA=773]="ONE_MINUS_DST_ALPHA",e[e.CONSTANT_COLOR=32769]="CONSTANT_COLOR",e[e.ONE_MINUS_CONSTANT_COLOR=32770]="ONE_MINUS_CONSTANT_COLOR",e[e.CONSTANT_ALPHA=32771]="CONSTANT_ALPHA",e[e.ONE_MINUS_CONSTANT_ALPHA=32772]="ONE_MINUS_CONSTANT_ALPHA",e[e.SRC_ALPHA_SATURATE=776]="SRC_ALPHA_SATURATE"}(An||(An={}));class Cn{static SetMatrix(e,n,o,s,r){let i=null;if("MODEL"===o.semantic?i=n.getWorldMatrix():"PROJECTION"===o.semantic?i=e.getProjectionMatrix():"VIEW"===o.semantic?i=e.getViewMatrix():"MODELVIEWINVERSETRANSPOSE"===o.semantic?i=t.Matrix.Transpose(n.getWorldMatrix().multiply(e.getViewMatrix()).invert()):"MODELVIEW"===o.semantic?i=n.getWorldMatrix().multiply(e.getViewMatrix()):"MODELVIEWPROJECTION"===o.semantic?i=n.getWorldMatrix().multiply(e.getTransformMatrix()):"MODELINVERSE"===o.semantic?i=n.getWorldMatrix().invert():"VIEWINVERSE"===o.semantic?i=e.getViewMatrix().invert():"PROJECTIONINVERSE"===o.semantic?i=e.getProjectionMatrix().invert():"MODELVIEWINVERSE"===o.semantic?i=n.getWorldMatrix().multiply(e.getViewMatrix()).invert():"MODELVIEWPROJECTIONINVERSE"===o.semantic?i=n.getWorldMatrix().multiply(e.getTransformMatrix()).invert():"MODELINVERSETRANSPOSE"===o.semantic&&(i=t.Matrix.Transpose(n.getWorldMatrix().invert())),i)switch(o.type){case yn.FLOAT_MAT2:r.setMatrix2x2(s,t.Matrix.GetAsMatrix2x2(i));break;case yn.FLOAT_MAT3:r.setMatrix3x3(s,t.Matrix.GetAsMatrix3x3(i));break;case yn.FLOAT_MAT4:r.setMatrix(s,i)}}static SetUniform(e,n,o,s){switch(s){case yn.FLOAT:return e.setFloat(n,o),!0;case yn.FLOAT_VEC2:return e.setVector2(n,t.Vector2.FromArray(o)),!0;case yn.FLOAT_VEC3:return e.setVector3(n,t.Vector3.FromArray(o)),!0;case yn.FLOAT_VEC4:return e.setVector4(n,t.Vector4.FromArray(o)),!0;default:return!1}}static GetWrapMode(e){switch(e){case vn.CLAMP_TO_EDGE:return t.Texture.CLAMP_ADDRESSMODE;case vn.MIRRORED_REPEAT:return t.Texture.MIRROR_ADDRESSMODE;case vn.REPEAT:default:return t.Texture.WRAP_ADDRESSMODE}}static GetByteStrideFromType(e){switch(e.type){case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16;default:return 1}}static GetTextureFilterMode(e){switch(e){case bn.LINEAR:case bn.LINEAR_MIPMAP_NEAREST:case bn.LINEAR_MIPMAP_LINEAR:return t.Texture.TRILINEAR_SAMPLINGMODE;case bn.NEAREST:case bn.NEAREST_MIPMAP_NEAREST:return t.Texture.NEAREST_SAMPLINGMODE;default:return t.Texture.BILINEAR_SAMPLINGMODE}}static GetBufferFromBufferView(e,t,n,o,s){n=t.byteOffset+n;const r=e.loadedBufferViews[t.buffer];if(n+o>r.byteLength)throw new Error("Buffer access is out of range");const i=r.buffer;switch(n+=r.byteOffset,s){case _n.BYTE:return new Int8Array(i,n,o);case _n.UNSIGNED_BYTE:return new Uint8Array(i,n,o);case _n.SHORT:return new Int16Array(i,n,o);case _n.UNSIGNED_SHORT:return new Uint16Array(i,n,o);default:return new Float32Array(i,n,o)}}static GetBufferFromAccessor(e,t){const n=e.bufferViews[t.bufferView],o=t.count*Cn.GetByteStrideFromType(t);return Cn.GetBufferFromBufferView(e,n,t.byteOffset,o,t.componentType)}static DecodeBufferToText(e){let t="";const n=e.byteLength;for(let o=0;o<n;++o)t+=String.fromCharCode(e[o]);return t}static GetDefaultMaterial(e){if(!Cn._DefaultMaterial){t.Effect.ShadersStore.GLTFDefaultMaterialVertexShader=["precision highp float;","","uniform mat4 worldView;","uniform mat4 projection;","","attribute vec3 position;","","void main(void)","{"," gl_Position = projection * worldView * vec4(position, 1.0);","}"].join("\n"),t.Effect.ShadersStore.GLTFDefaultMaterialPixelShader=["precision highp float;","","uniform vec4 u_emission;","","void main(void)","{"," gl_FragColor = u_emission;","}"].join("\n");const n={vertex:"GLTFDefaultMaterial",fragment:"GLTFDefaultMaterial"},o={attributes:["position"],uniforms:["worldView","projection","u_emission"],samplers:new Array,needAlphaBlending:!1};Cn._DefaultMaterial=new t.ShaderMaterial("GLTFDefaultMaterial",e,n,o),Cn._DefaultMaterial.setColor4("u_emission",new t.Color4(.5,.5,.5,1))}return Cn._DefaultMaterial}}Cn._DefaultMaterial=null,function(e){e[e.IDENTIFIER=1]="IDENTIFIER",e[e.UNKNOWN=2]="UNKNOWN",e[e.END_OF_INPUT=3]="END_OF_INPUT"}(Mn||(Mn={}));class Rn{constructor(e){this._pos=0,this.currentToken=Mn.UNKNOWN,this.currentIdentifier="",this.currentString="",this.isLetterOrDigitPattern=/^[a-zA-Z0-9]+$/,this._toParse=e,this._maxPos=e.length}getNextToken(){if(this.isEnd())return Mn.END_OF_INPUT;if(this.currentString=this.read(),this.currentToken=Mn.UNKNOWN,"_"===this.currentString||this.isLetterOrDigitPattern.test(this.currentString))for(this.currentToken=Mn.IDENTIFIER,this.currentIdentifier=this.currentString;!this.isEnd()&&(this.isLetterOrDigitPattern.test(this.currentString=this.peek())||"_"===this.currentString);)this.currentIdentifier+=this.currentString,this.forward();return this.currentToken}peek(){return this._toParse[this._pos]}read(){return this._toParse[this._pos++]}forward(){this._pos++}isEnd(){return this._pos>=this._maxPos}}const On=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],Sn=["world","view","projection","worldView","worldViewProjection","mBones"],Fn=["translation","rotation","scale"],En=["position","rotationQuaternion","scaling"],Ln=(e,t,n)=>{for(const o in e){const s=e[o];n[t][o]=s}},In=e=>{if(e)for(let t=0;t<e.length/2;t++)e[2*t+1]=1-e[2*t+1]},Nn=e=>{if("NORMAL"===e.semantic)return"normal";if("POSITION"===e.semantic)return"position";if("JOINT"===e.semantic)return"matricesIndices";if("WEIGHT"===e.semantic)return"matricesWeights";if("COLOR"===e.semantic)return"color";if(e.semantic&&-1!==e.semantic.indexOf("TEXCOORD_")){const t=Number(e.semantic.split("_")[1]);return"uv"+(0===t?"":t+1)}return null},Pn=e=>{let n;if(e.translation||e.rotation||e.scale){const o=t.Vector3.FromArray(e.scale||[1,1,1]),s=t.Quaternion.FromArray(e.rotation||[0,0,0,1]),r=t.Vector3.FromArray(e.translation||[0,0,0]);n=t.Matrix.Compose(o,s,r)}else n=t.Matrix.FromArray(e.matrix);return n},Bn=(e,n,o,s)=>{for(let e=0;e<s.bones.length;e++)if(s.bones[e].name===o)return s.bones[e];const r=e.nodes;for(const i in r){const a=r[i];if(!a.jointName)continue;const l=a.children;for(let r=0;r<l.length;r++){const u=e.nodes[l[r]];if(u.jointName&&u.jointName===o){const o=Pn(a),r=new t.Bone(a.name||"",s,Bn(e,n,a.jointName,s),o);return r.id=i,r}}}return null},kn=(e,t)=>{for(let n=0;n<e.length;n++){const o=e[n];for(let e=0;e<o.node.children.length;e++)if(o.node.children[e]===t)return o.bone}return null},Dn=(e,t)=>{const n=e.nodes;let o=n[t];if(o)return{node:o,id:t};for(const e in n)if(o=n[e],o.jointName===t)return{node:o,id:e};return null},Gn=(e,t)=>{for(let n=0;n<e.jointNames.length;n++)if(e.jointNames[n]===t)return!0;return!1},Vn=(e,n,o,s,r)=>{if(r||(e.scene._blockEntityCollection=!!e.assetContainer,(r=new t.Mesh(n.name||"",e.scene))._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,r.id=s),!n.babylonNode)return r;const i=[];let a=null;const l=[],u=[],c=[],d=[];for(let n=0;n<o.length;n++){const s=o[n],r=e.meshes[s];if(r)for(let n=0;n<r.primitives.length;n++){const o=new t.VertexData,s=r.primitives[n];s.mode;const h=s.attributes;let m,f;for(const n in h)if(m=e.accessors[h[n]],f=Cn.GetBufferFromAccessor(e,m),"NORMAL"===n)o.normals=new Float32Array(f.length),o.normals.set(f);else if("POSITION"===n){if(mn.HomogeneousCoordinates){o.positions=new Float32Array(f.length-f.length/4);for(let e=0;e<f.length;e+=4)o.positions[e]=f[e],o.positions[e+1]=f[e+1],o.positions[e+2]=f[e+2]}else o.positions=new Float32Array(f.length),o.positions.set(f);u.push(o.positions.length)}else if(-1!==n.indexOf("TEXCOORD_")){const e=Number(n.split("_")[1]),s=t.VertexBuffer.UVKind+(0===e?"":e+1),r=new Float32Array(f.length);r.set(f),In(r),o.set(r,s)}else"JOINT"===n?(o.matricesIndices=new Float32Array(f.length),o.matricesIndices.set(f)):"WEIGHT"===n?(o.matricesWeights=new Float32Array(f.length),o.matricesWeights.set(f)):"COLOR"===n&&(o.colors=new Float32Array(f.length),o.colors.set(f));if(m=e.accessors[s.indices],m)f=Cn.GetBufferFromAccessor(e,m),o.indices=new Int32Array(f.length),o.indices.set(f),d.push(o.indices.length);else{const e=[];for(let t=0;t<o.positions.length/3;t++)e.push(t);o.indices=new Int32Array(e),d.push(o.indices.length)}a?a.merge(o):a=o;const p=e.scene.getMaterialById(s.material);i.push(null===p?Cn.GetDefaultMaterial(e.scene):p),l.push(0===l.length?0:l[l.length-1]+u[u.length-2]),c.push(0===c.length?0:c[c.length-1]+d[d.length-2])}}let h;e.scene._blockEntityCollection=!!e.assetContainer,i.length>1?(h=new t.MultiMaterial("multimat"+s,e.scene),h.subMaterials=i):h=new t.StandardMaterial("multimat"+s,e.scene),1===i.length&&(h=i[0]),h._parentContainer=e.assetContainer,r.material||(r.material=h),new t.Geometry(s,e.scene,a,!1,r),r.computeWorldMatrix(!0),e.scene._blockEntityCollection=!1,r.subMeshes=[];let m=0;for(let n=0;n<o.length;n++){const s=o[n],i=e.meshes[s];if(i)for(let e=0;e<i.primitives.length;e++)i.primitives[e].mode,t.SubMesh.AddToMesh(m,l[m],u[m],c[m],d[m],r,r,!0),m++}return r},Hn=(e,t,n,o)=>{e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=n),e.scaling&&(e.scaling=o)},Kn=(e,n,o)=>{let s=null;if(e.importOnlyMeshes&&(n.skin||n.meshes)&&e.importMeshesNames&&e.importMeshesNames.length>0&&-1===e.importMeshesNames.indexOf(n.name||""))return null;if(n.skin){if(n.meshes){const r=e.skins[n.skin],i=Vn(e,n,n.meshes,o,n.babylonNode);i.skeleton=e.scene.getLastSkeletonById(n.skin),null===i.skeleton&&(i.skeleton=((e,n,o,s)=>{if(s||(s=new t.Skeleton(n.name||"","",e.scene)),!n.babylonSkeleton)return s;const r=[],i=[];((e,n,o,s)=>{for(const r in e.nodes){const i=e.nodes[r],a=r;if(!i.jointName||Gn(o,i.jointName))continue;const l=Pn(i),u=new t.Bone(i.name||"",n,null,l);u.id=a,s.push({bone:u,node:i,id:a})}for(let e=0;e<s.length;e++){const t=s[e],n=t.node.children;for(let e=0;e<n.length;e++){let o=null;for(let t=0;t<s.length;t++)if(s[t].id===n[e]){o=s[t];break}o&&(o.bone._parent=t.bone,t.bone.children.push(o.bone))}}})(e,s,n,r),s.bones=[];for(let o=0;o<n.jointNames.length;o++){const a=Dn(e,n.jointNames[o]);if(!a)continue;const l=a.node;if(!l){t.Tools.Warn("Joint named "+n.jointNames[o]+" does not exist");continue}const u=a.id,c=e.scene.getBoneById(u);if(c){s.bones.push(c);continue}let d,h=null;for(let r=0;r<o;r++){const o=Dn(e,n.jointNames[r]);if(!o)continue;const i=o.node;if(!i){t.Tools.Warn("Joint named "+n.jointNames[r]+" does not exist when looking for parent");continue}const a=i.children;if(a){d=!1;for(let t=0;t<a.length;t++)if(a[t]===u){h=Bn(e,n,n.jointNames[r],s),d=!0;break}if(d)break}}const m=Pn(l);!h&&r.length>0&&(h=kn(r,u),h&&-1===i.indexOf(h)&&i.push(h)),new t.Bone(l.jointName||"",s,h,m).id=u}const a=s.bones;s.bones=[];for(let t=0;t<n.jointNames.length;t++){const o=Dn(e,n.jointNames[t]);if(o)for(let e=0;e<a.length;e++)if(a[e].id===o.id){s.bones.push(a[e]);break}}s.prepare();for(let e=0;e<i.length;e++)s.bones.push(i[e]);return s})(e,r,0,r.babylonSkeleton),r.babylonSkeleton||(r.babylonSkeleton=i.skeleton)),s=i}}else if(n.meshes)s=Vn(e,n,n.mesh?[n.mesh]:n.meshes,o,n.babylonNode);else if(!n.light||n.babylonNode||e.importOnlyMeshes){if(n.camera&&!n.babylonNode&&!e.importOnlyMeshes){const o=e.cameras[n.camera];if(o){if(e.scene._blockEntityCollection=!!e.assetContainer,"orthographic"===o.type){const o=new t.FreeCamera(n.camera,t.Vector3.Zero(),e.scene,!1);o.name=n.name||"",o.mode=t.Camera.ORTHOGRAPHIC_CAMERA,o.attachControl(),s=o,o._parentContainer=e.assetContainer}else if("perspective"===o.type){const r=o[o.type],i=new t.FreeCamera(n.camera,t.Vector3.Zero(),e.scene,!1);i.name=n.name||"",i.attachControl(),r.aspectRatio||(r.aspectRatio=e.scene.getEngine().getRenderWidth()/e.scene.getEngine().getRenderHeight()),r.znear&&r.zfar&&(i.maxZ=r.zfar,i.minZ=r.znear),s=i,i._parentContainer=e.assetContainer}e.scene._blockEntityCollection=!1}}}else{const o=e.lights[n.light];if(o)if("ambient"===o.type){const r=o[o.type],i=new t.HemisphericLight(n.light,t.Vector3.Zero(),e.scene);i.name=n.name||"",r.color&&(i.diffuse=t.Color3.FromArray(r.color)),s=i}else if("directional"===o.type){const r=o[o.type],i=new t.DirectionalLight(n.light,t.Vector3.Zero(),e.scene);i.name=n.name||"",r.color&&(i.diffuse=t.Color3.FromArray(r.color)),s=i}else if("point"===o.type){const r=o[o.type],i=new t.PointLight(n.light,t.Vector3.Zero(),e.scene);i.name=n.name||"",r.color&&(i.diffuse=t.Color3.FromArray(r.color)),s=i}else if("spot"===o.type){const r=o[o.type],i=new t.SpotLight(n.light,t.Vector3.Zero(),t.Vector3.Zero(),0,0,e.scene);i.name=n.name||"",r.color&&(i.diffuse=t.Color3.FromArray(r.color)),r.fallOfAngle&&(i.angle=r.fallOfAngle),r.fallOffExponent&&(i.exponent=r.fallOffExponent),s=i}}if(!n.jointName){if(n.babylonNode)return n.babylonNode;if(null===s){e.scene._blockEntityCollection=!!e.assetContainer;const o=new t.Mesh(n.name||"",e.scene);o._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,n.babylonNode=o,s=o}}if(null!==s){if(n.matrix&&s instanceof t.Mesh)((e,n)=>{if(n.matrix){const o=new t.Vector3(0,0,0),s=new t.Quaternion,r=new t.Vector3(0,0,0);t.Matrix.FromArray(n.matrix).decompose(r,s,o),Hn(e,o,s,r)}else n.translation&&n.rotation&&n.scale&&Hn(e,t.Vector3.FromArray(n.translation),t.Quaternion.FromArray(n.rotation),t.Vector3.FromArray(n.scale));e.computeWorldMatrix(!0)})(s,n);else{const e=n.translation||[0,0,0],o=n.rotation||[0,0,0,1],r=n.scale||[1,1,1];Hn(s,t.Vector3.FromArray(e),t.Quaternion.FromArray(o),t.Vector3.FromArray(r))}s.updateCache(!0),n.babylonNode=s}return s},Un=(e,t,n,o=!1)=>{const s=e.nodes[t];let r=null;if(o=!(e.importOnlyMeshes&&!o&&e.importMeshesNames)||-1!==e.importMeshesNames.indexOf(s.name||"")||0===e.importMeshesNames.length,!s.jointName&&o&&(r=Kn(e,s,t),null!==r&&(r.id=t,r.parent=n)),s.children)for(let t=0;t<s.children.length;t++)Un(e,s.children[t],r,o)},$n=e=>{let n=e.currentScene;if(n)for(let t=0;t<n.nodes.length;t++)Un(e,n.nodes[t],null);else for(const t in e.scenes){n=e.scenes[t];for(let t=0;t<n.nodes.length;t++)Un(e,n.nodes[t],null)}(e=>{for(const n in e.animations){const o=e.animations[n];if(!o.channels||!o.samplers)continue;let s=null;for(let r=0;r<o.channels.length;r++){const i=o.channels[r],a=o.samplers[i.sampler];if(!a)continue;let l,u;o.parameters?(l=o.parameters[a.input],u=o.parameters[a.output]):(l=a.input,u=a.output);const c=Cn.GetBufferFromAccessor(e,e.accessors[l]),d=Cn.GetBufferFromAccessor(e,e.accessors[u]),h=i.target.id;let m=e.scene.getNodeById(h);if(null===m&&(m=e.scene.getNodeByName(h)),null===m){t.Tools.Warn("Creating animation named "+n+". But cannot find node named "+h+" to attach to");continue}const f=m instanceof t.Bone;let p=i.target.path;const _=Fn.indexOf(p);-1!==_&&(p=En[_]);let g=t.Animation.ANIMATIONTYPE_MATRIX;f||("rotationQuaternion"===p?(g=t.Animation.ANIMATIONTYPE_QUATERNION,m.rotationQuaternion=new t.Quaternion):g=t.Animation.ANIMATIONTYPE_VECTOR3);let y=null;const v=[];let b=0,x=!1;f&&s&&s.getKeys().length===c.length&&(y=s,x=!0),x||(e.scene._blockEntityCollection=!!e.assetContainer,y=new t.Animation(n,f?"_matrix":p,1,g,t.Animation.ANIMATIONLOOPMODE_CYCLE),e.scene._blockEntityCollection=!1);for(let e=0;e<c.length;e++){let n;if("rotationQuaternion"===p?(n=t.Quaternion.FromArray([d[b],d[b+1],d[b+2],d[b+3]]),b+=4):(n=t.Vector3.FromArray([d[b],d[b+1],d[b+2]]),b+=3),f){const o=m;let r=t.Vector3.Zero(),i=new t.Quaternion,a=t.Vector3.Zero(),l=o.getBaseMatrix();x&&s&&(l=s.getKeys()[e].value),l.decompose(a,i,r),"position"===p?r=n:"rotationQuaternion"===p?i=n:a=n,n=t.Matrix.Compose(a,i,r)}x?s&&(s.getKeys()[e].value=n):v.push({frame:c[e],value:n})}!x&&y&&(y.setKeys(v),m.animations.push(y)),s=y,e.scene.stopAnimation(m),e.scene.beginAnimation(m,0,c[c.length-1],!0,1)}}})(e);for(let t=0;t<e.scene.skeletons.length;t++){const n=e.scene.skeletons[t];e.scene.beginAnimation(n,0,Number.MAX_VALUE,!0,1)}},Wn=(e,t,n)=>{for(const o in t.uniforms){const s=t.uniforms[o],r=t.parameters[s];if(e.currentIdentifier===o&&r.semantic&&!r.source&&!r.node){const e=On.indexOf(r.semantic);if(-1!==e)return delete n[o],Sn[e]}}return e.currentIdentifier},zn=e=>{for(const t in e.materials)Xn.LoadMaterialAsync(e,t,()=>{},()=>{})};class jn{static CreateRuntime(e,t,n){const o={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:t,rootUrl:n,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[],assetContainer:null};return e.extensions&&Ln(e.extensions,"extensions",o),e.extensionsUsed&&Ln(e.extensionsUsed,"extensionsUsed",o),e.buffers&&((e,t)=>{for(const n in e){const o=e[n];t.buffers[n]=o,t.buffersCount++}})(e.buffers,o),e.bufferViews&&Ln(e.bufferViews,"bufferViews",o),e.accessors&&Ln(e.accessors,"accessors",o),e.meshes&&Ln(e.meshes,"meshes",o),e.lights&&Ln(e.lights,"lights",o),e.cameras&&Ln(e.cameras,"cameras",o),e.nodes&&Ln(e.nodes,"nodes",o),e.images&&Ln(e.images,"images",o),e.textures&&Ln(e.textures,"textures",o),e.shaders&&((e,t)=>{for(const n in e){const o=e[n];t.shaders[n]=o,t.shaderscount++}})(e.shaders,o),e.programs&&Ln(e.programs,"programs",o),e.samplers&&Ln(e.samplers,"samplers",o),e.techniques&&Ln(e.techniques,"techniques",o),e.materials&&Ln(e.materials,"materials",o),e.animations&&Ln(e.animations,"animations",o),e.skins&&Ln(e.skins,"skins",o),e.scenes&&(o.scenes=e.scenes),e.scene&&e.scenes&&(o.currentScene=e.scenes[e.scene]),o}static LoadBufferAsync(e,n,o,s,r){const i=e.buffers[n];t.Tools.IsBase64(i.uri)?setTimeout(()=>o(new Uint8Array(t.Tools.DecodeBase64(i.uri)))):t.Tools.LoadFile(e.rootUrl+i.uri,e=>o(new Uint8Array(e)),r,void 0,!0,e=>{e&&s(e.status+" "+e.statusText)})}static LoadTextureBufferAsync(e,n,o,s){const r=e.textures[n];if(!r||!r.source)return void s("");if(r.babylonTexture)return void o(null);const i=e.images[r.source];t.Tools.IsBase64(i.uri)?setTimeout(()=>o(new Uint8Array(t.Tools.DecodeBase64(i.uri)))):t.Tools.LoadFile(e.rootUrl+i.uri,e=>o(new Uint8Array(e)),void 0,void 0,!0,e=>{e&&s(e.status+" "+e.statusText)})}static CreateTextureAsync(e,n,o,s){const r=e.textures[n];if(r.babylonTexture)return void s(r.babylonTexture);const i=e.samplers[r.sampler],a=i.minFilter===bn.NEAREST_MIPMAP_NEAREST||i.minFilter===bn.NEAREST_MIPMAP_LINEAR||i.minFilter===bn.LINEAR_MIPMAP_NEAREST||i.minFilter===bn.LINEAR_MIPMAP_LINEAR,l=t.Texture.BILINEAR_SAMPLINGMODE,u=null==o?new Blob:new Blob([t.GetBlobBufferSource(o)]),c=URL.createObjectURL(u),d=()=>URL.revokeObjectURL(c),h=new t.Texture(c,e.scene,!a,!0,l,d,d);void 0!==i.wrapS&&(h.wrapU=Cn.GetWrapMode(i.wrapS)),void 0!==i.wrapT&&(h.wrapV=Cn.GetWrapMode(i.wrapT)),h.name=n,r.babylonTexture=h,s(h)}static LoadShaderStringAsync(e,n,o,s){const r=e.shaders[n];if(t.Tools.IsBase64(r.uri)){const e=atob(r.uri.split(",")[1]);o&&o(e)}else t.Tools.LoadFile(e.rootUrl+r.uri,o,void 0,void 0,!1,e=>{e&&s&&s(e.status+" "+e.statusText)})}static LoadMaterialAsync(e,n,o,s){const r=e.materials[n];if(!r.technique)return void(s&&s("No technique found."));const i=e.techniques[r.technique];if(!i){e.scene._blockEntityCollection=!!e.assetContainer;const s=new t.StandardMaterial(n,e.scene);return s._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,s.diffuseColor=new t.Color3(.5,.5,.5),s.sideOrientation=t.Material.CounterClockWiseSideOrientation,void o(s)}const a=e.programs[i.program],l=i.states,u=t.Effect.ShadersStore[a.vertexShader+"VertexShader"],c=t.Effect.ShadersStore[a.fragmentShader+"PixelShader"];let d="",h="";const m=new Rn(u),f=new Rn(c),p={},_=[],g=[],y=[];for(const e in i.uniforms){const t=i.uniforms[e],n=i.parameters[t];if(p[e]=n,!n.semantic||n.node||n.source)n.type===yn.SAMPLER_2D?y.push(e):_.push(e);else{const t=On.indexOf(n.semantic);-1!==t?(_.push(Sn[t]),delete p[e]):_.push(e)}}for(const e in i.attributes){const t=i.attributes[e],n=i.parameters[t];if(n.semantic){const e=Nn(n);e&&g.push(e)}}for(;!m.isEnd()&&m.getNextToken();){if(m.currentToken!==Mn.IDENTIFIER){d+=m.currentString;continue}let e=!1;for(const t in i.attributes){const n=i.attributes[t],o=i.parameters[n];if(m.currentIdentifier===t&&o.semantic){d+=Nn(o),e=!0;break}}e||(d+=Wn(m,i,p))}for(;!f.isEnd()&&f.getNextToken();)f.currentToken===Mn.IDENTIFIER?h+=Wn(f,i,p):h+=f.currentString;const v={vertex:a.vertexShader+n,fragment:a.fragmentShader+n},b={attributes:g,uniforms:_,samplers:y,needAlphaBlending:l&&l.enable&&-1!==l.enable.indexOf(3042)};t.Effect.ShadersStore[a.vertexShader+n+"VertexShader"]=d,t.Effect.ShadersStore[a.fragmentShader+n+"PixelShader"]=h;const x=new t.ShaderMaterial(n,e.scene,v,b);if(x.onError=((e,t,n)=>(o,s)=>{t.dispose(!0),n("Cannot compile program named "+e.name+". Error: "+s+". Default material will be applied")})(a,x,s),x.onCompiled=((e,t,n,o,s,r)=>i=>{((e,t,n,o,s)=>{const r=o.values||n.parameters,i=n.uniforms;for(const n in s){const a=s[n],l=a.type;let u=r[i[n]];if(void 0===u&&(u=a.value),!u)continue;const c=e=>n=>{a.value&&e&&(t.setTexture(e,n),delete s[e])};l===yn.SAMPLER_2D?Xn.LoadTextureAsync(e,o.values?u:a.value,c(n),()=>c(null)):a.value&&Cn.SetUniform(t,n,o.values?u:a.value,l)&&delete s[n]}})(e,t,n,o,s),t.onBind=i=>{((e,t,n,o,s,r,i)=>{const a=r.values||s.parameters;for(const i in n){const l=n[i],u=l.type;if(u===yn.FLOAT_MAT2||u===yn.FLOAT_MAT3||u===yn.FLOAT_MAT4)if(!l.semantic||l.source||l.node){if(l.semantic&&(l.source||l.node)){let e=t.scene.getNodeByName(l.source||l.node||"");if(null===e&&(e=t.scene.getNodeById(l.source||l.node||"")),null===e)continue;Cn.SetMatrix(t.scene,e,l,i,o.getEffect())}}else Cn.SetMatrix(t.scene,e,l,i,o.getEffect());else{const e=a[s.uniforms[i]];if(!e)continue;if(u===yn.SAMPLER_2D){const n=t.textures[r.values?e:l.value].babylonTexture;if(null==n)continue;o.getEffect().setTexture(i,n)}else Cn.SetUniform(o.getEffect(),i,e,u)}}i(o)})(i,e,s,t,n,o,r)}})(e,x,i,r,p,o),x.sideOrientation=t.Material.CounterClockWiseSideOrientation,l&&l.functions){const e=l.functions;e.cullFace&&e.cullFace[0]!==Tn.BACK&&(x.backFaceCulling=!1);const n=e.blendFuncSeparate;n&&(n[0]===An.SRC_ALPHA&&n[1]===An.ONE_MINUS_SRC_ALPHA&&n[2]===An.ONE&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_COMBINE:n[0]===An.ONE&&n[1]===An.ONE&&n[2]===An.ZERO&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_ONEONE:n[0]===An.SRC_ALPHA&&n[1]===An.ONE&&n[2]===An.ZERO&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_ADD:n[0]===An.ZERO&&n[1]===An.ONE_MINUS_SRC_COLOR&&n[2]===An.ONE&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_SUBTRACT:n[0]===An.DST_COLOR&&n[1]===An.ZERO&&n[2]===An.ONE&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_MULTIPLY:n[0]===An.SRC_ALPHA&&n[1]===An.ONE_MINUS_SRC_COLOR&&n[2]===An.ONE&&n[3]===An.ONE&&(x.alphaMode=t.Constants.ALPHA_MAXIMIZED))}}}let qn=class e{static RegisterExtension(n){e.Extensions[n.name]?t.Tools.Error('Tool with the same name "'+n.name+'" already exists'):e.Extensions[n.name]=n}dispose(){}_importMeshAsync(e,n,o,s,r,i,a,l){return n.useRightHandedSystem=!0,Xn.LoadRuntimeAsync(n,o,s,n=>{n.assetContainer=r,n.importOnlyMeshes=!0,""===e?n.importMeshesNames=[]:"string"==typeof e?n.importMeshesNames=[e]:!e||e instanceof Array?(n.importMeshesNames=[],t.Tools.Warn("Argument meshesNames must be of type string or string[]")):n.importMeshesNames=[e],this._createNodes(n);const o=[],s=[];for(const e in n.nodes){const s=n.nodes[e];s.babylonNode instanceof t.AbstractMesh&&o.push(s.babylonNode)}for(const e in n.skins){const o=n.skins[e];o.babylonSkeleton instanceof t.Skeleton&&s.push(o.babylonSkeleton)}this._loadBuffersAsync(n,()=>{this._loadShadersAsync(n,()=>{zn(n),$n(n),!mn.IncrementalLoading&&i&&i(o,s)})}),mn.IncrementalLoading&&i&&i(o,s)},l),!0}importMeshAsync(e,t,n,o,s,r){return new Promise((i,a)=>{this._importMeshAsync(e,t,o,s,n,(e,t)=>{i({meshes:e,particleSystems:[],skeletons:t,animationGroups:[],lights:[],transformNodes:[],geometries:[],spriteManagers:[]})},r,e=>{a(new Error(e))})})}_loadAsync(e,t,n,o,s,r){e.useRightHandedSystem=!0,Xn.LoadRuntimeAsync(e,t,n,e=>{Xn.LoadRuntimeExtensionsAsync(e,()=>{this._createNodes(e),this._loadBuffersAsync(e,()=>{this._loadShadersAsync(e,()=>{zn(e),$n(e),mn.IncrementalLoading||o()})}),mn.IncrementalLoading&&o()},r)},r)}loadAsync(e,t,n,o){return b(this,void 0,void 0,function*(){return yield new Promise((s,r)=>{this._loadAsync(e,t,n,()=>{s()},o,e=>{r(new Error(e))})})})}_loadShadersAsync(e,n){let o=!1;const s=(o,s)=>{Xn.LoadShaderStringAsync(e,o,r=>{r instanceof ArrayBuffer||(e.loadedShaderCount++,r&&(t.Effect.ShadersStore[o+(s.type===gn.VERTEX?"VertexShader":"PixelShader")]=r),e.loadedShaderCount===e.shaderscount&&n())},()=>{t.Tools.Error("Error when loading shader program named "+o+" located at "+s.uri)})};for(const n in e.shaders){o=!0;const r=e.shaders[n];r?s.bind(this,n,r)():t.Tools.Error("No shader named: "+n)}o||n()}_loadBuffersAsync(e,n){let o=!1;const s=(o,s)=>{Xn.LoadBufferAsync(e,o,r=>{e.loadedBufferCount++,r&&(r.byteLength!=e.buffers[o].byteLength&&t.Tools.Error("Buffer named "+o+" is length "+r.byteLength+". Expected: "+s.byteLength),e.loadedBufferViews[o]=r),e.loadedBufferCount===e.buffersCount&&n()},()=>{t.Tools.Error("Error when loading buffer named "+o+" located at "+s.uri)})};for(const n in e.buffers){o=!0;const r=e.buffers[n];r?s.bind(this,n,r)():t.Tools.Error("No buffer named: "+n)}o||n()}_createNodes(e){let t=e.currentScene;if(t)for(let n=0;n<t.nodes.length;n++)Un(e,t.nodes[n],null);else for(const n in e.scenes){t=e.scenes[n];for(let n=0;n<t.nodes.length;n++)Un(e,t.nodes[n],null)}}};qn.Extensions={};class Xn{constructor(e){this._name=e}get name(){return this._name}loadRuntimeAsync(e,t,n,o,s){return!1}loadRuntimeExtensionsAsync(e,t,n){return!1}loadBufferAsync(e,t,n,o,s){return!1}loadTextureBufferAsync(e,t,n,o){return!1}createTextureAsync(e,t,n,o,s){return!1}loadShaderStringAsync(e,t,n,o){return!1}loadMaterialAsync(e,t,n,o){return!1}static LoadRuntimeAsync(e,t,n,o,s){Xn._ApplyExtensions(r=>r.loadRuntimeAsync(e,t,n,o,s),()=>{setTimeout(()=>{o&&o(jn.CreateRuntime(t.json,e,n))})})}static LoadRuntimeExtensionsAsync(e,t,n){Xn._ApplyExtensions(o=>o.loadRuntimeExtensionsAsync(e,t,n),()=>{setTimeout(()=>{t()})})}static LoadBufferAsync(e,t,n,o,s){Xn._ApplyExtensions(r=>r.loadBufferAsync(e,t,n,o,s),()=>{jn.LoadBufferAsync(e,t,n,o,s)})}static LoadTextureAsync(e,t,n,o){Xn._LoadTextureBufferAsync(e,t,s=>{s&&Xn._CreateTextureAsync(e,t,s,n,o)},o)}static LoadShaderStringAsync(e,t,n,o){Xn._ApplyExtensions(s=>s.loadShaderStringAsync(e,t,n,o),()=>{jn.LoadShaderStringAsync(e,t,n,o)})}static LoadMaterialAsync(e,t,n,o){Xn._ApplyExtensions(s=>s.loadMaterialAsync(e,t,n,o),()=>{jn.LoadMaterialAsync(e,t,n,o)})}static _LoadTextureBufferAsync(e,t,n,o){Xn._ApplyExtensions(s=>s.loadTextureBufferAsync(e,t,n,o),()=>{jn.LoadTextureBufferAsync(e,t,n,o)})}static _CreateTextureAsync(e,t,n,o,s){Xn._ApplyExtensions(r=>r.createTextureAsync(e,t,n,o,s),()=>{jn.CreateTextureAsync(e,t,n,o)})}static _ApplyExtensions(e,t){for(const t in qn.Extensions)if(e(qn.Extensions[t]))return;t()}}mn._CreateGLTF1Loader=()=>new qn;class Yn extends Xn{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,n,o){const s=t.json.extensionsUsed;return!(!s||-1===s.indexOf(this.name)||!t.bin||(this._bin=t.bin,o(jn.CreateRuntime(t.json,e,n)),0))}loadBufferAsync(e,t,n,o){return-1!==e.extensionsUsed.indexOf(this.name)&&"binary_glTF"===t&&(this._bin.readAsync(0,this._bin.byteLength).then(n,e=>o(e.message)),!0)}loadTextureBufferAsync(e,t,n){const o=e.textures[t],s=e.images[o.source];if(!s.extensions||!(this.name in s.extensions))return!1;const r=s.extensions[this.name],i=e.bufferViews[r.bufferView];return n(Cn.GetBufferFromBufferView(e,i,0,i.byteLength,_n.UNSIGNED_BYTE)),!0}loadShaderStringAsync(e,t,n){const o=e.shaders[t];if(!o.extensions||!(this.name in o.extensions))return!1;const s=o.extensions[this.name],r=e.bufferViews[s.bufferView],i=Cn.GetBufferFromBufferView(e,r,0,r.byteLength,_n.UNSIGNED_BYTE);return setTimeout(()=>{const e=Cn.DecodeBufferToText(i);n(e)}),!0}}qn.RegisterExtension(new Yn);class Qn extends Xn{constructor(){super("KHR_materials_common")}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;const n=e.extensions[this.name];if(!n)return!1;const o=n.lights;if(o)for(const n in o){const s=o[n];switch(s.type){case"ambient":{const n=new t.HemisphericLight(s.name,new t.Vector3(0,1,0),e.scene),o=s.ambient;o&&(n.diffuse=t.Color3.FromArray(o.color||[1,1,1]));break}case"point":{const n=new t.PointLight(s.name,new t.Vector3(10,10,10),e.scene),o=s.point;o&&(n.diffuse=t.Color3.FromArray(o.color||[1,1,1]));break}case"directional":{const n=new t.DirectionalLight(s.name,new t.Vector3(0,-1,0),e.scene),o=s.directional;o&&(n.diffuse=t.Color3.FromArray(o.color||[1,1,1]));break}case"spot":{const n=s.spot;n&&(new t.SpotLight(s.name,new t.Vector3(0,10,0),new t.Vector3(0,-1,0),n.fallOffAngle||Math.PI,n.fallOffExponent||0,e.scene).diffuse=t.Color3.FromArray(n.color||[1,1,1]));break}default:t.Tools.Warn('GLTF Material Common extension: light type "'+s.type+"” not supported")}}return!1}loadMaterialAsync(e,n,o,s){const r=e.materials[n];if(!r||!r.extensions)return!1;const i=r.extensions[this.name];if(!i)return!1;const a=new t.StandardMaterial(n,e.scene);return a.sideOrientation=t.Material.CounterClockWiseSideOrientation,"CONSTANT"===i.technique&&(a.disableLighting=!0),a.backFaceCulling=void 0!==i.doubleSided&&!i.doubleSided,a.alpha=void 0===i.values.transparency?1:i.values.transparency,a.specularPower=void 0===i.values.shininess?0:i.values.shininess,"string"==typeof i.values.ambient?this._loadTexture(e,i.values.ambient,a,"ambientTexture",s):a.ambientColor=t.Color3.FromArray(i.values.ambient||[0,0,0]),"string"==typeof i.values.diffuse?this._loadTexture(e,i.values.diffuse,a,"diffuseTexture",s):a.diffuseColor=t.Color3.FromArray(i.values.diffuse||[0,0,0]),"string"==typeof i.values.emission?this._loadTexture(e,i.values.emission,a,"emissiveTexture",s):a.emissiveColor=t.Color3.FromArray(i.values.emission||[0,0,0]),"string"==typeof i.values.specular?this._loadTexture(e,i.values.specular,a,"specularTexture",s):a.specularColor=t.Color3.FromArray(i.values.specular||[0,0,0]),!0}_loadTexture(e,t,n,o,s){jn.LoadTextureBufferAsync(e,t,s=>{jn.CreateTextureAsync(e,t,s,e=>n[o]=e)},s)}}qn.RegisterExtension(new Qn);var Zn={__proto__:null,get EBlendingFunction(){return An},get EComponentType(){return _n},get ECullingType(){return Tn},get EParameterType(){return yn},get EShaderType(){return gn},get ETextureFilterType(){return bn},get ETextureFormat(){return xn},get ETextureWrapMode(){return vn},GLTFBinaryExtension:Yn,GLTFLoader:qn,GLTFLoaderBase:jn,GLTFLoaderExtension:Xn,GLTFMaterialsCommonExtension:Qn,GLTFUtils:Cn};const Jn=new Map,eo=Jn;function to(e,n,o){no(e)&&t.Logger.Warn(`Extension with the name '${e}' already exists`),Jn.set(e,{isGLTFExtension:n,factory:o})}function no(e){return Jn.delete(e)}const oo=[{regex:new RegExp("^/nodes/\\d+/extensions/")}];class so{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t,n=this._gltf,o=this._infoTree;if(!e.startsWith("/"))throw new Error("Path must start with a /");const s=e.split("/");if(s.shift(),s[s.length-1].includes(".length")){const e=s[s.length-1].split(".");s.pop(),s.push(...e)}let r=!1;for(const i of s){const s="length"===i;if(s&&!o.__array__)throw new Error(`Path ${e} is invalid`);if(o.__ignoreObjectTree__&&(r=!0),o.__array__&&!s)o=o.__array__;else if(o=o[i],!o)throw new Error(`Path ${e} is invalid`);if(!r)if(void 0===n){if(!oo.find(t=>t.regex.test(e)))throw new Error(`Path ${e} is invalid`)}else s||(n=null==n?void 0:n[i]);(o.__target__||s)&&(t=n)}return{object:t,info:o}}}function ro(e,t,n,o){const s=io(e);return o?s[n][o]:s[n]}function io(e,n,o){var s,r,i;return null===(i=null===(s=e._data)||void 0===s?void 0:s[null!==(r=null==o?void 0:o.fillMode)&&void 0!==r?r:t.Constants.MATERIAL_TriangleFillMode])||void 0===i?void 0:i.babylonMaterial}function ao(e,n){return{offset:{componentsCount:2,type:"Vector2",get:(o,s,r)=>{const i=ro(o,0,e,n);return new t.Vector2(null==i?void 0:i.uOffset,null==i?void 0:i.vOffset)},getTarget:io,set:(t,o,s,r)=>{const i=ro(o,0,e,n);i.uOffset=t.x,i.vOffset=t.y},getPropertyName:[()=>`${e}${n?"."+n:""}.uOffset`,()=>`${e}${n?"."+n:""}.vOffset`]},rotation:{type:"number",get:(t,o,s)=>{var r;return null===(r=ro(t,0,e,n))||void 0===r?void 0:r.wAng},getTarget:io,set:(t,o,s,r)=>ro(o,0,e,n).wAng=t,getPropertyName:[()=>`${e}${n?"."+n:""}.wAng`]},scale:{componentsCount:2,type:"Vector2",get:(o,s,r)=>{const i=ro(o,0,e,n);return new t.Vector2(null==i?void 0:i.uScale,null==i?void 0:i.vScale)},getTarget:io,set:(t,o,s,r)=>{const i=ro(o,0,e,n);i.uScale=t.x,i.vScale=t.y},getPropertyName:[()=>`${e}${n?"."+n:""}.uScale`,()=>`${e}${n?"."+n:""}.vScale`]}}}const lo={cameras:{__array__:{__target__:!0,orthographic:{xmag:{componentsCount:2,type:"Vector2",get:e=>{var n,o,s,r;return new t.Vector2(null!==(o=null===(n=e._babylonCamera)||void 0===n?void 0:n.orthoLeft)&&void 0!==o?o:0,null!==(r=null===(s=e._babylonCamera)||void 0===s?void 0:s.orthoRight)&&void 0!==r?r:0)},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.orthoLeft=e.x,t._babylonCamera.orthoRight=e.y)},getTarget:e=>e,getPropertyName:[()=>"orthoLeft",()=>"orthoRight"]},ymag:{componentsCount:2,type:"Vector2",get:e=>{var n,o,s,r;return new t.Vector2(null!==(o=null===(n=e._babylonCamera)||void 0===n?void 0:n.orthoBottom)&&void 0!==o?o:0,null!==(r=null===(s=e._babylonCamera)||void 0===s?void 0:s.orthoTop)&&void 0!==r?r:0)},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.orthoBottom=e.x,t._babylonCamera.orthoTop=e.y)},getTarget:e=>e,getPropertyName:[()=>"orthoBottom",()=>"orthoTop"]},zfar:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.maxZ},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.maxZ=e)},getTarget:e=>e,getPropertyName:[()=>"maxZ"]},znear:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.minZ},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.minZ=e)},getTarget:e=>e,getPropertyName:[()=>"minZ"]}},perspective:{aspectRatio:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.getEngine().getAspectRatio(e._babylonCamera)},getTarget:e=>e,getPropertyName:[()=>"aspectRatio"],isReadOnly:!0},yfov:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.fov},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.fov=e)},getTarget:e=>e,getPropertyName:[()=>"fov"]},zfar:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.maxZ},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.maxZ=e)},getTarget:e=>e,getPropertyName:[()=>"maxZ"]},znear:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.minZ},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.minZ=e)},getTarget:e=>e,getPropertyName:[()=>"minZ"]}}}},nodes:{length:{type:"number",get:e=>e.length,getTarget:e=>e.map(e=>e._babylonTransformNode),getPropertyName:[()=>"length"]},__array__:{__target__:!0,translation:{type:"Vector3",get:e=>{var t;return null===(t=e._babylonTransformNode)||void 0===t?void 0:t.position},set:(e,t)=>{var n;return null===(n=t._babylonTransformNode)||void 0===n?void 0:n.position.copyFrom(e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"position"]},rotation:{type:"Quaternion",get:e=>{var t;return null===(t=e._babylonTransformNode)||void 0===t?void 0:t.rotationQuaternion},set:(e,t)=>{var n,o;return null===(o=null===(n=t._babylonTransformNode)||void 0===n?void 0:n.rotationQuaternion)||void 0===o?void 0:o.copyFrom(e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"rotationQuaternion"]},scale:{type:"Vector3",get:e=>{var t;return null===(t=e._babylonTransformNode)||void 0===t?void 0:t.scaling},set:(e,t)=>{var n;return null===(n=t._babylonTransformNode)||void 0===n?void 0:n.scaling.copyFrom(e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"scaling"]},weights:{length:{type:"number",get:e=>e._numMorphTargets,getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"influence"]},__array__:{__target__:!0,type:"number",get:(e,t)=>{var n,o;return void 0!==t?null===(o=null===(n=e._primitiveBabylonMeshes)||void 0===n?void 0:n[0].morphTargetManager)||void 0===o?void 0:o.getTarget(t).influence:void 0},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"influence"]},type:"number[]",get:(e,t)=>[0],getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"influence"]},matrix:{type:"Matrix",get:e=>{var n,o,s;return t.Matrix.Compose(null===(n=e._babylonTransformNode)||void 0===n?void 0:n.scaling,null===(o=e._babylonTransformNode)||void 0===o?void 0:o.rotationQuaternion,null===(s=e._babylonTransformNode)||void 0===s?void 0:s.position)},getTarget:e=>e._babylonTransformNode,isReadOnly:!0},globalMatrix:{type:"Matrix",get:e=>{var n,o,s,r,i,a,l;const u=t.Matrix.Identity();let c=e.parent;for(;c&&c.parent;)c=c.parent;const d=(null===(n=e._babylonTransformNode)||void 0===n?void 0:n.position._isDirty)||(null===(s=null===(o=e._babylonTransformNode)||void 0===o?void 0:o.rotationQuaternion)||void 0===s?void 0:s._isDirty)||(null===(r=e._babylonTransformNode)||void 0===r?void 0:r.scaling._isDirty);if(c){const t=null===(i=c._babylonTransformNode)||void 0===i?void 0:i.computeWorldMatrix(!0).invert();t&&(null===(l=null===(a=e._babylonTransformNode)||void 0===a?void 0:a.computeWorldMatrix(d))||void 0===l||l.multiplyToRef(t,u))}else e._babylonTransformNode&&u.copyFrom(e._babylonTransformNode.computeWorldMatrix(d));return u},getTarget:e=>e._babylonTransformNode,isReadOnly:!0},extensions:{EXT_lights_ies:{multiplier:{type:"number",get:e=>{var n,o;return null===(o=null===(n=e._babylonTransformNode)||void 0===n?void 0:n.getChildren(e=>e instanceof t.SpotLight,!0)[0])||void 0===o?void 0:o.intensity},getTarget:e=>{var n;return null===(n=e._babylonTransformNode)||void 0===n?void 0:n.getChildren(e=>e instanceof t.SpotLight,!0)[0]},set:(e,n)=>{if(n._babylonTransformNode){const o=n._babylonTransformNode.getChildren(e=>e instanceof t.SpotLight,!0)[0];o&&(o.intensity=e)}}},color:{type:"Color3",get:e=>{var n,o;return null===(o=null===(n=e._babylonTransformNode)||void 0===n?void 0:n.getChildren(e=>e instanceof t.SpotLight,!0)[0])||void 0===o?void 0:o.diffuse},getTarget:e=>{var n;return null===(n=e._babylonTransformNode)||void 0===n?void 0:n.getChildren(e=>e instanceof t.SpotLight,!0)[0]},set:(e,n)=>{if(n._babylonTransformNode){const o=n._babylonTransformNode.getChildren(e=>e instanceof t.SpotLight,!0)[0];o&&(o.diffuse=e)}}}},KHR_node_visibility:{visible:{type:"boolean",get:e=>!!e._primitiveBabylonMeshes&&e._primitiveBabylonMeshes[0].isVisible,getTarget:()=>{},set:(e,t)=>{t._primitiveBabylonMeshes&&t._primitiveBabylonMeshes.forEach(t=>t.isVisible=e)}}}}}},materials:{__array__:{__target__:!0,emissiveFactor:{type:"Color3",get:(e,t,n)=>io(e,0,n).emissiveColor,set:(e,t,n,o)=>io(t,0,o).emissiveColor.copyFrom(e),getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"emissiveColor"]},emissiveTexture:{extensions:{KHR_texture_transform:ao("emissiveTexture")}},normalTexture:{scale:{type:"number",get:(e,t,n)=>{var o;return null===(o=ro(e,0,"bumpTexture"))||void 0===o?void 0:o.level},set:(e,t,n,o)=>{const s=ro(t,0,"bumpTexture");s&&(s.level=e)},getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"level"]},extensions:{KHR_texture_transform:ao("bumpTexture")}},occlusionTexture:{strength:{type:"number",get:(e,t,n)=>io(e,0,n).ambientTextureStrength,set:(e,t,n,o)=>{const s=io(t,0,o);s&&(s.ambientTextureStrength=e)},getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"ambientTextureStrength"]},extensions:{KHR_texture_transform:ao("ambientTexture")}},pbrMetallicRoughness:{baseColorFactor:{type:"Color4",get:(e,n,o)=>{const s=io(e,0,o);return t.Color4.FromColor3(s.albedoColor,s.alpha)},set:(e,t,n,o)=>{const s=io(t,0,o);s.albedoColor.set(e.r,e.g,e.b),s.alpha=e.a},getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"albedoColor",()=>"alpha"]},baseColorTexture:{extensions:{KHR_texture_transform:ao("albedoTexture")}},metallicFactor:{type:"number",get:(e,t,n)=>io(e,0,n).metallic,set:(e,t,n,o)=>{const s=io(t,0,o);s&&(s.metallic=e)},getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"metallic"]},roughnessFactor:{type:"number",get:(e,t,n)=>io(e,0,n).roughness,set:(e,t,n,o)=>{const s=io(t,0,o);s&&(s.roughness=e)},getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"roughness"]},metallicRoughnessTexture:{extensions:{KHR_texture_transform:ao("metallicTexture")}}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:{type:"number",get:(e,t,n)=>io(e,0,n).anisotropy.intensity,set:(e,t,n,o)=>{io(t,0,o).anisotropy.intensity=e},getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"anisotropy.intensity"]},anisotropyRotation:{type:"number",get:(e,t,n)=>io(e,0,n).anisotropy.angle,set:(e,t,n,o)=>{io(t,0,o).anisotropy.angle=e},getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"anisotropy.angle"]},anisotropyTexture:{extensions:{KHR_texture_transform:ao("anisotropy","texture")}}},KHR_materials_clearcoat:{clearcoatFactor:{type:"number",get:(e,t,n)=>io(e,0,n).clearCoat.intensity,set:(e,t,n,o)=>{io(t,0,o).clearCoat.intensity=e},getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"clearCoat.intensity"]},clearcoatRoughnessFactor:{type:"number",get:(e,t,n)=>io(e,0,n).clearCoat.roughness,set:(e,t,n,o)=>{io(t,0,o).clearCoat.roughness=e},getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"clearCoat.roughness"]},clearcoatTexture:{extensions:{KHR_texture_transform:ao("clearCoat","texture")}},clearcoatNormalTexture:{scale:{type:"number",get:(e,t,n)=>{var o;return null===(o=io(e,0,n).clearCoat.bumpTexture)||void 0===o?void 0:o.level},getTarget:io,set:(e,t,n,o)=>io(t,0,o).clearCoat.bumpTexture.level=e},extensions:{KHR_texture_transform:ao("clearCoat","bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:ao("clearCoat","textureRoughness")}}},KHR_materials_dispersion:{dispersion:{type:"number",get:(e,t,n)=>io(e,0,n).subSurface.dispersion,getTarget:io,set:(e,t,n,o)=>io(t,0,o).subSurface.dispersion=e}},KHR_materials_emissive_strength:{emissiveStrength:{type:"number",get:(e,t,n)=>io(e,0,n).emissiveIntensity,getTarget:io,set:(e,t,n,o)=>io(t,0,o).emissiveIntensity=e}},KHR_materials_ior:{ior:{type:"number",get:(e,t,n)=>io(e,0,n).indexOfRefraction,getTarget:io,set:(e,t,n,o)=>io(t,0,o).indexOfRefraction=e}},KHR_materials_iridescence:{iridescenceFactor:{type:"number",get:(e,t,n)=>io(e,0,n).iridescence.intensity,getTarget:io,set:(e,t,n,o)=>io(t,0,o).iridescence.intensity=e},iridescenceIor:{type:"number",get:(e,t,n)=>io(e,0,n).iridescence.indexOfRefraction,getTarget:io,set:(e,t,n,o)=>io(t,0,o).iridescence.indexOfRefraction=e},iridescenceTexture:{extensions:{KHR_texture_transform:ao("iridescence","texture")}},iridescenceThicknessMaximum:{type:"number",get:(e,t,n)=>io(e,0,n).iridescence.maximumThickness,getTarget:io,set:(e,t,n,o)=>io(t,0,o).iridescence.maximumThickness=e},iridescenceThicknessMinimum:{type:"number",get:(e,t,n)=>io(e,0,n).iridescence.minimumThickness,getTarget:io,set:(e,t,n,o)=>io(t,0,o).iridescence.minimumThickness=e},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:ao("iridescence","thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:{type:"Color3",get:(e,t,n)=>io(e,0,n).sheen.color,getTarget:io,set:(e,t,n,o)=>io(t,0,o).sheen.color.copyFrom(e)},sheenColorTexture:{extensions:{KHR_texture_transform:ao("sheen","texture")}},sheenRoughnessFactor:{type:"number",get:(e,t,n)=>io(e,0,n).sheen.intensity,getTarget:io,set:(e,t,n,o)=>io(t,0,o).sheen.intensity=e},sheenRoughnessTexture:{extensions:{KHR_texture_transform:ao("sheen","thicknessTexture")}}},KHR_materials_specular:{specularFactor:{type:"number",get:(e,t,n)=>io(e,0,n).metallicF0Factor,getTarget:io,set:(e,t,n,o)=>io(t,0,o).metallicF0Factor=e,getPropertyName:[()=>"metallicF0Factor"]},specularColorFactor:{type:"Color3",get:(e,t,n)=>io(e,0,n).metallicReflectanceColor,getTarget:io,set:(e,t,n,o)=>io(t,0,o).metallicReflectanceColor.copyFrom(e),getPropertyName:[()=>"metallicReflectanceColor"]},specularTexture:{extensions:{KHR_texture_transform:ao("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:ao("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:{type:"number",get:(e,t,n)=>io(e,0,n).subSurface.refractionIntensity,getTarget:io,set:(e,t,n,o)=>io(t,0,o).subSurface.refractionIntensity=e,getPropertyName:[()=>"subSurface.refractionIntensity"]},transmissionTexture:{extensions:{KHR_texture_transform:ao("subSurface","refractionIntensityTexture")}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:{type:"number",get:(e,t,n)=>io(e,0,n).subSurface.translucencyIntensity,getTarget:io,set:(e,t,n,o)=>io(t,0,o).subSurface.translucencyIntensity=e},diffuseTransmissionTexture:{extensions:{KHR_texture_transform:ao("subSurface","translucencyIntensityTexture")}},diffuseTransmissionColorFactor:{type:"Color3",get:(e,t,n)=>io(e,0,n).subSurface.translucencyColor,getTarget:io,set:(e,t,n,o)=>{var s;return e&&(null===(s=io(t,0,o).subSurface.translucencyColor)||void 0===s?void 0:s.copyFrom(e))}},diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:ao("subSurface","translucencyColorTexture")}}},KHR_materials_volume:{attenuationColor:{type:"Color3",get:(e,t,n)=>io(e,0,n).subSurface.tintColor,getTarget:io,set:(e,t,n,o)=>io(t,0,o).subSurface.tintColor.copyFrom(e)},attenuationDistance:{type:"number",get:(e,t,n)=>io(e,0,n).subSurface.tintColorAtDistance,getTarget:io,set:(e,t,n,o)=>io(t,0,o).subSurface.tintColorAtDistance=e},thicknessFactor:{type:"number",get:(e,t,n)=>io(e,0,n).subSurface.maximumThickness,getTarget:io,set:(e,t,n,o)=>io(t,0,o).subSurface.maximumThickness=e},thicknessTexture:{extensions:{KHR_texture_transform:ao("subSurface","thicknessTexture")}}}}}},extensions:{KHR_lights_punctual:{lights:{length:{type:"number",get:e=>e.length,getTarget:e=>e.map(e=>e._babylonLight),getPropertyName:[e=>"length"]},__array__:{__target__:!0,color:{type:"Color3",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.diffuse},set:(e,t)=>{var n;return null===(n=t._babylonLight)||void 0===n?void 0:n.diffuse.copyFrom(e)},getTarget:e=>e._babylonLight,getPropertyName:[e=>"diffuse"]},intensity:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.intensity},set:(e,t)=>t._babylonLight?t._babylonLight.intensity=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"intensity"]},range:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.range},set:(e,t)=>t._babylonLight?t._babylonLight.range=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"range"]},spot:{innerConeAngle:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.innerAngle},set:(e,t)=>t._babylonLight?t._babylonLight.innerAngle=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"innerConeAngle"]},outerConeAngle:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.angle},set:(e,t)=>t._babylonLight?t._babylonLight.angle=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"outerConeAngle"]}}}}},EXT_lights_area:{lights:{length:{type:"number",get:e=>e.length,getTarget:e=>e.map(e=>e._babylonLight),getPropertyName:[e=>"length"]},__array__:{__target__:!0,color:{type:"Color3",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.diffuse},set:(e,t)=>{var n;return null===(n=t._babylonLight)||void 0===n?void 0:n.diffuse.copyFrom(e)},getTarget:e=>e._babylonLight,getPropertyName:[e=>"diffuse"]},intensity:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.intensity},set:(e,t)=>t._babylonLight?t._babylonLight.intensity=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"intensity"]},size:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.height},set:(e,t)=>t._babylonLight?t._babylonLight.height=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"size"]},rect:{aspect:{type:"number",get:e=>{var t,n;return(null===(t=e._babylonLight)||void 0===t?void 0:t.width)/(null===(n=e._babylonLight)||void 0===n?void 0:n.height)},set:(e,t)=>t._babylonLight?t._babylonLight.width=e*t._babylonLight.height:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"aspect"]}}}}},EXT_lights_ies:{lights:{length:{type:"number",get:e=>e.length,getTarget:e=>e.map(e=>e._babylonLight),getPropertyName:[e=>"length"]}}},EXT_lights_image_based:{lights:{length:{type:"number",get:e=>e.length,getTarget:e=>e.map(e=>e._babylonTexture),getPropertyName:[e=>"length"]},__array__:{__target__:!0,intensity:{type:"number",get:e=>{var t;return null===(t=e._babylonTexture)||void 0===t?void 0:t.level},set:(e,t)=>{t._babylonTexture&&(t._babylonTexture.level=e)},getTarget:e=>e._babylonTexture},rotation:{type:"Quaternion",get:e=>{var n;return e._babylonTexture&&t.Quaternion.FromRotationMatrix(null===(n=e._babylonTexture)||void 0===n?void 0:n.getReflectionTextureMatrix())},set:(e,n)=>{var o;n._babylonTexture&&((null===(o=n._babylonTexture.getScene())||void 0===o?void 0:o.useRightHandedSystem)||(e=t.Quaternion.Inverse(e)),t.Matrix.FromQuaternionToRef(e,n._babylonTexture.getReflectionTextureMatrix()))},getTarget:e=>e._babylonTexture}}}}},animations:{length:{type:"number",get:e=>e.length,getTarget:e=>e.map(e=>e._babylonAnimationGroup),getPropertyName:[()=>"length"]},__array__:{}},meshes:{length:{type:"number",get:e=>e.length,getTarget:e=>e.map(e=>{var t;return null===(t=e.primitives[0]._instanceData)||void 0===t?void 0:t.babylonSourceMesh}),getPropertyName:[()=>"length"]},__array__:{}}};function uo(e){return new so(e,lo)}function co(e){const t=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let n=lo;for(const e of t)e&&(n=n[e]);if(n&&n.type&&n.get)return n}function ho(e,t){const n=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let o=lo;for(const e of n)e&&(o=o[e]);o&&o.type&&o.get&&(o.interpolation=t)}function mo(e,t){const n=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let o=lo;for(const e of n)if(e){if(!o[e]){if("?"===e){o.__ignoreObjectTree__=!0;continue}o[e]={},"__array__"===e&&(o[e].__target__=!0)}o=o[e]}Object.assign(o,t)}const fo=new t.Lazy(()=>Promise.resolve(BABYLON)),po=new t.Lazy(()=>Promise.resolve().then(function(){return Oo}));class _o{static Get(e,t,n){if(!t||null==n||!t[n])throw new Error(`${e}: Failed to find index (${n})`);return t[n]}static TryGet(e,t){return e&&null!=t&&e[t]?e[t]:null}static Assign(e){if(e)for(let t=0;t<e.length;t++)e[t].index=t}}function go(e){if(e.min&&e.max){const n=e.min,o=e.max,s=t.TmpVectors.Vector3[0].copyFromFloats(n[0],n[1],n[2]),r=t.TmpVectors.Vector3[1].copyFromFloats(o[0],o[1],o[2]);if(e.normalized&&5126!==e.componentType){let t=1;switch(e.componentType){case 5120:t=127;break;case 5121:t=255;break;case 5122:t=32767;break;case 5123:t=65535}const n=1/t;s.scaleInPlace(n),r.scaleInPlace(n)}return new t.BoundingInfo(s,r)}return null}class yo{isMatchingMaterialType(e){if(!e)return!1;const t=Array.from(this._pbrMaterialImpls.values());for(const n of t)if(e instanceof n.materialClass)return!0;return!1}static RegisterExtension(e,t){to(e,!1,t)}static UnregisterExtension(e){return no(e)}get gltf(){if(!this._gltf)throw new Error("glTF JSON is not available");return this._gltf}get bin(){return this._bin}get parent(){return this._parent}get babylonScene(){if(!this._babylonScene)throw new Error("Scene is not available");return this._babylonScene}get rootBabylonMesh(){return this._rootBabylonMesh}get rootUrl(){return this._rootUrl}constructor(e){this._completePromises=new Array,this._assetContainer=null,this._babylonLights=[],this._disableInstancedMesh=0,this._allMaterialsDirtyRequired=!1,this._skipStartAnimationStep=!1,this._extensions=new Array,this._disposed=!1,this._rootUrl=null,this._fileName=null,this._uniqueRootUrl=null,this._bin=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions=new Array,this._materialAdapterCache=new WeakMap,this._materialAdapters=new Set,this._pbrMaterialImpls=new Map,this._parent=e}_getOrCreateMaterialAdapter(e){let t=this._materialAdapterCache.get(e);if(!t){const n=Array.from(this._pbrMaterialImpls.values());for(const o of n)if(e instanceof o.materialClass){t=new o.adapterClass(e);break}if(!t)throw new Error("Appropriate material adapter class not found");const o=t;this._materialAdapterCache.set(e,o),this._materialAdapters.add(o)}return t}dispose(){this._disposed||(this._disposed=!0,this._completePromises.length=0,this._extensions.forEach(e=>e.dispose&&e.dispose()),this._extensions.length=0,this._materialAdapters.clear(),this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose())}importMeshAsync(e,t,n,o,s,r){return b(this,arguments,void 0,function*(e,t,n,o,s,r,i=""){return yield Promise.resolve().then(()=>b(this,void 0,void 0,function*(){this._babylonScene=t,this._assetContainer=n,this._loadData(o);let r=null;if(e){const t={};if(this._gltf.nodes)for(const e of this._gltf.nodes)e.name&&(t[e.name]=e.index);r=(e instanceof Array?e:[e]).map(e=>{const n=t[e];if(void 0===n)throw new Error(`Failed to find node '${e}'`);return n})}return yield this._loadAsync(s,i,r,()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]}))}))})}loadAsync(e,t,n,o){return b(this,arguments,void 0,function*(e,t,n,o,s=""){return this._babylonScene=e,this._loadData(t),yield this._loadAsync(n,s,null,()=>{})})}_loadAsync(n,o,s,r){return b(this,void 0,void 0,function*(){return yield Promise.resolve().then(()=>b(this,void 0,void 0,function*(){var i;if(this._rootUrl=n,this._uniqueRootUrl=!n.startsWith("file:")&&o?n:`${n}${Date.now()}/`,this._fileName=o,this._allMaterialsDirtyRequired=!1,yield this._loadExtensionsAsync(),!this.parent.skipMaterials){const e=this.parent.useOpenPBR||this.isExtensionUsed("KHR_materials_openpbr");let t=!1;this.parent.useOpenPBR?(null===(i=this._gltf.materials)||void 0===i?void 0:i.length)&&this._gltf.materials.some(e=>{var t;return!(null===(t=e.extensions)||void 0===t?void 0:t.KHR_materials_openpbr)})&&(t=!0):t=!0;const n=[];e&&!this._pbrMaterialImpls.has("openpbr")&&n.push(Promise.all([Promise.resolve(BABYLON),Promise.resolve().then(function(){return Fo})]).then(([{OpenPBRMaterial:e,RegisterOpenpbrMaterial:t},{OpenPBRMaterialLoadingAdapter:n}])=>{t(),this._pbrMaterialImpls.set("openpbr",{materialClass:e,adapterClass:n})})),t&&!this._pbrMaterialImpls.has("pbr")&&n.push(Promise.all([Promise.resolve(BABYLON),Promise.resolve().then(function(){return Lo})]).then(([{PBRMaterial:e,RegisterPbrMaterial:t},{PBRMaterialLoadingAdapter:n}])=>{t(),this._pbrMaterialImpls.set("pbr",{materialClass:e,adapterClass:n})})),yield Promise.all(n)}const a=`${e.GLTFLoaderState[e.GLTFLoaderState.LOADING]} => ${e.GLTFLoaderState[e.GLTFLoaderState.READY]}`,l=`${e.GLTFLoaderState[e.GLTFLoaderState.LOADING]} => ${e.GLTFLoaderState[e.GLTFLoaderState.COMPLETE]}`;this._parent._startPerformanceCounter(a),this._parent._startPerformanceCounter(l),this._parent._setState(e.GLTFLoaderState.LOADING),this._extensionsOnLoading();const u=new Array,c=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials)if(s)u.push(this.loadSceneAsync("/nodes",{nodes:s,index:-1}));else if(null!=this._gltf.scene||this._gltf.scenes&&this._gltf.scenes[0]){const e=_o.Get("/scene",this._gltf.scenes,this._gltf.scene||0);u.push(this.loadSceneAsync(`/scenes/${e.index}`,e))}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let e=0;e<this._gltf.materials.length;++e){const n=this._gltf.materials[e],o="/materials/"+e,s=t.Material.TriangleFillMode;u.push(this._loadMaterialAsync(o,n,null,s,()=>{}))}this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=c:this._babylonScene._forceBlockMaterialDirtyMechanism(c),this._parent.compileMaterials&&u.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&u.push(this._compileShadowGeneratorsAsync());const d=Promise.all(u).then(()=>{this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0);for(const e of this._babylonScene.materials){const t=e;void 0!==t.maxSimultaneousLights&&(t.maxSimultaneousLights=Math.max(t.maxSimultaneousLights,this._babylonScene.lights.length))}for(const e of Array.from(this._materialAdapters))this._completePromises.push(e.finalizeAsync(this));return this._extensionsOnReady(),this._parent._setState(e.GLTFLoaderState.READY),this._skipStartAnimationStep||this._startAnimations(),r()});return yield d.then(n=>(this._parent._endPerformanceCounter(a),t.Tools.SetImmediate(()=>{this._disposed||Promise.all(this._completePromises).then(()=>{this._parent._endPerformanceCounter(l),this._parent._setState(e.GLTFLoaderState.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()},e=>{this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()})}),n))})).catch(e=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()),e})})}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){const n=this._gltf.buffers;if(n&&n[0]&&!n[0].uri){const o=n[0];(o.byteLength<e.bin.byteLength-3||o.byteLength>e.bin.byteLength)&&t.Logger.Warn(`Binary buffer length (${o.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else t.Logger.Warn("Unexpected BIN chunk")}}_setupData(){if(_o.Assign(this._gltf.accessors),_o.Assign(this._gltf.animations),_o.Assign(this._gltf.buffers),_o.Assign(this._gltf.bufferViews),_o.Assign(this._gltf.cameras),_o.Assign(this._gltf.images),_o.Assign(this._gltf.materials),_o.Assign(this._gltf.meshes),_o.Assign(this._gltf.nodes),_o.Assign(this._gltf.samplers),_o.Assign(this._gltf.scenes),_o.Assign(this._gltf.skins),_o.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const t of this._gltf.nodes)if(t.children)for(const n of t.children)e[n]=t.index;const t=this._createRootNode();for(const n of this._gltf.nodes){const o=e[n.index];n.parent=void 0===o?t:this._gltf.nodes[o]}}}_loadExtensionsAsync(){return b(this,void 0,void 0,function*(){var e;const n=[];if(eo.forEach((e,o)=>{var s;!1===(null===(s=this.parent.extensionOptions[o])||void 0===s?void 0:s.enabled)?e.isGLTFExtension&&this.isExtensionUsed(o)&&t.Logger.Warn(`Extension ${o} is used but has been explicitly disabled.`):e.isGLTFExtension&&!this.isExtensionUsed(o)||n.push((()=>b(this,void 0,void 0,function*(){const n=yield e.factory(this);return n.name!==o&&t.Logger.Warn(`The name of the glTF loader extension instance does not match the registered name: ${n.name} !== ${o}`),this._parent.onExtensionLoadedObservable.notifyObservers(n),n}))())}),this._extensions.push(...yield Promise.all(n)),this._extensions.sort((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE)),this._parent.onExtensionLoadedObservable.clear(),this._gltf.extensionsRequired)for(const t of this._gltf.extensionsRequired)if(!this._extensions.some(e=>e.name===t&&e.enabled)){if(!1===(null===(e=this.parent.extensionOptions[t])||void 0===e?void 0:e.enabled))throw new Error(`Required extension ${t} is disabled`);throw new Error(`Required extension ${t} is not available`)}})}_createRootNode(){if(void 0!==this._parent.customRootNode)return this._rootBabylonMesh=this._parent.customRootNode,{_babylonTransformNode:null===this._rootBabylonMesh?void 0:this._rootBabylonMesh,index:-1};this._babylonScene._blockEntityCollection=!!this._assetContainer;const n=new t.Mesh("__root__",this._babylonScene);this._rootBabylonMesh=n,this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);const o={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case e.GLTFLoaderCoordinateSystemMode.AUTO:this._babylonScene.useRightHandedSystem||(o.rotation=[0,1,0,0],o.scale=[1,1,-1],yo._LoadTransform(o,this._rootBabylonMesh));break;case e.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:this._babylonScene.useRightHandedSystem=!0;break;default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(n),o}loadSceneAsync(e,t){const n=this._extensionsLoadSceneAsync(e,t);if(n)return n;const o=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const n of t.nodes){const t=_o.Get(`${e}/nodes/${n}`,this._gltf.nodes,n);o.push(this.loadNodeAsync(`/nodes/${t.index}`,t,e=>{e.parent=this._rootBabylonMesh}))}for(const e of this._postSceneLoadActions)e();return o.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(o).then(()=>{})}_forEachPrimitive(e,t){if(e._primitiveBabylonMeshes)for(const n of e._primitiveBabylonMeshes)t(n)}_getGeometries(){const e=[],t=this._gltf.nodes;if(t)for(const n of t)this._forEachPrimitive(n,t=>{const n=t.geometry;n&&-1===e.indexOf(n)&&e.push(n)});return e}_getMeshes(){const e=[];this._rootBabylonMesh instanceof t.AbstractMesh&&e.push(this._rootBabylonMesh);const n=this._gltf.nodes;if(n)for(const t of n)this._forEachPrimitive(t,t=>{e.push(t)});return e}_getTransformNodes(){const e=[],t=this._gltf.nodes;if(t)for(const n of t)n._babylonTransformNode&&"TransformNode"===n._babylonTransformNode.getClassName()&&e.push(n._babylonTransformNode),n._babylonTransformNodeForSkin&&e.push(n._babylonTransformNodeForSkin);return e}_getSkeletons(){const e=[],t=this._gltf.skins;if(t)for(const n of t)n._data&&e.push(n._data.babylonSkeleton);return e}_getAnimationGroups(){const e=[],t=this._gltf.animations;if(t)for(const n of t)n._babylonAnimationGroup&&e.push(n._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case e.GLTFLoaderAnimationStartMode.NONE:break;case e.GLTFLoaderAnimationStartMode.FIRST:{const e=this._getAnimationGroups();0!==e.length&&e[0].start(!0);break}case e.GLTFLoaderAnimationStartMode.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:return void t.Logger.Error(`Invalid animation start mode (${this._parent.animationStartMode})`)}}loadNodeAsync(e,n,o=()=>{}){const s=this._extensionsLoadNodeAsync(e,n,o);if(s)return s;if(n._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const r=new Array;this.logOpen(`${e} ${n.name||""}`);const i=t=>{if(yo.AddPointerMetadata(t,e),yo._LoadTransform(n,t),null!=n.camera){const o=_o.Get(`${e}/camera`,this._gltf.cameras,n.camera);r.push(this.loadCameraAsync(`/cameras/${o.index}`,o,e=>{e.parent=t,this._babylonScene.useRightHandedSystem||(t.scaling.x=-1)}))}if(n.children)for(const o of n.children){const n=_o.Get(`${e}/children/${o}`,this._gltf.nodes,o);r.push(this.loadNodeAsync(`/nodes/${n.index}`,n,e=>{e.parent=t}))}o(t)},a=null!=n.mesh,l=this._parent.loadSkins&&null!=n.skin;if(!a||l){const e=n.name||`node${n.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new t.TransformNode(e,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,null==n.mesh?n._babylonTransformNode=o:n._babylonTransformNodeForSkin=o,i(o)}if(a)if(l){const o=_o.Get(`${e}/mesh`,this._gltf.meshes,n.mesh);r.push(this._loadMeshAsync(`/meshes/${o.index}`,n,o,o=>{const s=n._babylonTransformNodeForSkin;o.metadata=t.deepMerge(s.metadata,o.metadata||{});const i=_o.Get(`${e}/skin`,this._gltf.skins,n.skin);r.push(this._loadSkinAsync(`/skins/${i.index}`,n,i,e=>{this._forEachPrimitive(n,t=>{t.skeleton=e}),this._postSceneLoadActions.push(()=>{if(null!=i.skeleton){const e=_o.Get(`/skins/${i.index}/skeleton`,this._gltf.nodes,i.skeleton).parent;n.index===e.index?o.parent=s.parent:o.parent=e._babylonTransformNode}else o.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:s,skinnedNode:o})})}))}))}else{const t=_o.Get(`${e}/mesh`,this._gltf.meshes,n.mesh);r.push(this._loadMeshAsync(`/meshes/${t.index}`,n,t,i))}return this.logClose(),Promise.all(r).then(()=>(this._forEachPrimitive(n,e=>{const t=e;!t.isAnInstance&&t.geometry&&t.geometry.useBoundingInfoFromGeometry?e._updateBoundingInfo():e.refreshBoundingInfo(!0,!0)}),n._babylonTransformNode))}_loadMeshAsync(e,n,o,s){const r=o.primitives;if(!r||!r.length)throw new Error(`${e}: Primitives are missing`);null==r[0].index&&_o.Assign(r);const i=new Array;this.logOpen(`${e} ${o.name||""}`);const a=n.name||`node${n.index}`;if(1===r.length){const t=o.primitives[0];i.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${t.index}`,a,n,o,t,e=>{n._babylonTransformNode=e,n._primitiveBabylonMeshes=[e]}))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,n._babylonTransformNode=new t.TransformNode(a,this._babylonScene),n._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n._primitiveBabylonMeshes=[];for(const t of r)i.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${t.index}`,`${a}_primitive${t.index}`,n,o,t,e=>{e.parent=n._babylonTransformNode,n._primitiveBabylonMeshes.push(e)}))}return s(n._babylonTransformNode),this.logClose(),Promise.all(i).then(()=>n._babylonTransformNode)}_loadMeshPrimitiveAsync(e,n,o,s,r,i){const a=this._extensionsLoadMeshPrimitiveAsync(e,n,o,s,r,i);if(a)return a;this.logOpen(`${e}`);const l=0===this._disableInstancedMesh&&this._parent.createInstances&&null==o.skin&&!s.primitives[0].targets;let u,c;if(l&&r._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,u=r._instanceData.babylonSourceMesh.createInstance(n),u._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,c=r._instanceData.promise;else{const i=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const a=new t.Mesh(n,this._babylonScene);if(a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,a.sideOrientation=this._babylonScene.useRightHandedSystem?t.Material.CounterClockWiseSideOrientation:t.Material.ClockWiseSideOrientation,this._createMorphTargets(e,o,s,r,a),i.push(this._loadVertexDataAsync(e,r,a).then(t=>b(this,void 0,void 0,function*(){return yield this._loadMorphTargetsAsync(e,r,a,t).then(()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,t.applyToMesh(a),t._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})}))),!this.parent.skipMaterials){const t=yo._GetDrawMode(e,r.mode);if(null==r.material){let e=this._defaultBabylonMaterialData[t];e||(e=this._createDefaultMaterial("__GLTFLoader._default",t,this._getDefaultImpl()),this._parent.onMaterialLoadedObservable.notifyObservers(e),this._defaultBabylonMaterialData[t]=e),a.material=e}else{const n=_o.Get(`${e}/material`,this._gltf.materials,r.material);i.push(this._loadMaterialAsync(`/materials/${n.index}`,n,a,t,e=>{a.material=e}))}}c=Promise.all(i),l&&(r._instanceData={babylonSourceMesh:a,promise:c}),u=a}return yo.AddPointerMetadata(u,e),this._parent.onMeshLoadedObservable.notifyObservers(u),i(u),this.logClose(),c.then(()=>u)}_loadVertexDataAsync(e,n,o){const s=this._extensionsLoadVertexDataAsync(e,n,o);if(s)return s;const r=n.attributes;if(!r)throw new Error(`${e}: Attributes are missing`);const i=new Array,a=new t.Geometry(o.name,this._babylonScene);if(null==n.indices)o.isUnIndexed=!0;else{const t=_o.Get(`${e}/indices`,this._gltf.accessors,n.indices);i.push(this._loadIndicesAccessorAsync(`/accessors/${t.index}`,t).then(e=>{a.setIndices(e)}))}const l=(n,s,l)=>{if(null==r[n])return;o._delayInfo=o._delayInfo||[],-1===o._delayInfo.indexOf(s)&&o._delayInfo.push(s);const u=_o.Get(`${e}/attributes/${n}`,this._gltf.accessors,r[n]);i.push(this._loadVertexAccessorAsync(`/accessors/${u.index}`,u,s).then(e=>{if(e.getKind()===t.VertexBuffer.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!o.skeleton){const e=go(u);e&&(a._boundingInfo=e,a.useBoundingInfoFromGeometry=!0)}a.setVerticesBuffer(e,u.count)})),s==t.VertexBuffer.MatricesIndicesExtraKind&&(o.numBoneInfluencers=8),l&&l(u)};return l("POSITION",t.VertexBuffer.PositionKind),l("NORMAL",t.VertexBuffer.NormalKind),l("TANGENT",t.VertexBuffer.TangentKind),l("TEXCOORD_0",t.VertexBuffer.UVKind),l("TEXCOORD_1",t.VertexBuffer.UV2Kind),l("TEXCOORD_2",t.VertexBuffer.UV3Kind),l("TEXCOORD_3",t.VertexBuffer.UV4Kind),l("TEXCOORD_4",t.VertexBuffer.UV5Kind),l("TEXCOORD_5",t.VertexBuffer.UV6Kind),l("JOINTS_0",t.VertexBuffer.MatricesIndicesKind),l("WEIGHTS_0",t.VertexBuffer.MatricesWeightsKind),l("JOINTS_1",t.VertexBuffer.MatricesIndicesExtraKind),l("WEIGHTS_1",t.VertexBuffer.MatricesWeightsExtraKind),l("COLOR_0",t.VertexBuffer.ColorKind,e=>{"VEC4"===e.type&&(o.hasVertexAlpha=!0)}),Promise.all(i).then(()=>a)}_createMorphTargets(e,n,o,s,r){if(!s.targets||!this._parent.loadMorphTargets)return;if(null==n._numMorphTargets)n._numMorphTargets=s.targets.length;else if(s.targets.length!==n._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);const i=o.extras?o.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,r.morphTargetManager=new t.MorphTargetManager(this._babylonScene),r.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.morphTargetManager.areUpdatesFrozen=!0;for(let e=0;e<s.targets.length;e++){const s=n.weights?n.weights[e]:o.weights?o.weights[e]:0,a=i?i[e]:`morphTarget${e}`;r.morphTargetManager.addTarget(new t.MorphTarget(a,s,r.getScene()))}}_loadMorphTargetsAsync(e,n,o,s){if(!n.targets||!this._parent.loadMorphTargets)return Promise.resolve();const r=new Array,i=o.morphTargetManager;for(let t=0;t<i.numTargets;t++){const o=i.getTarget(t);r.push(this._loadMorphTargetVertexDataAsync(`${e}/targets/${t}`,s,n.targets[t],o))}return Promise.all(r).then(()=>{i.areUpdatesFrozen=!1,this._parent.useMaxMorphTargetInfluencers&&(i.isUsingTextureForTargets||i.numTargets<=t.MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode)&&(i.optimizeInfluencers=!1,i.numMaxInfluencers=i.numTargets)})}_loadMorphTargetVertexDataAsync(e,n,o,s){return b(this,void 0,void 0,function*(){const r=new Array,i=(t,s,i)=>{if(null==o[t])return;const a=n.getVertexBuffer(s);if(!a)return;const l=_o.Get(`${e}/${t}`,this._gltf.accessors,o[t]);r.push(this._loadFloatAccessorAsync(`/accessors/${l.index}`,l).then(e=>{i(a,e)}))};return i("POSITION",t.VertexBuffer.PositionKind,(e,t)=>{const n=new Float32Array(t.length);e.forEach(t.length,(e,o)=>{n[o]=t[o]+e}),s.setPositions(n)}),i("NORMAL",t.VertexBuffer.NormalKind,(e,t)=>{const n=new Float32Array(t.length);e.forEach(n.length,(e,o)=>{n[o]=t[o]+e}),s.setNormals(n)}),i("TANGENT",t.VertexBuffer.TangentKind,(e,t)=>{const n=new Float32Array(t.length/3*4);let o=0;e.forEach(t.length/3*4,(e,s)=>{(s+1)%4!=0&&(n[o]=t[o]+e,o++)}),s.setTangents(n)}),i("TEXCOORD_0",t.VertexBuffer.UVKind,(e,t)=>{const n=new Float32Array(t.length);e.forEach(t.length,(e,o)=>{n[o]=t[o]+e}),s.setUVs(n)}),i("TEXCOORD_1",t.VertexBuffer.UV2Kind,(e,t)=>{const n=new Float32Array(t.length);e.forEach(t.length,(e,o)=>{n[o]=t[o]+e}),s.setUV2s(n)}),i("COLOR_0",t.VertexBuffer.ColorKind,(t,n)=>{let o=null;const r=t.getSize();if(3===r){o=new Float32Array(n.length/3*4),t.forEach(n.length,(e,t)=>{const s=Math.floor(t/3),r=t%3;o[4*s+r]=n[3*s+r]+e});for(let e=0;e<n.length/3;++e)o[4*e+3]=1}else{if(4!==r)throw new Error(`${e}: Invalid number of components (${r}) for COLOR_0 attribute`);o=new Float32Array(n.length),t.forEach(n.length,(e,t)=>{o[t]=n[t]+e})}s.setColors(o)}),yield Promise.all(r).then(()=>{})})}static _LoadTransform(e,n){if(null!=e.skin)return;let o=t.Vector3.Zero(),s=t.Quaternion.Identity(),r=t.Vector3.One();e.matrix?t.Matrix.FromArray(e.matrix).decompose(r,s,o):(e.translation&&(o=t.Vector3.FromArray(e.translation)),e.rotation&&(s=t.Quaternion.FromArray(e.rotation)),e.scale&&(r=t.Vector3.FromArray(e.scale))),n.position=o,n.rotationQuaternion=s,n.scaling=r}_loadSkinAsync(e,n,o,s){if(!this._parent.loadSkins)return Promise.resolve();const r=this._extensionsLoadSkinAsync(e,n,o);if(r)return r;if(o._data)return s(o._data.babylonSkeleton),o._data.promise;const i=`skeleton${o.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const a=new t.Skeleton(o.name||i,i,this._babylonScene);a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,o,a);const l=this._loadSkinInverseBindMatricesDataAsync(e,o).then(e=>{this._updateBoneMatrices(a,e)});return o._data={babylonSkeleton:a,promise:l},s(a),l}_loadBones(e,n,o){if(null==n.skeleton||this._parent.alwaysComputeSkeletonRootNode){const o=this._findSkeletonRootNode(`${e}/joints`,n.joints);if(o)if(void 0===n.skeleton)n.skeleton=o.index;else{const s=(e,t)=>{for(;t.parent;t=t.parent)if(t.parent===e)return!0;return!1},r=_o.Get(`${e}/skeleton`,this._gltf.nodes,n.skeleton);r===o||s(r,o)||(t.Logger.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),n.skeleton=o.index)}else t.Logger.Warn(`${e}: Failed to find common root`)}const s={};for(const t of n.joints){const r=_o.Get(`${e}/joints/${t}`,this._gltf.nodes,t);this._loadBone(r,n,o,s)}}_findSkeletonRootNode(e,t){if(0===t.length)return null;const n={};for(const o of t){const t=[];let s=_o.Get(`${e}/${o}`,this._gltf.nodes,o);for(;-1!==s.index;)t.unshift(s),s=s.parent;n[o]=t}let o=null;for(let e=0;;++e){let s=n[t[0]];if(e>=s.length)return o;const r=s[e];for(let i=1;i<t.length;++i)if(s=n[t[i]],e>=s.length||r!==s[e])return o;o=r}}_loadBone(e,n,o,s){e._isJoint=!0;let r=s[e.index];if(r)return r;let i=null;e.index!==n.skeleton&&(e.parent&&-1!==e.parent.index?i=this._loadBone(e.parent,n,o,s):void 0!==n.skeleton&&t.Logger.Warn(`/skins/${n.index}/skeleton: Skeleton node is not a common root`));const a=n.joints.indexOf(e.index);return r=new t.Bone(e.name||`joint${e.index}`,o,i,this._getNodeMatrix(e),null,null,a),s[e.index]=r,this._postSceneLoadActions.push(()=>{r.linkTransformNode(e._babylonTransformNode)}),r}_loadSkinInverseBindMatricesDataAsync(e,t){if(null==t.inverseBindMatrices)return Promise.resolve(null);const n=_o.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${n.index}`,n)}_updateBoneMatrices(e,n){for(const o of e.bones){const e=t.Matrix.Identity(),s=o._index;n&&-1!==s&&(t.Matrix.FromArrayToRef(n,16*s,e),e.invertToRef(e));const r=o.getParent();r&&e.multiplyToRef(r.getAbsoluteInverseBindMatrix(),e),o.updateMatrix(e,!1,!1),o._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?t.Matrix.FromArray(e.matrix):t.Matrix.Compose(e.scale?t.Vector3.FromArray(e.scale):t.Vector3.One(),e.rotation?t.Quaternion.FromArray(e.rotation):t.Quaternion.Identity(),e.translation?t.Vector3.FromArray(e.translation):t.Vector3.Zero())}loadCameraAsync(e,n,o=()=>{}){const s=this._extensionsLoadCameraAsync(e,n,o);if(s)return s;const r=new Array;this.logOpen(`${e} ${n.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new t.FreeCamera(n.name||`camera${n.index}`,t.Vector3.Zero(),this._babylonScene,!1);switch(i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n._babylonCamera=i,i.setTarget(new t.Vector3(0,0,-1)),n.type){case"perspective":{const t=n.perspective;if(!t)throw new Error(`${e}: Camera perspective properties are missing`);i.fov=t.yfov,i.minZ=t.znear,i.maxZ=t.zfar||0;break}case"orthographic":if(!n.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);i.mode=t.Camera.ORTHOGRAPHIC_CAMERA,i.orthoLeft=-n.orthographic.xmag,i.orthoRight=n.orthographic.xmag,i.orthoBottom=-n.orthographic.ymag,i.orthoTop=n.orthographic.ymag,i.minZ=n.orthographic.znear,i.maxZ=n.orthographic.zfar;break;default:throw new Error(`${e}: Invalid camera type (${n.type})`)}return yo.AddPointerMetadata(i,e),this._parent.onCameraLoadedObservable.notifyObservers(i),o(i),this.logClose(),Promise.all(r).then(()=>i)}_loadAnimationsAsync(){this._parent._startPerformanceCounter("Load animations");const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let n=0;n<e.length;n++){const o=e[n];t.push(this.loadAnimationAsync(`/animations/${o.index}`,o).then(e=>{0===e.targetedAnimations.length&&e.dispose()}))}return Promise.all(t).then(()=>{this._parent._endPerformanceCounter("Load animations")})}loadAnimationAsync(e,t){this._parent._startPerformanceCounter("Load animation");return this._extensionsLoadAnimationAsync(e,t)||fo.value.then(({AnimationGroup:n})=>{this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new n(t.name||`animation${t.index}`,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=o;const s=new Array;_o.Assign(t.channels),_o.Assign(t.samplers);for(const n of t.channels)s.push(this._loadAnimationChannelAsync(`${e}/channels/${n.index}`,e,t,n,(e,t)=>{e.animations=e.animations||[],e.animations.push(t),o.addTargetedAnimation(t,e)}));return this._parent._endPerformanceCounter("Load animation"),Promise.all(s).then(()=>(o.normalize(0),o))})}_loadAnimationChannelAsync(e,t,n,o,s){const r=this._extensionsLoadAnimationChannelAsync(e,t,n,o,s);if(r)return r;if(null==o.target.node)return Promise.resolve();const i=_o.Get(`${e}/target/node`,this._gltf.nodes,o.target.node),a=o.target.path,l="weights"===a;return l&&!i._numMorphTargets||!l&&!i._babylonTransformNode?Promise.resolve():this._parent.loadNodeAnimations||l||i._isJoint?po.value.then(()=>{var r,l,u,c;let d;switch(a){case"translation":d=null===(r=co("/nodes/{}/translation"))||void 0===r?void 0:r.interpolation;break;case"rotation":d=null===(l=co("/nodes/{}/rotation"))||void 0===l?void 0:l.interpolation;break;case"scale":d=null===(u=co("/nodes/{}/scale"))||void 0===u?void 0:u.interpolation;break;case"weights":d=null===(c=co("/nodes/{}/weights"))||void 0===c?void 0:c.interpolation;break;default:throw new Error(`${e}/target/path: Invalid value (${o.target.path})`)}if(!d)throw new Error(`${e}/target/path: Could not find interpolation properties for target path (${o.target.path})`);const h={object:i,info:d};return this._loadAnimationChannelFromTargetInfoAsync(e,t,n,o,h,s)}):Promise.resolve()}_loadAnimationChannelFromTargetInfoAsync(e,t,n,o,s,r){const i=this.parent.targetFps,a=1/i,l=_o.Get(`${e}/sampler`,n.samplers,o.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${o.sampler}`,l).then(e=>{let t=0;const l=s.object,u=s.info;for(const s of u){const u=s.getStride(l),c=e.input,d=e.output,h=new Array(c.length);let m=0;switch(e.interpolation){case"STEP":for(let e=0;e<c.length;e++){const t=s.getValue(l,d,m,1);m+=u,h[e]={frame:c[e]*i,value:t,interpolation:1}}break;case"CUBICSPLINE":for(let e=0;e<c.length;e++){const t=s.getValue(l,d,m,a);m+=u;const n=s.getValue(l,d,m,1);m+=u;const o=s.getValue(l,d,m,a);m+=u,h[e]={frame:c[e]*i,inTangent:t,value:n,outTangent:o}}break;case"LINEAR":for(let e=0;e<c.length;e++){const t=s.getValue(l,d,m,1);m+=u,h[e]={frame:c[e]*i,value:t}}}if(m>0){const e=`${n.name||`animation${n.index}`}_channel${o.index}_${t}`,a=s.buildAnimations(l,e,i,h);for(const e of a)t++,r(e.babylonAnimatable,e.babylonAnimation)}}})}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;const n=t.interpolation||"LINEAR";switch(n){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}const o=_o.Get(`${e}/input`,this._gltf.accessors,t.input),s=_o.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${o.index}`,o),this._loadFloatAccessorAsync(`/accessors/${s.index}`,s)]).then(([e,t])=>({input:e,interpolation:n,output:t})),t._data}loadBufferAsync(e,t,n,o){const s=this._extensionsLoadBufferAsync(e,t,n,o);if(s)return s;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);t._data=this._bin.readAsync(0,t.byteLength)}return t._data.then(t=>{try{return new Uint8Array(t.buffer,t.byteOffset+n,o)}catch(t){throw new Error(`${e}: ${t.message}`,{cause:t})}})}loadBufferViewAsync(e,t){const n=this._extensionsLoadBufferViewAsync(e,t);if(n)return n;if(t._data)return t._data;const o=_o.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${o.index}`,o,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,n,o){if(n._data)return n._data;const s=yo._GetNumComponents(e,n.type),r=s*t.VertexBufferGetTypeByteLength(n.componentType),i=s*n.count;if(null==n.bufferView)n._data=Promise.resolve(new o(i));else{const a=_o.Get(`${e}/bufferView`,this._gltf.bufferViews,n.bufferView);n._data=this.loadBufferViewAsync(`/bufferViews/${a.index}`,a).then(l=>{if(5126!==n.componentType||n.normalized||a.byteStride&&a.byteStride!==r){const e=new o(i);return t.VertexBufferForEach(l,n.byteOffset||0,a.byteStride||r,s,n.componentType,e.length,n.normalized||!1,(t,n)=>{e[n]=t}),e}return yo._GetTypedArray(e,n.componentType,l,n.byteOffset,i)})}if(n.sparse){const i=n.sparse;n._data=n._data.then(a=>{const l=a,u=_o.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,i.indices.bufferView),c=_o.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,i.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${u.index}`,u),this.loadBufferViewAsync(`/bufferViews/${c.index}`,c)]).then(([a,u])=>{const c=yo._GetTypedArray(`${e}/sparse/indices`,i.indices.componentType,a,i.indices.byteOffset,i.count),d=s*i.count;let h;if(5126!==n.componentType||n.normalized){const a=yo._GetTypedArray(`${e}/sparse/values`,n.componentType,u,i.values.byteOffset,d);h=new o(d),t.VertexBufferForEach(a,0,r,s,n.componentType,h.length,n.normalized||!1,(e,t)=>{h[t]=e})}else h=yo._GetTypedArray(`${e}/sparse/values`,n.componentType,u,i.values.byteOffset,d);let m=0;for(let e=0;e<c.length;e++){let t=c[e]*s;for(let e=0;e<s;e++)l[t++]=h[m++]}return l})})}return n._data}_loadFloatAccessorAsync(e,t){return this._loadAccessorAsync(e,t,Float32Array)}_loadIndicesAccessorAsync(e,t){if("SCALAR"!==t.type)throw new Error(`${e}/type: Invalid value ${t.type}`);if(5121!==t.componentType&&5123!==t.componentType&&5125!==t.componentType)throw new Error(`${e}/componentType: Invalid value ${t.componentType}`);if(t._data)return t._data;if(t.sparse){const n=yo._GetTypedArrayConstructor(`${e}/componentType`,t.componentType);t._data=this._loadAccessorAsync(e,t,n)}else{const n=_o.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${n.index}`,n).then(n=>yo._GetTypedArray(e,t.componentType,n,t.byteOffset,t.count))}return t._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;const n=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then(e=>new t.Buffer(n,e,!1)),e._babylonBuffer}_loadVertexAccessorAsync(e,n,o){var s;if(null===(s=n._babylonVertexBuffer)||void 0===s?void 0:s[o])return n._babylonVertexBuffer[o];n._babylonVertexBuffer||(n._babylonVertexBuffer={});const r=this._babylonScene.getEngine();if(n.sparse||null==n.bufferView)n._babylonVertexBuffer[o]=this._loadFloatAccessorAsync(e,n).then(e=>new t.VertexBuffer(r,e,o,!1));else{const s=_o.Get(`${e}/bufferView`,this._gltf.bufferViews,n.bufferView);n._babylonVertexBuffer[o]=this._loadVertexBufferViewAsync(s).then(i=>{const a=yo._GetNumComponents(e,n.type);return new t.VertexBuffer(r,i,o,!1,void 0,s.byteStride,void 0,n.byteOffset,a,n.componentType,n.normalized,!0,void 0,!0)})}return n._babylonVertexBuffer[o]}_loadMaterialMetallicRoughnessPropertiesAsync(e,n,o){const s=new Array,r=this._getOrCreateMaterialAdapter(o);return n&&(n.baseColorFactor?(r.baseColor=t.Color3.FromArray(n.baseColorFactor),r.geometryOpacity=n.baseColorFactor[3]):r.baseColor=t.Color3.White(),r.baseMetalness=null==n.metallicFactor?1:n.metallicFactor,r.specularRoughness=null==n.roughnessFactor?1:n.roughnessFactor,n.baseColorTexture&&s.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,n.baseColorTexture,e=>{e.name=`${o.name} (Base Color)`,r.baseColorTexture=e})),n.metallicRoughnessTexture&&(n.metallicRoughnessTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,n.metallicRoughnessTexture,e=>{e.name=`${o.name} (Metallic Roughness)`,r.baseMetalnessTexture=e,r.specularRoughnessTexture=e})),r.useRoughnessFromMetallicTextureGreen=!0,r.useMetallicFromMetallicTextureBlue=!0)),Promise.all(s).then(()=>{})}_loadMaterialAsync(e,t,n,o,s=()=>{}){const r=this._extensionsLoadMaterialAsync(e,t,n,o,s);if(r)return r;t._data=t._data||{};let i=t._data[o];if(!i){this.logOpen(`${e} ${t.name||""}`);const n=this.createMaterial(e,t,o);i={babylonMaterial:n,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,n)},t._data[o]=i,yo.AddPointerMetadata(n,e),this._parent.onMaterialLoadedObservable.notifyObservers(n),this.logClose()}return n&&(i.babylonMeshes.push(n),n.onDisposeObservable.addOnce(()=>{const e=i.babylonMeshes.indexOf(n);-1!==e&&i.babylonMeshes.splice(e,1)})),s(i.babylonMaterial),i.promise.then(()=>i.babylonMaterial)}_selectImplForGltfMaterial(e){var t;if(this.parent.useOpenPBR||(null===(t=e.extensions)||void 0===t?void 0:t.KHR_materials_openpbr)){const e=this._pbrMaterialImpls.get("openpbr");if(e)return e}const n=this._pbrMaterialImpls.get("pbr");if(n)return n;throw new Error("No PBR material implementation loaded")}_getDefaultImpl(){var e;if(this.parent.useOpenPBR){const e=this._pbrMaterialImpls.get("openpbr");if(e)return e}const t=null!==(e=this._pbrMaterialImpls.get("pbr"))&&void 0!==e?e:this._pbrMaterialImpls.values().next().value;if(t)return t;throw new Error("No PBR material implementation loaded")}_createDefaultMaterial(e,t,n){this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new n.materialClass(e,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,o.fillMode=t,o.transparencyMode=n.materialClass.MATERIAL_OPAQUE;const s=this._getOrCreateMaterialAdapter(o);return s.transparencyAsAlphaCoverage=this._parent.transparencyAsCoverage,s.baseMetalness=1,s.specularRoughness=1,o}createMaterial(e,t,n){const o=this._extensionsCreateMaterial(e,t,n);if(o)return o;const s=t.name||`material${t.index}`;return this._createDefaultMaterial(s,n,this._selectImplForGltfMaterial(t))}loadMaterialPropertiesAsync(e,t,n){const o=this._extensionsLoadMaterialPropertiesAsync(e,t,n);if(o)return o;const s=new Array;return s.push(this.loadMaterialBasePropertiesAsync(e,t,n)),t.pbrMetallicRoughness&&s.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,n)),this.loadMaterialAlphaProperties(e,t,n),Promise.all(s).then(()=>{})}loadMaterialBasePropertiesAsync(e,n,o){const s=new Array,r=this._getOrCreateMaterialAdapter(o);let i;r.emissionColor=n.emissiveFactor?t.Color3.FromArray(n.emissiveFactor):new t.Color3(0,0,0),n.doubleSided&&(r.backFaceCulling=!1,r.twoSidedLighting=!0),n.normalTexture&&(n.normalTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/normalTexture`,n.normalTexture,e=>{var t;e.name=`${o.name} (Normal)`,r.geometryNormalTexture=e,null!=(null===(t=n.normalTexture)||void 0===t?void 0:t.scale)&&(e.level=n.normalTexture.scale)})),r.setNormalMapInversions(!this._babylonScene.useRightHandedSystem,this._babylonScene.useRightHandedSystem));let a,l=1;return n.occlusionTexture&&(n.occlusionTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,n.occlusionTexture,e=>{e.name=`${o.name} (Occlusion)`,i=e})),null!=n.occlusionTexture.strength&&(l=n.occlusionTexture.strength)),n.emissiveTexture&&s.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,n.emissiveTexture,e=>{e.name=`${o.name} (Emissive)`,a=e})),Promise.all(s).then(()=>{i&&(r.ambientOcclusionTexture=i,r.ambientOcclusionTextureStrength=l),a&&(r.emissionColorTexture=a)})}loadMaterialAlphaProperties(e,n,o){if(0===this._pbrMaterialImpls.size)throw new Error(`${e}: Material type not supported`);const s=this._getOrCreateMaterialAdapter(o),r=s.baseColorTexture;switch(n.alphaMode||"OPAQUE"){case"OPAQUE":o.transparencyMode=t.Material.MATERIAL_OPAQUE,o.alpha=1;break;case"MASK":o.transparencyMode=t.Material.MATERIAL_ALPHATEST,s.alphaCutOff=null==n.alphaCutoff?.5:n.alphaCutoff,r&&(r.hasAlpha=!0,s.useAlphaFromBaseColorTexture=!0);break;case"BLEND":o.transparencyMode=t.Material.MATERIAL_ALPHABLEND,r&&(r.hasAlpha=!0,s.useAlphaFromBaseColorTexture=!0);break;default:throw new Error(`${e}/alphaMode: Invalid value (${n.alphaMode})`)}}loadTextureInfoAsync(e,t,n=()=>{}){const o=this._extensionsLoadTextureInfoAsync(e,t,n);if(o)return o;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const s=_o.Get(`${e}/index`,this._gltf.textures,t.index);s._textureInfo=t;const r=this._loadTextureAsync(`/textures/${t.index}`,s,o=>{o.coordinatesIndex=t.texCoord||0,yo.AddPointerMetadata(o,e),this._parent.onTextureLoadedObservable.notifyObservers(o),n(o)});return this.logClose(),r}_loadTextureAsync(e,t,n=()=>{}){const o=this._extensionsLoadTextureAsync(e,t,n);if(o)return o;this.logOpen(`${e} ${t.name||""}`);const s=null==t.sampler?yo.DefaultSampler:_o.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),r=_o.Get(`${e}/source`,this._gltf.images,t.source),i=this._createTextureAsync(e,s,r,n,void 0,!t._textureInfo.nonColorData);return this.logClose(),i}_createTextureAsync(e,n,o,s=()=>{},r,i){var a,l;const u=this._loadSampler(`/samplers/${n.index}`,n),c=new Array,d=new t.Deferred;this._babylonScene._blockEntityCollection=!!this._assetContainer;const h={noMipmap:u.noMipMaps,invertY:!1,samplingMode:u.samplingMode,onLoad:()=>{this._disposed||d.resolve()},onError:(t,n)=>{this._disposed||d.reject(new Error(`${e}: ${n&&n.message?n.message:t||"Failed to load texture"}`))},mimeType:null!==(a=o.mimeType)&&void 0!==a?a:t.GetMimeType(null!==(l=o.uri)&&void 0!==l?l:""),loaderOptions:r,useSRGBBuffer:!!i&&this._parent.useSRGBBuffers},m=new t.Texture(null,this._babylonScene,h);m._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,c.push(d.promise);const f=o.uri&&!t.IsBase64DataUrl(o.uri)?o.uri:void 0,p=null!=f?f:`${this._fileName}#image${o.index}`;if(c.push(this.loadImageAsync(`/images/${o.index}`,o).then(e=>{const t=`data:${this._uniqueRootUrl}${p}`;m.updateURL(t,e);const n=m.getInternalTexture();n&&(n.label=o.name)})),m.wrapU=u.wrapU,m.wrapV=u.wrapV,s(m),this._parent.useGltfTextureNames){const e=o.name||f||`image${o.index}`;m.name=e}return Promise.all(c).then(()=>m)}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:yo._GetTextureSamplingMode(e,t),wrapU:yo._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:yo._GetTextureWrapMode(`${e}/wrapT`,t.wrapT)}),t._data}loadImageAsync(e,t){if(!t._data){if(this.logOpen(`${e} ${t.name||""}`),t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{const n=_o.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${n.index}`,n)}this.logClose()}return t._data}loadUriAsync(e,n,o){const s=this._extensionsLoadUriAsync(e,n,o);if(s)return s;if(!yo._ValidateUri(o))throw new Error(`${e}: '${o}' is invalid`);if(t.IsBase64DataUrl(o)){const n=new Uint8Array(t.DecodeBase64UrlToBinary(o));return this.log(`${e}: Decoded ${o.substring(0,64)}... (${n.length} bytes)`),Promise.resolve(n)}return this.log(`${e}: Loading ${o}`),this._parent.preprocessUrlAsync(this._rootUrl+o).then(n=>new Promise((s,r)=>{this._parent._loadFile(this._babylonScene,n,t=>{this._disposed||(this.log(`${e}: Loaded ${o} (${t.byteLength} bytes)`),s(new Uint8Array(t)))},!0,n=>{r(new t.LoadFileError(`${e}: Failed to load '${o}'${n?": "+n.status+" "+n.statusText:""}`,n))})}))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};const n=e._internalMetadata=e._internalMetadata||{},o=n.gltf=n.gltf||{};(o.pointers=o.pointers||[]).push(t)}static _GetTextureWrapMode(e,n){switch(n=null==n?10497:n){case 33071:return t.Texture.CLAMP_ADDRESSMODE;case 33648:return t.Texture.MIRROR_ADDRESSMODE;case 10497:return t.Texture.WRAP_ADDRESSMODE;default:return t.Logger.Warn(`${e}: Invalid value (${n})`),t.Texture.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,n){const o=null==n.magFilter?9729:n.magFilter,s=null==n.minFilter?9987:n.minFilter;if(9729===o)switch(s){case 9728:return t.Texture.LINEAR_NEAREST;case 9729:return t.Texture.LINEAR_LINEAR;case 9984:return t.Texture.LINEAR_NEAREST_MIPNEAREST;case 9985:return t.Texture.LINEAR_LINEAR_MIPNEAREST;case 9986:return t.Texture.LINEAR_NEAREST_MIPLINEAR;case 9987:return t.Texture.LINEAR_LINEAR_MIPLINEAR;default:return t.Logger.Warn(`${e}/minFilter: Invalid value (${s})`),t.Texture.LINEAR_LINEAR_MIPLINEAR}else switch(9728!==o&&t.Logger.Warn(`${e}/magFilter: Invalid value (${o})`),s){case 9728:return t.Texture.NEAREST_NEAREST;case 9729:return t.Texture.NEAREST_LINEAR;case 9984:return t.Texture.NEAREST_NEAREST_MIPNEAREST;case 9985:return t.Texture.NEAREST_LINEAR_MIPNEAREST;case 9986:return t.Texture.NEAREST_NEAREST_MIPLINEAR;case 9987:return t.Texture.NEAREST_LINEAR_MIPLINEAR;default:return t.Logger.Warn(`${e}/minFilter: Invalid value (${s})`),t.Texture.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,n){try{return t.GetTypedArrayConstructor(n)}catch(t){throw new Error(`${e}: ${t.message}`,{cause:t})}}static _GetTypedArray(e,n,o,s,r){const i=o.buffer;s=o.byteOffset+(s||0);const a=yo._GetTypedArrayConstructor(`${e}/componentType`,n),l=t.VertexBufferGetTypeByteLength(n);return s%l!==0?(t.Logger.Warn(`${e}: Copying buffer as byte offset (${s}) is not a multiple of component type byte length (${l})`),new a(i.slice(s,s+r*l),0)):new a(i,s,r)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return t.Tools.IsBase64(e)||-1===e.indexOf("..")}static _GetDrawMode(e,n){switch(null==n&&(n=4),n){case 0:return t.Material.PointListDrawMode;case 1:return t.Material.LineListDrawMode;case 2:return t.Material.LineLoopDrawMode;case 3:return t.Material.LineStripDrawMode;case 4:return t.Material.TriangleFillMode;case 5:return t.Material.TriangleStripDrawMode;case 6:return t.Material.TriangleFanDrawMode}throw new Error(`${e}: Invalid mesh primitive mode (${n})`)}_compileMaterialsAsync(){this._parent._startPerformanceCounter("Compile materials");const e=new Array;if(this._gltf.materials)for(const t of this._gltf.materials)if(t._data)for(const n in t._data){const o=t._data[n];for(const t of o.babylonMeshes){t.computeWorldMatrix(!0);const n=o.babylonMaterial;e.push(n.forceCompilationAsync(t)),e.push(n.forceCompilationAsync(t,{useInstances:!0})),this._parent.useClipPlane&&(e.push(n.forceCompilationAsync(t,{clipPlane:!0})),e.push(n.forceCompilationAsync(t,{clipPlane:!0,useInstances:!0})))}}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile materials")})}_compileShadowGeneratorsAsync(){this._parent._startPerformanceCounter("Compile shadow generators");const e=new Array,t=this._babylonScene.lights;for(const n of t){const t=n.getShadowGenerator();t&&e.push(t.forceCompilationAsync())}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile shadow generators")})}_forEachExtensions(e){for(const t of this._extensions)t.enabled&&e(t)}_applyExtensions(e,t,n){for(const o of this._extensions)if(o.enabled){const s=`${o.name}.${t}`,r=e;r._activeLoaderExtensionFunctions=r._activeLoaderExtensionFunctions||{};const i=r._activeLoaderExtensionFunctions;if(!i[s]){i[s]=!0;try{const e=n(o);if(e)return e}finally{delete i[s]}}}return null}_extensionsOnLoading(){this._forEachExtensions(e=>e.onLoading&&e.onLoading())}_extensionsOnReady(){this._forEachExtensions(e=>e.onReady&&e.onReady())}_extensionsLoadSceneAsync(e,t){return this._applyExtensions(t,"loadScene",n=>n.loadSceneAsync&&n.loadSceneAsync(e,t))}_extensionsLoadNodeAsync(e,t,n){return this._applyExtensions(t,"loadNode",o=>o.loadNodeAsync&&o.loadNodeAsync(e,t,n))}_extensionsLoadCameraAsync(e,t,n){return this._applyExtensions(t,"loadCamera",o=>o.loadCameraAsync&&o.loadCameraAsync(e,t,n))}_extensionsLoadVertexDataAsync(e,t,n){return this._applyExtensions(t,"loadVertexData",o=>o._loadVertexDataAsync&&o._loadVertexDataAsync(e,t,n))}_extensionsLoadMeshPrimitiveAsync(e,t,n,o,s,r){return this._applyExtensions(s,"loadMeshPrimitive",i=>i._loadMeshPrimitiveAsync&&i._loadMeshPrimitiveAsync(e,t,n,o,s,r))}_extensionsLoadMaterialAsync(e,t,n,o,s){return this._applyExtensions(t,"loadMaterial",r=>r._loadMaterialAsync&&r._loadMaterialAsync(e,t,n,o,s))}_extensionsCreateMaterial(e,t,n){return this._applyExtensions(t,"createMaterial",o=>o.createMaterial&&o.createMaterial(e,t,n))}_extensionsLoadMaterialPropertiesAsync(e,t,n){return this._applyExtensions(t,"loadMaterialProperties",o=>o.loadMaterialPropertiesAsync&&o.loadMaterialPropertiesAsync(e,t,n))}_extensionsLoadTextureInfoAsync(e,t,n){return this._applyExtensions(t,"loadTextureInfo",o=>o.loadTextureInfoAsync&&o.loadTextureInfoAsync(e,t,n))}_extensionsLoadTextureAsync(e,t,n){return this._applyExtensions(t,"loadTexture",o=>o._loadTextureAsync&&o._loadTextureAsync(e,t,n))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",n=>n.loadAnimationAsync&&n.loadAnimationAsync(e,t))}_extensionsLoadAnimationChannelAsync(e,t,n,o,s){return this._applyExtensions(n,"loadAnimationChannel",r=>r._loadAnimationChannelAsync&&r._loadAnimationChannelAsync(e,t,n,o,s))}_extensionsLoadSkinAsync(e,t,n){return this._applyExtensions(n,"loadSkin",o=>o._loadSkinAsync&&o._loadSkinAsync(e,t,n))}_extensionsLoadUriAsync(e,t,n){return this._applyExtensions(t,"loadUri",o=>o._loadUriAsync&&o._loadUriAsync(e,t,n))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",n=>n.loadBufferViewAsync&&n.loadBufferViewAsync(e,t))}_extensionsLoadBufferAsync(e,t,n,o){return this._applyExtensions(t,"loadBuffer",s=>s.loadBufferAsync&&s.loadBufferAsync(e,t,n,o))}static LoadExtensionAsync(e,t,n,o){if(!t.extensions)return null;const s=t.extensions[n];return s?o(`${e}/extensions/${n}`,s):null}static LoadExtraAsync(e,t,n,o){if(!t.extras)return null;const s=t.extras[n];return s?o(`${e}/extras/${n}`,s):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&-1!==this._gltf.extensionsUsed.indexOf(e)}logOpen(e){this._parent._logOpen(e)}logClose(){this._parent._logClose()}log(e){this._parent._log(e)}startPerformanceCounter(e){this._parent._startPerformanceCounter(e)}endPerformanceCounter(e){this._parent._endPerformanceCounter(e)}}yo.DefaultSampler={index:-1};let vo=!1;function bo(){vo||(vo=!0,mn._CreateGLTF2Loader=e=>new yo(e))}bo(),pn();var xo={__proto__:null,ArrayItem:_o,GLTFFileLoader:mn,GLTFLoader:yo,LoadBoundingInfoFromPositionAccessor:go,RegisterGLTF2Loader:bo};function To(e,n,o,s){return t.Vector3.FromArray(n,o).scaleInPlace(s)}function Ao(e,n,o,s){return t.Quaternion.FromArray(n,o).scaleInPlace(s)}function Mo(e,t,n,o){const s=new Array(e._numMorphTargets);for(let e=0;e<s.length;e++)s[e]=t[n++]*o;return s}class wo{constructor(e,t,n,o){this.type=e,this.name=t,this.getValue=n,this.getStride=o}_buildAnimation(e,n,o){const s=new t.Animation(e,this.name,n,this.type);return s.setKeys(o,!0),s}}class Co extends wo{buildAnimations(e,t,n,o){const s=[];return s.push({babylonAnimatable:e._babylonTransformNode,babylonAnimation:this._buildAnimation(t,n,o)}),s}}class Ro extends wo{buildAnimations(e,n,o,s){const r=[];if(e._numMorphTargets)for(let i=0;i<e._numMorphTargets;i++){const a=new t.Animation(`${n}_${i}`,this.name,o,this.type);if(a.setKeys(s.map(e=>({frame:e.frame,inTangent:e.inTangent?e.inTangent[i]:void 0,value:e.value[i],outTangent:e.outTangent?e.outTangent[i]:void 0,interpolation:e.interpolation})),!0),e._primitiveBabylonMeshes)for(const t of e._primitiveBabylonMeshes)if(t.morphTargetManager){const e=t.morphTargetManager.getTarget(i),n=a.clone();e.animations.push(n),r.push({babylonAnimatable:e,babylonAnimation:n})}}return r}}ho("/nodes/{}/translation",[new Co(t.Animation.ANIMATIONTYPE_VECTOR3,"position",To,()=>3)]),ho("/nodes/{}/rotation",[new Co(t.Animation.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",Ao,()=>4)]),ho("/nodes/{}/scale",[new Co(t.Animation.ANIMATIONTYPE_VECTOR3,"scaling",To,()=>3)]),ho("/nodes/{}/weights",[new Ro(t.Animation.ANIMATIONTYPE_FLOAT,"influence",Mo,e=>e._numMorphTargets)]);var Oo={__proto__:null,AnimationPropertyInfo:wo,TransformNodeAnimationPropertyInfo:Co,WeightAnimationPropertyInfo:Ro,getQuaternion:Ao,getVector3:To,getWeights:Mo};class So{constructor(e){this._specWorkflow=!1,this._diffuseTransmissionTint=t.Color3.White(),this._diffuseTransmissionTintTexture=null,this._material=e}get material(){return this._material}get isUnlit(){return this._material.unlit}set isUnlit(e){this._material.unlit=e}set backFaceCulling(e){this._material.backFaceCulling=e}get backFaceCulling(){return this._material.backFaceCulling}set twoSidedLighting(e){this._material.twoSidedLighting=e}get twoSidedLighting(){return this._material.twoSidedLighting}set alphaCutOff(e){this._material.alphaCutOff=e}get alphaCutOff(){return this._material.alphaCutOff}set useAlphaFromBaseColorTexture(e){this._material._useAlphaFromBaseColorTexture=e}get useAlphaFromBaseColorTexture(){return this._material._useAlphaFromBaseColorTexture}get transparencyAsAlphaCoverage(){return!1}set transparencyAsAlphaCoverage(e){}set baseColor(e){this._material.baseColor=e}get baseColor(){return this._material.baseColor}set baseColorTexture(e){this._material.baseColorTexture=e}get baseColorTexture(){return this._material.baseColorTexture}set baseDiffuseRoughness(e){this._material.baseDiffuseRoughness=e}get baseDiffuseRoughness(){return this._material.baseDiffuseRoughness}set baseDiffuseRoughnessTexture(e){this._material.baseDiffuseRoughnessTexture=e}get baseDiffuseRoughnessTexture(){return this._material.baseDiffuseRoughnessTexture}set baseMetalness(e){this._material.baseMetalness=e}get baseMetalness(){return this._material.baseMetalness}set baseMetalnessTexture(e){this._material.baseMetalnessTexture=e}get baseMetalnessTexture(){return this._material.baseMetalnessTexture}set useRoughnessFromMetallicTextureGreen(e){this._material._useRoughnessFromMetallicTextureGreen=e}set useMetallicFromMetallicTextureBlue(e){this._material._useMetallicFromMetallicTextureBlue=e}enableSpecularEdgeColor(e=!1){}configureSpecularGlossiness(){this._specWorkflow=!0}set specularWeight(e){this._material.specularWeight=e}get specularWeight(){return this._material.specularWeight}set specularWeightTexture(e){this._material.specularColorTexture===e?(this._material.specularWeightTexture=null,this._material._useSpecularWeightFromSpecularColorTexture=!0,this._material._useSpecularWeightFromAlpha=!0):this._material.specularWeightTexture=e}get specularWeightTexture(){return this._material.specularWeightTexture}set specularColor(e){this._material.specularColor=e}get specularColor(){return this._material.specularColor}set specularColorTexture(e){this._material.specularColorTexture=e,this._material.specularWeightTexture===this._material.specularColorTexture&&(this._material.specularWeightTexture=null,this._material._useSpecularWeightFromSpecularColorTexture=!0,this._material._useSpecularWeightFromAlpha=!0)}get specularColorTexture(){return this._material.specularColorTexture}set specularRoughness(e){this._material.specularRoughness=e}get specularRoughness(){return this._material.specularRoughness}set specularRoughnessTexture(e){this._material.specularRoughnessTexture=e}get specularRoughnessTexture(){return this._material.specularRoughnessTexture}set specularIor(e){this._material.specularIor=e}get specularIor(){return this._material.specularIor}set glossiness(e){this._material.specularRoughness=Math.max(1-e,0)}get glossiness(){return 1-this._material.specularRoughness}set emissionColor(e){this._material.emissionColor=e}get emissionColor(){return this._material.emissionColor}set emissionLuminance(e){this._material.emissionLuminance=e}get emissionLuminance(){return this._material.emissionLuminance}set emissionColorTexture(e){this._material.emissionColorTexture=e}get emissionColorTexture(){return this._material.emissionColorTexture}set ambientOcclusionTexture(e){this._material.ambientOcclusionTexture=e}get ambientOcclusionTexture(){return this._material.ambientOcclusionTexture}set ambientOcclusionTextureStrength(e){const t=this._material.ambientOcclusionTexture;t&&(t.level=e)}get ambientOcclusionTextureStrength(){var e;const t=this._material.ambientOcclusionTexture;return null!==(e=null==t?void 0:t.level)&&void 0!==e?e:1}configureCoat(){}set coatWeight(e){this._material.coatWeight=e}get coatWeight(){return this._material.coatWeight}set coatWeightTexture(e){this._material.coatWeightTexture=e}get coatWeightTexture(){return this._material.coatWeightTexture}set coatColor(e){this._material.coatColor=e}get coatColor(){return this._material.coatColor}set coatColorTexture(e){this._material.coatColorTexture=e}set coatRoughness(e){this._material.coatRoughness=e}get coatRoughness(){return this._material.coatRoughness}set coatRoughnessTexture(e){this._material.coatRoughnessTexture=e,e&&(this._material._useCoatRoughnessFromGreenChannel=!0)}get coatRoughnessTexture(){return this._material.coatRoughnessTexture}set coatIor(e){this._material.coatIor=e}get coatIor(){return this._material.coatIor}set coatDarkening(e){this._material.coatDarkening=e}get coatDarkening(){return this._material.coatDarkening}set coatDarkeningTexture(e){this._material.coatDarkeningTexture=e}set coatRoughnessAnisotropy(e){this._material.coatRoughnessAnisotropy=e}get coatRoughnessAnisotropy(){return this._material.coatRoughnessAnisotropy}set geometryCoatTangentAngle(e){this._material.geometryCoatTangentAngle=e}set geometryCoatTangentTexture(e){this._material.geometryCoatTangentTexture=e,e&&(this._material._useCoatRoughnessAnisotropyFromTangentTexture=!0)}get geometryCoatTangentTexture(){return this._material.geometryCoatTangentTexture}configureTransmission(){this._material.geometryThinWalled=1,this._material.transmissionDepth=0}set transmissionWeight(e){this._material.transmissionWeight=e}set transmissionWeightTexture(e){this._material.transmissionWeightTexture=e}get transmissionWeightTexture(){return this._material.transmissionWeightTexture}get transmissionWeight(){return this._material.transmissionWeight}set transmissionScatter(e){this._material.transmissionScatter=e}get transmissionScatter(){return this._material.transmissionScatter}set transmissionScatterTexture(e){this._material.transmissionScatterTexture=e}get transmissionScatterTexture(){return this._material.transmissionScatterTexture}set transmissionScatterAnisotropy(e){this._material.transmissionScatterAnisotropy=e}set transmissionDispersionAbbeNumber(e){this._material.transmissionDispersionAbbeNumber=e}set transmissionDispersionScale(e){this._material.transmissionDispersionScale=e}set transmissionDepth(e){e!==Number.MAX_VALUE||0!==this._material.transmissionDepth?this._material.transmissionDepth=e:this._material.transmissionDepth=0}get transmissionDepth(){return this._material.transmissionDepth}set transmissionColor(e){e.equals(t.Color3.White())||(this._material.transmissionColor=e)}get transmissionColor(){return this._material.transmissionColor}get refractionBackgroundTexture(){return this._material.backgroundRefractionTexture}set refractionBackgroundTexture(e){this._material.backgroundRefractionTexture=e}configureVolume(){this._material.geometryThinWalled=0}set geometryThinWalled(e){this._material.geometryThinWalled=e?1:0}get geometryThinWalled(){return!!this._material.geometryThinWalled}set volumeThicknessTexture(e){this._material.geometryThicknessTexture=e,this._material._useGeometryThicknessFromGreenChannel=!0}set volumeThickness(e){this._material.geometryThickness=e}configureSubsurface(){this._material.geometryThinWalled=1,this._material.subsurfaceScatterAnisotropy=1}set subsurfaceWeight(e){this._material.subsurfaceWeight=e}get subsurfaceWeight(){return this._material.subsurfaceWeight}set subsurfaceWeightTexture(e){this._material.subsurfaceWeightTexture=e,this._material._useSubsurfaceWeightFromTextureAlpha=!0}get subsurfaceWeightTexture(){return this._material.subsurfaceWeightTexture}set subsurfaceColor(e){this._material.subsurfaceColor=e}set subsurfaceColorTexture(e){this._material.subsurfaceColorTexture=e}set diffuseTransmissionTint(e){this._diffuseTransmissionTint=e}get diffuseTransmissionTint(){return this._diffuseTransmissionTint}set diffuseTransmissionTintTexture(e){this._diffuseTransmissionTintTexture=e}get subsurfaceRadius(){return this._material.subsurfaceRadius}set subsurfaceRadius(e){this._material.subsurfaceRadius=e}get subsurfaceRadiusScale(){return this._material.subsurfaceRadiusScale}set subsurfaceRadiusScale(e){this._material.subsurfaceRadiusScale=e}set subsurfaceScatterAnisotropy(e){this._material.subsurfaceScatterAnisotropy=e}isTranslucent(){return this.transmissionWeight>0||this.subsurfaceWeight>0}configureFuzz(){}set fuzzWeight(e){this._material.fuzzWeight=e}set fuzzWeightTexture(e){this._material.fuzzWeightTexture=e}set fuzzColor(e){this._material.fuzzColor=e}set fuzzColorTexture(e){this._material.fuzzColorTexture=e}set fuzzRoughness(e){this._material.fuzzRoughness=e}set fuzzRoughnessTexture(e){this._material.fuzzRoughnessTexture=e,this._material._useFuzzRoughnessFromTextureAlpha=!0}set specularRoughnessAnisotropy(e){this._material.specularRoughnessAnisotropy=e}get specularRoughnessAnisotropy(){return this._material.specularRoughnessAnisotropy}set geometryTangentAngle(e){this._material.geometryTangentAngle=e}set geometryTangentTexture(e){this._material.geometryTangentTexture=e,this._material._useSpecularRoughnessAnisotropyFromTangentTexture=!0}get geometryTangentTexture(){return this._material.geometryTangentTexture}configureGltfStyleAnisotropy(e=!0){this._material._useGltfStyleAnisotropy=e}set thinFilmWeight(e){this._material.thinFilmWeight=e}set thinFilmIor(e){this._material.thinFilmIor=e}set thinFilmThicknessMinimum(e){this._material.thinFilmThicknessMin=e/1e3}set thinFilmThicknessMaximum(e){this._material.thinFilmThickness=e/1e3}set thinFilmWeightTexture(e){this._material.thinFilmWeightTexture=e}set thinFilmThicknessTexture(e){this._material.thinFilmThicknessTexture=e,this._material._useThinFilmThicknessFromTextureGreen=!0}set unlit(e){this._material.unlit=e}set geometryOpacity(e){this._material.geometryOpacity=e}get geometryOpacity(){return this._material.geometryOpacity}set geometryNormalTexture(e){this._material.geometryNormalTexture=e}get geometryNormalTexture(){return this._material.geometryNormalTexture}setNormalMapInversions(e,t){}set geometryCoatNormalTexture(e){this._material.geometryCoatNormalTexture=e}get geometryCoatNormalTexture(){return this._material.geometryCoatNormalTexture}set geometryCoatNormalTextureScale(e){this._material.geometryCoatNormalTexture&&(this._material.geometryCoatNormalTexture.level=e)}finalizeAsync(e){return b(this,void 0,void 0,function*(){var n,o,s;if(this._diffuseTransmissionTint&&!this._diffuseTransmissionTint.equals(t.Color3.White())||this._diffuseTransmissionTintTexture)if(this._material.geometryThinWalled)this.subsurfaceColor=this._diffuseTransmissionTint,this.subsurfaceColorTexture=this._diffuseTransmissionTintTexture;else if(yield this.copySurfaceToCoatAsync(e,this.subsurfaceWeight,this.subsurfaceWeightTexture,t.TextureChannel.A,this._diffuseTransmissionTint,this._diffuseTransmissionTintTexture,!0),e._disposed)return;if(this.transmissionWeight>0)if(this._material.geometryThinWalled||0===this._material.transmissionDepth)this._material.transmissionColor=this._material.baseColor,this._material.transmissionColorTexture=this._material.baseColorTexture;else if((!this.baseColor.equals(t.Color3.White())||null!==this.baseColorTexture)&&(yield this.copySurfaceToCoatAsync(e,this.transmissionWeight,this.transmissionWeightTexture,t.TextureChannel.R,this.baseColor,this.baseColorTexture,!1),e._disposed))return;if(this._specWorkflow){const r=yield t.InvertTextureAsync("newRoughnessTexture ("+this._material.name+")",yield t.ExtractChannelAsync("glossiness ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.specularColorTexture,new t.Color4(this.specularColor.r,this.specularColor.g,this.specularColor.b,this.glossiness),t.TextureChannel.A,t.TextureColorSpace.Linear),t.TextureChannel.A,this._material.getScene(),t.TextureColorSpace.Linear,t.ChannelMask.R),this._material.getScene(),t.ChannelMask.R,t.TextureColorSpace.Linear,t.ChannelMask.R);if(e._disposed)return void(null===(n=r.texture)||void 0===n||n.dispose());this.specularRoughnessTexture=r.texture,this.specularRoughness=r.factor?r.factor.r:1;const i=yield t.ExtractMaxChannelAsync("metallicTexture ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.specularColorTexture,this.specularColor.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.Linear),this._material.getScene(),!1,t.TextureColorSpace.SRGB,t.ChannelMask.RGB);if(e._disposed)return void(null===(o=i.texture)||void 0===o||o.dispose());this.baseMetalnessTexture=i.texture,this.baseMetalness=i.factor?i.factor.r:1;const a=yield t.LerpTexturesAsync("newBaseColor ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.baseColorTexture,this.baseColor.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.Linear),t.CreateTextureWithFactorOperand(this.specularColorTexture,this.specularColor.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.Linear),Object.assign(Object.assign({},i),{dispose:void 0,colorSpace:t.TextureColorSpace.Linear}),this._material.getScene(),t.TextureColorSpace.SRGB,t.ChannelMask.RGB);if(e._disposed)return void(null===(s=a.texture)||void 0===s||s.dispose());const l=this.baseColorTexture;null==l||l.dispose(),this.baseColorTexture=a.texture,this.baseColor=a.factor?new t.Color3(a.factor.r,a.factor.g,a.factor.b):t.Color3.White();const u=this.specularColorTexture;null==u||u.dispose(),this.specularColorTexture=null}})}copySurfaceToCoatAsync(e,n,o,s,r,i){return b(this,arguments,void 0,function*(e,n,o,s,r,i,a=!1){var l,u,c,d,h,m,f,p,_;const g=this._material.coatWeight,y=this._material.coatWeightTexture,v=this._material.coatColor.clone(),b=this._material.coatColorTexture,x=this._material.geometryCoatNormalTexture,T=new t.Color4(g,g,g,g),A=new t.Color4(n,n,n,n);this.coatWeightTexture=null,this.coatWeight=1;const M=yield Promise.allSettled([t.LerpTexturesAsync("lerpExistingCoat",t.CreateTextureWithFactorOperand(null,new t.Color4(1,1,1,1)),t.CreateTextureWithFactorOperand(b,v.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.SRGB),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene(),t.TextureColorSpace.SRGB),t.LerpTexturesAsync("lerpSurfaceColor",t.CreateTextureWithFactorOperand(null,new t.Color4(1,1,1,1)),t.CreateTextureWithFactorOperand(i,r.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.SRGB),t.CreateTextureWithFactorOperand(o,A,s),this._material.getScene(),t.TextureColorSpace.SRGB)]),w=M.find(e=>"rejected"===e.status);if(w){for(const e of M)"fulfilled"===e.status&&(null===(l=e.value.texture)||void 0===l||l.dispose());throw w.reason}const[C,R]=M.map(e=>e.value);if(e._disposed)return null===(u=C.texture)||void 0===u||u.dispose(),void(null===(c=R.texture)||void 0===c||c.dispose());const O=yield t.MultiplyTexturesAsync("newCoatColor ("+this._material.name+")",C,R,this._material.getScene(),t.TextureColorSpace.SRGB);if(e._disposed)return void(null===(d=O.texture)||void 0===d||d.dispose());O.texture?(this.coatColorTexture=O.texture,this.coatColor=t.Color3.White()):O.factor&&(this.coatColorTexture=null,this.coatColor.fromArray([O.factor.r,O.factor.g,O.factor.b]));const S=yield t.LerpTexturesAsync("newCoatIor ("+this._material.name+")",t.CreateTextureWithFactorOperand(null,new t.Color4(this._material.specularIor,this._material.specularIor,this._material.specularIor,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(null,new t.Color4(this.coatIor,this.coatIor,this.coatIor,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(h=S.texture)||void 0===h||h.dispose());this.coatIor=S.factor?S.factor.r:this.coatIor;const F=yield t.LerpTexturesAsync("newCoatRoughness ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.specularRoughnessTexture,new t.Color4(this.specularRoughness,this.specularRoughness,this.specularRoughness,1),t.TextureChannel.G),t.CreateTextureWithFactorOperand(this.coatRoughnessTexture,new t.Color4(this.coatRoughness,this.coatRoughness,this.coatRoughness,1),t.TextureChannel.G),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(m=F.texture)||void 0===m||m.dispose());this.coatRoughness=F.factor?F.factor.r:1,this.coatRoughnessTexture=F.texture;const E=yield t.LerpTexturesAsync("newCoatDarkening ("+this._material.name+")",t.CreateTextureWithFactorOperand(null,new t.Color4(0,0,0,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(null,new t.Color4(this.coatDarkening,this.coatDarkening,this.coatDarkening,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)null===(f=E.texture)||void 0===f||f.dispose();else{if(this.coatDarkening=E.factor?E.factor.r:this.coatDarkening,a){const n=yield t.LerpTexturesAsync("newSpecularRoughness ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.specularRoughnessTexture,new t.Color4(this._material.specularRoughness,this._material.specularRoughness,this._material.specularRoughness,1),t.TextureChannel.G),t.CreateTextureWithFactorOperand(null,new t.Color4(1,1,1,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(o,A,s),this._material.getScene());if(e._disposed)return void(null===(p=n.texture)||void 0===p||p.dispose());this.specularRoughness=n.factor?n.factor.r:1,this.specularRoughnessTexture=n.texture}if(x||this.geometryNormalTexture){const n=yield t.LerpTexturesAsync("newCoatNormal ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.geometryNormalTexture,this.geometryNormalTexture?new t.Color4(1,1,1,1):new t.Color4(.5,.5,1,1),t.TextureChannel.RGBA),t.CreateTextureWithFactorOperand(x,x?new t.Color4(1,1,1,1):new t.Color4(.5,.5,1,1),t.TextureChannel.RGBA),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(_=n.texture)||void 0===_||_.dispose());n.texture&&(this.geometryCoatNormalTexture=n.texture)}}})}}var Fo={__proto__:null,OpenPBRMaterialLoadingAdapter:So};class Eo{constructor(e){this._specWorkflow=!1,this._material=e,this._material.enableSpecularAntiAliasing=!0}get material(){return this._material}finalizeAsync(e){return b(this,void 0,void 0,function*(){})}get isUnlit(){return this._material.unlit}set isUnlit(e){this._material.unlit=e}set backFaceCulling(e){this._material.backFaceCulling=e}get backFaceCulling(){return this._material.backFaceCulling}set twoSidedLighting(e){this._material.twoSidedLighting=e}get twoSidedLighting(){return this._material.twoSidedLighting}set alphaCutOff(e){this._material.alphaCutOff=e}get alphaCutOff(){return this._material.alphaCutOff}set useAlphaFromBaseColorTexture(e){this._material.useAlphaFromAlbedoTexture=e}get useAlphaFromBaseColorTexture(){return this._material.useAlphaFromAlbedoTexture}get transparencyAsAlphaCoverage(){return this._material.useRadianceOverAlpha||this._material.useSpecularOverAlpha}set transparencyAsAlphaCoverage(e){this._material.useRadianceOverAlpha=!e,this._material.useSpecularOverAlpha=!e}set baseColor(e){this._material.albedoColor=e}get baseColor(){return this._material.albedoColor}set baseColorTexture(e){this._material.albedoTexture=e}get baseColorTexture(){return this._material.albedoTexture}set baseDiffuseRoughness(e){this._material.baseDiffuseRoughness=e,e>0&&(this._material.brdf.baseDiffuseModel=t.Constants.MATERIAL_DIFFUSE_MODEL_E_OREN_NAYAR)}get baseDiffuseRoughness(){var e;return null!==(e=this._material.baseDiffuseRoughness)&&void 0!==e?e:0}set baseDiffuseRoughnessTexture(e){this._material.baseDiffuseRoughnessTexture=e}get baseDiffuseRoughnessTexture(){return this._material.baseDiffuseRoughnessTexture}set baseMetalness(e){this._material.metallic=e}get baseMetalness(){var e;return null!==(e=this._material.metallic)&&void 0!==e?e:1}set baseMetalnessTexture(e){this._material.metallicTexture=e}get baseMetalnessTexture(){return this._material.metallicTexture}set useRoughnessFromMetallicTextureGreen(e){this._material.useRoughnessFromMetallicTextureGreen=e,this._material.useRoughnessFromMetallicTextureAlpha=!e}set useMetallicFromMetallicTextureBlue(e){this._material.useMetallnessFromMetallicTextureBlue=e}enableSpecularEdgeColor(e=!1){e&&(this._material.brdf.dielectricSpecularModel=t.Constants.MATERIAL_DIELECTRIC_SPECULAR_MODEL_OPENPBR,this._material.brdf.conductorSpecularModel=t.Constants.MATERIAL_CONDUCTOR_SPECULAR_MODEL_OPENPBR)}configureSpecularGlossiness(){this._specWorkflow=!0,this._material.metallic=null,this._material.roughness=null,this._material.useMicroSurfaceFromReflectivityMapAlpha=!0}set specularWeight(e){this._material.metallicF0Factor=e}get specularWeight(){var e;return null!==(e=this._material.metallicF0Factor)&&void 0!==e?e:1}set specularWeightTexture(e){e?(this._material.metallicReflectanceTexture=e,this._material.useOnlyMetallicFromMetallicReflectanceTexture=!0):(this._material.metallicReflectanceTexture=null,this._material.useOnlyMetallicFromMetallicReflectanceTexture=!1)}get specularWeightTexture(){return this._material.metallicReflectanceTexture}set specularColor(e){this._specWorkflow?this._material.reflectivityColor=e:this._material.metallicReflectanceColor=e}get specularColor(){return this._specWorkflow?this._material.reflectivityColor:this._material.metallicReflectanceColor}set specularColorTexture(e){this._specWorkflow?(this._material.reflectivityTexture=e,this._material.reflectivityTexture&&(this._material.reflectivityTexture.hasAlpha=!0)):this._material.reflectanceTexture=e}get specularColorTexture(){return this._specWorkflow?this._material.reflectivityTexture:this._material.reflectanceTexture}set specularRoughness(e){this._material.roughness=e}get specularRoughness(){var e;return null!==(e=this._material.roughness)&&void 0!==e?e:1}set specularRoughnessTexture(e){this.baseMetalnessTexture||(this._material.metallicTexture=e)}get specularRoughnessTexture(){return this._material.metallicTexture}set specularIor(e){this._material.indexOfRefraction=e}get specularIor(){return this._material.indexOfRefraction}get glossiness(){var e;return null!==(e=this._material.microSurface)&&void 0!==e?e:1}set glossiness(e){this._material.microSurface=e}set emissionColor(e){this._material.emissiveColor=e}get emissionColor(){return this._material.emissiveColor}set emissionLuminance(e){this._material.emissiveIntensity=e}get emissionLuminance(){return this._material.emissiveIntensity}set emissionColorTexture(e){this._material.emissiveTexture=e}get emissionColorTexture(){return this._material.emissiveTexture}set ambientOcclusionTexture(e){this._material.ambientTexture=e,e&&(this._material.useAmbientInGrayScale=!0)}get ambientOcclusionTexture(){return this._material.ambientTexture}set ambientOcclusionTextureStrength(e){this._material.ambientTextureStrength=e}get ambientOcclusionTextureStrength(){var e;return null!==(e=this._material.ambientTextureStrength)&&void 0!==e?e:1}configureCoat(){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.useRoughnessFromMainTexture=!1,this._material.clearCoat.remapF0OnInterfaceChange=!1}set coatWeight(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.intensity=e}get coatWeight(){return this._material.clearCoat.intensity}set coatWeightTexture(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.texture=e}get coatWeightTexture(){return this._material.clearCoat.texture}set coatColor(e){this._material.clearCoat.isTintEnabled=e!=t.Color3.White(),this._material.clearCoat.tintColor=e}set coatColorTexture(e){this._material.clearCoat.tintTexture=e}set coatRoughness(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.roughness=e}get coatRoughness(){var e;return null!==(e=this._material.clearCoat.roughness)&&void 0!==e?e:0}set coatRoughnessTexture(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.useRoughnessFromMainTexture=!1,this._material.clearCoat.textureRoughness=e}get coatRoughnessTexture(){return this._material.clearCoat.textureRoughness}set coatIor(e){this._material.clearCoat.indexOfRefraction=e}set coatDarkening(e){}set coatDarkeningTexture(e){}set coatRoughnessAnisotropy(e){}get coatRoughnessAnisotropy(){return 0}set geometryCoatTangentAngle(e){}set geometryCoatTangentTexture(e){}get geometryCoatTangentTexture(){return null}set transmissionWeight(e){this._material.subSurface.isRefractionEnabled=e>0,this._material.subSurface.refractionIntensity=e}get transmissionWeight(){return this._material.subSurface.isRefractionEnabled?this._material.subSurface.refractionIntensity:0}set transmissionWeightTexture(e){this._material.subSurface.isRefractionEnabled=!0,this._material.subSurface.refractionIntensityTexture=e,this._material.subSurface.useGltfStyleTextures=!0}set transmissionDepth(e){this.transmissionWeight>0?this._material.subSurface.tintColorAtDistance=e:this.subsurfaceWeight>0&&this._material.subSurface.diffusionDistance.multiplyInPlace(new t.Color3(e,e,e))}get transmissionDepth(){return this.transmissionWeight>0?this._material.subSurface.tintColorAtDistance:0}set transmissionColor(e){this.transmissionWeight>0?this._material.subSurface.tintColor=e:this.subsurfaceWeight>0&&this._material.subSurface.diffusionDistance.multiplyInPlace(e)}get transmissionColor(){return this.transmissionWeight>0?this._material.subSurface.tintColor:this.subsurfaceWeight>0?this._material.subSurface.diffusionDistance:new t.Color3(0,0,0)}set transmissionScatter(e){this._material.subSurface.diffusionDistance=e}get transmissionScatter(){return this._material.subSurface.diffusionDistance}set transmissionScatterTexture(e){}set transmissionScatterAnisotropy(e){}set transmissionDispersionAbbeNumber(e){}set transmissionDispersionScale(e){e>0?(this._material.subSurface.isDispersionEnabled=!0,this._material.subSurface.dispersion=20/e):(this._material.subSurface.isDispersionEnabled=!1,this._material.subSurface.dispersion=0)}get refractionBackgroundTexture(){return this._material.subSurface.refractionTexture}set refractionBackgroundTexture(e){this._material.subSurface.refractionTexture=e}configureTransmission(){this._material.subSurface.volumeIndexOfRefraction=1,this._material.subSurface.useAlbedoToTintRefraction=!0,this._material.subSurface.minimumThickness=0,this._material.subSurface.maximumThickness=0}configureVolume(){}set geometryThinWalled(e){}get geometryThinWalled(){return 0===this._material.subSurface.maximumThickness}set volumeThicknessTexture(e){this._material.subSurface.thicknessTexture=e,this._material.subSurface.useGltfStyleTextures=!0}set volumeThickness(e){this._material.subSurface.minimumThickness=0,this._material.subSurface.maximumThickness=e,this._material.subSurface.useThicknessAsDepth=!0,e>0&&(this._material.subSurface.volumeIndexOfRefraction=this._material.indexOfRefraction)}configureSubsurface(){this._material.subSurface.useGltfStyleTextures=!0,this._material.subSurface.volumeIndexOfRefraction=1,this._material.subSurface.minimumThickness=0,this._material.subSurface.maximumThickness=0,this._material.subSurface.useAlbedoToTintTranslucency=!1}set subsurfaceWeight(e){this._material.subSurface.isTranslucencyEnabled=e>0,this._material.subSurface.translucencyIntensity=e}get subsurfaceWeight(){return this._material.subSurface.isTranslucencyEnabled?this._material.subSurface.translucencyIntensity:0}set subsurfaceWeightTexture(e){this._material.subSurface.translucencyIntensityTexture=e}set subsurfaceColor(e){const n=new t.Vector3(-Math.log(this.transmissionColor.r),-Math.log(this.transmissionColor.g),-Math.log(this.transmissionColor.b));n.scaleInPlace(1/Math.max(this.transmissionDepth,.001));const o=n,s=Math.max(o.x,Math.max(o.y,o.z)),r=s>0?1/s:1;this._material.subSurface.diffusionDistance=new t.Color3(Math.exp(-o.x*r),Math.exp(-o.y*r),Math.exp(-o.z*r))}set subsurfaceColorTexture(e){}set diffuseTransmissionTint(e){this._material.subSurface.tintColor=e}get diffuseTransmissionTint(){return this._material.subSurface.tintColor}set diffuseTransmissionTintTexture(e){this._material.subSurface.translucencyColorTexture=e}get subsurfaceRadius(){return 1}set subsurfaceRadius(e){}get subsurfaceRadiusScale(){var e;return null!==(e=this._material.subSurface.scatteringDiffusionProfile)&&void 0!==e?e:t.Color3.White()}set subsurfaceRadiusScale(e){this._material.subSurface.scatteringDiffusionProfile=e}set subsurfaceScatterAnisotropy(e){}isTranslucent(){return this.transmissionWeight>0||this.subsurfaceWeight>0}configureFuzz(){this._material.sheen.isEnabled=!0,this._material.sheen.useRoughnessFromMainTexture=!1,this._material.sheen.albedoScaling=!0}set fuzzWeight(e){this._material.sheen.isEnabled=!0,this._material.sheen.intensity=e}set fuzzWeightTexture(e){this._material.sheen.texture||(this._material.sheen.texture=e)}set fuzzColor(e){this._material.sheen.isEnabled=!0,this._material.sheen.color=e}set fuzzColorTexture(e){this._material.sheen.texture=e}set fuzzRoughness(e){this._material.sheen.isEnabled=!0,this._material.sheen.roughness=e}set fuzzRoughnessTexture(e){this._material.sheen.isEnabled=!0,this._material.sheen.textureRoughness=e}set specularRoughnessAnisotropy(e){this._material.anisotropy.isEnabled=!0,this._material.anisotropy.intensity=e}get specularRoughnessAnisotropy(){return this._material.anisotropy.intensity}set geometryTangentAngle(e){this._material.anisotropy.isEnabled=!0,this._material.anisotropy.angle=e}set geometryTangentTexture(e){this._material.anisotropy.isEnabled=!0,this._material.anisotropy.texture=e}get geometryTangentTexture(){return this._material.anisotropy.texture}configureGltfStyleAnisotropy(e=!0){}set thinFilmWeight(e){this._material.iridescence.isEnabled=e>0,this._material.iridescence.intensity=e}set thinFilmIor(e){this._material.iridescence.indexOfRefraction=e}set thinFilmThicknessMinimum(e){this._material.iridescence.minimumThickness=e}set thinFilmThicknessMaximum(e){this._material.iridescence.maximumThickness=e}set thinFilmWeightTexture(e){this._material.iridescence.texture=e}set thinFilmThicknessTexture(e){this._material.iridescence.thicknessTexture=e}set unlit(e){this._material.unlit=e}set geometryOpacity(e){this._material.alpha=e}get geometryOpacity(){return this._material.alpha}set geometryNormalTexture(e){this._material.bumpTexture=e,this._material.forceIrradianceInFragment=!0}get geometryNormalTexture(){return this._material.bumpTexture}setNormalMapInversions(e,t){this._material.invertNormalMapX=e,this._material.invertNormalMapY=t}set geometryCoatNormalTexture(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.bumpTexture=e}get geometryCoatNormalTexture(){return this._material.clearCoat.bumpTexture}set geometryCoatNormalTextureScale(e){this._material.clearCoat.bumpTexture&&(this._material.clearCoat.bumpTexture.level=e)}}var Lo={__proto__:null,PBRMaterialLoadingAdapter:Eo};const Io="EXT_lights_image_based";let No=class{constructor(e){this.name=Io,this._loader=e,this.enabled=this._loader.isExtensionUsed(Io)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights}}loadSceneAsync(e,t){return yo.LoadExtensionAsync(e,t,this.name,(n,o)=>b(this,void 0,void 0,function*(){this._loader._allMaterialsDirtyRequired=!0;const s=new Array;s.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${n}`);const r=_o.Get(`${n}/light`,this._lights,o.light);return s.push(this._loadLightAsync(`/extensions/${this.name}/lights/${o.light}`,r).then(e=>{this._loader.babylonScene.environmentTexture=e})),this._loader.logClose(),yield Promise.all(s).then(()=>{})}))}_loadLightAsync(e,n){if(!n._loaded){const o=new Array;this._loader.logOpen(`${e}`);const s=new Array(n.specularImages.length);for(let t=0;t<n.specularImages.length;t++){const r=n.specularImages[t];s[t]=new Array(r.length);for(let n=0;n<r.length;n++){const i=`${e}/specularImages/${t}/${n}`;this._loader.logOpen(`${i}`);const a=r[n],l=_o.Get(i,this._loader.gltf.images,a);o.push(this._loader.loadImageAsync(`/images/${a}`,l).then(e=>{s[t][n]=e})),this._loader.logClose()}}this._loader.logClose(),n._loaded=Promise.all(o).then(()=>b(this,void 0,void 0,function*(){const o=new t.RawCubeTexture(this._loader.babylonScene,null,n.specularImageSize);if(o.name=n.name||"environment",n._babylonTexture=o,null!=n.intensity&&(o.level=n.intensity),n.rotation){let e=t.Quaternion.FromArray(n.rotation);this._loader.babylonScene.useRightHandedSystem||(e=t.Quaternion.Inverse(e)),t.Matrix.FromQuaternionToRef(e,o.getReflectionTextureMatrix())}if(!n.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const r=t.SphericalHarmonics.FromArray(n.irradianceCoefficients);r.scaleInPlace(n.intensity),r.convertIrradianceToLambertianRadiance();const i=t.SphericalPolynomial.FromHarmonics(r),a=(s.length-1)/Math.log2(n.specularImageSize);return yield o.updateRGBDAsync(s,i,a)}))}return n._loaded.then(()=>n._babylonTexture)}},Po=!1;function Bo(){Po||(Po=!0,no(Io),to(Io,!0,e=>new No(e)))}Bo();var ko={__proto__:null,EXT_lights_image_based:No,RegisterEXT_lights_image_based:Bo};const Do="EXT_mesh_gpu_instancing";let Go=class{constructor(e){this.name=Do,this._loader=e,this.enabled=this._loader.isExtensionUsed(Do)}dispose(){this._loader=null}loadNodeAsync(e,n,o){return yo.LoadExtensionAsync(e,n,this.name,(e,s)=>b(this,void 0,void 0,function*(){this._loader._disableInstancedMesh++;const r=this._loader.loadNodeAsync(`/nodes/${n.index}`,n,o);if(this._loader._disableInstancedMesh--,!n._primitiveBabylonMeshes)return yield r;const i=new Array;let a=0;const l=t=>{if(null==s.attributes[t])return void i.push(Promise.resolve(null));const n=_o.Get(`${e}/attributes/${t}`,this._loader.gltf.accessors,s.attributes[t]);if(i.push(this._loader._loadFloatAccessorAsync(`/accessors/${n.bufferView}`,n)),0===a)a=n.count;else if(a!==n.count)throw new Error(`${e}/attributes: Instance buffer accessors do not have the same count.`)};return l("TRANSLATION"),l("ROTATION"),l("SCALE"),l("_COLOR_0"),yield r.then(e=>b(this,void 0,void 0,function*(){const[o,s,r,l]=yield Promise.all(i),u=new Float32Array(16*a);t.TmpVectors.Vector3[0].copyFromFloats(0,0,0),t.TmpVectors.Quaternion[0].copyFromFloats(0,0,0,1),t.TmpVectors.Vector3[1].copyFromFloats(1,1,1);for(let e=0;e<a;++e)o&&t.Vector3.FromArrayToRef(o,3*e,t.TmpVectors.Vector3[0]),s&&t.Quaternion.FromArrayToRef(s,4*e,t.TmpVectors.Quaternion[0]),r&&t.Vector3.FromArrayToRef(r,3*e,t.TmpVectors.Vector3[1]),t.Matrix.ComposeToRef(t.TmpVectors.Vector3[1],t.TmpVectors.Quaternion[0],t.TmpVectors.Vector3[0],t.TmpVectors.Matrix[0]),t.TmpVectors.Matrix[0].copyToArray(u,16*e);for(const e of n._primitiveBabylonMeshes)e.thinInstanceSetBuffer("matrix",u,16,!0),l&&(l.length===3*a?e.thinInstanceSetBuffer("color",l,3,!0):l.length===4*a?e.thinInstanceSetBuffer("color",l,4,!0):t.Logger.Warn("Unexpected size of _COLOR_0 attribute for mesh "+e.name));return e}))}))}},Vo=!1;function Ho(){Vo||(Vo=!0,no(Do),to(Do,!0,e=>new Go(e)))}Ho();var Ko={__proto__:null,EXT_mesh_gpu_instancing:Go,RegisterEXT_mesh_gpu_instancing:Ho};const Uo="EXT_meshopt_compression";let $o=class{constructor(e){this.name=Uo,this.enabled=e.isExtensionUsed(Uo),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,n){return yo.LoadExtensionAsync(e,n,this.name,(o,s)=>b(this,void 0,void 0,function*(){const o=n;if(o._meshOptData)return yield o._meshOptData;const r=_o.Get(`${e}/buffer`,this._loader.gltf.buffers,s.buffer);return o._meshOptData=this._loader.loadBufferAsync(`/buffers/${r.index}`,r,s.byteOffset||0,s.byteLength).then(e=>b(this,void 0,void 0,function*(){return yield t.MeshoptCompression.Default.decodeGltfBufferAsync(e,s.count,s.byteStride,s.mode,s.filter)})),yield o._meshOptData}))}},Wo=!1;function zo(){Wo||(Wo=!0,no(Uo),to(Uo,!0,e=>new $o(e)))}zo();var jo={__proto__:null,EXT_meshopt_compression:$o,RegisterEXT_meshopt_compression:zo};const qo="EXT_texture_webp";let Xo=class{constructor(e){this.name=qo,this._loader=e,this.enabled=e.isExtensionUsed(qo)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?yo.DefaultSampler:_o.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=_o.Get(`${o}/source`,this._loader.gltf.images,s.source);return yield this._loader._createTextureAsync(e,r,i,e=>{n(e)},void 0,!t._textureInfo.nonColorData)}))}},Yo=!1;function Qo(){Yo||(Yo=!0,no(qo),to(qo,!0,e=>new Xo(e)))}Qo();var Zo={__proto__:null,EXT_texture_webp:Xo,RegisterEXT_texture_webp:Qo};const Jo="EXT_texture_avif";let es=class{constructor(e){this.name=Jo,this._loader=e,this.enabled=e.isExtensionUsed(Jo)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?yo.DefaultSampler:_o.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=_o.Get(`${o}/source`,this._loader.gltf.images,s.source);return yield this._loader._createTextureAsync(e,r,i,e=>{n(e)},void 0,!t._textureInfo.nonColorData)}))}},ts=!1;function ns(){ts||(ts=!0,no(Jo),to(Jo,!0,e=>new es(e)))}ns();var os={__proto__:null,EXT_texture_avif:es,RegisterEXT_texture_avif:ns};const ss="EXT_lights_ies";let rs=class{constructor(e){this.name=ss,this._loader=e,this.enabled=this._loader.isExtensionUsed(ss)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,_o.Assign(this._lights)}}loadNodeAsync(e,n,o){return yo.LoadExtensionAsync(e,n,this.name,(s,r)=>b(this,void 0,void 0,function*(){let i,a;this._loader._allMaterialsDirtyRequired=!0;const l=yield this._loader.loadNodeAsync(e,n,e=>{a=_o.Get(s,this._lights,r.light);const n=a.name||e.name;this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,i=new t.SpotLight(n,t.Vector3.Zero(),t.Vector3.Backward(),0,1,this._loader.babylonScene),i.angle=Math.PI/2,i.innerAngle=0,i._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,a._babylonLight=i,i.falloffType=t.Light.FALLOFF_GLTF,i.diffuse=r.color?t.Color3.FromArray(r.color):t.Color3.White(),i.intensity=r.multiplier||1,i.range=Number.MAX_VALUE,i.parent=e,this._loader._babylonLights.push(i),yo.AddPointerMetadata(i,s),o(e)});let u;if(a.uri)u=yield this._loader.loadUriAsync(e,a,a.uri);else{const t=_o.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,a.bufferView);u=yield this._loader.loadBufferViewAsync(`/bufferViews/${t.index}`,t)}return i.iesProfileTexture=new t.Texture(name+"_iesProfile",this._loader.babylonScene,!0,!1,void 0,null,null,u,!0,void 0,void 0,void 0,void 0,".ies"),l}))}},is=!1;function as(){is||(is=!0,no(ss),to(ss,!0,e=>new rs(e)))}as();var ls={__proto__:null,EXT_lights_ies:rs,RegisterEXT_lights_ies:as};const us="KHR_draco_mesh_compression";let cs=class{constructor(e){this.name=us,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=t.DracoDecoder.DefaultAvailable&&this._loader.isExtensionUsed(us)}dispose(){delete this.dracoDecoder,this._loader=null}_loadVertexDataAsync(e,n,o){return yo.LoadExtensionAsync(e,n,this.name,(s,r)=>b(this,void 0,void 0,function*(){if(null!=n.mode&&4!==n.mode&&5!==n.mode)throw new Error(`${e}: Unsupported mode ${n.mode}`);const i={},a={},l=(e,t)=>{const s=r.attributes[e];if(null!=s&&(o._delayInfo=o._delayInfo||[],-1===o._delayInfo.indexOf(t)&&o._delayInfo.push(t),i[t]=s,this.useNormalizedFlagFromAccessor)){const o=_o.TryGet(this._loader.gltf.accessors,n.attributes[e]);o&&(a[t]=o.normalized||!1)}};l("POSITION",t.VertexBuffer.PositionKind),l("NORMAL",t.VertexBuffer.NormalKind),l("TANGENT",t.VertexBuffer.TangentKind),l("TEXCOORD_0",t.VertexBuffer.UVKind),l("TEXCOORD_1",t.VertexBuffer.UV2Kind),l("TEXCOORD_2",t.VertexBuffer.UV3Kind),l("TEXCOORD_3",t.VertexBuffer.UV4Kind),l("TEXCOORD_4",t.VertexBuffer.UV5Kind),l("TEXCOORD_5",t.VertexBuffer.UV6Kind),l("JOINTS_0",t.VertexBuffer.MatricesIndicesKind),l("WEIGHTS_0",t.VertexBuffer.MatricesWeightsKind),l("COLOR_0",t.VertexBuffer.ColorKind);const u=_o.Get(s,this._loader.gltf.bufferViews,r.bufferView);return u._dracoBabylonGeometry||(u._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${u.index}`,u).then(s=>b(this,void 0,void 0,function*(){const r=this.dracoDecoder||t.DracoDecoder.Default,l=_o.TryGet(this._loader.gltf.accessors,n.attributes.POSITION),u=this._loader.parent.alwaysComputeBoundingBox||o.skeleton||!l?null:go(l);return yield r._decodeMeshToGeometryForGltfAsync(o.name,this._loader.babylonScene,s,i,a,u).catch(t=>{throw new Error(`${e}: ${t.message}`)})}))),yield u._dracoBabylonGeometry}))}},ds=!1;function hs(){ds||(ds=!0,no(us),to(us,!0,e=>new cs(e)))}hs();var ms={__proto__:null,KHR_draco_mesh_compression:cs,RegisterKHR_draco_mesh_compression:hs};const fs="KHR_gaussian_splatting",ps=.28209479177387814,_s=[0,3,5,7];function gs(e){return e<=0?0:e>=255?255:e+.5|0}let ys=class{constructor(e){this.name=fs,this._loader=e,this.enabled=this._loader.isExtensionUsed(fs)}dispose(){this._loader=null}_loadMeshPrimitiveAsync(e,n,o,s,r,i){return yo.LoadExtensionAsync(e,r,this.name,o=>b(this,void 0,void 0,function*(){if(null!=r.mode&&0!==r.mode)throw new Error(`${o}: Gaussian splatting primitives must use POINTS mode`);const s=this._loader,a=t=>{const n=r.attributes[t];if(null==n)return null;const o=_o.Get(`${e}/attributes/${t}`,s.gltf.accessors,n);return s._loadFloatAccessorAsync(`/accessors/${o.index}`,o)},l=a("POSITION");if(!l)throw new Error(`${o}: Gaussian splatting primitive is missing the POSITION attribute`);let u=0;const c=[];for(let e=1;e<=3&&null!=r.attributes[`KHR_gaussian_splatting:SH_DEGREE_${e}_COEF_0`];e++){u=e;for(let t=0;t<_s[e];t++)c.push(`KHR_gaussian_splatting:SH_DEGREE_${e}_COEF_${t}`)}const d=s.babylonScene;d._blockEntityCollection=!!s._assetContainer;const h=new t.GaussianSplattingMesh(n,null,d);h._parentContainer=s._assetContainer,d._blockEntityCollection=!1,yo.AddPointerMetadata(h,e),s.parent.onMeshLoadedObservable.notifyObservers(h),i(h);const m=d.getEngine().getCaps(),[f,p,_,g,y,v,...b]=yield Promise.all([l,a("KHR_gaussian_splatting:ROTATION"),a("KHR_gaussian_splatting:SCALE"),a("KHR_gaussian_splatting:OPACITY"),a("KHR_gaussian_splatting:SH_DEGREE_0_COEF_0"),a("COLOR_0"),...c.map(e=>a(e))]),x=f.length/3,T=v?v.length/x:0,A=new ArrayBuffer(32*x),M=new Float32Array(A),w=new Uint8Array(A);let C=null;if(u>0){const e=3*((u+1)*(u+1)-1),n=Math.ceil(e/16),o=m.maxTextureSize,s=Math.ceil(x/o);C=t.AllocateShBuffers(n,s*o*4*4)}for(let e=0;e<x;e++){const t=8*e,n=32*e,o=3*e;if(M[t+0]=f[o+0],M[t+1]=f[o+1],M[t+2]=f[o+2],M[t+3]=_?_[o+0]:1,M[t+4]=_?_[o+1]:1,M[t+5]=_?_[o+2]:1,y)w[n+24]=gs(255*(.5+ps*y[o+0])),w[n+25]=gs(255*(.5+ps*y[o+1])),w[n+26]=gs(255*(.5+ps*y[o+2]));else if(v){const t=e*T;w[n+24]=gs(255*v[t+0]),w[n+25]=gs(255*v[t+1]),w[n+26]=gs(255*v[t+2])}else w[n+24]=255,w[n+25]=255,w[n+26]=255;w[n+27]=g?gs(255*g[e]):v&&T>=4?gs(255*v[e*T+3]):255;const s=4*e,r=p?p[s+0]:0,i=p?p[s+1]:0,a=p?p[s+2]:0,l=p?p[s+3]:1;if(w[n+28]=gs(127.5*l+127.5),w[n+29]=gs(127.5*r+127.5),w[n+30]=gs(127.5*i+127.5),w[n+31]=gs(127.5*a+127.5),C){const t=16*e;for(let e=0;e<b.length;e++){const n=b[e];if(n)for(let s=0;s<3;s++){const r=3*e+s,i=15&r;C[r>>4][t+i]=gs(128*n[o+s]+128)}}}}return yield h.updateDataAsync(A,null!=C?C:void 0,void 0,u||void 0),h}))}},vs=!1;function bs(){vs||(vs=!0,no(fs),to(fs,!0,e=>new ys(e)))}bs();var xs={__proto__:null,KHR_gaussian_splatting:ys,RegisterKHR_gaussian_splatting:bs};const Ts="KHR_lights_punctual";class As{constructor(e){this.name=Ts,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ts)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,_o.Assign(this._lights)}}loadNodeAsync(e,n,o){return yo.LoadExtensionAsync(e,n,this.name,(s,r)=>b(this,void 0,void 0,function*(){return this._loader._allMaterialsDirtyRequired=!0,yield this._loader.loadNodeAsync(e,n,e=>{let n;const i=_o.Get(s,this._lights,r.light),a=i.name||e.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,i.type){case"directional":{const e=new t.DirectionalLight(a,t.Vector3.Backward(),this._loader.babylonScene);e.position.setAll(0),n=e;break}case"point":n=new t.PointLight(a,t.Vector3.Zero(),this._loader.babylonScene);break;case"spot":{const e=new t.SpotLight(a,t.Vector3.Zero(),t.Vector3.Backward(),0,1,this._loader.babylonScene);e.angle=2*(i.spot&&i.spot.outerConeAngle||Math.PI/4),e.innerAngle=2*(i.spot&&i.spot.innerConeAngle||0),n=e;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${s}: Invalid light type (${i.type})`)}n._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,i._babylonLight=n,n.falloffType=t.Light.FALLOFF_GLTF,n.diffuse=i.color?t.Color3.FromArray(i.color):t.Color3.White(),n.intensity=null==i.intensity?1:i.intensity,n.range=null==i.range?Number.MAX_VALUE:i.range,n.parent=e,this._loader._babylonLights.push(n),yo.AddPointerMetadata(n,s),o(e)})}))}}let Ms=!1;function ws(){Ms||(Ms=!0,no(Ts),to(Ts,!0,e=>new As(e)))}ws();var Cs={__proto__:null,KHR_lights:As,RegisterKHR_lights:ws};const Rs="EXT_lights_area";let Os=class{constructor(e){this.name=Rs,this._loader=e,this.enabled=this._loader.isExtensionUsed(Rs)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,_o.Assign(this._lights)}}loadNodeAsync(e,n,o){return yo.LoadExtensionAsync(e,n,this.name,(s,r)=>b(this,void 0,void 0,function*(){return this._loader._allMaterialsDirtyRequired=!0,yield this._loader.loadNodeAsync(e,n,e=>{var n;let i;const a=_o.Get(s,this._lights,r.light),l=a.name||e.name;this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer;const u=void 0!==a.size?a.size:1;switch(a.type){case"rect":{const e=void 0!==(null===(n=a.rect)||void 0===n?void 0:n.aspect)?a.rect.aspect*u:u,o=u;i=new t.RectAreaLight(l,t.Vector3.Zero(),e,o,this._loader.babylonScene);break}case"disk":{const e=Math.sqrt(u*u*.25*Math.PI);i=new t.RectAreaLight(l,t.Vector3.Zero(),e,e,this._loader.babylonScene);break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${s}: Invalid area light type (${a.type})`)}i._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,a._babylonLight=i,i.falloffType=t.Light.FALLOFF_GLTF,i.diffuse=a.color?t.Color3.FromArray(a.color):t.Color3.White(),i.intensity=null==a.intensity?1:a.intensity;const c=new t.TransformNode(`${l}_orientation`,this._loader.babylonScene);c.rotationQuaternion=t.Quaternion.RotationAxis(t.Vector3.Up(),Math.PI),c.parent=e,i.parent=c,this._loader._babylonLights.push(i),yo.AddPointerMetadata(i,s),o(e)})}))}},Ss=!1;function Fs(){Ss||(Ss=!0,no(Rs),to(Rs,!0,e=>new Os(e)))}Fs();var Es={__proto__:null,EXT_lights_area:Os,RegisterEXT_lights_area:Fs};const Ls="KHR_materials_pbrSpecularGlossiness";let Is=class{constructor(e){this.name=Ls,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ls)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,n)),r.push(this._loadSpecularGlossinessPropertiesAsync(o,s,n)),this._loader.loadMaterialAlphaProperties(e,t,n),yield Promise.all(r).then(()=>{})}))}_loadSpecularGlossinessPropertiesAsync(e,n,o){const s=this._loader._getOrCreateMaterialAdapter(o),r=new Array;return s.configureSpecularGlossiness(),n.diffuseFactor?(s.baseColor=t.Color3.FromArray(n.diffuseFactor),o.alpha=n.diffuseFactor[3]):s.baseColor=t.Color3.White(),s.specularColor=n.specularFactor?t.Color3.FromArray(n.specularFactor):t.Color3.White(),s.glossiness=null==n.glossinessFactor?1:n.glossinessFactor,n.diffuseTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,n.diffuseTexture,e=>{e.name=`${o.name} (Diffuse)`,s.baseColorTexture=e})),n.specularGlossinessTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,n.specularGlossinessTexture,e=>{e.name=`${o.name} (Specular Glossiness)`,s.specularColorTexture=e})),Promise.all(r).then(()=>{})}},Ns=!1;function Ps(){Ns||(Ns=!0,no(Ls),to(Ls,!0,e=>new Is(e)))}Ps();var Bs={__proto__:null,KHR_materials_pbrSpecularGlossiness:Is,RegisterKHR_materials_pbrSpecularGlossiness:Ps};const ks="KHR_materials_unlit";let Ds=class{constructor(e){this.name=ks,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(ks)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,()=>b(this,void 0,void 0,function*(){return yield this._loadUnlitPropertiesAsync(e,t,n)}))}_loadUnlitPropertiesAsync(e,n,o){const s=this._loader._getOrCreateMaterialAdapter(o),r=new Array,i=n.pbrMetallicRoughness;return i&&(i.baseColorFactor&&(s.baseColor=t.Color3.FromArray(i.baseColorFactor),s.geometryOpacity=i.baseColorFactor[3]),i.baseColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,i.baseColorTexture,e=>{e.name=`${o.name} (Base Color)`,s.baseColorTexture=e}))),s.isUnlit=!0,n.doubleSided&&(s.backFaceCulling=!1,s.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,n,o),Promise.all(r).then(()=>{})}},Gs=!1;function Vs(){Gs||(Gs=!0,no(ks),to(ks,!0,e=>new Ds(e)))}Vs();var Hs={__proto__:null,KHR_materials_unlit:Ds,RegisterKHR_materials_unlit:Vs};const Ks="KHR_materials_clearcoat";let Us=class{constructor(e){this.name=Ks,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ks)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadClearCoatPropertiesAsync(o,s,n)),yield Promise.all(r)}))}_loadClearCoatPropertiesAsync(e,t,n){const o=this._loader._getOrCreateMaterialAdapter(n),s=new Array;return o.configureCoat(),o.coatWeight=void 0!==t.clearcoatFactor?t.clearcoatFactor:0,o.coatRoughness=void 0!==t.clearcoatRoughnessFactor?t.clearcoatRoughnessFactor:0,t.clearcoatTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,e=>{e.name=`${n.name} (ClearCoat)`,o.coatWeightTexture=e})),t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,e=>{e.name=`${n.name} (ClearCoat Roughness)`,o.coatRoughnessTexture=e}))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,e=>{var s;e.name=`${n.name} (ClearCoat Normal)`,o.geometryCoatNormalTexture=e,null!=(null===(s=t.clearcoatNormalTexture)||void 0===s?void 0:s.scale)&&(o.geometryCoatNormalTextureScale=t.clearcoatNormalTexture.scale)})),o.setNormalMapInversions(!n.getScene().useRightHandedSystem,n.getScene().useRightHandedSystem)),Promise.all(s).then(()=>{})}},$s=!1;function Ws(){$s||($s=!0,no(Ks),to(Ks,!0,e=>new Us(e)))}Ws();var zs={__proto__:null,KHR_materials_clearcoat:Us,RegisterKHR_materials_clearcoat:Ws};const js="KHR_materials_coat";let qs=class{constructor(e){this.name=js,this.order=191,this.useOpenPBR=!1,this._loader=e,this.enabled=this._loader.isExtensionUsed(js)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),t.extensions&&t.extensions.KHR_materials_openpbr&&(this.useOpenPBR=!0),r.push(this._loadCoatPropertiesAsync(o,s,n)),yield Promise.all(r)}))}_loadCoatPropertiesAsync(e,n,o){var s,r;const i=this._loader._getOrCreateMaterialAdapter(o),a=new Array;i.configureCoat(),i.coatWeight=void 0!==n.coatFactor?n.coatFactor:0,i.coatRoughness=void 0!==n.coatRoughnessFactor?n.coatRoughnessFactor:0,n.coatTexture&&a.push(this._loader.loadTextureInfoAsync(`${e}/coatTexture`,n.coatTexture,e=>{e.name=`${o.name} (Coat)`,i.coatWeightTexture=e})),n.coatRoughnessTexture&&(n.coatRoughnessTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/coatRoughnessTexture`,n.coatRoughnessTexture,e=>{e.name=`${o.name} (Coat Roughness)`,i.coatRoughnessTexture=e}))),n.coatNormalTexture&&(n.coatNormalTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/coatNormalTexture`,n.coatNormalTexture,e=>{var t;e.name=`${o.name} (Coat Normal)`,i.geometryCoatNormalTexture=e,null!=(null===(t=n.coatNormalTexture)||void 0===t?void 0:t.scale)&&(i.geometryCoatNormalTextureScale=n.coatNormalTexture.scale)})),i.setNormalMapInversions(!o.getScene().useRightHandedSystem,o.getScene().useRightHandedSystem)),i.coatDarkening=void 0!==n.coatDarkeningFactor?n.coatDarkeningFactor:1,i.coatIor=void 0!==n.coatIor?n.coatIor:1.5;const l=t.Color3.White();void 0!==n.coatColorFactor&&l.fromArray(n.coatColorFactor),i.coatColor=l,n.coatColorTexture&&a.push(this._loader.loadTextureInfoAsync(`${e}/coatColorTexture`,n.coatColorTexture,e=>{e.name=`${o.name} (Coat Color)`,i.coatColorTexture=e}));const u=null!==(s=n.coatAnisotropyStrength)&&void 0!==s?s:0,c=null!==(r=n.coatAnisotropyRotation)&&void 0!==r?r:0;return i.coatRoughnessAnisotropy=u,i.geometryCoatTangentAngle=c,this.useOpenPBR||i.configureGltfStyleAnisotropy(!0),n.coatAnisotropyTexture&&(n.coatAnisotropyTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/coatAnisotropyTexture`,n.coatAnisotropyTexture,e=>{e.name=`${o.name} (Coat Anisotropy)`,i.geometryCoatTangentTexture=e}))),Promise.all(a).then(()=>{})}},Xs=!1;function Ys(){Xs||(Xs=!0,no(js),to(js,!0,e=>new qs(e)))}Ys();var Qs={__proto__:null,KHR_materials_coat:qs,RegisterKHR_materials_coat:Ys};const Zs="KHR_materials_iridescence";let Js=class{constructor(e){this.name=Zs,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(Zs)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadIridescencePropertiesAsync(o,s,n)),yield Promise.all(r).then(()=>{})}))}_loadIridescencePropertiesAsync(e,t,n){var o,s,r,i,a;const l=this._loader._getOrCreateMaterialAdapter(n),u=new Array;return l.thinFilmWeight=null!==(o=t.iridescenceFactor)&&void 0!==o?o:0,l.thinFilmIor=null!==(r=null!==(s=t.iridescenceIor)&&void 0!==s?s:t.iridescenceIOR)&&void 0!==r?r:1.3,l.thinFilmThicknessMinimum=null!==(i=t.iridescenceThicknessMinimum)&&void 0!==i?i:100,l.thinFilmThicknessMaximum=null!==(a=t.iridescenceThicknessMaximum)&&void 0!==a?a:400,t.iridescenceTexture&&u.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,e=>{e.name=`${n.name} (Iridescence)`,l.thinFilmWeightTexture=e})),t.iridescenceThicknessTexture&&u.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,e=>{e.name=`${n.name} (Iridescence Thickness)`,l.thinFilmThicknessTexture=e})),Promise.all(u).then(()=>{})}},er=!1;function tr(){er||(er=!0,no(Zs),to(Zs,!0,e=>new Js(e)))}tr();var nr={__proto__:null,KHR_materials_iridescence:Js,RegisterKHR_materials_iridescence:tr};const or="KHR_materials_anisotropy";let sr=class{constructor(e){this.name=or,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(or)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadAnisotropyPropertiesAsync(o,s,n)),yield Promise.all(r)}))}_loadAnisotropyPropertiesAsync(e,t,n){return b(this,void 0,void 0,function*(){var o,s,r;const i=this._loader._getOrCreateMaterialAdapter(n),a=new Array,l=null!==(o=t.anisotropyStrength)&&void 0!==o?o:0,u=null!==(s=t.anisotropyRotation)&&void 0!==s?s:0;i.specularRoughnessAnisotropy=l,i.geometryTangentAngle=u;const c=null!==(r=t.extensions)&&void 0!==r?r:{};c.EXT_materials_anisotropy_openpbr&&c.EXT_materials_anisotropy_openpbr.openPbrAnisotropyEnabled||i.configureGltfStyleAnisotropy(!0),t.anisotropyTexture&&(t.anisotropyTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,e=>{e.name=`${n.name} (Anisotropy Intensity)`,i.geometryTangentTexture=e}))),yield Promise.all(a)})}},rr=!1;function ir(){rr||(rr=!0,no(or),to(or,!0,e=>new sr(e)))}ir();var ar={__proto__:null,KHR_materials_anisotropy:sr,RegisterKHR_materials_anisotropy:ir};const lr="KHR_materials_emissive_strength";let ur=class{constructor(e){this.name=lr,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(lr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){return yield this._loader.loadMaterialPropertiesAsync(e,t,n),this._loadEmissiveProperties(o,s,n),yield Promise.resolve()}))}_loadEmissiveProperties(e,t,n){void 0!==t.emissiveStrength&&(this._loader._getOrCreateMaterialAdapter(n).emissionLuminance=t.emissiveStrength)}},cr=!1;function dr(){cr||(cr=!0,no(lr),to(lr,!0,e=>new ur(e)))}dr();var hr={__proto__:null,KHR_materials_emissive_strength:ur,RegisterKHR_materials_emissive_strength:dr};const mr="KHR_materials_sheen";let fr=class{constructor(e){this.name=mr,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(mr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadSheenPropertiesAsync(o,s,n)),yield Promise.all(r).then(()=>{})}))}_loadSheenPropertiesAsync(e,n,o){const s=this._loader._getOrCreateMaterialAdapter(o),r=new Array;s.configureFuzz();const i=void 0!==n.sheenColorFactor?t.Color3.FromArray(n.sheenColorFactor):t.Color3.Black(),a=void 0!==n.sheenRoughnessFactor?n.sheenRoughnessFactor:0;return s.fuzzWeight=1,s.fuzzColor=i,s.fuzzRoughness=a,n.sheenColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/sheenColorTexture`,n.sheenColorTexture,e=>{e.name=`${o.name} (Sheen Color)`,s.fuzzColorTexture=e})),n.sheenRoughnessTexture&&(n.sheenRoughnessTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,n.sheenRoughnessTexture,e=>{e.name=`${o.name} (Sheen Roughness)`,s.fuzzRoughnessTexture=e}))),Promise.all(r).then(()=>{})}},pr=!1;function _r(){pr||(pr=!0,no(mr),to(mr,!0,e=>new fr(e)))}_r();var gr={__proto__:null,KHR_materials_sheen:fr,RegisterKHR_materials_sheen:_r};const yr="KHR_materials_fuzz";let vr=class{constructor(e){this.name=yr,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(yr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadFuzzPropertiesAsync(o,s,n)),yield Promise.all(r).then(()=>{})}))}_loadFuzzPropertiesAsync(e,n,o){const s=this._loader._getOrCreateMaterialAdapter(o),r=new Array;return s.configureFuzz(),s.fuzzWeight=void 0!==n.fuzzFactor?n.fuzzFactor:0,s.fuzzColor=void 0!==n.fuzzColorFactor?t.Color3.FromArray(n.fuzzColorFactor):t.Color3.White(),s.fuzzRoughness=void 0!==n.fuzzRoughnessFactor?n.fuzzRoughnessFactor:.5,n.fuzzTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/fuzzTexture`,n.fuzzTexture,e=>{e.name=`${o.name} (Fuzz)`,s.fuzzWeightTexture=e})),n.fuzzColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/fuzzColorTexture`,n.fuzzColorTexture,e=>{e.name=`${o.name} (Fuzz Color)`,s.fuzzColorTexture=e})),n.fuzzRoughnessTexture&&(n.fuzzRoughnessTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/fuzzRoughnessTexture`,n.fuzzRoughnessTexture,e=>{e.name=`${o.name} (Fuzz Roughness)`,s.fuzzRoughnessTexture=e}))),Promise.all(r).then(()=>{})}},br=!1;function xr(){br||(br=!0,no(yr),to(yr,!0,e=>new vr(e)))}xr();var Tr={__proto__:null,KHR_materials_fuzz:vr,RegisterKHR_materials_fuzz:xr};const Ar="KHR_materials_specular";let Mr=class{constructor(e){this.name=Ar,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ar)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadSpecularPropertiesAsync(o,s,n));const i=this._loader._getOrCreateMaterialAdapter(n);return s.extensions&&s.extensions.EXT_materials_specular_edge_color&&s.extensions.EXT_materials_specular_edge_color.specularEdgeColorEnabled&&i.enableSpecularEdgeColor(!0),yield Promise.all(r).then(()=>{})}))}_loadSpecularPropertiesAsync(e,n,o){var s;const r=this._loader._getOrCreateMaterialAdapter(o),i=new Array;return r.specularWeight=null!==(s=n.specularFactor)&&void 0!==s?s:1,r.specularColor=void 0!==n.specularColorFactor?t.Color3.FromArray(n.specularColorFactor):new t.Color3(1,1,1),n.specularTexture&&(n.specularTexture.nonColorData=!0,i.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,n.specularTexture,e=>{e.name=`${o.name} (Specular)`,r.specularWeightTexture=e}))),n.specularColorTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,n.specularColorTexture,e=>{e.name=`${o.name} (Specular Color)`,r.specularColorTexture=e})),Promise.all(i).then(()=>{})}},wr=!1;function Cr(){wr||(wr=!0,no(Ar),to(Ar,!0,e=>new Mr(e)))}Cr();var Rr={__proto__:null,KHR_materials_specular:Mr,RegisterKHR_materials_specular:Cr};const Or="KHR_materials_ior";let Sr=class e{constructor(e){this.name=Or,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(Or)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadIorPropertiesAsync(o,s,n)),yield Promise.all(r).then(()=>{})}))}_loadIorPropertiesAsync(t,n,o){const s=this._loader._getOrCreateMaterialAdapter(o),r=void 0!==n.ior?n.ior:e._DEFAULT_IOR;return s.specularIor=r,Promise.resolve()}};Sr._DEFAULT_IOR=1.5;let Fr=!1;function Er(){Fr||(Fr=!0,no(Or),to(Or,!0,e=>new Sr(e)))}Er();var Lr={__proto__:null,KHR_materials_ior:Sr,RegisterKHR_materials_ior:Er};const Ir="KHR_materials_variants";let Nr=class e{constructor(e){this.name=Ir,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ir)&&!this._loader.parent.skipMaterials}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(t){return e.GetAvailableVariants(t)}static SelectVariant(e,t){const n=this._GetExtensionMetadata(e);if(!n)throw new Error(`Cannot select variant on a glTF mesh that does not have the ${Ir} extension`);const o=e=>{const t=n.variants[e];if(t)for(const e of t)e.mesh.material=e.material};if(t instanceof Array)for(const e of t)o(e);else o(t);n.lastSelected=t}selectVariant(t,n){e.SelectVariant(t,n)}static Reset(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot reset on a glTF mesh that does not have the ${Ir} extension`);for(const e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(t){e.Reset(t)}static GetLastSelectedVariant(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot get the last selected variant on a glTF mesh that does not have the ${Ir} extension`);return t.lastSelected}getLastSelectedVariant(t){return e.GetLastSelectedVariant(t)}static _GetExtensionMetadata(e){var t,n;return(null===(n=null===(t=null==e?void 0:e._internalMetadata)||void 0===t?void 0:t.gltf)||void 0===n?void 0:n[Ir])||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}onReady(){var t;const n=this._loader.rootBabylonMesh;if(n){const o=this._loader.parent.extensionOptions[Ir];(null==o?void 0:o.defaultVariant)&&e.SelectVariant(n,o.defaultVariant),null===(t=null==o?void 0:o.onLoaded)||void 0===t||t.call(o,{get variants(){return e.GetAvailableVariants(n)},get selectedVariant(){const t=e.GetLastSelectedVariant(n);return t?Array.isArray(t)?t[0]:t:e.GetAvailableVariants(n)[0]},set selectedVariant(t){e.SelectVariant(n,t)}})}}_loadMeshPrimitiveAsync(n,o,s,r,i,a){return yo.LoadExtensionAsync(n,i,this.name,(l,u)=>b(this,void 0,void 0,function*(){const c=new Array;return c.push(this._loader._loadMeshPrimitiveAsync(n,o,s,r,i,o=>{if(a(o),o instanceof t.Mesh){const t=yo._GetDrawMode(n,i.mode),s=this._loader.rootBabylonMesh,r=s?s._internalMetadata=s._internalMetadata||{}:{},a=r.gltf=r.gltf||{},d=a[Ir]=a[Ir]||{lastSelected:null,original:[],variants:{}};d.original.push({mesh:o,material:o.material});for(let n=0;n<u.mappings.length;++n){const r=u.mappings[n],i=_o.Get(`${l}/mappings/${n}/material`,this._loader.gltf.materials,r.material);c.push(this._loader._loadMaterialAsync(`#/materials/${r.material}`,i,o,t,t=>{for(let n=0;n<r.variants.length;++n){const i=r.variants[n],a=_o.Get(`/extensions/${Ir}/variants/${i}`,this._variants,i);d.variants[a.name]=d.variants[a.name]||[],d.variants[a.name].push({mesh:o,material:t}),o.onClonedObservable.add(t=>{const n=t;let r,i=n;do{if(i=i.parent,!i)return;r=e._GetExtensionMetadata(i)}while(null===r);if(s&&r===e._GetExtensionMetadata(s)){i._internalMetadata={};for(const e in s._internalMetadata)i._internalMetadata[e]=s._internalMetadata[e];i._internalMetadata.gltf=[];for(const e in s._internalMetadata.gltf)i._internalMetadata.gltf[e]=s._internalMetadata.gltf[e];i._internalMetadata.gltf[Ir]={lastSelected:null,original:[],variants:{}};for(const e of r.original)i._internalMetadata.gltf[Ir].original.push({mesh:e.mesh,material:e.material});for(const e in r.variants)if(Object.prototype.hasOwnProperty.call(r.variants,e)){i._internalMetadata.gltf[Ir].variants[e]=[];for(const t of r.variants[e])i._internalMetadata.gltf[Ir].variants[e].push({mesh:t.mesh,material:t.material})}r=i._internalMetadata.gltf[Ir]}for(const e of r.original)e.mesh===o&&(e.mesh=n);for(const e of r.variants[a.name])e.mesh===o&&(e.mesh=n)})}}))}}})),yield Promise.all(c).then(([e])=>e)}))}},Pr=!1;function Br(){Pr||(Pr=!0,no(Ir),to(Ir,!0,e=>new Nr(e)))}Br();var kr={__proto__:null,KHR_materials_variants:Nr,RegisterKHR_materials_variants:Br};class Dr{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:t.Constants.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,n){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._newMeshObserver=null,this._removedMeshObserver=null,this._disposed=!1,this._materialImpls=[],this._adapterCache=new WeakMap,this._translucentMaterialIndices=new Map,this._opaqueOnlySubMeshes=new Map,this._savedSubMeshes=new Map,this._options=Object.assign(Object.assign({},Dr._GetDefaultOptions()),e),this._scene=n,this._scene._transmissionHelper=this,this.onErrorObservable=new t.Observable,this._scene.onDisposeObservable.addOnce(()=>{this.dispose()}),this._parseScene(),this._setupRenderTargets()}addMaterialImpl(e){this._materialImpls.some(t=>t.materialClass===e.materialClass)||this._materialImpls.push(e)}updateOptions(e){if(!Object.keys(e).filter(t=>this._options[t]!==e[t]).length)return;const t=Object.assign(Object.assign({},this._options),e),n=this._options;this._options=t,t.renderSize===n.renderSize&&t.renderTargetTextureType===n.renderTargetTextureType&&t.generateMipmaps===n.generateMipmaps&&this._opaqueRenderTarget?(this._opaqueRenderTarget.samples=t.samples,this._opaqueRenderTarget.lodGenerationScale=t.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=t.lodGenerationOffset):this._setupRenderTargets()}getOpaqueTarget(){return this._opaqueRenderTarget}_getOrCreateAdapter(e){let t=this._adapterCache.get(e);if(!t)for(const n of this._materialImpls)if(e instanceof n.materialClass){t=new n.adapterClass(e),this._adapterCache.set(e,t);break}return t}_classifyMeshMaterials(e){const n=e.material;if(!n)return"opaque";if(!(n instanceof t.MultiMaterial)){const e=this._getOrCreateAdapter(n);return e&&e.isTranslucent()?(e.refractionBackgroundTexture=this._opaqueRenderTarget,"transparent"):"opaque"}let o=!1,s=!1;const r=new Set;for(let e=0;e<n.subMaterials.length;e++){const t=n.subMaterials[e];if(!t){s=!0;continue}const i=this._getOrCreateAdapter(t);i&&i.isTranslucent()?(i.refractionBackgroundTexture=this._opaqueRenderTarget,o=!0,r.add(e)):s=!0}return o&&s?(this._translucentMaterialIndices.set(e,r),this._rebuildOpaqueOnlySubMeshes(e,r),"mixed"):(this._translucentMaterialIndices.delete(e),this._opaqueOnlySubMeshes.delete(e),o?"transparent":"opaque")}_rebuildOpaqueOnlySubMeshes(e,t){e.subMeshes&&this._opaqueOnlySubMeshes.set(e,e.subMeshes.filter(e=>!t.has(e.materialIndex)))}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),t.Tools.SetImmediate(()=>{!this._disposed&&e.material&&("transparent"===this._classifyMeshMaterials(e)?-1===this._transparentMeshesCache.indexOf(e)&&this._transparentMeshesCache.push(e):-1===this._opaqueMeshesCache.indexOf(e)&&this._opaqueMeshesCache.push(e))})}_removeMesh(e){e.onMaterialChangedObservable.remove(this._materialObservers[e.uniqueId]),delete this._materialObservers[e.uniqueId];let t=this._transparentMeshesCache.indexOf(e);-1!==t&&this._transparentMeshesCache.splice(t,1),t=this._opaqueMeshesCache.indexOf(e),-1!==t&&this._opaqueMeshesCache.splice(t,1),this._translucentMaterialIndices.delete(e),this._opaqueOnlySubMeshes.delete(e)}_parseScene(){this._scene.meshes.forEach(this._addMesh.bind(this)),this._newMeshObserver=this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this)),this._removedMeshObserver=this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this))}_onMeshMaterialChanged(e){const t=this._transparentMeshesCache.indexOf(e),n=this._opaqueMeshesCache.indexOf(e);"transparent"===this._classifyMeshMaterials(e)?-1!==n?(this._opaqueMeshesCache.splice(n,1),this._transparentMeshesCache.push(e)):-1===t&&this._transparentMeshesCache.push(e):-1!==t?(this._transparentMeshesCache.splice(t,1),this._opaqueMeshesCache.push(e)):-1===n&&this._opaqueMeshesCache.push(e)}_isRenderTargetValid(){var e;return null!==(null===(e=this._opaqueRenderTarget)||void 0===e?void 0:e.getInternalTexture())}_setupRenderTargets(){var e,n;let o;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new t.RenderTargetTexture("opaqueSceneTexture",this._options.renderSize,this._scene,this._options.generateMipmaps,void 0,this._options.renderTargetTextureType),this._opaqueRenderTarget.ignoreCameraViewport=!0,this._opaqueRenderTarget.renderList=this._opaqueMeshesCache,this._opaqueRenderTarget.clearColor=null!==(n=null===(e=this._options.clearColor)||void 0===e?void 0:e.clone())&&void 0!==n?n:this._scene.clearColor.clone(),this._opaqueRenderTarget.clearColor.a=0,this._opaqueRenderTarget.gammaSpace=!1,this._opaqueRenderTarget.lodGenerationScale=this._options.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=this._options.lodGenerationOffset,this._opaqueRenderTarget.samples=this._options.samples,this._opaqueRenderTarget.renderSprites=!0,this._opaqueRenderTarget.renderParticles=!0,this._opaqueRenderTarget.disableImageProcessing=!0,this._opaqueRenderTarget.onBeforeBindObservable.add(e=>{o=this._scene.environmentIntensity,this._scene.environmentIntensity=1,this._options.clearColor?e.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(e.clearColor,this._scene.getEngine().useExactSrgbConversions),e.clearColor.a=0;const t=this._opaqueOnlySubMeshes.entries();for(let e=t.next();!e.done;e=t.next()){const t=e.value[0],n=e.value[1];t.subMeshes&&(this._savedSubMeshes.set(t,t.subMeshes),t.subMeshes=n)}}),this._opaqueRenderTarget.onAfterUnbindObservable.add(()=>{this._scene.environmentIntensity=o;const e=this._savedSubMeshes.entries();for(let t=e.next();!t.done;t=e.next())t.value[0].subMeshes=t.value[1];this._savedSubMeshes.clear()});for(const e of this._transparentMeshesCache)e.material&&this._classifyMeshMaterials(e);const s=this._translucentMaterialIndices.entries();for(let e=s.next();!e.done;e=s.next()){const t=e.value[0];t.material&&this._classifyMeshMaterials(t)}}dispose(){var e,t;this._disposed=!0,null===(e=this._newMeshObserver)||void 0===e||e.remove(),null===(t=this._removedMeshObserver)||void 0===t||t.remove(),this._newMeshObserver=null,this._removedMeshObserver=null;const n=[...this._transparentMeshesCache,...this._opaqueMeshesCache];for(const e of n){const t=this._materialObservers[e.uniqueId];t&&(t.remove(),delete this._materialObservers[e.uniqueId])}for(const e of this._scene.meshes){const t=this._materialObservers[e.uniqueId];t&&(t.remove(),delete this._materialObservers[e.uniqueId])}this._materialObservers={},this._scene._transmissionHelper=void 0,this._opaqueRenderTarget&&(this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[],this._translucentMaterialIndices.clear(),this._opaqueOnlySubMeshes.clear(),this._savedSubMeshes.clear()}}function Gr(e,t){if(e.parent.dontUseTransmissionHelper)return;const n=t.getScene()._transmissionHelper,o=null!=n?n:new Dr({},t.getScene());for(const t of Array.from(e._pbrMaterialImpls.values()))o.addMaterialImpl(t);n&&!n._isRenderTargetValid()&&n._setupRenderTargets()}const Vr="KHR_materials_transmission";let Hr=class{constructor(e){this.name=Vr,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(Vr),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadTransparentPropertiesAsync(o,t,n,s)),yield Promise.all(r).then(()=>{})}))}_loadTransparentPropertiesAsync(e,t,n,o){const s=this._loader._getOrCreateMaterialAdapter(n),r=void 0!==o.transmissionFactor?o.transmissionFactor:0;if(0===r||!s)return Promise.resolve();s.configureTransmission(),s.transmissionWeight=r,r>0&&Gr(this._loader,n);let i=Promise.resolve(null);return o.transmissionTexture&&(o.transmissionTexture.nonColorData=!0,i=this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,o.transmissionTexture,e=>{e.name=`${n.name} (Transmission)`,s.transmissionWeightTexture=e})),i.then(()=>{})}},Kr=!1;function Ur(){Kr||(Kr=!0,no(Vr),to(Vr,!0,e=>new Hr(e)))}Ur();var $r={__proto__:null,KHR_materials_transmission:Hr,RegisterKHR_materials_transmission:Ur};const Wr="KHR_materials_diffuse_transmission";let zr=class{constructor(e){this.name=Wr,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(Wr),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadTranslucentPropertiesAsync(o,t,n,s)),yield Promise.all(r).then(()=>{})}))}_loadTranslucentPropertiesAsync(e,n,o,s){var r;const i=this._loader._getOrCreateMaterialAdapter(o);i.configureSubsurface(),i.subsurfaceWeight=null!==(r=s.diffuseTransmissionFactor)&&void 0!==r?r:0,i.subsurfaceWeight>0&&Gr(this._loader,o),i.diffuseTransmissionTint=void 0!==s.diffuseTransmissionColorFactor?t.Color3.FromArray(s.diffuseTransmissionColorFactor):t.Color3.White();const a=new Array;return s.diffuseTransmissionTexture&&(s.diffuseTransmissionTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionTexture`,s.diffuseTransmissionTexture).then(e=>{e.name=`${o.name} (Diffuse Transmission)`,i.subsurfaceWeightTexture=e}))),s.diffuseTransmissionColorTexture&&a.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionColorTexture`,s.diffuseTransmissionColorTexture).then(e=>{e.name=`${o.name} (Diffuse Transmission Color)`,i.diffuseTransmissionTintTexture=e})),Promise.all(a).then(()=>{})}},jr=!1;function qr(){jr||(jr=!0,no(Wr),to(Wr,!0,e=>new zr(e)))}qr();var Xr={__proto__:null,KHR_materials_diffuse_transmission:zr,RegisterKHR_materials_diffuse_transmission:qr};const Yr="KHR_materials_volume";let Qr=class{constructor(e){this.name=Yr,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(Yr),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadVolumePropertiesAsync(o,t,n,s)),yield Promise.all(r).then(()=>{})}))}_loadVolumePropertiesAsync(e,n,o,s){var r;const i=this._loader._getOrCreateMaterialAdapter(o);if(0===i.transmissionWeight&&0===i.subsurfaceWeight||!s.thicknessFactor)return Promise.resolve();i.geometryThinWalled=!1;const a=void 0!==s.attenuationDistance?s.attenuationDistance:Number.MAX_VALUE,l=void 0!==s.attenuationColor&&3==s.attenuationColor.length?t.Color3.FromArray(s.attenuationColor):t.Color3.White();i.configureVolume(),i.transmissionColor=l,i.transmissionDepth=a,i.volumeThickness=null!==(r=s.thicknessFactor)&&void 0!==r?r:0;const u=new Array;return s.thicknessTexture&&(s.thicknessTexture.nonColorData=!0,u.push(this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,s.thicknessTexture,e=>{e.name=`${o.name} (Thickness)`,i.volumeThicknessTexture=e}))),Promise.all(u).then(()=>{})}},Zr=!1;function Jr(){Zr||(Zr=!0,no(Yr),to(Yr,!0,e=>new Qr(e)))}Jr();var ei={__proto__:null,KHR_materials_volume:Qr,RegisterKHR_materials_volume:Jr};const ti="KHR_materials_volume_scatter";let ni=class{constructor(e){this.name=ti,this.order=172,this._loader=e,this.enabled=this._loader.isExtensionUsed(ti),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadVolumePropertiesAsync(o,t,n,s)),yield Promise.all(r).then(()=>{})}))}_loadVolumePropertiesAsync(e,n,o,s){const r=this._loader._getOrCreateMaterialAdapter(o);if(0===r.transmissionWeight&&0===r.subsurfaceWeight||r.geometryThinWalled)return Promise.resolve();const i=void 0!==s.multiscatterColorFactor&&3==s.multiscatterColorFactor.length?t.Color3.FromArray(s.multiscatterColorFactor):t.Color3.Black(),a=void 0!==s.scatterAnisotropy?s.scatterAnisotropy:0;let l=Promise.resolve(null);s.multiscatterColorTexture&&(s.multiscatterColorTexture.nonColorData=!0,l=this._loader.loadTextureInfoAsync(`${e}/multiscatterColorTexture`,s.multiscatterColorTexture,e=>{e.name=`${o.name} (Scatter Color)`,r.transmissionWeight>0&&(r.transmissionScatterTexture=e),r.subsurfaceWeight>0&&(r.subsurfaceColorTexture=e)}));const u=new t.Vector3(-Math.log(r.transmissionColor.r),-Math.log(r.transmissionColor.g),-Math.log(r.transmissionColor.b));if(u.scaleInPlace(1/Math.max(r.transmissionDepth,1e-6)),r.transmissionWeight>0){const e=function(e){const n=new t.Vector3(e.r,e.g,e.b),o=new t.Vector3(4.09712,4.09712,4.09712);o.addInPlace(new t.Vector3(4.20863,4.20863,4.20863).multiplyInPlace(n));const s=new t.Vector3(9.59217,9.59217,9.59217);return s.addInPlace(new t.Vector3(41.6808,41.6808,41.6808).multiplyInPlace(n)),s.addInPlace(new t.Vector3(17.7126,17.7126,17.7126).multiplyInPlace(n.multiply(n))),o.subtractInPlace(new t.Vector3(Math.sqrt(s.x),Math.sqrt(s.y),Math.sqrt(s.z))),new t.Vector3(1,1,1).subtract(o.multiply(o))}(i),n=u.multiply(e);n.scaleInPlace(r.transmissionDepth),r.transmissionScatter.set(n.x,n.y,n.z),r.transmissionScatterAnisotropy=a}if(r.subsurfaceWeight>0){r.subsurfaceScatterAnisotropy=a,r.subsurfaceColor=i;const e=new t.Vector3(0!==u.x?1/u.x:1,0!==u.y?1/u.y:1,0!==u.z?1/u.z:1);r.subsurfaceRadius=Math.max(e.x,e.y,e.z),r.subsurfaceRadiusScale=new t.Color3(e.x/r.subsurfaceRadius,e.y/r.subsurfaceRadius,e.z/r.subsurfaceRadius)}return l.then(()=>{})}},oi=!1;function si(){oi||(oi=!0,no(ti),to(ti,!0,e=>new ni(e)))}si();var ri={__proto__:null,KHR_materials_volume_scatter:ni,RegisterKHR_materials_volume_scatter:si};const ii="KHR_materials_dispersion";let ai=class{constructor(e){this.name=ii,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(ii)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadDispersionPropertiesAsync(o,t,n,s)),yield Promise.all(r).then(()=>{})}))}_loadDispersionPropertiesAsync(e,t,n,o){const s=this._loader._getOrCreateMaterialAdapter(n);return 0!=s.transmissionWeight&&o.dispersion?(s.transmissionDispersionAbbeNumber=20,s.transmissionDispersionScale=o.dispersion,Promise.resolve()):Promise.resolve()}},li=!1;function ui(){li||(li=!0,no(ii),to(ii,!0,e=>new ai(e)))}ui();var ci={__proto__:null,KHR_materials_dispersion:ai,RegisterKHR_materials_dispersion:ui};const di="KHR_materials_diffuse_roughness";let hi=class{constructor(e){this.name=di,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(di)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadDiffuseRoughnessPropertiesAsync(o,s,n)),yield Promise.all(r).then(()=>{})}))}_loadDiffuseRoughnessPropertiesAsync(e,t,n){var o;const s=this._loader._getOrCreateMaterialAdapter(n),r=new Array;return s.baseDiffuseRoughness=null!==(o=t.diffuseRoughnessFactor)&&void 0!==o?o:0,t.diffuseRoughnessTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/diffuseRoughnessTexture`,t.diffuseRoughnessTexture,e=>{e.name=`${n.name} (Diffuse Roughness)`,s.baseDiffuseRoughnessTexture=e})),Promise.all(r).then(()=>{})}},mi=!1;function fi(){mi||(mi=!0,no(di),to(di,!0,e=>new hi(e)))}fi();var pi={__proto__:null,KHR_materials_diffuse_roughness:hi,RegisterKHR_materials_diffuse_roughness:fi};const _i="KHR_mesh_quantization";let gi=class{constructor(e){this.name=_i,this.enabled=e.isExtensionUsed(_i)}dispose(){}},yi=!1;function vi(){yi||(yi=!0,no(_i),to(_i,!0,e=>new gi(e)))}vi();var bi={__proto__:null,KHR_mesh_quantization:gi,RegisterKHR_mesh_quantization:vi};const xi="KHR_texture_basisu";let Ti=class{constructor(e){this.name=xi,this._loader=e,this.enabled=e.isExtensionUsed(xi)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?yo.DefaultSampler:_o.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=_o.Get(`${o}/source`,this._loader.gltf.images,s.source);return yield this._loader._createTextureAsync(e,r,i,e=>{n(e)},t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)}))}},Ai=!1;function Mi(){Ai||(Ai=!0,no(xi),to(xi,!0,e=>new Ti(e)))}Mi();var wi={__proto__:null,KHR_texture_basisu:Ti,RegisterKHR_texture_basisu:Mi};const Ci="KHR_texture_transform";let Ri=class{constructor(e){this.name=Ci,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ci)}dispose(){this._loader=null}loadTextureInfoAsync(e,n,o){return yo.LoadExtensionAsync(e,n,this.name,(s,r)=>b(this,void 0,void 0,function*(){return yield this._loader.loadTextureInfoAsync(e,n,e=>{if(!(e instanceof t.Texture))throw new Error(`${s}: Texture type not supported`);r.offset&&(e.uOffset=r.offset[0],e.vOffset=r.offset[1]),e.uRotationCenter=0,e.vRotationCenter=0,r.rotation&&(e.wAng=-r.rotation),r.scale&&(e.uScale=r.scale[0],e.vScale=r.scale[1]),null!=r.texCoord&&(e.coordinatesIndex=r.texCoord),o(e)})}))}},Oi=!1;function Si(){Oi||(Oi=!0,no(Ci),to(Ci,!0,e=>new Ri(e)))}Si();var Fi={__proto__:null,KHR_texture_transform:Ri,RegisterKHR_texture_transform:Si};const Ei="KHR_xmp_json_ld";let Li=class{constructor(e){this.name=Ei,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ei)}dispose(){this._loader=null}onLoading(){var e,t,n;if(null===this._loader.rootBabylonMesh)return;const o=null===(e=this._loader.gltf.extensions)||void 0===e?void 0:e.KHR_xmp_json_ld,s=null===(n=null===(t=this._loader.gltf.asset)||void 0===t?void 0:t.extensions)||void 0===n?void 0:n.KHR_xmp_json_ld;if(o&&s){const e=+s.packet;o.packets&&e<o.packets.length&&(this._loader.rootBabylonMesh.metadata=this._loader.rootBabylonMesh.metadata||{},this._loader.rootBabylonMesh.metadata.xmp=o.packets[e])}}},Ii=!1;function Ni(){Ii||(Ii=!0,no(Ei),to(Ei,!0,e=>new Li(e)))}Ni();var Pi={__proto__:null,KHR_xmp_json_ld:Li,RegisterKHR_xmp_json_ld:Ni};const Bi="KHR_animation_pointer";let ki=class{constructor(e){this.name=Bi,this._loader=e,this._pathToObjectConverter=uo(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(Bi)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,n,o,s,r){var i;const a=null===(i=s.target.extensions)||void 0===i?void 0:i.KHR_animation_pointer;if(!a||!this._pathToObjectConverter)return null;"pointer"!==s.target.path&&t.Logger.Warn(`${e}/target/path: Value (${s.target.path}) must be (pointer) when using the ${this.name} extension`),null!=s.target.node&&t.Logger.Warn(`${e}/target/node: Value (${s.target.node}) must not be present when using the ${this.name} extension`);const l=`${e}/extensions/${this.name}`,u=a.pointer;if(!u)throw new Error(`${l}: Pointer is missing`);try{const t=this._pathToObjectConverter.convert(u);if(!t.info.interpolation)throw new Error(`${l}/pointer: Interpolation is missing`);return this._loader._loadAnimationChannelFromTargetInfoAsync(e,n,o,s,{object:t.object,info:t.info.interpolation},r)}catch(e){return t.Logger.Warn(`${l}/pointer: Invalid pointer (${u}) skipped`),null}}},Di=!1;function Gi(){Di||(Di=!0,no(Bi),to(Bi,!0,e=>new ki(e)))}function Vi(e,n,o,s){return t.Color3.FromArray(n,o).scale(s)}function Hi(e,t,n,o){return t[n]*o}function Ki(e,t,n,o){return-t[n]*o}function Ui(e,t,n,o){return t[n+1]*o}function $i(e,t,n,o){return t[n]*o*2}function Wi(e){return{scale:[new ji(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.uScale`,Hi,()=>2),new ji(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.vScale`,Ui,()=>2)],offset:[new ji(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,Hi,()=>2),new ji(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,Ui,()=>2)],rotation:[new ji(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.wAng`,Ki,()=>1)]}}class zi extends wo{buildAnimations(e,t,n,o){return[{babylonAnimatable:e._babylonCamera,babylonAnimation:this._buildAnimation(t,n,o)}]}}class ji extends wo{buildAnimations(e,t,n,o){const s=[];for(const r in e._data)s.push({babylonAnimatable:e._data[r].babylonMaterial,babylonAnimation:this._buildAnimation(t,n,o)});return s}}class qi extends wo{buildAnimations(e,t,n,o){return[{babylonAnimatable:e._babylonLight,babylonAnimation:this._buildAnimation(t,n,o)}]}}ho("/cameras/{}/orthographic/xmag",[new zi(t.Animation.ANIMATIONTYPE_FLOAT,"orthoLeft",Ki,()=>1),new zi(t.Animation.ANIMATIONTYPE_FLOAT,"orthoRight",Ui,()=>1)]),ho("/cameras/{}/orthographic/ymag",[new zi(t.Animation.ANIMATIONTYPE_FLOAT,"orthoBottom",Ki,()=>1),new zi(t.Animation.ANIMATIONTYPE_FLOAT,"orthoTop",Ui,()=>1)]),ho("/cameras/{}/orthographic/zfar",[new zi(t.Animation.ANIMATIONTYPE_FLOAT,"maxZ",Hi,()=>1)]),ho("/cameras/{}/orthographic/znear",[new zi(t.Animation.ANIMATIONTYPE_FLOAT,"minZ",Hi,()=>1)]),ho("/cameras/{}/perspective/yfov",[new zi(t.Animation.ANIMATIONTYPE_FLOAT,"fov",Hi,()=>1)]),ho("/cameras/{}/perspective/zfar",[new zi(t.Animation.ANIMATIONTYPE_FLOAT,"maxZ",Hi,()=>1)]),ho("/cameras/{}/perspective/znear",[new zi(t.Animation.ANIMATIONTYPE_FLOAT,"minZ",Hi,()=>1)]),ho("/materials/{}/pbrMetallicRoughness/baseColorFactor",[new ji(t.Animation.ANIMATIONTYPE_COLOR3,"albedoColor",Vi,()=>4),new ji(t.Animation.ANIMATIONTYPE_FLOAT,"alpha",function(e,t,n,o){return t[n+3]*o},()=>4)]),ho("/materials/{}/pbrMetallicRoughness/metallicFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"metallic",Hi,()=>1)]),ho("/materials/{}/pbrMetallicRoughness/metallicFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"roughness",Hi,()=>1)]);const Xi=Wi("albedoTexture");ho("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/scale",Xi.scale),ho("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/offset",Xi.offset),ho("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/rotation",Xi.rotation);const Yi=Wi("metallicTexture");ho("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/scale",Yi.scale),ho("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/offset",Yi.offset),ho("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/rotation",Yi.rotation),ho("/materials/{}/emissiveFactor",[new ji(t.Animation.ANIMATIONTYPE_COLOR3,"emissiveColor",Vi,()=>3)]);const Qi=Wi("bumpTexture");ho("/materials/{}/normalTexture/scale",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"bumpTexture.level",Hi,()=>1)]),ho("/materials/{}/normalTexture/extensions/KHR_texture_transform/scale",Qi.scale),ho("/materials/{}/normalTexture/extensions/KHR_texture_transform/offset",Qi.offset),ho("/materials/{}/normalTexture/extensions/KHR_texture_transform/rotation",Qi.rotation),ho("/materials/{}/occlusionTexture/strength",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",Hi,()=>1)]);const Zi=Wi("ambientTexture");ho("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/scale",Zi.scale),ho("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/offset",Zi.offset),ho("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/rotation",Zi.rotation);const Ji=Wi("emissiveTexture");ho("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/scale",Ji.scale),ho("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/offset",Ji.offset),ho("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/rotation",Ji.rotation),ho("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyStrength",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyRotation",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"anisotropy.angle",Hi,()=>1)]);const ea=Wi("anisotropy.texture");ho("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/scale",ea.scale),ho("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/offset",ea.offset),ho("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/rotation",ea.rotation),ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",Hi,()=>1)]);const ta=Wi("clearCoat.texture");ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/scale",ta.scale),ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/offset",ta.offset),ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/rotation",ta.rotation);const na=Wi("clearCoat.bumpTexture");ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/scale",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/scale",na.scale),ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/offset",na.offset),ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/rotation",na.rotation);const oa=Wi("clearCoat.textureRoughness");ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/scale",oa.scale),ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/offset",oa.offset),ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/rotation",oa.rotation),ho("/materials/{}/extensions/KHR_materials_dispersion/dispersionFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_emissive_strength/emissiveStrength",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"emissiveIntensity",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_ior/ior",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"indexOfRefraction",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.intensity",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceIor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMinimum",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMaximum",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",Hi,()=>1)]);const sa=Wi("iridescence.texture");ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/scale",sa.scale),ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/offset",sa.offset),ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/rotation",sa.rotation);const ra=Wi("iridescence.thicknessTexture");ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/scale",ra.scale),ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/offset",ra.offset),ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/rotation",ra.rotation),ho("/materials/{}/extensions/KHR_materials_sheen/sheenColorFactor",[new ji(t.Animation.ANIMATIONTYPE_COLOR3,"sheen.color",Vi,()=>3)]),ho("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"sheen.roughness",Hi,()=>1)]);const ia=Wi("sheen.texture");ho("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/scale",ia.scale),ho("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/offset",ia.offset),ho("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/rotation",ia.rotation);const aa=Wi("sheen.textureRoughness");ho("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/scale",aa.scale),ho("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/offset",aa.offset),ho("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/rotation",aa.rotation),ho("/materials/{}/extensions/KHR_materials_specular/specularFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"metallicF0Factor",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_specular/specularColorFactor",[new ji(t.Animation.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",Vi,()=>3)]);const la=Wi("metallicReflectanceTexture");ho("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/scale",la.scale),ho("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/offset",la.offset),ho("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/rotation",la.rotation);const ua=Wi("reflectanceTexture");ho("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/scale",ua.scale),ho("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/offset",ua.offset),ho("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/rotation",ua.rotation),ho("/materials/{}/extensions/KHR_materials_transmission/transmissionFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",Hi,()=>1)]);const ca=Wi("subSurface.refractionIntensityTexture");ho("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/scale",ca.scale),ho("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/offset",ca.offset),ho("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/rotation",ca.rotation),ho("/materials/{}/extensions/KHR_materials_volume/attenuationColor",[new ji(t.Animation.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",Vi,()=>3)]),ho("/materials/{}/extensions/KHR_materials_volume/attenuationDistance",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_volume/thicknessFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",Hi,()=>1)]);const da=Wi("subSurface.thicknessTexture");ho("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/scale",da.scale),ho("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/offset",da.offset),ho("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/rotation",da.rotation),ho("/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.translucencyIntensity",Hi,()=>1)]);const ha=Wi("subSurface.translucencyIntensityTexture");ho("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/scale",ha.scale),ho("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/offset",ha.offset),ho("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/rotation",ha.rotation),ho("/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorFactor",[new ji(t.Animation.ANIMATIONTYPE_COLOR3,"subSurface.translucencyColor",Vi,()=>3)]);const ma=Wi("subSurface.translucencyColorTexture");ho("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/scale",ma.scale),ho("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/offset",ma.offset),ho("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/rotation",ma.rotation),ho("/extensions/KHR_lights_punctual/lights/{}/color",[new qi(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",Vi,()=>3)]),ho("/extensions/KHR_lights_punctual/lights/{}/intensity",[new qi(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",Hi,()=>1)]),ho("/extensions/KHR_lights_punctual/lights/{}/range",[new qi(t.Animation.ANIMATIONTYPE_FLOAT,"range",Hi,()=>1)]),ho("/extensions/KHR_lights_punctual/lights/{}/spot/innerConeAngle",[new qi(t.Animation.ANIMATIONTYPE_FLOAT,"innerAngle",$i,()=>1)]),ho("/extensions/KHR_lights_punctual/lights/{}/spot/outerConeAngle",[new qi(t.Animation.ANIMATIONTYPE_FLOAT,"angle",$i,()=>1)]),ho("/extensions/EXT_lights_area/lights/{}/color",[new qi(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",Vi,()=>3)]),ho("/extensions/EXT_lights_area/lights/{}/intensity",[new qi(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",Hi,()=>1)]),ho("/extensions/EXT_lights_area/lights/{}/size",[new qi(t.Animation.ANIMATIONTYPE_FLOAT,"radius",Hi,()=>1)]),ho("/extensions/EXT_lights_area/lights/{}/rect/aspect",[new qi(t.Animation.ANIMATIONTYPE_FLOAT,"radius",Hi,()=>1)]),ho("/nodes/{}/extensions/EXT_lights_ies/color",[new qi(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",Vi,()=>3)]),ho("/nodes/{}/extensions/EXT_lights_ies/multiplier",[new qi(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",Hi,()=>1)]),ho("/nodes/{}/extensions/KHR_node_visibility/visible",[new class extends wo{buildAnimations(e,t,n,o){return e._primitiveBabylonMeshes?e._primitiveBabylonMeshes.map(e=>({babylonAnimatable:e,babylonAnimation:this._buildAnimation(t,n,o)})):[]}}(t.Animation.ANIMATIONTYPE_FLOAT,"isVisible",Hi,()=>1)]),Gi();var fa={__proto__:null,KHR_animation_pointer:ki,RegisterKHR_animation_pointer:Gi};const pa="MSFT_audio_emitter";let _a=class{constructor(e){this.name=pa,this._loader=e,this.enabled=this._loader.isExtensionUsed(pa)}dispose(){this._loader=null,this._clips=null,this._emitters=null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._clips=t.clips,this._emitters=t.emitters,_o.Assign(this._clips),_o.Assign(this._emitters)}}loadSceneAsync(e,t){return yo.LoadExtensionAsync(e,t,this.name,(n,o)=>b(this,void 0,void 0,function*(){const s=new Array;s.push(this._loader.loadSceneAsync(e,t));for(const e of o.emitters){const t=_o.Get(`${n}/emitters`,this._emitters,e);if(null!=t.refDistance||null!=t.maxDistance||null!=t.rolloffFactor||null!=t.distanceModel||null!=t.innerAngle||null!=t.outerAngle)throw new Error(`${n}: Direction or Distance properties are not allowed on emitters attached to a scene`);s.push(this._loadEmitterAsync(`${n}/emitters/${t.index}`,t))}yield Promise.all(s)}))}loadNodeAsync(e,n,o){return yo.LoadExtensionAsync(e,n,this.name,(e,s)=>b(this,void 0,void 0,function*(){const r=new Array,i=yield this._loader.loadNodeAsync(e,n,n=>{for(const o of s.emitters){const s=_o.Get(`${e}/emitters`,this._emitters,o);r.push(this._loadEmitterAsync(`${e}/emitters/${s.index}`,s).then(()=>{for(const e of s._babylonSounds)e.attachToMesh(n),null==s.innerAngle&&null==s.outerAngle||(e.setLocalDirectionToMesh(t.Vector3.Forward()),e.setDirectionalCone(2*t.Tools.ToDegrees(null==s.innerAngle?Math.PI:s.innerAngle),2*t.Tools.ToDegrees(null==s.outerAngle?Math.PI:s.outerAngle),0))}))}o(n)});return yield Promise.all(r),i}))}loadAnimationAsync(e,t){return yo.LoadExtensionAsync(e,t,this.name,(n,o)=>b(this,void 0,void 0,function*(){const s=yield this._loader.loadAnimationAsync(e,t),r=new Array;_o.Assign(o.events);for(const i of o.events)r.push(this._loadAnimationEventAsync(`${n}/events/${i.index}`,e,t,i,s));return yield Promise.all(r),s}))}_loadClipAsync(e,n){if(n._objectURL)return n._objectURL;let o;if(n.uri)o=this._loader.loadUriAsync(e,n,n.uri);else{const t=_o.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,n.bufferView);o=this._loader.loadBufferViewAsync(`/bufferViews/${t.index}`,t)}return n._objectURL=o.then(e=>{const o=t.GetBlobBufferSource(e);return URL.createObjectURL(new Blob([o],{type:n.mimeType}))}),n._objectURL}_loadEmitterAsync(e,n){if(n._babylonSounds=n._babylonSounds||[],!n._babylonData){const e=new Array,o=n.name||`emitter${n.index}`,s={loop:!1,autoplay:!1,volume:null==n.volume?1:n.volume};for(let r=0;r<n.clips.length;r++){const i=`/extensions/${this.name}/clips`,a=_o.Get(i,this._clips,n.clips[r].clip);e.push(this._loadClipAsync(`${i}/${n.clips[r].clip}`,a).then(e=>{const i=n._babylonSounds[r]=new t.Sound(o,e,this._loader.babylonScene,null,s);i.refDistance=n.refDistance||1,i.maxDistance=n.maxDistance||256,i.rolloffFactor=n.rolloffFactor||1,i.distanceModel=n.distanceModel||"exponential"}))}const r=Promise.all(e).then(()=>{const e=n.clips.map(e=>e.weight||1),o=new t.WeightedSound(n.loop||!1,n._babylonSounds,e);n.innerAngle&&(o.directionalConeInnerAngle=2*t.Tools.ToDegrees(n.innerAngle)),n.outerAngle&&(o.directionalConeOuterAngle=2*t.Tools.ToDegrees(n.outerAngle)),n.volume&&(o.volume=n.volume),n._babylonData.sound=o});n._babylonData={loaded:r}}return n._babylonData.loaded}_getEventAction(e,t,n,o,s){switch(n){case"play":return e=>{const n=(s||0)+(e-o);t.play(n)};case"stop":return()=>{t.stop()};case"pause":return()=>{t.pause()};default:throw new Error(`${e}: Unsupported action ${n}`)}}_loadAnimationEventAsync(e,n,o,s,r){if(0==r.targetedAnimations.length)return Promise.resolve();const i=r.targetedAnimations[0],a=s.emitter,l=_o.Get(`/extensions/${this.name}/emitters`,this._emitters,a);return this._loadEmitterAsync(e,l).then(()=>{const n=l._babylonData.sound;if(n){const o=new t.AnimationEvent(s.time,this._getEventAction(e,n,s.action,s.time,s.startOffset));i.animation.addEvent(o),r.onAnimationGroupEndObservable.add(()=>{n.stop()}),r.onAnimationGroupPauseObservable.add(()=>{n.pause()})}})}},ga=!1;function ya(){ga||(ga=!0,no(pa),to(pa,!0,e=>new _a(e)))}ya();var va={__proto__:null,MSFT_audio_emitter:_a,RegisterMSFT_audio_emitter:ya};const ba="MSFT_lod";let xa=class{constructor(e){var n,o;this.name=ba,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new t.Observable,this.onMaterialLODsLoadedObservable=new t.Observable,this._bufferLODs=new Array,this._nodeIndexLOD=null,this._nodeSignalLODs=new Array,this._nodePromiseLODs=new Array,this._nodeBufferLODs=new Array,this._materialIndexLOD=null,this._materialSignalLODs=new Array,this._materialPromiseLODs=new Array,this._materialBufferLODs=new Array,this._loader=e,this.maxLODsToLoad=null!==(o=null===(n=this._loader.parent.extensionOptions[ba])||void 0===n?void 0:n.maxLODsToLoad)&&void 0!==o?o:this.maxLODsToLoad,this.enabled=this._loader.isExtensionUsed(ba)}dispose(){this._loader=null,this._nodeIndexLOD=null,this._nodeSignalLODs.length=0,this._nodePromiseLODs.length=0,this._nodeBufferLODs.length=0,this._materialIndexLOD=null,this._materialSignalLODs.length=0,this._materialPromiseLODs.length=0,this._materialBufferLODs.length=0,this.onMaterialLODsLoadedObservable.clear(),this.onNodeLODsLoadedObservable.clear()}onReady(){for(let e=0;e<this._nodePromiseLODs.length;e++){const t=Promise.all(this._nodePromiseLODs[e]).then(()=>{0!==e&&(this._loader.endPerformanceCounter(`Node LOD ${e}`),this._loader.log(`Loaded node LOD ${e}`)),this.onNodeLODsLoadedObservable.notifyObservers(e),e!==this._nodePromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Node LOD ${e+1}`),this._loadBufferLOD(this._nodeBufferLODs,e+1),this._nodeSignalLODs[e]&&this._nodeSignalLODs[e].resolve())});this._loader._completePromises.push(t)}for(let e=0;e<this._materialPromiseLODs.length;e++){const t=Promise.all(this._materialPromiseLODs[e]).then(()=>{0!==e&&(this._loader.endPerformanceCounter(`Material LOD ${e}`),this._loader.log(`Loaded material LOD ${e}`)),this.onMaterialLODsLoadedObservable.notifyObservers(e),e!==this._materialPromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Material LOD ${e+1}`),this._loadBufferLOD(this._materialBufferLODs,e+1),this._materialSignalLODs[e]&&this._materialSignalLODs[e].resolve())});this._loader._completePromises.push(t)}}loadSceneAsync(e,t){const n=this._loader.loadSceneAsync(e,t);return this._loadBufferLOD(this._bufferLODs,0),n}loadNodeAsync(e,n,o){return yo.LoadExtensionAsync(e,n,this.name,(e,s)=>b(this,void 0,void 0,function*(){let r;const i=this._getLODs(e,n,this._loader.gltf.nodes,s.ids);this._loader.logOpen(`${e}`);for(let e=0;e<i.length;e++){const n=i[e];0!==e&&(this._nodeIndexLOD=e,this._nodeSignalLODs[e]=this._nodeSignalLODs[e]||new t.Deferred);const s=e=>{o(e),e.setEnabled(!1)},a=this._loader.loadNodeAsync(`/nodes/${n.index}`,n,s).then(t=>{if(0!==e){const t=i[e-1];t._babylonTransformNode&&(this._disposeTransformNode(t._babylonTransformNode),delete t._babylonTransformNode)}return t.setEnabled(!0),t});this._nodePromiseLODs[e]=this._nodePromiseLODs[e]||[],0===e?r=a:(this._nodeIndexLOD=null,this._nodePromiseLODs[e].push(a))}return this._loader.logClose(),yield r}))}_loadMaterialAsync(e,t,n,o,s){return this._nodeIndexLOD?null:yo.LoadExtensionAsync(e,t,this.name,(e,r)=>b(this,void 0,void 0,function*(){let i;const a=this._getLODs(e,t,this._loader.gltf.materials,r.ids);this._loader.logOpen(`${e}`);for(let e=0;e<a.length;e++){const t=a[e];0!==e&&(this._materialIndexLOD=e);const r=this._loader._loadMaterialAsync(`/materials/${t.index}`,t,n,o,t=>{0===e&&s(t)}).then(t=>{if(0!==e){s(t);const n=a[e-1]._data;n[o]&&(this._disposeMaterials([n[o].babylonMaterial]),delete n[o])}return t});this._materialPromiseLODs[e]=this._materialPromiseLODs[e]||[],0===e?i=r:(this._materialIndexLOD=null,this._materialPromiseLODs[e].push(r))}return this._loader.logClose(),yield i}))}_loadUriAsync(e,n,o){if(null!==this._nodeIndexLOD){this._loader.log("deferred");const s=this._nodeIndexLOD-1;return this._nodeSignalLODs[s]=this._nodeSignalLODs[s]||new t.Deferred,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then(()=>b(this,void 0,void 0,function*(){return yield this._loader.loadUriAsync(e,n,o)}))}if(null!==this._materialIndexLOD){this._loader.log("deferred");const s=this._materialIndexLOD-1;return this._materialSignalLODs[s]=this._materialSignalLODs[s]||new t.Deferred,this._materialSignalLODs[s].promise.then(()=>b(this,void 0,void 0,function*(){return yield this._loader.loadUriAsync(e,n,o)}))}return null}loadBufferAsync(e,n,o,s){if(this._loader.parent.useRangeRequests&&!n.uri){if(!this._loader.bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);const n=(e,n)=>b(this,void 0,void 0,function*(){const r=o,i=r+s-1;let a=e[n];return a?(a.start=Math.min(a.start,r),a.end=Math.max(a.end,i)):(a={start:r,end:i,loaded:new t.Deferred},e[n]=a),yield a.loaded.promise.then(e=>new Uint8Array(e.buffer,e.byteOffset+o-a.start,s))});return this._loader.log("deferred"),null!==this._nodeIndexLOD?n(this._nodeBufferLODs,this._nodeIndexLOD):null!==this._materialIndexLOD?n(this._materialBufferLODs,this._materialIndexLOD):n(this._bufferLODs,0)}return null}_loadBufferLOD(e,t){const n=e[t];n&&(this._loader.log(`Loading buffer range [${n.start}-${n.end}]`),this._loader.bin.readAsync(n.start,n.end-n.start+1).then(e=>{n.loaded.resolve(e)},e=>{n.loaded.reject(e)}))}_getLODs(e,t,n,o){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const s=[];for(let t=o.length-1;t>=0;t--)if(s.push(_o.Get(`${e}/ids/${o[t]}`,n,o[t])),s.length===this.maxLODsToLoad)return s;return s.push(t),s}_disposeTransformNode(e){const t=[],n=e.material;n&&t.push(n);for(const n of e.getChildMeshes())n.material&&t.push(n.material);e.dispose();const o=t.filter(e=>this._loader.babylonScene.meshes.every(t=>t.material!=e));this._disposeMaterials(o)}_disposeMaterials(e){const t={};for(const n of e){for(const e of n.getActiveTextures())t[e.uniqueId]=e;n.dispose()}for(const e in t)for(const n of this._loader.babylonScene.materials)n.hasTexture(t[e])&&delete t[e];for(const e in t)t[e].dispose()}},Ta=!1;function Aa(){Ta||(Ta=!0,no(ba),to(ba,!0,e=>new xa(e)))}Aa();var Ma={__proto__:null,MSFT_lod:xa,RegisterMSFT_lod:Aa};const wa="MSFT_minecraftMesh";let Ca=class{constructor(e){this.name=wa,this._loader=e,this.enabled=this._loader.isExtensionUsed(wa)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtraAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){if(s){if(!this._loader._pbrMaterialImpls.get("pbr"))throw new Error(`${o}: Material type not supported`);const s=this._loader.loadMaterialPropertiesAsync(e,t,n);return n.needAlphaBlending()&&(n.forceDepthWrite=!0,n.separateCullingPass=!0),n.backFaceCulling=n.forceDepthWrite,n.twoSidedLighting=!0,yield s}}))}},Ra=!1;function Oa(){Ra||(Ra=!0,no(wa),to(wa,!0,e=>new Ca(e)))}Oa();var Sa={__proto__:null,MSFT_minecraftMesh:Ca,RegisterMSFT_minecraftMesh:Oa};const Fa="MSFT_sRGBFactors";let Ea=class{constructor(e){this.name=Fa,this._loader=e,this.enabled=this._loader.isExtensionUsed(Fa)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtraAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){if(s){const o=this._loader._getOrCreateMaterialAdapter(n),s=this._loader.loadMaterialPropertiesAsync(e,t,n),r=n.getScene().getEngine().useExactSrgbConversions;return o.baseColorTexture||o.baseColor.toLinearSpaceToRef(o.baseColor,r),o.specularColorTexture||o.specularColor.toLinearSpaceToRef(o.specularColor,r),yield s}}))}},La=!1;function Ia(){La||(La=!0,no(Fa),to(Fa,!0,e=>new Ea(e)))}Ia();var Na={__proto__:null,MSFT_sRGBFactors:Ea,RegisterMSFT_sRGBFactors:Ia};function Pa(e){const[t,n]=e.split(":");return Ba({op:t,extension:n})}function Ba(e,n=!0){var o;const s=e.extension?null===(o=Da[e.extension])||void 0===o?void 0:o[e.op]:Ga[e.op];if(!s&&(t.Logger.Warn(`No mapping found for operation ${e.op} and extension ${e.extension||"KHR_interactivity"}`),n)){const t={},n={flows:{}};if(e.inputValueSockets){t.values={};for(const n in e.inputValueSockets)t.values[n]={name:n}}return e.outputValueSockets&&(n.values={},Object.keys(e.outputValueSockets).forEach(e=>{n.values[e]={name:e}})),{blocks:[],inputs:t,outputs:n}}return s}function ka(e,t,n){Da[t]||(Da[t]={}),Da[t][e]=n}const Da={BABYLON:{"flow/log":{blocks:["FlowGraphConsoleLogBlock"],inputs:{values:{message:{name:"message"}}}}}},Ga={"event/onStart":{blocks:["FlowGraphSceneReadyEventBlock"],outputs:{flows:{out:{name:"done"}}}},"event/onTick":{blocks:["FlowGraphSceneTickEventBlock"],inputs:{},outputs:{values:{timeSinceLastTick:{name:"deltaTime",gltfType:"number"}},flows:{out:{name:"done"}}}},"event/send":{blocks:["FlowGraphSendCustomEventBlock"],extraProcessor(e,t,n,o,s){var r;if("event/send"!==t.op||!e.configuration||1!==Object.keys(e.configuration).length)throw new Error("Receive event should have a single configuration object, the event itself");const i=null===(r=e.configuration.event.value)||void 0===r?void 0:r[0];if("number"!=typeof i)throw new Error("Event id should be a number");const a=o.arrays.events[i],l=s[0];return l.config||(l.config={}),l.config.eventId=a.eventId,l.config.eventData=a.eventData,s}},"event/receive":{blocks:["FlowGraphReceiveCustomEventBlock"],outputs:{flows:{out:{name:"done"}}},validation(e,n){var o,s;if(!e.configuration)return t.Logger.Error("Receive event should have a configuration object"),{valid:!1,error:"Receive event should have a configuration object"};const r=e.configuration.event;if(!r)return t.Logger.Error("Receive event should have a single configuration object, the event itself"),{valid:!1,error:"Receive event should have a single configuration object, the event itself"};const i=null===(o=r.value)||void 0===o?void 0:o[0];return"number"!=typeof i?(t.Logger.Error("Event id should be a number"),{valid:!1,error:"Event id should be a number"}):(null===(s=n.events)||void 0===s?void 0:s[i])?{valid:!0}:(t.Logger.Error(`Event with id ${i} not found`),{valid:!1,error:`Event with id ${i} not found`})},extraProcessor(e,t,n,o,s){var r;if("event/receive"!==t.op||!e.configuration||1!==Object.keys(e.configuration).length)throw new Error("Receive event should have a single configuration object, the event itself");const i=null===(r=e.configuration.event.value)||void 0===r?void 0:r[0];if("number"!=typeof i)throw new Error("Event id should be a number");const a=o.arrays.events[i],l=s[0];return l.config||(l.config={}),l.config.eventId=a.eventId,l.config.eventData=a.eventData,s}},"math/E":Va("FlowGraphEBlock"),"math/Pi":Va("FlowGraphPIBlock"),"math/Inf":Va("FlowGraphInfBlock"),"math/NaN":Va("FlowGraphNaNBlock"),"math/abs":Va("FlowGraphAbsBlock"),"math/sign":Va("FlowGraphSignBlock"),"math/trunc":Va("FlowGraphTruncBlock"),"math/floor":Va("FlowGraphFloorBlock"),"math/ceil":Va("FlowGraphCeilBlock"),"math/round":{blocks:["FlowGraphRoundBlock"],configuration:{},inputs:{values:{a:{name:"a"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s){var r;return(r=s[0]).config||(r.config={}),s[0].config.roundHalfAwayFromZero=!0,s}},"math/fract":Va("FlowGraphFractBlock"),"math/neg":Va("FlowGraphNegationBlock"),"math/add":Va("FlowGraphAddBlock",["a","b"],!0),"math/sub":Va("FlowGraphSubtractBlock",["a","b"],!0),"math/mul":{blocks:["FlowGraphMultiplyBlock"],extraProcessor(e,t,n,o,s){var r;(r=s[0]).config||(r.config={}),s[0].config.useMatrixPerComponent=!0,s[0].config.preventIntegerFloatArithmetic=!0;let i=-1;return Object.keys(e.values||{}).find(t=>{var n;return void 0!==(null===(n=e.values)||void 0===n?void 0:n[t].type)&&(i=e.values[t].type,!0)}),-1!==i&&(s[0].config.type=o.arrays.types[i].flowGraphType),s},validation:e=>e.values?Ha(e):{valid:!0}},"math/div":Va("FlowGraphDivideBlock",["a","b"],!0),"math/rem":Va("FlowGraphModuloBlock",["a","b"]),"math/min":Va("FlowGraphMinBlock",["a","b"]),"math/max":Va("FlowGraphMaxBlock",["a","b"]),"math/clamp":Va("FlowGraphClampBlock",["a","b","c"]),"math/saturate":Va("FlowGraphSaturateBlock"),"math/mix":Va("FlowGraphMathInterpolationBlock",["a","b","c"]),"math/eq":Va("FlowGraphEqualityBlock",["a","b"]),"math/lt":Va("FlowGraphLessThanBlock",["a","b"]),"math/le":Va("FlowGraphLessThanOrEqualBlock",["a","b"]),"math/gt":Va("FlowGraphGreaterThanBlock",["a","b"]),"math/ge":Va("FlowGraphGreaterThanOrEqualBlock",["a","b"]),"math/isNaN":Va("FlowGraphIsNaNBlock"),"math/isInf":Va("FlowGraphIsInfBlock"),"math/select":{blocks:["FlowGraphConditionalBlock"],inputs:{values:{condition:{name:"condition"},a:{name:"onTrue"},b:{name:"onFalse"}}},outputs:{values:{value:{name:"output"}}}},"math/random":{blocks:["FlowGraphRandomBlock"],outputs:{values:{value:{name:"value"}}}},"math/sin":Va("FlowGraphSinBlock"),"math/cos":Va("FlowGraphCosBlock"),"math/tan":Va("FlowGraphTanBlock"),"math/asin":Va("FlowGraphASinBlock"),"math/acos":Va("FlowGraphACosBlock"),"math/atan":Va("FlowGraphATanBlock"),"math/atan2":Va("FlowGraphATan2Block",["a","b"]),"math/sinh":Va("FlowGraphSinhBlock"),"math/cosh":Va("FlowGraphCoshBlock"),"math/tanh":Va("FlowGraphTanhBlock"),"math/asinh":Va("FlowGraphASinhBlock"),"math/acosh":Va("FlowGraphACoshBlock"),"math/atanh":Va("FlowGraphATanhBlock"),"math/exp":Va("FlowGraphExponentialBlock"),"math/log":Va("FlowGraphLogBlock"),"math/log2":Va("FlowGraphLog2Block"),"math/log10":Va("FlowGraphLog10Block"),"math/sqrt":Va("FlowGraphSquareRootBlock"),"math/cbrt":Va("FlowGraphCubeRootBlock"),"math/pow":Va("FlowGraphPowerBlock",["a","b"]),"math/length":Va("FlowGraphLengthBlock"),"math/normalize":Va("FlowGraphNormalizeBlock"),"math/dot":Va("FlowGraphDotBlock",["a","b"]),"math/cross":Va("FlowGraphCrossBlock",["a","b"]),"math/rotate2D":{blocks:["FlowGraphRotate2DBlock"],inputs:{values:{a:{name:"a"},angle:{name:"b"}}},outputs:{values:{value:{name:"value"}}}},"math/rotate3D":{blocks:["FlowGraphRotate3DBlock"],inputs:{values:{a:{name:"a"},rotation:{name:"b"}}},outputs:{values:{value:{name:"value"}}}},"math/transform":{blocks:["FlowGraphTransformVectorBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}}},"math/combine2":{blocks:["FlowGraphCombineVector2Block"],inputs:{values:{a:{name:"input_0",gltfType:"number"},b:{name:"input_1",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}}},"math/combine3":{blocks:["FlowGraphCombineVector3Block"],inputs:{values:{a:{name:"input_0",gltfType:"number"},b:{name:"input_1",gltfType:"number"},c:{name:"input_2",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}}},"math/combine4":{blocks:["FlowGraphCombineVector4Block"],inputs:{values:{a:{name:"input_0",gltfType:"number"},b:{name:"input_1",gltfType:"number"},c:{name:"input_2",gltfType:"number"},d:{name:"input_3",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}}},"math/extract2":{blocks:["FlowGraphExtractVector2Block"],inputs:{values:{a:{name:"input",gltfType:"number"}}},outputs:{values:{0:{name:"output_0"},1:{name:"output_1"}}}},"math/extract3":{blocks:["FlowGraphExtractVector3Block"],inputs:{values:{a:{name:"input",gltfType:"number"}}},outputs:{values:{0:{name:"output_0"},1:{name:"output_1"},2:{name:"output_2"}}}},"math/extract4":{blocks:["FlowGraphExtractVector4Block"],inputs:{values:{a:{name:"input",gltfType:"number"}}},outputs:{values:{0:{name:"output_0"},1:{name:"output_1"},2:{name:"output_2"},3:{name:"output_3"}}}},"math/transpose":Va("FlowGraphTransposeBlock"),"math/determinant":Va("FlowGraphDeterminantBlock"),"math/inverse":Va("FlowGraphInvertMatrixBlock"),"math/matMul":Va("FlowGraphMatrixMultiplicationBlock",["a","b"]),"math/matCompose":{blocks:["FlowGraphMatrixCompose"],inputs:{values:{translation:{name:"position",gltfType:"float3"},rotation:{name:"rotationQuaternion",gltfType:"float4"},scale:{name:"scaling",gltfType:"float3"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s,r){const i=s[0].dataInputs.find(e=>"rotationQuaternion"===e.name);if(!i)throw new Error("Rotation quaternion input not found");return r._connectionValues[i.uniqueId]&&(r._connectionValues[i.uniqueId].type="Quaternion"),s}},"math/matDecompose":{blocks:["FlowGraphMatrixDecompose"],inputs:{values:{a:{name:"input",gltfType:"number"}}},outputs:{values:{translation:{name:"position"},rotation:{name:"rotationQuaternion"},scale:{name:"scaling"}}}},"math/quatConjugate":Va("FlowGraphConjugateBlock",["a"]),"math/quatMul":{blocks:["FlowGraphMultiplyBlock"],inputs:{values:{a:{name:"a",gltfType:"vector4"},b:{name:"b",gltfType:"vector4"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s){var r;return(r=s[0]).config||(r.config={}),s[0].config.type="Quaternion",s}},"math/quatAngleBetween":Va("FlowGraphAngleBetweenBlock",["a","b"]),"math/quatFromAxisAngle":{blocks:["FlowGraphQuaternionFromAxisAngleBlock"],inputs:{values:{axis:{name:"a",gltfType:"float3"},angle:{name:"b",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}}},"math/quatToAxisAngle":Va("FlowGraphAxisAngleFromQuaternionBlock",["a"]),"math/quatFromDirections":Va("FlowGraphQuaternionFromDirectionsBlock",["a","b"]),"math/combine2x2":{blocks:["FlowGraphCombineMatrix2DBlock"],inputs:{values:{a:{name:"input_0",gltfType:"number"},b:{name:"input_1",gltfType:"number"},c:{name:"input_2",gltfType:"number"},d:{name:"input_3",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s){var r;return(r=s[0]).config||(r.config={}),s[0].config.inputIsColumnMajor=!0,s}},"math/extract2x2":{blocks:["FlowGraphExtractMatrix2DBlock"],inputs:{values:{a:{name:"input",gltfType:"float2x2"}}},outputs:{values:{0:{name:"output_0"},1:{name:"output_1"},2:{name:"output_2"},3:{name:"output_3"}}}},"math/combine3x3":{blocks:["FlowGraphCombineMatrix3DBlock"],inputs:{values:{a:{name:"input_0",gltfType:"number"},b:{name:"input_1",gltfType:"number"},c:{name:"input_2",gltfType:"number"},d:{name:"input_3",gltfType:"number"},e:{name:"input_4",gltfType:"number"},f:{name:"input_5",gltfType:"number"},g:{name:"input_6",gltfType:"number"},h:{name:"input_7",gltfType:"number"},i:{name:"input_8",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s){var r;return(r=s[0]).config||(r.config={}),s[0].config.inputIsColumnMajor=!0,s}},"math/extract3x3":{blocks:["FlowGraphExtractMatrix3DBlock"],inputs:{values:{a:{name:"input",gltfType:"float3x3"}}},outputs:{values:{0:{name:"output_0"},1:{name:"output_1"},2:{name:"output_2"},3:{name:"output_3"},4:{name:"output_4"},5:{name:"output_5"},6:{name:"output_6"},7:{name:"output_7"},8:{name:"output_8"}}}},"math/combine4x4":{blocks:["FlowGraphCombineMatrixBlock"],inputs:{values:{a:{name:"input_0",gltfType:"number"},b:{name:"input_1",gltfType:"number"},c:{name:"input_2",gltfType:"number"},d:{name:"input_3",gltfType:"number"},e:{name:"input_4",gltfType:"number"},f:{name:"input_5",gltfType:"number"},g:{name:"input_6",gltfType:"number"},h:{name:"input_7",gltfType:"number"},i:{name:"input_8",gltfType:"number"},j:{name:"input_9",gltfType:"number"},k:{name:"input_10",gltfType:"number"},l:{name:"input_11",gltfType:"number"},m:{name:"input_12",gltfType:"number"},n:{name:"input_13",gltfType:"number"},o:{name:"input_14",gltfType:"number"},p:{name:"input_15",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s){var r;return(r=s[0]).config||(r.config={}),s[0].config.inputIsColumnMajor=!0,s}},"math/extract4x4":{blocks:["FlowGraphExtractMatrixBlock"],configuration:{},inputs:{values:{a:{name:"input",gltfType:"number"}}},outputs:{values:{0:{name:"output_0"},1:{name:"output_1"},2:{name:"output_2"},3:{name:"output_3"},4:{name:"output_4"},5:{name:"output_5"},6:{name:"output_6"},7:{name:"output_7"},8:{name:"output_8"},9:{name:"output_9"},10:{name:"output_10"},11:{name:"output_11"},12:{name:"output_12"},13:{name:"output_13"},14:{name:"output_14"},15:{name:"output_15"}}}},"math/not":{blocks:["FlowGraphBitwiseNotBlock"],inputs:{values:{a:{name:"a"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s,r){var i,a,l;(l=s[0]).config||(l.config={});const u=s[0].dataInputs[0];return s[0].config.valueType=null!==(a=null===(i=r._connectionValues[u.uniqueId])||void 0===i?void 0:i.type)&&void 0!==a?a:"FlowGraphInteger",s}},"math/and":{blocks:["FlowGraphBitwiseAndBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s,r){var i,a,l,u,c;(c=s[0]).config||(c.config={});const d=s[0].dataInputs[0],h=s[0].dataInputs[1];return s[0].config.valueType=null!==(u=null!==(a=null===(i=r._connectionValues[d.uniqueId])||void 0===i?void 0:i.type)&&void 0!==a?a:null===(l=r._connectionValues[h.uniqueId])||void 0===l?void 0:l.type)&&void 0!==u?u:"FlowGraphInteger",s}},"math/or":{blocks:["FlowGraphBitwiseOrBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s,r){var i,a,l,u,c;(c=s[0]).config||(c.config={});const d=s[0].dataInputs[0],h=s[0].dataInputs[1];return s[0].config.valueType=null!==(u=null!==(a=null===(i=r._connectionValues[d.uniqueId])||void 0===i?void 0:i.type)&&void 0!==a?a:null===(l=r._connectionValues[h.uniqueId])||void 0===l?void 0:l.type)&&void 0!==u?u:"FlowGraphInteger",s}},"math/xor":{blocks:["FlowGraphBitwiseXorBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s,r){var i,a,l,u,c;(c=s[0]).config||(c.config={});const d=s[0].dataInputs[0],h=s[0].dataInputs[1];return s[0].config.valueType=null!==(u=null!==(a=null===(i=r._connectionValues[d.uniqueId])||void 0===i?void 0:i.type)&&void 0!==a?a:null===(l=r._connectionValues[h.uniqueId])||void 0===l?void 0:l.type)&&void 0!==u?u:"FlowGraphInteger",s}},"math/asr":Va("FlowGraphBitwiseRightShiftBlock",["a","b"]),"math/lsl":Va("FlowGraphBitwiseLeftShiftBlock",["a","b"]),"math/clz":Va("FlowGraphLeadingZerosBlock"),"math/ctz":Va("FlowGraphTrailingZerosBlock"),"math/popcnt":Va("FlowGraphOneBitsCounterBlock"),"math/rad":Va("FlowGraphDegToRadBlock"),"math/deg":Va("FlowGraphRadToDegBlock"),"type/boolToInt":Va("FlowGraphBooleanToInt"),"type/boolToFloat":Va("FlowGraphBooleanToFloat"),"type/intToBool":Va("FlowGraphIntToBoolean"),"type/intToFloat":Va("FlowGraphIntToFloat"),"type/floatToInt":Va("FlowGraphFloatToInt"),"type/floatToBool":Va("FlowGraphFloatToBoolean"),"flow/sequence":{blocks:["FlowGraphSequenceBlock"],extraProcessor(e,t,n,o,s){const r=s[0];return r.config||(r.config={}),r.config.outputSignalCount=Object.keys(e.flows||[]).length,r.signalOutputs.forEach((e,t)=>{e.name="out_"+t}),s}},"flow/branch":{blocks:["FlowGraphBranchBlock"],outputs:{flows:{true:{name:"onTrue"},false:{name:"onFalse"}}}},"flow/switch":{blocks:["FlowGraphSwitchBlock"],configuration:{cases:{name:"cases",isArray:!0,inOptions:!0,defaultValue:[]}},inputs:{values:{selection:{name:"case"},default:{name:"default"}}},validation(e){var n;const o=null===(n=e.configuration)||void 0===n?void 0:n.cases;if(o&&o.value){if(!o.value.every(e=>"number"==typeof e&&/^-?\d+$/.test(e.toString())))return t.Logger.Warn("Switch cases should be integers. Using empty array instead."),o.value=[],{valid:!0};const e=new Set(o.value);o.value=Array.from(e)}return{valid:!0}},extraProcessor(e,t,n,o,s){if("flow/switch"!==t.op||!e.flows||0===Object.keys(e.flows).length)throw new Error("Switch should have a single configuration object, the cases array");return s[0].signalOutputs.forEach(e=>{"default"!==e.name&&(e.name="out_"+e.name)}),s}},"flow/while":{blocks:["FlowGraphWhileLoopBlock"],outputs:{flows:{loopBody:{name:"executionFlow"}}}},"flow/for":{blocks:["FlowGraphForLoopBlock"],configuration:{initialIndex:{name:"initialIndex",gltfType:"number",inOptions:!0,defaultValue:0}},inputs:{values:{startIndex:{name:"startIndex",gltfType:"number"},endIndex:{name:"endIndex",gltfType:"number"}}},outputs:{values:{index:{name:"index"}},flows:{loopBody:{name:"executionFlow"}}},extraProcessor(e,t,n,o,s){const r=s[0];return r.config||(r.config={}),r.config.incrementIndexWhenLoopDone=!0,s}},"flow/doN":{blocks:["FlowGraphDoNBlock"],configuration:{},inputs:{values:{n:{name:"maxExecutions",gltfType:"number"}}},outputs:{values:{currentCount:{name:"executionCount"}}}},"flow/multiGate":{blocks:["FlowGraphMultiGateBlock"],configuration:{isRandom:{name:"isRandom",gltfType:"boolean",inOptions:!0,defaultValue:!1},isLoop:{name:"isLoop",gltfType:"boolean",inOptions:!0,defaultValue:!1}},extraProcessor(e,t,n,o,s){if("flow/multiGate"!==t.op||!e.flows||0===Object.keys(e.flows).length)throw new Error("MultiGate should have a single configuration object, the number of output flows");const r=s[0];return r.config||(r.config={}),r.config.outputSignalCount=Object.keys(e.flows).length,r.signalOutputs.forEach((e,t)=>{e.name="out_"+t}),s}},"flow/waitAll":{blocks:["FlowGraphWaitAllBlock"],configuration:{inputFlows:{name:"inputSignalCount",gltfType:"number",inOptions:!0,defaultValue:0}},inputs:{flows:{reset:{name:"reset"},"[segment]":{name:"in_$1"}}},validation(e){var t,n,o;return"number"!=typeof(null===(o=null===(n=null===(t=e.configuration)||void 0===t?void 0:t.inputFlows)||void 0===n?void 0:n.value)||void 0===o?void 0:o[0])&&(e.configuration=e.configuration||{inputFlows:{value:[0]}},e.configuration.inputFlows.value=[0]),{valid:!0}}},"flow/throttle":{blocks:["FlowGraphThrottleBlock"],outputs:{flows:{err:{name:"error"}}}},"flow/setDelay":{blocks:["FlowGraphSetDelayBlock"],outputs:{flows:{err:{name:"error"}}}},"flow/cancelDelay":{blocks:["FlowGraphCancelDelayBlock"]},"variable/get":{blocks:["FlowGraphGetVariableBlock"],validation(e){var n,o;return(null===(o=null===(n=e.configuration)||void 0===n?void 0:n.variable)||void 0===o?void 0:o.value)?{valid:!0}:(t.Logger.Error("Variable get block should have a variable configuration"),{valid:!1,error:"Variable get block should have a variable configuration"})},configuration:{variable:{name:"variable",gltfType:"number",flowGraphType:"string",inOptions:!0,isVariable:!0,dataTransformer:(e,t)=>t.getVariableName(e)}}},"variable/set":{blocks:["FlowGraphSetVariableBlock"],configuration:{variables:{name:"variables",gltfType:"number",flowGraphType:"string",inOptions:!0,isArray:!0,dataTransformer:(e,t)=>e.map(e=>t.getVariableName(e))}},extraProcessor:(e,t,n,o,s)=>(s[0].dataInputs.forEach(e=>{e.name=o.getVariableName(+e.name)}),s)},"variable/interpolate":{blocks:["FlowGraphInterpolationBlock","FlowGraphContextBlock","FlowGraphPlayAnimationBlock","FlowGraphBezierCurveEasing","FlowGraphGetVariableBlock"],configuration:{variable:{name:"propertyName",inOptions:!0,isVariable:!0,dataTransformer:(e,t)=>t.getVariableName(e)},useSlerp:{name:"animationType",inOptions:!0,defaultValue:!1,dataTransformer:e=>!0===e?"Quaternion":void 0}},inputs:{values:{value:{name:"value_1"},duration:{name:"duration_1",gltfType:"number"},p1:{name:"controlPoint1",toBlock:"FlowGraphBezierCurveEasing"},p2:{name:"controlPoint2",toBlock:"FlowGraphBezierCurveEasing"}},flows:{in:{name:"in",toBlock:"FlowGraphPlayAnimationBlock"}}},outputs:{flows:{err:{name:"error",toBlock:"FlowGraphPlayAnimationBlock"},out:{name:"out",toBlock:"FlowGraphPlayAnimationBlock"},done:{name:"done",toBlock:"FlowGraphPlayAnimationBlock"}}},interBlockConnectors:[{input:"object",output:"userVariables",inputBlockIndex:2,outputBlockIndex:1,isVariable:!0},{input:"animation",output:"animation",inputBlockIndex:2,outputBlockIndex:0,isVariable:!0},{input:"easingFunction",output:"easingFunction",inputBlockIndex:0,outputBlockIndex:3,isVariable:!0},{input:"value_0",output:"value",inputBlockIndex:0,outputBlockIndex:4,isVariable:!0}],extraProcessor(e,n,o,s,r){var i,a,l,u,c,d;const h=r[0],m=null===(a=null===(i=e.configuration)||void 0===i?void 0:i.variable.value)||void 0===a?void 0:a[0];if("number"!=typeof m)throw t.Logger.Error("Variable index is not defined for variable interpolation block"),new Error("Variable index is not defined for variable interpolation block");const f=s.arrays.staticVariables[m];void 0===(null===(u=null===(l=h.config)||void 0===l?void 0:l.animationType)||void 0===u?void 0:u.value)&&(h.config||(h.config={}),(c=h.config).animationType||(c.animationType={}),h.config.animationType.value=t.getAnimationTypeByFlowGraphType(f.type));const p=r[4];return p.config||(p.config={}),(d=p.config).variable||(d.variable={}),p.config.variable.value=s.getVariableName(m),r}},"pointer/get":{blocks:["FlowGraphGetPropertyBlock","FlowGraphJsonPointerParserBlock"],configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock"}},inputs:{values:{"[segment]":{name:"$1",toBlock:"FlowGraphJsonPointerParserBlock"}}},interBlockConnectors:[{input:"object",output:"object",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"propertyName",output:"propertyName",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"customGetFunction",output:"getFunction",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0}],extraProcessor:(e,t,n,o,s)=>(s.forEach(e=>{"FlowGraphJsonPointerParserBlock"===e.className&&(e.config||(e.config={}),e.config.outputValue=!0)}),s)},"pointer/set":{blocks:["FlowGraphSetPropertyBlock","FlowGraphJsonPointerParserBlock"],configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock"}},inputs:{values:{value:{name:"value"},"[segment]":{name:"$1",toBlock:"FlowGraphJsonPointerParserBlock"}}},outputs:{flows:{err:{name:"error"}}},interBlockConnectors:[{input:"object",output:"object",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"propertyName",output:"propertyName",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"customSetFunction",output:"setFunction",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0}],extraProcessor:(e,t,n,o,s)=>(s.forEach(e=>{"FlowGraphJsonPointerParserBlock"===e.className&&(e.config||(e.config={}),e.config.outputValue=!0)}),s)},"pointer/interpolate":{blocks:["FlowGraphInterpolationBlock","FlowGraphJsonPointerParserBlock","FlowGraphPlayAnimationBlock","FlowGraphBezierCurveEasing"],configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock"}},inputs:{values:{value:{name:"value_1"},"[segment]":{name:"$1",toBlock:"FlowGraphJsonPointerParserBlock"},duration:{name:"duration_1",gltfType:"number"},p1:{name:"controlPoint1",toBlock:"FlowGraphBezierCurveEasing"},p2:{name:"controlPoint2",toBlock:"FlowGraphBezierCurveEasing"}},flows:{in:{name:"in",toBlock:"FlowGraphPlayAnimationBlock"}}},outputs:{flows:{err:{name:"error",toBlock:"FlowGraphPlayAnimationBlock"},out:{name:"out",toBlock:"FlowGraphPlayAnimationBlock"},done:{name:"done",toBlock:"FlowGraphPlayAnimationBlock"}}},interBlockConnectors:[{input:"object",output:"object",inputBlockIndex:2,outputBlockIndex:1,isVariable:!0},{input:"propertyName",output:"propertyName",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"customBuildAnimation",output:"generateAnimationsFunction",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"animation",output:"animation",inputBlockIndex:2,outputBlockIndex:0,isVariable:!0},{input:"easingFunction",output:"easingFunction",inputBlockIndex:0,outputBlockIndex:3,isVariable:!0},{input:"value_0",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0}],extraProcessor:(e,t,n,o,s)=>(s.forEach(t=>{"FlowGraphJsonPointerParserBlock"===t.className?(t.config||(t.config={}),t.config.outputValue=!0):"FlowGraphInterpolationBlock"===t.className&&(t.config||(t.config={}),Object.keys(e.values||[]).forEach(n=>{var s;const r=null===(s=e.values)||void 0===s?void 0:s[n];if("value"===n&&r){const e=r.type;void 0!==e&&(t.config.animationType=o.arrays.types[e].flowGraphType)}}))}),s)},"animation/start":{blocks:["FlowGraphPlayAnimationBlock","FlowGraphArrayIndexBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],inputs:{values:{animation:{name:"index",gltfType:"number",toBlock:"FlowGraphArrayIndexBlock"},speed:{name:"speed",gltfType:"number"},startTime:{name:"from",gltfType:"number",dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]},endTime:{name:"to",gltfType:"number",dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]}}},outputs:{flows:{err:{name:"error"}}},interBlockConnectors:[{input:"animationGroup",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"array",output:"animationGroups",inputBlockIndex:1,outputBlockIndex:2,isVariable:!0}],extraProcessor(e,t,n,o,s,r,i){const a=s[s.length-1];return a.config||(a.config={}),a.config.glTF=i,s}},"animation/stop":{blocks:["FlowGraphStopAnimationBlock","FlowGraphArrayIndexBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],inputs:{values:{animation:{name:"index",gltfType:"number",toBlock:"FlowGraphArrayIndexBlock"}}},outputs:{flows:{err:{name:"error"}}},interBlockConnectors:[{input:"animationGroup",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"array",output:"animationGroups",inputBlockIndex:1,outputBlockIndex:2,isVariable:!0}],extraProcessor(e,t,n,o,s,r,i){const a=s[s.length-1];return a.config||(a.config={}),a.config.glTF=i,s}},"animation/stopAt":{blocks:["FlowGraphStopAnimationBlock","FlowGraphArrayIndexBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{},inputs:{values:{animation:{name:"index",gltfType:"number",toBlock:"FlowGraphArrayIndexBlock"},stopTime:{name:"stopAtFrame",gltfType:"number",dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]}}},outputs:{flows:{err:{name:"error"}}},interBlockConnectors:[{input:"animationGroup",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"array",output:"animationGroups",inputBlockIndex:1,outputBlockIndex:2,isVariable:!0}],extraProcessor(e,t,n,o,s,r,i){const a=s[s.length-1];return a.config||(a.config={}),a.config.glTF=i,s}},"math/switch":{blocks:["FlowGraphDataSwitchBlock"],configuration:{cases:{name:"cases",isArray:!0,inOptions:!0,defaultValue:[]}},inputs:{values:{selection:{name:"case"}}},validation(e){var n;const o=null===(n=e.configuration)||void 0===n?void 0:n.cases;if(o&&o.value){if(!o.value.every(e=>"number"==typeof e&&/^-?\d+$/.test(e.toString())))return t.Logger.Warn("Switch cases should be integers. Using empty array instead."),o.value=[],{valid:!0};const e=new Set(o.value);o.value=Array.from(e)}return{valid:!0}},extraProcessor(e,t,n,o,s){const r=s[0];return r.dataInputs.forEach(e=>{"default"!==e.name&&"case"!==e.name&&(e.name="in_"+e.name)}),r.config||(r.config={}),r.config.treatCasesAsIntegers=!0,s}},"debug/log":{blocks:["FlowGraphConsoleLogBlock"],configuration:{message:{name:"messageTemplate",inOptions:!0}}}};function Va(e,t=["a"],n){return{blocks:[e],inputs:{values:t.reduce((e,t)=>(e[t]={name:t},e),{})},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,o,s,r){var i;if(n){(i=r[0]).config||(i.config={}),r[0].config.preventIntegerFloatArithmetic=!0;let t=-1;Object.keys(e.values||{}).find(n=>{var o;return void 0!==(null===(o=e.values)||void 0===o?void 0:o[n].type)&&(t=e.values[n].type,!0)}),-1!==t&&(r[0].config.type=s.arrays.types[t].flowGraphType)}return r},validation:e=>n?Ha(e):{valid:!0}}}function Ha(e){if(e.values){const t=Object.keys(e.values).map(t=>e.values[t].type).filter(e=>void 0!==e);if(!t.every(e=>e===t[0]))return{valid:!1,error:"All inputs must be of the same type"}}return{valid:!0}}function Ka(){return Object.keys(Ga)}const Ua={float:{length:1,flowGraphType:"number",elementType:"number"},bool:{length:1,flowGraphType:"boolean",elementType:"boolean"},float2:{length:2,flowGraphType:"Vector2",elementType:"number"},float3:{length:3,flowGraphType:"Vector3",elementType:"number"},float4:{length:4,flowGraphType:"Vector4",elementType:"number"},float4x4:{length:16,flowGraphType:"Matrix",elementType:"number"},float2x2:{length:4,flowGraphType:"Matrix2D",elementType:"number"},float3x3:{length:9,flowGraphType:"Matrix3D",elementType:"number"},int:{length:1,flowGraphType:"FlowGraphInteger",elementType:"number"}};class $a{constructor(e,t,n=60){this._interactivityGraph=e,this._gltf=t,this._animationTargetFps=n,this._types=[],this._mappings=[],this._staticVariables=[],this._events=[],this._internalEventsCounter=0,this._nodes=[],this._parseTypes(),this._parseDeclarations(),this._parseVariables(),this._parseEvents(),this._parseNodes()}get arrays(){return{types:this._types,mappings:this._mappings,staticVariables:this._staticVariables,events:this._events,nodes:this._nodes}}_parseTypes(){if(this._interactivityGraph.types)for(const e of this._interactivityGraph.types)this._types.push(Ua[e.signature])}_parseDeclarations(){if(this._interactivityGraph.declarations)for(const e of this._interactivityGraph.declarations){const n=Ba(e);if(!n)throw t.Logger.Error(["No mapping found for declaration",e]),new Error("Error parsing declarations");this._mappings.push({flowGraphMapping:n,fullOperationName:e.extension?e.op+":"+e.extension:e.op})}}_parseVariables(){if(this._interactivityGraph.variables)for(const e of this._interactivityGraph.variables){const t=this._parseVariable(e);this._staticVariables.push(t)}}_parseVariable(e,n){const o=this._types[e.type];if(!o)throw t.Logger.Error(["No type found for variable",e]),new Error("Error parsing variables");if(e.value&&e.value.length!==o.length)throw t.Logger.Error(["Invalid value length for variable",e,o]),new Error("Error parsing variables");const s=e.value||[];if(!s.length)switch(o.flowGraphType){case"boolean":s.push(!1);break;case"FlowGraphInteger":s.push(0);break;case"number":s.push(NaN);break;case"Vector2":s.push(NaN,NaN);break;case"Vector3":s.push(NaN,NaN,NaN);break;case"Vector4":case"Matrix2D":case"Quaternion":s.fill(NaN,0,4);break;case"Matrix":s.fill(NaN,0,16);break;case"Matrix3D":s.fill(NaN,0,9)}return"number"===o.elementType&&"string"==typeof s[0]&&(s[0]=parseFloat(s[0])),{type:o.flowGraphType,value:n?n(s,this):s}}_parseEvents(){if(this._interactivityGraph.events)for(const e of this._interactivityGraph.events){const n={eventId:e.id||"internalEvent_"+this._internalEventsCounter++};e.values&&(n.eventData=Object.keys(e.values).map(n=>{var o;const s=null===(o=e.values)||void 0===o?void 0:o[n];if(!s)throw t.Logger.Error(["No value found for event key",n]),new Error("Error parsing events");const r=this._types[s.type];if(!r)throw t.Logger.Error(["No type found for event value",s]),new Error("Error parsing events");const i=void 0!==s.value?this._parseVariable(s):void 0;return{id:n,type:r.flowGraphType,eventData:!0,value:i}})),this._events.push(n)}}_parseNodes(){var e;if(this._interactivityGraph.nodes)for(const n of this._interactivityGraph.nodes){if("number"!=typeof n.declaration)throw t.Logger.Error(["No declaration found for node",n]),new Error("Error parsing nodes");const o=this._mappings[n.declaration];if(!o)throw t.Logger.Error(["No mapping found for node",n]),new Error("Error parsing nodes");if(o.flowGraphMapping.validation){const t=o.flowGraphMapping.validation(n,this._interactivityGraph,this._gltf);if(!t.valid)throw new Error(`Error validating interactivity node ${null===(e=this._interactivityGraph.declarations)||void 0===e?void 0:e[n.declaration].op} - ${t.error}`)}const s=[];for(const e of o.flowGraphMapping.blocks){const t=this._getEmptyBlock(e,o.fullOperationName);this._parseNodeConfiguration(n,t,o.flowGraphMapping,e),s.push(t)}this._nodes.push({blocks:s,fullOperationName:o.fullOperationName})}}_getEmptyBlock(e,n){return{uniqueId:t.RandomGUID(),className:e,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[],config:{},type:n,metadata:{}}}_parseNodeConfiguration(e,n,o,s){var r;const i=e.configuration;if(i)for(const e in i){const a=i[e];if(!a)throw new Error("Error parsing node configuration");const l=null===(r=o.configuration)||void 0===r?void 0:r[e];if(l&&l.toBlock?l.toBlock===s:0===o.blocks.indexOf(s)){let o=null==l?void 0:l.defaultValue;(null==a?void 0:a.value)&&(o=a.value),(null==l?void 0:l.isArray)||(1!==o.length&&t.Logger.Warn(`Invalid non-array value length: ${o.length}`),o=o[0]),(null==l?void 0:l.dataTransformer)&&(o=l.dataTransformer(o,this)),void 0!==o&&(n.config[(null==l?void 0:l.name)||e]={value:o})}}}_parseNodeConnections(e){var n,o,s,r,i,a,l,u,c,d,h,m,f,p,_,g,y,v,b;for(let x=0;x<this._nodes.length;x++){const T=null===(n=this._interactivityGraph.nodes)||void 0===n?void 0:n[x];if(!T)throw t.Logger.Error(["No node found for interactivity node",this._nodes[x]]),new Error("Error parsing node connections");const A=this._nodes[x],M=this._mappings[T.declaration];if(!M)throw t.Logger.Error(["No mapping found for node",T]),new Error("Error parsing node connections");const w=T.flows||{},C=Object.keys(w).sort();for(const e of C){const n=w[e],c=null===(s=null===(o=M.flowGraphMapping.outputs)||void 0===o?void 0:o.flows)||void 0===s?void 0:s[e],d=(null==c?void 0:c.name)||e,h=this._createNewSocketConnection(d,!0);(c&&c.toBlock&&A.blocks.find(e=>e.className===c.toBlock)||A.blocks[0]).signalOutputs.push(h);const m=n.node,f=this._nodes[m];if(!f)throw t.Logger.Error(["No node found for input node id",m]),new Error("Error parsing node connections");const p=Pa(f.fullOperationName);if(!p)throw t.Logger.Error(["No mapping found for input node",f]),new Error("Error parsing node connections");let _=null===(i=null===(r=p.inputs)||void 0===r?void 0:r.flows)||void 0===i?void 0:i[n.socket||"in"],g=!1;if(!_)for(const e in null===(a=p.inputs)||void 0===a?void 0:a.flows)e.startsWith("[")&&e.endsWith("]")&&(g=!0,_=null===(u=null===(l=p.inputs)||void 0===l?void 0:l.flows)||void 0===u?void 0:u[e]);const y=_?g?_.name.replace("$1",n.socket||""):_.name:n.socket||"in",v=_&&_.toBlock&&f.blocks.find(e=>e.className===_.toBlock)||f.blocks[0];let b=v.signalInputs.find(e=>e.name===y);b||(b=this._createNewSocketConnection(y),v.signalInputs.push(b)),b.connectedPointIds.push(h.uniqueId),h.connectedPointIds.push(b.uniqueId)}const R=T.values||{},O=Object.keys(R);for(const n of O){const o=R[n];let s=null===(d=null===(c=M.flowGraphMapping.inputs)||void 0===c?void 0:c.values)||void 0===d?void 0:d[n],r=!1;if(!s)for(const e in null===(h=M.flowGraphMapping.inputs)||void 0===h?void 0:h.values)e.startsWith("[")&&e.endsWith("]")&&(r=!0,s=null===(f=null===(m=M.flowGraphMapping.inputs)||void 0===m?void 0:m.values)||void 0===f?void 0:f[e]);const i=s?r?s.name.replace("$1",n):s.name:n,a=this._createNewSocketConnection(i);if((s&&s.toBlock&&A.blocks.find(e=>e.className===s.toBlock)||A.blocks[0]).dataInputs.push(a),void 0!==o.value){const t=this._parseVariable(o,s&&s.dataTransformer);e._connectionValues[a.uniqueId]=t}else{if(void 0===o.node)throw t.Logger.Error(["Invalid value for value connection",o]),new Error("Error parsing node connections");{const e=o.node,n=o.socket||"value",s=this._nodes[e];if(!s)throw t.Logger.Error(["No node found for output socket reference",o]),new Error("Error parsing node connections");const r=Pa(s.fullOperationName);if(!r)throw t.Logger.Error(["No mapping found for output socket reference",o]),new Error("Error parsing node connections");let i=null===(_=null===(p=r.outputs)||void 0===p?void 0:p.values)||void 0===_?void 0:_[n],l=!1;if(!i)for(const e in null===(g=r.outputs)||void 0===g?void 0:g.values)e.startsWith("[")&&e.endsWith("]")&&(l=!0,i=null===(v=null===(y=r.outputs)||void 0===y?void 0:y.values)||void 0===v?void 0:v[e]);const u=i?l?i.name.replace("$1",n):null==i?void 0:i.name:n,c=i&&i.toBlock&&s.blocks.find(e=>e.className===i.toBlock)||s.blocks[0];let d=c.dataOutputs.find(e=>e.name===u);d||(d=this._createNewSocketConnection(u,!0),c.dataOutputs.push(d)),a.connectedPointIds.push(d.uniqueId),d.connectedPointIds.push(a.uniqueId)}}}if(M.flowGraphMapping.interBlockConnectors)for(const e of M.flowGraphMapping.interBlockConnectors){const t=e.input,n=e.output,o=e.isVariable;this._connectFlowGraphNodes(t,n,A.blocks[e.inputBlockIndex],A.blocks[e.outputBlockIndex],o)}if(M.flowGraphMapping.extraProcessor){const n=null===(b=this._interactivityGraph.declarations)||void 0===b?void 0:b[T.declaration];if(!n)throw t.Logger.Error(["No declaration found for extra processor",T]),new Error("Error parsing node connections");A.blocks=M.flowGraphMapping.extraProcessor(T,n,M.flowGraphMapping,this,A.blocks,e,this._gltf)}}}_createNewSocketConnection(e,n){return{uniqueId:t.RandomGUID(),name:e,_connectionType:n?1:0,connectedPointIds:[]}}_connectFlowGraphNodes(e,t,n,o,s){const r=s?n.dataInputs:n.signalInputs,i=s?o.dataOutputs:o.signalOutputs,a=r.find(t=>t.name===e)||this._createNewSocketConnection(e),l=i.find(e=>e.name===t)||this._createNewSocketConnection(t,!0);r.find(t=>t.name===e)||r.push(a),i.find(e=>e.name===t)||i.push(l),a.connectedPointIds.push(l.uniqueId),l.connectedPointIds.push(a.uniqueId)}getVariableName(e){return"staticVariable_"+e}serializeToFlowGraph(){const e={uniqueId:t.RandomGUID(),_userVariables:{},_connectionValues:{}};this._parseNodeConnections(e);for(let t=0;t<this._staticVariables.length;t++){const n=this._staticVariables[t];e._userVariables[this.getVariableName(t)]=n}return{rightHanded:!0,allBlocks:this._nodes.reduce((e,t)=>e.concat(t.blocks),[]),executionContexts:[e]}}}const Wa="KHR_interactivity";let za=class{constructor(e){this._loader=e,this.name=Wa,this.enabled=this._loader.isExtensionUsed(Wa),this._pathConverter=uo(this._loader.gltf),e._skipStartAnimationStep=!0;const t=e.babylonScene;t&&ja(t)}dispose(){this._loader=null,delete this._pathConverter}onReady(){return b(this,void 0,void 0,function*(){var e;if(!this._loader.babylonScene||!this._pathConverter)return;const n=this._loader.babylonScene,o=null===(e=this._loader.gltf.extensions)||void 0===e?void 0:e.KHR_interactivity;if(!o)return;const s=new t.FlowGraphCoordinator({scene:n});s.dispatchEventsSynchronously=!1;const r=o.graphs.map(e=>new $a(e,this._loader.gltf,this._loader.parent.targetFps).serializeToFlowGraph());yield Promise.all(r.map(e=>b(this,void 0,void 0,function*(){return yield t.ParseFlowGraphAsync(e,{coordinator:s,pathConverter:this._pathConverter})}))),s.start()})}};function ja(e){mo("/extensions/KHR_interactivity/?/activeCamera/rotation",{get:()=>{if(!e.activeCamera)return new t.Quaternion(NaN,NaN,NaN,NaN);const n=t.Quaternion.FromRotationMatrix(e.activeCamera.getWorldMatrix()).normalize();return e.useRightHandedSystem||(n.w*=-1,n.x*=-1),n},type:"Quaternion",getTarget:()=>e.activeCamera}),mo("/extensions/KHR_interactivity/?/activeCamera/position",{get:()=>{if(!e.activeCamera)return new t.Vector3(NaN,NaN,NaN);const n=e.activeCamera.getWorldMatrix().getTranslation();return e.useRightHandedSystem||(n.x*=-1),n},type:"Vector3",getTarget:()=>e.activeCamera}),mo("/animations/{}/extensions/KHR_interactivity/isPlaying",{get:e=>{var t,n;return null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.isPlaying)&&void 0!==n&&n},type:"boolean",getTarget:e=>e._babylonAnimationGroup}),mo("/animations/{}/extensions/KHR_interactivity/minTime",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.from)&&void 0!==n?n:0)/60},type:"number",getTarget:e=>e._babylonAnimationGroup}),mo("/animations/{}/extensions/KHR_interactivity/maxTime",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.to)&&void 0!==n?n:0)/60},type:"number",getTarget:e=>e._babylonAnimationGroup}),mo("/animations/{}/extensions/KHR_interactivity/playhead",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.getCurrentFrame())&&void 0!==n?n:0)/60},type:"number",getTarget:e=>e._babylonAnimationGroup}),mo("/animations/{}/extensions/KHR_interactivity/virtualPlayhead",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.getCurrentFrame())&&void 0!==n?n:0)/60},type:"number",getTarget:e=>e._babylonAnimationGroup})}let qa=!1;function Xa(){qa||(qa=!0,t.addToBlockFactory(Wa,"FlowGraphGLTFDataProvider",()=>b(this,void 0,void 0,function*(){return(yield Promise.resolve().then(function(){return bl})).FlowGraphGLTFDataProvider})),no(Wa),to(Wa,!0,e=>new za(e)))}Xa();var Ya={__proto__:null,KHR_interactivity:za,RegisterKHR_interactivity:Xa,_AddInteractivityObjectModel:ja};const Qa="KHR_node_visibility";let Za=class{constructor(e){this.name=Qa,this._loader=e,this.enabled=e.isExtensionUsed(Qa)}onReady(){if(!this._loader)return;const e=this._loader.gltf.nodes;if(e)for(const t of e){const e=t._babylonTransformNode;e&&(e.inheritVisibility=!0,t.extensions&&t.extensions.KHR_node_visibility&&!1===t.extensions.KHR_node_visibility.visible&&(e.isVisible=!1))}}dispose(){delete this._loader}},Ja=!1;function el(){Ja||(Ja=!0,mo("/nodes/{}/extensions/KHR_node_visibility/visible",{get:e=>{const t=e._babylonTransformNode;return!t||void 0===t.isVisible||t.isVisible},set:(e,t)=>{var n,o;null===(n=t._primitiveBabylonMeshes)||void 0===n||n.forEach(e=>{e.inheritVisibility=!0}),t._babylonTransformNode&&(t._babylonTransformNode.isVisible=e),null===(o=t._primitiveBabylonMeshes)||void 0===o||o.forEach(t=>{t.isVisible=e})},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"isVisible"],type:"boolean"}),no(Qa),to(Qa,!0,e=>new Za(e)))}el();var tl={__proto__:null,KHR_node_visibility:Za,RegisterKHR_node_visibility:el};const nl="KHR_node_selectability";let ol=class{constructor(e){this.name=nl,this._loader=e,this.enabled=e.isExtensionUsed(nl)}onReady(){return b(this,void 0,void 0,function*(){var e;null===(e=this._loader.gltf.nodes)||void 0===e||e.forEach(e=>{var t,n,o;(null===(t=e.extensions)||void 0===t?void 0:t.KHR_node_selectability)&&!1===(null===(n=e.extensions)||void 0===n?void 0:n.KHR_node_selectability.selectable)&&(null===(o=e._babylonTransformNode)||void 0===o||o.getChildMeshes().forEach(e=>{e.isPickable=!1}))})})}dispose(){this._loader=null}},sl=!1;function rl(){sl||(sl=!0,ka("event/onSelect",nl,{blocks:["FlowGraphMeshPickEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{stopPropagation:{name:"stopPropagation"},nodeIndex:{name:"variable",toBlock:"FlowGraphGetVariableBlock",dataTransformer:e=>"pickedMesh_"+e}},outputs:{values:{selectedNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},controllerIndex:{name:"pointerId"},selectionPoint:{name:"pickedPoint"},selectionRayOrigin:{name:"pickOrigin"}},flows:{out:{name:"done"}}},interBlockConnectors:[{input:"asset",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"array",output:"nodes",inputBlockIndex:2,outputBlockIndex:3,isVariable:!0},{input:"object",output:"pickedMesh",inputBlockIndex:2,outputBlockIndex:0,isVariable:!0}],extraProcessor(e,t,n,o,s,r,i){var a,l,u,c,d,h,m;const f=s[s.length-1];f.config=f.config||{},f.config.glTF=i;const p=null===(u=null===(l=null===(a=e.configuration)||void 0===a?void 0:a.nodeIndex)||void 0===l?void 0:l.value)||void 0===u?void 0:u[0];if(void 0===p||"number"!=typeof p)throw new Error("nodeIndex not found in configuration");const _="pickedMesh_"+p;return s[1].config.variable=_,r._userVariables[_]={className:"Mesh",id:null===(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c[p]._babylonTransformNode)||void 0===d?void 0:d.id,uniqueId:null===(m=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[p]._babylonTransformNode)||void 0===m?void 0:m.uniqueId},s}}),mo("/nodes/{}/extensions/KHR_node_selectability/selectable",{get:e=>{const t=e._babylonTransformNode;return!t||void 0===t.isPickable||t.isPickable},set:(e,t)=>{var n;null===(n=t._primitiveBabylonMeshes)||void 0===n||n.forEach(t=>{t.isPickable=e})},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"isPickable"],type:"boolean"}),no(nl),to(nl,!0,e=>new ol(e)))}rl();var il={__proto__:null,KHR_node_selectability:ol,RegisterKHR_node_selectability:rl};const al="KHR_node_hoverability",ll="targetMeshPointerOver_",ul="targetMeshPointerOut_";let cl=class{constructor(e){this.name=al,this._loader=e,this.enabled=e.isExtensionUsed(al)}onReady(){return b(this,void 0,void 0,function*(){var e;null===(e=this._loader.gltf.nodes)||void 0===e||e.forEach(e=>{var t,n,o;(null===(t=e.extensions)||void 0===t?void 0:t.KHR_node_hoverability)&&!1===(null===(n=e.extensions)||void 0===n?void 0:n.KHR_node_hoverability.hoverable)&&(null===(o=e._babylonTransformNode)||void 0===o||o.getChildMeshes().forEach(e=>{e.pointerOverDisableMeshTesting=!0}))})})}dispose(){this._loader=null}},dl=!1;function hl(){dl||(dl=!0,ka("event/onHoverIn",al,{blocks:["FlowGraphPointerOverEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{stopPropagation:{name:"stopPropagation"},nodeIndex:{name:"variable",toBlock:"FlowGraphGetVariableBlock",dataTransformer:e=>ll+e}},outputs:{values:{hoverNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},controllerIndex:{name:"pointerId"}},flows:{out:{name:"done"}}},interBlockConnectors:[{input:"targetMesh",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"array",output:"nodes",inputBlockIndex:2,outputBlockIndex:3,isVariable:!0},{input:"object",output:"meshUnderPointer",inputBlockIndex:2,outputBlockIndex:0,isVariable:!0}],extraProcessor(e,t,n,o,s,r,i){var a,l,u,c,d,h,m;const f=s[s.length-1];f.config=f.config||{},f.config.glTF=i;const p=null===(u=null===(l=null===(a=e.configuration)||void 0===a?void 0:a.nodeIndex)||void 0===l?void 0:l.value)||void 0===u?void 0:u[0];if(void 0===p||"number"!=typeof p)throw new Error("nodeIndex not found in configuration");const _=ll+p;return s[1].config.variable=_,r._userVariables[_]={className:"Mesh",id:null===(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c[p]._babylonTransformNode)||void 0===d?void 0:d.id,uniqueId:null===(m=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[p]._babylonTransformNode)||void 0===m?void 0:m.uniqueId},s}}),ka("event/onHoverOut",al,{blocks:["FlowGraphPointerOutEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{stopPropagation:{name:"stopPropagation"},nodeIndex:{name:"variable",toBlock:"FlowGraphGetVariableBlock",dataTransformer:e=>ul+e}},outputs:{values:{hoverNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},controllerIndex:{name:"pointerId"}},flows:{out:{name:"done"}}},interBlockConnectors:[{input:"targetMesh",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"array",output:"nodes",inputBlockIndex:2,outputBlockIndex:3,isVariable:!0},{input:"object",output:"meshOutOfPointer",inputBlockIndex:2,outputBlockIndex:0,isVariable:!0}],extraProcessor(e,t,n,o,s,r,i){var a,l,u,c,d,h,m;const f=s[s.length-1];f.config=f.config||{},f.config.glTF=i;const p=null===(u=null===(l=null===(a=e.configuration)||void 0===a?void 0:a.nodeIndex)||void 0===l?void 0:l.value)||void 0===u?void 0:u[0];if(void 0===p||"number"!=typeof p)throw new Error("nodeIndex not found in configuration");const _=ul+p;return s[1].config.variable=_,r._userVariables[_]={className:"Mesh",id:null===(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c[p]._babylonTransformNode)||void 0===d?void 0:d.id,uniqueId:null===(m=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[p]._babylonTransformNode)||void 0===m?void 0:m.uniqueId},s}}),mo("/nodes/{}/extensions/KHR_node_hoverability/hoverable",{get:e=>{const t=e._babylonTransformNode;return!t||void 0===t.pointerOverDisableMeshTesting||t.pointerOverDisableMeshTesting},set:(e,t)=>{var n;null===(n=t._primitiveBabylonMeshes)||void 0===n||n.forEach(t=>{t.pointerOverDisableMeshTesting=!e})},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"pointerOverDisableMeshTesting"],type:"boolean"}),no(al),to(al,!0,e=>new cl(e)))}hl();var ml={__proto__:null,KHR_node_hoverability:cl,RegisterKHR_node_hoverability:hl};const fl="ExtrasAsMetadata";let pl=class{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){const n=e.metadata=e.metadata||{};(n.gltf=n.gltf||{}).extras=t.extras}}constructor(e){this.name=fl,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,n){return this._loader.loadNodeAsync(e,t,e=>{this._assignExtras(e,t),n(e)})}loadCameraAsync(e,t,n){return this._loader.loadCameraAsync(e,t,e=>{this._assignExtras(e,t),n(e)})}createMaterial(e,t,n){const o=this._loader.createMaterial(e,t,n);return this._assignExtras(o,t),o}loadAnimationAsync(e,t){return this._loader.loadAnimationAsync(e,t).then(e=>(this._assignExtras(e,t),e))}},_l=!1;function gl(){_l||(_l=!0,no(fl),to(fl,!1,e=>new pl(e)))}gl();var yl={__proto__:null,ExtrasAsMetadata:pl,RegisterExtrasAsMetadata:gl};class vl extends t.FlowGraphBlock{constructor(e){var n,o;super(e);const s=e.glTF,r=(null===(n=null==s?void 0:s.animations)||void 0===n?void 0:n.map(e=>e._babylonAnimationGroup))||[];this.animationGroups=this.registerDataOutput("animationGroups",t.RichTypeAny,r);const i=(null===(o=null==s?void 0:s.nodes)||void 0===o?void 0:o.map(e=>e._babylonTransformNode))||[];this.nodes=this.registerDataOutput("nodes",t.RichTypeAny,i)}getClassName(){return"FlowGraphGLTFDataProvider"}}var bl={__proto__:null,FlowGraphGLTFDataProvider:vl},xl={__proto__:null,AddObjectAccessorToKey:mo,EXT_lights_area:Os,EXT_lights_ies:rs,EXT_lights_image_based:No,EXT_mesh_gpu_instancing:Go,EXT_meshopt_compression:$o,EXT_texture_avif:es,EXT_texture_webp:Xo,ExtrasAsMetadata:pl,FlowGraphGLTFDataProvider:vl,GetMappingForKey:co,GetPathToObjectConverter:uo,InteractivityGraphToFlowGraphParser:$a,KHR_animation_pointer:ki,KHR_draco_mesh_compression:cs,KHR_gaussian_splatting:ys,KHR_interactivity:za,KHR_lights:As,KHR_materials_anisotropy:sr,KHR_materials_clearcoat:Us,KHR_materials_coat:qs,KHR_materials_diffuse_roughness:hi,KHR_materials_diffuse_transmission:zr,KHR_materials_dispersion:ai,KHR_materials_emissive_strength:ur,KHR_materials_fuzz:vr,KHR_materials_ior:Sr,KHR_materials_iridescence:Js,KHR_materials_pbrSpecularGlossiness:Is,KHR_materials_sheen:fr,KHR_materials_specular:Mr,KHR_materials_transmission:Hr,KHR_materials_unlit:Ds,KHR_materials_variants:Nr,KHR_materials_volume:Qr,KHR_materials_volume_scatter:ni,KHR_mesh_quantization:gi,KHR_node_hoverability:cl,KHR_node_selectability:ol,KHR_node_visibility:Za,KHR_texture_basisu:Ti,KHR_texture_transform:Ri,KHR_xmp_json_ld:Li,MSFT_audio_emitter:_a,MSFT_lod:xa,MSFT_minecraftMesh:Ca,MSFT_sRGBFactors:Ea,RegisterEXT_lights_area:Fs,RegisterEXT_lights_ies:as,RegisterEXT_lights_image_based:Bo,RegisterEXT_mesh_gpu_instancing:Ho,RegisterEXT_meshopt_compression:zo,RegisterEXT_texture_avif:ns,RegisterEXT_texture_webp:Qo,RegisterExtrasAsMetadata:gl,RegisterKHR_animation_pointer:Gi,RegisterKHR_draco_mesh_compression:hs,RegisterKHR_gaussian_splatting:bs,RegisterKHR_interactivity:Xa,RegisterKHR_lights:ws,RegisterKHR_materials_anisotropy:ir,RegisterKHR_materials_clearcoat:Ws,RegisterKHR_materials_coat:Ys,RegisterKHR_materials_diffuse_roughness:fi,RegisterKHR_materials_diffuse_transmission:qr,RegisterKHR_materials_dispersion:ui,RegisterKHR_materials_emissive_strength:dr,RegisterKHR_materials_fuzz:xr,RegisterKHR_materials_ior:Er,RegisterKHR_materials_iridescence:tr,RegisterKHR_materials_pbrSpecularGlossiness:Ps,RegisterKHR_materials_sheen:_r,RegisterKHR_materials_specular:Cr,RegisterKHR_materials_transmission:Ur,RegisterKHR_materials_unlit:Vs,RegisterKHR_materials_variants:Br,RegisterKHR_materials_volume:Jr,RegisterKHR_materials_volume_scatter:si,RegisterKHR_mesh_quantization:vi,RegisterKHR_node_hoverability:hl,RegisterKHR_node_selectability:rl,RegisterKHR_node_visibility:el,RegisterKHR_texture_basisu:Mi,RegisterKHR_texture_transform:Si,RegisterKHR_xmp_json_ld:Ni,RegisterMSFT_audio_emitter:ya,RegisterMSFT_lod:Aa,RegisterMSFT_minecraftMesh:Oa,RegisterMSFT_sRGBFactors:Ia,SetInterpolationForKey:ho,TransmissionHelper:Dr,_AddInteractivityObjectModel:ja,addNewInteractivityFlowGraphMapping:ka,ensureTransmissionHelper:Gr,getAllSupportedNativeNodeTypes:Ka,getMappingForDeclaration:Ba,getMappingForFullOperationName:Pa,gltfTypeToBabylonType:Ua},Tl={__proto__:null,AddObjectAccessorToKey:mo,AnimationPropertyInfo:wo,ArrayItem:_o,EXT_lights_area:Os,EXT_lights_ies:rs,EXT_lights_image_based:No,EXT_mesh_gpu_instancing:Go,EXT_meshopt_compression:$o,EXT_texture_avif:es,EXT_texture_webp:Xo,ExtrasAsMetadata:pl,FlowGraphGLTFDataProvider:vl,GLTFFileLoader:mn,GLTFLoader:yo,GetMappingForKey:co,GetPathToObjectConverter:uo,InteractivityGraphToFlowGraphParser:$a,KHR_animation_pointer:ki,KHR_draco_mesh_compression:cs,KHR_gaussian_splatting:ys,KHR_interactivity:za,KHR_lights:As,KHR_materials_anisotropy:sr,KHR_materials_clearcoat:Us,KHR_materials_coat:qs,KHR_materials_diffuse_roughness:hi,KHR_materials_diffuse_transmission:zr,KHR_materials_dispersion:ai,KHR_materials_emissive_strength:ur,KHR_materials_fuzz:vr,KHR_materials_ior:Sr,KHR_materials_iridescence:Js,KHR_materials_pbrSpecularGlossiness:Is,KHR_materials_sheen:fr,KHR_materials_specular:Mr,KHR_materials_transmission:Hr,KHR_materials_unlit:Ds,KHR_materials_variants:Nr,KHR_materials_volume:Qr,KHR_materials_volume_scatter:ni,KHR_mesh_quantization:gi,KHR_node_hoverability:cl,KHR_node_selectability:ol,KHR_node_visibility:Za,KHR_texture_basisu:Ti,KHR_texture_transform:Ri,KHR_xmp_json_ld:Li,LoadBoundingInfoFromPositionAccessor:go,MSFT_audio_emitter:_a,MSFT_lod:xa,MSFT_minecraftMesh:Ca,MSFT_sRGBFactors:Ea,OpenPBRMaterialLoadingAdapter:So,PBRMaterialLoadingAdapter:Eo,RegisterEXT_lights_area:Fs,RegisterEXT_lights_ies:as,RegisterEXT_lights_image_based:Bo,RegisterEXT_mesh_gpu_instancing:Ho,RegisterEXT_meshopt_compression:zo,RegisterEXT_texture_avif:ns,RegisterEXT_texture_webp:Qo,RegisterExtrasAsMetadata:gl,RegisterGLTF2Loader:bo,RegisterKHR_animation_pointer:Gi,RegisterKHR_draco_mesh_compression:hs,RegisterKHR_gaussian_splatting:bs,RegisterKHR_interactivity:Xa,RegisterKHR_lights:ws,RegisterKHR_materials_anisotropy:ir,RegisterKHR_materials_clearcoat:Ws,RegisterKHR_materials_coat:Ys,RegisterKHR_materials_diffuse_roughness:fi,RegisterKHR_materials_diffuse_transmission:qr,RegisterKHR_materials_dispersion:ui,RegisterKHR_materials_emissive_strength:dr,RegisterKHR_materials_fuzz:xr,RegisterKHR_materials_ior:Er,RegisterKHR_materials_iridescence:tr,RegisterKHR_materials_pbrSpecularGlossiness:Ps,RegisterKHR_materials_sheen:_r,RegisterKHR_materials_specular:Cr,RegisterKHR_materials_transmission:Ur,RegisterKHR_materials_unlit:Vs,RegisterKHR_materials_variants:Br,RegisterKHR_materials_volume:Jr,RegisterKHR_materials_volume_scatter:si,RegisterKHR_mesh_quantization:vi,RegisterKHR_node_hoverability:hl,RegisterKHR_node_selectability:rl,RegisterKHR_node_visibility:el,RegisterKHR_texture_basisu:Mi,RegisterKHR_texture_transform:Si,RegisterKHR_xmp_json_ld:Ni,RegisterMSFT_audio_emitter:ya,RegisterMSFT_lod:Aa,RegisterMSFT_minecraftMesh:Oa,RegisterMSFT_sRGBFactors:Ia,SetInterpolationForKey:ho,TransformNodeAnimationPropertyInfo:Co,TransmissionHelper:Dr,WeightAnimationPropertyInfo:Ro,_AddInteractivityObjectModel:ja,addNewInteractivityFlowGraphMapping:ka,ensureTransmissionHelper:Gr,getAllSupportedNativeNodeTypes:Ka,getMappingForDeclaration:Ba,getMappingForFullOperationName:Pa,getQuaternion:Ao,getVector3:To,getWeights:Mo,gltfTypeToBabylonType:Ua,registerGLTFExtension:to,registeredGLTFExtensions:eo,unregisterGLTFExtension:no};class Al{constructor(){this.materials=[]}parseMTL(e,n,o,s){if(n instanceof ArrayBuffer)return;const r=n.split("\n"),i=/\s+/;let a,l=null;for(let n=0;n<r.length;n++){const u=r[n].trim();if(0===u.length||"#"===u.charAt(0))continue;const c=u.indexOf(" ");let d=c>=0?u.substring(0,c):u;d=d.toLowerCase();const h=c>=0?u.substring(c+1).trim():"";if("newmtl"===d)l&&this.materials.push(l),e._blockEntityCollection=!!s,l=new t.StandardMaterial(h,e),l._parentContainer=s,e._blockEntityCollection=!1;else if("kd"===d&&l)a=h.split(i,3).map(parseFloat),l.diffuseColor=t.Color3.FromArray(a);else if("ka"===d&&l)a=h.split(i,3).map(parseFloat),l.ambientColor=t.Color3.FromArray(a);else if("ks"===d&&l)a=h.split(i,3).map(parseFloat),l.specularColor=t.Color3.FromArray(a);else if("ke"===d&&l)a=h.split(i,3).map(parseFloat),l.emissiveColor=t.Color3.FromArray(a);else if("ns"===d&&l)l.specularPower=parseFloat(h);else if("d"===d&&l)l.alpha=parseFloat(h);else if("map_ka"===d&&l)l.ambientTexture=Al._GetTexture(o,h,e);else if("map_kd"===d&&l)l.diffuseTexture=Al._GetTexture(o,h,e);else if("map_ks"===d&&l)l.specularTexture=Al._GetTexture(o,h,e);else if("map_ns"===d);else if("map_bump"===d&&l){const t=h.split(i),n=t.indexOf("-bm");let s=null;n>=0&&(s=t[n+1],t.splice(n,2)),l.bumpTexture=Al._GetTexture(o,t.join(" "),e),l.bumpTexture&&null!==s&&(l.bumpTexture.level=parseFloat(s))}else"map_d"===d&&l&&(l.opacityTexture=Al._GetTexture(o,h,e))}l&&this.materials.push(l)}static _GetTexture(e,n,o){if(!n)return null;let s=e;if("file:"===e){let e=n.lastIndexOf("\\");-1===e&&(e=n.lastIndexOf("/")),s+=e>-1?n.substring(e+1):n}else s+=n;return new t.Texture(s,o,!1,Al.INVERT_TEXTURE_Y)}}Al.INVERT_TEXTURE_Y=!0;class Ml{constructor(e,n,o){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],this._extColors=[],this._meshesFromObj=[],this._indicesForBabylon=[],this._wrappedPositionForBabylon=[],this._wrappedUvsForBabylon=[],this._wrappedColorsForBabylon=[],this._wrappedNormalsForBabylon=[],this._tuplePosNorm=[],this._curPositionInIndices=0,this._hasMeshes=!1,this._unwrappedPositionsForBabylon=[],this._unwrappedColorsForBabylon=[],this._unwrappedNormalsForBabylon=[],this._unwrappedUVForBabylon=[],this._triangles=[],this._materialNameFromObj="",this._objMeshName="",this._increment=1,this._isFirstMaterial=!0,this._grayColor=new t.Color4(.5,.5,.5,1),this._hasLineData=!1,this._materialToUse=e,this._babylonMeshesArray=n,this._loadingOptions=o}_isInArray(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});const n=e[t[0]].normals.indexOf(t[1]);return-1===n?-1:e[t[0]].idx[n]}_isInArrayUV(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});const n=e[t[0]].normals.indexOf(t[1]);return 1!=n&&t[2]===e[t[0]].uv[n]?e[t[0]].idx[n]:-1}_setData(e){var t,n;let o;null!==(t=e.indiceUvsFromObj)&&void 0!==t||(e.indiceUvsFromObj=-1),null!==(n=e.indiceNormalFromObj)&&void 0!==n||(e.indiceNormalFromObj=-1),o=this._loadingOptions.optimizeWithUV?this._isInArrayUV(this._tuplePosNorm,[e.indicePositionFromObj,e.indiceNormalFromObj,e.indiceUvsFromObj]):this._isInArray(this._tuplePosNorm,[e.indicePositionFromObj,e.indiceNormalFromObj]),-1===o?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(e.positionVectorFromOBJ),void 0!==e.textureVectorFromOBJ&&this._wrappedUvsForBabylon.push(e.textureVectorFromOBJ),void 0!==e.normalsVectorFromOBJ&&this._wrappedNormalsForBabylon.push(e.normalsVectorFromOBJ),void 0!==e.positionColorsFromOBJ&&this._wrappedColorsForBabylon.push(e.positionColorsFromOBJ),this._tuplePosNorm[e.indicePositionFromObj].normals.push(e.indiceNormalFromObj),this._tuplePosNorm[e.indicePositionFromObj].idx.push(this._curPositionInIndices++),this._loadingOptions.optimizeWithUV&&this._tuplePosNorm[e.indicePositionFromObj].uv.push(e.indiceUvsFromObj)):this._indicesForBabylon.push(o)}_unwrapData(){try{for(let e=0;e<this._wrappedPositionForBabylon.length;e++)this._unwrappedPositionsForBabylon.push(this._wrappedPositionForBabylon[e].x*this._handednessSign,this._wrappedPositionForBabylon[e].y,this._wrappedPositionForBabylon[e].z),this._wrappedNormalsForBabylon.length&&this._unwrappedNormalsForBabylon.push(this._wrappedNormalsForBabylon[e].x*this._handednessSign,this._wrappedNormalsForBabylon[e].y,this._wrappedNormalsForBabylon[e].z),this._wrappedUvsForBabylon.length&&this._unwrappedUVForBabylon.push(this._wrappedUvsForBabylon[e].x,this._wrappedUvsForBabylon[e].y),this._wrappedColorsForBabylon.length&&this._unwrappedColorsForBabylon.push(this._wrappedColorsForBabylon[e].r,this._wrappedColorsForBabylon[e].g,this._wrappedColorsForBabylon[e].b,this._wrappedColorsForBabylon[e].a);this._wrappedPositionForBabylon.length=0,this._wrappedNormalsForBabylon.length=0,this._wrappedUvsForBabylon.length=0,this._wrappedColorsForBabylon.length=0,this._tuplePosNorm.length=0,this._curPositionInIndices=0}catch(e){throw new Error("Unable to unwrap data while parsing OBJ data.",{cause:e})}}_getTriangles(e,t){for(let n=t;n<e.length-1;n++)this._pushTriangle(e,n)}_getColor(e){var t;return this._loadingOptions.importVertexColors?null!==(t=this._extColors[e])&&void 0!==t?t:this._colors[e]:void 0}_setDataForCurrentFaceWithPattern1(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=parseInt(this._triangles[e])-1;this._setData({indicePositionFromObj:t,positionVectorFromOBJ:this._positions[t],positionColorsFromOBJ:this._getColor(t)})}this._triangles.length=0}_setDataForCurrentFaceWithPattern2(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=this._triangles[e].split("/"),n=parseInt(t[0])-1,o=parseInt(t[1])-1;this._setData({indicePositionFromObj:n,indiceUvsFromObj:o,positionVectorFromOBJ:this._positions[n],textureVectorFromOBJ:this._uvs[o],positionColorsFromOBJ:this._getColor(n)})}this._triangles.length=0}_setDataForCurrentFaceWithPattern3(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=this._triangles[e].split("/"),n=parseInt(t[0])-1,o=parseInt(t[1])-1,s=parseInt(t[2])-1;this._setData({indicePositionFromObj:n,indiceUvsFromObj:o,indiceNormalFromObj:s,positionVectorFromOBJ:this._positions[n],textureVectorFromOBJ:this._uvs[o],normalsVectorFromOBJ:this._normals[s]})}this._triangles.length=0}_setDataForCurrentFaceWithPattern4(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=this._triangles[e].split("//"),n=parseInt(t[0])-1,o=parseInt(t[1])-1;this._setData({indicePositionFromObj:n,indiceNormalFromObj:o,positionVectorFromOBJ:this._positions[n],normalsVectorFromOBJ:this._normals[o],positionColorsFromOBJ:this._getColor(n)})}this._triangles.length=0}_setDataForCurrentFaceWithPattern5(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=this._triangles[e].split("/"),n=this._positions.length+parseInt(t[0]),o=this._uvs.length+parseInt(t[1]),s=this._normals.length+parseInt(t[2]);this._setData({indicePositionFromObj:n,indiceUvsFromObj:o,indiceNormalFromObj:s,positionVectorFromOBJ:this._positions[n],textureVectorFromOBJ:this._uvs[o],normalsVectorFromOBJ:this._normals[s],positionColorsFromOBJ:this._getColor(n)})}this._triangles.length=0}_addPreviousObjMesh(){this._meshesFromObj.length>0&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._unwrapData(),this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._handledMesh.indices=this._indicesForBabylon.slice(),this._handledMesh.positions=this._unwrappedPositionsForBabylon.slice(),this._unwrappedNormalsForBabylon.length&&(this._handledMesh.normals=this._unwrappedNormalsForBabylon.slice()),this._unwrappedUVForBabylon.length&&(this._handledMesh.uvs=this._unwrappedUVForBabylon.slice()),this._unwrappedColorsForBabylon.length&&(this._handledMesh.colors=this._unwrappedColorsForBabylon.slice()),this._handledMesh.hasLines=this._hasLineData,this._indicesForBabylon.length=0,this._unwrappedPositionsForBabylon.length=0,this._unwrappedColorsForBabylon.length=0,this._unwrappedNormalsForBabylon.length=0,this._unwrappedUVForBabylon.length=0,this._hasLineData=!1)}_optimizeNormals(e){const n=e.getVerticesData(t.VertexBuffer.PositionKind),o=e.getVerticesData(t.VertexBuffer.NormalKind),s={};if(!n||!o)return;for(let e=0;e<n.length/3;e++){const t=n[3*e+0]+"_"+n[3*e+1]+"_"+n[3*e+2];let o=s[t];o||(o=[],s[t]=o),o.push(e)}const r=new t.Vector3;for(const e in s){const t=s[e];if(t.length<2)continue;const n=t[0];for(let e=1;e<t.length;++e){const s=t[e];o[3*n+0]+=o[3*s+0],o[3*n+1]+=o[3*s+1],o[3*n+2]+=o[3*s+2]}r.copyFromFloats(o[3*n+0],o[3*n+1],o[3*n+2]),r.normalize();for(let e=0;e<t.length;++e){const n=t[e];o[3*n+0]=r.x,o[3*n+1]=r.y,o[3*n+2]=r.z}}e.setVerticesData(t.VertexBuffer.NormalKind,o)}static _IsLineElement(e){return e.startsWith("l")}static _IsObjectElement(e){return e.startsWith("o")}static _IsGroupElement(e){return e.startsWith("g")}static _GetZbrushMRGB(e,n){if(!e.startsWith("mrgb"))return null;if(e=e.replace("mrgb","").trim(),n)return[];const o=e.match(/[a-z0-9]/g);if(!o||o.length%8!=0)return[];const s=[];for(let e=0;e<o.length/8;e++){const n=o[8*e+2]+o[8*e+3],r=o[8*e+4]+o[8*e+5],i=o[8*e+6]+o[8*e+7];s.push(new t.Color4(parseInt(n,16)/255,parseInt(r,16)/255,parseInt(i,16)/255,1))}return s}parse(e,n,o,s,r){var i,a,l,u,c;n=(n=n.replace(/#MRGB/g,"mrgb")).replace(/#.*$/gm,"").trim(),this._loadingOptions.useLegacyBehavior?(this._pushTriangle=(e,t)=>this._triangles.push(e[0],e[t],e[t+1]),this._handednessSign=1):o.useRightHandedSystem?(this._pushTriangle=(e,t)=>this._triangles.push(e[0],e[t+1],e[t]),this._handednessSign=1):(this._pushTriangle=(e,t)=>this._triangles.push(e[0],e[t],e[t+1]),this._handednessSign=-1);const d=n.split("\n"),h=[];let m=[];h.push(m);for(let e=0;e<d.length;e++){const t=d[e].trim().replace(/\s\s/g," ");if(0!==t.length&&"#"!==t.charAt(0))if((Ml._IsGroupElement(t)||Ml._IsObjectElement(t))&&(m=[],h.push(m)),Ml._IsLineElement(t)){const e=t.split(" ");for(let t=1;t<e.length-1;t++)m.push(`l ${e[t]} ${e[t+1]}`)}else m.push(t)}const f=h.flat();for(let e=0;e<f.length;e++){const n=f[e].trim().replace(/\s\s/g," ");let o;if(0!==n.length&&"#"!==n.charAt(0))if(Ml.VertexPattern.test(n)){if(o=n.match(/[^ ]+/g),this._positions.push(new t.Vector3(parseFloat(o[1]),parseFloat(o[2]),parseFloat(o[3]))),this._loadingOptions.importVertexColors)if(o.length>=7){const e=parseFloat(o[4]),n=parseFloat(o[5]),s=parseFloat(o[6]);this._colors.push(new t.Color4(e>1?e/255:e,n>1?n/255:n,s>1?s/255:s,7===o.length||void 0===o[7]?1:parseFloat(o[7])))}else this._colors.push(this._grayColor)}else if(null!==(o=Ml.NormalPattern.exec(n)))this._normals.push(new t.Vector3(parseFloat(o[1]),parseFloat(o[2]),parseFloat(o[3])));else if(null!==(o=Ml.UVPattern.exec(n)))this._uvs.push(new t.Vector2(parseFloat(o[1])*this._loadingOptions.UVScaling.x,parseFloat(o[2])*this._loadingOptions.UVScaling.y));else if(null!==(o=Ml.FacePattern3.exec(n)))this._setDataForCurrentFaceWithPattern3(o[1].trim().split(" "),1);else if(null!==(o=Ml.FacePattern4.exec(n)))this._setDataForCurrentFaceWithPattern4(o[1].trim().split(" "),1);else if(null!==(o=Ml.FacePattern5.exec(n)))this._setDataForCurrentFaceWithPattern5(o[1].trim().split(" "),1);else if(null!==(o=Ml.FacePattern2.exec(n)))this._setDataForCurrentFaceWithPattern2(o[1].trim().split(" "),1);else if(null!==(o=Ml.FacePattern1.exec(n)))this._setDataForCurrentFaceWithPattern1(o[1].trim().split(" "),1);else if(null!==(o=Ml.LinePattern1.exec(n)))this._setDataForCurrentFaceWithPattern1(o[1].trim().split(" "),0),this._hasLineData=!0;else if(null!==(o=Ml.LinePattern2.exec(n)))this._setDataForCurrentFaceWithPattern2(o[1].trim().split(" "),0),this._hasLineData=!0;else if(o=Ml._GetZbrushMRGB(n,!this._loadingOptions.importVertexColors))for(const e of o)this._extColors.push(e);else if(null!==(o=Ml.LinePattern3.exec(n)))this._setDataForCurrentFaceWithPattern3(o[1].trim().split(" "),0),this._hasLineData=!0;else if(Ml.GroupDescriptor.test(n)||Ml.ObjectDescriptor.test(n)){const e={name:n.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:Ml.ObjectDescriptor.test(n)};this._addPreviousObjMesh(),this._meshesFromObj.push(e),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(Ml.UseMtlDescriptor.test(n)){if(this._materialNameFromObj=n.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();const e={name:(this._objMeshName||"mesh")+"_mm"+this._increment.toString(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:!1};this._increment++,this._meshesFromObj.push(e),this._hasMeshes=!0}this._hasMeshes&&this._isFirstMaterial&&(this._meshesFromObj[this._meshesFromObj.length-1].materialName=this._materialNameFromObj,this._isFirstMaterial=!1)}else Ml.MtlLibGroupDescriptor.test(n)?r(n.substring(7).trim()):Ml.SmoothDescriptor.test(n)||t.Logger.Log("Unhandled expression at line : "+n)}if(this._hasMeshes&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData(),this._handledMesh.indices=this._indicesForBabylon,this._handledMesh.positions=this._unwrappedPositionsForBabylon,this._unwrappedNormalsForBabylon.length&&(this._handledMesh.normals=this._unwrappedNormalsForBabylon),this._unwrappedUVForBabylon.length&&(this._handledMesh.uvs=this._unwrappedUVForBabylon),this._unwrappedColorsForBabylon.length&&(this._handledMesh.colors=this._unwrappedColorsForBabylon),this._handledMesh.hasLines=this._hasLineData),!this._hasMeshes){let e=null;if(this._indicesForBabylon.length)this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData();else{for(const e of this._positions)this._unwrappedPositionsForBabylon.push(e.x,e.y,e.z);if(this._normals.length)for(const e of this._normals)this._unwrappedNormalsForBabylon.push(e.x,e.y,e.z);if(this._uvs.length)for(const e of this._uvs)this._unwrappedUVForBabylon.push(e.x,e.y);if(this._extColors.length)for(const e of this._extColors)this._unwrappedColorsForBabylon.push(e.r,e.g,e.b,e.a);else if(this._colors.length)for(const e of this._colors)this._unwrappedColorsForBabylon.push(e.r,e.g,e.b,e.a);this._materialNameFromObj||(e=new t.StandardMaterial(t.Geometry.RandomId(),o),e.pointsCloud=!0,this._materialNameFromObj=e.name,this._normals.length||(e.disableLighting=!0,e.emissiveColor=t.Color3.White()))}this._meshesFromObj.push({name:t.Geometry.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:e,isObject:!0,hasLines:this._hasLineData})}for(let n=0;n<this._meshesFromObj.length;n++){if(e&&this._meshesFromObj[n].name)if(e instanceof Array){if(-1===e.indexOf(this._meshesFromObj[n].name))continue}else if(this._meshesFromObj[n].name!==e)continue;this._handledMesh=this._meshesFromObj[n],o._blockEntityCollection=!!s;const r=new t.Mesh(this._meshesFromObj[n].name,o);if(r._parentContainer=s,o._blockEntityCollection=!1,this._handledMesh._babylonMesh=r,!this._handledMesh.isObject)for(let e=n-1;e>=0;--e)if(this._meshesFromObj[e].isObject&&this._meshesFromObj[e]._babylonMesh){r.parent=this._meshesFromObj[e]._babylonMesh;break}if(this._materialToUse.push(this._meshesFromObj[n].materialName),this._handledMesh.hasLines&&(null!==(i=r._internalMetadata)&&void 0!==i||(r._internalMetadata={}),r._internalMetadata._isLine=!0),0===(null===(a=this._handledMesh.positions)||void 0===a?void 0:a.length)){this._babylonMeshesArray.push(r);continue}const d=new t.VertexData;if(d.indices=this._handledMesh.indices,d.positions=this._handledMesh.positions,this._loadingOptions.computeNormals||!(null===(l=this._handledMesh.normals)||void 0===l?void 0:l.length)){const e=new Array;t.VertexData.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,e),d.normals=e}else d.normals=this._handledMesh.normals;(null===(u=this._handledMesh.uvs)||void 0===u?void 0:u.length)&&(d.uvs=this._handledMesh.uvs),(null===(c=this._handledMesh.colors)||void 0===c?void 0:c.length)&&(d.colors=this._handledMesh.colors),d.applyToMesh(r),this._loadingOptions.invertY&&(r.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(r),this._babylonMeshesArray.push(r),this._handledMesh.directMaterial&&(r.material=this._handledMesh.directMaterial)}}}Ml.ObjectDescriptor=/^o/,Ml.GroupDescriptor=/^g/,Ml.MtlLibGroupDescriptor=/^mtllib /,Ml.UseMtlDescriptor=/^usemtl /,Ml.SmoothDescriptor=/^s /,Ml.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/,Ml.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,Ml.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,Ml.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/,Ml.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,Ml.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,Ml.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,Ml.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,Ml.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/,Ml.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/,Ml.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;const wl={name:"obj",extensions:".obj"};class Cl{static get INVERT_TEXTURE_Y(){return Al.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){Al.INVERT_TEXTURE_Y=e}constructor(e){this.name=wl.name,this.extensions=wl.extensions,this._assetContainer=null,this._loadingOptions=Object.assign(Object.assign({},Cl._DefaultLoadingOptions),null!=e?e:{})}static get _DefaultLoadingOptions(){return{computeNormals:Cl.COMPUTE_NORMALS,optimizeNormals:Cl.OPTIMIZE_NORMALS,importVertexColors:Cl.IMPORT_VERTEX_COLORS,invertY:Cl.INVERT_Y,invertTextureY:Cl.INVERT_TEXTURE_Y,UVScaling:Cl.UV_SCALING,materialLoadingFailsSilently:Cl.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:Cl.OPTIMIZE_WITH_UV,skipMaterials:Cl.SKIP_MATERIALS,useLegacyBehavior:Cl.USE_LEGACY_BEHAVIOR}}_loadMTL(e,n,o,s){const r=n+e;t.Tools.LoadFile(r,o,void 0,void 0,!1,(e,t)=>{s(r,t)})}createPlugin(e){return new Cl(e[wl.name])}canDirectLoad(){return!1}importMeshAsync(e,t,n,o){return this._parseSolidAsync(e,t,n,o).then(e=>({meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))}loadAsync(e,t,n){return this.importMeshAsync(null,e,t,n).then(()=>{})}loadAssetContainerAsync(e,n,o){const s=new t.AssetContainer(e);return this._assetContainer=s,this.importMeshAsync(null,e,n,o).then(e=>(e.meshes.forEach(e=>s.meshes.push(e)),e.meshes.forEach(e=>{const t=e.material;t&&-1==s.materials.indexOf(t)&&(s.materials.push(t),t.getActiveTextures().forEach(e=>{-1==s.textures.indexOf(e)&&s.textures.push(e)}))}),this._assetContainer=null,s)).catch(e=>{throw this._assetContainer=null,e})}_parseSolidAsync(e,n,o,s){let r="";const i=new Al,a=[],l=[];o=o.replace(/#.*$/gm,"").trim(),new Ml(a,l,this._loadingOptions).parse(e,o,n,this._assetContainer,e=>{r=e});const u=[];return""===r||this._loadingOptions.skipMaterials||u.push(new Promise((e,o)=>{this._loadMTL(r,s,u=>{try{i.parseMTL(n,u,s,this._assetContainer);for(let e=0;e<i.materials.length;e++){let t=0;const n=[];let o;for(;(o=a.indexOf(i.materials[e].name,t))>-1;)n.push(o),t=o+1;if(-1===o&&0===n.length)i.materials[e].dispose();else for(let t=0;t<n.length;t++){const o=l[n[t]],s=i.materials[e];o.material=s,o.getTotalIndices()||(s.pointsCloud=!0)}}e()}catch(n){t.Tools.Warn(`Error processing MTL file: '${r}'`),this._loadingOptions.materialLoadingFailsSilently?e():o(n)}},(n,s)=>{t.Tools.Warn(`Error downloading MTL file: '${r}'`),this._loadingOptions.materialLoadingFailsSilently?e():o(s)})})),Promise.all(u).then(()=>{const e=e=>{var t,n;return Boolean(null!==(n=null===(t=e._internalMetadata)||void 0===t?void 0:t._isLine)&&void 0!==n&&n)};return l.forEach(o=>{var s,r;if(e(o)){let i=null!==(s=o.material)&&void 0!==s?s:new t.StandardMaterial(o.name+"_line",n);i.getBindedMeshes().filter(t=>!e(t)).length>0&&(i=null!==(r=i.clone(i.name+"_line"))&&void 0!==r?r:i),i.wireframe=!0,o.material=i,o._internalMetadata&&(o._internalMetadata._isLine=void 0)}}),l})}}Cl.OPTIMIZE_WITH_UV=!0,Cl.INVERT_Y=!1,Cl.IMPORT_VERTEX_COLORS=!1,Cl.COMPUTE_NORMALS=!1,Cl.OPTIMIZE_NORMALS=!1,Cl.UV_SCALING=new t.Vector2(1,1),Cl.SKIP_MATERIALS=!1,Cl.MATERIAL_LOADING_FAILS_SILENTLY=!0,Cl.USE_LEGACY_BEHAVIOR=!1;let Rl=!1;function Ol(){Rl||(Rl=!0,t.RegisterSceneLoaderPlugin(new Cl))}Ol();var Sl={__proto__:null,OBJFileLoader:Cl,RegisterOBJFileLoader:Ol},Fl={__proto__:null,MTLFileLoader:Al,OBJFileLoader:Cl,RegisterOBJFileLoader:Ol,SolidParser:Ml};const El={name:"stl",extensions:{".stl":{isBinary:!0}}};class Ll{constructor(){this.solidPattern=/solid (\S*)([\S\s]*?)endsolid[ ]*(\S*)/g,this.facetsPattern=/facet([\s\S]*?)endfacet/g,this.normalPattern=/normal[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g,this.vertexPattern=/vertex[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g,this.name=El.name,this.extensions=El.extensions}importMesh(e,n,o,s,r){let i;if("string"!=typeof o){if(this._isBinary(o)){const e=new t.Mesh("stlmesh",n);return this._parseBinary(e,o),r&&r.push(e),!0}o=(new TextDecoder).decode(new Uint8Array(o))}for(;i=this.solidPattern.exec(o);){let o=i[1];const s=i[3];if(s&&o!=s)return t.Tools.Error("Error in STL, solid name != endsolid name"),!1;if(e&&o)if(e instanceof Array){if(!e.indexOf(o))continue}else if(o!==e)continue;o=o||"stlmesh";const a=new t.Mesh(o,n);this._parseASCII(a,i[2]),r&&r.push(a)}return!0}load(e,t,n){return this.importMesh(null,e,t,n,null)}loadAssetContainer(e,n,o){const s=new t.AssetContainer(e);return e._blockEntityCollection=!0,this.importMesh(null,e,n,o,s.meshes),e._blockEntityCollection=!1,s}_isBinary(e){const t=new DataView(e);if(t.byteLength<=80)return!1;if(84+50*t.getUint32(80,!0)===t.byteLength)return!0;const n=[115,111,108,105,100];for(let e=0;e<5;e++)if(t.getUint8(e)!==n[e])return!0;return!1}_parseBinary(e,n){const o=new DataView(n),s=o.getUint32(80,!0);let r=0;const i=new Float32Array(3*s*3),a=new Float32Array(3*s*3),l=new Uint32Array(3*s);let u=0;for(let e=0;e<s;e++){const t=84+50*e,n=o.getFloat32(t,!0),s=o.getFloat32(t+4,!0),c=o.getFloat32(t+8,!0);for(let e=1;e<=3;e++){const l=t+12*e;i[r]=o.getFloat32(l,!0),a[r]=n,Ll.DO_NOT_ALTER_FILE_COORDINATES?(i[r+1]=o.getFloat32(l+4,!0),i[r+2]=o.getFloat32(l+8,!0),a[r+1]=s,a[r+2]=c):(i[r+2]=o.getFloat32(l+4,!0),i[r+1]=o.getFloat32(l+8,!0),a[r+2]=s,a[r+1]=c),r+=3}Ll.DO_NOT_ALTER_FILE_COORDINATES?(l[u]=u,l[u+1]=u+2,l[u+2]=u+1,u+=3):(l[u]=u++,l[u]=u++,l[u]=u++)}e.setVerticesData(t.VertexBuffer.PositionKind,i),e.setVerticesData(t.VertexBuffer.NormalKind,a),e.setIndices(l),e.computeWorldMatrix(!0)}_parseASCII(e,n){const o=[],s=[],r=[];let i,a=0;for(;i=this.facetsPattern.exec(n);){const e=i[1],t=this.normalPattern.exec(e);if(this.normalPattern.lastIndex=0,!t)continue;const n=[Number(t[1]),Number(t[5]),Number(t[3])];let l;for(;l=this.vertexPattern.exec(e);)Ll.DO_NOT_ALTER_FILE_COORDINATES?(o.push(Number(l[1]),Number(l[3]),Number(l[5])),s.push(n[0],n[2],n[1])):(o.push(Number(l[1]),Number(l[5]),Number(l[3])),s.push(n[0],n[1],n[2]));Ll.DO_NOT_ALTER_FILE_COORDINATES?(r.push(a,a+2,a+1),a+=3):r.push(a++,a++,a++),this.vertexPattern.lastIndex=0}this.facetsPattern.lastIndex=0,e.setVerticesData(t.VertexBuffer.PositionKind,o),e.setVerticesData(t.VertexBuffer.NormalKind,s),e.setIndices(r),e.computeWorldMatrix(!0)}}Ll.DO_NOT_ALTER_FILE_COORDINATES=!1;let Il=!1;function Nl(){Il||(Il=!0,t.RegisterSceneLoaderPlugin(new Ll))}Nl();var Pl={__proto__:null,RegisterSTLFileLoader:Nl,STLFileLoader:Ll},Bl={__proto__:null,RegisterSTLFileLoader:Nl,STLFileLoader:Ll};const kl={name:"splat",extensions:{".splat":{isBinary:!0},".ply":{isBinary:!0},".spz":{isBinary:!0},".json":{isBinary:!1},".sog":{isBinary:!0}}},Dl=.28209479177387814;function Gl(e,t,n){return b(this,void 0,void 0,function*(){const o=new Promise((o,s)=>{const r=n.createCanvasImage();if(!r)throw new Error("Failed to create ImageBitmap");let i;if(r.onload=()=>{try{const e=n.createCanvas(r.width,r.height);if(!e)throw new Error("Failed to create canvas");const t=e.getContext("2d");if(!t)throw new Error("Failed to get 2D context");t.drawImage(r,0,0);const s=t.getImageData(0,0,e.width,e.height);o({bits:new Uint8Array(s.data.buffer),width:s.width,height:s.height})}catch(e){s(`Error loading image ${r.src} with exception: ${e}`)}},r.onerror=e=>{s(`Error loading image ${r.src} with exception: ${e}`)},r.crossOrigin="anonymous","string"==typeof e){if(!t)throw new Error("filename is required when using a URL");r.src=e+t}else{const t=new Blob([e],{type:"image/webp"});i=URL.createObjectURL(t),r.src=i}});return yield o})}function Vl(e,n,o){return b(this,void 0,void 0,function*(){let s,r;if(e instanceof Map){r=e;const t=r.get("meta.json");if(!t)throw new Error("meta.json not found in files Map");s=JSON.parse((new TextDecoder).decode(t))}else s=e;const i=[...s.means.files,...s.scales.files,...s.quats.files,...s.sh0.files];s.shN&&i.push(...s.shN.files);const a=yield Promise.all(i.map(e=>b(this,void 0,void 0,function*(){if(r&&r.has(e)){const t=r.get(e);return yield Gl(t,e,o.getEngine())}return yield Gl(n,e,o.getEngine())})));return yield function(e,n,o){return b(this,void 0,void 0,function*(){const s=e.count?e.count:e.means.shape[0],r=new ArrayBuffer(32*s),i=new Float32Array(r),a=new Float32Array(r),l=new Uint8ClampedArray(r),u=new Uint8ClampedArray(r),c=e=>Math.sign(e)*(Math.exp(Math.abs(e))-1),d=n[0].bits,h=n[1].bits;if(!Array.isArray(e.means.mins)||!Array.isArray(e.means.maxs))throw new Error("Missing arrays in SOG data.");for(let n=0;n<s;n++){const o=4*n;for(let s=0;s<3;s++){const r=e.means.mins[s],a=e.means.maxs[s],l=h[o+s]<<8|d[o+s],u=t.Scalar.Lerp(r,a,l/65535);i[8*n+s]=c(u)}}const m=n[2].bits;if(2===e.version){if(!e.scales.codebook)throw new Error("Missing codebook in SOG version 2 scales data.");for(let t=0;t<s;t++){const n=4*t;for(let o=0;o<3;o++){const s=e.scales.codebook[m[n+o]],r=Math.exp(s);a[8*t+3+o]=r}}}else{if(!Array.isArray(e.scales.mins)||!Array.isArray(e.scales.maxs))throw new Error("Missing arrays in SOG scales data.");for(let n=0;n<s;n++){const o=4*n;for(let s=0;s<3;s++){const r=m[o+s],i=t.Scalar.Lerp(e.scales.mins[s],e.scales.maxs[s],r/255),l=Math.exp(i);a[8*n+3+s]=l}}}const f=n[4].bits;if(2===e.version){if(!e.sh0.codebook)throw new Error("Missing codebook in SOG version 2 sh0 data.");for(let t=0;t<s;t++){const n=4*t;for(let o=0;o<3;o++){const s=.5+e.sh0.codebook[f[n+o]]*Dl;l[32*t+24+o]=Math.max(0,Math.min(255,Math.round(255*s)))}l[32*t+24+3]=f[n+3]}}else{if(!Array.isArray(e.sh0.mins)||!Array.isArray(e.sh0.maxs))throw new Error("Missing arrays in SOG sh0 data.");for(let n=0;n<s;n++){const o=4*n;for(let s=0;s<4;s++){const r=e.sh0.mins[s],i=e.sh0.maxs[s],a=f[o+s],u=t.Scalar.Lerp(r,i,a/255);let c;c=s<3?.5+u*Dl:1/(1+Math.exp(-u)),l[32*n+24+s]=Math.max(0,Math.min(255,Math.round(255*c)))}}}const p=e=>2*(e/255-.5)/Math.SQRT2,_=n[3].bits;for(let e=0;e<s;e++){const t=_[4*e+0],n=_[4*e+1],o=_[4*e+2],s=_[4*e+3],r=p(t),i=p(n),a=p(o),l=s-252,c=r*r+i*i+a*a,d=Math.sqrt(Math.max(0,1-c));let h;switch(l){case 0:h=[d,r,i,a];break;case 1:h=[r,d,i,a];break;case 2:h=[r,i,d,a];break;case 3:h=[r,i,a,d];break;default:throw new Error("Invalid quaternion mode")}u[32*e+28+0]=127.5*h[0]+127.5,u[32*e+28+1]=127.5*h[1]+127.5,u[32*e+28+2]=127.5*h[2]+127.5,u[32*e+28+3]=127.5*h[3]+127.5}if(e.shN){const i=e.shN.bands?Math.pow(e.shN.bands+1,2)-1:e.shN.shape[1]/3,a=void 0!==e.shN.bands&&null!==e.shN.bands?e.shN.bands:Math.round(Math.sqrt(i+1)-1),l=n[5].bits,u=n[6].bits,c=n[5].width,d=3*i,h=Math.ceil(d/16),m=o.getEngine().getCaps().maxTextureSize,f=Math.ceil(s/m),p=t.AllocateShBuffers(h,f*m*4*4);if(2===e.version){if(!e.shN.codebook)throw new Error("Missing codebook in SOG version 2 shN data.");for(let t=0;t<s;t++){const n=u[4*t+0]+(u[4*t+1]<<8),o=n%64*i,s=Math.floor(n/64);for(let n=0;n<i;n++)for(let r=0;r<3;r++){const i=3*n+r,a=Math.floor(i/16),u=p[a],d=i%16,h=16*t,m=127.5*e.shN.codebook[l[4*(o+n)+r+s*c*4]]+127.5;u[d+h]=Math.max(0,Math.min(255,m))}}}else for(let n=0;n<s;n++){const o=u[4*n+0]+(u[4*n+1]<<8),s=o%64*i,r=Math.floor(o/64),a=e.shN.mins,d=e.shN.maxs;for(let e=0;e<3;e++)for(let o=0;o<i/3;o++){const i=3*o+e,u=Math.floor(i/16),h=p[u],m=i%16,f=16*n,_=127.5*t.Scalar.Lerp(a,d,l[4*(s+o)+e+r*c*4]/255)+127.5;h[m+f]=Math.max(0,Math.min(255,_))}}return yield new Promise(e=>{e({mode:0,data:r,hasVertexColors:!1,sh:p,shDegree:a})})}return yield new Promise(e=>{e({mode:0,data:r,hasVertexColors:!1})})})}(s,a,o)})}function Hl(e,n){return function(e,n,o,s){const r=new t.RawTexture(n,o,s,t.Constants.TEXTUREFORMAT_RGBA,e,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_UNSIGNED_BYTE);return r.wrapU=t.Constants.TEXTURE_CLAMP_ADDRESSMODE,r.wrapV=t.Constants.TEXTURE_CLAMP_ADDRESSMODE,r}(e,n.bits,n.width,n.height)}function Kl(e,n,o){return b(this,void 0,void 0,function*(){const s=o.getEngine();if("function"==typeof createImageBitmap)try{const r=n.toLowerCase().endsWith(".png")?"image/png":"image/webp";let i;if("string"==typeof e){const o=yield t.Tools.LoadFileAsync(e+n,!0);i=new Blob([o],{type:r})}else i=new Blob([e],{type:r});const a=yield createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});try{const e=new t.RawTexture(null,a.width,a.height,t.Constants.TEXTUREFORMAT_RGBA,o,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_UNSIGNED_BYTE);e.wrapU=t.Constants.TEXTURE_CLAMP_ADDRESSMODE,e.wrapV=t.Constants.TEXTURE_CLAMP_ADDRESSMODE;const n=e.getInternalTexture();return n&&s.updateDynamicTexture(n,a,!1,!1),e}finally{a.close()}}catch(e){}const r=yield Gl(e,n,s);return Hl(o,r)})}function Ul(e,n,o,s){const r=e=>Math.sign(e)*(Math.exp(Math.abs(e))-1);if(!Array.isArray(e.means.mins)||!Array.isArray(e.means.maxs))throw new Error("Missing arrays in SOG data.");const i=new Float32Array(4*s);for(let a=0;a<s;a++){const s=4*a;for(let l=0;l<3;l++){const u=o[s+l]<<8|n[s+l],c=t.Scalar.Lerp(e.means.mins[l],e.means.maxs[l],u/65535);i[4*a+l]=r(c)}i[4*a+3]=1}return i}function $l(e,n,o){return b(this,arguments,void 0,function*(e,n,o,s=!0,r,i){var a,l,u,c,d,h,m;let f,p;if(e instanceof Map){p=e;const t=p.get("meta.json");if(!t)throw new Error("meta.json not found in files Map");f=JSON.parse((new TextDecoder).decode(t))}else f=e;const _=e=>b(this,void 0,void 0,function*(){if(p&&p.has(e))return yield Gl(p.get(e),e,o.getEngine());if(r){const t=new Uint8Array(yield r.loadFileAsync(n+e,i));return yield Gl(t,e,o.getEngine())}return yield Gl(n,e,o.getEngine())}),g=e=>b(this,void 0,void 0,function*(){if(p&&p.has(e))return yield Kl(p.get(e),e,o);if(r){const t=new Uint8Array(yield r.loadFileAsync(n+e,i));return yield Kl(t,e,o)}return yield Kl(n,e,o)}),y=[...f.scales.files,...f.quats.files,...f.sh0.files,...null!==(l=null===(a=f.shN)||void 0===a?void 0:a.files)&&void 0!==l?l:[]];let v,x,T,A,M,w=null;if(s){const[e,t]=yield Promise.all([Promise.all(f.means.files.map(_)),Promise.all(y.map(g))]);w=[e[0],e[1]],M=t,v=Hl(o,e[0]),x=Hl(o,e[1]),T=e[0].width,A=e[0].height}else{const[e,t]=yield Promise.all([Promise.all(f.means.files.map(g)),Promise.all(y.map(g))]);M=t,v=e[0],x=e[1];const n=v.getSize();T=n.width,A=n.height}const C=null!==(u=f.count)&&void 0!==u?u:f.means.shape[0],R=T*A;if(R<C)throw new Error(`SOG texture contains ${R} texels, but metadata references ${C} splats.`);const O=M[0],S=M[1],F=M[2];let E,L,I,N=0,P=0;if(f.shN&&M.length>=5&&(E=M[3],L=M[4],N=f.shN.bands?Math.pow(f.shN.bands+1,2)-1:f.shN.shape[1]/3,P=null!==(c=f.shN.bands)&&void 0!==c?c:Math.round(Math.sqrt(N+1)-1)),2===f.version){const e=256,n=new Float32Array(3*e);f.scales.codebook&&n.set(f.scales.codebook.slice(0,e),0),f.sh0.codebook&&n.set(f.sh0.codebook.slice(0,e),e),(null===(d=f.shN)||void 0===d?void 0:d.codebook)&&n.set(f.shN.codebook.slice(0,e),2*e),I=new t.RawTexture(n,3*e,1,t.Constants.TEXTUREFORMAT_R,o,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_FLOAT),I.wrapU=t.Constants.TEXTURE_CLAMP_ADDRESSMODE,I.wrapV=t.Constants.TEXTURE_CLAMP_ADDRESSMODE}const B=f.means.mins,k=f.means.maxs,D={version:2===f.version?2:1,splatCount:C,shDegree:P,meansTextureL:v,meansTextureU:x,scalesTexture:O,quatsTexture:S,sh0Texture:F,shCentroidsTexture:E,shLabelsTexture:L,codebookTexture:I,meansMin:[B[0],B[1],B[2]],meansMax:[k[0],k[1],k[2]],scalesMin:Array.isArray(f.scales.mins)?[f.scales.mins[0],f.scales.mins[1],f.scales.mins[2]]:void 0,scalesMax:Array.isArray(f.scales.maxs)?[f.scales.maxs[0],f.scales.maxs[1],f.scales.maxs[2]]:void 0,sh0Min:Array.isArray(f.sh0.mins)?[f.sh0.mins[0],f.sh0.mins[1],f.sh0.mins[2],f.sh0.mins[3]]:void 0,sh0Max:Array.isArray(f.sh0.maxs)?[f.sh0.maxs[0],f.sh0.maxs[1],f.sh0.maxs[2],f.sh0.maxs[3]]:void 0,shnMin:"number"==typeof(null===(h=f.shN)||void 0===h?void 0:h.mins)?f.shN.mins:void 0,shnMax:"number"==typeof(null===(m=f.shN)||void 0===m?void 0:m.maxs)?f.shN.maxs:void 0,shCoeffCount:N,positions:w?Ul(f,w[0].bits,w[1].bits,C):new Float32Array(0)};return{mode:0,data:new ArrayBuffer(0),hasVertexColors:!1,shDegree:P,sogTextures:D}})}const Wl="precision highp float;\nattribute vec3 position;\nvoid main() {\n gl_Position = vec4(position.xy, 0.0, 1.0);\n}\n",zl="\nattribute position : vec3<f32>;\n@vertex\nfn main(input : VertexInputs) -> FragmentInputs {\n vertexOutputs.position = vec4<f32>(input.position.xy, 0.0, 1.0);\n}\n";class jl{get supportsAsyncCentersReadback(){var e;const t=this._scene.getEngine();if(t.isWebGPU)return!0;const n=t;return!!n._gl&&"function"==typeof n._readPixelsAsync&&(null!==(e=n.webGLVersion)&&void 0!==e?e:0)>=2}get textureSize(){return this._textureSize}get textures(){return this._mrt.textures}constructor(e,t){this._copyMaterial=null,this._relayoutMapData=null,this._relayoutMapTexture=null,this._disposed=!1,this._readFbo=null,this._scene=e,this._shaderLanguage=e.getEngine().isWebGPU?1:0,this._textureSize=Math.max(1,Math.ceil(Math.sqrt(Math.max(1,t)))),this._mrt=this._createMrt("gsWorkBuffer",!0),this._material=this._createMaterial(),this._quad=this._createQuad(),this._quad.material=this._material}_createMrt(e,n){const o=new t.MultiRenderTarget(e,{width:this._textureSize,height:this._textureSize},4,this._scene,{types:[t.Constants.TEXTURETYPE_FLOAT,t.Constants.TEXTURETYPE_FLOAT,t.Constants.TEXTURETYPE_FLOAT,t.Constants.TEXTURETYPE_UNSIGNED_BYTE],samplingModes:[t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE],formats:[t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA],generateDepthBuffer:!1,generateDepthTexture:!1,generateMipMaps:!1},[`${e}Centers`,`${e}CovA`,`${e}CovB`,`${e}Colors`]);return o.clearColor=new t.Color4(0,0,0,0),o.renderList=[],n&&o.onClearObservable.add(()=>{}),o}decodeAsync(e,t){return b(this,void 0,void 0,function*(){this._disposed||(this._applyPack(e,t),yield new Promise(e=>{const t=()=>{this._disposed?e():this._material.isReady(this._quad)?(this._mrt.renderList=[this._quad],this._mrt.render(),e()):this._scene.onBeforeRenderObservable.addOnce(t)};this._scene.onBeforeRenderObservable.addOnce(t)}))})}isRelayoutReady(){return!this._disposed&&(this._copyMaterial||(this._copyMaterial=this._createCopyMaterial()),this._copyMaterial.isReady(this._quad))}relayoutSync(e){if(this._disposed||!this._copyMaterial)return;const n=this._textureSize;this._relayoutMapData||(this._relayoutMapData=new Float32Array(n*n));const o=this._relayoutMapData;o.fill(-1),o.set(e.subarray(0,Math.min(e.length,o.length))),this._relayoutMapTexture?this._relayoutMapTexture.update(o):this._relayoutMapTexture=new t.RawTexture(o,n,n,t.Constants.TEXTUREFORMAT_R,this._scene,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_FLOAT);const s=this._relayoutMapTexture,r=this._createMrt("gsRelayoutTemp",!1);try{this._renderRelayoutPass(r,this._mrt.textures,s,1),this._renderRelayoutPass(this._mrt,r.textures,s,0)}finally{r.dispose(),this._quad.material=this._material}}_renderRelayoutPass(e,t,n,o){const s=this._copyMaterial;s.setTexture("uMapTex",n),s.setTexture("uSrc0",t[0]),s.setTexture("uSrc1",t[1]),s.setTexture("uSrc2",t[2]),s.setTexture("uSrc3",t[3]),s.setInt("uDstWidth",this._textureSize),s.setInt("uSrcWidth",this._textureSize),s.setInt("uUseMap",o),this._quad.material=s,e.renderList=[this._quad],e.render()}_createCopyMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsWorkBufferRelayout",this._scene,{vertexSource:e?zl:Wl,fragmentSource:e?"\nvar uMapTexSampler : sampler;\nvar uMapTex : texture_2d<f32>;\nvar uSrc0Sampler : sampler;\nvar uSrc0 : texture_2d<f32>;\nvar uSrc1Sampler : sampler;\nvar uSrc1 : texture_2d<f32>;\nvar uSrc2Sampler : sampler;\nvar uSrc2 : texture_2d<f32>;\nvar uSrc3Sampler : sampler;\nvar uSrc3 : texture_2d<f32>;\n\nuniform uDstWidth : i32;\nuniform uSrcWidth : i32;\nuniform uUseMap : i32;\n\n@fragment\nfn main(input : FragmentInputs) -> FragmentOutputs {\n let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y));\n var srcIdx : i32;\n if (uniforms.uUseMap == 1) {\n let m : f32 = textureLoad(uMapTex, p, 0).r;\n if (m < 0.0) {\n discard;\n }\n srcIdx = i32(m + 0.5);\n } else {\n srcIdx = p.y * uniforms.uDstWidth + p.x;\n }\n let s : vec2<i32> = vec2<i32>(srcIdx - (srcIdx / uniforms.uSrcWidth) * uniforms.uSrcWidth, srcIdx / uniforms.uSrcWidth);\n fragmentOutputs.fragData0 = textureLoad(uSrc0, s, 0);\n fragmentOutputs.fragData1 = textureLoad(uSrc1, s, 0);\n fragmentOutputs.fragData2 = textureLoad(uSrc2, s, 0);\n fragmentOutputs.fragData3 = textureLoad(uSrc3, s, 0);\n}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D uMapTex;\nuniform sampler2D uSrc0;\nuniform sampler2D uSrc1;\nuniform sampler2D uSrc2;\nuniform sampler2D uSrc3;\nuniform int uDstWidth;\nuniform int uSrcWidth;\nuniform int uUseMap;\n\nlayout(location = 0) out vec4 glFragData[4];\n\nvoid main() {\n ivec2 p = ivec2(gl_FragCoord.xy);\n int srcIdx;\n if (uUseMap == 1) {\n float m = texelFetch(uMapTex, p, 0).r;\n if (m < 0.0) {\n discard;\n }\n srcIdx = int(m + 0.5);\n } else {\n srcIdx = p.y * uDstWidth + p.x;\n }\n ivec2 s = ivec2(srcIdx - (srcIdx / uSrcWidth) * uSrcWidth, srcIdx / uSrcWidth);\n glFragData[0] = texelFetch(uSrc0, s, 0);\n glFragData[1] = texelFetch(uSrc1, s, 0);\n glFragData[2] = texelFetch(uSrc2, s, 0);\n glFragData[3] = texelFetch(uSrc3, s, 0);\n}\n"},{attributes:["position"],uniforms:["uDstWidth","uSrcWidth","uUseMap"],samplers:["uMapTex","uSrc0","uSrc1","uSrc2","uSrc3"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}readCentersRangeAsync(e,t){return b(this,void 0,void 0,function*(){var n,o;if(this._disposed||t<=0||!this.supportsAsyncCentersReadback)return null;const s=this._textureSize,r=Math.floor(e/s),i=Math.ceil((e+t)/s)-r,a=4*(e-r*s),l=a+4*t,u=this._mrt.textures[0],c=this._scene.getEngine();if(c.isWebGPU){const e=yield u.readPixels(0,0,null,!0,!0,0,r,s,i);if(this._disposed||!e)return null;const t=e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.byteLength/4);return t.length>=l?t.subarray(a,l):null}const d=c,h=d._gl,m=null===(o=null===(n=u.getInternalTexture())||void 0===n?void 0:n._hardwareTexture)||void 0===o?void 0:o.underlyingResource;if(!m)return null;const f=new Float32Array(s*i*4);this._readFbo||(this._readFbo=h.createFramebuffer());const p=d._currentFramebuffer;h.bindFramebuffer(h.FRAMEBUFFER,this._readFbo),h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,h.TEXTURE_2D,m,0),h.readBuffer(h.COLOR_ATTACHMENT0);const _=d._readPixelsAsync(0,r,s,i,h.RGBA,h.FLOAT,f);return h.bindFramebuffer(h.FRAMEBUFFER,p),p||h.readBuffer(h.BACK),_?(yield _,this._disposed||f.length<l?null:f.subarray(a,l)):null})}dispose(){var e,t,n;this._disposed=!0,this._readFbo&&(null===(e=this._scene.getEngine()._gl)||void 0===e||e.deleteFramebuffer(this._readFbo),this._readFbo=null),this._quad.dispose(),this._material.dispose(!0,!1),null===(t=this._copyMaterial)||void 0===t||t.dispose(!0,!1),null===(n=this._relayoutMapTexture)||void 0===n||n.dispose(),this._mrt.dispose()}_createQuad(){const e=new t.Mesh("gsWorkBufferQuad",this._scene),n=new t.VertexData;return n.positions=[-1,-1,0,3,-1,0,-1,3,0],n.indices=[0,1,2],n.applyToMesh(e),this._scene.removeMesh(e),e}_createMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsSogDecode",this._scene,{vertexSource:e?zl:Wl,fragmentSource:e?"\nvar sogMeansLTexSampler : sampler;\nvar sogMeansLTex : texture_2d<f32>;\nvar sogMeansUTexSampler : sampler;\nvar sogMeansUTex : texture_2d<f32>;\nvar sogScalesTexSampler : sampler;\nvar sogScalesTex : texture_2d<f32>;\nvar sogQuatsTexSampler : sampler;\nvar sogQuatsTex : texture_2d<f32>;\nvar sogSh0TexSampler : sampler;\nvar sogSh0Tex : texture_2d<f32>;\nvar sogCodebookTexSampler : sampler;\nvar sogCodebookTex : texture_2d<f32>;\n\nuniform sogMeansMin : vec3<f32>;\nuniform sogMeansMax : vec3<f32>;\nuniform sogScalesMin : vec3<f32>;\nuniform sogScalesMax : vec3<f32>;\nuniform sogSh0Min : vec4<f32>;\nuniform sogSh0Max : vec4<f32>;\nuniform uVersion : i32;\nuniform uOffset : i32;\nuniform uCount : i32;\nuniform uDestWidth : i32;\nuniform uSrcWidth : i32;\n\n@fragment\nfn main(input : FragmentInputs) -> FragmentOutputs {\n let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y));\n let global : i32 = p.y * uniforms.uDestWidth + p.x;\n if (global < uniforms.uOffset || global >= uniforms.uOffset + uniforms.uCount) {\n discard;\n }\n let k : i32 = global - uniforms.uOffset;\n let src : vec2<i32> = vec2<i32>(k - (k / uniforms.uSrcWidth) * uniforms.uSrcWidth, k / uniforms.uSrcWidth);\n\n let mL : vec3<f32> = textureLoad(sogMeansLTex, src, 0).xyz;\n let mU : vec3<f32> = textureLoad(sogMeansUTex, src, 0).xyz;\n let sRaw : vec3<f32> = textureLoad(sogScalesTex, src, 0).xyz;\n let qRaw : vec4<f32> = textureLoad(sogQuatsTex, src, 0);\n let c0 : vec4<f32> = textureLoad(sogSh0Tex, src, 0);\n\n let q16 : vec3<f32> = (mU * 256.0 + mL) * (255.0 / 65535.0);\n let nPos : vec3<f32> = mix(uniforms.sogMeansMin, uniforms.sogMeansMax, q16);\n let center : vec3<f32> = sign(nPos) * (exp(abs(nPos)) - vec3<f32>(1.0));\n\n var splatScale : vec3<f32>;\n if (uniforms.uVersion == 2) {\n let sIdx : vec3<f32> = floor(sRaw * 255.0 + 0.5);\n splatScale.x = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.x), 0), 0).r);\n splatScale.y = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.y), 0), 0).r);\n splatScale.z = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.z), 0), 0).r);\n } else {\n splatScale = exp(mix(uniforms.sogScalesMin, uniforms.sogScalesMax, sRaw));\n }\n\n let invSqrt2 : f32 = 0.70710678118;\n let qabc : vec3<f32> = (qRaw.xyz - vec3<f32>(0.5)) * 2.0 * invSqrt2;\n let qMode : i32 = i32(qRaw.w * 255.0 + 0.5) - 252;\n let qd : f32 = sqrt(max(0.0, 1.0 - dot(qabc, qabc)));\n var quat : vec4<f32>;\n if (qMode == 0) {\n quat = vec4<f32>(qd, qabc.x, qabc.y, qabc.z);\n } else if (qMode == 1) {\n quat = vec4<f32>(qabc.x, qd, qabc.y, qabc.z);\n } else if (qMode == 2) {\n quat = vec4<f32>(qabc.x, qabc.y, qd, qabc.z);\n } else {\n quat = vec4<f32>(qabc.x, qabc.y, qabc.z, qd);\n }\n\n let qw : f32 = quat.x;\n let qx : f32 = quat.y;\n let qy : f32 = quat.z;\n let qz : f32 = quat.w;\n let R : mat3x3<f32> = mat3x3<f32>(\n 1.0 - 2.0 * (qy * qy + qz * qz), 2.0 * (qx * qy + qw * qz), 2.0 * (qx * qz - qw * qy),\n 2.0 * (qx * qy - qw * qz), 1.0 - 2.0 * (qx * qx + qz * qz), 2.0 * (qy * qz + qw * qx),\n 2.0 * (qx * qz + qw * qy), 2.0 * (qy * qz - qw * qx), 1.0 - 2.0 * (qx * qx + qy * qy)\n );\n let S2 : mat3x3<f32> = mat3x3<f32>(\n 4.0 * splatScale.x * splatScale.x, 0.0, 0.0,\n 0.0, 4.0 * splatScale.y * splatScale.y, 0.0,\n 0.0, 0.0, 4.0 * splatScale.z * splatScale.z\n );\n let Sigma : mat3x3<f32> = R * S2 * transpose(R);\n\n let SH_C0 : f32 = 0.28209479177387814;\n var colRgb : vec3<f32>;\n var colA : f32;\n if (uniforms.uVersion == 2) {\n var c3 : vec3<f32>;\n c3.x = textureLoad(sogCodebookTex, vec2<i32>(256 + i32(c0.x * 255.0 + 0.5), 0), 0).r;\n c3.y = textureLoad(sogCodebookTex, vec2<i32>(256 + i32(c0.y * 255.0 + 0.5), 0), 0).r;\n c3.z = textureLoad(sogCodebookTex, vec2<i32>(256 + i32(c0.z * 255.0 + 0.5), 0), 0).r;\n colRgb = vec3<f32>(0.5) + c3 * SH_C0;\n colA = c0.w;\n } else {\n let cLerp : vec4<f32> = mix(uniforms.sogSh0Min, uniforms.sogSh0Max, c0);\n colRgb = vec3<f32>(0.5) + cLerp.xyz * SH_C0;\n colA = 1.0 / (1.0 + exp(-cLerp.w));\n }\n\n fragmentOutputs.fragData0 = vec4<f32>(center, 1.0);\n fragmentOutputs.fragData1 = vec4<f32>(Sigma[0][0], Sigma[0][1], Sigma[0][2], Sigma[1][1]);\n fragmentOutputs.fragData2 = vec4<f32>(Sigma[1][2], Sigma[2][2], 0.0, 0.0);\n fragmentOutputs.fragData3 = vec4<f32>(colRgb, colA);\n}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D sogMeansLTex;\nuniform sampler2D sogMeansUTex;\nuniform sampler2D sogScalesTex;\nuniform sampler2D sogQuatsTex;\nuniform sampler2D sogSh0Tex;\nuniform sampler2D sogCodebookTex;\n\nuniform vec3 sogMeansMin;\nuniform vec3 sogMeansMax;\nuniform vec3 sogScalesMin;\nuniform vec3 sogScalesMax;\nuniform vec4 sogSh0Min;\nuniform vec4 sogSh0Max;\nuniform int uVersion;\nuniform int uOffset;\nuniform int uCount;\nuniform int uDestWidth;\nuniform int uSrcWidth;\n\nlayout(location = 0) out vec4 glFragData[4];\n\nmat3 transposeM(mat3 m) {\n return mat3(m[0][0], m[1][0], m[2][0], m[0][1], m[1][1], m[2][1], m[0][2], m[1][2], m[2][2]);\n}\n\nvoid main() {\n ivec2 p = ivec2(gl_FragCoord.xy);\n int global = p.y * uDestWidth + p.x;\n if (global < uOffset || global >= uOffset + uCount) {\n discard;\n }\n int k = global - uOffset;\n ivec2 src = ivec2(k - (k / uSrcWidth) * uSrcWidth, k / uSrcWidth);\n\n vec3 mL = texelFetch(sogMeansLTex, src, 0).xyz;\n vec3 mU = texelFetch(sogMeansUTex, src, 0).xyz;\n vec3 sRaw = texelFetch(sogScalesTex, src, 0).xyz;\n vec4 qRaw = texelFetch(sogQuatsTex, src, 0);\n vec4 c0 = texelFetch(sogSh0Tex, src, 0);\n\n // Position: q16 = (u<<8)|l normalized; n = lerp(min,max,q16); pos = sign(n)*(exp(|n|)-1)\n vec3 q16 = (mU * 256.0 + mL) * (255.0 / 65535.0);\n vec3 nPos = mix(sogMeansMin, sogMeansMax, q16);\n vec3 center = sign(nPos) * (exp(abs(nPos)) - vec3(1.0));\n\n // Scale (v1: lerp+exp ; v2: codebook lookup)\n vec3 splatScale;\n if (uVersion == 2) {\n vec3 sIdx = floor(sRaw * 255.0 + 0.5);\n splatScale.x = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.x), 0), 0).r);\n splatScale.y = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.y), 0), 0).r);\n splatScale.z = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.z), 0), 0).r);\n } else {\n splatScale = exp(mix(sogScalesMin, sogScalesMax, sRaw));\n }\n\n // Quaternion (largest-omitted, mode in alpha as 252 + omitted-index)\n const float invSqrt2 = 0.70710678118;\n vec3 qabc = (qRaw.xyz - vec3(0.5)) * 2.0 * invSqrt2;\n int qMode = int(qRaw.w * 255.0 + 0.5) - 252;\n float qd = sqrt(max(0.0, 1.0 - dot(qabc, qabc)));\n vec4 quat;\n if (qMode == 0) {\n quat = vec4(qd, qabc.x, qabc.y, qabc.z);\n } else if (qMode == 1) {\n quat = vec4(qabc.x, qd, qabc.y, qabc.z);\n } else if (qMode == 2) {\n quat = vec4(qabc.x, qabc.y, qd, qabc.z);\n } else {\n quat = vec4(qabc.x, qabc.y, qabc.z, qd);\n }\n\n float qw = quat.x, qx = quat.y, qy = quat.z, qz = quat.w;\n mat3 R = mat3(\n 1.0 - 2.0 * (qy * qy + qz * qz), 2.0 * (qx * qy + qw * qz), 2.0 * (qx * qz - qw * qy),\n 2.0 * (qx * qy - qw * qz), 1.0 - 2.0 * (qx * qx + qz * qz), 2.0 * (qy * qz + qw * qx),\n 2.0 * (qx * qz + qw * qy), 2.0 * (qy * qz - qw * qx), 1.0 - 2.0 * (qx * qx + qy * qy)\n );\n mat3 S2 = mat3(\n 4.0 * splatScale.x * splatScale.x, 0.0, 0.0,\n 0.0, 4.0 * splatScale.y * splatScale.y, 0.0,\n 0.0, 0.0, 4.0 * splatScale.z * splatScale.z\n );\n mat3 Sigma = R * S2 * transposeM(R);\n\n // Color (sh0)\n const float SH_C0 = 0.28209479177387814;\n vec3 colRgb;\n float colA;\n if (uVersion == 2) {\n vec3 c3;\n c3.x = texelFetch(sogCodebookTex, ivec2(256 + int(c0.x * 255.0 + 0.5), 0), 0).r;\n c3.y = texelFetch(sogCodebookTex, ivec2(256 + int(c0.y * 255.0 + 0.5), 0), 0).r;\n c3.z = texelFetch(sogCodebookTex, ivec2(256 + int(c0.z * 255.0 + 0.5), 0), 0).r;\n colRgb = vec3(0.5) + c3 * SH_C0;\n colA = c0.w;\n } else {\n vec4 cLerp = mix(sogSh0Min, sogSh0Max, c0);\n colRgb = vec3(0.5) + cLerp.xyz * SH_C0;\n colA = 1.0 / (1.0 + exp(-cLerp.w));\n }\n\n glFragData[0] = vec4(center, 1.0);\n glFragData[1] = vec4(Sigma[0][0], Sigma[0][1], Sigma[0][2], Sigma[1][1]);\n glFragData[2] = vec4(Sigma[1][2], Sigma[2][2], 0.0, 0.0);\n glFragData[3] = vec4(colRgb, colA);\n}\n"},{attributes:["position"],uniforms:["sogMeansMin","sogMeansMax","sogScalesMin","sogScalesMax","sogSh0Min","sogSh0Max","uVersion","uOffset","uCount","uDestWidth","uSrcWidth"],samplers:["sogMeansLTex","sogMeansUTex","sogScalesTex","sogQuatsTex","sogSh0Tex","sogCodebookTex"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_applyPack(e,n){var o,s,r,i,a;const l=this._material,u=e.meansTextureL.getSize().width;l.setTexture("sogMeansLTex",e.meansTextureL),l.setTexture("sogMeansUTex",e.meansTextureU),l.setTexture("sogScalesTex",e.scalesTexture),l.setTexture("sogQuatsTex",e.quatsTexture),l.setTexture("sogSh0Tex",e.sh0Texture),l.setTexture("sogCodebookTex",null!==(o=e.codebookTexture)&&void 0!==o?o:e.sh0Texture),l.setVector3("sogMeansMin",new t.Vector3(e.meansMin[0],e.meansMin[1],e.meansMin[2])),l.setVector3("sogMeansMax",new t.Vector3(e.meansMax[0],e.meansMax[1],e.meansMax[2]));const c=null!==(s=e.scalesMin)&&void 0!==s?s:[0,0,0],d=null!==(r=e.scalesMax)&&void 0!==r?r:[0,0,0];l.setVector3("sogScalesMin",new t.Vector3(c[0],c[1],c[2])),l.setVector3("sogScalesMax",new t.Vector3(d[0],d[1],d[2]));const h=null!==(i=e.sh0Min)&&void 0!==i?i:[0,0,0,0],m=null!==(a=e.sh0Max)&&void 0!==a?a:[0,0,0,0];l.setVector4("sogSh0Min",new t.Vector4(h[0],h[1],h[2],h[3])),l.setVector4("sogSh0Max",new t.Vector4(m[0],m[1],m[2],m[3])),l.setInt("uVersion",e.version),l.setInt("uOffset",n),l.setInt("uCount",e.splatCount),l.setInt("uDestWidth",this._textureSize),l.setInt("uSrcWidth",u)}}class ql{constructor(e){var t,n;this._activeCount=0,this._queue=[],this._pending=new Map,this._groups=new Map,this._disposed=!1,this.maxConcurrent=Math.max(1,null!==(t=null==e?void 0:e.maxConcurrent)&&void 0!==t?t:2),this.maxRetries=Math.max(0,null!==(n=null==e?void 0:e.maxRetries)&&void 0!==n?n:2)}get isIdle(){return 0===this._pending.size}loadFileAsync(e,t){return b(this,void 0,void 0,function*(){if(this._disposed)throw new Error("GaussianSplattingDownloadManager has been disposed.");const n=this._pending.get(e);if(n)return yield n.promise;const o={url:e,groupId:t,settled:!1,cancelled:!1,started:!1,slotReleased:!1};if(o.promise=new Promise((e,t)=>{o.resolve=e,o.reject=t}),this._pending.set(e,o),void 0!==t){let n=this._groups.get(t);n||(n=new Set,this._groups.set(t,n)),n.add(e)}return this._queue.push(o),this._pump(),yield o.promise})}cancel(e){const t=this._pending.get(e);t&&this._abort(t,new Error(`GaussianSplattingDownloadManager: download cancelled (${e}).`))}cancelGroup(e){const t=this._groups.get(e);if(t){for(const e of Array.from(t))this.cancel(e);this._groups.delete(e)}}dispose(){if(!this._disposed){this._disposed=!0,this._queue.length=0;for(const e of Array.from(this._pending.values()))this._abort(e,new Error("GaussianSplattingDownloadManager has been disposed."))}}_abort(e,t){var n,o;if(e.settled)return;e.cancelled=!0;const s=this._queue.indexOf(e);-1!==s&&this._queue.splice(s,1),null===(n=e.request)||void 0===n||n.abort(),null===(o=e.cancelAttempt)||void 0===o||o.call(e,t),this._settle(e,()=>e.reject(t)),e.started&&this._releaseSlot(e)}_settle(e,t){if(!e.settled){if(e.settled=!0,this._pending.delete(e.url),void 0!==e.groupId){const t=this._groups.get(e.groupId);t&&(t.delete(e.url),0===t.size&&this._groups.delete(e.groupId))}t()}}_releaseSlot(e){e.slotReleased||(e.slotReleased=!0,this._activeCount--,this._pump())}_pump(){for(;!this._disposed&&this._activeCount<this.maxConcurrent&&this._queue.length>0;){const e=this._queue.shift();e.settled||(e.started=!0,this._activeCount++,this._runTaskAsync(e).finally(()=>{this._releaseSlot(e)}))}}_runTaskAsync(e){return b(this,void 0,void 0,function*(){let t;for(let n=0;n<=this.maxRetries;n++){if(this._disposed||e.cancelled)return;try{const t=yield this._downloadAttemptAsync(e);return void this._settle(e,()=>e.resolve(t))}catch(n){if(e.cancelAttempt=void 0,this._disposed||e.cancelled)return;t=n}}this._settle(e,()=>e.reject(t))})}_downloadAttemptAsync(e){return b(this,void 0,void 0,function*(){return yield new Promise((n,o)=>{e.cancelAttempt=o,e.request=t.Tools.LoadFile(e.url,e=>n(e),void 0,void 0,!0,(t,n)=>o(n instanceof Error?n:new Error(`GaussianSplattingDownloadManager: failed to load ${e.url}.`)))})})}}class Xl{constructor(){this._offset=0,this._size=0,this._free=!0,this._prev=null,this._next=null,this._prevFree=null,this._nextFree=null,this._bucket=-1}get offset(){return this._offset}get size(){return this._size}}class Yl{constructor(e=0,t=1.1){if(this._headAll=null,this._tailAll=null,this._freeBucketHeads=[],this._pool=[],this._capacity=0,this._usedSize=0,this._freeSize=0,this._freeRegionCount=0,this._growMultiplier=t,e>0){this._capacity=e,this._freeSize=e;const t=this._obtain(0,e,!0);this._headAll=t,this._tailAll=t,this._addToBucket(t)}}get capacity(){return this._capacity}get usedSize(){return this._usedSize}get freeSize(){return this._freeSize}get fragmentation(){return this._freeSize>0?1-1/this._freeRegionCount:0}allocate(e){if(e<=0)return null;const t=this._findFreeBlock(e);if(!t)return null;if(this._usedSize+=e,this._freeSize-=e,t._size===e)return t._free=!1,this._removeFromBucket(t),t;const n=this._obtain(t._offset,e,!1);return t._offset+=e,t._size-=e,this._rebucket(t),this._insertAfterInMainList(n,t._prev),n}free(e){if(!e||e._free)return;e._free=!0,this._usedSize-=e._size,this._freeSize+=e._size;const t=e._prev,n=e._next,o=t&&t._free,s=n&&n._free;o&&s?(t._size+=e._size+n._size,this._removeFromMainList(e),this._removeFromMainList(n),this._removeFromBucket(n),this._release(e),this._release(n),this._rebucket(t)):o?(t._size+=e._size,this._removeFromMainList(e),this._release(e),this._rebucket(t)):s?(e._size+=n._size,this._removeFromMainList(n),this._removeFromBucket(n),this._release(n),this._addToBucket(e)):this._addToBucket(e)}grow(e){if(e<=this._capacity)return;const t=e-this._capacity;if(this._capacity=e,this._freeSize+=t,this._tailAll&&this._tailAll._free)this._tailAll._size+=t,this._rebucket(this._tailAll);else{const e=this._obtain(this._capacity-t,t,!0);this._insertAfterInMainList(e,this._tailAll),this._addToBucket(e)}}defrag(e=0,t=new Set){return t.clear(),0===this._freeRegionCount||(0===e?this._defragFull(t):this._defragIncremental(e,t)),t}updateAllocation(e,t){for(let t=0;t<e.length;t++)this.free(e[t]);for(let e=0;e<t.length;e++){const n=t[e],o=this.allocate(n);if(!o){let o=n;for(let n=e+1;n<t.length;n++)o+=t[n];const s=this._usedSize+o,r=Math.ceil(s*this._growMultiplier);r>this._capacity&&this.grow(r),this.defrag(0);for(let n=e;n<t.length;n++)t[n]=this.allocate(t[n]);return!0}t[e]=o}return!1}_bucketFor(e){return 31-Math.clz32(e)}_addToBucket(e){const t=this._bucketFor(e._size);for(e._bucket=t;t>=this._freeBucketHeads.length;)this._freeBucketHeads.push(null);e._prevFree=null,e._nextFree=this._freeBucketHeads[t],this._freeBucketHeads[t]&&(this._freeBucketHeads[t]._prevFree=e),this._freeBucketHeads[t]=e,this._freeRegionCount++}_removeFromBucket(e){const t=e._bucket;e._prevFree?e._prevFree._nextFree=e._nextFree:this._freeBucketHeads[t]=e._nextFree,e._nextFree&&(e._nextFree._prevFree=e._prevFree),e._prevFree=null,e._nextFree=null,e._bucket=-1,this._freeRegionCount--}_rebucket(e){this._bucketFor(e._size)!==e._bucket&&(this._removeFromBucket(e),this._addToBucket(e))}_obtain(e,t,n){const o=this._pool.length>0?this._pool.pop():new Xl;return o._offset=e,o._size=t,o._free=n,o._prev=null,o._next=null,o._prevFree=null,o._nextFree=null,o._bucket=-1,o}_release(e){e._prev=null,e._next=null,e._prevFree=null,e._nextFree=null,e._bucket=-1,this._pool.push(e)}_insertAfterInMainList(e,t){null===t?(e._prev=null,e._next=this._headAll,this._headAll&&(this._headAll._prev=e),this._headAll=e,this._tailAll||(this._tailAll=e)):(e._prev=t,e._next=t._next,t._next&&(t._next._prev=e),t._next=e,this._tailAll===t&&(this._tailAll=e))}_removeFromMainList(e){e._prev?e._prev._next=e._next:this._headAll=e._next,e._next?e._next._prev=e._prev:this._tailAll=e._prev,e._prev=null,e._next=null}_findFreeBlock(e){const t=this._bucketFor(e),n=this._freeBucketHeads.length;if(t<n){let n=null,o=this._freeBucketHeads[t];for(;o&&!(o._size>=e&&(!n||o._size<n._size)&&(n=o,o._size===e));)o=o._nextFree;if(n)return n}for(let e=t+1;e<n;e++)if(this._freeBucketHeads[e])return this._freeBucketHeads[e];return null}_defragFull(e){for(let e=0;e<this._freeBucketHeads.length;e++){let t=this._freeBucketHeads[e];for(;t;){const e=t._nextFree;this._removeFromMainList(t),t._prevFree=null,t._nextFree=null,t._bucket=-1,this._pool.push(t),t=e}this._freeBucketHeads[e]=null}this._freeRegionCount=0;let t=0,n=this._headAll;for(;n;)n._offset!==t&&(n._offset=t,e.add(n)),t+=n._size,n=n._next;const o=this._capacity-t;if(o>0){const e=this._obtain(t,o,!0);this._insertAfterInMainList(e,this._tailAll),this._addToBucket(e)}}_defragIncremental(e,t){const n=Math.ceil(e/2),o=e-n;for(let e=0;e<n;e++){let e=this._tailAll;for(;e&&e._free;)e=e._prev;if(!e)break;const n=this._findFreeBlock(e._size);if(!n||n._offset>=e._offset)break;this._moveBlock(e,n),t.add(e)}let s=this._headAll;for(let e=0;e<o&&s;){const n=s._next;if(s._free&&n&&!n._free){const o=n,r=s;o._offset=r._offset,r._offset=o._offset+o._size;const i=r._prev,a=o._next;if(o._prev=i,o._next=r,r._prev=o,r._next=a,i?i._next=o:this._headAll=o,a?a._prev=r:this._tailAll=r,r._next&&r._next._free){const e=r._next;r._size+=e._size,this._removeFromMainList(e),this._removeFromBucket(e),this._release(e),this._rebucket(r)}t.add(o),e++,s=r._next}else s=n}}_moveBlock(e,t){const n=e._size,o=t._offset,s=e._prev;this._removeFromMainList(e);const r=this._obtain(e._offset,n,!0);if(this._insertAfterInMainList(r,s),this._addToBucket(r),r._next&&r._next._free){const e=r._next;r._size+=e._size,this._removeFromMainList(e),this._removeFromBucket(e),this._release(e),this._rebucket(r)}if(r._prev&&r._prev._free){const e=r._prev;e._size+=r._size,this._removeFromMainList(r),this._removeFromBucket(r),this._release(r),this._rebucket(e)}if(e._offset=o,t._size===n){const n=t._prev;this._removeFromMainList(t),this._removeFromBucket(t),this._release(t),this._insertAfterInMainList(e,n)}else t._offset+=n,t._size-=n,this._rebucket(t),this._insertAfterInMainList(e,t._prev)}}class Ql{constructor(e,t,n){this._blocks=new Map,this._cooldown=new Map,this._pinned=new Set,this._allocator=new Yl(e),this._cooldownFrames=Math.max(0,t),this._onEvict=n}get capacity(){return this._allocator.capacity}get residentCount(){return this._blocks.size}get freeSize(){return this._allocator.freeSize}has(e){return this._blocks.has(e)}offset(e){var t;return null===(t=this._blocks.get(e))||void 0===t?void 0:t.offset}allocate(e,t){const n=this._blocks.get(e);if(n)return n.offset;let o=this._allocator.allocate(t);return o||(this._evictAllCooled(),o=this._allocator.allocate(t),o)?(this._blocks.set(e,o),o.offset):null}pin(e,t){const n=this.allocate(e,t);return null!==n&&this._pinned.add(e),n}free(e){if(this._pinned.has(e))return;const t=this._blocks.get(e);t&&(this._allocator.free(t),this._blocks.delete(e),this._cooldown.delete(e))}compact(){const e=new Map;for(const[t,n]of Array.from(this._blocks))e.set(t,n.offset);this._allocator.defrag(0);const t=[];for(const[n,o]of Array.from(this._blocks)){const s=e.get(n);s!==o.offset&&t.push({file:n,oldOffset:s,newOffset:o.offset,count:o.size})}return t}getResidentBlocks(){const e=[];for(const[t,n]of Array.from(this._blocks))e.push({file:t,offset:n.offset,count:n.size});return e}scheduleEviction(e){!this._pinned.has(e)&&this._blocks.has(e)&&this._cooldown.set(e,this._cooldownFrames)}cancelEviction(e){this._cooldown.delete(e)}tick(){if(0===this._cooldown.size)return[];const e=[];for(const[t,n]of Array.from(this._cooldown))n<=1?e.push(t):this._cooldown.set(t,n-1);for(const t of e)this._evict(t);return e}dispose(){this._blocks.clear(),this._cooldown.clear(),this._pinned.clear()}_evictAllCooled(){const e=Array.from(this._cooldown.keys());for(const t of e)this._evict(t)}_evict(e){const t=this._blocks.get(e);t&&(this._allocator.free(t),this._blocks.delete(e)),this._cooldown.delete(e),this._onEvict(e)}}const Zl=Math.tan(22.5*Math.PI/180),Jl=new t.Matrix,eu=new t.Vector3,tu=new t.Vector3,nu=new t.Vector3,ou=new t.Vector3(0,0,1),su=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]],ru=2*su.length,iu=[new t.Color4(1,.2,.2,1),new t.Color4(1,.6,.1,1),new t.Color4(1,1,.2,1),new t.Color4(.3,1,.3,1),new t.Color4(.2,1,1,1),new t.Color4(.4,.5,1,1),new t.Color4(.9,.4,1,1),new t.Color4(1,1,1,1)];class au extends t.GaussianSplattingMesh{static IsLODMetadata(e){if("object"!=typeof e||null===e)return!1;const t=e;return"number"==typeof t.lodLevels&&Array.isArray(t.filenames)&&"object"==typeof t.tree&&null!==t.tree}constructor(e,n,o,s,r={}){super(e,null,s,!1),this._leafNodes=[],this._lodBaseDistance=5,this._lodMultiplier=3,this._lodBehindPenalty=1,this._lodRangeMin=0,this._maxDecodesPerFrame=1,this._lodCooldownFrames=10,this._lodUpdateInterval=4,this._lodUpdateDistance=.5,this._maxDetailLod=0,this._frustumCulling=!0,this._frustumPlanes=[new t.Plane(0,0,0,0),new t.Plane(0,0,0,0),new t.Plane(0,0,0,0),new t.Plane(0,0,0,0),new t.Plane(0,0,0,0),new t.Plane(0,0,0,0)],this._cullViewProj=new t.Matrix,this._workBuffer=null,this._useGpuPositionReadback=!1,this._readbackCandidate=!1,this._readbackProbed=!1,this._residency=null,this._fileCounts=new Map,this._fileMeta=new Map,this._decodedFiles=new Set,this._loadingFiles=new Set,this._decodeQueue=[],this._fileRefs=new Map,this._cancelledDecodes=new Set,this._evictionEnabled=!1,this._residentBudget=0,this._evictionCooldownFrames=100,this._decodeGate=Promise.resolve(),this._relayoutOldOffsets=new Map,this._relayoutSrcIndex=null,this._environmentRange=null,this._environmentFiles=null,this._lodObserver=null,this._baseLayerReady=!1,this._framesSinceLodUpdate=0,this._lastLodCamPos=new t.Vector3(1/0,1/0,1/0),this._forceLodUpdate=!1,this._boundsMin=new t.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._boundsMax=new t.Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._debugDisplay=!1,this._debugLodSource="optimal",this._debugMesh=null,this._debugObserver=null,this._debugColorData=null,this._debugSignature=0,this._disposed=!1,this._metadata=n,this._rootUrl=o,this._streamOptions=r;const i=Math.max(0,n.lodLevels-1);this._lodRangeMax=i,void 0!==r.lodBaseDistance&&(this._lodBaseDistance=Math.max(.1,r.lodBaseDistance)),void 0!==r.lodMultiplier&&(this._lodMultiplier=Math.max(1.2,r.lodMultiplier)),void 0!==r.lodBehindPenalty&&(this._lodBehindPenalty=Math.max(1,r.lodBehindPenalty)),void 0!==r.lodRangeMin&&(this._lodRangeMin=Math.max(0,Math.min(r.lodRangeMin,i))),void 0!==r.lodRangeMax&&(this._lodRangeMax=Math.max(this._lodRangeMin,Math.min(r.lodRangeMax,i))),void 0!==r.maxDecodesPerFrame&&(this._maxDecodesPerFrame=Math.max(1,r.maxDecodesPerFrame)),void 0!==r.lodCooldownFrames&&(this._lodCooldownFrames=Math.max(0,r.lodCooldownFrames)),void 0!==r.lodUpdateInterval&&(this._lodUpdateInterval=Math.max(1,r.lodUpdateInterval)),void 0!==r.lodUpdateDistance&&(this._lodUpdateDistance=Math.max(0,r.lodUpdateDistance)),void 0!==r.maxDetailLod&&(this._maxDetailLod=Math.max(0,Math.floor(r.maxDetailLod))),void 0!==r.frustumCulling&&(this._frustumCulling=r.frustumCulling),r.debugLodSource&&(this._debugLodSource=r.debugLodSource),void 0!==r.evictionCooldownFrames&&(this._evictionCooldownFrames=Math.max(0,Math.floor(r.evictionCooldownFrames)));let a=0;if(void 0!==r.maxResidentSplats&&r.maxResidentSplats>0&&(a=Math.floor(r.maxResidentSplats)),void 0!==r.memoryBudgetMb&&r.memoryBudgetMb>0){const e=Math.floor(1024*r.memoryBudgetMb*1024/84);a=a>0?Math.min(a,e):e}this._residentBudget=a,this._downloadManager=new ql({maxConcurrent:r.maxConcurrentDownloads,maxRetries:r.maxDownloadRetries}),this.scaling.y*=-1,this.rotation.x=-Math.PI/2,this._collectLodEntries(n.tree),r.debugDisplay&&(this.debugDisplay=!0),this._streamAllAsync().catch(e=>{var n;t.Logger.Error("GaussianSplattingStream: streaming failed: "+(null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e))})}getClassName(){return"GaussianSplattingStream"}whenSettledAsync(){return b(this,arguments,void 0,function*(e=3){if(this._disposed)return;this._forceLodUpdate=!0;const t=Math.max(1,e),n=this._scene;let o=0;const s=()=>this._isLoadingIdle()&&this._isDepthSortSettled?++o>=t:(o=0,!1);if(n.getEngine().activeRenderLoops.length>0)return void(yield new Promise(e=>{let t=null;t=n.onAfterRenderObservable.add(()=>{(this._disposed||s())&&(t&&(n.onAfterRenderObservable.remove(t),t=null),e())})}));const r=n.getEngine(),i=globalThis.requestAnimationFrame;for(;!this._disposed;){if(r.beginFrame(),n.render(),r.endFrame(),s())return;yield new Promise(e=>{"function"==typeof i?i(()=>e()):setTimeout(e,16)})}})}_isLoadingIdle(){return this._baseLayerReady&&0===this._decodeQueue.length&&0===this._loadingFiles.size&&this._downloadManager.isIdle}get maxDetailLod(){return this._maxDetailLod}set maxDetailLod(e){const t=Math.max(0,Math.floor(e));this._maxDetailLod!==t&&(this._maxDetailLod=t,this._forceLodUpdate=!0)}get maxLodLevel(){return Math.max(0,this._metadata.lodLevels-1)}get frustumCulling(){return this._frustumCulling}set frustumCulling(e){this._frustumCulling!==e&&(this._frustumCulling=e,this._forceLodUpdate=!0)}get debugDisplay(){return this._debugDisplay}set debugDisplay(e){this._debugDisplay!==e&&(this._debugDisplay=e,e?this._refreshDebugDisplay():this._clearDebugDisplay())}get debugLodSource(){return this._debugLodSource}set debugLodSource(e){this._debugLodSource!==e&&(this._debugLodSource=e,this._debugDisplay&&this._refreshDebugDisplay())}dispose(e){var t,n;this._disposed=!0,this._lodObserver&&(this._scene.onBeforeRenderObservable.remove(this._lodObserver),this._lodObserver=null),this._clearDebugDisplay(),this._downloadManager.dispose(),null===(t=this._residency)||void 0===t||t.dispose(),this._residency=null,null===(n=this._workBuffer)||void 0===n||n.dispose(),this._workBuffer=null,super.dispose(e)}evaluateOptimalLods(e=this._scene.activeCamera){if(!e||0===this._leafNodes.length)return;const n=Math.max(0,this._metadata.lodLevels-1),o=this._lodBaseDistance,s=this._lodMultiplier,r=this._lodBehindPenalty,i=this._lodRangeMin,a=this._lodRangeMax,l=this._scene.getEngine().getAspectRatio(e)||1;let u=Math.tan(.5*e.fov);e.fovMode===t.Camera.FOVMODE_HORIZONTAL_FIXED&&(u/=l);const c=u*l,d=Math.min(u,c)/Zl;this.computeWorldMatrix(!1).invertToRef(Jl);const h=t.Vector3.TransformCoordinatesToRef(e.globalPosition,Jl,eu),m=h.x,f=h.y,p=h.z;let _=0,g=0,y=0;if(r>1){e.getDirectionToRef(ou,nu);const n=t.Vector3.TransformNormalToRef(nu,Jl,tu);n.normalize(),_=n.x,g=n.y,y=n.z}for(const e of this._leafNodes){const t=e.bound.min,l=e.bound.max,u=(m<t[0]?t[0]:m>l[0]?l[0]:m)-m,c=(f<t[1]?t[1]:f>l[1]?l[1]:f)-f,h=(p<t[2]?t[2]:p>l[2]?l[2]:p)-p,v=Math.sqrt(u*u+c*c+h*h);let b=v;if(r>1&&v>.01){const e=(_*u+g*c+y*h)/v;e<0&&(b=v*(1+-e*(r-1)))}const x=b*d;let T;if(0===n||x<o)T=0;else for(T=n;T>1&&x<o*Math.pow(s,T-1);)T--;T<i?T=i:T>a&&(T=a),this._frustumCulling&&!1===e.inFrustum&&(T=a),e.optimalLod=T}}_displayedLodLevel(e){var t,n,o;return"optimal"===this._debugLodSource?null!==(n=null!==(t=e.optimalLod)&&void 0!==t?t:e.activeLod)&&void 0!==n?n:0:null!==(o=e.activeLod)&&void 0!==o?o:0}_refreshDebugDisplay(){"optimal"===this._debugLodSource&&this.evaluateOptimalLods(),this._buildDebugMesh();const e=this._debugDisplay;e&&!this._debugObserver?this._debugObserver=this._scene.onBeforeRenderObservable.add(()=>this._onDebugFrame()):!e&&this._debugObserver&&(this._scene.onBeforeRenderObservable.remove(this._debugObserver),this._debugObserver=null)}_onDebugFrame(){"optimal"===this._debugLodSource&&this.evaluateOptimalLods(),this._computeDebugSignature()!==this._debugSignature&&this._updateDebugColors()}_buildDebugMesh(){this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null),this._debugColorData=null;const e=[],n=[];for(const o of this._leafNodes){const s=iu[this._displayedLodLevel(o)%iu.length],r=o.bound.min,i=o.bound.max,a=[new t.Vector3(r[0],r[1],r[2]),new t.Vector3(i[0],r[1],r[2]),new t.Vector3(i[0],i[1],r[2]),new t.Vector3(r[0],i[1],r[2]),new t.Vector3(r[0],r[1],i[2]),new t.Vector3(i[0],r[1],i[2]),new t.Vector3(i[0],i[1],i[2]),new t.Vector3(r[0],i[1],i[2])];for(const t of su)e.push([a[t[0]],a[t[1]]]),n.push([s,s])}if(this._debugSignature=this._computeDebugSignature(),0===e.length)return;const o=t.CreateLineSystem(this.name+"_lodDebug",{lines:e,colors:n,updatable:!0,useVertexAlpha:!1},this._scene);o.parent=this,o.isPickable=!1,o.doNotSerialize=!0,o.reservedDataStore={hidden:!0},this._debugMesh=o,this._debugColorData=new Float32Array(this._leafNodes.length*ru*4)}_updateDebugColors(){if(!this._debugMesh||!this._debugColorData)return;const e=this._debugColorData;let n=0;for(const t of this._leafNodes){const o=iu[this._displayedLodLevel(t)%iu.length];for(let t=0;t<ru;t++)e[n++]=o.r,e[n++]=o.g,e[n++]=o.b,e[n++]=o.a}this._debugMesh.updateVerticesData(t.VertexBuffer.ColorKind,e),this._debugSignature=this._computeDebugSignature()}_computeDebugSignature(){let e=0;for(const t of this._leafNodes)e=31*e+this._displayedLodLevel(t)|0;return e}_clearDebugDisplay(){this._debugObserver&&(this._scene.onBeforeRenderObservable.remove(this._debugObserver),this._debugObserver=null),this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null),this._debugColorData=null,this._debugSignature=0}_collectLodEntries(e){if(e.children){for(const t of e.children)this._collectLodEntries(t);return}if(!e.lods)return;const n=[];for(const t of Object.keys(e.lods)){const o=Number(t),s=e.lods[t];Number.isFinite(o)&&s&&s.count>0&&n.push(o)}0!==n.length&&(n.sort((e,t)=>e-t),e.availableLevels=n,e.baseLod=n[n.length-1],e.activeLod=void 0,e.lodCooldown=0,e.inFrustum=!0,e.cullBounds=new t.BoundingInfo(t.Vector3.FromArray(e.bound.min),t.Vector3.FromArray(e.bound.max)),this._leafNodes.push(e))}_streamAllAsync(){return b(this,void 0,void 0,function*(){const e=this._collectAllFileIds(),n=yield this._gatherCountsAsync(e);if(this._disposed)return;let o=1;n>0&&(o+=n);for(const t of e){const e=this._fileCounts.get(t);void 0!==e&&e>0&&(o+=e)}if(o<=1)return;this._evictionEnabled=this._residentBudget>0&&this._residentBudget<o;const s=this._evictionEnabled?Math.max(this._residentBudget,1):o;if(this._residency=new Ql(s,this._evictionCooldownFrames,e=>this._onFileEvicted(e)),this._residency.pin(-2,1),n>0){const e=this._residency.pin(-1,n);null!==e?this._environmentRange={offset:e,count:n}:(t.Logger.Warn("GaussianSplattingStream: environment does not fit the memory budget; skipping it."),this._environmentFiles=null)}this._workBuffer=new jl(this._scene,s),this._readbackCandidate=this._workBuffer.supportsAsyncCentersReadback;const r=new Float32Array(4*s),i=this._workBuffer.textures;this._setExternalWorkBuffer(i[0],i[1],i[2],i[3],r,s),this.setSplatIndexRanges([]),this.setEnabled(!0),this._environmentRange&&this._environmentFiles&&(yield this._decodeEnvironmentAsync()),this._environmentFiles=null;const a=new Set;for(const e of this._leafNodes){const t=e.lods[String(e.baseLod)];t&&this._fileCounts.has(t.file)&&a.add(t.file)}for(const e of Array.from(a)){if(this._disposed)return;yield this._decodeFileAsync(e)}this._disposed||(this._baseLayerReady=!0,this._lodObserver||(this._lodObserver=this._scene.onBeforeRenderObservable.add(()=>this._onLodFrame())))})}_collectAllFileIds(){const e=new Set;for(const t of this._leafNodes)for(const n of t.availableLevels){const o=t.lods[String(n)];o&&e.add(o.file)}return Array.from(e).sort((e,t)=>e-t)}_gatherCountsAsync(e){return b(this,void 0,void 0,function*(){var n;let o=0;if(this._metadata.environment)try{const e=this._rootUrl+this._metadata.environment,t=yield this._downloadManager.loadFileAsync(e),n=yield this._unzipAsync(new Uint8Array(t)),s=n.get("meta.json");if(s){const e=JSON.parse((new TextDecoder).decode(s));o=au._GetSplatCount(e),this._environmentFiles=n}}catch(e){t.Logger.Warn("GaussianSplattingStream: failed to load environment: "+(null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e))}return yield Promise.all(e.map(e=>b(this,void 0,void 0,function*(){var n;const o=this._metadata.filenames[e];if(o)try{const t=this._rootUrl+o,n=t.substring(0,t.lastIndexOf("/")+1),s=yield this._downloadManager.loadFileAsync(t),r=JSON.parse((new TextDecoder).decode(new Uint8Array(s)));this._fileCounts.set(e,au._GetSplatCount(r)),this._fileMeta.set(e,{sogData:r,subRootUrl:n})}catch(e){t.Logger.Warn(`GaussianSplattingStream: failed to load metadata for ${o}: ${null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e}`)}else t.Logger.Warn(`GaussianSplattingStream: missing filename for file index ${e}.`)}))),o})}_enqueueDecode(e){this._decodedFiles.has(e)||this._loadingFiles.has(e)||!this._fileMeta.has(e)||-1===this._decodeQueue.indexOf(e)&&this._decodeQueue.push(e)}_pumpDecodeQueue(){let e=0;for(;this._decodeQueue.length>0&&e<this._maxDecodesPerFrame;){const n=this._decodeQueue.shift();this._decodedFiles.has(n)||this._loadingFiles.has(n)||(e++,this._decodeFileAsync(n).catch(e=>{var n;t.Logger.Warn("GaussianSplattingStream: decode failed: "+(null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e))}))}}_applyPositions(e,t,n){this._splatPositions.set(e,4*t),this._updateBounds(e,n),this._postWorkerPositionsRange(t,n)}_probeReadbackAsync(e,n,o){return b(this,void 0,void 0,function*(){if(this._readbackProbed=!0,!this._workBuffer)return;const s=Math.min(n,1024);let r=!1;try{const t=yield this._workBuffer.readCentersRangeAsync(e,s);if(this._disposed)return;if(t&&t.length>=4*s){r=!0;for(let e=0;e<s&&r;e++)for(let n=0;n<3;n++){const s=t[4*e+n],i=o[4*e+n];if(Math.abs(s-i)>.01*(1+Math.abs(i))){r=!1;break}}}}catch(e){r=!1}this._useGpuPositionReadback=r,t.Logger.Log(r?"GaussianSplattingStream: GPU position readback validated; streamed LOD positions are read back from the GPU.":"GaussianSplattingStream: GPU position readback unavailable; decoding LOD positions on the CPU.")})}_applyDecodedPositionsAsync(e,t,n){return b(this,void 0,void 0,function*(){if(this._useGpuPositionReadback&&this._workBuffer){const e=yield this._workBuffer.readCentersRangeAsync(t,n);if(this._disposed)return!1;if(e&&this._splatPositions)return this._applyPositions(e,t,n),!0}const o=e.positions.length>=4*n?e.positions.subarray(0,4*n):null;return!(!o||!this._splatPositions||(this._applyPositions(o,t,n),!this._readbackProbed&&this._readbackCandidate&&(yield this._probeReadbackAsync(t,n,o)),0))})}_decodeEnvironmentAsync(){return b(this,void 0,void 0,function*(){var e;if(!this._environmentRange||!this._environmentFiles||!this._workBuffer)return;const n=this._environmentRange;try{const e=(yield $l(this._environmentFiles,"",this._scene,!this._useGpuPositionReadback,this._downloadManager)).sogTextures;if(!e)return;try{if(this._disposed||!this._workBuffer)return;if(yield this._workBuffer.decodeAsync(e,n.offset),this._disposed)return;if(yield this._applyDecodedPositionsAsync(e,n.offset,n.count),this._disposed)return;this._refreshActiveRanges()}finally{au._DisposePack(e)}}catch(n){t.Logger.Warn("GaussianSplattingStream: failed to decode environment: "+(null!==(e=null==n?void 0:n.message)&&void 0!==e?e:n))}})}_decodeFileAsync(e){return b(this,void 0,void 0,function*(){if(this._decodedFiles.has(e)||this._loadingFiles.has(e)||!this._residency)return;const n=this._fileMeta.get(e),o=this._fileCounts.get(e);if(!n||void 0===o)return;this._loadingFiles.add(e),this._cancelledDecodes.delete(e);let s=!1;try{const r=(yield $l(n.sogData,n.subRootUrl,this._scene,!this._useGpuPositionReadback,this._downloadManager,e)).sogTextures;if(!r)return;const i=yield this._acquireDecodeGateAsync();try{if(this._disposed||!this._workBuffer||this._cancelledDecodes.has(e))return;let n=this._residency.allocate(e,o);if(null===n&&(n=yield this._relayoutAndAllocateAsync(e,o)),null===n)return void(this._cancelledDecodes.has(e)||t.Logger.Warn(`GaussianSplattingStream: resident memory budget full; skipping LOD file ${e}.`));if(s=!0,this._disposed||!this._workBuffer||this._cancelledDecodes.has(e))return;if(yield this._workBuffer.decodeAsync(r,n),this._disposed||this._cancelledDecodes.has(e))return;if(yield this._applyDecodedPositionsAsync(r,n,o),this._disposed)return;this._decodedFiles.add(e),this._applyDesiredLods()&&this._refreshActiveRanges()}finally{au._DisposePack(r),i()}}catch(t){if(!this._cancelledDecodes.has(e))throw t}finally{s&&!this._decodedFiles.has(e)&&this._residency.free(e),this._loadingFiles.delete(e),this._cancelledDecodes.delete(e)}})}_acquireDecodeGateAsync(){return b(this,void 0,void 0,function*(){const e=this._decodeGate;let t;return this._decodeGate=new Promise(e=>{t=e}),yield e,t})}_relayoutAndAllocateAsync(e,t){return b(this,void 0,void 0,function*(){return this._residency&&this._workBuffer?this._residency.freeSize<t?null:yield new Promise(n=>{const o=()=>{!this._disposed&&this._residency&&this._workBuffer&&!this._cancelledDecodes.has(e)?this._workBuffer.isRelayoutReady()?(this._performRelayout(),n(this._residency.allocate(e,t))):this._scene.onBeforeRenderObservable.addOnce(o):n(null)};this._scene.onBeforeRenderObservable.addOnce(o)}):null})}_performRelayout(){if(!this._residency||!this._workBuffer||!this._splatPositions)return;const e=this._relayoutOldOffsets;e.clear();for(const t of this._residency.getResidentBlocks())e.set(t.file,t.offset);if(0===this._residency.compact().length)return;const t=this._residency.capacity;this._relayoutSrcIndex&&this._relayoutSrcIndex.length===t||(this._relayoutSrcIndex=new Float32Array(t));const n=this._relayoutSrcIndex;n.fill(-1);const o=this._residency.getResidentBlocks();for(const t of o){const o=e.get(t.file);for(let e=0;e<t.count;e++)n[t.offset+e]=o+e}this._workBuffer.relayoutSync(n);const s=this._splatPositions;o.sort((e,t)=>e.offset-t.offset);for(const t of o){const n=e.get(t.file);n!==t.offset&&s.copyWithin(4*t.offset,4*n,4*(n+t.count))}if(this._environmentRange){const e=this._residency.offset(-1);void 0!==e&&(this._environmentRange.offset=e)}this._notifyWorkerNewData(),this._refreshActiveRanges()}_onFileEvicted(e){this._decodedFiles.delete(e)}_cappedLevelForNode(e,t){const n=e.availableLevels,o=this._maxDetailLod;let s=-1,r=Number.POSITIVE_INFINITY;for(const e of n){if(e<o)continue;const n=Math.abs(e-t);n<r&&(s=e,r=n)}return s<0?e.baseLod:s}_computeTargetLevels(){var e;for(const t of this._leafNodes){const n=null!==(e=t.optimalLod)&&void 0!==e?e:t.baseLod;t.targetLevel=this._cappedLevelForNode(t,n)}}_applyDesiredLods(){var e;let t=!1;for(const n of this._leafNodes){if(n.lodCooldown&&n.lodCooldown>0)continue;const o=null!==(e=n.targetLevel)&&void 0!==e?e:n.baseLod;let s;if(o!==n.activeLod){const e=n.lods[String(o)];e&&(this._decodedFiles.has(e.file)?(this._switchActiveFile(n,e.file),n.activeLod=o,n.lodCooldown=this._lodCooldownFrames,t=!0):s=e.file)}n.pendingFile!==s&&(void 0!==n.pendingFile&&this._releaseFileRef(n.pendingFile),void 0!==s&&this._acquirePendingFile(s),n.pendingFile=s)}return t}_switchActiveFile(e,t){e.activeFile!==t&&(void 0!==e.activeFile&&this._releaseFileRef(e.activeFile),this._acquireFileRef(t),e.activeFile=t)}_acquireFileRef(e){var t,n;const o=(null!==(t=this._fileRefs.get(e))&&void 0!==t?t:0)+1;this._fileRefs.set(e,o),1===o&&(null===(n=this._residency)||void 0===n||n.cancelEviction(e))}_acquirePendingFile(e){this._acquireFileRef(e),this._enqueueDecode(e)}_releaseFileRef(e){var t,n;const o=(null!==(t=this._fileRefs.get(e))&&void 0!==t?t:0)-1;if(o>0)return void this._fileRefs.set(e,o);if(this._fileRefs.delete(e),this._decodedFiles.has(e))return void(this._evictionEnabled&&(null===(n=this._residency)||void 0===n||n.scheduleEviction(e)));const s=this._decodeQueue.indexOf(e);-1!==s&&this._decodeQueue.splice(s,1),this._loadingFiles.has(e)&&(this._cancelledDecodes.add(e),this._downloadManager.cancelGroup(e))}_onLodFrame(){var e;if(this._disposed||!this._baseLayerReady)return;for(const e of this._leafNodes)e.lodCooldown&&e.lodCooldown>0&&e.lodCooldown--;this._evictionEnabled&&(null===(e=this._residency)||void 0===e||e.tick()),this._pumpDecodeQueue();const n=this._updateNodeFrustum();let o=this._forceLodUpdate||n;if(!o&&++this._framesSinceLodUpdate>=this._lodUpdateInterval){const e=this._scene.activeCamera,n=this._lodUpdateDistance;(!e||t.Vector3.DistanceSquared(e.globalPosition,this._lastLodCamPos)>=n*n)&&(e&&this._lastLodCamPos.copyFrom(e.globalPosition),o=!0)}o&&(this._forceLodUpdate=!1,this._framesSinceLodUpdate=0,this.evaluateOptimalLods(this._scene.activeCamera),this._computeTargetLevels(),this._applyDesiredLods()&&this._refreshActiveRanges())}_updateNodeFrustum(){const e=this._scene.activeCamera;let n=!1;if(!this._frustumCulling||!e){for(const e of this._leafNodes)!1===e.inFrustum&&(e.inFrustum=!0,n=!0);return n}const o=this.computeWorldMatrix(!1);e.getViewMatrix().multiplyToRef(e.getProjectionMatrix(),this._cullViewProj),t.Frustum.GetPlanesToRef(this._cullViewProj,this._frustumPlanes);for(const e of this._leafNodes){e.cullBounds.update(o);const t=e.cullBounds.isInFrustum(this._frustumPlanes);t!==e.inFrustum&&(e.inFrustum=t,n=!0)}return n}static _GetSplatCount(e){var t;return null!==(t=e.count)&&void 0!==t?t:Array.isArray(e.means.shape)?e.means.shape[0]:0}static _DisposePack(e){var t,n,o;e.meansTextureL.dispose(),e.meansTextureU.dispose(),e.scalesTexture.dispose(),e.quatsTexture.dispose(),e.sh0Texture.dispose(),null===(t=e.shCentroidsTexture)||void 0===t||t.dispose(),null===(n=e.shLabelsTexture)||void 0===n||n.dispose(),null===(o=e.codebookTexture)||void 0===o||o.dispose()}_updateBounds(e,n){const o=this._boundsMin,s=this._boundsMax;for(let t=0;t<n;t++){const n=e[4*t+0],r=e[4*t+1],i=e[4*t+2];o.minimizeInPlaceFromFloats(n,r,i),s.maximizeInPlaceFromFloats(n,r,i)}this.setBoundingInfo(new t.BoundingInfo(o,s))}_refreshActiveRanges(){var e;const t=[];this._environmentRange&&t.push({offset:this._environmentRange.offset,count:this._environmentRange.count});for(const n of this._leafNodes){if(void 0===n.activeLod)continue;const o=n.lods[String(n.activeLod)];if(!o)continue;const s=null===(e=this._residency)||void 0===e?void 0:e.offset(o.file);void 0!==s&&t.push({offset:s+o.offset,count:o.count})}this.setSplatIndexRanges(au._CoalesceRanges(t))}static _CoalesceRanges(e){if(e.length<=1)return e;const t=e.slice().sort((e,t)=>e.offset-t.offset),n=[{offset:t[0].offset,count:t[0].count}];for(let e=1;e<t.length;e++){const o=n[n.length-1],s=t[e],r=o.offset+o.count;if(s.offset<=r){const e=Math.max(r,s.offset+s.count);o.count=e-o.offset}else n.push({offset:s.offset,count:s.count})}return n}_unzipAsync(e){return b(this,void 0,void 0,function*(){var n;let o=this._streamOptions.fflate;o||(void 0===window.fflate&&(yield t.Tools.LoadScriptAsync(null!==(n=this._streamOptions.deflateURL)&&void 0!==n?n:"https://unpkg.com/fflate/umd/index.js")),o=window.fflate);const s=o.unzipSync(e),r=new Map;for(const[e,t]of Object.entries(s))r.set(e,t);return r})}}const lu=.28209479177387814;let uu=null,cu=null;class du{constructor(e={}){this.name=kl.name,this._assetContainer=null,this.extensions=kl.extensions,this._loadingOptions=Object.assign(Object.assign({},du._DefaultLoadingOptions),e)}createPlugin(e){return new du(e[kl.name])}importMeshAsync(e,t,n,o,s,r){return b(this,void 0,void 0,function*(){const s=this._tryCreateLODStream(t,n,o);return s?{meshes:[s],particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}:yield this._parseAsync(e,t,n,o).then(e=>({meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))})}_tryCreateLODStream(e,t,n){if("string"!=typeof t)return null;let o;try{o=JSON.parse(t)}catch(e){return null}if(!au.IsLODMetadata(o))return null;const s=e._blockEntityCollection;e._blockEntityCollection=!!this._assetContainer;try{const t=new au("GaussianSplattingStream",o,n,e,{deflateURL:this._loadingOptions.deflateURL,fflate:this._loadingOptions.fflate});return t._parentContainer=this._assetContainer,t}finally{e._blockEntityCollection=s}}static _BuildPointCloud(e,n){if(!n.byteLength)return!1;const o=new Uint8Array(n),s=new Float32Array(n),r=o.length/32;return e.addPoints(r,function(e,n){const r=s[8*n+0],i=s[8*n+1],a=s[8*n+2];e.position=new t.Vector3(r,i,a);const l=o[32*n+24+0]/255,u=o[32*n+24+1]/255,c=o[32*n+24+2]/255;e.color=new t.Color4(l,u,c,1)}),!0}static _BuildMesh(e,n){const o=new t.Mesh("PLYMesh",e),s=new Uint8Array(n.data),r=new Float32Array(n.data),i=s.length/32,a=[],l=new t.VertexData;for(let e=0;e<i;e++){const t=r[8*e+0],n=r[8*e+1],o=r[8*e+2];a.push(t,n,o)}if(n.hasVertexColors){const e=new Float32Array(4*i);for(let t=0;t<i;t++){const n=s[32*t+24+0]/255,o=s[32*t+24+1]/255,r=s[32*t+24+2]/255;e[4*t+0]=n,e[4*t+1]=o,e[4*t+2]=r,e[4*t+3]=1}l.colors=e}return l.positions=a,l.indices=n.faces,l.applyToMesh(o),o}_unzipWithFFlateAsync(e){return b(this,void 0,void 0,function*(){var n;let o=this._loadingOptions.fflate;o||(void 0===window.fflate&&(yield t.Tools.LoadScriptAsync(null!==(n=this._loadingOptions.deflateURL)&&void 0!==n?n:"https://unpkg.com/fflate/umd/index.js")),o=window.fflate);const{unzipSync:s}=o,r=s(e),i=new Map;for(const[e,t]of Object.entries(r))i.set(e,t);return i})}_parseAsync(e,n,o,s){const r=[],i=e=>{var o;n._blockEntityCollection=!!this._assetContainer;const s=null!==(o=this._loadingOptions.gaussianSplattingMesh)&&void 0!==o?o:new t.GaussianSplattingMesh("GaussianSplatting",null,n,this._loadingOptions.keepInRam,this._loadingOptions.needsRotationScaleTextures);s._parentContainer=this._assetContainer,r.push(s),e.sogTextures?s.setSogTextureData(e.sogTextures):s.updateData(e.data,e.sh,{flipY:!1},void 0,e.shDegree),s.scaling.y*=-1,s.computeWorldMatrix(!0),n._blockEntityCollection=!1},a=n.getEngine();let l=this._loadingOptions.useSogTextures;l&&!a.isWebGPU&&a.version<2&&(t.Logger.Warn("SPLATFileLoader: useSogTextures requires WebGL2 or WebGPU. Falling back to CPU path."),l=!1);const u=l?$l:Vl;if("string"==typeof o){const e=JSON.parse(o);if(e&&e.means&&e.scales&&e.quats&&e.sh0)return new Promise((t,o)=>{u(e,s,n).then(e=>{i(e),t(r)}).catch(e=>{o(new Error("Failed to parse SOG data.",{cause:e}))})})}const c=o instanceof ArrayBuffer?new Uint8Array(o):o;if(80===c[0]&&75===c[1])return new Promise((e,t)=>{this._unzipWithFFlateAsync(c).then(o=>{u(o,s,n).then(t=>{i(t),e(r)}).catch(e=>{t(new Error("Failed to parse SOG zip data.",{cause:e}))})})});const d=e=>{du._ConvertPLYToSplat(o).then(o=>b(this,void 0,void 0,function*(){var s;switch(n._blockEntityCollection=!!this._assetContainer,o.mode){case 0:{const e=null!==(s=this._loadingOptions.gaussianSplattingMesh)&&void 0!==s?s:new t.GaussianSplattingMesh("GaussianSplatting",null,n,this._loadingOptions.keepInRam,this._loadingOptions.needsRotationScaleTextures);switch(e._parentContainer=this._assetContainer,r.push(e),e.updateData(o.data,o.sh,{flipY:!1},void 0,o.shDegree),e.scaling.y*=-1,"RightHanded"===o.chirality&&(e.scaling.y*=-1),o.upAxis){case"X":e.rotation=new t.Vector3(0,0,Math.PI/2);break;case"Y":e.rotation=new t.Vector3(0,0,Math.PI);break;case"Z":e.rotation=new t.Vector3(-Math.PI/2,Math.PI,0)}e.computeWorldMatrix(!0)}break;case 1:{const e=new t.PointsCloudSystem("PointCloud",1,n);du._BuildPointCloud(e,o.data)?yield e.buildMeshAsync().then(e=>{r.push(e)}):e.dispose()}break;case 2:if(!o.faces)throw new Error("PLY mesh doesn't contain face informations.");r.push(du._BuildMesh(n,o));break;default:throw new Error("Unsupported Splat mode")}n._blockEntityCollection=!1,this.applyAutoCameraLimits(o,n),e(r)}))},h=31===c[0]&&139===c[1],m=78===c[0]&&71===c[1]&&83===c[2]&&80===c[3];if(!h&&!m)return new Promise(e=>{d(e)});const f=(e,o)=>{var s;n._blockEntityCollection=!!this._assetContainer;const i=null!==(s=this._loadingOptions.gaussianSplattingMesh)&&void 0!==s?s:new t.GaussianSplattingMesh("GaussianSplatting",null,n,this._loadingOptions.keepInRam,this._loadingOptions.needsRotationScaleTextures);if(e.trainedWithAntialiasing){const e=i.material;e.kernelSize=.1,e.compensation=!0}i._parentContainer=this._assetContainer,r.push(i),i.updateData(e.data,e.sh,{flipY:!1},void 0,e.shDegree),this._loadingOptions.flipY||(i.scaling.y*=-1,i.computeWorldMatrix(!0)),n._blockEntityCollection=!1,this.applyAutoCameraLimits(e,n),o(r)};if(this._loadingOptions.spzLibraryUrl)return function(e){return b(this,void 0,void 0,function*(){if(uu&&cu===e)return yield uu;const n=t._LoadScriptModuleAsync(`import createSpzModule from '${e}';\n const module = await createSpzModule();\n const returnedValue = module;`);return cu=e,uu=n,yield n})}(this._loadingOptions.spzLibraryUrl).then(e=>function(e,n){return b(this,void 0,void 0,function*(){return yield t.runCoroutineAsync(function*(e,n,o=!1){const s=e.numPoints,r=new ArrayBuffer(32*s),i=new Float32Array(r),a=new Uint8Array(r),l=e.positions,u=e.scales,c=e.colors,d=e.alphas,h=e.rotations;let m=null;const f=e.shDegree;let p,_,g=null,y=0,v=null,b=null,x=null;if(f>0&&e.sh.length>0){y=3*((f+1)*(f+1)-1);const o=Math.ceil(y/16),r=n.getEngine().getCaps().maxTextureSize,i=Math.ceil(s/r);m=t.AllocateShBuffers(o,i*r*4*4),v=new Int32Array(o),b=new Int32Array(o);for(let e=0;e<o;e++)v[e]=16*e,b[e]=Math.min(16*(e+1),y);x=m,g=e.sh}for(let e=0;e<s;e++){const t=8*e,n=32*e,s=3*e,r=4*e;i[t+0]=l[s+0],i[t+1]=l[s+1],i[t+2]=l[s+2],i[t+3]=Math.exp(u[s+0]),i[t+4]=Math.exp(u[s+1]),i[t+5]=Math.exp(u[s+2]);const m=255*(.5+lu*c[s+0]),f=255*(.5+lu*c[s+1]),p=255*(.5+lu*c[s+2]);a[n+24]=m<=0?0:m>=255?255:m+.5|0,a[n+25]=f<=0?0:f>=255?255:f+.5|0,a[n+26]=p<=0?0:p>=255?255:p+.5|0,a[n+27]=1/(1+Math.exp(-d[e]))*255+.5|0;const _=127.5*h[r+3]+127.5,T=127.5*h[r+0]+127.5,A=127.5*h[r+1]+127.5,M=127.5*h[r+2]+127.5;if(a[n+28]=_<=0?0:_>=255?255:_+.5|0,a[n+29]=T<=0?0:T>=255?255:T+.5|0,a[n+30]=A<=0?0:A>=255?255:A+.5|0,a[n+31]=M<=0?0:M>=255?255:M+.5|0,g&&x&&v&&b){const t=e*y,n=16*e;for(let e=0;e<x.length;e++){const o=x[e],s=v[e],r=b[e];for(let e=s;e<r;e++){const r=128*g[t+e]+128;o[n+e-s]=r<=0?0:r>=255?255:r+.5|0}}}e%32768==0&&o&&(yield)}if(e.extensions)for(const t of e.extensions){const e=t;if(void 0!==e.safeOrbitRadiusMin){p=e.safeOrbitRadiusMin,_=[e.safeOrbitElevationMin,e.safeOrbitElevationMax];break}}return{mode:0,data:r,hasVertexColors:!1,sh:null!==m?m:void 0,shDegree:f>0?f:void 0,trainedWithAntialiasing:!!e.antialiased,safeOrbitCameraRadiusMin:p,safeOrbitCameraElevationMinMax:_}}(e,n,!0),t.createYieldingScheduler())})}(e.loadSpzFromBuffer(new Uint8Array(o),{to:e.CoordinateSystem.RUB}),n).then(e=>new Promise(t=>{f(e,t)})));if(m)return Promise.reject(new Error("SPZ V4+ files (NGSP format) are not supported by the native fallback loader. Please provide a valid 'spzLibraryUrl' in the loading options to use the WASM-based SPZ library, or ensure WebAssembly is available in your environment."));const p=new ReadableStream({start(e){e.enqueue(new Uint8Array(o)),e.close()}}),_=new DecompressionStream("gzip"),g=p.pipeThrough(_);return new Promise(e=>{new Response(g).arrayBuffer().then(o=>{(function(e,n){const o=new Uint8Array(e),s=new Uint32Array(e.slice(0,12)),r=s[2],i=o[12],a=o[13],l=o[14],u=o[15],c=s[1];if(u||1347635022!=s[0]||c<2||c>4)return new Promise(e=>{e({mode:3,data:new ArrayBuffer(0),hasVertexColors:!1})});const d=new ArrayBuffer(32*r),h=1/(1<<a),m=new Int32Array(1),f=new Uint8Array(m.buffer),p=function(e,t){return f[0]=e[t+0],f[1]=e[t+1],f[2]=e[t+2],f[3]=128&e[t+2]?255:0,m[0]*h};let _=16;const g=new Float32Array(d),y=new Float32Array(d),v=new Uint8ClampedArray(d),b=new Uint8ClampedArray(d);for(let e=0;e<r;e++)g[8*e+0]=p(o,_+0),g[8*e+1]=p(o,_+3),g[8*e+2]=p(o,_+6),_+=9;for(let e=0;e<r;e++){for(let n=0;n<3;n++){const s=(o[_+r+3*e+n]-127.5)/38.25;v[32*e+24+n]=t.Scalar.Clamp(255*(.5+lu*s),0,255)}v[32*e+24+3]=o[_+e]}_+=4*r;for(let e=0;e<r;e++)y[8*e+3+0]=Math.exp(o[_+0]/16-10),y[8*e+3+1]=Math.exp(o[_+1]/16-10),y[8*e+3+2]=Math.exp(o[_+2]/16-10),_+=3;if(c>=3){const e=Math.SQRT1_2;for(let t=0;t<r;t++){const n=[o[_+0],o[_+1],o[_+2],o[_+3]],s=n[0]+(n[1]<<8)+(n[2]<<16)+(n[3]<<24),r=511,i=[],a=s>>>30;let l=s,u=0;for(let t=3;t>=0;--t)if(t!==a){const n=l&r,o=l>>>9&1;l>>>=10,i[t]=e*(n/r),1===o&&(i[t]=-i[t]),u+=i[t]*i[t]}const c=1-u;i[a]=Math.sqrt(Math.max(c,0));const d=[3,0,1,2];for(let e=0;e<4;e++)b[32*t+28+e]=Math.round(127.5+127.5*i[d[e]]);_+=4}}else for(let e=0;e<r;e++){const t=o[_+0],n=o[_+1],s=o[_+2],r=t/127.5-1,i=n/127.5-1,a=s/127.5-1;b[32*e+28+1]=t,b[32*e+28+2]=n,b[32*e+28+3]=s;const l=1-(r*r+i*i+a*a);b[32*e+28+0]=127.5+127.5*Math.sqrt(l<0?0:l),_+=3}if(i){const e=3*((i+1)*(i+1)-1),s=Math.ceil(e/16);let a=_;const u=n.getEngine().getCaps().maxTextureSize,c=Math.ceil(r/u),h=t.AllocateShBuffers(s,c*u*4*4);for(let t=0;t<r;t++)for(let n=0;n<e;n++){const e=o[a++],s=Math.floor(n/16);h[s][n%16+16*t]=e}return new Promise(e=>{e({mode:0,data:d,hasVertexColors:!1,sh:h,shDegree:i,trainedWithAntialiasing:!!l})})}return new Promise(e=>{e({mode:0,data:d,hasVertexColors:!1,trainedWithAntialiasing:!!l})})})(o,n,this._loadingOptions).then(t=>{f(t,e)})}).catch(()=>{d(e)})})}applyAutoCameraLimits(e,t){var n;if(!this._loadingOptions.disableAutoCameraLimits&&(void 0!==e.safeOrbitCameraRadiusMin||void 0!==e.safeOrbitCameraElevationMinMax)&&"ArcRotateCamera"===(null===(n=t.activeCamera)||void 0===n?void 0:n.getClassName())){const n=t.activeCamera;e.safeOrbitCameraElevationMinMax&&(n.lowerBetaLimit=.5*Math.PI-e.safeOrbitCameraElevationMinMax[1],n.upperBetaLimit=.5*Math.PI-e.safeOrbitCameraElevationMinMax[0]),e.safeOrbitCameraRadiusMin&&(n.lowerRadiusLimit=e.safeOrbitCameraRadiusMin)}}loadAssetContainerAsync(e,n,o){const s=new t.AssetContainer(e);return this._assetContainer=s,this.importMeshAsync(null,e,n,o).then(e=>{for(const t of e.meshes)s.meshes.push(t);return this._assetContainer=null,s}).catch(e=>{throw this._assetContainer=null,e})}loadAsync(e,t,n){return this.importMeshAsync(null,e,t,n).then(()=>{})}static _ConvertPLYToSplat(e){const n=new Uint8Array(e),o=(new TextDecoder).decode(n.slice(0,10240)),s=o.indexOf("end_header\n");if(s<0||!o)return new Promise(t=>{t({mode:0,data:e,rawSplat:!0})});const r=parseInt(/element vertex (\d+)\n/.exec(o)[1]),i=/element face (\d+)\n/.exec(o);let a=0;i&&(a=parseInt(i[1]));const l=/element chunk (\d+)\n/.exec(o);let u=0;l&&(u=parseInt(l[1]));let c=0,d=0;const h={double:8,int:4,uint:4,float:4,short:2,ushort:2,uchar:1,list:0};let m=1;const f=[],p=[],_=o.slice(0,s).split("\n"),g={};for(const n of _)if(n.startsWith("property ")){const[,o,s]=n.split(" ");if(1==m)p.push({name:s,type:o,offset:d}),d+=h[o];else if(0==m)f.push({name:s,type:o,offset:c}),c+=h[o];else if(2==m)f.push({name:s,type:o,offset:c});else if(3==m){const t=new DataView(e,d,2*h.float);g.safeOrbitCameraElevationMinMax=[t.getFloat32(0,!0),t.getFloat32(4,!0)]}else if(4==m){const t=new DataView(e,d,h.float);g.safeOrbitCameraRadiusMin=t.getFloat32(0,!0)}else if(5==m){const t=new DataView(e,d,h.uchar);"up_axis"==s?g.upAxis=0==t.getUint8(0)?"X":1==t.getUint8(0)?"Y":"Z":"chirality"==s&&(g.chirality=0==t.getUint8(0)?"LeftHanded":"RightHanded")}h[o]||t.Logger.Warn(`Unsupported property type: ${o}.`)}else if(n.startsWith("element ")){const[,e]=n.split(" ");"chunk"==e?m=1:"vertex"==e?m=0:"sh"==e?m=2:"safe_orbit_camera_elevation_min_max_radians"==e?m=3:"safe_orbit_camera_radius_min"==e?m=4:"up_axis"!=e&&"chirality"!=e||(m=5)}const y=c,v=d;return t.GaussianSplattingMesh.ConvertPLYWithSHToSplatAsync(e).then(t=>b(this,void 0,void 0,function*(){const n=new DataView(e,s+11);let o=v*u+y*r;const i=[];if(a)for(let e=0;e<a;e++){const e=n.getUint8(o);if(3==e){o+=1;for(let t=0;t<e;t++){const e=n.getUint32(o+4*(2-t),!0);i.push(e)}o+=12}}if(u)return yield new Promise(e=>{e({mode:0,data:t.buffer,sh:t.sh,shDegree:t.shDegree,faces:i,hasVertexColors:!1,compressed:!0,rawSplat:!1})});let l=0,c=0;const d=["x","y","z","scale_0","scale_1","scale_2","opacity","rot_0","rot_1","rot_2","rot_3"],h=["red","green","blue","f_dc_0","f_dc_1","f_dc_2"];for(let e=0;e<f.length;e++){const t=f[e];d.includes(t.name)&&l++,h.includes(t.name)&&c++}const m=l==d.length&&c>=3,p=a?2:m?0:1;return yield new Promise(e=>{e(Object.assign(Object.assign({},g),{mode:p,data:t.buffer,sh:t.sh,shDegree:t.shDegree,faces:i,hasVertexColors:!!c,compressed:!1,rawSplat:!1}))})}))}}du._DefaultLoadingOptions={keepInRam:!1,flipY:!1,needsRotationScaleTextures:!1,spzLibraryUrl:"object"==typeof WebAssembly?"https://unpkg.com/@adobe/spz@0.2.2/dist/spz.js":void 0};let hu=!1;function mu(){hu||(hu=!0,t.RegisterSceneLoaderPlugin(new du))}mu();var fu={__proto__:null,RegisterSPLATFileLoader:mu,SPLATFileLoader:du};function pu(){t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},f),{createPlugin:e=>b(this,void 0,void 0,function*(){const{BVHFileLoader:t}=yield Promise.resolve().then(function(){return y});return new t(e[f.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},Bt),{createPlugin:e=>b(this,void 0,void 0,function*(){const{FBXFileLoader:t}=yield Promise.resolve().then(function(){return Zt});return new t(e[Bt.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},sn),{createPlugin:e=>b(this,void 0,void 0,function*(){const{GLTFFileLoader:t}=yield Promise.resolve().then(function(){return xo});return new t(e[sn.name])})})),function(){no("EXT_lights_image_based"),to("EXT_lights_image_based",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_image_based:t}=yield Promise.resolve().then(function(){return ko});return new t(e)})),no("EXT_mesh_gpu_instancing"),to("EXT_mesh_gpu_instancing",!0,e=>b(this,void 0,void 0,function*(){const{EXT_mesh_gpu_instancing:t}=yield Promise.resolve().then(function(){return Ko});return new t(e)})),no("EXT_meshopt_compression"),to("EXT_meshopt_compression",!0,e=>b(this,void 0,void 0,function*(){const{EXT_meshopt_compression:t}=yield Promise.resolve().then(function(){return jo});return new t(e)})),no("EXT_texture_avif"),to("EXT_texture_avif",!0,e=>b(this,void 0,void 0,function*(){const{EXT_texture_avif:t}=yield Promise.resolve().then(function(){return os});return new t(e)})),no("EXT_texture_webp"),to("EXT_texture_webp",!0,e=>b(this,void 0,void 0,function*(){const{EXT_texture_webp:t}=yield Promise.resolve().then(function(){return Zo});return new t(e)})),no("ExtrasAsMetadata"),to("ExtrasAsMetadata",!1,e=>b(this,void 0,void 0,function*(){const{ExtrasAsMetadata:t}=yield Promise.resolve().then(function(){return yl});return new t(e)})),no("KHR_animation_pointer"),to("KHR_animation_pointer",!0,e=>b(this,void 0,void 0,function*(){const{KHR_animation_pointer:t}=yield Promise.resolve().then(function(){return fa});return new t(e)})),no("KHR_draco_mesh_compression"),to("KHR_draco_mesh_compression",!0,e=>b(this,void 0,void 0,function*(){const{KHR_draco_mesh_compression:t}=yield Promise.resolve().then(function(){return ms});return new t(e)})),no("KHR_gaussian_splatting"),to("KHR_gaussian_splatting",!0,e=>b(this,void 0,void 0,function*(){const{KHR_gaussian_splatting:t}=yield Promise.resolve().then(function(){return xs});return new t(e)})),no("KHR_interactivity"),to("KHR_interactivity",!0,e=>b(this,void 0,void 0,function*(){const{KHR_interactivity:t}=yield Promise.resolve().then(function(){return Ya});return new t(e)})),no("KHR_lights_punctual"),to("KHR_lights_punctual",!0,e=>b(this,void 0,void 0,function*(){const{KHR_lights:t}=yield Promise.resolve().then(function(){return Cs});return new t(e)})),no("EXT_lights_area"),to("EXT_lights_area",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_area:t}=yield Promise.resolve().then(function(){return Es});return new t(e)})),no("EXT_lights_ies"),to("EXT_lights_ies",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_ies:t}=yield Promise.resolve().then(function(){return ls});return new t(e)})),no("KHR_materials_anisotropy"),to("KHR_materials_anisotropy",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_anisotropy:t}=yield Promise.resolve().then(function(){return ar});return new t(e)})),no("KHR_materials_clearcoat"),to("KHR_materials_clearcoat",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_clearcoat:t}=yield Promise.resolve().then(function(){return zs});return new t(e)})),no("KHR_materials_diffuse_roughness"),to("KHR_materials_diffuse_roughness",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_diffuse_roughness:t}=yield Promise.resolve().then(function(){return pi});return new t(e)})),no("KHR_materials_diffuse_transmission"),to("KHR_materials_diffuse_transmission",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_diffuse_transmission:t}=yield Promise.resolve().then(function(){return Xr});return new t(e)})),no("KHR_materials_dispersion"),to("KHR_materials_dispersion",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_dispersion:t}=yield Promise.resolve().then(function(){return ci});return new t(e)})),no("KHR_materials_emissive_strength"),to("KHR_materials_emissive_strength",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_emissive_strength:t}=yield Promise.resolve().then(function(){return hr});return new t(e)})),no("KHR_materials_ior"),to("KHR_materials_ior",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_ior:t}=yield Promise.resolve().then(function(){return Lr});return new t(e)})),no("KHR_materials_iridescence"),to("KHR_materials_iridescence",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_iridescence:t}=yield Promise.resolve().then(function(){return nr});return new t(e)})),no("KHR_materials_pbrSpecularGlossiness"),to("KHR_materials_pbrSpecularGlossiness",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_pbrSpecularGlossiness:t}=yield Promise.resolve().then(function(){return Bs});return new t(e)})),no("KHR_materials_sheen"),to("KHR_materials_sheen",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_sheen:t}=yield Promise.resolve().then(function(){return gr});return new t(e)})),no("KHR_materials_specular"),to("KHR_materials_specular",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_specular:t}=yield Promise.resolve().then(function(){return Rr});return new t(e)})),no("KHR_materials_transmission"),to("KHR_materials_transmission",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_transmission:t}=yield Promise.resolve().then(function(){return $r});return new t(e)})),no("KHR_materials_unlit"),to("KHR_materials_unlit",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_unlit:t}=yield Promise.resolve().then(function(){return Hs});return new t(e)})),no("KHR_materials_variants"),to("KHR_materials_variants",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_variants:t}=yield Promise.resolve().then(function(){return kr});return new t(e)})),no("KHR_materials_volume"),to("KHR_materials_volume",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_volume:t}=yield Promise.resolve().then(function(){return ei});return new t(e)})),no("KHR_mesh_quantization"),to("KHR_mesh_quantization",!0,e=>b(this,void 0,void 0,function*(){const{KHR_mesh_quantization:t}=yield Promise.resolve().then(function(){return bi});return new t(e)})),no("KHR_texture_basisu"),to("KHR_texture_basisu",!0,e=>b(this,void 0,void 0,function*(){const{KHR_texture_basisu:t}=yield Promise.resolve().then(function(){return wi});return new t(e)})),no("KHR_texture_transform"),to("KHR_texture_transform",!0,e=>b(this,void 0,void 0,function*(){const{KHR_texture_transform:t}=yield Promise.resolve().then(function(){return Fi});return new t(e)})),no("KHR_xmp_json_ld"),to("KHR_xmp_json_ld",!0,e=>b(this,void 0,void 0,function*(){const{KHR_xmp_json_ld:t}=yield Promise.resolve().then(function(){return Pi});return new t(e)})),no("MSFT_audio_emitter"),to("MSFT_audio_emitter",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_audio_emitter:t}=yield Promise.resolve().then(function(){return va});return new t(e)})),no("MSFT_lod"),to("MSFT_lod",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_lod:t}=yield Promise.resolve().then(function(){return Ma});return new t(e)})),no("MSFT_minecraftMesh"),to("MSFT_minecraftMesh",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_minecraftMesh:t}=yield Promise.resolve().then(function(){return Sa});return new t(e)})),no("MSFT_sRGBFactors"),to("MSFT_sRGBFactors",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_sRGBFactors:t}=yield Promise.resolve().then(function(){return Na});return new t(e)})),no("KHR_node_visibility"),to("KHR_node_visibility",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_visibility:t}=yield Promise.resolve().then(function(){return tl});return new t(e)})),no("KHR_node_hoverability"),to("KHR_node_hoverability",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_hoverability:t}=yield Promise.resolve().then(function(){return ml});return new t(e)})),no("KHR_node_selectability"),to("KHR_node_selectability",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_selectability:t}=yield Promise.resolve().then(function(){return il});return new t(e)})),no("KHR_materials_coat"),to("KHR_materials_coat",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_coat:t}=yield Promise.resolve().then(function(){return Qs});return new t(e)})),no("KHR_materials_fuzz"),to("KHR_materials_fuzz",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_fuzz:t}=yield Promise.resolve().then(function(){return Tr});return new t(e)})),no("KHR_materials_volume_scatter"),to("KHR_materials_volume_scatter",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_volume_scatter:t}=yield Promise.resolve().then(function(){return ri});return new t(e)}))}(),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},wl),{createPlugin:e=>b(this,void 0,void 0,function*(){const{OBJFileLoader:t}=yield Promise.resolve().then(function(){return Sl});return new t(e[wl.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},kl),{createPlugin:e=>b(this,void 0,void 0,function*(){const{SPLATFileLoader:t}=yield Promise.resolve().then(function(){return fu});return new t(e[kl.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},El),{createPlugin:()=>b(this,void 0,void 0,function*(){const{STLFileLoader:e}=yield Promise.resolve().then(function(){return Pl});return new e})}))}var _u={__proto__:null,registerBuiltInLoaders:pu};const gu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==gu)for(const e in v)gu.BABYLON[e]||(gu.BABYLON[e]=v[e]);const yu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==yu){yu.BABYLON=yu.BABYLON||{};for(const e in _u)yu.BABYLON[e]=_u[e]}const vu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==vu){vu.BABYLON=vu.BABYLON||{};for(const e in wn)vu.BABYLON[e]=wn[e];for(const e in nn)vu.BABYLON[e]=nn[e]}const bu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==bu){bu.BABYLON=bu.BABYLON||{},bu.BABYLON.GLTF1=bu.BABYLON.GLTF1||{};for(const e in Zn)bu.BABYLON.GLTF1[e]=Zn[e]}const xu=Object.assign({},xl),Tu=Object.assign(Object.assign({},{__proto__:null}),{Extensions:xu}),Au=Object.assign(Object.assign({},Tl),{Loader:Tu}),Mu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Mu){Mu.BABYLON=Mu.BABYLON||{};const e=Mu.BABYLON;e.GLTF2=e.GLTF2||{},e.GLTF2.Loader=e.GLTF2.Loader||{},e.GLTF2.Loader.Extensions=e.GLTF2.Loader.Extensions||{};const t=["Loader"];for(const n in xu)e.GLTF2.Loader.Extensions[n]=xu[n],t.push(n);for(const n in Tu)"Extensions"!==n&&(e.GLTF2.Loader[n]=Tu[n],t.push(n));for(const n in Au)t.indexOf(n)>-1||(e.GLTF2[n]=Au[n])}const wu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==wu)for(const e in Fl)wu.BABYLON[e]||(wu.BABYLON[e]=Fl[e]);const Cu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Cu)for(const e in Bl)Cu.BABYLON[e]||(Cu.BABYLON[e]=Bl[e]);e.BVHFileLoader=p,e.FBXFileLoader=kt,e.FBXFileLoaderMetadata=Bt,e.GLTF1=Zn,e.GLTF2=Au,e.GLTFFileLoader=mn,e.GLTFLoaderDefaultOptions=dn,e.GLTFValidation=tn,e.GaussianSplattingStream=au,e.MTLFileLoader=Al,e.OBJFileLoader=Cl,e.ReadBvh=m,e.RegisterBVHFileLoader=g,e.RegisterGLTFFileLoader=pn,e.RegisterOBJFileLoader=Ol,e.RegisterSPLATFileLoader=mu,e.RegisterSTLFileLoader=Nl,e.SPLATFileLoader=du,e.STLFileLoader=Ll,e.SolidParser=Ml,e.registerBuiltInLoaders=pu});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("babylonjs")):"function"==typeof define&&define.amd?define(["exports","babylonjs"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).BABYLON=e.BABYLON||{},e.BABYLON)}(this,function(e,t){"use strict";const n="Xposition",o="Yposition",s="Zposition",r="Xrotation",i="Yrotation",a="Zrotation";class l{constructor(e){this.loopMode=t.Animation.ANIMATIONLOOPMODE_CYCLE,this.list=[],this.root=u(),this.numFrames=0,this.frameRate=0,this.skeleton=e}}function u(){return{name:"",type:"",offset:new t.Vector3,channels:[],children:[],frames:[],parent:null}}function c(e,l,u){const d=function(e){const n=e.offset.x,o=e.offset.y,s=e.offset.z;return t.Matrix.Translation(n,o,s)}(e),h=new t.Bone(e.name,u.skeleton,l,d),m=function(e,l){if(0===e.frames.length)return[];const u=[],c=e.channels.some(e=>e===n||e===o||e===s),d=e.channels.some(e=>e===r||e===i||e===a),h=new t.Animation(`${e.name}_pos`,"position",l.frameRate,t.Animation.ANIMATIONTYPE_VECTOR3,l.loopMode),m=new t.Animation(`${e.name}_rot`,"rotationQuaternion",l.frameRate,t.Animation.ANIMATIONTYPE_QUATERNION,l.loopMode),f=[],p=[];for(let t=0;t<e.frames.length;t++){const n=e.frames[t];c&&n.position&&f.push({frame:n.frame,value:n.position.clone()}),d&&p.push({frame:n.frame,value:n.rotation.clone()})}return f.length>0&&(h.setKeys(f),u.push(h)),p.length>0&&(m.setKeys(p),u.push(m)),u}(e,u);for(const e of m)e.getKeys()&&e.getKeys().length>0&&h.animations.push(e);for(const t of e.children)c(t,h,u)}function d(e,l,u,c){if("ENDSITE"===u.type)return;const h={frame:0,position:new t.Vector3,rotation:new t.Quaternion};h.frame=l,h.position=new t.Vector3,h.rotation=new t.Quaternion,u.frames.push(h);let m=t.Matrix.Identity();for(let l=0;l<u.channels.length;++l){const d=u.channels[l],f=e[c.i++];if(!f)continue;const p=parseFloat(f.trim());if(d.endsWith("position"))switch(d){case n:h.position.x=p;break;case o:h.position.y=p;break;case s:h.position.z=p}else if(d.endsWith("rotation")){const e=t.Tools.ToRadians(p);let n;switch(d){case r:n=t.Matrix.RotationX(e);break;case i:n=t.Matrix.RotationY(e);break;case a:n=t.Matrix.RotationZ(e)}m=n.multiply(m)}}t.Quaternion.FromRotationMatrixToRef(m,h.rotation);for(const t of u.children)d(e,l,t,c)}function h(e,n,o,s){var r,i,a,l;const c=u();c.parent=o,s.list.push(c);let d=n.trim().split(/\s+/);if("END"===d[0].toUpperCase()&&"SITE"===d[1].toUpperCase()?(c.type="ENDSITE",c.name="ENDSITE"):(c.name=d[1],c.type=d[0].toUpperCase()),"{"!=(null===(r=e.shift())||void 0===r?void 0:r.trim()))throw new Error("Expected opening { after type & name");const m=null===(i=e.shift())||void 0===i?void 0:i.trim().split(/\s+/);if(!m)throw new Error("Unexpected end of file: missing OFFSET");if(d=m,"OFFSET"!=d[0].toUpperCase())throw new Error("Expected OFFSET, but got: "+d[0]);if(4!=d.length)throw new Error("OFFSET: Invalid number of values");const f=new t.Vector3(parseFloat(d[1]),parseFloat(d[2]),parseFloat(d[3]));if(isNaN(f.x)||isNaN(f.y)||isNaN(f.z))throw new Error("OFFSET: Invalid values");if(c.offset=f,"ENDSITE"!=c.type){if(d=null===(a=e.shift())||void 0===a?void 0:a.trim().split(/\s+/),!d)throw new Error("Unexpected end of file: missing CHANNELS");if("CHANNELS"!=d[0].toUpperCase())throw new Error("Expected CHANNELS definition");const t=parseInt(d[1]);c.channels=d.splice(2,t),c.children=[]}for(;e.length>0;){const t=null===(l=e.shift())||void 0===l?void 0:l.trim();if("}"===t)return c;t&&c.children.push(h(e,t,c,s))}throw new Error("Unexpected end of file: missing closing brace")}function m(e,n,o,s){const r=e.split("\n"),{loopMode:i}=s;n._blockEntityCollection=!!o;const a=new t.Skeleton("","",n);a._parentContainer=o,n._blockEntityCollection=!1;const u=new l(a);u.loopMode=i;const m=r.shift();if(!m||"HIERARCHY"!==m.trim().toUpperCase())throw new Error("HIERARCHY expected");const f=r.shift();if(!f)throw new Error("Unexpected end of file after HIERARCHY");const p=h(r,f.trim(),null,u),_=r.shift();if(!_||"MOTION"!==_.trim().toUpperCase())throw new Error("MOTION expected");const g=r.shift();if(!g)throw new Error("Unexpected end of file before frame count");const y=g.trim().split(/[\s]+/);if(y.length<2)throw new Error("Invalid frame count line");const v=parseInt(y[1]);if(isNaN(v))throw new Error("Failed to read number of frames.");u.numFrames=v;const b=r.shift();if(!b)throw new Error("Unexpected end of file before frame time");const x=b.trim().split(/[\s]+/);if(x.length<3)throw new Error("Invalid frame time line");const T=parseFloat(x[2]);if(isNaN(T))throw new Error("Failed to read frame time.");if(T<=0)throw new Error("Failed to read frame time. Invalid value "+T);u.frameRate=1/T;for(let e=0;e<v;++e){const t=r.shift();t&&d(t.trim().split(/[\s]+/)||[],e,p,{i:0})}return u.root=p,c(u.root,null,u),u.skeleton.returnToRest(),u.skeleton}const f={name:"bvh",extensions:{".bvh":{isBinary:!1}}};class p{constructor(e){this.name=f.name,this.extensions=f.extensions,this._loadingOptions=Object.assign(Object.assign({},p._DefaultLoadingOptions),null!=e?e:{})}static get _DefaultLoadingOptions(){return{loopMode:t.Animation.ANIMATIONLOOPMODE_CYCLE}}createPlugin(e){return new p(e[f.name])}canDirectLoad(e){return this.isBvhHeader(e)}isBvhHeader(e){return"HIERARCHY"==e.split("\n")[0]}isNotBvhHeader(e){return!this.isBvhHeader(e)}importMeshAsync(e,t,n){if("string"!=typeof n)return Promise.reject("BVH loader expects string data.");if(this.isNotBvhHeader(n))return Promise.reject("BVH loader expects HIERARCHY header.");try{const e=m(n,t,null,this._loadingOptions);return Promise.resolve({meshes:[],particleSystems:[],skeletons:[e],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]})}catch(e){return Promise.reject(e)}}loadAsync(e,t){return"string"!=typeof t?Promise.reject("BVH loader expects string data."):this.isNotBvhHeader(t)?Promise.reject("BVH loader expects HIERARCHY header."):this.importMeshAsync(null,e,t).then(()=>{})}loadAssetContainerAsync(e,n){if("string"!=typeof n)return Promise.reject("BVH loader expects string data.");if(this.isNotBvhHeader(n))return Promise.reject("BVH loader expects HIERARCHY header.");const o=new t.AssetContainer(e);try{const t=m(n,e,o,this._loadingOptions);return o.skeletons.push(t),Promise.resolve(o)}catch(e){return Promise.reject(e)}}}let _=!1;function g(){_||(_=!0,t.RegisterSceneLoaderPlugin(new p))}g();var y={__proto__:null,BVHFileLoader:p,RegisterBVHFileLoader:g},v={__proto__:null,BVHFileLoader:p,ReadBvh:m,RegisterBVHFileLoader:g};function b(e,t,n,o){return new(n||(n=Promise))(function(s,r){function i(e){try{l(o.next(e))}catch(e){r(e)}}function a(e){try{l(o.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(i,a)}l((o=o.apply(e,t||[])).next())})}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;const x=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],T=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],A=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],M=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],w=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];class C{constructor(e,t,n){this.input=e,this.byteOffset=t,this.endOffset=n,this.bitBuffer=0,this.bitCount=0}readBits(e){this.ensureBits(e);const t=this.bitBuffer&(1<<e)-1;return this.bitBuffer>>>=e,this.bitCount-=e,t}readBit(){if(0===this.bitCount){if(this.byteOffset>=this.endOffset)throw new Error("zlib: unexpected end of input");this.bitBuffer=this.input[this.byteOffset++],this.bitCount=8}const e=1&this.bitBuffer;return this.bitBuffer>>>=1,this.bitCount--,e}alignToByte(){this.bitBuffer=0,this.bitCount=0}readUint16LE(){if(this.ensureByteAligned(),this.byteOffset+2>this.endOffset)throw new Error("zlib: unexpected end of input");const e=this.input[this.byteOffset]|this.input[this.byteOffset+1]<<8;return this.byteOffset+=2,e}readByte(){if(this.ensureByteAligned(),this.byteOffset>=this.endOffset)throw new Error("zlib: unexpected end of input");return this.input[this.byteOffset++]}ensureByteAligned(){if(0!==this.bitCount)throw new Error("deflate: expected byte alignment")}ensureBits(e){for(;this.bitCount<e;){if(this.byteOffset>=this.endOffset)throw new Error("zlib: unexpected end of input");this.bitBuffer|=this.input[this.byteOffset++]<<this.bitCount,this.bitCount+=8}}}class R{constructor(e){this.offset=0,this.adlerA=1,this.adlerB=0,this.bytes=new Uint8Array(e)}writeByte(e){if(this.offset>=this.bytes.byteLength)throw new Error("zlib: output length mismatch");const t=255&e;this.bytes[this.offset++]=t,this.adlerA+=t,this.adlerB+=this.adlerA,this.adlerA%=65521,this.adlerB%=65521}copy(e,t){if(e<=0||e>this.offset)throw new Error("deflate: distance out of range");for(let n=0;n<t;n++)this.writeByte(this.bytes[this.offset-e])}finish(){if(this.offset!==this.bytes.byteLength)throw new Error("zlib: output length mismatch")}adler32(){return(this.adlerB<<16|this.adlerA)>>>0}}class O{constructor(e,t={}){const n=new Array(16).fill(0);let o=0,s=0;for(const t of e){if(!Number.isInteger(t)||t<0||t>15)throw new Error("deflate: invalid huffman code lengths");t>0&&(n[t]++,o++,s=Math.max(s,t))}if(0===o){if(t.allowEmpty)return this.symbolsByLength=[],void(this.maxCodeLength=0);throw new Error("deflate: invalid huffman code lengths")}let r=1;for(let e=1;e<=15;e++)if(r=(r<<1)-n[e],r<0)throw new Error("deflate: invalid huffman code lengths");if(0!==r&&1!==o)throw new Error("deflate: invalid huffman code lengths");const i=new Array(16).fill(0);let a=0;for(let e=1;e<=15;e++)a=a+n[e-1]<<1,i[e]=a;this.symbolsByLength=Array.from({length:16},(e,t)=>{if(0===n[t])return;const o=new Int16Array(1<<t);return o.fill(-1),o});for(let t=0;t<e.length;t++){const n=e[t];0!==n&&(this.symbolsByLength[n][i[n]++]=t)}this.maxCodeLength=s}decode(e){var t,n;if(0===this.maxCodeLength)throw new Error("deflate: invalid huffman code");let o=0;for(let s=1;s<=this.maxCodeLength;s++){o=o<<1|e.readBit();const r=null!==(n=null===(t=this.symbolsByLength[s])||void 0===t?void 0:t[o])&&void 0!==n?n:-1;if(r>=0)return r}throw new Error("deflate: invalid huffman code")}}let S,F;function E(){if(!S){const e=new Array(288);for(let t=0;t<=143;t++)e[t]=8;for(let t=144;t<=255;t++)e[t]=9;for(let t=256;t<=279;t++)e[t]=7;for(let t=280;t<=287;t++)e[t]=8;S=new O(e)}return S}function L(){return F||(F=new O(new Array(32).fill(5))),F}function I(e,t){e.alignToByte();const n=e.readUint16LE();if(65535&(n^~e.readUint16LE()))throw new Error("deflate: invalid stored block length");for(let o=0;o<n;o++)t.writeByte(e.readByte())}function N(e,t,n,o){for(;;){const s=n.decode(e);if(s<256){t.writeByte(s);continue}if(256===s)return;if(s>285)throw new Error("deflate: invalid literal/length symbol");const r=s-257,i=x[r]+e.readBits(T[r]),a=o.decode(e);if(a>29)throw new Error("deflate: invalid distance symbol");const l=A[a]+e.readBits(M[a]);t.copy(l,i)}}function P(e){const t=e.readBits(5)+257,n=e.readBits(5)+1,o=e.readBits(4)+4,s=new Array(19).fill(0);for(let t=0;t<o;t++)s[w[t]]=e.readBits(3);const r=function(e,t,n){const o=[];for(;o.length<n;){const s=t.decode(e);if(s<=15){o.push(s);continue}let r,i;switch(s){case 16:if(0===o.length)throw new Error("deflate: invalid code length repeat");i=o[o.length-1],r=e.readBits(2)+3;break;case 17:i=0,r=e.readBits(3)+3;break;case 18:i=0,r=e.readBits(7)+11;break;default:throw new Error("deflate: invalid code length symbol")}if(o.length+r>n)throw new Error("deflate: invalid code length repeat");for(let e=0;e<r;e++)o.push(i)}return o}(e,new O(s),t+n),i=r.slice(0,t),a=r.slice(t);if(0===i[256])throw new Error("deflate: missing end-of-block code");return{literalLengthTree:new O(i),distanceTree:new O(a,{allowEmpty:!0})}}function B(e,t,n,o,s){let r,i,a,l;if(o?(G(t,n,25,s,"FBX node header"),r=V(e,n),i=V(e,n+8),a=V(e,n+16),l=25):(G(t,n,13,s,"FBX node header"),r=e.getUint32(n,!0),i=e.getUint32(n+4,!0),a=e.getUint32(n+8,!0),l=13),0===r)return null;if(r<=n||r>s)throw new Error(`Invalid FBX node end offset ${r} at offset ${n}`);const u=t[n+l-1];G(t,n+l,u,r,"FBX node name");const c=K(t,n+l,u);let d=n+l+u;const h=d+a;if(h>r)throw new Error(`Invalid FBX property list length for node '${c}' at offset ${n}`);const m=[];for(let n=0;n<i;n++){const n=k(e,t,d,h);m.push(n.property),d=n.nextOffset}if(d!==h)throw new Error(`Invalid FBX property list length for node '${c}' at offset ${n}`);const f=[];if(d<r)for(;d<r;){const n=B(e,t,d,o,r);if(null===n)break;if(n.endOffset<=d||n.endOffset>r)throw new Error(`Invalid FBX child node end offset ${n.endOffset} at offset ${d}`);f.push(n.node),d=n.endOffset}return{node:{name:c,properties:m,children:f},endOffset:r}}function k(e,t,n,o){G(t,n,1,o,"FBX property type");const s=String.fromCharCode(t[n]);switch(n+=1,s){case"C":return G(t,n,1,o,"FBX boolean property"),{property:{type:"boolean",value:0!==t[n]},nextOffset:n+1};case"Y":return G(t,n,2,o,"FBX int16 property"),{property:{type:"int16",value:e.getInt16(n,!0)},nextOffset:n+2};case"I":return G(t,n,4,o,"FBX int32 property"),{property:{type:"int32",value:e.getInt32(n,!0)},nextOffset:n+4};case"F":return G(t,n,4,o,"FBX float32 property"),{property:{type:"float32",value:e.getFloat32(n,!0)},nextOffset:n+4};case"D":return G(t,n,8,o,"FBX float64 property"),{property:{type:"float64",value:e.getFloat64(n,!0)},nextOffset:n+8};case"L":return G(t,n,8,o,"FBX int64 property"),{property:{type:"int64",value:H(e,n)},nextOffset:n+8};case"S":{G(t,n,4,o,"FBX string property length");const s=e.getUint32(n,!0);G(t,n+4,s,o,"FBX string property data");const r=function(e,t,n){return new TextDecoder("utf-8").decode(e.subarray(t,t+n))}(t,n+4,s);return{property:{type:"string",value:r},nextOffset:n+4+s}}case"R":{G(t,n,4,o,"FBX raw property length");const s=e.getUint32(n,!0);return G(t,n+4,s,o,"FBX raw property data"),{property:{type:"raw",value:t.slice(n+4,n+4+s)},nextOffset:n+4+s}}case"f":return D(e,t,n,"float32[]",4,o);case"d":return D(e,t,n,"float64[]",8,o);case"i":return D(e,t,n,"int32[]",4,o);case"l":return D(e,t,n,"int64[]",8,o);case"b":return D(e,t,n,"boolean[]",1,o);default:throw new Error(`Unknown FBX property type: '${s}' at offset ${n-1}`)}}function D(e,t,n,o,s,r){G(t,n,12,r,`FBX array property header for ${o}`);const i=e.getUint32(n,!0),a=e.getUint32(n+4,!0),l=e.getUint32(n+8,!0),u=i*s;let c;if(G(t,n+=12,l,r,`FBX array property data for ${o}`),1===a)c=function(e,t){if(!Number.isInteger(t)||t<0)throw new Error("zlib: invalid expected length");if(e.byteLength<6)throw new Error("zlib: unexpected end of input");const n=e[0],o=e[1];if(8!=(15&n)||n>>4>7||((n<<8)+o)%31!=0)throw new Error("zlib: invalid header");if(32&o)throw new Error("zlib: preset dictionary not supported");const s=new C(e,2,e.byteLength-4),r=new R(t);let i=!1;for(;!i;)switch(i=1===s.readBits(1),s.readBits(2)){case 0:I(s,r);break;case 1:N(s,r,E(),L());break;case 2:{const{literalLengthTree:e,distanceTree:t}=P(s);N(s,r,e,t);break}default:throw new Error("deflate: invalid block type")}if(s.byteOffset<e.byteLength-4)throw new Error("zlib: trailing deflate data");r.finish();const a=(e[e.byteLength-4]<<24|e[e.byteLength-3]<<16|e[e.byteLength-2]<<8|e[e.byteLength-1])>>>0;if(r.adler32()!==a)throw new Error("zlib: adler32 mismatch");return r.bytes}(t.subarray(n,n+l),u);else{if(0!==a)throw new Error(`Unsupported FBX array encoding: ${a}`);if(l!==u)throw new Error(`Invalid FBX array byte length for ${o}`);c=t.slice(n,n+l)}const d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);let h;switch(o){case"float32[]":h=new Float32Array(d);break;case"float64[]":h=new Float64Array(d);break;case"int32[]":h=new Int32Array(d);break;case"boolean[]":h=c;break;case"int64[]":h=function(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new Float64Array(e.byteLength/8);for(let e=0;e<n.length;e++)n[e]=H(t,8*e);return n}(c);break;default:throw new Error(`Unexpected array type: ${o}`)}return{property:{type:o,value:h},nextOffset:n+l}}function G(e,t,n,o,s){if(t<0||n<0||t+n>o||t+n>e.byteLength)throw new Error(`${s}: unexpected end of input`)}function V(e,t){const n=e.getUint32(t,!0);return 4294967296*e.getUint32(t+4,!0)+n}function H(e,t){const n=e.getUint32(t,!0);return 4294967296*e.getInt32(t+4,!0)+n}function K(e,t,n){let o="";for(let s=0;s<n;s++)o+=String.fromCharCode(e[t+s]);return o}function U(e){const t=new W(e),n=function(e){const t=e.match(/;\s*FBX\s+(\d+)\.(\d+)\.(\d+)/);if(!t)throw new Error("Cannot determine FBX version from ASCII header");return 1e3*parseInt(t[1])+100*parseInt(t[2])+parseInt(t[3])}(e),o=[];for(;!t.isEOF()&&(t.skipWhitespaceAndComments(),!t.isEOF());){const e=z(t);e&&o.push(e)}return{version:n,nodes:o}}var $;!function(e){e[e.Identifier=0]="Identifier",e[e.Number=1]="Number",e[e.String=2]="String",e[e.OpenBrace=3]="OpenBrace",e[e.CloseBrace=4]="CloseBrace",e[e.Colon=5]="Colon",e[e.Comma=6]="Comma",e[e.Star=7]="Star",e[e.EOF=8]="EOF"}($||($={}));let W=class{constructor(e){this.text=e,this.pos=0,this.len=e.length}isEOF(){return this.skipWhitespaceAndComments(),this.pos>=this.len}peek(){const e=this.pos,t=this.next();return this.pos=e,t}next(){if(this.skipWhitespaceAndComments(),this.pos>=this.len)return{type:8,value:"",pos:this.pos};const e=this.text[this.pos],t=this.pos;switch(e){case"{":return this.pos++,{type:3,value:"{",pos:t};case"}":return this.pos++,{type:4,value:"}",pos:t};case":":return this.pos++,{type:5,value:":",pos:t};case",":return this.pos++,{type:6,value:",",pos:t};case"*":return this.pos++,{type:7,value:"*",pos:t};case'"':return this.readString();default:if(this.isNumberStart(e))return this.readNumber();if(this.isIdentStart(e))return this.readIdentifier();throw new Error(`Unexpected character '${e}' at position ${this.pos}`)}}expect(e){const t=this.next();if(t.type!==e)throw new Error(`Expected token type ${e} but got ${t.type} ('${t.value}') at pos ${t.pos}`);return t}isNextNodeStart(){const e=this.pos;if(this.skipWhitespaceAndComments(),this.pos<this.len&&this.isIdentStart(this.text[this.pos])){for(;this.pos<this.len&&this.isIdentChar(this.text[this.pos]);)this.pos++;for(;this.pos<this.len&&(" "===this.text[this.pos]||"\t"===this.text[this.pos]);)this.pos++;const t=this.pos<this.len&&":"===this.text[this.pos];return this.pos=e,t}return this.pos=e,!1}skipWhitespaceAndComments(){for(;this.pos<this.len;){const e=this.text[this.pos];if(" "===e||"\t"===e||"\r"===e||"\n"===e)this.pos++;else{if(";"!==e)break;for(;this.pos<this.len&&"\n"!==this.text[this.pos];)this.pos++}}}readString(){const e=this.pos;this.pos++;let t="";for(;this.pos<this.len&&'"'!==this.text[this.pos];)"\\"===this.text[this.pos]&&this.pos+1<this.len?(this.pos++,t+=this.text[this.pos]):t+=this.text[this.pos],this.pos++;return this.pos<this.len&&this.pos++,{type:2,value:t,pos:e}}readNumber(){const e=this.pos;for("-"!==this.text[this.pos]&&"+"!==this.text[this.pos]||this.pos++;this.pos<this.len&&this.isDigit(this.text[this.pos]);)this.pos++;if(this.pos<this.len&&"."===this.text[this.pos])for(this.pos++;this.pos<this.len&&this.isDigit(this.text[this.pos]);)this.pos++;if(this.pos<this.len&&("e"===this.text[this.pos]||"E"===this.text[this.pos]))for(this.pos++,this.pos<this.len&&("+"===this.text[this.pos]||"-"===this.text[this.pos])&&this.pos++;this.pos<this.len&&this.isDigit(this.text[this.pos]);)this.pos++;return{type:1,value:this.text.substring(e,this.pos),pos:e}}readIdentifier(){const e=this.pos;for(;this.pos<this.len&&this.isIdentChar(this.text[this.pos]);)this.pos++;return{type:0,value:this.text.substring(e,this.pos),pos:e}}isDigit(e){return e>="0"&&e<="9"}isNumberStart(e){return!!this.isDigit(e)||("-"===e||"+"===e)&&this.pos+1<this.len&&(this.isDigit(this.text[this.pos+1])||"."===this.text[this.pos+1])}isIdentStart(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||"_"===e}isIdentChar(e){return this.isIdentStart(e)||this.isDigit(e)||"|"===e}};function z(e){const t=e.peek();if(4===t.type||8===t.type)return null;const n=e.next();if(0!==n.type)throw new Error(`Expected identifier for node name, got '${n.value}' at pos ${n.pos}`);const o=n.value;e.expect(5);const s=[],r=[];let i=e.peek();if(7===i.type){e.next();const t=e.expect(1),n=parseInt(t.value);e.expect(3);const i=e.next();if(0===i.type&&"a"===i.value){e.expect(5);const t=function(e,t){const n=[];for(;;){const t=e.peek();if(4===t.type||8===t.type)break;if(6!==t.type){if(1!==t.type)break;{const t=e.next();n.push(Number(t.value))}}else e.next()}if(n.length!==t)throw new Error(`ASCII FBX array declared ${t} values but parsed ${n.length}`);return n}(e,n);s.push({type:"float64[]",value:new Float64Array(t)})}return e.expect(4),{name:o,properties:s,children:r}}for(i=e.peek();3!==i.type&&4!==i.type&&8!==i.type;){if(1===i.type){const t=e.next(),n=j(t.value);!Number.isInteger(n)||t.value.includes(".")||t.value.includes("e")||t.value.includes("E")?s.push({type:"float64",value:n}):s.push({type:q(n)?"int32":"int64",value:n})}else if(2===i.type){const t=e.next();s.push({type:"string",value:t.value})}else if(0===i.type){if(e.isNextNodeStart())break;const t=e.next();s.push({type:"string",value:t.value})}else{if(6!==i.type)break;e.next()}i=e.peek()}if(i=e.peek(),3===i.type){for(e.next();i=e.peek(),4!==i.type&&8!==i.type;){const t=z(e);if(!t)break;r.push(t)}e.expect(4)}return{name:o,properties:s,children:r}}function j(e){return Number(e)}function q(e){return e>=-2147483648&&e<=2147483647}function X(e,t){return e.children.find(e=>e.name===t)}function Y(e,t){return e.nodes.find(e=>e.name===t)}function Q(e,t){if(t<e.properties.length)return e.properties[t].value}function Z(e){const t=e.indexOf("\0");t>=0&&(e=e.substring(0,t));const n=e.indexOf("::");return n>=0&&(e=e.substring(n+2)),e}function J(e,t,n){var o;const s=null!==(o=e.childrenOf.get(t))&&void 0!==o?o:[],r=[];for(const t of s){const o=e.objects.get(t.id);!o||n&&o.name!==n||r.push({id:t.id,node:o,propertyName:t.propertyName})}return r}function ee(e){return function(e){if("number"==typeof e){if(!Number.isSafeInteger(e))throw new Error(`Unsafe FBX object ID ${e.toString()}: object IDs must be safe integers.`);return e}}(e)}function te(e,t){const n=ee(e);if(void 0!==n)return n;if("string"!=typeof e)return;const o=Z(e);return"Scene"===o?0:t.get(o)}function ne(e,t,n,o,s,r,i,a,l){e.push({type:s,childId:r,parentId:i,propertyName:a}),t.has(i)||t.set(i,[]),t.get(i).push({id:r,propertyName:a}),n.get(r)&&o.push({reason:"duplicate-parent",message:"FBX object has multiple parents; preserving the existing last-parent behavior.",connectionIndex:l,type:s,childId:r,parentId:i,propertyName:a}),n.set(r,{id:i,propertyName:a})}function oe(e,t){var n,o;const s=Z(null!==(n=Q(e,0))&&void 0!==n?n:e.name),r=null!==(o=Q(e,1))&&void 0!==o?o:"";return Object.assign(Object.assign({},e),{properties:[{type:"int64",value:t},{type:"string",value:s},{type:"string",value:r}]})}function se(e,t){var n;return{name:"Geometry",properties:[{type:"int64",value:t},{type:"string",value:Z(null!==(n=Q(e,0))&&void 0!==n?n:"Geometry")},{type:"string",value:"Mesh"}],children:e.children}}function re(e,t){var n,o,s;const r=Z(null!==(n=Q(e,1))&&void 0!==n?n:"Geometry"),i=X(e,"Vertices");if(!i)throw new Error(`Geometry '${r}' has no Vertices node`);const a=fe(_e(i)),l=X(e,"PolygonVertexIndex");if(!l)throw new Error(`Geometry '${r}' has no PolygonVertexIndex node`);const u=[],c=function(e){const t=[];let n=[],o=0;for(let s=0;s<e.length;s++){const r=e[s];r<0?(n.push(-(r+1)),t.push({indices:n,startIndex:o}),n=[],o=s+1):n.push(r)}return t}(pe(_e(l))),d=function(e,t,n){const o=[];for(let s=0;s<e.length;s++){const r=e[s];o.push(...ie(r,s,t,n))}return o}(c,a,u),h=function(e){const t=[];for(let n=0;n<e.length;n++){const o=e[n];for(let e=0;e<o.indices.length;e++)t.push({polyIndex:n,vertexInPoly:e,controlPointIndex:o.indices[e],globalIndex:o.startIndex+e})}return t}(c),m=X(e,"LayerElementNormal");let f=null;m&&(f=he(m,"Normals","NormalsIndex",h,a.length,3,u));const p=e.children.filter(e=>"LayerElementUV"===e.name),_=[];for(const e of p){const t=X(e,"Name"),n=t&&null!==(o=Q(t,0))&&void 0!==o?o:`UVSet${_.length}`,s=he(e,"UV","UVIndex",h,a.length,2,u);s&&_.push({name:n,data:s})}const g=_.length>0?_[0].data:null,y=X(e,"LayerElementColor");let v=null;if(y){const e=he(y,"Colors","ColorIndex",h,a.length,4,u);if(e){v=new Float32Array(e.length);for(let t=0;t<e.length;t++)v[t]=e[t]}}const b=X(e,"LayerElementTangent"),x=X(e,"LayerElementBinormal"),T=x?he(x,"Binormals","BinormalsIndex",h,a.length,3,u):null,A=b?function(e,t,n,o,s,r){const i=function(e,t,n,o,s,r){var i,a,l,u;const c=X(e,"Tangents");if(!c)return 3;const d=fe(_e(c)),h=null!==(a=Q(null!==(i=X(e,"MappingInformationType"))&&void 0!==i?i:{name:"",properties:[],children:[]},0))&&void 0!==a?a:"",m=null!==(u=Q(null!==(l=X(e,"ReferenceInformationType"))&&void 0!==l?l:{name:"",properties:[],children:[]},0))&&void 0!==u?u:"",f=X(e,"TangentsIndex"),p=f?pe(_e(f)):null,_="IndexToDirect"===m&&p?Math.max(...Array.from(p),0)+1:"ByControlPoint"===h||"ByVertice"===h?s:"AllSame"===h?1:o.length;if(_>0&&d.length%_===0){const e=d.length/_;if(3===e||4===e)return e}return r.push({type:"layer-data-too-short",message:`Could not infer stride for layer '${e.name}', defaulting to 3.`,layerName:e.name}),3}(e,0,0,t,n,r),a=he(e,"Tangents","TangentsIndex",t,0,i,r);if(!a)return null;const l=new Float64Array(4*t.length);for(let e=0;e<t.length;e++){const t=e*i,n=4*e;l[n]=a[t],l[n+1]=a[t+1],l[n+2]=a[t+2],l[n+3]=i>=4?a[t+3]:me(e,l,o,s)}return l}(b,h,a.length/3,f,T,u):null,M=X(e,"LayerElementMaterial");let w=null;M&&(w=function(e,t){var n,o;const s=X(e,"MappingInformationType"),r=X(e,"ReferenceInformationType");if(!s||!r)return null;const i=null!==(n=Q(s,0))&&void 0!==n?n:"",a=null!==(o=Q(r,0))&&void 0!==o?o:"";if("AllSame"===i){const n=X(e,"Materials"),o=n?pe(_e(n)):null,s=o&&o.length>0?o[0]:0,r=new Int32Array(t);return 0!==s&&r.fill(s),r}if("ByPolygon"===i){const t=X(e,"Materials");if(!t)return null;const n=pe(_e(t));if("Direct"===a||"IndexToDirect"===a)return n}return null}(M,c.length));const C=function(e,t,n,o,s,r,i,a,l){const u=n.length,c=new Float64Array(3*u),d=new Uint32Array(u);for(let t=0;t<n.length;t++){const o=n[t].controlPointIndex;c[3*t]=e[3*o],c[3*t+1]=e[3*o+1],c[3*t+2]=e[3*o+2],d[t]=o}const h=3*t.length,m=new Uint32Array(h);for(let e=0;e<t.length;e++)m[3*e]=t[e].vertices[0],m[3*e+1]=t[e].vertices[1],m[3*e+2]=t[e].vertices[2];return{positions:c,indices:m,normals:o,uvs:s,uvSets:r,colors:i,tangents:a,binormals:l,controlPointIndices:d}}(a,d,h,f,g,_,v,A,T);let R=null;if(w){let e=!0;const t=w[0];for(let n=1;n<w.length;n++)if(w[n]!==t){e=!1;break}if(!e||0!==t){const e=C.indices.length/3;R=new Int32Array(e);for(let e=0;e<d.length;e++)R[e]=null!==(s=w[d[e].polyIndex])&&void 0!==s?s:0}}return{id:t,name:r,positions:C.positions,indices:C.indices,normals:C.normals,uvs:C.uvs,uvSets:C.uvSets,colors:C.colors,tangents:C.tangents,binormals:C.binormals,controlPointIndices:C.controlPointIndices,materialIndices:R,diagnostics:u}}function ie(e,t,n,o){if(e.indices.length<3)return o.push({type:"degenerate-polygon",message:`Polygon ${t} has fewer than three vertices.`,polygonIndex:t}),[];if(3===e.indices.length)return[{vertices:[e.startIndex,e.startIndex+1,e.startIndex+2],polyIndex:t}];const s=function(e,t){const n=function(e,t){let n=0,o=0,s=0;for(let r=0;r<e.indices.length;r++){const i=3*e.indices[r],a=3*e.indices[(r+1)%e.indices.length],l=t[i],u=t[i+1],c=t[i+2],d=t[a],h=t[a+1],m=t[a+2];n+=(u-h)*(c+m),o+=(c-m)*(l+d),s+=(l-d)*(u+h)}return[n,o,s]}(e,t),o=Math.abs(n[0]),s=Math.abs(n[1]),r=Math.abs(n[2]);if(o+s+r<1e-12)return null;const i=o>s&&o>r?0:s>r?1:2;return e.indices.map(e=>{const o=t[3*e],s=t[3*e+1],r=t[3*e+2];return 0===i?n[0]>=0?[s,r]:[r,s]:1===i?n[1]>=0?[r,o]:[o,r]:n[2]>=0?[o,s]:[s,o]})}(e,n);if(!s)return o.push({type:"degenerate-polygon",message:`Polygon ${t} has a near-zero normal; using fan triangulation.`,polygonIndex:t}),ae(e,t);const r=function(e){let t=0;for(let n=0;n<e.length;n++){const o=e[n],s=e[(n+1)%e.length];t+=o[0]*s[1]-s[0]*o[1]}return t/2}(s);if(Math.abs(r)<1e-12)return o.push({type:"degenerate-polygon",message:`Polygon ${t} projects to near-zero area; using fan triangulation.`,polygonIndex:t}),ae(e,t);const i=r>0,a=e.indices.map((e,t)=>t),l=[];let u=0;for(;a.length>3&&u++<e.indices.length*e.indices.length;){let n=!1;for(let o=0;o<a.length;o++){const r=a[(o+a.length-1)%a.length],u=a[o],c=a[(o+1)%a.length];if(le(s[r],s[u],s[c],i)&&!ue(s,a,r,u,c)){l.push({vertices:[e.startIndex+r,e.startIndex+u,e.startIndex+c],polyIndex:t}),a.splice(o,1),n=!0;break}}if(!n)return o.push({type:"triangulation-fallback",message:`Polygon ${t} could not be fully ear-clipped; using fan triangulation.`,polygonIndex:t}),ae(e,t)}return l.push({vertices:[e.startIndex+a[0],e.startIndex+a[1],e.startIndex+a[2]],polyIndex:t}),l}function ae(e,t){const n=[];for(let o=1;o<e.indices.length-1;o++)n.push({vertices:[e.startIndex,e.startIndex+o,e.startIndex+o+1],polyIndex:t});return n}function le(e,t,n,o){const s=(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0]);return o?s>1e-12:s<-1e-12}function ue(e,t,n,o,s){for(const r of t)if(r!==n&&r!==o&&r!==s&&ce(e[r],e[n],e[o],e[s]))return!0;return!1}function ce(e,t,n,o){const s=Math.abs(de(t,n,o)),r=Math.abs(de(e,t,n)),i=Math.abs(de(e,n,o)),a=Math.abs(de(e,o,t));return Math.abs(s-(r+i+a))<1e-10}function de(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function he(e,t,n,o,s,r,i){var a,l;const u=X(e,"MappingInformationType"),c=X(e,"ReferenceInformationType");if(!u||!c)return null;const d=null!==(a=Q(u,0))&&void 0!==a?a:"",h=null!==(l=Q(c,0))&&void 0!==l?l:"",m=X(e,t);if(!m)return null;const f=fe(_e(m));let p=null;if("IndexToDirect"===h){const t=X(e,n);t&&(p=pe(_e(t)))}const _=new Float64Array(o.length*r);for(let t=0;t<o.length;t++){const n=o[t];let s;s="ByPolygonVertex"===d?"IndexToDirect"===h&&p?p[n.globalIndex]:n.globalIndex:"ByControlPoint"===d||"ByVertice"===d?"IndexToDirect"===h&&p?p[n.controlPointIndex]:n.controlPointIndex:"ByPolygon"===d?"IndexToDirect"===h&&p?p[n.polyIndex]:n.polyIndex:"AllSame"===d?0:n.globalIndex;for(let n=0;n<r;n++){const o=s*r+n;s<0||o>=f.length?(i.push({type:o>=f.length?"layer-data-too-short":"layer-index-out-of-bounds",message:`Layer '${e.name}' references unavailable element ${s}.`,layerName:e.name,index:s}),_[t*r+n]=0):_[t*r+n]=f[o]}}return _}function me(e,t,n,o){if(!n||!o)return 1;const s=4*e,r=3*e,i=n[r],a=n[r+1],l=n[r+2],u=t[s],c=t[s+1],d=t[s+2];return(a*d-l*c)*o[r]+(l*u-i*d)*o[r+1]+(i*c-a*u)*o[r+2]<0?-1:1}function fe(e){if(e instanceof Float64Array)return e;if(e instanceof Float32Array)return new Float64Array(e);if(e instanceof Int32Array)return new Float64Array(e);if(Array.isArray(e)){const t=new Float64Array(e.length);for(let n=0;n<e.length;n++)t[n]=Number(e[n]);return t}throw new Error(`Cannot convert ${typeof e} to Float64Array`)}function pe(e){if(e instanceof Int32Array)return e;if(e instanceof Float64Array){const t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=Math.round(e[n]);return t}if(e instanceof Float32Array){const t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=Math.round(e[n]);return t}if(Array.isArray(e)){const t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=Math.round(Number(e[n]));return t}throw new Error(`Cannot convert ${typeof e} to Int32Array`)}function _e(e){return 1===e.properties.length?e.properties[0].value:e.properties.map(e=>e.value)}function ge(e,t,n){const o=e.get(t);if(o)return n?o.get(n):o.values().next().value}function ye(e,t,n,o=0){var s;return null===(s=xe(e,t,n))||void 0===s?void 0:s[o]}function ve(e,t,n,o){var s;return null!==(s=Te(ye(e,t,n)))&&void 0!==s?s:o}function be(e,t,n,o){const s=xe(e,t,n);if(!s)return o;const r=Te(s[0]),i=Te(s[1]),a=Te(s[2]);return void 0!==r&&void 0!==i&&void 0!==a?[r,i,a]:o}function xe(e,t,n){var o,s;return null!==(o=function(e,t){const n=[X(e,"Properties70"),X(e,"Properties60")].filter(e=>void 0!==e);for(const e of n)for(const n of e.children)if(("P"===n.name||"Property"===n.name)&&Q(n,0)===t)return n.properties.slice("Property"===n.name?3:4).map(e=>e.value)}(e,n))&&void 0!==o?o:null===(s=null==t?void 0:t.properties.get(n))||void 0===s?void 0:s.values}function Te(e){if("number"==typeof e)return e}function Ae(e,t,n){var o;const s=new Map,r=X(n,"Properties70");for(const e of null!==(o=null==r?void 0:r.children)&&void 0!==o?o:[]){if("P"!==e.name)continue;const t=Me(e);t&&s.set(t.name,t)}return{objectType:e,templateName:t,properties:s}}function Me(e){var t,n,o;const s=Q(e,0);return s?{name:s,propertyType:null!==(t=Q(e,1))&&void 0!==t?t:"",label:null!==(n=Q(e,2))&&void 0!==n?n:"",flags:null!==(o=Q(e,3))&&void 0!==o?o:"",values:e.properties.slice(4).map(e=>e.value)}:null}function we(e,t,n,o){var s,r,i,a;const l=Z(null!==(s=Q(e,1))&&void 0!==s?s:"Material"),u=function(e,t){var n,o;if(!t)return;const s=X(e,"ShadingModel"),r=s?Q(s,0):void 0;return"phong"===(null==r?void 0:r.toLowerCase())?null!==(n=ge(t,"Material","FbxSurfacePhong"))&&void 0!==n?n:ge(t,"Material"):"lambert"===(null==r?void 0:r.toLowerCase())&&null!==(o=ge(t,"Material","FbxSurfaceLambert"))&&void 0!==o?o:ge(t,"Material")}(e,o),c=X(e,"ShadingModel"),d="phong"===(c?null!==(r=Q(c,0))&&void 0!==r?r:"Lambert":null!==(i=ye(e,u,"ShadingModel"))&&void 0!==i?i:"Lambert").toLowerCase()?"Phong":"Lambert",h=function(e,t){var n,o,s,r,i;const a={};return a.diffuseColor=null!==(n=Ce(e,t,"DiffuseColor"))&&void 0!==n?n:Ce(e,t,"Diffuse"),a.diffuseFactor=Re(e,t,"DiffuseFactor"),a.ambientColor=null!==(o=Ce(e,t,"AmbientColor"))&&void 0!==o?o:Ce(e,t,"Ambient"),a.ambientFactor=Re(e,t,"AmbientFactor"),a.specularColor=null!==(s=Ce(e,t,"SpecularColor"))&&void 0!==s?s:Ce(e,t,"Specular"),a.specularFactor=Re(e,t,"SpecularFactor"),a.shininess=null!==(r=Re(e,t,"Shininess"))&&void 0!==r?r:Re(e,t,"ShininessExponent"),a.emissiveColor=null!==(i=Ce(e,t,"EmissiveColor"))&&void 0!==i?i:Ce(e,t,"Emissive"),a.emissiveFactor=Re(e,t,"EmissiveFactor"),a.opacity=Re(e,t,"Opacity"),a.transparencyFactor=Re(e,t,"TransparencyFactor"),a}(e,u),m=function(e,t,n){var o,s,r,i,a;const l=[],u=J(t,e,"Texture");for(const{id:e,node:c,propertyName:d}of u){const u=X(c,"FileName"),h=X(c,"RelativeFilename"),m=u&&null!==(o=Q(u,0))&&void 0!==o?o:"",f=h&&null!==(s=Q(h,0))&&void 0!==s?s:"";let p,_;const g=null!==(r=Re(c,n,"UVRotation"))&&void 0!==r?r:Re(c,n,"Rotation");let y;p=null!==(i=Oe(c,n,"UVTranslation"))&&void 0!==i?i:Oe(c,n,"Translation"),_=null!==(a=Oe(c,n,"UVScaling"))&&void 0!==a?a:Oe(c,n,"Scaling");const v=ye(c,n,"UVSet");v&&v.length>0&&(y=v),null!=p||(p=Fe(c,"ModelUVTranslation")),null!=_||(_=Fe(c,"ModelUVScaling"));let b=null;const x=J(t,e,"Video");for(const{node:e}of x){const t=X(e,"Content");if(t&&t.properties.length>0){const e=t.properties[0].value;e instanceof Uint8Array&&e.length>0?b=e:e instanceof ArrayBuffer&&e.byteLength>0&&(b=new Uint8Array(e))}}l.push({propertyName:null!=d?d:"DiffuseColor",fileName:m,relativeFileName:f,id:e,embeddedData:b,uvTranslation:p,uvScaling:_,uvRotation:g,uvSetName:y})}return l}(t,n,o?null!==(a=ge(o,"Texture","FbxFileTexture"))&&void 0!==a?a:ge(o,"Texture"):void 0);return{id:t,name:l,type:d,properties:h,textures:m}}function Ce(e,t,n){const o=xe(e,t,n);if(!o||o.length<3)return;const s=Se(o[0]),r=Se(o[1]),i=Se(o[2]);return void 0!==s&&void 0!==r&&void 0!==i?[s,r,i]:void 0}function Re(e,t,n){return Se(ye(e,t,n))}function Oe(e,t,n){const o=xe(e,t,n);if(!o)return;const s=Se(o[0]),r=Se(o[1]);return void 0!==s&&void 0!==r?[s,r]:void 0}function Se(e){if("number"==typeof e)return e}function Fe(e,t){var n,o;const s=X(e,t);if(!s)return;const r=Se(null===(n=s.properties[0])||void 0===n?void 0:n.value),i=Se(null===(o=s.properties[1])||void 0===o?void 0:o.value);return void 0!==r&&void 0!==i?[r,i]:void 0}function Ee(e,t,n){var o;const s=n.parentOf.get(e);if(!s)return null;const r=s.id,i=n.objects.get(r);if(!i||"Geometry"!==i.name)return null;const a=n.parentOf.get(r),l=a?n.objects.get(a.id):void 0,u="Model"===(null==l?void 0:l.name)?a.id:void 0,c=J(n,e,"Deformer");if(0===c.length)return null;const d=new Map;for(const{id:e,node:t}of c){if("Cluster"!==Q(t,2))continue;const o=J(n,e,"Model");o.length>0&&d.set(o[0].id,{clusterId:e,clusterNode:t})}const h=function(e,t){var n,o;const s=t.parentOf.get(e),r=s?t.objects.get(s.id):void 0,i="Model"===(null==r?void 0:r.name)?s.id:void 0;if(void 0===i)return new Map;for(const[,e]of Array.from(t.objects)){if("Pose"!==e.name||"BindPose"!==Q(e,2))continue;const t=new Map;for(const s of e.children){if("PoseNode"!==s.name)continue;const e=X(s,"Node"),r=X(s,"Matrix"),i=null===(n=null==e?void 0:e.properties[0])||void 0===n?void 0:n.value,a=null===(o=null==r?void 0:r.properties[0])||void 0===o?void 0:o.value;if("number"!=typeof i)continue;const l=Ge(a);16===(null==l?void 0:l.length)&&t.set(i,l)}if(t.has(i))return t}return new Map}(r,n),m=[],f=function(e,t,n,o){var s,r,i,a,l;const u=[],c=new Set,d=function(e,t){const n=new Set(Array.from(e.keys()));for(const o of Array.from(e.keys())){let e=Le(o,t);for(;void 0!==e;){const o=t.objects.get(e);if(!o||"Model"!==o.name)break;n.add(e),e=Le(e,t)}}return n}(e,n),h=function(e,t){const n=new Map;for(const o of Array.from(e)){let s=Le(o,t);for(;void 0!==s;){if(e.has(s)){n.set(o,s);break}s=Le(s,t)}}return n}(d,n),m=function(e,t){const n=new Map;for(const o of Array.from(e)){const e=t.get(o);void 0!==e&&(n.has(e)||n.set(e,[]),n.get(e).push(o))}return n}(d,h),f=Array.from(d).filter(e=>!h.has(e)).map(e=>({modelId:e,parentIndex:-1}));for(;f.length>0;){const{modelId:d,parentIndex:h}=f.shift();if(c.has(d))continue;c.add(d);const p=n.objects.get(d);if(!p)continue;const _=u.length,g=e.get(d),y=Ne(p),{bindPoseMatrix:v,transformLinkMatrix:b,transformAssociateModelMatrix:x,clusterMode:T}=g?Pe(g.clusterNode):{bindPoseMatrix:null,transformLinkMatrix:null,transformAssociateModelMatrix:null,clusterMode:"Unknown"},A=Be(d,Z(null!==(s=Q(p,1))&&void 0!==s?s:`Bone${_}`),void 0!==g,T,v,b,x,null!==(r=t.get(d))&&void 0!==r?r:null);o.push(...A),u.push({modelId:d,name:Z(null!==(i=Q(p,1))&&void 0!==i?i:`Bone${_}`),index:_,parentIndex:h,isCluster:void 0!==g,translation:y.translation,rotation:y.rotation,preRotation:y.preRotation,postRotation:y.postRotation,rotationPivot:y.rotationPivot,scalingPivot:y.scalingPivot,rotationOffset:y.rotationOffset,scalingOffset:y.scalingOffset,scale:y.scale,rotationOrder:y.rotationOrder,inheritType:y.inheritType,clusterMode:T,bindPoseMatrix:v,transformLinkMatrix:b,transformAssociateModelMatrix:x,modelBindPoseMatrix:null!==(a=t.get(d))&&void 0!==a?a:null,diagnostics:A});for(const e of null!==(l=m.get(d))&&void 0!==l?l:[])c.has(e)||f.push({modelId:e,parentIndex:_})}return u}(d,h,n,m);if(0===f.length)return null;const{boneIndices:p,boneWeights:_}=function(e,t){var n,o,s;let r=0;for(const o of e){const e=t.get(o.modelId);if(!e)continue;const s=X(e.clusterNode,"Indexes");if(!s)continue;const i=De(null===(n=s.properties[0])||void 0===n?void 0:n.value);if(i)for(let e=0;e<i.length;e++)i[e]>r&&(r=i[e])}const i=r+1,a=new Array(i),l=new Array(i);for(let e=0;e<i;e++)a[e]=[],l[e]=[];for(const n of e){const e=t.get(n.modelId);if(!e)continue;const r=X(e.clusterNode,"Indexes"),i=X(e.clusterNode,"Weights");if(!r||!i)continue;const u=De(null===(o=r.properties[0])||void 0===o?void 0:o.value),c=Ge(null===(s=i.properties[0])||void 0===s?void 0:s.value);if(u&&c)for(let e=0;e<u.length;e++){const t=u[e];a[t].push(n.index),l[t].push(c[e])}}for(let e=0;e<i;e++){if(0===a[e].length)continue;const t=a[e].map((t,n)=>({index:t,weight:l[e][n]}));t.sort((e,t)=>t.weight-e.weight);const n=t.slice(0,8);a[e]=n.map(e=>e.index),l[e]=n.map(e=>e.weight)}for(let e=0;e<i;e++){const t=l[e].reduce((e,t)=>e+t,0);if(t>0)for(let n=0;n<l[e].length;n++)l[e][n]/=t}return{boneIndices:a,boneWeights:l}}(f,d);return{id:e,geometryId:r,meshBindPoseMatrix:void 0!==u&&null!==(o=h.get(u))&&void 0!==o?o:null,bones:f,boneIndices:p,boneWeights:_,diagnostics:m}}function Le(e,t){const n=t.connections.find(n=>{var o;return"OO"===n.type&&n.childId===e&&"Model"===(null===(o=t.objects.get(n.parentId))||void 0===o?void 0:o.name)});return null==n?void 0:n.parentId}function Ie(e){const t=Q(e,2);return"Root"===t||"LimbNode"===t}function Ne(e){var t,n,o,s,r,i,a,l,u,c,d,h,m,f,p,_,g,y,v,b,x,T,A,M,w,C,R,O,S,F,E,L,I,N,P,B,k,D,G,V,H,K,U,$,W,z,j,q,Y,Z,J,ee,te,ne,oe,se,re,ie;const ae=[0,0,0],le=[0,0,0],ue=[0,0,0],ce=[0,0,0],de=[0,0,0],he=[0,0,0],me=[0,0,0],fe=[0,0,0],pe=[1,1,1];let _e=0,ge=1;const ye=X(e,"Properties70");if(!ye)return{translation:ae,rotation:le,preRotation:ue,postRotation:ce,rotationPivot:de,scalingPivot:he,rotationOffset:me,scalingOffset:fe,scale:pe,rotationOrder:_e,inheritType:ge};for(const e of ye.children){if("P"!==e.name)continue;const X=Q(e,0);if(X)switch(X){case"Lcl Translation":ae[0]=null!==(n=ke(null===(t=e.properties[4])||void 0===t?void 0:t.value))&&void 0!==n?n:0,ae[1]=null!==(s=ke(null===(o=e.properties[5])||void 0===o?void 0:o.value))&&void 0!==s?s:0,ae[2]=null!==(i=ke(null===(r=e.properties[6])||void 0===r?void 0:r.value))&&void 0!==i?i:0;break;case"Lcl Rotation":le[0]=null!==(l=ke(null===(a=e.properties[4])||void 0===a?void 0:a.value))&&void 0!==l?l:0,le[1]=null!==(c=ke(null===(u=e.properties[5])||void 0===u?void 0:u.value))&&void 0!==c?c:0,le[2]=null!==(h=ke(null===(d=e.properties[6])||void 0===d?void 0:d.value))&&void 0!==h?h:0;break;case"PreRotation":ue[0]=null!==(f=ke(null===(m=e.properties[4])||void 0===m?void 0:m.value))&&void 0!==f?f:0,ue[1]=null!==(_=ke(null===(p=e.properties[5])||void 0===p?void 0:p.value))&&void 0!==_?_:0,ue[2]=null!==(y=ke(null===(g=e.properties[6])||void 0===g?void 0:g.value))&&void 0!==y?y:0;break;case"PostRotation":ce[0]=null!==(b=ke(null===(v=e.properties[4])||void 0===v?void 0:v.value))&&void 0!==b?b:0,ce[1]=null!==(T=ke(null===(x=e.properties[5])||void 0===x?void 0:x.value))&&void 0!==T?T:0,ce[2]=null!==(M=ke(null===(A=e.properties[6])||void 0===A?void 0:A.value))&&void 0!==M?M:0;break;case"RotationPivot":de[0]=null!==(C=ke(null===(w=e.properties[4])||void 0===w?void 0:w.value))&&void 0!==C?C:0,de[1]=null!==(O=ke(null===(R=e.properties[5])||void 0===R?void 0:R.value))&&void 0!==O?O:0,de[2]=null!==(F=ke(null===(S=e.properties[6])||void 0===S?void 0:S.value))&&void 0!==F?F:0;break;case"ScalingPivot":he[0]=null!==(L=ke(null===(E=e.properties[4])||void 0===E?void 0:E.value))&&void 0!==L?L:0,he[1]=null!==(N=ke(null===(I=e.properties[5])||void 0===I?void 0:I.value))&&void 0!==N?N:0,he[2]=null!==(B=ke(null===(P=e.properties[6])||void 0===P?void 0:P.value))&&void 0!==B?B:0;break;case"RotationOffset":me[0]=null!==(D=ke(null===(k=e.properties[4])||void 0===k?void 0:k.value))&&void 0!==D?D:0,me[1]=null!==(V=ke(null===(G=e.properties[5])||void 0===G?void 0:G.value))&&void 0!==V?V:0,me[2]=null!==(K=ke(null===(H=e.properties[6])||void 0===H?void 0:H.value))&&void 0!==K?K:0;break;case"ScalingOffset":fe[0]=null!==($=ke(null===(U=e.properties[4])||void 0===U?void 0:U.value))&&void 0!==$?$:0,fe[1]=null!==(z=ke(null===(W=e.properties[5])||void 0===W?void 0:W.value))&&void 0!==z?z:0,fe[2]=null!==(q=ke(null===(j=e.properties[6])||void 0===j?void 0:j.value))&&void 0!==q?q:0;break;case"Lcl Scaling":pe[0]=null!==(Z=ke(null===(Y=e.properties[4])||void 0===Y?void 0:Y.value))&&void 0!==Z?Z:1,pe[1]=null!==(ee=ke(null===(J=e.properties[5])||void 0===J?void 0:J.value))&&void 0!==ee?ee:1,pe[2]=null!==(ne=ke(null===(te=e.properties[6])||void 0===te?void 0:te.value))&&void 0!==ne?ne:1;break;case"RotationOrder":_e=null!==(se=ke(null===(oe=e.properties[4])||void 0===oe?void 0:oe.value))&&void 0!==se?se:0;break;case"InheritType":ge=null!==(ie=ke(null===(re=e.properties[4])||void 0===re?void 0:re.value))&&void 0!==ie?ie:1}}return{translation:ae,rotation:le,preRotation:ue,postRotation:ce,rotationPivot:de,scalingPivot:he,rotationOffset:me,scalingOffset:fe,scale:pe,rotationOrder:_e,inheritType:ge}}function Pe(e){let t=null,n=null,o=null,s="Normalize";const r=X(e,"Transform");if(r&&r.properties[0]){const e=r.properties[0].value;e instanceof Float64Array&&16===e.length?t=e:e instanceof Float32Array&&16===e.length&&(t=new Float64Array(e))}const i=X(e,"TransformLink");if(i&&i.properties[0]){const e=i.properties[0].value;e instanceof Float64Array&&16===e.length?n=e:e instanceof Float32Array&&16===e.length&&(n=new Float64Array(e))}const a=X(e,"TransformAssociateModel");if(a&&a.properties[0]){const e=a.properties[0].value;e instanceof Float64Array&&16===e.length?o=e:e instanceof Float32Array&&16===e.length&&(o=new Float64Array(e))}const l=X(e,"Mode"),u=l?Q(l,0):void 0;return"Normalize"===u||"Additive"===u||"TotalOne"===u?s=u:u&&(s="Unknown"),{bindPoseMatrix:t,transformLinkMatrix:n,transformAssociateModelMatrix:o,clusterMode:s}}function Be(e,t,n,o,s,r,i,a){if(!n)return[];const l=[];return"Additive"!==o&&"TotalOne"!==o||l.push({type:"cluster-mode-runtime-unsupported",message:`Cluster mode '${o}' is preserved but not applied by Babylon linear blend skinning.`,boneModelId:e,boneName:t,clusterMode:o}),s||l.push({type:"missing-cluster-transform",message:"Cluster is missing Transform matrix; falling back to rest/bind-pose data.",boneModelId:e,boneName:t,clusterMode:o}),r||l.push({type:"missing-cluster-transform-link",message:"Cluster is missing TransformLink matrix; falling back to model bind pose or rest transform.",boneModelId:e,boneName:t,clusterMode:o}),a||l.push({type:"missing-bind-pose-matrix",message:"No BindPose matrix was found for this bone model.",boneModelId:e,boneName:t,clusterMode:o}),i&&l.push({type:"associate-model-present",message:"TransformAssociateModel is preserved for future associate-model skinning semantics.",boneModelId:e,boneName:t,clusterMode:o}),l}function ke(e){if("number"==typeof e)return e}function De(e){if(e instanceof Int32Array)return e;if(e instanceof Float64Array){const t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=Math.round(e[n]);return t}return null}function Ge(e){return e instanceof Float64Array?e:e instanceof Float32Array?new Float64Array(e):null}function Ve(e,t){var n;const o=null!==(n=function(e,t){if(0===e.length)return;const n=e.map(e=>He(e,t)),o=new Set(n[0]);for(const e of n.slice(1))for(const t of Array.from(o))e.includes(t)||o.delete(t);return n[0].find(e=>o.has(e))}(e,t))&&void 0!==n?n:e[0];let s=o,r=Ke(s,t);for(;void 0!==r;){const e=t.objects.get(r);if(!e||"Model"!==e.name||!Ie(e))break;s=r,r=Ke(r,t)}return s}function He(e,t){const n=[];let o=e;for(;void 0!==o;){const e=t.objects.get(o);if(!e||"Model"!==e.name)break;n.push(o),o=Ke(o,t)}return n}function Ke(e,t){const n=t.connections.find(n=>{var o;return"OO"===n.type&&n.childId===e&&"Model"===(null===(o=t.objects.get(n.parentId))||void 0===o?void 0:o.name)});return null==n?void 0:n.parentId}function Ue(e){var t,n,o;return null!==(o=null!==(n=null!==(t=e.find(e=>e.isCluster&&e.transformLinkMatrix))&&void 0!==t?t:e.find(e=>e.isCluster))&&void 0!==n?n:e.find(e=>e.modelBindPoseMatrix))&&void 0!==o?o:e[0]}function $e(e,t,n){if(e.length!==t.length)return!1;for(let o=0;o<e.length;o++)if(Math.abs(e[o]-t[o])>n)return!1;return!0}function We(e,t){var n;const o=t.objects.get(e);if(!o||"Model"!==o.name)return null;const s=Ne(o);return{modelId:e,name:Z(null!==(n=Q(o,1))&&void 0!==n?n:`Bone${e.toString()}`),index:-1,parentIndex:-1,isCluster:!1,translation:s.translation,rotation:s.rotation,preRotation:s.preRotation,postRotation:s.postRotation,rotationPivot:s.rotationPivot,scalingPivot:s.scalingPivot,rotationOffset:s.rotationOffset,scalingOffset:s.scalingOffset,scale:s.scale,rotationOrder:s.rotationOrder,inheritType:s.inheritType,clusterMode:"Unknown",bindPoseMatrix:null,transformLinkMatrix:null,transformAssociateModelMatrix:null,modelBindPoseMatrix:null,diagnostics:[]}}function ze(e,t){return e<t?-1:e>t?1:0}function je(e,t,n){var o,s;return(null!==(o=n.get(e))&&void 0!==o?o:Number.MAX_SAFE_INTEGER)-(null!==(s=n.get(t))&&void 0!==s?s:Number.MAX_SAFE_INTEGER)||ze(e,t)}const qe=46186158e3,Xe=1/23,Ye=1e-5,Qe=[24,25,30,48,50,60,100,120];function Ze(e,t,n){var o,s,r,i;const a=Z(null!==(o=Q(t,1))&&void 0!==o?o:"Animation"),l=function(e){var t,n,o,s;const r=X(e,"Properties70");if(!r)return null;let i=0,a=null;for(const e of r.children){if("P"!==e.name)continue;const r=Q(e,0);"LocalStart"===r||"ReferenceStart"===r?i=null!==(n=lt(null===(t=e.properties[4])||void 0===t?void 0:t.value))&&void 0!==n?n:i:"LocalStop"!==r&&"ReferenceStop"!==r||(a=null!==(s=lt(null===(o=e.properties[4])||void 0===o?void 0:o.value))&&void 0!==s?s:a)}return null!==a?{start:i,stop:a}:null}(t),u=J(n,e,"AnimationLayer");if(0===u.length)return null;const c=[],d=[],h=[],m=[];let f=1/0,p=0;for(const{id:e,node:t}of u){const o=Z(null!==(s=Q(t,1))&&void 0!==s?s:"Layer");let a=100,l=0;const u=X(t,"Properties70");if(u)for(const e of u.children){if("P"!==e.name)continue;const t=Q(e,0);if("Weight"===t){const t=null===(r=e.properties[4])||void 0===r?void 0:r.value;"number"==typeof t&&(a=t)}else if("BlendMode"===t){const t=null===(i=e.properties[4])||void 0===i?void 0:i.value;"number"==typeof t&&(l=t)}}const _=J(n,e,"AnimationCurveNode"),g=[],y=[],v=[];for(const{id:e,node:t}of _){const s=Je(e,t,n);if(!s){const s=et(e,t,n);if(s){tt(s.curves,e=>{e<f&&(f=e),e>p&&(p=e)}),y.push(s),d.push(s);const t={type:"unsupported-curve-node",message:`AnimationCurveNode '${s.type}' is preserved as diagnostic data but not evaluated at runtime.`,layerName:o,curveNodeId:e,curveNodeType:s.type,targetId:s.targetId,propertyName:s.propertyName};v.push(t),m.push(t)}continue}for(const e of s.curves)for(const t of e.keys)t.time<f&&(f=t.time),t.time>p&&(p=t.time);g.push(s),c.push(s)}h.push({name:o,weight:a,normalizedWeight:a/100,blendMode:l,curveNodes:g,unsupportedCurveNodes:y,diagnostics:v})}if(0===c.length&&0===d.length)return null;h.length>1&&m.push({type:"multiple-animation-layers",message:"Multiple animation layers are preserved, but runtime blending is not yet evaluated."});for(const e of h){if(0!==e.blendMode){const t={type:"unsupported-layer-blend-mode",message:`Animation layer blend mode ${e.blendMode} is preserved but not yet blended at runtime.`,layerName:e.name};e.diagnostics.push(t),m.push(t)}if(100!==e.weight){const t={type:"partial-layer-weight",message:`Animation layer weight ${e.weight} is preserved but not yet applied at runtime.`,layerName:e.name};e.diagnostics.push(t),m.push(t)}}const _=f>0&&isFinite(f)?f:0;if(_>0){for(const e of c)for(const t of e.curves)for(const e of t.keys)e.time-=_;for(const e of d)for(const t of e.curves)for(const e of t.keys)e.time-=_;p-=_}const g=l?Math.max(l.start-_,0):0,y=l?Math.max(l.stop-_,g):0,v=y>g,b=v?g:0,x=v?y:p;return{name:a,startTime:b,stopTime:x,duration:Math.max(x-b,0),curveNodes:c,layers:h,unsupportedCurveNodes:d,diagnostics:m}}function Je(e,t,n){var o;const s=Z(null!==(o=Q(t,1))&&void 0!==o?o:"");if("T"===s||"R"===s||"S"===s){const t=function(e,t){for(const n of t.connections)if(n.childId===e&&"OP"===n.type){const e=t.objects.get(n.parentId);if(e&&"Model"===e.name)return n.parentId}return null}(e,n);if(null===t)return null;const o=nt(e,n);return 0===o.length?null:{type:s,targetModelId:t,curves:o}}if("DeformPercent"===s){const t=function(e,t){for(const n of t.connections)if(n.childId===e&&"OP"===n.type){const e=t.objects.get(n.parentId);if(e&&"Deformer"===e.name&&"BlendShapeChannel"===Q(e,2))return n.parentId}for(const n of t.connections)if(n.childId===e&&"OO"===n.type){const e=t.objects.get(n.parentId);if(e&&"Deformer"===e.name&&"BlendShapeChannel"===Q(e,2))return n.parentId}return null}(e,n);if(null===t)return null;const o=nt(e,n);return 0===o.length?null:{type:"DeformPercent",targetModelId:t,curves:o}}return null}function et(e,t,n){var o;const s=Z(null!==(o=Q(t,1))&&void 0!==o?o:""),r=nt(e,n),i=function(e){var t,n;const o={},s=X(e,"Properties70");for(const e of null!==(t=null==s?void 0:s.children)&&void 0!==t?t:[]){if("P"!==e.name)continue;const t=Q(e,0);if(!(null==t?void 0:t.startsWith("d|")))continue;const s=ut(null===(n=e.properties[4])||void 0===n?void 0:n.value);null!==s&&(o[t]=s)}return o}(t);if(0===r.length&&0===Object.keys(i).length)return null;let a,l=null;for(const t of n.connections)if(t.childId===e&&"OP"===t.type){l=t.parentId,a=t.propertyName;break}return{type:s,id:e,targetId:l,propertyName:a,curveCount:r.length,curves:r,defaultValues:i}}function tt(e,t){for(const n of e)for(const e of n.keys)t(e.time)}function nt(e,t){var n;const o=[];for(const s of t.connections)if(s.parentId===e&&"OP"===s.type){const e=t.objects.get(s.childId);if(!e||"AnimationCurve"!==e.name)continue;const r=null!==(n=s.propertyName)&&void 0!==n?n:"d|X",i=ot(e);if(i.length>0){const t=st(e,i);o.push({channel:r,keys:t?rt(i):i,isSampled:t})}}if(0===o.length){const n=J(t,e,"AnimationCurve"),s=["d|X","d|Y","d|Z"];for(let e=0;e<n.length&&e<3;e++){const t=ot(n[e].node);if(t.length>0){const r=st(n[e].node,t);o.push({channel:s[e],keys:r?rt(t):t,isSampled:r})}}}return o}function ot(e){var t,n,o,s,r,i,a,l,u;const c=X(e,"KeyTime"),d=X(e,"KeyValueFloat");if(!c||!d)return[];const h=(g=null===(t=c.properties[0])||void 0===t?void 0:t.value)instanceof Float64Array?g:null,m=ct(null===(n=d.properties[0])||void 0===n?void 0:n.value),f=at(null===(s=null===(o=X(e,"KeyAttrFlags"))||void 0===o?void 0:o.properties[0])||void 0===s?void 0:s.value),p=ct(null===(i=null===(r=X(e,"KeyAttrDataFloat"))||void 0===r?void 0:r.properties[0])||void 0===i?void 0:i.value),_=at(null===(l=null===(a=X(e,"KeyAttrRefCount"))||void 0===a?void 0:a.properties[0])||void 0===l?void 0:l.value);var g;if(!h||!m)return[];if(h.length!==m.length)return[];const y=function(e,t,n){if(!t||0===t.length)return new Array(e).fill(-1);if(n&&n.length>0){let t=0;for(const e of n)t+=e;if(t===e){const e=[];for(let t=0;t<n.length;t++){const o=n[t];for(let n=0;n<o;n++)e.push(t)}return e}}return t.length===e?Array.from({length:e},(e,t)=>t):1===t.length?new Array(e).fill(0):Array.from({length:e},(e,n)=>Math.min(n,t.length-1))}(h.length,f,_),v=[];for(let e=0;e<h.length;e++){const t=y[e],n=t>=0&&null!==(u=null==f?void 0:f[t])&&void 0!==u?u:0,o=4*t;v.push({time:Number(h[e])/qe,value:m[e],interpolation:dt(n),constantMode:256&n?"next":"standard",rightSlope:ht(p,o),nextLeftSlope:ht(p,o+1)})}return v}function st(e,t){var n;return"FbxMayaSample Curve"===Z(null!==(n=Q(e,1))&&void 0!==n?n:"")||function(e){if(e.length<8)return!1;const t=[];for(let n=1;n<e.length;n++){const o=e[n].time-e[n-1].time;if(!(o>0))return!1;t.push(o)}const n=t.reduce((e,t)=>e+t,0)/t.length;if(n>Xe)return!1;const o=Math.max(1e-6,.05*n);if(t.some(e=>Math.abs(e-n)>o))return!1;const s=1/n;return!!Qe.some(e=>Math.abs(s-e)<=Math.max(.25,.02*e))&&!function(e){let t=!1,n=!0,o=!0,s=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,i=0;for(const t of e)s=Math.min(s,t.value),r=Math.max(r,t.value);for(let s=0;s<e.length-1;s++){const r=e[s],a=e[s+1];if("cubic"!==r.interpolation)continue;t=!0;const l=a.time-r.time;if(!(l>0))continue;const u=(a.value-r.value)/l,c=r.rightSlope,d=r.nextLeftSlope;if(void 0!==c&&void 0!==d){(Math.abs(c)>Ye||Math.abs(d)>Ye)&&(o=!1);for(const e of[.25,.5,.75]){const t=mt(r.value,a.value,c,d,l,e),n=r.value+e*l*u;i=Math.max(i,Math.abs(t-n))}}else n=!1}if(!t||!n||o)return!1;const a=r-s;return i>Math.max(1e-4,.01*a)}(e)}(t)}function rt(e){return e.map(e=>({time:e.time,value:e.value,interpolation:"linear"}))}function it(e,t){var n,o;if(!e||0===e.keys.length)return null;const s=e.keys;if(t<=s[0].time)return s[0].value;if(t>=s[s.length-1].time)return s[s.length-1].value;for(let r=0;r<s.length-1;r++){const i=s[r],a=s[r+1];if(t<i.time||t>a.time)continue;if(a.time===i.time)return i.value;if("constant"===i.interpolation)return"next"===i.constantMode?a.value:i.value;const l=a.time-i.time,u=(t-i.time)/l;if("cubic"===i.interpolation&&!e.isSampled){const e=(a.value-i.value)/l,t=null!==(n=i.rightSlope)&&void 0!==n?n:e,s=null!==(o=i.nextLeftSlope)&&void 0!==o?o:e;return mt(i.value,a.value,t,s,l,u)}return i.value+u*(a.value-i.value)}return s[s.length-1].value}function at(e){if(e instanceof Int32Array)return e;if(e instanceof Float32Array||e instanceof Float64Array){const t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}return null}function lt(e){return"number"==typeof e?e/qe:null}function ut(e){return"number"==typeof e?e:null}function ct(e){if(e instanceof Float32Array)return e;if(e instanceof Float64Array){const t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}return null}function dt(e){return 8&e?"cubic":4&e?"linear":2&e?"constant":"linear"}function ht(e,t){if(!e||t<0||t>=e.length)return;const n=e[t];return Number.isFinite(n)?n:void 0}function mt(e,t,n,o,s,r){const i=r*r,a=i*r;return(2*a-3*i+1)*e+(a-2*i+r)*s*n+(-2*a+3*i)*t+(a-i)*s*o}function ft(e,t,n){var o,s;const r=n.parentOf.get(e);if(!r)return null;const i=n.objects.get(r.id);if(!i||"Geometry"!==i.name)return null;const a=r.id,l=[],u=J(n,e,"Deformer");for(const{id:e,node:t}of u){if("BlendShapeChannel"!==Q(t,2))continue;const r=Z(null!==(o=Q(t,1))&&void 0!==o?o:"MorphTarget");let i=0;const a=X(t,"Properties70");if(a)for(const e of a.children)if("P"===e.name&&"DeformPercent"===Q(e,0)){const t=null===(s=e.properties[4])||void 0===s?void 0:s.value;"number"==typeof t&&(i=t)}const u=pt(t),c=[],d=J(n,e,"Geometry");for(const{node:e}of d){if("Shape"!==Q(e,2))continue;const t=yt(e);t&&c.push(t)}if(c.length>0){const t=[],n=_t(u,c,e,r,t);l.push({name:r,id:e,deformPercent:i,shapes:gt(c,n),fullWeights:n?[...n].sort((e,t)=>e-t):null,diagnostics:t})}}return 0===l.length?null:{id:e,geometryId:a,channels:l}}function pt(e){var t;const n=X(e,"FullWeights"),o=null===(t=null==n?void 0:n.properties[0])||void 0===t?void 0:t.value;return o&&(o instanceof Float64Array||o instanceof Float32Array||o instanceof Int32Array)?Array.from(o,e=>Number(e)):null}function _t(e,t,n,o,s){return e?e.length!==t.length?(1===t.length||s.push({type:"full-weights-mismatch",message:`FullWeights length ${e.length} does not match shape count ${t.length}; using the first shape for compatibility.`,channelId:n,channelName:o}),null):e:(t.length>1&&s.push({type:"missing-full-weights",message:"Blend shape channel has multiple shapes but no FullWeights; using the first shape for compatibility.",channelId:n,channelName:o}),null)}function gt(e,t){return t&&t.length===e.length?e.map((e,n)=>({shape:e,weight:t[n]})).sort((e,t)=>e.weight-t.weight).map(e=>e.shape):e.length>1?[e[0]]:e}function yt(e){var t,n,o;const s=X(e,"Indexes"),r=X(e,"Vertices");if(!s||!r)return null;const i=null===(t=s.properties[0])||void 0===t?void 0:t.value,a=null===(n=r.properties[0])||void 0===n?void 0:n.value;if(!i||!a)return null;const l=function(e){if(e instanceof Uint32Array)return e;if(e instanceof Int32Array||e instanceof Float32Array||e instanceof Float64Array){const t=new Uint32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}return null}(i);if(!l)return null;let u;if(a instanceof Float64Array)u=a;else{if(!(a instanceof Float32Array))return null;u=new Float64Array(a)}let c=null;const d=X(e,"Normals");if(d){const e=null===(o=d.properties[0])||void 0===o?void 0:o.value;e instanceof Float64Array?c=e:e instanceof Float32Array&&(c=new Float64Array(e))}return{indices:l,vertices:u,normals:c}}const vt=new Set(["Character","CharacterPose","ControlSet","ControlSetPlug","SelectionSet","CollectionExclusive"]);function bt(e){return"Skin"===e||"Cluster"===e||"BlendShape"===e||"BlendShapeChannel"===e}function xt(e,t,n,o,s){var r,i,a,l;return{type:o,message:s,objectId:t,objectName:Z(null!==(r=Q(n,1))&&void 0!==r?r:n.name),nodeName:n.name,subType:null!==(i=Q(n,2))&&void 0!==i?i:"",parentCount:e.connections.filter(e=>e.childId===t).length,childCount:null!==(l=null===(a=e.childrenOf.get(t))||void 0===a?void 0:a.length)&&void 0!==l?l:0}}function Tt(e){const t=function(e){var t,n;const o=new Map,s=[],r=new Map,i=new Map,a=[],l=[],u=[],c=new Map,d=new Map;let h=-1;const m=e=>{let t=c.get(e);return void 0===t&&(t=h--,c.set(e,t)),t},f=(e,t)=>{let n=d.get(e);n||(n=new Map,d.set(e,n));let o=n.get(t);return void 0===o&&(o=h--,n.set(t,o)),o},p=Y(e,"Objects");if(p)for(const e of p.children){const t=e.properties[0];if(t){const n=ee(t.value);if(void 0!==n)o.set(n,e),s.push({id:n,node:e,source:"Objects",synthetic:!1});else if("string"==typeof t.value){const n=Z(t.value),l=m(n),c=oe(e,l);if(o.set(l,c),s.push({id:l,node:c,source:"Objects",legacyName:n,synthetic:!1}),"Model"===e.name&&"Mesh"===Q(e,1)){const t=f("Geometry",n),c=se(e,t);o.set(t,c),s.push({id:t,node:c,source:"legacySyntheticGeometry",legacyName:n,synthetic:!0}),ne(a,r,i,u,"OO",t,l)}}}}const _=Y(e,"Connections");if(_)for(const e of _.children){if("C"!==e.name&&"Connect"!==e.name)continue;const s=l.length,d=Q(e,0),h=null===(t=e.properties[1])||void 0===t?void 0:t.value,m=null===(n=e.properties[2])||void 0===n?void 0:n.value,f={source:e.name,rawType:d,accepted:!1};if(l.push(f),"OO"!==d&&"OP"!==d){const e=void 0===h?void 0:te(h,c),t=void 0===m?void 0:te(m,c);u.push({reason:"unsupported-connection-type",message:`Unsupported FBX connection type '${null!=d?d:""}' was not added to the graph.`,connectionIndex:s,type:d,childId:e,parentId:t});continue}if(void 0===h||void 0===m){u.push({reason:"missing-connection-endpoint",message:"FBX connection is missing a child or parent endpoint.",connectionIndex:s,type:d});continue}const p=te(h,c),_=te(m,c);if(void 0===p||void 0===_){u.push({reason:"unresolved-legacy-endpoint",message:"FBX connection references a legacy string endpoint that is not present in the object table.",connectionIndex:s,type:d});continue}const g="OP"===d&&e.properties.length>3?Q(e,3):void 0;f.childId=p,f.parentId=_,f.propertyName=g,p===_&&u.push({reason:"self-loop",message:"FBX connection references the same object as child and parent.",connectionIndex:s,type:d,childId:p,parentId:_,propertyName:g}),o.has(p)||u.push({reason:"unresolved-object-reference",message:"FBX connection child ID is not present in the object table.",connectionIndex:s,type:d,childId:p,parentId:_,propertyName:g}),0===_||o.has(_)||u.push({reason:"unresolved-object-reference",message:"FBX connection parent ID is not present in the object table.",connectionIndex:s,type:d,childId:p,parentId:_,propertyName:g}),ne(a,r,i,u,d,p,_,g,s),f.accepted=!0}return{objects:o,objectEntries:s,childrenOf:r,parentOf:i,connections:a,connectionEntries:l,diagnostics:u}}(e),n=function(e){const t=new Map,n=Y(e,"Definitions");if(!n)return t;for(const e of n.children){if("ObjectType"!==e.name)continue;const n=Q(e,0);if(n)for(const o of e.children){if("PropertyTemplate"!==o.name)continue;const e=Q(o,0);if(!e)continue;const s=Ae(n,e,o);let r=t.get(n);r||(r=new Map,t.set(n,r)),r.set(e,s)}}return t}(e),o=function(e){var t;const n={upAxis:1,upAxisSign:1,frontAxis:2,frontAxisSign:1,coordAxis:0,coordAxisSign:1,unitScaleFactor:1},o=Y(e,"GlobalSettings");if(!o)return n;const s=o.children.find(e=>"Properties70"===e.name);if(!s)return n;for(const e of s.children){if("P"!==e.name)continue;const o=Q(e,0),s=Rt(null===(t=e.properties[4])||void 0===t?void 0:t.value);if(o&&void 0!==s)switch(o){case"UpAxis":n.upAxis=s;break;case"UpAxisSign":n.upAxisSign=s;break;case"FrontAxis":n.frontAxis=s;break;case"FrontAxisSign":n.frontAxisSign=s;break;case"CoordAxis":n.coordAxis=s;break;case"CoordAxisSign":n.coordAxisSign=s;break;case"UnitScaleFactor":n.unitScaleFactor=s}}return n}(e),s=[];for(const[e,o]of Array.from(t.objects))"Material"===o.name&&s.push(we(o,e,t,n));const r=[];for(const[e,n]of Array.from(t.objects))"Geometry"===n.name&&"Mesh"===Q(n,2)&&r.push(re(n,e));const i=function(e){const t=[];for(const[n,o]of Array.from(e.objects))if("Deformer"===o.name&&"Skin"===Q(o,2)){const o=Ee(n,0,e);o&&t.push(o)}return t}(t),a=function(e,t){if(0===t.length)return[];const n=new Map;for(const o of t){const t=o.bones.filter(e=>e.isCluster).map(e=>e.modelId);if(0===t.length)continue;const s=Ve(t,e),r=n.get(s);r?r.push(o):n.set(s,[o])}return Array.from(n.entries()).sort(([e],[t])=>ze(e,t)).map(([t,n])=>function(e,t,n){var o,s;const r=new Set,i=new Set,a=new Map,l=new Map;for(const e of t)for(const t of e.bones){l.has(t.modelId)||l.set(t.modelId,l.size);let e=a.get(t.modelId);if(e||(e=[],a.set(t.modelId,e)),e.push(t),t.isCluster){r.add(t.modelId);for(const e of He(t.modelId,n))i.add(e)}}const u=function(e){const t=[];for(const[n,o]of Array.from(e)){const e=o.filter(e=>e.isCluster&&e.transformLinkMatrix).map(e=>e.transformLinkMatrix);if(e.length<2)continue;const s=e[0];e.some(e=>!$e(s,e,1e-5))&&t.push(`Model ${n.toString()} has differing Cluster.TransformLink matrices across skins`)}return t}(a),c=new Map;for(const[e,t]of Array.from(a))c.set(e,Ue(t));const d=function(e,t){const n=new Map;for(const o of Array.from(e)){const s=Ke(o,t);void 0!==s&&e.has(s)&&n.set(o,s)}return n}(i,n),h=function(e,t,n){var o;const s=new Map;for(const n of Array.from(e)){const e=t.get(n);if(void 0===e)continue;let o=s.get(e);o||(o=[],s.set(e,o)),o.push(n)}for(const e of Array.from(s.values()))e.sort((e,t)=>je(e,t,n));const r=[],i=[...Array.from(e).filter(e=>!t.has(e)).sort((e,t)=>je(e,t,n))];for(;i.length>0;){const e=i.shift();r.push(e),i.push(...null!==(o=s.get(e))&&void 0!==o?o:[])}return r}(i,d,l),m=[],f=new Map;for(const e of h){const t=null!==(o=c.get(e))&&void 0!==o?o:We(e,n);if(!t)continue;const i=d.get(e),a=void 0===i?-1:null!==(s=f.get(i))&&void 0!==s?s:-1,l=m.length,u=Object.assign(Object.assign({},t),{index:l,parentIndex:a,isCluster:r.has(e)});m.push(u),f.set(e,l)}const p=t.map(t=>function(e,t,n){const o=e.bones.map(e=>{const o=n.get(e.modelId);if(void 0===o&&e.isCluster)throw new Error(`FBX rig resolver: cluster bone ${e.name} is missing from resolved rig ${t}`);return null!=o?o:-1});return{skinId:e.id,geometryId:e.geometryId,rigId:t,skinBoneIndexToRigBoneIndex:o,clusterModelIds:new Set(e.bones.filter(e=>e.isCluster).map(e=>e.modelId))}}(t,`rig_${e.toString()}`,f));return{id:`rig_${e.toString()}`,rootModelIds:m.filter(e=>e.parentIndex<0).map(e=>e.modelId),bones:m,modelIdToBoneIndex:f,clusterModelIds:r,skinBindings:p,warnings:u}}(t,n,e))}(t,i),l=function(e){const t=[];for(const[n,o]of Array.from(e.objects))if("Deformer"===o.name&&"BlendShape"===Q(o,2)){const o=ft(n,0,e);o&&t.push(o)}return t}(t),u=function(e){const t=[];for(const[n,o]of Array.from(e.objects))if("AnimationStack"===o.name){const s=Ze(n,o,e);s&&t.push(s)}return t}(t),c=function(e,t){var n,o,s,r;const i=[],a=null!==(n=ge(t,"NodeAttribute","FbxCamera"))&&void 0!==n?n:ge(t,"NodeAttribute");for(const[t,n]of Array.from(e.objects)){if("NodeAttribute"!==n.name)continue;if("Camera"!==Q(n,2))continue;const l=e.parentOf.get(t);if(!l)continue;const u=e.objects.get(l.id);if(!u||"Model"!==u.name)continue;const c=Z(null!==(o=Q(u,1))&&void 0!==o?o:"Camera"),d=ve(n,a,"NearPlane",.1),h=ve(n,a,"FarPlane",1e4),m=St(n,a),f=1===ve(n,a,"CameraProjectionType",0)||1===ve(n,a,"ProjectionType",0)?"orthographic":"perspective",p=Rt(ye(n,a,"FocalLength")),_=null!==(s=Rt(ye(n,a,"FilmWidth")))&&void 0!==s?s:Rt(ye(n,a,"ApertureWidth")),g=null!==(r=Rt(ye(n,a,"FilmHeight")))&&void 0!==r?r:Rt(ye(n,a,"ApertureHeight")),y=Rt(ye(n,a,"OrthoZoom")),v=Rt(ye(n,a,"Roll")),b=Ft(n,a,m,p,g),x=[];"orthographic"===f&&void 0===y&&x.push("Orthographic camera has no OrthoZoom; runtime orthographic bounds use a fallback."),void 0!==p&&void 0===g&&void 0===ye(n,a,"FieldOfView")&&x.push("FocalLength is present without FilmHeight; default field of view fallback may be used."),i.push({modelId:l.id,name:c,fieldOfView:b,nearPlane:d,farPlane:h,aspectRatio:m,projectionType:f,focalLength:p,filmWidth:_,filmHeight:g,orthoZoom:y,roll:v,unknownProperties:Et(n,wt),diagnostics:x})}return i}(t,n),d=function(e,t){var n,o,s,r,i;const a=[],l=null!==(n=ge(t,"NodeAttribute","FbxLight"))&&void 0!==n?n:ge(t,"NodeAttribute");for(const[t,n]of Array.from(e.objects)){if("NodeAttribute"!==n.name)continue;if("Light"!==Q(n,2))continue;const u=e.parentOf.get(t);if(!u)continue;const c=e.objects.get(u.id);if(!c||"Model"!==c.name)continue;const d=Z(null!==(o=Q(c,1))&&void 0!==o?o:"Light"),h=ve(n,l,"LightType",0),m=be(n,l,"Color",[1,1,1]),f=ve(n,l,"Intensity",100)/100,p=null!==(s=Rt(ye(n,l,"OuterAngle")))&&void 0!==s?s:Rt(ye(n,l,"ConeAngle")),_=Rt(ye(n,l,"InnerAngle")),g=null!=p?p:45,y=ve(n,l,"DecayType",2),v=Rt(ye(n,l,"DecayStart")),b=Ot(ye(n,l,"EnableNearAttenuation")),x=Ot(ye(n,l,"EnableFarAttenuation")),T=null!==(i=null!==(r=Ot(ye(n,l,"CastShadow")))&&void 0!==r?r:Ot(ye(c,void 0,"CastShadow")))&&void 0!==i?i:Ot(ye(c,void 0,"Shadow")),A=[];2!==y&&A.push(`DecayType ${y} is preserved as metadata; Babylon falloff is not remapped in this pass.`),void 0!==v&&A.push("DecayStart is preserved as metadata and is not mapped to Babylon light range."),a.push({modelId:u.id,name:d,lightType:h,color:m,intensity:f,coneAngle:g,decayType:y,innerAngle:_,outerAngle:p,decayStart:v,enableNearAttenuation:b,enableFarAttenuation:x,castShadows:T,unknownProperties:Et(n,Ct),diagnostics:A})}return a}(t,n),h=function(e){var t,n;const o=e.diagnostics.map(t=>({type:"connection-graph",message:t.message,objectId:t.childId,subType:t.reason,parentCount:void 0===t.childId?void 0:e.connections.filter(e=>e.childId===t.childId).length}));for(const[s,r]of Array.from(e.objects)){const i=null!==(t=Q(r,2))&&void 0!==t?t:"";"Constraint"!==r.name?vt.has(r.name)?o.push(xt(e,s,r,"unsupported-helper",`${r.name} helper data is preserved as diagnostic data but not evaluated at runtime.`)):"LayeredTexture"!==r.name?"Pose"!==r.name||"BindPose"===i?"Deformer"!==r.name||bt(i)?"NodeAttribute"===r.name&&i&&"Camera"!==i&&"Light"!==i&&o.push(xt(e,s,r,"unsupported-node-attribute",`NodeAttribute subtype '${i}' is preserved as diagnostic data but not converted to a Babylon object.`)):o.push(xt(e,s,r,"unsupported-deformer",`Deformer subtype '${i}' is preserved as diagnostic data but not evaluated at runtime.`)):o.push(xt(e,s,r,"unsupported-pose",`Pose subtype '${i}' is preserved as diagnostic data but not evaluated at runtime.`)):o.push(xt(e,s,r,"unsupported-layered-texture","LayeredTexture is preserved as diagnostic data; runtime texture layer blending is not implemented.")):o.push(xt(e,s,r,"unsupported-constraint",`Constraint '${i||Z(null!==(n=Q(r,1))&&void 0!==n?n:"")}' is preserved as diagnostic data but not evaluated at runtime.`))}return o}(t),m=function(e,t,n,o){var s;const r=new Map;for(const e of t)r.set(e.id,e);const i=new Map;for(const e of n)i.set(e.id,e);const a=null!==(s=e.childrenOf.get(0))&&void 0!==s?s:[],l=[];for(const{id:t}of a){const n=e.objects.get(t);n&&"Model"===n.name&&l.push(At(t,n,e,r,i,o))}return l}(t,r,s,n);return Object.assign({rootModels:m,geometries:r,materials:s,skins:i,rigs:a,blendShapes:l,animations:u,cameras:c,lights:d,diagnostics:h},o)}function At(e,t,n,o,s,r){var i,a,l;const u=Z(null!==(i=Q(t,1))&&void 0!==i?i:"Model"),c=null!==(a=Q(t,2))&&void 0!==a?a:"Null",d=J(n,e,"Geometry"),h=d.length>0?o.get(d[0].id):void 0,m=J(n,e,"Material"),f=[];for(const{id:e}of m){const t=s.get(e);t&&f.push(t)}const p=function(e,t){const n=be(e,t,"Lcl Translation",[0,0,0]),o=be(e,t,"Lcl Rotation",[0,0,0]),s=be(e,t,"Lcl Scaling",[1,1,1]),r=be(e,t,"PreRotation",[0,0,0]),i=be(e,t,"PostRotation",[0,0,0]),a=be(e,t,"RotationPivot",[0,0,0]),l=be(e,t,"ScalingPivot",[0,0,0]),u=be(e,t,"RotationOffset",[0,0,0]),c=be(e,t,"ScalingOffset",[0,0,0]),d=be(e,t,"GeometricTranslation",[0,0,0]),h=be(e,t,"GeometricRotation",[0,0,0]),m=be(e,t,"GeometricScaling",[1,1,1]),f=ve(e,t,"RotationOrder",0),p=ve(e,t,"InheritType",1);return{translation:n,rotation:o,scale:s,preRotation:r,postRotation:i,rotationPivot:a,scalingPivot:l,rotationOffset:u,scalingOffset:c,geometricTranslation:d,geometricRotation:h,geometricScaling:m,rotationOrder:f,inheritType:p,diagnostics:1!==p&&2!==p?[`InheritType ${p} is parsed and preserved; runtime parent-scale inheritance remains gated to avoid changing existing visual behavior without a fixture-specific baseline.`]:[]}}(t,null!==(l=ge(r,"Model","FbxNode"))&&void 0!==l?l:ge(r,"Model")),_=J(n,e,"Model"),g=[];for(const{id:e,node:t}of _)g.push(At(e,t,n,o,s,r));const y=t.children.find(e=>"Culling"===e.name),v=!!y&&"CullingOff"===Q(y,0),b=function(e){var t;const n=X(e,"Properties70");if(!n)return;const o={};let s=!1;for(const e of n.children){if("P"!==e.name)continue;const n=Q(e,0);if(!n||Mt.has(n))continue;const r=null===(t=e.properties[4])||void 0===t?void 0:t.value;void 0!==r&&("string"==typeof r||"number"==typeof r||"boolean"==typeof r)&&(o[n]=r,s=!0)}return s?o:void 0}(t);return Object.assign({id:e,name:u,subType:c,geometry:h,materials:f,children:g,cullingOff:v,customProperties:b},p)}const Mt=new Set(["Lcl Translation","Lcl Rotation","Lcl Scaling","PreRotation","PostRotation","RotationPivot","ScalingPivot","RotationOffset","ScalingOffset","RotationOrder","GeometricTranslation","GeometricRotation","GeometricScaling","Visibility","InheritType","ScalingMax","DefaultAttributeIndex","currentUVSet","lockInfluenceWeights"]),wt=new Set(["FieldOfView","FieldOfViewX","FieldOfViewY","NearPlane","FarPlane","AspectWidth","AspectHeight","FilmAspectRatio","FocalLength","FilmWidth","FilmHeight","ApertureWidth","ApertureHeight","CameraProjectionType","ProjectionType","OrthoZoom","Roll","ApertureMode"]),Ct=new Set(["LightType","Color","Intensity","InnerAngle","OuterAngle","ConeAngle","DecayType","DecayStart","EnableNearAttenuation","EnableFarAttenuation","CastShadow","Shadow"]);function Rt(e){if("number"==typeof e)return e}function Ot(e){return"boolean"==typeof e?e:"number"==typeof e?0!==e:void 0}function St(e,t){const n=Rt(ye(e,t,"FilmAspectRatio"));if(void 0!==n&&n>0)return n;const o=Rt(ye(e,t,"AspectWidth")),s=Rt(ye(e,t,"AspectHeight"));return void 0!==o&&void 0!==s&&o>0&&s>0?o/s:0}function Ft(e,t,n,o,s){var r;const i=null!==(r=Rt(ye(e,t,"FieldOfViewY")))&&void 0!==r?r:Rt(ye(e,t,"FieldOfView"));if(void 0!==i)return i;const a=Rt(ye(e,t,"FieldOfViewX"));return void 0!==a?n>0?Lt(2*Math.atan(Math.tan(a*Math.PI/180/2)/n)):a:void 0!==o&&o>0&&void 0!==s&&s>0?Lt(2*Math.atan(25.4*s/(2*o))):45}function Et(e,t){var n;const o=new Set;for(const s of["Properties70","Properties60"]){const r=X(e,s);for(const e of null!==(n=null==r?void 0:r.children)&&void 0!==n?n:[]){if("P"!==e.name&&"Property"!==e.name)continue;const n=Q(e,0);n&&!t.has(n)&&o.add(n)}}return Array.from(o).sort()}function Lt(e){return 180*e/Math.PI}function It(e,n,o){const s=t.Matrix.RotationX(e),r=t.Matrix.RotationY(n),i=t.Matrix.RotationZ(o);return s.multiply(r).multiply(i)}function Nt(e,n,o,s){const r=t.Matrix.RotationX(e),i=t.Matrix.RotationY(n),a=t.Matrix.RotationZ(o);switch(s){case 0:default:return r.multiply(i).multiply(a);case 1:return r.multiply(a).multiply(i);case 2:return i.multiply(a).multiply(r);case 3:return i.multiply(r).multiply(a);case 4:return a.multiply(r).multiply(i);case 5:return a.multiply(i).multiply(r)}}function Pt(e,n){const o=Math.PI/180,s=t.Matrix.Scaling(n[0],n[1],n[2]),r=It(e[0]*o,e[1]*o,e[2]*o);return s.multiply(r)}const Bt={name:"fbx",extensions:{".fbx":{isBinary:!0}}};class kt{constructor(e={}){var t;this.name=Bt.name,this.extensions=Bt.extensions,this._bindRestBones=new WeakSet,this._sourceBonesBySkeleton=new WeakMap,this._scaleCompensationHelpersBySkeleton=new WeakMap,this._options={normalMapCoordinateSystem:null!==(t=e.normalMapCoordinateSystem)&&void 0!==t?t:"y-up"}}createPlugin(e){return new kt(e[Bt.name])}importMeshAsync(e,t,n,o,s,r){return b(this,void 0,void 0,function*(){const s=Tt(this._parse(n));return this._buildScene(s,t,o,e)})}loadAsync(e,t,n,o,s){return b(this,void 0,void 0,function*(){const o=Tt(this._parse(t));this._buildScene(o,e,n,null)})}loadAssetContainerAsync(e,n,o,s,r){return b(this,void 0,void 0,function*(){const s=Tt(this._parse(n)),r=new t.AssetContainer(e),i=this._buildScene(s,e,o,null);for(const e of i.meshes)r.meshes.push(e);for(const e of i.skeletons)r.skeletons.push(e);for(const e of i.animationGroups)r.animationGroups.push(e);for(const e of i.transformNodes)r.transformNodes.push(e);for(const e of i.lights)r.lights.push(e);for(const e of i.cameras)r.cameras.push(e);for(const e of i.materials)this._addMaterialToContainer(e,r);for(const e of i.textures)this._addTextureToContainer(e,r);for(const e of i.meshes)this._addMaterialToContainer(e.material,r);return this._setAssetContainer(r),r.removeAllFromScene(),r})}_parse(e){if(e instanceof ArrayBuffer)return this._parseFromArrayBuffer(e);if(ArrayBuffer.isView(e)){const t=e,n=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);return this._parseFromArrayBuffer(n)}if("string"==typeof e)return U(e);throw new Error("FBXFileLoader: unsupported data type")}_parseFromArrayBuffer(e){const t=new Uint8Array(e,0,Math.min(21,e.byteLength));if(String.fromCharCode(...t).startsWith("Kaydara FBX Binary"))return function(e){const t=new DataView(e),n=new Uint8Array(e);if("Kaydara FBX Binary \0"!==K(n,0,21))throw new Error("Not a valid binary FBX file");if(e.byteLength<27)throw new Error("Truncated binary FBX header");const o=t.getUint32(23,!0),s=o>=7500,r=[];let i=27;for(;i<e.byteLength;){const o=B(t,n,i,s,e.byteLength);if(null===o)break;r.push(o.node),i=o.endOffset}return{version:o,nodes:r}}(e);const n=new TextDecoder("utf-8").decode(e);if(n.trimStart().startsWith("; FBX"))return U(n);throw new Error("FBXFileLoader: unrecognized FBX format")}_buildScene(e,n,o,s){var r;const i=this._buildNameFilter(s),a=new Map;for(const t of e.materials){const e=this._createMaterial(t,n,o);a.set(t.id,e)}const l=[],u=new Map,c=new Map,d=new Map,h=new Map,m=new Map;for(const t of e.skins)m.set(t.id,t);for(const t of e.rigs){const e=this._createSkeleton(t.id,t.bones,n);l.push(e),u.set(t.id,e);for(const n of t.skinBindings){const t=m.get(n.skinId);t&&(c.set(n.geometryId,e),d.set(n.geometryId,t),h.set(n.geometryId,n))}}const f=new Map,p=e=>{for(const t of e)f.set(t.id,t),p(t.children)};p(e.rootModels);const _=kt._collectCullingConflictMaterialIds(e.rootModels),g=new Map,y=new t.TransformNode("__fbx_root__",n);n.useRightHandedSystem||(y.rotation.y=Math.PI,y.scaling.z=-1);const v=[],b=[y];let x=y;const T=kt._computeFBXAxisConversionMatrix(e);T.equals(t.Matrix.Identity())||(x=new t.TransformNode("__fbx_axis_conversion__",n),x.parent=y,kt._applyMatrixToTransform(x,T),b.push(x));const A=new Map,M=t.Matrix.Identity();for(const t of e.rootModels)this._buildModel(t,n,x,x,M,a,i,v,b,c,d,h,A,_,g);this._linkSkeletonsToTransformNodes(e.rigs,u,A,b,n);for(const n of e.rigs){const e=u.get(n.id);if(!e)continue;const o=null!==(r=v.find(t=>t.skeleton===e))&&void 0!==r?r:null,s=null!=o?o:y,i=new Set;for(const t of e.bones){const e=t.getTransformNode();e&&i.add(e)}for(const r of n.bones){if(!r.isCluster)continue;const n=A.get(r.modelId),a=this._getSourceBone(e,r.index);if(n&&a)for(const r of[...n.getChildren()]){const n=r;if(!i.has(n)){const r=n.computeWorldMatrix(!0).clone(),i=kt._getBoneReferenceWorldMatrix(e,a,s,o),l=new t.Matrix;i.invertToRef(l);const u=r.multiply(l);n.parent=null,n.attachToBone(a,s),kt._applyMatrixToTransform(n,u)}}}}e.blendShapes.length>0&&this._applyBlendShapes(e.blendShapes,v,n);const w=[];for(const t of e.animations){const o=this._createAnimationGroup(t,e.rigs,u,n,A,f,v);o&&w.push(o)}const C=[];for(const t of e.cameras){const e=this._createCamera(t,A,n);e&&C.push(e)}const R=[];for(const t of e.lights){const e=this._createLight(t,A,n);e&&R.push(e)}return{meshes:v,particleSystems:[],skeletons:l,animationGroups:w,transformNodes:b,geometries:[],lights:R,spriteManagers:[],materials:Array.from(a.values()),textures:Array.from(new Set(Array.from(a.values()).flatMap(e=>e.getActiveTextures()))),cameras:C}}_addMaterialToContainer(e,n){if(e){if(e instanceof t.MultiMaterial){n.multiMaterials.includes(e)||n.multiMaterials.push(e);for(const t of e.subMaterials)this._addMaterialToContainer(t,n)}else n.materials.includes(e)||n.materials.push(e);for(const t of e.getActiveTextures())this._addTextureToContainer(t,n)}}_addTextureToContainer(e,t){t.textures.includes(e)||t.textures.push(e)}_setAssetContainer(e){for(const t of e.meshes)t._parentContainer=e;for(const t of e.transformNodes)t._parentContainer=e;for(const t of e.skeletons)t._parentContainer=e;for(const t of e.animationGroups)t._parentContainer=e;for(const t of e.lights)t._parentContainer=e;for(const t of e.cameras)t._parentContainer=e;for(const t of e.materials)t._parentContainer=e;for(const t of e.multiMaterials)t._parentContainer=e;for(const t of e.textures)t._parentContainer=e}static _computeFBXAxisConversionMatrix(e){const n=[[0,0,0],[0,0,0],[0,0,0]],o=(e,t,o)=>{if(e<0||e>2)return;const s=[0,0,0];s[o]=t>=0?1:-1,n[e]=s};return o(e.coordAxis,e.coordAxisSign,0),o(e.upAxis,e.upAxisSign,1),o(e.frontAxis,e.frontAxisSign,2),n.some(e=>e.every(e=>0===e))?t.Matrix.Identity():t.Matrix.FromValues(n[0][0],n[0][1],n[0][2],0,n[1][0],n[1][1],n[1][2],0,n[2][0],n[2][1],n[2][2],0,0,0,0,1)}_buildModel(e,n,o,s,r,i,a,l,u,c,d,h,m,f,p){var _,g;const y=kt._computeFBXModelLocalMatrix(e).multiply(r);if(!e.geometry||"Mesh"!==e.subType||a&&!a(e.name)){if(e.geometry&&"Mesh"===e.subType&&a&&!kt._modelSubtreeMatchesNameFilter(e,a))return;const r=new t.TransformNode(e.name,n);o&&(r.parent=o),kt._applyFBXTransform(r,e),u.push(r),m.set(e.id,r),kt._applyModelMetadata(r,e);for(const t of e.children)this._buildModel(t,n,r,s,y,i,a,l,u,c,d,h,m,f,p)}else{const r=c.get(e.geometry.id),v=d.get(e.geometry.id),b=h.get(e.geometry.id);r&&v&&(r.needInitialSkinMatrix=!0);const x=this._createMesh(e,e.geometry,n,r,v,b);if(r&&v){const e=v.meshBindPoseMatrix?t.Matrix.FromArray(v.meshBindPoseMatrix):y;x.parent=s,kt._applyMatrixToTransform(x,e),x.computeWorldMatrix(!0),x.updatePoseMatrix(t.Matrix.Invert(e)),x.alwaysSelectAsActiveMesh=!0}else o&&(x.parent=o),kt._applyFBXTransform(x,e);if(e.materials.length>1&&(null===(_=e.geometry)||void 0===_?void 0:_.materialIndices))this._applyMultiMaterial(x,e,i,n,f,p);else if(e.materials.length>0){const t=i.get(e.materials[0].id);t&&(x.material=kt._getModelMaterial(t,e,p,f.has(e.materials[0].id)))}(null===(g=e.geometry)||void 0===g?void 0:g.colors)&&this._useUnmodulatedVertexColorMaterials(x,n),this._applyMaterialUVSetCoordinates(x.material,e.geometry),l.push(x),m.set(e.id,x),kt._applyModelMetadata(x,e);for(const t of e.children)this._buildModel(t,n,x,s,y,i,a,l,u,c,d,h,m,f,p)}}_linkSkeletonsToTransformNodes(e,n,o,s,r){for(const i of e){const e=n.get(i.id);if(e)for(const n of i.bones){const i=this._getSourceBone(e,n.index),a=o.get(n.modelId);if(!i||!a)continue;const l=this._getScaleCompensationHelper(e,n.index);if(l){const e=new t.TransformNode(l.name,r);e.parent=a.parent,a.parent=e,kt._applyMatrixToTransform(e,l.getLocalMatrix()),kt._applyMatrixToTransform(a,i.getLocalMatrix()),l.linkTransformNode(e),s.push(e)}else kt._applyMatrixToTransform(a,i.getLocalMatrix());i.linkTransformNode(a)}}}static _modelSubtreeMatchesNameFilter(e,t){for(const n of e.children){if(n.geometry&&"Mesh"===n.subType&&t(n.name))return!0;if(kt._modelSubtreeMatchesNameFilter(n,t))return!0}return!1}static _applyModelMetadata(e,t){var n;(t.customProperties||0!==t.diagnostics.length)&&(e.metadata=Object.assign(Object.assign(Object.assign({},null!==(n=e.metadata)&&void 0!==n?n:{}),t.customProperties?{fbxCustomProperties:t.customProperties}:{}),t.diagnostics.length>0?{fbxDiagnostics:t.diagnostics}:{}))}_createMesh(e,n,o,s,r,i){var a;const l=new t.Mesh(e.name,o);l.sideOrientation=o.useRightHandedSystem?t.Material.CounterClockWiseSideOrientation:t.Material.ClockWiseSideOrientation;const u=new t.VertexData,c=Dt(n.positions),d=e.geometricTranslation,h=e.geometricRotation,m=e.geometricScaling,f=kt._computeFBXGeometricMatrix(d,h,m),p=kt._computeFBXGeometricDeltaMatrix(h,m),_=kt._computeFBXGeometricNormalMatrix(h,m),g=!f.equals(t.Matrix.Identity()),y=!p.equals(t.Matrix.Identity()),v=!_.equals(t.Matrix.Identity());if(g)for(let e=0;e<c.length;e+=3){const n=t.Vector3.TransformCoordinates(new t.Vector3(c[e],c[e+1],c[e+2]),f);c[e]=n.x,c[e+1]=n.y,c[e+2]=n.z}let b;if(u.positions=c,u.indices=Array.from(n.indices),n.normals){if(b=Dt(n.normals),v)for(let e=0;e<b.length;e+=3){const n=t.Vector3.TransformNormal(new t.Vector3(b[e],b[e+1],b[e+2]),_);n.lengthSquared()>0&&n.normalize(),b[e]=n.x,b[e+1]=n.y,b[e+2]=n.z}u.normals=b}if(n.uvs&&(u.uvs=Dt(n.uvs)),n.uvSets.length>1&&(u.uvs2=Dt(n.uvSets[1].data)),n.uvSets.length>2&&(u.uvs3=Dt(n.uvSets[2].data)),n.uvSets.length>3&&(u.uvs4=Dt(n.uvSets[3].data)),n.uvSets.length>4&&(u.uvs5=Dt(n.uvSets[4].data)),n.uvSets.length>5&&(u.uvs6=Dt(n.uvSets[5].data)),n.tangents){const e=Dt(n.tangents);if(v)for(let n=0;n<e.length;n+=4){const o=t.Vector3.TransformNormal(new t.Vector3(e[n],e[n+1],e[n+2]),_);o.lengthSquared()>0&&o.normalize(),e[n]=o.x,e[n+1]=o.y,e[n+2]=o.z}!function(e,t){if(1!==t)for(let n=3;n<e.length;n+=4)e[n]*=t}(e,this._getNormalMapTangentHandednessScale()),u.tangents=e}else b&&u.uvs&&(u.tangents=function(e,t,n,o,s=1,r=null,i=null){var a,l,u,c,d,h;const m=e.length/3,f=new Map,p=new Array(m).fill(null);for(let s=0;s+2<o.length;s+=3){const a=i?i[s/3]:0,l=o[s],u=o[s+1],c=o[s+2],d=3*l,h=3*u,m=3*c,_=2*l,g=2*u,y=2*c,v=e[h]-e[d],b=e[m]-e[d],x=e[h+1]-e[d+1],T=e[m+1]-e[d+1],A=e[h+2]-e[d+2],M=e[m+2]-e[d+2],w=n[g]-n[_],C=n[y]-n[_],R=n[g+1]-n[_+1],O=n[y+1]-n[_+1],S=w*O-C*R;if(Math.abs(S)<1e-8)continue;const F=1/S,E=(O*v-R*b)*F,L=(O*x-R*T)*F,I=(O*A-R*M)*F,N=(w*b-C*v)*F,P=(w*T-C*x)*F,B=(w*M-C*A)*F;Gt(l,u,c,E,L,I,N,P,B,e,t,n,r,a,f,p),Gt(u,c,l,E,L,I,N,P,B,e,t,n,r,a,f,p),Gt(c,l,u,E,L,I,N,P,B,e,t,n,r,a,f,p)}const _=new Float32Array(4*m);for(let e=0;e<m;e++){const n=3*e,o=4*e,[r,i,m]=Vt(t[n],t[n+1],t[n+2]),g=p[e]?f.get(p[e]):void 0,y=null!==(a=null==g?void 0:g.tx)&&void 0!==a?a:0,v=null!==(l=null==g?void 0:g.ty)&&void 0!==l?l:0,b=null!==(u=null==g?void 0:g.tz)&&void 0!==u?u:0,x=r*y+i*v+m*b;let T=y-r*x,A=v-i*x,M=b-m*x;const w=Math.hypot(T,A,M);w>1e-8?(T/=w,A/=w,M/=w):[T,A,M]=Kt(r,i,m);const C=null!==(c=null==g?void 0:g.bx)&&void 0!==c?c:0,R=null!==(d=null==g?void 0:g.by)&&void 0!==d?d:0,O=null!==(h=null==g?void 0:g.bz)&&void 0!==h?h:0,S=i*M-m*A,F=m*T-r*M,E=r*A-i*T,L=Math.hypot(C,R,O)>1e-8&&S*C+F*R+E*O<0?-1:1;_[o]=T,_[o+1]=A,_[o+2]=M,_[o+3]=L*s}return _}(c,b,u.uvs,n.indices,this._getNormalMapTangentHandednessScale(),n.controlPointIndices,n.materialIndices));if(n.colors){const e=new Float32Array(n.colors.length);for(let t=0;t<e.length;t+=4)e[t]=n.colors[t],e[t+1]=n.colors[t+1],e[t+2]=n.colors[t+2],e[t+3]=1;u.colors=e,l.hasVertexAlpha=!1}if(s&&r){const{matricesIndices:e,matricesWeights:t,matricesIndicesExtra:o,matricesWeightsExtra:s,numBoneInfluencers:a}=this._buildSkinningData(n,r,i);u.matricesIndices=e,u.matricesWeights=t,o&&s&&(u.matricesIndicesExtra=o,u.matricesWeightsExtra=s),l.numBoneInfluencers=a}return u.applyToMesh(l),l.metadata=Object.assign(Object.assign({},null!==(a=l.metadata)&&void 0!==a?a:{}),{fbxGeometryId:n.id,fbxControlPointIndices:n.controlPointIndices,fbxGeometryDeltaMatrix:y?p:null,fbxGeometryNormalMatrix:v?_:null,fbxPreRotMatrix:y?p:null}),s&&(l.skeleton=s),l}_applyMultiMaterial(e,n,o,s,r,i){const a=n.geometry.materialIndices,l=e.getIndices();if(!l)return;const u=l.length/3,c=new Map;for(let e=0;e<u;e++){const t=e<a.length?a[e]:0;let n=c.get(t);n||(n=[],c.set(t,n)),n.push(e)}const d=Array.from(c.keys()).sort((e,t)=>e-t),h=[],m=[];for(const e of d){const t=c.get(e),n=h.length;for(const e of t)h.push(l[3*e],l[3*e+1],l[3*e+2]);m.push({start:n,count:3*t.length,matIdx:e})}e.setIndices(h);const f=new t.MultiMaterial(n.name+"_multi",s);for(const e of m){const t=n.materials[e.matIdx];if(t){const e=o.get(t.id);e?f.subMaterials.push(kt._getModelMaterial(e,n,i,r.has(t.id))):f.subMaterials.push(null)}else f.subMaterials.push(null)}e.material=f,e.subMeshes=[];const p=e.getTotalVertices();for(let n=0;n<m.length;n++){const o=m[n];new t.SubMesh(n,0,p,o.start,o.count,e)}}static _collectCullingConflictMaterialIds(e){const t=new Map,n=e=>{var o;for(const n of e.materials){const s=null!==(o=t.get(n.id))&&void 0!==o?o:{cullingOff:!1,cullingOn:!1};e.cullingOff?s.cullingOff=!0:s.cullingOn=!0,t.set(n.id,s)}for(const t of e.children)n(t)};for(const t of e)n(t);const o=new Set;for(const[e,n]of Array.from(t))n.cullingOff&&n.cullingOn&&o.add(e);return o}static _getModelMaterial(e,t,n,o=!0){if(!t.cullingOff||!e.backFaceCulling)return e;if(!o)return e.backFaceCulling=!1,e;const s=null==n?void 0:n.get(e);if(s)return s;const r=e.clone(`${e.name}_CullingOff`);return r.backFaceCulling=!1,null==n||n.set(e,r),r}_applyMaterialUVSetCoordinates(e,n){if(e)if(e instanceof t.MultiMaterial)for(const o of e.subMaterials)o instanceof t.StandardMaterial&&this._applyStandardMaterialUVSetCoordinates(o,n);else e instanceof t.StandardMaterial&&this._applyStandardMaterialUVSetCoordinates(e,n)}_applyStandardMaterialUVSetCoordinates(e,t){var n;for(const o of[e.diffuseTexture,e.bumpTexture,e.emissiveTexture,e.ambientTexture,e.specularTexture,e.opacityTexture,e.reflectionTexture]){if(!o)continue;const e=null===(n=o.metadata)||void 0===n?void 0:n.fbxUVSetName;if(!e)continue;const s=t.uvSets.findIndex(t=>t.name===e);s>=0&&(o.coordinatesIndex=s)}}_useUnmodulatedVertexColorMaterials(e,n){const o=e.material;if(o)if(o instanceof t.StandardMaterial){if(!o.diffuseTexture){const n=o.clone(`${o.name}_VertexColor`);n.diffuseColor=new t.Color3(1,1,1),e.material=n}}else if(o instanceof t.MultiMaterial){const s=new t.MultiMaterial(`${o.name}_VertexColor`,n);s.subMaterials=o.subMaterials.map(e=>{if(e instanceof t.StandardMaterial&&!e.diffuseTexture){const n=e.clone(`${e.name}_VertexColor`);return n.diffuseColor=new t.Color3(1,1,1),n}return e}),e.material=s}}_buildSkinningData(e,t,n){var o,s,r;const i=e.positions.length/3,a=new Float32Array(4*i),l=new Float32Array(4*i);let u=null,c=null,d=0;if(e.controlPointIndices){for(let n=0;n<i;n++){const s=e.controlPointIndices[n],r=null!==(o=t.boneIndices[s])&&void 0!==o?o:[];d=Math.max(d,Math.min(r.length,8))}d>4&&(u=new Float32Array(4*i),c=new Float32Array(4*i));for(let o=0;o<i;o++){const i=e.controlPointIndices[o],d=null!==(s=t.boneIndices[i])&&void 0!==s?s:[],h=null!==(r=t.boneWeights[i])&&void 0!==r?r:[];for(let e=0;e<8;e++){const t=e<4?a:u,s=e<4?l:c;if(!t||!s)continue;const r=4*o+e%4;if(e<d.length){const o=d[e],s=n?n.skinBoneIndexToRigBoneIndex[o]:o;if(void 0===s||s<0)throw new Error(`FBXFileLoader: missing rig bone mapping for skin bone index ${o}`);t[r]=s}else t[r]=0;s[r]=e<h.length?h[e]:0}}}return{matricesIndices:a,matricesWeights:l,matricesIndicesExtra:u,matricesWeightsExtra:c,numBoneInfluencers:Math.max(d,1)}}_createMaterial(e,n,o){var s,r,i,a,l;const u=new t.StandardMaterial(e.name,n),c=e.properties,d=(...t)=>e.textures.some(e=>t.includes(e.propertyName));if("Lambert"===e.type&&(u.specularColor=t.Color3.Black()),c.diffuseColor){const e=d("DiffuseColor","Diffuse")?1:null!==(s=c.diffuseFactor)&&void 0!==s?s:1;u.diffuseColor=new t.Color3(c.diffuseColor[0]*e,c.diffuseColor[1]*e,c.diffuseColor[2]*e)}if(c.ambientColor){const e=d("AmbientColor","Ambient")?1:null!==(r=c.ambientFactor)&&void 0!==r?r:1;u.ambientColor=new t.Color3(c.ambientColor[0]*e,c.ambientColor[1]*e,c.ambientColor[2]*e)}if("Phong"===e.type&&c.specularColor){const e=d("SpecularColor","Specular","Shininess","ShininessExponent")?1:null!==(i=c.specularFactor)&&void 0!==i?i:1;u.specularColor=new t.Color3(c.specularColor[0]*e,c.specularColor[1]*e,c.specularColor[2]*e)}if(c.emissiveColor){const e=d("EmissiveColor","Emissive")?1:null!==(a=c.emissiveFactor)&&void 0!==a?a:1;u.emissiveColor=new t.Color3(c.emissiveColor[0]*e,c.emissiveColor[1]*e,c.emissiveColor[2]*e)}void 0!==c.opacity?u.alpha=c.opacity:void 0!==c.transparencyFactor&&(u.alpha=1-c.transparencyFactor),u.alpha<1&&(u.transparencyMode=t.Material.MATERIAL_ALPHABLEND),void 0!==c.shininess&&(u.specularPower=c.shininess);for(const s of e.textures){if(!kt._isSupportedMaterialTextureSlot(s.propertyName))continue;const e=kt._createTexture(s,n,o,kt._isNormalMapTextureSlot(s.propertyName));if(e){switch(s.propertyName){case"DiffuseColor":u.diffuseTexture=e,u.diffuseColor=new t.Color3(1,1,1);break;case"NormalMap":case"NormalMapTexture":case"normalCamera":case"Bump":case"BumpFactor":u.bumpTexture=e,this._configureNormalTexture(e,u);break;case"EmissiveColor":u.emissiveTexture=e;break;case"AmbientColor":u.ambientTexture=e;break;case"SpecularColor":u.specularTexture=e;break;case"TransparencyFactor":case"TransparentColor":u.opacityTexture=e,u.transparencyMode=t.Material.MATERIAL_ALPHATESTANDBLEND;break;case"ReflectionColor":case"ReflectionFactor":u.reflectionTexture=e}s.uvTranslation&&(e.uOffset=s.uvTranslation[0],e.vOffset=s.uvTranslation[1]),s.uvScaling&&(e.uScale=s.uvScaling[0],e.vScale=s.uvScaling[1]),void 0!==s.uvRotation&&(e.wAng=s.uvRotation*(Math.PI/180)),void 0!==s.uvSetIndex&&(e.coordinatesIndex=s.uvSetIndex),s.uvSetName&&(e.metadata=Object.assign(Object.assign({},null!==(l=e.metadata)&&void 0!==l?l:{}),{fbxUVSetName:s.uvSetName}))}}return u}_configureNormalTexture(e,t){e.gammaSpace=!1,t.invertNormalMapX=!1,t.invertNormalMapY="y-down"===this._options.normalMapCoordinateSystem}_getNormalMapTangentHandednessScale(){return"y-down"===this._options.normalMapCoordinateSystem?-1:1}static _isSupportedMaterialTextureSlot(e){switch(e){case"DiffuseColor":case"NormalMap":case"NormalMapTexture":case"normalCamera":case"Bump":case"BumpFactor":case"EmissiveColor":case"AmbientColor":case"SpecularColor":case"TransparencyFactor":case"TransparentColor":case"ReflectionColor":case"ReflectionFactor":case"DisplacementColor":case"Displacement":case"DisplacementFactor":case"ShininessExponent":case"Shininess":return!0;default:return!1}}static _isNormalMapTextureSlot(e){switch(e){case"NormalMap":case"NormalMapTexture":case"normalCamera":case"Bump":case"BumpFactor":return!0;default:return!1}}static _createTexture(e,n,o,s){const r=kt._getTextureSourceName(e),i=kt._getTextureCreationOptions(r,s,e.embeddedData);if(e.embeddedData){const o=new t.Texture(null,n,i),s=null!=r?r:`embeddedTexture_${e.id.toString()}`;return o.updateURL(`data:fbx-embedded-texture/${encodeURIComponent(s)}`,new Uint8Array(e.embeddedData),void 0,i.forcedExtension),o.name=s,o}const a=kt._getExternalTextureUrls(e,o),l=a.shift();return l?kt._createExternalTexture(l,a,n,i):null}static _createExternalTexture(e,n,o,s){n.push(...kt._buildTextureFallbackUrls(e));let r=0;const i=new t.Texture(e,o,Object.assign(Object.assign({},s),{onError:()=>{const e=n[r++];e&&i.getScene()&&i.updateURL(e,null,void 0,kt._getForcedExtension(e))}}));return i}static _buildTextureFallbackUrls(e){const t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),n=e.lastIndexOf(".");if(n<=t)return[];const o=e.slice(0,n),s=e.slice(n+1).toLowerCase();return["png","jpg","jpeg","webp","bmp","tga"].filter(e=>e!==s).map(e=>`${o}.${e}`)}static _getTextureCreationOptions(e,t,n){const o=n?e?kt._getMimeType(e):"image/png":void 0;return{buffer:n?new Uint8Array(n):void 0,forcedExtension:e?kt._getForcedExtension(e,o):n?".png":void 0,gammaSpace:!t,mimeType:o}}static _getExternalTextureUrls(e,t){const n=[e.relativeFileName,e.fileName].filter(e=>!!e),o=[];for(const e of n){const n=e.replace(/\\/g,"/");kt._isSafeRelativeTexturePath(n)&&o.push(t+n);const s=kt._getTextureSourceNameFromPath(n);s&&o.push(t+s)}return Array.from(new Set(o))}static _getTextureSourceName(e){const t=e.relativeFileName||e.fileName;if(!t)return null;const n=t.replace(/\\/g,"/");return kt._getTextureSourceNameFromPath(n)}static _getTextureSourceNameFromPath(e){var t;return null!==(t=e.split("/").pop())&&void 0!==t?t:e}static _isSafeRelativeTexturePath(e){return!(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)||e.startsWith("/")||e.startsWith("//")||e.split("/").some(e=>".."===e))}static _getForcedExtension(e,t){const n=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),o=e.lastIndexOf(".");if(o>n)return e.slice(o).toLowerCase();switch(t){case"image/png":return".png";case"image/jpeg":return".jpg";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/gif":return".gif";case"image/x-tga":return".tga";default:return}}static _getMimeType(e){const n=t.GetMimeType(e);if(n)return n;switch(kt._getForcedExtension(e)){case".tga":return"image/x-tga";case".bmp":return"image/bmp";case".gif":return"image/gif";default:return"image/png"}}_applyBlendShapes(e,n,o){var s,r,i,a,l,u,c,d;for(const h of e){const e=n.find(e=>{var t;return(null===(t=e.metadata)||void 0===t?void 0:t.fbxGeometryId)===h.geometryId});if(!e)continue;const m=new t.MorphTargetManager(o);m.optimizeInfluencers=!1;const f=null!==(a=null!==(r=null===(s=e.metadata)||void 0===s?void 0:s.fbxGeometryDeltaMatrix)&&void 0!==r?r:null===(i=e.metadata)||void 0===i?void 0:i.fbxPreRotMatrix)&&void 0!==a?a:null,p=null!==(u=null===(l=e.metadata)||void 0===l?void 0:l.fbxGeometryNormalMatrix)&&void 0!==u?u:f;for(const n of h.channels){const s=null===(c=e.metadata)||void 0===c?void 0:c.fbxControlPointIndices;if(!s)continue;const r=e.getVerticesData("position"),i=e.getVerticesData("normal");if(!r)continue;const a=$t(n.deformPercent,n.fullWeights,n.shapes.length),l=[];for(let e=0;e<n.shapes.length;e++){const u=n.shapes[e];if(!u)continue;const c=Ut(u,s,r,i,f,p);if(!c)continue;const h=n.fullWeights&&n.shapes.length>1?`${n.name}_${n.fullWeights[e]}`:n.name,_=new t.MorphTarget(h,null!==(d=a[e])&&void 0!==d?d:0,o);_.setPositions(c.positions),c.normals&&_.setNormals(c.normals),l.push(m.numTargets),m.addTarget(_)}0!==l.length&&(e.metadata||(e.metadata={}),e.metadata.fbxBlendShapeChannelIds||(e.metadata.fbxBlendShapeChannelIds=new Map),e.metadata.fbxBlendShapeChannelIds.set(n.id,l[0]),e.metadata.fbxBlendShapeChannelTargets||(e.metadata.fbxBlendShapeChannelTargets=new Map),e.metadata.fbxBlendShapeChannelTargets.set(n.id,{targetIndices:l,fullWeights:n.fullWeights}))}m.numTargets>0&&(m.numMaxInfluencers=m.numTargets,e.morphTargetManager=m)}}_createCamera(e,n,o){var s;const r=n.get(e.modelId),i=r?r.computeWorldMatrix(!0):t.Matrix.Identity(),a=t.Vector3.TransformCoordinates(t.Vector3.Zero(),i),l=new t.FreeCamera(e.name,a,o);if(l.fov=e.fieldOfView*(Math.PI/180),l.minZ=e.nearPlane,l.maxZ=e.farPlane,l.metadata=Object.assign(Object.assign({},null!==(s=l.metadata)&&void 0!==s?s:{}),{fbxCamera:{projectionType:e.projectionType,focalLength:e.focalLength,filmWidth:e.filmWidth,filmHeight:e.filmHeight,orthoZoom:e.orthoZoom,roll:e.roll,aspectRatio:e.aspectRatio,unknownProperties:e.unknownProperties,diagnostics:e.diagnostics}}),"orthographic"===e.projectionType){const n=e.orthoZoom&&e.orthoZoom>0?e.orthoZoom:1,o=e.aspectRatio>0?e.aspectRatio:1;l.mode=t.Camera.ORTHOGRAPHIC_CAMERA,l.orthoTop=n/2,l.orthoBottom=-n/2,l.orthoRight=n*o/2,l.orthoLeft=-n*o/2}const u=t.Vector3.TransformCoordinates(new t.Vector3(1,0,0),i);return l.setTarget(u),l}_createLight(e,n,o){var s;const r=n.get(e.modelId),i=r?r.computeWorldMatrix(!0):t.Matrix.Identity(),a=t.Vector3.TransformCoordinates(t.Vector3.Zero(),i),l=new t.Color3(e.color[0],e.color[1],e.color[2]),u=t.Vector3.TransformCoordinates(new t.Vector3(0,0,-1),i).subtract(a).normalize();let c;switch(e.lightType){case 1:c=new t.DirectionalLight(e.name,u,o),c.diffuse=l,c.intensity=e.intensity;break;case 2:{const n=e.coneAngle*(Math.PI/180);c=new t.SpotLight(e.name,a,u,n,2,o),c.diffuse=l,c.intensity=e.intensity;break}default:c=new t.PointLight(e.name,a,o),c.diffuse=l,c.intensity=e.intensity}return c.metadata=Object.assign(Object.assign({},null!==(s=c.metadata)&&void 0!==s?s:{}),{fbxLight:{lightType:e.lightType,decayType:e.decayType,decayStart:e.decayStart,innerAngle:e.innerAngle,outerAngle:e.outerAngle,enableNearAttenuation:e.enableNearAttenuation,enableFarAttenuation:e.enableFarAttenuation,castShadows:e.castShadows,unknownProperties:e.unknownProperties,diagnostics:e.diagnostics}}),c}_createSkeleton(e,n,o){var s;const r=new t.Skeleton("Skeleton",`skeleton_${e}`,o),i=[],a=new Map,l=[],u=[],c=[];for(let e=0;e<n.length;e++){const t=n[e],o=kt._computeFBXLocalMatrix(t.translation,t.rotation,t.scale,t.preRotation,t.postRotation,t.rotationPivot,t.scalingPivot,t.rotationOffset,t.scalingOffset,t.rotationOrder);l[e]=o,c[e]=kt._computeFBXRuntimeLocalMatrix(n,o,e)}u.push(...kt._computeFBXAbsoluteMatrices(n,c));const d=n.map((e,n)=>e.transformLinkMatrix?t.Matrix.FromArray(e.transformLinkMatrix):e.modelBindPoseMatrix?t.Matrix.FromArray(e.modelBindPoseMatrix):u[n]),h=d.map((e,o)=>{const s=n[o].parentIndex;if(s<0)return e;const r=new t.Matrix;return d[s].invertToRef(r),e.multiply(r)}),m=kt._shouldUseBindMatricesAsRest(n,l,h);for(let e=0;e<n.length;e++){let o=m?h[e]:c[e],u=n[e].parentIndex>=0?i[n[e].parentIndex]:null;if(!m&&2===n[e].inheritType&&n[e].parentIndex>=0&&u){const i=kt._splitParentScaleCompensatedLocalMatrix(l[e],n[n[e].parentIndex].scale),c=new t.Bone(`${n[e].name}__fbx_scaleCompensation`,r,u,i.helperLocalMatrix,i.helperLocalMatrix.clone(),t.Matrix.Identity(),-1);c.metadata=Object.assign(Object.assign({},null!==(s=c.metadata)&&void 0!==s?s:{}),{fbxScaleCompensationForBoneIndex:e,fbxScaleCompensationForBoneName:n[e].name}),a.set(e,c),u=c,o=i.boneLocalMatrix}const d=new t.Bone(n[e].name,r,u,o,m?o.clone():null,m?o.clone():null,e);m&&n[e].isCluster&&kt._getMaxScaleRatio(l[e],h[e])>=10&&this._bindRestBones.add(d),i.push(d)}if(this._sourceBonesBySkeleton.set(r,i),this._scaleCompensationHelpersBySkeleton.set(r,a),!m){for(let e=0;e<n.length;e++)i[e].updateMatrix(h[e],!1,!1);for(const e of Array.from(a.values()))e.updateMatrix(t.Matrix.Identity(),!1,!1);for(const e of r.bones)e.getParent()||e._updateAbsoluteBindMatrices(void 0,!0)}return r}_getSourceBone(e,t){var n,o;return null!==(o=null===(n=this._sourceBonesBySkeleton.get(e))||void 0===n?void 0:n[t])&&void 0!==o?o:e.bones[t]}_getScaleCompensationHelper(e,t){var n;return null===(n=this._scaleCompensationHelpersBySkeleton.get(e))||void 0===n?void 0:n.get(t)}static _computeFBXAbsoluteMatrices(e,t){const n=[];for(let o=0;o<e.length;o++){const s=e[o].parentIndex;n[o]=s<0?t[o].clone():t[o].multiply(n[s])}return n}static _computeFBXRuntimeLocalMatrix(e,t,n,o){const s=e[n].parentIndex;if(2!==e[n].inheritType||s<0)return t;const r=null!=o?o:e[s].scale;return kt._applyParentScaleCompensation(t,r)}static _applyParentScaleCompensation(e,t){const n=kt._splitParentScaleCompensatedLocalMatrix(e,t);return n.boneLocalMatrix.multiply(n.helperLocalMatrix)}static _splitParentScaleCompensatedLocalMatrix(e,n){const o=e.getTranslation(),s=e.clone();return s.setTranslation(t.Vector3.Zero()),{boneLocalMatrix:s,helperLocalMatrix:t.Matrix.Compose(kt._getInverseScaleVector(n),t.Quaternion.Identity(),o)}}static _safeInverseScale(e){return Math.abs(e)>1e-8?1/e:1}static _getInverseScaleVector(e){return new t.Vector3(kt._safeInverseScale(e[0]),kt._safeInverseScale(e[1]),kt._safeInverseScale(e[2]))}static _shouldUseBindMatricesAsRest(e,t,n){return e.some((e,o)=>!!e.isCluster&&kt._getMaxScaleRatio(t[o],n[o])>=10)}static _getMaxScaleRatio(e,n){const o=new t.Vector3,s=new t.Quaternion,r=new t.Vector3,i=new t.Vector3,a=new t.Quaternion,l=new t.Vector3;return e.decompose(o,s,r),n.decompose(i,a,l),Math.max(kt._getScaleRatio(o.x,i.x),kt._getScaleRatio(o.y,i.y),kt._getScaleRatio(o.z,i.z))}static _getScaleRatio(e,t){const n=Math.abs(e),o=Math.abs(t);return n<1e-6||o<1e-6?n<1e-6&&o<1e-6?1:Number.POSITIVE_INFINITY:Math.max(n/o,o/n)}static _computeFBXGeometricMatrix(e,n,o){return function(e,n,o){const s=t.Matrix.Translation(e[0],e[1],e[2]);return Pt(n,o).multiply(s)}(e,n,o)}static _computeFBXGeometricDeltaMatrix(e,t){return Pt(e,t)}static _computeFBXGeometricNormalMatrix(e,n){return function(e,n){const o=Math.PI/180,s=t.Matrix.Scaling(0===n[0]?0:1/n[0],0===n[1]?0:1/n[1],0===n[2]?0:1/n[2]),r=It(e[0]*o,e[1]*o,e[2]*o);return s.multiply(r)}(e,n)}static _computeFBXLocalMatrix(e,n,o,s,r,i,a,l,u,c=0){return function(e){const{translation:n,rotation:o,scale:s,preRotation:r,postRotation:i,rotationPivot:a,scalingPivot:l,rotationOffset:u,scalingOffset:c,rotationOrder:d}=e,h=Math.PI/180,m=0!==a[0]||0!==a[1]||0!==a[2]||0!==l[0]||0!==l[1]||0!==l[2],f=0!==u[0]||0!==u[1]||0!==u[2]||0!==c[0]||0!==c[1]||0!==c[2],p=0!==i[0]||0!==i[1]||0!==i[2];if(!m&&!f&&!p){const e=It(r[0]*h,r[1]*h,r[2]*h),i=Nt(o[0]*h,o[1]*h,o[2]*h,d),a=t.Matrix.Translation(n[0],n[1],n[2]),l=i.multiply(e);return t.Matrix.Scaling(s[0],s[1],s[2]).multiply(l).multiply(a)}const _=t.Matrix.Translation(n[0],n[1],n[2]),g=t.Matrix.Translation(u[0],u[1],u[2]),y=t.Matrix.Translation(a[0],a[1],a[2]),v=t.Matrix.Translation(-a[0],-a[1],-a[2]),b=t.Matrix.Translation(c[0],c[1],c[2]),x=t.Matrix.Translation(l[0],l[1],l[2]),T=t.Matrix.Translation(-l[0],-l[1],-l[2]),A=It(r[0]*h,r[1]*h,r[2]*h),M=Nt(o[0]*h,o[1]*h,o[2]*h,d),w=t.Matrix.Scaling(s[0],s[1],s[2]);let C;if(p){const e=It(i[0]*h,i[1]*h,i[2]*h);C=new t.Matrix,e.invertToRef(C)}else C=t.Matrix.Identity();let R=T;return R=R.multiply(w),R=R.multiply(x),R=R.multiply(b),R=R.multiply(v),R=R.multiply(C),R=R.multiply(M),R=R.multiply(A),R=R.multiply(y),R=R.multiply(g),R=R.multiply(_),R}({translation:e,rotation:n,scale:o,preRotation:s,postRotation:r,rotationPivot:i,scalingPivot:a,rotationOffset:l,scalingOffset:u,rotationOrder:c})}static _applyFBXTransform(e,n){const o=kt._computeFBXModelLocalMatrix(n),s=new t.Vector3,r=new t.Quaternion,i=new t.Vector3;o.decompose(s,r,i),e.position=i,e.rotationQuaternion=r,e.scaling=s}static _computeFBXModelLocalMatrix(e){return kt._computeFBXLocalMatrix(e.translation,e.rotation,e.scale,e.preRotation,e.postRotation,e.rotationPivot,e.scalingPivot,e.rotationOffset,e.scalingOffset,e.rotationOrder)}static _getBoneReferenceWorldMatrix(e,t,n,o){return o?e.getTransformMatrices(o):e.prepare(!0),n.computeWorldMatrix(!0),t.getFinalMatrix().multiply(n.getWorldMatrix())}static _applyMatrixToTransform(e,n){const o=new t.Vector3,s=new t.Quaternion,r=new t.Vector3;n.decompose(o,s,r),e.position=r,e.rotationQuaternion=s,e.scaling=o}_createAnimationGroup(e,n,o,s,r,i,a){if(0===e.curveNodes.length)return null;const l=new t.AnimationGroup(e.name,s),u=new Map,c=(e,t)=>{var n;const o=null!==(n=t.getTransformNode())&&void 0!==n?n:t;let s=u.get(o);if(s){if(s.has(e.targetProperty))return}else s=new Set,u.set(o,s);s.add(e.targetProperty),l.addTargetedAnimation(e,o)},d=new Map;for(const e of n){const t=o.get(e.id);if(t)for(const n of e.bones){const e=this._getSourceBone(t,n.index);if(!e)continue;const o=d.get(n.modelId);o?o.push(e):d.set(n.modelId,[e])}}const h=new Map,m=new Map,f=[];for(const t of e.curveNodes)"DeformPercent"!==t.type?d.has(t.targetModelId)?(h.has(t.targetModelId)||h.set(t.targetModelId,[]),h.get(t.targetModelId).push(t)):(m.has(t.targetModelId)||m.set(t.targetModelId,[]),m.get(t.targetModelId).push(t)):f.push(t);const p=new Set;for(const t of n){const n=new Set(t.bones.filter(e=>2===e.inheritType).map(e=>e.modelId));if(0===n.size)continue;const s=o.get(t.id);if(s&&!s.bones.some(e=>this._bindRestBones.has(e))){for(const e of Array.from(n))p.add(e);for(const{bone:o,animations:r}of this._buildInheritedRigBoneAnimations(t,s,h,i,n,e.startTime,e.stopTime))for(const e of r)c(e,o)}}for(const[t,n]of Array.from(h)){if(p.has(t))continue;const o=d.get(t),s=i.get(t);if(o&&0!==o.length&&s)for(const t of o){const o=this._buildBoneAnimations(n,t.name,s,e.startTime,e.stopTime,this._bindRestBones.has(t)?t.getBindMatrix():void 0);for(const e of o)c(e,t)}}for(const[t,n]of Array.from(m)){const o=r.get(t);if(!o)continue;const s=i.get(t);if(!s)continue;const a=this._buildNodeAnimations(n,o.name,s,e.startTime,e.stopTime);for(const e of a)l.addTargetedAnimation(e,o)}for(const n of f){const o=n.targetModelId;let s=!1;for(const r of a){if(!r.morphTargetManager||s)continue;const i=r.metadata,a=null==i?void 0:i.fbxBlendShapeChannelTargets,u=null==a?void 0:a.get(o);if(u&&n.curves.length>0){const o=30;for(let s=0;s<u.targetIndices.length;s++){const i=r.morphTargetManager.getTarget(u.targetIndices[s]);if(!i)continue;const a=new t.Animation(`${i.name}_influence`,"influence",o,t.Animation.ANIMATIONTYPE_FLOAT,t.Animation.ANIMATIONLOOPMODE_CYCLE),c=qt(n.curves[0],o,e.startTime,e.stopTime,e=>{var t;return null!==(t=$t(e,u.fullWeights,u.targetIndices.length)[s])&&void 0!==t?t:0});a.setKeys(c),l.addTargetedAnimation(a,i)}s=!0;continue}const c=null==i?void 0:i.fbxBlendShapeChannelIds;if(!c)continue;const d=c.get(o);if(void 0===d)continue;const h=r.morphTargetManager.getTarget(d);if(h&&n.curves.length>0){const o=30,r=new t.Animation(`${h.name}_influence`,"influence",o,t.Animation.ANIMATIONTYPE_FLOAT,t.Animation.ANIMATIONLOOPMODE_CYCLE),i=qt(n.curves[0],o,e.startTime,e.stopTime,e=>e/100);r.setKeys(i),l.addTargetedAnimation(r,h),s=!0}}}return l.targetedAnimations.length>0?(l.normalize(30*e.startTime,30*e.stopTime),l):(l.dispose(),null)}_buildInheritedRigBoneAnimations(e,n,o,s,r,i,a){const l=30,u=new Set;for(let t=0;t<e.bones.length;t++)if(r.has(e.bones[t].modelId))for(let n=t;n>=0;n=e.bones[n].parentIndex)u.add(e.bones[n].modelId);const c=zt(e.bones.filter(e=>u.has(e.modelId)).flatMap(e=>{var t;return null!==(t=o.get(e.modelId))&&void 0!==t?t:[]}),l,i,a);if(0===c.length)return[];const d=e.bones.map(()=>({posKeys:[],rotKeys:[],sclKeys:[],prevQuat:null})),h=e.bones.map(()=>({posKeys:[],rotKeys:[],sclKeys:[],prevQuat:null})),m=e.bones.map((e,o)=>{const r=this._getSourceBone(n,o),i=s.get(e.modelId);if(!r||!i||!this._bindRestBones.has(r))return null;const a=kt._computeFBXModelLocalMatrix(i),l=new t.Matrix;return a.invertToRef(l),l});for(const i of c){const a=e.bones.map((e,r)=>{var a,l;const u=s.get(e.modelId),c=null!==(a=o.get(e.modelId))&&void 0!==a?a:[];let d=u?this._sampleModelLocalMatrix(u,c,i):t.Matrix.Identity();const h=m[r];if(h){const e=this._getSourceBone(n,r);d=(null!==(l=null==e?void 0:e.getBindMatrix())&&void 0!==l?l:t.Matrix.Identity()).multiply(h).multiply(d)}return d}),u=e.bones.map(e=>{var t;const n=s.get(e.modelId),r=null!==(t=o.get(e.modelId))&&void 0!==t?t:[];return n?this._sampleModelScale(n,r,i):e.scale}),c=i*l;for(let t=0;t<a.length;t++){if(!r.has(e.bones[t].modelId))continue;const n=e.bones[t].parentIndex,o=n>=0?u[n]:e.bones[t].scale,s=kt._splitParentScaleCompensatedLocalMatrix(a[t],o);kt._pushMatrixKeys(d[t],c,s.boneLocalMatrix),kt._pushMatrixKeys(h[t],c,s.helperLocalMatrix)}}const f=[];for(let o=0;o<e.bones.length;o++){if(!r.has(e.bones[o].modelId))continue;const s=this._getSourceBone(n,o);if(!s)continue;const{posKeys:i,rotKeys:a,sclKeys:u}=d[o],c=[];if(!this._isVector3KeysConstant(i)){const e=new t.Animation(`${s.name}_position`,"position",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(i),c.push(e)}if(!jt(a)){const e=new t.Animation(`${s.name}_rotation`,"rotationQuaternion",l,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(a),c.push(e)}if(!this._isVector3KeysConstant(u)){const e=new t.Animation(`${s.name}_scaling`,"scaling",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(u),c.push(e)}c.length>0&&f.push({bone:s,animations:c});const m=this._getScaleCompensationHelper(n,o);if(!m)continue;const p=[],{posKeys:_,rotKeys:g,sclKeys:y}=h[o];if(!this._isVector3KeysConstant(_)){const e=new t.Animation(`${m.name}_position`,"position",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(_),p.push(e)}if(!jt(g)){const e=new t.Animation(`${m.name}_rotation`,"rotationQuaternion",l,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(g),p.push(e)}if(!this._isVector3KeysConstant(y)){const e=new t.Animation(`${m.name}_scaling`,"scaling",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(y),p.push(e)}p.length>0&&f.push({bone:m,animations:p})}return f}static _pushMatrixKeys(e,n,o){const s=new t.Vector3,r=new t.Quaternion,i=new t.Vector3;o.decompose(s,r,i),e.prevQuat&&t.Quaternion.Dot(e.prevQuat,r)<0&&r.scaleInPlace(-1),e.prevQuat=r,e.posKeys.push({frame:n,value:i}),e.rotKeys.push({frame:n,value:r}),e.sclKeys.push({frame:n,value:s})}_buildNodeAnimations(e,n,o,s,r){var i,a,l,u,c,d,h,m,f;const p=e.find(e=>"T"===e.type),_=e.find(e=>"R"===e.type),g=e.find(e=>"S"===e.type),y=zt(e,30,s,r);if(0===y.length)return[];const v=null==p?void 0:p.curves.find(e=>"d|X"===e.channel),b=null==p?void 0:p.curves.find(e=>"d|Y"===e.channel),x=null==p?void 0:p.curves.find(e=>"d|Z"===e.channel),T=null==_?void 0:_.curves.find(e=>"d|X"===e.channel),A=null==_?void 0:_.curves.find(e=>"d|Y"===e.channel),M=null==_?void 0:_.curves.find(e=>"d|Z"===e.channel),w=null==g?void 0:g.curves.find(e=>"d|X"===e.channel),C=null==g?void 0:g.curves.find(e=>"d|Y"===e.channel),R=null==g?void 0:g.curves.find(e=>"d|Z"===e.channel),O=[],S=[],F=[];let E=null;for(const e of y){const n=30*e,s=null!==(i=it(v,e))&&void 0!==i?i:o.translation[0],r=null!==(a=it(b,e))&&void 0!==a?a:o.translation[1],p=null!==(l=it(x,e))&&void 0!==l?l:o.translation[2],_=null!==(u=it(T,e))&&void 0!==u?u:o.rotation[0],g=null!==(c=it(A,e))&&void 0!==c?c:o.rotation[1],y=null!==(d=it(M,e))&&void 0!==d?d:o.rotation[2],L=null!==(h=it(w,e))&&void 0!==h?h:o.scale[0],I=null!==(m=it(C,e))&&void 0!==m?m:o.scale[1],N=null!==(f=it(R,e))&&void 0!==f?f:o.scale[2],P=kt._computeFBXLocalMatrix([s,r,p],[_,g,y],[L,I,N],o.preRotation,o.postRotation,o.rotationPivot,o.scalingPivot,o.rotationOffset,o.scalingOffset,o.rotationOrder),B=new t.Vector3,k=new t.Quaternion,D=new t.Vector3;P.decompose(B,k,D),E&&t.Quaternion.Dot(E,k)<0&&k.scaleInPlace(-1),E=k,O.push({frame:n,value:D}),S.push({frame:n,value:k}),F.push({frame:n,value:B})}const L=[];if(!this._isVector3KeysConstant(O)){const e=new t.Animation(`${n}_position`,"position",30,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(O),L.push(e)}if(_){const e=new t.Animation(`${n}_rotation`,"rotationQuaternion",30,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(S),L.push(e)}if(!this._isVector3KeysConstant(F)){const e=new t.Animation(`${n}_scaling`,"scaling",30,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(F),L.push(e)}return L}_isVector3KeysConstant(e){if(e.length<2)return!0;const t=e[0].value;for(let n=1;n<e.length;n++){const o=e[n].value;if(Math.abs(o.x-t.x)>1e-4||Math.abs(o.y-t.y)>1e-4||Math.abs(o.z-t.z)>1e-4)return!1}return!0}_sampleModelLocalMatrix(e,t,n,o){var s,r,i,a,l,u,c,d,h;const m=t.find(e=>"T"===e.type),f=t.find(e=>"R"===e.type),p=t.find(e=>"S"===e.type),_=null==m?void 0:m.curves.find(e=>"d|X"===e.channel),g=null==m?void 0:m.curves.find(e=>"d|Y"===e.channel),y=null==m?void 0:m.curves.find(e=>"d|Z"===e.channel),v=null==f?void 0:f.curves.find(e=>"d|X"===e.channel),b=null==f?void 0:f.curves.find(e=>"d|Y"===e.channel),x=null==f?void 0:f.curves.find(e=>"d|Z"===e.channel),T=null==p?void 0:p.curves.find(e=>"d|X"===e.channel),A=null==p?void 0:p.curves.find(e=>"d|Y"===e.channel),M=null==p?void 0:p.curves.find(e=>"d|Z"===e.channel);return kt._computeFBXLocalMatrix([null!==(s=it(_,n))&&void 0!==s?s:e.translation[0],null!==(r=it(g,n))&&void 0!==r?r:e.translation[1],null!==(i=it(y,n))&&void 0!==i?i:e.translation[2]],[null!==(a=it(v,n))&&void 0!==a?a:e.rotation[0],null!==(l=it(b,n))&&void 0!==l?l:e.rotation[1],null!==(u=it(x,n))&&void 0!==u?u:e.rotation[2]],null!=o?o:[null!==(c=it(T,n))&&void 0!==c?c:e.scale[0],null!==(d=it(A,n))&&void 0!==d?d:e.scale[1],null!==(h=it(M,n))&&void 0!==h?h:e.scale[2]],e.preRotation,e.postRotation,e.rotationPivot,e.scalingPivot,e.rotationOffset,e.scalingOffset,e.rotationOrder)}_sampleModelScale(e,t,n){var o,s,r;const i=t.find(e=>"S"===e.type),a=null==i?void 0:i.curves.find(e=>"d|X"===e.channel),l=null==i?void 0:i.curves.find(e=>"d|Y"===e.channel),u=null==i?void 0:i.curves.find(e=>"d|Z"===e.channel);return[null!==(o=it(a,n))&&void 0!==o?o:e.scale[0],null!==(s=it(l,n))&&void 0!==s?s:e.scale[1],null!==(r=it(u,n))&&void 0!==r?r:e.scale[2]]}_buildBoneAnimations(e,n,o,s,r,i){var a,l,u,c,d,h,m,f,p;const _=e.find(e=>"T"===e.type),g=e.find(e=>"R"===e.type),y=e.find(e=>"S"===e.type),v=zt(e,30,s,r);if(0===v.length)return[];const b=null==_?void 0:_.curves.find(e=>"d|X"===e.channel),x=null==_?void 0:_.curves.find(e=>"d|Y"===e.channel),T=null==_?void 0:_.curves.find(e=>"d|Z"===e.channel),A=null==g?void 0:g.curves.find(e=>"d|X"===e.channel),M=null==g?void 0:g.curves.find(e=>"d|Y"===e.channel),w=null==g?void 0:g.curves.find(e=>"d|Z"===e.channel),C=null==y?void 0:y.curves.find(e=>"d|X"===e.channel),R=null==y?void 0:y.curves.find(e=>"d|Y"===e.channel),O=null==y?void 0:y.curves.find(e=>"d|Z"===e.channel),S=[],F=[],E=[];let L=null,I=null;if(i){const e=kt._computeFBXLocalMatrix(o.translation,o.rotation,o.scale,o.preRotation,o.postRotation,o.rotationPivot,o.scalingPivot,o.rotationOffset,o.scalingOffset,o.rotationOrder);I=new t.Matrix,e.invertToRef(I)}for(const e of v){const n=30*e,s=null!==(a=it(b,e))&&void 0!==a?a:o.translation[0],r=null!==(l=it(x,e))&&void 0!==l?l:o.translation[1],_=null!==(u=it(T,e))&&void 0!==u?u:o.translation[2],g=null!==(c=it(A,e))&&void 0!==c?c:o.rotation[0],y=null!==(d=it(M,e))&&void 0!==d?d:o.rotation[1],v=null!==(h=it(w,e))&&void 0!==h?h:o.rotation[2],N=null!==(m=it(C,e))&&void 0!==m?m:o.scale[0],P=null!==(f=it(R,e))&&void 0!==f?f:o.scale[1],B=null!==(p=it(O,e))&&void 0!==p?p:o.scale[2],k=kt._computeFBXLocalMatrix([s,r,_],[g,y,v],[N,P,B],o.preRotation,o.postRotation,o.rotationPivot,o.scalingPivot,o.rotationOffset,o.scalingOffset,o.rotationOrder),D=I&&i?i.multiply(I).multiply(k):k,G=new t.Vector3,V=new t.Quaternion,H=new t.Vector3;D.decompose(G,V,H),L&&t.Quaternion.Dot(L,V)<0&&V.scaleInPlace(-1),L=V,S.push({frame:n,value:H}),F.push({frame:n,value:V}),E.push({frame:n,value:G})}const N=[];if(!this._isVector3KeysConstant(S)){const e=new t.Animation(`${n}_position`,"position",30,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(S),N.push(e)}if(g){const e=new t.Animation(`${n}_rotation`,"rotationQuaternion",30,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(F),N.push(e)}if(!this._isVector3KeysConstant(E)){const e=new t.Animation(`${n}_scaling`,"scaling",30,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(E),N.push(e)}return N}_buildNameFilter(e){if(!e)return null;if("string"==typeof e)return""===e?null:t=>t===e;if(0===e.length)return null;const t=new Set(e);return e=>t.has(e)}}function Dt(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}function Gt(e,t,n,o,s,r,i,a,l,u,c,d,h,m,f,p){var _;const g=function(e,t,n,o){const s=3*t,r=3*n,i=3*o,a=e[r]-e[s],l=e[r+1]-e[s+1],u=e[r+2]-e[s+2],c=e[i]-e[s],d=e[i+1]-e[s+1],h=e[i+2]-e[s+2],m=Math.hypot(a,l,u),f=Math.hypot(c,d,h);if(m<=1e-8||f<=1e-8)return 0;const p=(a*c+l*d+u*h)/(m*f);return Math.acos(Math.max(-1,Math.min(1,p)))}(u,e,t,n);if(g<=1e-8)return;const y=function(e,t,n,o,s,r,i,a,l,u,c,d){const h=3*e,m=3*e,f=2*e,[p,_,g]=Vt(l[m],l[m+1],l[m+2]),y=function(e,t,n,o,s,r,i,a,l){return(t*r-n*s)*i+(n*o-e*r)*a+(e*s-t*o)*l<0?-1:1}(p,_,g,t,n,o,s,r,i);return[c?`cp:${c[e]}`:`p:${Ht(a[h])},${Ht(a[h+1])},${Ht(a[h+2])}`,Ht(p),Ht(_),Ht(g),Ht(u[f]),Ht(u[f+1]),y,d].join("|")}(e,o,s,r,i,a,l,u,c,d,h,m);let v=f.get(y);v||(v={tx:0,ty:0,tz:0,bx:0,by:0,bz:0},f.set(y,v)),v.tx+=o*g,v.ty+=s*g,v.tz+=r*g,v.bx+=i*g,v.by+=a*g,v.bz+=l*g,null!==(_=p[e])&&void 0!==_||(p[e]=y)}function Vt(e,t,n){const o=Math.hypot(e,t,n);return o>1e-8?[e/o,t/o,n/o]:[0,0,1]}function Ht(e){const t=Math.round(1e6*e);return Object.is(t,-0)?0:t}function Kt(e,t,n){const o=Math.abs(e)<.9?1:0,s=1===o?0:1,r=e*o+t*s;let i=o-e*r,a=s-t*r,l=-n*r;const u=Math.hypot(i,a,l);return u<=1e-8?[1,0,0]:(i/=u,a/=u,l/=u,[i,a,l])}function Ut(e,n,o,s,r,i){const a=o.length/3,l=new Float32Array(3*a),u=null!==e.normals&&null!==s?new Float32Array(3*a):null;for(let e=0;e<l.length;e++)l[e]=o[e];if(u&&s)for(let e=0;e<u.length;e++)u[e]=s[e];const c=new Map;for(let t=0;t<e.indices.length;t++)c.set(e.indices[t],t);for(let o=0;o<a;o++){const s=n[o],a=c.get(s);if(void 0===a)continue;let d=e.vertices[3*a],h=e.vertices[3*a+1],m=e.vertices[3*a+2];if(r){const e=t.Vector3.TransformNormal(new t.Vector3(d,h,m),r);d=e.x,h=e.y,m=e.z}if(l[3*o]+=d,l[3*o+1]+=h,l[3*o+2]+=m,u&&e.normals){let n=e.normals[3*a],s=e.normals[3*a+1],r=e.normals[3*a+2];if(i){const e=t.Vector3.TransformNormal(new t.Vector3(n,s,r),i);e.lengthSquared()>0&&e.normalize(),n=e.x,s=e.y,r=e.z}u[3*o]+=n,u[3*o+1]+=s,u[3*o+2]+=r}}return{positions:l,normals:u}}function $t(e,t,n){if(n<=0)return[];if(!t||t.length!==n||1===n)return[Wt(e/((null==t?void 0:t[0])&&0!==t[0]?t[0]:100))];const o=new Array(n).fill(0);if(e<=t[0])return o[0]=0===t[0]?e<=0?1:0:Wt(e/t[0]),o;for(let n=1;n<t.length;n++){const s=t[n-1],r=t[n];if(e>r)continue;const i=r-s;if(Math.abs(i)<1e-6)return o[n]=1,o;const a=Wt((e-s)/i);return o[n-1]=1-a,o[n]=a,o}return o[n-1]=1,o}function Wt(e){return Math.max(0,Math.min(1,e))}function zt(e,t,n,o){let s=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;const i=new Set;for(const t of e)for(const e of t.curves)for(const t of e.keys)s=Math.min(s,t.time),r=Math.max(r,t.time),t.time>=n&&t.time<=o&&i.add(t.time);if(!Number.isFinite(s)||!Number.isFinite(r))return[];const a=o>n?n:s,l=o>n?o:r,u=new Set([a,l,...Array.from(i)]),c=Math.ceil(a*t),d=Math.floor(l*t);for(let e=c;e<=d;e++)u.add(e/t);return Array.from(u).sort((e,t)=>e-t)}function jt(e){if(e.length<2)return!0;const t=e[0].value;for(let n=1;n<e.length;n++){const o=e[n].value;if(Math.abs(o.x-t.x)>1e-4||Math.abs(o.y-t.y)>1e-4||Math.abs(o.z-t.z)>1e-4||Math.abs(o.w-t.w)>1e-4)return!1}return!0}function qt(e,t,n,o,s){var r,i,a,l,u,c;const d=function(e,t,n){var o,s,r,i;return n>t?{start:t,stop:n}:{start:null!==(s=null===(o=e.keys[0])||void 0===o?void 0:o.time)&&void 0!==s?s:0,stop:null!==(i=null===(r=e.keys[e.keys.length-1])||void 0===r?void 0:r.time)&&void 0!==i?i:0}}(e,n,o),h=e.keys.filter(e=>e.time>=d.start&&e.time<=d.stop).map(e=>({source:e,frame:e.time*t,value:s(e.value)}));h.some(e=>Math.abs(e.source.time-d.start)<1e-6)||h.unshift({source:{time:d.start,value:null!==(r=it(e,d.start))&&void 0!==r?r:0,interpolation:"linear"},frame:d.start*t,value:s(null!==(i=it(e,d.start))&&void 0!==i?i:0)}),h.some(e=>Math.abs(e.source.time-d.stop)<1e-6)||h.push({source:{time:d.stop,value:null!==(a=it(e,d.stop))&&void 0!==a?a:0,interpolation:"linear"},frame:d.stop*t,value:s(null!==(l=it(e,d.stop))&&void 0!==l?l:0)});const m=h.map(e=>({frame:e.frame,value:e.value}));for(let e=0;e<h.length-1;e++){const n=h[e].source,o=m[e+1];if("constant"===n.interpolation){m[e].interpolation=1;continue}if("cubic"!==n.interpolation)continue;const r=h[e+1].source,i=Math.max(r.time-n.time,1e-6),a=(r.value-n.value)/i;m[e].outTangent=Xt(null!==(u=n.rightSlope)&&void 0!==u?u:a,s)/t,o.inTangent=Xt(null!==(c=n.nextLeftSlope)&&void 0!==c?c:a,s)/t}return m}function Xt(e,t){return t(e)-t(0)}let Yt=!1;function Qt(){Yt||(Yt=!0,t.RegisterSceneLoaderPlugin(new kt))}Qt();var Zt={__proto__:null,FBXFileLoader:kt,RegisterFBXFileLoader:Qt};function Jt(e,t,n,o){const s={externalResourceFunction:o};return n&&(s.uri="file:"===t?n:t+n),ArrayBuffer.isView(e)?GLTFValidator.validateBytes(e,s):GLTFValidator.validateString(e,s)}function en(){const e=[];onmessage=t=>{const n=t.data;switch(n.id){case"init":importScripts(n.url);break;case"validate":Jt(n.data,n.rootUrl,n.fileName,t=>new Promise((n,o)=>{const s=e.length;e.push({resolve:n,reject:o}),postMessage({id:"getExternalResource",index:s,uri:t})})).then(e=>{postMessage({id:"validate.resolve",value:e})},e=>{postMessage({id:"validate.reject",reason:e})});break;case"getExternalResource.resolve":e[n.index].resolve(n.value);break;case"getExternalResource.reject":e[n.index].reject(n.reason)}}}class tn{static ValidateAsync(e,n,o,s){return"function"==typeof Worker?new Promise((r,i)=>{const a=`${Jt}(${en})()`,l=URL.createObjectURL(new Blob([a],{type:"application/javascript"})),u=new Worker(l),c=e=>{u.removeEventListener("error",c),u.removeEventListener("message",d),i(e)},d=e=>{const t=e.data;switch(t.id){case"getExternalResource":s(t.uri).then(e=>{u.postMessage({id:"getExternalResource.resolve",index:t.index,value:e},[e.buffer])},e=>{u.postMessage({id:"getExternalResource.reject",index:t.index,reason:e})});break;case"validate.resolve":u.removeEventListener("error",c),u.removeEventListener("message",d),tn._LastResults=t.value,r(t.value),u.terminate();break;case"validate.reject":u.removeEventListener("error",c),u.removeEventListener("message",d),i(t.reason),u.terminate()}};if(u.addEventListener("error",c),u.addEventListener("message",d),u.postMessage({id:"init",url:t.Tools.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){const t=e.slice();u.postMessage({id:"validate",data:t,rootUrl:n,fileName:o},[t.buffer])}else u.postMessage({id:"validate",data:e,rootUrl:n,fileName:o})}):(this._LoadScriptPromise||(this._LoadScriptPromise=t.Tools.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then(()=>Jt(e,n,o,s)))}}tn.Configuration={url:`${t.Tools._DefaultCdnUrl}/gltf_validator.js`},tn._LastResults=null;var nn={__proto__:null,GLTFValidation:tn};const on="Z2xURg",sn={name:"gltf",extensions:{".gltf":{isBinary:!1,mimeType:"model/gltf+json"},".glb":{isBinary:!0,mimeType:"model/gltf-binary"}},canDirectLoad:e=>-1!==e.indexOf("asset")&&-1!==e.indexOf("version")||e.startsWith("data:base64,"+on)||e.startsWith("data:;base64,"+on)||e.startsWith("data:application/octet-stream;base64,"+on)||e.startsWith("data:model/gltf-binary;base64,"+on)};function rn(e,t,n){try{return Promise.resolve(new Uint8Array(e,t,n))}catch(e){return Promise.reject(e)}}var an,ln,un;e.GLTFLoaderCoordinateSystemMode=void 0,(an=e.GLTFLoaderCoordinateSystemMode||(e.GLTFLoaderCoordinateSystemMode={}))[an.AUTO=0]="AUTO",an[an.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED",e.GLTFLoaderAnimationStartMode=void 0,(ln=e.GLTFLoaderAnimationStartMode||(e.GLTFLoaderAnimationStartMode={}))[ln.NONE=0]="NONE",ln[ln.FIRST=1]="FIRST",ln[ln.ALL=2]="ALL",e.GLTFLoaderState=void 0,(un=e.GLTFLoaderState||(e.GLTFLoaderState={}))[un.LOADING=0]="LOADING",un[un.READY=1]="READY",un[un.COMPLETE=2]="COMPLETE";class cn{constructor(){this.alwaysComputeBoundingBox=!1,this.alwaysComputeSkeletonRootNode=!1,this.animationStartMode=e.GLTFLoaderAnimationStartMode.FIRST,this.compileMaterials=!1,this.compileShadowGenerators=!1,this.coordinateSystemMode=e.GLTFLoaderCoordinateSystemMode.AUTO,this.createInstances=!0,this.loadAllMaterials=!1,this.loadMorphTargets=!0,this.useMaxMorphTargetInfluencers=!0,this.loadNodeAnimations=!0,this.loadOnlyMaterials=!1,this.loadSkins=!0,this.skipMaterials=!1,this.targetFps=60,this.transparencyAsCoverage=!1,this.useClipPlane=!1,this.useGltfTextureNames=!1,this.useRangeRequests=!1,this.useSRGBBuffers=!0,this.validate=!1,this.useOpenPBR=!1,this.dontUseTransmissionHelper=!1}}const dn=new cn;class hn extends cn{constructor(){super(...arguments),this.extensionOptions={},this.preprocessUrlAsync=e=>Promise.resolve(e)}copyFrom(e){var t,n,o,s,r,i,a,l,u,c,d,h,m,f,p,_,g,y,v,b,x,T,A,M,w,C,R;e&&(this.alwaysComputeBoundingBox=null!==(t=e.alwaysComputeBoundingBox)&&void 0!==t?t:this.alwaysComputeBoundingBox,this.alwaysComputeSkeletonRootNode=null!==(n=e.alwaysComputeSkeletonRootNode)&&void 0!==n?n:this.alwaysComputeSkeletonRootNode,this.animationStartMode=null!==(o=e.animationStartMode)&&void 0!==o?o:this.animationStartMode,this.capturePerformanceCounters=null!==(s=e.capturePerformanceCounters)&&void 0!==s?s:this.capturePerformanceCounters,this.compileMaterials=null!==(r=e.compileMaterials)&&void 0!==r?r:this.compileMaterials,this.compileShadowGenerators=null!==(i=e.compileShadowGenerators)&&void 0!==i?i:this.compileShadowGenerators,this.coordinateSystemMode=null!==(a=e.coordinateSystemMode)&&void 0!==a?a:this.coordinateSystemMode,this.createInstances=null!==(l=e.createInstances)&&void 0!==l?l:this.createInstances,this.customRootNode=e.customRootNode,this.extensionOptions=null!==(u=e.extensionOptions)&&void 0!==u?u:this.extensionOptions,this.loadAllMaterials=null!==(c=e.loadAllMaterials)&&void 0!==c?c:this.loadAllMaterials,this.loadMorphTargets=null!==(d=e.loadMorphTargets)&&void 0!==d?d:this.loadMorphTargets,this.loadNodeAnimations=null!==(h=e.loadNodeAnimations)&&void 0!==h?h:this.loadNodeAnimations,this.loadOnlyMaterials=null!==(m=e.loadOnlyMaterials)&&void 0!==m?m:this.loadOnlyMaterials,this.loadSkins=null!==(f=e.loadSkins)&&void 0!==f?f:this.loadSkins,this.loggingEnabled=null!==(p=e.loggingEnabled)&&void 0!==p?p:this.loggingEnabled,this.onCameraLoaded=e.onCameraLoaded,this.onMaterialLoaded=e.onMaterialLoaded,this.onMeshLoaded=e.onMeshLoaded,this.onParsed=e.onParsed,this.onSkinLoaded=e.onSkinLoaded,this.onTextureLoaded=e.onTextureLoaded,this.onValidated=e.onValidated,this.preprocessUrlAsync=null!==(_=e.preprocessUrlAsync)&&void 0!==_?_:this.preprocessUrlAsync,this.skipMaterials=null!==(g=e.skipMaterials)&&void 0!==g?g:this.skipMaterials,this.targetFps=null!==(y=e.targetFps)&&void 0!==y?y:this.targetFps,this.transparencyAsCoverage=null!==(v=e.transparencyAsCoverage)&&void 0!==v?v:this.transparencyAsCoverage,this.useClipPlane=null!==(b=e.useClipPlane)&&void 0!==b?b:this.useClipPlane,this.useGltfTextureNames=null!==(x=e.useGltfTextureNames)&&void 0!==x?x:this.useGltfTextureNames,this.useMaxMorphTargetInfluencers=null!==(T=e.useMaxMorphTargetInfluencers)&&void 0!==T?T:this.useMaxMorphTargetInfluencers,this.useOpenPBR=null!==(A=e.useOpenPBR)&&void 0!==A?A:this.useOpenPBR,this.useRangeRequests=null!==(M=e.useRangeRequests)&&void 0!==M?M:this.useRangeRequests,this.useSRGBBuffers=null!==(w=e.useSRGBBuffers)&&void 0!==w?w:this.useSRGBBuffers,this.validate=null!==(C=e.validate)&&void 0!==C?C:this.validate,this.dontUseTransmissionHelper=null!==(R=e.dontUseTransmissionHelper)&&void 0!==R?R:this.dontUseTransmissionHelper)}}class mn extends hn{constructor(e){super(),this.onParsedObservable=new t.Observable,this.onMeshLoadedObservable=new t.Observable,this.onSkinLoadedObservable=new t.Observable,this.onTextureLoadedObservable=new t.Observable,this.onMaterialLoadedObservable=new t.Observable,this.onCameraLoadedObservable=new t.Observable,this.onCompleteObservable=new t.Observable,this.onErrorObservable=new t.Observable,this.onDisposeObservable=new t.Observable,this.onExtensionLoadedObservable=new t.Observable,this.onValidatedObservable=new t.Observable,this._loader=null,this._state=null,this._requests=new Array,this.name=sn.name,this.extensions=sn.extensions,this.onLoaderStateChangedObservable=new t.Observable,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled,this.copyFrom(Object.assign(Object.assign({},dn),e))}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),e&&(this._onParsedObserver=this.onParsedObservable.add(e))}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),e&&(this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e))}set onSkinLoaded(e){this._onSkinLoadedObserver&&this.onSkinLoadedObservable.remove(this._onSkinLoadedObserver),e&&(this._onSkinLoadedObserver=this.onSkinLoadedObservable.add(t=>e(t.node,t.skinnedNode)))}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),e&&(this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e))}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),e&&(this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e))}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),e&&(this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e))}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(const e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,n,o,s,r,i,a,l){if(ArrayBuffer.isView(n))return this._loadBinary(e,n,o,s,a,l),null;this._progressCallback=r;const u=n.name||t.Tools.GetFilename(n);if(i){if(this.useRangeRequests){this.validate&&t.Logger.Warn("glTF validation is not supported when range requests are enabled");const o={abort:()=>{},onCompleteObservable:new t.Observable},r={readAsync:(t,o)=>new Promise((s,r)=>{this._loadFile(e,n,e=>{s(new Uint8Array(e))},!0,e=>{r(e)},e=>{e.setRequestHeader("Range",`bytes=${t}-${t+o-1}`)})}),byteLength:0};return this._unpackBinaryAsync(new t.DataReader(r)).then(e=>{o.onCompleteObservable.notifyObservers(o),s(e)},a?e=>a(void 0,e):void 0),o}return this._loadFile(e,n,n=>{this._validate(e,new Uint8Array(n,0,n.byteLength),o,u),this._unpackBinaryAsync(new t.DataReader({readAsync:(e,t)=>rn(n,e,t),byteLength:n.byteLength})).then(e=>{s(e)},a?e=>a(void 0,e):void 0)},!0,a)}return this._loadFile(e,n,t=>{try{this._validate(e,t,o,u),s({json:this._parseJson(t)})}catch(e){a&&a()}},!1,a)}_loadBinary(e,n,o,s,r,i){this._validate(e,new Uint8Array(n.buffer,n.byteOffset,n.byteLength),o,i),this._unpackBinaryAsync(new t.DataReader({readAsync:(e,t)=>function(e,t,n){try{if(t<0||t>=e.byteLength)throw new RangeError("Offset is out of range.");if(t+n>e.byteLength)throw new RangeError("Length is out of range.");return Promise.resolve(new Uint8Array(e.buffer,e.byteOffset+t,n))}catch(e){return Promise.reject(e)}}(n,e,t),byteLength:n.byteLength})).then(e=>{s(e)},r?e=>r(void 0,e):void 0)}importMeshAsync(e,t,n,o,s,r){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(n),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(n),this._loader.importMeshAsync(e,t,null,n,o,s,r)))}loadAsync(e,t,n,o,s){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,n,o,s)))}loadAssetContainerAsync(e,n,o,s,r){return Promise.resolve().then(()=>{this.onParsedObservable.notifyObservers(n),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(n);const i=new t.AssetContainer(e),a=[];this.onMaterialLoadedObservable.add(e=>{a.push(e)});const l=[];this.onTextureLoadedObservable.add(e=>{l.push(e)});const u=[];this.onCameraLoadedObservable.add(e=>{u.push(e)});const c=[];return this.onMeshLoadedObservable.add(e=>{e.morphTargetManager&&c.push(e.morphTargetManager)}),this._loader.importMeshAsync(null,e,i,n,o,s,r).then(e=>(Array.prototype.push.apply(i.geometries,e.geometries),Array.prototype.push.apply(i.meshes,e.meshes),Array.prototype.push.apply(i.particleSystems,e.particleSystems),Array.prototype.push.apply(i.skeletons,e.skeletons),Array.prototype.push.apply(i.animationGroups,e.animationGroups),Array.prototype.push.apply(i.materials,a),Array.prototype.push.apply(i.textures,l),Array.prototype.push.apply(i.lights,e.lights),Array.prototype.push.apply(i.transformNodes,e.transformNodes),Array.prototype.push.apply(i.cameras,u),Array.prototype.push.apply(i.morphTargetManagers,c),i))})}canDirectLoad(e){return sn.canDirectLoad(e)}directLoad(e,n){if(n.startsWith("base64,"+on)||n.startsWith(";base64,"+on)||n.startsWith("application/octet-stream;base64,"+on)||n.startsWith("model/gltf-binary;base64,"+on)){const o=t.DecodeBase64UrlToBinary(n);return this._validate(e,new Uint8Array(o,0,o.byteLength)),this._unpackBinaryAsync(new t.DataReader({readAsync:(e,t)=>rn(o,e,t),byteLength:o.byteLength}))}return this._validate(e,n),Promise.resolve({json:this._parseJson(n)})}createPlugin(e){return new mn(e[sn.name])}get loaderState(){return this._state}whenCompleteAsync(){return new Promise((e,t)=>{this.onCompleteObservable.addOnce(()=>{e()}),this.onErrorObservable.addOnce(e=>{t(e)})})}_setState(t){this._state!==t&&(this._state=t,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(e.GLTFLoaderState[this._state]))}_loadFile(e,t,n,o,s,r){const i=e._loadFile(t,n,e=>{this._onProgress(e,i)},!0,o,s,r);return i.onCompleteObservable.add(()=>{i._lengthComputable=!0,i._total=i._loaded}),this._requests.push(i),i}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let n=!0,o=0,s=0;for(const e of this._requests){if(void 0===e._lengthComputable||void 0===e._loaded||void 0===e._total)return;n=n&&e._lengthComputable,o+=e._loaded,s+=e._total}this._progressCallback({lengthComputable:n,loaded:o,total:n?s:0})}_validate(e,n,o="",s=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),tn.ValidateAsync(n,o,s,t=>this.preprocessUrlAsync(o+t).then(t=>e._loadFileAsync(t,void 0,!0,!0).then(e=>new Uint8Array(e,0,e.byteLength)))).then(e=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(e),this.onValidatedObservable.clear()},e=>{this._endPerformanceCounter("Validate JSON"),t.Tools.Warn(`Failed to validate: ${e.message}`),this.onValidatedObservable.clear()}))}_getLoader(e){const t=e.json.asset||{};this._log(`Asset version: ${t.version}`),t.minVersion&&this._log(`Asset minimum version: ${t.minVersion}`),t.generator&&this._log(`Asset generator: ${t.generator}`);const n=mn._parseVersion(t.version);if(!n)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=mn._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(mn._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const o={1:mn._CreateGLTF1Loader,2:mn._CreateGLTF2Loader}[n.major];if(!o)throw new Error("Unsupported version: "+t.version);return o(this)}_parseJson(e){this._startPerformanceCounter("Parse JSON"),this._log(`JSON length: ${e.length}`);const t=JSON.parse(e);return this._endPerformanceCounter("Parse JSON"),t}_unpackBinaryAsync(e){return this._startPerformanceCounter("Unpack Binary"),e.loadAsync(20).then(()=>{const n=e.readUint32();if(1179937895!==n)throw new t.RuntimeError("Unexpected magic: "+n,t.ErrorCodes.GLTFLoaderUnexpectedMagicError);const o=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${o}`);const s=e.readUint32();let r;switch(this.useRangeRequests||s===e.buffer.byteLength||t.Logger.Warn(`Length in header does not match actual data length: ${s} != ${e.buffer.byteLength}`),o){case 1:r=this._unpackBinaryV1Async(e,s);break;case 2:r=this._unpackBinaryV2Async(e,s);break;default:throw new Error("Unsupported version: "+o)}return this._endPerformanceCounter("Unpack Binary"),r})}_unpackBinaryV1Async(e,t){const n=e.readUint32(),o=e.readUint32();if(0!==o)throw new Error(`Unexpected content format: ${o}`);const s=t-e.byteOffset,r={json:this._parseJson(e.readString(n)),bin:null};if(0!==s){const t=e.byteOffset;r.bin={readAsync:(n,o)=>e.buffer.readAsync(t+n,o),byteLength:s}}return Promise.resolve(r)}_unpackBinaryV2Async(e,t){const n=1313821514,o=e.readUint32();if(e.readUint32()!==n)throw new Error("First chunk format is not JSON");return e.byteOffset+o===t?e.loadAsync(o).then(()=>({json:this._parseJson(e.readString(o)),bin:null})):e.loadAsync(o+8).then(()=>{const s={json:this._parseJson(e.readString(o)),bin:null},r=()=>{const o=e.readUint32();switch(e.readUint32()){case n:throw new Error("Unexpected JSON chunk");case 5130562:{const t=e.byteOffset;s.bin={readAsync:(n,o)=>e.buffer.readAsync(t+n,o),byteLength:o},e.skipBytes(o);break}default:e.skipBytes(o)}return e.byteOffset!==t?e.loadAsync(8).then(r):Promise.resolve(s)};return r()})}static _parseVersion(e){if("1.0"===e||"1.0.1"===e)return{major:1,minor:0};const t=(e+"").match(/^(\d+)\.(\d+)/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null}static _compareVersion(e,t){return e.major>t.major?1:e.major<t.major?-1:e.minor>t.minor?1:e.minor<t.minor?-1:0}_logOpen(e){this._log(e),this._logIndentLevel++}_logClose(){--this._logIndentLevel}_logEnabled(e){const n=mn._logSpaces.substring(0,2*this._logIndentLevel);t.Logger.Log(`${n}${e}`)}_logDisabled(e){}_startPerformanceCounterEnabled(e){t.Tools.StartPerformanceCounter(e)}_startPerformanceCounterDisabled(e){}_endPerformanceCounterEnabled(e){t.Tools.EndPerformanceCounter(e)}_endPerformanceCounterDisabled(e){}}mn.IncrementalLoading=!0,mn.HomogeneousCoordinates=!1,mn._logSpaces=" ";let fn=!1;function pn(){fn||(fn=!0,t.RegisterSceneLoaderPlugin(new mn))}pn();var _n,gn,yn,vn,bn,xn,Tn,An,Mn,wn={__proto__:null,GLTFFileLoader:mn,get GLTFLoaderAnimationStartMode(){return e.GLTFLoaderAnimationStartMode},get GLTFLoaderCoordinateSystemMode(){return e.GLTFLoaderCoordinateSystemMode},GLTFLoaderDefaultOptions:dn,get GLTFLoaderState(){return e.GLTFLoaderState},RegisterGLTFFileLoader:pn};!function(e){e[e.BYTE=5120]="BYTE",e[e.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",e[e.SHORT=5122]="SHORT",e[e.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",e[e.FLOAT=5126]="FLOAT"}(_n||(_n={})),function(e){e[e.FRAGMENT=35632]="FRAGMENT",e[e.VERTEX=35633]="VERTEX"}(gn||(gn={})),function(e){e[e.BYTE=5120]="BYTE",e[e.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",e[e.SHORT=5122]="SHORT",e[e.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",e[e.INT=5124]="INT",e[e.UNSIGNED_INT=5125]="UNSIGNED_INT",e[e.FLOAT=5126]="FLOAT",e[e.FLOAT_VEC2=35664]="FLOAT_VEC2",e[e.FLOAT_VEC3=35665]="FLOAT_VEC3",e[e.FLOAT_VEC4=35666]="FLOAT_VEC4",e[e.INT_VEC2=35667]="INT_VEC2",e[e.INT_VEC3=35668]="INT_VEC3",e[e.INT_VEC4=35669]="INT_VEC4",e[e.BOOL=35670]="BOOL",e[e.BOOL_VEC2=35671]="BOOL_VEC2",e[e.BOOL_VEC3=35672]="BOOL_VEC3",e[e.BOOL_VEC4=35673]="BOOL_VEC4",e[e.FLOAT_MAT2=35674]="FLOAT_MAT2",e[e.FLOAT_MAT3=35675]="FLOAT_MAT3",e[e.FLOAT_MAT4=35676]="FLOAT_MAT4",e[e.SAMPLER_2D=35678]="SAMPLER_2D"}(yn||(yn={})),function(e){e[e.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",e[e.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",e[e.REPEAT=10497]="REPEAT"}(vn||(vn={})),function(e){e[e.NEAREST=9728]="NEAREST",e[e.LINEAR=9728]="LINEAR",e[e.NEAREST_MIPMAP_NEAREST=9984]="NEAREST_MIPMAP_NEAREST",e[e.LINEAR_MIPMAP_NEAREST=9985]="LINEAR_MIPMAP_NEAREST",e[e.NEAREST_MIPMAP_LINEAR=9986]="NEAREST_MIPMAP_LINEAR",e[e.LINEAR_MIPMAP_LINEAR=9987]="LINEAR_MIPMAP_LINEAR"}(bn||(bn={})),function(e){e[e.ALPHA=6406]="ALPHA",e[e.RGB=6407]="RGB",e[e.RGBA=6408]="RGBA",e[e.LUMINANCE=6409]="LUMINANCE",e[e.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA"}(xn||(xn={})),function(e){e[e.FRONT=1028]="FRONT",e[e.BACK=1029]="BACK",e[e.FRONT_AND_BACK=1032]="FRONT_AND_BACK"}(Tn||(Tn={})),function(e){e[e.ZERO=0]="ZERO",e[e.ONE=1]="ONE",e[e.SRC_COLOR=768]="SRC_COLOR",e[e.ONE_MINUS_SRC_COLOR=769]="ONE_MINUS_SRC_COLOR",e[e.DST_COLOR=774]="DST_COLOR",e[e.ONE_MINUS_DST_COLOR=775]="ONE_MINUS_DST_COLOR",e[e.SRC_ALPHA=770]="SRC_ALPHA",e[e.ONE_MINUS_SRC_ALPHA=771]="ONE_MINUS_SRC_ALPHA",e[e.DST_ALPHA=772]="DST_ALPHA",e[e.ONE_MINUS_DST_ALPHA=773]="ONE_MINUS_DST_ALPHA",e[e.CONSTANT_COLOR=32769]="CONSTANT_COLOR",e[e.ONE_MINUS_CONSTANT_COLOR=32770]="ONE_MINUS_CONSTANT_COLOR",e[e.CONSTANT_ALPHA=32771]="CONSTANT_ALPHA",e[e.ONE_MINUS_CONSTANT_ALPHA=32772]="ONE_MINUS_CONSTANT_ALPHA",e[e.SRC_ALPHA_SATURATE=776]="SRC_ALPHA_SATURATE"}(An||(An={}));class Cn{static SetMatrix(e,n,o,s,r){let i=null;if("MODEL"===o.semantic?i=n.getWorldMatrix():"PROJECTION"===o.semantic?i=e.getProjectionMatrix():"VIEW"===o.semantic?i=e.getViewMatrix():"MODELVIEWINVERSETRANSPOSE"===o.semantic?i=t.Matrix.Transpose(n.getWorldMatrix().multiply(e.getViewMatrix()).invert()):"MODELVIEW"===o.semantic?i=n.getWorldMatrix().multiply(e.getViewMatrix()):"MODELVIEWPROJECTION"===o.semantic?i=n.getWorldMatrix().multiply(e.getTransformMatrix()):"MODELINVERSE"===o.semantic?i=n.getWorldMatrix().invert():"VIEWINVERSE"===o.semantic?i=e.getViewMatrix().invert():"PROJECTIONINVERSE"===o.semantic?i=e.getProjectionMatrix().invert():"MODELVIEWINVERSE"===o.semantic?i=n.getWorldMatrix().multiply(e.getViewMatrix()).invert():"MODELVIEWPROJECTIONINVERSE"===o.semantic?i=n.getWorldMatrix().multiply(e.getTransformMatrix()).invert():"MODELINVERSETRANSPOSE"===o.semantic&&(i=t.Matrix.Transpose(n.getWorldMatrix().invert())),i)switch(o.type){case yn.FLOAT_MAT2:r.setMatrix2x2(s,t.Matrix.GetAsMatrix2x2(i));break;case yn.FLOAT_MAT3:r.setMatrix3x3(s,t.Matrix.GetAsMatrix3x3(i));break;case yn.FLOAT_MAT4:r.setMatrix(s,i)}}static SetUniform(e,n,o,s){switch(s){case yn.FLOAT:return e.setFloat(n,o),!0;case yn.FLOAT_VEC2:return e.setVector2(n,t.Vector2.FromArray(o)),!0;case yn.FLOAT_VEC3:return e.setVector3(n,t.Vector3.FromArray(o)),!0;case yn.FLOAT_VEC4:return e.setVector4(n,t.Vector4.FromArray(o)),!0;default:return!1}}static GetWrapMode(e){switch(e){case vn.CLAMP_TO_EDGE:return t.Texture.CLAMP_ADDRESSMODE;case vn.MIRRORED_REPEAT:return t.Texture.MIRROR_ADDRESSMODE;case vn.REPEAT:default:return t.Texture.WRAP_ADDRESSMODE}}static GetByteStrideFromType(e){switch(e.type){case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16;default:return 1}}static GetTextureFilterMode(e){switch(e){case bn.LINEAR:case bn.LINEAR_MIPMAP_NEAREST:case bn.LINEAR_MIPMAP_LINEAR:return t.Texture.TRILINEAR_SAMPLINGMODE;case bn.NEAREST:case bn.NEAREST_MIPMAP_NEAREST:return t.Texture.NEAREST_SAMPLINGMODE;default:return t.Texture.BILINEAR_SAMPLINGMODE}}static GetBufferFromBufferView(e,t,n,o,s){n=t.byteOffset+n;const r=e.loadedBufferViews[t.buffer];if(n+o>r.byteLength)throw new Error("Buffer access is out of range");const i=r.buffer;switch(n+=r.byteOffset,s){case _n.BYTE:return new Int8Array(i,n,o);case _n.UNSIGNED_BYTE:return new Uint8Array(i,n,o);case _n.SHORT:return new Int16Array(i,n,o);case _n.UNSIGNED_SHORT:return new Uint16Array(i,n,o);default:return new Float32Array(i,n,o)}}static GetBufferFromAccessor(e,t){const n=e.bufferViews[t.bufferView],o=t.count*Cn.GetByteStrideFromType(t);return Cn.GetBufferFromBufferView(e,n,t.byteOffset,o,t.componentType)}static DecodeBufferToText(e){let t="";const n=e.byteLength;for(let o=0;o<n;++o)t+=String.fromCharCode(e[o]);return t}static GetDefaultMaterial(e){if(!Cn._DefaultMaterial){t.Effect.ShadersStore.GLTFDefaultMaterialVertexShader=["precision highp float;","","uniform mat4 worldView;","uniform mat4 projection;","","attribute vec3 position;","","void main(void)","{"," gl_Position = projection * worldView * vec4(position, 1.0);","}"].join("\n"),t.Effect.ShadersStore.GLTFDefaultMaterialPixelShader=["precision highp float;","","uniform vec4 u_emission;","","void main(void)","{"," gl_FragColor = u_emission;","}"].join("\n");const n={vertex:"GLTFDefaultMaterial",fragment:"GLTFDefaultMaterial"},o={attributes:["position"],uniforms:["worldView","projection","u_emission"],samplers:new Array,needAlphaBlending:!1};Cn._DefaultMaterial=new t.ShaderMaterial("GLTFDefaultMaterial",e,n,o),Cn._DefaultMaterial.setColor4("u_emission",new t.Color4(.5,.5,.5,1))}return Cn._DefaultMaterial}}Cn._DefaultMaterial=null,function(e){e[e.IDENTIFIER=1]="IDENTIFIER",e[e.UNKNOWN=2]="UNKNOWN",e[e.END_OF_INPUT=3]="END_OF_INPUT"}(Mn||(Mn={}));class Rn{constructor(e){this._pos=0,this.currentToken=Mn.UNKNOWN,this.currentIdentifier="",this.currentString="",this.isLetterOrDigitPattern=/^[a-zA-Z0-9]+$/,this._toParse=e,this._maxPos=e.length}getNextToken(){if(this.isEnd())return Mn.END_OF_INPUT;if(this.currentString=this.read(),this.currentToken=Mn.UNKNOWN,"_"===this.currentString||this.isLetterOrDigitPattern.test(this.currentString))for(this.currentToken=Mn.IDENTIFIER,this.currentIdentifier=this.currentString;!this.isEnd()&&(this.isLetterOrDigitPattern.test(this.currentString=this.peek())||"_"===this.currentString);)this.currentIdentifier+=this.currentString,this.forward();return this.currentToken}peek(){return this._toParse[this._pos]}read(){return this._toParse[this._pos++]}forward(){this._pos++}isEnd(){return this._pos>=this._maxPos}}const On=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],Sn=["world","view","projection","worldView","worldViewProjection","mBones"],Fn=["translation","rotation","scale"],En=["position","rotationQuaternion","scaling"],Ln=(e,t,n)=>{for(const o in e){const s=e[o];n[t][o]=s}},In=e=>{if(e)for(let t=0;t<e.length/2;t++)e[2*t+1]=1-e[2*t+1]},Nn=e=>{if("NORMAL"===e.semantic)return"normal";if("POSITION"===e.semantic)return"position";if("JOINT"===e.semantic)return"matricesIndices";if("WEIGHT"===e.semantic)return"matricesWeights";if("COLOR"===e.semantic)return"color";if(e.semantic&&-1!==e.semantic.indexOf("TEXCOORD_")){const t=Number(e.semantic.split("_")[1]);return"uv"+(0===t?"":t+1)}return null},Pn=e=>{let n;if(e.translation||e.rotation||e.scale){const o=t.Vector3.FromArray(e.scale||[1,1,1]),s=t.Quaternion.FromArray(e.rotation||[0,0,0,1]),r=t.Vector3.FromArray(e.translation||[0,0,0]);n=t.Matrix.Compose(o,s,r)}else n=t.Matrix.FromArray(e.matrix);return n},Bn=(e,n,o,s)=>{for(let e=0;e<s.bones.length;e++)if(s.bones[e].name===o)return s.bones[e];const r=e.nodes;for(const i in r){const a=r[i];if(!a.jointName)continue;const l=a.children;for(let r=0;r<l.length;r++){const u=e.nodes[l[r]];if(u.jointName&&u.jointName===o){const o=Pn(a),r=new t.Bone(a.name||"",s,Bn(e,n,a.jointName,s),o);return r.id=i,r}}}return null},kn=(e,t)=>{for(let n=0;n<e.length;n++){const o=e[n];for(let e=0;e<o.node.children.length;e++)if(o.node.children[e]===t)return o.bone}return null},Dn=(e,t)=>{const n=e.nodes;let o=n[t];if(o)return{node:o,id:t};for(const e in n)if(o=n[e],o.jointName===t)return{node:o,id:e};return null},Gn=(e,t)=>{for(let n=0;n<e.jointNames.length;n++)if(e.jointNames[n]===t)return!0;return!1},Vn=(e,n,o,s,r)=>{if(r||(e.scene._blockEntityCollection=!!e.assetContainer,(r=new t.Mesh(n.name||"",e.scene))._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,r.id=s),!n.babylonNode)return r;const i=[];let a=null;const l=[],u=[],c=[],d=[];for(let n=0;n<o.length;n++){const s=o[n],r=e.meshes[s];if(r)for(let n=0;n<r.primitives.length;n++){const o=new t.VertexData,s=r.primitives[n];s.mode;const h=s.attributes;let m,f;for(const n in h)if(m=e.accessors[h[n]],f=Cn.GetBufferFromAccessor(e,m),"NORMAL"===n)o.normals=new Float32Array(f.length),o.normals.set(f);else if("POSITION"===n){if(mn.HomogeneousCoordinates){o.positions=new Float32Array(f.length-f.length/4);for(let e=0;e<f.length;e+=4)o.positions[e]=f[e],o.positions[e+1]=f[e+1],o.positions[e+2]=f[e+2]}else o.positions=new Float32Array(f.length),o.positions.set(f);u.push(o.positions.length)}else if(-1!==n.indexOf("TEXCOORD_")){const e=Number(n.split("_")[1]),s=t.VertexBuffer.UVKind+(0===e?"":e+1),r=new Float32Array(f.length);r.set(f),In(r),o.set(r,s)}else"JOINT"===n?(o.matricesIndices=new Float32Array(f.length),o.matricesIndices.set(f)):"WEIGHT"===n?(o.matricesWeights=new Float32Array(f.length),o.matricesWeights.set(f)):"COLOR"===n&&(o.colors=new Float32Array(f.length),o.colors.set(f));if(m=e.accessors[s.indices],m)f=Cn.GetBufferFromAccessor(e,m),o.indices=new Int32Array(f.length),o.indices.set(f),d.push(o.indices.length);else{const e=[];for(let t=0;t<o.positions.length/3;t++)e.push(t);o.indices=new Int32Array(e),d.push(o.indices.length)}a?a.merge(o):a=o;const p=e.scene.getMaterialById(s.material);i.push(null===p?Cn.GetDefaultMaterial(e.scene):p),l.push(0===l.length?0:l[l.length-1]+u[u.length-2]),c.push(0===c.length?0:c[c.length-1]+d[d.length-2])}}let h;e.scene._blockEntityCollection=!!e.assetContainer,i.length>1?(h=new t.MultiMaterial("multimat"+s,e.scene),h.subMaterials=i):h=new t.StandardMaterial("multimat"+s,e.scene),1===i.length&&(h=i[0]),h._parentContainer=e.assetContainer,r.material||(r.material=h),new t.Geometry(s,e.scene,a,!1,r),r.computeWorldMatrix(!0),e.scene._blockEntityCollection=!1,r.subMeshes=[];let m=0;for(let n=0;n<o.length;n++){const s=o[n],i=e.meshes[s];if(i)for(let e=0;e<i.primitives.length;e++)i.primitives[e].mode,t.SubMesh.AddToMesh(m,l[m],u[m],c[m],d[m],r,r,!0),m++}return r},Hn=(e,t,n,o)=>{e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=n),e.scaling&&(e.scaling=o)},Kn=(e,n,o)=>{let s=null;if(e.importOnlyMeshes&&(n.skin||n.meshes)&&e.importMeshesNames&&e.importMeshesNames.length>0&&-1===e.importMeshesNames.indexOf(n.name||""))return null;if(n.skin){if(n.meshes){const r=e.skins[n.skin],i=Vn(e,n,n.meshes,o,n.babylonNode);i.skeleton=e.scene.getLastSkeletonById(n.skin),null===i.skeleton&&(i.skeleton=((e,n,o,s)=>{if(s||(s=new t.Skeleton(n.name||"","",e.scene)),!n.babylonSkeleton)return s;const r=[],i=[];((e,n,o,s)=>{for(const r in e.nodes){const i=e.nodes[r],a=r;if(!i.jointName||Gn(o,i.jointName))continue;const l=Pn(i),u=new t.Bone(i.name||"",n,null,l);u.id=a,s.push({bone:u,node:i,id:a})}for(let e=0;e<s.length;e++){const t=s[e],n=t.node.children;for(let e=0;e<n.length;e++){let o=null;for(let t=0;t<s.length;t++)if(s[t].id===n[e]){o=s[t];break}o&&(o.bone._parent=t.bone,t.bone.children.push(o.bone))}}})(e,s,n,r),s.bones=[];for(let o=0;o<n.jointNames.length;o++){const a=Dn(e,n.jointNames[o]);if(!a)continue;const l=a.node;if(!l){t.Tools.Warn("Joint named "+n.jointNames[o]+" does not exist");continue}const u=a.id,c=e.scene.getBoneById(u);if(c){s.bones.push(c);continue}let d,h=null;for(let r=0;r<o;r++){const o=Dn(e,n.jointNames[r]);if(!o)continue;const i=o.node;if(!i){t.Tools.Warn("Joint named "+n.jointNames[r]+" does not exist when looking for parent");continue}const a=i.children;if(a){d=!1;for(let t=0;t<a.length;t++)if(a[t]===u){h=Bn(e,n,n.jointNames[r],s),d=!0;break}if(d)break}}const m=Pn(l);!h&&r.length>0&&(h=kn(r,u),h&&-1===i.indexOf(h)&&i.push(h)),new t.Bone(l.jointName||"",s,h,m).id=u}const a=s.bones;s.bones=[];for(let t=0;t<n.jointNames.length;t++){const o=Dn(e,n.jointNames[t]);if(o)for(let e=0;e<a.length;e++)if(a[e].id===o.id){s.bones.push(a[e]);break}}s.prepare();for(let e=0;e<i.length;e++)s.bones.push(i[e]);return s})(e,r,0,r.babylonSkeleton),r.babylonSkeleton||(r.babylonSkeleton=i.skeleton)),s=i}}else if(n.meshes)s=Vn(e,n,n.mesh?[n.mesh]:n.meshes,o,n.babylonNode);else if(!n.light||n.babylonNode||e.importOnlyMeshes){if(n.camera&&!n.babylonNode&&!e.importOnlyMeshes){const o=e.cameras[n.camera];if(o){if(e.scene._blockEntityCollection=!!e.assetContainer,"orthographic"===o.type){const o=new t.FreeCamera(n.camera,t.Vector3.Zero(),e.scene,!1);o.name=n.name||"",o.mode=t.Camera.ORTHOGRAPHIC_CAMERA,o.attachControl(),s=o,o._parentContainer=e.assetContainer}else if("perspective"===o.type){const r=o[o.type],i=new t.FreeCamera(n.camera,t.Vector3.Zero(),e.scene,!1);i.name=n.name||"",i.attachControl(),r.aspectRatio||(r.aspectRatio=e.scene.getEngine().getRenderWidth()/e.scene.getEngine().getRenderHeight()),r.znear&&r.zfar&&(i.maxZ=r.zfar,i.minZ=r.znear),s=i,i._parentContainer=e.assetContainer}e.scene._blockEntityCollection=!1}}}else{const o=e.lights[n.light];if(o)if("ambient"===o.type){const r=o[o.type],i=new t.HemisphericLight(n.light,t.Vector3.Zero(),e.scene);i.name=n.name||"",r.color&&(i.diffuse=t.Color3.FromArray(r.color)),s=i}else if("directional"===o.type){const r=o[o.type],i=new t.DirectionalLight(n.light,t.Vector3.Zero(),e.scene);i.name=n.name||"",r.color&&(i.diffuse=t.Color3.FromArray(r.color)),s=i}else if("point"===o.type){const r=o[o.type],i=new t.PointLight(n.light,t.Vector3.Zero(),e.scene);i.name=n.name||"",r.color&&(i.diffuse=t.Color3.FromArray(r.color)),s=i}else if("spot"===o.type){const r=o[o.type],i=new t.SpotLight(n.light,t.Vector3.Zero(),t.Vector3.Zero(),0,0,e.scene);i.name=n.name||"",r.color&&(i.diffuse=t.Color3.FromArray(r.color)),r.fallOfAngle&&(i.angle=r.fallOfAngle),r.fallOffExponent&&(i.exponent=r.fallOffExponent),s=i}}if(!n.jointName){if(n.babylonNode)return n.babylonNode;if(null===s){e.scene._blockEntityCollection=!!e.assetContainer;const o=new t.Mesh(n.name||"",e.scene);o._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,n.babylonNode=o,s=o}}if(null!==s){if(n.matrix&&s instanceof t.Mesh)((e,n)=>{if(n.matrix){const o=new t.Vector3(0,0,0),s=new t.Quaternion,r=new t.Vector3(0,0,0);t.Matrix.FromArray(n.matrix).decompose(r,s,o),Hn(e,o,s,r)}else n.translation&&n.rotation&&n.scale&&Hn(e,t.Vector3.FromArray(n.translation),t.Quaternion.FromArray(n.rotation),t.Vector3.FromArray(n.scale));e.computeWorldMatrix(!0)})(s,n);else{const e=n.translation||[0,0,0],o=n.rotation||[0,0,0,1],r=n.scale||[1,1,1];Hn(s,t.Vector3.FromArray(e),t.Quaternion.FromArray(o),t.Vector3.FromArray(r))}s.updateCache(!0),n.babylonNode=s}return s},Un=(e,t,n,o=!1)=>{const s=e.nodes[t];let r=null;if(o=!(e.importOnlyMeshes&&!o&&e.importMeshesNames)||-1!==e.importMeshesNames.indexOf(s.name||"")||0===e.importMeshesNames.length,!s.jointName&&o&&(r=Kn(e,s,t),null!==r&&(r.id=t,r.parent=n)),s.children)for(let t=0;t<s.children.length;t++)Un(e,s.children[t],r,o)},$n=e=>{let n=e.currentScene;if(n)for(let t=0;t<n.nodes.length;t++)Un(e,n.nodes[t],null);else for(const t in e.scenes){n=e.scenes[t];for(let t=0;t<n.nodes.length;t++)Un(e,n.nodes[t],null)}(e=>{for(const n in e.animations){const o=e.animations[n];if(!o.channels||!o.samplers)continue;let s=null;for(let r=0;r<o.channels.length;r++){const i=o.channels[r],a=o.samplers[i.sampler];if(!a)continue;let l,u;o.parameters?(l=o.parameters[a.input],u=o.parameters[a.output]):(l=a.input,u=a.output);const c=Cn.GetBufferFromAccessor(e,e.accessors[l]),d=Cn.GetBufferFromAccessor(e,e.accessors[u]),h=i.target.id;let m=e.scene.getNodeById(h);if(null===m&&(m=e.scene.getNodeByName(h)),null===m){t.Tools.Warn("Creating animation named "+n+". But cannot find node named "+h+" to attach to");continue}const f=m instanceof t.Bone;let p=i.target.path;const _=Fn.indexOf(p);-1!==_&&(p=En[_]);let g=t.Animation.ANIMATIONTYPE_MATRIX;f||("rotationQuaternion"===p?(g=t.Animation.ANIMATIONTYPE_QUATERNION,m.rotationQuaternion=new t.Quaternion):g=t.Animation.ANIMATIONTYPE_VECTOR3);let y=null;const v=[];let b=0,x=!1;f&&s&&s.getKeys().length===c.length&&(y=s,x=!0),x||(e.scene._blockEntityCollection=!!e.assetContainer,y=new t.Animation(n,f?"_matrix":p,1,g,t.Animation.ANIMATIONLOOPMODE_CYCLE),e.scene._blockEntityCollection=!1);for(let e=0;e<c.length;e++){let n;if("rotationQuaternion"===p?(n=t.Quaternion.FromArray([d[b],d[b+1],d[b+2],d[b+3]]),b+=4):(n=t.Vector3.FromArray([d[b],d[b+1],d[b+2]]),b+=3),f){const o=m;let r=t.Vector3.Zero(),i=new t.Quaternion,a=t.Vector3.Zero(),l=o.getBaseMatrix();x&&s&&(l=s.getKeys()[e].value),l.decompose(a,i,r),"position"===p?r=n:"rotationQuaternion"===p?i=n:a=n,n=t.Matrix.Compose(a,i,r)}x?s&&(s.getKeys()[e].value=n):v.push({frame:c[e],value:n})}!x&&y&&(y.setKeys(v),m.animations.push(y)),s=y,e.scene.stopAnimation(m),e.scene.beginAnimation(m,0,c[c.length-1],!0,1)}}})(e);for(let t=0;t<e.scene.skeletons.length;t++){const n=e.scene.skeletons[t];e.scene.beginAnimation(n,0,Number.MAX_VALUE,!0,1)}},Wn=(e,t,n)=>{for(const o in t.uniforms){const s=t.uniforms[o],r=t.parameters[s];if(e.currentIdentifier===o&&r.semantic&&!r.source&&!r.node){const e=On.indexOf(r.semantic);if(-1!==e)return delete n[o],Sn[e]}}return e.currentIdentifier},zn=e=>{for(const t in e.materials)Xn.LoadMaterialAsync(e,t,()=>{},()=>{})};class jn{static CreateRuntime(e,t,n){const o={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:t,rootUrl:n,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[],assetContainer:null};return e.extensions&&Ln(e.extensions,"extensions",o),e.extensionsUsed&&Ln(e.extensionsUsed,"extensionsUsed",o),e.buffers&&((e,t)=>{for(const n in e){const o=e[n];t.buffers[n]=o,t.buffersCount++}})(e.buffers,o),e.bufferViews&&Ln(e.bufferViews,"bufferViews",o),e.accessors&&Ln(e.accessors,"accessors",o),e.meshes&&Ln(e.meshes,"meshes",o),e.lights&&Ln(e.lights,"lights",o),e.cameras&&Ln(e.cameras,"cameras",o),e.nodes&&Ln(e.nodes,"nodes",o),e.images&&Ln(e.images,"images",o),e.textures&&Ln(e.textures,"textures",o),e.shaders&&((e,t)=>{for(const n in e){const o=e[n];t.shaders[n]=o,t.shaderscount++}})(e.shaders,o),e.programs&&Ln(e.programs,"programs",o),e.samplers&&Ln(e.samplers,"samplers",o),e.techniques&&Ln(e.techniques,"techniques",o),e.materials&&Ln(e.materials,"materials",o),e.animations&&Ln(e.animations,"animations",o),e.skins&&Ln(e.skins,"skins",o),e.scenes&&(o.scenes=e.scenes),e.scene&&e.scenes&&(o.currentScene=e.scenes[e.scene]),o}static LoadBufferAsync(e,n,o,s,r){const i=e.buffers[n];t.Tools.IsBase64(i.uri)?setTimeout(()=>o(new Uint8Array(t.Tools.DecodeBase64(i.uri)))):t.Tools.LoadFile(e.rootUrl+i.uri,e=>o(new Uint8Array(e)),r,void 0,!0,e=>{e&&s(e.status+" "+e.statusText)})}static LoadTextureBufferAsync(e,n,o,s){const r=e.textures[n];if(!r||!r.source)return void s("");if(r.babylonTexture)return void o(null);const i=e.images[r.source];t.Tools.IsBase64(i.uri)?setTimeout(()=>o(new Uint8Array(t.Tools.DecodeBase64(i.uri)))):t.Tools.LoadFile(e.rootUrl+i.uri,e=>o(new Uint8Array(e)),void 0,void 0,!0,e=>{e&&s(e.status+" "+e.statusText)})}static CreateTextureAsync(e,n,o,s){const r=e.textures[n];if(r.babylonTexture)return void s(r.babylonTexture);const i=e.samplers[r.sampler],a=i.minFilter===bn.NEAREST_MIPMAP_NEAREST||i.minFilter===bn.NEAREST_MIPMAP_LINEAR||i.minFilter===bn.LINEAR_MIPMAP_NEAREST||i.minFilter===bn.LINEAR_MIPMAP_LINEAR,l=t.Texture.BILINEAR_SAMPLINGMODE,u=null==o?new Blob:new Blob([t.GetBlobBufferSource(o)]),c=URL.createObjectURL(u),d=()=>URL.revokeObjectURL(c),h=new t.Texture(c,e.scene,!a,!0,l,d,d);void 0!==i.wrapS&&(h.wrapU=Cn.GetWrapMode(i.wrapS)),void 0!==i.wrapT&&(h.wrapV=Cn.GetWrapMode(i.wrapT)),h.name=n,r.babylonTexture=h,s(h)}static LoadShaderStringAsync(e,n,o,s){const r=e.shaders[n];if(t.Tools.IsBase64(r.uri)){const e=atob(r.uri.split(",")[1]);o&&o(e)}else t.Tools.LoadFile(e.rootUrl+r.uri,o,void 0,void 0,!1,e=>{e&&s&&s(e.status+" "+e.statusText)})}static LoadMaterialAsync(e,n,o,s){const r=e.materials[n];if(!r.technique)return void(s&&s("No technique found."));const i=e.techniques[r.technique];if(!i){e.scene._blockEntityCollection=!!e.assetContainer;const s=new t.StandardMaterial(n,e.scene);return s._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,s.diffuseColor=new t.Color3(.5,.5,.5),s.sideOrientation=t.Material.CounterClockWiseSideOrientation,void o(s)}const a=e.programs[i.program],l=i.states,u=t.Effect.ShadersStore[a.vertexShader+"VertexShader"],c=t.Effect.ShadersStore[a.fragmentShader+"PixelShader"];let d="",h="";const m=new Rn(u),f=new Rn(c),p={},_=[],g=[],y=[];for(const e in i.uniforms){const t=i.uniforms[e],n=i.parameters[t];if(p[e]=n,!n.semantic||n.node||n.source)n.type===yn.SAMPLER_2D?y.push(e):_.push(e);else{const t=On.indexOf(n.semantic);-1!==t?(_.push(Sn[t]),delete p[e]):_.push(e)}}for(const e in i.attributes){const t=i.attributes[e],n=i.parameters[t];if(n.semantic){const e=Nn(n);e&&g.push(e)}}for(;!m.isEnd()&&m.getNextToken();){if(m.currentToken!==Mn.IDENTIFIER){d+=m.currentString;continue}let e=!1;for(const t in i.attributes){const n=i.attributes[t],o=i.parameters[n];if(m.currentIdentifier===t&&o.semantic){d+=Nn(o),e=!0;break}}e||(d+=Wn(m,i,p))}for(;!f.isEnd()&&f.getNextToken();)f.currentToken===Mn.IDENTIFIER?h+=Wn(f,i,p):h+=f.currentString;const v={vertex:a.vertexShader+n,fragment:a.fragmentShader+n},b={attributes:g,uniforms:_,samplers:y,needAlphaBlending:l&&l.enable&&-1!==l.enable.indexOf(3042)};t.Effect.ShadersStore[a.vertexShader+n+"VertexShader"]=d,t.Effect.ShadersStore[a.fragmentShader+n+"PixelShader"]=h;const x=new t.ShaderMaterial(n,e.scene,v,b);if(x.onError=((e,t,n)=>(o,s)=>{t.dispose(!0),n("Cannot compile program named "+e.name+". Error: "+s+". Default material will be applied")})(a,x,s),x.onCompiled=((e,t,n,o,s,r)=>i=>{((e,t,n,o,s)=>{const r=o.values||n.parameters,i=n.uniforms;for(const n in s){const a=s[n],l=a.type;let u=r[i[n]];if(void 0===u&&(u=a.value),!u)continue;const c=e=>n=>{a.value&&e&&(t.setTexture(e,n),delete s[e])};l===yn.SAMPLER_2D?Xn.LoadTextureAsync(e,o.values?u:a.value,c(n),()=>c(null)):a.value&&Cn.SetUniform(t,n,o.values?u:a.value,l)&&delete s[n]}})(e,t,n,o,s),t.onBind=i=>{((e,t,n,o,s,r,i)=>{const a=r.values||s.parameters;for(const i in n){const l=n[i],u=l.type;if(u===yn.FLOAT_MAT2||u===yn.FLOAT_MAT3||u===yn.FLOAT_MAT4)if(!l.semantic||l.source||l.node){if(l.semantic&&(l.source||l.node)){let e=t.scene.getNodeByName(l.source||l.node||"");if(null===e&&(e=t.scene.getNodeById(l.source||l.node||"")),null===e)continue;Cn.SetMatrix(t.scene,e,l,i,o.getEffect())}}else Cn.SetMatrix(t.scene,e,l,i,o.getEffect());else{const e=a[s.uniforms[i]];if(!e)continue;if(u===yn.SAMPLER_2D){const n=t.textures[r.values?e:l.value].babylonTexture;if(null==n)continue;o.getEffect().setTexture(i,n)}else Cn.SetUniform(o.getEffect(),i,e,u)}}i(o)})(i,e,s,t,n,o,r)}})(e,x,i,r,p,o),x.sideOrientation=t.Material.CounterClockWiseSideOrientation,l&&l.functions){const e=l.functions;e.cullFace&&e.cullFace[0]!==Tn.BACK&&(x.backFaceCulling=!1);const n=e.blendFuncSeparate;n&&(n[0]===An.SRC_ALPHA&&n[1]===An.ONE_MINUS_SRC_ALPHA&&n[2]===An.ONE&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_COMBINE:n[0]===An.ONE&&n[1]===An.ONE&&n[2]===An.ZERO&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_ONEONE:n[0]===An.SRC_ALPHA&&n[1]===An.ONE&&n[2]===An.ZERO&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_ADD:n[0]===An.ZERO&&n[1]===An.ONE_MINUS_SRC_COLOR&&n[2]===An.ONE&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_SUBTRACT:n[0]===An.DST_COLOR&&n[1]===An.ZERO&&n[2]===An.ONE&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_MULTIPLY:n[0]===An.SRC_ALPHA&&n[1]===An.ONE_MINUS_SRC_COLOR&&n[2]===An.ONE&&n[3]===An.ONE&&(x.alphaMode=t.Constants.ALPHA_MAXIMIZED))}}}let qn=class e{static RegisterExtension(n){e.Extensions[n.name]?t.Tools.Error('Tool with the same name "'+n.name+'" already exists'):e.Extensions[n.name]=n}dispose(){}_importMeshAsync(e,n,o,s,r,i,a,l){return n.useRightHandedSystem=!0,Xn.LoadRuntimeAsync(n,o,s,n=>{n.assetContainer=r,n.importOnlyMeshes=!0,""===e?n.importMeshesNames=[]:"string"==typeof e?n.importMeshesNames=[e]:!e||e instanceof Array?(n.importMeshesNames=[],t.Tools.Warn("Argument meshesNames must be of type string or string[]")):n.importMeshesNames=[e],this._createNodes(n);const o=[],s=[];for(const e in n.nodes){const s=n.nodes[e];s.babylonNode instanceof t.AbstractMesh&&o.push(s.babylonNode)}for(const e in n.skins){const o=n.skins[e];o.babylonSkeleton instanceof t.Skeleton&&s.push(o.babylonSkeleton)}this._loadBuffersAsync(n,()=>{this._loadShadersAsync(n,()=>{zn(n),$n(n),!mn.IncrementalLoading&&i&&i(o,s)})}),mn.IncrementalLoading&&i&&i(o,s)},l),!0}importMeshAsync(e,t,n,o,s,r){return new Promise((i,a)=>{this._importMeshAsync(e,t,o,s,n,(e,t)=>{i({meshes:e,particleSystems:[],skeletons:t,animationGroups:[],lights:[],transformNodes:[],geometries:[],spriteManagers:[]})},r,e=>{a(new Error(e))})})}_loadAsync(e,t,n,o,s,r){e.useRightHandedSystem=!0,Xn.LoadRuntimeAsync(e,t,n,e=>{Xn.LoadRuntimeExtensionsAsync(e,()=>{this._createNodes(e),this._loadBuffersAsync(e,()=>{this._loadShadersAsync(e,()=>{zn(e),$n(e),mn.IncrementalLoading||o()})}),mn.IncrementalLoading&&o()},r)},r)}loadAsync(e,t,n,o){return b(this,void 0,void 0,function*(){return yield new Promise((s,r)=>{this._loadAsync(e,t,n,()=>{s()},o,e=>{r(new Error(e))})})})}_loadShadersAsync(e,n){let o=!1;const s=(o,s)=>{Xn.LoadShaderStringAsync(e,o,r=>{r instanceof ArrayBuffer||(e.loadedShaderCount++,r&&(t.Effect.ShadersStore[o+(s.type===gn.VERTEX?"VertexShader":"PixelShader")]=r),e.loadedShaderCount===e.shaderscount&&n())},()=>{t.Tools.Error("Error when loading shader program named "+o+" located at "+s.uri)})};for(const n in e.shaders){o=!0;const r=e.shaders[n];r?s.bind(this,n,r)():t.Tools.Error("No shader named: "+n)}o||n()}_loadBuffersAsync(e,n){let o=!1;const s=(o,s)=>{Xn.LoadBufferAsync(e,o,r=>{e.loadedBufferCount++,r&&(r.byteLength!=e.buffers[o].byteLength&&t.Tools.Error("Buffer named "+o+" is length "+r.byteLength+". Expected: "+s.byteLength),e.loadedBufferViews[o]=r),e.loadedBufferCount===e.buffersCount&&n()},()=>{t.Tools.Error("Error when loading buffer named "+o+" located at "+s.uri)})};for(const n in e.buffers){o=!0;const r=e.buffers[n];r?s.bind(this,n,r)():t.Tools.Error("No buffer named: "+n)}o||n()}_createNodes(e){let t=e.currentScene;if(t)for(let n=0;n<t.nodes.length;n++)Un(e,t.nodes[n],null);else for(const n in e.scenes){t=e.scenes[n];for(let n=0;n<t.nodes.length;n++)Un(e,t.nodes[n],null)}}};qn.Extensions={};class Xn{constructor(e){this._name=e}get name(){return this._name}loadRuntimeAsync(e,t,n,o,s){return!1}loadRuntimeExtensionsAsync(e,t,n){return!1}loadBufferAsync(e,t,n,o,s){return!1}loadTextureBufferAsync(e,t,n,o){return!1}createTextureAsync(e,t,n,o,s){return!1}loadShaderStringAsync(e,t,n,o){return!1}loadMaterialAsync(e,t,n,o){return!1}static LoadRuntimeAsync(e,t,n,o,s){Xn._ApplyExtensions(r=>r.loadRuntimeAsync(e,t,n,o,s),()=>{setTimeout(()=>{o&&o(jn.CreateRuntime(t.json,e,n))})})}static LoadRuntimeExtensionsAsync(e,t,n){Xn._ApplyExtensions(o=>o.loadRuntimeExtensionsAsync(e,t,n),()=>{setTimeout(()=>{t()})})}static LoadBufferAsync(e,t,n,o,s){Xn._ApplyExtensions(r=>r.loadBufferAsync(e,t,n,o,s),()=>{jn.LoadBufferAsync(e,t,n,o,s)})}static LoadTextureAsync(e,t,n,o){Xn._LoadTextureBufferAsync(e,t,s=>{s&&Xn._CreateTextureAsync(e,t,s,n,o)},o)}static LoadShaderStringAsync(e,t,n,o){Xn._ApplyExtensions(s=>s.loadShaderStringAsync(e,t,n,o),()=>{jn.LoadShaderStringAsync(e,t,n,o)})}static LoadMaterialAsync(e,t,n,o){Xn._ApplyExtensions(s=>s.loadMaterialAsync(e,t,n,o),()=>{jn.LoadMaterialAsync(e,t,n,o)})}static _LoadTextureBufferAsync(e,t,n,o){Xn._ApplyExtensions(s=>s.loadTextureBufferAsync(e,t,n,o),()=>{jn.LoadTextureBufferAsync(e,t,n,o)})}static _CreateTextureAsync(e,t,n,o,s){Xn._ApplyExtensions(r=>r.createTextureAsync(e,t,n,o,s),()=>{jn.CreateTextureAsync(e,t,n,o)})}static _ApplyExtensions(e,t){for(const t in qn.Extensions)if(e(qn.Extensions[t]))return;t()}}mn._CreateGLTF1Loader=()=>new qn;class Yn extends Xn{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,n,o){const s=t.json.extensionsUsed;return!(!s||-1===s.indexOf(this.name)||!t.bin||(this._bin=t.bin,o(jn.CreateRuntime(t.json,e,n)),0))}loadBufferAsync(e,t,n,o){return-1!==e.extensionsUsed.indexOf(this.name)&&"binary_glTF"===t&&(this._bin.readAsync(0,this._bin.byteLength).then(n,e=>o(e.message)),!0)}loadTextureBufferAsync(e,t,n){const o=e.textures[t],s=e.images[o.source];if(!s.extensions||!(this.name in s.extensions))return!1;const r=s.extensions[this.name],i=e.bufferViews[r.bufferView];return n(Cn.GetBufferFromBufferView(e,i,0,i.byteLength,_n.UNSIGNED_BYTE)),!0}loadShaderStringAsync(e,t,n){const o=e.shaders[t];if(!o.extensions||!(this.name in o.extensions))return!1;const s=o.extensions[this.name],r=e.bufferViews[s.bufferView],i=Cn.GetBufferFromBufferView(e,r,0,r.byteLength,_n.UNSIGNED_BYTE);return setTimeout(()=>{const e=Cn.DecodeBufferToText(i);n(e)}),!0}}qn.RegisterExtension(new Yn);class Qn extends Xn{constructor(){super("KHR_materials_common")}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;const n=e.extensions[this.name];if(!n)return!1;const o=n.lights;if(o)for(const n in o){const s=o[n];switch(s.type){case"ambient":{const n=new t.HemisphericLight(s.name,new t.Vector3(0,1,0),e.scene),o=s.ambient;o&&(n.diffuse=t.Color3.FromArray(o.color||[1,1,1]));break}case"point":{const n=new t.PointLight(s.name,new t.Vector3(10,10,10),e.scene),o=s.point;o&&(n.diffuse=t.Color3.FromArray(o.color||[1,1,1]));break}case"directional":{const n=new t.DirectionalLight(s.name,new t.Vector3(0,-1,0),e.scene),o=s.directional;o&&(n.diffuse=t.Color3.FromArray(o.color||[1,1,1]));break}case"spot":{const n=s.spot;n&&(new t.SpotLight(s.name,new t.Vector3(0,10,0),new t.Vector3(0,-1,0),n.fallOffAngle||Math.PI,n.fallOffExponent||0,e.scene).diffuse=t.Color3.FromArray(n.color||[1,1,1]));break}default:t.Tools.Warn('GLTF Material Common extension: light type "'+s.type+"” not supported")}}return!1}loadMaterialAsync(e,n,o,s){const r=e.materials[n];if(!r||!r.extensions)return!1;const i=r.extensions[this.name];if(!i)return!1;const a=new t.StandardMaterial(n,e.scene);return a.sideOrientation=t.Material.CounterClockWiseSideOrientation,"CONSTANT"===i.technique&&(a.disableLighting=!0),a.backFaceCulling=void 0!==i.doubleSided&&!i.doubleSided,a.alpha=void 0===i.values.transparency?1:i.values.transparency,a.specularPower=void 0===i.values.shininess?0:i.values.shininess,"string"==typeof i.values.ambient?this._loadTexture(e,i.values.ambient,a,"ambientTexture",s):a.ambientColor=t.Color3.FromArray(i.values.ambient||[0,0,0]),"string"==typeof i.values.diffuse?this._loadTexture(e,i.values.diffuse,a,"diffuseTexture",s):a.diffuseColor=t.Color3.FromArray(i.values.diffuse||[0,0,0]),"string"==typeof i.values.emission?this._loadTexture(e,i.values.emission,a,"emissiveTexture",s):a.emissiveColor=t.Color3.FromArray(i.values.emission||[0,0,0]),"string"==typeof i.values.specular?this._loadTexture(e,i.values.specular,a,"specularTexture",s):a.specularColor=t.Color3.FromArray(i.values.specular||[0,0,0]),!0}_loadTexture(e,t,n,o,s){jn.LoadTextureBufferAsync(e,t,s=>{jn.CreateTextureAsync(e,t,s,e=>n[o]=e)},s)}}qn.RegisterExtension(new Qn);var Zn={__proto__:null,get EBlendingFunction(){return An},get EComponentType(){return _n},get ECullingType(){return Tn},get EParameterType(){return yn},get EShaderType(){return gn},get ETextureFilterType(){return bn},get ETextureFormat(){return xn},get ETextureWrapMode(){return vn},GLTFBinaryExtension:Yn,GLTFLoader:qn,GLTFLoaderBase:jn,GLTFLoaderExtension:Xn,GLTFMaterialsCommonExtension:Qn,GLTFUtils:Cn};const Jn=new Map,eo=Jn;function to(e,n,o){no(e)&&t.Logger.Warn(`Extension with the name '${e}' already exists`),Jn.set(e,{isGLTFExtension:n,factory:o})}function no(e){return Jn.delete(e)}const oo=[{regex:new RegExp("^/nodes/\\d+/extensions/")}];class so{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t,n=this._gltf,o=this._infoTree;if(!e.startsWith("/"))throw new Error("Path must start with a /");const s=e.split("/");if(s.shift(),s[s.length-1].includes(".length")){const e=s[s.length-1].split(".");s.pop(),s.push(...e)}let r=!1;for(const i of s){const s="length"===i;if(s&&!o.__array__)throw new Error(`Path ${e} is invalid`);if(o.__ignoreObjectTree__&&(r=!0),o.__array__&&!s)o=o.__array__;else if(o=o[i],!o)throw new Error(`Path ${e} is invalid`);if(!r)if(void 0===n){if(!oo.find(t=>t.regex.test(e)))throw new Error(`Path ${e} is invalid`)}else s||(n=null==n?void 0:n[i]);(o.__target__||s)&&(t=n)}return{object:t,info:o}}}function ro(e,t,n,o){const s=io(e);return o?s[n][o]:s[n]}function io(e,n,o){var s,r,i;return null===(i=null===(s=e._data)||void 0===s?void 0:s[null!==(r=null==o?void 0:o.fillMode)&&void 0!==r?r:t.Constants.MATERIAL_TriangleFillMode])||void 0===i?void 0:i.babylonMaterial}function ao(e,n){return{offset:{componentsCount:2,type:"Vector2",get:(o,s,r)=>{const i=ro(o,0,e,n);return new t.Vector2(null==i?void 0:i.uOffset,null==i?void 0:i.vOffset)},getTarget:io,set:(t,o,s,r)=>{const i=ro(o,0,e,n);i.uOffset=t.x,i.vOffset=t.y},getPropertyName:[()=>`${e}${n?"."+n:""}.uOffset`,()=>`${e}${n?"."+n:""}.vOffset`]},rotation:{type:"number",get:(t,o,s)=>{var r;return null===(r=ro(t,0,e,n))||void 0===r?void 0:r.wAng},getTarget:io,set:(t,o,s,r)=>ro(o,0,e,n).wAng=t,getPropertyName:[()=>`${e}${n?"."+n:""}.wAng`]},scale:{componentsCount:2,type:"Vector2",get:(o,s,r)=>{const i=ro(o,0,e,n);return new t.Vector2(null==i?void 0:i.uScale,null==i?void 0:i.vScale)},getTarget:io,set:(t,o,s,r)=>{const i=ro(o,0,e,n);i.uScale=t.x,i.vScale=t.y},getPropertyName:[()=>`${e}${n?"."+n:""}.uScale`,()=>`${e}${n?"."+n:""}.vScale`]}}}const lo={cameras:{__array__:{__target__:!0,orthographic:{xmag:{componentsCount:2,type:"Vector2",get:e=>{var n,o,s,r;return new t.Vector2(null!==(o=null===(n=e._babylonCamera)||void 0===n?void 0:n.orthoLeft)&&void 0!==o?o:0,null!==(r=null===(s=e._babylonCamera)||void 0===s?void 0:s.orthoRight)&&void 0!==r?r:0)},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.orthoLeft=e.x,t._babylonCamera.orthoRight=e.y)},getTarget:e=>e,getPropertyName:[()=>"orthoLeft",()=>"orthoRight"]},ymag:{componentsCount:2,type:"Vector2",get:e=>{var n,o,s,r;return new t.Vector2(null!==(o=null===(n=e._babylonCamera)||void 0===n?void 0:n.orthoBottom)&&void 0!==o?o:0,null!==(r=null===(s=e._babylonCamera)||void 0===s?void 0:s.orthoTop)&&void 0!==r?r:0)},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.orthoBottom=e.x,t._babylonCamera.orthoTop=e.y)},getTarget:e=>e,getPropertyName:[()=>"orthoBottom",()=>"orthoTop"]},zfar:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.maxZ},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.maxZ=e)},getTarget:e=>e,getPropertyName:[()=>"maxZ"]},znear:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.minZ},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.minZ=e)},getTarget:e=>e,getPropertyName:[()=>"minZ"]}},perspective:{aspectRatio:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.getEngine().getAspectRatio(e._babylonCamera)},getTarget:e=>e,getPropertyName:[()=>"aspectRatio"],isReadOnly:!0},yfov:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.fov},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.fov=e)},getTarget:e=>e,getPropertyName:[()=>"fov"]},zfar:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.maxZ},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.maxZ=e)},getTarget:e=>e,getPropertyName:[()=>"maxZ"]},znear:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.minZ},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.minZ=e)},getTarget:e=>e,getPropertyName:[()=>"minZ"]}}}},nodes:{length:{type:"number",get:e=>e.length,getTarget:e=>e.map(e=>e._babylonTransformNode),getPropertyName:[()=>"length"]},__array__:{__target__:!0,translation:{type:"Vector3",get:e=>{var t;return null===(t=e._babylonTransformNode)||void 0===t?void 0:t.position},set:(e,t)=>{var n;return null===(n=t._babylonTransformNode)||void 0===n?void 0:n.position.copyFrom(e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"position"]},rotation:{type:"Quaternion",get:e=>{var t;return null===(t=e._babylonTransformNode)||void 0===t?void 0:t.rotationQuaternion},set:(e,t)=>{var n,o;return null===(o=null===(n=t._babylonTransformNode)||void 0===n?void 0:n.rotationQuaternion)||void 0===o?void 0:o.copyFrom(e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"rotationQuaternion"]},scale:{type:"Vector3",get:e=>{var t;return null===(t=e._babylonTransformNode)||void 0===t?void 0:t.scaling},set:(e,t)=>{var n;return null===(n=t._babylonTransformNode)||void 0===n?void 0:n.scaling.copyFrom(e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"scaling"]},weights:{length:{type:"number",get:e=>e._numMorphTargets,getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"influence"]},__array__:{__target__:!0,type:"number",get:(e,t)=>{var n,o;return void 0!==t?null===(o=null===(n=e._primitiveBabylonMeshes)||void 0===n?void 0:n[0].morphTargetManager)||void 0===o?void 0:o.getTarget(t).influence:void 0},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"influence"]},type:"number[]",get:(e,t)=>[0],getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"influence"]},matrix:{type:"Matrix",get:e=>{var n,o,s;return t.Matrix.Compose(null===(n=e._babylonTransformNode)||void 0===n?void 0:n.scaling,null===(o=e._babylonTransformNode)||void 0===o?void 0:o.rotationQuaternion,null===(s=e._babylonTransformNode)||void 0===s?void 0:s.position)},getTarget:e=>e._babylonTransformNode,isReadOnly:!0},globalMatrix:{type:"Matrix",get:e=>{var n,o,s,r,i,a,l;const u=t.Matrix.Identity();let c=e.parent;for(;c&&c.parent;)c=c.parent;const d=(null===(n=e._babylonTransformNode)||void 0===n?void 0:n.position._isDirty)||(null===(s=null===(o=e._babylonTransformNode)||void 0===o?void 0:o.rotationQuaternion)||void 0===s?void 0:s._isDirty)||(null===(r=e._babylonTransformNode)||void 0===r?void 0:r.scaling._isDirty);if(c){const t=null===(i=c._babylonTransformNode)||void 0===i?void 0:i.computeWorldMatrix(!0).invert();t&&(null===(l=null===(a=e._babylonTransformNode)||void 0===a?void 0:a.computeWorldMatrix(d))||void 0===l||l.multiplyToRef(t,u))}else e._babylonTransformNode&&u.copyFrom(e._babylonTransformNode.computeWorldMatrix(d));return u},getTarget:e=>e._babylonTransformNode,isReadOnly:!0},extensions:{EXT_lights_ies:{multiplier:{type:"number",get:e=>{var n,o;return null===(o=null===(n=e._babylonTransformNode)||void 0===n?void 0:n.getChildren(e=>e instanceof t.SpotLight,!0)[0])||void 0===o?void 0:o.intensity},getTarget:e=>{var n;return null===(n=e._babylonTransformNode)||void 0===n?void 0:n.getChildren(e=>e instanceof t.SpotLight,!0)[0]},set:(e,n)=>{if(n._babylonTransformNode){const o=n._babylonTransformNode.getChildren(e=>e instanceof t.SpotLight,!0)[0];o&&(o.intensity=e)}}},color:{type:"Color3",get:e=>{var n,o;return null===(o=null===(n=e._babylonTransformNode)||void 0===n?void 0:n.getChildren(e=>e instanceof t.SpotLight,!0)[0])||void 0===o?void 0:o.diffuse},getTarget:e=>{var n;return null===(n=e._babylonTransformNode)||void 0===n?void 0:n.getChildren(e=>e instanceof t.SpotLight,!0)[0]},set:(e,n)=>{if(n._babylonTransformNode){const o=n._babylonTransformNode.getChildren(e=>e instanceof t.SpotLight,!0)[0];o&&(o.diffuse=e)}}}},KHR_node_visibility:{visible:{type:"boolean",get:e=>!!e._primitiveBabylonMeshes&&e._primitiveBabylonMeshes[0].isVisible,getTarget:()=>{},set:(e,t)=>{t._primitiveBabylonMeshes&&t._primitiveBabylonMeshes.forEach(t=>t.isVisible=e)}}}}}},materials:{__array__:{__target__:!0,emissiveFactor:{type:"Color3",get:(e,t,n)=>io(e,0,n).emissiveColor,set:(e,t,n,o)=>io(t,0,o).emissiveColor.copyFrom(e),getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"emissiveColor"]},emissiveTexture:{extensions:{KHR_texture_transform:ao("emissiveTexture")}},normalTexture:{scale:{type:"number",get:(e,t,n)=>{var o;return null===(o=ro(e,0,"bumpTexture"))||void 0===o?void 0:o.level},set:(e,t,n,o)=>{const s=ro(t,0,"bumpTexture");s&&(s.level=e)},getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"level"]},extensions:{KHR_texture_transform:ao("bumpTexture")}},occlusionTexture:{strength:{type:"number",get:(e,t,n)=>io(e,0,n).ambientTextureStrength,set:(e,t,n,o)=>{const s=io(t,0,o);s&&(s.ambientTextureStrength=e)},getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"ambientTextureStrength"]},extensions:{KHR_texture_transform:ao("ambientTexture")}},pbrMetallicRoughness:{baseColorFactor:{type:"Color4",get:(e,n,o)=>{const s=io(e,0,o);return t.Color4.FromColor3(s.albedoColor,s.alpha)},set:(e,t,n,o)=>{const s=io(t,0,o);s.albedoColor.set(e.r,e.g,e.b),s.alpha=e.a},getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"albedoColor",()=>"alpha"]},baseColorTexture:{extensions:{KHR_texture_transform:ao("albedoTexture")}},metallicFactor:{type:"number",get:(e,t,n)=>io(e,0,n).metallic,set:(e,t,n,o)=>{const s=io(t,0,o);s&&(s.metallic=e)},getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"metallic"]},roughnessFactor:{type:"number",get:(e,t,n)=>io(e,0,n).roughness,set:(e,t,n,o)=>{const s=io(t,0,o);s&&(s.roughness=e)},getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"roughness"]},metallicRoughnessTexture:{extensions:{KHR_texture_transform:ao("metallicTexture")}}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:{type:"number",get:(e,t,n)=>io(e,0,n).anisotropy.intensity,set:(e,t,n,o)=>{io(t,0,o).anisotropy.intensity=e},getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"anisotropy.intensity"]},anisotropyRotation:{type:"number",get:(e,t,n)=>io(e,0,n).anisotropy.angle,set:(e,t,n,o)=>{io(t,0,o).anisotropy.angle=e},getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"anisotropy.angle"]},anisotropyTexture:{extensions:{KHR_texture_transform:ao("anisotropy","texture")}}},KHR_materials_clearcoat:{clearcoatFactor:{type:"number",get:(e,t,n)=>io(e,0,n).clearCoat.intensity,set:(e,t,n,o)=>{io(t,0,o).clearCoat.intensity=e},getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"clearCoat.intensity"]},clearcoatRoughnessFactor:{type:"number",get:(e,t,n)=>io(e,0,n).clearCoat.roughness,set:(e,t,n,o)=>{io(t,0,o).clearCoat.roughness=e},getTarget:(e,t,n)=>io(e,0,n),getPropertyName:[()=>"clearCoat.roughness"]},clearcoatTexture:{extensions:{KHR_texture_transform:ao("clearCoat","texture")}},clearcoatNormalTexture:{scale:{type:"number",get:(e,t,n)=>{var o;return null===(o=io(e,0,n).clearCoat.bumpTexture)||void 0===o?void 0:o.level},getTarget:io,set:(e,t,n,o)=>io(t,0,o).clearCoat.bumpTexture.level=e},extensions:{KHR_texture_transform:ao("clearCoat","bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:ao("clearCoat","textureRoughness")}}},KHR_materials_dispersion:{dispersion:{type:"number",get:(e,t,n)=>io(e,0,n).subSurface.dispersion,getTarget:io,set:(e,t,n,o)=>io(t,0,o).subSurface.dispersion=e}},KHR_materials_emissive_strength:{emissiveStrength:{type:"number",get:(e,t,n)=>io(e,0,n).emissiveIntensity,getTarget:io,set:(e,t,n,o)=>io(t,0,o).emissiveIntensity=e}},KHR_materials_ior:{ior:{type:"number",get:(e,t,n)=>io(e,0,n).indexOfRefraction,getTarget:io,set:(e,t,n,o)=>io(t,0,o).indexOfRefraction=e}},KHR_materials_iridescence:{iridescenceFactor:{type:"number",get:(e,t,n)=>io(e,0,n).iridescence.intensity,getTarget:io,set:(e,t,n,o)=>io(t,0,o).iridescence.intensity=e},iridescenceIor:{type:"number",get:(e,t,n)=>io(e,0,n).iridescence.indexOfRefraction,getTarget:io,set:(e,t,n,o)=>io(t,0,o).iridescence.indexOfRefraction=e},iridescenceTexture:{extensions:{KHR_texture_transform:ao("iridescence","texture")}},iridescenceThicknessMaximum:{type:"number",get:(e,t,n)=>io(e,0,n).iridescence.maximumThickness,getTarget:io,set:(e,t,n,o)=>io(t,0,o).iridescence.maximumThickness=e},iridescenceThicknessMinimum:{type:"number",get:(e,t,n)=>io(e,0,n).iridescence.minimumThickness,getTarget:io,set:(e,t,n,o)=>io(t,0,o).iridescence.minimumThickness=e},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:ao("iridescence","thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:{type:"Color3",get:(e,t,n)=>io(e,0,n).sheen.color,getTarget:io,set:(e,t,n,o)=>io(t,0,o).sheen.color.copyFrom(e)},sheenColorTexture:{extensions:{KHR_texture_transform:ao("sheen","texture")}},sheenRoughnessFactor:{type:"number",get:(e,t,n)=>io(e,0,n).sheen.intensity,getTarget:io,set:(e,t,n,o)=>io(t,0,o).sheen.intensity=e},sheenRoughnessTexture:{extensions:{KHR_texture_transform:ao("sheen","thicknessTexture")}}},KHR_materials_specular:{specularFactor:{type:"number",get:(e,t,n)=>io(e,0,n).metallicF0Factor,getTarget:io,set:(e,t,n,o)=>io(t,0,o).metallicF0Factor=e,getPropertyName:[()=>"metallicF0Factor"]},specularColorFactor:{type:"Color3",get:(e,t,n)=>io(e,0,n).metallicReflectanceColor,getTarget:io,set:(e,t,n,o)=>io(t,0,o).metallicReflectanceColor.copyFrom(e),getPropertyName:[()=>"metallicReflectanceColor"]},specularTexture:{extensions:{KHR_texture_transform:ao("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:ao("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:{type:"number",get:(e,t,n)=>io(e,0,n).subSurface.refractionIntensity,getTarget:io,set:(e,t,n,o)=>io(t,0,o).subSurface.refractionIntensity=e,getPropertyName:[()=>"subSurface.refractionIntensity"]},transmissionTexture:{extensions:{KHR_texture_transform:ao("subSurface","refractionIntensityTexture")}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:{type:"number",get:(e,t,n)=>io(e,0,n).subSurface.translucencyIntensity,getTarget:io,set:(e,t,n,o)=>io(t,0,o).subSurface.translucencyIntensity=e},diffuseTransmissionTexture:{extensions:{KHR_texture_transform:ao("subSurface","translucencyIntensityTexture")}},diffuseTransmissionColorFactor:{type:"Color3",get:(e,t,n)=>io(e,0,n).subSurface.translucencyColor,getTarget:io,set:(e,t,n,o)=>{var s;return e&&(null===(s=io(t,0,o).subSurface.translucencyColor)||void 0===s?void 0:s.copyFrom(e))}},diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:ao("subSurface","translucencyColorTexture")}}},KHR_materials_volume:{attenuationColor:{type:"Color3",get:(e,t,n)=>io(e,0,n).subSurface.tintColor,getTarget:io,set:(e,t,n,o)=>io(t,0,o).subSurface.tintColor.copyFrom(e)},attenuationDistance:{type:"number",get:(e,t,n)=>io(e,0,n).subSurface.tintColorAtDistance,getTarget:io,set:(e,t,n,o)=>io(t,0,o).subSurface.tintColorAtDistance=e},thicknessFactor:{type:"number",get:(e,t,n)=>io(e,0,n).subSurface.maximumThickness,getTarget:io,set:(e,t,n,o)=>io(t,0,o).subSurface.maximumThickness=e},thicknessTexture:{extensions:{KHR_texture_transform:ao("subSurface","thicknessTexture")}}}}}},extensions:{KHR_lights_punctual:{lights:{length:{type:"number",get:e=>e.length,getTarget:e=>e.map(e=>e._babylonLight),getPropertyName:[e=>"length"]},__array__:{__target__:!0,color:{type:"Color3",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.diffuse},set:(e,t)=>{var n;return null===(n=t._babylonLight)||void 0===n?void 0:n.diffuse.copyFrom(e)},getTarget:e=>e._babylonLight,getPropertyName:[e=>"diffuse"]},intensity:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.intensity},set:(e,t)=>t._babylonLight?t._babylonLight.intensity=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"intensity"]},range:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.range},set:(e,t)=>t._babylonLight?t._babylonLight.range=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"range"]},spot:{innerConeAngle:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.innerAngle},set:(e,t)=>t._babylonLight?t._babylonLight.innerAngle=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"innerConeAngle"]},outerConeAngle:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.angle},set:(e,t)=>t._babylonLight?t._babylonLight.angle=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"outerConeAngle"]}}}}},EXT_lights_area:{lights:{length:{type:"number",get:e=>e.length,getTarget:e=>e.map(e=>e._babylonLight),getPropertyName:[e=>"length"]},__array__:{__target__:!0,color:{type:"Color3",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.diffuse},set:(e,t)=>{var n;return null===(n=t._babylonLight)||void 0===n?void 0:n.diffuse.copyFrom(e)},getTarget:e=>e._babylonLight,getPropertyName:[e=>"diffuse"]},intensity:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.intensity},set:(e,t)=>t._babylonLight?t._babylonLight.intensity=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"intensity"]},size:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.height},set:(e,t)=>t._babylonLight?t._babylonLight.height=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"size"]},rect:{aspect:{type:"number",get:e=>{var t,n;return(null===(t=e._babylonLight)||void 0===t?void 0:t.width)/(null===(n=e._babylonLight)||void 0===n?void 0:n.height)},set:(e,t)=>t._babylonLight?t._babylonLight.width=e*t._babylonLight.height:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"aspect"]}}}}},EXT_lights_ies:{lights:{length:{type:"number",get:e=>e.length,getTarget:e=>e.map(e=>e._babylonLight),getPropertyName:[e=>"length"]}}},EXT_lights_image_based:{lights:{length:{type:"number",get:e=>e.length,getTarget:e=>e.map(e=>e._babylonTexture),getPropertyName:[e=>"length"]},__array__:{__target__:!0,intensity:{type:"number",get:e=>{var t;return null===(t=e._babylonTexture)||void 0===t?void 0:t.level},set:(e,t)=>{t._babylonTexture&&(t._babylonTexture.level=e)},getTarget:e=>e._babylonTexture},rotation:{type:"Quaternion",get:e=>{var n;return e._babylonTexture&&t.Quaternion.FromRotationMatrix(null===(n=e._babylonTexture)||void 0===n?void 0:n.getReflectionTextureMatrix())},set:(e,n)=>{var o;n._babylonTexture&&((null===(o=n._babylonTexture.getScene())||void 0===o?void 0:o.useRightHandedSystem)||(e=t.Quaternion.Inverse(e)),t.Matrix.FromQuaternionToRef(e,n._babylonTexture.getReflectionTextureMatrix()))},getTarget:e=>e._babylonTexture}}}}},animations:{length:{type:"number",get:e=>e.length,getTarget:e=>e.map(e=>e._babylonAnimationGroup),getPropertyName:[()=>"length"]},__array__:{}},meshes:{length:{type:"number",get:e=>e.length,getTarget:e=>e.map(e=>{var t;return null===(t=e.primitives[0]._instanceData)||void 0===t?void 0:t.babylonSourceMesh}),getPropertyName:[()=>"length"]},__array__:{}}};function uo(e){return new so(e,lo)}function co(e){const t=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let n=lo;for(const e of t)e&&(n=n[e]);if(n&&n.type&&n.get)return n}function ho(e,t){const n=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let o=lo;for(const e of n)e&&(o=o[e]);o&&o.type&&o.get&&(o.interpolation=t)}function mo(e,t){const n=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let o=lo;for(const e of n)if(e){if(!o[e]){if("?"===e){o.__ignoreObjectTree__=!0;continue}o[e]={},"__array__"===e&&(o[e].__target__=!0)}o=o[e]}Object.assign(o,t)}const fo=new t.Lazy(()=>Promise.resolve(BABYLON)),po=new t.Lazy(()=>Promise.resolve().then(function(){return Oo}));class _o{static Get(e,t,n){if(!t||null==n||!t[n])throw new Error(`${e}: Failed to find index (${n})`);return t[n]}static TryGet(e,t){return e&&null!=t&&e[t]?e[t]:null}static Assign(e){if(e)for(let t=0;t<e.length;t++)e[t].index=t}}function go(e){if(e.min&&e.max){const n=e.min,o=e.max,s=t.TmpVectors.Vector3[0].copyFromFloats(n[0],n[1],n[2]),r=t.TmpVectors.Vector3[1].copyFromFloats(o[0],o[1],o[2]);if(e.normalized&&5126!==e.componentType){let t=1;switch(e.componentType){case 5120:t=127;break;case 5121:t=255;break;case 5122:t=32767;break;case 5123:t=65535}const n=1/t;s.scaleInPlace(n),r.scaleInPlace(n)}return new t.BoundingInfo(s,r)}return null}class yo{isMatchingMaterialType(e){if(!e)return!1;const t=Array.from(this._pbrMaterialImpls.values());for(const n of t)if(e instanceof n.materialClass)return!0;return!1}static RegisterExtension(e,t){to(e,!1,t)}static UnregisterExtension(e){return no(e)}get gltf(){if(!this._gltf)throw new Error("glTF JSON is not available");return this._gltf}get bin(){return this._bin}get parent(){return this._parent}get babylonScene(){if(!this._babylonScene)throw new Error("Scene is not available");return this._babylonScene}get rootBabylonMesh(){return this._rootBabylonMesh}get rootUrl(){return this._rootUrl}constructor(e){this._completePromises=new Array,this._assetContainer=null,this._babylonLights=[],this._disableInstancedMesh=0,this._allMaterialsDirtyRequired=!1,this._skipStartAnimationStep=!1,this._extensions=new Array,this._disposed=!1,this._rootUrl=null,this._fileName=null,this._uniqueRootUrl=null,this._bin=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions=new Array,this._materialAdapterCache=new WeakMap,this._materialAdapters=new Set,this._pbrMaterialImpls=new Map,this._parent=e}_getOrCreateMaterialAdapter(e){let t=this._materialAdapterCache.get(e);if(!t){const n=Array.from(this._pbrMaterialImpls.values());for(const o of n)if(e instanceof o.materialClass){t=new o.adapterClass(e);break}if(!t)throw new Error("Appropriate material adapter class not found");const o=t;this._materialAdapterCache.set(e,o),this._materialAdapters.add(o)}return t}dispose(){this._disposed||(this._disposed=!0,this._completePromises.length=0,this._extensions.forEach(e=>e.dispose&&e.dispose()),this._extensions.length=0,this._materialAdapters.clear(),this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose())}importMeshAsync(e,t,n,o,s,r){return b(this,arguments,void 0,function*(e,t,n,o,s,r,i=""){return yield Promise.resolve().then(()=>b(this,void 0,void 0,function*(){this._babylonScene=t,this._assetContainer=n,this._loadData(o);let r=null;if(e){const t={};if(this._gltf.nodes)for(const e of this._gltf.nodes)e.name&&(t[e.name]=e.index);r=(e instanceof Array?e:[e]).map(e=>{const n=t[e];if(void 0===n)throw new Error(`Failed to find node '${e}'`);return n})}return yield this._loadAsync(s,i,r,()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]}))}))})}loadAsync(e,t,n,o){return b(this,arguments,void 0,function*(e,t,n,o,s=""){return this._babylonScene=e,this._loadData(t),yield this._loadAsync(n,s,null,()=>{})})}_loadAsync(n,o,s,r){return b(this,void 0,void 0,function*(){return yield Promise.resolve().then(()=>b(this,void 0,void 0,function*(){var i;if(this._rootUrl=n,this._uniqueRootUrl=!n.startsWith("file:")&&o?n:`${n}${Date.now()}/`,this._fileName=o,this._allMaterialsDirtyRequired=!1,yield this._loadExtensionsAsync(),!this.parent.skipMaterials){const e=this.parent.useOpenPBR||this.isExtensionUsed("KHR_materials_openpbr");let t=!1;this.parent.useOpenPBR?(null===(i=this._gltf.materials)||void 0===i?void 0:i.length)&&this._gltf.materials.some(e=>{var t;return!(null===(t=e.extensions)||void 0===t?void 0:t.KHR_materials_openpbr)})&&(t=!0):t=!0;const n=[];e&&!this._pbrMaterialImpls.has("openpbr")&&n.push(Promise.all([Promise.resolve(BABYLON),Promise.resolve().then(function(){return Fo})]).then(([{OpenPBRMaterial:e,RegisterOpenpbrMaterial:t},{OpenPBRMaterialLoadingAdapter:n}])=>{t(),this._pbrMaterialImpls.set("openpbr",{materialClass:e,adapterClass:n})})),t&&!this._pbrMaterialImpls.has("pbr")&&n.push(Promise.all([Promise.resolve(BABYLON),Promise.resolve().then(function(){return Lo})]).then(([{PBRMaterial:e,RegisterPbrMaterial:t},{PBRMaterialLoadingAdapter:n}])=>{t(),this._pbrMaterialImpls.set("pbr",{materialClass:e,adapterClass:n})})),yield Promise.all(n)}const a=`${e.GLTFLoaderState[e.GLTFLoaderState.LOADING]} => ${e.GLTFLoaderState[e.GLTFLoaderState.READY]}`,l=`${e.GLTFLoaderState[e.GLTFLoaderState.LOADING]} => ${e.GLTFLoaderState[e.GLTFLoaderState.COMPLETE]}`;this._parent._startPerformanceCounter(a),this._parent._startPerformanceCounter(l),this._parent._setState(e.GLTFLoaderState.LOADING),this._extensionsOnLoading();const u=new Array,c=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials)if(s)u.push(this.loadSceneAsync("/nodes",{nodes:s,index:-1}));else if(null!=this._gltf.scene||this._gltf.scenes&&this._gltf.scenes[0]){const e=_o.Get("/scene",this._gltf.scenes,this._gltf.scene||0);u.push(this.loadSceneAsync(`/scenes/${e.index}`,e))}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let e=0;e<this._gltf.materials.length;++e){const n=this._gltf.materials[e],o="/materials/"+e,s=t.Material.TriangleFillMode;u.push(this._loadMaterialAsync(o,n,null,s,()=>{}))}this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=c:this._babylonScene._forceBlockMaterialDirtyMechanism(c),this._parent.compileMaterials&&u.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&u.push(this._compileShadowGeneratorsAsync());const d=Promise.all(u).then(()=>{this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0);for(const e of this._babylonScene.materials){const t=e;void 0!==t.maxSimultaneousLights&&(t.maxSimultaneousLights=Math.max(t.maxSimultaneousLights,this._babylonScene.lights.length))}for(const e of Array.from(this._materialAdapters))this._completePromises.push(e.finalizeAsync(this));return this._extensionsOnReady(),this._parent._setState(e.GLTFLoaderState.READY),this._skipStartAnimationStep||this._startAnimations(),r()});return yield d.then(n=>(this._parent._endPerformanceCounter(a),t.Tools.SetImmediate(()=>{this._disposed||Promise.all(this._completePromises).then(()=>{this._parent._endPerformanceCounter(l),this._parent._setState(e.GLTFLoaderState.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()},e=>{this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()})}),n))})).catch(e=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()),e})})}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){const n=this._gltf.buffers;if(n&&n[0]&&!n[0].uri){const o=n[0];(o.byteLength<e.bin.byteLength-3||o.byteLength>e.bin.byteLength)&&t.Logger.Warn(`Binary buffer length (${o.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else t.Logger.Warn("Unexpected BIN chunk")}}_setupData(){if(_o.Assign(this._gltf.accessors),_o.Assign(this._gltf.animations),_o.Assign(this._gltf.buffers),_o.Assign(this._gltf.bufferViews),_o.Assign(this._gltf.cameras),_o.Assign(this._gltf.images),_o.Assign(this._gltf.materials),_o.Assign(this._gltf.meshes),_o.Assign(this._gltf.nodes),_o.Assign(this._gltf.samplers),_o.Assign(this._gltf.scenes),_o.Assign(this._gltf.skins),_o.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const t of this._gltf.nodes)if(t.children)for(const n of t.children)e[n]=t.index;const t=this._createRootNode();for(const n of this._gltf.nodes){const o=e[n.index];n.parent=void 0===o?t:this._gltf.nodes[o]}}}_loadExtensionsAsync(){return b(this,void 0,void 0,function*(){var e;const n=[];if(eo.forEach((e,o)=>{var s;!1===(null===(s=this.parent.extensionOptions[o])||void 0===s?void 0:s.enabled)?e.isGLTFExtension&&this.isExtensionUsed(o)&&t.Logger.Warn(`Extension ${o} is used but has been explicitly disabled.`):e.isGLTFExtension&&!this.isExtensionUsed(o)||n.push((()=>b(this,void 0,void 0,function*(){const n=yield e.factory(this);return n.name!==o&&t.Logger.Warn(`The name of the glTF loader extension instance does not match the registered name: ${n.name} !== ${o}`),this._parent.onExtensionLoadedObservable.notifyObservers(n),n}))())}),this._extensions.push(...yield Promise.all(n)),this._extensions.sort((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE)),this._parent.onExtensionLoadedObservable.clear(),this._gltf.extensionsRequired)for(const t of this._gltf.extensionsRequired)if(!this._extensions.some(e=>e.name===t&&e.enabled)){if(!1===(null===(e=this.parent.extensionOptions[t])||void 0===e?void 0:e.enabled))throw new Error(`Required extension ${t} is disabled`);throw new Error(`Required extension ${t} is not available`)}})}_createRootNode(){if(void 0!==this._parent.customRootNode)return this._rootBabylonMesh=this._parent.customRootNode,{_babylonTransformNode:null===this._rootBabylonMesh?void 0:this._rootBabylonMesh,index:-1};this._babylonScene._blockEntityCollection=!!this._assetContainer;const n=new t.Mesh("__root__",this._babylonScene);this._rootBabylonMesh=n,this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);const o={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case e.GLTFLoaderCoordinateSystemMode.AUTO:this._babylonScene.useRightHandedSystem||(o.rotation=[0,1,0,0],o.scale=[1,1,-1],yo._LoadTransform(o,this._rootBabylonMesh));break;case e.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:this._babylonScene.useRightHandedSystem=!0;break;default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(n),o}loadSceneAsync(e,t){const n=this._extensionsLoadSceneAsync(e,t);if(n)return n;const o=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const n of t.nodes){const t=_o.Get(`${e}/nodes/${n}`,this._gltf.nodes,n);o.push(this.loadNodeAsync(`/nodes/${t.index}`,t,e=>{e.parent=this._rootBabylonMesh}))}for(const e of this._postSceneLoadActions)e();return o.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(o).then(()=>{})}_forEachPrimitive(e,t){if(e._primitiveBabylonMeshes)for(const n of e._primitiveBabylonMeshes)t(n)}_getGeometries(){const e=[],t=this._gltf.nodes;if(t)for(const n of t)this._forEachPrimitive(n,t=>{const n=t.geometry;n&&-1===e.indexOf(n)&&e.push(n)});return e}_getMeshes(){const e=[];this._rootBabylonMesh instanceof t.AbstractMesh&&e.push(this._rootBabylonMesh);const n=this._gltf.nodes;if(n)for(const t of n)this._forEachPrimitive(t,t=>{e.push(t)});return e}_getTransformNodes(){const e=[],t=this._gltf.nodes;if(t)for(const n of t)n._babylonTransformNode&&"TransformNode"===n._babylonTransformNode.getClassName()&&e.push(n._babylonTransformNode),n._babylonTransformNodeForSkin&&e.push(n._babylonTransformNodeForSkin);return e}_getSkeletons(){const e=[],t=this._gltf.skins;if(t)for(const n of t)n._data&&e.push(n._data.babylonSkeleton);return e}_getAnimationGroups(){const e=[],t=this._gltf.animations;if(t)for(const n of t)n._babylonAnimationGroup&&e.push(n._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case e.GLTFLoaderAnimationStartMode.NONE:break;case e.GLTFLoaderAnimationStartMode.FIRST:{const e=this._getAnimationGroups();0!==e.length&&e[0].start(!0);break}case e.GLTFLoaderAnimationStartMode.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:return void t.Logger.Error(`Invalid animation start mode (${this._parent.animationStartMode})`)}}loadNodeAsync(e,n,o=()=>{}){const s=this._extensionsLoadNodeAsync(e,n,o);if(s)return s;if(n._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const r=new Array;this.logOpen(`${e} ${n.name||""}`);const i=t=>{if(yo.AddPointerMetadata(t,e),yo._LoadTransform(n,t),null!=n.camera){const o=_o.Get(`${e}/camera`,this._gltf.cameras,n.camera);r.push(this.loadCameraAsync(`/cameras/${o.index}`,o,e=>{e.parent=t,this._babylonScene.useRightHandedSystem||(t.scaling.x=-1)}))}if(n.children)for(const o of n.children){const n=_o.Get(`${e}/children/${o}`,this._gltf.nodes,o);r.push(this.loadNodeAsync(`/nodes/${n.index}`,n,e=>{e.parent=t}))}o(t)},a=null!=n.mesh,l=this._parent.loadSkins&&null!=n.skin;if(!a||l){const e=n.name||`node${n.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new t.TransformNode(e,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,null==n.mesh?n._babylonTransformNode=o:n._babylonTransformNodeForSkin=o,i(o)}if(a)if(l){const o=_o.Get(`${e}/mesh`,this._gltf.meshes,n.mesh);r.push(this._loadMeshAsync(`/meshes/${o.index}`,n,o,o=>{const s=n._babylonTransformNodeForSkin;o.metadata=t.deepMerge(s.metadata,o.metadata||{});const i=_o.Get(`${e}/skin`,this._gltf.skins,n.skin);r.push(this._loadSkinAsync(`/skins/${i.index}`,n,i,e=>{this._forEachPrimitive(n,t=>{t.skeleton=e}),this._postSceneLoadActions.push(()=>{if(null!=i.skeleton){const e=_o.Get(`/skins/${i.index}/skeleton`,this._gltf.nodes,i.skeleton).parent;n.index===e.index?o.parent=s.parent:o.parent=e._babylonTransformNode}else o.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:s,skinnedNode:o})})}))}))}else{const t=_o.Get(`${e}/mesh`,this._gltf.meshes,n.mesh);r.push(this._loadMeshAsync(`/meshes/${t.index}`,n,t,i))}return this.logClose(),Promise.all(r).then(()=>(this._forEachPrimitive(n,e=>{const t=e;!t.isAnInstance&&t.geometry&&t.geometry.useBoundingInfoFromGeometry?e._updateBoundingInfo():e.refreshBoundingInfo(!0,!0)}),n._babylonTransformNode))}_loadMeshAsync(e,n,o,s){const r=o.primitives;if(!r||!r.length)throw new Error(`${e}: Primitives are missing`);null==r[0].index&&_o.Assign(r);const i=new Array;this.logOpen(`${e} ${o.name||""}`);const a=n.name||`node${n.index}`;if(1===r.length){const t=o.primitives[0];i.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${t.index}`,a,n,o,t,e=>{n._babylonTransformNode=e,n._primitiveBabylonMeshes=[e]}))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,n._babylonTransformNode=new t.TransformNode(a,this._babylonScene),n._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n._primitiveBabylonMeshes=[];for(const t of r)i.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${t.index}`,`${a}_primitive${t.index}`,n,o,t,e=>{e.parent=n._babylonTransformNode,n._primitiveBabylonMeshes.push(e)}))}return s(n._babylonTransformNode),this.logClose(),Promise.all(i).then(()=>n._babylonTransformNode)}_loadMeshPrimitiveAsync(e,n,o,s,r,i){const a=this._extensionsLoadMeshPrimitiveAsync(e,n,o,s,r,i);if(a)return a;this.logOpen(`${e}`);const l=0===this._disableInstancedMesh&&this._parent.createInstances&&null==o.skin&&!s.primitives[0].targets;let u,c;if(l&&r._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,u=r._instanceData.babylonSourceMesh.createInstance(n),u._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,c=r._instanceData.promise;else{const i=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const a=new t.Mesh(n,this._babylonScene);if(a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,a.sideOrientation=this._babylonScene.useRightHandedSystem?t.Material.CounterClockWiseSideOrientation:t.Material.ClockWiseSideOrientation,this._createMorphTargets(e,o,s,r,a),i.push(this._loadVertexDataAsync(e,r,a).then(t=>b(this,void 0,void 0,function*(){return yield this._loadMorphTargetsAsync(e,r,a,t).then(()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,t.applyToMesh(a),t._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})}))),!this.parent.skipMaterials){const t=yo._GetDrawMode(e,r.mode);if(null==r.material){let e=this._defaultBabylonMaterialData[t];e||(e=this._createDefaultMaterial("__GLTFLoader._default",t,this._getDefaultImpl()),this._parent.onMaterialLoadedObservable.notifyObservers(e),this._defaultBabylonMaterialData[t]=e),a.material=e}else{const n=_o.Get(`${e}/material`,this._gltf.materials,r.material);i.push(this._loadMaterialAsync(`/materials/${n.index}`,n,a,t,e=>{a.material=e}))}}c=Promise.all(i),l&&(r._instanceData={babylonSourceMesh:a,promise:c}),u=a}return yo.AddPointerMetadata(u,e),this._parent.onMeshLoadedObservable.notifyObservers(u),i(u),this.logClose(),c.then(()=>u)}_loadVertexDataAsync(e,n,o){const s=this._extensionsLoadVertexDataAsync(e,n,o);if(s)return s;const r=n.attributes;if(!r)throw new Error(`${e}: Attributes are missing`);const i=new Array,a=new t.Geometry(o.name,this._babylonScene);if(null==n.indices)o.isUnIndexed=!0;else{const t=_o.Get(`${e}/indices`,this._gltf.accessors,n.indices);i.push(this._loadIndicesAccessorAsync(`/accessors/${t.index}`,t).then(e=>{a.setIndices(e)}))}const l=(n,s,l)=>{if(null==r[n])return;o._delayInfo=o._delayInfo||[],-1===o._delayInfo.indexOf(s)&&o._delayInfo.push(s);const u=_o.Get(`${e}/attributes/${n}`,this._gltf.accessors,r[n]);i.push(this._loadVertexAccessorAsync(`/accessors/${u.index}`,u,s).then(e=>{if(e.getKind()===t.VertexBuffer.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!o.skeleton){const e=go(u);e&&(a._boundingInfo=e,a.useBoundingInfoFromGeometry=!0)}a.setVerticesBuffer(e,u.count)})),s==t.VertexBuffer.MatricesIndicesExtraKind&&(o.numBoneInfluencers=8),l&&l(u)};return l("POSITION",t.VertexBuffer.PositionKind),l("NORMAL",t.VertexBuffer.NormalKind),l("TANGENT",t.VertexBuffer.TangentKind),l("TEXCOORD_0",t.VertexBuffer.UVKind),l("TEXCOORD_1",t.VertexBuffer.UV2Kind),l("TEXCOORD_2",t.VertexBuffer.UV3Kind),l("TEXCOORD_3",t.VertexBuffer.UV4Kind),l("TEXCOORD_4",t.VertexBuffer.UV5Kind),l("TEXCOORD_5",t.VertexBuffer.UV6Kind),l("JOINTS_0",t.VertexBuffer.MatricesIndicesKind),l("WEIGHTS_0",t.VertexBuffer.MatricesWeightsKind),l("JOINTS_1",t.VertexBuffer.MatricesIndicesExtraKind),l("WEIGHTS_1",t.VertexBuffer.MatricesWeightsExtraKind),l("COLOR_0",t.VertexBuffer.ColorKind,e=>{"VEC4"===e.type&&(o.hasVertexAlpha=!0)}),Promise.all(i).then(()=>a)}_createMorphTargets(e,n,o,s,r){if(!s.targets||!this._parent.loadMorphTargets)return;if(null==n._numMorphTargets)n._numMorphTargets=s.targets.length;else if(s.targets.length!==n._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);const i=o.extras?o.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,r.morphTargetManager=new t.MorphTargetManager(this._babylonScene),r.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.morphTargetManager.areUpdatesFrozen=!0;for(let e=0;e<s.targets.length;e++){const s=n.weights?n.weights[e]:o.weights?o.weights[e]:0,a=i?i[e]:`morphTarget${e}`;r.morphTargetManager.addTarget(new t.MorphTarget(a,s,r.getScene()))}}_loadMorphTargetsAsync(e,n,o,s){if(!n.targets||!this._parent.loadMorphTargets)return Promise.resolve();const r=new Array,i=o.morphTargetManager;for(let t=0;t<i.numTargets;t++){const o=i.getTarget(t);r.push(this._loadMorphTargetVertexDataAsync(`${e}/targets/${t}`,s,n.targets[t],o))}return Promise.all(r).then(()=>{i.areUpdatesFrozen=!1,this._parent.useMaxMorphTargetInfluencers&&(i.isUsingTextureForTargets||i.numTargets<=t.MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode)&&(i.optimizeInfluencers=!1,i.numMaxInfluencers=i.numTargets)})}_loadMorphTargetVertexDataAsync(e,n,o,s){return b(this,void 0,void 0,function*(){const r=new Array,i=(t,s,i)=>{if(null==o[t])return;const a=n.getVertexBuffer(s);if(!a)return;const l=_o.Get(`${e}/${t}`,this._gltf.accessors,o[t]);r.push(this._loadFloatAccessorAsync(`/accessors/${l.index}`,l).then(e=>{i(a,e)}))};return i("POSITION",t.VertexBuffer.PositionKind,(e,t)=>{const n=new Float32Array(t.length);e.forEach(t.length,(e,o)=>{n[o]=t[o]+e}),s.setPositions(n)}),i("NORMAL",t.VertexBuffer.NormalKind,(e,t)=>{const n=new Float32Array(t.length);e.forEach(n.length,(e,o)=>{n[o]=t[o]+e}),s.setNormals(n)}),i("TANGENT",t.VertexBuffer.TangentKind,(e,t)=>{const n=new Float32Array(t.length/3*4);let o=0;e.forEach(t.length/3*4,(e,s)=>{(s+1)%4!=0&&(n[o]=t[o]+e,o++)}),s.setTangents(n)}),i("TEXCOORD_0",t.VertexBuffer.UVKind,(e,t)=>{const n=new Float32Array(t.length);e.forEach(t.length,(e,o)=>{n[o]=t[o]+e}),s.setUVs(n)}),i("TEXCOORD_1",t.VertexBuffer.UV2Kind,(e,t)=>{const n=new Float32Array(t.length);e.forEach(t.length,(e,o)=>{n[o]=t[o]+e}),s.setUV2s(n)}),i("COLOR_0",t.VertexBuffer.ColorKind,(t,n)=>{let o=null;const r=t.getSize();if(3===r){o=new Float32Array(n.length/3*4),t.forEach(n.length,(e,t)=>{const s=Math.floor(t/3),r=t%3;o[4*s+r]=n[3*s+r]+e});for(let e=0;e<n.length/3;++e)o[4*e+3]=1}else{if(4!==r)throw new Error(`${e}: Invalid number of components (${r}) for COLOR_0 attribute`);o=new Float32Array(n.length),t.forEach(n.length,(e,t)=>{o[t]=n[t]+e})}s.setColors(o)}),yield Promise.all(r).then(()=>{})})}static _LoadTransform(e,n){if(null!=e.skin)return;let o=t.Vector3.Zero(),s=t.Quaternion.Identity(),r=t.Vector3.One();e.matrix?t.Matrix.FromArray(e.matrix).decompose(r,s,o):(e.translation&&(o=t.Vector3.FromArray(e.translation)),e.rotation&&(s=t.Quaternion.FromArray(e.rotation)),e.scale&&(r=t.Vector3.FromArray(e.scale))),n.position=o,n.rotationQuaternion=s,n.scaling=r}_loadSkinAsync(e,n,o,s){if(!this._parent.loadSkins)return Promise.resolve();const r=this._extensionsLoadSkinAsync(e,n,o);if(r)return r;if(o._data)return s(o._data.babylonSkeleton),o._data.promise;const i=`skeleton${o.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const a=new t.Skeleton(o.name||i,i,this._babylonScene);a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,o,a);const l=this._loadSkinInverseBindMatricesDataAsync(e,o).then(e=>{this._updateBoneMatrices(a,e)});return o._data={babylonSkeleton:a,promise:l},s(a),l}_loadBones(e,n,o){if(null==n.skeleton||this._parent.alwaysComputeSkeletonRootNode){const o=this._findSkeletonRootNode(`${e}/joints`,n.joints);if(o)if(void 0===n.skeleton)n.skeleton=o.index;else{const s=(e,t)=>{for(;t.parent;t=t.parent)if(t.parent===e)return!0;return!1},r=_o.Get(`${e}/skeleton`,this._gltf.nodes,n.skeleton);r===o||s(r,o)||(t.Logger.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),n.skeleton=o.index)}else t.Logger.Warn(`${e}: Failed to find common root`)}const s={};for(const t of n.joints){const r=_o.Get(`${e}/joints/${t}`,this._gltf.nodes,t);this._loadBone(r,n,o,s)}}_findSkeletonRootNode(e,t){if(0===t.length)return null;const n={};for(const o of t){const t=[];let s=_o.Get(`${e}/${o}`,this._gltf.nodes,o);for(;-1!==s.index;)t.unshift(s),s=s.parent;n[o]=t}let o=null;for(let e=0;;++e){let s=n[t[0]];if(e>=s.length)return o;const r=s[e];for(let i=1;i<t.length;++i)if(s=n[t[i]],e>=s.length||r!==s[e])return o;o=r}}_loadBone(e,n,o,s){e._isJoint=!0;let r=s[e.index];if(r)return r;let i=null;e.index!==n.skeleton&&(e.parent&&-1!==e.parent.index?i=this._loadBone(e.parent,n,o,s):void 0!==n.skeleton&&t.Logger.Warn(`/skins/${n.index}/skeleton: Skeleton node is not a common root`));const a=n.joints.indexOf(e.index);return r=new t.Bone(e.name||`joint${e.index}`,o,i,this._getNodeMatrix(e),null,null,a),s[e.index]=r,this._postSceneLoadActions.push(()=>{r.linkTransformNode(e._babylonTransformNode)}),r}_loadSkinInverseBindMatricesDataAsync(e,t){if(null==t.inverseBindMatrices)return Promise.resolve(null);const n=_o.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${n.index}`,n)}_updateBoneMatrices(e,n){for(const o of e.bones){const e=t.Matrix.Identity(),s=o._index;n&&-1!==s&&(t.Matrix.FromArrayToRef(n,16*s,e),e.invertToRef(e));const r=o.getParent();r&&e.multiplyToRef(r.getAbsoluteInverseBindMatrix(),e),o.updateMatrix(e,!1,!1),o._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?t.Matrix.FromArray(e.matrix):t.Matrix.Compose(e.scale?t.Vector3.FromArray(e.scale):t.Vector3.One(),e.rotation?t.Quaternion.FromArray(e.rotation):t.Quaternion.Identity(),e.translation?t.Vector3.FromArray(e.translation):t.Vector3.Zero())}loadCameraAsync(e,n,o=()=>{}){const s=this._extensionsLoadCameraAsync(e,n,o);if(s)return s;const r=new Array;this.logOpen(`${e} ${n.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new t.FreeCamera(n.name||`camera${n.index}`,t.Vector3.Zero(),this._babylonScene,!1);switch(i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n._babylonCamera=i,i.setTarget(new t.Vector3(0,0,-1)),n.type){case"perspective":{const t=n.perspective;if(!t)throw new Error(`${e}: Camera perspective properties are missing`);i.fov=t.yfov,i.minZ=t.znear,i.maxZ=t.zfar||0;break}case"orthographic":if(!n.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);i.mode=t.Camera.ORTHOGRAPHIC_CAMERA,i.orthoLeft=-n.orthographic.xmag,i.orthoRight=n.orthographic.xmag,i.orthoBottom=-n.orthographic.ymag,i.orthoTop=n.orthographic.ymag,i.minZ=n.orthographic.znear,i.maxZ=n.orthographic.zfar;break;default:throw new Error(`${e}: Invalid camera type (${n.type})`)}return yo.AddPointerMetadata(i,e),this._parent.onCameraLoadedObservable.notifyObservers(i),o(i),this.logClose(),Promise.all(r).then(()=>i)}_loadAnimationsAsync(){this._parent._startPerformanceCounter("Load animations");const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let n=0;n<e.length;n++){const o=e[n];t.push(this.loadAnimationAsync(`/animations/${o.index}`,o).then(e=>{0===e.targetedAnimations.length&&e.dispose()}))}return Promise.all(t).then(()=>{this._parent._endPerformanceCounter("Load animations")})}loadAnimationAsync(e,t){this._parent._startPerformanceCounter("Load animation");return this._extensionsLoadAnimationAsync(e,t)||fo.value.then(({AnimationGroup:n})=>{this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new n(t.name||`animation${t.index}`,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=o;const s=new Array;_o.Assign(t.channels),_o.Assign(t.samplers);for(const n of t.channels)s.push(this._loadAnimationChannelAsync(`${e}/channels/${n.index}`,e,t,n,(e,t)=>{e.animations=e.animations||[],e.animations.push(t),o.addTargetedAnimation(t,e)}));return this._parent._endPerformanceCounter("Load animation"),Promise.all(s).then(()=>(o.normalize(0),o))})}_loadAnimationChannelAsync(e,t,n,o,s){const r=this._extensionsLoadAnimationChannelAsync(e,t,n,o,s);if(r)return r;if(null==o.target.node)return Promise.resolve();const i=_o.Get(`${e}/target/node`,this._gltf.nodes,o.target.node),a=o.target.path,l="weights"===a;return l&&!i._numMorphTargets||!l&&!i._babylonTransformNode?Promise.resolve():this._parent.loadNodeAnimations||l||i._isJoint?po.value.then(()=>{var r,l,u,c;let d;switch(a){case"translation":d=null===(r=co("/nodes/{}/translation"))||void 0===r?void 0:r.interpolation;break;case"rotation":d=null===(l=co("/nodes/{}/rotation"))||void 0===l?void 0:l.interpolation;break;case"scale":d=null===(u=co("/nodes/{}/scale"))||void 0===u?void 0:u.interpolation;break;case"weights":d=null===(c=co("/nodes/{}/weights"))||void 0===c?void 0:c.interpolation;break;default:throw new Error(`${e}/target/path: Invalid value (${o.target.path})`)}if(!d)throw new Error(`${e}/target/path: Could not find interpolation properties for target path (${o.target.path})`);const h={object:i,info:d};return this._loadAnimationChannelFromTargetInfoAsync(e,t,n,o,h,s)}):Promise.resolve()}_loadAnimationChannelFromTargetInfoAsync(e,t,n,o,s,r){const i=this.parent.targetFps,a=1/i,l=_o.Get(`${e}/sampler`,n.samplers,o.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${o.sampler}`,l).then(e=>{let t=0;const l=s.object,u=s.info;for(const s of u){const u=s.getStride(l),c=e.input,d=e.output,h=new Array(c.length);let m=0;switch(e.interpolation){case"STEP":for(let e=0;e<c.length;e++){const t=s.getValue(l,d,m,1);m+=u,h[e]={frame:c[e]*i,value:t,interpolation:1}}break;case"CUBICSPLINE":for(let e=0;e<c.length;e++){const t=s.getValue(l,d,m,a);m+=u;const n=s.getValue(l,d,m,1);m+=u;const o=s.getValue(l,d,m,a);m+=u,h[e]={frame:c[e]*i,inTangent:t,value:n,outTangent:o}}break;case"LINEAR":for(let e=0;e<c.length;e++){const t=s.getValue(l,d,m,1);m+=u,h[e]={frame:c[e]*i,value:t}}}if(m>0){const e=`${n.name||`animation${n.index}`}_channel${o.index}_${t}`,a=s.buildAnimations(l,e,i,h);for(const e of a)t++,r(e.babylonAnimatable,e.babylonAnimation)}}})}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;const n=t.interpolation||"LINEAR";switch(n){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}const o=_o.Get(`${e}/input`,this._gltf.accessors,t.input),s=_o.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${o.index}`,o),this._loadFloatAccessorAsync(`/accessors/${s.index}`,s)]).then(([e,t])=>({input:e,interpolation:n,output:t})),t._data}loadBufferAsync(e,t,n,o){const s=this._extensionsLoadBufferAsync(e,t,n,o);if(s)return s;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);t._data=this._bin.readAsync(0,t.byteLength)}return t._data.then(t=>{try{return new Uint8Array(t.buffer,t.byteOffset+n,o)}catch(t){throw new Error(`${e}: ${t.message}`,{cause:t})}})}loadBufferViewAsync(e,t){const n=this._extensionsLoadBufferViewAsync(e,t);if(n)return n;if(t._data)return t._data;const o=_o.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${o.index}`,o,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,n,o){if(n._data)return n._data;const s=yo._GetNumComponents(e,n.type),r=s*t.VertexBufferGetTypeByteLength(n.componentType),i=s*n.count;if(null==n.bufferView)n._data=Promise.resolve(new o(i));else{const a=_o.Get(`${e}/bufferView`,this._gltf.bufferViews,n.bufferView);n._data=this.loadBufferViewAsync(`/bufferViews/${a.index}`,a).then(l=>{if(5126!==n.componentType||n.normalized||a.byteStride&&a.byteStride!==r){const e=new o(i);return t.VertexBufferForEach(l,n.byteOffset||0,a.byteStride||r,s,n.componentType,e.length,n.normalized||!1,(t,n)=>{e[n]=t}),e}return yo._GetTypedArray(e,n.componentType,l,n.byteOffset,i)})}if(n.sparse){const i=n.sparse;n._data=n._data.then(a=>{const l=a,u=_o.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,i.indices.bufferView),c=_o.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,i.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${u.index}`,u),this.loadBufferViewAsync(`/bufferViews/${c.index}`,c)]).then(([a,u])=>{const c=yo._GetTypedArray(`${e}/sparse/indices`,i.indices.componentType,a,i.indices.byteOffset,i.count),d=s*i.count;let h;if(5126!==n.componentType||n.normalized){const a=yo._GetTypedArray(`${e}/sparse/values`,n.componentType,u,i.values.byteOffset,d);h=new o(d),t.VertexBufferForEach(a,0,r,s,n.componentType,h.length,n.normalized||!1,(e,t)=>{h[t]=e})}else h=yo._GetTypedArray(`${e}/sparse/values`,n.componentType,u,i.values.byteOffset,d);let m=0;for(let e=0;e<c.length;e++){let t=c[e]*s;for(let e=0;e<s;e++)l[t++]=h[m++]}return l})})}return n._data}_loadFloatAccessorAsync(e,t){return this._loadAccessorAsync(e,t,Float32Array)}_loadIndicesAccessorAsync(e,t){if("SCALAR"!==t.type)throw new Error(`${e}/type: Invalid value ${t.type}`);if(5121!==t.componentType&&5123!==t.componentType&&5125!==t.componentType)throw new Error(`${e}/componentType: Invalid value ${t.componentType}`);if(t._data)return t._data;if(t.sparse){const n=yo._GetTypedArrayConstructor(`${e}/componentType`,t.componentType);t._data=this._loadAccessorAsync(e,t,n)}else{const n=_o.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${n.index}`,n).then(n=>yo._GetTypedArray(e,t.componentType,n,t.byteOffset,t.count))}return t._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;const n=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then(e=>new t.Buffer(n,e,!1)),e._babylonBuffer}_loadVertexAccessorAsync(e,n,o){var s;if(null===(s=n._babylonVertexBuffer)||void 0===s?void 0:s[o])return n._babylonVertexBuffer[o];n._babylonVertexBuffer||(n._babylonVertexBuffer={});const r=this._babylonScene.getEngine();if(n.sparse||null==n.bufferView)n._babylonVertexBuffer[o]=this._loadFloatAccessorAsync(e,n).then(e=>new t.VertexBuffer(r,e,o,!1));else{const s=_o.Get(`${e}/bufferView`,this._gltf.bufferViews,n.bufferView);n._babylonVertexBuffer[o]=this._loadVertexBufferViewAsync(s).then(i=>{const a=yo._GetNumComponents(e,n.type);return new t.VertexBuffer(r,i,o,!1,void 0,s.byteStride,void 0,n.byteOffset,a,n.componentType,n.normalized,!0,void 0,!0)})}return n._babylonVertexBuffer[o]}_loadMaterialMetallicRoughnessPropertiesAsync(e,n,o){const s=new Array,r=this._getOrCreateMaterialAdapter(o);return n&&(n.baseColorFactor?(r.baseColor=t.Color3.FromArray(n.baseColorFactor),r.geometryOpacity=n.baseColorFactor[3]):r.baseColor=t.Color3.White(),r.baseMetalness=null==n.metallicFactor?1:n.metallicFactor,r.specularRoughness=null==n.roughnessFactor?1:n.roughnessFactor,n.baseColorTexture&&s.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,n.baseColorTexture,e=>{e.name=`${o.name} (Base Color)`,r.baseColorTexture=e})),n.metallicRoughnessTexture&&(n.metallicRoughnessTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,n.metallicRoughnessTexture,e=>{e.name=`${o.name} (Metallic Roughness)`,r.baseMetalnessTexture=e,r.specularRoughnessTexture=e})),r.useRoughnessFromMetallicTextureGreen=!0,r.useMetallicFromMetallicTextureBlue=!0)),Promise.all(s).then(()=>{})}_loadMaterialAsync(e,t,n,o,s=()=>{}){const r=this._extensionsLoadMaterialAsync(e,t,n,o,s);if(r)return r;t._data=t._data||{};let i=t._data[o];if(!i){this.logOpen(`${e} ${t.name||""}`);const n=this.createMaterial(e,t,o);i={babylonMaterial:n,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,n)},t._data[o]=i,yo.AddPointerMetadata(n,e),this._parent.onMaterialLoadedObservable.notifyObservers(n),this.logClose()}return n&&(i.babylonMeshes.push(n),n.onDisposeObservable.addOnce(()=>{const e=i.babylonMeshes.indexOf(n);-1!==e&&i.babylonMeshes.splice(e,1)})),s(i.babylonMaterial),i.promise.then(()=>i.babylonMaterial)}_selectImplForGltfMaterial(e){var t;if(this.parent.useOpenPBR||(null===(t=e.extensions)||void 0===t?void 0:t.KHR_materials_openpbr)){const e=this._pbrMaterialImpls.get("openpbr");if(e)return e}const n=this._pbrMaterialImpls.get("pbr");if(n)return n;throw new Error("No PBR material implementation loaded")}_getDefaultImpl(){var e;if(this.parent.useOpenPBR){const e=this._pbrMaterialImpls.get("openpbr");if(e)return e}const t=null!==(e=this._pbrMaterialImpls.get("pbr"))&&void 0!==e?e:this._pbrMaterialImpls.values().next().value;if(t)return t;throw new Error("No PBR material implementation loaded")}_createDefaultMaterial(e,t,n){this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new n.materialClass(e,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,o.fillMode=t,o.transparencyMode=n.materialClass.MATERIAL_OPAQUE;const s=this._getOrCreateMaterialAdapter(o);return s.transparencyAsAlphaCoverage=this._parent.transparencyAsCoverage,s.baseMetalness=1,s.specularRoughness=1,o}createMaterial(e,t,n){const o=this._extensionsCreateMaterial(e,t,n);if(o)return o;const s=t.name||`material${t.index}`;return this._createDefaultMaterial(s,n,this._selectImplForGltfMaterial(t))}loadMaterialPropertiesAsync(e,t,n){const o=this._extensionsLoadMaterialPropertiesAsync(e,t,n);if(o)return o;const s=new Array;return s.push(this.loadMaterialBasePropertiesAsync(e,t,n)),t.pbrMetallicRoughness&&s.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,n)),this.loadMaterialAlphaProperties(e,t,n),Promise.all(s).then(()=>{})}loadMaterialBasePropertiesAsync(e,n,o){const s=new Array,r=this._getOrCreateMaterialAdapter(o);let i;r.emissionColor=n.emissiveFactor?t.Color3.FromArray(n.emissiveFactor):new t.Color3(0,0,0),n.doubleSided&&(r.backFaceCulling=!1,r.twoSidedLighting=!0),n.normalTexture&&(n.normalTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/normalTexture`,n.normalTexture,e=>{var t;e.name=`${o.name} (Normal)`,r.geometryNormalTexture=e,null!=(null===(t=n.normalTexture)||void 0===t?void 0:t.scale)&&(e.level=n.normalTexture.scale)})),r.setNormalMapInversions(!this._babylonScene.useRightHandedSystem,this._babylonScene.useRightHandedSystem));let a,l=1;return n.occlusionTexture&&(n.occlusionTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,n.occlusionTexture,e=>{e.name=`${o.name} (Occlusion)`,i=e})),null!=n.occlusionTexture.strength&&(l=n.occlusionTexture.strength)),n.emissiveTexture&&s.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,n.emissiveTexture,e=>{e.name=`${o.name} (Emissive)`,a=e})),Promise.all(s).then(()=>{i&&(r.ambientOcclusionTexture=i,r.ambientOcclusionTextureStrength=l),a&&(r.emissionColorTexture=a)})}loadMaterialAlphaProperties(e,n,o){if(0===this._pbrMaterialImpls.size)throw new Error(`${e}: Material type not supported`);const s=this._getOrCreateMaterialAdapter(o),r=s.baseColorTexture;switch(n.alphaMode||"OPAQUE"){case"OPAQUE":o.transparencyMode=t.Material.MATERIAL_OPAQUE,o.alpha=1;break;case"MASK":o.transparencyMode=t.Material.MATERIAL_ALPHATEST,s.alphaCutOff=null==n.alphaCutoff?.5:n.alphaCutoff,r&&(r.hasAlpha=!0,s.useAlphaFromBaseColorTexture=!0);break;case"BLEND":o.transparencyMode=t.Material.MATERIAL_ALPHABLEND,r&&(r.hasAlpha=!0,s.useAlphaFromBaseColorTexture=!0);break;default:throw new Error(`${e}/alphaMode: Invalid value (${n.alphaMode})`)}}loadTextureInfoAsync(e,t,n=()=>{}){const o=this._extensionsLoadTextureInfoAsync(e,t,n);if(o)return o;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const s=_o.Get(`${e}/index`,this._gltf.textures,t.index);s._textureInfo=t;const r=this._loadTextureAsync(`/textures/${t.index}`,s,o=>{o.coordinatesIndex=t.texCoord||0,yo.AddPointerMetadata(o,e),this._parent.onTextureLoadedObservable.notifyObservers(o),n(o)});return this.logClose(),r}_loadTextureAsync(e,t,n=()=>{}){const o=this._extensionsLoadTextureAsync(e,t,n);if(o)return o;this.logOpen(`${e} ${t.name||""}`);const s=null==t.sampler?yo.DefaultSampler:_o.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),r=_o.Get(`${e}/source`,this._gltf.images,t.source),i=this._createTextureAsync(e,s,r,n,void 0,!t._textureInfo.nonColorData);return this.logClose(),i}_createTextureAsync(e,n,o,s=()=>{},r,i){var a,l;const u=this._loadSampler(`/samplers/${n.index}`,n),c=new Array,d=new t.Deferred;this._babylonScene._blockEntityCollection=!!this._assetContainer;const h={noMipmap:u.noMipMaps,invertY:!1,samplingMode:u.samplingMode,onLoad:()=>{this._disposed||d.resolve()},onError:(t,n)=>{this._disposed||d.reject(new Error(`${e}: ${n&&n.message?n.message:t||"Failed to load texture"}`))},mimeType:null!==(a=o.mimeType)&&void 0!==a?a:t.GetMimeType(null!==(l=o.uri)&&void 0!==l?l:""),loaderOptions:r,useSRGBBuffer:!!i&&this._parent.useSRGBBuffers},m=new t.Texture(null,this._babylonScene,h);m._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,c.push(d.promise);const f=o.uri&&!t.IsBase64DataUrl(o.uri)?o.uri:void 0,p=null!=f?f:`${this._fileName}#image${o.index}`;if(c.push(this.loadImageAsync(`/images/${o.index}`,o).then(e=>{const t=`data:${this._uniqueRootUrl}${p}`;m.updateURL(t,e);const n=m.getInternalTexture();n&&(n.label=o.name)})),m.wrapU=u.wrapU,m.wrapV=u.wrapV,s(m),this._parent.useGltfTextureNames){const e=o.name||f||`image${o.index}`;m.name=e}return Promise.all(c).then(()=>m)}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:yo._GetTextureSamplingMode(e,t),wrapU:yo._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:yo._GetTextureWrapMode(`${e}/wrapT`,t.wrapT)}),t._data}loadImageAsync(e,t){if(!t._data){if(this.logOpen(`${e} ${t.name||""}`),t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{const n=_o.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${n.index}`,n)}this.logClose()}return t._data}loadUriAsync(e,n,o){const s=this._extensionsLoadUriAsync(e,n,o);if(s)return s;if(!yo._ValidateUri(o))throw new Error(`${e}: '${o}' is invalid`);if(t.IsBase64DataUrl(o)){const n=new Uint8Array(t.DecodeBase64UrlToBinary(o));return this.log(`${e}: Decoded ${o.substring(0,64)}... (${n.length} bytes)`),Promise.resolve(n)}return this.log(`${e}: Loading ${o}`),this._parent.preprocessUrlAsync(this._rootUrl+o).then(n=>new Promise((s,r)=>{this._parent._loadFile(this._babylonScene,n,t=>{this._disposed||(this.log(`${e}: Loaded ${o} (${t.byteLength} bytes)`),s(new Uint8Array(t)))},!0,n=>{r(new t.LoadFileError(`${e}: Failed to load '${o}'${n?": "+n.status+" "+n.statusText:""}`,n))})}))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};const n=e._internalMetadata=e._internalMetadata||{},o=n.gltf=n.gltf||{};(o.pointers=o.pointers||[]).push(t)}static _GetTextureWrapMode(e,n){switch(n=null==n?10497:n){case 33071:return t.Texture.CLAMP_ADDRESSMODE;case 33648:return t.Texture.MIRROR_ADDRESSMODE;case 10497:return t.Texture.WRAP_ADDRESSMODE;default:return t.Logger.Warn(`${e}: Invalid value (${n})`),t.Texture.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,n){const o=null==n.magFilter?9729:n.magFilter,s=null==n.minFilter?9987:n.minFilter;if(9729===o)switch(s){case 9728:return t.Texture.LINEAR_NEAREST;case 9729:return t.Texture.LINEAR_LINEAR;case 9984:return t.Texture.LINEAR_NEAREST_MIPNEAREST;case 9985:return t.Texture.LINEAR_LINEAR_MIPNEAREST;case 9986:return t.Texture.LINEAR_NEAREST_MIPLINEAR;case 9987:return t.Texture.LINEAR_LINEAR_MIPLINEAR;default:return t.Logger.Warn(`${e}/minFilter: Invalid value (${s})`),t.Texture.LINEAR_LINEAR_MIPLINEAR}else switch(9728!==o&&t.Logger.Warn(`${e}/magFilter: Invalid value (${o})`),s){case 9728:return t.Texture.NEAREST_NEAREST;case 9729:return t.Texture.NEAREST_LINEAR;case 9984:return t.Texture.NEAREST_NEAREST_MIPNEAREST;case 9985:return t.Texture.NEAREST_LINEAR_MIPNEAREST;case 9986:return t.Texture.NEAREST_NEAREST_MIPLINEAR;case 9987:return t.Texture.NEAREST_LINEAR_MIPLINEAR;default:return t.Logger.Warn(`${e}/minFilter: Invalid value (${s})`),t.Texture.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,n){try{return t.GetTypedArrayConstructor(n)}catch(t){throw new Error(`${e}: ${t.message}`,{cause:t})}}static _GetTypedArray(e,n,o,s,r){const i=o.buffer;s=o.byteOffset+(s||0);const a=yo._GetTypedArrayConstructor(`${e}/componentType`,n),l=t.VertexBufferGetTypeByteLength(n);return s%l!==0?(t.Logger.Warn(`${e}: Copying buffer as byte offset (${s}) is not a multiple of component type byte length (${l})`),new a(i.slice(s,s+r*l),0)):new a(i,s,r)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return t.Tools.IsBase64(e)||-1===e.indexOf("..")}static _GetDrawMode(e,n){switch(null==n&&(n=4),n){case 0:return t.Material.PointListDrawMode;case 1:return t.Material.LineListDrawMode;case 2:return t.Material.LineLoopDrawMode;case 3:return t.Material.LineStripDrawMode;case 4:return t.Material.TriangleFillMode;case 5:return t.Material.TriangleStripDrawMode;case 6:return t.Material.TriangleFanDrawMode}throw new Error(`${e}: Invalid mesh primitive mode (${n})`)}_compileMaterialsAsync(){this._parent._startPerformanceCounter("Compile materials");const e=new Array;if(this._gltf.materials)for(const t of this._gltf.materials)if(t._data)for(const n in t._data){const o=t._data[n];for(const t of o.babylonMeshes){t.computeWorldMatrix(!0);const n=o.babylonMaterial;e.push(n.forceCompilationAsync(t)),e.push(n.forceCompilationAsync(t,{useInstances:!0})),this._parent.useClipPlane&&(e.push(n.forceCompilationAsync(t,{clipPlane:!0})),e.push(n.forceCompilationAsync(t,{clipPlane:!0,useInstances:!0})))}}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile materials")})}_compileShadowGeneratorsAsync(){this._parent._startPerformanceCounter("Compile shadow generators");const e=new Array,t=this._babylonScene.lights;for(const n of t){const t=n.getShadowGenerator();t&&e.push(t.forceCompilationAsync())}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile shadow generators")})}_forEachExtensions(e){for(const t of this._extensions)t.enabled&&e(t)}_applyExtensions(e,t,n){for(const o of this._extensions)if(o.enabled){const s=`${o.name}.${t}`,r=e;r._activeLoaderExtensionFunctions=r._activeLoaderExtensionFunctions||{};const i=r._activeLoaderExtensionFunctions;if(!i[s]){i[s]=!0;try{const e=n(o);if(e)return e}finally{delete i[s]}}}return null}_extensionsOnLoading(){this._forEachExtensions(e=>e.onLoading&&e.onLoading())}_extensionsOnReady(){this._forEachExtensions(e=>e.onReady&&e.onReady())}_extensionsLoadSceneAsync(e,t){return this._applyExtensions(t,"loadScene",n=>n.loadSceneAsync&&n.loadSceneAsync(e,t))}_extensionsLoadNodeAsync(e,t,n){return this._applyExtensions(t,"loadNode",o=>o.loadNodeAsync&&o.loadNodeAsync(e,t,n))}_extensionsLoadCameraAsync(e,t,n){return this._applyExtensions(t,"loadCamera",o=>o.loadCameraAsync&&o.loadCameraAsync(e,t,n))}_extensionsLoadVertexDataAsync(e,t,n){return this._applyExtensions(t,"loadVertexData",o=>o._loadVertexDataAsync&&o._loadVertexDataAsync(e,t,n))}_extensionsLoadMeshPrimitiveAsync(e,t,n,o,s,r){return this._applyExtensions(s,"loadMeshPrimitive",i=>i._loadMeshPrimitiveAsync&&i._loadMeshPrimitiveAsync(e,t,n,o,s,r))}_extensionsLoadMaterialAsync(e,t,n,o,s){return this._applyExtensions(t,"loadMaterial",r=>r._loadMaterialAsync&&r._loadMaterialAsync(e,t,n,o,s))}_extensionsCreateMaterial(e,t,n){return this._applyExtensions(t,"createMaterial",o=>o.createMaterial&&o.createMaterial(e,t,n))}_extensionsLoadMaterialPropertiesAsync(e,t,n){return this._applyExtensions(t,"loadMaterialProperties",o=>o.loadMaterialPropertiesAsync&&o.loadMaterialPropertiesAsync(e,t,n))}_extensionsLoadTextureInfoAsync(e,t,n){return this._applyExtensions(t,"loadTextureInfo",o=>o.loadTextureInfoAsync&&o.loadTextureInfoAsync(e,t,n))}_extensionsLoadTextureAsync(e,t,n){return this._applyExtensions(t,"loadTexture",o=>o._loadTextureAsync&&o._loadTextureAsync(e,t,n))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",n=>n.loadAnimationAsync&&n.loadAnimationAsync(e,t))}_extensionsLoadAnimationChannelAsync(e,t,n,o,s){return this._applyExtensions(n,"loadAnimationChannel",r=>r._loadAnimationChannelAsync&&r._loadAnimationChannelAsync(e,t,n,o,s))}_extensionsLoadSkinAsync(e,t,n){return this._applyExtensions(n,"loadSkin",o=>o._loadSkinAsync&&o._loadSkinAsync(e,t,n))}_extensionsLoadUriAsync(e,t,n){return this._applyExtensions(t,"loadUri",o=>o._loadUriAsync&&o._loadUriAsync(e,t,n))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",n=>n.loadBufferViewAsync&&n.loadBufferViewAsync(e,t))}_extensionsLoadBufferAsync(e,t,n,o){return this._applyExtensions(t,"loadBuffer",s=>s.loadBufferAsync&&s.loadBufferAsync(e,t,n,o))}static LoadExtensionAsync(e,t,n,o){if(!t.extensions)return null;const s=t.extensions[n];return s?o(`${e}/extensions/${n}`,s):null}static LoadExtraAsync(e,t,n,o){if(!t.extras)return null;const s=t.extras[n];return s?o(`${e}/extras/${n}`,s):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&-1!==this._gltf.extensionsUsed.indexOf(e)}logOpen(e){this._parent._logOpen(e)}logClose(){this._parent._logClose()}log(e){this._parent._log(e)}startPerformanceCounter(e){this._parent._startPerformanceCounter(e)}endPerformanceCounter(e){this._parent._endPerformanceCounter(e)}}yo.DefaultSampler={index:-1};let vo=!1;function bo(){vo||(vo=!0,mn._CreateGLTF2Loader=e=>new yo(e))}bo(),pn();var xo={__proto__:null,ArrayItem:_o,GLTFFileLoader:mn,GLTFLoader:yo,LoadBoundingInfoFromPositionAccessor:go,RegisterGLTF2Loader:bo};function To(e,n,o,s){return t.Vector3.FromArray(n,o).scaleInPlace(s)}function Ao(e,n,o,s){return t.Quaternion.FromArray(n,o).scaleInPlace(s)}function Mo(e,t,n,o){const s=new Array(e._numMorphTargets);for(let e=0;e<s.length;e++)s[e]=t[n++]*o;return s}class wo{constructor(e,t,n,o){this.type=e,this.name=t,this.getValue=n,this.getStride=o}_buildAnimation(e,n,o){const s=new t.Animation(e,this.name,n,this.type);return s.setKeys(o,!0),s}}class Co extends wo{buildAnimations(e,t,n,o){const s=[];return s.push({babylonAnimatable:e._babylonTransformNode,babylonAnimation:this._buildAnimation(t,n,o)}),s}}class Ro extends wo{buildAnimations(e,n,o,s){const r=[];if(e._numMorphTargets)for(let i=0;i<e._numMorphTargets;i++){const a=new t.Animation(`${n}_${i}`,this.name,o,this.type);if(a.setKeys(s.map(e=>({frame:e.frame,inTangent:e.inTangent?e.inTangent[i]:void 0,value:e.value[i],outTangent:e.outTangent?e.outTangent[i]:void 0,interpolation:e.interpolation})),!0),e._primitiveBabylonMeshes)for(const t of e._primitiveBabylonMeshes)if(t.morphTargetManager){const e=t.morphTargetManager.getTarget(i),n=a.clone();e.animations.push(n),r.push({babylonAnimatable:e,babylonAnimation:n})}}return r}}ho("/nodes/{}/translation",[new Co(t.Animation.ANIMATIONTYPE_VECTOR3,"position",To,()=>3)]),ho("/nodes/{}/rotation",[new Co(t.Animation.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",Ao,()=>4)]),ho("/nodes/{}/scale",[new Co(t.Animation.ANIMATIONTYPE_VECTOR3,"scaling",To,()=>3)]),ho("/nodes/{}/weights",[new Ro(t.Animation.ANIMATIONTYPE_FLOAT,"influence",Mo,e=>e._numMorphTargets)]);var Oo={__proto__:null,AnimationPropertyInfo:wo,TransformNodeAnimationPropertyInfo:Co,WeightAnimationPropertyInfo:Ro,getQuaternion:Ao,getVector3:To,getWeights:Mo};class So{constructor(e){this._specWorkflow=!1,this._diffuseTransmissionTint=t.Color3.White(),this._diffuseTransmissionTintTexture=null,this._material=e}get material(){return this._material}get isUnlit(){return this._material.unlit}set isUnlit(e){this._material.unlit=e}set backFaceCulling(e){this._material.backFaceCulling=e}get backFaceCulling(){return this._material.backFaceCulling}set twoSidedLighting(e){this._material.twoSidedLighting=e}get twoSidedLighting(){return this._material.twoSidedLighting}set alphaCutOff(e){this._material.alphaCutOff=e}get alphaCutOff(){return this._material.alphaCutOff}set useAlphaFromBaseColorTexture(e){this._material._useAlphaFromBaseColorTexture=e}get useAlphaFromBaseColorTexture(){return this._material._useAlphaFromBaseColorTexture}get transparencyAsAlphaCoverage(){return!1}set transparencyAsAlphaCoverage(e){}set baseColor(e){this._material.baseColor=e}get baseColor(){return this._material.baseColor}set baseColorTexture(e){this._material.baseColorTexture=e}get baseColorTexture(){return this._material.baseColorTexture}set baseDiffuseRoughness(e){this._material.baseDiffuseRoughness=e}get baseDiffuseRoughness(){return this._material.baseDiffuseRoughness}set baseDiffuseRoughnessTexture(e){this._material.baseDiffuseRoughnessTexture=e}get baseDiffuseRoughnessTexture(){return this._material.baseDiffuseRoughnessTexture}set baseMetalness(e){this._material.baseMetalness=e}get baseMetalness(){return this._material.baseMetalness}set baseMetalnessTexture(e){this._material.baseMetalnessTexture=e}get baseMetalnessTexture(){return this._material.baseMetalnessTexture}set useRoughnessFromMetallicTextureGreen(e){this._material._useRoughnessFromMetallicTextureGreen=e}set useMetallicFromMetallicTextureBlue(e){this._material._useMetallicFromMetallicTextureBlue=e}enableSpecularEdgeColor(e=!1){}configureSpecularGlossiness(){this._specWorkflow=!0}set specularWeight(e){this._material.specularWeight=e}get specularWeight(){return this._material.specularWeight}set specularWeightTexture(e){this._material.specularColorTexture===e?(this._material.specularWeightTexture=null,this._material._useSpecularWeightFromSpecularColorTexture=!0,this._material._useSpecularWeightFromAlpha=!0):this._material.specularWeightTexture=e}get specularWeightTexture(){return this._material.specularWeightTexture}set specularColor(e){this._material.specularColor=e}get specularColor(){return this._material.specularColor}set specularColorTexture(e){this._material.specularColorTexture=e,this._material.specularWeightTexture===this._material.specularColorTexture&&(this._material.specularWeightTexture=null,this._material._useSpecularWeightFromSpecularColorTexture=!0,this._material._useSpecularWeightFromAlpha=!0)}get specularColorTexture(){return this._material.specularColorTexture}set specularRoughness(e){this._material.specularRoughness=e}get specularRoughness(){return this._material.specularRoughness}set specularRoughnessTexture(e){this._material.specularRoughnessTexture=e}get specularRoughnessTexture(){return this._material.specularRoughnessTexture}set specularIor(e){this._material.specularIor=e}get specularIor(){return this._material.specularIor}set glossiness(e){this._material.specularRoughness=Math.max(1-e,0)}get glossiness(){return 1-this._material.specularRoughness}set emissionColor(e){this._material.emissionColor=e}get emissionColor(){return this._material.emissionColor}set emissionLuminance(e){this._material.emissionLuminance=e}get emissionLuminance(){return this._material.emissionLuminance}set emissionColorTexture(e){this._material.emissionColorTexture=e}get emissionColorTexture(){return this._material.emissionColorTexture}set ambientOcclusionTexture(e){this._material.ambientOcclusionTexture=e}get ambientOcclusionTexture(){return this._material.ambientOcclusionTexture}set ambientOcclusionTextureStrength(e){const t=this._material.ambientOcclusionTexture;t&&(t.level=e)}get ambientOcclusionTextureStrength(){var e;const t=this._material.ambientOcclusionTexture;return null!==(e=null==t?void 0:t.level)&&void 0!==e?e:1}configureCoat(){}set coatWeight(e){this._material.coatWeight=e}get coatWeight(){return this._material.coatWeight}set coatWeightTexture(e){this._material.coatWeightTexture=e}get coatWeightTexture(){return this._material.coatWeightTexture}set coatColor(e){this._material.coatColor=e}get coatColor(){return this._material.coatColor}set coatColorTexture(e){this._material.coatColorTexture=e}set coatRoughness(e){this._material.coatRoughness=e}get coatRoughness(){return this._material.coatRoughness}set coatRoughnessTexture(e){this._material.coatRoughnessTexture=e,e&&(this._material._useCoatRoughnessFromGreenChannel=!0)}get coatRoughnessTexture(){return this._material.coatRoughnessTexture}set coatIor(e){this._material.coatIor=e}get coatIor(){return this._material.coatIor}set coatDarkening(e){this._material.coatDarkening=e}get coatDarkening(){return this._material.coatDarkening}set coatDarkeningTexture(e){this._material.coatDarkeningTexture=e}set coatRoughnessAnisotropy(e){this._material.coatRoughnessAnisotropy=e}get coatRoughnessAnisotropy(){return this._material.coatRoughnessAnisotropy}set geometryCoatTangentAngle(e){this._material.geometryCoatTangentAngle=e}set geometryCoatTangentTexture(e){this._material.geometryCoatTangentTexture=e,e&&(this._material._useCoatRoughnessAnisotropyFromTangentTexture=!0)}get geometryCoatTangentTexture(){return this._material.geometryCoatTangentTexture}configureTransmission(){this._material.geometryThinWalled=1,this._material.transmissionDepth=0}set transmissionWeight(e){this._material.transmissionWeight=e}set transmissionWeightTexture(e){this._material.transmissionWeightTexture=e}get transmissionWeightTexture(){return this._material.transmissionWeightTexture}get transmissionWeight(){return this._material.transmissionWeight}set transmissionScatter(e){this._material.transmissionScatter=e}get transmissionScatter(){return this._material.transmissionScatter}set transmissionScatterTexture(e){this._material.transmissionScatterTexture=e}get transmissionScatterTexture(){return this._material.transmissionScatterTexture}set transmissionScatterAnisotropy(e){this._material.transmissionScatterAnisotropy=e}set transmissionDispersionAbbeNumber(e){this._material.transmissionDispersionAbbeNumber=e}set transmissionDispersionScale(e){this._material.transmissionDispersionScale=e}set transmissionDepth(e){e!==Number.MAX_VALUE||0!==this._material.transmissionDepth?this._material.transmissionDepth=e:this._material.transmissionDepth=0}get transmissionDepth(){return this._material.transmissionDepth}set transmissionColor(e){e.equals(t.Color3.White())||(this._material.transmissionColor=e)}get transmissionColor(){return this._material.transmissionColor}get refractionBackgroundTexture(){return this._material.backgroundRefractionTexture}set refractionBackgroundTexture(e){this._material.backgroundRefractionTexture=e}configureVolume(){this._material.geometryThinWalled=0}set geometryThinWalled(e){this._material.geometryThinWalled=e?1:0}get geometryThinWalled(){return!!this._material.geometryThinWalled}set volumeThicknessTexture(e){this._material.geometryThicknessTexture=e,this._material._useGeometryThicknessFromGreenChannel=!0}set volumeThickness(e){this._material.geometryThickness=e}configureSubsurface(){this._material.geometryThinWalled=1,this._material.subsurfaceScatterAnisotropy=1}set subsurfaceWeight(e){this._material.subsurfaceWeight=e}get subsurfaceWeight(){return this._material.subsurfaceWeight}set subsurfaceWeightTexture(e){this._material.subsurfaceWeightTexture=e,this._material._useSubsurfaceWeightFromTextureAlpha=!0}get subsurfaceWeightTexture(){return this._material.subsurfaceWeightTexture}set subsurfaceColor(e){this._material.subsurfaceColor=e}set subsurfaceColorTexture(e){this._material.subsurfaceColorTexture=e}set diffuseTransmissionTint(e){this._diffuseTransmissionTint=e}get diffuseTransmissionTint(){return this._diffuseTransmissionTint}set diffuseTransmissionTintTexture(e){this._diffuseTransmissionTintTexture=e}get subsurfaceRadius(){return this._material.subsurfaceRadius}set subsurfaceRadius(e){this._material.subsurfaceRadius=e}get subsurfaceRadiusScale(){return this._material.subsurfaceRadiusScale}set subsurfaceRadiusScale(e){this._material.subsurfaceRadiusScale=e}set subsurfaceScatterAnisotropy(e){this._material.subsurfaceScatterAnisotropy=e}isTranslucent(){return this.transmissionWeight>0||this.subsurfaceWeight>0}configureFuzz(){}set fuzzWeight(e){this._material.fuzzWeight=e}set fuzzWeightTexture(e){this._material.fuzzWeightTexture=e}set fuzzColor(e){this._material.fuzzColor=e}set fuzzColorTexture(e){this._material.fuzzColorTexture=e}set fuzzRoughness(e){this._material.fuzzRoughness=e}set fuzzRoughnessTexture(e){this._material.fuzzRoughnessTexture=e,this._material._useFuzzRoughnessFromTextureAlpha=!0}set specularRoughnessAnisotropy(e){this._material.specularRoughnessAnisotropy=e}get specularRoughnessAnisotropy(){return this._material.specularRoughnessAnisotropy}set geometryTangentAngle(e){this._material.geometryTangentAngle=e}set geometryTangentTexture(e){this._material.geometryTangentTexture=e,this._material._useSpecularRoughnessAnisotropyFromTangentTexture=!0}get geometryTangentTexture(){return this._material.geometryTangentTexture}configureGltfStyleAnisotropy(e=!0){this._material._useGltfStyleAnisotropy=e}set thinFilmWeight(e){this._material.thinFilmWeight=e}set thinFilmIor(e){this._material.thinFilmIor=e}set thinFilmThicknessMinimum(e){this._material.thinFilmThicknessMin=e/1e3}set thinFilmThicknessMaximum(e){this._material.thinFilmThickness=e/1e3}set thinFilmWeightTexture(e){this._material.thinFilmWeightTexture=e}set thinFilmThicknessTexture(e){this._material.thinFilmThicknessTexture=e,this._material._useThinFilmThicknessFromTextureGreen=!0}set unlit(e){this._material.unlit=e}set geometryOpacity(e){this._material.geometryOpacity=e}get geometryOpacity(){return this._material.geometryOpacity}set geometryNormalTexture(e){this._material.geometryNormalTexture=e}get geometryNormalTexture(){return this._material.geometryNormalTexture}setNormalMapInversions(e,t){}set geometryCoatNormalTexture(e){this._material.geometryCoatNormalTexture=e}get geometryCoatNormalTexture(){return this._material.geometryCoatNormalTexture}set geometryCoatNormalTextureScale(e){this._material.geometryCoatNormalTexture&&(this._material.geometryCoatNormalTexture.level=e)}finalizeAsync(e){return b(this,void 0,void 0,function*(){var n,o,s;if(this._diffuseTransmissionTint&&!this._diffuseTransmissionTint.equals(t.Color3.White())||this._diffuseTransmissionTintTexture)if(this._material.geometryThinWalled)this.subsurfaceColor=this._diffuseTransmissionTint,this.subsurfaceColorTexture=this._diffuseTransmissionTintTexture;else if(yield this.copySurfaceToCoatAsync(e,this.subsurfaceWeight,this.subsurfaceWeightTexture,t.TextureChannel.A,this._diffuseTransmissionTint,this._diffuseTransmissionTintTexture,!0),e._disposed)return;if(this.transmissionWeight>0)if(this._material.geometryThinWalled||0===this._material.transmissionDepth)this._material.transmissionColor=this._material.baseColor,this._material.transmissionColorTexture=this._material.baseColorTexture;else if((!this.baseColor.equals(t.Color3.White())||null!==this.baseColorTexture)&&(yield this.copySurfaceToCoatAsync(e,this.transmissionWeight,this.transmissionWeightTexture,t.TextureChannel.R,this.baseColor,this.baseColorTexture,!1),e._disposed))return;if(this._specWorkflow){const r=yield t.InvertTextureAsync("newRoughnessTexture ("+this._material.name+")",yield t.ExtractChannelAsync("glossiness ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.specularColorTexture,new t.Color4(this.specularColor.r,this.specularColor.g,this.specularColor.b,this.glossiness),t.TextureChannel.A,t.TextureColorSpace.Linear),t.TextureChannel.A,this._material.getScene(),t.TextureColorSpace.Linear,t.ChannelMask.R),this._material.getScene(),t.ChannelMask.R,t.TextureColorSpace.Linear,t.ChannelMask.R);if(e._disposed)return void(null===(n=r.texture)||void 0===n||n.dispose());this.specularRoughnessTexture=r.texture,this.specularRoughness=r.factor?r.factor.r:1;const i=yield t.ExtractMaxChannelAsync("metallicTexture ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.specularColorTexture,this.specularColor.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.Linear),this._material.getScene(),!1,t.TextureColorSpace.SRGB,t.ChannelMask.RGB);if(e._disposed)return void(null===(o=i.texture)||void 0===o||o.dispose());this.baseMetalnessTexture=i.texture,this.baseMetalness=i.factor?i.factor.r:1;const a=yield t.LerpTexturesAsync("newBaseColor ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.baseColorTexture,this.baseColor.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.Linear),t.CreateTextureWithFactorOperand(this.specularColorTexture,this.specularColor.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.Linear),Object.assign(Object.assign({},i),{dispose:void 0,colorSpace:t.TextureColorSpace.Linear}),this._material.getScene(),t.TextureColorSpace.SRGB,t.ChannelMask.RGB);if(e._disposed)return void(null===(s=a.texture)||void 0===s||s.dispose());const l=this.baseColorTexture;null==l||l.dispose(),this.baseColorTexture=a.texture,this.baseColor=a.factor?new t.Color3(a.factor.r,a.factor.g,a.factor.b):t.Color3.White();const u=this.specularColorTexture;null==u||u.dispose(),this.specularColorTexture=null}})}copySurfaceToCoatAsync(e,n,o,s,r,i){return b(this,arguments,void 0,function*(e,n,o,s,r,i,a=!1){var l,u,c,d,h,m,f,p,_;const g=this._material.coatWeight,y=this._material.coatWeightTexture,v=this._material.coatColor.clone(),b=this._material.coatColorTexture,x=this._material.geometryCoatNormalTexture,T=new t.Color4(g,g,g,g),A=new t.Color4(n,n,n,n);this.coatWeightTexture=null,this.coatWeight=1;const M=yield Promise.allSettled([t.LerpTexturesAsync("lerpExistingCoat",t.CreateTextureWithFactorOperand(null,new t.Color4(1,1,1,1)),t.CreateTextureWithFactorOperand(b,v.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.SRGB),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene(),t.TextureColorSpace.SRGB),t.LerpTexturesAsync("lerpSurfaceColor",t.CreateTextureWithFactorOperand(null,new t.Color4(1,1,1,1)),t.CreateTextureWithFactorOperand(i,r.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.SRGB),t.CreateTextureWithFactorOperand(o,A,s),this._material.getScene(),t.TextureColorSpace.SRGB)]),w=M.find(e=>"rejected"===e.status);if(w){for(const e of M)"fulfilled"===e.status&&(null===(l=e.value.texture)||void 0===l||l.dispose());throw w.reason}const[C,R]=M.map(e=>e.value);if(e._disposed)return null===(u=C.texture)||void 0===u||u.dispose(),void(null===(c=R.texture)||void 0===c||c.dispose());const O=yield t.MultiplyTexturesAsync("newCoatColor ("+this._material.name+")",C,R,this._material.getScene(),t.TextureColorSpace.SRGB);if(e._disposed)return void(null===(d=O.texture)||void 0===d||d.dispose());O.texture?(this.coatColorTexture=O.texture,this.coatColor=t.Color3.White()):O.factor&&(this.coatColorTexture=null,this.coatColor.fromArray([O.factor.r,O.factor.g,O.factor.b]));const S=yield t.LerpTexturesAsync("newCoatIor ("+this._material.name+")",t.CreateTextureWithFactorOperand(null,new t.Color4(this._material.specularIor,this._material.specularIor,this._material.specularIor,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(null,new t.Color4(this.coatIor,this.coatIor,this.coatIor,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(h=S.texture)||void 0===h||h.dispose());this.coatIor=S.factor?S.factor.r:this.coatIor;const F=yield t.LerpTexturesAsync("newCoatRoughness ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.specularRoughnessTexture,new t.Color4(this.specularRoughness,this.specularRoughness,this.specularRoughness,1),t.TextureChannel.G),t.CreateTextureWithFactorOperand(this.coatRoughnessTexture,new t.Color4(this.coatRoughness,this.coatRoughness,this.coatRoughness,1),t.TextureChannel.G),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(m=F.texture)||void 0===m||m.dispose());this.coatRoughness=F.factor?F.factor.r:1,this.coatRoughnessTexture=F.texture;const E=yield t.LerpTexturesAsync("newCoatDarkening ("+this._material.name+")",t.CreateTextureWithFactorOperand(null,new t.Color4(0,0,0,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(null,new t.Color4(this.coatDarkening,this.coatDarkening,this.coatDarkening,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)null===(f=E.texture)||void 0===f||f.dispose();else{if(this.coatDarkening=E.factor?E.factor.r:this.coatDarkening,a){const n=yield t.LerpTexturesAsync("newSpecularRoughness ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.specularRoughnessTexture,new t.Color4(this._material.specularRoughness,this._material.specularRoughness,this._material.specularRoughness,1),t.TextureChannel.G),t.CreateTextureWithFactorOperand(null,new t.Color4(1,1,1,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(o,A,s),this._material.getScene());if(e._disposed)return void(null===(p=n.texture)||void 0===p||p.dispose());this.specularRoughness=n.factor?n.factor.r:1,this.specularRoughnessTexture=n.texture}if(x||this.geometryNormalTexture){const n=yield t.LerpTexturesAsync("newCoatNormal ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.geometryNormalTexture,this.geometryNormalTexture?new t.Color4(1,1,1,1):new t.Color4(.5,.5,1,1),t.TextureChannel.RGBA),t.CreateTextureWithFactorOperand(x,x?new t.Color4(1,1,1,1):new t.Color4(.5,.5,1,1),t.TextureChannel.RGBA),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(_=n.texture)||void 0===_||_.dispose());n.texture&&(this.geometryCoatNormalTexture=n.texture)}}})}}var Fo={__proto__:null,OpenPBRMaterialLoadingAdapter:So};class Eo{constructor(e){this._specWorkflow=!1,this._material=e,this._material.enableSpecularAntiAliasing=!0}get material(){return this._material}finalizeAsync(e){return b(this,void 0,void 0,function*(){})}get isUnlit(){return this._material.unlit}set isUnlit(e){this._material.unlit=e}set backFaceCulling(e){this._material.backFaceCulling=e}get backFaceCulling(){return this._material.backFaceCulling}set twoSidedLighting(e){this._material.twoSidedLighting=e}get twoSidedLighting(){return this._material.twoSidedLighting}set alphaCutOff(e){this._material.alphaCutOff=e}get alphaCutOff(){return this._material.alphaCutOff}set useAlphaFromBaseColorTexture(e){this._material.useAlphaFromAlbedoTexture=e}get useAlphaFromBaseColorTexture(){return this._material.useAlphaFromAlbedoTexture}get transparencyAsAlphaCoverage(){return this._material.useRadianceOverAlpha||this._material.useSpecularOverAlpha}set transparencyAsAlphaCoverage(e){this._material.useRadianceOverAlpha=!e,this._material.useSpecularOverAlpha=!e}set baseColor(e){this._material.albedoColor=e}get baseColor(){return this._material.albedoColor}set baseColorTexture(e){this._material.albedoTexture=e}get baseColorTexture(){return this._material.albedoTexture}set baseDiffuseRoughness(e){this._material.baseDiffuseRoughness=e,e>0&&(this._material.brdf.baseDiffuseModel=t.Constants.MATERIAL_DIFFUSE_MODEL_E_OREN_NAYAR)}get baseDiffuseRoughness(){var e;return null!==(e=this._material.baseDiffuseRoughness)&&void 0!==e?e:0}set baseDiffuseRoughnessTexture(e){this._material.baseDiffuseRoughnessTexture=e}get baseDiffuseRoughnessTexture(){return this._material.baseDiffuseRoughnessTexture}set baseMetalness(e){this._material.metallic=e}get baseMetalness(){var e;return null!==(e=this._material.metallic)&&void 0!==e?e:1}set baseMetalnessTexture(e){this._material.metallicTexture=e}get baseMetalnessTexture(){return this._material.metallicTexture}set useRoughnessFromMetallicTextureGreen(e){this._material.useRoughnessFromMetallicTextureGreen=e,this._material.useRoughnessFromMetallicTextureAlpha=!e}set useMetallicFromMetallicTextureBlue(e){this._material.useMetallnessFromMetallicTextureBlue=e}enableSpecularEdgeColor(e=!1){e&&(this._material.brdf.dielectricSpecularModel=t.Constants.MATERIAL_DIELECTRIC_SPECULAR_MODEL_OPENPBR,this._material.brdf.conductorSpecularModel=t.Constants.MATERIAL_CONDUCTOR_SPECULAR_MODEL_OPENPBR)}configureSpecularGlossiness(){this._specWorkflow=!0,this._material.metallic=null,this._material.roughness=null,this._material.useMicroSurfaceFromReflectivityMapAlpha=!0}set specularWeight(e){this._material.metallicF0Factor=e}get specularWeight(){var e;return null!==(e=this._material.metallicF0Factor)&&void 0!==e?e:1}set specularWeightTexture(e){e?(this._material.metallicReflectanceTexture=e,this._material.useOnlyMetallicFromMetallicReflectanceTexture=!0):(this._material.metallicReflectanceTexture=null,this._material.useOnlyMetallicFromMetallicReflectanceTexture=!1)}get specularWeightTexture(){return this._material.metallicReflectanceTexture}set specularColor(e){this._specWorkflow?this._material.reflectivityColor=e:this._material.metallicReflectanceColor=e}get specularColor(){return this._specWorkflow?this._material.reflectivityColor:this._material.metallicReflectanceColor}set specularColorTexture(e){this._specWorkflow?(this._material.reflectivityTexture=e,this._material.reflectivityTexture&&(this._material.reflectivityTexture.hasAlpha=!0)):this._material.reflectanceTexture=e}get specularColorTexture(){return this._specWorkflow?this._material.reflectivityTexture:this._material.reflectanceTexture}set specularRoughness(e){this._material.roughness=e}get specularRoughness(){var e;return null!==(e=this._material.roughness)&&void 0!==e?e:1}set specularRoughnessTexture(e){this.baseMetalnessTexture||(this._material.metallicTexture=e)}get specularRoughnessTexture(){return this._material.metallicTexture}set specularIor(e){this._material.indexOfRefraction=e}get specularIor(){return this._material.indexOfRefraction}get glossiness(){var e;return null!==(e=this._material.microSurface)&&void 0!==e?e:1}set glossiness(e){this._material.microSurface=e}set emissionColor(e){this._material.emissiveColor=e}get emissionColor(){return this._material.emissiveColor}set emissionLuminance(e){this._material.emissiveIntensity=e}get emissionLuminance(){return this._material.emissiveIntensity}set emissionColorTexture(e){this._material.emissiveTexture=e}get emissionColorTexture(){return this._material.emissiveTexture}set ambientOcclusionTexture(e){this._material.ambientTexture=e,e&&(this._material.useAmbientInGrayScale=!0)}get ambientOcclusionTexture(){return this._material.ambientTexture}set ambientOcclusionTextureStrength(e){this._material.ambientTextureStrength=e}get ambientOcclusionTextureStrength(){var e;return null!==(e=this._material.ambientTextureStrength)&&void 0!==e?e:1}configureCoat(){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.useRoughnessFromMainTexture=!1,this._material.clearCoat.remapF0OnInterfaceChange=!1}set coatWeight(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.intensity=e}get coatWeight(){return this._material.clearCoat.intensity}set coatWeightTexture(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.texture=e}get coatWeightTexture(){return this._material.clearCoat.texture}set coatColor(e){this._material.clearCoat.isTintEnabled=e!=t.Color3.White(),this._material.clearCoat.tintColor=e}set coatColorTexture(e){this._material.clearCoat.tintTexture=e}set coatRoughness(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.roughness=e}get coatRoughness(){var e;return null!==(e=this._material.clearCoat.roughness)&&void 0!==e?e:0}set coatRoughnessTexture(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.useRoughnessFromMainTexture=!1,this._material.clearCoat.textureRoughness=e}get coatRoughnessTexture(){return this._material.clearCoat.textureRoughness}set coatIor(e){this._material.clearCoat.indexOfRefraction=e}set coatDarkening(e){}set coatDarkeningTexture(e){}set coatRoughnessAnisotropy(e){}get coatRoughnessAnisotropy(){return 0}set geometryCoatTangentAngle(e){}set geometryCoatTangentTexture(e){}get geometryCoatTangentTexture(){return null}set transmissionWeight(e){this._material.subSurface.isRefractionEnabled=e>0,this._material.subSurface.refractionIntensity=e}get transmissionWeight(){return this._material.subSurface.isRefractionEnabled?this._material.subSurface.refractionIntensity:0}set transmissionWeightTexture(e){this._material.subSurface.isRefractionEnabled=!0,this._material.subSurface.refractionIntensityTexture=e,this._material.subSurface.useGltfStyleTextures=!0}set transmissionDepth(e){this.transmissionWeight>0?this._material.subSurface.tintColorAtDistance=e:this.subsurfaceWeight>0&&this._material.subSurface.diffusionDistance.multiplyInPlace(new t.Color3(e,e,e))}get transmissionDepth(){return this.transmissionWeight>0?this._material.subSurface.tintColorAtDistance:0}set transmissionColor(e){this.transmissionWeight>0?this._material.subSurface.tintColor=e:this.subsurfaceWeight>0&&this._material.subSurface.diffusionDistance.multiplyInPlace(e)}get transmissionColor(){return this.transmissionWeight>0?this._material.subSurface.tintColor:this.subsurfaceWeight>0?this._material.subSurface.diffusionDistance:new t.Color3(0,0,0)}set transmissionScatter(e){this._material.subSurface.diffusionDistance=e}get transmissionScatter(){return this._material.subSurface.diffusionDistance}set transmissionScatterTexture(e){}set transmissionScatterAnisotropy(e){}set transmissionDispersionAbbeNumber(e){}set transmissionDispersionScale(e){e>0?(this._material.subSurface.isDispersionEnabled=!0,this._material.subSurface.dispersion=20/e):(this._material.subSurface.isDispersionEnabled=!1,this._material.subSurface.dispersion=0)}get refractionBackgroundTexture(){return this._material.subSurface.refractionTexture}set refractionBackgroundTexture(e){this._material.subSurface.refractionTexture=e}configureTransmission(){this._material.subSurface.volumeIndexOfRefraction=1,this._material.subSurface.useAlbedoToTintRefraction=!0,this._material.subSurface.minimumThickness=0,this._material.subSurface.maximumThickness=0}configureVolume(){}set geometryThinWalled(e){}get geometryThinWalled(){return 0===this._material.subSurface.maximumThickness}set volumeThicknessTexture(e){this._material.subSurface.thicknessTexture=e,this._material.subSurface.useGltfStyleTextures=!0}set volumeThickness(e){this._material.subSurface.minimumThickness=0,this._material.subSurface.maximumThickness=e,this._material.subSurface.useThicknessAsDepth=!0,e>0&&(this._material.subSurface.volumeIndexOfRefraction=this._material.indexOfRefraction)}configureSubsurface(){this._material.subSurface.useGltfStyleTextures=!0,this._material.subSurface.volumeIndexOfRefraction=1,this._material.subSurface.minimumThickness=0,this._material.subSurface.maximumThickness=0,this._material.subSurface.useAlbedoToTintTranslucency=!1}set subsurfaceWeight(e){this._material.subSurface.isTranslucencyEnabled=e>0,this._material.subSurface.translucencyIntensity=e}get subsurfaceWeight(){return this._material.subSurface.isTranslucencyEnabled?this._material.subSurface.translucencyIntensity:0}set subsurfaceWeightTexture(e){this._material.subSurface.translucencyIntensityTexture=e}set subsurfaceColor(e){const n=new t.Vector3(-Math.log(this.transmissionColor.r),-Math.log(this.transmissionColor.g),-Math.log(this.transmissionColor.b));n.scaleInPlace(1/Math.max(this.transmissionDepth,.001));const o=n,s=Math.max(o.x,Math.max(o.y,o.z)),r=s>0?1/s:1;this._material.subSurface.diffusionDistance=new t.Color3(Math.exp(-o.x*r),Math.exp(-o.y*r),Math.exp(-o.z*r))}set subsurfaceColorTexture(e){}set diffuseTransmissionTint(e){this._material.subSurface.tintColor=e}get diffuseTransmissionTint(){return this._material.subSurface.tintColor}set diffuseTransmissionTintTexture(e){this._material.subSurface.translucencyColorTexture=e}get subsurfaceRadius(){return 1}set subsurfaceRadius(e){}get subsurfaceRadiusScale(){var e;return null!==(e=this._material.subSurface.scatteringDiffusionProfile)&&void 0!==e?e:t.Color3.White()}set subsurfaceRadiusScale(e){this._material.subSurface.scatteringDiffusionProfile=e}set subsurfaceScatterAnisotropy(e){}isTranslucent(){return this.transmissionWeight>0||this.subsurfaceWeight>0}configureFuzz(){this._material.sheen.isEnabled=!0,this._material.sheen.useRoughnessFromMainTexture=!1,this._material.sheen.albedoScaling=!0}set fuzzWeight(e){this._material.sheen.isEnabled=!0,this._material.sheen.intensity=e}set fuzzWeightTexture(e){this._material.sheen.texture||(this._material.sheen.texture=e)}set fuzzColor(e){this._material.sheen.isEnabled=!0,this._material.sheen.color=e}set fuzzColorTexture(e){this._material.sheen.texture=e}set fuzzRoughness(e){this._material.sheen.isEnabled=!0,this._material.sheen.roughness=e}set fuzzRoughnessTexture(e){this._material.sheen.isEnabled=!0,this._material.sheen.textureRoughness=e}set specularRoughnessAnisotropy(e){this._material.anisotropy.isEnabled=!0,this._material.anisotropy.intensity=e}get specularRoughnessAnisotropy(){return this._material.anisotropy.intensity}set geometryTangentAngle(e){this._material.anisotropy.isEnabled=!0,this._material.anisotropy.angle=e}set geometryTangentTexture(e){this._material.anisotropy.isEnabled=!0,this._material.anisotropy.texture=e}get geometryTangentTexture(){return this._material.anisotropy.texture}configureGltfStyleAnisotropy(e=!0){}set thinFilmWeight(e){this._material.iridescence.isEnabled=e>0,this._material.iridescence.intensity=e}set thinFilmIor(e){this._material.iridescence.indexOfRefraction=e}set thinFilmThicknessMinimum(e){this._material.iridescence.minimumThickness=e}set thinFilmThicknessMaximum(e){this._material.iridescence.maximumThickness=e}set thinFilmWeightTexture(e){this._material.iridescence.texture=e}set thinFilmThicknessTexture(e){this._material.iridescence.thicknessTexture=e}set unlit(e){this._material.unlit=e}set geometryOpacity(e){this._material.alpha=e}get geometryOpacity(){return this._material.alpha}set geometryNormalTexture(e){this._material.bumpTexture=e,this._material.forceIrradianceInFragment=!0}get geometryNormalTexture(){return this._material.bumpTexture}setNormalMapInversions(e,t){this._material.invertNormalMapX=e,this._material.invertNormalMapY=t}set geometryCoatNormalTexture(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.bumpTexture=e}get geometryCoatNormalTexture(){return this._material.clearCoat.bumpTexture}set geometryCoatNormalTextureScale(e){this._material.clearCoat.bumpTexture&&(this._material.clearCoat.bumpTexture.level=e)}}var Lo={__proto__:null,PBRMaterialLoadingAdapter:Eo};const Io="EXT_lights_image_based";let No=class{constructor(e){this.name=Io,this._loader=e,this.enabled=this._loader.isExtensionUsed(Io)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights}}loadSceneAsync(e,t){return yo.LoadExtensionAsync(e,t,this.name,(n,o)=>b(this,void 0,void 0,function*(){this._loader._allMaterialsDirtyRequired=!0;const s=new Array;s.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${n}`);const r=_o.Get(`${n}/light`,this._lights,o.light);return s.push(this._loadLightAsync(`/extensions/${this.name}/lights/${o.light}`,r).then(e=>{this._loader.babylonScene.environmentTexture=e})),this._loader.logClose(),yield Promise.all(s).then(()=>{})}))}_loadLightAsync(e,n){if(!n._loaded){const o=new Array;this._loader.logOpen(`${e}`);const s=new Array(n.specularImages.length);for(let t=0;t<n.specularImages.length;t++){const r=n.specularImages[t];s[t]=new Array(r.length);for(let n=0;n<r.length;n++){const i=`${e}/specularImages/${t}/${n}`;this._loader.logOpen(`${i}`);const a=r[n],l=_o.Get(i,this._loader.gltf.images,a);o.push(this._loader.loadImageAsync(`/images/${a}`,l).then(e=>{s[t][n]=e})),this._loader.logClose()}}this._loader.logClose(),n._loaded=Promise.all(o).then(()=>b(this,void 0,void 0,function*(){const o=new t.RawCubeTexture(this._loader.babylonScene,null,n.specularImageSize);if(o.name=n.name||"environment",n._babylonTexture=o,null!=n.intensity&&(o.level=n.intensity),n.rotation){let e=t.Quaternion.FromArray(n.rotation);this._loader.babylonScene.useRightHandedSystem||(e=t.Quaternion.Inverse(e)),t.Matrix.FromQuaternionToRef(e,o.getReflectionTextureMatrix())}if(!n.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const r=t.SphericalHarmonics.FromArray(n.irradianceCoefficients);r.scaleInPlace(n.intensity),r.convertIrradianceToLambertianRadiance();const i=t.SphericalPolynomial.FromHarmonics(r),a=(s.length-1)/Math.log2(n.specularImageSize);return yield o.updateRGBDAsync(s,i,a)}))}return n._loaded.then(()=>n._babylonTexture)}},Po=!1;function Bo(){Po||(Po=!0,no(Io),to(Io,!0,e=>new No(e)))}Bo();var ko={__proto__:null,EXT_lights_image_based:No,RegisterEXT_lights_image_based:Bo};const Do="EXT_mesh_gpu_instancing";let Go=class{constructor(e){this.name=Do,this._loader=e,this.enabled=this._loader.isExtensionUsed(Do)}dispose(){this._loader=null}loadNodeAsync(e,n,o){return yo.LoadExtensionAsync(e,n,this.name,(e,s)=>b(this,void 0,void 0,function*(){this._loader._disableInstancedMesh++;const r=this._loader.loadNodeAsync(`/nodes/${n.index}`,n,o);if(this._loader._disableInstancedMesh--,!n._primitiveBabylonMeshes)return yield r;const i=new Array;let a=0;const l=t=>{if(null==s.attributes[t])return void i.push(Promise.resolve(null));const n=_o.Get(`${e}/attributes/${t}`,this._loader.gltf.accessors,s.attributes[t]);if(i.push(this._loader._loadFloatAccessorAsync(`/accessors/${n.bufferView}`,n)),0===a)a=n.count;else if(a!==n.count)throw new Error(`${e}/attributes: Instance buffer accessors do not have the same count.`)};return l("TRANSLATION"),l("ROTATION"),l("SCALE"),l("_COLOR_0"),yield r.then(e=>b(this,void 0,void 0,function*(){const[o,s,r,l]=yield Promise.all(i),u=new Float32Array(16*a);t.TmpVectors.Vector3[0].copyFromFloats(0,0,0),t.TmpVectors.Quaternion[0].copyFromFloats(0,0,0,1),t.TmpVectors.Vector3[1].copyFromFloats(1,1,1);for(let e=0;e<a;++e)o&&t.Vector3.FromArrayToRef(o,3*e,t.TmpVectors.Vector3[0]),s&&t.Quaternion.FromArrayToRef(s,4*e,t.TmpVectors.Quaternion[0]),r&&t.Vector3.FromArrayToRef(r,3*e,t.TmpVectors.Vector3[1]),t.Matrix.ComposeToRef(t.TmpVectors.Vector3[1],t.TmpVectors.Quaternion[0],t.TmpVectors.Vector3[0],t.TmpVectors.Matrix[0]),t.TmpVectors.Matrix[0].copyToArray(u,16*e);for(const e of n._primitiveBabylonMeshes)e.thinInstanceSetBuffer("matrix",u,16,!0),l&&(l.length===3*a?e.thinInstanceSetBuffer("color",l,3,!0):l.length===4*a?e.thinInstanceSetBuffer("color",l,4,!0):t.Logger.Warn("Unexpected size of _COLOR_0 attribute for mesh "+e.name));return e}))}))}},Vo=!1;function Ho(){Vo||(Vo=!0,no(Do),to(Do,!0,e=>new Go(e)))}Ho();var Ko={__proto__:null,EXT_mesh_gpu_instancing:Go,RegisterEXT_mesh_gpu_instancing:Ho};const Uo="EXT_meshopt_compression";let $o=class{constructor(e){this.name=Uo,this.enabled=e.isExtensionUsed(Uo),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,n){return yo.LoadExtensionAsync(e,n,this.name,(o,s)=>b(this,void 0,void 0,function*(){const o=n;if(o._meshOptData)return yield o._meshOptData;const r=_o.Get(`${e}/buffer`,this._loader.gltf.buffers,s.buffer);return o._meshOptData=this._loader.loadBufferAsync(`/buffers/${r.index}`,r,s.byteOffset||0,s.byteLength).then(e=>b(this,void 0,void 0,function*(){return yield t.MeshoptCompression.Default.decodeGltfBufferAsync(e,s.count,s.byteStride,s.mode,s.filter)})),yield o._meshOptData}))}},Wo=!1;function zo(){Wo||(Wo=!0,no(Uo),to(Uo,!0,e=>new $o(e)))}zo();var jo={__proto__:null,EXT_meshopt_compression:$o,RegisterEXT_meshopt_compression:zo};const qo="EXT_texture_webp";let Xo=class{constructor(e){this.name=qo,this._loader=e,this.enabled=e.isExtensionUsed(qo)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?yo.DefaultSampler:_o.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=_o.Get(`${o}/source`,this._loader.gltf.images,s.source);return yield this._loader._createTextureAsync(e,r,i,e=>{n(e)},void 0,!t._textureInfo.nonColorData)}))}},Yo=!1;function Qo(){Yo||(Yo=!0,no(qo),to(qo,!0,e=>new Xo(e)))}Qo();var Zo={__proto__:null,EXT_texture_webp:Xo,RegisterEXT_texture_webp:Qo};const Jo="EXT_texture_avif";let es=class{constructor(e){this.name=Jo,this._loader=e,this.enabled=e.isExtensionUsed(Jo)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?yo.DefaultSampler:_o.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=_o.Get(`${o}/source`,this._loader.gltf.images,s.source);return yield this._loader._createTextureAsync(e,r,i,e=>{n(e)},void 0,!t._textureInfo.nonColorData)}))}},ts=!1;function ns(){ts||(ts=!0,no(Jo),to(Jo,!0,e=>new es(e)))}ns();var os={__proto__:null,EXT_texture_avif:es,RegisterEXT_texture_avif:ns};const ss="EXT_lights_ies";let rs=class{constructor(e){this.name=ss,this._loader=e,this.enabled=this._loader.isExtensionUsed(ss)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,_o.Assign(this._lights)}}loadNodeAsync(e,n,o){return yo.LoadExtensionAsync(e,n,this.name,(s,r)=>b(this,void 0,void 0,function*(){let i,a;this._loader._allMaterialsDirtyRequired=!0;const l=yield this._loader.loadNodeAsync(e,n,e=>{a=_o.Get(s,this._lights,r.light);const n=a.name||e.name;this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,i=new t.SpotLight(n,t.Vector3.Zero(),t.Vector3.Backward(),0,1,this._loader.babylonScene),i.angle=Math.PI/2,i.innerAngle=0,i._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,a._babylonLight=i,i.falloffType=t.Light.FALLOFF_GLTF,i.diffuse=r.color?t.Color3.FromArray(r.color):t.Color3.White(),i.intensity=r.multiplier||1,i.range=Number.MAX_VALUE,i.parent=e,this._loader._babylonLights.push(i),yo.AddPointerMetadata(i,s),o(e)});let u;if(a.uri)u=yield this._loader.loadUriAsync(e,a,a.uri);else{const t=_o.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,a.bufferView);u=yield this._loader.loadBufferViewAsync(`/bufferViews/${t.index}`,t)}return i.iesProfileTexture=new t.Texture(name+"_iesProfile",this._loader.babylonScene,!0,!1,void 0,null,null,u,!0,void 0,void 0,void 0,void 0,".ies"),l}))}},is=!1;function as(){is||(is=!0,no(ss),to(ss,!0,e=>new rs(e)))}as();var ls={__proto__:null,EXT_lights_ies:rs,RegisterEXT_lights_ies:as};const us="KHR_draco_mesh_compression";let cs=class{constructor(e){this.name=us,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=t.DracoDecoder.DefaultAvailable&&this._loader.isExtensionUsed(us)}dispose(){delete this.dracoDecoder,this._loader=null}_loadVertexDataAsync(e,n,o){return yo.LoadExtensionAsync(e,n,this.name,(s,r)=>b(this,void 0,void 0,function*(){if(null!=n.mode&&4!==n.mode&&5!==n.mode)throw new Error(`${e}: Unsupported mode ${n.mode}`);const i={},a={},l=(e,t)=>{const s=r.attributes[e];if(null!=s&&(o._delayInfo=o._delayInfo||[],-1===o._delayInfo.indexOf(t)&&o._delayInfo.push(t),i[t]=s,this.useNormalizedFlagFromAccessor)){const o=_o.TryGet(this._loader.gltf.accessors,n.attributes[e]);o&&(a[t]=o.normalized||!1)}};l("POSITION",t.VertexBuffer.PositionKind),l("NORMAL",t.VertexBuffer.NormalKind),l("TANGENT",t.VertexBuffer.TangentKind),l("TEXCOORD_0",t.VertexBuffer.UVKind),l("TEXCOORD_1",t.VertexBuffer.UV2Kind),l("TEXCOORD_2",t.VertexBuffer.UV3Kind),l("TEXCOORD_3",t.VertexBuffer.UV4Kind),l("TEXCOORD_4",t.VertexBuffer.UV5Kind),l("TEXCOORD_5",t.VertexBuffer.UV6Kind),l("JOINTS_0",t.VertexBuffer.MatricesIndicesKind),l("WEIGHTS_0",t.VertexBuffer.MatricesWeightsKind),l("COLOR_0",t.VertexBuffer.ColorKind);const u=_o.Get(s,this._loader.gltf.bufferViews,r.bufferView);return u._dracoBabylonGeometry||(u._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${u.index}`,u).then(s=>b(this,void 0,void 0,function*(){const r=this.dracoDecoder||t.DracoDecoder.Default,l=_o.TryGet(this._loader.gltf.accessors,n.attributes.POSITION),u=this._loader.parent.alwaysComputeBoundingBox||o.skeleton||!l?null:go(l);return yield r._decodeMeshToGeometryForGltfAsync(o.name,this._loader.babylonScene,s,i,a,u).catch(t=>{throw new Error(`${e}: ${t.message}`)})}))),yield u._dracoBabylonGeometry}))}},ds=!1;function hs(){ds||(ds=!0,no(us),to(us,!0,e=>new cs(e)))}hs();var ms={__proto__:null,KHR_draco_mesh_compression:cs,RegisterKHR_draco_mesh_compression:hs};const fs="KHR_gaussian_splatting",ps=.28209479177387814,_s=[0,3,5,7];function gs(e){return e<=0?0:e>=255?255:e+.5|0}let ys=class{constructor(e){this.name=fs,this._loader=e,this.enabled=this._loader.isExtensionUsed(fs)}dispose(){this._loader=null}_loadMeshPrimitiveAsync(e,n,o,s,r,i){return yo.LoadExtensionAsync(e,r,this.name,o=>b(this,void 0,void 0,function*(){if(null!=r.mode&&0!==r.mode)throw new Error(`${o}: Gaussian splatting primitives must use POINTS mode`);const s=this._loader,a=t=>{const n=r.attributes[t];if(null==n)return null;const o=_o.Get(`${e}/attributes/${t}`,s.gltf.accessors,n);return s._loadFloatAccessorAsync(`/accessors/${o.index}`,o)},l=a("POSITION");if(!l)throw new Error(`${o}: Gaussian splatting primitive is missing the POSITION attribute`);let u=0;const c=[];for(let e=1;e<=3&&null!=r.attributes[`KHR_gaussian_splatting:SH_DEGREE_${e}_COEF_0`];e++){u=e;for(let t=0;t<_s[e];t++)c.push(`KHR_gaussian_splatting:SH_DEGREE_${e}_COEF_${t}`)}const d=s.babylonScene;d._blockEntityCollection=!!s._assetContainer;const h=new t.GaussianSplattingMesh(n,null,d);h._parentContainer=s._assetContainer,d._blockEntityCollection=!1,yo.AddPointerMetadata(h,e),s.parent.onMeshLoadedObservable.notifyObservers(h),i(h);const m=d.getEngine().getCaps(),[f,p,_,g,y,v,...b]=yield Promise.all([l,a("KHR_gaussian_splatting:ROTATION"),a("KHR_gaussian_splatting:SCALE"),a("KHR_gaussian_splatting:OPACITY"),a("KHR_gaussian_splatting:SH_DEGREE_0_COEF_0"),a("COLOR_0"),...c.map(e=>a(e))]),x=f.length/3,T=v?v.length/x:0,A=new ArrayBuffer(32*x),M=new Float32Array(A),w=new Uint8Array(A);let C=null;if(u>0){const e=3*((u+1)*(u+1)-1),n=Math.ceil(e/16),o=m.maxTextureSize,s=Math.ceil(x/o);C=t.AllocateShBuffers(n,s*o*4*4)}for(let e=0;e<x;e++){const t=8*e,n=32*e,o=3*e;if(M[t+0]=f[o+0],M[t+1]=f[o+1],M[t+2]=f[o+2],M[t+3]=_?_[o+0]:1,M[t+4]=_?_[o+1]:1,M[t+5]=_?_[o+2]:1,y)w[n+24]=gs(255*(.5+ps*y[o+0])),w[n+25]=gs(255*(.5+ps*y[o+1])),w[n+26]=gs(255*(.5+ps*y[o+2]));else if(v){const t=e*T;w[n+24]=gs(255*v[t+0]),w[n+25]=gs(255*v[t+1]),w[n+26]=gs(255*v[t+2])}else w[n+24]=255,w[n+25]=255,w[n+26]=255;w[n+27]=g?gs(255*g[e]):v&&T>=4?gs(255*v[e*T+3]):255;const s=4*e,r=p?p[s+0]:0,i=p?p[s+1]:0,a=p?p[s+2]:0,l=p?p[s+3]:1;if(w[n+28]=gs(127.5*l+127.5),w[n+29]=gs(127.5*r+127.5),w[n+30]=gs(127.5*i+127.5),w[n+31]=gs(127.5*a+127.5),C){const t=16*e;for(let e=0;e<b.length;e++){const n=b[e];if(n)for(let s=0;s<3;s++){const r=3*e+s,i=15&r;C[r>>4][t+i]=gs(128*n[o+s]+128)}}}}return yield h.updateDataAsync(A,null!=C?C:void 0,void 0,u||void 0),h}))}},vs=!1;function bs(){vs||(vs=!0,no(fs),to(fs,!0,e=>new ys(e)))}bs();var xs={__proto__:null,KHR_gaussian_splatting:ys,RegisterKHR_gaussian_splatting:bs};const Ts="KHR_lights_punctual";class As{constructor(e){this.name=Ts,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ts)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,_o.Assign(this._lights)}}loadNodeAsync(e,n,o){return yo.LoadExtensionAsync(e,n,this.name,(s,r)=>b(this,void 0,void 0,function*(){return this._loader._allMaterialsDirtyRequired=!0,yield this._loader.loadNodeAsync(e,n,e=>{let n;const i=_o.Get(s,this._lights,r.light),a=i.name||e.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,i.type){case"directional":{const e=new t.DirectionalLight(a,t.Vector3.Backward(),this._loader.babylonScene);e.position.setAll(0),n=e;break}case"point":n=new t.PointLight(a,t.Vector3.Zero(),this._loader.babylonScene);break;case"spot":{const e=new t.SpotLight(a,t.Vector3.Zero(),t.Vector3.Backward(),0,1,this._loader.babylonScene);e.angle=2*(i.spot&&i.spot.outerConeAngle||Math.PI/4),e.innerAngle=2*(i.spot&&i.spot.innerConeAngle||0),n=e;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${s}: Invalid light type (${i.type})`)}n._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,i._babylonLight=n,n.falloffType=t.Light.FALLOFF_GLTF,n.diffuse=i.color?t.Color3.FromArray(i.color):t.Color3.White(),n.intensity=null==i.intensity?1:i.intensity,n.range=null==i.range?Number.MAX_VALUE:i.range,n.parent=e,this._loader._babylonLights.push(n),yo.AddPointerMetadata(n,s),o(e)})}))}}let Ms=!1;function ws(){Ms||(Ms=!0,no(Ts),to(Ts,!0,e=>new As(e)))}ws();var Cs={__proto__:null,KHR_lights:As,RegisterKHR_lights:ws};const Rs="EXT_lights_area";let Os=class{constructor(e){this.name=Rs,this._loader=e,this.enabled=this._loader.isExtensionUsed(Rs)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,_o.Assign(this._lights)}}loadNodeAsync(e,n,o){return yo.LoadExtensionAsync(e,n,this.name,(s,r)=>b(this,void 0,void 0,function*(){return this._loader._allMaterialsDirtyRequired=!0,yield this._loader.loadNodeAsync(e,n,e=>{var n;let i;const a=_o.Get(s,this._lights,r.light),l=a.name||e.name;this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer;const u=void 0!==a.size?a.size:1;switch(a.type){case"rect":{const e=void 0!==(null===(n=a.rect)||void 0===n?void 0:n.aspect)?a.rect.aspect*u:u,o=u;i=new t.RectAreaLight(l,t.Vector3.Zero(),e,o,this._loader.babylonScene);break}case"disk":{const e=Math.sqrt(u*u*.25*Math.PI);i=new t.RectAreaLight(l,t.Vector3.Zero(),e,e,this._loader.babylonScene);break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${s}: Invalid area light type (${a.type})`)}i._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,a._babylonLight=i,i.falloffType=t.Light.FALLOFF_GLTF,i.diffuse=a.color?t.Color3.FromArray(a.color):t.Color3.White(),i.intensity=null==a.intensity?1:a.intensity;const c=new t.TransformNode(`${l}_orientation`,this._loader.babylonScene);c.rotationQuaternion=t.Quaternion.RotationAxis(t.Vector3.Up(),Math.PI),c.parent=e,i.parent=c,this._loader._babylonLights.push(i),yo.AddPointerMetadata(i,s),o(e)})}))}},Ss=!1;function Fs(){Ss||(Ss=!0,no(Rs),to(Rs,!0,e=>new Os(e)))}Fs();var Es={__proto__:null,EXT_lights_area:Os,RegisterEXT_lights_area:Fs};const Ls="KHR_materials_pbrSpecularGlossiness";let Is=class{constructor(e){this.name=Ls,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ls)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,n)),r.push(this._loadSpecularGlossinessPropertiesAsync(o,s,n)),this._loader.loadMaterialAlphaProperties(e,t,n),yield Promise.all(r).then(()=>{})}))}_loadSpecularGlossinessPropertiesAsync(e,n,o){const s=this._loader._getOrCreateMaterialAdapter(o),r=new Array;return s.configureSpecularGlossiness(),n.diffuseFactor?(s.baseColor=t.Color3.FromArray(n.diffuseFactor),o.alpha=n.diffuseFactor[3]):s.baseColor=t.Color3.White(),s.specularColor=n.specularFactor?t.Color3.FromArray(n.specularFactor):t.Color3.White(),s.glossiness=null==n.glossinessFactor?1:n.glossinessFactor,n.diffuseTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,n.diffuseTexture,e=>{e.name=`${o.name} (Diffuse)`,s.baseColorTexture=e})),n.specularGlossinessTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,n.specularGlossinessTexture,e=>{e.name=`${o.name} (Specular Glossiness)`,s.specularColorTexture=e})),Promise.all(r).then(()=>{})}},Ns=!1;function Ps(){Ns||(Ns=!0,no(Ls),to(Ls,!0,e=>new Is(e)))}Ps();var Bs={__proto__:null,KHR_materials_pbrSpecularGlossiness:Is,RegisterKHR_materials_pbrSpecularGlossiness:Ps};const ks="KHR_materials_unlit";let Ds=class{constructor(e){this.name=ks,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(ks)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,()=>b(this,void 0,void 0,function*(){return yield this._loadUnlitPropertiesAsync(e,t,n)}))}_loadUnlitPropertiesAsync(e,n,o){const s=this._loader._getOrCreateMaterialAdapter(o),r=new Array,i=n.pbrMetallicRoughness;return i&&(i.baseColorFactor&&(s.baseColor=t.Color3.FromArray(i.baseColorFactor),s.geometryOpacity=i.baseColorFactor[3]),i.baseColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,i.baseColorTexture,e=>{e.name=`${o.name} (Base Color)`,s.baseColorTexture=e}))),s.isUnlit=!0,n.doubleSided&&(s.backFaceCulling=!1,s.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,n,o),Promise.all(r).then(()=>{})}},Gs=!1;function Vs(){Gs||(Gs=!0,no(ks),to(ks,!0,e=>new Ds(e)))}Vs();var Hs={__proto__:null,KHR_materials_unlit:Ds,RegisterKHR_materials_unlit:Vs};const Ks="KHR_materials_clearcoat";let Us=class{constructor(e){this.name=Ks,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ks)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadClearCoatPropertiesAsync(o,s,n)),yield Promise.all(r)}))}_loadClearCoatPropertiesAsync(e,t,n){const o=this._loader._getOrCreateMaterialAdapter(n),s=new Array;return o.configureCoat(),o.coatWeight=void 0!==t.clearcoatFactor?t.clearcoatFactor:0,o.coatRoughness=void 0!==t.clearcoatRoughnessFactor?t.clearcoatRoughnessFactor:0,t.clearcoatTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,e=>{e.name=`${n.name} (ClearCoat)`,o.coatWeightTexture=e})),t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,e=>{e.name=`${n.name} (ClearCoat Roughness)`,o.coatRoughnessTexture=e}))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,e=>{var s;e.name=`${n.name} (ClearCoat Normal)`,o.geometryCoatNormalTexture=e,null!=(null===(s=t.clearcoatNormalTexture)||void 0===s?void 0:s.scale)&&(o.geometryCoatNormalTextureScale=t.clearcoatNormalTexture.scale)})),o.setNormalMapInversions(!n.getScene().useRightHandedSystem,n.getScene().useRightHandedSystem)),Promise.all(s).then(()=>{})}},$s=!1;function Ws(){$s||($s=!0,no(Ks),to(Ks,!0,e=>new Us(e)))}Ws();var zs={__proto__:null,KHR_materials_clearcoat:Us,RegisterKHR_materials_clearcoat:Ws};const js="KHR_materials_coat";let qs=class{constructor(e){this.name=js,this.order=191,this.useOpenPBR=!1,this._loader=e,this.enabled=this._loader.isExtensionUsed(js)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),t.extensions&&t.extensions.KHR_materials_openpbr&&(this.useOpenPBR=!0),r.push(this._loadCoatPropertiesAsync(o,s,n)),yield Promise.all(r)}))}_loadCoatPropertiesAsync(e,n,o){var s,r;const i=this._loader._getOrCreateMaterialAdapter(o),a=new Array;i.configureCoat(),i.coatWeight=void 0!==n.coatFactor?n.coatFactor:0,i.coatRoughness=void 0!==n.coatRoughnessFactor?n.coatRoughnessFactor:0,n.coatTexture&&a.push(this._loader.loadTextureInfoAsync(`${e}/coatTexture`,n.coatTexture,e=>{e.name=`${o.name} (Coat)`,i.coatWeightTexture=e})),n.coatRoughnessTexture&&(n.coatRoughnessTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/coatRoughnessTexture`,n.coatRoughnessTexture,e=>{e.name=`${o.name} (Coat Roughness)`,i.coatRoughnessTexture=e}))),n.coatNormalTexture&&(n.coatNormalTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/coatNormalTexture`,n.coatNormalTexture,e=>{var t;e.name=`${o.name} (Coat Normal)`,i.geometryCoatNormalTexture=e,null!=(null===(t=n.coatNormalTexture)||void 0===t?void 0:t.scale)&&(i.geometryCoatNormalTextureScale=n.coatNormalTexture.scale)})),i.setNormalMapInversions(!o.getScene().useRightHandedSystem,o.getScene().useRightHandedSystem)),i.coatDarkening=void 0!==n.coatDarkeningFactor?n.coatDarkeningFactor:1,i.coatIor=void 0!==n.coatIor?n.coatIor:1.5;const l=t.Color3.White();void 0!==n.coatColorFactor&&l.fromArray(n.coatColorFactor),i.coatColor=l,n.coatColorTexture&&a.push(this._loader.loadTextureInfoAsync(`${e}/coatColorTexture`,n.coatColorTexture,e=>{e.name=`${o.name} (Coat Color)`,i.coatColorTexture=e}));const u=null!==(s=n.coatAnisotropyStrength)&&void 0!==s?s:0,c=null!==(r=n.coatAnisotropyRotation)&&void 0!==r?r:0;return i.coatRoughnessAnisotropy=u,i.geometryCoatTangentAngle=c,this.useOpenPBR||i.configureGltfStyleAnisotropy(!0),n.coatAnisotropyTexture&&(n.coatAnisotropyTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/coatAnisotropyTexture`,n.coatAnisotropyTexture,e=>{e.name=`${o.name} (Coat Anisotropy)`,i.geometryCoatTangentTexture=e}))),Promise.all(a).then(()=>{})}},Xs=!1;function Ys(){Xs||(Xs=!0,no(js),to(js,!0,e=>new qs(e)))}Ys();var Qs={__proto__:null,KHR_materials_coat:qs,RegisterKHR_materials_coat:Ys};const Zs="KHR_materials_iridescence";let Js=class{constructor(e){this.name=Zs,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(Zs)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadIridescencePropertiesAsync(o,s,n)),yield Promise.all(r).then(()=>{})}))}_loadIridescencePropertiesAsync(e,t,n){var o,s,r,i,a;const l=this._loader._getOrCreateMaterialAdapter(n),u=new Array;return l.thinFilmWeight=null!==(o=t.iridescenceFactor)&&void 0!==o?o:0,l.thinFilmIor=null!==(r=null!==(s=t.iridescenceIor)&&void 0!==s?s:t.iridescenceIOR)&&void 0!==r?r:1.3,l.thinFilmThicknessMinimum=null!==(i=t.iridescenceThicknessMinimum)&&void 0!==i?i:100,l.thinFilmThicknessMaximum=null!==(a=t.iridescenceThicknessMaximum)&&void 0!==a?a:400,t.iridescenceTexture&&u.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,e=>{e.name=`${n.name} (Iridescence)`,l.thinFilmWeightTexture=e})),t.iridescenceThicknessTexture&&u.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,e=>{e.name=`${n.name} (Iridescence Thickness)`,l.thinFilmThicknessTexture=e})),Promise.all(u).then(()=>{})}},er=!1;function tr(){er||(er=!0,no(Zs),to(Zs,!0,e=>new Js(e)))}tr();var nr={__proto__:null,KHR_materials_iridescence:Js,RegisterKHR_materials_iridescence:tr};const or="KHR_materials_anisotropy";let sr=class{constructor(e){this.name=or,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(or)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadAnisotropyPropertiesAsync(o,s,n)),yield Promise.all(r)}))}_loadAnisotropyPropertiesAsync(e,t,n){return b(this,void 0,void 0,function*(){var o,s,r;const i=this._loader._getOrCreateMaterialAdapter(n),a=new Array,l=null!==(o=t.anisotropyStrength)&&void 0!==o?o:0,u=null!==(s=t.anisotropyRotation)&&void 0!==s?s:0;i.specularRoughnessAnisotropy=l,i.geometryTangentAngle=u;const c=null!==(r=t.extensions)&&void 0!==r?r:{};c.EXT_materials_anisotropy_openpbr&&c.EXT_materials_anisotropy_openpbr.openPbrAnisotropyEnabled||i.configureGltfStyleAnisotropy(!0),t.anisotropyTexture&&(t.anisotropyTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,e=>{e.name=`${n.name} (Anisotropy Intensity)`,i.geometryTangentTexture=e}))),yield Promise.all(a)})}},rr=!1;function ir(){rr||(rr=!0,no(or),to(or,!0,e=>new sr(e)))}ir();var ar={__proto__:null,KHR_materials_anisotropy:sr,RegisterKHR_materials_anisotropy:ir};const lr="KHR_materials_emissive_strength";let ur=class{constructor(e){this.name=lr,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(lr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){return yield this._loader.loadMaterialPropertiesAsync(e,t,n),this._loadEmissiveProperties(o,s,n),yield Promise.resolve()}))}_loadEmissiveProperties(e,t,n){void 0!==t.emissiveStrength&&(this._loader._getOrCreateMaterialAdapter(n).emissionLuminance=t.emissiveStrength)}},cr=!1;function dr(){cr||(cr=!0,no(lr),to(lr,!0,e=>new ur(e)))}dr();var hr={__proto__:null,KHR_materials_emissive_strength:ur,RegisterKHR_materials_emissive_strength:dr};const mr="KHR_materials_sheen";let fr=class{constructor(e){this.name=mr,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(mr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadSheenPropertiesAsync(o,s,n)),yield Promise.all(r).then(()=>{})}))}_loadSheenPropertiesAsync(e,n,o){const s=this._loader._getOrCreateMaterialAdapter(o),r=new Array;s.configureFuzz();const i=void 0!==n.sheenColorFactor?t.Color3.FromArray(n.sheenColorFactor):t.Color3.Black(),a=void 0!==n.sheenRoughnessFactor?n.sheenRoughnessFactor:0;return s.fuzzWeight=1,s.fuzzColor=i,s.fuzzRoughness=a,n.sheenColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/sheenColorTexture`,n.sheenColorTexture,e=>{e.name=`${o.name} (Sheen Color)`,s.fuzzColorTexture=e})),n.sheenRoughnessTexture&&(n.sheenRoughnessTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,n.sheenRoughnessTexture,e=>{e.name=`${o.name} (Sheen Roughness)`,s.fuzzRoughnessTexture=e}))),Promise.all(r).then(()=>{})}},pr=!1;function _r(){pr||(pr=!0,no(mr),to(mr,!0,e=>new fr(e)))}_r();var gr={__proto__:null,KHR_materials_sheen:fr,RegisterKHR_materials_sheen:_r};const yr="KHR_materials_fuzz";let vr=class{constructor(e){this.name=yr,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(yr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadFuzzPropertiesAsync(o,s,n)),yield Promise.all(r).then(()=>{})}))}_loadFuzzPropertiesAsync(e,n,o){const s=this._loader._getOrCreateMaterialAdapter(o),r=new Array;return s.configureFuzz(),s.fuzzWeight=void 0!==n.fuzzFactor?n.fuzzFactor:0,s.fuzzColor=void 0!==n.fuzzColorFactor?t.Color3.FromArray(n.fuzzColorFactor):t.Color3.White(),s.fuzzRoughness=void 0!==n.fuzzRoughnessFactor?n.fuzzRoughnessFactor:.5,n.fuzzTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/fuzzTexture`,n.fuzzTexture,e=>{e.name=`${o.name} (Fuzz)`,s.fuzzWeightTexture=e})),n.fuzzColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/fuzzColorTexture`,n.fuzzColorTexture,e=>{e.name=`${o.name} (Fuzz Color)`,s.fuzzColorTexture=e})),n.fuzzRoughnessTexture&&(n.fuzzRoughnessTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/fuzzRoughnessTexture`,n.fuzzRoughnessTexture,e=>{e.name=`${o.name} (Fuzz Roughness)`,s.fuzzRoughnessTexture=e}))),Promise.all(r).then(()=>{})}},br=!1;function xr(){br||(br=!0,no(yr),to(yr,!0,e=>new vr(e)))}xr();var Tr={__proto__:null,KHR_materials_fuzz:vr,RegisterKHR_materials_fuzz:xr};const Ar="KHR_materials_specular";let Mr=class{constructor(e){this.name=Ar,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ar)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadSpecularPropertiesAsync(o,s,n));const i=this._loader._getOrCreateMaterialAdapter(n);return s.extensions&&s.extensions.EXT_materials_specular_edge_color&&s.extensions.EXT_materials_specular_edge_color.specularEdgeColorEnabled&&i.enableSpecularEdgeColor(!0),yield Promise.all(r).then(()=>{})}))}_loadSpecularPropertiesAsync(e,n,o){var s;const r=this._loader._getOrCreateMaterialAdapter(o),i=new Array;return r.specularWeight=null!==(s=n.specularFactor)&&void 0!==s?s:1,r.specularColor=void 0!==n.specularColorFactor?t.Color3.FromArray(n.specularColorFactor):new t.Color3(1,1,1),n.specularTexture&&(n.specularTexture.nonColorData=!0,i.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,n.specularTexture,e=>{e.name=`${o.name} (Specular)`,r.specularWeightTexture=e}))),n.specularColorTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,n.specularColorTexture,e=>{e.name=`${o.name} (Specular Color)`,r.specularColorTexture=e})),Promise.all(i).then(()=>{})}},wr=!1;function Cr(){wr||(wr=!0,no(Ar),to(Ar,!0,e=>new Mr(e)))}Cr();var Rr={__proto__:null,KHR_materials_specular:Mr,RegisterKHR_materials_specular:Cr};const Or="KHR_materials_ior";let Sr=class e{constructor(e){this.name=Or,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(Or)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadIorPropertiesAsync(o,s,n)),yield Promise.all(r).then(()=>{})}))}_loadIorPropertiesAsync(t,n,o){const s=this._loader._getOrCreateMaterialAdapter(o),r=void 0!==n.ior?n.ior:e._DEFAULT_IOR;return s.specularIor=r,Promise.resolve()}};Sr._DEFAULT_IOR=1.5;let Fr=!1;function Er(){Fr||(Fr=!0,no(Or),to(Or,!0,e=>new Sr(e)))}Er();var Lr={__proto__:null,KHR_materials_ior:Sr,RegisterKHR_materials_ior:Er};const Ir="KHR_materials_variants";let Nr=class e{constructor(e){this.name=Ir,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ir)&&!this._loader.parent.skipMaterials}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(t){return e.GetAvailableVariants(t)}static SelectVariant(e,t){const n=this._GetExtensionMetadata(e);if(!n)throw new Error(`Cannot select variant on a glTF mesh that does not have the ${Ir} extension`);const o=e=>{const t=n.variants[e];if(t)for(const e of t)e.mesh.material=e.material};if(t instanceof Array)for(const e of t)o(e);else o(t);n.lastSelected=t}selectVariant(t,n){e.SelectVariant(t,n)}static Reset(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot reset on a glTF mesh that does not have the ${Ir} extension`);for(const e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(t){e.Reset(t)}static GetLastSelectedVariant(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot get the last selected variant on a glTF mesh that does not have the ${Ir} extension`);return t.lastSelected}getLastSelectedVariant(t){return e.GetLastSelectedVariant(t)}static _GetExtensionMetadata(e){var t,n;return(null===(n=null===(t=null==e?void 0:e._internalMetadata)||void 0===t?void 0:t.gltf)||void 0===n?void 0:n[Ir])||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}onReady(){var t;const n=this._loader.rootBabylonMesh;if(n){const o=this._loader.parent.extensionOptions[Ir];(null==o?void 0:o.defaultVariant)&&e.SelectVariant(n,o.defaultVariant),null===(t=null==o?void 0:o.onLoaded)||void 0===t||t.call(o,{get variants(){return e.GetAvailableVariants(n)},get selectedVariant(){const t=e.GetLastSelectedVariant(n);return t?Array.isArray(t)?t[0]:t:e.GetAvailableVariants(n)[0]},set selectedVariant(t){e.SelectVariant(n,t)}})}}_loadMeshPrimitiveAsync(n,o,s,r,i,a){return yo.LoadExtensionAsync(n,i,this.name,(l,u)=>b(this,void 0,void 0,function*(){const c=new Array;return c.push(this._loader._loadMeshPrimitiveAsync(n,o,s,r,i,o=>{if(a(o),o instanceof t.Mesh){const t=yo._GetDrawMode(n,i.mode),s=this._loader.rootBabylonMesh,r=s?s._internalMetadata=s._internalMetadata||{}:{},a=r.gltf=r.gltf||{},d=a[Ir]=a[Ir]||{lastSelected:null,original:[],variants:{}};d.original.push({mesh:o,material:o.material});for(let n=0;n<u.mappings.length;++n){const r=u.mappings[n],i=_o.Get(`${l}/mappings/${n}/material`,this._loader.gltf.materials,r.material);c.push(this._loader._loadMaterialAsync(`#/materials/${r.material}`,i,o,t,t=>{for(let n=0;n<r.variants.length;++n){const i=r.variants[n],a=_o.Get(`/extensions/${Ir}/variants/${i}`,this._variants,i);d.variants[a.name]=d.variants[a.name]||[],d.variants[a.name].push({mesh:o,material:t}),o.onClonedObservable.add(t=>{const n=t;let r,i=n;do{if(i=i.parent,!i)return;r=e._GetExtensionMetadata(i)}while(null===r);if(s&&r===e._GetExtensionMetadata(s)){i._internalMetadata={};for(const e in s._internalMetadata)i._internalMetadata[e]=s._internalMetadata[e];i._internalMetadata.gltf=[];for(const e in s._internalMetadata.gltf)i._internalMetadata.gltf[e]=s._internalMetadata.gltf[e];i._internalMetadata.gltf[Ir]={lastSelected:null,original:[],variants:{}};for(const e of r.original)i._internalMetadata.gltf[Ir].original.push({mesh:e.mesh,material:e.material});for(const e in r.variants)if(Object.prototype.hasOwnProperty.call(r.variants,e)){i._internalMetadata.gltf[Ir].variants[e]=[];for(const t of r.variants[e])i._internalMetadata.gltf[Ir].variants[e].push({mesh:t.mesh,material:t.material})}r=i._internalMetadata.gltf[Ir]}for(const e of r.original)e.mesh===o&&(e.mesh=n);for(const e of r.variants[a.name])e.mesh===o&&(e.mesh=n)})}}))}}})),yield Promise.all(c).then(([e])=>e)}))}},Pr=!1;function Br(){Pr||(Pr=!0,no(Ir),to(Ir,!0,e=>new Nr(e)))}Br();var kr={__proto__:null,KHR_materials_variants:Nr,RegisterKHR_materials_variants:Br};class Dr{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:t.Constants.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,n){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._newMeshObserver=null,this._removedMeshObserver=null,this._disposed=!1,this._materialImpls=[],this._adapterCache=new WeakMap,this._translucentMaterialIndices=new Map,this._opaqueOnlySubMeshes=new Map,this._savedSubMeshes=new Map,this._options=Object.assign(Object.assign({},Dr._GetDefaultOptions()),e),this._scene=n,this._scene._transmissionHelper=this,this.onErrorObservable=new t.Observable,this._scene.onDisposeObservable.addOnce(()=>{this.dispose()}),this._parseScene(),this._setupRenderTargets()}addMaterialImpl(e){this._materialImpls.some(t=>t.materialClass===e.materialClass)||this._materialImpls.push(e)}updateOptions(e){if(!Object.keys(e).filter(t=>this._options[t]!==e[t]).length)return;const t=Object.assign(Object.assign({},this._options),e),n=this._options;this._options=t,t.renderSize===n.renderSize&&t.renderTargetTextureType===n.renderTargetTextureType&&t.generateMipmaps===n.generateMipmaps&&this._opaqueRenderTarget?(this._opaqueRenderTarget.samples=t.samples,this._opaqueRenderTarget.lodGenerationScale=t.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=t.lodGenerationOffset):this._setupRenderTargets()}getOpaqueTarget(){return this._opaqueRenderTarget}_getOrCreateAdapter(e){let t=this._adapterCache.get(e);if(!t)for(const n of this._materialImpls)if(e instanceof n.materialClass){t=new n.adapterClass(e),this._adapterCache.set(e,t);break}return t}_classifyMeshMaterials(e){const n=e.material;if(!n)return"opaque";if(!(n instanceof t.MultiMaterial)){const e=this._getOrCreateAdapter(n);return e&&e.isTranslucent()?(e.refractionBackgroundTexture=this._opaqueRenderTarget,"transparent"):"opaque"}let o=!1,s=!1;const r=new Set;for(let e=0;e<n.subMaterials.length;e++){const t=n.subMaterials[e];if(!t){s=!0;continue}const i=this._getOrCreateAdapter(t);i&&i.isTranslucent()?(i.refractionBackgroundTexture=this._opaqueRenderTarget,o=!0,r.add(e)):s=!0}return o&&s?(this._translucentMaterialIndices.set(e,r),this._rebuildOpaqueOnlySubMeshes(e,r),"mixed"):(this._translucentMaterialIndices.delete(e),this._opaqueOnlySubMeshes.delete(e),o?"transparent":"opaque")}_rebuildOpaqueOnlySubMeshes(e,t){e.subMeshes&&this._opaqueOnlySubMeshes.set(e,e.subMeshes.filter(e=>!t.has(e.materialIndex)))}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),t.Tools.SetImmediate(()=>{!this._disposed&&e.material&&("transparent"===this._classifyMeshMaterials(e)?-1===this._transparentMeshesCache.indexOf(e)&&this._transparentMeshesCache.push(e):-1===this._opaqueMeshesCache.indexOf(e)&&this._opaqueMeshesCache.push(e))})}_removeMesh(e){e.onMaterialChangedObservable.remove(this._materialObservers[e.uniqueId]),delete this._materialObservers[e.uniqueId];let t=this._transparentMeshesCache.indexOf(e);-1!==t&&this._transparentMeshesCache.splice(t,1),t=this._opaqueMeshesCache.indexOf(e),-1!==t&&this._opaqueMeshesCache.splice(t,1),this._translucentMaterialIndices.delete(e),this._opaqueOnlySubMeshes.delete(e)}_parseScene(){this._scene.meshes.forEach(this._addMesh.bind(this)),this._newMeshObserver=this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this)),this._removedMeshObserver=this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this))}_onMeshMaterialChanged(e){const t=this._transparentMeshesCache.indexOf(e),n=this._opaqueMeshesCache.indexOf(e);"transparent"===this._classifyMeshMaterials(e)?-1!==n?(this._opaqueMeshesCache.splice(n,1),this._transparentMeshesCache.push(e)):-1===t&&this._transparentMeshesCache.push(e):-1!==t?(this._transparentMeshesCache.splice(t,1),this._opaqueMeshesCache.push(e)):-1===n&&this._opaqueMeshesCache.push(e)}_isRenderTargetValid(){var e;return null!==(null===(e=this._opaqueRenderTarget)||void 0===e?void 0:e.getInternalTexture())}_setupRenderTargets(){var e,n;let o;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new t.RenderTargetTexture("opaqueSceneTexture",this._options.renderSize,this._scene,this._options.generateMipmaps,void 0,this._options.renderTargetTextureType),this._opaqueRenderTarget.ignoreCameraViewport=!0,this._opaqueRenderTarget.renderList=this._opaqueMeshesCache,this._opaqueRenderTarget.clearColor=null!==(n=null===(e=this._options.clearColor)||void 0===e?void 0:e.clone())&&void 0!==n?n:this._scene.clearColor.clone(),this._opaqueRenderTarget.clearColor.a=0,this._opaqueRenderTarget.gammaSpace=!1,this._opaqueRenderTarget.lodGenerationScale=this._options.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=this._options.lodGenerationOffset,this._opaqueRenderTarget.samples=this._options.samples,this._opaqueRenderTarget.renderSprites=!0,this._opaqueRenderTarget.renderParticles=!0,this._opaqueRenderTarget.disableImageProcessing=!0,this._opaqueRenderTarget.onBeforeBindObservable.add(e=>{o=this._scene.environmentIntensity,this._scene.environmentIntensity=1,this._options.clearColor?e.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(e.clearColor,this._scene.getEngine().useExactSrgbConversions),e.clearColor.a=0;const t=this._opaqueOnlySubMeshes.entries();for(let e=t.next();!e.done;e=t.next()){const t=e.value[0],n=e.value[1];t.subMeshes&&(this._savedSubMeshes.set(t,t.subMeshes),t.subMeshes=n)}}),this._opaqueRenderTarget.onAfterUnbindObservable.add(()=>{this._scene.environmentIntensity=o;const e=this._savedSubMeshes.entries();for(let t=e.next();!t.done;t=e.next())t.value[0].subMeshes=t.value[1];this._savedSubMeshes.clear()});for(const e of this._transparentMeshesCache)e.material&&this._classifyMeshMaterials(e);const s=this._translucentMaterialIndices.entries();for(let e=s.next();!e.done;e=s.next()){const t=e.value[0];t.material&&this._classifyMeshMaterials(t)}}dispose(){var e,t;this._disposed=!0,null===(e=this._newMeshObserver)||void 0===e||e.remove(),null===(t=this._removedMeshObserver)||void 0===t||t.remove(),this._newMeshObserver=null,this._removedMeshObserver=null;const n=[...this._transparentMeshesCache,...this._opaqueMeshesCache];for(const e of n){const t=this._materialObservers[e.uniqueId];t&&(t.remove(),delete this._materialObservers[e.uniqueId])}for(const e of this._scene.meshes){const t=this._materialObservers[e.uniqueId];t&&(t.remove(),delete this._materialObservers[e.uniqueId])}this._materialObservers={},this._scene._transmissionHelper=void 0,this._opaqueRenderTarget&&(this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[],this._translucentMaterialIndices.clear(),this._opaqueOnlySubMeshes.clear(),this._savedSubMeshes.clear()}}function Gr(e,t){if(e.parent.dontUseTransmissionHelper)return;const n=t.getScene()._transmissionHelper,o=null!=n?n:new Dr({},t.getScene());for(const t of Array.from(e._pbrMaterialImpls.values()))o.addMaterialImpl(t);n&&!n._isRenderTargetValid()&&n._setupRenderTargets()}const Vr="KHR_materials_transmission";let Hr=class{constructor(e){this.name=Vr,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(Vr),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadTransparentPropertiesAsync(o,t,n,s)),yield Promise.all(r).then(()=>{})}))}_loadTransparentPropertiesAsync(e,t,n,o){const s=this._loader._getOrCreateMaterialAdapter(n),r=void 0!==o.transmissionFactor?o.transmissionFactor:0;if(0===r||!s)return Promise.resolve();s.configureTransmission(),s.transmissionWeight=r,r>0&&Gr(this._loader,n);let i=Promise.resolve(null);return o.transmissionTexture&&(o.transmissionTexture.nonColorData=!0,i=this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,o.transmissionTexture,e=>{e.name=`${n.name} (Transmission)`,s.transmissionWeightTexture=e})),i.then(()=>{})}},Kr=!1;function Ur(){Kr||(Kr=!0,no(Vr),to(Vr,!0,e=>new Hr(e)))}Ur();var $r={__proto__:null,KHR_materials_transmission:Hr,RegisterKHR_materials_transmission:Ur};const Wr="KHR_materials_diffuse_transmission";let zr=class{constructor(e){this.name=Wr,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(Wr),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadTranslucentPropertiesAsync(o,t,n,s)),yield Promise.all(r).then(()=>{})}))}_loadTranslucentPropertiesAsync(e,n,o,s){var r;const i=this._loader._getOrCreateMaterialAdapter(o);i.configureSubsurface(),i.subsurfaceWeight=null!==(r=s.diffuseTransmissionFactor)&&void 0!==r?r:0,i.subsurfaceWeight>0&&Gr(this._loader,o),i.diffuseTransmissionTint=void 0!==s.diffuseTransmissionColorFactor?t.Color3.FromArray(s.diffuseTransmissionColorFactor):t.Color3.White();const a=new Array;return s.diffuseTransmissionTexture&&(s.diffuseTransmissionTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionTexture`,s.diffuseTransmissionTexture).then(e=>{e.name=`${o.name} (Diffuse Transmission)`,i.subsurfaceWeightTexture=e}))),s.diffuseTransmissionColorTexture&&a.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionColorTexture`,s.diffuseTransmissionColorTexture).then(e=>{e.name=`${o.name} (Diffuse Transmission Color)`,i.diffuseTransmissionTintTexture=e})),Promise.all(a).then(()=>{})}},jr=!1;function qr(){jr||(jr=!0,no(Wr),to(Wr,!0,e=>new zr(e)))}qr();var Xr={__proto__:null,KHR_materials_diffuse_transmission:zr,RegisterKHR_materials_diffuse_transmission:qr};const Yr="KHR_materials_volume";let Qr=class{constructor(e){this.name=Yr,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(Yr),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadVolumePropertiesAsync(o,t,n,s)),yield Promise.all(r).then(()=>{})}))}_loadVolumePropertiesAsync(e,n,o,s){var r;const i=this._loader._getOrCreateMaterialAdapter(o);if(0===i.transmissionWeight&&0===i.subsurfaceWeight||!s.thicknessFactor)return Promise.resolve();i.geometryThinWalled=!1;const a=void 0!==s.attenuationDistance?s.attenuationDistance:Number.MAX_VALUE,l=void 0!==s.attenuationColor&&3==s.attenuationColor.length?t.Color3.FromArray(s.attenuationColor):t.Color3.White();i.configureVolume(),i.transmissionColor=l,i.transmissionDepth=a,i.volumeThickness=null!==(r=s.thicknessFactor)&&void 0!==r?r:0;const u=new Array;return s.thicknessTexture&&(s.thicknessTexture.nonColorData=!0,u.push(this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,s.thicknessTexture,e=>{e.name=`${o.name} (Thickness)`,i.volumeThicknessTexture=e}))),Promise.all(u).then(()=>{})}},Zr=!1;function Jr(){Zr||(Zr=!0,no(Yr),to(Yr,!0,e=>new Qr(e)))}Jr();var ei={__proto__:null,KHR_materials_volume:Qr,RegisterKHR_materials_volume:Jr};const ti="KHR_materials_volume_scatter";let ni=class{constructor(e){this.name=ti,this.order=172,this._loader=e,this.enabled=this._loader.isExtensionUsed(ti),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadVolumePropertiesAsync(o,t,n,s)),yield Promise.all(r).then(()=>{})}))}_loadVolumePropertiesAsync(e,n,o,s){const r=this._loader._getOrCreateMaterialAdapter(o);if(0===r.transmissionWeight&&0===r.subsurfaceWeight||r.geometryThinWalled)return Promise.resolve();const i=void 0!==s.multiscatterColorFactor&&3==s.multiscatterColorFactor.length?t.Color3.FromArray(s.multiscatterColorFactor):t.Color3.Black(),a=void 0!==s.scatterAnisotropy?s.scatterAnisotropy:0;let l=Promise.resolve(null);s.multiscatterColorTexture&&(s.multiscatterColorTexture.nonColorData=!0,l=this._loader.loadTextureInfoAsync(`${e}/multiscatterColorTexture`,s.multiscatterColorTexture,e=>{e.name=`${o.name} (Scatter Color)`,r.transmissionWeight>0&&(r.transmissionScatterTexture=e),r.subsurfaceWeight>0&&(r.subsurfaceColorTexture=e)}));const u=new t.Vector3(-Math.log(r.transmissionColor.r),-Math.log(r.transmissionColor.g),-Math.log(r.transmissionColor.b));if(u.scaleInPlace(1/Math.max(r.transmissionDepth,1e-6)),r.transmissionWeight>0){const e=function(e){const n=new t.Vector3(e.r,e.g,e.b),o=new t.Vector3(4.09712,4.09712,4.09712);o.addInPlace(new t.Vector3(4.20863,4.20863,4.20863).multiplyInPlace(n));const s=new t.Vector3(9.59217,9.59217,9.59217);return s.addInPlace(new t.Vector3(41.6808,41.6808,41.6808).multiplyInPlace(n)),s.addInPlace(new t.Vector3(17.7126,17.7126,17.7126).multiplyInPlace(n.multiply(n))),o.subtractInPlace(new t.Vector3(Math.sqrt(s.x),Math.sqrt(s.y),Math.sqrt(s.z))),new t.Vector3(1,1,1).subtract(o.multiply(o))}(i),n=u.multiply(e);n.scaleInPlace(r.transmissionDepth),r.transmissionScatter.set(n.x,n.y,n.z),r.transmissionScatterAnisotropy=a}if(r.subsurfaceWeight>0){r.subsurfaceScatterAnisotropy=a,r.subsurfaceColor=i;const e=new t.Vector3(0!==u.x?1/u.x:1,0!==u.y?1/u.y:1,0!==u.z?1/u.z:1);r.subsurfaceRadius=Math.max(e.x,e.y,e.z),r.subsurfaceRadiusScale=new t.Color3(e.x/r.subsurfaceRadius,e.y/r.subsurfaceRadius,e.z/r.subsurfaceRadius)}return l.then(()=>{})}},oi=!1;function si(){oi||(oi=!0,no(ti),to(ti,!0,e=>new ni(e)))}si();var ri={__proto__:null,KHR_materials_volume_scatter:ni,RegisterKHR_materials_volume_scatter:si};const ii="KHR_materials_dispersion";let ai=class{constructor(e){this.name=ii,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(ii)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadDispersionPropertiesAsync(o,t,n,s)),yield Promise.all(r).then(()=>{})}))}_loadDispersionPropertiesAsync(e,t,n,o){const s=this._loader._getOrCreateMaterialAdapter(n);return 0!=s.transmissionWeight&&o.dispersion?(s.transmissionDispersionAbbeNumber=20,s.transmissionDispersionScale=o.dispersion,Promise.resolve()):Promise.resolve()}},li=!1;function ui(){li||(li=!0,no(ii),to(ii,!0,e=>new ai(e)))}ui();var ci={__proto__:null,KHR_materials_dispersion:ai,RegisterKHR_materials_dispersion:ui};const di="KHR_materials_diffuse_roughness";let hi=class{constructor(e){this.name=di,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(di)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadDiffuseRoughnessPropertiesAsync(o,s,n)),yield Promise.all(r).then(()=>{})}))}_loadDiffuseRoughnessPropertiesAsync(e,t,n){var o;const s=this._loader._getOrCreateMaterialAdapter(n),r=new Array;return s.baseDiffuseRoughness=null!==(o=t.diffuseRoughnessFactor)&&void 0!==o?o:0,t.diffuseRoughnessTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/diffuseRoughnessTexture`,t.diffuseRoughnessTexture,e=>{e.name=`${n.name} (Diffuse Roughness)`,s.baseDiffuseRoughnessTexture=e})),Promise.all(r).then(()=>{})}},mi=!1;function fi(){mi||(mi=!0,no(di),to(di,!0,e=>new hi(e)))}fi();var pi={__proto__:null,KHR_materials_diffuse_roughness:hi,RegisterKHR_materials_diffuse_roughness:fi};const _i="KHR_mesh_quantization";let gi=class{constructor(e){this.name=_i,this.enabled=e.isExtensionUsed(_i)}dispose(){}},yi=!1;function vi(){yi||(yi=!0,no(_i),to(_i,!0,e=>new gi(e)))}vi();var bi={__proto__:null,KHR_mesh_quantization:gi,RegisterKHR_mesh_quantization:vi};const xi="KHR_texture_basisu";let Ti=class{constructor(e){this.name=xi,this._loader=e,this.enabled=e.isExtensionUsed(xi)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return yo.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?yo.DefaultSampler:_o.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=_o.Get(`${o}/source`,this._loader.gltf.images,s.source);return yield this._loader._createTextureAsync(e,r,i,e=>{n(e)},t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)}))}},Ai=!1;function Mi(){Ai||(Ai=!0,no(xi),to(xi,!0,e=>new Ti(e)))}Mi();var wi={__proto__:null,KHR_texture_basisu:Ti,RegisterKHR_texture_basisu:Mi};const Ci="KHR_texture_transform";let Ri=class{constructor(e){this.name=Ci,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ci)}dispose(){this._loader=null}loadTextureInfoAsync(e,n,o){return yo.LoadExtensionAsync(e,n,this.name,(s,r)=>b(this,void 0,void 0,function*(){return yield this._loader.loadTextureInfoAsync(e,n,e=>{if(!(e instanceof t.Texture))throw new Error(`${s}: Texture type not supported`);r.offset&&(e.uOffset=r.offset[0],e.vOffset=r.offset[1]),e.uRotationCenter=0,e.vRotationCenter=0,r.rotation&&(e.wAng=-r.rotation),r.scale&&(e.uScale=r.scale[0],e.vScale=r.scale[1]),null!=r.texCoord&&(e.coordinatesIndex=r.texCoord),o(e)})}))}},Oi=!1;function Si(){Oi||(Oi=!0,no(Ci),to(Ci,!0,e=>new Ri(e)))}Si();var Fi={__proto__:null,KHR_texture_transform:Ri,RegisterKHR_texture_transform:Si};const Ei="KHR_xmp_json_ld";let Li=class{constructor(e){this.name=Ei,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ei)}dispose(){this._loader=null}onLoading(){var e,t,n;if(null===this._loader.rootBabylonMesh)return;const o=null===(e=this._loader.gltf.extensions)||void 0===e?void 0:e.KHR_xmp_json_ld,s=null===(n=null===(t=this._loader.gltf.asset)||void 0===t?void 0:t.extensions)||void 0===n?void 0:n.KHR_xmp_json_ld;if(o&&s){const e=+s.packet;o.packets&&e<o.packets.length&&(this._loader.rootBabylonMesh.metadata=this._loader.rootBabylonMesh.metadata||{},this._loader.rootBabylonMesh.metadata.xmp=o.packets[e])}}},Ii=!1;function Ni(){Ii||(Ii=!0,no(Ei),to(Ei,!0,e=>new Li(e)))}Ni();var Pi={__proto__:null,KHR_xmp_json_ld:Li,RegisterKHR_xmp_json_ld:Ni};const Bi="KHR_animation_pointer";let ki=class{constructor(e){this.name=Bi,this._loader=e,this._pathToObjectConverter=uo(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(Bi)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,n,o,s,r){var i;const a=null===(i=s.target.extensions)||void 0===i?void 0:i.KHR_animation_pointer;if(!a||!this._pathToObjectConverter)return null;"pointer"!==s.target.path&&t.Logger.Warn(`${e}/target/path: Value (${s.target.path}) must be (pointer) when using the ${this.name} extension`),null!=s.target.node&&t.Logger.Warn(`${e}/target/node: Value (${s.target.node}) must not be present when using the ${this.name} extension`);const l=`${e}/extensions/${this.name}`,u=a.pointer;if(!u)throw new Error(`${l}: Pointer is missing`);try{const t=this._pathToObjectConverter.convert(u);if(!t.info.interpolation)throw new Error(`${l}/pointer: Interpolation is missing`);return this._loader._loadAnimationChannelFromTargetInfoAsync(e,n,o,s,{object:t.object,info:t.info.interpolation},r)}catch(e){return t.Logger.Warn(`${l}/pointer: Invalid pointer (${u}) skipped`),null}}},Di=!1;function Gi(){Di||(Di=!0,no(Bi),to(Bi,!0,e=>new ki(e)))}function Vi(e,n,o,s){return t.Color3.FromArray(n,o).scale(s)}function Hi(e,t,n,o){return t[n]*o}function Ki(e,t,n,o){return-t[n]*o}function Ui(e,t,n,o){return t[n+1]*o}function $i(e,t,n,o){return t[n]*o*2}function Wi(e){return{scale:[new ji(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.uScale`,Hi,()=>2),new ji(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.vScale`,Ui,()=>2)],offset:[new ji(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,Hi,()=>2),new ji(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,Ui,()=>2)],rotation:[new ji(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.wAng`,Ki,()=>1)]}}class zi extends wo{buildAnimations(e,t,n,o){return[{babylonAnimatable:e._babylonCamera,babylonAnimation:this._buildAnimation(t,n,o)}]}}class ji extends wo{buildAnimations(e,t,n,o){const s=[];for(const r in e._data)s.push({babylonAnimatable:e._data[r].babylonMaterial,babylonAnimation:this._buildAnimation(t,n,o)});return s}}class qi extends wo{buildAnimations(e,t,n,o){return[{babylonAnimatable:e._babylonLight,babylonAnimation:this._buildAnimation(t,n,o)}]}}ho("/cameras/{}/orthographic/xmag",[new zi(t.Animation.ANIMATIONTYPE_FLOAT,"orthoLeft",Ki,()=>1),new zi(t.Animation.ANIMATIONTYPE_FLOAT,"orthoRight",Ui,()=>1)]),ho("/cameras/{}/orthographic/ymag",[new zi(t.Animation.ANIMATIONTYPE_FLOAT,"orthoBottom",Ki,()=>1),new zi(t.Animation.ANIMATIONTYPE_FLOAT,"orthoTop",Ui,()=>1)]),ho("/cameras/{}/orthographic/zfar",[new zi(t.Animation.ANIMATIONTYPE_FLOAT,"maxZ",Hi,()=>1)]),ho("/cameras/{}/orthographic/znear",[new zi(t.Animation.ANIMATIONTYPE_FLOAT,"minZ",Hi,()=>1)]),ho("/cameras/{}/perspective/yfov",[new zi(t.Animation.ANIMATIONTYPE_FLOAT,"fov",Hi,()=>1)]),ho("/cameras/{}/perspective/zfar",[new zi(t.Animation.ANIMATIONTYPE_FLOAT,"maxZ",Hi,()=>1)]),ho("/cameras/{}/perspective/znear",[new zi(t.Animation.ANIMATIONTYPE_FLOAT,"minZ",Hi,()=>1)]),ho("/materials/{}/pbrMetallicRoughness/baseColorFactor",[new ji(t.Animation.ANIMATIONTYPE_COLOR3,"albedoColor",Vi,()=>4),new ji(t.Animation.ANIMATIONTYPE_FLOAT,"alpha",function(e,t,n,o){return t[n+3]*o},()=>4)]),ho("/materials/{}/pbrMetallicRoughness/metallicFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"metallic",Hi,()=>1)]),ho("/materials/{}/pbrMetallicRoughness/metallicFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"roughness",Hi,()=>1)]);const Xi=Wi("albedoTexture");ho("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/scale",Xi.scale),ho("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/offset",Xi.offset),ho("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/rotation",Xi.rotation);const Yi=Wi("metallicTexture");ho("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/scale",Yi.scale),ho("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/offset",Yi.offset),ho("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/rotation",Yi.rotation),ho("/materials/{}/emissiveFactor",[new ji(t.Animation.ANIMATIONTYPE_COLOR3,"emissiveColor",Vi,()=>3)]);const Qi=Wi("bumpTexture");ho("/materials/{}/normalTexture/scale",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"bumpTexture.level",Hi,()=>1)]),ho("/materials/{}/normalTexture/extensions/KHR_texture_transform/scale",Qi.scale),ho("/materials/{}/normalTexture/extensions/KHR_texture_transform/offset",Qi.offset),ho("/materials/{}/normalTexture/extensions/KHR_texture_transform/rotation",Qi.rotation),ho("/materials/{}/occlusionTexture/strength",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",Hi,()=>1)]);const Zi=Wi("ambientTexture");ho("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/scale",Zi.scale),ho("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/offset",Zi.offset),ho("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/rotation",Zi.rotation);const Ji=Wi("emissiveTexture");ho("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/scale",Ji.scale),ho("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/offset",Ji.offset),ho("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/rotation",Ji.rotation),ho("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyStrength",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyRotation",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"anisotropy.angle",Hi,()=>1)]);const ea=Wi("anisotropy.texture");ho("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/scale",ea.scale),ho("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/offset",ea.offset),ho("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/rotation",ea.rotation),ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",Hi,()=>1)]);const ta=Wi("clearCoat.texture");ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/scale",ta.scale),ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/offset",ta.offset),ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/rotation",ta.rotation);const na=Wi("clearCoat.bumpTexture");ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/scale",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/scale",na.scale),ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/offset",na.offset),ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/rotation",na.rotation);const oa=Wi("clearCoat.textureRoughness");ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/scale",oa.scale),ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/offset",oa.offset),ho("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/rotation",oa.rotation),ho("/materials/{}/extensions/KHR_materials_dispersion/dispersionFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_emissive_strength/emissiveStrength",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"emissiveIntensity",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_ior/ior",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"indexOfRefraction",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.intensity",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceIor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMinimum",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMaximum",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",Hi,()=>1)]);const sa=Wi("iridescence.texture");ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/scale",sa.scale),ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/offset",sa.offset),ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/rotation",sa.rotation);const ra=Wi("iridescence.thicknessTexture");ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/scale",ra.scale),ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/offset",ra.offset),ho("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/rotation",ra.rotation),ho("/materials/{}/extensions/KHR_materials_sheen/sheenColorFactor",[new ji(t.Animation.ANIMATIONTYPE_COLOR3,"sheen.color",Vi,()=>3)]),ho("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"sheen.roughness",Hi,()=>1)]);const ia=Wi("sheen.texture");ho("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/scale",ia.scale),ho("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/offset",ia.offset),ho("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/rotation",ia.rotation);const aa=Wi("sheen.textureRoughness");ho("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/scale",aa.scale),ho("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/offset",aa.offset),ho("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/rotation",aa.rotation),ho("/materials/{}/extensions/KHR_materials_specular/specularFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"metallicF0Factor",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_specular/specularColorFactor",[new ji(t.Animation.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",Vi,()=>3)]);const la=Wi("metallicReflectanceTexture");ho("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/scale",la.scale),ho("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/offset",la.offset),ho("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/rotation",la.rotation);const ua=Wi("reflectanceTexture");ho("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/scale",ua.scale),ho("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/offset",ua.offset),ho("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/rotation",ua.rotation),ho("/materials/{}/extensions/KHR_materials_transmission/transmissionFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",Hi,()=>1)]);const ca=Wi("subSurface.refractionIntensityTexture");ho("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/scale",ca.scale),ho("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/offset",ca.offset),ho("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/rotation",ca.rotation),ho("/materials/{}/extensions/KHR_materials_volume/attenuationColor",[new ji(t.Animation.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",Vi,()=>3)]),ho("/materials/{}/extensions/KHR_materials_volume/attenuationDistance",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",Hi,()=>1)]),ho("/materials/{}/extensions/KHR_materials_volume/thicknessFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",Hi,()=>1)]);const da=Wi("subSurface.thicknessTexture");ho("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/scale",da.scale),ho("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/offset",da.offset),ho("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/rotation",da.rotation),ho("/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionFactor",[new ji(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.translucencyIntensity",Hi,()=>1)]);const ha=Wi("subSurface.translucencyIntensityTexture");ho("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/scale",ha.scale),ho("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/offset",ha.offset),ho("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/rotation",ha.rotation),ho("/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorFactor",[new ji(t.Animation.ANIMATIONTYPE_COLOR3,"subSurface.translucencyColor",Vi,()=>3)]);const ma=Wi("subSurface.translucencyColorTexture");ho("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/scale",ma.scale),ho("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/offset",ma.offset),ho("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/rotation",ma.rotation),ho("/extensions/KHR_lights_punctual/lights/{}/color",[new qi(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",Vi,()=>3)]),ho("/extensions/KHR_lights_punctual/lights/{}/intensity",[new qi(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",Hi,()=>1)]),ho("/extensions/KHR_lights_punctual/lights/{}/range",[new qi(t.Animation.ANIMATIONTYPE_FLOAT,"range",Hi,()=>1)]),ho("/extensions/KHR_lights_punctual/lights/{}/spot/innerConeAngle",[new qi(t.Animation.ANIMATIONTYPE_FLOAT,"innerAngle",$i,()=>1)]),ho("/extensions/KHR_lights_punctual/lights/{}/spot/outerConeAngle",[new qi(t.Animation.ANIMATIONTYPE_FLOAT,"angle",$i,()=>1)]),ho("/extensions/EXT_lights_area/lights/{}/color",[new qi(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",Vi,()=>3)]),ho("/extensions/EXT_lights_area/lights/{}/intensity",[new qi(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",Hi,()=>1)]),ho("/extensions/EXT_lights_area/lights/{}/size",[new qi(t.Animation.ANIMATIONTYPE_FLOAT,"radius",Hi,()=>1)]),ho("/extensions/EXT_lights_area/lights/{}/rect/aspect",[new qi(t.Animation.ANIMATIONTYPE_FLOAT,"radius",Hi,()=>1)]),ho("/nodes/{}/extensions/EXT_lights_ies/color",[new qi(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",Vi,()=>3)]),ho("/nodes/{}/extensions/EXT_lights_ies/multiplier",[new qi(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",Hi,()=>1)]),ho("/nodes/{}/extensions/KHR_node_visibility/visible",[new class extends wo{buildAnimations(e,t,n,o){return e._primitiveBabylonMeshes?e._primitiveBabylonMeshes.map(e=>({babylonAnimatable:e,babylonAnimation:this._buildAnimation(t,n,o)})):[]}}(t.Animation.ANIMATIONTYPE_FLOAT,"isVisible",Hi,()=>1)]),Gi();var fa={__proto__:null,KHR_animation_pointer:ki,RegisterKHR_animation_pointer:Gi};const pa="MSFT_audio_emitter";let _a=class{constructor(e){this.name=pa,this._loader=e,this.enabled=this._loader.isExtensionUsed(pa)}dispose(){this._loader=null,this._clips=null,this._emitters=null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._clips=t.clips,this._emitters=t.emitters,_o.Assign(this._clips),_o.Assign(this._emitters)}}loadSceneAsync(e,t){return yo.LoadExtensionAsync(e,t,this.name,(n,o)=>b(this,void 0,void 0,function*(){const s=new Array;s.push(this._loader.loadSceneAsync(e,t));for(const e of o.emitters){const t=_o.Get(`${n}/emitters`,this._emitters,e);if(null!=t.refDistance||null!=t.maxDistance||null!=t.rolloffFactor||null!=t.distanceModel||null!=t.innerAngle||null!=t.outerAngle)throw new Error(`${n}: Direction or Distance properties are not allowed on emitters attached to a scene`);s.push(this._loadEmitterAsync(`${n}/emitters/${t.index}`,t))}yield Promise.all(s)}))}loadNodeAsync(e,n,o){return yo.LoadExtensionAsync(e,n,this.name,(e,s)=>b(this,void 0,void 0,function*(){const r=new Array,i=yield this._loader.loadNodeAsync(e,n,n=>{for(const o of s.emitters){const s=_o.Get(`${e}/emitters`,this._emitters,o);r.push(this._loadEmitterAsync(`${e}/emitters/${s.index}`,s).then(()=>{for(const e of s._babylonSounds)e.attachToMesh(n),null==s.innerAngle&&null==s.outerAngle||(e.setLocalDirectionToMesh(t.Vector3.Forward()),e.setDirectionalCone(2*t.Tools.ToDegrees(null==s.innerAngle?Math.PI:s.innerAngle),2*t.Tools.ToDegrees(null==s.outerAngle?Math.PI:s.outerAngle),0))}))}o(n)});return yield Promise.all(r),i}))}loadAnimationAsync(e,t){return yo.LoadExtensionAsync(e,t,this.name,(n,o)=>b(this,void 0,void 0,function*(){const s=yield this._loader.loadAnimationAsync(e,t),r=new Array;_o.Assign(o.events);for(const i of o.events)r.push(this._loadAnimationEventAsync(`${n}/events/${i.index}`,e,t,i,s));return yield Promise.all(r),s}))}_loadClipAsync(e,n){if(n._objectURL)return n._objectURL;let o;if(n.uri)o=this._loader.loadUriAsync(e,n,n.uri);else{const t=_o.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,n.bufferView);o=this._loader.loadBufferViewAsync(`/bufferViews/${t.index}`,t)}return n._objectURL=o.then(e=>{const o=t.GetBlobBufferSource(e);return URL.createObjectURL(new Blob([o],{type:n.mimeType}))}),n._objectURL}_loadEmitterAsync(e,n){if(n._babylonSounds=n._babylonSounds||[],!n._babylonData){const e=new Array,o=n.name||`emitter${n.index}`,s={loop:!1,autoplay:!1,volume:null==n.volume?1:n.volume};for(let r=0;r<n.clips.length;r++){const i=`/extensions/${this.name}/clips`,a=_o.Get(i,this._clips,n.clips[r].clip);e.push(this._loadClipAsync(`${i}/${n.clips[r].clip}`,a).then(e=>{const i=n._babylonSounds[r]=new t.Sound(o,e,this._loader.babylonScene,null,s);i.refDistance=n.refDistance||1,i.maxDistance=n.maxDistance||256,i.rolloffFactor=n.rolloffFactor||1,i.distanceModel=n.distanceModel||"exponential"}))}const r=Promise.all(e).then(()=>{const e=n.clips.map(e=>e.weight||1),o=new t.WeightedSound(n.loop||!1,n._babylonSounds,e);n.innerAngle&&(o.directionalConeInnerAngle=2*t.Tools.ToDegrees(n.innerAngle)),n.outerAngle&&(o.directionalConeOuterAngle=2*t.Tools.ToDegrees(n.outerAngle)),n.volume&&(o.volume=n.volume),n._babylonData.sound=o});n._babylonData={loaded:r}}return n._babylonData.loaded}_getEventAction(e,t,n,o,s){switch(n){case"play":return e=>{const n=(s||0)+(e-o);t.play(n)};case"stop":return()=>{t.stop()};case"pause":return()=>{t.pause()};default:throw new Error(`${e}: Unsupported action ${n}`)}}_loadAnimationEventAsync(e,n,o,s,r){if(0==r.targetedAnimations.length)return Promise.resolve();const i=r.targetedAnimations[0],a=s.emitter,l=_o.Get(`/extensions/${this.name}/emitters`,this._emitters,a);return this._loadEmitterAsync(e,l).then(()=>{const n=l._babylonData.sound;if(n){const o=new t.AnimationEvent(s.time,this._getEventAction(e,n,s.action,s.time,s.startOffset));i.animation.addEvent(o),r.onAnimationGroupEndObservable.add(()=>{n.stop()}),r.onAnimationGroupPauseObservable.add(()=>{n.pause()})}})}},ga=!1;function ya(){ga||(ga=!0,no(pa),to(pa,!0,e=>new _a(e)))}ya();var va={__proto__:null,MSFT_audio_emitter:_a,RegisterMSFT_audio_emitter:ya};const ba="MSFT_lod";let xa=class{constructor(e){var n,o;this.name=ba,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new t.Observable,this.onMaterialLODsLoadedObservable=new t.Observable,this._bufferLODs=new Array,this._nodeIndexLOD=null,this._nodeSignalLODs=new Array,this._nodePromiseLODs=new Array,this._nodeBufferLODs=new Array,this._materialIndexLOD=null,this._materialSignalLODs=new Array,this._materialPromiseLODs=new Array,this._materialBufferLODs=new Array,this._loader=e,this.maxLODsToLoad=null!==(o=null===(n=this._loader.parent.extensionOptions[ba])||void 0===n?void 0:n.maxLODsToLoad)&&void 0!==o?o:this.maxLODsToLoad,this.enabled=this._loader.isExtensionUsed(ba)}dispose(){this._loader=null,this._nodeIndexLOD=null,this._nodeSignalLODs.length=0,this._nodePromiseLODs.length=0,this._nodeBufferLODs.length=0,this._materialIndexLOD=null,this._materialSignalLODs.length=0,this._materialPromiseLODs.length=0,this._materialBufferLODs.length=0,this.onMaterialLODsLoadedObservable.clear(),this.onNodeLODsLoadedObservable.clear()}onReady(){for(let e=0;e<this._nodePromiseLODs.length;e++){const t=Promise.all(this._nodePromiseLODs[e]).then(()=>{0!==e&&(this._loader.endPerformanceCounter(`Node LOD ${e}`),this._loader.log(`Loaded node LOD ${e}`)),this.onNodeLODsLoadedObservable.notifyObservers(e),e!==this._nodePromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Node LOD ${e+1}`),this._loadBufferLOD(this._nodeBufferLODs,e+1),this._nodeSignalLODs[e]&&this._nodeSignalLODs[e].resolve())});this._loader._completePromises.push(t)}for(let e=0;e<this._materialPromiseLODs.length;e++){const t=Promise.all(this._materialPromiseLODs[e]).then(()=>{0!==e&&(this._loader.endPerformanceCounter(`Material LOD ${e}`),this._loader.log(`Loaded material LOD ${e}`)),this.onMaterialLODsLoadedObservable.notifyObservers(e),e!==this._materialPromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Material LOD ${e+1}`),this._loadBufferLOD(this._materialBufferLODs,e+1),this._materialSignalLODs[e]&&this._materialSignalLODs[e].resolve())});this._loader._completePromises.push(t)}}loadSceneAsync(e,t){const n=this._loader.loadSceneAsync(e,t);return this._loadBufferLOD(this._bufferLODs,0),n}loadNodeAsync(e,n,o){return yo.LoadExtensionAsync(e,n,this.name,(e,s)=>b(this,void 0,void 0,function*(){let r;const i=this._getLODs(e,n,this._loader.gltf.nodes,s.ids);this._loader.logOpen(`${e}`);for(let e=0;e<i.length;e++){const n=i[e];0!==e&&(this._nodeIndexLOD=e,this._nodeSignalLODs[e]=this._nodeSignalLODs[e]||new t.Deferred);const s=e=>{o(e),e.setEnabled(!1)},a=this._loader.loadNodeAsync(`/nodes/${n.index}`,n,s).then(t=>{if(0!==e){const t=i[e-1];t._babylonTransformNode&&(this._disposeTransformNode(t._babylonTransformNode),delete t._babylonTransformNode)}return t.setEnabled(!0),t});this._nodePromiseLODs[e]=this._nodePromiseLODs[e]||[],0===e?r=a:(this._nodeIndexLOD=null,this._nodePromiseLODs[e].push(a))}return this._loader.logClose(),yield r}))}_loadMaterialAsync(e,t,n,o,s){return this._nodeIndexLOD?null:yo.LoadExtensionAsync(e,t,this.name,(e,r)=>b(this,void 0,void 0,function*(){let i;const a=this._getLODs(e,t,this._loader.gltf.materials,r.ids);this._loader.logOpen(`${e}`);for(let e=0;e<a.length;e++){const t=a[e];0!==e&&(this._materialIndexLOD=e);const r=this._loader._loadMaterialAsync(`/materials/${t.index}`,t,n,o,t=>{0===e&&s(t)}).then(t=>{if(0!==e){s(t);const n=a[e-1]._data;n[o]&&(this._disposeMaterials([n[o].babylonMaterial]),delete n[o])}return t});this._materialPromiseLODs[e]=this._materialPromiseLODs[e]||[],0===e?i=r:(this._materialIndexLOD=null,this._materialPromiseLODs[e].push(r))}return this._loader.logClose(),yield i}))}_loadUriAsync(e,n,o){if(null!==this._nodeIndexLOD){this._loader.log("deferred");const s=this._nodeIndexLOD-1;return this._nodeSignalLODs[s]=this._nodeSignalLODs[s]||new t.Deferred,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then(()=>b(this,void 0,void 0,function*(){return yield this._loader.loadUriAsync(e,n,o)}))}if(null!==this._materialIndexLOD){this._loader.log("deferred");const s=this._materialIndexLOD-1;return this._materialSignalLODs[s]=this._materialSignalLODs[s]||new t.Deferred,this._materialSignalLODs[s].promise.then(()=>b(this,void 0,void 0,function*(){return yield this._loader.loadUriAsync(e,n,o)}))}return null}loadBufferAsync(e,n,o,s){if(this._loader.parent.useRangeRequests&&!n.uri){if(!this._loader.bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);const n=(e,n)=>b(this,void 0,void 0,function*(){const r=o,i=r+s-1;let a=e[n];return a?(a.start=Math.min(a.start,r),a.end=Math.max(a.end,i)):(a={start:r,end:i,loaded:new t.Deferred},e[n]=a),yield a.loaded.promise.then(e=>new Uint8Array(e.buffer,e.byteOffset+o-a.start,s))});return this._loader.log("deferred"),null!==this._nodeIndexLOD?n(this._nodeBufferLODs,this._nodeIndexLOD):null!==this._materialIndexLOD?n(this._materialBufferLODs,this._materialIndexLOD):n(this._bufferLODs,0)}return null}_loadBufferLOD(e,t){const n=e[t];n&&(this._loader.log(`Loading buffer range [${n.start}-${n.end}]`),this._loader.bin.readAsync(n.start,n.end-n.start+1).then(e=>{n.loaded.resolve(e)},e=>{n.loaded.reject(e)}))}_getLODs(e,t,n,o){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const s=[];for(let t=o.length-1;t>=0;t--)if(s.push(_o.Get(`${e}/ids/${o[t]}`,n,o[t])),s.length===this.maxLODsToLoad)return s;return s.push(t),s}_disposeTransformNode(e){const t=[],n=e.material;n&&t.push(n);for(const n of e.getChildMeshes())n.material&&t.push(n.material);e.dispose();const o=t.filter(e=>this._loader.babylonScene.meshes.every(t=>t.material!=e));this._disposeMaterials(o)}_disposeMaterials(e){const t={};for(const n of e){for(const e of n.getActiveTextures())t[e.uniqueId]=e;n.dispose()}for(const e in t)for(const n of this._loader.babylonScene.materials)n.hasTexture(t[e])&&delete t[e];for(const e in t)t[e].dispose()}},Ta=!1;function Aa(){Ta||(Ta=!0,no(ba),to(ba,!0,e=>new xa(e)))}Aa();var Ma={__proto__:null,MSFT_lod:xa,RegisterMSFT_lod:Aa};const wa="MSFT_minecraftMesh";let Ca=class{constructor(e){this.name=wa,this._loader=e,this.enabled=this._loader.isExtensionUsed(wa)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtraAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){if(s){if(!this._loader._pbrMaterialImpls.get("pbr"))throw new Error(`${o}: Material type not supported`);const s=this._loader.loadMaterialPropertiesAsync(e,t,n);return n.needAlphaBlending()&&(n.forceDepthWrite=!0,n.separateCullingPass=!0),n.backFaceCulling=n.forceDepthWrite,n.twoSidedLighting=!0,yield s}}))}},Ra=!1;function Oa(){Ra||(Ra=!0,no(wa),to(wa,!0,e=>new Ca(e)))}Oa();var Sa={__proto__:null,MSFT_minecraftMesh:Ca,RegisterMSFT_minecraftMesh:Oa};const Fa="MSFT_sRGBFactors";let Ea=class{constructor(e){this.name=Fa,this._loader=e,this.enabled=this._loader.isExtensionUsed(Fa)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yo.LoadExtraAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){if(s){const o=this._loader._getOrCreateMaterialAdapter(n),s=this._loader.loadMaterialPropertiesAsync(e,t,n),r=n.getScene().getEngine().useExactSrgbConversions;return o.baseColorTexture||o.baseColor.toLinearSpaceToRef(o.baseColor,r),o.specularColorTexture||o.specularColor.toLinearSpaceToRef(o.specularColor,r),yield s}}))}},La=!1;function Ia(){La||(La=!0,no(Fa),to(Fa,!0,e=>new Ea(e)))}Ia();var Na={__proto__:null,MSFT_sRGBFactors:Ea,RegisterMSFT_sRGBFactors:Ia};function Pa(e){const[t,n]=e.split(":");return Ba({op:t,extension:n})}function Ba(e,n=!0){var o;const s=e.extension?null===(o=Da[e.extension])||void 0===o?void 0:o[e.op]:Ga[e.op];if(!s&&(t.Logger.Warn(`No mapping found for operation ${e.op} and extension ${e.extension||"KHR_interactivity"}`),n)){const t={},n={flows:{}};if(e.inputValueSockets){t.values={};for(const n in e.inputValueSockets)t.values[n]={name:n}}return e.outputValueSockets&&(n.values={},Object.keys(e.outputValueSockets).forEach(e=>{n.values[e]={name:e}})),{blocks:[],inputs:t,outputs:n}}return s}function ka(e,t,n){Da[t]||(Da[t]={}),Da[t][e]=n}const Da={BABYLON:{"flow/log":{blocks:["FlowGraphConsoleLogBlock"],inputs:{values:{message:{name:"message"}}}}}},Ga={"event/onStart":{blocks:["FlowGraphSceneReadyEventBlock"],outputs:{flows:{out:{name:"done"}}}},"event/onTick":{blocks:["FlowGraphSceneTickEventBlock"],inputs:{},outputs:{values:{timeSinceLastTick:{name:"deltaTime",gltfType:"number"}},flows:{out:{name:"done"}}}},"event/send":{blocks:["FlowGraphSendCustomEventBlock"],extraProcessor(e,t,n,o,s){var r;if("event/send"!==t.op||!e.configuration||1!==Object.keys(e.configuration).length)throw new Error("Receive event should have a single configuration object, the event itself");const i=null===(r=e.configuration.event.value)||void 0===r?void 0:r[0];if("number"!=typeof i)throw new Error("Event id should be a number");const a=o.arrays.events[i],l=s[0];return l.config||(l.config={}),l.config.eventId=a.eventId,l.config.eventData=a.eventData,s}},"event/receive":{blocks:["FlowGraphReceiveCustomEventBlock"],outputs:{flows:{out:{name:"done"}}},validation(e,n){var o,s;if(!e.configuration)return t.Logger.Error("Receive event should have a configuration object"),{valid:!1,error:"Receive event should have a configuration object"};const r=e.configuration.event;if(!r)return t.Logger.Error("Receive event should have a single configuration object, the event itself"),{valid:!1,error:"Receive event should have a single configuration object, the event itself"};const i=null===(o=r.value)||void 0===o?void 0:o[0];return"number"!=typeof i?(t.Logger.Error("Event id should be a number"),{valid:!1,error:"Event id should be a number"}):(null===(s=n.events)||void 0===s?void 0:s[i])?{valid:!0}:(t.Logger.Error(`Event with id ${i} not found`),{valid:!1,error:`Event with id ${i} not found`})},extraProcessor(e,t,n,o,s){var r;if("event/receive"!==t.op||!e.configuration||1!==Object.keys(e.configuration).length)throw new Error("Receive event should have a single configuration object, the event itself");const i=null===(r=e.configuration.event.value)||void 0===r?void 0:r[0];if("number"!=typeof i)throw new Error("Event id should be a number");const a=o.arrays.events[i],l=s[0];return l.config||(l.config={}),l.config.eventId=a.eventId,l.config.eventData=a.eventData,s}},"math/E":Va("FlowGraphEBlock"),"math/Pi":Va("FlowGraphPIBlock"),"math/Inf":Va("FlowGraphInfBlock"),"math/NaN":Va("FlowGraphNaNBlock"),"math/abs":Va("FlowGraphAbsBlock"),"math/sign":Va("FlowGraphSignBlock"),"math/trunc":Va("FlowGraphTruncBlock"),"math/floor":Va("FlowGraphFloorBlock"),"math/ceil":Va("FlowGraphCeilBlock"),"math/round":{blocks:["FlowGraphRoundBlock"],configuration:{},inputs:{values:{a:{name:"a"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s){var r;return(r=s[0]).config||(r.config={}),s[0].config.roundHalfAwayFromZero=!0,s}},"math/fract":Va("FlowGraphFractBlock"),"math/neg":Va("FlowGraphNegationBlock"),"math/add":Va("FlowGraphAddBlock",["a","b"],!0),"math/sub":Va("FlowGraphSubtractBlock",["a","b"],!0),"math/mul":{blocks:["FlowGraphMultiplyBlock"],extraProcessor(e,t,n,o,s){var r;(r=s[0]).config||(r.config={}),s[0].config.useMatrixPerComponent=!0,s[0].config.preventIntegerFloatArithmetic=!0;let i=-1;return Object.keys(e.values||{}).find(t=>{var n;return void 0!==(null===(n=e.values)||void 0===n?void 0:n[t].type)&&(i=e.values[t].type,!0)}),-1!==i&&(s[0].config.type=o.arrays.types[i].flowGraphType),s},validation:e=>e.values?Ha(e):{valid:!0}},"math/div":Va("FlowGraphDivideBlock",["a","b"],!0),"math/rem":Va("FlowGraphModuloBlock",["a","b"]),"math/min":Va("FlowGraphMinBlock",["a","b"]),"math/max":Va("FlowGraphMaxBlock",["a","b"]),"math/clamp":Va("FlowGraphClampBlock",["a","b","c"]),"math/saturate":Va("FlowGraphSaturateBlock"),"math/mix":Va("FlowGraphMathInterpolationBlock",["a","b","c"]),"math/eq":Va("FlowGraphEqualityBlock",["a","b"]),"math/lt":Va("FlowGraphLessThanBlock",["a","b"]),"math/le":Va("FlowGraphLessThanOrEqualBlock",["a","b"]),"math/gt":Va("FlowGraphGreaterThanBlock",["a","b"]),"math/ge":Va("FlowGraphGreaterThanOrEqualBlock",["a","b"]),"math/isNaN":Va("FlowGraphIsNaNBlock"),"math/isInf":Va("FlowGraphIsInfBlock"),"math/select":{blocks:["FlowGraphConditionalBlock"],inputs:{values:{condition:{name:"condition"},a:{name:"onTrue"},b:{name:"onFalse"}}},outputs:{values:{value:{name:"output"}}}},"math/random":{blocks:["FlowGraphRandomBlock"],outputs:{values:{value:{name:"value"}}}},"math/sin":Va("FlowGraphSinBlock"),"math/cos":Va("FlowGraphCosBlock"),"math/tan":Va("FlowGraphTanBlock"),"math/asin":Va("FlowGraphASinBlock"),"math/acos":Va("FlowGraphACosBlock"),"math/atan":Va("FlowGraphATanBlock"),"math/atan2":Va("FlowGraphATan2Block",["a","b"]),"math/sinh":Va("FlowGraphSinhBlock"),"math/cosh":Va("FlowGraphCoshBlock"),"math/tanh":Va("FlowGraphTanhBlock"),"math/asinh":Va("FlowGraphASinhBlock"),"math/acosh":Va("FlowGraphACoshBlock"),"math/atanh":Va("FlowGraphATanhBlock"),"math/exp":Va("FlowGraphExponentialBlock"),"math/log":Va("FlowGraphLogBlock"),"math/log2":Va("FlowGraphLog2Block"),"math/log10":Va("FlowGraphLog10Block"),"math/sqrt":Va("FlowGraphSquareRootBlock"),"math/cbrt":Va("FlowGraphCubeRootBlock"),"math/pow":Va("FlowGraphPowerBlock",["a","b"]),"math/length":Va("FlowGraphLengthBlock"),"math/normalize":Va("FlowGraphNormalizeBlock"),"math/dot":Va("FlowGraphDotBlock",["a","b"]),"math/cross":Va("FlowGraphCrossBlock",["a","b"]),"math/rotate2D":{blocks:["FlowGraphRotate2DBlock"],inputs:{values:{a:{name:"a"},angle:{name:"b"}}},outputs:{values:{value:{name:"value"}}}},"math/rotate3D":{blocks:["FlowGraphRotate3DBlock"],inputs:{values:{a:{name:"a"},rotation:{name:"b"}}},outputs:{values:{value:{name:"value"}}}},"math/transform":{blocks:["FlowGraphTransformVectorBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}}},"math/combine2":{blocks:["FlowGraphCombineVector2Block"],inputs:{values:{a:{name:"input_0",gltfType:"number"},b:{name:"input_1",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}}},"math/combine3":{blocks:["FlowGraphCombineVector3Block"],inputs:{values:{a:{name:"input_0",gltfType:"number"},b:{name:"input_1",gltfType:"number"},c:{name:"input_2",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}}},"math/combine4":{blocks:["FlowGraphCombineVector4Block"],inputs:{values:{a:{name:"input_0",gltfType:"number"},b:{name:"input_1",gltfType:"number"},c:{name:"input_2",gltfType:"number"},d:{name:"input_3",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}}},"math/extract2":{blocks:["FlowGraphExtractVector2Block"],inputs:{values:{a:{name:"input",gltfType:"number"}}},outputs:{values:{0:{name:"output_0"},1:{name:"output_1"}}}},"math/extract3":{blocks:["FlowGraphExtractVector3Block"],inputs:{values:{a:{name:"input",gltfType:"number"}}},outputs:{values:{0:{name:"output_0"},1:{name:"output_1"},2:{name:"output_2"}}}},"math/extract4":{blocks:["FlowGraphExtractVector4Block"],inputs:{values:{a:{name:"input",gltfType:"number"}}},outputs:{values:{0:{name:"output_0"},1:{name:"output_1"},2:{name:"output_2"},3:{name:"output_3"}}}},"math/transpose":Va("FlowGraphTransposeBlock"),"math/determinant":Va("FlowGraphDeterminantBlock"),"math/inverse":Va("FlowGraphInvertMatrixBlock"),"math/matMul":Va("FlowGraphMatrixMultiplicationBlock",["a","b"]),"math/matCompose":{blocks:["FlowGraphMatrixCompose"],inputs:{values:{translation:{name:"position",gltfType:"float3"},rotation:{name:"rotationQuaternion",gltfType:"float4"},scale:{name:"scaling",gltfType:"float3"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s,r){const i=s[0].dataInputs.find(e=>"rotationQuaternion"===e.name);if(!i)throw new Error("Rotation quaternion input not found");return r._connectionValues[i.uniqueId]&&(r._connectionValues[i.uniqueId].type="Quaternion"),s}},"math/matDecompose":{blocks:["FlowGraphMatrixDecompose"],inputs:{values:{a:{name:"input",gltfType:"number"}}},outputs:{values:{translation:{name:"position"},rotation:{name:"rotationQuaternion"},scale:{name:"scaling"}}}},"math/quatConjugate":Va("FlowGraphConjugateBlock",["a"]),"math/quatMul":{blocks:["FlowGraphMultiplyBlock"],inputs:{values:{a:{name:"a",gltfType:"vector4"},b:{name:"b",gltfType:"vector4"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s){var r;return(r=s[0]).config||(r.config={}),s[0].config.type="Quaternion",s}},"math/quatAngleBetween":Va("FlowGraphAngleBetweenBlock",["a","b"]),"math/quatFromAxisAngle":{blocks:["FlowGraphQuaternionFromAxisAngleBlock"],inputs:{values:{axis:{name:"a",gltfType:"float3"},angle:{name:"b",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}}},"math/quatToAxisAngle":Va("FlowGraphAxisAngleFromQuaternionBlock",["a"]),"math/quatFromDirections":Va("FlowGraphQuaternionFromDirectionsBlock",["a","b"]),"math/combine2x2":{blocks:["FlowGraphCombineMatrix2DBlock"],inputs:{values:{a:{name:"input_0",gltfType:"number"},b:{name:"input_1",gltfType:"number"},c:{name:"input_2",gltfType:"number"},d:{name:"input_3",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s){var r;return(r=s[0]).config||(r.config={}),s[0].config.inputIsColumnMajor=!0,s}},"math/extract2x2":{blocks:["FlowGraphExtractMatrix2DBlock"],inputs:{values:{a:{name:"input",gltfType:"float2x2"}}},outputs:{values:{0:{name:"output_0"},1:{name:"output_1"},2:{name:"output_2"},3:{name:"output_3"}}}},"math/combine3x3":{blocks:["FlowGraphCombineMatrix3DBlock"],inputs:{values:{a:{name:"input_0",gltfType:"number"},b:{name:"input_1",gltfType:"number"},c:{name:"input_2",gltfType:"number"},d:{name:"input_3",gltfType:"number"},e:{name:"input_4",gltfType:"number"},f:{name:"input_5",gltfType:"number"},g:{name:"input_6",gltfType:"number"},h:{name:"input_7",gltfType:"number"},i:{name:"input_8",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s){var r;return(r=s[0]).config||(r.config={}),s[0].config.inputIsColumnMajor=!0,s}},"math/extract3x3":{blocks:["FlowGraphExtractMatrix3DBlock"],inputs:{values:{a:{name:"input",gltfType:"float3x3"}}},outputs:{values:{0:{name:"output_0"},1:{name:"output_1"},2:{name:"output_2"},3:{name:"output_3"},4:{name:"output_4"},5:{name:"output_5"},6:{name:"output_6"},7:{name:"output_7"},8:{name:"output_8"}}}},"math/combine4x4":{blocks:["FlowGraphCombineMatrixBlock"],inputs:{values:{a:{name:"input_0",gltfType:"number"},b:{name:"input_1",gltfType:"number"},c:{name:"input_2",gltfType:"number"},d:{name:"input_3",gltfType:"number"},e:{name:"input_4",gltfType:"number"},f:{name:"input_5",gltfType:"number"},g:{name:"input_6",gltfType:"number"},h:{name:"input_7",gltfType:"number"},i:{name:"input_8",gltfType:"number"},j:{name:"input_9",gltfType:"number"},k:{name:"input_10",gltfType:"number"},l:{name:"input_11",gltfType:"number"},m:{name:"input_12",gltfType:"number"},n:{name:"input_13",gltfType:"number"},o:{name:"input_14",gltfType:"number"},p:{name:"input_15",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s){var r;return(r=s[0]).config||(r.config={}),s[0].config.inputIsColumnMajor=!0,s}},"math/extract4x4":{blocks:["FlowGraphExtractMatrixBlock"],configuration:{},inputs:{values:{a:{name:"input",gltfType:"number"}}},outputs:{values:{0:{name:"output_0"},1:{name:"output_1"},2:{name:"output_2"},3:{name:"output_3"},4:{name:"output_4"},5:{name:"output_5"},6:{name:"output_6"},7:{name:"output_7"},8:{name:"output_8"},9:{name:"output_9"},10:{name:"output_10"},11:{name:"output_11"},12:{name:"output_12"},13:{name:"output_13"},14:{name:"output_14"},15:{name:"output_15"}}}},"math/not":{blocks:["FlowGraphBitwiseNotBlock"],inputs:{values:{a:{name:"a"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s,r){var i,a,l;(l=s[0]).config||(l.config={});const u=s[0].dataInputs[0];return s[0].config.valueType=null!==(a=null===(i=r._connectionValues[u.uniqueId])||void 0===i?void 0:i.type)&&void 0!==a?a:"FlowGraphInteger",s}},"math/and":{blocks:["FlowGraphBitwiseAndBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s,r){var i,a,l,u,c;(c=s[0]).config||(c.config={});const d=s[0].dataInputs[0],h=s[0].dataInputs[1];return s[0].config.valueType=null!==(u=null!==(a=null===(i=r._connectionValues[d.uniqueId])||void 0===i?void 0:i.type)&&void 0!==a?a:null===(l=r._connectionValues[h.uniqueId])||void 0===l?void 0:l.type)&&void 0!==u?u:"FlowGraphInteger",s}},"math/or":{blocks:["FlowGraphBitwiseOrBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s,r){var i,a,l,u,c;(c=s[0]).config||(c.config={});const d=s[0].dataInputs[0],h=s[0].dataInputs[1];return s[0].config.valueType=null!==(u=null!==(a=null===(i=r._connectionValues[d.uniqueId])||void 0===i?void 0:i.type)&&void 0!==a?a:null===(l=r._connectionValues[h.uniqueId])||void 0===l?void 0:l.type)&&void 0!==u?u:"FlowGraphInteger",s}},"math/xor":{blocks:["FlowGraphBitwiseXorBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s,r){var i,a,l,u,c;(c=s[0]).config||(c.config={});const d=s[0].dataInputs[0],h=s[0].dataInputs[1];return s[0].config.valueType=null!==(u=null!==(a=null===(i=r._connectionValues[d.uniqueId])||void 0===i?void 0:i.type)&&void 0!==a?a:null===(l=r._connectionValues[h.uniqueId])||void 0===l?void 0:l.type)&&void 0!==u?u:"FlowGraphInteger",s}},"math/asr":Va("FlowGraphBitwiseRightShiftBlock",["a","b"]),"math/lsl":Va("FlowGraphBitwiseLeftShiftBlock",["a","b"]),"math/clz":Va("FlowGraphLeadingZerosBlock"),"math/ctz":Va("FlowGraphTrailingZerosBlock"),"math/popcnt":Va("FlowGraphOneBitsCounterBlock"),"math/rad":Va("FlowGraphDegToRadBlock"),"math/deg":Va("FlowGraphRadToDegBlock"),"type/boolToInt":Va("FlowGraphBooleanToInt"),"type/boolToFloat":Va("FlowGraphBooleanToFloat"),"type/intToBool":Va("FlowGraphIntToBoolean"),"type/intToFloat":Va("FlowGraphIntToFloat"),"type/floatToInt":Va("FlowGraphFloatToInt"),"type/floatToBool":Va("FlowGraphFloatToBoolean"),"flow/sequence":{blocks:["FlowGraphSequenceBlock"],extraProcessor(e,t,n,o,s){const r=s[0];return r.config||(r.config={}),r.config.outputSignalCount=Object.keys(e.flows||[]).length,r.signalOutputs.forEach((e,t)=>{e.name="out_"+t}),s}},"flow/branch":{blocks:["FlowGraphBranchBlock"],outputs:{flows:{true:{name:"onTrue"},false:{name:"onFalse"}}}},"flow/switch":{blocks:["FlowGraphSwitchBlock"],configuration:{cases:{name:"cases",isArray:!0,inOptions:!0,defaultValue:[]}},inputs:{values:{selection:{name:"case"},default:{name:"default"}}},validation(e){var n;const o=null===(n=e.configuration)||void 0===n?void 0:n.cases;if(o&&o.value){if(!o.value.every(e=>"number"==typeof e&&/^-?\d+$/.test(e.toString())))return t.Logger.Warn("Switch cases should be integers. Using empty array instead."),o.value=[],{valid:!0};const e=new Set(o.value);o.value=Array.from(e)}return{valid:!0}},extraProcessor(e,t,n,o,s){if("flow/switch"!==t.op||!e.flows||0===Object.keys(e.flows).length)throw new Error("Switch should have a single configuration object, the cases array");return s[0].signalOutputs.forEach(e=>{"default"!==e.name&&(e.name="out_"+e.name)}),s}},"flow/while":{blocks:["FlowGraphWhileLoopBlock"],outputs:{flows:{loopBody:{name:"executionFlow"}}}},"flow/for":{blocks:["FlowGraphForLoopBlock"],configuration:{initialIndex:{name:"initialIndex",gltfType:"number",inOptions:!0,defaultValue:0}},inputs:{values:{startIndex:{name:"startIndex",gltfType:"number"},endIndex:{name:"endIndex",gltfType:"number"}}},outputs:{values:{index:{name:"index"}},flows:{loopBody:{name:"executionFlow"}}},extraProcessor(e,t,n,o,s){const r=s[0];return r.config||(r.config={}),r.config.incrementIndexWhenLoopDone=!0,s}},"flow/doN":{blocks:["FlowGraphDoNBlock"],configuration:{},inputs:{values:{n:{name:"maxExecutions",gltfType:"number"}}},outputs:{values:{currentCount:{name:"executionCount"}}}},"flow/multiGate":{blocks:["FlowGraphMultiGateBlock"],configuration:{isRandom:{name:"isRandom",gltfType:"boolean",inOptions:!0,defaultValue:!1},isLoop:{name:"isLoop",gltfType:"boolean",inOptions:!0,defaultValue:!1}},extraProcessor(e,t,n,o,s){if("flow/multiGate"!==t.op||!e.flows||0===Object.keys(e.flows).length)throw new Error("MultiGate should have a single configuration object, the number of output flows");const r=s[0];return r.config||(r.config={}),r.config.outputSignalCount=Object.keys(e.flows).length,r.signalOutputs.forEach((e,t)=>{e.name="out_"+t}),s}},"flow/waitAll":{blocks:["FlowGraphWaitAllBlock"],configuration:{inputFlows:{name:"inputSignalCount",gltfType:"number",inOptions:!0,defaultValue:0}},inputs:{flows:{reset:{name:"reset"},"[segment]":{name:"in_$1"}}},validation(e){var t,n,o;return"number"!=typeof(null===(o=null===(n=null===(t=e.configuration)||void 0===t?void 0:t.inputFlows)||void 0===n?void 0:n.value)||void 0===o?void 0:o[0])&&(e.configuration=e.configuration||{inputFlows:{value:[0]}},e.configuration.inputFlows.value=[0]),{valid:!0}}},"flow/throttle":{blocks:["FlowGraphThrottleBlock"],outputs:{flows:{err:{name:"error"}}}},"flow/setDelay":{blocks:["FlowGraphSetDelayBlock"],outputs:{flows:{err:{name:"error"}}}},"flow/cancelDelay":{blocks:["FlowGraphCancelDelayBlock"]},"variable/get":{blocks:["FlowGraphGetVariableBlock"],validation(e){var n,o;return(null===(o=null===(n=e.configuration)||void 0===n?void 0:n.variable)||void 0===o?void 0:o.value)?{valid:!0}:(t.Logger.Error("Variable get block should have a variable configuration"),{valid:!1,error:"Variable get block should have a variable configuration"})},configuration:{variable:{name:"variable",gltfType:"number",flowGraphType:"string",inOptions:!0,isVariable:!0,dataTransformer:(e,t)=>t.getVariableName(e)}}},"variable/set":{blocks:["FlowGraphSetVariableBlock"],configuration:{variables:{name:"variables",gltfType:"number",flowGraphType:"string",inOptions:!0,isArray:!0,dataTransformer:(e,t)=>e.map(e=>t.getVariableName(e))}},extraProcessor:(e,t,n,o,s)=>(s[0].dataInputs.forEach(e=>{e.name=o.getVariableName(+e.name)}),s)},"variable/interpolate":{blocks:["FlowGraphInterpolationBlock","FlowGraphContextBlock","FlowGraphPlayAnimationBlock","FlowGraphBezierCurveEasing","FlowGraphGetVariableBlock"],configuration:{variable:{name:"propertyName",inOptions:!0,isVariable:!0,dataTransformer:(e,t)=>t.getVariableName(e)},useSlerp:{name:"animationType",inOptions:!0,defaultValue:!1,dataTransformer:e=>!0===e?"Quaternion":void 0}},inputs:{values:{value:{name:"value_1"},duration:{name:"duration_1",gltfType:"number"},p1:{name:"controlPoint1",toBlock:"FlowGraphBezierCurveEasing"},p2:{name:"controlPoint2",toBlock:"FlowGraphBezierCurveEasing"}},flows:{in:{name:"in",toBlock:"FlowGraphPlayAnimationBlock"}}},outputs:{flows:{err:{name:"error",toBlock:"FlowGraphPlayAnimationBlock"},out:{name:"out",toBlock:"FlowGraphPlayAnimationBlock"},done:{name:"done",toBlock:"FlowGraphPlayAnimationBlock"}}},interBlockConnectors:[{input:"object",output:"userVariables",inputBlockIndex:2,outputBlockIndex:1,isVariable:!0},{input:"animation",output:"animation",inputBlockIndex:2,outputBlockIndex:0,isVariable:!0},{input:"easingFunction",output:"easingFunction",inputBlockIndex:0,outputBlockIndex:3,isVariable:!0},{input:"value_0",output:"value",inputBlockIndex:0,outputBlockIndex:4,isVariable:!0}],extraProcessor(e,n,o,s,r){var i,a,l,u,c,d;const h=r[0],m=null===(a=null===(i=e.configuration)||void 0===i?void 0:i.variable.value)||void 0===a?void 0:a[0];if("number"!=typeof m)throw t.Logger.Error("Variable index is not defined for variable interpolation block"),new Error("Variable index is not defined for variable interpolation block");const f=s.arrays.staticVariables[m];void 0===(null===(u=null===(l=h.config)||void 0===l?void 0:l.animationType)||void 0===u?void 0:u.value)&&(h.config||(h.config={}),(c=h.config).animationType||(c.animationType={}),h.config.animationType.value=t.getAnimationTypeByFlowGraphType(f.type));const p=r[4];return p.config||(p.config={}),(d=p.config).variable||(d.variable={}),p.config.variable.value=s.getVariableName(m),r}},"pointer/get":{blocks:["FlowGraphGetPropertyBlock","FlowGraphJsonPointerParserBlock"],configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock"}},inputs:{values:{"[segment]":{name:"$1",toBlock:"FlowGraphJsonPointerParserBlock"}}},interBlockConnectors:[{input:"object",output:"object",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"propertyName",output:"propertyName",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"customGetFunction",output:"getFunction",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0}],extraProcessor:(e,t,n,o,s)=>(s.forEach(e=>{"FlowGraphJsonPointerParserBlock"===e.className&&(e.config||(e.config={}),e.config.outputValue=!0)}),s)},"pointer/set":{blocks:["FlowGraphSetPropertyBlock","FlowGraphJsonPointerParserBlock"],configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock"}},inputs:{values:{value:{name:"value"},"[segment]":{name:"$1",toBlock:"FlowGraphJsonPointerParserBlock"}}},outputs:{flows:{err:{name:"error"}}},interBlockConnectors:[{input:"object",output:"object",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"propertyName",output:"propertyName",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"customSetFunction",output:"setFunction",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0}],extraProcessor:(e,t,n,o,s)=>(s.forEach(e=>{"FlowGraphJsonPointerParserBlock"===e.className&&(e.config||(e.config={}),e.config.outputValue=!0)}),s)},"pointer/interpolate":{blocks:["FlowGraphInterpolationBlock","FlowGraphJsonPointerParserBlock","FlowGraphPlayAnimationBlock","FlowGraphBezierCurveEasing"],configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock"}},inputs:{values:{value:{name:"value_1"},"[segment]":{name:"$1",toBlock:"FlowGraphJsonPointerParserBlock"},duration:{name:"duration_1",gltfType:"number"},p1:{name:"controlPoint1",toBlock:"FlowGraphBezierCurveEasing"},p2:{name:"controlPoint2",toBlock:"FlowGraphBezierCurveEasing"}},flows:{in:{name:"in",toBlock:"FlowGraphPlayAnimationBlock"}}},outputs:{flows:{err:{name:"error",toBlock:"FlowGraphPlayAnimationBlock"},out:{name:"out",toBlock:"FlowGraphPlayAnimationBlock"},done:{name:"done",toBlock:"FlowGraphPlayAnimationBlock"}}},interBlockConnectors:[{input:"object",output:"object",inputBlockIndex:2,outputBlockIndex:1,isVariable:!0},{input:"propertyName",output:"propertyName",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"customBuildAnimation",output:"generateAnimationsFunction",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"animation",output:"animation",inputBlockIndex:2,outputBlockIndex:0,isVariable:!0},{input:"easingFunction",output:"easingFunction",inputBlockIndex:0,outputBlockIndex:3,isVariable:!0},{input:"value_0",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0}],extraProcessor:(e,t,n,o,s)=>(s.forEach(t=>{"FlowGraphJsonPointerParserBlock"===t.className?(t.config||(t.config={}),t.config.outputValue=!0):"FlowGraphInterpolationBlock"===t.className&&(t.config||(t.config={}),Object.keys(e.values||[]).forEach(n=>{var s;const r=null===(s=e.values)||void 0===s?void 0:s[n];if("value"===n&&r){const e=r.type;void 0!==e&&(t.config.animationType=o.arrays.types[e].flowGraphType)}}))}),s)},"animation/start":{blocks:["FlowGraphPlayAnimationBlock","FlowGraphArrayIndexBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],inputs:{values:{animation:{name:"index",gltfType:"number",toBlock:"FlowGraphArrayIndexBlock"},speed:{name:"speed",gltfType:"number"},startTime:{name:"from",gltfType:"number",dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]},endTime:{name:"to",gltfType:"number",dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]}}},outputs:{flows:{err:{name:"error"}}},interBlockConnectors:[{input:"animationGroup",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"array",output:"animationGroups",inputBlockIndex:1,outputBlockIndex:2,isVariable:!0}],extraProcessor(e,t,n,o,s,r,i){const a=s[s.length-1];return a.config||(a.config={}),a.config.glTF=i,s}},"animation/stop":{blocks:["FlowGraphStopAnimationBlock","FlowGraphArrayIndexBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],inputs:{values:{animation:{name:"index",gltfType:"number",toBlock:"FlowGraphArrayIndexBlock"}}},outputs:{flows:{err:{name:"error"}}},interBlockConnectors:[{input:"animationGroup",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"array",output:"animationGroups",inputBlockIndex:1,outputBlockIndex:2,isVariable:!0}],extraProcessor(e,t,n,o,s,r,i){const a=s[s.length-1];return a.config||(a.config={}),a.config.glTF=i,s}},"animation/stopAt":{blocks:["FlowGraphStopAnimationBlock","FlowGraphArrayIndexBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{},inputs:{values:{animation:{name:"index",gltfType:"number",toBlock:"FlowGraphArrayIndexBlock"},stopTime:{name:"stopAtFrame",gltfType:"number",dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]}}},outputs:{flows:{err:{name:"error"}}},interBlockConnectors:[{input:"animationGroup",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"array",output:"animationGroups",inputBlockIndex:1,outputBlockIndex:2,isVariable:!0}],extraProcessor(e,t,n,o,s,r,i){const a=s[s.length-1];return a.config||(a.config={}),a.config.glTF=i,s}},"math/switch":{blocks:["FlowGraphDataSwitchBlock"],configuration:{cases:{name:"cases",isArray:!0,inOptions:!0,defaultValue:[]}},inputs:{values:{selection:{name:"case"}}},validation(e){var n;const o=null===(n=e.configuration)||void 0===n?void 0:n.cases;if(o&&o.value){if(!o.value.every(e=>"number"==typeof e&&/^-?\d+$/.test(e.toString())))return t.Logger.Warn("Switch cases should be integers. Using empty array instead."),o.value=[],{valid:!0};const e=new Set(o.value);o.value=Array.from(e)}return{valid:!0}},extraProcessor(e,t,n,o,s){const r=s[0];return r.dataInputs.forEach(e=>{"default"!==e.name&&"case"!==e.name&&(e.name="in_"+e.name)}),r.config||(r.config={}),r.config.treatCasesAsIntegers=!0,s}},"debug/log":{blocks:["FlowGraphConsoleLogBlock"],configuration:{message:{name:"messageTemplate",inOptions:!0}}}};function Va(e,t=["a"],n){return{blocks:[e],inputs:{values:t.reduce((e,t)=>(e[t]={name:t},e),{})},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,o,s,r){var i;if(n){(i=r[0]).config||(i.config={}),r[0].config.preventIntegerFloatArithmetic=!0;let t=-1;Object.keys(e.values||{}).find(n=>{var o;return void 0!==(null===(o=e.values)||void 0===o?void 0:o[n].type)&&(t=e.values[n].type,!0)}),-1!==t&&(r[0].config.type=s.arrays.types[t].flowGraphType)}return r},validation:e=>n?Ha(e):{valid:!0}}}function Ha(e){if(e.values){const t=Object.keys(e.values).map(t=>e.values[t].type).filter(e=>void 0!==e);if(!t.every(e=>e===t[0]))return{valid:!1,error:"All inputs must be of the same type"}}return{valid:!0}}function Ka(){return Object.keys(Ga)}const Ua={float:{length:1,flowGraphType:"number",elementType:"number"},bool:{length:1,flowGraphType:"boolean",elementType:"boolean"},float2:{length:2,flowGraphType:"Vector2",elementType:"number"},float3:{length:3,flowGraphType:"Vector3",elementType:"number"},float4:{length:4,flowGraphType:"Vector4",elementType:"number"},float4x4:{length:16,flowGraphType:"Matrix",elementType:"number"},float2x2:{length:4,flowGraphType:"Matrix2D",elementType:"number"},float3x3:{length:9,flowGraphType:"Matrix3D",elementType:"number"},int:{length:1,flowGraphType:"FlowGraphInteger",elementType:"number"}};class $a{constructor(e,t,n=60){this._interactivityGraph=e,this._gltf=t,this._animationTargetFps=n,this._types=[],this._mappings=[],this._staticVariables=[],this._events=[],this._internalEventsCounter=0,this._nodes=[],this._parseTypes(),this._parseDeclarations(),this._parseVariables(),this._parseEvents(),this._parseNodes()}get arrays(){return{types:this._types,mappings:this._mappings,staticVariables:this._staticVariables,events:this._events,nodes:this._nodes}}_parseTypes(){if(this._interactivityGraph.types)for(const e of this._interactivityGraph.types)this._types.push(Ua[e.signature])}_parseDeclarations(){if(this._interactivityGraph.declarations)for(const e of this._interactivityGraph.declarations){const n=Ba(e);if(!n)throw t.Logger.Error(["No mapping found for declaration",e]),new Error("Error parsing declarations");this._mappings.push({flowGraphMapping:n,fullOperationName:e.extension?e.op+":"+e.extension:e.op})}}_parseVariables(){if(this._interactivityGraph.variables)for(const e of this._interactivityGraph.variables){const t=this._parseVariable(e);this._staticVariables.push(t)}}_parseVariable(e,n){const o=this._types[e.type];if(!o)throw t.Logger.Error(["No type found for variable",e]),new Error("Error parsing variables");if(e.value&&e.value.length!==o.length)throw t.Logger.Error(["Invalid value length for variable",e,o]),new Error("Error parsing variables");const s=e.value||[];if(!s.length)switch(o.flowGraphType){case"boolean":s.push(!1);break;case"FlowGraphInteger":s.push(0);break;case"number":s.push(NaN);break;case"Vector2":s.push(NaN,NaN);break;case"Vector3":s.push(NaN,NaN,NaN);break;case"Vector4":case"Matrix2D":case"Quaternion":s.fill(NaN,0,4);break;case"Matrix":s.fill(NaN,0,16);break;case"Matrix3D":s.fill(NaN,0,9)}return"number"===o.elementType&&"string"==typeof s[0]&&(s[0]=parseFloat(s[0])),{type:o.flowGraphType,value:n?n(s,this):s}}_parseEvents(){if(this._interactivityGraph.events)for(const e of this._interactivityGraph.events){const n={eventId:e.id||"internalEvent_"+this._internalEventsCounter++};e.values&&(n.eventData=Object.keys(e.values).map(n=>{var o;const s=null===(o=e.values)||void 0===o?void 0:o[n];if(!s)throw t.Logger.Error(["No value found for event key",n]),new Error("Error parsing events");const r=this._types[s.type];if(!r)throw t.Logger.Error(["No type found for event value",s]),new Error("Error parsing events");const i=void 0!==s.value?this._parseVariable(s):void 0;return{id:n,type:r.flowGraphType,eventData:!0,value:i}})),this._events.push(n)}}_parseNodes(){var e;if(this._interactivityGraph.nodes)for(const n of this._interactivityGraph.nodes){if("number"!=typeof n.declaration)throw t.Logger.Error(["No declaration found for node",n]),new Error("Error parsing nodes");const o=this._mappings[n.declaration];if(!o)throw t.Logger.Error(["No mapping found for node",n]),new Error("Error parsing nodes");if(o.flowGraphMapping.validation){const t=o.flowGraphMapping.validation(n,this._interactivityGraph,this._gltf);if(!t.valid)throw new Error(`Error validating interactivity node ${null===(e=this._interactivityGraph.declarations)||void 0===e?void 0:e[n.declaration].op} - ${t.error}`)}const s=[];for(const e of o.flowGraphMapping.blocks){const t=this._getEmptyBlock(e,o.fullOperationName);this._parseNodeConfiguration(n,t,o.flowGraphMapping,e),s.push(t)}this._nodes.push({blocks:s,fullOperationName:o.fullOperationName})}}_getEmptyBlock(e,n){return{uniqueId:t.RandomGUID(),className:e,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[],config:{},type:n,metadata:{}}}_parseNodeConfiguration(e,n,o,s){var r;const i=e.configuration;if(i)for(const e in i){const a=i[e];if(!a)throw new Error("Error parsing node configuration");const l=null===(r=o.configuration)||void 0===r?void 0:r[e];if(l&&l.toBlock?l.toBlock===s:0===o.blocks.indexOf(s)){let o=null==l?void 0:l.defaultValue;(null==a?void 0:a.value)&&(o=a.value),(null==l?void 0:l.isArray)||(1!==o.length&&t.Logger.Warn(`Invalid non-array value length: ${o.length}`),o=o[0]),(null==l?void 0:l.dataTransformer)&&(o=l.dataTransformer(o,this)),void 0!==o&&(n.config[(null==l?void 0:l.name)||e]={value:o})}}}_parseNodeConnections(e){var n,o,s,r,i,a,l,u,c,d,h,m,f,p,_,g,y,v,b;for(let x=0;x<this._nodes.length;x++){const T=null===(n=this._interactivityGraph.nodes)||void 0===n?void 0:n[x];if(!T)throw t.Logger.Error(["No node found for interactivity node",this._nodes[x]]),new Error("Error parsing node connections");const A=this._nodes[x],M=this._mappings[T.declaration];if(!M)throw t.Logger.Error(["No mapping found for node",T]),new Error("Error parsing node connections");const w=T.flows||{},C=Object.keys(w).sort();for(const e of C){const n=w[e],c=null===(s=null===(o=M.flowGraphMapping.outputs)||void 0===o?void 0:o.flows)||void 0===s?void 0:s[e],d=(null==c?void 0:c.name)||e,h=this._createNewSocketConnection(d,!0);(c&&c.toBlock&&A.blocks.find(e=>e.className===c.toBlock)||A.blocks[0]).signalOutputs.push(h);const m=n.node,f=this._nodes[m];if(!f)throw t.Logger.Error(["No node found for input node id",m]),new Error("Error parsing node connections");const p=Pa(f.fullOperationName);if(!p)throw t.Logger.Error(["No mapping found for input node",f]),new Error("Error parsing node connections");let _=null===(i=null===(r=p.inputs)||void 0===r?void 0:r.flows)||void 0===i?void 0:i[n.socket||"in"],g=!1;if(!_)for(const e in null===(a=p.inputs)||void 0===a?void 0:a.flows)e.startsWith("[")&&e.endsWith("]")&&(g=!0,_=null===(u=null===(l=p.inputs)||void 0===l?void 0:l.flows)||void 0===u?void 0:u[e]);const y=_?g?_.name.replace("$1",n.socket||""):_.name:n.socket||"in",v=_&&_.toBlock&&f.blocks.find(e=>e.className===_.toBlock)||f.blocks[0];let b=v.signalInputs.find(e=>e.name===y);b||(b=this._createNewSocketConnection(y),v.signalInputs.push(b)),b.connectedPointIds.push(h.uniqueId),h.connectedPointIds.push(b.uniqueId)}const R=T.values||{},O=Object.keys(R);for(const n of O){const o=R[n];let s=null===(d=null===(c=M.flowGraphMapping.inputs)||void 0===c?void 0:c.values)||void 0===d?void 0:d[n],r=!1;if(!s)for(const e in null===(h=M.flowGraphMapping.inputs)||void 0===h?void 0:h.values)e.startsWith("[")&&e.endsWith("]")&&(r=!0,s=null===(f=null===(m=M.flowGraphMapping.inputs)||void 0===m?void 0:m.values)||void 0===f?void 0:f[e]);const i=s?r?s.name.replace("$1",n):s.name:n,a=this._createNewSocketConnection(i);if((s&&s.toBlock&&A.blocks.find(e=>e.className===s.toBlock)||A.blocks[0]).dataInputs.push(a),void 0!==o.value){const t=this._parseVariable(o,s&&s.dataTransformer);e._connectionValues[a.uniqueId]=t}else{if(void 0===o.node)throw t.Logger.Error(["Invalid value for value connection",o]),new Error("Error parsing node connections");{const e=o.node,n=o.socket||"value",s=this._nodes[e];if(!s)throw t.Logger.Error(["No node found for output socket reference",o]),new Error("Error parsing node connections");const r=Pa(s.fullOperationName);if(!r)throw t.Logger.Error(["No mapping found for output socket reference",o]),new Error("Error parsing node connections");let i=null===(_=null===(p=r.outputs)||void 0===p?void 0:p.values)||void 0===_?void 0:_[n],l=!1;if(!i)for(const e in null===(g=r.outputs)||void 0===g?void 0:g.values)e.startsWith("[")&&e.endsWith("]")&&(l=!0,i=null===(v=null===(y=r.outputs)||void 0===y?void 0:y.values)||void 0===v?void 0:v[e]);const u=i?l?i.name.replace("$1",n):null==i?void 0:i.name:n,c=i&&i.toBlock&&s.blocks.find(e=>e.className===i.toBlock)||s.blocks[0];let d=c.dataOutputs.find(e=>e.name===u);d||(d=this._createNewSocketConnection(u,!0),c.dataOutputs.push(d)),a.connectedPointIds.push(d.uniqueId),d.connectedPointIds.push(a.uniqueId)}}}if(M.flowGraphMapping.interBlockConnectors)for(const e of M.flowGraphMapping.interBlockConnectors){const t=e.input,n=e.output,o=e.isVariable;this._connectFlowGraphNodes(t,n,A.blocks[e.inputBlockIndex],A.blocks[e.outputBlockIndex],o)}if(M.flowGraphMapping.extraProcessor){const n=null===(b=this._interactivityGraph.declarations)||void 0===b?void 0:b[T.declaration];if(!n)throw t.Logger.Error(["No declaration found for extra processor",T]),new Error("Error parsing node connections");A.blocks=M.flowGraphMapping.extraProcessor(T,n,M.flowGraphMapping,this,A.blocks,e,this._gltf)}}}_createNewSocketConnection(e,n){return{uniqueId:t.RandomGUID(),name:e,_connectionType:n?1:0,connectedPointIds:[]}}_connectFlowGraphNodes(e,t,n,o,s){const r=s?n.dataInputs:n.signalInputs,i=s?o.dataOutputs:o.signalOutputs,a=r.find(t=>t.name===e)||this._createNewSocketConnection(e),l=i.find(e=>e.name===t)||this._createNewSocketConnection(t,!0);r.find(t=>t.name===e)||r.push(a),i.find(e=>e.name===t)||i.push(l),a.connectedPointIds.push(l.uniqueId),l.connectedPointIds.push(a.uniqueId)}getVariableName(e){return"staticVariable_"+e}serializeToFlowGraph(){const e={uniqueId:t.RandomGUID(),_userVariables:{},_connectionValues:{}};this._parseNodeConnections(e);for(let t=0;t<this._staticVariables.length;t++){const n=this._staticVariables[t];e._userVariables[this.getVariableName(t)]=n}return{rightHanded:!0,allBlocks:this._nodes.reduce((e,t)=>e.concat(t.blocks),[]),executionContexts:[e]}}}const Wa="KHR_interactivity";let za=class{constructor(e){this._loader=e,this.name=Wa,this.enabled=this._loader.isExtensionUsed(Wa),this._pathConverter=uo(this._loader.gltf),e._skipStartAnimationStep=!0;const t=e.babylonScene;t&&ja(t)}dispose(){this._loader=null,delete this._pathConverter}onReady(){return b(this,void 0,void 0,function*(){var e;if(!this._loader.babylonScene||!this._pathConverter)return;const n=this._loader.babylonScene,o=null===(e=this._loader.gltf.extensions)||void 0===e?void 0:e.KHR_interactivity;if(!o)return;const s=new t.FlowGraphCoordinator({scene:n});s.dispatchEventsSynchronously=!1;const r=o.graphs.map(e=>new $a(e,this._loader.gltf,this._loader.parent.targetFps).serializeToFlowGraph());yield Promise.all(r.map(e=>b(this,void 0,void 0,function*(){return yield t.ParseFlowGraphAsync(e,{coordinator:s,pathConverter:this._pathConverter})}))),s.start()})}};function ja(e){mo("/extensions/KHR_interactivity/?/activeCamera/rotation",{get:()=>{if(!e.activeCamera)return new t.Quaternion(NaN,NaN,NaN,NaN);const n=t.Quaternion.FromRotationMatrix(e.activeCamera.getWorldMatrix()).normalize();return e.useRightHandedSystem||(n.w*=-1,n.x*=-1),n},type:"Quaternion",getTarget:()=>e.activeCamera}),mo("/extensions/KHR_interactivity/?/activeCamera/position",{get:()=>{if(!e.activeCamera)return new t.Vector3(NaN,NaN,NaN);const n=e.activeCamera.getWorldMatrix().getTranslation();return e.useRightHandedSystem||(n.x*=-1),n},type:"Vector3",getTarget:()=>e.activeCamera}),mo("/animations/{}/extensions/KHR_interactivity/isPlaying",{get:e=>{var t,n;return null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.isPlaying)&&void 0!==n&&n},type:"boolean",getTarget:e=>e._babylonAnimationGroup}),mo("/animations/{}/extensions/KHR_interactivity/minTime",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.from)&&void 0!==n?n:0)/60},type:"number",getTarget:e=>e._babylonAnimationGroup}),mo("/animations/{}/extensions/KHR_interactivity/maxTime",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.to)&&void 0!==n?n:0)/60},type:"number",getTarget:e=>e._babylonAnimationGroup}),mo("/animations/{}/extensions/KHR_interactivity/playhead",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.getCurrentFrame())&&void 0!==n?n:0)/60},type:"number",getTarget:e=>e._babylonAnimationGroup}),mo("/animations/{}/extensions/KHR_interactivity/virtualPlayhead",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.getCurrentFrame())&&void 0!==n?n:0)/60},type:"number",getTarget:e=>e._babylonAnimationGroup})}let qa=!1;function Xa(){qa||(qa=!0,t.addToBlockFactory(Wa,"FlowGraphGLTFDataProvider",()=>b(this,void 0,void 0,function*(){return(yield Promise.resolve().then(function(){return bl})).FlowGraphGLTFDataProvider})),no(Wa),to(Wa,!0,e=>new za(e)))}Xa();var Ya={__proto__:null,KHR_interactivity:za,RegisterKHR_interactivity:Xa,_AddInteractivityObjectModel:ja};const Qa="KHR_node_visibility";let Za=class{constructor(e){this.name=Qa,this._loader=e,this.enabled=e.isExtensionUsed(Qa)}onReady(){if(!this._loader)return;const e=this._loader.gltf.nodes;if(e)for(const t of e){const e=t._babylonTransformNode;e&&(e.inheritVisibility=!0,t.extensions&&t.extensions.KHR_node_visibility&&!1===t.extensions.KHR_node_visibility.visible&&(e.isVisible=!1))}}dispose(){delete this._loader}},Ja=!1;function el(){Ja||(Ja=!0,mo("/nodes/{}/extensions/KHR_node_visibility/visible",{get:e=>{const t=e._babylonTransformNode;return!t||void 0===t.isVisible||t.isVisible},set:(e,t)=>{var n,o;null===(n=t._primitiveBabylonMeshes)||void 0===n||n.forEach(e=>{e.inheritVisibility=!0}),t._babylonTransformNode&&(t._babylonTransformNode.isVisible=e),null===(o=t._primitiveBabylonMeshes)||void 0===o||o.forEach(t=>{t.isVisible=e})},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"isVisible"],type:"boolean"}),no(Qa),to(Qa,!0,e=>new Za(e)))}el();var tl={__proto__:null,KHR_node_visibility:Za,RegisterKHR_node_visibility:el};const nl="KHR_node_selectability";let ol=class{constructor(e){this.name=nl,this._loader=e,this.enabled=e.isExtensionUsed(nl)}onReady(){return b(this,void 0,void 0,function*(){var e;null===(e=this._loader.gltf.nodes)||void 0===e||e.forEach(e=>{var t,n,o;(null===(t=e.extensions)||void 0===t?void 0:t.KHR_node_selectability)&&!1===(null===(n=e.extensions)||void 0===n?void 0:n.KHR_node_selectability.selectable)&&(null===(o=e._babylonTransformNode)||void 0===o||o.getChildMeshes().forEach(e=>{e.isPickable=!1}))})})}dispose(){this._loader=null}},sl=!1;function rl(){sl||(sl=!0,ka("event/onSelect",nl,{blocks:["FlowGraphMeshPickEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{stopPropagation:{name:"stopPropagation"},nodeIndex:{name:"variable",toBlock:"FlowGraphGetVariableBlock",dataTransformer:e=>"pickedMesh_"+e}},outputs:{values:{selectedNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},controllerIndex:{name:"pointerId"},selectionPoint:{name:"pickedPoint"},selectionRayOrigin:{name:"pickOrigin"}},flows:{out:{name:"done"}}},interBlockConnectors:[{input:"asset",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"array",output:"nodes",inputBlockIndex:2,outputBlockIndex:3,isVariable:!0},{input:"object",output:"pickedMesh",inputBlockIndex:2,outputBlockIndex:0,isVariable:!0}],extraProcessor(e,t,n,o,s,r,i){var a,l,u,c,d,h,m;const f=s[s.length-1];f.config=f.config||{},f.config.glTF=i;const p=null===(u=null===(l=null===(a=e.configuration)||void 0===a?void 0:a.nodeIndex)||void 0===l?void 0:l.value)||void 0===u?void 0:u[0];if(void 0===p||"number"!=typeof p)throw new Error("nodeIndex not found in configuration");const _="pickedMesh_"+p;return s[1].config.variable=_,r._userVariables[_]={className:"Mesh",id:null===(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c[p]._babylonTransformNode)||void 0===d?void 0:d.id,uniqueId:null===(m=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[p]._babylonTransformNode)||void 0===m?void 0:m.uniqueId},s}}),mo("/nodes/{}/extensions/KHR_node_selectability/selectable",{get:e=>{const t=e._babylonTransformNode;return!t||void 0===t.isPickable||t.isPickable},set:(e,t)=>{var n;null===(n=t._primitiveBabylonMeshes)||void 0===n||n.forEach(t=>{t.isPickable=e})},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"isPickable"],type:"boolean"}),no(nl),to(nl,!0,e=>new ol(e)))}rl();var il={__proto__:null,KHR_node_selectability:ol,RegisterKHR_node_selectability:rl};const al="KHR_node_hoverability",ll="targetMeshPointerOver_",ul="targetMeshPointerOut_";let cl=class{constructor(e){this.name=al,this._loader=e,this.enabled=e.isExtensionUsed(al)}onReady(){return b(this,void 0,void 0,function*(){var e;null===(e=this._loader.gltf.nodes)||void 0===e||e.forEach(e=>{var t,n,o;(null===(t=e.extensions)||void 0===t?void 0:t.KHR_node_hoverability)&&!1===(null===(n=e.extensions)||void 0===n?void 0:n.KHR_node_hoverability.hoverable)&&(null===(o=e._babylonTransformNode)||void 0===o||o.getChildMeshes().forEach(e=>{e.pointerOverDisableMeshTesting=!0}))})})}dispose(){this._loader=null}},dl=!1;function hl(){dl||(dl=!0,ka("event/onHoverIn",al,{blocks:["FlowGraphPointerOverEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{stopPropagation:{name:"stopPropagation"},nodeIndex:{name:"variable",toBlock:"FlowGraphGetVariableBlock",dataTransformer:e=>ll+e}},outputs:{values:{hoverNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},controllerIndex:{name:"pointerId"}},flows:{out:{name:"done"}}},interBlockConnectors:[{input:"targetMesh",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"array",output:"nodes",inputBlockIndex:2,outputBlockIndex:3,isVariable:!0},{input:"object",output:"meshUnderPointer",inputBlockIndex:2,outputBlockIndex:0,isVariable:!0}],extraProcessor(e,t,n,o,s,r,i){var a,l,u,c,d,h,m;const f=s[s.length-1];f.config=f.config||{},f.config.glTF=i;const p=null===(u=null===(l=null===(a=e.configuration)||void 0===a?void 0:a.nodeIndex)||void 0===l?void 0:l.value)||void 0===u?void 0:u[0];if(void 0===p||"number"!=typeof p)throw new Error("nodeIndex not found in configuration");const _=ll+p;return s[1].config.variable=_,r._userVariables[_]={className:"Mesh",id:null===(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c[p]._babylonTransformNode)||void 0===d?void 0:d.id,uniqueId:null===(m=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[p]._babylonTransformNode)||void 0===m?void 0:m.uniqueId},s}}),ka("event/onHoverOut",al,{blocks:["FlowGraphPointerOutEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{stopPropagation:{name:"stopPropagation"},nodeIndex:{name:"variable",toBlock:"FlowGraphGetVariableBlock",dataTransformer:e=>ul+e}},outputs:{values:{hoverNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},controllerIndex:{name:"pointerId"}},flows:{out:{name:"done"}}},interBlockConnectors:[{input:"targetMesh",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"array",output:"nodes",inputBlockIndex:2,outputBlockIndex:3,isVariable:!0},{input:"object",output:"meshOutOfPointer",inputBlockIndex:2,outputBlockIndex:0,isVariable:!0}],extraProcessor(e,t,n,o,s,r,i){var a,l,u,c,d,h,m;const f=s[s.length-1];f.config=f.config||{},f.config.glTF=i;const p=null===(u=null===(l=null===(a=e.configuration)||void 0===a?void 0:a.nodeIndex)||void 0===l?void 0:l.value)||void 0===u?void 0:u[0];if(void 0===p||"number"!=typeof p)throw new Error("nodeIndex not found in configuration");const _=ul+p;return s[1].config.variable=_,r._userVariables[_]={className:"Mesh",id:null===(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c[p]._babylonTransformNode)||void 0===d?void 0:d.id,uniqueId:null===(m=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[p]._babylonTransformNode)||void 0===m?void 0:m.uniqueId},s}}),mo("/nodes/{}/extensions/KHR_node_hoverability/hoverable",{get:e=>{const t=e._babylonTransformNode;return!t||void 0===t.pointerOverDisableMeshTesting||t.pointerOverDisableMeshTesting},set:(e,t)=>{var n;null===(n=t._primitiveBabylonMeshes)||void 0===n||n.forEach(t=>{t.pointerOverDisableMeshTesting=!e})},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"pointerOverDisableMeshTesting"],type:"boolean"}),no(al),to(al,!0,e=>new cl(e)))}hl();var ml={__proto__:null,KHR_node_hoverability:cl,RegisterKHR_node_hoverability:hl};const fl="ExtrasAsMetadata";let pl=class{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){const n=e.metadata=e.metadata||{};(n.gltf=n.gltf||{}).extras=t.extras}}constructor(e){this.name=fl,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,n){return this._loader.loadNodeAsync(e,t,e=>{this._assignExtras(e,t),n(e)})}loadCameraAsync(e,t,n){return this._loader.loadCameraAsync(e,t,e=>{this._assignExtras(e,t),n(e)})}createMaterial(e,t,n){const o=this._loader.createMaterial(e,t,n);return this._assignExtras(o,t),o}loadAnimationAsync(e,t){return this._loader.loadAnimationAsync(e,t).then(e=>(this._assignExtras(e,t),e))}},_l=!1;function gl(){_l||(_l=!0,no(fl),to(fl,!1,e=>new pl(e)))}gl();var yl={__proto__:null,ExtrasAsMetadata:pl,RegisterExtrasAsMetadata:gl};class vl extends t.FlowGraphBlock{constructor(e){var n,o;super(e);const s=e.glTF,r=(null===(n=null==s?void 0:s.animations)||void 0===n?void 0:n.map(e=>e._babylonAnimationGroup))||[];this.animationGroups=this.registerDataOutput("animationGroups",t.RichTypeAny,r);const i=(null===(o=null==s?void 0:s.nodes)||void 0===o?void 0:o.map(e=>e._babylonTransformNode))||[];this.nodes=this.registerDataOutput("nodes",t.RichTypeAny,i)}getClassName(){return"FlowGraphGLTFDataProvider"}}var bl={__proto__:null,FlowGraphGLTFDataProvider:vl},xl={__proto__:null,AddObjectAccessorToKey:mo,EXT_lights_area:Os,EXT_lights_ies:rs,EXT_lights_image_based:No,EXT_mesh_gpu_instancing:Go,EXT_meshopt_compression:$o,EXT_texture_avif:es,EXT_texture_webp:Xo,ExtrasAsMetadata:pl,FlowGraphGLTFDataProvider:vl,GetMappingForKey:co,GetPathToObjectConverter:uo,InteractivityGraphToFlowGraphParser:$a,KHR_animation_pointer:ki,KHR_draco_mesh_compression:cs,KHR_gaussian_splatting:ys,KHR_interactivity:za,KHR_lights:As,KHR_materials_anisotropy:sr,KHR_materials_clearcoat:Us,KHR_materials_coat:qs,KHR_materials_diffuse_roughness:hi,KHR_materials_diffuse_transmission:zr,KHR_materials_dispersion:ai,KHR_materials_emissive_strength:ur,KHR_materials_fuzz:vr,KHR_materials_ior:Sr,KHR_materials_iridescence:Js,KHR_materials_pbrSpecularGlossiness:Is,KHR_materials_sheen:fr,KHR_materials_specular:Mr,KHR_materials_transmission:Hr,KHR_materials_unlit:Ds,KHR_materials_variants:Nr,KHR_materials_volume:Qr,KHR_materials_volume_scatter:ni,KHR_mesh_quantization:gi,KHR_node_hoverability:cl,KHR_node_selectability:ol,KHR_node_visibility:Za,KHR_texture_basisu:Ti,KHR_texture_transform:Ri,KHR_xmp_json_ld:Li,MSFT_audio_emitter:_a,MSFT_lod:xa,MSFT_minecraftMesh:Ca,MSFT_sRGBFactors:Ea,RegisterEXT_lights_area:Fs,RegisterEXT_lights_ies:as,RegisterEXT_lights_image_based:Bo,RegisterEXT_mesh_gpu_instancing:Ho,RegisterEXT_meshopt_compression:zo,RegisterEXT_texture_avif:ns,RegisterEXT_texture_webp:Qo,RegisterExtrasAsMetadata:gl,RegisterKHR_animation_pointer:Gi,RegisterKHR_draco_mesh_compression:hs,RegisterKHR_gaussian_splatting:bs,RegisterKHR_interactivity:Xa,RegisterKHR_lights:ws,RegisterKHR_materials_anisotropy:ir,RegisterKHR_materials_clearcoat:Ws,RegisterKHR_materials_coat:Ys,RegisterKHR_materials_diffuse_roughness:fi,RegisterKHR_materials_diffuse_transmission:qr,RegisterKHR_materials_dispersion:ui,RegisterKHR_materials_emissive_strength:dr,RegisterKHR_materials_fuzz:xr,RegisterKHR_materials_ior:Er,RegisterKHR_materials_iridescence:tr,RegisterKHR_materials_pbrSpecularGlossiness:Ps,RegisterKHR_materials_sheen:_r,RegisterKHR_materials_specular:Cr,RegisterKHR_materials_transmission:Ur,RegisterKHR_materials_unlit:Vs,RegisterKHR_materials_variants:Br,RegisterKHR_materials_volume:Jr,RegisterKHR_materials_volume_scatter:si,RegisterKHR_mesh_quantization:vi,RegisterKHR_node_hoverability:hl,RegisterKHR_node_selectability:rl,RegisterKHR_node_visibility:el,RegisterKHR_texture_basisu:Mi,RegisterKHR_texture_transform:Si,RegisterKHR_xmp_json_ld:Ni,RegisterMSFT_audio_emitter:ya,RegisterMSFT_lod:Aa,RegisterMSFT_minecraftMesh:Oa,RegisterMSFT_sRGBFactors:Ia,SetInterpolationForKey:ho,TransmissionHelper:Dr,_AddInteractivityObjectModel:ja,addNewInteractivityFlowGraphMapping:ka,ensureTransmissionHelper:Gr,getAllSupportedNativeNodeTypes:Ka,getMappingForDeclaration:Ba,getMappingForFullOperationName:Pa,gltfTypeToBabylonType:Ua},Tl={__proto__:null,AddObjectAccessorToKey:mo,AnimationPropertyInfo:wo,ArrayItem:_o,EXT_lights_area:Os,EXT_lights_ies:rs,EXT_lights_image_based:No,EXT_mesh_gpu_instancing:Go,EXT_meshopt_compression:$o,EXT_texture_avif:es,EXT_texture_webp:Xo,ExtrasAsMetadata:pl,FlowGraphGLTFDataProvider:vl,GLTFFileLoader:mn,GLTFLoader:yo,GetMappingForKey:co,GetPathToObjectConverter:uo,InteractivityGraphToFlowGraphParser:$a,KHR_animation_pointer:ki,KHR_draco_mesh_compression:cs,KHR_gaussian_splatting:ys,KHR_interactivity:za,KHR_lights:As,KHR_materials_anisotropy:sr,KHR_materials_clearcoat:Us,KHR_materials_coat:qs,KHR_materials_diffuse_roughness:hi,KHR_materials_diffuse_transmission:zr,KHR_materials_dispersion:ai,KHR_materials_emissive_strength:ur,KHR_materials_fuzz:vr,KHR_materials_ior:Sr,KHR_materials_iridescence:Js,KHR_materials_pbrSpecularGlossiness:Is,KHR_materials_sheen:fr,KHR_materials_specular:Mr,KHR_materials_transmission:Hr,KHR_materials_unlit:Ds,KHR_materials_variants:Nr,KHR_materials_volume:Qr,KHR_materials_volume_scatter:ni,KHR_mesh_quantization:gi,KHR_node_hoverability:cl,KHR_node_selectability:ol,KHR_node_visibility:Za,KHR_texture_basisu:Ti,KHR_texture_transform:Ri,KHR_xmp_json_ld:Li,LoadBoundingInfoFromPositionAccessor:go,MSFT_audio_emitter:_a,MSFT_lod:xa,MSFT_minecraftMesh:Ca,MSFT_sRGBFactors:Ea,OpenPBRMaterialLoadingAdapter:So,PBRMaterialLoadingAdapter:Eo,RegisterEXT_lights_area:Fs,RegisterEXT_lights_ies:as,RegisterEXT_lights_image_based:Bo,RegisterEXT_mesh_gpu_instancing:Ho,RegisterEXT_meshopt_compression:zo,RegisterEXT_texture_avif:ns,RegisterEXT_texture_webp:Qo,RegisterExtrasAsMetadata:gl,RegisterGLTF2Loader:bo,RegisterKHR_animation_pointer:Gi,RegisterKHR_draco_mesh_compression:hs,RegisterKHR_gaussian_splatting:bs,RegisterKHR_interactivity:Xa,RegisterKHR_lights:ws,RegisterKHR_materials_anisotropy:ir,RegisterKHR_materials_clearcoat:Ws,RegisterKHR_materials_coat:Ys,RegisterKHR_materials_diffuse_roughness:fi,RegisterKHR_materials_diffuse_transmission:qr,RegisterKHR_materials_dispersion:ui,RegisterKHR_materials_emissive_strength:dr,RegisterKHR_materials_fuzz:xr,RegisterKHR_materials_ior:Er,RegisterKHR_materials_iridescence:tr,RegisterKHR_materials_pbrSpecularGlossiness:Ps,RegisterKHR_materials_sheen:_r,RegisterKHR_materials_specular:Cr,RegisterKHR_materials_transmission:Ur,RegisterKHR_materials_unlit:Vs,RegisterKHR_materials_variants:Br,RegisterKHR_materials_volume:Jr,RegisterKHR_materials_volume_scatter:si,RegisterKHR_mesh_quantization:vi,RegisterKHR_node_hoverability:hl,RegisterKHR_node_selectability:rl,RegisterKHR_node_visibility:el,RegisterKHR_texture_basisu:Mi,RegisterKHR_texture_transform:Si,RegisterKHR_xmp_json_ld:Ni,RegisterMSFT_audio_emitter:ya,RegisterMSFT_lod:Aa,RegisterMSFT_minecraftMesh:Oa,RegisterMSFT_sRGBFactors:Ia,SetInterpolationForKey:ho,TransformNodeAnimationPropertyInfo:Co,TransmissionHelper:Dr,WeightAnimationPropertyInfo:Ro,_AddInteractivityObjectModel:ja,addNewInteractivityFlowGraphMapping:ka,ensureTransmissionHelper:Gr,getAllSupportedNativeNodeTypes:Ka,getMappingForDeclaration:Ba,getMappingForFullOperationName:Pa,getQuaternion:Ao,getVector3:To,getWeights:Mo,gltfTypeToBabylonType:Ua,registerGLTFExtension:to,registeredGLTFExtensions:eo,unregisterGLTFExtension:no};class Al{constructor(){this.materials=[]}parseMTL(e,n,o,s){if(n instanceof ArrayBuffer)return;const r=n.split("\n"),i=/\s+/;let a,l=null;for(let n=0;n<r.length;n++){const u=r[n].trim();if(0===u.length||"#"===u.charAt(0))continue;const c=u.indexOf(" ");let d=c>=0?u.substring(0,c):u;d=d.toLowerCase();const h=c>=0?u.substring(c+1).trim():"";if("newmtl"===d)l&&this.materials.push(l),e._blockEntityCollection=!!s,l=new t.StandardMaterial(h,e),l._parentContainer=s,e._blockEntityCollection=!1;else if("kd"===d&&l)a=h.split(i,3).map(parseFloat),l.diffuseColor=t.Color3.FromArray(a);else if("ka"===d&&l)a=h.split(i,3).map(parseFloat),l.ambientColor=t.Color3.FromArray(a);else if("ks"===d&&l)a=h.split(i,3).map(parseFloat),l.specularColor=t.Color3.FromArray(a);else if("ke"===d&&l)a=h.split(i,3).map(parseFloat),l.emissiveColor=t.Color3.FromArray(a);else if("ns"===d&&l)l.specularPower=parseFloat(h);else if("d"===d&&l)l.alpha=parseFloat(h);else if("map_ka"===d&&l)l.ambientTexture=Al._GetTexture(o,h,e);else if("map_kd"===d&&l)l.diffuseTexture=Al._GetTexture(o,h,e);else if("map_ks"===d&&l)l.specularTexture=Al._GetTexture(o,h,e);else if("map_ns"===d);else if("map_bump"===d&&l){const t=h.split(i),n=t.indexOf("-bm");let s=null;n>=0&&(s=t[n+1],t.splice(n,2)),l.bumpTexture=Al._GetTexture(o,t.join(" "),e),l.bumpTexture&&null!==s&&(l.bumpTexture.level=parseFloat(s))}else"map_d"===d&&l&&(l.opacityTexture=Al._GetTexture(o,h,e))}l&&this.materials.push(l)}static _GetTexture(e,n,o){if(!n)return null;let s=e;if("file:"===e){let e=n.lastIndexOf("\\");-1===e&&(e=n.lastIndexOf("/")),s+=e>-1?n.substring(e+1):n}else s+=n;return new t.Texture(s,o,!1,Al.INVERT_TEXTURE_Y)}}Al.INVERT_TEXTURE_Y=!0;class Ml{constructor(e,n,o){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],this._extColors=[],this._meshesFromObj=[],this._indicesForBabylon=[],this._wrappedPositionForBabylon=[],this._wrappedUvsForBabylon=[],this._wrappedColorsForBabylon=[],this._wrappedNormalsForBabylon=[],this._tuplePosNorm=[],this._curPositionInIndices=0,this._hasMeshes=!1,this._unwrappedPositionsForBabylon=[],this._unwrappedColorsForBabylon=[],this._unwrappedNormalsForBabylon=[],this._unwrappedUVForBabylon=[],this._triangles=[],this._materialNameFromObj="",this._objMeshName="",this._increment=1,this._isFirstMaterial=!0,this._grayColor=new t.Color4(.5,.5,.5,1),this._hasLineData=!1,this._materialToUse=e,this._babylonMeshesArray=n,this._loadingOptions=o}_isInArray(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});const n=e[t[0]].normals.indexOf(t[1]);return-1===n?-1:e[t[0]].idx[n]}_isInArrayUV(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});const n=e[t[0]].normals.indexOf(t[1]);return 1!=n&&t[2]===e[t[0]].uv[n]?e[t[0]].idx[n]:-1}_setData(e){var t,n;let o;null!==(t=e.indiceUvsFromObj)&&void 0!==t||(e.indiceUvsFromObj=-1),null!==(n=e.indiceNormalFromObj)&&void 0!==n||(e.indiceNormalFromObj=-1),o=this._loadingOptions.optimizeWithUV?this._isInArrayUV(this._tuplePosNorm,[e.indicePositionFromObj,e.indiceNormalFromObj,e.indiceUvsFromObj]):this._isInArray(this._tuplePosNorm,[e.indicePositionFromObj,e.indiceNormalFromObj]),-1===o?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(e.positionVectorFromOBJ),void 0!==e.textureVectorFromOBJ&&this._wrappedUvsForBabylon.push(e.textureVectorFromOBJ),void 0!==e.normalsVectorFromOBJ&&this._wrappedNormalsForBabylon.push(e.normalsVectorFromOBJ),void 0!==e.positionColorsFromOBJ&&this._wrappedColorsForBabylon.push(e.positionColorsFromOBJ),this._tuplePosNorm[e.indicePositionFromObj].normals.push(e.indiceNormalFromObj),this._tuplePosNorm[e.indicePositionFromObj].idx.push(this._curPositionInIndices++),this._loadingOptions.optimizeWithUV&&this._tuplePosNorm[e.indicePositionFromObj].uv.push(e.indiceUvsFromObj)):this._indicesForBabylon.push(o)}_unwrapData(){try{for(let e=0;e<this._wrappedPositionForBabylon.length;e++)this._unwrappedPositionsForBabylon.push(this._wrappedPositionForBabylon[e].x*this._handednessSign,this._wrappedPositionForBabylon[e].y,this._wrappedPositionForBabylon[e].z),this._wrappedNormalsForBabylon.length&&this._unwrappedNormalsForBabylon.push(this._wrappedNormalsForBabylon[e].x*this._handednessSign,this._wrappedNormalsForBabylon[e].y,this._wrappedNormalsForBabylon[e].z),this._wrappedUvsForBabylon.length&&this._unwrappedUVForBabylon.push(this._wrappedUvsForBabylon[e].x,this._wrappedUvsForBabylon[e].y),this._wrappedColorsForBabylon.length&&this._unwrappedColorsForBabylon.push(this._wrappedColorsForBabylon[e].r,this._wrappedColorsForBabylon[e].g,this._wrappedColorsForBabylon[e].b,this._wrappedColorsForBabylon[e].a);this._wrappedPositionForBabylon.length=0,this._wrappedNormalsForBabylon.length=0,this._wrappedUvsForBabylon.length=0,this._wrappedColorsForBabylon.length=0,this._tuplePosNorm.length=0,this._curPositionInIndices=0}catch(e){throw new Error("Unable to unwrap data while parsing OBJ data.",{cause:e})}}_getTriangles(e,t){for(let n=t;n<e.length-1;n++)this._pushTriangle(e,n)}_getColor(e){var t;return this._loadingOptions.importVertexColors?null!==(t=this._extColors[e])&&void 0!==t?t:this._colors[e]:void 0}_setDataForCurrentFaceWithPattern1(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=parseInt(this._triangles[e])-1;this._setData({indicePositionFromObj:t,positionVectorFromOBJ:this._positions[t],positionColorsFromOBJ:this._getColor(t)})}this._triangles.length=0}_setDataForCurrentFaceWithPattern2(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=this._triangles[e].split("/"),n=parseInt(t[0])-1,o=parseInt(t[1])-1;this._setData({indicePositionFromObj:n,indiceUvsFromObj:o,positionVectorFromOBJ:this._positions[n],textureVectorFromOBJ:this._uvs[o],positionColorsFromOBJ:this._getColor(n)})}this._triangles.length=0}_setDataForCurrentFaceWithPattern3(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=this._triangles[e].split("/"),n=parseInt(t[0])-1,o=parseInt(t[1])-1,s=parseInt(t[2])-1;this._setData({indicePositionFromObj:n,indiceUvsFromObj:o,indiceNormalFromObj:s,positionVectorFromOBJ:this._positions[n],textureVectorFromOBJ:this._uvs[o],normalsVectorFromOBJ:this._normals[s]})}this._triangles.length=0}_setDataForCurrentFaceWithPattern4(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=this._triangles[e].split("//"),n=parseInt(t[0])-1,o=parseInt(t[1])-1;this._setData({indicePositionFromObj:n,indiceNormalFromObj:o,positionVectorFromOBJ:this._positions[n],normalsVectorFromOBJ:this._normals[o],positionColorsFromOBJ:this._getColor(n)})}this._triangles.length=0}_setDataForCurrentFaceWithPattern5(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=this._triangles[e].split("/"),n=this._positions.length+parseInt(t[0]),o=this._uvs.length+parseInt(t[1]),s=this._normals.length+parseInt(t[2]);this._setData({indicePositionFromObj:n,indiceUvsFromObj:o,indiceNormalFromObj:s,positionVectorFromOBJ:this._positions[n],textureVectorFromOBJ:this._uvs[o],normalsVectorFromOBJ:this._normals[s],positionColorsFromOBJ:this._getColor(n)})}this._triangles.length=0}_addPreviousObjMesh(){this._meshesFromObj.length>0&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._unwrapData(),this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._handledMesh.indices=this._indicesForBabylon.slice(),this._handledMesh.positions=this._unwrappedPositionsForBabylon.slice(),this._unwrappedNormalsForBabylon.length&&(this._handledMesh.normals=this._unwrappedNormalsForBabylon.slice()),this._unwrappedUVForBabylon.length&&(this._handledMesh.uvs=this._unwrappedUVForBabylon.slice()),this._unwrappedColorsForBabylon.length&&(this._handledMesh.colors=this._unwrappedColorsForBabylon.slice()),this._handledMesh.hasLines=this._hasLineData,this._indicesForBabylon.length=0,this._unwrappedPositionsForBabylon.length=0,this._unwrappedColorsForBabylon.length=0,this._unwrappedNormalsForBabylon.length=0,this._unwrappedUVForBabylon.length=0,this._hasLineData=!1)}_optimizeNormals(e){const n=e.getVerticesData(t.VertexBuffer.PositionKind),o=e.getVerticesData(t.VertexBuffer.NormalKind),s={};if(!n||!o)return;for(let e=0;e<n.length/3;e++){const t=n[3*e+0]+"_"+n[3*e+1]+"_"+n[3*e+2];let o=s[t];o||(o=[],s[t]=o),o.push(e)}const r=new t.Vector3;for(const e in s){const t=s[e];if(t.length<2)continue;const n=t[0];for(let e=1;e<t.length;++e){const s=t[e];o[3*n+0]+=o[3*s+0],o[3*n+1]+=o[3*s+1],o[3*n+2]+=o[3*s+2]}r.copyFromFloats(o[3*n+0],o[3*n+1],o[3*n+2]),r.normalize();for(let e=0;e<t.length;++e){const n=t[e];o[3*n+0]=r.x,o[3*n+1]=r.y,o[3*n+2]=r.z}}e.setVerticesData(t.VertexBuffer.NormalKind,o)}static _IsLineElement(e){return e.startsWith("l")}static _IsObjectElement(e){return e.startsWith("o")}static _IsGroupElement(e){return e.startsWith("g")}static _GetZbrushMRGB(e,n){if(!e.startsWith("mrgb"))return null;if(e=e.replace("mrgb","").trim(),n)return[];const o=e.match(/[a-z0-9]/g);if(!o||o.length%8!=0)return[];const s=[];for(let e=0;e<o.length/8;e++){const n=o[8*e+2]+o[8*e+3],r=o[8*e+4]+o[8*e+5],i=o[8*e+6]+o[8*e+7];s.push(new t.Color4(parseInt(n,16)/255,parseInt(r,16)/255,parseInt(i,16)/255,1))}return s}parse(e,n,o,s,r){var i,a,l,u,c;n=(n=n.replace(/#MRGB/g,"mrgb")).replace(/#.*$/gm,"").trim(),this._loadingOptions.useLegacyBehavior?(this._pushTriangle=(e,t)=>this._triangles.push(e[0],e[t],e[t+1]),this._handednessSign=1):o.useRightHandedSystem?(this._pushTriangle=(e,t)=>this._triangles.push(e[0],e[t+1],e[t]),this._handednessSign=1):(this._pushTriangle=(e,t)=>this._triangles.push(e[0],e[t],e[t+1]),this._handednessSign=-1);const d=n.split("\n"),h=[];let m=[];h.push(m);for(let e=0;e<d.length;e++){const t=d[e].trim().replace(/\s\s/g," ");if(0!==t.length&&"#"!==t.charAt(0))if((Ml._IsGroupElement(t)||Ml._IsObjectElement(t))&&(m=[],h.push(m)),Ml._IsLineElement(t)){const e=t.split(" ");for(let t=1;t<e.length-1;t++)m.push(`l ${e[t]} ${e[t+1]}`)}else m.push(t)}const f=h.flat();for(let e=0;e<f.length;e++){const n=f[e].trim().replace(/\s\s/g," ");let o;if(0!==n.length&&"#"!==n.charAt(0))if(Ml.VertexPattern.test(n)){if(o=n.match(/[^ ]+/g),this._positions.push(new t.Vector3(parseFloat(o[1]),parseFloat(o[2]),parseFloat(o[3]))),this._loadingOptions.importVertexColors)if(o.length>=7){const e=parseFloat(o[4]),n=parseFloat(o[5]),s=parseFloat(o[6]);this._colors.push(new t.Color4(e>1?e/255:e,n>1?n/255:n,s>1?s/255:s,7===o.length||void 0===o[7]?1:parseFloat(o[7])))}else this._colors.push(this._grayColor)}else if(null!==(o=Ml.NormalPattern.exec(n)))this._normals.push(new t.Vector3(parseFloat(o[1]),parseFloat(o[2]),parseFloat(o[3])));else if(null!==(o=Ml.UVPattern.exec(n)))this._uvs.push(new t.Vector2(parseFloat(o[1])*this._loadingOptions.UVScaling.x,parseFloat(o[2])*this._loadingOptions.UVScaling.y));else if(null!==(o=Ml.FacePattern3.exec(n)))this._setDataForCurrentFaceWithPattern3(o[1].trim().split(" "),1);else if(null!==(o=Ml.FacePattern4.exec(n)))this._setDataForCurrentFaceWithPattern4(o[1].trim().split(" "),1);else if(null!==(o=Ml.FacePattern5.exec(n)))this._setDataForCurrentFaceWithPattern5(o[1].trim().split(" "),1);else if(null!==(o=Ml.FacePattern2.exec(n)))this._setDataForCurrentFaceWithPattern2(o[1].trim().split(" "),1);else if(null!==(o=Ml.FacePattern1.exec(n)))this._setDataForCurrentFaceWithPattern1(o[1].trim().split(" "),1);else if(null!==(o=Ml.LinePattern1.exec(n)))this._setDataForCurrentFaceWithPattern1(o[1].trim().split(" "),0),this._hasLineData=!0;else if(null!==(o=Ml.LinePattern2.exec(n)))this._setDataForCurrentFaceWithPattern2(o[1].trim().split(" "),0),this._hasLineData=!0;else if(o=Ml._GetZbrushMRGB(n,!this._loadingOptions.importVertexColors))for(const e of o)this._extColors.push(e);else if(null!==(o=Ml.LinePattern3.exec(n)))this._setDataForCurrentFaceWithPattern3(o[1].trim().split(" "),0),this._hasLineData=!0;else if(Ml.GroupDescriptor.test(n)||Ml.ObjectDescriptor.test(n)){const e={name:n.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:Ml.ObjectDescriptor.test(n)};this._addPreviousObjMesh(),this._meshesFromObj.push(e),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(Ml.UseMtlDescriptor.test(n)){if(this._materialNameFromObj=n.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();const e={name:(this._objMeshName||"mesh")+"_mm"+this._increment.toString(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:!1};this._increment++,this._meshesFromObj.push(e),this._hasMeshes=!0}this._hasMeshes&&this._isFirstMaterial&&(this._meshesFromObj[this._meshesFromObj.length-1].materialName=this._materialNameFromObj,this._isFirstMaterial=!1)}else Ml.MtlLibGroupDescriptor.test(n)?r(n.substring(7).trim()):Ml.SmoothDescriptor.test(n)||t.Logger.Log("Unhandled expression at line : "+n)}if(this._hasMeshes&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData(),this._handledMesh.indices=this._indicesForBabylon,this._handledMesh.positions=this._unwrappedPositionsForBabylon,this._unwrappedNormalsForBabylon.length&&(this._handledMesh.normals=this._unwrappedNormalsForBabylon),this._unwrappedUVForBabylon.length&&(this._handledMesh.uvs=this._unwrappedUVForBabylon),this._unwrappedColorsForBabylon.length&&(this._handledMesh.colors=this._unwrappedColorsForBabylon),this._handledMesh.hasLines=this._hasLineData),!this._hasMeshes){let e=null;if(this._indicesForBabylon.length)this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData();else{for(const e of this._positions)this._unwrappedPositionsForBabylon.push(e.x,e.y,e.z);if(this._normals.length)for(const e of this._normals)this._unwrappedNormalsForBabylon.push(e.x,e.y,e.z);if(this._uvs.length)for(const e of this._uvs)this._unwrappedUVForBabylon.push(e.x,e.y);if(this._extColors.length)for(const e of this._extColors)this._unwrappedColorsForBabylon.push(e.r,e.g,e.b,e.a);else if(this._colors.length)for(const e of this._colors)this._unwrappedColorsForBabylon.push(e.r,e.g,e.b,e.a);this._materialNameFromObj||(e=new t.StandardMaterial(t.Geometry.RandomId(),o),e.pointsCloud=!0,this._materialNameFromObj=e.name,this._normals.length||(e.disableLighting=!0,e.emissiveColor=t.Color3.White()))}this._meshesFromObj.push({name:t.Geometry.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:e,isObject:!0,hasLines:this._hasLineData})}for(let n=0;n<this._meshesFromObj.length;n++){if(e&&this._meshesFromObj[n].name)if(e instanceof Array){if(-1===e.indexOf(this._meshesFromObj[n].name))continue}else if(this._meshesFromObj[n].name!==e)continue;this._handledMesh=this._meshesFromObj[n],o._blockEntityCollection=!!s;const r=new t.Mesh(this._meshesFromObj[n].name,o);if(r._parentContainer=s,o._blockEntityCollection=!1,this._handledMesh._babylonMesh=r,!this._handledMesh.isObject)for(let e=n-1;e>=0;--e)if(this._meshesFromObj[e].isObject&&this._meshesFromObj[e]._babylonMesh){r.parent=this._meshesFromObj[e]._babylonMesh;break}if(this._materialToUse.push(this._meshesFromObj[n].materialName),this._handledMesh.hasLines&&(null!==(i=r._internalMetadata)&&void 0!==i||(r._internalMetadata={}),r._internalMetadata._isLine=!0),0===(null===(a=this._handledMesh.positions)||void 0===a?void 0:a.length)){this._babylonMeshesArray.push(r);continue}const d=new t.VertexData;if(d.indices=this._handledMesh.indices,d.positions=this._handledMesh.positions,this._loadingOptions.computeNormals||!(null===(l=this._handledMesh.normals)||void 0===l?void 0:l.length)){const e=new Array;t.VertexData.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,e),d.normals=e}else d.normals=this._handledMesh.normals;(null===(u=this._handledMesh.uvs)||void 0===u?void 0:u.length)&&(d.uvs=this._handledMesh.uvs),(null===(c=this._handledMesh.colors)||void 0===c?void 0:c.length)&&(d.colors=this._handledMesh.colors),d.applyToMesh(r),this._loadingOptions.invertY&&(r.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(r),this._babylonMeshesArray.push(r),this._handledMesh.directMaterial&&(r.material=this._handledMesh.directMaterial)}}}Ml.ObjectDescriptor=/^o/,Ml.GroupDescriptor=/^g/,Ml.MtlLibGroupDescriptor=/^mtllib /,Ml.UseMtlDescriptor=/^usemtl /,Ml.SmoothDescriptor=/^s /,Ml.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/,Ml.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,Ml.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,Ml.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/,Ml.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,Ml.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,Ml.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,Ml.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,Ml.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/,Ml.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/,Ml.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;const wl={name:"obj",extensions:".obj"};class Cl{static get INVERT_TEXTURE_Y(){return Al.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){Al.INVERT_TEXTURE_Y=e}constructor(e){this.name=wl.name,this.extensions=wl.extensions,this._assetContainer=null,this._loadingOptions=Object.assign(Object.assign({},Cl._DefaultLoadingOptions),null!=e?e:{})}static get _DefaultLoadingOptions(){return{computeNormals:Cl.COMPUTE_NORMALS,optimizeNormals:Cl.OPTIMIZE_NORMALS,importVertexColors:Cl.IMPORT_VERTEX_COLORS,invertY:Cl.INVERT_Y,invertTextureY:Cl.INVERT_TEXTURE_Y,UVScaling:Cl.UV_SCALING,materialLoadingFailsSilently:Cl.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:Cl.OPTIMIZE_WITH_UV,skipMaterials:Cl.SKIP_MATERIALS,useLegacyBehavior:Cl.USE_LEGACY_BEHAVIOR}}_loadMTL(e,n,o,s){const r=n+e;t.Tools.LoadFile(r,o,void 0,void 0,!1,(e,t)=>{s(r,t)})}createPlugin(e){return new Cl(e[wl.name])}canDirectLoad(){return!1}importMeshAsync(e,t,n,o){return this._parseSolidAsync(e,t,n,o).then(e=>({meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))}loadAsync(e,t,n){return this.importMeshAsync(null,e,t,n).then(()=>{})}loadAssetContainerAsync(e,n,o){const s=new t.AssetContainer(e);return this._assetContainer=s,this.importMeshAsync(null,e,n,o).then(e=>(e.meshes.forEach(e=>s.meshes.push(e)),e.meshes.forEach(e=>{const t=e.material;t&&-1==s.materials.indexOf(t)&&(s.materials.push(t),t.getActiveTextures().forEach(e=>{-1==s.textures.indexOf(e)&&s.textures.push(e)}))}),this._assetContainer=null,s)).catch(e=>{throw this._assetContainer=null,e})}_parseSolidAsync(e,n,o,s){let r="";const i=new Al,a=[],l=[];o=o.replace(/#.*$/gm,"").trim(),new Ml(a,l,this._loadingOptions).parse(e,o,n,this._assetContainer,e=>{r=e});const u=[];return""===r||this._loadingOptions.skipMaterials||u.push(new Promise((e,o)=>{this._loadMTL(r,s,u=>{try{i.parseMTL(n,u,s,this._assetContainer);for(let e=0;e<i.materials.length;e++){let t=0;const n=[];let o;for(;(o=a.indexOf(i.materials[e].name,t))>-1;)n.push(o),t=o+1;if(-1===o&&0===n.length)i.materials[e].dispose();else for(let t=0;t<n.length;t++){const o=l[n[t]],s=i.materials[e];o.material=s,o.getTotalIndices()||(s.pointsCloud=!0)}}e()}catch(n){t.Tools.Warn(`Error processing MTL file: '${r}'`),this._loadingOptions.materialLoadingFailsSilently?e():o(n)}},(n,s)=>{t.Tools.Warn(`Error downloading MTL file: '${r}'`),this._loadingOptions.materialLoadingFailsSilently?e():o(s)})})),Promise.all(u).then(()=>{const e=e=>{var t,n;return Boolean(null!==(n=null===(t=e._internalMetadata)||void 0===t?void 0:t._isLine)&&void 0!==n&&n)};return l.forEach(o=>{var s,r;if(e(o)){let i=null!==(s=o.material)&&void 0!==s?s:new t.StandardMaterial(o.name+"_line",n);i.getBindedMeshes().filter(t=>!e(t)).length>0&&(i=null!==(r=i.clone(i.name+"_line"))&&void 0!==r?r:i),i.wireframe=!0,o.material=i,o._internalMetadata&&(o._internalMetadata._isLine=void 0)}}),l})}}Cl.OPTIMIZE_WITH_UV=!0,Cl.INVERT_Y=!1,Cl.IMPORT_VERTEX_COLORS=!1,Cl.COMPUTE_NORMALS=!1,Cl.OPTIMIZE_NORMALS=!1,Cl.UV_SCALING=new t.Vector2(1,1),Cl.SKIP_MATERIALS=!1,Cl.MATERIAL_LOADING_FAILS_SILENTLY=!0,Cl.USE_LEGACY_BEHAVIOR=!1;let Rl=!1;function Ol(){Rl||(Rl=!0,t.RegisterSceneLoaderPlugin(new Cl))}Ol();var Sl={__proto__:null,OBJFileLoader:Cl,RegisterOBJFileLoader:Ol},Fl={__proto__:null,MTLFileLoader:Al,OBJFileLoader:Cl,RegisterOBJFileLoader:Ol,SolidParser:Ml};const El={name:"stl",extensions:{".stl":{isBinary:!0}}};class Ll{constructor(){this.solidPattern=/solid (\S*)([\S\s]*?)endsolid[ ]*(\S*)/g,this.facetsPattern=/facet([\s\S]*?)endfacet/g,this.normalPattern=/normal[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g,this.vertexPattern=/vertex[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g,this.name=El.name,this.extensions=El.extensions}importMesh(e,n,o,s,r){let i;if("string"!=typeof o){if(this._isBinary(o)){const e=new t.Mesh("stlmesh",n);return this._parseBinary(e,o),r&&r.push(e),!0}o=(new TextDecoder).decode(new Uint8Array(o))}for(;i=this.solidPattern.exec(o);){let o=i[1];const s=i[3];if(s&&o!=s)return t.Tools.Error("Error in STL, solid name != endsolid name"),!1;if(e&&o)if(e instanceof Array){if(!e.indexOf(o))continue}else if(o!==e)continue;o=o||"stlmesh";const a=new t.Mesh(o,n);this._parseASCII(a,i[2]),r&&r.push(a)}return!0}load(e,t,n){return this.importMesh(null,e,t,n,null)}loadAssetContainer(e,n,o){const s=new t.AssetContainer(e);return e._blockEntityCollection=!0,this.importMesh(null,e,n,o,s.meshes),e._blockEntityCollection=!1,s}_isBinary(e){const t=new DataView(e);if(t.byteLength<=80)return!1;if(84+50*t.getUint32(80,!0)===t.byteLength)return!0;const n=[115,111,108,105,100];for(let e=0;e<5;e++)if(t.getUint8(e)!==n[e])return!0;return!1}_parseBinary(e,n){const o=new DataView(n),s=o.getUint32(80,!0);let r=0;const i=new Float32Array(3*s*3),a=new Float32Array(3*s*3),l=new Uint32Array(3*s);let u=0;for(let e=0;e<s;e++){const t=84+50*e,n=o.getFloat32(t,!0),s=o.getFloat32(t+4,!0),c=o.getFloat32(t+8,!0);for(let e=1;e<=3;e++){const l=t+12*e;i[r]=o.getFloat32(l,!0),a[r]=n,Ll.DO_NOT_ALTER_FILE_COORDINATES?(i[r+1]=o.getFloat32(l+4,!0),i[r+2]=o.getFloat32(l+8,!0),a[r+1]=s,a[r+2]=c):(i[r+2]=o.getFloat32(l+4,!0),i[r+1]=o.getFloat32(l+8,!0),a[r+2]=s,a[r+1]=c),r+=3}Ll.DO_NOT_ALTER_FILE_COORDINATES?(l[u]=u,l[u+1]=u+2,l[u+2]=u+1,u+=3):(l[u]=u++,l[u]=u++,l[u]=u++)}e.setVerticesData(t.VertexBuffer.PositionKind,i),e.setVerticesData(t.VertexBuffer.NormalKind,a),e.setIndices(l),e.computeWorldMatrix(!0)}_parseASCII(e,n){const o=[],s=[],r=[];let i,a=0;for(;i=this.facetsPattern.exec(n);){const e=i[1],t=this.normalPattern.exec(e);if(this.normalPattern.lastIndex=0,!t)continue;const n=[Number(t[1]),Number(t[5]),Number(t[3])];let l;for(;l=this.vertexPattern.exec(e);)Ll.DO_NOT_ALTER_FILE_COORDINATES?(o.push(Number(l[1]),Number(l[3]),Number(l[5])),s.push(n[0],n[2],n[1])):(o.push(Number(l[1]),Number(l[5]),Number(l[3])),s.push(n[0],n[1],n[2]));Ll.DO_NOT_ALTER_FILE_COORDINATES?(r.push(a,a+2,a+1),a+=3):r.push(a++,a++,a++),this.vertexPattern.lastIndex=0}this.facetsPattern.lastIndex=0,e.setVerticesData(t.VertexBuffer.PositionKind,o),e.setVerticesData(t.VertexBuffer.NormalKind,s),e.setIndices(r),e.computeWorldMatrix(!0)}}Ll.DO_NOT_ALTER_FILE_COORDINATES=!1;let Il=!1;function Nl(){Il||(Il=!0,t.RegisterSceneLoaderPlugin(new Ll))}Nl();var Pl={__proto__:null,RegisterSTLFileLoader:Nl,STLFileLoader:Ll},Bl={__proto__:null,RegisterSTLFileLoader:Nl,STLFileLoader:Ll};const kl={name:"splat",extensions:{".splat":{isBinary:!0},".ply":{isBinary:!0},".spz":{isBinary:!0},".json":{isBinary:!1},".sog":{isBinary:!0}}},Dl=.28209479177387814;function Gl(e,t,n){return b(this,void 0,void 0,function*(){const o=new Promise((o,s)=>{const r=n.createCanvasImage();if(!r)throw new Error("Failed to create ImageBitmap");let i;if(r.onload=()=>{try{const e=n.createCanvas(r.width,r.height);if(!e)throw new Error("Failed to create canvas");const t=e.getContext("2d");if(!t)throw new Error("Failed to get 2D context");t.drawImage(r,0,0);const s=t.getImageData(0,0,e.width,e.height);o({bits:new Uint8Array(s.data.buffer),width:s.width,height:s.height})}catch(e){s(`Error loading image ${r.src} with exception: ${e}`)}},r.onerror=e=>{s(`Error loading image ${r.src} with exception: ${e}`)},r.crossOrigin="anonymous","string"==typeof e){if(!t)throw new Error("filename is required when using a URL");r.src=e+t}else{const t=new Blob([e],{type:"image/webp"});i=URL.createObjectURL(t),r.src=i}});return yield o})}function Vl(e,n,o){return b(this,void 0,void 0,function*(){let s,r;if(e instanceof Map){r=e;const t=r.get("meta.json");if(!t)throw new Error("meta.json not found in files Map");s=JSON.parse((new TextDecoder).decode(t))}else s=e;const i=[...s.means.files,...s.scales.files,...s.quats.files,...s.sh0.files];s.shN&&i.push(...s.shN.files);const a=yield Promise.all(i.map(e=>b(this,void 0,void 0,function*(){if(r&&r.has(e)){const t=r.get(e);return yield Gl(t,e,o.getEngine())}return yield Gl(n,e,o.getEngine())})));return yield function(e,n,o){return b(this,void 0,void 0,function*(){const s=e.count?e.count:e.means.shape[0],r=new ArrayBuffer(32*s),i=new Float32Array(r),a=new Float32Array(r),l=new Uint8ClampedArray(r),u=new Uint8ClampedArray(r),c=e=>Math.sign(e)*(Math.exp(Math.abs(e))-1),d=n[0].bits,h=n[1].bits;if(!Array.isArray(e.means.mins)||!Array.isArray(e.means.maxs))throw new Error("Missing arrays in SOG data.");for(let n=0;n<s;n++){const o=4*n;for(let s=0;s<3;s++){const r=e.means.mins[s],a=e.means.maxs[s],l=h[o+s]<<8|d[o+s],u=t.Scalar.Lerp(r,a,l/65535);i[8*n+s]=c(u)}}const m=n[2].bits;if(2===e.version){if(!e.scales.codebook)throw new Error("Missing codebook in SOG version 2 scales data.");for(let t=0;t<s;t++){const n=4*t;for(let o=0;o<3;o++){const s=e.scales.codebook[m[n+o]],r=Math.exp(s);a[8*t+3+o]=r}}}else{if(!Array.isArray(e.scales.mins)||!Array.isArray(e.scales.maxs))throw new Error("Missing arrays in SOG scales data.");for(let n=0;n<s;n++){const o=4*n;for(let s=0;s<3;s++){const r=m[o+s],i=t.Scalar.Lerp(e.scales.mins[s],e.scales.maxs[s],r/255),l=Math.exp(i);a[8*n+3+s]=l}}}const f=n[4].bits;if(2===e.version){if(!e.sh0.codebook)throw new Error("Missing codebook in SOG version 2 sh0 data.");for(let t=0;t<s;t++){const n=4*t;for(let o=0;o<3;o++){const s=.5+e.sh0.codebook[f[n+o]]*Dl;l[32*t+24+o]=Math.max(0,Math.min(255,Math.round(255*s)))}l[32*t+24+3]=f[n+3]}}else{if(!Array.isArray(e.sh0.mins)||!Array.isArray(e.sh0.maxs))throw new Error("Missing arrays in SOG sh0 data.");for(let n=0;n<s;n++){const o=4*n;for(let s=0;s<4;s++){const r=e.sh0.mins[s],i=e.sh0.maxs[s],a=f[o+s],u=t.Scalar.Lerp(r,i,a/255);let c;c=s<3?.5+u*Dl:1/(1+Math.exp(-u)),l[32*n+24+s]=Math.max(0,Math.min(255,Math.round(255*c)))}}}const p=e=>2*(e/255-.5)/Math.SQRT2,_=n[3].bits;for(let e=0;e<s;e++){const t=_[4*e+0],n=_[4*e+1],o=_[4*e+2],s=_[4*e+3],r=p(t),i=p(n),a=p(o),l=s-252,c=r*r+i*i+a*a,d=Math.sqrt(Math.max(0,1-c));let h;switch(l){case 0:h=[d,r,i,a];break;case 1:h=[r,d,i,a];break;case 2:h=[r,i,d,a];break;case 3:h=[r,i,a,d];break;default:throw new Error("Invalid quaternion mode")}u[32*e+28+0]=127.5*h[0]+127.5,u[32*e+28+1]=127.5*h[1]+127.5,u[32*e+28+2]=127.5*h[2]+127.5,u[32*e+28+3]=127.5*h[3]+127.5}if(e.shN){const i=e.shN.bands?Math.pow(e.shN.bands+1,2)-1:e.shN.shape[1]/3,a=void 0!==e.shN.bands&&null!==e.shN.bands?e.shN.bands:Math.round(Math.sqrt(i+1)-1),l=n[5].bits,u=n[6].bits,c=n[5].width,d=3*i,h=Math.ceil(d/16),m=o.getEngine().getCaps().maxTextureSize,f=Math.ceil(s/m),p=t.AllocateShBuffers(h,f*m*4*4);if(2===e.version){if(!e.shN.codebook)throw new Error("Missing codebook in SOG version 2 shN data.");for(let t=0;t<s;t++){const n=u[4*t+0]+(u[4*t+1]<<8),o=n%64*i,s=Math.floor(n/64);for(let n=0;n<i;n++)for(let r=0;r<3;r++){const i=3*n+r,a=Math.floor(i/16),u=p[a],d=i%16,h=16*t,m=127.5*e.shN.codebook[l[4*(o+n)+r+s*c*4]]+127.5;u[d+h]=Math.max(0,Math.min(255,m))}}}else for(let n=0;n<s;n++){const o=u[4*n+0]+(u[4*n+1]<<8),s=o%64*i,r=Math.floor(o/64),a=e.shN.mins,d=e.shN.maxs;for(let e=0;e<3;e++)for(let o=0;o<i/3;o++){const i=3*o+e,u=Math.floor(i/16),h=p[u],m=i%16,f=16*n,_=127.5*t.Scalar.Lerp(a,d,l[4*(s+o)+e+r*c*4]/255)+127.5;h[m+f]=Math.max(0,Math.min(255,_))}}return yield new Promise(e=>{e({mode:0,data:r,hasVertexColors:!1,sh:p,shDegree:a})})}return yield new Promise(e=>{e({mode:0,data:r,hasVertexColors:!1})})})}(s,a,o)})}function Hl(e,n){return function(e,n,o,s){const r=new t.RawTexture(n,o,s,t.Constants.TEXTUREFORMAT_RGBA,e,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_UNSIGNED_BYTE);return r.wrapU=t.Constants.TEXTURE_CLAMP_ADDRESSMODE,r.wrapV=t.Constants.TEXTURE_CLAMP_ADDRESSMODE,r}(e,n.bits,n.width,n.height)}function Kl(e,n,o){return b(this,void 0,void 0,function*(){const s=o.getEngine();if("function"==typeof createImageBitmap)try{const r=n.toLowerCase().endsWith(".png")?"image/png":"image/webp";let i;if("string"==typeof e){const o=yield t.Tools.LoadFileAsync(e+n,!0);i=new Blob([o],{type:r})}else i=new Blob([e],{type:r});const a=yield createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});try{const e=new t.RawTexture(null,a.width,a.height,t.Constants.TEXTUREFORMAT_RGBA,o,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_UNSIGNED_BYTE);e.wrapU=t.Constants.TEXTURE_CLAMP_ADDRESSMODE,e.wrapV=t.Constants.TEXTURE_CLAMP_ADDRESSMODE;const n=e.getInternalTexture();return n&&s.updateDynamicTexture(n,a,!1,!1),e}finally{a.close()}}catch(e){}const r=yield Gl(e,n,s);return Hl(o,r)})}function Ul(e,n,o,s){const r=e=>Math.sign(e)*(Math.exp(Math.abs(e))-1);if(!Array.isArray(e.means.mins)||!Array.isArray(e.means.maxs))throw new Error("Missing arrays in SOG data.");const i=new Float32Array(4*s);for(let a=0;a<s;a++){const s=4*a;for(let l=0;l<3;l++){const u=o[s+l]<<8|n[s+l],c=t.Scalar.Lerp(e.means.mins[l],e.means.maxs[l],u/65535);i[4*a+l]=r(c)}i[4*a+3]=1}return i}function $l(e,n,o){return b(this,arguments,void 0,function*(e,n,o,s=!0,r,i){var a,l,u,c,d,h,m;let f,p;if(e instanceof Map){p=e;const t=p.get("meta.json");if(!t)throw new Error("meta.json not found in files Map");f=JSON.parse((new TextDecoder).decode(t))}else f=e;const _=e=>b(this,void 0,void 0,function*(){if(p&&p.has(e))return yield Gl(p.get(e),e,o.getEngine());if(r){const t=new Uint8Array(yield r.loadFileAsync(n+e,i));return yield Gl(t,e,o.getEngine())}return yield Gl(n,e,o.getEngine())}),g=e=>b(this,void 0,void 0,function*(){if(p&&p.has(e))return yield Kl(p.get(e),e,o);if(r){const t=new Uint8Array(yield r.loadFileAsync(n+e,i));return yield Kl(t,e,o)}return yield Kl(n,e,o)}),y=[...f.scales.files,...f.quats.files,...f.sh0.files,...null!==(l=null===(a=f.shN)||void 0===a?void 0:a.files)&&void 0!==l?l:[]];let v,x,T,A,M,w=null;if(s){const[e,t]=yield Promise.all([Promise.all(f.means.files.map(_)),Promise.all(y.map(g))]);w=[e[0],e[1]],M=t,v=Hl(o,e[0]),x=Hl(o,e[1]),T=e[0].width,A=e[0].height}else{const[e,t]=yield Promise.all([Promise.all(f.means.files.map(g)),Promise.all(y.map(g))]);M=t,v=e[0],x=e[1];const n=v.getSize();T=n.width,A=n.height}const C=null!==(u=f.count)&&void 0!==u?u:f.means.shape[0],R=T*A;if(R<C)throw new Error(`SOG texture contains ${R} texels, but metadata references ${C} splats.`);const O=M[0],S=M[1],F=M[2];let E,L,I,N=0,P=0;if(f.shN&&M.length>=5&&(E=M[3],L=M[4],N=f.shN.bands?Math.pow(f.shN.bands+1,2)-1:f.shN.shape[1]/3,P=null!==(c=f.shN.bands)&&void 0!==c?c:Math.round(Math.sqrt(N+1)-1)),2===f.version){const e=256,n=new Float32Array(3*e);f.scales.codebook&&n.set(f.scales.codebook.slice(0,e),0),f.sh0.codebook&&n.set(f.sh0.codebook.slice(0,e),e),(null===(d=f.shN)||void 0===d?void 0:d.codebook)&&n.set(f.shN.codebook.slice(0,e),2*e),I=new t.RawTexture(n,3*e,1,t.Constants.TEXTUREFORMAT_R,o,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_FLOAT),I.wrapU=t.Constants.TEXTURE_CLAMP_ADDRESSMODE,I.wrapV=t.Constants.TEXTURE_CLAMP_ADDRESSMODE}const B=f.means.mins,k=f.means.maxs,D={version:2===f.version?2:1,splatCount:C,shDegree:P,meansTextureL:v,meansTextureU:x,scalesTexture:O,quatsTexture:S,sh0Texture:F,shCentroidsTexture:E,shLabelsTexture:L,codebookTexture:I,meansMin:[B[0],B[1],B[2]],meansMax:[k[0],k[1],k[2]],scalesMin:Array.isArray(f.scales.mins)?[f.scales.mins[0],f.scales.mins[1],f.scales.mins[2]]:void 0,scalesMax:Array.isArray(f.scales.maxs)?[f.scales.maxs[0],f.scales.maxs[1],f.scales.maxs[2]]:void 0,sh0Min:Array.isArray(f.sh0.mins)?[f.sh0.mins[0],f.sh0.mins[1],f.sh0.mins[2],f.sh0.mins[3]]:void 0,sh0Max:Array.isArray(f.sh0.maxs)?[f.sh0.maxs[0],f.sh0.maxs[1],f.sh0.maxs[2],f.sh0.maxs[3]]:void 0,shnMin:"number"==typeof(null===(h=f.shN)||void 0===h?void 0:h.mins)?f.shN.mins:void 0,shnMax:"number"==typeof(null===(m=f.shN)||void 0===m?void 0:m.maxs)?f.shN.maxs:void 0,shCoeffCount:N,positions:w?Ul(f,w[0].bits,w[1].bits,C):new Float32Array(0)};return{mode:0,data:new ArrayBuffer(0),hasVertexColors:!1,shDegree:P,sogTextures:D}})}const Wl="precision highp float;\nattribute vec3 position;\nvoid main() {\n gl_Position = vec4(position.xy, 0.0, 1.0);\n}\n",zl="\nattribute position : vec3<f32>;\n@vertex\nfn main(input : VertexInputs) -> FragmentInputs {\n vertexOutputs.position = vec4<f32>(input.position.xy, 0.0, 1.0);\n}\n";class jl{get supportsAsyncCentersReadback(){var e;const t=this._scene.getEngine();if(t.isWebGPU)return!0;const n=t;return!!n._gl&&"function"==typeof n._readPixelsAsync&&(null!==(e=n.webGLVersion)&&void 0!==e?e:0)>=2}get textureSize(){return this._textureSize}get textures(){return this._mrt.textures}constructor(e,t){this._copyMaterial=null,this._relayoutMapData=null,this._relayoutMapTexture=null,this._disposed=!1,this._readFbo=null,this._scene=e,this._shaderLanguage=e.getEngine().isWebGPU?1:0,this._textureSize=Math.max(1,Math.ceil(Math.sqrt(Math.max(1,t)))),this._mrt=this._createMrt("gsWorkBuffer",!0),this._material=this._createMaterial(),this._quad=this._createQuad(),this._quad.material=this._material}_createMrt(e,n){const o=this._scene.getEngine()._caps.textureHalfFloatRender?t.Constants.TEXTURETYPE_HALF_FLOAT:t.Constants.TEXTURETYPE_FLOAT,s=new t.MultiRenderTarget(e,{width:this._textureSize,height:this._textureSize},4,this._scene,{types:[t.Constants.TEXTURETYPE_FLOAT,o,o,t.Constants.TEXTURETYPE_UNSIGNED_BYTE],samplingModes:[t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE],formats:[t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA],generateDepthBuffer:!1,generateDepthTexture:!1,generateMipMaps:!1},[`${e}Centers`,`${e}CovA`,`${e}CovB`,`${e}Colors`]);return s.clearColor=new t.Color4(0,0,0,0),s.renderList=[],n&&s.onClearObservable.add(()=>{}),s}decodeAsync(e,t){return b(this,void 0,void 0,function*(){this._disposed||(this._applyPack(e,t),yield new Promise(e=>{const t=()=>{this._disposed?e():this._material.isReady(this._quad)?(this._mrt.renderList=[this._quad],this._mrt.render(),e()):this._scene.onBeforeRenderObservable.addOnce(t)};this._scene.onBeforeRenderObservable.addOnce(t)}))})}isRelayoutReady(){return!this._disposed&&(this._copyMaterial||(this._copyMaterial=this._createCopyMaterial()),this._copyMaterial.isReady(this._quad))}relayoutSync(e){if(this._disposed||!this._copyMaterial)return;const n=this._textureSize;this._relayoutMapData||(this._relayoutMapData=new Float32Array(n*n));const o=this._relayoutMapData;o.fill(-1),o.set(e.subarray(0,Math.min(e.length,o.length))),this._relayoutMapTexture?this._relayoutMapTexture.update(o):this._relayoutMapTexture=new t.RawTexture(o,n,n,t.Constants.TEXTUREFORMAT_R,this._scene,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_FLOAT);const s=this._relayoutMapTexture,r=this._createMrt("gsRelayoutTemp",!1);try{this._renderRelayoutPass(r,this._mrt.textures,s,1),this._renderRelayoutPass(this._mrt,r.textures,s,0)}finally{r.dispose(),this._quad.material=this._material}}_renderRelayoutPass(e,t,n,o){const s=this._copyMaterial;s.setTexture("uMapTex",n),s.setTexture("uSrc0",t[0]),s.setTexture("uSrc1",t[1]),s.setTexture("uSrc2",t[2]),s.setTexture("uSrc3",t[3]),s.setInt("uDstWidth",this._textureSize),s.setInt("uSrcWidth",this._textureSize),s.setInt("uUseMap",o),this._quad.material=s,e.renderList=[this._quad],e.render()}_createCopyMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsWorkBufferRelayout",this._scene,{vertexSource:e?zl:Wl,fragmentSource:e?"\nvar uMapTexSampler : sampler;\nvar uMapTex : texture_2d<f32>;\nvar uSrc0Sampler : sampler;\nvar uSrc0 : texture_2d<f32>;\nvar uSrc1Sampler : sampler;\nvar uSrc1 : texture_2d<f32>;\nvar uSrc2Sampler : sampler;\nvar uSrc2 : texture_2d<f32>;\nvar uSrc3Sampler : sampler;\nvar uSrc3 : texture_2d<f32>;\n\nuniform uDstWidth : i32;\nuniform uSrcWidth : i32;\nuniform uUseMap : i32;\n\n@fragment\nfn main(input : FragmentInputs) -> FragmentOutputs {\n let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y));\n var srcIdx : i32;\n if (uniforms.uUseMap == 1) {\n let m : f32 = textureLoad(uMapTex, p, 0).r;\n if (m < 0.0) {\n discard;\n }\n srcIdx = i32(m + 0.5);\n } else {\n srcIdx = p.y * uniforms.uDstWidth + p.x;\n }\n let s : vec2<i32> = vec2<i32>(srcIdx - (srcIdx / uniforms.uSrcWidth) * uniforms.uSrcWidth, srcIdx / uniforms.uSrcWidth);\n fragmentOutputs.fragData0 = textureLoad(uSrc0, s, 0);\n fragmentOutputs.fragData1 = textureLoad(uSrc1, s, 0);\n fragmentOutputs.fragData2 = textureLoad(uSrc2, s, 0);\n fragmentOutputs.fragData3 = textureLoad(uSrc3, s, 0);\n}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D uMapTex;\nuniform sampler2D uSrc0;\nuniform sampler2D uSrc1;\nuniform sampler2D uSrc2;\nuniform sampler2D uSrc3;\nuniform int uDstWidth;\nuniform int uSrcWidth;\nuniform int uUseMap;\n\nlayout(location = 0) out vec4 glFragData[4];\n\nvoid main() {\n ivec2 p = ivec2(gl_FragCoord.xy);\n int srcIdx;\n if (uUseMap == 1) {\n float m = texelFetch(uMapTex, p, 0).r;\n if (m < 0.0) {\n discard;\n }\n srcIdx = int(m + 0.5);\n } else {\n srcIdx = p.y * uDstWidth + p.x;\n }\n ivec2 s = ivec2(srcIdx - (srcIdx / uSrcWidth) * uSrcWidth, srcIdx / uSrcWidth);\n glFragData[0] = texelFetch(uSrc0, s, 0);\n glFragData[1] = texelFetch(uSrc1, s, 0);\n glFragData[2] = texelFetch(uSrc2, s, 0);\n glFragData[3] = texelFetch(uSrc3, s, 0);\n}\n"},{attributes:["position"],uniforms:["uDstWidth","uSrcWidth","uUseMap"],samplers:["uMapTex","uSrc0","uSrc1","uSrc2","uSrc3"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}readCentersRangeAsync(e,t){return b(this,void 0,void 0,function*(){var n,o;if(this._disposed||t<=0||!this.supportsAsyncCentersReadback)return null;const s=this._textureSize,r=Math.floor(e/s),i=Math.ceil((e+t)/s)-r,a=4*(e-r*s),l=a+4*t,u=this._mrt.textures[0],c=this._scene.getEngine();if(c.isWebGPU){const e=yield u.readPixels(0,0,null,!0,!0,0,r,s,i);if(this._disposed||!e)return null;const t=e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.byteLength/4);return t.length>=l?t.subarray(a,l):null}const d=c,h=d._gl,m=null===(o=null===(n=u.getInternalTexture())||void 0===n?void 0:n._hardwareTexture)||void 0===o?void 0:o.underlyingResource;if(!m)return null;const f=new Float32Array(s*i*4);this._readFbo||(this._readFbo=h.createFramebuffer());const p=d._currentFramebuffer;h.bindFramebuffer(h.FRAMEBUFFER,this._readFbo),h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,h.TEXTURE_2D,m,0),h.readBuffer(h.COLOR_ATTACHMENT0);const _=d._readPixelsAsync(0,r,s,i,h.RGBA,h.FLOAT,f);return h.bindFramebuffer(h.FRAMEBUFFER,p),p||h.readBuffer(h.BACK),_?(yield _,this._disposed||f.length<l?null:f.subarray(a,l)):null})}dispose(){var e,t,n;this._disposed=!0,this._readFbo&&(null===(e=this._scene.getEngine()._gl)||void 0===e||e.deleteFramebuffer(this._readFbo),this._readFbo=null),this._quad.dispose(),this._material.dispose(!0,!1),null===(t=this._copyMaterial)||void 0===t||t.dispose(!0,!1),null===(n=this._relayoutMapTexture)||void 0===n||n.dispose(),this._mrt.dispose()}_createQuad(){const e=new t.Mesh("gsWorkBufferQuad",this._scene),n=new t.VertexData;return n.positions=[-1,-1,0,3,-1,0,-1,3,0],n.indices=[0,1,2],n.applyToMesh(e),this._scene.removeMesh(e),e}_createMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsSogDecode",this._scene,{vertexSource:e?zl:Wl,fragmentSource:e?"\nvar sogMeansLTexSampler : sampler;\nvar sogMeansLTex : texture_2d<f32>;\nvar sogMeansUTexSampler : sampler;\nvar sogMeansUTex : texture_2d<f32>;\nvar sogScalesTexSampler : sampler;\nvar sogScalesTex : texture_2d<f32>;\nvar sogQuatsTexSampler : sampler;\nvar sogQuatsTex : texture_2d<f32>;\nvar sogSh0TexSampler : sampler;\nvar sogSh0Tex : texture_2d<f32>;\nvar sogCodebookTexSampler : sampler;\nvar sogCodebookTex : texture_2d<f32>;\n\nuniform sogMeansMin : vec3<f32>;\nuniform sogMeansMax : vec3<f32>;\nuniform sogScalesMin : vec3<f32>;\nuniform sogScalesMax : vec3<f32>;\nuniform sogSh0Min : vec4<f32>;\nuniform sogSh0Max : vec4<f32>;\nuniform uVersion : i32;\nuniform uOffset : i32;\nuniform uCount : i32;\nuniform uDestWidth : i32;\nuniform uSrcWidth : i32;\n\n@fragment\nfn main(input : FragmentInputs) -> FragmentOutputs {\n let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y));\n let global : i32 = p.y * uniforms.uDestWidth + p.x;\n if (global < uniforms.uOffset || global >= uniforms.uOffset + uniforms.uCount) {\n discard;\n }\n let k : i32 = global - uniforms.uOffset;\n let src : vec2<i32> = vec2<i32>(k - (k / uniforms.uSrcWidth) * uniforms.uSrcWidth, k / uniforms.uSrcWidth);\n\n let mL : vec3<f32> = textureLoad(sogMeansLTex, src, 0).xyz;\n let mU : vec3<f32> = textureLoad(sogMeansUTex, src, 0).xyz;\n let sRaw : vec3<f32> = textureLoad(sogScalesTex, src, 0).xyz;\n let qRaw : vec4<f32> = textureLoad(sogQuatsTex, src, 0);\n let c0 : vec4<f32> = textureLoad(sogSh0Tex, src, 0);\n\n let q16 : vec3<f32> = (mU * 256.0 + mL) * (255.0 / 65535.0);\n let nPos : vec3<f32> = mix(uniforms.sogMeansMin, uniforms.sogMeansMax, q16);\n let center : vec3<f32> = sign(nPos) * (exp(abs(nPos)) - vec3<f32>(1.0));\n\n var splatScale : vec3<f32>;\n if (uniforms.uVersion == 2) {\n let sIdx : vec3<f32> = floor(sRaw * 255.0 + 0.5);\n splatScale.x = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.x), 0), 0).r);\n splatScale.y = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.y), 0), 0).r);\n splatScale.z = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.z), 0), 0).r);\n } else {\n splatScale = exp(mix(uniforms.sogScalesMin, uniforms.sogScalesMax, sRaw));\n }\n\n let invSqrt2 : f32 = 0.70710678118;\n let qabc : vec3<f32> = (qRaw.xyz - vec3<f32>(0.5)) * 2.0 * invSqrt2;\n let qMode : i32 = i32(qRaw.w * 255.0 + 0.5) - 252;\n let qd : f32 = sqrt(max(0.0, 1.0 - dot(qabc, qabc)));\n var quat : vec4<f32>;\n if (qMode == 0) {\n quat = vec4<f32>(qd, qabc.x, qabc.y, qabc.z);\n } else if (qMode == 1) {\n quat = vec4<f32>(qabc.x, qd, qabc.y, qabc.z);\n } else if (qMode == 2) {\n quat = vec4<f32>(qabc.x, qabc.y, qd, qabc.z);\n } else {\n quat = vec4<f32>(qabc.x, qabc.y, qabc.z, qd);\n }\n\n let qw : f32 = quat.x;\n let qx : f32 = quat.y;\n let qy : f32 = quat.z;\n let qz : f32 = quat.w;\n let R : mat3x3<f32> = mat3x3<f32>(\n 1.0 - 2.0 * (qy * qy + qz * qz), 2.0 * (qx * qy + qw * qz), 2.0 * (qx * qz - qw * qy),\n 2.0 * (qx * qy - qw * qz), 1.0 - 2.0 * (qx * qx + qz * qz), 2.0 * (qy * qz + qw * qx),\n 2.0 * (qx * qz + qw * qy), 2.0 * (qy * qz - qw * qx), 1.0 - 2.0 * (qx * qx + qy * qy)\n );\n let S2 : mat3x3<f32> = mat3x3<f32>(\n 4.0 * splatScale.x * splatScale.x, 0.0, 0.0,\n 0.0, 4.0 * splatScale.y * splatScale.y, 0.0,\n 0.0, 0.0, 4.0 * splatScale.z * splatScale.z\n );\n let Sigma : mat3x3<f32> = R * S2 * transpose(R);\n\n let SH_C0 : f32 = 0.28209479177387814;\n var colRgb : vec3<f32>;\n var colA : f32;\n if (uniforms.uVersion == 2) {\n var c3 : vec3<f32>;\n c3.x = textureLoad(sogCodebookTex, vec2<i32>(256 + i32(c0.x * 255.0 + 0.5), 0), 0).r;\n c3.y = textureLoad(sogCodebookTex, vec2<i32>(256 + i32(c0.y * 255.0 + 0.5), 0), 0).r;\n c3.z = textureLoad(sogCodebookTex, vec2<i32>(256 + i32(c0.z * 255.0 + 0.5), 0), 0).r;\n colRgb = vec3<f32>(0.5) + c3 * SH_C0;\n colA = c0.w;\n } else {\n let cLerp : vec4<f32> = mix(uniforms.sogSh0Min, uniforms.sogSh0Max, c0);\n colRgb = vec3<f32>(0.5) + cLerp.xyz * SH_C0;\n colA = 1.0 / (1.0 + exp(-cLerp.w));\n }\n\n fragmentOutputs.fragData0 = vec4<f32>(center, 1.0);\n fragmentOutputs.fragData1 = vec4<f32>(Sigma[0][0], Sigma[0][1], Sigma[0][2], Sigma[1][1]);\n fragmentOutputs.fragData2 = vec4<f32>(Sigma[1][2], Sigma[2][2], 0.0, 0.0);\n fragmentOutputs.fragData3 = vec4<f32>(colRgb, colA);\n}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D sogMeansLTex;\nuniform sampler2D sogMeansUTex;\nuniform sampler2D sogScalesTex;\nuniform sampler2D sogQuatsTex;\nuniform sampler2D sogSh0Tex;\nuniform sampler2D sogCodebookTex;\n\nuniform vec3 sogMeansMin;\nuniform vec3 sogMeansMax;\nuniform vec3 sogScalesMin;\nuniform vec3 sogScalesMax;\nuniform vec4 sogSh0Min;\nuniform vec4 sogSh0Max;\nuniform int uVersion;\nuniform int uOffset;\nuniform int uCount;\nuniform int uDestWidth;\nuniform int uSrcWidth;\n\nlayout(location = 0) out vec4 glFragData[4];\n\nmat3 transposeM(mat3 m) {\n return mat3(m[0][0], m[1][0], m[2][0], m[0][1], m[1][1], m[2][1], m[0][2], m[1][2], m[2][2]);\n}\n\nvoid main() {\n ivec2 p = ivec2(gl_FragCoord.xy);\n int global = p.y * uDestWidth + p.x;\n if (global < uOffset || global >= uOffset + uCount) {\n discard;\n }\n int k = global - uOffset;\n ivec2 src = ivec2(k - (k / uSrcWidth) * uSrcWidth, k / uSrcWidth);\n\n vec3 mL = texelFetch(sogMeansLTex, src, 0).xyz;\n vec3 mU = texelFetch(sogMeansUTex, src, 0).xyz;\n vec3 sRaw = texelFetch(sogScalesTex, src, 0).xyz;\n vec4 qRaw = texelFetch(sogQuatsTex, src, 0);\n vec4 c0 = texelFetch(sogSh0Tex, src, 0);\n\n // Position: q16 = (u<<8)|l normalized; n = lerp(min,max,q16); pos = sign(n)*(exp(|n|)-1)\n vec3 q16 = (mU * 256.0 + mL) * (255.0 / 65535.0);\n vec3 nPos = mix(sogMeansMin, sogMeansMax, q16);\n vec3 center = sign(nPos) * (exp(abs(nPos)) - vec3(1.0));\n\n // Scale (v1: lerp+exp ; v2: codebook lookup)\n vec3 splatScale;\n if (uVersion == 2) {\n vec3 sIdx = floor(sRaw * 255.0 + 0.5);\n splatScale.x = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.x), 0), 0).r);\n splatScale.y = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.y), 0), 0).r);\n splatScale.z = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.z), 0), 0).r);\n } else {\n splatScale = exp(mix(sogScalesMin, sogScalesMax, sRaw));\n }\n\n // Quaternion (largest-omitted, mode in alpha as 252 + omitted-index)\n const float invSqrt2 = 0.70710678118;\n vec3 qabc = (qRaw.xyz - vec3(0.5)) * 2.0 * invSqrt2;\n int qMode = int(qRaw.w * 255.0 + 0.5) - 252;\n float qd = sqrt(max(0.0, 1.0 - dot(qabc, qabc)));\n vec4 quat;\n if (qMode == 0) {\n quat = vec4(qd, qabc.x, qabc.y, qabc.z);\n } else if (qMode == 1) {\n quat = vec4(qabc.x, qd, qabc.y, qabc.z);\n } else if (qMode == 2) {\n quat = vec4(qabc.x, qabc.y, qd, qabc.z);\n } else {\n quat = vec4(qabc.x, qabc.y, qabc.z, qd);\n }\n\n float qw = quat.x, qx = quat.y, qy = quat.z, qz = quat.w;\n mat3 R = mat3(\n 1.0 - 2.0 * (qy * qy + qz * qz), 2.0 * (qx * qy + qw * qz), 2.0 * (qx * qz - qw * qy),\n 2.0 * (qx * qy - qw * qz), 1.0 - 2.0 * (qx * qx + qz * qz), 2.0 * (qy * qz + qw * qx),\n 2.0 * (qx * qz + qw * qy), 2.0 * (qy * qz - qw * qx), 1.0 - 2.0 * (qx * qx + qy * qy)\n );\n mat3 S2 = mat3(\n 4.0 * splatScale.x * splatScale.x, 0.0, 0.0,\n 0.0, 4.0 * splatScale.y * splatScale.y, 0.0,\n 0.0, 0.0, 4.0 * splatScale.z * splatScale.z\n );\n mat3 Sigma = R * S2 * transposeM(R);\n\n // Color (sh0)\n const float SH_C0 = 0.28209479177387814;\n vec3 colRgb;\n float colA;\n if (uVersion == 2) {\n vec3 c3;\n c3.x = texelFetch(sogCodebookTex, ivec2(256 + int(c0.x * 255.0 + 0.5), 0), 0).r;\n c3.y = texelFetch(sogCodebookTex, ivec2(256 + int(c0.y * 255.0 + 0.5), 0), 0).r;\n c3.z = texelFetch(sogCodebookTex, ivec2(256 + int(c0.z * 255.0 + 0.5), 0), 0).r;\n colRgb = vec3(0.5) + c3 * SH_C0;\n colA = c0.w;\n } else {\n vec4 cLerp = mix(sogSh0Min, sogSh0Max, c0);\n colRgb = vec3(0.5) + cLerp.xyz * SH_C0;\n colA = 1.0 / (1.0 + exp(-cLerp.w));\n }\n\n glFragData[0] = vec4(center, 1.0);\n glFragData[1] = vec4(Sigma[0][0], Sigma[0][1], Sigma[0][2], Sigma[1][1]);\n glFragData[2] = vec4(Sigma[1][2], Sigma[2][2], 0.0, 0.0);\n glFragData[3] = vec4(colRgb, colA);\n}\n"},{attributes:["position"],uniforms:["sogMeansMin","sogMeansMax","sogScalesMin","sogScalesMax","sogSh0Min","sogSh0Max","uVersion","uOffset","uCount","uDestWidth","uSrcWidth"],samplers:["sogMeansLTex","sogMeansUTex","sogScalesTex","sogQuatsTex","sogSh0Tex","sogCodebookTex"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_applyPack(e,n){var o,s,r,i,a;const l=this._material,u=e.meansTextureL.getSize().width;l.setTexture("sogMeansLTex",e.meansTextureL),l.setTexture("sogMeansUTex",e.meansTextureU),l.setTexture("sogScalesTex",e.scalesTexture),l.setTexture("sogQuatsTex",e.quatsTexture),l.setTexture("sogSh0Tex",e.sh0Texture),l.setTexture("sogCodebookTex",null!==(o=e.codebookTexture)&&void 0!==o?o:e.sh0Texture),l.setVector3("sogMeansMin",new t.Vector3(e.meansMin[0],e.meansMin[1],e.meansMin[2])),l.setVector3("sogMeansMax",new t.Vector3(e.meansMax[0],e.meansMax[1],e.meansMax[2]));const c=null!==(s=e.scalesMin)&&void 0!==s?s:[0,0,0],d=null!==(r=e.scalesMax)&&void 0!==r?r:[0,0,0];l.setVector3("sogScalesMin",new t.Vector3(c[0],c[1],c[2])),l.setVector3("sogScalesMax",new t.Vector3(d[0],d[1],d[2]));const h=null!==(i=e.sh0Min)&&void 0!==i?i:[0,0,0,0],m=null!==(a=e.sh0Max)&&void 0!==a?a:[0,0,0,0];l.setVector4("sogSh0Min",new t.Vector4(h[0],h[1],h[2],h[3])),l.setVector4("sogSh0Max",new t.Vector4(m[0],m[1],m[2],m[3])),l.setInt("uVersion",e.version),l.setInt("uOffset",n),l.setInt("uCount",e.splatCount),l.setInt("uDestWidth",this._textureSize),l.setInt("uSrcWidth",u)}}class ql{constructor(e){var t,n;this._activeCount=0,this._queue=[],this._pending=new Map,this._groups=new Map,this._disposed=!1,this.maxConcurrent=Math.max(1,null!==(t=null==e?void 0:e.maxConcurrent)&&void 0!==t?t:2),this.maxRetries=Math.max(0,null!==(n=null==e?void 0:e.maxRetries)&&void 0!==n?n:2)}get isIdle(){return 0===this._pending.size}loadFileAsync(e,t){return b(this,void 0,void 0,function*(){if(this._disposed)throw new Error("GaussianSplattingDownloadManager has been disposed.");const n=this._pending.get(e);if(n)return yield n.promise;const o={url:e,groupId:t,settled:!1,cancelled:!1,started:!1,slotReleased:!1};if(o.promise=new Promise((e,t)=>{o.resolve=e,o.reject=t}),this._pending.set(e,o),void 0!==t){let n=this._groups.get(t);n||(n=new Set,this._groups.set(t,n)),n.add(e)}return this._queue.push(o),this._pump(),yield o.promise})}cancel(e){const t=this._pending.get(e);t&&this._abort(t,new Error(`GaussianSplattingDownloadManager: download cancelled (${e}).`))}cancelGroup(e){const t=this._groups.get(e);if(t){for(const e of Array.from(t))this.cancel(e);this._groups.delete(e)}}dispose(){if(!this._disposed){this._disposed=!0,this._queue.length=0;for(const e of Array.from(this._pending.values()))this._abort(e,new Error("GaussianSplattingDownloadManager has been disposed."))}}_abort(e,t){var n,o;if(e.settled)return;e.cancelled=!0;const s=this._queue.indexOf(e);-1!==s&&this._queue.splice(s,1),null===(n=e.request)||void 0===n||n.abort(),null===(o=e.cancelAttempt)||void 0===o||o.call(e,t),this._settle(e,()=>e.reject(t)),e.started&&this._releaseSlot(e)}_settle(e,t){if(!e.settled){if(e.settled=!0,this._pending.delete(e.url),void 0!==e.groupId){const t=this._groups.get(e.groupId);t&&(t.delete(e.url),0===t.size&&this._groups.delete(e.groupId))}t()}}_releaseSlot(e){e.slotReleased||(e.slotReleased=!0,this._activeCount--,this._pump())}_pump(){for(;!this._disposed&&this._activeCount<this.maxConcurrent&&this._queue.length>0;){const e=this._queue.shift();e.settled||(e.started=!0,this._activeCount++,this._runTaskAsync(e).finally(()=>{this._releaseSlot(e)}))}}_runTaskAsync(e){return b(this,void 0,void 0,function*(){let t;for(let n=0;n<=this.maxRetries;n++){if(this._disposed||e.cancelled)return;try{const t=yield this._downloadAttemptAsync(e);return void this._settle(e,()=>e.resolve(t))}catch(n){if(e.cancelAttempt=void 0,this._disposed||e.cancelled)return;t=n}}this._settle(e,()=>e.reject(t))})}_downloadAttemptAsync(e){return b(this,void 0,void 0,function*(){return yield new Promise((n,o)=>{e.cancelAttempt=o,e.request=t.Tools.LoadFile(e.url,e=>n(e),void 0,void 0,!0,(t,n)=>o(n instanceof Error?n:new Error(`GaussianSplattingDownloadManager: failed to load ${e.url}.`)))})})}}class Xl{constructor(){this._offset=0,this._size=0,this._free=!0,this._prev=null,this._next=null,this._prevFree=null,this._nextFree=null,this._bucket=-1}get offset(){return this._offset}get size(){return this._size}}class Yl{constructor(e=0,t=1.1){if(this._headAll=null,this._tailAll=null,this._freeBucketHeads=[],this._pool=[],this._capacity=0,this._usedSize=0,this._freeSize=0,this._freeRegionCount=0,this._growMultiplier=t,e>0){this._capacity=e,this._freeSize=e;const t=this._obtain(0,e,!0);this._headAll=t,this._tailAll=t,this._addToBucket(t)}}get capacity(){return this._capacity}get usedSize(){return this._usedSize}get freeSize(){return this._freeSize}get fragmentation(){return this._freeSize>0?1-1/this._freeRegionCount:0}allocate(e){if(e<=0)return null;const t=this._findFreeBlock(e);if(!t)return null;if(this._usedSize+=e,this._freeSize-=e,t._size===e)return t._free=!1,this._removeFromBucket(t),t;const n=this._obtain(t._offset,e,!1);return t._offset+=e,t._size-=e,this._rebucket(t),this._insertAfterInMainList(n,t._prev),n}free(e){if(!e||e._free)return;e._free=!0,this._usedSize-=e._size,this._freeSize+=e._size;const t=e._prev,n=e._next,o=t&&t._free,s=n&&n._free;o&&s?(t._size+=e._size+n._size,this._removeFromMainList(e),this._removeFromMainList(n),this._removeFromBucket(n),this._release(e),this._release(n),this._rebucket(t)):o?(t._size+=e._size,this._removeFromMainList(e),this._release(e),this._rebucket(t)):s?(e._size+=n._size,this._removeFromMainList(n),this._removeFromBucket(n),this._release(n),this._addToBucket(e)):this._addToBucket(e)}grow(e){if(e<=this._capacity)return;const t=e-this._capacity;if(this._capacity=e,this._freeSize+=t,this._tailAll&&this._tailAll._free)this._tailAll._size+=t,this._rebucket(this._tailAll);else{const e=this._obtain(this._capacity-t,t,!0);this._insertAfterInMainList(e,this._tailAll),this._addToBucket(e)}}defrag(e=0,t=new Set){return t.clear(),0===this._freeRegionCount||(0===e?this._defragFull(t):this._defragIncremental(e,t)),t}updateAllocation(e,t){for(let t=0;t<e.length;t++)this.free(e[t]);for(let e=0;e<t.length;e++){const n=t[e],o=this.allocate(n);if(!o){let o=n;for(let n=e+1;n<t.length;n++)o+=t[n];const s=this._usedSize+o,r=Math.ceil(s*this._growMultiplier);r>this._capacity&&this.grow(r),this.defrag(0);for(let n=e;n<t.length;n++)t[n]=this.allocate(t[n]);return!0}t[e]=o}return!1}_bucketFor(e){return 31-Math.clz32(e)}_addToBucket(e){const t=this._bucketFor(e._size);for(e._bucket=t;t>=this._freeBucketHeads.length;)this._freeBucketHeads.push(null);e._prevFree=null,e._nextFree=this._freeBucketHeads[t],this._freeBucketHeads[t]&&(this._freeBucketHeads[t]._prevFree=e),this._freeBucketHeads[t]=e,this._freeRegionCount++}_removeFromBucket(e){const t=e._bucket;e._prevFree?e._prevFree._nextFree=e._nextFree:this._freeBucketHeads[t]=e._nextFree,e._nextFree&&(e._nextFree._prevFree=e._prevFree),e._prevFree=null,e._nextFree=null,e._bucket=-1,this._freeRegionCount--}_rebucket(e){this._bucketFor(e._size)!==e._bucket&&(this._removeFromBucket(e),this._addToBucket(e))}_obtain(e,t,n){const o=this._pool.length>0?this._pool.pop():new Xl;return o._offset=e,o._size=t,o._free=n,o._prev=null,o._next=null,o._prevFree=null,o._nextFree=null,o._bucket=-1,o}_release(e){e._prev=null,e._next=null,e._prevFree=null,e._nextFree=null,e._bucket=-1,this._pool.push(e)}_insertAfterInMainList(e,t){null===t?(e._prev=null,e._next=this._headAll,this._headAll&&(this._headAll._prev=e),this._headAll=e,this._tailAll||(this._tailAll=e)):(e._prev=t,e._next=t._next,t._next&&(t._next._prev=e),t._next=e,this._tailAll===t&&(this._tailAll=e))}_removeFromMainList(e){e._prev?e._prev._next=e._next:this._headAll=e._next,e._next?e._next._prev=e._prev:this._tailAll=e._prev,e._prev=null,e._next=null}_findFreeBlock(e){const t=this._bucketFor(e),n=this._freeBucketHeads.length;if(t<n){let n=null,o=this._freeBucketHeads[t];for(;o&&!(o._size>=e&&(!n||o._size<n._size)&&(n=o,o._size===e));)o=o._nextFree;if(n)return n}for(let e=t+1;e<n;e++)if(this._freeBucketHeads[e])return this._freeBucketHeads[e];return null}_defragFull(e){for(let e=0;e<this._freeBucketHeads.length;e++){let t=this._freeBucketHeads[e];for(;t;){const e=t._nextFree;this._removeFromMainList(t),t._prevFree=null,t._nextFree=null,t._bucket=-1,this._pool.push(t),t=e}this._freeBucketHeads[e]=null}this._freeRegionCount=0;let t=0,n=this._headAll;for(;n;)n._offset!==t&&(n._offset=t,e.add(n)),t+=n._size,n=n._next;const o=this._capacity-t;if(o>0){const e=this._obtain(t,o,!0);this._insertAfterInMainList(e,this._tailAll),this._addToBucket(e)}}_defragIncremental(e,t){const n=Math.ceil(e/2),o=e-n;for(let e=0;e<n;e++){let e=this._tailAll;for(;e&&e._free;)e=e._prev;if(!e)break;const n=this._findFreeBlock(e._size);if(!n||n._offset>=e._offset)break;this._moveBlock(e,n),t.add(e)}let s=this._headAll;for(let e=0;e<o&&s;){const n=s._next;if(s._free&&n&&!n._free){const o=n,r=s;o._offset=r._offset,r._offset=o._offset+o._size;const i=r._prev,a=o._next;if(o._prev=i,o._next=r,r._prev=o,r._next=a,i?i._next=o:this._headAll=o,a?a._prev=r:this._tailAll=r,r._next&&r._next._free){const e=r._next;r._size+=e._size,this._removeFromMainList(e),this._removeFromBucket(e),this._release(e),this._rebucket(r)}t.add(o),e++,s=r._next}else s=n}}_moveBlock(e,t){const n=e._size,o=t._offset,s=e._prev;this._removeFromMainList(e);const r=this._obtain(e._offset,n,!0);if(this._insertAfterInMainList(r,s),this._addToBucket(r),r._next&&r._next._free){const e=r._next;r._size+=e._size,this._removeFromMainList(e),this._removeFromBucket(e),this._release(e),this._rebucket(r)}if(r._prev&&r._prev._free){const e=r._prev;e._size+=r._size,this._removeFromMainList(r),this._removeFromBucket(r),this._release(r),this._rebucket(e)}if(e._offset=o,t._size===n){const n=t._prev;this._removeFromMainList(t),this._removeFromBucket(t),this._release(t),this._insertAfterInMainList(e,n)}else t._offset+=n,t._size-=n,this._rebucket(t),this._insertAfterInMainList(e,t._prev)}}class Ql{constructor(e,t,n){this._blocks=new Map,this._cooldown=new Map,this._pinned=new Set,this._allocator=new Yl(e),this._cooldownFrames=Math.max(0,t),this._onEvict=n}get capacity(){return this._allocator.capacity}get residentCount(){return this._blocks.size}get freeSize(){return this._allocator.freeSize}has(e){return this._blocks.has(e)}offset(e){var t;return null===(t=this._blocks.get(e))||void 0===t?void 0:t.offset}allocate(e,t){const n=this._blocks.get(e);if(n)return n.offset;let o=this._allocator.allocate(t);return o||(this._evictAllCooled(),o=this._allocator.allocate(t),o)?(this._blocks.set(e,o),o.offset):null}pin(e,t){const n=this.allocate(e,t);return null!==n&&this._pinned.add(e),n}free(e){if(this._pinned.has(e))return;const t=this._blocks.get(e);t&&(this._allocator.free(t),this._blocks.delete(e),this._cooldown.delete(e))}compact(){const e=new Map;for(const[t,n]of Array.from(this._blocks))e.set(t,n.offset);this._allocator.defrag(0);const t=[];for(const[n,o]of Array.from(this._blocks)){const s=e.get(n);s!==o.offset&&t.push({file:n,oldOffset:s,newOffset:o.offset,count:o.size})}return t}getResidentBlocks(){const e=[];for(const[t,n]of Array.from(this._blocks))e.push({file:t,offset:n.offset,count:n.size});return e}scheduleEviction(e){!this._pinned.has(e)&&this._blocks.has(e)&&this._cooldown.set(e,this._cooldownFrames)}cancelEviction(e){this._cooldown.delete(e)}tick(){if(0===this._cooldown.size)return[];const e=[];for(const[t,n]of Array.from(this._cooldown))n<=1?e.push(t):this._cooldown.set(t,n-1);for(const t of e)this._evict(t);return e}dispose(){this._blocks.clear(),this._cooldown.clear(),this._pinned.clear()}_evictAllCooled(){const e=Array.from(this._cooldown.keys());for(const t of e)this._evict(t)}_evict(e){const t=this._blocks.get(e);t&&(this._allocator.free(t),this._blocks.delete(e)),this._cooldown.delete(e),this._onEvict(e)}}const Zl=Math.tan(22.5*Math.PI/180),Jl=new t.Matrix,eu=new t.Vector3,tu=new t.Vector3,nu=new t.Vector3,ou=new t.Vector3(0,0,1),su=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]],ru=2*su.length,iu=[new t.Color4(1,.2,.2,1),new t.Color4(1,.6,.1,1),new t.Color4(1,1,.2,1),new t.Color4(.3,1,.3,1),new t.Color4(.2,1,1,1),new t.Color4(.4,.5,1,1),new t.Color4(.9,.4,1,1),new t.Color4(1,1,1,1)];class au extends t.GaussianSplattingMesh{static IsLODMetadata(e){if("object"!=typeof e||null===e)return!1;const t=e;return"number"==typeof t.lodLevels&&Array.isArray(t.filenames)&&"object"==typeof t.tree&&null!==t.tree}constructor(e,n,o,s,r={}){super(e,null,s,!1),this._leafNodes=[],this._lodBaseDistance=5,this._lodMultiplier=3,this._lodBehindPenalty=1,this._lodRangeMin=0,this._maxDecodesPerFrame=1,this._lodCooldownFrames=10,this._lodUpdateInterval=4,this._lodUpdateDistance=.5,this._maxDetailLod=0,this._frustumCulling=!0,this._frustumPlanes=[new t.Plane(0,0,0,0),new t.Plane(0,0,0,0),new t.Plane(0,0,0,0),new t.Plane(0,0,0,0),new t.Plane(0,0,0,0),new t.Plane(0,0,0,0)],this._cullViewProj=new t.Matrix,this._workBuffer=null,this._useGpuPositionReadback=!1,this._readbackCandidate=!1,this._readbackProbed=!1,this._residency=null,this._fileCounts=new Map,this._fileMeta=new Map,this._decodedFiles=new Set,this._loadingFiles=new Set,this._decodeQueue=[],this._fileRefs=new Map,this._cancelledDecodes=new Set,this._evictionEnabled=!1,this._residentBudget=0,this._evictionCooldownFrames=100,this._decodeGate=Promise.resolve(),this._relayoutOldOffsets=new Map,this._relayoutSrcIndex=null,this._environmentRange=null,this._environmentFiles=null,this._lodObserver=null,this._baseLayerReady=!1,this._framesSinceLodUpdate=0,this._lastLodCamPos=new t.Vector3(1/0,1/0,1/0),this._forceLodUpdate=!1,this._boundsMin=new t.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._boundsMax=new t.Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._debugDisplay=!1,this._debugLodSource="optimal",this._debugMesh=null,this._debugObserver=null,this._debugColorData=null,this._debugSignature=0,this._disposed=!1,this._metadata=n,this._rootUrl=o,this._streamOptions=r;const i=Math.max(0,n.lodLevels-1);this._lodRangeMax=i,void 0!==r.lodBaseDistance&&(this._lodBaseDistance=Math.max(.1,r.lodBaseDistance)),void 0!==r.lodMultiplier&&(this._lodMultiplier=Math.max(1.2,r.lodMultiplier)),void 0!==r.lodBehindPenalty&&(this._lodBehindPenalty=Math.max(1,r.lodBehindPenalty)),void 0!==r.lodRangeMin&&(this._lodRangeMin=Math.max(0,Math.min(r.lodRangeMin,i))),void 0!==r.lodRangeMax&&(this._lodRangeMax=Math.max(this._lodRangeMin,Math.min(r.lodRangeMax,i))),void 0!==r.maxDecodesPerFrame&&(this._maxDecodesPerFrame=Math.max(1,r.maxDecodesPerFrame)),void 0!==r.lodCooldownFrames&&(this._lodCooldownFrames=Math.max(0,r.lodCooldownFrames)),void 0!==r.lodUpdateInterval&&(this._lodUpdateInterval=Math.max(1,r.lodUpdateInterval)),void 0!==r.lodUpdateDistance&&(this._lodUpdateDistance=Math.max(0,r.lodUpdateDistance)),void 0!==r.maxDetailLod&&(this._maxDetailLod=Math.max(0,Math.floor(r.maxDetailLod))),void 0!==r.frustumCulling&&(this._frustumCulling=r.frustumCulling),r.debugLodSource&&(this._debugLodSource=r.debugLodSource),void 0!==r.evictionCooldownFrames&&(this._evictionCooldownFrames=Math.max(0,Math.floor(r.evictionCooldownFrames)));let a=0;if(void 0!==r.maxResidentSplats&&r.maxResidentSplats>0&&(a=Math.floor(r.maxResidentSplats)),void 0!==r.memoryBudgetMb&&r.memoryBudgetMb>0){const e=Math.floor(1024*r.memoryBudgetMb*1024/84);a=a>0?Math.min(a,e):e}this._residentBudget=a,this._downloadManager=new ql({maxConcurrent:r.maxConcurrentDownloads,maxRetries:r.maxDownloadRetries}),this.scaling.y*=-1,this.rotation.x=-Math.PI/2,this._collectLodEntries(n.tree),r.debugDisplay&&(this.debugDisplay=!0),this._streamAllAsync().catch(e=>{var n;t.Logger.Error("GaussianSplattingStream: streaming failed: "+(null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e))})}getClassName(){return"GaussianSplattingStream"}whenSettledAsync(){return b(this,arguments,void 0,function*(e=3){if(this._disposed)return;this._forceLodUpdate=!0;const t=Math.max(1,e),n=this._scene;let o=0;const s=()=>this._isLoadingIdle()&&this._isDepthSortSettled?++o>=t:(o=0,!1);if(n.getEngine().activeRenderLoops.length>0)return void(yield new Promise(e=>{let t=null;t=n.onAfterRenderObservable.add(()=>{(this._disposed||s())&&(t&&(n.onAfterRenderObservable.remove(t),t=null),e())})}));const r=n.getEngine(),i=globalThis.requestAnimationFrame;for(;!this._disposed;){if(r.beginFrame(),n.render(),r.endFrame(),s())return;yield new Promise(e=>{"function"==typeof i?i(()=>e()):setTimeout(e,16)})}})}_isLoadingIdle(){return this._baseLayerReady&&0===this._decodeQueue.length&&0===this._loadingFiles.size&&this._downloadManager.isIdle}get maxDetailLod(){return this._maxDetailLod}set maxDetailLod(e){const t=Math.max(0,Math.floor(e));this._maxDetailLod!==t&&(this._maxDetailLod=t,this._forceLodUpdate=!0)}get maxLodLevel(){return Math.max(0,this._metadata.lodLevels-1)}get frustumCulling(){return this._frustumCulling}set frustumCulling(e){this._frustumCulling!==e&&(this._frustumCulling=e,this._forceLodUpdate=!0)}get debugDisplay(){return this._debugDisplay}set debugDisplay(e){this._debugDisplay!==e&&(this._debugDisplay=e,e?this._refreshDebugDisplay():this._clearDebugDisplay())}get debugLodSource(){return this._debugLodSource}set debugLodSource(e){this._debugLodSource!==e&&(this._debugLodSource=e,this._debugDisplay&&this._refreshDebugDisplay())}dispose(e){var t,n;this._disposed=!0,this._lodObserver&&(this._scene.onBeforeRenderObservable.remove(this._lodObserver),this._lodObserver=null),this._clearDebugDisplay(),this._downloadManager.dispose(),null===(t=this._residency)||void 0===t||t.dispose(),this._residency=null,null===(n=this._workBuffer)||void 0===n||n.dispose(),this._workBuffer=null,super.dispose(e)}evaluateOptimalLods(e=this._scene.activeCamera){if(!e||0===this._leafNodes.length)return;const n=Math.max(0,this._metadata.lodLevels-1),o=this._lodBaseDistance,s=this._lodMultiplier,r=this._lodBehindPenalty,i=this._lodRangeMin,a=this._lodRangeMax,l=this._scene.getEngine().getAspectRatio(e)||1;let u=Math.tan(.5*e.fov);e.fovMode===t.Camera.FOVMODE_HORIZONTAL_FIXED&&(u/=l);const c=u*l,d=Math.min(u,c)/Zl;this.computeWorldMatrix(!1).invertToRef(Jl);const h=t.Vector3.TransformCoordinatesToRef(e.globalPosition,Jl,eu),m=h.x,f=h.y,p=h.z;let _=0,g=0,y=0;if(r>1){e.getDirectionToRef(ou,nu);const n=t.Vector3.TransformNormalToRef(nu,Jl,tu);n.normalize(),_=n.x,g=n.y,y=n.z}for(const e of this._leafNodes){const t=e.bound.min,l=e.bound.max,u=(m<t[0]?t[0]:m>l[0]?l[0]:m)-m,c=(f<t[1]?t[1]:f>l[1]?l[1]:f)-f,h=(p<t[2]?t[2]:p>l[2]?l[2]:p)-p,v=Math.sqrt(u*u+c*c+h*h);let b=v;if(r>1&&v>.01){const e=(_*u+g*c+y*h)/v;e<0&&(b=v*(1+-e*(r-1)))}const x=b*d;let T;if(0===n||x<o)T=0;else for(T=n;T>1&&x<o*Math.pow(s,T-1);)T--;T<i?T=i:T>a&&(T=a),this._frustumCulling&&!1===e.inFrustum&&(T=a),e.optimalLod=T}}_displayedLodLevel(e){var t,n,o;return"optimal"===this._debugLodSource?null!==(n=null!==(t=e.optimalLod)&&void 0!==t?t:e.activeLod)&&void 0!==n?n:0:null!==(o=e.activeLod)&&void 0!==o?o:0}_refreshDebugDisplay(){"optimal"===this._debugLodSource&&this.evaluateOptimalLods(),this._buildDebugMesh();const e=this._debugDisplay;e&&!this._debugObserver?this._debugObserver=this._scene.onBeforeRenderObservable.add(()=>this._onDebugFrame()):!e&&this._debugObserver&&(this._scene.onBeforeRenderObservable.remove(this._debugObserver),this._debugObserver=null)}_onDebugFrame(){"optimal"===this._debugLodSource&&this.evaluateOptimalLods(),this._computeDebugSignature()!==this._debugSignature&&this._updateDebugColors()}_buildDebugMesh(){this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null),this._debugColorData=null;const e=[],n=[];for(const o of this._leafNodes){const s=iu[this._displayedLodLevel(o)%iu.length],r=o.bound.min,i=o.bound.max,a=[new t.Vector3(r[0],r[1],r[2]),new t.Vector3(i[0],r[1],r[2]),new t.Vector3(i[0],i[1],r[2]),new t.Vector3(r[0],i[1],r[2]),new t.Vector3(r[0],r[1],i[2]),new t.Vector3(i[0],r[1],i[2]),new t.Vector3(i[0],i[1],i[2]),new t.Vector3(r[0],i[1],i[2])];for(const t of su)e.push([a[t[0]],a[t[1]]]),n.push([s,s])}if(this._debugSignature=this._computeDebugSignature(),0===e.length)return;const o=t.CreateLineSystem(this.name+"_lodDebug",{lines:e,colors:n,updatable:!0,useVertexAlpha:!1},this._scene);o.parent=this,o.isPickable=!1,o.doNotSerialize=!0,o.reservedDataStore={hidden:!0},this._debugMesh=o,this._debugColorData=new Float32Array(this._leafNodes.length*ru*4)}_updateDebugColors(){if(!this._debugMesh||!this._debugColorData)return;const e=this._debugColorData;let n=0;for(const t of this._leafNodes){const o=iu[this._displayedLodLevel(t)%iu.length];for(let t=0;t<ru;t++)e[n++]=o.r,e[n++]=o.g,e[n++]=o.b,e[n++]=o.a}this._debugMesh.updateVerticesData(t.VertexBuffer.ColorKind,e),this._debugSignature=this._computeDebugSignature()}_computeDebugSignature(){let e=0;for(const t of this._leafNodes)e=31*e+this._displayedLodLevel(t)|0;return e}_clearDebugDisplay(){this._debugObserver&&(this._scene.onBeforeRenderObservable.remove(this._debugObserver),this._debugObserver=null),this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null),this._debugColorData=null,this._debugSignature=0}_collectLodEntries(e){if(e.children){for(const t of e.children)this._collectLodEntries(t);return}if(!e.lods)return;const n=[];for(const t of Object.keys(e.lods)){const o=Number(t),s=e.lods[t];Number.isFinite(o)&&s&&s.count>0&&n.push(o)}0!==n.length&&(n.sort((e,t)=>e-t),e.availableLevels=n,e.baseLod=n[n.length-1],e.activeLod=void 0,e.lodCooldown=0,e.inFrustum=!0,e.cullBounds=new t.BoundingInfo(t.Vector3.FromArray(e.bound.min),t.Vector3.FromArray(e.bound.max)),this._leafNodes.push(e))}_streamAllAsync(){return b(this,void 0,void 0,function*(){const e=this._collectAllFileIds(),n=yield this._gatherCountsAsync(e);if(this._disposed)return;let o=1;n>0&&(o+=n);for(const t of e){const e=this._fileCounts.get(t);void 0!==e&&e>0&&(o+=e)}if(o<=1)return;this._evictionEnabled=this._residentBudget>0&&this._residentBudget<o;const s=this._evictionEnabled?Math.max(this._residentBudget,1):o;if(this._residency=new Ql(s,this._evictionCooldownFrames,e=>this._onFileEvicted(e)),this._residency.pin(-2,1),n>0){const e=this._residency.pin(-1,n);null!==e?this._environmentRange={offset:e,count:n}:(t.Logger.Warn("GaussianSplattingStream: environment does not fit the memory budget; skipping it."),this._environmentFiles=null)}this._workBuffer=new jl(this._scene,s),this._readbackCandidate=this._workBuffer.supportsAsyncCentersReadback;const r=new Float32Array(4*s),i=this._workBuffer.textures;this._setExternalWorkBuffer(i[0],i[1],i[2],i[3],r,s),this.setSplatIndexRanges([]),this.setEnabled(!0),this._environmentRange&&this._environmentFiles&&(yield this._decodeEnvironmentAsync()),this._environmentFiles=null;const a=new Set;for(const e of this._leafNodes){const t=e.lods[String(e.baseLod)];t&&this._fileCounts.has(t.file)&&a.add(t.file)}for(const e of Array.from(a)){if(this._disposed)return;yield this._decodeFileAsync(e)}this._disposed||(this._baseLayerReady=!0,this._lodObserver||(this._lodObserver=this._scene.onBeforeRenderObservable.add(()=>this._onLodFrame())))})}_collectAllFileIds(){const e=new Set;for(const t of this._leafNodes)for(const n of t.availableLevels){const o=t.lods[String(n)];o&&e.add(o.file)}return Array.from(e).sort((e,t)=>e-t)}_gatherCountsAsync(e){return b(this,void 0,void 0,function*(){var n;let o=0;if(this._metadata.environment)try{const e=this._rootUrl+this._metadata.environment,t=yield this._downloadManager.loadFileAsync(e),n=yield this._unzipAsync(new Uint8Array(t)),s=n.get("meta.json");if(s){const e=JSON.parse((new TextDecoder).decode(s));o=au._GetSplatCount(e),this._environmentFiles=n}}catch(e){t.Logger.Warn("GaussianSplattingStream: failed to load environment: "+(null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e))}return yield Promise.all(e.map(e=>b(this,void 0,void 0,function*(){var n;const o=this._metadata.filenames[e];if(o)try{const t=this._rootUrl+o,n=t.substring(0,t.lastIndexOf("/")+1),s=yield this._downloadManager.loadFileAsync(t),r=JSON.parse((new TextDecoder).decode(new Uint8Array(s)));this._fileCounts.set(e,au._GetSplatCount(r)),this._fileMeta.set(e,{sogData:r,subRootUrl:n})}catch(e){t.Logger.Warn(`GaussianSplattingStream: failed to load metadata for ${o}: ${null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e}`)}else t.Logger.Warn(`GaussianSplattingStream: missing filename for file index ${e}.`)}))),o})}_enqueueDecode(e){this._decodedFiles.has(e)||this._loadingFiles.has(e)||!this._fileMeta.has(e)||-1===this._decodeQueue.indexOf(e)&&this._decodeQueue.push(e)}_pumpDecodeQueue(){let e=0;for(;this._decodeQueue.length>0&&e<this._maxDecodesPerFrame;){const n=this._decodeQueue.shift();this._decodedFiles.has(n)||this._loadingFiles.has(n)||(e++,this._decodeFileAsync(n).catch(e=>{var n;t.Logger.Warn("GaussianSplattingStream: decode failed: "+(null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e))}))}}_applyPositions(e,t,n){this._splatPositions.set(e,4*t),this._updateBounds(e,n),this._postWorkerPositionsRange(t,n)}_probeReadbackAsync(e,n,o){return b(this,void 0,void 0,function*(){if(this._readbackProbed=!0,!this._workBuffer)return;const s=Math.min(n,1024);let r=!1;try{const t=yield this._workBuffer.readCentersRangeAsync(e,s);if(this._disposed)return;if(t&&t.length>=4*s){r=!0;for(let e=0;e<s&&r;e++)for(let n=0;n<3;n++){const s=t[4*e+n],i=o[4*e+n];if(Math.abs(s-i)>.01*(1+Math.abs(i))){r=!1;break}}}}catch(e){r=!1}this._useGpuPositionReadback=r,t.Logger.Log(r?"GaussianSplattingStream: GPU position readback validated; streamed LOD positions are read back from the GPU.":"GaussianSplattingStream: GPU position readback unavailable; decoding LOD positions on the CPU.")})}_applyDecodedPositionsAsync(e,t,n){return b(this,void 0,void 0,function*(){if(this._useGpuPositionReadback&&this._workBuffer){const e=yield this._workBuffer.readCentersRangeAsync(t,n);if(this._disposed)return!1;if(e&&this._splatPositions)return this._applyPositions(e,t,n),!0}const o=e.positions.length>=4*n?e.positions.subarray(0,4*n):null;return!(!o||!this._splatPositions||(this._applyPositions(o,t,n),!this._readbackProbed&&this._readbackCandidate&&(yield this._probeReadbackAsync(t,n,o)),0))})}_decodeEnvironmentAsync(){return b(this,void 0,void 0,function*(){var e;if(!this._environmentRange||!this._environmentFiles||!this._workBuffer)return;const n=this._environmentRange;try{const e=(yield $l(this._environmentFiles,"",this._scene,!this._useGpuPositionReadback,this._downloadManager)).sogTextures;if(!e)return;try{if(this._disposed||!this._workBuffer)return;if(yield this._workBuffer.decodeAsync(e,n.offset),this._disposed)return;if(yield this._applyDecodedPositionsAsync(e,n.offset,n.count),this._disposed)return;this._refreshActiveRanges()}finally{au._DisposePack(e)}}catch(n){t.Logger.Warn("GaussianSplattingStream: failed to decode environment: "+(null!==(e=null==n?void 0:n.message)&&void 0!==e?e:n))}})}_decodeFileAsync(e){return b(this,void 0,void 0,function*(){if(this._decodedFiles.has(e)||this._loadingFiles.has(e)||!this._residency)return;const n=this._fileMeta.get(e),o=this._fileCounts.get(e);if(!n||void 0===o)return;this._loadingFiles.add(e),this._cancelledDecodes.delete(e);let s=!1;try{const r=(yield $l(n.sogData,n.subRootUrl,this._scene,!this._useGpuPositionReadback,this._downloadManager,e)).sogTextures;if(!r)return;const i=yield this._acquireDecodeGateAsync();try{if(this._disposed||!this._workBuffer||this._cancelledDecodes.has(e))return;let n=this._residency.allocate(e,o);if(null===n&&(n=yield this._relayoutAndAllocateAsync(e,o)),null===n)return void(this._cancelledDecodes.has(e)||t.Logger.Warn(`GaussianSplattingStream: resident memory budget full; skipping LOD file ${e}.`));if(s=!0,this._disposed||!this._workBuffer||this._cancelledDecodes.has(e))return;if(yield this._workBuffer.decodeAsync(r,n),this._disposed||this._cancelledDecodes.has(e))return;if(yield this._applyDecodedPositionsAsync(r,n,o),this._disposed)return;this._decodedFiles.add(e),this._applyDesiredLods()&&this._refreshActiveRanges()}finally{au._DisposePack(r),i()}}catch(t){if(!this._cancelledDecodes.has(e))throw t}finally{s&&!this._decodedFiles.has(e)&&this._residency.free(e),this._loadingFiles.delete(e),this._cancelledDecodes.delete(e)}})}_acquireDecodeGateAsync(){return b(this,void 0,void 0,function*(){const e=this._decodeGate;let t;return this._decodeGate=new Promise(e=>{t=e}),yield e,t})}_relayoutAndAllocateAsync(e,t){return b(this,void 0,void 0,function*(){return this._residency&&this._workBuffer?this._residency.freeSize<t?null:yield new Promise(n=>{const o=()=>{!this._disposed&&this._residency&&this._workBuffer&&!this._cancelledDecodes.has(e)?this._workBuffer.isRelayoutReady()?(this._performRelayout(),n(this._residency.allocate(e,t))):this._scene.onBeforeRenderObservable.addOnce(o):n(null)};this._scene.onBeforeRenderObservable.addOnce(o)}):null})}_performRelayout(){if(!this._residency||!this._workBuffer||!this._splatPositions)return;const e=this._relayoutOldOffsets;e.clear();for(const t of this._residency.getResidentBlocks())e.set(t.file,t.offset);if(0===this._residency.compact().length)return;const t=this._residency.capacity;this._relayoutSrcIndex&&this._relayoutSrcIndex.length===t||(this._relayoutSrcIndex=new Float32Array(t));const n=this._relayoutSrcIndex;n.fill(-1);const o=this._residency.getResidentBlocks();for(const t of o){const o=e.get(t.file);for(let e=0;e<t.count;e++)n[t.offset+e]=o+e}this._workBuffer.relayoutSync(n);const s=this._splatPositions;o.sort((e,t)=>e.offset-t.offset);for(const t of o){const n=e.get(t.file);n!==t.offset&&s.copyWithin(4*t.offset,4*n,4*(n+t.count))}if(this._environmentRange){const e=this._residency.offset(-1);void 0!==e&&(this._environmentRange.offset=e)}this._notifyWorkerNewData(),this._refreshActiveRanges()}_onFileEvicted(e){this._decodedFiles.delete(e)}_cappedLevelForNode(e,t){const n=e.availableLevels,o=this._maxDetailLod;let s=-1,r=Number.POSITIVE_INFINITY;for(const e of n){if(e<o)continue;const n=Math.abs(e-t);n<r&&(s=e,r=n)}return s<0?e.baseLod:s}_computeTargetLevels(){var e;for(const t of this._leafNodes){const n=null!==(e=t.optimalLod)&&void 0!==e?e:t.baseLod;t.targetLevel=this._cappedLevelForNode(t,n)}}_applyDesiredLods(){var e;let t=!1;for(const n of this._leafNodes){if(n.lodCooldown&&n.lodCooldown>0)continue;const o=null!==(e=n.targetLevel)&&void 0!==e?e:n.baseLod;let s;if(o!==n.activeLod){const e=n.lods[String(o)];e&&(this._decodedFiles.has(e.file)?(this._switchActiveFile(n,e.file),n.activeLod=o,n.lodCooldown=this._lodCooldownFrames,t=!0):s=e.file)}n.pendingFile!==s&&(void 0!==n.pendingFile&&this._releaseFileRef(n.pendingFile),void 0!==s&&this._acquirePendingFile(s),n.pendingFile=s)}return t}_switchActiveFile(e,t){e.activeFile!==t&&(void 0!==e.activeFile&&this._releaseFileRef(e.activeFile),this._acquireFileRef(t),e.activeFile=t)}_acquireFileRef(e){var t,n;const o=(null!==(t=this._fileRefs.get(e))&&void 0!==t?t:0)+1;this._fileRefs.set(e,o),1===o&&(null===(n=this._residency)||void 0===n||n.cancelEviction(e))}_acquirePendingFile(e){this._acquireFileRef(e),this._enqueueDecode(e)}_releaseFileRef(e){var t,n;const o=(null!==(t=this._fileRefs.get(e))&&void 0!==t?t:0)-1;if(o>0)return void this._fileRefs.set(e,o);if(this._fileRefs.delete(e),this._decodedFiles.has(e))return void(this._evictionEnabled&&(null===(n=this._residency)||void 0===n||n.scheduleEviction(e)));const s=this._decodeQueue.indexOf(e);-1!==s&&this._decodeQueue.splice(s,1),this._loadingFiles.has(e)&&(this._cancelledDecodes.add(e),this._downloadManager.cancelGroup(e))}_onLodFrame(){var e;if(this._disposed||!this._baseLayerReady)return;let n=!1;for(const e of this._leafNodes)e.lodCooldown&&e.lodCooldown>0&&(e.lodCooldown--,0===e.lodCooldown&&void 0!==e.targetLevel&&e.targetLevel!==e.activeLod&&(n=!0));this._evictionEnabled&&(null===(e=this._residency)||void 0===e||e.tick()),this._pumpDecodeQueue();const o=this._updateNodeFrustum();let s=this._forceLodUpdate||o||n;if(!s&&++this._framesSinceLodUpdate>=this._lodUpdateInterval){const e=this._scene.activeCamera,n=this._lodUpdateDistance;(!e||t.Vector3.DistanceSquared(e.globalPosition,this._lastLodCamPos)>=n*n)&&(e&&this._lastLodCamPos.copyFrom(e.globalPosition),s=!0)}s&&(this._forceLodUpdate=!1,this._framesSinceLodUpdate=0,this.evaluateOptimalLods(this._scene.activeCamera),this._computeTargetLevels(),this._applyDesiredLods()&&this._refreshActiveRanges())}_updateNodeFrustum(){const e=this._scene.activeCamera;let n=!1;if(!this._frustumCulling||!e){for(const e of this._leafNodes)!1===e.inFrustum&&(e.inFrustum=!0,n=!0);return n}const o=this.computeWorldMatrix(!1);e.getViewMatrix().multiplyToRef(e.getProjectionMatrix(),this._cullViewProj),t.Frustum.GetPlanesToRef(this._cullViewProj,this._frustumPlanes);for(const e of this._leafNodes){e.cullBounds.update(o);const t=e.cullBounds.isInFrustum(this._frustumPlanes);t!==e.inFrustum&&(e.inFrustum=t,n=!0)}return n}static _GetSplatCount(e){var t;return null!==(t=e.count)&&void 0!==t?t:Array.isArray(e.means.shape)?e.means.shape[0]:0}static _DisposePack(e){var t,n,o;e.meansTextureL.dispose(),e.meansTextureU.dispose(),e.scalesTexture.dispose(),e.quatsTexture.dispose(),e.sh0Texture.dispose(),null===(t=e.shCentroidsTexture)||void 0===t||t.dispose(),null===(n=e.shLabelsTexture)||void 0===n||n.dispose(),null===(o=e.codebookTexture)||void 0===o||o.dispose()}_updateBounds(e,n){const o=this._boundsMin,s=this._boundsMax;for(let t=0;t<n;t++){const n=e[4*t+0],r=e[4*t+1],i=e[4*t+2];o.minimizeInPlaceFromFloats(n,r,i),s.maximizeInPlaceFromFloats(n,r,i)}this.setBoundingInfo(new t.BoundingInfo(o,s))}_refreshActiveRanges(){var e;const t=[];this._environmentRange&&t.push({offset:this._environmentRange.offset,count:this._environmentRange.count});for(const n of this._leafNodes){if(void 0===n.activeLod)continue;const o=n.lods[String(n.activeLod)];if(!o)continue;const s=null===(e=this._residency)||void 0===e?void 0:e.offset(o.file);void 0!==s&&t.push({offset:s+o.offset,count:o.count})}this.setSplatIndexRanges(au._CoalesceRanges(t))}static _CoalesceRanges(e){if(e.length<=1)return e;const t=e.slice().sort((e,t)=>e.offset-t.offset),n=[{offset:t[0].offset,count:t[0].count}];for(let e=1;e<t.length;e++){const o=n[n.length-1],s=t[e],r=o.offset+o.count;if(s.offset<=r){const e=Math.max(r,s.offset+s.count);o.count=e-o.offset}else n.push({offset:s.offset,count:s.count})}return n}_unzipAsync(e){return b(this,void 0,void 0,function*(){var n;let o=this._streamOptions.fflate;o||(void 0===window.fflate&&(yield t.Tools.LoadScriptAsync(null!==(n=this._streamOptions.deflateURL)&&void 0!==n?n:"https://unpkg.com/fflate/umd/index.js")),o=window.fflate);const s=o.unzipSync(e),r=new Map;for(const[e,t]of Object.entries(s))r.set(e,t);return r})}}const lu=.28209479177387814;let uu=null,cu=null;class du{constructor(e={}){this.name=kl.name,this._assetContainer=null,this.extensions=kl.extensions,this._loadingOptions=Object.assign(Object.assign({},du._DefaultLoadingOptions),e)}createPlugin(e){return new du(e[kl.name])}importMeshAsync(e,t,n,o,s,r){return b(this,void 0,void 0,function*(){const s=this._tryCreateLODStream(t,n,o);return s?{meshes:[s],particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}:yield this._parseAsync(e,t,n,o).then(e=>({meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))})}_tryCreateLODStream(e,t,n){if("string"!=typeof t)return null;let o;try{o=JSON.parse(t)}catch(e){return null}if(!au.IsLODMetadata(o))return null;const s=e._blockEntityCollection;e._blockEntityCollection=!!this._assetContainer;try{const t=new au("GaussianSplattingStream",o,n,e,{deflateURL:this._loadingOptions.deflateURL,fflate:this._loadingOptions.fflate});return t._parentContainer=this._assetContainer,t}finally{e._blockEntityCollection=s}}static _BuildPointCloud(e,n){if(!n.byteLength)return!1;const o=new Uint8Array(n),s=new Float32Array(n),r=o.length/32;return e.addPoints(r,function(e,n){const r=s[8*n+0],i=s[8*n+1],a=s[8*n+2];e.position=new t.Vector3(r,i,a);const l=o[32*n+24+0]/255,u=o[32*n+24+1]/255,c=o[32*n+24+2]/255;e.color=new t.Color4(l,u,c,1)}),!0}static _BuildMesh(e,n){const o=new t.Mesh("PLYMesh",e),s=new Uint8Array(n.data),r=new Float32Array(n.data),i=s.length/32,a=[],l=new t.VertexData;for(let e=0;e<i;e++){const t=r[8*e+0],n=r[8*e+1],o=r[8*e+2];a.push(t,n,o)}if(n.hasVertexColors){const e=new Float32Array(4*i);for(let t=0;t<i;t++){const n=s[32*t+24+0]/255,o=s[32*t+24+1]/255,r=s[32*t+24+2]/255;e[4*t+0]=n,e[4*t+1]=o,e[4*t+2]=r,e[4*t+3]=1}l.colors=e}return l.positions=a,l.indices=n.faces,l.applyToMesh(o),o}_unzipWithFFlateAsync(e){return b(this,void 0,void 0,function*(){var n;let o=this._loadingOptions.fflate;o||(void 0===window.fflate&&(yield t.Tools.LoadScriptAsync(null!==(n=this._loadingOptions.deflateURL)&&void 0!==n?n:"https://unpkg.com/fflate/umd/index.js")),o=window.fflate);const{unzipSync:s}=o,r=s(e),i=new Map;for(const[e,t]of Object.entries(r))i.set(e,t);return i})}_parseAsync(e,n,o,s){const r=[],i=e=>{var o;n._blockEntityCollection=!!this._assetContainer;const s=null!==(o=this._loadingOptions.gaussianSplattingMesh)&&void 0!==o?o:new t.GaussianSplattingMesh("GaussianSplatting",null,n,this._loadingOptions.keepInRam,this._loadingOptions.needsRotationScaleTextures);s._parentContainer=this._assetContainer,r.push(s),e.sogTextures?s.setSogTextureData(e.sogTextures):s.updateData(e.data,e.sh,{flipY:!1},void 0,e.shDegree),s.scaling.y*=-1,s.computeWorldMatrix(!0),s.safeOrbitCameraLimits=du._ExtractSafeOrbitLimits(e),n._blockEntityCollection=!1},a=n.getEngine();let l=this._loadingOptions.useSogTextures;l&&!a.isWebGPU&&a.version<2&&(t.Logger.Warn("SPLATFileLoader: useSogTextures requires WebGL2 or WebGPU. Falling back to CPU path."),l=!1);const u=l?$l:Vl;if("string"==typeof o){const e=JSON.parse(o);if(e&&e.means&&e.scales&&e.quats&&e.sh0)return new Promise((t,o)=>{u(e,s,n).then(e=>{i(e),t(r)}).catch(e=>{o(new Error("Failed to parse SOG data.",{cause:e}))})})}const c=o instanceof ArrayBuffer?new Uint8Array(o):o;if(80===c[0]&&75===c[1])return new Promise((e,t)=>{this._unzipWithFFlateAsync(c).then(o=>{u(o,s,n).then(t=>{i(t),e(r)}).catch(e=>{t(new Error("Failed to parse SOG zip data.",{cause:e}))})})});const d=e=>{du._ConvertPLYToSplat(o).then(o=>b(this,void 0,void 0,function*(){var s;switch(n._blockEntityCollection=!!this._assetContainer,o.mode){case 0:{const e=null!==(s=this._loadingOptions.gaussianSplattingMesh)&&void 0!==s?s:new t.GaussianSplattingMesh("GaussianSplatting",null,n,this._loadingOptions.keepInRam,this._loadingOptions.needsRotationScaleTextures);switch(e._parentContainer=this._assetContainer,r.push(e),e.updateData(o.data,o.sh,{flipY:!1},void 0,o.shDegree),e.scaling.y*=-1,"RightHanded"===o.chirality&&(e.scaling.y*=-1),o.upAxis){case"X":e.rotation=new t.Vector3(0,0,Math.PI/2);break;case"Y":e.rotation=new t.Vector3(0,0,Math.PI);break;case"Z":e.rotation=new t.Vector3(-Math.PI/2,Math.PI,0)}e.computeWorldMatrix(!0),e.safeOrbitCameraLimits=du._ExtractSafeOrbitLimits(o)}break;case 1:{const e=new t.PointsCloudSystem("PointCloud",1,n);du._BuildPointCloud(e,o.data)?yield e.buildMeshAsync().then(e=>{r.push(e)}):e.dispose()}break;case 2:if(!o.faces)throw new Error("PLY mesh doesn't contain face informations.");r.push(du._BuildMesh(n,o));break;default:throw new Error("Unsupported Splat mode")}n._blockEntityCollection=!1,this.applyAutoCameraLimits(du._ExtractSafeOrbitLimits(o),n),e(r)}))},h=31===c[0]&&139===c[1],m=78===c[0]&&71===c[1]&&83===c[2]&&80===c[3];if(!h&&!m)return new Promise(e=>{d(e)});const f=(e,o)=>{var s;n._blockEntityCollection=!!this._assetContainer;const i=null!==(s=this._loadingOptions.gaussianSplattingMesh)&&void 0!==s?s:new t.GaussianSplattingMesh("GaussianSplatting",null,n,this._loadingOptions.keepInRam,this._loadingOptions.needsRotationScaleTextures);if(e.trainedWithAntialiasing){const e=i.material;e.kernelSize=.1,e.compensation=!0}i._parentContainer=this._assetContainer,r.push(i),i.updateData(e.data,e.sh,{flipY:!1},void 0,e.shDegree),this._loadingOptions.flipY||(i.scaling.y*=-1,i.computeWorldMatrix(!0)),n._blockEntityCollection=!1;const a=du._ExtractSafeOrbitLimits(e);i.safeOrbitCameraLimits=a,this.applyAutoCameraLimits(a,n),o(r)};if(this._loadingOptions.spzLibraryUrl)return function(e){return b(this,void 0,void 0,function*(){if(uu&&cu===e)return yield uu;const n=t._LoadScriptModuleAsync(`import createSpzModule from '${e}';\n const module = await createSpzModule();\n const returnedValue = module;`);return cu=e,uu=n,yield n})}(this._loadingOptions.spzLibraryUrl).then(e=>function(e,n){return b(this,void 0,void 0,function*(){return yield t.runCoroutineAsync(function*(e,n,o=!1){const s=e.numPoints,r=new ArrayBuffer(32*s),i=new Float32Array(r),a=new Uint8Array(r),l=e.positions,u=e.scales,c=e.colors,d=e.alphas,h=e.rotations;let m=null;const f=e.shDegree;let p,_,g=null,y=0,v=null,b=null,x=null;if(f>0&&e.sh.length>0){y=3*((f+1)*(f+1)-1);const o=Math.ceil(y/16),r=n.getEngine().getCaps().maxTextureSize,i=Math.ceil(s/r);m=t.AllocateShBuffers(o,i*r*4*4),v=new Int32Array(o),b=new Int32Array(o);for(let e=0;e<o;e++)v[e]=16*e,b[e]=Math.min(16*(e+1),y);x=m,g=e.sh}for(let e=0;e<s;e++){const t=8*e,n=32*e,s=3*e,r=4*e;i[t+0]=l[s+0],i[t+1]=l[s+1],i[t+2]=l[s+2],i[t+3]=Math.exp(u[s+0]),i[t+4]=Math.exp(u[s+1]),i[t+5]=Math.exp(u[s+2]);const m=255*(.5+lu*c[s+0]),f=255*(.5+lu*c[s+1]),p=255*(.5+lu*c[s+2]);a[n+24]=m<=0?0:m>=255?255:m+.5|0,a[n+25]=f<=0?0:f>=255?255:f+.5|0,a[n+26]=p<=0?0:p>=255?255:p+.5|0,a[n+27]=1/(1+Math.exp(-d[e]))*255+.5|0;const _=127.5*h[r+3]+127.5,T=127.5*h[r+0]+127.5,A=127.5*h[r+1]+127.5,M=127.5*h[r+2]+127.5;if(a[n+28]=_<=0?0:_>=255?255:_+.5|0,a[n+29]=T<=0?0:T>=255?255:T+.5|0,a[n+30]=A<=0?0:A>=255?255:A+.5|0,a[n+31]=M<=0?0:M>=255?255:M+.5|0,g&&x&&v&&b){const t=e*y,n=16*e;for(let e=0;e<x.length;e++){const o=x[e],s=v[e],r=b[e];for(let e=s;e<r;e++){const r=128*g[t+e]+128;o[n+e-s]=r<=0?0:r>=255?255:r+.5|0}}}e%32768==0&&o&&(yield)}if(e.extensions)for(const t of e.extensions){const e=t;if(void 0!==e.safeOrbitRadiusMin){p=e.safeOrbitRadiusMin,_=[e.safeOrbitElevationMin,e.safeOrbitElevationMax];break}}return{mode:0,data:r,hasVertexColors:!1,sh:null!==m?m:void 0,shDegree:f>0?f:void 0,trainedWithAntialiasing:!!e.antialiased,safeOrbitCameraRadiusMin:p,safeOrbitCameraElevationMinMax:_}}(e,n,!0),t.createYieldingScheduler())})}(e.loadSpzFromBuffer(new Uint8Array(o),{to:e.CoordinateSystem.RUB}),n).then(e=>new Promise(t=>{f(e,t)})));if(m)return Promise.reject(new Error("SPZ V4+ files (NGSP format) are not supported by the native fallback loader. Please provide a valid 'spzLibraryUrl' in the loading options to use the WASM-based SPZ library, or ensure WebAssembly is available in your environment."));const p=new ReadableStream({start(e){e.enqueue(new Uint8Array(o)),e.close()}}),_=new DecompressionStream("gzip"),g=p.pipeThrough(_);return new Promise(e=>{new Response(g).arrayBuffer().then(o=>{(function(e,n){const o=new Uint8Array(e),s=new Uint32Array(e.slice(0,12)),r=s[2],i=o[12],a=o[13],l=o[14],u=o[15],c=s[1];if(u||1347635022!=s[0]||c<2||c>4)return new Promise(e=>{e({mode:3,data:new ArrayBuffer(0),hasVertexColors:!1})});const d=new ArrayBuffer(32*r),h=1/(1<<a),m=new Int32Array(1),f=new Uint8Array(m.buffer),p=function(e,t){return f[0]=e[t+0],f[1]=e[t+1],f[2]=e[t+2],f[3]=128&e[t+2]?255:0,m[0]*h};let _=16;const g=new Float32Array(d),y=new Float32Array(d),v=new Uint8ClampedArray(d),b=new Uint8ClampedArray(d);for(let e=0;e<r;e++)g[8*e+0]=p(o,_+0),g[8*e+1]=p(o,_+3),g[8*e+2]=p(o,_+6),_+=9;for(let e=0;e<r;e++){for(let n=0;n<3;n++){const s=(o[_+r+3*e+n]-127.5)/38.25;v[32*e+24+n]=t.Scalar.Clamp(255*(.5+lu*s),0,255)}v[32*e+24+3]=o[_+e]}_+=4*r;for(let e=0;e<r;e++)y[8*e+3+0]=Math.exp(o[_+0]/16-10),y[8*e+3+1]=Math.exp(o[_+1]/16-10),y[8*e+3+2]=Math.exp(o[_+2]/16-10),_+=3;if(c>=3){const e=Math.SQRT1_2;for(let t=0;t<r;t++){const n=[o[_+0],o[_+1],o[_+2],o[_+3]],s=n[0]+(n[1]<<8)+(n[2]<<16)+(n[3]<<24),r=511,i=[],a=s>>>30;let l=s,u=0;for(let t=3;t>=0;--t)if(t!==a){const n=l&r,o=l>>>9&1;l>>>=10,i[t]=e*(n/r),1===o&&(i[t]=-i[t]),u+=i[t]*i[t]}const c=1-u;i[a]=Math.sqrt(Math.max(c,0));const d=[3,0,1,2];for(let e=0;e<4;e++)b[32*t+28+e]=Math.round(127.5+127.5*i[d[e]]);_+=4}}else for(let e=0;e<r;e++){const t=o[_+0],n=o[_+1],s=o[_+2],r=t/127.5-1,i=n/127.5-1,a=s/127.5-1;b[32*e+28+1]=t,b[32*e+28+2]=n,b[32*e+28+3]=s;const l=1-(r*r+i*i+a*a);b[32*e+28+0]=127.5+127.5*Math.sqrt(l<0?0:l),_+=3}if(i){const e=3*((i+1)*(i+1)-1),s=Math.ceil(e/16);let a=_;const u=n.getEngine().getCaps().maxTextureSize,c=Math.ceil(r/u),h=t.AllocateShBuffers(s,c*u*4*4);for(let t=0;t<r;t++)for(let n=0;n<e;n++){const e=o[a++],s=Math.floor(n/16);h[s][n%16+16*t]=e}return new Promise(e=>{e({mode:0,data:d,hasVertexColors:!1,sh:h,shDegree:i,trainedWithAntialiasing:!!l})})}return new Promise(e=>{e({mode:0,data:d,hasVertexColors:!1,trainedWithAntialiasing:!!l})})})(o,n,this._loadingOptions).then(t=>{f(t,e)})}).catch(()=>{d(e)})})}static _ExtractSafeOrbitLimits(e){return void 0===e.safeOrbitCameraRadiusMin&&void 0===e.safeOrbitCameraElevationMinMax?null:{radiusMin:e.safeOrbitCameraRadiusMin,elevationMinMax:e.safeOrbitCameraElevationMinMax}}applyAutoCameraLimits(e,t){var n;if(!this._loadingOptions.disableAutoCameraLimits&&e&&"ArcRotateCamera"===(null===(n=t.activeCamera)||void 0===n?void 0:n.getClassName())){const n=t.activeCamera;e.elevationMinMax&&(n.lowerBetaLimit=.5*Math.PI-e.elevationMinMax[1],n.upperBetaLimit=.5*Math.PI-e.elevationMinMax[0]),e.radiusMin&&(n.lowerRadiusLimit=e.radiusMin)}}loadAssetContainerAsync(e,n,o){const s=new t.AssetContainer(e);return this._assetContainer=s,this.importMeshAsync(null,e,n,o).then(e=>{for(const t of e.meshes)s.meshes.push(t);return this._assetContainer=null,s}).catch(e=>{throw this._assetContainer=null,e})}loadAsync(e,t,n){return this.importMeshAsync(null,e,t,n).then(()=>{})}static _ConvertPLYToSplat(e){const n=new Uint8Array(e),o=(new TextDecoder).decode(n.slice(0,10240)),s=o.indexOf("end_header\n");if(s<0||!o)return new Promise(t=>{t({mode:0,data:e,rawSplat:!0})});const r=parseInt(/element vertex (\d+)\n/.exec(o)[1]),i=/element face (\d+)\n/.exec(o);let a=0;i&&(a=parseInt(i[1]));const l=/element chunk (\d+)\n/.exec(o);let u=0;l&&(u=parseInt(l[1]));let c=0,d=0;const h={double:8,int:4,uint:4,float:4,short:2,ushort:2,uchar:1,list:0};let m=1;const f=[],p=[],_=o.slice(0,s).split("\n"),g={};for(const n of _)if(n.startsWith("property ")){const[,o,s]=n.split(" ");if(1==m)p.push({name:s,type:o,offset:d}),d+=h[o];else if(0==m)f.push({name:s,type:o,offset:c}),c+=h[o];else if(2==m)f.push({name:s,type:o,offset:c});else if(3==m){const t=new DataView(e,d,2*h.float);g.safeOrbitCameraElevationMinMax=[t.getFloat32(0,!0),t.getFloat32(4,!0)]}else if(4==m){const t=new DataView(e,d,h.float);g.safeOrbitCameraRadiusMin=t.getFloat32(0,!0)}else if(5==m){const t=new DataView(e,d,h.uchar);"up_axis"==s?g.upAxis=0==t.getUint8(0)?"X":1==t.getUint8(0)?"Y":"Z":"chirality"==s&&(g.chirality=0==t.getUint8(0)?"LeftHanded":"RightHanded")}h[o]||t.Logger.Warn(`Unsupported property type: ${o}.`)}else if(n.startsWith("element ")){const[,e]=n.split(" ");"chunk"==e?m=1:"vertex"==e?m=0:"sh"==e?m=2:"safe_orbit_camera_elevation_min_max_radians"==e?m=3:"safe_orbit_camera_radius_min"==e?m=4:"up_axis"!=e&&"chirality"!=e||(m=5)}const y=c,v=d;return t.GaussianSplattingMesh.ConvertPLYWithSHToSplatAsync(e).then(t=>b(this,void 0,void 0,function*(){const n=new DataView(e,s+11);let o=v*u+y*r;const i=[];if(a)for(let e=0;e<a;e++){const e=n.getUint8(o);if(3==e){o+=1;for(let t=0;t<e;t++){const e=n.getUint32(o+4*(2-t),!0);i.push(e)}o+=12}}if(u)return yield new Promise(e=>{e({mode:0,data:t.buffer,sh:t.sh,shDegree:t.shDegree,faces:i,hasVertexColors:!1,compressed:!0,rawSplat:!1})});let l=0,c=0;const d=["x","y","z","scale_0","scale_1","scale_2","opacity","rot_0","rot_1","rot_2","rot_3"],h=["red","green","blue","f_dc_0","f_dc_1","f_dc_2"];for(let e=0;e<f.length;e++){const t=f[e];d.includes(t.name)&&l++,h.includes(t.name)&&c++}const m=l==d.length&&c>=3,p=a?2:m?0:1;return yield new Promise(e=>{e(Object.assign(Object.assign({},g),{mode:p,data:t.buffer,sh:t.sh,shDegree:t.shDegree,faces:i,hasVertexColors:!!c,compressed:!1,rawSplat:!1}))})}))}}du._DefaultLoadingOptions={keepInRam:!1,flipY:!1,needsRotationScaleTextures:!1,spzLibraryUrl:"object"==typeof WebAssembly?"https://unpkg.com/@adobe/spz@0.2.2/dist/spz.js":void 0};let hu=!1;function mu(){hu||(hu=!0,t.RegisterSceneLoaderPlugin(new du))}mu();var fu={__proto__:null,RegisterSPLATFileLoader:mu,SPLATFileLoader:du};function pu(){t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},f),{createPlugin:e=>b(this,void 0,void 0,function*(){const{BVHFileLoader:t}=yield Promise.resolve().then(function(){return y});return new t(e[f.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},Bt),{createPlugin:e=>b(this,void 0,void 0,function*(){const{FBXFileLoader:t}=yield Promise.resolve().then(function(){return Zt});return new t(e[Bt.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},sn),{createPlugin:e=>b(this,void 0,void 0,function*(){const{GLTFFileLoader:t}=yield Promise.resolve().then(function(){return xo});return new t(e[sn.name])})})),function(){no("EXT_lights_image_based"),to("EXT_lights_image_based",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_image_based:t}=yield Promise.resolve().then(function(){return ko});return new t(e)})),no("EXT_mesh_gpu_instancing"),to("EXT_mesh_gpu_instancing",!0,e=>b(this,void 0,void 0,function*(){const{EXT_mesh_gpu_instancing:t}=yield Promise.resolve().then(function(){return Ko});return new t(e)})),no("EXT_meshopt_compression"),to("EXT_meshopt_compression",!0,e=>b(this,void 0,void 0,function*(){const{EXT_meshopt_compression:t}=yield Promise.resolve().then(function(){return jo});return new t(e)})),no("EXT_texture_avif"),to("EXT_texture_avif",!0,e=>b(this,void 0,void 0,function*(){const{EXT_texture_avif:t}=yield Promise.resolve().then(function(){return os});return new t(e)})),no("EXT_texture_webp"),to("EXT_texture_webp",!0,e=>b(this,void 0,void 0,function*(){const{EXT_texture_webp:t}=yield Promise.resolve().then(function(){return Zo});return new t(e)})),no("ExtrasAsMetadata"),to("ExtrasAsMetadata",!1,e=>b(this,void 0,void 0,function*(){const{ExtrasAsMetadata:t}=yield Promise.resolve().then(function(){return yl});return new t(e)})),no("KHR_animation_pointer"),to("KHR_animation_pointer",!0,e=>b(this,void 0,void 0,function*(){const{KHR_animation_pointer:t}=yield Promise.resolve().then(function(){return fa});return new t(e)})),no("KHR_draco_mesh_compression"),to("KHR_draco_mesh_compression",!0,e=>b(this,void 0,void 0,function*(){const{KHR_draco_mesh_compression:t}=yield Promise.resolve().then(function(){return ms});return new t(e)})),no("KHR_gaussian_splatting"),to("KHR_gaussian_splatting",!0,e=>b(this,void 0,void 0,function*(){const{KHR_gaussian_splatting:t}=yield Promise.resolve().then(function(){return xs});return new t(e)})),no("KHR_interactivity"),to("KHR_interactivity",!0,e=>b(this,void 0,void 0,function*(){const{KHR_interactivity:t}=yield Promise.resolve().then(function(){return Ya});return new t(e)})),no("KHR_lights_punctual"),to("KHR_lights_punctual",!0,e=>b(this,void 0,void 0,function*(){const{KHR_lights:t}=yield Promise.resolve().then(function(){return Cs});return new t(e)})),no("EXT_lights_area"),to("EXT_lights_area",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_area:t}=yield Promise.resolve().then(function(){return Es});return new t(e)})),no("EXT_lights_ies"),to("EXT_lights_ies",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_ies:t}=yield Promise.resolve().then(function(){return ls});return new t(e)})),no("KHR_materials_anisotropy"),to("KHR_materials_anisotropy",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_anisotropy:t}=yield Promise.resolve().then(function(){return ar});return new t(e)})),no("KHR_materials_clearcoat"),to("KHR_materials_clearcoat",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_clearcoat:t}=yield Promise.resolve().then(function(){return zs});return new t(e)})),no("KHR_materials_diffuse_roughness"),to("KHR_materials_diffuse_roughness",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_diffuse_roughness:t}=yield Promise.resolve().then(function(){return pi});return new t(e)})),no("KHR_materials_diffuse_transmission"),to("KHR_materials_diffuse_transmission",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_diffuse_transmission:t}=yield Promise.resolve().then(function(){return Xr});return new t(e)})),no("KHR_materials_dispersion"),to("KHR_materials_dispersion",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_dispersion:t}=yield Promise.resolve().then(function(){return ci});return new t(e)})),no("KHR_materials_emissive_strength"),to("KHR_materials_emissive_strength",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_emissive_strength:t}=yield Promise.resolve().then(function(){return hr});return new t(e)})),no("KHR_materials_ior"),to("KHR_materials_ior",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_ior:t}=yield Promise.resolve().then(function(){return Lr});return new t(e)})),no("KHR_materials_iridescence"),to("KHR_materials_iridescence",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_iridescence:t}=yield Promise.resolve().then(function(){return nr});return new t(e)})),no("KHR_materials_pbrSpecularGlossiness"),to("KHR_materials_pbrSpecularGlossiness",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_pbrSpecularGlossiness:t}=yield Promise.resolve().then(function(){return Bs});return new t(e)})),no("KHR_materials_sheen"),to("KHR_materials_sheen",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_sheen:t}=yield Promise.resolve().then(function(){return gr});return new t(e)})),no("KHR_materials_specular"),to("KHR_materials_specular",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_specular:t}=yield Promise.resolve().then(function(){return Rr});return new t(e)})),no("KHR_materials_transmission"),to("KHR_materials_transmission",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_transmission:t}=yield Promise.resolve().then(function(){return $r});return new t(e)})),no("KHR_materials_unlit"),to("KHR_materials_unlit",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_unlit:t}=yield Promise.resolve().then(function(){return Hs});return new t(e)})),no("KHR_materials_variants"),to("KHR_materials_variants",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_variants:t}=yield Promise.resolve().then(function(){return kr});return new t(e)})),no("KHR_materials_volume"),to("KHR_materials_volume",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_volume:t}=yield Promise.resolve().then(function(){return ei});return new t(e)})),no("KHR_mesh_quantization"),to("KHR_mesh_quantization",!0,e=>b(this,void 0,void 0,function*(){const{KHR_mesh_quantization:t}=yield Promise.resolve().then(function(){return bi});return new t(e)})),no("KHR_texture_basisu"),to("KHR_texture_basisu",!0,e=>b(this,void 0,void 0,function*(){const{KHR_texture_basisu:t}=yield Promise.resolve().then(function(){return wi});return new t(e)})),no("KHR_texture_transform"),to("KHR_texture_transform",!0,e=>b(this,void 0,void 0,function*(){const{KHR_texture_transform:t}=yield Promise.resolve().then(function(){return Fi});return new t(e)})),no("KHR_xmp_json_ld"),to("KHR_xmp_json_ld",!0,e=>b(this,void 0,void 0,function*(){const{KHR_xmp_json_ld:t}=yield Promise.resolve().then(function(){return Pi});return new t(e)})),no("MSFT_audio_emitter"),to("MSFT_audio_emitter",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_audio_emitter:t}=yield Promise.resolve().then(function(){return va});return new t(e)})),no("MSFT_lod"),to("MSFT_lod",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_lod:t}=yield Promise.resolve().then(function(){return Ma});return new t(e)})),no("MSFT_minecraftMesh"),to("MSFT_minecraftMesh",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_minecraftMesh:t}=yield Promise.resolve().then(function(){return Sa});return new t(e)})),no("MSFT_sRGBFactors"),to("MSFT_sRGBFactors",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_sRGBFactors:t}=yield Promise.resolve().then(function(){return Na});return new t(e)})),no("KHR_node_visibility"),to("KHR_node_visibility",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_visibility:t}=yield Promise.resolve().then(function(){return tl});return new t(e)})),no("KHR_node_hoverability"),to("KHR_node_hoverability",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_hoverability:t}=yield Promise.resolve().then(function(){return ml});return new t(e)})),no("KHR_node_selectability"),to("KHR_node_selectability",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_selectability:t}=yield Promise.resolve().then(function(){return il});return new t(e)})),no("KHR_materials_coat"),to("KHR_materials_coat",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_coat:t}=yield Promise.resolve().then(function(){return Qs});return new t(e)})),no("KHR_materials_fuzz"),to("KHR_materials_fuzz",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_fuzz:t}=yield Promise.resolve().then(function(){return Tr});return new t(e)})),no("KHR_materials_volume_scatter"),to("KHR_materials_volume_scatter",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_volume_scatter:t}=yield Promise.resolve().then(function(){return ri});return new t(e)}))}(),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},wl),{createPlugin:e=>b(this,void 0,void 0,function*(){const{OBJFileLoader:t}=yield Promise.resolve().then(function(){return Sl});return new t(e[wl.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},kl),{createPlugin:e=>b(this,void 0,void 0,function*(){const{SPLATFileLoader:t}=yield Promise.resolve().then(function(){return fu});return new t(e[kl.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},El),{createPlugin:()=>b(this,void 0,void 0,function*(){const{STLFileLoader:e}=yield Promise.resolve().then(function(){return Pl});return new e})}))}var _u={__proto__:null,registerBuiltInLoaders:pu};const gu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==gu)for(const e in v)gu.BABYLON[e]||(gu.BABYLON[e]=v[e]);const yu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==yu){yu.BABYLON=yu.BABYLON||{};for(const e in _u)yu.BABYLON[e]=_u[e]}const vu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==vu){vu.BABYLON=vu.BABYLON||{};for(const e in wn)vu.BABYLON[e]=wn[e];for(const e in nn)vu.BABYLON[e]=nn[e]}const bu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==bu){bu.BABYLON=bu.BABYLON||{},bu.BABYLON.GLTF1=bu.BABYLON.GLTF1||{};for(const e in Zn)bu.BABYLON.GLTF1[e]=Zn[e]}const xu=Object.assign({},xl),Tu=Object.assign(Object.assign({},{__proto__:null}),{Extensions:xu}),Au=Object.assign(Object.assign({},Tl),{Loader:Tu}),Mu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Mu){Mu.BABYLON=Mu.BABYLON||{};const e=Mu.BABYLON;e.GLTF2=e.GLTF2||{},e.GLTF2.Loader=e.GLTF2.Loader||{},e.GLTF2.Loader.Extensions=e.GLTF2.Loader.Extensions||{};const t=["Loader"];for(const n in xu)e.GLTF2.Loader.Extensions[n]=xu[n],t.push(n);for(const n in Tu)"Extensions"!==n&&(e.GLTF2.Loader[n]=Tu[n],t.push(n));for(const n in Au)t.indexOf(n)>-1||(e.GLTF2[n]=Au[n])}const wu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==wu)for(const e in Fl)wu.BABYLON[e]||(wu.BABYLON[e]=Fl[e]);const Cu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Cu)for(const e in Bl)Cu.BABYLON[e]||(Cu.BABYLON[e]=Bl[e]);e.BVHFileLoader=p,e.FBXFileLoader=kt,e.FBXFileLoaderMetadata=Bt,e.GLTF1=Zn,e.GLTF2=Au,e.GLTFFileLoader=mn,e.GLTFLoaderDefaultOptions=dn,e.GLTFValidation=tn,e.GaussianSplattingStream=au,e.MTLFileLoader=Al,e.OBJFileLoader=Cl,e.ReadBvh=m,e.RegisterBVHFileLoader=g,e.RegisterGLTFFileLoader=pn,e.RegisterOBJFileLoader=Ol,e.RegisterSPLATFileLoader=mu,e.RegisterSTLFileLoader=Nl,e.SPLATFileLoader=du,e.STLFileLoader=Ll,e.SolidParser=Ml,e.registerBuiltInLoaders=pu});
|
|
2
2
|
//# sourceMappingURL=babylonjs.loaders.min.js.map
|