@needle-tools/gltf-progressive 1.0.0-alpha → 1.0.0-alpha.10

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.
@@ -0,0 +1,679 @@
1
+ var oe = Object.defineProperty;
2
+ var ae = (l, e, t) => e in l ? oe(l, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : l[e] = t;
3
+ var u = (l, e, t) => (ae(l, typeof e != "symbol" ? e + "" : e, t), t);
4
+ import { Mesh as q, BufferGeometry as X, Material as le, Texture as U, TextureLoader as ue, Matrix4 as j, Frustum as ce, Sphere as fe, Box3 as ee, Vector3 as R } from "three";
5
+ import { GLTFLoader as de } from "three/examples/jsm/loaders/GLTFLoader.js";
6
+ import { MeshoptDecoder as ge } from "three/examples/jsm/libs/meshopt_decoder.module.js";
7
+ import { DRACOLoader as he } from "three/examples/jsm/loaders/DRACOLoader.js";
8
+ import { KTX2Loader as pe } from "three/examples/jsm/loaders/KTX2Loader.js";
9
+ const ye = "https://www.gstatic.com/draco/versioned/decoders/1.4.1/", me = "https://www.gstatic.com/basis-universal/versioned/2021-04-15-ba1c3e4/";
10
+ let F, H, W;
11
+ function se(l) {
12
+ F || (F = new he(), F.setDecoderPath(ye), F.setDecoderConfig({ type: "js" })), W || (W = new pe(), W.setTranscoderPath(me)), H || (H = ge), l ? W.detectSupport(l) : console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail");
13
+ }
14
+ function ie(l) {
15
+ l.dracoLoader || l.setDRACOLoader(F), l.ktx2Loader || l.setKTX2Loader(W), l.meshoptDecoder || l.setMeshoptDecoder(H);
16
+ }
17
+ function Z(l) {
18
+ const t = new URL(window.location.href).searchParams.get(l);
19
+ return t == null || t === "0" || t === "false" ? !1 : t === "" ? !0 : t;
20
+ }
21
+ function Le(l, e) {
22
+ if (e === void 0 || e.startsWith("./") || e.startsWith("http") || l === void 0)
23
+ return e;
24
+ const t = l.lastIndexOf("/");
25
+ if (t >= 0) {
26
+ const r = l.substring(0, t + 1);
27
+ for (; r.endsWith("/") && e.startsWith("/"); )
28
+ e = e.substring(1);
29
+ return r + e;
30
+ }
31
+ return e;
32
+ }
33
+ const J = new Array();
34
+ function _e(l) {
35
+ J.push(l);
36
+ }
37
+ const k = "NEEDLE_progressive", S = Z("debugprogressive"), V = Symbol("needle-progressive-texture"), z = /* @__PURE__ */ new Map(), Q = /* @__PURE__ */ new Set();
38
+ if (S) {
39
+ let l = function() {
40
+ e += 1, console.log("Toggle LOD level", e, z), z.forEach((i, n) => {
41
+ for (const s of i.keys) {
42
+ const o = n[s];
43
+ if (o.isBufferGeometry === !0) {
44
+ const a = v.getMeshLODInformation(o), h = a ? Math.min(e, a.lods.length) : 0;
45
+ n["DEBUG:LOD"] = e, v.assignMeshLOD(n, h), a && (t = Math.max(t, a.lods.length - 1));
46
+ } else if (n.isMaterial === !0) {
47
+ n["DEBUG:LOD"] = e, v.assignTextureLOD(n, e);
48
+ break;
49
+ }
50
+ }
51
+ }), e >= t && (e = -1);
52
+ }, e = -1, t = 2, r = !1;
53
+ window.addEventListener("keyup", (i) => {
54
+ i.key === "p" && l(), i.key === "w" && (r = !r, Q && Q.forEach((n) => {
55
+ n.name != "BackgroundCubeMaterial" && "wireframe" in n && (n.wireframe = r);
56
+ }));
57
+ });
58
+ }
59
+ function te(l, e, t) {
60
+ var i;
61
+ if (!S)
62
+ return;
63
+ z.has(l) || z.set(l, { keys: [], sourceId: t });
64
+ const r = z.get(l);
65
+ ((i = r == null ? void 0 : r.keys) == null ? void 0 : i.includes(e)) == !1 && r.keys.push(e);
66
+ }
67
+ const M = class {
68
+ constructor(e, t) {
69
+ u(this, "parser");
70
+ u(this, "url");
71
+ S && console.log("Progressive extension registered for", t), this.parser = e, this.url = t;
72
+ }
73
+ /** The name of the extension */
74
+ get name() {
75
+ return k;
76
+ }
77
+ static getMeshLODInformation(e) {
78
+ const t = this.getAssignedLODInformation(e);
79
+ return t != null && t.key ? this.lodInfos.get(t.key) : null;
80
+ }
81
+ /** Check if a LOD level is available for a mesh or a texture
82
+ * @param obj the mesh or texture to check
83
+ * @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
84
+ * @returns true if the LOD level is available (or if any LOD level is available if level is undefined)
85
+ */
86
+ static hasLODLevelAvailable(e, t) {
87
+ var n;
88
+ if (e.isMaterial === !0) {
89
+ for (const s of Object.keys(e)) {
90
+ const o = e[s];
91
+ if (o.isTexture && this.hasLODLevelAvailable(o, t))
92
+ return !0;
93
+ }
94
+ return !1;
95
+ } else if (e.isGroup === !0) {
96
+ for (const s of e.children)
97
+ if (s.isMesh === !0 && this.hasLODLevelAvailable(s, t))
98
+ return !0;
99
+ }
100
+ let r, i;
101
+ if (e.isMesh ? r = e.geometry : (e.isBufferGeometry || e.isTexture) && (r = e), r && (n = r == null ? void 0 : r.userData) != null && n.LODS) {
102
+ const s = r.userData.LODS;
103
+ if (i = this.lodInfos.get(s.key), t === void 0)
104
+ return i != null;
105
+ if (i)
106
+ return Array.isArray(i.lods) ? t < i.lods.length : t === 0;
107
+ }
108
+ return !1;
109
+ }
110
+ /** Load a different resolution of a mesh (if available)
111
+ * @param context the context
112
+ * @param source the sourceid of the file from which the mesh is loaded (this is usually the component's sourceId)
113
+ * @param mesh the mesh to load the LOD for
114
+ * @param level the level of detail to load (0 is the highest resolution)
115
+ * @returns a promise that resolves to the mesh with the requested LOD level
116
+ * @example
117
+ * ```javascript
118
+ * const mesh = this.gameObject as Mesh;
119
+ * NEEDLE_progressive.assignMeshLOD(context, sourceId, mesh, 1).then(mesh => {
120
+ * console.log("Mesh with LOD level 1 loaded", mesh);
121
+ * });
122
+ * ```
123
+ */
124
+ static assignMeshLOD(e, t) {
125
+ var r;
126
+ if (!e)
127
+ return Promise.resolve(null);
128
+ if (e instanceof q || e.isMesh === !0) {
129
+ const i = e.geometry, n = this.getAssignedLODInformation(i);
130
+ if (!n)
131
+ return Promise.resolve(null);
132
+ for (const s of J)
133
+ (r = s.onBeforeGetLODMesh) == null || r.call(s, e, t);
134
+ return e["LOD:requested level"] = t, M.getOrLoadLOD(i, t).then((s) => {
135
+ if (e["LOD:requested level"] === t) {
136
+ if (delete e["LOD:requested level"], Array.isArray(s)) {
137
+ const o = n.index || 0;
138
+ s = s[o];
139
+ }
140
+ s && i != s && s instanceof X && (e.geometry = s, S && te(e, "geometry", n.url));
141
+ }
142
+ return s;
143
+ }).catch((s) => (console.error("Error loading mesh LOD", e, s), null));
144
+ } else
145
+ S && console.error("Invalid call to assignMeshLOD: Request mesh LOD but the object is not a mesh", e);
146
+ return Promise.resolve(null);
147
+ }
148
+ /** Load a different resolution of a texture (if available)
149
+ * @param context the context
150
+ * @param source the sourceid of the file from which the texture is loaded (this is usually the component's sourceId)
151
+ * @param materialOrTexture the material or texture to load the LOD for (if passing in a material all textures in the material will be loaded)
152
+ * @param level the level of detail to load (0 is the highest resolution) - currently only 0 is supported
153
+ * @returns a promise that resolves to the material or texture with the requested LOD level
154
+ */
155
+ static assignTextureLOD(e, t = 0) {
156
+ if (!e)
157
+ return Promise.resolve(null);
158
+ if (e instanceof le || e.isMaterial === !0) {
159
+ const r = e, i = [], n = new Array();
160
+ if (S && Q.add(r), r.uniforms && r.isRawShaderMaterial || r.isShaderMaterial === !0) {
161
+ const s = r;
162
+ for (const o of Object.keys(s.uniforms)) {
163
+ const a = s.uniforms[o].value;
164
+ if ((a == null ? void 0 : a.isTexture) === !0) {
165
+ const h = this.assignTextureLODForSlot(a, t, r, o);
166
+ i.push(h), n.push(o);
167
+ }
168
+ }
169
+ } else
170
+ for (const s of Object.keys(r)) {
171
+ const o = r[s];
172
+ if ((o == null ? void 0 : o.isTexture) === !0) {
173
+ const a = this.assignTextureLODForSlot(o, t, r, s);
174
+ i.push(a), n.push(s);
175
+ }
176
+ }
177
+ return Promise.all(i).then((s) => {
178
+ const o = new Array();
179
+ for (let a = 0; a < s.length; a++) {
180
+ const h = s[a], g = n[a];
181
+ h && h.isTexture === !0 ? o.push({ material: r, slot: g, texture: h, level: t }) : o.push({ material: r, slot: g, texture: null, level: t });
182
+ }
183
+ return o;
184
+ });
185
+ }
186
+ if (e instanceof U || e.isTexture === !0) {
187
+ const r = e;
188
+ return this.assignTextureLODForSlot(r, t, null, null);
189
+ }
190
+ return Promise.resolve(null);
191
+ }
192
+ static assignTextureLODForSlot(e, t, r, i) {
193
+ return (e == null ? void 0 : e.isTexture) !== !0 ? Promise.resolve(null) : M.getOrLoadLOD(e, t).then((n) => {
194
+ if (Array.isArray(n))
195
+ return null;
196
+ if ((n == null ? void 0 : n.isTexture) === !0) {
197
+ if (n != e && (r && i && (r[i] = n), S && i && r)) {
198
+ const s = this.getAssignedLODInformation(e);
199
+ s && te(r, i, s.url);
200
+ }
201
+ return n;
202
+ } else
203
+ S == "verbose" && console.warn("No LOD found for", e, t);
204
+ return null;
205
+ }).catch((n) => (console.error("Error loading LOD", e, n), null));
206
+ }
207
+ afterRoot(e) {
208
+ var t, r;
209
+ return S && console.log("AFTER", this.url, e), (t = this.parser.json.textures) == null || t.forEach((i, n) => {
210
+ if (i != null && i.extensions) {
211
+ const s = i == null ? void 0 : i.extensions[k];
212
+ if (s) {
213
+ let o = !1;
214
+ for (const a of this.parser.associations.keys())
215
+ a.isTexture === !0 && this.parser.associations.get(a).textures === n && (o = !0, M.registerTexture(this.url, a, n, s));
216
+ o || this.parser.getDependency("texture", n).then((a) => {
217
+ a && M.registerTexture(this.url, a, n, s);
218
+ });
219
+ }
220
+ }
221
+ }), (r = this.parser.json.meshes) == null || r.forEach((i, n) => {
222
+ if (i != null && i.extensions) {
223
+ const s = i == null ? void 0 : i.extensions[k];
224
+ if (s && s.lods) {
225
+ for (const o of this.parser.associations.keys())
226
+ if (o.isMesh) {
227
+ const a = this.parser.associations.get(o);
228
+ a.meshes === n && M.registerMesh(this.url, s.guid, o, s.lods.length, a.primitives, s);
229
+ }
230
+ }
231
+ }
232
+ }), null;
233
+ }
234
+ static async getOrLoadLOD(e, t) {
235
+ var o, a, h;
236
+ const r = S == "verbose", i = e.userData.LODS;
237
+ if (!i)
238
+ return null;
239
+ const n = i == null ? void 0 : i.key;
240
+ let s;
241
+ if (e.isTexture === !0) {
242
+ const g = e;
243
+ g.source && g.source[V] && (s = g.source[V]);
244
+ }
245
+ if (s || (s = M.lodInfos.get(n)), s) {
246
+ if (t > 0) {
247
+ let f = !1;
248
+ const w = Array.isArray(s.lods);
249
+ if (w && t >= s.lods.length ? f = !0 : w || (f = !0), f)
250
+ return this.lowresCache.get(n);
251
+ }
252
+ const g = Array.isArray(s.lods) ? s.lods[t].path : s.lods;
253
+ if (!g)
254
+ return S && !s["missing:uri"] && (s["missing:uri"] = !0, console.warn("Missing uri for progressive asset for LOD " + t, s)), null;
255
+ const c = Le(i.url, g);
256
+ if (c.endsWith(".glb") || c.endsWith(".gltf")) {
257
+ if (!s.guid)
258
+ return console.warn("missing pointer for glb/gltf texture", s), null;
259
+ const f = c + "_" + s.guid, w = this.previouslyLoaded.get(f);
260
+ if (w !== void 0) {
261
+ r && console.log(`LOD ${t} was already loading/loaded: ${f}`);
262
+ let D = await w.catch((I) => (console.error(`Error loading LOD ${t} from ${c}
263
+ `, I), null)), C = !1;
264
+ if (D == null || (D instanceof U && e instanceof U ? (o = D.image) != null && o.data || (a = D.source) != null && a.data ? D = this.copySettings(e, D) : (C = !0, this.previouslyLoaded.delete(f)) : D instanceof X && e instanceof X && ((h = D.attributes.position) != null && h.array || (C = !0, this.previouslyLoaded.delete(f)))), !C)
265
+ return D;
266
+ }
267
+ const L = s, A = new Promise(async (D, C) => {
268
+ const I = new de();
269
+ ie(I), S && (await new Promise((y) => setTimeout(y, 1e3)), r && console.warn("Start loading (delayed) " + c, L.guid));
270
+ let m = c;
271
+ if (L && Array.isArray(L.lods)) {
272
+ const y = L.lods[t];
273
+ y.hash && (m += "?v=" + y.hash);
274
+ }
275
+ const p = await I.loadAsync(m).catch((y) => (console.error(`Error loading LOD ${t} from ${c}
276
+ `, y), null));
277
+ if (!p)
278
+ return null;
279
+ const b = p.parser;
280
+ r && console.log("Loading finished " + c, L.guid);
281
+ let x = 0;
282
+ if (p.parser.json.textures) {
283
+ let y = !1;
284
+ for (const d of p.parser.json.textures) {
285
+ if (d != null && d.extensions) {
286
+ const O = d == null ? void 0 : d.extensions[k];
287
+ if (O != null && O.guid && O.guid === L.guid) {
288
+ y = !0;
289
+ break;
290
+ }
291
+ }
292
+ x++;
293
+ }
294
+ if (y) {
295
+ let d = await b.getDependency("texture", x);
296
+ return r && console.log('change "' + e.name + '" → "' + d.name + '"', c, x, d, f), e instanceof U && (d = this.copySettings(e, d)), d && (d.guid = L.guid), D(d);
297
+ }
298
+ }
299
+ if (x = 0, p.parser.json.meshes) {
300
+ let y = !1;
301
+ for (const d of p.parser.json.meshes) {
302
+ if (d != null && d.extensions) {
303
+ const O = d == null ? void 0 : d.extensions[k];
304
+ if (O != null && O.guid && O.guid === L.guid) {
305
+ y = !0;
306
+ break;
307
+ }
308
+ }
309
+ x++;
310
+ }
311
+ if (y) {
312
+ const d = await b.getDependency("mesh", x), O = L;
313
+ if (r && console.log(`Loaded Mesh "${d.name}"`, c, x, d, f), d.isMesh === !0) {
314
+ const P = d.geometry;
315
+ return M.assignLODInformation(i.url, P, n, t, void 0, O.density), D(P);
316
+ } else {
317
+ const P = new Array();
318
+ for (let _ = 0; _ < d.children.length; _++) {
319
+ const E = d.children[_];
320
+ if (E instanceof q) {
321
+ const N = E.geometry;
322
+ M.assignLODInformation(i.url, N, n, t, _, O.density), P.push(N);
323
+ }
324
+ }
325
+ return D(P);
326
+ }
327
+ }
328
+ }
329
+ return D(null);
330
+ });
331
+ return this.previouslyLoaded.set(f, A), await A;
332
+ } else if (e instanceof U) {
333
+ r && console.log("Load texture from uri: " + c);
334
+ const w = await new ue().loadAsync(c);
335
+ return w ? (w.guid = s.guid, w.flipY = !1, w.needsUpdate = !0, w.colorSpace = e.colorSpace, r && console.log(s, w)) : S && console.warn("failed loading", c), w;
336
+ }
337
+ } else
338
+ S && console.warn(`Can not load LOD ${t}: no LOD info found for "${n}" ${e.name}`, e.type);
339
+ return null;
340
+ }
341
+ static assignLODInformation(e, t, r, i, n, s) {
342
+ if (!t)
343
+ return;
344
+ t.userData || (t.userData = {});
345
+ const o = new De(e, r, i, n, s);
346
+ t.userData.LODS = o, t.userData.LOD = i;
347
+ }
348
+ static getAssignedLODInformation(e) {
349
+ var t;
350
+ return ((t = e == null ? void 0 : e.userData) == null ? void 0 : t.LODS) || null;
351
+ }
352
+ static copySettings(e, t) {
353
+ const r = this._copiedTextures.get(e);
354
+ return r || (t = t.clone(), this._copiedTextures.set(e, t), t.offset = e.offset, t.repeat = e.repeat, t.colorSpace = e.colorSpace, t);
355
+ }
356
+ };
357
+ let v = M;
358
+ /**
359
+ * Register a texture with LOD information
360
+ */
361
+ u(v, "registerTexture", (e, t, r, i) => {
362
+ S && console.log("> Progressive: register texture", r, t.name, t.uuid, t, i), t.source && (t.source[V] = i);
363
+ const n = i.guid;
364
+ M.assignLODInformation(e, t, n, 0, 0, void 0), M.lodInfos.set(n, i), M.lowresCache.set(n, t);
365
+ }), /**
366
+ * Register a mesh with LOD information
367
+ */
368
+ u(v, "registerMesh", (e, t, r, i, n, s) => {
369
+ var h;
370
+ S && console.log("> Progressive: register mesh", n, r.name, s, r.uuid, r);
371
+ const o = r.geometry;
372
+ o.userData || (o.userData = {}), M.assignLODInformation(e, o, t, i, n, s.density), M.lodInfos.set(t, s);
373
+ let a = M.lowresCache.get(t);
374
+ a ? a.push(r.geometry) : a = [r.geometry], M.lowresCache.set(t, a);
375
+ for (const g of J)
376
+ (h = g.onRegisteredNewMesh) == null || h.call(g, r, s);
377
+ }), /** A map of key = asset uuid and value = LOD information */
378
+ u(v, "lodInfos", /* @__PURE__ */ new Map()), /** cache of already loaded mesh lods */
379
+ u(v, "previouslyLoaded", /* @__PURE__ */ new Map()), /** this contains the geometry/textures that were originally loaded */
380
+ u(v, "lowresCache", /* @__PURE__ */ new Map()), u(v, "_copiedTextures", /* @__PURE__ */ new Map());
381
+ class De {
382
+ constructor(e, t, r, i, n) {
383
+ u(this, "url");
384
+ /** the key to lookup the LOD information */
385
+ u(this, "key");
386
+ u(this, "level");
387
+ /** For multi objects (e.g. a group of meshes) this is the index of the object */
388
+ u(this, "index");
389
+ /** the mesh density */
390
+ u(this, "density");
391
+ this.url = e, this.key = t, this.level = r, i != null && (this.index = i), n != null && (this.density = n);
392
+ }
393
+ }
394
+ const Y = Z("debugprogressive"), xe = Z("noprogressive"), T = class {
395
+ constructor(e) {
396
+ u(this, "renderer");
397
+ u(this, "projectionScreenMatrix", new j());
398
+ u(this, "cameraFrustrum", new ce());
399
+ /**
400
+ * The update interval in frames. If set to 0, the LODs will be updated every frame. If set to 1, the LODs will be updated every second frame, etc.
401
+ */
402
+ u(this, "updateInterval", 0);
403
+ /**
404
+ * If set to true, the LODsManager will not update the LODs.
405
+ */
406
+ u(this, "pause", !1);
407
+ u(this, "plugins", []);
408
+ u(this, "_frame", 0);
409
+ u(this, "_originalRender");
410
+ // private testIfLODLevelsAreAvailable() {
411
+ u(this, "_sphere", new fe());
412
+ u(this, "_tempBox", new ee());
413
+ u(this, "tempMatrix", new j());
414
+ u(this, "_tempWorldPosition", new R());
415
+ u(this, "_tempBoxSize", new R());
416
+ u(this, "_tempBox2Size", new R());
417
+ this.renderer = e;
418
+ }
419
+ /** @internal */
420
+ static getObjectLODState(e) {
421
+ var t;
422
+ return (t = e.userData) == null ? void 0 : t.LOD_state;
423
+ }
424
+ /**
425
+ * Enable the LODsManager. This will replace the render method of the renderer with a method that updates the LODs.
426
+ */
427
+ enable() {
428
+ if (this._originalRender)
429
+ return;
430
+ let e = 0;
431
+ this._originalRender = this.renderer.render;
432
+ const t = this;
433
+ se(this.renderer), this.renderer.render = function(r, i) {
434
+ t.renderer.getRenderTarget() == null && (e = 0, t._frame += 1);
435
+ const s = t._frame, o = e++;
436
+ t.onBeforeRender(r, i, o, s), t._originalRender.call(this, r, i), t.onAfterRender(r, i, o, s);
437
+ };
438
+ }
439
+ disable() {
440
+ this._originalRender && (this.renderer.render = this._originalRender, this._originalRender = void 0);
441
+ }
442
+ onBeforeRender(e, t, r, i) {
443
+ }
444
+ onAfterRender(e, t, r, i) {
445
+ var n, s;
446
+ if (!this.pause && r == 0) {
447
+ if (xe || this.updateInterval > 0 && i % this.updateInterval != 0)
448
+ return;
449
+ this.projectionScreenMatrix.multiplyMatrices(t.projectionMatrix, t.matrixWorldInverse), this.cameraFrustrum.setFromProjectionMatrix(this.projectionScreenMatrix, this.renderer.coordinateSystem);
450
+ const o = 1e5, a = this.renderer.renderLists.get(e, r), h = a.opaque;
451
+ for (const c of h) {
452
+ if (c.material && (((n = c.geometry) == null ? void 0 : n.type) === "BoxGeometry" || ((s = c.geometry) == null ? void 0 : s.type) === "BufferGeometry") && (c.material.name === "SphericalGaussianBlur" || c.material.name == "BackgroundCubeMaterial" || c.material.name === "CubemapFromEquirect" || c.material.name === "EquirectangularToCubeUV")) {
453
+ Y && (c.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"] || (c.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"] = !0, console.warn("Ignoring skybox or BLIT object", c, c.material.name, c.material.type)));
454
+ continue;
455
+ }
456
+ const f = c.object;
457
+ (f instanceof q || f.isMesh) && this.updateLODs(e, t, f, o);
458
+ }
459
+ const g = a.transparent;
460
+ for (const c of g) {
461
+ const f = c.object;
462
+ (f instanceof q || f.isMesh) && this.updateLODs(e, t, f, o);
463
+ }
464
+ }
465
+ }
466
+ /** Update the LOD levels for the renderer. */
467
+ updateLODs(e, t, r, i) {
468
+ var a, h;
469
+ for (const g of this.plugins)
470
+ (a = g.onBeforeUpdateLOD) == null || a.call(g, this.renderer, e, t, r);
471
+ let n = r.userData.LOD_state;
472
+ n || (n = new we(), r.userData.LOD_state = n);
473
+ let s = this.calculateLodLevel(t, r, n, i);
474
+ s = Math.round(s), s >= 0 && this.loadProgressiveMeshes(r, s);
475
+ let o = 0;
476
+ if (r.material) {
477
+ const g = r["DEBUG:LOD"];
478
+ if (g != null && (o = g), Array.isArray(r.material))
479
+ for (const c of r.material)
480
+ this.loadProgressiveTextures(c, o);
481
+ else
482
+ this.loadProgressiveTextures(r.material, o);
483
+ }
484
+ for (const g of this.plugins)
485
+ (h = g.onAfterUpdatedLOD) == null || h.call(g, this.renderer, e, t, r, s);
486
+ n.lastLodLevel = s;
487
+ }
488
+ /** Load progressive textures for the given material
489
+ * @param material the material to load the textures for
490
+ * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
491
+ * @returns Promise with true if the LOD was loaded, false if not
492
+ */
493
+ loadProgressiveTextures(e, t) {
494
+ return e && e.userData && e.userData.LOD !== t ? (e.userData.LOD = t, v.assignTextureLOD(e, t)) : Promise.resolve(null);
495
+ }
496
+ /** Load progressive meshes for the given mesh
497
+ * @param mesh the mesh to load the LOD for
498
+ * @param index the index of the mesh if it's part of a group
499
+ * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
500
+ * @returns Promise with true if the LOD was loaded, false if not
501
+ */
502
+ loadProgressiveMeshes(e, t) {
503
+ if (!e)
504
+ return Promise.resolve(null);
505
+ if (e.userData || (e.userData = {}), e.userData.LOD !== t) {
506
+ e.userData.LOD = t;
507
+ const r = e.geometry;
508
+ return v.assignMeshLOD(e, t).then((i) => (i && e.userData.LOD == t && r != e.geometry, i));
509
+ }
510
+ return Promise.resolve(null);
511
+ }
512
+ calculateLodLevel(e, t, r, i) {
513
+ var o;
514
+ if (!t)
515
+ return -1;
516
+ let s = 10 + 1;
517
+ if (e) {
518
+ if (Y && t["DEBUG:LOD"] != null)
519
+ return t["DEBUG:LOD"];
520
+ const a = v.getMeshLODInformation(t.geometry), h = a == null ? void 0 : a.lods;
521
+ if (!h || h.length <= 0 || !((o = this.cameraFrustrum) != null && o.intersectsObject(t)))
522
+ return 99;
523
+ const g = t.geometry.boundingBox;
524
+ if (g && e.isPerspectiveCamera) {
525
+ const c = e;
526
+ if (t.geometry.attributes.color && t.geometry.attributes.color.count < 100 && t.geometry.boundingSphere) {
527
+ this._sphere.copy(t.geometry.boundingSphere), this._sphere.applyMatrix4(t.matrixWorld);
528
+ const m = e.getWorldPosition(this._tempWorldPosition);
529
+ if (this._sphere.containsPoint(m))
530
+ return 0;
531
+ }
532
+ if (this._tempBox.copy(g), this._tempBox.applyMatrix4(t.matrixWorld), this._tempBox.applyMatrix4(this.projectionScreenMatrix), this.renderer.xr.enabled && c.fov > 70) {
533
+ const m = this._tempBox.min, p = this._tempBox.max;
534
+ let b = m.x, x = m.y, y = p.x, d = p.y;
535
+ const O = 2, P = 1.5, _ = (m.x + p.x) * 0.5, E = (m.y + p.y) * 0.5;
536
+ b = (b - _) * O + _, x = (x - E) * O + E, y = (y - _) * O + _, d = (d - E) * O + E;
537
+ const N = b < 0 && y > 0 ? 0 : Math.min(Math.abs(m.x), Math.abs(p.x)), ne = x < 0 && d > 0 ? 0 : Math.min(Math.abs(m.y), Math.abs(p.y)), K = Math.max(N, ne);
538
+ r.lastCentrality = (P - K) * (P - K) * (P - K);
539
+ } else
540
+ r.lastCentrality = 1;
541
+ const f = this._tempBox.getSize(this._tempBoxSize);
542
+ f.multiplyScalar(0.5), screen.availHeight > 0 && f.multiplyScalar(this.renderer.domElement.clientHeight / screen.availHeight), f.x *= c.aspect;
543
+ const w = e.matrixWorldInverse, L = new ee();
544
+ L.copy(g), L.applyMatrix4(t.matrixWorld), L.applyMatrix4(w);
545
+ const A = L.getSize(this._tempBox2Size), G = Math.max(A.x, A.y);
546
+ if (Math.max(f.x, f.y) != 0 && G != 0 && (f.z = A.z / Math.max(A.x, A.y) * Math.max(f.x, f.y)), r.lastScreenCoverage = Math.max(f.x, f.y, f.z), r.lastScreenspaceVolume.copy(f), r.lastScreenCoverage *= r.lastCentrality, Y && T.debugDrawLine) {
547
+ const m = this.tempMatrix.copy(this.projectionScreenMatrix);
548
+ m.invert();
549
+ const p = T.corner0, b = T.corner1, x = T.corner2, y = T.corner3;
550
+ p.copy(this._tempBox.min), b.copy(this._tempBox.max), b.x = p.x, x.copy(this._tempBox.max), x.y = p.y, y.copy(this._tempBox.max);
551
+ const d = (p.z + y.z) * 0.5;
552
+ p.z = b.z = x.z = y.z = d, p.applyMatrix4(m), b.applyMatrix4(m), x.applyMatrix4(m), y.applyMatrix4(m), T.debugDrawLine(p, b, 255), T.debugDrawLine(p, x, 255), T.debugDrawLine(b, y, 255), T.debugDrawLine(x, y, 255);
553
+ }
554
+ let C = 999;
555
+ if (h && r.lastScreenCoverage > 0) {
556
+ for (let m = 0; m < h.length; m++)
557
+ if (h[m].density / r.lastScreenCoverage < i) {
558
+ C = m;
559
+ break;
560
+ }
561
+ }
562
+ C < s && (s = C);
563
+ }
564
+ }
565
+ return s;
566
+ }
567
+ };
568
+ let B = T;
569
+ /** 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.
570
+ */
571
+ u(B, "debugDrawLine"), u(B, "corner0", new R()), u(B, "corner1", new R()), u(B, "corner2", new R()), u(B, "corner3", new R());
572
+ class we {
573
+ constructor() {
574
+ u(this, "lastLodLevel", 0);
575
+ u(this, "lastScreenCoverage", 0);
576
+ u(this, "lastScreenspaceVolume", new R());
577
+ u(this, "lastCentrality", 0);
578
+ }
579
+ }
580
+ const re = Symbol("NEEDLE_mesh_lod"), $ = Symbol("NEEDLE_texture_lod");
581
+ function Oe(l) {
582
+ if (!l)
583
+ return null;
584
+ let e = null, t = null;
585
+ for (let r = l; r != null; r = Object.getPrototypeOf(r)) {
586
+ const i = Object.getOwnPropertySymbols(r), n = i.find((o) => o.toString() == "Symbol(renderer)"), s = i.find((o) => o.toString() == "Symbol(scene)");
587
+ !e && n != null && (e = l[n].threeRenderer), !t && s != null && (t = l[s]);
588
+ }
589
+ if (e) {
590
+ console.log("Adding Needle LODs to modelviewer");
591
+ const r = new B(e);
592
+ if (r.plugins.push(new Me(l)), r.enable(), t) {
593
+ const i = t.camera || t.traverse((n) => n.type == "PerspectiveCamera")[0];
594
+ i && e.render(t, i);
595
+ }
596
+ return () => {
597
+ r.disable();
598
+ };
599
+ }
600
+ return null;
601
+ }
602
+ class Me {
603
+ constructor(e) {
604
+ u(this, "modelviewer");
605
+ u(this, "_didWarnAboutMissingUrl", !1);
606
+ this.modelviewer = e;
607
+ }
608
+ onBeforeUpdateLOD(e, t, r, i) {
609
+ this.tryParseMeshLOD(t, i), this.tryParseTextureLOD(t, i);
610
+ }
611
+ getUrl() {
612
+ let e = this.modelviewer.getAttribute("src");
613
+ return e || (e = this.modelviewer.src), e || (this._didWarnAboutMissingUrl || console.warn("No url found in modelviewer", this.modelviewer), this._didWarnAboutMissingUrl = !0), e;
614
+ }
615
+ tryGetCurrentGLTF(e) {
616
+ return e._currentGLTF;
617
+ }
618
+ tryParseTextureLOD(e, t) {
619
+ if (t[$] == !0)
620
+ return;
621
+ t[$] = !0;
622
+ const r = this.tryGetCurrentGLTF(e), i = this.getUrl();
623
+ if (i && r && t.material) {
624
+ let n = function(o) {
625
+ var h, g, c;
626
+ if (o[$] == !0)
627
+ return;
628
+ o[$] = !0, o.userData && (o.userData.LOD = -1);
629
+ const a = Object.keys(o);
630
+ for (let f = 0; f < a.length; f++) {
631
+ const w = a[f], L = o[w];
632
+ if ((L == null ? void 0 : L.isTexture) === !0) {
633
+ const A = (g = (h = L.userData) == null ? void 0 : h.associations) == null ? void 0 : g.textures, G = r.parser.json.textures[A];
634
+ if ((c = G.extensions) != null && c[k]) {
635
+ const D = G.extensions[k];
636
+ D && i && v.registerTexture(i, L, D.lods.length, D);
637
+ }
638
+ }
639
+ }
640
+ };
641
+ const s = t.material;
642
+ if (Array.isArray(s))
643
+ for (const o of s)
644
+ n(o);
645
+ else
646
+ n(s);
647
+ }
648
+ }
649
+ tryParseMeshLOD(e, t) {
650
+ var n, s;
651
+ if (t[re] == !0)
652
+ return;
653
+ t[re] = !0;
654
+ const r = this.getUrl();
655
+ if (!r)
656
+ return;
657
+ const i = (s = (n = t.userData) == null ? void 0 : n.gltfExtensions) == null ? void 0 : s[k];
658
+ if (i && r) {
659
+ const o = t.uuid;
660
+ v.registerMesh(r, o, t, 0, i.lods.length, i);
661
+ }
662
+ }
663
+ }
664
+ function Be(l, e, t, r) {
665
+ se(e), ie(t), t.register((n) => new v(n, l));
666
+ const i = new B(e);
667
+ return (r == null ? void 0 : r.enableLODsManager) !== !1 && i.enable(), i;
668
+ }
669
+ document.addEventListener("DOMContentLoaded", () => {
670
+ Oe(document.querySelector("model-viewer"));
671
+ });
672
+ export {
673
+ k as EXTENSION_NAME,
674
+ B as LODsManager,
675
+ v as NEEDLE_progressive,
676
+ Oe as patchModelViewer,
677
+ _e as registerPlugin,
678
+ Be as useNeedleProgressive
679
+ };