@margoengine/gltf 0.0.0-stage → 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 (138) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1753 -2
  4. package/dist/accessor-CU_1uSZ1.js +1 -0
  5. package/dist/accessor-DuqjpuxI.js +1 -0
  6. package/dist/accessor.d.ts +12 -0
  7. package/dist/asset-DN3ocEdY.js +4 -0
  8. package/dist/asset-entry.d.ts +1 -0
  9. package/dist/asset-entry.js +1 -0
  10. package/dist/asset.d.ts +395 -0
  11. package/dist/audio.d.ts +47 -0
  12. package/dist/audio.js +1 -0
  13. package/dist/auto.d.ts +29 -0
  14. package/dist/auto.js +1 -0
  15. package/dist/base-textures.d.ts +20 -0
  16. package/dist/coalesce.d.ts +29 -0
  17. package/dist/compression-CUOCmjmE.js +1 -0
  18. package/dist/compression.d.ts +21 -0
  19. package/dist/coordinates.d.ts +1 -0
  20. package/dist/coordinates.js +1 -0
  21. package/dist/dds.d.ts +7 -0
  22. package/dist/dds.js +1 -0
  23. package/dist/decoder-default-CxLH8Vz0.js +1 -0
  24. package/dist/decoder-default.d.ts +5 -0
  25. package/dist/default-materials.d.ts +10 -0
  26. package/dist/default-transmission.d.ts +13 -0
  27. package/dist/draco-state.d.ts +7 -0
  28. package/dist/draw-batch.d.ts +83 -0
  29. package/dist/draw-memo.d.ts +136 -0
  30. package/dist/extended.d.ts +12 -0
  31. package/dist/extended.js +1 -0
  32. package/dist/gltf.worker.d.ts +1 -0
  33. package/dist/group.d.ts +18 -0
  34. package/dist/image-limit-DvFSfR5T.js +1 -0
  35. package/dist/image-limit.d.ts +6 -0
  36. package/dist/index.d.ts +95 -0
  37. package/dist/index.js +1 -0
  38. package/dist/instanced-shader-C9ZMazvo.js +5 -0
  39. package/dist/instanced-shader.d.ts +14 -0
  40. package/dist/instancing.d.ts +9 -0
  41. package/dist/instancing.js +1 -0
  42. package/dist/interactivity-graph.d.ts +193 -0
  43. package/dist/interactivity-model.d.ts +94 -0
  44. package/dist/interactivity-ops.d.ts +20 -0
  45. package/dist/interactivity.d.ts +33 -0
  46. package/dist/interactivity.js +1 -0
  47. package/dist/lights.d.ts +98 -0
  48. package/dist/lights.js +1 -0
  49. package/dist/limits-_LZ441oV.js +1 -0
  50. package/dist/material-draw-state-GKiHDb0p.js +1 -0
  51. package/dist/material-draw-state.d.ts +7 -0
  52. package/dist/material-draw.d.ts +18 -0
  53. package/dist/material-draw.js +1 -0
  54. package/dist/material-extension.d.ts +96 -0
  55. package/dist/mesh-source-DvU8YvMc.js +1 -0
  56. package/dist/meshopt.d.ts +9 -0
  57. package/dist/meshopt.js +1 -0
  58. package/dist/metadata.d.ts +114 -0
  59. package/dist/metadata.js +1 -0
  60. package/dist/mipmaps-38NmjDc3.js +21 -0
  61. package/dist/model-C77ATxi1.js +25 -0
  62. package/dist/model-entry.d.ts +2 -0
  63. package/dist/model-entry.js +1 -0
  64. package/dist/model.d.ts +1088 -0
  65. package/dist/native-glass-D85twud0.js +19 -0
  66. package/dist/node-image-decode.d.ts +6 -0
  67. package/dist/node-matrix-R9BipGnp.js +1 -0
  68. package/dist/node-matrix.d.ts +16 -0
  69. package/dist/occlusion.d.ts +8 -0
  70. package/dist/pack-DdxRO8k6.js +1 -0
  71. package/dist/pack.d.ts +27 -0
  72. package/dist/parts.d.ts +54 -0
  73. package/dist/pbr-instancing.d.ts +83 -0
  74. package/dist/pbr-instancing.js +1 -0
  75. package/dist/pbr.d.ts +13 -0
  76. package/dist/pbr.js +1 -0
  77. package/dist/physics.d.ts +148 -0
  78. package/dist/physics.js +1 -0
  79. package/dist/prepare.d.ts +26 -0
  80. package/dist/prepare.js +1 -0
  81. package/dist/progressive-lod.d.ts +13 -0
  82. package/dist/progressive.d.ts +62 -0
  83. package/dist/progressive.js +4 -0
  84. package/dist/progressive.worker.d.ts +1 -0
  85. package/dist/quantized.d.ts +8 -0
  86. package/dist/quantized.js +1 -0
  87. package/dist/render-state.d.ts +18 -0
  88. package/dist/replica.d.ts +37 -0
  89. package/dist/report.d.ts +128 -0
  90. package/dist/report.js +1 -0
  91. package/dist/scene-data.d.ts +61 -0
  92. package/dist/scene-data.js +1 -0
  93. package/dist/scene-scope-CZDEkd24.js +4 -0
  94. package/dist/scene.d.ts +61 -0
  95. package/dist/scene.js +4 -0
  96. package/dist/shader-C29RtPAw.js +409 -0
  97. package/dist/shader.d.ts +246 -0
  98. package/dist/shared/caster.d.ts +159 -0
  99. package/dist/shared/gltf.d.ts +257 -0
  100. package/dist/shared/iridescence.d.ts +2 -0
  101. package/dist/shared/prepared-geometry.d.ts +8 -0
  102. package/dist/side-shader.d.ts +1 -0
  103. package/dist/soft-mesh.d.ts +132 -0
  104. package/dist/soft-mesh.js +4 -0
  105. package/dist/spec-gloss.d.ts +21 -0
  106. package/dist/spec-gloss.js +18 -0
  107. package/dist/splat-state.d.ts +7 -0
  108. package/dist/splats.d.ts +18 -0
  109. package/dist/splats.js +1 -0
  110. package/dist/src-Btvz5f6i.js +4 -0
  111. package/dist/stream-CrfNNCRd.js +1 -0
  112. package/dist/stream.d.ts +104 -0
  113. package/dist/stroke-width-B2cnYGgn.js +1 -0
  114. package/dist/stroke-width.d.ts +18 -0
  115. package/dist/strokes.d.ts +12 -0
  116. package/dist/strokes.js +1 -0
  117. package/dist/texture-coordinates-XFsEMdU6.js +2 -0
  118. package/dist/texture-coordinates.d.ts +26 -0
  119. package/dist/texture-stream-Cu_XpyVO.js +4 -0
  120. package/dist/texture-stream.d.ts +88 -0
  121. package/dist/textured.d.ts +34 -0
  122. package/dist/textured.js +5 -0
  123. package/dist/transmission.d.ts +81 -0
  124. package/dist/transmission.js +66 -0
  125. package/dist/uniform-arena.d.ts +78 -0
  126. package/dist/version-B6NE5cJf.js +1 -0
  127. package/dist/version.d.ts +8 -0
  128. package/dist/vertex-inputs.d.ts +53 -0
  129. package/dist/view-uniform.d.ts +13 -0
  130. package/dist/visibility-C_Oqz9Sr.js +1 -0
  131. package/dist/warning-UqjZyyqW.js +89 -0
  132. package/dist/warning.d.ts +24 -0
  133. package/dist/worker-CY1TQnYX.js +1 -0
  134. package/dist/worker.d.ts +21 -0
  135. package/dist/worker.js +4 -0
  136. package/dist/workers/gltf.js +322 -0
  137. package/dist/workers/progressive.js +1 -0
  138. package/package.json +232 -4
@@ -0,0 +1,8 @@
1
+ /** Validate packed triangle geometry without loading its renderer. */
2
+ export function validatePreparedGeometry(data: {
3
+ vertices: Float32Array;
4
+ indices: Uint32Array;
5
+ interpolatedDirections?: boolean;
6
+ }): void;
7
+ /** Validate an already checked vertex range. */
8
+ export function checkPreparedVertices(vertices: Float32Array, from: number, to: number, interpolated?: boolean): void;
@@ -0,0 +1 @@
1
+ export declare function backSideShader(code: string): string;
@@ -0,0 +1,132 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import type { Engine, EnginePlugin } from '@margoengine/core/extension';
4
+ // @ts-ignore optional peer: its types apply when it is installed
5
+ import type { GPUCloth } from '@margoengine/physics/gpu-cloth';
6
+ // @ts-ignore optional peer: its types apply when it is installed
7
+ import type { SoftBody } from '@margoengine/physics/soft';
8
+ import { type GLTFDocument, type GLTFImage } from './asset.js';
9
+ import { PBRModel } from './model.js';
10
+ /** A glTF 2.0 material (`materials[i]` of a glTF file). */
11
+ export type SoftMeshMaterial = NonNullable<GLTFDocument['materials']>[number];
12
+ /** Options for {@link SoftSurface}. */
13
+ export interface SoftSurfaceOptions {
14
+ /**
15
+ * Texture coordinates, two a particle (two a skin vertex for a skinned body, two a vertex of the source mesh for a body
16
+ * made by `SoftBodyDesc.volume`). Default: a `volume` body's own (its mesh's `uvs` or `TEXCOORD_0`), the grid of a body built by
17
+ * `cloth`, `clothAnisotropic` or `clothTube` (particle (i, j) at (i / (nu - 1), j / (nv - 1)), a tube's seam doubled so
18
+ * u runs 0 to 1 around it), else the body's shape where the surface is made, laid flat on the plane of its two largest
19
+ * extents and scaled to 0..1.
20
+ */
21
+ uvs?: ArrayLike<number>;
22
+ }
23
+ /**
24
+ * The surface of a soft body as packed PBR vertices (`STRIDE` = 20 floats: position and 1, normal and 0, tangent with
25
+ * its handedness, two UV sets, colour) and triangles. `update()` copies the particles (or the skin) and recomputes the
26
+ * normals, each the area-weighted sum of its triangles' normals, and the tangents from the UVs (Lengyel 2001).
27
+ */
28
+ export declare class SoftSurface {
29
+ readonly body: SoftBody;
30
+ /** 20 floats a vertex, in the layout `PBRModel` draws. */
31
+ readonly vertices: Float32Array;
32
+ /** Three vertex indices a triangle, wound as the body's triangles are. */
33
+ readonly indices: Uint32Array;
34
+ /** Two floats a vertex. */
35
+ readonly uvs: Float32Array;
36
+ /** The particle each vertex copies (a tube's seam vertices copy the first ring); empty for a skinned body. */
37
+ private readonly source;
38
+ /** Pairs of vertices that are one particle (a tube's first ring and its seam copy). */
39
+ private readonly twins;
40
+ private readonly skinned;
41
+ /** For a body made by `SoftBodyDesc.volume`, each particle's normal: the copies of a welded vertex share it. */
42
+ private readonly particleNormals;
43
+ private readonly scratch;
44
+ private readonly normal;
45
+ private readonly tangent;
46
+ private readonly bitangent;
47
+ constructor(body: SoftBody, _arg0?: SoftSurfaceOptions);
48
+ /** The number of vertices (a tube has one more ring of them than of particles around). */
49
+ get vertexCount(): number;
50
+ /** Copies the body's particles (or its skin) into the vertices and recomputes the normals and tangents. */
51
+ update(): this;
52
+ }
53
+ /** Options for {@link drawSoftBody}. */
54
+ export interface SoftBodyMeshOptions extends SoftSurfaceOptions {
55
+ /**
56
+ * The glTF material it is drawn with. Default `{doubleSided: true, pbrMetallicRoughness: {metallicFactor: 0,
57
+ * roughnessFactor: 0.8}}`: a matte sheet seen from both sides. `doubleSided` stays true unless the material says false.
58
+ * Its textures name `images` by index: texture `i` is image `i`.
59
+ */
60
+ material?: SoftMeshMaterial;
61
+ /** The images its textures read (an `ImageBitmap`, or `{width, height, data}` RGBA8 pixels). Default none. */
62
+ images?: readonly GLTFImage[];
63
+ }
64
+ /**
65
+ * A soft body drawn as a PBR mesh: each frame, before the engine draws, the vertices follow the body (when it is awake)
66
+ * and upload in place. Make it after the body's `Physics` is on the engine, so the frame's step runs first. A body that is
67
+ * removed (or splits on a tear) stops it at its last pose: draw the pieces with `drawSoftBody` from `soft.onTear`.
68
+ */
69
+ export declare class SoftBodyMesh implements EnginePlugin {
70
+ readonly name: string;
71
+ /**
72
+ * Copies the particles after physics has stepped them this frame (physics is a `late` plugin, KB-PHYS-FRAMEORDER1):
73
+ * a late plugin added after the physics world runs after it, so the mesh drawn is the step just taken, not the one
74
+ * before (KB-SOFTMESH-LAG1).
75
+ */
76
+ readonly late = true;
77
+ /** The model it draws with: `model.setVisible`, picking and the PBR model API work on it. */
78
+ readonly model: PBRModel;
79
+ /** The CPU surface it uploads. */
80
+ readonly surface: SoftSurface;
81
+ private engine?;
82
+ private disposed;
83
+ /** The vertices the model holds, and the array the next frame writes. */
84
+ private held;
85
+ private spare;
86
+ constructor(engine: EngineKernel, body: SoftBody, _arg1?: SoftBodyMeshOptions);
87
+ setup(engine: Engine): void;
88
+ onPreUpdate(): void;
89
+ /** Moves the mesh to where the body is now, at once (the frame does this by itself). */
90
+ sync(): this;
91
+ /** Removes the mesh from the engine and frees its buffers. The body is not touched. */
92
+ dispose(): void;
93
+ [Symbol.dispose]: () => void;
94
+ }
95
+ /**
96
+ * Draws a soft body with one call: `const mesh = drawSoftBody(engine, cloth, {material})`. The mesh follows the body every
97
+ * frame with recomputed normals and tangents and grid texture coordinates; `mesh.dispose()` (or `using`) removes it.
98
+ */
99
+ export declare function drawSoftBody(engine: EngineKernel, body: SoftBody, options?: SoftBodyMeshOptions): SoftBodyMesh;
100
+ /** Options for {@link drawGPUCloth}: the material and images, as {@link drawSoftBody} takes them. */
101
+ export type GPUClothMeshOptions = Pick<SoftBodyMeshOptions, 'material' | 'images'>;
102
+ /**
103
+ * A `GPUCloth` of `@margoengine/physics/gpu-cloth` drawn as a PBR mesh. On WebGPU the model draws the vertex buffer the
104
+ * cloth's compute writes (as a skin's output is drawn): no readback, no upload. On the WebGL2 compatibility layer the cloth
105
+ * steps on the CPU and the mesh uploads its vertices when they change.
106
+ */
107
+ export declare class GPUClothMesh implements EnginePlugin {
108
+ readonly cloth: GPUCloth;
109
+ readonly name: string;
110
+ /** After the cloth (a late plugin), so a CPU step of this frame is the one uploaded. */
111
+ readonly late = true;
112
+ /** The model it draws with: `model.setVisible`, picking and the PBR model API work on it. */
113
+ readonly model: PBRModel;
114
+ private engine?;
115
+ private disposed;
116
+ private seen;
117
+ private held;
118
+ private spare;
119
+ constructor(engine: EngineKernel, cloth: GPUCloth, _arg2?: GPUClothMeshOptions);
120
+ setup(engine: Engine): void;
121
+ onPreUpdate(): void;
122
+ /** Points the model at the cloth's GPU vertices, or uploads its CPU vertices when they changed (the frame does this). */
123
+ sync(): this;
124
+ /** Removes the mesh from the engine and frees its buffers. The cloth is not touched. */
125
+ dispose(): void;
126
+ [Symbol.dispose]: () => void;
127
+ }
128
+ /**
129
+ * Draws a GPU cloth with one call: `const mesh = drawGPUCloth(engine, cloth, {material})`. Attach it after the cloth;
130
+ * `mesh.dispose()` (or `using`) removes it.
131
+ */
132
+ export declare function drawGPUCloth(engine: EngineKernel, cloth: GPUCloth, options?: GPUClothMeshOptions): GPUClothMesh;
@@ -0,0 +1,4 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import{n as e}from"./model-C77ATxi1.js";import{t}from"./asset-DN3ocEdY.js";import{MargoError as n}from"@margoengine/math/errors";var r=20,i=0,a=class{constructor(e,{uvs:t}={}){if(this.body=e,!e.valid)throw new n(`state`,`Soft body was removed; draw a body that is still in its world.`);this.skinned=e.meshIndices().length>0;let i=this.skinned?e.meshIndices():e.triangles();if(i.length===0)throw TypeError(`This soft body has no triangles to draw (a rope or a bare particle set); draw a rope with @margoengine/lines, or build the body with cloth, trimesh, sphere or setSkin.`);let a=this.skinned?null:e.sourceMesh,s=t??e.sourceMesh?.uvs??void 0,c=this.skinned?e.meshVertices().length/3:a?a.particles.length:e.numParticles(),l=this.skinned||s||a?null:e.grid,u,d,f;if(l?.wrap){let{nu:e,nv:t}=l;u=new Uint32Array((e+1)*t),f=new Float32Array(u.length*2);for(let n=0;n<=e;n++)for(let r=0;r<t;r++)u[n*t+r]=n%e*t+r,f[(n*t+r)*2]=n/e,f[(n*t+r)*2+1]=r/(t-1);d=new Uint32Array(i.length);for(let n=0;n<i.length;n+=3){let r=[0,1,2].map(e=>Math.floor(i[n+e]/t)),a=r.includes(e-1)&&r.includes(0);for(let o=0;o<3;o++)d[n+o]=a&&r[o]===0?e*t+i[n+o]%t:i[n+o]}}else if(u=this.skinned?/* @__PURE__ */ new Uint32Array:a?a.particles.slice():Uint32Array.from({length:c},(e,t)=>t),d=a?a.indices.slice():i,s){if(s.length!==c*2)throw RangeError(`Soft surface uvs need two numbers a vertex: ${c*2}, not ${s.length}.`);if(f=Float32Array.from(s),!f.every(Number.isFinite))throw RangeError(`Soft surface uvs must be finite numbers.`)}else if(l){f=new Float32Array(c*2);for(let e=0;e<l.nu;e++)for(let t=0;t<l.nv;t++)f[(e*l.nv+t)*2]=e/(l.nu-1),f[(e*l.nv+t)*2+1]=t/(l.nv-1)}else{let t=this.skinned?e.meshVertices():e.particlePositions();f=o(a?Float32Array.from({length:c*3},(e,n)=>t[u[n/3|0]*3+n%3]):t)}this.source=u,this.particleNormals=a?new Float32Array(e.numParticles()*3):null;let p=[];if(l?.wrap)for(let e=0;e<l.nv;e++)p.push(e,l.nu*l.nv+e);this.twins=Uint32Array.from(p),this.indices=d,this.uvs=f;let m=this.vertices=new Float32Array(f.length/2*r);for(let e=0;e<f.length/2;e++){let t=e*r;m[t+3]=1,m[t+12]=m[t+14]=f[e*2],m[t+13]=m[t+15]=f[e*2+1],m[t+16]=m[t+17]=m[t+18]=m[t+19]=1}this.scratch=new Float32Array((this.skinned?c:e.numParticles())*3),this.normal=new Float32Array(f.length/2*3),this.tangent=new Float32Array(this.normal.length),this.bitangent=new Float32Array(this.normal.length),this.update()}get vertexCount(){return this.uvs.length/2}update(){if(!this.body.valid)throw new n(`state`,`Soft body was removed; draw the bodies that replaced it with drawSoftBody.`);let e=this.skinned?this.body.meshVertices():this.body.particlePositions(this.scratch),t=this.vertices,i=this.normal,a=this.tangent,o=this.bitangent,s=this.uvs,c=this.indices,l=this.vertexCount;for(let n=0;n<l;n++){let i=(this.skinned?n:this.source[n])*3,a=n*r;t[a]=e[i],t[a+1]=e[i+1],t[a+2]=e[i+2]}i.fill(0),a.fill(0),o.fill(0);for(let e=0;e<c.length;e+=3){let n=c[e],l=c[e+1],u=c[e+2],d=n*r,f=t[l*r]-t[d],p=t[l*r+1]-t[d+1],m=t[l*r+2]-t[d+2],h=t[u*r]-t[d],g=t[u*r+1]-t[d+1],_=t[u*r+2]-t[d+2],v=p*_-m*g,y=m*h-f*_,b=f*g-p*h,x=s[l*2]-s[n*2],S=s[l*2+1]-s[n*2+1],C=s[u*2]-s[n*2],w=s[u*2+1]-s[n*2+1],T=x*w-C*S,E=T===0?0:1/T,D=(f*w-h*S)*E,O=(p*w-g*S)*E,k=(m*w-_*S)*E,A=(h*x-f*C)*E,j=(g*x-p*C)*E,M=(_*x-m*C)*E;for(let e of[n,l,u])i[e*3]=i[e*3]+v,i[e*3+1]=i[e*3+1]+y,i[e*3+2]=i[e*3+2]+b,a[e*3]=a[e*3]+D,a[e*3+1]=a[e*3+1]+O,a[e*3+2]=a[e*3+2]+k,o[e*3]=o[e*3]+A,o[e*3+1]=o[e*3+1]+j,o[e*3+2]=o[e*3+2]+M}for(let e=0;e<this.twins.length;e+=2){let t=this.twins[e]*3,n=this.twins[e+1]*3;for(let e of[i,a,o])for(let r=0;r<3;r++)e[t+r]=e[n+r]=e[t+r]+e[n+r]}let u=this.particleNormals;if(u){u.fill(0);for(let e=0;e<l;e++)for(let t=0;t<3;t++)u[this.source[e]*3+t]=u[this.source[e]*3+t]+i[e*3+t];for(let e=0;e<l;e++)for(let t=0;t<3;t++)i[e*3+t]=u[this.source[e]*3+t]}for(let e=0;e<l;e++){let n=e*r,s=i[e*3],c=i[e*3+1],l=i[e*3+2],u=Math.hypot(s,c,l);u>0?(s/=u,c/=u,l/=u):(s=t[n+4],c=t[n+5],l=t[n+6]||+(s===0&&c===0)),t[n+4]=s,t[n+5]=c,t[n+6]=l;let d=a[e*3],f=a[e*3+1],p=a[e*3+2],m=d*s+f*c+p*l;d-=s*m,f-=c*m,p-=l*m;let h=Math.hypot(d,f,p);h>1e-12||([d,f,p]=Math.abs(s)<.9?[0,-l,c]:[l,0,-s],h=Math.hypot(d,f,p)),t[n+8]=d/h,t[n+9]=f/h,t[n+10]=p/h;let g=c*p-l*f,_=l*d-s*p,v=s*f-c*d;t[n+11]=g*o[e*3]+_*o[e*3+1]+v*o[e*3+2]<0?-1:1}return this}};function o(e){let t=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0];for(let r=0;r<e.length;r++)t[r%3]=Math.min(t[r%3],e[r]),n[r%3]=Math.max(n[r%3],e[r]);let r=[0,1,2].map(e=>n[e]-t[e]),[i,a]=[0,1,2].sort((e,t)=>r[t]-r[e]||e-t),o=new Float32Array(e.length/3*2);for(let n=0;n<e.length/3;n++)o[n*2]=r[i]>0?(e[n*3+i]-t[i])/r[i]:0,o[n*2+1]=r[a]>0?(e[n*3+a]-t[a])/r[a]:0;return o}var s=class{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);constructor(e,t,{material:n,images:r=[],...o}={}){this.name=`soft-mesh:`+i++,this.late=!0,this.disposed=!1,this.surface=new a(t,o),this.held=this.surface.vertices.slice(),this.spare=this.surface.vertices.slice(),this.model=l(e,this.held,this.surface.indices,n,r),e.use(this.model);try{e.use(this)}catch(e){throw this.model.dispose(),e}}setup(e){this.engine=e}onPreUpdate(){let e=this.surface.body;this.disposed||!e.valid||e.sleeping||this.sync()}sync(){if(this.disposed)throw new n(`disposed`,`SoftBodyMesh is disposed; draw the body again with drawSoftBody.`);this.surface.update();let e=this.spare;return e.set(this.surface.vertices),this.model.writeGeometry([{vertices:e,indices:this.surface.indices}],{start:0,count:this.surface.vertexCount}),this.spare=this.held,this.held=e,this}dispose(){this.disposed||(this.disposed=!0,this.engine?.sceneOf(this)?.removePlugin(this.name),this.model.dispose())}[Symbol.dispose??Symbol()](){this.dispose()}};function c(e,t,n){return new s(e,t,n)}function l(n,r,i,a,o){let s=o.map((e,t)=>({source:t}));return new e(n,new t({asset:{version:`2.0`},materials:[{doubleSided:!0,pbrMetallicRoughness:{metallicFactor:0,roughnessFactor:.8},...a}],...s.length?{textures:s,images:o.map(()=>({}))}:{},meshes:[{primitives:[{attributes:{POSITION:0},material:0}]}],nodes:[{mesh:0}]},[]),o,[[{vertices:r,indices:i}]])}var u=class{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);constructor(e,t,{material:r,images:a=[]}={}){if(this.cloth=t,this.name=`gpu-cloth-mesh:`+i++,this.late=!0,this.disposed=!1,this.seen=-1,!(t?.vertices instanceof Float32Array)||!(t.indices instanceof Uint32Array))throw new n(`unsupported`,`drawGPUCloth takes a GPUCloth of @margoengine/physics/gpu-cloth; pass the cloth that entry creates.`);this.held=t.vertices.slice(),this.spare=t.vertices.slice(),this.model=l(e,this.held,t.indices,r,a),e.use(this.model);try{e.use(this)}catch(e){throw this.model.dispose(),e}}setup(e){this.engine=e}onPreUpdate(){this.disposed||this.sync()}sync(){if(this.disposed)throw new n(`disposed`,`GPUClothMesh is disposed; draw the cloth again with drawGPUCloth.`);let e=this.cloth.vertexBuffer;if(e){for(let t of this.model.primitives)t.deformed!==e&&(t.deformed=e,t.deformedOffset=0);return this}for(let e of this.model.primitives)e.deformed=void 0;if(this.cloth.revision===this.seen)return this;this.seen=this.cloth.revision;let t=this.spare;return t.set(this.cloth.vertices),this.model.writeGeometry([{vertices:t,indices:this.cloth.indices}],{start:0,count:this.cloth.count}),this.spare=this.held,this.held=t,this}dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.model.primitives)e.deformed=void 0;this.engine?.sceneOf(this)?.removePlugin(this.name),this.model.dispose()}}[Symbol.dispose??Symbol()](){this.dispose()}};function d(e,t,n){return new u(e,t,n)}export{u as GPUClothMesh,s as SoftBodyMesh,a as SoftSurface,d as drawGPUCloth,c as drawSoftBody};
@@ -0,0 +1,21 @@
1
+ import type { GLTFMaterial } from './shared/gltf.js';
2
+ import type { GLTFExtendedMaterials } from './asset.js';
3
+ /** Metal/rough factors derived from one linear-light spec/gloss sample. */
4
+ export interface MetalRoughSample {
5
+ /** Linear RGBA; opacity is copied from diffuse alpha. */
6
+ readonly baseColor: readonly number[];
7
+ readonly metallic: number;
8
+ readonly roughness: number;
9
+ }
10
+ /**
11
+ * Converts linear diffuse RGBA, specular RGB and glossiness to metal/rough. Defaults are the extension's white/white/1.
12
+ * Conversion is an approximation for nonphysical spec/gloss colours; saturated endpoints remain finite.
13
+ */
14
+ export declare function specGlossToMetalRough(diffuse?: readonly number[], specular?: readonly number[], glossiness?: number): MetalRoughSample;
15
+ /** Converts the authored factors/map routing without changing the input document or baking mismatched UV sets. */
16
+ export declare function convertSpecGlossMaterial(material: GLTFMaterial): GLTFMaterial;
17
+ /**
18
+ * Optional reader for loadGLTF/parseGLTFAsync (selected automatically) and synchronous parseGLTF's materials hook.
19
+ * Retains per-map UV sets, transforms, filters, alpha, normal/occlusion/emission maps and material variants.
20
+ */
21
+ export declare const specGlossMaterials: GLTFExtendedMaterials;
@@ -0,0 +1,18 @@
1
+ import{a as e,o as t}from"./shader-C29RtPAw.js";import{r as n}from"./texture-coordinates-XFsEMdU6.js";import{extendedMaterials as r}from"./extended.js";import{margoError as i}from"@margoengine/core/extension";var a=`KHR_materials_pbrSpecularGlossiness`,o=(e,t)=>{if(typeof e!=`number`||!Number.isFinite(e)||e<0||e>1)throw TypeError(`Invalid glTF spec/gloss ${t}; pass a finite number from 0 to 1`);return e},s=(e,t,n)=>{if(!Array.isArray(e)||e.length!==t||Array.from(e).some(e=>typeof e!=`number`))throw TypeError(`Invalid glTF spec/gloss ${n}; pass ${t} finite components from 0 to 1`);return Array.from(e,e=>o(e,n))},c=e=>{if(e!==void 0){if(!e||typeof e!=`object`||Array.isArray(e)||!Number.isSafeInteger(e.index)||e.index<0)throw TypeError(`Invalid glTF spec/gloss texture; pass a textureInfo with a nonnegative integer index`);return n(e),e}};function l(e=[1,1,1,1],t=[1,1,1],n=1){let r=s(e,4,`diffuse`),i=s(t,3,`specular`),a=e=>Math.sqrt(.299*e[0]**2+.587*e[1]**2+.114*e[2]**2),c=a(r),l=a(i),u=1-Math.max(...i),d=c*u/.96+l-.08,f=l<.04?0:Math.min(1,Math.max(0,(-d+Math.sqrt(d*d-.16*(.04-l)))/.08));return{baseColor:[...i.map((e,t)=>{let n=r[t]*u/(.96*Math.max(1-f,1e-6)),i=(e-.04*(1-f))/Math.max(f,1e-6);return Math.min(1,Math.max(0,n*(1-f*f)+i*f*f))}),r[3]],metallic:f,roughness:1-o(n,`glossiness`)}}function u(e){let t=e.extensions?.[a];if(t===void 0)return e;if(!t||typeof t!=`object`||Array.isArray(t))throw TypeError(`Invalid glTF spec/gloss extension; pass a material extension object`);let n=t,r=s(n.diffuseFactor===void 0?[1,1,1,1]:n.diffuseFactor,4,`diffuse`),i=s(n.specularFactor===void 0?[1,1,1]:n.specularFactor,3,`specular`),l=o(n.glossinessFactor===void 0?1:n.glossinessFactor,`glossiness`);return{...e,pbrMetallicRoughness:{baseColorFactor:r,baseColorTexture:c(n.diffuseTexture),roughnessFactor:l,metallicFactor:0},extensions:{...e.extensions,KHR_materials_specular:{specularColorFactor:i.map(e=>e*25),specularColorTexture:c(n.specularGlossinessTexture)},KHR_materials_ior:{ior:1.5}}}}var d=`
2
+ fn margoSpecGloss(d:vec3f,s:vec3f)->vec4f {
3
+ let weights=vec3f(0.299,0.587,0.114);
4
+ let db=sqrt(dot(d*d,weights)); let sb=sqrt(dot(s*s,weights));
5
+ let share=1-max(s.r,max(s.g,s.b)); let qb=db*share/0.96+sb-0.08;
6
+ let metal=select(clamp((-qb+sqrt(max(0.0,qb*qb-0.16*(0.04-sb))))/0.08,0.0,1.0),0.0,sb<0.04);
7
+ let bd=d*share/(0.96*max(1-metal,0.000001));
8
+ let bs=(s-vec3f(0.04*(1-metal)))/max(metal,0.000001);
9
+ return vec4f(clamp(mix(bd,bs,metal*metal),vec3f(0),vec3f(1)),metal);
10
+ }
11
+ `,f={extensions:[a],convert:u,parse(e){let t=r.parse(e);return e[a]===void 0?t:{features:{iridescence:!1,anisotropy:!1,diffuseTransmission:!1,...t?.features,specularGlossiness:!0},maps:t?.maps??Array(8).fill(void 0),rows:t?.rows??Array(24).fill(0)}},plan:e,shader(e){let n=t(e);if(!e.specularGlossiness)return n;let r=e.slots[12],a=r>=0?`textureSample(margoMap${r},margoSampler${r},uv(i,12)).a`:`1.0`,o=` return s;`;if(n.split(o).length!==2)throw i(`failed`,`Spec/gloss surface conversion anchor changed; update the optional material shader`);return d+n.replace(o,`
12
+ if(f.ext.x<0.5){
13
+ let converted=margoSpecGloss(s.base.rgb,s.f0);
14
+ s.base=vec4f(converted.rgb,s.base.a); s.metal=converted.a;
15
+ s.roughness=clamp(1-f.factors.x*${a},0.045,1.0);
16
+ s.f0=vec3f(0.04); s.sw=1;
17
+ }
18
+ ${o}`)}};export{u as convertSpecGlossMaterial,f as specGlossMaterials,l as specGlossToMetalRough};
@@ -0,0 +1,7 @@
1
+ import type { GLTFDocument } from './shared/gltf.js';
2
+ /** True for a mesh primitive whose data is Gaussian splats (KHR_gaussian_splatting). */
3
+ export declare const isSplatPrimitive: (primitive: {
4
+ extensions?: unknown;
5
+ } | undefined) => boolean;
6
+ /** True when any mesh of the file holds Gaussian splats. */
7
+ export declare const hasSplats: (doc: GLTFDocument) => boolean;
@@ -0,0 +1,18 @@
1
+ // @ts-ignore optional peer: its types apply when it is installed
2
+ import type { SplatData } from '@margoengine/splats/data';
3
+ import type { GLTFPrimitive } from './shared/gltf.js';
4
+ import type { GLTFAsset, GLTFSplatReader } from './asset.js';
5
+ /**
6
+ * The splats of mesh primitive `primitive`, in the primitive's local space, as `SplatData` for @margoengine/splats: its
7
+ * glTF attributes or its KHR_gaussian_splatting_compression_spz_2 payload. Needs no GPU.
8
+ * @throws TypeError when the primitive breaks the extension's rules, RangeError on values @margoengine/splats refuses,
9
+ * MargoError `'unsupported'` for a kernel or colour space the extension does not define.
10
+ */
11
+ export declare function readGaussianSplats(asset: GLTFAsset, primitive: GLTFPrimitive, _arg0?: {
12
+ signal?: AbortSignal;
13
+ }): Promise<SplatData>;
14
+ /**
15
+ * The reader `loadGLTF` and `parseGLTFAsync` import when a file holds splats: each primitive read, placed by its node's
16
+ * world matrix, the clouds of the file merged so that they sort together, in clouds of at most 3,000,000 splats.
17
+ */
18
+ export declare const gaussianSplats: GLTFSplatReader;
package/dist/splats.js ADDED
@@ -0,0 +1 @@
1
+ import{t as e}from"./scene-scope-CZDEkd24.js";import{margoError as t}from"@margoengine/core/extension";var n=`KHR_gaussian_splatting`,r=`KHR_gaussian_splatting_compression_spz_2`,i=5126,a=[3,5,7],o=3e6,s=.2820947917738781,c=[[i,!1],[5120,!0],[5122,!0]],l=[[i,!1],[5121,!1],[5121,!0],[5123,!1],[5123,!0]],u=[[i,!1],[5121,!0],[5123,!0]],d=[[i,!1]],f=e=>/* @__PURE__ */ TypeError(`Invalid glTF ${n} ${e}; the file is not valid, re-export it and check it with the glTF Validator`),p=e=>e.catch(e=>{throw t(`unsupported`,`${n} needs @margoengine/splats (${e instanceof Error?e.message:e}): install it, or pass decoders: {splats: false} for the point cloud fallback`)});function m(e,t,n,r,i,a){let o=t[n];if(o===void 0)throw f(`primitive: ${n} is missing`);let s=e.doc.accessors?.[o];if(!i.some(([e,t])=>e===s?.componentType&&t===!!s?.normalized))throw f(`accessor for ${n}: componentType ${s?.componentType}${s?.normalized?` normalized`:``}`);let c=e.accessor(o,r);if(s?.count!==a)throw f(`accessor for ${n}: its count differs from POSITION`);return c}async function h(e,i,{signal:o}={}){let s=i.extensions?.[n],h=i.attributes??{};if(!s||typeof s!=`object`||Array.isArray(s))throw f(`extension`);if(i.mode!==0)throw f(`primitive: its mode must be POINTS`);let{kernel:g=`ellipse`,colorSpace:_=`srgb_rec709_display`}=s;if(g!==`ellipse`)throw t(`unsupported`,`${n} kernel ${g} is not supported; re-export the file with "ellipse"`);if(_!==`srgb_rec709_display`&&_!==`lin_rec709_display`)throw t(`unsupported`,`${n} color space ${_} is not supported; re-export the file in rec709`);let{parseSpz:v,splatsFromAttributes:y}=await p(import(`@margoengine/splats/data`));o?.throwIfAborted();let b=s.extensions?.[r];if(b){if(_!==`srgb_rec709_display`)throw f(`primitive: SPZ colour is srgb_rec709_display`);return v(e.view(b.bufferView),{signal:o})}let x=e.accessor(h.POSITION,`VEC3`),S=x.length/3,C=(t,r,i)=>m(e,h,`${n}:${t}`,r,i,S),w=C(`ROTATION`,`VEC4`,c),T=C(`SCALE`,`VEC3`,l),E=C(`OPACITY`,`SCALAR`,u),D=C(`SH_DEGREE_0_COEF_0`,`VEC3`,d),O=[],k=!1;a.forEach((e,t)=>{let r=Array.from({length:e},(e,n)=>`SH_DEGREE_${t+1}_COEF_${n}`),i=r.filter(e=>`${n}:${e}`in h).length;if(i&&(i!==e||k))throw f(`primitive: spherical harmonics degree ${t+1}`);if(i)for(let e of r)O.push(C(e,`VEC3`,d));else k=!0});let A={count:S,positions:x,logScales:T.map(Math.log),rotations:new Float32Array(S*4),dc:D,alphas:E};for(let e=0;e<S;e++)A.rotations[e*4]=w[e*4+3],A.rotations.set(w.subarray(e*4,e*4+3),e*4+1);if(O.length){let e=new Float32Array(S*O.length*3);O.forEach((t,n)=>{for(let r=0;r<S;r++)e.set(t.subarray(r*3,r*3+3),(r*O.length+n)*3)}),A.rest=e}return y(A,{linear:_===`lin_rec709_display`})}var g=e=>e.sphericalHarmonics?e.sphericalHarmonics.length/(e.positions.length/3)/3:0;function _(e,t){let n=g(e);if(n===t)return e;let r=e.positions.length/3,i=new Float32Array(r*t*3);for(let a=0;a<r;a++)if(n)i.set(e.sphericalHarmonics.subarray(a*n*3,(a+1)*n*3),a*t*3);else for(let n=0;n<3;n++)i[a*t*3+n]=(e.colors[a*4+n]-.5)/s;return{...e,sphericalHarmonics:i}}function v({positions:e}){let t=new Float32Array([1/0,1/0,1/0,-1/0,-1/0,-1/0]);for(let n=0;n<e.length;n+=3)for(let r=0;r<3;r++)t[r]=Math.min(t[r],e[n+r]),t[r+3]=Math.max(t[r+3],e[n+r]);return t}var y={async attach(t,n,r,i){let a=e(t),{Splats:s,mergeSplats:c,transformSplats:l}=await p(import(`@margoengine/splats`)),u=[];for(let{primitive:e,matrix:t}of r)u.push(l(await h(n,e,{signal:i}),t));let d=Math.max(...u.map(g)),f=[],m=o;for(let e of u){let t=e.positions.length/3;m+t>o&&(f.push([]),m=0),f[f.length-1].push(d?_(e,d):e),m+=t}let y=[];try{for(let e of f){i?.throwIfAborted();let n=e.length>1?c(...e):e[0],r=new s(n);a.run(()=>t.use(r)),y.push({cloud:r,bounds:v(n)})}}catch(e){for(let{cloud:e}of y)e.dispose();throw e}return y}};export{y as gaussianSplats,h as readGaussianSplats};
@@ -0,0 +1,4 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const _=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import{t as e}from"./node-matrix-R9BipGnp.js";import{a as t,c as n,d as r,l as i,o as a,s as o,t as s,u as c}from"./version-B6NE5cJf.js";import{n as l,t as u}from"./limits-_LZ441oV.js";import{t as d}from"./scene-scope-CZDEkd24.js";import{n as f,r as p,t as m}from"./accessor-CU_1uSZ1.js";import{Geometry as h,PbrMaterial as g,engineRuntime as __margoRuntime,fault as v,margoError as y,rangeError as b,typeError as x}from"@margoengine/core/extension";var S=`version https://git-lfs`;function C(e,t){if(!(e.length<23)){for(let t=0;t<23;t++)if((typeof e==`string`?e.charCodeAt(t):e[t])!==S.charCodeAt(t))return;throw v(`failed`,`${t} is a Git LFS pointer file, not the asset; run git lfs pull and serve the real file`,`git-lfs`)}}var w=67108864,T=e=>y(`unsupported`,`${e} over the light loader's 64 MiB; use @margoengine/gltf/pbr (512 MiB by default) or loadAuto`),E=e=>!!e&&typeof e==`object`&&!Array.isArray(e);function D(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{throw x(`Invalid glTF JSON: not UTF-8`,`gltf-invalid`)}}function O(e){try{return c(e)}catch(e){throw x(`Invalid glTF JSON: ${e.message}`,`gltf-invalid`)}}function k(e){return e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function A(e){if(typeof e==`string`){if(C(e,`The glTF input`),e.length>w||new TextEncoder().encode(e).length>w)throw RangeError(`glTF JSON exceeds 64 MiB; load a smaller file or split it`);return{doc:O(e)}}if(!(e instanceof ArrayBuffer)&&!ArrayBuffer.isView(e))return{doc:e};let n=k(e);if(C(n,`The glTF input`),n.length>w)throw RangeError(`GLB exceeds 64 MiB; load a smaller file or split it`);let r=a(n),i=O(D(r[0].data)),o=r[1]?.type===5130562?r[1].data:void 0,s=i.buffers?.[0];return o&&s&&typeof s==`object`&&s.uri===void 0&&t(o.length,s.byteLength),{doc:i,binary:o}}function j(e){let t=/^data:application\/(?:octet-stream|gltf-buffer);base64,([A-Za-z0-9+/]*={0,2})$/.exec(e);if(!t||t[1].length>89478489.33333333)throw TypeError(`Invalid glTF data URI; use a base64 data URI`);let n;try{n=atob(t[1])}catch{throw TypeError(`Invalid glTF data URI; use a base64 data URI`)}return Uint8Array.from(n,e=>e.charCodeAt(0))}function M(e,t,n){let r=l(`maxNodes`,t);if(!e||!s(e.asset))throw TypeError(`Expected glTF 2.0`);for(let t of[`buffers`,`bufferViews`,`accessors`,`meshes`,`nodes`,`scenes`,`materials`,`skins`,`animations`,`extensionsRequired`])if(e[t]!==void 0&&!Array.isArray(e[t]))throw TypeError(`glTF ${t} must be an array`);for(let t of[`buffers`,`bufferViews`,`accessors`,`meshes`,`nodes`,`scenes`,`materials`]){let n=e[t];if(Array.isArray(n)&&!n.every(E))throw x(`Invalid glTF ${t} entry`,`gltf-invalid`)}if(e.extensionsRequired?.some(e=>!n.some(t=>t.handles.includes(e)))||e.skins?.length||e.animations?.length)throw v(`unsupported`,`Skins, animations and required extensions need @margoengine/gltf/pbr`,`gltf-light`);u(`Too many glTF nodes`,e.nodes?.length??0,r,`maxNodes`)}function N(e,t){for(let[n,r]of[[`translation`,3],[`rotation`,4],[`scale`,3]]){let i=e[n];if(i!==void 0&&(!Array.isArray(i)||i.length!==r||i.some(e=>typeof e!=`number`||!Number.isFinite(Math.fround(e)))))throw x(`Invalid glTF ${n} on node ${t}: ${r} finite numbers`,`gltf-transform`)}}function P(t,n,r){if(n.matrix!==void 0){if(n.translation!==void 0||n.rotation!==void 0||n.scale!==void 0||!Array.isArray(n.matrix)||n.matrix.length!==16||n.matrix.some(e=>typeof e!=`number`||!Number.isFinite(Math.fround(e))))throw x(`Invalid glTF matrix`,`gltf-invalid`);let i=n.matrix;if(i[3]!==0||i[7]!==0||i[11]!==0||i[15]!==1)throw TypeError(`glTF matrix must be affine`);let a=e(i);if(!a.ok)throw a.reason===`singular`?/* @__PURE__ */ RangeError(`Singular glTF matrix`):x(`Sheared glTF matrix on node ${r}`,`gltf-transform`);t.setPosition(a.position).setScale(a.scale).setQuaternion(a.rotation)}else N(n,r),t.setPosition(n.translation??[0,0,0]).setScale(n.scale??[1,1,1]).setQuaternion(n.rotation??[0,0,0,1])}var F=(e,t)=>e.some(e=>e.handles.some(e=>t?.extensions?.[e]!==void 0)),I=(e,t,n,r)=>{let i=e.buffers[t];if(n.some(e=>e.handles.some(e=>i.extensions?.[e]?.fallback===!0)))return!0;let a=(e.bufferViews??[]).filter(e=>e.buffer===t);return!r&&i.uri===void 0&&a.length>0&&a.every(e=>F(n,e))};function L(e,t,{maxNodes:n,extensions:r=[]}){let{doc:i,binary:a}=A(e);M(i,n,r);let o=0;return{doc:i,buffers:(i.buffers??[]).map((e,n)=>{let s=f(e.byteLength,`buffer length`,1);if(I(i,n,r,(t[n]?.byteLength??0)>0||n===0&&!!a&&!e.uri))return/* @__PURE__ */ new Uint8Array;let c=t[n]?k(t[n]):e.uri?j(e.uri):n===0?a:void 0;if(!c||s>c.length)throw RangeError(`Truncated glTF buffer; download the file again, it is incomplete`);if(o+=c.length,o>w)throw T(`glTF buffers are`);return c.subarray(0,s)}),maxNodes:n}}function R(e,t,{maxNodes:n,extensions:r=[]}){let i=_(e);for(let e of r)e.read?.(t);let{doc:a}=t;r.length&&M(a,n,r);let o=0,s=(e,n)=>{for(let i of r){let r=i.attribute?.(t,e,f(n,`accessor`));if(r)return r}return p(t,n,3,e=>!e.normalized&&e.type===`VEC3`&&e.componentType===5126)},c=[],l=e=>{let t=e.pbrMetallicRoughness??{},n=t.baseColorFactor??[1,1,1,1];if((e.alphaMode??`OPAQUE`)!==`OPAQUE`||!Array.isArray(n)||n.length!==4||e.emissiveFactor!==void 0&&(!Array.isArray(e.emissiveFactor)||e.emissiveFactor.some(e=>e!==0))||e.extensions||[t.baseColorTexture,t.metallicRoughnessTexture,e.normalTexture,e.occlusionTexture,e.emissiveTexture].some(Boolean))throw v(`unsupported`,`Maps, emission and transparency need @margoengine/gltf/textured or gltf/pbr`,`gltf-light`);return new g({color:n.slice(0,3),roughness:t.roughnessFactor??1,metalness:t.metallicFactor??1,doubleSided:e.doubleSided??!1})},u=(a.meshes??[]).map(e=>{if(!Array.isArray(e.primitives)||!e.primitives.length||!e.primitives.every(E))throw x(`Missing glTF primitives`,`gltf-invalid`);return e.primitives.flatMap(e=>{if(e.attributes?.POSITION===void 0)return[];if((e.mode??4)!==4||e.targets||e.extensions||Object.keys(e.attributes??{}).some(e=>/^(COLOR|JOINTS|WEIGHTS)_/.test(e)))throw v(`unsupported`,`Points, lines, morphs, skins and vertex colours need @margoengine/gltf/pbr`,`gltf-light`);let n=s(`POSITION`,e.attributes?.POSITION),r=e.attributes?.NORMAL===void 0?null:s(`NORMAL`,e.attributes.NORMAL),i=e.indices===void 0?Uint32Array.from({length:n.length/3},(e,t)=>t):p(t,e.indices,1,e=>!e.normalized&&e.type===`SCALAR`&&[5121,5123,5125].includes(e.componentType),!0);if(i.length%3)throw RangeError(`Indices must contain complete triangles`);let u=r?void 0:i;if(o+=r?n.length/3:i.length,o>1e6)throw v(`unsupported`,`glTF exceeds one million vertices, the light loader limit`,`gltf-light`);if(!r){let e=new Float32Array(i.length*3);r=new Float32Array(e.length);for(let t=0,r=n.length/3;t<i.length;t++){let a=i[t];if(a>=r)throw RangeError(`Index exceeds vertices; load a smaller file or split it`);e[t*3]=n[a*3],e[t*3+1]=n[a*3+1],e[t*3+2]=n[a*3+2]}for(let t=0;t<e.length;t+=9){let n=e,i=n[t+3]-n[t],a=n[t+4]-n[t+1],o=n[t+5]-n[t+2],s=n[t+6]-n[t],c=n[t+7]-n[t+1],l=n[t+8]-n[t+2],u=a*l-o*c,d=o*s-i*l,f=i*c-a*s;for(let e=t;e<t+9;e+=3)r[e]=u,r[e+1]=d,r[e+2]=f}n=e,i=new Uint32Array(e.length/3);for(let e=0;e<i.length;e++)i[e]=e}let d=e.material===void 0?new g({color:[1,1,1],roughness:1,metalness:1,doubleSided:!1}):a.materials?.[f(e.material,`material reference`)]&&(c[e.material]??=l(a.materials[e.material]));if(!d)throw x(`Missing glTF material`,`gltf-invalid`);return[{geometry:new h(n,r,i),material:d,source:e,expanded:u}]})}),d=a.nodes??[],y=new Int32Array(d.length).fill(-1);d.forEach((e,t)=>{if(!e||e.skin!==void 0||e.camera!==void 0||e.extensions)throw v(`unsupported`,`Unsupported glTF node for the light loader`,`gltf-light`);if(e.children!==void 0&&!Array.isArray(e.children))throw x(`Invalid glTF children`,`gltf-invalid`);for(let n of e.children??[]){let e=f(n,`child reference`);if(e>=d.length||y[e]!==-1||e===t)throw x(`Invalid glTF hierarchy`,`gltf-transform`);y[e]=t}});for(let e=0;e<d.length;e++){let t=0;for(let n=e;n!==-1;n=y[n])if(++t>d.length)throw x(`glTF hierarchy cycle through node ${e}`,`gltf-transform`);if(t>62)throw b(`glTF node ${e} is ${t} levels deep, past 62`,`gltf-transform`)}let S=a.scenes?m(a.scenes,a.scene??0,`scene`).nodes??[]:d.map((e,t)=>t).filter(e=>y[e]===-1);if(!Array.isArray(S)||new Set(S).size!==S.length)throw x(`Invalid glTF scene roots`,`gltf-invalid`);let C=[],w=[],T=[],D=[],O;try{let e=i.createMesh();C.push(e);let n=S.map(t=>({id:f(t,`root`),parent:e})).reverse();for(;n.length;){let{id:t,parent:r}=n.pop(),a=m(d,t,`node`);if(r===e&&y[t]!==-1)throw x(`glTF scene root has a parent`,`gltf-transform`);let o=i.createMesh(r);if(C.push(o),T.push(o),D[t]=o,o.name=typeof a.name==`string`?a.name:``,P(o,a,t),a.mesh!==void 0){let e=u[f(a.mesh,`mesh reference`)];if(!e)throw x(`Missing glTF mesh`,`gltf-invalid`);for(let t of e){let e=i.createMesh(o);C.push(e),e.setGeometry(t.geometry).setMaterial(t.material),w.push(e)}}let s=a.children??[];for(let e=s.length-1;e>=0;e--)n.push({id:s[e],parent:o})}if(!w.length&&!r.some(e=>e.allowEmptyScene))throw v(`failed`,`glTF contains no renderable meshes`,`gltf-light`);let a=()=>{for(let e=C.length-1;e>=0;e--)C[e].dispose()};O={root:e,meshes:w,nodes:T,warnings:[],dispose:a,[Symbol.dispose??Symbol()]:a};for(let e of r)e.finish?.(O,t,{engine:i,primitives:u.flat(),nodes:D});return O}catch(e){if(O)O.dispose();else for(let e=C.length-1;e>=0;e--)C[e].dispose();throw e}}async function z(e,t,n,r,i){let a=n.extensions??[],o=[];try{for(let e of a)o.push(e),await e.load?.(t,r),r?.throwIfAborted();return i.run(()=>R(e,t,n))}catch(e){for(let e of o)e.abandon?.(t);throw e}}function B(e,t,n=[],r={}){if(r.extensions?.some(e=>e.load))throw y(`unsupported`,`This glTF extension loads asynchronously; use parseGLTFAsync or loadGLTF`);return R(e,L(t,n,r),r)}async function V(e,t,n=[],{signal:r,...i}={}){return r?.throwIfAborted(),z(e,L(t,n,i),i,r,d(e))}async function H(e,t,{signal:a,maxNodes:s,allowedURLs:c,extensions:l=[],fetch:u=globalThis.fetch}={}){a?.throwIfAborted();let f=d(e),p=new URL(t,globalThis.location?.href),m=0;async function h(e,t=!1){if(![`http:`,`https:`].includes(e.protocol))throw x(`glTF URL must use HTTP(S)`,`gltf-url`);let n=await u(e,{signal:a});t&&n.url?p=new URL(n.url):t||i(n,p,c,`glTF buffer`);let o=await r(n,{maxBytes:w-m,signal:a,label:`glTF download`}).catch(e=>{throw e instanceof RangeError?T(`glTF download is`):e});if(C(o,e.href),(m+=o.byteLength)>w)throw T(`glTF download is`);return o}let g=await h(p,!0),{doc:_,binary:v}=A(o(g)?g:D(g));M(_,s,l);let y=[];for(let[e,t]of(_.buffers??[]).entries())if(I(_,e,l,e===0&&!t.uri&&!!v))y.push(/* @__PURE__ */ new Uint8Array);else if(!t.uri)y.push(e===0&&v||/* @__PURE__ */ new Uint8Array);else if(typeof t.uri==`string`&&t.uri.startsWith(`data:`)){let e=j(t.uri);if(m+=e.length,m>w)throw T(`glTF download is`);y.push(e)}else y.push(await h(n(t.uri,p,c,`glTF buffer`)));a?.throwIfAborted();let b={maxNodes:s,extensions:l},S=L(_,y,b);return S.fetch=e=>h(n(e,p,c,`glTF image`)),z(e,S,b,a,f)}export{C as i,B as n,V as r,H as t};
@@ -0,0 +1 @@
1
+ import{a as e,c as t,d as n,l as r}from"./version-B6NE5cJf.js";import{t as i}from"./accessor-DuqjpuxI.js";import"./image-limit-DvFSfR5T.js";import{A as a,C as o,O as s,T as c,a as l,b as u,c as d,h as f,i as p,m,t as h,u as g,v as _,y as v}from"./asset-DN3ocEdY.js";import{a as y,o as b,r as x,t as S}from"./pack-DdxRO8k6.js";import{margoError as C}from"@margoengine/core/extension";function w(e,t){let n=f(e.bufferViews,t,`bufferView`),r=n.extensions?.EXT_meshopt_compression??n.extensions?.KHR_meshopt_compression,i=r??n;return{buffer:i.buffer,offset:i.byteOffset??0,length:i.byteLength,packed:!!r}}var T=1<<20,E=262144,D=4;function O(e,t,n){let r=[],i=!1;for(let a=0;a<e.length;a+=2){let o=e[a],s=e[a+1];s<t?r.push(o,s):o>n?(i||=(r.push(t,n),!0),r.push(o,s)):(t=Math.min(t,o),n=Math.max(n,s))}i||r.push(t,n),e.length=0;for(let t of r)e.push(t)}function k(e,t,n){let r=[];for(let i=0;i<e.length&&t<n;i+=2)if(!(e[i+1]<=t)){if(e[i]>=n)break;e[i]>t&&r.push([t,e[i]]),t=Math.max(t,e[i+1])}return t<n&&r.push([t,n]),r}var A=(e,t,n)=>!k(e,t,n).length,j=e=>{let{name:t=`Error`,code:n}=e??{};return{name:t,message:e instanceof Error?e.message:String(e),...typeof n==`string`?{code:n}:{}}},M=class{constructor(e,t,n,r=p,i,o,s=!1,c=a,l={}){this.url=e,this.post=t,this.signal=n,this.limit=r,this.maxNodes=i,this.allowedURLs=o,this.textures=s,this.partVertices=c,this.decoders=l,this.sources=[],this.map=[],this.needs=[],this.posted=/* @__PURE__ */ new Set,this.waiters=[],this.inflight=0,this.pending=0,this.loaded=0,this.reported=0,this.decoding=Promise.resolve(),this.base=e,n.addEventListener(`abort`,()=>this.notify(),{once:!0})}setOrder(e){this.order=e,this.notify()}notify(){for(let e of this.waiters.splice(0))e()}async next(){if(await new Promise(e=>this.waiters.push(e)),this.signal.throwIfAborted(),this.failure)throw this.failure}async run(){try{let e=await this.head();if(l(e),s(e)||e.meshes?.some(e=>e?.primitives?.some(e=>(e?.mode??4)<4))||e.textures?.some(e=>e?.extensions?.MSFT_texture_dds)||!this.textures&&(e.textures?.some(e=>e?.extensions?.KHR_texture_basisu)||e.images?.some(e=>e?.mimeType===`image/ktx2`))||!this.decoders.draco&&e.meshes?.some(e=>e?.primitives?.some(e=>e?.extensions?.KHR_draco_mesh_compression))){this.post({type:`fallback`});return}for(this.post({type:`doc`,doc:e}),this.buffers(e),await this.asset.prepareMeshopt();!this.order;)await this.next();await this.geometry(e),await this.images(e);for(let[e,t]of this.sources.entries())if(t.ranged!==!1){let n=k(t.asked,0,t.data.length);for(let t=0;t<n.length;){let r=n[t][0],i=n[t++][1];for(;t<n.length&&n[t][0]-i<=E;)i=n[t++][1];this.request(e,r,i)}}for(;this.inflight||this.sources.some(e=>!A(e.got,0,e.data?.length??0));)await this.next();this.bytes(!0);let t=new Map(S(this.asset)),n=[];y(e).forEach((e,r)=>{let i=c.get(this.asset)?.get(e);if(!i)return;n.push([r,i]);let a=e.extensions.KHR_draco_mesh_compression;for(let n of[...Object.keys(a.attributes).map(t=>e.attributes[t]),e.indices])n!==void 0&&t.set(n,this.asset.accessor(n))}),this.post({type:`done`,buffers:this.asset.buffers,accessors:[...t],...n.length?{draco:n}:{}})}catch(e){this.signal.aborted||this.post({type:`error`,error:j(e)})}}bytes(e=!1){let t=Date.now();!e&&t-this.reported<100||(this.reported=t,this.post({type:`bytes`,loaded:this.loaded,total:this.sources.reduce((e,t)=>e+(t.size??0),0)}))}fetch(e,t,n=!1){if(![`http:`,`https:`].includes(e.url.protocol))throw TypeError(`glTF URL must use HTTP(S); for a blob: or file: source, read its bytes (await file.arrayBuffer()) and pass them to parseGLTFAsync`);return fetch(e.url,{signal:this.signal,headers:t}).then(e=>{if(n||r(e,this.base,this.allowedURLs,`glTF`),!e.ok)throw C(`failed`,`glTF download request failed: HTTP ${e.status}; check the URL and that the server allows the request`);return e})}allocate(e,t){if(!Number.isSafeInteger(t)||t>this.limit-this.sources.reduce((e,t)=>e+(t.data?.length??0),0))throw _(`glTF exceeds download budget`,this.limit);e.data=new Uint8Array(t),e.size??=t}async read(e,t,n,r={left:0}){let i=t.body.getReader(),a=()=>i.cancel().catch(()=>{});this.signal.addEventListener(`abort`,a,{once:!0});try{for(;;){let{done:t,value:o}=await i.read();if(this.signal.throwIfAborted(),t)break;let s=e.data.length-n,c=o.length>s?o.subarray(0,s):o;e.data.set(c,n),O(e.got,n,n+c.length),this.loaded+=c.length,n+=c.length;let l=Math.min(c.length,r.left);if(r.left-=l,this.pending-=l,this.bytes(),this.notify(),n>=e.data.length){a();break}}}finally{this.signal.removeEventListener(`abort`,a)}}async head(){let e={url:this.url,got:[],asked:[]};this.sources.push(e);let t=await this.fetch(e,{Range:`bytes=0-65535`},!0),r=/^bytes 0-\d+\/(\d+|\*)$/.exec(t.headers.get(`content-range`)??``),i=r&&r[1]!==`*`?Number(r[1]):void 0;t.url&&(e.url=this.base=new URL(t.url)),e.ranged=t.status===206&&!!r;let a=t.body.getReader(),o=[],s=0;for(;s<12;){let{done:e,value:t}=await a.read();if(e)break;o.push(t),s+=t.length}let c=new Uint8Array(s);o.reduce((e,t)=>(c.set(t,e),e+t.length),0);let l=new DataView(c.buffer);if(s<12||l.getUint32(0,!0)!==1179937895){for(let e;!(e=await a.read()).done;)if(o.push(e.value),(s+=e.value.length)>this.limit)throw a.cancel().catch(()=>{}),_(`glTF JSON exceeds byte budget`,this.limit);let t=i===void 0?s-1:s;e.ranged&&(i===void 0?s>=65536:i>s)&&o.push((await n(await this.fetch(e,{Range:`bytes=${t}-`}),{maxBytes:this.limit-t,signal:this.signal,label:`glTF JSON`}).catch(e=>{throw e instanceof RangeError?_(`glTF JSON exceeds byte budget`,this.limit):e})).subarray(s-t));let r=new Uint8Array(o.reduce((e,t)=>e+t.length,0));if(o.reduce((e,t)=>(r.set(t,e),e+t.length),0),this.loaded+=r.length,r.length>this.limit)throw _(`glTF JSON exceeds byte budget`,this.limit);return this.sources.length=0,u(r,e.url.href),v(r)}let d=l.getUint32(8,!0);if(l.getUint32(4,!0)!==2||d<20||i!==void 0&&i!==d)throw TypeError(`Invalid GLB header; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);this.allocate(e,d),e.data.set(c.subarray(0,d)),O(e.got,0,Math.min(s,d)),this.loaded+=s;let f=s,p=(async()=>{try{for(;;){let{done:t,value:n}=await a.read();if(this.signal.throwIfAborted(),t)break;let r=n.subarray(0,Math.max(0,d-f));e.data.set(r,f),O(e.got,f,f+r.length),this.loaded+=r.length,f+=r.length,this.bytes(),this.notify()}if(!e.ranged&&f<d)throw RangeError(`Truncated GLB; download the file again, it is incomplete`)}catch(e){this.failure??=e,this.notify()}})();if(O(e.asked,0,e.ranged?Math.min(65536,d):d),e.ranged&&(await p,!this.failure&&!A(e.got,0,Math.min(65536,d))))throw RangeError(`Truncated glTF range response; download the file again, it is incomplete`);let m=()=>new DataView(e.data.buffer).getUint32(12,!0),h=()=>Math.min(d,28+m());for(;!A(e.got,0,20);)await this.next();if(m()%4||20+m()>d||new DataView(e.data.buffer).getUint32(16,!0)!==1313821514)throw TypeError(`Invalid GLB chunk; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);if(e.ranged)for(let[t,n]of k(e.got,0,h()))this.request(0,t,n);for(;!A(e.got,0,h());)await this.next();return v(e.data.subarray(20,20+m()))}buffers(n){let r=this.sources[0],i=/* @__PURE__ */ new Map,a=0,o=0,s=0;if(r){let e=r.data,t=new DataView(e.buffer),n=20+t.getUint32(12,!0);n+8<=e.length&&A(r.got,n,n+8)&&t.getUint32(n+4,!0)===5130562&&(a=n+8,s=t.getUint32(n,!0),o=Math.min(s,e.length-a))}let c=(n.buffers??[]).map((n,c)=>{let l=n?.extensions;if((l?.EXT_meshopt_compression??l?.KHR_meshopt_compression)?.fallback===!0)return this.map.push({source:-1,offset:0}),/* @__PURE__ */ new Uint8Array;if(n?.uri===void 0)return c===0&&r&&o?(e(s,n.byteLength),this.map.push({source:0,offset:a}),r.data.subarray(a,a+o)):(this.map.push({source:-1,offset:0}),/* @__PURE__ */ new Uint8Array);if(typeof n.uri==`string`&&n.uri.startsWith(`data:`)){this.map.push({source:-1,offset:0});let e=m(n.uri,this.limit);return this.loaded+=e.length,e}let u=t(n.uri,this.base,this.allowedURLs,`glTF`).href,d=i.get(u);if(d===void 0){d=this.sources.length,i.set(u,d);let e={url:new URL(u),got:[],asked:[]};this.sources.push(e),this.allocate(e,Number.isSafeInteger(n.byteLength)&&n.byteLength>0?n.byteLength:0)}return this.map.push({source:d,offset:0}),this.sources[d].data}),{meshopt:l}=this.decoders;this.asset=new h(n,c,void 0,l?{meshopt:l}:{},this.limit,this.maxNodes),this.asset.partVertices=this.partVertices,this.needs=y(n).map(e=>{let t=[],r=e?.attributes??{},i=e?.extensions?.KHR_draco_mesh_compression;try{let a=[`POSITION`,`NORMAL`,`TANGENT`,`TEXCOORD_0`,`TEXCOORD_1`,...b(n,e)?[`TEXCOORD_2`,`TEXCOORD_3`]:[],`COLOR_0`];i&&this.whole(n,i.bufferView,t);for(let o of[...a.filter(e=>!(i?.attributes&&e in i.attributes)).map(e=>r[e]),i?void 0:e.indices])o!==void 0&&this.ranges(n,o,t)}catch{for(let[e,n]of this.map.entries())n.source>=0&&t.push([n.source,n.offset,n.offset+this.asset.buffers[e].length])}return t})}ranges(e,t,n){let r=f(e.accessors,t,`accessor`),a=i[r.componentType],o=d[r.type],s=r.count,c=(t,r,i)=>{if(w(e,t).packed)return this.whole(e,t,n);let a=f(e.bufferViews,t,`bufferView`),o=this.map[a.buffer],s=(a.byteOffset??0)+r,c=(a.byteOffset??0)+a.byteLength;if(!o||!Number.isSafeInteger(s)||s<0||!Number.isSafeInteger(c)||!(i>0))throw TypeError(`range; pass a { start, end } byte range`);let l=Math.min(s+i,c,this.asset.buffers[a.buffer].length);o.source>=0&&s<l&&n.push([o.source,o.offset+s,o.offset+l])};if(r.bufferView!==void 0&&c(r.bufferView,r.byteOffset??0,(s-1)*(f(e.bufferViews,r.bufferView,`bufferView`).byteStride??a*o)+a*o),r.sparse){let e=r.sparse.count;c(r.sparse.indices.bufferView,r.sparse.indices.byteOffset??0,e*i[r.sparse.indices.componentType]),c(r.sparse.values.bufferView,r.sparse.values.byteOffset??0,e*a*o)}}whole(e,t,n){let{buffer:r,offset:i,length:a}=w(e,t),o=this.map[r],s=i+a;if(!o||!Number.isSafeInteger(i)||i<0||!Number.isSafeInteger(s)||!(a>0))throw TypeError(`range; pass a { start, end } byte range`);let c=Math.min(s,this.asset.buffers[r].length);o.source>=0&&i<c&&n.push([o.source,o.offset+i,o.offset+c])}request(e,t,n){let r=this.sources[e],i={left:n-t};O(r.asked,t,n),this.inflight++,this.pending+=n-t,r.ranged===void 0&&(r.probing=!0),(async()=>{let e=await this.fetch(r,{Range:`bytes=${t}-${n-1}`}),a=/^bytes (\d+)-\d+\/(\d+|\*)$/.exec(e.headers.get(`content-range`)??``);if(e.status===206&&a&&+a[1]===t){if(r.ranged===void 0&&a[2]!==`*`&&+a[2]<r.data.length)throw RangeError(`Truncated glTF buffer; download the file again, it is incomplete`);if(r.ranged=!0,await this.read(r,e,t,i),!A(r.got,t,Math.min(n,r.data.length)))throw RangeError(`Truncated glTF range response; download the file again, it is incomplete`)}else if(r.ranged=!1,O(r.asked,0,r.data.length),await this.read(r,e,0,i),!A(r.got,0,r.data.length))throw RangeError(`Truncated glTF buffer; download the file again, it is incomplete`)})().catch(e=>{this.failure??=e}).finally(()=>{this.inflight--,this.pending-=i.left,r.probing=!1,this.notify()})}ready(e){return this.needs[e].every(([e,t,n])=>A(this.sources[e].got,t,n))}async geometry(e){let t=y(e);for(;;){if(this.failure)throw this.failure;let e=this.order.filter(e=>!this.posted.has(e));for(let n of e)this.ready(n)&&(this.posted.add(n),t[n]?.extensions?.KHR_draco_mesh_compression?this.decoding=this.decoding.then(()=>this.decompress(n,t[n])):this.pack(n,t[n]));if(this.order.every(e=>this.posted.has(e)))return this.decoding;let n=T,r=[];for(let t of e){if(this.inflight>=D||n<=0||this.pending>=T)break;for(let[e,i,a]of this.needs[t]){let t=this.sources[e];if(!(t.ranged===!1||t.probing)){for(let[o,s]of k(t.asked,i-i%E,Math.min(t.data.length,Math.ceil(a/E)*E)))if(r.push([e,o,s]),O(t.asked,o,s),n-=s-o,t.ranged===void 0){t.probing=!0;break}}}}r.sort((e,t)=>e[0]-t[0]||e[1]-t[1]);for(let e=0;e<r.length;){let[t,n,i]=r[e++];for(;e<r.length&&r[e][0]===t&&r[e][1]<=i;)i=Math.max(i,r[e++][2]);this.request(t,n,i)}r.length||await this.next()}}pack(e,t){try{x(this.asset,t,({vertices:t,indices:n,uvs:r,part:i})=>this.post({type:`geometry`,key:e,vertices:t,indices:n,uvs:r,...i?{part:i}:{}}))}catch(t){this.post({type:`geometry`,key:e,error:j(t)})}}async decompress(e,t){try{let{decompressPrimitive:e}=await import(`./compression-CUOCmjmE.js`);this.signal.throwIfAborted(),await e(this.asset,t,async()=>this.decoders.draco,this.signal),this.signal.throwIfAborted()}catch(t){this.signal.aborted||this.post({type:`geometry`,key:e,error:j(t)});return}this.pack(e,t)}async textureSource(e,n){if(n.bufferView===void 0){if(typeof n.uri!=`string`)throw TypeError(`Invalid glTF image; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);return n.uri.startsWith(`data:`)?{bytes:m(n.uri,this.limit)}:{url:t(n.uri,this.base,this.allowedURLs,`glTF`).href}}let r=w(e,n.bufferView),i=this.map[r.buffer];if(r.packed||this.asset.view(n.bufferView),i?.source>=0){let e=this.sources[i.source],t=i.offset+r.offset,n=t+r.length;for(;e.ranged===void 0;)e.probing||this.request(i.source,t,Math.min(n,t+1)),await this.next();if(e.ranged&&!r.packed)return O(e.asked,t,n),O(e.got,t,n),{url:e.url.href,offset:t,length:r.length};if(e.ranged)for(let[r,a]of k(e.asked,t,Math.min(n,e.data.length)))this.request(i.source,r,a);for(;!A(e.got,t,Math.min(n,e.data.length));)await this.next()}return{bytes:this.asset.view(n.bufferView).slice()}}async images(e){let r=y(e),i=[],a=e.images??[],s=t=>e.materials?.[t?.material],c=(e,t=[],n=0)=>{if(e&&typeof e==`object`&&n<8){let r=e.index;typeof r==`number`&&Number.isSafeInteger(r)&&r>=0&&t.push(r);for(let r of Object.values(e))c(r,t,n+1)}return t};for(let t of this.order)for(let n of c(s(r[t]))){let t=e.textures?.[n];for(let e of[t?.source,...Object.values(t?.extensions??{}).map(e=>e?.source)])Number.isInteger(e)&&!i.includes(e)&&i.push(e)}let l=[...i,...a.map((e,t)=>t).filter(e=>!i.includes(e))].filter(e=>e<a.length),u=0,d=this.textures?o(e):/* @__PURE__ */ new Set,f=async r=>{let i=a[r],o=i.mimeType===`image/ktx2`||/\.ktx2$/i.test(i.uri??``);if(o&&this.textures){this.post({type:`image`,index:r,source:await this.textureSource(e,i)});return}if(o||d.has(r)){this.post({type:`image`,index:r});return}let s;if(i.bufferView!==void 0){let t=w(e,i.bufferView),n=this.map[t.buffer];if(t.packed||this.asset.view(i.bufferView),n?.source>=0){let e=this.sources[n.source],r=n.offset+t.offset,i=Math.min(r+t.length,e.data.length);if(e.ranged){let t=k(e.asked,r,i);for(let[e,r]of t)this.request(n.source,e,r)}for(;!A(e.got,r,Math.min(i,e.data.length));)e.ranged===void 0&&!e.probing&&this.request(n.source,r,i),await this.next()}s=this.asset.view(i.bufferView)}else if(typeof i.uri==`string`&&i.uri.startsWith(`data:`))s=m(i.uri,this.limit);else if(typeof i.uri==`string`){let e=await this.fetch({url:t(i.uri,this.base,this.allowedURLs,`glTF`),got:[],asked:[]});s=await n(e,{maxBytes:Math.max(0,this.limit-this.loaded),signal:this.signal,label:`glTF image`}).catch(e=>{throw e instanceof RangeError?_(`glTF exceeds download budget`,this.limit):e}),this.loaded+=s.length}else throw TypeError(`Invalid glTF image; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let c=await g(s,i.mimeType,r,this.signal);if(u+=c.width*c.height*4,c.width*c.height>67108864)throw`close`in c&&c.close(),RangeError(`glTF images exceed decoded size limit; load a smaller model, or reduce its textures and meshes`);if(u>this.limit*4)throw`close`in c&&c.close(),_(`glTF images exceed decoded size limit`,this.limit*4);this.post({type:`image`,index:r,image:c})},p=Array.from({length:D},async()=>{for(let e;(e=l.shift())!==void 0;)await f(e)});await Promise.all(p)}};export{M as GLTFStream};
@@ -0,0 +1,104 @@
1
+ import type { PrimitivePart } from './model.js';
2
+ import type { GLTFDecoderHooks, GLTFDocument, GLTFDracoDecodeOptions, GLTFStreamSource } from './asset.js';
3
+ /** An error as it crosses to the main thread; `code` keeps a MargoError's code. */
4
+ export type StreamError = {
5
+ name: string;
6
+ message: string;
7
+ code?: string;
8
+ };
9
+ export type StreamMessage = {
10
+ type: 'fallback';
11
+ } | {
12
+ type: 'doc';
13
+ doc: GLTFDocument;
14
+ } | {
15
+ type: 'geometry';
16
+ key: number;
17
+ vertices?: Float32Array;
18
+ indices?: Uint32Array;
19
+ uvs?: Float32Array;
20
+ /** Set on each part of a split primitive; parts arrive in order, one message each. */
21
+ part?: PrimitivePart;
22
+ error?: StreamError;
23
+ } | {
24
+ type: 'image';
25
+ index: number;
26
+ image?: ImageBitmap | import('./asset.js').GLTFPixelImage;
27
+ source?: GLTFStreamSource;
28
+ } | {
29
+ type: 'bytes';
30
+ loaded: number;
31
+ total: number;
32
+ } | {
33
+ type: 'done';
34
+ buffers: Uint8Array[];
35
+ accessors: [number, Float32Array][];
36
+ /** Decoded indices of each Draco primitive, by key. */
37
+ draco?: [number, Float32Array][];
38
+ }
39
+ /** From the worker script: a Draco stream for the main thread's decoder, answered by `{ draco: id, result }`. */
40
+ | {
41
+ type: 'draco';
42
+ id: number;
43
+ data: Uint8Array;
44
+ options: GLTFDracoDecodeOptions;
45
+ } | {
46
+ type: 'error';
47
+ error: StreamError;
48
+ };
49
+ /** The decoders a stream uses: Draco (the main thread's, for a worker) and a caller's own meshopt decoder. */
50
+ export type StreamDecoders = Pick<GLTFDecoderHooks, 'draco' | 'meshopt'>;
51
+ export declare class GLTFStream {
52
+ private readonly url;
53
+ private readonly post;
54
+ private readonly signal;
55
+ private readonly limit;
56
+ private readonly maxNodes?;
57
+ private readonly allowedURLs?;
58
+ private readonly textures;
59
+ private readonly partVertices;
60
+ private readonly decoders;
61
+ private order?;
62
+ private readonly sources;
63
+ private map;
64
+ private needs;
65
+ private asset?;
66
+ private readonly posted;
67
+ private waiters;
68
+ private failure;
69
+ private inflight;
70
+ /** Requested bytes not yet received: new batches wait until under BATCH, so bandwidth goes to the first keys. */
71
+ private pending;
72
+ private loaded;
73
+ private reported;
74
+ private base;
75
+ /** Draco primitives decode one after another here, while the requests go on. */
76
+ private decoding;
77
+ /**
78
+ * `limit`: maxDownloadBytes, already validated by the caller; `maxNodes`: the load's maxNodes; `textures`: KTX2 images
79
+ * stream on the main thread, so this reports where each one is and fetches none of it; `partVertices`: the load's
80
+ * maxPartVertices, already validated; `decoders`: what decodes Draco and, when given, meshopt.
81
+ */
82
+ constructor(url: URL, post: (message: StreamMessage) => void, signal: AbortSignal, limit?: number, maxNodes?: number | undefined, allowedURLs?: readonly string[] | undefined, textures?: boolean, partVertices?: number, decoders?: StreamDecoders);
83
+ /** Primitive keys still wanted, most important first (the main thread re-sends this as the camera moves). */
84
+ setOrder(order: number[]): void;
85
+ private notify;
86
+ private next;
87
+ run(): Promise<void>;
88
+ private bytes;
89
+ /** `root`: the model's own first request, whose final URL becomes the base; every other response must stay in it. */
90
+ private fetch;
91
+ private allocate;
92
+ private read;
93
+ private head;
94
+ private buffers;
95
+ private ranges;
96
+ private whole;
97
+ private request;
98
+ private ready;
99
+ private geometry;
100
+ private pack;
101
+ private decompress;
102
+ private textureSource;
103
+ private images;
104
+ }
@@ -0,0 +1 @@
1
+ var e=e=>typeof e==`number`&&Number.isFinite(e)&&e>0;function t(t,n){let r=n?.mode??4;if(r>3)return;let i=r===0?`points`:`lines`,a=n.extras,o=a?.[i===`points`?`pointSize`:`lineWidth`],s=a?.[i===`points`?`pointSizeUnits`:`lineWidthUnits`]??`pixels`;if(e(o)&&(s===`pixels`||s===`world`))return{kind:i,size:o,units:s,bentley:!1};let c=(n.material===void 0?void 0:t.materials?.[n.material])?.extensions?.[i===`points`?`BENTLEY_materials_point_style`:`BENTLEY_materials_line_style`]?.[i===`points`?`diameter`:`width`];return e(c)?{kind:i,size:c,units:`pixels`,bentley:!0}:void 0}var n=e=>!!e.meshes?.some(n=>n?.primitives?.some(n=>t(e,n)!==void 0));export{t as n,n as t};
@@ -0,0 +1,18 @@
1
+ import type { GLTFDocument, GLTFPrimitive } from './shared/gltf.js';
2
+ /** A point diameter or line width and its units. */
3
+ export interface StrokeWidth {
4
+ readonly kind: 'points' | 'lines';
5
+ readonly size: number;
6
+ readonly units: 'pixels' | 'world';
7
+ /** From a Bentley material style, which draws a point as a disc; false for the primitive's extras. */
8
+ readonly bentley: boolean;
9
+ }
10
+ /**
11
+ * The width primitive `p` of `doc` asks for, or undefined for a triangle primitive or one that asks for none. Extras
12
+ * come first, being the file's own value; a value that is not a positive finite number, or units other than `'pixels'`
13
+ * and `'world'` (absent means pixels), is not this convention's and is not read, as extras are application-specific
14
+ * (glTF 2.0 section 3.12).
15
+ */
16
+ export declare function strokeWidth(doc: GLTFDocument, p: GLTFPrimitive | undefined): StrokeWidth | undefined;
17
+ /** True when some primitive of `doc` asks for a width: the strokes reader then loads. */
18
+ export declare const hasStrokes: (doc: GLTFDocument) => boolean;
@@ -0,0 +1,12 @@
1
+ import type { GLTFStrokeReader } from './asset.js';
2
+ /**
3
+ * The key on the plugins this reader adds: scene writers of @margoengine/exporters skip them, as the model writes these
4
+ * points and lines itself, with their widths.
5
+ */
6
+ export declare const strokesKey: unique symbol;
7
+ /**
8
+ * The reader `loadGLTF` and `parseGLTFAsync` import when a file asks for a point or line width: each item drawn by a
9
+ * scene-wide `gltf-lines` or `gltf-points` plugin, following its node's world matrix and visibility.
10
+ */
11
+ export declare const wideStrokes: GLTFStrokeReader;
12
+ export { strokeWidth, type StrokeWidth } from './stroke-width.js';
@@ -0,0 +1 @@
1
+ import{t as e}from"./scene-scope-CZDEkd24.js";import{n as t}from"./stroke-width-B2cnYGgn.js";import{margoError as n}from"@margoengine/core/extension";var r=Symbol.for(`margoengine.gltf-strokes.v1`),i=`gltf-lines`,a=`gltf-points`,o=(e,t)=>t.catch(t=>{throw n(`unsupported`,`Wide glTF points and lines need ${e} (${t instanceof Error?t.message:t}): install it, or pass decoders: {strokes: false} to draw them 1 px wide`)});function s(e,t,i,a){let o=e.plugins.get(t);if(o){if(!(o instanceof a))throw n(`state`,`A plugin named "${t}" is not gltf/pbr's; remove it before loading wide glTF lines`);return o}let s=i();return Object.defineProperty(s,r,{value:!0}),e.use(s),s}function c(e,t,n){let r=t.length,i=new Float32Array(r*3),a=new Float32Array(r*4),o=!1;for(let s=0;s<r;s++){let r=t[s]*20;i[s*3]=e[r],i[s*3+1]=e[r+1],i[s*3+2]=e[r+2];for(let t=0;t<4;t++){let i=t===3&&!n?1:e[r+16+t];a[s*4+t]=i,i!==1&&(o=!0)}}return{positions:i,colors:o?a:null}}function l(e){if(e.length<4)return{order:e,mode:`segments`};let t=[e[0]];for(let n=1;n<e.length;n+=2){if(n>1&&e[n-1]!==e[n-2])return{order:e,mode:`segments`};t.push(e[n])}return t.length>3&&t[t.length-1]===t[0]?(t.pop(),{order:t,mode:`loop`}):{order:t,mode:`strip`}}var u=e=>e===`butt`||e===`round`||e===`square`,d=e=>typeof e==`boolean`,f=e=>typeof e==`number`&&Number.isFinite(e)&&e>=0,p={shape:e=>e===`square`||e===`round`,minPixelSize:f,maxPixelSize:f,edl:d,adaptiveSize:f,alphaTest:e=>f(e)&&e<=1,blending:e=>e===`normal`||e===`additive`,depthTest:d,depthWrite:d,fog:d};function m(e,t,n){let r={};for(let[i,a]of Object.entries(t)){let t=n[`${e}${i[0].toUpperCase()}${i.slice(1)}`];a(t)&&(r[i]=t)}return r}function h(e){let t=m(`point`,p,Object(e));return Number(t.minPixelSize??1)>Number(t.maxPixelSize??256)&&(delete t.minPixelSize,delete t.maxPixelSize),t}var g={join:e=>e===`miter`||e===`round`||e===`bevel`,cap:u,miterLimit:e=>f(e)&&e>=1,onTop:d,antialias:d,depthWrite:d,depthBias:e=>f(e)&&e<1,behind:d,alphaToCoverage:d,fog:d};function _(e){let t=Object(e),n=m(`line`,g,t),r=t.lineDash;if(Array.isArray(r)&&r.length===2&&f(r[0])&&r[0]>0&&f(r[1])){let{lineDashOffset:e,lineDashCap:i}=t;Object.assign(n,{dashed:!0,dashSize:r[0],gapSize:r[1]}),Number.isFinite(e)&&(n.dashOffset=e),u(i)&&(n.dashCap=i)}return n}function v(e,t){if(!e)return;let n=Float32Array.from(t,t=>e[t]);if(n.some(e=>!Number.isFinite(e)||e<0))throw RangeError(`Invalid glTF _WIDTH values; each must be finite and non-negative, re-export the file`);return n.every(e=>e===1)?void 0:n}var y={async attach(t,n,r){let i=e(t),a=n.some(e=>e.width.kind===`lines`),s=n.some(e=>e.width.kind===`points`),[c,l,u]=await Promise.all([a?o(`@margoengine/lines`,import(`@margoengine/lines`)):void 0,a?o(`@margoengine/lines`,import(`@margoengine/lines/stroke`)):void 0,s?o(`@margoengine/points`,import(`@margoengine/points`)):void 0]);r?.throwIfAborted();let d=[],f=()=>{for(let{owner:e,item:n}of d.splice(0)){e.remove(n);let r=e,i=t.sceneOf(e);!(r.lines??r.pointClouds)?.size&&i&&i.removePlugin(e.name)}};try{i.run(()=>{for(let e of n)d.push(...b(t,e,c,l,u))})}catch(e){throw f(),e}return{dispose:f}}};function b(e,t,n,r,o){let{width:u,vertices:d,indices:f,material:p,node:m}=t,g=p.alphaMode===`BLEND`,y=[p.base[0],p.base[1],p.base[2]],b=g?p.base[3]:1;if(u.kind===`lines`){let a=s(e,i,()=>new n.Lines({name:i}),n.Lines),{order:o,mode:p}=l(f),{positions:h,colors:x}=c(d,o,g),S=v(t.widths,o);if(o.length<2)return[];let C={positions:h,colors:x,mode:p,mesh:m,color:y,opacity:b,width:u.size,worldUnits:u.units===`world`,..._(t.extras)},w=S?new r.Stroke({...C,widths:S}):new n.Line(C);return[{owner:a,item:a.add(w)}]}let x=s(e,a,()=>new o.PointsPlugin({name:a}),o.PointsPlugin),{positions:S,colors:C}=c(d,f,g),w=v(t.widths,f),T=!(p.extensions&&`KHR_materials_unlit`in p.extensions);if(!f.length)return[];let E=new o.PointCloud({positions:S,colors:C??void 0,colorFormat:`float`,colorSpace:`linear`,sizes:w,material:{color:y,opacity:b,size:u.size,sizeUnits:u.units,shape:u.bentley?`round`:void 0,shading:T?`sphere`:`flat`,transparent:g,...h(t.extras)}});return E.attach(m),[{owner:x,item:x.add(E)}]}export{t as strokeWidth,r as strokesKey,y as wideStrokes};
@@ -0,0 +1,2 @@
1
+ function e(e){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`Invalid texture coordinates; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let t=e?.extensions?.KHR_texture_transform;if(t!==void 0&&(!t||typeof t!=`object`||Array.isArray(t)))throw TypeError(`Invalid KHR_texture_transform; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let n=t?.texCoord===void 0?e.texCoord===void 0?0:e.texCoord:t.texCoord;if(n!==0&&n!==1&&n!==2&&n!==3)throw RangeError(`Texture requires TEXCOORD_0 to TEXCOORD_3`);if(t===void 0)return{texCoord:n};let r=(e,t,n)=>{if(e===void 0)return t;if(!Array.isArray(e)||e.length!==2||Array.from(e).some(e=>typeof e!=`number`||!Number.isFinite(Math.fround(e))))throw TypeError(`Invalid texture transform `+n+`; re-export the file and check it with the glTF Validator`);return e},i=r(t.offset,[0,0],`offset`),a=r(t.scale,[1,1],`scale`),o=t.rotation===void 0?0:t.rotation;if(typeof o!=`number`||!Number.isFinite(Math.fround(o)))throw TypeError(`Invalid texture transform rotation; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);if(o===0&&i[0]===0&&i[1]===0&&a[0]===1&&a[1]===1)return{texCoord:n};let s=Math.cos(o),c=Math.sin(o);return{texCoord:n,transform:new Float32Array([s*a[0],c*a[1],i[0],0,-c*a[0],s*a[1],i[1],0])}}var t=[`f.coordsA.x`,`f.coordsA.y`,`f.coordsA.z`,`f.coordsA.w`,`f.coordsB.x`];function n(t,n,r){if(!t.some(e=>e?.extensions?.KHR_texture_transform!==void 0))return;let i=t.map(t=>t?.extensions?.KHR_texture_transform===void 0?void 0:e(t).transform);if(!i.some(Boolean))return;let a=n?.factors?.length??0;if(n?.factors!==void 0&&(!(n.factors instanceof Float32Array)||!a||a%4||n.factors.some(e=>!Number.isFinite(e))))throw TypeError(`Material extension factors require finite vec4 values`);let o=r;if(!o||o.source!==n||o.length!==a||i.some((e,t)=>!!e!=!!o.transforms[t])){let e=new Float32Array(a+i.filter(Boolean).length*8);o={extension:{...n,factors:e},source:n,length:a,transforms:i}}let s=o.extension,c=s.factors;Object.assign(s,n),s.factors=c;for(let e of[`wgsl`,`direct`,`ambient`,`output`,`lighting`,`declarations`,`textures`,`transmission`,`afterOpaque`])n?.[e]===void 0&&delete s[e];n?.factors&&c.set(n.factors);let l=a;for(let e of i)e&&(c.set(e,l),l+=8);return o.transforms=i,o}function r(e,t,n=!1){let r=0;for(let e=0;e<5;e++)t?.transforms[e]&&(r|=1<<e);let o=t?`${t.length}:${r}:${+!!t.source?.declarations?.includes(`fn materialUV(`)}:${+n}`:`-:${+n}`,s=i.get(e);s||(i.size>=64&&i.clear(),i.set(e,s=/* @__PURE__ */ new Map));let c=s.get(o);return c===void 0&&(s.size>=64&&s.clear(),s.set(o,c=a(e,t,n))),c}var i=/* @__PURE__ */ new Map;function a(e,n,r){if(n){let r=n.length/4;for(let i=0;i<5;i++)n.transforms[i]&&(e=e.replaceAll(`uv(i,`+t[i]+`)`,`materialUV(uv(i,${t[i]}),materialFactors[${r}],materialFactors[${r+1}])`),r+=2);n.source?.declarations?.includes(`fn materialUV(`)||(e=`fn materialUV(p:vec2f,a:vec4f,b:vec4f)->vec2f{return vec2f(dot(a.xy,p)+a.z,dot(b.xy,p)+b.z);}
2
+ `+e)}return(r||n?.transforms[2])&&(e=e.replace(`if(abs(i.tangent.w)<0.5)`,`if(true)`)),e}export{r as n,e as r,n as t};
@@ -0,0 +1,26 @@
1
+ import type { GLTFTextureInfo } from './shared/gltf.js';
2
+ import type { MaterialExtension } from './material-extension.js';
3
+ /** A glTF UV set a texture may read: TEXCOORD_0 to TEXCOORD_3. */
4
+ export type UVSet = 0 | 1 | 2 | 3;
5
+ /** glTF texture coordinates: scale, then rotation about the origin, then offset. */
6
+ export interface TextureTransform {
7
+ offset?: readonly [number, number];
8
+ rotation?: number;
9
+ scale?: readonly [number, number];
10
+ texCoord?: UVSet;
11
+ }
12
+ /** A texture's UV set and, with KHR_texture_transform, its affine rows; throws on invalid values or a fifth UV set. */
13
+ export declare function textureCoordinates(info: Pick<GLTFTextureInfo, 'texCoord' | 'extensions'>): {
14
+ texCoord: UVSet;
15
+ transform?: Float32Array;
16
+ };
17
+ export declare const textureTransformWGSL = "fn materialUV(p:vec2f,a:vec4f,b:vec4f)->vec2f{return vec2f(dot(a.xy,p)+a.z,dot(b.xy,p)+b.z);}\n";
18
+ export interface CoordinateExtension {
19
+ extension: MaterialExtension;
20
+ source?: MaterialExtension;
21
+ length: number;
22
+ transforms: readonly (Float32Array | undefined)[];
23
+ }
24
+ /** Append affine rows to the optional slot without changing caller-owned factors. */
25
+ export declare function coordinateExtension(maps: readonly (GLTFTextureInfo | undefined)[], source?: MaterialExtension, previous?: CoordinateExtension): CoordinateExtension | undefined;
26
+ export declare function coordinateShader(code: string, coordinates?: CoordinateExtension, normalUV1?: boolean): string;
@@ -0,0 +1,4 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const t=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import{r as e}from"./texture-coordinates-XFsEMdU6.js";import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";import{KTX2Streamer as n,colorTwin as r}from"@margoengine/decoders/ktx2-stream";var i=4096;function a(e,t,n){let r=[1/0,1/0,1/0],a=[-1/0,-1/0,-1/0];for(let t=0;t<e.length;t+=20)for(let n=0;n<3;n++)r[n]=Math.min(r[n],e[t+n]),a[n]=Math.max(a[n],e[t+n]);let o=[0,1,2].map(e=>(r[e]+a[e])/2||0),s=Math.hypot(a[0]-r[0],a[1]-r[1],a[2]-r[2])/2||0,c=Math.floor(t.length/3),l=Math.max(1,Math.floor(c/i)),u=[0,0,0,0],d=0,f=(t,r,i)=>r<2?e[t*20+12+r*2+i]:n?.[t*4+(r-2)*2+i]??0;for(let n=0;n<c;n+=l){let r=t[n*3],i=t[n*3+1],a=t[n*3+2],o=r*20,s=i*20,c=a*20,l=e[s]-e[o],p=e[s+1]-e[o+1],m=e[s+2]-e[o+2],h=e[c]-e[o],g=e[c+1]-e[o+1],_=e[c+2]-e[o+2];d+=Math.hypot(p*_-m*g,m*h-l*_,l*g-p*h)/2;for(let e=0;e<4;e++){let t=f(r,e,0),n=f(r,e,1);u[e]+=Math.abs((f(i,e,0)-t)*(f(a,e,1)-n)-(f(a,e,0)-t)*(f(i,e,1)-n))/2}}return{centre:o,radius:s,spans:u.map(e=>e>0&&d>0?Math.sqrt(d/e):s*2)}}function o(e,t=0){return Math.max(Math.hypot(e[t],e[t+1],e[t+2]),Math.hypot(e[t+4],e[t+5],e[t+6]),Math.hypot(e[t+8],e[t+9],e[t+10]))}var s=.2,c=/* @__PURE__ */ new WeakMap,l=0,u=(e,t,n,r,i=0)=>[e[i]*t+e[i+4]*n+e[i+8]*r+e[i+12],e[i+1]*t+e[i+5]*n+e[i+9]*r+e[i+13],e[i+2]*t+e[i+6]*n+e[i+10]*r+e[i+14]];function d(e,t,n){let r=e.views?.length?e.views:[void 0],i=e.canvas.height,a=0;for(let o of r){let r=o?.camera??e.camera,s=r.planes,c=!0;if(s.some(e=>e!==0))for(let e=0;e<24;e+=4)s[e]*t[0]+s[e+1]*t[1]+s[e+2]*t[2]+s[e+3]<-n&&(c=!1);if(!c)continue;let l=r.position,u=Math.max(Math.hypot(t[0]-l[0],t[1]-l[1],t[2]-l[2])-n,r.near);a=Math.max(a,i/2/(u*Math.tan(r.fov*Math.PI/360)))}return a}var f=class{constructor(e,t){this.owner=e,this.source=t,this.streamed=!0,this.users=/* @__PURE__ */ new Set,this.width=1,this.height=1,this.wanted=0,this.views=/* @__PURE__ */ new Map}view(e,t){let n=this.stream;if(!n||this.owner.device!==e)return;let i=this.views.get(t);if(!i){let e=n.format.replace(/-srgb$/,``),a=t&&r(e)?r(e):e;this.views.set(t,i=n.texture.createView({format:a}))}return i}viewSize(){let e=this.stream?.texture;return e?{width:e.width,height:e.height,levels:e.mipLevelCount}:void 0}use(e){this.stream=e,this.width=e.width,this.height=e.height,e.onChange=()=>this.changed(),this.changed()}changed(){this.views.clear();for(let e of[...this.users])e.rebindStreamed(this)}drop(){this.stream?.dispose(),this.stream=void 0,this.views.clear()}close(){this.drop(),this.owner.forget(this)}},p=class r{static attach(e,t={},n){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));return new r(e,t,n)}constructor(e,n={},r=new AbortController().signal){this.options=n,this.signal=r,this.name=`gltf-pbr-textures-${++l}`,this.images=/* @__PURE__ */ new Set,this.models=/* @__PURE__ */ new Set,this.uses=/* @__PURE__ */ new WeakMap,this.since=0,this.closed=!1,this.engine=t(e),this.start();let i=this;this.engine.use(this.plugin={coreRequirement:/*@__PURE__*/__margoCoreRequirement("1.0.0",import.meta.url),name:this.name,setup(){},onPreUpdate(e){i.since+=e,i.since>=s&&i.update()},onDeviceRestored(){i.restart()}})}start(){this.streamer=new n({...this.options,device:this.engine.gpu,onError:e=>(this.options.onError??console.error)(e)})}get device(){return this.streamer.device}get budgetBytes(){return this.streamer.budgetBytes}set budgetBytes(e){this.streamer.budgetBytes=e}get usedBytes(){return this.streamer.usedBytes}get textures(){return[...this.images].flatMap(({stream:e,width:t,height:n,wanted:r})=>e?[{width:t,height:n,level:e.residentLevel,levels:e.levels,pixels:r}]:[])}async begin(e){let{source:t}=e,{streamer:n}=this,r={signal:this.signal,colorViews:!0},i=`bytes`in t?await n.open(t.bytes,r):await n.open(t.url,{...r,offset:t.offset,length:t.length});this.closed||!this.images.has(e)||n!==this.streamer?i.dispose():e.use(i)}async open(e){let t=new f(this,e);this.images.add(t);for(let e of this.models)t.users.add(e);return await this.begin(t),t}attach(e){this.models.add(e);for(let t of this.images)t.users.add(e);e.onDispose(()=>{this.models.delete(e),!this.models.size&&!this.images.size&&this.dispose()})}forget(e){this.images.delete(e),this.images.size||this.dispose()}mapsOf(t,n,r){let i=this.uses.get(r);return i||(i=r.maps.flatMap(r=>{let i=r&&n.textures?.[r.index],a=i?.extensions?.KHR_texture_basisu?.source??i?.source,o=a===void 0?void 0:t.images[a];if(!(o instanceof f))return[];let{texCoord:s,transform:c}=e(r);return[{image:o,set:s,repeat:(c?Math.min(Math.hypot(c[0],c[4]),Math.hypot(c[1],c[5])):1)||1}]}),r.maps.some(Boolean)&&this.uses.set(r,i)),i}measure(e,t){let n=this.mapsOf(e,e.asset.doc,t.material);if(!n.length)return;let r=c.get(t.vertices);r||c.set(t.vertices,r=a(t.vertices,t.indices,t.uvs));let{centre:i,radius:s,spans:l}=r,f=t.node.matrix,p=o(f),m=(e,t)=>{let r=d(this.engine,e,s*t)*t;for(let e of n)e.image.wanted=Math.max(e.image.wanted,r*(l[e.set]??0)/e.repeat)},h=t.instances;if(!h)m(u(f,...i),p);else for(let e=0,t=h.count;e<t;e++)m(u(f,...u(h.data,...i,e*24)),p*o(h.data,e*24))}update(){if(this.since=0,!this.closed){for(let e of this.images)e.wanted=0;for(let e of this.models)if(e.disposed)this.models.delete(e);else for(let t of e.primitives)this.measure(e,t);for(let e of this.images)e.stream?.want(e.wanted);this.streamer.update()}}restart(){if(!this.closed){for(let e of this.images)e.drop();this.streamer.dispose(),this.start();for(let e of this.images)this.begin(e).catch(e=>(this.options.onError??console.error)(e))}}dispose(){if(!this.closed){this.closed=!0;for(let e of this.images)e.drop();this.images.clear(),this.streamer.dispose(),this.engine.sceneOf(this.plugin)?.removePlugin(this.name)}}};export{p as GLTFTextureStream};
@@ -0,0 +1,88 @@
1
+ import type { EngineKernel } from '@margoengine/core';
2
+ import type { KTX2StreamerOptions, StreamedKTX2 } from '@margoengine/decoders/ktx2-stream';
3
+ import type { GLTFStreamedImage, GLTFStreamSource, GLTFTextureOpener } from './asset.js';
4
+ import type { PBRModel } from './pbr.js';
5
+ /** `textures` of `loadGLTFProgressive`: the memory budget and loading of its KTX2 textures. */
6
+ export interface GLTFTextureStreamOptions extends Pick<KTX2StreamerOptions, 'budgetBytes' | 'concurrency' | 'headBytes' | 'decoder' | 'hdrDecoder'> {
7
+ /** Called when a finer level fails to load; the texture keeps the levels it has. Default: `console.error`. */
8
+ onError?: (error: unknown) => void;
9
+ }
10
+ /** One image of a model: a stream that hands the current view to whoever draws it. */
11
+ declare class StreamedImage implements GLTFStreamedImage {
12
+ private readonly owner;
13
+ readonly source: GLTFStreamSource;
14
+ readonly streamed = true;
15
+ readonly users: Set<{
16
+ rebindStreamed(image: GLTFStreamedImage): void;
17
+ }>;
18
+ stream?: StreamedKTX2;
19
+ width: number;
20
+ height: number;
21
+ /** On-screen size for the next update. */
22
+ wanted: number;
23
+ private views;
24
+ constructor(owner: GLTFTextureStream, source: GLTFStreamSource);
25
+ view(device: GPUDevice, srgb: boolean): GPUTextureView | undefined;
26
+ viewSize(): {
27
+ width: number;
28
+ height: number;
29
+ levels: number;
30
+ } | undefined;
31
+ /** Takes on a newly opened stream and tells the models. */
32
+ use(stream: StreamedKTX2): void;
33
+ private changed;
34
+ /** Lets go of the stream only, for a restart on a new device. */
35
+ drop(): void;
36
+ close(): void;
37
+ }
38
+ /**
39
+ * The live texture side of one progressive load (`load.textures`). It reads how large each KTX2 texture is on screen about
40
+ * five times a second and asks for the levels that need, inside `budgetBytes`, for as long as the model lives.
41
+ */
42
+ export declare class GLTFTextureStream implements GLTFTextureOpener {
43
+ private readonly options;
44
+ private readonly signal;
45
+ private readonly engine;
46
+ private readonly name;
47
+ private readonly images;
48
+ private readonly models;
49
+ private readonly uses;
50
+ private streamer;
51
+ private since;
52
+ private closed;
53
+ private plugin;
54
+ /** Creates the stream on `engine` (preferred over the constructor); the `textures` option of `/progressive` calls this. */
55
+ static attach(engine: EngineKernel, options?: GLTFTextureStreamOptions, signal?: AbortSignal): GLTFTextureStream;
56
+ constructor(instance: EngineKernel, options?: GLTFTextureStreamOptions, signal?: AbortSignal);
57
+ private start;
58
+ /** The device the streams live on. */
59
+ get device(): GPUDevice;
60
+ /** Most bytes of GPU memory the textures may hold; lower it under memory pressure. */
61
+ get budgetBytes(): number;
62
+ set budgetBytes(bytes: number);
63
+ /** GPU bytes the textures hold now. */
64
+ get usedBytes(): number;
65
+ /** Textures streaming, with the finest level each holds (0 is full size), its level count and size on screen in pixels. */
66
+ get textures(): {
67
+ width: number;
68
+ height: number;
69
+ level: number;
70
+ levels: number;
71
+ pixels: number;
72
+ }[];
73
+ private begin;
74
+ /** Opens one image; resolves once its smallest levels are on the GPU. */
75
+ open(source: GLTFStreamSource): Promise<GLTFStreamedImage>;
76
+ /** Follows `model`, which then rebinds as its textures change. */
77
+ attach(model: PBRModel): void;
78
+ /** Forgets a closed image; with the last one gone, the stream closes. */
79
+ forget(image: StreamedImage): void;
80
+ private mapsOf;
81
+ private measure;
82
+ /** Reads every texture's size on screen and starts the loads that calls for; runs by itself about five times a second. */
83
+ update(): void;
84
+ private restart;
85
+ /** Stops loading and frees every texture; disposing the model does this. */
86
+ dispose(): void;
87
+ }
88
+ export {};