babylonjs-loaders 9.27.0 → 9.28.0

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.
@@ -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),p=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),p=new t.Animation(`${e.name}_rot`,"rotationQuaternion",l.frameRate,t.Animation.ANIMATIONTYPE_QUATERNION,l.loopMode),f=[],m=[];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&&m.push({frame:n.frame,value:n.rotation.clone()})}return f.length>0&&(h.setKeys(f),u.push(h)),m.length>0&&(p.setKeys(m),u.push(p)),u}(e,u);for(const e of p)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 p=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 m=parseFloat(f.trim());if(d.endsWith("position"))switch(d){case n:h.position.x=m;break;case o:h.position.y=m;break;case s:h.position.z=m}else if(d.endsWith("rotation")){const e=t.Tools.ToRadians(m);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)}p=n.multiply(p)}}t.Quaternion.FromRotationMatrixToRef(p,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 p=null===(i=e.shift())||void 0===i?void 0:i.trim().split(/\s+/);if(!p)throw new Error("Unexpected end of file: missing OFFSET");if(d=p,"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 p(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 p=r.shift();if(!p||"HIERARCHY"!==p.trim().toUpperCase())throw new Error("HIERARCHY expected");const f=r.shift();if(!f)throw new Error("Unexpected end of file after HIERARCHY");const m=h(r,f.trim(),null,u),g=r.shift();if(!g||"MOTION"!==g.trim().toUpperCase())throw new Error("MOTION expected");const _=r.shift();if(!_)throw new Error("Unexpected end of file before frame count");const v=_.trim().split(/[\s]+/);if(v.length<2)throw new Error("Invalid frame count line");const y=parseInt(v[1]);if(isNaN(y))throw new Error("Failed to read number of frames.");u.numFrames=y;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<y;++e){const t=r.shift();t&&d(t.trim().split(/[\s]+/)||[],e,m,{i:0})}return u.root=m,c(u.root,null,u),u.skeleton.returnToRest(),u.skeleton}const f={name:"bvh",extensions:{".bvh":{isBinary:!1}}};class m{constructor(e){this.name=f.name,this.extensions=f.extensions,this._loadingOptions=Object.assign(Object.assign({},m._DefaultLoadingOptions),null!=e?e:{})}static get _DefaultLoadingOptions(){return{loopMode:t.Animation.ANIMATIONLOOPMODE_CYCLE}}createPlugin(e){return new m(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=p(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=p(n,e,o,this._loadingOptions);return o.skeletons.push(t),Promise.resolve(o)}catch(e){return Promise.reject(e)}}}let g=!1;function _(){g||(g=!0,t.RegisterSceneLoaderPlugin(new m))}var v={__proto__:null,BVHFileLoader:m,RegisterBVHFileLoader:_};_();var y={__proto__:null,BVHFileLoader:m,ReadBvh:p,RegisterBVHFileLoader:_};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())})}function x(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)}function T(e,t,n,o,s){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?s.call(e,n):s?s.value=n:t.set(e,n),n}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;const A=[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],w=[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],M=[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],S=[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],R=[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 I{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 F,E;function N(){if(!F){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;F=new O(e)}return F}function L(){return E||(E=new O(new Array(32).fill(5))),E}function k(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 P(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=A[r]+e.readBits(w[r]),a=o.decode(e);if(a>29)throw new Error("deflate: invalid distance symbol");const l=M[a]+e.readBits(S[a]);t.copy(l,i)}}function B(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[R[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})}}let D=!0;function V(e,t,n,o,s){let r,i,a,l;if(o?(U(t,n,25,s,"FBX node header"),r=H(e,n),i=H(e,n+8),a=H(e,n+16),l=25):(U(t,n,13,s,"FBX node header"),r=e.getUint32(n,D),i=e.getUint32(n+4,D),a=e.getUint32(n+8,D),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];U(t,n+l,u,r,"FBX node name");const c=j(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 p=[];for(let n=0;n<i;n++){const n=G(e,t,d,h);p.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=V(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:p,children:f},endOffset:r}}function G(e,t,n,o){U(t,n,1,o,"FBX property type");const s=String.fromCharCode(t[n]);switch(n+=1,s){case"C":{U(t,n,1,o,"FBX boolean property");const e=t[n];return e>1?{property:{type:"int32",value:e},nextOffset:n+1}:{property:{type:"boolean",value:0!==e},nextOffset:n+1}}case"Z":return U(t,n,1,o,"FBX byte property"),{property:{type:"int32",value:t[n]},nextOffset:n+1};case"Y":return U(t,n,2,o,"FBX int16 property"),{property:{type:"int16",value:e.getInt16(n,D)},nextOffset:n+2};case"I":return U(t,n,4,o,"FBX int32 property"),{property:{type:"int32",value:e.getInt32(n,D)},nextOffset:n+4};case"F":return U(t,n,4,o,"FBX float32 property"),{property:{type:"float32",value:e.getFloat32(n,D)},nextOffset:n+4};case"D":return U(t,n,8,o,"FBX float64 property"),{property:{type:"float64",value:e.getFloat64(n,D)},nextOffset:n+8};case"L":{U(t,n,8,o,"FBX int64 property");const s=K(e,n),r={type:"int64",value:s};return Number.isSafeInteger(s)||(r.raw=function(e,t){let n=e.getUint32(D?t:t+4,D),o=e.getUint32(D?t+4:t,D);const s=!!(2147483648&o);s&&(n=1+~n>>>0,o=~o+(0===n?1:0)>>>0);const r=[];for(;0!==o||0!==n;){const e=Math.floor(o/10),t=o%10*4294967296+n;r.push(t%10),o=e,n=Math.floor(t/10)}return(s?"-":"")+(r.length>0?r.reverse().join(""):"0")}(e,n)),{property:r,nextOffset:n+8}}case"S":{U(t,n,4,o,"FBX string property length");const s=e.getUint32(n,D);U(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":{U(t,n,4,o,"FBX raw property length");const s=e.getUint32(n,D);return U(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 $(e,t,n,"float32[]",4,o);case"d":return $(e,t,n,"float64[]",8,o);case"i":return $(e,t,n,"int32[]",4,o);case"l":return $(e,t,n,"int64[]",8,o);case"b":case"c":return $(e,t,n,"boolean[]",1,o);default:throw new Error(`Unknown FBX property type: '${s}' at offset ${n-1}`)}}function $(e,t,n,o,s,r){U(t,n,12,r,`FBX array property header for ${o}`);const i=e.getUint32(n,D),a=e.getUint32(n+4,D),l=e.getUint32(n+8,D),u=i*s;let c;if(U(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 I(t);let i=!1;for(;!i;)switch(i=1===s.readBits(1),s.readBits(2)){case 0:k(s,r);break;case 1:P(s,r,N(),L());break;case 2:{const{literalLengthTree:e,distanceTree:t}=B(s);P(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)}!D&&s>1&&"int64[]"!==o&&function(e,t){for(let n=0;n+t<=e.length;n+=t)for(let o=n,s=n+t-1;o<s;o++,s--){const t=e[o];e[o]=e[s],e[s]=t}}(c,s);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]=K(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 U(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 H(e,t){const n=e.getUint32(D?t:t+4,D);return 4294967296*e.getUint32(D?t+4:t,D)+n}function K(e,t){const n=e.getUint32(D?t:t+4,D);return 4294967296*e.getInt32(D?t+4:t,D)+n}function j(e,t,n){let o="";for(let s=0;s<n;s++)o+=String.fromCharCode(e[t+s]);return o}function W(e){const t=new X(e),n=function(e){const t=e.match(/;\s*FBX\s+(\d+)\.(\d+)\.(\d+)/);if(t)return 1e3*parseInt(t[1])+100*parseInt(t[2])+parseInt(t[3]);const n=e.match(/FBXVersion:\s*(\d+)/);return n?parseInt(n[1]):e.includes("Properties70")?7e3:6e3}(e),o=[];for(;!t.isEOF()&&(t.skipWhitespaceAndComments(),!t.isEOF());){const e=Y(t);e&&o.push(e)}return n>=7200&&q(o),{version:n,nodes:o}}function q(e){for(const t of e){if("KeyAttrDataFloat"===t.name&&1===t.properties.length&&t.properties[0].value instanceof Float64Array){const e=t.properties[0].value,n=new Int32Array(e.length);for(let t=0;t<e.length;t++)n[t]=0|e[t];t.properties[0]={type:"float32[]",value:new Float32Array(n.buffer)}}t.children.length>0&&q(t.children)}}var z;!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"}(z||(z={}));let X=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++,t.includes("&quot;")&&(t=t.split("&quot;").join('"')),{type:2,value:t,pos:e}}readNumber(){const e=this.pos;if("-"!==this.text[this.pos]&&"+"!==this.text[this.pos]||this.pos++,this.pos<this.len&&this.isIdentStart(this.text[this.pos])){for(;this.pos<this.len&&this.isIdentStart(this.text[this.pos]);)this.pos++;return this.skipSpecialNumberSuffix(),{type:1,value:this.text.substring(e,this.pos),pos:e}}for(;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++;if(this.pos<this.len&&"#"===this.text[this.pos]){for(this.pos++;this.pos<this.len&&(this.isIdentStart(this.text[this.pos])||this.isDigit(this.text[this.pos]));)this.pos++;this.skipSpecialNumberSuffix()}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 this.skipSpecialNumberSuffix(),{type:0,value:this.text.substring(e,this.pos),pos:e}}skipSpecialNumberSuffix(){if(this.pos<this.len&&"("===this.text[this.pos])for(;this.pos<this.len;){const e=this.text[this.pos];if("("!==e&&")"!==e&&!this.isIdentChar(e))break;this.pos++}}isDigit(e){return e>="0"&&e<="9"}isNumberStart(e){if(this.isDigit(e)||"."===e)return!0;if(("-"===e||"+"===e)&&this.pos+1<this.len){const e=this.text[this.pos+1];return this.isDigit(e)||"."===e||Q(this.text.substring(this.pos+1,this.pos+10))}return!!Q(this.text.substring(this.pos,this.pos+9))&&!this.isFollowedByColon(this.pos)}isFollowedByColon(e){let t=e;for(;t<this.len&&this.isIdentChar(this.text[t]);)t++;for(;t<this.len&&(" "===this.text[t]||"\t"===this.text[t]);)t++;return t<this.len&&":"===this.text[t]}isIdentStart(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||"_"===e}isIdentChar(e){return this.isIdentStart(e)||this.isDigit(e)||"|"===e||"-"===e}};function Y(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){const t=e.next();n.push(Z(t.value))}else{if(0!==t.type||e.isNextNodeStart())break;{const t=e.next();n.push(Z(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=Z(t.value);if(!Number.isInteger(n)||t.value.includes(".")||t.value.includes("e")||t.value.includes("E"))s.push({type:"float64",value:n});else{const e={type:ee(n)?"int32":"int64",value:n};Number.isSafeInteger(n)||(e.raw=J(t.value)),s.push(e)}}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=Y(e);if(!t)break;r.push(t)}e.expect(4)}return{name:o,properties:s,children:r}}function Q(e){return/^(?:inf(?:inity)?|nan|ind)(?![A-Za-z0-9_|])/i.test(e)}function Z(e){const t=Number(e);if(!Number.isNaN(t))return t;const n=e.startsWith("-")?-1:1,o=e.replace(/^[+-]/,"").replace(/\(.*$/,"");return/#INF/i.test(o)||/^inf/i.test(o)?n*(1/0):NaN}function J(e){const t=e.startsWith("-"),n=e.replace(/^[+-]/,"").replace(/^0+(?=\d)/,"");return t&&"0"!==n?`-${n}`:n}function ee(e){return e>=-2147483648&&e<=2147483647}function te(e,t){return e.children.find(e=>e.name===t)}function ne(e,t){return e.nodes.find(e=>e.name===t)}function oe(e,t){if(t<e.properties.length)return e.properties[t].value}function se(e){if(!e||0===e.properties.length)return null;const t=e.properties[0].value;if(1===e.properties.length&&(t instanceof Float32Array||t instanceof Float64Array||t instanceof Int32Array||t instanceof Uint8Array))return t;const n=new Float64Array(e.properties.length);for(let t=0;t<e.properties.length;t++){const o=e.properties[t].value;if("number"==typeof o)n[t]=o;else{if("boolean"!=typeof o)return null;n[t]=o?1:0}}return n}function re(e){const t=e.indexOf("\0");if(t>=0)return e.substring(0,t);const n=e.indexOf("::");return n>=0?e.substring(n+2):e}function ie(e,t,n){const o=e.get(t);if(o)return n?o.get(n):o.values().next().value}function ae(e,t,n,o=0){var s;return null===(s=ce(e,t,n))||void 0===s?void 0:s[o]}function le(e,t,n,o){var s;return null!==(s=de(ae(e,t,n)))&&void 0!==s?s:o}function ue(e,t,n,o){const s=ce(e,t,n);if(!s)return o;const r=de(s[0]),i=de(s[1]),a=de(s[2]);return void 0!==r&&void 0!==i&&void 0!==a?[r,i,a]:o}function ce(e,t,n){var o,s;return null!==(o=function(e,t){const n=[te(e,"Properties70"),te(e,"Properties60")].filter(e=>void 0!==e);let o;for(const e of n)for(const n of e.children)"P"!==n.name&&"Property"!==n.name||oe(n,0)===t&&(o=n.properties.slice("Property"===n.name?3:4).map(e=>e.value));return o}(e,n))&&void 0!==o?o:null===(s=null==t?void 0:t.properties.get(n))||void 0===s?void 0:s.values}function de(e){if("number"==typeof e)return e}function he(e,t,n){var o;const s=new Map,r=te(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=_e(e);t&&s.set(t.name,t)}return{objectType:e,templateName:t,properties:s}}function pe(e){const t=[];if(!e)return t;for(const n of e.children)if("Properties70"===n.name||"Properties60"===n.name)for(const e of n.children){if("P"!==e.name&&"PS"!==e.name&&"Property"!==e.name)continue;const n=oe(e,0);if("string"!=typeof n)continue;const o="Property"!==e.name,s=oe(e,1),r=oe(e,o?3:2);t.push({name:n,type:"string"==typeof s?s:"",flags:"string"==typeof r?r:"",values:e.properties.slice(o?4:3).map(e=>e.value)})}return t}function fe(e){const t={};let n=!1;for(const o of pe(e)){if(!o.flags.includes("U"))continue;const e=ge(o.values,o.type);void 0!==e&&(t[o.name]=e,n=!0)}return n?t:void 0}const me=new Set(["Integer","int","Number","double","Float","float","Bool","bool","Enum","enum","Visibility","Roll","Weight","Distance","KTime","Time"]);function ge(e,t){if(0===e.length)return;const n=e[0];if(void 0!==t&&me.has(t)&&("number"==typeof n||"boolean"==typeof n))return n;if(1===e.length)return"string"==typeof n||"number"==typeof n||"boolean"==typeof n?n:void 0;const o=[];for(const t of e)if("number"==typeof t)o.push(t);else{if("boolean"!=typeof t)break;o.push(t?1:0)}return o.length===e.length?o:"string"==typeof n?n:void 0}function _e(e){var t,n,o;const s=oe(e,0);return s?{name:s,propertyType:null!==(t=oe(e,1))&&void 0!==t?t:"",label:null!==(n=oe(e,2))&&void 0!==n?n:"",flags:null!==(o=oe(e,3))&&void 0!==o?o:"",values:e.properties.slice(4).map(e=>e.value)}:null}function ve(e,t){const n=ue(e,t,"Lcl Translation",[0,0,0]),o=ue(e,t,"Lcl Rotation",[0,0,0]),s=ue(e,t,"Lcl Scaling",[1,1,1]);let r=ue(e,t,"PreRotation",[0,0,0]),i=ue(e,t,"PostRotation",[0,0,0]);const a=ue(e,t,"RotationPivot",[0,0,0]),l=ue(e,t,"ScalingPivot",[0,0,0]),u=ue(e,t,"RotationOffset",[0,0,0]),c=ue(e,t,"ScalingOffset",[0,0,0]),d=ue(e,t,"GeometricTranslation",[0,0,0]),h=ue(e,t,"GeometricRotation",[0,0,0]),p=ue(e,t,"GeometricScaling",[1,1,1]);let f=le(e,t,"RotationOrder",0);const m=le(e,t,"InheritType",1),g=le(e,t,"RotationActive",1),_=le(e,t,"RotationSpaceForLimitOnly",0),v=0!==g&&0===_;return v||(f=0,r=[0,0,0],i=[0,0,0]),{translation:n,rotation:o,scale:s,preRotation:r,postRotation:i,rotationPivot:a,scalingPivot:l,rotationOffset:u,scalingOffset:c,geometricTranslation:d,geometricRotation:h,geometricScaling:p,rotationOrder:f,inheritType:m,rotationActive:v,diagnostics:0===m||1===m||2===m?[]:[`InheritType ${m} is unknown; treated as RSrs.`]}}function ye(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 be(e){return{name:"Version",properties:[{type:"int32",value:e}],children:[]}}function xe(e,t,n,o,s){return{name:e,properties:[{type:"int64",value:t},{type:"string",value:n},{type:"string",value:o}],children:s}}function Te(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 Ae(e,t){var n,o;const s=re(null!==(n=oe(e,0))&&void 0!==n?n:e.name),r=null!==(o=oe(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 we(e,t){var n;return{name:"Geometry",properties:[{type:"int64",value:t},{type:"string",value:re(null!==(n=oe(e,0))&&void 0!==n?n:"Geometry")},{type:"string",value:"Mesh"}],children:e.children}}function Me(e,t){var n,o,s;const r=re(null!==(n=oe(e,1))&&void 0!==n?n:"Geometry"),i=te(e,"Vertices"),a=i?Fe(Ne(i)):new Float64Array(0),l=te(e,"PolygonVertexIndex"),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}(l?Ee(Ne(l)):new Int32Array(0)),d=function(e,t,n){const o=[];for(let s=0;s<e.length;s++){const r=e[s];o.push(...Se(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),p=te(e,"LayerElementNormal");let f=null;p&&(f=Ie(p,"Normals","NormalsIndex",h,a.length,3,u));const m=e.children.filter(e=>"LayerElementUV"===e.name),g=[];for(const e of m){const t=te(e,"Name"),n=t&&null!==(o=oe(t,0))&&void 0!==o?o:`UVSet${g.length}`,s=Ie(e,"UV","UVIndex",h,a.length,2,u);s&&g.push({name:n,data:s})}const _=g.length>0?g[0].data:null,v=te(e,"LayerElementColor");let y=null;if(v){const e=Ie(v,"Colors","ColorIndex",h,a.length,4,u);if(e){y=new Float32Array(e.length);for(let t=0;t<e.length;t++)y[t]=e[t]}}const b=te(e,"LayerElementTangent"),x=te(e,"LayerElementBinormal"),T=x?Ie(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=te(e,"Tangents");if(!c)return 3;const d=Fe(Ne(c)),h=null!==(a=oe(null!==(i=te(e,"MappingInformationType"))&&void 0!==i?i:{name:"",properties:[],children:[]},0))&&void 0!==a?a:"",p=null!==(u=oe(null!==(l=te(e,"ReferenceInformationType"))&&void 0!==l?l:{name:"",properties:[],children:[]},0))&&void 0!==u?u:"",f=te(e,"TangentsIndex"),m=f?Ee(Ne(f)):null,g="IndexToDirect"===p&&m?Math.max(...Array.from(m),0)+1:"ByControlPoint"===h||"ByVertice"===h?s:"AllSame"===h?1:o.length;if(g>0&&d.length%g===0){const e=d.length/g;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=Ie(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]:Oe(e,l,o,s)}return l}(b,h,a.length/3,f,T,u):null,w=te(e,"LayerElementMaterial");let M=null;w&&(M=function(e,t){var n,o;const s=te(e,"MappingInformationType"),r=te(e,"ReferenceInformationType");if(!s||!r)return null;const i=null!==(n=oe(s,0))&&void 0!==n?n:"",a=null!==(o=oe(r,0))&&void 0!==o?o:"";if("AllSame"===i){const n=te(e,"Materials"),o=n?Ee(Ne(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=te(e,"Materials");if(!t)return null;const n=Ee(Ne(t));if("Direct"===a||"IndexToDirect"===a)return n}return null}(w,c.length));const S=function(e,t,n,o,s,r,i,a,l){const u=n.length,c=new Uint32Array(u),d=[],h=new Map,p=r.length;for(let e=0;e<u;e++){let t=String(n[e].controlPointIndex);o&&(t+=`|${o[3*e]},${o[3*e+1]},${o[3*e+2]}`);for(let n=0;n<p;n++){const o=r[n].data;t+=`|${o[2*e]},${o[2*e+1]}`}i&&(t+=`|${i[4*e]},${i[4*e+1]},${i[4*e+2]},${i[4*e+3]}`),a&&(t+=`|${a[4*e]},${a[4*e+1]},${a[4*e+2]},${a[4*e+3]}`);let s=h.get(t);void 0===s&&(s=d.length,h.set(t,s),d.push(e)),c[e]=s}const f=d.length,m=new Float64Array(3*f),g=new Uint32Array(f),_=(e,t,n)=>{if(!e)return null;const o=new n(f*t);for(let n=0;n<f;n++){const s=d[n]*t;for(let r=0;r<t;r++)o[n*t+r]=e[s+r]}return o};for(let t=0;t<f;t++){const o=n[d[t]].controlPointIndex;m[3*t]=e[3*o],m[3*t+1]=e[3*o+1],m[3*t+2]=e[3*o+2],g[t]=o}const v=3*t.length,y=new Uint32Array(v);for(let e=0;e<t.length;e++)y[3*e]=c[t[e].vertices[0]],y[3*e+1]=c[t[e].vertices[1]],y[3*e+2]=c[t[e].vertices[2]];const b=r.map(e=>({name:e.name,data:_(e.data,2,Float64Array)}));return{positions:m,indices:y,normals:_(o,3,Float64Array),uvs:b.length>0?b[0].data:_(s,2,Float64Array),uvSets:b,colors:_(i,4,Float32Array),tangents:_(a,4,Float64Array),binormals:_(l,3,Float64Array),controlPointIndices:g}}(a,d,h,f,_,g,y,A,T);let R=null;if(M){let e=!0;const t=M[0];for(let n=1;n<M.length;n++)if(M[n]!==t){e=!1;break}if(!e||0!==t){const e=S.indices.length/3;R=new Int32Array(e);for(let e=0;e<d.length;e++)R[e]=null!==(s=M[d[e].polyIndex])&&void 0!==s?s:0}}return{id:t,name:r,positions:S.positions,indices:S.indices,normals:S.normals,uvs:S.uvs,uvSets:S.uvSets,colors:S.colors,tangents:S.tangents,binormals:S.binormals,controlPointIndices:S.controlPointIndices,materialIndices:R,diagnostics:u}}function Se(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],p=t[a+2];n+=(u-h)*(c+p),o+=(c-p)*(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}),Re(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}),Re(e,t);const i=function(e,t,n){const o=e.length,s=new Int32Array(o),r=new Int32Array(o);for(let e=0;e<o;e++)s[e]=(e+o-1)%o,r[e]=(e+1)%o;const i=1e-12*Math.abs(n)+1e-300,a=t?1:-1,l=t=>a*Ce(e[s[t]],e[t],e[r[t]]),u=new Uint8Array(o);for(let e=0;e<o;e++)u[e]=l(e)<-i?1:0;const c=(e,t,n,o)=>a*Ce(t,n,e)>=-i&&a*Ce(n,o,e)>=-i&&a*Ce(o,t,e)>=-i,d=[];let h=o,p=0,f=0;for(;h>3;){const t=s[p],n=r[p];let o=!1;if(!u[p])if(l(p)<=i)o=!0,d.push([t,p,n]);else{o=!0;for(let s=r[n];s!==t;s=r[s])if(u[s]&&c(e[s],e[t],e[p],e[n])){o=!1;break}o&&d.push([t,p,n])}if(o)r[t]=n,s[n]=t,h--,u[t]=l(t)<-i?1:0,u[n]=l(n)<-i?1:0,p=n,f=0;else if(p=n,++f>h)return null}const m=p;return d.push([s[m],m,r[m]]),d}(s,r>0,r);return i?i.map(([n,o,s])=>({vertices:[e.startIndex+n,e.startIndex+o,e.startIndex+s],polyIndex:t})):(o.push({type:"triangulation-fallback",message:`Polygon ${t} could not be fully ear-clipped; using fan triangulation.`,polygonIndex:t}),Re(e,t))}function Re(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 Ce(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function Ie(e,t,n,o,s,r,i){var a,l;const u=te(e,"MappingInformationType"),c=te(e,"ReferenceInformationType");if(!u||!c)return null;const d=null!==(a=oe(u,0))&&void 0!==a?a:"",h=null!==(l=oe(c,0))&&void 0!==l?l:"",p=te(e,t);if(!p)return null;const f=Fe(Ne(p));let m=null;if("IndexToDirect"===h){const t=te(e,n);t&&(m=Ee(Ne(t)))}const g=new Float64Array(o.length*r);for(let t=0;t<o.length;t++){const n=o[t];let s;s="ByPolygonVertex"===d?"IndexToDirect"===h&&m?m[n.globalIndex]:n.globalIndex:"ByControlPoint"===d||"ByVertice"===d?"IndexToDirect"===h&&m?m[n.controlPointIndex]:n.controlPointIndex:"ByPolygon"===d?"IndexToDirect"===h&&m?m[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}),g[t*r+n]=0):g[t*r+n]=f[o]}}return g}function Oe(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||e instanceof Uint8Array)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 Ee(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||e instanceof Uint8Array){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 Ne(e){var t;return null!==(t=se(e))&&void 0!==t?t:new Float64Array(0)}function Le(e){return"Closed"===e?"closed":"Periodic"===e?"periodic":"open"}function ke(e,t,n){const o={order:e,topology:Le(t),knots:n,tMin:0,tMax:0,spans:new Float64Array(0),valid:!1};if(e>1&&e<=128){const t=e-1;if(n.length>=2*t+1){o.tMin=n[t],o.tMax=n[n.length-t-1];const e=n.length-2*t,s=[];let r=-1/0;for(let o=0;o<e;o++){const e=n[t+o];e!==r&&(s.push(e),r=e)}o.spans=Float64Array.from(s),o.valid=!0;for(let e=1;e<n.length;e++)if(!(n[e-1]<=n[e])){o.valid=!1;break}}}return o}function Pe(e,t,n,o){if(t<0||t>=e.length||e.length-t<n)return 0;const s=e[t],r=e[t+n];return s>=r||o<=s?0:o>=r?1:(o-s)/(r-s)}function Be(e,t,n){if(t<0||t>=e.length||e.length-t<n)return 0;const o=e[t],s=e[t+n];return o>=s?0:n/(s-o)}function De(e,t,n,o){if(e.order<=1||!e.valid)return-1;const s=e.order-1,r=e.knots;let i;if(t<=e.tMin)i=s,t=e.tMin;else if(t>=e.tMax)i=r.length-s-2,t=e.tMax;else{let e=0,n=r.length-1;for(;e<n;){const o=e+n>>1;r[o+1]<=t?e=o+1:n=o}if(!(r[e]<=t&&t<r[e+1]))return-1;i=e}if(i<s)return-1;n[0]=1;for(let e=1;e<=s;e++){let a=0,l=1-Pe(r,i-e+1,e,t),u=0;const c=null!==o&&e===s;c&&(u=Be(r,i-e+1,e));for(let s=e;s>0;s--){const d=Pe(r,i-e+s,e,t),h=n[s-1];if(n[s]=d*h+l*a,c){const t=Be(r,i-e+s,e);o[s]=t*h-u*a,u=t}a=h,l=1-d}n[0]=l*a,c&&(o[0]=-u*a)}return i-s}function Ve(e,t,n,o,s){const r=De(e.basis,t,o,s);if(r<0||0===e.numControlPoints)return!1;const i=e.basis.order;let a=0,l=0,u=0,c=0,d=0,h=0,p=0,f=0;const m=e.controlPoints;for(let t=0;t<i;t++){const n=(r+t)%e.numControlPoints*4,i=o[t]*m[n+3],g=s[t]*m[n+3];a+=m[n]*i,l+=m[n+1]*i,u+=m[n+2]*i,c+=i,d+=m[n]*g,h+=m[n+1]*g,p+=m[n+2]*g,f+=g}const g=0!==c?1/c:0;return n[0]=a*g,n[1]=l*g,n[2]=u*g,n[3]=(d-f*n[0])*g,n[4]=(h-f*n[1])*g,n[5]=(p-f*n[2])*g,!0}function Ge(e,t,n,o,s){const r=De(e.basisU,t,s.wu,s.du),i=De(e.basisV,n,s.wv,s.dv);if(r<0||i<0||0===e.numU||0===e.numV)return!1;const a=e.basisU.order,l=e.basisV.order,u=e.controlPoints;let c=0,d=0,h=0,p=0,f=0,m=0,g=0,_=0,v=0,y=0,b=0,x=0;for(let t=0;t<l;t++){const n=(i+t)%e.numV,o=s.wv[t],l=s.dv[t];for(let t=0;t<a;t++){const i=(r+t)%e.numU,a=s.wu[t],T=s.du[t],A=4*(n*e.numU+i),w=u[A+3],M=a*o*w,S=T*o*w,R=l*a*w,C=u[A],I=u[A+1],O=u[A+2];c+=C*M,d+=I*M,h+=O*M,p+=M,f+=C*S,m+=I*S,g+=O*S,_+=S,v+=C*R,y+=I*R,b+=O*R,x+=R}}const T=0!==p?1/p:0;return o[0]=c*T,o[1]=d*T,o[2]=h*T,o[3]=(f-_*o[0])*T,o[4]=(m-_*o[1])*T,o[5]=(g-_*o[2])*T,o[6]=(v-x*o[0])*T,o[7]=(y-x*o[1])*T,o[8]=(b-x*o[2])*T,!0}function $e(e,t){return void 0!==t&&Number.isFinite(t)&&t>0?Math.min(64,Math.max(1,Math.floor(t))):e>0?Math.min(16,Math.floor(e)):4}function Ue(e,t){const n=te(e,t);if(!n)return null;const o=se(n);return o?o instanceof Float64Array?o:Float64Array.from(o):null}function He(e){const t=pe(e).find(e=>"Color"===e.name);return t&&"number"==typeof t.values[0]&&"number"==typeof t.values[1]&&"number"==typeof t.values[2]?[t.values[0],t.values[1],t.values[2]]:null}function Ke(e,t,n){var o;const s=re(null!==(o=oe(e,1))&&void 0!==o?o:"NurbsSurface"),r=function(e){var t,n,o,s,r,i;const a=te(e,"NurbsSurfaceOrder"),l=te(e,"Dimensions"),u=te(e,"Step"),c=te(e,"Form"),d=te(e,"FlipNormals"),h=a&&null!==(t=oe(a,0))&&void 0!==t?t:0,p=a&&null!==(n=oe(a,1))&&void 0!==n?n:0,f=l&&null!==(o=oe(l,0))&&void 0!==o?o:0,m=l&&null!==(s=oe(l,1))&&void 0!==s?s:0,g=u&&null!==(r=oe(u,0))&&void 0!==r?r:0,_=u&&null!==(i=oe(u,1))&&void 0!==i?i:0,v=c?oe(c,0):void 0,y=c?oe(c,1):void 0,b=d?oe(d,0):0,x=Ue(e,"Points"),T=Ue(e,"KnotVectorU"),A=Ue(e,"KnotVectorV");return!x||!T||!A||x.length%4!=0||x.length/4!==f*m||f<=0||m<=0?null:{basisU:ke(h,v,T),basisV:ke(p,y,A),numU:f,numV:m,controlPoints:x,flipNormals:!0===b||1===b,stepU:"number"==typeof g?g:0,stepV:"number"==typeof _?_:0}}(e),i=[];if(!r)return null;const a=function(e,t,n){const o=e.basisU,s=e.basisV;if(!o.valid||!s.valid||0===e.numU||0===e.numV||o.spans.length<2||s.spans.length<2)return null;const r="open"===o.topology,i="open"===s.topology,a=o.spans.length,l=s.spans.length,u=(a-1)*t,c=(l-1)*n,d=a+(a-1)*(t-1),h=d*(l+(l-1)*(n-1));if(h>1073741823||u*c>1073741823)return null;const p=new Uint32Array(h),f=new Float64Array(3*h);let m=0;const g=new Float64Array(2*h),_={wu:new Float64Array(o.order+1),wv:new Float64Array(s.order+1),du:new Float64Array(o.order+1),dv:new Float64Array(s.order+1)},v=new Float64Array(9);for(let u=0;u<l;u++){const c=u+1===l?1:n;for(let h=0;h<c;h++){const y=u*n+h;let b=s.spans[u];if(h>0){const e=h/c;b=b*(1-e)+e*s.spans[u+1]}const x=b;u+1!==l||i||(b=s.spans[0]);for(let n=0;n<a;n++){const s=n+1===a?1:t;for(let i=0;i<s;i++){const c=n*t+i;let T=o.spans[n];if(i>0){const e=i/s;T=T*(1-e)+e*o.spans[n+1]}const A=T;n+1!==a||r||(T=o.spans[0]);let w=0,M=0,S=0;Ge(e,T,b,v,_)&&(w=v[0],M=v[1],S=v[2]);const R=[];(0===u&&(n>0||i>0)||0===n&&(u>0||h>0))&&R.push(0),u+1===l&&(R.push(c),(n>0||i>0)&&R.push(y*d)),n+1===a&&(R.push(y*d),(u>0||h>0)&&R.push(d-1));const C=y*d+c;let I=m;for(const e of R){if(e>=C)continue;const t=p[e],n=f[3*t]-w,o=f[3*t+1]-M,s=f[3*t+2]-S;if(n*n+o*o+s*s<1e-7){I=t;break}}p[C]=I,I===m&&(f[3*I]=w,f[3*I+1]=M,f[3*I+2]=S,m++),g[2*C]=A,g[2*C+1]=x}}}}const y=[],b=[0,0,0,0],x=[0,0,0,0];for(let e=0;e<c;e++)for(let t=0;t<u;t++){b[0]=e*d+t,b[1]=e*d+t+1,b[2]=(e+1)*d+t+1,b[3]=(e+1)*d+t;for(let e=0;e<4;e++)x[e]=p[b[e]];let n=4;for(let e=0;e<4;e++){const t=(e+1)%4;if(x[e]===x[t]){for(let e=t;e<3;e++)b[e]=b[e+1],x[e]=x[e+1];n=3;break}}y.push(b[0],b[1],b[2]),4===n&&y.push(b[0],b[2],b[3])}const T=new Float64Array(3*m);for(let e=0;e<y.length;e+=3){const t=3*p[y[e]],n=3*p[y[e+1]],o=3*p[y[e+2]],s=f[n]-f[t],r=f[n+1]-f[t+1],i=f[n+2]-f[t+2],a=f[o]-f[t],l=f[o+1]-f[t+1],u=f[o+2]-f[t+2],c=r*u-i*l,d=i*a-s*u,h=s*l-r*a;for(const e of[t,n,o])T[e]+=c,T[e+1]+=d,T[e+2]+=h}const A=e.flipNormals?-1:1;for(let e=0;e<m;e++){const t=T[3*e],n=T[3*e+1],o=T[3*e+2],s=Math.hypot(t,n,o);s>0&&(T[3*e]=t/s*A,T[3*e+1]=n/s*A,T[3*e+2]=o/s*A)}const w=new Float64Array(3*h),M=new Float64Array(3*h);for(let e=0;e<h;e++){const t=3*p[e];w[3*e]=f[t],w[3*e+1]=f[t+1],w[3*e+2]=f[t+2],M[3*e]=T[t],M[3*e+1]=T[t+1],M[3*e+2]=T[t+2]}return{positions:w,indices:Uint32Array.from(y),normals:M,uvs:g}}(r,$e(r.stepU,n),$e(r.stepV,n));return a?{id:t,name:s,positions:a.positions,indices:a.indices,normals:a.normals,uvs:a.uvs,uvSets:[{name:"map1",data:a.uvs}],colors:null,tangents:null,binormals:null,controlPointIndices:null,materialIndices:null,diagnostics:i}:(i.push({type:"nurbs-invalid",message:`NURBS surface '${s}' has an invalid basis and was skipped.`}),{id:t,name:s,positions:new Float64Array(0),indices:new Uint32Array(0),normals:null,uvs:null,uvSets:[],colors:null,tangents:null,binormals:null,controlPointIndices:null,materialIndices:null,diagnostics:i})}function je(e,t,n=4){var o;const s=re(null!==(o=oe(e,1))&&void 0!==o?o:"NurbsCurve"),r=[],i=function(e){var t;const n=te(e,"Order"),o=te(e,"Form"),s=n&&null!==(t=oe(n,0))&&void 0!==t?t:0,r=o?oe(o,0):void 0,i=Ue(e,"Points"),a=Ue(e,"KnotVector");return i&&a&&i.length%4==0?{basis:ke(s,r,a),controlPoints:i,numControlPoints:i.length/4}:null}(e),a=i?function(e,t=4){const n=e.basis;if(!n.valid||0===e.numControlPoints||0===n.spans.length)return null;const o=Math.max(1,Math.floor(t)),s=n.spans.length,r=s+(s-1)*(o-1),i=r-("open"===n.topology?0:1),a=new Float64Array(3*r),l=new Float64Array(n.order+1),u=new Float64Array(n.order+1),c=new Float64Array(6);for(let t=0;t<s;t++){const r=t+1===s?1:o;for(let s=0;s<r;s++){const r=t*o+s;if(r<i){let i=n.spans[t];if(s>0){const e=s/o;i=i*(1-e)+e*n.spans[t+1]}Ve(e,i,c,l,u)&&(a[3*r]=c[0],a[3*r+1]=c[1],a[3*r+2]=c[2])}else a[3*r]=a[0],a[3*r+1]=a[1],a[3*r+2]=a[2]}}return a}(i,n):null;return a||r.push({type:"nurbs-invalid",message:`NURBS curve '${s}' has an invalid basis and was skipped.`}),{id:t,name:s,kind:"nurbsCurve",polylines:a?[a]:[],color:He(e),diagnostics:r}}function We(e,t){var n;const o=re(null!==(n=oe(e,1))&&void 0!==n?n:"Line"),s=[],r=Ue(e,"Points"),i=te(e,"PointsIndex"),a=i?se(i):null,l=[];if(r&&r.length%3==0){const e=r.length/3,t=a?Array.from(a):Array.from({length:e},(e,t)=>t);let n=[];const i=()=>{n.length>=2?l.push(Float64Array.from(n)):1===n.length&&s.push({type:"degenerate-polygon",message:`Line '${o}' has a single-point segment that was skipped.`}),n=[]};for(let a=0;a<t.length;a++){let l=t[a];const u=l<0;u&&(l=~l),l>=0&&l<e?n.push(r[3*l],r[3*l+1],r[3*l+2]):s.push({type:"layer-index-out-of-bounds",message:`Line '${o}' references point ${l} outside its ${e} points.`,index:a}),u&&i()}i()}return{id:t,name:o,kind:"line",polylines:l,color:He(e),diagnostics:s}}const qe=e=>({type:"string",value:e}),ze=e=>({type:"float64",value:e}),Xe=e=>({type:"int32",value:e}),Ye=(e,t=[],n=[])=>({name:e,properties:t,children:n});function Qe(e,t,n,...o){return Ye("Property",[qe(e),qe(t),qe(n),...o.map(e=>"string"==typeof e?qe(e):ze(e))])}function Ze(e,t,n,...o){return Ye("P",[qe(e),qe(t),qe(""),qe(n),...o.map(e=>"string"==typeof e?qe(e):ze(e))])}const Je=(e,t)=>Ye(e,[{type:t instanceof Int32Array?"int32[]":"float64[]",value:t}]);function et(e,t=0){var n;const o=null===(n=null==e?void 0:e.properties[t])||void 0===n?void 0:n.value;return"number"==typeof o?o:"boolean"==typeof o?o?1:0:void 0}function tt(e){if(!e)return[];const t=se(e);return t?Array.from(t):[]}function nt(e){const t=e?se(e):null;return t?t instanceof Float64Array?t:Float64Array.from(t):null}function ot(e){const t=e?se(e):null;return t?t instanceof Int32Array?t:Int32Array.from(t,e=>Math.trunc(e)):null}function st(e,t){if(e)for(const n of e.children){if("Channel"!==n.name)continue;const e=oe(n,0),o="T"===e?"t":"R"===e?"r":"S"===e?"s":void 0;if(!o||t[o])continue;const s=[0,0,0];let r=!1;for(const e of n.children){if("Channel"!==e.name)continue;const t=oe(e,0),n="X"===t?0:"Y"===t?1:"Z"===t?2:-1,o=et(te(e,"Default"));n>=0&&void 0!==o&&(s[n]=o,r=!0)}r&&(t[o]=s)}}function rt(e){const t=te(e,"Key");return!!(t&&t.properties.length>0)||e.children.some(e=>"Channel"===e.name&&rt(e))}function it(e,t){var n;const o=null!==(n=e.usedNames.get(t))&&void 0!==n?n:0;return e.usedNames.set(t,o+1),0===o?t:`${t} (${o+1})`}function at(e,t,n){e.connections.push(Ye("C",[qe("OO"),qe(t),qe(n)]))}function lt(e){const t=new Float64Array(e.length);for(let n=0;n+2<e.length;n+=3){const o=e[n],s=e[n+1],r=e[n+2],i=Math.hypot(o,s,r);i>0&&(t[n]=o/i,t[n+1]=s/i,t[n+2]=r/i)}return t}function ut(e,t){var n,o,s,r,i,a,l;const u=null!==(n=oe(t,0))&&void 0!==n?n:"Model",c=oe(null!==(o=te(t,"Type"))&&void 0!==o?o:Ye("x"),0),d=!!te(t,"Vertices"),h="Light"===c?"Light":"Camera"===c?"Camera":"LimbNode"===c?"LimbNode":d?"Mesh":"Null",p={};st(t.children.find(e=>"Channel"===e.name&&"Transform"===oe(e,0)),p),st(e.takeDefaults.get(u),p);const f=null!==(s=p.t)&&void 0!==s?s:[0,0,0],m=null!==(r=p.r)&&void 0!==r?r:[0,0,0],g=null!==(i=p.s)&&void 0!==i?i:[1,1,1],_=[Qe("Lcl Translation","Lcl Translation","A+",f[0],f[1],f[2]),Qe("Lcl Rotation","Lcl Rotation","A+",m[0],m[1],m[2]),Qe("Lcl Scaling","Lcl Scaling","A+",g[0],g[1],g[2])],v=t.children.find(e=>"Channel"===e.name&&"Visibility"===oe(e,0)),y=et(te(null!=v?v:Ye("x"),"Default"));if(void 0!==y&&y<=0&&_.push(Qe("Visibility","Visibility","A+",0)),"Light"===h)_.push(...function(e){const t=[],n=et(te(e,"LightType"));void 0!==n&&t.push(Qe("LightType","enum","",n));const o=tt(te(e,"Color"));o.length>=3&&t.push(Qe("Color","ColorRGB","",o[0],o[1],o[2]));const s=[["Intensity","Intensity"],["ConeAngle","OuterAngle"],["HotSpot","InnerAngle"]];for(const[n,o]of s){const s=et(te(e,n));void 0!==s&&t.push(Qe(o,"double","",s))}const r=et(te(e,"CastShadows"));return void 0!==r&&t.push(Qe("CastShadows","bool","",r)),t}(t));else if("Camera"===h)_.push(...function(e){const t=[],n=[["Aperture","FieldOfView"],["FieldOfViewXProperty","FieldOfViewX"],["FieldOfViewYProperty","FieldOfViewY"],["SqueezeRatio","FilmSqueezeRatio"],["FocalLength","FocalLength"],["AspectType","AspectRatioMode"],["AspectW","AspectWidth"],["AspectH","AspectHeight"],["ApertureMode","ApertureMode"],["NearPlane","NearPlane"],["FarPlane","FarPlane"],["Roll","Roll"]];for(const[o,s]of n){const n=et(te(e,o));void 0!==n&&t.push(Qe(s,"AspectRatioMode"===s||"ApertureMode"===s?"enum":"double","",n))}const o=tt(te(e,"CameraAperture"));return o.length>=2&&(t.push(Qe("FilmWidth","double","",o[0])),t.push(Qe("FilmHeight","double","",o[1]))),t}(t));else if("LimbNode"===h){const e=et(te(null!==(a=te(t,"Properties"))&&void 0!==a?a:Ye("x"),"Size"));void 0!==e&&_.push(Qe("Size","double","",e))}const b=[Ye("Version",[Xe(232)]),Ye("Properties60",[],_)];for(const e of["Culling","Position","Up","LookAt"]){const n=te(t,e);n&&b.push(n)}"Mesh"===h&&b.push(...function(e,t){var n;const o=nt(te(e,"Vertices")),s=ot(te(e,"PolygonVertexIndex"));if(!o||!s)return[];const r=Math.floor(o.length/3),i=s.length;i>0&&s[i-1]>=0&&(s[i-1]=~s[i-1]);const a=[Ye("GeometryVersion",[Xe(124)]),Je("Vertices",o),Je("PolygonVertexIndex",s)],l=nt(te(e,"Normals"));if(l){const e=Math.floor(l.length/3),n=e===i,o=e!==r||n&&5e3!==t?n?"ByPolygonVertex":void 0:"ByVertice";o&&a.push(Ye("LayerElementNormal",[Xe(0)],[Ye("Version",[Xe(101)]),Ye("Name",[qe("")]),Ye("MappingInformationType",[qe(o)]),Ye("ReferenceInformationType",[qe("Direct")]),Je("Normals",lt(l))]))}const u=te(e,"GeometryUVInfo"),c=u?nt(te(u,"TextureUV")):null;if(u&&c){const e=ot(te(u,"TextureUVVerticeIndex")),t=Math.floor(c.length/2);let n;const o=[Ye("Version",[Xe(101)]),Ye("Name",[qe("")])];e&&e.length===i?n=Ye("LayerElementUV",[Xe(0)],[...o,Ye("MappingInformationType",[qe("ByPolygonVertex")]),Ye("ReferenceInformationType",[qe("IndexToDirect")]),Je("UV",c),Je("UVIndex",e)]):t===i?n=Ye("LayerElementUV",[Xe(0)],[...o,Ye("MappingInformationType",[qe("ByPolygonVertex")]),Ye("ReferenceInformationType",[qe("Direct")]),Je("UV",c)]):t===r&&(n=Ye("LayerElementUV",[Xe(0)],[...o,Ye("MappingInformationType",[qe("ByVertice")]),Ye("ReferenceInformationType",[qe("Direct")]),Je("UV",c)])),n&&a.push(n)}const d=oe(null!==(n=te(e,"MaterialAssignation"))&&void 0!==n?n:Ye("x"),0),h=ot(te(e,"Materials"));if(h&&h.length>0){const e="ByPolygon"===d?"ByPolygon":"AllSame";a.push(Ye("LayerElementMaterial",[Xe(0)],[Ye("Version",[Xe(101)]),Ye("Name",[qe("")]),Ye("MappingInformationType",[qe(e)]),Ye("ReferenceInformationType",[qe("IndexToDirect")]),Je("Materials","AllSame"===e?Int32Array.of(h[0]):h)]))}for(const t of e.children)"Shape"===t.name&&a.push(t);return a}(t,e.version)),e.objects.push(Ye("Model",[qe(u),qe(h)],b)),function(e,t,n){var o;for(const s of t.children){if("Material"!==s.name)continue;const t=null!==(o=oe(s,0))&&void 0!==o?o:"Material",r=it(e,t.includes("::")?t:`Material::${t}`),i=(e,t)=>{const n=tt(te(s,e));return n.length>=3?Qe(t,"ColorRGB","",n[0],n[1],n[2]):null},a=(e,t)=>{const n=et(te(s,e));return void 0!==n?Qe(t,"double","",n):null},l=[i("Ambient","AmbientColor"),i("Diffuse","DiffuseColor"),i("Specular","SpecularColor"),i("Emissive","EmissiveColor"),a("Shininess","Shininess"),a("Alpha","Opacity"),a("Reflectivity","ReflectionFactor")].filter(e=>null!==e),u=te(s,"ShadingModel");e.objects.push(Ye("Material",[qe(r),qe("")],[Ye("Version",[Xe(100)]),null!=u?u:Ye("ShadingModel",[qe("phong")]),Ye("Properties60",[],l)])),at(e,r,n)}}(e,t,u),function(e,t,n){var o;const s=t.children.filter(e=>"Link"===e.name);if(0===s.length)return;const r=it(e,`Deformer::Skin ${re(n)}`);e.objects.push(Ye("Deformer",[qe(r),qe("Skin")],[Ye("Version",[Xe(100)]),Ye("Link_DeformAcuracy",[ze(50)])])),at(e,r,n);for(const t of s){const s=null!==(o=oe(t,0))&&void 0!==o?o:"",i=it(e,`SubDeformer::Cluster ${re(n)} ${re(s)}`),a=[Ye("Version",[Xe(100)]),Ye("Mode",[qe("Normalize")])];for(const e of["Indexes","Weights","Transform","TransformLink"]){const n=te(t,e);if(!n)continue;const o="Indexes"===e?ot(n):nt(n);o&&a.push(Je(e,o))}e.objects.push(Ye("Deformer",[qe(i),qe("Cluster")],a)),at(e,i,r),at(e,s,i)}}(e,t,u);const x=te(t,"Children");for(const t of null!==(l=null==x?void 0:x.properties)&&void 0!==l?l:[])"string"==typeof t.value&&at(e,t.value,u)}const ct={Aim:"aim","Parent-Child":"parent","Position From Positions":"position","Rotation From Rotations":"rotation","Scale From Scales":"scale","Single Chain IK":"singleChainIK"};function dt(e,t){return e&&"number"==typeof e[0]&&"number"==typeof e[1]&&"number"==typeof e[2]?[e[0],e[1],e[2]]:t}function ht(e,t){const n=null==e?void 0:e[0];return"number"==typeof n?n:"boolean"==typeof n?n?1:0:t}function pt(e,t,n){var o,s,r,i,a;const l=t.children.find(e=>"Type"===e.name),u=null!==(s=null!==(o=l?oe(l,0):void 0)&&void 0!==o?o:oe(t,2))&&void 0!==s?s:"",c=null!==(r=ct[u])&&void 0!==r?r:"unknown",d=new Map;for(const e of pe(t))d.set(e.name,e.values);const h=(e,t)=>[0!==ht(d.get(`${e}X`),t?1:0),0!==ht(d.get(`${e}Y`),t?1:0),0!==ht(d.get(`${e}Z`),t?1:0)],p={id:e,name:re(null!==(i=oe(t,1))&&void 0!==i?i:"Constraint"),type:c,typeName:u,targets:[],weight:ht(d.get("Weight"),100)/100,active:0!==ht(d.get("Active"),1),affectTranslation:[!0,!0,!0],affectRotation:[!0,!0,!0],affectScale:[!1,!1,!1],offsetTranslation:[0,0,0],offsetRotation:[0,0,0],offsetScale:[1,1,1],aimVector:dt(d.get("AimVector"),[1,0,0]),upVector:dt(d.get("UpVector"),[0,1,0]),worldUpVector:dt(d.get("WorldUpVector"),[0,1,0]),worldUpType:ht(d.get("WorldUpType"),0),ikPoleVector:dt(d.get("PoleVector"),[0,0,0])};switch(c){case"aim":p.affectRotation=h("Affect",!0),p.offsetRotation=dt(d.get("RotationOffset"),[0,0,0]);break;case"parent":p.affectTranslation=h("AffectTranslation",!0),p.affectRotation=h("AffectRotation",!0),p.affectScale=h("AffectScale",!1);break;case"position":p.affectTranslation=h("Affect",!0),p.offsetTranslation=dt(d.get("Translation"),[0,0,0]);break;case"rotation":p.affectRotation=h("Affect",!0),p.offsetRotation=dt(d.get("Rotation"),[0,0,0]);break;case"scale":p.affectScale=h("Affect",!0),p.offsetScale=dt(d.get("Scaling"),[1,1,1])}const f="singleChainIK"===c?1:100;for(const t of n.connections){if(t.parentId!==e||"OP"!==t.type||!t.propertyName)continue;const o=n.objects.get(t.childId);if(!o||"Model"!==o.name)continue;const s=t.propertyName,r=re(null!==(a=oe(o,1))&&void 0!==a?a:"");switch(s){case"Constrained Object":case"Constrained object (Child)":p.nodeId=t.childId;break;case"Source":case"Source (Parent)":case"Aim At Object":case"Pole Vector Object":p.targets.push({modelId:t.childId,weight:ht(d.get(`${r}.Weight`),f)/f,offsetTranslation:dt(d.get(`${r}.Offset T`),[0,0,0]),offsetRotation:dt(d.get(`${r}.Offset R`),[0,0,0]),offsetScale:dt(d.get(`${r}.Offset S`),[1,1,1])});break;case"World Up Object":p.worldUpNodeId=t.childId;break;case"First Joint":p.ikFirstJointId=t.childId;break;case"End Joint":p.ikEndJointId=t.childId;break;case"Effector":p.ikEffectorId=t.childId}}return p}var ft,mt,gt;!function(e){e[e.DefaultW1=1]="DefaultW1",e[e.WidenToRgb=2]="WidenToRgb",e[e.MultiplyValue=4]="MultiplyValue"}(ft||(ft={})),function(e){e[e.None=0]="None",e[e.InvertX=1]="InvertX",e[e.UnknownShininess=2]="UnknownShininess"}(mt||(mt={})),function(e){e[e.Inverted=1]="Inverted",e[e.IfExists=2]="IfExists",e[e.IfTexture=4]="IfTexture",e[e.IfAround1=8]="IfAround1"}(gt||(gt={}));const _t=[["diffuseColor",1,0,"Diffuse"],["diffuseColor",1,0,"DiffuseColor"],["diffuseFactor",0,0,"DiffuseFactor"],["specularColor",1,0,"Specular"],["specularColor",1,0,"SpecularColor"],["specularFactor",0,0,"SpecularFactor"],["specularExponent",0,0,"Shininess"],["specularExponent",0,0,"ShininessExponent"],["reflectionColor",1,0,"Reflection"],["reflectionColor",1,0,"ReflectionColor"],["reflectionFactor",0,0,"ReflectionFactor"],["transparencyColor",1,0,"Transparent"],["transparencyColor",1,0,"TransparentColor"],["transparencyFactor",0,0,"TransparentFactor"],["transparencyFactor",0,0,"TransparencyFactor"],["emissionColor",1,0,"Emissive"],["emissionColor",1,0,"EmissiveColor"],["emissionFactor",0,0,"EmissiveFactor"],["ambientColor",1,0,"Ambient"],["ambientColor",1,0,"AmbientColor"],["ambientFactor",0,0,"AmbientFactor"],["normalMap",0,0,"NormalMap"],["bump",0,0,"Bump"],["bumpFactor",0,0,"BumpFactor"],["displacement",0,0,"Displacement"],["displacementFactor",0,0,"DisplacementFactor"],["vectorDisplacement",0,0,"VectorDisplacement"],["vectorDisplacementFactor",0,0,"VectorDisplacementFactor"]],vt=[["baseColor",1,0,"Diffuse"],["baseColor",1,0,"DiffuseColor"],["baseFactor",0,0,"DiffuseFactor"],["specularColor",1,0,"Specular"],["specularColor",1,0,"SpecularColor"],["specularFactor",0,0,"SpecularFactor"],["roughness",0,2,"Shininess"],["roughness",0,2,"ShininessExponent"],["transmissionColor",1,0,"Transparent"],["transmissionColor",1,0,"TransparentColor"],["transmissionFactor",0,0,"TransparentFactor"],["transmissionFactor",0,0,"TransparencyFactor"],["emissionColor",1,0,"Emissive"],["emissionColor",1,0,"EmissiveColor"],["emissionFactor",0,0,"EmissiveFactor"],["normalMap",0,0,"NormalMap"]],yt=[["roughnessAsGlossiness",8,"useGlossiness"]],bt=["pbr","metalness","diffuse","specular","coat","sheen","transmission","opacity","ior","diffuseRoughness"],xt={unknown:{maps:vt,features:[],defaultFeatures:["diffuse","specular","emission","transmission"]},fbxLambert:{maps:[["baseColor",1,0,"Diffuse"],["baseColor",1,0,"DiffuseColor"],["baseFactor",0,0,"DiffuseFactor"],["transmissionColor",1,0,"Transparent"],["transmissionColor",1,0,"TransparentColor"],["transmissionFactor",0,0,"TransparentFactor"],["transmissionFactor",0,0,"TransparencyFactor"],["emissionColor",1,0,"Emissive"],["emissionColor",1,0,"EmissiveColor"],["emissionFactor",0,0,"EmissiveFactor"],["normalMap",0,0,"NormalMap"]],features:[],defaultFeatures:["diffuse","emission","transmission"]},fbxPhong:{maps:vt,features:[],defaultFeatures:["diffuse","specular","emission","transmission"]},oslStandardSurface:{maps:[["baseFactor",0,0,"base"],["baseColor",1,0,"base_color"],["roughness",0,0,"specular_roughness"],["diffuseRoughness",0,0,"diffuse_roughness"],["metalness",0,0,"metalness"],["specularFactor",0,0,"specular"],["specularColor",1,0,"specular_color"],["specularIor",0,0,"specular_IOR"],["specularAnisotropy",0,0,"specular_anisotropy"],["specularRotation",0,0,"specular_rotation"],["transmissionFactor",0,0,"transmission"],["transmissionColor",1,0,"transmission_color"],["transmissionDepth",0,0,"transmission_depth"],["transmissionScatter",2,0,"transmission_scatter"],["transmissionScatterAnisotropy",0,0,"transmission_scatter_anisotropy"],["transmissionDispersion",0,0,"transmission_dispersion"],["transmissionExtraRoughness",0,0,"transmission_extra_roughness"],["subsurfaceFactor",0,0,"subsurface"],["subsurfaceColor",1,0,"subsurface_color"],["subsurfaceRadius",2,0,"subsurface_radius"],["subsurfaceScale",0,0,"subsurface_scale"],["subsurfaceAnisotropy",0,0,"subsurface_anisotropy"],["sheenFactor",0,0,"sheen"],["sheenColor",1,0,"sheen_color"],["sheenRoughness",0,0,"sheen_roughness"],["coatFactor",0,0,"coat"],["coatColor",1,0,"coat_color"],["coatRoughness",0,0,"coat_roughness"],["coatIor",0,0,"coat_IOR"],["coatAnisotropy",0,0,"coat_anisotropy"],["coatRotation",0,0,"coat_rotation"],["coatNormal",0,0,"coat_normal"],["coatAffectBaseColor",1,0,"coat_affect_color"],["coatAffectBaseRoughness",0,0,"coat_affect_roughness"],["thinFilmThickness",0,0,"thin_film_thickness"],["thinFilmIor",0,0,"thin_film_IOR"],["emissionFactor",0,0,"emission"],["emissionColor",1,0,"emission_color"],["opacity",2,0,"opacity"],["normalMap",0,0,"NormalMap"],["normalMap",0,0,"normalCamera"],["tangentMap",0,0,"tangent"]],features:[["thinWalled",0,"thin_walled"]],defaultFeatures:bt},arnoldStandardSurface:{maps:[["baseFactor",0,0,"base"],["baseColor",1,0,"baseColor"],["roughness",0,0,"specularRoughness"],["diffuseRoughness",0,0,"diffuseRoughness"],["metalness",0,0,"metalness"],["specularFactor",0,0,"specular"],["specularColor",1,0,"specularColor"],["specularIor",0,0,"specularIOR"],["specularAnisotropy",0,0,"specularAnisotropy"],["specularRotation",0,0,"specularRotation"],["transmissionFactor",0,0,"transmission"],["transmissionColor",1,0,"transmissionColor"],["transmissionDepth",0,0,"transmissionDepth"],["transmissionScatter",2,0,"transmissionScatter"],["transmissionScatterAnisotropy",0,0,"transmissionScatterAnisotropy"],["transmissionDispersion",0,0,"transmissionDispersion"],["transmissionExtraRoughness",0,0,"transmissionExtraRoughness"],["subsurfaceFactor",0,0,"subsurface"],["subsurfaceColor",1,0,"subsurfaceColor"],["subsurfaceRadius",2,0,"subsurfaceRadius"],["subsurfaceScale",0,0,"subsurfaceScale"],["subsurfaceAnisotropy",0,0,"subsurfaceAnisotropy"],["sheenFactor",0,0,"sheen"],["sheenColor",1,0,"sheenColor"],["sheenRoughness",0,0,"sheenRoughness"],["coatFactor",0,0,"coat"],["coatColor",1,0,"coatColor"],["coatRoughness",0,0,"coatRoughness"],["coatIor",0,0,"coatIOR"],["coatAnisotropy",0,0,"coatAnisotropy"],["coatRotation",0,0,"coatRotation"],["coatNormal",0,0,"coatNormal"],["thinFilmThickness",0,0,"thinFilmThickness"],["thinFilmIor",0,0,"thinFilmIOR"],["emissionFactor",0,0,"emission"],["emissionColor",1,0,"emissionColor"],["opacity",2,0,"opacity"],["indirectDiffuse",0,0,"indirectDiffuse"],["indirectSpecular",0,0,"indirectSpecular"],["normalMap",0,0,"NormalMap"],["normalMap",0,0,"normalCamera"],["tangentMap",0,0,"tangent"],["matteColor",1,0,"aiMatteColor"],["matteFactor",0,0,"aiMatteColorA"],["subsurfaceType",0,0,"subsurfaceType"],["transmissionPriority",0,0,"dielectricPriority"],["transmissionEnableInAov",0,0,"transmitAovs"]],features:[["matte",0,"aiEnableMatte"],["thinWalled",0,"thinWalled"],["caustics",0,"caustics"],["internalReflections",0,"internalReflections"],["exitToBackground",0,"exitToBackground"]],defaultFeatures:bt},"3dsMaxPhysicalMaterial":{maps:[["baseFactor",0,0,"base_weight"],["baseColor",1,0,"base_color"],["roughness",0,0,"roughness"],["diffuseRoughness",0,0,"diff_rough"],["diffuseRoughness",0,0,"diff_roughness"],["metalness",0,0,"metalness"],["specularFactor",0,0,"reflectivity"],["specularColor",1,0,"refl_color"],["specularAnisotropy",0,0,"anisotropy"],["specularRotation",0,0,"aniso_angle"],["specularRotation",0,0,"anisoangle"],["specularIor",0,0,"trans_ior"],["transmissionFactor",0,0,"transparency"],["transmissionColor",1,0,"trans_color"],["transmissionDepth",0,0,"trans_depth"],["transmissionRoughness",0,0,"trans_rough"],["transmissionRoughness",0,0,"trans_roughness"],["subsurfaceFactor",0,0,"scattering"],["subsurfaceTintColor",1,0,"sss_color"],["subsurfaceColor",1,0,"sss_scatter_color"],["subsurfaceRadius",2,0,"sss_depth"],["subsurfaceScale",0,0,"sss_scale"],["coatFactor",0,0,"coat"],["coatFactor",0,0,"coating"],["coatColor",1,0,"coat_color"],["coatRoughness",0,0,"coat_rough"],["coatRoughness",0,0,"coat_roughness"],["coatIor",0,0,"coat_ior"],["coatNormal",0,0,"coat_bump"],["coatNormal",0,0,"clearcoat_bump_map_amt"],["coatAffectBaseColor",1,0,"coat_affect_color"],["coatAffectBaseRoughness",0,0,"coat_affect_roughness"],["emissionFactor",0,0,"emission"],["emissionColor",1,0,"emit_color"],["opacity",2,0,"cutout"],["normalMap",0,0,"bump"],["normalMap",0,0,"bump_map_amt"],["displacementMap",0,0,"displacement"],["displacementMap",0,0,"displacement_map_amt"],["subsurfaceType",0,0,"subsurfaceType"]],features:[["thinWalled",0,"thin_walled"],["specular",0,"material_mode"],["diffuseRoughness",0,"material_mode"],["transmissionRoughness",1,"trans_roughness_lock"],["roughnessAsGlossiness",0,"roughness_inv"],["transmissionRoughnessAsGlossiness",0,"trans_roughness_inv"],["coatRoughnessAsGlossiness",0,"coat_roughness_inv"]],defaultFeatures:["pbr","metalness","diffuse","coat","sheen","transmission","opacity","ior"],textureSuffix:"_map",textureEnabledSuffix:"_map_on"},"3dsMaxPbrMetalRough":{maps:[["baseColor",1,0,"base_color"],["baseColor",1,0,"baseColor"],["roughness",0,0,"roughness"],["roughness",0,0,"Roughness_Map"],["metalness",0,0,"metalness"],["ambientOcclusion",0,0,"ao"],["normalMap",0,0,"norm"],["emissionColor",1,0,"emit_color"],["displacementMap",0,0,"displacement"],["displacementMap",0,0,"displacement_amt"],["opacity",2,0,"opacity"]],features:yt,defaultFeatures:["pbr","metalness","diffuse","opacity"],textureSuffix:"_map"},"3dsMaxPbrSpecGloss":{maps:[["baseColor",1,0,"base_color"],["baseColor",1,0,"baseColor"],["specularColor",1,0,"Specular"],["specularColor",1,0,"specular"],["roughness",0,0,"glossiness"],["ambientOcclusion",0,0,"ao"],["normalMap",0,0,"norm"],["emissionColor",1,0,"emit_color"],["displacementMap",0,0,"displacement"],["displacementMap",0,0,"displacement_amt"],["opacity",2,0,"opacity"]],features:yt,defaultFeatures:["pbr","specular","diffuse","opacity"],textureSuffix:"_map"},gltfMaterial:{maps:[["baseColor",1,0,"main|baseColor"],["roughness",0,0,"main|roughness"],["metalness",0,0,"main|metalness"],["normalMap",0,0,"main|normal"],["ambientOcclusion",0,0,"main|ambientOcclusion"],["emissionColor",1,0,"main|emission"],["emissionColor",1,0,"main|emissionColor"],["opacity",2,0,"main|Alpha"],["coatFactor",0,0,"extension|clearcoat"],["coatRoughness",0,0,"extension|clearcoatRoughness"],["coatNormal",0,0,"extension|clearcoatNormal"],["sheenColor",1,0,"extension|sheenColor"],["sheenRoughness",0,0,"extension|sheenRoughness"],["specularFactor",0,0,"extension|specular"],["specularFactor",0,0,"extension|Specular"],["specularColor",1,0,"extension|specularcolor"],["specularColor",1,0,"extension|specularColor"],["transmissionFactor",0,0,"extension|transmission"],["specularIor",0,0,"extension|indexOfRefraction"]],features:[["doubleSided",0,"main|DoubleSided"],["sheen",0,"extension|enableSheen"],["coat",0,"extension|enableClearCoat"],["transmission",0,"extension|enableTransmission"],["ior",0,"extension|enableIndexOfRefraction"],["specular",0,"extension|enableSpecular"],["unlit",0,"extension|unlit"]],defaultFeatures:["pbr","metalness","diffuse","emission","opacity","ambientOcclusion"],textureSuffix:"Map"},openPbrMaterial:{maps:[["baseFactor",0,0,"base_weight"],["baseColor",1,0,"base_color"],["roughness",0,0,"specular_roughness"],["diffuseRoughness",0,0,"base_diffuse_roughness"],["metalness",0,0,"base_metalness"],["specularFactor",0,0,"specular_weight"],["specularColor",1,0,"specular_color"],["specularAnisotropy",0,0,"specular_roughness_anisotropy"],["specularIor",0,0,"specular_ior"],["transmissionFactor",0,0,"transmission_weight"],["transmissionColor",1,0,"transmission_color"],["transmissionDepth",0,0,"transmission_depth"],["transmissionScatter",2,0,"transmission_scatter"],["transmissionScatterAnisotropy",0,0,"transmission_scatter_anisotropy"],["transmissionDispersion",0,0,"transmission_dispersion_scale"],["subsurfaceFactor",0,0,"subsurface_weight"],["subsurfaceColor",1,0,"subsurface_color"],["subsurfaceRadius",2,0,"subsurface_radius_scale"],["subsurfaceScale",0,0,"subsurface_radius"],["subsurfaceAnisotropy",0,0,"subsurface_scatter_anisotropy"],["coatFactor",0,0,"coat_weight"],["coatColor",1,0,"coat_color"],["coatRoughness",0,0,"coat_roughness"],["coatAnisotropy",0,0,"coat_roughness_anisotropy"],["coatIor",0,0,"coat_ior"],["coatNormal",0,0,"coat_normal_map"],["sheenFactor",0,0,"fuzz_weight"],["sheenColor",1,0,"fuzz_color"],["sheenRoughness",0,0,"fuzz_roughness"],["emissionFactor",0,0,"emission_weight"],["emissionFactor",4,0,"emission_luminance"],["emissionColor",1,0,"emission_color"],["thinFilmFactor",0,0,"thin_film_weight"],["thinFilmThickness",0,0,"thin_film_thickness"],["thinFilmIor",0,0,"thin_film_ior"],["normalMap",0,0,"bump"],["normalMap",0,0,"bump_map_amt"],["displacementMap",0,0,"displacement"],["displacementMap",0,0,"displacement_map_amt"],["coatNormal",0,0,"coat_bump"],["coatNormal",0,0,"coat_bump_map_amt"],["tangentMap",0,0,"geometry_tangent_map"],["opacity",2,0,"geometry_opacity"]],features:[["thinWalled",0,"geometry_thin_walled"]],defaultFeatures:bt,textureSuffix:"_map",textureEnabledSuffix:"_map_on"},shaderFxGraph:{maps:[["baseColor",1,0,"color"],["baseColor",1,0,"base_color"],["roughness",0,0,"roughness"],["metalness",0,0,"metallic"],["normalMap",0,0,"normal"],["emissionFactor",0,0,"emissive_intensity"],["emissionColor",1,0,"emissive"],["ambientOcclusion",0,0,"ao"]],features:[],defaultFeatures:["pbr","metalness","diffuse","emission","ambientOcclusion"],texturePrefix:"TEX_",textureSuffix:"_map",textureEnabledPrefix:"use_",textureEnabledSuffix:"_map"}};function Tt(e){return"unknown"!==e&&"fbxLambert"!==e&&"fbxPhong"!==e}function At(e,t){switch(e){case 1:t[0]=1-t[0];break;case 2:t[0]>=0&&(t[0]=1-.1*Math.sqrt(t[0]),t[0]<0&&(t[0]=0))}}function wt(e){const t=[];for(const n of e)if("number"==typeof n)t.push(n);else{if("boolean"!=typeof n)break;t.push(n?1:0)}return t}function Mt(e){var t,n,o,s,r,i,a,l,u,c;const{shaderType:d,shaderPropPrefix:h}=function(e){var t,n,o,s,r,i;let a="unknown";const l=e.shadingModelName.toLowerCase();if("lambert"===l?a="fbxLambert":"phong"===l&&(a="fbxPhong"),e.shader)switch(e.shader.renderApi){case"ARNOLD_SHADER_ID":return{shaderType:"arnoldStandardSurface",shaderPropPrefix:""};case"OSL":return{shaderType:"oslStandardSurface",shaderPropPrefix:""};case"SFX_PBS_SHADER":return{shaderType:"shaderFxGraph",shaderPropPrefix:""};default:return{shaderType:"unknown",shaderPropPrefix:""}}if("unknown"===a){const a=(null!==(o=wt(null!==(n=null===(t=e.props.get("3dsMax|ClassIDa"))||void 0===t?void 0:t.values)&&void 0!==n?n:[])[0])&&void 0!==o?o:0)>>>0,l=(null!==(i=wt(null!==(r=null===(s=e.props.get("3dsMax|ClassIDb"))||void 0===s?void 0:s.values)&&void 0!==r?r:[])[0])&&void 0!==i?i:0)>>>0;if(1030429932===a&&3735928833===l)return{shaderType:"3dsMaxPhysicalMaterial",shaderPropPrefix:"3dsMax|Parameters|"};if(4048887347===a&&939201335===l)return{shaderType:"openPbrMaterial",shaderPropPrefix:"3dsMax|Parameters|"};if(943849874===a&&1174294043===l)return{shaderType:"gltfMaterial",shaderPropPrefix:"3dsMax|"};if(3490651648===a&&3195528448===l)return{shaderType:"3dsMaxPbrMetalRough",shaderPropPrefix:"3dsMax|main|"};if(3490651648===a&&31173939===l)return{shaderType:"3dsMaxPbrSpecGloss",shaderPropPrefix:"3dsMax|main|"}}return{shaderType:a,shaderPropPrefix:""}}(e),p=xt[d],f={shaderType:d,shaderPropPrefix:h,fbx:{},pbr:{},features:{}};for(const e of p.defaultFeatures)f.features[e]={enabled:!0,explicit:!1};const m=t=>{var n;const o=null===(n=e.shader)||void 0===n?void 0:n.bindings.get(t);return o&&o.length>0?o:[t]},g=e.shader?"":h,_=(t,n,o,s,r,i,a)=>{var l,u,c,d,h;for(const[p,f,_,v]of t){const t=g+o+v+s;for(const o of m(t)){const t=e.props.get(o),s=null!==(l=n[p])&&void 0!==l?l:n[p]={valueComponents:0,textureEnabled:!1};if(r&&t&&"Reference"!==t.type){const e=wt(t.values);if(e.length>0){const t=e.slice(0,4);4&f?(t[0]*=null!==(c=null===(u=s.value)||void 0===u?void 0:u[0])&&void 0!==c?c:1,s.value=[t[0],...null!==(h=null===(d=s.value)||void 0===d?void 0:d.slice(1))&&void 0!==h?h:[]]):s.value=t,At(_,s.value);const n=e.length>=4?4:3===e.length?3:2===e.length?2:1;1&f&&n<4&&(s.value[3]=1),2&f&&1===n&&(s.value[1]=s.value[0],s.value[2]=s.value[0]),s.valueComponents=n}}if(i){const t=e.texturesByProp.get(o);t&&(s.texture=t,s.textureEnabled=!0)}if(a&&t){const e=wt(t.values);e.length>0&&(s.textureEnabled=0!==e[0])}}}};_(_t,f.fbx,"","",!0,!0,!1),(p.texturePrefix||p.textureSuffix)&&_(p.maps,f.pbr,null!==(t=p.texturePrefix)&&void 0!==t?t:"",null!==(n=p.textureSuffix)&&void 0!==n?n:"",!1,!0,!1),_(p.maps,f.pbr,"","",!0,!0,!1),(p.textureEnabledPrefix||p.textureEnabledSuffix)&&_(p.maps,f.pbr,null!==(o=p.textureEnabledPrefix)&&void 0!==o?o:"",null!==(s=p.textureEnabledSuffix)&&void 0!==s?s:"",!1,!1,!0);for(const[t,n,o]of p.features){const s=g+o;for(const o of m(s)){const s=e.props.get(o),i=null!==(r=(c=f.features)[t])&&void 0!==r?r:c[t]={enabled:!1,explicit:!1};if(s&&"Reference"!==s.type){const e=wt(s.values);e.length>0&&(i.enabled=0!==e[0],i.explicit=!0,8&n&&(i.enabled=e[0]>=.5&&e[0]<=1.5),1&n&&(i.enabled=!i.enabled),2&n&&(i.enabled=!0))}4&n&&e.texturesByProp.has(o)&&(i.enabled=!0)}}const v=(e,t,n)=>{var o;const s=null!==(o=e[t])&&void 0!==o?o:e[t]={valueComponents:0,textureEnabled:!1};if(s.value)return;const r=e[n],i=(null==r?void 0:r.value)&&r.value.some(e=>0!==e);s.value=[i?1:0],s.valueComponents=1};v(f.fbx,"diffuseFactor","diffuseColor"),v(f.fbx,"specularFactor","specularColor"),v(f.fbx,"reflectionFactor","reflectionColor"),v(f.fbx,"transparencyFactor","transparencyColor"),v(f.fbx,"emissionFactor","emissionColor"),v(f.fbx,"ambientFactor","ambientColor"),v(f.pbr,"baseFactor","baseColor"),v(f.pbr,"specularFactor","specularColor"),v(f.pbr,"emissionFactor","emissionColor"),v(f.pbr,"sheenFactor","sheenColor"),v(f.pbr,"thinFilmFactor","thinFilmThickness"),v(f.pbr,"transmissionFactor","transmissionColor"),!(null===(i=f.pbr.transmissionRoughness)||void 0===i?void 0:i.value)&&(null===(a=f.pbr.roughness)||void 0===a?void 0:a.value)&&(null===(l=f.pbr.transmissionExtraRoughness)||void 0===l?void 0:l.value)&&(f.pbr.transmissionRoughness={value:[f.pbr.roughness.value[0]+f.pbr.transmissionExtraRoughness.value[0]],valueComponents:1,textureEnabled:!1});const y=[["roughnessAsGlossiness","roughness","glossiness"],["coatRoughnessAsGlossiness","coatRoughness","coatGlossiness"],["transmissionRoughnessAsGlossiness","transmissionRoughness","transmissionGlossiness"]];for(const[e,t,n]of y){const o=f.pbr[t];(null===(u=f.features[e])||void 0===u?void 0:u.enabled)?o&&(f.pbr[n]=o,f.pbr[t]=o.value?{value:[1-o.value[0]],valueComponents:1,textureEnabled:!1}:{valueComponents:0,textureEnabled:!1}):(null==o?void 0:o.value)&&(f.pbr[n]={value:[1-o.value[0]],valueComponents:1,textureEnabled:!1})}return f}function St(e){var t,n;if(!(null==e?void 0:e.value))return;const o=e.value;return 1===e.valueComponents?[o[0],o[0],o[0]]:[o[0],null!==(t=o[1])&&void 0!==t?t:o[0],null!==(n=o[2])&&void 0!==n?n:o[0]]}function Rt(e){return(null==e?void 0:e.value)?e.value[0]:void 0}function Ct(e,t,n,o){var s,r,i,a,l;const u=re(null!==(s=oe(e,1))&&void 0!==s?s:"Material"),c=function(e,t){var n,o;if(!t)return;const s=te(e,"ShadingModel"),r=s?oe(s,0):void 0;return"phong"===(null==r?void 0:r.toLowerCase())?null!==(n=ie(t,"Material","FbxSurfacePhong"))&&void 0!==n?n:ie(t,"Material"):"lambert"===(null==r?void 0:r.toLowerCase())&&null!==(o=ie(t,"Material","FbxSurfaceLambert"))&&void 0!==o?o:ie(t,"Material")}(e,o),d=te(e,"ShadingModel"),h=d?null!==(r=oe(d,0))&&void 0!==r?r:"Lambert":null!==(i=ae(e,c,"ShadingModel"))&&void 0!==i?i:"Lambert",p="phong"===h.toLowerCase()?"Phong":"Lambert",f=function(e,t){var n,o,s,r,i;const a={};return a.diffuseColor=null!==(n=Ft(e,t,"DiffuseColor"))&&void 0!==n?n:Ft(e,t,"Diffuse"),a.diffuseFactor=Et(e,t,"DiffuseFactor"),a.ambientColor=null!==(o=Ft(e,t,"AmbientColor"))&&void 0!==o?o:Ft(e,t,"Ambient"),a.ambientFactor=Et(e,t,"AmbientFactor"),a.specularColor=null!==(s=Ft(e,t,"SpecularColor"))&&void 0!==s?s:Ft(e,t,"Specular"),a.specularFactor=Et(e,t,"SpecularFactor"),a.shininess=null!==(r=Et(e,t,"Shininess"))&&void 0!==r?r:Et(e,t,"ShininessExponent"),a.emissiveColor=null!==(i=Ft(e,t,"EmissiveColor"))&&void 0!==i?i:Ft(e,t,"Emissive"),a.emissiveFactor=Et(e,t,"EmissiveFactor"),a.opacity=Et(e,t,"Opacity"),a.transparencyFactor=Et(e,t,"TransparencyFactor"),a}(e,c),m=function(e,t,n){const o=[],s=ye(t,e,"Texture");for(const{id:e,node:r,propertyName:i}of s)o.push(Ot(e,r,i,t,n));for(const{id:s,propertyName:r}of ye(t,e,"LayeredTexture")){const e=ye(t,s,"Texture");if(0===e.length)continue;const i=Ot(e[0].id,e[0].node,r,t,n);i.layeredTextureId=s,o.push(i)}return o}(t,n,o?null!==(a=ie(o,"Texture","FbxFileTexture"))&&void 0!==a?a:ie(o,"Texture"):void 0),g=new Map;for(const e of null!==(l=null==c?void 0:c.properties.values())&&void 0!==l?l:[])g.set(e.name,{type:e.propertyType,values:e.values});for(const t of pe(e))g.set(t.name,{type:t.type,values:t.values});const _=new Map;for(const e of m)_.has(e.propertyName)||_.set(e.propertyName,e);return{id:t,name:u,type:p,properties:f,textures:m,model:Mt({shadingModelName:h,props:g,texturesByProp:_,shader:It(t,n)}),userProperties:fe(e)}}function It(e,t){var n;const o=t.connections.filter(n=>{var o;return"OO"===n.type&&n.childId===e&&"Implementation"===(null===(o=t.objects.get(n.parentId))||void 0===o?void 0:o.name)}).map(e=>({id:e.parentId,node:t.objects.get(e.parentId)}));if(0===o.length)return;const s=o[0],r=null===(n=pe(s.node).find(e=>"RenderAPI"===e.name))||void 0===n?void 0:n.values[0],i=new Map,a=(e,t)=>{const n=i.get(e);n?n.push(t):i.set(e,[t])};for(const e of ye(t,s.id,"BindingTable"))for(const t of e.node.children){if("Entry"!==t.name)continue;const e=oe(t,0),n=oe(t,1),o=oe(t,2),s=oe(t,3);"string"==typeof e&&"string"==typeof o&&("FbxPropertyEntry"===n&&"FbxSemanticEntry"===s?a(o,e):"FbxSemanticEntry"===n&&"FbxPropertyEntry"===s&&a(e,o))}return{renderApi:"string"==typeof r?r:"",bindings:i}}function Ot(e,t,n,o,s){var r,i,a,l,u;{const c=te(t,"FileName"),d=te(t,"RelativeFilename"),h=c&&null!==(r=oe(c,0))&&void 0!==r?r:"",p=d&&null!==(i=oe(d,0))&&void 0!==i?i:"";let f,m;const g=null!==(a=Et(t,s,"UVRotation"))&&void 0!==a?a:Et(t,s,"Rotation");let _;f=null!==(l=Nt(t,s,"UVTranslation"))&&void 0!==l?l:Nt(t,s,"Translation"),m=null!==(u=Nt(t,s,"UVScaling"))&&void 0!==u?u:Nt(t,s,"Scaling");const v=ae(t,s,"UVSet");v&&v.length>0&&(_=v),null!=f||(f=kt(t,"ModelUVTranslation")),null!=m||(m=kt(t,"ModelUVScaling"));const y=Et(t,s,"WrapModeU"),b=Et(t,s,"WrapModeV");let x=null;const T=ye(o,e,"Video");for(const{node:e}of T){const t=te(e,"Content");if(t&&t.properties.length>0){const e=t.properties[0].value;e instanceof Uint8Array&&e.length>0?x=e:e instanceof ArrayBuffer&&e.byteLength>0&&(x=new Uint8Array(e))}}return{propertyName:null!=n?n:"DiffuseColor",fileName:h,relativeFileName:p,id:e,embeddedData:x,uvTranslation:f,uvScaling:m,uvRotation:g,uvSetName:_,wrapU:y,wrapV:b}}}function Ft(e,t,n){const o=ce(e,t,n);if(!o||o.length<3)return;const s=Lt(o[0]),r=Lt(o[1]),i=Lt(o[2]);return void 0!==s&&void 0!==r&&void 0!==i?[s,r,i]:void 0}function Et(e,t,n){return Lt(ae(e,t,n))}function Nt(e,t,n){const o=ce(e,t,n);if(!o)return;const s=Lt(o[0]),r=Lt(o[1]);return void 0!==s&&void 0!==r?[s,r]:void 0}function Lt(e){if("number"==typeof e)return e}function kt(e,t){var n,o;const s=te(e,t);if(!s)return;const r=Lt(null===(n=s.properties[0])||void 0===n?void 0:n.value),i=Lt(null===(o=s.properties[1])||void 0===o?void 0:o.value);return void 0!==r&&void 0!==i?[r,i]:void 0}let Pt;function Bt(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=ye(n,e,"Deformer");if(0===c.length)return null;const d=new Map;for(const{id:e,node:t}of c){if("Cluster"!==oe(t,2))continue;const o=ye(n,e,"Model");o.length>0&&d.set(o[0].id,{clusterId:e,clusterNode:t})}const h=function(e,t){var n;const o=t.parentOf.get(e),s=o?t.objects.get(o.id):void 0,r="Model"===(null==s?void 0:s.name)?o.id:void 0;if(void 0===r)return new Map;for(const[,e]of Array.from(t.objects)){if("Pose"!==e.name||"BindPose"!==oe(e,2))continue;const t=new Map;for(const o of e.children){if("PoseNode"!==o.name)continue;const e=te(o,"Node"),s=te(o,"Matrix"),r=null===(n=null==e?void 0:e.properties[0])||void 0===n?void 0:n.value,i=se(s);if("number"!=typeof r)continue;const a=Kt(i);16===(null==a?void 0:a.length)&&t.set(r,a)}if(t.has(r))return t}return new Map}(r,n),p=[],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=Dt(o,t);for(;void 0!==e;){const o=t.objects.get(e);if(!o||"Model"!==o.name)break;n.add(e),e=Dt(e,t)}}return n}(e,n),h=function(e,t){const n=new Map;for(const o of Array.from(e)){let s=Dt(o,t);for(;void 0!==s;){if(e.has(s)){n.set(o,s);break}s=Dt(s,t)}}return n}(d,n),p=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 m=n.objects.get(d);if(!m)continue;const g=u.length,_=e.get(d),v=Gt(m),{bindPoseMatrix:y,transformLinkMatrix:b,transformAssociateModelMatrix:x,clusterMode:T}=_?$t(_.clusterNode):{bindPoseMatrix:null,transformLinkMatrix:null,transformAssociateModelMatrix:null,clusterMode:"Unknown"},A=Ut(d,re(null!==(s=oe(m,1))&&void 0!==s?s:`Bone${g}`),void 0!==_,T,y,b,x,null!==(r=t.get(d))&&void 0!==r?r:null);o.push(...A),u.push({modelId:d,name:re(null!==(i=oe(m,1))&&void 0!==i?i:`Bone${g}`),index:g,parentIndex:h,isCluster:void 0!==_,translation:v.translation,rotation:v.rotation,preRotation:v.preRotation,postRotation:v.postRotation,rotationPivot:v.rotationPivot,scalingPivot:v.scalingPivot,rotationOffset:v.rotationOffset,scalingOffset:v.scalingOffset,scale:v.scale,rotationOrder:v.rotationOrder,inheritType:v.inheritType,clusterMode:T,bindPoseMatrix:y,transformLinkMatrix:b,transformAssociateModelMatrix:x,modelBindPoseMatrix:null!==(a=t.get(d))&&void 0!==a?a:null,diagnostics:A});for(const e of null!==(l=p.get(d))&&void 0!==l?l:[])c.has(e)||f.push({modelId:e,parentIndex:g})}return u}(d,h,n,p);if(0===f.length)return null;const{boneIndices:m,boneWeights:g}=function(e,t){let n=0;for(const o of e){const e=t.get(o.modelId);if(!e)continue;const s=te(e.clusterNode,"Indexes");if(!s)continue;const r=Ht(se(s));if(r)for(let e=0;e<r.length;e++)r[e]>n&&(n=r[e])}const o=n+1,s=new Array(o),r=new Array(o);for(let e=0;e<o;e++)s[e]=[],r[e]=[];for(const n of e){const e=t.get(n.modelId);if(!e)continue;const o=te(e.clusterNode,"Indexes"),i=te(e.clusterNode,"Weights");if(!o||!i)continue;const a=Ht(se(o)),l=Kt(se(i));if(a&&l)for(let e=0;e<a.length;e++){const t=a[e];s[t].push(n.index),r[t].push(l[e])}}for(let e=0;e<o;e++){if(0===s[e].length)continue;const t=s[e].map((t,n)=>({index:t,weight:r[e][n]}));t.sort((e,t)=>t.weight-e.weight);const n=t.slice(0,8);s[e]=n.map(e=>e.index),r[e]=n.map(e=>e.weight)}for(let e=0;e<o;e++){const t=r[e].reduce((e,t)=>e+t,0);if(t>0)for(let n=0;n<r[e].length;n++)r[e][n]/=t}return{boneIndices:s,boneWeights:r}}(f,d);return{id:e,geometryId:r,meshBindPoseMatrix:void 0!==u&&null!==(o=h.get(u))&&void 0!==o?o:null,bones:f,boneIndices:m,boneWeights:g,diagnostics:p}}function Dt(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 Vt(e){const t=oe(e,2);return"Root"===t||"LimbNode"===t}function Gt(e,t){return ve(e,null!=t?t:Pt)}function $t(e){let t=null,n=null,o=null,s="Normalize";const r=te(e,"Transform");if(r&&r.properties[0]){const e=se(r);e instanceof Float64Array&&16===e.length?t=e:e instanceof Float32Array&&16===e.length&&(t=new Float64Array(e))}const i=te(e,"TransformLink");if(i&&i.properties[0]){const e=se(i);e instanceof Float64Array&&16===e.length?n=e:e instanceof Float32Array&&16===e.length&&(n=new Float64Array(e))}const a=te(e,"TransformAssociateModel");if(a&&a.properties[0]){const e=se(a);e instanceof Float64Array&&16===e.length?o=e:e instanceof Float32Array&&16===e.length&&(o=new Float64Array(e))}const l=te(e,"Mode"),u=l?oe(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 Ut(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 Ht(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 Kt(e){return e instanceof Float64Array?e:e instanceof Float32Array?new Float64Array(e):null}function jt(e,t){var n;const o=null!==(n=function(e,t){if(0===e.length)return;const n=e.map(e=>Wt(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=qt(s,t);for(;void 0!==r;){const e=t.objects.get(r);if(!e||"Model"!==e.name||!Vt(e))break;s=r,r=qt(r,t)}return s}function Wt(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=qt(o,t)}return n}function qt(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 zt(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 Xt(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 Yt(e,t){var n;const o=t.objects.get(e);if(!o||"Model"!==o.name)return null;const s=Gt(o);return{modelId:e,name:re(null!==(n=oe(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 Qt(e,t){return e<t?-1:e>t?1:0}function Zt(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)||Qt(e,t)}const Jt=46186158e3,en=.333333,tn=1e-5,nn=new Float32Array(1),on=new Uint32Array(nn.buffer);function sn(e){return nn[0]=e,on[0]}function rn(e,t,n,o,s,r){const i=r?1:.5;return{left:i*(1-e)*(1+n)*(1-t)*o+i*(1-e)*(1-n)*(1+t)*s,right:i*(1-e)*(1+n)*(1+t)*o+i*(1-e)*(1-n)*(1-t)*s}}function an(e,t,n,o,s,r,i,a,l,u){if(4096&u&&Math.min(Math.abs(o-s),Math.abs(r-s))<=tn)return 0;let c=(r-o)/(n-e);if(!(8192&u)){const i=(s-o)/(t-e),a=(r-s)/(n-t),u=(t-e)/(n-e);c=.5*c+.5*(i*(1-u)+a*u);const d=Math.abs(l)/100;if(d>1e-4){const e=l>0?a:i,t=e-c;c=c*(1-d)+e*d;const n=d-5;if(n>0){let e=Math.abs(t)>1e-5?t:l;e=e>0?1:-1,c+=n*n*e*40}}}if(16384&u){const l=c>=0?1:-1;let u=l*c;const d=i*(t-e),h=a*(n-t);let p=d>0?l*(s-o)/d:0,f=h>0?l*(r-s)/h:0;p>0||(p=0),f>0||(f=0),u=Math.min(u,p,f),c=l*u}return c}function ln(e,t,n,o,s,r){if(16384&r)return 0;if(4096&r&&Math.abs(o-n)<=tn)return 0;let i=(o-n)/(t-e);if(!(8192&r)){const e=Math.abs(s)/100-5;e>0&&(i+=e*e*(s>0?1:-1)*40)}return i}function un(e,t,n){const o=3*e,s=3*t,r=o-s+1,i=s-o-o,a=o,l=3*r,u=2*i;let c,d=n;for(let e=0;e<11;e++){const t=d*d;c=r*(t*d)+i*t+a*d-n;const o=l*t+u*d+a;if(0===o)break;if(d-=c/o,e>=2&&Math.abs(c)<=8881784197001252e-31)break}return d}function cn(e,t){var n,o;const s=t.time-e.time;if(Number.isFinite(e.rightDx)&&Number.isFinite(e.rightDy)&&Number.isFinite(t.leftDx)&&Number.isFinite(t.leftDy)&&(e.rightDx>0||t.leftDx>0))return{rightDx:e.rightDx,rightDy:e.rightDy,leftDx:t.leftDx,leftDy:t.leftDy};const r=null!==(n=e.rightSlope)&&void 0!==n?n:0;return{rightDx:s/3,rightDy:s/3*r,leftDx:s/3,leftDy:s/3*(null!==(o=e.nextLeftSlope)&&void 0!==o?o:t.leftDx>0?t.leftDy/t.leftDx:r)}}function dn(e,t,n,o=!1){if(!e||0===e.keys.length)return n;const s=e.keys;if(1===s.length)return s[0].value;const r=s[0].time,i=s[s.length-1].time;if(!o&&(t<r||t>i))return function(e,t){var n;const o=e.keys,s=o[0].time,r=o[o.length-1].time,i=t<s,a=i?o[0]:o[o.length-1],l=null!==(n=i?e.preExtrapolation:e.postExtrapolation)&&void 0!==n?n:{mode:"constant",repeatCount:-1};if("constant"===l.mode)return a.value;if("slope"===l.mode){const e=i?a.rightDx:a.leftDx,n=i?a.rightDy:a.leftDy;return 0!==e?a.value+n*((t-a.time)/e):a.value}if(0===l.repeatCount)return a.value;const u=Jt,c=Math.round(s*u),d=Math.round(r*u),h=t*u,p=i?c-h:h-d,f=d-c;if(!(f>=1))return a.value;const m=p/f;let g=Math.floor(m),_=p-g*f;l.repeatCount>0&&g>=l.repeatCount&&(g=l.repeatCount-1,_=f),"mirror"===l.mode&&.5*g-Math.floor(.5*g)<=.25&&(_=f-_),i&&(_=f-_);let v=dn(e,(c+_)/u,a.value,!0);if("repeatRelative"===l.mode){let e=o[o.length-1].value-o[0].value;i&&(e=-e),v+=e*(g+1)}return v}(e,t);let a=0,l=s.length;for(;l-a>=8;){const e=a+l>>1;s[e].time<=t?a=e+1:l=e}for(l=s.length;a<l;a++){const e=s[a];if(e.time<=t)continue;if(0===a)return e.value;const n=s[a-1];if(n.time===t)return n.value;const o=1/(e.time-n.time);let r=(t-n.time)*o;switch(n.interpolation){case"constant":return"next"===n.constantMode?e.value:n.value;case"linear":return n.value*(1-r)+e.value*r;default:{const t=cn(n,e);r=un(t.rightDx*o,1-t.leftDx*o,r);const s=r*r,i=s*r,a=1-r,l=a*a,u=l*a,c=n.value,d=e.value;return u*c+3*(l*r*(c+t.rightDy)+a*s*(d-t.leftDy))+i*d}}}return s[s.length-1].value}const hn=Math.PI/180,pn=180/Math.PI;function fn(e,t){const n=e[0]*(.5*hn),o=e[1]*(.5*hn),s=e[2]*(.5*hn),r=Math.cos(n),i=Math.sin(n),a=Math.cos(o),l=Math.sin(o),u=Math.cos(s),c=Math.sin(s);switch(t){case 1:return[r*l*c+a*u*i,r*u*l+a*i*c,r*a*c-u*i*l,r*a*u-i*l*c];case 2:return[-r*l*c+a*u*i,r*u*l-a*i*c,r*a*c+u*i*l,r*a*u+i*l*c];case 3:return[-r*l*c+a*u*i,r*u*l+a*i*c,r*a*c+u*i*l,r*a*u-i*l*c];case 4:return[r*l*c+a*u*i,r*u*l-a*i*c,r*a*c-u*i*l,r*a*u+i*l*c];case 5:return[r*l*c+a*u*i,r*u*l-a*i*c,r*a*c+u*i*l,r*a*u-i*l*c];default:return[-r*l*c+a*u*i,r*u*l+a*i*c,r*a*c-u*i*l,r*a*u+i*l*c]}}function mn(e,t){const n=.999999999,[o,s,r,i]=e;let a,l=0,u=0,c=0;const d=.5*Math.PI;switch(t){case 1:a=2*(i*r+o*s),Math.abs(a)<n?(c=Math.asin(a),u=Math.atan2(2*(i*s-o*r),2*(i*i+o*o)-1),l=-Math.atan2(-2*(i*o-s*r),2*(i*i+s*s)-1)):(c=Math.sign(a)*d,u=Math.atan2(2*a*(i*o+s*r),-a*(2*o*s-2*i*r)));break;case 2:a=2*(i*r-o*s),Math.abs(a)<n?(c=Math.asin(a),l=Math.atan2(2*(i*o+s*r),2*(i*i+s*s)-1),u=-Math.atan2(-2*(i*s+o*r),2*(i*i+o*o)-1)):(c=Math.sign(a)*d,l=Math.atan2(-2*a*(i*s-o*r),a*(2*i*r+2*o*s)));break;case 3:a=2*(i*o+s*r),Math.abs(a)<n?(l=Math.asin(a),c=Math.atan2(2*(i*r-o*s),2*(i*i+s*s)-1),u=-Math.atan2(-2*(i*s-o*r),2*(i*i+r*r)-1)):(l=Math.sign(a)*d,c=Math.atan2(2*a*(i*s+o*r),-a*(2*s*r-2*i*o)));break;case 4:a=2*(i*o-s*r),Math.abs(a)<n?(l=Math.asin(a),u=Math.atan2(2*(i*s+o*r),2*(i*i+r*r)-1),c=-Math.atan2(-2*(i*r+o*s),2*(i*i+s*s)-1)):(l=Math.sign(a)*d,u=Math.atan2(-2*a*(i*r-o*s),a*(2*i*o+2*s*r)));break;case 5:a=2*(i*s+o*r),Math.abs(a)<n?(u=Math.asin(a),l=Math.atan2(2*(i*o-s*r),2*(i*i+r*r)-1),c=-Math.atan2(-2*(i*r-o*s),2*(i*i+o*o)-1)):(u=Math.sign(a)*d,l=Math.atan2(2*a*(i*r+o*s),-a*(2*o*r-2*i*s)));break;default:a=2*(i*s-o*r),Math.abs(a)<n?(u=Math.asin(a),c=Math.atan2(2*(i*r+o*s),2*(i*i+o*o)-1),l=-Math.atan2(-2*(i*o+s*r),2*(i*i+r*r)-1)):(u=Math.sign(a)*d,c=Math.atan2(-2*a*(i*o-s*r),a*(2*i*s+2*o*r)))}return[l*pn,u*pn,c*pn]}function gn(e,t,n){let o,s,r=e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],i=t[0],a=t[1],l=t[2],u=t[3];if(r<0&&(r=-r,i=-i,a=-a,l=-l,u=-u),r>.9995)o=1-n,s=n;else{const e=Math.acos(Math.min(1,r)),t=1/Math.sin(e);o=Math.sin((1-n)*e)*t,s=Math.sin(n*e)*t}const c=e[0]*o+i*s,d=e[1]*o+a*s,h=e[2]*o+l*s,p=e[3]*o+u*s,f=Math.hypot(c,d,h,p)||1;return[c/f,d/f,h/f,p/f]}function _n(e,t){return e>=0?Math.pow(e,t):-Math.pow(-e,t)}function vn(e,t,n,o,s){const r=n.weight;if(n.additive)return n.composeScale&&"S"===o?[e[0]*_n(t[0],r),e[1]*_n(t[1],r),e[2]*_n(t[2],r)]:n.composeRotation&&"R"===o?mn((i=fn(e,s),a=gn([0,0,0,1],fn(t,s),r),[i[3]*a[0]+i[0]*a[3]+i[1]*a[2]-i[2]*a[1],i[3]*a[1]-i[0]*a[2]+i[1]*a[3]+i[2]*a[0],i[3]*a[2]+i[0]*a[1]-i[1]*a[0]+i[2]*a[3],i[3]*a[3]-i[0]*a[0]-i[1]*a[1]-i[2]*a[2]]),s):[e[0]+t[0]*r,e[1]+t[1]*r,e[2]+t[2]*r];var i,a;if(n.blended){const i=1-r;return n.composeScale&&"S"===o?[_n(e[0],i)*_n(t[0],r),_n(e[1],i)*_n(t[1],r),_n(e[2],i)*_n(t[2],r)]:n.composeRotation&&"R"===o?mn(gn(fn(e,s),fn(t,s),r),s):[e[0]*i+t[0]*r,e[1]*i+t[1]*r,e[2]*i+t[2]*r]}return[t[0],t[1],t[2]]}function yn(e,t,n,o){var s,r;const i=re(null!==(s=oe(t,1))&&void 0!==s?s:"Animation"),a=function(e){var t,n,o,s;const r=te(e,"Properties70");if(!r)return null;let i=0,a=null;for(const e of r.children){if("P"!==e.name)continue;const r=oe(e,0);"LocalStart"===r||"ReferenceStart"===r?i=null!==(n=Fn(null===(t=e.properties[4])||void 0===t?void 0:t.value))&&void 0!==n?n:i:"LocalStop"!==r&&"ReferenceStop"!==r||(a=null!==(s=Fn(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),l=ye(n,e,"AnimationLayer");if(0===l.length)return null;const u=[],c=[],d=[],h=[];let p=1/0,f=-1/0;for(const{id:e,node:t}of l){const o=re(null!==(r=oe(t,1))&&void 0!==r?r:"Layer");let s=100,i=0,a=0,l=0;for(const e of pe(t)){const t=e.values[0];"number"==typeof t&&("Weight"===e.name?s=t:"BlendMode"===e.name?i=t:"RotationAccumulationMode"===e.name?a=t:"ScaleAccumulationMode"===e.name&&(l=t))}const m=d.length,g=ye(n,e,"AnimationCurveNode"),_=[],v=[],y=[];let b;for(const{id:t,node:s}of g){const r=xn(t,s,n,m);if(!r){const r=Tn(t,s,n,m);if(r){if(r.targetId===e&&"Weight"===r.propertyName&&r.curves.length>0){b=r.curves[0];continue}An(r.curves,e=>{e<p&&(p=e),e>f&&(f=e)}),v.push(r),c.push(r);const n={type:"unsupported-curve-node",message:`AnimationCurveNode '${r.type}' is preserved as diagnostic data but not evaluated at runtime.`,layerName:o,curveNodeId:t,curveNodeType:r.type,targetId:r.targetId,propertyName:r.propertyName};y.push(n),h.push(n)}continue}for(const e of r.curves)for(const t of e.keys)t.time<p&&(p=t.time),t.time>f&&(f=t.time);_.push(r),u.push(r)}d.push({name:o,weight:s,normalizedWeight:s/100,blendMode:i,blend:Cn(i,s,a,l),weightCurve:b,curveNodes:_,unsupportedCurveNodes:v,diagnostics:y})}return 0===u.length&&0===c.length?null:bn(i,d,u,c,h,p,f,a,o)}function bn(e,t,n,o,s,r,i,a,l){const u=isFinite(r)&&isFinite(i),c=l&&u&&r>0?r:0;if(c>0){for(const e of n)for(const t of e.curves)for(const e of t.keys)e.time-=c;for(const e of o)for(const t of e.curves)for(const e of t.keys)e.time-=c;i-=c}const d=a?l?Math.max(a.start-c,0):a.start:0,h=a?Math.max(a.stop-c,d):0,p=h>d,f=u?r-c:0,m=u?i:0,g=p?d:l?Math.min(0,f):f,_=p?h:Math.max(m,g);return{name:e,startTime:g,stopTime:_,duration:Math.max(_-g,0),curveNodes:n,layers:t,unsupportedCurveNodes:o,diagnostics:s}}function xn(e,t,n,o){var s,r,i,a;const l=re(null!==(s=oe(t,1))&&void 0!==s?s:""),u=Mn(t),c="d|X"in u||"d|Y"in u||"d|Z"in u?[null!==(r=u["d|X"])&&void 0!==r?r:0,null!==(i=u["d|Y"])&&void 0!==i?i:0,null!==(a=u["d|Z"])&&void 0!==a?a:0]:void 0;if("T"===l||"R"===l||"S"===l){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 s=wn(e,n);return 0!==s.length||c?{type:l,targetModelId:t,curves:s,layerIndex:o,defaultValues:c}:null}const d=function(e,t){var n;for(const o of t.connections){if(o.childId!==e||"OP"!==o.type||!o.propertyName)continue;const s=t.objects.get(o.parentId);if(s&&"Geometry"===s.name)for(const e of ye(t,o.parentId,"Deformer"))if("BlendShape"===oe(e.node,2))for(const s of ye(t,e.id,"Deformer"))if("BlendShapeChannel"===oe(s.node,2)&&re(null!==(n=oe(s.node,1))&&void 0!==n?n:"")===o.propertyName)return s.id}return null}(e,n);if(null!==d){const t=wn(e,n);return 0===t.length?null:{type:"DeformPercent",targetModelId:d,curves:t,layerIndex:o,defaultValues:c}}if("DeformPercent"===l){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"===oe(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"===oe(e,2))return n.parentId}return null}(e,n);if(null===t)return null;const s=wn(e,n);return 0===s.length?null:{type:"DeformPercent",targetModelId:t,curves:s,layerIndex:o,defaultValues:c}}return null}function Tn(e,t,n,o){var s;const r=re(null!==(s=oe(t,1))&&void 0!==s?s:""),i=wn(e,n),a=Mn(t);if(0===i.length&&0===Object.keys(a).length)return null;let l,u=null;for(const t of n.connections)if(t.childId===e&&"OP"===t.type){u=t.parentId,l=t.propertyName;break}return{type:r,id:e,layerIndex:o,targetId:u,propertyName:l,curveCount:i.length,curves:i,defaultValues:a}}function An(e,t){for(const n of e)for(const e of n.keys)t(e.time)}function wn(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=Sn(e);i.length>0&&o.push(Object.assign({channel:r,keys:i},Rn(e)))}if(0===o.length){const n=ye(t,e,"AnimationCurve"),s=["d|X","d|Y","d|Z"];for(let e=0;e<n.length&&e<3;e++){const t=Sn(n[e].node);t.length>0&&o.push(Object.assign({channel:s[e],keys:t},Rn(n[e].node)))}}return o}function Mn(e){var t,n;const o={},s=te(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=oe(e,0);if(!(null==t?void 0:t.startsWith("d|")))continue;const s=En(null===(n=e.properties[4])||void 0===n?void 0:n.value);null!==s&&(o[t]=s)}return o}function Sn(e){const t=te(e,"KeyTime"),n=te(e,"KeyValueFloat");if(!t||!n)return[];const o=(l=se(t))instanceof Float64Array?l:null,s=Nn(se(n)),r=On(se(te(e,"KeyAttrFlags"))),i=Nn(se(te(e,"KeyAttrDataFloat"))),a=On(se(te(e,"KeyAttrRefCount")));var l;if(!o||!s)return[];if(o.length!==s.length)return[];const u=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))}(o.length,r,a);return function(e,t,n){const o=Math.min(e.length,t.length),s=[];if(0===o)return s;let r=0,i=en,a=0,l=Number(e[0])/Jt;for(let u=0;u<o;u++){const c=l,d=t[u];u+1<o&&(l=Number(e[u+1])/Jt);const h=u>0?t[u-1]:d,p=u+1<o?t[u+1]:d,f=n(u),m=f.flags;let g,_=f.data[0],v=en,y=f.data[1],b=en;if(50331648&m){const e=sn(f.data[2]);16777216&m&&(v=1e-4*(65535&e)),33554432&m&&(b=1e-4*(e>>>16))}let x="standard";if(2&m)g="constant",x=256&m?"next":"standard",v=b=en,_=y=0;else if(8&m)if(g="cubic",512&m){let e=0,t=0,n=!1;u>0&&c>a?e=(d-h)/(c-a):n=!0,u+1<o&&l>c?t=(p-d)/(l-c):n=!0;const s=rn(f.data[0],f.data[1],f.data[2],e,t,n);r=s.left,_=s.right,y=0,b=en}else 1024&m||(u>0&&u+1<o&&c>a&&l>c?Math.abs(r+_)<=1e-4?r=_=an(a,c,l,h,d,p,i,v,_,m):(r=an(a,c,l,h,d,p,i,v,-r,m),_=an(a,c,l,h,d,p,i,v,_,m)):r=_=u>0&&c>a?ln(a,c,h,d,-r,m):u+1<o&&l>c?ln(c,l,d,p,_,m):0);else{g="linear",v=en,b=en;const e=l-c;_=y=e>0?(p-d)/e:0}const T={time:c,value:d,interpolation:g,constantMode:x,leftDx:0,leftDy:0,rightDx:0,rightDy:0};c>a&&(T.leftDx=i*(c-a),T.leftDy=T.leftDx*r),l>c&&(T.rightDx=v*(l-c),T.rightDy=T.rightDx*_),T.rightSlope=_,s.push(T),r=y,i=b,a=c}for(let e=0;e+1<s.length;e++){const t=s[e+1];s[e].nextLeftSlope=t.leftDx>0?t.leftDy/t.leftDx:0}return s}(o,s,e=>{var t,n,o,s,a;const l=u[e],c=4*l;return{flags:l>=0&&null!==(t=null==r?void 0:r[l])&&void 0!==t?t:0,data:[null!==(n=Ln(i,c))&&void 0!==n?n:0,null!==(o=Ln(i,c+1))&&void 0!==o?o:0,null!==(s=Ln(i,c+2))&&void 0!==s?s:0,null!==(a=Ln(i,c+3))&&void 0!==a?a:0]}})}function Rn(e){const t=t=>{var n,o,s,r;const i=te(e,t);return function(e,t){const n="string"==typeof e?e.charCodeAt(0):"number"==typeof e?e:0;let o;switch(String.fromCharCode(n)){case"A":o="repeatRelative";break;case"K":o="slope";break;case"M":o="mirror";break;case"R":o="repeat";break;default:o="constant"}let s="number"==typeof t?t:-1;return s<0&&(s=-1),{mode:o,repeatCount:s}}(null===(o=null===(n=te(null!=i?i:e,"Type"))||void 0===n?void 0:n.properties[0])||void 0===o?void 0:o.value,null===(r=null===(s=te(null!=i?i:e,"Repetition"))||void 0===s?void 0:s.properties[0])||void 0===r?void 0:r.value)};return{preExtrapolation:t("Pre-Extrapolation"),postExtrapolation:t("Post-Extrapolation")}}function Cn(e,t,n,o){let s=!1,r=!1;switch(e){case 0:s=!0,r=!0;break;case 2:s=!0}let i=t/100;return i<0&&(i=0),i>.99999&&(i=1),{blended:s,additive:r,composeRotation:0===n,composeScale:0===o,weight:i}}function In(e,t){return e&&0!==e.keys.length?dn(e,t,e.keys[0].value):null}function On(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 Fn(e){return"number"==typeof e?e/Jt:null}function En(e){return"number"==typeof e?e:null}function Nn(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 Ln(e,t){if(!e||t<0||t>=e.length)return;const n=e[t];return Number.isFinite(n)?n:void 0}const kn=new Set(["Color","Intensity","OuterAngle","InnerAngle","ConeAngle","HotSpot","FieldOfView","FieldOfViewX","FieldOfViewY","FocalLength","NearPlane","FarPlane","OrthoZoom","Roll","FilmWidth","FilmHeight"]);function Pn(e,t,n){var o;const s=n.endsWith(" (Shape)")?n.slice(0,-8):n;for(const n of ye(e,t,"Geometry"))for(const t of ye(e,n.id,"Deformer"))if("BlendShape"===oe(t.node,2))for(const n of ye(e,t.id,"Deformer"))if("BlendShapeChannel"===oe(n.node,2)&&re(null!==(o=oe(n.node,1))&&void 0!==o?o:"")===s)return n.id}function Bn(e){var t,n;if(!e)return null;const o=Fn(null===(t=e.properties[0])||void 0===t?void 0:t.value),s=Fn(null===(n=e.properties[1])||void 0===n?void 0:n.value);return null!==o&&null!==s?{start:o,stop:s}:null}function Dn(e,t){var n;const o=e=>e.children.some(e=>"Key"===e.name||"Default"===e.name);if(o(e)){const n=Vn(e,t);return n.length>0?[Object.assign({channel:"d|X",keys:n},Rn(e))]:[]}const s=[];for(const r of e.children){if("Channel"!==r.name||!o(r))continue;const e=null!==(n=oe(r,0))&&void 0!==n?n:"X",i=Vn(r,t);if(i.length>0&&s.push(Object.assign({channel:`d|${e}`,keys:i},Rn(r))),3===s.length)break}return s}function Vn(e,t){var n,o,s,r,i,a;const l=te(e,"Key");if(!l)return[];const u=l.properties.map(e=>e.value),c=e=>"number"==typeof e?e:"boolean"==typeof e?e?1:0:NaN,d=e=>"string"==typeof e?e:"number"==typeof e?String.fromCharCode(e):"boolean"==typeof e?e?"":"\0":"?";let h=null!==(s=En(null===(o=null===(n=te(e,"KeyVer"))||void 0===n?void 0:n.properties[0])||void 0===o?void 0:o.value))&&void 0!==s?s:0;h<=0&&(h=t<5e3?4003:t<6e3?4004:4005);const p=null!==(a=En(null===(i=null===(r=te(e,"KeyCount"))||void 0===r?void 0:r.properties[0])||void 0===i?void 0:i.value))&&void 0!==a?a:0,f=[],m=[],g=[],_=[],v=[],y=[],b=[],x=[],T=[];let A=0,w=1/3,M=0;for(let e=0;e<p&&!(M+3>u.length);e++){const e=c(u[M])/Jt,t=c(u[M+1]),n=d(u[M+2]);M+=3;let o=0,s=0,r=1/3,i=1/3,a=!1,l="cubic",p=!1;if("U"===n){const e=d(u[M]);M+=1;let t=1;if("s"===e||"b"===e)o=c(u[M]),s=c(u[M+1]),M+=2,4003===h&&(t=0);else if("a"===e)a=!0,h<=4004&&(t=0);else if("p"===e||"q"===e)a=!0,M+=2,t=h<=4004?1:2;else if("t"===e)a=!0,M+=3,t=0;else{if("d"!==e)break;a=!0,M+=1}for(;t>0;t--){const e=d(u[M]);if(M+=1,"n"===e||"c"===e);else if("a"===e)r=c(u[M]),i=c(u[M+1]),M+=2;else if("l"===e)i=c(u[M]),M+=1;else{if("r"!==e){M=u.length;break}r=c(u[M]),M+=1}}}else if("L"===n)l="linear";else{if("C"!==n)break;l="constant",h>=4004&&(p="n"===d(u[M]),M+=1)}f.push(e),m.push(t),g.push(l),_.push(p),v.push(A),y.push(o),b.push(w),x.push(r),T.push(a),A=s,w=i}for(let e=0;e<f.length;e++){if(T[e]){const t=e>0&&e+1<f.length?Gn(f[e-1],f[e],f[e+1],m[e-1],m[e],m[e+1],b[e],x[e]):0;v[e]=t,y[e]=t}if("linear"===g[e]&&e+1<f.length){const t=f[e+1]-f[e],n=t>0?(m[e+1]-m[e])/t:0;y[e]=n,T[e+1]||(v[e+1]=n)}}return function(e,t,n,o,s,r,i,a){var l,u;const c=[];for(let d=0;d<e.length;d++){const h={time:e[d],value:t[d],interpolation:n[d],constantMode:o[d]?"next":"standard",leftDx:0,leftDy:0,rightDx:0,rightDy:0,rightSlope:r[d],nextLeftSlope:d+1<e.length?s[d+1]:void 0};d>0&&e[d]>e[d-1]&&(h.leftDx=(null!==(l=null==i?void 0:i[d])&&void 0!==l?l:en)*(e[d]-e[d-1]),h.leftDy=h.leftDx*s[d]),d+1<e.length&&e[d+1]>e[d]&&(h.rightDx=(null!==(u=null==a?void 0:a[d])&&void 0!==u?u:en)*(e[d+1]-e[d]),h.rightDy=h.rightDx*r[d]),c.push(h)}return c}(f,m,g,_,v,y,b,x)}function Gn(e,t,n,o,s,r,i,a){if(!(n>e))return 0;const l=(r-o)/(n-e),u=l>=0?1:-1;let c=u*l;const d=i*(t-e),h=a*(n-t);let p=d>0?u*(s-o)/d:0,f=h>0?u*(r-s)/h:0;return p>0||(p=0),f>0||(f=0),c=Math.min(c,p,f),u*c}function $n(e,t,n,o,s,r){var i;let a=[o[0],o[1],o[2]];for(let o=0;o<Math.max(t.length,1);o++){const l=e.find(e=>e.type===n&&e.layerIndex===o);if(!l)continue;const u=null!==(i=l.defaultValues)&&void 0!==i?i:a,c=[dn(l.curves.find(e=>"d|X"===e.channel),r,u[0]),dn(l.curves.find(e=>"d|Y"===e.channel),r,u[1]),dn(l.curves.find(e=>"d|Z"===e.channel),r,u[2])],d=t[o];if(0!==o&&d){let e=d.blend;if(d.weightCurve&&e.blended){let t=dn(d.weightCurve,r,d.weight)/100;t=t<0?0:t>.99999?1:t,e=Object.assign(Object.assign({},e),{weight:t})}a=vn(a,c,e,n,s)}else a=c}return a}function Un(e,t,n,o,s){const r=n.map((e,t)=>{var n;return null!==(n=o[t])&&void 0!==n?n:0});for(let o=0;o<Math.max(t.length,1);o++){const i=e.find(e=>e.layerIndex===o);if(!i)continue;const a=n.map((e,t)=>{var n,o;return dn(i.curves.find(t=>t.channel===e),s,null!==(o=null===(n=i.defaultValues)||void 0===n?void 0:n[e])&&void 0!==o?o:r[t])}),l=t[o];if(0===o||!l){for(let e=0;e<r.length;e++)r[e]=a[e];continue}let u=l.blend;if(l.weightCurve&&u.blended){let e=dn(l.weightCurve,s,l.weight)/100;e=e<0?0:e>.99999?1:e,u=Object.assign(Object.assign({},u),{weight:e})}for(let e=0;e<r.length;e++)r[e]=vn([r[e],0,0],[a[e],0,0],u,"other",0)[0]}return r}function Hn(e,t,n){let o=!1;for(const s of e)if(s.type===t)for(const e of s.curves){const t=e.keys;if(t.length<2)continue;if(o=!0,n<t[0].time||n>=t[t.length-1].time)return!1;let s=0;for(;s+1<t.length&&t[s+1].time<=n;)s++;if("constant"!==t[s].interpolation)return!1}return o}function Kn(e,t,n){var o;const s=n.parentOf.get(e);if(!s)return null;const r=n.objects.get(s.id);if(!r||"Geometry"!==r.name)return null;const i=s.id,a=[],l=ye(n,e,"Deformer");for(const{id:e,node:t}of l){if("BlendShapeChannel"!==oe(t,2))continue;const s=re(null!==(o=oe(t,1))&&void 0!==o?o:"MorphTarget");let r=0;for(const e of pe(t))"DeformPercent"===e.name&&"number"==typeof e.values[0]&&(r=e.values[0]);const i=jn(t),l=[],u=ye(n,e,"Geometry");for(const{node:e}of u){if("Shape"!==oe(e,2))continue;const t=zn(e);t&&l.push(t)}if(l.length>0){const t=[],n=Wn(i,l,e,s,t);a.push({name:s,id:e,deformPercent:r,shapes:qn(l,n),fullWeights:n?[...n].sort((e,t)=>e-t):null,diagnostics:t})}}return 0===a.length?null:{id:e,geometryId:i,channels:a}}function jn(e){const t=se(te(e,"FullWeights"));return t&&(t instanceof Float64Array||t instanceof Float32Array||t instanceof Int32Array)?Array.from(t,e=>Number(e)):null}function Wn(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 qn(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 zn(e){const t=te(e,"Indexes"),n=te(e,"Vertices");if(!t||!n)return null;const o=se(t),s=se(n);if(!o||!s)return null;const r=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}(o);if(!r)return null;let i;if(s instanceof Float64Array)i=s;else{if(!(s instanceof Float32Array))return null;i=new Float64Array(s)}let a=null;const l=te(e,"Normals");if(l){const e=se(l);e instanceof Float64Array?a=e:e instanceof Float32Array&&(a=new Float64Array(e))}return{indices:r,vertices:i,normals:a}}const Xn=new Set(["Character","CharacterPose","ControlSet","ControlSetPlug"]),Yn=new Set(["Camera","Light","Null","LodGroup","LimbNode","Limb","Root","Skeleton","Marker","CameraSwitcher","Mesh","NurbsCurve","NurbsSurface","TrimNurbsSurface","Line","Boundary"]);function Qn(e){return"Skin"===e||"Cluster"===e||"BlendShape"===e||"BlendShapeChannel"===e}function Zn(e,t,n,o,s){var r,i,a,l;return{type:o,message:s,objectId:t,objectName:re(null!==(r=oe(n,1))&&void 0!==r?r:n.name),nodeName:n.name,subType:null!==(i=oe(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 Jn(e,t,n){const o=ye(e,t,"Deformer").map(e=>{var t;return null!==(t=oe(e.node,2))&&void 0!==t?t:""}).filter(e=>"Skin"===e||"BlendShape"===e);0!==o.length&&n.diagnostics.push({type:"nurbs-deformer-ignored",message:`${Array.from(new Set(o)).join(" and ")} deformer on NURBS surface '${n.name}' is ignored: the tessellated mesh has no control point mapping.`})}function eo(e,t={}){var n;(function(e){return!ne(e,"Objects")&&e.nodes.some(e=>"Model"===e.name)})(e)&&(e=function(e){var t,n,o,s,r,i,a;const l=et(te(null!==(t=ne(e,"FBXHeaderExtension"))&&void 0!==t?t:Ye("x"),"FBXVersion")),u=Math.max(e.version,null!=l?l:0),c={version:u,objects:[],connections:[],usedNames:new Map,takeDefaults:new Map},d=ne(e,"Takes");for(const e of null!==(n=null==d?void 0:d.children)&&void 0!==n?n:[])if("Take"===e.name)for(const t of e.children){if("Model"!==t.name)continue;const e=oe(t,0),n=t.children.find(e=>"Channel"===e.name&&"Transform"===oe(e,0));e&&n&&!c.takeDefaults.has(e)&&c.takeDefaults.set(e,n)}const h=e.nodes.filter(e=>"Model"===e.name);for(const e of h)ut(c,e);const p=[];for(const e of h){const t=e.children.filter(e=>"Channel"===e.name&&rt(e));t.length>0&&p.push(Ye("Model",[qe(null!==(o=oe(e,0))&&void 0!==o?o:"")],t))}let f=d;if(p.length>0){const e=Ye("Take",[qe("(internal)")],p);f=d?Ye("Takes",d.properties,[...d.children,e]):Ye("Takes",[],[e])}const m=null!==(s=ne(e,"Settings"))&&void 0!==s?s:te(null!==(r=ne(e,"Version5"))&&void 0!==r?r:Ye("x"),"Settings"),g=m?te(m,"FrameRate"):void 0,_=null===(i=null==g?void 0:g.properties[0])||void 0===i?void 0:i.value,v="number"==typeof _?_:"string"==typeof _?Number.parseFloat(_):NaN,y=[];let b=!1;if(Number.isFinite(v)&&v>0){const t=ne(e,"GlobalSettings");if(t){const e=te(t,"Properties70"),n=null!==(a=null!=e?e:te(t,"Properties60"))&&void 0!==a?a:Ye("Properties60"),o=e?Ze:Qe,s=n.children.some(e=>"TimeMode"===oe(e,0))?[]:[o("TimeMode","enum","",14),o("CustomFrameRate","double","",v)],r=t.children.filter(e=>e!==n);y.push(Ye("GlobalSettings",t.properties,[...r,Ye(n.name,n.properties,[...n.children,...s])]))}else y.push(Ye("GlobalSettings",[],[Ye("Version",[Xe(1e3)]),Ye("Properties60",[],[Qe("TimeMode","enum","",14),Qe("CustomFrameRate","double","",v)])]));b=!0}const x=[...e.nodes.filter(e=>"Model"!==e.name&&"Takes"!==e.name&&"Settings"!==e.name&&("GlobalSettings"!==e.name||!b)),...y,Ye("Objects",[],c.objects),Ye("Connections",[],c.connections)];return f&&x.push(f),Object.assign(Object.assign({},e),{version:u,nodes:x})}(e));const o=function(e){var t,n,o,s,r;const i=new Map,a=[],l=new Map,u=new Map,c=[],d=[],h=[],p=new Map,f=new Map,m=new Map,g=new Map,_=ne(e,"Objects"),v=ne(e,"Connections"),y=new Set,b=e=>{const t=null==e?void 0:e.value;"number"==typeof t&&Number.isSafeInteger(t)&&y.add(t)};for(const e of null!==(t=null==_?void 0:_.children)&&void 0!==t?t:[])b(e.properties[0]);for(const e of null!==(n=null==v?void 0:v.children)&&void 0!==n?n:[])b(e.properties[1]),b(e.properties[2]),b(e.properties[3]);let x=-1;const T=()=>{for(;y.has(x);)x--;const e=x--;return y.add(e),e},A=new Map,w=e=>{if(e){if(void 0!==e.raw){let t=A.get(e.raw);return void 0===t&&(t=T(),A.set(e.raw,t)),t}return function(e){if("number"==typeof e&&Number.isFinite(e)&&Number.isInteger(e))return e}(e.value)}},M=e=>{const t=w(e);if(void 0!==t)return t;const n=null==e?void 0:e.value;if("string"!=typeof n)return;const o=p.get(n);if(void 0!==o)return o;const s=re(n);return"Scene"===s?0:f.get(s)},S=e=>{let t=p.get(e);if(void 0===t){t=T(),p.set(e,t);const n=re(e);f.has(n)||f.set(n,t)}return t},R=(e,t)=>{let n=m.get(e);n||(n=new Map,m.set(e,n));let o=n.get(t);return void 0===o&&(o=T(),n.set(t,o)),o},C=(e,t,n)=>{var o;const s=e.children.filter(e=>"Shape"===e.name);if(0===s.length)return;const r=R("BlendShape",n),d=xe("Deformer",r,`Deformer::${re(n)}`,"BlendShape",[be(100)]);i.set(r,d),a.push({id:r,node:d,source:"legacySyntheticBlendShape",legacyName:n,synthetic:!0}),Te(c,l,u,h,"OO",r,t);for(const e of s){const t=re(null!==(o=oe(e,0))&&void 0!==o?o:"Shape"),s=R("BlendShapeChannel",`${n}|${t}`),d=xe("Deformer",s,`SubDeformer::${t}`,"BlendShapeChannel",[be(100),{name:"DeformPercent",properties:[{type:"float64",value:0}],children:[]},{name:"Properties60",properties:[],children:[{name:"Property",properties:[{type:"string",value:"DeformPercent"},{type:"string",value:"Number"},{type:"string",value:"A"},{type:"float64",value:0}],children:[]}]}]);i.set(s,d),a.push({id:s,node:d,source:"legacySyntheticBlendShape",legacyName:`${n}|${t}`,synthetic:!0}),Te(c,l,u,h,"OO",s,r);const p=R("Shape",`${n}|${t}`),f=xe("Geometry",p,`Geometry::${t}`,"Shape",e.children);i.set(p,f),a.push({id:p,node:f,source:"legacySyntheticBlendShape",legacyName:`${n}|${t}`,synthetic:!0}),Te(c,l,u,h,"OO",p,s)}};if(_)for(const e of _.children){const t=e.properties[0];if(t){const n=w(t);if(void 0!==n)i.set(n,e),a.push({id:n,node:e,source:"Objects",synthetic:!1}),"Geometry"===e.name&&"Mesh"===oe(e,2)&&C(e,n,String(n));else if("string"==typeof t.value){const n=t.value,o=S(n),s=Ae(e,o);i.set(o,s),a.push({id:o,node:s,source:"Objects",legacyName:n,synthetic:!1});const r="Model"===e.name?oe(e,1):void 0;if("Mesh"===r){const t=R("Geometry",n),s=we(e,t);i.set(t,s),a.push({id:t,node:s,source:"legacySyntheticGeometry",legacyName:n,synthetic:!0}),Te(c,l,u,h,"OO",t,o),g.set(o,t),C(e,t,n)}else if("Light"===r||"Camera"===r){const t=R("NodeAttribute",n),s=xe("NodeAttribute",t,`NodeAttribute::${re(n)}`,r,e.children);i.set(t,s),a.push({id:t,node:s,source:"legacySyntheticAttribute",legacyName:n,synthetic:!0}),Te(c,l,u,h,"OO",t,o)}}}}if(v)for(const e of v.children){if("C"!==e.name&&"Connect"!==e.name)continue;const t=d.length;let n,a=oe(e,0),p=e.properties[1],f=e.properties[2];"PO"===a&&"string"==typeof(null===(o=e.properties[2])||void 0===o?void 0:o.value)&&e.properties.length>3&&(a="OP",n=e.properties[2].value,p=e.properties[3],f=e.properties[1]);const m={source:e.name,rawType:a,accepted:!1};if(d.push(m),"OO"!==a&&"OP"!==a){const e=M(p),n=M(f);h.push({reason:"unsupported-connection-type",message:`Unsupported FBX connection type '${null!=a?a:""}' was not added to the graph.`,connectionIndex:t,type:a,childId:e,parentId:n});continue}if(void 0===p||void 0===f){h.push({reason:"missing-connection-endpoint",message:"FBX connection is missing a child or parent endpoint.",connectionIndex:t,type:a});continue}const _=M(p);let v=M(f);if(void 0!==_&&void 0!==v&&"Deformer"===(null===(s=i.get(_))||void 0===s?void 0:s.name)&&(v=null!==(r=g.get(v))&&void 0!==r?r:v),void 0===_||void 0===v){h.push({reason:"unresolved-legacy-endpoint",message:"FBX connection references a legacy string endpoint that is not present in the object table.",connectionIndex:t,type:a});continue}const y=null!=n?n:"OP"===a&&e.properties.length>3?oe(e,3):void 0;m.childId=_,m.parentId=v,m.propertyName=y,_===v&&h.push({reason:"self-loop",message:"FBX connection references the same object as child and parent.",connectionIndex:t,type:a,childId:_,parentId:v,propertyName:y}),i.has(_)||h.push({reason:"unresolved-object-reference",message:"FBX connection child ID is not present in the object table.",connectionIndex:t,type:a,childId:_,parentId:v,propertyName:y}),0===v||i.has(v)||h.push({reason:"unresolved-object-reference",message:"FBX connection parent ID is not present in the object table.",connectionIndex:t,type:a,childId:_,parentId:v,propertyName:y}),Te(c,l,u,h,a,_,v,y,t),m.accepted=!0}return{objects:i,objectEntries:a,childrenOf:l,parentOf:u,connections:c,connectionEntries:d,diagnostics:h}}(e),s=function(e){const t=new Map,n=ne(e,"Definitions");if(!n)return t;for(const e of n.children){if("ObjectType"!==e.name)continue;const n=oe(e,0);if(n)for(const o of e.children){if("PropertyTemplate"!==o.name)continue;const e=oe(o,0);if(!e)continue;const s=he(n,e,o);let r=t.get(n);r||(r=new Map,t.set(n,r)),r.set(e,s)}}return t}(e),r=function(e){var t;const n={upAxis:1,upAxisSign:1,frontAxis:2,frontAxisSign:1,coordAxis:0,coordAxisSign:1,unitScaleFactor:1,frameRate:30},o=ne(e,"GlobalSettings");if(!o)return n;let s=0,r=24;for(const{name:e,values:t}of pe(o)){const o=ao(t[0]);if(e&&void 0!==o)switch(e){case"UpAxis":n.upAxis=o;break;case"UpAxisSign":n.upAxisSign=o;break;case"FrontAxis":n.frontAxis=o;break;case"FrontAxisSign":n.frontAxisSign=o;break;case"CoordAxis":n.coordAxis=o;break;case"CoordAxisSign":n.coordAxisSign=o;break;case"UnitScaleFactor":n.unitScaleFactor=o;break;case"TimeMode":s=o;break;case"CustomFrameRate":r=o}}return n.frameRate=14===s?r>0?r:24:null!==(t=oo[s])&&void 0!==t?t:30,n}(e),i=[];for(const[e,t]of Array.from(o.objects))"Material"===t.name&&i.push(Ct(t,e,o,s));!function(e,t,n){var o,s,r,i;const a=new Map(t.map(e=>[e.id,e])),l=null!==(o=ie(n,"Texture","FbxFileTexture"))&&void 0!==o?o:ie(n,"Texture");for(const[t,n]of Array.from(e.objects)){if("Model"!==n.name)continue;const o=ye(e,t,"Texture");if(0===o.length)continue;const u=ye(e,t,"Material").filter(e=>!e.propertyName).map(e=>a.get(e.id)).filter(e=>void 0!==e);if(0===u.length)continue;const c=null!==(r=null===(s=ye(e,t,"Geometry")[0])||void 0===s?void 0:s.node)&&void 0!==r?r:n,d=te(c,"LayerElementMaterial"),h=d?se(te(d,"Materials")):null,p=e=>{switch(e.replace(/^LayerElement/,"").replace(/Textures?$/,"")){case"":case"Diffuse":return{prop:"DiffuseColor",fbx:"diffuseColor",pbr:"baseColor"};case"Emissive":return{prop:"EmissiveColor",fbx:"emissionColor",pbr:"emissionColor"};case"Specular":return{prop:"SpecularColor",fbx:"specularColor",pbr:"specularColor"};case"Ambient":return{prop:"AmbientColor",fbx:"ambientColor",pbr:"ambientOcclusion"};case"Bump":case"NormalMap":return{prop:"NormalMap",fbx:"normalMap",pbr:"normalMap"};case"Transparent":return{prop:"TransparentColor",fbx:"transparencyColor",pbr:"opacity"};case"Reflection":return{prop:"ReflectionColor",fbx:"reflectionColor",pbr:"specularColor"};case"Shininess":return{prop:"ShininessExponent",fbx:"specularExponent",pbr:"roughness"};case"Displacement":return{prop:"DisplacementColor",fbx:"displacement",pbr:"displacementMap"};default:return null}},f=c.children.filter(e=>/^LayerElement\w*Textures?$/.test(e.name)),m=o.map(({id:t,node:n})=>Ot(t,n,void 0,e,l)),g=(e,t,n)=>{var o,s,r,i,a,l;const c=u[e],d=m[t];if(!c||!d||c.textures.some(e=>e.propertyName===n.prop))return;const h=Object.assign(Object.assign({},d),{propertyName:n.prop});c.textures.push(h);const p=null!==(o=(r=c.model.fbx)[i=n.fbx])&&void 0!==o?o:r[i]={valueComponents:0,textureEnabled:!1};p.texture=h,p.textureEnabled=!0;const f=null!==(s=(a=c.model.pbr)[l=n.pbr])&&void 0!==s?s:a[l]={valueComponents:0,textureEnabled:!1};f.texture=h,f.textureEnabled=!0};if(0!==f.length)for(const e of f){const t=p(e.name),n=se(te(e,"TextureId"));if(!t||!n||0===n.length)continue;const o=Math.max(n.length,null!==(i=null==h?void 0:h.length)&&void 0!==i?i:0);for(let e=0;e<o;e++){const o=n[Math.min(e,n.length-1)],s=h&&h.length>0?h[Math.min(e,h.length-1)]:0;o>=0&&g(s,o,t)}}else 1===u.length&&1===m.length&&g(0,0,p("LayerElementTexture"))}}(o,i,s);const a=[],l=[];for(const[e,n]of Array.from(o.objects))if("Geometry"===n.name){const s=oe(n,2);if("Mesh"===s){const t=Me(n,e);t.positions.length>0&&t.indices.length>0&&a.push(t)}else if("NurbsSurface"===s){const s=Ke(n,e,t.nurbsSubdivision);s&&(Jn(o,e,s),a.push(s))}else if("TrimNurbsSurface"===s){const n=ye(o,e,"Geometry").find(e=>"NurbsSurface"===oe(e.node,2)),s=n?Ke(n.node,e,t.nurbsSubdivision):null;s&&(Jn(o,e,s),s.diagnostics.push({type:"nurbs-trim-ignored",message:`Trim curves of NURBS surface '${s.name}' are ignored; the surface is rendered untrimmed.`}),a.push(s))}else"NurbsCurve"===s?l.push(je(n,e)):"Line"===s&&l.push(We(n,e))}const u=function(e,t){var n;Pt=t?null!==(n=ie(t,"Model","FbxNode"))&&void 0!==n?n:ie(t,"Model"):void 0;const o=[];for(const[t,n]of Array.from(e.objects))if("Deformer"===n.name&&"Skin"===oe(n,2)){const n=Bt(t,0,e);n&&o.push(n)}return o}(o,s),c=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=jt(t,e),r=n.get(s);r?r.push(o):n.set(s,[o])}return Array.from(n.entries()).sort(([e],[t])=>Qt(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 Wt(t.modelId,n))i.add(e)}}const u=Array.from(i);for(;u.length>0;){const e=u.pop();for(const t of n.connections){if("OO"!==t.type||t.parentId!==e||i.has(t.childId))continue;const o=n.objects.get(t.childId);o&&"Model"===o.name&&Vt(o)&&(i.add(t.childId),u.push(t.childId))}}const c=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=>!Xt(s,e,1e-5))&&t.push(`Model ${n.toString()} has differing Cluster.TransformLink matrices across skins`)}return t}(a),d=new Map;for(const[e,t]of Array.from(a))d.set(e,zt(t));const h=function(e,t){const n=new Map;for(const o of Array.from(e)){const s=qt(o,t);void 0!==s&&e.has(s)&&n.set(o,s)}return n}(i,n),p=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)=>Zt(e,t,n));const r=[],i=[...Array.from(e).filter(e=>!t.has(e)).sort((e,t)=>Zt(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,h,l),f=[],m=new Map;for(const e of p){const t=null!==(o=d.get(e))&&void 0!==o?o:Yt(e,n);if(!t)continue;const i=h.get(e),a=void 0===i?-1:null!==(s=m.get(i))&&void 0!==s?s:-1,l=f.length,u=Object.assign(Object.assign({},t),{index:l,parentIndex:a,isCluster:r.has(e)});f.push(u),m.set(e,l)}const g=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()}`,m));return{id:`rig_${e.toString()}`,rootModelIds:f.filter(e=>e.parentIndex<0).map(e=>e.modelId),bones:f,modelIdToBoneIndex:m,clusterModelIds:r,skinBindings:g,warnings:c}}(t,n,e))}(o,u),d=function(e){const t=[];for(const[n,o]of Array.from(e.objects))if("Deformer"===o.name&&"BlendShape"===oe(o,2)){const o=Kn(n,0,e);o&&t.push(o)}return t}(o),h=function(e,t,n={}){var o;const s=[],r=null===(o=n.rebaseKeyframes)||void 0===o||o;for(const[t,n]of Array.from(e.objects))if("AnimationStack"===n.name){const o=yn(t,n,e,r);o&&s.push(o)}return 0===s.length&&t&&s.push(...function(e,t,n=!0){var o,s,r,i,a,l;const u=ne(e,"Takes");if(!u)return[];const c=new Map,d=new Map;for(const e of t.objectEntries)if(void 0!==e.legacyName&&!e.synthetic&&!c.has(e.legacyName)){c.set(e.legacyName,e.id);const t=re(e.legacyName);d.has(t)||d.set(t,e.id)}const h=[];let p=-1e6;for(const f of u.children){if("Take"!==f.name)continue;const u=re(null!==(o=oe(f,0))&&void 0!==o?o:"Take"),m=null!==(s=Bn(te(f,"LocalTime")))&&void 0!==s?s:Bn(te(f,"ReferenceTime")),g=[],_=[];let v=1/0,y=-1/0;const b=e=>{for(const t of e)for(const e of t.keys)e.time<v&&(v=e.time),e.time>y&&(y=e.time)};for(const n of f.children){if("Model"!==n.name)continue;const o=null!==(r=oe(n,0))&&void 0!==r?r:"",s=null!==(i=c.get(o))&&void 0!==i?i:d.get(re(o));if(void 0!==s)for(const o of n.children){if("Channel"!==o.name)continue;const n=null!==(a=oe(o,0))&&void 0!==a?a:"";if("Transform"===n)for(const t of o.children){if("Channel"!==t.name)continue;const n=oe(t,0);if("T"!==n&&"R"!==n&&"S"!==n)continue;const o=Dn(t,e.version);o.length>0&&(b(o),g.push({type:n,targetModelId:s,curves:o,layerIndex:0}))}else{const r=Dn(o,e.version);if(r.length>0){b(r);const e=Pn(t,s,n);if(void 0!==e){g.push({type:"DeformPercent",targetModelId:e,curves:r,layerIndex:0});continue}const o=kn.has(n)?null===(l=ye(t,s,"NodeAttribute")[0])||void 0===l?void 0:l.id:void 0;_.push({type:n,id:p--,layerIndex:0,targetId:null!=o?o:s,propertyName:n,curveCount:r.length,curves:r,defaultValues:{}})}}}}if(0===g.length&&0===_.length)continue;const x={name:"BaseLayer",weight:100,normalizedWeight:1,blendMode:0,blend:Cn(0,100,0,0),curveNodes:g,unsupportedCurveNodes:_,diagnostics:[]};h.push(bn(u,[x],g,_,[],v,y,m,n))}return h}(t,e,r)),s}(o,e,{rebaseKeyframes:null===(n=t.rebaseKeyframes)||void 0===n||n}),p=function(e,t){var n,o,s,r;const i=[],a=null!==(n=ie(t,"NodeAttribute","FbxCamera"))&&void 0!==n?n:ie(t,"NodeAttribute");for(const[t,n]of Array.from(e.objects)){if("NodeAttribute"!==n.name)continue;if("Camera"!==oe(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=re(null!==(o=oe(u,1))&&void 0!==o?o:"Camera"),d=le(n,a,"NearPlane",.1),h=le(n,a,"FarPlane",1e4),p=1===le(n,a,"CameraProjectionType",0)||1===le(n,a,"ProjectionType",0)?"orthographic":"perspective",f=ao(ae(n,a,"FocalLength")),m=null!==(s=ao(ae(n,a,"FilmWidth")))&&void 0!==s?s:ao(ae(n,a,"ApertureWidth")),g=null!==(r=ao(ae(n,a,"FilmHeight")))&&void 0!==r?r:ao(ae(n,a,"ApertureHeight")),_=ao(ae(n,a,"OrthoZoom")),v=ao(ae(n,a,"Roll")),y=co(n,a),b=y.aspectRatio,x=y.fovDegY,T=[];"orthographic"===p&&void 0===_&&T.push("Orthographic camera has no OrthoZoom; runtime orthographic bounds use a fallback."),void 0!==f&&void 0===g&&void 0===ae(n,a,"FieldOfView")&&T.push("FocalLength is present without FilmHeight; default field of view fallback may be used."),i.push({modelId:l.id,attributeId:t,userProperties:fe(n),name:c,fieldOfView:x,fieldOfViewX:y.fovDegX,apertureMode:y.apertureMode,apertureSizeInch:y.apertureSizeInch,orthographicSize:y.orthographicSize,nearPlane:d,farPlane:h,aspectRatio:b,projectionType:p,focalLength:f,filmWidth:m,filmHeight:g,orthoZoom:_,roll:v,unknownProperties:ho(n,ro),diagnostics:T})}return i}(o,s),f=function(e,t){var n,o,s,r,i;const a=[],l=null!==(n=ie(t,"NodeAttribute","FbxLight"))&&void 0!==n?n:ie(t,"NodeAttribute");for(const[t,n]of Array.from(e.objects)){if("NodeAttribute"!==n.name)continue;if("Light"!==oe(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=re(null!==(o=oe(c,1))&&void 0!==o?o:"Light"),h=le(n,l,"LightType",0),p=ue(n,l,"Color",[1,1,1]),f=le(n,l,"Intensity",100)/100,m=null!==(s=ao(ae(n,l,"OuterAngle")))&&void 0!==s?s:ao(ae(n,l,"ConeAngle")),g=ao(ae(n,l,"InnerAngle")),_=null!=m?m:45,v=le(n,l,"DecayType",2),y=ao(ae(n,l,"DecayStart")),b=lo(ae(n,l,"EnableNearAttenuation")),x=lo(ae(n,l,"EnableFarAttenuation")),T=null!==(i=null!==(r=lo(ae(n,l,"CastShadow")))&&void 0!==r?r:lo(ae(c,void 0,"CastShadow")))&&void 0!==i?i:lo(ae(c,void 0,"Shadow")),A=[];2!==v&&A.push(`DecayType ${v} is preserved as metadata; Babylon falloff is not remapped in this pass.`),void 0!==y&&A.push("DecayStart is preserved as metadata and is not mapped to Babylon light range."),a.push({modelId:u.id,attributeId:t,userProperties:fe(n),nearAttenuationStart:ao(ae(n,l,"NearAttenuationStart")),nearAttenuationEnd:ao(ae(n,l,"NearAttenuationEnd")),farAttenuationStart:ao(ae(n,l,"FarAttenuationStart")),farAttenuationEnd:ao(ae(n,l,"FarAttenuationEnd")),areaLightShape:ao(ae(n,l,"AreaLightShape")),name:d,lightType:h,color:p,intensity:f,coneAngle:_,decayType:v,innerAngle:g,outerAngle:m,decayStart:y,enableNearAttenuation:b,enableFarAttenuation:x,castShadows:T,unknownProperties:ho(n,io),diagnostics:A})}return a}(o,s),m=function(e){var t,n,o;const s=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[r,i]of Array.from(e.objects)){const a=null!==(t=oe(i,2))&&void 0!==t?t:"";if("Constraint"===i.name){const t=i.children.find(e=>"Type"===e.name),l=null!==(n=t?oe(t,0):void 0)&&void 0!==n?n:a;new Set(["Aim","Parent-Child","Position From Positions","Rotation From Rotations","Scale From Scales"]).has(l)||s.push(Zn(e,r,i,"unsupported-constraint",`Constraint '${l||re(null!==(o=oe(i,1))&&void 0!==o?o:"")}' is preserved as metadata but not evaluated at runtime.`));continue}Xn.has(i.name)?s.push(Zn(e,r,i,"unsupported-helper",`${i.name} helper data is preserved as diagnostic data but not evaluated at runtime.`)):"LayeredTexture"!==i.name?"Pose"!==i.name||"BindPose"===a?"Deformer"!==i.name||Qn(a)?"NodeAttribute"===i.name&&a&&!Yn.has(a)&&s.push(Zn(e,r,i,"unsupported-node-attribute",`NodeAttribute subtype '${a}' is preserved as diagnostic data but not converted to a Babylon object.`)):s.push(Zn(e,r,i,"unsupported-deformer",`Deformer subtype '${a}' is preserved as diagnostic data but not evaluated at runtime.`)):s.push(Zn(e,r,i,"unsupported-pose",`Pose subtype '${a}' is preserved as diagnostic data but not evaluated at runtime.`)):s.push(Zn(e,r,i,"unsupported-layered-texture","LayeredTexture is preserved as diagnostic data; runtime texture layer blending is not implemented."))}return s}(o),g=function(e){const t=[];for(const[n,o]of Array.from(e.objects))"Constraint"===o.name&&t.push(pt(n,o,e));return t}(o),_=function(e,t,n,o,s){var r;const i=new Map;for(const e of t)i.set(e.id,e);const a=new Map;for(const e of n)a.set(e.id,e);const l=new Map;for(const e of o)l.set(e.id,e);const u=null!==(r=e.childrenOf.get(0))&&void 0!==r?r:[],c=[],d=new Set,h=new Set;for(const{id:t}of u){const n=e.objects.get(t);n&&"Model"===n.name&&!d.has(t)&&(d.add(t),c.push(no(t,n,e,i,a,l,s,h)))}const p=new Set;for(const t of e.connections){if("OO"!==t.type)continue;const n=e.objects.get(t.parentId);0!==t.parentId&&"Model"!==(null==n?void 0:n.name)||p.add(t.childId)}for(const[t,n]of Array.from(e.objects))"Model"!==n.name||p.has(t)||d.has(t)||(d.add(t),c.push(no(t,n,e,i,a,l,s,h)));return c}(o,a,l,i,s),{displayLayers:v,selectionSets:y}=function(e,t){var n,o,s,r,i;const a=new Map,l=e=>{for(const t of e)a.set(t.id,t),l(t.children)};l(t);const u=[],c=[];for(const[t,l]of Array.from(e.objects))if("CollectionExclusive"===l.name){const s=pe(l),r=(e,t)=>{var n;const o=null===(n=s.find(t=>t.name===e))||void 0===n?void 0:n.values[0];return"number"==typeof o?o:"boolean"==typeof o?o?1:0:t},i=null===(n=s.find(e=>"Color"===e.name))||void 0===n?void 0:n.values,c=i&&"number"==typeof i[0]&&"number"==typeof i[1]&&"number"==typeof i[2]?[i[0],i[1],i[2]]:[.8,.8,.8],d={id:t,name:re(null!==(o=oe(l,1))&&void 0!==o?o:"DisplayLayer"),show:0!==r("Show",1),freeze:0!==r("Freeze",0),color:c,modelIds:ye(e,t,"Model").map(e=>e.id)};u.push(d);for(const e of d.modelIds){const t=a.get(e);t&&(t.displayLayer=d)}}else if("SelectionSet"===l.name||"Collection"===l.name&&"SelectionSet"===oe(l,2)){const n=[];for(const o of ye(e,t))if("Model"===o.node.name)n.push({modelId:o.id,includeNode:!0});else if("SelectionNode"===o.node.name){const t=e=>{const t=te(o.node,e);if(t)return Array.from(se(t))},i=null===(r=null===(s=te(o.node,"IsTheNodeInSet"))||void 0===s?void 0:s.properties[0])||void 0===r?void 0:r.value;for(const s of ye(e,o.id,"Model"))n.push({modelId:s.id,includeNode:void 0===i||1===i||!0===i,vertices:t("VertexIndexArray"),edges:t("EdgeIndexArray"),faces:t("PolygonIndexArray")})}c.push({id:t,name:re(null!==(i=oe(l,1))&&void 0!==i?i:"SelectionSet"),members:n})}return{displayLayers:u,selectionSets:c}}(o,_);return Object.assign({rootModels:_,displayLayers:v,selectionSets:y,constraints:g,geometries:a,curves:l,materials:i,skins:u,rigs:c,blendShapes:d,animations:h,cameras:p,lights:f,diagnostics:m},r)}const to=512;function no(e,t,n,o,s,r,i,a){var l,u,c,d;const h=re(null!==(l=oe(t,1))&&void 0!==l?l:"Model");a.add(e);const p=null!==(u=oe(t,2))&&void 0!==u?u:"Null",f=ye(n,e,"Geometry"),m=f.map(e=>o.get(e.id)).find(e=>void 0!==e),g=f.map(e=>s.get(e.id)).find(e=>void 0!==e),_=ye(n,e,"Material"),v=[];for(const{id:e}of _){const t=r.get(e);t&&v.push(t)}const y=function(e,t){return ve(e,t)}(t,null!==(c=ie(i,"Model","FbxNode"))&&void 0!==c?c:ie(i,"Model")),b=ye(n,e,"Model").filter(e=>!e.propertyName),x=[],T=[];for(const{id:e,node:t}of b){if(a.size>to){T.push(`Model hierarchy deeper than ${to} levels; deeper children were skipped.`);break}a.has(e)?T.push(`Model connection cycle detected at '${re(null!==(d=oe(t,1))&&void 0!==d?d:"")}'; the recursive child was skipped.`):x.push(no(e,t,n,o,s,r,i,a))}a.delete(e);const A=t.children.find(e=>"Culling"===e.name),w=!!A&&"CullingOff"===oe(A,0),M=function(e){const t=fe(e);if(!t)return;let n=!1;const o={};for(const e of Object.keys(t))so.has(e)||(o[e]=t[e],n=!0);return n?o:void 0}(t);let S;if("LodGroup"===p){const t=ye(n,e,"NodeAttribute").find(e=>"LodGroup"===oe(e.node,2)),o=t?pe(t.node):[],s=[],r=[];for(let e=0;;e++){const t=o.find(t=>t.name===`Thresholds|Level${e}`);if(!t)break;s.push("number"==typeof t.values[0]?t.values[0]:0)}for(let e=0;;e++){const t=o.find(t=>t.name===`DisplayLevels|Level${e}`);if(!t)break;r.push("number"==typeof t.values[0]?t.values[0]:0)}const i=o.find(e=>"ThresholdsUsedAsPercentage"===e.name);S={thresholds:s,relative:!!i&&0!==i.values[0]&&!1!==i.values[0],displayLevels:r}}return Object.assign(Object.assign({id:e,name:h,subType:p,geometry:m,materials:v,children:x,cullingOff:w,customProperties:M,lodGroup:S,curve:g},y),{diagnostics:[...y.diagnostics,...T]})}const oo=[30,120,100,60,50,48,30,30,29.97,29.97,25,24,1e3,23.976,24,96,72,59.94],so=new Set(["Lcl Translation","Lcl Rotation","Lcl Scaling","PreRotation","PostRotation","RotationPivot","ScalingPivot","RotationOffset","ScalingOffset","RotationOrder","GeometricTranslation","GeometricRotation","GeometricScaling","Visibility","InheritType","ScalingMax","DefaultAttributeIndex","currentUVSet","lockInfluenceWeights"]),ro=new Set(["FieldOfView","FieldOfViewX","FieldOfViewY","NearPlane","FarPlane","AspectWidth","AspectHeight","FilmAspectRatio","FocalLength","FilmWidth","FilmHeight","ApertureWidth","ApertureHeight","CameraProjectionType","ProjectionType","OrthoZoom","Roll","ApertureMode"]),io=new Set(["LightType","Color","Intensity","InnerAngle","OuterAngle","ConeAngle","DecayType","DecayStart","EnableNearAttenuation","EnableFarAttenuation","CastShadow","Shadow"]);function ao(e){if("number"==typeof e)return e}function lo(e){return"boolean"==typeof e?e:"number"==typeof e?0!==e:void 0}const uo=[[1e3,1e3],[404,295],[493,292],[864,630],[816,612],[980,735],[825,446],[864,732],[2066,906],[1485,991],[2080,1480],[2772,2072]];function co(e,t){const n=(n,o)=>{var s;return null!==(s=ao(ae(e,t,n)))&&void 0!==s?s:o},o=n("AspectRatioMode",0),s=n("ApertureMode",2),r=Math.max(0,Math.min(uo.length-1,Math.round(n("ApertureFormat",0)))),i=n("GateFit",0);let a=n("AspectW",0),l=n("AspectH",0);a=n("AspectWidth",a),l=n("AspectHeight",l);const u=n("FieldOfView",0),c=n("FieldOfViewX",0),d=n("FieldOfViewY",0),h=n("FocalLength",0),p=30*n("OrthoZoom",1),f=uo[r];let m=n("FilmWidth",.001*f[0]),g=n("FilmHeight",.001*f[1]);a<=0&&l<=0?(a=m>0?m:1,l=g>0?g:1):a<=0?a=m>0&&g>0?l/g*m:l:l<=0&&(l=m>0&&g>0?a/m*g:a),g*=n("FilmSqueezeRatio",7===r?2:1);let _=a,v=l;switch(o){case 3:_=a,v=a*l;break;case 4:_=l*a,v=l}const y=0!==v?_/v:1,b=0!==g?m/g:1;let x=i;3===x?x=y>b?2:1:4===x&&(x=y<b?2:1);let T=m,A=g,w=p,M=p;switch(x){case 1:T=g*y,A=g,w=p*y;break;case 2:T=m,A=m/y,M=p/y}m=T;const S=Math.PI/180,R=180/Math.PI;let C,I;switch(s){case 0:C=Math.tan(c*S*.5),I=Math.tan(d*S*.5);break;case 1:C=Math.tan(u*S*.5),I=C/y;break;case 3:{const e=h/25.4;C=e>0?T/e*.5:Math.tan(u*S*.5)*y,I=e>0?A/e*.5:Math.tan(u*S*.5);break}default:I=Math.tan(u*S*.5),C=I*y}return{fovDegX:Math.atan(C)*R*2,fovDegY:Math.atan(I)*R*2,aspectRatio:y,apertureMode:s,apertureSizeInch:[T,A],orthographicSize:[w,M]}}function ho(e,t){var n;const o=new Set;for(const s of["Properties70","Properties60"]){const r=te(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=oe(e,0);n&&!t.has(n)&&o.add(n)}}return Array.from(o).sort()}function po(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 fo(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 mo(e,n){const o=Math.PI/180,s=t.Matrix.Scaling(n[0],n[1],n[2]),r=po(e[0]*o,e[1]*o,e[2]*o);return s.multiply(r)}const go=Math.PI/180,_o={invRoot:new t.Matrix,parent:new t.Matrix,invParent:new t.Matrix,world:new t.Matrix,local:new t.Matrix,mA:new t.Matrix,mB:new t.Matrix,mC:new t.Matrix,mD:new t.Matrix,position:new t.Vector3,scale:new t.Vector3,translation:new t.Vector3,decomposedScale:new t.Vector3,localValue:new t.Vector3,up:new t.Vector3,forward:new t.Vector3,origin:new t.Vector3,axisA:new t.Vector3,axisB:new t.Vector3,axisC:new t.Vector3,eulerA:new t.Vector3,eulerB:new t.Vector3,rotation:new t.Quaternion,decomposedRotation:new t.Quaternion,result:new t.Quaternion},vo=new WeakMap;class yo{constructor(e){this._behaviors=[],this._ordered=[],this._cyclic=[],this._dirty=!1,this._beforeAnimations=null,this._afterAnimations=null,this._scene=e}static Get(e){return vo.get(e)}static GetOrCreate(e){let t=vo.get(e);return t||(t=new yo(e),vo.set(e,t)),t}get constraints(){return this._ensureOrder(),this._ordered}get cyclicConstraints(){return this._ensureOrder(),this._cyclic}register(e){this._behaviors.indexOf(e)>=0||(this._behaviors.push(e),this._dirty=!0,this._beforeAnimations||(this._beforeAnimations=this._scene.onBeforeAnimationsObservable.add(()=>this.beginFrame()),this._afterAnimations=this._scene.onAfterAnimationsObservable.add(()=>this.solve())))}unregister(e){const t=this._behaviors.indexOf(e);t<0||(this._behaviors.splice(t,1),this._dirty=!0,0===this._behaviors.length&&(this._scene.onBeforeAnimationsObservable.remove(this._beforeAnimations),this._scene.onAfterAnimationsObservable.remove(this._afterAnimations),this._beforeAnimations=null,this._afterAnimations=null,vo.delete(this._scene)))}invalidateOrder(){this._dirty=!0}beginFrame(){for(const e of this._behaviors)e.restoreBase()}solve(){this._ensureOrder();for(const e of this._behaviors)e.captureBase();for(const e of this._ordered)e.evaluate()}_ensureOrder(){if(!this._dirty)return;this._dirty=!1;const e=this._behaviors,t=e.length,n=e.map(()=>[]);for(let o=0;o<t;o++){const s=e[o].dependencyNodes();for(let r=0;r<t;r++){if(o===r)continue;const t=e[r].attachedNode;t&&s.some(e=>yo._IsAncestorOrSelf(t,e))&&n[o].push(r)}}const o=n.map(e=>e.length),s=e.map(()=>!1),r=[];let i=!0;for(;i;){i=!1;for(let a=0;a<t;a++)if(!(s[a]||o[a]>0)){s[a]=!0,r.push(e[a]),i=!0;for(let e=0;e<t;e++)!s[e]&&n[e].indexOf(a)>=0&&o[e]--}}const a=[];for(let n=0;n<t;n++)s[n]||(a.push(e[n]),r.push(e[n]));this._ordered=r,this._cyclic=a}static _IsAncestorOrSelf(e,t){let n=t;for(;n;){if(n===e)return!0;n=n.parent}return!1}}class bo{constructor(e,n){this.constraint=e,this._options=n,this.attachedNode=null,this.enabled=!0,this._base={position:new t.Vector3,rotation:new t.Quaternion,scaling:new t.Vector3},this._hasBase=!1,this.name=`fbxConstraint:${e.name}`,this._offsetTranslation=new t.Vector3(e.offsetTranslation[0],e.offsetTranslation[1],e.offsetTranslation[2]),this._offsetRotation=po(e.offsetRotation[0]*go,e.offsetRotation[1]*go,e.offsetRotation[2]*go),this._offsetScale=new t.Vector3(e.offsetScale[0],e.offsetScale[1],e.offsetScale[2]);const o=new t.Matrix;this._localBasisTransposed=bo._OrthonormalBasisToRef(new t.Vector3(e.aimVector[0],e.aimVector[1],e.aimVector[2]),new t.Vector3(e.upVector[0],e.upVector[1],e.upVector[2]),o)?o.transpose():null}init(){}attach(e){this.attachedNode=e,yo.GetOrCreate(e.getScene()).register(this),this.captureBase(),this.evaluate()}detach(){var e;this.attachedNode&&(null===(e=yo.Get(this.attachedNode.getScene()))||void 0===e||e.unregister(this)),this.attachedNode=null,this._hasBase=!1}captureBase(){const e=this.attachedNode;e&&(e.rotationQuaternion||(e.rotationQuaternion=t.Quaternion.FromEulerVector(e.rotation)),this._base.position.copyFrom(e.position),this._base.rotation.copyFrom(e.rotationQuaternion),this._base.scaling.copyFrom(e.scaling),this._hasBase=!0)}restoreBase(){const e=this.attachedNode;e&&this._hasBase&&(e.position.copyFrom(this._base.position),e.rotationQuaternion.copyFrom(this._base.rotation),e.scaling.copyFrom(this._base.scaling))}dependencyNodes(){const e=this._options.targets.map(e=>e.node);return e.push(this._options.upNode),e.push(this.attachedNode?this.attachedNode.parent:null),e}evaluate(){const e=this.attachedNode,n=this.constraint;if(!e||!this.enabled||!n.active||n.weight<=0||0===this._options.targets.length)return;this._hasBase||this.captureBase(),this._options.root.computeWorldMatrix(!0).invertToRef(_o.invRoot);const o=e.parent;switch(o&&"function"==typeof o.computeWorldMatrix?this._fbxWorld(o,_o.parent):t.Matrix.IdentityToRef(_o.parent),_o.parent.invertToRef(_o.invParent),n.type){case"position":this._solvePosition(e);break;case"rotation":this._solveRotation(e);break;case"scale":this._solveScale(e);break;case"parent":this._solveParent(e);break;case"aim":this._solveAim(e)}}_fbxWorld(e,t){return e.computeWorldMatrix(!0).multiplyToRef(_o.invRoot,t),t}_blendTargets(e,n,o){e.set(0,0,0),o.set(0,0,0),n.set(0,0,0,1);let s=0;for(const r of this._options.targets){if(r.weight<=0)continue;r.offset.multiplyToRef(this._fbxWorld(r.node,_o.world),_o.local),_o.local.decompose(_o.decomposedScale,_o.decomposedRotation,_o.translation);const i=s+r.weight;e.addInPlace(_o.translation.scaleInPlace(r.weight)),o.addInPlace(_o.decomposedScale.scaleInPlace(r.weight)),0===s?n.copyFrom(_o.decomposedRotation):t.Quaternion.SlerpToRef(n,_o.decomposedRotation,r.weight/i,n),s=i}return s>0&&(e.scaleInPlace(1/s),o.scaleInPlace(1/s)),s}_applyWeighted(e,t,n,o){const s=this.constraint.weight;o.set(n[0]?e.x+(t.x-e.x)*s:e.x,n[1]?e.y+(t.y-e.y)*s:e.y,n[2]?e.z+(t.z-e.z)*s:e.z)}_applyRotation(e,n,o){const s=this._base.rotation,r=_o.result;r.copyFrom(n),o[0]&&o[1]&&o[2]||(s.toEulerAnglesToRef(_o.eulerA),n.toEulerAnglesToRef(_o.eulerB),t.Quaternion.FromEulerAnglesToRef(o[0]?_o.eulerB.x:_o.eulerA.x,o[1]?_o.eulerB.y:_o.eulerA.y,o[2]?_o.eulerB.z:_o.eulerA.z,r)),this.constraint.weight<1&&t.Quaternion.SlerpToRef(s,r,this.constraint.weight,r),e.rotationQuaternion.copyFrom(r)}_writePosition(e,t){this._applyWeighted(this._base.position,t,this.constraint.affectTranslation,e.position)}_writeScaling(e,t){this._applyWeighted(this._base.scaling,t,this.constraint.affectScale,e.scaling)}_solvePosition(e){0!==this._blendTargets(_o.position,_o.rotation,_o.scale)&&(t.Vector3.TransformCoordinatesToRef(_o.position,_o.invParent,_o.localValue),_o.localValue.addInPlace(this._offsetTranslation),this._writePosition(e,_o.localValue))}_solveRotation(e){0!==this._blendTargets(_o.position,_o.rotation,_o.scale)&&(t.Matrix.FromQuaternionToRef(_o.rotation,_o.mA),this._offsetRotation.multiplyToRef(_o.mA,_o.mB),_o.mB.multiplyToRef(_o.invParent,_o.mC),_o.mC.decompose(_o.decomposedScale,_o.decomposedRotation,_o.translation),this._applyRotation(e,_o.decomposedRotation,this.constraint.affectRotation))}_solveScale(e){if(0===this._blendTargets(_o.position,_o.rotation,_o.scale))return;_o.parent.decompose(_o.decomposedScale,_o.decomposedRotation,_o.translation);const t=_o.decomposedScale,n=_o.scale;_o.localValue.set((0!==t.x?n.x/t.x:n.x)*this._offsetScale.x,(0!==t.y?n.y/t.y:n.y)*this._offsetScale.y,(0!==t.z?n.z/t.z:n.z)*this._offsetScale.z),this._writeScaling(e,_o.localValue)}_solveParent(e){0!==this._blendTargets(_o.position,_o.rotation,_o.scale)&&(t.Matrix.ComposeToRef(_o.scale,_o.rotation,_o.position,_o.mA),_o.mA.multiplyToRef(_o.invParent,_o.mB),_o.mB.decompose(_o.decomposedScale,_o.decomposedRotation,_o.translation),this._writePosition(e,_o.translation),this._applyRotation(e,_o.decomposedRotation,this.constraint.affectRotation),this._writeScaling(e,_o.decomposedScale))}_solveAim(e){const n=this.constraint;if(!this._localBasisTransposed||0===this._blendTargets(_o.position,_o.rotation,_o.scale))return;const o=this._fbxWorld(e,_o.world);if(o.getTranslationToRef(_o.origin),_o.position.subtractToRef(_o.origin,_o.forward),_o.forward.lengthSquared()<1e-20)return;_o.forward.normalize();const s=_o.up;switch(n.worldUpType){case 1:this._options.upNode?(this._fbxWorld(this._options.upNode,_o.local).getTranslationToRef(s),s.subtractInPlace(_o.origin)):s.copyFrom(this._options.sceneUp);break;case 2:this._options.upNode?(this._fbxWorld(this._options.upNode,_o.local).decompose(_o.decomposedScale,_o.decomposedRotation,_o.translation),s.set(n.worldUpVector[0],n.worldUpVector[1],n.worldUpVector[2]),s.rotateByQuaternionToRef(_o.decomposedRotation,s)):s.copyFrom(this._options.sceneUp);break;case 3:s.set(n.worldUpVector[0],n.worldUpVector[1],n.worldUpVector[2]);break;case 4:_o.localValue.set(n.upVector[0],n.upVector[1],n.upVector[2]),t.Vector3.TransformNormalToRef(_o.localValue,o,s);break;default:s.copyFrom(this._options.sceneUp)}(s.lengthSquared()<1e-20||Math.abs(t.Vector3.Dot(s.normalizeToRef(_o.localValue),_o.forward))>.9999)&&(Math.abs(_o.forward.y)<.9?s.set(0,1,0):s.set(1,0,0)),bo._OrthonormalBasisToRef(_o.forward,s,_o.mA)&&(this._localBasisTransposed.multiplyToRef(_o.mA,_o.mB),this._offsetRotation.multiplyToRef(_o.mB,_o.mC),_o.mC.multiplyToRef(_o.invParent,_o.mD),_o.mD.decompose(_o.decomposedScale,_o.decomposedRotation,_o.translation),this._applyRotation(e,_o.decomposedRotation,n.affectRotation))}static _OrthonormalBasisToRef(e,n,o){const s=_o.axisA,r=_o.axisB,i=_o.axisC;return e.normalizeToRef(s),n.subtractToRef(s.scaleToRef(t.Vector3.Dot(s,n),r),r),!(s.lengthSquared()<1e-20||r.lengthSquared()<1e-20||(r.normalize(),t.Vector3.CrossToRef(s,r,i),t.Matrix.FromValuesToRef(s.x,s.y,s.z,0,r.x,r.y,r.z,0,i.x,i.y,i.z,0,0,0,0,1,o),0))}}const xo={name:"fbx",extensions:{".fbx":{isBinary:!0}}};class To{constructor(e={}){var t,n,o,s,r,i,a,l,u,c;this.name=xo.name,this.extensions=xo.extensions,this._bindRestBones=new WeakSet,this._sourceBonesBySkeleton=new WeakMap,this._scaleCompensationHelpersBySkeleton=new WeakMap,this._frameRate=30,this._activeLayers=[],this._parentModelById=new Map,this._curveNodesByModelId=new Map,this._inheritScaleHelpers=new Map,this._meshByGeometryKey=new Map,this._instanceSource=new Map,this._evaluatedCurveNodeIds=new Set,this._rigBoneModelIds=new Set;const d="full"===e.preset;this._options={preset:d?"full":"compatible",normalMapCoordinateSystem:null!==(t=e.normalMapCoordinateSystem)&&void 0!==t?t:"y-up",materials:null!==(n=e.materials)&&void 0!==n?n:d?"auto":"standard",unitScale:null!==(o=e.unitScale)&&void 0!==o?o:"preserve",shareGeometry:null!==(s=e.shareGeometry)&&void 0!==s?s:d,onWarning:null!==(r=e.onWarning)&&void 0!==r?r:()=>{},nurbsSubdivision:null!==(i=e.nurbsSubdivision)&&void 0!==i?i:0,curves:null!==(a=e.curves)&&void 0!==a?a:d?"lines":"skip",constraints:null!==(l=e.constraints)&&void 0!==l?l:d?"apply":"metadata",rebaseAnimations:null!==(u=e.rebaseAnimations)&&void 0!==u?u:!d,attachCamerasAndLights:null!==(c=e.attachCamerasAndLights)&&void 0!==c?c:d}}createPlugin(e){return new To(e[xo.name])}importMeshAsync(e,t,n,o,s,r){return b(this,void 0,void 0,function*(){const s=this._parseAndInterpret(n);return this._buildScene(s,t,o,e)})}loadAsync(e,t,n,o,s){return b(this,void 0,void 0,function*(){const o=this._parseAndInterpret(t);this._buildScene(o,e,n,null)})}loadAssetContainerAsync(e,n,o,s,r){return b(this,void 0,void 0,function*(){const s=this._parseAndInterpret(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)e instanceof t.LinesMesh||this._addMaterialToContainer(e.material,r);return this._setAssetContainer(r),r.removeAllFromScene(),r})}_parseAndInterpret(e){return eo(this._parse(e),{nurbsSubdivision:this._options.nurbsSubdivision>0?this._options.nurbsSubdivision:void 0,rebaseKeyframes:this._options.rebaseAnimations})}_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 W(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(D=!(n.length>22)||0===n[22],"Kaydara FBX Binary \0"!==j(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,D),s=o>=7500,r=[];let i=27;for(;i<e.byteLength;){const o=V(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),o=n.substring(0,4096);if(o.trimStart().startsWith("; FBX")||/^\s*(?:;[^\n]*\n\s*)*(?:FBXHeaderExtension|Definitions|Objects|Connections)\s*:/.test(o))return W(n);throw new Error("FBXFileLoader: unrecognized FBX format")}_buildScene(e,n,o,s){var r;const i=this._buildNameFilter(s);this._frameRate=e.frameRate>0?e.frameRate:30,this._inheritScaleHelpers=new Map;const 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,p=new Map;for(const t of e.skins)p.set(t.id,t);this._rigBoneModelIds=new Set;for(const t of e.rigs)for(const e of t.bones)this._rigBoneModelIds.add(e.modelId);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=p.get(n.skinId);t&&(c.set(n.geometryId,e),d.set(n.geometryId,t),h.set(n.geometryId,n))}}const f=new Map;this._parentModelById=new Map;const m=(e,t)=>{for(const n of e)f.set(n.id,n),t&&this._parentModelById.set(n.id,t),m(n.children,n)};m(e.rootModels,null);const g=To._collectCullingConflictMaterialIds(e.rootModels),_=new Map,v=new t.TransformNode("__fbx_root__",n);n.useRightHandedSystem||(v.rotation.y=Math.PI,v.scaling.z=-1);const y=this._options.unitScale,b="preserve"===y?0:"meters"===y?100:y;if(b>0&&e.unitScaleFactor>0){const t=e.unitScaleFactor/b;v.scaling.scaleInPlace(t)}v.metadata=Object.assign(Object.assign({},null!==(r=v.metadata)&&void 0!==r?r:{}),{fbxUnitScaleFactor:e.unitScaleFactor,fbxFrameRate:e.frameRate}),this._meshByGeometryKey=new Map,this._instanceSource=new Map,this._evaluatedCurveNodeIds=new Set;const x=[],T=[v];let A=v;const w=To._computeFBXAxisConversionMatrix(e);w.equals(t.Matrix.Identity())||(A=new t.TransformNode("__fbx_axis_conversion__",n),A.parent=v,To._applyMatrixToTransform(A,w),T.push(A));const M=new Map,S=t.Matrix.Identity();for(const t of e.rootModels)this._buildModel(t,n,A,A,S,a,i,x,T,c,d,h,M,g,_);this._linkSkeletonsToTransformNodes(e.rigs,u,M,T,n);for(const t of e.rigs){const e=u.get(t.id);if(!e)continue;x.find(t=>t.skeleton===e);const n=new Set;for(const t of e.bones){const e=t.getTransformNode();e&&n.add(e)}}if(e.blendShapes.length>0){this._applyBlendShapes(e.blendShapes,x,n);for(const[e,t]of Array.from(this._instanceSource))t.morphTargetManager&&!e.morphTargetManager&&(e.morphTargetManager=t.morphTargetManager)}const R=[],C=new Map;for(const t of e.cameras){const e=this._createCamera(t,M,n);e&&(R.push(e),C.set(t.attributeId,e))}const I=[],O=new Map;for(const t of e.lights){const e=this._createLight(t,M,n);e&&(I.push(e),O.set(t.attributeId,e))}this._applyConstraints(e,M,v,n);const F=[];for(const t of e.animations){const o=this._createAnimationGroup(t,e.rigs,u,n,M,f,x,{cameraByAttributeId:C,lightByAttributeId:O,materialCache:a});o&&F.push(o)}return this._reportDiagnostics(e,v,M),{meshes:x,particleSystems:[],skeletons:l,animationGroups:F,transformNodes:T,geometries:[],lights:I,spriteManagers:[],materials:Array.from(a.values()),textures:Array.from(new Set(Array.from(a.values()).flatMap(e=>e.getActiveTextures()))),cameras:R}}_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,p,f,m){var g,_,v;let y=o;const b=To._computeFBXModelLocalMatrix(e).multiply(r),x=this._parentModelById.get(e.id),T=x?p.get(x.id):void 0;if(y&&x&&T&&y===T&&1!==e.inheritType&&!this._isRigBone(e.id)&&!this._isRigBone(x.id)&&(!x.geometry||!d.has(x.geometry.id))){const o=new t.TransformNode(`${e.name}__fbx_inheritScale`,n);o.parent=T.parent,o.position.copyFrom(T.position),o.rotationQuaternion=T.rotationQuaternion?T.rotationQuaternion.clone():t.Quaternion.FromEulerVector(T.rotation),o.scaling.set(1,1,1),u.push(o),this._inheritScaleHelpers.set(e.id,o),y=o}if(e.geometry&&e.geometry.indices.length>0&&(!a||a(e.name))){const o=null!==e.geometry.controlPointIndices,r=o?c.get(e.geometry.id):void 0,x=o?d.get(e.geometry.id):void 0,T=o?h.get(e.geometry.id):void 0;r&&x&&(r.needInitialSkinMatrix=!0);const A=`${e.geometry.id}|${e.geometricTranslation.join(",")}|${e.geometricRotation.join(",")}|${e.geometricScaling.join(",")}`,w=!r&&this._options.shareGeometry?this._meshByGeometryKey.get(A):void 0;let M;if(w?(M=w.clone(e.name,null,!0),M.sideOrientation=w.sideOrientation,M.metadata=Object.assign(Object.assign({},null!==(g=w.metadata)&&void 0!==g?g:{}),{fbxInstanceOf:w.name}),this._instanceSource.set(M,w)):(M=this._createMesh(e,e.geometry,n,r,x,T),r||this._meshByGeometryKey.set(A,M)),r&&x){const e=x.meshBindPoseMatrix?t.Matrix.FromArray(x.meshBindPoseMatrix):b;M.parent=s,To._applyMatrixToTransform(M,e),M.computeWorldMatrix(!0),M.updatePoseMatrix(t.Matrix.Invert(e)),M.alwaysSelectAsActiveMesh=!0}else y&&(M.parent=y),this._applyRestTRS(M,e);if(e.materials.length>1&&(null===(_=e.geometry)||void 0===_?void 0:_.materialIndices))this._applyMultiMaterial(M,e,i,n,f,m);else if(e.materials.length>0){const t=i.get(e.materials[0].id);t&&(M.material=To._getModelMaterial(t,e,m,f.has(e.materials[0].id)))}(null===(v=e.geometry)||void 0===v?void 0:v.colors)&&this._useUnmodulatedVertexColorMaterials(M,n),this._applyMaterialUVSetCoordinates(M.material,e.geometry),l.push(M),p.set(e.id,M),To._applyModelMetadata(M,e);for(const t of e.children)this._buildModel(t,n,M,s,b,i,a,l,u,c,d,h,p,f,m)}else if(e.curve&&"skip"!==this._options.curves&&e.curve.polylines.length>0&&(!a||a(e.name))){const t=this._createLinesMesh(e,e.curve,n);y&&(t.parent=y),this._applyRestTRS(t,e),l.push(t),p.set(e.id,t),To._applyModelMetadata(t,e);for(const o of e.children)this._buildModel(o,n,t,s,b,i,a,l,u,c,d,h,p,f,m)}else{if((e.geometry||e.curve)&&a&&!To._modelSubtreeMatchesNameFilter(e,a))return;const o=new t.TransformNode(e.name,n);y&&(o.parent=y),this._applyRestTRS(o,e),u.push(o),p.set(e.id,o),To._applyModelMetadata(o,e);for(const t of e.children)this._buildModel(t,n,o,s,b,i,a,l,u,c,d,h,p,f,m);To._applyLodGroup(e,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,To._applyMatrixToTransform(e,l.getLocalMatrix()),To._applyMatrixToTransform(a,i.getLocalMatrix()),l.linkTransformNode(e),s.push(e)}else To._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(To._modelSubtreeMatchesNameFilter(n,t))return!0}return!1}static _applyModelMetadata(e,t){var n;(t.customProperties||0!==t.diagnostics.length||t.displayLayer||t.lodGroup)&&(e.metadata=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},null!==(n=e.metadata)&&void 0!==n?n:{}),t.customProperties?{fbxCustomProperties:t.customProperties,fbxUserProperties:t.customProperties}:{}),t.diagnostics.length>0?{fbxDiagnostics:t.diagnostics}:{}),t.displayLayer?{fbxDisplayLayer:{name:t.displayLayer.name,show:t.displayLayer.show,freeze:t.displayLayer.freeze,color:t.displayLayer.color}}:{}),t.lodGroup?{fbxLodGroup:t.lodGroup}:{}),t.displayLayer&&!t.displayLayer.show&&e.setEnabled(!1))}static _applyLodGroup(e,n){var o,s,r,i,a,l;const u=e.lodGroup;if(!u)return;const c=[];for(let t=0;t<e.children.length;t++){const r=e.children[t],i=null!==(o=u.displayLevels[t])&&void 0!==o?o:0;2===i?null===(s=n.get(r.id))||void 0===s||s.setEnabled(!1):0===i&&c.push({child:r,level:t})}if(c.length<2)return;const d=e=>{const o=n.get(e.id);if(!o)return[];const s=o instanceof t.Mesh?[o]:[];for(const e of o.getChildMeshes(!1))e instanceof t.Mesh&&s.push(e);return s},h=d(c[0].child);for(let e=1;e<c.length;e++){const t=c[e].level,n=d(c[e].child),o=null!==(i=null!==(r=u.thresholds[t-1])&&void 0!==r?r:u.thresholds[u.thresholds.length-1])&&void 0!==i?i:0;for(let e=0;e<h.length;e++){const s=null!==(a=n[e])&&void 0!==a?a:null;u.relative?(h[e].useLODScreenCoverage=!0,h[e].addLODLevel(o/100,s)):h[e].addLODLevel(o,s),s&&(s.metadata=Object.assign(Object.assign({},null!==(l=s.metadata)&&void 0!==l?l:{}),{fbxLodLevel:t}))}}}_createLinesMesh(e,n,o){var s;const r=new t.LinesMesh(e.name,o),i=[],a=[];for(const e of n.polylines){const t=e.length/3;if(t<2)continue;const n=i.length/3;for(let t=0;t<e.length;t++)i.push(e[t]);for(let e=0;e<t-1;e++)a.push(n+e,n+e+1)}const l=To._computeFBXGeometricMatrix(e.geometricTranslation,e.geometricRotation,e.geometricScaling);if(!l.equals(t.Matrix.Identity()))for(let e=0;e<i.length;e+=3){const n=t.Vector3.TransformCoordinates(new t.Vector3(i[e],i[e+1],i[e+2]),l);i[e]=n.x,i[e+1]=n.y,i[e+2]=n.z}const u=new t.VertexData;return u.positions=i,u.indices=a,u.applyToMesh(r),n.color&&(r.color=new t.Color3(n.color[0],n.color[1],n.color[2])),r.metadata=Object.assign(Object.assign({},null!==(s=r.metadata)&&void 0!==s?s:{}),{fbxCurveType:n.kind,fbxCurveSegments:n.polylines.length}),r}_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=Ao(n.positions),d=e.geometricTranslation,h=e.geometricRotation,p=e.geometricScaling,f=To._computeFBXGeometricMatrix(d,h,p),m=To._computeFBXGeometricDeltaMatrix(h,p),g=To._computeFBXGeometricNormalMatrix(h,p),_=!f.equals(t.Matrix.Identity()),v=!m.equals(t.Matrix.Identity()),y=!g.equals(t.Matrix.Identity());if(_)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=Ao(n.normals),y)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]),g);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=Ao(n.uvs)),n.uvSets.length>1&&(u.uvs2=Ao(n.uvSets[1].data)),n.uvSets.length>2&&(u.uvs3=Ao(n.uvSets[2].data)),n.uvSets.length>3&&(u.uvs4=Ao(n.uvSets[3].data)),n.uvSets.length>4&&(u.uvs5=Ao(n.uvSets[4].data)),n.uvSets.length>5&&(u.uvs6=Ao(n.uvSets[5].data)),n.tangents){const e=Ao(n.tangents);if(y)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]),g);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 p=e.length/3,f=new Map,m=new Array(p).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,p=3*c,g=2*l,_=2*u,v=2*c,y=e[h]-e[d],b=e[p]-e[d],x=e[h+1]-e[d+1],T=e[p+1]-e[d+1],A=e[h+2]-e[d+2],w=e[p+2]-e[d+2],M=n[_]-n[g],S=n[v]-n[g],R=n[_+1]-n[g+1],C=n[v+1]-n[g+1],I=M*C-S*R;if(Math.abs(I)<1e-8)continue;const O=1/I,F=(C*y-R*b)*O,E=(C*x-R*T)*O,N=(C*A-R*w)*O,L=(M*b-S*y)*O,k=(M*T-S*x)*O,P=(M*w-S*A)*O;wo(l,u,c,F,E,N,L,k,P,e,t,n,r,a,f,m),wo(u,c,l,F,E,N,L,k,P,e,t,n,r,a,f,m),wo(c,l,u,F,E,N,L,k,P,e,t,n,r,a,f,m)}const g=new Float32Array(4*p);for(let e=0;e<p;e++){const n=3*e,o=4*e,[r,i,p]=Mo(t[n],t[n+1],t[n+2]),_=m[e]?f.get(m[e]):void 0,v=null!==(a=null==_?void 0:_.tx)&&void 0!==a?a:0,y=null!==(l=null==_?void 0:_.ty)&&void 0!==l?l:0,b=null!==(u=null==_?void 0:_.tz)&&void 0!==u?u:0,x=r*v+i*y+p*b;let T=v-r*x,A=y-i*x,w=b-p*x;const M=Math.hypot(T,A,w);M>1e-8?(T/=M,A/=M,w/=M):[T,A,w]=Ro(r,i,p);const S=null!==(c=null==_?void 0:_.bx)&&void 0!==c?c:0,R=null!==(d=null==_?void 0:_.by)&&void 0!==d?d:0,C=null!==(h=null==_?void 0:_.bz)&&void 0!==h?h:0,I=i*w-p*A,O=p*T-r*w,F=r*A-i*T,E=Math.hypot(S,R,C)>1e-8&&I*S+O*R+F*C<0?-1:1;g[o]=T,g[o+1]=A,g[o+2]=w,g[o+3]=E*s}return g}(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:v?m:null,fbxGeometryNormalMatrix:y?g:null,fbxPreRotMatrix:v?m:null}),s&&(l.skeleton=s),l}_applyMultiMaterial(e,n,o,s,r,i){var a,l;const u=n.geometry.materialIndices,c=null===(a=e.metadata)||void 0===a?void 0:a.fbxSubMeshMaterialIndices;if(c){const a=new t.MultiMaterial(n.name+"_multi",s);for(const e of c){const t=n.materials[e],s=t?o.get(t.id):void 0;a.subMaterials.push(s?To._getModelMaterial(s,n,i,r.has(t.id)):null)}return void(e.material=a)}const d=e.getIndices();if(!d)return;const h=d.length/3,p=new Map;for(let e=0;e<h;e++){const t=e<u.length?u[e]:0;let n=p.get(t);n||(n=[],p.set(t,n)),n.push(e)}const f=Array.from(p.keys()).sort((e,t)=>e-t),m=[],g=[];for(const e of f){const t=p.get(e),n=m.length;for(const e of t)m.push(d[3*e],d[3*e+1],d[3*e+2]);g.push({start:n,count:3*t.length,matIdx:e})}e.setIndices(m);const _=new t.MultiMaterial(n.name+"_multi",s);for(const e of g){const t=n.materials[e.matIdx];if(t){const e=o.get(t.id);e?_.subMaterials.push(To._getModelMaterial(e,n,i,r.has(t.id))):_.subMaterials.push(null)}else _.subMaterials.push(null)}e.material=_,e.subMeshes=[];const v=e.getTotalVertices();for(let n=0;n<g.length;n++){const o=g[n];new t.SubMesh(n,0,v,o.start,o.count,e)}e.metadata=Object.assign(Object.assign({},null!==(l=e.metadata)&&void 0!==l?l:{}),{fbxSubMeshMaterialIndices:f})}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){var s;if(!t.cullingOff||!e.backFaceCulling)return e;if(!o)return e.backFaceCulling=!1,e;const r=null==n?void 0:n.get(e);if(r)return r;const i=null!==(s=e.clone(`${e.name}_CullingOff`))&&void 0!==s?s:e;return i.backFaceCulling=!1,null==n||n.set(e,i),i}_applyMaterialUVSetCoordinates(e,n){if(e)if(e instanceof t.MultiMaterial)for(const o of e.subMaterials)(o instanceof t.StandardMaterial||o instanceof t.PBRMaterial)&&this._applyStandardMaterialUVSetCoordinates(o,n);else(e instanceof t.StandardMaterial||e instanceof t.PBRMaterial)&&this._applyStandardMaterialUVSetCoordinates(e,n)}_applyStandardMaterialUVSetCoordinates(e,n){var o;for(const s of e instanceof t.PBRMaterial?[e.albedoTexture,e.bumpTexture,e.emissiveTexture,e.ambientTexture,e.metallicTexture,e.reflectivityTexture,e.microSurfaceTexture,e.opacityTexture,e.clearCoat.texture,e.clearCoat.bumpTexture,e.sheen.texture]:[e.diffuseTexture,e.bumpTexture,e.emissiveTexture,e.ambientTexture,e.specularTexture,e.opacityTexture,e.reflectionTexture]){if(!s)continue;const e=null===(o=s.metadata)||void 0===o?void 0:o.fbxUVSetName;if(!e)continue;const t=n.uvSets.findIndex(t=>t.name===e);t>=0&&(s.coordinatesIndex=t)}}_useUnmodulatedVertexColorMaterials(e,n){const o=e.material;if(!o)return;const s=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}if(e instanceof t.PBRMaterial&&!e.albedoTexture){const n=e.clone(`${e.name}_VertexColor`);return n.albedoColor=new t.Color3(1,1,1),n}return e};if(o instanceof t.MultiMaterial){const r=new t.MultiMaterial(`${o.name}_VertexColor`,n);return r.subMaterials=o.subMaterials.map(e=>e?s(e):e),void(e.material=r)}e.material=s(o)}_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,t,n){var o;const s=this._options.materials,r="pbr"===s||"auto"===s&&Tt(e.model.shaderType)?this._createPbrMaterial(e,t,n):this._createStandardMaterial(e,t,n);return r.metadata=Object.assign(Object.assign(Object.assign({},null!==(o=r.metadata)&&void 0!==o?o:{}),e.userProperties?{fbxUserProperties:e.userProperties}:{}),{fbxShaderType:e.model.shaderType,fbxFeatures:Object.fromEntries(Object.entries(e.model.features).map(([e,t])=>{var n;return[e,null!==(n=null==t?void 0:t.enabled)&&void 0!==n&&n]}))}),r}_createPbrMaterial(e,n,o){var s,r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b,x,T,A,w,M,S,R;const C=new t.PBRMaterial(e.name,n),I=e.model.pbr,O=e.model.features,F=e=>{var t,n;return null!==(n=null===(t=O[e])||void 0===t?void 0:t.enabled)&&void 0!==n&&n},E="3dsMaxPbrSpecGloss"===e.model.shaderType,N=(e,n)=>e?new t.Color3(e[0]*(null!=n?n:1),e[1]*(null!=n?n:1),e[2]*(null!=n?n:1)):void 0,L=St(I.baseColor);if(C.albedoColor=null!==(r=N(L,(null===(s=I.baseColor)||void 0===s?void 0:s.texture)?1:Rt(I.baseFactor)))&&void 0!==r?r:t.Color3.White(),E)C.metallic=null,C.roughness=null,C.reflectivityColor=null!==(i=N(St(I.specularColor),1))&&void 0!==i?i:t.Color3.White(),C.microSurface=null!==(a=Rt(I.glossiness))&&void 0!==a?a:1-(null!==(l=Rt(I.roughness))&&void 0!==l?l:.5);else if(C.metallic=F("metalness")&&null!==(u=Rt(I.metalness))&&void 0!==u?u:0,C.roughness=null!==(c=Rt(I.roughness))&&void 0!==c?c:(null===(d=I.glossiness)||void 0===d?void 0:d.value)?1-I.glossiness.value[0]:.5,F("specular")&&(null===(h=I.specularFactor)||void 0===h?void 0:h.value)&&(C.metallicF0Factor=null!==(p=Rt(I.specularFactor))&&void 0!==p?p:1),F("specular")){const e=St(I.specularColor);e&&(C.metallicReflectanceColor=new t.Color3(e[0],e[1],e[2]))}const k=N(St(I.emissionColor),(null===(f=I.emissionColor)||void 0===f?void 0:f.texture)?1:Rt(I.emissionFactor));(k&&F("emission")||k&&(k.r>0||k.g>0||k.b>0))&&(C.emissiveColor=k);const P=St(I.opacity);P&&F("opacity")?C.alpha=(P[0]+P[1]+P[2])/3:Tt(e.model.shaderType)||(C.alpha=To._alphaFromClassicTransparency(e)),C.alpha<1&&(C.transparencyMode=t.Material.MATERIAL_ALPHABLEND);const B=null!==(m=Rt(I.transmissionFactor))&&void 0!==m?m:0;if(F("transmission")&&Tt(e.model.shaderType)&&B>0){C.subSurface.isRefractionEnabled=!0,C.subSurface.refractionIntensity=B;const e=St(I.transmissionColor);e&&(C.subSurface.tintColor=new t.Color3(e[0],e[1],e[2]));const n=Rt(I.specularIor);n&&F("ior")&&(C.subSurface.indexOfRefraction=n)}else{const e=Rt(I.specularIor);e&&F("ior")&&e>1&&(C.indexOfRefraction=e)}const D=null!==(g=Rt(I.coatFactor))&&void 0!==g?g:0;if(F("coat")&&D>0||(null===(_=I.coatFactor)||void 0===_?void 0:_.texture)){C.clearCoat.isEnabled=!0,C.clearCoat.intensity=D;const e=Rt(I.coatRoughness);void 0!==e&&(C.clearCoat.roughness=e);const n=Rt(I.coatIor);void 0!==n&&n>1&&(C.clearCoat.indexOfRefraction=n);const o=St(I.coatColor);!o||1===o[0]&&1===o[1]&&1===o[2]||(C.clearCoat.isTintEnabled=!0,C.clearCoat.tintColor=new t.Color3(o[0],o[1],o[2]))}const V=null!==(v=Rt(I.sheenFactor))&&void 0!==v?v:0;if(F("sheen")&&V>0||(null===(y=I.sheenColor)||void 0===y?void 0:y.texture)){C.sheen.isEnabled=!0,C.sheen.intensity=V;const e=St(I.sheenColor);e&&(C.sheen.color=new t.Color3(e[0],e[1],e[2]));const n=Rt(I.sheenRoughness);void 0!==n&&(C.sheen.roughness=n)}F("unlit")&&(C.unlit=!0),F("doubleSided")&&(C.backFaceCulling=!1);const G=(e,t=!1)=>{if(!(null==e?void 0:e.texture)||!e.textureEnabled)return null;const s=To._createTexture(e.texture,n,o,t);return s&&To._applyTextureSettings(s,e.texture),s},$=G(I.baseColor);$&&(C.albedoTexture=$);const U=G(I.normalMap,!0);U&&(C.bumpTexture=U,this._configureNormalTexture(U,C));const H=G(I.emissionColor);H&&(C.emissiveTexture=H,(!k||0===k.r&&0===k.g&&0===k.b)&&(C.emissiveColor=t.Color3.White()));const K=G(I.ambientOcclusion);if(K&&(C.ambientTexture=K,C.useAmbientInGrayScale=!0),E){const e=G(I.specularColor);e&&(C.reflectivityTexture=e);const t=null!==(b=G(I.glossiness))&&void 0!==b?b:G(I.roughness);t&&(C.microSurfaceTexture=t)}else{const e=(null===(x=I.metalness)||void 0===x?void 0:x.textureEnabled)?I.metalness.texture:void 0,t=(null===(T=I.roughness)||void 0===T?void 0:T.textureEnabled)&&I.roughness.texture?I.roughness:(null===(A=I.glossiness)||void 0===A?void 0:A.textureEnabled)&&I.glossiness.texture?I.glossiness:void 0,n=null==t?void 0:t.texture,o=!!e&&!!n&&e.id===n.id;let s=!1;if(!e||!o&&n){if(n){const n=G(t);n&&(C.metallicTexture=n,C.useMetallnessFromMetallicTextureBlue=!1,C.useRoughnessFromMetallicTextureGreen=!0,C.useRoughnessFromMetallicTextureAlpha=!1,e&&(C.metadata=Object.assign(Object.assign({},null!==(w=C.metadata)&&void 0!==w?w:{}),{fbxDroppedMetalnessTexture:e.relativeFileName})))}}else{const e=G(I.metalness);e&&(s=!0,C.metallicTexture=e,C.useMetallnessFromMetallicTextureBlue=!0,C.useRoughnessFromMetallicTextureGreen=o,C.useRoughnessFromMetallicTextureAlpha=!1)}s&&0===C.metallic&&(C.metallic=1)}if((null===(M=I.opacity)||void 0===M?void 0:M.texture)&&I.opacity.textureEnabled)if($&&I.opacity.texture.id===(null===(R=null===(S=I.baseColor)||void 0===S?void 0:S.texture)||void 0===R?void 0:R.id))C.useAlphaFromAlbedoTexture=!0,C.transparencyMode=t.Material.MATERIAL_ALPHATESTANDBLEND;else{const e=G(I.opacity);e&&(C.opacityTexture=e,C.transparencyMode=t.Material.MATERIAL_ALPHATESTANDBLEND)}if(C.clearCoat.isEnabled){const e=G(I.coatFactor);e&&(C.clearCoat.texture=e);const t=G(I.coatNormal,!0);t&&(C.clearCoat.bumpTexture=t)}if(C.sheen.isEnabled){const e=G(I.sheenColor);e&&(C.sheen.texture=e)}return C}static _alphaFromClassicTransparency(e){const t=e.properties;if(void 0!==t.opacity)return t.opacity;const n=Rt(e.model.fbx.transparencyFactor);if(void 0===n)return 1;const o=St(e.model.fbx.transparencyColor),s=o?(o[0]+o[1]+o[2])/3:1;return Math.min(1,Math.max(0,1-s*n))}static _applyTextureSettings(e,n){var o;n.uvTranslation&&(e.uOffset=n.uvTranslation[0],e.vOffset=n.uvTranslation[1]),n.uvScaling&&(e.uScale=n.uvScaling[0],e.vScale=n.uvScaling[1]),void 0!==n.uvRotation&&(e.wAng=n.uvRotation*(Math.PI/180)),void 0!==n.uvSetIndex&&(e.coordinatesIndex=n.uvSetIndex),void 0!==n.wrapU&&(e.wrapU=1===n.wrapU?t.Texture.CLAMP_ADDRESSMODE:t.Texture.WRAP_ADDRESSMODE),void 0!==n.wrapV&&(e.wrapV=1===n.wrapV?t.Texture.CLAMP_ADDRESSMODE:t.Texture.WRAP_ADDRESSMODE),(n.uvSetName||void 0!==n.layeredTextureId)&&(e.metadata=Object.assign(Object.assign(Object.assign({},null!==(o=e.metadata)&&void 0!==o?o:{}),n.uvSetName?{fbxUVSetName:n.uvSetName}:{}),void 0!==n.layeredTextureId?{fbxLayeredTextureId:n.layeredTextureId}:{}))}_createStandardMaterial(e,n,o){var s,r,i,a;const l=new t.StandardMaterial(e.name,n),u=e.properties,c=(...t)=>e.textures.some(e=>t.includes(e.propertyName));if("Lambert"===e.type&&(l.specularColor=t.Color3.Black()),u.diffuseColor){const e=c("DiffuseColor","Diffuse")?1:null!==(s=u.diffuseFactor)&&void 0!==s?s:1;l.diffuseColor=new t.Color3(u.diffuseColor[0]*e,u.diffuseColor[1]*e,u.diffuseColor[2]*e)}if(u.ambientColor){const e=c("AmbientColor","Ambient")?1:null!==(r=u.ambientFactor)&&void 0!==r?r:1;l.ambientColor=new t.Color3(u.ambientColor[0]*e,u.ambientColor[1]*e,u.ambientColor[2]*e)}if("Phong"===e.type&&u.specularColor){const e=c("SpecularColor","Specular","Shininess","ShininessExponent")?1:null!==(i=u.specularFactor)&&void 0!==i?i:1;l.specularColor=new t.Color3(u.specularColor[0]*e,u.specularColor[1]*e,u.specularColor[2]*e)}if(u.emissiveColor){const e=c("EmissiveColor","Emissive")?1:null!==(a=u.emissiveFactor)&&void 0!==a?a:1;l.emissiveColor=new t.Color3(u.emissiveColor[0]*e,u.emissiveColor[1]*e,u.emissiveColor[2]*e)}l.alpha=To._alphaFromClassicTransparency(e),l.alpha<1&&(l.transparencyMode=t.Material.MATERIAL_ALPHABLEND),void 0!==u.shininess&&(l.specularPower=u.shininess);for(const s of e.textures){if(!To._isSupportedMaterialTextureSlot(s.propertyName))continue;const e=To._createTexture(s,n,o,To._isNormalMapTextureSlot(s.propertyName));if(e){switch(s.propertyName){case"DiffuseColor":l.diffuseTexture=e,l.diffuseColor=new t.Color3(1,1,1);break;case"NormalMap":case"NormalMapTexture":case"normalCamera":case"Bump":case"BumpFactor":l.bumpTexture=e,this._configureNormalTexture(e,l);break;case"EmissiveColor":l.emissiveTexture=e;break;case"AmbientColor":l.ambientTexture=e;break;case"SpecularColor":l.specularTexture=e;break;case"TransparencyFactor":case"TransparentColor":l.opacityTexture=e,l.transparencyMode=t.Material.MATERIAL_ALPHATESTANDBLEND;break;case"ReflectionColor":case"ReflectionFactor":l.reflectionTexture=e}To._applyTextureSettings(e,s)}}return l}_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=To._getTextureSourceName(e),i=To._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=To._getExternalTextureUrls(e,o),l=a.shift();return l?To._createExternalTexture(l,a,n,i):null}static _createExternalTexture(e,n,o,s){n.push(...To._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,To._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?To._getMimeType(e):"image/png":void 0;return{buffer:n?new Uint8Array(n):void 0,forcedExtension:e?To._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,"/");To._isSafeRelativeTexturePath(n)&&o.push(t+n);const s=To._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 To._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(To._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 p=new t.MorphTargetManager(o);p.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,m=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=Io(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=Co(u,s,r,i,f,m);if(!c)continue;const h=n.fullWeights&&n.shapes.length>1?`${n.name}_${n.fullWeights[e]}`:n.name,g=new t.MorphTarget(h,null!==(d=a[e])&&void 0!==d?d:0,o);g.setPositions(c.positions),c.normals&&g.setNormals(c.normals),l.push(p.numTargets),p.addTarget(g)}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}))}p.numTargets>0&&(p.numMaxInfluencers=p.numTargets,e.morphTargetManager=p)}}_createCamera(e,n,o){var s,r;const i=n.get(e.modelId),a=i?i.computeWorldMatrix(!0):t.Matrix.Identity(),l=t.Vector3.TransformCoordinates(t.Vector3.Zero(),a),u=new t.FreeCamera(e.name,l,o);if(u.fov=e.fieldOfView*(Math.PI/180),u.fovMode=t.Camera.FOVMODE_VERTICAL_FIXED,u.minZ=e.nearPlane,u.maxZ=e.farPlane,u.metadata=Object.assign(Object.assign({},null!==(s=u.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,fieldOfViewX:e.fieldOfViewX,apertureMode:e.apertureMode,apertureSizeInch:e.apertureSizeInch,userProperties:e.userProperties,unknownProperties:e.unknownProperties,diagnostics:e.diagnostics}}),"orthographic"===e.projectionType&&(u.mode=t.Camera.ORTHOGRAPHIC_CAMERA,u.orthoTop=e.orthographicSize[1]/2,u.orthoBottom=-e.orthographicSize[1]/2,u.orthoRight=e.orthographicSize[0]/2,u.orthoLeft=-e.orthographicSize[0]/2),i&&this._options.attachCamerasAndLights){let n=i;if(a.determinant()<0){const s=new t.TransformNode(`${e.name}__fbx_cameraPivot`,o);s.parent=i,s.scaling.set(1,1,-1),n=s}u.parent=n,u.position.set(0,0,0);const s=(null!==(r=e.roll)&&void 0!==r?r:0)*Math.PI/180;u.rotationQuaternion=t.Quaternion.FromRotationMatrix(t.Matrix.RotationZ(s).multiply(t.Matrix.RotationY(Math.PI/2)))}else{const e=t.Vector3.TransformCoordinates(new t.Vector3(1,0,0),a);u.setTarget(e)}return u}_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;const d=!!r&&this._options.attachCamerasAndLights,h=d?t.Vector3.Zero():a,p=d?new t.Vector3(0,0,-1):u;switch(e.lightType){case 1:c=new t.DirectionalLight(e.name,p,o),c.diffuse=l,c.intensity=e.intensity;break;case 2:{const n=e.coneAngle*(Math.PI/180);c=new t.SpotLight(e.name,h,p,n,2,o),c.diffuse=l,c.intensity=e.intensity,void 0!==e.innerAngle&&(c.innerAngle=Math.min(n,e.innerAngle*Math.PI/180));break}default:c=new t.PointLight(e.name,h,o),c.diffuse=l,c.intensity=e.intensity}return d&&r&&(c.parent=r,c.computeTransformedInformation()),c.specular=l,e.enableFarAttenuation&&void 0!==e.farAttenuationEnd&&e.farAttenuationEnd>0&&(c.range=e.farAttenuationEnd),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,farAttenuationStart:e.farAttenuationStart,farAttenuationEnd:e.farAttenuationEnd,areaLightShape:e.areaLightShape,userProperties:e.userProperties,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=[],d=To._computeBoneInheritScales(n,n.map(e=>e.scale));for(let e=0;e<n.length;e++){const t=n[e],o=To._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]=To._computeFBXRuntimeLocalMatrix(n,o,e,d)}u.push(...To._computeFBXAbsoluteMatrices(n,c));const h=n.map((e,n)=>e.transformLinkMatrix?t.Matrix.FromArray(e.transformLinkMatrix):e.modelBindPoseMatrix?t.Matrix.FromArray(e.modelBindPoseMatrix):u[n]),p=h.map((e,o)=>{const s=n[o].parentIndex;if(s<0)return e;const r=new t.Matrix;return h[s].invertToRef(r),e.multiply(r)}),f=To._shouldUseBindMatricesAsRest(n,l,p),m=To._computeBoneInheritScales(n,n.map(e=>e.scale));for(let e=0;e<n.length;e++){let o=f?p[e]:c[e],u=n[e].parentIndex>=0?i[n[e].parentIndex]:null;if(!f&&1!==n[e].inheritType&&n[e].parentIndex>=0&&u){const i=To._splitParentScaleCompensatedLocalMatrix(l[e],m[n[e].parentIndex],To._getBoneInheritedScale(n,e,m)),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,f?o.clone():null,f?o.clone():null,e);f&&n[e].isCluster&&To._getMaxScaleRatio(l[e],p[e])>=10&&this._bindRestBones.add(d),i.push(d)}if(this._sourceBonesBySkeleton.set(r,i),this._scaleCompensationHelpersBySkeleton.set(r,a),!f){for(let e=0;e<n.length;e++)i[e].updateMatrix(p[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}_isRigBone(e){return this._rigBoneModelIds.has(e)}_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 _computeBoneInheritScales(e,t){const n=[];for(let o=0;o<e.length;o++){const s=t[o],r=To._getBoneInheritScaleNode(e,o);if(r<0||r>=o)n[o]=[s[0],s[1],s[2]];else{const e=n[r];n[o]=[s[0]*e[0],s[1]*e[1],s[2]*e[2]]}}return n}static _getBoneInheritScaleNode(e,t){const n=e[t].parentIndex;return n<0?-1:0===e[t].inheritType?n:2===e[t].inheritType?To._getBoneInheritScaleNode(e,n):-1}static _getBoneInheritedScale(e,t,n){const o=To._getBoneInheritScaleNode(e,t);return o>=0?n[o]:[1,1,1]}static _computeFBXRuntimeLocalMatrix(e,t,n,o){const s=e[n].parentIndex;if(1===e[n].inheritType||s<0)return t;const r=null!=o?o:To._computeBoneInheritScales(e,e.map(e=>e.scale));return To._applyParentScaleCompensation(t,r[s],To._getBoneInheritedScale(e,n,r))}static _applyParentScaleCompensation(e,t,n){const o=To._splitParentScaleCompensatedLocalMatrix(e,t,n);return o.boneLocalMatrix.multiply(o.helperLocalMatrix)}static _splitParentScaleCompensatedLocalMatrix(e,n,o){const s=e.getTranslation();let r=e.clone();return r.setTranslation(t.Vector3.Zero()),!o||1===o[0]&&1===o[1]&&1===o[2]||(r=t.Matrix.Scaling(o[0],o[1],o[2]).multiply(r)),{boneLocalMatrix:r,helperLocalMatrix:t.Matrix.Compose(To._getInverseScaleVector(n),t.Quaternion.Identity(),s)}}static _safeInverseScale(e){return Math.abs(e)>1e-8?1/e:1}static _getInverseScaleVector(e){return new t.Vector3(To._safeInverseScale(e[0]),To._safeInverseScale(e[1]),To._safeInverseScale(e[2]))}static _shouldUseBindMatricesAsRest(e,t,n){return e.some((e,o)=>!!e.isCluster&&To._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(To._getScaleRatio(o.x,i.x),To._getScaleRatio(o.y,i.y),To._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 mo(n,o).multiply(s)}(e,n,o)}static _computeFBXGeometricDeltaMatrix(e,t){return mo(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=po(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,p=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],m=0!==i[0]||0!==i[1]||0!==i[2];if(!p&&!f&&!m){const e=po(r[0]*h,r[1]*h,r[2]*h),i=fo(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 g=t.Matrix.Translation(n[0],n[1],n[2]),_=t.Matrix.Translation(u[0],u[1],u[2]),v=t.Matrix.Translation(a[0],a[1],a[2]),y=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=po(r[0]*h,r[1]*h,r[2]*h),w=fo(o[0]*h,o[1]*h,o[2]*h,d),M=t.Matrix.Scaling(s[0],s[1],s[2]);let S;if(m){const e=po(i[0]*h,i[1]*h,i[2]*h);S=new t.Matrix,e.invertToRef(S)}else S=t.Matrix.Identity();let R=T;return R=R.multiply(M),R=R.multiply(x),R=R.multiply(b),R=R.multiply(y),R=R.multiply(S),R=R.multiply(w),R=R.multiply(A),R=R.multiply(v),R=R.multiply(_),R=R.multiply(g),R}({translation:e,rotation:n,scale:o,preRotation:s,postRotation:r,rotationPivot:i,scalingPivot:a,rotationOffset:l,scalingOffset:u,rotationOrder:c})}_applyRestTRS(e,t){const n=To._computeLocalTRS(t,t.translation,t.rotation,t.scale);this._adjustTRSForInheritMode(t,n,void 0),e.position=n.position,e.rotationQuaternion=n.rotationQuaternion,e.scaling=n.scaling}static _computeFBXModelLocalMatrix(e){return To._computeFBXLocalMatrix(e.translation,e.rotation,e.scale,e.preRotation,e.postRotation,e.rotationPivot,e.scalingPivot,e.rotationOffset,e.scalingOffset,e.rotationOrder)}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,l){var u,c;if(0===e.curveNodes.length&&!e.unsupportedCurveNodes.some(e=>null!==e.targetId&&e.curves.length>0))return null;this._activeLayers=e.layers,this._curveNodesByModelId=new Map;for(const t of e.curveNodes){if("DeformPercent"===t.type)continue;const e=this._curveNodesByModelId.get(t.targetModelId);e?e.push(t):this._curveNodesByModelId.set(t.targetModelId,[t])}const d=new t.AnimationGroup(e.name,s),h=new Map,p=(e,t)=>{var n;const o=null!==(n=t.getTransformNode())&&void 0!==n?n:t;let s=h.get(o);if(s){if(s.has(e.targetProperty))return}else s=new Set,h.set(o,s);s.add(e.targetProperty),d.addTargetedAnimation(e,o)},f=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=f.get(n.modelId);o?o.push(e):f.set(n.modelId,[e])}}const m=new Map,g=new Map,_=[];for(const t of e.curveNodes)"DeformPercent"!==t.type?f.has(t.targetModelId)?(m.has(t.targetModelId)||m.set(t.targetModelId,[]),m.get(t.targetModelId).push(t)):(g.has(t.targetModelId)||g.set(t.targetModelId,[]),g.get(t.targetModelId).push(t)):_.push(t);const v=new Set;for(const t of n){const n=new Set(t.bones.filter(e=>1!==e.inheritType&&e.parentIndex>=0).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))v.add(e);for(const{bone:o,animations:r}of this._buildInheritedRigBoneAnimations(t,s,m,i,n,e.startTime,e.stopTime))for(const e of r)p(e,o)}}for(const[t,n]of Array.from(m)){if(v.has(t))continue;const o=f.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)p(e,t)}}for(const[t,n]of Array.from(g)){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)d.addTargetedAnimation(e,o)}for(const[n,o]of Array.from(this._inheritScaleHelpers)){const s=i.get(n),a=s?this._parentModelById.get(n):void 0;if(!s||!a)continue;const l=this._frameRate,c=[...null!==(u=this._curveNodesByModelId.get(a.id))&&void 0!==u?u:[],...this._collectInheritScaleCurves(a).filter(e=>e.targetModelId!==a.id)];if(c.length>0){const n=Lo(c,l,e.startTime,e.stopTime),s=e=>{var t;return this._computeInheritAwareLocalMatrix(a,this._sampleModelLocalMatrix(a,null!==(t=this._curveNodesByModelId.get(a.id))&&void 0!==t?t:[],e),e)},r=To._refineSampleTimes(n,s),i=[],u=[];let h=null;for(const e of r){const n=new t.Vector3,o=new t.Quaternion,r=new t.Vector3;s(e).decompose(n,o,r),h&&t.Quaternion.Dot(h,o)<0&&o.scaleInPlace(-1),h=o,i.push({frame:e*l,value:r}),u.push({frame:e*l,value:o})}if(!this._isVector3KeysConstant(i)){const e=new t.Animation(`${o.name}_position`,"position",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(i),d.addTargetedAnimation(e,o)}if(!ko(u)){const e=new t.Animation(`${o.name}_rotation`,"rotationQuaternion",l,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(u),d.addTargetedAnimation(e,o)}}const h=this._collectInheritScaleCurves(a),p=r.get(n);if(p&&h.length>0&&!g.has(n)&&!m.has(n))for(const t of this._buildNodeAnimations([],p.name,s,e.startTime,e.stopTime,h))d.addTargetedAnimation(t,p)}const y=new Map;for(const e of _){const t=y.get(e.targetModelId);t?t.push(e):y.set(e.targetModelId,[e])}for(const[n,o]of Array.from(y)){o.sort((e,t)=>e.layerIndex-t.layerIndex);const s=o.filter(e=>e.curves.length>0).map(e=>({layerIndex:e.layerIndex,curves:e.curves}));if(0===s.length)continue;let r=!1;for(const o of a){if(!o.morphTargetManager||r)continue;const i=o.metadata,a=null==i?void 0:i.fbxBlendShapeChannelTargets,l=null==a?void 0:a.get(n);if(l){const n=this._frameRate;for(let r=0;r<l.targetIndices.length;r++){const i=o.morphTargetManager.getTarget(l.targetIndices[r]);if(!i)continue;const a=new t.Animation(`${i.name}_influence`,"influence",n,t.Animation.ANIMATIONTYPE_FLOAT,t.Animation.ANIMATIONLOOPMODE_CYCLE),u=this._layeredScalarKeys(s,e,e=>{var t;return null!==(t=Io(e,l.fullWeights,l.targetIndices.length)[r])&&void 0!==t?t:0});a.setKeys(u),d.addTargetedAnimation(a,i)}r=!0;continue}const u=null==i?void 0:i.fbxBlendShapeChannelIds;if(!u)continue;const c=u.get(n);if(void 0===c)continue;const h=o.morphTargetManager.getTarget(c);if(h){const n=this._frameRate,o=new t.Animation(`${h.name}_influence`,"influence",n,t.Animation.ANIMATIONTYPE_FLOAT,t.Animation.ANIMATIONLOOPMODE_CYCLE);o.setKeys(this._layeredScalarKeys(s,e,e=>e/100)),d.addTargetedAnimation(o,h),r=!0}}}const b=new Map;for(const t of e.unsupportedCurveNodes){if(null===t.targetId||0===t.curves.length)continue;const e=`${t.targetId}|${null!==(c=t.propertyName)&&void 0!==c?c:t.type}`,n=b.get(e);n?n.push(t):b.set(e,[t])}for(const t of Array.from(b.values())){t.sort((e,t)=>e.layerIndex-t.layerIndex);const n=this._buildPropertyAnimations(t,e,r,l);if(n.length>0)for(const e of t)this._evaluatedCurveNodeIds.add(e.id);for(const{animation:e,target:t}of n)d.addTargetedAnimation(e,t)}return d.targetedAnimations.length>0?(d.normalize(e.startTime*this._frameRate,e.stopTime*this._frameRate),d):(d.dispose(),null)}_buildInheritedRigBoneAnimations(e,n,o,s,r,i,a){var l;const u=this._frameRate,c=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)c.add(e.bones[n].modelId);const d=e.bones.filter(e=>c.has(e.modelId)).flatMap(e=>{var t;return null!==(t=o.get(e.modelId))&&void 0!==t?t:[]});let h=Lo(d,u,i,a);if(0===h.length)return[];for(const t of e.bones){const e=s.get(t.modelId),n=null!==(l=o.get(t.modelId))&&void 0!==l?l:[];c.has(t.modelId)&&e&&0!==n.length&&(h=To._refineSampleTimes(h,t=>this._sampleModelLocalMatrix(e,n,t)))}const p=e.bones.map(()=>({posKeys:[],rotKeys:[],sclKeys:[],prevQuat:null})),f=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=To._computeFBXModelLocalMatrix(i),l=new t.Matrix;return a.invertToRef(l),l});for(const i of h){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}),l=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=To._computeBoneInheritScales(e.bones,l),d=i*u;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?c[n]:e.bones[t].scale,s=To._splitParentScaleCompensatedLocalMatrix(a[t],o,To._getBoneInheritedScale(e.bones,t,c));To._pushMatrixKeys(p[t],d,s.boneLocalMatrix),To._pushMatrixKeys(f[t],d,s.helperLocalMatrix)}}const g=[];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:l}=p[o],c=[];if(!this._isVector3KeysConstant(i)){const e=new t.Animation(`${s.name}_position`,"position",u,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(i),c.push(e)}if(!ko(a)){const e=new t.Animation(`${s.name}_rotation`,"rotationQuaternion",u,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(a),c.push(e)}if(!this._isVector3KeysConstant(l)){const e=new t.Animation(`${s.name}_scaling`,"scaling",u,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(l),c.push(e)}c.length>0&&g.push({bone:s,animations:c});const d=this._getScaleCompensationHelper(n,o);if(!d)continue;const h=[],{posKeys:m,rotKeys:_,sclKeys:v}=f[o];if(!this._isVector3KeysConstant(m)){const e=new t.Animation(`${d.name}_position`,"position",u,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(m),h.push(e)}if(!ko(_)){const e=new t.Animation(`${d.name}_rotation`,"rotationQuaternion",u,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(_),h.push(e)}if(!this._isVector3KeysConstant(v)){const e=new t.Animation(`${d.name}_scaling`,"scaling",u,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(v),h.push(e)}h.length>0&&g.push({bone:d,animations:h})}return g}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,i=[]){const a=this._frameRate,l=e.find(e=>"R"===e.type),u=Lo([...e,...i],a,s,r);if(0===u.length)return[];const c=t=>{const n=this._sampleModelTRS(o,e,t),s=To._computeLocalTRS(o,n.translation,n.rotation,n.scale);return this._adjustTRSForInheritMode(o,s,t),s},d=To._refineSampleTimes(u,e=>{const n=c(e);return t.Matrix.Compose(n.scaling,n.rotationQuaternion,n.position)}),h=[],p=[],f=[];let m=null;for(const n of d){const o=n*a,s=c(n),r=s.scaling,i=s.rotationQuaternion,l=s.position,u=Hn(e,"T",n),d=Hn(e,"R",n),g=Hn(e,"S",n);m&&t.Quaternion.Dot(m,i)<0&&i.scaleInPlace(-1),m=i,h.push(u?{frame:o,value:l,interpolation:1}:{frame:o,value:l}),p.push(d?{frame:o,value:i,interpolation:1}:{frame:o,value:i}),f.push(g?{frame:o,value:r,interpolation:1}:{frame:o,value:r})}const g=[];if(!this._isVector3KeysConstant(h)){const e=new t.Animation(`${n}_position`,"position",a,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(h),g.push(e)}if(l){const e=new t.Animation(`${n}_rotation`,"rotationQuaternion",a,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(p),g.push(e)}if(!this._isVector3KeysConstant(f)){const e=new t.Animation(`${n}_scaling`,"scaling",a,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(f),g.push(e)}return g}static _refineSampleTimes(e,n,o=2){const s=e=>{const o=new t.Vector3,s=new t.Quaternion,r=new t.Vector3;return n(e).decompose(o,s,r),{s:o,r:s,t:r}},r=[],i=(e,n,a,l,u)=>{if(u>=o)return;const c=.5*(e+n);if(!(c>e&&c<n))return;const d=s(c),h=t.Vector3.Lerp(a.t,l.t,.5),p=t.Vector3.Lerp(a.s,l.s,.5),f=t.Quaternion.Slerp(a.r,l.r,.5),m=t.Vector3.Distance(h,d.t),g=t.Vector3.Distance(p,d.s),_=Math.min(1,Math.abs(t.Quaternion.Dot(f,d.r))),v=2*Math.acos(_),y=1e-4*(1+Math.max(Math.abs(d.t.x),Math.abs(d.t.y),Math.abs(d.t.z))),b=1e-4*(1+Math.max(Math.abs(d.s.x),Math.abs(d.s.y),Math.abs(d.s.z)));(m>y||g>b||v>5e-4)&&(i(e,c,a,d,u+1),r.push(c),i(c,n,d,l,u+1))};let a=e.length>0?s(e[0]):null;for(let t=0;t<e.length;t++)if(r.push(e[t]),t+1<e.length&&a){const n=s(e[t+1]);i(e[t],e[t+1],a,n,0),a=n}return r}_layeredScalarKeys(e,t,n){const o=this._frameRate;if(0===e.length)return[];if(1===e.length)return Po(e[0].curves[0],o,t.startTime,t.stopTime,n);const s=e[0].curves[0].channel;return Lo(e.map(e=>({type:"other",targetModelId:0,curves:Array.from(e.curves),layerIndex:e.layerIndex})),o,t.startTime,t.stopTime).map(r=>({frame:r*o,value:n(Un(e,t.layers,[s],[0],r)[0])}))}_buildPropertyAnimations(e,n,o,s){var r,i,a,l,u,c,d,h,p,f,m,g;const _=this._frameRate,v=e[0],y=null!==(r=v.propertyName)&&void 0!==r?r:v.type,b=v.targetId,x=[],T=null!==(i=v.curves.find(e=>"d|X"===e.channel))&&void 0!==i?i:v.curves[0],A=v.defaultValues,w=e.length>1,M=e.map(e=>({layerIndex:e.layerIndex,curves:e.curves,defaultValues:e.defaultValues})),S=()=>Lo(e.map(e=>({type:"other",targetModelId:b,curves:e.curves,layerIndex:e.layerIndex})),_,n.startTime,n.stopTime),R=e=>{const t=v.curves.find(e=>"d|X"===e.channel),o=v.curves.find(e=>"d|Y"===e.channel),s=v.curves.find(e=>"d|Z"===e.channel);return S().map(r=>{var i,a,l;return{frame:r*_,values:w?Un(M,n.layers,["d|X","d|Y","d|Z"],e,r):[null!==(i=In(t,r))&&void 0!==i?i:e[0],null!==(a=In(o,r))&&void 0!==a?a:e[1],null!==(l=In(s,r))&&void 0!==l?l:e[2]]}})},C=(e,t=!1)=>{const o=w?S().map(t=>{var o;return{frame:t*_,value:e(Un(M,n.layers,[T.channel],[null!==(o=A[T.channel])&&void 0!==o?o:0],t)[0])}}):Po(T,_,n.startTime,n.stopTime,e);if(t)for(const e of o)e.interpolation=1,delete e.inTangent,delete e.outTangent;return o},I=()=>{var e,n,o;return R([null!==(e=A["d|X"])&&void 0!==e?e:1,null!==(n=A["d|Y"])&&void 0!==n?n:1,null!==(o=A["d|Z"])&&void 0!==o?o:1]).map(({frame:e,values:n})=>({frame:e,value:new t.Color3(n[0],n[1],n[2])}))},O=(e,n,o,s,r)=>{if(0===s.length)return;const i=new t.Animation(`${r}_${n}`,n,_,o,t.Animation.ANIMATIONLOOPMODE_CYCLE);i.setKeys(s),x.push({animation:i,target:e})},F=o.get(b);if(F){if("Visibility"===y&&F instanceof t.Mesh)return O(F,"visibility",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>Math.min(1,Math.max(0,e)),!0),F.name),x;const e=null===(a=F.metadata)||void 0===a?void 0:a.fbxUserProperties;if(e&&y in e)if(v.curves.some(e=>"d|Y"===e.channel||"d|Z"===e.channel)){const n=e[y],o=Array.isArray(n)?n:[0,0,0];e[y]=new t.Vector3(null!==(l=o[0])&&void 0!==l?l:0,null!==(u=o[1])&&void 0!==u?u:0,null!==(c=o[2])&&void 0!==c?c:0);const s=R([null!==(d=o[0])&&void 0!==d?d:0,null!==(h=o[1])&&void 0!==h?h:0,null!==(p=o[2])&&void 0!==p?p:0]).map(({frame:e,values:n})=>({frame:e,value:new t.Vector3(n[0],n[1],n[2])}));O(F,`metadata.fbxUserProperties.${y}`,t.Animation.ANIMATIONTYPE_VECTOR3,s,F.name)}else"boolean"==typeof e[y]&&(e[y]=e[y]?1:0),O(F,`metadata.fbxUserProperties.${y}`,t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e),F.name);return x}const E=s.cameraByAttributeId.get(b);if(E){const e=null===(f=E.metadata)||void 0===f?void 0:f.fbxCamera,n=(null==e?void 0:e.aspectRatio)||1,o=null!==(m=null==e?void 0:e.apertureMode)&&void 0!==m?m:2;switch(y){case"FieldOfView":O(E,"fov",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>1===o?2*Math.atan(Math.tan(e*Math.PI/360)/n):e*Math.PI/180),E.name);break;case"FieldOfViewY":O(E,"fov",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e*Math.PI/180),E.name);break;case"FieldOfViewX":0!==o&&O(E,"fov",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>2*Math.atan(Math.tan(e*Math.PI/360)/n)),E.name);break;case"FocalLength":{const n=null===(g=null==e?void 0:e.apertureSizeInch)||void 0===g?void 0:g[1];n&&3===o&&O(E,"fov",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>2*Math.atan(n/Math.max(e/25.4,1e-6)*.5)),E.name);break}case"NearPlane":O(E,"minZ",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e),E.name);break;case"FarPlane":O(E,"maxZ",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e),E.name)}return x}const N=s.lightByAttributeId.get(b);if(N){switch(y){case"Intensity":O(N,"intensity",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e/100),N.name);break;case"Color":O(N,"diffuse",t.Animation.ANIMATIONTYPE_COLOR3,I(),N.name);break;case"OuterAngle":case"ConeAngle":N instanceof t.SpotLight&&O(N,"angle",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e*Math.PI/180),N.name);break;case"InnerAngle":N instanceof t.SpotLight&&O(N,"innerAngle",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e*Math.PI/180),N.name)}return x}const L=s.materialCache.get(b);if(L){const e=L instanceof t.PBRMaterial,n=y.substring(y.lastIndexOf("|")+1);return"DiffuseColor"===y||"Diffuse"===y||"baseColor"===n||"base_color"===n||"color"===n?O(L,e?"albedoColor":"diffuseColor",t.Animation.ANIMATIONTYPE_COLOR3,I(),L.name):"EmissiveColor"===y||"Emissive"===y||"emissionColor"===n||"emission_color"===n||"emissive"===n||"emit_color"===n?O(L,"emissiveColor",t.Animation.ANIMATIONTYPE_COLOR3,I(),L.name):"Opacity"===y?O(L,"alpha",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e),L.name):"TransparencyFactor"===y||"TransparentFactor"===y?O(L,"alpha",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>1-e),L.name):!e||"roughness"!==n&&"specular_roughness"!==n&&"specularRoughness"!==n?!e||"metalness"!==n&&"metallic"!==n&&"base_metalness"!==n?e||"SpecularColor"!==y||O(L,"specularColor",t.Animation.ANIMATIONTYPE_COLOR3,I(),L.name):O(L,"metallic",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e),L.name):O(L,"roughness",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e),L.name),x}return x}_applyConstraints(e,n,o,s){var r,i,a,l,u;const c=e=>{var t;return void 0===e||null===(t=n.get(e))||void 0===t?void 0:t.name},d=e.upAxisSign>=0?1:-1,h=new t.Vector3(0===e.upAxis?d:0,1===e.upAxis?d:0,2===e.upAxis?d:0),p=[];for(const s of e.constraints){const e=Object.assign({name:s.name,type:s.type,node:c(s.nodeId),targets:s.targets.map(e=>({node:c(e.modelId),weight:e.weight})),weight:s.weight,active:s.active},"singleChainIK"===s.type?{firstJoint:c(s.ikFirstJointId),endJoint:c(s.ikEndJointId),effector:c(s.ikEffectorId)}:{});p.push(e);const u=void 0!==s.nodeId?n.get(s.nodeId):void 0;if(!u)continue;const d=null!==(i=null===(r=u.metadata)||void 0===r?void 0:r.fbxConstraints)&&void 0!==i?i:[];if(u.metadata=Object.assign(Object.assign({},null!==(a=u.metadata)&&void 0!==a?a:{}),{fbxConstraints:[...d,e]}),"apply"!==this._options.constraints||"singleChainIK"===s.type||"unknown"===s.type)continue;const f=[];for(const e of s.targets){const o=n.get(e.modelId);if(!o)continue;const r=Math.PI/180,i="parent"===s.type?t.Matrix.Compose(new t.Vector3(...e.offsetScale),t.Quaternion.FromRotationMatrix(po(e.offsetRotation[0]*r,e.offsetRotation[1]*r,e.offsetRotation[2]*r)),new t.Vector3(...e.offsetTranslation)):t.Matrix.Identity();f.push({node:o,weight:e.weight,offset:i})}if(0===f.length)continue;const m=void 0!==s.worldUpNodeId&&null!==(l=n.get(s.worldUpNodeId))&&void 0!==l?l:null;u.addBehavior(new bo(s,{root:o,targets:f,upNode:m,sceneUp:h}))}p.length>0&&(o.metadata=Object.assign(Object.assign({},null!==(u=o.metadata)&&void 0!==u?u:{}),{fbxConstraints:p}))}_reportDiagnostics(e,t,n){var o,s;const r=[],i=(e,t,n)=>{var o;const s="string"==typeof t?t:null!==(o=null==t?void 0:t.message)&&void 0!==o?o:JSON.stringify(t);r.push({source:e,message:s,objectName:n,details:"string"==typeof t?void 0:t})};for(const t of e.diagnostics)"duplicate-parent"!==t.subType&&i("scene",t,null!==(o=t.objectName)&&void 0!==o?o:t.nodeName);for(const t of e.geometries)for(const e of t.diagnostics)i("geometry",e,t.name);for(const t of e.curves)for(const e of t.diagnostics)i("geometry",e,t.name);for(const t of e.skins){for(const e of t.diagnostics)i("skin",e);for(const e of t.bones)for(const t of e.diagnostics)i("skin",t,e.name)}for(const t of e.rigs)for(const e of t.warnings)i("rig",e);for(const t of e.animations)for(const e of t.diagnostics)"unsupported-curve-node"===e.type&&void 0!==e.curveNodeId&&this._evaluatedCurveNodeIds.has(e.curveNodeId)||i("animation",e,t.name);for(const t of e.cameras)for(const e of t.diagnostics)i("camera",e,t.name);for(const t of e.lights)for(const e of t.diagnostics)i("light",e,t.name);const a=e=>{for(const t of e){for(const e of t.diagnostics)i("model",e,t.name);a(t.children)}};a(e.rootModels),t.metadata=Object.assign(Object.assign({},null!==(s=t.metadata)&&void 0!==s?s:{}),{fbxDiagnostics:r,fbxDisplayLayers:e.displayLayers.map(e=>({name:e.name,show:e.show,freeze:e.freeze,color:e.color})),fbxSelectionSets:e.selectionSets.map(e=>({name:e.name,members:e.members.map(e=>{var t,o;return Object.assign(Object.assign(Object.assign({node:null!==(o=null===(t=n.get(e.modelId))||void 0===t?void 0:t.name)&&void 0!==o?o:String(e.modelId),includeNode:e.includeNode},e.vertices?{vertices:e.vertices}:{}),e.edges?{edges:e.edges}:{}),e.faces?{faces:e.faces}:{})})}))});for(const e of r)this._options.onWarning(e)}_collectInheritScaleCurves(e){var t;const n=[];let o=e;const s=new Set;for(;o&&!s.has(o.id);){s.add(o.id);for(const e of null!==(t=this._curveNodesByModelId.get(o.id))&&void 0!==t?t:[])"S"===e.type&&n.push(e);o=this._getInheritScaleNode(o)}return n}_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}_sampleModelTRS(e,t,n){const o=this._activeLayers;return{translation:$n(t,o,"T",e.translation,e.rotationOrder,n),rotation:$n(t,o,"R",e.rotation,e.rotationOrder,n),scale:$n(t,o,"S",e.scale,e.rotationOrder,n)}}static _computeLocalTRS(e,n,o,s){const r=e=>0!==e[0]||0!==e[1]||0!==e[2],i=Math.PI/180;let a=fo(o[0]*i,o[1]*i,o[2]*i,e.rotationOrder);if(r(e.preRotation)&&(a=a.multiply(po(e.preRotation[0]*i,e.preRotation[1]*i,e.preRotation[2]*i))),r(e.postRotation)){const n=po(e.postRotation[0]*i,e.postRotation[1]*i,e.postRotation[2]*i),o=new t.Matrix;n.invertToRef(o),a=o.multiply(a)}let l=new t.Vector3(n[0],n[1],n[2]);return(r(e.rotationPivot)||r(e.scalingPivot)||r(e.rotationOffset)||r(e.scalingOffset))&&(l=To._computeFBXLocalMatrix(n,o,s,e.preRotation,e.postRotation,e.rotationPivot,e.scalingPivot,e.rotationOffset,e.scalingOffset,e.rotationOrder).getTranslation()),{position:l,rotationQuaternion:t.Quaternion.FromRotationMatrix(a),scaling:new t.Vector3(s[0],s[1],s[2])}}_adjustTRSForInheritMode(e,t,n){const o=this._parentModelById.get(e.id);if(1===e.inheritType||!o)return;const s=this._getInheritScale(o,n);t.position.x*=s[0],t.position.y*=s[1],t.position.z*=s[2];const r=this._getInheritScaleNode(e);if(r){const e=this._getInheritScale(r,n);t.scaling.x*=e[0],t.scaling.y*=e[1],t.scaling.z*=e[2]}}_sampleModelLocalMatrix(e,t,n,o){const s=this._sampleModelTRS(e,t,n);return To._computeFBXLocalMatrix(s.translation,s.rotation,null!=o?o:s.scale,e.preRotation,e.postRotation,e.rotationPivot,e.scalingPivot,e.rotationOffset,e.scalingOffset,e.rotationOrder)}_sampleModelScale(e,t,n){return $n(t,this._activeLayers,"S",e.scale,e.rotationOrder,n)}_getInheritScale(e,t){var n;if(!e)return[1,1,1];const o=void 0===t?e.scale:this._sampleModelScale(e,null!==(n=this._curveNodesByModelId.get(e.id))&&void 0!==n?n:[],t),s=this._getInheritScaleNode(e);if(!s)return[o[0],o[1],o[2]];const r=this._getInheritScale(s,t);return[o[0]*r[0],o[1]*r[1],o[2]*r[2]]}_getInheritScaleNode(e){const t=this._parentModelById.get(e.id);if(t)return 0===e.inheritType?t:2===e.inheritType?this._getInheritScaleNode(t):void 0}_computeInheritAwareLocalMatrix(e,n,o){const s=this._parentModelById.get(e.id);if(1===e.inheritType||!s)return n;const r=new t.Vector3,i=new t.Quaternion,a=new t.Vector3;n.decompose(r,i,a);const l=this._getInheritScale(s,o);a.x*=l[0],a.y*=l[1],a.z*=l[2];const u=this._getInheritScaleNode(e);if(u){const e=this._getInheritScale(u,o);r.x*=e[0],r.y*=e[1],r.z*=e[2]}return t.Matrix.Compose(r,i,a)}_buildBoneAnimations(e,n,o,s,r,i){const a=this._frameRate,l=e.find(e=>"R"===e.type),u=Lo(e,a,s,r);if(0===u.length)return[];const c=To._refineSampleTimes(u,t=>this._sampleModelLocalMatrix(o,e,t)),d=[],h=[],p=[];let f=null,m=null;if(i){const e=To._computeFBXLocalMatrix(o.translation,o.rotation,o.scale,o.preRotation,o.postRotation,o.rotationPivot,o.scalingPivot,o.rotationOffset,o.scalingOffset,o.rotationOrder);m=new t.Matrix,e.invertToRef(m)}for(const n of c){const s=n*a,r=this._sampleModelLocalMatrix(o,e,n),l=m&&i?i.multiply(m).multiply(r):r,u=new t.Vector3,c=new t.Quaternion,g=new t.Vector3;l.decompose(u,c,g),f&&t.Quaternion.Dot(f,c)<0&&c.scaleInPlace(-1),f=c,d.push({frame:s,value:g}),h.push({frame:s,value:c}),p.push({frame:s,value:u})}const g=[];if(!this._isVector3KeysConstant(d)){const e=new t.Animation(`${n}_position`,"position",a,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(d),g.push(e)}if(l){const e=new t.Animation(`${n}_rotation`,"rotationQuaternion",a,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(h),g.push(e)}if(!this._isVector3KeysConstant(p)){const e=new t.Animation(`${n}_scaling`,"scaling",a,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(p),g.push(e)}return g}_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 Ao(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}function wo(e,t,n,o,s,r,i,a,l,u,c,d,h,p,f,m){var g;const _=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],p=Math.hypot(a,l,u),f=Math.hypot(c,d,h);if(p<=1e-8||f<=1e-8)return 0;const m=(a*c+l*d+u*h)/(p*f);return Math.acos(Math.max(-1,Math.min(1,m)))}(u,e,t,n);if(_<=1e-8)return;const v=function(e,t,n,o,s,r,i,a,l,u,c,d){const h=3*e,p=3*e,f=2*e,[m,g,_]=Mo(l[p],l[p+1],l[p+2]),v=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}(m,g,_,t,n,o,s,r,i);return[c?`cp:${c[e]}`:`p:${So(a[h])},${So(a[h+1])},${So(a[h+2])}`,So(m),So(g),So(_),So(u[f]),So(u[f+1]),v,d].join("|")}(e,o,s,r,i,a,l,u,c,d,h,p);let y=f.get(v);y||(y={tx:0,ty:0,tz:0,bx:0,by:0,bz:0},f.set(v,y)),y.tx+=o*_,y.ty+=s*_,y.tz+=r*_,y.bx+=i*_,y.by+=a*_,y.bz+=l*_,null!==(g=m[e])&&void 0!==g||(m[e]=v)}function Mo(e,t,n){const o=Math.hypot(e,t,n);return o>1e-8?[e/o,t/o,n/o]:[0,0,1]}function So(e){const t=Math.round(1e6*e);return Object.is(t,-0)?0:t}function Ro(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 Co(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],p=e.vertices[3*a+2];if(r){const e=t.Vector3.TransformNormal(new t.Vector3(d,h,p),r);d=e.x,h=e.y,p=e.z}if(l[3*o]+=d,l[3*o+1]+=h,l[3*o+2]+=p,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 Io(e,t,n){if(n<=0)return[];if(!t||t.length!==n||1===n)return[Oo(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:Oo(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=Oo((e-s)/i);return o[n-1]=1-a,o[n]=a,o}return o[n-1]=1,o}function Oo(e){return Math.max(0,Math.min(1,e))}const Fo=512,Eo=32,No=1e5;function Lo(e,t,n,o){let s=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;const i=new Set,a=[];for(const t of e)for(const e of t.curves){a.push(e);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 l=o>n?n:s,u=o>n?o:r;i.add(l),i.add(u);const c=Array.from(i).filter(e=>e>=l&&e<=u).sort((e,t)=>e-t),d=e=>{for(const t of a){const n=t.keys;if(0===n.length)continue;if(e<n[0].time){if(t.preExtrapolation&&"constant"!==t.preExtrapolation.mode)return!0;continue}if(e>=n[n.length-1].time){if(t.postExtrapolation&&"constant"!==t.postExtrapolation.mode)return!0;continue}let o=0,s=n.length-1;for(;s-o>1;){const t=o+s>>1;n[t].time<=e?o=t:s=t}if("cubic"===n[o].interpolation)return!0}return!1},h=[],p=Math.floor(u*t)-Math.ceil(l*t)+1,f=Math.max(1,Math.ceil(p/No));for(let e=0;e<c.length;e++){const n=c[e];if(h.push(n),e+1>=c.length)break;const o=c[e+1],s=Math.floor(n*t)+1,r=Math.ceil(o*t)-1,i=r-s+1;if(i<=0)continue;const a=d(n)?Fo:Eo,l=Math.max(f,Math.ceil(i/a));for(let e=s;e<=r;e+=l)h.push(e/t)}const m=h.sort((e,t)=>e-t),g=[];for(const e of m)e<l-1e-9||e>u+1e-9||(0===g.length||e-g[g.length-1]>1e-9)&&g.push(e);return g}function ko(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 Po(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=In(e,d.start))&&void 0!==r?r:0,interpolation:"linear",leftDx:0,leftDy:0,rightDx:0,rightDy:0},frame:d.start*t,value:s(null!==(i=In(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=In(e,d.stop))&&void 0!==a?a:0,interpolation:"linear",leftDx:0,leftDy:0,rightDx:0,rightDy:0},frame:d.stop*t,value:s(null!==(l=In(e,d.stop))&&void 0!==l?l:0)});const p=h.map(e=>({frame:e.frame,value:e.value}));for(let e=0;e<h.length-1;e++){const n=h[e].source,o=p[e+1];if("constant"===n.interpolation){p[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;p[e].outTangent=Bo(null!==(u=n.rightSlope)&&void 0!==u?u:a,s)/t,o.inTangent=Bo(null!==(c=n.nextLeftSlope)&&void 0!==c?c:a,s)/t}return p}function Bo(e,t){return t(e)-t(0)}let Do=!1;function Vo(){Do||(Do=!0,t.RegisterSceneLoaderPlugin(new To))}var Go={__proto__:null,FBXFileLoader:To,RegisterFBXFileLoader:Vo};function $o(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 Uo(){const e=[];onmessage=t=>{const n=t.data;switch(n.id){case"init":importScripts(n.url);break;case"validate":$o(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)}}}Vo();class Ho{static ValidateAsync(e,n,o,s){return"function"==typeof Worker?new Promise((r,i)=>{const a=`${$o}(${Uo})()`,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),Ho._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(()=>$o(e,n,o,s)))}}Ho.Configuration={url:`${t.Tools._DefaultCdnUrl}/gltf_validator.js`},Ho._LastResults=null;var Ko={__proto__:null,GLTFValidation:Ho};const jo="Z2xURg",Wo={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,"+jo)||e.startsWith("data:;base64,"+jo)||e.startsWith("data:application/octet-stream;base64,"+jo)||e.startsWith("data:model/gltf-binary;base64,"+jo)};function qo(e,t,n){try{return Promise.resolve(new Uint8Array(e,t,n))}catch(e){return Promise.reject(e)}}var zo,Xo,Yo;e.GLTFLoaderCoordinateSystemMode=void 0,(zo=e.GLTFLoaderCoordinateSystemMode||(e.GLTFLoaderCoordinateSystemMode={}))[zo.AUTO=0]="AUTO",zo[zo.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED",e.GLTFLoaderAnimationStartMode=void 0,(Xo=e.GLTFLoaderAnimationStartMode||(e.GLTFLoaderAnimationStartMode={}))[Xo.NONE=0]="NONE",Xo[Xo.FIRST=1]="FIRST",Xo[Xo.ALL=2]="ALL",e.GLTFLoaderState=void 0,(Yo=e.GLTFLoaderState||(e.GLTFLoaderState={}))[Yo.LOADING=0]="LOADING",Yo[Yo.READY=1]="READY",Yo[Yo.COMPLETE=2]="COMPLETE";const Qo=e=>Promise.resolve(e);class Zo{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 Jo=new Zo;class es extends Zo{constructor(){super(...arguments),this.extensionOptions={},this.preprocessUrlAsync=Qo}copyFrom(e){var t,n,o,s,r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b,x,T,A,w,M,S,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!==(p=e.loadOnlyMaterials)&&void 0!==p?p:this.loadOnlyMaterials,this.loadSkins=null!==(f=e.loadSkins)&&void 0!==f?f:this.loadSkins,this.loggingEnabled=null!==(m=e.loggingEnabled)&&void 0!==m?m: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!==(g=e.preprocessUrlAsync)&&void 0!==g?g:this.preprocessUrlAsync,this.skipMaterials=null!==(_=e.skipMaterials)&&void 0!==_?_:this.skipMaterials,this.targetFps=null!==(v=e.targetFps)&&void 0!==v?v:this.targetFps,this.transparencyAsCoverage=null!==(y=e.transparencyAsCoverage)&&void 0!==y?y: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!==(w=e.useRangeRequests)&&void 0!==w?w:this.useRangeRequests,this.useSRGBBuffers=null!==(M=e.useSRGBBuffers)&&void 0!==M?M:this.useSRGBBuffers,this.validate=null!==(S=e.validate)&&void 0!==S?S:this.validate,this.dontUseTransmissionHelper=null!==(R=e.dontUseTransmissionHelper)&&void 0!==R?R:this.dontUseTransmissionHelper)}}class ts extends es{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=Wo.name,this.extensions=Wo.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({},Jo),e))}get _isPreprocessUrlAsyncSet(){return this.preprocessUrlAsync!==Qo}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=Qo,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)=>qo(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 Wo.canDirectLoad(e)}directLoad(e,n){if(n.startsWith("base64,"+jo)||n.startsWith(";base64,"+jo)||n.startsWith("application/octet-stream;base64,"+jo)||n.startsWith("model/gltf-binary;base64,"+jo)){const o=t.DecodeBase64UrlToBinary(n);return this._validate(e,new Uint8Array(o,0,o.byteLength)),this._unpackBinaryAsync(new t.DataReader({readAsync:(e,t)=>qo(o,e,t),byteLength:o.byteLength}))}return this._validate(e,n),Promise.resolve({json:this._parseJson(n)})}createPlugin(e){return new ts(e[Wo.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"),Ho.ValidateAsync(n,o,s,t=>this.preprocessUrlAsync(o+t,o).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=ts._parseVersion(t.version);if(!n)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=ts._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(ts._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const o={1:ts._CreateGLTF1Loader,2:ts._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=ts._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){}}ts.IncrementalLoading=!0,ts.HomogeneousCoordinates=!1,ts._logSpaces=" ";let ns=!1;function os(){ns||(ns=!0,t.RegisterSceneLoaderPlugin(new ts))}os();var ss,rs,is,as,ls,us,cs,ds,hs,ps={__proto__:null,GLTFFileLoader:ts,get GLTFLoaderAnimationStartMode(){return e.GLTFLoaderAnimationStartMode},get GLTFLoaderCoordinateSystemMode(){return e.GLTFLoaderCoordinateSystemMode},GLTFLoaderDefaultOptions:Jo,get GLTFLoaderState(){return e.GLTFLoaderState},RegisterGLTFFileLoader:os};!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"}(ss||(ss={})),function(e){e[e.FRAGMENT=35632]="FRAGMENT",e[e.VERTEX=35633]="VERTEX"}(rs||(rs={})),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"}(is||(is={})),function(e){e[e.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",e[e.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",e[e.REPEAT=10497]="REPEAT"}(as||(as={})),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"}(ls||(ls={})),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"}(us||(us={})),function(e){e[e.FRONT=1028]="FRONT",e[e.BACK=1029]="BACK",e[e.FRONT_AND_BACK=1032]="FRONT_AND_BACK"}(cs||(cs={})),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"}(ds||(ds={}));class fs{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 is.FLOAT_MAT2:r.setMatrix2x2(s,t.Matrix.GetAsMatrix2x2(i));break;case is.FLOAT_MAT3:r.setMatrix3x3(s,t.Matrix.GetAsMatrix3x3(i));break;case is.FLOAT_MAT4:r.setMatrix(s,i)}}static SetUniform(e,n,o,s){switch(s){case is.FLOAT:return e.setFloat(n,o),!0;case is.FLOAT_VEC2:return e.setVector2(n,t.Vector2.FromArray(o)),!0;case is.FLOAT_VEC3:return e.setVector3(n,t.Vector3.FromArray(o)),!0;case is.FLOAT_VEC4:return e.setVector4(n,t.Vector4.FromArray(o)),!0;default:return!1}}static GetWrapMode(e){switch(e){case as.CLAMP_TO_EDGE:return t.Texture.CLAMP_ADDRESSMODE;case as.MIRRORED_REPEAT:return t.Texture.MIRROR_ADDRESSMODE;case as.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 ls.LINEAR:case ls.LINEAR_MIPMAP_NEAREST:case ls.LINEAR_MIPMAP_LINEAR:return t.Texture.TRILINEAR_SAMPLINGMODE;case ls.NEAREST:case ls.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 ss.BYTE:return new Int8Array(i,n,o);case ss.UNSIGNED_BYTE:return new Uint8Array(i,n,o);case ss.SHORT:return new Int16Array(i,n,o);case ss.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*fs.GetByteStrideFromType(t);return fs.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(!fs._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};fs._DefaultMaterial=new t.ShaderMaterial("GLTFDefaultMaterial",e,n,o),fs._DefaultMaterial.setColor4("u_emission",new t.Color4(.5,.5,.5,1))}return fs._DefaultMaterial}}fs._DefaultMaterial=null,function(e){e[e.IDENTIFIER=1]="IDENTIFIER",e[e.UNKNOWN=2]="UNKNOWN",e[e.END_OF_INPUT=3]="END_OF_INPUT"}(hs||(hs={}));class ms{constructor(e){this._pos=0,this.currentToken=hs.UNKNOWN,this.currentIdentifier="",this.currentString="",this.isLetterOrDigitPattern=/^[a-zA-Z0-9]+$/,this._toParse=e,this._maxPos=e.length}getNextToken(){if(this.isEnd())return hs.END_OF_INPUT;if(this.currentString=this.read(),this.currentToken=hs.UNKNOWN,"_"===this.currentString||this.isLetterOrDigitPattern.test(this.currentString))for(this.currentToken=hs.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 gs=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],_s=["world","view","projection","worldView","worldViewProjection","mBones"],vs=["translation","rotation","scale"],ys=["position","rotationQuaternion","scaling"],bs=(e,t,n)=>{for(const o in e){const s=e[o];n[t][o]=s}},xs=e=>{if(e)for(let t=0;t<e.length/2;t++)e[2*t+1]=1-e[2*t+1]},Ts=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},As=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},ws=(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=As(a),r=new t.Bone(a.name||"",s,ws(e,n,a.jointName,s),o);return r.id=i,r}}}return null},Ms=(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},Ss=(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},Rs=(e,t)=>{for(let n=0;n<e.jointNames.length;n++)if(e.jointNames[n]===t)return!0;return!1},Cs=(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 p,f;for(const n in h)if(p=e.accessors[h[n]],f=fs.GetBufferFromAccessor(e,p),"NORMAL"===n)o.normals=new Float32Array(f.length),o.normals.set(f);else if("POSITION"===n){if(ts.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),xs(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(p=e.accessors[s.indices],p)f=fs.GetBufferFromAccessor(e,p),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 m=e.scene.getMaterialById(s.material);i.push(null===m?fs.GetDefaultMaterial(e.scene):m),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 p=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(p,l[p],u[p],c[p],d[p],r,r,!0),p++}return r},Is=(e,t,n,o)=>{e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=n),e.scaling&&(e.scaling=o)},Os=(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=Cs(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||Rs(o,i.jointName))continue;const l=As(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=Ss(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=Ss(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=ws(e,n,n.jointNames[r],s),d=!0;break}if(d)break}}const p=As(l);!h&&r.length>0&&(h=Ms(r,u),h&&-1===i.indexOf(h)&&i.push(h)),new t.Bone(l.jointName||"",s,h,p).id=u}const a=s.bones;s.bones=[];for(let t=0;t<n.jointNames.length;t++){const o=Ss(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=Cs(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),Is(e,o,s,r)}else n.translation&&n.rotation&&n.scale&&Is(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];Is(s,t.Vector3.FromArray(e),t.Quaternion.FromArray(o),t.Vector3.FromArray(r))}s.updateCache(!0),n.babylonNode=s}return s},Fs=(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=Os(e,s,t),null!==r&&(r.id=t,r.parent=n)),s.children)for(let t=0;t<s.children.length;t++)Fs(e,s.children[t],r,o)},Es=e=>{let n=e.currentScene;if(n)for(let t=0;t<n.nodes.length;t++)Fs(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++)Fs(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=fs.GetBufferFromAccessor(e,e.accessors[l]),d=fs.GetBufferFromAccessor(e,e.accessors[u]),h=i.target.id;let p=e.scene.getNodeById(h);if(null===p&&(p=e.scene.getNodeByName(h)),null===p){t.Tools.Warn("Creating animation named "+n+". But cannot find node named "+h+" to attach to");continue}const f=p instanceof t.Bone;let m=i.target.path;const g=vs.indexOf(m);-1!==g&&(m=ys[g]);let _=t.Animation.ANIMATIONTYPE_MATRIX;f||("rotationQuaternion"===m?(_=t.Animation.ANIMATIONTYPE_QUATERNION,p.rotationQuaternion=new t.Quaternion):_=t.Animation.ANIMATIONTYPE_VECTOR3);let v=null;const y=[];let b=0,x=!1;f&&s&&s.getKeys().length===c.length&&(v=s,x=!0),x||(e.scene._blockEntityCollection=!!e.assetContainer,v=new t.Animation(n,f?"_matrix":m,1,_,t.Animation.ANIMATIONLOOPMODE_CYCLE),e.scene._blockEntityCollection=!1);for(let e=0;e<c.length;e++){let n;if("rotationQuaternion"===m?(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=p;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"===m?r=n:"rotationQuaternion"===m?i=n:a=n,n=t.Matrix.Compose(a,i,r)}x?s&&(s.getKeys()[e].value=n):y.push({frame:c[e],value:n})}!x&&v&&(v.setKeys(y),p.animations.push(v)),s=v,e.scene.stopAnimation(p),e.scene.beginAnimation(p,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)}},Ns=(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=gs.indexOf(r.semantic);if(-1!==e)return delete n[o],_s[e]}}return e.currentIdentifier},Ls=e=>{for(const t in e.materials)Bs.LoadMaterialAsync(e,t,()=>{},()=>{})};class ks{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&&bs(e.extensions,"extensions",o),e.extensionsUsed&&bs(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&&bs(e.bufferViews,"bufferViews",o),e.accessors&&bs(e.accessors,"accessors",o),e.meshes&&bs(e.meshes,"meshes",o),e.lights&&bs(e.lights,"lights",o),e.cameras&&bs(e.cameras,"cameras",o),e.nodes&&bs(e.nodes,"nodes",o),e.images&&bs(e.images,"images",o),e.textures&&bs(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&&bs(e.programs,"programs",o),e.samplers&&bs(e.samplers,"samplers",o),e.techniques&&bs(e.techniques,"techniques",o),e.materials&&bs(e.materials,"materials",o),e.animations&&bs(e.animations,"animations",o),e.skins&&bs(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===ls.NEAREST_MIPMAP_NEAREST||i.minFilter===ls.NEAREST_MIPMAP_LINEAR||i.minFilter===ls.LINEAR_MIPMAP_NEAREST||i.minFilter===ls.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=fs.GetWrapMode(i.wrapS)),void 0!==i.wrapT&&(h.wrapV=fs.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 p=new ms(u),f=new ms(c),m={},g=[],_=[],v=[];for(const e in i.uniforms){const t=i.uniforms[e],n=i.parameters[t];if(m[e]=n,!n.semantic||n.node||n.source)n.type===is.SAMPLER_2D?v.push(e):g.push(e);else{const t=gs.indexOf(n.semantic);-1!==t?(g.push(_s[t]),delete m[e]):g.push(e)}}for(const e in i.attributes){const t=i.attributes[e],n=i.parameters[t];if(n.semantic){const e=Ts(n);e&&_.push(e)}}for(;!p.isEnd()&&p.getNextToken();){if(p.currentToken!==hs.IDENTIFIER){d+=p.currentString;continue}let e=!1;for(const t in i.attributes){const n=i.attributes[t],o=i.parameters[n];if(p.currentIdentifier===t&&o.semantic){d+=Ts(o),e=!0;break}}e||(d+=Ns(p,i,m))}for(;!f.isEnd()&&f.getNextToken();)f.currentToken===hs.IDENTIFIER?h+=Ns(f,i,m):h+=f.currentString;const y={vertex:a.vertexShader+n,fragment:a.fragmentShader+n},b={attributes:_,uniforms:g,samplers:v,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,y,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===is.SAMPLER_2D?Bs.LoadTextureAsync(e,o.values?u:a.value,c(n),()=>c(null)):a.value&&fs.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===is.FLOAT_MAT2||u===is.FLOAT_MAT3||u===is.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;fs.SetMatrix(t.scene,e,l,i,o.getEffect())}}else fs.SetMatrix(t.scene,e,l,i,o.getEffect());else{const e=a[s.uniforms[i]];if(!e)continue;if(u===is.SAMPLER_2D){const n=t.textures[r.values?e:l.value].babylonTexture;if(null==n)continue;o.getEffect().setTexture(i,n)}else fs.SetUniform(o.getEffect(),i,e,u)}}i(o)})(i,e,s,t,n,o,r)}})(e,x,i,r,m,o),x.sideOrientation=t.Material.CounterClockWiseSideOrientation,l&&l.functions){const e=l.functions;e.cullFace&&e.cullFace[0]!==cs.BACK&&(x.backFaceCulling=!1);const n=e.blendFuncSeparate;n&&(n[0]===ds.SRC_ALPHA&&n[1]===ds.ONE_MINUS_SRC_ALPHA&&n[2]===ds.ONE&&n[3]===ds.ONE?x.alphaMode=t.Constants.ALPHA_COMBINE:n[0]===ds.ONE&&n[1]===ds.ONE&&n[2]===ds.ZERO&&n[3]===ds.ONE?x.alphaMode=t.Constants.ALPHA_ONEONE:n[0]===ds.SRC_ALPHA&&n[1]===ds.ONE&&n[2]===ds.ZERO&&n[3]===ds.ONE?x.alphaMode=t.Constants.ALPHA_ADD:n[0]===ds.ZERO&&n[1]===ds.ONE_MINUS_SRC_COLOR&&n[2]===ds.ONE&&n[3]===ds.ONE?x.alphaMode=t.Constants.ALPHA_SUBTRACT:n[0]===ds.DST_COLOR&&n[1]===ds.ZERO&&n[2]===ds.ONE&&n[3]===ds.ONE?x.alphaMode=t.Constants.ALPHA_MULTIPLY:n[0]===ds.SRC_ALPHA&&n[1]===ds.ONE_MINUS_SRC_COLOR&&n[2]===ds.ONE&&n[3]===ds.ONE&&(x.alphaMode=t.Constants.ALPHA_MAXIMIZED))}}}let Ps=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,Bs.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,()=>{Ls(n),Es(n),!ts.IncrementalLoading&&i&&i(o,s)})}),ts.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,Bs.LoadRuntimeAsync(e,t,n,e=>{Bs.LoadRuntimeExtensionsAsync(e,()=>{this._createNodes(e),this._loadBuffersAsync(e,()=>{this._loadShadersAsync(e,()=>{Ls(e),Es(e),ts.IncrementalLoading||o()})}),ts.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)=>{Bs.LoadShaderStringAsync(e,o,r=>{r instanceof ArrayBuffer||(e.loadedShaderCount++,r&&(t.Effect.ShadersStore[o+(s.type===rs.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)=>{Bs.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++)Fs(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++)Fs(e,t.nodes[n],null)}}};Ps.Extensions={};class Bs{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){Bs._ApplyExtensions(r=>r.loadRuntimeAsync(e,t,n,o,s),()=>{setTimeout(()=>{o&&o(ks.CreateRuntime(t.json,e,n))})})}static LoadRuntimeExtensionsAsync(e,t,n){Bs._ApplyExtensions(o=>o.loadRuntimeExtensionsAsync(e,t,n),()=>{setTimeout(()=>{t()})})}static LoadBufferAsync(e,t,n,o,s){Bs._ApplyExtensions(r=>r.loadBufferAsync(e,t,n,o,s),()=>{ks.LoadBufferAsync(e,t,n,o,s)})}static LoadTextureAsync(e,t,n,o){Bs._LoadTextureBufferAsync(e,t,s=>{s&&Bs._CreateTextureAsync(e,t,s,n,o)},o)}static LoadShaderStringAsync(e,t,n,o){Bs._ApplyExtensions(s=>s.loadShaderStringAsync(e,t,n,o),()=>{ks.LoadShaderStringAsync(e,t,n,o)})}static LoadMaterialAsync(e,t,n,o){Bs._ApplyExtensions(s=>s.loadMaterialAsync(e,t,n,o),()=>{ks.LoadMaterialAsync(e,t,n,o)})}static _LoadTextureBufferAsync(e,t,n,o){Bs._ApplyExtensions(s=>s.loadTextureBufferAsync(e,t,n,o),()=>{ks.LoadTextureBufferAsync(e,t,n,o)})}static _CreateTextureAsync(e,t,n,o,s){Bs._ApplyExtensions(r=>r.createTextureAsync(e,t,n,o,s),()=>{ks.CreateTextureAsync(e,t,n,o)})}static _ApplyExtensions(e,t){for(const t in Ps.Extensions)if(e(Ps.Extensions[t]))return;t()}}let Ds=!1;function Vs(){Ds||(Ds=!0,ts._CreateGLTF1Loader=()=>new Ps)}class Gs extends Bs{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(ks.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(fs.GetBufferFromBufferView(e,i,0,i.byteLength,ss.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=fs.GetBufferFromBufferView(e,r,0,r.byteLength,ss.UNSIGNED_BYTE);return setTimeout(()=>{const e=fs.DecodeBufferToText(i);n(e)}),!0}}let $s=!1;function Us(){$s||($s=!0,Ps.RegisterExtension(new Gs))}Vs(),os(),Us();class Hs extends Bs{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){ks.LoadTextureBufferAsync(e,t,s=>{ks.CreateTextureAsync(e,t,s,e=>n[o]=e)},s)}}let Ks=!1;function js(){Ks||(Ks=!0,Ps.RegisterExtension(new Hs))}js();var Ws={__proto__:null,get EBlendingFunction(){return ds},get EComponentType(){return ss},get ECullingType(){return cs},get EParameterType(){return is},get EShaderType(){return rs},get ETextureFilterType(){return ls},get ETextureFormat(){return us},get ETextureWrapMode(){return as},GLTFBinaryExtension:Gs,GLTFLoader:Ps,GLTFLoaderBase:ks,GLTFLoaderExtension:Bs,GLTFMaterialsCommonExtension:Hs,GLTFUtils:fs,RegisterGLTF1Loader:Vs,RegisterGLTFBinaryExtension:Us,RegisterGLTFMaterialsCommonExtension:js};const qs=new Map,zs=qs;function Xs(e,n,o){Ys(e)&&t.Logger.Warn(`Extension with the name '${e}' already exists`),qs.set(e,{isGLTFExtension:n,factory:o})}function Ys(e){return qs.delete(e)}const Qs=[{regex:new RegExp("^/nodes/\\d+/extensions/")},{regex:new RegExp("^/animations/\\d+/extensions/")},{regex:new RegExp("^/nodes/\\d+/weights")},{regex:new RegExp("^/meshes/\\d+/weights")},{regex:new RegExp("/extensions/KHR_texture_transform/")}];class Zs{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)if("length"===i){if(!o.length)throw o.__array__?new Error(`Path ${e} is invalid - no length accessor`):new Error(`Path ${e} is invalid`);o=o.length,void 0!==n&&(t=n)}else{if(o.__ignoreObjectTree__&&(r=!0),o.__array__)o=o.__array__;else if(o=o[i],!o)throw new Error(`Path ${e} is invalid`);if(o.__passThroughTarget__)r=!0;else if(r){const e=/^\d+$/.test(i)?parseInt(i,10):NaN;if(!isNaN(e)&&"function"==typeof o.get){const t=o;o=Object.assign({},t),o.get=(n,o,...s)=>t.get(n,e,...s),"function"==typeof t.set&&(o.set=(n,o,s,...r)=>t.set(n,o,e,...r)),"function"==typeof t.getTarget&&(o.getTarget=(n,o,...s)=>t.getTarget(n,e,...s))}}else if(void 0===n){if(!Qs.find(t=>t.regex.test(e)))throw new Error(`Path ${e} is invalid`)}else n=null==n?void 0:n[i];o.__target__&&void 0!==n&&(t=n)}return{object:t,info:o}}}function Js(e,n){return{type:"FlowGraphInteger",get:n=>{const o=e(n);return void 0===o?void 0:t.FlowGraphInteger.FromValue(o)},getTarget:n,getPropertyName:[()=>"length"]}}const er={length:Js(e=>e.length,e=>e.map(e=>e._babylonTransformNode)),__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:{__passThroughTarget__:!0,length:Js(e=>{const t=rr(e);return t?t.mtm.numTargets:void 0!==(null==e?void 0:e.mesh)?0:void 0},e=>null==e?void 0:e._babylonTransformNode),__array__:{__target__:!0,type:"number",get:(e,t)=>{const n=rr(e);if(n&&void 0!==t&&t>=0&&t<n.mtm.numTargets)return ir(n.mtm.getTarget(t).influence)},set:(e,t,n)=>{var o;const s="number"==typeof e?e:"number"==typeof(null==e?void 0:e.value)?e.value:e,r=rr(t);if(!(!r||void 0===n||n<0||n>=r.mtm.numTargets))for(const e of r.meshes){const t=null===(o=e.morphTargetManager)||void 0===o?void 0:o.getTarget(n);t&&(t.influence=s)}},getTarget:(e,t)=>{const n=rr(e);return n&&void 0!==t&&t>=0&&t<n.mtm.numTargets?n.mtm.getTarget(t):null==e?void 0:e._babylonTransformNode},getPropertyName:[()=>"influence"]},type:"number[]",get:e=>{const t=rr(e);if(!t)return[];const n=[];for(let e=0;e<t.mtm.numTargets;e++)n.push(ir(t.mtm.getTarget(e).influence));return n},getTarget:e=>null==e?void 0: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},camera:{type:"string",get:e=>void 0!==e.camera?`/cameras/${e.camera}`:"",getTarget:e=>e,isReadOnly:!0},mesh:{type:"string",get:e=>void 0!==e.mesh?`/meshes/${e.mesh}`:"",getTarget:e=>e,isReadOnly:!0},skin:{type:"string",get:e=>void 0!==e.skin?`/skins/${e.skin}`:"",getTarget:e=>e,isReadOnly:!0},parent:{type:"string",get:e=>e.parent&&void 0!==e.parent.index?`/nodes/${e.parent.index}`:"",getTarget:e=>e,isReadOnly:!0},children:{length:Js(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,type:"string",get:e=>"number"==typeof e?`/nodes/${e}`:"",getTarget:()=>({__nodeIndex:!0}),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)}}}}}},tr={length:Js(e=>e.length,e=>e.map(e=>e._babylonAnimationGroup)),__array__:{__target__:!0,type:"string",get:e=>e&&"number"==typeof e.index?`/animations/${e.index}`:"",getTarget:e=>e._babylonAnimationGroup,isReadOnly:!0}},nr={length:Js(e=>e.length,e=>e.map(e=>{var t;return null===(t=e.primitives[0]._instanceData)||void 0===t?void 0:t.babylonSourceMesh})),__array__:{__target__:!0,primitives:{length:Js(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,material:{type:"string",get:e=>void 0!==e.material?`/materials/${e.material}`:"",getTarget:e=>e,isReadOnly:!0}}},weights:{length:Js(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,type:"number",get:e=>e,getTarget:()=>({__weightValue:!0}),isReadOnly:!0}}}};function or(e,t,n,o){const s=sr(e);return o?s[n][o]:s[n]}function sr(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 rr(e){var t,n,o,s;const r=null==e?void 0:e._babylonTransformNode;if(!r)return;const i=function(e){var t;const n=null==e?void 0:e._babylonTransformNode;if(!n)return;if(n.morphTargetManager)return n.morphTargetManager;const o=e._primitiveBabylonMeshes;if(o)for(const e of o){if(null==e?void 0:e.morphTargetManager)return e.morphTargetManager;if(null===(t=null==e?void 0:e.sourceMesh)||void 0===t?void 0:t.morphTargetManager)return e.sourceMesh.morphTargetManager}}(e);if(i&&e._primitiveBabylonMeshes&&e._primitiveBabylonMeshes.length>0)return{mtm:i,meshes:e._primitiveBabylonMeshes};const a=r.getDescendants(!1);for(const e of a){const r=e,i=null!==(t=r.morphTargetManager)&&void 0!==t?t:null===(n=r.sourceMesh)||void 0===n?void 0:n.morphTargetManager;if(!i)continue;const a=[],l=r.parent;if(l)for(const e of l.getChildMeshes(!0))(null!==(o=e.morphTargetManager)&&void 0!==o?o:null===(s=e.sourceMesh)||void 0===s?void 0:s.morphTargetManager)===i&&a.push(e);return 0===a.length&&a.push(r),{mtm:i,meshes:a}}}function ir(e){return Number.isFinite(e)?parseFloat(e.toPrecision(7)):e}function ar(e,t,n){if(!e)return;let o=e.extensions;if(!o){if(!n)return;o={},e.extensions=o}let s=o[t.extensionKey];if(!s){if(!n)return;s={},o[t.extensionKey]=s}for(const e of t.texturePath){let t=s[e];if(!t){if(!n)return;t={},s[e]=t}s=t}if(!s.extensions){if(!n)return;s.extensions={}}let r=s.extensions.KHR_texture_transform;if(!r){if(!n)return;r={},s.extensions.KHR_texture_transform=r}return r}function lr(e,n,o){return{offset:{componentsCount:2,type:"Vector2",get:(s,r,i)=>{var a,l;const u=or(s,0,e,n);if(u)return new t.Vector2(u.uOffset,u.vOffset);if(o){const e=ar(s,o,!1),n=null==e?void 0:e.offset;return new t.Vector2(null!==(a=null==n?void 0:n[0])&&void 0!==a?a:0,null!==(l=null==n?void 0:n[1])&&void 0!==l?l:0)}return new t.Vector2(0,0)},getTarget:sr,set:(t,s,r,i)=>{const a=or(s,0,e,n);if(a&&(a.uOffset=t.x,a.vOffset=t.y),o){const e=ar(s,o,!0);e&&(e.offset=[t.x,t.y])}},getPropertyName:[()=>`${e}${n?"."+n:""}.uOffset`,()=>`${e}${n?"."+n:""}.vOffset`]},rotation:{type:"number",get:(t,s,r)=>{var i;const a=or(t,0,e,n);if(a)return a.wAng;if(o){const e=ar(t,o,!1);return null!==(i=null==e?void 0:e.rotation)&&void 0!==i?i:0}return 0},getTarget:sr,set:(t,s,r,i)=>{const a=or(s,0,e,n);if(a&&(a.wAng=t),o){const e=ar(s,o,!0);e&&(e.rotation=t)}},getPropertyName:[()=>`${e}${n?"."+n:""}.wAng`]},scale:{componentsCount:2,type:"Vector2",get:(s,r,i)=>{var a,l;const u=or(s,0,e,n);if(u)return new t.Vector2(u.uScale,u.vScale);if(o){const e=ar(s,o,!1),n=null==e?void 0:e.scale;return new t.Vector2(null!==(a=null==n?void 0:n[0])&&void 0!==a?a:1,null!==(l=null==n?void 0:n[1])&&void 0!==l?l:1)}return new t.Vector2(1,1)},getTarget:sr,set:(t,s,r,i)=>{const a=or(s,0,e,n);if(a&&(a.uScale=t.x,a.vScale=t.y),o){const e=ar(s,o,!0);e&&(e.scale=[t.x,t.y])}},getPropertyName:[()=>`${e}${n?"."+n:""}.uScale`,()=>`${e}${n?"."+n:""}.vScale`]}}}const ur={scene:{__target__:!0,type:"number",get:e=>null!=e?e:0,getTarget:()=>({__gltfRoot:!0}),isReadOnly:!0,getPropertyName:[()=>"scene"]},cameras:{length:Js(e=>e.length,e=>e.map(e=>e._babylonCamera)),__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:er,materials:{length:Js(e=>e.length,e=>e.map(e=>{var n,o;return null===(o=null===(n=e._data)||void 0===n?void 0:n[t.Constants.MATERIAL_TriangleFillMode])||void 0===o?void 0:o.babylonMaterial})),__array__:{__target__:!0,doubleSided:{type:"boolean",get:(e,t,n)=>{var o;return!(null===(o=sr(e,0,n))||void 0===o?void 0:o.backFaceCulling)},set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.backFaceCulling=!e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"backFaceCulling"]},alphaCutoff:{type:"number",get:(e,t,n)=>{var o;return null===(o=sr(e,0,n))||void 0===o?void 0:o.alphaCutOff},set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.alphaCutOff=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"alphaCutOff"]},emissiveFactor:{type:"Color3",get:(e,t,n)=>sr(e,0,n).emissiveColor,set:(e,t,n,o)=>sr(t,0,o).emissiveColor.copyFrom(e),getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"emissiveColor"]},emissiveTexture:{extensions:{KHR_texture_transform:lr("emissiveTexture")}},normalTexture:{scale:{type:"number",get:(e,t,n)=>{var o;return null===(o=or(e,0,"bumpTexture"))||void 0===o?void 0:o.level},set:(e,t,n,o)=>{const s=or(t,0,"bumpTexture");s&&(s.level=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"level"]},extensions:{KHR_texture_transform:lr("bumpTexture")}},occlusionTexture:{strength:{type:"number",get:(e,t,n)=>sr(e,0,n).ambientTextureStrength,set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.ambientTextureStrength=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"ambientTextureStrength"]},extensions:{KHR_texture_transform:lr("ambientTexture")}},pbrMetallicRoughness:{baseColorFactor:{type:"Color4",get:(e,n,o)=>{const s=sr(e,0,o);return t.Color4.FromColor3(s.albedoColor,s.alpha)},set:(e,t,n,o)=>{const s=sr(t,0,o);s.albedoColor.set(e.r,e.g,e.b),s.alpha=e.a},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"albedoColor",()=>"alpha"]},baseColorTexture:{extensions:{KHR_texture_transform:lr("albedoTexture")}},metallicFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).metallic,set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.metallic=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"metallic"]},roughnessFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).roughness,set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.roughness=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"roughness"]},metallicRoughnessTexture:{extensions:{KHR_texture_transform:lr("metallicTexture")}}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:{type:"number",get:(e,t,n)=>{var o,s;return null===(s=null===(o=sr(e,0,n))||void 0===o?void 0:o.anisotropy)||void 0===s?void 0:s.intensity},set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.anisotropy.intensity=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"anisotropy.intensity"]},anisotropyRotation:{type:"number",get:(e,t,n)=>{var o,s;return null===(s=null===(o=sr(e,0,n))||void 0===o?void 0:o.anisotropy)||void 0===s?void 0:s.angle},set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.anisotropy.angle=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"anisotropy.angle"]},anisotropyTexture:{extensions:{KHR_texture_transform:lr("anisotropy","texture")}}},KHR_materials_clearcoat:{clearcoatFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).clearCoat.intensity,set:(e,t,n,o)=>{sr(t,0,o).clearCoat.intensity=e},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"clearCoat.intensity"]},clearcoatRoughnessFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).clearCoat.roughness,set:(e,t,n,o)=>{sr(t,0,o).clearCoat.roughness=e},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"clearCoat.roughness"]},clearcoatTexture:{extensions:{KHR_texture_transform:lr("clearCoat","texture")}},clearcoatNormalTexture:{scale:{type:"number",get:(e,t,n)=>{var o;return null===(o=sr(e,0,n).clearCoat.bumpTexture)||void 0===o?void 0:o.level},getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).clearCoat.bumpTexture.level=e},extensions:{KHR_texture_transform:lr("clearCoat","bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:lr("clearCoat","textureRoughness")}}},KHR_materials_dispersion:{dispersion:{type:"number",get:(e,t,n)=>sr(e,0,n).subSurface.dispersion,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).subSurface.dispersion=e}},KHR_materials_emissive_strength:{emissiveStrength:{type:"number",get:(e,t,n)=>sr(e,0,n).emissiveIntensity,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).emissiveIntensity=e}},KHR_materials_ior:{ior:{type:"number",get:(e,t,n)=>sr(e,0,n).indexOfRefraction,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).indexOfRefraction=e}},KHR_materials_iridescence:{iridescenceFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).iridescence.intensity,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).iridescence.intensity=e},iridescenceIor:{type:"number",get:(e,t,n)=>sr(e,0,n).iridescence.indexOfRefraction,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).iridescence.indexOfRefraction=e},iridescenceTexture:{extensions:{KHR_texture_transform:lr("iridescence","texture")}},iridescenceThicknessMaximum:{type:"number",get:(e,t,n)=>sr(e,0,n).iridescence.maximumThickness,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).iridescence.maximumThickness=e},iridescenceThicknessMinimum:{type:"number",get:(e,t,n)=>sr(e,0,n).iridescence.minimumThickness,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).iridescence.minimumThickness=e},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:lr("iridescence","thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:{type:"Color3",get:(e,t,n)=>sr(e,0,n).sheen.color,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).sheen.color.copyFrom(e)},sheenColorTexture:{extensions:{KHR_texture_transform:lr("sheen","texture")}},sheenRoughnessFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).sheen.intensity,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).sheen.intensity=e},sheenRoughnessTexture:{extensions:{KHR_texture_transform:lr("sheen","textureRoughness")}}},KHR_materials_specular:{specularFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).metallicF0Factor,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).metallicF0Factor=e,getPropertyName:[()=>"metallicF0Factor"]},specularColorFactor:{type:"Color3",get:(e,t,n)=>sr(e,0,n).metallicReflectanceColor,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).metallicReflectanceColor.copyFrom(e),getPropertyName:[()=>"metallicReflectanceColor"]},specularTexture:{extensions:{KHR_texture_transform:lr("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:lr("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).subSurface.refractionIntensity,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).subSurface.refractionIntensity=e,getPropertyName:[()=>"subSurface.refractionIntensity"]},transmissionTexture:{extensions:{KHR_texture_transform:lr("subSurface","refractionIntensityTexture",{extensionKey:"KHR_materials_transmission",texturePath:["transmissionTexture"]})}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).subSurface.translucencyIntensity,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).subSurface.translucencyIntensity=e},diffuseTransmissionTexture:{extensions:{KHR_texture_transform:lr("subSurface","translucencyIntensityTexture",{extensionKey:"KHR_materials_diffuse_transmission",texturePath:["diffuseTransmissionTexture"]})}},diffuseTransmissionColorFactor:{type:"Color3",get:(e,t,n)=>sr(e,0,n).subSurface.translucencyColor,getTarget:sr,set:(e,t,n,o)=>{var s;return e&&(null===(s=sr(t,0,o).subSurface.translucencyColor)||void 0===s?void 0:s.copyFrom(e))}},diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:lr("subSurface","translucencyColorTexture",{extensionKey:"KHR_materials_diffuse_transmission",texturePath:["diffuseTransmissionColorTexture"]})}}},KHR_materials_volume:{attenuationColor:{type:"Color3",get:(e,t,n)=>sr(e,0,n).subSurface.tintColor,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).subSurface.tintColor.copyFrom(e)},attenuationDistance:{type:"number",get:(e,t,n)=>sr(e,0,n).subSurface.tintColorAtDistance,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).subSurface.tintColorAtDistance=e},thicknessFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).subSurface.maximumThickness,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).subSurface.maximumThickness=e},thicknessTexture:{extensions:{KHR_texture_transform:lr("subSurface","thicknessTexture",{extensionKey:"KHR_materials_volume",texturePath:["thicknessTexture"]})}}}}}},extensions:{KHR_lights_punctual:{lights:{length:Js(e=>e.length,e=>e.map(e=>e._babylonLight)),__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:Js(e=>e.length,e=>e.map(e=>e._babylonLight)),__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:Js(e=>e.length,e=>e.map(e=>e._babylonLight))}},EXT_lights_image_based:{lights:{length:Js(e=>e.length,e=>e.map(e=>e._babylonTexture)),__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:tr,meshes:nr,scenes:{length:Js(e=>e.length,e=>e),__array__:{__target__:!0,nodes:{length:Js(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,type:"string",get:e=>"number"==typeof e?`/nodes/${e}`:"",getTarget:()=>({__nodeIndex:!0}),isReadOnly:!0}}}},skins:{length:Js(e=>e.length,e=>e.map(e=>{var t;return null===(t=e._data)||void 0===t?void 0:t.babylonSkeleton})),__array__:{__target__:!0,joints:{length:Js(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,type:"string",get:e=>"number"==typeof e?`/nodes/${e}`:"",getTarget:()=>({__nodeIndex:!0}),isReadOnly:!0}},skeleton:{type:"string",get:e=>{const t=e.skeleton;return"number"==typeof t?`/nodes/${t}`:""},getTarget:e=>e,isReadOnly:!0}}}};function cr(e){if(Array.isArray(e))return e.map(e=>cr(e));if(null!==e&&"object"==typeof e){const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return e;const n={};for(const[t,o]of Object.entries(e))n[t]=cr(o);return n}return e}function dr(e,t){if(!t)return new Zs(e,ur);const n=cr(ur);return t(n),new Zs(e,n)}function hr(e){const t=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let n=ur;for(const e of t)e&&(n=n[e]);if(n&&n.type&&n.get)return n}function pr(e,t){const n=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let o=ur;for(const e of n)e&&(o=o[e]);o&&o.type&&o.get&&(o.interpolation=t)}function fr(e,t,n=ur){const o=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let s=n;for(const e of o)if(e){if(!s[e]){if("?"===e){s.__ignoreObjectTree__=!0;continue}s[e]={},"__array__"===e&&(s[e].__target__=!0)}s=s[e]}Object.assign(s,t)}const mr=new t.Lazy(()=>Promise.resolve(BABYLON)),gr=new t.Lazy(()=>Promise.resolve().then(function(){return Fr}));class _r{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 vr(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 yr{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){Xs(e,!1,t)}static UnregisterExtension(e){return Ys(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}${t.RandomGUID()}/`,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 Nr})]).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 kr})]).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=_r.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(()=>b(this,void 0,void 0,function*(){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 yield this._extensionsOnReadyAsync(),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(_r.Assign(this._gltf.accessors),_r.Assign(this._gltf.animations),_r.Assign(this._gltf.buffers),_r.Assign(this._gltf.bufferViews),_r.Assign(this._gltf.cameras),_r.Assign(this._gltf.images),_r.Assign(this._gltf.materials),_r.Assign(this._gltf.meshes),_r.Assign(this._gltf.nodes),_r.Assign(this._gltf.samplers),_r.Assign(this._gltf.scenes),_r.Assign(this._gltf.skins),_r.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(zs.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],yr._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=_r.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(yr.AddPointerMetadata(t,e),yr._LoadTransform(n,t),null!=n.camera){const o=_r.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=_r.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=_r.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=_r.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=_r.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=_r.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&&_r.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=yr._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=_r.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 yr.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=_r.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=_r.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=vr(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=_r.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=_r.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=_r.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=_r.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=_r.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 yr.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)||mr.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;_r.Assign(t.channels),_r.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=_r.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?gr.value.then(({RegisterGLTFLoaderAnimation:r})=>{var l,u,c,d;let h;switch(r(),a){case"translation":h=null===(l=hr("/nodes/{}/translation"))||void 0===l?void 0:l.interpolation;break;case"rotation":h=null===(u=hr("/nodes/{}/rotation"))||void 0===u?void 0:u.interpolation;break;case"scale":h=null===(c=hr("/nodes/{}/scale"))||void 0===c?void 0:c.interpolation;break;case"weights":h=null===(d=hr("/nodes/{}/weights"))||void 0===d?void 0:d.interpolation;break;default:throw new Error(`${e}/target/path: Invalid value (${o.target.path})`)}if(!h)throw new Error(`${e}/target/path: Could not find interpolation properties for target path (${o.target.path})`);const p={object:i,info:h};return this._loadAnimationChannelFromTargetInfoAsync(e,t,n,o,p,s)}):Promise.resolve()}_loadAnimationChannelFromTargetInfoAsync(e,t,n,o,s,r){const i=this.parent.targetFps,a=1/i,l=_r.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 p=0;switch(e.interpolation){case"STEP":for(let e=0;e<c.length;e++){const t=s.getValue(l,d,p,1);p+=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,p,a);p+=u;const n=s.getValue(l,d,p,1);p+=u;const o=s.getValue(l,d,p,a);p+=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,p,1);p+=u,h[e]={frame:c[e]*i,value:t}}}if(p>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=_r.Get(`${e}/input`,this._gltf.accessors,t.input),s=_r.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=_r.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=yr._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=_r.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 yr._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=_r.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,i.indices.bufferView),c=_r.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=yr._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=yr._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=yr._GetTypedArray(`${e}/sparse/values`,n.componentType,u,i.values.byteOffset,d);let p=0;for(let e=0;e<c.length;e++){let t=c[e]*s;for(let e=0;e<s;e++)l[t++]=h[p++]}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=yr._GetTypedArrayConstructor(`${e}/componentType`,t.componentType);t._data=this._loadAccessorAsync(e,t,n)}else{const n=_r.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${n.index}`,n).then(n=>yr._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=_r.Get(`${e}/bufferView`,this._gltf.bufferViews,n.bufferView);n._babylonVertexBuffer[o]=this._loadVertexBufferViewAsync(s).then(i=>{const a=yr._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,yr.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.then(e=>{var n;const o=null===(n=this._gltf.textures)||void 0===n?void 0:n[t.index];return o&&this._trackTexture(o,e),e});if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const s=_r.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,yr.AddPointerMetadata(o,e),this._parent.onTextureLoadedObservable.notifyObservers(o),n(o)});return this.logClose(),r}_loadTextureAsync(e,t,n=()=>{}){const o=e=>{this._trackTexture(t,e),n(e)},s=this._extensionsLoadTextureAsync(e,t,o);if(s)return s;this.logOpen(`${e} ${t.name||""}`);const r=null==t.sampler?yr.DefaultSampler:_r.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),i=_r.Get(`${e}/source`,this._gltf.images,t.source),a=this._createTextureAsync(e,r,i,o,void 0,!t._textureInfo.nonColorData,t);return this.logClose(),a}_trackTexture(e,t,n,o){var s,r;e._babylonTextures||(e._babylonTextures=[]),e._babylonTextures.includes(t)||e._babylonTextures.push(t),e._babylonTextureSources||(e._babylonTextureSources=[]);const i=e._babylonTextureSources.find(e=>e.babylonTexture===t),a=e._babylonTextureSources[e._babylonTextureSources.length-1],l=null!==(s=null!=n?n:null==i?void 0:i.imageIndex)&&void 0!==s?s:null==a?void 0:a.imageIndex;void 0!==l&&(i?(i.imageIndex=l,i.samplerIndex=null!==(r=null!=o?o:i.samplerIndex)&&void 0!==r?r:null==a?void 0:a.samplerIndex):e._babylonTextureSources.push({babylonTexture:t,imageIndex:l,samplerIndex:null!=o?o:null==a?void 0:a.samplerIndex}))}_createTextureAsync(e,n,o,s=()=>{},r,i,a){var l,u;const c=this._loadSampler(`/samplers/${n.index}`,n),d=new Array,h=new t.Deferred;this._babylonScene._blockEntityCollection=!!this._assetContainer;const p={noMipmap:c.noMipMaps,invertY:!1,samplingMode:c.samplingMode,onLoad:()=>{this._disposed||h.resolve()},onError:(t,n)=>{this._disposed||h.reject(new Error(`${e}: ${n&&n.message?n.message:t||"Failed to load texture"}`))},mimeType:null!==(l=o.mimeType)&&void 0!==l?l:t.GetMimeType(null!==(u=o.uri)&&void 0!==u?u:""),loaderOptions:r,useSRGBBuffer:!!i&&this._parent.useSRGBBuffers},f=new t.Texture(null,this._babylonScene,p);a&&this._trackTexture(a,f,o.index,n.index>=0?n.index:void 0),f._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,d.push(h.promise);const m=o.uri&&!t.IsBase64DataUrl(o.uri)?o.uri:void 0,g=null!=m?m:`${this._fileName}#image${o.index}`;if(d.push(this.loadImageAsync(`/images/${o.index}`,o).then(e=>{const t=`data:${this._uniqueRootUrl}${g}`;f.updateURL(t,e);const n=f.getInternalTexture();n&&(n.label=o.name)})),f.wrapU=c.wrapU,f.wrapV=c.wrapV,s(f),this._parent.useGltfTextureNames){const e=o.name||m||`image${o.index}`;f.name=e}return Promise.all(d).then(()=>f)}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:yr._GetTextureSamplingMode(e,t),wrapU:yr._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:yr._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=_r.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){var s;const r=this._extensionsLoadUriAsync(e,n,o);if(r)return r;if(!this._parent._isPreprocessUrlAsyncSet&&!yr._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,null!==(s=this._rootUrl)&&void 0!==s?s:void 0).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=yr._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())}_extensionsOnReadyAsync(){return b(this,void 0,void 0,function*(){for(const e of this._extensions)e.enabled&&e.onReady&&(yield 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)}}yr.DefaultSampler={index:-1};let br=!1;function xr(){br||(br=!0,ts._CreateGLTF2Loader=e=>new yr(e))}var Tr={__proto__:null,ArrayItem:_r,GLTFFileLoader:ts,GLTFLoader:yr,LoadBoundingInfoFromPositionAccessor:vr,RegisterGLTF2Loader:xr};function Ar(e,n,o,s){return t.Vector3.FromArray(n,o).scaleInPlace(s)}function wr(e,n,o,s){return t.Quaternion.FromArray(n,o).scaleInPlace(s)}function Mr(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}xr(),os();class Sr{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 Rr extends Sr{buildAnimations(e,t,n,o){const s=[];return s.push({babylonAnimatable:e._babylonTransformNode,babylonAnimation:this._buildAnimation(t,n,o)}),s}}class Cr extends Sr{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}}let Ir=!1;function Or(){Ir||(Ir=!0,pr("/nodes/{}/translation",[new Rr(t.Animation.ANIMATIONTYPE_VECTOR3,"position",Ar,()=>3)]),pr("/nodes/{}/rotation",[new Rr(t.Animation.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",wr,()=>4)]),pr("/nodes/{}/scale",[new Rr(t.Animation.ANIMATIONTYPE_VECTOR3,"scaling",Ar,()=>3)]),pr("/nodes/{}/weights",[new Cr(t.Animation.ANIMATIONTYPE_FLOAT,"influence",Mr,e=>e._numMorphTargets)]))}var Fr={__proto__:null,AnimationPropertyInfo:Sr,RegisterGLTFLoaderAnimation:Or,TransformNodeAnimationPropertyInfo:Rr,WeightAnimationPropertyInfo:Cr,getQuaternion:wr,getVector3:Ar,getWeights:Mr};Or();class Er{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,p,f,m,g;const _=this._material.coatWeight,v=this._material.coatWeightTexture,y=this._material.coatColor.clone(),b=this._material.coatColorTexture,x=this._material.geometryCoatNormalTexture,T=new t.Color4(_,_,_,_),A=new t.Color4(n,n,n,n);this.coatWeightTexture=null,this.coatWeight=1;const w=yield Promise.allSettled([t.LerpTexturesAsync("lerpExistingCoat",t.CreateTextureWithFactorOperand(null,new t.Color4(1,1,1,1)),t.CreateTextureWithFactorOperand(b,y.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.SRGB),t.CreateTextureWithFactorOperand(v,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)]),M=w.find(e=>"rejected"===e.status);if(M){for(const e of w)"fulfilled"===e.status&&(null===(l=e.value.texture)||void 0===l||l.dispose());throw M.reason}const[S,R]=w.map(e=>e.value);if(e._disposed)return null===(u=S.texture)||void 0===u||u.dispose(),void(null===(c=R.texture)||void 0===c||c.dispose());const C=yield t.MultiplyTexturesAsync("newCoatColor ("+this._material.name+")",S,R,this._material.getScene(),t.TextureColorSpace.SRGB);if(e._disposed)return void(null===(d=C.texture)||void 0===d||d.dispose());C.texture?(this.coatColorTexture=C.texture,this.coatColor=t.Color3.White()):C.factor&&(this.coatColorTexture=null,this.coatColor.fromArray([C.factor.r,C.factor.g,C.factor.b]));const I=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(v,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(h=I.texture)||void 0===h||h.dispose());this.coatIor=I.factor?I.factor.r:this.coatIor;const O=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(v,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(p=O.texture)||void 0===p||p.dispose());this.coatRoughness=O.factor?O.factor.r:1,this.coatRoughnessTexture=O.texture;const F=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(v,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)null===(f=F.texture)||void 0===f||f.dispose();else{if(this.coatDarkening=F.factor?F.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===(m=n.texture)||void 0===m||m.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(v,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(g=n.texture)||void 0===g||g.dispose());n.texture&&(this.geometryCoatNormalTexture=n.texture)}}})}}var Nr={__proto__:null,OpenPBRMaterialLoadingAdapter:Er};class Lr{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 kr={__proto__:null,PBRMaterialLoadingAdapter:Lr};const Pr="EXT_lights_image_based";class Br{constructor(e){this.name=Pr,this._loader=e,this.enabled=this._loader.isExtensionUsed(Pr)}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 yr.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=_r.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=_r.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)}}let Dr=!1;function Vr(){Dr||(Dr=!0,Ys(Pr),Xs(Pr,!0,e=>new Br(e)))}var Gr={__proto__:null,EXT_lights_image_based:Br,RegisterEXT_lights_image_based:Vr};Vr();const $r="EXT_mesh_gpu_instancing";class Ur{constructor(e){this.name=$r,this._loader=e,this.enabled=this._loader.isExtensionUsed($r)}dispose(){this._loader=null}loadNodeAsync(e,n,o){return yr.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=_r.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}))}))}}let Hr=!1;function Kr(){Hr||(Hr=!0,Ys($r),Xs($r,!0,e=>new Ur(e)))}var jr={__proto__:null,EXT_mesh_gpu_instancing:Ur,RegisterEXT_mesh_gpu_instancing:Kr};Kr();const Wr="EXT_meshopt_compression";class qr{constructor(e){this.name=Wr,this.enabled=e.isExtensionUsed(Wr),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,n){return yr.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=_r.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}))}}let zr=!1;function Xr(){zr||(zr=!0,Ys(Wr),Xs(Wr,!0,e=>new qr(e)))}var Yr={__proto__:null,EXT_meshopt_compression:qr,RegisterEXT_meshopt_compression:Xr};Xr();const Qr="EXT_texture_webp";class Zr{constructor(e){this.name=Qr,this._loader=e,this.enabled=e.isExtensionUsed(Qr)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?yr.DefaultSampler:_r.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=_r.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,t)}))}}let Jr=!1;function ei(){Jr||(Jr=!0,Ys(Qr),Xs(Qr,!0,e=>new Zr(e)))}var ti={__proto__:null,EXT_texture_webp:Zr,RegisterEXT_texture_webp:ei};ei();const ni="EXT_texture_avif";class oi{constructor(e){this.name=ni,this._loader=e,this.enabled=e.isExtensionUsed(ni)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?yr.DefaultSampler:_r.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=_r.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,t)}))}}let si=!1;function ri(){si||(si=!0,Ys(ni),Xs(ni,!0,e=>new oi(e)))}var ii={__proto__:null,EXT_texture_avif:oi,RegisterEXT_texture_avif:ri};ri();const ai="EXT_lights_ies";class li{constructor(e){this.name=ai,this._loader=e,this.enabled=this._loader.isExtensionUsed(ai)}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,_r.Assign(this._lights)}}loadNodeAsync(e,n,o){return yr.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=_r.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),yr.AddPointerMetadata(i,s),o(e)});let u;if(a.uri)u=yield this._loader.loadUriAsync(e,a,a.uri);else{const t=_r.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,a.bufferView);u=yield this._loader.loadBufferViewAsync(`/bufferViews/${t.index}`,t)}return i.iesProfileTexture=new t.Texture(i.name+"_iesProfile",this._loader.babylonScene,!0,!1,void 0,null,null,u,!0,void 0,void 0,void 0,void 0,".ies"),l}))}}let ui=!1;function ci(){ui||(ui=!0,Ys(ai),Xs(ai,!0,e=>new li(e)))}var di={__proto__:null,EXT_lights_ies:li,RegisterEXT_lights_ies:ci};ci();const hi="KHR_draco_mesh_compression";class pi{constructor(e){this.name=hi,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=t.DracoDecoder.DefaultAvailable&&this._loader.isExtensionUsed(hi)}dispose(){delete this.dracoDecoder,this._loader=null}_loadVertexDataAsync(e,n,o){return yr.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=_r.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=_r.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=_r.TryGet(this._loader.gltf.accessors,n.attributes.POSITION),u=this._loader.parent.alwaysComputeBoundingBox||o.skeleton||!l?null:vr(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}))}}let fi=!1;function mi(){fi||(fi=!0,Ys(hi),Xs(hi,!0,e=>new pi(e)))}var gi={__proto__:null,KHR_draco_mesh_compression:pi,RegisterKHR_draco_mesh_compression:mi};mi();const _i="KHR_gaussian_splatting",vi=.28209479177387814,yi=[0,3,5,7];function bi(e){return e<=0?0:e>=255?255:e+.5|0}class xi{constructor(e){this.name=_i,this._loader=e,this.enabled=this._loader.isExtensionUsed(_i)}dispose(){this._loader=null}_loadMeshPrimitiveAsync(e,n,o,s,r,i){return yr.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=_r.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<yi[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,yr.AddPointerMetadata(h,e),s.parent.onMeshLoadedObservable.notifyObservers(h),i(h);const p=d.getEngine().getCaps(),[f,m,g,_,v,y,...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=y?y.length/x:0,A=new ArrayBuffer(32*x),w=new Float32Array(A),M=new Uint8Array(A);let S=null;if(u>0){const e=3*((u+1)*(u+1)-1),n=Math.ceil(e/16),o=p.maxTextureSize,s=Math.ceil(x/o);S=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(w[t+0]=f[o+0],w[t+1]=f[o+1],w[t+2]=f[o+2],w[t+3]=g?g[o+0]:1,w[t+4]=g?g[o+1]:1,w[t+5]=g?g[o+2]:1,v)M[n+24]=bi(255*(.5+vi*v[o+0])),M[n+25]=bi(255*(.5+vi*v[o+1])),M[n+26]=bi(255*(.5+vi*v[o+2]));else if(y){const t=e*T;M[n+24]=bi(255*y[t+0]),M[n+25]=bi(255*y[t+1]),M[n+26]=bi(255*y[t+2])}else M[n+24]=255,M[n+25]=255,M[n+26]=255;M[n+27]=_?bi(255*_[e]):y&&T>=4?bi(255*y[e*T+3]):255;const s=4*e,r=m?m[s+0]:0,i=m?m[s+1]:0,a=m?m[s+2]:0,l=m?m[s+3]:1;if(M[n+28]=bi(127.5*l+127.5),M[n+29]=bi(127.5*r+127.5),M[n+30]=bi(127.5*i+127.5),M[n+31]=bi(127.5*a+127.5),S){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;S[r>>4][t+i]=bi(128*n[o+s]+128)}}}}return yield h.updateDataAsync(A,null!=S?S:void 0,void 0,u||void 0),h}))}}let Ti=!1;function Ai(){Ti||(Ti=!0,Ys(_i),Xs(_i,!0,e=>new xi(e)))}var wi={__proto__:null,KHR_gaussian_splatting:xi,RegisterKHR_gaussian_splatting:Ai};Ai();const Mi="KHR_lights_punctual";class Si{constructor(e){this.name=Mi,this._loader=e,this.enabled=this._loader.isExtensionUsed(Mi)}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,_r.Assign(this._lights)}}loadNodeAsync(e,n,o){return yr.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=_r.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),yr.AddPointerMetadata(n,s),o(e)})}))}}let Ri=!1;function Ci(){Ri||(Ri=!0,Ys(Mi),Xs(Mi,!0,e=>new Si(e)))}var Ii={__proto__:null,KHR_lights:Si,RegisterKHR_lights:Ci};Ci();const Oi="EXT_lights_area";class Fi{constructor(e){this.name=Oi,this._loader=e,this.enabled=this._loader.isExtensionUsed(Oi)}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,_r.Assign(this._lights)}}loadNodeAsync(e,n,o){return yr.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=_r.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),yr.AddPointerMetadata(i,s),o(e)})}))}}let Ei=!1;function Ni(){Ei||(Ei=!0,Ys(Oi),Xs(Oi,!0,e=>new Fi(e)))}var Li={__proto__:null,EXT_lights_area:Fi,RegisterEXT_lights_area:Ni};Ni();const ki="KHR_materials_pbrSpecularGlossiness";class Pi{constructor(e){this.name=ki,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(ki)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let Bi=!1;function Di(){Bi||(Bi=!0,Ys(ki),Xs(ki,!0,e=>new Pi(e)))}var Vi={__proto__:null,KHR_materials_pbrSpecularGlossiness:Pi,RegisterKHR_materials_pbrSpecularGlossiness:Di};Di();const Gi="KHR_materials_unlit";class $i{constructor(e){this.name=Gi,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(Gi)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let Ui=!1;function Hi(){Ui||(Ui=!0,Ys(Gi),Xs(Gi,!0,e=>new $i(e)))}var Ki={__proto__:null,KHR_materials_unlit:$i,RegisterKHR_materials_unlit:Hi};Hi();const ji="KHR_materials_clearcoat";class Wi{constructor(e){this.name=ji,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(ji)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let qi=!1;function zi(){qi||(qi=!0,Ys(ji),Xs(ji,!0,e=>new Wi(e)))}var Xi={__proto__:null,KHR_materials_clearcoat:Wi,RegisterKHR_materials_clearcoat:zi};zi();const Yi="KHR_materials_coat";class Qi{constructor(e){this.name=Yi,this.order=191,this.useOpenPBR=!1,this._loader=e,this.enabled=this._loader.isExtensionUsed(Yi)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let Zi=!1;function Ji(){Zi||(Zi=!0,Ys(Yi),Xs(Yi,!0,e=>new Qi(e)))}var ea={__proto__:null,KHR_materials_coat:Qi,RegisterKHR_materials_coat:Ji};Ji();const ta="KHR_materials_iridescence";class na{constructor(e){this.name=ta,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(ta)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let oa=!1;function sa(){oa||(oa=!0,Ys(ta),Xs(ta,!0,e=>new na(e)))}var ra={__proto__:null,KHR_materials_iridescence:na,RegisterKHR_materials_iridescence:sa};sa();const ia="KHR_materials_anisotropy";class aa{constructor(e){this.name=ia,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(ia)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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)})}}let la=!1;function ua(){la||(la=!0,Ys(ia),Xs(ia,!0,e=>new aa(e)))}var ca={__proto__:null,KHR_materials_anisotropy:aa,RegisterKHR_materials_anisotropy:ua};ua();const da="KHR_materials_emissive_strength";class ha{constructor(e){this.name=da,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(da)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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)}}let pa=!1;function fa(){pa||(pa=!0,Ys(da),Xs(da,!0,e=>new ha(e)))}var ma={__proto__:null,KHR_materials_emissive_strength:ha,RegisterKHR_materials_emissive_strength:fa};fa();const ga="KHR_materials_sheen";class _a{constructor(e){this.name=ga,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(ga)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let va=!1;function ya(){va||(va=!0,Ys(ga),Xs(ga,!0,e=>new _a(e)))}var ba={__proto__:null,KHR_materials_sheen:_a,RegisterKHR_materials_sheen:ya};ya();const xa="KHR_materials_fuzz";class Ta{constructor(e){this.name=xa,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(xa)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let Aa=!1;function wa(){Aa||(Aa=!0,Ys(xa),Xs(xa,!0,e=>new Ta(e)))}var Ma={__proto__:null,KHR_materials_fuzz:Ta,RegisterKHR_materials_fuzz:wa};wa();const Sa="KHR_materials_specular";class Ra{constructor(e){this.name=Sa,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Sa)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let Ca=!1;function Ia(){Ca||(Ca=!0,Ys(Sa),Xs(Sa,!0,e=>new Ra(e)))}var Oa={__proto__:null,KHR_materials_specular:Ra,RegisterKHR_materials_specular:Ia};Ia();const Fa="KHR_materials_ior";class Ea{constructor(e){this.name=Fa,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(Fa)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(e,t,n){const o=this._loader._getOrCreateMaterialAdapter(n),s=void 0!==t.ior?t.ior:Ea._DEFAULT_IOR;return o.specularIor=s,Promise.resolve()}}Ea._DEFAULT_IOR=1.5;let Na=!1;function La(){Na||(Na=!0,Ys(Fa),Xs(Fa,!0,e=>new Ea(e)))}var ka={__proto__:null,KHR_materials_ior:Ea,RegisterKHR_materials_ior:La};La();const Pa="KHR_materials_variants";class Ba{constructor(e){this.name=Pa,this._loader=e,this.enabled=this._loader.isExtensionUsed(Pa)&&!this._loader.parent.skipMaterials}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return Ba.GetAvailableVariants(e)}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 ${Pa} 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(e,t){Ba.SelectVariant(e,t)}static Reset(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot reset on a glTF mesh that does not have the ${Pa} extension`);for(const e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(e){Ba.Reset(e)}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 ${Pa} extension`);return t.lastSelected}getLastSelectedVariant(e){return Ba.GetLastSelectedVariant(e)}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[Pa])||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}onReady(){var e;const t=this._loader.rootBabylonMesh;if(t){const n=this._loader.parent.extensionOptions[Pa];(null==n?void 0:n.defaultVariant)&&Ba.SelectVariant(t,n.defaultVariant),null===(e=null==n?void 0:n.onLoaded)||void 0===e||e.call(n,{get variants(){return Ba.GetAvailableVariants(t)},get selectedVariant(){const e=Ba.GetLastSelectedVariant(t);return e?Array.isArray(e)?e[0]:e:Ba.GetAvailableVariants(t)[0]},set selectedVariant(e){Ba.SelectVariant(t,e)}})}}_loadMeshPrimitiveAsync(e,n,o,s,r,i){return yr.LoadExtensionAsync(e,r,this.name,(a,l)=>b(this,void 0,void 0,function*(){const u=new Array;return u.push(this._loader._loadMeshPrimitiveAsync(e,n,o,s,r,n=>{if(i(n),n instanceof t.Mesh){const t=yr._GetDrawMode(e,r.mode),o=this._loader.rootBabylonMesh,s=o?o._internalMetadata=o._internalMetadata||{}:{},i=s.gltf=s.gltf||{},c=i[Pa]=i[Pa]||{lastSelected:null,original:[],variants:{}};c.original.push({mesh:n,material:n.material});for(let e=0;e<l.mappings.length;++e){const s=l.mappings[e],r=_r.Get(`${a}/mappings/${e}/material`,this._loader.gltf.materials,s.material);u.push(this._loader._loadMaterialAsync(`#/materials/${s.material}`,r,n,t,e=>{for(let t=0;t<s.variants.length;++t){const r=s.variants[t],i=_r.Get(`/extensions/${Pa}/variants/${r}`,this._variants,r);c.variants[i.name]=c.variants[i.name]||[],c.variants[i.name].push({mesh:n,material:e}),n.onClonedObservable.add(e=>{const t=e;let s,r=t;do{if(r=r.parent,!r)return;s=Ba._GetExtensionMetadata(r)}while(null===s);if(o&&s===Ba._GetExtensionMetadata(o)){r._internalMetadata={};for(const e in o._internalMetadata)r._internalMetadata[e]=o._internalMetadata[e];r._internalMetadata.gltf=[];for(const e in o._internalMetadata.gltf)r._internalMetadata.gltf[e]=o._internalMetadata.gltf[e];r._internalMetadata.gltf[Pa]={lastSelected:null,original:[],variants:{}};for(const e of s.original)r._internalMetadata.gltf[Pa].original.push({mesh:e.mesh,material:e.material});for(const e in s.variants)if(Object.prototype.hasOwnProperty.call(s.variants,e)){r._internalMetadata.gltf[Pa].variants[e]=[];for(const t of s.variants[e])r._internalMetadata.gltf[Pa].variants[e].push({mesh:t.mesh,material:t.material})}s=r._internalMetadata.gltf[Pa]}for(const e of s.original)e.mesh===n&&(e.mesh=t);for(const e of s.variants[i.name])e.mesh===n&&(e.mesh=t)})}}))}}})),yield Promise.all(u).then(([e])=>e)}))}}let Da=!1;function Va(){Da||(Da=!0,Ys(Pa),Xs(Pa,!0,e=>new Ba(e)))}var Ga={__proto__:null,KHR_materials_variants:Ba,RegisterKHR_materials_variants:Va};Va();class $a{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({},$a._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.forceLayerMaskCheck=!0,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 Ua(e,t){if(e.parent.dontUseTransmissionHelper)return;const n=t.getScene()._transmissionHelper,o=null!=n?n:new $a({},t.getScene());for(const t of Array.from(e._pbrMaterialImpls.values()))o.addMaterialImpl(t);n&&!n._isRenderTargetValid()&&n._setupRenderTargets()}const Ha="KHR_materials_transmission";class Ka{constructor(e){this.name=Ha,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ha),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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&&Ua(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(()=>{})}}let ja=!1;function Wa(){ja||(ja=!0,Ys(Ha),Xs(Ha,!0,e=>new Ka(e)))}var qa={__proto__:null,KHR_materials_transmission:Ka,RegisterKHR_materials_transmission:Wa};Wa();const za="KHR_materials_diffuse_transmission";class Xa{constructor(e){this.name=za,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(za),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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&&Ua(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(()=>{})}}let Ya=!1;function Qa(){Ya||(Ya=!0,Ys(za),Xs(za,!0,e=>new Xa(e)))}var Za={__proto__:null,KHR_materials_diffuse_transmission:Xa,RegisterKHR_materials_diffuse_transmission:Qa};Qa();const Ja="KHR_materials_volume";class el{constructor(e){this.name=Ja,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ja),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let tl=!1;function nl(){tl||(tl=!0,Ys(Ja),Xs(Ja,!0,e=>new el(e)))}var ol={__proto__:null,KHR_materials_volume:el,RegisterKHR_materials_volume:nl};nl();const sl="KHR_materials_volume_scatter";class rl{constructor(e){this.name=sl,this.order=172,this._loader=e,this.enabled=this._loader.isExtensionUsed(sl),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let il=!1;function al(){il||(il=!0,Ys(sl),Xs(sl,!0,e=>new rl(e)))}var ll={__proto__:null,KHR_materials_volume_scatter:rl,RegisterKHR_materials_volume_scatter:al};al();const ul="KHR_materials_dispersion";class cl{constructor(e){this.name=ul,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(ul)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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()}}let dl=!1;function hl(){dl||(dl=!0,Ys(ul),Xs(ul,!0,e=>new cl(e)))}var pl={__proto__:null,KHR_materials_dispersion:cl,RegisterKHR_materials_dispersion:hl};hl();const fl="KHR_materials_diffuse_roughness";class ml{constructor(e){this.name=fl,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(fl)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let gl=!1;function _l(){gl||(gl=!0,Ys(fl),Xs(fl,!0,e=>new ml(e)))}var vl={__proto__:null,KHR_materials_diffuse_roughness:ml,RegisterKHR_materials_diffuse_roughness:_l};_l();const yl="KHR_mesh_quantization";class bl{constructor(e){this.name=yl,this.enabled=e.isExtensionUsed(yl)}dispose(){}}let xl=!1;function Tl(){xl||(xl=!0,Ys(yl),Xs(yl,!0,e=>new bl(e)))}var Al={__proto__:null,KHR_mesh_quantization:bl,RegisterKHR_mesh_quantization:Tl};Tl();const wl="KHR_texture_basisu";class Ml{constructor(e){this.name=wl,this._loader=e,this.enabled=e.isExtensionUsed(wl)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?yr.DefaultSampler:_r.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=_r.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,t)}))}}let Sl=!1;function Rl(){Sl||(Sl=!0,Ys(wl),Xs(wl,!0,e=>new Ml(e)))}var Cl={__proto__:null,KHR_texture_basisu:Ml,RegisterKHR_texture_basisu:Rl};Rl();const Il="KHR_texture_transform";class Ol{constructor(e){this.name=Il,this._loader=e,this.enabled=this._loader.isExtensionUsed(Il)}dispose(){this._loader=null}loadTextureInfoAsync(e,n,o){return yr.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)})}))}}let Fl=!1;function El(){Fl||(Fl=!0,Ys(Il),Xs(Il,!0,e=>new Ol(e)))}var Nl={__proto__:null,KHR_texture_transform:Ol,RegisterKHR_texture_transform:El};El();const Ll="KHR_xmp_json_ld";class kl{constructor(e){this.name=Ll,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ll)}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])}}}let Pl=!1;function Bl(){Pl||(Pl=!0,Ys(Ll),Xs(Ll,!0,e=>new kl(e)))}var Dl={__proto__:null,KHR_xmp_json_ld:kl,RegisterKHR_xmp_json_ld:Bl};Bl();const Vl="KHR_animation_pointer";class Gl{constructor(e){this.name=Vl,this._loader=e,this._pathToObjectConverter=dr(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(Vl)}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}}}let $l=!1;function Ul(){$l||($l=!0,Ys(Vl),Xs(Vl,!0,e=>new Gl(e)))}var Hl={__proto__:null,KHR_animation_pointer:Gl,RegisterKHR_animation_pointer:Ul};function Kl(e,n,o,s){return t.Color3.FromArray(n,o).scale(s)}function jl(e,t,n,o){return t[n+3]*o}function Wl(e,t,n,o){return t[n]*o}function ql(e,t,n,o){return-t[n]*o}function zl(e,t,n,o){return t[n+1]*o}function Xl(e,t,n,o){return t[n]*o*2}function Yl(e){return{scale:[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.uScale`,Wl,()=>2),new Zl(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.vScale`,zl,()=>2)],offset:[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,Wl,()=>2),new Zl(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,zl,()=>2)],rotation:[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.wAng`,ql,()=>1)]}}class Ql extends Sr{buildAnimations(e,t,n,o){return[{babylonAnimatable:e._babylonCamera,babylonAnimation:this._buildAnimation(t,n,o)}]}}class Zl extends Sr{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 Jl extends Sr{buildAnimations(e,t,n,o){return[{babylonAnimatable:e._babylonLight,babylonAnimation:this._buildAnimation(t,n,o)}]}}class eu extends Sr{buildAnimations(e,t,n,o){return e._primitiveBabylonMeshes?e._primitiveBabylonMeshes.map(e=>({babylonAnimatable:e,babylonAnimation:this._buildAnimation(t,n,o)})):[]}}let tu=!1;function nu(){if(tu)return;tu=!0,Or(),pr("/cameras/{}/orthographic/xmag",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"orthoLeft",ql,()=>1),new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"orthoRight",zl,()=>1)]),pr("/cameras/{}/orthographic/ymag",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"orthoBottom",ql,()=>1),new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"orthoTop",zl,()=>1)]),pr("/cameras/{}/orthographic/zfar",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"maxZ",Wl,()=>1)]),pr("/cameras/{}/orthographic/znear",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"minZ",Wl,()=>1)]),pr("/cameras/{}/perspective/yfov",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"fov",Wl,()=>1)]),pr("/cameras/{}/perspective/zfar",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"maxZ",Wl,()=>1)]),pr("/cameras/{}/perspective/znear",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"minZ",Wl,()=>1)]),pr("/materials/{}/pbrMetallicRoughness/baseColorFactor",[new Zl(t.Animation.ANIMATIONTYPE_COLOR3,"albedoColor",Kl,()=>4),new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"alpha",jl,()=>4)]),pr("/materials/{}/pbrMetallicRoughness/metallicFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"metallic",Wl,()=>1)]),pr("/materials/{}/pbrMetallicRoughness/metallicFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"roughness",Wl,()=>1)]);const e=Yl("albedoTexture");pr("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/scale",e.scale),pr("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/offset",e.offset),pr("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/rotation",e.rotation);const n=Yl("metallicTexture");pr("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/scale",n.scale),pr("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/offset",n.offset),pr("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/rotation",n.rotation),pr("/materials/{}/emissiveFactor",[new Zl(t.Animation.ANIMATIONTYPE_COLOR3,"emissiveColor",Kl,()=>3)]);const o=Yl("bumpTexture");pr("/materials/{}/normalTexture/scale",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"bumpTexture.level",Wl,()=>1)]),pr("/materials/{}/normalTexture/extensions/KHR_texture_transform/scale",o.scale),pr("/materials/{}/normalTexture/extensions/KHR_texture_transform/offset",o.offset),pr("/materials/{}/normalTexture/extensions/KHR_texture_transform/rotation",o.rotation),pr("/materials/{}/occlusionTexture/strength",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",Wl,()=>1)]);const s=Yl("ambientTexture");pr("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/scale",s.scale),pr("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/offset",s.offset),pr("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/rotation",s.rotation);const r=Yl("emissiveTexture");pr("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/scale",r.scale),pr("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/offset",r.offset),pr("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/rotation",r.rotation),pr("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyStrength",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyRotation",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"anisotropy.angle",Wl,()=>1)]);const i=Yl("anisotropy.texture");pr("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/scale",i.scale),pr("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/offset",i.offset),pr("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/rotation",i.rotation),pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",Wl,()=>1)]);const a=Yl("clearCoat.texture");pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/scale",a.scale),pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/offset",a.offset),pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/rotation",a.rotation);const l=Yl("clearCoat.bumpTexture");pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/scale",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/scale",l.scale),pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/offset",l.offset),pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/rotation",l.rotation);const u=Yl("clearCoat.textureRoughness");pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/scale",u.scale),pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/offset",u.offset),pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/rotation",u.rotation),pr("/materials/{}/extensions/KHR_materials_dispersion/dispersionFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_emissive_strength/emissiveStrength",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"emissiveIntensity",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_ior/ior",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"indexOfRefraction",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.intensity",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceIor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMinimum",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMaximum",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",Wl,()=>1)]);const c=Yl("iridescence.texture");pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/scale",c.scale),pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/offset",c.offset),pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/rotation",c.rotation);const d=Yl("iridescence.thicknessTexture");pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/scale",d.scale),pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/offset",d.offset),pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/rotation",d.rotation),pr("/materials/{}/extensions/KHR_materials_sheen/sheenColorFactor",[new Zl(t.Animation.ANIMATIONTYPE_COLOR3,"sheen.color",Kl,()=>3)]),pr("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"sheen.roughness",Wl,()=>1)]);const h=Yl("sheen.texture");pr("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/scale",h.scale),pr("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/offset",h.offset),pr("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/rotation",h.rotation);const p=Yl("sheen.textureRoughness");pr("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/scale",p.scale),pr("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/offset",p.offset),pr("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/rotation",p.rotation),pr("/materials/{}/extensions/KHR_materials_specular/specularFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"metallicF0Factor",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_specular/specularColorFactor",[new Zl(t.Animation.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",Kl,()=>3)]);const f=Yl("metallicReflectanceTexture");pr("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/scale",f.scale),pr("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/offset",f.offset),pr("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/rotation",f.rotation);const m=Yl("reflectanceTexture");pr("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/scale",m.scale),pr("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/offset",m.offset),pr("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/rotation",m.rotation),pr("/materials/{}/extensions/KHR_materials_transmission/transmissionFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",Wl,()=>1)]);const g=Yl("subSurface.refractionIntensityTexture");pr("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/scale",g.scale),pr("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/offset",g.offset),pr("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/rotation",g.rotation),pr("/materials/{}/extensions/KHR_materials_volume/attenuationColor",[new Zl(t.Animation.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",Kl,()=>3)]),pr("/materials/{}/extensions/KHR_materials_volume/attenuationDistance",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_volume/thicknessFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",Wl,()=>1)]);const _=Yl("subSurface.thicknessTexture");pr("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/scale",_.scale),pr("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/offset",_.offset),pr("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/rotation",_.rotation),pr("/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.translucencyIntensity",Wl,()=>1)]);const v=Yl("subSurface.translucencyIntensityTexture");pr("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/scale",v.scale),pr("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/offset",v.offset),pr("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/rotation",v.rotation),pr("/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorFactor",[new Zl(t.Animation.ANIMATIONTYPE_COLOR3,"subSurface.translucencyColor",Kl,()=>3)]);const y=Yl("subSurface.translucencyColorTexture");pr("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/scale",y.scale),pr("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/offset",y.offset),pr("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/rotation",y.rotation),pr("/extensions/KHR_lights_punctual/lights/{}/color",[new Jl(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",Kl,()=>3)]),pr("/extensions/KHR_lights_punctual/lights/{}/intensity",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",Wl,()=>1)]),pr("/extensions/KHR_lights_punctual/lights/{}/range",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"range",Wl,()=>1)]),pr("/extensions/KHR_lights_punctual/lights/{}/spot/innerConeAngle",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"innerAngle",Xl,()=>1)]),pr("/extensions/KHR_lights_punctual/lights/{}/spot/outerConeAngle",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"angle",Xl,()=>1)]),pr("/extensions/EXT_lights_area/lights/{}/color",[new Jl(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",Kl,()=>3)]),pr("/extensions/EXT_lights_area/lights/{}/intensity",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",Wl,()=>1)]),pr("/extensions/EXT_lights_area/lights/{}/size",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"radius",Wl,()=>1)]),pr("/extensions/EXT_lights_area/lights/{}/rect/aspect",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"radius",Wl,()=>1)]),pr("/nodes/{}/extensions/EXT_lights_ies/color",[new Jl(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",Kl,()=>3)]),pr("/nodes/{}/extensions/EXT_lights_ies/multiplier",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",Wl,()=>1)]),pr("/nodes/{}/extensions/KHR_node_visibility/visible",[new eu(t.Animation.ANIMATIONTYPE_FLOAT,"isVisible",Wl,()=>1)])}var ou={__proto__:null,_RegisterKHRAnimationPointerData:nu};nu(),Ul();const su="MSFT_audio_emitter";class ru{constructor(e){this.name=su,this._loader=e,this.enabled=this._loader.isExtensionUsed(su)}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,_r.Assign(this._clips),_r.Assign(this._emitters)}}loadSceneAsync(e,t){return yr.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=_r.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 yr.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=_r.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 yr.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;_r.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=_r.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=_r.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=_r.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()})}})}}let iu=!1;function au(){iu||(iu=!0,Ys(su),Xs(su,!0,e=>new ru(e)))}var lu={__proto__:null,MSFT_audio_emitter:ru,RegisterMSFT_audio_emitter:au};au();const uu="MSFT_lod";class cu{constructor(e){var n,o;this.name=uu,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[uu])||void 0===n?void 0:n.maxLODsToLoad)&&void 0!==o?o:this.maxLODsToLoad,this.enabled=this._loader.isExtensionUsed(uu)}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 yr.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:yr.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(_r.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()}}let du=!1;function hu(){du||(du=!0,Ys(uu),Xs(uu,!0,e=>new cu(e)))}var pu={__proto__:null,MSFT_lod:cu,RegisterMSFT_lod:hu};hu();const fu="MSFT_minecraftMesh";class mu{constructor(e){this.name=fu,this._loader=e,this.enabled=this._loader.isExtensionUsed(fu)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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}}))}}let gu=!1;function _u(){gu||(gu=!0,Ys(fu),Xs(fu,!0,e=>new mu(e)))}var vu={__proto__:null,MSFT_minecraftMesh:mu,RegisterMSFT_minecraftMesh:_u};_u();const yu="MSFT_sRGBFactors";class bu{constructor(e){this.name=yu,this._loader=e,this.enabled=this._loader.isExtensionUsed(yu)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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}}))}}let xu=!1;function Tu(){xu||(xu=!0,Ys(yu),Xs(yu,!0,e=>new bu(e)))}var Au={__proto__:null,MSFT_sRGBFactors:bu,RegisterMSFT_sRGBFactors:Tu};function wu(e){const[t,n]=e.split(":");return Ru({op:t,extension:n})}function Mu(e){return"flow/waitAll"!==e&&(e.startsWith("flow/")||e.startsWith("animation/")||"pointer/set"===e||"pointer/interpolate"===e||"variable/set"===e||"variable/interpolate"===e||"event/send"===e||"event/stopPropagation"===e||"flow/log:BABYLON"===e)}function Su(e){const t=e=>{if(Array.isArray(e))return e.slice();if(null!==e&&"object"==typeof e){if("function"==typeof e.asArray)return Array.from(e.asArray());if(Object.prototype.hasOwnProperty.call(e,"value")){const t=e.value;return Array.isArray(t)?t.slice():[t]}}return[e]};return Array.isArray(e)?e.filter(e=>null!==e&&"object"==typeof e&&"string"==typeof e.id).map(e=>Object.assign({id:e.id,type:e.type},void 0===e.value?{}:{value:t(e.value)})).sort((e,t)=>e.id.localeCompare(t.id)):null!==e&&"object"==typeof e?Object.entries(e).map(([e,n])=>{var o;if(null===n||"object"!=typeof n)return{id:e,malformed:!0};const s=n;return Object.assign({id:e,type:"string"==typeof s.type?s.type:null===(o=s.type)||void 0===o?void 0:o.typeName},void 0===s.value?{}:{value:t(s.value)})}).sort((e,t)=>e.id.localeCompare(t.id)):e}function Ru(e,n=!0){const o=e.extension?Ou(Eu,e.extension):void 0,s=e.extension?Ou(o,e.op):Ou(Nu,e.op);return!s&&n?(t.Logger.Warn(`No mapping found for operation ${e.op} and extension ${e.extension||"KHR_interactivity"}`),Cu(e)):s}function Cu(e){const t={},n={flows:{}};if(e.inputValueSockets){t.values=Object.create(null);for(const n in e.inputValueSockets)Object.prototype.hasOwnProperty.call(e.inputValueSockets,n)&&Object.defineProperty(t.values,n,{configurable:!0,enumerable:!0,value:{name:n},writable:!0})}return e.outputValueSockets&&(n.values=Object.create(null),Object.keys(e.outputValueSockets).forEach(e=>{Object.defineProperty(n.values,e,{configurable:!0,enumerable:!0,value:{name:e},writable:!0})})),{blocks:[],inputs:t,outputs:n}}function Iu(e,t,n){let o=Ou(Eu,t);o||(o=Object.create(null),Object.defineProperty(Eu,t,{configurable:!0,enumerable:!0,value:o,writable:!0})),Object.defineProperty(o,e,{configurable:!0,enumerable:!0,value:n,writable:!0})}function Ou(e,t){return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Fu(){const e=Object.keys(Nu).map(e=>({op:e,mapping:Nu[e]}));for(const t of Object.keys(Eu).sort())for(const n of Object.keys(Eu[t]).sort())e.push({op:n,extension:t,mapping:Eu[t][n]});return e.sort((e,t)=>{var n,o;return`${null!==(n=e.extension)&&void 0!==n?n:""}:${e.op}`.localeCompare(`${null!==(o=t.extension)&&void 0!==o?o:""}:${t.op}`)})}Tu();const Eu={BABYLON:{"flow/log":{blocks:["FlowGraphConsoleLogBlock"],inputs:{values:{message:{name:"message"},"[segment]":{name:"$1",compatibilityOnly:!0}}},outputs:{flows:{out:{name:"out",compatibilityOnly:!0}}}}}},Nu={"event/onStart":{blocks:["FlowGraphSceneReadyEventBlock"],outputs:{values:{event:{name:"event"}},flows:{out:{name:"done"}}}},"event/onTick":{blocks:["FlowGraphSceneTickEventBlock"],inputs:{},outputs:{values:{timeSinceStart:{name:"timeSinceStart",gltfType:"number"},timeSinceLastTick:{name:"deltaTime",gltfType:"number"},event:{name:"event"}},flows:{out:{name:"done"}}}},"event/send":{blocks:["FlowGraphSendCustomEventBlock"],configuration:{event:{name:"eventId",configurationType:"int",required:!0,indexSource:"events",validationOnly:!0}},inputs:{values:{"[segment]":{name:"$1"}}},outputs:{flows:{out:{name:"out"}}},extraProcessor(e,t,n,o,s){var r,i;if("event/send"!==t.op||!(null===(r=e.configuration)||void 0===r?void 0:r.event))throw new Error("Send event should have a single configuration object, the event itself");const a=null===(i=e.configuration.event.value)||void 0===i?void 0:i[0];if("number"!=typeof a)throw new Error("Event id should be a number");const l=o.arrays.events[a],u=s[0];return u.config||(u.config={}),u.config.eventId=l.eventId,u.config.eventData=l.eventData,s}},"event/receive":{blocks:["FlowGraphReceiveCustomEventBlock"],configuration:{event:{name:"eventId",configurationType:"int",required:!0,indexSource:"events",validationOnly:!0}},outputs:{values:{event:{name:"event"},"[segment]":{name:"$1"}},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,i;if("event/receive"!==t.op||!(null===(r=e.configuration)||void 0===r?void 0:r.event))throw new Error("Receive event should have a single configuration object, the event itself");const a=null===(i=e.configuration.event.value)||void 0===i?void 0:i[0];if("number"!=typeof a)throw new Error("Event id should be a number");const l=o.arrays.events[a],u=s[0];return u.config||(u.config={}),u.config.eventId=l.eventId,u.config.eventData=l.eventData,s}},"event/stopPropagation":{blocks:["FlowGraphStopEventPropagationBlock"],inputs:{values:{event:{name:"event"},stopImmediate:{name:"stopImmediate"}},flows:{in:{name:"in"}}},outputs:{flows:{out:{name:"out"}}}},"math/E":Lu("FlowGraphEBlock",[]),"math/Pi":Lu("FlowGraphPIBlock",[]),"math/Tau":Lu("FlowGraphTauBlock",[]),"math/Inf":Lu("FlowGraphInfBlock",[]),"math/NaN":Lu("FlowGraphNaNBlock",[]),"math/abs":Lu("FlowGraphAbsBlock"),"math/sign":Lu("FlowGraphSignBlock"),"math/trunc":Lu("FlowGraphTruncBlock"),"math/floor":Lu("FlowGraphFloorBlock"),"math/ceil":Lu("FlowGraphCeilBlock"),"math/round":{blocks:["FlowGraphRoundBlock"],configuration:{},inputs:{values:{a:{name:"a"}}},outputs:{values:{value:{name:"value",typeSourceInput:"a"}}},extraProcessor(e,t,n,o,s){var r;return(r=s[0]).config||(r.config={}),s[0].config.roundHalfAwayFromZero=!0,s}},"math/fract":Lu("FlowGraphFractBlock"),"math/neg":Lu("FlowGraphNegationBlock"),"math/add":Lu("FlowGraphAddBlock",["a","b"],!0),"math/sub":Lu("FlowGraphSubtractBlock",["a","b"],!0),"math/mul":{blocks:["FlowGraphMultiplyBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value",typeSourceInput:"a"}}},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?ku(e):{valid:!0}},"math/div":Lu("FlowGraphDivideBlock",["a","b"],!0),"math/rem":Lu("FlowGraphModuloBlock",["a","b"]),"math/min":Lu("FlowGraphMinBlock",["a","b"]),"math/max":Lu("FlowGraphMaxBlock",["a","b"]),"math/clamp":Lu("FlowGraphClampBlock",["a","b","c"]),"math/saturate":Lu("FlowGraphSaturateBlock"),"math/mix":Lu("FlowGraphMathInterpolationBlock",["a","b","c"]),"math/smoothStep":Lu("FlowGraphSmoothStepBlock",["a","b","c"]),"math/rgbToOkLCh":{blocks:["FlowGraphRGBToOkLChBlock"],inputs:{values:{r:{name:"r",gltfType:"number"},g:{name:"g",gltfType:"number"},b:{name:"b",gltfType:"number"}}},outputs:{values:{l:{name:"l"},c:{name:"c"},h:{name:"h"}}}},"math/rgbFromOkLCh":{blocks:["FlowGraphRGBFromOkLChBlock"],inputs:{values:{l:{name:"l",gltfType:"number"},c:{name:"c",gltfType:"number"},h:{name:"h",gltfType:"number"}}},outputs:{values:{r:{name:"r"},g:{name:"g"},b:{name:"b"}}}},"math/quatSlerp":Lu("FlowGraphMathSlerpBlock",["a","b","c"]),"math/slerp":Lu("FlowGraphVectorSlerpBlock",["a","b","c"]),"math/eq":Lu("FlowGraphEqualityBlock",["a","b"]),"ref/eq":Lu("FlowGraphEqualityBlock",["a","b"]),"math/lt":Lu("FlowGraphLessThanBlock",["a","b"]),"math/le":Lu("FlowGraphLessThanOrEqualBlock",["a","b"]),"math/gt":Lu("FlowGraphGreaterThanBlock",["a","b"]),"math/ge":Lu("FlowGraphGreaterThanOrEqualBlock",["a","b"]),"math/isNaN":Lu("FlowGraphIsNaNBlock"),"math/isInf":Lu("FlowGraphIsInfBlock"),"math/select":{blocks:["FlowGraphConditionalBlock"],inputs:{values:{condition:{name:"condition"},a:{name:"onTrue"},b:{name:"onFalse"}}},outputs:{values:{value:{name:"output",typeSourceInput:"a"}}}},"math/random":{blocks:["FlowGraphRandomBlock"],outputs:{values:{value:{name:"value",gltfType:"float"}}}},"math/sin":Lu("FlowGraphSinBlock"),"math/cos":Lu("FlowGraphCosBlock"),"math/tan":Lu("FlowGraphTanBlock"),"math/asin":Lu("FlowGraphASinBlock"),"math/acos":Lu("FlowGraphACosBlock"),"math/atan":Lu("FlowGraphATanBlock"),"math/atan2":Lu("FlowGraphATan2Block",["a","b"]),"math/sinh":Lu("FlowGraphSinhBlock"),"math/cosh":Lu("FlowGraphCoshBlock"),"math/tanh":Lu("FlowGraphTanhBlock"),"math/asinh":Lu("FlowGraphASinhBlock"),"math/acosh":Lu("FlowGraphACoshBlock"),"math/atanh":Lu("FlowGraphATanhBlock"),"math/exp":Lu("FlowGraphExponentialBlock"),"math/log":Lu("FlowGraphLogBlock"),"math/log2":Lu("FlowGraphLog2Block"),"math/log10":Lu("FlowGraphLog10Block"),"math/sqrt":Lu("FlowGraphSquareRootBlock"),"math/cbrt":Lu("FlowGraphCubeRootBlock"),"math/pow":Lu("FlowGraphPowerBlock",["a","b"]),"math/length":Lu("FlowGraphLengthBlock"),"math/normalize":Object.assign(Object.assign({},Lu("FlowGraphNormalizeBlock")),{outputs:{values:{value:{name:"value",typeSourceInput:"a"},isValid:{name:"isValid",gltfType:"bool"}}}}),"math/dot":Lu("FlowGraphDotBlock",["a","b"]),"math/cross":Lu("FlowGraphCrossBlock",["a","b"]),"math/rotate2D":{blocks:["FlowGraphRotate2DBlock"],inputs:{values:{a:{name:"a"},angle:{name:"b"}}},outputs:{values:{value:{name:"value",typeSourceInput:"a"}}}},"math/rotate3D":{blocks:["FlowGraphRotate3DBlock"],inputs:{values:{a:{name:"a"},rotation:{name:"b"}}},outputs:{values:{value:{name:"value",typeSourceInput:"a"}}}},"math/transform":{blocks:["FlowGraphTransformVectorBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value",typeSourceInput:"a"}}}},"math/combine2":{blocks:["FlowGraphCombineVector2Block"],inputs:{values:{a:{name:"input_0",gltfType:"number"},b:{name:"input_1",gltfType:"number"}}},outputs:{values:{value:{name:"value",gltfType:"float2"}}}},"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",gltfType:"float3"}}}},"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",gltfType:"float4"}}}},"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":Lu("FlowGraphTransposeBlock"),"math/determinant":Lu("FlowGraphDeterminantBlock"),"math/inverse":Object.assign(Object.assign({},Lu("FlowGraphInvertMatrixBlock")),{outputs:{values:{value:{name:"value",typeSourceInput:"a"},isValid:{name:"isValid",gltfType:"bool"}}}}),"math/matMul":Lu("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",gltfType:"float4x4"}}},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"},scaling:{name:"scaling",compatibilityOnly:!0},isValid:{name:"isValid",compatibilityOnly:!0}}},extraProcessor(e,t,n,o,s){var r;return(r=s[0]).config||(r.config={}),s[0].config.keepDegenerateComponents=!0,s}},"math/quatConjugate":Lu("FlowGraphConjugateBlock",["a"]),"math/quatMul":{blocks:["FlowGraphMultiplyBlock"],inputs:{values:{a:{name:"a",gltfType:"float4"},b:{name:"b",gltfType:"float4"}}},outputs:{values:{value:{name:"value",gltfType:"float4"}}},extraProcessor(e,t,n,o,s){var r;return(r=s[0]).config||(r.config={}),s[0].config.type="Quaternion",s}},"math/quatAngleBetween":Lu("FlowGraphAngleBetweenBlock",["a","b"]),"math/quatFromAxisAngle":{blocks:["FlowGraphQuaternionFromAxisAngleBlock"],inputs:{values:{axis:{name:"a",gltfType:"float3"},angle:{name:"b",gltfType:"number"}}},outputs:{values:{value:{name:"value",gltfType:"float4"}}}},"math/quatToAxisAngle":{blocks:["FlowGraphAxisAngleFromQuaternionBlock"],inputs:{values:{a:{name:"a",gltfType:"float4"}}},outputs:{values:{axis:{name:"axis",gltfType:"float3"},angle:{name:"angle",gltfType:"float"}}}},"math/quatFromDirections":Object.assign(Object.assign({},Lu("FlowGraphQuaternionFromDirectionsBlock",["a","b"])),{outputs:{values:{value:{name:"value",gltfType:"float4"}}}}),"math/quatFromUpForward":{blocks:["FlowGraphQuaternionFromUpForwardBlock"],inputs:{values:{up:{name:"a",gltfType:"float3"},forward:{name:"b",gltfType:"float3"}}},outputs:{values:{value:{name:"value",gltfType:"float4"}}}},"math/quatFromAngles":{blocks:["FlowGraphQuaternionFromAnglesBlock"],configuration:{order:{name:"order",defaultValue:["yxz"],configurationType:"string",invalidUsesDefault:!0,allowedValues:["xyz","xzy","yxz","yzx","zxy","zyx"]}},inputs:{values:{x:{name:"a",gltfType:"number"},y:{name:"b",gltfType:"number"},z:{name:"c",gltfType:"number"}}},outputs:{values:{value:{name:"value",gltfType:"float4"}}}},"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",gltfType:"float2x2"}}}},"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",gltfType:"float3x3"}}}},"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",gltfType:"float4x4"}}}},"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",typeSourceInput:"a"}}},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",typeSourceInput:"a"}}},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",typeSourceInput:"a"}}},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",typeSourceInput:"a"}}},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":Lu("FlowGraphBitwiseRightShiftBlock",["a","b"]),"math/lsl":Lu("FlowGraphBitwiseLeftShiftBlock",["a","b"]),"math/clz":Lu("FlowGraphLeadingZerosBlock"),"math/ctz":Lu("FlowGraphTrailingZerosBlock"),"math/popcnt":Lu("FlowGraphOneBitsCounterBlock"),"math/rad":Lu("FlowGraphDegToRadBlock"),"math/deg":Lu("FlowGraphRadToDegBlock"),"type/boolToInt":Lu("FlowGraphBooleanToInt"),"type/boolToFloat":Lu("FlowGraphBooleanToFloat"),"type/intToBool":Lu("FlowGraphIntToBoolean"),"type/intToFloat":Lu("FlowGraphIntToFloat"),"type/floatToInt":Lu("FlowGraphFloatToInt"),"type/floatToBool":Lu("FlowGraphFloatToBoolean"),"flow/sequence":{blocks:["FlowGraphSequenceBlock"],outputs:{flows:{"[segment]":{name:"$1"}}},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"],inputs:{values:{condition:{name:"condition",gltfType:"boolean"}}},outputs:{flows:{true:{name:"onTrue"},false:{name:"onFalse"}}}},"flow/switch":{blocks:["FlowGraphSwitchBlock"],configuration:{cases:{name:"cases",isArray:!0,inOptions:!0,defaultValue:[],configurationType:"int[]",invalidUsesDefault:!0,generatesOutputFlowSockets:!0,uniqueValues:!0}},inputs:{values:{selection:{name:"case"},default:{name:"default"}}},outputs:{flows:{default:{name:"default"},"[segment]":{name:"$1"}}},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&&Number.isInteger(e)&&e>=-2147483648&&e<=2147483647))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"],inputs:{values:{condition:{name:"condition",gltfType:"boolean"}}},outputs:{flows:{loopBody:{name:"executionFlow"},completed:{name:"completed"}}}},"flow/for":{blocks:["FlowGraphForLoopBlock"],configuration:{initialIndex:{name:"initialIndex",gltfType:"int",inOptions:!0,defaultValue:0,configurationType:"int",invalidUsesDefault:!0}},inputs:{values:{startIndex:{name:"startIndex",gltfType:"int"},endIndex:{name:"endIndex",gltfType:"int"}}},outputs:{values:{index:{name:"index"}},flows:{loopBody:{name:"executionFlow"},completed:{name:"completed"}}},extraProcessor(e,t,n,o,s){const r=s[0];return r.config||(r.config={}),r.config.incrementIndexWhenLoopDone=!0,r.config.maxLoopIterations=2e4,s}},"flow/doN":{blocks:["FlowGraphDoNBlock"],configuration:{},inputs:{values:{n:{name:"maxExecutions",gltfType:"int"}},flows:{reset:{name:"reset"}}},outputs:{flows:{out:{name:"out"}},values:{currentCount:{name:"executionCount"}}}},"flow/multiGate":{blocks:["FlowGraphMultiGateBlock"],inputs:{flows:{reset:{name:"reset"}}},configuration:{isRandom:{name:"isRandom",gltfType:"boolean",inOptions:!0,defaultValue:!1,configurationType:"bool",invalidUsesDefault:!0,configurationGroup:"multiGate"},isLoop:{name:"isLoop",gltfType:"boolean",inOptions:!0,defaultValue:!1,configurationType:"bool",invalidUsesDefault:!0,configurationGroup:"multiGate"}},outputs:{flows:{"[segment]":{name:"$1"}},values:{lastIndex:{name:"lastIndex",gltfType:"int"}}},extraProcessor(e,t,n,o,s){var r;if("flow/multiGate"!==t.op)throw new Error("Invalid operation for MultiGate mapping");const i=s[0];return i.config||(i.config={}),i.config.outputSignalCount=Object.keys(null!==(r=e.flows)&&void 0!==r?r:{}).length,i.signalOutputs.forEach((e,t)=>{e.name="out_"+t}),s}},"flow/waitAll":{blocks:["FlowGraphWaitAllBlock"],configuration:{inputFlows:{name:"inputSignalCount",gltfType:"number",inOptions:!0,defaultValue:[0],configurationType:"int",invalidUsesDefault:!0,minimum:0,maximum:64,generatesInputFlowSockets:!0}},inputs:{flows:{reset:{name:"reset"},"[segment]":{name:"in_$1"}}},outputs:{flows:{out:{name:"out"},completed:{name:"completed"}},values:{remainingInputs:{name:"remainingInputs",gltfType:"int"}}},validation(e){var t,n;const o=null===(n=null===(t=e.configuration)||void 0===t?void 0:t.inputFlows)||void 0===n?void 0:n.value,s=null==o?void 0:o[0];return(1!==(null==o?void 0:o.length)||"number"!=typeof s||!Number.isInteger(s)||s<0||s>64)&&(e.configuration=e.configuration||{inputFlows:{value:[0]}},e.configuration.inputFlows.value=[0]),{valid:!0}}},"flow/throttle":{blocks:["FlowGraphThrottleBlock"],inputs:{values:{duration:{name:"duration",gltfType:"number"}},flows:{reset:{name:"reset"}}},outputs:{flows:{out:{name:"out"},err:{name:"error"}},values:{lastRemainingTime:{name:"lastRemainingTime",gltfType:"number"}}}},"flow/setDelay":{blocks:["FlowGraphSetDelayBlock"],inputs:{values:{duration:{name:"duration",gltfType:"number"}},flows:{cancel:{name:"cancel"}}},outputs:{flows:{out:{name:"out"},err:{name:"error"},done:{name:"done"}},values:{lastDelay:{name:"lastDelayIndex"},lastDelayIndex:{name:"lastDelayIndex",compatibilityOnly:!0}}}},"flow/cancelDelay":{blocks:["FlowGraphCancelDelayBlock"],inputs:{values:{delay:{name:"delayIndex",gltfType:"ref"}}},outputs:{flows:{out:{name:"out"}}}},"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",configurationType:"int",required:!0,indexSource:"variables",flowGraphType:"string",inOptions:!0,isVariable:!0,dataTransformer:(e,t)=>t.getVariableName(e)}},outputs:{values:{value:{name:"value"}}}},"variable/set":{blocks:["FlowGraphSetVariableBlock"],inputs:{values:{"[segment]":{name:"$1"}}},configuration:{variables:{name:"variables",gltfType:"number",configurationType:"int[]",required:!0,indexSource:"variables",minItems:1,generatesInputValueSockets:!0,flowGraphType:"string",inOptions:!0,isArray:!0,dataTransformer:(e,t)=>e.map(e=>t.getVariableName(e))}},outputs:{flows:{out:{name:"out",compatibilityOnly:!0}}},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",configurationType:"int",required:!0,indexSource:"variables",inOptions:!0,isVariable:!0,dataTransformer:(e,t)=>t.getVariableName(e)},useSlerp:{name:"animationType",configurationType:"bool",required:!0,inOptions:!0,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],p=null===(a=null===(i=e.configuration)||void 0===i?void 0:i.variable.value)||void 0===a?void 0:a[0];if("number"!=typeof p)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[p];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 m=r[4];return m.config||(m.config={}),(d=m.config).variable||(d.variable={}),m.config.variable.value=s.getVariableName(p),r}},"pointer/get":{blocks:["FlowGraphGetPropertyBlock","FlowGraphJsonPointerParserBlock"],validation:e=>Du(e),configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock",configurationType:"string",required:!0,pointerTemplate:!0},type:{name:"type",configurationType:"int",required:!0,validationOnly:!0,indexSource:"types"}},inputs:{values:{"[segment]":{name:"$1",toBlock:"FlowGraphJsonPointerParserBlock"}}},outputs:{values:{value:{name:"value"},isValid:{name:"isValid",gltfType:"bool"}}},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"],validation:e=>Du(e,new Set(["value"])),configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock",configurationType:"string",required:!0,pointerTemplate:!0},type:{name:"type",configurationType:"int",required:!0,validationOnly:!0,indexSource:"types"}},inputs:{values:{value:{name:"value"},"[segment]":{name:"$1",toBlock:"FlowGraphJsonPointerParserBlock"}}},outputs:{flows:{err:{name:"error"},out:{name:"out",compatibilityOnly:!0}}},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"],validation:e=>Du(e,new Set(["value","duration","p1","p2"])),configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock",configurationType:"string",required:!0,pointerTemplate:!0},type:{name:"type",configurationType:"int",required:!0,validationOnly:!0,indexSource:"types",allowedSignatures:["float","float2","float3","float4","float2x2","float3x3","float4x4"]}},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:"ref",toBlock:"FlowGraphArrayIndexBlock"},speed:{name:"speed",gltfType:"number"},startTime:{name:"from",gltfType:"number",convertConnectedTimeToFrames:!0,dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]},endTime:{name:"to",gltfType:"number",convertConnectedTimeToFrames:!0,dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]}}},outputs:{flows:{out:{name:"out"},err:{name:"error"},done:{name:"done"}}},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.find(e=>"FlowGraphPlayAnimationBlock"===e.className);a&&(a.config.useVirtualTimeline=!0);const l=s.find(e=>"FlowGraphArrayIndexBlock"===e.className);l&&(l.config.referenceCollection="animations");const u=s[s.length-1];return u.config||(u.config={}),u.config.glTF=i,s}},"animation/stop":{blocks:["FlowGraphStopAnimationBlock","FlowGraphArrayIndexBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],inputs:{values:{animation:{name:"index",gltfType:"ref",toBlock:"FlowGraphArrayIndexBlock"}}},outputs:{flows:{out:{name:"out"},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.find(e=>"FlowGraphStopAnimationBlock"===e.className);a&&(a.config.skipOnAnimationEnd=!0);const l=s.find(e=>"FlowGraphArrayIndexBlock"===e.className);l&&(l.config.referenceCollection="animations");const u=s[s.length-1];return u.config||(u.config={}),u.config.glTF=i,s}},"animation/stopAt":{blocks:["FlowGraphStopAnimationBlock","FlowGraphArrayIndexBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{},inputs:{values:{animation:{name:"index",gltfType:"ref",toBlock:"FlowGraphArrayIndexBlock"},stopTime:{name:"stopAtFrame",gltfType:"number",convertConnectedTimeToFrames:!0,dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]}}},outputs:{flows:{out:{name:"out"},err:{name:"error"},done:{name:"done"}}},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.find(e=>"FlowGraphStopAnimationBlock"===e.className);a&&(a.config.useVirtualStopAt=!0,a.config.skipOnAnimationEnd=!0);const l=s.find(e=>"FlowGraphArrayIndexBlock"===e.className);l&&(l.config.referenceCollection="animations");const u=s[s.length-1];return u.config||(u.config={}),u.config.glTF=i,s}},"math/switch":{blocks:["FlowGraphDataSwitchBlock"],configuration:{cases:{name:"cases",isArray:!0,inOptions:!0,defaultValue:[],configurationType:"int[]",invalidUsesDefault:!0,generatesCaseInputValueSockets:!0,uniqueValues:!0}},inputs:{values:{selection:{name:"case",gltfType:"int"},default:{name:"default"},"[case]":{name:"$1"}}},outputs:{values:{value:{name:"value"}}},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"],inputs:{flows:{in:{name:"in"}},values:{"[parameter]":{name:"$1"}}},outputs:{flows:{out:{name:"out"}}},configuration:{severity:{name:"severity",configurationType:"int",defaultValue:0,invalidUsesDefault:!0,validationOnly:!0,configurationGroup:"debugLog"},message:{name:"messageTemplate",configurationType:"string",defaultValue:"",invalidUsesDefault:!0,inOptions:!0,configurationGroup:"debugLog",debugLogTemplate:!0}}}};function Lu(e,t=["a"],n){return{blocks:[e],inputs:{values:t.reduce((e,t)=>(e[t]={name:t},e),{})},outputs:{values:{value:{name:"value",typeSourceInput:t[0]}}},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?ku(e):{valid:!0}}}function ku(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 Pu(e){for(let t=0;t<e.length;t++){const n=e[t];if(-1==="[]{}".indexOf(n))continue;let o=1;for(;e[t+o]===n;)o++;if(o%2!=0)return!0;t+=o-1}return!1}function Bu(e){let t=0,n=-1;const o=[],s=new Set;for(let r=0;r<e.length;r++){const i=e[r];if("{"===i)if(0===t)t=1;else{if(1!==t)return{valid:!1,sockets:[]};t=0}else if("}"===i)if(0===t)t=3;else if(3===t)t=0;else{if(2!==t)return{valid:!1,sockets:[]};{const i=e.substring(n+1,r);s.has(i)||(s.add(i),o.push(i)),t=0}}else if(1===t)n=r-1,t=2;else if(3===t)return{valid:!1,sockets:[]}}return{valid:0===t,sockets:0===t?o:[]}}function Du(e,t=new Set){var n,o,s;const r=null===(s=null===(o=null===(n=e.configuration)||void 0===n?void 0:n.pointer)||void 0===o?void 0:o.value)||void 0===s?void 0:s[0];if("string"!=typeof r)return{valid:!1,error:"A pointer operation requires a string `pointer` configuration value"};if(0!==r.length&&"/"!==r[0])return{valid:!1,error:`The JSON Pointer Template "${r}" is not a syntactically valid JSON Pointer`};const i=e=>({valid:!1,error:`The JSON Pointer Template "${r}" is invalid: ${e}`}),a=new Set;for(const e of r.split("/")){if(/~(?:[^01]|$)/.test(e))return i(`the path segment "${e}" contains an invalid RFC 6901 escape`);const n="["===e[0]&&"["!==e[1],o="{"===e[0]&&"{"!==e[1];if(!n&&!o){if(Pu(e))return i(`the path segment "${e}" contains an odd number of consecutive brackets`);continue}const s=n?"]":"}",r=e.substring(1,e.length-1);if(e.length<3||e[e.length-1]!==s||/[[{]/.test(r)||/[\]}]/.test(r))return i(`the template parameter path segment "${e}" is malformed`);const l=r.replace(/~1/g,"/").replace(/~0/g,"~");if(t.has(l))return i(`the template parameter "${l}" uses a reserved input socket id`);if(a.has(l))return i(`the template parameter "${l}" is used more than once`);a.add(l)}return{valid:!0}}function Vu(){return Object.keys(Nu)}const Gu="f798712c5685bc9223a628140fba707db8889300",$u={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"},ref:{length:1,flowGraphType:"string",elementType:"string"},custom:{length:0,flowGraphType:"any",elementType:"any"}};function Uu(e){if(void 0!==e){if(null!==e&&"object"==typeof e){const t=e.asArray;if("function"==typeof t)return Array.from(t.call(e));if("value"in e&&"object"!=typeof e.value)return[e.value]}return Array.isArray(e)?e.slice():[e]}}function Hu(e,t){if(void 0===e)return["undefined"];if(null===e)return["null"];switch(typeof e){case"boolean":return["boolean",e];case"number":return["number",Number.isNaN(e)?"NaN":e===1/0?"Infinity":e===-1/0?"-Infinity":Object.is(e,-0)?"-0":e];case"string":return["string",e];case"object":{if(Object.getOwnPropertySymbols(e).length>0)return;if(Array.isArray(e)){if(Object.getOwnPropertyNames(e).some(t=>"length"!==t&&(!/^(0|[1-9]\d*)$/.test(t)||Number(t)>=e.length||!("value"in Object.getOwnPropertyDescriptor(e,t)))))return}else{const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return;if(Object.getOwnPropertyNames(e).some(t=>!Object.prototype.propertyIsEnumerable.call(e,t)||!("value"in Object.getOwnPropertyDescriptor(e,t))))return}if(t.has(e))return;let n;if(t.add(e),Array.isArray(e)){const o=e.map(e=>Hu(e,t));n=o.some(e=>void 0===e)?void 0:["array",o]}else{const o=[];let s=!1;for(const n of Object.keys(e).sort()){const r=Hu(e[n],t);if(void 0===r){s=!0;break}o.push([n,r])}n=s?void 0:["object",o]}return t.delete(e),n}default:return}}function Ku(e){try{const t=Hu(Array.isArray(e)?e:Uu(e),new Set);return void 0===t?{unrepresentable:!0}:{runtimeValueFingerprint:JSON.stringify(t)}}catch(e){return{unrepresentable:!0}}}function ju(e){if(Array.isArray(e))return e.map(e=>ju(e));if(null!==e&&"object"==typeof e){const t={};for(const[n,o]of Object.entries(e))Object.defineProperty(t,n,{configurable:!0,enumerable:!0,value:ju(o),writable:!0});return t}return e}function Wu(e){return ju(e)}function qu(e,t){return"number"==typeof e&&Number.isInteger(e)&&e>=0&&e<t}function zu(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Xu(e,t,n){e.push({path:t,message:n,severity:"error"})}function Yu(e){return""===e||/^(?:\/(?:[^~]|~[01])*)*$/.test(e)}function Qu(e,t,n,o,s,r){var i,a,l,u,c,d;if(e&&Object.prototype.hasOwnProperty.call(e,t))return!0;if(t===r&&e&&Object.prototype.hasOwnProperty.call(e,r))return!0;if(!Object.keys(null!=e?e:{}).some(e=>e.startsWith("[")&&e.endsWith("]")))return!1;if("event/receive"===n.operation){const e=null===(l=null===(a=null===(i=o.configuration)||void 0===i?void 0:i.event)||void 0===a?void 0:a.value)||void 0===l?void 0:l[0];return"number"==typeof e&&Object.prototype.hasOwnProperty.call(null!==(d=null===(c=null===(u=s.events)||void 0===u?void 0:u[e])||void 0===c?void 0:c.values)&&void 0!==d?d:{},t)}return!0}function Zu(e,t,n,o){var s,r;return!!qu(e,null!==(r=null===(s=t.types)||void 0===s?void 0:s.length)&&void 0!==r?r:0)||(Xu(n,o,`Type index ${String(e)} is out of range.`),!1)}function Ju(e,t,n,o){if(!Zu(e.type,t,n,`${o}/type`))return;if(void 0===e.value)return;if(!Array.isArray(e.value))return void Xu(n,`${o}/value`,"Value must be an array when present.");const s=t.types[e.type],r=$u[s.signature];r&&"custom"!==s.signature&&e.value.length!==r.length&&Xu(n,`${o}/value`,`Expected ${r.length} value component(s) for type "${s.signature}", received ${e.value.length}.`);for(let t=0;t<e.value.length;t++){const r=e.value[t];let i=!0;switch(s.signature){case"bool":i="boolean"==typeof r;break;case"int":i="number"==typeof r&&Number.isInteger(r)&&r>=-2147483648&&r<=2147483647;break;case"float":case"float2":case"float3":case"float4":case"float2x2":case"float3x3":case"float4x4":i="number"==typeof r&&Number.isFinite(r);break;case"ref":i="string"==typeof r&&Yu(r)}i||Xu(n,`${o}/value/${t}`,`Value component is invalid for type "${s.signature}".`)}}function ec(e,t){if(!Array.isArray(e))return!1;const n=e=>"number"==typeof e&&Number.isInteger(e)&&e>=-2147483648&&e<=2147483647;switch(t){case"bool":return 1===e.length&&"boolean"==typeof e[0];case"int":return 1===e.length&&n(e[0]);case"int[]":return e.every(n);case"string":return 1===e.length&&"string"==typeof e[0];default:return e.length>0}}function tc(e,t,n){var o,s,r,i,a,l,u,c;switch(t){case"types":return null!==(s=null===(o=e.types)||void 0===o?void 0:o.length)&&void 0!==s?s:0;case"variables":return null!==(i=null===(r=e.variables)||void 0===r?void 0:r.length)&&void 0!==i?i:0;case"events":return null!==(l=null===(a=e.events)||void 0===a?void 0:a.length)&&void 0!==l?l:0;case"nodes":return null!==(c=null===(u=e.nodes)||void 0===u?void 0:u.length)&&void 0!==c?c:0;case"assetNodes":return null!=n?n:0;default:return 0}}function nc(e,t,n,o){var s,r;if(!e||!ec(e.value,t.configurationType)||!e.value)return!1;if(void 0!==t.minItems&&e.value.length<t.minItems)return!1;if(void 0!==t.minimum&&e.value.some(e=>"number"!=typeof e||e<t.minimum))return!1;if(void 0!==t.maximum&&e.value.some(e=>"number"!=typeof e||e>t.maximum))return!1;if(t.indexSource){const s=tc(n,t.indexSource,o);if(e.value.some(e=>!qu(e,s)))return!1}if(t.allowedSignatures){const o=e.value[0],i="number"==typeof o?null===(r=null===(s=n.types)||void 0===s?void 0:s[o])||void 0===r?void 0:r.signature:void 0;if(!i||!t.allowedSignatures.includes(i))return!1}return!(t.allowedValues&&e.value.some(e=>!t.allowedValues.includes(e))||t.debugLogTemplate&&!Bu(e.value[0]).valid)}function oc(e,t,n){var o,s,r,i,a,l,u,c;const d=Wu(e);for(let e=0;e<(null!==(s=null===(o=d.nodes)||void 0===o?void 0:o.length)&&void 0!==s?s:0);e++){const o=d.nodes[e],s=t[o.declaration];if(!s||"unknown-core"===s.support||"unsupported-extension"===s.support)continue;const h=Ru(s.source,!1);if(!(null==h?void 0:h.configuration))continue;const p=new Map;for(const[e,t]of Object.entries(h.configuration))if(t.configurationGroup){const s=nc(null===(r=o.configuration)||void 0===r?void 0:r[e],t,d,n);p.set(t.configurationGroup,(null===(i=p.get(t.configurationGroup))||void 0===i||i)&&s)}for(const[e,t]of Object.entries(h.configuration)){const s=(!t.configurationGroup||!0===p.get(t.configurationGroup))&&nc(null===(a=o.configuration)||void 0===a?void 0:a[e],t,d,n);s||void 0===t.defaultValue?s&&t.uniqueValues&&(null===(c=null===(u=o.configuration)||void 0===u?void 0:u[e])||void 0===c?void 0:c.value)&&(o.configuration[e].value=Array.from(new Set(o.configuration[e].value))):(null!==(l=o.configuration)&&void 0!==l||(o.configuration={}),o.configuration[e]={value:Array.isArray(t.defaultValue)?ju(t.defaultValue):[t.defaultValue]})}}return d}function sc(e){const t=[];for(const n of e.split("/")){const e=n.startsWith("[")&&!n.startsWith("[[")?"int":n.startsWith("{")&&!n.startsWith("{{")?"ref":void 0;if(e){const o=n.substring(1,n.length-1).replace(/~1/g,"/").replace(/~0/g,"~");t.push({name:o,signature:e})}}return t}function rc(e,t,n,o=new Set){var s;return"node"in e?ic(e.node,null!==(s=e.socket)&&void 0!==s?s:"value",t,n,o):e.type}function ic(e,t,n,o,s=new Set){var r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b,x,T,A,w,M,S,R;const C=`${e}:${t}`;if(s.has(C))return;if(s.add(C),!qu(e,null!==(i=null===(r=n.nodes)||void 0===r?void 0:r.length)&&void 0!==i?i:0))return;const I=n.nodes[e];if(!qu(I.declaration,o.length))return;const O=o[I.declaration],F=null===(l=null===(a=O.source.outputValueSockets)||void 0===a?void 0:a[t])||void 0===l?void 0:l.type;if(void 0!==F)return F;const E=e=>{var t,o;const s=null!==(o=null===(t=n.types)||void 0===t?void 0:t.findIndex(t=>t.signature===e))&&void 0!==o?o:-1;return s>=0?s:void 0};if("isValid"===t)return E("bool");if("pointer/get"===O.operation&&"value"===t){const e=null===(d=null===(c=null===(u=I.configuration)||void 0===u?void 0:u.type)||void 0===c?void 0:c.value)||void 0===d?void 0:d[0];return"number"==typeof e?e:void 0}if("variable/get"===O.operation&&"value"===t){const e=null===(f=null===(p=null===(h=I.configuration)||void 0===h?void 0:h.variable)||void 0===p?void 0:p.value)||void 0===f?void 0:f[0];return"number"==typeof e?null===(g=null===(m=n.variables)||void 0===m?void 0:m[e])||void 0===g?void 0:g.type:void 0}if("math/switch"===O.operation&&"value"===t){const e=null===(_=I.values)||void 0===_?void 0:_.default;return e?rc(e,n,o,s):void 0}if("event/receive"===O.operation&&"event"!==t){const e=null===(b=null===(y=null===(v=I.configuration)||void 0===v?void 0:v.event)||void 0===y?void 0:y.value)||void 0===b?void 0:b[0];return"number"==typeof e?null===(w=null===(A=null===(T=null===(x=n.events)||void 0===x?void 0:x[e])||void 0===T?void 0:T.values)||void 0===A?void 0:A[t])||void 0===w?void 0:w.type:void 0}const N=ac(O.operation,t);if(N)return E(String(N));const L=Ru(O.source,!1),k=null===(S=null===(M=null==L?void 0:L.outputs)||void 0===M?void 0:M.values)||void 0===S?void 0:S[t],P=null==k?void 0:k.gltfType,B="number"===P?"float":"boolean"===P?"bool":P;if(B&&B in $u)return E(B);const D=(null==k?void 0:k.typeSourceInput)?null===(R=I.values)||void 0===R?void 0:R[k.typeSourceInput]:void 0;return D?rc(D,n,o,s):void 0}function ac(e,t){return"value"!==t?"math/rgbToOkLCh"===e&&["l","c","h"].includes(t)||"math/rgbFromOkLCh"===e&&["r","g","b"].includes(t)||e.startsWith("math/extract")?"float":"math/matDecompose"===e?"rotation"===t?"float4":"translation"===t||"scale"===t?"float3":void 0:"math/quatToAxisAngle"===e?"axis"===t?"float3":"angle"===t?"float":void 0:"flow/doN"===e&&"currentCount"===t||"flow/for"===e&&"index"===t?"int":"flow/setDelay"===e&&"lastDelay"===t?"ref":"flow/throttle"===e&&"lastRemainingTime"===t?"float":"event/onStart"!==e&&"event/onTick"!==e&&"event/receive"!==e||"event"!==t?"event/onTick"===e&&"timeSinceLastTick"===t||"event/onTick"===e&&"timeSinceStart"===t?"float":void 0:"ref":["math/E","math/Pi","math/Tau","math/Inf","math/NaN","math/random","math/length","math/dot","math/determinant","math/quatAngleBetween"].includes(e)?"float":["math/eq","ref/eq","math/lt","math/le","math/gt","math/ge","math/isNaN","math/isInf","type/intToBool","type/floatToBool"].includes(e)?"bool":["math/clz","math/ctz","math/popcnt","type/boolToInt","type/floatToInt"].includes(e)?"int":["type/boolToFloat","type/intToFloat"].includes(e)?"float":void 0}function lc(e,t,n,o,s,r,i){var a,l,u,c,d,h,p,f,m,g,_,v,y,b,x,T,A,w,M,S,R,C,I,O,F,E,N,L,k,P,B,D,V,G,$,U,H,K,j,W,q,z,X,Y,Q,Z,J;const ee=`${r}/nodes/${t}`;if(!qu(e.declaration,o.length))return void Xu(s,`${ee}/declaration`,`Declaration index ${String(e.declaration)} is out of range.`);const te=o[e.declaration],ne="unsupported-extension"===te.support?Cu(te.source):Ru(te.source,!1);if("unknown-core"===te.support||!ne)return;const oe=(e,t,n)=>{e.invalidUsesDefault||void 0!==e.defaultValue?function(e,t,n){e.push({path:t,message:n,severity:"warning"})}(s,t,`${n} The default configuration will be used.`):Xu(s,t,n)};for(const[t,n]of Object.entries(null!==(a=e.configuration)&&void 0!==a?a:{}))zu(n)?void 0===n.value||Array.isArray(n.value)?n.value&&0===n.value.length&&Xu(s,`${ee}/configuration/${t}/value`,"Configuration value arrays must contain at least one item when present."):Xu(s,`${ee}/configuration/${t}/value`,"Configuration value must be an array when present."):Xu(s,`${ee}/configuration/${t}`,`Configuration "${t}" must be an object.`);for(const[t,r]of Object.entries(null!==(l=ne.configuration)&&void 0!==l?l:{})){const a=null===(u=e.configuration)||void 0===u?void 0:u[t],l=!!a&&ec(a.value,r.configurationType);if(!a&&r.required?Xu(s,`${ee}/configuration/${t}`,`Required configuration "${t}" is missing.`):a&&!l&&oe(r,`${ee}/configuration/${t}`,`Configuration "${t}" is invalid.`),l&&a.value&&void 0!==r.minItems&&a.value.length<r.minItems&&Xu(s,`${ee}/configuration/${t}/value`,`Configuration "${t}" requires at least ${r.minItems} value(s).`),l&&a.value&&r.indexSource){const e=tc(n,r.indexSource,i);for(let n=0;n<a.value.length;n++)qu(a.value[n],e)||oe(r,`${ee}/configuration/${t}/value/${n}`,`Index is out of range for graph ${r.indexSource}.`)}if(l&&a.value&&r.allowedSignatures){const e=a.value[0],o="number"==typeof e?null===(d=null===(c=n.types)||void 0===c?void 0:c[e])||void 0===d?void 0:d.signature:void 0;o&&r.allowedSignatures.includes(o)||oe(r,`${ee}/configuration/${t}/value/0`,`Type "${String(o)}" is not supported by this operation.`)}if(l&&a.value&&r.allowedValues&&a.value.some(e=>!r.allowedValues.includes(e))&&oe(r,`${ee}/configuration/${t}/value`,`Configuration "${t}" contains an unsupported value.`),l&&a.value&&r.debugLogTemplate&&!Bu(a.value[0]).valid&&oe(r,`${ee}/configuration/${t}/value/0`,`Configuration "${t}" is not a valid debug message template.`),l&&a.value&&(void 0!==r.minimum||void 0!==r.maximum)){const e=a.value[0];(void 0!==r.minimum&&e<r.minimum||void 0!==r.maximum&&e>r.maximum)&&oe(r,`${ee}/configuration/${t}/value/0`,`Configuration "${t}" must be between ${String(r.minimum)} and ${String(r.maximum)}.`)}if(l&&a.value&&r.generatesInputValueSockets)for(const t of a.value){if("number"!=typeof t||!qu(t,null!==(p=null===(h=n.variables)||void 0===h?void 0:h.length)&&void 0!==p?p:0))continue;const r=null===(f=e.values)||void 0===f?void 0:f[String(t)];r?rc(r,n,o)!==n.variables[t].type&&Xu(s,`${ee}/values/${t}/type`,`Configured input value socket "${t}" has the wrong type.`):Xu(s,`${ee}/values/${t}`,`Required configured input value socket "${t}" is missing.`)}if(l&&a.value&&r.generatesCaseInputValueSockets){const t=(null===(m=e.values)||void 0===m?void 0:m.default)?rc(e.values.default,n,o):void 0;for(const r of a.value){const i=null===(g=e.values)||void 0===g?void 0:g[String(r)];i?void 0!==t&&rc(i,n,o)!==t&&Xu(s,`${ee}/values/${r}/type`,`Case input value socket "${r}" must match the default socket type.`):Xu(s,`${ee}/values/${r}`,`Required case input value socket "${r}" is missing.`)}}if(l&&a.value&&r.pointerTemplate&&"string"==typeof a.value[0])for(const t of sc(a.value[0])){const r=null===(_=e.values)||void 0===_?void 0:_[t.name],i=null!==(y=null===(v=n.types)||void 0===v?void 0:v.findIndex(e=>e.signature===t.signature))&&void 0!==y?y:-1;r?(i<0||rc(r,n,o)!==i)&&Xu(s,`${ee}/values/${t.name}/type`,`Pointer template input "${t.name}" must have type "${t.signature}".`):Xu(s,`${ee}/values/${t.name}`,`Required pointer template input "${t.name}" is missing.`)}}if("debug/log"===te.operation){const t=null===(b=ne.configuration)||void 0===b?void 0:b.severity,o=null===(x=ne.configuration)||void 0===x?void 0:x.message,r=!!t&&nc(null===(T=e.configuration)||void 0===T?void 0:T.severity,t,n,i),a=!!o&&nc(null===(A=e.configuration)||void 0===A?void 0:A.message,o,n,i),l=r&&a?e.configuration.message.value[0]:"";for(const t of Bu(l).sockets)(null===(w=e.values)||void 0===w?void 0:w[t])||Xu(s,`${ee}/values/${t}`,`Required debug message template input "${t}" is missing.`)}for(const[t,r]of Object.entries(null!==(S=null===(M=ne.inputs)||void 0===M?void 0:M.values)&&void 0!==S?S:{})){if(t.startsWith("[")||(null===(R=e.values)||void 0===R?void 0:R[t])||Xu(s,`${ee}/values/${t}`,`Required input value socket "${t}" is missing.`),"event/send"===te.operation){const t=null===(O=null===(I=null===(C=e.configuration)||void 0===C?void 0:C.event)||void 0===I?void 0:I.value)||void 0===O?void 0:O[0],r="number"==typeof t?null===(F=n.events)||void 0===F?void 0:F[t]:void 0;for(const[t,i]of Object.entries(null!==(E=null==r?void 0:r.values)&&void 0!==E?E:{})){const r=null===(N=e.values)||void 0===N?void 0:N[t];r?rc(r,n,o)!==i.type&&Xu(s,`${ee}/values/${t}/type`,`Custom event input value socket "${t}" has the wrong type.`):Xu(s,`${ee}/values/${t}`,`Required custom event input value socket "${t}" is missing.`)}}const i="number"===r.gltfType?"float":"boolean"===r.gltfType?"bool":r.gltfType,a=null===(L=e.values)||void 0===L?void 0:L[t];if(a&&i&&i in $u){const e=rc(a,n,o);void 0!==e&&(null===(P=null===(k=n.types)||void 0===k?void 0:k[e])||void 0===P?void 0:P.signature)!==i&&Xu(s,`${ee}/values/${t}/type`,`Input value socket "${t}" must have type "${i}".`)}}if(ne.validation)try{const t=ju(e);for(const e of Object.values(null!==(B=t.values)&&void 0!==B?B:{}))void 0===e.type&&(e.type=rc(e,n,o));const r=ne.validation(t,n);r.valid||Xu(s,ee,null!==(D=r.error)&&void 0!==D?D:`Operation "${te.operation}" is invalid.`)}catch(e){Xu(s,ee,e.message)}for(const[r,i]of Object.entries(null!==(V=e.values)&&void 0!==V?V:{}))if(zu(i))if("unsupported-extension"!==te.support||(null===(G=te.source.inputValueSockets)||void 0===G?void 0:G[r])||Xu(s,`${ee}/values/${r}`,`Input value socket "${r}" is not defined by operation "${te.operation}".`),"node"in i){if("value"in i&&Xu(s,`${ee}/values/${r}`,"An input value socket cannot define both inline and node sources."),!qu(i.node,null!==(U=null===($=n.nodes)||void 0===$?void 0:$.length)&&void 0!==U?U:0)){Xu(s,`${ee}/values/${r}/node`,`Node index ${String(i.node)} is out of range.`);continue}i.node>=t&&Xu(s,`${ee}/values/${r}/node`,"Value connections must reference an earlier node."),void 0!==i.type&&Zu(i.type,n,s,`${ee}/values/${r}/type`);const e=n.nodes[i.node];if(qu(e.declaration,o.length)){const t=o[e.declaration],a="unsupported-extension"===t.support?Cu(t.source):Ru(t.source,!1),l=null!==(H=i.socket)&&void 0!==H?H:"value",u=Qu(null===(K=null==a?void 0:a.outputs)||void 0===K?void 0:K.values,l,t,e,n,"value");a&&!u&&Xu(s,`${ee}/values/${r}/socket`,`Output value socket "${l}" does not exist on node ${i.node}.`);const c=null===(W=null===(j=t.source.outputValueSockets)||void 0===j?void 0:j[l])||void 0===W?void 0:W.type,d=null!=c?c:ic(i.node,l,n,o);if(void 0!==i.type){const e=null===(q=null==a?void 0:a.outputs)||void 0===q?void 0:q.values,o=e&&Object.prototype.hasOwnProperty.call(e,l)?e[l]:void 0,u=null==o?void 0:o.gltfType,c="number"===u?"float":"boolean"===u?"bool":"vector2"===u?"float2":"vector3"===u?"float3":"vector4"===u?"float4":u,h=null!==(z=ac(t.operation,l))&&void 0!==z?z:c&&Object.prototype.hasOwnProperty.call($u,c)?c:void 0,p=null===(Y=null===(X=n.types)||void 0===X?void 0:X[i.type])||void 0===Y?void 0:Y.signature;(void 0!==h&&p!==h||void 0===h&&void 0!==d&&i.type!==d)&&Xu(s,`${ee}/values/${r}/type`,`Type assertion does not match output socket "${l}".`)}}}else Ju(i,n,s,`${ee}/values/${r}`);else Xu(s,`${ee}/values/${r}`,`Input value socket "${r}" must be an object.`);for(const[o,r]of Object.entries(null!==(Q=e.flows)&&void 0!==Q?Q:{}))zu(r)?qu(r.node,null!==(J=null===(Z=n.nodes)||void 0===Z?void 0:Z.length)&&void 0!==J?J:0)?r.node<=t&&Xu(s,`${ee}/flows/${o}/node`,"Flow connections must reference a later node."):Xu(s,`${ee}/flows/${o}/node`,`Node index ${String(r.node)} is out of range.`):Xu(s,`${ee}/flows/${o}`,`Output flow socket "${o}" must be an object.`)}function uc(e,t=0,n,o){var s,r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b;const x=[],T=`/extensions/KHR_interactivity/graphs/${t}`;null===e||"object"!=typeof e||Array.isArray(e)?(Xu(x,T,"Behavior graph must be an object."),e={}):e=Wu(e);const A={types:()=>({signature:"custom"}),variables:()=>({type:-1}),events:()=>({}),declarations:()=>({op:""}),nodes:()=>({declaration:-1})};for(const t of["types","variables","events","declarations","nodes"]){const n=e[t];void 0===n||Array.isArray(n)?Array.isArray(n)&&0===n.length?Xu(x,`${T}/${t}`,`"${t}" must contain at least one item when present.`):Array.isArray(n)&&(e[t]=n.map((e,n)=>null===e||"object"!=typeof e||Array.isArray(e)?(Xu(x,`${T}/${t}/${n}`,`Each "${t}" item must be an object.`),A[t]()):e)):(Xu(x,`${T}/${t}`,`"${t}" must be an array when present.`),e[t]=[])}for(let t=0;t<(null!==(r=null===(s=e.events)||void 0===s?void 0:s.length)&&void 0!==r?r:0);t++){const n=e.events[t];void 0===n.values||zu(n.values)?n.values&&0===Object.keys(n.values).length&&Xu(x,`${T}/events/${t}/values`,'"values" must contain at least one property when present.'):(Xu(x,`${T}/events/${t}/values`,'"values" must be an object when present.'),n.values=void 0)}for(let t=0;t<(null!==(a=null===(i=e.declarations)||void 0===i?void 0:i.length)&&void 0!==a?a:0);t++){const n=e.declarations[t];for(const e of["inputValueSockets","outputValueSockets"])void 0===n[e]||zu(n[e])?n[e]&&0===Object.keys(n[e]).length&&Xu(x,`${T}/declarations/${t}/${e}`,`"${e}" must contain at least one property when present.`):(Xu(x,`${T}/declarations/${t}/${e}`,`"${e}" must be an object when present.`),n[e]=void 0)}for(let t=0;t<(null!==(u=null===(l=e.nodes)||void 0===l?void 0:l.length)&&void 0!==u?u:0);t++){const n=e.nodes[t];for(const e of["configuration","values","flows"])void 0===n[e]||zu(n[e])?n[e]&&0===Object.keys(n[e]).length&&Xu(x,`${T}/nodes/${t}/${e}`,`"${e}" must contain at least one property when present.`):(Xu(x,`${T}/nodes/${t}/${e}`,`"${e}" must be an object when present.`),n[e]=void 0)}const w=new Set,M=(null!==(c=e.declarations)&&void 0!==c?c:[]).map((t,o)=>{var s,r,i,a;const l=Object.keys(null!==(s=t.inputValueSockets)&&void 0!==s?s:{}).sort().map(e=>{const n=t.inputValueSockets[e];return`${JSON.stringify(e)}:${zu(n)?String(n.type):"invalid"}`}).join(","),u=`${JSON.stringify(t.op)}:${JSON.stringify(null!==(r=t.extension)&&void 0!==r?r:"")}:${l}`;w.has(u)&&Xu(x,`${T}/declarations/${o}`,"Duplicate equivalent declaration."),w.add(u);const{support:c}=function(e,t,n){const o=e.extension&&n&&!n.has(e.extension)?void 0:Ru(e,!1);return o?e.extension&&o.declarationSchema&&!function(e,t,n){const o=(e,n)=>{const o=Object.keys(null!=e?e:{}).sort(),s=Object.keys(n).sort();return o.length===s.length&&!o.some((e,t)=>e!==s[t])&&o.every(o=>{var s,r;return zu(e[o])&&(null===(r=null===(s=t.types)||void 0===s?void 0:s[e[o].type])||void 0===r?void 0:r.signature)===n[o]})};return o(e.inputValueSockets,n.inputValueSockets)&&o(e.outputValueSockets,n.outputValueSockets)}(e,t,o.declarationSchema)?{mapping:void 0,support:"unsupported-extension"}:{mapping:o,support:e.extension?"extension":"core"}:{mapping:void 0,support:e.extension?"unsupported-extension":"unknown-core"}}(t,e,n);"unknown-core"===c&&Xu(x,`${T}/declarations/${o}/op`,`Unknown core operation "${t.op}".`),t.extension||!t.inputValueSockets&&!t.outputValueSockets||Xu(x,`${T}/declarations/${o}`,"Core operation declarations cannot define dynamic value sockets.");for(const[n,s]of Object.entries(null!==(i=t.inputValueSockets)&&void 0!==i?i:{}))zu(s)?Zu(s.type,e,x,`${T}/declarations/${o}/inputValueSockets/${n}/type`):Xu(x,`${T}/declarations/${o}/inputValueSockets/${n}`,`Input value socket "${n}" must be an object.`);for(const[n,s]of Object.entries(null!==(a=t.outputValueSockets)&&void 0!==a?a:{}))zu(s)?Zu(s.type,e,x,`${T}/declarations/${o}/outputValueSockets/${n}/type`):Xu(x,`${T}/declarations/${o}/outputValueSockets/${n}`,`Output value socket "${n}" must be an object.`);return{index:o,operation:t.extension?`${t.op}:${t.extension}`:t.op,support:c,source:t}}),S=new Set;for(let t=0;t<(null!==(h=null===(d=e.types)||void 0===d?void 0:d.length)&&void 0!==h?h:0);t++){const n=e.types[t].signature;"custom"!==n&&S.has(n)&&Xu(x,`${T}/types/${t}/signature`,`Duplicate built-in type signature "${n}".`),S.add(n),"custom"===n||$u[n]||Xu(x,`${T}/types/${t}/signature`,`Unknown built-in type signature "${n}".`)}for(let t=0;t<(null!==(f=null===(p=e.variables)||void 0===p?void 0:p.length)&&void 0!==f?f:0);t++)Ju(e.variables[t],e,x,`${T}/variables/${t}`);for(let t=0;t<(null!==(g=null===(m=e.events)||void 0===m?void 0:m.length)&&void 0!==g?g:0);t++){const n=e.events[t].id;void 0!==n&&e.events.slice(0,t).some(e=>e.id===n)&&Xu(x,`${T}/events/${t}/id`,`Duplicate event id "${n}".`),e.events[t].values&&Object.prototype.hasOwnProperty.call(e.events[t].values,"event")&&Xu(x,`${T}/events/${t}/values/event`,'Custom event value socket id "event" is reserved.');for(const[n,o]of Object.entries(null!==(_=e.events[t].values)&&void 0!==_?_:{}))zu(o)?Ju(o,e,x,`${T}/events/${t}/values/${n}`):Xu(x,`${T}/events/${t}/values/${n}`,`Event value socket "${n}" must be an object.`)}for(let t=0;t<(null!==(y=null===(v=e.nodes)||void 0===v?void 0:v.length)&&void 0!==y?y:0);t++)lc(e.nodes[t],t,e,M,x,T,o);return{index:t,path:T,name:null!==(b=e.name)&&void 0!==b?b:`Graph ${t+1}`,source:e,effectiveSource:oc(e,M,o),declarations:M,diagnostics:x,valid:!x.some(e=>"error"===e.severity)}}function cc(e,t,n){var o;const s=ju(e),r=[];Array.isArray(s.graphs)||(Xu(r,"/extensions/KHR_interactivity/graphs",'"graphs" must be an array.'),s.graphs=[]),0===s.graphs.length&&Xu(r,"/extensions/KHR_interactivity/graphs","At least one behavior graph is required.");const i=null!==(o=s.graph)&&void 0!==o?o:0,a=qu(i,s.graphs.length)?i:-1;-1===a&&Xu(r,"/extensions/KHR_interactivity/graph",`Default graph index ${String(i)} is out of range.`);const l=s.graphs.map((e,o)=>uc(e,o,t,n));return s.graphs=l.map(e=>e.source),{specificationCommit:Gu,source:s,defaultGraphIndex:a,graphs:l,diagnostics:r}}const dc="/extensions/KHR_interactivity/events/",hc="/extensions/KHR_interactivity/delays/";function pc(e,t){return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function fc(e){if(Array.isArray(e))return e.map(e=>fc(e));if(null!==e&&"object"==typeof e){const t={};for(const[n,o]of Object.entries(e))Object.defineProperty(t,n,{configurable:!0,enumerable:!0,value:fc(o),writable:!0});return t}return e}function mc(e){return null===e||["string","number","boolean"].includes(typeof e)||Array.isArray(e)&&e.every(mc)||"object"==typeof e&&Object.values(e).every(mc)}function gc(e){var t,n,o,s,r;for(const i of e.getAllBlocks()){const e=null===(t=i.metadata)||void 0===t?void 0:t.khrInteractivity;if(e){Object.prototype.hasOwnProperty.call(null!==(n=e.generatedConfiguration)&&void 0!==n?n:{},"eventData")&&(e.generatedConfigurationRuntime||(e.generatedConfigurationRuntime={}),Object.prototype.hasOwnProperty.call(e.generatedConfigurationRuntime,"eventData")||Object.defineProperty(e.generatedConfigurationRuntime,"eventData",{configurable:!0,enumerable:!0,value:Ku(Su(null===(o=i.config)||void 0===o?void 0:o.eventData)),writable:!0}));for(const t of i.dataInputs){if(t.isConnected())continue;const n=null===(s=t.metadata)||void 0===s?void 0:s.khrInteractivity;n?null!==(r=n.runtimeValueSnapshot)&&void 0!==r||(n.runtimeValueSnapshot=Ku(t._defaultValue)):e.generatedInputDefaults&&Object.prototype.hasOwnProperty.call(e.generatedInputDefaults,t.name)||(e.generatedInputDefaults||(e.generatedInputDefaults={}),Object.defineProperty(e.generatedInputDefaults,t.name,{configurable:!0,enumerable:!0,value:Ku(t._defaultValue),writable:!0}))}}}}class _c{constructor(e,t,n=60,o=0,s,r,i){var a,l;this._gltf=t,this._animationTargetFps=n,this._graphIndex=o,this._supportedExtensions=s,this._declarationModels=r,this._types=[],this._mappings=[],this._staticVariables=[],this._events=[],this._internalEventsCounter=0,this._nodes=[],this._insertedBlocks=[],this._canonicalGraph=Wu(null!=i?i:e),this._interactivityGraph=this._declarationModels?oc(e,this._declarationModels,null!==(l=null===(a=this._gltf.nodes)||void 0===a?void 0:a.length)&&void 0!==l?l:0):Wu(e),this._parseTypes(),this._parseDeclarations(),this._parseVariables(),this._parseEvents(),this._parseNodes()}get _strictValidation(){return!!this._declarationModels}_getAllowedDynamicValueSockets(e,t,n){var o,s,r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b;if(("debug/log"===e||"flow/log:BABYLON"===e)&&"input"===n){const n=null===(r=null===(s=null===(o=t.configuration)||void 0===o?void 0:o["debug/log"===e?"message":"messageTemplate"])||void 0===s?void 0:s.value)||void 0===r?void 0:r[0];return new Set("string"==typeof n?Bu(n).sockets:[])}if("event/send"===e&&"input"===n||"event/receive"===e&&"output"===n){const e=null===(l=null===(a=null===(i=t.configuration)||void 0===i?void 0:i.event)||void 0===a?void 0:a.value)||void 0===l?void 0:l[0];if("number"==typeof e)return new Set(Object.keys(null!==(d=null===(c=null===(u=this._interactivityGraph.events)||void 0===u?void 0:u[e])||void 0===c?void 0:c.values)&&void 0!==d?d:{}))}if("variable/set"===e&&"input"===n)return new Set((null!==(f=null===(p=null===(h=t.configuration)||void 0===h?void 0:h.variables)||void 0===p?void 0:p.value)&&void 0!==f?f:[]).map(String));if("math/switch"===e&&"input"===n)return new Set((null!==(_=null===(g=null===(m=t.configuration)||void 0===m?void 0:m.cases)||void 0===g?void 0:g.value)&&void 0!==_?_:[]).map(String));if(("pointer/get"===e||"pointer/set"===e||"pointer/interpolate"===e)&&"input"===n){const e=null===(b=null===(y=null===(v=t.configuration)||void 0===v?void 0:v.pointer)||void 0===y?void 0:y.value)||void 0===b?void 0:b[0];if("string"==typeof e)return new Set(e.split("/").filter(e=>e.startsWith("[")&&!e.startsWith("[[")||e.startsWith("{")&&!e.startsWith("{{")).map(e=>e.substring(1,e.length-1).replace(/~1/g,"/").replace(/~0/g,"~")))}}_getAllowedDynamicFlowSockets(e,t,n){var o,s,r;for(const[i,a]of Object.entries(null!==(o=t.configuration)&&void 0!==o?o:{})){if(!("input"===n?a.generatesInputFlowSockets:a.generatesOutputFlowSockets))continue;const t=null===(r=null===(s=e.configuration)||void 0===s?void 0:s[i])||void 0===r?void 0:r.value,o=t&&t.length>0&&("int"!==a.configurationType||1===t.length)&&t.every(e=>{var t,n;return"number"==typeof e&&Number.isInteger(e)&&e>=(null!==(t=a.minimum)&&void 0!==t?t:-2147483648)&&e<=(null!==(n=a.maximum)&&void 0!==n?n:2147483647)}),l=o?t:a.defaultValue;if("input"===n){const e=Array.isArray(l)&&"number"==typeof l[0]?l[0]:0;return new Set(Array.from({length:e},(e,t)=>String(t)))}return new Set(Array.isArray(l)?l.map(String):[])}}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($u[e.signature])}_parseDeclarations(){var e;if(this._interactivityGraph.declarations)for(let n=0;n<this._interactivityGraph.declarations.length;n++){const o=this._interactivityGraph.declarations[n],s=null===(e=this._declarationModels)||void 0===e?void 0:e[n],r=!o.extension||!this._supportedExtensions||this._supportedExtensions.has(o.extension),i="unsupported-extension"===(null==s?void 0:s.support)?void 0:r?Ru(o,!1):void 0;if(!i&&!o.extension)throw new Error(`Unknown core KHR_interactivity operation "${o.op}".`);const a=null!=i?i:o.extension?Cu(o):void 0;if(!a)throw t.Logger.Error(["No mapping found for declaration",o]),new Error("Error parsing declarations");this._mappings.push({flowGraphMapping:a,fullOperationName:o.extension?o.op+":"+o.extension:o.op,declaration:null!=s?s:{index:n,operation:o.extension?`${o.op}:${o.extension}`:o.op,support:i?o.extension?"extension":"core":"unsupported-extension",source:o}})}}_parseVariables(){if(this._interactivityGraph.variables)for(const e of this._interactivityGraph.variables){const t=this._parseVariable(e);this._staticVariables.push(t)}}_parseVariable(e,n){var o,s;const r=this._types[e.type];if(!r)throw t.Logger.Error(["No type found for variable",e]),new Error("Error parsing variables");if(e.value&&"custom"!==(null===(s=null===(o=this._interactivityGraph.types)||void 0===o?void 0:o[e.type])||void 0===s?void 0:s.signature)&&e.value.length!==r.length)throw t.Logger.Error(["Invalid value length for variable",e,r]),new Error("Error parsing variables");const i=e.value?e.value.slice():[];if(!i.length)switch(r.flowGraphType){case"boolean":i.push(!1);break;case"FlowGraphInteger":i.push(0);break;case"number":i.push(NaN);break;case"string":i.push("");break;case"Vector2":i.push(NaN,NaN);break;case"Vector3":i.push(NaN,NaN,NaN);break;case"Vector4":case"Matrix2D":case"Quaternion":i.push(NaN,NaN,NaN,NaN);break;case"Matrix":for(let e=0;e<16;e++)i.push(NaN);break;case"Matrix3D":for(let e=0;e<9;e++)i.push(NaN)}return"number"===r.elementType&&"string"==typeof i[0]?i[0]=parseFloat(i[0]):"string"===r.flowGraphType&&"string"==typeof i[0]&&(i[0]=this._normalizeStaticReference(i[0])),{type:r.flowGraphType,value:n?n(i,this):i}}_normalizeStaticReference(e){if(!e||e.startsWith(dc)||e.startsWith(hc))return"";if(!e.startsWith("/"))return"";let t=this._gltf;for(const n of e.substring(1).split("/")){const e=n.replace(/~1/g,"/").replace(/~0/g,"~");if(Array.isArray(t)){if(!/^(0|[1-9]\d*)$/.test(e))return"";t=t[parseInt(e,10)]}else{if(null===t||"object"!=typeof t||!Object.prototype.hasOwnProperty.call(t,e))return"";t=t[e]}}return null!==t&&"object"==typeof t?e:""}_parseEvents(){var e;if(!this._interactivityGraph.events)return;const n=new Set(this._interactivityGraph.events.flatMap(e=>void 0===e.id?[]:[e.id])),o=`__babylon_khr_internal_${this._graphIndex}_`;for(const s of this._interactivityGraph.events){let r;if(void 0===s.id){do{r=o+this._internalEventsCounter++}while(n.has(r));n.add(r)}const i={eventId:null!==(e=s.id)&&void 0!==e?e:r};s.values&&(i.eventData=Object.keys(s.values).map(e=>{var n;const o=null===(n=s.values)||void 0===n?void 0:n[e];if(!o)throw t.Logger.Error(["No value found for event key",e]),new Error("Error parsing events");const r=this._types[o.type];if(!r)throw t.Logger.Error(["No type found for event value",o]),new Error("Error parsing events");const i=void 0!==o.value?this._parseVariable(o):void 0;return{id:e,type:r.flowGraphType,eventData:!0,value:i}})),this._events.push(i)}}_parseNodes(){var e;if(this._interactivityGraph.nodes)for(let n=0;n<this._interactivityGraph.nodes.length;n++){const o=this._interactivityGraph.nodes[n];if("number"!=typeof o.declaration)throw t.Logger.Error(["No declaration found for node",o]),new Error("Error parsing nodes");const s=this._mappings[o.declaration];if(!s)throw t.Logger.Error(["No mapping found for node",o]),new Error("Error parsing nodes");if(s.flowGraphMapping.validation){const t=s.flowGraphMapping.validation(o,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[o.declaration].op} - ${t.error}`)}const r=[];"unsupported-extension"===s.declaration.support&&r.push(this._createUnsupportedExtensionBlock(o,n,s));for(let e=0;e<s.flowGraphMapping.blocks.length;e++){const t=s.flowGraphMapping.blocks[e],i=this._getEmptyBlock(t,s.fullOperationName,n,o.declaration,e);this._parseNodeConfiguration(o,i,s.flowGraphMapping,t),r.push(i)}this._nodes.push({blocks:r,fullOperationName:s.fullOperationName})}}_createBlockProvenance(e,t,n,o){return{graphIndex:this._graphIndex,nodeIndex:e,declarationIndex:t,operation:n,role:o,sourcePath:`/extensions/KHR_interactivity/graphs/${this._graphIndex}/nodes/${e}`}}_getEmptyBlock(e,n,o,s,r){return{uniqueId:t.RandomGUID(),className:e,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[],config:{},type:n,metadata:void 0===o?{}:{khrInteractivity:this._createBlockProvenance(o,s,n,null!=r?r:0)}}}_setSocketProvenance(e,t,n,o,s,r,i,a){var l;e.metadata=Object.assign(Object.assign({},null!==(l=e.metadata)&&void 0!==l?l:{}),{khrInteractivity:Object.assign(Object.assign({},this._createBlockProvenance(t,n,o,s)),{kind:r,direction:i,socket:a})})}_getBlockRole(e,t){var n,o,s;return null!==(s=null===(o=null===(n=t.metadata)||void 0===n?void 0:n.khrInteractivity)||void 0===o?void 0:o.role)&&void 0!==s?s:e.indexOf(t)}_createUnsupportedExtensionBlock(e,t,n){var o,s,r,i;const a=this._getEmptyBlock("KHR_interactivity/FlowGraphUnsupportedInteractivityBlock",n.fullOperationName,t,e.declaration,0),l=new Set;for(const e of null!==(o=this._interactivityGraph.nodes)&&void 0!==o?o:[])for(const n of Object.values(null!==(s=e.flows)&&void 0!==s?s:{}))n.node===t&&l.add(null!==(r=n.socket)&&void 0!==r?r:"in");const u=e=>Object.entries(null!=e?e:{}).map(([e,t])=>{var n,o,s;return{name:e,type:null===(n=this._types[t.type])||void 0===n?void 0:n.flowGraphType,signature:null===(s=null===(o=this._interactivityGraph.types)||void 0===o?void 0:o[t.type])||void 0===s?void 0:s.signature}});a.config={operation:n.fullOperationName,inputValueSockets:u(n.declaration.source.inputValueSockets),outputValueSockets:u(n.declaration.source.outputValueSockets),inputFlowSockets:Array.from(l).sort(),outputFlowSockets:Object.keys(null!==(i=e.flows)&&void 0!==i?i:{}).sort()};for(const o of a.config.inputValueSockets){const s=this._createNewSocketConnection(o.name);this._setSocketProvenance(s,t,e.declaration,n.fullOperationName,0,"value","input",o.name),a.dataInputs.push(s)}for(const o of a.config.outputValueSockets){const s=this._createNewSocketConnection(o.name,!0);this._setSocketProvenance(s,t,e.declaration,n.fullOperationName,0,"value","output",o.name),a.dataOutputs.push(s)}for(const o of a.config.inputFlowSockets){const s=this._createNewSocketConnection(o);this._setSocketProvenance(s,t,e.declaration,n.fullOperationName,0,"flow","input",o),a.signalInputs.push(s)}for(const o of a.config.outputFlowSockets){const s=this._createNewSocketConnection(o,!0);this._setSocketProvenance(s,t,e.declaration,n.fullOperationName,0,"flow","output",o),a.signalOutputs.push(s)}return a}_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||!this._strictValidation)&&(!(null==l?void 0:l.validationOnly)&&(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,p,f,m,g,_,v,y,b,x,T,A,w,M,S,R,C,I,O;for(let F=0;F<this._nodes.length;F++){const E=null===(n=this._interactivityGraph.nodes)||void 0===n?void 0:n[F];if(!E)throw t.Logger.Error(["No node found for interactivity node",this._nodes[F]]),new Error("Error parsing node connections");const N=this._nodes[F],L=this._mappings[E.declaration];if(!L)throw t.Logger.Error(["No mapping found for node",E]),new Error("Error parsing node connections");if(0===N.blocks.length){t.Logger.Warn(`Skipping connections for no-op node #${F} (unsupported operation: ${N.fullOperationName})`);continue}const k=E.flows||{},P=Object.keys(k).sort();for(const e of P){const n=k[e];let g=pc(null===(o=L.flowGraphMapping.outputs)||void 0===o?void 0:o.flows,e);this._strictValidation&&(null==g?void 0:g.compatibilityOnly)&&(g=void 0);let _=!1;if(!g)for(const e in null===(s=L.flowGraphMapping.outputs)||void 0===s?void 0:s.flows)if(e.startsWith("[")&&e.endsWith("]")){const t=null===(i=null===(r=L.flowGraphMapping.outputs)||void 0===r?void 0:r.flows)||void 0===i?void 0:i[e];if(!this._strictValidation||!(null==t?void 0:t.compatibilityOnly)){_=!0,g=t;break}}const v=_?this._getAllowedDynamicFlowSockets(E,L.flowGraphMapping,"output"):void 0;if(this._strictValidation&&v&&!v.has(e)&&(g=void 0),!g&&!this._isUnsupportedExtensionBlock(N.blocks[0]))continue;const y=g?_?g.name.replace("$1",e):g.name:e,b=n.node,x=this._nodes[b];if(!x)throw t.Logger.Error(["No node found for input node id",b]),new Error("Error parsing node connections");if(0===x.blocks.length){t.Logger.Warn(`Dropping flow connection from node #${F} "${e}" to no-op node #${b} (unsupported operation: ${x.fullOperationName})`);continue}const T=g&&g.toBlock&&N.blocks.find(e=>e.className===g.toBlock)||N.blocks[0],A=null!==(a=T.signalOutputs.find(e=>e.name===y))&&void 0!==a?a:this._createNewSocketConnection(y,!0);T.signalOutputs.includes(A)||T.signalOutputs.push(A),this._setSocketProvenance(A,F,E.declaration,N.fullOperationName,this._getBlockRole(N.blocks,T),"flow","output",e);const w=null===(l=this._mappings[this._interactivityGraph.nodes[b].declaration])||void 0===l?void 0:l.flowGraphMapping;if(!w)throw t.Logger.Error(["No mapping found for input node",x]),new Error("Error parsing node connections");let M=pc(null===(u=w.inputs)||void 0===u?void 0:u.flows,n.socket||"in");this._strictValidation&&(null==M?void 0:M.compatibilityOnly)&&(M=void 0);let S=!1;if(!M){for(const e in null===(c=w.inputs)||void 0===c?void 0:c.flows)if(e.startsWith("[")&&e.endsWith("]")){const t=null===(h=null===(d=w.inputs)||void 0===d?void 0:d.flows)||void 0===h?void 0:h[e];this._strictValidation&&(null==t?void 0:t.compatibilityOnly)||(S=!0,M=t)}const e=S?this._getAllowedDynamicFlowSockets(this._interactivityGraph.nodes[b],w,"input"):void 0;if(this._strictValidation&&e&&!e.has(null!==(p=n.socket)&&void 0!==p?p:"in")&&(M=void 0),!M&&"in"===(null!==(f=n.socket)&&void 0!==f?f:"in")&&Mu(x.fullOperationName)&&(M={name:"in"}),!M&&!this._isUnsupportedExtensionBlock(x.blocks[0]))continue}const R=M?S?M.name.replace("$1",n.socket||""):M.name:n.socket||"in",C=M&&M.toBlock&&x.blocks.find(e=>e.className===M.toBlock)||x.blocks[0];let I=C.signalInputs.find(e=>e.name===R);I||(I=this._createNewSocketConnection(R),C.signalInputs.push(I)),this._setSocketProvenance(I,b,this._interactivityGraph.nodes[b].declaration,x.fullOperationName,this._getBlockRole(x.blocks,C),"flow","input",null!==(m=n.socket)&&void 0!==m?m:"in"),I.connectedPointIds.push(A.uniqueId),A.connectedPointIds.push(I.uniqueId)}const B=E.values||{},D=Object.keys(B);for(const n of D){const o=B[n];let s=pc(null===(g=L.flowGraphMapping.inputs)||void 0===g?void 0:g.values,n);this._strictValidation&&(null==s?void 0:s.compatibilityOnly)&&(s=void 0);let r=!1;if(!s)for(const e in null===(_=L.flowGraphMapping.inputs)||void 0===_?void 0:_.values)if(e.startsWith("[")&&e.endsWith("]")){const t=null===(y=null===(v=L.flowGraphMapping.inputs)||void 0===v?void 0:v.values)||void 0===y?void 0:y[e];this._strictValidation&&(null==t?void 0:t.compatibilityOnly)||(r=!0,s=t)}const i=r?this._getAllowedDynamicValueSockets(L.fullOperationName,E,"input"):void 0;if(!s||i&&!i.has(n))continue;const a=s?r?s.name.replace("$1",n):s.name:n,l=s&&s.toBlock&&N.blocks.find(e=>e.className===s.toBlock)||N.blocks[0],u=null!==(b=l.dataInputs.find(e=>e.name===a))&&void 0!==b?b:this._createNewSocketConnection(a);l.dataInputs.includes(u)||l.dataInputs.push(u),this._setSocketProvenance(u,F,E.declaration,N.fullOperationName,this._getBlockRole(N.blocks,l),"value","input",n);const c=u.metadata.khrInteractivity;c.sourceValue=fc(null!==(w=null===(A=null===(T=null===(x=this._canonicalGraph.nodes)||void 0===x?void 0:x[F])||void 0===T?void 0:T.values)||void 0===A?void 0:A[n])&&void 0!==w?w:o);const d=!!(null==s?void 0:s.convertConnectedTimeToFrames);if(void 0!==o.value){const t=this._parseVariable(o,s&&s.dataTransformer);e._connectionValues[u.uniqueId]=t,u.defaultValue=t,c.runtimeValue=fc(t.value)}else{if(void 0===o.node)throw t.Logger.Error(["Invalid value for value connection",o]),new Error("Error parsing node connections");{const s=o.node,r=o.socket||"value",i=this._nodes[s];if(!i)throw t.Logger.Error(["No node found for output socket reference",o]),new Error("Error parsing node connections");if(0===i.blocks.length){t.Logger.Warn(`Dropping value connection from no-op node #${s} (unsupported operation: ${i.fullOperationName}) into node #${F} "${n}"; consumer will use type-default value`);continue}const a=null===(M=this._mappings[this._interactivityGraph.nodes[s].declaration])||void 0===M?void 0:M.flowGraphMapping;if(!a)throw t.Logger.Error(["No mapping found for output socket reference",o]),new Error("Error parsing node connections");let l=pc(null===(S=a.outputs)||void 0===S?void 0:S.values,r);this._strictValidation&&(null==l?void 0:l.compatibilityOnly)&&(l=void 0);let c=!1;if(!l){for(const e in null===(R=a.outputs)||void 0===R?void 0:R.values)if(e.startsWith("[")&&e.endsWith("]")){const t=null===(I=null===(C=a.outputs)||void 0===C?void 0:C.values)||void 0===I?void 0:I[e];this._strictValidation&&(null==t?void 0:t.compatibilityOnly)||(c=!0,l=t)}const e=c?this._getAllowedDynamicValueSockets(i.fullOperationName,this._interactivityGraph.nodes[s],"output"):void 0;if(!l||e&&!e.has(r))continue}const h=l?c?l.name.replace("$1",r):null==l?void 0:l.name:r,p=l&&l.toBlock&&i.blocks.find(e=>e.className===l.toBlock)||i.blocks[0];let f=p.dataOutputs.find(e=>e.name===h);f||(f=this._createNewSocketConnection(h,!0),p.dataOutputs.push(f)),this._setSocketProvenance(f,s,this._interactivityGraph.nodes[s].declaration,i.fullOperationName,this._getBlockRole(i.blocks,p),"value","output",r),d?this._connectWithSecondsToFramesConversion(e,f,u,F,E.declaration,N.fullOperationName):(u.connectedPointIds.push(f.uniqueId),f.connectedPointIds.push(u.uniqueId))}}}if(L.flowGraphMapping.interBlockConnectors)for(const e of L.flowGraphMapping.interBlockConnectors){const t=e.input,n=e.output,o=e.isVariable;this._connectFlowGraphNodes(t,n,N.blocks[e.inputBlockIndex],N.blocks[e.outputBlockIndex],o)}if(L.flowGraphMapping.extraProcessor){const n=null===(O=this._interactivityGraph.declarations)||void 0===O?void 0:O[E.declaration];if(!n)throw t.Logger.Error(["No declaration found for extra processor",E]),new Error("Error parsing node connections");N.blocks=L.flowGraphMapping.extraProcessor(E,n,L.flowGraphMapping,this,N.blocks,e,this._gltf)}this._ensureMappedSocketProvenance(F,E,N.blocks,L)}}_ensureMappedSocketProvenance(e,t,n,o){var s,r,i,a,l,u,c,d,h,p,f,m,g;const _=(s,r,i)=>{for(const[a,l]of Object.entries(null!=s?s:{})){if(a.startsWith("[")&&a.endsWith("]")||this._strictValidation&&l.compatibilityOnly)continue;const s=l.toBlock&&n.find(e=>e.className===l.toBlock)||n[0];if(!s)continue;const u="value"===r?"input"===i?s.dataInputs:s.dataOutputs:"input"===i?s.signalInputs:s.signalOutputs;let c=u.find(e=>e.name===l.name);c||(c=this._createNewSocketConnection(l.name,"output"===i),u.push(c)),this._setSocketProvenance(c,e,t.declaration,o.fullOperationName,this._getBlockRole(n,s),r,i,a)}};if(_(null===(s=o.flowGraphMapping.outputs)||void 0===s?void 0:s.values,"value","output"),_(null===(r=o.flowGraphMapping.inputs)||void 0===r?void 0:r.flows,"flow","input"),_(null===(i=o.flowGraphMapping.outputs)||void 0===i?void 0:i.flows,"flow","output"),Mu(o.fullOperationName)){const s=n[0];if(s){let r=s.signalInputs.find(e=>"in"===e.name);r||(r=this._createNewSocketConnection("in"),s.signalInputs.push(r)),this._setSocketProvenance(r,e,t.declaration,o.fullOperationName,this._getBlockRole(n,s),"flow","input","in")}}for(const[t,s]of Object.entries(null!==(a=o.flowGraphMapping.configuration)&&void 0!==a?a:{})){const o=s.toBlock&&n.find(e=>e.className===s.toBlock)||n[0],r=null===(l=null==o?void 0:o.metadata)||void 0===l?void 0:l.khrInteractivity;if(!o||!r)continue;const i=null===(u=o.config)||void 0===u?void 0:u[s.name],a=null!==i&&"object"==typeof i&&Object.prototype.hasOwnProperty.call(i,"value")?i.value:i;r.configuration||(r.configuration={});const f={sourceValue:fc(null===(p=null===(h=null===(d=null===(c=this._canonicalGraph.nodes)||void 0===c?void 0:c[e])||void 0===d?void 0:d.configuration)||void 0===h?void 0:h[t])||void 0===p?void 0:p.value),runtimeValue:fc(a)};Object.defineProperty(r.configuration,t,{configurable:!0,enumerable:!0,value:f,writable:!0})}for(const e of n){const t=null===(f=e.metadata)||void 0===f?void 0:f.khrInteractivity;if(!t)continue;const n=new Set(Object.values(null!==(m=o.flowGraphMapping.configuration)&&void 0!==m?m:{}).filter(n=>n.toBlock?e.className===n.toBlock:0===t.role).map(e=>e.name)),s=new Set(["glTF"]);for(const[o,r]of Object.entries(null!==(g=e.config)&&void 0!==g?g:{})){if(n.has(o)||s.has(o))continue;const e="eventData"===o?Su(r):null!==r&&"object"==typeof r&&Object.prototype.hasOwnProperty.call(r,"value")?r.value:r;mc(e)&&(t.generatedConfiguration||(t.generatedConfiguration={}),Object.defineProperty(t.generatedConfiguration,o,{configurable:!0,enumerable:!0,value:fc(e),writable:!0}))}}}_createNewSocketConnection(e,n){return{uniqueId:t.RandomGUID(),name:e,_connectionType:n?1:0,connectedPointIds:[]}}_isUnsupportedExtensionBlock(e){return"KHR_interactivity/FlowGraphUnsupportedInteractivityBlock"===(null==e?void 0:e.className)}_connectWithSecondsToFramesConversion(e,t,n,o,s,r){const i=this._getEmptyBlock("FlowGraphMultiplyBlock",r,o,s,-1);i.config={type:"number"};const a=this._createNewSocketConnection("a"),l=this._createNewSocketConnection("b"),u=this._createNewSocketConnection("value",!0);i.dataInputs.push(a,l),i.dataOutputs.push(u);const c={type:"number",value:[this._animationTargetFps]};e._connectionValues[l.uniqueId]=c,l.defaultValue=c,a.connectedPointIds.push(t.uniqueId),t.connectedPointIds.push(a.uniqueId),n.connectedPointIds.push(u.uniqueId),u.connectedPointIds.push(n.uniqueId),this._insertedBlocks.push(i)}_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(){var e;const n={uniqueId:t.RandomGUID(),_userVariables:{},_connectionValues:{}};this._parseNodeConnections(n);for(let e=0;e<this._staticVariables.length;e++){const t=this._staticVariables[e];n._userVariables[this.getVariableName(e)]=t}const o=this._nodes.reduce((e,t)=>e.concat(t.blocks),[]).concat(this._insertedBlocks);return{name:null!==(e=this._interactivityGraph.name)&&void 0!==e?e:`Graph ${this._graphIndex+1}`,metadata:{khrInteractivity:{graphIndex:this._graphIndex,specificationCommit:Gu,source:Wu(this._canonicalGraph)}},rightHanded:!0,allBlocks:o,executionContexts:[n]}}}class vc{constructor(e,t){this._prefixes=e,this._fallback=t}addPrefix(e){this._prefixes.unshift(e)}convert(e){for(const{prefix:t,converter:n}of this._prefixes)if(e.startsWith(t))return n.convert(e);return this._fallback.convert(e)}}const yc="/extensions/BABYLON_scene_objects/";class bc{constructor(e,t){this._scene=e,this._tree=t}convert(e){if(!e.startsWith(yc))throw new Error(`BabylonScenePathToObjectConverter: path "${e}" does not start with the expected prefix "${yc}".`);const t=e.slice(34).split("/").filter(e=>e.length>0);if(0===t.length)throw new Error(`BabylonScenePathToObjectConverter: path "${e}" is missing a collection name.`);const n=t[0],o=this._tree[n];if(!o)throw new Error(`BabylonScenePathToObjectConverter: unknown collection "${n}" in path "${e}".`);if(2===t.length&&"length"===t[1])return{object:this._getCollectionArray(n),info:o.length};if(t.length<2)throw new Error(`BabylonScenePathToObjectConverter: path "${e}" is missing an instance id.`);if(!/^\d+$/.test(t[1]))throw new Error(`BabylonScenePathToObjectConverter: invalid uniqueId "${t[1]}" in path "${e}".`);const s=parseInt(t[1],10);if(!Number.isFinite(s)||s<0)throw new Error(`BabylonScenePathToObjectConverter: invalid uniqueId "${t[1]}" in path "${e}".`);const r=this._lookupInstanceByUniqueId(n,s);if(!r)throw new Error(`BabylonScenePathToObjectConverter: no ${n} instance found with uniqueId ${s} (path "${e}").`);if(2===t.length)return{object:r,info:this._buildIdentityAccessor(r)};if(t.length>3)throw new Error(`BabylonScenePathToObjectConverter: nested property paths are not yet supported (path "${e}").`);const i=t[2],a=o.__array__[i];if(!a||"boolean"==typeof a)throw new Error(`BabylonScenePathToObjectConverter: property "${i}" is not registered on ${n} (path "${e}").`);return{object:r,info:a}}_getCollectionArray(e){switch(e){case"transformNodes":return this._scene.transformNodes;case"meshes":return this._scene.meshes;case"materials":return this._scene.materials;default:return[]}}_lookupInstanceByUniqueId(e,t){switch(e){case"transformNodes":return this._scene.transformNodes.find(e=>e.uniqueId===t)||this._scene.meshes.find(e=>e.uniqueId===t);case"meshes":return this._scene.meshes.find(e=>e.uniqueId===t);case"materials":return this._scene.materials.find(e=>e.uniqueId===t);default:return}}_buildIdentityAccessor(e){return{type:"object",get:()=>e,getTarget:()=>e,isReadOnly:!0}}}const xc={isKhrInteractivityRef:!0};class Tc{convert(e){const n=e===dc,o=e.endsWith("/")?e.slice(0,-1):e;if(n||o.startsWith(dc)){const t=o.substring(37);return{object:xc,info:{type:"object",isReadOnly:!0,get:()=>n?e:t.length>0?o:void 0,getTarget:()=>xc}}}const s=o.substring(37),r=/^\d+$/.test(s)?parseInt(s,10):NaN;return{object:xc,info:{type:"object",isReadOnly:!0,get:(e,n,o)=>{const s=o;if(!(!s||isNaN(r)||r<0))return t.IsDelayActive(s,r)?new t.FlowGraphInteger(r):void 0},getTarget:()=>xc}}}}const Ac="/extensions/KHR_interactivity/limits/",wc={major:2,minor:0},Mc=2147483647,Sc={maxActiveAnimations:Mc,maxActiveDelays:Mc,maxActivePropertyInterpolations:Mc,maxActiveVariableInterpolations:Mc},Rc={isKhrInteractivityAssetCapability:!0};class Cc{constructor(e,t){this._gltf=e,this._isExtensionEnabled=t}convert(e){const t=e.endsWith("/")?e.slice(0,-1):e;if(t.startsWith(Ac)){const n=Sc[t.substring(37)];if(void 0===n)throw new Error(`Path ${e} is invalid`);return this._createAccessor("number",()=>n)}const n=t.substring(36);if("majorVersion"===n||"minorVersion"===n)return this._createAccessor("number",()=>{var e;return function(e){const[t,n]=(null!=e?e:"").split("."),o=parseInt(t,10),s=parseInt(n,10);return isNaN(o)?wc:o!==wc.major?o<wc.major?{major:o,minor:isNaN(s)?0:s}:wc:{major:o,minor:Math.min(isNaN(s)?0:s,wc.minor)}}(null===(e=this._gltf.asset)||void 0===e?void 0:e.version)["majorVersion"===n?"major":"minor"]});const o=n.split("/");if(3===o.length&&"extensions"===o[0]&&"enabled"===o[2]){const e=o[1];return this._createAccessor("boolean",()=>this._isExtensionEnabled(e))}throw new Error(`Path ${e} is invalid`)}_createAccessor(e,t){return{object:Rc,info:{type:e,isReadOnly:!0,get:t,getTarget:()=>Rc}}}}class Ic{encodeEventReference(e){return function(e){return dc+e}(e)}decodeEventReference(e){return function(e){return"string"==typeof(t=e)&&t.startsWith(dc)?e.substring(37):void 0;var t}(e)}decodeIndexReference(e,t){if(0===e.length||"/"!==e[0])return;const n=t?`/${t}/`:"/";if(!e.startsWith(n))return;const o=t?e.substring(n.length):e.substring(e.lastIndexOf("/")+1);return/^(0|[1-9]\d*)$/.test(o)?parseInt(o,10):void 0}getObjectReference(e,t){var n,o;const s=null===(o=null===(n=e._internalMetadata)||void 0===n?void 0:n.gltf)||void 0===o?void 0:o.pointers;if(!Array.isArray(s))return;const r=s.filter(e=>"string"==typeof e);if(0!==r.length){if(t){const e=r.find(e=>e.split("/")[1]===t);if(e)return e}return r[0]}}}class Oc extends Error{constructor(e){super(e.map(e=>`${e.path}: ${e.message}`).join("\n")),this.diagnostics=e,this.name="KHRInteractivityExportError"}}const Fc=new Set(["nodes","animations","cameras","materials","meshes","textures","images","samplers","skins","scenes"]),Ec=["KHR_node_hoverability","KHR_node_selectability","KHR_node_visibility"];function Nc(e){const t=e.split("/").map(e=>e.replace(/~1/g,"/").replace(/~0/g,"~")),n=[];for(let e=0;e<t.length-1;e++)"extensions"===t[e]&&t[e+1]&&n.push(t[e+1]);return n}const Lc={number:"float",boolean:"bool",FlowGraphInteger:"int",string:"ref",Vector2:"float2",Vector3:"float3",Vector4:"float4",Quaternion:"float4",Color3:"float3",Color4:"float4",Matrix2D:"float2x2",Matrix3D:"float3x3",Matrix:"float4x4",Mesh:"ref",TransformNode:"ref",Camera:"ref",Light:"ref",Material:"ref",AnimationGroup:"ref"};function kc(e){if(Array.isArray(e))return e.map(e=>kc(e));if(null!==e&&"object"==typeof e){const t={};for(const[n,o]of Object.entries(e))Object.defineProperty(t,n,{configurable:!0,enumerable:!0,value:kc(o),writable:!0});return t}return e}function Pc(e){var t;return null===(t=e.metadata)||void 0===t?void 0:t.khrInteractivity}function Bc(e){var t;return null===(t=e.metadata)||void 0===t?void 0:t.khrInteractivity}function Dc(e,t){return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Vc(e,t){return t?`${e}:${t}`:e}function Gc(e){return e.substring(e.lastIndexOf("/")+1)}function $c(e,t){return e.find(e=>{var n;return(null===(n=Pc(e))||void 0===n?void 0:n.role)===t})}function Uc(e,t,n){for(const o of e)for(const e of o.dataInputs){const o=Bc(e);if((null==o?void 0:o.nodeIndex)===t&&"value"===o.kind&&"input"===o.direction&&o.socket===n)return e}}function Hc(e){return Uu(e)}function Kc(e){return Ku(Array.isArray(e)?e.map(e=>{if(null===e||"object"!=typeof e)return e;const n=e,o="Matrix"===n.type&&Array.isArray(n.value)?Array.from(t.Matrix.FromArray(n.value).asArray()):n.value;return void 0===n.value?e:Object.assign(Object.assign({},n),{value:o})}):e)}function jc(e,t){if(!e||!t||e.length!==t.length)return e===t;for(let n=0;n<e.length;n++)if(!("number"==typeof e[n]&&"number"==typeof t[n]&&Number.isNaN(e[n])&&Number.isNaN(t[n])||e[n]===t[n]))return!1;return!0}function Wc(e,t){if("number"==typeof e&&"number"==typeof t&&Number.isNaN(e)&&Number.isNaN(t))return!0;if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>Wc(e,t[n]));if(null!==e&&null!==t&&"object"==typeof e&&"object"==typeof t){const n=Object.entries(e),o=Object.keys(t);return n.length===o.length&&n.every(([e,n])=>Object.prototype.hasOwnProperty.call(t,e)&&Wc(n,t[e]))}return!1}function qc(e,t){var n;const o=Lc[t];if(!o||!$u[o])return;null!==(n=e.types)&&void 0!==n||(e.types=[]);const s=e.types.findIndex(e=>e.signature===o);return s>=0?s:(e.types.push({signature:o}),e.types.length-1)}function zc(e,t){const n=t.toBlock;return n?e.blocks.find(t=>{var o,s;return t.getClassName()===Gc(n)||(null===(o=Pc(t))||void 0===o?void 0:o.role)===(null===(s=e.mapping)||void 0===s?void 0:s.blocks.indexOf(n))}):$c(e.blocks,0)}function Xc(e,t,n,o,s=!0){var r,i;const a=zc(e,n);if(!a)return;const l=null===(r=a.config)||void 0===r?void 0:r[n.name],u=Yc(e,t,n);if(s&&u&&jc(Hc(l),Hc(u.runtimeValue)))return u.sourceValue?kc(u.sourceValue):void 0;if("variables"===n.indexSource){const e=(Array.isArray(l)?l:[l]).filter(e=>"string"==typeof e).map(e=>/^staticVariable_(0|[1-9]\d*)$/.test(e)?parseInt(e.substring(15),10):-1);return e.every(e=>{var t,n;return e>=0&&e<(null!==(n=null===(t=o.variables)||void 0===t?void 0:t.length)&&void 0!==n?n:0)})?e:void 0}if("events"===n.indexSource){const e=l,t=null===(i=o.events)||void 0===i?void 0:i.findIndex(t=>t.id===e);return void 0!==t&&t>=0?[t]:void 0}return"assetNodes"!==n.indexSource||"string"!=typeof l?"useSlerp"===t?["Quaternion"===l]:Hc(l):void 0}function Yc(e,t,n){var o;const s=zc(e,n);return s?Dc(null===(o=Pc(s))||void 0===o?void 0:o.configuration,t):void 0}function Qc(e,t,n,o){var s,r,i,a,l,u,c,d,h,p;if(!e)return!1;const f=e=>"number"==typeof e&&Number.isInteger(e)&&e>=-2147483648&&e<=2147483647;let m;switch(t.configurationType){case"bool":m=1===e.length&&"boolean"==typeof e[0];break;case"int":m=1===e.length&&f(e[0]);break;case"int[]":m=e.every(f);break;case"string":m=1===e.length&&"string"==typeof e[0];break;default:m=e.length>0}if(!m||void 0!==t.minItems&&e.length<t.minItems)return!1;if(void 0!==t.minimum&&e.some(e=>"number"!=typeof e||e<t.minimum))return!1;if(void 0!==t.maximum&&e.some(e=>"number"!=typeof e||e>t.maximum))return!1;if(t.indexSource){const h={types:null!==(r=null===(s=n.types)||void 0===s?void 0:s.length)&&void 0!==r?r:0,variables:null!==(a=null===(i=n.variables)||void 0===i?void 0:i.length)&&void 0!==a?a:0,events:null!==(u=null===(l=n.events)||void 0===l?void 0:l.length)&&void 0!==u?u:0,nodes:null!==(d=null===(c=n.nodes)||void 0===c?void 0:c.length)&&void 0!==d?d:0,assetNodes:null!=o?o:0};if(e.some(e=>!f(e)||e<0||e>=h[t.indexSource]))return!1}if(t.allowedSignatures){const o=e[0],s="number"==typeof o?null===(p=null===(h=n.types)||void 0===h?void 0:h[o])||void 0===p?void 0:p.signature:void 0;if(!s||!t.allowedSignatures.includes(s))return!1}return!(t.allowedValues&&e.some(e=>!t.allowedValues.includes(e))||t.debugLogTemplate&&("string"!=typeof e[0]||!Bu(e[0]).valid))}function Zc(e,t,n,o,s,r,i){var a;const l=(t,n)=>{var o,i;return r?Xc(r,t,n,s):null===(i=null===(o=e.configuration)||void 0===o?void 0:o[t])||void 0===i?void 0:i.value};if(o.configurationGroup)for(const[e,n]of Object.entries(null!==(a=t.configuration)&&void 0!==a?a:{}))if(n.configurationGroup===o.configurationGroup&&!Qc(l(e,n),n,s,i))return void 0===o.defaultValue?void 0:Hc(o.defaultValue);const u=l(n,o);return Qc(u,o,s,i)?o.uniqueValues?Array.from(new Set(u)):u:void 0===o.defaultValue?void 0:Hc(o.defaultValue)}function Jc(e,t){e.push(Object.assign({severity:"error"},t))}function ed(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}class td{get additionalExtensionsUsed(){return this._additionalExtensionsUsed}constructor(e,t={}){var n,o;this._flowGraphs=e,this._options=t,this._graphAnalyses=[],this._additionalExtensionsUsed=[],this._rootDiagnostics=[],this._isPreflight=!1,this.required=null===(n=t.required)||void 0===n||n,this.additionalExtensionsRequired=Array.from(new Set(null!==(o=t.additionalExtensionsRequired)&&void 0!==o?o:[])).sort(),this._refreshAnalysis()}_refreshAnalysis(){this._rootDiagnostics.length=0,this._graphAnalyses=this._analyzeGraphs(),this._additionalExtensionsUsed=Array.from(new Set([...this._collectAdditionalExtensions(),...this.additionalExtensionsRequired])).sort();const e=this._mergeBuildDiagnostics(this._validateBuildWithSourceIndices()),t=this._graphAnalyses.flatMap(e=>e.nodes.map(t=>({graphIndex:e.graphIndex,nodeIndex:t.sourceIndex,operation:t.operation,blockIds:t.blocks.map(e=>e.uniqueId).sort(),classification:t.classification,diagnostics:t.diagnostics.slice()}))),n=this._sortDiagnostics(this._rootDiagnostics.concat(this._graphAnalyses.flatMap(e=>e.diagnostics.concat(e.nodes.flatMap(e=>e.diagnostics))),e));this._analysis={representable:!n.some(e=>"error"===e.severity),nodes:t,diagnostics:n}}_mergeBuildDiagnostics(e){var t,n;const o=[];for(const s of e){const e=null===(t=/\/nodes\/(\d+)(?:\/|$)/.exec(s.path))||void 0===t?void 0:t[1],r=null!==(n=s.nodeIndex)&&void 0!==n?n:void 0===e?void 0:parseInt(e,10),i=void 0===s.graphIndex?void 0:this._graphAnalyses[s.graphIndex],a=void 0===r||null==i?void 0:i.nodes.find(e=>e.sourceIndex===r);a?(a.diagnostics.some(e=>e.code===s.code&&e.path===s.path&&e.message===s.message)||a.diagnostics.push(Object.assign(Object.assign({},s),{nodeIndex:r})),"error"!==s.severity||"exact"!==a.classification&&"inverse-composite"!==a.classification||(a.classification="lossy")):o.push(s)}return o}analyze(){return this._refreshAnalysis(),{representable:this._analysis.representable,nodes:this._analysis.nodes.map(e=>Object.assign(Object.assign({},e),{blockIds:e.blockIds.slice(),diagnostics:e.diagnostics.slice()})),diagnostics:this._analysis.diagnostics.slice()}}build(e){var t,n,o,s;if(this._refreshAnalysis(),!this._analysis.representable)throw new Oc(this._analysis.diagnostics);const r=[],i=this._graphAnalyses.map(t=>this._buildGraph(t,e,r));if(this._writeCompanionNodeExtensions(e,r),r.some(e=>"error"===e.severity))throw new Oc(this._sortDiagnostics(r));const a=(null===(t=this._options.document)||void 0===t?void 0:t.source)?kc(this._options.document.source):{graphs:[]};a.graphs=i;const l=null!==(s=null!==(n=this._options.defaultGraphIndex)&&void 0!==n?n:null===(o=this._options.document)||void 0===o?void 0:o.defaultGraphIndex)&&void 0!==s?s:0;if(l<0||l>=i.length)throw Jc(r,{code:"GRAPH_COUNT_MISMATCH",path:"/extensions/KHR_interactivity/graph",message:`Default graph index ${l} is outside the exported graph range.`}),new Oc(r);return 0===l&&void 0===a.graph||(a.graph=l),a}_getSourceGraph(e,t){var n,o,s;const r=null===(o=null===(n=this._options.document)||void 0===n?void 0:n.graphs[t])||void 0===o?void 0:o.source;if(r)return Wu(r);const i=null===(s=e.metadata)||void 0===s?void 0:s.khrInteractivity;return(null==i?void 0:i.source)?Wu(i.source):void 0}_validateBuildWithSourceIndices(){const e=[],t=this._options.sourceGLTF,n=e=>void 0!==e&&e>=0?e:void 0,o={getNodeCount:()=>{var e,n;return null!==(n=null===(e=null==t?void 0:t.nodes)||void 0===e?void 0:e.length)&&void 0!==n?n:0},getNodeIndex:e=>{var o;return n(null===(o=null==t?void 0:t.nodes)||void 0===o?void 0:o.findIndex(t=>t._babylonTransformNode===e))},getAnimationIndex:e=>{var o;return n(null===(o=null==t?void 0:t.animations)||void 0===o?void 0:o.findIndex(t=>t._babylonAnimationGroup===e))},getCameraIndex:e=>{var o;return n(null===(o=null==t?void 0:t.cameras)||void 0===o?void 0:o.findIndex(t=>t._babylonCamera===e))},getMaterialIndex:e=>{var o;return n(null===(o=null==t?void 0:t.materials)||void 0===o?void 0:o.findIndex(t=>{var n;return Object.values(null!==(n=t._data)&&void 0!==n?n:{}).some(t=>t.babylonMaterial===e)}))},getRootIndex:(e,t)=>this._getSourceRootIndex(e,t),setNodeExtension:()=>{}};this._isPreflight=!0;try{for(const t of this._graphAnalyses)this._buildGraph(t,o,e);this._writeCompanionNodeExtensions(o,e)}finally{this._isPreflight=!1}return e}_analyzeGraphs(){var e,t,n,o,s;const r=[];if(this._options.document||Jc(this._rootDiagnostics,{code:"GRAPH_SOURCE_MISSING",path:"/extensions/KHR_interactivity",message:"A canonical KHR_interactivity document is required to preserve root metadata and the default graph selection."}),0===this._flowGraphs.length)return Jc(this._rootDiagnostics,{code:"GRAPH_COUNT_MISMATCH",path:"/extensions/KHR_interactivity/graphs",message:"At least one FlowGraph is required for KHR_interactivity export."}),r;for(const n of null!==(t=null===(e=this._options.document)||void 0===e?void 0:e.diagnostics)&&void 0!==t?t:[])Jc(this._rootDiagnostics,{code:"GRAPH_INVALID",path:n.path,message:n.message,severity:n.severity});if(this._options.document&&this._options.document.graphs.length!==this._flowGraphs.length)return Jc(this._rootDiagnostics,{code:"GRAPH_COUNT_MISMATCH",path:"/extensions/KHR_interactivity/graphs",message:`Canonical source has ${this._options.document.graphs.length} graph(s), but ${this._flowGraphs.length} FlowGraph(s) were supplied.`}),r;for(let e=0;e<this._flowGraphs.length;e++){const t=this._flowGraphs[e],i=this._getSourceGraph(t,e),a=[];for(const t of null!==(s=null===(o=null===(n=this._options.document)||void 0===n?void 0:n.graphs[e])||void 0===o?void 0:o.diagnostics)&&void 0!==s?s:[])Jc(a,{code:"GRAPH_INVALID",graphIndex:e,path:t.path,message:t.message,severity:t.severity});if(!i){Jc(a,{code:"GRAPH_SOURCE_MISSING",graphIndex:e,path:`/graphs/${e}`,message:"This FlowGraph has no canonical KHR_interactivity source. Only imported graphs and registered standalone inverse mappings can be exported."});const n=t.getAllBlocks().map(e=>({sourceIndex:-1,declarationIndex:-1,operation:"",blocks:[e],classification:this._classifyStandaloneBlock(e,a),diagnostics:a.filter(t=>t.blockId===e.uniqueId)}));r.push({graph:t,graphIndex:e,source:{},nodes:n,diagnostics:a});continue}r.push({graph:t,graphIndex:e,source:i,nodes:this._analyzeImportedNodes(t,e,i,a),diagnostics:a})}return r}_classifyStandaloneBlock(e,t){const n=Fu().filter(t=>1===t.mapping.blocks.length&&Gc(t.mapping.blocks[0])===e.getClassName()),o=`/blocks/${e.uniqueId}`;return 0===n.length?(Jc(t,{code:"BLOCK_UNSUPPORTED",path:o,blockId:e.uniqueId,message:`FlowGraph block "${e.getClassName()}" has no KHR_interactivity inverse mapping.`}),"unsupported"):(Jc(t,{code:"BLOCK_AMBIGUOUS",path:o,blockId:e.uniqueId,message:1===n.length?`FlowGraph block "${e.getClassName()}" is not associated with canonical KHR source provenance.`:`FlowGraph block "${e.getClassName()}" is ambiguous between ${n.map(e=>Vc(e.op,e.extension)).join(", ")}.`}),"lossy")}_analyzeImportedNodes(e,t,n,o){var s,r,i,a,l,u,c;const d=new Map;for(const n of e.getAllBlocks()){const e=Pc(n);if(!e||e.graphIndex!==t||e.nodeIndex<0){const e=[];this._classifyStandaloneBlock(n,e),o.push(...e),d.set(Number.MIN_SAFE_INTEGER+d.size,[n]);continue}const r=null!==(s=d.get(e.nodeIndex))&&void 0!==s?s:[];r.push(n),d.set(e.nodeIndex,r)}const h=[];for(let e=0;e<(null!==(i=null===(r=n.nodes)||void 0===r?void 0:r.length)&&void 0!==i?i:0);e++){const o=n.nodes[e],s=null===(a=n.declarations)||void 0===a?void 0:a[o.declaration],r=null===(u=null===(l=this._options.document)||void 0===l?void 0:l.graphs[t])||void 0===u?void 0:u.declarations[o.declaration],i=s?Vc(s.op,s.extension):"",p=s&&"unsupported-extension"!==(null==r?void 0:r.support)?Ru(s,!1):void 0,f=null!==(c=d.get(e))&&void 0!==c?c:[],m=[];let g=p&&p.blocks.length>1?"inverse-composite":"exact";s?"BABYLON"===s.extension?(g="unsupported",Jc(m,{code:"BLOCK_UNSUPPORTED",graphIndex:t,nodeIndex:e,path:`/graphs/${t}/nodes/${e}`,message:`Compatibility-only operation "${i}" is not part of ratified KHR_interactivity and cannot be exported as standards-compliant data.`})):p||s.extension?!p&&s.extension?1!==f.length||"FlowGraphUnsupportedInteractivityBlock"!==f[0].getClassName()?(g="unsupported",Jc(m,{code:"BLOCK_TYPE_MISMATCH",graphIndex:t,nodeIndex:e,path:`/graphs/${t}/nodes/${e}`,message:`Unsupported extension operation "${i}" must remain an intact typed no-op block.`})):(this._validateUnsupportedExtensionBlock(n,o,e,i,s,f[0],t,m),m.some(e=>"error"===e.severity)&&(g="lossy")):(this._validateMappedBlocks(t,e,i,p,f,m),m.some(e=>"error"===e.severity)&&(g="lossy")):(g="unsupported",Jc(m,{code:"BLOCK_UNSUPPORTED",graphIndex:t,nodeIndex:e,path:`/graphs/${t}/nodes/${e}`,message:`Unknown core operation "${s.op}" cannot be exported.`})):(g="unsupported",Jc(m,{code:"NODE_SOURCE_MISSING",graphIndex:t,nodeIndex:e,path:`/graphs/${t}/nodes/${e}/declaration`,message:`Declaration index ${o.declaration} is unavailable.`})),0===f.length&&(g="unsupported",Jc(m,{code:"BLOCK_ROLE_MISSING",graphIndex:t,nodeIndex:e,path:`/graphs/${t}/nodes/${e}`,message:`The FlowGraph blocks for "${i}" were removed.`})),d.delete(e),h.push({sourceIndex:e,declarationIndex:o.declaration,operation:i,mapping:p,blocks:f,classification:g,diagnostics:m})}for(const e of d.values()){const t=e[0],n=[],s=this._classifyStandaloneBlock(t,n);o.push(...n),h.push({sourceIndex:-1,declarationIndex:-1,operation:"",blocks:e,classification:s,diagnostics:n})}return h}_validateUnsupportedExtensionBlock(e,n,o,s,r,i,a,l){var u,c,d,h;const p=i.config,f=e=>Array.isArray(e)?e.map(e=>null!==e&&"object"==typeof e?{name:e.name,signature:e.signature}:e).sort((e,t)=>String(JSON.stringify(e)).localeCompare(String(JSON.stringify(t)))):e,m=e=>Array.isArray(e)?e.slice().sort():e,g=t=>Object.entries(null!=t?t:{}).map(([t,n])=>{var o,s;return{name:t,signature:null===(s=null===(o=e.types)||void 0===o?void 0:o[n.type])||void 0===s?void 0:s.signature}}).sort((e,t)=>e.name.localeCompare(t.name)),_=Array.from(new Set((null!==(u=e.nodes)&&void 0!==u?u:[]).flatMap(e=>{var t;return Object.values(null!==(t=e.flows)&&void 0!==t?t:{}).filter(e=>e.node===o).map(e=>{var t;return null!==(t=e.socket)&&void 0!==t?t:"in"})}))).sort(),v=Object.keys(null!==(c=n.flows)&&void 0!==c?c:{}).sort(),y={inputValues:i.dataInputs.map(e=>e.name).sort(),outputValues:i.dataOutputs.map(e=>e.name).sort(),inputFlows:i instanceof t.FlowGraphExecutionBlock?i.signalInputs.map(e=>e.name).sort():[],outputFlows:i instanceof t.FlowGraphExecutionBlock?i.signalOutputs.map(e=>e.name).sort():[]},b={inputValues:Object.keys(null!==(d=r.inputValueSockets)&&void 0!==d?d:{}).sort(),outputValues:Object.keys(null!==(h=r.outputValueSockets)&&void 0!==h?h:{}).sort(),inputFlows:_,outputFlows:v};p.operation===s&&Wc(f(p.inputValueSockets),g(r.inputValueSockets))&&Wc(f(p.outputValueSockets),g(r.outputValueSockets))&&Wc(m(p.inputFlowSockets),_)&&Wc(m(p.outputFlowSockets),v)&&Wc(y,b)||Jc(l,{code:"BLOCK_TYPE_MISMATCH",graphIndex:a,nodeIndex:o,path:`/graphs/${a}/nodes/${o}`,blockId:i.uniqueId,message:`Unsupported extension operation "${s}" has edited socket metadata and can no longer be exported as its canonical typed no-op.`})}_validateMappedBlocks(e,n,o,s,r,i){var a,l,u,c,d,h,p,f,m,g,_,v;for(let t=0;t<s.blocks.length;t++){const a=r.filter(e=>{var n;return(null===(n=Pc(e))||void 0===n?void 0:n.role)===t});0!==a.length?a.length>1?Jc(i,{code:"BLOCK_ROLE_DUPLICATE",graphIndex:e,nodeIndex:n,path:`/graphs/${e}/nodes/${n}`,message:`Composite "${o}" has more than one block for role ${t}.`}):a[0].getClassName()!==Gc(s.blocks[t])&&Jc(i,{code:"BLOCK_TYPE_MISMATCH",graphIndex:e,nodeIndex:n,blockId:a[0].uniqueId,path:`/blocks/${a[0].uniqueId}`,message:`Composite role ${t} must be "${s.blocks[t]}", not "${a[0].getClassName()}".`}):Jc(i,{code:"BLOCK_ROLE_MISSING",graphIndex:e,nodeIndex:n,path:`/graphs/${e}/nodes/${n}`,message:`Composite "${o}" is missing role ${t} (${s.blocks[t]}).`})}for(const t of r){const r=Pc(t);!r||r.nodeIndex!==n||r.operation!==o||r.declarationIndex<0?Jc(i,{code:"BLOCK_PROVENANCE_INVALID",graphIndex:e,nodeIndex:n,blockId:t.uniqueId,path:`/blocks/${t.uniqueId}`,message:`Block provenance no longer identifies the imported "${o}" node.`}):(r.role<-1||r.role>=s.blocks.length)&&Jc(i,{code:"BLOCK_PROVENANCE_INVALID",graphIndex:e,nodeIndex:n,blockId:t.uniqueId,path:`/blocks/${t.uniqueId}`,message:`Block role ${r.role} is not part of the "${o}" inverse mapping.`})}const y=new Map,b=(e,t)=>{var n,o;const s=null!==(n=y.get(e))&&void 0!==n?n:new Set;s.add(t),y.set(e,s);const r=null!==(o=y.get(t))&&void 0!==o?o:new Set;r.add(e),y.set(t,r)};for(const o of null!==(a=s.interBlockConnectors)&&void 0!==a?a:[]){const s=$c(r,o.inputBlockIndex),a=$c(r,o.outputBlockIndex),l=o.isVariable?null==s?void 0:s.dataInputs.find(e=>e.name===o.input):s instanceof t.FlowGraphExecutionBlock?s.signalInputs.find(e=>e.name===o.input):void 0,u=o.isVariable?null==a?void 0:a.dataOutputs.find(e=>e.name===o.output):a instanceof t.FlowGraphExecutionBlock?a.signalOutputs.find(e=>e.name===o.output):void 0;l&&u&&b(l,u),l&&u&&l._connectedPoint.includes(u)||Jc(i,{code:"COMPOSITE_CONNECTION_CHANGED",graphIndex:e,nodeIndex:n,path:`/graphs/${e}/nodes/${n}`,message:`Internal composite connection "${o.output}" -> "${o.input}" was changed.`})}const x=new Set;for(const a of r){const b=Pc(a);for(const[t,s]of Object.entries(null!==(l=null==b?void 0:b.generatedConfiguration)&&void 0!==l?l:{})){const r="eventData"===t?Su(null===(u=a.config)||void 0===u?void 0:u[t]):"outputSignalCount"===t?null!==(p=null!==(d=null===(c=a.outputSignals)||void 0===c?void 0:c.length)&&void 0!==d?d:null===(h=a.executionSignals)||void 0===h?void 0:h.length)&&void 0!==p?p:null===(f=a.config)||void 0===f?void 0:f[t]:null===(m=a.config)||void 0===m?void 0:m[t],l=null!==(g=Dc(null==b?void 0:b.generatedConfigurationRuntime,t))&&void 0!==g?g:"eventData"===t?Kc(s):void 0,_=l?"eventData"===t?Kc(r):Ku(r):void 0;(l?l.unrepresentable||(null==_?void 0:_.unrepresentable)||(null==_?void 0:_.runtimeValueFingerprint)!==l.runtimeValueFingerprint:!Wc(r,s))&&Jc(i,{code:"CONFIGURATION_UNREPRESENTABLE",graphIndex:e,nodeIndex:n,blockId:a.uniqueId,path:`/blocks/${a.uniqueId}/config/${t}`,message:`Importer-generated configuration "${t}" was changed and no longer represents "${o}".`})}for(const t of a.dataInputs){if(t.isConnected()||Bc(t))continue;const o=Dc(null==b?void 0:b.generatedInputDefaults,t.name),s=Ku(t._defaultValue);(!o||o.unrepresentable||s.unrepresentable||s.runtimeValueFingerprint!==o.runtimeValueFingerprint)&&Jc(i,{code:"INPUT_DEFAULT_UNREPRESENTABLE",graphIndex:e,nodeIndex:n,blockId:a.uniqueId,socket:t.name,path:`/blocks/${a.uniqueId}/dataInputs/${t.name}`,message:(null==o?void 0:o.unrepresentable)?`Importer-generated input default "${t.name}" could not be preserved safely for inverse export.`:o?`Importer-generated input default "${t.name}" was changed and has no KHR_interactivity inverse mapping.`:`Input default "${t.name}" has no import-time provenance or KHR_interactivity inverse mapping.`})}if((null!==(_=null==b?void 0:b.role)&&void 0!==_?_:0)<0)continue;const T=[...a.dataInputs,...a.dataOutputs,...a instanceof t.FlowGraphExecutionBlock?a.signalInputs:[],...a instanceof t.FlowGraphExecutionBlock?a.signalOutputs:[]];for(const t of T){if(!t.isConnected()||x.has(t))continue;const l=null!==(v=Bc(t))&&void 0!==v?v:this._inferSocketProvenance(t,{sourceIndex:n,declarationIndex:-1,operation:o,mapping:s,blocks:r,classification:"exact",diagnostics:i}),u=t._connectedPoint.filter(e=>{var n,o;const s=r.includes(e._ownerBlock),i=s&&-1===(null===(n=Pc(e._ownerBlock))||void 0===n?void 0:n.role);return s?!((null===(o=y.get(t))||void 0===o?void 0:o.has(e))||l&&i):!l});u.length>0&&(x.add(t),u.forEach(e=>x.add(e)),Jc(i,{code:"SOCKET_PROVENANCE_MISSING",graphIndex:e,nodeIndex:n,blockId:a.uniqueId,socket:t.name,path:`/blocks/${a.uniqueId}/${t.name}`,message:`Connection from socket "${t.name}" is not part of the "${o}" inverse mapping.`}))}}}_buildGraph(e,t,n){var o,s,r;const i=Wu(e.source),a=null!==(o=e.source.name)&&void 0!==o?o:`Graph ${e.graphIndex+1}`;void 0!==e.source.name||e.graph.name!==a?i.name=e.graph.name:delete i.name,this._updateVariables(i,e.graph,n,e.graphIndex);const l=new Map(e.nodes.filter(e=>e.sourceIndex>=0).map(e=>[e.sourceIndex,e])),u=(null!==(s=i.nodes)&&void 0!==s?s:[]).map((o,s)=>{const r=l.get(s);return this._rebuildNode(i,o,r,e,t,n)}),c=this._topologicallyOrderNodes(u,e.graphIndex,n);if(!c)return i;void 0!==e.source.nodes||c.nodes.length>0?i.nodes=c.nodes:delete i.nodes,this._remapGraphReferences(i,t,n,e.graphIndex,c.sourceIndices);const d=uc(i,e.graphIndex,new Set(this.additionalExtensionsUsed),t.getNodeCount());for(const t of d.diagnostics)if("error"===t.severity){const o=null===(r=/\/nodes\/(\d+)(?:\/|$)/.exec(t.path))||void 0===r?void 0:r[1],s=void 0===o?void 0:parseInt(o,10);Jc(n,{code:"GRAPH_INVALID",graphIndex:e.graphIndex,nodeIndex:void 0===s?void 0:c.sourceIndices[s],path:t.path,message:t.message})}return i}_rebuildNode(e,n,o,s,r,i){var a,l,u,c,d,h,p,f,m;const g=kc(n),_=o.mapping;_&&this._rebuildConfiguration(e,g,o,s.graphIndex,r,i);for(const t of Object.keys(null!==(a=n.values)&&void 0!==a?a:{}).sort()){if(_){const r=this._isEffectiveValueInput(e,n,o,t,!1),a=this._isEffectiveValueInput(e,n,o,t,!0);if(!r){a&&Jc(i,{code:"CONFIGURATION_UNREPRESENTABLE",graphIndex:s.graphIndex,nodeIndex:o.sourceIndex,socket:t,path:`/graphs/${s.graphIndex}/nodes/${o.sourceIndex}/values/${t}`,message:`Configuration edits made formerly ignored value socket "${t}" effective without an authored FlowGraph socket.`});continue}if(!a){delete g.values[t];continue}}const r=Uc(o.blocks,o.sourceIndex,t);if(!r){Jc(i,{code:"SOCKET_PROVENANCE_MISSING",graphIndex:s.graphIndex,nodeIndex:o.sourceIndex,socket:t,path:`/graphs/${s.graphIndex}/nodes/${o.sourceIndex}/values/${t}`,message:`Input value socket "${t}" no longer has KHR_interactivity provenance.`});continue}const a=this._getMappingObject(null===(l=null==_?void 0:_.inputs)||void 0===l?void 0:l.values,t);g.values[t]=this._rebuildInputValue(e,n.values[t],r,a,o,s,i)}g.values&&0===Object.keys(g.values).length&&delete g.values;const v=new Map;for(const r of o.blocks)if(r instanceof t.FlowGraphExecutionBlock)for(const t of r.signalOutputs){const r=null!==(u=Bc(t))&&void 0!==u?u:this._inferSocketProvenance(t,o);if((null==r?void 0:r.nodeIndex)===o.sourceIndex&&"flow"===r.kind&&"output"===r.direction){if(!this._isEffectiveFlowOutput(e,n,o,r.socket,!0)){t.isConnected()&&Jc(i,{code:"CONFIGURATION_UNREPRESENTABLE",graphIndex:s.graphIndex,nodeIndex:o.sourceIndex,socket:r.socket,path:`/graphs/${s.graphIndex}/nodes/${o.sourceIndex}/flows/${r.socket}`,message:`Flow socket "${r.socket}" is connected but disabled by the edited configuration.`});continue}v.has(r.socket)?Jc(i,{code:"SOCKET_CONNECTION_AMBIGUOUS",graphIndex:s.graphIndex,nodeIndex:o.sourceIndex,socket:r.socket,path:`/graphs/${s.graphIndex}/nodes/${o.sourceIndex}/flows/${r.socket}`,message:`Multiple FlowGraph outputs map to KHR flow socket "${r.socket}".`}):v.set(r.socket,t)}}const y={};for(const[t,r]of Object.entries(null!==(c=n.flows)&&void 0!==c?c:{})){const a=this._isEffectiveFlowOutput(e,n,o,t,!1),l=this._isEffectiveFlowOutput(e,n,o,t,!0);a||(l?Jc(i,{code:"CONFIGURATION_UNREPRESENTABLE",graphIndex:s.graphIndex,nodeIndex:o.sourceIndex,socket:t,path:`/graphs/${s.graphIndex}/nodes/${o.sourceIndex}/flows/${t}`,message:`Configuration edits made formerly ignored flow socket "${t}" effective without a live FlowGraph connection.`}):ed(y,t,kc(r)))}for(const[t,r]of[...v.entries()].sort(([e],[t])=>e.localeCompare(t))){if(0===r._connectedPoint.length){const r=null===(d=n.flows)||void 0===d?void 0:d[t];if(r){const n=this._isNoOpFlowTarget(e,s,r,!1),a=this._isNoOpFlowTarget(e,s,r,!0);n&&a?ed(y,t,kc(r)):n&&!a&&Jc(i,{code:"CONFIGURATION_UNREPRESENTABLE",graphIndex:s.graphIndex,nodeIndex:o.sourceIndex,socket:t,path:`/graphs/${s.graphIndex}/nodes/${o.sourceIndex}/flows/${t}`,message:`Configuration edits made formerly ignored flow target "${null!==(h=r.socket)&&void 0!==h?h:"in"}" effective without a live FlowGraph connection.`})}continue}if(r._connectedPoint.length>1){Jc(i,{code:"SOCKET_CONNECTION_AMBIGUOUS",graphIndex:s.graphIndex,nodeIndex:o.sourceIndex,socket:t,path:`/graphs/${s.graphIndex}/nodes/${o.sourceIndex}/flows/${t}`,message:`KHR output flow "${t}" must connect to exactly one target; found ${r._connectedPoint.length}.`});continue}const a=r._connectedPoint[0],l=Pc(a._ownerBlock),u=l?s.nodes.find(e=>e.sourceIndex===l.nodeIndex):void 0,c=null!==(p=Bc(a))&&void 0!==p?p:u?this._inferSocketProvenance(a,u):void 0;if(!c||"flow"!==c.kind||"input"!==c.direction){Jc(i,{code:"SOCKET_TARGET_UNREPRESENTABLE",graphIndex:s.graphIndex,nodeIndex:o.sourceIndex,socket:t,path:`/graphs/${s.graphIndex}/nodes/${o.sourceIndex}/flows/${t}`,message:`Flow target for "${t}" is not part of a representable KHR node.`});continue}if(u){const n=null===(f=e.nodes)||void 0===f?void 0:f[u.sourceIndex];if(n&&!this._isEffectiveFlowInput(e,n,u,c.socket,!0)){Jc(i,{code:"CONFIGURATION_UNREPRESENTABLE",graphIndex:s.graphIndex,nodeIndex:o.sourceIndex,socket:t,path:`/graphs/${s.graphIndex}/nodes/${o.sourceIndex}/flows/${t}`,message:`Flow target socket "${c.socket}" is disabled by the target node's edited configuration.`});continue}}const g=(null===(m=n.flows)||void 0===m?void 0:m[t])?kc(n.flows[t]):{node:c.nodeIndex};g.node=c.nodeIndex,"in"===c.socket?delete g.socket:g.socket=c.socket,ed(y,t,g)}return Object.keys(y).length>0?g.flows=y:delete g.flows,_&&this._remapPointerTemplateInputs(e,g,o,s.graphIndex,r,i),g}_getMappingObject(e,t){var n;return Dc(e,t)||(null===(n=Object.entries(null!=e?e:{}).find(([e])=>e.startsWith("[")&&e.endsWith("]")))||void 0===n?void 0:n[1])}_inferSocketProvenance(e,n){var o,s,r,i;const a=n.mapping,l=e._ownerBlock,u=Pc(l);if(!a||!u||u.role<0)return;const c=l.dataInputs.includes(e),d=l.dataOutputs.includes(e),h=l instanceof t.FlowGraphExecutionBlock&&l.signalInputs.includes(e),p=l instanceof t.FlowGraphExecutionBlock&&l.signalOutputs.includes(e),f=c||d?"value":"flow",m=c||h?"input":"output";if(!(c||d||h||p))return;const g="value"===f?"input"===m?null===(o=a.inputs)||void 0===o?void 0:o.values:null===(s=a.outputs)||void 0===s?void 0:s.values:"input"===m?null===(r=a.inputs)||void 0===r?void 0:r.flows:null===(i=a.outputs)||void 0===i?void 0:i.flows;for(const[t,n]of Object.entries(null!=g?g:{})){if(n.compatibilityOnly)continue;if((n.toBlock?a.blocks.indexOf(n.toBlock):0)!==u.role)continue;let o;if(t.startsWith("[")&&t.endsWith("]")){if("flow"!==f||"input"!==m)continue;const[t,s=""]=n.name.split("$1");e.name.startsWith(t)&&e.name.endsWith(s)&&(o=e.name.substring(t.length,e.name.length-s.length))}else n.name===e.name&&(o=t);if(void 0!==o)return Object.assign(Object.assign({},u),{kind:f,direction:m,socket:o})}return"flow"===f&&"input"===m&&"in"===e.name&&Mu(n.operation)?Object.assign(Object.assign({},u),{kind:f,direction:m,socket:"in"}):void 0}_isNoOpFlowTarget(e,t,n,o){var s,r,i,a,l,u;const c=null===(s=e.nodes)||void 0===s?void 0:s[n.node],d=c?null===(r=e.declarations)||void 0===r?void 0:r[c.declaration]:void 0;if(!d)return!1;const h=Ru(d,!1);if(!h)return!1;const p=null!==(i=n.socket)&&void 0!==i?i:"in",f=Dc(null===(a=h.inputs)||void 0===a?void 0:a.flows,p);if(f&&!f.compatibilityOnly)return!1;if(Object.keys(null!==(u=null===(l=h.inputs)||void 0===l?void 0:l.flows)&&void 0!==u?u:{}).some(e=>e.startsWith("[")&&e.endsWith("]"))){const s=t.nodes.find(e=>e.sourceIndex===n.node),r=this._getAllowedDynamicFlowSockets(c,h,"input",o?s:void 0,e);return!!r&&!r.has(p)}return!("in"===p&&Mu(Vc(d.op,d.extension)))}_isEffectiveFlowInput(e,t,n,o,s){var r,i,a;const l=n.mapping;if(!l)return!0;const u=Dc(null===(r=l.inputs)||void 0===r?void 0:r.flows,o);if(u&&!u.compatibilityOnly)return!0;if(Object.keys(null!==(a=null===(i=l.inputs)||void 0===i?void 0:i.flows)&&void 0!==a?a:{}).some(e=>e.startsWith("[")&&e.endsWith("]"))){const r=this._getAllowedDynamicFlowSockets(t,l,"input",s?n:void 0,e);return!r||r.has(o)}return"in"===o&&Mu(n.operation)}_isEffectiveFlowOutput(e,t,n,o,s){var r,i,a;const l=null===(i=null===(r=n.mapping)||void 0===r?void 0:r.outputs)||void 0===i?void 0:i.flows;if(!n.mapping)return Object.prototype.hasOwnProperty.call(null!==(a=t.flows)&&void 0!==a?a:{},o);const u=Dc(l,o);if(u&&!u.compatibilityOnly)return!0;if(!Object.keys(null!=l?l:{}).some(e=>e.startsWith("[")&&e.endsWith("]")))return!1;const c=n.mapping?this._getAllowedDynamicFlowSockets(t,n.mapping,"output",s?n:void 0,e):void 0;return!c||c.has(o)}_getAllowedDynamicFlowSockets(e,t,n,o,s){var r,i,a,l,u;for(const[c,d]of Object.entries(null!==(r=t.configuration)&&void 0!==r?r:{})){if(!("input"===n?d.generatesInputFlowSockets:d.generatesOutputFlowSockets))continue;const r=s?Zc(e,t,c,d,s,o,null===(a=null===(i=this._options.sourceGLTF)||void 0===i?void 0:i.nodes)||void 0===a?void 0:a.length):null===(u=null===(l=e.configuration)||void 0===l?void 0:l[c])||void 0===u?void 0:u.value,h=null!=r?r:Array.isArray(d.defaultValue)?d.defaultValue:[d.defaultValue];if("input"===n){const e="number"==typeof h[0]&&Number.isInteger(h[0])&&h[0]>=0?h[0]:0;return new Set(Array.from({length:e},(e,t)=>String(t)))}return new Set(h.filter(e=>void 0!==e).map(String))}}_resolveValueTypeIndex(e,t,n){var o;return"node"in t?this._resolveOutputTypeIndex(e,t.node,null!==(o=t.socket)&&void 0!==o?o:"value",n):t.type}_resolveOutputTypeIndex(e,t,n,o=new Set){var s,r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b,x,T,A,w,M,S,R;const C=`${t}:${n}`;if(o.has(C))return;o.add(C);const I=null===(s=e.nodes)||void 0===s?void 0:s[t],O=I?null===(r=e.declarations)||void 0===r?void 0:r[I.declaration]:void 0;if(!I||!O)return;const F=null===(a=null===(i=O.outputValueSockets)||void 0===i?void 0:i[n])||void 0===a?void 0:a.type;if(void 0!==F)return F;if("pointer/get"===O.op&&"value"===n){const e=null===(c=null===(u=null===(l=I.configuration)||void 0===l?void 0:l.type)||void 0===u?void 0:u.value)||void 0===c?void 0:c[0];return"number"==typeof e?e:void 0}if("variable/get"===O.op&&"value"===n){const t=null===(p=null===(h=null===(d=I.configuration)||void 0===d?void 0:d.variable)||void 0===h?void 0:h.value)||void 0===p?void 0:p[0];return"number"==typeof t?null===(m=null===(f=e.variables)||void 0===f?void 0:f[t])||void 0===m?void 0:m.type:void 0}if("math/switch"===O.op&&"value"===n){const t=null===(g=I.values)||void 0===g?void 0:g.default;return t?this._resolveValueTypeIndex(e,t,o):void 0}if("event/receive"===O.op&&"event"!==n){const t=null===(y=null===(v=null===(_=I.configuration)||void 0===_?void 0:_.event)||void 0===v?void 0:v.value)||void 0===y?void 0:y[0];return"number"==typeof t?null===(A=null===(T=null===(x=null===(b=e.events)||void 0===b?void 0:b[t])||void 0===x?void 0:x.values)||void 0===T?void 0:T[n])||void 0===A?void 0:A.type:void 0}const E=Ru(O,!1),N=this._getMappingObject(null===(w=null==E?void 0:E.outputs)||void 0===w?void 0:w.values,n),L=null==N?void 0:N.gltfType,k="number"===L?"float":"boolean"===L?"bool":"vector2"===L?"float2":"vector3"===L?"float3":"vector4"===L?"float4":L;if(k&&Object.prototype.hasOwnProperty.call($u,k)){const t=null!==(S=null===(M=e.types)||void 0===M?void 0:M.findIndex(e=>e.signature===k))&&void 0!==S?S:-1;return t>=0?t:void 0}const P=(null==N?void 0:N.typeSourceInput)?null===(R=I.values)||void 0===R?void 0:R[N.typeSourceInput]:void 0;return P?this._resolveValueTypeIndex(e,P,o):void 0}_isEffectiveValueInput(e,t,n,o,s){var r,i,a,l,u,c,d,h,p,f;const m=null===(i=null===(r=n.mapping)||void 0===r?void 0:r.inputs)||void 0===i?void 0:i.values,g=Dc(m,o);if(g&&!g.compatibilityOnly)return!0;if(!Object.keys(null!=m?m:{}).some(e=>e.startsWith("[")&&e.endsWith("]")))return!1;const _=o=>{var r,i,a,l;const u=null===(i=null===(r=n.mapping)||void 0===r?void 0:r.configuration)||void 0===i?void 0:i[o];return u?Zc(t,n.mapping,o,u,e,s?n:void 0,null===(l=null===(a=this._options.sourceGLTF)||void 0===a?void 0:a.nodes)||void 0===l?void 0:l.length):void 0};switch(n.operation){case"debug/log":{const e=null===(a=_("message"))||void 0===a?void 0:a[0];return"string"==typeof e&&Bu(e).sockets.includes(o)}case"event/send":{const t=null===(l=_("event"))||void 0===l?void 0:l[0];return"number"==typeof t&&Object.prototype.hasOwnProperty.call(null!==(d=null===(c=null===(u=e.events)||void 0===u?void 0:u[t])||void 0===c?void 0:c.values)&&void 0!==d?d:{},o)}case"variable/set":return(null!==(h=_("variables"))&&void 0!==h?h:[]).map(String).includes(o);case"math/switch":return(null!==(p=_("cases"))&&void 0!==p?p:[]).map(String).includes(o);case"pointer/get":case"pointer/set":case"pointer/interpolate":{const e=null===(f=_("pointer"))||void 0===f?void 0:f[0];return"string"==typeof e&&e.split("/").some(e=>(e.startsWith("[")&&!e.startsWith("[[")||e.startsWith("{")&&!e.startsWith("{{"))&&e.substring(1,e.length-1).replace(/~1/g,"/").replace(/~0/g,"~")===o)}default:return!0}}_rebuildInputValue(e,n,o,s,r,i,a){var l,u,c,d,h,p,f,m;let g=o._connectedPoint[0];if(o.isConnected()&&(null==s?void 0:s.convertConnectedTimeToFrames)&&(g=this._unwrapAnimationTimeHelper(o,r,i,a)),g){const t=Bc(g);if(!t||"value"!==t.kind||"output"!==t.direction)return Jc(a,{code:"SOCKET_TARGET_UNREPRESENTABLE",graphIndex:i.graphIndex,nodeIndex:r.sourceIndex,path:`/graphs/${i.graphIndex}/nodes/${r.sourceIndex}/values`,message:"Value input is connected to a block without representable KHR output provenance."}),n;const o=kc(n);if(delete o.value,o.node=t.nodeIndex,"value"===t.socket?delete o.socket:o.socket=t.socket,void 0!==o.type){const n=this._resolveOutputTypeIndex(e,t.nodeIndex,t.socket);void 0!==n&&(o.type=n)}return o}const _=Bc(o),v=null==_?void 0:_.sourceValue,y=Hc(o._defaultValue),b=Ku(o._defaultValue),x=v&&!("node"in v)?function(e,n,o){var s,r;const i=void 0===n||null===(r=null===(s=e.types)||void 0===s?void 0:s[n])||void 0===r?void 0:r.signature,a=Array.isArray(o)?o:Hc(o);return Ku("float4x4"===i&&a?t.Matrix.FromArray(a):a)}(e,v.type,null!==(l=null==_?void 0:_.runtimeValue)&&void 0!==l?l:v.value):void 0,T=null!==(u=null==_?void 0:_.runtimeValueSnapshot)&&void 0!==u?u:x;if(!o.isConnected()&&T&&!T.unrepresentable&&!b.unrepresentable&&b.runtimeValueFingerprint===T.runtimeValueFingerprint&&v)return kc(v);if(!o.isConnected()&&(null==_?void 0:_.runtimeValue)&&jc(y,_.runtimeValue)&&_.sourceValue)return kc(_.sourceValue);const A=null!==(c=null==_?void 0:_.sourceValue)&&void 0!==c?c:n,w=null!==(d=A.type)&&void 0!==d?d:function(e,t,n,o,s){var r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b;if("variable/set"===o.operation&&/^(0|[1-9]\d*)$/.test(s))return null===(i=null===(r=e.variables)||void 0===r?void 0:r[parseInt(s,10)])||void 0===i?void 0:i.type;if("event/send"===o.operation){const t=null===(l=null===(a=o.mapping)||void 0===a?void 0:a.configuration)||void 0===l?void 0:l.event,n=t?null===(u=Xc(o,"event",t,e))||void 0===u?void 0:u[0]:void 0;if("number"==typeof n)return null===(p=null===(h=null===(d=null===(c=e.events)||void 0===c?void 0:c[n])||void 0===d?void 0:d.values)||void 0===h?void 0:h[s])||void 0===p?void 0:p.type}if("pointer/get"===o.operation||"pointer/set"===o.operation||"pointer/interpolate"===o.operation){const t=null===(m=null===(f=o.mapping)||void 0===f?void 0:f.configuration)||void 0===m?void 0:m.pointer,n=t?null===(g=Xc(o,"pointer",t,e))||void 0===g?void 0:g[0]:void 0;if("string"==typeof n){const t=n.split("/").find(e=>e===`[${s}]`||e===`{${s}}`),o=(null==t?void 0:t.startsWith("["))?"int":(null==t?void 0:t.startsWith("{"))?"ref":void 0;if(o){const t=null!==(v=null===(_=e.types)||void 0===_?void 0:_.findIndex(e=>e.signature===o))&&void 0!==v?v:-1;return t>=0?t:(null!==(y=e.types)&&void 0!==y||(e.types=[]),e.types.push({signature:o}),e.types.length-1)}}}const x=null==n?void 0:n.gltfType,T="number"===x?"float":"boolean"===x?"bool":"vector2"===x?"float2":"vector3"===x?"float3":"vector4"===x?"float4":x&&"any"!==x?x:Lc[t.richType.typeName];if(!T||!$u[T])return;null!==(b=e.types)&&void 0!==b||(e.types=[]);const A=e.types.findIndex(e=>e.signature===T);return A>=0?A:(e.types.push({signature:T}),e.types.length-1)}(e,o,s,r,null!==(h=null==_?void 0:_.socket)&&void 0!==h?h:o.name);if(void 0===w||!(null===(p=e.types)||void 0===p?void 0:p[w]))return Jc(a,{code:"VALUE_UNREPRESENTABLE",graphIndex:i.graphIndex,nodeIndex:r.sourceIndex,path:`/graphs/${i.graphIndex}/nodes/${r.sourceIndex}/values`,message:"A newly inlined value has no canonical KHR type."}),n;const M="node"in A?void 0:A,S=M?function(e,t,n,o=60){var s,r,i,a,l;const u=null!==(i=null===(r=null===(s=e.types)||void 0===s?void 0:s[t.type])||void 0===r?void 0:r.signature)&&void 0!==i?i:"custom",c=null!==(l=null===(a=t.value)||void 0===a?void 0:a.slice())&&void 0!==l?l:function(e){switch(e){case"bool":return[!1];case"int":return[0];case"ref":return[""];case"float":return[NaN];case"float2":return[NaN,NaN];case"float3":return[NaN,NaN,NaN];case"float4":case"float2x2":return[NaN,NaN,NaN,NaN];case"float3x3":return[NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN];case"float4x4":return[NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN];default:return[]}}(u);return(null==n?void 0:n.convertConnectedTimeToFrames)&&1===c.length&&"number"==typeof c[0]&&(c[0]*=o),c}(e,M,s,null!==(f=this._options.targetFps)&&void 0!==f?f:60):void 0;if(jc(y,S))return kc(A);if(!y)return Jc(a,{code:"VALUE_UNREPRESENTABLE",graphIndex:i.graphIndex,nodeIndex:r.sourceIndex,path:`/graphs/${i.graphIndex}/nodes/${r.sourceIndex}/values`,message:"The FlowGraph input value cannot be converted to a KHR value array."}),n;(null==s?void 0:s.convertConnectedTimeToFrames)&&1===y.length&&"number"==typeof y[0]&&(y[0]/=null!==(m=this._options.targetFps)&&void 0!==m?m:60);const R=kc(A);return delete R.node,delete R.socket,R.type=w,R.value=y,R}_unwrapAnimationTimeHelper(e,t,n,o){var s,r,i;const a=n.graphIndex,l=e._connectedPoint[0],u=null==l?void 0:l._ownerBlock,c=u?Pc(u):void 0;if(!u||"FlowGraphMultiplyBlock"!==u.getClassName()||-1!==(null==c?void 0:c.role)||c.nodeIndex!==t.sourceIndex)return void Jc(o,{code:"COMPOSITE_CONNECTION_CHANGED",graphIndex:a,nodeIndex:t.sourceIndex,blockId:null==u?void 0:u.uniqueId,path:`/graphs/${a}/nodes/${t.sourceIndex}`,message:"The generated seconds-to-frames animation helper was changed."});const d=null===(s=u.dataInputs.find(e=>"a"===e.name))||void 0===s?void 0:s._connectedPoint[0],h=u.dataInputs.find(e=>"b"===e.name),p=null!==(r=this._options.targetFps)&&void 0!==r?r:60,f=h?h._defaultValue:void 0;return h&&!h.isConnected()&&(null===(i=Hc(f))||void 0===i?void 0:i[0])===p||Jc(o,{code:"COMPOSITE_CONNECTION_CHANGED",graphIndex:a,nodeIndex:t.sourceIndex,blockId:u.uniqueId,path:`/blocks/${u.uniqueId}`,message:`Animation time helper must multiply by the target frame rate (${p}).`}),d}_rebuildConfiguration(e,t,n,o,s,r){var i,a,l,u,c,d,h,p,f,m,g,_,v,y,b,x,T,A,w,M,S,R,C,I,O;const F=new Set,E=new Set;for(const[t,o]of Object.entries(null!==(a=null===(i=n.mapping)||void 0===i?void 0:i.configuration)&&void 0!==a?a:{})){if(!o.configurationGroup)continue;const s=zc(n,o),r=Yc(n,t,o);r&&!Wc(null===(l=null==s?void 0:s.config)||void 0===l?void 0:l[o.name],r.runtimeValue)&&F.add(o.configurationGroup),Qc(null==r?void 0:r.sourceValue,o,e,null===(c=null===(u=this._options.sourceGLTF)||void 0===u?void 0:u.nodes)||void 0===c?void 0:c.length)||E.add(o.configurationGroup)}for(const[i,a]of Object.entries(null!==(h=null===(d=n.mapping)||void 0===d?void 0:d.configuration)&&void 0!==h?h:{})){const l=!!a.configurationGroup&&F.has(a.configurationGroup),u=!!a.configurationGroup&&E.has(a.configurationGroup),c=Yc(n,i,a),d=l&&!u&&void 0!==c&&void 0===c.runtimeValue&&Qc(c.sourceValue,a,e,null===(f=null===(p=this._options.sourceGLTF)||void 0===p?void 0:p.nodes)||void 0===f?void 0:f.length);let h=Xc(n,i,a,e,!l||d);l&&void 0===h&&void 0!==a.defaultValue&&(h=Hc(a.defaultValue));const N=null===(g=null===(m=t.configuration)||void 0===m?void 0:m[i])||void 0===g?void 0:g.value;if(a.validationOnly&&void 0===h&&void 0===(null==c?void 0:c.runtimeValue))continue;if(l&&!Qc(h,a,e,null===(v=null===(_=this._options.sourceGLTF)||void 0===_?void 0:_.nodes)||void 0===v?void 0:v.length)){Jc(r,{code:"CONFIGURATION_UNREPRESENTABLE",graphIndex:o,nodeIndex:n.sourceIndex,path:`/graphs/${o}/nodes/${n.sourceIndex}/configuration/${i}`,message:`Edited configuration group "${a.configurationGroup}" does not contain a valid value for "${i}".`});continue}if(!h){(void 0!==N||a.required)&&Jc(r,{code:"CONFIGURATION_UNREPRESENTABLE",graphIndex:o,nodeIndex:n.sourceIndex,path:`/graphs/${o}/nodes/${n.sourceIndex}/configuration/${i}`,message:`Configuration "${i}" cannot be inverted from the edited FlowGraph composite.`});continue}if("events"===a.indexSource&&1===h.length&&"number"==typeof h[0]){const t=null===(y=e.events)||void 0===y?void 0:y[h[0]],s=zc(n,a),l=Su(null===(b=null==s?void 0:s.config)||void 0===b?void 0:b.eventData),u=void 0===l?[]:l,d=s?Pc(s):void 0,p=Dc(null==d?void 0:d.generatedConfigurationRuntime,"eventData"),f=c&&Wc(null===(x=null==s?void 0:s.config)||void 0===x?void 0:x[a.name],c.runtimeValue),m=Object.entries(null!==(T=null==t?void 0:t.values)&&void 0!==T?T:{}).map(([t,n])=>{var o,s,r,i;return Object.assign({id:t,type:null===(i=$u[null!==(r=null===(s=null===(o=e.types)||void 0===o?void 0:o[n.type])||void 0===s?void 0:s.signature)&&void 0!==r?r:""])||void 0===i?void 0:i.flowGraphType},void 0===n.value?{}:{value:n.value.slice()})}).sort((e,t)=>e.id.localeCompare(t.id)),g=Kc(u),_=Kc(m);if(!(f&&p?!p.unrepresentable&&!g.unrepresentable&&g.runtimeValueFingerprint===p.runtimeValueFingerprint:!g.unrepresentable&&!_.unrepresentable&&g.runtimeValueFingerprint===_.runtimeValueFingerprint)){Jc(r,{code:"CONFIGURATION_UNREPRESENTABLE",graphIndex:o,nodeIndex:n.sourceIndex,path:`/graphs/${o}/nodes/${n.sourceIndex}/configuration/${i}`,message:`The runtime custom-event payload schema does not match event index ${h[0]}.`});continue}}if((!c||!Wc(null===(w=null===(A=zc(n,a))||void 0===A?void 0:A.config)||void 0===w?void 0:w[a.name],c.runtimeValue)||Qc(c.sourceValue,a,e,null===(S=null===(M=this._options.sourceGLTF)||void 0===M?void 0:M.nodes)||void 0===S?void 0:S.length))&&"assetNodes"===a.indexSource&&1===h.length&&"number"==typeof h[0]){const e=null===(I=null===(C=null===(R=this._options.sourceGLTF)||void 0===R?void 0:R.nodes)||void 0===C?void 0:C[h[0]])||void 0===I?void 0:I._babylonTransformNode,t=e?s.getNodeIndex(e):void 0;if(void 0===t){Jc(r,{code:"REFERENCE_UNRESOLVED",graphIndex:o,nodeIndex:n.sourceIndex,path:`/graphs/${o}/nodes/${n.sourceIndex}/configuration/${i}`,message:`Referenced glTF node ${h[0]} was not exported.`});continue}h[0]=t}if(void 0===N&&void 0!==a.defaultValue&&jc(h,Hc(a.defaultValue)))continue;null!==(O=t.configuration)&&void 0!==O||(t.configuration={});const L=t.configuration[i]?kc(t.configuration[i]):{};L.value=h,ed(t.configuration,i,L)}}_remapPointerTemplateInputs(e,t,n,o,s,r){var i,a,l,u,c,d,h,p,f,m;for(const[e,g]of Object.entries(null!==(a=null===(i=n.mapping)||void 0===i?void 0:i.configuration)&&void 0!==a?a:{})){if(!g.pointerTemplate)continue;const i=null===(c=null===(u=null===(l=t.configuration)||void 0===l?void 0:l[e])||void 0===u?void 0:u.value)||void 0===c?void 0:c[0];if("string"!=typeof i)continue;const a=i.split("/");if(""!==a[0]||a.length<3)continue;let _=a[1].replace(/~1/g,"/").replace(/~0/g,"~");const v=/^\{([^\{\}]+)\}$/.exec(a[1]);if(v){const e=null===(d=t.values)||void 0===d?void 0:d[v[1]],s=e&&!("node"in e)?null===(h=e.value)||void 0===h?void 0:h[0]:void 0,i="string"==typeof s?/^\/([^/]+)$/.exec(s):void 0;if(_=null!==(p=null==i?void 0:i[1])&&void 0!==p?p:"",!Fc.has(_)){Jc(r,{code:"REFERENCE_UNRESOLVED",graphIndex:o,nodeIndex:n.sourceIndex,socket:v[1],path:`/graphs/${o}/nodes/${n.sourceIndex}/values/${v[1]}`,message:`Root collection template input "${v[1]}" cannot be resolved statically for export.`});continue}}if(!Fc.has(_))continue;const y=/^\[([^\[\]]+)\]$/.exec(a[2]),b=/^\{([^\{\}]+)\}$/.exec(a[2]);if(!(v||y||b)||this._validateExtensionReferencePreservation(i,_,r,o,n.sourceIndex,`/graphs/${o}/nodes/${n.sourceIndex}/configuration/${e}`))if(y){const e=null===(f=t.values)||void 0===f?void 0:f[y[1]],i=`/graphs/${o}/nodes/${n.sourceIndex}/values/${y[1]}`;if(!e||"node"in e){Jc(r,{code:"REFERENCE_UNRESOLVED",graphIndex:o,nodeIndex:n.sourceIndex,socket:y[1],path:i,message:`Dynamic index template input "${y[1]}" cannot be safely remapped for the exported ${_} array.`});continue}const a=null===(m=e.value)||void 0===m?void 0:m[0],l="number"==typeof a&&Number.isInteger(a)?this._getRemappedRootIndex(_,a,s):void 0;if(void 0===l){Jc(r,{code:"REFERENCE_UNRESOLVED",graphIndex:o,nodeIndex:n.sourceIndex,socket:y[1],path:i,message:`Template input "${y[1]}" does not resolve to an exported ${_} element.`});continue}e.value=[l]}else if(v&&/^(0|[1-9]\d*)$/.test(a[2])){const i=parseInt(a[2],10),l=this._getRemappedRootIndex(_,i,s);void 0===l?Jc(r,{code:"REFERENCE_UNRESOLVED",graphIndex:o,nodeIndex:n.sourceIndex,path:`/graphs/${o}/nodes/${n.sourceIndex}/configuration/${e}`,message:`Static ${_} index ${i} does not resolve to an exported element.`}):(a[2]=String(l),t.configuration[e].value[0]=a.join("/"))}}}_updateVariables(e,t,n,o){var s,r,i,a;const l=null===(s=t.metadata)||void 0===s?void 0:s.khrInteractivity;(null==l?void 0:l.authoredVariableStructureChanged)&&Jc(n,{code:"VALUE_UNREPRESENTABLE",graphIndex:o,path:`/graphs/${o}/variables`,message:"Adding, renaming, or deleting variables from an imported KHR_interactivity graph is not supported by lossless export."});const u=null==l?void 0:l.authoredVariableValues,c=null==l?void 0:l.authoredVariableTypes;if(u||c){for(const[t,s]of Object.entries(null!=c?c:{})){const i=Number(t),a=null===(r=e.variables)||void 0===r?void 0:r[i],l=qc(e,s);a&&void 0!==l?a.type=l:Jc(n,{code:"VALUE_UNREPRESENTABLE",graphIndex:o,path:`/graphs/${o}/variables/${i}/type`,message:`Authored variable type "${s}" cannot be represented by KHR_interactivity.`})}for(const[t,s]of Object.entries(null!=u?u:{})){const r=Number(t),l=e.variables[r];if(!l){Jc(n,{code:"VALUE_UNREPRESENTABLE",graphIndex:o,path:`/graphs/${o}/variables/${r}`,message:`Authored variable index ${r} does not exist in the canonical graph.`});continue}const u=Hc(s),c=null===(a=null===(i=e.types)||void 0===i?void 0:i[l.type])||void 0===a?void 0:a.signature;u&&c&&(l.value=u)}}}_remapValueArray(e,t,n,o,s,r,i){return"ref"!==t?e:e.map(e=>{var t,a;if("string"==typeof e){const a=null===(t=null==i?void 0:i.match(/^\/([^/]+)\//))||void 0===t?void 0:t[1];return a&&Fc.has(a)?this._remapReferenceToCollection(e,a,n,o,s,r):this._remapReference(e,n,o,s,r)}if(null!==e&&"object"==typeof e){const t=null===(a=null==i?void 0:i.match(/^\/([^/]+)\//))||void 0===a?void 0:a[1];if(t&&Fc.has(t)&&n.getRootIndex){const o=n.getRootIndex(t,e);if(void 0!==o)return`/${t}/${o}`}const o=[["animations",n.getAnimationIndex(e)],["cameras",n.getCameraIndex(e)],["materials",n.getMaterialIndex(e)],["nodes",n.getNodeIndex(e)]],s=(t?o.filter(([e])=>e===t):null===i?[]:o).filter(([,e])=>void 0!==e);if(1===s.length)return`/${s[0][0]}/${s[0][1]}`;if(this._isPreflight)return""}return Jc(o,{code:"REFERENCE_UNRESOLVED",graphIndex:s,nodeIndex:r,path:`/graphs/${s}${void 0===r?"":`/nodes/${r}`}`,message:"An authored reference value does not resolve to an exported glTF entity."}),""})}_topologicallyOrderNodes(e,t,n){var o,s,r,i;const a=e.map(()=>new Set),l=e.map(()=>0);let u=!1;const c=(o,s)=>o<0||s<0||o>=e.length||s>=e.length?(u=!0,void Jc(n,{code:"SOCKET_TARGET_UNREPRESENTABLE",graphIndex:t,path:`/graphs/${t}/nodes`,message:`Dependency ${o} -> ${s} references a node outside the exported graph.`})):o===s?(u=!0,void Jc(n,{code:"DEPENDENCY_CYCLE",graphIndex:t,nodeIndex:o,path:`/graphs/${t}/nodes/${o}`,message:"A KHR_interactivity node cannot depend on itself."})):void(a[o].has(s)||(a[o].add(s),l[s]++));for(let t=0;t<e.length;t++){for(const n of Object.values(null!==(o=e[t].values)&&void 0!==o?o:{}))"node"in n&&c(n.node,t);for(const n of Object.values(null!==(s=e[t].flows)&&void 0!==s?s:{}))c(t,n.node)}if(u)return;const d=l.flatMap((e,t)=>0===e?[t]:[]),h=[];for(;d.length>0;){d.sort((e,t)=>e-t);const e=d.shift();h.push(e);for(const t of a[e])l[t]--,0===l[t]&&d.push(t)}if(h.length!==e.length)return void Jc(n,{code:"DEPENDENCY_CYCLE",graphIndex:t,path:`/graphs/${t}/nodes`,message:"Value and flow dependencies form a cycle that cannot satisfy KHR_interactivity node ordering constraints."});const p=new Map(h.map((e,t)=>[e,t])),f=h.map(t=>e[t]);for(const e of f){for(const t of Object.values(null!==(r=e.values)&&void 0!==r?r:{}))"node"in t&&(t.node=p.get(t.node));for(const t of Object.values(null!==(i=e.flows)&&void 0!==i?i:{}))t.node=p.get(t.node)}return{nodes:f,sourceIndices:h}}_remapGraphReferences(e,t,n,o,s){var r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b,x,T,A,w,M,S,R,C,I,O,F,E;for(let s=0;s<(null!==(i=null===(r=e.variables)||void 0===r?void 0:r.length)&&void 0!==i?i:0);s++){const r=e.variables[s];if("ref"===(null===(l=null===(a=e.types)||void 0===a?void 0:a[r.type])||void 0===l?void 0:l.signature)&&r.value){const i=null===(p=null===(h=null===(d=null===(c=null===(u=this._options.document)||void 0===u?void 0:u.graphs[o])||void 0===c?void 0:c.source.variables)||void 0===d?void 0:d[s])||void 0===h?void 0:h.value)||void 0===p?void 0:p[0],a=r.value[0],l=this._getVariableReferenceCollection(e,s),f=null===l?null:l?`/${l}/0`:"object"!=typeof a&&a!==i||"string"!=typeof i?void 0:i;r.value=this._remapValueArray(r.value,"ref",t,n,o,void 0,f)}}for(const s of null!==(f=e.events)&&void 0!==f?f:[])for(const r of Object.values(null!==(m=s.values)&&void 0!==m?m:{}))"ref"===(null===(_=null===(g=e.types)||void 0===g?void 0:g[r.type])||void 0===_?void 0:_.signature)&&r.value&&(r.value=this._remapValueArray(r.value,"ref",t,n,o));for(let r=0;r<(null!==(y=null===(v=e.nodes)||void 0===v?void 0:v.length)&&void 0!==y?y:0);r++){const i=e.nodes[r],a=null!==(b=s[r])&&void 0!==b?b:r,l=null===(x=e.declarations)||void 0===x?void 0:x[i.declaration],u=l?Ru(l,!1):void 0;for(const[s,r]of Object.entries(null!==(T=i.values)&&void 0!==T?T:{}))if(!("node"in r)&&"ref"===(null===(w=null===(A=e.types)||void 0===A?void 0:A[r.type])||void 0===w?void 0:w.signature)&&r.value){const e=this._getPointerReferenceCollection(i,u,s);if(null===e){Jc(n,{code:"REFERENCE_UNRESOLVED",graphIndex:o,nodeIndex:a,socket:s,path:`/graphs/${o}/nodes/${a}/values/${s}`,message:`Pointer template collection for reference input "${s}" cannot be resolved statically.`});continue}const l=null===(I=null===(C=null===(R=null===(S=null===(M=this._options.document)||void 0===M?void 0:M.graphs[o])||void 0===S?void 0:S.source.nodes)||void 0===R?void 0:R[a])||void 0===C?void 0:C.values)||void 0===I?void 0:I[s],c=l&&!("node"in l)?null===(O=l.value)||void 0===O?void 0:O[0]:void 0,d=r.value[0],h=e?`/${e}/0`:"object"!=typeof d&&d!==c||"string"!=typeof c?void 0:c;r.value=this._remapValueArray(r.value,"ref",t,n,o,a,h)}for(const[e,s]of Object.entries(null!==(F=null==u?void 0:u.configuration)&&void 0!==F?F:{})){if(!s.pointerTemplate)continue;const r=null===(E=i.configuration)||void 0===E?void 0:E[e];(null==r?void 0:r.value)&&(r.value=r.value.map(e=>"string"==typeof e?this._remapReference(e,t,n,o,a):e))}}}_getVariableReferenceCollection(e,t){var n,o,s,r,i,a,l,u,c;const d=new Set;for(let l=0;l<(null!==(o=null===(n=e.nodes)||void 0===n?void 0:n.length)&&void 0!==o?o:0);l++){const n=e.nodes[l],o=null===(s=e.declarations)||void 0===s?void 0:s[n.declaration];"variable/get"!==(null==o?void 0:o.op)||o.extension||(null===(a=null===(i=null===(r=n.configuration)||void 0===r?void 0:r.variable)||void 0===i?void 0:i.value)||void 0===a?void 0:a[0])!==t||d.add(l)}const h=new Set;for(const t of null!==(l=e.nodes)&&void 0!==l?l:[]){const n=null===(u=e.declarations)||void 0===u?void 0:u[t.declaration],o=n?Ru(n,!1):void 0;for(const[e,n]of Object.entries(null!==(c=t.values)&&void 0!==c?c:{})){if(!("node"in n)||!d.has(n.node))continue;const s=this._getPointerReferenceCollection(t,o,e);if(null===s)return null;s&&h.add(s)}}return 1===h.size?h.values().next().value:h.size>1?null:void 0}_getPointerReferenceCollection(e,t,n){var o,s,r,i,a,l,u,c;for(const[d,h]of Object.entries(null!==(o=null==t?void 0:t.configuration)&&void 0!==o?o:{})){if(!h.pointerTemplate)continue;const t=null===(i=null===(r=null===(s=e.configuration)||void 0===s?void 0:s[d])||void 0===r?void 0:r.value)||void 0===i?void 0:i[0];if("string"!=typeof t)continue;const o=t.split("/"),p=o.findIndex(e=>e===`{${n}}`);if(p>1){const t=o[p-1],n=/^\{([^\{\}]+)\}$/.exec(t),s=n?null===(a=e.values)||void 0===a?void 0:a[n[1]]:void 0,r=s&&!("node"in s)?null===(l=s.value)||void 0===l?void 0:l[0]:void 0,i=(n&&"string"==typeof r?null!==(c=null===(u=/^\/([^/]+)$/.exec(r))||void 0===u?void 0:u[1])&&void 0!==c?c:"":t).replace(/~1/g,"/").replace(/~0/g,"~");if(Fc.has(i))return i;if(n)return null}}}_getRemappedRootIndex(e,t,n){const o=new Set(this._getSourceRootObjects(e,t).map(t=>this._getExportedObjectIndex(e,t,n)).filter(e=>void 0!==e));return 1===o.size?o.values().next().value:void 0}_getSourceRootObjects(e,t){var n,o,s,r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b,x,T,A,w,M,S,R,C;const I=this._options.sourceGLTF;switch(e){case"nodes":return(null===(o=null===(n=null==I?void 0:I.nodes)||void 0===n?void 0:n[t])||void 0===o?void 0:o._babylonTransformNode)?[I.nodes[t]._babylonTransformNode]:[];case"animations":return(null===(r=null===(s=null==I?void 0:I.animations)||void 0===s?void 0:s[t])||void 0===r?void 0:r._babylonAnimationGroup)?[I.animations[t]._babylonAnimationGroup]:[];case"cameras":return(null===(a=null===(i=null==I?void 0:I.cameras)||void 0===i?void 0:i[t])||void 0===a?void 0:a._babylonCamera)?[I.cameras[t]._babylonCamera]:[];case"materials":return Array.from(new Set(Object.values(null!==(c=null===(u=null===(l=null==I?void 0:I.materials)||void 0===l?void 0:l[t])||void 0===u?void 0:u._data)&&void 0!==c?c:{}).map(e=>e.babylonMaterial)));case"meshes":return Array.from(new Set([...null!==(p=null===(h=null===(d=null==I?void 0:I.meshes)||void 0===d?void 0:d[t])||void 0===h?void 0:h.primitives.flatMap(e=>e._instanceData?[e._instanceData.babylonSourceMesh]:[]))&&void 0!==p?p:[],...null!==(m=null===(f=null==I?void 0:I.nodes)||void 0===f?void 0:f.filter(e=>e.mesh===t).flatMap(e=>{var t;return[...e._babylonTransformNode?[e._babylonTransformNode]:[],...null!==(t=e._primitiveBabylonMeshes)&&void 0!==t?t:[]]}))&&void 0!==m?m:[]]));case"textures":return null!==(y=null===(v=null===(_=null===(g=null==I?void 0:I.textures)||void 0===g?void 0:g[t])||void 0===_?void 0:_._babylonTextures)||void 0===v?void 0:v.slice())&&void 0!==y?y:[];case"images":return Array.from(new Set(null!==(x=null===(b=null==I?void 0:I.textures)||void 0===b?void 0:b.flatMap(e=>{var t;return null!==(t=e._babylonTextureSources)&&void 0!==t?t:[]}).filter(e=>e.imageIndex===t).map(e=>e.babylonTexture))&&void 0!==x?x:[]));case"samplers":return Array.from(new Set(null!==(A=null===(T=null==I?void 0:I.textures)||void 0===T?void 0:T.flatMap(e=>{var t;return null!==(t=e._babylonTextureSources)&&void 0!==t?t:[]}).filter(e=>e.samplerIndex===t).map(e=>e.babylonTexture))&&void 0!==A?A:[]));case"skins":return(null===(S=null===(M=null===(w=null==I?void 0:I.skins)||void 0===w?void 0:w[t])||void 0===M?void 0:M._data)||void 0===S?void 0:S.babylonSkeleton)?[I.skins[t]._data.babylonSkeleton]:[];case"scenes":return t===(null!==(R=null==I?void 0:I.scene)&&void 0!==R?R:0)&&(null===(C=this._flowGraphs[0])||void 0===C?void 0:C.scene)?[this._flowGraphs[0].scene]:[]}}_getSourceRootIndex(e,t){var n;const o=null===(n=this._options.sourceGLTF)||void 0===n?void 0:n[e];if(!o)return;const s=[];for(let n=0;n<o.length;n++)this._getSourceRootObjects(e,n).includes(t)&&s.push(n);return 1===s.length?s[0]:void 0}_getExportedObjectIndex(e,t,n){if(n.getRootIndex)return n.getRootIndex(e,t);switch(e){case"nodes":return n.getNodeIndex(t);case"animations":return n.getAnimationIndex(t);case"cameras":return n.getCameraIndex(t);case"materials":return n.getMaterialIndex(t);default:return}}_remapReferenceToCollection(e,t,n,o,s,r){var i;if(!this._validateExtensionReferencePreservation(e,t,o,s,r))return e;const a=e.match(/^\/([^/]+)\/(0|[1-9]\d*)(\/.*)?$/);if(!a||!Fc.has(a[1]))return this._remapReference(e,n,o,s,r);const l=this._getSourceRootObjects(t,parseInt(a[2],10)),u=new Set(l.map(e=>this._getExportedObjectIndex(t,e,n)).filter(e=>void 0!==e)),c=1===u.size?u.values().next().value:void 0;return void 0===c?(Jc(o,{code:"REFERENCE_UNRESOLVED",graphIndex:s,nodeIndex:r,path:`/graphs/${s}${void 0===r?"":`/nodes/${r}`}`,message:`Reference "${e}" cannot be remapped to the exported ${t} collection.`}),e):`/${t}/${c}${null!==(i=a[3])&&void 0!==i?i:""}`}_remapReference(e,t,n,o,s){var r;if(!e||e.startsWith("/extensions/KHR_interactivity/events/")||e.startsWith("/extensions/KHR_interactivity/delays/"))return e;const i=/^\/extensions\/([^/]+)\/[^/]+\/(0|[1-9]\d*)(?:\/|$)/.exec(e);if(i&&"KHR_interactivity"!==i[1])return Jc(n,{code:"REFERENCE_UNRESOLVED",graphIndex:o,nodeIndex:s,path:`/graphs/${o}${void 0===s?"":`/nodes/${s}`}`,message:`Indexed reference "${e}" belongs to ${i[1]}, whose serializer index mapping is unavailable.`}),e;const a=e.match(/^\/([^/]+)\/(0|[1-9]\d*)(\/.*)?$/);if(!a||!Fc.has(a[1]))return e;if(!this._validateExtensionReferencePreservation(e,a[1],n,o,s))return e;const l=a[1],u=parseInt(a[2],10),c=this._getRemappedRootIndex(l,u,t);return void 0===c?(Jc(n,{code:"REFERENCE_UNRESOLVED",graphIndex:o,nodeIndex:s,path:`/graphs/${o}${void 0===s?"":`/nodes/${s}`}`,message:`Reference "${e}" cannot be remapped because its ${l} target was not exported uniquely.`}),e):`/${l}/${c}${null!==(r=a[3])&&void 0!==r?r:""}`}_validateExtensionReferencePreservation(e,t,n,o,s,r=`/graphs/${o}${void 0===s?"":`/nodes/${s}`}`){const i=Nc(e).filter(e=>"KHR_interactivity"!==e);return!(0!==i.length&&!function(e,t){const n=e.split("/").map(e=>e.replace(/~1/g,"/").replace(/~0/g,"~")),o=n.indexOf("extensions");return o>1&&"nodes"===(null!=t?t:n[1])&&Ec.includes(n[o+1])}(e,t)&&(Jc(n,{code:"REFERENCE_UNRESOLVED",graphIndex:o,nodeIndex:s,path:r,message:`Reference "${e}" observes extension-backed data (${i.join(", ")}) that the serializer cannot guarantee will retain its source semantics.`}),1))}_collectAdditionalExtensions(){var e,t,n,o,s,r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b,x,T,A;const w=new Set,M=e=>{if("string"==typeof e)for(const t of Nc(e))"KHR_interactivity"!==t&&w.add(t)},S=e=>{if(Array.isArray(e))return void e.forEach(S);if(null===e||"object"!=typeof e)return;const t=e;for(const[e,n]of Object.entries(t))if("extras"!==e)if("extensions"!==e||null===n||"object"!=typeof n||Array.isArray(n))"extensions"!==e&&S(n);else for(const[e,t]of Object.entries(n))"KHR_interactivity"!==e&&w.add(e),S(t)};S(null===(e=this._options.document)||void 0===e?void 0:e.source);for(const e of this._graphAnalyses){S(e.source);for(const r of null!==(t=e.source.variables)&&void 0!==t?t:[])"ref"===(null===(o=null===(n=e.source.types)||void 0===n?void 0:n[r.type])||void 0===o?void 0:o.signature)&&(null===(s=r.value)||void 0===s||s.forEach(M));for(const t of null!==(r=e.source.events)&&void 0!==r?r:[])for(const n of Object.values(null!==(i=t.values)&&void 0!==i?i:{}))n&&"object"==typeof n&&"ref"===(null===(l=null===(a=e.source.types)||void 0===a?void 0:a[n.type])||void 0===l?void 0:l.signature)&&(null===(u=n.value)||void 0===u||u.forEach(M));for(const t of null!==(c=e.source.declarations)&&void 0!==c?c:[])t.extension&&w.add(t.extension);for(const t of null!==(d=e.source.nodes)&&void 0!==d?d:[]){for(const n of Object.values(null!==(h=t.values)&&void 0!==h?h:{}))n&&"object"==typeof n&&!("node"in n)&&"ref"===(null===(f=null===(p=e.source.types)||void 0===p?void 0:p[n.type])||void 0===f?void 0:f.signature)&&(null===(m=n.value)||void 0===m||m.forEach(M));const n=null===(g=e.source.declarations)||void 0===g?void 0:g[t.declaration],o=n?Ru(n,!1):void 0;for(const[e,n]of Object.entries(null!==(_=null==o?void 0:o.configuration)&&void 0!==_?_:{}))n.pointerTemplate&&(null===(b=null===(y=null===(v=t.configuration)||void 0===v?void 0:v[e])||void 0===y?void 0:y.value)||void 0===b||b.forEach(M))}}for(const e of null!==(T=null===(x=this._options.sourceGLTF)||void 0===x?void 0:x.nodes)&&void 0!==T?T:[])for(const t of Ec){const n=null===(A=e.extensions)||void 0===A?void 0:A[t];n&&(w.add(t),S(n))}return Array.from(w).sort()}_writeCompanionNodeExtensions(e,t){var n,o,s,r;for(let i=0;i<(null!==(s=null===(o=null===(n=this._options.sourceGLTF)||void 0===n?void 0:n.nodes)||void 0===o?void 0:o.length)&&void 0!==s?s:0);i++){const n=this._options.sourceGLTF.nodes[i];for(const o of Ec){const s=null===(r=n.extensions)||void 0===r?void 0:r[o];if(!s)continue;const a=n._babylonTransformNode?e.getNodeIndex(n._babylonTransformNode):void 0;void 0!==a?e.setNodeExtension(a,o,kc(s)):Jc(t,{code:"REFERENCE_UNRESOLVED",path:`/nodes/${i}/extensions/${o}`,message:`Companion extension "${o}" targets a node that was not exported.`})}}}_sortDiagnostics(e){return e.slice().sort((e,t)=>{var n,o,s,r;return(null!==(n=e.graphIndex)&&void 0!==n?n:-1)-(null!==(o=t.graphIndex)&&void 0!==o?o:-1)||(null!==(s=e.nodeIndex)&&void 0!==s?s:-1)-(null!==(r=t.nodeIndex)&&void 0!==r?r:-1)||e.path.localeCompare(t.path)||e.code.localeCompare(t.code)})}}function nd(e,t={}){return new td(e,t)}const od="KHR_interactivity",sd=new WeakMap;function rd(e){const t=sd.get(e);return null==t?void 0:t[t.length-1]}function id(e){var t;return null!==(t=sd.get(e))&&void 0!==t?t:[]}class ad{constructor(e){this._loader=e,this.name=od,this.order=200,this.enabled=this._loader.isExtensionUsed(od),e._skipStartAnimationStep=!0}_initializePathConverter(e){var n;this._gltfPathConverter=dr(this._loader.gltf,t=>ld(e,this._loader.parent.targetFps,t));const o=[{prefix:yc,converter:new bc(e,{transformNodes:{length:{type:"number",get:e=>e.length,getTarget:e=>e},__array__:{__target__:!0,name:{type:"string",get:e=>e.name,set:(e,t)=>{t.name=e},getTarget:e=>e},translation:{type:"Vector3",get:e=>e.position,set:(e,t)=>t.position.copyFrom(e),getTarget:e=>e},rotation:{type:"Quaternion",get:e=>{var n;return null!==(n=e.rotationQuaternion)&&void 0!==n?n:t.Quaternion.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z)},set:(e,t)=>{t.rotationQuaternion?t.rotationQuaternion.copyFrom(e):t.rotationQuaternion=e.clone()},getTarget:e=>e},scale:{type:"Vector3",get:e=>e.scaling,set:(e,t)=>t.scaling.copyFrom(e),getTarget:e=>e},matrix:{type:"Matrix",get:e=>e.computeWorldMatrix(!1),getTarget:e=>e,isReadOnly:!0},globalMatrix:{type:"Matrix",get:e=>e.computeWorldMatrix(!0),getTarget:e=>e,isReadOnly:!0}}},meshes:{length:{type:"number",get:e=>e.length,getTarget:e=>e},__array__:{__target__:!0,name:{type:"string",get:e=>e.name,set:(e,t)=>{t.name=e},getTarget:e=>e},visible:{type:"boolean",get:e=>e.isVisible,set:(e,t)=>{t.isVisible=e},getTarget:e=>e}}},materials:{length:{type:"number",get:e=>e.length,getTarget:e=>e},__array__:{__target__:!0,name:{type:"string",get:e=>e.name,set:(e,t)=>{t.name=e},getTarget:e=>e}}}})}],s=new Tc;o.push({prefix:dc,converter:s}),o.push({prefix:hc,converter:s});const r=new Set((null!==(n=this._loader.gltf.extensionsUsed)&&void 0!==n?n:[]).filter(e=>{var t;return zs.has(e)&&!1!==(null===(t=this._loader.parent.extensionOptions[e])||void 0===t?void 0:t.enabled)})),i=new Cc(this._loader.gltf,e=>r.has(e));o.push({prefix:"/extensions/KHR_interactivity/asset/",converter:i}),o.push({prefix:Ac,converter:i});const a=new vc(o,this._gltfPathConverter);return this._pathConverter=a,a}dispose(){this._loader=null,delete this._gltfPathConverter,delete this._pathConverter}onReady(){return b(this,void 0,void 0,function*(){var e,n,o,s,r,i,a,l;if(!this._loader.babylonScene)return;const u=this._loader.babylonScene,c=this._initializePathConverter(u),d=null===(e=this._loader.gltf.extensions)||void 0===e?void 0:e.KHR_interactivity;if(!d)return;const h=new Set((null!==(n=this._loader.gltf.extensionsUsed)&&void 0!==n?n:[]).filter(e=>{var t;return!1!==(null===(t=this._loader.parent.extensionOptions[e])||void 0===t?void 0:t.enabled)})),p=cc(d,h,null!==(s=null===(o=this._loader.gltf.nodes)||void 0===o?void 0:o.length)&&void 0!==s?s:0),f=this._loader.parent.extensionOptions[od],m=null===(r=null==f?void 0:f.autoStart)||void 0===r||r,g=null!==(i=null==f?void 0:f.parseOnly)&&void 0!==i&&i,_=null===(a=null==f?void 0:f.strictValidation)||void 0===a||a,v=null!==(l=sd.get(u))&&void 0!==l?l:[],y={assetIndex:v.length,document:p,graphs:[],pathConverter:c,glTF:this._loader.gltf,scene:u,hostResolver:new Ic};v.push(y),sd.set(u,v),yield Promise.all(p.graphs.map(e=>b(this,void 0,void 0,function*(){var n,o;const s={graph:e,diagnostics:e.diagnostics.slice()};if(y.graphs[e.index]=s,e.valid||!_)try{const n=new _c(_?e.effectiveSource:e.source,this._loader.gltf,this._loader.parent.targetFps,e.index,h,_?e.declarations:void 0,e.source).serializeToFlowGraph();if(s.serializedFlowGraph=n,g)return;const o=new t.FlowGraphCoordinator({scene:u,hostResolver:y.hostResolver});o.dispatchEventsSynchronously=!1,s.coordinator=o,s.flowGraph=yield t.ParseFlowGraphAsync(n,{coordinator:o,pathConverter:c}),gc(s.flowGraph),m&&e.index===p.defaultGraphIndex&&o.start()}catch(r){const i=null!==(n=null==r?void 0:r.message)&&void 0!==n?n:String(r);s.diagnostics.push({path:e.path,message:i,severity:"error"}),t.Logger.Error(`KHR_interactivity: rejecting behavior graph #${e.index}: ${i}`),null===(o=s.coordinator)||void 0===o||o.dispose(),delete s.coordinator,delete s.flowGraph,delete s.serializedFlowGraph}else t.Logger.Error(`KHR_interactivity: rejecting behavior graph #${e.index}: ${e.diagnostics.map(e=>e.message).join("; ")}`)})))})}}function ld(e,n,o){fr("/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},o),fr("/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},o);const s=n=>{const o=e.activeCamera;return o&&o.mode!==t.Constants.ORTHOGRAPHIC_CAMERA?n(o):NaN},r=n=>{const o=e.activeCamera;return o&&o.mode===t.Constants.ORTHOGRAPHIC_CAMERA?n(o):NaN};fr("/extensions/KHR_interactivity/?/activeCamera/perspective/aspectRatio",{get:()=>s(e=>e.getEngine().getAspectRatio(e)),type:"number",getTarget:()=>e.activeCamera},o),fr("/extensions/KHR_interactivity/?/activeCamera/perspective/yfov",{get:()=>s(e=>{if(e.fovMode===t.Constants.FOVMODE_VERTICAL_FIXED)return e.fov;const n=e.getEngine().getAspectRatio(e);return n?2*Math.atan(Math.tan(e.fov/2)/n):e.fov}),type:"number",getTarget:()=>e.activeCamera},o),fr("/extensions/KHR_interactivity/?/activeCamera/perspective/znear",{get:()=>s(e=>e.minZ),type:"number",getTarget:()=>e.activeCamera},o),fr("/extensions/KHR_interactivity/?/activeCamera/perspective/zfar",{get:()=>s(e=>0===e.maxZ?1/0:e.maxZ),type:"number",getTarget:()=>e.activeCamera},o),fr("/extensions/KHR_interactivity/?/activeCamera/orthographic/xmag",{get:()=>r(e=>{var t,n;const o=e.getEngine().getRenderWidth()/2;return((null!==(t=e.orthoRight)&&void 0!==t?t:o)-(null!==(n=e.orthoLeft)&&void 0!==n?n:-o))/2}),type:"number",getTarget:()=>e.activeCamera},o),fr("/extensions/KHR_interactivity/?/activeCamera/orthographic/ymag",{get:()=>r(e=>{var t,n;const o=e.getEngine().getRenderHeight()/2;return((null!==(t=e.orthoTop)&&void 0!==t?t:o)-(null!==(n=e.orthoBottom)&&void 0!==n?n:-o))/2}),type:"number",getTarget:()=>e.activeCamera},o),fr("/extensions/KHR_interactivity/?/activeCamera/orthographic/znear",{get:()=>r(e=>e.minZ),type:"number",getTarget:()=>e.activeCamera},o),fr("/extensions/KHR_interactivity/?/activeCamera/orthographic/zfar",{get:()=>r(e=>e.maxZ),type:"number",getTarget:()=>e.activeCamera},o);const i=e=>{var t,o,s,r;return null!==(r=null===(s=null===(o=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.targetedAnimations)||void 0===o?void 0:o[0])||void 0===s?void 0:s.animation.framePerSecond)&&void 0!==r?r:n};fr("/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},o),fr("/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)/i(e)},type:"number",getTarget:e=>e._babylonAnimationGroup},o),fr("/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)/i(e)},type:"number",getTarget:e=>e._babylonAnimationGroup},o),fr("/animations/{}/extensions/KHR_interactivity/playhead",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.getRetainedCurrentFrame())&&void 0!==n?n:0)/i(e)},type:"number",getTarget:e=>e._babylonAnimationGroup},o),fr("/animations/{}/extensions/KHR_interactivity/virtualPlayhead",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.getVirtualCurrentFrame())&&void 0!==n?n:0)/i(e)},type:"number",getTarget:e=>e._babylonAnimationGroup},o)}let ud=!1;function cd(){ud||(ud=!0,t.addToBlockFactory(od,"FlowGraphGLTFDataProvider",()=>b(this,void 0,void 0,function*(){return(yield Promise.resolve().then(function(){return eh})).FlowGraphGLTFDataProvider})),t.addToBlockFactory(od,"FlowGraphUnsupportedInteractivityBlock",()=>b(this,void 0,void 0,function*(){return(yield Promise.resolve().then(function(){return lh})).FlowGraphUnsupportedInteractivityBlock})),t.addToBlockFactory(od,"FlowGraphObjectReferenceBlock",()=>b(this,void 0,void 0,function*(){return(yield Promise.resolve().then(function(){return oh})).FlowGraphObjectReferenceBlock})),t.addToBlockFactory(od,"FlowGraphEventReferenceBlock",()=>b(this,void 0,void 0,function*(){return(yield Promise.resolve().then(function(){return rh})).FlowGraphEventReferenceBlock})))}let dd=!1;function hd(){dd||(dd=!0,cd(),Ys(od),Xs(od,!0,e=>new ad(e)))}var pd={__proto__:null,CreateKHRInteractivityExportPlan:nd,GetKHRInteractivityImportResult:rd,GetKHRInteractivityImportResults:id,KHRInteractivityExportError:Oc,KHRInteractivityExportPlan:td,KHR_interactivity:ad,RegisterKHR_interactivity:hd,_AddInteractivityObjectModel:ld,_CaptureKHRInteractivityRuntimeInputDefaults:gc,_RegisterKHRInteractivityRuntime:cd};hd();const fd="KHR_node_visibility";class md{constructor(e){this.name=fd,this._loader=e,this.enabled=e.isExtensionUsed(fd)}onReady(){var e;if(!this._loader)return;const t=this._loader.gltf.nodes;if(t)for(const n of t){const t=n._babylonTransformNode;t&&(t.inheritVisibility=!0,n.extensions&&n.extensions.KHR_node_visibility&&!1===n.extensions.KHR_node_visibility.visible&&(t.isVisible=!1,null===(e=n._primitiveBabylonMeshes)||void 0===e||e.forEach(e=>{e.inheritVisibility=!0,e.isVisible=!1})))}}dispose(){delete this._loader}}let gd=!1;function _d(){gd||(gd=!0,fr("/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"}))}let vd=!1;function yd(){vd||(vd=!0,_d(),Ys(fd),Xs(fd,!0,e=>new md(e)))}var bd={__proto__:null,KHR_node_visibility:md,RegisterKHR_node_visibility:yd,_RegisterKHRNodeVisibilityRuntime:_d};yd();const xd=new WeakMap,Td=new WeakMap,Ad=new WeakMap;function wd(e){return"selectable"===e?Ad:Td}function Md(e,t){var n;return null===(n=wd(t).get(e))||void 0===n||n}function Sd(e,t,n){"selectable"===t?e.isPickable=n:e._isPointerMovePickable=n}function Rd(e,t){var n;const o=function(e,t){let n=e;for(;n;){if(!Md(n,t))return!1;n=n.parent}return!0}(e,t),s=null!==(n=e._primitiveBabylonMeshes)&&void 0!==n?n:[];for(const e of s)Sd(e,t,o);const r=e._babylonTransformNode;r&&"isPickable"in r&&Sd(r,t,o)}function Cd(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parent}return!1}function Id(e,t,n){var o;const s=wd(t);for(const t of e)xd.set(t,e),s.set(t,null===(o=n(t))||void 0===o||o);for(const n of e)Rd(n,t)}function Od(e,t){return Md(e,t)}function Fd(e,t,n){var o;wd(t).set(e,n);const s=null!==(o=xd.get(e))&&void 0!==o?o:[e];for(const n of s)Cd(n,e)&&Rd(n,t)}const Ed="KHR_node_selectability";class Nd{constructor(e){this.name=Ed,this.order=100,this._loader=e,this.enabled=e.isExtensionUsed(Ed)}onReady(){return b(this,void 0,void 0,function*(){var e;Id(null!==(e=this._loader.gltf.nodes)&&void 0!==e?e:[],"selectable",e=>{var t,n;return null===(n=null===(t=e.extensions)||void 0===t?void 0:t.KHR_node_selectability)||void 0===n?void 0:n.selectable})})}dispose(){this._loader=null}}let Ld=!1;function kd(){Ld||(Ld=!0,Iu("event/onSelect",Ed,{blocks:["FlowGraphMeshPickEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider","KHR_interactivity/FlowGraphEventReferenceBlock"],declarationSchema:{inputValueSockets:{},outputValueSockets:{selectedNode:"ref",selectionRayOrigin:"float3",selectionPoint:"float3",controllerIndex:"int",event:"ref"}},configuration:{nodeIndex:{name:"variable",configurationType:"int",toBlock:"FlowGraphGetVariableBlock",indexSource:"assetNodes",invalidUsesDefault:!0,dataTransformer:e=>"pickedMesh_"+e}},outputs:{values:{selectedNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},selectedNode:{name:"nodeReference",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},controllerIndex:{name:"controllerIndex",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},selectionPoint:{name:"selectionPoint",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},selectionRayOrigin:{name:"selectionRayOrigin",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},event:{name:"value",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"}},flows:{out:{name:"out",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"}}},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},{input:"node",output:"pickedMesh",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"controllerIndexInput",output:"pointerId",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"selectionPointInput",output:"pickedPoint",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"selectionRayOriginInput",output:"pickOrigin",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"in",output:"done",inputBlockIndex:4,outputBlockIndex:0}],extraProcessor(e,t,n,o,s,r,i){var a,l,u,c,d,h,p,f,m;const g=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],_="number"==typeof g&&Number.isInteger(g)&&g>=0&&g<(null!==(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c.length)&&void 0!==d?d:0),v=_?"pickedMesh_"+g:"pickedMesh_unbound";s[1].config.variable=v,r._userVariables[v]=_?{className:"Mesh",id:null===(p=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[g]._babylonTransformNode)||void 0===p?void 0:p.id,uniqueId:null===(m=null===(f=null==i?void 0:i.nodes)||void 0===f?void 0:f[g]._babylonTransformNode)||void 0===m?void 0:m.uniqueId}:{type:"any",value:[{}]};const y=`${Ed}:event/onSelect:${g}`;return s[0].config.eventKey=y,s[0].config.useNaNDefaults=!0,s[0].config.pointerIdDefault=-1,s[4].config.eventKey=y,s}}),fr("/nodes/{}/extensions/KHR_node_selectability/selectable",{get:e=>Od(e,"selectable"),set:(e,t)=>{Fd(t,"selectable",e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"isPickable"],type:"boolean"}))}let Pd=!1;function Bd(){Pd||(Pd=!0,kd(),Ys(Ed),Xs(Ed,!0,e=>new Nd(e)))}var Dd={__proto__:null,KHR_node_selectability:Nd,RegisterKHR_node_selectability:Bd,_RegisterKHRNodeSelectabilityRuntime:kd};Bd();const Vd="KHR_node_hoverability",Gd="targetMeshPointerOver_",$d="targetMeshPointerOut_";class Ud{constructor(e){this.name=Vd,this.order=100,this._loader=e,this.enabled=e.isExtensionUsed(Vd)}onReady(){return b(this,void 0,void 0,function*(){var e;Id(null!==(e=this._loader.gltf.nodes)&&void 0!==e?e:[],"hoverable",e=>{var t,n;return null===(n=null===(t=e.extensions)||void 0===t?void 0:t.KHR_node_hoverability)||void 0===n?void 0:n.hoverable})})}dispose(){this._loader=null}}let Hd=!1;function Kd(){Hd||(Hd=!0,Iu("event/onHoverIn",Vd,{blocks:["FlowGraphPointerOverEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider","KHR_interactivity/FlowGraphEventReferenceBlock"],declarationSchema:{inputValueSockets:{},outputValueSockets:{hoveredNode:"ref",controllerIndex:"int",event:"ref"}},configuration:{nodeIndex:{name:"variable",configurationType:"int",toBlock:"FlowGraphGetVariableBlock",indexSource:"assetNodes",invalidUsesDefault:!0,dataTransformer:e=>Gd+e}},outputs:{values:{hoverNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},hoveredNode:{name:"nodeReference",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},controllerIndex:{name:"controllerIndex",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},event:{name:"value",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"}},flows:{out:{name:"out",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"}}},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},{input:"node",output:"meshUnderPointer",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"controllerIndexInput",output:"pointerId",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"in",output:"done",inputBlockIndex:4,outputBlockIndex:0}],extraProcessor(e,t,n,o,s,r,i){var a,l,u,c,d,h,p,f,m;const g=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],_="number"==typeof g&&Number.isInteger(g)&&g>=0&&g<(null!==(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c.length)&&void 0!==d?d:0),v=_?Gd+g:Gd+"unbound";s[1].config.variable=v,r._userVariables[v]=_?{className:"Mesh",id:null===(p=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[g]._babylonTransformNode)||void 0===p?void 0:p.id,uniqueId:null===(m=null===(f=null==i?void 0:i.nodes)||void 0===f?void 0:f[g]._babylonTransformNode)||void 0===m?void 0:m.uniqueId}:{type:"any",value:[{}]};const y=`${Vd}:event/onHoverIn:${g}`;return s[0].config.eventKey=y,s[4].config.eventKey=y,s}}),Iu("event/onHoverOut",Vd,{blocks:["FlowGraphPointerOutEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider","KHR_interactivity/FlowGraphEventReferenceBlock"],declarationSchema:{inputValueSockets:{},outputValueSockets:{hoveredNode:"ref",controllerIndex:"int",event:"ref"}},configuration:{nodeIndex:{name:"variable",configurationType:"int",toBlock:"FlowGraphGetVariableBlock",indexSource:"assetNodes",invalidUsesDefault:!0,dataTransformer:e=>$d+e}},outputs:{values:{hoverNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},hoveredNode:{name:"nodeReference",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},controllerIndex:{name:"controllerIndex",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},event:{name:"value",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"}},flows:{out:{name:"out",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"}}},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},{input:"node",output:"meshOutOfPointer",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"controllerIndexInput",output:"pointerId",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"in",output:"done",inputBlockIndex:4,outputBlockIndex:0}],extraProcessor(e,t,n,o,s,r,i){var a,l,u,c,d,h,p,f,m;const g=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],_="number"==typeof g&&Number.isInteger(g)&&g>=0&&g<(null!==(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c.length)&&void 0!==d?d:0),v=_?$d+g:$d+"unbound";s[1].config.variable=v,r._userVariables[v]=_?{className:"Mesh",id:null===(p=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[g]._babylonTransformNode)||void 0===p?void 0:p.id,uniqueId:null===(m=null===(f=null==i?void 0:i.nodes)||void 0===f?void 0:f[g]._babylonTransformNode)||void 0===m?void 0:m.uniqueId}:{type:"any",value:[{}]};const y=`${Vd}:event/onHoverOut:${g}`;return s[0].config.eventKey=y,s[4].config.eventKey=y,s}}),fr("/nodes/{}/extensions/KHR_node_hoverability/hoverable",{get:e=>Od(e,"hoverable"),set:(e,t)=>{Fd(t,"hoverable",e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"pointerOverDisableMeshTesting"],type:"boolean"}))}let jd=!1;function Wd(){jd||(jd=!0,Kd(),Ys(Vd),Xs(Vd,!0,e=>new Ud(e)))}var qd={__proto__:null,KHR_node_hoverability:Ud,RegisterKHR_node_hoverability:Wd,_RegisterKHRNodeHoverabilityRuntime:Kd};Wd();const zd="ExtrasAsMetadata";class Xd{_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=zd,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))}}let Yd=!1;function Qd(){Yd||(Yd=!0,Ys(zd),Xs(zd,!1,e=>new Xd(e)))}var Zd={__proto__:null,ExtrasAsMetadata:Xd,RegisterExtrasAsMetadata:Qd};Qd();class Jd 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 eh={__proto__:null,FlowGraphGLTFDataProvider:Jd};function th(e,t){let n=t;for(;n;){const t=e.getObjectReference(n,"nodes");if(null==t?void 0:t.startsWith("/nodes/"))return t;n=n.parent}return""}class nh extends t.FlowGraphBlock{constructor(e){super(e),this.object=this.registerDataInput("object",t.RichTypeAny),this.value=this.registerDataOutput("value",t.RichTypeString,"")}_updateOutputs(e){this.value.setValue(th(e,this.object.getValue(e)),e)}getClassName(){return"FlowGraphObjectReferenceBlock"}}var oh={__proto__:null,FlowGraphObjectReferenceBlock:nh,GetInteractivityObjectReference:th};class sh extends t.FlowGraphExecutionBlock{constructor(e){super(e),this.config=e,this._assetInverse=t.Matrix.Identity(),this._selectionPointValue=t.Vector3.Zero(),this._selectionRayOriginValue=t.Vector3.Zero();const n=new t.Vector3(NaN,NaN,NaN);this.node=this.registerDataInput("node",t.RichTypeAny),this.controllerIndexInput=this.registerDataInput("controllerIndexInput",t.RichTypeNumber,-1),this.selectionPointInput=this.registerDataInput("selectionPointInput",t.RichTypeVector3,n),this.selectionRayOriginInput=this.registerDataInput("selectionRayOriginInput",t.RichTypeVector3,n),this.nodeReference=this.registerDataOutput("nodeReference",t.RichTypeString,""),this.controllerIndex=this.registerDataOutput("controllerIndex",t.RichTypeNumber,-1),this.selectionPoint=this.registerDataOutput("selectionPoint",t.RichTypeVector3,n),this.selectionRayOrigin=this.registerDataOutput("selectionRayOrigin",t.RichTypeVector3,n),this.value=this.registerDataOutput("value",t.RichTypeString,""),this.out=this._registerSignalOutput("out")}_execute(e){var n;this.nodeReference.setValue(th(e,this.node.getValue(e)),e);const o=this.controllerIndexInput.getValue(e);if(o<0)this.controllerIndex.setValue(-1,e);else{const t=e._getGlobalContextVariable("khrInteractivityControllerIndices",new Map);let n=t.get(o);void 0===n&&(n=t.size,t.set(o,n),e._setGlobalContextVariable("khrInteractivityControllerIndices",t)),this.controllerIndex.setValue(n,e)}const s=this.node.getValue(e);let r=null==s?void 0:s.parent;for(;null==r?void 0:r.parent;)r=r.parent;(null==r?void 0:r.getWorldMatrix)?(r.getWorldMatrix().invertToRef(this._assetInverse),t.Vector3.TransformCoordinatesToRef(this.selectionPointInput.getValue(e),this._assetInverse,this._selectionPointValue),t.Vector3.TransformCoordinatesToRef(this.selectionRayOriginInput.getValue(e),this._assetInverse,this._selectionRayOriginValue),this.selectionPoint.setValue(this._selectionPointValue,e),this.selectionRayOrigin.setValue(this._selectionRayOriginValue,e)):(this.selectionPoint.setValue(this.selectionPointInput.getValue(e),e),this.selectionRayOrigin.setValue(this.selectionRayOriginInput.getValue(e),e)),this.value.setValue(e.getEventReference(null!==(n=this.config.eventKey)&&void 0!==n?n:"gltf:manual"),e),this.out._activateSignal(e)}getClassName(){return"FlowGraphEventReferenceBlock"}}var rh={__proto__:null,FlowGraphEventReferenceBlock:sh};function ih(e){switch(e){case"bool":return!1;case"int":return new t.FlowGraphInteger(0);case"float":return NaN;case"float2":return new t.Vector2(NaN,NaN);case"float3":return new t.Vector3(NaN,NaN,NaN);case"float4":return new t.Vector4(NaN,NaN,NaN,NaN);case"float2x2":return new t.FlowGraphMatrix2D([NaN,NaN,NaN,NaN]);case"float3x3":return new t.FlowGraphMatrix3D([NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN]);case"float4x4":return t.Matrix.FromArray([NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN]);case"ref":return"";default:return}}class ah extends t.FlowGraphExecutionBlock{constructor(e){var n,o,s,r;super(e),this.config=e,this._unregisterSignalInput("in"),this._unregisterSignalOutput("error");for(const o of null!==(n=e.inputValueSockets)&&void 0!==n?n:[])this.registerDataInput(o.name,t.getRichTypeByFlowGraphType(o.type));for(const n of null!==(o=e.outputValueSockets)&&void 0!==o?o:[])this.registerDataOutput(n.name,t.getRichTypeByFlowGraphType(n.type),ih(n.signature));for(const t of null!==(s=e.inputFlowSockets)&&void 0!==s?s:[])this._registerSignalInput(t);for(const t of null!==(r=e.outputFlowSockets)&&void 0!==r?r:[])this._registerSignalOutput(t)}_execute(e,t){}getClassName(){return"FlowGraphUnsupportedInteractivityBlock"}}var lh={__proto__:null,FlowGraphUnsupportedInteractivityBlock:ah},uh={__proto__:null,AddObjectAccessorToKey:fr,CloneKHRInteractivityGraph:Wu,CreateEffectiveKHRInteractivityGraph:oc,CreateKHRInteractivityDocument:cc,CreateKHRInteractivityExportPlan:nd,CreateKHRInteractivityGraphModel:uc,EXT_lights_area:Fi,EXT_lights_ies:li,EXT_lights_image_based:Br,EXT_mesh_gpu_instancing:Ur,EXT_meshopt_compression:qr,EXT_texture_avif:oi,EXT_texture_webp:Zr,ExtrasAsMetadata:Xd,FlowGraphEventReferenceBlock:sh,FlowGraphGLTFDataProvider:Jd,FlowGraphObjectReferenceBlock:nh,FlowGraphUnsupportedInteractivityBlock:ah,GetInteractivityNodeState:Od,GetInteractivityObjectReference:th,GetInteractivityOperationRegistry:Fu,GetKHRInteractivityImportResult:rd,GetKHRInteractivityImportResults:id,GetMappingForKey:hr,GetPathToObjectConverter:dr,HasDefaultInteractivityFlowInput:Mu,InitializeInteractivityNodeState:Id,InteractivityGraphToFlowGraphParser:_c,KHRInteractivityExportError:Oc,KHRInteractivityExportPlan:td,KHR_INTERACTIVITY_SPECIFICATION_COMMIT:Gu,KHR_animation_pointer:Gl,KHR_draco_mesh_compression:pi,KHR_gaussian_splatting:xi,KHR_interactivity:ad,KHR_lights:Si,KHR_materials_anisotropy:aa,KHR_materials_clearcoat:Wi,KHR_materials_coat:Qi,KHR_materials_diffuse_roughness:ml,KHR_materials_diffuse_transmission:Xa,KHR_materials_dispersion:cl,KHR_materials_emissive_strength:ha,KHR_materials_fuzz:Ta,KHR_materials_ior:Ea,KHR_materials_iridescence:na,KHR_materials_pbrSpecularGlossiness:Pi,KHR_materials_sheen:_a,KHR_materials_specular:Ra,KHR_materials_transmission:Ka,KHR_materials_unlit:$i,KHR_materials_variants:Ba,KHR_materials_volume:el,KHR_materials_volume_scatter:rl,KHR_mesh_quantization:bl,KHR_node_hoverability:Ud,KHR_node_selectability:Nd,KHR_node_visibility:md,KHR_texture_basisu:Ml,KHR_texture_transform:Ol,KHR_xmp_json_ld:kl,MSFT_audio_emitter:ru,MSFT_lod:cu,MSFT_minecraftMesh:mu,MSFT_sRGBFactors:bu,NormalizeInteractivityEventDataConfiguration:Su,ParseDebugLogTemplate:Bu,RegisterEXT_lights_area:Ni,RegisterEXT_lights_ies:ci,RegisterEXT_lights_image_based:Vr,RegisterEXT_mesh_gpu_instancing:Kr,RegisterEXT_meshopt_compression:Xr,RegisterEXT_texture_avif:ri,RegisterEXT_texture_webp:ei,RegisterExtrasAsMetadata:Qd,RegisterKHR_animation_pointer:Ul,RegisterKHR_draco_mesh_compression:mi,RegisterKHR_gaussian_splatting:Ai,RegisterKHR_interactivity:hd,RegisterKHR_lights:Ci,RegisterKHR_materials_anisotropy:ua,RegisterKHR_materials_clearcoat:zi,RegisterKHR_materials_coat:Ji,RegisterKHR_materials_diffuse_roughness:_l,RegisterKHR_materials_diffuse_transmission:Qa,RegisterKHR_materials_dispersion:hl,RegisterKHR_materials_emissive_strength:fa,RegisterKHR_materials_fuzz:wa,RegisterKHR_materials_ior:La,RegisterKHR_materials_iridescence:sa,RegisterKHR_materials_pbrSpecularGlossiness:Di,RegisterKHR_materials_sheen:ya,RegisterKHR_materials_specular:Ia,RegisterKHR_materials_transmission:Wa,RegisterKHR_materials_unlit:Hi,RegisterKHR_materials_variants:Va,RegisterKHR_materials_volume:nl,RegisterKHR_materials_volume_scatter:al,RegisterKHR_mesh_quantization:Tl,RegisterKHR_node_hoverability:Wd,RegisterKHR_node_selectability:Bd,RegisterKHR_node_visibility:yd,RegisterKHR_texture_basisu:Rl,RegisterKHR_texture_transform:El,RegisterKHR_xmp_json_ld:Bl,RegisterMSFT_audio_emitter:au,RegisterMSFT_lod:hu,RegisterMSFT_minecraftMesh:_u,RegisterMSFT_sRGBFactors:Tu,SetInteractivityNodeState:Fd,SetInterpolationForKey:pr,TransmissionHelper:$a,_AddInteractivityObjectModel:ld,_CaptureKHRInteractivityRuntimeInputDefaults:gc,_CreateKHRInteractivityRuntimeValueSnapshot:Ku,_NormalizeKHRInteractivityRuntimeValue:Uu,_RegisterKHRInteractivityRuntime:cd,_RegisterKHRNodeHoverabilityRuntime:Kd,_RegisterKHRNodeSelectabilityRuntime:kd,_RegisterKHRNodeVisibilityRuntime:_d,addNewInteractivityFlowGraphMapping:Iu,ensureTransmissionHelper:Ua,getAllSupportedNativeNodeTypes:Vu,getMappingForDeclaration:Ru,getMappingForFullOperationName:wu,getNoOpMappingForDeclaration:Cu,gltfTypeToBabylonType:$u},ch={__proto__:null,AddObjectAccessorToKey:fr,AnimationPropertyInfo:Sr,ArrayItem:_r,CloneKHRInteractivityGraph:Wu,CreateEffectiveKHRInteractivityGraph:oc,CreateKHRInteractivityDocument:cc,CreateKHRInteractivityExportPlan:nd,CreateKHRInteractivityGraphModel:uc,EXT_lights_area:Fi,EXT_lights_ies:li,EXT_lights_image_based:Br,EXT_mesh_gpu_instancing:Ur,EXT_meshopt_compression:qr,EXT_texture_avif:oi,EXT_texture_webp:Zr,ExtrasAsMetadata:Xd,FlowGraphEventReferenceBlock:sh,FlowGraphGLTFDataProvider:Jd,FlowGraphObjectReferenceBlock:nh,FlowGraphUnsupportedInteractivityBlock:ah,GLTFFileLoader:ts,GLTFLoader:yr,GetInteractivityNodeState:Od,GetInteractivityObjectReference:th,GetInteractivityOperationRegistry:Fu,GetKHRInteractivityImportResult:rd,GetKHRInteractivityImportResults:id,GetMappingForKey:hr,GetPathToObjectConverter:dr,HasDefaultInteractivityFlowInput:Mu,InitializeInteractivityNodeState:Id,InteractivityGraphToFlowGraphParser:_c,KHRInteractivityExportError:Oc,KHRInteractivityExportPlan:td,KHR_INTERACTIVITY_SPECIFICATION_COMMIT:Gu,KHR_animation_pointer:Gl,KHR_draco_mesh_compression:pi,KHR_gaussian_splatting:xi,KHR_interactivity:ad,KHR_lights:Si,KHR_materials_anisotropy:aa,KHR_materials_clearcoat:Wi,KHR_materials_coat:Qi,KHR_materials_diffuse_roughness:ml,KHR_materials_diffuse_transmission:Xa,KHR_materials_dispersion:cl,KHR_materials_emissive_strength:ha,KHR_materials_fuzz:Ta,KHR_materials_ior:Ea,KHR_materials_iridescence:na,KHR_materials_pbrSpecularGlossiness:Pi,KHR_materials_sheen:_a,KHR_materials_specular:Ra,KHR_materials_transmission:Ka,KHR_materials_unlit:$i,KHR_materials_variants:Ba,KHR_materials_volume:el,KHR_materials_volume_scatter:rl,KHR_mesh_quantization:bl,KHR_node_hoverability:Ud,KHR_node_selectability:Nd,KHR_node_visibility:md,KHR_texture_basisu:Ml,KHR_texture_transform:Ol,KHR_xmp_json_ld:kl,LoadBoundingInfoFromPositionAccessor:vr,MSFT_audio_emitter:ru,MSFT_lod:cu,MSFT_minecraftMesh:mu,MSFT_sRGBFactors:bu,NormalizeInteractivityEventDataConfiguration:Su,OpenPBRMaterialLoadingAdapter:Er,PBRMaterialLoadingAdapter:Lr,ParseDebugLogTemplate:Bu,RegisterEXT_lights_area:Ni,RegisterEXT_lights_ies:ci,RegisterEXT_lights_image_based:Vr,RegisterEXT_mesh_gpu_instancing:Kr,RegisterEXT_meshopt_compression:Xr,RegisterEXT_texture_avif:ri,RegisterEXT_texture_webp:ei,RegisterExtrasAsMetadata:Qd,RegisterGLTF2Loader:xr,RegisterGLTFLoaderAnimation:Or,RegisterKHR_animation_pointer:Ul,RegisterKHR_draco_mesh_compression:mi,RegisterKHR_gaussian_splatting:Ai,RegisterKHR_interactivity:hd,RegisterKHR_lights:Ci,RegisterKHR_materials_anisotropy:ua,RegisterKHR_materials_clearcoat:zi,RegisterKHR_materials_coat:Ji,RegisterKHR_materials_diffuse_roughness:_l,RegisterKHR_materials_diffuse_transmission:Qa,RegisterKHR_materials_dispersion:hl,RegisterKHR_materials_emissive_strength:fa,RegisterKHR_materials_fuzz:wa,RegisterKHR_materials_ior:La,RegisterKHR_materials_iridescence:sa,RegisterKHR_materials_pbrSpecularGlossiness:Di,RegisterKHR_materials_sheen:ya,RegisterKHR_materials_specular:Ia,RegisterKHR_materials_transmission:Wa,RegisterKHR_materials_unlit:Hi,RegisterKHR_materials_variants:Va,RegisterKHR_materials_volume:nl,RegisterKHR_materials_volume_scatter:al,RegisterKHR_mesh_quantization:Tl,RegisterKHR_node_hoverability:Wd,RegisterKHR_node_selectability:Bd,RegisterKHR_node_visibility:yd,RegisterKHR_texture_basisu:Rl,RegisterKHR_texture_transform:El,RegisterKHR_xmp_json_ld:Bl,RegisterMSFT_audio_emitter:au,RegisterMSFT_lod:hu,RegisterMSFT_minecraftMesh:_u,RegisterMSFT_sRGBFactors:Tu,SetInteractivityNodeState:Fd,SetInterpolationForKey:pr,TransformNodeAnimationPropertyInfo:Rr,TransmissionHelper:$a,WeightAnimationPropertyInfo:Cr,_AddInteractivityObjectModel:ld,_CaptureKHRInteractivityRuntimeInputDefaults:gc,_CreateKHRInteractivityRuntimeValueSnapshot:Ku,_NormalizeKHRInteractivityRuntimeValue:Uu,_RegisterKHRInteractivityRuntime:cd,_RegisterKHRNodeHoverabilityRuntime:Kd,_RegisterKHRNodeSelectabilityRuntime:kd,_RegisterKHRNodeVisibilityRuntime:_d,addNewInteractivityFlowGraphMapping:Iu,ensureTransmissionHelper:Ua,getAllSupportedNativeNodeTypes:Vu,getMappingForDeclaration:Ru,getMappingForFullOperationName:wu,getNoOpMappingForDeclaration:Cu,getQuaternion:wr,getVector3:Ar,getWeights:Mr,gltfTypeToBabylonType:$u,registerGLTFExtension:Xs,registeredGLTFExtensions:zs,unregisterGLTFExtension:Ys};class dh{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=dh._GetTexture(o,h,e);else if("map_kd"===d&&l)l.diffuseTexture=dh._GetTexture(o,h,e);else if("map_ks"===d&&l)l.specularTexture=dh._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=dh._GetTexture(o,t.join(" "),e),l.bumpTexture&&null!==s&&(l.bumpTexture.level=parseFloat(s))}else"map_d"===d&&l&&(l.opacityTexture=dh._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,dh.INVERT_TEXTURE_Y)}}dh.INVERT_TEXTURE_Y=!0;class hh{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 p=[];h.push(p);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((hh._IsGroupElement(t)||hh._IsObjectElement(t))&&(p=[],h.push(p)),hh._IsLineElement(t)){const e=t.split(" ");for(let t=1;t<e.length-1;t++)p.push(`l ${e[t]} ${e[t+1]}`)}else p.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(hh.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=hh.NormalPattern.exec(n)))this._normals.push(new t.Vector3(parseFloat(o[1]),parseFloat(o[2]),parseFloat(o[3])));else if(null!==(o=hh.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=hh.FacePattern3.exec(n)))this._setDataForCurrentFaceWithPattern3(o[1].trim().split(" "),1);else if(null!==(o=hh.FacePattern4.exec(n)))this._setDataForCurrentFaceWithPattern4(o[1].trim().split(" "),1);else if(null!==(o=hh.FacePattern5.exec(n)))this._setDataForCurrentFaceWithPattern5(o[1].trim().split(" "),1);else if(null!==(o=hh.FacePattern2.exec(n)))this._setDataForCurrentFaceWithPattern2(o[1].trim().split(" "),1);else if(null!==(o=hh.FacePattern1.exec(n)))this._setDataForCurrentFaceWithPattern1(o[1].trim().split(" "),1);else if(null!==(o=hh.LinePattern1.exec(n)))this._setDataForCurrentFaceWithPattern1(o[1].trim().split(" "),0),this._hasLineData=!0;else if(null!==(o=hh.LinePattern2.exec(n)))this._setDataForCurrentFaceWithPattern2(o[1].trim().split(" "),0),this._hasLineData=!0;else if(o=hh._GetZbrushMRGB(n,!this._loadingOptions.importVertexColors))for(const e of o)this._extColors.push(e);else if(null!==(o=hh.LinePattern3.exec(n)))this._setDataForCurrentFaceWithPattern3(o[1].trim().split(" "),0),this._hasLineData=!0;else if(hh.GroupDescriptor.test(n)||hh.ObjectDescriptor.test(n)){const e={name:n.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:hh.ObjectDescriptor.test(n)};this._addPreviousObjMesh(),this._meshesFromObj.push(e),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(hh.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 hh.MtlLibGroupDescriptor.test(n)?r(n.substring(7).trim()):hh.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)}}}hh.ObjectDescriptor=/^o/,hh.GroupDescriptor=/^g/,hh.MtlLibGroupDescriptor=/^mtllib /,hh.UseMtlDescriptor=/^usemtl /,hh.SmoothDescriptor=/^s /,hh.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/,hh.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,hh.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,hh.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/,hh.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,hh.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,hh.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,hh.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,hh.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/,hh.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/,hh.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;const ph={name:"obj",extensions:{".obj":{isBinary:!0}}};class fh{static get INVERT_TEXTURE_Y(){return dh.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){dh.INVERT_TEXTURE_Y=e}constructor(e){this.name=ph.name,this.extensions=ph.extensions,this._assetContainer=null,this._loadingOptions=Object.assign(Object.assign({},fh._DefaultLoadingOptions),null!=e?e:{})}static get _DefaultLoadingOptions(){return{encoding:fh.ENCODING,computeNormals:fh.COMPUTE_NORMALS,optimizeNormals:fh.OPTIMIZE_NORMALS,importVertexColors:fh.IMPORT_VERTEX_COLORS,invertY:fh.INVERT_Y,invertTextureY:fh.INVERT_TEXTURE_Y,UVScaling:fh.UV_SCALING,materialLoadingFailsSilently:fh.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:fh.OPTIMIZE_WITH_UV,skipMaterials:fh.SKIP_MATERIALS,useLegacyBehavior:fh.USE_LEGACY_BEHAVIOR}}_loadMTL(e,n,o,s){const r=n+e;t.Tools.LoadFile(r,o,void 0,void 0,!0,(e,t)=>{s(r,t)})}_decode(e){var t;if("string"==typeof e)return e;const n=new Uint8Array(e),o=null!==(t=this._loadingOptions.encoding)&&void 0!==t?t:"auto";if("auto"!==o)return new TextDecoder(o).decode(n);if(255===n[0]&&254===n[1])return new TextDecoder("utf-16le").decode(n);if(254===n[0]&&255===n[1])return new TextDecoder("utf-16be").decode(n);try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch(e){return new TextDecoder("gb18030").decode(n)}}createPlugin(e){return new fh(e[ph.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 dh,a=[],l=[];o=(o=this._decode(o)).replace(/#.*$/gm,"").trim(),new hh(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,this._decode(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})}}fh.ENCODING="auto",fh.OPTIMIZE_WITH_UV=!0,fh.INVERT_Y=!1,fh.IMPORT_VERTEX_COLORS=!1,fh.COMPUTE_NORMALS=!1,fh.OPTIMIZE_NORMALS=!1,fh.UV_SCALING=new t.Vector2(1,1),fh.SKIP_MATERIALS=!1,fh.MATERIAL_LOADING_FAILS_SILENTLY=!0,fh.USE_LEGACY_BEHAVIOR=!1;let mh=!1;function gh(){mh||(mh=!0,t.RegisterSceneLoaderPlugin(new fh))}var _h={__proto__:null,OBJFileLoader:fh,RegisterOBJFileLoader:gh};gh();var vh={__proto__:null,MTLFileLoader:dh,OBJFileLoader:fh,RegisterOBJFileLoader:gh,SolidParser:hh};const yh={name:"stl",extensions:{".stl":{isBinary:!0}}};class bh{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=yh.name,this.extensions=yh.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,bh.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}bh.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);)bh.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]));bh.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)}}bh.DO_NOT_ALTER_FILE_COORDINATES=!1;let xh=!1;function Th(){xh||(xh=!0,t.RegisterSceneLoaderPlugin(new bh))}var Ah={__proto__:null,RegisterSTLFileLoader:Th,STLFileLoader:bh};Th();var wh={__proto__:null,RegisterSTLFileLoader:Th,STLFileLoader:bh};const Mh={name:"splat",extensions:{".splat":{isBinary:!0},".ply":{isBinary:!0},".spz":{isBinary:!0},".json":{isBinary:!1},".sog":{isBinary:!0}}},Sh=.28209479177387814;function Rh(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 Ch(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 Rh(t,e,o.getEngine())}return yield Rh(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 p=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[p[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=p[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]]*Sh;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*Sh:1/(1+Math.exp(-u)),l[32*n+24+s]=Math.max(0,Math.min(255,Math.round(255*c)))}}}const m=e=>2*(e/255-.5)/Math.SQRT2,g=n[3].bits;for(let e=0;e<s;e++){const t=g[4*e+0],n=g[4*e+1],o=g[4*e+2],s=g[4*e+3],r=m(t),i=m(n),a=m(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),p=o.getEngine().getCaps().maxTextureSize,f=Math.ceil(s/p),m=t.AllocateShBuffers(h,f*p*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=m[a],d=i%16,h=16*t,p=127.5*e.shN.codebook[l[4*(o+n)+r+s*c*4]]+127.5;u[d+h]=Math.max(0,Math.min(255,p))}}}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=m[u],p=i%16,f=16*n,g=127.5*t.Scalar.Lerp(a,d,l[4*(s+o)+e+r*c*4]/255)+127.5;h[p+f]=Math.max(0,Math.min(255,g))}}return yield new Promise(e=>{e({mode:0,data:r,hasVertexColors:!1,sh:m,shDegree:a})})}return yield new Promise(e=>{e({mode:0,data:r,hasVertexColors:!1})})})}(s,a,o)})}function Ih(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 Oh(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 Rh(e,n,s);return Ih(o,r)})}function Fh(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 Eh(e,n,o){return b(this,arguments,void 0,function*(e,n,o,s=!0,r,i){var a,l,u,c,d,h,p;let f,m;if(e instanceof Map){m=e;const t=m.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 g=e=>b(this,void 0,void 0,function*(){if(m&&m.has(e))return yield Rh(m.get(e),e,o.getEngine());if(r){const t=new Uint8Array(yield r.loadFileAsync(n+e,i));return yield Rh(t,e,o.getEngine())}return yield Rh(n,e,o.getEngine())}),_=e=>b(this,void 0,void 0,function*(){if(m&&m.has(e))return yield Oh(m.get(e),e,o);if(r){const t=new Uint8Array(yield r.loadFileAsync(n+e,i));return yield Oh(t,e,o)}return yield Oh(n,e,o)}),v=[...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 y,x,T,A,w,M=null;if(s){const[e,t]=yield Promise.all([Promise.all(f.means.files.map(g)),Promise.all(v.map(_))]);M=[e[0],e[1]],w=t,y=Ih(o,e[0]),x=Ih(o,e[1]),T=e[0].width,A=e[0].height}else{const[e,t]=yield Promise.all([Promise.all(f.means.files.map(_)),Promise.all(v.map(_))]);w=t,y=e[0],x=e[1];const n=y.getSize();T=n.width,A=n.height}const S=null!==(u=f.count)&&void 0!==u?u:f.means.shape[0],R=T*A;if(R<S)throw new Error(`SOG texture contains ${R} texels, but metadata references ${S} splats.`);const C=w[0],I=w[1],O=w[2];let F,E,N,L=0,k=0;if(f.shN&&w.length>=5&&(F=w[3],E=w[4],L=f.shN.bands?Math.pow(f.shN.bands+1,2)-1:f.shN.shape[1]/3,k=null!==(c=f.shN.bands)&&void 0!==c?c:Math.round(Math.sqrt(L+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),N=new t.RawTexture(n,3*e,1,t.Constants.TEXTUREFORMAT_R,o,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_FLOAT),N.wrapU=t.Constants.TEXTURE_CLAMP_ADDRESSMODE,N.wrapV=t.Constants.TEXTURE_CLAMP_ADDRESSMODE}const P=f.means.mins,B=f.means.maxs,D={version:2===f.version?2:1,splatCount:S,shDegree:k,meansTextureL:y,meansTextureU:x,scalesTexture:C,quatsTexture:I,sh0Texture:O,shCentroidsTexture:F,shLabelsTexture:E,codebookTexture:N,meansMin:[P[0],P[1],P[2]],meansMax:[B[0],B[1],B[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===(p=f.shN)||void 0===p?void 0:p.maxs)?f.shN.maxs:void 0,shCoeffCount:L,positions:M?Fh(f,M[0].bits,M[1].bits,S):new Float32Array(0)};return{mode:0,data:new ArrayBuffer(0),hasVertexColors:!1,shDegree:k,sogTextures:D}})}const Nh="precision highp float;\nattribute vec3 position;\nvoid main() {\n gl_Position = vec4(position.xy, 0.0, 1.0);\n}\n",Lh="\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 kh{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}get shTextures(){return this._shMrts.map(e=>e.textures[0])}get rotationTextures(){return this._rotMrt?this._rotMrt.textures:[]}constructor(e,t,n,o,s){if(this._copyMaterial=null,this._relayoutMapData=null,this._relayoutMapTexture=null,this._backupMrt=null,this._disposed=!1,this._readFbo=null,this._shMrts=[],this._ownsShMrts=!1,this._shMaterial=null,this._shCopyMaterial=null,this._backupShMrts=null,this._rotMrt=null,this._ownsRotMrt=!1,this._rotMaterial=null,this._rotCopyMaterial=null,this._backupRotMrt=null,this._scene=e,this._shaderLanguage=e.getEngine().isWebGPU?1:0,this._capacity=Math.max(1,t),n?(this._mrt=n.mrt,this._textureSize=n.width,this._baseOffset=n.baseOffset,this._ownsMrt=!1):(this._textureSize=Math.max(1,Math.ceil(Math.sqrt(Math.max(1,t)))),this._baseOffset=0,this._ownsMrt=!0,this._mrt=this._createMrt("gsWorkBuffer",!0)),o&&o.textureCount>0){if(o.externalMrts)this._shMrts=o.externalMrts.slice(0,o.textureCount),this._ownsShMrts=!1;else{for(let e=0;e<o.textureCount;e++)this._shMrts.push(this._createShMrt(`gsWorkBufferSh${e}`,!0));this._ownsShMrts=!0}this._shMaterial=this._createShMaterial()}s&&(s.externalMrt?(this._rotMrt=s.externalMrt,this._ownsRotMrt=!1):(this._rotMrt=this._createRotMrt("gsWorkBufferRot",!0),this._ownsRotMrt=!0),this._rotMaterial=this._createRotMaterial()),this._material=this._createMaterial(),this._quad=this._createQuad(),this._quad.material=this._material,this._ownsMrt||this.isRelayoutReady()}rebindAtlas(e){this._ownsMrt||(this._mrt=e)}rebindShAtlas(e){!this._ownsShMrts&&e&&this._shMrts.length&&(this._shMrts=e.slice(0,this._shMrts.length))}rebindRotAtlas(e){!this._ownsRotMrt&&e&&this._rotMrt&&(this._rotMrt=e)}setBaseOffset(e){this._ownsMrt||(this._baseOffset=e)}get canBackup(){return!this._disposed&&!this._ownsMrt&&this.isRelayoutReady()}backupRegion(){if(this._disposed||this._ownsMrt)return;if(!this.isRelayoutReady())return void t.Logger.Warn("GaussianSplattingWorkBuffer: backup skipped because the copy shaders are not ready; streamed region data may be lost on the atlas rebuild.");const e=this._textureSize,n=Math.max(1,Math.floor(this._capacity/e)),o=Math.floor(this._baseOffset/e);if(this._backupMrt||(this._backupMrt=this._createMrt("gsAtlasBackup",!1,e,n)),this._renderRelayoutPass(this._backupMrt,this._mrt.textures,this._mrt.textures[0],0,e,e,0,-o),this._shMrts.length&&this._shCopyMaterial){this._backupShMrts||(this._backupShMrts=this._shMrts.map((t,o)=>this._createShMrt(`gsShAtlasBackup${o}`,!1,e,n)));for(let t=0;t<this._shMrts.length;t++)this._renderShCopyPass(this._backupShMrts[t],this._shMrts[t].textures[0],this._mrt.textures[0],0,e,e,0,-o)}this._rotMrt&&this._rotCopyMaterial&&(this._backupRotMrt||(this._backupRotMrt=this._createRotMrt("gsRotAtlasBackup",!1,e,n)),this._renderRotCopyPass(this._backupRotMrt,this._rotMrt.textures,this._mrt.textures[0],0,e,e,0,-o)),this._quad.material=this._material}restoreRegion(){var e;if(this._disposed||this._ownsMrt||!this._backupMrt||!this._copyMaterial)return;const t=this._textureSize,n=Math.max(1,Math.floor(this._capacity/t)),o=Math.floor(this._baseOffset/t),s=this._scene.getEngine();s.enableScissor(0,o,t,n);try{if(this._renderRelayoutPass(this._mrt,this._backupMrt.textures,this._backupMrt.textures[0],0,t,t,0,o),this._backupShMrts&&this._shMrts.length&&this._shCopyMaterial)for(let e=0;e<this._shMrts.length&&e<this._backupShMrts.length;e++)this._renderShCopyPass(this._shMrts[e],this._backupShMrts[e].textures[0],this._mrt.textures[0],0,t,t,0,o);this._backupRotMrt&&this._rotMrt&&this._rotCopyMaterial&&this._renderRotCopyPass(this._rotMrt,this._backupRotMrt.textures,this._mrt.textures[0],0,t,t,0,o)}finally{s.disableScissor(),this._quad.material=this._material}if(this._backupMrt.dispose(),this._backupMrt=null,this._backupShMrts){for(const e of this._backupShMrts)e.dispose();this._backupShMrts=null}null===(e=this._backupRotMrt)||void 0===e||e.dispose(),this._backupRotMrt=null}_createMrt(e,n,o=this._textureSize,s=this._textureSize){const r=this._scene.getEngine()._caps.textureHalfFloatRender?t.Constants.TEXTURETYPE_HALF_FLOAT:t.Constants.TEXTURETYPE_FLOAT,i=new t.MultiRenderTarget(e,{width:o,height:s},4,this._scene,{types:[t.Constants.TEXTURETYPE_FLOAT,r,r,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 i.clearColor=new t.Color4(0,0,0,0),i.renderList=[],n&&i.onClearObservable.add(()=>{}),i}_createShMrt(e,n,o=this._textureSize,s=this._textureSize){const r=new t.MultiRenderTarget(e,{width:o,height:s},1,this._scene,{types:[t.Constants.TEXTURETYPE_UNSIGNED_INTEGER],formats:[t.Constants.TEXTUREFORMAT_RGBA_INTEGER],samplingModes:[t.Constants.TEXTURE_NEAREST_SAMPLINGMODE],generateDepthBuffer:!1,generateDepthTexture:!1,generateMipMaps:!1},[e]);return r.clearColor=new t.Color4(0,0,0,0),r.renderList=[],n&&r.onClearObservable.add(()=>{}),r}_createRotMrt(e,n,o=this._textureSize,s=this._textureSize){const r=this._scene.getEngine()._caps.textureHalfFloatRender?t.Constants.TEXTURETYPE_HALF_FLOAT:t.Constants.TEXTURETYPE_FLOAT,i=new t.MultiRenderTarget(e,{width:o,height:s},3,this._scene,{types:[r,r,r],formats:[t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA],samplingModes:[t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE],generateDepthBuffer:!1,generateDepthTexture:!1,generateMipMaps:!1},[`${e}A`,`${e}B`,`${e}Scale`]);return i.clearColor=new t.Color4(0,0,0,0),i.renderList=[],n&&i.onClearObservable.add(()=>{}),i}decodeAsync(e,t){return b(this,void 0,void 0,function*(){if(this._disposed)return;this._applyPack(e);const n=null!==this._shMaterial&&this._shMrts.length>0;n&&this._applyShPack(e);const o=null!==this._rotMaterial&&null!==this._rotMrt;o&&this._applyRotPack(e),yield new Promise(s=>{const r=()=>{if(this._disposed)return void s();if(!this._material.isReady(this._quad)||n&&!this._shMaterial.isReady(this._quad)||o&&!this._rotMaterial.isReady(this._quad))return void this._scene.onBeforeRenderObservable.addOnce(r);const i=this._textureSize,a=this._baseOffset+t;this._material.setInt("uOffset",a),n&&this._shMaterial.setInt("uOffset",a),o&&this._rotMaterial.setInt("uOffset",a);const l=Math.floor(a/i),u=Math.max(1,Math.ceil((a+e.splatCount)/i)-l),c=this._scene.getEngine();c.enableScissor(0,l,i,u);try{if(this._quad.material=this._material,this._mrt.renderList=[this._quad],this._mrt.render(),n){for(let e=0;e<this._shMrts.length;e++)this._shMaterial.setInt("uShTextureIndex",e),this._quad.material=this._shMaterial,this._shMrts[e].renderList=[this._quad],this._shMrts[e].render();this._quad.material=this._material}o&&(this._quad.material=this._rotMaterial,this._rotMrt.renderList=[this._quad],this._rotMrt.render(),this._quad.material=this._material)}finally{c.disableScissor()}s()};this._scene.onBeforeRenderObservable.addOnce(r)})})}isRelayoutReady(){if(this._disposed)return!1;this._copyMaterial||(this._copyMaterial=this._createCopyMaterial()),this._shMrts.length&&!this._shCopyMaterial&&(this._shCopyMaterial=this._createShCopyMaterial()),this._rotMrt&&!this._rotCopyMaterial&&(this._rotCopyMaterial=this._createRotCopyMaterial()),this._bindCopyMaterialsToAtlas();const e=0===this._shMrts.length||null!==this._shCopyMaterial&&this._shCopyMaterial.isReady(this._quad),t=!this._rotMrt||null!==this._rotCopyMaterial&&this._rotCopyMaterial.isReady(this._quad);return this._copyMaterial.isReady(this._quad)&&e&&t}_bindCopyMaterialsToAtlas(){const e=this._mrt.textures;if(this._copyMaterial&&(this._copyMaterial.setTexture("uMapTex",e[0]),this._copyMaterial.setTexture("uSrc0",e[0]),this._copyMaterial.setTexture("uSrc1",e[1]),this._copyMaterial.setTexture("uSrc2",e[2]),this._copyMaterial.setTexture("uSrc3",e[3])),this._shCopyMaterial&&this._shMrts.length&&(this._shCopyMaterial.setTexture("uMapTex",e[0]),this._shCopyMaterial.setTexture("uSrcSh",this._shMrts[0].textures[0])),this._rotCopyMaterial&&this._rotMrt){const t=this._rotMrt.textures;this._rotCopyMaterial.setTexture("uMapTex",e[0]),this._rotCopyMaterial.setTexture("uSrc0",t[0]),this._rotCopyMaterial.setTexture("uSrc1",t[1]),this._rotCopyMaterial.setTexture("uSrc2",t[2])}}relayoutSync(e){if(this._disposed||!this._copyMaterial)return;const n=this._textureSize,o=n,s=this._ownsMrt?n:Math.max(1,Math.floor(this._capacity/n));this._relayoutMapData||(this._relayoutMapData=new Float32Array(o*s));const r=this._relayoutMapData;r.fill(-1),r.set(e.subarray(0,Math.min(e.length,r.length))),this._relayoutMapTexture?this._relayoutMapTexture.update(r):this._relayoutMapTexture=new t.RawTexture(r,o,s,t.Constants.TEXTUREFORMAT_R,this._scene,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_FLOAT);const i=this._relayoutMapTexture;if(this._ownsMrt){const e=this._createMrt("gsRelayoutTemp",!1);try{this._renderRelayoutPass(e,this._mrt.textures,i,1),this._renderRelayoutPass(this._mrt,e.textures,i,0)}finally{e.dispose()}if(this._shMrts.length&&this._shCopyMaterial)for(let e=0;e<this._shMrts.length;e++){const t=this._createShMrt("gsShRelayoutTemp",!1);try{this._renderShCopyPass(t,this._shMrts[e].textures[0],i,1),this._renderShCopyPass(this._shMrts[e],t.textures[0],i,0)}finally{t.dispose()}}if(this._rotMrt&&this._rotCopyMaterial){const e=this._createRotMrt("gsRotRelayoutTemp",!1);try{this._renderRotCopyPass(e,this._rotMrt.textures,i,1),this._renderRotCopyPass(this._rotMrt,e.textures,i,0)}finally{e.dispose()}}return void(this._quad.material=this._material)}const a=Math.floor(this._baseOffset/n),l=s,u=this._scene.getEngine(),c=this._createMrt("gsRelayoutTemp",!1,n,l),d=this._shMrts.length&&this._shCopyMaterial?this._shMrts.map((e,t)=>this._createShMrt(`gsShRelayoutTemp${t}`,!1,n,l)):[],h=this._rotMrt&&this._rotCopyMaterial?this._createRotMrt("gsRotRelayoutTemp",!1,n,l):null;try{this._renderRelayoutPass(c,this._mrt.textures,i,1,n,n,this._baseOffset,0);for(let e=0;e<d.length;e++)this._renderShCopyPass(d[e],this._shMrts[e].textures[0],i,1,n,n,this._baseOffset,0);h&&this._renderRotCopyPass(h,this._rotMrt.textures,i,1,n,n,this._baseOffset,0),u.enableScissor(0,a,n,l);try{this._renderRelayoutPass(this._mrt,c.textures,i,0,n,n,0,a);for(let e=0;e<d.length;e++)this._renderShCopyPass(this._shMrts[e],d[e].textures[0],i,0,n,n,0,a);h&&this._renderRotCopyPass(this._rotMrt,h.textures,i,0,n,n,0,a)}finally{u.disableScissor()}}finally{c.dispose();for(const e of d)e.dispose();null==h||h.dispose(),this._quad.material=this._material}}_renderRelayoutPass(e,t,n,o,s=this._textureSize,r=this._textureSize,i=0,a=0){const l=this._copyMaterial;l.setTexture("uMapTex",n),l.setTexture("uSrc0",t[0]),l.setTexture("uSrc1",t[1]),l.setTexture("uSrc2",t[2]),l.setTexture("uSrc3",t[3]),l.setInt("uDstWidth",s),l.setInt("uSrcWidth",r),l.setInt("uUseMap",o),l.setInt("uSrcBaseOffset",i),l.setInt("uDstBaseRow",a),this._quad.material=l,e.renderList=[this._quad],e.render()}_createCopyMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsWorkBufferRelayout",this._scene,{vertexSource:e?Lh:Nh,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// Region-scoped relayout (hosted compound atlas), both default 0 (standalone square path unchanged).\nuniform uSrcBaseOffset : i32;\nuniform uDstBaseRow : 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 = uniforms.uSrcBaseOffset + i32(m + 0.5);\n } else {\n srcIdx = (p.y - uniforms.uDstBaseRow) * 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// Region-scoped relayout (hosted compound atlas), both default 0 (standalone square path unchanged):\n// uSrcBaseOffset — added to the map's (region-local) source index so pass 1 reads the correct GLOBAL atlas texel.\n// uDstBaseRow — subtracted from the atlas destination row so pass 2's identity copy reads the region-local temp.\nuniform int uSrcBaseOffset;\nuniform int uDstBaseRow;\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 = uSrcBaseOffset + int(m + 0.5);\n } else {\n srcIdx = (p.y - uDstBaseRow) * 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","uSrcBaseOffset","uDstBaseRow"],samplers:["uMapTex","uSrc0","uSrc1","uSrc2","uSrc3"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_renderShCopyPass(e,t,n,o,s=this._textureSize,r=this._textureSize,i=0,a=0){const l=this._shCopyMaterial;l.setTexture("uMapTex",n),l.setTexture("uSrcSh",t),l.setInt("uDstWidth",s),l.setInt("uSrcWidth",r),l.setInt("uUseMap",o),l.setInt("uSrcBaseOffset",i),l.setInt("uDstBaseRow",a),this._quad.material=l,e.renderList=[this._quad],e.render()}_createShCopyMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsWorkBufferShCopy",this._scene,{vertexSource:e?Lh:Nh,fragmentSource:e?'\nvar uMapTexSampler : sampler;\nvar uMapTex : texture_2d<f32>;\n// Integer source sampled via textureLoad only — NO paired sampler (a sampler on a Uint texture fails WebGPU\n// validation: "None of the supported sample types (Uint)"). Mirrors the draw shader\'s shTexture0 declaration.\nvar uSrcSh : texture_2d<u32>;\n\nuniform uDstWidth : i32;\nuniform uSrcWidth : i32;\nuniform uUseMap : i32;\nuniform uSrcBaseOffset : i32;\nuniform uDstBaseRow : 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 = uniforms.uSrcBaseOffset + i32(m + 0.5);\n } else {\n srcIdx = (p.y - uniforms.uDstBaseRow) * uniforms.uDstWidth + p.x;\n }\n let s : vec2<i32> = vec2<i32>(srcIdx - (srcIdx / uniforms.uSrcWidth) * uniforms.uSrcWidth, srcIdx / uniforms.uSrcWidth);\n // Wrap in an explicit vec4<u32> so the WGSL processor emits an integer fragData location (its detection keys\n // off a literal vec4<u32>/vec4u in the assignment; a bare textureLoad(...) would default to vec4<f32>).\n fragmentOutputs.fragData0 = vec4<u32>(textureLoad(uSrcSh, s, 0));\n}\n':"precision highp float;\nprecision highp int;\nprecision highp usampler2D;\n\nuniform sampler2D uMapTex;\nuniform usampler2D uSrcSh;\nuniform int uDstWidth;\nuniform int uSrcWidth;\nuniform int uUseMap;\nuniform int uSrcBaseOffset;\nuniform int uDstBaseRow;\n\nlayout(location = 0) out uvec4 outSh;\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 = uSrcBaseOffset + int(m + 0.5);\n } else {\n srcIdx = (p.y - uDstBaseRow) * uDstWidth + p.x;\n }\n ivec2 s = ivec2(srcIdx - (srcIdx / uSrcWidth) * uSrcWidth, srcIdx / uSrcWidth);\n outSh = texelFetch(uSrcSh, s, 0);\n}\n"},{attributes:["position"],uniforms:["uDstWidth","uSrcWidth","uUseMap","uSrcBaseOffset","uDstBaseRow"],samplers:["uMapTex","uSrcSh"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_renderRotCopyPass(e,t,n,o,s=this._textureSize,r=this._textureSize,i=0,a=0){const l=this._rotCopyMaterial;l.setTexture("uMapTex",n),l.setTexture("uSrc0",t[0]),l.setTexture("uSrc1",t[1]),l.setTexture("uSrc2",t[2]),l.setInt("uDstWidth",s),l.setInt("uSrcWidth",r),l.setInt("uUseMap",o),l.setInt("uSrcBaseOffset",i),l.setInt("uDstBaseRow",a),this._quad.material=l,e.renderList=[this._quad],e.render()}_createRotCopyMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsWorkBufferRotCopy",this._scene,{vertexSource:e?Lh:Nh,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>;\n\nuniform uDstWidth : i32;\nuniform uSrcWidth : i32;\nuniform uUseMap : i32;\nuniform uSrcBaseOffset : i32;\nuniform uDstBaseRow : 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 = uniforms.uSrcBaseOffset + i32(m + 0.5);\n } else {\n srcIdx = (p.y - uniforms.uDstBaseRow) * 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}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D uMapTex;\nuniform sampler2D uSrc0;\nuniform sampler2D uSrc1;\nuniform sampler2D uSrc2;\nuniform int uDstWidth;\nuniform int uSrcWidth;\nuniform int uUseMap;\nuniform int uSrcBaseOffset;\nuniform int uDstBaseRow;\n\nlayout(location = 0) out vec4 glFragData[3];\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 = uSrcBaseOffset + int(m + 0.5);\n } else {\n srcIdx = (p.y - uDstBaseRow) * 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}\n"},{attributes:["position"],uniforms:["uDstWidth","uSrcWidth","uUseMap","uSrcBaseOffset","uDstBaseRow"],samplers:["uMapTex","uSrc0","uSrc1","uSrc2"],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=this._baseOffset+e,i=Math.floor(r/s),a=Math.ceil((r+t)/s)-i,l=4*(r-i*s),u=l+4*t,c=this._mrt.textures[0],d=this._scene.getEngine();if(d.isWebGPU){const e=yield c.readPixels(0,0,null,!0,!0,0,i,s,a);if(this._disposed||!e)return null;const t=e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.byteLength/4);return t.length>=u?t.subarray(l,u):null}const h=d,p=h._gl,f=null===(o=null===(n=c.getInternalTexture())||void 0===n?void 0:n._hardwareTexture)||void 0===o?void 0:o.underlyingResource;if(!f)return null;const m=new Float32Array(s*a*4);this._readFbo||(this._readFbo=p.createFramebuffer());const g=h._currentFramebuffer;p.bindFramebuffer(p.FRAMEBUFFER,this._readFbo),p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_2D,f,0),p.readBuffer(p.COLOR_ATTACHMENT0);const _=h._readPixelsAsync(0,i,s,a,p.RGBA,p.FLOAT,m);return p.bindFramebuffer(p.FRAMEBUFFER,g),g||p.readBuffer(p.BACK),_?(yield _,this._disposed||m.length<u?null:m.subarray(l,u)):null})}dispose(){var e,t,n,o,s,r,i,a,l,u;if(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._shMaterial)||void 0===t||t.dispose(!0,!1),null===(n=this._rotMaterial)||void 0===n||n.dispose(!0,!1),null===(o=this._copyMaterial)||void 0===o||o.dispose(!0,!1),null===(s=this._shCopyMaterial)||void 0===s||s.dispose(!0,!1),null===(r=this._rotCopyMaterial)||void 0===r||r.dispose(!0,!1),null===(i=this._relayoutMapTexture)||void 0===i||i.dispose(),null===(a=this._backupMrt)||void 0===a||a.dispose(),this._backupMrt=null,this._backupShMrts){for(const e of this._backupShMrts)e.dispose();this._backupShMrts=null}if(null===(l=this._backupRotMrt)||void 0===l||l.dispose(),this._backupRotMrt=null,this._ownsMrt&&this._mrt.dispose(),this._ownsShMrts)for(const e of this._shMrts)e.dispose();this._shMrts=[],this._ownsRotMrt&&(null===(u=this._rotMrt)||void 0===u||u.dispose()),this._rotMrt=null}_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?Lh:Nh,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){var n,o,s,r,i;const a=this._material,l=e.meansTextureL.getSize().width;a.setTexture("sogMeansLTex",e.meansTextureL),a.setTexture("sogMeansUTex",e.meansTextureU),a.setTexture("sogScalesTex",e.scalesTexture),a.setTexture("sogQuatsTex",e.quatsTexture),a.setTexture("sogSh0Tex",e.sh0Texture),a.setTexture("sogCodebookTex",null!==(n=e.codebookTexture)&&void 0!==n?n:e.sh0Texture),a.setVector3("sogMeansMin",new t.Vector3(e.meansMin[0],e.meansMin[1],e.meansMin[2])),a.setVector3("sogMeansMax",new t.Vector3(e.meansMax[0],e.meansMax[1],e.meansMax[2]));const u=null!==(o=e.scalesMin)&&void 0!==o?o:[0,0,0],c=null!==(s=e.scalesMax)&&void 0!==s?s:[0,0,0];a.setVector3("sogScalesMin",new t.Vector3(u[0],u[1],u[2])),a.setVector3("sogScalesMax",new t.Vector3(c[0],c[1],c[2]));const d=null!==(r=e.sh0Min)&&void 0!==r?r:[0,0,0,0],h=null!==(i=e.sh0Max)&&void 0!==i?i:[0,0,0,0];a.setVector4("sogSh0Min",new t.Vector4(d[0],d[1],d[2],d[3])),a.setVector4("sogSh0Max",new t.Vector4(h[0],h[1],h[2],h[3])),a.setInt("uVersion",e.version),a.setInt("uCount",e.splatCount),a.setInt("uDestWidth",this._textureSize),a.setInt("uSrcWidth",l)}_createShMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsSogShDecodeToWorkBuffer",this._scene,{vertexSource:e?Lh:Nh,fragmentSource:e?"\nvar sogShLabelsTexSampler : sampler;\nvar sogShLabelsTex : texture_2d<f32>;\nvar sogShCentroidsTexSampler : sampler;\nvar sogShCentroidsTex : texture_2d<f32>;\nvar sogCodebookTexSampler : sampler;\nvar sogCodebookTex : texture_2d<f32>;\n\nuniform sogShnMin : f32;\nuniform sogShnMax : f32;\nuniform uVersion : i32;\nuniform uOffset : i32;\nuniform uCount : i32;\nuniform uDestWidth : i32;\nuniform uSrcWidth : i32;\nuniform uCoeffs : i32;\nuniform uShTextureIndex : 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 kLocal : i32 = global - uniforms.uOffset;\n\n let lsz : vec2<i32> = vec2<i32>(textureDimensions(sogShLabelsTex, 0));\n let lsrc : vec2<i32> = vec2<i32>(kLocal - (kLocal / lsz.x) * lsz.x, kLocal / lsz.x);\n let labelRaw : vec4<f32> = textureLoad(sogShLabelsTex, lsrc, 0);\n let n : i32 = i32(labelRaw.r * 255.0 + 0.5) + i32(labelRaw.g * 255.0 + 0.5) * 256;\n let u : i32 = (n - (n / 64) * 64) * uniforms.uCoeffs;\n let v : i32 = n / 64;\n\n var packed : array<u32, 4> = array<u32, 4>(0u, 0u, 0u, 0u);\n\n for (var b : i32 = 0; b < 16; b = b + 1) {\n let s : i32 = uniforms.uShTextureIndex * 16 + b;\n let kc : i32 = s / 3;\n let j : i32 = s - kc * 3;\n var byteVal : f32 = 128.0;\n if (kc < uniforms.uCoeffs) {\n let centroidRaw : vec4<f32> = textureLoad(sogShCentroidsTex, vec2<i32>(u + kc, v), 0);\n var ch : f32 = centroidRaw.b;\n if (j == 0) { ch = centroidRaw.r; } else if (j == 1) { ch = centroidRaw.g; }\n var coeff : f32;\n if (uniforms.uVersion == 2) {\n let cidx : i32 = i32(ch * 255.0 + 0.5);\n coeff = textureLoad(sogCodebookTex, vec2<i32>(512 + cidx, 0), 0).r;\n } else {\n coeff = mix(uniforms.sogShnMin, uniforms.sogShnMax, ch);\n }\n byteVal = clamp(coeff * 127.5 + 127.5, 0.0, 255.0);\n }\n let bv : u32 = u32(byteVal + 0.5);\n let comp : i32 = b / 4;\n packed[comp] = packed[comp] | (bv << u32((b - comp * 4) * 8));\n }\n fragmentOutputs.fragData0 = vec4<u32>(packed[0], packed[1], packed[2], packed[3]);\n}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D sogShLabelsTex;\nuniform sampler2D sogShCentroidsTex;\nuniform sampler2D sogCodebookTex;\nuniform float sogShnMin;\nuniform float sogShnMax;\nuniform int uVersion;\nuniform int uOffset;\nuniform int uCount;\nuniform int uDestWidth;\nuniform int uSrcWidth;\nuniform int uCoeffs;\nuniform int uShTextureIndex;\n\nlayout(location = 0) out uvec4 outSh;\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 kLocal = global - uOffset;\n\n // 16-bit label for this source splat (LSB in r, MSB in g), indexed over the labels texture's own width.\n ivec2 lsz = textureSize(sogShLabelsTex, 0);\n ivec2 lsrc = ivec2(kLocal - (kLocal / lsz.x) * lsz.x, kLocal / lsz.x);\n vec4 labelRaw = texelFetch(sogShLabelsTex, lsrc, 0);\n int n = int(labelRaw.r * 255.0 + 0.5) + int(labelRaw.g * 255.0 + 0.5) * 256;\n int u = (n - (n / 64) * 64) * uCoeffs;\n int v = n / 64;\n\n uint packed0 = 0u;\n uint packed1 = 0u;\n uint packed2 = 0u;\n uint packed3 = 0u;\n\n for (int b = 0; b < 16; b++) {\n int s = uShTextureIndex * 16 + b; // flat SH scalar index\n int kc = s / 3; // higher-order coefficient (0-based)\n int j = s - kc * 3; // channel (0=r,1=g,2=b)\n float byteVal = 128.0; // neutral (decompose(128) ~= 0)\n if (kc < uCoeffs) {\n vec4 centroidRaw = texelFetch(sogShCentroidsTex, ivec2(u + kc, v), 0);\n float ch = (j == 0) ? centroidRaw.r : ((j == 1) ? centroidRaw.g : centroidRaw.b);\n float coeff;\n if (uVersion == 2) {\n int cidx = int(ch * 255.0 + 0.5);\n coeff = texelFetch(sogCodebookTex, ivec2(512 + cidx, 0), 0).r;\n } else {\n coeff = mix(sogShnMin, sogShnMax, ch);\n }\n byteVal = clamp(coeff * 127.5 + 127.5, 0.0, 255.0);\n }\n uint bv = uint(byteVal + 0.5);\n int comp = b / 4;\n uint contrib = bv << uint((b - comp * 4) * 8);\n if (comp == 0) { packed0 |= contrib; }\n else if (comp == 1) { packed1 |= contrib; }\n else if (comp == 2) { packed2 |= contrib; }\n else { packed3 |= contrib; }\n }\n outSh = uvec4(packed0, packed1, packed2, packed3);\n}\n"},{attributes:["position"],uniforms:["sogShnMin","sogShnMax","uVersion","uOffset","uCount","uDestWidth","uSrcWidth","uCoeffs","uShTextureIndex"],samplers:["sogShLabelsTex","sogShCentroidsTex","sogCodebookTex"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_applyShPack(e){var t,n,o,s,r;const i=this._shMaterial,a=!!e.shLabelsTexture&&!!e.shCentroidsTexture,l=null!==(t=e.shLabelsTexture)&&void 0!==t?t:e.sh0Texture,u=null!==(n=e.shCentroidsTexture)&&void 0!==n?n:e.sh0Texture;i.setTexture("sogShLabelsTex",l),i.setTexture("sogShCentroidsTex",u),i.setTexture("sogCodebookTex",null!==(o=e.codebookTexture)&&void 0!==o?o:l),i.setFloat("sogShnMin",null!==(s=e.shnMin)&&void 0!==s?s:0),i.setFloat("sogShnMax",null!==(r=e.shnMax)&&void 0!==r?r:0),i.setInt("uVersion",e.version),i.setInt("uCount",e.splatCount),i.setInt("uDestWidth",this._textureSize),i.setInt("uSrcWidth",l.getSize().width),i.setInt("uCoeffs",a?e.shCoeffCount:0)}_createRotMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsSogRotDecodeToWorkBuffer",this._scene,{vertexSource:e?Lh:Nh,fragmentSource:e?"\nvar sogScalesTexSampler : sampler;\nvar sogScalesTex : texture_2d<f32>;\nvar sogQuatsTexSampler : sampler;\nvar sogQuatsTex : texture_2d<f32>;\nvar sogCodebookTexSampler : sampler;\nvar sogCodebookTex : texture_2d<f32>;\n\nuniform sogScalesMin : vec3<f32>;\nuniform sogScalesMax : vec3<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 sRaw : vec3<f32> = textureLoad(sogScalesTex, src, 0).xyz;\n let qRaw : vec4<f32> = textureLoad(sogQuatsTex, src, 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\n fragmentOutputs.fragData0 = vec4<f32>(R[0], R[1].x);\n fragmentOutputs.fragData1 = vec4<f32>(R[1].y, R[1].z, R[2].x, R[2].y);\n fragmentOutputs.fragData2 = vec4<f32>(R[2].z, 2.0 * splatScale.x, 2.0 * splatScale.y, 2.0 * splatScale.z);\n}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D sogScalesTex;\nuniform sampler2D sogQuatsTex;\nuniform sampler2D sogCodebookTex;\n\nuniform vec3 sogScalesMin;\nuniform vec3 sogScalesMax;\nuniform int uVersion;\nuniform int uOffset;\nuniform int uCount;\nuniform int uDestWidth;\nuniform int uSrcWidth;\n\nlayout(location = 0) out vec4 glFragData[3];\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 sRaw = texelFetch(sogScalesTex, src, 0).xyz;\n vec4 qRaw = texelFetch(sogQuatsTex, src, 0);\n\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 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\n glFragData[0] = vec4(R[0], R[1].x);\n glFragData[1] = vec4(R[1].y, R[1].z, R[2].x, R[2].y);\n glFragData[2] = vec4(R[2].z, 2.0 * splatScale.x, 2.0 * splatScale.y, 2.0 * splatScale.z);\n}\n"},{attributes:["position"],uniforms:["sogScalesMin","sogScalesMax","uVersion","uOffset","uCount","uDestWidth","uSrcWidth"],samplers:["sogScalesTex","sogQuatsTex","sogCodebookTex"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_applyRotPack(e){var n,o,s;const r=this._rotMaterial,i=e.scalesTexture.getSize().width;r.setTexture("sogScalesTex",e.scalesTexture),r.setTexture("sogQuatsTex",e.quatsTexture),r.setTexture("sogCodebookTex",null!==(n=e.codebookTexture)&&void 0!==n?n:e.scalesTexture);const a=null!==(o=e.scalesMin)&&void 0!==o?o:[0,0,0],l=null!==(s=e.scalesMax)&&void 0!==s?s:[0,0,0];r.setVector3("sogScalesMin",new t.Vector3(a[0],a[1],a[2])),r.setVector3("sogScalesMax",new t.Vector3(l[0],l[1],l[2])),r.setInt("uVersion",e.version),r.setInt("uCount",e.splatCount),r.setInt("uDestWidth",this._textureSize),r.setInt("uSrcWidth",i)}}class Ph{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 Bh{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 Dh{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 Bh;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 Vh{constructor(e,t,n){this._blocks=new Map,this._cooldown=new Map,this._pinned=new Set,this._allocator=new Dh(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 Gh=Math.tan(22.5*Math.PI/180),$h=new t.Matrix,Uh=new t.Vector3,Hh=new t.Vector3,Kh=new t.Vector3,jh=new t.Vector3(0,0,1),Wh=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]],qh=2*Wh.length,zh=[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 Xh 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={}){var i,a,l,u,c;const d=Xh._NormalizeResidentLimit(null!==(i=r.maxResidentSplats)&&void 0!==i?i:0,"maxResidentSplats",!0),h=Xh._NormalizeResidentLimit(null!==(a=r.memoryBudgetMb)&&void 0!==a?a:0,"memoryBudgetMb",!1);super(e,null,s,!1),this._leafNodes=[],this._lod0SplatCount=Object.freeze({status:"pending"}),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._lodPixelThreshold=1,this._hostBudgetAllocation=null,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._cullCameraViewProj=new t.Matrix,this._cullViewProj=new t.Matrix,this._frustumScratch=[],this._workBuffer=null,this._streamShDegree=0,this._shTextureCount=0,this._needsRotationScale=!1,this._useGpuPositionReadback=!1,this._readbackCandidate=!1,this._readbackProbed=!1,this._residency=null,this._fileCounts=new Map,this._fileMeta=new Map,this._baseFileIds=new Set,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._minimumResidentSplats=0,this._maxResidentSplats=0,this._memoryBudgetMb=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._metadataReady=!1,this._framesSinceLodUpdate=0,this._lastLodCamPositions=[],this._lastLodSignature="",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._hostCompound=null,this._host=null,this._positionBase=0,this._unsubBeforeRebuild=null,this._unsubAfterRebuild=null,this._hostUnsubRemove=null,this._hostUnsubDispose=null,this._partReleasedByHost=!1,this._positionSnapshot=null,this._partReadyPromise=null,this._partReadyResolve=null,this._partReadyReject=null,this._partReadySettled=!1,this._metadata=n,this._rootUrl=o,this._streamOptions=r,this._hostCompound=null!==(l=r.hostCompound)&&void 0!==l?l:null,this._decodeSh=null===(u=r.decodeSh)||void 0===u||u,this._needsRotationScale=null!==(c=r.needsRotationScale)&&void 0!==c&&c;const p=Math.max(0,n.lodLevels-1);if(this._lodRangeMax=p,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,p))),void 0!==r.lodRangeMax&&(this._lodRangeMax=Math.max(this._lodRangeMin,Math.min(r.lodRangeMax,p))),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))),this._splatBudget=this._resolveSplatBudget(r.splatBudget),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))),this._maxResidentSplats=d,this._memoryBudgetMb=h,this._downloadManager=new Ph({maxConcurrent:r.maxConcurrentDownloads,maxRetries:r.maxDownloadRetries}),this._hostCompound){this.setEnabled(!1),this.isPickable=!1,this.doNotSerialize=!0,this._partReadyPromise=new Promise((e,t)=>{this._partReadyResolve=e,this._partReadyReject=t}),this._partReadyPromise.catch(()=>{});const e=this._hostCompound.onDisposeObservable.add(()=>{this._disposed||(this._partReleasedByHost=!0,this.dispose())});this._hostUnsubDispose=()=>this._hostCompound.onDisposeObservable.remove(e)}else this.scaling.y*=-1,this.rotation.x=-Math.PI/2;this._collectLodEntries(n.tree),r.debugDisplay&&(this.debugDisplay=!0),this._streamAllAsync().then(()=>{const e=this._partReadySettled;this._rejectPartReady("GaussianSplattingStream: stream produced no splats."),e||!this._hostCompound||this._disposed||this._disposeAndReclaim()},e=>{var n,o;this._lod0SplatCount=Object.freeze({status:"unavailable"}),t.Logger.Error("GaussianSplattingStream: streaming failed: "+(null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e)),this._rejectPartReady("GaussianSplattingStream: streaming failed: "+(null!==(o=null==e?void 0:e.message)&&void 0!==o?o:e)),this._disposed||this._disposeAndReclaim()})}getClassName(){return"GaussianSplattingStream"}isReady(e=!1){return!!this._hostCompound||super.isReady(e)}get streamingPartProxy(){var e,t;return null!==(t=null===(e=this._host)||void 0===e?void 0:e.proxy)&&void 0!==t?t:null}whenPartReadyAsync(){return b(this,void 0,void 0,function*(){var e;yield null!==(e=this._partReadyPromise)&&void 0!==e?e:Promise.resolve()})}_resolvePartReady(){var e;this._partReadySettled||(this._partReadySettled=!0,null===(e=this._partReadyResolve)||void 0===e||e.call(this))}_rejectPartReady(e){var t;this._partReadySettled||(this._partReadySettled=!0,null===(t=this._partReadyReject)||void 0===t||t.call(this,new Error(e)))}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._sinkIsDepthSortSettled?++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&&this._metadataReady&&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 splatBudget(){return this._splatBudget}set splatBudget(e){const t=e>0?Math.floor(e):0;t!==this._splatBudget&&(this._splatBudget=t,this._forceLodUpdate=!0)}get effectiveSplatBudget(){return this._effectiveSplatBudget()}get residentSplatBudget(){return this._residentBudget}get minimumResidentSplats(){return this._minimumResidentSplats}get lod0SplatCount(){return this._lod0SplatCount}_resolveSplatBudget(e){return void 0===e?0:"auto"===e?this._computeDefaultSplatBudget():e>0?Math.floor(e):0}_computeDefaultSplatBudget(){var e;return(null===(e=this._scene.getEngine().hostInformation)||void 0===e?void 0:e.isMobile)?"undefined"!=typeof navigator&&navigator.userAgent&&/iPad|iPhone|iPod/.test(navigator.userAgent)?15e5:1e6:25e5}_effectiveSplatBudget(){if(null!==this._hostBudgetAllocation){const e=Math.max(1,this._hostBudgetAllocation);return this._residentBudget>0?Math.min(e,this._residentBudget):e}return this._splatBudget<=0?0:this._residentBudget>0?Math.min(this._splatBudget,this._residentBudget):this._splatBudget}_splatBudgetEnabled(){return this._effectiveSplatBudget()>0}getBudgetDemand(){var e;if(!this._baseLayerReady)return 0;let t=this._environmentSplatCount();for(const n of this._leafNodes){const o=null!==(e=n.optimalLod)&&void 0!==e?e:n.baseLod;t+=this._countAtLevel(n,this._cappedLevelForNode(n,o))}return t}setBudgetAllocation(e){if(null===e)return void(null!==this._hostBudgetAllocation&&(this._hostBudgetAllocation=null,this._forceLodUpdate=!0));const t=this._hostBudgetAllocation;this._hostBudgetAllocation=e,null!==t&&e===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,o,s,r,i;this._disposed||(this._disposed=!0,this._rejectPartReady("GaussianSplattingStream: disposed before the part was ready."),null===(t=this._unsubBeforeRebuild)||void 0===t||t.call(this),null===(n=this._unsubAfterRebuild)||void 0===n||n.call(this),this._unsubBeforeRebuild=null,this._unsubAfterRebuild=null,null===(o=this._hostUnsubRemove)||void 0===o||o.call(this),null===(s=this._hostUnsubDispose)||void 0===s||s.call(this),this._hostUnsubRemove=null,this._hostUnsubDispose=null,this._hostCompound&&!this._hostCompound.isDisposed()&&this._hostCompound.unregisterLodBudgetParticipant(this),this._host&&this._hostCompound&&!this._partReleasedByHost&&!this._hostCompound.isDisposed()&&this._hostCompound.removePart(this._host.partIndex),this._host=null,this._lodObserver&&(this._scene.onBeforeRenderObservable.remove(this._lodObserver),this._lodObserver=null),this._clearDebugDisplay(),this._downloadManager.dispose(),null===(r=this._residency)||void 0===r||r.dispose(),this._residency=null,null===(i=this._workBuffer)||void 0===i||i.dispose(),this._workBuffer=null,super.dispose(e))}_disposeAndReclaim(){const e=this._hostCompound,t=!!this._host&&!this._partReleasedByHost;this.dispose(),t&&e&&!e.isDisposed()&&e.compactAtlas()}_getEffectiveWorldMatrix(e){return this._host?this._host.proxy.computeWorldMatrix(e):this.computeWorldMatrix(e)}_getActiveLodCameras(){var e;return((null===(e=this._scene.activeCameras)||void 0===e?void 0:e.length)?this._scene.activeCameras:this._scene.activeCamera?[this._scene.activeCamera]:[]).filter(e=>!!e)}evaluateOptimalLods(e=null){const n=e?[e]:this._getActiveLodCameras();if(0===n.length||0===this._leafNodes.length)return;const o=Math.max(0,this._metadata.lodLevels-1),s=this._lodBaseDistance,r=this._lodMultiplier,i=this._lodBehindPenalty,a=this._lodRangeMin,l=this._lodRangeMax,u=this._splatBudgetEnabled(),c=this._scene.getEngine().getRenderHeight()||1,d=this._scene.getEngine();this._getEffectiveWorldMatrix(!1).invertToRef($h);const h=n.map(e=>{const n=d.getAspectRatio(e)||1;let o=Math.tan(.5*e.fov);e.fovMode===t.Camera.FOVMODE_HORIZONTAL_FIXED&&(o/=n);const s=o*n,r=Math.min(o,s)/Gh,a=c*(e.viewport?e.viewport.height:1),l=t.Vector3.TransformCoordinatesToRef(e.globalPosition,$h,Uh),u={px:l.x,py:l.y,pz:l.z,fwx:0,fwy:0,fwz:0,fovScale:r,tanHalfV:o,pixelHeight:a};if(i>1){e.getDirectionToRef(jh,Kh);const n=t.Vector3.TransformNormalToRef(Kh,$h,Hh);n.normalize(),u.fwx=n.x,u.fwy=n.y,u.fwz=n.z}return u});for(const e of this._leafNodes){const t=e.bound.min,n=e.bound.max,c=.5*(t[0]+n[0]),d=.5*(t[1]+n[1]),p=.5*(t[2]+n[2]),f=n[0]-t[0],m=n[1]-t[1],g=n[2]-t[2],_=.5*Math.sqrt(f*f+m*m+g*g);let v=Number.POSITIVE_INFINITY,y=0;for(const e of h){const a=e.px<t[0]?t[0]:e.px>n[0]?n[0]:e.px,l=e.py<t[1]?t[1]:e.py>n[1]?n[1]:e.py,h=e.pz<t[2]?t[2]:e.pz>n[2]?n[2]:e.pz,f=a-e.px,m=l-e.py,g=h-e.pz,b=Math.sqrt(f*f+m*m+g*g);let x=b;if(i>1&&b>.01){const t=(e.fwx*f+e.fwy*m+e.fwz*g)/b;t<0&&(x=b*(1+-t*(i-1)))}const T=x*e.fovScale;let A;if(0===o||T<s)A=0;else for(A=o;A>1&&T<s*Math.pow(r,A-1);)A--;if(A<v&&(v=A),u){const t=c-e.px,n=d-e.py,o=p-e.pz,s=Math.sqrt(t*t+n*n+o*o),r=_*e.pixelHeight/(Math.max(s,1e-4)*e.tanHalfV);r>y&&(y=r)}}v<a?v=a:v>l&&(v=l),this._frustumCulling&&!1===e.inFrustum&&(v=l),e.optimalLod=v,u&&(e.pixelSize=y)}}_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=zh[this._displayedLodLevel(o)%zh.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 Wh)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*qh*4)}_updateDebugColors(){if(!this._debugMesh||!this._debugColorData)return;const e=this._debugColorData;let n=0;for(const t of this._leafNodes){const o=zh[this._displayedLodLevel(t)%zh.length];for(let t=0;t<qh;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){var n,o;if(e.children){for(const t of e.children)this._collectLodEntries(t);return}if(!e.lods)return;const s=null===(n=e.bound)||void 0===n?void 0:n.min,r=null===(o=e.bound)||void 0===o?void 0:o.max;if(!s||!r||s.length<3||r.length<3||!s.every(e=>Number.isFinite(e))||!r.every(e=>Number.isFinite(e)))return;const i=r[0]-s[0],a=r[1]-s[1],l=r[2]-s[2],u=Math.sqrt(i*i+a*a+l*l);if(!Number.isFinite(u)||u<=0)return;const c=Math.floor(Number(this._metadata.lodLevels)),d=Number.isFinite(c)&&c>0?c-1:0,h=[];for(const t of Object.keys(e.lods)){const n=Number(t),o=e.lods[t],s=o?Math.floor(Number(o.count)):NaN;Number.isInteger(n)&&String(n)===t&&n>=0&&n<=d&&o&&Number.isFinite(s)&&s>0&&(o.count=s,h.push(n))}if(0===h.length)return;h.sort((e,t)=>e-t);const p=[];let f=1/0;for(const t of h){const n=e.lods[String(t)].count;n<=f&&(p.push(t),f=n)}e.availableLevels=p,e.baseLod=p[p.length-1],e.activeLod=void 0,e.lodCooldown=0,e.inFrustum=!0,e.cullBounds=new t.BoundingInfo(t.Vector3.FromArray(s),t.Vector3.FromArray(r)),this._leafNodes.push(e)}_streamAllAsync(){return b(this,void 0,void 0,function*(){const e=this._collectAllFileIds(),n=this._collectBaseFileIds();this._baseFileIds.clear();for(const e of n)this._baseFileIds.add(e);if(this._leafNodes.length>0&&0===n.length)throw new Error("GaussianSplattingStream: no valid coarse source files were referenced.");const o=e.length>32&&n.length<e.length;o&&this._decodeSh&&(this._streamShDegree=4,this._shTextureCount=5);const s=o?n:e,r=yield this._gatherCountsAsync(s);if(this._disposed)return;for(const e of n){const t=this._fileCounts.get(e);if(!this._fileMeta.has(e)||void 0===t||t<=0)throw new Error(`GaussianSplattingStream: required coarse metadata for file ${e} is unavailable or invalid.`)}this._resolveMinimumResidentSplats(n,r),o||(this._resolveLod0SplatCount(),this._metadataReady=!0);let i=null;if(!o){i=1+r;for(const t of e){const e=this._fileCounts.get(t);void 0!==e&&e>0&&(i=Xh._SafeAddCounts(i,e,"stream capacity"))}}if(this._minimumResidentSplats<=1)throw new Error("GaussianSplattingStream: stream produced no splats.");let a=0;for(const e of n)a=Math.max(a,this._fileCounts.get(e));const l=this._resolveResidentBudget(i,a);if(this._evictionEnabled=o||null!==i&&l<i,this._residency=new Vh(l,this._evictionCooldownFrames,e=>this._onFileEvicted(e)),this._residency.pin(-2,1),r>0){const e=this._residency.allocate(-1,r);null!==e?this._environmentRange={offset:e,count:r}:(t.Logger.Warn("GaussianSplattingStream: environment does not fit the memory budget; skipping it."),this._environmentFiles=null)}if(this._hostCompound){const e=t.Matrix.Compose(new t.Vector3(1,-1,1),t.Quaternion.RotationYawPitchRoll(0,-Math.PI/2,0),t.Vector3.ZeroReadOnly),n=this._hostCompound.reserveStreamingPart(l,e,this.name+"_part",this._shTextureCount,this._streamShDegree,this._needsRotationScale);this._host=n,this._positionBase=n.base,this._hostCompound.registerLodBudgetParticipant(this);const o=this._hostCompound,s=o.onPartRemovedObservable.add(e=>{!this._disposed&&this._host&&e===this._host.partIndex&&(this._partReleasedByHost=!0,this.dispose())});this._hostUnsubRemove=()=>o.onPartRemovedObservable.remove(s);const r=this._shTextureCount>0&&n.shMrtAtlas?{textureCount:this._shTextureCount,externalMrts:n.shMrtAtlas}:void 0,i=this._needsRotationScale&&n.rotMrtAtlas?{externalMrt:n.rotMrtAtlas}:void 0;this._workBuffer=new kh(this._scene,n.capacity,{mrt:n.mrtAtlas,width:n.atlasWidth,baseOffset:n.base},r,i),this._readbackCandidate=this._workBuffer.supportsAsyncCentersReadback,this._splatPositions=n.splatPositions,this._vertexCount=l;const a=this._workBuffer;this._unsubBeforeRebuild=n.onBeforeAtlasRebuild(()=>{a.backupRegion(),this._positionSnapshot=this._splatPositions?this._splatPositions.slice(4*this._positionBase,4*(this._positionBase+this._vertexCount)):null}),this._unsubAfterRebuild=n.onAfterAtlasRebuild(()=>{n.mrtAtlas&&a.rebindAtlas(n.mrtAtlas),a.rebindShAtlas(n.shMrtAtlas),a.rebindRotAtlas(n.rotMrtAtlas),this._positionBase=n.base,a.setBaseOffset(n.base),a.restoreRegion(),this._splatPositions=n.splatPositions,this._positionSnapshot&&this._splatPositions&&(this._splatPositions.set(this._positionSnapshot,4*this._positionBase),this._positionSnapshot=null)}),n.setActiveRanges([])}else{const e=this._shTextureCount>0?{textureCount:this._shTextureCount}:void 0,t=this._needsRotationScale?{}:void 0;this._workBuffer=new kh(this._scene,l,void 0,e,t),this._readbackCandidate=this._workBuffer.supportsAsyncCentersReadback;const n=new Float32Array(4*l),o=this._workBuffer.textures,s=e?this._workBuffer.shTextures:void 0,r=t?this._workBuffer.rotationTextures:void 0;this._setExternalWorkBuffer(o[0],o[1],o[2],o[3],n,l,s,this._streamShDegree,r),this.setSplatIndexRanges([]),this.setEnabled(!0)}if(!(this._host&&this._workBuffer&&(yield this._waitForCanBackupAsync(this._workBuffer),this._disposed))){this._environmentRange&&this._environmentFiles&&(yield this._decodeEnvironmentAsync()),this._environmentFiles=null;for(const e of n){if(this._disposed)return;if(!(yield this._decodeFileAsync(e)))throw new Error(`GaussianSplattingStream: required coarse file ${e} failed to decode.`)}if(!this._disposed){for(const e of this._leafNodes)if(e.activeLod!==e.baseLod||void 0===e.activeFile)throw new Error("GaussianSplattingStream: the complete coarse layer could not be activated.");if(this._baseLayerReady=!0,this._resolvePartReady(),o){const t=e.filter(e=>!this._baseFileIds.has(e));if(yield this._gatherCountsAsync(t,!1),this._resolveLod0SplatCount(),this._metadataReady=!0,this._disposed)return}this._lodObserver||(this._lodObserver=this._scene.onBeforeRenderObservable.add(()=>this._onLodFrame()))}}})}_waitForCanBackupAsync(e){return b(this,void 0,void 0,function*(){for(let t=0;t<600&&!this._disposed;t++){if(e.canBackup)return;yield new Promise(e=>this._scene.onBeforeRenderObservable.addOnce(()=>e()))}this._disposed||e.canBackup||t.Logger.Warn("GaussianSplattingStream: backup/restore copy shaders did not compile in time; a grow/compaction before they are ready may drop streamed data.")})}_resolveResidentBudget(e=null,n=0){var o;const s=this._maxResidentSplats>0||this._memoryBudgetMb>0;let r=this._maxResidentSplats>0?this._maxResidentSplats:Number.POSITIVE_INFINITY;const i=this._bytesPerResidentSplat();if(this._memoryBudgetMb>0){const e=Math.floor(1024*this._memoryBudgetMb*1024/i);r=Math.min(r,e)}if(s||null===e)if(s)r<this._minimumResidentSplats&&t.Logger.Warn(`GaussianSplattingStream: the requested initial residency (${r} splats) is below the complete coarse minimum (${this._minimumResidentSplats}); using the minimum.`);else{const e=(null===(o=this._scene.getEngine().hostInformation)||void 0===o?void 0:o.isMobile)?256:512,t=Math.floor(1024*e*1024/i),s=Math.max(0,Math.floor(n)),a=Xh._SafeAddCounts(this._minimumResidentSplats,s,"automatic resident capacity");r=Math.max(t,a)}else r=e;if(r=Math.max(this._minimumResidentSplats,Math.floor(r)),null!==e&&(r=Math.min(r,e)),null!==e||this._minimumResidentSplats>0){const e=Math.floor(this._scene.getEngine().getCaps().maxTextureSize),t=e*e;if(!Number.isSafeInteger(t)||this._minimumResidentSplats>t)throw new Error(`GaussianSplattingStream: minimum resident splat count ${this._minimumResidentSplats} exceeds the device texture capacity ${t}.`);if(r>t&&(r=t),r<this._minimumResidentSplats)throw new Error(`GaussianSplattingStream: minimum resident splat count ${this._minimumResidentSplats} exceeds the device texture capacity ${t}.`)}if(!Number.isSafeInteger(r)||r<this._minimumResidentSplats||r<1)throw new Error("GaussianSplattingStream: resolved resident capacity is invalid.");return this._residentBudget=r,r}_bytesPerResidentSplat(){const e=this._scene.getEngine().getCaps().textureHalfFloatRender?24:48;return 84+16*this._shTextureCount+(this._needsRotationScale?e:0)}_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)}_collectBaseFileIds(){var e;const t=new Set;for(const n of this._leafNodes){const o=null===(e=n.lods)||void 0===e?void 0:e[String(n.baseLod)];o&&t.add(o.file)}return Array.from(t).sort((e,t)=>e-t)}_resolveMinimumResidentSplats(e,t){let n=Xh._SafeAddCounts(1,Math.max(0,Math.floor(t)),"minimum resident splats");for(const t of e){const e=this._fileCounts.get(t);if(void 0===e||!Number.isSafeInteger(e)||e<=0)throw new Error(`GaussianSplattingStream: required coarse metadata for file ${t} is unavailable or invalid.`);n=Xh._SafeAddCounts(n,e,"minimum resident splats")}this._minimumResidentSplats=n}_resolveLod0SplatCount(){var e,t;let n=0,o=!1;for(const s of this._leafNodes){if(0!==(null===(e=s.availableLevels)||void 0===e?void 0:e[0]))continue;const r=null===(t=s.lods)||void 0===t?void 0:t[0];if(!r)return void(this._lod0SplatCount=Object.freeze({status:"unavailable"}));if(o=!0,!this._fileCounts.has(r.file)||!this._fileMeta.has(r.file))return void(this._lod0SplatCount=Object.freeze({status:"unavailable"}));if(n+=r.count,!Number.isSafeInteger(n))return void(this._lod0SplatCount=Object.freeze({status:"unavailable"}))}this._lod0SplatCount=o?Object.freeze({status:"available",count:n}):Object.freeze({status:"unavailable"})}_gatherCountsAsync(e){return b(this,arguments,void 0,function*(e,n=!0){var o;let s=0,r=0,i=0;const a=e=>{const t=Xh._GetShInfo(e);t.degree>r&&(r=t.degree),t.coeffs>i&&(i=t.coeffs)};if(n&&this._metadata.environment)try{const e=this._rootUrl+this._metadata.environment,t=yield this._downloadManager.loadFileAsync(e),n=yield this._unzipAsync(new Uint8Array(t)),o=n.get("meta.json");if(o){const e=JSON.parse((new TextDecoder).decode(o));s=Xh._GetSplatCount(e),a(e),this._environmentFiles=n}}catch(e){t.Logger.Warn("GaussianSplattingStream: failed to load environment: "+(null!==(o=null==e?void 0:e.message)&&void 0!==o?o:e))}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,Xh._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}.`)})));for(const{sogData:e}of this._fileMeta.values())a(e);return this._decodeSh&&r>0&&i>0&&(this._streamShDegree=Math.max(this._streamShDegree,r),this._shTextureCount=Math.max(this._shTextureCount,Math.ceil(3*i/16))),s})}_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*(this._positionBase+t)),this._updateBounds(e,n),this._sinkPostPositionsRange(t,n)}_sinkSetActiveRanges(e){this._host?this._host.setActiveRanges(e):this.setSplatIndexRanges(e)}_sinkPostPositionsRange(e,t){this._host?this._host.postPositionsRange(e,t):this._postWorkerPositionsRange(e,t)}_sinkNotifyDataChanged(){this._host?this._host.notifyDataChanged():this._notifyWorkerNewData()}get _sinkIsDepthSortSettled(){return this._host?this._host.isDepthSortSettled:this._isDepthSortSettled}_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,n,o;if(!this._environmentRange||!this._environmentFiles||!this._workBuffer)return;const s=this._environmentRange;let r=!1;try{const n=(yield Eh(this._environmentFiles,"",this._scene,!this._useGpuPositionReadback,this._downloadManager)).sogTextures;if(!n)return void t.Logger.Warn("GaussianSplattingStream: environment decoding produced no texture data.");try{if(this._disposed||!this._workBuffer)return;if(yield this._workBuffer.decodeAsync(n,s.offset),this._disposed)return;const o=yield this._applyDecodedPositionsAsync(n,s.offset,s.count);if(this._disposed)return;if(!o)return void t.Logger.Warn("GaussianSplattingStream: decoded positions could not be applied for the environment.");if((null===(e=this._residency)||void 0===e?void 0:e.pin(-1,s.count))!==s.offset)throw new Error("GaussianSplattingStream: decoded environment could not be pinned.");r=!0,this._refreshActiveRanges()}finally{Xh._DisposePack(n)}}catch(e){t.Logger.Warn("GaussianSplattingStream: failed to decode environment: "+(null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e))}finally{r||(null===(o=this._residency)||void 0===o||o.free(-1),this._environmentRange=null)}})}_decodeFileAsync(e){return b(this,void 0,void 0,function*(){var n;if(this._decodedFiles.has(e))return!0;if(this._loadingFiles.has(e)||!this._residency)return!1;const o=this._fileMeta.get(e),s=this._fileCounts.get(e);if(!o||void 0===s)return!1;this._loadingFiles.add(e),this._cancelledDecodes.delete(e);let r=!1;try{const n=(yield Eh(o.sogData,o.subRootUrl,this._scene,!this._useGpuPositionReadback,this._downloadManager,e)).sogTextures;if(!n)return!1;const i=yield this._acquireDecodeGateAsync();try{if(this._disposed||!this._workBuffer||this._cancelledDecodes.has(e))return!1;const o=this._residency;if(!o)return!1;let i=o.allocate(e,s);if(null===i&&(i=yield this._relayoutAndAllocateAsync(e,s)),null===i)return this._cancelledDecodes.has(e)||t.Logger.Warn(`GaussianSplattingStream: resident memory budget full; skipping LOD file ${e}.`),!1;if(r=!0,this._disposed||!this._workBuffer||this._cancelledDecodes.has(e))return!1;if(yield this._workBuffer.decodeAsync(n,i),this._disposed||this._cancelledDecodes.has(e))return!1;const a=yield this._applyDecodedPositionsAsync(n,i,s);if(this._disposed)return!1;if(!a)return t.Logger.Warn(`GaussianSplattingStream: decoded positions could not be applied for LOD file ${e}.`),!1;if(this._baseFileIds.has(e)&&o.pin(e,s)!==i)throw new Error(`GaussianSplattingStream: required coarse file ${e} could not be pinned.`);return this._decodedFiles.add(e),this._applyDesiredLods()&&this._refreshActiveRanges(),!0}finally{Xh._DisposePack(n),i()}}catch(t){if(!this._cancelledDecodes.has(e))throw t;return!1}finally{r&&!this._decodedFiles.has(e)&&(null===(n=this._residency)||void 0===n||n.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,r=this._positionBase;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*(r+t.offset),4*(r+n),4*(r+n+t.count))}if(this._environmentRange){const e=this._residency.offset(-1);void 0!==e&&(this._environmentRange.offset=e)}this._sinkNotifyDataChanged(),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;const t=this._effectiveSplatBudget();if(t<=0){for(const t of this._leafNodes){const n=null!==(e=t.optimalLod)&&void 0!==e?e:t.baseLod;t.targetLevel=this._cappedLevelForNode(t,n)}return}const n=Math.max(0,t-this._environmentSplatCount());this._convergePixelThreshold(n);const o=this._lodPixelThreshold;for(const e of this._leafNodes)e.targetLevel=this._budgetedLevel(e,o)}_environmentSplatCount(){const e=this._environmentRange?Math.floor(Number(this._environmentRange.count)):0;return Number.isFinite(e)&&e>0?e:0}_budgetedLevel(e,t){var n,o;const s=null!==(n=e.optimalLod)&&void 0!==n?n:e.baseLod,r=null!==(o=e.pixelSize)&&void 0!==o?o:0;let i=0;return r>0&&t>r&&(i=Math.max(0,Math.round(Math.log(t/r)/Math.log(this._lodMultiplier)))),this._cappedLevelForNode(e,s+i)}_countAtLevel(e,t){const n=e.lods[String(t)];return n?n.count:0}_totalSplatsAtThreshold(e){let t=0;for(const n of this._leafNodes)t+=this._countAtLevel(n,this._budgetedLevel(n,e));return t}_convergePixelThreshold(e){if(this._totalSplatsAtThreshold(1)<=e)return void(this._lodPixelThreshold=1);let t=1;for(const e of this._leafNodes)e.pixelSize&&e.pixelSize>t&&(t=e.pixelSize);const n=Math.min(32,Math.max(1,this._metadata.lodLevels)),o=t*Math.pow(this._lodMultiplier,n+1);if(this._totalSplatsAtThreshold(o)>e)return void(this._lodPixelThreshold=o);let s=1,r=o;for(let t=0;t<40&&r-s>.001*r;t++){const t=.5*(s+r);this._totalSplatsAtThreshold(t)<=e?r=t:s=t}this._lodPixelThreshold=r}_residentLevelAtLeast(e,t){for(const n of e.availableLevels)if(n>=t&&this._decodedFiles.has(e.lods[String(n)].file))return n;return null}_applyDesiredLods(){var e;let t=!1;for(const n of this._leafNodes){const o=null!==(e=n.targetLevel)&&void 0!==e?e:n.baseLod;if(this._splatBudgetEnabled()&&void 0!==n.activeLod&&n.activeLod<o){const e=this._residentLevelAtLeast(n,o);null!==e&&e!==n.activeLod&&(this._switchActiveFile(n,n.lods[String(e)].file),n.activeLod=e,n.lodCooldown=this._lodCooldownFrames,t=!0)}if(n.lodCooldown&&n.lodCooldown>0)continue;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._getActiveLodCameras(),n=this._lodUpdateDistance;if(e.length!==this._lastLodCamPositions.length||this._computeLodSignature(e)!==this._lastLodSignature)s=!0;else for(let o=0;o<e.length;o++)if(t.Vector3.DistanceSquared(e[o].globalPosition,this._lastLodCamPositions[o])>=n*n){s=!0;break}}if(s){this._forceLodUpdate=!1,this._framesSinceLodUpdate=0;const e=this._getActiveLodCameras();this._lastLodCamPositions.length=0;for(const t of e)this._lastLodCamPositions.push(t.globalPosition.clone());this._lastLodSignature=this._computeLodSignature(e),this.evaluateOptimalLods(),this._computeTargetLevels(),this._applyDesiredLods()&&this._refreshActiveRanges()}}_computeLodSignature(e){const t=this._scene.getEngine();let n=`${t.getRenderWidth()}x${t.getRenderHeight()}#${this._getEffectiveWorldMatrix(!1).updateFlag}`;for(const t of e){const e=t.viewport;n+=`|${t.uniqueId}:${t.fov}:${t.fovMode}:${e.x},${e.y},${e.width},${e.height}`}return n}_updateNodeFrustum(){const e=this._getActiveLodCameras();let n=!1;if(!this._frustumCulling||0===e.length){for(const e of this._leafNodes)!1===e.inFrustum&&(e.inFrustum=!0,n=!0);return n}const o=this._leafNodes,s=this._frustumScratch,r=this._getEffectiveWorldMatrix(!1);for(let e=0;e<o.length;e++)s[e]=!1;for(const n of e){n.getViewMatrix().multiplyToRef(n.getProjectionMatrix(),this._cullCameraViewProj),r.multiplyToRef(this._cullCameraViewProj,this._cullViewProj),t.Frustum.GetPlanesToRef(this._cullViewProj,this._frustumPlanes);let e=!0;for(const t of this._frustumPlanes)if(!(Number.isFinite(t.normal.x)&&Number.isFinite(t.normal.y)&&Number.isFinite(t.normal.z)&&Number.isFinite(t.d)&&0!==t.normal.lengthSquared())){e=!1;break}if(e)for(let e=0;e<o.length;e++)!s[e]&&o[e].cullBounds.isInFrustum(this._frustumPlanes)&&(s[e]=!0);else for(let e=0;e<o.length;e++)s[e]=!0}for(let e=0;e<o.length;e++)s[e]!==o[e].inFrustum&&(o[e].inFrustum=s[e],n=!0);return n}static _NormalizeResidentLimit(e,t,n){if(!Number.isFinite(e))throw new RangeError(`GaussianSplattingStream: ${t} must be finite.`);if(e<=0)return 0;const o=n?Math.max(1,Math.floor(e)):e;if(o>Number.MAX_SAFE_INTEGER)throw new RangeError(`GaussianSplattingStream: ${t} is outside the supported range.`);return o}static _SafeAddCounts(e,t,n){const o=e+t;if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(o))throw new Error(`GaussianSplattingStream: ${n} exceeds the supported integer range.`);return o}static _GetSplatCount(e){var t;const n=null!==(t=e.count)&&void 0!==t?t:Array.isArray(e.means.shape)?e.means.shape[0]:0,o=Math.floor(Number(n));return Number.isFinite(o)&&o>0?o:0}static _GetShInfo(e){if(!e.shN)return{degree:0,coeffs:0};let n=0;const o=e.shN.bands;if("number"==typeof o&&Number.isFinite(o)&&o>0)n=Math.floor(o);else if(Array.isArray(e.shN.shape)&&Number.isFinite(e.shN.shape[1])&&e.shN.shape[1]>0){const t=Math.floor(e.shN.shape[1]/3);n=t>0?Math.round(Math.sqrt(t+1)-1):0}return n>0?(n>4&&(t.Logger.Warn(`GaussianSplattingStream: SH degree ${n} exceeds the maximum supported (4); clamping.`),n=4),{degree:n,coeffs:Math.pow(n+1,2)-1}):{degree:0,coeffs: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._host?this._host.expandBounds(o,s):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._sinkSetActiveRanges(Xh._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 Yh=.28209479177387814;let Qh=null,Zh=null;class Jh{constructor(e={}){this.name=Mh.name,this._assetContainer=null,this.extensions=Mh.extensions,this._loadingOptions=Object.assign(Object.assign({},Jh._DefaultLoadingOptions),e)}createPlugin(e){return new Jh(e[Mh.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(!Xh.IsLODMetadata(o))return null;const s=e._blockEntityCollection;e._blockEntityCollection=!!this._assetContainer;try{const t=new Xh("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=Jh._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?Eh:Ch;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=>{Jh._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=Jh._ExtractSafeOrbitLimits(o)}break;case 1:{const e=new t.PointsCloudSystem("PointCloud",1,n);Jh._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(Jh._BuildMesh(n,o));break;default:throw new Error("Unsupported Splat mode")}n._blockEntityCollection=!1,this.applyAutoCameraLimits(Jh._ExtractSafeOrbitLimits(o),n),e(r)}))},h=31===c[0]&&139===c[1],p=78===c[0]&&71===c[1]&&83===c[2]&&80===c[3];if(!h&&!p)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=Jh._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(Qh&&Zh===e)return yield Qh;const n=t._LoadScriptModuleAsync(`import createSpzModule from '${e}';\n const module = await createSpzModule();\n const returnedValue = module;`);return Zh=e,Qh=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 p=null;const f=e.shDegree;let m,g,_=null,v=0,y=null,b=null,x=null;if(f>0&&e.sh.length>0){v=3*((f+1)*(f+1)-1);const o=Math.ceil(v/16),r=n.getEngine().getCaps().maxTextureSize,i=Math.ceil(s/r);p=t.AllocateShBuffers(o,i*r*4*4),y=new Int32Array(o),b=new Int32Array(o);for(let e=0;e<o;e++)y[e]=16*e,b[e]=Math.min(16*(e+1),v);x=p,_=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 p=255*(.5+Yh*c[s+0]),f=255*(.5+Yh*c[s+1]),m=255*(.5+Yh*c[s+2]);a[n+24]=p<=0?0:p>=255?255:p+.5|0,a[n+25]=f<=0?0:f>=255?255:f+.5|0,a[n+26]=m<=0?0:m>=255?255:m+.5|0,a[n+27]=1/(1+Math.exp(-d[e]))*255+.5|0;const g=127.5*h[r+3]+127.5,T=127.5*h[r+0]+127.5,A=127.5*h[r+1]+127.5,w=127.5*h[r+2]+127.5;if(a[n+28]=g<=0?0:g>=255?255:g+.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]=w<=0?0:w>=255?255:w+.5|0,_&&x&&y&&b){const t=e*v,n=16*e;for(let e=0;e<x.length;e++){const o=x[e],s=y[e],r=b[e];for(let e=s;e<r;e++){const r=128*_[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){m=e.safeOrbitRadiusMin,g=[e.safeOrbitElevationMin,e.safeOrbitElevationMax];break}}return{mode:0,data:r,hasVertexColors:!1,sh:null!==p?p:void 0,shDegree:f>0?f:void 0,trainedWithAntialiasing:!!e.antialiased,safeOrbitCameraRadiusMin:m,safeOrbitCameraElevationMinMax:g}}(e,n,!0),t.createYieldingScheduler())})}(e.loadSpzFromBuffer(new Uint8Array(o),{to:e.CoordinateSystem.RUB}),n).then(e=>new Promise(t=>{f(e,t)})));if(p)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 m=new ReadableStream({start(e){e.enqueue(new Uint8Array(o)),e.close()}}),g=new DecompressionStream("gzip"),_=m.pipeThrough(g);return new Promise(e=>{new Response(_).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),p=new Int32Array(1),f=new Uint8Array(p.buffer),m=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,p[0]*h};let g=16;const _=new Float32Array(d),v=new Float32Array(d),y=new Uint8ClampedArray(d),b=new Uint8ClampedArray(d);for(let e=0;e<r;e++)_[8*e+0]=m(o,g+0),_[8*e+1]=m(o,g+3),_[8*e+2]=m(o,g+6),g+=9;for(let e=0;e<r;e++){for(let n=0;n<3;n++){const s=(o[g+r+3*e+n]-127.5)/38.25;y[32*e+24+n]=t.Scalar.Clamp(255*(.5+Yh*s),0,255)}y[32*e+24+3]=o[g+e]}g+=4*r;for(let e=0;e<r;e++)v[8*e+3+0]=Math.exp(o[g+0]/16-10),v[8*e+3+1]=Math.exp(o[g+1]/16-10),v[8*e+3+2]=Math.exp(o[g+2]/16-10),g+=3;if(c>=3){const e=Math.SQRT1_2;for(let t=0;t<r;t++){const n=[o[g+0],o[g+1],o[g+2],o[g+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]]);g+=4}}else for(let e=0;e<r;e++){const t=o[g+0],n=o[g+1],s=o[g+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),g+=3}if(i){const e=3*((i+1)*(i+1)-1),s=Math.ceil(e/16);let a=g;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,uint16:2,uchar:1,list:0};let p=1;const f=[],m=[],g=o.slice(0,s).split("\n"),_={};for(const n of g)if(n.startsWith("property ")){const[,o,s]=n.split(" ");if(1==p)m.push({name:s,type:o,offset:d}),d+=h[o];else if(0==p)f.push({name:s,type:o,offset:c}),c+=h[o];else if(2==p)f.push({name:s,type:o,offset:c});else if(3==p){const t=new DataView(e,d,2*h.float);_.safeOrbitCameraElevationMinMax=[t.getFloat32(0,!0),t.getFloat32(4,!0)]}else if(4==p){const t=new DataView(e,d,h.float);_.safeOrbitCameraRadiusMin=t.getFloat32(0,!0)}else if(5==p){const t=new DataView(e,d,h.uchar);"up_axis"==s?_.upAxis=0==t.getUint8(0)?"X":1==t.getUint8(0)?"Y":"Z":"chirality"==s&&(_.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?p=1:"vertex"==e?p=0:"sh"==e?p=2:"safe_orbit_camera_elevation_min_max_radians"==e?p=3:"safe_orbit_camera_radius_min"==e?p=4:"up_axis"!=e&&"chirality"!=e||(p=5)}const v=c,y=d;return t.GaussianSplattingMesh.ConvertPLYWithSHToSplatAsync(e).then(t=>b(this,void 0,void 0,function*(){const n=new DataView(e,s+11);let o=y*u+v*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 p=l==d.length&&c>=3,m=a?2:p?0:1;return yield new Promise(e=>{e(Object.assign(Object.assign({},_),{mode:m,data:t.buffer,sh:t.sh,shDegree:t.shDegree,faces:i,hasVertexColors:!!c,compressed:!1,rawSplat:!1}))})}))}}Jh._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 ep=!1;function tp(){ep||(ep=!0,t.RegisterSceneLoaderPlugin(new Jh))}var np={__proto__:null,RegisterSPLATFileLoader:tp,SPLATFileLoader:Jh};tp();const op={name:"usd",extensions:{".usd":{isBinary:!0},".usda":{isBinary:!0},".usdc":{isBinary:!0},".usdz":{isBinary:!0}}};var sp,rp,ip,ap;const lp=4294967295;var up,cp,dp,hp,pp,fp,mp,gp,_p,vp;function yp(e){switch(e){case 1:case 11:return 12;case 2:return 48;case 3:return 96;case 4:case 5:return 20;case 6:return 60;case 7:return 40;case 8:return 16;case 9:case 12:return 32;case 10:return 44;default:throw new Error(`Unknown OpenUSD Babylon command opcode ${e}.`)}}!function(e){e[e.Scene=1]="Scene",e[e.Texture=2]="Texture",e[e.Material=3]="Material",e[e.TransformNode=4]="TransformNode",e[e.Skeleton=5]="Skeleton",e[e.Geometry=6]="Geometry",e[e.Mesh=7]="Mesh",e[e.Instance=8]="Instance",e[e.Animation=9]="Animation",e[e.AnalyticPrimitive=10]="AnalyticPrimitive",e[e.ThinInstances=11]="ThinInstances",e[e.MorphTarget=12]="MorphTarget"}(up||(up={})),function(e){e[e.Cube=0]="Cube",e[e.Sphere=1]="Sphere",e[e.Cylinder=2]="Cylinder",e[e.Cone=3]="Cone"}(cp||(cp={})),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(dp||(dp={})),function(e){e[e.Node=0]="Node",e[e.Bone=1]="Bone",e[e.MorphTarget=2]="MorphTarget"}(hp||(hp={})),function(e){e[e.Position=0]="Position",e[e.RotationQuaternion=1]="RotationQuaternion",e[e.Scaling=2]="Scaling",e[e.Matrix=3]="Matrix",e[e.Influence=4]="Influence"}(pp||(pp={})),function(e){e[e.DoubleSided=1]="DoubleSided",e[e.Unlit=2]="Unlit",e[e.AlphaBlend=4]="AlphaBlend"}(fp||(fp={})),function(e){e[e.R=0]="R",e[e.G=1]="G",e[e.B=2]="B",e[e.A=3]="A",e[e.RGB=4]="RGB"}(mp||(mp={})),function(e){e[e.Auto=0]="Auto",e[e.Raw=1]="Raw",e[e.SRGB=2]="SRGB"}(gp||(gp={})),function(e){e[e.DoubleSided=1]="DoubleSided",e[e.LeftHanded=2]="LeftHanded"}(_p||(_p={})),function(e){e[e.Normals=1]="Normals",e[e.Tangents=2]="Tangents",e[e.Uv0=4]="Uv0",e[e.Colors=8]="Colors",e[e.Skin0=16]="Skin0",e[e.Skin1=32]="Skin1"}(vp||(vp={}));class bp{constructor(e,t,n){sp.add(this),rp.set(this,void 0),ip.set(this,void 0),T(this,rp,new DataView(e),"f"),this.offset=t,T(this,ip,t+n,"f")}u32(){x(this,sp,"m",ap).call(this,4);const e=x(this,rp,"f").getUint32(this.offset,!0);return this.offset+=4,e}f32(){x(this,sp,"m",ap).call(this,4);const e=x(this,rp,"f").getFloat32(this.offset,!0);return this.offset+=4,e}}rp=new WeakMap,ip=new WeakMap,sp=new WeakSet,ap=function(e){if(this.offset+e>x(this,ip,"f"))throw new Error("OpenUSD Babylon command payload read exceeded its bounds.")};class xp extends t.AbstractAssetContainer{dispose(){for(const e of this.animationGroups.splice(0))e.dispose();for(const e of this.meshes.splice(0))e.dispose();for(const e of this.morphTargetManagers.splice(0))e.dispose();for(const e of this.skeletons.splice(0))e.dispose();for(const e of this.multiMaterials.splice(0))e.dispose();for(const e of this.materials.splice(0))e.dispose();for(const e of this.geometries.splice(0))e.dispose();for(const e of this.transformNodes.splice(0))e.dispose();for(const e of this.textures.splice(0))e.dispose();this.rootNodes.length=0}}const Tp=new TextDecoder,Ap="__babylonUsdLocalMatrix";function wp(e,t,n,o,s){if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<0||t%Math.min(o,4)!==0||n>Math.floor((e.byteLength-t)/o))throw new Error(`Invalid ${s} range in OpenUSD Babylon data buffer.`)}function Mp(e,t,n){return wp(e,t,n,1,"string"),Tp.decode(new Uint8Array(e,t,n))}function Sp(e,n){wp(e,n,16,4,"matrix");const o=new Float32Array(e,n,16);return t.Matrix.FromValues(o[0],o[1],o[2],o[3],o[4],o[5],o[6],o[7],o[8],o[9],o[10],o[11],o[12],o[13],o[14],o[15])}function Rp(e){switch(e){case 2:return"image/jpeg";case 3:return"image/bmp";case 4:return"image/webp";default:return"image/png"}}function Cp(e){switch(e){case 0:return t.Texture.CLAMP_ADDRESSMODE;case 1:return t.Texture.WRAP_ADDRESSMODE;case 2:return t.Texture.MIRROR_ADDRESSMODE;default:throw new Error(`Invalid texture wrap mode ${e}.`)}}function Ip(e,t){return b(this,void 0,void 0,function*(){if(!t)return yield e;let n;const o=new Promise((e,o)=>{n=()=>o(t.reason instanceof Error?t.reason:new Error("USD materialization was aborted.")),t.addEventListener("abort",n,{once:!0}),t.aborted&&n()});try{return yield Promise.race([e,o])}finally{n&&t.removeEventListener("abort",n)}})}const Op=`${t.Tools._DefaultCdnUrl}/babylonUsdImporter/5/`,Fp=/\.(?:usd|usda|usdc|usdz)$/i;function Ep(e){return e instanceof Uint8Array?e.slice():e instanceof ArrayBuffer?new Uint8Array(e.slice(0)):new Uint8Array(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength))}function Np(e,t,n){const o=null==e?void 0:e.replace(/\\/g,"/").replace(/^\.\/+/,""),s=n?o:null==o?void 0:o.split(/[?#]/,1)[0],r=null==s?void 0:s.split("/").filter(Boolean);return s&&!s.startsWith("/")&&(null==r?void 0:r.length)&&!r.includes("..")&&Fp.test(s)?r.join("/"):t.length>=4&&80===t[0]&&75===t[1]&&3===t[2]&&4===t[3]?"scene.usdz":"scene.usd"}class Lp{constructor(e={}){var t,n,o,s,r;this.name=op.name,this.extensions=op.extensions,this._nextRequestId=1,this._pending=new Map,this._activeLoads=new Set,this._options=Object.assign(Object.assign({},e),{resolveByFileName:null===(t=e.resolveByFileName)||void 0===t||t,glueUrl:null!==(n=e.glueUrl)&&void 0!==n?n:Lp.DefaultConfiguration.glueUrl,wasmUrl:null!==(o=e.wasmUrl)&&void 0!==o?o:Lp.DefaultConfiguration.wasmUrl,dataUrl:null!==(s=e.dataUrl)&&void 0!==s?s:Lp.DefaultConfiguration.dataUrl,workerUrl:null!==(r=e.workerUrl)&&void 0!==r?r:Lp.DefaultConfiguration.workerUrl})}createPlugin(e){return Bp(),new Lp(e[op.name])}importMeshAsync(e,t,n,o,s,r){return b(this,void 0,void 0,function*(){return{meshes:(e=(yield this._loadAsync(t,n,o,s,r,!0)).container).meshes,particleSystems:e.particleSystems,skeletons:e.skeletons,animationGroups:e.animationGroups,transformNodes:e.transformNodes,geometries:e.geometries,lights:e.lights,spriteManagers:e.spriteManagers};var e})}loadAsync(e,t,n,o,s){return b(this,void 0,void 0,function*(){yield this._loadAsync(e,t,n,o,s,!0)})}loadAssetContainerAsync(e,n,o,s,r){return b(this,void 0,void 0,function*(){const i=(yield this._loadAsync(e,n,o,s,r,!1)).container;if(!(i instanceof t.AssetContainer))throw new Error("USDFileLoader failed to create an asset container.");return i})}dispose(){this._terminateWorker();const e=new Error("USDFileLoader was disposed.");for(const t of this._activeLoads)t.abort(e);for(const t of this._pending.values())t.reject(e);this._pending.clear()}_loadAsync(e,n,o,s,r,i){return b(this,void 0,void 0,function*(){var o,a,l,u,c,d;if(!(n instanceof ArrayBuffer||ArrayBuffer.isView(n)))throw new Error("USDFileLoader expects binary USD data.");const h=Ep(n),p=function(e){if(!e)return;const t={};for(const[n,o]of Object.entries(e))t[n]=Ep(o);return t}(this._options.files),f=this._nextRequestId++,m={type:"extract",requestId:f,asset:{bytes:h,files:p,fileName:Np(null!==(o=this._options.rootFileName)&&void 0!==o?o:r,h,void 0!==this._options.rootFileName),resolveByFileName:null===(a=this._options.resolveByFileName)||void 0===a||a,glueUrl:this._options.glueUrl,wasmUrl:this._options.wasmUrl,dataUrl:this._options.dataUrl}},g=[...new Set([h.buffer,...Object.values(null!=p?p:{}).map(e=>e.buffer)])],_=new AbortController,v=_.signal;this._activeLoads.add(_);try{const n=this._getWorker(this._options.workerUrl),o=yield new Promise((e,t)=>{this._pending.set(f,{resolve:e,reject:t,onProgress:e=>{var t,n;null===(n=(t=this._options).onProgress)||void 0===n||n.call(t,e),null==s||s({lengthComputable:!1,loaded:kp[e.phase],total:4})},onLog:this._options.onLog});try{n.postMessage(m,g)}catch(e){this._pending.delete(f),t(e instanceof Error?e:new Error(String(e)))}}),r={phase:"materializing",message:"Creating Babylon.js objects..."};null===(u=(l=this._options).onProgress)||void 0===u||u.call(l,r),null==s||s({lengthComputable:!1,loaded:4,total:4}),v.throwIfAborted();const a=yield function(e,n,o,s,r){return b(this,void 0,void 0,function*(){var i,a,l,u,c,d,h,p,f;null==r||r.throwIfAborted();const m=performance.now(),g=function(e){const t=new DataView(e);if(t.byteLength<16||1111774037!==t.getUint32(0,!0))throw new Error("Invalid OpenUSD Babylon command buffer.");if(5!==t.getUint16(4,!0))throw new Error(`Unsupported OpenUSD Babylon protocol ${t.getUint16(4,!0)}.`);const n=t.getUint32(8,!0),o=[];let s=16;for(let e=0;e<n;++e){if(s+8>t.byteLength)throw new Error("Truncated OpenUSD Babylon command header.");const e=t.getUint16(s,!0),n=t.getUint16(s+2,!0),r=t.getUint32(s+4,!0),i=s+8,a=yp(e);if(r!==a)throw new Error(`Invalid payload length ${r} for command ${e}; expected ${a}.`);if(i+r>t.byteLength)throw new Error("Truncated OpenUSD Babylon command payload.");o.push({opcode:e,flags:n,payloadOffset:i,payloadLength:r}),s=i+r}if(s!==t.byteLength)throw new Error("Unexpected trailing data in OpenUSD Babylon command buffer.");return o}(n),_=s?new xp:new t.AssetContainer(e),v=new Map,y=[],x=new Map,T=new Map,A=new Map,w=new Map,M=new Map,S=new Map,R=new Map,C=new Map,I=new Map,O=new Set,F=new Set,E=new Map,N=[],L=new Set,k=[],P=new Map,B=_ instanceof t.AssetContainer?_:void 0;let D,V=24,G=!1;const $=e.getEngine().getCaps(),U=$.textureHalfFloatRender&&$.textureHalfFloatLinearFiltering?t.Constants.TEXTURETYPE_HALF_FLOAT:$.textureFloatRender&&$.textureFloatLinearFiltering?t.Constants.TEXTURETYPE_FLOAT:t.Constants.TEXTURETYPE_UNSIGNED_BYTE,H=(e,t)=>{e.push(t),B&&(t._parentContainer=B)},K=(n,o)=>{const s=!(2&o);n.sideOrientation=e.useRightHandedSystem===s?t.Material.CounterClockWiseSideOrientation:t.Material.ClockWiseSideOrientation},j=(e,t)=>{const n=T.get(e);if(!n||!t||!n.backFaceCulling)return null!=n?n:null;let o=A.get(e);return o||(o=n.clone(`${n.name} (double-sided)`),H(_.materials,o),o.backFaceCulling=!1,o.twoSidedLighting=!0,A.set(e,o)),o},W=(e,t,n)=>{if(e===lp){if(t!==lp)throw new Error(`USD ${n} binding has a channel without a texture.`);return}const o=x.get(e);if(!o)throw new Error(`USD ${n} binding references missing texture ${e}.`);if(t<0||t>4)throw new Error(`USD ${n} binding has invalid output channel ${t}.`);return{descriptor:o,channel:t}},q=e=>{if(4===e)throw new Error("A scalar USD texture binding cannot use the RGB output.");return e},z=e=>1===e.descriptor.sourceColorSpace,X=(e,t,n)=>t.every((t,n)=>e.scale[n]===t)&&n.every((t,n)=>e.bias[n]===t),Y=(n,o,s,i,...a)=>b(this,[n,o,s,i,...a],void 0,function*(n,o,s,i,a=o.channel,l=!1){const u=o.descriptor,c=u.texture.getSize(),d=!(e.getEngine().needPOTTextures&&(c.width&c.width-1||c.height&c.height-1)),h={textureType:l?U:t.Constants.TEXTURETYPE_UNSIGNED_BYTE,samplingMode:d?t.Constants.TEXTURE_TRILINEAR_SAMPLINGMODE:t.Constants.TEXTURE_BILINEAR_SAMPLINGMODE,generateMipMaps:d};if(l&&U===t.Constants.TEXTURETYPE_UNSIGNED_BYTE&&s.slice(0,3).some((e,t)=>Math.min(i[t],i[t]+e)<0))throw new Error(`USD texture processing for '${n}' requires a floating-point render target to preserve signed values.`);const p=`${u.id}:${a}:${s.join(",")}:${i.join(",")}:${l}`,f=P.get(p);if(f)return yield f;const m=(()=>b(this,void 0,void 0,function*(){var o;const l=new t.Color4(i[0],i[1],i[2],i[3]),c=new t.Color4(i[0]+s[0],i[1]+s[1],i[2]+s[2],i[3]+s[3]),d=e._blockEntityCollection;let p;e._blockEntityCollection=!0;try{p=t.LerpTexturesAsync(n,t.CreateFactorOperand(l),t.CreateFactorOperand(c),t.CreateTextureOperand(u.texture,(e=>{switch(e){case 0:return t.TextureChannel.R;case 1:return t.TextureChannel.G;case 2:return t.TextureChannel.B;case 3:return t.TextureChannel.A;default:return t.TextureChannel.RGBA}})(a),1===u.sourceColorSpace?t.TextureColorSpace.Linear:t.TextureColorSpace.SRGB),e,t.TextureColorSpace.Linear,void 0,h)}finally{e._blockEntityCollection=d}const f=yield p;if(!f.texture)throw new Error(`USD texture processing for '${n}' did not produce a texture.`);if(G||(null==r?void 0:r.aborted))throw null===(o=f.dispose)||void 0===o||o.call(f),(null==r?void 0:r.aborted)&&r.throwIfAborted(),new Error("USD materialization was rolled back.");B||e.addTexture(f.texture);const m=(e=>(H(_.textures,e),e))(f.texture);m.gammaSpace=!1;const g=m;return g.uRotationCenter=u.texture.uRotationCenter,g.vRotationCenter=u.texture.vRotationCenter,g.wRotationCenter=u.texture.wRotationCenter,g.homogeneousRotationInUVTransform=u.texture.homogeneousRotationInUVTransform,m}))();P.set(p,m);try{return yield m}catch(e){throw P.delete(p),e}}),Q=(e,t)=>b(this,void 0,void 0,function*(){const n=q(t.channel),o=t.descriptor.scale[n],s=t.descriptor.bias[n];return yield Y(e,t,[o,o,o,1],[s,s,s,0],t.channel)}),Z=e=>b(this,void 0,void 0,function*(){var n,o,s,r;const{material:i,normalScale:a,base:l,opacity:u,normal:c,metallic:d,roughness:h,occlusion:p,emissive:f}=e;if(l){if(4!==l.channel)throw new Error("A USD base-color texture must use the RGB output.");i.albedoColor=t.Color3.White(),i.albedoTexture=X(l.descriptor,[1,1,1,1],[0,0,0,0])?l.descriptor.texture:yield Y(`${i.name} base color`,l,l.descriptor.scale,l.descriptor.bias)}if(f){if(4!==f.channel)throw new Error("A USD emissive texture must use the RGB output.");const e=f.descriptor;if(e.bias.slice(0,3).every(e=>0===e))i.emissiveColor=new t.Color3(e.scale[0],e.scale[1],e.scale[2]),i.emissiveTexture=e.texture;else{const n=Array.from({length:3},(t,n)=>Math.max(1,Math.abs(e.bias[n]),Math.abs(e.bias[n]+e.scale[n]))),o=e.scale.map((e,t)=>t<3?e/n[t]:e),s=e.bias.map((e,t)=>t<3?e/n[t]:e);i.emissiveColor=new t.Color3(n[0],n[1],n[2]),i.emissiveTexture=yield Y(`${i.name} emissive`,f,o,s,f.channel,!0)}}if(c){if(4!==c.channel)throw new Error("A USD normal texture must use the RGB output.");if(1===c.descriptor.sourceColorSpace&&X(c.descriptor,[2,2,2,1],[-1,-1,-1,0]))i.bumpTexture=c.descriptor.texture;else{const e=Array.from(c.descriptor.scale,e=>.5*e),t=Array.from(c.descriptor.bias,(e,t)=>t<3?.5*(e+1):e);i.bumpTexture=yield Y(`${i.name} normal`,c,e,t)}i.bumpTexture.gammaSpace=!1,i.bumpTexture.level=a}let m=!1;if(!d||!h||d.descriptor!==h.descriptor||0!==d.channel&&2!==d.channel||1!==h.channel&&3!==h.channel||!z(d)||0!==d.descriptor.bias[q(d.channel)]||0!==h.descriptor.bias[q(h.channel)]){if(d){const e=q(d.channel),t=z(d)&&(0===d.channel||2===d.channel)&&0===d.descriptor.bias[e];i.metallicTexture=t?d.descriptor.texture:yield Q(`${i.name} metallic`,d),i.useRoughnessFromMetallicTextureAlpha=!1,i.useRoughnessFromMetallicTextureGreen=!1,i.useMetallnessFromMetallicTextureBlue=t&&2===d.channel,i.metallic=t?(null!==(s=i.metallic)&&void 0!==s?s:1)*d.descriptor.scale[e]:1}if(h){const e=q(h.channel),t=z(h)&&0===h.channel&&0===h.descriptor.bias[e];i.microSurfaceTexture=t?h.descriptor.texture:yield Q(`${i.name} roughness`,h),i.microSurfaceTexture.gammaSpace=!!t&&h.descriptor.texture.gammaSpace,i.roughness=t?(null!==(r=i.roughness)&&void 0!==r?r:1)*h.descriptor.scale[e]:1}}else{const e=d.descriptor;i.metallicTexture=e.texture,i.metallic=(null!==(n=i.metallic)&&void 0!==n?n:1)*e.scale[q(d.channel)],i.roughness=(null!==(o=i.roughness)&&void 0!==o?o:1)*e.scale[q(h.channel)],i.useRoughnessFromMetallicTextureAlpha=3===h.channel,i.useRoughnessFromMetallicTextureGreen=1===h.channel,i.useMetallnessFromMetallicTextureBlue=2===d.channel,m=(null==p?void 0:p.descriptor)===e&&0===p.channel&&1===e.scale[0]&&0===e.bias[0],i.useAmbientOcclusionFromMetallicTextureRed=m}if(p&&!m){const e=q(p.channel),t=z(p)&&0===p.channel&&1===p.descriptor.scale[e]&&0===p.descriptor.bias[e];i.ambientTexture=t?p.descriptor.texture:yield Q(`${i.name} occlusion`,p),i.useAmbientInGrayScale=!0}if(u)if(l&&i.albedoTexture&&u.descriptor===l.descriptor&&3===u.channel&&1===u.descriptor.scale[3]&&0===u.descriptor.bias[3])i.albedoTexture.hasAlpha=!0,i.useAlphaFromAlbedoTexture=!0;else{const e=3===u.channel&&1===u.descriptor.scale[3]&&0===u.descriptor.bias[3];i.opacityTexture=e?u.descriptor.texture:yield Q(`${i.name} opacity`,u),i.opacityTexture.gammaSpace=!!e&&u.descriptor.texture.gammaSpace,i.opacityTexture.getAlphaFromRGB=!e}const g=A.get(e.id);g&&(g.albedoColor.copyFrom(i.albedoColor),g.albedoTexture=i.albedoTexture,g.emissiveColor.copyFrom(i.emissiveColor),g.emissiveTexture=i.emissiveTexture,g.bumpTexture=i.bumpTexture,g.metallic=i.metallic,g.roughness=i.roughness,g.metallicTexture=i.metallicTexture,g.microSurfaceTexture=i.microSurfaceTexture,g.ambientTexture=i.ambientTexture,g.opacityTexture=i.opacityTexture,g.alpha=i.alpha,g.useAlphaFromAlbedoTexture=i.useAlphaFromAlbedoTexture,g.useRoughnessFromMetallicTextureAlpha=i.useRoughnessFromMetallicTextureAlpha,g.useRoughnessFromMetallicTextureGreen=i.useRoughnessFromMetallicTextureGreen,g.useMetallnessFromMetallicTextureBlue=i.useMetallnessFromMetallicTextureBlue,g.useAmbientOcclusionFromMetallicTextureRed=i.useAmbientOcclusionFromMetallicTextureRed,g.useAmbientInGrayScale=i.useAmbientInGrayScale)});try{const A=e._blockEntityCollection;s||(e._blockEntityCollection=!0);try{for(const s of g){const r=new bp(n,s.payloadOffset,s.payloadLength);switch(s.opcode){case 1:{const n=1===r.u32(),o=r.f32();V=r.f32()||24,D=new t.TransformNode("USD Root",e),H(_.transformNodes,D),_.rootNodes.push(D),D.rotationQuaternion=n?t.Quaternion.FromArray([-.7071068,0,0,.7071068]):t.Quaternion.Identity(),D.scaling.copyFrom(e.useRightHandedSystem?new t.Vector3(o,o,o):n?new t.Vector3(o,-o,o):new t.Vector3(o,o,-o));break}case 2:{const n=r.u32();if(x.has(n))throw new Error(`Duplicate USD texture ${n}.`);const s=r.u32(),i=r.u32(),a=Rp(r.u32()),l=r.u32(),u=r.u32(),c=r.u32(),d=r.u32(),h=r.u32(),p=r.u32(),f=r.u32(),m=r.u32();if(wp(o,d,5,4,"texture transform"),wp(o,m,8,4,"texture value transform"),wp(o,l,u,1,"texture image"),f<0||f>2)throw new Error(`Invalid USD texture color space ${f}.`);const g=new Float32Array(o,d,5),v=new Float32Array(o,m,8);if(![...g,...v].every(Number.isFinite))throw new Error(`USD texture ${n} has a non-finite transform.`);const y=new Uint8Array(o,l,u),b=URL.createObjectURL(new Blob([y],{type:a}));let T,A;L.add(b);const w=new Promise((e,t)=>{T=e,A=t});N.push(w);const M=new t.Texture(b,e,!1,!1,t.Texture.TRILINEAR_SAMPLINGMODE,T,(e,t)=>{URL.revokeObjectURL(b),A(t instanceof Error?t:new Error(e||`Could not load texture '${b}'.`))});H(_.textures,M),M.onDisposeObservable.addOnce(()=>URL.revokeObjectURL(b)),M.name=Mp(o,s,i),M.coordinatesIndex=c,M.uScale=g[0],M.vScale=g[1],M.uRotationCenter=0,M.vRotationCenter=0,M.uOffset=g[2]-g[1]*Math.sin(g[4]),M.vOffset=1-g[1]*Math.cos(g[4])-g[3],M.wAng=-g[4],M.wrapU=Cp(h),M.wrapV=Cp(p),M.gammaSpace=1!==f,x.set(n,{id:n,texture:M,sourceColorSpace:f,scale:v.subarray(0,4),bias:v.subarray(4,8)});break}case 3:{const n=r.u32(),s=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=r.f32(),c=r.f32(),d=r.f32(),h=r.f32(),p=r.u32(),f=Array.from({length:7},()=>r.u32()),m=Array.from({length:7},()=>r.u32());wp(o,a,4,4,"material base color"),wp(o,l,3,4,"material emissive color");const g=new Float32Array(o,a,4),v=new Float32Array(o,l,3),y=new t.PBRMaterial(Mp(o,s,i),e);H(_.materials,y),y.id=`usd-material-${n}`,y.albedoColor=new t.Color3(g[0],g[1],g[2]),y.alpha=g[3],y.metallic=u,y.roughness=c,y.emissiveColor=new t.Color3(v[0],v[1],v[2]);const b=Boolean(1&p);y.backFaceCulling=!b,y.twoSidedLighting=b,y.unlit=Boolean(2&p),4&p&&(y.transparencyMode=2),h>0&&(y.transparencyMode=1,y.alphaCutOff=h),k.push({id:n,material:y,normalScale:d,base:W(f[0],m[0],"base-color texture"),opacity:W(f[1],m[1],"opacity texture"),normal:W(f[2],m[2],"normal texture"),metallic:W(f[3],m[3],"metallic texture"),roughness:W(f[4],m[4],"roughness texture"),occlusion:W(f[5],m[5],"occlusion texture"),emissive:W(f[6],m[6],"emissive texture")}),T.set(n,y);break}case 4:{const n=r.u32(),s=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=new t.TransformNode(Mp(o,i,a),e);H(_.transformNodes,u),u.setPreTransformMatrix(Sp(o,l)),Object.defineProperty(u,Ap,{configurable:!0,get:()=>u.getPivotMatrix(),set:e=>u.setPreTransformMatrix(e)}),v.set(n,u),s===lp?u.parent=null!=D?D:null:y.push({node:u,parentId:s});break}case 5:{const n=r.u32(),s=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=new t.Skeleton(Mp(o,s,i),`usd-skeleton-${n}`,e);H(_.skeletons,u);const c=new DataView(o);wp(o,l,6*a,4,"skeleton joints");const d=[];for(let e=0;e<a;++e){const s=l+24*e,r=c.getUint32(s,!0),i=c.getUint32(s+4,!0),a=c.getUint32(s+8,!0),h=c.getUint32(s+12,!0),p=c.getUint32(s+16,!0),f=c.getUint32(s+20,!0);if(r!==lp&&r>=e)throw new Error(`Skeleton ${n} has an invalid parent joint index.`);const m=new t.Bone(Mp(o,a,h),u,r===lp?null:d[r],Sp(o,p),Sp(o,p),Sp(o,f),e);d.push(m),M.set(i,m)}w.set(n,u);break}case 6:{const e=r.u32();S.set(e,{vertexCount:r.u32(),indexCount:r.u32(),flags:r.u32(),positions:r.u32(),normals:r.u32(),tangents:r.u32(),uv0:r.u32(),colors:r.u32(),joints0:r.u32(),weights0:r.u32(),joints1:r.u32(),weights1:r.u32(),indices:r.u32(),influences:r.u32()});break}case 7:{const n=r.u32(),s=r.u32(),u=r.u32(),c=r.u32(),d=r.u32(),h=r.u32(),p=r.u32(),f=r.u32(),m=r.u32(),g=r.u32(),y=S.get(u);if(!y)throw new Error(`Mesh ${n} references missing geometry ${u}.`);const b=new t.Mesh(Mp(o,d,h),e);H(_.meshes,b),K(b,p),b.parent=null!==(a=null!==(i=v.get(s))&&void 0!==i?i:D)&&void 0!==a?a:null;const x=new t.VertexData;wp(o,y.positions,3*y.vertexCount,4,"positions"),x.positions=new Float32Array(o,y.positions,3*y.vertexCount),1&y.flags&&(wp(o,y.normals,3*y.vertexCount,4,"normals"),x.normals=new Float32Array(o,y.normals,3*y.vertexCount)),2&y.flags&&(wp(o,y.tangents,4*y.vertexCount,4,"tangents"),x.tangents=new Float32Array(o,y.tangents,4*y.vertexCount)),4&y.flags&&(wp(o,y.uv0,2*y.vertexCount,4,"texture coordinates"),x.uvs=new Float32Array(o,y.uv0,2*y.vertexCount)),8&y.flags&&(wp(o,y.colors,4*y.vertexCount,4,"vertex colors"),x.colors=new Float32Array(o,y.colors,4*y.vertexCount)),16&y.flags&&(wp(o,y.joints0,4*y.vertexCount,2,"joint indices"),wp(o,y.weights0,4*y.vertexCount,4,"joint weights"),x.matricesIndices=Float32Array.from(new Uint16Array(o,y.joints0,4*y.vertexCount)),x.matricesWeights=new Float32Array(o,y.weights0,4*y.vertexCount)),32&y.flags&&(wp(o,y.joints1,4*y.vertexCount,2,"extra joint indices"),wp(o,y.weights1,4*y.vertexCount,4,"extra joint weights"),x.matricesIndicesExtra=Float32Array.from(new Uint16Array(o,y.joints1,4*y.vertexCount)),x.matricesWeightsExtra=new Float32Array(o,y.weights1,4*y.vertexCount)),wp(o,y.indices,y.indexCount,4,"indices"),x.indices=new Uint32Array(o,y.indices,y.indexCount),x.applyToMesh(b,!0),b.geometry&&H(_.geometries,b.geometry),b.numBoneInfluencers=Math.min(y.influences,8),f!==lp&&(b.skeleton=null!==(l=w.get(f))&&void 0!==l?l:null);const T=new DataView(o);wp(o,m,5*g,4,"submeshes");const A=Boolean(1&p);if(1===g&&c!==lp)b.material=j(c,A);else{const n=new t.MultiMaterial(`${b.name} materials`,e);H(_.multiMaterials,n);for(let e=0;e<g;++e){const t=m+20*e;n.subMaterials.push(j(T.getUint32(t,!0),A))}b.material=n}b.releaseSubMeshes();for(let e=0;e<g;++e){const n=m+20*e;new t.SubMesh(e,T.getUint32(n+12,!0),T.getUint32(n+16,!0),T.getUint32(n+4,!0),T.getUint32(n+8,!0),b)}R.set(n,b);break}case 12:{const n=r.u32(),s=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=r.u32(),c=r.u32(),d=r.f32(),h=R.get(s);if(!h)throw new Error(`Morph target references missing mesh ${s}.`);if(I.has(n)||l!==h.getTotalVertices()||!Number.isFinite(d))throw new Error(`Morph target ${n} has invalid metadata.`);wp(o,u,3*l,4,"morph target positions");let p=C.get(s);p||(p=new t.MorphTargetManager(e,h.name),p.areUpdatesFrozen=!0,H(_.morphTargetManagers,p),C.set(s,p));const f=new t.MorphTarget(Mp(o,i,a),d,e,p);f.id=`usd-morph-target-${n}`,f.setPositions(new Float32Array(o,u,3*l)),c!==lp&&(wp(o,c,3*l,4,"morph target normals"),f.setNormals(new Float32Array(o,c,3*l))),p.addTarget(f),I.set(n,f);break}case 10:{const n=r.u32(),s=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),d=r.u32(),h=r.u32(),p=r.u32(),f=r.f32(),m=r.f32(),g=r.u32(),y=Mp(o,l,d);if(!Number.isFinite(f)||f<=0)throw new Error(`Analytic primitive ${n} has an invalid size or radius.`);if((2===i||3===i)&&(!Number.isFinite(m)||m<=0))throw new Error(`Analytic primitive ${n} has an invalid height.`);if(0!==i&&(!Number.isInteger(g)||g<3||g>512))throw new Error(`Analytic primitive ${n} has invalid tessellation.`);let b;switch(i){case 0:b=t.CreateBox(y,{size:f},e);break;case 1:b=t.CreateSphere(y,{diameter:2*f,segments:g},e);break;case 2:case 3:b=t.CreateCylinder(y,{height:m,diameterTop:3===i?0:2*f,diameterBottom:2*f,tessellation:g},e);break;default:throw new Error(`Unsupported analytic primitive type ${i}.`)}if(H(_.meshes,b),b.geometry&&H(_.geometries,b.geometry),!(2&h)){const e=b.getIndices();if(!e)throw new Error(`Analytic primitive ${n} has no generated indices.`);const t=Array.from(e);for(let e=0;e<t.length;e+=3)[t[e],t[e+2]]=[t[e+2],t[e]];b.setIndices(t)}if(0===p)b.rotationQuaternion=t.Quaternion.RotationAxis(new t.Vector3(0,0,1),-Math.PI/2);else if(2===p)b.rotationQuaternion=t.Quaternion.RotationAxis(new t.Vector3(1,0,0),Math.PI/2);else if(1!==p)throw new Error(`Unsupported analytic primitive axis ${p}.`);K(b,h),b.parent=null!==(c=null!==(u=v.get(s))&&void 0!==u?u:D)&&void 0!==c?c:null,b.material=j(a,Boolean(1&h)),R.set(n,b);break}case 8:{const e=r.u32(),t=r.u32(),n=r.u32(),s=r.u32(),i=R.get(e);if(!i)throw new Error(`Instance references missing mesh ${e}.`);if(F.has(e))throw new Error(`Mesh ${e} cannot mix classic and thin instances.`);O.add(e);const a=i.createInstance(Mp(o,n,s));H(_.meshes,a),a.parent=null!==(h=null!==(d=v.get(t))&&void 0!==d?d:D)&&void 0!==h?h:null;break}case 11:{const e=r.u32(),t=r.u32(),n=r.u32(),s=R.get(e);if(!s)throw new Error(`Thin instances reference missing mesh ${e}.`);if(F.has(e)||O.has(e))throw new Error(`Mesh ${e} has duplicate or mixed thin instances.`);wp(o,t,16*n,4,"thin instance transforms"),s.thinInstanceSetBuffer("matrix",new Float32Array(o,t,16*n),16,!0),s.thinInstanceEnablePicking=!0,F.add(e);break}case 9:{const n=r.u32(),s=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=r.u32(),c=r.u32(),d=r.u32();if(0!==n&&1!==n&&2!==n)throw new Error(`Invalid animation target kind ${n}.`);if(2===n!=(4===i))throw new Error(`Invalid animation property ${i} for target kind ${n}.`);if(d!==(4===i?1:0===i||2===i?3:1===i?4:3===i?16:0))throw new Error(`Invalid animation value stride ${d} for property ${i}.`);const h=0===n?v.get(s):1===n?M.get(s):I.get(s);if(!h)break;const p=0===i?"position":1===i?"rotationQuaternion":2===i?"scaling":4===i?"influence":0===n?Ap:"_matrix",f=4===i?t.Animation.ANIMATIONTYPE_FLOAT:1===i?t.Animation.ANIMATIONTYPE_QUATERNION:3===i?t.Animation.ANIMATIONTYPE_MATRIX:t.Animation.ANIMATIONTYPE_VECTOR3,m=new t.Animation(`USD ${p}`,p,V,f,t.Animation.ANIMATIONLOOPMODE_CYCLE);wp(o,u,l,4,"animation times"),wp(o,c,l*d,4,"animation values");const g=new Float32Array(o,u,l),y=new Float32Array(o,c,l*d);m.setKeys(Array.from({length:l},(e,n)=>({frame:g[n],value:f===t.Animation.ANIMATIONTYPE_QUATERNION?t.Quaternion.FromArray(y,n*d):f===t.Animation.ANIMATIONTYPE_MATRIX?t.Matrix.FromArray(y,n*d):f===t.Animation.ANIMATIONTYPE_FLOAT?y[n*d]:t.Vector3.FromArray(y,n*d)})));let b=E.get(a);b||(b=new t.AnimationGroup(`USD Animation ${a+1}`,e),E.set(a,b),H(_.animationGroups,b)),b.addTargetedAnimation(m,h);break}}}for(const[e,n]of C)n.areUpdatesFrozen=!1,!n.isUsingTextureForTargets&&n.numTargets<=t.MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode&&(n.optimizeInfluencers=!1,n.numMaxInfluencers=n.numTargets),R.get(e).morphTargetManager=n}finally{s||(e._blockEntityCollection=A)}yield Ip(Promise.all(N),r),yield Ip(Promise.all(k.map(e=>b(this,void 0,void 0,function*(){yield Z(e)}))),r);for(const{node:e,parentId:t}of y)e.parent=null!==(f=null!==(p=v.get(t))&&void 0!==p?p:D)&&void 0!==f?f:null;return{container:_,materializeMs:performance.now()-m}}catch(e){G=!0,Promise.allSettled(N),Promise.allSettled(P.values()),_.dispose();for(const e of L)URL.revokeObjectURL(e);throw e}})}(e,o.commands,o.data,i,v),h={container:a.container,timings:Object.assign(Object.assign({},o.timings),{materializeMs:a.materializeMs}),statistics:o.statistics,missingAssets:o.missingAssets};try{v.throwIfAborted(),null===(d=(c=this._options).onComplete)||void 0===d||d.call(c,{timings:h.timings,statistics:h.statistics,missingAssets:h.missingAssets}),v.throwIfAborted()}catch(e){throw a.container.dispose(),e}return h}finally{this._activeLoads.delete(_),0===this._pending.size&&this._terminateWorker()}})}_getWorker(e){var t;if(!e)throw new Error("The USD worker URL was not configured.");const n=globalThis.location,o=new URL(String(e),null!==(t=null==n?void 0:n.href)&&void 0!==t?t:"http://localhost/").href;if(this._worker&&this._workerUrl!==o){if(this._pending.size>0)throw new Error("Cannot change the USD worker URL while requests are pending.");this._terminateWorker()}if(this._worker)return this._worker;this._workerUrl=o,n&&new URL(o).origin!==n.origin?(this._workerBlobUrl=URL.createObjectURL(new Blob([`import ${JSON.stringify(o)};`],{type:"application/javascript"})),this._worker=new Worker(this._workerBlobUrl,{type:"module"})):this._worker=new Worker(o,{type:"module"}),this._worker.addEventListener("message",e=>{var t,n;const o=e.data,s=this._pending.get(o.requestId);if(s)if("progress"!==o.type)if("log"!==o.type)if(this._pending.delete(o.requestId),"error"===o.type){const e=new Error(o.message);e.stack=o.stack,s.reject(e)}else s.resolve(o);else null===(n=s.onLog)||void 0===n||n.call(s,o.level>=2?"error":1===o.level?"warning":"info",o.message);else null===(t=s.onProgress)||void 0===t||t.call(s,o.progress)});const s=e=>{this._terminateWorker();for(const t of this._pending.values())t.reject(e);this._pending.clear()};return this._worker.addEventListener("error",e=>{var t;s(null!==(t=e.error)&&void 0!==t?t:new Error(e.message||`Could not load the USD worker from '${o}'.`))}),this._worker.addEventListener("messageerror",()=>{s(new Error("The USD worker returned a message that could not be deserialized."))}),this._worker}_terminateWorker(){var e;null===(e=this._worker)||void 0===e||e.terminate(),this._worker=void 0,this._workerUrl=void 0,this._workerBlobUrl&&(URL.revokeObjectURL(this._workerBlobUrl),this._workerBlobUrl=void 0)}}Lp.DefaultConfiguration={glueUrl:`${Op}babylon-usd-importer.js`,wasmUrl:`${Op}babylon-usd-importer.wasm`,dataUrl:`${Op}babylon-usd-importer.data`,workerUrl:`${Op}babylon-usd-importer.worker.js`};const kp={initializing:1,staging:2,extracting:3,materializing:4};let Pp=!1;function Bp(){t.RegisterPbrMaterial(),t.RegisterInstancedMesh(),t.RegisterThinInstanceMesh()}function Dp(){Pp||(Pp=!0,Bp(),t.RegisterSceneLoaderPlugin(new Lp))}var Vp={__proto__:null,RegisterUSDFileLoader:Dp,USDFileLoader:Lp,_RegisterUSDLoaderDependencies:Bp};function Gp(){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 v});return new t(e[f.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},xo),{createPlugin:e=>b(this,void 0,void 0,function*(){const{FBXFileLoader:t}=yield Promise.resolve().then(function(){return Go});return new t(e[xo.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},Wo),{createPlugin:e=>b(this,void 0,void 0,function*(){const[{GLTFFileLoader:t,RegisterGLTF2Loader:n},{RegisterInstancedMesh:o}]=yield Promise.all([Promise.resolve().then(function(){return Tr}),Promise.resolve(BABYLON)]);return o(),n(),new t(e[Wo.name])})})),function(){Ys("EXT_lights_image_based"),Xs("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 Gr});return new t(e)})),Ys("EXT_mesh_gpu_instancing"),Xs("EXT_mesh_gpu_instancing",!0,e=>b(this,void 0,void 0,function*(){const[{EXT_mesh_gpu_instancing:t},{RegisterThinInstanceMesh:n}]=yield Promise.all([Promise.resolve().then(function(){return jr}),Promise.resolve(BABYLON)]);return n(),new t(e)})),Ys("EXT_meshopt_compression"),Xs("EXT_meshopt_compression",!0,e=>b(this,void 0,void 0,function*(){const{EXT_meshopt_compression:t}=yield Promise.resolve().then(function(){return Yr});return new t(e)})),Ys("EXT_texture_avif"),Xs("EXT_texture_avif",!0,e=>b(this,void 0,void 0,function*(){const{EXT_texture_avif:t}=yield Promise.resolve().then(function(){return ii});return new t(e)})),Ys("EXT_texture_webp"),Xs("EXT_texture_webp",!0,e=>b(this,void 0,void 0,function*(){const{EXT_texture_webp:t}=yield Promise.resolve().then(function(){return ti});return new t(e)})),Ys("ExtrasAsMetadata"),Xs("ExtrasAsMetadata",!1,e=>b(this,void 0,void 0,function*(){const{ExtrasAsMetadata:t}=yield Promise.resolve().then(function(){return Zd});return new t(e)})),Ys("KHR_animation_pointer"),Xs("KHR_animation_pointer",!0,e=>b(this,void 0,void 0,function*(){const[{KHR_animation_pointer:t},{_RegisterKHRAnimationPointerData:n}]=yield Promise.all([Promise.resolve().then(function(){return Hl}),Promise.resolve().then(function(){return ou})]);return n(),new t(e)})),Ys("KHR_draco_mesh_compression"),Xs("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 gi});return new t(e)})),Ys("KHR_gaussian_splatting"),Xs("KHR_gaussian_splatting",!0,e=>b(this,void 0,void 0,function*(){const{KHR_gaussian_splatting:t}=yield Promise.resolve().then(function(){return wi});return new t(e)})),Ys("KHR_interactivity"),Xs("KHR_interactivity",!0,e=>b(this,void 0,void 0,function*(){const{KHR_interactivity:t,_RegisterKHRInteractivityRuntime:n}=yield Promise.resolve().then(function(){return pd});return n(),new t(e)})),Ys("KHR_lights_punctual"),Xs("KHR_lights_punctual",!0,e=>b(this,void 0,void 0,function*(){const{KHR_lights:t}=yield Promise.resolve().then(function(){return Ii});return new t(e)})),Ys("EXT_lights_area"),Xs("EXT_lights_area",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_area:t}=yield Promise.resolve().then(function(){return Li});return new t(e)})),Ys("EXT_lights_ies"),Xs("EXT_lights_ies",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_ies:t}=yield Promise.resolve().then(function(){return di});return new t(e)})),Ys("KHR_materials_anisotropy"),Xs("KHR_materials_anisotropy",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_anisotropy:t}=yield Promise.resolve().then(function(){return ca});return new t(e)})),Ys("KHR_materials_clearcoat"),Xs("KHR_materials_clearcoat",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_clearcoat:t}=yield Promise.resolve().then(function(){return Xi});return new t(e)})),Ys("KHR_materials_diffuse_roughness"),Xs("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 vl});return new t(e)})),Ys("KHR_materials_diffuse_transmission"),Xs("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 Za});return new t(e)})),Ys("KHR_materials_dispersion"),Xs("KHR_materials_dispersion",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_dispersion:t}=yield Promise.resolve().then(function(){return pl});return new t(e)})),Ys("KHR_materials_emissive_strength"),Xs("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 ma});return new t(e)})),Ys("KHR_materials_ior"),Xs("KHR_materials_ior",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_ior:t}=yield Promise.resolve().then(function(){return ka});return new t(e)})),Ys("KHR_materials_iridescence"),Xs("KHR_materials_iridescence",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_iridescence:t}=yield Promise.resolve().then(function(){return ra});return new t(e)})),Ys("KHR_materials_pbrSpecularGlossiness"),Xs("KHR_materials_pbrSpecularGlossiness",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_pbrSpecularGlossiness:t}=yield Promise.resolve().then(function(){return Vi});return new t(e)})),Ys("KHR_materials_sheen"),Xs("KHR_materials_sheen",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_sheen:t}=yield Promise.resolve().then(function(){return ba});return new t(e)})),Ys("KHR_materials_specular"),Xs("KHR_materials_specular",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_specular:t}=yield Promise.resolve().then(function(){return Oa});return new t(e)})),Ys("KHR_materials_transmission"),Xs("KHR_materials_transmission",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_transmission:t}=yield Promise.resolve().then(function(){return qa});return new t(e)})),Ys("KHR_materials_unlit"),Xs("KHR_materials_unlit",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_unlit:t}=yield Promise.resolve().then(function(){return Ki});return new t(e)})),Ys("KHR_materials_variants"),Xs("KHR_materials_variants",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_variants:t}=yield Promise.resolve().then(function(){return Ga});return new t(e)})),Ys("KHR_materials_volume"),Xs("KHR_materials_volume",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_volume:t}=yield Promise.resolve().then(function(){return ol});return new t(e)})),Ys("KHR_mesh_quantization"),Xs("KHR_mesh_quantization",!0,e=>b(this,void 0,void 0,function*(){const{KHR_mesh_quantization:t}=yield Promise.resolve().then(function(){return Al});return new t(e)})),Ys("KHR_texture_basisu"),Xs("KHR_texture_basisu",!0,e=>b(this,void 0,void 0,function*(){const{KHR_texture_basisu:t}=yield Promise.resolve().then(function(){return Cl});return new t(e)})),Ys("KHR_texture_transform"),Xs("KHR_texture_transform",!0,e=>b(this,void 0,void 0,function*(){const{KHR_texture_transform:t}=yield Promise.resolve().then(function(){return Nl});return new t(e)})),Ys("KHR_xmp_json_ld"),Xs("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 Dl});return new t(e)})),Ys("MSFT_audio_emitter"),Xs("MSFT_audio_emitter",!0,e=>b(this,void 0,void 0,function*(){const[{MSFT_audio_emitter:t},{RegisterAudioSceneComponent:n},{Sound:o}]=yield Promise.all([Promise.resolve().then(function(){return lu}),Promise.resolve(BABYLON),Promise.resolve(BABYLON)]);return n(o),new t(e)})),Ys("MSFT_lod"),Xs("MSFT_lod",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_lod:t}=yield Promise.resolve().then(function(){return pu});return new t(e)})),Ys("MSFT_minecraftMesh"),Xs("MSFT_minecraftMesh",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_minecraftMesh:t}=yield Promise.resolve().then(function(){return vu});return new t(e)})),Ys("MSFT_sRGBFactors"),Xs("MSFT_sRGBFactors",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_sRGBFactors:t}=yield Promise.resolve().then(function(){return Au});return new t(e)})),Ys("KHR_node_visibility"),Xs("KHR_node_visibility",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_visibility:t,_RegisterKHRNodeVisibilityRuntime:n}=yield Promise.resolve().then(function(){return bd});return n(),new t(e)})),Ys("KHR_node_hoverability"),Xs("KHR_node_hoverability",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_hoverability:t,_RegisterKHRNodeHoverabilityRuntime:n}=yield Promise.resolve().then(function(){return qd});return n(),new t(e)})),Ys("KHR_node_selectability"),Xs("KHR_node_selectability",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_selectability:t,_RegisterKHRNodeSelectabilityRuntime:n}=yield Promise.resolve().then(function(){return Dd});return n(),new t(e)})),Ys("KHR_materials_coat"),Xs("KHR_materials_coat",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_coat:t}=yield Promise.resolve().then(function(){return ea});return new t(e)})),Ys("KHR_materials_fuzz"),Xs("KHR_materials_fuzz",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_fuzz:t}=yield Promise.resolve().then(function(){return Ma});return new t(e)})),Ys("KHR_materials_volume_scatter"),Xs("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 ll});return new t(e)}))}(),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},ph),{createPlugin:e=>b(this,void 0,void 0,function*(){const{OBJFileLoader:t}=yield Promise.resolve().then(function(){return _h});return new t(e[ph.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},Mh),{createPlugin:e=>b(this,void 0,void 0,function*(){const[{SPLATFileLoader:t},{RegisterEnginesExtensionsEngineDynamicTexture:n}]=yield Promise.all([Promise.resolve().then(function(){return np}),Promise.resolve(BABYLON)]);return n(),new t(e[Mh.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},yh),{createPlugin:()=>b(this,void 0,void 0,function*(){const[{STLFileLoader:e},{RegisterStandardMaterial:t}]=yield Promise.all([Promise.resolve().then(function(){return Ah}),Promise.resolve(BABYLON)]);return t(),new e})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},op),{createPlugin:e=>b(this,void 0,void 0,function*(){const{USDFileLoader:t,_RegisterUSDLoaderDependencies:n}=yield Promise.resolve().then(function(){return Vp});return n(),new t(e[op.name])})}))}Dp();var $p={__proto__:null,registerBuiltInLoaders:Gp};const Up="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Up)for(const e in y)Up.BABYLON[e]||(Up.BABYLON[e]=y[e]);const Hp="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Hp){Hp.BABYLON=Hp.BABYLON||{};for(const e in $p)Hp.BABYLON[e]=$p[e]}const Kp="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Kp){Kp.BABYLON=Kp.BABYLON||{};for(const e in ps)Kp.BABYLON[e]=ps[e];for(const e in Ko)Kp.BABYLON[e]=Ko[e]}const jp="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==jp){jp.BABYLON=jp.BABYLON||{},jp.BABYLON.GLTF1=jp.BABYLON.GLTF1||{};for(const e in Ws)jp.BABYLON.GLTF1[e]=Ws[e]}const Wp=Object.assign({},uh),qp=Object.assign(Object.assign({},{__proto__:null}),{Extensions:Wp}),zp=Object.assign(Object.assign({},ch),{Loader:qp}),Xp="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Xp){Xp.BABYLON=Xp.BABYLON||{};const e=Xp.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 Wp)e.GLTF2.Loader.Extensions[n]=Wp[n],t.push(n);for(const n in qp)"Extensions"!==n&&(e.GLTF2.Loader[n]=qp[n],t.push(n));for(const n in zp)t.indexOf(n)>-1||(e.GLTF2[n]=zp[n])}const Yp="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Yp)for(const e in vh)Yp.BABYLON[e]||(Yp.BABYLON[e]=vh[e]);const Qp="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Qp)for(const e in wh)Qp.BABYLON[e]||(Qp.BABYLON[e]=wh[e]);e.AddGaussianSplattingStreamPart=function(e,t,n,o,s={}){return new Xh(t,n,o,e.getScene(),Object.assign(Object.assign({},s),{hostCompound:e}))},e.AddGaussianSplattingStreamPartAsync=function(e,t,n,o){return b(this,arguments,void 0,function*(e,t,n,o,s={}){const r=new Xh(t,n,o,e.getScene(),Object.assign(Object.assign({},s),{hostCompound:e}));try{yield r.whenPartReadyAsync()}catch(e){throw r.dispose(),e}const i=r.streamingPartProxy;if(!i)throw r.dispose(),new Error("GaussianSplattingStream: streaming part was not reserved.");return i})},e.BVHFileLoader=m,e.FBXConstraintBehavior=bo,e.FBXConstraintSolver=yo,e.FBXFileLoader=To,e.FBXFileLoaderMetadata=xo,e.GLTF1=Ws,e.GLTF2=zp,e.GLTFFileLoader=ts,e.GLTFLoaderDefaultOptions=Jo,e.GLTFValidation=Ho,e.GaussianSplattingStream=Xh,e.MTLFileLoader=dh,e.OBJFileLoader=fh,e.ReadBvh=p,e.RegisterBVHFileLoader=_,e.RegisterGLTFFileLoader=os,e.RegisterOBJFileLoader=gh,e.RegisterSPLATFileLoader=tp,e.RegisterSTLFileLoader=Th,e.RegisterUSDFileLoader=Dp,e.SPLATFileLoader=Jh,e.STLFileLoader=bh,e.SolidParser=hh,e.USDFileLoader=Lp,e._RegisterUSDLoaderDependencies=Bp,e.registerBuiltInLoaders=Gp});
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),p=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),p=new t.Animation(`${e.name}_rot`,"rotationQuaternion",l.frameRate,t.Animation.ANIMATIONTYPE_QUATERNION,l.loopMode),f=[],m=[];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&&m.push({frame:n.frame,value:n.rotation.clone()})}return f.length>0&&(h.setKeys(f),u.push(h)),m.length>0&&(p.setKeys(m),u.push(p)),u}(e,u);for(const e of p)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 p=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 m=parseFloat(f.trim());if(d.endsWith("position"))switch(d){case n:h.position.x=m;break;case o:h.position.y=m;break;case s:h.position.z=m}else if(d.endsWith("rotation")){const e=t.Tools.ToRadians(m);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)}p=n.multiply(p)}}t.Quaternion.FromRotationMatrixToRef(p,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 p=null===(i=e.shift())||void 0===i?void 0:i.trim().split(/\s+/);if(!p)throw new Error("Unexpected end of file: missing OFFSET");if(d=p,"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 p(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 p=r.shift();if(!p||"HIERARCHY"!==p.trim().toUpperCase())throw new Error("HIERARCHY expected");const f=r.shift();if(!f)throw new Error("Unexpected end of file after HIERARCHY");const m=h(r,f.trim(),null,u),g=r.shift();if(!g||"MOTION"!==g.trim().toUpperCase())throw new Error("MOTION expected");const _=r.shift();if(!_)throw new Error("Unexpected end of file before frame count");const v=_.trim().split(/[\s]+/);if(v.length<2)throw new Error("Invalid frame count line");const y=parseInt(v[1]);if(isNaN(y))throw new Error("Failed to read number of frames.");u.numFrames=y;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<y;++e){const t=r.shift();t&&d(t.trim().split(/[\s]+/)||[],e,m,{i:0})}return u.root=m,c(u.root,null,u),u.skeleton.returnToRest(),u.skeleton}const f={name:"bvh",extensions:{".bvh":{isBinary:!1}}};class m{constructor(e){this.name=f.name,this.extensions=f.extensions,this._loadingOptions=Object.assign(Object.assign({},m._DefaultLoadingOptions),null!=e?e:{})}static get _DefaultLoadingOptions(){return{loopMode:t.Animation.ANIMATIONLOOPMODE_CYCLE}}createPlugin(e){return new m(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=p(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=p(n,e,o,this._loadingOptions);return o.skeletons.push(t),Promise.resolve(o)}catch(e){return Promise.reject(e)}}}let g=!1;function _(){g||(g=!0,t.RegisterSceneLoaderPlugin(new m))}var v={__proto__:null,BVHFileLoader:m,RegisterBVHFileLoader:_};_();var y={__proto__:null,BVHFileLoader:m,ReadBvh:p,RegisterBVHFileLoader:_};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())})}function x(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)}function T(e,t,n,o,s){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?s.call(e,n):s?s.value=n:t.set(e,n),n}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;const A=[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],w=[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],M=[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],S=[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],R=[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 I{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 F,E;function N(){if(!F){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;F=new O(e)}return F}function L(){return E||(E=new O(new Array(32).fill(5))),E}function k(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 P(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=A[r]+e.readBits(w[r]),a=o.decode(e);if(a>29)throw new Error("deflate: invalid distance symbol");const l=M[a]+e.readBits(S[a]);t.copy(l,i)}}function B(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[R[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})}}let D=!0;function V(e,t,n,o,s){let r,i,a,l;if(o?(U(t,n,25,s,"FBX node header"),r=H(e,n),i=H(e,n+8),a=H(e,n+16),l=25):(U(t,n,13,s,"FBX node header"),r=e.getUint32(n,D),i=e.getUint32(n+4,D),a=e.getUint32(n+8,D),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];U(t,n+l,u,r,"FBX node name");const c=j(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 p=[];for(let n=0;n<i;n++){const n=G(e,t,d,h);p.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=V(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:p,children:f},endOffset:r}}function G(e,t,n,o){U(t,n,1,o,"FBX property type");const s=String.fromCharCode(t[n]);switch(n+=1,s){case"C":{U(t,n,1,o,"FBX boolean property");const e=t[n];return e>1?{property:{type:"int32",value:e},nextOffset:n+1}:{property:{type:"boolean",value:0!==e},nextOffset:n+1}}case"Z":return U(t,n,1,o,"FBX byte property"),{property:{type:"int32",value:t[n]},nextOffset:n+1};case"Y":return U(t,n,2,o,"FBX int16 property"),{property:{type:"int16",value:e.getInt16(n,D)},nextOffset:n+2};case"I":return U(t,n,4,o,"FBX int32 property"),{property:{type:"int32",value:e.getInt32(n,D)},nextOffset:n+4};case"F":return U(t,n,4,o,"FBX float32 property"),{property:{type:"float32",value:e.getFloat32(n,D)},nextOffset:n+4};case"D":return U(t,n,8,o,"FBX float64 property"),{property:{type:"float64",value:e.getFloat64(n,D)},nextOffset:n+8};case"L":{U(t,n,8,o,"FBX int64 property");const s=K(e,n),r={type:"int64",value:s};return Number.isSafeInteger(s)||(r.raw=function(e,t){let n=e.getUint32(D?t:t+4,D),o=e.getUint32(D?t+4:t,D);const s=!!(2147483648&o);s&&(n=1+~n>>>0,o=~o+(0===n?1:0)>>>0);const r=[];for(;0!==o||0!==n;){const e=Math.floor(o/10),t=o%10*4294967296+n;r.push(t%10),o=e,n=Math.floor(t/10)}return(s?"-":"")+(r.length>0?r.reverse().join(""):"0")}(e,n)),{property:r,nextOffset:n+8}}case"S":{U(t,n,4,o,"FBX string property length");const s=e.getUint32(n,D);U(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":{U(t,n,4,o,"FBX raw property length");const s=e.getUint32(n,D);return U(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 $(e,t,n,"float32[]",4,o);case"d":return $(e,t,n,"float64[]",8,o);case"i":return $(e,t,n,"int32[]",4,o);case"l":return $(e,t,n,"int64[]",8,o);case"b":case"c":return $(e,t,n,"boolean[]",1,o);default:throw new Error(`Unknown FBX property type: '${s}' at offset ${n-1}`)}}function $(e,t,n,o,s,r){U(t,n,12,r,`FBX array property header for ${o}`);const i=e.getUint32(n,D),a=e.getUint32(n+4,D),l=e.getUint32(n+8,D),u=i*s;let c;if(U(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 I(t);let i=!1;for(;!i;)switch(i=1===s.readBits(1),s.readBits(2)){case 0:k(s,r);break;case 1:P(s,r,N(),L());break;case 2:{const{literalLengthTree:e,distanceTree:t}=B(s);P(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)}!D&&s>1&&"int64[]"!==o&&function(e,t){for(let n=0;n+t<=e.length;n+=t)for(let o=n,s=n+t-1;o<s;o++,s--){const t=e[o];e[o]=e[s],e[s]=t}}(c,s);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]=K(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 U(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 H(e,t){const n=e.getUint32(D?t:t+4,D);return 4294967296*e.getUint32(D?t+4:t,D)+n}function K(e,t){const n=e.getUint32(D?t:t+4,D);return 4294967296*e.getInt32(D?t+4:t,D)+n}function j(e,t,n){let o="";for(let s=0;s<n;s++)o+=String.fromCharCode(e[t+s]);return o}function W(e){const t=new X(e),n=function(e){const t=e.match(/;\s*FBX\s+(\d+)\.(\d+)\.(\d+)/);if(t)return 1e3*parseInt(t[1])+100*parseInt(t[2])+parseInt(t[3]);const n=e.match(/FBXVersion:\s*(\d+)/);return n?parseInt(n[1]):e.includes("Properties70")?7e3:6e3}(e),o=[];for(;!t.isEOF()&&(t.skipWhitespaceAndComments(),!t.isEOF());){const e=Y(t);e&&o.push(e)}return n>=7200&&q(o),{version:n,nodes:o}}function q(e){for(const t of e){if("KeyAttrDataFloat"===t.name&&1===t.properties.length&&t.properties[0].value instanceof Float64Array){const e=t.properties[0].value,n=new Int32Array(e.length);for(let t=0;t<e.length;t++)n[t]=0|e[t];t.properties[0]={type:"float32[]",value:new Float32Array(n.buffer)}}t.children.length>0&&q(t.children)}}var z;!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"}(z||(z={}));let X=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++,t.includes("&quot;")&&(t=t.split("&quot;").join('"')),{type:2,value:t,pos:e}}readNumber(){const e=this.pos;if("-"!==this.text[this.pos]&&"+"!==this.text[this.pos]||this.pos++,this.pos<this.len&&this.isIdentStart(this.text[this.pos])){for(;this.pos<this.len&&this.isIdentStart(this.text[this.pos]);)this.pos++;return this.skipSpecialNumberSuffix(),{type:1,value:this.text.substring(e,this.pos),pos:e}}for(;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++;if(this.pos<this.len&&"#"===this.text[this.pos]){for(this.pos++;this.pos<this.len&&(this.isIdentStart(this.text[this.pos])||this.isDigit(this.text[this.pos]));)this.pos++;this.skipSpecialNumberSuffix()}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 this.skipSpecialNumberSuffix(),{type:0,value:this.text.substring(e,this.pos),pos:e}}skipSpecialNumberSuffix(){if(this.pos<this.len&&"("===this.text[this.pos])for(;this.pos<this.len;){const e=this.text[this.pos];if("("!==e&&")"!==e&&!this.isIdentChar(e))break;this.pos++}}isDigit(e){return e>="0"&&e<="9"}isNumberStart(e){if(this.isDigit(e)||"."===e)return!0;if(("-"===e||"+"===e)&&this.pos+1<this.len){const e=this.text[this.pos+1];return this.isDigit(e)||"."===e||Q(this.text.substring(this.pos+1,this.pos+10))}return!!Q(this.text.substring(this.pos,this.pos+9))&&!this.isFollowedByColon(this.pos)}isFollowedByColon(e){let t=e;for(;t<this.len&&this.isIdentChar(this.text[t]);)t++;for(;t<this.len&&(" "===this.text[t]||"\t"===this.text[t]);)t++;return t<this.len&&":"===this.text[t]}isIdentStart(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||"_"===e}isIdentChar(e){return this.isIdentStart(e)||this.isDigit(e)||"|"===e||"-"===e}};function Y(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){const t=e.next();n.push(Z(t.value))}else{if(0!==t.type||e.isNextNodeStart())break;{const t=e.next();n.push(Z(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=Z(t.value);if(!Number.isInteger(n)||t.value.includes(".")||t.value.includes("e")||t.value.includes("E"))s.push({type:"float64",value:n});else{const e={type:ee(n)?"int32":"int64",value:n};Number.isSafeInteger(n)||(e.raw=J(t.value)),s.push(e)}}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=Y(e);if(!t)break;r.push(t)}e.expect(4)}return{name:o,properties:s,children:r}}function Q(e){return/^(?:inf(?:inity)?|nan|ind)(?![A-Za-z0-9_|])/i.test(e)}function Z(e){const t=Number(e);if(!Number.isNaN(t))return t;const n=e.startsWith("-")?-1:1,o=e.replace(/^[+-]/,"").replace(/\(.*$/,"");return/#INF/i.test(o)||/^inf/i.test(o)?n*(1/0):NaN}function J(e){const t=e.startsWith("-"),n=e.replace(/^[+-]/,"").replace(/^0+(?=\d)/,"");return t&&"0"!==n?`-${n}`:n}function ee(e){return e>=-2147483648&&e<=2147483647}function te(e,t){return e.children.find(e=>e.name===t)}function ne(e,t){return e.nodes.find(e=>e.name===t)}function oe(e,t){if(t<e.properties.length)return e.properties[t].value}function se(e){if(!e||0===e.properties.length)return null;const t=e.properties[0].value;if(1===e.properties.length&&(t instanceof Float32Array||t instanceof Float64Array||t instanceof Int32Array||t instanceof Uint8Array))return t;const n=new Float64Array(e.properties.length);for(let t=0;t<e.properties.length;t++){const o=e.properties[t].value;if("number"==typeof o)n[t]=o;else{if("boolean"!=typeof o)return null;n[t]=o?1:0}}return n}function re(e){const t=e.indexOf("\0");if(t>=0)return e.substring(0,t);const n=e.indexOf("::");return n>=0?e.substring(n+2):e}function ie(e,t,n){const o=e.get(t);if(o)return n?o.get(n):o.values().next().value}function ae(e,t,n,o=0){var s;return null===(s=ce(e,t,n))||void 0===s?void 0:s[o]}function le(e,t,n,o){var s;return null!==(s=de(ae(e,t,n)))&&void 0!==s?s:o}function ue(e,t,n,o){const s=ce(e,t,n);if(!s)return o;const r=de(s[0]),i=de(s[1]),a=de(s[2]);return void 0!==r&&void 0!==i&&void 0!==a?[r,i,a]:o}function ce(e,t,n){var o,s;return null!==(o=function(e,t){const n=[te(e,"Properties70"),te(e,"Properties60")].filter(e=>void 0!==e);let o;for(const e of n)for(const n of e.children)"P"!==n.name&&"Property"!==n.name||oe(n,0)===t&&(o=n.properties.slice("Property"===n.name?3:4).map(e=>e.value));return o}(e,n))&&void 0!==o?o:null===(s=null==t?void 0:t.properties.get(n))||void 0===s?void 0:s.values}function de(e){if("number"==typeof e)return e}function he(e,t,n){var o;const s=new Map,r=te(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=_e(e);t&&s.set(t.name,t)}return{objectType:e,templateName:t,properties:s}}function pe(e){const t=[];if(!e)return t;for(const n of e.children)if("Properties70"===n.name||"Properties60"===n.name)for(const e of n.children){if("P"!==e.name&&"PS"!==e.name&&"Property"!==e.name)continue;const n=oe(e,0);if("string"!=typeof n)continue;const o="Property"!==e.name,s=oe(e,1),r=oe(e,o?3:2);t.push({name:n,type:"string"==typeof s?s:"",flags:"string"==typeof r?r:"",values:e.properties.slice(o?4:3).map(e=>e.value)})}return t}function fe(e){const t={};let n=!1;for(const o of pe(e)){if(!o.flags.includes("U"))continue;const e=ge(o.values,o.type);void 0!==e&&(t[o.name]=e,n=!0)}return n?t:void 0}const me=new Set(["Integer","int","Number","double","Float","float","Bool","bool","Enum","enum","Visibility","Roll","Weight","Distance","KTime","Time"]);function ge(e,t){if(0===e.length)return;const n=e[0];if(void 0!==t&&me.has(t)&&("number"==typeof n||"boolean"==typeof n))return n;if(1===e.length)return"string"==typeof n||"number"==typeof n||"boolean"==typeof n?n:void 0;const o=[];for(const t of e)if("number"==typeof t)o.push(t);else{if("boolean"!=typeof t)break;o.push(t?1:0)}return o.length===e.length?o:"string"==typeof n?n:void 0}function _e(e){var t,n,o;const s=oe(e,0);return s?{name:s,propertyType:null!==(t=oe(e,1))&&void 0!==t?t:"",label:null!==(n=oe(e,2))&&void 0!==n?n:"",flags:null!==(o=oe(e,3))&&void 0!==o?o:"",values:e.properties.slice(4).map(e=>e.value)}:null}function ve(e,t){const n=ue(e,t,"Lcl Translation",[0,0,0]),o=ue(e,t,"Lcl Rotation",[0,0,0]),s=ue(e,t,"Lcl Scaling",[1,1,1]);let r=ue(e,t,"PreRotation",[0,0,0]),i=ue(e,t,"PostRotation",[0,0,0]);const a=ue(e,t,"RotationPivot",[0,0,0]),l=ue(e,t,"ScalingPivot",[0,0,0]),u=ue(e,t,"RotationOffset",[0,0,0]),c=ue(e,t,"ScalingOffset",[0,0,0]),d=ue(e,t,"GeometricTranslation",[0,0,0]),h=ue(e,t,"GeometricRotation",[0,0,0]),p=ue(e,t,"GeometricScaling",[1,1,1]);let f=le(e,t,"RotationOrder",0);const m=le(e,t,"InheritType",1),g=le(e,t,"RotationActive",1),_=le(e,t,"RotationSpaceForLimitOnly",0),v=0!==g&&0===_;return v||(f=0,r=[0,0,0],i=[0,0,0]),{translation:n,rotation:o,scale:s,preRotation:r,postRotation:i,rotationPivot:a,scalingPivot:l,rotationOffset:u,scalingOffset:c,geometricTranslation:d,geometricRotation:h,geometricScaling:p,rotationOrder:f,inheritType:m,rotationActive:v,diagnostics:0===m||1===m||2===m?[]:[`InheritType ${m} is unknown; treated as RSrs.`]}}function ye(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 be(e){return{name:"Version",properties:[{type:"int32",value:e}],children:[]}}function xe(e,t,n,o,s){return{name:e,properties:[{type:"int64",value:t},{type:"string",value:n},{type:"string",value:o}],children:s}}function Te(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 Ae(e,t){var n,o;const s=re(null!==(n=oe(e,0))&&void 0!==n?n:e.name),r=null!==(o=oe(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 we(e,t){var n;return{name:"Geometry",properties:[{type:"int64",value:t},{type:"string",value:re(null!==(n=oe(e,0))&&void 0!==n?n:"Geometry")},{type:"string",value:"Mesh"}],children:e.children}}function Me(e,t){var n,o,s;const r=re(null!==(n=oe(e,1))&&void 0!==n?n:"Geometry"),i=te(e,"Vertices"),a=i?Fe(Ne(i)):new Float64Array(0),l=te(e,"PolygonVertexIndex"),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}(l?Ee(Ne(l)):new Int32Array(0)),d=function(e,t,n){const o=[];for(let s=0;s<e.length;s++){const r=e[s];o.push(...Se(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),p=te(e,"LayerElementNormal");let f=null;p&&(f=Ie(p,"Normals","NormalsIndex",h,a.length,3,u));const m=e.children.filter(e=>"LayerElementUV"===e.name),g=[];for(const e of m){const t=te(e,"Name"),n=t&&null!==(o=oe(t,0))&&void 0!==o?o:`UVSet${g.length}`,s=Ie(e,"UV","UVIndex",h,a.length,2,u);s&&g.push({name:n,data:s})}const _=g.length>0?g[0].data:null,v=te(e,"LayerElementColor");let y=null;if(v){const e=Ie(v,"Colors","ColorIndex",h,a.length,4,u);if(e){y=new Float32Array(e.length);for(let t=0;t<e.length;t++)y[t]=e[t]}}const b=te(e,"LayerElementTangent"),x=te(e,"LayerElementBinormal"),T=x?Ie(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=te(e,"Tangents");if(!c)return 3;const d=Fe(Ne(c)),h=null!==(a=oe(null!==(i=te(e,"MappingInformationType"))&&void 0!==i?i:{name:"",properties:[],children:[]},0))&&void 0!==a?a:"",p=null!==(u=oe(null!==(l=te(e,"ReferenceInformationType"))&&void 0!==l?l:{name:"",properties:[],children:[]},0))&&void 0!==u?u:"",f=te(e,"TangentsIndex"),m=f?Ee(Ne(f)):null,g="IndexToDirect"===p&&m?Math.max(...Array.from(m),0)+1:"ByControlPoint"===h||"ByVertice"===h?s:"AllSame"===h?1:o.length;if(g>0&&d.length%g===0){const e=d.length/g;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=Ie(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]:Oe(e,l,o,s)}return l}(b,h,a.length/3,f,T,u):null,w=te(e,"LayerElementMaterial");let M=null;w&&(M=function(e,t){var n,o;const s=te(e,"MappingInformationType"),r=te(e,"ReferenceInformationType");if(!s||!r)return null;const i=null!==(n=oe(s,0))&&void 0!==n?n:"",a=null!==(o=oe(r,0))&&void 0!==o?o:"";if("AllSame"===i){const n=te(e,"Materials"),o=n?Ee(Ne(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=te(e,"Materials");if(!t)return null;const n=Ee(Ne(t));if("Direct"===a||"IndexToDirect"===a)return n}return null}(w,c.length));const S=function(e,t,n,o,s,r,i,a,l){const u=n.length,c=new Uint32Array(u),d=[],h=new Map,p=r.length;for(let e=0;e<u;e++){let t=String(n[e].controlPointIndex);o&&(t+=`|${o[3*e]},${o[3*e+1]},${o[3*e+2]}`);for(let n=0;n<p;n++){const o=r[n].data;t+=`|${o[2*e]},${o[2*e+1]}`}i&&(t+=`|${i[4*e]},${i[4*e+1]},${i[4*e+2]},${i[4*e+3]}`),a&&(t+=`|${a[4*e]},${a[4*e+1]},${a[4*e+2]},${a[4*e+3]}`);let s=h.get(t);void 0===s&&(s=d.length,h.set(t,s),d.push(e)),c[e]=s}const f=d.length,m=new Float64Array(3*f),g=new Uint32Array(f),_=(e,t,n)=>{if(!e)return null;const o=new n(f*t);for(let n=0;n<f;n++){const s=d[n]*t;for(let r=0;r<t;r++)o[n*t+r]=e[s+r]}return o};for(let t=0;t<f;t++){const o=n[d[t]].controlPointIndex;m[3*t]=e[3*o],m[3*t+1]=e[3*o+1],m[3*t+2]=e[3*o+2],g[t]=o}const v=3*t.length,y=new Uint32Array(v);for(let e=0;e<t.length;e++)y[3*e]=c[t[e].vertices[0]],y[3*e+1]=c[t[e].vertices[1]],y[3*e+2]=c[t[e].vertices[2]];const b=r.map(e=>({name:e.name,data:_(e.data,2,Float64Array)}));return{positions:m,indices:y,normals:_(o,3,Float64Array),uvs:b.length>0?b[0].data:_(s,2,Float64Array),uvSets:b,colors:_(i,4,Float32Array),tangents:_(a,4,Float64Array),binormals:_(l,3,Float64Array),controlPointIndices:g}}(a,d,h,f,_,g,y,A,T);let R=null;if(M){let e=!0;const t=M[0];for(let n=1;n<M.length;n++)if(M[n]!==t){e=!1;break}if(!e||0!==t){const e=S.indices.length/3;R=new Int32Array(e);for(let e=0;e<d.length;e++)R[e]=null!==(s=M[d[e].polyIndex])&&void 0!==s?s:0}}return{id:t,name:r,positions:S.positions,indices:S.indices,normals:S.normals,uvs:S.uvs,uvSets:S.uvSets,colors:S.colors,tangents:S.tangents,binormals:S.binormals,controlPointIndices:S.controlPointIndices,materialIndices:R,diagnostics:u}}function Se(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],p=t[a+2];n+=(u-h)*(c+p),o+=(c-p)*(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}),Re(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}),Re(e,t);const i=function(e,t,n){const o=e.length,s=new Int32Array(o),r=new Int32Array(o);for(let e=0;e<o;e++)s[e]=(e+o-1)%o,r[e]=(e+1)%o;const i=1e-12*Math.abs(n)+1e-300,a=t?1:-1,l=t=>a*Ce(e[s[t]],e[t],e[r[t]]),u=new Uint8Array(o);for(let e=0;e<o;e++)u[e]=l(e)<-i?1:0;const c=(e,t,n,o)=>a*Ce(t,n,e)>=-i&&a*Ce(n,o,e)>=-i&&a*Ce(o,t,e)>=-i,d=[];let h=o,p=0,f=0;for(;h>3;){const t=s[p],n=r[p];let o=!1;if(!u[p])if(l(p)<=i)o=!0,d.push([t,p,n]);else{o=!0;for(let s=r[n];s!==t;s=r[s])if(u[s]&&c(e[s],e[t],e[p],e[n])){o=!1;break}o&&d.push([t,p,n])}if(o)r[t]=n,s[n]=t,h--,u[t]=l(t)<-i?1:0,u[n]=l(n)<-i?1:0,p=n,f=0;else if(p=n,++f>h)return null}const m=p;return d.push([s[m],m,r[m]]),d}(s,r>0,r);return i?i.map(([n,o,s])=>({vertices:[e.startIndex+n,e.startIndex+o,e.startIndex+s],polyIndex:t})):(o.push({type:"triangulation-fallback",message:`Polygon ${t} could not be fully ear-clipped; using fan triangulation.`,polygonIndex:t}),Re(e,t))}function Re(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 Ce(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function Ie(e,t,n,o,s,r,i){var a,l;const u=te(e,"MappingInformationType"),c=te(e,"ReferenceInformationType");if(!u||!c)return null;const d=null!==(a=oe(u,0))&&void 0!==a?a:"",h=null!==(l=oe(c,0))&&void 0!==l?l:"",p=te(e,t);if(!p)return null;const f=Fe(Ne(p));let m=null;if("IndexToDirect"===h){const t=te(e,n);t&&(m=Ee(Ne(t)))}const g=new Float64Array(o.length*r);for(let t=0;t<o.length;t++){const n=o[t];let s;s="ByPolygonVertex"===d?"IndexToDirect"===h&&m?m[n.globalIndex]:n.globalIndex:"ByControlPoint"===d||"ByVertice"===d?"IndexToDirect"===h&&m?m[n.controlPointIndex]:n.controlPointIndex:"ByPolygon"===d?"IndexToDirect"===h&&m?m[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}),g[t*r+n]=0):g[t*r+n]=f[o]}}return g}function Oe(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||e instanceof Uint8Array)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 Ee(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||e instanceof Uint8Array){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 Ne(e){var t;return null!==(t=se(e))&&void 0!==t?t:new Float64Array(0)}function Le(e){return"Closed"===e?"closed":"Periodic"===e?"periodic":"open"}function ke(e,t,n){const o={order:e,topology:Le(t),knots:n,tMin:0,tMax:0,spans:new Float64Array(0),valid:!1};if(e>1&&e<=128){const t=e-1;if(n.length>=2*t+1){o.tMin=n[t],o.tMax=n[n.length-t-1];const e=n.length-2*t,s=[];let r=-1/0;for(let o=0;o<e;o++){const e=n[t+o];e!==r&&(s.push(e),r=e)}o.spans=Float64Array.from(s),o.valid=!0;for(let e=1;e<n.length;e++)if(!(n[e-1]<=n[e])){o.valid=!1;break}}}return o}function Pe(e,t,n,o){if(t<0||t>=e.length||e.length-t<n)return 0;const s=e[t],r=e[t+n];return s>=r||o<=s?0:o>=r?1:(o-s)/(r-s)}function Be(e,t,n){if(t<0||t>=e.length||e.length-t<n)return 0;const o=e[t],s=e[t+n];return o>=s?0:n/(s-o)}function De(e,t,n,o){if(e.order<=1||!e.valid)return-1;const s=e.order-1,r=e.knots;let i;if(t<=e.tMin)i=s,t=e.tMin;else if(t>=e.tMax)i=r.length-s-2,t=e.tMax;else{let e=0,n=r.length-1;for(;e<n;){const o=e+n>>1;r[o+1]<=t?e=o+1:n=o}if(!(r[e]<=t&&t<r[e+1]))return-1;i=e}if(i<s)return-1;n[0]=1;for(let e=1;e<=s;e++){let a=0,l=1-Pe(r,i-e+1,e,t),u=0;const c=null!==o&&e===s;c&&(u=Be(r,i-e+1,e));for(let s=e;s>0;s--){const d=Pe(r,i-e+s,e,t),h=n[s-1];if(n[s]=d*h+l*a,c){const t=Be(r,i-e+s,e);o[s]=t*h-u*a,u=t}a=h,l=1-d}n[0]=l*a,c&&(o[0]=-u*a)}return i-s}function Ve(e,t,n,o,s){const r=De(e.basis,t,o,s);if(r<0||0===e.numControlPoints)return!1;const i=e.basis.order;let a=0,l=0,u=0,c=0,d=0,h=0,p=0,f=0;const m=e.controlPoints;for(let t=0;t<i;t++){const n=(r+t)%e.numControlPoints*4,i=o[t]*m[n+3],g=s[t]*m[n+3];a+=m[n]*i,l+=m[n+1]*i,u+=m[n+2]*i,c+=i,d+=m[n]*g,h+=m[n+1]*g,p+=m[n+2]*g,f+=g}const g=0!==c?1/c:0;return n[0]=a*g,n[1]=l*g,n[2]=u*g,n[3]=(d-f*n[0])*g,n[4]=(h-f*n[1])*g,n[5]=(p-f*n[2])*g,!0}function Ge(e,t,n,o,s){const r=De(e.basisU,t,s.wu,s.du),i=De(e.basisV,n,s.wv,s.dv);if(r<0||i<0||0===e.numU||0===e.numV)return!1;const a=e.basisU.order,l=e.basisV.order,u=e.controlPoints;let c=0,d=0,h=0,p=0,f=0,m=0,g=0,_=0,v=0,y=0,b=0,x=0;for(let t=0;t<l;t++){const n=(i+t)%e.numV,o=s.wv[t],l=s.dv[t];for(let t=0;t<a;t++){const i=(r+t)%e.numU,a=s.wu[t],T=s.du[t],A=4*(n*e.numU+i),w=u[A+3],M=a*o*w,S=T*o*w,R=l*a*w,C=u[A],I=u[A+1],O=u[A+2];c+=C*M,d+=I*M,h+=O*M,p+=M,f+=C*S,m+=I*S,g+=O*S,_+=S,v+=C*R,y+=I*R,b+=O*R,x+=R}}const T=0!==p?1/p:0;return o[0]=c*T,o[1]=d*T,o[2]=h*T,o[3]=(f-_*o[0])*T,o[4]=(m-_*o[1])*T,o[5]=(g-_*o[2])*T,o[6]=(v-x*o[0])*T,o[7]=(y-x*o[1])*T,o[8]=(b-x*o[2])*T,!0}function $e(e,t){return void 0!==t&&Number.isFinite(t)&&t>0?Math.min(64,Math.max(1,Math.floor(t))):e>0?Math.min(16,Math.floor(e)):4}function Ue(e,t){const n=te(e,t);if(!n)return null;const o=se(n);return o?o instanceof Float64Array?o:Float64Array.from(o):null}function He(e){const t=pe(e).find(e=>"Color"===e.name);return t&&"number"==typeof t.values[0]&&"number"==typeof t.values[1]&&"number"==typeof t.values[2]?[t.values[0],t.values[1],t.values[2]]:null}function Ke(e,t,n){var o;const s=re(null!==(o=oe(e,1))&&void 0!==o?o:"NurbsSurface"),r=function(e){var t,n,o,s,r,i;const a=te(e,"NurbsSurfaceOrder"),l=te(e,"Dimensions"),u=te(e,"Step"),c=te(e,"Form"),d=te(e,"FlipNormals"),h=a&&null!==(t=oe(a,0))&&void 0!==t?t:0,p=a&&null!==(n=oe(a,1))&&void 0!==n?n:0,f=l&&null!==(o=oe(l,0))&&void 0!==o?o:0,m=l&&null!==(s=oe(l,1))&&void 0!==s?s:0,g=u&&null!==(r=oe(u,0))&&void 0!==r?r:0,_=u&&null!==(i=oe(u,1))&&void 0!==i?i:0,v=c?oe(c,0):void 0,y=c?oe(c,1):void 0,b=d?oe(d,0):0,x=Ue(e,"Points"),T=Ue(e,"KnotVectorU"),A=Ue(e,"KnotVectorV");return!x||!T||!A||x.length%4!=0||x.length/4!==f*m||f<=0||m<=0?null:{basisU:ke(h,v,T),basisV:ke(p,y,A),numU:f,numV:m,controlPoints:x,flipNormals:!0===b||1===b,stepU:"number"==typeof g?g:0,stepV:"number"==typeof _?_:0}}(e),i=[];if(!r)return null;const a=function(e,t,n){const o=e.basisU,s=e.basisV;if(!o.valid||!s.valid||0===e.numU||0===e.numV||o.spans.length<2||s.spans.length<2)return null;const r="open"===o.topology,i="open"===s.topology,a=o.spans.length,l=s.spans.length,u=(a-1)*t,c=(l-1)*n,d=a+(a-1)*(t-1),h=d*(l+(l-1)*(n-1));if(h>1073741823||u*c>1073741823)return null;const p=new Uint32Array(h),f=new Float64Array(3*h);let m=0;const g=new Float64Array(2*h),_={wu:new Float64Array(o.order+1),wv:new Float64Array(s.order+1),du:new Float64Array(o.order+1),dv:new Float64Array(s.order+1)},v=new Float64Array(9);for(let u=0;u<l;u++){const c=u+1===l?1:n;for(let h=0;h<c;h++){const y=u*n+h;let b=s.spans[u];if(h>0){const e=h/c;b=b*(1-e)+e*s.spans[u+1]}const x=b;u+1!==l||i||(b=s.spans[0]);for(let n=0;n<a;n++){const s=n+1===a?1:t;for(let i=0;i<s;i++){const c=n*t+i;let T=o.spans[n];if(i>0){const e=i/s;T=T*(1-e)+e*o.spans[n+1]}const A=T;n+1!==a||r||(T=o.spans[0]);let w=0,M=0,S=0;Ge(e,T,b,v,_)&&(w=v[0],M=v[1],S=v[2]);const R=[];(0===u&&(n>0||i>0)||0===n&&(u>0||h>0))&&R.push(0),u+1===l&&(R.push(c),(n>0||i>0)&&R.push(y*d)),n+1===a&&(R.push(y*d),(u>0||h>0)&&R.push(d-1));const C=y*d+c;let I=m;for(const e of R){if(e>=C)continue;const t=p[e],n=f[3*t]-w,o=f[3*t+1]-M,s=f[3*t+2]-S;if(n*n+o*o+s*s<1e-7){I=t;break}}p[C]=I,I===m&&(f[3*I]=w,f[3*I+1]=M,f[3*I+2]=S,m++),g[2*C]=A,g[2*C+1]=x}}}}const y=[],b=[0,0,0,0],x=[0,0,0,0];for(let e=0;e<c;e++)for(let t=0;t<u;t++){b[0]=e*d+t,b[1]=e*d+t+1,b[2]=(e+1)*d+t+1,b[3]=(e+1)*d+t;for(let e=0;e<4;e++)x[e]=p[b[e]];let n=4;for(let e=0;e<4;e++){const t=(e+1)%4;if(x[e]===x[t]){for(let e=t;e<3;e++)b[e]=b[e+1],x[e]=x[e+1];n=3;break}}y.push(b[0],b[1],b[2]),4===n&&y.push(b[0],b[2],b[3])}const T=new Float64Array(3*m);for(let e=0;e<y.length;e+=3){const t=3*p[y[e]],n=3*p[y[e+1]],o=3*p[y[e+2]],s=f[n]-f[t],r=f[n+1]-f[t+1],i=f[n+2]-f[t+2],a=f[o]-f[t],l=f[o+1]-f[t+1],u=f[o+2]-f[t+2],c=r*u-i*l,d=i*a-s*u,h=s*l-r*a;for(const e of[t,n,o])T[e]+=c,T[e+1]+=d,T[e+2]+=h}const A=e.flipNormals?-1:1;for(let e=0;e<m;e++){const t=T[3*e],n=T[3*e+1],o=T[3*e+2],s=Math.hypot(t,n,o);s>0&&(T[3*e]=t/s*A,T[3*e+1]=n/s*A,T[3*e+2]=o/s*A)}const w=new Float64Array(3*h),M=new Float64Array(3*h);for(let e=0;e<h;e++){const t=3*p[e];w[3*e]=f[t],w[3*e+1]=f[t+1],w[3*e+2]=f[t+2],M[3*e]=T[t],M[3*e+1]=T[t+1],M[3*e+2]=T[t+2]}return{positions:w,indices:Uint32Array.from(y),normals:M,uvs:g}}(r,$e(r.stepU,n),$e(r.stepV,n));return a?{id:t,name:s,positions:a.positions,indices:a.indices,normals:a.normals,uvs:a.uvs,uvSets:[{name:"map1",data:a.uvs}],colors:null,tangents:null,binormals:null,controlPointIndices:null,materialIndices:null,diagnostics:i}:(i.push({type:"nurbs-invalid",message:`NURBS surface '${s}' has an invalid basis and was skipped.`}),{id:t,name:s,positions:new Float64Array(0),indices:new Uint32Array(0),normals:null,uvs:null,uvSets:[],colors:null,tangents:null,binormals:null,controlPointIndices:null,materialIndices:null,diagnostics:i})}function je(e,t,n=4){var o;const s=re(null!==(o=oe(e,1))&&void 0!==o?o:"NurbsCurve"),r=[],i=function(e){var t;const n=te(e,"Order"),o=te(e,"Form"),s=n&&null!==(t=oe(n,0))&&void 0!==t?t:0,r=o?oe(o,0):void 0,i=Ue(e,"Points"),a=Ue(e,"KnotVector");return i&&a&&i.length%4==0?{basis:ke(s,r,a),controlPoints:i,numControlPoints:i.length/4}:null}(e),a=i?function(e,t=4){const n=e.basis;if(!n.valid||0===e.numControlPoints||0===n.spans.length)return null;const o=Math.max(1,Math.floor(t)),s=n.spans.length,r=s+(s-1)*(o-1),i=r-("open"===n.topology?0:1),a=new Float64Array(3*r),l=new Float64Array(n.order+1),u=new Float64Array(n.order+1),c=new Float64Array(6);for(let t=0;t<s;t++){const r=t+1===s?1:o;for(let s=0;s<r;s++){const r=t*o+s;if(r<i){let i=n.spans[t];if(s>0){const e=s/o;i=i*(1-e)+e*n.spans[t+1]}Ve(e,i,c,l,u)&&(a[3*r]=c[0],a[3*r+1]=c[1],a[3*r+2]=c[2])}else a[3*r]=a[0],a[3*r+1]=a[1],a[3*r+2]=a[2]}}return a}(i,n):null;return a||r.push({type:"nurbs-invalid",message:`NURBS curve '${s}' has an invalid basis and was skipped.`}),{id:t,name:s,kind:"nurbsCurve",polylines:a?[a]:[],color:He(e),diagnostics:r}}function We(e,t){var n;const o=re(null!==(n=oe(e,1))&&void 0!==n?n:"Line"),s=[],r=Ue(e,"Points"),i=te(e,"PointsIndex"),a=i?se(i):null,l=[];if(r&&r.length%3==0){const e=r.length/3,t=a?Array.from(a):Array.from({length:e},(e,t)=>t);let n=[];const i=()=>{n.length>=2?l.push(Float64Array.from(n)):1===n.length&&s.push({type:"degenerate-polygon",message:`Line '${o}' has a single-point segment that was skipped.`}),n=[]};for(let a=0;a<t.length;a++){let l=t[a];const u=l<0;u&&(l=~l),l>=0&&l<e?n.push(r[3*l],r[3*l+1],r[3*l+2]):s.push({type:"layer-index-out-of-bounds",message:`Line '${o}' references point ${l} outside its ${e} points.`,index:a}),u&&i()}i()}return{id:t,name:o,kind:"line",polylines:l,color:He(e),diagnostics:s}}const qe=e=>({type:"string",value:e}),ze=e=>({type:"float64",value:e}),Xe=e=>({type:"int32",value:e}),Ye=(e,t=[],n=[])=>({name:e,properties:t,children:n});function Qe(e,t,n,...o){return Ye("Property",[qe(e),qe(t),qe(n),...o.map(e=>"string"==typeof e?qe(e):ze(e))])}function Ze(e,t,n,...o){return Ye("P",[qe(e),qe(t),qe(""),qe(n),...o.map(e=>"string"==typeof e?qe(e):ze(e))])}const Je=(e,t)=>Ye(e,[{type:t instanceof Int32Array?"int32[]":"float64[]",value:t}]);function et(e,t=0){var n;const o=null===(n=null==e?void 0:e.properties[t])||void 0===n?void 0:n.value;return"number"==typeof o?o:"boolean"==typeof o?o?1:0:void 0}function tt(e){if(!e)return[];const t=se(e);return t?Array.from(t):[]}function nt(e){const t=e?se(e):null;return t?t instanceof Float64Array?t:Float64Array.from(t):null}function ot(e){const t=e?se(e):null;return t?t instanceof Int32Array?t:Int32Array.from(t,e=>Math.trunc(e)):null}function st(e,t){if(e)for(const n of e.children){if("Channel"!==n.name)continue;const e=oe(n,0),o="T"===e?"t":"R"===e?"r":"S"===e?"s":void 0;if(!o||t[o])continue;const s=[0,0,0];let r=!1;for(const e of n.children){if("Channel"!==e.name)continue;const t=oe(e,0),n="X"===t?0:"Y"===t?1:"Z"===t?2:-1,o=et(te(e,"Default"));n>=0&&void 0!==o&&(s[n]=o,r=!0)}r&&(t[o]=s)}}function rt(e){const t=te(e,"Key");return!!(t&&t.properties.length>0)||e.children.some(e=>"Channel"===e.name&&rt(e))}function it(e,t){var n;const o=null!==(n=e.usedNames.get(t))&&void 0!==n?n:0;return e.usedNames.set(t,o+1),0===o?t:`${t} (${o+1})`}function at(e,t,n){e.connections.push(Ye("C",[qe("OO"),qe(t),qe(n)]))}function lt(e){const t=new Float64Array(e.length);for(let n=0;n+2<e.length;n+=3){const o=e[n],s=e[n+1],r=e[n+2],i=Math.hypot(o,s,r);i>0&&(t[n]=o/i,t[n+1]=s/i,t[n+2]=r/i)}return t}function ut(e,t){var n,o,s,r,i,a,l;const u=null!==(n=oe(t,0))&&void 0!==n?n:"Model",c=oe(null!==(o=te(t,"Type"))&&void 0!==o?o:Ye("x"),0),d=!!te(t,"Vertices"),h="Light"===c?"Light":"Camera"===c?"Camera":"LimbNode"===c?"LimbNode":d?"Mesh":"Null",p={};st(t.children.find(e=>"Channel"===e.name&&"Transform"===oe(e,0)),p),st(e.takeDefaults.get(u),p);const f=null!==(s=p.t)&&void 0!==s?s:[0,0,0],m=null!==(r=p.r)&&void 0!==r?r:[0,0,0],g=null!==(i=p.s)&&void 0!==i?i:[1,1,1],_=[Qe("Lcl Translation","Lcl Translation","A+",f[0],f[1],f[2]),Qe("Lcl Rotation","Lcl Rotation","A+",m[0],m[1],m[2]),Qe("Lcl Scaling","Lcl Scaling","A+",g[0],g[1],g[2])],v=t.children.find(e=>"Channel"===e.name&&"Visibility"===oe(e,0)),y=et(te(null!=v?v:Ye("x"),"Default"));if(void 0!==y&&y<=0&&_.push(Qe("Visibility","Visibility","A+",0)),"Light"===h)_.push(...function(e){const t=[],n=et(te(e,"LightType"));void 0!==n&&t.push(Qe("LightType","enum","",n));const o=tt(te(e,"Color"));o.length>=3&&t.push(Qe("Color","ColorRGB","",o[0],o[1],o[2]));const s=[["Intensity","Intensity"],["ConeAngle","OuterAngle"],["HotSpot","InnerAngle"]];for(const[n,o]of s){const s=et(te(e,n));void 0!==s&&t.push(Qe(o,"double","",s))}const r=et(te(e,"CastShadows"));return void 0!==r&&t.push(Qe("CastShadows","bool","",r)),t}(t));else if("Camera"===h)_.push(...function(e){const t=[],n=[["Aperture","FieldOfView"],["FieldOfViewXProperty","FieldOfViewX"],["FieldOfViewYProperty","FieldOfViewY"],["SqueezeRatio","FilmSqueezeRatio"],["FocalLength","FocalLength"],["AspectType","AspectRatioMode"],["AspectW","AspectWidth"],["AspectH","AspectHeight"],["ApertureMode","ApertureMode"],["NearPlane","NearPlane"],["FarPlane","FarPlane"],["Roll","Roll"]];for(const[o,s]of n){const n=et(te(e,o));void 0!==n&&t.push(Qe(s,"AspectRatioMode"===s||"ApertureMode"===s?"enum":"double","",n))}const o=tt(te(e,"CameraAperture"));return o.length>=2&&(t.push(Qe("FilmWidth","double","",o[0])),t.push(Qe("FilmHeight","double","",o[1]))),t}(t));else if("LimbNode"===h){const e=et(te(null!==(a=te(t,"Properties"))&&void 0!==a?a:Ye("x"),"Size"));void 0!==e&&_.push(Qe("Size","double","",e))}const b=[Ye("Version",[Xe(232)]),Ye("Properties60",[],_)];for(const e of["Culling","Position","Up","LookAt"]){const n=te(t,e);n&&b.push(n)}"Mesh"===h&&b.push(...function(e,t){var n;const o=nt(te(e,"Vertices")),s=ot(te(e,"PolygonVertexIndex"));if(!o||!s)return[];const r=Math.floor(o.length/3),i=s.length;i>0&&s[i-1]>=0&&(s[i-1]=~s[i-1]);const a=[Ye("GeometryVersion",[Xe(124)]),Je("Vertices",o),Je("PolygonVertexIndex",s)],l=nt(te(e,"Normals"));if(l){const e=Math.floor(l.length/3),n=e===i,o=e!==r||n&&5e3!==t?n?"ByPolygonVertex":void 0:"ByVertice";o&&a.push(Ye("LayerElementNormal",[Xe(0)],[Ye("Version",[Xe(101)]),Ye("Name",[qe("")]),Ye("MappingInformationType",[qe(o)]),Ye("ReferenceInformationType",[qe("Direct")]),Je("Normals",lt(l))]))}const u=te(e,"GeometryUVInfo"),c=u?nt(te(u,"TextureUV")):null;if(u&&c){const e=ot(te(u,"TextureUVVerticeIndex")),t=Math.floor(c.length/2);let n;const o=[Ye("Version",[Xe(101)]),Ye("Name",[qe("")])];e&&e.length===i?n=Ye("LayerElementUV",[Xe(0)],[...o,Ye("MappingInformationType",[qe("ByPolygonVertex")]),Ye("ReferenceInformationType",[qe("IndexToDirect")]),Je("UV",c),Je("UVIndex",e)]):t===i?n=Ye("LayerElementUV",[Xe(0)],[...o,Ye("MappingInformationType",[qe("ByPolygonVertex")]),Ye("ReferenceInformationType",[qe("Direct")]),Je("UV",c)]):t===r&&(n=Ye("LayerElementUV",[Xe(0)],[...o,Ye("MappingInformationType",[qe("ByVertice")]),Ye("ReferenceInformationType",[qe("Direct")]),Je("UV",c)])),n&&a.push(n)}const d=oe(null!==(n=te(e,"MaterialAssignation"))&&void 0!==n?n:Ye("x"),0),h=ot(te(e,"Materials"));if(h&&h.length>0){const e="ByPolygon"===d?"ByPolygon":"AllSame";a.push(Ye("LayerElementMaterial",[Xe(0)],[Ye("Version",[Xe(101)]),Ye("Name",[qe("")]),Ye("MappingInformationType",[qe(e)]),Ye("ReferenceInformationType",[qe("IndexToDirect")]),Je("Materials","AllSame"===e?Int32Array.of(h[0]):h)]))}for(const t of e.children)"Shape"===t.name&&a.push(t);return a}(t,e.version)),e.objects.push(Ye("Model",[qe(u),qe(h)],b)),function(e,t,n){var o;for(const s of t.children){if("Material"!==s.name)continue;const t=null!==(o=oe(s,0))&&void 0!==o?o:"Material",r=it(e,t.includes("::")?t:`Material::${t}`),i=(e,t)=>{const n=tt(te(s,e));return n.length>=3?Qe(t,"ColorRGB","",n[0],n[1],n[2]):null},a=(e,t)=>{const n=et(te(s,e));return void 0!==n?Qe(t,"double","",n):null},l=[i("Ambient","AmbientColor"),i("Diffuse","DiffuseColor"),i("Specular","SpecularColor"),i("Emissive","EmissiveColor"),a("Shininess","Shininess"),a("Alpha","Opacity"),a("Reflectivity","ReflectionFactor")].filter(e=>null!==e),u=te(s,"ShadingModel");e.objects.push(Ye("Material",[qe(r),qe("")],[Ye("Version",[Xe(100)]),null!=u?u:Ye("ShadingModel",[qe("phong")]),Ye("Properties60",[],l)])),at(e,r,n)}}(e,t,u),function(e,t,n){var o;const s=t.children.filter(e=>"Link"===e.name);if(0===s.length)return;const r=it(e,`Deformer::Skin ${re(n)}`);e.objects.push(Ye("Deformer",[qe(r),qe("Skin")],[Ye("Version",[Xe(100)]),Ye("Link_DeformAcuracy",[ze(50)])])),at(e,r,n);for(const t of s){const s=null!==(o=oe(t,0))&&void 0!==o?o:"",i=it(e,`SubDeformer::Cluster ${re(n)} ${re(s)}`),a=[Ye("Version",[Xe(100)]),Ye("Mode",[qe("Normalize")])];for(const e of["Indexes","Weights","Transform","TransformLink"]){const n=te(t,e);if(!n)continue;const o="Indexes"===e?ot(n):nt(n);o&&a.push(Je(e,o))}e.objects.push(Ye("Deformer",[qe(i),qe("Cluster")],a)),at(e,i,r),at(e,s,i)}}(e,t,u);const x=te(t,"Children");for(const t of null!==(l=null==x?void 0:x.properties)&&void 0!==l?l:[])"string"==typeof t.value&&at(e,t.value,u)}const ct={Aim:"aim","Parent-Child":"parent","Position From Positions":"position","Rotation From Rotations":"rotation","Scale From Scales":"scale","Single Chain IK":"singleChainIK"};function dt(e,t){return e&&"number"==typeof e[0]&&"number"==typeof e[1]&&"number"==typeof e[2]?[e[0],e[1],e[2]]:t}function ht(e,t){const n=null==e?void 0:e[0];return"number"==typeof n?n:"boolean"==typeof n?n?1:0:t}function pt(e,t,n){var o,s,r,i,a;const l=t.children.find(e=>"Type"===e.name),u=null!==(s=null!==(o=l?oe(l,0):void 0)&&void 0!==o?o:oe(t,2))&&void 0!==s?s:"",c=null!==(r=ct[u])&&void 0!==r?r:"unknown",d=new Map;for(const e of pe(t))d.set(e.name,e.values);const h=(e,t)=>[0!==ht(d.get(`${e}X`),t?1:0),0!==ht(d.get(`${e}Y`),t?1:0),0!==ht(d.get(`${e}Z`),t?1:0)],p={id:e,name:re(null!==(i=oe(t,1))&&void 0!==i?i:"Constraint"),type:c,typeName:u,targets:[],weight:ht(d.get("Weight"),100)/100,active:0!==ht(d.get("Active"),1),affectTranslation:[!0,!0,!0],affectRotation:[!0,!0,!0],affectScale:[!1,!1,!1],offsetTranslation:[0,0,0],offsetRotation:[0,0,0],offsetScale:[1,1,1],aimVector:dt(d.get("AimVector"),[1,0,0]),upVector:dt(d.get("UpVector"),[0,1,0]),worldUpVector:dt(d.get("WorldUpVector"),[0,1,0]),worldUpType:ht(d.get("WorldUpType"),0),ikPoleVector:dt(d.get("PoleVector"),[0,0,0])};switch(c){case"aim":p.affectRotation=h("Affect",!0),p.offsetRotation=dt(d.get("RotationOffset"),[0,0,0]);break;case"parent":p.affectTranslation=h("AffectTranslation",!0),p.affectRotation=h("AffectRotation",!0),p.affectScale=h("AffectScale",!1);break;case"position":p.affectTranslation=h("Affect",!0),p.offsetTranslation=dt(d.get("Translation"),[0,0,0]);break;case"rotation":p.affectRotation=h("Affect",!0),p.offsetRotation=dt(d.get("Rotation"),[0,0,0]);break;case"scale":p.affectScale=h("Affect",!0),p.offsetScale=dt(d.get("Scaling"),[1,1,1])}const f="singleChainIK"===c?1:100;for(const t of n.connections){if(t.parentId!==e||"OP"!==t.type||!t.propertyName)continue;const o=n.objects.get(t.childId);if(!o||"Model"!==o.name)continue;const s=t.propertyName,r=re(null!==(a=oe(o,1))&&void 0!==a?a:"");switch(s){case"Constrained Object":case"Constrained object (Child)":p.nodeId=t.childId;break;case"Source":case"Source (Parent)":case"Aim At Object":case"Pole Vector Object":p.targets.push({modelId:t.childId,weight:ht(d.get(`${r}.Weight`),f)/f,offsetTranslation:dt(d.get(`${r}.Offset T`),[0,0,0]),offsetRotation:dt(d.get(`${r}.Offset R`),[0,0,0]),offsetScale:dt(d.get(`${r}.Offset S`),[1,1,1])});break;case"World Up Object":p.worldUpNodeId=t.childId;break;case"First Joint":p.ikFirstJointId=t.childId;break;case"End Joint":p.ikEndJointId=t.childId;break;case"Effector":p.ikEffectorId=t.childId}}return p}var ft,mt,gt;!function(e){e[e.DefaultW1=1]="DefaultW1",e[e.WidenToRgb=2]="WidenToRgb",e[e.MultiplyValue=4]="MultiplyValue"}(ft||(ft={})),function(e){e[e.None=0]="None",e[e.InvertX=1]="InvertX",e[e.UnknownShininess=2]="UnknownShininess"}(mt||(mt={})),function(e){e[e.Inverted=1]="Inverted",e[e.IfExists=2]="IfExists",e[e.IfTexture=4]="IfTexture",e[e.IfAround1=8]="IfAround1"}(gt||(gt={}));const _t=[["diffuseColor",1,0,"Diffuse"],["diffuseColor",1,0,"DiffuseColor"],["diffuseFactor",0,0,"DiffuseFactor"],["specularColor",1,0,"Specular"],["specularColor",1,0,"SpecularColor"],["specularFactor",0,0,"SpecularFactor"],["specularExponent",0,0,"Shininess"],["specularExponent",0,0,"ShininessExponent"],["reflectionColor",1,0,"Reflection"],["reflectionColor",1,0,"ReflectionColor"],["reflectionFactor",0,0,"ReflectionFactor"],["transparencyColor",1,0,"Transparent"],["transparencyColor",1,0,"TransparentColor"],["transparencyFactor",0,0,"TransparentFactor"],["transparencyFactor",0,0,"TransparencyFactor"],["emissionColor",1,0,"Emissive"],["emissionColor",1,0,"EmissiveColor"],["emissionFactor",0,0,"EmissiveFactor"],["ambientColor",1,0,"Ambient"],["ambientColor",1,0,"AmbientColor"],["ambientFactor",0,0,"AmbientFactor"],["normalMap",0,0,"NormalMap"],["bump",0,0,"Bump"],["bumpFactor",0,0,"BumpFactor"],["displacement",0,0,"Displacement"],["displacementFactor",0,0,"DisplacementFactor"],["vectorDisplacement",0,0,"VectorDisplacement"],["vectorDisplacementFactor",0,0,"VectorDisplacementFactor"]],vt=[["baseColor",1,0,"Diffuse"],["baseColor",1,0,"DiffuseColor"],["baseFactor",0,0,"DiffuseFactor"],["specularColor",1,0,"Specular"],["specularColor",1,0,"SpecularColor"],["specularFactor",0,0,"SpecularFactor"],["roughness",0,2,"Shininess"],["roughness",0,2,"ShininessExponent"],["transmissionColor",1,0,"Transparent"],["transmissionColor",1,0,"TransparentColor"],["transmissionFactor",0,0,"TransparentFactor"],["transmissionFactor",0,0,"TransparencyFactor"],["emissionColor",1,0,"Emissive"],["emissionColor",1,0,"EmissiveColor"],["emissionFactor",0,0,"EmissiveFactor"],["normalMap",0,0,"NormalMap"]],yt=[["roughnessAsGlossiness",8,"useGlossiness"]],bt=["pbr","metalness","diffuse","specular","coat","sheen","transmission","opacity","ior","diffuseRoughness"],xt={unknown:{maps:vt,features:[],defaultFeatures:["diffuse","specular","emission","transmission"]},fbxLambert:{maps:[["baseColor",1,0,"Diffuse"],["baseColor",1,0,"DiffuseColor"],["baseFactor",0,0,"DiffuseFactor"],["transmissionColor",1,0,"Transparent"],["transmissionColor",1,0,"TransparentColor"],["transmissionFactor",0,0,"TransparentFactor"],["transmissionFactor",0,0,"TransparencyFactor"],["emissionColor",1,0,"Emissive"],["emissionColor",1,0,"EmissiveColor"],["emissionFactor",0,0,"EmissiveFactor"],["normalMap",0,0,"NormalMap"]],features:[],defaultFeatures:["diffuse","emission","transmission"]},fbxPhong:{maps:vt,features:[],defaultFeatures:["diffuse","specular","emission","transmission"]},oslStandardSurface:{maps:[["baseFactor",0,0,"base"],["baseColor",1,0,"base_color"],["roughness",0,0,"specular_roughness"],["diffuseRoughness",0,0,"diffuse_roughness"],["metalness",0,0,"metalness"],["specularFactor",0,0,"specular"],["specularColor",1,0,"specular_color"],["specularIor",0,0,"specular_IOR"],["specularAnisotropy",0,0,"specular_anisotropy"],["specularRotation",0,0,"specular_rotation"],["transmissionFactor",0,0,"transmission"],["transmissionColor",1,0,"transmission_color"],["transmissionDepth",0,0,"transmission_depth"],["transmissionScatter",2,0,"transmission_scatter"],["transmissionScatterAnisotropy",0,0,"transmission_scatter_anisotropy"],["transmissionDispersion",0,0,"transmission_dispersion"],["transmissionExtraRoughness",0,0,"transmission_extra_roughness"],["subsurfaceFactor",0,0,"subsurface"],["subsurfaceColor",1,0,"subsurface_color"],["subsurfaceRadius",2,0,"subsurface_radius"],["subsurfaceScale",0,0,"subsurface_scale"],["subsurfaceAnisotropy",0,0,"subsurface_anisotropy"],["sheenFactor",0,0,"sheen"],["sheenColor",1,0,"sheen_color"],["sheenRoughness",0,0,"sheen_roughness"],["coatFactor",0,0,"coat"],["coatColor",1,0,"coat_color"],["coatRoughness",0,0,"coat_roughness"],["coatIor",0,0,"coat_IOR"],["coatAnisotropy",0,0,"coat_anisotropy"],["coatRotation",0,0,"coat_rotation"],["coatNormal",0,0,"coat_normal"],["coatAffectBaseColor",1,0,"coat_affect_color"],["coatAffectBaseRoughness",0,0,"coat_affect_roughness"],["thinFilmThickness",0,0,"thin_film_thickness"],["thinFilmIor",0,0,"thin_film_IOR"],["emissionFactor",0,0,"emission"],["emissionColor",1,0,"emission_color"],["opacity",2,0,"opacity"],["normalMap",0,0,"NormalMap"],["normalMap",0,0,"normalCamera"],["tangentMap",0,0,"tangent"]],features:[["thinWalled",0,"thin_walled"]],defaultFeatures:bt},arnoldStandardSurface:{maps:[["baseFactor",0,0,"base"],["baseColor",1,0,"baseColor"],["roughness",0,0,"specularRoughness"],["diffuseRoughness",0,0,"diffuseRoughness"],["metalness",0,0,"metalness"],["specularFactor",0,0,"specular"],["specularColor",1,0,"specularColor"],["specularIor",0,0,"specularIOR"],["specularAnisotropy",0,0,"specularAnisotropy"],["specularRotation",0,0,"specularRotation"],["transmissionFactor",0,0,"transmission"],["transmissionColor",1,0,"transmissionColor"],["transmissionDepth",0,0,"transmissionDepth"],["transmissionScatter",2,0,"transmissionScatter"],["transmissionScatterAnisotropy",0,0,"transmissionScatterAnisotropy"],["transmissionDispersion",0,0,"transmissionDispersion"],["transmissionExtraRoughness",0,0,"transmissionExtraRoughness"],["subsurfaceFactor",0,0,"subsurface"],["subsurfaceColor",1,0,"subsurfaceColor"],["subsurfaceRadius",2,0,"subsurfaceRadius"],["subsurfaceScale",0,0,"subsurfaceScale"],["subsurfaceAnisotropy",0,0,"subsurfaceAnisotropy"],["sheenFactor",0,0,"sheen"],["sheenColor",1,0,"sheenColor"],["sheenRoughness",0,0,"sheenRoughness"],["coatFactor",0,0,"coat"],["coatColor",1,0,"coatColor"],["coatRoughness",0,0,"coatRoughness"],["coatIor",0,0,"coatIOR"],["coatAnisotropy",0,0,"coatAnisotropy"],["coatRotation",0,0,"coatRotation"],["coatNormal",0,0,"coatNormal"],["thinFilmThickness",0,0,"thinFilmThickness"],["thinFilmIor",0,0,"thinFilmIOR"],["emissionFactor",0,0,"emission"],["emissionColor",1,0,"emissionColor"],["opacity",2,0,"opacity"],["indirectDiffuse",0,0,"indirectDiffuse"],["indirectSpecular",0,0,"indirectSpecular"],["normalMap",0,0,"NormalMap"],["normalMap",0,0,"normalCamera"],["tangentMap",0,0,"tangent"],["matteColor",1,0,"aiMatteColor"],["matteFactor",0,0,"aiMatteColorA"],["subsurfaceType",0,0,"subsurfaceType"],["transmissionPriority",0,0,"dielectricPriority"],["transmissionEnableInAov",0,0,"transmitAovs"]],features:[["matte",0,"aiEnableMatte"],["thinWalled",0,"thinWalled"],["caustics",0,"caustics"],["internalReflections",0,"internalReflections"],["exitToBackground",0,"exitToBackground"]],defaultFeatures:bt},"3dsMaxPhysicalMaterial":{maps:[["baseFactor",0,0,"base_weight"],["baseColor",1,0,"base_color"],["roughness",0,0,"roughness"],["diffuseRoughness",0,0,"diff_rough"],["diffuseRoughness",0,0,"diff_roughness"],["metalness",0,0,"metalness"],["specularFactor",0,0,"reflectivity"],["specularColor",1,0,"refl_color"],["specularAnisotropy",0,0,"anisotropy"],["specularRotation",0,0,"aniso_angle"],["specularRotation",0,0,"anisoangle"],["specularIor",0,0,"trans_ior"],["transmissionFactor",0,0,"transparency"],["transmissionColor",1,0,"trans_color"],["transmissionDepth",0,0,"trans_depth"],["transmissionRoughness",0,0,"trans_rough"],["transmissionRoughness",0,0,"trans_roughness"],["subsurfaceFactor",0,0,"scattering"],["subsurfaceTintColor",1,0,"sss_color"],["subsurfaceColor",1,0,"sss_scatter_color"],["subsurfaceRadius",2,0,"sss_depth"],["subsurfaceScale",0,0,"sss_scale"],["coatFactor",0,0,"coat"],["coatFactor",0,0,"coating"],["coatColor",1,0,"coat_color"],["coatRoughness",0,0,"coat_rough"],["coatRoughness",0,0,"coat_roughness"],["coatIor",0,0,"coat_ior"],["coatNormal",0,0,"coat_bump"],["coatNormal",0,0,"clearcoat_bump_map_amt"],["coatAffectBaseColor",1,0,"coat_affect_color"],["coatAffectBaseRoughness",0,0,"coat_affect_roughness"],["emissionFactor",0,0,"emission"],["emissionColor",1,0,"emit_color"],["opacity",2,0,"cutout"],["normalMap",0,0,"bump"],["normalMap",0,0,"bump_map_amt"],["displacementMap",0,0,"displacement"],["displacementMap",0,0,"displacement_map_amt"],["subsurfaceType",0,0,"subsurfaceType"]],features:[["thinWalled",0,"thin_walled"],["specular",0,"material_mode"],["diffuseRoughness",0,"material_mode"],["transmissionRoughness",1,"trans_roughness_lock"],["roughnessAsGlossiness",0,"roughness_inv"],["transmissionRoughnessAsGlossiness",0,"trans_roughness_inv"],["coatRoughnessAsGlossiness",0,"coat_roughness_inv"]],defaultFeatures:["pbr","metalness","diffuse","coat","sheen","transmission","opacity","ior"],textureSuffix:"_map",textureEnabledSuffix:"_map_on"},"3dsMaxPbrMetalRough":{maps:[["baseColor",1,0,"base_color"],["baseColor",1,0,"baseColor"],["roughness",0,0,"roughness"],["roughness",0,0,"Roughness_Map"],["metalness",0,0,"metalness"],["ambientOcclusion",0,0,"ao"],["normalMap",0,0,"norm"],["emissionColor",1,0,"emit_color"],["displacementMap",0,0,"displacement"],["displacementMap",0,0,"displacement_amt"],["opacity",2,0,"opacity"]],features:yt,defaultFeatures:["pbr","metalness","diffuse","opacity"],textureSuffix:"_map"},"3dsMaxPbrSpecGloss":{maps:[["baseColor",1,0,"base_color"],["baseColor",1,0,"baseColor"],["specularColor",1,0,"Specular"],["specularColor",1,0,"specular"],["roughness",0,0,"glossiness"],["ambientOcclusion",0,0,"ao"],["normalMap",0,0,"norm"],["emissionColor",1,0,"emit_color"],["displacementMap",0,0,"displacement"],["displacementMap",0,0,"displacement_amt"],["opacity",2,0,"opacity"]],features:yt,defaultFeatures:["pbr","specular","diffuse","opacity"],textureSuffix:"_map"},gltfMaterial:{maps:[["baseColor",1,0,"main|baseColor"],["roughness",0,0,"main|roughness"],["metalness",0,0,"main|metalness"],["normalMap",0,0,"main|normal"],["ambientOcclusion",0,0,"main|ambientOcclusion"],["emissionColor",1,0,"main|emission"],["emissionColor",1,0,"main|emissionColor"],["opacity",2,0,"main|Alpha"],["coatFactor",0,0,"extension|clearcoat"],["coatRoughness",0,0,"extension|clearcoatRoughness"],["coatNormal",0,0,"extension|clearcoatNormal"],["sheenColor",1,0,"extension|sheenColor"],["sheenRoughness",0,0,"extension|sheenRoughness"],["specularFactor",0,0,"extension|specular"],["specularFactor",0,0,"extension|Specular"],["specularColor",1,0,"extension|specularcolor"],["specularColor",1,0,"extension|specularColor"],["transmissionFactor",0,0,"extension|transmission"],["specularIor",0,0,"extension|indexOfRefraction"]],features:[["doubleSided",0,"main|DoubleSided"],["sheen",0,"extension|enableSheen"],["coat",0,"extension|enableClearCoat"],["transmission",0,"extension|enableTransmission"],["ior",0,"extension|enableIndexOfRefraction"],["specular",0,"extension|enableSpecular"],["unlit",0,"extension|unlit"]],defaultFeatures:["pbr","metalness","diffuse","emission","opacity","ambientOcclusion"],textureSuffix:"Map"},openPbrMaterial:{maps:[["baseFactor",0,0,"base_weight"],["baseColor",1,0,"base_color"],["roughness",0,0,"specular_roughness"],["diffuseRoughness",0,0,"base_diffuse_roughness"],["metalness",0,0,"base_metalness"],["specularFactor",0,0,"specular_weight"],["specularColor",1,0,"specular_color"],["specularAnisotropy",0,0,"specular_roughness_anisotropy"],["specularIor",0,0,"specular_ior"],["transmissionFactor",0,0,"transmission_weight"],["transmissionColor",1,0,"transmission_color"],["transmissionDepth",0,0,"transmission_depth"],["transmissionScatter",2,0,"transmission_scatter"],["transmissionScatterAnisotropy",0,0,"transmission_scatter_anisotropy"],["transmissionDispersion",0,0,"transmission_dispersion_scale"],["subsurfaceFactor",0,0,"subsurface_weight"],["subsurfaceColor",1,0,"subsurface_color"],["subsurfaceRadius",2,0,"subsurface_radius_scale"],["subsurfaceScale",0,0,"subsurface_radius"],["subsurfaceAnisotropy",0,0,"subsurface_scatter_anisotropy"],["coatFactor",0,0,"coat_weight"],["coatColor",1,0,"coat_color"],["coatRoughness",0,0,"coat_roughness"],["coatAnisotropy",0,0,"coat_roughness_anisotropy"],["coatIor",0,0,"coat_ior"],["coatNormal",0,0,"coat_normal_map"],["sheenFactor",0,0,"fuzz_weight"],["sheenColor",1,0,"fuzz_color"],["sheenRoughness",0,0,"fuzz_roughness"],["emissionFactor",0,0,"emission_weight"],["emissionFactor",4,0,"emission_luminance"],["emissionColor",1,0,"emission_color"],["thinFilmFactor",0,0,"thin_film_weight"],["thinFilmThickness",0,0,"thin_film_thickness"],["thinFilmIor",0,0,"thin_film_ior"],["normalMap",0,0,"bump"],["normalMap",0,0,"bump_map_amt"],["displacementMap",0,0,"displacement"],["displacementMap",0,0,"displacement_map_amt"],["coatNormal",0,0,"coat_bump"],["coatNormal",0,0,"coat_bump_map_amt"],["tangentMap",0,0,"geometry_tangent_map"],["opacity",2,0,"geometry_opacity"]],features:[["thinWalled",0,"geometry_thin_walled"]],defaultFeatures:bt,textureSuffix:"_map",textureEnabledSuffix:"_map_on"},shaderFxGraph:{maps:[["baseColor",1,0,"color"],["baseColor",1,0,"base_color"],["roughness",0,0,"roughness"],["metalness",0,0,"metallic"],["normalMap",0,0,"normal"],["emissionFactor",0,0,"emissive_intensity"],["emissionColor",1,0,"emissive"],["ambientOcclusion",0,0,"ao"]],features:[],defaultFeatures:["pbr","metalness","diffuse","emission","ambientOcclusion"],texturePrefix:"TEX_",textureSuffix:"_map",textureEnabledPrefix:"use_",textureEnabledSuffix:"_map"}};function Tt(e){return"unknown"!==e&&"fbxLambert"!==e&&"fbxPhong"!==e}function At(e,t){switch(e){case 1:t[0]=1-t[0];break;case 2:t[0]>=0&&(t[0]=1-.1*Math.sqrt(t[0]),t[0]<0&&(t[0]=0))}}function wt(e){const t=[];for(const n of e)if("number"==typeof n)t.push(n);else{if("boolean"!=typeof n)break;t.push(n?1:0)}return t}function Mt(e){var t,n,o,s,r,i,a,l,u,c;const{shaderType:d,shaderPropPrefix:h}=function(e){var t,n,o,s,r,i;let a="unknown";const l=e.shadingModelName.toLowerCase();if("lambert"===l?a="fbxLambert":"phong"===l&&(a="fbxPhong"),e.shader)switch(e.shader.renderApi){case"ARNOLD_SHADER_ID":return{shaderType:"arnoldStandardSurface",shaderPropPrefix:""};case"OSL":return{shaderType:"oslStandardSurface",shaderPropPrefix:""};case"SFX_PBS_SHADER":return{shaderType:"shaderFxGraph",shaderPropPrefix:""};default:return{shaderType:"unknown",shaderPropPrefix:""}}if("unknown"===a){const a=(null!==(o=wt(null!==(n=null===(t=e.props.get("3dsMax|ClassIDa"))||void 0===t?void 0:t.values)&&void 0!==n?n:[])[0])&&void 0!==o?o:0)>>>0,l=(null!==(i=wt(null!==(r=null===(s=e.props.get("3dsMax|ClassIDb"))||void 0===s?void 0:s.values)&&void 0!==r?r:[])[0])&&void 0!==i?i:0)>>>0;if(1030429932===a&&3735928833===l)return{shaderType:"3dsMaxPhysicalMaterial",shaderPropPrefix:"3dsMax|Parameters|"};if(4048887347===a&&939201335===l)return{shaderType:"openPbrMaterial",shaderPropPrefix:"3dsMax|Parameters|"};if(943849874===a&&1174294043===l)return{shaderType:"gltfMaterial",shaderPropPrefix:"3dsMax|"};if(3490651648===a&&3195528448===l)return{shaderType:"3dsMaxPbrMetalRough",shaderPropPrefix:"3dsMax|main|"};if(3490651648===a&&31173939===l)return{shaderType:"3dsMaxPbrSpecGloss",shaderPropPrefix:"3dsMax|main|"}}return{shaderType:a,shaderPropPrefix:""}}(e),p=xt[d],f={shaderType:d,shaderPropPrefix:h,fbx:{},pbr:{},features:{}};for(const e of p.defaultFeatures)f.features[e]={enabled:!0,explicit:!1};const m=t=>{var n;const o=null===(n=e.shader)||void 0===n?void 0:n.bindings.get(t);return o&&o.length>0?o:[t]},g=e.shader?"":h,_=(t,n,o,s,r,i,a)=>{var l,u,c,d,h;for(const[p,f,_,v]of t){const t=g+o+v+s;for(const o of m(t)){const t=e.props.get(o),s=null!==(l=n[p])&&void 0!==l?l:n[p]={valueComponents:0,textureEnabled:!1};if(r&&t&&"Reference"!==t.type){const e=wt(t.values);if(e.length>0){const t=e.slice(0,4);4&f?(t[0]*=null!==(c=null===(u=s.value)||void 0===u?void 0:u[0])&&void 0!==c?c:1,s.value=[t[0],...null!==(h=null===(d=s.value)||void 0===d?void 0:d.slice(1))&&void 0!==h?h:[]]):s.value=t,At(_,s.value);const n=e.length>=4?4:3===e.length?3:2===e.length?2:1;1&f&&n<4&&(s.value[3]=1),2&f&&1===n&&(s.value[1]=s.value[0],s.value[2]=s.value[0]),s.valueComponents=n}}if(i){const t=e.texturesByProp.get(o);t&&(s.texture=t,s.textureEnabled=!0)}if(a&&t){const e=wt(t.values);e.length>0&&(s.textureEnabled=0!==e[0])}}}};_(_t,f.fbx,"","",!0,!0,!1),(p.texturePrefix||p.textureSuffix)&&_(p.maps,f.pbr,null!==(t=p.texturePrefix)&&void 0!==t?t:"",null!==(n=p.textureSuffix)&&void 0!==n?n:"",!1,!0,!1),_(p.maps,f.pbr,"","",!0,!0,!1),(p.textureEnabledPrefix||p.textureEnabledSuffix)&&_(p.maps,f.pbr,null!==(o=p.textureEnabledPrefix)&&void 0!==o?o:"",null!==(s=p.textureEnabledSuffix)&&void 0!==s?s:"",!1,!1,!0);for(const[t,n,o]of p.features){const s=g+o;for(const o of m(s)){const s=e.props.get(o),i=null!==(r=(c=f.features)[t])&&void 0!==r?r:c[t]={enabled:!1,explicit:!1};if(s&&"Reference"!==s.type){const e=wt(s.values);e.length>0&&(i.enabled=0!==e[0],i.explicit=!0,8&n&&(i.enabled=e[0]>=.5&&e[0]<=1.5),1&n&&(i.enabled=!i.enabled),2&n&&(i.enabled=!0))}4&n&&e.texturesByProp.has(o)&&(i.enabled=!0)}}const v=(e,t,n)=>{var o;const s=null!==(o=e[t])&&void 0!==o?o:e[t]={valueComponents:0,textureEnabled:!1};if(s.value)return;const r=e[n],i=(null==r?void 0:r.value)&&r.value.some(e=>0!==e);s.value=[i?1:0],s.valueComponents=1};v(f.fbx,"diffuseFactor","diffuseColor"),v(f.fbx,"specularFactor","specularColor"),v(f.fbx,"reflectionFactor","reflectionColor"),v(f.fbx,"transparencyFactor","transparencyColor"),v(f.fbx,"emissionFactor","emissionColor"),v(f.fbx,"ambientFactor","ambientColor"),v(f.pbr,"baseFactor","baseColor"),v(f.pbr,"specularFactor","specularColor"),v(f.pbr,"emissionFactor","emissionColor"),v(f.pbr,"sheenFactor","sheenColor"),v(f.pbr,"thinFilmFactor","thinFilmThickness"),v(f.pbr,"transmissionFactor","transmissionColor"),!(null===(i=f.pbr.transmissionRoughness)||void 0===i?void 0:i.value)&&(null===(a=f.pbr.roughness)||void 0===a?void 0:a.value)&&(null===(l=f.pbr.transmissionExtraRoughness)||void 0===l?void 0:l.value)&&(f.pbr.transmissionRoughness={value:[f.pbr.roughness.value[0]+f.pbr.transmissionExtraRoughness.value[0]],valueComponents:1,textureEnabled:!1});const y=[["roughnessAsGlossiness","roughness","glossiness"],["coatRoughnessAsGlossiness","coatRoughness","coatGlossiness"],["transmissionRoughnessAsGlossiness","transmissionRoughness","transmissionGlossiness"]];for(const[e,t,n]of y){const o=f.pbr[t];(null===(u=f.features[e])||void 0===u?void 0:u.enabled)?o&&(f.pbr[n]=o,f.pbr[t]=o.value?{value:[1-o.value[0]],valueComponents:1,textureEnabled:!1}:{valueComponents:0,textureEnabled:!1}):(null==o?void 0:o.value)&&(f.pbr[n]={value:[1-o.value[0]],valueComponents:1,textureEnabled:!1})}return f}function St(e){var t,n;if(!(null==e?void 0:e.value))return;const o=e.value;return 1===e.valueComponents?[o[0],o[0],o[0]]:[o[0],null!==(t=o[1])&&void 0!==t?t:o[0],null!==(n=o[2])&&void 0!==n?n:o[0]]}function Rt(e){return(null==e?void 0:e.value)?e.value[0]:void 0}function Ct(e,t,n,o){var s,r,i,a,l;const u=re(null!==(s=oe(e,1))&&void 0!==s?s:"Material"),c=function(e,t){var n,o;if(!t)return;const s=te(e,"ShadingModel"),r=s?oe(s,0):void 0;return"phong"===(null==r?void 0:r.toLowerCase())?null!==(n=ie(t,"Material","FbxSurfacePhong"))&&void 0!==n?n:ie(t,"Material"):"lambert"===(null==r?void 0:r.toLowerCase())&&null!==(o=ie(t,"Material","FbxSurfaceLambert"))&&void 0!==o?o:ie(t,"Material")}(e,o),d=te(e,"ShadingModel"),h=d?null!==(r=oe(d,0))&&void 0!==r?r:"Lambert":null!==(i=ae(e,c,"ShadingModel"))&&void 0!==i?i:"Lambert",p="phong"===h.toLowerCase()?"Phong":"Lambert",f=function(e,t){var n,o,s,r,i;const a={};return a.diffuseColor=null!==(n=Ft(e,t,"DiffuseColor"))&&void 0!==n?n:Ft(e,t,"Diffuse"),a.diffuseFactor=Et(e,t,"DiffuseFactor"),a.ambientColor=null!==(o=Ft(e,t,"AmbientColor"))&&void 0!==o?o:Ft(e,t,"Ambient"),a.ambientFactor=Et(e,t,"AmbientFactor"),a.specularColor=null!==(s=Ft(e,t,"SpecularColor"))&&void 0!==s?s:Ft(e,t,"Specular"),a.specularFactor=Et(e,t,"SpecularFactor"),a.shininess=null!==(r=Et(e,t,"Shininess"))&&void 0!==r?r:Et(e,t,"ShininessExponent"),a.emissiveColor=null!==(i=Ft(e,t,"EmissiveColor"))&&void 0!==i?i:Ft(e,t,"Emissive"),a.emissiveFactor=Et(e,t,"EmissiveFactor"),a.opacity=Et(e,t,"Opacity"),a.transparencyFactor=Et(e,t,"TransparencyFactor"),a}(e,c),m=function(e,t,n){const o=[],s=ye(t,e,"Texture");for(const{id:e,node:r,propertyName:i}of s)o.push(Ot(e,r,i,t,n));for(const{id:s,propertyName:r}of ye(t,e,"LayeredTexture")){const e=ye(t,s,"Texture");if(0===e.length)continue;const i=Ot(e[0].id,e[0].node,r,t,n);i.layeredTextureId=s,o.push(i)}return o}(t,n,o?null!==(a=ie(o,"Texture","FbxFileTexture"))&&void 0!==a?a:ie(o,"Texture"):void 0),g=new Map;for(const e of null!==(l=null==c?void 0:c.properties.values())&&void 0!==l?l:[])g.set(e.name,{type:e.propertyType,values:e.values});for(const t of pe(e))g.set(t.name,{type:t.type,values:t.values});const _=new Map;for(const e of m)_.has(e.propertyName)||_.set(e.propertyName,e);return{id:t,name:u,type:p,properties:f,textures:m,model:Mt({shadingModelName:h,props:g,texturesByProp:_,shader:It(t,n)}),userProperties:fe(e)}}function It(e,t){var n;const o=t.connections.filter(n=>{var o;return"OO"===n.type&&n.childId===e&&"Implementation"===(null===(o=t.objects.get(n.parentId))||void 0===o?void 0:o.name)}).map(e=>({id:e.parentId,node:t.objects.get(e.parentId)}));if(0===o.length)return;const s=o[0],r=null===(n=pe(s.node).find(e=>"RenderAPI"===e.name))||void 0===n?void 0:n.values[0],i=new Map,a=(e,t)=>{const n=i.get(e);n?n.push(t):i.set(e,[t])};for(const e of ye(t,s.id,"BindingTable"))for(const t of e.node.children){if("Entry"!==t.name)continue;const e=oe(t,0),n=oe(t,1),o=oe(t,2),s=oe(t,3);"string"==typeof e&&"string"==typeof o&&("FbxPropertyEntry"===n&&"FbxSemanticEntry"===s?a(o,e):"FbxSemanticEntry"===n&&"FbxPropertyEntry"===s&&a(e,o))}return{renderApi:"string"==typeof r?r:"",bindings:i}}function Ot(e,t,n,o,s){var r,i,a,l,u;{const c=te(t,"FileName"),d=te(t,"RelativeFilename"),h=c&&null!==(r=oe(c,0))&&void 0!==r?r:"",p=d&&null!==(i=oe(d,0))&&void 0!==i?i:"";let f,m;const g=null!==(a=Et(t,s,"UVRotation"))&&void 0!==a?a:Et(t,s,"Rotation");let _;f=null!==(l=Nt(t,s,"UVTranslation"))&&void 0!==l?l:Nt(t,s,"Translation"),m=null!==(u=Nt(t,s,"UVScaling"))&&void 0!==u?u:Nt(t,s,"Scaling");const v=ae(t,s,"UVSet");v&&v.length>0&&(_=v),null!=f||(f=kt(t,"ModelUVTranslation")),null!=m||(m=kt(t,"ModelUVScaling"));const y=Et(t,s,"WrapModeU"),b=Et(t,s,"WrapModeV");let x=null;const T=ye(o,e,"Video");for(const{node:e}of T){const t=te(e,"Content");if(t&&t.properties.length>0){const e=t.properties[0].value;e instanceof Uint8Array&&e.length>0?x=e:e instanceof ArrayBuffer&&e.byteLength>0&&(x=new Uint8Array(e))}}return{propertyName:null!=n?n:"DiffuseColor",fileName:h,relativeFileName:p,id:e,embeddedData:x,uvTranslation:f,uvScaling:m,uvRotation:g,uvSetName:_,wrapU:y,wrapV:b}}}function Ft(e,t,n){const o=ce(e,t,n);if(!o||o.length<3)return;const s=Lt(o[0]),r=Lt(o[1]),i=Lt(o[2]);return void 0!==s&&void 0!==r&&void 0!==i?[s,r,i]:void 0}function Et(e,t,n){return Lt(ae(e,t,n))}function Nt(e,t,n){const o=ce(e,t,n);if(!o)return;const s=Lt(o[0]),r=Lt(o[1]);return void 0!==s&&void 0!==r?[s,r]:void 0}function Lt(e){if("number"==typeof e)return e}function kt(e,t){var n,o;const s=te(e,t);if(!s)return;const r=Lt(null===(n=s.properties[0])||void 0===n?void 0:n.value),i=Lt(null===(o=s.properties[1])||void 0===o?void 0:o.value);return void 0!==r&&void 0!==i?[r,i]:void 0}let Pt;function Bt(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=ye(n,e,"Deformer");if(0===c.length)return null;const d=new Map;for(const{id:e,node:t}of c){if("Cluster"!==oe(t,2))continue;const o=ye(n,e,"Model");o.length>0&&d.set(o[0].id,{clusterId:e,clusterNode:t})}const h=function(e,t){var n;const o=t.parentOf.get(e),s=o?t.objects.get(o.id):void 0,r="Model"===(null==s?void 0:s.name)?o.id:void 0;if(void 0===r)return new Map;for(const[,e]of Array.from(t.objects)){if("Pose"!==e.name||"BindPose"!==oe(e,2))continue;const t=new Map;for(const o of e.children){if("PoseNode"!==o.name)continue;const e=te(o,"Node"),s=te(o,"Matrix"),r=null===(n=null==e?void 0:e.properties[0])||void 0===n?void 0:n.value,i=se(s);if("number"!=typeof r)continue;const a=Kt(i);16===(null==a?void 0:a.length)&&t.set(r,a)}if(t.has(r))return t}return new Map}(r,n),p=[],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=Dt(o,t);for(;void 0!==e;){const o=t.objects.get(e);if(!o||"Model"!==o.name)break;n.add(e),e=Dt(e,t)}}return n}(e,n),h=function(e,t){const n=new Map;for(const o of Array.from(e)){let s=Dt(o,t);for(;void 0!==s;){if(e.has(s)){n.set(o,s);break}s=Dt(s,t)}}return n}(d,n),p=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 m=n.objects.get(d);if(!m)continue;const g=u.length,_=e.get(d),v=Gt(m),{bindPoseMatrix:y,transformLinkMatrix:b,transformAssociateModelMatrix:x,clusterMode:T}=_?$t(_.clusterNode):{bindPoseMatrix:null,transformLinkMatrix:null,transformAssociateModelMatrix:null,clusterMode:"Unknown"},A=Ut(d,re(null!==(s=oe(m,1))&&void 0!==s?s:`Bone${g}`),void 0!==_,T,y,b,x,null!==(r=t.get(d))&&void 0!==r?r:null);o.push(...A),u.push({modelId:d,name:re(null!==(i=oe(m,1))&&void 0!==i?i:`Bone${g}`),index:g,parentIndex:h,isCluster:void 0!==_,translation:v.translation,rotation:v.rotation,preRotation:v.preRotation,postRotation:v.postRotation,rotationPivot:v.rotationPivot,scalingPivot:v.scalingPivot,rotationOffset:v.rotationOffset,scalingOffset:v.scalingOffset,scale:v.scale,rotationOrder:v.rotationOrder,inheritType:v.inheritType,clusterMode:T,bindPoseMatrix:y,transformLinkMatrix:b,transformAssociateModelMatrix:x,modelBindPoseMatrix:null!==(a=t.get(d))&&void 0!==a?a:null,diagnostics:A});for(const e of null!==(l=p.get(d))&&void 0!==l?l:[])c.has(e)||f.push({modelId:e,parentIndex:g})}return u}(d,h,n,p);if(0===f.length)return null;const{boneIndices:m,boneWeights:g}=function(e,t){let n=0;for(const o of e){const e=t.get(o.modelId);if(!e)continue;const s=te(e.clusterNode,"Indexes");if(!s)continue;const r=Ht(se(s));if(r)for(let e=0;e<r.length;e++)r[e]>n&&(n=r[e])}const o=n+1,s=new Array(o),r=new Array(o);for(let e=0;e<o;e++)s[e]=[],r[e]=[];for(const n of e){const e=t.get(n.modelId);if(!e)continue;const o=te(e.clusterNode,"Indexes"),i=te(e.clusterNode,"Weights");if(!o||!i)continue;const a=Ht(se(o)),l=Kt(se(i));if(a&&l)for(let e=0;e<a.length;e++){const t=a[e];s[t].push(n.index),r[t].push(l[e])}}for(let e=0;e<o;e++){if(0===s[e].length)continue;const t=s[e].map((t,n)=>({index:t,weight:r[e][n]}));t.sort((e,t)=>t.weight-e.weight);const n=t.slice(0,8);s[e]=n.map(e=>e.index),r[e]=n.map(e=>e.weight)}for(let e=0;e<o;e++){const t=r[e].reduce((e,t)=>e+t,0);if(t>0)for(let n=0;n<r[e].length;n++)r[e][n]/=t}return{boneIndices:s,boneWeights:r}}(f,d);return{id:e,geometryId:r,meshBindPoseMatrix:void 0!==u&&null!==(o=h.get(u))&&void 0!==o?o:null,bones:f,boneIndices:m,boneWeights:g,diagnostics:p}}function Dt(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 Vt(e){const t=oe(e,2);return"Root"===t||"LimbNode"===t}function Gt(e,t){return ve(e,null!=t?t:Pt)}function $t(e){let t=null,n=null,o=null,s="Normalize";const r=te(e,"Transform");if(r&&r.properties[0]){const e=se(r);e instanceof Float64Array&&16===e.length?t=e:e instanceof Float32Array&&16===e.length&&(t=new Float64Array(e))}const i=te(e,"TransformLink");if(i&&i.properties[0]){const e=se(i);e instanceof Float64Array&&16===e.length?n=e:e instanceof Float32Array&&16===e.length&&(n=new Float64Array(e))}const a=te(e,"TransformAssociateModel");if(a&&a.properties[0]){const e=se(a);e instanceof Float64Array&&16===e.length?o=e:e instanceof Float32Array&&16===e.length&&(o=new Float64Array(e))}const l=te(e,"Mode"),u=l?oe(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 Ut(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 Ht(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 Kt(e){return e instanceof Float64Array?e:e instanceof Float32Array?new Float64Array(e):null}function jt(e,t){var n;const o=null!==(n=function(e,t){if(0===e.length)return;const n=e.map(e=>Wt(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=qt(s,t);for(;void 0!==r;){const e=t.objects.get(r);if(!e||"Model"!==e.name||!Vt(e))break;s=r,r=qt(r,t)}return s}function Wt(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=qt(o,t)}return n}function qt(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 zt(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 Xt(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 Yt(e,t){var n;const o=t.objects.get(e);if(!o||"Model"!==o.name)return null;const s=Gt(o);return{modelId:e,name:re(null!==(n=oe(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 Qt(e,t){return e<t?-1:e>t?1:0}function Zt(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)||Qt(e,t)}const Jt=46186158e3,en=.333333,tn=1e-5,nn=new Float32Array(1),on=new Uint32Array(nn.buffer);function sn(e){return nn[0]=e,on[0]}function rn(e,t,n,o,s,r){const i=r?1:.5;return{left:i*(1-e)*(1+n)*(1-t)*o+i*(1-e)*(1-n)*(1+t)*s,right:i*(1-e)*(1+n)*(1+t)*o+i*(1-e)*(1-n)*(1-t)*s}}function an(e,t,n,o,s,r,i,a,l,u){if(4096&u&&Math.min(Math.abs(o-s),Math.abs(r-s))<=tn)return 0;let c=(r-o)/(n-e);if(!(8192&u)){const i=(s-o)/(t-e),a=(r-s)/(n-t),u=(t-e)/(n-e);c=.5*c+.5*(i*(1-u)+a*u);const d=Math.abs(l)/100;if(d>1e-4){const e=l>0?a:i,t=e-c;c=c*(1-d)+e*d;const n=d-5;if(n>0){let e=Math.abs(t)>1e-5?t:l;e=e>0?1:-1,c+=n*n*e*40}}}if(16384&u){const l=c>=0?1:-1;let u=l*c;const d=i*(t-e),h=a*(n-t);let p=d>0?l*(s-o)/d:0,f=h>0?l*(r-s)/h:0;p>0||(p=0),f>0||(f=0),u=Math.min(u,p,f),c=l*u}return c}function ln(e,t,n,o,s,r){if(16384&r)return 0;if(4096&r&&Math.abs(o-n)<=tn)return 0;let i=(o-n)/(t-e);if(!(8192&r)){const e=Math.abs(s)/100-5;e>0&&(i+=e*e*(s>0?1:-1)*40)}return i}function un(e,t,n){const o=3*e,s=3*t,r=o-s+1,i=s-o-o,a=o,l=3*r,u=2*i;let c,d=n;for(let e=0;e<11;e++){const t=d*d;c=r*(t*d)+i*t+a*d-n;const o=l*t+u*d+a;if(0===o)break;if(d-=c/o,e>=2&&Math.abs(c)<=8881784197001252e-31)break}return d}function cn(e,t){var n,o;const s=t.time-e.time;if(Number.isFinite(e.rightDx)&&Number.isFinite(e.rightDy)&&Number.isFinite(t.leftDx)&&Number.isFinite(t.leftDy)&&(e.rightDx>0||t.leftDx>0))return{rightDx:e.rightDx,rightDy:e.rightDy,leftDx:t.leftDx,leftDy:t.leftDy};const r=null!==(n=e.rightSlope)&&void 0!==n?n:0;return{rightDx:s/3,rightDy:s/3*r,leftDx:s/3,leftDy:s/3*(null!==(o=e.nextLeftSlope)&&void 0!==o?o:t.leftDx>0?t.leftDy/t.leftDx:r)}}function dn(e,t,n,o=!1){if(!e||0===e.keys.length)return n;const s=e.keys;if(1===s.length)return s[0].value;const r=s[0].time,i=s[s.length-1].time;if(!o&&(t<r||t>i))return function(e,t){var n;const o=e.keys,s=o[0].time,r=o[o.length-1].time,i=t<s,a=i?o[0]:o[o.length-1],l=null!==(n=i?e.preExtrapolation:e.postExtrapolation)&&void 0!==n?n:{mode:"constant",repeatCount:-1};if("constant"===l.mode)return a.value;if("slope"===l.mode){const e=i?a.rightDx:a.leftDx,n=i?a.rightDy:a.leftDy;return 0!==e?a.value+n*((t-a.time)/e):a.value}if(0===l.repeatCount)return a.value;const u=Jt,c=Math.round(s*u),d=Math.round(r*u),h=t*u,p=i?c-h:h-d,f=d-c;if(!(f>=1))return a.value;const m=p/f;let g=Math.floor(m),_=p-g*f;l.repeatCount>0&&g>=l.repeatCount&&(g=l.repeatCount-1,_=f),"mirror"===l.mode&&.5*g-Math.floor(.5*g)<=.25&&(_=f-_),i&&(_=f-_);let v=dn(e,(c+_)/u,a.value,!0);if("repeatRelative"===l.mode){let e=o[o.length-1].value-o[0].value;i&&(e=-e),v+=e*(g+1)}return v}(e,t);let a=0,l=s.length;for(;l-a>=8;){const e=a+l>>1;s[e].time<=t?a=e+1:l=e}for(l=s.length;a<l;a++){const e=s[a];if(e.time<=t)continue;if(0===a)return e.value;const n=s[a-1];if(n.time===t)return n.value;const o=1/(e.time-n.time);let r=(t-n.time)*o;switch(n.interpolation){case"constant":return"next"===n.constantMode?e.value:n.value;case"linear":return n.value*(1-r)+e.value*r;default:{const t=cn(n,e);r=un(t.rightDx*o,1-t.leftDx*o,r);const s=r*r,i=s*r,a=1-r,l=a*a,u=l*a,c=n.value,d=e.value;return u*c+3*(l*r*(c+t.rightDy)+a*s*(d-t.leftDy))+i*d}}}return s[s.length-1].value}const hn=Math.PI/180,pn=180/Math.PI;function fn(e,t){const n=e[0]*(.5*hn),o=e[1]*(.5*hn),s=e[2]*(.5*hn),r=Math.cos(n),i=Math.sin(n),a=Math.cos(o),l=Math.sin(o),u=Math.cos(s),c=Math.sin(s);switch(t){case 1:return[r*l*c+a*u*i,r*u*l+a*i*c,r*a*c-u*i*l,r*a*u-i*l*c];case 2:return[-r*l*c+a*u*i,r*u*l-a*i*c,r*a*c+u*i*l,r*a*u+i*l*c];case 3:return[-r*l*c+a*u*i,r*u*l+a*i*c,r*a*c+u*i*l,r*a*u-i*l*c];case 4:return[r*l*c+a*u*i,r*u*l-a*i*c,r*a*c-u*i*l,r*a*u+i*l*c];case 5:return[r*l*c+a*u*i,r*u*l-a*i*c,r*a*c+u*i*l,r*a*u-i*l*c];default:return[-r*l*c+a*u*i,r*u*l+a*i*c,r*a*c-u*i*l,r*a*u+i*l*c]}}function mn(e,t){const n=.999999999,[o,s,r,i]=e;let a,l=0,u=0,c=0;const d=.5*Math.PI;switch(t){case 1:a=2*(i*r+o*s),Math.abs(a)<n?(c=Math.asin(a),u=Math.atan2(2*(i*s-o*r),2*(i*i+o*o)-1),l=-Math.atan2(-2*(i*o-s*r),2*(i*i+s*s)-1)):(c=Math.sign(a)*d,u=Math.atan2(2*a*(i*o+s*r),-a*(2*o*s-2*i*r)));break;case 2:a=2*(i*r-o*s),Math.abs(a)<n?(c=Math.asin(a),l=Math.atan2(2*(i*o+s*r),2*(i*i+s*s)-1),u=-Math.atan2(-2*(i*s+o*r),2*(i*i+o*o)-1)):(c=Math.sign(a)*d,l=Math.atan2(-2*a*(i*s-o*r),a*(2*i*r+2*o*s)));break;case 3:a=2*(i*o+s*r),Math.abs(a)<n?(l=Math.asin(a),c=Math.atan2(2*(i*r-o*s),2*(i*i+s*s)-1),u=-Math.atan2(-2*(i*s-o*r),2*(i*i+r*r)-1)):(l=Math.sign(a)*d,c=Math.atan2(2*a*(i*s+o*r),-a*(2*s*r-2*i*o)));break;case 4:a=2*(i*o-s*r),Math.abs(a)<n?(l=Math.asin(a),u=Math.atan2(2*(i*s+o*r),2*(i*i+r*r)-1),c=-Math.atan2(-2*(i*r+o*s),2*(i*i+s*s)-1)):(l=Math.sign(a)*d,u=Math.atan2(-2*a*(i*r-o*s),a*(2*i*o+2*s*r)));break;case 5:a=2*(i*s+o*r),Math.abs(a)<n?(u=Math.asin(a),l=Math.atan2(2*(i*o-s*r),2*(i*i+r*r)-1),c=-Math.atan2(-2*(i*r-o*s),2*(i*i+o*o)-1)):(u=Math.sign(a)*d,l=Math.atan2(2*a*(i*r+o*s),-a*(2*o*r-2*i*s)));break;default:a=2*(i*s-o*r),Math.abs(a)<n?(u=Math.asin(a),c=Math.atan2(2*(i*r+o*s),2*(i*i+o*o)-1),l=-Math.atan2(-2*(i*o+s*r),2*(i*i+r*r)-1)):(u=Math.sign(a)*d,c=Math.atan2(-2*a*(i*o-s*r),a*(2*i*s+2*o*r)))}return[l*pn,u*pn,c*pn]}function gn(e,t,n){let o,s,r=e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],i=t[0],a=t[1],l=t[2],u=t[3];if(r<0&&(r=-r,i=-i,a=-a,l=-l,u=-u),r>.9995)o=1-n,s=n;else{const e=Math.acos(Math.min(1,r)),t=1/Math.sin(e);o=Math.sin((1-n)*e)*t,s=Math.sin(n*e)*t}const c=e[0]*o+i*s,d=e[1]*o+a*s,h=e[2]*o+l*s,p=e[3]*o+u*s,f=Math.hypot(c,d,h,p)||1;return[c/f,d/f,h/f,p/f]}function _n(e,t){return e>=0?Math.pow(e,t):-Math.pow(-e,t)}function vn(e,t,n,o,s){const r=n.weight;if(n.additive)return n.composeScale&&"S"===o?[e[0]*_n(t[0],r),e[1]*_n(t[1],r),e[2]*_n(t[2],r)]:n.composeRotation&&"R"===o?mn((i=fn(e,s),a=gn([0,0,0,1],fn(t,s),r),[i[3]*a[0]+i[0]*a[3]+i[1]*a[2]-i[2]*a[1],i[3]*a[1]-i[0]*a[2]+i[1]*a[3]+i[2]*a[0],i[3]*a[2]+i[0]*a[1]-i[1]*a[0]+i[2]*a[3],i[3]*a[3]-i[0]*a[0]-i[1]*a[1]-i[2]*a[2]]),s):[e[0]+t[0]*r,e[1]+t[1]*r,e[2]+t[2]*r];var i,a;if(n.blended){const i=1-r;return n.composeScale&&"S"===o?[_n(e[0],i)*_n(t[0],r),_n(e[1],i)*_n(t[1],r),_n(e[2],i)*_n(t[2],r)]:n.composeRotation&&"R"===o?mn(gn(fn(e,s),fn(t,s),r),s):[e[0]*i+t[0]*r,e[1]*i+t[1]*r,e[2]*i+t[2]*r]}return[t[0],t[1],t[2]]}function yn(e,t,n,o){var s,r;const i=re(null!==(s=oe(t,1))&&void 0!==s?s:"Animation"),a=function(e){var t,n,o,s;const r=te(e,"Properties70");if(!r)return null;let i=0,a=null;for(const e of r.children){if("P"!==e.name)continue;const r=oe(e,0);"LocalStart"===r||"ReferenceStart"===r?i=null!==(n=Fn(null===(t=e.properties[4])||void 0===t?void 0:t.value))&&void 0!==n?n:i:"LocalStop"!==r&&"ReferenceStop"!==r||(a=null!==(s=Fn(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),l=ye(n,e,"AnimationLayer");if(0===l.length)return null;const u=[],c=[],d=[],h=[];let p=1/0,f=-1/0;for(const{id:e,node:t}of l){const o=re(null!==(r=oe(t,1))&&void 0!==r?r:"Layer");let s=100,i=0,a=0,l=0;for(const e of pe(t)){const t=e.values[0];"number"==typeof t&&("Weight"===e.name?s=t:"BlendMode"===e.name?i=t:"RotationAccumulationMode"===e.name?a=t:"ScaleAccumulationMode"===e.name&&(l=t))}const m=d.length,g=ye(n,e,"AnimationCurveNode"),_=[],v=[],y=[];let b;for(const{id:t,node:s}of g){const r=xn(t,s,n,m);if(!r){const r=Tn(t,s,n,m);if(r){if(r.targetId===e&&"Weight"===r.propertyName&&r.curves.length>0){b=r.curves[0];continue}An(r.curves,e=>{e<p&&(p=e),e>f&&(f=e)}),v.push(r),c.push(r);const n={type:"unsupported-curve-node",message:`AnimationCurveNode '${r.type}' is preserved as diagnostic data but not evaluated at runtime.`,layerName:o,curveNodeId:t,curveNodeType:r.type,targetId:r.targetId,propertyName:r.propertyName};y.push(n),h.push(n)}continue}for(const e of r.curves)for(const t of e.keys)t.time<p&&(p=t.time),t.time>f&&(f=t.time);_.push(r),u.push(r)}d.push({name:o,weight:s,normalizedWeight:s/100,blendMode:i,blend:Cn(i,s,a,l),weightCurve:b,curveNodes:_,unsupportedCurveNodes:v,diagnostics:y})}return 0===u.length&&0===c.length?null:bn(i,d,u,c,h,p,f,a,o)}function bn(e,t,n,o,s,r,i,a,l){const u=isFinite(r)&&isFinite(i),c=l&&u&&r>0?r:0;if(c>0){for(const e of n)for(const t of e.curves)for(const e of t.keys)e.time-=c;for(const e of o)for(const t of e.curves)for(const e of t.keys)e.time-=c;i-=c}const d=a?l?Math.max(a.start-c,0):a.start:0,h=a?Math.max(a.stop-c,d):0,p=h>d,f=u?r-c:0,m=u?i:0,g=p?d:l?Math.min(0,f):f,_=p?h:Math.max(m,g);return{name:e,startTime:g,stopTime:_,duration:Math.max(_-g,0),curveNodes:n,layers:t,unsupportedCurveNodes:o,diagnostics:s}}function xn(e,t,n,o){var s,r,i,a;const l=re(null!==(s=oe(t,1))&&void 0!==s?s:""),u=Mn(t),c="d|X"in u||"d|Y"in u||"d|Z"in u?[null!==(r=u["d|X"])&&void 0!==r?r:0,null!==(i=u["d|Y"])&&void 0!==i?i:0,null!==(a=u["d|Z"])&&void 0!==a?a:0]:void 0;if("T"===l||"R"===l||"S"===l){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 s=wn(e,n);return 0!==s.length||c?{type:l,targetModelId:t,curves:s,layerIndex:o,defaultValues:c}:null}const d=function(e,t){var n;for(const o of t.connections){if(o.childId!==e||"OP"!==o.type||!o.propertyName)continue;const s=t.objects.get(o.parentId);if(s&&"Geometry"===s.name)for(const e of ye(t,o.parentId,"Deformer"))if("BlendShape"===oe(e.node,2))for(const s of ye(t,e.id,"Deformer"))if("BlendShapeChannel"===oe(s.node,2)&&re(null!==(n=oe(s.node,1))&&void 0!==n?n:"")===o.propertyName)return s.id}return null}(e,n);if(null!==d){const t=wn(e,n);return 0===t.length?null:{type:"DeformPercent",targetModelId:d,curves:t,layerIndex:o,defaultValues:c}}if("DeformPercent"===l){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"===oe(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"===oe(e,2))return n.parentId}return null}(e,n);if(null===t)return null;const s=wn(e,n);return 0===s.length?null:{type:"DeformPercent",targetModelId:t,curves:s,layerIndex:o,defaultValues:c}}return null}function Tn(e,t,n,o){var s;const r=re(null!==(s=oe(t,1))&&void 0!==s?s:""),i=wn(e,n),a=Mn(t);if(0===i.length&&0===Object.keys(a).length)return null;let l,u=null;for(const t of n.connections)if(t.childId===e&&"OP"===t.type){u=t.parentId,l=t.propertyName;break}return{type:r,id:e,layerIndex:o,targetId:u,propertyName:l,curveCount:i.length,curves:i,defaultValues:a}}function An(e,t){for(const n of e)for(const e of n.keys)t(e.time)}function wn(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=Sn(e);i.length>0&&o.push(Object.assign({channel:r,keys:i},Rn(e)))}if(0===o.length){const n=ye(t,e,"AnimationCurve"),s=["d|X","d|Y","d|Z"];for(let e=0;e<n.length&&e<3;e++){const t=Sn(n[e].node);t.length>0&&o.push(Object.assign({channel:s[e],keys:t},Rn(n[e].node)))}}return o}function Mn(e){var t,n;const o={},s=te(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=oe(e,0);if(!(null==t?void 0:t.startsWith("d|")))continue;const s=En(null===(n=e.properties[4])||void 0===n?void 0:n.value);null!==s&&(o[t]=s)}return o}function Sn(e){const t=te(e,"KeyTime"),n=te(e,"KeyValueFloat");if(!t||!n)return[];const o=(l=se(t))instanceof Float64Array?l:null,s=Nn(se(n)),r=On(se(te(e,"KeyAttrFlags"))),i=Nn(se(te(e,"KeyAttrDataFloat"))),a=On(se(te(e,"KeyAttrRefCount")));var l;if(!o||!s)return[];if(o.length!==s.length)return[];const u=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))}(o.length,r,a);return function(e,t,n){const o=Math.min(e.length,t.length),s=[];if(0===o)return s;let r=0,i=en,a=0,l=Number(e[0])/Jt;for(let u=0;u<o;u++){const c=l,d=t[u];u+1<o&&(l=Number(e[u+1])/Jt);const h=u>0?t[u-1]:d,p=u+1<o?t[u+1]:d,f=n(u),m=f.flags;let g,_=f.data[0],v=en,y=f.data[1],b=en;if(50331648&m){const e=sn(f.data[2]);16777216&m&&(v=1e-4*(65535&e)),33554432&m&&(b=1e-4*(e>>>16))}let x="standard";if(2&m)g="constant",x=256&m?"next":"standard",v=b=en,_=y=0;else if(8&m)if(g="cubic",512&m){let e=0,t=0,n=!1;u>0&&c>a?e=(d-h)/(c-a):n=!0,u+1<o&&l>c?t=(p-d)/(l-c):n=!0;const s=rn(f.data[0],f.data[1],f.data[2],e,t,n);r=s.left,_=s.right,y=0,b=en}else 1024&m||(u>0&&u+1<o&&c>a&&l>c?Math.abs(r+_)<=1e-4?r=_=an(a,c,l,h,d,p,i,v,_,m):(r=an(a,c,l,h,d,p,i,v,-r,m),_=an(a,c,l,h,d,p,i,v,_,m)):r=_=u>0&&c>a?ln(a,c,h,d,-r,m):u+1<o&&l>c?ln(c,l,d,p,_,m):0);else{g="linear",v=en,b=en;const e=l-c;_=y=e>0?(p-d)/e:0}const T={time:c,value:d,interpolation:g,constantMode:x,leftDx:0,leftDy:0,rightDx:0,rightDy:0};c>a&&(T.leftDx=i*(c-a),T.leftDy=T.leftDx*r),l>c&&(T.rightDx=v*(l-c),T.rightDy=T.rightDx*_),T.rightSlope=_,s.push(T),r=y,i=b,a=c}for(let e=0;e+1<s.length;e++){const t=s[e+1];s[e].nextLeftSlope=t.leftDx>0?t.leftDy/t.leftDx:0}return s}(o,s,e=>{var t,n,o,s,a;const l=u[e],c=4*l;return{flags:l>=0&&null!==(t=null==r?void 0:r[l])&&void 0!==t?t:0,data:[null!==(n=Ln(i,c))&&void 0!==n?n:0,null!==(o=Ln(i,c+1))&&void 0!==o?o:0,null!==(s=Ln(i,c+2))&&void 0!==s?s:0,null!==(a=Ln(i,c+3))&&void 0!==a?a:0]}})}function Rn(e){const t=t=>{var n,o,s,r;const i=te(e,t);return function(e,t){const n="string"==typeof e?e.charCodeAt(0):"number"==typeof e?e:0;let o;switch(String.fromCharCode(n)){case"A":o="repeatRelative";break;case"K":o="slope";break;case"M":o="mirror";break;case"R":o="repeat";break;default:o="constant"}let s="number"==typeof t?t:-1;return s<0&&(s=-1),{mode:o,repeatCount:s}}(null===(o=null===(n=te(null!=i?i:e,"Type"))||void 0===n?void 0:n.properties[0])||void 0===o?void 0:o.value,null===(r=null===(s=te(null!=i?i:e,"Repetition"))||void 0===s?void 0:s.properties[0])||void 0===r?void 0:r.value)};return{preExtrapolation:t("Pre-Extrapolation"),postExtrapolation:t("Post-Extrapolation")}}function Cn(e,t,n,o){let s=!1,r=!1;switch(e){case 0:s=!0,r=!0;break;case 2:s=!0}let i=t/100;return i<0&&(i=0),i>.99999&&(i=1),{blended:s,additive:r,composeRotation:0===n,composeScale:0===o,weight:i}}function In(e,t){return e&&0!==e.keys.length?dn(e,t,e.keys[0].value):null}function On(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 Fn(e){return"number"==typeof e?e/Jt:null}function En(e){return"number"==typeof e?e:null}function Nn(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 Ln(e,t){if(!e||t<0||t>=e.length)return;const n=e[t];return Number.isFinite(n)?n:void 0}const kn=new Set(["Color","Intensity","OuterAngle","InnerAngle","ConeAngle","HotSpot","FieldOfView","FieldOfViewX","FieldOfViewY","FocalLength","NearPlane","FarPlane","OrthoZoom","Roll","FilmWidth","FilmHeight"]);function Pn(e,t,n){var o;const s=n.endsWith(" (Shape)")?n.slice(0,-8):n;for(const n of ye(e,t,"Geometry"))for(const t of ye(e,n.id,"Deformer"))if("BlendShape"===oe(t.node,2))for(const n of ye(e,t.id,"Deformer"))if("BlendShapeChannel"===oe(n.node,2)&&re(null!==(o=oe(n.node,1))&&void 0!==o?o:"")===s)return n.id}function Bn(e){var t,n;if(!e)return null;const o=Fn(null===(t=e.properties[0])||void 0===t?void 0:t.value),s=Fn(null===(n=e.properties[1])||void 0===n?void 0:n.value);return null!==o&&null!==s?{start:o,stop:s}:null}function Dn(e,t){var n;const o=e=>e.children.some(e=>"Key"===e.name||"Default"===e.name);if(o(e)){const n=Vn(e,t);return n.length>0?[Object.assign({channel:"d|X",keys:n},Rn(e))]:[]}const s=[];for(const r of e.children){if("Channel"!==r.name||!o(r))continue;const e=null!==(n=oe(r,0))&&void 0!==n?n:"X",i=Vn(r,t);if(i.length>0&&s.push(Object.assign({channel:`d|${e}`,keys:i},Rn(r))),3===s.length)break}return s}function Vn(e,t){var n,o,s,r,i,a;const l=te(e,"Key");if(!l)return[];const u=l.properties.map(e=>e.value),c=e=>"number"==typeof e?e:"boolean"==typeof e?e?1:0:NaN,d=e=>"string"==typeof e?e:"number"==typeof e?String.fromCharCode(e):"boolean"==typeof e?e?"":"\0":"?";let h=null!==(s=En(null===(o=null===(n=te(e,"KeyVer"))||void 0===n?void 0:n.properties[0])||void 0===o?void 0:o.value))&&void 0!==s?s:0;h<=0&&(h=t<5e3?4003:t<6e3?4004:4005);const p=null!==(a=En(null===(i=null===(r=te(e,"KeyCount"))||void 0===r?void 0:r.properties[0])||void 0===i?void 0:i.value))&&void 0!==a?a:0,f=[],m=[],g=[],_=[],v=[],y=[],b=[],x=[],T=[];let A=0,w=1/3,M=0;for(let e=0;e<p&&!(M+3>u.length);e++){const e=c(u[M])/Jt,t=c(u[M+1]),n=d(u[M+2]);M+=3;let o=0,s=0,r=1/3,i=1/3,a=!1,l="cubic",p=!1;if("U"===n){const e=d(u[M]);M+=1;let t=1;if("s"===e||"b"===e)o=c(u[M]),s=c(u[M+1]),M+=2,4003===h&&(t=0);else if("a"===e)a=!0,h<=4004&&(t=0);else if("p"===e||"q"===e)a=!0,M+=2,t=h<=4004?1:2;else if("t"===e)a=!0,M+=3,t=0;else{if("d"!==e)break;a=!0,M+=1}for(;t>0;t--){const e=d(u[M]);if(M+=1,"n"===e||"c"===e);else if("a"===e)r=c(u[M]),i=c(u[M+1]),M+=2;else if("l"===e)i=c(u[M]),M+=1;else{if("r"!==e){M=u.length;break}r=c(u[M]),M+=1}}}else if("L"===n)l="linear";else{if("C"!==n)break;l="constant",h>=4004&&(p="n"===d(u[M]),M+=1)}f.push(e),m.push(t),g.push(l),_.push(p),v.push(A),y.push(o),b.push(w),x.push(r),T.push(a),A=s,w=i}for(let e=0;e<f.length;e++){if(T[e]){const t=e>0&&e+1<f.length?Gn(f[e-1],f[e],f[e+1],m[e-1],m[e],m[e+1],b[e],x[e]):0;v[e]=t,y[e]=t}if("linear"===g[e]&&e+1<f.length){const t=f[e+1]-f[e],n=t>0?(m[e+1]-m[e])/t:0;y[e]=n,T[e+1]||(v[e+1]=n)}}return function(e,t,n,o,s,r,i,a){var l,u;const c=[];for(let d=0;d<e.length;d++){const h={time:e[d],value:t[d],interpolation:n[d],constantMode:o[d]?"next":"standard",leftDx:0,leftDy:0,rightDx:0,rightDy:0,rightSlope:r[d],nextLeftSlope:d+1<e.length?s[d+1]:void 0};d>0&&e[d]>e[d-1]&&(h.leftDx=(null!==(l=null==i?void 0:i[d])&&void 0!==l?l:en)*(e[d]-e[d-1]),h.leftDy=h.leftDx*s[d]),d+1<e.length&&e[d+1]>e[d]&&(h.rightDx=(null!==(u=null==a?void 0:a[d])&&void 0!==u?u:en)*(e[d+1]-e[d]),h.rightDy=h.rightDx*r[d]),c.push(h)}return c}(f,m,g,_,v,y,b,x)}function Gn(e,t,n,o,s,r,i,a){if(!(n>e))return 0;const l=(r-o)/(n-e),u=l>=0?1:-1;let c=u*l;const d=i*(t-e),h=a*(n-t);let p=d>0?u*(s-o)/d:0,f=h>0?u*(r-s)/h:0;return p>0||(p=0),f>0||(f=0),c=Math.min(c,p,f),u*c}function $n(e,t,n,o,s,r){var i;let a=[o[0],o[1],o[2]];for(let o=0;o<Math.max(t.length,1);o++){const l=e.find(e=>e.type===n&&e.layerIndex===o);if(!l)continue;const u=null!==(i=l.defaultValues)&&void 0!==i?i:a,c=[dn(l.curves.find(e=>"d|X"===e.channel),r,u[0]),dn(l.curves.find(e=>"d|Y"===e.channel),r,u[1]),dn(l.curves.find(e=>"d|Z"===e.channel),r,u[2])],d=t[o];if(0!==o&&d){let e=d.blend;if(d.weightCurve&&e.blended){let t=dn(d.weightCurve,r,d.weight)/100;t=t<0?0:t>.99999?1:t,e=Object.assign(Object.assign({},e),{weight:t})}a=vn(a,c,e,n,s)}else a=c}return a}function Un(e,t,n,o,s){const r=n.map((e,t)=>{var n;return null!==(n=o[t])&&void 0!==n?n:0});for(let o=0;o<Math.max(t.length,1);o++){const i=e.find(e=>e.layerIndex===o);if(!i)continue;const a=n.map((e,t)=>{var n,o;return dn(i.curves.find(t=>t.channel===e),s,null!==(o=null===(n=i.defaultValues)||void 0===n?void 0:n[e])&&void 0!==o?o:r[t])}),l=t[o];if(0===o||!l){for(let e=0;e<r.length;e++)r[e]=a[e];continue}let u=l.blend;if(l.weightCurve&&u.blended){let e=dn(l.weightCurve,s,l.weight)/100;e=e<0?0:e>.99999?1:e,u=Object.assign(Object.assign({},u),{weight:e})}for(let e=0;e<r.length;e++)r[e]=vn([r[e],0,0],[a[e],0,0],u,"other",0)[0]}return r}function Hn(e,t,n){let o=!1;for(const s of e)if(s.type===t)for(const e of s.curves){const t=e.keys;if(t.length<2)continue;if(o=!0,n<t[0].time||n>=t[t.length-1].time)return!1;let s=0;for(;s+1<t.length&&t[s+1].time<=n;)s++;if("constant"!==t[s].interpolation)return!1}return o}function Kn(e,t,n){var o;const s=n.parentOf.get(e);if(!s)return null;const r=n.objects.get(s.id);if(!r||"Geometry"!==r.name)return null;const i=s.id,a=[],l=ye(n,e,"Deformer");for(const{id:e,node:t}of l){if("BlendShapeChannel"!==oe(t,2))continue;const s=re(null!==(o=oe(t,1))&&void 0!==o?o:"MorphTarget");let r=0;for(const e of pe(t))"DeformPercent"===e.name&&"number"==typeof e.values[0]&&(r=e.values[0]);const i=jn(t),l=[],u=ye(n,e,"Geometry");for(const{node:e}of u){if("Shape"!==oe(e,2))continue;const t=zn(e);t&&l.push(t)}if(l.length>0){const t=[],n=Wn(i,l,e,s,t);a.push({name:s,id:e,deformPercent:r,shapes:qn(l,n),fullWeights:n?[...n].sort((e,t)=>e-t):null,diagnostics:t})}}return 0===a.length?null:{id:e,geometryId:i,channels:a}}function jn(e){const t=se(te(e,"FullWeights"));return t&&(t instanceof Float64Array||t instanceof Float32Array||t instanceof Int32Array)?Array.from(t,e=>Number(e)):null}function Wn(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 qn(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 zn(e){const t=te(e,"Indexes"),n=te(e,"Vertices");if(!t||!n)return null;const o=se(t),s=se(n);if(!o||!s)return null;const r=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}(o);if(!r)return null;let i;if(s instanceof Float64Array)i=s;else{if(!(s instanceof Float32Array))return null;i=new Float64Array(s)}let a=null;const l=te(e,"Normals");if(l){const e=se(l);e instanceof Float64Array?a=e:e instanceof Float32Array&&(a=new Float64Array(e))}return{indices:r,vertices:i,normals:a}}const Xn=new Set(["Character","CharacterPose","ControlSet","ControlSetPlug"]),Yn=new Set(["Camera","Light","Null","LodGroup","LimbNode","Limb","Root","Skeleton","Marker","CameraSwitcher","Mesh","NurbsCurve","NurbsSurface","TrimNurbsSurface","Line","Boundary"]);function Qn(e){return"Skin"===e||"Cluster"===e||"BlendShape"===e||"BlendShapeChannel"===e}function Zn(e,t,n,o,s){var r,i,a,l;return{type:o,message:s,objectId:t,objectName:re(null!==(r=oe(n,1))&&void 0!==r?r:n.name),nodeName:n.name,subType:null!==(i=oe(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 Jn(e,t,n){const o=ye(e,t,"Deformer").map(e=>{var t;return null!==(t=oe(e.node,2))&&void 0!==t?t:""}).filter(e=>"Skin"===e||"BlendShape"===e);0!==o.length&&n.diagnostics.push({type:"nurbs-deformer-ignored",message:`${Array.from(new Set(o)).join(" and ")} deformer on NURBS surface '${n.name}' is ignored: the tessellated mesh has no control point mapping.`})}function eo(e,t={}){var n;(function(e){return!ne(e,"Objects")&&e.nodes.some(e=>"Model"===e.name)})(e)&&(e=function(e){var t,n,o,s,r,i,a;const l=et(te(null!==(t=ne(e,"FBXHeaderExtension"))&&void 0!==t?t:Ye("x"),"FBXVersion")),u=Math.max(e.version,null!=l?l:0),c={version:u,objects:[],connections:[],usedNames:new Map,takeDefaults:new Map},d=ne(e,"Takes");for(const e of null!==(n=null==d?void 0:d.children)&&void 0!==n?n:[])if("Take"===e.name)for(const t of e.children){if("Model"!==t.name)continue;const e=oe(t,0),n=t.children.find(e=>"Channel"===e.name&&"Transform"===oe(e,0));e&&n&&!c.takeDefaults.has(e)&&c.takeDefaults.set(e,n)}const h=e.nodes.filter(e=>"Model"===e.name);for(const e of h)ut(c,e);const p=[];for(const e of h){const t=e.children.filter(e=>"Channel"===e.name&&rt(e));t.length>0&&p.push(Ye("Model",[qe(null!==(o=oe(e,0))&&void 0!==o?o:"")],t))}let f=d;if(p.length>0){const e=Ye("Take",[qe("(internal)")],p);f=d?Ye("Takes",d.properties,[...d.children,e]):Ye("Takes",[],[e])}const m=null!==(s=ne(e,"Settings"))&&void 0!==s?s:te(null!==(r=ne(e,"Version5"))&&void 0!==r?r:Ye("x"),"Settings"),g=m?te(m,"FrameRate"):void 0,_=null===(i=null==g?void 0:g.properties[0])||void 0===i?void 0:i.value,v="number"==typeof _?_:"string"==typeof _?Number.parseFloat(_):NaN,y=[];let b=!1;if(Number.isFinite(v)&&v>0){const t=ne(e,"GlobalSettings");if(t){const e=te(t,"Properties70"),n=null!==(a=null!=e?e:te(t,"Properties60"))&&void 0!==a?a:Ye("Properties60"),o=e?Ze:Qe,s=n.children.some(e=>"TimeMode"===oe(e,0))?[]:[o("TimeMode","enum","",14),o("CustomFrameRate","double","",v)],r=t.children.filter(e=>e!==n);y.push(Ye("GlobalSettings",t.properties,[...r,Ye(n.name,n.properties,[...n.children,...s])]))}else y.push(Ye("GlobalSettings",[],[Ye("Version",[Xe(1e3)]),Ye("Properties60",[],[Qe("TimeMode","enum","",14),Qe("CustomFrameRate","double","",v)])]));b=!0}const x=[...e.nodes.filter(e=>"Model"!==e.name&&"Takes"!==e.name&&"Settings"!==e.name&&("GlobalSettings"!==e.name||!b)),...y,Ye("Objects",[],c.objects),Ye("Connections",[],c.connections)];return f&&x.push(f),Object.assign(Object.assign({},e),{version:u,nodes:x})}(e));const o=function(e){var t,n,o,s,r;const i=new Map,a=[],l=new Map,u=new Map,c=[],d=[],h=[],p=new Map,f=new Map,m=new Map,g=new Map,_=ne(e,"Objects"),v=ne(e,"Connections"),y=new Set,b=e=>{const t=null==e?void 0:e.value;"number"==typeof t&&Number.isSafeInteger(t)&&y.add(t)};for(const e of null!==(t=null==_?void 0:_.children)&&void 0!==t?t:[])b(e.properties[0]);for(const e of null!==(n=null==v?void 0:v.children)&&void 0!==n?n:[])b(e.properties[1]),b(e.properties[2]),b(e.properties[3]);let x=-1;const T=()=>{for(;y.has(x);)x--;const e=x--;return y.add(e),e},A=new Map,w=e=>{if(e){if(void 0!==e.raw){let t=A.get(e.raw);return void 0===t&&(t=T(),A.set(e.raw,t)),t}return function(e){if("number"==typeof e&&Number.isFinite(e)&&Number.isInteger(e))return e}(e.value)}},M=e=>{const t=w(e);if(void 0!==t)return t;const n=null==e?void 0:e.value;if("string"!=typeof n)return;const o=p.get(n);if(void 0!==o)return o;const s=re(n);return"Scene"===s?0:f.get(s)},S=e=>{let t=p.get(e);if(void 0===t){t=T(),p.set(e,t);const n=re(e);f.has(n)||f.set(n,t)}return t},R=(e,t)=>{let n=m.get(e);n||(n=new Map,m.set(e,n));let o=n.get(t);return void 0===o&&(o=T(),n.set(t,o)),o},C=(e,t,n)=>{var o;const s=e.children.filter(e=>"Shape"===e.name);if(0===s.length)return;const r=R("BlendShape",n),d=xe("Deformer",r,`Deformer::${re(n)}`,"BlendShape",[be(100)]);i.set(r,d),a.push({id:r,node:d,source:"legacySyntheticBlendShape",legacyName:n,synthetic:!0}),Te(c,l,u,h,"OO",r,t);for(const e of s){const t=re(null!==(o=oe(e,0))&&void 0!==o?o:"Shape"),s=R("BlendShapeChannel",`${n}|${t}`),d=xe("Deformer",s,`SubDeformer::${t}`,"BlendShapeChannel",[be(100),{name:"DeformPercent",properties:[{type:"float64",value:0}],children:[]},{name:"Properties60",properties:[],children:[{name:"Property",properties:[{type:"string",value:"DeformPercent"},{type:"string",value:"Number"},{type:"string",value:"A"},{type:"float64",value:0}],children:[]}]}]);i.set(s,d),a.push({id:s,node:d,source:"legacySyntheticBlendShape",legacyName:`${n}|${t}`,synthetic:!0}),Te(c,l,u,h,"OO",s,r);const p=R("Shape",`${n}|${t}`),f=xe("Geometry",p,`Geometry::${t}`,"Shape",e.children);i.set(p,f),a.push({id:p,node:f,source:"legacySyntheticBlendShape",legacyName:`${n}|${t}`,synthetic:!0}),Te(c,l,u,h,"OO",p,s)}};if(_)for(const e of _.children){const t=e.properties[0];if(t){const n=w(t);if(void 0!==n)i.set(n,e),a.push({id:n,node:e,source:"Objects",synthetic:!1}),"Geometry"===e.name&&"Mesh"===oe(e,2)&&C(e,n,String(n));else if("string"==typeof t.value){const n=t.value,o=S(n),s=Ae(e,o);i.set(o,s),a.push({id:o,node:s,source:"Objects",legacyName:n,synthetic:!1});const r="Model"===e.name?oe(e,1):void 0;if("Mesh"===r){const t=R("Geometry",n),s=we(e,t);i.set(t,s),a.push({id:t,node:s,source:"legacySyntheticGeometry",legacyName:n,synthetic:!0}),Te(c,l,u,h,"OO",t,o),g.set(o,t),C(e,t,n)}else if("Light"===r||"Camera"===r){const t=R("NodeAttribute",n),s=xe("NodeAttribute",t,`NodeAttribute::${re(n)}`,r,e.children);i.set(t,s),a.push({id:t,node:s,source:"legacySyntheticAttribute",legacyName:n,synthetic:!0}),Te(c,l,u,h,"OO",t,o)}}}}if(v)for(const e of v.children){if("C"!==e.name&&"Connect"!==e.name)continue;const t=d.length;let n,a=oe(e,0),p=e.properties[1],f=e.properties[2];"PO"===a&&"string"==typeof(null===(o=e.properties[2])||void 0===o?void 0:o.value)&&e.properties.length>3&&(a="OP",n=e.properties[2].value,p=e.properties[3],f=e.properties[1]);const m={source:e.name,rawType:a,accepted:!1};if(d.push(m),"OO"!==a&&"OP"!==a){const e=M(p),n=M(f);h.push({reason:"unsupported-connection-type",message:`Unsupported FBX connection type '${null!=a?a:""}' was not added to the graph.`,connectionIndex:t,type:a,childId:e,parentId:n});continue}if(void 0===p||void 0===f){h.push({reason:"missing-connection-endpoint",message:"FBX connection is missing a child or parent endpoint.",connectionIndex:t,type:a});continue}const _=M(p);let v=M(f);if(void 0!==_&&void 0!==v&&"Deformer"===(null===(s=i.get(_))||void 0===s?void 0:s.name)&&(v=null!==(r=g.get(v))&&void 0!==r?r:v),void 0===_||void 0===v){h.push({reason:"unresolved-legacy-endpoint",message:"FBX connection references a legacy string endpoint that is not present in the object table.",connectionIndex:t,type:a});continue}const y=null!=n?n:"OP"===a&&e.properties.length>3?oe(e,3):void 0;m.childId=_,m.parentId=v,m.propertyName=y,_===v&&h.push({reason:"self-loop",message:"FBX connection references the same object as child and parent.",connectionIndex:t,type:a,childId:_,parentId:v,propertyName:y}),i.has(_)||h.push({reason:"unresolved-object-reference",message:"FBX connection child ID is not present in the object table.",connectionIndex:t,type:a,childId:_,parentId:v,propertyName:y}),0===v||i.has(v)||h.push({reason:"unresolved-object-reference",message:"FBX connection parent ID is not present in the object table.",connectionIndex:t,type:a,childId:_,parentId:v,propertyName:y}),Te(c,l,u,h,a,_,v,y,t),m.accepted=!0}return{objects:i,objectEntries:a,childrenOf:l,parentOf:u,connections:c,connectionEntries:d,diagnostics:h}}(e),s=function(e){const t=new Map,n=ne(e,"Definitions");if(!n)return t;for(const e of n.children){if("ObjectType"!==e.name)continue;const n=oe(e,0);if(n)for(const o of e.children){if("PropertyTemplate"!==o.name)continue;const e=oe(o,0);if(!e)continue;const s=he(n,e,o);let r=t.get(n);r||(r=new Map,t.set(n,r)),r.set(e,s)}}return t}(e),r=function(e){var t;const n={upAxis:1,upAxisSign:1,frontAxis:2,frontAxisSign:1,coordAxis:0,coordAxisSign:1,unitScaleFactor:1,frameRate:30},o=ne(e,"GlobalSettings");if(!o)return n;let s=0,r=24;for(const{name:e,values:t}of pe(o)){const o=ao(t[0]);if(e&&void 0!==o)switch(e){case"UpAxis":n.upAxis=o;break;case"UpAxisSign":n.upAxisSign=o;break;case"FrontAxis":n.frontAxis=o;break;case"FrontAxisSign":n.frontAxisSign=o;break;case"CoordAxis":n.coordAxis=o;break;case"CoordAxisSign":n.coordAxisSign=o;break;case"UnitScaleFactor":n.unitScaleFactor=o;break;case"TimeMode":s=o;break;case"CustomFrameRate":r=o}}return n.frameRate=14===s?r>0?r:24:null!==(t=oo[s])&&void 0!==t?t:30,n}(e),i=[];for(const[e,t]of Array.from(o.objects))"Material"===t.name&&i.push(Ct(t,e,o,s));!function(e,t,n){var o,s,r,i;const a=new Map(t.map(e=>[e.id,e])),l=null!==(o=ie(n,"Texture","FbxFileTexture"))&&void 0!==o?o:ie(n,"Texture");for(const[t,n]of Array.from(e.objects)){if("Model"!==n.name)continue;const o=ye(e,t,"Texture");if(0===o.length)continue;const u=ye(e,t,"Material").filter(e=>!e.propertyName).map(e=>a.get(e.id)).filter(e=>void 0!==e);if(0===u.length)continue;const c=null!==(r=null===(s=ye(e,t,"Geometry")[0])||void 0===s?void 0:s.node)&&void 0!==r?r:n,d=te(c,"LayerElementMaterial"),h=d?se(te(d,"Materials")):null,p=e=>{switch(e.replace(/^LayerElement/,"").replace(/Textures?$/,"")){case"":case"Diffuse":return{prop:"DiffuseColor",fbx:"diffuseColor",pbr:"baseColor"};case"Emissive":return{prop:"EmissiveColor",fbx:"emissionColor",pbr:"emissionColor"};case"Specular":return{prop:"SpecularColor",fbx:"specularColor",pbr:"specularColor"};case"Ambient":return{prop:"AmbientColor",fbx:"ambientColor",pbr:"ambientOcclusion"};case"Bump":case"NormalMap":return{prop:"NormalMap",fbx:"normalMap",pbr:"normalMap"};case"Transparent":return{prop:"TransparentColor",fbx:"transparencyColor",pbr:"opacity"};case"Reflection":return{prop:"ReflectionColor",fbx:"reflectionColor",pbr:"specularColor"};case"Shininess":return{prop:"ShininessExponent",fbx:"specularExponent",pbr:"roughness"};case"Displacement":return{prop:"DisplacementColor",fbx:"displacement",pbr:"displacementMap"};default:return null}},f=c.children.filter(e=>/^LayerElement\w*Textures?$/.test(e.name)),m=o.map(({id:t,node:n})=>Ot(t,n,void 0,e,l)),g=(e,t,n)=>{var o,s,r,i,a,l;const c=u[e],d=m[t];if(!c||!d||c.textures.some(e=>e.propertyName===n.prop))return;const h=Object.assign(Object.assign({},d),{propertyName:n.prop});c.textures.push(h);const p=null!==(o=(r=c.model.fbx)[i=n.fbx])&&void 0!==o?o:r[i]={valueComponents:0,textureEnabled:!1};p.texture=h,p.textureEnabled=!0;const f=null!==(s=(a=c.model.pbr)[l=n.pbr])&&void 0!==s?s:a[l]={valueComponents:0,textureEnabled:!1};f.texture=h,f.textureEnabled=!0};if(0!==f.length)for(const e of f){const t=p(e.name),n=se(te(e,"TextureId"));if(!t||!n||0===n.length)continue;const o=Math.max(n.length,null!==(i=null==h?void 0:h.length)&&void 0!==i?i:0);for(let e=0;e<o;e++){const o=n[Math.min(e,n.length-1)],s=h&&h.length>0?h[Math.min(e,h.length-1)]:0;o>=0&&g(s,o,t)}}else 1===u.length&&1===m.length&&g(0,0,p("LayerElementTexture"))}}(o,i,s);const a=[],l=[];for(const[e,n]of Array.from(o.objects))if("Geometry"===n.name){const s=oe(n,2);if("Mesh"===s){const t=Me(n,e);t.positions.length>0&&t.indices.length>0&&a.push(t)}else if("NurbsSurface"===s){const s=Ke(n,e,t.nurbsSubdivision);s&&(Jn(o,e,s),a.push(s))}else if("TrimNurbsSurface"===s){const n=ye(o,e,"Geometry").find(e=>"NurbsSurface"===oe(e.node,2)),s=n?Ke(n.node,e,t.nurbsSubdivision):null;s&&(Jn(o,e,s),s.diagnostics.push({type:"nurbs-trim-ignored",message:`Trim curves of NURBS surface '${s.name}' are ignored; the surface is rendered untrimmed.`}),a.push(s))}else"NurbsCurve"===s?l.push(je(n,e)):"Line"===s&&l.push(We(n,e))}const u=function(e,t){var n;Pt=t?null!==(n=ie(t,"Model","FbxNode"))&&void 0!==n?n:ie(t,"Model"):void 0;const o=[];for(const[t,n]of Array.from(e.objects))if("Deformer"===n.name&&"Skin"===oe(n,2)){const n=Bt(t,0,e);n&&o.push(n)}return o}(o,s),c=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=jt(t,e),r=n.get(s);r?r.push(o):n.set(s,[o])}return Array.from(n.entries()).sort(([e],[t])=>Qt(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 Wt(t.modelId,n))i.add(e)}}const u=Array.from(i);for(;u.length>0;){const e=u.pop();for(const t of n.connections){if("OO"!==t.type||t.parentId!==e||i.has(t.childId))continue;const o=n.objects.get(t.childId);o&&"Model"===o.name&&Vt(o)&&(i.add(t.childId),u.push(t.childId))}}const c=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=>!Xt(s,e,1e-5))&&t.push(`Model ${n.toString()} has differing Cluster.TransformLink matrices across skins`)}return t}(a),d=new Map;for(const[e,t]of Array.from(a))d.set(e,zt(t));const h=function(e,t){const n=new Map;for(const o of Array.from(e)){const s=qt(o,t);void 0!==s&&e.has(s)&&n.set(o,s)}return n}(i,n),p=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)=>Zt(e,t,n));const r=[],i=[...Array.from(e).filter(e=>!t.has(e)).sort((e,t)=>Zt(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,h,l),f=[],m=new Map;for(const e of p){const t=null!==(o=d.get(e))&&void 0!==o?o:Yt(e,n);if(!t)continue;const i=h.get(e),a=void 0===i?-1:null!==(s=m.get(i))&&void 0!==s?s:-1,l=f.length,u=Object.assign(Object.assign({},t),{index:l,parentIndex:a,isCluster:r.has(e)});f.push(u),m.set(e,l)}const g=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()}`,m));return{id:`rig_${e.toString()}`,rootModelIds:f.filter(e=>e.parentIndex<0).map(e=>e.modelId),bones:f,modelIdToBoneIndex:m,clusterModelIds:r,skinBindings:g,warnings:c}}(t,n,e))}(o,u),d=function(e){const t=[];for(const[n,o]of Array.from(e.objects))if("Deformer"===o.name&&"BlendShape"===oe(o,2)){const o=Kn(n,0,e);o&&t.push(o)}return t}(o),h=function(e,t,n={}){var o;const s=[],r=null===(o=n.rebaseKeyframes)||void 0===o||o;for(const[t,n]of Array.from(e.objects))if("AnimationStack"===n.name){const o=yn(t,n,e,r);o&&s.push(o)}return 0===s.length&&t&&s.push(...function(e,t,n=!0){var o,s,r,i,a,l;const u=ne(e,"Takes");if(!u)return[];const c=new Map,d=new Map;for(const e of t.objectEntries)if(void 0!==e.legacyName&&!e.synthetic&&!c.has(e.legacyName)){c.set(e.legacyName,e.id);const t=re(e.legacyName);d.has(t)||d.set(t,e.id)}const h=[];let p=-1e6;for(const f of u.children){if("Take"!==f.name)continue;const u=re(null!==(o=oe(f,0))&&void 0!==o?o:"Take"),m=null!==(s=Bn(te(f,"LocalTime")))&&void 0!==s?s:Bn(te(f,"ReferenceTime")),g=[],_=[];let v=1/0,y=-1/0;const b=e=>{for(const t of e)for(const e of t.keys)e.time<v&&(v=e.time),e.time>y&&(y=e.time)};for(const n of f.children){if("Model"!==n.name)continue;const o=null!==(r=oe(n,0))&&void 0!==r?r:"",s=null!==(i=c.get(o))&&void 0!==i?i:d.get(re(o));if(void 0!==s)for(const o of n.children){if("Channel"!==o.name)continue;const n=null!==(a=oe(o,0))&&void 0!==a?a:"";if("Transform"===n)for(const t of o.children){if("Channel"!==t.name)continue;const n=oe(t,0);if("T"!==n&&"R"!==n&&"S"!==n)continue;const o=Dn(t,e.version);o.length>0&&(b(o),g.push({type:n,targetModelId:s,curves:o,layerIndex:0}))}else{const r=Dn(o,e.version);if(r.length>0){b(r);const e=Pn(t,s,n);if(void 0!==e){g.push({type:"DeformPercent",targetModelId:e,curves:r,layerIndex:0});continue}const o=kn.has(n)?null===(l=ye(t,s,"NodeAttribute")[0])||void 0===l?void 0:l.id:void 0;_.push({type:n,id:p--,layerIndex:0,targetId:null!=o?o:s,propertyName:n,curveCount:r.length,curves:r,defaultValues:{}})}}}}if(0===g.length&&0===_.length)continue;const x={name:"BaseLayer",weight:100,normalizedWeight:1,blendMode:0,blend:Cn(0,100,0,0),curveNodes:g,unsupportedCurveNodes:_,diagnostics:[]};h.push(bn(u,[x],g,_,[],v,y,m,n))}return h}(t,e,r)),s}(o,e,{rebaseKeyframes:null===(n=t.rebaseKeyframes)||void 0===n||n}),p=function(e,t){var n,o,s,r;const i=[],a=null!==(n=ie(t,"NodeAttribute","FbxCamera"))&&void 0!==n?n:ie(t,"NodeAttribute");for(const[t,n]of Array.from(e.objects)){if("NodeAttribute"!==n.name)continue;if("Camera"!==oe(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=re(null!==(o=oe(u,1))&&void 0!==o?o:"Camera"),d=le(n,a,"NearPlane",.1),h=le(n,a,"FarPlane",1e4),p=1===le(n,a,"CameraProjectionType",0)||1===le(n,a,"ProjectionType",0)?"orthographic":"perspective",f=ao(ae(n,a,"FocalLength")),m=null!==(s=ao(ae(n,a,"FilmWidth")))&&void 0!==s?s:ao(ae(n,a,"ApertureWidth")),g=null!==(r=ao(ae(n,a,"FilmHeight")))&&void 0!==r?r:ao(ae(n,a,"ApertureHeight")),_=ao(ae(n,a,"OrthoZoom")),v=ao(ae(n,a,"Roll")),y=co(n,a),b=y.aspectRatio,x=y.fovDegY,T=[];"orthographic"===p&&void 0===_&&T.push("Orthographic camera has no OrthoZoom; runtime orthographic bounds use a fallback."),void 0!==f&&void 0===g&&void 0===ae(n,a,"FieldOfView")&&T.push("FocalLength is present without FilmHeight; default field of view fallback may be used."),i.push({modelId:l.id,attributeId:t,userProperties:fe(n),name:c,fieldOfView:x,fieldOfViewX:y.fovDegX,apertureMode:y.apertureMode,apertureSizeInch:y.apertureSizeInch,orthographicSize:y.orthographicSize,nearPlane:d,farPlane:h,aspectRatio:b,projectionType:p,focalLength:f,filmWidth:m,filmHeight:g,orthoZoom:_,roll:v,unknownProperties:ho(n,ro),diagnostics:T})}return i}(o,s),f=function(e,t){var n,o,s,r,i;const a=[],l=null!==(n=ie(t,"NodeAttribute","FbxLight"))&&void 0!==n?n:ie(t,"NodeAttribute");for(const[t,n]of Array.from(e.objects)){if("NodeAttribute"!==n.name)continue;if("Light"!==oe(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=re(null!==(o=oe(c,1))&&void 0!==o?o:"Light"),h=le(n,l,"LightType",0),p=ue(n,l,"Color",[1,1,1]),f=le(n,l,"Intensity",100)/100,m=null!==(s=ao(ae(n,l,"OuterAngle")))&&void 0!==s?s:ao(ae(n,l,"ConeAngle")),g=ao(ae(n,l,"InnerAngle")),_=null!=m?m:45,v=le(n,l,"DecayType",2),y=ao(ae(n,l,"DecayStart")),b=lo(ae(n,l,"EnableNearAttenuation")),x=lo(ae(n,l,"EnableFarAttenuation")),T=null!==(i=null!==(r=lo(ae(n,l,"CastShadow")))&&void 0!==r?r:lo(ae(c,void 0,"CastShadow")))&&void 0!==i?i:lo(ae(c,void 0,"Shadow")),A=[];2!==v&&A.push(`DecayType ${v} is preserved as metadata; Babylon falloff is not remapped in this pass.`),void 0!==y&&A.push("DecayStart is preserved as metadata and is not mapped to Babylon light range."),a.push({modelId:u.id,attributeId:t,userProperties:fe(n),nearAttenuationStart:ao(ae(n,l,"NearAttenuationStart")),nearAttenuationEnd:ao(ae(n,l,"NearAttenuationEnd")),farAttenuationStart:ao(ae(n,l,"FarAttenuationStart")),farAttenuationEnd:ao(ae(n,l,"FarAttenuationEnd")),areaLightShape:ao(ae(n,l,"AreaLightShape")),name:d,lightType:h,color:p,intensity:f,coneAngle:_,decayType:v,innerAngle:g,outerAngle:m,decayStart:y,enableNearAttenuation:b,enableFarAttenuation:x,castShadows:T,unknownProperties:ho(n,io),diagnostics:A})}return a}(o,s),m=function(e){var t,n,o;const s=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[r,i]of Array.from(e.objects)){const a=null!==(t=oe(i,2))&&void 0!==t?t:"";if("Constraint"===i.name){const t=i.children.find(e=>"Type"===e.name),l=null!==(n=t?oe(t,0):void 0)&&void 0!==n?n:a;new Set(["Aim","Parent-Child","Position From Positions","Rotation From Rotations","Scale From Scales"]).has(l)||s.push(Zn(e,r,i,"unsupported-constraint",`Constraint '${l||re(null!==(o=oe(i,1))&&void 0!==o?o:"")}' is preserved as metadata but not evaluated at runtime.`));continue}Xn.has(i.name)?s.push(Zn(e,r,i,"unsupported-helper",`${i.name} helper data is preserved as diagnostic data but not evaluated at runtime.`)):"LayeredTexture"!==i.name?"Pose"!==i.name||"BindPose"===a?"Deformer"!==i.name||Qn(a)?"NodeAttribute"===i.name&&a&&!Yn.has(a)&&s.push(Zn(e,r,i,"unsupported-node-attribute",`NodeAttribute subtype '${a}' is preserved as diagnostic data but not converted to a Babylon object.`)):s.push(Zn(e,r,i,"unsupported-deformer",`Deformer subtype '${a}' is preserved as diagnostic data but not evaluated at runtime.`)):s.push(Zn(e,r,i,"unsupported-pose",`Pose subtype '${a}' is preserved as diagnostic data but not evaluated at runtime.`)):s.push(Zn(e,r,i,"unsupported-layered-texture","LayeredTexture is preserved as diagnostic data; runtime texture layer blending is not implemented."))}return s}(o),g=function(e){const t=[];for(const[n,o]of Array.from(e.objects))"Constraint"===o.name&&t.push(pt(n,o,e));return t}(o),_=function(e,t,n,o,s){var r;const i=new Map;for(const e of t)i.set(e.id,e);const a=new Map;for(const e of n)a.set(e.id,e);const l=new Map;for(const e of o)l.set(e.id,e);const u=null!==(r=e.childrenOf.get(0))&&void 0!==r?r:[],c=[],d=new Set,h=new Set;for(const{id:t}of u){const n=e.objects.get(t);n&&"Model"===n.name&&!d.has(t)&&(d.add(t),c.push(no(t,n,e,i,a,l,s,h)))}const p=new Set;for(const t of e.connections){if("OO"!==t.type)continue;const n=e.objects.get(t.parentId);0!==t.parentId&&"Model"!==(null==n?void 0:n.name)||p.add(t.childId)}for(const[t,n]of Array.from(e.objects))"Model"!==n.name||p.has(t)||d.has(t)||(d.add(t),c.push(no(t,n,e,i,a,l,s,h)));return c}(o,a,l,i,s),{displayLayers:v,selectionSets:y}=function(e,t){var n,o,s,r,i;const a=new Map,l=e=>{for(const t of e)a.set(t.id,t),l(t.children)};l(t);const u=[],c=[];for(const[t,l]of Array.from(e.objects))if("CollectionExclusive"===l.name){const s=pe(l),r=(e,t)=>{var n;const o=null===(n=s.find(t=>t.name===e))||void 0===n?void 0:n.values[0];return"number"==typeof o?o:"boolean"==typeof o?o?1:0:t},i=null===(n=s.find(e=>"Color"===e.name))||void 0===n?void 0:n.values,c=i&&"number"==typeof i[0]&&"number"==typeof i[1]&&"number"==typeof i[2]?[i[0],i[1],i[2]]:[.8,.8,.8],d={id:t,name:re(null!==(o=oe(l,1))&&void 0!==o?o:"DisplayLayer"),show:0!==r("Show",1),freeze:0!==r("Freeze",0),color:c,modelIds:ye(e,t,"Model").map(e=>e.id)};u.push(d);for(const e of d.modelIds){const t=a.get(e);t&&(t.displayLayer=d)}}else if("SelectionSet"===l.name||"Collection"===l.name&&"SelectionSet"===oe(l,2)){const n=[];for(const o of ye(e,t))if("Model"===o.node.name)n.push({modelId:o.id,includeNode:!0});else if("SelectionNode"===o.node.name){const t=e=>{const t=te(o.node,e);if(t)return Array.from(se(t))},i=null===(r=null===(s=te(o.node,"IsTheNodeInSet"))||void 0===s?void 0:s.properties[0])||void 0===r?void 0:r.value;for(const s of ye(e,o.id,"Model"))n.push({modelId:s.id,includeNode:void 0===i||1===i||!0===i,vertices:t("VertexIndexArray"),edges:t("EdgeIndexArray"),faces:t("PolygonIndexArray")})}c.push({id:t,name:re(null!==(i=oe(l,1))&&void 0!==i?i:"SelectionSet"),members:n})}return{displayLayers:u,selectionSets:c}}(o,_);return Object.assign({rootModels:_,displayLayers:v,selectionSets:y,constraints:g,geometries:a,curves:l,materials:i,skins:u,rigs:c,blendShapes:d,animations:h,cameras:p,lights:f,diagnostics:m},r)}const to=512;function no(e,t,n,o,s,r,i,a){var l,u,c,d;const h=re(null!==(l=oe(t,1))&&void 0!==l?l:"Model");a.add(e);const p=null!==(u=oe(t,2))&&void 0!==u?u:"Null",f=ye(n,e,"Geometry"),m=f.map(e=>o.get(e.id)).find(e=>void 0!==e),g=f.map(e=>s.get(e.id)).find(e=>void 0!==e),_=ye(n,e,"Material"),v=[];for(const{id:e}of _){const t=r.get(e);t&&v.push(t)}const y=function(e,t){return ve(e,t)}(t,null!==(c=ie(i,"Model","FbxNode"))&&void 0!==c?c:ie(i,"Model")),b=ye(n,e,"Model").filter(e=>!e.propertyName),x=[],T=[];for(const{id:e,node:t}of b){if(a.size>to){T.push(`Model hierarchy deeper than ${to} levels; deeper children were skipped.`);break}a.has(e)?T.push(`Model connection cycle detected at '${re(null!==(d=oe(t,1))&&void 0!==d?d:"")}'; the recursive child was skipped.`):x.push(no(e,t,n,o,s,r,i,a))}a.delete(e);const A=t.children.find(e=>"Culling"===e.name),w=!!A&&"CullingOff"===oe(A,0),M=function(e){const t=fe(e);if(!t)return;let n=!1;const o={};for(const e of Object.keys(t))so.has(e)||(o[e]=t[e],n=!0);return n?o:void 0}(t);let S;if("LodGroup"===p){const t=ye(n,e,"NodeAttribute").find(e=>"LodGroup"===oe(e.node,2)),o=t?pe(t.node):[],s=[],r=[];for(let e=0;;e++){const t=o.find(t=>t.name===`Thresholds|Level${e}`);if(!t)break;s.push("number"==typeof t.values[0]?t.values[0]:0)}for(let e=0;;e++){const t=o.find(t=>t.name===`DisplayLevels|Level${e}`);if(!t)break;r.push("number"==typeof t.values[0]?t.values[0]:0)}const i=o.find(e=>"ThresholdsUsedAsPercentage"===e.name);S={thresholds:s,relative:!!i&&0!==i.values[0]&&!1!==i.values[0],displayLevels:r}}return Object.assign(Object.assign({id:e,name:h,subType:p,geometry:m,materials:v,children:x,cullingOff:w,customProperties:M,lodGroup:S,curve:g},y),{diagnostics:[...y.diagnostics,...T]})}const oo=[30,120,100,60,50,48,30,30,29.97,29.97,25,24,1e3,23.976,24,96,72,59.94],so=new Set(["Lcl Translation","Lcl Rotation","Lcl Scaling","PreRotation","PostRotation","RotationPivot","ScalingPivot","RotationOffset","ScalingOffset","RotationOrder","GeometricTranslation","GeometricRotation","GeometricScaling","Visibility","InheritType","ScalingMax","DefaultAttributeIndex","currentUVSet","lockInfluenceWeights"]),ro=new Set(["FieldOfView","FieldOfViewX","FieldOfViewY","NearPlane","FarPlane","AspectWidth","AspectHeight","FilmAspectRatio","FocalLength","FilmWidth","FilmHeight","ApertureWidth","ApertureHeight","CameraProjectionType","ProjectionType","OrthoZoom","Roll","ApertureMode"]),io=new Set(["LightType","Color","Intensity","InnerAngle","OuterAngle","ConeAngle","DecayType","DecayStart","EnableNearAttenuation","EnableFarAttenuation","CastShadow","Shadow"]);function ao(e){if("number"==typeof e)return e}function lo(e){return"boolean"==typeof e?e:"number"==typeof e?0!==e:void 0}const uo=[[1e3,1e3],[404,295],[493,292],[864,630],[816,612],[980,735],[825,446],[864,732],[2066,906],[1485,991],[2080,1480],[2772,2072]];function co(e,t){const n=(n,o)=>{var s;return null!==(s=ao(ae(e,t,n)))&&void 0!==s?s:o},o=n("AspectRatioMode",0),s=n("ApertureMode",2),r=Math.max(0,Math.min(uo.length-1,Math.round(n("ApertureFormat",0)))),i=n("GateFit",0);let a=n("AspectW",0),l=n("AspectH",0);a=n("AspectWidth",a),l=n("AspectHeight",l);const u=n("FieldOfView",0),c=n("FieldOfViewX",0),d=n("FieldOfViewY",0),h=n("FocalLength",0),p=30*n("OrthoZoom",1),f=uo[r];let m=n("FilmWidth",.001*f[0]),g=n("FilmHeight",.001*f[1]);a<=0&&l<=0?(a=m>0?m:1,l=g>0?g:1):a<=0?a=m>0&&g>0?l/g*m:l:l<=0&&(l=m>0&&g>0?a/m*g:a),g*=n("FilmSqueezeRatio",7===r?2:1);let _=a,v=l;switch(o){case 3:_=a,v=a*l;break;case 4:_=l*a,v=l}const y=0!==v?_/v:1,b=0!==g?m/g:1;let x=i;3===x?x=y>b?2:1:4===x&&(x=y<b?2:1);let T=m,A=g,w=p,M=p;switch(x){case 1:T=g*y,A=g,w=p*y;break;case 2:T=m,A=m/y,M=p/y}m=T;const S=Math.PI/180,R=180/Math.PI;let C,I;switch(s){case 0:C=Math.tan(c*S*.5),I=Math.tan(d*S*.5);break;case 1:C=Math.tan(u*S*.5),I=C/y;break;case 3:{const e=h/25.4;C=e>0?T/e*.5:Math.tan(u*S*.5)*y,I=e>0?A/e*.5:Math.tan(u*S*.5);break}default:I=Math.tan(u*S*.5),C=I*y}return{fovDegX:Math.atan(C)*R*2,fovDegY:Math.atan(I)*R*2,aspectRatio:y,apertureMode:s,apertureSizeInch:[T,A],orthographicSize:[w,M]}}function ho(e,t){var n;const o=new Set;for(const s of["Properties70","Properties60"]){const r=te(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=oe(e,0);n&&!t.has(n)&&o.add(n)}}return Array.from(o).sort()}function po(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 fo(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 mo(e,n){const o=Math.PI/180,s=t.Matrix.Scaling(n[0],n[1],n[2]),r=po(e[0]*o,e[1]*o,e[2]*o);return s.multiply(r)}const go=Math.PI/180,_o={invRoot:new t.Matrix,parent:new t.Matrix,invParent:new t.Matrix,world:new t.Matrix,local:new t.Matrix,mA:new t.Matrix,mB:new t.Matrix,mC:new t.Matrix,mD:new t.Matrix,position:new t.Vector3,scale:new t.Vector3,translation:new t.Vector3,decomposedScale:new t.Vector3,localValue:new t.Vector3,up:new t.Vector3,forward:new t.Vector3,origin:new t.Vector3,axisA:new t.Vector3,axisB:new t.Vector3,axisC:new t.Vector3,eulerA:new t.Vector3,eulerB:new t.Vector3,rotation:new t.Quaternion,decomposedRotation:new t.Quaternion,result:new t.Quaternion},vo=new WeakMap;class yo{constructor(e){this._behaviors=[],this._ordered=[],this._cyclic=[],this._dirty=!1,this._beforeAnimations=null,this._afterAnimations=null,this._scene=e}static Get(e){return vo.get(e)}static GetOrCreate(e){let t=vo.get(e);return t||(t=new yo(e),vo.set(e,t)),t}get constraints(){return this._ensureOrder(),this._ordered}get cyclicConstraints(){return this._ensureOrder(),this._cyclic}register(e){this._behaviors.indexOf(e)>=0||(this._behaviors.push(e),this._dirty=!0,this._beforeAnimations||(this._beforeAnimations=this._scene.onBeforeAnimationsObservable.add(()=>this.beginFrame()),this._afterAnimations=this._scene.onAfterAnimationsObservable.add(()=>this.solve())))}unregister(e){const t=this._behaviors.indexOf(e);t<0||(this._behaviors.splice(t,1),this._dirty=!0,0===this._behaviors.length&&(this._scene.onBeforeAnimationsObservable.remove(this._beforeAnimations),this._scene.onAfterAnimationsObservable.remove(this._afterAnimations),this._beforeAnimations=null,this._afterAnimations=null,vo.delete(this._scene)))}invalidateOrder(){this._dirty=!0}beginFrame(){for(const e of this._behaviors)e.restoreBase()}solve(){this._ensureOrder();for(const e of this._behaviors)e.captureBase();for(const e of this._ordered)e.evaluate()}_ensureOrder(){if(!this._dirty)return;this._dirty=!1;const e=this._behaviors,t=e.length,n=e.map(()=>[]);for(let o=0;o<t;o++){const s=e[o].dependencyNodes();for(let r=0;r<t;r++){if(o===r)continue;const t=e[r].attachedNode;t&&s.some(e=>yo._IsAncestorOrSelf(t,e))&&n[o].push(r)}}const o=n.map(e=>e.length),s=e.map(()=>!1),r=[];let i=!0;for(;i;){i=!1;for(let a=0;a<t;a++)if(!(s[a]||o[a]>0)){s[a]=!0,r.push(e[a]),i=!0;for(let e=0;e<t;e++)!s[e]&&n[e].indexOf(a)>=0&&o[e]--}}const a=[];for(let n=0;n<t;n++)s[n]||(a.push(e[n]),r.push(e[n]));this._ordered=r,this._cyclic=a}static _IsAncestorOrSelf(e,t){let n=t;for(;n;){if(n===e)return!0;n=n.parent}return!1}}class bo{constructor(e,n){this.constraint=e,this._options=n,this.attachedNode=null,this.enabled=!0,this._base={position:new t.Vector3,rotation:new t.Quaternion,scaling:new t.Vector3},this._hasBase=!1,this.name=`fbxConstraint:${e.name}`,this._offsetTranslation=new t.Vector3(e.offsetTranslation[0],e.offsetTranslation[1],e.offsetTranslation[2]),this._offsetRotation=po(e.offsetRotation[0]*go,e.offsetRotation[1]*go,e.offsetRotation[2]*go),this._offsetScale=new t.Vector3(e.offsetScale[0],e.offsetScale[1],e.offsetScale[2]);const o=new t.Matrix;this._localBasisTransposed=bo._OrthonormalBasisToRef(new t.Vector3(e.aimVector[0],e.aimVector[1],e.aimVector[2]),new t.Vector3(e.upVector[0],e.upVector[1],e.upVector[2]),o)?o.transpose():null}init(){}attach(e){this.attachedNode=e,yo.GetOrCreate(e.getScene()).register(this),this.captureBase(),this.evaluate()}detach(){var e;this.attachedNode&&(null===(e=yo.Get(this.attachedNode.getScene()))||void 0===e||e.unregister(this)),this.attachedNode=null,this._hasBase=!1}captureBase(){const e=this.attachedNode;e&&(e.rotationQuaternion||(e.rotationQuaternion=t.Quaternion.FromEulerVector(e.rotation)),this._base.position.copyFrom(e.position),this._base.rotation.copyFrom(e.rotationQuaternion),this._base.scaling.copyFrom(e.scaling),this._hasBase=!0)}restoreBase(){const e=this.attachedNode;e&&this._hasBase&&(e.position.copyFrom(this._base.position),e.rotationQuaternion.copyFrom(this._base.rotation),e.scaling.copyFrom(this._base.scaling))}dependencyNodes(){const e=this._options.targets.map(e=>e.node);return e.push(this._options.upNode),e.push(this.attachedNode?this.attachedNode.parent:null),e}evaluate(){const e=this.attachedNode,n=this.constraint;if(!e||!this.enabled||!n.active||n.weight<=0||0===this._options.targets.length)return;this._hasBase||this.captureBase(),this._options.root.computeWorldMatrix(!0).invertToRef(_o.invRoot);const o=e.parent;switch(o&&"function"==typeof o.computeWorldMatrix?this._fbxWorld(o,_o.parent):t.Matrix.IdentityToRef(_o.parent),_o.parent.invertToRef(_o.invParent),n.type){case"position":this._solvePosition(e);break;case"rotation":this._solveRotation(e);break;case"scale":this._solveScale(e);break;case"parent":this._solveParent(e);break;case"aim":this._solveAim(e)}}_fbxWorld(e,t){return e.computeWorldMatrix(!0).multiplyToRef(_o.invRoot,t),t}_blendTargets(e,n,o){e.set(0,0,0),o.set(0,0,0),n.set(0,0,0,1);let s=0;for(const r of this._options.targets){if(r.weight<=0)continue;r.offset.multiplyToRef(this._fbxWorld(r.node,_o.world),_o.local),_o.local.decompose(_o.decomposedScale,_o.decomposedRotation,_o.translation);const i=s+r.weight;e.addInPlace(_o.translation.scaleInPlace(r.weight)),o.addInPlace(_o.decomposedScale.scaleInPlace(r.weight)),0===s?n.copyFrom(_o.decomposedRotation):t.Quaternion.SlerpToRef(n,_o.decomposedRotation,r.weight/i,n),s=i}return s>0&&(e.scaleInPlace(1/s),o.scaleInPlace(1/s)),s}_applyWeighted(e,t,n,o){const s=this.constraint.weight;o.set(n[0]?e.x+(t.x-e.x)*s:e.x,n[1]?e.y+(t.y-e.y)*s:e.y,n[2]?e.z+(t.z-e.z)*s:e.z)}_applyRotation(e,n,o){const s=this._base.rotation,r=_o.result;r.copyFrom(n),o[0]&&o[1]&&o[2]||(s.toEulerAnglesToRef(_o.eulerA),n.toEulerAnglesToRef(_o.eulerB),t.Quaternion.FromEulerAnglesToRef(o[0]?_o.eulerB.x:_o.eulerA.x,o[1]?_o.eulerB.y:_o.eulerA.y,o[2]?_o.eulerB.z:_o.eulerA.z,r)),this.constraint.weight<1&&t.Quaternion.SlerpToRef(s,r,this.constraint.weight,r),e.rotationQuaternion.copyFrom(r)}_writePosition(e,t){this._applyWeighted(this._base.position,t,this.constraint.affectTranslation,e.position)}_writeScaling(e,t){this._applyWeighted(this._base.scaling,t,this.constraint.affectScale,e.scaling)}_solvePosition(e){0!==this._blendTargets(_o.position,_o.rotation,_o.scale)&&(t.Vector3.TransformCoordinatesToRef(_o.position,_o.invParent,_o.localValue),_o.localValue.addInPlace(this._offsetTranslation),this._writePosition(e,_o.localValue))}_solveRotation(e){0!==this._blendTargets(_o.position,_o.rotation,_o.scale)&&(t.Matrix.FromQuaternionToRef(_o.rotation,_o.mA),this._offsetRotation.multiplyToRef(_o.mA,_o.mB),_o.mB.multiplyToRef(_o.invParent,_o.mC),_o.mC.decompose(_o.decomposedScale,_o.decomposedRotation,_o.translation),this._applyRotation(e,_o.decomposedRotation,this.constraint.affectRotation))}_solveScale(e){if(0===this._blendTargets(_o.position,_o.rotation,_o.scale))return;_o.parent.decompose(_o.decomposedScale,_o.decomposedRotation,_o.translation);const t=_o.decomposedScale,n=_o.scale;_o.localValue.set((0!==t.x?n.x/t.x:n.x)*this._offsetScale.x,(0!==t.y?n.y/t.y:n.y)*this._offsetScale.y,(0!==t.z?n.z/t.z:n.z)*this._offsetScale.z),this._writeScaling(e,_o.localValue)}_solveParent(e){0!==this._blendTargets(_o.position,_o.rotation,_o.scale)&&(t.Matrix.ComposeToRef(_o.scale,_o.rotation,_o.position,_o.mA),_o.mA.multiplyToRef(_o.invParent,_o.mB),_o.mB.decompose(_o.decomposedScale,_o.decomposedRotation,_o.translation),this._writePosition(e,_o.translation),this._applyRotation(e,_o.decomposedRotation,this.constraint.affectRotation),this._writeScaling(e,_o.decomposedScale))}_solveAim(e){const n=this.constraint;if(!this._localBasisTransposed||0===this._blendTargets(_o.position,_o.rotation,_o.scale))return;const o=this._fbxWorld(e,_o.world);if(o.getTranslationToRef(_o.origin),_o.position.subtractToRef(_o.origin,_o.forward),_o.forward.lengthSquared()<1e-20)return;_o.forward.normalize();const s=_o.up;switch(n.worldUpType){case 1:this._options.upNode?(this._fbxWorld(this._options.upNode,_o.local).getTranslationToRef(s),s.subtractInPlace(_o.origin)):s.copyFrom(this._options.sceneUp);break;case 2:this._options.upNode?(this._fbxWorld(this._options.upNode,_o.local).decompose(_o.decomposedScale,_o.decomposedRotation,_o.translation),s.set(n.worldUpVector[0],n.worldUpVector[1],n.worldUpVector[2]),s.rotateByQuaternionToRef(_o.decomposedRotation,s)):s.copyFrom(this._options.sceneUp);break;case 3:s.set(n.worldUpVector[0],n.worldUpVector[1],n.worldUpVector[2]);break;case 4:_o.localValue.set(n.upVector[0],n.upVector[1],n.upVector[2]),t.Vector3.TransformNormalToRef(_o.localValue,o,s);break;default:s.copyFrom(this._options.sceneUp)}(s.lengthSquared()<1e-20||Math.abs(t.Vector3.Dot(s.normalizeToRef(_o.localValue),_o.forward))>.9999)&&(Math.abs(_o.forward.y)<.9?s.set(0,1,0):s.set(1,0,0)),bo._OrthonormalBasisToRef(_o.forward,s,_o.mA)&&(this._localBasisTransposed.multiplyToRef(_o.mA,_o.mB),this._offsetRotation.multiplyToRef(_o.mB,_o.mC),_o.mC.multiplyToRef(_o.invParent,_o.mD),_o.mD.decompose(_o.decomposedScale,_o.decomposedRotation,_o.translation),this._applyRotation(e,_o.decomposedRotation,n.affectRotation))}static _OrthonormalBasisToRef(e,n,o){const s=_o.axisA,r=_o.axisB,i=_o.axisC;return e.normalizeToRef(s),n.subtractToRef(s.scaleToRef(t.Vector3.Dot(s,n),r),r),!(s.lengthSquared()<1e-20||r.lengthSquared()<1e-20||(r.normalize(),t.Vector3.CrossToRef(s,r,i),t.Matrix.FromValuesToRef(s.x,s.y,s.z,0,r.x,r.y,r.z,0,i.x,i.y,i.z,0,0,0,0,1,o),0))}}const xo={name:"fbx",extensions:{".fbx":{isBinary:!0}}};class To{constructor(e={}){var t,n,o,s,r,i,a,l,u,c;this.name=xo.name,this.extensions=xo.extensions,this._bindRestBones=new WeakSet,this._sourceBonesBySkeleton=new WeakMap,this._scaleCompensationHelpersBySkeleton=new WeakMap,this._frameRate=30,this._activeLayers=[],this._parentModelById=new Map,this._curveNodesByModelId=new Map,this._inheritScaleHelpers=new Map,this._meshByGeometryKey=new Map,this._instanceSource=new Map,this._evaluatedCurveNodeIds=new Set,this._rigBoneModelIds=new Set;const d="full"===e.preset;this._options={preset:d?"full":"compatible",normalMapCoordinateSystem:null!==(t=e.normalMapCoordinateSystem)&&void 0!==t?t:"y-up",materials:null!==(n=e.materials)&&void 0!==n?n:d?"auto":"standard",unitScale:null!==(o=e.unitScale)&&void 0!==o?o:"preserve",shareGeometry:null!==(s=e.shareGeometry)&&void 0!==s?s:d,onWarning:null!==(r=e.onWarning)&&void 0!==r?r:()=>{},nurbsSubdivision:null!==(i=e.nurbsSubdivision)&&void 0!==i?i:0,curves:null!==(a=e.curves)&&void 0!==a?a:d?"lines":"skip",constraints:null!==(l=e.constraints)&&void 0!==l?l:d?"apply":"metadata",rebaseAnimations:null!==(u=e.rebaseAnimations)&&void 0!==u?u:!d,attachCamerasAndLights:null!==(c=e.attachCamerasAndLights)&&void 0!==c?c:d}}createPlugin(e){return new To(e[xo.name])}importMeshAsync(e,t,n,o,s,r){return b(this,void 0,void 0,function*(){const s=this._parseAndInterpret(n);return this._buildScene(s,t,o,e)})}loadAsync(e,t,n,o,s){return b(this,void 0,void 0,function*(){const o=this._parseAndInterpret(t);this._buildScene(o,e,n,null)})}loadAssetContainerAsync(e,n,o,s,r){return b(this,void 0,void 0,function*(){const s=this._parseAndInterpret(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)e instanceof t.LinesMesh||this._addMaterialToContainer(e.material,r);return this._setAssetContainer(r),r.removeAllFromScene(),r})}_parseAndInterpret(e){return eo(this._parse(e),{nurbsSubdivision:this._options.nurbsSubdivision>0?this._options.nurbsSubdivision:void 0,rebaseKeyframes:this._options.rebaseAnimations})}_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 W(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(D=!(n.length>22)||0===n[22],"Kaydara FBX Binary \0"!==j(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,D),s=o>=7500,r=[];let i=27;for(;i<e.byteLength;){const o=V(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),o=n.substring(0,4096);if(o.trimStart().startsWith("; FBX")||/^\s*(?:;[^\n]*\n\s*)*(?:FBXHeaderExtension|Definitions|Objects|Connections)\s*:/.test(o))return W(n);throw new Error("FBXFileLoader: unrecognized FBX format")}_buildScene(e,n,o,s){var r;const i=this._buildNameFilter(s);this._frameRate=e.frameRate>0?e.frameRate:30,this._inheritScaleHelpers=new Map;const 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,p=new Map;for(const t of e.skins)p.set(t.id,t);this._rigBoneModelIds=new Set;for(const t of e.rigs)for(const e of t.bones)this._rigBoneModelIds.add(e.modelId);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=p.get(n.skinId);t&&(c.set(n.geometryId,e),d.set(n.geometryId,t),h.set(n.geometryId,n))}}const f=new Map;this._parentModelById=new Map;const m=(e,t)=>{for(const n of e)f.set(n.id,n),t&&this._parentModelById.set(n.id,t),m(n.children,n)};m(e.rootModels,null);const g=To._collectCullingConflictMaterialIds(e.rootModels),_=new Map,v=new t.TransformNode("__fbx_root__",n);n.useRightHandedSystem||(v.rotation.y=Math.PI,v.scaling.z=-1);const y=this._options.unitScale,b="preserve"===y?0:"meters"===y?100:y;if(b>0&&e.unitScaleFactor>0){const t=e.unitScaleFactor/b;v.scaling.scaleInPlace(t)}v.metadata=Object.assign(Object.assign({},null!==(r=v.metadata)&&void 0!==r?r:{}),{fbxUnitScaleFactor:e.unitScaleFactor,fbxFrameRate:e.frameRate}),this._meshByGeometryKey=new Map,this._instanceSource=new Map,this._evaluatedCurveNodeIds=new Set;const x=[],T=[v];let A=v;const w=To._computeFBXAxisConversionMatrix(e);w.equals(t.Matrix.Identity())||(A=new t.TransformNode("__fbx_axis_conversion__",n),A.parent=v,To._applyMatrixToTransform(A,w),T.push(A));const M=new Map,S=t.Matrix.Identity();for(const t of e.rootModels)this._buildModel(t,n,A,A,S,a,i,x,T,c,d,h,M,g,_);this._linkSkeletonsToTransformNodes(e.rigs,u,M,T,n);for(const t of e.rigs){const e=u.get(t.id);if(!e)continue;x.find(t=>t.skeleton===e);const n=new Set;for(const t of e.bones){const e=t.getTransformNode();e&&n.add(e)}}if(e.blendShapes.length>0){this._applyBlendShapes(e.blendShapes,x,n);for(const[e,t]of Array.from(this._instanceSource))t.morphTargetManager&&!e.morphTargetManager&&(e.morphTargetManager=t.morphTargetManager)}const R=[],C=new Map;for(const t of e.cameras){const e=this._createCamera(t,M,n);e&&(R.push(e),C.set(t.attributeId,e))}const I=[],O=new Map;for(const t of e.lights){const e=this._createLight(t,M,n);e&&(I.push(e),O.set(t.attributeId,e))}this._applyConstraints(e,M,v,n);const F=[];for(const t of e.animations){const o=this._createAnimationGroup(t,e.rigs,u,n,M,f,x,{cameraByAttributeId:C,lightByAttributeId:O,materialCache:a});o&&F.push(o)}return this._reportDiagnostics(e,v,M),{meshes:x,particleSystems:[],skeletons:l,animationGroups:F,transformNodes:T,geometries:[],lights:I,spriteManagers:[],materials:Array.from(a.values()),textures:Array.from(new Set(Array.from(a.values()).flatMap(e=>e.getActiveTextures()))),cameras:R}}_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,p,f,m){var g,_,v;let y=o;const b=To._computeFBXModelLocalMatrix(e).multiply(r),x=this._parentModelById.get(e.id),T=x?p.get(x.id):void 0;if(y&&x&&T&&y===T&&1!==e.inheritType&&!this._isRigBone(e.id)&&!this._isRigBone(x.id)&&(!x.geometry||!d.has(x.geometry.id))){const o=new t.TransformNode(`${e.name}__fbx_inheritScale`,n);o.parent=T.parent,o.position.copyFrom(T.position),o.rotationQuaternion=T.rotationQuaternion?T.rotationQuaternion.clone():t.Quaternion.FromEulerVector(T.rotation),o.scaling.set(1,1,1),u.push(o),this._inheritScaleHelpers.set(e.id,o),y=o}if(e.geometry&&e.geometry.indices.length>0&&(!a||a(e.name))){const o=null!==e.geometry.controlPointIndices,r=o?c.get(e.geometry.id):void 0,x=o?d.get(e.geometry.id):void 0,T=o?h.get(e.geometry.id):void 0;r&&x&&(r.needInitialSkinMatrix=!0);const A=`${e.geometry.id}|${e.geometricTranslation.join(",")}|${e.geometricRotation.join(",")}|${e.geometricScaling.join(",")}`,w=!r&&this._options.shareGeometry?this._meshByGeometryKey.get(A):void 0;let M;if(w?(M=w.clone(e.name,null,!0),M.sideOrientation=w.sideOrientation,M.metadata=Object.assign(Object.assign({},null!==(g=w.metadata)&&void 0!==g?g:{}),{fbxInstanceOf:w.name}),this._instanceSource.set(M,w)):(M=this._createMesh(e,e.geometry,n,r,x,T),r||this._meshByGeometryKey.set(A,M)),r&&x){const e=x.meshBindPoseMatrix?t.Matrix.FromArray(x.meshBindPoseMatrix):b;M.parent=s,To._applyMatrixToTransform(M,e),M.computeWorldMatrix(!0),M.updatePoseMatrix(t.Matrix.Invert(e)),M.alwaysSelectAsActiveMesh=!0}else y&&(M.parent=y),this._applyRestTRS(M,e);if(e.materials.length>1&&(null===(_=e.geometry)||void 0===_?void 0:_.materialIndices))this._applyMultiMaterial(M,e,i,n,f,m);else if(e.materials.length>0){const t=i.get(e.materials[0].id);t&&(M.material=To._getModelMaterial(t,e,m,f.has(e.materials[0].id)))}(null===(v=e.geometry)||void 0===v?void 0:v.colors)&&this._useUnmodulatedVertexColorMaterials(M,n),this._applyMaterialUVSetCoordinates(M.material,e.geometry),l.push(M),p.set(e.id,M),To._applyModelMetadata(M,e);for(const t of e.children)this._buildModel(t,n,M,s,b,i,a,l,u,c,d,h,p,f,m)}else if(e.curve&&"skip"!==this._options.curves&&e.curve.polylines.length>0&&(!a||a(e.name))){const t=this._createLinesMesh(e,e.curve,n);y&&(t.parent=y),this._applyRestTRS(t,e),l.push(t),p.set(e.id,t),To._applyModelMetadata(t,e);for(const o of e.children)this._buildModel(o,n,t,s,b,i,a,l,u,c,d,h,p,f,m)}else{if((e.geometry||e.curve)&&a&&!To._modelSubtreeMatchesNameFilter(e,a))return;const o=new t.TransformNode(e.name,n);y&&(o.parent=y),this._applyRestTRS(o,e),u.push(o),p.set(e.id,o),To._applyModelMetadata(o,e);for(const t of e.children)this._buildModel(t,n,o,s,b,i,a,l,u,c,d,h,p,f,m);To._applyLodGroup(e,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,To._applyMatrixToTransform(e,l.getLocalMatrix()),To._applyMatrixToTransform(a,i.getLocalMatrix()),l.linkTransformNode(e),s.push(e)}else To._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(To._modelSubtreeMatchesNameFilter(n,t))return!0}return!1}static _applyModelMetadata(e,t){var n;(t.customProperties||0!==t.diagnostics.length||t.displayLayer||t.lodGroup)&&(e.metadata=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},null!==(n=e.metadata)&&void 0!==n?n:{}),t.customProperties?{fbxCustomProperties:t.customProperties,fbxUserProperties:t.customProperties}:{}),t.diagnostics.length>0?{fbxDiagnostics:t.diagnostics}:{}),t.displayLayer?{fbxDisplayLayer:{name:t.displayLayer.name,show:t.displayLayer.show,freeze:t.displayLayer.freeze,color:t.displayLayer.color}}:{}),t.lodGroup?{fbxLodGroup:t.lodGroup}:{}),t.displayLayer&&!t.displayLayer.show&&e.setEnabled(!1))}static _applyLodGroup(e,n){var o,s,r,i,a,l;const u=e.lodGroup;if(!u)return;const c=[];for(let t=0;t<e.children.length;t++){const r=e.children[t],i=null!==(o=u.displayLevels[t])&&void 0!==o?o:0;2===i?null===(s=n.get(r.id))||void 0===s||s.setEnabled(!1):0===i&&c.push({child:r,level:t})}if(c.length<2)return;const d=e=>{const o=n.get(e.id);if(!o)return[];const s=o instanceof t.Mesh?[o]:[];for(const e of o.getChildMeshes(!1))e instanceof t.Mesh&&s.push(e);return s},h=d(c[0].child);for(let e=1;e<c.length;e++){const t=c[e].level,n=d(c[e].child),o=null!==(i=null!==(r=u.thresholds[t-1])&&void 0!==r?r:u.thresholds[u.thresholds.length-1])&&void 0!==i?i:0;for(let e=0;e<h.length;e++){const s=null!==(a=n[e])&&void 0!==a?a:null;u.relative?(h[e].useLODScreenCoverage=!0,h[e].addLODLevel(o/100,s)):h[e].addLODLevel(o,s),s&&(s.metadata=Object.assign(Object.assign({},null!==(l=s.metadata)&&void 0!==l?l:{}),{fbxLodLevel:t}))}}}_createLinesMesh(e,n,o){var s;const r=new t.LinesMesh(e.name,o),i=[],a=[];for(const e of n.polylines){const t=e.length/3;if(t<2)continue;const n=i.length/3;for(let t=0;t<e.length;t++)i.push(e[t]);for(let e=0;e<t-1;e++)a.push(n+e,n+e+1)}const l=To._computeFBXGeometricMatrix(e.geometricTranslation,e.geometricRotation,e.geometricScaling);if(!l.equals(t.Matrix.Identity()))for(let e=0;e<i.length;e+=3){const n=t.Vector3.TransformCoordinates(new t.Vector3(i[e],i[e+1],i[e+2]),l);i[e]=n.x,i[e+1]=n.y,i[e+2]=n.z}const u=new t.VertexData;return u.positions=i,u.indices=a,u.applyToMesh(r),n.color&&(r.color=new t.Color3(n.color[0],n.color[1],n.color[2])),r.metadata=Object.assign(Object.assign({},null!==(s=r.metadata)&&void 0!==s?s:{}),{fbxCurveType:n.kind,fbxCurveSegments:n.polylines.length}),r}_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=Ao(n.positions),d=e.geometricTranslation,h=e.geometricRotation,p=e.geometricScaling,f=To._computeFBXGeometricMatrix(d,h,p),m=To._computeFBXGeometricDeltaMatrix(h,p),g=To._computeFBXGeometricNormalMatrix(h,p),_=!f.equals(t.Matrix.Identity()),v=!m.equals(t.Matrix.Identity()),y=!g.equals(t.Matrix.Identity());if(_)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=Ao(n.normals),y)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]),g);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=Ao(n.uvs)),n.uvSets.length>1&&(u.uvs2=Ao(n.uvSets[1].data)),n.uvSets.length>2&&(u.uvs3=Ao(n.uvSets[2].data)),n.uvSets.length>3&&(u.uvs4=Ao(n.uvSets[3].data)),n.uvSets.length>4&&(u.uvs5=Ao(n.uvSets[4].data)),n.uvSets.length>5&&(u.uvs6=Ao(n.uvSets[5].data)),n.tangents){const e=Ao(n.tangents);if(y)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]),g);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 p=e.length/3,f=new Map,m=new Array(p).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,p=3*c,g=2*l,_=2*u,v=2*c,y=e[h]-e[d],b=e[p]-e[d],x=e[h+1]-e[d+1],T=e[p+1]-e[d+1],A=e[h+2]-e[d+2],w=e[p+2]-e[d+2],M=n[_]-n[g],S=n[v]-n[g],R=n[_+1]-n[g+1],C=n[v+1]-n[g+1],I=M*C-S*R;if(Math.abs(I)<1e-8)continue;const O=1/I,F=(C*y-R*b)*O,E=(C*x-R*T)*O,N=(C*A-R*w)*O,L=(M*b-S*y)*O,k=(M*T-S*x)*O,P=(M*w-S*A)*O;wo(l,u,c,F,E,N,L,k,P,e,t,n,r,a,f,m),wo(u,c,l,F,E,N,L,k,P,e,t,n,r,a,f,m),wo(c,l,u,F,E,N,L,k,P,e,t,n,r,a,f,m)}const g=new Float32Array(4*p);for(let e=0;e<p;e++){const n=3*e,o=4*e,[r,i,p]=Mo(t[n],t[n+1],t[n+2]),_=m[e]?f.get(m[e]):void 0,v=null!==(a=null==_?void 0:_.tx)&&void 0!==a?a:0,y=null!==(l=null==_?void 0:_.ty)&&void 0!==l?l:0,b=null!==(u=null==_?void 0:_.tz)&&void 0!==u?u:0,x=r*v+i*y+p*b;let T=v-r*x,A=y-i*x,w=b-p*x;const M=Math.hypot(T,A,w);M>1e-8?(T/=M,A/=M,w/=M):[T,A,w]=Ro(r,i,p);const S=null!==(c=null==_?void 0:_.bx)&&void 0!==c?c:0,R=null!==(d=null==_?void 0:_.by)&&void 0!==d?d:0,C=null!==(h=null==_?void 0:_.bz)&&void 0!==h?h:0,I=i*w-p*A,O=p*T-r*w,F=r*A-i*T,E=Math.hypot(S,R,C)>1e-8&&I*S+O*R+F*C<0?-1:1;g[o]=T,g[o+1]=A,g[o+2]=w,g[o+3]=E*s}return g}(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:v?m:null,fbxGeometryNormalMatrix:y?g:null,fbxPreRotMatrix:v?m:null}),s&&(l.skeleton=s),l}_applyMultiMaterial(e,n,o,s,r,i){var a,l;const u=n.geometry.materialIndices,c=null===(a=e.metadata)||void 0===a?void 0:a.fbxSubMeshMaterialIndices;if(c){const a=new t.MultiMaterial(n.name+"_multi",s);for(const e of c){const t=n.materials[e],s=t?o.get(t.id):void 0;a.subMaterials.push(s?To._getModelMaterial(s,n,i,r.has(t.id)):null)}return void(e.material=a)}const d=e.getIndices();if(!d)return;const h=d.length/3,p=new Map;for(let e=0;e<h;e++){const t=e<u.length?u[e]:0;let n=p.get(t);n||(n=[],p.set(t,n)),n.push(e)}const f=Array.from(p.keys()).sort((e,t)=>e-t),m=[],g=[];for(const e of f){const t=p.get(e),n=m.length;for(const e of t)m.push(d[3*e],d[3*e+1],d[3*e+2]);g.push({start:n,count:3*t.length,matIdx:e})}e.setIndices(m);const _=new t.MultiMaterial(n.name+"_multi",s);for(const e of g){const t=n.materials[e.matIdx];if(t){const e=o.get(t.id);e?_.subMaterials.push(To._getModelMaterial(e,n,i,r.has(t.id))):_.subMaterials.push(null)}else _.subMaterials.push(null)}e.material=_,e.subMeshes=[];const v=e.getTotalVertices();for(let n=0;n<g.length;n++){const o=g[n];new t.SubMesh(n,0,v,o.start,o.count,e)}e.metadata=Object.assign(Object.assign({},null!==(l=e.metadata)&&void 0!==l?l:{}),{fbxSubMeshMaterialIndices:f})}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){var s;if(!t.cullingOff||!e.backFaceCulling)return e;if(!o)return e.backFaceCulling=!1,e;const r=null==n?void 0:n.get(e);if(r)return r;const i=null!==(s=e.clone(`${e.name}_CullingOff`))&&void 0!==s?s:e;return i.backFaceCulling=!1,null==n||n.set(e,i),i}_applyMaterialUVSetCoordinates(e,n){if(e)if(e instanceof t.MultiMaterial)for(const o of e.subMaterials)(o instanceof t.StandardMaterial||o instanceof t.PBRMaterial)&&this._applyStandardMaterialUVSetCoordinates(o,n);else(e instanceof t.StandardMaterial||e instanceof t.PBRMaterial)&&this._applyStandardMaterialUVSetCoordinates(e,n)}_applyStandardMaterialUVSetCoordinates(e,n){var o;for(const s of e instanceof t.PBRMaterial?[e.albedoTexture,e.bumpTexture,e.emissiveTexture,e.ambientTexture,e.metallicTexture,e.reflectivityTexture,e.microSurfaceTexture,e.opacityTexture,e.clearCoat.texture,e.clearCoat.bumpTexture,e.sheen.texture]:[e.diffuseTexture,e.bumpTexture,e.emissiveTexture,e.ambientTexture,e.specularTexture,e.opacityTexture,e.reflectionTexture]){if(!s)continue;const e=null===(o=s.metadata)||void 0===o?void 0:o.fbxUVSetName;if(!e)continue;const t=n.uvSets.findIndex(t=>t.name===e);t>=0&&(s.coordinatesIndex=t)}}_useUnmodulatedVertexColorMaterials(e,n){const o=e.material;if(!o)return;const s=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}if(e instanceof t.PBRMaterial&&!e.albedoTexture){const n=e.clone(`${e.name}_VertexColor`);return n.albedoColor=new t.Color3(1,1,1),n}return e};if(o instanceof t.MultiMaterial){const r=new t.MultiMaterial(`${o.name}_VertexColor`,n);return r.subMaterials=o.subMaterials.map(e=>e?s(e):e),void(e.material=r)}e.material=s(o)}_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,t,n){var o;const s=this._options.materials,r="pbr"===s||"auto"===s&&Tt(e.model.shaderType)?this._createPbrMaterial(e,t,n):this._createStandardMaterial(e,t,n);return r.metadata=Object.assign(Object.assign(Object.assign({},null!==(o=r.metadata)&&void 0!==o?o:{}),e.userProperties?{fbxUserProperties:e.userProperties}:{}),{fbxShaderType:e.model.shaderType,fbxFeatures:Object.fromEntries(Object.entries(e.model.features).map(([e,t])=>{var n;return[e,null!==(n=null==t?void 0:t.enabled)&&void 0!==n&&n]}))}),r}_createPbrMaterial(e,n,o){var s,r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b,x,T,A,w,M,S,R;const C=new t.PBRMaterial(e.name,n),I=e.model.pbr,O=e.model.features,F=e=>{var t,n;return null!==(n=null===(t=O[e])||void 0===t?void 0:t.enabled)&&void 0!==n&&n},E="3dsMaxPbrSpecGloss"===e.model.shaderType,N=(e,n)=>e?new t.Color3(e[0]*(null!=n?n:1),e[1]*(null!=n?n:1),e[2]*(null!=n?n:1)):void 0,L=St(I.baseColor);if(C.albedoColor=null!==(r=N(L,(null===(s=I.baseColor)||void 0===s?void 0:s.texture)?1:Rt(I.baseFactor)))&&void 0!==r?r:t.Color3.White(),E)C.metallic=null,C.roughness=null,C.reflectivityColor=null!==(i=N(St(I.specularColor),1))&&void 0!==i?i:t.Color3.White(),C.microSurface=null!==(a=Rt(I.glossiness))&&void 0!==a?a:1-(null!==(l=Rt(I.roughness))&&void 0!==l?l:.5);else if(C.metallic=F("metalness")&&null!==(u=Rt(I.metalness))&&void 0!==u?u:0,C.roughness=null!==(c=Rt(I.roughness))&&void 0!==c?c:(null===(d=I.glossiness)||void 0===d?void 0:d.value)?1-I.glossiness.value[0]:.5,F("specular")&&(null===(h=I.specularFactor)||void 0===h?void 0:h.value)&&(C.metallicF0Factor=null!==(p=Rt(I.specularFactor))&&void 0!==p?p:1),F("specular")){const e=St(I.specularColor);e&&(C.metallicReflectanceColor=new t.Color3(e[0],e[1],e[2]))}const k=N(St(I.emissionColor),(null===(f=I.emissionColor)||void 0===f?void 0:f.texture)?1:Rt(I.emissionFactor));(k&&F("emission")||k&&(k.r>0||k.g>0||k.b>0))&&(C.emissiveColor=k);const P=St(I.opacity);P&&F("opacity")?C.alpha=(P[0]+P[1]+P[2])/3:Tt(e.model.shaderType)||(C.alpha=To._alphaFromClassicTransparency(e)),C.alpha<1&&(C.transparencyMode=t.Material.MATERIAL_ALPHABLEND);const B=null!==(m=Rt(I.transmissionFactor))&&void 0!==m?m:0;if(F("transmission")&&Tt(e.model.shaderType)&&B>0){C.subSurface.isRefractionEnabled=!0,C.subSurface.refractionIntensity=B;const e=St(I.transmissionColor);e&&(C.subSurface.tintColor=new t.Color3(e[0],e[1],e[2]));const n=Rt(I.specularIor);n&&F("ior")&&(C.subSurface.indexOfRefraction=n)}else{const e=Rt(I.specularIor);e&&F("ior")&&e>1&&(C.indexOfRefraction=e)}const D=null!==(g=Rt(I.coatFactor))&&void 0!==g?g:0;if(F("coat")&&D>0||(null===(_=I.coatFactor)||void 0===_?void 0:_.texture)){C.clearCoat.isEnabled=!0,C.clearCoat.intensity=D;const e=Rt(I.coatRoughness);void 0!==e&&(C.clearCoat.roughness=e);const n=Rt(I.coatIor);void 0!==n&&n>1&&(C.clearCoat.indexOfRefraction=n);const o=St(I.coatColor);!o||1===o[0]&&1===o[1]&&1===o[2]||(C.clearCoat.isTintEnabled=!0,C.clearCoat.tintColor=new t.Color3(o[0],o[1],o[2]))}const V=null!==(v=Rt(I.sheenFactor))&&void 0!==v?v:0;if(F("sheen")&&V>0||(null===(y=I.sheenColor)||void 0===y?void 0:y.texture)){C.sheen.isEnabled=!0,C.sheen.intensity=V;const e=St(I.sheenColor);e&&(C.sheen.color=new t.Color3(e[0],e[1],e[2]));const n=Rt(I.sheenRoughness);void 0!==n&&(C.sheen.roughness=n)}F("unlit")&&(C.unlit=!0),F("doubleSided")&&(C.backFaceCulling=!1);const G=(e,t=!1)=>{if(!(null==e?void 0:e.texture)||!e.textureEnabled)return null;const s=To._createTexture(e.texture,n,o,t);return s&&To._applyTextureSettings(s,e.texture),s},$=G(I.baseColor);$&&(C.albedoTexture=$);const U=G(I.normalMap,!0);U&&(C.bumpTexture=U,this._configureNormalTexture(U,C));const H=G(I.emissionColor);H&&(C.emissiveTexture=H,(!k||0===k.r&&0===k.g&&0===k.b)&&(C.emissiveColor=t.Color3.White()));const K=G(I.ambientOcclusion);if(K&&(C.ambientTexture=K,C.useAmbientInGrayScale=!0),E){const e=G(I.specularColor);e&&(C.reflectivityTexture=e);const t=null!==(b=G(I.glossiness))&&void 0!==b?b:G(I.roughness);t&&(C.microSurfaceTexture=t)}else{const e=(null===(x=I.metalness)||void 0===x?void 0:x.textureEnabled)?I.metalness.texture:void 0,t=(null===(T=I.roughness)||void 0===T?void 0:T.textureEnabled)&&I.roughness.texture?I.roughness:(null===(A=I.glossiness)||void 0===A?void 0:A.textureEnabled)&&I.glossiness.texture?I.glossiness:void 0,n=null==t?void 0:t.texture,o=!!e&&!!n&&e.id===n.id;let s=!1;if(!e||!o&&n){if(n){const n=G(t);n&&(C.metallicTexture=n,C.useMetallnessFromMetallicTextureBlue=!1,C.useRoughnessFromMetallicTextureGreen=!0,C.useRoughnessFromMetallicTextureAlpha=!1,e&&(C.metadata=Object.assign(Object.assign({},null!==(w=C.metadata)&&void 0!==w?w:{}),{fbxDroppedMetalnessTexture:e.relativeFileName})))}}else{const e=G(I.metalness);e&&(s=!0,C.metallicTexture=e,C.useMetallnessFromMetallicTextureBlue=!0,C.useRoughnessFromMetallicTextureGreen=o,C.useRoughnessFromMetallicTextureAlpha=!1)}s&&0===C.metallic&&(C.metallic=1)}if((null===(M=I.opacity)||void 0===M?void 0:M.texture)&&I.opacity.textureEnabled)if($&&I.opacity.texture.id===(null===(R=null===(S=I.baseColor)||void 0===S?void 0:S.texture)||void 0===R?void 0:R.id))C.useAlphaFromAlbedoTexture=!0,C.transparencyMode=t.Material.MATERIAL_ALPHATESTANDBLEND;else{const e=G(I.opacity);e&&(C.opacityTexture=e,C.transparencyMode=t.Material.MATERIAL_ALPHATESTANDBLEND)}if(C.clearCoat.isEnabled){const e=G(I.coatFactor);e&&(C.clearCoat.texture=e);const t=G(I.coatNormal,!0);t&&(C.clearCoat.bumpTexture=t)}if(C.sheen.isEnabled){const e=G(I.sheenColor);e&&(C.sheen.texture=e)}return C}static _alphaFromClassicTransparency(e){const t=e.properties;if(void 0!==t.opacity)return t.opacity;const n=Rt(e.model.fbx.transparencyFactor);if(void 0===n)return 1;const o=St(e.model.fbx.transparencyColor),s=o?(o[0]+o[1]+o[2])/3:1;return Math.min(1,Math.max(0,1-s*n))}static _applyTextureSettings(e,n){var o;n.uvTranslation&&(e.uOffset=n.uvTranslation[0],e.vOffset=n.uvTranslation[1]),n.uvScaling&&(e.uScale=n.uvScaling[0],e.vScale=n.uvScaling[1]),void 0!==n.uvRotation&&(e.wAng=n.uvRotation*(Math.PI/180)),void 0!==n.uvSetIndex&&(e.coordinatesIndex=n.uvSetIndex),void 0!==n.wrapU&&(e.wrapU=1===n.wrapU?t.Texture.CLAMP_ADDRESSMODE:t.Texture.WRAP_ADDRESSMODE),void 0!==n.wrapV&&(e.wrapV=1===n.wrapV?t.Texture.CLAMP_ADDRESSMODE:t.Texture.WRAP_ADDRESSMODE),(n.uvSetName||void 0!==n.layeredTextureId)&&(e.metadata=Object.assign(Object.assign(Object.assign({},null!==(o=e.metadata)&&void 0!==o?o:{}),n.uvSetName?{fbxUVSetName:n.uvSetName}:{}),void 0!==n.layeredTextureId?{fbxLayeredTextureId:n.layeredTextureId}:{}))}_createStandardMaterial(e,n,o){var s,r,i,a;const l=new t.StandardMaterial(e.name,n),u=e.properties,c=(...t)=>e.textures.some(e=>t.includes(e.propertyName));if("Lambert"===e.type&&(l.specularColor=t.Color3.Black()),u.diffuseColor){const e=c("DiffuseColor","Diffuse")?1:null!==(s=u.diffuseFactor)&&void 0!==s?s:1;l.diffuseColor=new t.Color3(u.diffuseColor[0]*e,u.diffuseColor[1]*e,u.diffuseColor[2]*e)}if(u.ambientColor){const e=c("AmbientColor","Ambient")?1:null!==(r=u.ambientFactor)&&void 0!==r?r:1;l.ambientColor=new t.Color3(u.ambientColor[0]*e,u.ambientColor[1]*e,u.ambientColor[2]*e)}if("Phong"===e.type&&u.specularColor){const e=c("SpecularColor","Specular","Shininess","ShininessExponent")?1:null!==(i=u.specularFactor)&&void 0!==i?i:1;l.specularColor=new t.Color3(u.specularColor[0]*e,u.specularColor[1]*e,u.specularColor[2]*e)}if(u.emissiveColor){const e=c("EmissiveColor","Emissive")?1:null!==(a=u.emissiveFactor)&&void 0!==a?a:1;l.emissiveColor=new t.Color3(u.emissiveColor[0]*e,u.emissiveColor[1]*e,u.emissiveColor[2]*e)}l.alpha=To._alphaFromClassicTransparency(e),l.alpha<1&&(l.transparencyMode=t.Material.MATERIAL_ALPHABLEND),void 0!==u.shininess&&(l.specularPower=u.shininess);for(const s of e.textures){if(!To._isSupportedMaterialTextureSlot(s.propertyName))continue;const e=To._createTexture(s,n,o,To._isNormalMapTextureSlot(s.propertyName));if(e){switch(s.propertyName){case"DiffuseColor":l.diffuseTexture=e,l.diffuseColor=new t.Color3(1,1,1);break;case"NormalMap":case"NormalMapTexture":case"normalCamera":case"Bump":case"BumpFactor":l.bumpTexture=e,this._configureNormalTexture(e,l);break;case"EmissiveColor":l.emissiveTexture=e;break;case"AmbientColor":l.ambientTexture=e;break;case"SpecularColor":l.specularTexture=e;break;case"TransparencyFactor":case"TransparentColor":l.opacityTexture=e,l.transparencyMode=t.Material.MATERIAL_ALPHATESTANDBLEND;break;case"ReflectionColor":case"ReflectionFactor":l.reflectionTexture=e}To._applyTextureSettings(e,s)}}return l}_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=To._getTextureSourceName(e),i=To._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=To._getExternalTextureUrls(e,o),l=a.shift();return l?To._createExternalTexture(l,a,n,i):null}static _createExternalTexture(e,n,o,s){n.push(...To._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,To._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?To._getMimeType(e):"image/png":void 0;return{buffer:n?new Uint8Array(n):void 0,forcedExtension:e?To._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,"/");To._isSafeRelativeTexturePath(n)&&o.push(t+n);const s=To._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 To._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(To._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 p=new t.MorphTargetManager(o);p.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,m=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=Io(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=Co(u,s,r,i,f,m);if(!c)continue;const h=n.fullWeights&&n.shapes.length>1?`${n.name}_${n.fullWeights[e]}`:n.name,g=new t.MorphTarget(h,null!==(d=a[e])&&void 0!==d?d:0,o);g.setPositions(c.positions),c.normals&&g.setNormals(c.normals),l.push(p.numTargets),p.addTarget(g)}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}))}p.numTargets>0&&(p.numMaxInfluencers=p.numTargets,e.morphTargetManager=p)}}_createCamera(e,n,o){var s,r;const i=n.get(e.modelId),a=i?i.computeWorldMatrix(!0):t.Matrix.Identity(),l=t.Vector3.TransformCoordinates(t.Vector3.Zero(),a),u=new t.FreeCamera(e.name,l,o);if(u.fov=e.fieldOfView*(Math.PI/180),u.fovMode=t.Camera.FOVMODE_VERTICAL_FIXED,u.minZ=e.nearPlane,u.maxZ=e.farPlane,u.metadata=Object.assign(Object.assign({},null!==(s=u.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,fieldOfViewX:e.fieldOfViewX,apertureMode:e.apertureMode,apertureSizeInch:e.apertureSizeInch,userProperties:e.userProperties,unknownProperties:e.unknownProperties,diagnostics:e.diagnostics}}),"orthographic"===e.projectionType&&(u.mode=t.Camera.ORTHOGRAPHIC_CAMERA,u.orthoTop=e.orthographicSize[1]/2,u.orthoBottom=-e.orthographicSize[1]/2,u.orthoRight=e.orthographicSize[0]/2,u.orthoLeft=-e.orthographicSize[0]/2),i&&this._options.attachCamerasAndLights){let n=i;if(a.determinant()<0){const s=new t.TransformNode(`${e.name}__fbx_cameraPivot`,o);s.parent=i,s.scaling.set(1,1,-1),n=s}u.parent=n,u.position.set(0,0,0);const s=(null!==(r=e.roll)&&void 0!==r?r:0)*Math.PI/180;u.rotationQuaternion=t.Quaternion.FromRotationMatrix(t.Matrix.RotationZ(s).multiply(t.Matrix.RotationY(Math.PI/2)))}else{const e=t.Vector3.TransformCoordinates(new t.Vector3(1,0,0),a);u.setTarget(e)}return u}_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;const d=!!r&&this._options.attachCamerasAndLights,h=d?t.Vector3.Zero():a,p=d?new t.Vector3(0,0,-1):u;switch(e.lightType){case 1:c=new t.DirectionalLight(e.name,p,o),c.diffuse=l,c.intensity=e.intensity;break;case 2:{const n=e.coneAngle*(Math.PI/180);c=new t.SpotLight(e.name,h,p,n,2,o),c.diffuse=l,c.intensity=e.intensity,void 0!==e.innerAngle&&(c.innerAngle=Math.min(n,e.innerAngle*Math.PI/180));break}default:c=new t.PointLight(e.name,h,o),c.diffuse=l,c.intensity=e.intensity}return d&&r&&(c.parent=r,c.computeTransformedInformation()),c.specular=l,e.enableFarAttenuation&&void 0!==e.farAttenuationEnd&&e.farAttenuationEnd>0&&(c.range=e.farAttenuationEnd),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,farAttenuationStart:e.farAttenuationStart,farAttenuationEnd:e.farAttenuationEnd,areaLightShape:e.areaLightShape,userProperties:e.userProperties,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=[],d=To._computeBoneInheritScales(n,n.map(e=>e.scale));for(let e=0;e<n.length;e++){const t=n[e],o=To._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]=To._computeFBXRuntimeLocalMatrix(n,o,e,d)}u.push(...To._computeFBXAbsoluteMatrices(n,c));const h=n.map((e,n)=>e.transformLinkMatrix?t.Matrix.FromArray(e.transformLinkMatrix):e.modelBindPoseMatrix?t.Matrix.FromArray(e.modelBindPoseMatrix):u[n]),p=h.map((e,o)=>{const s=n[o].parentIndex;if(s<0)return e;const r=new t.Matrix;return h[s].invertToRef(r),e.multiply(r)}),f=To._shouldUseBindMatricesAsRest(n,l,p),m=To._computeBoneInheritScales(n,n.map(e=>e.scale));for(let e=0;e<n.length;e++){let o=f?p[e]:c[e],u=n[e].parentIndex>=0?i[n[e].parentIndex]:null;if(!f&&1!==n[e].inheritType&&n[e].parentIndex>=0&&u){const i=To._splitParentScaleCompensatedLocalMatrix(l[e],m[n[e].parentIndex],To._getBoneInheritedScale(n,e,m)),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,f?o.clone():null,f?o.clone():null,e);f&&n[e].isCluster&&To._getMaxScaleRatio(l[e],p[e])>=10&&this._bindRestBones.add(d),i.push(d)}if(this._sourceBonesBySkeleton.set(r,i),this._scaleCompensationHelpersBySkeleton.set(r,a),!f){for(let e=0;e<n.length;e++)i[e].updateMatrix(p[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}_isRigBone(e){return this._rigBoneModelIds.has(e)}_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 _computeBoneInheritScales(e,t){const n=[];for(let o=0;o<e.length;o++){const s=t[o],r=To._getBoneInheritScaleNode(e,o);if(r<0||r>=o)n[o]=[s[0],s[1],s[2]];else{const e=n[r];n[o]=[s[0]*e[0],s[1]*e[1],s[2]*e[2]]}}return n}static _getBoneInheritScaleNode(e,t){const n=e[t].parentIndex;return n<0?-1:0===e[t].inheritType?n:2===e[t].inheritType?To._getBoneInheritScaleNode(e,n):-1}static _getBoneInheritedScale(e,t,n){const o=To._getBoneInheritScaleNode(e,t);return o>=0?n[o]:[1,1,1]}static _computeFBXRuntimeLocalMatrix(e,t,n,o){const s=e[n].parentIndex;if(1===e[n].inheritType||s<0)return t;const r=null!=o?o:To._computeBoneInheritScales(e,e.map(e=>e.scale));return To._applyParentScaleCompensation(t,r[s],To._getBoneInheritedScale(e,n,r))}static _applyParentScaleCompensation(e,t,n){const o=To._splitParentScaleCompensatedLocalMatrix(e,t,n);return o.boneLocalMatrix.multiply(o.helperLocalMatrix)}static _splitParentScaleCompensatedLocalMatrix(e,n,o){const s=e.getTranslation();let r=e.clone();return r.setTranslation(t.Vector3.Zero()),!o||1===o[0]&&1===o[1]&&1===o[2]||(r=t.Matrix.Scaling(o[0],o[1],o[2]).multiply(r)),{boneLocalMatrix:r,helperLocalMatrix:t.Matrix.Compose(To._getInverseScaleVector(n),t.Quaternion.Identity(),s)}}static _safeInverseScale(e){return Math.abs(e)>1e-8?1/e:1}static _getInverseScaleVector(e){return new t.Vector3(To._safeInverseScale(e[0]),To._safeInverseScale(e[1]),To._safeInverseScale(e[2]))}static _shouldUseBindMatricesAsRest(e,t,n){return e.some((e,o)=>!!e.isCluster&&To._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(To._getScaleRatio(o.x,i.x),To._getScaleRatio(o.y,i.y),To._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 mo(n,o).multiply(s)}(e,n,o)}static _computeFBXGeometricDeltaMatrix(e,t){return mo(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=po(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,p=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],m=0!==i[0]||0!==i[1]||0!==i[2];if(!p&&!f&&!m){const e=po(r[0]*h,r[1]*h,r[2]*h),i=fo(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 g=t.Matrix.Translation(n[0],n[1],n[2]),_=t.Matrix.Translation(u[0],u[1],u[2]),v=t.Matrix.Translation(a[0],a[1],a[2]),y=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=po(r[0]*h,r[1]*h,r[2]*h),w=fo(o[0]*h,o[1]*h,o[2]*h,d),M=t.Matrix.Scaling(s[0],s[1],s[2]);let S;if(m){const e=po(i[0]*h,i[1]*h,i[2]*h);S=new t.Matrix,e.invertToRef(S)}else S=t.Matrix.Identity();let R=T;return R=R.multiply(M),R=R.multiply(x),R=R.multiply(b),R=R.multiply(y),R=R.multiply(S),R=R.multiply(w),R=R.multiply(A),R=R.multiply(v),R=R.multiply(_),R=R.multiply(g),R}({translation:e,rotation:n,scale:o,preRotation:s,postRotation:r,rotationPivot:i,scalingPivot:a,rotationOffset:l,scalingOffset:u,rotationOrder:c})}_applyRestTRS(e,t){const n=To._computeLocalTRS(t,t.translation,t.rotation,t.scale);this._adjustTRSForInheritMode(t,n,void 0),e.position=n.position,e.rotationQuaternion=n.rotationQuaternion,e.scaling=n.scaling}static _computeFBXModelLocalMatrix(e){return To._computeFBXLocalMatrix(e.translation,e.rotation,e.scale,e.preRotation,e.postRotation,e.rotationPivot,e.scalingPivot,e.rotationOffset,e.scalingOffset,e.rotationOrder)}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,l){var u,c;if(0===e.curveNodes.length&&!e.unsupportedCurveNodes.some(e=>null!==e.targetId&&e.curves.length>0))return null;this._activeLayers=e.layers,this._curveNodesByModelId=new Map;for(const t of e.curveNodes){if("DeformPercent"===t.type)continue;const e=this._curveNodesByModelId.get(t.targetModelId);e?e.push(t):this._curveNodesByModelId.set(t.targetModelId,[t])}const d=new t.AnimationGroup(e.name,s),h=new Map,p=(e,t)=>{var n;const o=null!==(n=t.getTransformNode())&&void 0!==n?n:t;let s=h.get(o);if(s){if(s.has(e.targetProperty))return}else s=new Set,h.set(o,s);s.add(e.targetProperty),d.addTargetedAnimation(e,o)},f=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=f.get(n.modelId);o?o.push(e):f.set(n.modelId,[e])}}const m=new Map,g=new Map,_=[];for(const t of e.curveNodes)"DeformPercent"!==t.type?f.has(t.targetModelId)?(m.has(t.targetModelId)||m.set(t.targetModelId,[]),m.get(t.targetModelId).push(t)):(g.has(t.targetModelId)||g.set(t.targetModelId,[]),g.get(t.targetModelId).push(t)):_.push(t);const v=new Set;for(const t of n){const n=new Set(t.bones.filter(e=>1!==e.inheritType&&e.parentIndex>=0).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))v.add(e);for(const{bone:o,animations:r}of this._buildInheritedRigBoneAnimations(t,s,m,i,n,e.startTime,e.stopTime))for(const e of r)p(e,o)}}for(const[t,n]of Array.from(m)){if(v.has(t))continue;const o=f.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)p(e,t)}}for(const[t,n]of Array.from(g)){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)d.addTargetedAnimation(e,o)}for(const[n,o]of Array.from(this._inheritScaleHelpers)){const s=i.get(n),a=s?this._parentModelById.get(n):void 0;if(!s||!a)continue;const l=this._frameRate,c=[...null!==(u=this._curveNodesByModelId.get(a.id))&&void 0!==u?u:[],...this._collectInheritScaleCurves(a).filter(e=>e.targetModelId!==a.id)];if(c.length>0){const n=Lo(c,l,e.startTime,e.stopTime),s=e=>{var t;return this._computeInheritAwareLocalMatrix(a,this._sampleModelLocalMatrix(a,null!==(t=this._curveNodesByModelId.get(a.id))&&void 0!==t?t:[],e),e)},r=To._refineSampleTimes(n,s),i=[],u=[];let h=null;for(const e of r){const n=new t.Vector3,o=new t.Quaternion,r=new t.Vector3;s(e).decompose(n,o,r),h&&t.Quaternion.Dot(h,o)<0&&o.scaleInPlace(-1),h=o,i.push({frame:e*l,value:r}),u.push({frame:e*l,value:o})}if(!this._isVector3KeysConstant(i)){const e=new t.Animation(`${o.name}_position`,"position",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(i),d.addTargetedAnimation(e,o)}if(!ko(u)){const e=new t.Animation(`${o.name}_rotation`,"rotationQuaternion",l,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(u),d.addTargetedAnimation(e,o)}}const h=this._collectInheritScaleCurves(a),p=r.get(n);if(p&&h.length>0&&!g.has(n)&&!m.has(n))for(const t of this._buildNodeAnimations([],p.name,s,e.startTime,e.stopTime,h))d.addTargetedAnimation(t,p)}const y=new Map;for(const e of _){const t=y.get(e.targetModelId);t?t.push(e):y.set(e.targetModelId,[e])}for(const[n,o]of Array.from(y)){o.sort((e,t)=>e.layerIndex-t.layerIndex);const s=o.filter(e=>e.curves.length>0).map(e=>({layerIndex:e.layerIndex,curves:e.curves}));if(0===s.length)continue;let r=!1;for(const o of a){if(!o.morphTargetManager||r)continue;const i=o.metadata,a=null==i?void 0:i.fbxBlendShapeChannelTargets,l=null==a?void 0:a.get(n);if(l){const n=this._frameRate;for(let r=0;r<l.targetIndices.length;r++){const i=o.morphTargetManager.getTarget(l.targetIndices[r]);if(!i)continue;const a=new t.Animation(`${i.name}_influence`,"influence",n,t.Animation.ANIMATIONTYPE_FLOAT,t.Animation.ANIMATIONLOOPMODE_CYCLE),u=this._layeredScalarKeys(s,e,e=>{var t;return null!==(t=Io(e,l.fullWeights,l.targetIndices.length)[r])&&void 0!==t?t:0});a.setKeys(u),d.addTargetedAnimation(a,i)}r=!0;continue}const u=null==i?void 0:i.fbxBlendShapeChannelIds;if(!u)continue;const c=u.get(n);if(void 0===c)continue;const h=o.morphTargetManager.getTarget(c);if(h){const n=this._frameRate,o=new t.Animation(`${h.name}_influence`,"influence",n,t.Animation.ANIMATIONTYPE_FLOAT,t.Animation.ANIMATIONLOOPMODE_CYCLE);o.setKeys(this._layeredScalarKeys(s,e,e=>e/100)),d.addTargetedAnimation(o,h),r=!0}}}const b=new Map;for(const t of e.unsupportedCurveNodes){if(null===t.targetId||0===t.curves.length)continue;const e=`${t.targetId}|${null!==(c=t.propertyName)&&void 0!==c?c:t.type}`,n=b.get(e);n?n.push(t):b.set(e,[t])}for(const t of Array.from(b.values())){t.sort((e,t)=>e.layerIndex-t.layerIndex);const n=this._buildPropertyAnimations(t,e,r,l);if(n.length>0)for(const e of t)this._evaluatedCurveNodeIds.add(e.id);for(const{animation:e,target:t}of n)d.addTargetedAnimation(e,t)}return d.targetedAnimations.length>0?(d.normalize(e.startTime*this._frameRate,e.stopTime*this._frameRate),d):(d.dispose(),null)}_buildInheritedRigBoneAnimations(e,n,o,s,r,i,a){var l;const u=this._frameRate,c=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)c.add(e.bones[n].modelId);const d=e.bones.filter(e=>c.has(e.modelId)).flatMap(e=>{var t;return null!==(t=o.get(e.modelId))&&void 0!==t?t:[]});let h=Lo(d,u,i,a);if(0===h.length)return[];for(const t of e.bones){const e=s.get(t.modelId),n=null!==(l=o.get(t.modelId))&&void 0!==l?l:[];c.has(t.modelId)&&e&&0!==n.length&&(h=To._refineSampleTimes(h,t=>this._sampleModelLocalMatrix(e,n,t)))}const p=e.bones.map(()=>({posKeys:[],rotKeys:[],sclKeys:[],prevQuat:null})),f=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=To._computeFBXModelLocalMatrix(i),l=new t.Matrix;return a.invertToRef(l),l});for(const i of h){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}),l=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=To._computeBoneInheritScales(e.bones,l),d=i*u;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?c[n]:e.bones[t].scale,s=To._splitParentScaleCompensatedLocalMatrix(a[t],o,To._getBoneInheritedScale(e.bones,t,c));To._pushMatrixKeys(p[t],d,s.boneLocalMatrix),To._pushMatrixKeys(f[t],d,s.helperLocalMatrix)}}const g=[];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:l}=p[o],c=[];if(!this._isVector3KeysConstant(i)){const e=new t.Animation(`${s.name}_position`,"position",u,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(i),c.push(e)}if(!ko(a)){const e=new t.Animation(`${s.name}_rotation`,"rotationQuaternion",u,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(a),c.push(e)}if(!this._isVector3KeysConstant(l)){const e=new t.Animation(`${s.name}_scaling`,"scaling",u,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(l),c.push(e)}c.length>0&&g.push({bone:s,animations:c});const d=this._getScaleCompensationHelper(n,o);if(!d)continue;const h=[],{posKeys:m,rotKeys:_,sclKeys:v}=f[o];if(!this._isVector3KeysConstant(m)){const e=new t.Animation(`${d.name}_position`,"position",u,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(m),h.push(e)}if(!ko(_)){const e=new t.Animation(`${d.name}_rotation`,"rotationQuaternion",u,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(_),h.push(e)}if(!this._isVector3KeysConstant(v)){const e=new t.Animation(`${d.name}_scaling`,"scaling",u,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(v),h.push(e)}h.length>0&&g.push({bone:d,animations:h})}return g}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,i=[]){const a=this._frameRate,l=e.find(e=>"R"===e.type),u=Lo([...e,...i],a,s,r);if(0===u.length)return[];const c=t=>{const n=this._sampleModelTRS(o,e,t),s=To._computeLocalTRS(o,n.translation,n.rotation,n.scale);return this._adjustTRSForInheritMode(o,s,t),s},d=To._refineSampleTimes(u,e=>{const n=c(e);return t.Matrix.Compose(n.scaling,n.rotationQuaternion,n.position)}),h=[],p=[],f=[];let m=null;for(const n of d){const o=n*a,s=c(n),r=s.scaling,i=s.rotationQuaternion,l=s.position,u=Hn(e,"T",n),d=Hn(e,"R",n),g=Hn(e,"S",n);m&&t.Quaternion.Dot(m,i)<0&&i.scaleInPlace(-1),m=i,h.push(u?{frame:o,value:l,interpolation:1}:{frame:o,value:l}),p.push(d?{frame:o,value:i,interpolation:1}:{frame:o,value:i}),f.push(g?{frame:o,value:r,interpolation:1}:{frame:o,value:r})}const g=[];if(!this._isVector3KeysConstant(h)){const e=new t.Animation(`${n}_position`,"position",a,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(h),g.push(e)}if(l){const e=new t.Animation(`${n}_rotation`,"rotationQuaternion",a,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(p),g.push(e)}if(!this._isVector3KeysConstant(f)){const e=new t.Animation(`${n}_scaling`,"scaling",a,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(f),g.push(e)}return g}static _refineSampleTimes(e,n,o=2){const s=e=>{const o=new t.Vector3,s=new t.Quaternion,r=new t.Vector3;return n(e).decompose(o,s,r),{s:o,r:s,t:r}},r=[],i=(e,n,a,l,u)=>{if(u>=o)return;const c=.5*(e+n);if(!(c>e&&c<n))return;const d=s(c),h=t.Vector3.Lerp(a.t,l.t,.5),p=t.Vector3.Lerp(a.s,l.s,.5),f=t.Quaternion.Slerp(a.r,l.r,.5),m=t.Vector3.Distance(h,d.t),g=t.Vector3.Distance(p,d.s),_=Math.min(1,Math.abs(t.Quaternion.Dot(f,d.r))),v=2*Math.acos(_),y=1e-4*(1+Math.max(Math.abs(d.t.x),Math.abs(d.t.y),Math.abs(d.t.z))),b=1e-4*(1+Math.max(Math.abs(d.s.x),Math.abs(d.s.y),Math.abs(d.s.z)));(m>y||g>b||v>5e-4)&&(i(e,c,a,d,u+1),r.push(c),i(c,n,d,l,u+1))};let a=e.length>0?s(e[0]):null;for(let t=0;t<e.length;t++)if(r.push(e[t]),t+1<e.length&&a){const n=s(e[t+1]);i(e[t],e[t+1],a,n,0),a=n}return r}_layeredScalarKeys(e,t,n){const o=this._frameRate;if(0===e.length)return[];if(1===e.length)return Po(e[0].curves[0],o,t.startTime,t.stopTime,n);const s=e[0].curves[0].channel;return Lo(e.map(e=>({type:"other",targetModelId:0,curves:Array.from(e.curves),layerIndex:e.layerIndex})),o,t.startTime,t.stopTime).map(r=>({frame:r*o,value:n(Un(e,t.layers,[s],[0],r)[0])}))}_buildPropertyAnimations(e,n,o,s){var r,i,a,l,u,c,d,h,p,f,m,g;const _=this._frameRate,v=e[0],y=null!==(r=v.propertyName)&&void 0!==r?r:v.type,b=v.targetId,x=[],T=null!==(i=v.curves.find(e=>"d|X"===e.channel))&&void 0!==i?i:v.curves[0],A=v.defaultValues,w=e.length>1,M=e.map(e=>({layerIndex:e.layerIndex,curves:e.curves,defaultValues:e.defaultValues})),S=()=>Lo(e.map(e=>({type:"other",targetModelId:b,curves:e.curves,layerIndex:e.layerIndex})),_,n.startTime,n.stopTime),R=e=>{const t=v.curves.find(e=>"d|X"===e.channel),o=v.curves.find(e=>"d|Y"===e.channel),s=v.curves.find(e=>"d|Z"===e.channel);return S().map(r=>{var i,a,l;return{frame:r*_,values:w?Un(M,n.layers,["d|X","d|Y","d|Z"],e,r):[null!==(i=In(t,r))&&void 0!==i?i:e[0],null!==(a=In(o,r))&&void 0!==a?a:e[1],null!==(l=In(s,r))&&void 0!==l?l:e[2]]}})},C=(e,t=!1)=>{const o=w?S().map(t=>{var o;return{frame:t*_,value:e(Un(M,n.layers,[T.channel],[null!==(o=A[T.channel])&&void 0!==o?o:0],t)[0])}}):Po(T,_,n.startTime,n.stopTime,e);if(t)for(const e of o)e.interpolation=1,delete e.inTangent,delete e.outTangent;return o},I=()=>{var e,n,o;return R([null!==(e=A["d|X"])&&void 0!==e?e:1,null!==(n=A["d|Y"])&&void 0!==n?n:1,null!==(o=A["d|Z"])&&void 0!==o?o:1]).map(({frame:e,values:n})=>({frame:e,value:new t.Color3(n[0],n[1],n[2])}))},O=(e,n,o,s,r)=>{if(0===s.length)return;const i=new t.Animation(`${r}_${n}`,n,_,o,t.Animation.ANIMATIONLOOPMODE_CYCLE);i.setKeys(s),x.push({animation:i,target:e})},F=o.get(b);if(F){if("Visibility"===y&&F instanceof t.Mesh)return O(F,"visibility",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>Math.min(1,Math.max(0,e)),!0),F.name),x;const e=null===(a=F.metadata)||void 0===a?void 0:a.fbxUserProperties;if(e&&y in e)if(v.curves.some(e=>"d|Y"===e.channel||"d|Z"===e.channel)){const n=e[y],o=Array.isArray(n)?n:[0,0,0];e[y]=new t.Vector3(null!==(l=o[0])&&void 0!==l?l:0,null!==(u=o[1])&&void 0!==u?u:0,null!==(c=o[2])&&void 0!==c?c:0);const s=R([null!==(d=o[0])&&void 0!==d?d:0,null!==(h=o[1])&&void 0!==h?h:0,null!==(p=o[2])&&void 0!==p?p:0]).map(({frame:e,values:n})=>({frame:e,value:new t.Vector3(n[0],n[1],n[2])}));O(F,`metadata.fbxUserProperties.${y}`,t.Animation.ANIMATIONTYPE_VECTOR3,s,F.name)}else"boolean"==typeof e[y]&&(e[y]=e[y]?1:0),O(F,`metadata.fbxUserProperties.${y}`,t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e),F.name);return x}const E=s.cameraByAttributeId.get(b);if(E){const e=null===(f=E.metadata)||void 0===f?void 0:f.fbxCamera,n=(null==e?void 0:e.aspectRatio)||1,o=null!==(m=null==e?void 0:e.apertureMode)&&void 0!==m?m:2;switch(y){case"FieldOfView":O(E,"fov",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>1===o?2*Math.atan(Math.tan(e*Math.PI/360)/n):e*Math.PI/180),E.name);break;case"FieldOfViewY":O(E,"fov",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e*Math.PI/180),E.name);break;case"FieldOfViewX":0!==o&&O(E,"fov",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>2*Math.atan(Math.tan(e*Math.PI/360)/n)),E.name);break;case"FocalLength":{const n=null===(g=null==e?void 0:e.apertureSizeInch)||void 0===g?void 0:g[1];n&&3===o&&O(E,"fov",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>2*Math.atan(n/Math.max(e/25.4,1e-6)*.5)),E.name);break}case"NearPlane":O(E,"minZ",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e),E.name);break;case"FarPlane":O(E,"maxZ",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e),E.name)}return x}const N=s.lightByAttributeId.get(b);if(N){switch(y){case"Intensity":O(N,"intensity",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e/100),N.name);break;case"Color":O(N,"diffuse",t.Animation.ANIMATIONTYPE_COLOR3,I(),N.name);break;case"OuterAngle":case"ConeAngle":N instanceof t.SpotLight&&O(N,"angle",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e*Math.PI/180),N.name);break;case"InnerAngle":N instanceof t.SpotLight&&O(N,"innerAngle",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e*Math.PI/180),N.name)}return x}const L=s.materialCache.get(b);if(L){const e=L instanceof t.PBRMaterial,n=y.substring(y.lastIndexOf("|")+1);return"DiffuseColor"===y||"Diffuse"===y||"baseColor"===n||"base_color"===n||"color"===n?O(L,e?"albedoColor":"diffuseColor",t.Animation.ANIMATIONTYPE_COLOR3,I(),L.name):"EmissiveColor"===y||"Emissive"===y||"emissionColor"===n||"emission_color"===n||"emissive"===n||"emit_color"===n?O(L,"emissiveColor",t.Animation.ANIMATIONTYPE_COLOR3,I(),L.name):"Opacity"===y?O(L,"alpha",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e),L.name):"TransparencyFactor"===y||"TransparentFactor"===y?O(L,"alpha",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>1-e),L.name):!e||"roughness"!==n&&"specular_roughness"!==n&&"specularRoughness"!==n?!e||"metalness"!==n&&"metallic"!==n&&"base_metalness"!==n?e||"SpecularColor"!==y||O(L,"specularColor",t.Animation.ANIMATIONTYPE_COLOR3,I(),L.name):O(L,"metallic",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e),L.name):O(L,"roughness",t.Animation.ANIMATIONTYPE_FLOAT,C(e=>e),L.name),x}return x}_applyConstraints(e,n,o,s){var r,i,a,l,u;const c=e=>{var t;return void 0===e||null===(t=n.get(e))||void 0===t?void 0:t.name},d=e.upAxisSign>=0?1:-1,h=new t.Vector3(0===e.upAxis?d:0,1===e.upAxis?d:0,2===e.upAxis?d:0),p=[];for(const s of e.constraints){const e=Object.assign({name:s.name,type:s.type,node:c(s.nodeId),targets:s.targets.map(e=>({node:c(e.modelId),weight:e.weight})),weight:s.weight,active:s.active},"singleChainIK"===s.type?{firstJoint:c(s.ikFirstJointId),endJoint:c(s.ikEndJointId),effector:c(s.ikEffectorId)}:{});p.push(e);const u=void 0!==s.nodeId?n.get(s.nodeId):void 0;if(!u)continue;const d=null!==(i=null===(r=u.metadata)||void 0===r?void 0:r.fbxConstraints)&&void 0!==i?i:[];if(u.metadata=Object.assign(Object.assign({},null!==(a=u.metadata)&&void 0!==a?a:{}),{fbxConstraints:[...d,e]}),"apply"!==this._options.constraints||"singleChainIK"===s.type||"unknown"===s.type)continue;const f=[];for(const e of s.targets){const o=n.get(e.modelId);if(!o)continue;const r=Math.PI/180,i="parent"===s.type?t.Matrix.Compose(new t.Vector3(...e.offsetScale),t.Quaternion.FromRotationMatrix(po(e.offsetRotation[0]*r,e.offsetRotation[1]*r,e.offsetRotation[2]*r)),new t.Vector3(...e.offsetTranslation)):t.Matrix.Identity();f.push({node:o,weight:e.weight,offset:i})}if(0===f.length)continue;const m=void 0!==s.worldUpNodeId&&null!==(l=n.get(s.worldUpNodeId))&&void 0!==l?l:null;u.addBehavior(new bo(s,{root:o,targets:f,upNode:m,sceneUp:h}))}p.length>0&&(o.metadata=Object.assign(Object.assign({},null!==(u=o.metadata)&&void 0!==u?u:{}),{fbxConstraints:p}))}_reportDiagnostics(e,t,n){var o,s;const r=[],i=(e,t,n)=>{var o;const s="string"==typeof t?t:null!==(o=null==t?void 0:t.message)&&void 0!==o?o:JSON.stringify(t);r.push({source:e,message:s,objectName:n,details:"string"==typeof t?void 0:t})};for(const t of e.diagnostics)"duplicate-parent"!==t.subType&&i("scene",t,null!==(o=t.objectName)&&void 0!==o?o:t.nodeName);for(const t of e.geometries)for(const e of t.diagnostics)i("geometry",e,t.name);for(const t of e.curves)for(const e of t.diagnostics)i("geometry",e,t.name);for(const t of e.skins){for(const e of t.diagnostics)i("skin",e);for(const e of t.bones)for(const t of e.diagnostics)i("skin",t,e.name)}for(const t of e.rigs)for(const e of t.warnings)i("rig",e);for(const t of e.animations)for(const e of t.diagnostics)"unsupported-curve-node"===e.type&&void 0!==e.curveNodeId&&this._evaluatedCurveNodeIds.has(e.curveNodeId)||i("animation",e,t.name);for(const t of e.cameras)for(const e of t.diagnostics)i("camera",e,t.name);for(const t of e.lights)for(const e of t.diagnostics)i("light",e,t.name);const a=e=>{for(const t of e){for(const e of t.diagnostics)i("model",e,t.name);a(t.children)}};a(e.rootModels),t.metadata=Object.assign(Object.assign({},null!==(s=t.metadata)&&void 0!==s?s:{}),{fbxDiagnostics:r,fbxDisplayLayers:e.displayLayers.map(e=>({name:e.name,show:e.show,freeze:e.freeze,color:e.color})),fbxSelectionSets:e.selectionSets.map(e=>({name:e.name,members:e.members.map(e=>{var t,o;return Object.assign(Object.assign(Object.assign({node:null!==(o=null===(t=n.get(e.modelId))||void 0===t?void 0:t.name)&&void 0!==o?o:String(e.modelId),includeNode:e.includeNode},e.vertices?{vertices:e.vertices}:{}),e.edges?{edges:e.edges}:{}),e.faces?{faces:e.faces}:{})})}))});for(const e of r)this._options.onWarning(e)}_collectInheritScaleCurves(e){var t;const n=[];let o=e;const s=new Set;for(;o&&!s.has(o.id);){s.add(o.id);for(const e of null!==(t=this._curveNodesByModelId.get(o.id))&&void 0!==t?t:[])"S"===e.type&&n.push(e);o=this._getInheritScaleNode(o)}return n}_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}_sampleModelTRS(e,t,n){const o=this._activeLayers;return{translation:$n(t,o,"T",e.translation,e.rotationOrder,n),rotation:$n(t,o,"R",e.rotation,e.rotationOrder,n),scale:$n(t,o,"S",e.scale,e.rotationOrder,n)}}static _computeLocalTRS(e,n,o,s){const r=e=>0!==e[0]||0!==e[1]||0!==e[2],i=Math.PI/180;let a=fo(o[0]*i,o[1]*i,o[2]*i,e.rotationOrder);if(r(e.preRotation)&&(a=a.multiply(po(e.preRotation[0]*i,e.preRotation[1]*i,e.preRotation[2]*i))),r(e.postRotation)){const n=po(e.postRotation[0]*i,e.postRotation[1]*i,e.postRotation[2]*i),o=new t.Matrix;n.invertToRef(o),a=o.multiply(a)}let l=new t.Vector3(n[0],n[1],n[2]);return(r(e.rotationPivot)||r(e.scalingPivot)||r(e.rotationOffset)||r(e.scalingOffset))&&(l=To._computeFBXLocalMatrix(n,o,s,e.preRotation,e.postRotation,e.rotationPivot,e.scalingPivot,e.rotationOffset,e.scalingOffset,e.rotationOrder).getTranslation()),{position:l,rotationQuaternion:t.Quaternion.FromRotationMatrix(a),scaling:new t.Vector3(s[0],s[1],s[2])}}_adjustTRSForInheritMode(e,t,n){const o=this._parentModelById.get(e.id);if(1===e.inheritType||!o)return;const s=this._getInheritScale(o,n);t.position.x*=s[0],t.position.y*=s[1],t.position.z*=s[2];const r=this._getInheritScaleNode(e);if(r){const e=this._getInheritScale(r,n);t.scaling.x*=e[0],t.scaling.y*=e[1],t.scaling.z*=e[2]}}_sampleModelLocalMatrix(e,t,n,o){const s=this._sampleModelTRS(e,t,n);return To._computeFBXLocalMatrix(s.translation,s.rotation,null!=o?o:s.scale,e.preRotation,e.postRotation,e.rotationPivot,e.scalingPivot,e.rotationOffset,e.scalingOffset,e.rotationOrder)}_sampleModelScale(e,t,n){return $n(t,this._activeLayers,"S",e.scale,e.rotationOrder,n)}_getInheritScale(e,t){var n;if(!e)return[1,1,1];const o=void 0===t?e.scale:this._sampleModelScale(e,null!==(n=this._curveNodesByModelId.get(e.id))&&void 0!==n?n:[],t),s=this._getInheritScaleNode(e);if(!s)return[o[0],o[1],o[2]];const r=this._getInheritScale(s,t);return[o[0]*r[0],o[1]*r[1],o[2]*r[2]]}_getInheritScaleNode(e){const t=this._parentModelById.get(e.id);if(t)return 0===e.inheritType?t:2===e.inheritType?this._getInheritScaleNode(t):void 0}_computeInheritAwareLocalMatrix(e,n,o){const s=this._parentModelById.get(e.id);if(1===e.inheritType||!s)return n;const r=new t.Vector3,i=new t.Quaternion,a=new t.Vector3;n.decompose(r,i,a);const l=this._getInheritScale(s,o);a.x*=l[0],a.y*=l[1],a.z*=l[2];const u=this._getInheritScaleNode(e);if(u){const e=this._getInheritScale(u,o);r.x*=e[0],r.y*=e[1],r.z*=e[2]}return t.Matrix.Compose(r,i,a)}_buildBoneAnimations(e,n,o,s,r,i){const a=this._frameRate,l=e.find(e=>"R"===e.type),u=Lo(e,a,s,r);if(0===u.length)return[];const c=To._refineSampleTimes(u,t=>this._sampleModelLocalMatrix(o,e,t)),d=[],h=[],p=[];let f=null,m=null;if(i){const e=To._computeFBXLocalMatrix(o.translation,o.rotation,o.scale,o.preRotation,o.postRotation,o.rotationPivot,o.scalingPivot,o.rotationOffset,o.scalingOffset,o.rotationOrder);m=new t.Matrix,e.invertToRef(m)}for(const n of c){const s=n*a,r=this._sampleModelLocalMatrix(o,e,n),l=m&&i?i.multiply(m).multiply(r):r,u=new t.Vector3,c=new t.Quaternion,g=new t.Vector3;l.decompose(u,c,g),f&&t.Quaternion.Dot(f,c)<0&&c.scaleInPlace(-1),f=c,d.push({frame:s,value:g}),h.push({frame:s,value:c}),p.push({frame:s,value:u})}const g=[];if(!this._isVector3KeysConstant(d)){const e=new t.Animation(`${n}_position`,"position",a,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(d),g.push(e)}if(l){const e=new t.Animation(`${n}_rotation`,"rotationQuaternion",a,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(h),g.push(e)}if(!this._isVector3KeysConstant(p)){const e=new t.Animation(`${n}_scaling`,"scaling",a,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(p),g.push(e)}return g}_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 Ao(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}function wo(e,t,n,o,s,r,i,a,l,u,c,d,h,p,f,m){var g;const _=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],p=Math.hypot(a,l,u),f=Math.hypot(c,d,h);if(p<=1e-8||f<=1e-8)return 0;const m=(a*c+l*d+u*h)/(p*f);return Math.acos(Math.max(-1,Math.min(1,m)))}(u,e,t,n);if(_<=1e-8)return;const v=function(e,t,n,o,s,r,i,a,l,u,c,d){const h=3*e,p=3*e,f=2*e,[m,g,_]=Mo(l[p],l[p+1],l[p+2]),v=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}(m,g,_,t,n,o,s,r,i);return[c?`cp:${c[e]}`:`p:${So(a[h])},${So(a[h+1])},${So(a[h+2])}`,So(m),So(g),So(_),So(u[f]),So(u[f+1]),v,d].join("|")}(e,o,s,r,i,a,l,u,c,d,h,p);let y=f.get(v);y||(y={tx:0,ty:0,tz:0,bx:0,by:0,bz:0},f.set(v,y)),y.tx+=o*_,y.ty+=s*_,y.tz+=r*_,y.bx+=i*_,y.by+=a*_,y.bz+=l*_,null!==(g=m[e])&&void 0!==g||(m[e]=v)}function Mo(e,t,n){const o=Math.hypot(e,t,n);return o>1e-8?[e/o,t/o,n/o]:[0,0,1]}function So(e){const t=Math.round(1e6*e);return Object.is(t,-0)?0:t}function Ro(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 Co(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],p=e.vertices[3*a+2];if(r){const e=t.Vector3.TransformNormal(new t.Vector3(d,h,p),r);d=e.x,h=e.y,p=e.z}if(l[3*o]+=d,l[3*o+1]+=h,l[3*o+2]+=p,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 Io(e,t,n){if(n<=0)return[];if(!t||t.length!==n||1===n)return[Oo(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:Oo(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=Oo((e-s)/i);return o[n-1]=1-a,o[n]=a,o}return o[n-1]=1,o}function Oo(e){return Math.max(0,Math.min(1,e))}const Fo=512,Eo=32,No=1e5;function Lo(e,t,n,o){let s=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;const i=new Set,a=[];for(const t of e)for(const e of t.curves){a.push(e);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 l=o>n?n:s,u=o>n?o:r;i.add(l),i.add(u);const c=Array.from(i).filter(e=>e>=l&&e<=u).sort((e,t)=>e-t),d=e=>{for(const t of a){const n=t.keys;if(0===n.length)continue;if(e<n[0].time){if(t.preExtrapolation&&"constant"!==t.preExtrapolation.mode)return!0;continue}if(e>=n[n.length-1].time){if(t.postExtrapolation&&"constant"!==t.postExtrapolation.mode)return!0;continue}let o=0,s=n.length-1;for(;s-o>1;){const t=o+s>>1;n[t].time<=e?o=t:s=t}if("cubic"===n[o].interpolation)return!0}return!1},h=[],p=Math.floor(u*t)-Math.ceil(l*t)+1,f=Math.max(1,Math.ceil(p/No));for(let e=0;e<c.length;e++){const n=c[e];if(h.push(n),e+1>=c.length)break;const o=c[e+1],s=Math.floor(n*t)+1,r=Math.ceil(o*t)-1,i=r-s+1;if(i<=0)continue;const a=d(n)?Fo:Eo,l=Math.max(f,Math.ceil(i/a));for(let e=s;e<=r;e+=l)h.push(e/t)}const m=h.sort((e,t)=>e-t),g=[];for(const e of m)e<l-1e-9||e>u+1e-9||(0===g.length||e-g[g.length-1]>1e-9)&&g.push(e);return g}function ko(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 Po(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=In(e,d.start))&&void 0!==r?r:0,interpolation:"linear",leftDx:0,leftDy:0,rightDx:0,rightDy:0},frame:d.start*t,value:s(null!==(i=In(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=In(e,d.stop))&&void 0!==a?a:0,interpolation:"linear",leftDx:0,leftDy:0,rightDx:0,rightDy:0},frame:d.stop*t,value:s(null!==(l=In(e,d.stop))&&void 0!==l?l:0)});const p=h.map(e=>({frame:e.frame,value:e.value}));for(let e=0;e<h.length-1;e++){const n=h[e].source,o=p[e+1];if("constant"===n.interpolation){p[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;p[e].outTangent=Bo(null!==(u=n.rightSlope)&&void 0!==u?u:a,s)/t,o.inTangent=Bo(null!==(c=n.nextLeftSlope)&&void 0!==c?c:a,s)/t}return p}function Bo(e,t){return t(e)-t(0)}let Do=!1;function Vo(){Do||(Do=!0,t.RegisterSceneLoaderPlugin(new To))}var Go={__proto__:null,FBXFileLoader:To,RegisterFBXFileLoader:Vo};function $o(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 Uo(){const e=[];onmessage=t=>{const n=t.data;switch(n.id){case"init":importScripts(n.url);break;case"validate":$o(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)}}}Vo();class Ho{static ValidateAsync(e,n,o,s){return"function"==typeof Worker?new Promise((r,i)=>{const a=`${$o}(${Uo})()`,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),Ho._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(()=>$o(e,n,o,s)))}}Ho.Configuration={url:`${t.Tools._DefaultCdnUrl}/gltf_validator.js`},Ho._LastResults=null;var Ko={__proto__:null,GLTFValidation:Ho};const jo="Z2xURg",Wo={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,"+jo)||e.startsWith("data:;base64,"+jo)||e.startsWith("data:application/octet-stream;base64,"+jo)||e.startsWith("data:model/gltf-binary;base64,"+jo)};function qo(e,t,n){try{return Promise.resolve(new Uint8Array(e,t,n))}catch(e){return Promise.reject(e)}}var zo,Xo,Yo;e.GLTFLoaderCoordinateSystemMode=void 0,(zo=e.GLTFLoaderCoordinateSystemMode||(e.GLTFLoaderCoordinateSystemMode={}))[zo.AUTO=0]="AUTO",zo[zo.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED",e.GLTFLoaderAnimationStartMode=void 0,(Xo=e.GLTFLoaderAnimationStartMode||(e.GLTFLoaderAnimationStartMode={}))[Xo.NONE=0]="NONE",Xo[Xo.FIRST=1]="FIRST",Xo[Xo.ALL=2]="ALL",e.GLTFLoaderState=void 0,(Yo=e.GLTFLoaderState||(e.GLTFLoaderState={}))[Yo.LOADING=0]="LOADING",Yo[Yo.READY=1]="READY",Yo[Yo.COMPLETE=2]="COMPLETE";const Qo=e=>Promise.resolve(e);class Zo{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 Jo=new Zo;class es extends Zo{constructor(){super(...arguments),this.extensionOptions={},this.preprocessUrlAsync=Qo}copyFrom(e){var t,n,o,s,r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b,x,T,A,w,M,S,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!==(p=e.loadOnlyMaterials)&&void 0!==p?p:this.loadOnlyMaterials,this.loadSkins=null!==(f=e.loadSkins)&&void 0!==f?f:this.loadSkins,this.loggingEnabled=null!==(m=e.loggingEnabled)&&void 0!==m?m: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!==(g=e.preprocessUrlAsync)&&void 0!==g?g:this.preprocessUrlAsync,this.skipMaterials=null!==(_=e.skipMaterials)&&void 0!==_?_:this.skipMaterials,this.targetFps=null!==(v=e.targetFps)&&void 0!==v?v:this.targetFps,this.transparencyAsCoverage=null!==(y=e.transparencyAsCoverage)&&void 0!==y?y: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!==(w=e.useRangeRequests)&&void 0!==w?w:this.useRangeRequests,this.useSRGBBuffers=null!==(M=e.useSRGBBuffers)&&void 0!==M?M:this.useSRGBBuffers,this.validate=null!==(S=e.validate)&&void 0!==S?S:this.validate,this.dontUseTransmissionHelper=null!==(R=e.dontUseTransmissionHelper)&&void 0!==R?R:this.dontUseTransmissionHelper)}}class ts extends es{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=Wo.name,this.extensions=Wo.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({},Jo),e))}get _isPreprocessUrlAsyncSet(){return this.preprocessUrlAsync!==Qo}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=Qo,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)=>qo(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 Wo.canDirectLoad(e)}directLoad(e,n){if(n.startsWith("base64,"+jo)||n.startsWith(";base64,"+jo)||n.startsWith("application/octet-stream;base64,"+jo)||n.startsWith("model/gltf-binary;base64,"+jo)){const o=t.DecodeBase64UrlToBinary(n);return this._validate(e,new Uint8Array(o,0,o.byteLength)),this._unpackBinaryAsync(new t.DataReader({readAsync:(e,t)=>qo(o,e,t),byteLength:o.byteLength}))}return this._validate(e,n),Promise.resolve({json:this._parseJson(n)})}createPlugin(e){return new ts(e[Wo.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"),Ho.ValidateAsync(n,o,s,t=>this.preprocessUrlAsync(o+t,o).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=ts._parseVersion(t.version);if(!n)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=ts._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(ts._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const o={1:ts._CreateGLTF1Loader,2:ts._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=ts._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){}}ts.IncrementalLoading=!0,ts.HomogeneousCoordinates=!1,ts._logSpaces=" ";let ns=!1;function os(){ns||(ns=!0,t.RegisterSceneLoaderPlugin(new ts))}os();var ss,rs,is,as,ls,us,cs,ds,hs,ps={__proto__:null,GLTFFileLoader:ts,get GLTFLoaderAnimationStartMode(){return e.GLTFLoaderAnimationStartMode},get GLTFLoaderCoordinateSystemMode(){return e.GLTFLoaderCoordinateSystemMode},GLTFLoaderDefaultOptions:Jo,get GLTFLoaderState(){return e.GLTFLoaderState},RegisterGLTFFileLoader:os};!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"}(ss||(ss={})),function(e){e[e.FRAGMENT=35632]="FRAGMENT",e[e.VERTEX=35633]="VERTEX"}(rs||(rs={})),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"}(is||(is={})),function(e){e[e.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",e[e.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",e[e.REPEAT=10497]="REPEAT"}(as||(as={})),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"}(ls||(ls={})),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"}(us||(us={})),function(e){e[e.FRONT=1028]="FRONT",e[e.BACK=1029]="BACK",e[e.FRONT_AND_BACK=1032]="FRONT_AND_BACK"}(cs||(cs={})),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"}(ds||(ds={}));class fs{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 is.FLOAT_MAT2:r.setMatrix2x2(s,t.Matrix.GetAsMatrix2x2(i));break;case is.FLOAT_MAT3:r.setMatrix3x3(s,t.Matrix.GetAsMatrix3x3(i));break;case is.FLOAT_MAT4:r.setMatrix(s,i)}}static SetUniform(e,n,o,s){switch(s){case is.FLOAT:return e.setFloat(n,o),!0;case is.FLOAT_VEC2:return e.setVector2(n,t.Vector2.FromArray(o)),!0;case is.FLOAT_VEC3:return e.setVector3(n,t.Vector3.FromArray(o)),!0;case is.FLOAT_VEC4:return e.setVector4(n,t.Vector4.FromArray(o)),!0;default:return!1}}static GetWrapMode(e){switch(e){case as.CLAMP_TO_EDGE:return t.Texture.CLAMP_ADDRESSMODE;case as.MIRRORED_REPEAT:return t.Texture.MIRROR_ADDRESSMODE;case as.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 ls.LINEAR:case ls.LINEAR_MIPMAP_NEAREST:case ls.LINEAR_MIPMAP_LINEAR:return t.Texture.TRILINEAR_SAMPLINGMODE;case ls.NEAREST:case ls.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 ss.BYTE:return new Int8Array(i,n,o);case ss.UNSIGNED_BYTE:return new Uint8Array(i,n,o);case ss.SHORT:return new Int16Array(i,n,o);case ss.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*fs.GetByteStrideFromType(t);return fs.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(!fs._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};fs._DefaultMaterial=new t.ShaderMaterial("GLTFDefaultMaterial",e,n,o),fs._DefaultMaterial.setColor4("u_emission",new t.Color4(.5,.5,.5,1))}return fs._DefaultMaterial}}fs._DefaultMaterial=null,function(e){e[e.IDENTIFIER=1]="IDENTIFIER",e[e.UNKNOWN=2]="UNKNOWN",e[e.END_OF_INPUT=3]="END_OF_INPUT"}(hs||(hs={}));class ms{constructor(e){this._pos=0,this.currentToken=hs.UNKNOWN,this.currentIdentifier="",this.currentString="",this.isLetterOrDigitPattern=/^[a-zA-Z0-9]+$/,this._toParse=e,this._maxPos=e.length}getNextToken(){if(this.isEnd())return hs.END_OF_INPUT;if(this.currentString=this.read(),this.currentToken=hs.UNKNOWN,"_"===this.currentString||this.isLetterOrDigitPattern.test(this.currentString))for(this.currentToken=hs.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 gs=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],_s=["world","view","projection","worldView","worldViewProjection","mBones"],vs=["translation","rotation","scale"],ys=["position","rotationQuaternion","scaling"],bs=(e,t,n)=>{for(const o in e){const s=e[o];n[t][o]=s}},xs=e=>{if(e)for(let t=0;t<e.length/2;t++)e[2*t+1]=1-e[2*t+1]},Ts=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},As=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},ws=(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=As(a),r=new t.Bone(a.name||"",s,ws(e,n,a.jointName,s),o);return r.id=i,r}}}return null},Ms=(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},Ss=(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},Rs=(e,t)=>{for(let n=0;n<e.jointNames.length;n++)if(e.jointNames[n]===t)return!0;return!1},Cs=(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 p,f;for(const n in h)if(p=e.accessors[h[n]],f=fs.GetBufferFromAccessor(e,p),"NORMAL"===n)o.normals=new Float32Array(f.length),o.normals.set(f);else if("POSITION"===n){if(ts.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),xs(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(p=e.accessors[s.indices],p)f=fs.GetBufferFromAccessor(e,p),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 m=e.scene.getMaterialById(s.material);i.push(null===m?fs.GetDefaultMaterial(e.scene):m),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 p=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(p,l[p],u[p],c[p],d[p],r,r,!0),p++}return r},Is=(e,t,n,o)=>{e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=n),e.scaling&&(e.scaling=o)},Os=(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=Cs(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||Rs(o,i.jointName))continue;const l=As(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=Ss(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=Ss(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=ws(e,n,n.jointNames[r],s),d=!0;break}if(d)break}}const p=As(l);!h&&r.length>0&&(h=Ms(r,u),h&&-1===i.indexOf(h)&&i.push(h)),new t.Bone(l.jointName||"",s,h,p).id=u}const a=s.bones;s.bones=[];for(let t=0;t<n.jointNames.length;t++){const o=Ss(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=Cs(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),Is(e,o,s,r)}else n.translation&&n.rotation&&n.scale&&Is(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];Is(s,t.Vector3.FromArray(e),t.Quaternion.FromArray(o),t.Vector3.FromArray(r))}s.updateCache(!0),n.babylonNode=s}return s},Fs=(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=Os(e,s,t),null!==r&&(r.id=t,r.parent=n)),s.children)for(let t=0;t<s.children.length;t++)Fs(e,s.children[t],r,o)},Es=e=>{let n=e.currentScene;if(n)for(let t=0;t<n.nodes.length;t++)Fs(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++)Fs(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=fs.GetBufferFromAccessor(e,e.accessors[l]),d=fs.GetBufferFromAccessor(e,e.accessors[u]),h=i.target.id;let p=e.scene.getNodeById(h);if(null===p&&(p=e.scene.getNodeByName(h)),null===p){t.Tools.Warn("Creating animation named "+n+". But cannot find node named "+h+" to attach to");continue}const f=p instanceof t.Bone;let m=i.target.path;const g=vs.indexOf(m);-1!==g&&(m=ys[g]);let _=t.Animation.ANIMATIONTYPE_MATRIX;f||("rotationQuaternion"===m?(_=t.Animation.ANIMATIONTYPE_QUATERNION,p.rotationQuaternion=new t.Quaternion):_=t.Animation.ANIMATIONTYPE_VECTOR3);let v=null;const y=[];let b=0,x=!1;f&&s&&s.getKeys().length===c.length&&(v=s,x=!0),x||(e.scene._blockEntityCollection=!!e.assetContainer,v=new t.Animation(n,f?"_matrix":m,1,_,t.Animation.ANIMATIONLOOPMODE_CYCLE),e.scene._blockEntityCollection=!1);for(let e=0;e<c.length;e++){let n;if("rotationQuaternion"===m?(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=p;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"===m?r=n:"rotationQuaternion"===m?i=n:a=n,n=t.Matrix.Compose(a,i,r)}x?s&&(s.getKeys()[e].value=n):y.push({frame:c[e],value:n})}!x&&v&&(v.setKeys(y),p.animations.push(v)),s=v,e.scene.stopAnimation(p),e.scene.beginAnimation(p,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)}},Ns=(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=gs.indexOf(r.semantic);if(-1!==e)return delete n[o],_s[e]}}return e.currentIdentifier},Ls=e=>{for(const t in e.materials)Bs.LoadMaterialAsync(e,t,()=>{},()=>{})};class ks{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&&bs(e.extensions,"extensions",o),e.extensionsUsed&&bs(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&&bs(e.bufferViews,"bufferViews",o),e.accessors&&bs(e.accessors,"accessors",o),e.meshes&&bs(e.meshes,"meshes",o),e.lights&&bs(e.lights,"lights",o),e.cameras&&bs(e.cameras,"cameras",o),e.nodes&&bs(e.nodes,"nodes",o),e.images&&bs(e.images,"images",o),e.textures&&bs(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&&bs(e.programs,"programs",o),e.samplers&&bs(e.samplers,"samplers",o),e.techniques&&bs(e.techniques,"techniques",o),e.materials&&bs(e.materials,"materials",o),e.animations&&bs(e.animations,"animations",o),e.skins&&bs(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===ls.NEAREST_MIPMAP_NEAREST||i.minFilter===ls.NEAREST_MIPMAP_LINEAR||i.minFilter===ls.LINEAR_MIPMAP_NEAREST||i.minFilter===ls.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=fs.GetWrapMode(i.wrapS)),void 0!==i.wrapT&&(h.wrapV=fs.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 p=new ms(u),f=new ms(c),m={},g=[],_=[],v=[];for(const e in i.uniforms){const t=i.uniforms[e],n=i.parameters[t];if(m[e]=n,!n.semantic||n.node||n.source)n.type===is.SAMPLER_2D?v.push(e):g.push(e);else{const t=gs.indexOf(n.semantic);-1!==t?(g.push(_s[t]),delete m[e]):g.push(e)}}for(const e in i.attributes){const t=i.attributes[e],n=i.parameters[t];if(n.semantic){const e=Ts(n);e&&_.push(e)}}for(;!p.isEnd()&&p.getNextToken();){if(p.currentToken!==hs.IDENTIFIER){d+=p.currentString;continue}let e=!1;for(const t in i.attributes){const n=i.attributes[t],o=i.parameters[n];if(p.currentIdentifier===t&&o.semantic){d+=Ts(o),e=!0;break}}e||(d+=Ns(p,i,m))}for(;!f.isEnd()&&f.getNextToken();)f.currentToken===hs.IDENTIFIER?h+=Ns(f,i,m):h+=f.currentString;const y={vertex:a.vertexShader+n,fragment:a.fragmentShader+n},b={attributes:_,uniforms:g,samplers:v,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,y,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===is.SAMPLER_2D?Bs.LoadTextureAsync(e,o.values?u:a.value,c(n),()=>c(null)):a.value&&fs.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===is.FLOAT_MAT2||u===is.FLOAT_MAT3||u===is.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;fs.SetMatrix(t.scene,e,l,i,o.getEffect())}}else fs.SetMatrix(t.scene,e,l,i,o.getEffect());else{const e=a[s.uniforms[i]];if(!e)continue;if(u===is.SAMPLER_2D){const n=t.textures[r.values?e:l.value].babylonTexture;if(null==n)continue;o.getEffect().setTexture(i,n)}else fs.SetUniform(o.getEffect(),i,e,u)}}i(o)})(i,e,s,t,n,o,r)}})(e,x,i,r,m,o),x.sideOrientation=t.Material.CounterClockWiseSideOrientation,l&&l.functions){const e=l.functions;e.cullFace&&e.cullFace[0]!==cs.BACK&&(x.backFaceCulling=!1);const n=e.blendFuncSeparate;n&&(n[0]===ds.SRC_ALPHA&&n[1]===ds.ONE_MINUS_SRC_ALPHA&&n[2]===ds.ONE&&n[3]===ds.ONE?x.alphaMode=t.Constants.ALPHA_COMBINE:n[0]===ds.ONE&&n[1]===ds.ONE&&n[2]===ds.ZERO&&n[3]===ds.ONE?x.alphaMode=t.Constants.ALPHA_ONEONE:n[0]===ds.SRC_ALPHA&&n[1]===ds.ONE&&n[2]===ds.ZERO&&n[3]===ds.ONE?x.alphaMode=t.Constants.ALPHA_ADD:n[0]===ds.ZERO&&n[1]===ds.ONE_MINUS_SRC_COLOR&&n[2]===ds.ONE&&n[3]===ds.ONE?x.alphaMode=t.Constants.ALPHA_SUBTRACT:n[0]===ds.DST_COLOR&&n[1]===ds.ZERO&&n[2]===ds.ONE&&n[3]===ds.ONE?x.alphaMode=t.Constants.ALPHA_MULTIPLY:n[0]===ds.SRC_ALPHA&&n[1]===ds.ONE_MINUS_SRC_COLOR&&n[2]===ds.ONE&&n[3]===ds.ONE&&(x.alphaMode=t.Constants.ALPHA_MAXIMIZED))}}}let Ps=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,Bs.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,()=>{Ls(n),Es(n),!ts.IncrementalLoading&&i&&i(o,s)})}),ts.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,Bs.LoadRuntimeAsync(e,t,n,e=>{Bs.LoadRuntimeExtensionsAsync(e,()=>{this._createNodes(e),this._loadBuffersAsync(e,()=>{this._loadShadersAsync(e,()=>{Ls(e),Es(e),ts.IncrementalLoading||o()})}),ts.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)=>{Bs.LoadShaderStringAsync(e,o,r=>{r instanceof ArrayBuffer||(e.loadedShaderCount++,r&&(t.Effect.ShadersStore[o+(s.type===rs.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)=>{Bs.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++)Fs(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++)Fs(e,t.nodes[n],null)}}};Ps.Extensions={};class Bs{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){Bs._ApplyExtensions(r=>r.loadRuntimeAsync(e,t,n,o,s),()=>{setTimeout(()=>{o&&o(ks.CreateRuntime(t.json,e,n))})})}static LoadRuntimeExtensionsAsync(e,t,n){Bs._ApplyExtensions(o=>o.loadRuntimeExtensionsAsync(e,t,n),()=>{setTimeout(()=>{t()})})}static LoadBufferAsync(e,t,n,o,s){Bs._ApplyExtensions(r=>r.loadBufferAsync(e,t,n,o,s),()=>{ks.LoadBufferAsync(e,t,n,o,s)})}static LoadTextureAsync(e,t,n,o){Bs._LoadTextureBufferAsync(e,t,s=>{s&&Bs._CreateTextureAsync(e,t,s,n,o)},o)}static LoadShaderStringAsync(e,t,n,o){Bs._ApplyExtensions(s=>s.loadShaderStringAsync(e,t,n,o),()=>{ks.LoadShaderStringAsync(e,t,n,o)})}static LoadMaterialAsync(e,t,n,o){Bs._ApplyExtensions(s=>s.loadMaterialAsync(e,t,n,o),()=>{ks.LoadMaterialAsync(e,t,n,o)})}static _LoadTextureBufferAsync(e,t,n,o){Bs._ApplyExtensions(s=>s.loadTextureBufferAsync(e,t,n,o),()=>{ks.LoadTextureBufferAsync(e,t,n,o)})}static _CreateTextureAsync(e,t,n,o,s){Bs._ApplyExtensions(r=>r.createTextureAsync(e,t,n,o,s),()=>{ks.CreateTextureAsync(e,t,n,o)})}static _ApplyExtensions(e,t){for(const t in Ps.Extensions)if(e(Ps.Extensions[t]))return;t()}}let Ds=!1;function Vs(){Ds||(Ds=!0,ts._CreateGLTF1Loader=()=>new Ps)}class Gs extends Bs{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(ks.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(fs.GetBufferFromBufferView(e,i,0,i.byteLength,ss.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=fs.GetBufferFromBufferView(e,r,0,r.byteLength,ss.UNSIGNED_BYTE);return setTimeout(()=>{const e=fs.DecodeBufferToText(i);n(e)}),!0}}let $s=!1;function Us(){$s||($s=!0,Ps.RegisterExtension(new Gs))}Vs(),os(),Us();class Hs extends Bs{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){ks.LoadTextureBufferAsync(e,t,s=>{ks.CreateTextureAsync(e,t,s,e=>n[o]=e)},s)}}let Ks=!1;function js(){Ks||(Ks=!0,Ps.RegisterExtension(new Hs))}js();var Ws={__proto__:null,get EBlendingFunction(){return ds},get EComponentType(){return ss},get ECullingType(){return cs},get EParameterType(){return is},get EShaderType(){return rs},get ETextureFilterType(){return ls},get ETextureFormat(){return us},get ETextureWrapMode(){return as},GLTFBinaryExtension:Gs,GLTFLoader:Ps,GLTFLoaderBase:ks,GLTFLoaderExtension:Bs,GLTFMaterialsCommonExtension:Hs,GLTFUtils:fs,RegisterGLTF1Loader:Vs,RegisterGLTFBinaryExtension:Us,RegisterGLTFMaterialsCommonExtension:js};const qs=new Map,zs=qs;function Xs(e,n,o){Ys(e)&&t.Logger.Warn(`Extension with the name '${e}' already exists`),qs.set(e,{isGLTFExtension:n,factory:o})}function Ys(e){return qs.delete(e)}const Qs=[{regex:new RegExp("^/nodes/\\d+/extensions/")},{regex:new RegExp("^/animations/\\d+/extensions/")},{regex:new RegExp("^/nodes/\\d+/weights")},{regex:new RegExp("^/meshes/\\d+/weights")},{regex:new RegExp("/extensions/KHR_texture_transform/")}];class Zs{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)if("length"===i){if(!o.length)throw o.__array__?new Error(`Path ${e} is invalid - no length accessor`):new Error(`Path ${e} is invalid`);o=o.length,void 0!==n&&(t=n)}else{if(o.__ignoreObjectTree__&&(r=!0),o.__array__)o=o.__array__;else if(o=o[i],!o)throw new Error(`Path ${e} is invalid`);if(o.__passThroughTarget__)r=!0;else if(r){const e=/^\d+$/.test(i)?parseInt(i,10):NaN;if(!isNaN(e)&&"function"==typeof o.get){const t=o;o=Object.assign({},t),o.get=(n,o,...s)=>t.get(n,e,...s),"function"==typeof t.set&&(o.set=(n,o,s,...r)=>t.set(n,o,e,...r)),"function"==typeof t.getTarget&&(o.getTarget=(n,o,...s)=>t.getTarget(n,e,...s))}}else if(void 0===n){if(!Qs.find(t=>t.regex.test(e)))throw new Error(`Path ${e} is invalid`)}else n=null==n?void 0:n[i];o.__target__&&void 0!==n&&(t=n)}return{object:t,info:o}}}function Js(e,n){return{type:"FlowGraphInteger",get:n=>{const o=e(n);return void 0===o?void 0:t.FlowGraphInteger.FromValue(o)},getTarget:n,getPropertyName:[()=>"length"]}}const er={length:Js(e=>e.length,e=>e.map(e=>e._babylonTransformNode)),__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:{__passThroughTarget__:!0,length:Js(e=>{const t=rr(e);return t?t.mtm.numTargets:void 0!==(null==e?void 0:e.mesh)?0:void 0},e=>null==e?void 0:e._babylonTransformNode),__array__:{__target__:!0,type:"number",get:(e,t)=>{const n=rr(e);if(n&&void 0!==t&&t>=0&&t<n.mtm.numTargets)return ir(n.mtm.getTarget(t).influence)},set:(e,t,n)=>{var o;const s="number"==typeof e?e:"number"==typeof(null==e?void 0:e.value)?e.value:e,r=rr(t);if(!(!r||void 0===n||n<0||n>=r.mtm.numTargets))for(const e of r.meshes){const t=null===(o=e.morphTargetManager)||void 0===o?void 0:o.getTarget(n);t&&(t.influence=s)}},getTarget:(e,t)=>{const n=rr(e);return n&&void 0!==t&&t>=0&&t<n.mtm.numTargets?n.mtm.getTarget(t):null==e?void 0:e._babylonTransformNode},getPropertyName:[()=>"influence"]},type:"number[]",get:e=>{const t=rr(e);if(!t)return[];const n=[];for(let e=0;e<t.mtm.numTargets;e++)n.push(ir(t.mtm.getTarget(e).influence));return n},getTarget:e=>null==e?void 0: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},camera:{type:"string",get:e=>void 0!==e.camera?`/cameras/${e.camera}`:"",getTarget:e=>e,isReadOnly:!0},mesh:{type:"string",get:e=>void 0!==e.mesh?`/meshes/${e.mesh}`:"",getTarget:e=>e,isReadOnly:!0},skin:{type:"string",get:e=>void 0!==e.skin?`/skins/${e.skin}`:"",getTarget:e=>e,isReadOnly:!0},parent:{type:"string",get:e=>e.parent&&void 0!==e.parent.index?`/nodes/${e.parent.index}`:"",getTarget:e=>e,isReadOnly:!0},children:{length:Js(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,type:"string",get:e=>"number"==typeof e?`/nodes/${e}`:"",getTarget:()=>({__nodeIndex:!0}),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)}}}}}},tr={length:Js(e=>e.length,e=>e.map(e=>e._babylonAnimationGroup)),__array__:{__target__:!0,type:"string",get:e=>e&&"number"==typeof e.index?`/animations/${e.index}`:"",getTarget:e=>e._babylonAnimationGroup,isReadOnly:!0}},nr={length:Js(e=>e.length,e=>e.map(e=>{var t;return null===(t=e.primitives[0]._instanceData)||void 0===t?void 0:t.babylonSourceMesh})),__array__:{__target__:!0,primitives:{length:Js(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,material:{type:"string",get:e=>void 0!==e.material?`/materials/${e.material}`:"",getTarget:e=>e,isReadOnly:!0}}},weights:{length:Js(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,type:"number",get:e=>e,getTarget:()=>({__weightValue:!0}),isReadOnly:!0}}}};function or(e,t,n,o){const s=sr(e);return o?s[n][o]:s[n]}function sr(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 rr(e){var t,n,o,s;const r=null==e?void 0:e._babylonTransformNode;if(!r)return;const i=function(e){var t;const n=null==e?void 0:e._babylonTransformNode;if(!n)return;if(n.morphTargetManager)return n.morphTargetManager;const o=e._primitiveBabylonMeshes;if(o)for(const e of o){if(null==e?void 0:e.morphTargetManager)return e.morphTargetManager;if(null===(t=null==e?void 0:e.sourceMesh)||void 0===t?void 0:t.morphTargetManager)return e.sourceMesh.morphTargetManager}}(e);if(i&&e._primitiveBabylonMeshes&&e._primitiveBabylonMeshes.length>0)return{mtm:i,meshes:e._primitiveBabylonMeshes};const a=r.getDescendants(!1);for(const e of a){const r=e,i=null!==(t=r.morphTargetManager)&&void 0!==t?t:null===(n=r.sourceMesh)||void 0===n?void 0:n.morphTargetManager;if(!i)continue;const a=[],l=r.parent;if(l)for(const e of l.getChildMeshes(!0))(null!==(o=e.morphTargetManager)&&void 0!==o?o:null===(s=e.sourceMesh)||void 0===s?void 0:s.morphTargetManager)===i&&a.push(e);return 0===a.length&&a.push(r),{mtm:i,meshes:a}}}function ir(e){return Number.isFinite(e)?parseFloat(e.toPrecision(7)):e}function ar(e,t,n){if(!e)return;let o=e.extensions;if(!o){if(!n)return;o={},e.extensions=o}let s=o[t.extensionKey];if(!s){if(!n)return;s={},o[t.extensionKey]=s}for(const e of t.texturePath){let t=s[e];if(!t){if(!n)return;t={},s[e]=t}s=t}if(!s.extensions){if(!n)return;s.extensions={}}let r=s.extensions.KHR_texture_transform;if(!r){if(!n)return;r={},s.extensions.KHR_texture_transform=r}return r}function lr(e,n,o){return{offset:{componentsCount:2,type:"Vector2",get:(s,r,i)=>{var a,l;const u=or(s,0,e,n);if(u)return new t.Vector2(u.uOffset,u.vOffset);if(o){const e=ar(s,o,!1),n=null==e?void 0:e.offset;return new t.Vector2(null!==(a=null==n?void 0:n[0])&&void 0!==a?a:0,null!==(l=null==n?void 0:n[1])&&void 0!==l?l:0)}return new t.Vector2(0,0)},getTarget:sr,set:(t,s,r,i)=>{const a=or(s,0,e,n);if(a&&(a.uOffset=t.x,a.vOffset=t.y),o){const e=ar(s,o,!0);e&&(e.offset=[t.x,t.y])}},getPropertyName:[()=>`${e}${n?"."+n:""}.uOffset`,()=>`${e}${n?"."+n:""}.vOffset`]},rotation:{type:"number",get:(t,s,r)=>{var i;const a=or(t,0,e,n);if(a)return a.wAng;if(o){const e=ar(t,o,!1);return null!==(i=null==e?void 0:e.rotation)&&void 0!==i?i:0}return 0},getTarget:sr,set:(t,s,r,i)=>{const a=or(s,0,e,n);if(a&&(a.wAng=t),o){const e=ar(s,o,!0);e&&(e.rotation=t)}},getPropertyName:[()=>`${e}${n?"."+n:""}.wAng`]},scale:{componentsCount:2,type:"Vector2",get:(s,r,i)=>{var a,l;const u=or(s,0,e,n);if(u)return new t.Vector2(u.uScale,u.vScale);if(o){const e=ar(s,o,!1),n=null==e?void 0:e.scale;return new t.Vector2(null!==(a=null==n?void 0:n[0])&&void 0!==a?a:1,null!==(l=null==n?void 0:n[1])&&void 0!==l?l:1)}return new t.Vector2(1,1)},getTarget:sr,set:(t,s,r,i)=>{const a=or(s,0,e,n);if(a&&(a.uScale=t.x,a.vScale=t.y),o){const e=ar(s,o,!0);e&&(e.scale=[t.x,t.y])}},getPropertyName:[()=>`${e}${n?"."+n:""}.uScale`,()=>`${e}${n?"."+n:""}.vScale`]}}}const ur={scene:{__target__:!0,type:"number",get:e=>null!=e?e:0,getTarget:()=>({__gltfRoot:!0}),isReadOnly:!0,getPropertyName:[()=>"scene"]},cameras:{length:Js(e=>e.length,e=>e.map(e=>e._babylonCamera)),__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:er,materials:{length:Js(e=>e.length,e=>e.map(e=>{var n,o;return null===(o=null===(n=e._data)||void 0===n?void 0:n[t.Constants.MATERIAL_TriangleFillMode])||void 0===o?void 0:o.babylonMaterial})),__array__:{__target__:!0,doubleSided:{type:"boolean",get:(e,t,n)=>{var o;return!(null===(o=sr(e,0,n))||void 0===o?void 0:o.backFaceCulling)},set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.backFaceCulling=!e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"backFaceCulling"]},alphaCutoff:{type:"number",get:(e,t,n)=>{var o;return null===(o=sr(e,0,n))||void 0===o?void 0:o.alphaCutOff},set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.alphaCutOff=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"alphaCutOff"]},emissiveFactor:{type:"Color3",get:(e,t,n)=>sr(e,0,n).emissiveColor,set:(e,t,n,o)=>sr(t,0,o).emissiveColor.copyFrom(e),getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"emissiveColor"]},emissiveTexture:{extensions:{KHR_texture_transform:lr("emissiveTexture")}},normalTexture:{scale:{type:"number",get:(e,t,n)=>{var o;return null===(o=or(e,0,"bumpTexture"))||void 0===o?void 0:o.level},set:(e,t,n,o)=>{const s=or(t,0,"bumpTexture");s&&(s.level=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"level"]},extensions:{KHR_texture_transform:lr("bumpTexture")}},occlusionTexture:{strength:{type:"number",get:(e,t,n)=>sr(e,0,n).ambientTextureStrength,set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.ambientTextureStrength=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"ambientTextureStrength"]},extensions:{KHR_texture_transform:lr("ambientTexture")}},pbrMetallicRoughness:{baseColorFactor:{type:"Color4",get:(e,n,o)=>{const s=sr(e,0,o);return t.Color4.FromColor3(s.albedoColor,s.alpha)},set:(e,t,n,o)=>{const s=sr(t,0,o);s.albedoColor.set(e.r,e.g,e.b),s.alpha=e.a},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"albedoColor",()=>"alpha"]},baseColorTexture:{extensions:{KHR_texture_transform:lr("albedoTexture")}},metallicFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).metallic,set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.metallic=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"metallic"]},roughnessFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).roughness,set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.roughness=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"roughness"]},metallicRoughnessTexture:{extensions:{KHR_texture_transform:lr("metallicTexture")}}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:{type:"number",get:(e,t,n)=>{var o,s;return null===(s=null===(o=sr(e,0,n))||void 0===o?void 0:o.anisotropy)||void 0===s?void 0:s.intensity},set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.anisotropy.intensity=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"anisotropy.intensity"]},anisotropyRotation:{type:"number",get:(e,t,n)=>{var o,s;return null===(s=null===(o=sr(e,0,n))||void 0===o?void 0:o.anisotropy)||void 0===s?void 0:s.angle},set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.anisotropy.angle=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"anisotropy.angle"]},anisotropyTexture:{extensions:{KHR_texture_transform:lr("anisotropy","texture")}}},KHR_materials_clearcoat:{clearcoatFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).clearCoat.intensity,set:(e,t,n,o)=>{sr(t,0,o).clearCoat.intensity=e},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"clearCoat.intensity"]},clearcoatRoughnessFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).clearCoat.roughness,set:(e,t,n,o)=>{sr(t,0,o).clearCoat.roughness=e},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"clearCoat.roughness"]},clearcoatTexture:{extensions:{KHR_texture_transform:lr("clearCoat","texture")}},clearcoatNormalTexture:{scale:{type:"number",get:(e,t,n)=>{var o;return null===(o=sr(e,0,n).clearCoat.bumpTexture)||void 0===o?void 0:o.level},getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).clearCoat.bumpTexture.level=e},extensions:{KHR_texture_transform:lr("clearCoat","bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:lr("clearCoat","textureRoughness")}}},KHR_materials_dispersion:{dispersion:{type:"number",get:(e,t,n)=>sr(e,0,n).subSurface.dispersion,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).subSurface.dispersion=e}},KHR_materials_emissive_strength:{emissiveStrength:{type:"number",get:(e,t,n)=>sr(e,0,n).emissiveIntensity,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).emissiveIntensity=e}},KHR_materials_ior:{ior:{type:"number",get:(e,t,n)=>sr(e,0,n).indexOfRefraction,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).indexOfRefraction=e}},KHR_materials_iridescence:{iridescenceFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).iridescence.intensity,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).iridescence.intensity=e},iridescenceIor:{type:"number",get:(e,t,n)=>sr(e,0,n).iridescence.indexOfRefraction,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).iridescence.indexOfRefraction=e},iridescenceTexture:{extensions:{KHR_texture_transform:lr("iridescence","texture")}},iridescenceThicknessMaximum:{type:"number",get:(e,t,n)=>sr(e,0,n).iridescence.maximumThickness,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).iridescence.maximumThickness=e},iridescenceThicknessMinimum:{type:"number",get:(e,t,n)=>sr(e,0,n).iridescence.minimumThickness,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).iridescence.minimumThickness=e},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:lr("iridescence","thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:{type:"Color3",get:(e,t,n)=>sr(e,0,n).sheen.color,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).sheen.color.copyFrom(e)},sheenColorTexture:{extensions:{KHR_texture_transform:lr("sheen","texture")}},sheenRoughnessFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).sheen.intensity,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).sheen.intensity=e},sheenRoughnessTexture:{extensions:{KHR_texture_transform:lr("sheen","textureRoughness")}}},KHR_materials_specular:{specularFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).metallicF0Factor,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).metallicF0Factor=e,getPropertyName:[()=>"metallicF0Factor"]},specularColorFactor:{type:"Color3",get:(e,t,n)=>sr(e,0,n).metallicReflectanceColor,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).metallicReflectanceColor.copyFrom(e),getPropertyName:[()=>"metallicReflectanceColor"]},specularTexture:{extensions:{KHR_texture_transform:lr("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:lr("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).subSurface.refractionIntensity,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).subSurface.refractionIntensity=e,getPropertyName:[()=>"subSurface.refractionIntensity"]},transmissionTexture:{extensions:{KHR_texture_transform:lr("subSurface","refractionIntensityTexture",{extensionKey:"KHR_materials_transmission",texturePath:["transmissionTexture"]})}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).subSurface.translucencyIntensity,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).subSurface.translucencyIntensity=e},diffuseTransmissionTexture:{extensions:{KHR_texture_transform:lr("subSurface","translucencyIntensityTexture",{extensionKey:"KHR_materials_diffuse_transmission",texturePath:["diffuseTransmissionTexture"]})}},diffuseTransmissionColorFactor:{type:"Color3",get:(e,t,n)=>sr(e,0,n).subSurface.translucencyColor,getTarget:sr,set:(e,t,n,o)=>{var s;return e&&(null===(s=sr(t,0,o).subSurface.translucencyColor)||void 0===s?void 0:s.copyFrom(e))}},diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:lr("subSurface","translucencyColorTexture",{extensionKey:"KHR_materials_diffuse_transmission",texturePath:["diffuseTransmissionColorTexture"]})}}},KHR_materials_volume:{attenuationColor:{type:"Color3",get:(e,t,n)=>sr(e,0,n).subSurface.tintColor,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).subSurface.tintColor.copyFrom(e)},attenuationDistance:{type:"number",get:(e,t,n)=>sr(e,0,n).subSurface.tintColorAtDistance,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).subSurface.tintColorAtDistance=e},thicknessFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).subSurface.maximumThickness,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).subSurface.maximumThickness=e},thicknessTexture:{extensions:{KHR_texture_transform:lr("subSurface","thicknessTexture",{extensionKey:"KHR_materials_volume",texturePath:["thicknessTexture"]})}}}}}},extensions:{KHR_lights_punctual:{lights:{length:Js(e=>e.length,e=>e.map(e=>e._babylonLight)),__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:Js(e=>e.length,e=>e.map(e=>e._babylonLight)),__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:Js(e=>e.length,e=>e.map(e=>e._babylonLight))}},EXT_lights_image_based:{lights:{length:Js(e=>e.length,e=>e.map(e=>e._babylonTexture)),__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:tr,meshes:nr,scenes:{length:Js(e=>e.length,e=>e),__array__:{__target__:!0,nodes:{length:Js(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,type:"string",get:e=>"number"==typeof e?`/nodes/${e}`:"",getTarget:()=>({__nodeIndex:!0}),isReadOnly:!0}}}},skins:{length:Js(e=>e.length,e=>e.map(e=>{var t;return null===(t=e._data)||void 0===t?void 0:t.babylonSkeleton})),__array__:{__target__:!0,joints:{length:Js(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,type:"string",get:e=>"number"==typeof e?`/nodes/${e}`:"",getTarget:()=>({__nodeIndex:!0}),isReadOnly:!0}},skeleton:{type:"string",get:e=>{const t=e.skeleton;return"number"==typeof t?`/nodes/${t}`:""},getTarget:e=>e,isReadOnly:!0}}}};function cr(e){if(Array.isArray(e))return e.map(e=>cr(e));if(null!==e&&"object"==typeof e){const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return e;const n={};for(const[t,o]of Object.entries(e))n[t]=cr(o);return n}return e}function dr(e,t){if(!t)return new Zs(e,ur);const n=cr(ur);return t(n),new Zs(e,n)}function hr(e){const t=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let n=ur;for(const e of t)e&&(n=n[e]);if(n&&n.type&&n.get)return n}function pr(e,t){const n=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let o=ur;for(const e of n)e&&(o=o[e]);o&&o.type&&o.get&&(o.interpolation=t)}function fr(e,t,n=ur){const o=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let s=n;for(const e of o)if(e){if(!s[e]){if("?"===e){s.__ignoreObjectTree__=!0;continue}s[e]={},"__array__"===e&&(s[e].__target__=!0)}s=s[e]}Object.assign(s,t)}const mr=new t.Lazy(()=>Promise.resolve(BABYLON)),gr=new t.Lazy(()=>Promise.resolve().then(function(){return Fr}));class _r{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 vr(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 yr{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){Xs(e,!1,t)}static UnregisterExtension(e){return Ys(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}${t.RandomGUID()}/`,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 Nr})]).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 kr})]).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=_r.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(()=>b(this,void 0,void 0,function*(){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 yield this._extensionsOnReadyAsync(),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(_r.Assign(this._gltf.accessors),_r.Assign(this._gltf.animations),_r.Assign(this._gltf.buffers),_r.Assign(this._gltf.bufferViews),_r.Assign(this._gltf.cameras),_r.Assign(this._gltf.images),_r.Assign(this._gltf.materials),_r.Assign(this._gltf.meshes),_r.Assign(this._gltf.nodes),_r.Assign(this._gltf.samplers),_r.Assign(this._gltf.scenes),_r.Assign(this._gltf.skins),_r.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(zs.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],yr._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=_r.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(yr.AddPointerMetadata(t,e),yr._LoadTransform(n,t),null!=n.camera){const o=_r.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=_r.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=_r.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=_r.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=_r.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=_r.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&&_r.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=yr._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=_r.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 yr.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=_r.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=_r.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=vr(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=_r.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=_r.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=_r.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=_r.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=_r.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 yr.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)||mr.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;_r.Assign(t.channels),_r.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=_r.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?gr.value.then(({RegisterGLTFLoaderAnimation:r})=>{var l,u,c,d;let h;switch(r(),a){case"translation":h=null===(l=hr("/nodes/{}/translation"))||void 0===l?void 0:l.interpolation;break;case"rotation":h=null===(u=hr("/nodes/{}/rotation"))||void 0===u?void 0:u.interpolation;break;case"scale":h=null===(c=hr("/nodes/{}/scale"))||void 0===c?void 0:c.interpolation;break;case"weights":h=null===(d=hr("/nodes/{}/weights"))||void 0===d?void 0:d.interpolation;break;default:throw new Error(`${e}/target/path: Invalid value (${o.target.path})`)}if(!h)throw new Error(`${e}/target/path: Could not find interpolation properties for target path (${o.target.path})`);const p={object:i,info:h};return this._loadAnimationChannelFromTargetInfoAsync(e,t,n,o,p,s)}):Promise.resolve()}_loadAnimationChannelFromTargetInfoAsync(e,t,n,o,s,r){const i=this.parent.targetFps,a=1/i,l=_r.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 p=0;switch(e.interpolation){case"STEP":for(let e=0;e<c.length;e++){const t=s.getValue(l,d,p,1);p+=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,p,a);p+=u;const n=s.getValue(l,d,p,1);p+=u;const o=s.getValue(l,d,p,a);p+=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,p,1);p+=u,h[e]={frame:c[e]*i,value:t}}}if(p>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=_r.Get(`${e}/input`,this._gltf.accessors,t.input),s=_r.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=_r.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=yr._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=_r.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 yr._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=_r.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,i.indices.bufferView),c=_r.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=yr._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=yr._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=yr._GetTypedArray(`${e}/sparse/values`,n.componentType,u,i.values.byteOffset,d);let p=0;for(let e=0;e<c.length;e++){let t=c[e]*s;for(let e=0;e<s;e++)l[t++]=h[p++]}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=yr._GetTypedArrayConstructor(`${e}/componentType`,t.componentType);t._data=this._loadAccessorAsync(e,t,n)}else{const n=_r.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${n.index}`,n).then(n=>yr._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=_r.Get(`${e}/bufferView`,this._gltf.bufferViews,n.bufferView);n._babylonVertexBuffer[o]=this._loadVertexBufferViewAsync(s).then(i=>{const a=yr._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,yr.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.then(e=>{var n;const o=null===(n=this._gltf.textures)||void 0===n?void 0:n[t.index];return o&&this._trackTexture(o,e),e});if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const s=_r.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,yr.AddPointerMetadata(o,e),this._parent.onTextureLoadedObservable.notifyObservers(o),n(o)});return this.logClose(),r}_loadTextureAsync(e,t,n=()=>{}){const o=e=>{this._trackTexture(t,e),n(e)},s=this._extensionsLoadTextureAsync(e,t,o);if(s)return s;this.logOpen(`${e} ${t.name||""}`);const r=null==t.sampler?yr.DefaultSampler:_r.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),i=_r.Get(`${e}/source`,this._gltf.images,t.source),a=this._createTextureAsync(e,r,i,o,void 0,!t._textureInfo.nonColorData,t);return this.logClose(),a}_trackTexture(e,t,n,o){var s,r;e._babylonTextures||(e._babylonTextures=[]),e._babylonTextures.includes(t)||e._babylonTextures.push(t),e._babylonTextureSources||(e._babylonTextureSources=[]);const i=e._babylonTextureSources.find(e=>e.babylonTexture===t),a=e._babylonTextureSources[e._babylonTextureSources.length-1],l=null!==(s=null!=n?n:null==i?void 0:i.imageIndex)&&void 0!==s?s:null==a?void 0:a.imageIndex;void 0!==l&&(i?(i.imageIndex=l,i.samplerIndex=null!==(r=null!=o?o:i.samplerIndex)&&void 0!==r?r:null==a?void 0:a.samplerIndex):e._babylonTextureSources.push({babylonTexture:t,imageIndex:l,samplerIndex:null!=o?o:null==a?void 0:a.samplerIndex}))}_createTextureAsync(e,n,o,s=()=>{},r,i,a){var l,u;const c=this._loadSampler(`/samplers/${n.index}`,n),d=new Array,h=new t.Deferred;this._babylonScene._blockEntityCollection=!!this._assetContainer;const p={noMipmap:c.noMipMaps,invertY:!1,samplingMode:c.samplingMode,onLoad:()=>{this._disposed||h.resolve()},onError:(t,n)=>{this._disposed||h.reject(new Error(`${e}: ${n&&n.message?n.message:t||"Failed to load texture"}`))},mimeType:null!==(l=o.mimeType)&&void 0!==l?l:t.GetMimeType(null!==(u=o.uri)&&void 0!==u?u:""),loaderOptions:r,useSRGBBuffer:!!i&&this._parent.useSRGBBuffers},f=new t.Texture(null,this._babylonScene,p);a&&this._trackTexture(a,f,o.index,n.index>=0?n.index:void 0),f._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,d.push(h.promise);const m=o.uri&&!t.IsBase64DataUrl(o.uri)?o.uri:void 0,g=null!=m?m:`${this._fileName}#image${o.index}`;if(d.push(this.loadImageAsync(`/images/${o.index}`,o).then(e=>{const t=`data:${this._uniqueRootUrl}${g}`;f.updateURL(t,e);const n=f.getInternalTexture();n&&(n.label=o.name)})),f.wrapU=c.wrapU,f.wrapV=c.wrapV,s(f),this._parent.useGltfTextureNames){const e=o.name||m||`image${o.index}`;f.name=e}return Promise.all(d).then(()=>f)}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:yr._GetTextureSamplingMode(e,t),wrapU:yr._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:yr._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=_r.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){var s;const r=this._extensionsLoadUriAsync(e,n,o);if(r)return r;if(!this._parent._isPreprocessUrlAsyncSet&&!yr._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,null!==(s=this._rootUrl)&&void 0!==s?s:void 0).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=yr._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())}_extensionsOnReadyAsync(){return b(this,void 0,void 0,function*(){for(const e of this._extensions)e.enabled&&e.onReady&&(yield 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)}}yr.DefaultSampler={index:-1};let br=!1;function xr(){br||(br=!0,ts._CreateGLTF2Loader=e=>new yr(e))}var Tr={__proto__:null,ArrayItem:_r,GLTFFileLoader:ts,GLTFLoader:yr,LoadBoundingInfoFromPositionAccessor:vr,RegisterGLTF2Loader:xr};function Ar(e,n,o,s){return t.Vector3.FromArray(n,o).scaleInPlace(s)}function wr(e,n,o,s){return t.Quaternion.FromArray(n,o).scaleInPlace(s)}function Mr(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}xr(),os();class Sr{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 Rr extends Sr{buildAnimations(e,t,n,o){const s=[];return s.push({babylonAnimatable:e._babylonTransformNode,babylonAnimation:this._buildAnimation(t,n,o)}),s}}class Cr extends Sr{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}}let Ir=!1;function Or(){Ir||(Ir=!0,pr("/nodes/{}/translation",[new Rr(t.Animation.ANIMATIONTYPE_VECTOR3,"position",Ar,()=>3)]),pr("/nodes/{}/rotation",[new Rr(t.Animation.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",wr,()=>4)]),pr("/nodes/{}/scale",[new Rr(t.Animation.ANIMATIONTYPE_VECTOR3,"scaling",Ar,()=>3)]),pr("/nodes/{}/weights",[new Cr(t.Animation.ANIMATIONTYPE_FLOAT,"influence",Mr,e=>e._numMorphTargets)]))}var Fr={__proto__:null,AnimationPropertyInfo:Sr,RegisterGLTFLoaderAnimation:Or,TransformNodeAnimationPropertyInfo:Rr,WeightAnimationPropertyInfo:Cr,getQuaternion:wr,getVector3:Ar,getWeights:Mr};Or();class Er{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,p,f,m,g;const _=this._material.coatWeight,v=this._material.coatWeightTexture,y=this._material.coatColor.clone(),b=this._material.coatColorTexture,x=this._material.geometryCoatNormalTexture,T=new t.Color4(_,_,_,_),A=new t.Color4(n,n,n,n);this.coatWeightTexture=null,this.coatWeight=1;const w=yield Promise.allSettled([t.LerpTexturesAsync("lerpExistingCoat",t.CreateTextureWithFactorOperand(null,new t.Color4(1,1,1,1)),t.CreateTextureWithFactorOperand(b,y.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.SRGB),t.CreateTextureWithFactorOperand(v,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)]),M=w.find(e=>"rejected"===e.status);if(M){for(const e of w)"fulfilled"===e.status&&(null===(l=e.value.texture)||void 0===l||l.dispose());throw M.reason}const[S,R]=w.map(e=>e.value);if(e._disposed)return null===(u=S.texture)||void 0===u||u.dispose(),void(null===(c=R.texture)||void 0===c||c.dispose());const C=yield t.MultiplyTexturesAsync("newCoatColor ("+this._material.name+")",S,R,this._material.getScene(),t.TextureColorSpace.SRGB);if(e._disposed)return void(null===(d=C.texture)||void 0===d||d.dispose());C.texture?(this.coatColorTexture=C.texture,this.coatColor=t.Color3.White()):C.factor&&(this.coatColorTexture=null,this.coatColor.fromArray([C.factor.r,C.factor.g,C.factor.b]));const I=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(v,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(h=I.texture)||void 0===h||h.dispose());this.coatIor=I.factor?I.factor.r:this.coatIor;const O=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(v,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(p=O.texture)||void 0===p||p.dispose());this.coatRoughness=O.factor?O.factor.r:1,this.coatRoughnessTexture=O.texture;const F=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(v,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)null===(f=F.texture)||void 0===f||f.dispose();else{if(this.coatDarkening=F.factor?F.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===(m=n.texture)||void 0===m||m.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(v,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(g=n.texture)||void 0===g||g.dispose());n.texture&&(this.geometryCoatNormalTexture=n.texture)}}})}}var Nr={__proto__:null,OpenPBRMaterialLoadingAdapter:Er};class Lr{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 kr={__proto__:null,PBRMaterialLoadingAdapter:Lr};const Pr="EXT_lights_image_based";class Br{constructor(e){this.name=Pr,this._loader=e,this.enabled=this._loader.isExtensionUsed(Pr)}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 yr.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=_r.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=_r.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)}}let Dr=!1;function Vr(){Dr||(Dr=!0,Ys(Pr),Xs(Pr,!0,e=>new Br(e)))}var Gr={__proto__:null,EXT_lights_image_based:Br,RegisterEXT_lights_image_based:Vr};Vr();const $r="EXT_mesh_gpu_instancing";class Ur{constructor(e){this.name=$r,this._loader=e,this.enabled=this._loader.isExtensionUsed($r)}dispose(){this._loader=null}loadNodeAsync(e,n,o){return yr.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=_r.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}))}))}}let Hr=!1;function Kr(){Hr||(Hr=!0,Ys($r),Xs($r,!0,e=>new Ur(e)))}var jr={__proto__:null,EXT_mesh_gpu_instancing:Ur,RegisterEXT_mesh_gpu_instancing:Kr};Kr();const Wr="EXT_meshopt_compression";class qr{constructor(e){this.name=Wr,this.enabled=e.isExtensionUsed(Wr),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,n){return yr.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=_r.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}))}}let zr=!1;function Xr(){zr||(zr=!0,Ys(Wr),Xs(Wr,!0,e=>new qr(e)))}var Yr={__proto__:null,EXT_meshopt_compression:qr,RegisterEXT_meshopt_compression:Xr};Xr();const Qr="EXT_texture_webp";class Zr{constructor(e){this.name=Qr,this._loader=e,this.enabled=e.isExtensionUsed(Qr)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?yr.DefaultSampler:_r.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=_r.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,t)}))}}let Jr=!1;function ei(){Jr||(Jr=!0,Ys(Qr),Xs(Qr,!0,e=>new Zr(e)))}var ti={__proto__:null,EXT_texture_webp:Zr,RegisterEXT_texture_webp:ei};ei();const ni="EXT_texture_avif";class oi{constructor(e){this.name=ni,this._loader=e,this.enabled=e.isExtensionUsed(ni)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?yr.DefaultSampler:_r.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=_r.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,t)}))}}let si=!1;function ri(){si||(si=!0,Ys(ni),Xs(ni,!0,e=>new oi(e)))}var ii={__proto__:null,EXT_texture_avif:oi,RegisterEXT_texture_avif:ri};ri();const ai="EXT_lights_ies";class li{constructor(e){this.name=ai,this._loader=e,this.enabled=this._loader.isExtensionUsed(ai)}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,_r.Assign(this._lights)}}loadNodeAsync(e,n,o){return yr.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=_r.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),yr.AddPointerMetadata(i,s),o(e)});let u;if(a.uri)u=yield this._loader.loadUriAsync(e,a,a.uri);else{const t=_r.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,a.bufferView);u=yield this._loader.loadBufferViewAsync(`/bufferViews/${t.index}`,t)}return i.iesProfileTexture=new t.Texture(i.name+"_iesProfile",this._loader.babylonScene,!0,!1,void 0,null,null,u,!0,void 0,void 0,void 0,void 0,".ies"),l}))}}let ui=!1;function ci(){ui||(ui=!0,Ys(ai),Xs(ai,!0,e=>new li(e)))}var di={__proto__:null,EXT_lights_ies:li,RegisterEXT_lights_ies:ci};ci();const hi="KHR_draco_mesh_compression";class pi{constructor(e){this.name=hi,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=t.DracoDecoder.DefaultAvailable&&this._loader.isExtensionUsed(hi)}dispose(){delete this.dracoDecoder,this._loader=null}_loadVertexDataAsync(e,n,o){return yr.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=_r.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=_r.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=_r.TryGet(this._loader.gltf.accessors,n.attributes.POSITION),u=this._loader.parent.alwaysComputeBoundingBox||o.skeleton||!l?null:vr(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}))}}let fi=!1;function mi(){fi||(fi=!0,Ys(hi),Xs(hi,!0,e=>new pi(e)))}var gi={__proto__:null,KHR_draco_mesh_compression:pi,RegisterKHR_draco_mesh_compression:mi};mi();const _i="KHR_gaussian_splatting",vi=.28209479177387814,yi=[0,3,5,7];function bi(e){return e<=0?0:e>=255?255:e+.5|0}class xi{constructor(e){this.name=_i,this._loader=e,this.enabled=this._loader.isExtensionUsed(_i)}dispose(){this._loader=null}_loadMeshPrimitiveAsync(e,n,o,s,r,i){return yr.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=_r.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<yi[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,yr.AddPointerMetadata(h,e),s.parent.onMeshLoadedObservable.notifyObservers(h),i(h);const p=d.getEngine().getCaps(),[f,m,g,_,v,y,...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=y?y.length/x:0,A=new ArrayBuffer(32*x),w=new Float32Array(A),M=new Uint8Array(A);let S=null;if(u>0){const e=3*((u+1)*(u+1)-1),n=Math.ceil(e/16),o=p.maxTextureSize,s=Math.ceil(x/o);S=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(w[t+0]=f[o+0],w[t+1]=f[o+1],w[t+2]=f[o+2],w[t+3]=g?g[o+0]:1,w[t+4]=g?g[o+1]:1,w[t+5]=g?g[o+2]:1,v)M[n+24]=bi(255*(.5+vi*v[o+0])),M[n+25]=bi(255*(.5+vi*v[o+1])),M[n+26]=bi(255*(.5+vi*v[o+2]));else if(y){const t=e*T;M[n+24]=bi(255*y[t+0]),M[n+25]=bi(255*y[t+1]),M[n+26]=bi(255*y[t+2])}else M[n+24]=255,M[n+25]=255,M[n+26]=255;M[n+27]=_?bi(255*_[e]):y&&T>=4?bi(255*y[e*T+3]):255;const s=4*e,r=m?m[s+0]:0,i=m?m[s+1]:0,a=m?m[s+2]:0,l=m?m[s+3]:1;if(M[n+28]=bi(127.5*l+127.5),M[n+29]=bi(127.5*r+127.5),M[n+30]=bi(127.5*i+127.5),M[n+31]=bi(127.5*a+127.5),S){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;S[r>>4][t+i]=bi(128*n[o+s]+128)}}}}return yield h.updateDataAsync(A,null!=S?S:void 0,void 0,u||void 0),h}))}}let Ti=!1;function Ai(){Ti||(Ti=!0,Ys(_i),Xs(_i,!0,e=>new xi(e)))}var wi={__proto__:null,KHR_gaussian_splatting:xi,RegisterKHR_gaussian_splatting:Ai};Ai();const Mi="KHR_lights_punctual";class Si{constructor(e){this.name=Mi,this._loader=e,this.enabled=this._loader.isExtensionUsed(Mi)}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,_r.Assign(this._lights)}}loadNodeAsync(e,n,o){return yr.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=_r.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),yr.AddPointerMetadata(n,s),o(e)})}))}}let Ri=!1;function Ci(){Ri||(Ri=!0,Ys(Mi),Xs(Mi,!0,e=>new Si(e)))}var Ii={__proto__:null,KHR_lights:Si,RegisterKHR_lights:Ci};Ci();const Oi="EXT_lights_area";class Fi{constructor(e){this.name=Oi,this._loader=e,this.enabled=this._loader.isExtensionUsed(Oi)}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,_r.Assign(this._lights)}}loadNodeAsync(e,n,o){return yr.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=_r.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),yr.AddPointerMetadata(i,s),o(e)})}))}}let Ei=!1;function Ni(){Ei||(Ei=!0,Ys(Oi),Xs(Oi,!0,e=>new Fi(e)))}var Li={__proto__:null,EXT_lights_area:Fi,RegisterEXT_lights_area:Ni};Ni();const ki="KHR_materials_pbrSpecularGlossiness";class Pi{constructor(e){this.name=ki,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(ki)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let Bi=!1;function Di(){Bi||(Bi=!0,Ys(ki),Xs(ki,!0,e=>new Pi(e)))}var Vi={__proto__:null,KHR_materials_pbrSpecularGlossiness:Pi,RegisterKHR_materials_pbrSpecularGlossiness:Di};Di();const Gi="KHR_materials_unlit";class $i{constructor(e){this.name=Gi,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(Gi)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let Ui=!1;function Hi(){Ui||(Ui=!0,Ys(Gi),Xs(Gi,!0,e=>new $i(e)))}var Ki={__proto__:null,KHR_materials_unlit:$i,RegisterKHR_materials_unlit:Hi};Hi();const ji="KHR_materials_clearcoat";class Wi{constructor(e){this.name=ji,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(ji)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let qi=!1;function zi(){qi||(qi=!0,Ys(ji),Xs(ji,!0,e=>new Wi(e)))}var Xi={__proto__:null,KHR_materials_clearcoat:Wi,RegisterKHR_materials_clearcoat:zi};zi();const Yi="KHR_materials_coat";class Qi{constructor(e){this.name=Yi,this.order=191,this.useOpenPBR=!1,this._loader=e,this.enabled=this._loader.isExtensionUsed(Yi)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let Zi=!1;function Ji(){Zi||(Zi=!0,Ys(Yi),Xs(Yi,!0,e=>new Qi(e)))}var ea={__proto__:null,KHR_materials_coat:Qi,RegisterKHR_materials_coat:Ji};Ji();const ta="KHR_materials_iridescence";class na{constructor(e){this.name=ta,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(ta)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let oa=!1;function sa(){oa||(oa=!0,Ys(ta),Xs(ta,!0,e=>new na(e)))}var ra={__proto__:null,KHR_materials_iridescence:na,RegisterKHR_materials_iridescence:sa};sa();const ia="KHR_materials_anisotropy";class aa{constructor(e){this.name=ia,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(ia)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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)})}}let la=!1;function ua(){la||(la=!0,Ys(ia),Xs(ia,!0,e=>new aa(e)))}var ca={__proto__:null,KHR_materials_anisotropy:aa,RegisterKHR_materials_anisotropy:ua};ua();const da="KHR_materials_emissive_strength";class ha{constructor(e){this.name=da,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(da)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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)}}let pa=!1;function fa(){pa||(pa=!0,Ys(da),Xs(da,!0,e=>new ha(e)))}var ma={__proto__:null,KHR_materials_emissive_strength:ha,RegisterKHR_materials_emissive_strength:fa};fa();const ga="KHR_materials_sheen";class _a{constructor(e){this.name=ga,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(ga)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let va=!1;function ya(){va||(va=!0,Ys(ga),Xs(ga,!0,e=>new _a(e)))}var ba={__proto__:null,KHR_materials_sheen:_a,RegisterKHR_materials_sheen:ya};ya();const xa="KHR_materials_fuzz";class Ta{constructor(e){this.name=xa,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(xa)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let Aa=!1;function wa(){Aa||(Aa=!0,Ys(xa),Xs(xa,!0,e=>new Ta(e)))}var Ma={__proto__:null,KHR_materials_fuzz:Ta,RegisterKHR_materials_fuzz:wa};wa();const Sa="KHR_materials_specular";class Ra{constructor(e){this.name=Sa,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Sa)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let Ca=!1;function Ia(){Ca||(Ca=!0,Ys(Sa),Xs(Sa,!0,e=>new Ra(e)))}var Oa={__proto__:null,KHR_materials_specular:Ra,RegisterKHR_materials_specular:Ia};Ia();const Fa="KHR_materials_ior";class Ea{constructor(e){this.name=Fa,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(Fa)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(e,t,n){const o=this._loader._getOrCreateMaterialAdapter(n),s=void 0!==t.ior?t.ior:Ea._DEFAULT_IOR;return o.specularIor=s,Promise.resolve()}}Ea._DEFAULT_IOR=1.5;let Na=!1;function La(){Na||(Na=!0,Ys(Fa),Xs(Fa,!0,e=>new Ea(e)))}var ka={__proto__:null,KHR_materials_ior:Ea,RegisterKHR_materials_ior:La};La();const Pa="KHR_materials_variants";class Ba{constructor(e){this.name=Pa,this._loader=e,this.enabled=this._loader.isExtensionUsed(Pa)&&!this._loader.parent.skipMaterials}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return Ba.GetAvailableVariants(e)}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 ${Pa} 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(e,t){Ba.SelectVariant(e,t)}static Reset(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot reset on a glTF mesh that does not have the ${Pa} extension`);for(const e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(e){Ba.Reset(e)}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 ${Pa} extension`);return t.lastSelected}getLastSelectedVariant(e){return Ba.GetLastSelectedVariant(e)}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[Pa])||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}onReady(){var e;const t=this._loader.rootBabylonMesh;if(t){const n=this._loader.parent.extensionOptions[Pa];(null==n?void 0:n.defaultVariant)&&Ba.SelectVariant(t,n.defaultVariant),null===(e=null==n?void 0:n.onLoaded)||void 0===e||e.call(n,{get variants(){return Ba.GetAvailableVariants(t)},get selectedVariant(){const e=Ba.GetLastSelectedVariant(t);return e?Array.isArray(e)?e[0]:e:Ba.GetAvailableVariants(t)[0]},set selectedVariant(e){Ba.SelectVariant(t,e)}})}}_loadMeshPrimitiveAsync(e,n,o,s,r,i){return yr.LoadExtensionAsync(e,r,this.name,(a,l)=>b(this,void 0,void 0,function*(){const u=new Array;return u.push(this._loader._loadMeshPrimitiveAsync(e,n,o,s,r,n=>{if(i(n),n instanceof t.Mesh){const t=yr._GetDrawMode(e,r.mode),o=this._loader.rootBabylonMesh,s=o?o._internalMetadata=o._internalMetadata||{}:{},i=s.gltf=s.gltf||{},c=i[Pa]=i[Pa]||{lastSelected:null,original:[],variants:{}};c.original.push({mesh:n,material:n.material});for(let e=0;e<l.mappings.length;++e){const s=l.mappings[e],r=_r.Get(`${a}/mappings/${e}/material`,this._loader.gltf.materials,s.material);u.push(this._loader._loadMaterialAsync(`#/materials/${s.material}`,r,n,t,e=>{for(let t=0;t<s.variants.length;++t){const r=s.variants[t],i=_r.Get(`/extensions/${Pa}/variants/${r}`,this._variants,r);c.variants[i.name]=c.variants[i.name]||[],c.variants[i.name].push({mesh:n,material:e}),n.onClonedObservable.add(e=>{const t=e;let s,r=t;do{if(r=r.parent,!r)return;s=Ba._GetExtensionMetadata(r)}while(null===s);if(o&&s===Ba._GetExtensionMetadata(o)){r._internalMetadata={};for(const e in o._internalMetadata)r._internalMetadata[e]=o._internalMetadata[e];r._internalMetadata.gltf=[];for(const e in o._internalMetadata.gltf)r._internalMetadata.gltf[e]=o._internalMetadata.gltf[e];r._internalMetadata.gltf[Pa]={lastSelected:null,original:[],variants:{}};for(const e of s.original)r._internalMetadata.gltf[Pa].original.push({mesh:e.mesh,material:e.material});for(const e in s.variants)if(Object.prototype.hasOwnProperty.call(s.variants,e)){r._internalMetadata.gltf[Pa].variants[e]=[];for(const t of s.variants[e])r._internalMetadata.gltf[Pa].variants[e].push({mesh:t.mesh,material:t.material})}s=r._internalMetadata.gltf[Pa]}for(const e of s.original)e.mesh===n&&(e.mesh=t);for(const e of s.variants[i.name])e.mesh===n&&(e.mesh=t)})}}))}}})),yield Promise.all(u).then(([e])=>e)}))}}let Da=!1;function Va(){Da||(Da=!0,Ys(Pa),Xs(Pa,!0,e=>new Ba(e)))}var Ga={__proto__:null,KHR_materials_variants:Ba,RegisterKHR_materials_variants:Va};Va();class $a{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({},$a._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.forceLayerMaskCheck=!0,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 Ua(e,t){if(e.parent.dontUseTransmissionHelper)return;const n=t.getScene()._transmissionHelper,o=null!=n?n:new $a({},t.getScene());for(const t of Array.from(e._pbrMaterialImpls.values()))o.addMaterialImpl(t);n&&!n._isRenderTargetValid()&&n._setupRenderTargets()}const Ha="KHR_materials_transmission";class Ka{constructor(e){this.name=Ha,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ha),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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&&Ua(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(()=>{})}}let ja=!1;function Wa(){ja||(ja=!0,Ys(Ha),Xs(Ha,!0,e=>new Ka(e)))}var qa={__proto__:null,KHR_materials_transmission:Ka,RegisterKHR_materials_transmission:Wa};Wa();const za="KHR_materials_diffuse_transmission";class Xa{constructor(e){this.name=za,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(za),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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&&Ua(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(()=>{})}}let Ya=!1;function Qa(){Ya||(Ya=!0,Ys(za),Xs(za,!0,e=>new Xa(e)))}var Za={__proto__:null,KHR_materials_diffuse_transmission:Xa,RegisterKHR_materials_diffuse_transmission:Qa};Qa();const Ja="KHR_materials_volume";class el{constructor(e){this.name=Ja,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ja),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let tl=!1;function nl(){tl||(tl=!0,Ys(Ja),Xs(Ja,!0,e=>new el(e)))}var ol={__proto__:null,KHR_materials_volume:el,RegisterKHR_materials_volume:nl};nl();const sl="KHR_materials_volume_scatter";class rl{constructor(e){this.name=sl,this.order=172,this._loader=e,this.enabled=this._loader.isExtensionUsed(sl),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let il=!1;function al(){il||(il=!0,Ys(sl),Xs(sl,!0,e=>new rl(e)))}var ll={__proto__:null,KHR_materials_volume_scatter:rl,RegisterKHR_materials_volume_scatter:al};al();const ul="KHR_materials_dispersion";class cl{constructor(e){this.name=ul,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(ul)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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()}}let dl=!1;function hl(){dl||(dl=!0,Ys(ul),Xs(ul,!0,e=>new cl(e)))}var pl={__proto__:null,KHR_materials_dispersion:cl,RegisterKHR_materials_dispersion:hl};hl();const fl="KHR_materials_diffuse_roughness";class ml{constructor(e){this.name=fl,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(fl)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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(()=>{})}}let gl=!1;function _l(){gl||(gl=!0,Ys(fl),Xs(fl,!0,e=>new ml(e)))}var vl={__proto__:null,KHR_materials_diffuse_roughness:ml,RegisterKHR_materials_diffuse_roughness:_l};_l();const yl="KHR_mesh_quantization";class bl{constructor(e){this.name=yl,this.enabled=e.isExtensionUsed(yl)}dispose(){}}let xl=!1;function Tl(){xl||(xl=!0,Ys(yl),Xs(yl,!0,e=>new bl(e)))}var Al={__proto__:null,KHR_mesh_quantization:bl,RegisterKHR_mesh_quantization:Tl};Tl();const wl="KHR_texture_basisu";class Ml{constructor(e){this.name=wl,this._loader=e,this.enabled=e.isExtensionUsed(wl)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?yr.DefaultSampler:_r.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=_r.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,t)}))}}let Sl=!1;function Rl(){Sl||(Sl=!0,Ys(wl),Xs(wl,!0,e=>new Ml(e)))}var Cl={__proto__:null,KHR_texture_basisu:Ml,RegisterKHR_texture_basisu:Rl};Rl();const Il="KHR_texture_transform";class Ol{constructor(e){this.name=Il,this._loader=e,this.enabled=this._loader.isExtensionUsed(Il)}dispose(){this._loader=null}loadTextureInfoAsync(e,n,o){return yr.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)})}))}}let Fl=!1;function El(){Fl||(Fl=!0,Ys(Il),Xs(Il,!0,e=>new Ol(e)))}var Nl={__proto__:null,KHR_texture_transform:Ol,RegisterKHR_texture_transform:El};El();const Ll="KHR_xmp_json_ld";class kl{constructor(e){this.name=Ll,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ll)}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])}}}let Pl=!1;function Bl(){Pl||(Pl=!0,Ys(Ll),Xs(Ll,!0,e=>new kl(e)))}var Dl={__proto__:null,KHR_xmp_json_ld:kl,RegisterKHR_xmp_json_ld:Bl};Bl();const Vl="KHR_animation_pointer";class Gl{constructor(e){this.name=Vl,this._loader=e,this._pathToObjectConverter=dr(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(Vl)}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}}}let $l=!1;function Ul(){$l||($l=!0,Ys(Vl),Xs(Vl,!0,e=>new Gl(e)))}var Hl={__proto__:null,KHR_animation_pointer:Gl,RegisterKHR_animation_pointer:Ul};function Kl(e,n,o,s){return t.Color3.FromArray(n,o).scale(s)}function jl(e,t,n,o){return t[n+3]*o}function Wl(e,t,n,o){return t[n]*o}function ql(e,t,n,o){return-t[n]*o}function zl(e,t,n,o){return t[n+1]*o}function Xl(e,t,n,o){return t[n]*o*2}function Yl(e){return{scale:[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.uScale`,Wl,()=>2),new Zl(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.vScale`,zl,()=>2)],offset:[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,Wl,()=>2),new Zl(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,zl,()=>2)],rotation:[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.wAng`,ql,()=>1)]}}class Ql extends Sr{buildAnimations(e,t,n,o){return[{babylonAnimatable:e._babylonCamera,babylonAnimation:this._buildAnimation(t,n,o)}]}}class Zl extends Sr{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 Jl extends Sr{buildAnimations(e,t,n,o){return[{babylonAnimatable:e._babylonLight,babylonAnimation:this._buildAnimation(t,n,o)}]}}class eu extends Sr{buildAnimations(e,t,n,o){return e._primitiveBabylonMeshes?e._primitiveBabylonMeshes.map(e=>({babylonAnimatable:e,babylonAnimation:this._buildAnimation(t,n,o)})):[]}}let tu=!1;function nu(){if(tu)return;tu=!0,Or(),pr("/cameras/{}/orthographic/xmag",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"orthoLeft",ql,()=>1),new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"orthoRight",zl,()=>1)]),pr("/cameras/{}/orthographic/ymag",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"orthoBottom",ql,()=>1),new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"orthoTop",zl,()=>1)]),pr("/cameras/{}/orthographic/zfar",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"maxZ",Wl,()=>1)]),pr("/cameras/{}/orthographic/znear",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"minZ",Wl,()=>1)]),pr("/cameras/{}/perspective/yfov",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"fov",Wl,()=>1)]),pr("/cameras/{}/perspective/zfar",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"maxZ",Wl,()=>1)]),pr("/cameras/{}/perspective/znear",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"minZ",Wl,()=>1)]),pr("/materials/{}/pbrMetallicRoughness/baseColorFactor",[new Zl(t.Animation.ANIMATIONTYPE_COLOR3,"albedoColor",Kl,()=>4),new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"alpha",jl,()=>4)]),pr("/materials/{}/pbrMetallicRoughness/metallicFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"metallic",Wl,()=>1)]),pr("/materials/{}/pbrMetallicRoughness/metallicFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"roughness",Wl,()=>1)]);const e=Yl("albedoTexture");pr("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/scale",e.scale),pr("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/offset",e.offset),pr("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/rotation",e.rotation);const n=Yl("metallicTexture");pr("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/scale",n.scale),pr("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/offset",n.offset),pr("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/rotation",n.rotation),pr("/materials/{}/emissiveFactor",[new Zl(t.Animation.ANIMATIONTYPE_COLOR3,"emissiveColor",Kl,()=>3)]);const o=Yl("bumpTexture");pr("/materials/{}/normalTexture/scale",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"bumpTexture.level",Wl,()=>1)]),pr("/materials/{}/normalTexture/extensions/KHR_texture_transform/scale",o.scale),pr("/materials/{}/normalTexture/extensions/KHR_texture_transform/offset",o.offset),pr("/materials/{}/normalTexture/extensions/KHR_texture_transform/rotation",o.rotation),pr("/materials/{}/occlusionTexture/strength",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",Wl,()=>1)]);const s=Yl("ambientTexture");pr("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/scale",s.scale),pr("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/offset",s.offset),pr("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/rotation",s.rotation);const r=Yl("emissiveTexture");pr("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/scale",r.scale),pr("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/offset",r.offset),pr("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/rotation",r.rotation),pr("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyStrength",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyRotation",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"anisotropy.angle",Wl,()=>1)]);const i=Yl("anisotropy.texture");pr("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/scale",i.scale),pr("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/offset",i.offset),pr("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/rotation",i.rotation),pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",Wl,()=>1)]);const a=Yl("clearCoat.texture");pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/scale",a.scale),pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/offset",a.offset),pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/rotation",a.rotation);const l=Yl("clearCoat.bumpTexture");pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/scale",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/scale",l.scale),pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/offset",l.offset),pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/rotation",l.rotation);const u=Yl("clearCoat.textureRoughness");pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/scale",u.scale),pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/offset",u.offset),pr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/rotation",u.rotation),pr("/materials/{}/extensions/KHR_materials_dispersion/dispersionFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_emissive_strength/emissiveStrength",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"emissiveIntensity",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_ior/ior",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"indexOfRefraction",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.intensity",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceIor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMinimum",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMaximum",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",Wl,()=>1)]);const c=Yl("iridescence.texture");pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/scale",c.scale),pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/offset",c.offset),pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/rotation",c.rotation);const d=Yl("iridescence.thicknessTexture");pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/scale",d.scale),pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/offset",d.offset),pr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/rotation",d.rotation),pr("/materials/{}/extensions/KHR_materials_sheen/sheenColorFactor",[new Zl(t.Animation.ANIMATIONTYPE_COLOR3,"sheen.color",Kl,()=>3)]),pr("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"sheen.roughness",Wl,()=>1)]);const h=Yl("sheen.texture");pr("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/scale",h.scale),pr("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/offset",h.offset),pr("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/rotation",h.rotation);const p=Yl("sheen.textureRoughness");pr("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/scale",p.scale),pr("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/offset",p.offset),pr("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/rotation",p.rotation),pr("/materials/{}/extensions/KHR_materials_specular/specularFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"metallicF0Factor",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_specular/specularColorFactor",[new Zl(t.Animation.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",Kl,()=>3)]);const f=Yl("metallicReflectanceTexture");pr("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/scale",f.scale),pr("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/offset",f.offset),pr("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/rotation",f.rotation);const m=Yl("reflectanceTexture");pr("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/scale",m.scale),pr("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/offset",m.offset),pr("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/rotation",m.rotation),pr("/materials/{}/extensions/KHR_materials_transmission/transmissionFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",Wl,()=>1)]);const g=Yl("subSurface.refractionIntensityTexture");pr("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/scale",g.scale),pr("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/offset",g.offset),pr("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/rotation",g.rotation),pr("/materials/{}/extensions/KHR_materials_volume/attenuationColor",[new Zl(t.Animation.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",Kl,()=>3)]),pr("/materials/{}/extensions/KHR_materials_volume/attenuationDistance",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",Wl,()=>1)]),pr("/materials/{}/extensions/KHR_materials_volume/thicknessFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",Wl,()=>1)]);const _=Yl("subSurface.thicknessTexture");pr("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/scale",_.scale),pr("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/offset",_.offset),pr("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/rotation",_.rotation),pr("/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.translucencyIntensity",Wl,()=>1)]);const v=Yl("subSurface.translucencyIntensityTexture");pr("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/scale",v.scale),pr("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/offset",v.offset),pr("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/rotation",v.rotation),pr("/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorFactor",[new Zl(t.Animation.ANIMATIONTYPE_COLOR3,"subSurface.translucencyColor",Kl,()=>3)]);const y=Yl("subSurface.translucencyColorTexture");pr("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/scale",y.scale),pr("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/offset",y.offset),pr("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/rotation",y.rotation),pr("/extensions/KHR_lights_punctual/lights/{}/color",[new Jl(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",Kl,()=>3)]),pr("/extensions/KHR_lights_punctual/lights/{}/intensity",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",Wl,()=>1)]),pr("/extensions/KHR_lights_punctual/lights/{}/range",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"range",Wl,()=>1)]),pr("/extensions/KHR_lights_punctual/lights/{}/spot/innerConeAngle",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"innerAngle",Xl,()=>1)]),pr("/extensions/KHR_lights_punctual/lights/{}/spot/outerConeAngle",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"angle",Xl,()=>1)]),pr("/extensions/EXT_lights_area/lights/{}/color",[new Jl(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",Kl,()=>3)]),pr("/extensions/EXT_lights_area/lights/{}/intensity",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",Wl,()=>1)]),pr("/extensions/EXT_lights_area/lights/{}/size",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"radius",Wl,()=>1)]),pr("/extensions/EXT_lights_area/lights/{}/rect/aspect",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"radius",Wl,()=>1)]),pr("/nodes/{}/extensions/EXT_lights_ies/color",[new Jl(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",Kl,()=>3)]),pr("/nodes/{}/extensions/EXT_lights_ies/multiplier",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",Wl,()=>1)]),pr("/nodes/{}/extensions/KHR_node_visibility/visible",[new eu(t.Animation.ANIMATIONTYPE_FLOAT,"isVisible",Wl,()=>1)])}var ou={__proto__:null,_RegisterKHRAnimationPointerData:nu};nu(),Ul();const su="MSFT_audio_emitter";class ru{constructor(e){this.name=su,this._loader=e,this.enabled=this._loader.isExtensionUsed(su)}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,_r.Assign(this._clips),_r.Assign(this._emitters)}}loadSceneAsync(e,t){return yr.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=_r.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 yr.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=_r.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 yr.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;_r.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=_r.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=_r.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=_r.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()})}})}}let iu=!1;function au(){iu||(iu=!0,Ys(su),Xs(su,!0,e=>new ru(e)))}var lu={__proto__:null,MSFT_audio_emitter:ru,RegisterMSFT_audio_emitter:au};au();const uu="MSFT_lod";class cu{constructor(e){var n,o;this.name=uu,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[uu])||void 0===n?void 0:n.maxLODsToLoad)&&void 0!==o?o:this.maxLODsToLoad,this.enabled=this._loader.isExtensionUsed(uu)}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 yr.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:yr.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(_r.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()}}let du=!1;function hu(){du||(du=!0,Ys(uu),Xs(uu,!0,e=>new cu(e)))}var pu={__proto__:null,MSFT_lod:cu,RegisterMSFT_lod:hu};hu();const fu="MSFT_minecraftMesh";class mu{constructor(e){this.name=fu,this._loader=e,this.enabled=this._loader.isExtensionUsed(fu)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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}}))}}let gu=!1;function _u(){gu||(gu=!0,Ys(fu),Xs(fu,!0,e=>new mu(e)))}var vu={__proto__:null,MSFT_minecraftMesh:mu,RegisterMSFT_minecraftMesh:_u};_u();const yu="MSFT_sRGBFactors";class bu{constructor(e){this.name=yu,this._loader=e,this.enabled=this._loader.isExtensionUsed(yu)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.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}}))}}let xu=!1;function Tu(){xu||(xu=!0,Ys(yu),Xs(yu,!0,e=>new bu(e)))}var Au={__proto__:null,MSFT_sRGBFactors:bu,RegisterMSFT_sRGBFactors:Tu};function wu(e){const[t,n]=e.split(":");return Ru({op:t,extension:n})}function Mu(e){return"flow/waitAll"!==e&&(e.startsWith("flow/")||e.startsWith("animation/")||"pointer/set"===e||"pointer/interpolate"===e||"variable/set"===e||"variable/interpolate"===e||"event/send"===e||"event/stopPropagation"===e||"flow/log:BABYLON"===e)}function Su(e){const t=e=>{if(Array.isArray(e))return e.slice();if(null!==e&&"object"==typeof e){if("function"==typeof e.asArray)return Array.from(e.asArray());if(Object.prototype.hasOwnProperty.call(e,"value")){const t=e.value;return Array.isArray(t)?t.slice():[t]}}return[e]};return Array.isArray(e)?e.filter(e=>null!==e&&"object"==typeof e&&"string"==typeof e.id).map(e=>Object.assign({id:e.id,type:e.type},void 0===e.value?{}:{value:t(e.value)})).sort((e,t)=>e.id.localeCompare(t.id)):null!==e&&"object"==typeof e?Object.entries(e).map(([e,n])=>{var o;if(null===n||"object"!=typeof n)return{id:e,malformed:!0};const s=n;return Object.assign({id:e,type:"string"==typeof s.type?s.type:null===(o=s.type)||void 0===o?void 0:o.typeName},void 0===s.value?{}:{value:t(s.value)})}).sort((e,t)=>e.id.localeCompare(t.id)):e}function Ru(e,n=!0){const o=e.extension?Ou(Eu,e.extension):void 0,s=e.extension?Ou(o,e.op):Ou(Nu,e.op);return!s&&n?(t.Logger.Warn(`No mapping found for operation ${e.op} and extension ${e.extension||"KHR_interactivity"}`),Cu(e)):s}function Cu(e){const t={},n={flows:{}};if(e.inputValueSockets){t.values=Object.create(null);for(const n in e.inputValueSockets)Object.prototype.hasOwnProperty.call(e.inputValueSockets,n)&&Object.defineProperty(t.values,n,{configurable:!0,enumerable:!0,value:{name:n},writable:!0})}return e.outputValueSockets&&(n.values=Object.create(null),Object.keys(e.outputValueSockets).forEach(e=>{Object.defineProperty(n.values,e,{configurable:!0,enumerable:!0,value:{name:e},writable:!0})})),{blocks:[],inputs:t,outputs:n}}function Iu(e,t,n){let o=Ou(Eu,t);o||(o=Object.create(null),Object.defineProperty(Eu,t,{configurable:!0,enumerable:!0,value:o,writable:!0})),Object.defineProperty(o,e,{configurable:!0,enumerable:!0,value:n,writable:!0})}function Ou(e,t){return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Fu(){const e=Object.keys(Nu).map(e=>({op:e,mapping:Nu[e]}));for(const t of Object.keys(Eu).sort())for(const n of Object.keys(Eu[t]).sort())e.push({op:n,extension:t,mapping:Eu[t][n]});return e.sort((e,t)=>{var n,o;return`${null!==(n=e.extension)&&void 0!==n?n:""}:${e.op}`.localeCompare(`${null!==(o=t.extension)&&void 0!==o?o:""}:${t.op}`)})}Tu();const Eu={BABYLON:{"flow/log":{blocks:["FlowGraphConsoleLogBlock"],inputs:{values:{message:{name:"message"},"[segment]":{name:"$1",compatibilityOnly:!0}}},outputs:{flows:{out:{name:"out",compatibilityOnly:!0}}}}}},Nu={"event/onStart":{blocks:["FlowGraphSceneReadyEventBlock"],outputs:{values:{event:{name:"event"}},flows:{out:{name:"done"}}}},"event/onTick":{blocks:["FlowGraphSceneTickEventBlock"],inputs:{},outputs:{values:{timeSinceStart:{name:"timeSinceStart",gltfType:"number"},timeSinceLastTick:{name:"deltaTime",gltfType:"number"},event:{name:"event"}},flows:{out:{name:"done"}}}},"event/send":{blocks:["FlowGraphSendCustomEventBlock"],configuration:{event:{name:"eventId",configurationType:"int",required:!0,indexSource:"events",validationOnly:!0}},inputs:{values:{"[segment]":{name:"$1"}}},outputs:{flows:{out:{name:"out"}}},extraProcessor(e,t,n,o,s){var r,i;if("event/send"!==t.op||!(null===(r=e.configuration)||void 0===r?void 0:r.event))throw new Error("Send event should have a single configuration object, the event itself");const a=null===(i=e.configuration.event.value)||void 0===i?void 0:i[0];if("number"!=typeof a)throw new Error("Event id should be a number");const l=o.arrays.events[a],u=s[0];return u.config||(u.config={}),u.config.eventId=l.eventId,u.config.eventData=l.eventData,s}},"event/receive":{blocks:["FlowGraphReceiveCustomEventBlock"],configuration:{event:{name:"eventId",configurationType:"int",required:!0,indexSource:"events",validationOnly:!0}},outputs:{values:{event:{name:"event"},"[segment]":{name:"$1"}},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,i;if("event/receive"!==t.op||!(null===(r=e.configuration)||void 0===r?void 0:r.event))throw new Error("Receive event should have a single configuration object, the event itself");const a=null===(i=e.configuration.event.value)||void 0===i?void 0:i[0];if("number"!=typeof a)throw new Error("Event id should be a number");const l=o.arrays.events[a],u=s[0];return u.config||(u.config={}),u.config.eventId=l.eventId,u.config.eventData=l.eventData,s}},"event/stopPropagation":{blocks:["FlowGraphStopEventPropagationBlock"],inputs:{values:{event:{name:"event"},stopImmediate:{name:"stopImmediate"}},flows:{in:{name:"in"}}},outputs:{flows:{out:{name:"out"}}}},"math/E":Lu("FlowGraphEBlock",[]),"math/Pi":Lu("FlowGraphPIBlock",[]),"math/Tau":Lu("FlowGraphTauBlock",[]),"math/Inf":Lu("FlowGraphInfBlock",[]),"math/NaN":Lu("FlowGraphNaNBlock",[]),"math/abs":Lu("FlowGraphAbsBlock"),"math/sign":Lu("FlowGraphSignBlock"),"math/trunc":Lu("FlowGraphTruncBlock"),"math/floor":Lu("FlowGraphFloorBlock"),"math/ceil":Lu("FlowGraphCeilBlock"),"math/round":{blocks:["FlowGraphRoundBlock"],configuration:{},inputs:{values:{a:{name:"a"}}},outputs:{values:{value:{name:"value",typeSourceInput:"a"}}},extraProcessor(e,t,n,o,s){var r;return(r=s[0]).config||(r.config={}),s[0].config.roundHalfAwayFromZero=!0,s}},"math/fract":Lu("FlowGraphFractBlock"),"math/neg":Lu("FlowGraphNegationBlock"),"math/add":Lu("FlowGraphAddBlock",["a","b"],!0),"math/sub":Lu("FlowGraphSubtractBlock",["a","b"],!0),"math/mul":{blocks:["FlowGraphMultiplyBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value",typeSourceInput:"a"}}},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?ku(e):{valid:!0}},"math/div":Lu("FlowGraphDivideBlock",["a","b"],!0),"math/rem":Lu("FlowGraphModuloBlock",["a","b"]),"math/min":Lu("FlowGraphMinBlock",["a","b"]),"math/max":Lu("FlowGraphMaxBlock",["a","b"]),"math/clamp":Lu("FlowGraphClampBlock",["a","b","c"]),"math/saturate":Lu("FlowGraphSaturateBlock"),"math/mix":Lu("FlowGraphMathInterpolationBlock",["a","b","c"]),"math/smoothStep":Lu("FlowGraphSmoothStepBlock",["a","b","c"]),"math/rgbToOkLCh":{blocks:["FlowGraphRGBToOkLChBlock"],inputs:{values:{r:{name:"r",gltfType:"number"},g:{name:"g",gltfType:"number"},b:{name:"b",gltfType:"number"}}},outputs:{values:{l:{name:"l"},c:{name:"c"},h:{name:"h"}}}},"math/rgbFromOkLCh":{blocks:["FlowGraphRGBFromOkLChBlock"],inputs:{values:{l:{name:"l",gltfType:"number"},c:{name:"c",gltfType:"number"},h:{name:"h",gltfType:"number"}}},outputs:{values:{r:{name:"r"},g:{name:"g"},b:{name:"b"}}}},"math/quatSlerp":Lu("FlowGraphMathSlerpBlock",["a","b","c"]),"math/slerp":Lu("FlowGraphVectorSlerpBlock",["a","b","c"]),"math/eq":Lu("FlowGraphEqualityBlock",["a","b"]),"ref/eq":Lu("FlowGraphEqualityBlock",["a","b"]),"math/lt":Lu("FlowGraphLessThanBlock",["a","b"]),"math/le":Lu("FlowGraphLessThanOrEqualBlock",["a","b"]),"math/gt":Lu("FlowGraphGreaterThanBlock",["a","b"]),"math/ge":Lu("FlowGraphGreaterThanOrEqualBlock",["a","b"]),"math/isNaN":Lu("FlowGraphIsNaNBlock"),"math/isInf":Lu("FlowGraphIsInfBlock"),"math/select":{blocks:["FlowGraphConditionalBlock"],inputs:{values:{condition:{name:"condition"},a:{name:"onTrue"},b:{name:"onFalse"}}},outputs:{values:{value:{name:"output",typeSourceInput:"a"}}}},"math/random":{blocks:["FlowGraphRandomBlock"],outputs:{values:{value:{name:"value",gltfType:"float"}}}},"math/sin":Lu("FlowGraphSinBlock"),"math/cos":Lu("FlowGraphCosBlock"),"math/tan":Lu("FlowGraphTanBlock"),"math/asin":Lu("FlowGraphASinBlock"),"math/acos":Lu("FlowGraphACosBlock"),"math/atan":Lu("FlowGraphATanBlock"),"math/atan2":Lu("FlowGraphATan2Block",["a","b"]),"math/sinh":Lu("FlowGraphSinhBlock"),"math/cosh":Lu("FlowGraphCoshBlock"),"math/tanh":Lu("FlowGraphTanhBlock"),"math/asinh":Lu("FlowGraphASinhBlock"),"math/acosh":Lu("FlowGraphACoshBlock"),"math/atanh":Lu("FlowGraphATanhBlock"),"math/exp":Lu("FlowGraphExponentialBlock"),"math/log":Lu("FlowGraphLogBlock"),"math/log2":Lu("FlowGraphLog2Block"),"math/log10":Lu("FlowGraphLog10Block"),"math/sqrt":Lu("FlowGraphSquareRootBlock"),"math/cbrt":Lu("FlowGraphCubeRootBlock"),"math/pow":Lu("FlowGraphPowerBlock",["a","b"]),"math/length":Lu("FlowGraphLengthBlock"),"math/normalize":Object.assign(Object.assign({},Lu("FlowGraphNormalizeBlock")),{outputs:{values:{value:{name:"value",typeSourceInput:"a"},isValid:{name:"isValid",gltfType:"bool"}}}}),"math/dot":Lu("FlowGraphDotBlock",["a","b"]),"math/cross":Lu("FlowGraphCrossBlock",["a","b"]),"math/rotate2D":{blocks:["FlowGraphRotate2DBlock"],inputs:{values:{a:{name:"a"},angle:{name:"b"}}},outputs:{values:{value:{name:"value",typeSourceInput:"a"}}}},"math/rotate3D":{blocks:["FlowGraphRotate3DBlock"],inputs:{values:{a:{name:"a"},rotation:{name:"b"}}},outputs:{values:{value:{name:"value",typeSourceInput:"a"}}}},"math/transform":{blocks:["FlowGraphTransformVectorBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value",typeSourceInput:"a"}}}},"math/combine2":{blocks:["FlowGraphCombineVector2Block"],inputs:{values:{a:{name:"input_0",gltfType:"number"},b:{name:"input_1",gltfType:"number"}}},outputs:{values:{value:{name:"value",gltfType:"float2"}}}},"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",gltfType:"float3"}}}},"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",gltfType:"float4"}}}},"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":Lu("FlowGraphTransposeBlock"),"math/determinant":Lu("FlowGraphDeterminantBlock"),"math/inverse":Object.assign(Object.assign({},Lu("FlowGraphInvertMatrixBlock")),{outputs:{values:{value:{name:"value",typeSourceInput:"a"},isValid:{name:"isValid",gltfType:"bool"}}}}),"math/matMul":Lu("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",gltfType:"float4x4"}}},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"},scaling:{name:"scaling",compatibilityOnly:!0},isValid:{name:"isValid",compatibilityOnly:!0}}},extraProcessor(e,t,n,o,s){var r;return(r=s[0]).config||(r.config={}),s[0].config.keepDegenerateComponents=!0,s}},"math/quatConjugate":Lu("FlowGraphConjugateBlock",["a"]),"math/quatMul":{blocks:["FlowGraphMultiplyBlock"],inputs:{values:{a:{name:"a",gltfType:"float4"},b:{name:"b",gltfType:"float4"}}},outputs:{values:{value:{name:"value",gltfType:"float4"}}},extraProcessor(e,t,n,o,s){var r;return(r=s[0]).config||(r.config={}),s[0].config.type="Quaternion",s}},"math/quatAngleBetween":Lu("FlowGraphAngleBetweenBlock",["a","b"]),"math/quatFromAxisAngle":{blocks:["FlowGraphQuaternionFromAxisAngleBlock"],inputs:{values:{axis:{name:"a",gltfType:"float3"},angle:{name:"b",gltfType:"number"}}},outputs:{values:{value:{name:"value",gltfType:"float4"}}}},"math/quatToAxisAngle":{blocks:["FlowGraphAxisAngleFromQuaternionBlock"],inputs:{values:{a:{name:"a",gltfType:"float4"}}},outputs:{values:{axis:{name:"axis",gltfType:"float3"},angle:{name:"angle",gltfType:"float"}}}},"math/quatFromDirections":Object.assign(Object.assign({},Lu("FlowGraphQuaternionFromDirectionsBlock",["a","b"])),{outputs:{values:{value:{name:"value",gltfType:"float4"}}}}),"math/quatFromUpForward":{blocks:["FlowGraphQuaternionFromUpForwardBlock"],inputs:{values:{up:{name:"a",gltfType:"float3"},forward:{name:"b",gltfType:"float3"}}},outputs:{values:{value:{name:"value",gltfType:"float4"}}}},"math/quatFromAngles":{blocks:["FlowGraphQuaternionFromAnglesBlock"],configuration:{order:{name:"order",defaultValue:["yxz"],configurationType:"string",invalidUsesDefault:!0,allowedValues:["xyz","xzy","yxz","yzx","zxy","zyx"]}},inputs:{values:{x:{name:"a",gltfType:"number"},y:{name:"b",gltfType:"number"},z:{name:"c",gltfType:"number"}}},outputs:{values:{value:{name:"value",gltfType:"float4"}}}},"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",gltfType:"float2x2"}}}},"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",gltfType:"float3x3"}}}},"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",gltfType:"float4x4"}}}},"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",typeSourceInput:"a"}}},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",typeSourceInput:"a"}}},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",typeSourceInput:"a"}}},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",typeSourceInput:"a"}}},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":Lu("FlowGraphBitwiseRightShiftBlock",["a","b"]),"math/lsl":Lu("FlowGraphBitwiseLeftShiftBlock",["a","b"]),"math/clz":Lu("FlowGraphLeadingZerosBlock"),"math/ctz":Lu("FlowGraphTrailingZerosBlock"),"math/popcnt":Lu("FlowGraphOneBitsCounterBlock"),"math/rad":Lu("FlowGraphDegToRadBlock"),"math/deg":Lu("FlowGraphRadToDegBlock"),"type/boolToInt":Lu("FlowGraphBooleanToInt"),"type/boolToFloat":Lu("FlowGraphBooleanToFloat"),"type/intToBool":Lu("FlowGraphIntToBoolean"),"type/intToFloat":Lu("FlowGraphIntToFloat"),"type/floatToInt":Lu("FlowGraphFloatToInt"),"type/floatToBool":Lu("FlowGraphFloatToBoolean"),"flow/sequence":{blocks:["FlowGraphSequenceBlock"],outputs:{flows:{"[segment]":{name:"$1"}}},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"],inputs:{values:{condition:{name:"condition",gltfType:"boolean"}}},outputs:{flows:{true:{name:"onTrue"},false:{name:"onFalse"}}}},"flow/switch":{blocks:["FlowGraphSwitchBlock"],configuration:{cases:{name:"cases",isArray:!0,inOptions:!0,defaultValue:[],configurationType:"int[]",invalidUsesDefault:!0,generatesOutputFlowSockets:!0,uniqueValues:!0}},inputs:{values:{selection:{name:"case"},default:{name:"default"}}},outputs:{flows:{default:{name:"default"},"[segment]":{name:"$1"}}},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&&Number.isInteger(e)&&e>=-2147483648&&e<=2147483647))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"],inputs:{values:{condition:{name:"condition",gltfType:"boolean"}}},outputs:{flows:{loopBody:{name:"executionFlow"},completed:{name:"completed"}}}},"flow/for":{blocks:["FlowGraphForLoopBlock"],configuration:{initialIndex:{name:"initialIndex",gltfType:"int",inOptions:!0,defaultValue:0,configurationType:"int",invalidUsesDefault:!0}},inputs:{values:{startIndex:{name:"startIndex",gltfType:"int"},endIndex:{name:"endIndex",gltfType:"int"}}},outputs:{values:{index:{name:"index"}},flows:{loopBody:{name:"executionFlow"},completed:{name:"completed"}}},extraProcessor(e,t,n,o,s){const r=s[0];return r.config||(r.config={}),r.config.incrementIndexWhenLoopDone=!0,r.config.maxLoopIterations=2e4,s}},"flow/doN":{blocks:["FlowGraphDoNBlock"],configuration:{},inputs:{values:{n:{name:"maxExecutions",gltfType:"int"}},flows:{reset:{name:"reset"}}},outputs:{flows:{out:{name:"out"}},values:{currentCount:{name:"executionCount"}}}},"flow/multiGate":{blocks:["FlowGraphMultiGateBlock"],inputs:{flows:{reset:{name:"reset"}}},configuration:{isRandom:{name:"isRandom",gltfType:"boolean",inOptions:!0,defaultValue:!1,configurationType:"bool",invalidUsesDefault:!0,configurationGroup:"multiGate"},isLoop:{name:"isLoop",gltfType:"boolean",inOptions:!0,defaultValue:!1,configurationType:"bool",invalidUsesDefault:!0,configurationGroup:"multiGate"}},outputs:{flows:{"[segment]":{name:"$1"}},values:{lastIndex:{name:"lastIndex",gltfType:"int"}}},extraProcessor(e,t,n,o,s){var r;if("flow/multiGate"!==t.op)throw new Error("Invalid operation for MultiGate mapping");const i=s[0];return i.config||(i.config={}),i.config.outputSignalCount=Object.keys(null!==(r=e.flows)&&void 0!==r?r:{}).length,i.signalOutputs.forEach((e,t)=>{e.name="out_"+t}),s}},"flow/waitAll":{blocks:["FlowGraphWaitAllBlock"],configuration:{inputFlows:{name:"inputSignalCount",gltfType:"number",inOptions:!0,defaultValue:[0],configurationType:"int",invalidUsesDefault:!0,minimum:0,maximum:64,generatesInputFlowSockets:!0}},inputs:{flows:{reset:{name:"reset"},"[segment]":{name:"in_$1"}}},outputs:{flows:{out:{name:"out"},completed:{name:"completed"}},values:{remainingInputs:{name:"remainingInputs",gltfType:"int"}}},validation(e){var t,n;const o=null===(n=null===(t=e.configuration)||void 0===t?void 0:t.inputFlows)||void 0===n?void 0:n.value,s=null==o?void 0:o[0];return(1!==(null==o?void 0:o.length)||"number"!=typeof s||!Number.isInteger(s)||s<0||s>64)&&(e.configuration=e.configuration||{inputFlows:{value:[0]}},e.configuration.inputFlows.value=[0]),{valid:!0}}},"flow/throttle":{blocks:["FlowGraphThrottleBlock"],inputs:{values:{duration:{name:"duration",gltfType:"number"}},flows:{reset:{name:"reset"}}},outputs:{flows:{out:{name:"out"},err:{name:"error"}},values:{lastRemainingTime:{name:"lastRemainingTime",gltfType:"number"}}}},"flow/setDelay":{blocks:["FlowGraphSetDelayBlock"],inputs:{values:{duration:{name:"duration",gltfType:"number"}},flows:{cancel:{name:"cancel"}}},outputs:{flows:{out:{name:"out"},err:{name:"error"},done:{name:"done"}},values:{lastDelay:{name:"lastDelayIndex"},lastDelayIndex:{name:"lastDelayIndex",compatibilityOnly:!0}}}},"flow/cancelDelay":{blocks:["FlowGraphCancelDelayBlock"],inputs:{values:{delay:{name:"delayIndex",gltfType:"ref"}}},outputs:{flows:{out:{name:"out"}}}},"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",configurationType:"int",required:!0,indexSource:"variables",flowGraphType:"string",inOptions:!0,isVariable:!0,dataTransformer:(e,t)=>t.getVariableName(e)}},outputs:{values:{value:{name:"value"}}}},"variable/set":{blocks:["FlowGraphSetVariableBlock"],inputs:{values:{"[segment]":{name:"$1"}}},configuration:{variables:{name:"variables",gltfType:"number",configurationType:"int[]",required:!0,indexSource:"variables",minItems:1,generatesInputValueSockets:!0,flowGraphType:"string",inOptions:!0,isArray:!0,dataTransformer:(e,t)=>e.map(e=>t.getVariableName(e))}},outputs:{flows:{out:{name:"out",compatibilityOnly:!0}}},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",configurationType:"int",required:!0,indexSource:"variables",inOptions:!0,isVariable:!0,dataTransformer:(e,t)=>t.getVariableName(e)},useSlerp:{name:"animationType",configurationType:"bool",required:!0,inOptions:!0,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],p=null===(a=null===(i=e.configuration)||void 0===i?void 0:i.variable.value)||void 0===a?void 0:a[0];if("number"!=typeof p)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[p];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 m=r[4];return m.config||(m.config={}),(d=m.config).variable||(d.variable={}),m.config.variable.value=s.getVariableName(p),r}},"pointer/get":{blocks:["FlowGraphGetPropertyBlock","FlowGraphJsonPointerParserBlock"],validation:e=>Du(e),configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock",configurationType:"string",required:!0,pointerTemplate:!0},type:{name:"type",configurationType:"int",required:!0,validationOnly:!0,indexSource:"types"}},inputs:{values:{"[segment]":{name:"$1",toBlock:"FlowGraphJsonPointerParserBlock"}}},outputs:{values:{value:{name:"value"},isValid:{name:"isValid",gltfType:"bool"}}},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"],validation:e=>Du(e,new Set(["value"])),configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock",configurationType:"string",required:!0,pointerTemplate:!0},type:{name:"type",configurationType:"int",required:!0,validationOnly:!0,indexSource:"types"}},inputs:{values:{value:{name:"value"},"[segment]":{name:"$1",toBlock:"FlowGraphJsonPointerParserBlock"}}},outputs:{flows:{err:{name:"error"},out:{name:"out",compatibilityOnly:!0}}},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"],validation:e=>Du(e,new Set(["value","duration","p1","p2"])),configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock",configurationType:"string",required:!0,pointerTemplate:!0},type:{name:"type",configurationType:"int",required:!0,validationOnly:!0,indexSource:"types",allowedSignatures:["float","float2","float3","float4","float2x2","float3x3","float4x4"]}},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:"ref",toBlock:"FlowGraphArrayIndexBlock"},speed:{name:"speed",gltfType:"number"},startTime:{name:"from",gltfType:"number",convertConnectedTimeToFrames:!0,dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]},endTime:{name:"to",gltfType:"number",convertConnectedTimeToFrames:!0,dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]}}},outputs:{flows:{out:{name:"out"},err:{name:"error"},done:{name:"done"}}},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.find(e=>"FlowGraphPlayAnimationBlock"===e.className);a&&(a.config.useVirtualTimeline=!0);const l=s.find(e=>"FlowGraphArrayIndexBlock"===e.className);l&&(l.config.referenceCollection="animations");const u=s[s.length-1];return u.config||(u.config={}),u.config.glTF=i,s}},"animation/stop":{blocks:["FlowGraphStopAnimationBlock","FlowGraphArrayIndexBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],inputs:{values:{animation:{name:"index",gltfType:"ref",toBlock:"FlowGraphArrayIndexBlock"}}},outputs:{flows:{out:{name:"out"},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.find(e=>"FlowGraphStopAnimationBlock"===e.className);a&&(a.config.skipOnAnimationEnd=!0);const l=s.find(e=>"FlowGraphArrayIndexBlock"===e.className);l&&(l.config.referenceCollection="animations");const u=s[s.length-1];return u.config||(u.config={}),u.config.glTF=i,s}},"animation/stopAt":{blocks:["FlowGraphStopAnimationBlock","FlowGraphArrayIndexBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{},inputs:{values:{animation:{name:"index",gltfType:"ref",toBlock:"FlowGraphArrayIndexBlock"},stopTime:{name:"stopAtFrame",gltfType:"number",convertConnectedTimeToFrames:!0,dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]}}},outputs:{flows:{out:{name:"out"},err:{name:"error"},done:{name:"done"}}},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.find(e=>"FlowGraphStopAnimationBlock"===e.className);a&&(a.config.useVirtualStopAt=!0,a.config.skipOnAnimationEnd=!0);const l=s.find(e=>"FlowGraphArrayIndexBlock"===e.className);l&&(l.config.referenceCollection="animations");const u=s[s.length-1];return u.config||(u.config={}),u.config.glTF=i,s}},"math/switch":{blocks:["FlowGraphDataSwitchBlock"],configuration:{cases:{name:"cases",isArray:!0,inOptions:!0,defaultValue:[],configurationType:"int[]",invalidUsesDefault:!0,generatesCaseInputValueSockets:!0,uniqueValues:!0}},inputs:{values:{selection:{name:"case",gltfType:"int"},default:{name:"default"},"[case]":{name:"$1"}}},outputs:{values:{value:{name:"value"}}},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"],inputs:{flows:{in:{name:"in"}},values:{"[parameter]":{name:"$1"}}},outputs:{flows:{out:{name:"out"}}},configuration:{severity:{name:"severity",configurationType:"int",defaultValue:0,invalidUsesDefault:!0,validationOnly:!0,configurationGroup:"debugLog"},message:{name:"messageTemplate",configurationType:"string",defaultValue:"",invalidUsesDefault:!0,inOptions:!0,configurationGroup:"debugLog",debugLogTemplate:!0}}}};function Lu(e,t=["a"],n){return{blocks:[e],inputs:{values:t.reduce((e,t)=>(e[t]={name:t},e),{})},outputs:{values:{value:{name:"value",typeSourceInput:t[0]}}},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?ku(e):{valid:!0}}}function ku(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 Pu(e){for(let t=0;t<e.length;t++){const n=e[t];if(-1==="[]{}".indexOf(n))continue;let o=1;for(;e[t+o]===n;)o++;if(o%2!=0)return!0;t+=o-1}return!1}function Bu(e){let t=0,n=-1;const o=[],s=new Set;for(let r=0;r<e.length;r++){const i=e[r];if("{"===i)if(0===t)t=1;else{if(1!==t)return{valid:!1,sockets:[]};t=0}else if("}"===i)if(0===t)t=3;else if(3===t)t=0;else{if(2!==t)return{valid:!1,sockets:[]};{const i=e.substring(n+1,r);s.has(i)||(s.add(i),o.push(i)),t=0}}else if(1===t)n=r-1,t=2;else if(3===t)return{valid:!1,sockets:[]}}return{valid:0===t,sockets:0===t?o:[]}}function Du(e,t=new Set){var n,o,s;const r=null===(s=null===(o=null===(n=e.configuration)||void 0===n?void 0:n.pointer)||void 0===o?void 0:o.value)||void 0===s?void 0:s[0];if("string"!=typeof r)return{valid:!1,error:"A pointer operation requires a string `pointer` configuration value"};if(0!==r.length&&"/"!==r[0])return{valid:!1,error:`The JSON Pointer Template "${r}" is not a syntactically valid JSON Pointer`};const i=e=>({valid:!1,error:`The JSON Pointer Template "${r}" is invalid: ${e}`}),a=new Set;for(const e of r.split("/")){if(/~(?:[^01]|$)/.test(e))return i(`the path segment "${e}" contains an invalid RFC 6901 escape`);const n="["===e[0]&&"["!==e[1],o="{"===e[0]&&"{"!==e[1];if(!n&&!o){if(Pu(e))return i(`the path segment "${e}" contains an odd number of consecutive brackets`);continue}const s=n?"]":"}",r=e.substring(1,e.length-1);if(e.length<3||e[e.length-1]!==s||/[[{]/.test(r)||/[\]}]/.test(r))return i(`the template parameter path segment "${e}" is malformed`);const l=r.replace(/~1/g,"/").replace(/~0/g,"~");if(t.has(l))return i(`the template parameter "${l}" uses a reserved input socket id`);if(a.has(l))return i(`the template parameter "${l}" is used more than once`);a.add(l)}return{valid:!0}}function Vu(){return Object.keys(Nu)}const Gu="f798712c5685bc9223a628140fba707db8889300",$u={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"},ref:{length:1,flowGraphType:"string",elementType:"string"},custom:{length:0,flowGraphType:"any",elementType:"any"}};function Uu(e){if(void 0!==e){if(null!==e&&"object"==typeof e){const t=e.asArray;if("function"==typeof t)return Array.from(t.call(e));if("value"in e&&"object"!=typeof e.value)return[e.value]}return Array.isArray(e)?e.slice():[e]}}function Hu(e,t){if(void 0===e)return["undefined"];if(null===e)return["null"];switch(typeof e){case"boolean":return["boolean",e];case"number":return["number",Number.isNaN(e)?"NaN":e===1/0?"Infinity":e===-1/0?"-Infinity":Object.is(e,-0)?"-0":e];case"string":return["string",e];case"object":{if(Object.getOwnPropertySymbols(e).length>0)return;if(Array.isArray(e)){if(Object.getOwnPropertyNames(e).some(t=>"length"!==t&&(!/^(0|[1-9]\d*)$/.test(t)||Number(t)>=e.length||!("value"in Object.getOwnPropertyDescriptor(e,t)))))return}else{const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return;if(Object.getOwnPropertyNames(e).some(t=>!Object.prototype.propertyIsEnumerable.call(e,t)||!("value"in Object.getOwnPropertyDescriptor(e,t))))return}if(t.has(e))return;let n;if(t.add(e),Array.isArray(e)){const o=e.map(e=>Hu(e,t));n=o.some(e=>void 0===e)?void 0:["array",o]}else{const o=[];let s=!1;for(const n of Object.keys(e).sort()){const r=Hu(e[n],t);if(void 0===r){s=!0;break}o.push([n,r])}n=s?void 0:["object",o]}return t.delete(e),n}default:return}}function Ku(e){try{const t=Hu(Array.isArray(e)?e:Uu(e),new Set);return void 0===t?{unrepresentable:!0}:{runtimeValueFingerprint:JSON.stringify(t)}}catch(e){return{unrepresentable:!0}}}function ju(e){if(Array.isArray(e))return e.map(e=>ju(e));if(null!==e&&"object"==typeof e){const t={};for(const[n,o]of Object.entries(e))Object.defineProperty(t,n,{configurable:!0,enumerable:!0,value:ju(o),writable:!0});return t}return e}function Wu(e){return ju(e)}function qu(e,t){return"number"==typeof e&&Number.isInteger(e)&&e>=0&&e<t}function zu(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Xu(e,t,n){e.push({path:t,message:n,severity:"error"})}function Yu(e){return""===e||/^(?:\/(?:[^~]|~[01])*)*$/.test(e)}function Qu(e,t,n,o,s,r){var i,a,l,u,c,d;if(e&&Object.prototype.hasOwnProperty.call(e,t))return!0;if(t===r&&e&&Object.prototype.hasOwnProperty.call(e,r))return!0;if(!Object.keys(null!=e?e:{}).some(e=>e.startsWith("[")&&e.endsWith("]")))return!1;if("event/receive"===n.operation){const e=null===(l=null===(a=null===(i=o.configuration)||void 0===i?void 0:i.event)||void 0===a?void 0:a.value)||void 0===l?void 0:l[0];return"number"==typeof e&&Object.prototype.hasOwnProperty.call(null!==(d=null===(c=null===(u=s.events)||void 0===u?void 0:u[e])||void 0===c?void 0:c.values)&&void 0!==d?d:{},t)}return!0}function Zu(e,t,n,o){var s,r;return!!qu(e,null!==(r=null===(s=t.types)||void 0===s?void 0:s.length)&&void 0!==r?r:0)||(Xu(n,o,`Type index ${String(e)} is out of range.`),!1)}function Ju(e,t,n,o){if(!Zu(e.type,t,n,`${o}/type`))return;if(void 0===e.value)return;if(!Array.isArray(e.value))return void Xu(n,`${o}/value`,"Value must be an array when present.");const s=t.types[e.type],r=$u[s.signature];r&&"custom"!==s.signature&&e.value.length!==r.length&&Xu(n,`${o}/value`,`Expected ${r.length} value component(s) for type "${s.signature}", received ${e.value.length}.`);for(let t=0;t<e.value.length;t++){const r=e.value[t];let i=!0;switch(s.signature){case"bool":i="boolean"==typeof r;break;case"int":i="number"==typeof r&&Number.isInteger(r)&&r>=-2147483648&&r<=2147483647;break;case"float":case"float2":case"float3":case"float4":case"float2x2":case"float3x3":case"float4x4":i="number"==typeof r&&Number.isFinite(r);break;case"ref":i="string"==typeof r&&Yu(r)}i||Xu(n,`${o}/value/${t}`,`Value component is invalid for type "${s.signature}".`)}}function ec(e,t){if(!Array.isArray(e))return!1;const n=e=>"number"==typeof e&&Number.isInteger(e)&&e>=-2147483648&&e<=2147483647;switch(t){case"bool":return 1===e.length&&"boolean"==typeof e[0];case"int":return 1===e.length&&n(e[0]);case"int[]":return e.every(n);case"string":return 1===e.length&&"string"==typeof e[0];default:return e.length>0}}function tc(e,t,n){var o,s,r,i,a,l,u,c;switch(t){case"types":return null!==(s=null===(o=e.types)||void 0===o?void 0:o.length)&&void 0!==s?s:0;case"variables":return null!==(i=null===(r=e.variables)||void 0===r?void 0:r.length)&&void 0!==i?i:0;case"events":return null!==(l=null===(a=e.events)||void 0===a?void 0:a.length)&&void 0!==l?l:0;case"nodes":return null!==(c=null===(u=e.nodes)||void 0===u?void 0:u.length)&&void 0!==c?c:0;case"assetNodes":return null!=n?n:0;default:return 0}}function nc(e,t,n,o){var s,r;if(!e||!ec(e.value,t.configurationType)||!e.value)return!1;if(void 0!==t.minItems&&e.value.length<t.minItems)return!1;if(void 0!==t.minimum&&e.value.some(e=>"number"!=typeof e||e<t.minimum))return!1;if(void 0!==t.maximum&&e.value.some(e=>"number"!=typeof e||e>t.maximum))return!1;if(t.indexSource){const s=tc(n,t.indexSource,o);if(e.value.some(e=>!qu(e,s)))return!1}if(t.allowedSignatures){const o=e.value[0],i="number"==typeof o?null===(r=null===(s=n.types)||void 0===s?void 0:s[o])||void 0===r?void 0:r.signature:void 0;if(!i||!t.allowedSignatures.includes(i))return!1}return!(t.allowedValues&&e.value.some(e=>!t.allowedValues.includes(e))||t.debugLogTemplate&&!Bu(e.value[0]).valid)}function oc(e,t,n){var o,s,r,i,a,l,u,c;const d=Wu(e);for(let e=0;e<(null!==(s=null===(o=d.nodes)||void 0===o?void 0:o.length)&&void 0!==s?s:0);e++){const o=d.nodes[e],s=t[o.declaration];if(!s||"unknown-core"===s.support||"unsupported-extension"===s.support)continue;const h=Ru(s.source,!1);if(!(null==h?void 0:h.configuration))continue;const p=new Map;for(const[e,t]of Object.entries(h.configuration))if(t.configurationGroup){const s=nc(null===(r=o.configuration)||void 0===r?void 0:r[e],t,d,n);p.set(t.configurationGroup,(null===(i=p.get(t.configurationGroup))||void 0===i||i)&&s)}for(const[e,t]of Object.entries(h.configuration)){const s=(!t.configurationGroup||!0===p.get(t.configurationGroup))&&nc(null===(a=o.configuration)||void 0===a?void 0:a[e],t,d,n);s||void 0===t.defaultValue?s&&t.uniqueValues&&(null===(c=null===(u=o.configuration)||void 0===u?void 0:u[e])||void 0===c?void 0:c.value)&&(o.configuration[e].value=Array.from(new Set(o.configuration[e].value))):(null!==(l=o.configuration)&&void 0!==l||(o.configuration={}),o.configuration[e]={value:Array.isArray(t.defaultValue)?ju(t.defaultValue):[t.defaultValue]})}}return d}function sc(e){const t=[];for(const n of e.split("/")){const e=n.startsWith("[")&&!n.startsWith("[[")?"int":n.startsWith("{")&&!n.startsWith("{{")?"ref":void 0;if(e){const o=n.substring(1,n.length-1).replace(/~1/g,"/").replace(/~0/g,"~");t.push({name:o,signature:e})}}return t}function rc(e,t,n,o=new Set){var s;return"node"in e?ic(e.node,null!==(s=e.socket)&&void 0!==s?s:"value",t,n,o):e.type}function ic(e,t,n,o,s=new Set){var r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b,x,T,A,w,M,S,R;const C=`${e}:${t}`;if(s.has(C))return;if(s.add(C),!qu(e,null!==(i=null===(r=n.nodes)||void 0===r?void 0:r.length)&&void 0!==i?i:0))return;const I=n.nodes[e];if(!qu(I.declaration,o.length))return;const O=o[I.declaration],F=null===(l=null===(a=O.source.outputValueSockets)||void 0===a?void 0:a[t])||void 0===l?void 0:l.type;if(void 0!==F)return F;const E=e=>{var t,o;const s=null!==(o=null===(t=n.types)||void 0===t?void 0:t.findIndex(t=>t.signature===e))&&void 0!==o?o:-1;return s>=0?s:void 0};if("isValid"===t)return E("bool");if("pointer/get"===O.operation&&"value"===t){const e=null===(d=null===(c=null===(u=I.configuration)||void 0===u?void 0:u.type)||void 0===c?void 0:c.value)||void 0===d?void 0:d[0];return"number"==typeof e?e:void 0}if("variable/get"===O.operation&&"value"===t){const e=null===(f=null===(p=null===(h=I.configuration)||void 0===h?void 0:h.variable)||void 0===p?void 0:p.value)||void 0===f?void 0:f[0];return"number"==typeof e?null===(g=null===(m=n.variables)||void 0===m?void 0:m[e])||void 0===g?void 0:g.type:void 0}if("math/switch"===O.operation&&"value"===t){const e=null===(_=I.values)||void 0===_?void 0:_.default;return e?rc(e,n,o,s):void 0}if("event/receive"===O.operation&&"event"!==t){const e=null===(b=null===(y=null===(v=I.configuration)||void 0===v?void 0:v.event)||void 0===y?void 0:y.value)||void 0===b?void 0:b[0];return"number"==typeof e?null===(w=null===(A=null===(T=null===(x=n.events)||void 0===x?void 0:x[e])||void 0===T?void 0:T.values)||void 0===A?void 0:A[t])||void 0===w?void 0:w.type:void 0}const N=ac(O.operation,t);if(N)return E(String(N));const L=Ru(O.source,!1),k=null===(S=null===(M=null==L?void 0:L.outputs)||void 0===M?void 0:M.values)||void 0===S?void 0:S[t],P=null==k?void 0:k.gltfType,B="number"===P?"float":"boolean"===P?"bool":P;if(B&&B in $u)return E(B);const D=(null==k?void 0:k.typeSourceInput)?null===(R=I.values)||void 0===R?void 0:R[k.typeSourceInput]:void 0;return D?rc(D,n,o,s):void 0}function ac(e,t){return"value"!==t?"math/rgbToOkLCh"===e&&["l","c","h"].includes(t)||"math/rgbFromOkLCh"===e&&["r","g","b"].includes(t)||e.startsWith("math/extract")?"float":"math/matDecompose"===e?"rotation"===t?"float4":"translation"===t||"scale"===t?"float3":void 0:"math/quatToAxisAngle"===e?"axis"===t?"float3":"angle"===t?"float":void 0:"flow/doN"===e&&"currentCount"===t||"flow/for"===e&&"index"===t?"int":"flow/setDelay"===e&&"lastDelay"===t?"ref":"flow/throttle"===e&&"lastRemainingTime"===t?"float":"event/onStart"!==e&&"event/onTick"!==e&&"event/receive"!==e||"event"!==t?"event/onTick"===e&&"timeSinceLastTick"===t||"event/onTick"===e&&"timeSinceStart"===t?"float":void 0:"ref":["math/E","math/Pi","math/Tau","math/Inf","math/NaN","math/random","math/length","math/dot","math/determinant","math/quatAngleBetween"].includes(e)?"float":["math/eq","ref/eq","math/lt","math/le","math/gt","math/ge","math/isNaN","math/isInf","type/intToBool","type/floatToBool"].includes(e)?"bool":["math/clz","math/ctz","math/popcnt","type/boolToInt","type/floatToInt"].includes(e)?"int":["type/boolToFloat","type/intToFloat"].includes(e)?"float":void 0}function lc(e,t,n,o,s,r,i){var a,l,u,c,d,h,p,f,m,g,_,v,y,b,x,T,A,w,M,S,R,C,I,O,F,E,N,L,k,P,B,D,V,G,$,U,H,K,j,W,q,z,X,Y,Q,Z,J;const ee=`${r}/nodes/${t}`;if(!qu(e.declaration,o.length))return void Xu(s,`${ee}/declaration`,`Declaration index ${String(e.declaration)} is out of range.`);const te=o[e.declaration],ne="unsupported-extension"===te.support?Cu(te.source):Ru(te.source,!1);if("unknown-core"===te.support||!ne)return;const oe=(e,t,n)=>{e.invalidUsesDefault||void 0!==e.defaultValue?function(e,t,n){e.push({path:t,message:n,severity:"warning"})}(s,t,`${n} The default configuration will be used.`):Xu(s,t,n)};for(const[t,n]of Object.entries(null!==(a=e.configuration)&&void 0!==a?a:{}))zu(n)?void 0===n.value||Array.isArray(n.value)?n.value&&0===n.value.length&&Xu(s,`${ee}/configuration/${t}/value`,"Configuration value arrays must contain at least one item when present."):Xu(s,`${ee}/configuration/${t}/value`,"Configuration value must be an array when present."):Xu(s,`${ee}/configuration/${t}`,`Configuration "${t}" must be an object.`);for(const[t,r]of Object.entries(null!==(l=ne.configuration)&&void 0!==l?l:{})){const a=null===(u=e.configuration)||void 0===u?void 0:u[t],l=!!a&&ec(a.value,r.configurationType);if(!a&&r.required?Xu(s,`${ee}/configuration/${t}`,`Required configuration "${t}" is missing.`):a&&!l&&oe(r,`${ee}/configuration/${t}`,`Configuration "${t}" is invalid.`),l&&a.value&&void 0!==r.minItems&&a.value.length<r.minItems&&Xu(s,`${ee}/configuration/${t}/value`,`Configuration "${t}" requires at least ${r.minItems} value(s).`),l&&a.value&&r.indexSource){const e=tc(n,r.indexSource,i);for(let n=0;n<a.value.length;n++)qu(a.value[n],e)||oe(r,`${ee}/configuration/${t}/value/${n}`,`Index is out of range for graph ${r.indexSource}.`)}if(l&&a.value&&r.allowedSignatures){const e=a.value[0],o="number"==typeof e?null===(d=null===(c=n.types)||void 0===c?void 0:c[e])||void 0===d?void 0:d.signature:void 0;o&&r.allowedSignatures.includes(o)||oe(r,`${ee}/configuration/${t}/value/0`,`Type "${String(o)}" is not supported by this operation.`)}if(l&&a.value&&r.allowedValues&&a.value.some(e=>!r.allowedValues.includes(e))&&oe(r,`${ee}/configuration/${t}/value`,`Configuration "${t}" contains an unsupported value.`),l&&a.value&&r.debugLogTemplate&&!Bu(a.value[0]).valid&&oe(r,`${ee}/configuration/${t}/value/0`,`Configuration "${t}" is not a valid debug message template.`),l&&a.value&&(void 0!==r.minimum||void 0!==r.maximum)){const e=a.value[0];(void 0!==r.minimum&&e<r.minimum||void 0!==r.maximum&&e>r.maximum)&&oe(r,`${ee}/configuration/${t}/value/0`,`Configuration "${t}" must be between ${String(r.minimum)} and ${String(r.maximum)}.`)}if(l&&a.value&&r.generatesInputValueSockets)for(const t of a.value){if("number"!=typeof t||!qu(t,null!==(p=null===(h=n.variables)||void 0===h?void 0:h.length)&&void 0!==p?p:0))continue;const r=null===(f=e.values)||void 0===f?void 0:f[String(t)];r?rc(r,n,o)!==n.variables[t].type&&Xu(s,`${ee}/values/${t}/type`,`Configured input value socket "${t}" has the wrong type.`):Xu(s,`${ee}/values/${t}`,`Required configured input value socket "${t}" is missing.`)}if(l&&a.value&&r.generatesCaseInputValueSockets){const t=(null===(m=e.values)||void 0===m?void 0:m.default)?rc(e.values.default,n,o):void 0;for(const r of a.value){const i=null===(g=e.values)||void 0===g?void 0:g[String(r)];i?void 0!==t&&rc(i,n,o)!==t&&Xu(s,`${ee}/values/${r}/type`,`Case input value socket "${r}" must match the default socket type.`):Xu(s,`${ee}/values/${r}`,`Required case input value socket "${r}" is missing.`)}}if(l&&a.value&&r.pointerTemplate&&"string"==typeof a.value[0])for(const t of sc(a.value[0])){const r=null===(_=e.values)||void 0===_?void 0:_[t.name],i=null!==(y=null===(v=n.types)||void 0===v?void 0:v.findIndex(e=>e.signature===t.signature))&&void 0!==y?y:-1;r?(i<0||rc(r,n,o)!==i)&&Xu(s,`${ee}/values/${t.name}/type`,`Pointer template input "${t.name}" must have type "${t.signature}".`):Xu(s,`${ee}/values/${t.name}`,`Required pointer template input "${t.name}" is missing.`)}}if("debug/log"===te.operation){const t=null===(b=ne.configuration)||void 0===b?void 0:b.severity,o=null===(x=ne.configuration)||void 0===x?void 0:x.message,r=!!t&&nc(null===(T=e.configuration)||void 0===T?void 0:T.severity,t,n,i),a=!!o&&nc(null===(A=e.configuration)||void 0===A?void 0:A.message,o,n,i),l=r&&a?e.configuration.message.value[0]:"";for(const t of Bu(l).sockets)(null===(w=e.values)||void 0===w?void 0:w[t])||Xu(s,`${ee}/values/${t}`,`Required debug message template input "${t}" is missing.`)}for(const[t,r]of Object.entries(null!==(S=null===(M=ne.inputs)||void 0===M?void 0:M.values)&&void 0!==S?S:{})){if(t.startsWith("[")||(null===(R=e.values)||void 0===R?void 0:R[t])||Xu(s,`${ee}/values/${t}`,`Required input value socket "${t}" is missing.`),"event/send"===te.operation){const t=null===(O=null===(I=null===(C=e.configuration)||void 0===C?void 0:C.event)||void 0===I?void 0:I.value)||void 0===O?void 0:O[0],r="number"==typeof t?null===(F=n.events)||void 0===F?void 0:F[t]:void 0;for(const[t,i]of Object.entries(null!==(E=null==r?void 0:r.values)&&void 0!==E?E:{})){const r=null===(N=e.values)||void 0===N?void 0:N[t];r?rc(r,n,o)!==i.type&&Xu(s,`${ee}/values/${t}/type`,`Custom event input value socket "${t}" has the wrong type.`):Xu(s,`${ee}/values/${t}`,`Required custom event input value socket "${t}" is missing.`)}}const i="number"===r.gltfType?"float":"boolean"===r.gltfType?"bool":r.gltfType,a=null===(L=e.values)||void 0===L?void 0:L[t];if(a&&i&&i in $u){const e=rc(a,n,o);void 0!==e&&(null===(P=null===(k=n.types)||void 0===k?void 0:k[e])||void 0===P?void 0:P.signature)!==i&&Xu(s,`${ee}/values/${t}/type`,`Input value socket "${t}" must have type "${i}".`)}}if(ne.validation)try{const t=ju(e);for(const e of Object.values(null!==(B=t.values)&&void 0!==B?B:{}))void 0===e.type&&(e.type=rc(e,n,o));const r=ne.validation(t,n);r.valid||Xu(s,ee,null!==(D=r.error)&&void 0!==D?D:`Operation "${te.operation}" is invalid.`)}catch(e){Xu(s,ee,e.message)}for(const[r,i]of Object.entries(null!==(V=e.values)&&void 0!==V?V:{}))if(zu(i))if("unsupported-extension"!==te.support||(null===(G=te.source.inputValueSockets)||void 0===G?void 0:G[r])||Xu(s,`${ee}/values/${r}`,`Input value socket "${r}" is not defined by operation "${te.operation}".`),"node"in i){if("value"in i&&Xu(s,`${ee}/values/${r}`,"An input value socket cannot define both inline and node sources."),!qu(i.node,null!==(U=null===($=n.nodes)||void 0===$?void 0:$.length)&&void 0!==U?U:0)){Xu(s,`${ee}/values/${r}/node`,`Node index ${String(i.node)} is out of range.`);continue}i.node>=t&&Xu(s,`${ee}/values/${r}/node`,"Value connections must reference an earlier node."),void 0!==i.type&&Zu(i.type,n,s,`${ee}/values/${r}/type`);const e=n.nodes[i.node];if(qu(e.declaration,o.length)){const t=o[e.declaration],a="unsupported-extension"===t.support?Cu(t.source):Ru(t.source,!1),l=null!==(H=i.socket)&&void 0!==H?H:"value",u=Qu(null===(K=null==a?void 0:a.outputs)||void 0===K?void 0:K.values,l,t,e,n,"value");a&&!u&&Xu(s,`${ee}/values/${r}/socket`,`Output value socket "${l}" does not exist on node ${i.node}.`);const c=null===(W=null===(j=t.source.outputValueSockets)||void 0===j?void 0:j[l])||void 0===W?void 0:W.type,d=null!=c?c:ic(i.node,l,n,o);if(void 0!==i.type){const e=null===(q=null==a?void 0:a.outputs)||void 0===q?void 0:q.values,o=e&&Object.prototype.hasOwnProperty.call(e,l)?e[l]:void 0,u=null==o?void 0:o.gltfType,c="number"===u?"float":"boolean"===u?"bool":"vector2"===u?"float2":"vector3"===u?"float3":"vector4"===u?"float4":u,h=null!==(z=ac(t.operation,l))&&void 0!==z?z:c&&Object.prototype.hasOwnProperty.call($u,c)?c:void 0,p=null===(Y=null===(X=n.types)||void 0===X?void 0:X[i.type])||void 0===Y?void 0:Y.signature;(void 0!==h&&p!==h||void 0===h&&void 0!==d&&i.type!==d)&&Xu(s,`${ee}/values/${r}/type`,`Type assertion does not match output socket "${l}".`)}}}else Ju(i,n,s,`${ee}/values/${r}`);else Xu(s,`${ee}/values/${r}`,`Input value socket "${r}" must be an object.`);for(const[o,r]of Object.entries(null!==(Q=e.flows)&&void 0!==Q?Q:{}))zu(r)?qu(r.node,null!==(J=null===(Z=n.nodes)||void 0===Z?void 0:Z.length)&&void 0!==J?J:0)?r.node<=t&&Xu(s,`${ee}/flows/${o}/node`,"Flow connections must reference a later node."):Xu(s,`${ee}/flows/${o}/node`,`Node index ${String(r.node)} is out of range.`):Xu(s,`${ee}/flows/${o}`,`Output flow socket "${o}" must be an object.`)}function uc(e,t=0,n,o){var s,r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b;const x=[],T=`/extensions/KHR_interactivity/graphs/${t}`;null===e||"object"!=typeof e||Array.isArray(e)?(Xu(x,T,"Behavior graph must be an object."),e={}):e=Wu(e);const A={types:()=>({signature:"custom"}),variables:()=>({type:-1}),events:()=>({}),declarations:()=>({op:""}),nodes:()=>({declaration:-1})};for(const t of["types","variables","events","declarations","nodes"]){const n=e[t];void 0===n||Array.isArray(n)?Array.isArray(n)&&0===n.length?Xu(x,`${T}/${t}`,`"${t}" must contain at least one item when present.`):Array.isArray(n)&&(e[t]=n.map((e,n)=>null===e||"object"!=typeof e||Array.isArray(e)?(Xu(x,`${T}/${t}/${n}`,`Each "${t}" item must be an object.`),A[t]()):e)):(Xu(x,`${T}/${t}`,`"${t}" must be an array when present.`),e[t]=[])}for(let t=0;t<(null!==(r=null===(s=e.events)||void 0===s?void 0:s.length)&&void 0!==r?r:0);t++){const n=e.events[t];void 0===n.values||zu(n.values)?n.values&&0===Object.keys(n.values).length&&Xu(x,`${T}/events/${t}/values`,'"values" must contain at least one property when present.'):(Xu(x,`${T}/events/${t}/values`,'"values" must be an object when present.'),n.values=void 0)}for(let t=0;t<(null!==(a=null===(i=e.declarations)||void 0===i?void 0:i.length)&&void 0!==a?a:0);t++){const n=e.declarations[t];for(const e of["inputValueSockets","outputValueSockets"])void 0===n[e]||zu(n[e])?n[e]&&0===Object.keys(n[e]).length&&Xu(x,`${T}/declarations/${t}/${e}`,`"${e}" must contain at least one property when present.`):(Xu(x,`${T}/declarations/${t}/${e}`,`"${e}" must be an object when present.`),n[e]=void 0)}for(let t=0;t<(null!==(u=null===(l=e.nodes)||void 0===l?void 0:l.length)&&void 0!==u?u:0);t++){const n=e.nodes[t];for(const e of["configuration","values","flows"])void 0===n[e]||zu(n[e])?n[e]&&0===Object.keys(n[e]).length&&Xu(x,`${T}/nodes/${t}/${e}`,`"${e}" must contain at least one property when present.`):(Xu(x,`${T}/nodes/${t}/${e}`,`"${e}" must be an object when present.`),n[e]=void 0)}const w=new Set,M=(null!==(c=e.declarations)&&void 0!==c?c:[]).map((t,o)=>{var s,r,i,a;const l=Object.keys(null!==(s=t.inputValueSockets)&&void 0!==s?s:{}).sort().map(e=>{const n=t.inputValueSockets[e];return`${JSON.stringify(e)}:${zu(n)?String(n.type):"invalid"}`}).join(","),u=`${JSON.stringify(t.op)}:${JSON.stringify(null!==(r=t.extension)&&void 0!==r?r:"")}:${l}`;w.has(u)&&Xu(x,`${T}/declarations/${o}`,"Duplicate equivalent declaration."),w.add(u);const{support:c}=function(e,t,n){const o=e.extension&&n&&!n.has(e.extension)?void 0:Ru(e,!1);return o?e.extension&&o.declarationSchema&&!function(e,t,n){const o=(e,n)=>{const o=Object.keys(null!=e?e:{}).sort(),s=Object.keys(n).sort();return o.length===s.length&&!o.some((e,t)=>e!==s[t])&&o.every(o=>{var s,r;return zu(e[o])&&(null===(r=null===(s=t.types)||void 0===s?void 0:s[e[o].type])||void 0===r?void 0:r.signature)===n[o]})};return o(e.inputValueSockets,n.inputValueSockets)&&o(e.outputValueSockets,n.outputValueSockets)}(e,t,o.declarationSchema)?{mapping:void 0,support:"unsupported-extension"}:{mapping:o,support:e.extension?"extension":"core"}:{mapping:void 0,support:e.extension?"unsupported-extension":"unknown-core"}}(t,e,n);"unknown-core"===c&&Xu(x,`${T}/declarations/${o}/op`,`Unknown core operation "${t.op}".`),t.extension||!t.inputValueSockets&&!t.outputValueSockets||Xu(x,`${T}/declarations/${o}`,"Core operation declarations cannot define dynamic value sockets.");for(const[n,s]of Object.entries(null!==(i=t.inputValueSockets)&&void 0!==i?i:{}))zu(s)?Zu(s.type,e,x,`${T}/declarations/${o}/inputValueSockets/${n}/type`):Xu(x,`${T}/declarations/${o}/inputValueSockets/${n}`,`Input value socket "${n}" must be an object.`);for(const[n,s]of Object.entries(null!==(a=t.outputValueSockets)&&void 0!==a?a:{}))zu(s)?Zu(s.type,e,x,`${T}/declarations/${o}/outputValueSockets/${n}/type`):Xu(x,`${T}/declarations/${o}/outputValueSockets/${n}`,`Output value socket "${n}" must be an object.`);return{index:o,operation:t.extension?`${t.op}:${t.extension}`:t.op,support:c,source:t}}),S=new Set;for(let t=0;t<(null!==(h=null===(d=e.types)||void 0===d?void 0:d.length)&&void 0!==h?h:0);t++){const n=e.types[t].signature;"custom"!==n&&S.has(n)&&Xu(x,`${T}/types/${t}/signature`,`Duplicate built-in type signature "${n}".`),S.add(n),"custom"===n||$u[n]||Xu(x,`${T}/types/${t}/signature`,`Unknown built-in type signature "${n}".`)}for(let t=0;t<(null!==(f=null===(p=e.variables)||void 0===p?void 0:p.length)&&void 0!==f?f:0);t++)Ju(e.variables[t],e,x,`${T}/variables/${t}`);for(let t=0;t<(null!==(g=null===(m=e.events)||void 0===m?void 0:m.length)&&void 0!==g?g:0);t++){const n=e.events[t].id;void 0!==n&&e.events.slice(0,t).some(e=>e.id===n)&&Xu(x,`${T}/events/${t}/id`,`Duplicate event id "${n}".`),e.events[t].values&&Object.prototype.hasOwnProperty.call(e.events[t].values,"event")&&Xu(x,`${T}/events/${t}/values/event`,'Custom event value socket id "event" is reserved.');for(const[n,o]of Object.entries(null!==(_=e.events[t].values)&&void 0!==_?_:{}))zu(o)?Ju(o,e,x,`${T}/events/${t}/values/${n}`):Xu(x,`${T}/events/${t}/values/${n}`,`Event value socket "${n}" must be an object.`)}for(let t=0;t<(null!==(y=null===(v=e.nodes)||void 0===v?void 0:v.length)&&void 0!==y?y:0);t++)lc(e.nodes[t],t,e,M,x,T,o);return{index:t,path:T,name:null!==(b=e.name)&&void 0!==b?b:`Graph ${t+1}`,source:e,effectiveSource:oc(e,M,o),declarations:M,diagnostics:x,valid:!x.some(e=>"error"===e.severity)}}function cc(e,t,n){var o;const s=ju(e),r=[];Array.isArray(s.graphs)||(Xu(r,"/extensions/KHR_interactivity/graphs",'"graphs" must be an array.'),s.graphs=[]),0===s.graphs.length&&Xu(r,"/extensions/KHR_interactivity/graphs","At least one behavior graph is required.");const i=null!==(o=s.graph)&&void 0!==o?o:0,a=qu(i,s.graphs.length)?i:-1;-1===a&&Xu(r,"/extensions/KHR_interactivity/graph",`Default graph index ${String(i)} is out of range.`);const l=s.graphs.map((e,o)=>uc(e,o,t,n));return s.graphs=l.map(e=>e.source),{specificationCommit:Gu,source:s,defaultGraphIndex:a,graphs:l,diagnostics:r}}const dc="/extensions/KHR_interactivity/events/",hc="/extensions/KHR_interactivity/delays/";function pc(e,t){return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function fc(e){if(Array.isArray(e))return e.map(e=>fc(e));if(null!==e&&"object"==typeof e){const t={};for(const[n,o]of Object.entries(e))Object.defineProperty(t,n,{configurable:!0,enumerable:!0,value:fc(o),writable:!0});return t}return e}function mc(e){return null===e||["string","number","boolean"].includes(typeof e)||Array.isArray(e)&&e.every(mc)||"object"==typeof e&&Object.values(e).every(mc)}function gc(e){var t,n,o,s,r;for(const i of e.getAllBlocks()){const e=null===(t=i.metadata)||void 0===t?void 0:t.khrInteractivity;if(e){Object.prototype.hasOwnProperty.call(null!==(n=e.generatedConfiguration)&&void 0!==n?n:{},"eventData")&&(e.generatedConfigurationRuntime||(e.generatedConfigurationRuntime={}),Object.prototype.hasOwnProperty.call(e.generatedConfigurationRuntime,"eventData")||Object.defineProperty(e.generatedConfigurationRuntime,"eventData",{configurable:!0,enumerable:!0,value:Ku(Su(null===(o=i.config)||void 0===o?void 0:o.eventData)),writable:!0}));for(const t of i.dataInputs){if(t.isConnected())continue;const n=null===(s=t.metadata)||void 0===s?void 0:s.khrInteractivity;n?null!==(r=n.runtimeValueSnapshot)&&void 0!==r||(n.runtimeValueSnapshot=Ku(t._defaultValue)):e.generatedInputDefaults&&Object.prototype.hasOwnProperty.call(e.generatedInputDefaults,t.name)||(e.generatedInputDefaults||(e.generatedInputDefaults={}),Object.defineProperty(e.generatedInputDefaults,t.name,{configurable:!0,enumerable:!0,value:Ku(t._defaultValue),writable:!0}))}}}}class _c{constructor(e,t,n=60,o=0,s,r,i){var a,l;this._gltf=t,this._animationTargetFps=n,this._graphIndex=o,this._supportedExtensions=s,this._declarationModels=r,this._types=[],this._mappings=[],this._staticVariables=[],this._events=[],this._internalEventsCounter=0,this._nodes=[],this._insertedBlocks=[],this._canonicalGraph=Wu(null!=i?i:e),this._interactivityGraph=this._declarationModels?oc(e,this._declarationModels,null!==(l=null===(a=this._gltf.nodes)||void 0===a?void 0:a.length)&&void 0!==l?l:0):Wu(e),this._parseTypes(),this._parseDeclarations(),this._parseVariables(),this._parseEvents(),this._parseNodes()}get _strictValidation(){return!!this._declarationModels}_getAllowedDynamicValueSockets(e,t,n){var o,s,r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b;if(("debug/log"===e||"flow/log:BABYLON"===e)&&"input"===n){const n=null===(r=null===(s=null===(o=t.configuration)||void 0===o?void 0:o["debug/log"===e?"message":"messageTemplate"])||void 0===s?void 0:s.value)||void 0===r?void 0:r[0];return new Set("string"==typeof n?Bu(n).sockets:[])}if("event/send"===e&&"input"===n||"event/receive"===e&&"output"===n){const e=null===(l=null===(a=null===(i=t.configuration)||void 0===i?void 0:i.event)||void 0===a?void 0:a.value)||void 0===l?void 0:l[0];if("number"==typeof e)return new Set(Object.keys(null!==(d=null===(c=null===(u=this._interactivityGraph.events)||void 0===u?void 0:u[e])||void 0===c?void 0:c.values)&&void 0!==d?d:{}))}if("variable/set"===e&&"input"===n)return new Set((null!==(f=null===(p=null===(h=t.configuration)||void 0===h?void 0:h.variables)||void 0===p?void 0:p.value)&&void 0!==f?f:[]).map(String));if("math/switch"===e&&"input"===n)return new Set((null!==(_=null===(g=null===(m=t.configuration)||void 0===m?void 0:m.cases)||void 0===g?void 0:g.value)&&void 0!==_?_:[]).map(String));if(("pointer/get"===e||"pointer/set"===e||"pointer/interpolate"===e)&&"input"===n){const e=null===(b=null===(y=null===(v=t.configuration)||void 0===v?void 0:v.pointer)||void 0===y?void 0:y.value)||void 0===b?void 0:b[0];if("string"==typeof e)return new Set(e.split("/").filter(e=>e.startsWith("[")&&!e.startsWith("[[")||e.startsWith("{")&&!e.startsWith("{{")).map(e=>e.substring(1,e.length-1).replace(/~1/g,"/").replace(/~0/g,"~")))}}_getAllowedDynamicFlowSockets(e,t,n){var o,s,r;for(const[i,a]of Object.entries(null!==(o=t.configuration)&&void 0!==o?o:{})){if(!("input"===n?a.generatesInputFlowSockets:a.generatesOutputFlowSockets))continue;const t=null===(r=null===(s=e.configuration)||void 0===s?void 0:s[i])||void 0===r?void 0:r.value,o=t&&t.length>0&&("int"!==a.configurationType||1===t.length)&&t.every(e=>{var t,n;return"number"==typeof e&&Number.isInteger(e)&&e>=(null!==(t=a.minimum)&&void 0!==t?t:-2147483648)&&e<=(null!==(n=a.maximum)&&void 0!==n?n:2147483647)}),l=o?t:a.defaultValue;if("input"===n){const e=Array.isArray(l)&&"number"==typeof l[0]?l[0]:0;return new Set(Array.from({length:e},(e,t)=>String(t)))}return new Set(Array.isArray(l)?l.map(String):[])}}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($u[e.signature])}_parseDeclarations(){var e;if(this._interactivityGraph.declarations)for(let n=0;n<this._interactivityGraph.declarations.length;n++){const o=this._interactivityGraph.declarations[n],s=null===(e=this._declarationModels)||void 0===e?void 0:e[n],r=!o.extension||!this._supportedExtensions||this._supportedExtensions.has(o.extension),i="unsupported-extension"===(null==s?void 0:s.support)?void 0:r?Ru(o,!1):void 0;if(!i&&!o.extension)throw new Error(`Unknown core KHR_interactivity operation "${o.op}".`);const a=null!=i?i:o.extension?Cu(o):void 0;if(!a)throw t.Logger.Error(["No mapping found for declaration",o]),new Error("Error parsing declarations");this._mappings.push({flowGraphMapping:a,fullOperationName:o.extension?o.op+":"+o.extension:o.op,declaration:null!=s?s:{index:n,operation:o.extension?`${o.op}:${o.extension}`:o.op,support:i?o.extension?"extension":"core":"unsupported-extension",source:o}})}}_parseVariables(){if(this._interactivityGraph.variables)for(const e of this._interactivityGraph.variables){const t=this._parseVariable(e);this._staticVariables.push(t)}}_parseVariable(e,n){var o,s;const r=this._types[e.type];if(!r)throw t.Logger.Error(["No type found for variable",e]),new Error("Error parsing variables");if(e.value&&"custom"!==(null===(s=null===(o=this._interactivityGraph.types)||void 0===o?void 0:o[e.type])||void 0===s?void 0:s.signature)&&e.value.length!==r.length)throw t.Logger.Error(["Invalid value length for variable",e,r]),new Error("Error parsing variables");const i=e.value?e.value.slice():[];if(!i.length)switch(r.flowGraphType){case"boolean":i.push(!1);break;case"FlowGraphInteger":i.push(0);break;case"number":i.push(NaN);break;case"string":i.push("");break;case"Vector2":i.push(NaN,NaN);break;case"Vector3":i.push(NaN,NaN,NaN);break;case"Vector4":case"Matrix2D":case"Quaternion":i.push(NaN,NaN,NaN,NaN);break;case"Matrix":for(let e=0;e<16;e++)i.push(NaN);break;case"Matrix3D":for(let e=0;e<9;e++)i.push(NaN)}return"number"===r.elementType&&"string"==typeof i[0]?i[0]=parseFloat(i[0]):"string"===r.flowGraphType&&"string"==typeof i[0]&&(i[0]=this._normalizeStaticReference(i[0])),{type:r.flowGraphType,value:n?n(i,this):i}}_normalizeStaticReference(e){if(!e||e.startsWith(dc)||e.startsWith(hc))return"";if(!e.startsWith("/"))return"";let t=this._gltf;for(const n of e.substring(1).split("/")){const e=n.replace(/~1/g,"/").replace(/~0/g,"~");if(Array.isArray(t)){if(!/^(0|[1-9]\d*)$/.test(e))return"";t=t[parseInt(e,10)]}else{if(null===t||"object"!=typeof t||!Object.prototype.hasOwnProperty.call(t,e))return"";t=t[e]}}return null!==t&&"object"==typeof t?e:""}_parseEvents(){var e;if(!this._interactivityGraph.events)return;const n=new Set(this._interactivityGraph.events.flatMap(e=>void 0===e.id?[]:[e.id])),o=`__babylon_khr_internal_${this._graphIndex}_`;for(const s of this._interactivityGraph.events){let r;if(void 0===s.id){do{r=o+this._internalEventsCounter++}while(n.has(r));n.add(r)}const i={eventId:null!==(e=s.id)&&void 0!==e?e:r};s.values&&(i.eventData=Object.keys(s.values).map(e=>{var n;const o=null===(n=s.values)||void 0===n?void 0:n[e];if(!o)throw t.Logger.Error(["No value found for event key",e]),new Error("Error parsing events");const r=this._types[o.type];if(!r)throw t.Logger.Error(["No type found for event value",o]),new Error("Error parsing events");const i=void 0!==o.value?this._parseVariable(o):void 0;return{id:e,type:r.flowGraphType,eventData:!0,value:i}})),this._events.push(i)}}_parseNodes(){var e;if(this._interactivityGraph.nodes)for(let n=0;n<this._interactivityGraph.nodes.length;n++){const o=this._interactivityGraph.nodes[n];if("number"!=typeof o.declaration)throw t.Logger.Error(["No declaration found for node",o]),new Error("Error parsing nodes");const s=this._mappings[o.declaration];if(!s)throw t.Logger.Error(["No mapping found for node",o]),new Error("Error parsing nodes");if(s.flowGraphMapping.validation){const t=s.flowGraphMapping.validation(o,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[o.declaration].op} - ${t.error}`)}const r=[];"unsupported-extension"===s.declaration.support&&r.push(this._createUnsupportedExtensionBlock(o,n,s));for(let e=0;e<s.flowGraphMapping.blocks.length;e++){const t=s.flowGraphMapping.blocks[e],i=this._getEmptyBlock(t,s.fullOperationName,n,o.declaration,e);this._parseNodeConfiguration(o,i,s.flowGraphMapping,t),r.push(i)}this._nodes.push({blocks:r,fullOperationName:s.fullOperationName})}}_createBlockProvenance(e,t,n,o){return{graphIndex:this._graphIndex,nodeIndex:e,declarationIndex:t,operation:n,role:o,sourcePath:`/extensions/KHR_interactivity/graphs/${this._graphIndex}/nodes/${e}`}}_getEmptyBlock(e,n,o,s,r){return{uniqueId:t.RandomGUID(),className:e,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[],config:{},type:n,metadata:void 0===o?{}:{khrInteractivity:this._createBlockProvenance(o,s,n,null!=r?r:0)}}}_setSocketProvenance(e,t,n,o,s,r,i,a){var l;e.metadata=Object.assign(Object.assign({},null!==(l=e.metadata)&&void 0!==l?l:{}),{khrInteractivity:Object.assign(Object.assign({},this._createBlockProvenance(t,n,o,s)),{kind:r,direction:i,socket:a})})}_getBlockRole(e,t){var n,o,s;return null!==(s=null===(o=null===(n=t.metadata)||void 0===n?void 0:n.khrInteractivity)||void 0===o?void 0:o.role)&&void 0!==s?s:e.indexOf(t)}_createUnsupportedExtensionBlock(e,t,n){var o,s,r,i;const a=this._getEmptyBlock("KHR_interactivity/FlowGraphUnsupportedInteractivityBlock",n.fullOperationName,t,e.declaration,0),l=new Set;for(const e of null!==(o=this._interactivityGraph.nodes)&&void 0!==o?o:[])for(const n of Object.values(null!==(s=e.flows)&&void 0!==s?s:{}))n.node===t&&l.add(null!==(r=n.socket)&&void 0!==r?r:"in");const u=e=>Object.entries(null!=e?e:{}).map(([e,t])=>{var n,o,s;return{name:e,type:null===(n=this._types[t.type])||void 0===n?void 0:n.flowGraphType,signature:null===(s=null===(o=this._interactivityGraph.types)||void 0===o?void 0:o[t.type])||void 0===s?void 0:s.signature}});a.config={operation:n.fullOperationName,inputValueSockets:u(n.declaration.source.inputValueSockets),outputValueSockets:u(n.declaration.source.outputValueSockets),inputFlowSockets:Array.from(l).sort(),outputFlowSockets:Object.keys(null!==(i=e.flows)&&void 0!==i?i:{}).sort()};for(const o of a.config.inputValueSockets){const s=this._createNewSocketConnection(o.name);this._setSocketProvenance(s,t,e.declaration,n.fullOperationName,0,"value","input",o.name),a.dataInputs.push(s)}for(const o of a.config.outputValueSockets){const s=this._createNewSocketConnection(o.name,!0);this._setSocketProvenance(s,t,e.declaration,n.fullOperationName,0,"value","output",o.name),a.dataOutputs.push(s)}for(const o of a.config.inputFlowSockets){const s=this._createNewSocketConnection(o);this._setSocketProvenance(s,t,e.declaration,n.fullOperationName,0,"flow","input",o),a.signalInputs.push(s)}for(const o of a.config.outputFlowSockets){const s=this._createNewSocketConnection(o,!0);this._setSocketProvenance(s,t,e.declaration,n.fullOperationName,0,"flow","output",o),a.signalOutputs.push(s)}return a}_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||!this._strictValidation)&&(!(null==l?void 0:l.validationOnly)&&(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,p,f,m,g,_,v,y,b,x,T,A,w,M,S,R,C,I,O;for(let F=0;F<this._nodes.length;F++){const E=null===(n=this._interactivityGraph.nodes)||void 0===n?void 0:n[F];if(!E)throw t.Logger.Error(["No node found for interactivity node",this._nodes[F]]),new Error("Error parsing node connections");const N=this._nodes[F],L=this._mappings[E.declaration];if(!L)throw t.Logger.Error(["No mapping found for node",E]),new Error("Error parsing node connections");if(0===N.blocks.length){t.Logger.Warn(`Skipping connections for no-op node #${F} (unsupported operation: ${N.fullOperationName})`);continue}const k=E.flows||{},P=Object.keys(k).sort();for(const e of P){const n=k[e];let g=pc(null===(o=L.flowGraphMapping.outputs)||void 0===o?void 0:o.flows,e);this._strictValidation&&(null==g?void 0:g.compatibilityOnly)&&(g=void 0);let _=!1;if(!g)for(const e in null===(s=L.flowGraphMapping.outputs)||void 0===s?void 0:s.flows)if(e.startsWith("[")&&e.endsWith("]")){const t=null===(i=null===(r=L.flowGraphMapping.outputs)||void 0===r?void 0:r.flows)||void 0===i?void 0:i[e];if(!this._strictValidation||!(null==t?void 0:t.compatibilityOnly)){_=!0,g=t;break}}const v=_?this._getAllowedDynamicFlowSockets(E,L.flowGraphMapping,"output"):void 0;if(this._strictValidation&&v&&!v.has(e)&&(g=void 0),!g&&!this._isUnsupportedExtensionBlock(N.blocks[0]))continue;const y=g?_?g.name.replace("$1",e):g.name:e,b=n.node,x=this._nodes[b];if(!x)throw t.Logger.Error(["No node found for input node id",b]),new Error("Error parsing node connections");if(0===x.blocks.length){t.Logger.Warn(`Dropping flow connection from node #${F} "${e}" to no-op node #${b} (unsupported operation: ${x.fullOperationName})`);continue}const T=g&&g.toBlock&&N.blocks.find(e=>e.className===g.toBlock)||N.blocks[0],A=null!==(a=T.signalOutputs.find(e=>e.name===y))&&void 0!==a?a:this._createNewSocketConnection(y,!0);T.signalOutputs.includes(A)||T.signalOutputs.push(A),this._setSocketProvenance(A,F,E.declaration,N.fullOperationName,this._getBlockRole(N.blocks,T),"flow","output",e);const w=null===(l=this._mappings[this._interactivityGraph.nodes[b].declaration])||void 0===l?void 0:l.flowGraphMapping;if(!w)throw t.Logger.Error(["No mapping found for input node",x]),new Error("Error parsing node connections");let M=pc(null===(u=w.inputs)||void 0===u?void 0:u.flows,n.socket||"in");this._strictValidation&&(null==M?void 0:M.compatibilityOnly)&&(M=void 0);let S=!1;if(!M){for(const e in null===(c=w.inputs)||void 0===c?void 0:c.flows)if(e.startsWith("[")&&e.endsWith("]")){const t=null===(h=null===(d=w.inputs)||void 0===d?void 0:d.flows)||void 0===h?void 0:h[e];this._strictValidation&&(null==t?void 0:t.compatibilityOnly)||(S=!0,M=t)}const e=S?this._getAllowedDynamicFlowSockets(this._interactivityGraph.nodes[b],w,"input"):void 0;if(this._strictValidation&&e&&!e.has(null!==(p=n.socket)&&void 0!==p?p:"in")&&(M=void 0),!M&&"in"===(null!==(f=n.socket)&&void 0!==f?f:"in")&&Mu(x.fullOperationName)&&(M={name:"in"}),!M&&!this._isUnsupportedExtensionBlock(x.blocks[0]))continue}const R=M?S?M.name.replace("$1",n.socket||""):M.name:n.socket||"in",C=M&&M.toBlock&&x.blocks.find(e=>e.className===M.toBlock)||x.blocks[0];let I=C.signalInputs.find(e=>e.name===R);I||(I=this._createNewSocketConnection(R),C.signalInputs.push(I)),this._setSocketProvenance(I,b,this._interactivityGraph.nodes[b].declaration,x.fullOperationName,this._getBlockRole(x.blocks,C),"flow","input",null!==(m=n.socket)&&void 0!==m?m:"in"),I.connectedPointIds.push(A.uniqueId),A.connectedPointIds.push(I.uniqueId)}const B=E.values||{},D=Object.keys(B);for(const n of D){const o=B[n];let s=pc(null===(g=L.flowGraphMapping.inputs)||void 0===g?void 0:g.values,n);this._strictValidation&&(null==s?void 0:s.compatibilityOnly)&&(s=void 0);let r=!1;if(!s)for(const e in null===(_=L.flowGraphMapping.inputs)||void 0===_?void 0:_.values)if(e.startsWith("[")&&e.endsWith("]")){const t=null===(y=null===(v=L.flowGraphMapping.inputs)||void 0===v?void 0:v.values)||void 0===y?void 0:y[e];this._strictValidation&&(null==t?void 0:t.compatibilityOnly)||(r=!0,s=t)}const i=r?this._getAllowedDynamicValueSockets(L.fullOperationName,E,"input"):void 0;if(!s||i&&!i.has(n))continue;const a=s?r?s.name.replace("$1",n):s.name:n,l=s&&s.toBlock&&N.blocks.find(e=>e.className===s.toBlock)||N.blocks[0],u=null!==(b=l.dataInputs.find(e=>e.name===a))&&void 0!==b?b:this._createNewSocketConnection(a);l.dataInputs.includes(u)||l.dataInputs.push(u),this._setSocketProvenance(u,F,E.declaration,N.fullOperationName,this._getBlockRole(N.blocks,l),"value","input",n);const c=u.metadata.khrInteractivity;c.sourceValue=fc(null!==(w=null===(A=null===(T=null===(x=this._canonicalGraph.nodes)||void 0===x?void 0:x[F])||void 0===T?void 0:T.values)||void 0===A?void 0:A[n])&&void 0!==w?w:o);const d=!!(null==s?void 0:s.convertConnectedTimeToFrames);if(void 0!==o.value){const t=this._parseVariable(o,s&&s.dataTransformer);e._connectionValues[u.uniqueId]=t,u.defaultValue=t,c.runtimeValue=fc(t.value)}else{if(void 0===o.node)throw t.Logger.Error(["Invalid value for value connection",o]),new Error("Error parsing node connections");{const s=o.node,r=o.socket||"value",i=this._nodes[s];if(!i)throw t.Logger.Error(["No node found for output socket reference",o]),new Error("Error parsing node connections");if(0===i.blocks.length){t.Logger.Warn(`Dropping value connection from no-op node #${s} (unsupported operation: ${i.fullOperationName}) into node #${F} "${n}"; consumer will use type-default value`);continue}const a=null===(M=this._mappings[this._interactivityGraph.nodes[s].declaration])||void 0===M?void 0:M.flowGraphMapping;if(!a)throw t.Logger.Error(["No mapping found for output socket reference",o]),new Error("Error parsing node connections");let l=pc(null===(S=a.outputs)||void 0===S?void 0:S.values,r);this._strictValidation&&(null==l?void 0:l.compatibilityOnly)&&(l=void 0);let c=!1;if(!l){for(const e in null===(R=a.outputs)||void 0===R?void 0:R.values)if(e.startsWith("[")&&e.endsWith("]")){const t=null===(I=null===(C=a.outputs)||void 0===C?void 0:C.values)||void 0===I?void 0:I[e];this._strictValidation&&(null==t?void 0:t.compatibilityOnly)||(c=!0,l=t)}const e=c?this._getAllowedDynamicValueSockets(i.fullOperationName,this._interactivityGraph.nodes[s],"output"):void 0;if(!l||e&&!e.has(r))continue}const h=l?c?l.name.replace("$1",r):null==l?void 0:l.name:r,p=l&&l.toBlock&&i.blocks.find(e=>e.className===l.toBlock)||i.blocks[0];let f=p.dataOutputs.find(e=>e.name===h);f||(f=this._createNewSocketConnection(h,!0),p.dataOutputs.push(f)),this._setSocketProvenance(f,s,this._interactivityGraph.nodes[s].declaration,i.fullOperationName,this._getBlockRole(i.blocks,p),"value","output",r),d?this._connectWithSecondsToFramesConversion(e,f,u,F,E.declaration,N.fullOperationName):(u.connectedPointIds.push(f.uniqueId),f.connectedPointIds.push(u.uniqueId))}}}if(L.flowGraphMapping.interBlockConnectors)for(const e of L.flowGraphMapping.interBlockConnectors){const t=e.input,n=e.output,o=e.isVariable;this._connectFlowGraphNodes(t,n,N.blocks[e.inputBlockIndex],N.blocks[e.outputBlockIndex],o)}if(L.flowGraphMapping.extraProcessor){const n=null===(O=this._interactivityGraph.declarations)||void 0===O?void 0:O[E.declaration];if(!n)throw t.Logger.Error(["No declaration found for extra processor",E]),new Error("Error parsing node connections");N.blocks=L.flowGraphMapping.extraProcessor(E,n,L.flowGraphMapping,this,N.blocks,e,this._gltf)}this._ensureMappedSocketProvenance(F,E,N.blocks,L)}}_ensureMappedSocketProvenance(e,t,n,o){var s,r,i,a,l,u,c,d,h,p,f,m,g;const _=(s,r,i)=>{for(const[a,l]of Object.entries(null!=s?s:{})){if(a.startsWith("[")&&a.endsWith("]")||this._strictValidation&&l.compatibilityOnly)continue;const s=l.toBlock&&n.find(e=>e.className===l.toBlock)||n[0];if(!s)continue;const u="value"===r?"input"===i?s.dataInputs:s.dataOutputs:"input"===i?s.signalInputs:s.signalOutputs;let c=u.find(e=>e.name===l.name);c||(c=this._createNewSocketConnection(l.name,"output"===i),u.push(c)),this._setSocketProvenance(c,e,t.declaration,o.fullOperationName,this._getBlockRole(n,s),r,i,a)}};if(_(null===(s=o.flowGraphMapping.outputs)||void 0===s?void 0:s.values,"value","output"),_(null===(r=o.flowGraphMapping.inputs)||void 0===r?void 0:r.flows,"flow","input"),_(null===(i=o.flowGraphMapping.outputs)||void 0===i?void 0:i.flows,"flow","output"),Mu(o.fullOperationName)){const s=n[0];if(s){let r=s.signalInputs.find(e=>"in"===e.name);r||(r=this._createNewSocketConnection("in"),s.signalInputs.push(r)),this._setSocketProvenance(r,e,t.declaration,o.fullOperationName,this._getBlockRole(n,s),"flow","input","in")}}for(const[t,s]of Object.entries(null!==(a=o.flowGraphMapping.configuration)&&void 0!==a?a:{})){const o=s.toBlock&&n.find(e=>e.className===s.toBlock)||n[0],r=null===(l=null==o?void 0:o.metadata)||void 0===l?void 0:l.khrInteractivity;if(!o||!r)continue;const i=null===(u=o.config)||void 0===u?void 0:u[s.name],a=null!==i&&"object"==typeof i&&Object.prototype.hasOwnProperty.call(i,"value")?i.value:i;r.configuration||(r.configuration={});const f={sourceValue:fc(null===(p=null===(h=null===(d=null===(c=this._canonicalGraph.nodes)||void 0===c?void 0:c[e])||void 0===d?void 0:d.configuration)||void 0===h?void 0:h[t])||void 0===p?void 0:p.value),runtimeValue:fc(a)};Object.defineProperty(r.configuration,t,{configurable:!0,enumerable:!0,value:f,writable:!0})}for(const e of n){const t=null===(f=e.metadata)||void 0===f?void 0:f.khrInteractivity;if(!t)continue;const n=new Set(Object.values(null!==(m=o.flowGraphMapping.configuration)&&void 0!==m?m:{}).filter(n=>n.toBlock?e.className===n.toBlock:0===t.role).map(e=>e.name)),s=new Set(["glTF"]);for(const[o,r]of Object.entries(null!==(g=e.config)&&void 0!==g?g:{})){if(n.has(o)||s.has(o))continue;const e="eventData"===o?Su(r):null!==r&&"object"==typeof r&&Object.prototype.hasOwnProperty.call(r,"value")?r.value:r;mc(e)&&(t.generatedConfiguration||(t.generatedConfiguration={}),Object.defineProperty(t.generatedConfiguration,o,{configurable:!0,enumerable:!0,value:fc(e),writable:!0}))}}}_createNewSocketConnection(e,n){return{uniqueId:t.RandomGUID(),name:e,_connectionType:n?1:0,connectedPointIds:[]}}_isUnsupportedExtensionBlock(e){return"KHR_interactivity/FlowGraphUnsupportedInteractivityBlock"===(null==e?void 0:e.className)}_connectWithSecondsToFramesConversion(e,t,n,o,s,r){const i=this._getEmptyBlock("FlowGraphMultiplyBlock",r,o,s,-1);i.config={type:"number"};const a=this._createNewSocketConnection("a"),l=this._createNewSocketConnection("b"),u=this._createNewSocketConnection("value",!0);i.dataInputs.push(a,l),i.dataOutputs.push(u);const c={type:"number",value:[this._animationTargetFps]};e._connectionValues[l.uniqueId]=c,l.defaultValue=c,a.connectedPointIds.push(t.uniqueId),t.connectedPointIds.push(a.uniqueId),n.connectedPointIds.push(u.uniqueId),u.connectedPointIds.push(n.uniqueId),this._insertedBlocks.push(i)}_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(){var e;const n={uniqueId:t.RandomGUID(),_userVariables:{},_connectionValues:{}};this._parseNodeConnections(n);for(let e=0;e<this._staticVariables.length;e++){const t=this._staticVariables[e];n._userVariables[this.getVariableName(e)]=t}const o=this._nodes.reduce((e,t)=>e.concat(t.blocks),[]).concat(this._insertedBlocks);return{name:null!==(e=this._interactivityGraph.name)&&void 0!==e?e:`Graph ${this._graphIndex+1}`,metadata:{khrInteractivity:{graphIndex:this._graphIndex,specificationCommit:Gu,source:Wu(this._canonicalGraph)}},rightHanded:!0,allBlocks:o,executionContexts:[n]}}}class vc{constructor(e,t){this._prefixes=e,this._fallback=t}addPrefix(e){this._prefixes.unshift(e)}convert(e){for(const{prefix:t,converter:n}of this._prefixes)if(e.startsWith(t))return n.convert(e);return this._fallback.convert(e)}}const yc="/extensions/BABYLON_scene_objects/";class bc{constructor(e,t){this._scene=e,this._tree=t}convert(e){if(!e.startsWith(yc))throw new Error(`BabylonScenePathToObjectConverter: path "${e}" does not start with the expected prefix "${yc}".`);const t=e.slice(34).split("/").filter(e=>e.length>0);if(0===t.length)throw new Error(`BabylonScenePathToObjectConverter: path "${e}" is missing a collection name.`);const n=t[0],o=this._tree[n];if(!o)throw new Error(`BabylonScenePathToObjectConverter: unknown collection "${n}" in path "${e}".`);if(2===t.length&&"length"===t[1])return{object:this._getCollectionArray(n),info:o.length};if(t.length<2)throw new Error(`BabylonScenePathToObjectConverter: path "${e}" is missing an instance id.`);if(!/^\d+$/.test(t[1]))throw new Error(`BabylonScenePathToObjectConverter: invalid uniqueId "${t[1]}" in path "${e}".`);const s=parseInt(t[1],10);if(!Number.isFinite(s)||s<0)throw new Error(`BabylonScenePathToObjectConverter: invalid uniqueId "${t[1]}" in path "${e}".`);const r=this._lookupInstanceByUniqueId(n,s);if(!r)throw new Error(`BabylonScenePathToObjectConverter: no ${n} instance found with uniqueId ${s} (path "${e}").`);if(2===t.length)return{object:r,info:this._buildIdentityAccessor(r)};if(t.length>3)throw new Error(`BabylonScenePathToObjectConverter: nested property paths are not yet supported (path "${e}").`);const i=t[2],a=o.__array__[i];if(!a||"boolean"==typeof a)throw new Error(`BabylonScenePathToObjectConverter: property "${i}" is not registered on ${n} (path "${e}").`);return{object:r,info:a}}_getCollectionArray(e){switch(e){case"transformNodes":return this._scene.transformNodes;case"meshes":return this._scene.meshes;case"materials":return this._scene.materials;default:return[]}}_lookupInstanceByUniqueId(e,t){switch(e){case"transformNodes":return this._scene.transformNodes.find(e=>e.uniqueId===t)||this._scene.meshes.find(e=>e.uniqueId===t);case"meshes":return this._scene.meshes.find(e=>e.uniqueId===t);case"materials":return this._scene.materials.find(e=>e.uniqueId===t);default:return}}_buildIdentityAccessor(e){return{type:"object",get:()=>e,getTarget:()=>e,isReadOnly:!0}}}const xc={isKhrInteractivityRef:!0};class Tc{convert(e){const n=e===dc,o=e.endsWith("/")?e.slice(0,-1):e;if(n||o.startsWith(dc)){const t=o.substring(37);return{object:xc,info:{type:"object",isReadOnly:!0,get:()=>n?e:t.length>0?o:void 0,getTarget:()=>xc}}}const s=o.substring(37),r=/^\d+$/.test(s)?parseInt(s,10):NaN;return{object:xc,info:{type:"object",isReadOnly:!0,get:(e,n,o)=>{const s=o;if(!(!s||isNaN(r)||r<0))return t.IsDelayActive(s,r)?new t.FlowGraphInteger(r):void 0},getTarget:()=>xc}}}}const Ac="/extensions/KHR_interactivity/limits/",wc={major:2,minor:0},Mc=2147483647,Sc={maxActiveAnimations:Mc,maxActiveDelays:Mc,maxActivePropertyInterpolations:Mc,maxActiveVariableInterpolations:Mc},Rc={isKhrInteractivityAssetCapability:!0};class Cc{constructor(e,t){this._gltf=e,this._isExtensionEnabled=t}convert(e){const t=e.endsWith("/")?e.slice(0,-1):e;if(t.startsWith(Ac)){const n=Sc[t.substring(37)];if(void 0===n)throw new Error(`Path ${e} is invalid`);return this._createAccessor("number",()=>n)}const n=t.substring(36);if("majorVersion"===n||"minorVersion"===n)return this._createAccessor("number",()=>{var e;return function(e){const[t,n]=(null!=e?e:"").split("."),o=parseInt(t,10),s=parseInt(n,10);return isNaN(o)?wc:o!==wc.major?o<wc.major?{major:o,minor:isNaN(s)?0:s}:wc:{major:o,minor:Math.min(isNaN(s)?0:s,wc.minor)}}(null===(e=this._gltf.asset)||void 0===e?void 0:e.version)["majorVersion"===n?"major":"minor"]});const o=n.split("/");if(3===o.length&&"extensions"===o[0]&&"enabled"===o[2]){const e=o[1];return this._createAccessor("boolean",()=>this._isExtensionEnabled(e))}throw new Error(`Path ${e} is invalid`)}_createAccessor(e,t){return{object:Rc,info:{type:e,isReadOnly:!0,get:t,getTarget:()=>Rc}}}}class Ic{encodeEventReference(e){return function(e){return dc+e}(e)}decodeEventReference(e){return function(e){return"string"==typeof(t=e)&&t.startsWith(dc)?e.substring(37):void 0;var t}(e)}decodeIndexReference(e,t){if(0===e.length||"/"!==e[0])return;const n=t?`/${t}/`:"/";if(!e.startsWith(n))return;const o=t?e.substring(n.length):e.substring(e.lastIndexOf("/")+1);return/^(0|[1-9]\d*)$/.test(o)?parseInt(o,10):void 0}getObjectReference(e,t){var n,o;const s=null===(o=null===(n=e._internalMetadata)||void 0===n?void 0:n.gltf)||void 0===o?void 0:o.pointers;if(!Array.isArray(s))return;const r=s.filter(e=>"string"==typeof e);if(0!==r.length){if(t){const e=r.find(e=>e.split("/")[1]===t);if(e)return e}return r[0]}}}class Oc extends Error{constructor(e){super(e.map(e=>`${e.path}: ${e.message}`).join("\n")),this.diagnostics=e,this.name="KHRInteractivityExportError"}}const Fc=new Set(["nodes","animations","cameras","materials","meshes","textures","images","samplers","skins","scenes"]),Ec=["KHR_node_hoverability","KHR_node_selectability","KHR_node_visibility"];function Nc(e){const t=e.split("/").map(e=>e.replace(/~1/g,"/").replace(/~0/g,"~")),n=[];for(let e=0;e<t.length-1;e++)"extensions"===t[e]&&t[e+1]&&n.push(t[e+1]);return n}const Lc={number:"float",boolean:"bool",FlowGraphInteger:"int",string:"ref",Vector2:"float2",Vector3:"float3",Vector4:"float4",Quaternion:"float4",Color3:"float3",Color4:"float4",Matrix2D:"float2x2",Matrix3D:"float3x3",Matrix:"float4x4",Mesh:"ref",TransformNode:"ref",Camera:"ref",Light:"ref",Material:"ref",AnimationGroup:"ref"};function kc(e){if(Array.isArray(e))return e.map(e=>kc(e));if(null!==e&&"object"==typeof e){const t={};for(const[n,o]of Object.entries(e))Object.defineProperty(t,n,{configurable:!0,enumerable:!0,value:kc(o),writable:!0});return t}return e}function Pc(e){var t;return null===(t=e.metadata)||void 0===t?void 0:t.khrInteractivity}function Bc(e){var t;return null===(t=e.metadata)||void 0===t?void 0:t.khrInteractivity}function Dc(e,t){return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Vc(e,t){return t?`${e}:${t}`:e}function Gc(e){return e.substring(e.lastIndexOf("/")+1)}function $c(e,t){return e.find(e=>{var n;return(null===(n=Pc(e))||void 0===n?void 0:n.role)===t})}function Uc(e,t,n){for(const o of e)for(const e of o.dataInputs){const o=Bc(e);if((null==o?void 0:o.nodeIndex)===t&&"value"===o.kind&&"input"===o.direction&&o.socket===n)return e}}function Hc(e){return Uu(e)}function Kc(e){return Ku(Array.isArray(e)?e.map(e=>{if(null===e||"object"!=typeof e)return e;const n=e,o="Matrix"===n.type&&Array.isArray(n.value)?Array.from(t.Matrix.FromArray(n.value).asArray()):n.value;return void 0===n.value?e:Object.assign(Object.assign({},n),{value:o})}):e)}function jc(e,t){if(!e||!t||e.length!==t.length)return e===t;for(let n=0;n<e.length;n++)if(!("number"==typeof e[n]&&"number"==typeof t[n]&&Number.isNaN(e[n])&&Number.isNaN(t[n])||e[n]===t[n]))return!1;return!0}function Wc(e,t){if("number"==typeof e&&"number"==typeof t&&Number.isNaN(e)&&Number.isNaN(t))return!0;if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>Wc(e,t[n]));if(null!==e&&null!==t&&"object"==typeof e&&"object"==typeof t){const n=Object.entries(e),o=Object.keys(t);return n.length===o.length&&n.every(([e,n])=>Object.prototype.hasOwnProperty.call(t,e)&&Wc(n,t[e]))}return!1}function qc(e,t){var n;const o=Lc[t];if(!o||!$u[o])return;null!==(n=e.types)&&void 0!==n||(e.types=[]);const s=e.types.findIndex(e=>e.signature===o);return s>=0?s:(e.types.push({signature:o}),e.types.length-1)}function zc(e,t){const n=t.toBlock;return n?e.blocks.find(t=>{var o,s;return t.getClassName()===Gc(n)||(null===(o=Pc(t))||void 0===o?void 0:o.role)===(null===(s=e.mapping)||void 0===s?void 0:s.blocks.indexOf(n))}):$c(e.blocks,0)}function Xc(e,t,n,o,s=!0){var r,i;const a=zc(e,n);if(!a)return;const l=null===(r=a.config)||void 0===r?void 0:r[n.name],u=Yc(e,t,n);if(s&&u&&jc(Hc(l),Hc(u.runtimeValue)))return u.sourceValue?kc(u.sourceValue):void 0;if("variables"===n.indexSource){const e=(Array.isArray(l)?l:[l]).filter(e=>"string"==typeof e).map(e=>/^staticVariable_(0|[1-9]\d*)$/.test(e)?parseInt(e.substring(15),10):-1);return e.every(e=>{var t,n;return e>=0&&e<(null!==(n=null===(t=o.variables)||void 0===t?void 0:t.length)&&void 0!==n?n:0)})?e:void 0}if("events"===n.indexSource){const e=l,t=null===(i=o.events)||void 0===i?void 0:i.findIndex(t=>t.id===e);return void 0!==t&&t>=0?[t]:void 0}return"assetNodes"!==n.indexSource||"string"!=typeof l?"useSlerp"===t?["Quaternion"===l]:Hc(l):void 0}function Yc(e,t,n){var o;const s=zc(e,n);return s?Dc(null===(o=Pc(s))||void 0===o?void 0:o.configuration,t):void 0}function Qc(e,t,n,o){var s,r,i,a,l,u,c,d,h,p;if(!e)return!1;const f=e=>"number"==typeof e&&Number.isInteger(e)&&e>=-2147483648&&e<=2147483647;let m;switch(t.configurationType){case"bool":m=1===e.length&&"boolean"==typeof e[0];break;case"int":m=1===e.length&&f(e[0]);break;case"int[]":m=e.every(f);break;case"string":m=1===e.length&&"string"==typeof e[0];break;default:m=e.length>0}if(!m||void 0!==t.minItems&&e.length<t.minItems)return!1;if(void 0!==t.minimum&&e.some(e=>"number"!=typeof e||e<t.minimum))return!1;if(void 0!==t.maximum&&e.some(e=>"number"!=typeof e||e>t.maximum))return!1;if(t.indexSource){const h={types:null!==(r=null===(s=n.types)||void 0===s?void 0:s.length)&&void 0!==r?r:0,variables:null!==(a=null===(i=n.variables)||void 0===i?void 0:i.length)&&void 0!==a?a:0,events:null!==(u=null===(l=n.events)||void 0===l?void 0:l.length)&&void 0!==u?u:0,nodes:null!==(d=null===(c=n.nodes)||void 0===c?void 0:c.length)&&void 0!==d?d:0,assetNodes:null!=o?o:0};if(e.some(e=>!f(e)||e<0||e>=h[t.indexSource]))return!1}if(t.allowedSignatures){const o=e[0],s="number"==typeof o?null===(p=null===(h=n.types)||void 0===h?void 0:h[o])||void 0===p?void 0:p.signature:void 0;if(!s||!t.allowedSignatures.includes(s))return!1}return!(t.allowedValues&&e.some(e=>!t.allowedValues.includes(e))||t.debugLogTemplate&&("string"!=typeof e[0]||!Bu(e[0]).valid))}function Zc(e,t,n,o,s,r,i){var a;const l=(t,n)=>{var o,i;return r?Xc(r,t,n,s):null===(i=null===(o=e.configuration)||void 0===o?void 0:o[t])||void 0===i?void 0:i.value};if(o.configurationGroup)for(const[e,n]of Object.entries(null!==(a=t.configuration)&&void 0!==a?a:{}))if(n.configurationGroup===o.configurationGroup&&!Qc(l(e,n),n,s,i))return void 0===o.defaultValue?void 0:Hc(o.defaultValue);const u=l(n,o);return Qc(u,o,s,i)?o.uniqueValues?Array.from(new Set(u)):u:void 0===o.defaultValue?void 0:Hc(o.defaultValue)}function Jc(e,t){e.push(Object.assign({severity:"error"},t))}function ed(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}class td{get additionalExtensionsUsed(){return this._additionalExtensionsUsed}constructor(e,t={}){var n,o;this._flowGraphs=e,this._options=t,this._graphAnalyses=[],this._additionalExtensionsUsed=[],this._rootDiagnostics=[],this._isPreflight=!1,this.required=null===(n=t.required)||void 0===n||n,this.additionalExtensionsRequired=Array.from(new Set(null!==(o=t.additionalExtensionsRequired)&&void 0!==o?o:[])).sort(),this._refreshAnalysis()}_refreshAnalysis(){this._rootDiagnostics.length=0,this._graphAnalyses=this._analyzeGraphs(),this._additionalExtensionsUsed=Array.from(new Set([...this._collectAdditionalExtensions(),...this.additionalExtensionsRequired])).sort();const e=this._mergeBuildDiagnostics(this._validateBuildWithSourceIndices()),t=this._graphAnalyses.flatMap(e=>e.nodes.map(t=>({graphIndex:e.graphIndex,nodeIndex:t.sourceIndex,operation:t.operation,blockIds:t.blocks.map(e=>e.uniqueId).sort(),classification:t.classification,diagnostics:t.diagnostics.slice()}))),n=this._sortDiagnostics(this._rootDiagnostics.concat(this._graphAnalyses.flatMap(e=>e.diagnostics.concat(e.nodes.flatMap(e=>e.diagnostics))),e));this._analysis={representable:!n.some(e=>"error"===e.severity),nodes:t,diagnostics:n}}_mergeBuildDiagnostics(e){var t,n;const o=[];for(const s of e){const e=null===(t=/\/nodes\/(\d+)(?:\/|$)/.exec(s.path))||void 0===t?void 0:t[1],r=null!==(n=s.nodeIndex)&&void 0!==n?n:void 0===e?void 0:parseInt(e,10),i=void 0===s.graphIndex?void 0:this._graphAnalyses[s.graphIndex],a=void 0===r||null==i?void 0:i.nodes.find(e=>e.sourceIndex===r);a?(a.diagnostics.some(e=>e.code===s.code&&e.path===s.path&&e.message===s.message)||a.diagnostics.push(Object.assign(Object.assign({},s),{nodeIndex:r})),"error"!==s.severity||"exact"!==a.classification&&"inverse-composite"!==a.classification||(a.classification="lossy")):o.push(s)}return o}analyze(){return this._refreshAnalysis(),{representable:this._analysis.representable,nodes:this._analysis.nodes.map(e=>Object.assign(Object.assign({},e),{blockIds:e.blockIds.slice(),diagnostics:e.diagnostics.slice()})),diagnostics:this._analysis.diagnostics.slice()}}build(e){var t,n,o,s;if(this._refreshAnalysis(),!this._analysis.representable)throw new Oc(this._analysis.diagnostics);const r=[],i=this._graphAnalyses.map(t=>this._buildGraph(t,e,r));if(this._writeCompanionNodeExtensions(e,r),r.some(e=>"error"===e.severity))throw new Oc(this._sortDiagnostics(r));const a=(null===(t=this._options.document)||void 0===t?void 0:t.source)?kc(this._options.document.source):{graphs:[]};a.graphs=i;const l=null!==(s=null!==(n=this._options.defaultGraphIndex)&&void 0!==n?n:null===(o=this._options.document)||void 0===o?void 0:o.defaultGraphIndex)&&void 0!==s?s:0;if(l<0||l>=i.length)throw Jc(r,{code:"GRAPH_COUNT_MISMATCH",path:"/extensions/KHR_interactivity/graph",message:`Default graph index ${l} is outside the exported graph range.`}),new Oc(r);return 0===l&&void 0===a.graph||(a.graph=l),a}_getSourceGraph(e,t){var n,o,s;const r=null===(o=null===(n=this._options.document)||void 0===n?void 0:n.graphs[t])||void 0===o?void 0:o.source;if(r)return Wu(r);const i=null===(s=e.metadata)||void 0===s?void 0:s.khrInteractivity;return(null==i?void 0:i.source)?Wu(i.source):void 0}_validateBuildWithSourceIndices(){const e=[],t=this._options.sourceGLTF,n=e=>void 0!==e&&e>=0?e:void 0,o={getNodeCount:()=>{var e,n;return null!==(n=null===(e=null==t?void 0:t.nodes)||void 0===e?void 0:e.length)&&void 0!==n?n:0},getNodeIndex:e=>{var o;return n(null===(o=null==t?void 0:t.nodes)||void 0===o?void 0:o.findIndex(t=>t._babylonTransformNode===e))},getAnimationIndex:e=>{var o;return n(null===(o=null==t?void 0:t.animations)||void 0===o?void 0:o.findIndex(t=>t._babylonAnimationGroup===e))},getCameraIndex:e=>{var o;return n(null===(o=null==t?void 0:t.cameras)||void 0===o?void 0:o.findIndex(t=>t._babylonCamera===e))},getMaterialIndex:e=>{var o;return n(null===(o=null==t?void 0:t.materials)||void 0===o?void 0:o.findIndex(t=>{var n;return Object.values(null!==(n=t._data)&&void 0!==n?n:{}).some(t=>t.babylonMaterial===e)}))},getRootIndex:(e,t)=>this._getSourceRootIndex(e,t),setNodeExtension:()=>{}};this._isPreflight=!0;try{for(const t of this._graphAnalyses)this._buildGraph(t,o,e);this._writeCompanionNodeExtensions(o,e)}finally{this._isPreflight=!1}return e}_analyzeGraphs(){var e,t,n,o,s;const r=[];if(this._options.document||Jc(this._rootDiagnostics,{code:"GRAPH_SOURCE_MISSING",path:"/extensions/KHR_interactivity",message:"A canonical KHR_interactivity document is required to preserve root metadata and the default graph selection."}),0===this._flowGraphs.length)return Jc(this._rootDiagnostics,{code:"GRAPH_COUNT_MISMATCH",path:"/extensions/KHR_interactivity/graphs",message:"At least one FlowGraph is required for KHR_interactivity export."}),r;for(const n of null!==(t=null===(e=this._options.document)||void 0===e?void 0:e.diagnostics)&&void 0!==t?t:[])Jc(this._rootDiagnostics,{code:"GRAPH_INVALID",path:n.path,message:n.message,severity:n.severity});if(this._options.document&&this._options.document.graphs.length!==this._flowGraphs.length)return Jc(this._rootDiagnostics,{code:"GRAPH_COUNT_MISMATCH",path:"/extensions/KHR_interactivity/graphs",message:`Canonical source has ${this._options.document.graphs.length} graph(s), but ${this._flowGraphs.length} FlowGraph(s) were supplied.`}),r;for(let e=0;e<this._flowGraphs.length;e++){const t=this._flowGraphs[e],i=this._getSourceGraph(t,e),a=[];for(const t of null!==(s=null===(o=null===(n=this._options.document)||void 0===n?void 0:n.graphs[e])||void 0===o?void 0:o.diagnostics)&&void 0!==s?s:[])Jc(a,{code:"GRAPH_INVALID",graphIndex:e,path:t.path,message:t.message,severity:t.severity});if(!i){Jc(a,{code:"GRAPH_SOURCE_MISSING",graphIndex:e,path:`/graphs/${e}`,message:"This FlowGraph has no canonical KHR_interactivity source. Only imported graphs and registered standalone inverse mappings can be exported."});const n=t.getAllBlocks().map(e=>({sourceIndex:-1,declarationIndex:-1,operation:"",blocks:[e],classification:this._classifyStandaloneBlock(e,a),diagnostics:a.filter(t=>t.blockId===e.uniqueId)}));r.push({graph:t,graphIndex:e,source:{},nodes:n,diagnostics:a});continue}r.push({graph:t,graphIndex:e,source:i,nodes:this._analyzeImportedNodes(t,e,i,a),diagnostics:a})}return r}_classifyStandaloneBlock(e,t){const n=Fu().filter(t=>1===t.mapping.blocks.length&&Gc(t.mapping.blocks[0])===e.getClassName()),o=`/blocks/${e.uniqueId}`;return 0===n.length?(Jc(t,{code:"BLOCK_UNSUPPORTED",path:o,blockId:e.uniqueId,message:`FlowGraph block "${e.getClassName()}" has no KHR_interactivity inverse mapping.`}),"unsupported"):(Jc(t,{code:"BLOCK_AMBIGUOUS",path:o,blockId:e.uniqueId,message:1===n.length?`FlowGraph block "${e.getClassName()}" is not associated with canonical KHR source provenance.`:`FlowGraph block "${e.getClassName()}" is ambiguous between ${n.map(e=>Vc(e.op,e.extension)).join(", ")}.`}),"lossy")}_analyzeImportedNodes(e,t,n,o){var s,r,i,a,l,u,c;const d=new Map;for(const n of e.getAllBlocks()){const e=Pc(n);if(!e||e.graphIndex!==t||e.nodeIndex<0){const e=[];this._classifyStandaloneBlock(n,e),o.push(...e),d.set(Number.MIN_SAFE_INTEGER+d.size,[n]);continue}const r=null!==(s=d.get(e.nodeIndex))&&void 0!==s?s:[];r.push(n),d.set(e.nodeIndex,r)}const h=[];for(let e=0;e<(null!==(i=null===(r=n.nodes)||void 0===r?void 0:r.length)&&void 0!==i?i:0);e++){const o=n.nodes[e],s=null===(a=n.declarations)||void 0===a?void 0:a[o.declaration],r=null===(u=null===(l=this._options.document)||void 0===l?void 0:l.graphs[t])||void 0===u?void 0:u.declarations[o.declaration],i=s?Vc(s.op,s.extension):"",p=s&&"unsupported-extension"!==(null==r?void 0:r.support)?Ru(s,!1):void 0,f=null!==(c=d.get(e))&&void 0!==c?c:[],m=[];let g=p&&p.blocks.length>1?"inverse-composite":"exact";s?"BABYLON"===s.extension?(g="unsupported",Jc(m,{code:"BLOCK_UNSUPPORTED",graphIndex:t,nodeIndex:e,path:`/graphs/${t}/nodes/${e}`,message:`Compatibility-only operation "${i}" is not part of ratified KHR_interactivity and cannot be exported as standards-compliant data.`})):p||s.extension?!p&&s.extension?1!==f.length||"FlowGraphUnsupportedInteractivityBlock"!==f[0].getClassName()?(g="unsupported",Jc(m,{code:"BLOCK_TYPE_MISMATCH",graphIndex:t,nodeIndex:e,path:`/graphs/${t}/nodes/${e}`,message:`Unsupported extension operation "${i}" must remain an intact typed no-op block.`})):(this._validateUnsupportedExtensionBlock(n,o,e,i,s,f[0],t,m),m.some(e=>"error"===e.severity)&&(g="lossy")):(this._validateMappedBlocks(t,e,i,p,f,m),m.some(e=>"error"===e.severity)&&(g="lossy")):(g="unsupported",Jc(m,{code:"BLOCK_UNSUPPORTED",graphIndex:t,nodeIndex:e,path:`/graphs/${t}/nodes/${e}`,message:`Unknown core operation "${s.op}" cannot be exported.`})):(g="unsupported",Jc(m,{code:"NODE_SOURCE_MISSING",graphIndex:t,nodeIndex:e,path:`/graphs/${t}/nodes/${e}/declaration`,message:`Declaration index ${o.declaration} is unavailable.`})),0===f.length&&(g="unsupported",Jc(m,{code:"BLOCK_ROLE_MISSING",graphIndex:t,nodeIndex:e,path:`/graphs/${t}/nodes/${e}`,message:`The FlowGraph blocks for "${i}" were removed.`})),d.delete(e),h.push({sourceIndex:e,declarationIndex:o.declaration,operation:i,mapping:p,blocks:f,classification:g,diagnostics:m})}for(const e of d.values()){const t=e[0],n=[],s=this._classifyStandaloneBlock(t,n);o.push(...n),h.push({sourceIndex:-1,declarationIndex:-1,operation:"",blocks:e,classification:s,diagnostics:n})}return h}_validateUnsupportedExtensionBlock(e,n,o,s,r,i,a,l){var u,c,d,h;const p=i.config,f=e=>Array.isArray(e)?e.map(e=>null!==e&&"object"==typeof e?{name:e.name,signature:e.signature}:e).sort((e,t)=>String(JSON.stringify(e)).localeCompare(String(JSON.stringify(t)))):e,m=e=>Array.isArray(e)?e.slice().sort():e,g=t=>Object.entries(null!=t?t:{}).map(([t,n])=>{var o,s;return{name:t,signature:null===(s=null===(o=e.types)||void 0===o?void 0:o[n.type])||void 0===s?void 0:s.signature}}).sort((e,t)=>e.name.localeCompare(t.name)),_=Array.from(new Set((null!==(u=e.nodes)&&void 0!==u?u:[]).flatMap(e=>{var t;return Object.values(null!==(t=e.flows)&&void 0!==t?t:{}).filter(e=>e.node===o).map(e=>{var t;return null!==(t=e.socket)&&void 0!==t?t:"in"})}))).sort(),v=Object.keys(null!==(c=n.flows)&&void 0!==c?c:{}).sort(),y={inputValues:i.dataInputs.map(e=>e.name).sort(),outputValues:i.dataOutputs.map(e=>e.name).sort(),inputFlows:i instanceof t.FlowGraphExecutionBlock?i.signalInputs.map(e=>e.name).sort():[],outputFlows:i instanceof t.FlowGraphExecutionBlock?i.signalOutputs.map(e=>e.name).sort():[]},b={inputValues:Object.keys(null!==(d=r.inputValueSockets)&&void 0!==d?d:{}).sort(),outputValues:Object.keys(null!==(h=r.outputValueSockets)&&void 0!==h?h:{}).sort(),inputFlows:_,outputFlows:v};p.operation===s&&Wc(f(p.inputValueSockets),g(r.inputValueSockets))&&Wc(f(p.outputValueSockets),g(r.outputValueSockets))&&Wc(m(p.inputFlowSockets),_)&&Wc(m(p.outputFlowSockets),v)&&Wc(y,b)||Jc(l,{code:"BLOCK_TYPE_MISMATCH",graphIndex:a,nodeIndex:o,path:`/graphs/${a}/nodes/${o}`,blockId:i.uniqueId,message:`Unsupported extension operation "${s}" has edited socket metadata and can no longer be exported as its canonical typed no-op.`})}_validateMappedBlocks(e,n,o,s,r,i){var a,l,u,c,d,h,p,f,m,g,_,v;for(let t=0;t<s.blocks.length;t++){const a=r.filter(e=>{var n;return(null===(n=Pc(e))||void 0===n?void 0:n.role)===t});0!==a.length?a.length>1?Jc(i,{code:"BLOCK_ROLE_DUPLICATE",graphIndex:e,nodeIndex:n,path:`/graphs/${e}/nodes/${n}`,message:`Composite "${o}" has more than one block for role ${t}.`}):a[0].getClassName()!==Gc(s.blocks[t])&&Jc(i,{code:"BLOCK_TYPE_MISMATCH",graphIndex:e,nodeIndex:n,blockId:a[0].uniqueId,path:`/blocks/${a[0].uniqueId}`,message:`Composite role ${t} must be "${s.blocks[t]}", not "${a[0].getClassName()}".`}):Jc(i,{code:"BLOCK_ROLE_MISSING",graphIndex:e,nodeIndex:n,path:`/graphs/${e}/nodes/${n}`,message:`Composite "${o}" is missing role ${t} (${s.blocks[t]}).`})}for(const t of r){const r=Pc(t);!r||r.nodeIndex!==n||r.operation!==o||r.declarationIndex<0?Jc(i,{code:"BLOCK_PROVENANCE_INVALID",graphIndex:e,nodeIndex:n,blockId:t.uniqueId,path:`/blocks/${t.uniqueId}`,message:`Block provenance no longer identifies the imported "${o}" node.`}):(r.role<-1||r.role>=s.blocks.length)&&Jc(i,{code:"BLOCK_PROVENANCE_INVALID",graphIndex:e,nodeIndex:n,blockId:t.uniqueId,path:`/blocks/${t.uniqueId}`,message:`Block role ${r.role} is not part of the "${o}" inverse mapping.`})}const y=new Map,b=(e,t)=>{var n,o;const s=null!==(n=y.get(e))&&void 0!==n?n:new Set;s.add(t),y.set(e,s);const r=null!==(o=y.get(t))&&void 0!==o?o:new Set;r.add(e),y.set(t,r)};for(const o of null!==(a=s.interBlockConnectors)&&void 0!==a?a:[]){const s=$c(r,o.inputBlockIndex),a=$c(r,o.outputBlockIndex),l=o.isVariable?null==s?void 0:s.dataInputs.find(e=>e.name===o.input):s instanceof t.FlowGraphExecutionBlock?s.signalInputs.find(e=>e.name===o.input):void 0,u=o.isVariable?null==a?void 0:a.dataOutputs.find(e=>e.name===o.output):a instanceof t.FlowGraphExecutionBlock?a.signalOutputs.find(e=>e.name===o.output):void 0;l&&u&&b(l,u),l&&u&&l._connectedPoint.includes(u)||Jc(i,{code:"COMPOSITE_CONNECTION_CHANGED",graphIndex:e,nodeIndex:n,path:`/graphs/${e}/nodes/${n}`,message:`Internal composite connection "${o.output}" -> "${o.input}" was changed.`})}const x=new Set;for(const a of r){const b=Pc(a);for(const[t,s]of Object.entries(null!==(l=null==b?void 0:b.generatedConfiguration)&&void 0!==l?l:{})){const r="eventData"===t?Su(null===(u=a.config)||void 0===u?void 0:u[t]):"outputSignalCount"===t?null!==(p=null!==(d=null===(c=a.outputSignals)||void 0===c?void 0:c.length)&&void 0!==d?d:null===(h=a.executionSignals)||void 0===h?void 0:h.length)&&void 0!==p?p:null===(f=a.config)||void 0===f?void 0:f[t]:null===(m=a.config)||void 0===m?void 0:m[t],l=null!==(g=Dc(null==b?void 0:b.generatedConfigurationRuntime,t))&&void 0!==g?g:"eventData"===t?Kc(s):void 0,_=l?"eventData"===t?Kc(r):Ku(r):void 0;(l?l.unrepresentable||(null==_?void 0:_.unrepresentable)||(null==_?void 0:_.runtimeValueFingerprint)!==l.runtimeValueFingerprint:!Wc(r,s))&&Jc(i,{code:"CONFIGURATION_UNREPRESENTABLE",graphIndex:e,nodeIndex:n,blockId:a.uniqueId,path:`/blocks/${a.uniqueId}/config/${t}`,message:`Importer-generated configuration "${t}" was changed and no longer represents "${o}".`})}for(const t of a.dataInputs){if(t.isConnected()||Bc(t))continue;const o=Dc(null==b?void 0:b.generatedInputDefaults,t.name),s=Ku(t._defaultValue);(!o||o.unrepresentable||s.unrepresentable||s.runtimeValueFingerprint!==o.runtimeValueFingerprint)&&Jc(i,{code:"INPUT_DEFAULT_UNREPRESENTABLE",graphIndex:e,nodeIndex:n,blockId:a.uniqueId,socket:t.name,path:`/blocks/${a.uniqueId}/dataInputs/${t.name}`,message:(null==o?void 0:o.unrepresentable)?`Importer-generated input default "${t.name}" could not be preserved safely for inverse export.`:o?`Importer-generated input default "${t.name}" was changed and has no KHR_interactivity inverse mapping.`:`Input default "${t.name}" has no import-time provenance or KHR_interactivity inverse mapping.`})}if((null!==(_=null==b?void 0:b.role)&&void 0!==_?_:0)<0)continue;const T=[...a.dataInputs,...a.dataOutputs,...a instanceof t.FlowGraphExecutionBlock?a.signalInputs:[],...a instanceof t.FlowGraphExecutionBlock?a.signalOutputs:[]];for(const t of T){if(!t.isConnected()||x.has(t))continue;const l=null!==(v=Bc(t))&&void 0!==v?v:this._inferSocketProvenance(t,{sourceIndex:n,declarationIndex:-1,operation:o,mapping:s,blocks:r,classification:"exact",diagnostics:i}),u=t._connectedPoint.filter(e=>{var n,o;const s=r.includes(e._ownerBlock),i=s&&-1===(null===(n=Pc(e._ownerBlock))||void 0===n?void 0:n.role);return s?!((null===(o=y.get(t))||void 0===o?void 0:o.has(e))||l&&i):!l});u.length>0&&(x.add(t),u.forEach(e=>x.add(e)),Jc(i,{code:"SOCKET_PROVENANCE_MISSING",graphIndex:e,nodeIndex:n,blockId:a.uniqueId,socket:t.name,path:`/blocks/${a.uniqueId}/${t.name}`,message:`Connection from socket "${t.name}" is not part of the "${o}" inverse mapping.`}))}}}_buildGraph(e,t,n){var o,s,r;const i=Wu(e.source),a=null!==(o=e.source.name)&&void 0!==o?o:`Graph ${e.graphIndex+1}`;void 0!==e.source.name||e.graph.name!==a?i.name=e.graph.name:delete i.name,this._updateVariables(i,e.graph,n,e.graphIndex);const l=new Map(e.nodes.filter(e=>e.sourceIndex>=0).map(e=>[e.sourceIndex,e])),u=(null!==(s=i.nodes)&&void 0!==s?s:[]).map((o,s)=>{const r=l.get(s);return this._rebuildNode(i,o,r,e,t,n)}),c=this._topologicallyOrderNodes(u,e.graphIndex,n);if(!c)return i;void 0!==e.source.nodes||c.nodes.length>0?i.nodes=c.nodes:delete i.nodes,this._remapGraphReferences(i,t,n,e.graphIndex,c.sourceIndices);const d=uc(i,e.graphIndex,new Set(this.additionalExtensionsUsed),t.getNodeCount());for(const t of d.diagnostics)if("error"===t.severity){const o=null===(r=/\/nodes\/(\d+)(?:\/|$)/.exec(t.path))||void 0===r?void 0:r[1],s=void 0===o?void 0:parseInt(o,10);Jc(n,{code:"GRAPH_INVALID",graphIndex:e.graphIndex,nodeIndex:void 0===s?void 0:c.sourceIndices[s],path:t.path,message:t.message})}return i}_rebuildNode(e,n,o,s,r,i){var a,l,u,c,d,h,p,f,m;const g=kc(n),_=o.mapping;_&&this._rebuildConfiguration(e,g,o,s.graphIndex,r,i);for(const t of Object.keys(null!==(a=n.values)&&void 0!==a?a:{}).sort()){if(_){const r=this._isEffectiveValueInput(e,n,o,t,!1),a=this._isEffectiveValueInput(e,n,o,t,!0);if(!r){a&&Jc(i,{code:"CONFIGURATION_UNREPRESENTABLE",graphIndex:s.graphIndex,nodeIndex:o.sourceIndex,socket:t,path:`/graphs/${s.graphIndex}/nodes/${o.sourceIndex}/values/${t}`,message:`Configuration edits made formerly ignored value socket "${t}" effective without an authored FlowGraph socket.`});continue}if(!a){delete g.values[t];continue}}const r=Uc(o.blocks,o.sourceIndex,t);if(!r){Jc(i,{code:"SOCKET_PROVENANCE_MISSING",graphIndex:s.graphIndex,nodeIndex:o.sourceIndex,socket:t,path:`/graphs/${s.graphIndex}/nodes/${o.sourceIndex}/values/${t}`,message:`Input value socket "${t}" no longer has KHR_interactivity provenance.`});continue}const a=this._getMappingObject(null===(l=null==_?void 0:_.inputs)||void 0===l?void 0:l.values,t);g.values[t]=this._rebuildInputValue(e,n.values[t],r,a,o,s,i)}g.values&&0===Object.keys(g.values).length&&delete g.values;const v=new Map;for(const r of o.blocks)if(r instanceof t.FlowGraphExecutionBlock)for(const t of r.signalOutputs){const r=null!==(u=Bc(t))&&void 0!==u?u:this._inferSocketProvenance(t,o);if((null==r?void 0:r.nodeIndex)===o.sourceIndex&&"flow"===r.kind&&"output"===r.direction){if(!this._isEffectiveFlowOutput(e,n,o,r.socket,!0)){t.isConnected()&&Jc(i,{code:"CONFIGURATION_UNREPRESENTABLE",graphIndex:s.graphIndex,nodeIndex:o.sourceIndex,socket:r.socket,path:`/graphs/${s.graphIndex}/nodes/${o.sourceIndex}/flows/${r.socket}`,message:`Flow socket "${r.socket}" is connected but disabled by the edited configuration.`});continue}v.has(r.socket)?Jc(i,{code:"SOCKET_CONNECTION_AMBIGUOUS",graphIndex:s.graphIndex,nodeIndex:o.sourceIndex,socket:r.socket,path:`/graphs/${s.graphIndex}/nodes/${o.sourceIndex}/flows/${r.socket}`,message:`Multiple FlowGraph outputs map to KHR flow socket "${r.socket}".`}):v.set(r.socket,t)}}const y={};for(const[t,r]of Object.entries(null!==(c=n.flows)&&void 0!==c?c:{})){const a=this._isEffectiveFlowOutput(e,n,o,t,!1),l=this._isEffectiveFlowOutput(e,n,o,t,!0);a||(l?Jc(i,{code:"CONFIGURATION_UNREPRESENTABLE",graphIndex:s.graphIndex,nodeIndex:o.sourceIndex,socket:t,path:`/graphs/${s.graphIndex}/nodes/${o.sourceIndex}/flows/${t}`,message:`Configuration edits made formerly ignored flow socket "${t}" effective without a live FlowGraph connection.`}):ed(y,t,kc(r)))}for(const[t,r]of[...v.entries()].sort(([e],[t])=>e.localeCompare(t))){if(0===r._connectedPoint.length){const r=null===(d=n.flows)||void 0===d?void 0:d[t];if(r){const n=this._isNoOpFlowTarget(e,s,r,!1),a=this._isNoOpFlowTarget(e,s,r,!0);n&&a?ed(y,t,kc(r)):n&&!a&&Jc(i,{code:"CONFIGURATION_UNREPRESENTABLE",graphIndex:s.graphIndex,nodeIndex:o.sourceIndex,socket:t,path:`/graphs/${s.graphIndex}/nodes/${o.sourceIndex}/flows/${t}`,message:`Configuration edits made formerly ignored flow target "${null!==(h=r.socket)&&void 0!==h?h:"in"}" effective without a live FlowGraph connection.`})}continue}if(r._connectedPoint.length>1){Jc(i,{code:"SOCKET_CONNECTION_AMBIGUOUS",graphIndex:s.graphIndex,nodeIndex:o.sourceIndex,socket:t,path:`/graphs/${s.graphIndex}/nodes/${o.sourceIndex}/flows/${t}`,message:`KHR output flow "${t}" must connect to exactly one target; found ${r._connectedPoint.length}.`});continue}const a=r._connectedPoint[0],l=Pc(a._ownerBlock),u=l?s.nodes.find(e=>e.sourceIndex===l.nodeIndex):void 0,c=null!==(p=Bc(a))&&void 0!==p?p:u?this._inferSocketProvenance(a,u):void 0;if(!c||"flow"!==c.kind||"input"!==c.direction){Jc(i,{code:"SOCKET_TARGET_UNREPRESENTABLE",graphIndex:s.graphIndex,nodeIndex:o.sourceIndex,socket:t,path:`/graphs/${s.graphIndex}/nodes/${o.sourceIndex}/flows/${t}`,message:`Flow target for "${t}" is not part of a representable KHR node.`});continue}if(u){const n=null===(f=e.nodes)||void 0===f?void 0:f[u.sourceIndex];if(n&&!this._isEffectiveFlowInput(e,n,u,c.socket,!0)){Jc(i,{code:"CONFIGURATION_UNREPRESENTABLE",graphIndex:s.graphIndex,nodeIndex:o.sourceIndex,socket:t,path:`/graphs/${s.graphIndex}/nodes/${o.sourceIndex}/flows/${t}`,message:`Flow target socket "${c.socket}" is disabled by the target node's edited configuration.`});continue}}const g=(null===(m=n.flows)||void 0===m?void 0:m[t])?kc(n.flows[t]):{node:c.nodeIndex};g.node=c.nodeIndex,"in"===c.socket?delete g.socket:g.socket=c.socket,ed(y,t,g)}return Object.keys(y).length>0?g.flows=y:delete g.flows,_&&this._remapPointerTemplateInputs(e,g,o,s.graphIndex,r,i),g}_getMappingObject(e,t){var n;return Dc(e,t)||(null===(n=Object.entries(null!=e?e:{}).find(([e])=>e.startsWith("[")&&e.endsWith("]")))||void 0===n?void 0:n[1])}_inferSocketProvenance(e,n){var o,s,r,i;const a=n.mapping,l=e._ownerBlock,u=Pc(l);if(!a||!u||u.role<0)return;const c=l.dataInputs.includes(e),d=l.dataOutputs.includes(e),h=l instanceof t.FlowGraphExecutionBlock&&l.signalInputs.includes(e),p=l instanceof t.FlowGraphExecutionBlock&&l.signalOutputs.includes(e),f=c||d?"value":"flow",m=c||h?"input":"output";if(!(c||d||h||p))return;const g="value"===f?"input"===m?null===(o=a.inputs)||void 0===o?void 0:o.values:null===(s=a.outputs)||void 0===s?void 0:s.values:"input"===m?null===(r=a.inputs)||void 0===r?void 0:r.flows:null===(i=a.outputs)||void 0===i?void 0:i.flows;for(const[t,n]of Object.entries(null!=g?g:{})){if(n.compatibilityOnly)continue;if((n.toBlock?a.blocks.indexOf(n.toBlock):0)!==u.role)continue;let o;if(t.startsWith("[")&&t.endsWith("]")){if("flow"!==f||"input"!==m)continue;const[t,s=""]=n.name.split("$1");e.name.startsWith(t)&&e.name.endsWith(s)&&(o=e.name.substring(t.length,e.name.length-s.length))}else n.name===e.name&&(o=t);if(void 0!==o)return Object.assign(Object.assign({},u),{kind:f,direction:m,socket:o})}return"flow"===f&&"input"===m&&"in"===e.name&&Mu(n.operation)?Object.assign(Object.assign({},u),{kind:f,direction:m,socket:"in"}):void 0}_isNoOpFlowTarget(e,t,n,o){var s,r,i,a,l,u;const c=null===(s=e.nodes)||void 0===s?void 0:s[n.node],d=c?null===(r=e.declarations)||void 0===r?void 0:r[c.declaration]:void 0;if(!d)return!1;const h=Ru(d,!1);if(!h)return!1;const p=null!==(i=n.socket)&&void 0!==i?i:"in",f=Dc(null===(a=h.inputs)||void 0===a?void 0:a.flows,p);if(f&&!f.compatibilityOnly)return!1;if(Object.keys(null!==(u=null===(l=h.inputs)||void 0===l?void 0:l.flows)&&void 0!==u?u:{}).some(e=>e.startsWith("[")&&e.endsWith("]"))){const s=t.nodes.find(e=>e.sourceIndex===n.node),r=this._getAllowedDynamicFlowSockets(c,h,"input",o?s:void 0,e);return!!r&&!r.has(p)}return!("in"===p&&Mu(Vc(d.op,d.extension)))}_isEffectiveFlowInput(e,t,n,o,s){var r,i,a;const l=n.mapping;if(!l)return!0;const u=Dc(null===(r=l.inputs)||void 0===r?void 0:r.flows,o);if(u&&!u.compatibilityOnly)return!0;if(Object.keys(null!==(a=null===(i=l.inputs)||void 0===i?void 0:i.flows)&&void 0!==a?a:{}).some(e=>e.startsWith("[")&&e.endsWith("]"))){const r=this._getAllowedDynamicFlowSockets(t,l,"input",s?n:void 0,e);return!r||r.has(o)}return"in"===o&&Mu(n.operation)}_isEffectiveFlowOutput(e,t,n,o,s){var r,i,a;const l=null===(i=null===(r=n.mapping)||void 0===r?void 0:r.outputs)||void 0===i?void 0:i.flows;if(!n.mapping)return Object.prototype.hasOwnProperty.call(null!==(a=t.flows)&&void 0!==a?a:{},o);const u=Dc(l,o);if(u&&!u.compatibilityOnly)return!0;if(!Object.keys(null!=l?l:{}).some(e=>e.startsWith("[")&&e.endsWith("]")))return!1;const c=n.mapping?this._getAllowedDynamicFlowSockets(t,n.mapping,"output",s?n:void 0,e):void 0;return!c||c.has(o)}_getAllowedDynamicFlowSockets(e,t,n,o,s){var r,i,a,l,u;for(const[c,d]of Object.entries(null!==(r=t.configuration)&&void 0!==r?r:{})){if(!("input"===n?d.generatesInputFlowSockets:d.generatesOutputFlowSockets))continue;const r=s?Zc(e,t,c,d,s,o,null===(a=null===(i=this._options.sourceGLTF)||void 0===i?void 0:i.nodes)||void 0===a?void 0:a.length):null===(u=null===(l=e.configuration)||void 0===l?void 0:l[c])||void 0===u?void 0:u.value,h=null!=r?r:Array.isArray(d.defaultValue)?d.defaultValue:[d.defaultValue];if("input"===n){const e="number"==typeof h[0]&&Number.isInteger(h[0])&&h[0]>=0?h[0]:0;return new Set(Array.from({length:e},(e,t)=>String(t)))}return new Set(h.filter(e=>void 0!==e).map(String))}}_resolveValueTypeIndex(e,t,n){var o;return"node"in t?this._resolveOutputTypeIndex(e,t.node,null!==(o=t.socket)&&void 0!==o?o:"value",n):t.type}_resolveOutputTypeIndex(e,t,n,o=new Set){var s,r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b,x,T,A,w,M,S,R;const C=`${t}:${n}`;if(o.has(C))return;o.add(C);const I=null===(s=e.nodes)||void 0===s?void 0:s[t],O=I?null===(r=e.declarations)||void 0===r?void 0:r[I.declaration]:void 0;if(!I||!O)return;const F=null===(a=null===(i=O.outputValueSockets)||void 0===i?void 0:i[n])||void 0===a?void 0:a.type;if(void 0!==F)return F;if("pointer/get"===O.op&&"value"===n){const e=null===(c=null===(u=null===(l=I.configuration)||void 0===l?void 0:l.type)||void 0===u?void 0:u.value)||void 0===c?void 0:c[0];return"number"==typeof e?e:void 0}if("variable/get"===O.op&&"value"===n){const t=null===(p=null===(h=null===(d=I.configuration)||void 0===d?void 0:d.variable)||void 0===h?void 0:h.value)||void 0===p?void 0:p[0];return"number"==typeof t?null===(m=null===(f=e.variables)||void 0===f?void 0:f[t])||void 0===m?void 0:m.type:void 0}if("math/switch"===O.op&&"value"===n){const t=null===(g=I.values)||void 0===g?void 0:g.default;return t?this._resolveValueTypeIndex(e,t,o):void 0}if("event/receive"===O.op&&"event"!==n){const t=null===(y=null===(v=null===(_=I.configuration)||void 0===_?void 0:_.event)||void 0===v?void 0:v.value)||void 0===y?void 0:y[0];return"number"==typeof t?null===(A=null===(T=null===(x=null===(b=e.events)||void 0===b?void 0:b[t])||void 0===x?void 0:x.values)||void 0===T?void 0:T[n])||void 0===A?void 0:A.type:void 0}const E=Ru(O,!1),N=this._getMappingObject(null===(w=null==E?void 0:E.outputs)||void 0===w?void 0:w.values,n),L=null==N?void 0:N.gltfType,k="number"===L?"float":"boolean"===L?"bool":"vector2"===L?"float2":"vector3"===L?"float3":"vector4"===L?"float4":L;if(k&&Object.prototype.hasOwnProperty.call($u,k)){const t=null!==(S=null===(M=e.types)||void 0===M?void 0:M.findIndex(e=>e.signature===k))&&void 0!==S?S:-1;return t>=0?t:void 0}const P=(null==N?void 0:N.typeSourceInput)?null===(R=I.values)||void 0===R?void 0:R[N.typeSourceInput]:void 0;return P?this._resolveValueTypeIndex(e,P,o):void 0}_isEffectiveValueInput(e,t,n,o,s){var r,i,a,l,u,c,d,h,p,f;const m=null===(i=null===(r=n.mapping)||void 0===r?void 0:r.inputs)||void 0===i?void 0:i.values,g=Dc(m,o);if(g&&!g.compatibilityOnly)return!0;if(!Object.keys(null!=m?m:{}).some(e=>e.startsWith("[")&&e.endsWith("]")))return!1;const _=o=>{var r,i,a,l;const u=null===(i=null===(r=n.mapping)||void 0===r?void 0:r.configuration)||void 0===i?void 0:i[o];return u?Zc(t,n.mapping,o,u,e,s?n:void 0,null===(l=null===(a=this._options.sourceGLTF)||void 0===a?void 0:a.nodes)||void 0===l?void 0:l.length):void 0};switch(n.operation){case"debug/log":{const e=null===(a=_("message"))||void 0===a?void 0:a[0];return"string"==typeof e&&Bu(e).sockets.includes(o)}case"event/send":{const t=null===(l=_("event"))||void 0===l?void 0:l[0];return"number"==typeof t&&Object.prototype.hasOwnProperty.call(null!==(d=null===(c=null===(u=e.events)||void 0===u?void 0:u[t])||void 0===c?void 0:c.values)&&void 0!==d?d:{},o)}case"variable/set":return(null!==(h=_("variables"))&&void 0!==h?h:[]).map(String).includes(o);case"math/switch":return(null!==(p=_("cases"))&&void 0!==p?p:[]).map(String).includes(o);case"pointer/get":case"pointer/set":case"pointer/interpolate":{const e=null===(f=_("pointer"))||void 0===f?void 0:f[0];return"string"==typeof e&&e.split("/").some(e=>(e.startsWith("[")&&!e.startsWith("[[")||e.startsWith("{")&&!e.startsWith("{{"))&&e.substring(1,e.length-1).replace(/~1/g,"/").replace(/~0/g,"~")===o)}default:return!0}}_rebuildInputValue(e,n,o,s,r,i,a){var l,u,c,d,h,p,f,m;let g=o._connectedPoint[0];if(o.isConnected()&&(null==s?void 0:s.convertConnectedTimeToFrames)&&(g=this._unwrapAnimationTimeHelper(o,r,i,a)),g){const t=Bc(g);if(!t||"value"!==t.kind||"output"!==t.direction)return Jc(a,{code:"SOCKET_TARGET_UNREPRESENTABLE",graphIndex:i.graphIndex,nodeIndex:r.sourceIndex,path:`/graphs/${i.graphIndex}/nodes/${r.sourceIndex}/values`,message:"Value input is connected to a block without representable KHR output provenance."}),n;const o=kc(n);if(delete o.value,o.node=t.nodeIndex,"value"===t.socket?delete o.socket:o.socket=t.socket,void 0!==o.type){const n=this._resolveOutputTypeIndex(e,t.nodeIndex,t.socket);void 0!==n&&(o.type=n)}return o}const _=Bc(o),v=null==_?void 0:_.sourceValue,y=Hc(o._defaultValue),b=Ku(o._defaultValue),x=v&&!("node"in v)?function(e,n,o){var s,r;const i=void 0===n||null===(r=null===(s=e.types)||void 0===s?void 0:s[n])||void 0===r?void 0:r.signature,a=Array.isArray(o)?o:Hc(o);return Ku("float4x4"===i&&a?t.Matrix.FromArray(a):a)}(e,v.type,null!==(l=null==_?void 0:_.runtimeValue)&&void 0!==l?l:v.value):void 0,T=null!==(u=null==_?void 0:_.runtimeValueSnapshot)&&void 0!==u?u:x;if(!o.isConnected()&&T&&!T.unrepresentable&&!b.unrepresentable&&b.runtimeValueFingerprint===T.runtimeValueFingerprint&&v)return kc(v);if(!o.isConnected()&&(null==_?void 0:_.runtimeValue)&&jc(y,_.runtimeValue)&&_.sourceValue)return kc(_.sourceValue);const A=null!==(c=null==_?void 0:_.sourceValue)&&void 0!==c?c:n,w=null!==(d=A.type)&&void 0!==d?d:function(e,t,n,o,s){var r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b;if("variable/set"===o.operation&&/^(0|[1-9]\d*)$/.test(s))return null===(i=null===(r=e.variables)||void 0===r?void 0:r[parseInt(s,10)])||void 0===i?void 0:i.type;if("event/send"===o.operation){const t=null===(l=null===(a=o.mapping)||void 0===a?void 0:a.configuration)||void 0===l?void 0:l.event,n=t?null===(u=Xc(o,"event",t,e))||void 0===u?void 0:u[0]:void 0;if("number"==typeof n)return null===(p=null===(h=null===(d=null===(c=e.events)||void 0===c?void 0:c[n])||void 0===d?void 0:d.values)||void 0===h?void 0:h[s])||void 0===p?void 0:p.type}if("pointer/get"===o.operation||"pointer/set"===o.operation||"pointer/interpolate"===o.operation){const t=null===(m=null===(f=o.mapping)||void 0===f?void 0:f.configuration)||void 0===m?void 0:m.pointer,n=t?null===(g=Xc(o,"pointer",t,e))||void 0===g?void 0:g[0]:void 0;if("string"==typeof n){const t=n.split("/").find(e=>e===`[${s}]`||e===`{${s}}`),o=(null==t?void 0:t.startsWith("["))?"int":(null==t?void 0:t.startsWith("{"))?"ref":void 0;if(o){const t=null!==(v=null===(_=e.types)||void 0===_?void 0:_.findIndex(e=>e.signature===o))&&void 0!==v?v:-1;return t>=0?t:(null!==(y=e.types)&&void 0!==y||(e.types=[]),e.types.push({signature:o}),e.types.length-1)}}}const x=null==n?void 0:n.gltfType,T="number"===x?"float":"boolean"===x?"bool":"vector2"===x?"float2":"vector3"===x?"float3":"vector4"===x?"float4":x&&"any"!==x?x:Lc[t.richType.typeName];if(!T||!$u[T])return;null!==(b=e.types)&&void 0!==b||(e.types=[]);const A=e.types.findIndex(e=>e.signature===T);return A>=0?A:(e.types.push({signature:T}),e.types.length-1)}(e,o,s,r,null!==(h=null==_?void 0:_.socket)&&void 0!==h?h:o.name);if(void 0===w||!(null===(p=e.types)||void 0===p?void 0:p[w]))return Jc(a,{code:"VALUE_UNREPRESENTABLE",graphIndex:i.graphIndex,nodeIndex:r.sourceIndex,path:`/graphs/${i.graphIndex}/nodes/${r.sourceIndex}/values`,message:"A newly inlined value has no canonical KHR type."}),n;const M="node"in A?void 0:A,S=M?function(e,t,n,o=60){var s,r,i,a,l;const u=null!==(i=null===(r=null===(s=e.types)||void 0===s?void 0:s[t.type])||void 0===r?void 0:r.signature)&&void 0!==i?i:"custom",c=null!==(l=null===(a=t.value)||void 0===a?void 0:a.slice())&&void 0!==l?l:function(e){switch(e){case"bool":return[!1];case"int":return[0];case"ref":return[""];case"float":return[NaN];case"float2":return[NaN,NaN];case"float3":return[NaN,NaN,NaN];case"float4":case"float2x2":return[NaN,NaN,NaN,NaN];case"float3x3":return[NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN];case"float4x4":return[NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN];default:return[]}}(u);return(null==n?void 0:n.convertConnectedTimeToFrames)&&1===c.length&&"number"==typeof c[0]&&(c[0]*=o),c}(e,M,s,null!==(f=this._options.targetFps)&&void 0!==f?f:60):void 0;if(jc(y,S))return kc(A);if(!y)return Jc(a,{code:"VALUE_UNREPRESENTABLE",graphIndex:i.graphIndex,nodeIndex:r.sourceIndex,path:`/graphs/${i.graphIndex}/nodes/${r.sourceIndex}/values`,message:"The FlowGraph input value cannot be converted to a KHR value array."}),n;(null==s?void 0:s.convertConnectedTimeToFrames)&&1===y.length&&"number"==typeof y[0]&&(y[0]/=null!==(m=this._options.targetFps)&&void 0!==m?m:60);const R=kc(A);return delete R.node,delete R.socket,R.type=w,R.value=y,R}_unwrapAnimationTimeHelper(e,t,n,o){var s,r,i;const a=n.graphIndex,l=e._connectedPoint[0],u=null==l?void 0:l._ownerBlock,c=u?Pc(u):void 0;if(!u||"FlowGraphMultiplyBlock"!==u.getClassName()||-1!==(null==c?void 0:c.role)||c.nodeIndex!==t.sourceIndex)return void Jc(o,{code:"COMPOSITE_CONNECTION_CHANGED",graphIndex:a,nodeIndex:t.sourceIndex,blockId:null==u?void 0:u.uniqueId,path:`/graphs/${a}/nodes/${t.sourceIndex}`,message:"The generated seconds-to-frames animation helper was changed."});const d=null===(s=u.dataInputs.find(e=>"a"===e.name))||void 0===s?void 0:s._connectedPoint[0],h=u.dataInputs.find(e=>"b"===e.name),p=null!==(r=this._options.targetFps)&&void 0!==r?r:60,f=h?h._defaultValue:void 0;return h&&!h.isConnected()&&(null===(i=Hc(f))||void 0===i?void 0:i[0])===p||Jc(o,{code:"COMPOSITE_CONNECTION_CHANGED",graphIndex:a,nodeIndex:t.sourceIndex,blockId:u.uniqueId,path:`/blocks/${u.uniqueId}`,message:`Animation time helper must multiply by the target frame rate (${p}).`}),d}_rebuildConfiguration(e,t,n,o,s,r){var i,a,l,u,c,d,h,p,f,m,g,_,v,y,b,x,T,A,w,M,S,R,C,I,O;const F=new Set,E=new Set;for(const[t,o]of Object.entries(null!==(a=null===(i=n.mapping)||void 0===i?void 0:i.configuration)&&void 0!==a?a:{})){if(!o.configurationGroup)continue;const s=zc(n,o),r=Yc(n,t,o);r&&!Wc(null===(l=null==s?void 0:s.config)||void 0===l?void 0:l[o.name],r.runtimeValue)&&F.add(o.configurationGroup),Qc(null==r?void 0:r.sourceValue,o,e,null===(c=null===(u=this._options.sourceGLTF)||void 0===u?void 0:u.nodes)||void 0===c?void 0:c.length)||E.add(o.configurationGroup)}for(const[i,a]of Object.entries(null!==(h=null===(d=n.mapping)||void 0===d?void 0:d.configuration)&&void 0!==h?h:{})){const l=!!a.configurationGroup&&F.has(a.configurationGroup),u=!!a.configurationGroup&&E.has(a.configurationGroup),c=Yc(n,i,a),d=l&&!u&&void 0!==c&&void 0===c.runtimeValue&&Qc(c.sourceValue,a,e,null===(f=null===(p=this._options.sourceGLTF)||void 0===p?void 0:p.nodes)||void 0===f?void 0:f.length);let h=Xc(n,i,a,e,!l||d);l&&void 0===h&&void 0!==a.defaultValue&&(h=Hc(a.defaultValue));const N=null===(g=null===(m=t.configuration)||void 0===m?void 0:m[i])||void 0===g?void 0:g.value;if(a.validationOnly&&void 0===h&&void 0===(null==c?void 0:c.runtimeValue))continue;if(l&&!Qc(h,a,e,null===(v=null===(_=this._options.sourceGLTF)||void 0===_?void 0:_.nodes)||void 0===v?void 0:v.length)){Jc(r,{code:"CONFIGURATION_UNREPRESENTABLE",graphIndex:o,nodeIndex:n.sourceIndex,path:`/graphs/${o}/nodes/${n.sourceIndex}/configuration/${i}`,message:`Edited configuration group "${a.configurationGroup}" does not contain a valid value for "${i}".`});continue}if(!h){(void 0!==N||a.required)&&Jc(r,{code:"CONFIGURATION_UNREPRESENTABLE",graphIndex:o,nodeIndex:n.sourceIndex,path:`/graphs/${o}/nodes/${n.sourceIndex}/configuration/${i}`,message:`Configuration "${i}" cannot be inverted from the edited FlowGraph composite.`});continue}if("events"===a.indexSource&&1===h.length&&"number"==typeof h[0]){const t=null===(y=e.events)||void 0===y?void 0:y[h[0]],s=zc(n,a),l=Su(null===(b=null==s?void 0:s.config)||void 0===b?void 0:b.eventData),u=void 0===l?[]:l,d=s?Pc(s):void 0,p=Dc(null==d?void 0:d.generatedConfigurationRuntime,"eventData"),f=c&&Wc(null===(x=null==s?void 0:s.config)||void 0===x?void 0:x[a.name],c.runtimeValue),m=Object.entries(null!==(T=null==t?void 0:t.values)&&void 0!==T?T:{}).map(([t,n])=>{var o,s,r,i;return Object.assign({id:t,type:null===(i=$u[null!==(r=null===(s=null===(o=e.types)||void 0===o?void 0:o[n.type])||void 0===s?void 0:s.signature)&&void 0!==r?r:""])||void 0===i?void 0:i.flowGraphType},void 0===n.value?{}:{value:n.value.slice()})}).sort((e,t)=>e.id.localeCompare(t.id)),g=Kc(u),_=Kc(m);if(!(f&&p?!p.unrepresentable&&!g.unrepresentable&&g.runtimeValueFingerprint===p.runtimeValueFingerprint:!g.unrepresentable&&!_.unrepresentable&&g.runtimeValueFingerprint===_.runtimeValueFingerprint)){Jc(r,{code:"CONFIGURATION_UNREPRESENTABLE",graphIndex:o,nodeIndex:n.sourceIndex,path:`/graphs/${o}/nodes/${n.sourceIndex}/configuration/${i}`,message:`The runtime custom-event payload schema does not match event index ${h[0]}.`});continue}}if((!c||!Wc(null===(w=null===(A=zc(n,a))||void 0===A?void 0:A.config)||void 0===w?void 0:w[a.name],c.runtimeValue)||Qc(c.sourceValue,a,e,null===(S=null===(M=this._options.sourceGLTF)||void 0===M?void 0:M.nodes)||void 0===S?void 0:S.length))&&"assetNodes"===a.indexSource&&1===h.length&&"number"==typeof h[0]){const e=null===(I=null===(C=null===(R=this._options.sourceGLTF)||void 0===R?void 0:R.nodes)||void 0===C?void 0:C[h[0]])||void 0===I?void 0:I._babylonTransformNode,t=e?s.getNodeIndex(e):void 0;if(void 0===t){Jc(r,{code:"REFERENCE_UNRESOLVED",graphIndex:o,nodeIndex:n.sourceIndex,path:`/graphs/${o}/nodes/${n.sourceIndex}/configuration/${i}`,message:`Referenced glTF node ${h[0]} was not exported.`});continue}h[0]=t}if(void 0===N&&void 0!==a.defaultValue&&jc(h,Hc(a.defaultValue)))continue;null!==(O=t.configuration)&&void 0!==O||(t.configuration={});const L=t.configuration[i]?kc(t.configuration[i]):{};L.value=h,ed(t.configuration,i,L)}}_remapPointerTemplateInputs(e,t,n,o,s,r){var i,a,l,u,c,d,h,p,f,m;for(const[e,g]of Object.entries(null!==(a=null===(i=n.mapping)||void 0===i?void 0:i.configuration)&&void 0!==a?a:{})){if(!g.pointerTemplate)continue;const i=null===(c=null===(u=null===(l=t.configuration)||void 0===l?void 0:l[e])||void 0===u?void 0:u.value)||void 0===c?void 0:c[0];if("string"!=typeof i)continue;const a=i.split("/");if(""!==a[0]||a.length<3)continue;let _=a[1].replace(/~1/g,"/").replace(/~0/g,"~");const v=/^\{([^\{\}]+)\}$/.exec(a[1]);if(v){const e=null===(d=t.values)||void 0===d?void 0:d[v[1]],s=e&&!("node"in e)?null===(h=e.value)||void 0===h?void 0:h[0]:void 0,i="string"==typeof s?/^\/([^/]+)$/.exec(s):void 0;if(_=null!==(p=null==i?void 0:i[1])&&void 0!==p?p:"",!Fc.has(_)){Jc(r,{code:"REFERENCE_UNRESOLVED",graphIndex:o,nodeIndex:n.sourceIndex,socket:v[1],path:`/graphs/${o}/nodes/${n.sourceIndex}/values/${v[1]}`,message:`Root collection template input "${v[1]}" cannot be resolved statically for export.`});continue}}if(!Fc.has(_))continue;const y=/^\[([^\[\]]+)\]$/.exec(a[2]),b=/^\{([^\{\}]+)\}$/.exec(a[2]);if(!(v||y||b)||this._validateExtensionReferencePreservation(i,_,r,o,n.sourceIndex,`/graphs/${o}/nodes/${n.sourceIndex}/configuration/${e}`))if(y){const e=null===(f=t.values)||void 0===f?void 0:f[y[1]],i=`/graphs/${o}/nodes/${n.sourceIndex}/values/${y[1]}`;if(!e||"node"in e){Jc(r,{code:"REFERENCE_UNRESOLVED",graphIndex:o,nodeIndex:n.sourceIndex,socket:y[1],path:i,message:`Dynamic index template input "${y[1]}" cannot be safely remapped for the exported ${_} array.`});continue}const a=null===(m=e.value)||void 0===m?void 0:m[0],l="number"==typeof a&&Number.isInteger(a)?this._getRemappedRootIndex(_,a,s):void 0;if(void 0===l){Jc(r,{code:"REFERENCE_UNRESOLVED",graphIndex:o,nodeIndex:n.sourceIndex,socket:y[1],path:i,message:`Template input "${y[1]}" does not resolve to an exported ${_} element.`});continue}e.value=[l]}else if(v&&/^(0|[1-9]\d*)$/.test(a[2])){const i=parseInt(a[2],10),l=this._getRemappedRootIndex(_,i,s);void 0===l?Jc(r,{code:"REFERENCE_UNRESOLVED",graphIndex:o,nodeIndex:n.sourceIndex,path:`/graphs/${o}/nodes/${n.sourceIndex}/configuration/${e}`,message:`Static ${_} index ${i} does not resolve to an exported element.`}):(a[2]=String(l),t.configuration[e].value[0]=a.join("/"))}}}_updateVariables(e,t,n,o){var s,r,i,a;const l=null===(s=t.metadata)||void 0===s?void 0:s.khrInteractivity;(null==l?void 0:l.authoredVariableStructureChanged)&&Jc(n,{code:"VALUE_UNREPRESENTABLE",graphIndex:o,path:`/graphs/${o}/variables`,message:"Adding, renaming, or deleting variables from an imported KHR_interactivity graph is not supported by lossless export."});const u=null==l?void 0:l.authoredVariableValues,c=null==l?void 0:l.authoredVariableTypes;if(u||c){for(const[t,s]of Object.entries(null!=c?c:{})){const i=Number(t),a=null===(r=e.variables)||void 0===r?void 0:r[i],l=qc(e,s);a&&void 0!==l?a.type=l:Jc(n,{code:"VALUE_UNREPRESENTABLE",graphIndex:o,path:`/graphs/${o}/variables/${i}/type`,message:`Authored variable type "${s}" cannot be represented by KHR_interactivity.`})}for(const[t,s]of Object.entries(null!=u?u:{})){const r=Number(t),l=e.variables[r];if(!l){Jc(n,{code:"VALUE_UNREPRESENTABLE",graphIndex:o,path:`/graphs/${o}/variables/${r}`,message:`Authored variable index ${r} does not exist in the canonical graph.`});continue}const u=Hc(s),c=null===(a=null===(i=e.types)||void 0===i?void 0:i[l.type])||void 0===a?void 0:a.signature;u&&c&&(l.value=u)}}}_remapValueArray(e,t,n,o,s,r,i){return"ref"!==t?e:e.map(e=>{var t,a;if("string"==typeof e){const a=null===(t=null==i?void 0:i.match(/^\/([^/]+)\//))||void 0===t?void 0:t[1];return a&&Fc.has(a)?this._remapReferenceToCollection(e,a,n,o,s,r):this._remapReference(e,n,o,s,r)}if(null!==e&&"object"==typeof e){const t=null===(a=null==i?void 0:i.match(/^\/([^/]+)\//))||void 0===a?void 0:a[1];if(t&&Fc.has(t)&&n.getRootIndex){const o=n.getRootIndex(t,e);if(void 0!==o)return`/${t}/${o}`}const o=[["animations",n.getAnimationIndex(e)],["cameras",n.getCameraIndex(e)],["materials",n.getMaterialIndex(e)],["nodes",n.getNodeIndex(e)]],s=(t?o.filter(([e])=>e===t):null===i?[]:o).filter(([,e])=>void 0!==e);if(1===s.length)return`/${s[0][0]}/${s[0][1]}`;if(this._isPreflight)return""}return Jc(o,{code:"REFERENCE_UNRESOLVED",graphIndex:s,nodeIndex:r,path:`/graphs/${s}${void 0===r?"":`/nodes/${r}`}`,message:"An authored reference value does not resolve to an exported glTF entity."}),""})}_topologicallyOrderNodes(e,t,n){var o,s,r,i;const a=e.map(()=>new Set),l=e.map(()=>0);let u=!1;const c=(o,s)=>o<0||s<0||o>=e.length||s>=e.length?(u=!0,void Jc(n,{code:"SOCKET_TARGET_UNREPRESENTABLE",graphIndex:t,path:`/graphs/${t}/nodes`,message:`Dependency ${o} -> ${s} references a node outside the exported graph.`})):o===s?(u=!0,void Jc(n,{code:"DEPENDENCY_CYCLE",graphIndex:t,nodeIndex:o,path:`/graphs/${t}/nodes/${o}`,message:"A KHR_interactivity node cannot depend on itself."})):void(a[o].has(s)||(a[o].add(s),l[s]++));for(let t=0;t<e.length;t++){for(const n of Object.values(null!==(o=e[t].values)&&void 0!==o?o:{}))"node"in n&&c(n.node,t);for(const n of Object.values(null!==(s=e[t].flows)&&void 0!==s?s:{}))c(t,n.node)}if(u)return;const d=l.flatMap((e,t)=>0===e?[t]:[]),h=[];for(;d.length>0;){d.sort((e,t)=>e-t);const e=d.shift();h.push(e);for(const t of a[e])l[t]--,0===l[t]&&d.push(t)}if(h.length!==e.length)return void Jc(n,{code:"DEPENDENCY_CYCLE",graphIndex:t,path:`/graphs/${t}/nodes`,message:"Value and flow dependencies form a cycle that cannot satisfy KHR_interactivity node ordering constraints."});const p=new Map(h.map((e,t)=>[e,t])),f=h.map(t=>e[t]);for(const e of f){for(const t of Object.values(null!==(r=e.values)&&void 0!==r?r:{}))"node"in t&&(t.node=p.get(t.node));for(const t of Object.values(null!==(i=e.flows)&&void 0!==i?i:{}))t.node=p.get(t.node)}return{nodes:f,sourceIndices:h}}_remapGraphReferences(e,t,n,o,s){var r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b,x,T,A,w,M,S,R,C,I,O,F,E;for(let s=0;s<(null!==(i=null===(r=e.variables)||void 0===r?void 0:r.length)&&void 0!==i?i:0);s++){const r=e.variables[s];if("ref"===(null===(l=null===(a=e.types)||void 0===a?void 0:a[r.type])||void 0===l?void 0:l.signature)&&r.value){const i=null===(p=null===(h=null===(d=null===(c=null===(u=this._options.document)||void 0===u?void 0:u.graphs[o])||void 0===c?void 0:c.source.variables)||void 0===d?void 0:d[s])||void 0===h?void 0:h.value)||void 0===p?void 0:p[0],a=r.value[0],l=this._getVariableReferenceCollection(e,s),f=null===l?null:l?`/${l}/0`:"object"!=typeof a&&a!==i||"string"!=typeof i?void 0:i;r.value=this._remapValueArray(r.value,"ref",t,n,o,void 0,f)}}for(const s of null!==(f=e.events)&&void 0!==f?f:[])for(const r of Object.values(null!==(m=s.values)&&void 0!==m?m:{}))"ref"===(null===(_=null===(g=e.types)||void 0===g?void 0:g[r.type])||void 0===_?void 0:_.signature)&&r.value&&(r.value=this._remapValueArray(r.value,"ref",t,n,o));for(let r=0;r<(null!==(y=null===(v=e.nodes)||void 0===v?void 0:v.length)&&void 0!==y?y:0);r++){const i=e.nodes[r],a=null!==(b=s[r])&&void 0!==b?b:r,l=null===(x=e.declarations)||void 0===x?void 0:x[i.declaration],u=l?Ru(l,!1):void 0;for(const[s,r]of Object.entries(null!==(T=i.values)&&void 0!==T?T:{}))if(!("node"in r)&&"ref"===(null===(w=null===(A=e.types)||void 0===A?void 0:A[r.type])||void 0===w?void 0:w.signature)&&r.value){const e=this._getPointerReferenceCollection(i,u,s);if(null===e){Jc(n,{code:"REFERENCE_UNRESOLVED",graphIndex:o,nodeIndex:a,socket:s,path:`/graphs/${o}/nodes/${a}/values/${s}`,message:`Pointer template collection for reference input "${s}" cannot be resolved statically.`});continue}const l=null===(I=null===(C=null===(R=null===(S=null===(M=this._options.document)||void 0===M?void 0:M.graphs[o])||void 0===S?void 0:S.source.nodes)||void 0===R?void 0:R[a])||void 0===C?void 0:C.values)||void 0===I?void 0:I[s],c=l&&!("node"in l)?null===(O=l.value)||void 0===O?void 0:O[0]:void 0,d=r.value[0],h=e?`/${e}/0`:"object"!=typeof d&&d!==c||"string"!=typeof c?void 0:c;r.value=this._remapValueArray(r.value,"ref",t,n,o,a,h)}for(const[e,s]of Object.entries(null!==(F=null==u?void 0:u.configuration)&&void 0!==F?F:{})){if(!s.pointerTemplate)continue;const r=null===(E=i.configuration)||void 0===E?void 0:E[e];(null==r?void 0:r.value)&&(r.value=r.value.map(e=>"string"==typeof e?this._remapReference(e,t,n,o,a):e))}}}_getVariableReferenceCollection(e,t){var n,o,s,r,i,a,l,u,c;const d=new Set;for(let l=0;l<(null!==(o=null===(n=e.nodes)||void 0===n?void 0:n.length)&&void 0!==o?o:0);l++){const n=e.nodes[l],o=null===(s=e.declarations)||void 0===s?void 0:s[n.declaration];"variable/get"!==(null==o?void 0:o.op)||o.extension||(null===(a=null===(i=null===(r=n.configuration)||void 0===r?void 0:r.variable)||void 0===i?void 0:i.value)||void 0===a?void 0:a[0])!==t||d.add(l)}const h=new Set;for(const t of null!==(l=e.nodes)&&void 0!==l?l:[]){const n=null===(u=e.declarations)||void 0===u?void 0:u[t.declaration],o=n?Ru(n,!1):void 0;for(const[e,n]of Object.entries(null!==(c=t.values)&&void 0!==c?c:{})){if(!("node"in n)||!d.has(n.node))continue;const s=this._getPointerReferenceCollection(t,o,e);if(null===s)return null;s&&h.add(s)}}return 1===h.size?h.values().next().value:h.size>1?null:void 0}_getPointerReferenceCollection(e,t,n){var o,s,r,i,a,l,u,c;for(const[d,h]of Object.entries(null!==(o=null==t?void 0:t.configuration)&&void 0!==o?o:{})){if(!h.pointerTemplate)continue;const t=null===(i=null===(r=null===(s=e.configuration)||void 0===s?void 0:s[d])||void 0===r?void 0:r.value)||void 0===i?void 0:i[0];if("string"!=typeof t)continue;const o=t.split("/"),p=o.findIndex(e=>e===`{${n}}`);if(p>1){const t=o[p-1],n=/^\{([^\{\}]+)\}$/.exec(t),s=n?null===(a=e.values)||void 0===a?void 0:a[n[1]]:void 0,r=s&&!("node"in s)?null===(l=s.value)||void 0===l?void 0:l[0]:void 0,i=(n&&"string"==typeof r?null!==(c=null===(u=/^\/([^/]+)$/.exec(r))||void 0===u?void 0:u[1])&&void 0!==c?c:"":t).replace(/~1/g,"/").replace(/~0/g,"~");if(Fc.has(i))return i;if(n)return null}}}_getRemappedRootIndex(e,t,n){const o=new Set(this._getSourceRootObjects(e,t).map(t=>this._getExportedObjectIndex(e,t,n)).filter(e=>void 0!==e));return 1===o.size?o.values().next().value:void 0}_getSourceRootObjects(e,t){var n,o,s,r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b,x,T,A,w,M,S,R,C;const I=this._options.sourceGLTF;switch(e){case"nodes":return(null===(o=null===(n=null==I?void 0:I.nodes)||void 0===n?void 0:n[t])||void 0===o?void 0:o._babylonTransformNode)?[I.nodes[t]._babylonTransformNode]:[];case"animations":return(null===(r=null===(s=null==I?void 0:I.animations)||void 0===s?void 0:s[t])||void 0===r?void 0:r._babylonAnimationGroup)?[I.animations[t]._babylonAnimationGroup]:[];case"cameras":return(null===(a=null===(i=null==I?void 0:I.cameras)||void 0===i?void 0:i[t])||void 0===a?void 0:a._babylonCamera)?[I.cameras[t]._babylonCamera]:[];case"materials":return Array.from(new Set(Object.values(null!==(c=null===(u=null===(l=null==I?void 0:I.materials)||void 0===l?void 0:l[t])||void 0===u?void 0:u._data)&&void 0!==c?c:{}).map(e=>e.babylonMaterial)));case"meshes":return Array.from(new Set([...null!==(p=null===(h=null===(d=null==I?void 0:I.meshes)||void 0===d?void 0:d[t])||void 0===h?void 0:h.primitives.flatMap(e=>e._instanceData?[e._instanceData.babylonSourceMesh]:[]))&&void 0!==p?p:[],...null!==(m=null===(f=null==I?void 0:I.nodes)||void 0===f?void 0:f.filter(e=>e.mesh===t).flatMap(e=>{var t;return[...e._babylonTransformNode?[e._babylonTransformNode]:[],...null!==(t=e._primitiveBabylonMeshes)&&void 0!==t?t:[]]}))&&void 0!==m?m:[]]));case"textures":return null!==(y=null===(v=null===(_=null===(g=null==I?void 0:I.textures)||void 0===g?void 0:g[t])||void 0===_?void 0:_._babylonTextures)||void 0===v?void 0:v.slice())&&void 0!==y?y:[];case"images":return Array.from(new Set(null!==(x=null===(b=null==I?void 0:I.textures)||void 0===b?void 0:b.flatMap(e=>{var t;return null!==(t=e._babylonTextureSources)&&void 0!==t?t:[]}).filter(e=>e.imageIndex===t).map(e=>e.babylonTexture))&&void 0!==x?x:[]));case"samplers":return Array.from(new Set(null!==(A=null===(T=null==I?void 0:I.textures)||void 0===T?void 0:T.flatMap(e=>{var t;return null!==(t=e._babylonTextureSources)&&void 0!==t?t:[]}).filter(e=>e.samplerIndex===t).map(e=>e.babylonTexture))&&void 0!==A?A:[]));case"skins":return(null===(S=null===(M=null===(w=null==I?void 0:I.skins)||void 0===w?void 0:w[t])||void 0===M?void 0:M._data)||void 0===S?void 0:S.babylonSkeleton)?[I.skins[t]._data.babylonSkeleton]:[];case"scenes":return t===(null!==(R=null==I?void 0:I.scene)&&void 0!==R?R:0)&&(null===(C=this._flowGraphs[0])||void 0===C?void 0:C.scene)?[this._flowGraphs[0].scene]:[]}}_getSourceRootIndex(e,t){var n;const o=null===(n=this._options.sourceGLTF)||void 0===n?void 0:n[e];if(!o)return;const s=[];for(let n=0;n<o.length;n++)this._getSourceRootObjects(e,n).includes(t)&&s.push(n);return 1===s.length?s[0]:void 0}_getExportedObjectIndex(e,t,n){if(n.getRootIndex)return n.getRootIndex(e,t);switch(e){case"nodes":return n.getNodeIndex(t);case"animations":return n.getAnimationIndex(t);case"cameras":return n.getCameraIndex(t);case"materials":return n.getMaterialIndex(t);default:return}}_remapReferenceToCollection(e,t,n,o,s,r){var i;if(!this._validateExtensionReferencePreservation(e,t,o,s,r))return e;const a=e.match(/^\/([^/]+)\/(0|[1-9]\d*)(\/.*)?$/);if(!a||!Fc.has(a[1]))return this._remapReference(e,n,o,s,r);const l=this._getSourceRootObjects(t,parseInt(a[2],10)),u=new Set(l.map(e=>this._getExportedObjectIndex(t,e,n)).filter(e=>void 0!==e)),c=1===u.size?u.values().next().value:void 0;return void 0===c?(Jc(o,{code:"REFERENCE_UNRESOLVED",graphIndex:s,nodeIndex:r,path:`/graphs/${s}${void 0===r?"":`/nodes/${r}`}`,message:`Reference "${e}" cannot be remapped to the exported ${t} collection.`}),e):`/${t}/${c}${null!==(i=a[3])&&void 0!==i?i:""}`}_remapReference(e,t,n,o,s){var r;if(!e||e.startsWith("/extensions/KHR_interactivity/events/")||e.startsWith("/extensions/KHR_interactivity/delays/"))return e;const i=/^\/extensions\/([^/]+)\/[^/]+\/(0|[1-9]\d*)(?:\/|$)/.exec(e);if(i&&"KHR_interactivity"!==i[1])return Jc(n,{code:"REFERENCE_UNRESOLVED",graphIndex:o,nodeIndex:s,path:`/graphs/${o}${void 0===s?"":`/nodes/${s}`}`,message:`Indexed reference "${e}" belongs to ${i[1]}, whose serializer index mapping is unavailable.`}),e;const a=e.match(/^\/([^/]+)\/(0|[1-9]\d*)(\/.*)?$/);if(!a||!Fc.has(a[1]))return e;if(!this._validateExtensionReferencePreservation(e,a[1],n,o,s))return e;const l=a[1],u=parseInt(a[2],10),c=this._getRemappedRootIndex(l,u,t);return void 0===c?(Jc(n,{code:"REFERENCE_UNRESOLVED",graphIndex:o,nodeIndex:s,path:`/graphs/${o}${void 0===s?"":`/nodes/${s}`}`,message:`Reference "${e}" cannot be remapped because its ${l} target was not exported uniquely.`}),e):`/${l}/${c}${null!==(r=a[3])&&void 0!==r?r:""}`}_validateExtensionReferencePreservation(e,t,n,o,s,r=`/graphs/${o}${void 0===s?"":`/nodes/${s}`}`){const i=Nc(e).filter(e=>"KHR_interactivity"!==e);return!(0!==i.length&&!function(e,t){const n=e.split("/").map(e=>e.replace(/~1/g,"/").replace(/~0/g,"~")),o=n.indexOf("extensions");return o>1&&"nodes"===(null!=t?t:n[1])&&Ec.includes(n[o+1])}(e,t)&&(Jc(n,{code:"REFERENCE_UNRESOLVED",graphIndex:o,nodeIndex:s,path:r,message:`Reference "${e}" observes extension-backed data (${i.join(", ")}) that the serializer cannot guarantee will retain its source semantics.`}),1))}_collectAdditionalExtensions(){var e,t,n,o,s,r,i,a,l,u,c,d,h,p,f,m,g,_,v,y,b,x,T,A;const w=new Set,M=e=>{if("string"==typeof e)for(const t of Nc(e))"KHR_interactivity"!==t&&w.add(t)},S=e=>{if(Array.isArray(e))return void e.forEach(S);if(null===e||"object"!=typeof e)return;const t=e;for(const[e,n]of Object.entries(t))if("extras"!==e)if("extensions"!==e||null===n||"object"!=typeof n||Array.isArray(n))"extensions"!==e&&S(n);else for(const[e,t]of Object.entries(n))"KHR_interactivity"!==e&&w.add(e),S(t)};S(null===(e=this._options.document)||void 0===e?void 0:e.source);for(const e of this._graphAnalyses){S(e.source);for(const r of null!==(t=e.source.variables)&&void 0!==t?t:[])"ref"===(null===(o=null===(n=e.source.types)||void 0===n?void 0:n[r.type])||void 0===o?void 0:o.signature)&&(null===(s=r.value)||void 0===s||s.forEach(M));for(const t of null!==(r=e.source.events)&&void 0!==r?r:[])for(const n of Object.values(null!==(i=t.values)&&void 0!==i?i:{}))n&&"object"==typeof n&&"ref"===(null===(l=null===(a=e.source.types)||void 0===a?void 0:a[n.type])||void 0===l?void 0:l.signature)&&(null===(u=n.value)||void 0===u||u.forEach(M));for(const t of null!==(c=e.source.declarations)&&void 0!==c?c:[])t.extension&&w.add(t.extension);for(const t of null!==(d=e.source.nodes)&&void 0!==d?d:[]){for(const n of Object.values(null!==(h=t.values)&&void 0!==h?h:{}))n&&"object"==typeof n&&!("node"in n)&&"ref"===(null===(f=null===(p=e.source.types)||void 0===p?void 0:p[n.type])||void 0===f?void 0:f.signature)&&(null===(m=n.value)||void 0===m||m.forEach(M));const n=null===(g=e.source.declarations)||void 0===g?void 0:g[t.declaration],o=n?Ru(n,!1):void 0;for(const[e,n]of Object.entries(null!==(_=null==o?void 0:o.configuration)&&void 0!==_?_:{}))n.pointerTemplate&&(null===(b=null===(y=null===(v=t.configuration)||void 0===v?void 0:v[e])||void 0===y?void 0:y.value)||void 0===b||b.forEach(M))}}for(const e of null!==(T=null===(x=this._options.sourceGLTF)||void 0===x?void 0:x.nodes)&&void 0!==T?T:[])for(const t of Ec){const n=null===(A=e.extensions)||void 0===A?void 0:A[t];n&&(w.add(t),S(n))}return Array.from(w).sort()}_writeCompanionNodeExtensions(e,t){var n,o,s,r;for(let i=0;i<(null!==(s=null===(o=null===(n=this._options.sourceGLTF)||void 0===n?void 0:n.nodes)||void 0===o?void 0:o.length)&&void 0!==s?s:0);i++){const n=this._options.sourceGLTF.nodes[i];for(const o of Ec){const s=null===(r=n.extensions)||void 0===r?void 0:r[o];if(!s)continue;const a=n._babylonTransformNode?e.getNodeIndex(n._babylonTransformNode):void 0;void 0!==a?e.setNodeExtension(a,o,kc(s)):Jc(t,{code:"REFERENCE_UNRESOLVED",path:`/nodes/${i}/extensions/${o}`,message:`Companion extension "${o}" targets a node that was not exported.`})}}}_sortDiagnostics(e){return e.slice().sort((e,t)=>{var n,o,s,r;return(null!==(n=e.graphIndex)&&void 0!==n?n:-1)-(null!==(o=t.graphIndex)&&void 0!==o?o:-1)||(null!==(s=e.nodeIndex)&&void 0!==s?s:-1)-(null!==(r=t.nodeIndex)&&void 0!==r?r:-1)||e.path.localeCompare(t.path)||e.code.localeCompare(t.code)})}}function nd(e,t={}){return new td(e,t)}const od="KHR_interactivity",sd=new WeakMap;function rd(e){const t=sd.get(e);return null==t?void 0:t[t.length-1]}function id(e){var t;return null!==(t=sd.get(e))&&void 0!==t?t:[]}class ad{constructor(e){this._loader=e,this.name=od,this.order=200,this.enabled=this._loader.isExtensionUsed(od),e._skipStartAnimationStep=!0}_initializePathConverter(e){var n;this._gltfPathConverter=dr(this._loader.gltf,t=>ld(e,this._loader.parent.targetFps,t));const o=[{prefix:yc,converter:new bc(e,{transformNodes:{length:{type:"number",get:e=>e.length,getTarget:e=>e},__array__:{__target__:!0,name:{type:"string",get:e=>e.name,set:(e,t)=>{t.name=e},getTarget:e=>e},translation:{type:"Vector3",get:e=>e.position,set:(e,t)=>t.position.copyFrom(e),getTarget:e=>e},rotation:{type:"Quaternion",get:e=>{var n;return null!==(n=e.rotationQuaternion)&&void 0!==n?n:t.Quaternion.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z)},set:(e,t)=>{t.rotationQuaternion?t.rotationQuaternion.copyFrom(e):t.rotationQuaternion=e.clone()},getTarget:e=>e},scale:{type:"Vector3",get:e=>e.scaling,set:(e,t)=>t.scaling.copyFrom(e),getTarget:e=>e},matrix:{type:"Matrix",get:e=>e.computeWorldMatrix(!1),getTarget:e=>e,isReadOnly:!0},globalMatrix:{type:"Matrix",get:e=>e.computeWorldMatrix(!0),getTarget:e=>e,isReadOnly:!0}}},meshes:{length:{type:"number",get:e=>e.length,getTarget:e=>e},__array__:{__target__:!0,name:{type:"string",get:e=>e.name,set:(e,t)=>{t.name=e},getTarget:e=>e},visible:{type:"boolean",get:e=>e.isVisible,set:(e,t)=>{t.isVisible=e},getTarget:e=>e}}},materials:{length:{type:"number",get:e=>e.length,getTarget:e=>e},__array__:{__target__:!0,name:{type:"string",get:e=>e.name,set:(e,t)=>{t.name=e},getTarget:e=>e}}}})}],s=new Tc;o.push({prefix:dc,converter:s}),o.push({prefix:hc,converter:s});const r=new Set((null!==(n=this._loader.gltf.extensionsUsed)&&void 0!==n?n:[]).filter(e=>{var t;return zs.has(e)&&!1!==(null===(t=this._loader.parent.extensionOptions[e])||void 0===t?void 0:t.enabled)})),i=new Cc(this._loader.gltf,e=>r.has(e));o.push({prefix:"/extensions/KHR_interactivity/asset/",converter:i}),o.push({prefix:Ac,converter:i});const a=new vc(o,this._gltfPathConverter);return this._pathConverter=a,a}dispose(){this._loader=null,delete this._gltfPathConverter,delete this._pathConverter}onReady(){return b(this,void 0,void 0,function*(){var e,n,o,s,r,i,a,l;if(!this._loader.babylonScene)return;const u=this._loader.babylonScene,c=this._initializePathConverter(u),d=null===(e=this._loader.gltf.extensions)||void 0===e?void 0:e.KHR_interactivity;if(!d)return;const h=new Set((null!==(n=this._loader.gltf.extensionsUsed)&&void 0!==n?n:[]).filter(e=>{var t;return!1!==(null===(t=this._loader.parent.extensionOptions[e])||void 0===t?void 0:t.enabled)})),p=cc(d,h,null!==(s=null===(o=this._loader.gltf.nodes)||void 0===o?void 0:o.length)&&void 0!==s?s:0),f=this._loader.parent.extensionOptions[od],m=null===(r=null==f?void 0:f.autoStart)||void 0===r||r,g=null!==(i=null==f?void 0:f.parseOnly)&&void 0!==i&&i,_=null===(a=null==f?void 0:f.strictValidation)||void 0===a||a,v=null!==(l=sd.get(u))&&void 0!==l?l:[],y={assetIndex:v.length,document:p,graphs:[],pathConverter:c,glTF:this._loader.gltf,scene:u,hostResolver:new Ic};v.push(y),sd.set(u,v),yield Promise.all(p.graphs.map(e=>b(this,void 0,void 0,function*(){var n,o;const s={graph:e,diagnostics:e.diagnostics.slice()};if(y.graphs[e.index]=s,e.valid||!_)try{const n=new _c(_?e.effectiveSource:e.source,this._loader.gltf,this._loader.parent.targetFps,e.index,h,_?e.declarations:void 0,e.source).serializeToFlowGraph();if(s.serializedFlowGraph=n,g)return;const o=new t.FlowGraphCoordinator({scene:u,hostResolver:y.hostResolver});o.dispatchEventsSynchronously=!1,s.coordinator=o,s.flowGraph=yield t.ParseFlowGraphAsync(n,{coordinator:o,pathConverter:c}),gc(s.flowGraph),m&&e.index===p.defaultGraphIndex&&o.start()}catch(r){const i=null!==(n=null==r?void 0:r.message)&&void 0!==n?n:String(r);s.diagnostics.push({path:e.path,message:i,severity:"error"}),t.Logger.Error(`KHR_interactivity: rejecting behavior graph #${e.index}: ${i}`),null===(o=s.coordinator)||void 0===o||o.dispose(),delete s.coordinator,delete s.flowGraph,delete s.serializedFlowGraph}else t.Logger.Error(`KHR_interactivity: rejecting behavior graph #${e.index}: ${e.diagnostics.map(e=>e.message).join("; ")}`)})))})}}function ld(e,n,o){fr("/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},o),fr("/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},o);const s=n=>{const o=e.activeCamera;return o&&o.mode!==t.Constants.ORTHOGRAPHIC_CAMERA?n(o):NaN},r=n=>{const o=e.activeCamera;return o&&o.mode===t.Constants.ORTHOGRAPHIC_CAMERA?n(o):NaN};fr("/extensions/KHR_interactivity/?/activeCamera/perspective/aspectRatio",{get:()=>s(e=>e.getEngine().getAspectRatio(e)),type:"number",getTarget:()=>e.activeCamera},o),fr("/extensions/KHR_interactivity/?/activeCamera/perspective/yfov",{get:()=>s(e=>{if(e.fovMode===t.Constants.FOVMODE_VERTICAL_FIXED)return e.fov;const n=e.getEngine().getAspectRatio(e);return n?2*Math.atan(Math.tan(e.fov/2)/n):e.fov}),type:"number",getTarget:()=>e.activeCamera},o),fr("/extensions/KHR_interactivity/?/activeCamera/perspective/znear",{get:()=>s(e=>e.minZ),type:"number",getTarget:()=>e.activeCamera},o),fr("/extensions/KHR_interactivity/?/activeCamera/perspective/zfar",{get:()=>s(e=>0===e.maxZ?1/0:e.maxZ),type:"number",getTarget:()=>e.activeCamera},o),fr("/extensions/KHR_interactivity/?/activeCamera/orthographic/xmag",{get:()=>r(e=>{var t,n;const o=e.getEngine().getRenderWidth()/2;return((null!==(t=e.orthoRight)&&void 0!==t?t:o)-(null!==(n=e.orthoLeft)&&void 0!==n?n:-o))/2}),type:"number",getTarget:()=>e.activeCamera},o),fr("/extensions/KHR_interactivity/?/activeCamera/orthographic/ymag",{get:()=>r(e=>{var t,n;const o=e.getEngine().getRenderHeight()/2;return((null!==(t=e.orthoTop)&&void 0!==t?t:o)-(null!==(n=e.orthoBottom)&&void 0!==n?n:-o))/2}),type:"number",getTarget:()=>e.activeCamera},o),fr("/extensions/KHR_interactivity/?/activeCamera/orthographic/znear",{get:()=>r(e=>e.minZ),type:"number",getTarget:()=>e.activeCamera},o),fr("/extensions/KHR_interactivity/?/activeCamera/orthographic/zfar",{get:()=>r(e=>e.maxZ),type:"number",getTarget:()=>e.activeCamera},o);const i=e=>{var t,o,s,r;return null!==(r=null===(s=null===(o=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.targetedAnimations)||void 0===o?void 0:o[0])||void 0===s?void 0:s.animation.framePerSecond)&&void 0!==r?r:n};fr("/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},o),fr("/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)/i(e)},type:"number",getTarget:e=>e._babylonAnimationGroup},o),fr("/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)/i(e)},type:"number",getTarget:e=>e._babylonAnimationGroup},o),fr("/animations/{}/extensions/KHR_interactivity/playhead",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.getRetainedCurrentFrame())&&void 0!==n?n:0)/i(e)},type:"number",getTarget:e=>e._babylonAnimationGroup},o),fr("/animations/{}/extensions/KHR_interactivity/virtualPlayhead",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.getVirtualCurrentFrame())&&void 0!==n?n:0)/i(e)},type:"number",getTarget:e=>e._babylonAnimationGroup},o)}let ud=!1;function cd(){ud||(ud=!0,t.addToBlockFactory(od,"FlowGraphGLTFDataProvider",()=>b(this,void 0,void 0,function*(){return(yield Promise.resolve().then(function(){return eh})).FlowGraphGLTFDataProvider})),t.addToBlockFactory(od,"FlowGraphUnsupportedInteractivityBlock",()=>b(this,void 0,void 0,function*(){return(yield Promise.resolve().then(function(){return lh})).FlowGraphUnsupportedInteractivityBlock})),t.addToBlockFactory(od,"FlowGraphObjectReferenceBlock",()=>b(this,void 0,void 0,function*(){return(yield Promise.resolve().then(function(){return oh})).FlowGraphObjectReferenceBlock})),t.addToBlockFactory(od,"FlowGraphEventReferenceBlock",()=>b(this,void 0,void 0,function*(){return(yield Promise.resolve().then(function(){return rh})).FlowGraphEventReferenceBlock})))}let dd=!1;function hd(){dd||(dd=!0,cd(),Ys(od),Xs(od,!0,e=>new ad(e)))}var pd={__proto__:null,CreateKHRInteractivityExportPlan:nd,GetKHRInteractivityImportResult:rd,GetKHRInteractivityImportResults:id,KHRInteractivityExportError:Oc,KHRInteractivityExportPlan:td,KHR_interactivity:ad,RegisterKHR_interactivity:hd,_AddInteractivityObjectModel:ld,_CaptureKHRInteractivityRuntimeInputDefaults:gc,_RegisterKHRInteractivityRuntime:cd};hd();const fd="KHR_node_visibility";class md{constructor(e){this.name=fd,this._loader=e,this.enabled=e.isExtensionUsed(fd)}onReady(){var e;if(!this._loader)return;const t=this._loader.gltf.nodes;if(t)for(const n of t){const t=n._babylonTransformNode;t&&(t.inheritVisibility=!0,n.extensions&&n.extensions.KHR_node_visibility&&!1===n.extensions.KHR_node_visibility.visible&&(t.isVisible=!1,null===(e=n._primitiveBabylonMeshes)||void 0===e||e.forEach(e=>{e.inheritVisibility=!0,e.isVisible=!1})))}}dispose(){delete this._loader}}let gd=!1;function _d(){gd||(gd=!0,fr("/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"}))}let vd=!1;function yd(){vd||(vd=!0,_d(),Ys(fd),Xs(fd,!0,e=>new md(e)))}var bd={__proto__:null,KHR_node_visibility:md,RegisterKHR_node_visibility:yd,_RegisterKHRNodeVisibilityRuntime:_d};yd();const xd=new WeakMap,Td=new WeakMap,Ad=new WeakMap;function wd(e){return"selectable"===e?Ad:Td}function Md(e,t){var n;return null===(n=wd(t).get(e))||void 0===n||n}function Sd(e,t,n){"selectable"===t?e.isPickable=n:e._isPointerMovePickable=n}function Rd(e,t){var n;const o=function(e,t){let n=e;for(;n;){if(!Md(n,t))return!1;n=n.parent}return!0}(e,t),s=null!==(n=e._primitiveBabylonMeshes)&&void 0!==n?n:[];for(const e of s)Sd(e,t,o);const r=e._babylonTransformNode;r&&"isPickable"in r&&Sd(r,t,o)}function Cd(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parent}return!1}function Id(e,t,n){var o;const s=wd(t);for(const t of e)xd.set(t,e),s.set(t,null===(o=n(t))||void 0===o||o);for(const n of e)Rd(n,t)}function Od(e,t){return Md(e,t)}function Fd(e,t,n){var o;wd(t).set(e,n);const s=null!==(o=xd.get(e))&&void 0!==o?o:[e];for(const n of s)Cd(n,e)&&Rd(n,t)}const Ed="KHR_node_selectability";class Nd{constructor(e){this.name=Ed,this.order=100,this._loader=e,this.enabled=e.isExtensionUsed(Ed)}onReady(){return b(this,void 0,void 0,function*(){var e;Id(null!==(e=this._loader.gltf.nodes)&&void 0!==e?e:[],"selectable",e=>{var t,n;return null===(n=null===(t=e.extensions)||void 0===t?void 0:t.KHR_node_selectability)||void 0===n?void 0:n.selectable})})}dispose(){this._loader=null}}let Ld=!1;function kd(){Ld||(Ld=!0,Iu("event/onSelect",Ed,{blocks:["FlowGraphMeshPickEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider","KHR_interactivity/FlowGraphEventReferenceBlock"],declarationSchema:{inputValueSockets:{},outputValueSockets:{selectedNode:"ref",selectionRayOrigin:"float3",selectionPoint:"float3",controllerIndex:"int",event:"ref"}},configuration:{nodeIndex:{name:"variable",configurationType:"int",toBlock:"FlowGraphGetVariableBlock",indexSource:"assetNodes",invalidUsesDefault:!0,dataTransformer:e=>"pickedMesh_"+e}},outputs:{values:{selectedNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},selectedNode:{name:"nodeReference",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},controllerIndex:{name:"controllerIndex",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},selectionPoint:{name:"selectionPoint",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},selectionRayOrigin:{name:"selectionRayOrigin",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},event:{name:"value",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"}},flows:{out:{name:"out",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"}}},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},{input:"node",output:"pickedMesh",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"controllerIndexInput",output:"pointerId",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"selectionPointInput",output:"pickedPoint",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"selectionRayOriginInput",output:"pickOrigin",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"in",output:"done",inputBlockIndex:4,outputBlockIndex:0}],extraProcessor(e,t,n,o,s,r,i){var a,l,u,c,d,h,p,f,m;const g=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],_="number"==typeof g&&Number.isInteger(g)&&g>=0&&g<(null!==(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c.length)&&void 0!==d?d:0),v=_?"pickedMesh_"+g:"pickedMesh_unbound";s[1].config.variable=v,r._userVariables[v]=_?{className:"Mesh",id:null===(p=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[g]._babylonTransformNode)||void 0===p?void 0:p.id,uniqueId:null===(m=null===(f=null==i?void 0:i.nodes)||void 0===f?void 0:f[g]._babylonTransformNode)||void 0===m?void 0:m.uniqueId}:{type:"any",value:[{}]};const y=`${Ed}:event/onSelect:${g}`;return s[0].config.eventKey=y,s[0].config.useNaNDefaults=!0,s[0].config.pointerIdDefault=-1,s[4].config.eventKey=y,s}}),fr("/nodes/{}/extensions/KHR_node_selectability/selectable",{get:e=>Od(e,"selectable"),set:(e,t)=>{Fd(t,"selectable",e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"isPickable"],type:"boolean"}))}let Pd=!1;function Bd(){Pd||(Pd=!0,kd(),Ys(Ed),Xs(Ed,!0,e=>new Nd(e)))}var Dd={__proto__:null,KHR_node_selectability:Nd,RegisterKHR_node_selectability:Bd,_RegisterKHRNodeSelectabilityRuntime:kd};Bd();const Vd="KHR_node_hoverability",Gd="targetMeshPointerOver_",$d="targetMeshPointerOut_";class Ud{constructor(e){this.name=Vd,this.order=100,this._loader=e,this.enabled=e.isExtensionUsed(Vd)}onReady(){return b(this,void 0,void 0,function*(){var e;Id(null!==(e=this._loader.gltf.nodes)&&void 0!==e?e:[],"hoverable",e=>{var t,n;return null===(n=null===(t=e.extensions)||void 0===t?void 0:t.KHR_node_hoverability)||void 0===n?void 0:n.hoverable})})}dispose(){this._loader=null}}let Hd=!1;function Kd(){Hd||(Hd=!0,Iu("event/onHoverIn",Vd,{blocks:["FlowGraphPointerOverEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider","KHR_interactivity/FlowGraphEventReferenceBlock"],declarationSchema:{inputValueSockets:{},outputValueSockets:{hoveredNode:"ref",controllerIndex:"int",event:"ref"}},configuration:{nodeIndex:{name:"variable",configurationType:"int",toBlock:"FlowGraphGetVariableBlock",indexSource:"assetNodes",invalidUsesDefault:!0,dataTransformer:e=>Gd+e}},outputs:{values:{hoverNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},hoveredNode:{name:"nodeReference",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},controllerIndex:{name:"controllerIndex",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},event:{name:"value",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"}},flows:{out:{name:"out",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"}}},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},{input:"node",output:"meshUnderPointer",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"controllerIndexInput",output:"pointerId",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"in",output:"done",inputBlockIndex:4,outputBlockIndex:0}],extraProcessor(e,t,n,o,s,r,i){var a,l,u,c,d,h,p,f,m;const g=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],_="number"==typeof g&&Number.isInteger(g)&&g>=0&&g<(null!==(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c.length)&&void 0!==d?d:0),v=_?Gd+g:Gd+"unbound";s[1].config.variable=v,r._userVariables[v]=_?{className:"Mesh",id:null===(p=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[g]._babylonTransformNode)||void 0===p?void 0:p.id,uniqueId:null===(m=null===(f=null==i?void 0:i.nodes)||void 0===f?void 0:f[g]._babylonTransformNode)||void 0===m?void 0:m.uniqueId}:{type:"any",value:[{}]};const y=`${Vd}:event/onHoverIn:${g}`;return s[0].config.eventKey=y,s[4].config.eventKey=y,s}}),Iu("event/onHoverOut",Vd,{blocks:["FlowGraphPointerOutEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider","KHR_interactivity/FlowGraphEventReferenceBlock"],declarationSchema:{inputValueSockets:{},outputValueSockets:{hoveredNode:"ref",controllerIndex:"int",event:"ref"}},configuration:{nodeIndex:{name:"variable",configurationType:"int",toBlock:"FlowGraphGetVariableBlock",indexSource:"assetNodes",invalidUsesDefault:!0,dataTransformer:e=>$d+e}},outputs:{values:{hoverNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},hoveredNode:{name:"nodeReference",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},controllerIndex:{name:"controllerIndex",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},event:{name:"value",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"}},flows:{out:{name:"out",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"}}},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},{input:"node",output:"meshOutOfPointer",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"controllerIndexInput",output:"pointerId",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"in",output:"done",inputBlockIndex:4,outputBlockIndex:0}],extraProcessor(e,t,n,o,s,r,i){var a,l,u,c,d,h,p,f,m;const g=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],_="number"==typeof g&&Number.isInteger(g)&&g>=0&&g<(null!==(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c.length)&&void 0!==d?d:0),v=_?$d+g:$d+"unbound";s[1].config.variable=v,r._userVariables[v]=_?{className:"Mesh",id:null===(p=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[g]._babylonTransformNode)||void 0===p?void 0:p.id,uniqueId:null===(m=null===(f=null==i?void 0:i.nodes)||void 0===f?void 0:f[g]._babylonTransformNode)||void 0===m?void 0:m.uniqueId}:{type:"any",value:[{}]};const y=`${Vd}:event/onHoverOut:${g}`;return s[0].config.eventKey=y,s[4].config.eventKey=y,s}}),fr("/nodes/{}/extensions/KHR_node_hoverability/hoverable",{get:e=>Od(e,"hoverable"),set:(e,t)=>{Fd(t,"hoverable",e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"pointerOverDisableMeshTesting"],type:"boolean"}))}let jd=!1;function Wd(){jd||(jd=!0,Kd(),Ys(Vd),Xs(Vd,!0,e=>new Ud(e)))}var qd={__proto__:null,KHR_node_hoverability:Ud,RegisterKHR_node_hoverability:Wd,_RegisterKHRNodeHoverabilityRuntime:Kd};Wd();const zd="ExtrasAsMetadata";class Xd{_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=zd,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))}}let Yd=!1;function Qd(){Yd||(Yd=!0,Ys(zd),Xs(zd,!1,e=>new Xd(e)))}var Zd={__proto__:null,ExtrasAsMetadata:Xd,RegisterExtrasAsMetadata:Qd};Qd();class Jd 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 eh={__proto__:null,FlowGraphGLTFDataProvider:Jd};function th(e,t){let n=t;for(;n;){const t=e.getObjectReference(n,"nodes");if(null==t?void 0:t.startsWith("/nodes/"))return t;n=n.parent}return""}class nh extends t.FlowGraphBlock{constructor(e){super(e),this.object=this.registerDataInput("object",t.RichTypeAny),this.value=this.registerDataOutput("value",t.RichTypeString,"")}_updateOutputs(e){this.value.setValue(th(e,this.object.getValue(e)),e)}getClassName(){return"FlowGraphObjectReferenceBlock"}}var oh={__proto__:null,FlowGraphObjectReferenceBlock:nh,GetInteractivityObjectReference:th};class sh extends t.FlowGraphExecutionBlock{constructor(e){super(e),this.config=e,this._assetInverse=t.Matrix.Identity(),this._selectionPointValue=t.Vector3.Zero(),this._selectionRayOriginValue=t.Vector3.Zero();const n=new t.Vector3(NaN,NaN,NaN);this.node=this.registerDataInput("node",t.RichTypeAny),this.controllerIndexInput=this.registerDataInput("controllerIndexInput",t.RichTypeNumber,-1),this.selectionPointInput=this.registerDataInput("selectionPointInput",t.RichTypeVector3,n),this.selectionRayOriginInput=this.registerDataInput("selectionRayOriginInput",t.RichTypeVector3,n),this.nodeReference=this.registerDataOutput("nodeReference",t.RichTypeString,""),this.controllerIndex=this.registerDataOutput("controllerIndex",t.RichTypeNumber,-1),this.selectionPoint=this.registerDataOutput("selectionPoint",t.RichTypeVector3,n),this.selectionRayOrigin=this.registerDataOutput("selectionRayOrigin",t.RichTypeVector3,n),this.value=this.registerDataOutput("value",t.RichTypeString,""),this.out=this._registerSignalOutput("out")}_execute(e){var n;this.nodeReference.setValue(th(e,this.node.getValue(e)),e);const o=this.controllerIndexInput.getValue(e);if(o<0)this.controllerIndex.setValue(-1,e);else{const t=e._getGlobalContextVariable("khrInteractivityControllerIndices",new Map);let n=t.get(o);void 0===n&&(n=t.size,t.set(o,n),e._setGlobalContextVariable("khrInteractivityControllerIndices",t)),this.controllerIndex.setValue(n,e)}const s=this.node.getValue(e);let r=null==s?void 0:s.parent;for(;null==r?void 0:r.parent;)r=r.parent;(null==r?void 0:r.getWorldMatrix)?(r.getWorldMatrix().invertToRef(this._assetInverse),t.Vector3.TransformCoordinatesToRef(this.selectionPointInput.getValue(e),this._assetInverse,this._selectionPointValue),t.Vector3.TransformCoordinatesToRef(this.selectionRayOriginInput.getValue(e),this._assetInverse,this._selectionRayOriginValue),this.selectionPoint.setValue(this._selectionPointValue,e),this.selectionRayOrigin.setValue(this._selectionRayOriginValue,e)):(this.selectionPoint.setValue(this.selectionPointInput.getValue(e),e),this.selectionRayOrigin.setValue(this.selectionRayOriginInput.getValue(e),e)),this.value.setValue(e.getEventReference(null!==(n=this.config.eventKey)&&void 0!==n?n:"gltf:manual"),e),this.out._activateSignal(e)}getClassName(){return"FlowGraphEventReferenceBlock"}}var rh={__proto__:null,FlowGraphEventReferenceBlock:sh};function ih(e){switch(e){case"bool":return!1;case"int":return new t.FlowGraphInteger(0);case"float":return NaN;case"float2":return new t.Vector2(NaN,NaN);case"float3":return new t.Vector3(NaN,NaN,NaN);case"float4":return new t.Vector4(NaN,NaN,NaN,NaN);case"float2x2":return new t.FlowGraphMatrix2D([NaN,NaN,NaN,NaN]);case"float3x3":return new t.FlowGraphMatrix3D([NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN]);case"float4x4":return t.Matrix.FromArray([NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN]);case"ref":return"";default:return}}class ah extends t.FlowGraphExecutionBlock{constructor(e){var n,o,s,r;super(e),this.config=e,this._unregisterSignalInput("in"),this._unregisterSignalOutput("error");for(const o of null!==(n=e.inputValueSockets)&&void 0!==n?n:[])this.registerDataInput(o.name,t.getRichTypeByFlowGraphType(o.type));for(const n of null!==(o=e.outputValueSockets)&&void 0!==o?o:[])this.registerDataOutput(n.name,t.getRichTypeByFlowGraphType(n.type),ih(n.signature));for(const t of null!==(s=e.inputFlowSockets)&&void 0!==s?s:[])this._registerSignalInput(t);for(const t of null!==(r=e.outputFlowSockets)&&void 0!==r?r:[])this._registerSignalOutput(t)}_execute(e,t){}getClassName(){return"FlowGraphUnsupportedInteractivityBlock"}}var lh={__proto__:null,FlowGraphUnsupportedInteractivityBlock:ah},uh={__proto__:null,AddObjectAccessorToKey:fr,CloneKHRInteractivityGraph:Wu,CreateEffectiveKHRInteractivityGraph:oc,CreateKHRInteractivityDocument:cc,CreateKHRInteractivityExportPlan:nd,CreateKHRInteractivityGraphModel:uc,EXT_lights_area:Fi,EXT_lights_ies:li,EXT_lights_image_based:Br,EXT_mesh_gpu_instancing:Ur,EXT_meshopt_compression:qr,EXT_texture_avif:oi,EXT_texture_webp:Zr,ExtrasAsMetadata:Xd,FlowGraphEventReferenceBlock:sh,FlowGraphGLTFDataProvider:Jd,FlowGraphObjectReferenceBlock:nh,FlowGraphUnsupportedInteractivityBlock:ah,GetInteractivityNodeState:Od,GetInteractivityObjectReference:th,GetInteractivityOperationRegistry:Fu,GetKHRInteractivityImportResult:rd,GetKHRInteractivityImportResults:id,GetMappingForKey:hr,GetPathToObjectConverter:dr,HasDefaultInteractivityFlowInput:Mu,InitializeInteractivityNodeState:Id,InteractivityGraphToFlowGraphParser:_c,KHRInteractivityExportError:Oc,KHRInteractivityExportPlan:td,KHR_INTERACTIVITY_SPECIFICATION_COMMIT:Gu,KHR_animation_pointer:Gl,KHR_draco_mesh_compression:pi,KHR_gaussian_splatting:xi,KHR_interactivity:ad,KHR_lights:Si,KHR_materials_anisotropy:aa,KHR_materials_clearcoat:Wi,KHR_materials_coat:Qi,KHR_materials_diffuse_roughness:ml,KHR_materials_diffuse_transmission:Xa,KHR_materials_dispersion:cl,KHR_materials_emissive_strength:ha,KHR_materials_fuzz:Ta,KHR_materials_ior:Ea,KHR_materials_iridescence:na,KHR_materials_pbrSpecularGlossiness:Pi,KHR_materials_sheen:_a,KHR_materials_specular:Ra,KHR_materials_transmission:Ka,KHR_materials_unlit:$i,KHR_materials_variants:Ba,KHR_materials_volume:el,KHR_materials_volume_scatter:rl,KHR_mesh_quantization:bl,KHR_node_hoverability:Ud,KHR_node_selectability:Nd,KHR_node_visibility:md,KHR_texture_basisu:Ml,KHR_texture_transform:Ol,KHR_xmp_json_ld:kl,MSFT_audio_emitter:ru,MSFT_lod:cu,MSFT_minecraftMesh:mu,MSFT_sRGBFactors:bu,NormalizeInteractivityEventDataConfiguration:Su,ParseDebugLogTemplate:Bu,RegisterEXT_lights_area:Ni,RegisterEXT_lights_ies:ci,RegisterEXT_lights_image_based:Vr,RegisterEXT_mesh_gpu_instancing:Kr,RegisterEXT_meshopt_compression:Xr,RegisterEXT_texture_avif:ri,RegisterEXT_texture_webp:ei,RegisterExtrasAsMetadata:Qd,RegisterKHR_animation_pointer:Ul,RegisterKHR_draco_mesh_compression:mi,RegisterKHR_gaussian_splatting:Ai,RegisterKHR_interactivity:hd,RegisterKHR_lights:Ci,RegisterKHR_materials_anisotropy:ua,RegisterKHR_materials_clearcoat:zi,RegisterKHR_materials_coat:Ji,RegisterKHR_materials_diffuse_roughness:_l,RegisterKHR_materials_diffuse_transmission:Qa,RegisterKHR_materials_dispersion:hl,RegisterKHR_materials_emissive_strength:fa,RegisterKHR_materials_fuzz:wa,RegisterKHR_materials_ior:La,RegisterKHR_materials_iridescence:sa,RegisterKHR_materials_pbrSpecularGlossiness:Di,RegisterKHR_materials_sheen:ya,RegisterKHR_materials_specular:Ia,RegisterKHR_materials_transmission:Wa,RegisterKHR_materials_unlit:Hi,RegisterKHR_materials_variants:Va,RegisterKHR_materials_volume:nl,RegisterKHR_materials_volume_scatter:al,RegisterKHR_mesh_quantization:Tl,RegisterKHR_node_hoverability:Wd,RegisterKHR_node_selectability:Bd,RegisterKHR_node_visibility:yd,RegisterKHR_texture_basisu:Rl,RegisterKHR_texture_transform:El,RegisterKHR_xmp_json_ld:Bl,RegisterMSFT_audio_emitter:au,RegisterMSFT_lod:hu,RegisterMSFT_minecraftMesh:_u,RegisterMSFT_sRGBFactors:Tu,SetInteractivityNodeState:Fd,SetInterpolationForKey:pr,TransmissionHelper:$a,_AddInteractivityObjectModel:ld,_CaptureKHRInteractivityRuntimeInputDefaults:gc,_CreateKHRInteractivityRuntimeValueSnapshot:Ku,_NormalizeKHRInteractivityRuntimeValue:Uu,_RegisterKHRInteractivityRuntime:cd,_RegisterKHRNodeHoverabilityRuntime:Kd,_RegisterKHRNodeSelectabilityRuntime:kd,_RegisterKHRNodeVisibilityRuntime:_d,addNewInteractivityFlowGraphMapping:Iu,ensureTransmissionHelper:Ua,getAllSupportedNativeNodeTypes:Vu,getMappingForDeclaration:Ru,getMappingForFullOperationName:wu,getNoOpMappingForDeclaration:Cu,gltfTypeToBabylonType:$u},ch={__proto__:null,AddObjectAccessorToKey:fr,AnimationPropertyInfo:Sr,ArrayItem:_r,CloneKHRInteractivityGraph:Wu,CreateEffectiveKHRInteractivityGraph:oc,CreateKHRInteractivityDocument:cc,CreateKHRInteractivityExportPlan:nd,CreateKHRInteractivityGraphModel:uc,EXT_lights_area:Fi,EXT_lights_ies:li,EXT_lights_image_based:Br,EXT_mesh_gpu_instancing:Ur,EXT_meshopt_compression:qr,EXT_texture_avif:oi,EXT_texture_webp:Zr,ExtrasAsMetadata:Xd,FlowGraphEventReferenceBlock:sh,FlowGraphGLTFDataProvider:Jd,FlowGraphObjectReferenceBlock:nh,FlowGraphUnsupportedInteractivityBlock:ah,GLTFFileLoader:ts,GLTFLoader:yr,GetInteractivityNodeState:Od,GetInteractivityObjectReference:th,GetInteractivityOperationRegistry:Fu,GetKHRInteractivityImportResult:rd,GetKHRInteractivityImportResults:id,GetMappingForKey:hr,GetPathToObjectConverter:dr,HasDefaultInteractivityFlowInput:Mu,InitializeInteractivityNodeState:Id,InteractivityGraphToFlowGraphParser:_c,KHRInteractivityExportError:Oc,KHRInteractivityExportPlan:td,KHR_INTERACTIVITY_SPECIFICATION_COMMIT:Gu,KHR_animation_pointer:Gl,KHR_draco_mesh_compression:pi,KHR_gaussian_splatting:xi,KHR_interactivity:ad,KHR_lights:Si,KHR_materials_anisotropy:aa,KHR_materials_clearcoat:Wi,KHR_materials_coat:Qi,KHR_materials_diffuse_roughness:ml,KHR_materials_diffuse_transmission:Xa,KHR_materials_dispersion:cl,KHR_materials_emissive_strength:ha,KHR_materials_fuzz:Ta,KHR_materials_ior:Ea,KHR_materials_iridescence:na,KHR_materials_pbrSpecularGlossiness:Pi,KHR_materials_sheen:_a,KHR_materials_specular:Ra,KHR_materials_transmission:Ka,KHR_materials_unlit:$i,KHR_materials_variants:Ba,KHR_materials_volume:el,KHR_materials_volume_scatter:rl,KHR_mesh_quantization:bl,KHR_node_hoverability:Ud,KHR_node_selectability:Nd,KHR_node_visibility:md,KHR_texture_basisu:Ml,KHR_texture_transform:Ol,KHR_xmp_json_ld:kl,LoadBoundingInfoFromPositionAccessor:vr,MSFT_audio_emitter:ru,MSFT_lod:cu,MSFT_minecraftMesh:mu,MSFT_sRGBFactors:bu,NormalizeInteractivityEventDataConfiguration:Su,OpenPBRMaterialLoadingAdapter:Er,PBRMaterialLoadingAdapter:Lr,ParseDebugLogTemplate:Bu,RegisterEXT_lights_area:Ni,RegisterEXT_lights_ies:ci,RegisterEXT_lights_image_based:Vr,RegisterEXT_mesh_gpu_instancing:Kr,RegisterEXT_meshopt_compression:Xr,RegisterEXT_texture_avif:ri,RegisterEXT_texture_webp:ei,RegisterExtrasAsMetadata:Qd,RegisterGLTF2Loader:xr,RegisterGLTFLoaderAnimation:Or,RegisterKHR_animation_pointer:Ul,RegisterKHR_draco_mesh_compression:mi,RegisterKHR_gaussian_splatting:Ai,RegisterKHR_interactivity:hd,RegisterKHR_lights:Ci,RegisterKHR_materials_anisotropy:ua,RegisterKHR_materials_clearcoat:zi,RegisterKHR_materials_coat:Ji,RegisterKHR_materials_diffuse_roughness:_l,RegisterKHR_materials_diffuse_transmission:Qa,RegisterKHR_materials_dispersion:hl,RegisterKHR_materials_emissive_strength:fa,RegisterKHR_materials_fuzz:wa,RegisterKHR_materials_ior:La,RegisterKHR_materials_iridescence:sa,RegisterKHR_materials_pbrSpecularGlossiness:Di,RegisterKHR_materials_sheen:ya,RegisterKHR_materials_specular:Ia,RegisterKHR_materials_transmission:Wa,RegisterKHR_materials_unlit:Hi,RegisterKHR_materials_variants:Va,RegisterKHR_materials_volume:nl,RegisterKHR_materials_volume_scatter:al,RegisterKHR_mesh_quantization:Tl,RegisterKHR_node_hoverability:Wd,RegisterKHR_node_selectability:Bd,RegisterKHR_node_visibility:yd,RegisterKHR_texture_basisu:Rl,RegisterKHR_texture_transform:El,RegisterKHR_xmp_json_ld:Bl,RegisterMSFT_audio_emitter:au,RegisterMSFT_lod:hu,RegisterMSFT_minecraftMesh:_u,RegisterMSFT_sRGBFactors:Tu,SetInteractivityNodeState:Fd,SetInterpolationForKey:pr,TransformNodeAnimationPropertyInfo:Rr,TransmissionHelper:$a,WeightAnimationPropertyInfo:Cr,_AddInteractivityObjectModel:ld,_CaptureKHRInteractivityRuntimeInputDefaults:gc,_CreateKHRInteractivityRuntimeValueSnapshot:Ku,_NormalizeKHRInteractivityRuntimeValue:Uu,_RegisterKHRInteractivityRuntime:cd,_RegisterKHRNodeHoverabilityRuntime:Kd,_RegisterKHRNodeSelectabilityRuntime:kd,_RegisterKHRNodeVisibilityRuntime:_d,addNewInteractivityFlowGraphMapping:Iu,ensureTransmissionHelper:Ua,getAllSupportedNativeNodeTypes:Vu,getMappingForDeclaration:Ru,getMappingForFullOperationName:wu,getNoOpMappingForDeclaration:Cu,getQuaternion:wr,getVector3:Ar,getWeights:Mr,gltfTypeToBabylonType:$u,registerGLTFExtension:Xs,registeredGLTFExtensions:zs,unregisterGLTFExtension:Ys};class dh{constructor(){this.materials=[]}parseMTL(e,n,o,s,r=dh.INVERT_TEXTURE_Y,i,a=!1){const l=a?[]:null;if(n instanceof ArrayBuffer)return null!=l?l:[];const u=n.split("\n"),c=/\s+/;let d,h=null;for(let n=0;n<u.length;n++){const a=u[n].trim();if(0===a.length||"#"===a.charAt(0))continue;const p=a.indexOf(" ");let f=p>=0?a.substring(0,p):a;f=f.toLowerCase();const m=p>=0?a.substring(p+1).trim():"";if("newmtl"===f){if(h&&this.materials.push(h),i&&!i.has(m)){h=null;continue}const n=e._blockEntityCollection;e._blockEntityCollection=!!s;try{h=new t.StandardMaterial(m,e),h._parentContainer=s,null==s||s.materials.push(h)}finally{e._blockEntityCollection=n}}else if("kd"===f&&h)d=m.split(c,3).map(parseFloat),h.diffuseColor=t.Color3.FromArray(d);else if("ka"===f&&h)d=m.split(c,3).map(parseFloat),h.ambientColor=t.Color3.FromArray(d);else if("ks"===f&&h)d=m.split(c,3).map(parseFloat),h.specularColor=t.Color3.FromArray(d);else if("ke"===f&&h)d=m.split(c,3).map(parseFloat),h.emissiveColor=t.Color3.FromArray(d);else if("ns"===f&&h)h.specularPower=parseFloat(m);else if("d"===f&&h)h.alpha=parseFloat(m);else if("map_ka"===f&&h)h.ambientTexture=dh._GetTexture(o,m,e,s,r,l);else if("map_kd"===f&&h)h.diffuseTexture=dh._GetTexture(o,m,e,s,r,l);else if("map_ks"===f&&h)h.specularTexture=dh._GetTexture(o,m,e,s,r,l);else if("map_ns"===f);else if("map_bump"===f&&h){const t=m.split(c),n=t.indexOf("-bm");let i=null;n>=0&&(i=t[n+1],t.splice(n,2)),h.bumpTexture=dh._GetTexture(o,t.join(" "),e,s,r,l),h.bumpTexture&&null!==i&&(h.bumpTexture.level=parseFloat(i))}else"map_d"===f&&h&&(h.opacityTexture=dh._GetTexture(o,m,e,s,r,l))}return h&&this.materials.push(h),null!=l?l:[]}static _GetTexture(e,n,o,s,r,i){if(!n)return null;let a=e;if("file:"===e){let e=n.lastIndexOf("\\");-1===e&&(e=n.lastIndexOf("/")),a+=e>-1?n.substring(e+1):n}else a+=n;const l=i?new t.Deferred:null;let u;l&&(l.promise.catch(()=>{}),i.push(l.promise));const c=()=>{const e=null==u?void 0:u.getInternalTexture();if(!e)return;const t=o.getEngine().getLoadedTexturesCache(),n=t.indexOf(e);-1!==n&&t.splice(n,1)},d=o._blockEntityCollection;o._blockEntityCollection=!!s;try{u=new t.Texture(a,o,{invertY:r,onLoad:null==l?void 0:l.resolve,onError:(e,t)=>{u?c():queueMicrotask(c),l&&l.reject(new Error(`${a}: ${(null==t?void 0:t.message)||e||"Failed to load texture"}`))}}),u._parentContainer=s,null==s||s.textures.push(u)}finally{o._blockEntityCollection=d}return l&&u.delayLoadState===t.Constants.DELAYLOADSTATE_NOTLOADED&&u.delayLoad(),u}}dh.INVERT_TEXTURE_Y=!0;class hh{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 p=[];h.push(p);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((hh._IsGroupElement(t)||hh._IsObjectElement(t))&&(p=[],h.push(p)),hh._IsLineElement(t)){const e=t.split(" ");for(let t=1;t<e.length-1;t++)p.push(`l ${e[t]} ${e[t+1]}`)}else p.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(hh.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=hh.NormalPattern.exec(n)))this._normals.push(new t.Vector3(parseFloat(o[1]),parseFloat(o[2]),parseFloat(o[3])));else if(null!==(o=hh.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=hh.FacePattern3.exec(n)))this._setDataForCurrentFaceWithPattern3(o[1].trim().split(" "),1);else if(null!==(o=hh.FacePattern4.exec(n)))this._setDataForCurrentFaceWithPattern4(o[1].trim().split(" "),1);else if(null!==(o=hh.FacePattern5.exec(n)))this._setDataForCurrentFaceWithPattern5(o[1].trim().split(" "),1);else if(null!==(o=hh.FacePattern2.exec(n)))this._setDataForCurrentFaceWithPattern2(o[1].trim().split(" "),1);else if(null!==(o=hh.FacePattern1.exec(n)))this._setDataForCurrentFaceWithPattern1(o[1].trim().split(" "),1);else if(null!==(o=hh.LinePattern1.exec(n)))this._setDataForCurrentFaceWithPattern1(o[1].trim().split(" "),0),this._hasLineData=!0;else if(null!==(o=hh.LinePattern2.exec(n)))this._setDataForCurrentFaceWithPattern2(o[1].trim().split(" "),0),this._hasLineData=!0;else if(o=hh._GetZbrushMRGB(n,!this._loadingOptions.importVertexColors))for(const e of o)this._extColors.push(e);else if(null!==(o=hh.LinePattern3.exec(n)))this._setDataForCurrentFaceWithPattern3(o[1].trim().split(" "),0),this._hasLineData=!0;else if(hh.GroupDescriptor.test(n)||hh.ObjectDescriptor.test(n)){const e={name:n.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:hh.ObjectDescriptor.test(n)};this._addPreviousObjMesh(),this._meshesFromObj.push(e),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(hh.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 hh.MtlLibGroupDescriptor.test(n)?r(n.substring(7).trim()):hh.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);if(!this._materialNameFromObj){const n=o._blockEntityCollection;o._blockEntityCollection=!!s;try{e=new t.StandardMaterial(t.Geometry.RandomId(),o),e._parentContainer=s,null==s||s.materials.push(e)}finally{o._blockEntityCollection=n}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];const r=o._blockEntityCollection;let d;o._blockEntityCollection=!!s;try{d=new t.Mesh(this._meshesFromObj[n].name,o),d._parentContainer=s,null==s||s.meshes.push(d)}finally{o._blockEntityCollection=r}if(this._handledMesh._babylonMesh=d,!this._handledMesh.isObject)for(let e=n-1;e>=0;--e)if(this._meshesFromObj[e].isObject&&this._meshesFromObj[e]._babylonMesh){d.parent=this._meshesFromObj[e]._babylonMesh;break}if(this._materialToUse.push(this._meshesFromObj[n].materialName),this._handledMesh.hasLines&&(null!==(i=d._internalMetadata)&&void 0!==i||(d._internalMetadata={}),d._internalMetadata._isLine=!0),0===(null===(a=this._handledMesh.positions)||void 0===a?void 0:a.length)){this._babylonMeshesArray.push(d);continue}const h=new t.VertexData;if(h.indices=this._handledMesh.indices,h.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),h.normals=e}else h.normals=this._handledMesh.normals;(null===(u=this._handledMesh.uvs)||void 0===u?void 0:u.length)&&(h.uvs=this._handledMesh.uvs),(null===(c=this._handledMesh.colors)||void 0===c?void 0:c.length)&&(h.colors=this._handledMesh.colors);const p=o._blockEntityCollection;o._blockEntityCollection=!!s;try{h.applyToMesh(d),d.geometry._parentContainer=s,null==s||s.geometries.push(d.geometry)}finally{o._blockEntityCollection=p}this._loadingOptions.invertY&&(d.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(d),this._babylonMeshesArray.push(d),this._handledMesh.directMaterial&&(d.material=this._handledMesh.directMaterial)}}}hh.ObjectDescriptor=/^o/,hh.GroupDescriptor=/^g/,hh.MtlLibGroupDescriptor=/^mtllib /,hh.UseMtlDescriptor=/^usemtl /,hh.SmoothDescriptor=/^s /,hh.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/,hh.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,hh.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,hh.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/,hh.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,hh.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,hh.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,hh.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,hh.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/,hh.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/,hh.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;const ph={name:"obj",extensions:{".obj":{isBinary:!0}}};class fh{static get INVERT_TEXTURE_Y(){return dh.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){dh.INVERT_TEXTURE_Y=e}constructor(e){this.name=ph.name,this.extensions=ph.extensions,this._assetContainer=null,this._loadingOptions=Object.assign(Object.assign({},fh._DefaultLoadingOptions),null!=e?e:{})}static get _DefaultLoadingOptions(){return{encoding:fh.ENCODING,computeNormals:fh.COMPUTE_NORMALS,optimizeNormals:fh.OPTIMIZE_NORMALS,importVertexColors:fh.IMPORT_VERTEX_COLORS,invertY:fh.INVERT_Y,invertTextureY:fh.INVERT_TEXTURE_Y,waitForTextures:fh.WAIT_FOR_TEXTURES,UVScaling:fh.UV_SCALING,materialLoadingFailsSilently:fh.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:fh.OPTIMIZE_WITH_UV,skipMaterials:fh.SKIP_MATERIALS,useLegacyBehavior:fh.USE_LEGACY_BEHAVIOR}}_loadMTL(e,n,o,s){const r=n+e;t.Tools.LoadFile(r,o,void 0,void 0,!0,(e,t)=>{s(r,t)})}_decode(e){var t;if("string"==typeof e)return e;const n=new Uint8Array(e),o=null!==(t=this._loadingOptions.encoding)&&void 0!==t?t:"auto";if("auto"!==o)return new TextDecoder(o).decode(n);if(255===n[0]&&254===n[1])return new TextDecoder("utf-16le").decode(n);if(254===n[0]&&255===n[1])return new TextDecoder("utf-16be").decode(n);try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch(e){return new TextDecoder("gb18030").decode(n)}}createPlugin(e){return new fh(e[ph.name])}canDirectLoad(){return!1}importMeshAsync(e,t,n,o){return this._parseSolidAsync(e,t,n,o).then(e=>{const t=[];for(let n=0;n<e.length;++n){const o=e[n].geometry;o&&t.push(o)}return{meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:t,lights:[],spriteManagers:[]}})}loadAsync(e,t,n){return this.importMeshAsync(null,e,t,n).then(()=>{})}loadAssetContainerAsync(e,n,o){return b(this,void 0,void 0,function*(){const s=new t.AssetContainer(e);this._assetContainer=s;try{return yield this.importMeshAsync(null,e,n,o),s}catch(e){throw s.dispose(),e}finally{this._assetContainer=null}})}_parseSolidAsync(e,n,o,s){let r="";const i=new dh,a=[],l=[];o=(o=this._decode(o)).replace(/#.*$/gm,"").trim(),new hh(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=>b(this,void 0,void 0,function*(){try{const t=i.parseMTL(n,this._decode(u),s,this._assetContainer,this._loadingOptions.invertTextureY,new Set(a),this._loadingOptions.waitForTextures);for(let e=0;e<i.materials.length;++e){const t=i.materials[e];for(let e=a.indexOf(t.name);-1!==e;e=a.indexOf(t.name,e+1)){const n=l[e];n.material=t,n.getTotalIndices()||(t.pointsCloud=!0)}}if(this._loadingOptions.waitForTextures){const e=(yield Promise.allSettled(t)).find(e=>"rejected"===e.status);if(e)throw e.reason}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=o.material;if(!i){const e=n._blockEntityCollection;n._blockEntityCollection=!!this._assetContainer;try{i=new t.StandardMaterial(o.name+"_line",n),i._parentContainer=this._assetContainer,null===(s=this._assetContainer)||void 0===s||s.materials.push(i)}finally{n._blockEntityCollection=e}}if(i.getBindedMeshes().filter(t=>!e(t)).length>0){const e=i,{ambientTexture:t,diffuseTexture:o,specularTexture:s,bumpTexture:a,opacityTexture:l}=e,u=n._blockEntityCollection;let c;try{e.ambientTexture=null,e.diffuseTexture=null,e.specularTexture=null,e.bumpTexture=null,e.opacityTexture=null,n._blockEntityCollection=!!this._assetContainer,c=e.clone(e.name+"_line"),c._parentContainer=this._assetContainer,null===(r=this._assetContainer)||void 0===r||r.materials.push(c)}finally{n._blockEntityCollection=u,e.ambientTexture=t,e.diffuseTexture=o,e.specularTexture=s,e.bumpTexture=a,e.opacityTexture=l}c.ambientTexture=t,c.diffuseTexture=o,c.specularTexture=s,c.bumpTexture=a,c.opacityTexture=l,i=c}i.wireframe=!0,o.material=i}}),l.forEach(e=>{e._internalMetadata&&(e._internalMetadata._isLine=void 0)}),l})}}fh.ENCODING="auto",fh.OPTIMIZE_WITH_UV=!0,fh.INVERT_Y=!1,fh.WAIT_FOR_TEXTURES=!1,fh.IMPORT_VERTEX_COLORS=!1,fh.COMPUTE_NORMALS=!1,fh.OPTIMIZE_NORMALS=!1,fh.UV_SCALING=new t.Vector2(1,1),fh.SKIP_MATERIALS=!1,fh.MATERIAL_LOADING_FAILS_SILENTLY=!0,fh.USE_LEGACY_BEHAVIOR=!1;let mh=!1;function gh(){mh||(mh=!0,t.RegisterSceneLoaderPlugin(new fh))}var _h={__proto__:null,OBJFileLoader:fh,RegisterOBJFileLoader:gh};gh();var vh={__proto__:null,MTLFileLoader:dh,OBJFileLoader:fh,RegisterOBJFileLoader:gh,SolidParser:hh};const yh={name:"stl",extensions:{".stl":{isBinary:!0}}};class bh{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=yh.name,this.extensions=yh.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,bh.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}bh.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);)bh.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]));bh.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)}}bh.DO_NOT_ALTER_FILE_COORDINATES=!1;let xh=!1;function Th(){xh||(xh=!0,t.RegisterSceneLoaderPlugin(new bh))}var Ah={__proto__:null,RegisterSTLFileLoader:Th,STLFileLoader:bh};Th();var wh={__proto__:null,RegisterSTLFileLoader:Th,STLFileLoader:bh};const Mh={name:"splat",extensions:{".splat":{isBinary:!0},".ply":{isBinary:!0},".spz":{isBinary:!0},".json":{isBinary:!1},".sog":{isBinary:!0}}},Sh=.28209479177387814;function Rh(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 Ch(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 Rh(t,e,o.getEngine())}return yield Rh(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 p=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[p[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=p[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]]*Sh;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*Sh:1/(1+Math.exp(-u)),l[32*n+24+s]=Math.max(0,Math.min(255,Math.round(255*c)))}}}const m=e=>2*(e/255-.5)/Math.SQRT2,g=n[3].bits;for(let e=0;e<s;e++){const t=g[4*e+0],n=g[4*e+1],o=g[4*e+2],s=g[4*e+3],r=m(t),i=m(n),a=m(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),p=o.getEngine().getCaps().maxTextureSize,f=Math.ceil(s/p),m=t.AllocateShBuffers(h,f*p*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=m[a],d=i%16,h=16*t,p=127.5*e.shN.codebook[l[4*(o+n)+r+s*c*4]]+127.5;u[d+h]=Math.max(0,Math.min(255,p))}}}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=m[u],p=i%16,f=16*n,g=127.5*t.Scalar.Lerp(a,d,l[4*(s+o)+e+r*c*4]/255)+127.5;h[p+f]=Math.max(0,Math.min(255,g))}}return yield new Promise(e=>{e({mode:0,data:r,hasVertexColors:!1,sh:m,shDegree:a})})}return yield new Promise(e=>{e({mode:0,data:r,hasVertexColors:!1})})})}(s,a,o)})}function Ih(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 Oh(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 Rh(e,n,s);return Ih(o,r)})}function Fh(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 Eh(e,n,o){return b(this,arguments,void 0,function*(e,n,o,s=!0,r,i){var a,l,u,c,d,h,p;let f,m;if(e instanceof Map){m=e;const t=m.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 g=e=>b(this,void 0,void 0,function*(){if(m&&m.has(e))return yield Rh(m.get(e),e,o.getEngine());if(r){const t=new Uint8Array(yield r.loadFileAsync(n+e,i));return yield Rh(t,e,o.getEngine())}return yield Rh(n,e,o.getEngine())}),_=e=>b(this,void 0,void 0,function*(){if(m&&m.has(e))return yield Oh(m.get(e),e,o);if(r){const t=new Uint8Array(yield r.loadFileAsync(n+e,i));return yield Oh(t,e,o)}return yield Oh(n,e,o)}),v=[...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 y,x,T,A,w,M=null;if(s){const[e,t]=yield Promise.all([Promise.all(f.means.files.map(g)),Promise.all(v.map(_))]);M=[e[0],e[1]],w=t,y=Ih(o,e[0]),x=Ih(o,e[1]),T=e[0].width,A=e[0].height}else{const[e,t]=yield Promise.all([Promise.all(f.means.files.map(_)),Promise.all(v.map(_))]);w=t,y=e[0],x=e[1];const n=y.getSize();T=n.width,A=n.height}const S=null!==(u=f.count)&&void 0!==u?u:f.means.shape[0],R=T*A;if(R<S)throw new Error(`SOG texture contains ${R} texels, but metadata references ${S} splats.`);const C=w[0],I=w[1],O=w[2];let F,E,N,L=0,k=0;if(f.shN&&w.length>=5&&(F=w[3],E=w[4],L=f.shN.bands?Math.pow(f.shN.bands+1,2)-1:f.shN.shape[1]/3,k=null!==(c=f.shN.bands)&&void 0!==c?c:Math.round(Math.sqrt(L+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),N=new t.RawTexture(n,3*e,1,t.Constants.TEXTUREFORMAT_R,o,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_FLOAT),N.wrapU=t.Constants.TEXTURE_CLAMP_ADDRESSMODE,N.wrapV=t.Constants.TEXTURE_CLAMP_ADDRESSMODE}const P=f.means.mins,B=f.means.maxs,D={version:2===f.version?2:1,splatCount:S,shDegree:k,meansTextureL:y,meansTextureU:x,scalesTexture:C,quatsTexture:I,sh0Texture:O,shCentroidsTexture:F,shLabelsTexture:E,codebookTexture:N,meansMin:[P[0],P[1],P[2]],meansMax:[B[0],B[1],B[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===(p=f.shN)||void 0===p?void 0:p.maxs)?f.shN.maxs:void 0,shCoeffCount:L,positions:M?Fh(f,M[0].bits,M[1].bits,S):new Float32Array(0)};return{mode:0,data:new ArrayBuffer(0),hasVertexColors:!1,shDegree:k,sogTextures:D}})}const Nh="precision highp float;\nattribute vec3 position;\nvoid main() {\n gl_Position = vec4(position.xy, 0.0, 1.0);\n}\n",Lh="\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 kh{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}get shTextures(){return this._shMrts.map(e=>e.textures[0])}get rotationTextures(){return this._rotMrt?this._rotMrt.textures:[]}constructor(e,t,n,o,s){if(this._copyMaterial=null,this._relayoutMapData=null,this._relayoutMapTexture=null,this._backupMrt=null,this._disposed=!1,this._readFbo=null,this._shMrts=[],this._ownsShMrts=!1,this._shMaterial=null,this._shCopyMaterial=null,this._backupShMrts=null,this._rotMrt=null,this._ownsRotMrt=!1,this._rotMaterial=null,this._rotCopyMaterial=null,this._backupRotMrt=null,this._scene=e,this._shaderLanguage=e.getEngine().isWebGPU?1:0,this._capacity=Math.max(1,t),n?(this._mrt=n.mrt,this._textureSize=n.width,this._baseOffset=n.baseOffset,this._ownsMrt=!1):(this._textureSize=Math.max(1,Math.ceil(Math.sqrt(Math.max(1,t)))),this._baseOffset=0,this._ownsMrt=!0,this._mrt=this._createMrt("gsWorkBuffer",!0)),o&&o.textureCount>0){if(o.externalMrts)this._shMrts=o.externalMrts.slice(0,o.textureCount),this._ownsShMrts=!1;else{for(let e=0;e<o.textureCount;e++)this._shMrts.push(this._createShMrt(`gsWorkBufferSh${e}`,!0));this._ownsShMrts=!0}this._shMaterial=this._createShMaterial()}s&&(s.externalMrt?(this._rotMrt=s.externalMrt,this._ownsRotMrt=!1):(this._rotMrt=this._createRotMrt("gsWorkBufferRot",!0),this._ownsRotMrt=!0),this._rotMaterial=this._createRotMaterial()),this._material=this._createMaterial(),this._quad=this._createQuad(),this._quad.material=this._material,this._ownsMrt||this.isRelayoutReady()}rebindAtlas(e){this._ownsMrt||(this._mrt=e)}rebindShAtlas(e){!this._ownsShMrts&&e&&this._shMrts.length&&(this._shMrts=e.slice(0,this._shMrts.length))}rebindRotAtlas(e){!this._ownsRotMrt&&e&&this._rotMrt&&(this._rotMrt=e)}setBaseOffset(e){this._ownsMrt||(this._baseOffset=e)}get canBackup(){return!this._disposed&&!this._ownsMrt&&this.isRelayoutReady()}backupRegion(){if(this._disposed||this._ownsMrt)return;if(!this.isRelayoutReady())return void t.Logger.Warn("GaussianSplattingWorkBuffer: backup skipped because the copy shaders are not ready; streamed region data may be lost on the atlas rebuild.");const e=this._textureSize,n=Math.max(1,Math.floor(this._capacity/e)),o=Math.floor(this._baseOffset/e);if(this._backupMrt||(this._backupMrt=this._createMrt("gsAtlasBackup",!1,e,n)),this._renderRelayoutPass(this._backupMrt,this._mrt.textures,this._mrt.textures[0],0,e,e,0,-o),this._shMrts.length&&this._shCopyMaterial){this._backupShMrts||(this._backupShMrts=this._shMrts.map((t,o)=>this._createShMrt(`gsShAtlasBackup${o}`,!1,e,n)));for(let t=0;t<this._shMrts.length;t++)this._renderShCopyPass(this._backupShMrts[t],this._shMrts[t].textures[0],this._mrt.textures[0],0,e,e,0,-o)}this._rotMrt&&this._rotCopyMaterial&&(this._backupRotMrt||(this._backupRotMrt=this._createRotMrt("gsRotAtlasBackup",!1,e,n)),this._renderRotCopyPass(this._backupRotMrt,this._rotMrt.textures,this._mrt.textures[0],0,e,e,0,-o)),this._quad.material=this._material}restoreRegion(){var e;if(this._disposed||this._ownsMrt||!this._backupMrt||!this._copyMaterial)return;const t=this._textureSize,n=Math.max(1,Math.floor(this._capacity/t)),o=Math.floor(this._baseOffset/t),s=this._scene.getEngine();s.enableScissor(0,o,t,n);try{if(this._renderRelayoutPass(this._mrt,this._backupMrt.textures,this._backupMrt.textures[0],0,t,t,0,o),this._backupShMrts&&this._shMrts.length&&this._shCopyMaterial)for(let e=0;e<this._shMrts.length&&e<this._backupShMrts.length;e++)this._renderShCopyPass(this._shMrts[e],this._backupShMrts[e].textures[0],this._mrt.textures[0],0,t,t,0,o);this._backupRotMrt&&this._rotMrt&&this._rotCopyMaterial&&this._renderRotCopyPass(this._rotMrt,this._backupRotMrt.textures,this._mrt.textures[0],0,t,t,0,o)}finally{s.disableScissor(),this._quad.material=this._material}if(this._backupMrt.dispose(),this._backupMrt=null,this._backupShMrts){for(const e of this._backupShMrts)e.dispose();this._backupShMrts=null}null===(e=this._backupRotMrt)||void 0===e||e.dispose(),this._backupRotMrt=null}_createMrt(e,n,o=this._textureSize,s=this._textureSize){const r=this._scene.getEngine()._caps.textureHalfFloatRender?t.Constants.TEXTURETYPE_HALF_FLOAT:t.Constants.TEXTURETYPE_FLOAT,i=new t.MultiRenderTarget(e,{width:o,height:s},4,this._scene,{types:[t.Constants.TEXTURETYPE_FLOAT,r,r,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 i.clearColor=new t.Color4(0,0,0,0),i.renderList=[],n&&i.onClearObservable.add(()=>{}),i}_createShMrt(e,n,o=this._textureSize,s=this._textureSize){const r=new t.MultiRenderTarget(e,{width:o,height:s},1,this._scene,{types:[t.Constants.TEXTURETYPE_UNSIGNED_INTEGER],formats:[t.Constants.TEXTUREFORMAT_RGBA_INTEGER],samplingModes:[t.Constants.TEXTURE_NEAREST_SAMPLINGMODE],generateDepthBuffer:!1,generateDepthTexture:!1,generateMipMaps:!1},[e]);return r.clearColor=new t.Color4(0,0,0,0),r.renderList=[],n&&r.onClearObservable.add(()=>{}),r}_createRotMrt(e,n,o=this._textureSize,s=this._textureSize){const r=this._scene.getEngine()._caps.textureHalfFloatRender?t.Constants.TEXTURETYPE_HALF_FLOAT:t.Constants.TEXTURETYPE_FLOAT,i=new t.MultiRenderTarget(e,{width:o,height:s},3,this._scene,{types:[r,r,r],formats:[t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA],samplingModes:[t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE],generateDepthBuffer:!1,generateDepthTexture:!1,generateMipMaps:!1},[`${e}A`,`${e}B`,`${e}Scale`]);return i.clearColor=new t.Color4(0,0,0,0),i.renderList=[],n&&i.onClearObservable.add(()=>{}),i}decodeAsync(e,t){return b(this,void 0,void 0,function*(){if(this._disposed)return;this._applyPack(e);const n=null!==this._shMaterial&&this._shMrts.length>0;n&&this._applyShPack(e);const o=null!==this._rotMaterial&&null!==this._rotMrt;o&&this._applyRotPack(e),yield new Promise(s=>{const r=()=>{if(this._disposed)return void s();if(!this._material.isReady(this._quad)||n&&!this._shMaterial.isReady(this._quad)||o&&!this._rotMaterial.isReady(this._quad))return void this._scene.onBeforeRenderObservable.addOnce(r);const i=this._textureSize,a=this._baseOffset+t;this._material.setInt("uOffset",a),n&&this._shMaterial.setInt("uOffset",a),o&&this._rotMaterial.setInt("uOffset",a);const l=Math.floor(a/i),u=Math.max(1,Math.ceil((a+e.splatCount)/i)-l),c=this._scene.getEngine();c.enableScissor(0,l,i,u);try{if(this._quad.material=this._material,this._mrt.renderList=[this._quad],this._mrt.render(),n){for(let e=0;e<this._shMrts.length;e++)this._shMaterial.setInt("uShTextureIndex",e),this._quad.material=this._shMaterial,this._shMrts[e].renderList=[this._quad],this._shMrts[e].render();this._quad.material=this._material}o&&(this._quad.material=this._rotMaterial,this._rotMrt.renderList=[this._quad],this._rotMrt.render(),this._quad.material=this._material)}finally{c.disableScissor()}s()};this._scene.onBeforeRenderObservable.addOnce(r)})})}isRelayoutReady(){if(this._disposed)return!1;this._copyMaterial||(this._copyMaterial=this._createCopyMaterial()),this._shMrts.length&&!this._shCopyMaterial&&(this._shCopyMaterial=this._createShCopyMaterial()),this._rotMrt&&!this._rotCopyMaterial&&(this._rotCopyMaterial=this._createRotCopyMaterial()),this._bindCopyMaterialsToAtlas();const e=0===this._shMrts.length||null!==this._shCopyMaterial&&this._shCopyMaterial.isReady(this._quad),t=!this._rotMrt||null!==this._rotCopyMaterial&&this._rotCopyMaterial.isReady(this._quad);return this._copyMaterial.isReady(this._quad)&&e&&t}_bindCopyMaterialsToAtlas(){const e=this._mrt.textures;if(this._copyMaterial&&(this._copyMaterial.setTexture("uMapTex",e[0]),this._copyMaterial.setTexture("uSrc0",e[0]),this._copyMaterial.setTexture("uSrc1",e[1]),this._copyMaterial.setTexture("uSrc2",e[2]),this._copyMaterial.setTexture("uSrc3",e[3])),this._shCopyMaterial&&this._shMrts.length&&(this._shCopyMaterial.setTexture("uMapTex",e[0]),this._shCopyMaterial.setTexture("uSrcSh",this._shMrts[0].textures[0])),this._rotCopyMaterial&&this._rotMrt){const t=this._rotMrt.textures;this._rotCopyMaterial.setTexture("uMapTex",e[0]),this._rotCopyMaterial.setTexture("uSrc0",t[0]),this._rotCopyMaterial.setTexture("uSrc1",t[1]),this._rotCopyMaterial.setTexture("uSrc2",t[2])}}relayoutSync(e){if(this._disposed||!this._copyMaterial)return;const n=this._textureSize,o=n,s=this._ownsMrt?n:Math.max(1,Math.floor(this._capacity/n));this._relayoutMapData||(this._relayoutMapData=new Float32Array(o*s));const r=this._relayoutMapData;r.fill(-1),r.set(e.subarray(0,Math.min(e.length,r.length))),this._relayoutMapTexture?this._relayoutMapTexture.update(r):this._relayoutMapTexture=new t.RawTexture(r,o,s,t.Constants.TEXTUREFORMAT_R,this._scene,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_FLOAT);const i=this._relayoutMapTexture;if(this._ownsMrt){const e=this._createMrt("gsRelayoutTemp",!1);try{this._renderRelayoutPass(e,this._mrt.textures,i,1),this._renderRelayoutPass(this._mrt,e.textures,i,0)}finally{e.dispose()}if(this._shMrts.length&&this._shCopyMaterial)for(let e=0;e<this._shMrts.length;e++){const t=this._createShMrt("gsShRelayoutTemp",!1);try{this._renderShCopyPass(t,this._shMrts[e].textures[0],i,1),this._renderShCopyPass(this._shMrts[e],t.textures[0],i,0)}finally{t.dispose()}}if(this._rotMrt&&this._rotCopyMaterial){const e=this._createRotMrt("gsRotRelayoutTemp",!1);try{this._renderRotCopyPass(e,this._rotMrt.textures,i,1),this._renderRotCopyPass(this._rotMrt,e.textures,i,0)}finally{e.dispose()}}return void(this._quad.material=this._material)}const a=Math.floor(this._baseOffset/n),l=s,u=this._scene.getEngine(),c=this._createMrt("gsRelayoutTemp",!1,n,l),d=this._shMrts.length&&this._shCopyMaterial?this._shMrts.map((e,t)=>this._createShMrt(`gsShRelayoutTemp${t}`,!1,n,l)):[],h=this._rotMrt&&this._rotCopyMaterial?this._createRotMrt("gsRotRelayoutTemp",!1,n,l):null;try{this._renderRelayoutPass(c,this._mrt.textures,i,1,n,n,this._baseOffset,0);for(let e=0;e<d.length;e++)this._renderShCopyPass(d[e],this._shMrts[e].textures[0],i,1,n,n,this._baseOffset,0);h&&this._renderRotCopyPass(h,this._rotMrt.textures,i,1,n,n,this._baseOffset,0),u.enableScissor(0,a,n,l);try{this._renderRelayoutPass(this._mrt,c.textures,i,0,n,n,0,a);for(let e=0;e<d.length;e++)this._renderShCopyPass(this._shMrts[e],d[e].textures[0],i,0,n,n,0,a);h&&this._renderRotCopyPass(this._rotMrt,h.textures,i,0,n,n,0,a)}finally{u.disableScissor()}}finally{c.dispose();for(const e of d)e.dispose();null==h||h.dispose(),this._quad.material=this._material}}_renderRelayoutPass(e,t,n,o,s=this._textureSize,r=this._textureSize,i=0,a=0){const l=this._copyMaterial;l.setTexture("uMapTex",n),l.setTexture("uSrc0",t[0]),l.setTexture("uSrc1",t[1]),l.setTexture("uSrc2",t[2]),l.setTexture("uSrc3",t[3]),l.setInt("uDstWidth",s),l.setInt("uSrcWidth",r),l.setInt("uUseMap",o),l.setInt("uSrcBaseOffset",i),l.setInt("uDstBaseRow",a),this._quad.material=l,e.renderList=[this._quad],e.render()}_createCopyMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsWorkBufferRelayout",this._scene,{vertexSource:e?Lh:Nh,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// Region-scoped relayout (hosted compound atlas), both default 0 (standalone square path unchanged).\nuniform uSrcBaseOffset : i32;\nuniform uDstBaseRow : 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 = uniforms.uSrcBaseOffset + i32(m + 0.5);\n } else {\n srcIdx = (p.y - uniforms.uDstBaseRow) * 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// Region-scoped relayout (hosted compound atlas), both default 0 (standalone square path unchanged):\n// uSrcBaseOffset — added to the map's (region-local) source index so pass 1 reads the correct GLOBAL atlas texel.\n// uDstBaseRow — subtracted from the atlas destination row so pass 2's identity copy reads the region-local temp.\nuniform int uSrcBaseOffset;\nuniform int uDstBaseRow;\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 = uSrcBaseOffset + int(m + 0.5);\n } else {\n srcIdx = (p.y - uDstBaseRow) * 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","uSrcBaseOffset","uDstBaseRow"],samplers:["uMapTex","uSrc0","uSrc1","uSrc2","uSrc3"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_renderShCopyPass(e,t,n,o,s=this._textureSize,r=this._textureSize,i=0,a=0){const l=this._shCopyMaterial;l.setTexture("uMapTex",n),l.setTexture("uSrcSh",t),l.setInt("uDstWidth",s),l.setInt("uSrcWidth",r),l.setInt("uUseMap",o),l.setInt("uSrcBaseOffset",i),l.setInt("uDstBaseRow",a),this._quad.material=l,e.renderList=[this._quad],e.render()}_createShCopyMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsWorkBufferShCopy",this._scene,{vertexSource:e?Lh:Nh,fragmentSource:e?'\nvar uMapTexSampler : sampler;\nvar uMapTex : texture_2d<f32>;\n// Integer source sampled via textureLoad only — NO paired sampler (a sampler on a Uint texture fails WebGPU\n// validation: "None of the supported sample types (Uint)"). Mirrors the draw shader\'s shTexture0 declaration.\nvar uSrcSh : texture_2d<u32>;\n\nuniform uDstWidth : i32;\nuniform uSrcWidth : i32;\nuniform uUseMap : i32;\nuniform uSrcBaseOffset : i32;\nuniform uDstBaseRow : 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 = uniforms.uSrcBaseOffset + i32(m + 0.5);\n } else {\n srcIdx = (p.y - uniforms.uDstBaseRow) * uniforms.uDstWidth + p.x;\n }\n let s : vec2<i32> = vec2<i32>(srcIdx - (srcIdx / uniforms.uSrcWidth) * uniforms.uSrcWidth, srcIdx / uniforms.uSrcWidth);\n // Wrap in an explicit vec4<u32> so the WGSL processor emits an integer fragData location (its detection keys\n // off a literal vec4<u32>/vec4u in the assignment; a bare textureLoad(...) would default to vec4<f32>).\n fragmentOutputs.fragData0 = vec4<u32>(textureLoad(uSrcSh, s, 0));\n}\n':"precision highp float;\nprecision highp int;\nprecision highp usampler2D;\n\nuniform sampler2D uMapTex;\nuniform usampler2D uSrcSh;\nuniform int uDstWidth;\nuniform int uSrcWidth;\nuniform int uUseMap;\nuniform int uSrcBaseOffset;\nuniform int uDstBaseRow;\n\nlayout(location = 0) out uvec4 outSh;\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 = uSrcBaseOffset + int(m + 0.5);\n } else {\n srcIdx = (p.y - uDstBaseRow) * uDstWidth + p.x;\n }\n ivec2 s = ivec2(srcIdx - (srcIdx / uSrcWidth) * uSrcWidth, srcIdx / uSrcWidth);\n outSh = texelFetch(uSrcSh, s, 0);\n}\n"},{attributes:["position"],uniforms:["uDstWidth","uSrcWidth","uUseMap","uSrcBaseOffset","uDstBaseRow"],samplers:["uMapTex","uSrcSh"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_renderRotCopyPass(e,t,n,o,s=this._textureSize,r=this._textureSize,i=0,a=0){const l=this._rotCopyMaterial;l.setTexture("uMapTex",n),l.setTexture("uSrc0",t[0]),l.setTexture("uSrc1",t[1]),l.setTexture("uSrc2",t[2]),l.setInt("uDstWidth",s),l.setInt("uSrcWidth",r),l.setInt("uUseMap",o),l.setInt("uSrcBaseOffset",i),l.setInt("uDstBaseRow",a),this._quad.material=l,e.renderList=[this._quad],e.render()}_createRotCopyMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsWorkBufferRotCopy",this._scene,{vertexSource:e?Lh:Nh,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>;\n\nuniform uDstWidth : i32;\nuniform uSrcWidth : i32;\nuniform uUseMap : i32;\nuniform uSrcBaseOffset : i32;\nuniform uDstBaseRow : 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 = uniforms.uSrcBaseOffset + i32(m + 0.5);\n } else {\n srcIdx = (p.y - uniforms.uDstBaseRow) * 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}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D uMapTex;\nuniform sampler2D uSrc0;\nuniform sampler2D uSrc1;\nuniform sampler2D uSrc2;\nuniform int uDstWidth;\nuniform int uSrcWidth;\nuniform int uUseMap;\nuniform int uSrcBaseOffset;\nuniform int uDstBaseRow;\n\nlayout(location = 0) out vec4 glFragData[3];\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 = uSrcBaseOffset + int(m + 0.5);\n } else {\n srcIdx = (p.y - uDstBaseRow) * 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}\n"},{attributes:["position"],uniforms:["uDstWidth","uSrcWidth","uUseMap","uSrcBaseOffset","uDstBaseRow"],samplers:["uMapTex","uSrc0","uSrc1","uSrc2"],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=this._baseOffset+e,i=Math.floor(r/s),a=Math.ceil((r+t)/s)-i,l=4*(r-i*s),u=l+4*t,c=this._mrt.textures[0],d=this._scene.getEngine();if(d.isWebGPU){const e=yield c.readPixels(0,0,null,!0,!0,0,i,s,a);if(this._disposed||!e)return null;const t=e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.byteLength/4);return t.length>=u?t.subarray(l,u):null}const h=d,p=h._gl,f=null===(o=null===(n=c.getInternalTexture())||void 0===n?void 0:n._hardwareTexture)||void 0===o?void 0:o.underlyingResource;if(!f)return null;const m=new Float32Array(s*a*4);this._readFbo||(this._readFbo=p.createFramebuffer());const g=h._currentFramebuffer;p.bindFramebuffer(p.FRAMEBUFFER,this._readFbo),p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_2D,f,0),p.readBuffer(p.COLOR_ATTACHMENT0);const _=h._readPixelsAsync(0,i,s,a,p.RGBA,p.FLOAT,m);return p.bindFramebuffer(p.FRAMEBUFFER,g),g||p.readBuffer(p.BACK),_?(yield _,this._disposed||m.length<u?null:m.subarray(l,u)):null})}dispose(){var e,t,n,o,s,r,i,a,l,u;if(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._shMaterial)||void 0===t||t.dispose(!0,!1),null===(n=this._rotMaterial)||void 0===n||n.dispose(!0,!1),null===(o=this._copyMaterial)||void 0===o||o.dispose(!0,!1),null===(s=this._shCopyMaterial)||void 0===s||s.dispose(!0,!1),null===(r=this._rotCopyMaterial)||void 0===r||r.dispose(!0,!1),null===(i=this._relayoutMapTexture)||void 0===i||i.dispose(),null===(a=this._backupMrt)||void 0===a||a.dispose(),this._backupMrt=null,this._backupShMrts){for(const e of this._backupShMrts)e.dispose();this._backupShMrts=null}if(null===(l=this._backupRotMrt)||void 0===l||l.dispose(),this._backupRotMrt=null,this._ownsMrt&&this._mrt.dispose(),this._ownsShMrts)for(const e of this._shMrts)e.dispose();this._shMrts=[],this._ownsRotMrt&&(null===(u=this._rotMrt)||void 0===u||u.dispose()),this._rotMrt=null}_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?Lh:Nh,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){var n,o,s,r,i;const a=this._material,l=e.meansTextureL.getSize().width;a.setTexture("sogMeansLTex",e.meansTextureL),a.setTexture("sogMeansUTex",e.meansTextureU),a.setTexture("sogScalesTex",e.scalesTexture),a.setTexture("sogQuatsTex",e.quatsTexture),a.setTexture("sogSh0Tex",e.sh0Texture),a.setTexture("sogCodebookTex",null!==(n=e.codebookTexture)&&void 0!==n?n:e.sh0Texture),a.setVector3("sogMeansMin",new t.Vector3(e.meansMin[0],e.meansMin[1],e.meansMin[2])),a.setVector3("sogMeansMax",new t.Vector3(e.meansMax[0],e.meansMax[1],e.meansMax[2]));const u=null!==(o=e.scalesMin)&&void 0!==o?o:[0,0,0],c=null!==(s=e.scalesMax)&&void 0!==s?s:[0,0,0];a.setVector3("sogScalesMin",new t.Vector3(u[0],u[1],u[2])),a.setVector3("sogScalesMax",new t.Vector3(c[0],c[1],c[2]));const d=null!==(r=e.sh0Min)&&void 0!==r?r:[0,0,0,0],h=null!==(i=e.sh0Max)&&void 0!==i?i:[0,0,0,0];a.setVector4("sogSh0Min",new t.Vector4(d[0],d[1],d[2],d[3])),a.setVector4("sogSh0Max",new t.Vector4(h[0],h[1],h[2],h[3])),a.setInt("uVersion",e.version),a.setInt("uCount",e.splatCount),a.setInt("uDestWidth",this._textureSize),a.setInt("uSrcWidth",l)}_createShMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsSogShDecodeToWorkBuffer",this._scene,{vertexSource:e?Lh:Nh,fragmentSource:e?"\nvar sogShLabelsTexSampler : sampler;\nvar sogShLabelsTex : texture_2d<f32>;\nvar sogShCentroidsTexSampler : sampler;\nvar sogShCentroidsTex : texture_2d<f32>;\nvar sogCodebookTexSampler : sampler;\nvar sogCodebookTex : texture_2d<f32>;\n\nuniform sogShnMin : f32;\nuniform sogShnMax : f32;\nuniform uVersion : i32;\nuniform uOffset : i32;\nuniform uCount : i32;\nuniform uDestWidth : i32;\nuniform uSrcWidth : i32;\nuniform uCoeffs : i32;\nuniform uShTextureIndex : 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 kLocal : i32 = global - uniforms.uOffset;\n\n let lsz : vec2<i32> = vec2<i32>(textureDimensions(sogShLabelsTex, 0));\n let lsrc : vec2<i32> = vec2<i32>(kLocal - (kLocal / lsz.x) * lsz.x, kLocal / lsz.x);\n let labelRaw : vec4<f32> = textureLoad(sogShLabelsTex, lsrc, 0);\n let n : i32 = i32(labelRaw.r * 255.0 + 0.5) + i32(labelRaw.g * 255.0 + 0.5) * 256;\n let u : i32 = (n - (n / 64) * 64) * uniforms.uCoeffs;\n let v : i32 = n / 64;\n\n var packed : array<u32, 4> = array<u32, 4>(0u, 0u, 0u, 0u);\n\n for (var b : i32 = 0; b < 16; b = b + 1) {\n let s : i32 = uniforms.uShTextureIndex * 16 + b;\n let kc : i32 = s / 3;\n let j : i32 = s - kc * 3;\n var byteVal : f32 = 128.0;\n if (kc < uniforms.uCoeffs) {\n let centroidRaw : vec4<f32> = textureLoad(sogShCentroidsTex, vec2<i32>(u + kc, v), 0);\n var ch : f32 = centroidRaw.b;\n if (j == 0) { ch = centroidRaw.r; } else if (j == 1) { ch = centroidRaw.g; }\n var coeff : f32;\n if (uniforms.uVersion == 2) {\n let cidx : i32 = i32(ch * 255.0 + 0.5);\n coeff = textureLoad(sogCodebookTex, vec2<i32>(512 + cidx, 0), 0).r;\n } else {\n coeff = mix(uniforms.sogShnMin, uniforms.sogShnMax, ch);\n }\n byteVal = clamp(coeff * 127.5 + 127.5, 0.0, 255.0);\n }\n let bv : u32 = u32(byteVal + 0.5);\n let comp : i32 = b / 4;\n packed[comp] = packed[comp] | (bv << u32((b - comp * 4) * 8));\n }\n fragmentOutputs.fragData0 = vec4<u32>(packed[0], packed[1], packed[2], packed[3]);\n}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D sogShLabelsTex;\nuniform sampler2D sogShCentroidsTex;\nuniform sampler2D sogCodebookTex;\nuniform float sogShnMin;\nuniform float sogShnMax;\nuniform int uVersion;\nuniform int uOffset;\nuniform int uCount;\nuniform int uDestWidth;\nuniform int uSrcWidth;\nuniform int uCoeffs;\nuniform int uShTextureIndex;\n\nlayout(location = 0) out uvec4 outSh;\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 kLocal = global - uOffset;\n\n // 16-bit label for this source splat (LSB in r, MSB in g), indexed over the labels texture's own width.\n ivec2 lsz = textureSize(sogShLabelsTex, 0);\n ivec2 lsrc = ivec2(kLocal - (kLocal / lsz.x) * lsz.x, kLocal / lsz.x);\n vec4 labelRaw = texelFetch(sogShLabelsTex, lsrc, 0);\n int n = int(labelRaw.r * 255.0 + 0.5) + int(labelRaw.g * 255.0 + 0.5) * 256;\n int u = (n - (n / 64) * 64) * uCoeffs;\n int v = n / 64;\n\n uint packed0 = 0u;\n uint packed1 = 0u;\n uint packed2 = 0u;\n uint packed3 = 0u;\n\n for (int b = 0; b < 16; b++) {\n int s = uShTextureIndex * 16 + b; // flat SH scalar index\n int kc = s / 3; // higher-order coefficient (0-based)\n int j = s - kc * 3; // channel (0=r,1=g,2=b)\n float byteVal = 128.0; // neutral (decompose(128) ~= 0)\n if (kc < uCoeffs) {\n vec4 centroidRaw = texelFetch(sogShCentroidsTex, ivec2(u + kc, v), 0);\n float ch = (j == 0) ? centroidRaw.r : ((j == 1) ? centroidRaw.g : centroidRaw.b);\n float coeff;\n if (uVersion == 2) {\n int cidx = int(ch * 255.0 + 0.5);\n coeff = texelFetch(sogCodebookTex, ivec2(512 + cidx, 0), 0).r;\n } else {\n coeff = mix(sogShnMin, sogShnMax, ch);\n }\n byteVal = clamp(coeff * 127.5 + 127.5, 0.0, 255.0);\n }\n uint bv = uint(byteVal + 0.5);\n int comp = b / 4;\n uint contrib = bv << uint((b - comp * 4) * 8);\n if (comp == 0) { packed0 |= contrib; }\n else if (comp == 1) { packed1 |= contrib; }\n else if (comp == 2) { packed2 |= contrib; }\n else { packed3 |= contrib; }\n }\n outSh = uvec4(packed0, packed1, packed2, packed3);\n}\n"},{attributes:["position"],uniforms:["sogShnMin","sogShnMax","uVersion","uOffset","uCount","uDestWidth","uSrcWidth","uCoeffs","uShTextureIndex"],samplers:["sogShLabelsTex","sogShCentroidsTex","sogCodebookTex"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_applyShPack(e){var t,n,o,s,r;const i=this._shMaterial,a=!!e.shLabelsTexture&&!!e.shCentroidsTexture,l=null!==(t=e.shLabelsTexture)&&void 0!==t?t:e.sh0Texture,u=null!==(n=e.shCentroidsTexture)&&void 0!==n?n:e.sh0Texture;i.setTexture("sogShLabelsTex",l),i.setTexture("sogShCentroidsTex",u),i.setTexture("sogCodebookTex",null!==(o=e.codebookTexture)&&void 0!==o?o:l),i.setFloat("sogShnMin",null!==(s=e.shnMin)&&void 0!==s?s:0),i.setFloat("sogShnMax",null!==(r=e.shnMax)&&void 0!==r?r:0),i.setInt("uVersion",e.version),i.setInt("uCount",e.splatCount),i.setInt("uDestWidth",this._textureSize),i.setInt("uSrcWidth",l.getSize().width),i.setInt("uCoeffs",a?e.shCoeffCount:0)}_createRotMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsSogRotDecodeToWorkBuffer",this._scene,{vertexSource:e?Lh:Nh,fragmentSource:e?"\nvar sogScalesTexSampler : sampler;\nvar sogScalesTex : texture_2d<f32>;\nvar sogQuatsTexSampler : sampler;\nvar sogQuatsTex : texture_2d<f32>;\nvar sogCodebookTexSampler : sampler;\nvar sogCodebookTex : texture_2d<f32>;\n\nuniform sogScalesMin : vec3<f32>;\nuniform sogScalesMax : vec3<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 sRaw : vec3<f32> = textureLoad(sogScalesTex, src, 0).xyz;\n let qRaw : vec4<f32> = textureLoad(sogQuatsTex, src, 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\n fragmentOutputs.fragData0 = vec4<f32>(R[0], R[1].x);\n fragmentOutputs.fragData1 = vec4<f32>(R[1].y, R[1].z, R[2].x, R[2].y);\n fragmentOutputs.fragData2 = vec4<f32>(R[2].z, 2.0 * splatScale.x, 2.0 * splatScale.y, 2.0 * splatScale.z);\n}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D sogScalesTex;\nuniform sampler2D sogQuatsTex;\nuniform sampler2D sogCodebookTex;\n\nuniform vec3 sogScalesMin;\nuniform vec3 sogScalesMax;\nuniform int uVersion;\nuniform int uOffset;\nuniform int uCount;\nuniform int uDestWidth;\nuniform int uSrcWidth;\n\nlayout(location = 0) out vec4 glFragData[3];\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 sRaw = texelFetch(sogScalesTex, src, 0).xyz;\n vec4 qRaw = texelFetch(sogQuatsTex, src, 0);\n\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 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\n glFragData[0] = vec4(R[0], R[1].x);\n glFragData[1] = vec4(R[1].y, R[1].z, R[2].x, R[2].y);\n glFragData[2] = vec4(R[2].z, 2.0 * splatScale.x, 2.0 * splatScale.y, 2.0 * splatScale.z);\n}\n"},{attributes:["position"],uniforms:["sogScalesMin","sogScalesMax","uVersion","uOffset","uCount","uDestWidth","uSrcWidth"],samplers:["sogScalesTex","sogQuatsTex","sogCodebookTex"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_applyRotPack(e){var n,o,s;const r=this._rotMaterial,i=e.scalesTexture.getSize().width;r.setTexture("sogScalesTex",e.scalesTexture),r.setTexture("sogQuatsTex",e.quatsTexture),r.setTexture("sogCodebookTex",null!==(n=e.codebookTexture)&&void 0!==n?n:e.scalesTexture);const a=null!==(o=e.scalesMin)&&void 0!==o?o:[0,0,0],l=null!==(s=e.scalesMax)&&void 0!==s?s:[0,0,0];r.setVector3("sogScalesMin",new t.Vector3(a[0],a[1],a[2])),r.setVector3("sogScalesMax",new t.Vector3(l[0],l[1],l[2])),r.setInt("uVersion",e.version),r.setInt("uCount",e.splatCount),r.setInt("uDestWidth",this._textureSize),r.setInt("uSrcWidth",i)}}class Ph{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 Bh{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 Dh{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 Bh;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 Vh{constructor(e,t,n){this._blocks=new Map,this._cooldown=new Map,this._pinned=new Set,this._allocator=new Dh(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 Gh=Math.tan(22.5*Math.PI/180),$h=new t.Matrix,Uh=new t.Vector3,Hh=new t.Vector3,Kh=new t.Vector3,jh=new t.Vector3(0,0,1),Wh=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]],qh=2*Wh.length,zh=[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 Xh 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={}){var i,a,l,u,c;const d=Xh._NormalizeResidentLimit(null!==(i=r.maxResidentSplats)&&void 0!==i?i:0,"maxResidentSplats",!0),h=Xh._NormalizeResidentLimit(null!==(a=r.memoryBudgetMb)&&void 0!==a?a:0,"memoryBudgetMb",!1);super(e,null,s,!1),this._leafNodes=[],this._lod0SplatCount=Object.freeze({status:"pending"}),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._lodPixelThreshold=1,this._hostBudgetAllocation=null,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._cullCameraViewProj=new t.Matrix,this._cullViewProj=new t.Matrix,this._frustumScratch=[],this._workBuffer=null,this._streamShDegree=0,this._shTextureCount=0,this._needsRotationScale=!1,this._useGpuPositionReadback=!1,this._readbackCandidate=!1,this._readbackProbed=!1,this._residency=null,this._fileCounts=new Map,this._fileMeta=new Map,this._baseFileIds=new Set,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._minimumResidentSplats=0,this._maxResidentSplats=0,this._memoryBudgetMb=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._metadataReady=!1,this._framesSinceLodUpdate=0,this._lastLodCamPositions=[],this._lastLodSignature="",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._hostCompound=null,this._host=null,this._positionBase=0,this._unsubBeforeRebuild=null,this._unsubAfterRebuild=null,this._hostUnsubRemove=null,this._hostUnsubDispose=null,this._partReleasedByHost=!1,this._positionSnapshot=null,this._partReadyPromise=null,this._partReadyResolve=null,this._partReadyReject=null,this._partReadySettled=!1,this._metadata=n,this._rootUrl=o,this._streamOptions=r,this._hostCompound=null!==(l=r.hostCompound)&&void 0!==l?l:null,this._decodeSh=null===(u=r.decodeSh)||void 0===u||u,this._needsRotationScale=null!==(c=r.needsRotationScale)&&void 0!==c&&c;const p=Math.max(0,n.lodLevels-1);if(this._lodRangeMax=p,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,p))),void 0!==r.lodRangeMax&&(this._lodRangeMax=Math.max(this._lodRangeMin,Math.min(r.lodRangeMax,p))),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))),this._splatBudget=this._resolveSplatBudget(r.splatBudget),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))),this._maxResidentSplats=d,this._memoryBudgetMb=h,this._downloadManager=new Ph({maxConcurrent:r.maxConcurrentDownloads,maxRetries:r.maxDownloadRetries}),this._hostCompound){this.setEnabled(!1),this.isPickable=!1,this.doNotSerialize=!0,this._partReadyPromise=new Promise((e,t)=>{this._partReadyResolve=e,this._partReadyReject=t}),this._partReadyPromise.catch(()=>{});const e=this._hostCompound.onDisposeObservable.add(()=>{this._disposed||(this._partReleasedByHost=!0,this.dispose())});this._hostUnsubDispose=()=>this._hostCompound.onDisposeObservable.remove(e)}else this.scaling.y*=-1,this.rotation.x=-Math.PI/2;this._collectLodEntries(n.tree),r.debugDisplay&&(this.debugDisplay=!0),this._streamAllAsync().then(()=>{const e=this._partReadySettled;this._rejectPartReady("GaussianSplattingStream: stream produced no splats."),e||!this._hostCompound||this._disposed||this._disposeAndReclaim()},e=>{var n,o;this._lod0SplatCount=Object.freeze({status:"unavailable"}),t.Logger.Error("GaussianSplattingStream: streaming failed: "+(null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e)),this._rejectPartReady("GaussianSplattingStream: streaming failed: "+(null!==(o=null==e?void 0:e.message)&&void 0!==o?o:e)),this._disposed||this._disposeAndReclaim()})}getClassName(){return"GaussianSplattingStream"}isReady(e=!1){return!!this._hostCompound||super.isReady(e)}get streamingPartProxy(){var e,t;return null!==(t=null===(e=this._host)||void 0===e?void 0:e.proxy)&&void 0!==t?t:null}whenPartReadyAsync(){return b(this,void 0,void 0,function*(){var e;yield null!==(e=this._partReadyPromise)&&void 0!==e?e:Promise.resolve()})}_resolvePartReady(){var e;this._partReadySettled||(this._partReadySettled=!0,null===(e=this._partReadyResolve)||void 0===e||e.call(this))}_rejectPartReady(e){var t;this._partReadySettled||(this._partReadySettled=!0,null===(t=this._partReadyReject)||void 0===t||t.call(this,new Error(e)))}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._sinkIsDepthSortSettled?++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&&this._metadataReady&&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 splatBudget(){return this._splatBudget}set splatBudget(e){const t=e>0?Math.floor(e):0;t!==this._splatBudget&&(this._splatBudget=t,this._forceLodUpdate=!0)}get effectiveSplatBudget(){return this._effectiveSplatBudget()}get residentSplatBudget(){return this._residentBudget}get minimumResidentSplats(){return this._minimumResidentSplats}get lod0SplatCount(){return this._lod0SplatCount}_resolveSplatBudget(e){return void 0===e?0:"auto"===e?this._computeDefaultSplatBudget():e>0?Math.floor(e):0}_computeDefaultSplatBudget(){var e;return(null===(e=this._scene.getEngine().hostInformation)||void 0===e?void 0:e.isMobile)?"undefined"!=typeof navigator&&navigator.userAgent&&/iPad|iPhone|iPod/.test(navigator.userAgent)?15e5:1e6:25e5}_effectiveSplatBudget(){if(null!==this._hostBudgetAllocation){const e=Math.max(1,this._hostBudgetAllocation);return this._residentBudget>0?Math.min(e,this._residentBudget):e}return this._splatBudget<=0?0:this._residentBudget>0?Math.min(this._splatBudget,this._residentBudget):this._splatBudget}_splatBudgetEnabled(){return this._effectiveSplatBudget()>0}getBudgetDemand(){var e;if(!this._baseLayerReady)return 0;let t=this._environmentSplatCount();for(const n of this._leafNodes){const o=null!==(e=n.optimalLod)&&void 0!==e?e:n.baseLod;t+=this._countAtLevel(n,this._cappedLevelForNode(n,o))}return t}setBudgetAllocation(e){if(null===e)return void(null!==this._hostBudgetAllocation&&(this._hostBudgetAllocation=null,this._forceLodUpdate=!0));const t=this._hostBudgetAllocation;this._hostBudgetAllocation=e,null!==t&&e===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,o,s,r,i;this._disposed||(this._disposed=!0,this._rejectPartReady("GaussianSplattingStream: disposed before the part was ready."),null===(t=this._unsubBeforeRebuild)||void 0===t||t.call(this),null===(n=this._unsubAfterRebuild)||void 0===n||n.call(this),this._unsubBeforeRebuild=null,this._unsubAfterRebuild=null,null===(o=this._hostUnsubRemove)||void 0===o||o.call(this),null===(s=this._hostUnsubDispose)||void 0===s||s.call(this),this._hostUnsubRemove=null,this._hostUnsubDispose=null,this._hostCompound&&!this._hostCompound.isDisposed()&&this._hostCompound.unregisterLodBudgetParticipant(this),this._host&&this._hostCompound&&!this._partReleasedByHost&&!this._hostCompound.isDisposed()&&this._hostCompound.removePart(this._host.partIndex),this._host=null,this._lodObserver&&(this._scene.onBeforeRenderObservable.remove(this._lodObserver),this._lodObserver=null),this._clearDebugDisplay(),this._downloadManager.dispose(),null===(r=this._residency)||void 0===r||r.dispose(),this._residency=null,null===(i=this._workBuffer)||void 0===i||i.dispose(),this._workBuffer=null,super.dispose(e))}_disposeAndReclaim(){const e=this._hostCompound,t=!!this._host&&!this._partReleasedByHost;this.dispose(),t&&e&&!e.isDisposed()&&e.compactAtlas()}_getEffectiveWorldMatrix(e){return this._host?this._host.proxy.computeWorldMatrix(e):this.computeWorldMatrix(e)}_getActiveLodCameras(){var e;return((null===(e=this._scene.activeCameras)||void 0===e?void 0:e.length)?this._scene.activeCameras:this._scene.activeCamera?[this._scene.activeCamera]:[]).filter(e=>!!e)}evaluateOptimalLods(e=null){const n=e?[e]:this._getActiveLodCameras();if(0===n.length||0===this._leafNodes.length)return;const o=Math.max(0,this._metadata.lodLevels-1),s=this._lodBaseDistance,r=this._lodMultiplier,i=this._lodBehindPenalty,a=this._lodRangeMin,l=this._lodRangeMax,u=this._splatBudgetEnabled(),c=this._scene.getEngine().getRenderHeight()||1,d=this._scene.getEngine();this._getEffectiveWorldMatrix(!1).invertToRef($h);const h=n.map(e=>{const n=d.getAspectRatio(e)||1;let o=Math.tan(.5*e.fov);e.fovMode===t.Camera.FOVMODE_HORIZONTAL_FIXED&&(o/=n);const s=o*n,r=Math.min(o,s)/Gh,a=c*(e.viewport?e.viewport.height:1),l=t.Vector3.TransformCoordinatesToRef(e.globalPosition,$h,Uh),u={px:l.x,py:l.y,pz:l.z,fwx:0,fwy:0,fwz:0,fovScale:r,tanHalfV:o,pixelHeight:a};if(i>1){e.getDirectionToRef(jh,Kh);const n=t.Vector3.TransformNormalToRef(Kh,$h,Hh);n.normalize(),u.fwx=n.x,u.fwy=n.y,u.fwz=n.z}return u});for(const e of this._leafNodes){const t=e.bound.min,n=e.bound.max,c=.5*(t[0]+n[0]),d=.5*(t[1]+n[1]),p=.5*(t[2]+n[2]),f=n[0]-t[0],m=n[1]-t[1],g=n[2]-t[2],_=.5*Math.sqrt(f*f+m*m+g*g);let v=Number.POSITIVE_INFINITY,y=0;for(const e of h){const a=e.px<t[0]?t[0]:e.px>n[0]?n[0]:e.px,l=e.py<t[1]?t[1]:e.py>n[1]?n[1]:e.py,h=e.pz<t[2]?t[2]:e.pz>n[2]?n[2]:e.pz,f=a-e.px,m=l-e.py,g=h-e.pz,b=Math.sqrt(f*f+m*m+g*g);let x=b;if(i>1&&b>.01){const t=(e.fwx*f+e.fwy*m+e.fwz*g)/b;t<0&&(x=b*(1+-t*(i-1)))}const T=x*e.fovScale;let A;if(0===o||T<s)A=0;else for(A=o;A>1&&T<s*Math.pow(r,A-1);)A--;if(A<v&&(v=A),u){const t=c-e.px,n=d-e.py,o=p-e.pz,s=Math.sqrt(t*t+n*n+o*o),r=_*e.pixelHeight/(Math.max(s,1e-4)*e.tanHalfV);r>y&&(y=r)}}v<a?v=a:v>l&&(v=l),this._frustumCulling&&!1===e.inFrustum&&(v=l),e.optimalLod=v,u&&(e.pixelSize=y)}}_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=zh[this._displayedLodLevel(o)%zh.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 Wh)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*qh*4)}_updateDebugColors(){if(!this._debugMesh||!this._debugColorData)return;const e=this._debugColorData;let n=0;for(const t of this._leafNodes){const o=zh[this._displayedLodLevel(t)%zh.length];for(let t=0;t<qh;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){var n,o;if(e.children){for(const t of e.children)this._collectLodEntries(t);return}if(!e.lods)return;const s=null===(n=e.bound)||void 0===n?void 0:n.min,r=null===(o=e.bound)||void 0===o?void 0:o.max;if(!s||!r||s.length<3||r.length<3||!s.every(e=>Number.isFinite(e))||!r.every(e=>Number.isFinite(e)))return;const i=r[0]-s[0],a=r[1]-s[1],l=r[2]-s[2],u=Math.sqrt(i*i+a*a+l*l);if(!Number.isFinite(u)||u<=0)return;const c=Math.floor(Number(this._metadata.lodLevels)),d=Number.isFinite(c)&&c>0?c-1:0,h=[];for(const t of Object.keys(e.lods)){const n=Number(t),o=e.lods[t],s=o?Math.floor(Number(o.count)):NaN;Number.isInteger(n)&&String(n)===t&&n>=0&&n<=d&&o&&Number.isFinite(s)&&s>0&&(o.count=s,h.push(n))}if(0===h.length)return;h.sort((e,t)=>e-t);const p=[];let f=1/0;for(const t of h){const n=e.lods[String(t)].count;n<=f&&(p.push(t),f=n)}e.availableLevels=p,e.baseLod=p[p.length-1],e.activeLod=void 0,e.lodCooldown=0,e.inFrustum=!0,e.cullBounds=new t.BoundingInfo(t.Vector3.FromArray(s),t.Vector3.FromArray(r)),this._leafNodes.push(e)}_streamAllAsync(){return b(this,void 0,void 0,function*(){const e=this._collectAllFileIds(),n=this._collectBaseFileIds();this._baseFileIds.clear();for(const e of n)this._baseFileIds.add(e);if(this._leafNodes.length>0&&0===n.length)throw new Error("GaussianSplattingStream: no valid coarse source files were referenced.");const o=e.length>32&&n.length<e.length;o&&this._decodeSh&&(this._streamShDegree=4,this._shTextureCount=5);const s=o?n:e,r=yield this._gatherCountsAsync(s);if(this._disposed)return;for(const e of n){const t=this._fileCounts.get(e);if(!this._fileMeta.has(e)||void 0===t||t<=0)throw new Error(`GaussianSplattingStream: required coarse metadata for file ${e} is unavailable or invalid.`)}this._resolveMinimumResidentSplats(n,r),o||(this._resolveLod0SplatCount(),this._metadataReady=!0);let i=null;if(!o){i=1+r;for(const t of e){const e=this._fileCounts.get(t);void 0!==e&&e>0&&(i=Xh._SafeAddCounts(i,e,"stream capacity"))}}if(this._minimumResidentSplats<=1)throw new Error("GaussianSplattingStream: stream produced no splats.");let a=0;for(const e of n)a=Math.max(a,this._fileCounts.get(e));const l=this._resolveResidentBudget(i,a);if(this._evictionEnabled=o||null!==i&&l<i,this._residency=new Vh(l,this._evictionCooldownFrames,e=>this._onFileEvicted(e)),this._residency.pin(-2,1),r>0){const e=this._residency.allocate(-1,r);null!==e?this._environmentRange={offset:e,count:r}:(t.Logger.Warn("GaussianSplattingStream: environment does not fit the memory budget; skipping it."),this._environmentFiles=null)}if(this._hostCompound){const e=t.Matrix.Compose(new t.Vector3(1,-1,1),t.Quaternion.RotationYawPitchRoll(0,-Math.PI/2,0),t.Vector3.ZeroReadOnly),n=this._hostCompound.reserveStreamingPart(l,e,this.name+"_part",this._shTextureCount,this._streamShDegree,this._needsRotationScale);this._host=n,this._positionBase=n.base,this._hostCompound.registerLodBudgetParticipant(this);const o=this._hostCompound,s=o.onPartRemovedObservable.add(e=>{!this._disposed&&this._host&&e===this._host.partIndex&&(this._partReleasedByHost=!0,this.dispose())});this._hostUnsubRemove=()=>o.onPartRemovedObservable.remove(s);const r=this._shTextureCount>0&&n.shMrtAtlas?{textureCount:this._shTextureCount,externalMrts:n.shMrtAtlas}:void 0,i=this._needsRotationScale&&n.rotMrtAtlas?{externalMrt:n.rotMrtAtlas}:void 0;this._workBuffer=new kh(this._scene,n.capacity,{mrt:n.mrtAtlas,width:n.atlasWidth,baseOffset:n.base},r,i),this._readbackCandidate=this._workBuffer.supportsAsyncCentersReadback,this._splatPositions=n.splatPositions,this._vertexCount=l;const a=this._workBuffer;this._unsubBeforeRebuild=n.onBeforeAtlasRebuild(()=>{a.backupRegion(),this._positionSnapshot=this._splatPositions?this._splatPositions.slice(4*this._positionBase,4*(this._positionBase+this._vertexCount)):null}),this._unsubAfterRebuild=n.onAfterAtlasRebuild(()=>{n.mrtAtlas&&a.rebindAtlas(n.mrtAtlas),a.rebindShAtlas(n.shMrtAtlas),a.rebindRotAtlas(n.rotMrtAtlas),this._positionBase=n.base,a.setBaseOffset(n.base),a.restoreRegion(),this._splatPositions=n.splatPositions,this._positionSnapshot&&this._splatPositions&&(this._splatPositions.set(this._positionSnapshot,4*this._positionBase),this._positionSnapshot=null)}),n.setActiveRanges([])}else{const e=this._shTextureCount>0?{textureCount:this._shTextureCount}:void 0,t=this._needsRotationScale?{}:void 0;this._workBuffer=new kh(this._scene,l,void 0,e,t),this._readbackCandidate=this._workBuffer.supportsAsyncCentersReadback;const n=new Float32Array(4*l),o=this._workBuffer.textures,s=e?this._workBuffer.shTextures:void 0,r=t?this._workBuffer.rotationTextures:void 0;this._setExternalWorkBuffer(o[0],o[1],o[2],o[3],n,l,s,this._streamShDegree,r),this.setSplatIndexRanges([]),this.setEnabled(!0)}if(!(this._host&&this._workBuffer&&(yield this._waitForCanBackupAsync(this._workBuffer),this._disposed))){this._environmentRange&&this._environmentFiles&&(yield this._decodeEnvironmentAsync()),this._environmentFiles=null;for(const e of n){if(this._disposed)return;if(!(yield this._decodeFileAsync(e)))throw new Error(`GaussianSplattingStream: required coarse file ${e} failed to decode.`)}if(!this._disposed){for(const e of this._leafNodes)if(e.activeLod!==e.baseLod||void 0===e.activeFile)throw new Error("GaussianSplattingStream: the complete coarse layer could not be activated.");if(this._baseLayerReady=!0,this._resolvePartReady(),o){const t=e.filter(e=>!this._baseFileIds.has(e));if(yield this._gatherCountsAsync(t,!1),this._resolveLod0SplatCount(),this._metadataReady=!0,this._disposed)return}this._lodObserver||(this._lodObserver=this._scene.onBeforeRenderObservable.add(()=>this._onLodFrame()))}}})}_waitForCanBackupAsync(e){return b(this,void 0,void 0,function*(){for(let t=0;t<600&&!this._disposed;t++){if(e.canBackup)return;yield new Promise(e=>this._scene.onBeforeRenderObservable.addOnce(()=>e()))}this._disposed||e.canBackup||t.Logger.Warn("GaussianSplattingStream: backup/restore copy shaders did not compile in time; a grow/compaction before they are ready may drop streamed data.")})}_resolveResidentBudget(e=null,n=0){var o;const s=this._maxResidentSplats>0||this._memoryBudgetMb>0;let r=this._maxResidentSplats>0?this._maxResidentSplats:Number.POSITIVE_INFINITY;const i=this._bytesPerResidentSplat();if(this._memoryBudgetMb>0){const e=Math.floor(1024*this._memoryBudgetMb*1024/i);r=Math.min(r,e)}if(s||null===e)if(s)r<this._minimumResidentSplats&&t.Logger.Warn(`GaussianSplattingStream: the requested initial residency (${r} splats) is below the complete coarse minimum (${this._minimumResidentSplats}); using the minimum.`);else{const e=(null===(o=this._scene.getEngine().hostInformation)||void 0===o?void 0:o.isMobile)?256:512,t=Math.floor(1024*e*1024/i),s=Math.max(0,Math.floor(n)),a=Xh._SafeAddCounts(this._minimumResidentSplats,s,"automatic resident capacity");r=Math.max(t,a)}else r=e;if(r=Math.max(this._minimumResidentSplats,Math.floor(r)),null!==e&&(r=Math.min(r,e)),null!==e||this._minimumResidentSplats>0){const e=Math.floor(this._scene.getEngine().getCaps().maxTextureSize),t=e*e;if(!Number.isSafeInteger(t)||this._minimumResidentSplats>t)throw new Error(`GaussianSplattingStream: minimum resident splat count ${this._minimumResidentSplats} exceeds the device texture capacity ${t}.`);if(r>t&&(r=t),r<this._minimumResidentSplats)throw new Error(`GaussianSplattingStream: minimum resident splat count ${this._minimumResidentSplats} exceeds the device texture capacity ${t}.`)}if(!Number.isSafeInteger(r)||r<this._minimumResidentSplats||r<1)throw new Error("GaussianSplattingStream: resolved resident capacity is invalid.");return this._residentBudget=r,r}_bytesPerResidentSplat(){const e=this._scene.getEngine().getCaps().textureHalfFloatRender?24:48;return 84+16*this._shTextureCount+(this._needsRotationScale?e:0)}_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)}_collectBaseFileIds(){var e;const t=new Set;for(const n of this._leafNodes){const o=null===(e=n.lods)||void 0===e?void 0:e[String(n.baseLod)];o&&t.add(o.file)}return Array.from(t).sort((e,t)=>e-t)}_resolveMinimumResidentSplats(e,t){let n=Xh._SafeAddCounts(1,Math.max(0,Math.floor(t)),"minimum resident splats");for(const t of e){const e=this._fileCounts.get(t);if(void 0===e||!Number.isSafeInteger(e)||e<=0)throw new Error(`GaussianSplattingStream: required coarse metadata for file ${t} is unavailable or invalid.`);n=Xh._SafeAddCounts(n,e,"minimum resident splats")}this._minimumResidentSplats=n}_resolveLod0SplatCount(){var e,t;let n=0,o=!1;for(const s of this._leafNodes){if(0!==(null===(e=s.availableLevels)||void 0===e?void 0:e[0]))continue;const r=null===(t=s.lods)||void 0===t?void 0:t[0];if(!r)return void(this._lod0SplatCount=Object.freeze({status:"unavailable"}));if(o=!0,!this._fileCounts.has(r.file)||!this._fileMeta.has(r.file))return void(this._lod0SplatCount=Object.freeze({status:"unavailable"}));if(n+=r.count,!Number.isSafeInteger(n))return void(this._lod0SplatCount=Object.freeze({status:"unavailable"}))}this._lod0SplatCount=o?Object.freeze({status:"available",count:n}):Object.freeze({status:"unavailable"})}_gatherCountsAsync(e){return b(this,arguments,void 0,function*(e,n=!0){var o;let s=0,r=0,i=0;const a=e=>{const t=Xh._GetShInfo(e);t.degree>r&&(r=t.degree),t.coeffs>i&&(i=t.coeffs)};if(n&&this._metadata.environment)try{const e=this._rootUrl+this._metadata.environment,t=yield this._downloadManager.loadFileAsync(e),n=yield this._unzipAsync(new Uint8Array(t)),o=n.get("meta.json");if(o){const e=JSON.parse((new TextDecoder).decode(o));s=Xh._GetSplatCount(e),a(e),this._environmentFiles=n}}catch(e){t.Logger.Warn("GaussianSplattingStream: failed to load environment: "+(null!==(o=null==e?void 0:e.message)&&void 0!==o?o:e))}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,Xh._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}.`)})));for(const{sogData:e}of this._fileMeta.values())a(e);return this._decodeSh&&r>0&&i>0&&(this._streamShDegree=Math.max(this._streamShDegree,r),this._shTextureCount=Math.max(this._shTextureCount,Math.ceil(3*i/16))),s})}_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*(this._positionBase+t)),this._updateBounds(e,n),this._sinkPostPositionsRange(t,n)}_sinkSetActiveRanges(e){this._host?this._host.setActiveRanges(e):this.setSplatIndexRanges(e)}_sinkPostPositionsRange(e,t){this._host?this._host.postPositionsRange(e,t):this._postWorkerPositionsRange(e,t)}_sinkNotifyDataChanged(){this._host?this._host.notifyDataChanged():this._notifyWorkerNewData()}get _sinkIsDepthSortSettled(){return this._host?this._host.isDepthSortSettled:this._isDepthSortSettled}_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,n,o;if(!this._environmentRange||!this._environmentFiles||!this._workBuffer)return;const s=this._environmentRange;let r=!1;try{const n=(yield Eh(this._environmentFiles,"",this._scene,!this._useGpuPositionReadback,this._downloadManager)).sogTextures;if(!n)return void t.Logger.Warn("GaussianSplattingStream: environment decoding produced no texture data.");try{if(this._disposed||!this._workBuffer)return;if(yield this._workBuffer.decodeAsync(n,s.offset),this._disposed)return;const o=yield this._applyDecodedPositionsAsync(n,s.offset,s.count);if(this._disposed)return;if(!o)return void t.Logger.Warn("GaussianSplattingStream: decoded positions could not be applied for the environment.");if((null===(e=this._residency)||void 0===e?void 0:e.pin(-1,s.count))!==s.offset)throw new Error("GaussianSplattingStream: decoded environment could not be pinned.");r=!0,this._refreshActiveRanges()}finally{Xh._DisposePack(n)}}catch(e){t.Logger.Warn("GaussianSplattingStream: failed to decode environment: "+(null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e))}finally{r||(null===(o=this._residency)||void 0===o||o.free(-1),this._environmentRange=null)}})}_decodeFileAsync(e){return b(this,void 0,void 0,function*(){var n;if(this._decodedFiles.has(e))return!0;if(this._loadingFiles.has(e)||!this._residency)return!1;const o=this._fileMeta.get(e),s=this._fileCounts.get(e);if(!o||void 0===s)return!1;this._loadingFiles.add(e),this._cancelledDecodes.delete(e);let r=!1;try{const n=(yield Eh(o.sogData,o.subRootUrl,this._scene,!this._useGpuPositionReadback,this._downloadManager,e)).sogTextures;if(!n)return!1;const i=yield this._acquireDecodeGateAsync();try{if(this._disposed||!this._workBuffer||this._cancelledDecodes.has(e))return!1;const o=this._residency;if(!o)return!1;let i=o.allocate(e,s);if(null===i&&(i=yield this._relayoutAndAllocateAsync(e,s)),null===i)return this._cancelledDecodes.has(e)||t.Logger.Warn(`GaussianSplattingStream: resident memory budget full; skipping LOD file ${e}.`),!1;if(r=!0,this._disposed||!this._workBuffer||this._cancelledDecodes.has(e))return!1;if(yield this._workBuffer.decodeAsync(n,i),this._disposed||this._cancelledDecodes.has(e))return!1;const a=yield this._applyDecodedPositionsAsync(n,i,s);if(this._disposed)return!1;if(!a)return t.Logger.Warn(`GaussianSplattingStream: decoded positions could not be applied for LOD file ${e}.`),!1;if(this._baseFileIds.has(e)&&o.pin(e,s)!==i)throw new Error(`GaussianSplattingStream: required coarse file ${e} could not be pinned.`);return this._decodedFiles.add(e),this._applyDesiredLods()&&this._refreshActiveRanges(),!0}finally{Xh._DisposePack(n),i()}}catch(t){if(!this._cancelledDecodes.has(e))throw t;return!1}finally{r&&!this._decodedFiles.has(e)&&(null===(n=this._residency)||void 0===n||n.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,r=this._positionBase;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*(r+t.offset),4*(r+n),4*(r+n+t.count))}if(this._environmentRange){const e=this._residency.offset(-1);void 0!==e&&(this._environmentRange.offset=e)}this._sinkNotifyDataChanged(),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;const t=this._effectiveSplatBudget();if(t<=0){for(const t of this._leafNodes){const n=null!==(e=t.optimalLod)&&void 0!==e?e:t.baseLod;t.targetLevel=this._cappedLevelForNode(t,n)}return}const n=Math.max(0,t-this._environmentSplatCount());this._convergePixelThreshold(n);const o=this._lodPixelThreshold;for(const e of this._leafNodes)e.targetLevel=this._budgetedLevel(e,o)}_environmentSplatCount(){const e=this._environmentRange?Math.floor(Number(this._environmentRange.count)):0;return Number.isFinite(e)&&e>0?e:0}_budgetedLevel(e,t){var n,o;const s=null!==(n=e.optimalLod)&&void 0!==n?n:e.baseLod,r=null!==(o=e.pixelSize)&&void 0!==o?o:0;let i=0;return r>0&&t>r&&(i=Math.max(0,Math.round(Math.log(t/r)/Math.log(this._lodMultiplier)))),this._cappedLevelForNode(e,s+i)}_countAtLevel(e,t){const n=e.lods[String(t)];return n?n.count:0}_totalSplatsAtThreshold(e){let t=0;for(const n of this._leafNodes)t+=this._countAtLevel(n,this._budgetedLevel(n,e));return t}_convergePixelThreshold(e){if(this._totalSplatsAtThreshold(1)<=e)return void(this._lodPixelThreshold=1);let t=1;for(const e of this._leafNodes)e.pixelSize&&e.pixelSize>t&&(t=e.pixelSize);const n=Math.min(32,Math.max(1,this._metadata.lodLevels)),o=t*Math.pow(this._lodMultiplier,n+1);if(this._totalSplatsAtThreshold(o)>e)return void(this._lodPixelThreshold=o);let s=1,r=o;for(let t=0;t<40&&r-s>.001*r;t++){const t=.5*(s+r);this._totalSplatsAtThreshold(t)<=e?r=t:s=t}this._lodPixelThreshold=r}_residentLevelAtLeast(e,t){for(const n of e.availableLevels)if(n>=t&&this._decodedFiles.has(e.lods[String(n)].file))return n;return null}_applyDesiredLods(){var e;let t=!1;for(const n of this._leafNodes){const o=null!==(e=n.targetLevel)&&void 0!==e?e:n.baseLod;if(this._splatBudgetEnabled()&&void 0!==n.activeLod&&n.activeLod<o){const e=this._residentLevelAtLeast(n,o);null!==e&&e!==n.activeLod&&(this._switchActiveFile(n,n.lods[String(e)].file),n.activeLod=e,n.lodCooldown=this._lodCooldownFrames,t=!0)}if(n.lodCooldown&&n.lodCooldown>0)continue;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._getActiveLodCameras(),n=this._lodUpdateDistance;if(e.length!==this._lastLodCamPositions.length||this._computeLodSignature(e)!==this._lastLodSignature)s=!0;else for(let o=0;o<e.length;o++)if(t.Vector3.DistanceSquared(e[o].globalPosition,this._lastLodCamPositions[o])>=n*n){s=!0;break}}if(s){this._forceLodUpdate=!1,this._framesSinceLodUpdate=0;const e=this._getActiveLodCameras();this._lastLodCamPositions.length=0;for(const t of e)this._lastLodCamPositions.push(t.globalPosition.clone());this._lastLodSignature=this._computeLodSignature(e),this.evaluateOptimalLods(),this._computeTargetLevels(),this._applyDesiredLods()&&this._refreshActiveRanges()}}_computeLodSignature(e){const t=this._scene.getEngine();let n=`${t.getRenderWidth()}x${t.getRenderHeight()}#${this._getEffectiveWorldMatrix(!1).updateFlag}`;for(const t of e){const e=t.viewport;n+=`|${t.uniqueId}:${t.fov}:${t.fovMode}:${e.x},${e.y},${e.width},${e.height}`}return n}_updateNodeFrustum(){const e=this._getActiveLodCameras();let n=!1;if(!this._frustumCulling||0===e.length){for(const e of this._leafNodes)!1===e.inFrustum&&(e.inFrustum=!0,n=!0);return n}const o=this._leafNodes,s=this._frustumScratch,r=this._getEffectiveWorldMatrix(!1);for(let e=0;e<o.length;e++)s[e]=!1;for(const n of e){n.getViewMatrix().multiplyToRef(n.getProjectionMatrix(),this._cullCameraViewProj),r.multiplyToRef(this._cullCameraViewProj,this._cullViewProj),t.Frustum.GetPlanesToRef(this._cullViewProj,this._frustumPlanes);let e=!0;for(const t of this._frustumPlanes)if(!(Number.isFinite(t.normal.x)&&Number.isFinite(t.normal.y)&&Number.isFinite(t.normal.z)&&Number.isFinite(t.d)&&0!==t.normal.lengthSquared())){e=!1;break}if(e)for(let e=0;e<o.length;e++)!s[e]&&o[e].cullBounds.isInFrustum(this._frustumPlanes)&&(s[e]=!0);else for(let e=0;e<o.length;e++)s[e]=!0}for(let e=0;e<o.length;e++)s[e]!==o[e].inFrustum&&(o[e].inFrustum=s[e],n=!0);return n}static _NormalizeResidentLimit(e,t,n){if(!Number.isFinite(e))throw new RangeError(`GaussianSplattingStream: ${t} must be finite.`);if(e<=0)return 0;const o=n?Math.max(1,Math.floor(e)):e;if(o>Number.MAX_SAFE_INTEGER)throw new RangeError(`GaussianSplattingStream: ${t} is outside the supported range.`);return o}static _SafeAddCounts(e,t,n){const o=e+t;if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(o))throw new Error(`GaussianSplattingStream: ${n} exceeds the supported integer range.`);return o}static _GetSplatCount(e){var t;const n=null!==(t=e.count)&&void 0!==t?t:Array.isArray(e.means.shape)?e.means.shape[0]:0,o=Math.floor(Number(n));return Number.isFinite(o)&&o>0?o:0}static _GetShInfo(e){if(!e.shN)return{degree:0,coeffs:0};let n=0;const o=e.shN.bands;if("number"==typeof o&&Number.isFinite(o)&&o>0)n=Math.floor(o);else if(Array.isArray(e.shN.shape)&&Number.isFinite(e.shN.shape[1])&&e.shN.shape[1]>0){const t=Math.floor(e.shN.shape[1]/3);n=t>0?Math.round(Math.sqrt(t+1)-1):0}return n>0?(n>4&&(t.Logger.Warn(`GaussianSplattingStream: SH degree ${n} exceeds the maximum supported (4); clamping.`),n=4),{degree:n,coeffs:Math.pow(n+1,2)-1}):{degree:0,coeffs: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._host?this._host.expandBounds(o,s):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._sinkSetActiveRanges(Xh._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 Yh=.28209479177387814;let Qh=null,Zh=null;class Jh{constructor(e={}){this.name=Mh.name,this._assetContainer=null,this.extensions=Mh.extensions,this._loadingOptions=Object.assign(Object.assign({},Jh._DefaultLoadingOptions),e)}createPlugin(e){return new Jh(e[Mh.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(!Xh.IsLODMetadata(o))return null;const s=e._blockEntityCollection;e._blockEntityCollection=!!this._assetContainer;try{const t=new Xh("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=Jh._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?Eh:Ch;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=>{Jh._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=Jh._ExtractSafeOrbitLimits(o)}break;case 1:{const e=new t.PointsCloudSystem("PointCloud",1,n);Jh._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(Jh._BuildMesh(n,o));break;default:throw new Error("Unsupported Splat mode")}n._blockEntityCollection=!1,this.applyAutoCameraLimits(Jh._ExtractSafeOrbitLimits(o),n),e(r)}))},h=31===c[0]&&139===c[1],p=78===c[0]&&71===c[1]&&83===c[2]&&80===c[3];if(!h&&!p)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=Jh._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(Qh&&Zh===e)return yield Qh;const n=t._LoadScriptModuleAsync(`import createSpzModule from '${e}';\n const module = await createSpzModule();\n const returnedValue = module;`);return Zh=e,Qh=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 p=null;const f=e.shDegree;let m,g,_=null,v=0,y=null,b=null,x=null;if(f>0&&e.sh.length>0){v=3*((f+1)*(f+1)-1);const o=Math.ceil(v/16),r=n.getEngine().getCaps().maxTextureSize,i=Math.ceil(s/r);p=t.AllocateShBuffers(o,i*r*4*4),y=new Int32Array(o),b=new Int32Array(o);for(let e=0;e<o;e++)y[e]=16*e,b[e]=Math.min(16*(e+1),v);x=p,_=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 p=255*(.5+Yh*c[s+0]),f=255*(.5+Yh*c[s+1]),m=255*(.5+Yh*c[s+2]);a[n+24]=p<=0?0:p>=255?255:p+.5|0,a[n+25]=f<=0?0:f>=255?255:f+.5|0,a[n+26]=m<=0?0:m>=255?255:m+.5|0,a[n+27]=1/(1+Math.exp(-d[e]))*255+.5|0;const g=127.5*h[r+3]+127.5,T=127.5*h[r+0]+127.5,A=127.5*h[r+1]+127.5,w=127.5*h[r+2]+127.5;if(a[n+28]=g<=0?0:g>=255?255:g+.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]=w<=0?0:w>=255?255:w+.5|0,_&&x&&y&&b){const t=e*v,n=16*e;for(let e=0;e<x.length;e++){const o=x[e],s=y[e],r=b[e];for(let e=s;e<r;e++){const r=128*_[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){m=e.safeOrbitRadiusMin,g=[e.safeOrbitElevationMin,e.safeOrbitElevationMax];break}}return{mode:0,data:r,hasVertexColors:!1,sh:null!==p?p:void 0,shDegree:f>0?f:void 0,trainedWithAntialiasing:!!e.antialiased,safeOrbitCameraRadiusMin:m,safeOrbitCameraElevationMinMax:g}}(e,n,!0),t.createYieldingScheduler())})}(e.loadSpzFromBuffer(new Uint8Array(o),{to:e.CoordinateSystem.RUB}),n).then(e=>new Promise(t=>{f(e,t)})));if(p)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 m=new ReadableStream({start(e){e.enqueue(new Uint8Array(o)),e.close()}}),g=new DecompressionStream("gzip"),_=m.pipeThrough(g);return new Promise(e=>{new Response(_).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),p=new Int32Array(1),f=new Uint8Array(p.buffer),m=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,p[0]*h};let g=16;const _=new Float32Array(d),v=new Float32Array(d),y=new Uint8ClampedArray(d),b=new Uint8ClampedArray(d);for(let e=0;e<r;e++)_[8*e+0]=m(o,g+0),_[8*e+1]=m(o,g+3),_[8*e+2]=m(o,g+6),g+=9;for(let e=0;e<r;e++){for(let n=0;n<3;n++){const s=(o[g+r+3*e+n]-127.5)/38.25;y[32*e+24+n]=t.Scalar.Clamp(255*(.5+Yh*s),0,255)}y[32*e+24+3]=o[g+e]}g+=4*r;for(let e=0;e<r;e++)v[8*e+3+0]=Math.exp(o[g+0]/16-10),v[8*e+3+1]=Math.exp(o[g+1]/16-10),v[8*e+3+2]=Math.exp(o[g+2]/16-10),g+=3;if(c>=3){const e=Math.SQRT1_2;for(let t=0;t<r;t++){const n=[o[g+0],o[g+1],o[g+2],o[g+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]]);g+=4}}else for(let e=0;e<r;e++){const t=o[g+0],n=o[g+1],s=o[g+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),g+=3}if(i){const e=3*((i+1)*(i+1)-1),s=Math.ceil(e/16);let a=g;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,uint16:2,uchar:1,list:0};let p=1;const f=[],m=[],g=o.slice(0,s).split("\n"),_={};for(const n of g)if(n.startsWith("property ")){const[,o,s]=n.split(" ");if(1==p)m.push({name:s,type:o,offset:d}),d+=h[o];else if(0==p)f.push({name:s,type:o,offset:c}),c+=h[o];else if(2==p)f.push({name:s,type:o,offset:c});else if(3==p){const t=new DataView(e,d,2*h.float);_.safeOrbitCameraElevationMinMax=[t.getFloat32(0,!0),t.getFloat32(4,!0)]}else if(4==p){const t=new DataView(e,d,h.float);_.safeOrbitCameraRadiusMin=t.getFloat32(0,!0)}else if(5==p){const t=new DataView(e,d,h.uchar);"up_axis"==s?_.upAxis=0==t.getUint8(0)?"X":1==t.getUint8(0)?"Y":"Z":"chirality"==s&&(_.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?p=1:"vertex"==e?p=0:"sh"==e?p=2:"safe_orbit_camera_elevation_min_max_radians"==e?p=3:"safe_orbit_camera_radius_min"==e?p=4:"up_axis"!=e&&"chirality"!=e||(p=5)}const v=c,y=d;return t.GaussianSplattingMesh.ConvertPLYWithSHToSplatAsync(e).then(t=>b(this,void 0,void 0,function*(){const n=new DataView(e,s+11);let o=y*u+v*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 p=l==d.length&&c>=3,m=a?2:p?0:1;return yield new Promise(e=>{e(Object.assign(Object.assign({},_),{mode:m,data:t.buffer,sh:t.sh,shDegree:t.shDegree,faces:i,hasVertexColors:!!c,compressed:!1,rawSplat:!1}))})}))}}Jh._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 ep=!1;function tp(){ep||(ep=!0,t.RegisterSceneLoaderPlugin(new Jh))}var np={__proto__:null,RegisterSPLATFileLoader:tp,SPLATFileLoader:Jh};tp();const op={name:"usd",extensions:{".usd":{isBinary:!0},".usda":{isBinary:!0},".usdc":{isBinary:!0},".usdz":{isBinary:!0}}};var sp,rp,ip,ap;const lp=4294967295;var up,cp,dp,hp,pp,fp,mp,gp,_p,vp;function yp(e){switch(e){case 1:case 11:return 12;case 2:return 48;case 3:return 96;case 4:case 5:return 20;case 6:return 60;case 7:return 40;case 8:return 16;case 9:case 12:return 32;case 10:return 44;default:throw new Error(`Unknown OpenUSD Babylon command opcode ${e}.`)}}!function(e){e[e.Scene=1]="Scene",e[e.Texture=2]="Texture",e[e.Material=3]="Material",e[e.TransformNode=4]="TransformNode",e[e.Skeleton=5]="Skeleton",e[e.Geometry=6]="Geometry",e[e.Mesh=7]="Mesh",e[e.Instance=8]="Instance",e[e.Animation=9]="Animation",e[e.AnalyticPrimitive=10]="AnalyticPrimitive",e[e.ThinInstances=11]="ThinInstances",e[e.MorphTarget=12]="MorphTarget"}(up||(up={})),function(e){e[e.Cube=0]="Cube",e[e.Sphere=1]="Sphere",e[e.Cylinder=2]="Cylinder",e[e.Cone=3]="Cone"}(cp||(cp={})),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(dp||(dp={})),function(e){e[e.Node=0]="Node",e[e.Bone=1]="Bone",e[e.MorphTarget=2]="MorphTarget"}(hp||(hp={})),function(e){e[e.Position=0]="Position",e[e.RotationQuaternion=1]="RotationQuaternion",e[e.Scaling=2]="Scaling",e[e.Matrix=3]="Matrix",e[e.Influence=4]="Influence"}(pp||(pp={})),function(e){e[e.DoubleSided=1]="DoubleSided",e[e.Unlit=2]="Unlit",e[e.AlphaBlend=4]="AlphaBlend"}(fp||(fp={})),function(e){e[e.R=0]="R",e[e.G=1]="G",e[e.B=2]="B",e[e.A=3]="A",e[e.RGB=4]="RGB"}(mp||(mp={})),function(e){e[e.Auto=0]="Auto",e[e.Raw=1]="Raw",e[e.SRGB=2]="SRGB"}(gp||(gp={})),function(e){e[e.DoubleSided=1]="DoubleSided",e[e.LeftHanded=2]="LeftHanded"}(_p||(_p={})),function(e){e[e.Normals=1]="Normals",e[e.Tangents=2]="Tangents",e[e.Uv0=4]="Uv0",e[e.Colors=8]="Colors",e[e.Skin0=16]="Skin0",e[e.Skin1=32]="Skin1"}(vp||(vp={}));class bp{constructor(e,t,n){sp.add(this),rp.set(this,void 0),ip.set(this,void 0),T(this,rp,new DataView(e),"f"),this.offset=t,T(this,ip,t+n,"f")}u32(){x(this,sp,"m",ap).call(this,4);const e=x(this,rp,"f").getUint32(this.offset,!0);return this.offset+=4,e}f32(){x(this,sp,"m",ap).call(this,4);const e=x(this,rp,"f").getFloat32(this.offset,!0);return this.offset+=4,e}}rp=new WeakMap,ip=new WeakMap,sp=new WeakSet,ap=function(e){if(this.offset+e>x(this,ip,"f"))throw new Error("OpenUSD Babylon command payload read exceeded its bounds.")};class xp extends t.AbstractAssetContainer{dispose(){for(const e of this.animationGroups.splice(0))e.dispose();for(const e of this.meshes.splice(0))e.dispose();for(const e of this.morphTargetManagers.splice(0))e.dispose();for(const e of this.skeletons.splice(0))e.dispose();for(const e of this.multiMaterials.splice(0))e.dispose();for(const e of this.materials.splice(0))e.dispose();for(const e of this.geometries.splice(0))e.dispose();for(const e of this.transformNodes.splice(0))e.dispose();for(const e of this.textures.splice(0))e.dispose();this.rootNodes.length=0}}const Tp=new TextDecoder,Ap="__babylonUsdLocalMatrix";function wp(e,t,n,o,s){if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<0||t%Math.min(o,4)!==0||n>Math.floor((e.byteLength-t)/o))throw new Error(`Invalid ${s} range in OpenUSD Babylon data buffer.`)}function Mp(e,t,n){return wp(e,t,n,1,"string"),Tp.decode(new Uint8Array(e,t,n))}function Sp(e,n){wp(e,n,16,4,"matrix");const o=new Float32Array(e,n,16);return t.Matrix.FromValues(o[0],o[1],o[2],o[3],o[4],o[5],o[6],o[7],o[8],o[9],o[10],o[11],o[12],o[13],o[14],o[15])}function Rp(e){switch(e){case 2:return"image/jpeg";case 3:return"image/bmp";case 4:return"image/webp";default:return"image/png"}}function Cp(e){switch(e){case 0:return t.Texture.CLAMP_ADDRESSMODE;case 1:return t.Texture.WRAP_ADDRESSMODE;case 2:return t.Texture.MIRROR_ADDRESSMODE;default:throw new Error(`Invalid texture wrap mode ${e}.`)}}function Ip(e,t){return b(this,void 0,void 0,function*(){if(!t)return yield e;let n;const o=new Promise((e,o)=>{n=()=>o(t.reason instanceof Error?t.reason:new Error("USD materialization was aborted.")),t.addEventListener("abort",n,{once:!0}),t.aborted&&n()});try{return yield Promise.race([e,o])}finally{n&&t.removeEventListener("abort",n)}})}const Op=`${t.Tools._DefaultCdnUrl}/babylonUsdImporter/5/`,Fp=/\.(?:usd|usda|usdc|usdz)$/i;function Ep(e){return e instanceof Uint8Array?e.slice():e instanceof ArrayBuffer?new Uint8Array(e.slice(0)):new Uint8Array(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength))}function Np(e,t,n){const o=null==e?void 0:e.replace(/\\/g,"/").replace(/^\.\/+/,""),s=n?o:null==o?void 0:o.split(/[?#]/,1)[0],r=null==s?void 0:s.split("/").filter(Boolean);return s&&!s.startsWith("/")&&(null==r?void 0:r.length)&&!r.includes("..")&&Fp.test(s)?r.join("/"):t.length>=4&&80===t[0]&&75===t[1]&&3===t[2]&&4===t[3]?"scene.usdz":"scene.usd"}class Lp{constructor(e={}){var t,n,o,s,r;this.name=op.name,this.extensions=op.extensions,this._nextRequestId=1,this._pending=new Map,this._activeLoads=new Set,this._options=Object.assign(Object.assign({},e),{resolveByFileName:null===(t=e.resolveByFileName)||void 0===t||t,glueUrl:null!==(n=e.glueUrl)&&void 0!==n?n:Lp.DefaultConfiguration.glueUrl,wasmUrl:null!==(o=e.wasmUrl)&&void 0!==o?o:Lp.DefaultConfiguration.wasmUrl,dataUrl:null!==(s=e.dataUrl)&&void 0!==s?s:Lp.DefaultConfiguration.dataUrl,workerUrl:null!==(r=e.workerUrl)&&void 0!==r?r:Lp.DefaultConfiguration.workerUrl})}createPlugin(e){return Bp(),new Lp(e[op.name])}importMeshAsync(e,t,n,o,s,r){return b(this,void 0,void 0,function*(){return{meshes:(e=(yield this._loadAsync(t,n,o,s,r,!0)).container).meshes,particleSystems:e.particleSystems,skeletons:e.skeletons,animationGroups:e.animationGroups,transformNodes:e.transformNodes,geometries:e.geometries,lights:e.lights,spriteManagers:e.spriteManagers};var e})}loadAsync(e,t,n,o,s){return b(this,void 0,void 0,function*(){yield this._loadAsync(e,t,n,o,s,!0)})}loadAssetContainerAsync(e,n,o,s,r){return b(this,void 0,void 0,function*(){const i=(yield this._loadAsync(e,n,o,s,r,!1)).container;if(!(i instanceof t.AssetContainer))throw new Error("USDFileLoader failed to create an asset container.");return i})}dispose(){this._terminateWorker();const e=new Error("USDFileLoader was disposed.");for(const t of this._activeLoads)t.abort(e);for(const t of this._pending.values())t.reject(e);this._pending.clear()}_loadAsync(e,n,o,s,r,i){return b(this,void 0,void 0,function*(){var o,a,l,u,c,d;if(!(n instanceof ArrayBuffer||ArrayBuffer.isView(n)))throw new Error("USDFileLoader expects binary USD data.");const h=Ep(n),p=function(e){if(!e)return;const t={};for(const[n,o]of Object.entries(e))t[n]=Ep(o);return t}(this._options.files),f=this._nextRequestId++,m={type:"extract",requestId:f,asset:{bytes:h,files:p,fileName:Np(null!==(o=this._options.rootFileName)&&void 0!==o?o:r,h,void 0!==this._options.rootFileName),resolveByFileName:null===(a=this._options.resolveByFileName)||void 0===a||a,glueUrl:this._options.glueUrl,wasmUrl:this._options.wasmUrl,dataUrl:this._options.dataUrl}},g=[...new Set([h.buffer,...Object.values(null!=p?p:{}).map(e=>e.buffer)])],_=new AbortController,v=_.signal;this._activeLoads.add(_);try{const n=this._getWorker(this._options.workerUrl),o=yield new Promise((e,t)=>{this._pending.set(f,{resolve:e,reject:t,onProgress:e=>{var t,n;null===(n=(t=this._options).onProgress)||void 0===n||n.call(t,e),null==s||s({lengthComputable:!1,loaded:kp[e.phase],total:4})},onLog:this._options.onLog});try{n.postMessage(m,g)}catch(e){this._pending.delete(f),t(e instanceof Error?e:new Error(String(e)))}}),r={phase:"materializing",message:"Creating Babylon.js objects..."};null===(u=(l=this._options).onProgress)||void 0===u||u.call(l,r),null==s||s({lengthComputable:!1,loaded:4,total:4}),v.throwIfAborted();const a=yield function(e,n,o,s,r){return b(this,void 0,void 0,function*(){var i,a,l,u,c,d,h,p,f;null==r||r.throwIfAborted();const m=performance.now(),g=function(e){const t=new DataView(e);if(t.byteLength<16||1111774037!==t.getUint32(0,!0))throw new Error("Invalid OpenUSD Babylon command buffer.");if(5!==t.getUint16(4,!0))throw new Error(`Unsupported OpenUSD Babylon protocol ${t.getUint16(4,!0)}.`);const n=t.getUint32(8,!0),o=[];let s=16;for(let e=0;e<n;++e){if(s+8>t.byteLength)throw new Error("Truncated OpenUSD Babylon command header.");const e=t.getUint16(s,!0),n=t.getUint16(s+2,!0),r=t.getUint32(s+4,!0),i=s+8,a=yp(e);if(r!==a)throw new Error(`Invalid payload length ${r} for command ${e}; expected ${a}.`);if(i+r>t.byteLength)throw new Error("Truncated OpenUSD Babylon command payload.");o.push({opcode:e,flags:n,payloadOffset:i,payloadLength:r}),s=i+r}if(s!==t.byteLength)throw new Error("Unexpected trailing data in OpenUSD Babylon command buffer.");return o}(n),_=s?new xp:new t.AssetContainer(e),v=new Map,y=[],x=new Map,T=new Map,A=new Map,w=new Map,M=new Map,S=new Map,R=new Map,C=new Map,I=new Map,O=new Set,F=new Set,E=new Map,N=[],L=new Set,k=[],P=new Map,B=_ instanceof t.AssetContainer?_:void 0;let D,V=24,G=!1;const $=e.getEngine().getCaps(),U=$.textureHalfFloatRender&&$.textureHalfFloatLinearFiltering?t.Constants.TEXTURETYPE_HALF_FLOAT:$.textureFloatRender&&$.textureFloatLinearFiltering?t.Constants.TEXTURETYPE_FLOAT:t.Constants.TEXTURETYPE_UNSIGNED_BYTE,H=(e,t)=>{e.push(t),B&&(t._parentContainer=B)},K=(n,o)=>{const s=!(2&o);n.sideOrientation=e.useRightHandedSystem===s?t.Material.CounterClockWiseSideOrientation:t.Material.ClockWiseSideOrientation},j=(e,t)=>{const n=T.get(e);if(!n||!t||!n.backFaceCulling)return null!=n?n:null;let o=A.get(e);return o||(o=n.clone(`${n.name} (double-sided)`),H(_.materials,o),o.backFaceCulling=!1,o.twoSidedLighting=!0,A.set(e,o)),o},W=(e,t,n)=>{if(e===lp){if(t!==lp)throw new Error(`USD ${n} binding has a channel without a texture.`);return}const o=x.get(e);if(!o)throw new Error(`USD ${n} binding references missing texture ${e}.`);if(t<0||t>4)throw new Error(`USD ${n} binding has invalid output channel ${t}.`);return{descriptor:o,channel:t}},q=e=>{if(4===e)throw new Error("A scalar USD texture binding cannot use the RGB output.");return e},z=e=>1===e.descriptor.sourceColorSpace,X=(e,t,n)=>t.every((t,n)=>e.scale[n]===t)&&n.every((t,n)=>e.bias[n]===t),Y=(n,o,s,i,...a)=>b(this,[n,o,s,i,...a],void 0,function*(n,o,s,i,a=o.channel,l=!1){const u=o.descriptor,c=u.texture.getSize(),d=!(e.getEngine().needPOTTextures&&(c.width&c.width-1||c.height&c.height-1)),h={textureType:l?U:t.Constants.TEXTURETYPE_UNSIGNED_BYTE,samplingMode:d?t.Constants.TEXTURE_TRILINEAR_SAMPLINGMODE:t.Constants.TEXTURE_BILINEAR_SAMPLINGMODE,generateMipMaps:d};if(l&&U===t.Constants.TEXTURETYPE_UNSIGNED_BYTE&&s.slice(0,3).some((e,t)=>Math.min(i[t],i[t]+e)<0))throw new Error(`USD texture processing for '${n}' requires a floating-point render target to preserve signed values.`);const p=`${u.id}:${a}:${s.join(",")}:${i.join(",")}:${l}`,f=P.get(p);if(f)return yield f;const m=(()=>b(this,void 0,void 0,function*(){var o;const l=new t.Color4(i[0],i[1],i[2],i[3]),c=new t.Color4(i[0]+s[0],i[1]+s[1],i[2]+s[2],i[3]+s[3]),d=e._blockEntityCollection;let p;e._blockEntityCollection=!0;try{p=t.LerpTexturesAsync(n,t.CreateFactorOperand(l),t.CreateFactorOperand(c),t.CreateTextureOperand(u.texture,(e=>{switch(e){case 0:return t.TextureChannel.R;case 1:return t.TextureChannel.G;case 2:return t.TextureChannel.B;case 3:return t.TextureChannel.A;default:return t.TextureChannel.RGBA}})(a),1===u.sourceColorSpace?t.TextureColorSpace.Linear:t.TextureColorSpace.SRGB),e,t.TextureColorSpace.Linear,void 0,h)}finally{e._blockEntityCollection=d}const f=yield p;if(!f.texture)throw new Error(`USD texture processing for '${n}' did not produce a texture.`);if(G||(null==r?void 0:r.aborted))throw null===(o=f.dispose)||void 0===o||o.call(f),(null==r?void 0:r.aborted)&&r.throwIfAborted(),new Error("USD materialization was rolled back.");B||e.addTexture(f.texture);const m=(e=>(H(_.textures,e),e))(f.texture);m.gammaSpace=!1;const g=m;return g.uRotationCenter=u.texture.uRotationCenter,g.vRotationCenter=u.texture.vRotationCenter,g.wRotationCenter=u.texture.wRotationCenter,g.homogeneousRotationInUVTransform=u.texture.homogeneousRotationInUVTransform,m}))();P.set(p,m);try{return yield m}catch(e){throw P.delete(p),e}}),Q=(e,t)=>b(this,void 0,void 0,function*(){const n=q(t.channel),o=t.descriptor.scale[n],s=t.descriptor.bias[n];return yield Y(e,t,[o,o,o,1],[s,s,s,0],t.channel)}),Z=e=>b(this,void 0,void 0,function*(){var n,o,s,r;const{material:i,normalScale:a,base:l,opacity:u,normal:c,metallic:d,roughness:h,occlusion:p,emissive:f}=e;if(l){if(4!==l.channel)throw new Error("A USD base-color texture must use the RGB output.");i.albedoColor=t.Color3.White(),i.albedoTexture=X(l.descriptor,[1,1,1,1],[0,0,0,0])?l.descriptor.texture:yield Y(`${i.name} base color`,l,l.descriptor.scale,l.descriptor.bias)}if(f){if(4!==f.channel)throw new Error("A USD emissive texture must use the RGB output.");const e=f.descriptor;if(e.bias.slice(0,3).every(e=>0===e))i.emissiveColor=new t.Color3(e.scale[0],e.scale[1],e.scale[2]),i.emissiveTexture=e.texture;else{const n=Array.from({length:3},(t,n)=>Math.max(1,Math.abs(e.bias[n]),Math.abs(e.bias[n]+e.scale[n]))),o=e.scale.map((e,t)=>t<3?e/n[t]:e),s=e.bias.map((e,t)=>t<3?e/n[t]:e);i.emissiveColor=new t.Color3(n[0],n[1],n[2]),i.emissiveTexture=yield Y(`${i.name} emissive`,f,o,s,f.channel,!0)}}if(c){if(4!==c.channel)throw new Error("A USD normal texture must use the RGB output.");if(1===c.descriptor.sourceColorSpace&&X(c.descriptor,[2,2,2,1],[-1,-1,-1,0]))i.bumpTexture=c.descriptor.texture;else{const e=Array.from(c.descriptor.scale,e=>.5*e),t=Array.from(c.descriptor.bias,(e,t)=>t<3?.5*(e+1):e);i.bumpTexture=yield Y(`${i.name} normal`,c,e,t)}i.bumpTexture.gammaSpace=!1,i.bumpTexture.level=a}let m=!1;if(!d||!h||d.descriptor!==h.descriptor||0!==d.channel&&2!==d.channel||1!==h.channel&&3!==h.channel||!z(d)||0!==d.descriptor.bias[q(d.channel)]||0!==h.descriptor.bias[q(h.channel)]){if(d){const e=q(d.channel),t=z(d)&&(0===d.channel||2===d.channel)&&0===d.descriptor.bias[e];i.metallicTexture=t?d.descriptor.texture:yield Q(`${i.name} metallic`,d),i.useRoughnessFromMetallicTextureAlpha=!1,i.useRoughnessFromMetallicTextureGreen=!1,i.useMetallnessFromMetallicTextureBlue=t&&2===d.channel,i.metallic=t?(null!==(s=i.metallic)&&void 0!==s?s:1)*d.descriptor.scale[e]:1}if(h){const e=q(h.channel),t=z(h)&&0===h.channel&&0===h.descriptor.bias[e];i.microSurfaceTexture=t?h.descriptor.texture:yield Q(`${i.name} roughness`,h),i.microSurfaceTexture.gammaSpace=!!t&&h.descriptor.texture.gammaSpace,i.roughness=t?(null!==(r=i.roughness)&&void 0!==r?r:1)*h.descriptor.scale[e]:1}}else{const e=d.descriptor;i.metallicTexture=e.texture,i.metallic=(null!==(n=i.metallic)&&void 0!==n?n:1)*e.scale[q(d.channel)],i.roughness=(null!==(o=i.roughness)&&void 0!==o?o:1)*e.scale[q(h.channel)],i.useRoughnessFromMetallicTextureAlpha=3===h.channel,i.useRoughnessFromMetallicTextureGreen=1===h.channel,i.useMetallnessFromMetallicTextureBlue=2===d.channel,m=(null==p?void 0:p.descriptor)===e&&0===p.channel&&1===e.scale[0]&&0===e.bias[0],i.useAmbientOcclusionFromMetallicTextureRed=m}if(p&&!m){const e=q(p.channel),t=z(p)&&0===p.channel&&1===p.descriptor.scale[e]&&0===p.descriptor.bias[e];i.ambientTexture=t?p.descriptor.texture:yield Q(`${i.name} occlusion`,p),i.useAmbientInGrayScale=!0}if(u)if(l&&i.albedoTexture&&u.descriptor===l.descriptor&&3===u.channel&&1===u.descriptor.scale[3]&&0===u.descriptor.bias[3])i.albedoTexture.hasAlpha=!0,i.useAlphaFromAlbedoTexture=!0;else{const e=3===u.channel&&1===u.descriptor.scale[3]&&0===u.descriptor.bias[3];i.opacityTexture=e?u.descriptor.texture:yield Q(`${i.name} opacity`,u),i.opacityTexture.gammaSpace=!!e&&u.descriptor.texture.gammaSpace,i.opacityTexture.getAlphaFromRGB=!e}const g=A.get(e.id);g&&(g.albedoColor.copyFrom(i.albedoColor),g.albedoTexture=i.albedoTexture,g.emissiveColor.copyFrom(i.emissiveColor),g.emissiveTexture=i.emissiveTexture,g.bumpTexture=i.bumpTexture,g.metallic=i.metallic,g.roughness=i.roughness,g.metallicTexture=i.metallicTexture,g.microSurfaceTexture=i.microSurfaceTexture,g.ambientTexture=i.ambientTexture,g.opacityTexture=i.opacityTexture,g.alpha=i.alpha,g.useAlphaFromAlbedoTexture=i.useAlphaFromAlbedoTexture,g.useRoughnessFromMetallicTextureAlpha=i.useRoughnessFromMetallicTextureAlpha,g.useRoughnessFromMetallicTextureGreen=i.useRoughnessFromMetallicTextureGreen,g.useMetallnessFromMetallicTextureBlue=i.useMetallnessFromMetallicTextureBlue,g.useAmbientOcclusionFromMetallicTextureRed=i.useAmbientOcclusionFromMetallicTextureRed,g.useAmbientInGrayScale=i.useAmbientInGrayScale)});try{const A=e._blockEntityCollection;s||(e._blockEntityCollection=!0);try{for(const s of g){const r=new bp(n,s.payloadOffset,s.payloadLength);switch(s.opcode){case 1:{const n=1===r.u32(),o=r.f32();V=r.f32()||24,D=new t.TransformNode("USD Root",e),H(_.transformNodes,D),_.rootNodes.push(D),D.rotationQuaternion=n?t.Quaternion.FromArray([-.7071068,0,0,.7071068]):t.Quaternion.Identity(),D.scaling.copyFrom(e.useRightHandedSystem?new t.Vector3(o,o,o):n?new t.Vector3(o,-o,o):new t.Vector3(o,o,-o));break}case 2:{const n=r.u32();if(x.has(n))throw new Error(`Duplicate USD texture ${n}.`);const s=r.u32(),i=r.u32(),a=Rp(r.u32()),l=r.u32(),u=r.u32(),c=r.u32(),d=r.u32(),h=r.u32(),p=r.u32(),f=r.u32(),m=r.u32();if(wp(o,d,5,4,"texture transform"),wp(o,m,8,4,"texture value transform"),wp(o,l,u,1,"texture image"),f<0||f>2)throw new Error(`Invalid USD texture color space ${f}.`);const g=new Float32Array(o,d,5),v=new Float32Array(o,m,8);if(![...g,...v].every(Number.isFinite))throw new Error(`USD texture ${n} has a non-finite transform.`);const y=new Uint8Array(o,l,u),b=URL.createObjectURL(new Blob([y],{type:a}));let T,A;L.add(b);const w=new Promise((e,t)=>{T=e,A=t});N.push(w);const M=new t.Texture(b,e,!1,!1,t.Texture.TRILINEAR_SAMPLINGMODE,T,(e,t)=>{URL.revokeObjectURL(b),A(t instanceof Error?t:new Error(e||`Could not load texture '${b}'.`))});H(_.textures,M),M.onDisposeObservable.addOnce(()=>URL.revokeObjectURL(b)),M.name=Mp(o,s,i),M.coordinatesIndex=c,M.uScale=g[0],M.vScale=g[1],M.uRotationCenter=0,M.vRotationCenter=0,M.uOffset=g[2]-g[1]*Math.sin(g[4]),M.vOffset=1-g[1]*Math.cos(g[4])-g[3],M.wAng=-g[4],M.wrapU=Cp(h),M.wrapV=Cp(p),M.gammaSpace=1!==f,x.set(n,{id:n,texture:M,sourceColorSpace:f,scale:v.subarray(0,4),bias:v.subarray(4,8)});break}case 3:{const n=r.u32(),s=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=r.f32(),c=r.f32(),d=r.f32(),h=r.f32(),p=r.u32(),f=Array.from({length:7},()=>r.u32()),m=Array.from({length:7},()=>r.u32());wp(o,a,4,4,"material base color"),wp(o,l,3,4,"material emissive color");const g=new Float32Array(o,a,4),v=new Float32Array(o,l,3),y=new t.PBRMaterial(Mp(o,s,i),e);H(_.materials,y),y.id=`usd-material-${n}`,y.albedoColor=new t.Color3(g[0],g[1],g[2]),y.alpha=g[3],y.metallic=u,y.roughness=c,y.emissiveColor=new t.Color3(v[0],v[1],v[2]);const b=Boolean(1&p);y.backFaceCulling=!b,y.twoSidedLighting=b,y.unlit=Boolean(2&p),4&p&&(y.transparencyMode=2),h>0&&(y.transparencyMode=1,y.alphaCutOff=h),k.push({id:n,material:y,normalScale:d,base:W(f[0],m[0],"base-color texture"),opacity:W(f[1],m[1],"opacity texture"),normal:W(f[2],m[2],"normal texture"),metallic:W(f[3],m[3],"metallic texture"),roughness:W(f[4],m[4],"roughness texture"),occlusion:W(f[5],m[5],"occlusion texture"),emissive:W(f[6],m[6],"emissive texture")}),T.set(n,y);break}case 4:{const n=r.u32(),s=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=new t.TransformNode(Mp(o,i,a),e);H(_.transformNodes,u),u.setPreTransformMatrix(Sp(o,l)),Object.defineProperty(u,Ap,{configurable:!0,get:()=>u.getPivotMatrix(),set:e=>u.setPreTransformMatrix(e)}),v.set(n,u),s===lp?u.parent=null!=D?D:null:y.push({node:u,parentId:s});break}case 5:{const n=r.u32(),s=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=new t.Skeleton(Mp(o,s,i),`usd-skeleton-${n}`,e);H(_.skeletons,u);const c=new DataView(o);wp(o,l,6*a,4,"skeleton joints");const d=[];for(let e=0;e<a;++e){const s=l+24*e,r=c.getUint32(s,!0),i=c.getUint32(s+4,!0),a=c.getUint32(s+8,!0),h=c.getUint32(s+12,!0),p=c.getUint32(s+16,!0),f=c.getUint32(s+20,!0);if(r!==lp&&r>=e)throw new Error(`Skeleton ${n} has an invalid parent joint index.`);const m=new t.Bone(Mp(o,a,h),u,r===lp?null:d[r],Sp(o,p),Sp(o,p),Sp(o,f),e);d.push(m),M.set(i,m)}w.set(n,u);break}case 6:{const e=r.u32();S.set(e,{vertexCount:r.u32(),indexCount:r.u32(),flags:r.u32(),positions:r.u32(),normals:r.u32(),tangents:r.u32(),uv0:r.u32(),colors:r.u32(),joints0:r.u32(),weights0:r.u32(),joints1:r.u32(),weights1:r.u32(),indices:r.u32(),influences:r.u32()});break}case 7:{const n=r.u32(),s=r.u32(),u=r.u32(),c=r.u32(),d=r.u32(),h=r.u32(),p=r.u32(),f=r.u32(),m=r.u32(),g=r.u32(),y=S.get(u);if(!y)throw new Error(`Mesh ${n} references missing geometry ${u}.`);const b=new t.Mesh(Mp(o,d,h),e);H(_.meshes,b),K(b,p),b.parent=null!==(a=null!==(i=v.get(s))&&void 0!==i?i:D)&&void 0!==a?a:null;const x=new t.VertexData;wp(o,y.positions,3*y.vertexCount,4,"positions"),x.positions=new Float32Array(o,y.positions,3*y.vertexCount),1&y.flags&&(wp(o,y.normals,3*y.vertexCount,4,"normals"),x.normals=new Float32Array(o,y.normals,3*y.vertexCount)),2&y.flags&&(wp(o,y.tangents,4*y.vertexCount,4,"tangents"),x.tangents=new Float32Array(o,y.tangents,4*y.vertexCount)),4&y.flags&&(wp(o,y.uv0,2*y.vertexCount,4,"texture coordinates"),x.uvs=new Float32Array(o,y.uv0,2*y.vertexCount)),8&y.flags&&(wp(o,y.colors,4*y.vertexCount,4,"vertex colors"),x.colors=new Float32Array(o,y.colors,4*y.vertexCount)),16&y.flags&&(wp(o,y.joints0,4*y.vertexCount,2,"joint indices"),wp(o,y.weights0,4*y.vertexCount,4,"joint weights"),x.matricesIndices=Float32Array.from(new Uint16Array(o,y.joints0,4*y.vertexCount)),x.matricesWeights=new Float32Array(o,y.weights0,4*y.vertexCount)),32&y.flags&&(wp(o,y.joints1,4*y.vertexCount,2,"extra joint indices"),wp(o,y.weights1,4*y.vertexCount,4,"extra joint weights"),x.matricesIndicesExtra=Float32Array.from(new Uint16Array(o,y.joints1,4*y.vertexCount)),x.matricesWeightsExtra=new Float32Array(o,y.weights1,4*y.vertexCount)),wp(o,y.indices,y.indexCount,4,"indices"),x.indices=new Uint32Array(o,y.indices,y.indexCount),x.applyToMesh(b,!0),b.geometry&&H(_.geometries,b.geometry),b.numBoneInfluencers=Math.min(y.influences,8),f!==lp&&(b.skeleton=null!==(l=w.get(f))&&void 0!==l?l:null);const T=new DataView(o);wp(o,m,5*g,4,"submeshes");const A=Boolean(1&p);if(1===g&&c!==lp)b.material=j(c,A);else{const n=new t.MultiMaterial(`${b.name} materials`,e);H(_.multiMaterials,n);for(let e=0;e<g;++e){const t=m+20*e;n.subMaterials.push(j(T.getUint32(t,!0),A))}b.material=n}b.releaseSubMeshes();for(let e=0;e<g;++e){const n=m+20*e;new t.SubMesh(e,T.getUint32(n+12,!0),T.getUint32(n+16,!0),T.getUint32(n+4,!0),T.getUint32(n+8,!0),b)}R.set(n,b);break}case 12:{const n=r.u32(),s=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=r.u32(),c=r.u32(),d=r.f32(),h=R.get(s);if(!h)throw new Error(`Morph target references missing mesh ${s}.`);if(I.has(n)||l!==h.getTotalVertices()||!Number.isFinite(d))throw new Error(`Morph target ${n} has invalid metadata.`);wp(o,u,3*l,4,"morph target positions");let p=C.get(s);p||(p=new t.MorphTargetManager(e,h.name),p.areUpdatesFrozen=!0,H(_.morphTargetManagers,p),C.set(s,p));const f=new t.MorphTarget(Mp(o,i,a),d,e,p);f.id=`usd-morph-target-${n}`,f.setPositions(new Float32Array(o,u,3*l)),c!==lp&&(wp(o,c,3*l,4,"morph target normals"),f.setNormals(new Float32Array(o,c,3*l))),p.addTarget(f),I.set(n,f);break}case 10:{const n=r.u32(),s=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),d=r.u32(),h=r.u32(),p=r.u32(),f=r.f32(),m=r.f32(),g=r.u32(),y=Mp(o,l,d);if(!Number.isFinite(f)||f<=0)throw new Error(`Analytic primitive ${n} has an invalid size or radius.`);if((2===i||3===i)&&(!Number.isFinite(m)||m<=0))throw new Error(`Analytic primitive ${n} has an invalid height.`);if(0!==i&&(!Number.isInteger(g)||g<3||g>512))throw new Error(`Analytic primitive ${n} has invalid tessellation.`);let b;switch(i){case 0:b=t.CreateBox(y,{size:f},e);break;case 1:b=t.CreateSphere(y,{diameter:2*f,segments:g},e);break;case 2:case 3:b=t.CreateCylinder(y,{height:m,diameterTop:3===i?0:2*f,diameterBottom:2*f,tessellation:g},e);break;default:throw new Error(`Unsupported analytic primitive type ${i}.`)}if(H(_.meshes,b),b.geometry&&H(_.geometries,b.geometry),!(2&h)){const e=b.getIndices();if(!e)throw new Error(`Analytic primitive ${n} has no generated indices.`);const t=Array.from(e);for(let e=0;e<t.length;e+=3)[t[e],t[e+2]]=[t[e+2],t[e]];b.setIndices(t)}if(0===p)b.rotationQuaternion=t.Quaternion.RotationAxis(new t.Vector3(0,0,1),-Math.PI/2);else if(2===p)b.rotationQuaternion=t.Quaternion.RotationAxis(new t.Vector3(1,0,0),Math.PI/2);else if(1!==p)throw new Error(`Unsupported analytic primitive axis ${p}.`);K(b,h),b.parent=null!==(c=null!==(u=v.get(s))&&void 0!==u?u:D)&&void 0!==c?c:null,b.material=j(a,Boolean(1&h)),R.set(n,b);break}case 8:{const e=r.u32(),t=r.u32(),n=r.u32(),s=r.u32(),i=R.get(e);if(!i)throw new Error(`Instance references missing mesh ${e}.`);if(F.has(e))throw new Error(`Mesh ${e} cannot mix classic and thin instances.`);O.add(e);const a=i.createInstance(Mp(o,n,s));H(_.meshes,a),a.parent=null!==(h=null!==(d=v.get(t))&&void 0!==d?d:D)&&void 0!==h?h:null;break}case 11:{const e=r.u32(),t=r.u32(),n=r.u32(),s=R.get(e);if(!s)throw new Error(`Thin instances reference missing mesh ${e}.`);if(F.has(e)||O.has(e))throw new Error(`Mesh ${e} has duplicate or mixed thin instances.`);wp(o,t,16*n,4,"thin instance transforms"),s.thinInstanceSetBuffer("matrix",new Float32Array(o,t,16*n),16,!0),s.thinInstanceEnablePicking=!0,F.add(e);break}case 9:{const n=r.u32(),s=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=r.u32(),c=r.u32(),d=r.u32();if(0!==n&&1!==n&&2!==n)throw new Error(`Invalid animation target kind ${n}.`);if(2===n!=(4===i))throw new Error(`Invalid animation property ${i} for target kind ${n}.`);if(d!==(4===i?1:0===i||2===i?3:1===i?4:3===i?16:0))throw new Error(`Invalid animation value stride ${d} for property ${i}.`);const h=0===n?v.get(s):1===n?M.get(s):I.get(s);if(!h)break;const p=0===i?"position":1===i?"rotationQuaternion":2===i?"scaling":4===i?"influence":0===n?Ap:"_matrix",f=4===i?t.Animation.ANIMATIONTYPE_FLOAT:1===i?t.Animation.ANIMATIONTYPE_QUATERNION:3===i?t.Animation.ANIMATIONTYPE_MATRIX:t.Animation.ANIMATIONTYPE_VECTOR3,m=new t.Animation(`USD ${p}`,p,V,f,t.Animation.ANIMATIONLOOPMODE_CYCLE);wp(o,u,l,4,"animation times"),wp(o,c,l*d,4,"animation values");const g=new Float32Array(o,u,l),y=new Float32Array(o,c,l*d);m.setKeys(Array.from({length:l},(e,n)=>({frame:g[n],value:f===t.Animation.ANIMATIONTYPE_QUATERNION?t.Quaternion.FromArray(y,n*d):f===t.Animation.ANIMATIONTYPE_MATRIX?t.Matrix.FromArray(y,n*d):f===t.Animation.ANIMATIONTYPE_FLOAT?y[n*d]:t.Vector3.FromArray(y,n*d)})));let b=E.get(a);b||(b=new t.AnimationGroup(`USD Animation ${a+1}`,e),E.set(a,b),H(_.animationGroups,b)),b.addTargetedAnimation(m,h);break}}}for(const[e,n]of C)n.areUpdatesFrozen=!1,!n.isUsingTextureForTargets&&n.numTargets<=t.MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode&&(n.optimizeInfluencers=!1,n.numMaxInfluencers=n.numTargets),R.get(e).morphTargetManager=n}finally{s||(e._blockEntityCollection=A)}yield Ip(Promise.all(N),r),yield Ip(Promise.all(k.map(e=>b(this,void 0,void 0,function*(){yield Z(e)}))),r);for(const{node:e,parentId:t}of y)e.parent=null!==(f=null!==(p=v.get(t))&&void 0!==p?p:D)&&void 0!==f?f:null;return{container:_,materializeMs:performance.now()-m}}catch(e){G=!0,Promise.allSettled(N),Promise.allSettled(P.values()),_.dispose();for(const e of L)URL.revokeObjectURL(e);throw e}})}(e,o.commands,o.data,i,v),h={container:a.container,timings:Object.assign(Object.assign({},o.timings),{materializeMs:a.materializeMs}),statistics:o.statistics,missingAssets:o.missingAssets};try{v.throwIfAborted(),null===(d=(c=this._options).onComplete)||void 0===d||d.call(c,{timings:h.timings,statistics:h.statistics,missingAssets:h.missingAssets}),v.throwIfAborted()}catch(e){throw a.container.dispose(),e}return h}finally{this._activeLoads.delete(_),0===this._pending.size&&this._terminateWorker()}})}_getWorker(e){var t;if(!e)throw new Error("The USD worker URL was not configured.");const n=globalThis.location,o=new URL(String(e),null!==(t=null==n?void 0:n.href)&&void 0!==t?t:"http://localhost/").href;if(this._worker&&this._workerUrl!==o){if(this._pending.size>0)throw new Error("Cannot change the USD worker URL while requests are pending.");this._terminateWorker()}if(this._worker)return this._worker;this._workerUrl=o,n&&new URL(o).origin!==n.origin?(this._workerBlobUrl=URL.createObjectURL(new Blob([`import ${JSON.stringify(o)};`],{type:"application/javascript"})),this._worker=new Worker(this._workerBlobUrl,{type:"module"})):this._worker=new Worker(o,{type:"module"}),this._worker.addEventListener("message",e=>{var t,n;const o=e.data,s=this._pending.get(o.requestId);if(s)if("progress"!==o.type)if("log"!==o.type)if(this._pending.delete(o.requestId),"error"===o.type){const e=new Error(o.message);e.stack=o.stack,s.reject(e)}else s.resolve(o);else null===(n=s.onLog)||void 0===n||n.call(s,o.level>=2?"error":1===o.level?"warning":"info",o.message);else null===(t=s.onProgress)||void 0===t||t.call(s,o.progress)});const s=e=>{this._terminateWorker();for(const t of this._pending.values())t.reject(e);this._pending.clear()};return this._worker.addEventListener("error",e=>{var t;s(null!==(t=e.error)&&void 0!==t?t:new Error(e.message||`Could not load the USD worker from '${o}'.`))}),this._worker.addEventListener("messageerror",()=>{s(new Error("The USD worker returned a message that could not be deserialized."))}),this._worker}_terminateWorker(){var e;null===(e=this._worker)||void 0===e||e.terminate(),this._worker=void 0,this._workerUrl=void 0,this._workerBlobUrl&&(URL.revokeObjectURL(this._workerBlobUrl),this._workerBlobUrl=void 0)}}Lp.DefaultConfiguration={glueUrl:`${Op}babylon-usd-importer.js`,wasmUrl:`${Op}babylon-usd-importer.wasm`,dataUrl:`${Op}babylon-usd-importer.data`,workerUrl:`${Op}babylon-usd-importer.worker.js`};const kp={initializing:1,staging:2,extracting:3,materializing:4};let Pp=!1;function Bp(){t.RegisterPbrMaterial(),t.RegisterInstancedMesh(),t.RegisterThinInstanceMesh()}function Dp(){Pp||(Pp=!0,Bp(),t.RegisterSceneLoaderPlugin(new Lp))}var Vp={__proto__:null,RegisterUSDFileLoader:Dp,USDFileLoader:Lp,_RegisterUSDLoaderDependencies:Bp};function Gp(){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 v});return new t(e[f.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},xo),{createPlugin:e=>b(this,void 0,void 0,function*(){const{FBXFileLoader:t}=yield Promise.resolve().then(function(){return Go});return new t(e[xo.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},Wo),{createPlugin:e=>b(this,void 0,void 0,function*(){const[{GLTFFileLoader:t,RegisterGLTF2Loader:n},{RegisterInstancedMesh:o}]=yield Promise.all([Promise.resolve().then(function(){return Tr}),Promise.resolve(BABYLON)]);return o(),n(),new t(e[Wo.name])})})),function(){Ys("EXT_lights_image_based"),Xs("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 Gr});return new t(e)})),Ys("EXT_mesh_gpu_instancing"),Xs("EXT_mesh_gpu_instancing",!0,e=>b(this,void 0,void 0,function*(){const[{EXT_mesh_gpu_instancing:t},{RegisterThinInstanceMesh:n}]=yield Promise.all([Promise.resolve().then(function(){return jr}),Promise.resolve(BABYLON)]);return n(),new t(e)})),Ys("EXT_meshopt_compression"),Xs("EXT_meshopt_compression",!0,e=>b(this,void 0,void 0,function*(){const{EXT_meshopt_compression:t}=yield Promise.resolve().then(function(){return Yr});return new t(e)})),Ys("EXT_texture_avif"),Xs("EXT_texture_avif",!0,e=>b(this,void 0,void 0,function*(){const{EXT_texture_avif:t}=yield Promise.resolve().then(function(){return ii});return new t(e)})),Ys("EXT_texture_webp"),Xs("EXT_texture_webp",!0,e=>b(this,void 0,void 0,function*(){const{EXT_texture_webp:t}=yield Promise.resolve().then(function(){return ti});return new t(e)})),Ys("ExtrasAsMetadata"),Xs("ExtrasAsMetadata",!1,e=>b(this,void 0,void 0,function*(){const{ExtrasAsMetadata:t}=yield Promise.resolve().then(function(){return Zd});return new t(e)})),Ys("KHR_animation_pointer"),Xs("KHR_animation_pointer",!0,e=>b(this,void 0,void 0,function*(){const[{KHR_animation_pointer:t},{_RegisterKHRAnimationPointerData:n}]=yield Promise.all([Promise.resolve().then(function(){return Hl}),Promise.resolve().then(function(){return ou})]);return n(),new t(e)})),Ys("KHR_draco_mesh_compression"),Xs("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 gi});return new t(e)})),Ys("KHR_gaussian_splatting"),Xs("KHR_gaussian_splatting",!0,e=>b(this,void 0,void 0,function*(){const{KHR_gaussian_splatting:t}=yield Promise.resolve().then(function(){return wi});return new t(e)})),Ys("KHR_interactivity"),Xs("KHR_interactivity",!0,e=>b(this,void 0,void 0,function*(){const{KHR_interactivity:t,_RegisterKHRInteractivityRuntime:n}=yield Promise.resolve().then(function(){return pd});return n(),new t(e)})),Ys("KHR_lights_punctual"),Xs("KHR_lights_punctual",!0,e=>b(this,void 0,void 0,function*(){const{KHR_lights:t}=yield Promise.resolve().then(function(){return Ii});return new t(e)})),Ys("EXT_lights_area"),Xs("EXT_lights_area",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_area:t}=yield Promise.resolve().then(function(){return Li});return new t(e)})),Ys("EXT_lights_ies"),Xs("EXT_lights_ies",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_ies:t}=yield Promise.resolve().then(function(){return di});return new t(e)})),Ys("KHR_materials_anisotropy"),Xs("KHR_materials_anisotropy",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_anisotropy:t}=yield Promise.resolve().then(function(){return ca});return new t(e)})),Ys("KHR_materials_clearcoat"),Xs("KHR_materials_clearcoat",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_clearcoat:t}=yield Promise.resolve().then(function(){return Xi});return new t(e)})),Ys("KHR_materials_diffuse_roughness"),Xs("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 vl});return new t(e)})),Ys("KHR_materials_diffuse_transmission"),Xs("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 Za});return new t(e)})),Ys("KHR_materials_dispersion"),Xs("KHR_materials_dispersion",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_dispersion:t}=yield Promise.resolve().then(function(){return pl});return new t(e)})),Ys("KHR_materials_emissive_strength"),Xs("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 ma});return new t(e)})),Ys("KHR_materials_ior"),Xs("KHR_materials_ior",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_ior:t}=yield Promise.resolve().then(function(){return ka});return new t(e)})),Ys("KHR_materials_iridescence"),Xs("KHR_materials_iridescence",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_iridescence:t}=yield Promise.resolve().then(function(){return ra});return new t(e)})),Ys("KHR_materials_pbrSpecularGlossiness"),Xs("KHR_materials_pbrSpecularGlossiness",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_pbrSpecularGlossiness:t}=yield Promise.resolve().then(function(){return Vi});return new t(e)})),Ys("KHR_materials_sheen"),Xs("KHR_materials_sheen",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_sheen:t}=yield Promise.resolve().then(function(){return ba});return new t(e)})),Ys("KHR_materials_specular"),Xs("KHR_materials_specular",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_specular:t}=yield Promise.resolve().then(function(){return Oa});return new t(e)})),Ys("KHR_materials_transmission"),Xs("KHR_materials_transmission",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_transmission:t}=yield Promise.resolve().then(function(){return qa});return new t(e)})),Ys("KHR_materials_unlit"),Xs("KHR_materials_unlit",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_unlit:t}=yield Promise.resolve().then(function(){return Ki});return new t(e)})),Ys("KHR_materials_variants"),Xs("KHR_materials_variants",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_variants:t}=yield Promise.resolve().then(function(){return Ga});return new t(e)})),Ys("KHR_materials_volume"),Xs("KHR_materials_volume",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_volume:t}=yield Promise.resolve().then(function(){return ol});return new t(e)})),Ys("KHR_mesh_quantization"),Xs("KHR_mesh_quantization",!0,e=>b(this,void 0,void 0,function*(){const{KHR_mesh_quantization:t}=yield Promise.resolve().then(function(){return Al});return new t(e)})),Ys("KHR_texture_basisu"),Xs("KHR_texture_basisu",!0,e=>b(this,void 0,void 0,function*(){const{KHR_texture_basisu:t}=yield Promise.resolve().then(function(){return Cl});return new t(e)})),Ys("KHR_texture_transform"),Xs("KHR_texture_transform",!0,e=>b(this,void 0,void 0,function*(){const{KHR_texture_transform:t}=yield Promise.resolve().then(function(){return Nl});return new t(e)})),Ys("KHR_xmp_json_ld"),Xs("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 Dl});return new t(e)})),Ys("MSFT_audio_emitter"),Xs("MSFT_audio_emitter",!0,e=>b(this,void 0,void 0,function*(){const[{MSFT_audio_emitter:t},{RegisterAudioSceneComponent:n},{Sound:o}]=yield Promise.all([Promise.resolve().then(function(){return lu}),Promise.resolve(BABYLON),Promise.resolve(BABYLON)]);return n(o),new t(e)})),Ys("MSFT_lod"),Xs("MSFT_lod",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_lod:t}=yield Promise.resolve().then(function(){return pu});return new t(e)})),Ys("MSFT_minecraftMesh"),Xs("MSFT_minecraftMesh",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_minecraftMesh:t}=yield Promise.resolve().then(function(){return vu});return new t(e)})),Ys("MSFT_sRGBFactors"),Xs("MSFT_sRGBFactors",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_sRGBFactors:t}=yield Promise.resolve().then(function(){return Au});return new t(e)})),Ys("KHR_node_visibility"),Xs("KHR_node_visibility",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_visibility:t,_RegisterKHRNodeVisibilityRuntime:n}=yield Promise.resolve().then(function(){return bd});return n(),new t(e)})),Ys("KHR_node_hoverability"),Xs("KHR_node_hoverability",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_hoverability:t,_RegisterKHRNodeHoverabilityRuntime:n}=yield Promise.resolve().then(function(){return qd});return n(),new t(e)})),Ys("KHR_node_selectability"),Xs("KHR_node_selectability",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_selectability:t,_RegisterKHRNodeSelectabilityRuntime:n}=yield Promise.resolve().then(function(){return Dd});return n(),new t(e)})),Ys("KHR_materials_coat"),Xs("KHR_materials_coat",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_coat:t}=yield Promise.resolve().then(function(){return ea});return new t(e)})),Ys("KHR_materials_fuzz"),Xs("KHR_materials_fuzz",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_fuzz:t}=yield Promise.resolve().then(function(){return Ma});return new t(e)})),Ys("KHR_materials_volume_scatter"),Xs("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 ll});return new t(e)}))}(),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},ph),{createPlugin:e=>b(this,void 0,void 0,function*(){const{OBJFileLoader:t}=yield Promise.resolve().then(function(){return _h});return new t(e[ph.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},Mh),{createPlugin:e=>b(this,void 0,void 0,function*(){const[{SPLATFileLoader:t},{RegisterEnginesExtensionsEngineDynamicTexture:n}]=yield Promise.all([Promise.resolve().then(function(){return np}),Promise.resolve(BABYLON)]);return n(),new t(e[Mh.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},yh),{createPlugin:()=>b(this,void 0,void 0,function*(){const[{STLFileLoader:e},{RegisterStandardMaterial:t}]=yield Promise.all([Promise.resolve().then(function(){return Ah}),Promise.resolve(BABYLON)]);return t(),new e})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},op),{createPlugin:e=>b(this,void 0,void 0,function*(){const{USDFileLoader:t,_RegisterUSDLoaderDependencies:n}=yield Promise.resolve().then(function(){return Vp});return n(),new t(e[op.name])})}))}Dp();var $p={__proto__:null,registerBuiltInLoaders:Gp};const Up="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Up)for(const e in y)Up.BABYLON[e]||(Up.BABYLON[e]=y[e]);const Hp="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Hp){Hp.BABYLON=Hp.BABYLON||{};for(const e in $p)Hp.BABYLON[e]=$p[e]}const Kp="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Kp){Kp.BABYLON=Kp.BABYLON||{};for(const e in ps)Kp.BABYLON[e]=ps[e];for(const e in Ko)Kp.BABYLON[e]=Ko[e]}const jp="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==jp){jp.BABYLON=jp.BABYLON||{},jp.BABYLON.GLTF1=jp.BABYLON.GLTF1||{};for(const e in Ws)jp.BABYLON.GLTF1[e]=Ws[e]}const Wp=Object.assign({},uh),qp=Object.assign(Object.assign({},{__proto__:null}),{Extensions:Wp}),zp=Object.assign(Object.assign({},ch),{Loader:qp}),Xp="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Xp){Xp.BABYLON=Xp.BABYLON||{};const e=Xp.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 Wp)e.GLTF2.Loader.Extensions[n]=Wp[n],t.push(n);for(const n in qp)"Extensions"!==n&&(e.GLTF2.Loader[n]=qp[n],t.push(n));for(const n in zp)t.indexOf(n)>-1||(e.GLTF2[n]=zp[n])}const Yp="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Yp)for(const e in vh)Yp.BABYLON[e]||(Yp.BABYLON[e]=vh[e]);const Qp="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Qp)for(const e in wh)Qp.BABYLON[e]||(Qp.BABYLON[e]=wh[e]);e.AddGaussianSplattingStreamPart=function(e,t,n,o,s={}){return new Xh(t,n,o,e.getScene(),Object.assign(Object.assign({},s),{hostCompound:e}))},e.AddGaussianSplattingStreamPartAsync=function(e,t,n,o){return b(this,arguments,void 0,function*(e,t,n,o,s={}){const r=new Xh(t,n,o,e.getScene(),Object.assign(Object.assign({},s),{hostCompound:e}));try{yield r.whenPartReadyAsync()}catch(e){throw r.dispose(),e}const i=r.streamingPartProxy;if(!i)throw r.dispose(),new Error("GaussianSplattingStream: streaming part was not reserved.");return i})},e.BVHFileLoader=m,e.FBXConstraintBehavior=bo,e.FBXConstraintSolver=yo,e.FBXFileLoader=To,e.FBXFileLoaderMetadata=xo,e.GLTF1=Ws,e.GLTF2=zp,e.GLTFFileLoader=ts,e.GLTFLoaderDefaultOptions=Jo,e.GLTFValidation=Ho,e.GaussianSplattingStream=Xh,e.MTLFileLoader=dh,e.OBJFileLoader=fh,e.ReadBvh=p,e.RegisterBVHFileLoader=_,e.RegisterGLTFFileLoader=os,e.RegisterOBJFileLoader=gh,e.RegisterSPLATFileLoader=tp,e.RegisterSTLFileLoader=Th,e.RegisterUSDFileLoader=Dp,e.SPLATFileLoader=Jh,e.STLFileLoader=bh,e.SolidParser=hh,e.USDFileLoader=Lp,e._RegisterUSDLoaderDependencies=Bp,e.registerBuiltInLoaders=Gp});
2
2
  //# sourceMappingURL=babylonjs.loaders.min.js.map