@needle-tools/gltf-progressive 3.4.0-rc → 4.0.0-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1489 +0,0 @@
1
- import { BufferGeometry as E, Mesh as V, Box3 as he, Vector3 as C, Sphere as De, CompressedTexture as Be, Texture as F, Matrix3 as Ge, InterleavedBuffer as Fe, InterleavedBufferAttribute as We, BufferAttribute as Ue, TextureLoader as ze, Matrix4 as Le, Clock as Ne, MeshStandardMaterial as qe } from "three";
2
- import { GLTFLoader as ye } from "three/examples/jsm/loaders/GLTFLoader.js";
3
- import { MeshoptDecoder as Ee } from "three/examples/jsm/libs/meshopt_decoder.module.js";
4
- import { DRACOLoader as Ve } from "three/examples/jsm/loaders/DRACOLoader.js";
5
- import { KTX2Loader as Xe } from "three/examples/jsm/loaders/KTX2Loader.js";
6
- const je = "";
7
- globalThis.GLTF_PROGRESSIVE_VERSION = je;
8
- console.debug("[gltf-progressive] version -");
9
- let R = "https://www.gstatic.com/draco/versioned/decoders/1.5.7/", X = "https://cdn.needle.tools/static/three/0.179.1/basis2/";
10
- const Ye = R, Ke = X, Oe = new URL(R + "draco_decoder.js");
11
- Oe.searchParams.append("range", "true");
12
- fetch(Oe, {
13
- method: "GET",
14
- headers: {
15
- Range: "bytes=0-1"
16
- }
17
- }).catch((n) => {
18
- console.debug(`Failed to fetch remote Draco decoder from ${R} (offline: ${typeof navigator < "u" ? navigator.onLine : "unknown"})`), R === Ye && Qe("./include/draco/"), X === Ke && Je("./include/ktx2/");
19
- }).finally(() => {
20
- Pe();
21
- });
22
- const He = () => ({
23
- dracoDecoderPath: R,
24
- ktx2TranscoderPath: X
25
- });
26
- function Qe(n) {
27
- R = n, A && A[ge] != R ? (console.debug("Updating Draco decoder path to " + n), A[ge] = R, A.setDecoderPath(R), A.preload()) : console.debug("Setting Draco decoder path to " + n);
28
- }
29
- function Je(n) {
30
- X = n, $ && $.transcoderPath != X ? (console.debug("Updating KTX2 transcoder path to " + n), $.setTranscoderPath(X), $.init()) : console.debug("Setting KTX2 transcoder path to " + n);
31
- }
32
- function xe(n) {
33
- return Pe(), n ? $.detectSupport(n) : n !== null && console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures might fail"), { dracoLoader: A, ktx2Loader: $, meshoptDecoder: oe };
34
- }
35
- function Se(n) {
36
- n.dracoLoader || n.setDRACOLoader(A), n.ktx2Loader || n.setKTX2Loader($), n.meshoptDecoder || n.setMeshoptDecoder(oe);
37
- }
38
- const ge = /* @__PURE__ */ Symbol("dracoDecoderPath");
39
- let A, oe, $;
40
- function Pe() {
41
- A || (A = new Ve(), A[ge] = R, A.setDecoderPath(R), A.setDecoderConfig({ type: "js" }), A.preload()), $ || ($ = new Xe(), $.setTranscoderPath(X), $.init()), oe || (oe = Ee);
42
- }
43
- const pe = /* @__PURE__ */ new WeakMap();
44
- function Te(n, t) {
45
- let e = pe.get(n);
46
- e ? e = Object.assign(e, t) : e = t, pe.set(n, e);
47
- }
48
- const Ze = ye.prototype.load;
49
- function et(...n) {
50
- const t = pe.get(this);
51
- let e = n[0];
52
- const s = new URL(e, window.location.href);
53
- if (s.hostname.endsWith("needle.tools")) {
54
- const r = t?.progressive !== void 0 ? t.progressive : !0, i = t?.usecase ? t.usecase : "default";
55
- r ? this.requestHeader.Accept = `*/*;progressive=allowed;usecase=${i}` : this.requestHeader.Accept = `*/*;usecase=${i}`, e = s.toString();
56
- }
57
- return n[0] = e, Ze?.call(this, ...n);
58
- }
59
- ye.prototype.load = et;
60
- j("debugprogressive");
61
- function j(n) {
62
- if (typeof window > "u") return !1;
63
- const e = new URL(window.location.href).searchParams.get(n);
64
- return e == null || e === "0" || e === "false" ? !1 : e === "" ? !0 : e;
65
- }
66
- function tt(n, t) {
67
- if (t === void 0 || n === void 0 || t.startsWith("./") || t.startsWith("http") || t.startsWith("data:") || t.startsWith("blob:"))
68
- return t;
69
- const e = n.lastIndexOf("/");
70
- if (e >= 0) {
71
- const s = n.substring(0, e + 1);
72
- for (; s.endsWith("/") && t.startsWith("/"); ) t = t.substring(1);
73
- return s + t;
74
- }
75
- return t;
76
- }
77
- function Ae() {
78
- return K !== void 0 || (K = /iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent), j("debugprogressive") && console.log("[glTF Progressive]: isMobileDevice", K)), K;
79
- }
80
- let K;
81
- function _e() {
82
- if (typeof window > "u") return !1;
83
- const n = new URL(window.location.href), t = n.hostname === "localhost" || /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n.hostname);
84
- return n.hostname === "127.0.0.1" || t;
85
- }
86
- class st {
87
- constructor(t = 100, e = {}) {
88
- this.maxConcurrent = t, this.debug = e.debug ?? !1, window.requestAnimationFrame(this.tick);
89
- }
90
- _running = /* @__PURE__ */ new Map();
91
- _queue = [];
92
- debug = !1;
93
- tick = () => {
94
- this.internalUpdate(), setTimeout(this.tick, 10);
95
- };
96
- /**
97
- * Request a slot for a promise with a specific key. This function returns a promise with a `use` method that can be called to add the promise to the queue.
98
- */
99
- slot(t) {
100
- return this.debug && console.debug(`[PromiseQueue]: Requesting slot for key ${t}, running: ${this._running.size}, waiting: ${this._queue.length}`), new Promise((e) => {
101
- this._queue.push({ key: t, resolve: e });
102
- });
103
- }
104
- add(t, e) {
105
- this._running.has(t) || (this._running.set(t, e), e.finally(() => {
106
- this._running.delete(t), this.debug && console.debug(`[PromiseQueue]: Promise finished now running: ${this._running.size}, waiting: ${this._queue.length}. (finished ${t})`);
107
- }), this.debug && console.debug(`[PromiseQueue]: Added new promise, now running: ${this._running.size}, waiting: ${this._queue.length}. (added ${t})`));
108
- }
109
- internalUpdate() {
110
- const t = this.maxConcurrent - this._running.size;
111
- for (let e = 0; e < t && this._queue.length > 0; e++) {
112
- this.debug && console.debug(`[PromiseQueue]: Running ${this._running.size} promises, waiting for ${this._queue.length} more.`);
113
- const { key: s, resolve: o } = this._queue.shift();
114
- o({
115
- use: (r) => this.add(s, r)
116
- });
117
- }
118
- }
119
- }
120
- const rt = typeof window > "u" && typeof document > "u", me = /* @__PURE__ */ Symbol("needle:raycast-mesh");
121
- function Z(n) {
122
- return n?.[me] instanceof E ? n[me] : null;
123
- }
124
- function ot(n, t) {
125
- if ((n.type === "Mesh" || n.type === "SkinnedMesh") && !Z(n)) {
126
- const s = nt(t);
127
- s.userData = { isRaycastMesh: !0 }, n[me] = s;
128
- }
129
- }
130
- function it(n = !0) {
131
- if (n) {
132
- if (H) return;
133
- const t = H = V.prototype.raycast;
134
- V.prototype.raycast = function(e, s) {
135
- const o = this, r = Z(o);
136
- let i;
137
- r && o.isMesh && (i = o.geometry, o.geometry = r), t.call(this, e, s), i && (o.geometry = i);
138
- };
139
- } else {
140
- if (!H) return;
141
- V.prototype.raycast = H, H = null;
142
- }
143
- }
144
- let H = null;
145
- function nt(n) {
146
- const t = new E();
147
- for (const e in n.attributes)
148
- t.setAttribute(e, n.getAttribute(e));
149
- return t.setIndex(n.getIndex()), t;
150
- }
151
- const z = new Array(), g = j("debugprogressive");
152
- let J, q = -1;
153
- if (g) {
154
- let n = function() {
155
- q += 1, q >= t && (q = -1), console.log(`Toggle LOD level [${q}]`);
156
- }, t = 6;
157
- window.addEventListener("keyup", (e) => {
158
- e.key === "p" && n(), e.key === "w" && (J = !J, console.log(`Toggle wireframe [${J}]`));
159
- const s = parseInt(e.key);
160
- !isNaN(s) && s >= 0 && (q = s, console.log(`Set LOD level to [${q}]`));
161
- });
162
- }
163
- function Ce(n) {
164
- if (g && J !== void 0)
165
- if (Array.isArray(n))
166
- for (const t of n)
167
- Ce(t);
168
- else n && "wireframe" in n && (n.wireframe = J === !0);
169
- }
170
- const Q = new Array();
171
- let at = 0;
172
- const lt = Ae() ? 2 : 10;
173
- function dt(n) {
174
- if (Q.length < lt) {
175
- const s = Q.length;
176
- g && console.warn(`[Worker] Creating new worker #${s}`);
177
- const o = we.createWorker(n || {});
178
- return Q.push(o), o;
179
- }
180
- const t = at++ % Q.length;
181
- return Q[t];
182
- }
183
- class we {
184
- constructor(t, e) {
185
- this.worker = t, this._debug = e.debug ?? !1, t.onmessage = (s) => {
186
- const o = s.data;
187
- switch (this._debug && console.log("[Worker] EVENT", o), o.type) {
188
- case "loaded-gltf":
189
- for (const r of this._running)
190
- if (r.url === o.result.url) {
191
- ut(o.result), r.resolve(o.result);
192
- const i = r.url;
193
- i.startsWith("blob:") && URL.revokeObjectURL(i);
194
- }
195
- }
196
- }, t.onerror = (s) => {
197
- console.error("[Worker] Error in gltf-progressive worker:", s);
198
- }, t.postMessage({
199
- type: "init"
200
- });
201
- }
202
- static async createWorker(t) {
203
- const e = new Worker(new URL(
204
- /* @vite-ignore */
205
- "/assets/loader.worker-CCrD-Ycm.js",
206
- import.meta.url
207
- ), {
208
- type: "module"
209
- });
210
- return new we(e, t);
211
- }
212
- _running = [];
213
- _webglRenderer = null;
214
- async load(t, e) {
215
- const s = He();
216
- let o = e?.renderer;
217
- o || (this._webglRenderer ??= (async () => {
218
- const { WebGLRenderer: d } = await import("three");
219
- return new d();
220
- })(), o = await this._webglRenderer);
221
- const l = xe(o).ktx2Loader.workerConfig;
222
- t instanceof URL ? t = t.toString() : t.startsWith("file:") ? t = URL.createObjectURL(new Blob([t])) : !t.startsWith("blob:") && !t.startsWith("http:") && !t.startsWith("https:") && (t = new URL(t, window.location.href).toString());
223
- const a = {
224
- type: "load",
225
- url: t,
226
- dracoDecoderPath: s.dracoDecoderPath,
227
- ktx2TranscoderPath: s.ktx2TranscoderPath,
228
- ktx2LoaderConfig: l
229
- };
230
- return this._debug && console.debug("[Worker] Sending load request", a), this.worker.postMessage(a), new Promise((d) => {
231
- this._running.push({
232
- url: t.toString(),
233
- resolve: d
234
- });
235
- });
236
- }
237
- _debug = !1;
238
- }
239
- function ut(n) {
240
- for (const t of n.geometries) {
241
- const e = t.geometry, s = new E();
242
- if (s.name = e.name || "", e.index) {
243
- const o = e.index;
244
- s.setIndex(ae(o));
245
- }
246
- for (const o in e.attributes) {
247
- const r = e.attributes[o], i = ae(r);
248
- s.setAttribute(o, i);
249
- }
250
- if (e.morphAttributes)
251
- for (const o in e.morphAttributes) {
252
- const i = e.morphAttributes[o].map((l) => ae(l));
253
- s.morphAttributes[o] = i;
254
- }
255
- if (s.morphTargetsRelative = e.morphTargetsRelative ?? !1, s.boundingBox = new he(), s.boundingBox.min = new C(
256
- e.boundingBox?.min.x,
257
- e.boundingBox?.min.y,
258
- e.boundingBox?.min.z
259
- ), s.boundingBox.max = new C(
260
- e.boundingBox?.max.x,
261
- e.boundingBox?.max.y,
262
- e.boundingBox?.max.z
263
- ), s.boundingSphere = new De(
264
- new C(
265
- e.boundingSphere?.center.x,
266
- e.boundingSphere?.center.y,
267
- e.boundingSphere?.center.z
268
- ),
269
- e.boundingSphere?.radius
270
- ), e.groups)
271
- for (const o of e.groups)
272
- s.addGroup(o.start, o.count, o.materialIndex);
273
- e.userData && (s.userData = e.userData), t.geometry = s;
274
- }
275
- for (const t of n.textures) {
276
- const e = t.texture;
277
- let s = null;
278
- if (e.isCompressedTexture) {
279
- const o = e.mipmaps, r = e.image?.width || e.source?.data?.width || -1, i = e.image?.height || e.source?.data?.height || -1;
280
- s = new Be(
281
- o,
282
- r,
283
- i,
284
- e.format,
285
- e.type,
286
- e.mapping,
287
- e.wrapS,
288
- e.wrapT,
289
- e.magFilter,
290
- e.minFilter,
291
- e.anisotropy,
292
- e.colorSpace
293
- );
294
- } else
295
- s = new F(
296
- e.image,
297
- e.mapping,
298
- e.wrapS,
299
- e.wrapT,
300
- e.magFilter,
301
- e.minFilter,
302
- e.format,
303
- e.type,
304
- e.anisotropy,
305
- e.colorSpace
306
- ), s.mipmaps = e.mipmaps, s.channel = e.channel, s.source.data = e.source.data, s.flipY = e.flipY, s.premultiplyAlpha = e.premultiplyAlpha, s.unpackAlignment = e.unpackAlignment, s.matrix = new Ge(...e.matrix.elements);
307
- if (!s) {
308
- console.error("[Worker] Failed to create new texture from received data. Texture is not a CompressedTexture or Texture.");
309
- continue;
310
- }
311
- t.texture = s;
312
- }
313
- return n;
314
- }
315
- function ae(n) {
316
- let t = n;
317
- if ("isInterleavedBufferAttribute" in n && n.isInterleavedBufferAttribute) {
318
- const e = n.data, s = e.array, o = new Fe(s, e.stride);
319
- t = new We(o, n.itemSize, s.byteOffset, n.normalized), t.offset = n.offset;
320
- } else "isBufferAttribute" in n && n.isBufferAttribute && (t = new Ue(n.array, n.itemSize, n.normalized), t.usage = n.usage, t.gpuType = n.gpuType, t.updateRanges = n.updateRanges);
321
- return t;
322
- }
323
- const ct = j("gltf-progressive-worker"), ft = j("gltf-progressive-reduce-mipmaps"), le = /* @__PURE__ */ Symbol("needle-progressive-texture"), W = "NEEDLE_progressive";
324
- class m {
325
- /** The name of the extension */
326
- get name() {
327
- return W;
328
- }
329
- // #region PUBLIC API
330
- static getMeshLODExtension(t) {
331
- const e = this.getAssignedLODInformation(t);
332
- return e?.key ? this.lodInfos.get(e.key) : null;
333
- }
334
- static getPrimitiveIndex(t) {
335
- const e = this.getAssignedLODInformation(t)?.index;
336
- return e ?? -1;
337
- }
338
- static getMaterialMinMaxLODsCount(t, e) {
339
- const s = this, o = "LODS:minmax", r = t[o];
340
- if (r != null) return r;
341
- if (e || (e = {
342
- min_count: 1 / 0,
343
- max_count: 0,
344
- lods: []
345
- }), Array.isArray(t)) {
346
- for (const l of t)
347
- this.getMaterialMinMaxLODsCount(l, e);
348
- return t[o] = e, e;
349
- }
350
- if (g === "verbose" && console.log("getMaterialMinMaxLODsCount", t), t.type === "ShaderMaterial" || t.type === "RawShaderMaterial") {
351
- const l = t;
352
- for (const a of Object.keys(l.uniforms)) {
353
- const d = l.uniforms[a].value;
354
- d?.isTexture === !0 && i(d, e);
355
- }
356
- } else if (t.isMaterial)
357
- for (const l of Object.keys(t)) {
358
- const a = t[l];
359
- a?.isTexture === !0 && i(a, e);
360
- }
361
- else
362
- g && console.warn(`[getMaterialMinMaxLODsCount] Unsupported material type: ${t.type}`);
363
- return t[o] = e, e;
364
- function i(l, a) {
365
- const d = s.getAssignedLODInformation(l);
366
- if (d) {
367
- const u = s.lodInfos.get(d.key);
368
- if (u && u.lods) {
369
- a.min_count = Math.min(a.min_count, u.lods.length), a.max_count = Math.max(a.max_count, u.lods.length);
370
- for (let y = 0; y < u.lods.length; y++) {
371
- const w = u.lods[y];
372
- w.width && (a.lods[y] = a.lods[y] || { min_height: 1 / 0, max_height: 0 }, a.lods[y].min_height = Math.min(a.lods[y].min_height, w.height), a.lods[y].max_height = Math.max(a.lods[y].max_height, w.height));
373
- }
374
- }
375
- }
376
- }
377
- }
378
- /** Check if a LOD level is available for a mesh or a texture
379
- * @param obj the mesh or texture to check
380
- * @param level the level of detail to check for (0 is the highest resolution). If undefined, the function checks if any LOD level is available
381
- * @returns true if the LOD level is available (or if any LOD level is available if level is undefined)
382
- */
383
- static hasLODLevelAvailable(t, e) {
384
- if (Array.isArray(t)) {
385
- for (const r of t)
386
- if (this.hasLODLevelAvailable(r, e)) return !0;
387
- return !1;
388
- }
389
- if (t.isMaterial === !0) {
390
- for (const r of Object.keys(t)) {
391
- const i = t[r];
392
- if (i && i.isTexture && this.hasLODLevelAvailable(i, e))
393
- return !0;
394
- }
395
- return !1;
396
- } else if (t.isGroup === !0) {
397
- for (const r of t.children)
398
- if (r.isMesh === !0 && this.hasLODLevelAvailable(r, e))
399
- return !0;
400
- }
401
- let s, o;
402
- if (t.isMesh ? s = t.geometry : (t.isBufferGeometry || t.isTexture) && (s = t), s && s?.userData?.LODS) {
403
- const r = s.userData.LODS;
404
- if (o = this.lodInfos.get(r.key), e === void 0) return o != null;
405
- if (o)
406
- return Array.isArray(o.lods) ? e < o.lods.length : e === 0;
407
- }
408
- return !1;
409
- }
410
- /** Load a different resolution of a mesh (if available)
411
- * @param context the context
412
- * @param source the sourceid of the file from which the mesh is loaded (this is usually the component's sourceId)
413
- * @param mesh the mesh to load the LOD for
414
- * @param level the level of detail to load (0 is the highest resolution)
415
- * @returns a promise that resolves to the mesh with the requested LOD level
416
- * @example
417
- * ```javascript
418
- * const mesh = this.gameObject as Mesh;
419
- * NEEDLE_progressive.assignMeshLOD(context, sourceId, mesh, 1).then(mesh => {
420
- * console.log("Mesh with LOD level 1 loaded", mesh);
421
- * });
422
- * ```
423
- */
424
- static assignMeshLOD(t, e) {
425
- if (!t) return Promise.resolve(null);
426
- if (t instanceof V || t.isMesh === !0) {
427
- const s = t.geometry, o = this.getAssignedLODInformation(s);
428
- if (!o)
429
- return Promise.resolve(null);
430
- for (const r of z)
431
- r.onBeforeGetLODMesh?.(t, e);
432
- return t["LOD:requested level"] = e, m.getOrLoadLOD(s, e).then((r) => {
433
- if (Array.isArray(r)) {
434
- const i = o.index || 0;
435
- r = r[i];
436
- }
437
- return t["LOD:requested level"] === e && (delete t["LOD:requested level"], r && s != r && (r?.isBufferGeometry ? t.geometry = r : g && console.error("Invalid LOD geometry", r))), r;
438
- }).catch((r) => (console.error("Error loading mesh LOD", t, r), null));
439
- } else g && console.error("Invalid call to assignMeshLOD: Request mesh LOD but the object is not a mesh", t);
440
- return Promise.resolve(null);
441
- }
442
- static assignTextureLOD(t, e = 0) {
443
- if (!t) return Promise.resolve(null);
444
- if (t.isMesh === !0) {
445
- const s = t;
446
- if (Array.isArray(s.material)) {
447
- const o = new Array();
448
- for (const r of s.material) {
449
- const i = this.assignTextureLOD(r, e);
450
- o.push(i);
451
- }
452
- return Promise.all(o).then((r) => {
453
- const i = new Array();
454
- for (const l of r)
455
- Array.isArray(l) && i.push(...l);
456
- return i;
457
- });
458
- } else
459
- return this.assignTextureLOD(s.material, e);
460
- }
461
- if (t.isMaterial === !0) {
462
- const s = t, o = [], r = new Array();
463
- if (s.uniforms && (s.isRawShaderMaterial || s.isShaderMaterial === !0)) {
464
- const i = s;
465
- for (const l of Object.keys(i.uniforms)) {
466
- const a = i.uniforms[l].value;
467
- if (a?.isTexture === !0) {
468
- const d = this.assignTextureLODForSlot(a, e, s, l).then((u) => (u && i.uniforms[l].value != u && (i.uniforms[l].value = u, i.uniformsNeedUpdate = !0), u));
469
- o.push(d), r.push(l);
470
- }
471
- }
472
- } else
473
- for (const i of Object.keys(s)) {
474
- const l = s[i];
475
- if (l?.isTexture === !0) {
476
- const a = this.assignTextureLODForSlot(l, e, s, i);
477
- o.push(a), r.push(i);
478
- }
479
- }
480
- return Promise.all(o).then((i) => {
481
- const l = new Array();
482
- for (let a = 0; a < i.length; a++) {
483
- const d = i[a], u = r[a];
484
- d && d.isTexture === !0 ? l.push({ material: s, slot: u, texture: d, level: e }) : l.push({ material: s, slot: u, texture: null, level: e });
485
- }
486
- return l;
487
- });
488
- }
489
- if (t instanceof F || t.isTexture === !0) {
490
- const s = t;
491
- return this.assignTextureLODForSlot(s, e, null, null);
492
- }
493
- return Promise.resolve(null);
494
- }
495
- // #region INTERNAL
496
- static assignTextureLODForSlot(t, e, s, o) {
497
- return t?.isTexture !== !0 ? Promise.resolve(null) : o === "glyphMap" ? Promise.resolve(t) : m.getOrLoadLOD(t, e).then((r) => {
498
- if (Array.isArray(r))
499
- return console.warn("Progressive: Got an array of textures for a texture slot, this should not happen..."), null;
500
- if (r?.isTexture === !0) {
501
- if (r != t && s && o) {
502
- const i = s[o];
503
- if (i && !g) {
504
- const l = this.getAssignedLODInformation(i);
505
- if (l && l?.level < e)
506
- return g === "verbose" && console.warn("Assigned texture level is already higher: ", l.level, e, s, i, r), null;
507
- }
508
- if (ft && r.mipmaps) {
509
- const l = r.mipmaps.length;
510
- r.mipmaps.length = Math.min(r.mipmaps.length, 3), l !== r.mipmaps.length && g && console.debug(`Reduced mipmap count from ${l} to ${r.mipmaps.length} for ${r.uuid}: ${r.image?.width}x${r.image?.height}.`);
511
- }
512
- s[o] = r;
513
- }
514
- return r;
515
- } else g == "verbose" && console.warn("No LOD found for", t, e);
516
- return null;
517
- }).catch((r) => (console.error("Error loading LOD", t, r), null));
518
- }
519
- parser;
520
- url;
521
- constructor(t) {
522
- const e = t.options.path;
523
- g && console.log("Progressive extension registered for", e), this.parser = t, this.url = e;
524
- }
525
- _isLoadingMesh;
526
- loadMesh = (t) => {
527
- if (this._isLoadingMesh) return null;
528
- const e = this.parser.json.meshes[t]?.extensions?.[W];
529
- return e ? (this._isLoadingMesh = !0, this.parser.getDependency("mesh", t).then((s) => (this._isLoadingMesh = !1, s && m.registerMesh(this.url, e.guid, s, e.lods?.length, 0, e), s))) : null;
530
- };
531
- // private _isLoadingTexture;
532
- // loadTexture = (textureIndex: number) => {
533
- // if (this._isLoadingTexture) return null;
534
- // const ext = this.parser.json.textures[textureIndex]?.extensions?.[EXTENSION_NAME] as NEEDLE_ext_progressive_texture;
535
- // if (!ext) return null;
536
- // this._isLoadingTexture = true;
537
- // return this.parser.getDependency("texture", textureIndex).then(tex => {
538
- // this._isLoadingTexture = false;
539
- // if (tex) {
540
- // NEEDLE_progressive.registerTexture(this.url, tex as Texture, ext.lods?.length, textureIndex, ext);
541
- // }
542
- // return tex;
543
- // });
544
- // }
545
- afterRoot(t) {
546
- return g && console.log("AFTER", this.url, t), this.parser.json.textures?.forEach((e, s) => {
547
- if (e?.extensions) {
548
- const o = e?.extensions[W];
549
- if (o) {
550
- if (!o.lods) {
551
- g && console.warn("Texture has no LODs", o);
552
- return;
553
- }
554
- let r = !1;
555
- for (const i of this.parser.associations.keys())
556
- i.isTexture === !0 && this.parser.associations.get(i)?.textures === s && (r = !0, m.registerTexture(this.url, i, o.lods?.length, s, o));
557
- r || this.parser.getDependency("texture", s).then((i) => {
558
- i && m.registerTexture(this.url, i, o.lods?.length, s, o);
559
- });
560
- }
561
- }
562
- }), this.parser.json.meshes?.forEach((e, s) => {
563
- if (e?.extensions) {
564
- const o = e?.extensions[W];
565
- if (o && o.lods) {
566
- for (const r of this.parser.associations.keys())
567
- if (r.isMesh) {
568
- const i = this.parser.associations.get(r);
569
- i?.meshes === s && m.registerMesh(this.url, o.guid, r, o.lods.length, i.primitives, o);
570
- }
571
- }
572
- }
573
- }), null;
574
- }
575
- /**
576
- * Register a texture with LOD information
577
- */
578
- static registerTexture = (t, e, s, o, r) => {
579
- if (!e) {
580
- g && console.error("!! gltf-progressive: Called register texture without texture");
581
- return;
582
- }
583
- if (g) {
584
- const l = e.image?.width || e.source?.data?.width || 0, a = e.image?.height || e.source?.data?.height || 0;
585
- console.log(`> gltf-progressive: register texture[${o}] "${e.name || e.uuid}", Current: ${l}x${a}, Max: ${r.lods[0]?.width}x${r.lods[0]?.height}, uuid: ${e.uuid}`, r, e);
586
- }
587
- e.source && (e.source[le] = r);
588
- const i = r.guid;
589
- m.assignLODInformation(t, e, i, s, o), m.lodInfos.set(i, r), m.lowresCache.set(i, new WeakRef(e));
590
- };
591
- /**
592
- * Register a mesh with LOD information
593
- */
594
- static registerMesh = (t, e, s, o, r, i) => {
595
- const l = s.geometry;
596
- if (!l) {
597
- g && console.warn("gltf-progressive: Register mesh without geometry");
598
- return;
599
- }
600
- l.userData || (l.userData = {}), g && console.log("> Progressive: register mesh " + s.name, { index: r, uuid: s.uuid }, i, s), m.assignLODInformation(t, l, e, o, r), m.lodInfos.set(e, i);
601
- let d = m.lowresCache.get(e)?.deref();
602
- d ? d.push(s.geometry) : d = [s.geometry], m.lowresCache.set(e, new WeakRef(d)), o > 0 && !Z(s) && ot(s, l);
603
- for (const u of z)
604
- u.onRegisteredNewMesh?.(s, i);
605
- };
606
- /**
607
- * Dispose cached resources to free memory.
608
- * Call this when a model is removed from the scene to allow garbage collection of its LOD resources.
609
- * Calls three.js `.dispose()` on cached Textures and BufferGeometries to free GPU memory.
610
- * @param guid Optional GUID to dispose resources for a specific model. If omitted, all cached resources are cleared.
611
- */
612
- static dispose(t) {
613
- if (t) {
614
- this.lodInfos.delete(t);
615
- const e = this.lowresCache.get(t);
616
- if (e) {
617
- const s = e.deref();
618
- if (s) {
619
- if (s.isTexture)
620
- s.dispose();
621
- else if (Array.isArray(s))
622
- for (const o of s) o.dispose();
623
- }
624
- this.lowresCache.delete(t);
625
- }
626
- for (const [s, o] of this.previouslyLoaded)
627
- s.includes(t) && (this._disposeCacheEntry(o), this.previouslyLoaded.delete(s));
628
- } else {
629
- this.lodInfos.clear();
630
- for (const [, e] of this.lowresCache) {
631
- const s = e.deref();
632
- if (s) {
633
- if (s.isTexture)
634
- s.dispose();
635
- else if (Array.isArray(s))
636
- for (const o of s) o.dispose();
637
- }
638
- }
639
- this.lowresCache.clear();
640
- for (const [, e] of this.previouslyLoaded)
641
- this._disposeCacheEntry(e);
642
- this.previouslyLoaded.clear();
643
- }
644
- }
645
- /** Dispose a single cache entry's three.js resource(s) to free GPU memory. */
646
- static _disposeCacheEntry(t) {
647
- t instanceof WeakRef ? t.deref()?.dispose() : t.then((e) => {
648
- if (e)
649
- if (Array.isArray(e))
650
- for (const s of e) s.dispose();
651
- else
652
- e.dispose();
653
- }).catch(() => {
654
- });
655
- }
656
- /** A map of key = asset uuid and value = LOD information */
657
- static lodInfos = /* @__PURE__ */ new Map();
658
- /** cache of already loaded mesh lods. Uses WeakRef for single resources to allow garbage collection when unused. */
659
- static previouslyLoaded = /* @__PURE__ */ new Map();
660
- /** this contains the geometry/textures that were originally loaded. Uses WeakRef to allow garbage collection when unused. */
661
- static lowresCache = /* @__PURE__ */ new Map();
662
- /**
663
- * FinalizationRegistry to automatically clean up `previouslyLoaded` cache entries
664
- * when their associated three.js resources are garbage collected by the browser.
665
- * The held value is the cache key string used in `previouslyLoaded`.
666
- */
667
- static _resourceRegistry = new FinalizationRegistry((t) => {
668
- const e = m.previouslyLoaded.get(t);
669
- console.debug(`[gltf-progressive] FinalizationRegistry cleanup: Resource GC'd for ${t}.`), e instanceof WeakRef && (e.deref() || (m.previouslyLoaded.delete(t), g && console.log(`[gltf-progressive] Cache entry auto-cleaned (GC'd): ${t}`)));
670
- });
671
- static workers = [];
672
- static _workersIndex = 0;
673
- static async getOrLoadLOD(t, e) {
674
- const s = g == "verbose", o = this.getAssignedLODInformation(t);
675
- if (!o)
676
- return g && console.warn(`[gltf-progressive] No LOD information found: ${t.name}, uuid: ${t.uuid}, type: ${t.type}`, t), null;
677
- const r = o?.key;
678
- let i;
679
- if (t.isTexture === !0) {
680
- const a = t;
681
- a.source && a.source[le] && (i = a.source[le]);
682
- }
683
- if (i || (i = m.lodInfos.get(r)), !i)
684
- g && console.warn(`Can not load LOD ${e}: no LOD info found for "${r}" ${t.name}`, t.type, m.lodInfos);
685
- else {
686
- if (e > 0) {
687
- let u = !1;
688
- const y = Array.isArray(i.lods);
689
- if (y && e >= i.lods.length ? u = !0 : y || (u = !0), u) {
690
- const w = this.lowresCache.get(r);
691
- if (w) {
692
- const L = w.deref();
693
- if (L) return L;
694
- this.lowresCache.delete(r), g && console.log(`[gltf-progressive] Lowres cache entry was GC'd: ${r}`);
695
- }
696
- return null;
697
- }
698
- }
699
- const a = Array.isArray(i.lods) ? i.lods[e]?.path : i.lods;
700
- if (!a)
701
- return g && !i["missing:uri"] && (i["missing:uri"] = !0, console.warn("Missing uri for progressive asset for LOD " + e, i)), null;
702
- const d = tt(o.url, a);
703
- if (d.endsWith(".glb") || d.endsWith(".gltf")) {
704
- if (!i.guid)
705
- return console.warn("missing pointer for glb/gltf texture", i), null;
706
- const u = d + "_" + i.guid, y = await this.queue.slot(d), w = this.previouslyLoaded.get(u);
707
- if (w !== void 0)
708
- if (s && console.log(`LOD ${e} was already loading/loaded: ${u}`), w instanceof WeakRef) {
709
- const c = w.deref();
710
- if (c) {
711
- let h = c, b = !1;
712
- if (h instanceof F && t instanceof F ? h.image?.data || h.source?.data ? h = this.copySettings(t, h) : b = !0 : h instanceof E && t instanceof E && (h.attributes.position?.array || (b = !0)), !b)
713
- return h;
714
- }
715
- this.previouslyLoaded.delete(u), g && console.log(`[gltf-progressive] Re-loading GC'd/disposed resource: ${u}`);
716
- } else {
717
- let c = await w.catch((b) => (console.error(`Error loading LOD ${e} from ${d}
718
- `, b), null)), h = !1;
719
- if (c == null || (c instanceof F && t instanceof F ? c.image?.data || c.source?.data ? c = this.copySettings(t, c) : (h = !0, this.previouslyLoaded.delete(u)) : c instanceof E && t instanceof E && (c.attributes.position?.array || (h = !0, this.previouslyLoaded.delete(u)))), !h)
720
- return c;
721
- }
722
- if (!y.use)
723
- return g && console.log(`LOD ${e} was aborted: ${d}`), null;
724
- const L = i, I = new Promise(async (c, h) => {
725
- if (ct) {
726
- const x = await (await dt({})).load(d);
727
- if (x.textures.length > 0)
728
- for (const f of x.textures) {
729
- let p = f.texture;
730
- return m.assignLODInformation(o.url, p, r, e, void 0), t instanceof F && (p = this.copySettings(t, p)), p && (p.guid = L.guid), c(p);
731
- }
732
- if (x.geometries.length > 0) {
733
- const f = new Array();
734
- for (const p of x.geometries) {
735
- const D = p.geometry;
736
- m.assignLODInformation(o.url, D, r, e, p.primitiveIndex), f.push(D);
737
- }
738
- return c(f);
739
- }
740
- return c(null);
741
- }
742
- const b = new ye();
743
- Se(b), g && (await new Promise((_) => setTimeout(_, 1e3)), s && console.warn("Start loading (delayed) " + d, L.guid));
744
- let B = d;
745
- if (L && Array.isArray(L.lods)) {
746
- const _ = L.lods[e];
747
- _.hash && (B += "?v=" + _.hash);
748
- }
749
- const M = await b.loadAsync(B).catch((_) => (console.error(`Error loading LOD ${e} from ${d}
750
- `, _), c(null)));
751
- if (!M)
752
- return c(null);
753
- const N = M.parser;
754
- s && console.log("Loading finished " + d, L.guid);
755
- let P = 0;
756
- if (M.parser.json.textures) {
757
- let _ = !1;
758
- for (const x of M.parser.json.textures) {
759
- if (x?.extensions) {
760
- const f = x?.extensions[W];
761
- if (f?.guid && f.guid === L.guid) {
762
- _ = !0;
763
- break;
764
- }
765
- }
766
- P++;
767
- }
768
- if (_) {
769
- let x = await N.getDependency("texture", P);
770
- return x && m.assignLODInformation(o.url, x, r, e, void 0), s && console.log('change "' + t.name + '" → "' + x.name + '"', d, P, x, u), t instanceof F && (x = this.copySettings(t, x)), x && (x.guid = L.guid), c(x);
771
- } else g && console.warn("Could not find texture with guid", L.guid, M.parser.json);
772
- }
773
- if (P = 0, M.parser.json.meshes) {
774
- let _ = !1;
775
- for (const x of M.parser.json.meshes) {
776
- if (x?.extensions) {
777
- const f = x?.extensions[W];
778
- if (f?.guid && f.guid === L.guid) {
779
- _ = !0;
780
- break;
781
- }
782
- }
783
- P++;
784
- }
785
- if (_) {
786
- const x = await N.getDependency("mesh", P);
787
- if (s && console.log(`Loaded Mesh "${x.name}"`, d, P, x, u), x.isMesh === !0) {
788
- const f = x.geometry;
789
- return m.assignLODInformation(o.url, f, r, e, 0), c(f);
790
- } else {
791
- const f = new Array();
792
- for (let p = 0; p < x.children.length; p++) {
793
- const D = x.children[p];
794
- if (D.isMesh === !0) {
795
- const S = D.geometry;
796
- m.assignLODInformation(o.url, S, r, e, p), f.push(S);
797
- }
798
- }
799
- return c(f);
800
- }
801
- } else g && console.warn("Could not find mesh with guid", L.guid, M.parser.json);
802
- }
803
- return c(null);
804
- });
805
- this.previouslyLoaded.set(u, I), y.use(I);
806
- const O = await I;
807
- return O != null ? Array.isArray(O) ? this.previouslyLoaded.set(u, Promise.resolve(O)) : (this.previouslyLoaded.set(u, new WeakRef(O)), m._resourceRegistry.register(O, u)) : this.previouslyLoaded.set(u, Promise.resolve(null)), O;
808
- } else if (t instanceof F) {
809
- s && console.log("Load texture from uri: " + d);
810
- const y = await new ze().loadAsync(d);
811
- return y ? (y.guid = i.guid, y.flipY = !1, y.needsUpdate = !0, y.colorSpace = t.colorSpace, s && console.log(i, y)) : g && console.warn("failed loading", d), y;
812
- }
813
- }
814
- return null;
815
- }
816
- static maxConcurrent = 50;
817
- static queue = new st(m.maxConcurrent, { debug: g != !1 });
818
- static assignLODInformation(t, e, s, o, r) {
819
- if (!e) return;
820
- e.userData || (e.userData = {});
821
- const i = new ht(t, s, o, r);
822
- e.userData.LODS = i, "source" in e && typeof e.source == "object" && (e.source.LODS = i);
823
- }
824
- static getAssignedLODInformation(t) {
825
- return t ? t.userData?.LODS ? t.userData.LODS : "source" in t && t.source?.LODS ? t.source.LODS : null : null;
826
- }
827
- // private static readonly _copiedTextures: WeakMap<Texture, Texture> = new Map();
828
- static copySettings(t, e) {
829
- return e ? (g === "verbose" && console.debug(`Copy texture settings
830
- `, t.uuid, `
831
- `, e.uuid), e = e.clone(), e.offset = t.offset, e.repeat = t.repeat, e.colorSpace = t.colorSpace, e.magFilter = t.magFilter, e.minFilter = t.minFilter, e.wrapS = t.wrapS, e.wrapT = t.wrapT, e.flipY = t.flipY, e.anisotropy = t.anisotropy, e.mipmaps || (e.generateMipmaps = t.generateMipmaps), e) : t;
832
- }
833
- }
834
- class ht {
835
- url;
836
- /** the key to lookup the LOD information */
837
- key;
838
- level;
839
- /** For multi objects (e.g. a group of meshes) this is the index of the object */
840
- index;
841
- constructor(t, e, s, o) {
842
- this.url = t, this.key = e, this.level = s, o != null && (this.index = o);
843
- }
844
- }
845
- class de {
846
- static addPromise = (t, e, s, o) => {
847
- o.forEach((r) => {
848
- r.add(t, e, s);
849
- });
850
- };
851
- ready;
852
- /** The number of promises that have been added to this group so far */
853
- get awaitedCount() {
854
- return this._addedCount;
855
- }
856
- /** The number of promises that have been resolved */
857
- get resolvedCount() {
858
- return this._resolvedCount;
859
- }
860
- /** The number of promises that are in-flight */
861
- get currentlyAwaiting() {
862
- return this._awaiting.length;
863
- }
864
- _resolve;
865
- _signal;
866
- /** start frame can be undefined if the user configured this group to wait for the first promise.
867
- * Then the start frame will be set when the first promise has been added to the group */
868
- _frame_start;
869
- /** How many frames to capture since the start frame */
870
- _frames_to_capture;
871
- _resolved = !1;
872
- _addedCount = 0;
873
- _resolvedCount = 0;
874
- /** These promises are currently being awaited */
875
- _awaiting = [];
876
- _maxPromisesPerObject = 1;
877
- constructor(t, e) {
878
- const o = Math.max(e.frames ?? 2, 2);
879
- this._frame_start = e.waitForFirstCapture ? void 0 : t, this._frames_to_capture = o, this.ready = new Promise((r) => {
880
- this._resolve = r;
881
- }), this.ready.finally(() => {
882
- this._resolved = !0, this._awaiting.length = 0;
883
- }), this._signal = e.signal, this._signal?.addEventListener("abort", () => {
884
- this.resolveNow();
885
- }), this._maxPromisesPerObject = Math.max(1, e.maxPromisesPerObject ?? 1);
886
- }
887
- _currentFrame = 0;
888
- update(t) {
889
- this._currentFrame = t, this._frame_start === void 0 && this._addedCount > 0 && (this._frame_start = t), (this._signal?.aborted || this._awaiting.length === 0 && this._frame_start !== void 0 && t > this._frame_start + this._frames_to_capture) && this.resolveNow();
890
- }
891
- _seen = /* @__PURE__ */ new WeakMap();
892
- add(t, e, s) {
893
- if (this._resolved) {
894
- g && console.warn("PromiseGroup: Trying to add a promise to a resolved group, ignoring.");
895
- return;
896
- }
897
- if (!(this._frame_start !== void 0 && this._currentFrame > this._frame_start + this._frames_to_capture)) {
898
- if (this._maxPromisesPerObject >= 1)
899
- if (this._seen.has(e)) {
900
- let o = this._seen.get(e);
901
- if (o >= this._maxPromisesPerObject) {
902
- g && console.warn("PromiseGroup: Already awaiting object ignoring new promise for it.");
903
- return;
904
- }
905
- this._seen.set(e, o + 1);
906
- } else
907
- this._seen.set(e, 1);
908
- this._awaiting.push(s), this._addedCount++, s.finally(() => {
909
- this._resolvedCount++, this._awaiting.splice(this._awaiting.indexOf(s), 1);
910
- });
911
- }
912
- }
913
- resolveNow() {
914
- this._resolved || this._resolve?.({
915
- awaited_count: this._addedCount,
916
- resolved_count: this._resolvedCount,
917
- cancelled: this._signal?.aborted ?? !1
918
- });
919
- }
920
- }
921
- const k = j("debugprogressive"), gt = j("noprogressive"), ue = /* @__PURE__ */ Symbol("Needle:LODSManager"), ce = /* @__PURE__ */ Symbol("Needle:LODState"), U = /* @__PURE__ */ Symbol("Needle:CurrentLOD"), T = { mesh_lod: -1, texture_lod: -1 };
922
- class v {
923
- /**
924
- * Assign a function to draw debug lines for the LODs. This function will be called with the start and end position of the line and the color of the line when the `debugprogressive` query parameter is set.
925
- */
926
- static debugDrawLine;
927
- /** @internal */
928
- static getObjectLODState(t) {
929
- return t[ce];
930
- }
931
- static addPlugin(t) {
932
- z.push(t);
933
- }
934
- static removePlugin(t) {
935
- const e = z.indexOf(t);
936
- e >= 0 && z.splice(e, 1);
937
- }
938
- /**
939
- * Gets the LODsManager for the given renderer. If the LODsManager does not exist yet, it will be created.
940
- * @param renderer The renderer to get the LODsManager for.
941
- * @returns The LODsManager instance.
942
- */
943
- static get(t, e) {
944
- if (t[ue])
945
- return console.debug("[gltf-progressive] LODsManager already exists for this renderer"), t[ue];
946
- const s = new v(t, {
947
- engine: "unknown",
948
- ...e
949
- });
950
- return t[ue] = s, s;
951
- }
952
- renderer;
953
- context;
954
- projectionScreenMatrix = new Le();
955
- /** @deprecated use static `LODsManager.addPlugin()` method. This getter will be removed in later versions */
956
- get plugins() {
957
- return z;
958
- }
959
- /**
960
- * Force override the LOD level for all objects (meshes + textures) rendered in the scene
961
- * @default undefined automatically calculate LOD level
962
- */
963
- overrideLodLevel = void 0;
964
- /**
965
- * The target triangle density is the desired max amount of triangles on screen when the mesh is filling the screen.
966
- * @default 200_000
967
- */
968
- targetTriangleDensity = 2e5;
969
- /**
970
- * The interval in frames to automatically update the bounds of skinned meshes.
971
- * Set to 0 or a negative value to disable automatic bounds updates.
972
- * @default 30
973
- */
974
- skinnedMeshAutoUpdateBoundsInterval = 30;
975
- /**
976
- * The update interval in frames. If set to 0, the LODs will be updated every frame. If set to 2, the LODs will be updated every second frame, etc.
977
- * @default "auto"
978
- */
979
- updateInterval = "auto";
980
- #e = 1;
981
- /**
982
- * If set to true, the LODsManager will not update the LODs.
983
- * @default false
984
- */
985
- pause = !1;
986
- /**
987
- * When set to true the LODsManager will not update the LODs. This can be used to manually update the LODs using the `update` method.
988
- * Otherwise the LODs will be updated automatically when the renderer renders the scene.
989
- * @default false
990
- */
991
- manual = !1;
992
- _newPromiseGroups = [];
993
- _promiseGroupIds = 0;
994
- /**
995
- * Call to await LODs loading during the next render cycle.
996
- */
997
- awaitLoading(t) {
998
- const e = this._promiseGroupIds++, s = new de(this.#r, { ...t });
999
- this._newPromiseGroups.push(s);
1000
- const o = performance.now();
1001
- return s.ready.finally(() => {
1002
- const r = this._newPromiseGroups.indexOf(s);
1003
- r >= 0 && (this._newPromiseGroups.splice(r, 1), _e() && performance.measure("LODsManager:awaitLoading", {
1004
- start: o,
1005
- detail: { id: e, name: t?.name, awaited: s.awaitedCount, resolved: s.resolvedCount }
1006
- }));
1007
- }), s.ready;
1008
- }
1009
- _postprocessPromiseGroups() {
1010
- if (this._newPromiseGroups.length !== 0)
1011
- for (let t = this._newPromiseGroups.length - 1; t >= 0; t--)
1012
- this._newPromiseGroups[t].update(this.#r);
1013
- }
1014
- _lodchangedlisteners = [];
1015
- addEventListener(t, e) {
1016
- t === "changed" && this._lodchangedlisteners.push(e);
1017
- }
1018
- removeEventListener(t, e) {
1019
- if (t === "changed") {
1020
- const s = this._lodchangedlisteners.indexOf(e);
1021
- s >= 0 && this._lodchangedlisteners.splice(s, 1);
1022
- }
1023
- }
1024
- // readonly plugins: NEEDLE_progressive_plugin[] = [];
1025
- constructor(t, e) {
1026
- this.renderer = t, this.context = { ...e };
1027
- }
1028
- #t;
1029
- #i = new Ne();
1030
- #r = 0;
1031
- #o = 0;
1032
- #n = 0;
1033
- #s = 0;
1034
- _fpsBuffer = [60, 60, 60, 60, 60];
1035
- /**
1036
- * Enable the LODsManager. This will replace the render method of the renderer with a method that updates the LODs.
1037
- */
1038
- enable() {
1039
- if (this.#t) return;
1040
- console.debug("[gltf-progressive] Enabling LODsManager for renderer");
1041
- let t = 0;
1042
- this.#t = this.renderer.render;
1043
- const e = this;
1044
- xe(this.renderer), this.renderer.render = function(s, o) {
1045
- const r = e.renderer.getRenderTarget();
1046
- (r == null || "isXRRenderTarget" in r && r.isXRRenderTarget) && (t = 0, e.#r += 1, e.#o = e.#i.getDelta(), e.#n += e.#o, e._fpsBuffer.shift(), e._fpsBuffer.push(1 / e.#o), e.#s = e._fpsBuffer.reduce((l, a) => l + a) / e._fpsBuffer.length, k && e.#r % 200 === 0 && console.log("FPS", Math.round(e.#s), "Interval:", e.#e));
1047
- const i = t++;
1048
- e.#t.call(this, s, o), e.onAfterRender(s, o, i);
1049
- };
1050
- }
1051
- disable() {
1052
- this.#t && (console.debug("[gltf-progressive] Disabling LODsManager for renderer"), this.renderer.render = this.#t, this.#t = void 0);
1053
- }
1054
- update(t, e) {
1055
- this.internalUpdate(t, e);
1056
- }
1057
- onAfterRender(t, e, s) {
1058
- if (this.pause) return;
1059
- const r = this.renderer.renderLists.get(t, 0).opaque;
1060
- let i = !0;
1061
- if (r.length === 1) {
1062
- const l = r[0].material;
1063
- (l.name === "EffectMaterial" || l.name === "CopyShader") && (i = !1);
1064
- }
1065
- if ((e.parent && e.parent.type === "CubeCamera" || s >= 1 && e.type === "OrthographicCamera") && (i = !1), i) {
1066
- if (gt || (this.updateInterval === "auto" ? this.#s < 40 && this.#e < 10 ? (this.#e += 1, k && console.warn("↓ Reducing LOD updates", this.#e, this.#s.toFixed(0))) : this.#s >= 60 && this.#e > 1 && (this.#e -= 1, k && console.warn("↑ Increasing LOD updates", this.#e, this.#s.toFixed(0))) : this.#e = this.updateInterval, this.#e > 0 && this.#r % this.#e != 0))
1067
- return;
1068
- this.internalUpdate(t, e), this._postprocessPromiseGroups();
1069
- }
1070
- }
1071
- /**
1072
- * Update LODs in a scene
1073
- */
1074
- internalUpdate(t, e) {
1075
- const s = this.renderer.renderLists.get(t, 0), o = s.opaque;
1076
- this.projectionScreenMatrix.multiplyMatrices(e.projectionMatrix, e.matrixWorldInverse);
1077
- const r = this.targetTriangleDensity;
1078
- for (const a of o) {
1079
- if (a.material && (a.geometry?.type === "BoxGeometry" || a.geometry?.type === "BufferGeometry") && (a.material.name === "SphericalGaussianBlur" || a.material.name == "BackgroundCubeMaterial" || a.material.name === "CubemapFromEquirect" || a.material.name === "EquirectangularToCubeUV")) {
1080
- k && (a.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"] || (a.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"] = !0, console.warn("Ignoring skybox or BLIT object", a, a.material.name, a.material.type)));
1081
- continue;
1082
- }
1083
- switch (a.material.type) {
1084
- case "LineBasicMaterial":
1085
- case "LineDashedMaterial":
1086
- case "PointsMaterial":
1087
- case "ShadowMaterial":
1088
- case "MeshDistanceMaterial":
1089
- case "MeshDepthMaterial":
1090
- continue;
1091
- }
1092
- if (k === "color" && a.material && !a.object.progressive_debug_color) {
1093
- a.object.progressive_debug_color = !0;
1094
- const u = Math.random() * 16777215, y = new qe({ color: u });
1095
- a.object.material = y;
1096
- }
1097
- const d = a.object;
1098
- (d instanceof V || d.isMesh) && this.updateLODs(t, e, d, r);
1099
- }
1100
- const i = s.transparent;
1101
- for (const a of i) {
1102
- const d = a.object;
1103
- (d instanceof V || d.isMesh) && this.updateLODs(t, e, d, r);
1104
- }
1105
- const l = s.transmissive;
1106
- for (const a of l) {
1107
- const d = a.object;
1108
- (d instanceof V || d.isMesh) && this.updateLODs(t, e, d, r);
1109
- }
1110
- }
1111
- /** Update the LOD levels for the renderer. */
1112
- updateLODs(t, e, s, o) {
1113
- s.userData || (s.userData = {});
1114
- let r = s[ce];
1115
- if (r || (r = new pt(), s[ce] = r), r.frames++ < 2)
1116
- return;
1117
- for (const l of z)
1118
- l.onBeforeUpdateLOD?.(this.renderer, t, e, s);
1119
- const i = this.overrideLodLevel !== void 0 ? this.overrideLodLevel : q;
1120
- i >= 0 ? (T.mesh_lod = i, T.texture_lod = i) : (this.calculateLodLevel(e, s, r, o, T), T.mesh_lod = Math.round(T.mesh_lod), T.texture_lod = Math.round(T.texture_lod)), T.mesh_lod >= 0 && this.loadProgressiveMeshes(s, T.mesh_lod), s.material && T.texture_lod >= 0 && this.loadProgressiveTextures(s.material, T.texture_lod, i), g && s.material && !s.isGizmo && Ce(s.material);
1121
- for (const l of z)
1122
- l.onAfterUpdatedLOD?.(this.renderer, t, e, s, T);
1123
- r.lastLodLevel_Mesh = T.mesh_lod, r.lastLodLevel_Texture = T.texture_lod;
1124
- }
1125
- /** Load progressive textures for the given material
1126
- * @param material the material to load the textures for
1127
- * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
1128
- * @returns Promise with true if the LOD was loaded, false if not
1129
- */
1130
- loadProgressiveTextures(t, e, s) {
1131
- if (!t) return;
1132
- if (Array.isArray(t)) {
1133
- for (const r of t)
1134
- this.loadProgressiveTextures(r, e);
1135
- return;
1136
- }
1137
- let o = !1;
1138
- if ((t[U] === void 0 || e < t[U]) && (o = !0), s !== void 0 && s >= 0 && (o = t[U] != s, e = s), o) {
1139
- t[U] = e;
1140
- const r = m.assignTextureLOD(t, e).then((i) => {
1141
- this._lodchangedlisteners.forEach((l) => l({ type: "texture", level: e, object: t }));
1142
- });
1143
- de.addPromise("texture", t, r, this._newPromiseGroups);
1144
- }
1145
- }
1146
- /** Load progressive meshes for the given mesh
1147
- * @param mesh the mesh to load the LOD for
1148
- * @param index the index of the mesh if it's part of a group
1149
- * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
1150
- * @returns Promise with true if the LOD was loaded, false if not
1151
- */
1152
- loadProgressiveMeshes(t, e) {
1153
- if (!t) return Promise.resolve(null);
1154
- let s = t[U] !== e;
1155
- const o = t["DEBUG:LOD"];
1156
- if (o != null && (s = t[U] != o, e = o), s) {
1157
- t[U] = e;
1158
- const r = t.geometry, i = m.assignMeshLOD(t, e).then((l) => (l && t[U] == e && r != t.geometry && this._lodchangedlisteners.forEach((a) => a({ type: "mesh", level: e, object: t })), l));
1159
- return de.addPromise("mesh", t, i, this._newPromiseGroups), i;
1160
- }
1161
- return Promise.resolve(null);
1162
- }
1163
- // private testIfLODLevelsAreAvailable() {
1164
- _sphere = new De();
1165
- _tempBox = new he();
1166
- _tempBox2 = new he();
1167
- tempMatrix = new Le();
1168
- _tempWorldPosition = new C();
1169
- _tempBoxSize = new C();
1170
- _tempBox2Size = new C();
1171
- static corner0 = new C();
1172
- static corner1 = new C();
1173
- static corner2 = new C();
1174
- static corner3 = new C();
1175
- static _tempPtInside = new C();
1176
- static isInside(t, e) {
1177
- const s = t.min, o = t.max, r = (s.x + o.x) * 0.5, i = (s.y + o.y) * 0.5;
1178
- return this._tempPtInside.set(r, i, s.z).applyMatrix4(e).z < 0;
1179
- }
1180
- static skinnedMeshBoundsFrameOffsetCounter = 0;
1181
- static $skinnedMeshBoundsOffset = /* @__PURE__ */ Symbol("gltf-progressive-skinnedMeshBoundsOffset");
1182
- // #region calculateLodLevel
1183
- calculateLodLevel(t, e, s, o, r) {
1184
- if (!e) {
1185
- r.mesh_lod = -1, r.texture_lod = -1;
1186
- return;
1187
- }
1188
- if (!t) {
1189
- r.mesh_lod = -1, r.texture_lod = -1;
1190
- return;
1191
- }
1192
- let l = 10 + 1, a = !1;
1193
- if (k && e["DEBUG:LOD"] != null)
1194
- return e["DEBUG:LOD"];
1195
- const d = m.getMeshLODExtension(e.geometry)?.lods, u = m.getPrimitiveIndex(e.geometry), y = d && d.length > 0, w = m.getMaterialMinMaxLODsCount(e.material), L = w.min_count !== 1 / 0 && w.min_count >= 0 && w.max_count >= 0;
1196
- if (!y && !L) {
1197
- r.mesh_lod = 0, r.texture_lod = 0;
1198
- return;
1199
- }
1200
- y || (a = !0, l = 0);
1201
- const I = this.renderer.domElement.clientHeight || this.renderer.domElement.height;
1202
- let O = e.geometry.boundingBox;
1203
- if (e.type === "SkinnedMesh") {
1204
- const c = e;
1205
- if (!c.boundingBox)
1206
- c.computeBoundingBox();
1207
- else if (this.skinnedMeshAutoUpdateBoundsInterval > 0) {
1208
- if (!c[v.$skinnedMeshBoundsOffset]) {
1209
- const b = v.skinnedMeshBoundsFrameOffsetCounter++;
1210
- c[v.$skinnedMeshBoundsOffset] = b;
1211
- }
1212
- const h = c[v.$skinnedMeshBoundsOffset];
1213
- if ((s.frames + h) % this.skinnedMeshAutoUpdateBoundsInterval === 0) {
1214
- const b = Z(c), B = c.geometry;
1215
- b && (c.geometry = b), c.computeBoundingBox(), c.geometry = B;
1216
- }
1217
- }
1218
- O = c.boundingBox;
1219
- }
1220
- if (O) {
1221
- const c = t;
1222
- if (e.geometry.attributes.color && e.geometry.attributes.color.count < 100 && e.geometry.boundingSphere) {
1223
- this._sphere.copy(e.geometry.boundingSphere), this._sphere.applyMatrix4(e.matrixWorld);
1224
- const f = t.getWorldPosition(this._tempWorldPosition);
1225
- if (this._sphere.containsPoint(f)) {
1226
- r.mesh_lod = 0, r.texture_lod = 0;
1227
- return;
1228
- }
1229
- }
1230
- if (this._tempBox.copy(O), this._tempBox.applyMatrix4(e.matrixWorld), c.isPerspectiveCamera && v.isInside(this._tempBox, this.projectionScreenMatrix)) {
1231
- r.mesh_lod = 0, r.texture_lod = 0;
1232
- return;
1233
- }
1234
- if (this._tempBox.applyMatrix4(this.projectionScreenMatrix), this.renderer.xr.enabled && c.isPerspectiveCamera && c.fov > 70) {
1235
- const f = this._tempBox.min, p = this._tempBox.max;
1236
- let D = f.x, S = f.y, G = p.x, Y = p.y;
1237
- const ee = 2, ie = 1.5, te = (f.x + p.x) * 0.5, se = (f.y + p.y) * 0.5;
1238
- D = (D - te) * ee + te, S = (S - se) * ee + se, G = (G - te) * ee + te, Y = (Y - se) * ee + se;
1239
- const Re = D < 0 && G > 0 ? 0 : Math.min(Math.abs(f.x), Math.abs(p.x)), $e = S < 0 && Y > 0 ? 0 : Math.min(Math.abs(f.y), Math.abs(p.y)), ne = Math.max(Re, $e);
1240
- s.lastCentrality = (ie - ne) * (ie - ne) * (ie - ne);
1241
- } else
1242
- s.lastCentrality = 1;
1243
- const h = this._tempBox.getSize(this._tempBoxSize);
1244
- h.multiplyScalar(0.5), screen.availHeight > 0 && I > 0 && h.multiplyScalar(I / screen.availHeight), t.isPerspectiveCamera ? h.x *= t.aspect : t.isOrthographicCamera;
1245
- const b = t.matrixWorldInverse, B = this._tempBox2;
1246
- B.copy(O), B.applyMatrix4(e.matrixWorld), B.applyMatrix4(b);
1247
- const M = B.getSize(this._tempBox2Size), N = Math.max(M.x, M.y);
1248
- if (Math.max(h.x, h.y) != 0 && N != 0 && (h.z = M.z / Math.max(M.x, M.y) * Math.max(h.x, h.y)), s.lastScreenCoverage = Math.max(h.x, h.y, h.z), s.lastScreenspaceVolume.copy(h), s.lastScreenCoverage *= s.lastCentrality, k && v.debugDrawLine) {
1249
- const f = this.tempMatrix.copy(this.projectionScreenMatrix);
1250
- f.invert();
1251
- const p = v.corner0, D = v.corner1, S = v.corner2, G = v.corner3;
1252
- p.copy(this._tempBox.min), D.copy(this._tempBox.max), D.x = p.x, S.copy(this._tempBox.max), S.y = p.y, G.copy(this._tempBox.max);
1253
- const Y = (p.z + G.z) * 0.5;
1254
- p.z = D.z = S.z = G.z = Y, p.applyMatrix4(f), D.applyMatrix4(f), S.applyMatrix4(f), G.applyMatrix4(f), v.debugDrawLine(p, D, 255), v.debugDrawLine(p, S, 255), v.debugDrawLine(D, G, 255), v.debugDrawLine(S, G, 255);
1255
- }
1256
- let _ = 999;
1257
- if (d && s.lastScreenCoverage > 0)
1258
- for (let f = 0; f < d.length; f++) {
1259
- const p = d[f], S = (p.densities?.[u] || p.density || 1e-5) / s.lastScreenCoverage;
1260
- if (u > 0 && _e() && !p.densities && !globalThis["NEEDLE:MISSING_LOD_PRIMITIVE_DENSITIES"] && (window["NEEDLE:MISSING_LOD_PRIMITIVE_DENSITIES"] = !0, console.warn("[Needle Progressive] Detected usage of mesh without primitive densities. This might cause incorrect LOD level selection: Consider re-optimizing your model by updating your Needle Integration, Needle glTF Pipeline or running optimization again on Needle Cloud.")), S < o) {
1261
- _ = f;
1262
- break;
1263
- }
1264
- }
1265
- _ < l && (l = _, a = !0);
1266
- }
1267
- if (a ? r.mesh_lod = l : r.mesh_lod = s.lastLodLevel_Mesh, k && r.mesh_lod != s.lastLodLevel_Mesh) {
1268
- const h = d?.[r.mesh_lod];
1269
- h && console.log(`Mesh LOD changed: ${s.lastLodLevel_Mesh} → ${r.mesh_lod} (density: ${h.densities?.[u].toFixed(0)}) | ${e.name}`);
1270
- }
1271
- if (L) {
1272
- const c = "saveData" in globalThis.navigator && globalThis.navigator.saveData === !0;
1273
- if (s.lastLodLevel_Texture < 0) {
1274
- if (r.texture_lod = w.max_count - 1, k) {
1275
- const h = w.lods[w.max_count - 1];
1276
- k && console.log(`First Texture LOD ${r.texture_lod} (${h.max_height}px) - ${e.name}`);
1277
- }
1278
- } else {
1279
- const h = s.lastScreenspaceVolume.x + s.lastScreenspaceVolume.y + s.lastScreenspaceVolume.z;
1280
- let b = s.lastScreenCoverage * 4;
1281
- this.context?.engine === "model-viewer" && (b *= 1.5);
1282
- const M = I / window.devicePixelRatio * b;
1283
- let N = !1;
1284
- for (let P = w.lods.length - 1; P >= 0; P--) {
1285
- const _ = w.lods[P];
1286
- if (!(c && _.max_height >= 2048) && !(Ae() && _.max_height > 4096) && (_.max_height > M || !N && P === 0)) {
1287
- if (N = !0, r.texture_lod = P, k && r.texture_lod < s.lastLodLevel_Texture) {
1288
- const x = _.max_height;
1289
- console.log(`Texture LOD changed: ${s.lastLodLevel_Texture} → ${r.texture_lod} = ${x}px
1290
- Screensize: ${M.toFixed(0)}px, Coverage: ${(100 * s.lastScreenCoverage).toFixed(2)}%, Volume ${h.toFixed(1)}
1291
- ${e.name}`);
1292
- }
1293
- break;
1294
- }
1295
- }
1296
- }
1297
- } else
1298
- r.texture_lod = 0;
1299
- }
1300
- }
1301
- class pt {
1302
- frames = 0;
1303
- lastLodLevel_Mesh = -1;
1304
- lastLodLevel_Texture = -1;
1305
- lastScreenCoverage = 0;
1306
- lastScreenspaceVolume = new C();
1307
- lastCentrality = 0;
1308
- }
1309
- const ve = /* @__PURE__ */ Symbol("NEEDLE_mesh_lod"), re = /* @__PURE__ */ Symbol("NEEDLE_texture_lod");
1310
- let fe = null;
1311
- function Ie() {
1312
- const n = mt();
1313
- n && (n.mapURLs(function(t) {
1314
- return be(), t;
1315
- }), be(), fe?.disconnect(), fe = new MutationObserver((t) => {
1316
- t.forEach((e) => {
1317
- e.addedNodes.forEach((s) => {
1318
- s instanceof HTMLElement && s.tagName.toLowerCase() === "model-viewer" && ke(s);
1319
- });
1320
- });
1321
- }), fe.observe(document, { childList: !0, subtree: !0 }));
1322
- }
1323
- function mt() {
1324
- if (typeof customElements > "u") return null;
1325
- const n = customElements.get("model-viewer");
1326
- return n || (customElements.whenDefined("model-viewer").then(() => {
1327
- console.debug("[gltf-progressive] model-viewer defined"), Ie();
1328
- }), null);
1329
- }
1330
- function be() {
1331
- if (typeof document > "u") return;
1332
- document.querySelectorAll("model-viewer").forEach((t) => {
1333
- ke(t);
1334
- });
1335
- }
1336
- const Me = /* @__PURE__ */ new WeakSet();
1337
- let yt = 0;
1338
- function ke(n) {
1339
- if (!n || Me.has(n))
1340
- return null;
1341
- Me.add(n), console.debug("[gltf-progressive] found new model-viewer..." + ++yt + `
1342
- `, n.getAttribute("src"));
1343
- let t = null, e = null, s = null;
1344
- for (let o = n; o != null; o = Object.getPrototypeOf(o)) {
1345
- const r = Object.getOwnPropertySymbols(o), i = r.find((d) => d.toString() == "Symbol(renderer)"), l = r.find((d) => d.toString() == "Symbol(scene)"), a = r.find((d) => d.toString() == "Symbol(needsRender)");
1346
- !t && i != null && (t = n[i].threeRenderer), !e && l != null && (e = n[l]), !s && a != null && (s = n[a]);
1347
- }
1348
- if (t && e) {
1349
- let o = function() {
1350
- if (s) {
1351
- let i = 0, l = setInterval(() => {
1352
- if (i++ > 5) {
1353
- clearInterval(l);
1354
- return;
1355
- }
1356
- s?.call(n);
1357
- }, 300);
1358
- }
1359
- };
1360
- console.debug("[gltf-progressive] setup model-viewer");
1361
- const r = v.get(t, { engine: "model-viewer" });
1362
- return v.addPlugin(new xt()), r.enable(), r.addEventListener("changed", () => {
1363
- s?.call(n);
1364
- }), n.addEventListener("model-visibility", (i) => {
1365
- i.detail.visible && s?.call(n);
1366
- }), n.addEventListener("load", () => {
1367
- o();
1368
- }), () => {
1369
- r.disable();
1370
- };
1371
- }
1372
- return null;
1373
- }
1374
- class xt {
1375
- _didWarnAboutMissingUrl = !1;
1376
- onBeforeUpdateLOD(t, e, s, o) {
1377
- this.tryParseMeshLOD(e, o), this.tryParseTextureLOD(e, o);
1378
- }
1379
- getUrl(t) {
1380
- if (!t)
1381
- return null;
1382
- let e = t.getAttribute("src");
1383
- return e || (e = t.src), e || (this._didWarnAboutMissingUrl || console.warn("No url found in modelviewer", t), this._didWarnAboutMissingUrl = !0), e;
1384
- }
1385
- tryGetCurrentGLTF(t) {
1386
- return t._currentGLTF;
1387
- }
1388
- tryGetCurrentModelViewer(t) {
1389
- return t.element;
1390
- }
1391
- tryParseTextureLOD(t, e) {
1392
- if (e[re] == !0) return;
1393
- e[re] = !0;
1394
- const s = this.tryGetCurrentGLTF(t), o = this.tryGetCurrentModelViewer(t), r = this.getUrl(o);
1395
- if (r && s && e.material) {
1396
- let i = function(a) {
1397
- if (a[re] == !0) return;
1398
- a[re] = !0, a.userData && (a.userData.LOD = -1);
1399
- const d = Object.keys(a);
1400
- for (let u = 0; u < d.length; u++) {
1401
- const y = d[u], w = a[y];
1402
- if (w?.isTexture === !0) {
1403
- const L = w.userData?.associations?.textures;
1404
- if (L == null) continue;
1405
- const I = s.parser.json.textures[L];
1406
- if (!I) {
1407
- console.warn("Texture data not found for texture index " + L);
1408
- continue;
1409
- }
1410
- if (I?.extensions?.[W]) {
1411
- const O = I.extensions[W];
1412
- O && r && m.registerTexture(r, w, O.lods.length, L, O);
1413
- }
1414
- }
1415
- }
1416
- };
1417
- const l = e.material;
1418
- if (Array.isArray(l)) for (const a of l) i(a);
1419
- else i(l);
1420
- }
1421
- }
1422
- tryParseMeshLOD(t, e) {
1423
- if (e[ve] == !0) return;
1424
- e[ve] = !0;
1425
- const s = this.tryGetCurrentModelViewer(t), o = this.getUrl(s);
1426
- if (!o)
1427
- return;
1428
- const r = e.userData?.gltfExtensions?.[W];
1429
- if (r && o) {
1430
- const i = e.uuid;
1431
- m.registerMesh(o, i, e, 0, r.lods.length, r);
1432
- }
1433
- }
1434
- }
1435
- function wt(...n) {
1436
- let t, e, s, o;
1437
- switch (n.length) {
1438
- case 2:
1439
- [s, e] = n, o = {};
1440
- break;
1441
- case 3:
1442
- [s, e, o] = n;
1443
- break;
1444
- case 4:
1445
- [t, e, s, o] = n;
1446
- break;
1447
- default:
1448
- throw new Error("Invalid arguments");
1449
- }
1450
- xe(e), Se(s), Te(s, {
1451
- progressive: !0,
1452
- ...o?.hints
1453
- }), s.register((i) => new m(i));
1454
- const r = v.get(e);
1455
- return o?.enableLODsManager !== !1 && r.enable(), r;
1456
- }
1457
- Ie();
1458
- if (!rt) {
1459
- const n = {
1460
- gltfProgressive: {
1461
- useNeedleProgressive: wt,
1462
- LODsManager: v,
1463
- configureLoader: Te,
1464
- getRaycastMesh: Z,
1465
- useRaycastMeshes: it
1466
- }
1467
- };
1468
- if (!globalThis.Needle)
1469
- globalThis.Needle = n;
1470
- else
1471
- for (const t in n)
1472
- globalThis.Needle[t] = n[t];
1473
- }
1474
- export {
1475
- W as EXTENSION_NAME,
1476
- v as LODsManager,
1477
- m as NEEDLE_progressive,
1478
- je as VERSION,
1479
- Se as addDracoAndKTX2Loaders,
1480
- Te as configureLoader,
1481
- xe as createLoaders,
1482
- Z as getRaycastMesh,
1483
- Ie as patchModelViewer,
1484
- ot as registerRaycastMesh,
1485
- Qe as setDracoDecoderLocation,
1486
- Je as setKTX2TranscoderLocation,
1487
- wt as useNeedleProgressive,
1488
- it as useRaycastMeshes
1489
- };