@margoengine/gltf 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/LICENSE +201 -201
  2. package/NOTICE +4 -4
  3. package/README.md +1754 -1438
  4. package/dist/accessor-CU_1uSZ1.js +1 -0
  5. package/dist/asset-DN3ocEdY.js +4 -0
  6. package/dist/asset-entry.js +1 -1
  7. package/dist/asset.d.ts +76 -0
  8. package/dist/audio.js +1 -1
  9. package/dist/auto.js +1 -1
  10. package/dist/compression-CUOCmjmE.js +1 -0
  11. package/dist/compression.d.ts +6 -0
  12. package/dist/dds.js +1 -1
  13. package/dist/default-materials.d.ts +3 -1
  14. package/dist/default-transmission.d.ts +13 -0
  15. package/dist/extended.js +1 -1
  16. package/dist/group.d.ts +15 -3
  17. package/dist/index.d.ts +11 -0
  18. package/dist/index.js +1 -1
  19. package/dist/{instanced-shader-BebTnbkj.js → instanced-shader-C9ZMazvo.js} +1 -1
  20. package/dist/instancing.js +1 -1
  21. package/dist/lights.js +1 -1
  22. package/dist/material-draw-state-GKiHDb0p.js +1 -0
  23. package/dist/material-draw.js +1 -1
  24. package/dist/meshopt.js +1 -1
  25. package/dist/mipmaps-38NmjDc3.js +21 -0
  26. package/dist/model-C77ATxi1.js +25 -0
  27. package/dist/model-entry.js +1 -1
  28. package/dist/model.d.ts +84 -7
  29. package/dist/native-glass-D85twud0.js +19 -0
  30. package/dist/pack-DdxRO8k6.js +1 -0
  31. package/dist/pbr-instancing.js +1 -1
  32. package/dist/pbr.js +1 -1
  33. package/dist/physics.js +1 -1
  34. package/dist/prepare.js +1 -1
  35. package/dist/progressive-lod.d.ts +13 -0
  36. package/dist/progressive.d.ts +5 -2
  37. package/dist/progressive.js +3 -3
  38. package/dist/quantized.js +1 -1
  39. package/dist/report.js +1 -1
  40. package/dist/scene-data.js +1 -1
  41. package/dist/scene-scope-CZDEkd24.js +2 -2
  42. package/dist/scene.js +3 -3
  43. package/dist/{shader-DPqfUcmp.js → shader-C29RtPAw.js} +43 -39
  44. package/dist/shader.d.ts +24 -0
  45. package/dist/shared/caster.d.ts +159 -152
  46. package/dist/shared/gltf.d.ts +257 -257
  47. package/dist/shared/iridescence.d.ts +2 -2
  48. package/dist/shared/prepared-geometry.d.ts +8 -8
  49. package/dist/soft-mesh.d.ts +39 -1
  50. package/dist/soft-mesh.js +2 -2
  51. package/dist/spec-gloss.js +2 -2
  52. package/dist/splats.js +1 -1
  53. package/dist/src-Btvz5f6i.js +4 -0
  54. package/dist/stream-CrfNNCRd.js +1 -0
  55. package/dist/stream.d.ts +20 -3
  56. package/dist/stroke-width-B2cnYGgn.js +1 -0
  57. package/dist/stroke-width.d.ts +18 -0
  58. package/dist/strokes.d.ts +12 -0
  59. package/dist/strokes.js +1 -0
  60. package/dist/texture-stream-Cu_XpyVO.js +3 -3
  61. package/dist/textured.js +3 -3
  62. package/dist/transmission.d.ts +81 -0
  63. package/dist/transmission.js +66 -0
  64. package/dist/version-B6NE5cJf.js +1 -0
  65. package/dist/vertex-inputs.d.ts +6 -0
  66. package/dist/{unit-light-DvtsuFYP.js → warning-UqjZyyqW.js} +2 -22
  67. package/dist/warning.d.ts +24 -0
  68. package/dist/worker.d.ts +1 -1
  69. package/dist/worker.js +3 -3
  70. package/dist/workers/gltf.js +36 -36
  71. package/dist/workers/progressive.js +1 -1
  72. package/package.json +234 -213
  73. package/dist/accessor-nVsu_f1L.js +0 -1
  74. package/dist/asset-1b8ejkZX.js +0 -4
  75. package/dist/compression-D4IkO5vE.js +0 -1
  76. package/dist/errors-THVaUwlL.js +0 -1
  77. package/dist/material-draw-state-BHeTb1FP.js +0 -1
  78. package/dist/model-iRvuj19h.js +0 -39
  79. package/dist/optimize-7SEzNA23.js +0 -1
  80. package/dist/pack-BVDYuqZe.js +0 -1
  81. package/dist/src-WMRHArDp.js +0 -4
  82. package/dist/stream-C3bKMy1B.js +0 -1
  83. package/dist/version-BmU1nesQ.js +0 -1
@@ -0,0 +1 @@
1
+ import{N as e,h as t,j as n,w as r}from"./asset-DN3ocEdY.js";import{margoError as i}from"@margoengine/core/extension";function a(e){if(!e||typeof e!=`object`)return!1;for(let[t,n]of Object.entries(e))if(t===`texCoord`?n>1:a(n))return!0;return!1}function o(e,t){let n=t.extensions?.KHR_materials_variants,r=[t.material,...(n?.mappings??[]).map(e=>e?.material)],i=/* @__PURE__ */ new Set;for(let t=0;t<r.length;t++){let n=r[t];if(n===void 0||i.has(n))continue;i.add(n);let o=e.materials?.[n];if(a(o))return!0;let s=(o?.extensions)?.MSFT_lod?.ids;if(Array.isArray(s))for(let t of s)Number.isInteger(t)&&t>=0&&t<(e.materials?.length??0)&&r.push(t)}return!1}var s=/* @__PURE__ */ new WeakMap;function c(e,t,n){r(e,t);try{return u(e,t,n)}catch(n){let r=e.doc.meshes??[],i=r.findIndex(e=>e?.primitives?.includes?.(t));throw n instanceof Error&&i>=0&&(n.message=`glTF mesh ${i}${r[i].name?` "${r[i].name}"`:``} primitive ${r[i].primitives.indexOf(t)}: ${n.message}`),n}}function l(e,t){let n=e.length;if(t===2||t===3){let r=n<2?0:t===2?n:n-1,i=new Uint32Array(r*2);for(let t=0;t<r;t++)i[t*2]=e[t],i[t*2+1]=e[(t+1)%n];return i}if(t===5||t===6){let r=new Uint32Array(Math.max(n-2,0)*3);for(let i=0,a=0;i<n-2;i++,a+=3)t===5?(r[a]=e[i],r[a+1]=e[i+1+i%2],r[a+2]=e[i+2-i%2]):(r[a]=e[i+1],r[a+1]=e[i+2],r[a+2]=e[0]);return r}return e}function u(a,s,c){let u=s.mode??4,d=u===0?1:u<4?2:3;if(!Number.isInteger(u)||u<0||u>6)throw TypeError(`Invalid glTF primitive mode; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let f=s.attributes??{},p=(e,t,n)=>{try{return a.accessor(t,n)}catch(n){throw n instanceof Error&&(n.message=`${e} (accessor ${t}): ${n.message}`),n}};if(t(a.doc.accessors,f.POSITION,`POSITION`).count>16777216)throw i(`unsupported`,`glTF primitive has more than ${n} vertices, the most one primitive may hold; split the mesh into several primitives`);let m=p(`POSITION`,f.POSITION,`VEC3`),h=m.length/3,g=a.doc.extensionsUsed?.includes(`KHR_mesh_quantization`),_=a.partVertices;if(h<d)throw RangeError(`Expected bounded triangle geometry`);for(let e of[`POSITION`,`NORMAL`,`TANGENT`])if(f[e]!==void 0&&!g){let n=t(a.doc.accessors,f[e],`attribute`);if(n.componentType!==5126||n.normalized)throw TypeError(`Expected Float32 `+e)}for(let e of[`TEXCOORD_0`,`TEXCOORD_1`,`TEXCOORD_2`,`TEXCOORD_3`,`COLOR_0`])if(f[e]!==void 0&&!(g&&e!==`COLOR_0`)){let n=t(a.doc.accessors,f[e],`attribute`);if(![5126,5121,5123].includes(n.componentType)||n.componentType!==5126&&!n.normalized)throw TypeError(`Invalid normalized `+e+`; re-export the file and check it with the glTF Validator`)}let v=f.NORMAL===void 0?new Float32Array(m.length):p(`NORMAL`,f.NORMAL,`VEC3`),y=r(a,s)??(s.indices===void 0?null:p(`indices`,s.indices,`SCALAR`));if(y)for(let e=0;e<y.length;e++){let t=y[e];if(!Number.isInteger(t)||t<0||t>=h)throw RangeError(`Invalid glTF triangle indices; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`)}let b=y?new Uint32Array(y):new Uint32Array(h);if(!y)for(let e=0;e<h;e++)b[e]=e;if(b=l(b,u),!b.length||b.length%d)throw RangeError(`Invalid glTF triangle indices; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);if(s.indices!==void 0&&(![5121,5123,5125].includes(t(a.doc.accessors,s.indices,`indices`).componentType)||a.doc.accessors[s.indices].normalized))throw TypeError(`Invalid index component type; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);if(f.NORMAL===void 0&&d===3)for(let e=0;e<b.length;e+=3){let t=b[e]*3,n=b[e+1]*3,r=b[e+2]*3,i=m[n]-m[t],a=m[n+1]-m[t+1],o=m[n+2]-m[t+2],s=m[r]-m[t],c=m[r+1]-m[t+1],l=m[r+2]-m[t+2],u=a*l-o*c,d=o*s-i*l,f=i*c-a*s;v[t]+=u,v[t+1]+=d,v[t+2]+=f,v[n]+=u,v[n+1]+=d,v[n+2]+=f,v[r]+=u,v[r+1]+=d,v[r+2]+=f}let x=a.doc.materials?.[s.material]?.alphaMode===`BLEND`,S=h>_?e(b,d,h,_,x?null:m):null;if(a.reorder&&d===3&&!x){if(!S)b=a.reorder(b,m,h);else for(let e of S){let t=e.vertexMap.length,n=new Float32Array(t*3);for(let r=0;r<t;r++){let t=e.vertexMap[r]*3;n[r*3]=m[t],n[r*3+1]=m[t+1],n[r*3+2]=m[t+2]}e.indices=a.reorder(e.indices,n,t)}}let C=f.TEXCOORD_0===void 0?null:p(`TEXCOORD_0`,f.TEXCOORD_0,`VEC2`),w=f.TEXCOORD_1===void 0?null:p(`TEXCOORD_1`,f.TEXCOORD_1,`VEC2`),T=o(a.doc,s),E=!T||f.TEXCOORD_2===void 0?null:p(`TEXCOORD_2`,f.TEXCOORD_2,`VEC2`),D=!T||f.TEXCOORD_3===void 0?null:p(`TEXCOORD_3`,f.TEXCOORD_3,`VEC2`),O=f.TANGENT===void 0?null:p(`TANGENT`,f.TANGENT,`VEC4`),k=f.COLOR_0===void 0?null:p(`COLOR_0`,f.COLOR_0),A=k?k.length/h:0;if(v.length!==h*3||C&&C.length!==h*2||w&&w.length!==h*2||E&&E.length!==h*2||D&&D.length!==h*2||O&&O.length!==h*4||k&&![3,4].includes(A))throw RangeError(`Mismatched glTF attributes; the file holds invalid numbers, re-export it and check it with the glTF Validator`);let j=(e,t,n)=>{let r=t*3,i=v[r],a=v[r+1],o=v[r+2],s=Math.hypot(i,a,o);if(e[n]=m[r],e[n+1]=m[r+1],e[n+2]=m[r+2],e[n+3]=1,!s||!Number.isFinite(s)){if(f.NORMAL!==void 0)throw RangeError(`Zero or non-finite glTF normal; the file holds invalid numbers, re-export it and check it with the glTF Validator`);e[n+6]=1}else e[n+4]=i/s,e[n+5]=a/s,e[n+6]=o/s;if(O){let r=t*4,i=Math.hypot(O[r],O[r+1],O[r+2]);i&&(e[n+8]=O[r]/i,e[n+9]=O[r+1]/i,e[n+10]=O[r+2]/i,e[n+11]=Math.sign(O[r+3]))}if(C&&(e[n+12]=C[t*2],e[n+13]=C[t*2+1]),w&&(e[n+14]=w[t*2],e[n+15]=w[t*2+1]),k){let r=t*A;e[n+16]=k[r],e[n+17]=k[r+1],e[n+18]=k[r+2],e[n+19]=A===3?1:k[r+3]}else e[n+16]=1,e[n+17]=1,e[n+18]=1,e[n+19]=1},M=(e,t,n)=>{E&&e.set(E.subarray(t*2,t*2+2),n),D&&e.set(D.subarray(t*2,t*2+2),n+2)},N=d<3?{topology:d===1?`point-list`:`line-list`}:{};if(!S){let e=new Float32Array(h*20),t=E||D?new Float32Array(h*4):void 0;for(let t=0;t<h;t++)j(e,t,t*20);if(t)for(let e=0;e<h;e++)M(t,e,e*4);let n={vertices:e,indices:b,...N,...t?{uvs:t}:{}};return c?(c(n),[]):[n]}let P=[];for(let e=0;e<S.length;e++){let{indices:t,vertexMap:n}=S[e],r=n.length,i=new Float32Array(r*20),a=E||D?new Float32Array(r*4):void 0;for(let e=0;e<r;e++)j(i,n[e],e*20);if(a)for(let e=0;e<r;e++)M(a,n[e],e*4);let o={vertices:i,indices:t,...N,...a?{uvs:a}:{},part:{index:e,count:S.length,vertexMap:n}};c?c(o):P.push(o)}return P}function d(e,n,r){let i=n.attributes??{},a=t(e.doc.accessors,i.POSITION,`POSITION`).count,o=i.TEXCOORD_2===void 0?null:e.accessor(i.TEXCOORD_2,`VEC2`),s=i.TEXCOORD_3===void 0?null:e.accessor(i.TEXCOORD_3,`VEC2`);if(!o&&!s)return;if(o&&o.length!==a*2||s&&s.length!==a*2)throw RangeError(`Mismatched glTF attributes; the file holds invalid numbers, re-export it and check it with the glTF Validator`);let c=new Float32Array(r.length*4);for(let e=0;e<r.length;e++){let t=r[e];o&&c.set(o.subarray(t*2,t*2+2),e*4),s&&c.set(s.subarray(t*2,t*2+2),e*4+2)}return c}function f(e){let t=e.doc,n=[];for(let e of t.skins??[])n.push(e?.inverseBindMatrices);for(let e of t.meshes??[])for(let t of e?.primitives??[]){n.push(t?.attributes?.JOINTS_0,t?.attributes?.WEIGHTS_0);for(let e of t?.targets??[])n.push(e?.POSITION,e?.NORMAL)}for(let e of t.animations??[])for(let t of e?.samplers??[])n.push(t?.input,t?.output);for(let e of t.nodes??[])n.push(...Object.values(e?.extensions?.EXT_mesh_gpu_instancing?.attributes??{}));let r=[];for(let t of n)if(t!==void 0)try{r.push([t,e.accessor(t)])}catch{}return r}var p=e=>(e.meshes??[]).flatMap(e=>Array.isArray(e?.primitives)?e.primitives:[]);export{p as a,s as i,d as n,o,c as r,f as t};
@@ -1 +1 @@
1
- import{a as e,i as t,t as n}from"./instanced-shader-BebTnbkj.js";import{composeMatrix as r}from"@margoengine/math/mat4";var i=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,1,1,1,1,1,1,0,0],a=class r{constructor(e){if(this.low=0,this.stale=!0,this.revision=0,this.flipCount=0,this.capacity=e,!Number.isInteger(e)||e<1||e>1e6)throw RangeError(`Invalid instance capacity; pass a whole number from 0 up to the capacity`);this.data=new Float32Array(e*24);for(let t=0;t<e;t++)this.data.set(i,t*24);this.drawn=this.high=e}get count(){return this.source?.count??this.drawn}set count(e){if(this.source)this.source.count=e;else{if(!Number.isInteger(e)||e<0||e>this.capacity)throw RangeError(`Invalid instance count; pass a whole number from 0 up to the capacity`);this.drawn=e,this.stale=!0}}get version(){return this.source?this.source.revision:this.revision}get needsUpdate(){return this.source?!this.gpu||this.revision!==this.source.revision:this.high>this.low}set needsUpdate(e){this.source?this.source.needsUpdate=e:e&&(this.low=0,this.high=this.capacity,this.stale=!0,this.revision++)}index(e){if(!Number.isInteger(e)||e<0||e>=this.capacity)throw RangeError(`Instance index out of range; use an index below the instance count`);return e*24}row(e,t,n,r,i=-1/0){if(this.source)return this.source.row(e,t,n,r,i),this;let a=this.index(e)+t,o=0;for(let e=0;e<r;e++)o+=Math.fround(n[e]);if(!Number.isFinite(o))throw RangeError(`Invalid instance value: pass finite float32 numbers`);if(i>-1/0||!ArrayBuffer.isView(n)){for(let e=0;e<r;e++)if(typeof n[e]!=`number`||n[e]<i)throw RangeError(`Invalid instance value: pass finite float32 numbers (tints 0 or more)`)}for(let e=0;e<r;e++)this.data[a+e]=n[e];if(e<this.low&&(this.low=e),e>=this.high&&(this.high=e+1),t===0&&!this.stale){let t=+(this.determinant(a)<0),n=this.flips;e<this.drawn&&(this.flipCount+=t-n[e]),n[e]=t}return this.revision++,this}determinant(e){let t=this.data;return t[e]*(t[e+5]*t[e+10]-t[e+6]*t[e+9])-t[e+4]*(t[e+1]*t[e+10]-t[e+2]*t[e+9])+t[e+8]*(t[e+1]*t[e+6]-t[e+2]*t[e+5])}setMatrixAt(e,t){if(t?.length!==16||t[3]||t[7]||t[11]||t[15]!==1)throw TypeError(`Invalid instance matrix; pass 16 finite numbers, column-major`);return this.row(e,0,t,16)}setMatrices(e,t){if(this.source)return this.source.setMatrices(e,t),this;let n=t?.length;if(!Number.isInteger(n)||n%16)throw TypeError(`Instance matrices: pass 16 numbers per instance`);let r=n/16;if(!Number.isInteger(e)||e<0||e+r>this.capacity)throw RangeError(`Instance index out of range; write rows from 0 to capacity - 1`);if(!r)return this;let i=0;for(let e=0;e<n;e++)i+=Math.fround(t[e]);if(!Number.isFinite(i))throw RangeError(`Invalid instance value: pass finite float32 numbers`);let a=!ArrayBuffer.isView(t);for(let e=0;e<r;e++){let n=e*16;if(t[n+3]||t[n+7]||t[n+11]||t[n+15]!==1)throw TypeError(`Invalid instance matrix: pass column-major affine matrices (last row 0, 0, 0, 1)`);if(a){for(let e=0;e<16;e++)if(typeof t[n+e]!=`number`)throw TypeError(`Invalid instance matrix: pass column-major affine matrices (last row 0, 0, 0, 1)`)}}let o=this.data,s=this.stale?void 0:this.flips;for(let n=0;n<r;n++){let r=e+n,i=r*24,a=n*16;for(let e=0;e<16;e++)o[i+e]=t[a+e];if(s){let e=+(this.determinant(i)<0);r<this.drawn&&(this.flipCount+=e-s[r]),s[r]=e}}return e<this.low&&(this.low=e),e+r>this.high&&(this.high=e+r),this.revision++,this}getMatrixAt(e,t=/* @__PURE__ */ new Float32Array(16)){let n=this.index(e);for(let e=0;e<16;e++)t[e]=this.data[n+e];return t}setColorAt(e,t){if(t?.length!==3&&t?.length!==4)throw TypeError(`Invalid instance color; pass finite RGB or RGBA numbers`);return this.row(e,16,t.length===3?[t[0],t[1],t[2],1]:t,4,0)}setUVTransformAt(e,t){let n=t?.offset??[0,0],r=t?.scale??[1,1];if(t?.rotation||n.length!==2||r.length!==2)throw TypeError(`Invalid instance UV transform; pass finite offset and scale numbers`);return this.row(e,20,[r[0],r[1],n[0],n[1]],4)}get mirrored(){return this.source?this.source.mirrored:(this.scan(),this.flipCount>0)}upload(e){return this.source&&this.revision!==this.source.revision&&(this.low=0,this.high=this.capacity),(this.device!==e||!this.gpu)&&(this.gpu?.destroy(),this.gpu=e.createBuffer({size:this.data.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE}),this.device=e,this.low=0,this.high=this.capacity),this.high>this.low&&(e.queue.writeBuffer(this.gpu,this.low*96,this.data,this.low*24,(this.high-this.low)*24),this.low=this.capacity,this.high=0,this.source&&(this.revision=this.source.revision)),this.source||this.scan(),this.gpu}createProjection(){let e=this.source??this;return Object.assign(Object.create(r.prototype),{data:e.data,capacity:e.capacity,source:e,revision:-1,low:0,high:e.capacity})}scan(){if(!this.stale)return;let e=this.flips??=new Uint8Array(this.capacity);this.stale=!1,this.flipCount=0;for(let t=0;t<this.capacity;t++)e[t]=+(this.determinant(t*24)<0),t<this.drawn&&(this.flipCount+=e[t])}dispose(){this.gpu?.destroy(),this.gpu=this.device=void 0}[Symbol.dispose??Symbol()](){this.dispose()}get layout(){return t}shader(e){return n(e)}bounds(t,n,r){let i=[1/0,1/0,1/0,-1/0,-1/0,-1/0],a=/* @__PURE__ */ new Float32Array(16);for(let e=0;e<n.length;e+=20)for(let t=0;t<3;t++)i[t]=Math.min(i[t],n[e+t]),i[t+3]=Math.max(i[t+3],n[e+t]);for(let n=0;n<this.count;n++){e(t,this.data,n,a);for(let e=0;e<8;e++)for(let t=0;t<3;t++){let n=a[t]*i[e&1?3:0]+a[4+t]*i[e&2?4:1]+a[8+t]*i[e&4?5:2]+a[12+t];r[t]=Math.min(r[t],n),r[t+3]=Math.max(r[t+3],n)}}}},o={read(e,t){let n=t?.attributes??{},i=(t,r)=>n[t]===void 0?null:e.accessor(n[t],r),o=i(`TRANSLATION`,`VEC3`),s=i(`ROTATION`,`VEC4`),c=i(`SCALE`,`VEC3`),l=o?o.length/3:s?s.length/4:c?c.length/3:0;if(!l||o&&o.length!==l*3||s&&s.length!==l*4||c&&c.length!==l*3)throw TypeError(`Invalid EXT_mesh_gpu_instancing attributes; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);e.reserveDecodedBytes(l*96);let u=new a(l),d=[0,0,0,1];for(let e=0;e<l;e++){if(s){let t=Math.hypot(s[e*4],s[e*4+1],s[e*4+2],s[e*4+3]);if(!t)throw RangeError(`Zero instance rotation; use a unit quaternion, not [0, 0, 0, 0]`);for(let n=0;n<4;n++)d[n]=s[e*4+n]/t}r(o?.subarray(e*3)??[0,0,0],d,c?.subarray(e*3)??[1,1,1],u.data.subarray(e*24,e*24+16))}return u}};export{a as PBRInstances,n as instancedShader,o as instancing};
1
+ import{a as e,i as t,t as n}from"./instanced-shader-C9ZMazvo.js";import{composeMatrix as r}from"@margoengine/math/mat4";var i=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,1,1,1,1,1,1,0,0],a=class r{constructor(e){if(this.low=0,this.stale=!0,this.revision=0,this.flipCount=0,this.capacity=e,!Number.isInteger(e)||e<1||e>1e6)throw RangeError(`Invalid instance capacity; pass a whole number from 0 up to the capacity`);this.data=new Float32Array(e*24);for(let t=0;t<e;t++)this.data.set(i,t*24);this.drawn=this.high=e}get count(){return this.source?.count??this.drawn}set count(e){if(this.source)this.source.count=e;else{if(!Number.isInteger(e)||e<0||e>this.capacity)throw RangeError(`Invalid instance count; pass a whole number from 0 up to the capacity`);this.drawn=e,this.stale=!0}}get version(){return this.source?this.source.revision:this.revision}get needsUpdate(){return this.source?!this.gpu||this.revision!==this.source.revision:this.high>this.low}set needsUpdate(e){this.source?this.source.needsUpdate=e:e&&(this.low=0,this.high=this.capacity,this.stale=!0,this.revision++)}index(e){if(!Number.isInteger(e)||e<0||e>=this.capacity)throw RangeError(`Instance index out of range; use an index below the instance count`);return e*24}row(e,t,n,r,i=-1/0){if(this.source)return this.source.row(e,t,n,r,i),this;let a=this.index(e)+t,o=0;for(let e=0;e<r;e++)o+=Math.fround(n[e]);if(!Number.isFinite(o))throw RangeError(`Invalid instance value: pass finite float32 numbers`);if(i>-1/0||!ArrayBuffer.isView(n)){for(let e=0;e<r;e++)if(typeof n[e]!=`number`||n[e]<i)throw RangeError(`Invalid instance value: pass finite float32 numbers (tints 0 or more)`)}for(let e=0;e<r;e++)this.data[a+e]=n[e];if(e<this.low&&(this.low=e),e>=this.high&&(this.high=e+1),t===0&&!this.stale){let t=+(this.determinant(a)<0),n=this.flips;e<this.drawn&&(this.flipCount+=t-n[e]),n[e]=t}return this.revision++,this}determinant(e){let t=this.data;return t[e]*(t[e+5]*t[e+10]-t[e+6]*t[e+9])-t[e+4]*(t[e+1]*t[e+10]-t[e+2]*t[e+9])+t[e+8]*(t[e+1]*t[e+6]-t[e+2]*t[e+5])}setMatrixAt(e,t){if(t?.length!==16||t[3]||t[7]||t[11]||t[15]!==1)throw TypeError(`Invalid instance matrix; pass 16 finite numbers, column-major`);return this.row(e,0,t,16)}setMatrices(e,t){if(this.source)return this.source.setMatrices(e,t),this;let n=t?.length;if(!Number.isInteger(n)||n%16)throw TypeError(`Instance matrices: pass 16 numbers per instance`);let r=n/16;if(!Number.isInteger(e)||e<0||e+r>this.capacity)throw RangeError(`Instance index out of range; write rows from 0 to capacity - 1`);if(!r)return this;let i=0;for(let e=0;e<n;e++)i+=Math.fround(t[e]);if(!Number.isFinite(i))throw RangeError(`Invalid instance value: pass finite float32 numbers`);let a=!ArrayBuffer.isView(t);for(let e=0;e<r;e++){let n=e*16;if(t[n+3]||t[n+7]||t[n+11]||t[n+15]!==1)throw TypeError(`Invalid instance matrix: pass column-major affine matrices (last row 0, 0, 0, 1)`);if(a){for(let e=0;e<16;e++)if(typeof t[n+e]!=`number`)throw TypeError(`Invalid instance matrix: pass column-major affine matrices (last row 0, 0, 0, 1)`)}}let o=this.data,s=this.stale?void 0:this.flips;for(let n=0;n<r;n++){let r=e+n,i=r*24,a=n*16;for(let e=0;e<16;e++)o[i+e]=t[a+e];if(s){let e=+(this.determinant(i)<0);r<this.drawn&&(this.flipCount+=e-s[r]),s[r]=e}}return e<this.low&&(this.low=e),e+r>this.high&&(this.high=e+r),this.revision++,this}getMatrixAt(e,t=/* @__PURE__ */ new Float32Array(16)){let n=this.index(e);for(let e=0;e<16;e++)t[e]=this.data[n+e];return t}setColorAt(e,t){if(t?.length!==3&&t?.length!==4)throw TypeError(`Invalid instance color; pass finite RGB or RGBA numbers`);return this.row(e,16,t.length===3?[t[0],t[1],t[2],1]:t,4,0)}setUVTransformAt(e,t){let n=t?.offset??[0,0],r=t?.scale??[1,1];if(t?.rotation||n.length!==2||r.length!==2)throw TypeError(`Invalid instance UV transform; pass finite offset and scale numbers`);return this.row(e,20,[r[0],r[1],n[0],n[1]],4)}get mirrored(){return this.source?this.source.mirrored:(this.scan(),this.flipCount>0)}upload(e){return this.source&&this.revision!==this.source.revision&&(this.low=0,this.high=this.capacity),(this.device!==e||!this.gpu)&&(this.gpu?.destroy(),this.gpu=e.createBuffer({size:this.data.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this.device=e,this.low=0,this.high=this.capacity),this.high>this.low&&(e.queue.writeBuffer(this.gpu,this.low*96,this.data,this.low*24,(this.high-this.low)*24),this.low=this.capacity,this.high=0,this.source&&(this.revision=this.source.revision)),this.source||this.scan(),this.gpu}createProjection(){let e=this.source??this;return Object.assign(Object.create(r.prototype),{data:e.data,capacity:e.capacity,source:e,revision:-1,low:0,high:e.capacity})}scan(){if(!this.stale)return;let e=this.flips??=new Uint8Array(this.capacity);this.stale=!1,this.flipCount=0;for(let t=0;t<this.capacity;t++)e[t]=+(this.determinant(t*24)<0),t<this.drawn&&(this.flipCount+=e[t])}dispose(){this.gpu?.destroy(),this.gpu=this.device=void 0}[Symbol.dispose??Symbol()](){this.dispose()}get layout(){return t}shader(e){return n(e)}bounds(t,n,r){let i=[1/0,1/0,1/0,-1/0,-1/0,-1/0],a=/* @__PURE__ */ new Float32Array(16);for(let e=0;e<n.length;e+=20)for(let t=0;t<3;t++)i[t]=Math.min(i[t],n[e+t]),i[t+3]=Math.max(i[t+3],n[e+t]);for(let n=0;n<this.count;n++){e(t,this.data,n,a);for(let e=0;e<8;e++)for(let t=0;t<3;t++){let n=a[t]*i[e&1?3:0]+a[4+t]*i[e&2?4:1]+a[8+t]*i[e&4?5:2]+a[12+t];r[t]=Math.min(r[t],n),r[t+3]=Math.max(r[t+3],n)}}}},o={read(e,t){let n=t?.attributes??{},i=(t,r)=>n[t]===void 0?null:e.accessor(n[t],r),o=i(`TRANSLATION`,`VEC3`),s=i(`ROTATION`,`VEC4`),c=i(`SCALE`,`VEC3`),l=o?o.length/3:s?s.length/4:c?c.length/3:0;if(!l||o&&o.length!==l*3||s&&s.length!==l*4||c&&c.length!==l*3)throw TypeError(`Invalid EXT_mesh_gpu_instancing attributes; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);e.reserveDecodedBytes(l*96);let u=new a(l),d=[0,0,0,1];for(let e=0;e<l;e++){if(s){let t=Math.hypot(s[e*4],s[e*4+1],s[e*4+2],s[e*4+3]);if(!t)throw RangeError(`Zero instance rotation; use a unit quaternion, not [0, 0, 0, 0]`);for(let n=0;n<4;n++)d[n]=s[e*4+n]/t}r(o?.subarray(e*3)??[0,0,0],d,c?.subarray(e*3)??[1,1,1],u.data.subarray(e*24,e*24+16))}return u}};export{a as PBRInstances,n as instancedShader,o as instancing};
package/dist/pbr.js CHANGED
@@ -1 +1 @@
1
- import{t as e}from"./decoder-default-CxLH8Vz0.js";import{a as t,c as n,i as r,l as i,n as a,o,r as s,s as c,t as l,u}from"./model-iRvuj19h.js";import{o as d,t as f}from"./asset-1b8ejkZX.js";import{r as p}from"./texture-coordinates-XFsEMdU6.js";function m(t,n,i={}){return r(t,n,e(i))}function h(t,n,r,i=[],a={}){return r===void 0&&(r=arguments.length<4?{}:[]),Array.isArray(r)?o(t,n,r,i,e(a)):o(t,n,e(r))}export{f as GLTFAsset,l as PBRDrawRun,a as PBRModel,s as applyGLTFLights,d as closeImages,m as loadGLTF,t as parseGLTF,h as parseGLTFAsync,c as parsePreparedPBR,p as textureCoordinates,n as textureTransform,u as validatePreparedGeometry,i as viewGLTFCamera};
1
+ import{t as e}from"./decoder-default-CxLH8Vz0.js";import{a as t,c as n,d as r,i,l as a,n as o,o as s,r as c,s as l,t as u}from"./model-C77ATxi1.js";import{s as d,t as f}from"./asset-DN3ocEdY.js";import{r as p}from"./texture-coordinates-XFsEMdU6.js";function m(t,n,r={}){return i(t,n,e(r))}function h(t,n,r,i=[],a={}){return r===void 0&&(r=arguments.length<4?{}:[]),Array.isArray(r)?s(t,n,r,i,e(a)):s(t,n,e(r))}export{f as GLTFAsset,u as PBRDrawRun,o as PBRModel,c as applyGLTFLights,d as closeImages,m as loadGLTF,t as parseGLTF,h as parseGLTFAsync,l as parsePreparedPBR,p as textureCoordinates,n as textureTransform,r as validatePreparedGeometry,a as viewGLTFCamera};
package/dist/physics.js CHANGED
@@ -1 +1 @@
1
- import{n as e}from"./errors-THVaUwlL.js";import{n as t,t as n}from"./scene-scope-CZDEkd24.js";import{r}from"./pack-BVDYuqZe.js";import{normalizeQuaternion as i,rotationToQuaternion as a}from"@margoengine/math/quat";import{composeMatrix as o,invertMatrix as s,multiplyMatrices as c}from"@margoengine/math/mat4";var l=e=>/* @__PURE__ */ TypeError(`Invalid ${e}; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`),u={box:[1,1,1],sphere:.5,height:.5,radius:.25},d={friction:.6,restitution:0};function f(e){return e.matrix?Float64Array.from(e.matrix):o(e.translation??[0,0,0],e.rotation??[0,0,0,1],e.scale??[1,1,1],/* @__PURE__ */ new Float64Array(16))}function p(e){let t=[Math.hypot(e[0],e[1],e[2]),Math.hypot(e[4],e[5],e[6]),Math.hypot(e[8],e[9],e[10])];e[0]*(e[5]*e[10]-e[6]*e[9])-e[4]*(e[1]*e[10]-e[2]*e[9])+e[8]*(e[1]*e[6]-e[2]*e[5])<0&&(t[0]=-t[0]);let n=[0,0,0,1];return a(e,n,t[0]||1,t[1]||1,t[2]||1),i(n,n),{position:[e[12],e[13],e[14]],rotation:n,scale:t}}function m(e){let{position:t,rotation:n}=p(e);return o(t,n,[1,1,1],/* @__PURE__ */ new Float64Array(16))}function h(e,t){let n=s(m(e),/* @__PURE__ */ new Float64Array(16));if(!n)throw l(`KHR_physics_rigid_bodies node transform`);return c(n,t,/* @__PURE__ */ new Float64Array(16))}function g(e,t){let n=m(e);return[0,1,2].map(e=>n[e]*t[0]+n[4+e]*t[1]+n[8+e]*t[2])}function ee(e,t=[0,0,0,1]){return[e[3]*t[0]+e[0]*t[3]+e[1]*t[2]-e[2]*t[1],e[3]*t[1]-e[0]*t[2]+e[1]*t[3]+e[2]*t[0],e[3]*t[2]+e[0]*t[1]-e[1]*t[0]+e[2]*t[3],e[3]*t[3]-e[0]*t[0]-e[1]*t[1]-e[2]*t[2]]}function te(e,t,n=[0,0,0]){let[r,i,a,o]=t,[s,c,l]=n,u=2*(i*l-a*c),d=2*(a*s-r*l),f=2*(r*c-i*s);return[e[0]+s+o*u+i*f-a*d,e[1]+c+o*d+a*u-r*f,e[2]+l+o*f+r*d-i*u]}function _(e){let t=[...e,{}],n=e=>JSON.stringify([e.collisionSystems,e.collideWithSystems,e.notCollideWithSystems]),r=[...new Map(t.map(e=>[n(e),e])).values()];if(r.length>16)throw RangeError(`KHR_physics_rigid_bodies: more than 15 distinct collision filters; merge filters that act alike in the file`);let i=(e,t)=>!!e.collisionSystems?.length&&e.collisionSystems.every(e=>t.includes(e)),a=(e,t)=>(!e.collideWithSystems||i(t,e.collideWithSystems))&&(!e.notCollideWithSystems||!i(t,e.notCollideWithSystems)),o=r.map((e,t)=>({memberships:1<<t,filter:r.reduce((t,n,r)=>a(e,n)&&a(n,e)?t|1<<r:t,0)}));return t.map(e=>o[r.findIndex(t=>n(t)===n(e))])}var v=(e,t,n,r,i=16)=>{for(let a=0;a<i;a++){let o=a/i*Math.PI*2;r.push(Math.cos(o)*t*n[0],e*n[1],Math.sin(o)*t*n[2])}},y=(e,t,n,r)=>{for(let i of[1,-1])for(let a=0;a<=6;a++){let o=a/6*(Math.PI/2);a===6?r.push(0,(e+i*t)*n[1],0):v(e+i*Math.sin(o)*t,Math.cos(o)*t,n,r)}};function b(e,t){let[n,r,i]=t,a=(e,t)=>Math.abs(e-t)<=1e-6*Math.max(e,t),o=a(n,i),s=(e,t)=>({collider:{shape:`convexHull`,points:Float32Array.from(e)},note:t});switch(e.type){case`box`:{let[t,a,o]=e.box?.size??u.box;return{collider:{shape:`box`,halfExtents:[t*n/2,a*r/2,o*i/2]}}}case`sphere`:{let i=e.sphere?.radius??u.sphere;if(o&&a(n,r))return{collider:{shape:`sphere`,radius:i*n}};let c=[];return y(0,i,t,c),s(c,`a sphere under uneven scale is a convex hull of 194 points`)}case`cylinder`:{let i=e.cylinder?.height??u.height,c=e.cylinder?.radiusTop??u.radius,l=e.cylinder?.radiusBottom??u.radius,d=i/2*r;if(o&&a(c,l))return{collider:{shape:`cylinder`,halfHeight:d,radius:c*n}};if(o&&!c)return{collider:{shape:`cone`,halfHeight:d,radius:l*n}};if(o&&!l)return{collider:{shape:`cone`,halfHeight:d,radius:c*n,rotation:[1,0,0,0]}};let f=[];return v(i/2,c,t,f,32),v(-i/2,l,t,f,32),s(f,`a cylinder with two radii or uneven scale is a convex hull of 64 points`)}case`capsule`:{let i=e.capsule?.height??u.height,c=e.capsule?.radiusTop??u.radius,l=e.capsule?.radiusBottom??u.radius;if(o&&a(c,l)&&a(n,r))return{collider:{shape:`capsule`,halfHeight:i/2*r,radius:c*n}};let d=[];return y(i/2,c,t,d),y(-i/2,l,t,d),s(d,`a capsule with two radii or uneven scale is a convex hull of 388 points`)}case`plane`:{let{sizeX:t,sizeZ:r,doubleSided:a}=e.plane??{};if(t===void 0&&r===void 0&&!a)return{collider:{shape:`halfSpace`}};let o=1e3;return{collider:{shape:`box`,halfExtents:[t===void 0?o:t*n/2,.001,r===void 0?o:r*i/2],offset:[0,a?0:-.001,0]},note:`a finite or double sided plane is a box 2 mm thick`}}default:throw l(`KHR_implicit_shapes type ${String(e.type)}`)}}var x=[`linX`,`linY`,`linZ`,`angX`,`angY`,`angZ`],S=e=>{if(!(e.axis>=0&&e.axis<=2)||e.type!==`linear`&&e.type!==`angular`)throw l(`KHR_physics_rigid_bodies joint drive`);return x[(e.type===`linear`?0:3)+e.axis]},C=e=>({targetPosition:e.positionTarget??0,targetVelocity:e.velocityTarget??0,stiffness:e.stiffness??0,damping:e.damping??0,model:e.mode===`force`?`force`:`acceleration`,...e.maxForce===void 0?{}:{maxForce:e.maxForce}});function w({limits:e=[],drives:t=[]},n=[]){let r=/* @__PURE__ */ new Set,i={},a={};for(let t of e){let e=t.linearAxes??t.angularAxes;if(!e?.length||e.length>3||t.linearAxes&&t.angularAxes)throw l(`KHR_physics_rigid_bodies joint limit`);t.stiffness!==void 0&&n.push(`a soft joint limit is held hard`);let a=e.length>1,o=t.linearAxes?1e6:Math.PI;if(a&&t.max===void 0){t.min&&n.push(`a lower limit on several axes at once is not held`);continue}a&&t.min&&n.push(`a lower limit on several axes at once is not held`),a&&t.max&&n.push(`a limit on ${e.length} axes at once is a range on each axis`);let s=Math.min(t.max??o,o),c=a?-s:Math.max(t.min??-o,-o);for(let n of e){if(!(n>=0&&n<=2))throw l(`KHR_physics_rigid_bodies joint axis`);let e=x[(t.linearAxes?0:3)+n],a=i[e];c===0&&s===0?r.add(e):i[e]=a?[Math.max(a[0],c),Math.min(a[1],s)]:[c,s]}}for(let e of r)delete i[e];for(let e of t)a[S(e)]=C(e);return{locked:[...r],limits:i,motors:a}}function ne({times:e,values:t,mode:n},r){let i=n===`CUBICSPLINE`,a=e=>t[i?e*3+1:e],o=e.length-1;if(r<=e[0])return a(0);if(r>=e[o])return a(o);let s=0;for(;e[s+1]<=r;)s++;let c=e[s+1]-e[s],l=(r-e[s])/c;if(n===`STEP`)return a(s);if(!i)return a(s)+(a(s+1)-a(s))*l;let u=l*l,d=u*l;return(2*d-3*u+1)*a(s)+(d-2*u+l)*c*t[s*3+2]+(-2*d+3*u)*a(s+1)+(d-u)*c*t[(s+1)*3]}var T=/^\/extensions\/KHR_physics_rigid_bodies\/physicsJoints\/(\d+)\/drives\/(\d+)\/(maxForce|positionTarget|velocityTarget|stiffness|damping)$/,re=/^\/nodes\/(\d+)\/extensions\/KHR_physics_rigid_bodies\/motion\/(linearVelocity|angularVelocity|gravityFactor)$/;async function E(i,a={}){let s=i.engine,u=s?.sceneOf?.(i),m=u?t(s,u):n(s),{Physics:v,collisionGroups:y}=await import(`@margoengine/physics`).catch(t=>{throw e(`unsupported`,`glTF physics needs @margoengine/physics (${t instanceof Error?t.message:t}): install it to use @margoengine/gltf/physics`)});a.physics||await v.load();let x=!a.physics,E=a.physics??m.run(()=>v.attach(s)),D=i.asset.doc,O=D.nodes??[],k=D.extensions?.KHR_physics_rigid_bodies??{},ie=D.extensions?.KHR_implicit_shapes?.shapes??[],ae=k.physicsMaterials??[],A=k.collisionFilters??[],j=structuredClone(k.physicsJoints??[]),oe=_(A),M=new Int32Array(O.length).fill(-1),N=[],P=/* @__PURE__ */ new Map,F=/* @__PURE__ */ new Map,I=/* @__PURE__ */ new Map,L=[],R=[],z=[],B=/* @__PURE__ */ new Map,V=(e,t)=>{N.some(n=>n.nodeIndex===e&&n.note===t)||N.push({nodeIndex:e,note:t})};O.forEach((e,t)=>e?.children?.forEach(e=>M[e]=t));let H=e=>O[e]?.extensions?.KHR_physics_rigid_bodies;s?.store.tick(!1);let U=e=>{let t=i.nodes[e];if(t)return Float64Array.from(t.matrix);let n=M[e];return n<0?f(O[e]):c(U(n),f(O[e]),/* @__PURE__ */ new Float64Array(16))},W=e=>{for(let t=e;t>=0;t=M[t])if(H(t)?.motion)return t;return-1},G=/* @__PURE__ */ new Set,K=/* @__PURE__ */ new Set,q=[];for(let e of D.animations??[])for(let t of e.channels??[]){let n=t.target,r=n?.extensions?.KHR_animation_pointer?.pointer,a=r?/^\/nodes\/(\d+)\/(translation|rotation|scale|matrix)$/.exec(r):void 0,o=r?a?.[1]:n?.node,s=r?a?.[2]:n?.path;if(o!==void 0&&s!==`weights`&&(G.add(+o),(s===`scale`||s===`matrix`)&&K.add(+o)),r){if(T.exec(r)){let n=e.samplers[t.sampler];q.push({pointer:r,times:i.asset.accessor(n.input,`SCALAR`),values:i.asset.accessor(n.output,`SCALAR`),mode:n.interpolation??`LINEAR`})}else r.includes(`KHR_physics_rigid_bodies`)&&V(-1,`the animated property ${r} is not followed`)}}let J=(e,t)=>{for(let n=e;n>=0;n=M[n])if(t.has(n))return!0;return!1},Y=/* @__PURE__ */ new Map,se=e=>{let t=Y.get(e);if(!t){let n=D.meshes?.[e];if(!n)throw l(`KHR_physics_rigid_bodies geometry mesh`);t=n.primitives.filter(e=>(e.mode??4)>=4).flatMap(e=>r(i.asset,e).map(({vertices:e,indices:t})=>{let n=new Float32Array(e.length/20*3);for(let t=0,r=0;r<e.length;t+=3,r+=20)n.set(e.subarray(r,r+3),t);return{positions:n,indices:t}})),Y.set(e,t)}return t},ce=(e,t)=>{let n=[],r=[],i=(e,i)=>{for(let a of se(e)){let e=n.length/3;for(let e=0;e<a.positions.length;e+=3){let r=a.positions[e],o=a.positions[e+1],s=a.positions[e+2];for(let e=0;e<3;e++)n.push((i[e]*r+i[4+e]*o+i[8+e]*s+i[12+e])*t[e])}for(let t=0;t<a.indices.length;t++)r.push(e+a.indices[t])}},a=(e,t)=>{if(!O[e])throw l(`KHR_physics_rigid_bodies geometry node`);O[e].mesh!==void 0&&i(O[e].mesh,t);for(let n of O[e].children??[])a(n,c(t,f(O[n]),/* @__PURE__ */ new Float64Array(16)))},s=o([0,0,0],[0,0,0,1],[1,1,1],/* @__PURE__ */ new Float64Array(16));return e.node===void 0?i(e.mesh,s):a(e.node,s),{points:n,indices:r}},X=e=>{let{geometry:t,node:n}=e,{position:r,rotation:i,scale:a}=p(h(U(e.base),U(n))),o=a.map(Math.abs);if(e.size=o,o.some(e=>e===0))return;if(t.shape===void 0==(t.node===void 0&&t.mesh===void 0))throw l(`KHR_physics_rigid_bodies geometry`);let s;if(t.shape!==void 0){let e=ie[t.shape];if(!e)throw l(`KHR_implicit_shapes shape index`);let r=b(e,o);s=r.collider,r.note&&V(n,r.note)}else{let{points:e,indices:n}=ce(t,o);if(!e.length)return;s=t.convexHull?{shape:`convexHull`,points:Float32Array.from(e)}:{shape:`trimesh`,vertices:Float32Array.from(e),indices:Uint32Array.from(n)}}let c=s;return{...s,...e.extra,offset:te(r,i,c.offset),rotation:ee(i,c.rotation)}},le=(e,t,n)=>{let r={};if(A.length){let e=oe[t??A.length];if(!e)throw l(`KHR_physics_rigid_bodies collisionFilter`);r.collisionGroups=y(e.memberships,e.filter)}if(n!==void 0){let t=ae[n];if(!t)throw l(`KHR_physics_rigid_bodies physicsMaterial`);let i=e=>e===`minimum`?`min`:e===`maximum`?`max`:e,a=t.dynamicFriction??d.friction;(t.staticFriction??d.friction)!==a&&V(e,`static friction is not separate: the dynamic value is used`),r.friction=a,r.restitution=t.restitution??d.restitution,t.frictionCombine&&(r.frictionCombine=i(t.frictionCombine)),t.restitutionCombine&&(r.restitutionCombine=i(t.restitutionCombine))}return r},Z=/* @__PURE__ */ new Map,Q=/* @__PURE__ */ new Map,ue=(e,t,n)=>{if(!t)throw l(`KHR_physics_rigid_bodies geometry`);let r=W(e),i=r>=0?r:e;Z.has(i)||Z.set(i,[]),Z.get(i).push({node:e,base:i,geometry:t,extra:n})};O.forEach((e,t)=>{let{collider:n,trigger:r}=H(t)??{};if(n&&ue(t,n.geometry,le(t,n.collisionFilter,n.physicsMaterial)),r?.nodes)for(let e of r.nodes)Q.set(e,t);r?.geometry&&ue(t,r.geometry,{...le(t,r.collisionFilter),sensor:!0,density:0})});let de=/* @__PURE__ */ new Set;O.forEach((e,t)=>{let n=H(t)?.joint;if(n&&j[n.joint]?.drives?.length)for(let e of[t,n.connectedNode])de.add(W(e))});let $=(e,t)=>{let n=i.nodes[e],r=!!n&&J(e,G),a=(Z.get(e)??[]).map(e=>({part:e,collider:X(e)})).filter(e=>e.collider),o=a.map(e=>e.collider),{position:s,rotation:c}=p(U(e)),l=de.has(e)?{canSleep:!1}:{},u=n&&t!==`fixed`&&!r?E.addBody(n,{type:t,colliders:o,...l}):E.addBody(null,{type:r?`kinematicPosition`:t,position:s,rotation:c,colliders:o,...l});return a.forEach(({part:e},t)=>{e.made=u.colliders[t],B.set(u.colliders[t],e.node)}),r&&R.push({body:u,node:e}),P.set(e,u),u},fe=e=>{let t=W(e);return P.get(t>=0?t:e)},pe=e=>{let t=W(e),n=t>=0?t:e;return[P.get(n)??$(n,`fixed`),p(h(U(n),U(e)))]},me=(e,t,n)=>{let{mass:r,inertiaDiagonal:i,centerOfMass:a,inertiaOrientation:o}=t;(r!==void 0||i||a)&&e.setMassProperties({mass:r,centerOfMass:a&&a.map((e,t)=>e*n[t]),inertia:i,inertiaFrame:o})},he=()=>{for(let e of z.splice(0))e();for(let e of F.values())e.remove();for(let e of P.values())E.removeBody(e);x&&E.dispose()};try{O.forEach((e,t)=>{let n=H(t)?.motion;if(!n)return;let r=U(t),i=$(t,n.isKinematic?`kinematicVelocity`:`dynamic`);n.linearVelocity&&i.setLinearVelocity(g(r,n.linearVelocity)),n.angularVelocity&&i.setAngularVelocity(g(r,n.angularVelocity)),n.gravityFactor!==void 0&&(i.gravityScale=n.gravityFactor),n.isKinematic||me(i,n,p(r).scale)});for(let e of Z.keys())P.has(e)||$(e,`fixed`);O.forEach((e,t)=>{H(t)?.trigger?.geometry&&L.push({nodeIndex:t,body:fe(t)})}),O.forEach((e,t)=>{let n=H(t)?.joint;if(!n)return;let r=j[n.joint],i=n.connectedNode;if(!r||!O[i])throw l(`KHR_physics_rigid_bodies joint`);let a=[],o=w(r,a),[s,c]=pe(t),[u,d]=pe(i);for(let e of a)V(t,e);if(s===u)return V(t,`a joint between two nodes of one body has no effect`);let f=E.addJoint(s,u,{type:`generic`,...o,anchorA:c.position,frameA:c.rotation,anchorB:d.position,frameB:d.rotation,contactsEnabled:!!n.enableCollision});F.set(t,f),I.has(n.joint)||I.set(n.joint,[]),I.get(n.joint).push(f)})}catch(e){throw he(),e}let ge=(e,t)=>{let n=T.exec(e);if(n){let e=j[+n[1]]?.drives?.[+n[2]];if(!e||typeof t!=`number`)return!1;e[n[3]]=t;for(let t of I.get(+n[1])??[])t.setAxisMotor(S(e),C(e));return!0}let r=re.exec(e),i=r&&P.get(+r[1]);if(!r||!i)return!1;if(r[2]===`gravityFactor`)return typeof t==`number`&&(i.gravityScale=t,!0);if(typeof t==`number`)return!1;let a=g(U(+r[1]),t);return r[2]===`linearVelocity`?i.setLinearVelocity(a):i.setAngularVelocity(a),!0},_e=(e,t)=>{let n=e.size,{scale:r}=p(h(U(e.base),U(e.node)));if(r.every((e,t)=>Math.abs(Math.abs(e)-n[t])<=1e-6*n[t]))return;e.made&&=(B.delete(e.made),t.removeCollider(e.made),void 0);let i=X(e);i&&(e.made=t.addCollider(i),B.set(e.made,e.node))};if(R.length||q.length){let e=0,t=q.reduce((e,t)=>Math.max(e,t.times[t.times.length-1]),0);z.push(E.on(`beforestep`,n=>{if(q.length){e+=n;let r=t>0?e%t:0;for(let e of q)ge(e.pointer,ne(e,r))}for(let{body:e,node:t}of R){let{position:n,rotation:r}=p(U(t));e.setNextPosition(n),e.setNextRotation(r);for(let n of Z.get(t)??[])J(n.node,K)&&_e(n,e)}}))}let ve=e=>{let t=e;for(;Q.has(t);)t=Q.get(t);return t},ye=!1;return{physics:E,bodies:P,joints:F,triggers:L,notes:N,bodyOf:fe,setPointer:ge,onTrigger(e){let t=/* @__PURE__ */ new Map,n=n=>r=>{for(let[i,a,o]of[[r.colliderA,r.colliderB,r.bodyB],[r.colliderB,r.colliderA,r.bodyA]]){let r=B.get(i);if(r===void 0||!i.isSensor()||a.isSensor())continue;let s=ve(r),c=`${s}/${a.handle}`,l=(t.get(c)??0)+(n?1:-1);if(l?t.set(c,l):t.delete(c),l!==+!!n)continue;let u=B.get(a)??-1;e({entered:n,nodeIndex:s,colliderNodeIndex:u,motionNodeIndex:u<0?-1:W(u),body:o})}},r=[E.on(`intersectionstart`,n(!0)),E.on(`intersectionend`,n(!1))],i=()=>r.forEach(e=>e());return z.push(i),i},dispose(){ye||(ye=!0,he())}}}export{E as applyGLTFPhysics,_ as filterMasks,w as jointOptions,b as shapeCollider};
1
+ import{n as e,t}from"./scene-scope-CZDEkd24.js";import{r as n}from"./pack-DdxRO8k6.js";import{margoError as r}from"@margoengine/core/extension";import{normalizeQuaternion as i,rotationToQuaternion as a}from"@margoengine/math/quat";import{composeMatrix as o,invertMatrix as s,multiplyMatrices as c}from"@margoengine/math/mat4";var l=e=>/* @__PURE__ */ TypeError(`Invalid ${e}; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`),u={box:[1,1,1],sphere:.5,height:.5,radius:.25},d={friction:.6,restitution:0};function f(e){return e.matrix?Float64Array.from(e.matrix):o(e.translation??[0,0,0],e.rotation??[0,0,0,1],e.scale??[1,1,1],/* @__PURE__ */ new Float64Array(16))}function p(e){let t=[Math.hypot(e[0],e[1],e[2]),Math.hypot(e[4],e[5],e[6]),Math.hypot(e[8],e[9],e[10])];e[0]*(e[5]*e[10]-e[6]*e[9])-e[4]*(e[1]*e[10]-e[2]*e[9])+e[8]*(e[1]*e[6]-e[2]*e[5])<0&&(t[0]=-t[0]);let n=[0,0,0,1];return a(e,n,t[0]||1,t[1]||1,t[2]||1),i(n,n),{position:[e[12],e[13],e[14]],rotation:n,scale:t}}function m(e){let{position:t,rotation:n}=p(e);return o(t,n,[1,1,1],/* @__PURE__ */ new Float64Array(16))}function h(e,t){let n=s(m(e),/* @__PURE__ */ new Float64Array(16));if(!n)throw l(`KHR_physics_rigid_bodies node transform`);return c(n,t,/* @__PURE__ */ new Float64Array(16))}function g(e,t){let n=m(e);return[0,1,2].map(e=>n[e]*t[0]+n[4+e]*t[1]+n[8+e]*t[2])}function ee(e,t=[0,0,0,1]){return[e[3]*t[0]+e[0]*t[3]+e[1]*t[2]-e[2]*t[1],e[3]*t[1]-e[0]*t[2]+e[1]*t[3]+e[2]*t[0],e[3]*t[2]+e[0]*t[1]-e[1]*t[0]+e[2]*t[3],e[3]*t[3]-e[0]*t[0]-e[1]*t[1]-e[2]*t[2]]}function te(e,t,n=[0,0,0]){let[r,i,a,o]=t,[s,c,l]=n,u=2*(i*l-a*c),d=2*(a*s-r*l),f=2*(r*c-i*s);return[e[0]+s+o*u+i*f-a*d,e[1]+c+o*d+a*u-r*f,e[2]+l+o*f+r*d-i*u]}function _(e){let t=[...e,{}],n=e=>JSON.stringify([e.collisionSystems,e.collideWithSystems,e.notCollideWithSystems]),r=[...new Map(t.map(e=>[n(e),e])).values()];if(r.length>16)throw RangeError(`KHR_physics_rigid_bodies: more than 15 distinct collision filters; merge filters that act alike in the file`);let i=(e,t)=>!!e.collisionSystems?.length&&e.collisionSystems.every(e=>t.includes(e)),a=(e,t)=>(!e.collideWithSystems||i(t,e.collideWithSystems))&&(!e.notCollideWithSystems||!i(t,e.notCollideWithSystems)),o=r.map((e,t)=>({memberships:1<<t,filter:r.reduce((t,n,r)=>a(e,n)&&a(n,e)?t|1<<r:t,0)}));return t.map(e=>o[r.findIndex(t=>n(t)===n(e))])}var v=(e,t,n,r,i=16)=>{for(let a=0;a<i;a++){let o=a/i*Math.PI*2;r.push(Math.cos(o)*t*n[0],e*n[1],Math.sin(o)*t*n[2])}},y=(e,t,n,r)=>{for(let i of[1,-1])for(let a=0;a<=6;a++){let o=a/6*(Math.PI/2);a===6?r.push(0,(e+i*t)*n[1],0):v(e+i*Math.sin(o)*t,Math.cos(o)*t,n,r)}};function b(e,t){let[n,r,i]=t,a=(e,t)=>Math.abs(e-t)<=1e-6*Math.max(e,t),o=a(n,i),s=(e,t)=>({collider:{shape:`convexHull`,points:Float32Array.from(e)},note:t});switch(e.type){case`box`:{let[t,a,o]=e.box?.size??u.box;return{collider:{shape:`box`,halfExtents:[t*n/2,a*r/2,o*i/2]}}}case`sphere`:{let i=e.sphere?.radius??u.sphere;if(o&&a(n,r))return{collider:{shape:`sphere`,radius:i*n}};let c=[];return y(0,i,t,c),s(c,`a sphere under uneven scale is a convex hull of 194 points`)}case`cylinder`:{let i=e.cylinder?.height??u.height,c=e.cylinder?.radiusTop??u.radius,l=e.cylinder?.radiusBottom??u.radius,d=i/2*r;if(o&&a(c,l))return{collider:{shape:`cylinder`,halfHeight:d,radius:c*n}};if(o&&!c)return{collider:{shape:`cone`,halfHeight:d,radius:l*n}};if(o&&!l)return{collider:{shape:`cone`,halfHeight:d,radius:c*n,rotation:[1,0,0,0]}};let f=[];return v(i/2,c,t,f,32),v(-i/2,l,t,f,32),s(f,`a cylinder with two radii or uneven scale is a convex hull of 64 points`)}case`capsule`:{let i=e.capsule?.height??u.height,c=e.capsule?.radiusTop??u.radius,l=e.capsule?.radiusBottom??u.radius;if(o&&a(c,l)&&a(n,r))return{collider:{shape:`capsule`,halfHeight:i/2*r,radius:c*n}};let d=[];return y(i/2,c,t,d),y(-i/2,l,t,d),s(d,`a capsule with two radii or uneven scale is a convex hull of 388 points`)}case`plane`:{let{sizeX:t,sizeZ:r,doubleSided:a}=e.plane??{};if(t===void 0&&r===void 0&&!a)return{collider:{shape:`halfSpace`}};let o=1e3;return{collider:{shape:`box`,halfExtents:[t===void 0?o:t*n/2,.001,r===void 0?o:r*i/2],offset:[0,a?0:-.001,0]},note:`a finite or double sided plane is a box 2 mm thick`}}default:throw l(`KHR_implicit_shapes type ${String(e.type)}`)}}var x=[`linX`,`linY`,`linZ`,`angX`,`angY`,`angZ`],S=e=>{if(!(e.axis>=0&&e.axis<=2)||e.type!==`linear`&&e.type!==`angular`)throw l(`KHR_physics_rigid_bodies joint drive`);return x[(e.type===`linear`?0:3)+e.axis]},C=e=>({targetPosition:e.positionTarget??0,targetVelocity:e.velocityTarget??0,stiffness:e.stiffness??0,damping:e.damping??0,model:e.mode===`force`?`force`:`acceleration`,...e.maxForce===void 0?{}:{maxForce:e.maxForce}});function w({limits:e=[],drives:t=[]},n=[]){let r=/* @__PURE__ */ new Set,i={},a={};for(let t of e){let e=t.linearAxes??t.angularAxes;if(!e?.length||e.length>3||t.linearAxes&&t.angularAxes)throw l(`KHR_physics_rigid_bodies joint limit`);t.stiffness!==void 0&&n.push(`a soft joint limit is held hard`);let a=e.length>1,o=t.linearAxes?1e6:Math.PI;if(a&&t.max===void 0){t.min&&n.push(`a lower limit on several axes at once is not held`);continue}a&&t.min&&n.push(`a lower limit on several axes at once is not held`),a&&t.max&&n.push(`a limit on ${e.length} axes at once is a range on each axis`);let s=Math.min(t.max??o,o),c=a?-s:Math.max(t.min??-o,-o);for(let n of e){if(!(n>=0&&n<=2))throw l(`KHR_physics_rigid_bodies joint axis`);let e=x[(t.linearAxes?0:3)+n],a=i[e];c===0&&s===0?r.add(e):i[e]=a?[Math.max(a[0],c),Math.min(a[1],s)]:[c,s]}}for(let e of r)delete i[e];for(let e of t)a[S(e)]=C(e);return{locked:[...r],limits:i,motors:a}}function ne({times:e,values:t,mode:n},r){let i=n===`CUBICSPLINE`,a=e=>t[i?e*3+1:e],o=e.length-1;if(r<=e[0])return a(0);if(r>=e[o])return a(o);let s=0;for(;e[s+1]<=r;)s++;let c=e[s+1]-e[s],l=(r-e[s])/c;if(n===`STEP`)return a(s);if(!i)return a(s)+(a(s+1)-a(s))*l;let u=l*l,d=u*l;return(2*d-3*u+1)*a(s)+(d-2*u+l)*c*t[s*3+2]+(-2*d+3*u)*a(s+1)+(d-u)*c*t[(s+1)*3]}var re=/^\/extensions\/KHR_physics_rigid_bodies\/physicsJoints\/(\d+)\/drives\/(\d+)\/(maxForce|positionTarget|velocityTarget|stiffness|damping)$/,ie=/^\/nodes\/(\d+)\/extensions\/KHR_physics_rigid_bodies\/motion\/(linearVelocity|angularVelocity|gravityFactor)$/;async function T(i,a={}){let s=i.engine,u=s?.sceneOf?.(i),m=u?e(s,u):t(s),{Physics:v,collisionGroups:y,densityOf:x}=await import(`@margoengine/physics`).catch(e=>{throw r(`unsupported`,`glTF physics needs @margoengine/physics (${e instanceof Error?e.message:e}): install it to use @margoengine/gltf/physics`)});a.physics||await v.load();let T=(i.asset.doc.nodes??[]).some(e=>e.extensions?.KHR_physics_rigid_bodies?.collider?.extras?.margo?.decomposition===!0)?(await import(`@margoengine/physics/decomposition`)).convexDecomposition:null,ae=!a.physics,E=a.physics??m.run(()=>v.attach(s)),D=i.asset.doc,O=D.nodes??[],k=D.extensions?.KHR_physics_rigid_bodies??{},oe=D.extensions?.KHR_implicit_shapes?.shapes??[],se=k.physicsMaterials??[],A=k.collisionFilters??[],j=structuredClone(k.physicsJoints??[]),ce=_(A),M=new Int32Array(O.length).fill(-1),N=[],P=/* @__PURE__ */ new Map,F=/* @__PURE__ */ new Map,I=/* @__PURE__ */ new Map,L=[],R=[],z=[],B=/* @__PURE__ */ new Map,V=(e,t)=>{N.some(n=>n.nodeIndex===e&&n.note===t)||N.push({nodeIndex:e,note:t})};O.forEach((e,t)=>e?.children?.forEach(e=>M[e]=t));let H=e=>O[e]?.extensions?.KHR_physics_rigid_bodies;s?.store.tick(!1);let U=e=>{let t=i.nodes[e];if(t)return Float64Array.from(t.matrix);let n=M[e];return n<0?f(O[e]):c(U(n),f(O[e]),/* @__PURE__ */ new Float64Array(16))},W=e=>{for(let t=e;t>=0;t=M[t])if(H(t)?.motion)return t;return-1},G=/* @__PURE__ */ new Set,K=/* @__PURE__ */ new Set,q=[];for(let e of D.animations??[])for(let t of e.channels??[]){let n=t.target,r=n?.extensions?.KHR_animation_pointer?.pointer,a=r?/^\/nodes\/(\d+)\/(translation|rotation|scale|matrix)$/.exec(r):void 0,o=r?a?.[1]:n?.node,s=r?a?.[2]:n?.path;if(o!==void 0&&s!==`weights`&&(G.add(+o),(s===`scale`||s===`matrix`)&&K.add(+o)),r){if(re.exec(r)){let n=e.samplers[t.sampler];q.push({pointer:r,times:i.asset.accessor(n.input,`SCALAR`),values:i.asset.accessor(n.output,`SCALAR`),mode:n.interpolation??`LINEAR`})}else r.includes(`KHR_physics_rigid_bodies`)&&V(-1,`the animated property ${r} is not followed`)}}let J=(e,t)=>{for(let n=e;n>=0;n=M[n])if(t.has(n))return!0;return!1},Y=/* @__PURE__ */ new Map,le=e=>{let t=Y.get(e);if(!t){let r=D.meshes?.[e];if(!r)throw l(`KHR_physics_rigid_bodies geometry mesh`);let a=e=>{let t=new Float32Array(e.length/20*3);for(let n=0,r=0;r<e.length;n+=3,r+=20)t.set(e.subarray(r,r+3),n);return t};if(!D.buffers?.length){let n=i.primitives??[],r=n.find(t=>t.nodeIndex!==void 0&&O[t.nodeIndex]?.mesh===e)?.nodeIndex,o=n.filter(e=>e.nodeIndex===r);if(r!==void 0&&o.length)return t=o.map(e=>({positions:a(e.vertices),indices:e.indices})),Y.set(e,t),t}t=r.primitives.filter(e=>(e.mode??4)>=4).flatMap(e=>n(i.asset,e).map(({vertices:e,indices:t})=>{let n=new Float32Array(e.length/20*3);for(let t=0,r=0;r<e.length;t+=3,r+=20)n.set(e.subarray(r,r+3),t);return{positions:n,indices:t}})),Y.set(e,t)}return t},ue=(e,t)=>{let n=[],r=[],i=(e,i)=>{for(let a of le(e)){let e=n.length/3;for(let e=0;e<a.positions.length;e+=3){let r=a.positions[e],o=a.positions[e+1],s=a.positions[e+2];for(let e=0;e<3;e++)n.push((i[e]*r+i[4+e]*o+i[8+e]*s+i[12+e])*t[e])}for(let t=0;t<a.indices.length;t++)r.push(e+a.indices[t])}},a=(e,t)=>{if(!O[e])throw l(`KHR_physics_rigid_bodies geometry node`);O[e].mesh!==void 0&&i(O[e].mesh,t);for(let n of O[e].children??[])a(n,c(t,f(O[n]),/* @__PURE__ */ new Float64Array(16)))},s=o([0,0,0],[0,0,0,1],[1,1,1],/* @__PURE__ */ new Float64Array(16));return e.node===void 0?i(e.mesh,s):a(e.node,s),{points:n,indices:r}},X=e=>{let{geometry:t,node:n}=e,{position:r,rotation:i,scale:a}=p(h(U(e.base),U(n))),o=a.map(Math.abs);if(e.size=o,o.some(e=>e===0))return;if(t.shape===void 0==(t.node===void 0&&t.mesh===void 0))throw l(`KHR_physics_rigid_bodies geometry`);let s;if(t.shape!==void 0){let e=oe[t.shape];if(!e)throw l(`KHR_implicit_shapes shape index`);let r=b(e,o);s=r.collider,r.note&&V(n,r.note)}else{let{points:n,indices:r}=ue(t,o);if(!n.length)return;s=t.convexHull?{shape:`convexHull`,points:Float32Array.from(n)}:e.decompose&&T?T({vertices:Float32Array.from(n),indices:Uint32Array.from(r)}):{shape:`trimesh`,vertices:Float32Array.from(n),indices:Uint32Array.from(r)}}let c=s;return{...s,...e.extra,offset:te(r,i,c.offset),rotation:ee(i,c.rotation)}},de=(e,t,n)=>{let r={};if(A.length){let e=ce[t??A.length];if(!e)throw l(`KHR_physics_rigid_bodies collisionFilter`);r.collisionGroups=y(e.memberships,e.filter)}if(n!==void 0){let t=se[n];if(!t)throw l(`KHR_physics_rigid_bodies physicsMaterial`);let i=e=>e===`minimum`?`min`:e===`maximum`?`max`:e,a=t.dynamicFriction??d.friction;(t.staticFriction??d.friction)!==a&&V(e,`static friction is not separate: the dynamic value is used`),r.friction=a,r.restitution=t.restitution??d.restitution,t.frictionCombine&&(r.frictionCombine=i(t.frictionCombine)),t.restitutionCombine&&(r.restitutionCombine=i(t.restitutionCombine))}return r},Z=/* @__PURE__ */ new Map,Q=/* @__PURE__ */ new Map,fe=(e,t,n)=>{if(!t)throw l(`KHR_physics_rigid_bodies geometry`);let r=W(e),i=r>=0?r:e;Z.has(i)||Z.set(i,[]),Z.get(i).push({node:e,base:i,geometry:t,extra:n})};O.forEach((e,t)=>{let{collider:n,trigger:r}=H(t)??{};if(n){let e=n.extras?.margo,r=de(t,n.collisionFilter,n.physicsMaterial);e?.density!==void 0&&(r.density=x(e.density)),fe(t,n.geometry,r),e?.decomposition===!0&&(Z.get(W(t)>=0?W(t):t).at(-1).decompose=!0)}if(r?.nodes)for(let e of r.nodes)Q.set(e,t);r?.geometry&&fe(t,r.geometry,{...de(t,r.collisionFilter),sensor:!0,density:0})});let pe=/* @__PURE__ */ new Set;O.forEach((e,t)=>{let n=H(t)?.joint;if(n&&j[n.joint]?.drives?.length)for(let e of[t,n.connectedNode])pe.add(W(e))});let $=(e,t)=>{let n=i.nodes[e],r=!!n&&J(e,G),a=(Z.get(e)??[]).map(e=>({part:e,collider:X(e)})).filter(e=>e.collider),o=a.map(e=>e.collider),{position:s,rotation:c}=p(U(e)),l=pe.has(e)?{canSleep:!1}:{},u=n&&t!==`fixed`&&!r?E.addBody(n,{type:t,colliders:o,...l}):E.addBody(null,{type:r?`kinematicPosition`:t,position:s,rotation:c,colliders:o,...l});return a.forEach(({part:e},t)=>{e.made=u.colliders[t],B.set(u.colliders[t],e.node)}),r&&R.push({body:u,node:e}),P.set(e,u),u},me=e=>{let t=W(e);return P.get(t>=0?t:e)},he=e=>{let t=W(e),n=t>=0?t:e;return[P.get(n)??$(n,`fixed`),p(h(U(n),U(e)))]},ge=(e,t,n)=>{let{mass:r,inertiaDiagonal:i,centerOfMass:a,inertiaOrientation:o}=t;(r!==void 0||i||a)&&e.setMassProperties({mass:r,centerOfMass:a&&a.map((e,t)=>e*n[t]),inertia:i,inertiaFrame:o})},_e=()=>{for(let e of z.splice(0))e();for(let e of F.values())e.remove();for(let e of P.values())E.removeBody(e);ae&&E.dispose()};try{O.forEach((e,t)=>{let n=H(t)?.motion;if(!n)return;let r=U(t),i=$(t,n.isKinematic?`kinematicVelocity`:`dynamic`);n.linearVelocity&&i.setLinearVelocity(g(r,n.linearVelocity)),n.angularVelocity&&i.setAngularVelocity(g(r,n.angularVelocity)),n.gravityFactor!==void 0&&(i.gravityScale=n.gravityFactor),n.isKinematic||ge(i,n,p(r).scale)});for(let e of Z.keys())P.has(e)||$(e,`fixed`);O.forEach((e,t)=>{H(t)?.trigger?.geometry&&L.push({nodeIndex:t,body:me(t)})}),O.forEach((e,t)=>{let n=H(t)?.joint;if(!n)return;let r=j[n.joint],i=n.connectedNode;if(!r||!O[i])throw l(`KHR_physics_rigid_bodies joint`);let a=[],o=w(r,a),[s,c]=he(t),[u,d]=he(i);for(let e of a)V(t,e);if(s===u)return V(t,`a joint between two nodes of one body has no effect`);let f=E.addJoint(s,u,{type:`generic`,...o,anchorA:c.position,frameA:c.rotation,anchorB:d.position,frameB:d.rotation,contactsEnabled:!!n.enableCollision});F.set(t,f),I.has(n.joint)||I.set(n.joint,[]),I.get(n.joint).push(f)})}catch(e){throw _e(),e}let ve=(e,t)=>{let n=re.exec(e);if(n){let e=j[+n[1]]?.drives?.[+n[2]];if(!e||typeof t!=`number`)return!1;e[n[3]]=t;for(let t of I.get(+n[1])??[])t.setAxisMotor(S(e),C(e));return!0}let r=ie.exec(e),i=r&&P.get(+r[1]);if(!r||!i)return!1;if(r[2]===`gravityFactor`)return typeof t==`number`&&(i.gravityScale=t,!0);if(typeof t==`number`)return!1;let a=g(U(+r[1]),t);return r[2]===`linearVelocity`?i.setLinearVelocity(a):i.setAngularVelocity(a),!0},ye=(e,t)=>{let n=e.size,{scale:r}=p(h(U(e.base),U(e.node)));if(r.every((e,t)=>Math.abs(Math.abs(e)-n[t])<=1e-6*n[t]))return;e.made&&=(B.delete(e.made),t.removeCollider(e.made),void 0);let i=X(e);i&&(e.made=t.addCollider(i),B.set(e.made,e.node))};if(R.length||q.length){let e=0,t=q.reduce((e,t)=>Math.max(e,t.times[t.times.length-1]),0);z.push(E.on(`beforestep`,n=>{if(q.length){e+=n;let r=t>0?e%t:0;for(let e of q)ve(e.pointer,ne(e,r))}for(let{body:e,node:t}of R){let{position:n,rotation:r}=p(U(t));e.setNextPosition(n),e.setNextRotation(r);for(let n of Z.get(t)??[])J(n.node,K)&&ye(n,e)}}))}let be=e=>{let t=e;for(;Q.has(t);)t=Q.get(t);return t},xe=!1;return{physics:E,bodies:P,joints:F,triggers:L,notes:N,bodyOf:me,setPointer:ve,onTrigger(e){let t=/* @__PURE__ */ new Map,n=n=>r=>{for(let[i,a,o]of[[r.colliderA,r.colliderB,r.bodyB],[r.colliderB,r.colliderA,r.bodyA]]){let r=B.get(i);if(r===void 0||!i.isSensor()||a.isSensor())continue;let s=be(r),c=`${s}/${a.handle}`,l=(t.get(c)??0)+(n?1:-1);if(l?t.set(c,l):t.delete(c),l!==+!!n)continue;let u=B.get(a)??-1;e({entered:n,nodeIndex:s,colliderNodeIndex:u,motionNodeIndex:u<0?-1:W(u),body:o})}},r=[E.on(`intersectionstart`,n(!0)),E.on(`intersectionend`,n(!1))],i=()=>r.forEach(e=>e());return z.push(i),i},dispose(){xe||(xe=!0,_e())}}}export{T as applyGLTFPhysics,_ as filterMasks,w as jointOptions,b as shapeCollider};
package/dist/prepare.js CHANGED
@@ -1 +1 @@
1
- import{_ as e,g as t}from"./asset-1b8ejkZX.js";import{r as n,t as r}from"./pack-BVDYuqZe.js";function i(t,i){let a=t.doc,o=e=>{try{return e()}catch{return null}},s=0,c=(a.meshes??[]).map(r=>(Array.isArray(r?.primitives)?r.primitives:[]).map(r=>{let i=o(()=>n(t,r));for(let e of i??[])s+=e.vertices.byteLength+e.indices.byteLength+(e.uvs?.byteLength??0);if(s>t.maxBytes*4)throw e(`Decoded glTF geometry exceeds byte budget`,t.maxBytes*4);return i&&i.length===1?i[0]:i}));return r(t),{doc:a,buffers:t.buffers,images:i,geometry:c,accessors:[...t.cache],maxDownloadBytes:t.maxBytes,maxNodes:t.maxNodes,maxPartVertices:t.partVertices}}async function a(e,n,r,a,o,s,c,l){let{asset:u,images:d,deferred:f,baseURL:p,downloadedBytes:m}=await t(e,{buffers:r,maxDownloadBytes:a,maxNodes:o,allowedURLs:s,optimize:c,maxPartVertices:l},n,{},!0);return f?{doc:u.doc,buffers:u.buffers,images:d,geometry:[],accessors:[],maxDownloadBytes:u.maxBytes,maxNodes:u.maxNodes,maxPartVertices:u.partVertices,deferred:f,baseURL:p,downloadedBytes:m}:i(u,d)}export{i as prepareAsset,a as prepareGLTF};
1
+ import{_ as e,v as t}from"./asset-DN3ocEdY.js";import{r as n,t as r}from"./pack-DdxRO8k6.js";function i(e,i){let a=e.doc,o=e=>{try{return e()}catch{return null}},s=0,c=(a.meshes??[]).map(r=>(Array.isArray(r?.primitives)?r.primitives:[]).map(r=>{let i=o(()=>n(e,r));for(let e of i??[])s+=e.vertices.byteLength+e.indices.byteLength+(e.uvs?.byteLength??0);if(s>e.maxBytes*4)throw t(`Decoded glTF geometry exceeds byte budget`,e.maxBytes*4);return i&&i.length===1?i[0]:i}));return r(e),{doc:a,buffers:e.buffers,images:i,geometry:c,accessors:[...e.cache],maxDownloadBytes:e.maxBytes,maxNodes:e.maxNodes,maxPartVertices:e.partVertices}}async function a(t,n,r,a,o,s,c,l){let{asset:u,images:d,deferred:f,baseURL:p,downloadedBytes:m}=await e(t,{buffers:r,maxDownloadBytes:a,maxNodes:o,allowedURLs:s,optimize:c,maxPartVertices:l},n,{},!0);return f?{doc:u.doc,buffers:u.buffers,images:d,geometry:[],accessors:[],maxDownloadBytes:u.maxBytes,maxNodes:u.maxNodes,maxPartVertices:u.partVertices,deferred:f,baseURL:p,downloadedBytes:m}:i(u,d)}export{i as prepareAsset,a as prepareGLTF};
@@ -0,0 +1,13 @@
1
+ import type { engineRuntime } from '@margoengine/core/extension';
2
+ import type { PBRModel } from './model.js';
3
+ export declare function levelOrder(model: PBRModel, engine: ReturnType<typeof engineRuntime>): {
4
+ /** A primitive has all its geometry: each object not taken over shows its finest level that has. */
5
+ arrived(key: number): void;
6
+ /**
7
+ * Raises each key's view score (0 to 2) by its tier: 8 for what the first whole picture needs (no levels, or a
8
+ * coarsest level), 4 for the level this view calls for, else under 4 with coarser levels first.
9
+ */
10
+ rank(score: Float64Array): void;
11
+ /** The load is over: no level is waited for, and an object not taken over shows its level 0 as loaded. */
12
+ release(): void;
13
+ };
@@ -53,7 +53,10 @@ export interface ProgressiveGLTF {
53
53
  * Load a .glb/.gltf so it is interactive at once: `ready` resolves with the model drawn as one box per primitive (fit the
54
54
  * camera to `model.bounds`), then real geometry streams in, most visible and largest on screen first (HTTP range requests
55
55
  * where the server supports them, else the whole file parsed as it arrives), then textures. Network and decoding run in a
56
- * worker (dist/workers/progressive.js; on this thread where Worker is unavailable); GPU uploads run here within
57
- * `frameBudget` ms per animation frame. Draco, meshopt or KTX2 `decoders` fall back to `loadGLTF` (ready = complete).
56
+ * worker (dist/workers/progressive.js; on this thread where Worker is unavailable, or for your own `decoders.meshopt`);
57
+ * GPU uploads run here within `frameBudget` ms per animation frame. Draco primitives decode one by one as their bytes
58
+ * arrive and meshopt views as they are read. An `MSFT_lod` object streams its coarsest level first and shows the finest
59
+ * level that has arrived; `LOD.fromModel` called at `ready` takes over and picks only levels that have arrived. A custom
60
+ * `fetch` or a `ktx2` decoder falls back to `loadGLTF` (ready = complete).
58
61
  */
59
62
  export declare function loadGLTFProgressive(instance: EngineKernel, url: string | URL, options?: ProgressiveGLTFOptions): ProgressiveGLTF;
@@ -1,4 +1,4 @@
1
- // @margo/core-built 0.1.0
1
+ // @margo/core-built 1.0.0
2
2
  import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
- const p=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
- import{n as e}from"./errors-THVaUwlL.js";import{f as t}from"./version-BmU1nesQ.js";import{t as n}from"./scene-scope-CZDEkd24.js";import{n as r}from"./model-iRvuj19h.js";import{A as i,_ as a,f as o,n as s,t as c}from"./asset-1b8ejkZX.js";import{a as l,i as u}from"./pack-BVDYuqZe.js";import{loadGLTF as d}from"./pbr.js";import{t as f}from"./worker-CY1TQnYX.js";import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";function m(e,t,n,r=0,i=0,a=0){let o=e[t],s=e[t+1],c=e[t+2],l=e[t+4],u=e[t+5],d=e[t+6],f=e[t+8],p=e[t+9],m=e[t+10],h=o*o+s*s+c*c,ee=l*l+u*u+d*d,te=f*f+p*p+m*m,g=Math.abs(o*l+s*u+c*d),_=Math.abs(o*f+s*p+c*m),v=Math.abs(l*f+u*p+d*m),y=n*Math.sqrt(Math.max(h+g+_,ee+g+v,te+_+v));return y+1e-5*(Math.hypot(r,i,a)+y)}var h=Symbol.for(`margoengine.gltf/pbr.defer-static-batches`),ee=()=>new URL(`./workers/progressive.js?no-inline`,import.meta.url),te=1<<20,g=[`KHR_texture_basisu`,`EXT_texture_webp`,`EXT_texture_avif`],_={TypeError,RangeError,SyntaxError},v=t=>{let n=typeof t?.message==`string`?t.message:`Progressive glTF worker sent an invalid message`;return t?.name===`MargoError`&&typeof t.code==`string`?e(t.code,n):new(Object.hasOwn(_,t?.name??``)?_[t.name]:Error)(n)};function y(e,t){let n=e.accessors?.[t?.attributes?.POSITION],r=e=>Array.isArray(e)&&e.length===3&&e.every(Number.isFinite),i=n?.normalized?{5120:127,5121:255,5122:32767,5123:65535}[n.componentType]??1:1,a=e=>r(e)?e.map(e=>i>1?Math.max(-1,e/i):e):[0,0,0],o=a(n?.min),s=a(n?.max),c=/* @__PURE__ */ new Float32Array(480),l=/* @__PURE__ */ new Uint32Array(36);for(let e=0;e<6;e++){let t=e>>1,n=e&1?1:-1,r=(t+1)%3,i=(t+2)%3,a=e*4;for(let e=0;e<4;e++){let l=(a+e)*20;c[l+t]=n>0?s[t]:o[t],c[l+r]=e&1?s[r]:o[r],c[l+i]=e&2?s[i]:o[i],c[l+3]=1,c[l+4+t]=n,c.fill(1,l+16,l+20)}l.set(n>0?[a,a+1,a+3,a,a+3,a+2]:[a,a+3,a+1,a,a+2,a+3],e*6)}return{vertices:c,indices:l,lo:o,hi:s}}function b(e,_,b={}){let{decoders:x={},signal:S,onProgress:ne,frameBudget:re=4,maxJobs:C,clock:w=()=>performance.now()}=b,T=new AbortController;if(C!==void 0&&!(C>=1))throw RangeError(`Invalid maxJobs; pass a count, 1 or more`);if(typeof w!=`function`)throw TypeError(`Invalid clock; pass a function returning milliseconds`);let E=e=>T.abort(e);S?.aborted?E(S.reason):S?.addEventListener(`abort`,()=>E(S.reason),{once:!0});let D={stage:`ready`,bytesLoaded:0,bytesTotal:0,primitives:0,primitivesLoaded:0,images:0,imagesLoaded:0},O=(e=D.stage)=>{D.stage=e,ne?.({...D})},ie=n(e),k=p(e),A=()=>k.gpu,ae=b.textures===!0?{}:b.textures,j=ae&&k.gpu?import(`./texture-stream-Cu_XpyVO.js`).then(({GLTFTextureStream:t})=>ie.run(()=>t.attach(e,ae,T.signal))):void 0;j?.catch(()=>{});let oe=async()=>{let t=await j,n=await ie.run(()=>d(e,_,{...b,decoders:t?{...x,textureStream:t}:x,signal:T.signal}));return t?.attach(n),n};if(b.fetch||b.draco||b.ktx2||x.draco||x.meshopt||x.ktx2){let e=oe().then(e=>(O(`complete`),e));return e.catch(()=>{}),{ready:e,complete:e,abort:E,...j?{textures:j}:{}}}let M,se,N,ce,le=new Promise((e,t)=>{M=e,se=t}),ue=new Promise((e,t)=>{N=e,ce=t});le.catch(()=>{}),ue.catch(()=>{});let P,F,I,L,de,R=!1,z=[],B=[],V=/* @__PURE__ */ new Set,H=[],fe=[],U=/* @__PURE__ */ new Map,W=/* @__PURE__ */ new Map,pe=/* @__PURE__ */ new Set,G=/* @__PURE__ */ new Set,me=[],K=[],q={},he=0,ge=``,_e=-1/0,J=!1,Y=s,X=0,ve=0,Z,ye=()=>{if(!Z||ve)return;let e=Z;Z=void 0,e()},Q=e=>{if(!R){R=!0,L?.terminate(),T.abort(e);for(let e of G)e.destroy();if(G.clear(),P)P.dispose();else for(let e of z)e?.close?.();j?.then(e=>e.dispose(),()=>{}),se(e),ce(e)}};T.signal.addEventListener(`abort`,()=>Q(T.signal.reason),{once:!0});let be=e=>L?L.postMessage({order:e}):de?.setOrder(e),xe=()=>{k.store.tick(!1);let e=k.camera,t=e.planes,n=e.position,r=t.some(e=>e!==0),i=new Float64Array(H.length);return P.primitives.forEach(e=>{let a=W.get(e),[o,s]=fe[a],c=e.node.matrix,l=[0,1,2].map(e=>c[e]*(o[0]+s[0])/2+c[4+e]*(o[1]+s[1])/2+c[8+e]*(o[2]+s[2])/2+c[12+e]),u=m(c,0,Math.hypot(s[0]-o[0],s[1]-o[1],s[2]-o[2])/2,l[0],l[1],l[2]),d=1;if(r)for(let e=0;e<24;e+=4)t[e]*l[0]+t[e+1]*l[1]+t[e+2]*l[2]+t[e+3]<-u&&(d=0);let f=u/Math.max(Math.hypot(l[0]-n[0],l[1]-n[1],l[2]-n[2])-u,1e-9);i[a]=Math.max(i[a],d+f/(1+f))}),H.map((e,t)=>t).filter(e=>H[e].length&&!pe.has(e)).sort((e,t)=>i[t]-i[e])},Se=e=>{let t=[];try{return r.prototype.setup.call(Object.create(P,{primitives:{value:e},resources:{value:t}}),P.engine),t}catch(e){for(let e of t)e.uniform.destroy();throw e}},Ce=e=>{let n=Se(e),r=P.resources,i=new t;e.forEach((e,t)=>{let a=P.primitives.indexOf(e),o=r[a];i.run(()=>o.uniform.destroy()).run(()=>o.wireframe?.index.destroy()),r[a]=n[t]}),i.finish()},we=e=>{let t=U.get(e),n=t.maps,r=0;return()=>{for(;r<n.length&&!n[r];)r++;if(r<n.length){let i=r++;return Se([{...e,material:{...t,maps:n.map((e,t)=>t===i?e:void 0)}}])[0].uniform.destroy(),!1}return e.material=t,Ce([e]),O(`textures`),!0}},$=(e=!1)=>{for(let t of V){let n=U.get(t).maps.flatMap(e=>{let t=e&&I.textures?.[e.index];return t?[t.source,...g.map(e=>t.extensions?.[e]?.source)].filter(Number.isSafeInteger):[]});(e||n.every(e=>B[e]))&&(V.delete(t),K.push(we(t)))}},Te=(e,t,n,r,i)=>{let o=[{data:t,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.STORAGE,at:0,buffer:void 0},{data:n,usage:GPUBufferUsage.INDEX,at:0,buffer:void 0},...r?[{data:r,usage:GPUBufferUsage.VERTEX,at:0,buffer:void 0}]:[]];if(he+=t.byteLength+n.byteLength+(r?.byteLength??0),he>Y*4)throw a(`Decoded glTF geometry exceeds byte budget`,Y*4);return()=>{let a=o.find(e=>e.at<e.data.byteLength);if(a){if(!a.buffer){if(a.data.byteLength>A().limits.maxBufferSize)throw RangeError(`PBR buffer exceeds device limit; load a smaller model, or reduce its textures and meshes`);G.add(a.buffer=A().createBuffer({size:a.data.byteLength,usage:a.usage|GPUBufferUsage.COPY_DST}))}let e=new Uint8Array(a.data.buffer,a.data.byteOffset,a.data.byteLength),t=Math.min(a.at+te,e.length);return A().queue.writeBuffer(a.buffer,a.at,e.subarray(a.at,t)),a.at=t,!1}let s=P.gpuCache,c=/* @__PURE__ */ new Set;for(let{data:e,buffer:t}of o)s.set(e,t),G.delete(t);if(i?.index)H[e]=H[e].map(a=>{let o={node:a.node,nodeIndex:a.nodeIndex,vertices:t,indices:n,definition:a.definition,material:a.material,weights:Float32Array.from(a.weights),targetNames:a.targetNames,...r?{uvs:r}:{},part:i};return W.set(o,e),U.set(o,U.get(a)),o.material!==U.get(o)&&V.add(o),P.insertPart(a,o,Se([o])[0]),o}),$();else{for(let a of H[e])c.add(a.vertices),c.add(a.indices),a.vertices=t,a.indices=n,r&&(a.uvs=r),i&&(a.part=i);Ce(H[e]);for(let e of c){let t=s.get(e);t&&P.dropBuffer(A(),t)}}return(!i||i.index===i.count-1)&&D.primitivesLoaded++,ve--,O(`geometry`),ye(),!0}},Ee=(e,t)=>()=>{e.forEach((e,t)=>{F.buffers[t]=e});for(let[e,n]of t)F.cache.set(e,n);if(x.instancing){q.instancing=x.instancing;let e=/* @__PURE__ */ new Map;for(let t of P.primitives){let n=I.nodes[t.nodeIndex]?.extensions?.EXT_mesh_gpu_instancing;n&&(e.has(t.nodeIndex)||e.set(t.nodeIndex,x.instancing.read(F,n)),t.instances=e.get(t.nodeIndex))}}let n=P.gpuCache,r=new Set(P.primitives.flatMap(e=>e.material.maps.map((e,t)=>e?-1:t)));for(let[e,t]of n)typeof e==`string`&&e.startsWith(`default:`)&&!r.has(+e.slice(8))&&P.dropTexture(A(),e,t);return F[h]?.commit?.(),R=!0,L?.terminate(),O(`complete`),N(P),!0},De=()=>{if(J=!1,!R){try{let e=w(),t=k.camera,n=String(t.position)+t.target;P&&n!==ge&&e-_e>200&&(ge=n,_e=e,be(xe()));let r=0;do K.length&&K[0]()&&K.shift(),r++;while(K.length&&!R&&(C===void 0?w()-e<re:r<C))}catch(e){Q(e);return}Oe()}},Oe=()=>{if(J||R)return;J=!0;let e=typeof requestAnimationFrame==`function`?requestAnimationFrame(n):0,t=setTimeout(n,e?100:16);function n(){clearTimeout(t),e&&cancelAnimationFrame(e),J&&De()}},ke=t=>{I=t;let n=l(I),i=new Map(n.map((e,t)=>[e,t]));n.forEach((e,t)=>{let n=y(I,e);fe[t]=[n.lo,n.hi],e&&typeof e==`object`&&u.set(e,[n])}),x.instancing&&(q.instancing={read:()=>void 0}),x.materials&&(q.materials=x.materials);let o=(I.buffers??[]).map(e=>Number.isSafeInteger(e?.byteLength)&&e.byteLength>0?e.byteLength:0);if(o.reduce((e,t)=>e+t,0)>Y)throw a(`glTF buffers exceed byte budget`,Y);F=new c(I,o.map(e=>new Uint8Array(e)),void 0,q,Y,b.maxNodes),F.partVertices=X,F[h]={},z=Array.from(I.images??[],()=>void 0),B=z.map(()=>!1),D.images=z.length,P=new r(e,F,z),H=n.map(()=>[]);for(let e of P.primitives){let t=i.get(e.definition);H[t].push(e),W.set(e,t)}D.primitives=H.filter(e=>e.length).length;let s=/* @__PURE__ */ new Map;for(let e of P.primitives){let t=e.material;U.set(e,t),t.maps.some(Boolean)&&(s.has(t)||s.set(t,Object.defineProperties(Object.assign(Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t)),{maps:t.maps.map(()=>void 0)}),{side:Object.getOwnPropertyDescriptor(t,`side`),wireframe:{enumerable:!0,get:()=>t.wireframe,set:e=>{t.wireframe=e}}})),e.material=s.get(t),V.add(e))}k.use(P),P.onDispose(()=>E(new DOMException(`Model disposed while loading`,`AbortError`))),j?.then(e=>e.attach(P),Q),O(`ready`),M(P),Oe()},Ae=e=>{if(R)e.type===`image`&&e.image&&`close`in e.image&&e.image.close();else try{if(e.type===`fallback`)L?.terminate(),L=void 0,oe().then(e=>{R?e.dispose():(P=e,R=!0,O(`complete`),M(e),N(e))},Q);else if(e.type===`doc`)ie.run(()=>ke(e.doc));else if(e.type===`geometry`){if(e.error)throw v(e.error);pe.add(e.key),K.push(Te(e.key,e.vertices,e.indices,e.uvs,e.part)),ve++}else if(e.type===`image`){if(!Number.isInteger(e.index)||e.index<0||e.index>=z.length)throw RangeError(`Progressive glTF worker sent an invalid image index; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let{index:t,source:n}=e;n?me.push(j.then(e=>e.open(n)).then(e=>{R?e.close():(z[t]=e,B[t]=!0,D.imagesLoaded++,$())}).catch(Q)):(z[t]=e.image,B[t]=!0,e.image&&D.imagesLoaded++,$())}else if(e.type===`bytes`)D.bytesLoaded=e.loaded,D.bytesTotal=e.total,P&&O();else if(e.type===`done`){let{buffers:t,accessors:n}=e;Promise.all(me).then(()=>{R||(Z=()=>{$(!0),K.push(Ee(t,n))},ye())})}else throw v(e.error)}catch(e){Q(e)}};try{S?.throwIfAborted(),Y=o(b.maxDownloadBytes),X=i(b.maxPartVertices);let e=new URL(_,globalThis.location?.href).href;f()?(L=new Worker(ee(),{name:`margoengine-progressive`}),L.onmessage=({data:e})=>Ae(e&&typeof e==`object`?e:{type:`error`,error:{name:`TypeError`,message:`Progressive glTF worker sent an invalid message`}}),L.onerror=e=>{e.preventDefault?.(),Q(/* @__PURE__ */ Error(`Progressive glTF worker failed: `+(e.message||`unknown error`)))},L.onmessageerror=()=>Q(/* @__PURE__ */ Error(`Progressive glTF worker message could not be deserialized`)),L.postMessage({url:e,maxDownloadBytes:Y,maxNodes:b.maxNodes,allowedURLs:b.allowedURLs,textures:!!j,maxPartVertices:X})):import(`./stream-C3bKMy1B.js`).then(({GLTFStream:t})=>{R||(de=new t(new URL(e),Ae,T.signal,Y,b.maxNodes,b.allowedURLs,!!j,X)).run()},Q)}catch(e){Q(e)}return{ready:le,complete:ue,abort:E,...j?{textures:j}:{}}}export{b as loadGLTFProgressive};
3
+ const g=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import{f as e}from"./version-B6NE5cJf.js";import{t}from"./scene-scope-CZDEkd24.js";import{t as n}from"./decoder-default-CxLH8Vz0.js";import{n as r,u as i}from"./model-C77ATxi1.js";import{D as a,M as o,T as s,i as c,n as l,o as u,p as d,r as f,t as p,v as m}from"./asset-DN3ocEdY.js";import{a as ee,i as te}from"./pack-DdxRO8k6.js";import{loadGLTF as ne}from"./pbr.js";import{t as h}from"./worker-CY1TQnYX.js";import{engineRuntime as __margoRuntime,margoError as _}from"@margoengine/core/extension";function v(e,t,n,r=0,i=0,a=0){let o=e[t],s=e[t+1],c=e[t+2],l=e[t+4],u=e[t+5],d=e[t+6],f=e[t+8],p=e[t+9],m=e[t+10],ee=o*o+s*s+c*c,te=l*l+u*u+d*d,ne=f*f+p*p+m*m,h=Math.abs(o*l+s*u+c*d),g=Math.abs(o*f+s*p+c*m),_=Math.abs(l*f+u*p+d*m),v=n*Math.sqrt(Math.max(ee+h+g,te+h+_,ne+g+_));return v+1e-5*(Math.hypot(r,i,a)+v)}function re(e,t){let n=e.asset.doc,r=e.nodes,i=/* @__PURE__ */ new Map,a=0;for(let e of n.meshes??[])for(let t of e?.primitives??[])i.set(t,a++);let o=/* @__PURE__ */ new Set,s=/* @__PURE__ */ new Set,c=e.lods.map(t=>{let a=t.levels.map(e=>r.indexOf(e)),o=new Set(a),c=a.map(t=>{let r=/* @__PURE__ */ new Set,a=[t];for(;a.length;){let e=a.pop();if(!r.has(e)){r.add(e);for(let t of n.nodes?.[e]?.children??[])o.has(t)||a.push(t)}}let c=/* @__PURE__ */ new Set;for(let t of e.primitives)r.has(t.nodeIndex)&&c.add(i.get(t.definition));for(let e of c)s.add(e);return c}),l=c.length-1;for(;l>0&&!c[l].size;)l--;return{lod:t,levels:c,coarsest:l,visible:t.levels[0].visible,taken:!1}}),l=(e,t)=>[...e.levels[t]].every(e=>o.has(e)),u=(e,t)=>e.lod.levels.forEach((n,r)=>{n.visible=r===t&&e.visible});for(let e of c)e.lod.levels.forEach((t,n)=>{t.request=()=>{if(!e.taken){e.taken=!0;for(let t of e.lod.levels)t.visible=!1}return l(e,n)||n===e.coarsest&&!e.levels.some((t,n)=>t.size&&l(e,n))}});return{arrived(e){o.add(e);for(let e of c){if(e.taken)continue;let t=e.levels.findIndex((t,n)=>t.size>0&&l(e,n));u(e,Math.max(t,0))}},rank(n){if(!c.length)return;let r=new Float64Array(n.length).fill(0);for(let e=0;e<n.length;e++)s.has(e)||(r[e]=8);let a=t.camera.matrix,o=Math.hypot(a[1],a[5],a[9]);for(let t of c){let n=0;for(let r of e.primitives){if(!t.levels[0].has(i.get(r.definition)))continue;let e=r.vertices,s=r.node.matrix,c=[1/0,1/0,1/0],l=[-1/0,-1/0,-1/0];for(let t=0;t<e.length;t+=20)for(let n=0;n<3;n++)c[n]=Math.min(c[n],e[t+n]),l[n]=Math.max(l[n],e[t+n]);let u=[0,1,2].map(e=>s[e]*(c[0]+l[0])/2+s[4+e]*(c[1]+l[1])/2+s[8+e]*(c[2]+l[2])/2+s[12+e]),d=v(s,0,Math.hypot(l[0]-c[0],l[1]-c[1],l[2]-c[2])/2,u[0],u[1],u[2]),f=Math.abs(a[3]*u[0]+a[7]*u[1]+a[11]*u[2]+a[15]);n=Math.max(n,o*d/Math.max(f,1e-9))}let s=t.lod.screenCoverage,c=0;for(let e=1;e<t.levels.length;e++)n<=(s?.[e-1]??.25*.5**(e-1))&&(c=e);t.levels.forEach((e,n)=>{let i=n===t.coarsest?8:n===c?4:2*n/t.levels.length;for(let t of e)r[t]=Math.max(r[t],i)})}for(let e=0;e<n.length;e++)n[e]+=r[e]},release(){for(let e of c){for(let t of e.lod.levels)delete t.request;e.taken||u(e,0)}}}}var ie=Symbol.for(`margoengine.gltf/pbr.defer-static-batches`),ae=()=>new URL(`./workers/progressive.js?no-inline`,import.meta.url),oe=1<<20,se=[`KHR_texture_basisu`,`EXT_texture_webp`,`EXT_texture_avif`],y={TypeError,RangeError,SyntaxError},ce=e=>{let t=typeof e?.message==`string`?e.message:`Progressive glTF worker sent an invalid message`;return e?.name===`MargoError`&&typeof e.code==`string`?_(e.code,t):new(Object.hasOwn(y,e?.name??``)?y[e.name]:Error)(t)};function le(e,t){let n=e.accessors?.[t?.attributes?.POSITION],r=e=>Array.isArray(e)&&e.length===3&&e.every(Number.isFinite),i=n?.normalized?{5120:127,5121:255,5122:32767,5123:65535}[n.componentType]??1:1,a=e=>r(e)?e.map(e=>i>1?Math.max(-1,e/i):e):[0,0,0],o=a(n?.min),s=a(n?.max),c=/* @__PURE__ */ new Float32Array(480),l=/* @__PURE__ */ new Uint32Array(36);for(let e=0;e<6;e++){let t=e>>1,n=e&1?1:-1,r=(t+1)%3,i=(t+2)%3,a=e*4;for(let e=0;e<4;e++){let l=(a+e)*20;c[l+t]=n>0?s[t]:o[t],c[l+r]=e&1?s[r]:o[r],c[l+i]=e&2?s[i]:o[i],c[l+3]=1,c[l+4+t]=n,c.fill(1,l+16,l+20)}l.set(n>0?[a,a+1,a+3,a,a+3,a+2]:[a,a+3,a+1,a,a+2,a+3],e*6)}return{vertices:c,indices:l,lo:o,hi:s}}function b(_,y,b={}){let{decoders:x={},signal:S,onProgress:ue,frameBudget:de=4,maxJobs:C,clock:fe=()=>performance.now()}=b,pe=u(b.maxAnisotropy),w=new AbortController;if(C!==void 0&&!(C>=1))throw RangeError(`Invalid maxJobs; pass a count, 1 or more`);if(typeof fe!=`function`)throw TypeError(`Invalid clock; pass a function returning milliseconds`);let T=e=>w.abort(e);S?.aborted?T(S.reason):S?.addEventListener(`abort`,()=>T(S.reason),{once:!0});let E={stage:`ready`,bytesLoaded:0,bytesTotal:0,primitives:0,primitivesLoaded:0,images:0,imagesLoaded:0},D=(e=E.stage)=>{E.stage=e,ue?.({...E})},me=t(_),O=g(_),k=()=>O.gpu,he=b.textures===!0?{}:b.textures,A=he&&O.gpu?import(`./texture-stream-Cu_XpyVO.js`).then(({GLTFTextureStream:e})=>me.run(()=>e.attach(_,he,w.signal))):void 0;A?.catch(()=>{});let ge=async()=>{let e=await A,t=await me.run(()=>ne(_,y,{...b,maxAnisotropy:pe,decoders:e?{...x,textureStream:e}:x,signal:w.signal}));return e?.attach(t),t};if(b.fetch||b.ktx2||x.ktx2){let e=ge().then(e=>(D(`complete`),e));return e.catch(()=>{}),{ready:e,complete:e,abort:T,...A?{textures:A}:{}}}let j,_e,ve,ye,be=new Promise((e,t)=>{j=e,_e=t}),xe=new Promise((e,t)=>{ve=e,ye=t});be.catch(()=>{}),xe.catch(()=>{});let M,N,P,F,Se,I=!1,L=[],R=[],z=/* @__PURE__ */ new Set,B=[],Ce=[],V=/* @__PURE__ */ new Map,we=/* @__PURE__ */ new Map,Te=/* @__PURE__ */ new Set,H=/* @__PURE__ */ new Set,Ee=[],U=[],W={},De=0,Oe=``,ke=-1/0,G=!1,K=c,q=0,Ae=0,J,je=()=>{if(!J||Ae)return;let e=J;J=void 0,e()},Me,Ne,Pe={decode:async(e,t)=>(Me??=(async()=>{let e=b.draco??x.draco;if(e)return l(e);let{DracoDecoder:t}=await n({decoders:x}).decoders.decoderModule();return w.signal.throwIfAborted(),Ne=new t})(),(await Me).decode(e,{...t,signal:w.signal}))},Fe=()=>void Me?.then(()=>Ne?.dispose(),()=>{}),Y,X=e=>{if(!I){I=!0,F?.terminate(),Fe(),Y?.release(),w.abort(e);for(let e of H)e.destroy();if(H.clear(),M)M.dispose();else for(let e of L)e?.close?.();A?.then(e=>e.dispose(),()=>{}),_e(e),ye(e)}};w.signal.addEventListener(`abort`,()=>X(w.signal.reason),{once:!0});let Ie=e=>F?F.postMessage({order:e}):Se?.setOrder(e),Le=()=>{O.store.tick(!1);let e=O.camera,t=e.planes,n=e.position,r=t.some(e=>e!==0),i=new Float64Array(B.length);return M.primitives.forEach(e=>{let a=we.get(e),[o,s]=Ce[a],c=e.node.matrix,l=[0,1,2].map(e=>c[e]*(o[0]+s[0])/2+c[4+e]*(o[1]+s[1])/2+c[8+e]*(o[2]+s[2])/2+c[12+e]),u=v(c,0,Math.hypot(s[0]-o[0],s[1]-o[1],s[2]-o[2])/2,l[0],l[1],l[2]),d=1;if(r)for(let e=0;e<24;e+=4)t[e]*l[0]+t[e+1]*l[1]+t[e+2]*l[2]+t[e+3]<-u&&(d=0);let f=u/Math.max(Math.hypot(l[0]-n[0],l[1]-n[1],l[2]-n[2])-u,1e-9);i[a]=Math.max(i[a],d+f/(1+f))}),Y.rank(i),B.map((e,t)=>t).filter(e=>B[e].length&&!Te.has(e)).sort((e,t)=>i[t]-i[e])},Re=e=>{let t=[];try{return r.prototype.setup.call(Object.create(M,{primitives:{value:e},resources:{value:t}}),M.engine),t}catch(e){for(let e of t)e.uniform.destroy();throw e}},ze=t=>{let n=Re(t),r=M.resources,i=new e;t.forEach((e,t)=>{let a=M.primitives.indexOf(e),o=r[a];i.run(()=>o.uniform.destroy()).run(()=>o.wireframe?.index.destroy()),r[a]=n[t]}),i.finish()},Be=e=>{let t=V.get(e),n=t.maps,r=0;return()=>{for(;r<n.length&&!n[r];)r++;if(r<n.length){let i=r++;return Re([{...e,material:{...t,maps:n.map((e,t)=>t===i?e:void 0)}}])[0].uniform.destroy(),!1}return e.material=t,ze([e]),D(`textures`),!0}},Z=(e=!1)=>{for(let t of z){let n=V.get(t).maps.flatMap(e=>{let t=e&&P.textures?.[e.index];return t?[t.source,...se.map(e=>t.extensions?.[e]?.source)].filter(Number.isSafeInteger):[]});(e||n.every(e=>R[e]))&&(z.delete(t),U.push(Be(t)))}},Ve=(e,t,n,r,i)=>{let a=[{data:t,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.STORAGE,at:0,buffer:void 0},{data:n,usage:GPUBufferUsage.INDEX,at:0,buffer:void 0},...r?[{data:r,usage:GPUBufferUsage.VERTEX,at:0,buffer:void 0}]:[]];if(De+=t.byteLength+n.byteLength+(r?.byteLength??0),De>K*4)throw m(`Decoded glTF geometry exceeds byte budget`,K*4);return()=>{let o=a.find(e=>e.at<e.data.byteLength);if(o){if(!o.buffer){if(o.data.byteLength>k().limits.maxBufferSize)throw RangeError(`PBR buffer exceeds device limit; load a smaller model, or reduce its textures and meshes`);H.add(o.buffer=k().createBuffer({size:o.data.byteLength,usage:o.usage|GPUBufferUsage.COPY_DST}))}let e=new Uint8Array(o.data.buffer,o.data.byteOffset,o.data.byteLength),t=Math.min(o.at+oe,e.length);return k().queue.writeBuffer(o.buffer,o.at,e.subarray(o.at,t)),o.at=t,!1}let s=M.gpuCache,c=/* @__PURE__ */ new Set;for(let{data:e,buffer:t}of a)s.set(e,t),H.delete(t);if(i?.index)B[e]=B[e].map(a=>{let o={node:a.node,nodeIndex:a.nodeIndex,vertices:t,indices:n,definition:a.definition,material:a.material,weights:Float32Array.from(a.weights),targetNames:a.targetNames,...r?{uvs:r}:{},part:i};return we.set(o,e),V.set(o,V.get(a)),o.material!==V.get(o)&&z.add(o),M.insertPart(a,o,Re([o])[0]),o}),Z();else{for(let a of B[e])c.add(a.vertices),c.add(a.indices),a.vertices=t,a.indices=n,r&&(a.uvs=r),i&&(a.part=i);ze(B[e]);for(let e of c){let t=s.get(e);t&&M.dropBuffer(k(),t)}}return(!i||i.index===i.count-1)&&(E.primitivesLoaded++,Y.arrived(e)),Ae--,D(`geometry`),je(),!0}},He=e=>()=>{e.buffers.forEach((e,t)=>{N.buffers[t]=e});for(let[t,n]of e.accessors)N.cache.set(t,n);if(e.draco){let t=ee(P);s.set(N,new Map(e.draco.map(([e,n])=>[t[e],n])))}if(Y.release(),x.instancing){W.instancing=x.instancing;let e=/* @__PURE__ */ new Map;for(let t of M.primitives){let n=P.nodes[t.nodeIndex]?.extensions?.EXT_mesh_gpu_instancing;n&&(e.has(t.nodeIndex)||e.set(t.nodeIndex,x.instancing.read(N,n)),t.instances=e.get(t.nodeIndex))}}let t=M.gpuCache,n=new Set(M.primitives.flatMap(e=>e.material.maps.map((e,t)=>e?-1:t)));for(let[e,r]of t)typeof e==`string`&&e.startsWith(`default:`)&&!n.has(+e.slice(8))&&M.dropTexture(k(),e,r);return N[ie]?.commit?.(),I=!0,F?.terminate(),Fe(),D(`complete`),ve(M),!0},Ue=()=>{if(G=!1,!I){try{let e=fe(),t=O.camera,n=String(t.position)+t.target;M&&n!==Oe&&e-ke>200&&(Oe=n,ke=e,Ie(Le()));let r=0;do U.length&&U[0]()&&U.shift(),r++;while(U.length&&!I&&(C===void 0?fe()-e<de:r<C))}catch(e){X(e);return}We()}},We=()=>{if(G||I)return;G=!0;let e=typeof requestAnimationFrame==`function`?requestAnimationFrame(n):0,t=setTimeout(n,e?100:16);function n(){clearTimeout(t),e&&cancelAnimationFrame(e),G&&Ue()}},Ge=(e,t,n)=>{P=e;let i=ee(P),a=new Map(i.map((e,t)=>[e,t]));i.forEach((e,t)=>{let n=le(P,e);Ce[t]=[n.lo,n.hi],e&&typeof e==`object`&&te.set(e,[n])}),x.instancing&&(W.instancing={read:()=>void 0}),t&&(W.materials=t),n&&(W.transmission=n),x.meshopt&&(W.meshopt=x.meshopt);let o=(P.buffers??[]).map(e=>{let t=e?.extensions;return(t?.EXT_meshopt_compression??t?.KHR_meshopt_compression)?.fallback!==!0&&Number.isSafeInteger(e?.byteLength)&&e.byteLength>0?e.byteLength:0});if(o.reduce((e,t)=>e+t,0)>K)throw m(`glTF buffers exceed byte budget`,K);N=new p(P,o.map(e=>new Uint8Array(e)),void 0,W,K,b.maxNodes),f.set(N,pe),N.partVertices=q,Ee.push(N.prepareMeshopt().catch(X)),N[ie]={},L=Array.from(P.images??[],()=>void 0),R=L.map(()=>!1),E.images=L.length,M=new r(_,N,L),B=i.map(()=>[]);for(let e of M.primitives){let t=a.get(e.definition);B[t].push(e),we.set(e,t)}E.primitives=B.filter(e=>e.length).length;let s=/* @__PURE__ */ new Map;for(let e of M.primitives){let t=e.material;V.set(e,t),t.maps.some(Boolean)&&(s.has(t)||s.set(t,Object.defineProperties(Object.assign(Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t)),{maps:t.maps.map(()=>void 0)}),{side:Object.getOwnPropertyDescriptor(t,`side`),wireframe:{enumerable:!0,get:()=>t.wireframe,set:e=>{t.wireframe=e}}})),e.material=s.get(t),z.add(e))}O.use(M),Y=re(M,O),M.onDispose(()=>T(new DOMException(`Model disposed while loading`,`AbortError`))),A?.then(e=>e.attach(M),X),D(`ready`),j(M),We()},Q,$=e=>{if(Q)Q.push(e);else if(I)e.type===`image`&&e.image&&`close`in e.image&&e.image.close();else try{if(e.type===`fallback`)F?.terminate(),F=void 0,ge().then(e=>{I?e.dispose():(M=e,I=!0,D(`complete`),j(e),ve(e))},X);else if(e.type===`doc`)Q=[],a(e.doc,x).then(t=>i(e.doc,t)).then(t=>{I||me.run(()=>Ge(e.doc,t.materials,t.transmission))}).catch(X).then(()=>{let e=Q;Q=void 0,e.forEach($)});else if(e.type===`geometry`){if(e.error)throw ce(e.error);Te.add(e.key),U.push(Ve(e.key,e.vertices,e.indices,e.uvs,e.part)),Ae++}else if(e.type===`image`){if(!Number.isInteger(e.index)||e.index<0||e.index>=L.length)throw RangeError(`Progressive glTF worker sent an invalid image index; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let{index:t,source:n}=e;n?Ee.push(A.then(e=>e.open(n)).then(e=>{I?e.close():(L[t]=e,R[t]=!0,E.imagesLoaded++,Z())}).catch(X)):(L[t]=e.image,R[t]=!0,e.image&&E.imagesLoaded++,Z())}else if(e.type===`bytes`)E.bytesLoaded=e.loaded,E.bytesTotal=e.total,M&&D();else if(e.type===`draco`){let{id:t}=e,n=F;Pe.decode(e.data,e.options).then(e=>{try{n?.postMessage({draco:t,result:e})}catch(e){X(e)}},e=>n?.postMessage({draco:t,error:{name:e?.name,message:e?.message,code:e?.code}}))}else if(e.type===`done`)Promise.all(Ee).then(()=>{I||(J=()=>{Z(!0),U.push(He(e))},je())});else throw ce(e.error)}catch(e){X(e)}};try{S?.throwIfAborted(),K=d(b.maxDownloadBytes),q=o(b.maxPartVertices);let e=new URL(y,globalThis.location?.href).href;h()&&!x.meshopt?(F=new Worker(ae(),{name:`margoengine-progressive`}),F.onmessage=({data:e})=>$(e&&typeof e==`object`?e:{type:`error`,error:{name:`TypeError`,message:`Progressive glTF worker sent an invalid message`}}),F.onerror=e=>{e.preventDefault?.(),X(/* @__PURE__ */ Error(`Progressive glTF worker failed: `+(e.message||`unknown error`)))},F.onmessageerror=()=>X(/* @__PURE__ */ Error(`Progressive glTF worker message could not be deserialized`)),F.postMessage({url:e,maxDownloadBytes:K,maxNodes:b.maxNodes,allowedURLs:b.allowedURLs,textures:!!A,maxPartVertices:q})):import(`./stream-CrfNNCRd.js`).then(({GLTFStream:t})=>{I||(Se=new t(new URL(e),$,w.signal,K,b.maxNodes,b.allowedURLs,!!A,q,{draco:Pe,...x.meshopt?{meshopt:x.meshopt}:{}})).run()},X)}catch(e){X(e)}return{ready:be,complete:xe,abort:T,...A?{textures:A}:{}}}export{b as loadGLTFProgressive};
package/dist/quantized.js CHANGED
@@ -1 +1 @@
1
- import{r as e,t}from"./accessor-nVsu_f1L.js";var n=5120,r=5121,i=5122,a=5123,o={handles:[`KHR_mesh_quantization`],attribute(o,s,c){let{componentType:l,normalized:u}=t(o.doc.accessors,c,`accessor`);return(s===`POSITION`?l===n||l===r||l===i||l===a:(l===n||l===i)&&u===!0)?e(o,c,3,e=>e.type===`VEC3`):void 0}};export{o as quantized};
1
+ import{r as e,t}from"./accessor-CU_1uSZ1.js";var n=5120,r=5121,i=5122,a=5123,o={handles:[`KHR_mesh_quantization`],attribute(o,s,c){let{componentType:l,normalized:u}=t(o.doc.accessors,c,`accessor`);return(s===`POSITION`?l===n||l===r||l===i||l===a:(l===n||l===i)&&u===!0)?e(o,c,3,e=>e.type===`VEC3`):void 0}};export{o as quantized};
package/dist/report.js CHANGED
@@ -1 +1 @@
1
- import{t as e}from"./version-BmU1nesQ.js";import{t}from"./decoder-default-CxLH8Vz0.js";import{c as n,t as r}from"./asset-1b8ejkZX.js";var i=/* @__PURE__ */ new Set([`KHR_mesh_quantization`,`KHR_texture_transform`,`KHR_materials_emissive_strength`,`KHR_materials_unlit`,`KHR_lights_punctual`,`KHR_node_visibility`,`KHR_materials_clearcoat`,`KHR_materials_transmission`,`KHR_materials_ior`,`KHR_materials_dispersion`,`KHR_materials_volume`,`KHR_materials_sheen`,`KHR_materials_specular`,`KHR_materials_variants`,`KHR_materials_iridescence`,`KHR_materials_anisotropy`,`KHR_materials_diffuse_roughness`,`KHR_texture_basisu`,`KHR_draco_mesh_compression`,`EXT_meshopt_compression`,`KHR_meshopt_compression`,`EXT_texture_webp`,`EXT_texture_avif`,`EXT_mesh_gpu_instancing`]),a=()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function o(e,t){let n=Array(16);for(let r=0;r<4;r++)for(let i=0;i<4;i++)n[r*4+i]=e[i]*t[r*4]+e[4+i]*t[r*4+1]+e[8+i]*t[r*4+2]+e[12+i]*t[r*4+3];return n}function s(e,t,n){let[r,i,a,o]=t;return[(1-2*(i*i+a*a))*n[0],2*(r*i+a*o)*n[0],2*(r*a-i*o)*n[0],0,2*(r*i-a*o)*n[1],(1-2*(r*r+a*a))*n[1],2*(i*a+r*o)*n[1],0,2*(r*a+i*o)*n[2],2*(i*a-r*o)*n[2],(1-2*(r*r+i*i))*n[2],0,e[0],e[1],e[2],1]}var c=e=>e.matrix?.slice()??s(e.translation??[0,0,0],e.rotation??[0,0,0,1],e.scale??[1,1,1]);function l(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.length>=24&&t.getUint32(0)===2303741511)return{format:`png`,width:t.getUint32(16),height:t.getUint32(20)};if(e.length>=4&&e[0]===255&&e[1]===216)for(let n=2;n+9<e.length;){if(e[n]!==255)return;let r=e[n+1];if(r===255){n++;continue}if(r===216||r===1||r>=208&&r<=215){n+=2;continue}let i=t.getUint16(n+2);if(r>=192&&r<=207&&r!==196&&r!==200&&r!==204)return{format:`jpeg`,width:t.getUint16(n+7),height:t.getUint16(n+5)};n+=2+i}else{if(e.length>=30&&t.getUint32(0)===1380533830&&t.getUint32(8)===1464156752){let n=String.fromCharCode(e[12],e[13],e[14],e[15]);if(n===`VP8 `)return{format:`webp`,width:t.getUint16(26,!0)&16383,height:t.getUint16(28,!0)&16383};if(n===`VP8L`){let e=t.getUint32(21,!0);return{format:`webp`,width:(e&16383)+1,height:(e>>>14&16383)+1}}return n===`VP8X`?{format:`webp`,width:1+(e[24]|e[25]<<8|e[26]<<16),height:1+(e[27]|e[28]<<8|e[29]<<16)}:void 0}if(e.length>=28&&t.getUint32(0)===2873840728&&t.getUint32(4)===540160010)return{format:`ktx2`,width:t.getUint32(20,!0),height:Math.max(1,t.getUint32(24,!0))}}}function u(e,t){let n=e.doc,r=n.nodes??[],i=n.scenes?.[n.scene??0],l=new Set(r.flatMap(e=>e.children??[])),u=i?i.nodes??[]:r.map((e,t)=>t).filter(e=>!l.has(e)),d=[],f=/* @__PURE__ */ new Set,p=(n,i)=>{let a=r[n];if(!a)return void t.push({code:`json`,detail:`the scene names node ${n}, which does not exist`});if(f.has(n))return void t.push({code:`json`,detail:`node ${n} is its own ancestor (a cycle)`});f.add(n);let l=o(i,c(a)),u=[l],m=a.extensions?.EXT_mesh_gpu_instancing?.attributes;if(m&&a.mesh!==void 0)try{let t=m.TRANSLATION===void 0?void 0:e.accessor(m.TRANSLATION),n=m.ROTATION===void 0?void 0:e.accessor(m.ROTATION),r=m.SCALE===void 0?void 0:e.accessor(m.SCALE),i=t?t.length/3:n?n.length/4:r?r.length/3:0;u=[];for(let e=0;e<i;e++)u.push(o(l,s(t?[t[e*3],t[e*3+1],t[e*3+2]]:[0,0,0],n?[n[e*4],n[e*4+1],n[e*4+2],n[e*4+3]]:[0,0,0,1],r?[r[e*3],r[e*3+1],r[e*3+2]]:[1,1,1])))}catch(e){t.push({code:`accessor`,where:a.name,detail:`node ${a.name??n} instancing: ${e.message}`})}u.some(e=>e.some(e=>!Number.isFinite(e)))&&t.push({code:`not-finite`,where:a.name,detail:`node ${a.name??n} has a transform that is not finite`}),d.push({index:n,node:a,matrices:u});for(let e of a.children??[])p(e,l);f.delete(n)};for(let e of u)p(e,a());return d}function d(e,t,n){if(n.length=0,e===4)for(let e=0;e+2<t.length;e+=3)n.push(t[e],t[e+1],t[e+2]);else if(e===5)for(let e=0;e+2<t.length;e++)e%2?n.push(t[e+1],t[e],t[e+2]):n.push(t[e],t[e+1],t[e+2]);else for(let e=1;e+1<t.length;e++)n.push(t[0],t[e],t[e+1])}var f=(e,t,n,r,i)=>{n<e[0]&&(e[0]=n),r<e[1]&&(e[1]=r),i<e[2]&&(e[2]=i),n>t[0]&&(t[0]=n),r>t[1]&&(t[1]=r),i>t[2]&&(t[2]=i)},p=(e,t)=>e.every(Number.isFinite)&&t.every(Number.isFinite)?{min:[e[0],e[1],e[2]],max:[t[0],t[1],t[2]],size:[t[0]-e[0],t[1]-e[1],t[2]-e[2]],centre:[(t[0]+e[0])/2,(t[1]+e[1])/2,(t[2]+e[2])/2]}:null,m=e=>[e.pbrMetallicRoughness?.baseColorTexture,e.pbrMetallicRoughness?.metallicRoughnessTexture,e.normalTexture,e.occlusionTexture,e.emissiveTexture].filter(e=>!!e);async function h(a,o={}){let s=[],c=o.zeroArea??1e-9,h={triangles:0,vertices:0,primitives:0,meshes:0,nodes:0,materials:0,textures:0,images:0,texturePixels:0,largestTexture:0,rgbaBytes:0,zeroArea:0,pointsAndLines:0},v={ok:!1,counts:h,bounds:null,extensions:{used:[],required:[],unsupported:[]},images:[],zeroAreaByNode:[],problems:s},y=()=>(v.ok=s.length===0,v);o.signal?.throwIfAborted();let b,x;try{if({doc:b,binary:x}=n(a),!b||typeof b!=`object`||!e(b.asset))throw TypeError(`Expected glTF 2.0`)}catch(e){return s.push({code:`not-gltf`,detail:e.message}),y()}let S=Array.isArray(b.extensionsUsed)?[...b.extensionsUsed]:[],C=Array.isArray(b.extensionsRequired)?[...b.extensionsRequired]:[],w=C.filter(e=>!i.has(e)&&!o.supported?.includes(e));v.extensions={used:S,required:C,unsupported:w};for(let e of w)s.push({code:`extension`,detail:`${e} is required and Margo's loaders do not read it`});h.meshes=b.meshes?.length??0,h.nodes=b.nodes?.length??0,h.materials=b.materials?.length??0,h.textures=b.textures?.length??0,h.images=b.images?.length??0;let T=(b.buffers??[]).some(e=>e?.uri!==void 0&&!String(e.uri).startsWith(`data:`));T&&s.push({code:`external`,detail:`a buffer points at a file outside these bytes; pass a GLB or embed the buffers`});let E;try{let e={...b,extensionsRequired:C.filter(e=>!w.includes(e))};E=new r(e,T?[]:x?[x]:[],x,t(o).decoders)}catch(e){return s.push({code:`json`,detail:e.message}),y()}let D=!0;try{await E.decode(o.signal)}catch(e){o.signal?.throwIfAborted(),D=!1,s.push({code:`decode`,detail:`compressed geometry could not be decoded here: ${e.message}`})}let O=[];for(let[e,t]of(b.images??[]).entries()){let n;try{if(t.bufferView!==void 0)n=E.view(t.bufferView);else if(typeof t.uri==`string`&&t.uri.startsWith(`data:`)){let e=t.uri.indexOf(`,`);n=Uint8Array.from(atob(t.uri.slice(e+1)),e=>e.charCodeAt(0))}}catch(n){s.push({code:`json`,detail:`image ${t.name??e}: ${n.message}`})}if(O.push(n),!n){v.images.push({index:e,name:t.name,format:`external`,width:0,height:0}),t.uri!==void 0&&s.push({code:`external`,detail:`image ${t.name??e} points at ${String(t.uri).slice(0,80)}, outside these bytes`});continue}let r=l(n);r?(v.images.push({index:e,name:t.name,...r}),h.texturePixels+=r.width*r.height,h.largestTexture=Math.max(h.largestTexture,r.width,r.height)):(v.images.push({index:e,name:t.name,format:`unknown`,width:0,height:0}),s.push({code:`image-format`,detail:`image ${t.name??e} is not PNG, JPEG, WebP or KTX2`}))}h.rgbaBytes=h.texturePixels*4;let k=[1/0,1/0,1/0],A=[-1/0,-1/0,-1/0],j={primitives:0,samples:0,min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]},M=[],N=[],P=/* @__PURE__ */ new Map,F=e=>{let t=P.get(e);return t||P.set(e,t=E.accessor(e,void 0,!1)),t},I=/* @__PURE__ */ new Map;for(let{index:e,node:t,matrices:n}of u(E,s)){if(o.signal?.throwIfAborted(),t.mesh===void 0)continue;let r=b.meshes?.[t.mesh],i=t.name??`node with mesh ${t.mesh}`;if(!r)s.push({code:`json`,where:t.name,detail:`${i} names mesh ${t.mesh}, which does not exist`});else for(let[a,l]of(r.primitives??[]).entries()){let r=`${i} primitive ${a}`,u=l.mode??4,p=l.attributes??{},_=n.length;if(h.primitives+=_,u<4){h.pointsAndLines+=_;continue}let v=l.material===void 0?void 0:b.materials?.[l.material];l.material===void 0?s.push({code:`no-material`,where:i,detail:`${r} has no material (drawn with the default)`}):v||s.push({code:`json`,where:i,detail:`${r} names material ${l.material}, which does not exist`}),p.NORMAL===void 0&&!v?.extensions?.KHR_materials_unlit&&s.push({code:`no-normals`,where:i,detail:`${r} has no NORMAL (flat normals are made at load)`});for(let e of v?m(v):[])if(p[`TEXCOORD_${e.texCoord??0}`]===void 0){s.push({code:`no-uvs`,where:i,detail:`${r} is textured and has no TEXCOORD_${e.texCoord??0}`});break}if(p.POSITION===void 0){s.push({code:`accessor`,where:i,detail:`${r} has no POSITION`});continue}if(l.extensions?.KHR_draco_mesh_compression&&!D){let e=b.accessors?.[p.POSITION],t=(l.indices===void 0?void 0:b.accessors?.[l.indices])?.count??e?.count??0;h.vertices+=(e?.count??0)*_,h.triangles+=(u===4?Math.floor(t/3):Math.max(0,t-2))*_;let r=e?.min,i=e?.max;if(r&&i)for(let e of n)for(let t=0;t<8;t++){let n=t&1?i[0]:r[0],a=t&2?i[1]:r[1],o=t&4?i[2]:r[2];f(k,A,e[0]*n+e[4]*a+e[8]*o+e[12],e[1]*n+e[5]*a+e[9]*o+e[13],e[2]*n+e[6]*a+e[10]*o+e[14])}continue}let y,x;try{y=F(p.POSITION);for(let[e,t]of Object.entries(p))F(t).some(e=>!Number.isFinite(e))&&s.push({code:`not-finite`,where:i,detail:`${r} ${e} holds NaN or infinity`});let e=y.length/3;if(x=l.indices===void 0?Uint32Array.from({length:e},(e,t)=>t):F(l.indices),Array.prototype.some.call(x,t=>t>=e||t<0)){s.push({code:`index-range`,where:i,detail:`${r} has an index past its ${e} vertices`});continue}}catch(e){s.push({code:`accessor`,where:i,detail:`${r}: ${e.message}`});continue}d(u,x,N);let S=y.length/3,C=new Uint8Array(S);h.vertices+=S*_,h.triangles+=N.length/3*_;for(let e of N)C[e]=1;for(let r of n){let n=0;for(let e=0;e<N.length;e+=3){let t=N[e]*3,i=N[e+1]*3,a=N[e+2]*3,o=r[0]*y[t]+r[4]*y[t+1]+r[8]*y[t+2],s=r[1]*y[t]+r[5]*y[t+1]+r[9]*y[t+2],l=r[2]*y[t]+r[6]*y[t+1]+r[10]*y[t+2],u=r[0]*y[i]+r[4]*y[i+1]+r[8]*y[i+2]-o,d=r[1]*y[i]+r[5]*y[i+1]+r[9]*y[i+2]-s,f=r[2]*y[i]+r[6]*y[i+1]+r[10]*y[i+2]-l,p=r[0]*y[a]+r[4]*y[a+1]+r[8]*y[a+2]-o,m=r[1]*y[a]+r[5]*y[a+1]+r[9]*y[a+2]-s,h=r[2]*y[a]+r[6]*y[a+1]+r[10]*y[a+2]-l;Math.hypot(d*h-f*m,f*p-u*h,u*m-d*p)/2<c&&n++}if(h.zeroArea+=n,n){let r=I.get(e)??{node:e,mesh:t.mesh,where:i,zeroArea:0,triangles:0};r.zeroArea+=n,r.triangles+=N.length/3,I.set(e,r)}for(let e=0;e<S;e++)if(C[e]){let t=y[e*3],n=y[e*3+1],i=y[e*3+2];f(k,A,r[0]*t+r[4]*n+r[8]*i+r[12],r[1]*t+r[5]*n+r[9]*i+r[13],r[2]*t+r[6]*n+r[10]*i+r[14])}}let w=g(y,N);w!==void 0&&w<0&&s.push({code:`inside-out`,where:i,detail:`${r} is closed and its triangles face inward (signed volume ${w.toPrecision(3)})`});let T=v?.pbrMetallicRoughness?.baseColorTexture,E=v?.alphaMode??`OPAQUE`;if(o.alpha&&T&&(E===`MASK`||E===`BLEND`)&&p[`TEXCOORD_${T.texCoord??0}`]!==void 0)try{M.push({positions:y,uvs:F(p[`TEXCOORD_${T.texCoord??0}`]),tris:N.slice(),matrices:n,texture:T.index,cutoff:(E===`MASK`?v?.alphaCutoff??.5:o.blendCutoff??.5)/(v?.pbrMetallicRoughness?.baseColorFactor?.[3]??1)})}catch(e){s.push({code:`accessor`,where:i,detail:`${r}: ${e.message}`})}}}if(v.bounds=p(k,A),h.triangles===0&&h.pointsAndLines===0&&s.push({code:`empty`,detail:`the default scene draws nothing`}),v.zeroAreaByNode=[...I.values()],h.zeroArea&&s.push({code:`zero-area`,detail:`${h.zeroArea} of ${h.triangles} drawn triangles have zero area`}),o.alpha){let{decodeImage:e}=await import(`@margoengine/decoders/image`),t=/* @__PURE__ */ new Map,n=o.maxSamples??4194304,r=M.reduce((e,t)=>e+t.tris.length/3,0);for(let i of M){let a=b.textures?.[i.texture]?.source;if(a===void 0||!O[a])continue;t.has(a)||t.set(a,await e(O[a],{signal:o.signal}).catch(e=>(s.push({code:`image-format`,detail:`image ${a} could not be decoded for alpha: ${e.message}`}),null)));let c=t.get(a);c&&(j.primitives++,j.samples+=_(i,c,Math.max(1,Math.floor(n/Math.max(1,r))),j.min,j.max))}v.cutouts={primitives:j.primitives,bounds:p(j.min,j.max),samples:j.samples}}return y()}function g(e,t){let n=/* @__PURE__ */ new Map,r=new Int32Array(e.length/3);for(let t=0;t<r.length;t++){let i=`${Math.round(e[t*3]*1e5)},${Math.round(e[t*3+1]*1e5)},${Math.round(e[t*3+2]*1e5)}`,a=n.get(i);a===void 0&&n.set(i,a=n.size),r[t]=a}let i=/* @__PURE__ */ new Map,a=n.size,o=0;for(let n=0;n<t.length;n+=3){let s=t[n]*3,c=t[n+1]*3,l=t[n+2]*3,u=e;o+=(u[s]*(u[c+1]*u[l+2]-u[c+2]*u[l+1])-u[s+1]*(u[c]*u[l+2]-u[c+2]*u[l])+u[s+2]*(u[c]*u[l+1]-u[c+1]*u[l]))/6;for(let e=0;e<3;e++){let o=r[t[n+e]],s=r[t[n+(e+1)%3]];if(o===s)continue;let c=Math.min(o,s)*a+Math.max(o,s);i.set(c,(i.get(c)??0)+1)}}if(i.size){for(let e of i.values())if(e!==2)return;return o}}function _(e,t,n,r,i){let{positions:a,uvs:o,tris:s}=e,{width:c,height:l,data:u}=t,d=Math.min(1,Math.max(0,e.cutoff))*255,p=0;for(let t=0;t<s.length;t+=3){let[m,h,g]=[s[t],s[t+1],s[t+2]],_=o[m*2]*c,v=o[m*2+1]*l,y=o[h*2]*c,b=o[h*2+1]*l,x=o[g*2]*c,S=o[g*2+1]*l,C=Math.abs((y-_)*(S-v)-(x-_)*(b-v))/2,w=Math.max(1,Math.min(Math.ceil(Math.sqrt(2*C)),Math.floor(Math.sqrt(2*n))));for(let t=0;t<=w;t++)for(let n=0;n<=w-t;n++){let o=t/w,s=n/w,C=1-o-s,T=C*_+o*y+s*x,E=C*v+o*b+s*S,D=(Math.floor(T)%c+c)%c,O=(Math.floor(E)%l+l)%l;if(p++,u[(O*c+D)*4+3]<d)continue;let k=C*a[m*3]+o*a[h*3]+s*a[g*3],A=C*a[m*3+1]+o*a[h*3+1]+s*a[g*3+1],j=C*a[m*3+2]+o*a[h*3+2]+s*a[g*3+2];for(let t of e.matrices)f(r,i,t[0]*k+t[4]*A+t[8]*j+t[12],t[1]*k+t[5]*A+t[9]*j+t[13],t[2]*k+t[6]*A+t[10]*j+t[14])}}return p}export{l as imageHeader,h as reportGLTF};
1
+ import{t as e}from"./version-B6NE5cJf.js";import{t}from"./decoder-default-CxLH8Vz0.js";import{l as n,t as r}from"./asset-DN3ocEdY.js";var i=/* @__PURE__ */ new Set([`KHR_mesh_quantization`,`KHR_texture_transform`,`KHR_materials_emissive_strength`,`KHR_materials_unlit`,`KHR_lights_punctual`,`KHR_node_visibility`,`KHR_materials_clearcoat`,`KHR_materials_transmission`,`KHR_materials_ior`,`KHR_materials_dispersion`,`KHR_materials_volume`,`KHR_materials_sheen`,`KHR_materials_specular`,`KHR_materials_variants`,`KHR_materials_iridescence`,`KHR_materials_anisotropy`,`KHR_materials_diffuse_roughness`,`KHR_texture_basisu`,`KHR_draco_mesh_compression`,`EXT_meshopt_compression`,`KHR_meshopt_compression`,`EXT_texture_webp`,`EXT_texture_avif`,`EXT_mesh_gpu_instancing`]),a=()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function o(e,t){let n=Array(16);for(let r=0;r<4;r++)for(let i=0;i<4;i++)n[r*4+i]=e[i]*t[r*4]+e[4+i]*t[r*4+1]+e[8+i]*t[r*4+2]+e[12+i]*t[r*4+3];return n}function s(e,t,n){let[r,i,a,o]=t;return[(1-2*(i*i+a*a))*n[0],2*(r*i+a*o)*n[0],2*(r*a-i*o)*n[0],0,2*(r*i-a*o)*n[1],(1-2*(r*r+a*a))*n[1],2*(i*a+r*o)*n[1],0,2*(r*a+i*o)*n[2],2*(i*a-r*o)*n[2],(1-2*(r*r+i*i))*n[2],0,e[0],e[1],e[2],1]}var c=e=>e.matrix?.slice()??s(e.translation??[0,0,0],e.rotation??[0,0,0,1],e.scale??[1,1,1]);function l(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.length>=24&&t.getUint32(0)===2303741511)return{format:`png`,width:t.getUint32(16),height:t.getUint32(20)};if(e.length>=4&&e[0]===255&&e[1]===216)for(let n=2;n+9<e.length;){if(e[n]!==255)return;let r=e[n+1];if(r===255){n++;continue}if(r===216||r===1||r>=208&&r<=215){n+=2;continue}let i=t.getUint16(n+2);if(r>=192&&r<=207&&r!==196&&r!==200&&r!==204)return{format:`jpeg`,width:t.getUint16(n+7),height:t.getUint16(n+5)};n+=2+i}else{if(e.length>=30&&t.getUint32(0)===1380533830&&t.getUint32(8)===1464156752){let n=String.fromCharCode(e[12],e[13],e[14],e[15]);if(n===`VP8 `)return{format:`webp`,width:t.getUint16(26,!0)&16383,height:t.getUint16(28,!0)&16383};if(n===`VP8L`){let e=t.getUint32(21,!0);return{format:`webp`,width:(e&16383)+1,height:(e>>>14&16383)+1}}return n===`VP8X`?{format:`webp`,width:1+(e[24]|e[25]<<8|e[26]<<16),height:1+(e[27]|e[28]<<8|e[29]<<16)}:void 0}if(e.length>=28&&t.getUint32(0)===2873840728&&t.getUint32(4)===540160010)return{format:`ktx2`,width:t.getUint32(20,!0),height:Math.max(1,t.getUint32(24,!0))}}}function u(e,t){let n=e.doc,r=n.nodes??[],i=n.scenes?.[n.scene??0],l=new Set(r.flatMap(e=>e.children??[])),u=i?i.nodes??[]:r.map((e,t)=>t).filter(e=>!l.has(e)),d=[],f=/* @__PURE__ */ new Set,p=(n,i)=>{let a=r[n];if(!a)return void t.push({code:`json`,detail:`the scene names node ${n}, which does not exist`});if(f.has(n))return void t.push({code:`json`,detail:`node ${n} is its own ancestor (a cycle)`});f.add(n);let l=o(i,c(a)),u=[l],m=a.extensions?.EXT_mesh_gpu_instancing?.attributes;if(m&&a.mesh!==void 0)try{let t=m.TRANSLATION===void 0?void 0:e.accessor(m.TRANSLATION),n=m.ROTATION===void 0?void 0:e.accessor(m.ROTATION),r=m.SCALE===void 0?void 0:e.accessor(m.SCALE),i=t?t.length/3:n?n.length/4:r?r.length/3:0;u=[];for(let e=0;e<i;e++)u.push(o(l,s(t?[t[e*3],t[e*3+1],t[e*3+2]]:[0,0,0],n?[n[e*4],n[e*4+1],n[e*4+2],n[e*4+3]]:[0,0,0,1],r?[r[e*3],r[e*3+1],r[e*3+2]]:[1,1,1])))}catch(e){t.push({code:`accessor`,where:a.name,detail:`node ${a.name??n} instancing: ${e.message}`})}u.some(e=>e.some(e=>!Number.isFinite(e)))&&t.push({code:`not-finite`,where:a.name,detail:`node ${a.name??n} has a transform that is not finite`}),d.push({index:n,node:a,matrices:u});for(let e of a.children??[])p(e,l);f.delete(n)};for(let e of u)p(e,a());return d}function d(e,t,n){if(n.length=0,e===4)for(let e=0;e+2<t.length;e+=3)n.push(t[e],t[e+1],t[e+2]);else if(e===5)for(let e=0;e+2<t.length;e++)e%2?n.push(t[e+1],t[e],t[e+2]):n.push(t[e],t[e+1],t[e+2]);else for(let e=1;e+1<t.length;e++)n.push(t[0],t[e],t[e+1])}var f=(e,t,n,r,i)=>{n<e[0]&&(e[0]=n),r<e[1]&&(e[1]=r),i<e[2]&&(e[2]=i),n>t[0]&&(t[0]=n),r>t[1]&&(t[1]=r),i>t[2]&&(t[2]=i)},p=(e,t)=>e.every(Number.isFinite)&&t.every(Number.isFinite)?{min:[e[0],e[1],e[2]],max:[t[0],t[1],t[2]],size:[t[0]-e[0],t[1]-e[1],t[2]-e[2]],centre:[(t[0]+e[0])/2,(t[1]+e[1])/2,(t[2]+e[2])/2]}:null,m=e=>[e.pbrMetallicRoughness?.baseColorTexture,e.pbrMetallicRoughness?.metallicRoughnessTexture,e.normalTexture,e.occlusionTexture,e.emissiveTexture].filter(e=>!!e);async function h(a,o={}){let s=[],c=o.zeroArea??1e-9,h={triangles:0,vertices:0,primitives:0,meshes:0,nodes:0,materials:0,textures:0,images:0,texturePixels:0,largestTexture:0,rgbaBytes:0,zeroArea:0,pointsAndLines:0},v={ok:!1,counts:h,bounds:null,extensions:{used:[],required:[],unsupported:[]},images:[],zeroAreaByNode:[],problems:s},y=()=>(v.ok=s.length===0,v);o.signal?.throwIfAborted();let b,x;try{if({doc:b,binary:x}=n(a),!b||typeof b!=`object`||!e(b.asset))throw TypeError(`Expected glTF 2.0`)}catch(e){return s.push({code:`not-gltf`,detail:e.message}),y()}let S=Array.isArray(b.extensionsUsed)?[...b.extensionsUsed]:[],C=Array.isArray(b.extensionsRequired)?[...b.extensionsRequired]:[],w=C.filter(e=>!i.has(e)&&!o.supported?.includes(e));v.extensions={used:S,required:C,unsupported:w};for(let e of w)s.push({code:`extension`,detail:`${e} is required and Margo's loaders do not read it`});h.meshes=b.meshes?.length??0,h.nodes=b.nodes?.length??0,h.materials=b.materials?.length??0,h.textures=b.textures?.length??0,h.images=b.images?.length??0;let T=(b.buffers??[]).some(e=>e?.uri!==void 0&&!String(e.uri).startsWith(`data:`));T&&s.push({code:`external`,detail:`a buffer points at a file outside these bytes; pass a GLB or embed the buffers`});let E;try{let e={...b,extensionsRequired:C.filter(e=>!w.includes(e))};E=new r(e,T?[]:x?[x]:[],x,t(o).decoders)}catch(e){return s.push({code:`json`,detail:e.message}),y()}let D=!0;try{await E.decode(o.signal)}catch(e){o.signal?.throwIfAborted(),D=!1,s.push({code:`decode`,detail:`compressed geometry could not be decoded here: ${e.message}`})}let O=[];for(let[e,t]of(b.images??[]).entries()){let n;try{if(t.bufferView!==void 0)n=E.view(t.bufferView);else if(typeof t.uri==`string`&&t.uri.startsWith(`data:`)){let e=t.uri.indexOf(`,`);n=Uint8Array.from(atob(t.uri.slice(e+1)),e=>e.charCodeAt(0))}}catch(n){s.push({code:`json`,detail:`image ${t.name??e}: ${n.message}`})}if(O.push(n),!n){v.images.push({index:e,name:t.name,format:`external`,width:0,height:0}),t.uri!==void 0&&s.push({code:`external`,detail:`image ${t.name??e} points at ${String(t.uri).slice(0,80)}, outside these bytes`});continue}let r=l(n);r?(v.images.push({index:e,name:t.name,...r}),h.texturePixels+=r.width*r.height,h.largestTexture=Math.max(h.largestTexture,r.width,r.height)):(v.images.push({index:e,name:t.name,format:`unknown`,width:0,height:0}),s.push({code:`image-format`,detail:`image ${t.name??e} is not PNG, JPEG, WebP or KTX2`}))}h.rgbaBytes=h.texturePixels*4;let k=[1/0,1/0,1/0],A=[-1/0,-1/0,-1/0],j={primitives:0,samples:0,min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]},M=[],N=[],P=/* @__PURE__ */ new Map,F=e=>{let t=P.get(e);return t||P.set(e,t=E.accessor(e,void 0,!1)),t},I=/* @__PURE__ */ new Map;for(let{index:e,node:t,matrices:n}of u(E,s)){if(o.signal?.throwIfAborted(),t.mesh===void 0)continue;let r=b.meshes?.[t.mesh],i=t.name??`node with mesh ${t.mesh}`;if(!r)s.push({code:`json`,where:t.name,detail:`${i} names mesh ${t.mesh}, which does not exist`});else for(let[a,l]of(r.primitives??[]).entries()){let r=`${i} primitive ${a}`,u=l.mode??4,p=l.attributes??{},_=n.length;if(h.primitives+=_,u<4){h.pointsAndLines+=_;continue}let v=l.material===void 0?void 0:b.materials?.[l.material];l.material===void 0?s.push({code:`no-material`,where:i,detail:`${r} has no material (drawn with the default)`}):v||s.push({code:`json`,where:i,detail:`${r} names material ${l.material}, which does not exist`}),p.NORMAL===void 0&&!v?.extensions?.KHR_materials_unlit&&s.push({code:`no-normals`,where:i,detail:`${r} has no NORMAL (flat normals are made at load)`});for(let e of v?m(v):[])if(p[`TEXCOORD_${e.texCoord??0}`]===void 0){s.push({code:`no-uvs`,where:i,detail:`${r} is textured and has no TEXCOORD_${e.texCoord??0}`});break}if(p.POSITION===void 0){s.push({code:`accessor`,where:i,detail:`${r} has no POSITION`});continue}if(l.extensions?.KHR_draco_mesh_compression&&!D){let e=b.accessors?.[p.POSITION],t=(l.indices===void 0?void 0:b.accessors?.[l.indices])?.count??e?.count??0;h.vertices+=(e?.count??0)*_,h.triangles+=(u===4?Math.floor(t/3):Math.max(0,t-2))*_;let r=e?.min,i=e?.max;if(r&&i)for(let e of n)for(let t=0;t<8;t++){let n=t&1?i[0]:r[0],a=t&2?i[1]:r[1],o=t&4?i[2]:r[2];f(k,A,e[0]*n+e[4]*a+e[8]*o+e[12],e[1]*n+e[5]*a+e[9]*o+e[13],e[2]*n+e[6]*a+e[10]*o+e[14])}continue}let y,x;try{y=F(p.POSITION);for(let[e,t]of Object.entries(p))F(t).some(e=>!Number.isFinite(e))&&s.push({code:`not-finite`,where:i,detail:`${r} ${e} holds NaN or infinity`});let e=y.length/3;if(x=l.indices===void 0?Uint32Array.from({length:e},(e,t)=>t):F(l.indices),Array.prototype.some.call(x,t=>t>=e||t<0)){s.push({code:`index-range`,where:i,detail:`${r} has an index past its ${e} vertices`});continue}}catch(e){s.push({code:`accessor`,where:i,detail:`${r}: ${e.message}`});continue}d(u,x,N);let S=y.length/3,C=new Uint8Array(S);h.vertices+=S*_,h.triangles+=N.length/3*_;for(let e of N)C[e]=1;for(let r of n){let n=0;for(let e=0;e<N.length;e+=3){let t=N[e]*3,i=N[e+1]*3,a=N[e+2]*3,o=r[0]*y[t]+r[4]*y[t+1]+r[8]*y[t+2],s=r[1]*y[t]+r[5]*y[t+1]+r[9]*y[t+2],l=r[2]*y[t]+r[6]*y[t+1]+r[10]*y[t+2],u=r[0]*y[i]+r[4]*y[i+1]+r[8]*y[i+2]-o,d=r[1]*y[i]+r[5]*y[i+1]+r[9]*y[i+2]-s,f=r[2]*y[i]+r[6]*y[i+1]+r[10]*y[i+2]-l,p=r[0]*y[a]+r[4]*y[a+1]+r[8]*y[a+2]-o,m=r[1]*y[a]+r[5]*y[a+1]+r[9]*y[a+2]-s,h=r[2]*y[a]+r[6]*y[a+1]+r[10]*y[a+2]-l;Math.hypot(d*h-f*m,f*p-u*h,u*m-d*p)/2<c&&n++}if(h.zeroArea+=n,n){let r=I.get(e)??{node:e,mesh:t.mesh,where:i,zeroArea:0,triangles:0};r.zeroArea+=n,r.triangles+=N.length/3,I.set(e,r)}for(let e=0;e<S;e++)if(C[e]){let t=y[e*3],n=y[e*3+1],i=y[e*3+2];f(k,A,r[0]*t+r[4]*n+r[8]*i+r[12],r[1]*t+r[5]*n+r[9]*i+r[13],r[2]*t+r[6]*n+r[10]*i+r[14])}}let w=g(y,N);w!==void 0&&w<0&&s.push({code:`inside-out`,where:i,detail:`${r} is closed and its triangles face inward (signed volume ${w.toPrecision(3)})`});let T=v?.pbrMetallicRoughness?.baseColorTexture,E=v?.alphaMode??`OPAQUE`;if(o.alpha&&T&&(E===`MASK`||E===`BLEND`)&&p[`TEXCOORD_${T.texCoord??0}`]!==void 0)try{M.push({positions:y,uvs:F(p[`TEXCOORD_${T.texCoord??0}`]),tris:N.slice(),matrices:n,texture:T.index,cutoff:(E===`MASK`?v?.alphaCutoff??.5:o.blendCutoff??.5)/(v?.pbrMetallicRoughness?.baseColorFactor?.[3]??1)})}catch(e){s.push({code:`accessor`,where:i,detail:`${r}: ${e.message}`})}}}if(v.bounds=p(k,A),h.triangles===0&&h.pointsAndLines===0&&s.push({code:`empty`,detail:`the default scene draws nothing`}),v.zeroAreaByNode=[...I.values()],h.zeroArea&&s.push({code:`zero-area`,detail:`${h.zeroArea} of ${h.triangles} drawn triangles have zero area`}),o.alpha){let{decodeImage:e}=await import(`@margoengine/decoders/image`),t=/* @__PURE__ */ new Map,n=o.maxSamples??4194304,r=M.reduce((e,t)=>e+t.tris.length/3,0);for(let i of M){let a=b.textures?.[i.texture]?.source;if(a===void 0||!O[a])continue;t.has(a)||t.set(a,await e(O[a],{signal:o.signal}).catch(e=>(s.push({code:`image-format`,detail:`image ${a} could not be decoded for alpha: ${e.message}`}),null)));let c=t.get(a);c&&(j.primitives++,j.samples+=_(i,c,Math.max(1,Math.floor(n/Math.max(1,r))),j.min,j.max))}v.cutouts={primitives:j.primitives,bounds:p(j.min,j.max),samples:j.samples}}return y()}function g(e,t){let n=/* @__PURE__ */ new Map,r=new Int32Array(e.length/3);for(let t=0;t<r.length;t++){let i=`${Math.round(e[t*3]*1e5)},${Math.round(e[t*3+1]*1e5)},${Math.round(e[t*3+2]*1e5)}`,a=n.get(i);a===void 0&&n.set(i,a=n.size),r[t]=a}let i=/* @__PURE__ */ new Map,a=n.size,o=0;for(let n=0;n<t.length;n+=3){let s=t[n]*3,c=t[n+1]*3,l=t[n+2]*3,u=e;o+=(u[s]*(u[c+1]*u[l+2]-u[c+2]*u[l+1])-u[s+1]*(u[c]*u[l+2]-u[c+2]*u[l])+u[s+2]*(u[c]*u[l+1]-u[c+1]*u[l]))/6;for(let e=0;e<3;e++){let o=r[t[n+e]],s=r[t[n+(e+1)%3]];if(o===s)continue;let c=Math.min(o,s)*a+Math.max(o,s);i.set(c,(i.get(c)??0)+1)}}if(i.size){for(let e of i.values())if(e!==2)return;return o}}function _(e,t,n,r,i){let{positions:a,uvs:o,tris:s}=e,{width:c,height:l,data:u}=t,d=Math.min(1,Math.max(0,e.cutoff))*255,p=0;for(let t=0;t<s.length;t+=3){let[m,h,g]=[s[t],s[t+1],s[t+2]],_=o[m*2]*c,v=o[m*2+1]*l,y=o[h*2]*c,b=o[h*2+1]*l,x=o[g*2]*c,S=o[g*2+1]*l,C=Math.abs((y-_)*(S-v)-(x-_)*(b-v))/2,w=Math.max(1,Math.min(Math.ceil(Math.sqrt(2*C)),Math.floor(Math.sqrt(2*n))));for(let t=0;t<=w;t++)for(let n=0;n<=w-t;n++){let o=t/w,s=n/w,C=1-o-s,T=C*_+o*y+s*x,E=C*v+o*b+s*S,D=(Math.floor(T)%c+c)%c,O=(Math.floor(E)%l+l)%l;if(p++,u[(O*c+D)*4+3]<d)continue;let k=C*a[m*3]+o*a[h*3]+s*a[g*3],A=C*a[m*3+1]+o*a[h*3+1]+s*a[g*3+1],j=C*a[m*3+2]+o*a[h*3+2]+s*a[g*3+2];for(let t of e.matrices)f(r,i,t[0]*k+t[4]*A+t[8]*j+t[12],t[1]*k+t[5]*A+t[9]*j+t[13],t[2]*k+t[6]*A+t[10]*j+t[14])}}return p}export{l as imageHeader,h as reportGLTF};
@@ -1 +1 @@
1
- import{n as e,t}from"./accessor-nVsu_f1L.js";import{composeMatrix as n,multiplyMatrices as r}from"@margoengine/math/mat4";var i=`KHR_lights_punctual`,a=e=>/* @__PURE__ */ TypeError(`Invalid glTF ${e}; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`),o=(e,t,n=-1/0)=>{if(typeof e!=`number`||!Number.isFinite(e)||e<n)throw a(t);return e},s=(e,t,n)=>{if(o(e,t)<=n)throw a(t);return e},c=(e,t)=>{if(o(e,t)===0)throw a(t);return e};function l(e){if(e.type===`perspective`&&e.perspective){let t=e.perspective;return{type:`perspective`,yfov:s(t.yfov,`camera yfov`,0),znear:s(t.znear,`camera znear`,0),...t.zfar===void 0?{}:{zfar:s(t.zfar,`camera zfar`,t.znear)},...t.aspectRatio===void 0?{}:{aspectRatio:s(t.aspectRatio,`camera aspect`,0)}}}if(e.type===`orthographic`&&e.orthographic){let t=e.orthographic;return{type:`orthographic`,xmag:c(t.xmag,`camera xmag`),ymag:c(t.ymag,`camera ymag`),znear:o(t.znear,`camera znear`,0),zfar:s(t.zfar,`camera zfar`,t.znear)}}throw a(`camera`)}function u(e){if(e.type!==`directional`&&e.type!==`point`&&e.type!==`spot`)throw a(`light type`);let t=e.color??[1,1,1];if(!Array.isArray(t)||t.length!==3)throw a(`light color`);let n={type:e.type,color:t.map(e=>o(e,`light color`,0)),intensity:o(e.intensity??1,`light intensity`,0),...e.range===void 0||e.type===`directional`?{}:{range:s(e.range,`light range`,0)}};if(e.type!==`spot`)return n;let r=o(e.spot?.innerConeAngle??0,`spot angle`,0),i=s(e.spot?.outerConeAngle??Math.PI/4,`spot angle`,r);if(i>Math.PI/2)throw a(`spot angle`);return{...n,innerConeAngle:r,outerConeAngle:i}}function d(e,t,i,a){let o=a.get(t);if(o)return o;let s=e.nodes[t],c=s.matrix?Float64Array.from(s.matrix):n(s.translation??[0,0,0],s.rotation??[0,0,0,1],s.scale??[1,1,1],/* @__PURE__ */ new Float64Array(16)),l=i[t]<0?c:r(d(e,i[t],i,a),c);return a.set(t,l),l}function f(e,t,n){let r=Math.hypot(n[8],n[9],n[10])||1;return{name:typeof e.name==`string`?e.name:``,node:t,position:[n[12],n[13],n[14]],direction:[-n[8]/r,-n[9]/r,-n[10]/r],matrix:n}}var p=/* @__PURE__ */ new WeakMap,m=/* @__PURE__ */ new WeakMap,h={handles:[i],allowEmptyScene:!0,read(e){let t=e.doc.nodes??[];m.set(e,t),e.doc={...e.doc,nodes:t.map(e=>{if(e?.camera===void 0&&!e?.extensions?.[i])return e;let{camera:t,extensions:n,...r}=e,{[i]:a,...o}=n??{};return Object.keys(o).length?{...r,extensions:o}:r})}},finish(n,r,a){let o={cameras:[],lights:[]},s=m.get(r),c=r.doc,h=c.extensions?.[i]?.lights,g=new Int32Array(c.nodes?.length??0).fill(-1),_=/* @__PURE__ */ new Map;c.nodes?.forEach((e,t)=>e.children?.forEach(e=>g[e]=t)),s.forEach((n,r)=>{let s=a.nodes[r],p=n?.extensions?.[i];if(!s||n.camera===void 0&&!p)return;let m=f(n,s,d(c,r,g,_));n.camera!==void 0&&o.cameras.push({...m,...l(t(c.cameras,n.camera,`camera`))}),p&&o.lights.push({...m,...u(t(h,e(p.light,`light`),`light`))})}),p.set(n,o)}};function g(e){return p.get(e)??{cameras:[],lights:[]}}export{g as sceneData,h as sceneExtras};
1
+ import{n as e,t}from"./accessor-CU_1uSZ1.js";import{composeMatrix as n,multiplyMatrices as r}from"@margoengine/math/mat4";var i=`KHR_lights_punctual`,a=e=>/* @__PURE__ */ TypeError(`Invalid glTF ${e}; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`),o=(e,t,n=-1/0)=>{if(typeof e!=`number`||!Number.isFinite(e)||e<n)throw a(t);return e},s=(e,t,n)=>{if(o(e,t)<=n)throw a(t);return e},c=(e,t)=>{if(o(e,t)===0)throw a(t);return e};function l(e){if(e.type===`perspective`&&e.perspective){let t=e.perspective;return{type:`perspective`,yfov:s(t.yfov,`camera yfov`,0),znear:s(t.znear,`camera znear`,0),...t.zfar===void 0?{}:{zfar:s(t.zfar,`camera zfar`,t.znear)},...t.aspectRatio===void 0?{}:{aspectRatio:s(t.aspectRatio,`camera aspect`,0)}}}if(e.type===`orthographic`&&e.orthographic){let t=e.orthographic;return{type:`orthographic`,xmag:c(t.xmag,`camera xmag`),ymag:c(t.ymag,`camera ymag`),znear:o(t.znear,`camera znear`,0),zfar:s(t.zfar,`camera zfar`,t.znear)}}throw a(`camera`)}function u(e){if(e.type!==`directional`&&e.type!==`point`&&e.type!==`spot`)throw a(`light type`);let t=e.color??[1,1,1];if(!Array.isArray(t)||t.length!==3)throw a(`light color`);let n={type:e.type,color:t.map(e=>o(e,`light color`,0)),intensity:o(e.intensity??1,`light intensity`,0),...e.range===void 0||e.type===`directional`?{}:{range:s(e.range,`light range`,0)}};if(e.type!==`spot`)return n;let r=o(e.spot?.innerConeAngle??0,`spot angle`,0),i=s(e.spot?.outerConeAngle??Math.PI/4,`spot angle`,r);if(i>Math.PI/2)throw a(`spot angle`);return{...n,innerConeAngle:r,outerConeAngle:i}}function d(e,t,i,a){let o=a.get(t);if(o)return o;let s=e.nodes[t],c=s.matrix?Float64Array.from(s.matrix):n(s.translation??[0,0,0],s.rotation??[0,0,0,1],s.scale??[1,1,1],/* @__PURE__ */ new Float64Array(16)),l=i[t]<0?c:r(d(e,i[t],i,a),c);return a.set(t,l),l}function f(e,t,n){let r=Math.hypot(n[8],n[9],n[10])||1;return{name:typeof e.name==`string`?e.name:``,node:t,position:[n[12],n[13],n[14]],direction:[-n[8]/r,-n[9]/r,-n[10]/r],matrix:n}}var p=/* @__PURE__ */ new WeakMap,m=/* @__PURE__ */ new WeakMap,h={handles:[i],allowEmptyScene:!0,read(e){let t=e.doc.nodes??[];m.set(e,t),e.doc={...e.doc,nodes:t.map(e=>{if(e?.camera===void 0&&!e?.extensions?.[i])return e;let{camera:t,extensions:n,...r}=e,{[i]:a,...o}=n??{};return Object.keys(o).length?{...r,extensions:o}:r})}},finish(n,r,a){let o={cameras:[],lights:[]},s=m.get(r),c=r.doc,h=c.extensions?.[i]?.lights,g=new Int32Array(c.nodes?.length??0).fill(-1),_=/* @__PURE__ */ new Map;c.nodes?.forEach((e,t)=>e.children?.forEach(e=>g[e]=t)),s.forEach((n,r)=>{let s=a.nodes[r],p=n?.extensions?.[i];if(!s||n.camera===void 0&&!p)return;let m=f(n,s,d(c,r,g,_));n.camera!==void 0&&o.cameras.push({...m,...l(t(c.cameras,n.camera,`camera`))}),p&&o.lights.push({...m,...u(t(h,e(p.light,`light`),`light`))})}),p.set(n,o)}};function g(e){return p.get(e)??{cameras:[],lights:[]}}export{g as sceneData,h as sceneExtras};
@@ -1,4 +1,4 @@
1
- // @margo/core-built 0.1.0
1
+ // @margo/core-built 1.0.0
2
2
  import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
3
 
4
- var e=0,t=(t,n)=>{let r=n+e++;for(;t.plugins?.has(r);)r+=`:`;return r};function n(e){let n;if(typeof e?.sceneOf==`function`){for(let t of e.plugins?.values()??[])if(n=e.sceneOf(t))break;if(!n){let r={coreRequirement:/*@__PURE__*/__margoCoreRequirement("0.1.0",import.meta.url),name:t(e,`scene-scope:`),setup(){n=e.sceneOf(r)}};e.use(r),e.removePlugin(r.name)}}return r(e,n)}function r(e,n){return{scene:n,run(r){if(!n)return r();let i,a={coreRequirement:/*@__PURE__*/__margoCoreRequirement("0.1.0",import.meta.url),name:t(e,`scene-scope:`),setup(){i=r()}};return n.use(a),n.removePlugin(a.name),i}}}export{r as n,n as t};
4
+ var e=0,t=(t,n)=>{let r=n+e++;for(;t.plugins?.has(r);)r+=`:`;return r};function n(e){let n;if(typeof e?.sceneOf==`function`){for(let t of e.plugins?.values()??[])if(n=e.sceneOf(t))break;if(!n){let r={coreRequirement:/*@__PURE__*/__margoCoreRequirement("1.0.0",import.meta.url),name:t(e,`scene-scope:`),setup(){n=e.sceneOf(r)}};e.use(r),e.removePlugin(r.name)}}return r(e,n)}function r(e,n){return{scene:n,run(r){if(!n)return r();let i,a={coreRequirement:/*@__PURE__*/__margoCoreRequirement("1.0.0",import.meta.url),name:t(e,`scene-scope:`),setup(){i=r()}};return n.use(a),n.removePlugin(a.name),i}}}export{r as n,n as t};
package/dist/scene.js CHANGED
@@ -1,4 +1,4 @@
1
- // @margo/core-built 0.1.0
1
+ // @margo/core-built 1.0.0
2
2
  import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
- const r=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
- import{n as e}from"./errors-THVaUwlL.js";import{n as t}from"./mesh-source-DvU8YvMc.js";import{t as n}from"./visibility-C_Oqz9Sr.js";import{engineRuntime as __margoRuntime,meshRuntime as i}from"@margoengine/core/extension";function a(t,a,{visibleOnly:o=!0}){if(t.disposed)throw e(`disposed`,`Engine disposed; create a new engine`);if(typeof o!=`boolean`)throw TypeError(`Invalid visibleOnly; pass true or false`);let s=r(t),c=/* @__PURE__ */ new Set;for(let e of Array.from(a)){e.check();let t=i(e);if(t.engine!==s)throw TypeError(`Foreign mesh; pass meshes created by the same engine`);c.add(t.id)}s.store.tick(!1);let l=[];for(let e of s.meshes.values()){let t=!1,r=0;for(let n=e.id;n!==-1;n=s.store.parents[n]){if(++r>64)throw RangeError(`Parent depth: 64; flatten the mesh hierarchy`);c.has(n)&&(t=!0)}t&&(!o||!n(s.store,e.id))&&l.push(e)}return{engine:s,meshes:l}}function o(n,r,i={}){let{meshes:o}=a(n,r,i),s=[1/0,1/0,1/0,-1/0,-1/0,-1/0],c=(e,t,n)=>{for(let r=0;r<e.length;r+=t){let t=e[r],i=e[r+1],a=e[r+2];for(let e=0;e<3;e++){let r=n[e]*t+n[e+4]*i+n[e+8]*a+n[e+12];if(!Number.isFinite(Math.fround(r)))throw RangeError(`Scene positions must be finite`);s[e]=Math.min(s[e],r),s[e+3]=Math.max(s[e+3],r)}}};for(let e of o){let n=t(e);if(n?.kind===`core`)c(n.geometry.vertices,6,e.matrix);else if(n?.kind===`pbr`)for(let t of n.source.primitives)c(t.vertices,20,e.matrix)}if(!Number.isFinite(s[0]))throw e(`state`,`No geometry; select meshes with triangles`);return Float32Array.from(s)}function s(e,t,n={}){let r=o(e,t,n),i=e.canvas,a=n.aspect??Math.max(1,i.clientWidth||i.width)/Math.max(1,i.clientHeight||i.height);return e.camera.fitToBoundingBox([r[0],r[1],r[2]],[r[3],r[4],r[5]],{aspect:a,duration:n.duration,padding:n.padding}),r}function c(n,r,i={}){let{engine:o,meshes:s}=a(n,r,i);if(n.backend!==`webgpu`)return null;let c=[];for(let n of s){let r=t(n);if(r?.kind===`core`){let t=o.geometryBuffers(r.geometry);if(!t)throw e(`state`,`Geometry unavailable; render one frame first`);c.push({kind:`core`,node:n,matrix:n.matrix,geometry:r.geometry,vertex:t.vertex,index:t.index,instance:t.instance,count:r.geometry.indices.length,stride:24,indexFormat:`uint32`})}else if(r?.kind===`pbr`){let t=r.source.draws;if(r.source.primitives.length&&!t.length)throw e(`state`,`PBR geometry unavailable; render one frame first`);for(let e of t)c.push({...e,kind:`pbr`,matrix:n.matrix,stride:80,indexFormat:`uint32`})}}return c}export{s as fitScene,c as gatherSceneBuffers,o as getSceneBounds};
3
+ const n=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import{n as e}from"./mesh-source-DvU8YvMc.js";import{t}from"./visibility-C_Oqz9Sr.js";import{engineRuntime as __margoRuntime,margoError as r,meshRuntime as i}from"@margoengine/core/extension";function a(e,a,{visibleOnly:o=!0}){if(e.disposed)throw r(`disposed`,`Engine disposed; create a new engine`);if(typeof o!=`boolean`)throw TypeError(`Invalid visibleOnly; pass true or false`);let s=n(e),c=/* @__PURE__ */ new Set;for(let e of Array.from(a)){e.check();let t=i(e);if(t.engine!==s)throw TypeError(`Foreign mesh; pass meshes created by the same engine`);c.add(t.id)}s.store.tick(!1);let l=[];for(let e of s.meshes.values()){let n=!1,r=0;for(let t=e.id;t!==-1;t=s.store.parents[t]){if(++r>64)throw RangeError(`Parent depth: 64; flatten the mesh hierarchy`);c.has(t)&&(n=!0)}n&&(!o||!t(s.store,e.id))&&l.push(e)}return{engine:s,meshes:l}}function o(t,n,i={}){let{meshes:o}=a(t,n,i),s=[1/0,1/0,1/0,-1/0,-1/0,-1/0],c=(e,t,n)=>{for(let r=0;r<e.length;r+=t){let t=e[r],i=e[r+1],a=e[r+2];for(let e=0;e<3;e++){let r=n[e]*t+n[e+4]*i+n[e+8]*a+n[e+12];if(!Number.isFinite(Math.fround(r)))throw RangeError(`Scene positions must be finite`);s[e]=Math.min(s[e],r),s[e+3]=Math.max(s[e+3],r)}}};for(let t of o){let n=e(t);if(n?.kind===`core`)c(n.geometry.vertices,6,t.matrix);else if(n?.kind===`pbr`)for(let e of n.source.primitives)c(e.vertices,20,t.matrix)}if(!Number.isFinite(s[0]))throw r(`state`,`No geometry; select meshes with triangles`);return Float32Array.from(s)}function s(e,t,n={}){let r=o(e,t,n),i=e.canvas,a=n.aspect??Math.max(1,i.clientWidth||i.width)/Math.max(1,i.clientHeight||i.height);return e.camera.fitToBoundingBox([r[0],r[1],r[2]],[r[3],r[4],r[5]],{aspect:a,duration:n.duration,padding:n.padding}),r}function c(t,n,i={}){let{engine:o,meshes:s}=a(t,n,i);if(t.backend!==`webgpu`)return null;let c=[];for(let t of s){let n=e(t);if(n?.kind===`core`){let e=o.geometryBuffers(n.geometry);if(!e)throw r(`state`,`Geometry unavailable; render one frame first`);c.push({kind:`core`,node:t,matrix:t.matrix,geometry:n.geometry,vertex:e.vertex,index:e.index,instance:e.instance,count:n.geometry.indices.length,stride:24,indexFormat:`uint32`})}else if(n?.kind===`pbr`){let e=n.source.draws;if(n.source.primitives.length&&!e.length)throw r(`state`,`PBR geometry unavailable; render one frame first`);for(let n of e)c.push({...n,kind:`pbr`,matrix:t.matrix,stride:80,indexFormat:`uint32`})}}return c}export{s as fitScene,c as gatherSceneBuffers,o as getSceneBounds};