@gltf-transform/core
Advanced tools
Comparing version 2.0.5 to 2.1.0
@@ -1,2 +0,2 @@ | ||
import{GraphNode as t,$attributes as e,GraphEdge as r,$immutableKeys as s,isRef as n,isRefList as i,isRefMap as o,Graph as a}from"property-graph";export{Graph,GraphEdge}from"property-graph";import{transformMat4 as u,length as c}from"gl-matrix/vec3";import{determinant as h,getRotation as l,multiply as f}from"gl-matrix/mat4";const d="v2.0.5",g="@glb.bin";var p,m,w,y,T;function v(t){const e={min:[Infinity,Infinity,Infinity],max:[-Infinity,-Infinity,-Infinity]},r=t.propertyType===p.NODE?[t]:t.listChildren();for(const t of r)t.traverse(t=>{const r=t.getMesh();if(!r)return;const s=x(r,t.getWorldMatrix());b(s.min,e),b(s.max,e)});return e}function x(t,e){const r={min:[Infinity,Infinity,Infinity],max:[-Infinity,-Infinity,-Infinity]};for(const s of t.listPrimitives()){const t=s.getAttribute("POSITION");if(!t)continue;let n=[0,0,0],i=[0,0,0];for(let s=0;s<t.getCount();s++)n=t.getElement(s,n),i=u(i,n,e),b(i,r)}return r}function b(t,e){for(let r=0;r<3;r++)e.min[r]=Math.min(t[r],e.min[r]),e.max[r]=Math.max(t[r],e.max[r])}!function(t){t.ACCESSOR="Accessor",t.ANIMATION="Animation",t.ANIMATION_CHANNEL="AnimationChannel",t.ANIMATION_SAMPLER="AnimationSampler",t.BUFFER="Buffer",t.CAMERA="Camera",t.MATERIAL="Material",t.MESH="Mesh",t.PRIMITIVE="Primitive",t.PRIMITIVE_TARGET="PrimitiveTarget",t.NODE="Node",t.ROOT="Root",t.SCENE="Scene",t.SKIN="Skin",t.TEXTURE="Texture",t.TEXTURE_INFO="TextureInfo"}(p||(p={})),function(t){t.INTERLEAVED="interleaved",t.SEPARATE="separate"}(m||(m={})),function(t){t.ARRAY_BUFFER="ARRAY_BUFFER",t.ELEMENT_ARRAY_BUFFER="ELEMENT_ARRAY_BUFFER",t.INVERSE_BIND_MATRICES="INVERSE_BIND_MATRICES",t.OTHER="OTHER"}(w||(w={})),function(t){t[t.R=4096]="R",t[t.G=256]="G",t[t.B=16]="B",t[t.A=1]="A"}(y||(y={})),function(t){t.GLTF="GLTF",t.GLB="GLB"}(T||(T={}));class A{static createBufferFromDataURI(t){if("undefined"==typeof Buffer){const e=atob(t.split(",")[1]),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}{const e=t.split(",")[1],r=t.indexOf("base64")>=0;return Buffer.from(e,r?"base64":"utf8")}}static encodeText(t){return"undefined"!=typeof TextEncoder?(new TextEncoder).encode(t):Buffer.from(t)}static decodeText(t){return"undefined"!=typeof TextDecoder?(new TextDecoder).decode(t):Buffer.from(t).toString("utf8")}static concat(t){let e=0;for(const r of t)e+=r.byteLength;const r=new Uint8Array(e);let s=0;for(const e of t)r.set(e,s),s+=e.byteLength;return r}static pad(t,e=0){const r=this.padNumber(t.byteLength);if(r===t.byteLength)return t;const s=new Uint8Array(r);if(s.set(t),0!==e)for(let n=t.byteLength;n<r;n++)s[n]=e;return s}static padNumber(t){return 4*Math.ceil(t/4)}static equals(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;let r=t.byteLength;for(;r--;)if(t[r]!==e[r])return!1;return!0}static toView(t,e=0,r=Infinity){return new Uint8Array(t.buffer,t.byteOffset+e,Math.min(t.byteLength,r))}static assertView(t){if(t&&!ArrayBuffer.isView(t))throw new Error(`Method requires Uint8Array parameter; received "${typeof t}".`);return t}}class E{static hexToFactor(t,e){t=Math.floor(t);const r=e;return r[0]=(t>>16&255)/255,r[1]=(t>>8&255)/255,r[2]=(255&t)/255,this.convertSRGBToLinear(e,e)}static factorToHex(t){const e=[...t],[r,s,n]=this.convertLinearToSRGB(t,e);return 255*r<<16^255*s<<8^255*n<<0}static convertSRGBToLinear(t,e){const r=t,s=e;for(let t=0;t<3;t++)s[t]=r[t]<.04045?.0773993808*r[t]:Math.pow(.9478672986*r[t]+.0521327014,2.4);return e}static convertLinearToSRGB(t,e){const r=t,s=e;for(let t=0;t<3;t++)s[t]=r[t]<.0031308?12.92*r[t]:1.055*Math.pow(r[t],.41666)-.055;return e}}class S{static basename(t){const e=(t=new URL(t,"https://null.example").pathname).split(/[\\/]/).pop();return e.substring(0,e.lastIndexOf("."))}static extension(t){return 0!==t.indexOf("data:")?(t=new URL(t,"https://null.example").pathname).split(/[\\/]/).pop().split(/[.]/).pop():0===t.indexOf("data:image/png")?"png":0===t.indexOf("data:image/jpeg")?"jpeg":"bin"}}class M{match(t){return t.length>=8&&137===t[0]&&80===t[1]&&78===t[2]&&71===t[3]&&13===t[4]&&10===t[5]&&26===t[6]&&10===t[7]}getSize(t){const e=new DataView(t.buffer,t.byteOffset);return A.decodeText(t.slice(12,16))===M.PNG_FRIED_CHUNK_NAME?[e.getUint32(32,!1),e.getUint32(36,!1)]:[e.getUint32(16,!1),e.getUint32(20,!1)]}getChannels(t){return 4}}M.PNG_FRIED_CHUNK_NAME="CgBI";class I{static registerFormat(t,e){this.impls[t]=e}static getMimeType(t){for(const e in this.impls)if(this.impls[e].match(t))return e;return null}static getSize(t,e){return this.impls[e]?this.impls[e].getSize(t):null}static getChannels(t,e){return this.impls[e]?this.impls[e].getChannels(t):null}static getMemSize(t,e){if(!this.impls[e])return null;if(this.impls[e].getGPUByteLength)return this.impls[e].getGPUByteLength(t);let r=0;const s=this.getSize(t,e);if(!s)return null;for(;s[0]>1||s[1]>1;)r+=s[0]*s[1]*4,s[0]=Math.max(Math.floor(s[0]/2),1),s[1]=Math.max(Math.floor(s[1]/2),1);return r+=4,r}static mimeTypeToExtension(t){return"image/jpeg"===t?"jpg":t.split("/").pop()}static extensionToMimeType(t){return"jpg"===t?"image/jpeg":`image/${t}`}}function R(t,e){if(e>t.byteLength)throw new TypeError("Corrupt JPG, exceeded buffer limits");if(255!==t.getUint8(e))throw new TypeError("Invalid JPG, marker table corrupted");return t}function N(t){return"[object Object]"===Object.prototype.toString.call(t)}function O(t){if(!1===N(t))return!1;const e=t.constructor;if(void 0===e)return!0;const r=e.prototype;return!1!==N(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}I.impls={"image/jpeg":new class{match(t){return t.length>=3&&255===t[0]&&216===t[1]&&255===t[2]}getSize(t){let e,r,s=new DataView(t.buffer,t.byteOffset+4);for(;s.byteLength;){if(e=s.getUint16(0,!1),R(s,e),r=s.getUint8(e+1),192===r||193===r||194===r)return[s.getUint16(e+7,!1),s.getUint16(e+5,!1)];s=new DataView(t.buffer,s.byteOffset+e+2)}throw new TypeError("Invalid JPG, no size found")}getChannels(t){return 3}},"image/png":new M};class C{constructor(t){this.verbosity=void 0,this.verbosity=t}debug(t){this.verbosity<=C.Verbosity.DEBUG&&console.debug(t)}info(t){this.verbosity<=C.Verbosity.INFO&&console.info(t)}warn(t){this.verbosity<=C.Verbosity.WARN&&console.warn(t)}error(t){this.verbosity<=C.Verbosity.ERROR&&console.error(t)}}C.Verbosity={SILENT:4,ERROR:3,WARN:2,INFO:1,DEBUG:0},C.DEFAULT_INSTANCE=new C(C.Verbosity.INFO);class F{static identity(t){return t}static eq(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(Math.abs(t[r]-e[r])>1e-5)return!1;return!0}static denormalize(t,e){switch(e){case 5126:return t;case 5123:return t/65535;case 5121:return t/255;case 5122:return Math.max(t/32767,-1);case 5120:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}static normalize(t,e){switch(e){case 5126:return t;case 5123:return Math.round(65535*t);case 5121:return Math.round(255*t);case 5122:return Math.round(32767*t);case 5120:return Math.round(127*t);default:throw new Error("Invalid component type.")}}static decompose(t,e,r,s){let n=c([t[0],t[1],t[2]]);const i=c([t[4],t[5],t[6]]),o=c([t[8],t[9],t[10]]);h(t)<0&&(n=-n),e[0]=t[12],e[1]=t[13],e[2]=t[14];const a=t.slice(),u=1/n,f=1/i,d=1/o;a[0]*=u,a[1]*=u,a[2]*=u,a[4]*=f,a[5]*=f,a[6]*=f,a[8]*=d,a[9]*=d,a[10]*=d,l(r,a),s[0]=n,s[1]=i,s[2]=o}static compose(t,e,r,s){const n=s,i=e[0],o=e[1],a=e[2],u=e[3],c=i+i,h=o+o,l=a+a,f=i*c,d=i*h,g=i*l,p=o*h,m=o*l,w=a*l,y=u*c,T=u*h,v=u*l,x=r[0],b=r[1],A=r[2];return n[0]=(1-(p+w))*x,n[1]=(d+v)*x,n[2]=(g-T)*x,n[3]=0,n[4]=(d-v)*b,n[5]=(1-(f+w))*b,n[6]=(m+y)*b,n[7]=0,n[8]=(g+T)*A,n[9]=(m-y)*A,n[10]=(1-(f+p))*A,n[11]=0,n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=1,n}}function B(t,e){if(!!t!=!!e)return!1;const r=t.getChild(),s=e.getChild();return r===s||r.equals(s)}function U(t,e){if(!!t!=!!e)return!1;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){const s=t[r],n=e[r];if(s.getChild()!==n.getChild()&&!s.getChild().equals(n.getChild()))return!1}return!0}function P(t,e){if(!!t!=!!e)return!1;const r=Object.keys(t),s=Object.keys(e);if(r.length!==s.length)return!1;for(const r in t){const s=t[r],n=e[r];if(!!s!=!!n)return!1;const i=s.getChild(),o=n.getChild();if(i!==o&&!i.equals(o))return!1}return!0}function j(t,e){if(t===e)return!0;if(!!t!=!!e||!t||!e)return!1;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}function L(t,e){if(t===e)return!0;if(!!t!=!!e)return!1;if(!O(t)||!O(e))return t===e;const r=t,s=e;let n,i=0,o=0;for(n in r)i++;for(n in s)o++;if(i!==o)return!1;for(n in r){const t=r[n],e=s[n];if(_(t)&&_(e)){if(!j(t,e))return!1}else if(O(t)&&O(e)){if(!L(t,e))return!1}else if(t!==e)return!1}return!0}function _(t){return Array.isArray(t)||ArrayBuffer.isView(t)}const D="23456789abdegjkmnpqrvwxyzABDEGJKMNPQRVWXYZ",k=new Set,z=function(){let t="";for(let e=0;e<6;e++)t+=D.charAt(Math.floor(Math.random()*D.length));return t},G=function(){for(let t=0;t<999;t++){const t=z();if(!k.has(t))return k.add(t),t}return""};class J{static dirname(t){const e=t.lastIndexOf("/");return-1===e?"./":t.substring(0,e+1)}static resolve(t,e){if(!this.isRelativePath(e))return e;const r=t.split("/"),s=e.split("/");r.pop();for(let t=0;t<s.length;t++)"."!==s[t]&&(".."===s[t]?r.pop():r.push(s[t]));return r.join("/")}static isAbsoluteURL(t){return this.PROTOCOL_REGEXP.test(t)}static isRelativePath(t){return!/^(?:[a-zA-Z]+:)?\//.test(t)}}J.DEFAULT_INIT={},J.PROTOCOL_REGEXP=/^[a-zA-Z]+:\/\//;const $=t=>t;class V extends t{constructor(t,r=""){super(t),this[e].name=r,this.init(),this.dispatchEvent({type:"create"})}getDefaults(){return Object.assign(super.getDefaults(),{name:"",extras:{}})}getName(){return this.get("name")}setName(t){return this.set("name",t)}getExtras(){return this.get("extras")}setExtras(t){return this.set("extras",t)}clone(){return new(0,this.constructor)(this.graph).copy(this,$)}copy(t,n=$){for(const t in this[e]){const n=this[e][t];if(n instanceof r)this[s].has(t)||n.dispose();else if(Array.isArray(n)&&n[0]instanceof r)for(const t of n)t.dispose();else if(O(n)&&Object.values(n)[0]instanceof r)for(const t in n)n[t].dispose()}for(const i in t[e]){const o=this[e][i],a=t[e][i];if(a instanceof r)this[s].has(i)?o.getChild().copy(n(a.getChild()),n):this.setRef(i,n(a.getChild()),a.getAttributes());else if(Array.isArray(a)&&a[0]instanceof r)for(const t of a)this.addRef(i,n(t.getChild()),t.getAttributes());else if(O(a)&&Object.values(a)[0]instanceof r)for(const t in a){const e=a[t];this.setRefMap(i,t,n(e.getChild()),e.getAttributes())}else this[e][i]=O(a)?JSON.parse(JSON.stringify(a)):Array.isArray(a)||a instanceof ArrayBuffer||ArrayBuffer.isView(a)?a.slice():a}return this}equals(t){if(this===t)return!0;if(this.propertyType!==t.propertyType)return!1;for(const r in this[e]){const s=this[e][r],a=t[e][r];if(n(s)||n(a)){if(!B(s,a))return!1}else if(i(s)||i(a)){if(!U(s,a))return!1}else if(o(s)||o(a)){if(!P(s,a))return!1}else if(O(s)||O(a)){if(!L(s,a))return!1}else if(_(s)||_(a)){if(!j(s,a))return!1}else if(s!==a)return!1}return!0}detach(){return this.graph.disconnectParents(this,t=>"Root"!==t.propertyType),this}listParents(){return this.graph.listParents(this)}}class q extends V{getDefaults(){return Object.assign(super.getDefaults(),{extensions:{}})}getExtension(t){return this.getRefMap("extensions",t)}setExtension(t,e){return e&&e.t(this),this.setRefMap("extensions",t,e)}listExtensions(){return this.listRefMapValues("extensions")}}class W extends q{constructor(...t){super(...t),this.i=F.identity,this.o=F.identity}init(){this.propertyType=p.ACCESSOR}getDefaults(){return Object.assign(super.getDefaults(),{array:null,type:W.Type.SCALAR,componentType:W.ComponentType.FLOAT,normalized:!1,buffer:null})}copy(t,e=$){return super.copy(t,e),this.i=t.i,this.o=t.o,this}static getElementSize(t){switch(t){case W.Type.SCALAR:return 1;case W.Type.VEC2:return 2;case W.Type.VEC3:return 3;case W.Type.VEC4:case W.Type.MAT2:return 4;case W.Type.MAT3:return 9;case W.Type.MAT4:return 16;default:throw new Error("Unexpected type: "+t)}}static getComponentSize(t){switch(t){case W.ComponentType.BYTE:case W.ComponentType.UNSIGNED_BYTE:return 1;case W.ComponentType.SHORT:case W.ComponentType.UNSIGNED_SHORT:return 2;case W.ComponentType.UNSIGNED_INT:case W.ComponentType.FLOAT:return 4;default:throw new Error("Unexpected component type: "+t)}}getMinNormalized(t){const e=this.getElementSize();this.getMin(t);for(let r=0;r<e;r++)t[r]=this.o(t[r]);return t}getMin(t){const e=this.get("array"),r=this.getCount(),s=this.getElementSize();for(let e=0;e<s;e++)t[e]=Infinity;for(let n=0;n<r*s;n+=s)for(let r=0;r<s;r++){const s=e[n+r];Number.isFinite(s)&&(t[r]=Math.min(t[r],s))}return t}getMaxNormalized(t){const e=this.getElementSize();this.getMax(t);for(let r=0;r<e;r++)t[r]=this.o(t[r]);return t}getMax(t){const e=this.get("array"),r=this.getCount(),s=this.getElementSize();for(let e=0;e<s;e++)t[e]=-Infinity;for(let n=0;n<r*s;n+=s)for(let r=0;r<s;r++){const s=e[n+r];Number.isFinite(s)&&(t[r]=Math.max(t[r],s))}return t}getCount(){const t=this.get("array");return t?t.length/this.getElementSize():0}getType(){return this.get("type")}setType(t){return this.set("type",t)}getElementSize(){return W.getElementSize(this.get("type"))}getComponentSize(){return this.get("array").BYTES_PER_ELEMENT}getComponentType(){return this.get("componentType")}getNormalized(){return this.get("normalized")}setNormalized(t){return this.set("normalized",t),t?(this.o=t=>F.denormalize(t,this.get("componentType")),this.i=t=>F.normalize(t,this.get("componentType"))):(this.o=F.identity,this.i=F.identity),this}getScalar(t){const e=this.getElementSize();return this.o(this.get("array")[t*e])}setScalar(t,e){return this.get("array")[t*this.getElementSize()]=this.i(e),this}getElement(t,e){const r=this.getElementSize(),s=this.get("array");for(let n=0;n<r;n++)e[n]=this.o(s[t*r+n]);return e}setElement(t,e){const r=this.getElementSize(),s=this.get("array");for(let n=0;n<r;n++)s[t*r+n]=this.i(e[n]);return this}getBuffer(){return this.getRef("buffer")}setBuffer(t){return this.setRef("buffer",t)}getArray(){return this.get("array")}setArray(t){return this.set("componentType",t?function(t){switch(t.constructor){case Float32Array:return W.ComponentType.FLOAT;case Uint32Array:return W.ComponentType.UNSIGNED_INT;case Uint16Array:return W.ComponentType.UNSIGNED_SHORT;case Uint8Array:return W.ComponentType.UNSIGNED_BYTE;case Int16Array:return W.ComponentType.SHORT;case Int8Array:return W.ComponentType.BYTE;default:throw new Error("Unknown accessor componentType.")}}(t):W.ComponentType.FLOAT),this.set("array",t),this}getByteLength(){const t=this.get("array");return t?t.byteLength:0}}W.Type={SCALAR:"SCALAR",VEC2:"VEC2",VEC3:"VEC3",VEC4:"VEC4",MAT2:"MAT2",MAT3:"MAT3",MAT4:"MAT4"},W.ComponentType={BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,UNSIGNED_INT:5125,FLOAT:5126};class H extends q{init(){this.propertyType=p.ANIMATION}getDefaults(){return Object.assign(super.getDefaults(),{channels:[],samplers:[]})}addChannel(t){return this.addRef("channels",t)}removeChannel(t){return this.removeRef("channels",t)}listChannels(){return this.listRefs("channels")}addSampler(t){return this.addRef("samplers",t)}removeSampler(t){return this.removeRef("samplers",t)}listSamplers(){return this.listRefs("samplers")}}class Y extends q{init(){this.propertyType=p.ANIMATION_CHANNEL}getDefaults(){return Object.assign(super.getDefaults(),{targetPath:null,targetNode:null,sampler:null})}getTargetPath(){return this.get("targetPath")}setTargetPath(t){return this.set("targetPath",t)}getTargetNode(){return this.getRef("targetNode")}setTargetNode(t){return this.setRef("targetNode",t)}getSampler(){return this.getRef("sampler")}setSampler(t){return this.setRef("sampler",t)}}Y.TargetPath={TRANSLATION:"translation",ROTATION:"rotation",SCALE:"scale",WEIGHTS:"weights"};class Z extends q{init(){this.propertyType=p.ANIMATION_SAMPLER}getDefaultAttributes(){return Object.assign(super.getDefaults(),{interpolation:Z.Interpolation.LINEAR,input:null,output:null})}getInterpolation(){return this.get("interpolation")}setInterpolation(t){return this.set("interpolation",t)}getInput(){return this.getRef("input")}setInput(t){return this.setRef("input",t,{usage:w.OTHER})}getOutput(){return this.getRef("output")}setOutput(t){return this.setRef("output",t,{usage:w.OTHER})}}Z.Interpolation={LINEAR:"LINEAR",STEP:"STEP",CUBICSPLINE:"CUBICSPLINE"};class K extends q{init(){this.propertyType=p.BUFFER}getDefaults(){return Object.assign(super.getDefaults(),{uri:""})}getURI(){return this.get("uri")}setURI(t){return this.set("uri",t)}}class Q extends q{init(){this.propertyType=p.CAMERA}getDefaults(){return Object.assign(super.getDefaults(),{type:Q.Type.PERSPECTIVE,znear:.1,zfar:100,aspectRatio:null,yfov:2*Math.PI*50/360,xmag:1,ymag:1})}getType(){return this.get("type")}setType(t){return this.set("type",t)}getZNear(){return this.get("znear")}setZNear(t){return this.set("znear",t)}getZFar(){return this.get("zfar")}setZFar(t){return this.set("zfar",t)}getAspectRatio(){return this.get("aspectRatio")}setAspectRatio(t){return this.set("aspectRatio",t)}getYFov(){return this.get("yfov")}setYFov(t){return this.set("yfov",t)}getXMag(){return this.get("xmag")}setXMag(t){return this.set("xmag",t)}getYMag(){return this.get("ymag")}setYMag(t){return this.set("ymag",t)}}Q.Type={PERSPECTIVE:"perspective",ORTHOGRAPHIC:"orthographic"};class X extends V{t(t){if(!this.parentTypes.includes(t.propertyType))throw new Error(`Parent "${t.propertyType}" invalid for child "${this.propertyType}".`)}}X.EXTENSION_NAME=void 0;class tt extends q{init(){this.propertyType=p.TEXTURE_INFO}getDefaults(){return Object.assign(super.getDefaults(),{texCoord:0,magFilter:null,minFilter:null,wrapS:tt.WrapMode.REPEAT,wrapT:tt.WrapMode.REPEAT})}getTexCoord(){return this.get("texCoord")}setTexCoord(t){return this.set("texCoord",t)}getMagFilter(){return this.get("magFilter")}setMagFilter(t){return this.set("magFilter",t)}getMinFilter(){return this.get("minFilter")}setMinFilter(t){return this.set("minFilter",t)}getWrapS(){return this.get("wrapS")}setWrapS(t){return this.set("wrapS",t)}getWrapT(){return this.get("wrapT")}setWrapT(t){return this.set("wrapT",t)}}tt.WrapMode={CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497},tt.MagFilter={NEAREST:9728,LINEAR:9729},tt.MinFilter={NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987};const{R:et,G:rt,B:st,A:nt}=y;class it extends q{init(){this.propertyType=p.MATERIAL}getDefaults(){return Object.assign(super.getDefaults(),{alphaMode:it.AlphaMode.OPAQUE,alphaCutoff:.5,doubleSided:!1,baseColorFactor:[1,1,1,1],baseColorTexture:null,baseColorTextureInfo:new tt(this.graph,"baseColorTextureInfo"),emissiveFactor:[0,0,0],emissiveTexture:null,emissiveTextureInfo:new tt(this.graph,"emissiveTextureInfo"),normalScale:1,normalTexture:null,normalTextureInfo:new tt(this.graph,"normalTextureInfo"),occlusionStrength:1,occlusionTexture:null,occlusionTextureInfo:new tt(this.graph,"occlusionTextureInfo"),roughnessFactor:1,metallicFactor:1,metallicRoughnessTexture:null,metallicRoughnessTextureInfo:new tt(this.graph,"metallicRoughnessTextureInfo")})}getDoubleSided(){return this.get("doubleSided")}setDoubleSided(t){return this.set("doubleSided",t)}getAlpha(){return this.get("baseColorFactor")[3]}setAlpha(t){const e=this.get("baseColorFactor").slice();return e[3]=t,this.set("baseColorFactor",e)}getAlphaMode(){return this.get("alphaMode")}setAlphaMode(t){return this.set("alphaMode",t)}getAlphaCutoff(){return this.get("alphaCutoff")}setAlphaCutoff(t){return this.set("alphaCutoff",t)}getBaseColorFactor(){return this.get("baseColorFactor")}setBaseColorFactor(t){return this.set("baseColorFactor",t)}getBaseColorHex(){return E.factorToHex(this.get("baseColorFactor"))}setBaseColorHex(t){const e=this.get("baseColorFactor").slice();return this.set("baseColorFactor",E.hexToFactor(t,e))}getBaseColorTexture(){return this.getRef("baseColorTexture")}getBaseColorTextureInfo(){return this.getRef("baseColorTexture")?this.getRef("baseColorTextureInfo"):null}setBaseColorTexture(t){return this.setRef("baseColorTexture",t,{channels:et|rt|st|nt})}getEmissiveFactor(){return this.get("emissiveFactor")}setEmissiveFactor(t){return this.set("emissiveFactor",t)}getEmissiveHex(){return E.factorToHex(this.get("emissiveFactor"))}setEmissiveHex(t){const e=this.get("emissiveFactor").slice();return this.set("emissiveFactor",E.hexToFactor(t,e))}getEmissiveTexture(){return this.getRef("emissiveTexture")}getEmissiveTextureInfo(){return this.getRef("emissiveTexture")?this.getRef("emissiveTextureInfo"):null}setEmissiveTexture(t){return this.setRef("emissiveTexture",t,{channels:et|rt|st})}getNormalScale(){return this.get("normalScale")}setNormalScale(t){return this.set("normalScale",t)}getNormalTexture(){return this.getRef("normalTexture")}getNormalTextureInfo(){return this.getRef("normalTexture")?this.getRef("normalTextureInfo"):null}setNormalTexture(t){return this.setRef("normalTexture",t,{channels:et|rt|st})}getOcclusionStrength(){return this.get("occlusionStrength")}setOcclusionStrength(t){return this.set("occlusionStrength",t)}getOcclusionTexture(){return this.getRef("occlusionTexture")}getOcclusionTextureInfo(){return this.getRef("occlusionTexture")?this.getRef("occlusionTextureInfo"):null}setOcclusionTexture(t){return this.setRef("occlusionTexture",t,{channels:et})}getRoughnessFactor(){return this.get("roughnessFactor")}setRoughnessFactor(t){return this.set("roughnessFactor",t)}getMetallicFactor(){return this.get("metallicFactor")}setMetallicFactor(t){return this.set("metallicFactor",t)}getMetallicRoughnessTexture(){return this.getRef("metallicRoughnessTexture")}getMetallicRoughnessTextureInfo(){return this.getRef("metallicRoughnessTexture")?this.getRef("metallicRoughnessTextureInfo"):null}setMetallicRoughnessTexture(t){return this.setRef("metallicRoughnessTexture",t,{channels:rt|st})}}it.AlphaMode={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};class ot extends q{init(){this.propertyType=p.MESH}getDefaults(){return Object.assign(super.getDefaults(),{weights:[],primitives:[]})}addPrimitive(t){return this.addRef("primitives",t)}removePrimitive(t){return this.removeRef("primitives",t)}listPrimitives(){return this.listRefs("primitives")}getWeights(){return this.get("weights")}setWeights(t){return this.set("weights",t)}}class at extends q{constructor(...t){super(...t),this.u=null}init(){this.propertyType=p.NODE}getDefaults(){return Object.assign(super.getDefaults(),{translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1],weights:[],camera:null,mesh:null,skin:null,children:[]})}copy(t,e=$){if(e===$)throw new Error("Node cannot be copied.");return super.copy(t,e)}getTranslation(){return this.get("translation")}getRotation(){return this.get("rotation")}getScale(){return this.get("scale")}setTranslation(t){return this.set("translation",t)}setRotation(t){return this.set("rotation",t)}setScale(t){return this.set("scale",t)}getMatrix(){return F.compose(this.get("translation"),this.get("rotation"),this.get("scale"),[])}setMatrix(t){const e=this.get("translation").slice(),r=this.get("rotation").slice(),s=this.get("scale").slice();return F.decompose(t,e,r,s),this.set("translation",e).set("rotation",r).set("scale",s)}getWorldTranslation(){const t=[0,0,0];return F.decompose(this.getWorldMatrix(),t,[0,0,0,1],[1,1,1]),t}getWorldRotation(){const t=[0,0,0,1];return F.decompose(this.getWorldMatrix(),[0,0,0],t,[1,1,1]),t}getWorldScale(){const t=[1,1,1];return F.decompose(this.getWorldMatrix(),[0,0,0],[0,0,0,1],t),t}getWorldMatrix(){const t=[];for(let e=this;e instanceof at;e=e.u)t.push(e);let e;const r=t.pop().getMatrix();for(;e=t.pop();)f(r,r,e.getMatrix());return r}addChild(t){t.u&&t.u.removeChild(t),this.addRef("children",t),t.u=this;const r=this[e].children;return r[r.length-1].addEventListener("dispose",()=>t.u=null),this}removeChild(t){return this.removeRef("children",t)}listChildren(){return this.listRefs("children")}getParent(){return this.u}getMesh(){return this.getRef("mesh")}setMesh(t){return this.setRef("mesh",t)}getCamera(){return this.getRef("camera")}setCamera(t){return this.setRef("camera",t)}getSkin(){return this.getRef("skin")}setSkin(t){return this.setRef("skin",t)}getWeights(){return this.get("weights")}setWeights(t){return this.set("weights",t)}traverse(t){t(this);for(const e of this.listChildren())e.traverse(t);return this}}class ut extends q{init(){this.propertyType=p.PRIMITIVE}getDefaults(){return Object.assign(super.getDefaults(),{mode:ut.Mode.TRIANGLES,material:null,indices:null,attributes:{},targets:[]})}getIndices(){return this.getRef("indices")}setIndices(t){return this.setRef("indices",t,{usage:w.ELEMENT_ARRAY_BUFFER})}getAttribute(t){return this.getRefMap("attributes",t)}setAttribute(t,e){return this.setRefMap("attributes",t,e,{usage:w.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}getMaterial(){return this.getRef("material")}setMaterial(t){return this.setRef("material",t)}getMode(){return this.get("mode")}setMode(t){return this.set("mode",t)}listTargets(){return this.listRefs("targets")}addTarget(t){return this.addRef("targets",t)}removeTarget(t){return this.removeRef("targets",t)}}ut.Mode={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6};class ct extends V{init(){this.propertyType=p.PRIMITIVE_TARGET}getDefaults(){return Object.assign(super.getDefaults(),{attributes:{}})}getAttribute(t){return this.getRefMap("attributes",t)}setAttribute(t,e){return this.setRefMap("attributes",t,e,{usage:w.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}}function ht(){return(ht=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(t[s]=r[s])}return t}).apply(this,arguments)}class lt extends q{init(){this.propertyType=p.SCENE}getDefaults(){return Object.assign(super.getDefaults(),{children:[]})}copy(t,e=$){if(e===$)throw new Error("Scene cannot be copied.");return super.copy(t,e)}addChild(t){t.u&&t.u.removeChild(t),this.addRef("children",t),t.u=this;const r=this[e].children;return r[r.length-1].addEventListener("dispose",()=>t.u=null),this}removeChild(t){return this.removeRef("children",t)}listChildren(){return this.listRefs("children")}traverse(t){for(const e of this.listChildren())e.traverse(t);return this}}class ft extends q{init(){this.propertyType=p.SKIN}getDefaults(){return Object.assign(super.getDefaults(),{skeleton:null,inverseBindMatrices:null,joints:[]})}getSkeleton(){return this.getRef("skeleton")}setSkeleton(t){return this.setRef("skeleton",t)}getInverseBindMatrices(){return this.getRef("inverseBindMatrices")}setInverseBindMatrices(t){return this.setRef("inverseBindMatrices",t,{usage:w.INVERSE_BIND_MATRICES})}addJoint(t){return this.addRef("joints",t)}removeJoint(t){return this.removeRef("joints",t)}listJoints(){return this.listRefs("joints")}}class dt extends q{init(){this.propertyType=p.TEXTURE}getDefaults(){return Object.assign(super.getDefaults(),{image:null,mimeType:"",uri:""})}getMimeType(){return this.get("mimeType")||I.extensionToMimeType(S.extension(this.get("uri")))}setMimeType(t){return this.set("mimeType",t)}getURI(){return this.get("uri")}setURI(t){return this.set("uri",t),this.set("mimeType",I.extensionToMimeType(S.extension(t))),this}getImage(){return this.get("image")}setImage(t){return this.set("image",A.assertView(t))}getSize(){const t=this.get("image");return t?I.getSize(t,this.getMimeType()):null}}class gt extends q{init(){this.propertyType=p.ROOT}getDefaults(){return Object.assign(super.getDefaults(),{asset:{generator:"glTF-Transform v2.0.5",version:"2.0"},defaultScene:null,accessors:[],animations:[],buffers:[],cameras:[],materials:[],meshes:[],nodes:[],scenes:[],skins:[],textures:[]})}constructor(t){super(t),this.h=new Set,t.addEventListener("node:create",t=>{this.l(t.target)})}clone(){throw new Error("Root cannot be cloned.")}copy(t,e=$){if(e===$)throw new Error("Root cannot be copied.");this.set("asset",ht({},t.get("asset"))),this.setName(t.getName()),this.setExtras(ht({},t.getExtras())),this.setDefaultScene(t.getDefaultScene()?e(t.getDefaultScene()):null);for(const r of t.listRefMapKeys("extensions")){const s=t.getExtension(r);this.setExtension(r,e(s))}return this}l(t){return t instanceof lt?this.addRef("scenes",t):t instanceof at?this.addRef("nodes",t):t instanceof Q?this.addRef("cameras",t):t instanceof ft?this.addRef("skins",t):t instanceof ot?this.addRef("meshes",t):t instanceof it?this.addRef("materials",t):t instanceof dt?this.addRef("textures",t):t instanceof H?this.addRef("animations",t):t instanceof W?this.addRef("accessors",t):t instanceof K&&this.addRef("buffers",t),this}getAsset(){return this.get("asset")}listExtensionsUsed(){return Array.from(this.h)}listExtensionsRequired(){return this.listExtensionsUsed().filter(t=>t.isRequired())}g(t){return this.h.add(t),this}p(t){return this.h.delete(t),this}listScenes(){return this.listRefs("scenes")}setDefaultScene(t){return this.setRef("defaultScene",t)}getDefaultScene(){return this.getRef("defaultScene")}listNodes(){return this.listRefs("nodes")}listCameras(){return this.listRefs("cameras")}listSkins(){return this.listRefs("skins")}listMeshes(){return this.listRefs("meshes")}listMaterials(){return this.listRefs("materials")}listTextures(){return this.listRefs("textures")}listAnimations(){return this.listRefs("animations")}listAccessors(){return this.listRefs("accessors")}listBuffers(){return this.listRefs("buffers")}}class pt{constructor(){this.m=new a,this.T=new gt(this.m),this.v=C.DEFAULT_INSTANCE}getRoot(){return this.T}getGraph(){return this.m}getLogger(){return this.v}setLogger(t){return this.v=t,this}clone(){return(new pt).setLogger(this.v).merge(this)}merge(t){for(const e of t.getRoot().listExtensionsUsed()){const t=this.createExtension(e.constructor);e.isRequired()&&t.setRequired(!0)}const e=new Set,r=new Map;e.add(t.T),r.set(t.T,this.T);for(const s of t.m.listEdges())for(const t of[s.getParent(),s.getChild()]){if(e.has(t))continue;let s;s=t.propertyType===p.TEXTURE_INFO?t:new(0,t.constructor)(this.m),r.set(t,s),e.add(t)}const s=t=>{const e=r.get(t);if(!e)throw new Error("Could resolve property.");return e};for(const t of e){const e=r.get(t);if(!e)throw new Error("Could resolve property.");e.copy(t,s)}return this}async transform(...t){const e=t.map(t=>t.name);for(const r of t)await r(this,{stack:e});return this}createExtension(t){const e=t.EXTENSION_NAME;return this.getRoot().listExtensionsUsed().find(t=>t.extensionName===e)||new t(this)}createScene(t=""){return new lt(this.m,t)}createNode(t=""){return new at(this.m,t)}createCamera(t=""){return new Q(this.m,t)}createSkin(t=""){return new ft(this.m,t)}createMesh(t=""){return new ot(this.m,t)}createPrimitive(){return new ut(this.m)}createPrimitiveTarget(t=""){return new ct(this.m,t)}createMaterial(t=""){return new it(this.m,t)}createTexture(t=""){return new dt(this.m,t)}createAnimation(t=""){return new H(this.m,t)}createAnimationChannel(t=""){return new Y(this.m,t)}createAnimationSampler(t=""){return new Z(this.m,t)}createAccessor(t="",e=null){return e||(e=this.getRoot().listBuffers()[0]),new W(this.m,t).setBuffer(e)}createBuffer(t=""){return new K(this.m,t)}}class mt{constructor(t){this.extensionName="",this.prereadTypes=[],this.prewriteTypes=[],this.readDependencies=[],this.writeDependencies=[],this.document=void 0,this.required=!1,this.properties=new Set,this.S=void 0,this.document=t,t.getRoot().g(this),this.S=t=>{const e=t,r=e.target;r instanceof X&&r.extensionName===this.extensionName&&("node:create"===e.type&&this.M(r),"node:dispose"===e.type&&this.I(r))};const e=t.getGraph();e.addEventListener("node:create",this.S),e.addEventListener("node:dispose",this.S)}dispose(){this.document.getRoot().p(this);const t=this.document.getGraph();t.removeEventListener("node:create",this.S),t.removeEventListener("node:dispose",this.S);for(const t of this.properties)t.dispose()}static register(){}isRequired(){return this.required}setRequired(t){return this.required=t,this}M(t){return this.properties.add(t),this}I(t){return this.properties.delete(t),this}install(t,e){return this}preread(t,e){return this}prewrite(t,e){return this}}mt.EXTENSION_NAME=void 0;class wt{constructor(t){this.jsonDoc=void 0,this.buffers=[],this.bufferViews=[],this.bufferViewBuffers=[],this.accessors=[],this.textures=[],this.textureInfos=new Map,this.materials=[],this.meshes=[],this.cameras=[],this.nodes=[],this.skins=[],this.animations=[],this.scenes=[],this.jsonDoc=t}setTextureInfo(t,e){this.textureInfos.set(t,e),void 0!==e.texCoord&&t.setTexCoord(e.texCoord);const r=this.jsonDoc.json.textures[e.index];if(void 0===r.sampler)return;const s=this.jsonDoc.json.samplers[r.sampler];void 0!==s.magFilter&&t.setMagFilter(s.magFilter),void 0!==s.minFilter&&t.setMinFilter(s.minFilter),void 0!==s.wrapS&&t.setWrapS(s.wrapS),void 0!==s.wrapT&&t.setWrapT(s.wrapT)}}const yt={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},Tt={logger:C.DEFAULT_INSTANCE,extensions:[],dependencies:{}};function vt(t,e){const r=e.bufferViews[t.bufferView],s=e.jsonDoc.json.bufferViews[t.bufferView],n=yt[t.componentType],i=W.getElementSize(t.type),o=n.BYTES_PER_ELEMENT;if(void 0!==s.byteStride&&s.byteStride!==i*o)return function(t,e){const r=e.bufferViews[t.bufferView],s=e.jsonDoc.json.bufferViews[t.bufferView],n=yt[t.componentType],i=W.getElementSize(t.type),o=n.BYTES_PER_ELEMENT,a=t.byteOffset||0,u=new n(t.count*i),c=new DataView(r.buffer,r.byteOffset,r.byteLength),h=s.byteStride;for(let e=0;e<t.count;e++)for(let r=0;r<i;r++){const s=a+e*h+r*o;let n;switch(t.componentType){case W.ComponentType.FLOAT:n=c.getFloat32(s,!0);break;case W.ComponentType.UNSIGNED_INT:n=c.getUint32(s,!0);break;case W.ComponentType.UNSIGNED_SHORT:n=c.getUint16(s,!0);break;case W.ComponentType.UNSIGNED_BYTE:n=c.getUint8(s);break;case W.ComponentType.SHORT:n=c.getInt16(s,!0);break;case W.ComponentType.BYTE:n=c.getInt8(s);break;default:throw new Error(`Unexpected componentType "${t.componentType}".`)}u[e*i+r]=n}return u}(t,e);const a=r.byteOffset+(t.byteOffset||0);return new n(r.buffer.slice(a,a+t.count*i*o))}var xt;!function(t){t[t.ARRAY_BUFFER=34962]="ARRAY_BUFFER",t[t.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER"}(xt||(xt={}));class bt{constructor(t,e,r){this.N=void 0,this.jsonDoc=void 0,this.options=void 0,this.accessorIndexMap=new Map,this.animationIndexMap=new Map,this.bufferIndexMap=new Map,this.cameraIndexMap=new Map,this.skinIndexMap=new Map,this.materialIndexMap=new Map,this.meshIndexMap=new Map,this.nodeIndexMap=new Map,this.imageIndexMap=new Map,this.textureDefIndexMap=new Map,this.textureInfoDefMap=new Map,this.samplerDefIndexMap=new Map,this.sceneIndexMap=new Map,this.imageBufferViews=[],this.otherBufferViews=new Map,this.otherBufferViewsIndexMap=new Map,this.extensionData={},this.bufferURIGenerator=void 0,this.imageURIGenerator=void 0,this.logger=void 0,this.O=new Map,this.accessorUsageGroupedByParent=new Set(["ARRAY_BUFFER"]),this.accessorParents=new Map,this.N=t,this.jsonDoc=e,this.options=r;const s=t.getRoot(),n=s.listBuffers().length,i=s.listTextures().length;this.bufferURIGenerator=new At(n>1,r.basename),this.imageURIGenerator=new At(i>1,r.basename),this.logger=t.getLogger()}createTextureInfoDef(t,e){const r={magFilter:e.getMagFilter()||void 0,minFilter:e.getMinFilter()||void 0,wrapS:e.getWrapS(),wrapT:e.getWrapT()},s=JSON.stringify(r);this.samplerDefIndexMap.has(s)||(this.samplerDefIndexMap.set(s,this.jsonDoc.json.samplers.length),this.jsonDoc.json.samplers.push(r));const n={source:this.imageIndexMap.get(t),sampler:this.samplerDefIndexMap.get(s)},i=JSON.stringify(n);this.textureDefIndexMap.has(i)||(this.textureDefIndexMap.set(i,this.jsonDoc.json.textures.length),this.jsonDoc.json.textures.push(n));const o={index:this.textureDefIndexMap.get(i)};return 0!==e.getTexCoord()&&(o.texCoord=e.getTexCoord()),this.textureInfoDefMap.set(e,o),o}createPropertyDef(t){const e={};return t.getName()&&(e.name=t.getName()),Object.keys(t.getExtras()).length>0&&(e.extras=t.getExtras()),e}createAccessorDef(t){const e=this.createPropertyDef(t);return e.type=t.getType(),e.componentType=t.getComponentType(),e.count=t.getCount(),this.N.getGraph().listParentEdges(t).some(t=>"attributes"===t.getName()&&"POSITION"===t.getAttributes().key||"input"===t.getName())&&(e.max=t.getMax([]).map(Math.fround),e.min=t.getMin([]).map(Math.fround)),t.getNormalized()&&(e.normalized=t.getNormalized()),e}createImageData(t,e,r){if(this.options.format===T.GLB)this.imageBufferViews.push(e),t.bufferView=this.jsonDoc.json.bufferViews.length,this.jsonDoc.json.bufferViews.push({buffer:0,byteOffset:-1,byteLength:e.byteLength});else{const s=I.mimeTypeToExtension(r.getMimeType());t.uri=this.imageURIGenerator.createURI(r,s),this.jsonDoc.resources[t.uri]=e}}getAccessorUsage(t){const e=this.O.get(t);if(e)return e;for(const e of this.N.getGraph().listParentEdges(t)){const{usage:t}=e.getAttributes();if(t)return t;e.getParent().propertyType!==p.ROOT&&this.N.getLogger().warn(`Missing attribute ".usage" on edge, "${e.getName()}".`)}return bt.BufferViewUsage.OTHER}addAccessorToUsageGroup(t,e){const r=this.O.get(t);if(r&&r!==e)throw new Error(`Accessor with usage "${r}" cannot be reused as "${e}".`);return this.O.set(t,e),this}listAccessorUsageGroups(){const t={};for(const[e,r]of Array.from(this.O.entries()))t[r]=t[r]||[],t[r].push(e);return t}}bt.BufferViewTarget=xt,bt.BufferViewUsage=w,bt.USAGE_TO_TARGET={[w.ARRAY_BUFFER]:xt.ARRAY_BUFFER,[w.ELEMENT_ARRAY_BUFFER]:xt.ELEMENT_ARRAY_BUFFER};class At{constructor(t,e){this.multiple=void 0,this.basename=void 0,this.counter=1,this.multiple=t,this.basename=e}createURI(t,e){return t.getURI()?t.getURI():this.multiple?`${this.basename}_${this.counter++}.${e}`:`${this.basename}.${e}`}}const{BufferViewUsage:Et}=bt;var St;!function(t){t[t.JSON=1313821514]="JSON",t[t.BIN=5130562]="BIN"}(St||(St={}));class Mt{constructor(){this.v=C.DEFAULT_INSTANCE,this.h=new Set,this.C={},this.F=m.INTERLEAVED,this.lastReadBytes=0,this.lastWriteBytes=0}setLogger(t){return this.v=t,this}registerExtensions(t){for(const e of t)this.h.add(e),e.register();return this}registerDependencies(t){return Object.assign(this.C,t),this}setVertexLayout(t){return this.F=t,this}async read(t){return await this.readJSON(await this.readAsJSON(t))}async readAsJSON(t){return t.match(/^data:application\/octet-stream;/)||"glb"===S.extension(t)?this.U(t):this.P(t)}async readJSON(t){return t=this.j(t),this.L(t),class{static read(t,e=Tt){const r=ht({},Tt,e),{json:s}=t,n=new pt;this.validate(t,r);const i=new wt(t),o=s.asset,a=n.getRoot().getAsset();o.copyright&&(a.copyright=o.copyright),o.extras&&(a.extras=o.extras),void 0!==s.extras&&n.getRoot().setExtras(ht({},s.extras));const u=s.extensionsUsed||[],c=s.extensionsRequired||[];for(const t of r.extensions)if(u.includes(t.EXTENSION_NAME)){const e=n.createExtension(t).setRequired(c.includes(t.EXTENSION_NAME));for(const t of e.readDependencies)e.install(t,r.dependencies[t])}const h=s.buffers||[];n.getRoot().listExtensionsUsed().filter(t=>t.prereadTypes.includes(p.BUFFER)).forEach(t=>t.preread(i,p.BUFFER)),i.buffers=h.map(t=>{const e=n.createBuffer(t.name);return t.extras&&e.setExtras(t.extras),t.uri&&0!==t.uri.indexOf("__")&&e.setURI(t.uri),e}),i.bufferViewBuffers=(s.bufferViews||[]).map((e,r)=>{if(!i.bufferViews[r]){const s=t.json.buffers[e.buffer];i.bufferViews[r]=A.toView(s.uri?t.resources[s.uri]:t.resources["@glb.bin"],e.byteOffset||0,e.byteLength)}return i.buffers[e.buffer]}),i.accessors=(s.accessors||[]).map(t=>{const e=n.createAccessor(t.name,i.bufferViewBuffers[t.bufferView]).setType(t.type);if(t.extras&&e.setExtras(t.extras),void 0!==t.normalized&&e.setNormalized(t.normalized),void 0===t.bufferView&&!t.sparse)return e;let r;return r=void 0!==t.sparse?function(t,e){const r=yt[t.componentType],s=W.getElementSize(t.type);let n;n=void 0!==t.bufferView?vt(t,e):new r(t.count*s);const i=t.sparse,o=i.count,a=ht({},t,i.indices,{count:o,type:"SCALAR"}),u=ht({},t,i.values,{count:o}),c=vt(a,e),h=vt(u,e);for(let t=0;t<a.count;t++)for(let e=0;e<s;e++)n[c[t]*s+e]=h[t*s+e];return n}(t,i):vt(t,i),e.setArray(r),e});const l=s.images||[],f=s.textures||[];n.getRoot().listExtensionsUsed().filter(t=>t.prereadTypes.includes(p.TEXTURE)).forEach(t=>t.preread(i,p.TEXTURE)),i.textures=l.map(e=>{const r=n.createTexture(e.name);if(e.extras&&r.setExtras(e.extras),void 0!==e.bufferView){const n=s.bufferViews[e.bufferView],i=t.json.buffers[n.buffer],o=n.byteOffset||0,a=(i.uri?t.resources[i.uri]:t.resources["@glb.bin"]).slice(o,o+n.byteLength);r.setImage(a)}else void 0!==e.uri&&(r.setImage(t.resources[e.uri]),0!==e.uri.indexOf("__")&&r.setURI(e.uri));if(void 0!==e.mimeType)r.setMimeType(e.mimeType);else if(e.uri){const t=S.extension(e.uri);r.setMimeType(I.extensionToMimeType(t))}return r}),i.materials=(s.materials||[]).map(t=>{const e=n.createMaterial(t.name);t.extras&&e.setExtras(t.extras),void 0!==t.alphaMode&&e.setAlphaMode(t.alphaMode),void 0!==t.alphaCutoff&&e.setAlphaCutoff(t.alphaCutoff),void 0!==t.doubleSided&&e.setDoubleSided(t.doubleSided);const r=t.pbrMetallicRoughness||{};if(void 0!==r.baseColorFactor&&e.setBaseColorFactor(r.baseColorFactor),void 0!==t.emissiveFactor&&e.setEmissiveFactor(t.emissiveFactor),void 0!==r.metallicFactor&&e.setMetallicFactor(r.metallicFactor),void 0!==r.roughnessFactor&&e.setRoughnessFactor(r.roughnessFactor),void 0!==r.baseColorTexture){const t=r.baseColorTexture;e.setBaseColorTexture(i.textures[f[t.index].source]),i.setTextureInfo(e.getBaseColorTextureInfo(),t)}if(void 0!==t.emissiveTexture){const r=t.emissiveTexture;e.setEmissiveTexture(i.textures[f[r.index].source]),i.setTextureInfo(e.getEmissiveTextureInfo(),r)}if(void 0!==t.normalTexture){const r=t.normalTexture;e.setNormalTexture(i.textures[f[r.index].source]),i.setTextureInfo(e.getNormalTextureInfo(),r),void 0!==t.normalTexture.scale&&e.setNormalScale(t.normalTexture.scale)}if(void 0!==t.occlusionTexture){const r=t.occlusionTexture;e.setOcclusionTexture(i.textures[f[r.index].source]),i.setTextureInfo(e.getOcclusionTextureInfo(),r),void 0!==t.occlusionTexture.strength&&e.setOcclusionStrength(t.occlusionTexture.strength)}if(void 0!==r.metallicRoughnessTexture){const t=r.metallicRoughnessTexture;e.setMetallicRoughnessTexture(i.textures[f[t.index].source]),i.setTextureInfo(e.getMetallicRoughnessTextureInfo(),t)}return e});const d=s.meshes||[];n.getRoot().listExtensionsUsed().filter(t=>t.prereadTypes.includes(p.PRIMITIVE)).forEach(t=>t.preread(i,p.PRIMITIVE)),i.meshes=d.map(t=>{const e=n.createMesh(t.name);return t.extras&&e.setExtras(t.extras),void 0!==t.weights&&e.setWeights(t.weights),(t.primitives||[]).forEach(r=>{const s=n.createPrimitive();r.extras&&s.setExtras(r.extras),void 0!==r.material&&s.setMaterial(i.materials[r.material]),void 0!==r.mode&&s.setMode(r.mode);for(const[t,e]of Object.entries(r.attributes||{}))s.setAttribute(t,i.accessors[e]);void 0!==r.indices&&s.setIndices(i.accessors[r.indices]);const o=t.extras&&t.extras.targetNames||[];(r.targets||[]).forEach((t,e)=>{const r=o[e]||e.toString(),a=n.createPrimitiveTarget(r);for(const[e,r]of Object.entries(t))a.setAttribute(e,i.accessors[r]);s.addTarget(a)}),e.addPrimitive(s)}),e}),i.cameras=(s.cameras||[]).map(t=>{const e=n.createCamera(t.name).setType(t.type);if(t.extras&&e.setExtras(t.extras),t.type===Q.Type.PERSPECTIVE){const r=t.perspective;e.setYFov(r.yfov),e.setZNear(r.znear),void 0!==r.zfar&&e.setZFar(r.zfar),void 0!==r.aspectRatio&&e.setAspectRatio(r.aspectRatio)}else{const r=t.orthographic;e.setZNear(r.znear).setZFar(r.zfar).setXMag(r.xmag).setYMag(r.ymag)}return e});const g=s.nodes||[];n.getRoot().listExtensionsUsed().filter(t=>t.prereadTypes.includes(p.NODE)).forEach(t=>t.preread(i,p.NODE)),i.nodes=g.map(t=>{const e=n.createNode(t.name);if(t.extras&&e.setExtras(t.extras),void 0!==t.translation&&e.setTranslation(t.translation),void 0!==t.rotation&&e.setRotation(t.rotation),void 0!==t.scale&&e.setScale(t.scale),void 0!==t.matrix){const r=[0,0,0],s=[0,0,0,1],n=[1,1,1];F.decompose(t.matrix,r,s,n),e.setTranslation(r),e.setRotation(s),e.setScale(n)}return void 0!==t.weights&&e.setWeights(t.weights),e}),i.skins=(s.skins||[]).map(t=>{const e=n.createSkin(t.name);t.extras&&e.setExtras(t.extras),void 0!==t.inverseBindMatrices&&e.setInverseBindMatrices(i.accessors[t.inverseBindMatrices]),void 0!==t.skeleton&&e.setSkeleton(i.nodes[t.skeleton]);for(const r of t.joints)e.addJoint(i.nodes[r]);return e}),g.map((t,e)=>{const r=i.nodes[e];(t.children||[]).forEach(t=>r.addChild(i.nodes[t])),void 0!==t.mesh&&r.setMesh(i.meshes[t.mesh]),void 0!==t.camera&&r.setCamera(i.cameras[t.camera]),void 0!==t.skin&&r.setSkin(i.skins[t.skin])}),i.animations=(s.animations||[]).map(t=>{const e=n.createAnimation(t.name);t.extras&&e.setExtras(t.extras);const r=(t.samplers||[]).map(t=>{const r=n.createAnimationSampler().setInput(i.accessors[t.input]).setOutput(i.accessors[t.output]).setInterpolation(t.interpolation||Z.Interpolation.LINEAR);return t.extras&&r.setExtras(t.extras),e.addSampler(r),r});return(t.channels||[]).forEach(t=>{const s=n.createAnimationChannel().setSampler(r[t.sampler]).setTargetNode(i.nodes[t.target.node]).setTargetPath(t.target.path);t.extras&&s.setExtras(t.extras),e.addChannel(s)}),e});const m=s.scenes||[];return n.getRoot().listExtensionsUsed().filter(t=>t.prereadTypes.includes(p.SCENE)).forEach(t=>t.preread(i,p.SCENE)),i.scenes=m.map(t=>{const e=n.createScene(t.name);return t.extras&&e.setExtras(t.extras),(t.nodes||[]).map(t=>i.nodes[t]).forEach(t=>e.addChild(t)),e}),void 0!==s.scene&&n.getRoot().setDefaultScene(i.scenes[s.scene]),n.getRoot().listExtensionsUsed().forEach(t=>t.read(i)),n}static validate(t,e){const r=t.json;if("2.0"!==r.asset.version)throw new Error(`Unsupported glTF version, "${r.asset.version}".`);if(r.extensionsRequired)for(const t of r.extensionsRequired)if(!e.extensions.find(e=>e.EXTENSION_NAME===t))throw new Error(`Missing required extension, "${t}".`);if(r.extensionsUsed)for(const t of r.extensionsUsed)e.extensions.find(e=>e.EXTENSION_NAME===t)||e.logger.warn(`Missing optional extension, "${t}".`)}}.read(t,{extensions:Array.from(this.h),dependencies:this.C,logger:this.v})}async binaryToJSON(t){const e=this._(A.assertView(t));this.L(e);const r=e.json;if(r.buffers&&r.buffers.some(t=>function(t,e){return void 0!==e.uri&&!(e.uri in t.resources)}(e,t)))throw new Error("Cannot resolve external buffers with binaryToJSON().");if(r.images&&r.images.some(t=>function(t,e){return void 0!==e.uri&&!(e.uri in t.resources)&&void 0===e.bufferView}(e,t)))throw new Error("Cannot resolve external images with binaryToJSON().");return e}async readBinary(t){return this.readJSON(await this.binaryToJSON(A.assertView(t)))}async writeJSON(t,e={}){if(e.format===T.GLB&&t.getRoot().listBuffers().length>1)throw new Error("GLB must have 0–1 buffers.");return class{static write(t,e){const r=t.getRoot(),s={asset:ht({generator:"glTF-Transform v2.0.5"},r.getAsset()),extras:ht({},r.getExtras())},n={json:s,resources:{}},i=new bt(t,n,e),o=e.logger||C.DEFAULT_INSTANCE,a=new Set(e.extensions.map(t=>t.EXTENSION_NAME)),u=t.getRoot().listExtensionsUsed().filter(t=>a.has(t.extensionName)),c=t.getRoot().listExtensionsRequired().filter(t=>a.has(t.extensionName));u.length<t.getRoot().listExtensionsUsed().length&&o.debug("Some extensions were not registered for I/O, and will not be written.");for(const t of u)for(const r of t.writeDependencies)t.install(r,e.dependencies[r]);function h(t,e,r,n){const o=[];let a=0;for(const e of t){const t=i.createAccessorDef(e);t.bufferView=s.bufferViews.length;const r=e.getArray(),n=A.pad(A.toView(r));t.byteOffset=a,a+=n.byteLength,o.push(n),i.accessorIndexMap.set(e,s.accessors.length),s.accessors.push(t)}const u={buffer:e,byteOffset:r,byteLength:A.concat(o).byteLength};return n&&(u.target=n),s.bufferViews.push(u),{buffers:o,byteLength:a}}function l(t,e,r){const n=t[0].getCount();let o=0;for(const e of t){const t=i.createAccessorDef(e);t.bufferView=s.bufferViews.length,t.byteOffset=o;const r=e.getElementSize(),n=e.getComponentSize();o+=A.padNumber(r*n),i.accessorIndexMap.set(e,s.accessors.length),s.accessors.push(t)}const a=n*o,u=new ArrayBuffer(a),c=new DataView(u);for(let e=0;e<n;e++){let r=0;for(const s of t){const t=s.getElementSize(),n=s.getComponentSize(),i=s.getComponentType(),a=s.getArray();for(let s=0;s<t;s++){const u=e*o+r+s*n,h=a[e*t+s];switch(i){case W.ComponentType.FLOAT:c.setFloat32(u,h,!0);break;case W.ComponentType.BYTE:c.setInt8(u,h);break;case W.ComponentType.SHORT:c.setInt16(u,h,!0);break;case W.ComponentType.UNSIGNED_BYTE:c.setUint8(u,h);break;case W.ComponentType.UNSIGNED_SHORT:c.setUint16(u,h,!0);break;case W.ComponentType.UNSIGNED_INT:c.setUint32(u,h,!0);break;default:throw new Error("Unexpected component type: "+i)}}r+=A.padNumber(t*n)}}return s.bufferViews.push({buffer:e,byteOffset:r,byteLength:a,byteStride:o,target:bt.BufferViewTarget.ARRAY_BUFFER}),{byteLength:a,buffers:[new Uint8Array(u)]}}const f=new Map;for(const e of t.getGraph().listEdges()){if(e.getParent()===r)continue;const t=e.getChild();if(t instanceof W){const r=f.get(t)||[];r.push(e),f.set(t,r)}}if(s.accessors=[],s.bufferViews=[],s.samplers=[],s.textures=[],s.images=r.listTextures().map((t,e)=>{const r=i.createPropertyDef(t);t.getMimeType()&&(r.mimeType=t.getMimeType());const s=t.getImage();return s&&i.createImageData(r,s,t),i.imageIndexMap.set(t,e),r}),u.filter(t=>t.prewriteTypes.includes(p.ACCESSOR)).forEach(t=>t.prewrite(i,p.ACCESSOR)),r.listAccessors().forEach(t=>{const e=i.accessorUsageGroupedByParent,r=i.accessorParents;if(i.accessorIndexMap.has(t))return;const s=f.get(t)||[],n=i.getAccessorUsage(t);if(i.addAccessorToUsageGroup(t,n),e.has(n)){const e=s[0].getParent(),n=r.get(e)||new Set;n.add(t),r.set(e,n)}}),u.filter(t=>t.prewriteTypes.includes(p.BUFFER)).forEach(t=>t.prewrite(i,p.BUFFER)),(r.listAccessors().length>0||r.listTextures().length>0||i.otherBufferViews.size>0)&&0===r.listBuffers().length)throw new Error("Buffer required for Document resources, but none was found.");s.buffers=[],r.listBuffers().forEach((t,r)=>{const o=i.createPropertyDef(t),a=i.accessorUsageGroupedByParent,u=i.accessorParents,c=t.listParents().filter(t=>t instanceof W),f=new Set(c),d=[],g=s.buffers.length;let p=0;const w=i.listAccessorUsageGroups();for(const t in w)if(a.has(t))for(const r of Array.from(u.values())){const s=Array.from(r).filter(t=>f.has(t)).filter(e=>i.getAccessorUsage(e)===t);if(s.length)if(t!==Et.ARRAY_BUFFER||e.vertexLayout===m.INTERLEAVED){const e=t===Et.ARRAY_BUFFER?l(s,g,p):h(s,g,p);p+=e.byteLength,d.push(...e.buffers)}else for(const t of s){const e=l([t],g,p);p+=e.byteLength,d.push(...e.buffers)}}else{const e=w[t].filter(t=>f.has(t));if(!e.length)continue;const r=h(e,g,p,t===Et.ELEMENT_ARRAY_BUFFER?bt.BufferViewTarget.ELEMENT_ARRAY_BUFFER:void 0);p+=r.byteLength,d.push(...r.buffers)}if(i.imageBufferViews.length&&0===r)for(let t=0;t<i.imageBufferViews.length;t++)if(s.bufferViews[s.images[t].bufferView].byteOffset=p,p+=i.imageBufferViews[t].byteLength,d.push(i.imageBufferViews[t]),p%8){const t=8-p%8;p+=t,d.push(new Uint8Array(t))}if(i.otherBufferViews.has(t))for(const e of i.otherBufferViews.get(t))s.bufferViews.push({buffer:g,byteOffset:p,byteLength:e.byteLength}),i.otherBufferViewsIndexMap.set(e,s.bufferViews.length-1),p+=e.byteLength,d.push(e);if(p){let r;e.format===T.GLB?r="@glb.bin":(r=i.bufferURIGenerator.createURI(t,"bin"),o.uri=r),o.byteLength=p,n.resources[r]=A.concat(d)}s.buffers.push(o),i.bufferIndexMap.set(t,r)}),r.listAccessors().find(t=>!t.getBuffer())&&o.warn("Skipped writing one or more Accessors: no Buffer assigned."),s.materials=r.listMaterials().map((t,e)=>{const r=i.createPropertyDef(t);if(t.getAlphaMode()!==it.AlphaMode.OPAQUE&&(r.alphaMode=t.getAlphaMode()),t.getAlphaMode()===it.AlphaMode.MASK&&(r.alphaCutoff=t.getAlphaCutoff()),t.getDoubleSided()&&(r.doubleSided=!0),r.pbrMetallicRoughness={},F.eq(t.getBaseColorFactor(),[1,1,1,1])||(r.pbrMetallicRoughness.baseColorFactor=t.getBaseColorFactor()),F.eq(t.getEmissiveFactor(),[0,0,0])||(r.emissiveFactor=t.getEmissiveFactor()),1!==t.getRoughnessFactor()&&(r.pbrMetallicRoughness.roughnessFactor=t.getRoughnessFactor()),1!==t.getMetallicFactor()&&(r.pbrMetallicRoughness.metallicFactor=t.getMetallicFactor()),t.getBaseColorTexture()){const e=t.getBaseColorTexture(),s=t.getBaseColorTextureInfo();r.pbrMetallicRoughness.baseColorTexture=i.createTextureInfoDef(e,s)}if(t.getEmissiveTexture()){const e=t.getEmissiveTexture(),s=t.getEmissiveTextureInfo();r.emissiveTexture=i.createTextureInfoDef(e,s)}if(t.getNormalTexture()){const e=t.getNormalTexture(),s=t.getNormalTextureInfo(),n=i.createTextureInfoDef(e,s);1!==t.getNormalScale()&&(n.scale=t.getNormalScale()),r.normalTexture=n}if(t.getOcclusionTexture()){const e=t.getOcclusionTexture(),s=t.getOcclusionTextureInfo(),n=i.createTextureInfoDef(e,s);1!==t.getOcclusionStrength()&&(n.strength=t.getOcclusionStrength()),r.occlusionTexture=n}if(t.getMetallicRoughnessTexture()){const e=t.getMetallicRoughnessTexture(),s=t.getMetallicRoughnessTextureInfo();r.pbrMetallicRoughness.metallicRoughnessTexture=i.createTextureInfoDef(e,s)}return i.materialIndexMap.set(t,e),r}),s.meshes=r.listMeshes().map((t,e)=>{const r=i.createPropertyDef(t);let s=null;return r.primitives=t.listPrimitives().map(t=>{const e={attributes:{}};e.mode=t.getMode();const r=t.getMaterial();r&&(e.material=i.materialIndexMap.get(r)),Object.keys(t.getExtras()).length&&(e.extras=t.getExtras());const n=t.getIndices();n&&(e.indices=i.accessorIndexMap.get(n));for(const r of t.listSemantics())e.attributes[r]=i.accessorIndexMap.get(t.getAttribute(r));for(const r of t.listTargets()){const t={};for(const e of r.listSemantics())t[e]=i.accessorIndexMap.get(r.getAttribute(e));e.targets=e.targets||[],e.targets.push(t)}return t.listTargets().length&&!s&&(s=t.listTargets().map(t=>t.getName())),e}),t.getWeights().length&&(r.weights=t.getWeights()),s&&(r.extras=r.extras||{},r.extras.targetNames=s),i.meshIndexMap.set(t,e),r}),s.cameras=r.listCameras().map((t,e)=>{const r=i.createPropertyDef(t);if(r.type=t.getType(),r.type===Q.Type.PERSPECTIVE){r.perspective={znear:t.getZNear(),zfar:t.getZFar(),yfov:t.getYFov()};const e=t.getAspectRatio();null!==e&&(r.perspective.aspectRatio=e)}else r.orthographic={znear:t.getZNear(),zfar:t.getZFar(),xmag:t.getXMag(),ymag:t.getYMag()};return i.cameraIndexMap.set(t,e),r}),s.nodes=r.listNodes().map((t,e)=>{const r=i.createPropertyDef(t);return F.eq(t.getTranslation(),[0,0,0])||(r.translation=t.getTranslation()),F.eq(t.getRotation(),[0,0,0,1])||(r.rotation=t.getRotation()),F.eq(t.getScale(),[1,1,1])||(r.scale=t.getScale()),t.getWeights().length&&(r.weights=t.getWeights()),i.nodeIndexMap.set(t,e),r}),s.skins=r.listSkins().map((t,e)=>{const r=i.createPropertyDef(t),s=t.getInverseBindMatrices();s&&(r.inverseBindMatrices=i.accessorIndexMap.get(s));const n=t.getSkeleton();return n&&(r.skeleton=i.nodeIndexMap.get(n)),r.joints=t.listJoints().map(t=>i.nodeIndexMap.get(t)),i.skinIndexMap.set(t,e),r}),r.listNodes().forEach((t,e)=>{const r=s.nodes[e],n=t.getMesh();n&&(r.mesh=i.meshIndexMap.get(n));const o=t.getCamera();o&&(r.camera=i.cameraIndexMap.get(o));const a=t.getSkin();a&&(r.skin=i.skinIndexMap.get(a)),t.listChildren().length>0&&(r.children=t.listChildren().map(t=>i.nodeIndexMap.get(t)))}),s.animations=r.listAnimations().map((t,e)=>{const r=i.createPropertyDef(t),s=new Map;return r.samplers=t.listSamplers().map((t,e)=>{const r=i.createPropertyDef(t);return r.input=i.accessorIndexMap.get(t.getInput()),r.output=i.accessorIndexMap.get(t.getOutput()),r.interpolation=t.getInterpolation(),s.set(t,e),r}),r.channels=t.listChannels().map(t=>{const e=i.createPropertyDef(t);return e.sampler=s.get(t.getSampler()),e.target={node:i.nodeIndexMap.get(t.getTargetNode()),path:t.getTargetPath()},e}),i.animationIndexMap.set(t,e),r}),s.scenes=r.listScenes().map((t,e)=>{const r=i.createPropertyDef(t);return r.nodes=t.listChildren().map(t=>i.nodeIndexMap.get(t)),i.sceneIndexMap.set(t,e),r});const d=r.getDefaultScene();return d&&(s.scene=r.listScenes().indexOf(d)),s.extensionsUsed=u.map(t=>t.extensionName),s.extensionsRequired=c.map(t=>t.extensionName),u.forEach(t=>t.write(i)),function(t){const e=[];for(const r in t){const s=t[r];(Array.isArray(s)&&0===s.length||null===s||""===s||s&&"object"==typeof s&&0===Object.keys(s).length)&&e.push(r)}for(const r of e)delete t[r]}(s),n}}.write(t,{format:e.format||T.GLTF,basename:e.basename||"",logger:this.v,vertexLayout:this.F,dependencies:ht({},this.C),extensions:Array.from(this.h)})}async writeBinary(t){const{json:e,resources:r}=await this.writeJSON(t,{format:T.GLB}),s=new Uint32Array([1179937895,2,12]),n=JSON.stringify(e),i=A.pad(A.encodeText(n),32),o=A.toView(new Uint32Array([i.byteLength,1313821514])),a=A.concat([o,i]);s[s.length-1]+=a.byteLength;const u=Object.values(r)[0];if(!u||!u.byteLength)return A.concat([A.toView(s),a]);const c=A.pad(u,0),h=A.toView(new Uint32Array([c.byteLength,5130562])),l=A.concat([h,c]);return s[s.length-1]+=l.byteLength,A.concat([A.toView(s),a,l])}async P(t){this.lastReadBytes=0;const e=await this.readURI(t,"text");this.lastReadBytes+=e.length;const r={json:JSON.parse(e),resources:{}};return await this.D(r,this.dirname(t)),this.L(r),r}async U(t){const e=await this.readURI(t,"view");this.lastReadBytes=e.byteLength;const r=this._(e);return await this.D(r,this.dirname(t)),this.L(r),r}async D(t,e){var r=this;const s=[...t.json.images||[],...t.json.buffers||[]].map(async function(s){const n=s.uri;if(!n||n.match(/data:/))return Promise.resolve();t.resources[n]=await r.readURI(r.resolve(e,n),"view"),r.lastReadBytes+=t.resources[n].byteLength});await Promise.all(s)}L(t){function e(e){if(e.uri)if(e.uri in t.resources)A.assertView(t.resources[e.uri]);else if(e.uri.match(/data:/)){const r=`__${G()}.${S.extension(e.uri)}`;t.resources[r]=A.createBufferFromDataURI(e.uri),e.uri=r}}(t.json.images||[]).forEach(t=>{if(void 0===t.bufferView&&void 0===t.uri)throw new Error("Missing resource URI or buffer view.");e(t)}),(t.json.buffers||[]).forEach(e)}j(t){const{images:e,buffers:r}=t.json;return t={json:ht({},t.json),resources:ht({},t.resources)},e&&(t.json.images=e.map(t=>ht({},t))),r&&(t.json.buffers=r.map(t=>ht({},t))),t}_(t){const e=new Uint32Array(t.buffer,t.byteOffset,3);if(1179937895!==e[0])throw new Error("Invalid glTF asset.");if(2!==e[1])throw new Error(`Unsupported glTF binary version, "${e[1]}".`);const r=new Uint32Array(t.buffer,t.byteOffset+12,2);if(r[1]!==St.JSON)throw new Error("Missing required GLB JSON chunk.");const s=r[0],n=A.decodeText(A.toView(t,20,s)),i=JSON.parse(n),o=20+s;if(t.byteLength<=o)return{json:i,resources:{}};const a=new Uint32Array(t.buffer,t.byteOffset+o,2);if(a[1]!==St.BIN)throw new Error("Expected GLB BIN in second chunk.");return{json:i,resources:{"@glb.bin":A.toView(t,o+8,a[0])}}}}class It extends Mt{constructor(t=null,e=J.DEFAULT_INIT){super(),this.k=void 0,this.J=void 0,this.$=void 0,this.V=void 0,this.q=!1,this.k=require("fs").promises,this.J=require("path"),this.$=t,this.V=e}setAllowHTTP(t){if(t&&!this.$)throw new Error("NodeIO requires a Fetch API implementation for HTTP requests.");return this.q=t,this}async readURI(t,e){if(J.isAbsoluteURL(t)){if(!this.q||!this.$)throw new Error("Network request blocked. Allow HTTP requests explicitly, if needed.");const r=await this.$(t,this.V);switch(e){case"view":return new Uint8Array(await r.arrayBuffer());case"text":return r.text()}}else switch(e){case"view":return this.k.readFile(t);case"text":return this.k.readFile(t,"utf8")}}resolve(t,e){return J.isAbsoluteURL(t)||J.isAbsoluteURL(e)?J.resolve(t,e):this.J.resolve(t,e)}dirname(t){return J.isAbsoluteURL(t)?J.dirname(t):this.J.dirname(t)}async write(t,e){const r=!!t.match(/\.glb$/);await(r?this.W(t,e):this.H(t,e))}async H(t,e){var r=this;this.lastWriteBytes=0;const{json:s,resources:n}=await this.writeJSON(e,{format:T.GLTF,basename:S.basename(t)}),{k:i,J:o}=this,a=o.dirname(t),u=JSON.stringify(s,null,2);this.lastWriteBytes+=u.length,await i.writeFile(t,u);const c=Object.keys(n).map(async function(t){if(J.isAbsoluteURL(t)){if("bin"===S.extension(t))throw new Error(`Cannot write buffer to path "${t}".`);return}const e=Buffer.from(n[t]);await i.writeFile(o.join(a,t),e),r.lastWriteBytes+=e.byteLength});await Promise.all(c)}async W(t,e){const r=Buffer.from(await this.writeBinary(e));await this.k.writeFile(t,r),this.lastWriteBytes=r.byteLength}}class Rt extends Mt{constructor(t){super(),this.J=void 0,this.J=t}async readURI(t,e){switch(e){case"view":return Deno.readFile(t);case"text":return Deno.readTextFile(t)}}resolve(t,e){return this.J.resolve(t,e)}dirname(t){return this.J.dirname(t)}}class Nt extends Mt{constructor(t=J.DEFAULT_INIT){super(),this.V=void 0,this.V=t}async readURI(t,e){const r=await fetch(t,this.V);switch(e){case"view":return new Uint8Array(await r.arrayBuffer());case"text":return r.text()}}resolve(t,e){return J.resolve(t,e)}dirname(t){return J.dirname(t)}}export{W as Accessor,H as Animation,Y as AnimationChannel,Z as AnimationSampler,K as Buffer,A as BufferUtils,$ as COPY_IDENTITY,Q as Camera,E as ColorUtils,Rt as DenoIO,pt as Document,q as ExtensibleProperty,mt as Extension,X as ExtensionProperty,S as FileUtils,T as Format,g as GLB_BUFFER,I as ImageUtils,C as Logger,it as Material,F as MathUtils,ot as Mesh,at as Node,It as NodeIO,Mt as PlatformIO,ut as Primitive,ct as PrimitiveTarget,V as Property,p as PropertyType,wt as ReaderContext,gt as Root,lt as Scene,ft as Skin,dt as Texture,y as TextureChannel,tt as TextureInfo,d as VERSION,m as VertexLayout,Nt as WebIO,bt as WriterContext,v as bounds,G as uuid}; | ||
import{GraphNode as t,$attributes as e,GraphEdge as r,$immutableKeys as s,isRef as n,isRefList as i,isRefMap as o,Graph as a}from"property-graph";export{Graph,GraphEdge}from"property-graph";import{transformMat4 as u,length as c}from"gl-matrix/vec3";import{determinant as h,getRotation as l,multiply as f}from"gl-matrix/mat4";const d="v2.1.0",g="@glb.bin";var p,m,w,y,T;function v(t){const e={min:[Infinity,Infinity,Infinity],max:[-Infinity,-Infinity,-Infinity]},r=t.propertyType===p.NODE?[t]:t.listChildren();for(const t of r)t.traverse(t=>{const r=t.getMesh();if(!r)return;const s=x(r,t.getWorldMatrix());b(s.min,e),b(s.max,e)});return e}function x(t,e){const r={min:[Infinity,Infinity,Infinity],max:[-Infinity,-Infinity,-Infinity]};for(const s of t.listPrimitives()){const t=s.getAttribute("POSITION");if(!t)continue;let n=[0,0,0],i=[0,0,0];for(let s=0;s<t.getCount();s++)n=t.getElement(s,n),i=u(i,n,e),b(i,r)}return r}function b(t,e){for(let r=0;r<3;r++)e.min[r]=Math.min(t[r],e.min[r]),e.max[r]=Math.max(t[r],e.max[r])}!function(t){t.ACCESSOR="Accessor",t.ANIMATION="Animation",t.ANIMATION_CHANNEL="AnimationChannel",t.ANIMATION_SAMPLER="AnimationSampler",t.BUFFER="Buffer",t.CAMERA="Camera",t.MATERIAL="Material",t.MESH="Mesh",t.PRIMITIVE="Primitive",t.PRIMITIVE_TARGET="PrimitiveTarget",t.NODE="Node",t.ROOT="Root",t.SCENE="Scene",t.SKIN="Skin",t.TEXTURE="Texture",t.TEXTURE_INFO="TextureInfo"}(p||(p={})),function(t){t.INTERLEAVED="interleaved",t.SEPARATE="separate"}(m||(m={})),function(t){t.ARRAY_BUFFER="ARRAY_BUFFER",t.ELEMENT_ARRAY_BUFFER="ELEMENT_ARRAY_BUFFER",t.INVERSE_BIND_MATRICES="INVERSE_BIND_MATRICES",t.OTHER="OTHER"}(w||(w={})),function(t){t[t.R=4096]="R",t[t.G=256]="G",t[t.B=16]="B",t[t.A=1]="A"}(y||(y={})),function(t){t.GLTF="GLTF",t.GLB="GLB"}(T||(T={}));class A{static createBufferFromDataURI(t){if("undefined"==typeof Buffer){const e=atob(t.split(",")[1]),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}{const e=t.split(",")[1],r=t.indexOf("base64")>=0;return Buffer.from(e,r?"base64":"utf8")}}static encodeText(t){return"undefined"!=typeof TextEncoder?(new TextEncoder).encode(t):Buffer.from(t)}static decodeText(t){return"undefined"!=typeof TextDecoder?(new TextDecoder).decode(t):Buffer.from(t).toString("utf8")}static concat(t){let e=0;for(const r of t)e+=r.byteLength;const r=new Uint8Array(e);let s=0;for(const e of t)r.set(e,s),s+=e.byteLength;return r}static pad(t,e=0){const r=this.padNumber(t.byteLength);if(r===t.byteLength)return t;const s=new Uint8Array(r);if(s.set(t),0!==e)for(let n=t.byteLength;n<r;n++)s[n]=e;return s}static padNumber(t){return 4*Math.ceil(t/4)}static equals(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;let r=t.byteLength;for(;r--;)if(t[r]!==e[r])return!1;return!0}static toView(t,e=0,r=Infinity){return new Uint8Array(t.buffer,t.byteOffset+e,Math.min(t.byteLength,r))}static assertView(t){if(t&&!ArrayBuffer.isView(t))throw new Error(`Method requires Uint8Array parameter; received "${typeof t}".`);return t}}class E{static hexToFactor(t,e){t=Math.floor(t);const r=e;return r[0]=(t>>16&255)/255,r[1]=(t>>8&255)/255,r[2]=(255&t)/255,this.convertSRGBToLinear(e,e)}static factorToHex(t){const e=[...t],[r,s,n]=this.convertLinearToSRGB(t,e);return 255*r<<16^255*s<<8^255*n<<0}static convertSRGBToLinear(t,e){const r=t,s=e;for(let t=0;t<3;t++)s[t]=r[t]<.04045?.0773993808*r[t]:Math.pow(.9478672986*r[t]+.0521327014,2.4);return e}static convertLinearToSRGB(t,e){const r=t,s=e;for(let t=0;t<3;t++)s[t]=r[t]<.0031308?12.92*r[t]:1.055*Math.pow(r[t],.41666)-.055;return e}}class S{match(t){return t.length>=8&&137===t[0]&&80===t[1]&&78===t[2]&&71===t[3]&&13===t[4]&&10===t[5]&&26===t[6]&&10===t[7]}getSize(t){const e=new DataView(t.buffer,t.byteOffset);return A.decodeText(t.slice(12,16))===S.PNG_FRIED_CHUNK_NAME?[e.getUint32(32,!1),e.getUint32(36,!1)]:[e.getUint32(16,!1),e.getUint32(20,!1)]}getChannels(t){return 4}}S.PNG_FRIED_CHUNK_NAME="CgBI";class M{static registerFormat(t,e){this.impls[t]=e}static getMimeType(t){for(const e in this.impls)if(this.impls[e].match(t))return e;return null}static getSize(t,e){return this.impls[e]?this.impls[e].getSize(t):null}static getChannels(t,e){return this.impls[e]?this.impls[e].getChannels(t):null}static getMemSize(t,e){if(!this.impls[e])return null;if(this.impls[e].getGPUByteLength)return this.impls[e].getGPUByteLength(t);let r=0;const s=this.getSize(t,e);if(!s)return null;for(;s[0]>1||s[1]>1;)r+=s[0]*s[1]*4,s[0]=Math.max(Math.floor(s[0]/2),1),s[1]=Math.max(Math.floor(s[1]/2),1);return r+=4,r}static mimeTypeToExtension(t){return"image/jpeg"===t?"jpg":t.split("/").pop()}static extensionToMimeType(t){return"jpg"===t?"image/jpeg":`image/${t}`}}function I(t,e){if(e>t.byteLength)throw new TypeError("Corrupt JPG, exceeded buffer limits");if(255!==t.getUint8(e))throw new TypeError("Invalid JPG, marker table corrupted");return t}M.impls={"image/jpeg":new class{match(t){return t.length>=3&&255===t[0]&&216===t[1]&&255===t[2]}getSize(t){let e,r,s=new DataView(t.buffer,t.byteOffset+4);for(;s.byteLength;){if(e=s.getUint16(0,!1),I(s,e),r=s.getUint8(e+1),192===r||193===r||194===r)return[s.getUint16(e+7,!1),s.getUint16(e+5,!1)];s=new DataView(t.buffer,s.byteOffset+e+2)}throw new TypeError("Invalid JPG, no size found")}getChannels(t){return 3}},"image/png":new S};class R{static basename(t){const e=t.split(/[\\/]/).pop();return e.substring(0,e.lastIndexOf("."))}static extension(t){if(t.startsWith("data:image/")){const e=t.match(/data:(image\/\w+)/)[1];return M.mimeTypeToExtension(e)}return t.startsWith("data:model/gltf+json")?"gltf":t.startsWith("data:model/gltf-binary")?"glb":t.startsWith("data:application/")?"bin":t.split(/[\\/]/).pop().split(/[.]/).pop()}}function N(t){return"[object Object]"===Object.prototype.toString.call(t)}function O(t){if(!1===N(t))return!1;const e=t.constructor;if(void 0===e)return!0;const r=e.prototype;return!1!==N(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}class C{constructor(t){this.verbosity=void 0,this.verbosity=t}debug(t){this.verbosity<=C.Verbosity.DEBUG&&console.debug(t)}info(t){this.verbosity<=C.Verbosity.INFO&&console.info(t)}warn(t){this.verbosity<=C.Verbosity.WARN&&console.warn(t)}error(t){this.verbosity<=C.Verbosity.ERROR&&console.error(t)}}C.Verbosity={SILENT:4,ERROR:3,WARN:2,INFO:1,DEBUG:0},C.DEFAULT_INSTANCE=new C(C.Verbosity.INFO);class F{static identity(t){return t}static eq(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(Math.abs(t[r]-e[r])>1e-5)return!1;return!0}static denormalize(t,e){switch(e){case 5126:return t;case 5123:return t/65535;case 5121:return t/255;case 5122:return Math.max(t/32767,-1);case 5120:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}static normalize(t,e){switch(e){case 5126:return t;case 5123:return Math.round(65535*t);case 5121:return Math.round(255*t);case 5122:return Math.round(32767*t);case 5120:return Math.round(127*t);default:throw new Error("Invalid component type.")}}static decompose(t,e,r,s){let n=c([t[0],t[1],t[2]]);const i=c([t[4],t[5],t[6]]),o=c([t[8],t[9],t[10]]);h(t)<0&&(n=-n),e[0]=t[12],e[1]=t[13],e[2]=t[14];const a=t.slice(),u=1/n,f=1/i,d=1/o;a[0]*=u,a[1]*=u,a[2]*=u,a[4]*=f,a[5]*=f,a[6]*=f,a[8]*=d,a[9]*=d,a[10]*=d,l(r,a),s[0]=n,s[1]=i,s[2]=o}static compose(t,e,r,s){const n=s,i=e[0],o=e[1],a=e[2],u=e[3],c=i+i,h=o+o,l=a+a,f=i*c,d=i*h,g=i*l,p=o*h,m=o*l,w=a*l,y=u*c,T=u*h,v=u*l,x=r[0],b=r[1],A=r[2];return n[0]=(1-(p+w))*x,n[1]=(d+v)*x,n[2]=(g-T)*x,n[3]=0,n[4]=(d-v)*b,n[5]=(1-(f+w))*b,n[6]=(m+y)*b,n[7]=0,n[8]=(g+T)*A,n[9]=(m-y)*A,n[10]=(1-(f+p))*A,n[11]=0,n[12]=t[0],n[13]=t[1],n[14]=t[2],n[15]=1,n}}function B(t,e){if(!!t!=!!e)return!1;const r=t.getChild(),s=e.getChild();return r===s||r.equals(s)}function U(t,e){if(!!t!=!!e)return!1;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){const s=t[r],n=e[r];if(s.getChild()!==n.getChild()&&!s.getChild().equals(n.getChild()))return!1}return!0}function P(t,e){if(!!t!=!!e)return!1;const r=Object.keys(t),s=Object.keys(e);if(r.length!==s.length)return!1;for(const r in t){const s=t[r],n=e[r];if(!!s!=!!n)return!1;const i=s.getChild(),o=n.getChild();if(i!==o&&!i.equals(o))return!1}return!0}function j(t,e){if(t===e)return!0;if(!!t!=!!e||!t||!e)return!1;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}function L(t,e){if(t===e)return!0;if(!!t!=!!e)return!1;if(!O(t)||!O(e))return t===e;const r=t,s=e;let n,i=0,o=0;for(n in r)i++;for(n in s)o++;if(i!==o)return!1;for(n in r){const t=r[n],e=s[n];if(_(t)&&_(e)){if(!j(t,e))return!1}else if(O(t)&&O(e)){if(!L(t,e))return!1}else if(t!==e)return!1}return!0}function _(t){return Array.isArray(t)||ArrayBuffer.isView(t)}const D="23456789abdegjkmnpqrvwxyzABDEGJKMNPQRVWXYZ",k=new Set,z=function(){let t="";for(let e=0;e<6;e++)t+=D.charAt(Math.floor(Math.random()*D.length));return t},G=function(){for(let t=0;t<999;t++){const t=z();if(!k.has(t))return k.add(t),t}return""};class J{static dirname(t){const e=t.lastIndexOf("/");return-1===e?"./":t.substring(0,e+1)}static basename(t){return R.basename(new URL(t,"https://null.example").pathname)}static extension(t){return R.extension(new URL(t,"https://null.example").pathname)}static resolve(t,e){if(!this.isRelativePath(e))return e;const r=t.split("/"),s=e.split("/");r.pop();for(let t=0;t<s.length;t++)"."!==s[t]&&(".."===s[t]?r.pop():r.push(s[t]));return r.join("/")}static isAbsoluteURL(t){return this.PROTOCOL_REGEXP.test(t)}static isRelativePath(t){return!/^(?:[a-zA-Z]+:)?\//.test(t)}}J.DEFAULT_INIT={},J.PROTOCOL_REGEXP=/^[a-zA-Z]+:\/\//;const $=t=>t;class V extends t{constructor(t,r=""){super(t),this[e].name=r,this.init(),this.dispatchEvent({type:"create"})}getDefaults(){return Object.assign(super.getDefaults(),{name:"",extras:{}})}getName(){return this.get("name")}setName(t){return this.set("name",t)}getExtras(){return this.get("extras")}setExtras(t){return this.set("extras",t)}clone(){return new(0,this.constructor)(this.graph).copy(this,$)}copy(t,n=$){for(const t in this[e]){const n=this[e][t];if(n instanceof r)this[s].has(t)||n.dispose();else if(Array.isArray(n)&&n[0]instanceof r)for(const t of n)t.dispose();else if(O(n)&&Object.values(n)[0]instanceof r)for(const t in n)n[t].dispose()}for(const i in t[e]){const o=this[e][i],a=t[e][i];if(a instanceof r)this[s].has(i)?o.getChild().copy(n(a.getChild()),n):this.setRef(i,n(a.getChild()),a.getAttributes());else if(Array.isArray(a)&&a[0]instanceof r)for(const t of a)this.addRef(i,n(t.getChild()),t.getAttributes());else if(O(a)&&Object.values(a)[0]instanceof r)for(const t in a){const e=a[t];this.setRefMap(i,t,n(e.getChild()),e.getAttributes())}else this[e][i]=O(a)?JSON.parse(JSON.stringify(a)):Array.isArray(a)||a instanceof ArrayBuffer||ArrayBuffer.isView(a)?a.slice():a}return this}equals(t){if(this===t)return!0;if(this.propertyType!==t.propertyType)return!1;for(const r in this[e]){const s=this[e][r],a=t[e][r];if(n(s)||n(a)){if(!B(s,a))return!1}else if(i(s)||i(a)){if(!U(s,a))return!1}else if(o(s)||o(a)){if(!P(s,a))return!1}else if(O(s)||O(a)){if(!L(s,a))return!1}else if(_(s)||_(a)){if(!j(s,a))return!1}else if(s!==a)return!1}return!0}detach(){return this.graph.disconnectParents(this,t=>"Root"!==t.propertyType),this}listParents(){return this.graph.listParents(this)}}class q extends V{getDefaults(){return Object.assign(super.getDefaults(),{extensions:{}})}getExtension(t){return this.getRefMap("extensions",t)}setExtension(t,e){return e&&e.t(this),this.setRefMap("extensions",t,e)}listExtensions(){return this.listRefMapValues("extensions")}}class W extends q{constructor(...t){super(...t),this.i=F.identity,this.o=F.identity}init(){this.propertyType=p.ACCESSOR}getDefaults(){return Object.assign(super.getDefaults(),{array:null,type:W.Type.SCALAR,componentType:W.ComponentType.FLOAT,normalized:!1,buffer:null})}copy(t,e=$){return super.copy(t,e),this.i=t.i,this.o=t.o,this}static getElementSize(t){switch(t){case W.Type.SCALAR:return 1;case W.Type.VEC2:return 2;case W.Type.VEC3:return 3;case W.Type.VEC4:case W.Type.MAT2:return 4;case W.Type.MAT3:return 9;case W.Type.MAT4:return 16;default:throw new Error("Unexpected type: "+t)}}static getComponentSize(t){switch(t){case W.ComponentType.BYTE:case W.ComponentType.UNSIGNED_BYTE:return 1;case W.ComponentType.SHORT:case W.ComponentType.UNSIGNED_SHORT:return 2;case W.ComponentType.UNSIGNED_INT:case W.ComponentType.FLOAT:return 4;default:throw new Error("Unexpected component type: "+t)}}getMinNormalized(t){const e=this.getElementSize();this.getMin(t);for(let r=0;r<e;r++)t[r]=this.o(t[r]);return t}getMin(t){const e=this.get("array"),r=this.getCount(),s=this.getElementSize();for(let e=0;e<s;e++)t[e]=Infinity;for(let n=0;n<r*s;n+=s)for(let r=0;r<s;r++){const s=e[n+r];Number.isFinite(s)&&(t[r]=Math.min(t[r],s))}return t}getMaxNormalized(t){const e=this.getElementSize();this.getMax(t);for(let r=0;r<e;r++)t[r]=this.o(t[r]);return t}getMax(t){const e=this.get("array"),r=this.getCount(),s=this.getElementSize();for(let e=0;e<s;e++)t[e]=-Infinity;for(let n=0;n<r*s;n+=s)for(let r=0;r<s;r++){const s=e[n+r];Number.isFinite(s)&&(t[r]=Math.max(t[r],s))}return t}getCount(){const t=this.get("array");return t?t.length/this.getElementSize():0}getType(){return this.get("type")}setType(t){return this.set("type",t)}getElementSize(){return W.getElementSize(this.get("type"))}getComponentSize(){return this.get("array").BYTES_PER_ELEMENT}getComponentType(){return this.get("componentType")}getNormalized(){return this.get("normalized")}setNormalized(t){return this.set("normalized",t),t?(this.o=t=>F.denormalize(t,this.get("componentType")),this.i=t=>F.normalize(t,this.get("componentType"))):(this.o=F.identity,this.i=F.identity),this}getScalar(t){const e=this.getElementSize();return this.o(this.get("array")[t*e])}setScalar(t,e){return this.get("array")[t*this.getElementSize()]=this.i(e),this}getElement(t,e){const r=this.getElementSize(),s=this.get("array");for(let n=0;n<r;n++)e[n]=this.o(s[t*r+n]);return e}setElement(t,e){const r=this.getElementSize(),s=this.get("array");for(let n=0;n<r;n++)s[t*r+n]=this.i(e[n]);return this}getBuffer(){return this.getRef("buffer")}setBuffer(t){return this.setRef("buffer",t)}getArray(){return this.get("array")}setArray(t){return this.set("componentType",t?function(t){switch(t.constructor){case Float32Array:return W.ComponentType.FLOAT;case Uint32Array:return W.ComponentType.UNSIGNED_INT;case Uint16Array:return W.ComponentType.UNSIGNED_SHORT;case Uint8Array:return W.ComponentType.UNSIGNED_BYTE;case Int16Array:return W.ComponentType.SHORT;case Int8Array:return W.ComponentType.BYTE;default:throw new Error("Unknown accessor componentType.")}}(t):W.ComponentType.FLOAT),this.set("array",t),this}getByteLength(){const t=this.get("array");return t?t.byteLength:0}}W.Type={SCALAR:"SCALAR",VEC2:"VEC2",VEC3:"VEC3",VEC4:"VEC4",MAT2:"MAT2",MAT3:"MAT3",MAT4:"MAT4"},W.ComponentType={BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,UNSIGNED_INT:5125,FLOAT:5126};class H extends q{init(){this.propertyType=p.ANIMATION}getDefaults(){return Object.assign(super.getDefaults(),{channels:[],samplers:[]})}addChannel(t){return this.addRef("channels",t)}removeChannel(t){return this.removeRef("channels",t)}listChannels(){return this.listRefs("channels")}addSampler(t){return this.addRef("samplers",t)}removeSampler(t){return this.removeRef("samplers",t)}listSamplers(){return this.listRefs("samplers")}}class Y extends q{init(){this.propertyType=p.ANIMATION_CHANNEL}getDefaults(){return Object.assign(super.getDefaults(),{targetPath:null,targetNode:null,sampler:null})}getTargetPath(){return this.get("targetPath")}setTargetPath(t){return this.set("targetPath",t)}getTargetNode(){return this.getRef("targetNode")}setTargetNode(t){return this.setRef("targetNode",t)}getSampler(){return this.getRef("sampler")}setSampler(t){return this.setRef("sampler",t)}}Y.TargetPath={TRANSLATION:"translation",ROTATION:"rotation",SCALE:"scale",WEIGHTS:"weights"};class Z extends q{init(){this.propertyType=p.ANIMATION_SAMPLER}getDefaultAttributes(){return Object.assign(super.getDefaults(),{interpolation:Z.Interpolation.LINEAR,input:null,output:null})}getInterpolation(){return this.get("interpolation")}setInterpolation(t){return this.set("interpolation",t)}getInput(){return this.getRef("input")}setInput(t){return this.setRef("input",t,{usage:w.OTHER})}getOutput(){return this.getRef("output")}setOutput(t){return this.setRef("output",t,{usage:w.OTHER})}}Z.Interpolation={LINEAR:"LINEAR",STEP:"STEP",CUBICSPLINE:"CUBICSPLINE"};class K extends q{init(){this.propertyType=p.BUFFER}getDefaults(){return Object.assign(super.getDefaults(),{uri:""})}getURI(){return this.get("uri")}setURI(t){return this.set("uri",t)}}class Q extends q{init(){this.propertyType=p.CAMERA}getDefaults(){return Object.assign(super.getDefaults(),{type:Q.Type.PERSPECTIVE,znear:.1,zfar:100,aspectRatio:null,yfov:2*Math.PI*50/360,xmag:1,ymag:1})}getType(){return this.get("type")}setType(t){return this.set("type",t)}getZNear(){return this.get("znear")}setZNear(t){return this.set("znear",t)}getZFar(){return this.get("zfar")}setZFar(t){return this.set("zfar",t)}getAspectRatio(){return this.get("aspectRatio")}setAspectRatio(t){return this.set("aspectRatio",t)}getYFov(){return this.get("yfov")}setYFov(t){return this.set("yfov",t)}getXMag(){return this.get("xmag")}setXMag(t){return this.set("xmag",t)}getYMag(){return this.get("ymag")}setYMag(t){return this.set("ymag",t)}}Q.Type={PERSPECTIVE:"perspective",ORTHOGRAPHIC:"orthographic"};class X extends V{t(t){if(!this.parentTypes.includes(t.propertyType))throw new Error(`Parent "${t.propertyType}" invalid for child "${this.propertyType}".`)}}X.EXTENSION_NAME=void 0;class tt extends q{init(){this.propertyType=p.TEXTURE_INFO}getDefaults(){return Object.assign(super.getDefaults(),{texCoord:0,magFilter:null,minFilter:null,wrapS:tt.WrapMode.REPEAT,wrapT:tt.WrapMode.REPEAT})}getTexCoord(){return this.get("texCoord")}setTexCoord(t){return this.set("texCoord",t)}getMagFilter(){return this.get("magFilter")}setMagFilter(t){return this.set("magFilter",t)}getMinFilter(){return this.get("minFilter")}setMinFilter(t){return this.set("minFilter",t)}getWrapS(){return this.get("wrapS")}setWrapS(t){return this.set("wrapS",t)}getWrapT(){return this.get("wrapT")}setWrapT(t){return this.set("wrapT",t)}}tt.WrapMode={CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497},tt.MagFilter={NEAREST:9728,LINEAR:9729},tt.MinFilter={NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987};const{R:et,G:rt,B:st,A:nt}=y;class it extends q{init(){this.propertyType=p.MATERIAL}getDefaults(){return Object.assign(super.getDefaults(),{alphaMode:it.AlphaMode.OPAQUE,alphaCutoff:.5,doubleSided:!1,baseColorFactor:[1,1,1,1],baseColorTexture:null,baseColorTextureInfo:new tt(this.graph,"baseColorTextureInfo"),emissiveFactor:[0,0,0],emissiveTexture:null,emissiveTextureInfo:new tt(this.graph,"emissiveTextureInfo"),normalScale:1,normalTexture:null,normalTextureInfo:new tt(this.graph,"normalTextureInfo"),occlusionStrength:1,occlusionTexture:null,occlusionTextureInfo:new tt(this.graph,"occlusionTextureInfo"),roughnessFactor:1,metallicFactor:1,metallicRoughnessTexture:null,metallicRoughnessTextureInfo:new tt(this.graph,"metallicRoughnessTextureInfo")})}getDoubleSided(){return this.get("doubleSided")}setDoubleSided(t){return this.set("doubleSided",t)}getAlpha(){return this.get("baseColorFactor")[3]}setAlpha(t){const e=this.get("baseColorFactor").slice();return e[3]=t,this.set("baseColorFactor",e)}getAlphaMode(){return this.get("alphaMode")}setAlphaMode(t){return this.set("alphaMode",t)}getAlphaCutoff(){return this.get("alphaCutoff")}setAlphaCutoff(t){return this.set("alphaCutoff",t)}getBaseColorFactor(){return this.get("baseColorFactor")}setBaseColorFactor(t){return this.set("baseColorFactor",t)}getBaseColorHex(){return E.factorToHex(this.get("baseColorFactor"))}setBaseColorHex(t){const e=this.get("baseColorFactor").slice();return this.set("baseColorFactor",E.hexToFactor(t,e))}getBaseColorTexture(){return this.getRef("baseColorTexture")}getBaseColorTextureInfo(){return this.getRef("baseColorTexture")?this.getRef("baseColorTextureInfo"):null}setBaseColorTexture(t){return this.setRef("baseColorTexture",t,{channels:et|rt|st|nt})}getEmissiveFactor(){return this.get("emissiveFactor")}setEmissiveFactor(t){return this.set("emissiveFactor",t)}getEmissiveHex(){return E.factorToHex(this.get("emissiveFactor"))}setEmissiveHex(t){const e=this.get("emissiveFactor").slice();return this.set("emissiveFactor",E.hexToFactor(t,e))}getEmissiveTexture(){return this.getRef("emissiveTexture")}getEmissiveTextureInfo(){return this.getRef("emissiveTexture")?this.getRef("emissiveTextureInfo"):null}setEmissiveTexture(t){return this.setRef("emissiveTexture",t,{channels:et|rt|st})}getNormalScale(){return this.get("normalScale")}setNormalScale(t){return this.set("normalScale",t)}getNormalTexture(){return this.getRef("normalTexture")}getNormalTextureInfo(){return this.getRef("normalTexture")?this.getRef("normalTextureInfo"):null}setNormalTexture(t){return this.setRef("normalTexture",t,{channels:et|rt|st})}getOcclusionStrength(){return this.get("occlusionStrength")}setOcclusionStrength(t){return this.set("occlusionStrength",t)}getOcclusionTexture(){return this.getRef("occlusionTexture")}getOcclusionTextureInfo(){return this.getRef("occlusionTexture")?this.getRef("occlusionTextureInfo"):null}setOcclusionTexture(t){return this.setRef("occlusionTexture",t,{channels:et})}getRoughnessFactor(){return this.get("roughnessFactor")}setRoughnessFactor(t){return this.set("roughnessFactor",t)}getMetallicFactor(){return this.get("metallicFactor")}setMetallicFactor(t){return this.set("metallicFactor",t)}getMetallicRoughnessTexture(){return this.getRef("metallicRoughnessTexture")}getMetallicRoughnessTextureInfo(){return this.getRef("metallicRoughnessTexture")?this.getRef("metallicRoughnessTextureInfo"):null}setMetallicRoughnessTexture(t){return this.setRef("metallicRoughnessTexture",t,{channels:rt|st})}}it.AlphaMode={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};class ot extends q{init(){this.propertyType=p.MESH}getDefaults(){return Object.assign(super.getDefaults(),{weights:[],primitives:[]})}addPrimitive(t){return this.addRef("primitives",t)}removePrimitive(t){return this.removeRef("primitives",t)}listPrimitives(){return this.listRefs("primitives")}getWeights(){return this.get("weights")}setWeights(t){return this.set("weights",t)}}class at extends q{constructor(...t){super(...t),this.u=null}init(){this.propertyType=p.NODE}getDefaults(){return Object.assign(super.getDefaults(),{translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1],weights:[],camera:null,mesh:null,skin:null,children:[]})}copy(t,e=$){if(e===$)throw new Error("Node cannot be copied.");return super.copy(t,e)}getTranslation(){return this.get("translation")}getRotation(){return this.get("rotation")}getScale(){return this.get("scale")}setTranslation(t){return this.set("translation",t)}setRotation(t){return this.set("rotation",t)}setScale(t){return this.set("scale",t)}getMatrix(){return F.compose(this.get("translation"),this.get("rotation"),this.get("scale"),[])}setMatrix(t){const e=this.get("translation").slice(),r=this.get("rotation").slice(),s=this.get("scale").slice();return F.decompose(t,e,r,s),this.set("translation",e).set("rotation",r).set("scale",s)}getWorldTranslation(){const t=[0,0,0];return F.decompose(this.getWorldMatrix(),t,[0,0,0,1],[1,1,1]),t}getWorldRotation(){const t=[0,0,0,1];return F.decompose(this.getWorldMatrix(),[0,0,0],t,[1,1,1]),t}getWorldScale(){const t=[1,1,1];return F.decompose(this.getWorldMatrix(),[0,0,0],[0,0,0,1],t),t}getWorldMatrix(){const t=[];for(let e=this;e instanceof at;e=e.u)t.push(e);let e;const r=t.pop().getMatrix();for(;e=t.pop();)f(r,r,e.getMatrix());return r}addChild(t){t.u&&t.u.removeChild(t),this.addRef("children",t),t.u=this;const r=this[e].children;return r[r.length-1].addEventListener("dispose",()=>t.u=null),this}removeChild(t){return this.removeRef("children",t)}listChildren(){return this.listRefs("children")}getParent(){return this.u}getMesh(){return this.getRef("mesh")}setMesh(t){return this.setRef("mesh",t)}getCamera(){return this.getRef("camera")}setCamera(t){return this.setRef("camera",t)}getSkin(){return this.getRef("skin")}setSkin(t){return this.setRef("skin",t)}getWeights(){return this.get("weights")}setWeights(t){return this.set("weights",t)}traverse(t){t(this);for(const e of this.listChildren())e.traverse(t);return this}}class ut extends q{init(){this.propertyType=p.PRIMITIVE}getDefaults(){return Object.assign(super.getDefaults(),{mode:ut.Mode.TRIANGLES,material:null,indices:null,attributes:{},targets:[]})}getIndices(){return this.getRef("indices")}setIndices(t){return this.setRef("indices",t,{usage:w.ELEMENT_ARRAY_BUFFER})}getAttribute(t){return this.getRefMap("attributes",t)}setAttribute(t,e){return this.setRefMap("attributes",t,e,{usage:w.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}getMaterial(){return this.getRef("material")}setMaterial(t){return this.setRef("material",t)}getMode(){return this.get("mode")}setMode(t){return this.set("mode",t)}listTargets(){return this.listRefs("targets")}addTarget(t){return this.addRef("targets",t)}removeTarget(t){return this.removeRef("targets",t)}}ut.Mode={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6};class ct extends V{init(){this.propertyType=p.PRIMITIVE_TARGET}getDefaults(){return Object.assign(super.getDefaults(),{attributes:{}})}getAttribute(t){return this.getRefMap("attributes",t)}setAttribute(t,e){return this.setRefMap("attributes",t,e,{usage:w.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}}function ht(){return(ht=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(t[s]=r[s])}return t}).apply(this,arguments)}class lt extends q{init(){this.propertyType=p.SCENE}getDefaults(){return Object.assign(super.getDefaults(),{children:[]})}copy(t,e=$){if(e===$)throw new Error("Scene cannot be copied.");return super.copy(t,e)}addChild(t){t.u&&t.u.removeChild(t),this.addRef("children",t),t.u=this;const r=this[e].children;return r[r.length-1].addEventListener("dispose",()=>t.u=null),this}removeChild(t){return this.removeRef("children",t)}listChildren(){return this.listRefs("children")}traverse(t){for(const e of this.listChildren())e.traverse(t);return this}}class ft extends q{init(){this.propertyType=p.SKIN}getDefaults(){return Object.assign(super.getDefaults(),{skeleton:null,inverseBindMatrices:null,joints:[]})}getSkeleton(){return this.getRef("skeleton")}setSkeleton(t){return this.setRef("skeleton",t)}getInverseBindMatrices(){return this.getRef("inverseBindMatrices")}setInverseBindMatrices(t){return this.setRef("inverseBindMatrices",t,{usage:w.INVERSE_BIND_MATRICES})}addJoint(t){return this.addRef("joints",t)}removeJoint(t){return this.removeRef("joints",t)}listJoints(){return this.listRefs("joints")}}class dt extends q{init(){this.propertyType=p.TEXTURE}getDefaults(){return Object.assign(super.getDefaults(),{image:null,mimeType:"",uri:""})}getMimeType(){return this.get("mimeType")||M.extensionToMimeType(R.extension(this.get("uri")))}setMimeType(t){return this.set("mimeType",t)}getURI(){return this.get("uri")}setURI(t){return this.set("uri",t),this.set("mimeType",M.extensionToMimeType(R.extension(t))),this}getImage(){return this.get("image")}setImage(t){return this.set("image",A.assertView(t))}getSize(){const t=this.get("image");return t?M.getSize(t,this.getMimeType()):null}}class gt extends q{init(){this.propertyType=p.ROOT}getDefaults(){return Object.assign(super.getDefaults(),{asset:{generator:"glTF-Transform v2.1.0",version:"2.0"},defaultScene:null,accessors:[],animations:[],buffers:[],cameras:[],materials:[],meshes:[],nodes:[],scenes:[],skins:[],textures:[]})}constructor(t){super(t),this.h=new Set,t.addEventListener("node:create",t=>{this.l(t.target)})}clone(){throw new Error("Root cannot be cloned.")}copy(t,e=$){if(e===$)throw new Error("Root cannot be copied.");this.set("asset",ht({},t.get("asset"))),this.setName(t.getName()),this.setExtras(ht({},t.getExtras())),this.setDefaultScene(t.getDefaultScene()?e(t.getDefaultScene()):null);for(const r of t.listRefMapKeys("extensions")){const s=t.getExtension(r);this.setExtension(r,e(s))}return this}l(t){return t instanceof lt?this.addRef("scenes",t):t instanceof at?this.addRef("nodes",t):t instanceof Q?this.addRef("cameras",t):t instanceof ft?this.addRef("skins",t):t instanceof ot?this.addRef("meshes",t):t instanceof it?this.addRef("materials",t):t instanceof dt?this.addRef("textures",t):t instanceof H?this.addRef("animations",t):t instanceof W?this.addRef("accessors",t):t instanceof K&&this.addRef("buffers",t),this}getAsset(){return this.get("asset")}listExtensionsUsed(){return Array.from(this.h)}listExtensionsRequired(){return this.listExtensionsUsed().filter(t=>t.isRequired())}g(t){return this.h.add(t),this}p(t){return this.h.delete(t),this}listScenes(){return this.listRefs("scenes")}setDefaultScene(t){return this.setRef("defaultScene",t)}getDefaultScene(){return this.getRef("defaultScene")}listNodes(){return this.listRefs("nodes")}listCameras(){return this.listRefs("cameras")}listSkins(){return this.listRefs("skins")}listMeshes(){return this.listRefs("meshes")}listMaterials(){return this.listRefs("materials")}listTextures(){return this.listRefs("textures")}listAnimations(){return this.listRefs("animations")}listAccessors(){return this.listRefs("accessors")}listBuffers(){return this.listRefs("buffers")}}class pt{constructor(){this.m=new a,this.T=new gt(this.m),this.v=C.DEFAULT_INSTANCE}getRoot(){return this.T}getGraph(){return this.m}getLogger(){return this.v}setLogger(t){return this.v=t,this}clone(){return(new pt).setLogger(this.v).merge(this)}merge(t){for(const e of t.getRoot().listExtensionsUsed()){const t=this.createExtension(e.constructor);e.isRequired()&&t.setRequired(!0)}const e=new Set,r=new Map;e.add(t.T),r.set(t.T,this.T);for(const s of t.m.listEdges())for(const t of[s.getParent(),s.getChild()]){if(e.has(t))continue;let s;s=t.propertyType===p.TEXTURE_INFO?t:new(0,t.constructor)(this.m),r.set(t,s),e.add(t)}const s=t=>{const e=r.get(t);if(!e)throw new Error("Could resolve property.");return e};for(const t of e){const e=r.get(t);if(!e)throw new Error("Could resolve property.");e.copy(t,s)}return this}async transform(...t){const e=t.map(t=>t.name);for(const r of t)await r(this,{stack:e});return this}createExtension(t){const e=t.EXTENSION_NAME;return this.getRoot().listExtensionsUsed().find(t=>t.extensionName===e)||new t(this)}createScene(t=""){return new lt(this.m,t)}createNode(t=""){return new at(this.m,t)}createCamera(t=""){return new Q(this.m,t)}createSkin(t=""){return new ft(this.m,t)}createMesh(t=""){return new ot(this.m,t)}createPrimitive(){return new ut(this.m)}createPrimitiveTarget(t=""){return new ct(this.m,t)}createMaterial(t=""){return new it(this.m,t)}createTexture(t=""){return new dt(this.m,t)}createAnimation(t=""){return new H(this.m,t)}createAnimationChannel(t=""){return new Y(this.m,t)}createAnimationSampler(t=""){return new Z(this.m,t)}createAccessor(t="",e=null){return e||(e=this.getRoot().listBuffers()[0]),new W(this.m,t).setBuffer(e)}createBuffer(t=""){return new K(this.m,t)}}class mt{constructor(t){this.extensionName="",this.prereadTypes=[],this.prewriteTypes=[],this.readDependencies=[],this.writeDependencies=[],this.document=void 0,this.required=!1,this.properties=new Set,this.S=void 0,this.document=t,t.getRoot().g(this),this.S=t=>{const e=t,r=e.target;r instanceof X&&r.extensionName===this.extensionName&&("node:create"===e.type&&this.M(r),"node:dispose"===e.type&&this.I(r))};const e=t.getGraph();e.addEventListener("node:create",this.S),e.addEventListener("node:dispose",this.S)}dispose(){this.document.getRoot().p(this);const t=this.document.getGraph();t.removeEventListener("node:create",this.S),t.removeEventListener("node:dispose",this.S);for(const t of this.properties)t.dispose()}static register(){}isRequired(){return this.required}setRequired(t){return this.required=t,this}M(t){return this.properties.add(t),this}I(t){return this.properties.delete(t),this}install(t,e){return this}preread(t,e){return this}prewrite(t,e){return this}}mt.EXTENSION_NAME=void 0;class wt{constructor(t){this.jsonDoc=void 0,this.buffers=[],this.bufferViews=[],this.bufferViewBuffers=[],this.accessors=[],this.textures=[],this.textureInfos=new Map,this.materials=[],this.meshes=[],this.cameras=[],this.nodes=[],this.skins=[],this.animations=[],this.scenes=[],this.jsonDoc=t}setTextureInfo(t,e){this.textureInfos.set(t,e),void 0!==e.texCoord&&t.setTexCoord(e.texCoord);const r=this.jsonDoc.json.textures[e.index];if(void 0===r.sampler)return;const s=this.jsonDoc.json.samplers[r.sampler];void 0!==s.magFilter&&t.setMagFilter(s.magFilter),void 0!==s.minFilter&&t.setMinFilter(s.minFilter),void 0!==s.wrapS&&t.setWrapS(s.wrapS),void 0!==s.wrapT&&t.setWrapT(s.wrapT)}}const yt={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},Tt={logger:C.DEFAULT_INSTANCE,extensions:[],dependencies:{}};function vt(t,e){const r=e.bufferViews[t.bufferView],s=e.jsonDoc.json.bufferViews[t.bufferView],n=yt[t.componentType],i=W.getElementSize(t.type),o=n.BYTES_PER_ELEMENT;if(void 0!==s.byteStride&&s.byteStride!==i*o)return function(t,e){const r=e.bufferViews[t.bufferView],s=e.jsonDoc.json.bufferViews[t.bufferView],n=yt[t.componentType],i=W.getElementSize(t.type),o=n.BYTES_PER_ELEMENT,a=t.byteOffset||0,u=new n(t.count*i),c=new DataView(r.buffer,r.byteOffset,r.byteLength),h=s.byteStride;for(let e=0;e<t.count;e++)for(let r=0;r<i;r++){const s=a+e*h+r*o;let n;switch(t.componentType){case W.ComponentType.FLOAT:n=c.getFloat32(s,!0);break;case W.ComponentType.UNSIGNED_INT:n=c.getUint32(s,!0);break;case W.ComponentType.UNSIGNED_SHORT:n=c.getUint16(s,!0);break;case W.ComponentType.UNSIGNED_BYTE:n=c.getUint8(s);break;case W.ComponentType.SHORT:n=c.getInt16(s,!0);break;case W.ComponentType.BYTE:n=c.getInt8(s);break;default:throw new Error(`Unexpected componentType "${t.componentType}".`)}u[e*i+r]=n}return u}(t,e);const a=r.byteOffset+(t.byteOffset||0);return new n(r.buffer.slice(a,a+t.count*i*o))}var xt;!function(t){t[t.ARRAY_BUFFER=34962]="ARRAY_BUFFER",t[t.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER"}(xt||(xt={}));class bt{constructor(t,e,r){this.N=void 0,this.jsonDoc=void 0,this.options=void 0,this.accessorIndexMap=new Map,this.animationIndexMap=new Map,this.bufferIndexMap=new Map,this.cameraIndexMap=new Map,this.skinIndexMap=new Map,this.materialIndexMap=new Map,this.meshIndexMap=new Map,this.nodeIndexMap=new Map,this.imageIndexMap=new Map,this.textureDefIndexMap=new Map,this.textureInfoDefMap=new Map,this.samplerDefIndexMap=new Map,this.sceneIndexMap=new Map,this.imageBufferViews=[],this.otherBufferViews=new Map,this.otherBufferViewsIndexMap=new Map,this.extensionData={},this.bufferURIGenerator=void 0,this.imageURIGenerator=void 0,this.logger=void 0,this.O=new Map,this.accessorUsageGroupedByParent=new Set(["ARRAY_BUFFER"]),this.accessorParents=new Map,this.N=t,this.jsonDoc=e,this.options=r;const s=t.getRoot(),n=s.listBuffers().length,i=s.listTextures().length;this.bufferURIGenerator=new At(n>1,r.basename),this.imageURIGenerator=new At(i>1,r.basename),this.logger=t.getLogger()}createTextureInfoDef(t,e){const r={magFilter:e.getMagFilter()||void 0,minFilter:e.getMinFilter()||void 0,wrapS:e.getWrapS(),wrapT:e.getWrapT()},s=JSON.stringify(r);this.samplerDefIndexMap.has(s)||(this.samplerDefIndexMap.set(s,this.jsonDoc.json.samplers.length),this.jsonDoc.json.samplers.push(r));const n={source:this.imageIndexMap.get(t),sampler:this.samplerDefIndexMap.get(s)},i=JSON.stringify(n);this.textureDefIndexMap.has(i)||(this.textureDefIndexMap.set(i,this.jsonDoc.json.textures.length),this.jsonDoc.json.textures.push(n));const o={index:this.textureDefIndexMap.get(i)};return 0!==e.getTexCoord()&&(o.texCoord=e.getTexCoord()),this.textureInfoDefMap.set(e,o),o}createPropertyDef(t){const e={};return t.getName()&&(e.name=t.getName()),Object.keys(t.getExtras()).length>0&&(e.extras=t.getExtras()),e}createAccessorDef(t){const e=this.createPropertyDef(t);return e.type=t.getType(),e.componentType=t.getComponentType(),e.count=t.getCount(),this.N.getGraph().listParentEdges(t).some(t=>"attributes"===t.getName()&&"POSITION"===t.getAttributes().key||"input"===t.getName())&&(e.max=t.getMax([]).map(Math.fround),e.min=t.getMin([]).map(Math.fround)),t.getNormalized()&&(e.normalized=t.getNormalized()),e}createImageData(t,e,r){if(this.options.format===T.GLB)this.imageBufferViews.push(e),t.bufferView=this.jsonDoc.json.bufferViews.length,this.jsonDoc.json.bufferViews.push({buffer:0,byteOffset:-1,byteLength:e.byteLength});else{const s=M.mimeTypeToExtension(r.getMimeType());t.uri=this.imageURIGenerator.createURI(r,s),this.jsonDoc.resources[t.uri]=e}}getAccessorUsage(t){const e=this.O.get(t);if(e)return e;for(const e of this.N.getGraph().listParentEdges(t)){const{usage:t}=e.getAttributes();if(t)return t;e.getParent().propertyType!==p.ROOT&&this.N.getLogger().warn(`Missing attribute ".usage" on edge, "${e.getName()}".`)}return bt.BufferViewUsage.OTHER}addAccessorToUsageGroup(t,e){const r=this.O.get(t);if(r&&r!==e)throw new Error(`Accessor with usage "${r}" cannot be reused as "${e}".`);return this.O.set(t,e),this}listAccessorUsageGroups(){const t={};for(const[e,r]of Array.from(this.O.entries()))t[r]=t[r]||[],t[r].push(e);return t}}bt.BufferViewTarget=xt,bt.BufferViewUsage=w,bt.USAGE_TO_TARGET={[w.ARRAY_BUFFER]:xt.ARRAY_BUFFER,[w.ELEMENT_ARRAY_BUFFER]:xt.ELEMENT_ARRAY_BUFFER};class At{constructor(t,e){this.multiple=void 0,this.basename=void 0,this.counter=1,this.multiple=t,this.basename=e}createURI(t,e){return t.getURI()?t.getURI():this.multiple?`${this.basename}_${this.counter++}.${e}`:`${this.basename}.${e}`}}const{BufferViewUsage:Et}=bt;var St;!function(t){t[t.JSON=1313821514]="JSON",t[t.BIN=5130562]="BIN"}(St||(St={}));class Mt{constructor(){this.v=C.DEFAULT_INSTANCE,this.h=new Set,this.C={},this.F=m.INTERLEAVED,this.lastReadBytes=0,this.lastWriteBytes=0}setLogger(t){return this.v=t,this}registerExtensions(t){for(const e of t)this.h.add(e),e.register();return this}registerDependencies(t){return Object.assign(this.C,t),this}setVertexLayout(t){return this.F=t,this}async read(t){return await this.readJSON(await this.readAsJSON(t))}async readAsJSON(t){return t.match(/^data:application\/octet-stream;/)||this.detectFormat(t)===T.GLB?this.U(t):this.P(t)}async readJSON(t){return t=this.j(t),this.L(t),class{static read(t,e=Tt){const r=ht({},Tt,e),{json:s}=t,n=new pt;this.validate(t,r);const i=new wt(t),o=s.asset,a=n.getRoot().getAsset();o.copyright&&(a.copyright=o.copyright),o.extras&&(a.extras=o.extras),void 0!==s.extras&&n.getRoot().setExtras(ht({},s.extras));const u=s.extensionsUsed||[],c=s.extensionsRequired||[];for(const t of r.extensions)if(u.includes(t.EXTENSION_NAME)){const e=n.createExtension(t).setRequired(c.includes(t.EXTENSION_NAME));for(const t of e.readDependencies)e.install(t,r.dependencies[t])}const h=s.buffers||[];n.getRoot().listExtensionsUsed().filter(t=>t.prereadTypes.includes(p.BUFFER)).forEach(t=>t.preread(i,p.BUFFER)),i.buffers=h.map(t=>{const e=n.createBuffer(t.name);return t.extras&&e.setExtras(t.extras),t.uri&&0!==t.uri.indexOf("__")&&e.setURI(t.uri),e}),i.bufferViewBuffers=(s.bufferViews||[]).map((e,r)=>{if(!i.bufferViews[r]){const s=t.json.buffers[e.buffer];i.bufferViews[r]=A.toView(s.uri?t.resources[s.uri]:t.resources["@glb.bin"],e.byteOffset||0,e.byteLength)}return i.buffers[e.buffer]}),i.accessors=(s.accessors||[]).map(t=>{const e=n.createAccessor(t.name,i.bufferViewBuffers[t.bufferView]).setType(t.type);if(t.extras&&e.setExtras(t.extras),void 0!==t.normalized&&e.setNormalized(t.normalized),void 0===t.bufferView&&!t.sparse)return e;let r;return r=void 0!==t.sparse?function(t,e){const r=yt[t.componentType],s=W.getElementSize(t.type);let n;n=void 0!==t.bufferView?vt(t,e):new r(t.count*s);const i=t.sparse,o=i.count,a=ht({},t,i.indices,{count:o,type:"SCALAR"}),u=ht({},t,i.values,{count:o}),c=vt(a,e),h=vt(u,e);for(let t=0;t<a.count;t++)for(let e=0;e<s;e++)n[c[t]*s+e]=h[t*s+e];return n}(t,i):vt(t,i),e.setArray(r),e});const l=s.images||[],f=s.textures||[];n.getRoot().listExtensionsUsed().filter(t=>t.prereadTypes.includes(p.TEXTURE)).forEach(t=>t.preread(i,p.TEXTURE)),i.textures=l.map(e=>{const r=n.createTexture(e.name);if(e.extras&&r.setExtras(e.extras),void 0!==e.bufferView){const n=s.bufferViews[e.bufferView],i=t.json.buffers[n.buffer],o=n.byteOffset||0,a=(i.uri?t.resources[i.uri]:t.resources["@glb.bin"]).slice(o,o+n.byteLength);r.setImage(a)}else void 0!==e.uri&&(r.setImage(t.resources[e.uri]),0!==e.uri.indexOf("__")&&r.setURI(e.uri));if(void 0!==e.mimeType)r.setMimeType(e.mimeType);else if(e.uri){const t=R.extension(e.uri);r.setMimeType(M.extensionToMimeType(t))}return r}),i.materials=(s.materials||[]).map(t=>{const e=n.createMaterial(t.name);t.extras&&e.setExtras(t.extras),void 0!==t.alphaMode&&e.setAlphaMode(t.alphaMode),void 0!==t.alphaCutoff&&e.setAlphaCutoff(t.alphaCutoff),void 0!==t.doubleSided&&e.setDoubleSided(t.doubleSided);const r=t.pbrMetallicRoughness||{};if(void 0!==r.baseColorFactor&&e.setBaseColorFactor(r.baseColorFactor),void 0!==t.emissiveFactor&&e.setEmissiveFactor(t.emissiveFactor),void 0!==r.metallicFactor&&e.setMetallicFactor(r.metallicFactor),void 0!==r.roughnessFactor&&e.setRoughnessFactor(r.roughnessFactor),void 0!==r.baseColorTexture){const t=r.baseColorTexture;e.setBaseColorTexture(i.textures[f[t.index].source]),i.setTextureInfo(e.getBaseColorTextureInfo(),t)}if(void 0!==t.emissiveTexture){const r=t.emissiveTexture;e.setEmissiveTexture(i.textures[f[r.index].source]),i.setTextureInfo(e.getEmissiveTextureInfo(),r)}if(void 0!==t.normalTexture){const r=t.normalTexture;e.setNormalTexture(i.textures[f[r.index].source]),i.setTextureInfo(e.getNormalTextureInfo(),r),void 0!==t.normalTexture.scale&&e.setNormalScale(t.normalTexture.scale)}if(void 0!==t.occlusionTexture){const r=t.occlusionTexture;e.setOcclusionTexture(i.textures[f[r.index].source]),i.setTextureInfo(e.getOcclusionTextureInfo(),r),void 0!==t.occlusionTexture.strength&&e.setOcclusionStrength(t.occlusionTexture.strength)}if(void 0!==r.metallicRoughnessTexture){const t=r.metallicRoughnessTexture;e.setMetallicRoughnessTexture(i.textures[f[t.index].source]),i.setTextureInfo(e.getMetallicRoughnessTextureInfo(),t)}return e});const d=s.meshes||[];n.getRoot().listExtensionsUsed().filter(t=>t.prereadTypes.includes(p.PRIMITIVE)).forEach(t=>t.preread(i,p.PRIMITIVE)),i.meshes=d.map(t=>{const e=n.createMesh(t.name);return t.extras&&e.setExtras(t.extras),void 0!==t.weights&&e.setWeights(t.weights),(t.primitives||[]).forEach(r=>{const s=n.createPrimitive();r.extras&&s.setExtras(r.extras),void 0!==r.material&&s.setMaterial(i.materials[r.material]),void 0!==r.mode&&s.setMode(r.mode);for(const[t,e]of Object.entries(r.attributes||{}))s.setAttribute(t,i.accessors[e]);void 0!==r.indices&&s.setIndices(i.accessors[r.indices]);const o=t.extras&&t.extras.targetNames||[];(r.targets||[]).forEach((t,e)=>{const r=o[e]||e.toString(),a=n.createPrimitiveTarget(r);for(const[e,r]of Object.entries(t))a.setAttribute(e,i.accessors[r]);s.addTarget(a)}),e.addPrimitive(s)}),e}),i.cameras=(s.cameras||[]).map(t=>{const e=n.createCamera(t.name).setType(t.type);if(t.extras&&e.setExtras(t.extras),t.type===Q.Type.PERSPECTIVE){const r=t.perspective;e.setYFov(r.yfov),e.setZNear(r.znear),void 0!==r.zfar&&e.setZFar(r.zfar),void 0!==r.aspectRatio&&e.setAspectRatio(r.aspectRatio)}else{const r=t.orthographic;e.setZNear(r.znear).setZFar(r.zfar).setXMag(r.xmag).setYMag(r.ymag)}return e});const g=s.nodes||[];n.getRoot().listExtensionsUsed().filter(t=>t.prereadTypes.includes(p.NODE)).forEach(t=>t.preread(i,p.NODE)),i.nodes=g.map(t=>{const e=n.createNode(t.name);if(t.extras&&e.setExtras(t.extras),void 0!==t.translation&&e.setTranslation(t.translation),void 0!==t.rotation&&e.setRotation(t.rotation),void 0!==t.scale&&e.setScale(t.scale),void 0!==t.matrix){const r=[0,0,0],s=[0,0,0,1],n=[1,1,1];F.decompose(t.matrix,r,s,n),e.setTranslation(r),e.setRotation(s),e.setScale(n)}return void 0!==t.weights&&e.setWeights(t.weights),e}),i.skins=(s.skins||[]).map(t=>{const e=n.createSkin(t.name);t.extras&&e.setExtras(t.extras),void 0!==t.inverseBindMatrices&&e.setInverseBindMatrices(i.accessors[t.inverseBindMatrices]),void 0!==t.skeleton&&e.setSkeleton(i.nodes[t.skeleton]);for(const r of t.joints)e.addJoint(i.nodes[r]);return e}),g.map((t,e)=>{const r=i.nodes[e];(t.children||[]).forEach(t=>r.addChild(i.nodes[t])),void 0!==t.mesh&&r.setMesh(i.meshes[t.mesh]),void 0!==t.camera&&r.setCamera(i.cameras[t.camera]),void 0!==t.skin&&r.setSkin(i.skins[t.skin])}),i.animations=(s.animations||[]).map(t=>{const e=n.createAnimation(t.name);t.extras&&e.setExtras(t.extras);const r=(t.samplers||[]).map(t=>{const r=n.createAnimationSampler().setInput(i.accessors[t.input]).setOutput(i.accessors[t.output]).setInterpolation(t.interpolation||Z.Interpolation.LINEAR);return t.extras&&r.setExtras(t.extras),e.addSampler(r),r});return(t.channels||[]).forEach(t=>{const s=n.createAnimationChannel().setSampler(r[t.sampler]).setTargetNode(i.nodes[t.target.node]).setTargetPath(t.target.path);t.extras&&s.setExtras(t.extras),e.addChannel(s)}),e});const m=s.scenes||[];return n.getRoot().listExtensionsUsed().filter(t=>t.prereadTypes.includes(p.SCENE)).forEach(t=>t.preread(i,p.SCENE)),i.scenes=m.map(t=>{const e=n.createScene(t.name);return t.extras&&e.setExtras(t.extras),(t.nodes||[]).map(t=>i.nodes[t]).forEach(t=>e.addChild(t)),e}),void 0!==s.scene&&n.getRoot().setDefaultScene(i.scenes[s.scene]),n.getRoot().listExtensionsUsed().forEach(t=>t.read(i)),n}static validate(t,e){const r=t.json;if("2.0"!==r.asset.version)throw new Error(`Unsupported glTF version, "${r.asset.version}".`);if(r.extensionsRequired)for(const t of r.extensionsRequired)if(!e.extensions.find(e=>e.EXTENSION_NAME===t))throw new Error(`Missing required extension, "${t}".`);if(r.extensionsUsed)for(const t of r.extensionsUsed)e.extensions.find(e=>e.EXTENSION_NAME===t)||e.logger.warn(`Missing optional extension, "${t}".`)}}.read(t,{extensions:Array.from(this.h),dependencies:this.C,logger:this.v})}async binaryToJSON(t){const e=this._(A.assertView(t));this.L(e);const r=e.json;if(r.buffers&&r.buffers.some(t=>function(t,e){return void 0!==e.uri&&!(e.uri in t.resources)}(e,t)))throw new Error("Cannot resolve external buffers with binaryToJSON().");if(r.images&&r.images.some(t=>function(t,e){return void 0!==e.uri&&!(e.uri in t.resources)&&void 0===e.bufferView}(e,t)))throw new Error("Cannot resolve external images with binaryToJSON().");return e}async readBinary(t){return this.readJSON(await this.binaryToJSON(A.assertView(t)))}async writeJSON(t,e={}){if(e.format===T.GLB&&t.getRoot().listBuffers().length>1)throw new Error("GLB must have 0–1 buffers.");return class{static write(t,e){const r=t.getRoot(),s={asset:ht({generator:"glTF-Transform v2.1.0"},r.getAsset()),extras:ht({},r.getExtras())},n={json:s,resources:{}},i=new bt(t,n,e),o=e.logger||C.DEFAULT_INSTANCE,a=new Set(e.extensions.map(t=>t.EXTENSION_NAME)),u=t.getRoot().listExtensionsUsed().filter(t=>a.has(t.extensionName)),c=t.getRoot().listExtensionsRequired().filter(t=>a.has(t.extensionName));u.length<t.getRoot().listExtensionsUsed().length&&o.debug("Some extensions were not registered for I/O, and will not be written.");for(const t of u)for(const r of t.writeDependencies)t.install(r,e.dependencies[r]);function h(t,e,r,n){const o=[];let a=0;for(const e of t){const t=i.createAccessorDef(e);t.bufferView=s.bufferViews.length;const r=e.getArray(),n=A.pad(A.toView(r));t.byteOffset=a,a+=n.byteLength,o.push(n),i.accessorIndexMap.set(e,s.accessors.length),s.accessors.push(t)}const u={buffer:e,byteOffset:r,byteLength:A.concat(o).byteLength};return n&&(u.target=n),s.bufferViews.push(u),{buffers:o,byteLength:a}}function l(t,e,r){const n=t[0].getCount();let o=0;for(const e of t){const t=i.createAccessorDef(e);t.bufferView=s.bufferViews.length,t.byteOffset=o;const r=e.getElementSize(),n=e.getComponentSize();o+=A.padNumber(r*n),i.accessorIndexMap.set(e,s.accessors.length),s.accessors.push(t)}const a=n*o,u=new ArrayBuffer(a),c=new DataView(u);for(let e=0;e<n;e++){let r=0;for(const s of t){const t=s.getElementSize(),n=s.getComponentSize(),i=s.getComponentType(),a=s.getArray();for(let s=0;s<t;s++){const u=e*o+r+s*n,h=a[e*t+s];switch(i){case W.ComponentType.FLOAT:c.setFloat32(u,h,!0);break;case W.ComponentType.BYTE:c.setInt8(u,h);break;case W.ComponentType.SHORT:c.setInt16(u,h,!0);break;case W.ComponentType.UNSIGNED_BYTE:c.setUint8(u,h);break;case W.ComponentType.UNSIGNED_SHORT:c.setUint16(u,h,!0);break;case W.ComponentType.UNSIGNED_INT:c.setUint32(u,h,!0);break;default:throw new Error("Unexpected component type: "+i)}}r+=A.padNumber(t*n)}}return s.bufferViews.push({buffer:e,byteOffset:r,byteLength:a,byteStride:o,target:bt.BufferViewTarget.ARRAY_BUFFER}),{byteLength:a,buffers:[new Uint8Array(u)]}}const f=new Map;for(const e of t.getGraph().listEdges()){if(e.getParent()===r)continue;const t=e.getChild();if(t instanceof W){const r=f.get(t)||[];r.push(e),f.set(t,r)}}if(s.accessors=[],s.bufferViews=[],s.samplers=[],s.textures=[],s.images=r.listTextures().map((t,e)=>{const r=i.createPropertyDef(t);t.getMimeType()&&(r.mimeType=t.getMimeType());const s=t.getImage();return s&&i.createImageData(r,s,t),i.imageIndexMap.set(t,e),r}),u.filter(t=>t.prewriteTypes.includes(p.ACCESSOR)).forEach(t=>t.prewrite(i,p.ACCESSOR)),r.listAccessors().forEach(t=>{const e=i.accessorUsageGroupedByParent,r=i.accessorParents;if(i.accessorIndexMap.has(t))return;const s=f.get(t)||[],n=i.getAccessorUsage(t);if(i.addAccessorToUsageGroup(t,n),e.has(n)){const e=s[0].getParent(),n=r.get(e)||new Set;n.add(t),r.set(e,n)}}),u.filter(t=>t.prewriteTypes.includes(p.BUFFER)).forEach(t=>t.prewrite(i,p.BUFFER)),(r.listAccessors().length>0||r.listTextures().length>0||i.otherBufferViews.size>0)&&0===r.listBuffers().length)throw new Error("Buffer required for Document resources, but none was found.");s.buffers=[],r.listBuffers().forEach((t,r)=>{const o=i.createPropertyDef(t),a=i.accessorUsageGroupedByParent,u=i.accessorParents,c=t.listParents().filter(t=>t instanceof W),f=new Set(c),d=[],g=s.buffers.length;let p=0;const w=i.listAccessorUsageGroups();for(const t in w)if(a.has(t))for(const r of Array.from(u.values())){const s=Array.from(r).filter(t=>f.has(t)).filter(e=>i.getAccessorUsage(e)===t);if(s.length)if(t!==Et.ARRAY_BUFFER||e.vertexLayout===m.INTERLEAVED){const e=t===Et.ARRAY_BUFFER?l(s,g,p):h(s,g,p);p+=e.byteLength,d.push(...e.buffers)}else for(const t of s){const e=l([t],g,p);p+=e.byteLength,d.push(...e.buffers)}}else{const e=w[t].filter(t=>f.has(t));if(!e.length)continue;const r=h(e,g,p,t===Et.ELEMENT_ARRAY_BUFFER?bt.BufferViewTarget.ELEMENT_ARRAY_BUFFER:void 0);p+=r.byteLength,d.push(...r.buffers)}if(i.imageBufferViews.length&&0===r)for(let t=0;t<i.imageBufferViews.length;t++)if(s.bufferViews[s.images[t].bufferView].byteOffset=p,p+=i.imageBufferViews[t].byteLength,d.push(i.imageBufferViews[t]),p%8){const t=8-p%8;p+=t,d.push(new Uint8Array(t))}if(i.otherBufferViews.has(t))for(const e of i.otherBufferViews.get(t))s.bufferViews.push({buffer:g,byteOffset:p,byteLength:e.byteLength}),i.otherBufferViewsIndexMap.set(e,s.bufferViews.length-1),p+=e.byteLength,d.push(e);if(p){let r;e.format===T.GLB?r="@glb.bin":(r=i.bufferURIGenerator.createURI(t,"bin"),o.uri=r),o.byteLength=p,n.resources[r]=A.concat(d)}s.buffers.push(o),i.bufferIndexMap.set(t,r)}),r.listAccessors().find(t=>!t.getBuffer())&&o.warn("Skipped writing one or more Accessors: no Buffer assigned."),s.materials=r.listMaterials().map((t,e)=>{const r=i.createPropertyDef(t);if(t.getAlphaMode()!==it.AlphaMode.OPAQUE&&(r.alphaMode=t.getAlphaMode()),t.getAlphaMode()===it.AlphaMode.MASK&&(r.alphaCutoff=t.getAlphaCutoff()),t.getDoubleSided()&&(r.doubleSided=!0),r.pbrMetallicRoughness={},F.eq(t.getBaseColorFactor(),[1,1,1,1])||(r.pbrMetallicRoughness.baseColorFactor=t.getBaseColorFactor()),F.eq(t.getEmissiveFactor(),[0,0,0])||(r.emissiveFactor=t.getEmissiveFactor()),1!==t.getRoughnessFactor()&&(r.pbrMetallicRoughness.roughnessFactor=t.getRoughnessFactor()),1!==t.getMetallicFactor()&&(r.pbrMetallicRoughness.metallicFactor=t.getMetallicFactor()),t.getBaseColorTexture()){const e=t.getBaseColorTexture(),s=t.getBaseColorTextureInfo();r.pbrMetallicRoughness.baseColorTexture=i.createTextureInfoDef(e,s)}if(t.getEmissiveTexture()){const e=t.getEmissiveTexture(),s=t.getEmissiveTextureInfo();r.emissiveTexture=i.createTextureInfoDef(e,s)}if(t.getNormalTexture()){const e=t.getNormalTexture(),s=t.getNormalTextureInfo(),n=i.createTextureInfoDef(e,s);1!==t.getNormalScale()&&(n.scale=t.getNormalScale()),r.normalTexture=n}if(t.getOcclusionTexture()){const e=t.getOcclusionTexture(),s=t.getOcclusionTextureInfo(),n=i.createTextureInfoDef(e,s);1!==t.getOcclusionStrength()&&(n.strength=t.getOcclusionStrength()),r.occlusionTexture=n}if(t.getMetallicRoughnessTexture()){const e=t.getMetallicRoughnessTexture(),s=t.getMetallicRoughnessTextureInfo();r.pbrMetallicRoughness.metallicRoughnessTexture=i.createTextureInfoDef(e,s)}return i.materialIndexMap.set(t,e),r}),s.meshes=r.listMeshes().map((t,e)=>{const r=i.createPropertyDef(t);let s=null;return r.primitives=t.listPrimitives().map(t=>{const e={attributes:{}};e.mode=t.getMode();const r=t.getMaterial();r&&(e.material=i.materialIndexMap.get(r)),Object.keys(t.getExtras()).length&&(e.extras=t.getExtras());const n=t.getIndices();n&&(e.indices=i.accessorIndexMap.get(n));for(const r of t.listSemantics())e.attributes[r]=i.accessorIndexMap.get(t.getAttribute(r));for(const r of t.listTargets()){const t={};for(const e of r.listSemantics())t[e]=i.accessorIndexMap.get(r.getAttribute(e));e.targets=e.targets||[],e.targets.push(t)}return t.listTargets().length&&!s&&(s=t.listTargets().map(t=>t.getName())),e}),t.getWeights().length&&(r.weights=t.getWeights()),s&&(r.extras=r.extras||{},r.extras.targetNames=s),i.meshIndexMap.set(t,e),r}),s.cameras=r.listCameras().map((t,e)=>{const r=i.createPropertyDef(t);if(r.type=t.getType(),r.type===Q.Type.PERSPECTIVE){r.perspective={znear:t.getZNear(),zfar:t.getZFar(),yfov:t.getYFov()};const e=t.getAspectRatio();null!==e&&(r.perspective.aspectRatio=e)}else r.orthographic={znear:t.getZNear(),zfar:t.getZFar(),xmag:t.getXMag(),ymag:t.getYMag()};return i.cameraIndexMap.set(t,e),r}),s.nodes=r.listNodes().map((t,e)=>{const r=i.createPropertyDef(t);return F.eq(t.getTranslation(),[0,0,0])||(r.translation=t.getTranslation()),F.eq(t.getRotation(),[0,0,0,1])||(r.rotation=t.getRotation()),F.eq(t.getScale(),[1,1,1])||(r.scale=t.getScale()),t.getWeights().length&&(r.weights=t.getWeights()),i.nodeIndexMap.set(t,e),r}),s.skins=r.listSkins().map((t,e)=>{const r=i.createPropertyDef(t),s=t.getInverseBindMatrices();s&&(r.inverseBindMatrices=i.accessorIndexMap.get(s));const n=t.getSkeleton();return n&&(r.skeleton=i.nodeIndexMap.get(n)),r.joints=t.listJoints().map(t=>i.nodeIndexMap.get(t)),i.skinIndexMap.set(t,e),r}),r.listNodes().forEach((t,e)=>{const r=s.nodes[e],n=t.getMesh();n&&(r.mesh=i.meshIndexMap.get(n));const o=t.getCamera();o&&(r.camera=i.cameraIndexMap.get(o));const a=t.getSkin();a&&(r.skin=i.skinIndexMap.get(a)),t.listChildren().length>0&&(r.children=t.listChildren().map(t=>i.nodeIndexMap.get(t)))}),s.animations=r.listAnimations().map((t,e)=>{const r=i.createPropertyDef(t),s=new Map;return r.samplers=t.listSamplers().map((t,e)=>{const r=i.createPropertyDef(t);return r.input=i.accessorIndexMap.get(t.getInput()),r.output=i.accessorIndexMap.get(t.getOutput()),r.interpolation=t.getInterpolation(),s.set(t,e),r}),r.channels=t.listChannels().map(t=>{const e=i.createPropertyDef(t);return e.sampler=s.get(t.getSampler()),e.target={node:i.nodeIndexMap.get(t.getTargetNode()),path:t.getTargetPath()},e}),i.animationIndexMap.set(t,e),r}),s.scenes=r.listScenes().map((t,e)=>{const r=i.createPropertyDef(t);return r.nodes=t.listChildren().map(t=>i.nodeIndexMap.get(t)),i.sceneIndexMap.set(t,e),r});const d=r.getDefaultScene();return d&&(s.scene=r.listScenes().indexOf(d)),s.extensionsUsed=u.map(t=>t.extensionName),s.extensionsRequired=c.map(t=>t.extensionName),u.forEach(t=>t.write(i)),function(t){const e=[];for(const r in t){const s=t[r];(Array.isArray(s)&&0===s.length||null===s||""===s||s&&"object"==typeof s&&0===Object.keys(s).length)&&e.push(r)}for(const r of e)delete t[r]}(s),n}}.write(t,{format:e.format||T.GLTF,basename:e.basename||"",logger:this.v,vertexLayout:this.F,dependencies:ht({},this.C),extensions:Array.from(this.h)})}async writeBinary(t){const{json:e,resources:r}=await this.writeJSON(t,{format:T.GLB}),s=new Uint32Array([1179937895,2,12]),n=JSON.stringify(e),i=A.pad(A.encodeText(n),32),o=A.toView(new Uint32Array([i.byteLength,1313821514])),a=A.concat([o,i]);s[s.length-1]+=a.byteLength;const u=Object.values(r)[0];if(!u||!u.byteLength)return A.concat([A.toView(s),a]);const c=A.pad(u,0),h=A.toView(new Uint32Array([c.byteLength,5130562])),l=A.concat([h,c]);return s[s.length-1]+=l.byteLength,A.concat([A.toView(s),a,l])}detectFormat(t){return"glb"===(J.isAbsoluteURL(t)?J.extension(t):R.extension(t))?T.GLB:T.GLTF}async P(t){this.lastReadBytes=0;const e=await this.readURI(t,"text");this.lastReadBytes+=e.length;const r={json:JSON.parse(e),resources:{}};return await this.D(r,this.dirname(t)),this.L(r),r}async U(t){const e=await this.readURI(t,"view");this.lastReadBytes=e.byteLength;const r=this._(e);return await this.D(r,this.dirname(t)),this.L(r),r}async D(t,e){var r=this;const s=[...t.json.images||[],...t.json.buffers||[]].map(async function(s){const n=s.uri;if(!n||n.match(/data:/))return Promise.resolve();t.resources[n]=await r.readURI(r.resolve(e,n),"view"),r.lastReadBytes+=t.resources[n].byteLength});await Promise.all(s)}L(t){function e(e){if(e.uri)if(e.uri in t.resources)A.assertView(t.resources[e.uri]);else if(e.uri.match(/data:/)){const r=`__${G()}.${R.extension(e.uri)}`;t.resources[r]=A.createBufferFromDataURI(e.uri),e.uri=r}}(t.json.images||[]).forEach(t=>{if(void 0===t.bufferView&&void 0===t.uri)throw new Error("Missing resource URI or buffer view.");e(t)}),(t.json.buffers||[]).forEach(e)}j(t){const{images:e,buffers:r}=t.json;return t={json:ht({},t.json),resources:ht({},t.resources)},e&&(t.json.images=e.map(t=>ht({},t))),r&&(t.json.buffers=r.map(t=>ht({},t))),t}_(t){const e=new Uint32Array(t.buffer,t.byteOffset,3);if(1179937895!==e[0])throw new Error("Invalid glTF asset.");if(2!==e[1])throw new Error(`Unsupported glTF binary version, "${e[1]}".`);const r=new Uint32Array(t.buffer,t.byteOffset+12,2);if(r[1]!==St.JSON)throw new Error("Missing required GLB JSON chunk.");const s=r[0],n=A.decodeText(A.toView(t,20,s)),i=JSON.parse(n),o=20+s;if(t.byteLength<=o)return{json:i,resources:{}};const a=new Uint32Array(t.buffer,t.byteOffset+o,2);if(a[1]!==St.BIN)throw new Error("Expected GLB BIN in second chunk.");return{json:i,resources:{"@glb.bin":A.toView(t,o+8,a[0])}}}}class It extends Mt{constructor(t=null,e=J.DEFAULT_INIT){super(),this.k=void 0,this.J=void 0,this.$=void 0,this.V=void 0,this.q=!1,this.k=require("fs").promises,this.J=require("path"),this.$=t,this.V=e}setAllowHTTP(t){if(t&&!this.$)throw new Error("NodeIO requires a Fetch API implementation for HTTP requests.");return this.q=t,this}async readURI(t,e){if(J.isAbsoluteURL(t)){if(!this.q||!this.$)throw new Error("Network request blocked. Allow HTTP requests explicitly, if needed.");const r=await this.$(t,this.V);switch(e){case"view":return new Uint8Array(await r.arrayBuffer());case"text":return r.text()}}else switch(e){case"view":return this.k.readFile(t);case"text":return this.k.readFile(t,"utf8")}}resolve(t,e){return J.isAbsoluteURL(t)||J.isAbsoluteURL(e)?J.resolve(t,e):this.J.resolve(t,e)}dirname(t){return J.isAbsoluteURL(t)?J.dirname(t):this.J.dirname(t)}async write(t,e){const r=!!t.match(/\.glb$/);await(r?this.W(t,e):this.H(t,e))}async H(t,e){var r=this;this.lastWriteBytes=0;const{json:s,resources:n}=await this.writeJSON(e,{format:T.GLTF,basename:R.basename(t)}),{k:i,J:o}=this,a=o.dirname(t),u=JSON.stringify(s,null,2);this.lastWriteBytes+=u.length,await i.writeFile(t,u);const c=Object.keys(n).map(async function(t){if(J.isAbsoluteURL(t)){if("bin"===J.extension(t))throw new Error(`Cannot write buffer to path "${t}".`);return}const e=Buffer.from(n[t]);await i.writeFile(o.join(a,t),e),r.lastWriteBytes+=e.byteLength});await Promise.all(c)}async W(t,e){const r=Buffer.from(await this.writeBinary(e));await this.k.writeFile(t,r),this.lastWriteBytes=r.byteLength}}class Rt extends Mt{constructor(t){super(),this.J=void 0,this.J=t}async readURI(t,e){switch(e){case"view":return Deno.readFile(t);case"text":return Deno.readTextFile(t)}}resolve(t,e){return this.J.resolve(t,e)}dirname(t){return this.J.dirname(t)}}class Nt extends Mt{constructor(t=J.DEFAULT_INIT){super(),this.V=void 0,this.V=t}async readURI(t,e){const r=await fetch(t,this.V);switch(e){case"view":return new Uint8Array(await r.arrayBuffer());case"text":return r.text()}}resolve(t,e){return J.resolve(t,e)}dirname(t){return J.dirname(t)}detectFormat(t){return"glb"===J.extension(t)?T.GLB:T.GLTF}}export{W as Accessor,H as Animation,Y as AnimationChannel,Z as AnimationSampler,K as Buffer,A as BufferUtils,$ as COPY_IDENTITY,Q as Camera,E as ColorUtils,Rt as DenoIO,pt as Document,q as ExtensibleProperty,mt as Extension,X as ExtensionProperty,R as FileUtils,T as Format,g as GLB_BUFFER,M as ImageUtils,C as Logger,it as Material,F as MathUtils,ot as Mesh,at as Node,It as NodeIO,Mt as PlatformIO,ut as Primitive,ct as PrimitiveTarget,V as Property,p as PropertyType,wt as ReaderContext,gt as Root,lt as Scene,ft as Skin,dt as Texture,y as TextureChannel,tt as TextureInfo,d as VERSION,m as VertexLayout,Nt as WebIO,bt as WriterContext,v as bounds,G as uuid}; | ||
//# sourceMappingURL=core.modern.js.map |
@@ -1,2 +0,2 @@ | ||
import { VertexLayout } from '../constants'; | ||
import { Format, VertexLayout } from '../constants'; | ||
import { Document } from '../document'; | ||
@@ -74,2 +74,4 @@ import { Extension } from '../extension'; | ||
*/ | ||
/** @hidden */ | ||
protected detectFormat(uri: string): Format; | ||
private _readGLTF; | ||
@@ -76,0 +78,0 @@ private _readGLB; |
import { PlatformIO } from './platform-io'; | ||
import { Format } from '../constants'; | ||
/** | ||
@@ -40,2 +41,4 @@ * # WebIO | ||
protected dirname(uri: string): string; | ||
/** @hidden */ | ||
protected detectFormat(uri: string): Format; | ||
} |
@@ -9,6 +9,12 @@ /** | ||
export declare class FileUtils { | ||
/** Extracts the basename from a path, e.g. "folder/model.glb" -> "model". */ | ||
static basename(path: string): string; | ||
/** Extracts the extension from a path, e.g. "folder/model.glb" -> "glb". */ | ||
static extension(path: string): string; | ||
/** | ||
* Extracts the basename from a file path, e.g. "folder/model.glb" -> "model". | ||
* See: {@link HTTPUtils.basename} | ||
*/ | ||
static basename(uri: string): string; | ||
/** | ||
* Extracts the extension from a file path, e.g. "folder/model.glb" -> "glb". | ||
* See: {@link HTTPUtils.extension} | ||
*/ | ||
static extension(uri: string): string; | ||
} |
@@ -1,1 +0,33 @@ | ||
export {}; | ||
/** | ||
* # HTTPUtils | ||
* | ||
* *Utility class for working with URLs.* | ||
* | ||
* @category Utilities | ||
*/ | ||
export declare class HTTPUtils { | ||
static readonly DEFAULT_INIT: RequestInit; | ||
static readonly PROTOCOL_REGEXP: RegExp; | ||
static dirname(path: string): string; | ||
/** | ||
* Extracts the basename from a URL, e.g. "folder/model.glb" -> "model". | ||
* See: {@link FileUtils.basename} | ||
*/ | ||
static basename(uri: string): string; | ||
/** | ||
* Extracts the extension from a URL, e.g. "folder/model.glb" -> "glb". | ||
* See: {@link FileUtils.extension} | ||
*/ | ||
static extension(uri: string): string; | ||
static resolve(base: string, path: string): string; | ||
/** | ||
* Returns true for URLs containing a protocol, and false for both | ||
* absolute and relative paths. | ||
*/ | ||
static isAbsoluteURL(path: string): boolean; | ||
/** | ||
* Returns true for paths that are declared relative to some unknown base | ||
* path. For example, "foo/bar/" is relative both "/foo/bar/" is not. | ||
*/ | ||
static isRelativePath(path: string): boolean; | ||
} |
{ | ||
"name": "@gltf-transform/core", | ||
"version": "2.0.5", | ||
"version": "2.1.0", | ||
"repository": "github:donmccurdy/glTF-Transform", | ||
@@ -49,3 +49,3 @@ "homepage": "https://gltf-transform.donmccurdy.com/", | ||
}, | ||
"gitHead": "9431e3aeec7d1bac01c31090b2c20fe5227a8146" | ||
"gitHead": "5cc8d10b5de17633b6a63a4fa5e10e0e60c71e84" | ||
} |
@@ -148,3 +148,3 @@ import { Format } from '../constants'; | ||
if (HTTPUtils.isAbsoluteURL(resourceURI)) { | ||
if (FileUtils.extension(resourceURI) === 'bin') { | ||
if (HTTPUtils.extension(resourceURI) === 'bin') { | ||
throw new Error(`Cannot write buffer to path "${resourceURI}".`); | ||
@@ -151,0 +151,0 @@ } |
@@ -6,3 +6,3 @@ import { Format, GLB_BUFFER, VertexLayout } from '../constants'; | ||
import { GLTF } from '../types/gltf'; | ||
import { BufferUtils, FileUtils, Logger, uuid } from '../utils/'; | ||
import { BufferUtils, FileUtils, HTTPUtils, Logger, uuid } from '../utils/'; | ||
import { GLTFReader } from './reader'; | ||
@@ -95,3 +95,3 @@ import { GLTFWriter, WriterOptions } from './writer'; | ||
public async readAsJSON(uri: string): Promise<JSONDocument> { | ||
const isGLB = uri.match(/^data:application\/octet-stream;/) || FileUtils.extension(uri) === 'glb'; | ||
const isGLB = uri.match(/^data:application\/octet-stream;/) || this.detectFormat(uri) === Format.GLB; | ||
return isGLB ? this._readGLB(uri) : this._readGLTF(uri); | ||
@@ -180,2 +180,9 @@ } | ||
/** @hidden */ | ||
protected detectFormat(uri: string): Format { | ||
// Overriden by WebIO, which only uses HTTPUtils. | ||
const extension = HTTPUtils.isAbsoluteURL(uri) ? HTTPUtils.extension(uri) : FileUtils.extension(uri); | ||
return extension === 'glb' ? Format.GLB : Format.GLTF; | ||
} | ||
private async _readGLTF(uri: string): Promise<JSONDocument> { | ||
@@ -182,0 +189,0 @@ this.lastReadBytes = 0; |
import { PlatformIO } from './platform-io'; | ||
import { HTTPUtils } from '../utils'; | ||
import { Format } from '../constants'; | ||
@@ -62,2 +63,7 @@ /** | ||
} | ||
/** @hidden */ | ||
protected detectFormat(uri: string): Format { | ||
return HTTPUtils.extension(uri) === 'glb' ? Format.GLB : Format.GLTF; | ||
} | ||
} |
@@ -1,4 +0,2 @@ | ||
// Need a placeholder domain to construct a URL from a relative path. We only | ||
// access `url.pathname`, so the domain doesn't matter. | ||
const NULL_DOMAIN = 'https://null.example'; | ||
import { ImageUtils } from './image-utils'; | ||
@@ -13,22 +11,28 @@ /** | ||
export class FileUtils { | ||
/** Extracts the basename from a path, e.g. "folder/model.glb" -> "model". */ | ||
static basename(path: string): string { | ||
path = new URL(path, NULL_DOMAIN).pathname; | ||
const fileName = path.split(/[\\/]/).pop()!; | ||
/** | ||
* Extracts the basename from a file path, e.g. "folder/model.glb" -> "model". | ||
* See: {@link HTTPUtils.basename} | ||
*/ | ||
static basename(uri: string): string { | ||
const fileName = uri.split(/[\\/]/).pop()!; | ||
return fileName.substring(0, fileName.lastIndexOf('.')); | ||
} | ||
/** Extracts the extension from a path, e.g. "folder/model.glb" -> "glb". */ | ||
static extension(path: string): string { | ||
if (path.indexOf('data:') !== 0) { | ||
path = new URL(path, NULL_DOMAIN).pathname; | ||
return path.split(/[\\/]/).pop()!.split(/[.]/).pop()!; | ||
} else if (path.indexOf('data:image/png') === 0) { | ||
return 'png'; | ||
} else if (path.indexOf('data:image/jpeg') === 0) { | ||
return 'jpeg'; | ||
} else { | ||
/** | ||
* Extracts the extension from a file path, e.g. "folder/model.glb" -> "glb". | ||
* See: {@link HTTPUtils.extension} | ||
*/ | ||
static extension(uri: string): string { | ||
if (uri.startsWith('data:image/')) { | ||
const mimeType = uri.match(/data:(image\/\w+)/)![1]; | ||
return ImageUtils.mimeTypeToExtension(mimeType); | ||
} else if (uri.startsWith('data:model/gltf+json')) { | ||
return 'gltf'; | ||
} else if (uri.startsWith('data:model/gltf-binary')) { | ||
return 'glb'; | ||
} else if (uri.startsWith('data:application/')) { | ||
return 'bin'; | ||
} | ||
return uri.split(/[\\/]/).pop()!.split(/[.]/).pop()!; | ||
} | ||
} |
@@ -1,2 +0,14 @@ | ||
/** @internal */ | ||
import { FileUtils } from './file-utils'; | ||
// Need a placeholder domain to construct a URL from a relative path. We only | ||
// access `url.pathname`, so the domain doesn't matter. | ||
const NULL_DOMAIN = 'https://null.example'; | ||
/** | ||
* # HTTPUtils | ||
* | ||
* *Utility class for working with URLs.* | ||
* | ||
* @category Utilities | ||
*/ | ||
export class HTTPUtils { | ||
@@ -12,2 +24,18 @@ static readonly DEFAULT_INIT: RequestInit = {}; | ||
/** | ||
* Extracts the basename from a URL, e.g. "folder/model.glb" -> "model". | ||
* See: {@link FileUtils.basename} | ||
*/ | ||
static basename(uri: string): string { | ||
return FileUtils.basename(new URL(uri, NULL_DOMAIN).pathname); | ||
} | ||
/** | ||
* Extracts the extension from a URL, e.g. "folder/model.glb" -> "glb". | ||
* See: {@link FileUtils.extension} | ||
*/ | ||
static extension(uri: string): string { | ||
return FileUtils.extension(new URL(uri, NULL_DOMAIN).pathname); | ||
} | ||
static resolve(base: string, path: string) { | ||
@@ -14,0 +42,0 @@ if (!this.isRelativePath(path)) return path; |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
1211361
11314