@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.
@@ -1,387 +1,381 @@
1
- import { Box3, BufferGeometry, Camera, Frustum, Material, Matrix4, Mesh, Object3D, PerspectiveCamera, Scene, Sphere, Texture, Vector3, WebGLRenderer } from "three";
2
- import { NEEDLE_progressive, ProgressiveMaterialTextureLoadingResult } from "./extension.js";
3
- import { createLoaders } from "./loaders.js"
4
- import { getParam } from "./utils.js"
5
- import { NEEDLE_progressive_plugin } from "./plugins/plugin.js";
6
-
7
- let debugProgressiveLoading = getParam("debugprogressive");
8
- const suppressProgressiveLoading = getParam("noprogressive");
9
-
10
-
11
- export class LODsManager {
12
- readonly renderer: WebGLRenderer;
13
- readonly projectionScreenMatrix = new Matrix4();
14
- readonly cameraFrustrum = new Frustum();
15
-
16
- updateInterval: number = 0;
17
- pause: boolean = false;
18
-
19
- readonly plugins: NEEDLE_progressive_plugin[] = [];
20
-
21
- constructor(renderer: WebGLRenderer) {
22
- this.renderer = renderer;
23
- }
24
-
25
- private _originalRender?: (scene: Scene, camera: Camera) => void;
26
-
27
- enable() {
28
- if (this._originalRender) return;
29
- let stack = 0;
30
- // Save the original render method
31
- this._originalRender = this.renderer.render;
32
- const self = this;
33
- let frames = 0;
34
- createLoaders(this.renderer);
35
- this.renderer.render = function (scene: Scene, camera: Camera) {
36
- const frame = frames++;
37
- const level = stack++;
38
- self._originalRender!.call(this, scene, camera);
39
- self.onUpdateLODs(scene, camera, level, frame);
40
- stack--;
41
- };
42
- }
43
- disable() {
44
- if (!this._originalRender) return;
45
- this.renderer.render = this._originalRender;
46
- this._originalRender = undefined;
47
- }
48
-
49
-
50
-
51
- private onUpdateLODs(scene: Scene, camera: Camera, stack: number, frame: number) {
52
-
53
- if (suppressProgressiveLoading) return;
54
- if (this.pause) return;
55
- if (this.updateInterval > 0 && frame % this.updateInterval != 0) return;
56
-
57
- this.projectionScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
58
- this.cameraFrustrum.setFromProjectionMatrix(this.projectionScreenMatrix, this.renderer.coordinateSystem);
59
- const desiredDensity = 100_000;
60
-
61
- // const isLowPerformanceDevice = false;// isMobileDevice();
62
-
63
- // Experiment: quick & dirty performance-adaptive LODs
64
- /*
65
- if (this.context.time.smoothedFps < 59) {
66
- currentAllowedDensity *= 0.5;
67
- }
68
- else if (this.context.time.smoothedFps >= 59) {
69
- currentAllowedDensity *= 1.25;
70
- }
71
- */
72
-
73
- const renderList = this.renderer.renderLists.get(scene, stack);
74
- const opaque = renderList.opaque;
75
- for (const entry of opaque) {
76
- const object = entry.object as any;
77
-
78
- for (const plugin of this.plugins) {
79
- plugin.onBeforeUpdateLOD?.(this.renderer, scene, camera, object);
80
- }
81
-
82
- if (object instanceof Mesh || (object.isMesh)) {
83
- this.updateLODs(camera, object, desiredDensity);
84
- }
85
- }
86
- }
87
-
88
- /** Update the LOD levels for the renderer. */
89
- private updateLODs(camera: Camera, object: Mesh, desiredDensity: number) {
90
-
91
-
92
- // we currently only support auto LOD changes for meshes
93
- // if (this.hasMeshLODs) {
94
- let state = object.userData.LOD_state as LOD_state;
95
- if (!state) {
96
- state = new LOD_state();
97
- object.userData.LOD_state = state;
98
- }
99
-
100
- let level = this.calculateLodLevel(camera, object, state, desiredDensity);
101
- level = Math.round(level);
102
- state.lastLodLevel = level;
103
- // }
104
-
105
- if (level >= 0) {
106
- this.loadProgressiveMeshes(object, level);
107
- }
108
-
109
- // TODO: we currently can not switch texture lods because we need better caching for the textures internally (see copySettings in progressive + NE-4431)
110
- let textureLOD = 0;// Math.max(0, LODlevel - 2)
111
-
112
- if (object.material) {
113
- const debugLevel = object["DEBUG:LOD"];
114
- if (debugLevel != undefined) textureLOD = debugLevel;
115
-
116
- if (Array.isArray(object.material)) {
117
- for (const mat of object.material) {
118
- this.loadProgressiveTextures(mat, textureLOD);
119
- }
120
- }
121
- else {
122
- this.loadProgressiveTextures(object.material, textureLOD);
123
- }
124
- }
125
- }
126
-
127
-
128
- /** Load progressive textures for the given material
129
- * @param material the material to load the textures for
130
- * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
131
- * @returns Promise with true if the LOD was loaded, false if not
132
- */
133
- private loadProgressiveTextures(material: Material, level: number): Promise<ProgressiveMaterialTextureLoadingResult[] | Texture | null> {
134
- if (!material) return Promise.resolve(null);
135
- if (material.userData && material.userData.LOD !== level) {
136
- material.userData.LOD = level;
137
- return NEEDLE_progressive.assignTextureLOD(material, level);
138
- }
139
- return Promise.resolve(null);
140
- }
141
-
142
- /** Load progressive meshes for the given mesh
143
- * @param mesh the mesh to load the LOD for
144
- * @param index the index of the mesh if it's part of a group
145
- * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
146
- * @returns Promise with true if the LOD was loaded, false if not
147
- */
148
- private loadProgressiveMeshes(mesh: Mesh, level: number): Promise<BufferGeometry | null> {
149
- level = 0;
150
- if (!mesh) return Promise.resolve(null);
151
- if (!mesh.userData) mesh.userData = {};
152
- if (mesh.userData.LOD !== level) {
153
- mesh.userData.LOD = level;
154
- const originalGeometry = mesh.geometry;
155
- return NEEDLE_progressive.assignMeshLOD(mesh, level).then(res => {
156
- if (res && mesh.userData.LOD == level && originalGeometry != mesh.geometry) {
157
- // update the lightmap
158
- // this.applyLightmapping();
159
-
160
- // if (this.handles) {
161
- // for (const inst of this.handles) {
162
- // // if (inst["LOD"] < level) continue;
163
- // // inst["LOD"] = level;
164
- // inst.setGeometry(mesh.geometry);
165
- // }
166
- // }
167
- }
168
- return res;
169
- })
170
- }
171
- return Promise.resolve(null);
172
- }
173
-
174
- // private testIfLODLevelsAreAvailable() {
175
-
176
- private readonly _sphere = new Sphere();
177
- private readonly _box = new Box3();
178
- private readonly tempMatrix = new Matrix4();
179
- private readonly _tempWorldPosition = new Vector3();
180
- private readonly _tempBoxSize = new Vector3();
181
- private readonly _tempBox2Size = new Vector3();
182
-
183
- private static corner0 = new Vector3();
184
- private static corner1 = new Vector3();
185
- private static corner2 = new Vector3();
186
- private static corner3 = new Vector3();
187
-
188
- static debugDrawLine: (a: Vector3, b: Vector3, color: number) => void | null;
189
-
190
- private calculateLodLevel(camera: Camera, mesh: Mesh, state: LOD_state, desiredDensity: number): number {
191
- if (!mesh) return -1;
192
-
193
- // if this is using instancing we always load level 0
194
- // if (this.isInstancingActive) return 0;
195
-
196
- /** rough measure of "triangles on quadratic screen" – we're switching LODs based on this metric. */
197
- /** highest LOD level we'd ever expect to be generated */
198
- const maxLevel = 10;
199
- let level = maxLevel + 1;
200
-
201
- if (camera) {
202
- if (debugProgressiveLoading && mesh["DEBUG:LOD"] != undefined) {
203
- return mesh["DEBUG:LOD"];
204
- }
205
-
206
- // The mesh info contains also the density for all available LOD level so we can use this for selecting which level to show
207
- const lodsInfo = NEEDLE_progressive.getMeshLODInformation(mesh.geometry);
208
- const lods = lodsInfo?.lods;
209
-
210
- // We can skip all this if we dont have any LOD information - we can ask the progressive extension for that
211
- if (!lods || lods.length <= 0) {
212
- return 99;
213
- }
214
-
215
- if (!this.cameraFrustrum?.intersectsObject(mesh)) {
216
- console.log("Mesh not visible");
217
- // if (debugProgressiveLoading && mesh.geometry.boundingSphere) {
218
- // const bounds = mesh.geometry.boundingSphere;
219
- // this._sphere.copy(bounds);
220
- // this._sphere.applyMatrix4(mesh.matrixWorld);
221
- // Gizmos.DrawWireSphere(this._sphere.center, this._sphere.radius * 1.01, 0xff5555, .5);
222
- // }
223
- // the object is not visible by the camera
224
- return 99;
225
- }
226
-
227
- const box = mesh.geometry.boundingBox;
228
- if (box && camera instanceof PerspectiveCamera) {
229
-
230
- // hack: if the mesh has vertex colors, has less than 100 vertices we always select the highest LOD
231
- if (mesh.geometry.attributes.color && mesh.geometry.attributes.color.count < 100) {
232
- if (mesh.geometry.boundingSphere) {
233
- this._sphere.copy(mesh.geometry.boundingSphere);
234
- this._sphere.applyMatrix4(mesh.matrixWorld);
235
- const worldPosition = camera.getWorldPosition(this._tempWorldPosition)
236
- if (this._sphere.containsPoint(worldPosition)) {
237
- return 0;
238
- }
239
- }
240
- }
241
-
242
- // calculate size on screen
243
- this._box.copy(box);
244
- this._box.applyMatrix4(mesh.matrixWorld);
245
-
246
- // Converting into projection space has the disadvantage that objects further to the side
247
- // will have a much larger coverage, especially with high-field-of-view situations like in VR.
248
- // Alternatively, we could attempt to calculate angular coverage (some kind of polar coordinates maybe?)
249
- // or introduce a correction factor based on "expected distortion" of the object.
250
- // High distortions would lead to lower LOD levels.
251
- // "Centrality" of the calculated screen-space bounding box could be a factor here –
252
- // what's the distance of the bounding box to the center of the screen?
253
- this._box.applyMatrix4(this.projectionScreenMatrix);
254
-
255
- // TODO might need to be adjusted for cameras that are rendered during an XR session but are
256
- // actually not XR cameras (e.g. a render texture)
257
- if (this.renderer.xr.enabled && camera.fov > 70) {
258
- // calculate centrality of the bounding box - how close is it to the screen center
259
- const min = this._box.min;
260
- const max = this._box.max;
261
-
262
- let minX = min.x;
263
- let minY = min.y;
264
- let maxX = max.x;
265
- let maxY = max.y;
266
-
267
- // enlarge
268
- const enlargementFactor = 2.0;
269
- const centerBoost = 1.5;
270
- const centerX = (min.x + max.x) * 0.5;
271
- const centerY = (min.y + max.y) * 0.5;
272
- minX = (minX - centerX) * enlargementFactor + centerX;
273
- minY = (minY - centerY) * enlargementFactor + centerY;
274
- maxX = (maxX - centerX) * enlargementFactor + centerX;
275
- maxY = (maxY - centerY) * enlargementFactor + centerY;
276
-
277
- const xCentrality = minX < 0 && maxX > 0 ? 0 : Math.min(Math.abs(min.x), Math.abs(max.x));
278
- const yCentrality = minY < 0 && maxY > 0 ? 0 : Math.min(Math.abs(min.y), Math.abs(max.y));
279
- const centrality = Math.max(xCentrality, yCentrality);
280
-
281
- // heuristically determined to lower quality for objects at the edges of vision
282
- state.lastCentrality = (centerBoost - centrality) * (centerBoost - centrality) * (centerBoost - centrality);
283
- }
284
- else {
285
- state.lastCentrality = 1;
286
- }
287
-
288
- const boxSize = this._box.getSize(this._tempBoxSize);
289
- boxSize.multiplyScalar(0.5); // goes from -1..1, we want -0.5..0.5 for coverage in percent
290
- if (screen.availHeight > 0)
291
- boxSize.multiplyScalar(this.renderer.domElement.clientHeight / screen.availHeight); // correct for size of context on screen
292
- boxSize.x *= camera.aspect;
293
-
294
- const matView = camera.matrixWorldInverse;
295
- const box2 = new Box3();
296
- box2.copy(box);
297
- box2.applyMatrix4(mesh.matrixWorld);
298
- box2.applyMatrix4(matView);
299
- const boxSize2 = box2.getSize(this._tempBox2Size);
300
-
301
- // approximate depth coverage in relation to screenspace size
302
- const max2 = Math.max(boxSize2.x, boxSize2.y);
303
- const max1 = Math.max(boxSize.x, boxSize.y);
304
- if (max1 != 0 && max2 != 0)
305
- boxSize.z = boxSize2.z / Math.max(boxSize2.x, boxSize2.y) * Math.max(boxSize.x, boxSize.y);
306
-
307
- state.lastScreenCoverage = Math.max(boxSize.x, boxSize.y, boxSize.z);
308
- state.lastScreenspaceVolume.copy(boxSize);
309
- state.lastScreenCoverage *= state.lastCentrality;
310
-
311
- // draw screen size box
312
- if (debugProgressiveLoading && LODsManager.debugDrawLine) {
313
- const mat = this.tempMatrix.copy(this.projectionScreenMatrix);
314
- mat.invert();
315
-
316
- const corner0 = LODsManager.corner0;
317
- const corner1 = LODsManager.corner1;
318
- const corner2 = LODsManager.corner2;
319
- const corner3 = LODsManager.corner3;
320
-
321
- // get box corners, transform with camera space, and draw as quad lines
322
- corner0.copy(this._box.min);
323
- corner1.copy(this._box.max);
324
- corner1.x = corner0.x;
325
- corner2.copy(this._box.max);
326
- corner2.y = corner0.y;
327
- corner3.copy(this._box.max);
328
- // draw outlines at the center of the box
329
- const z = (corner0.z + corner3.z) * 0.5;
330
- // all outlines should have the same depth in screen space
331
- corner0.z = corner1.z = corner2.z = corner3.z = z;
332
-
333
- corner0.applyMatrix4(mat);
334
- corner1.applyMatrix4(mat);
335
- corner2.applyMatrix4(mat);
336
- corner3.applyMatrix4(mat);
337
-
338
- LODsManager.debugDrawLine(corner0, corner1, 0x0000ff);
339
- LODsManager.debugDrawLine(corner0, corner2, 0x0000ff);
340
- LODsManager.debugDrawLine(corner1, corner3, 0x0000ff);
341
- LODsManager.debugDrawLine(corner2, corner3, 0x0000ff);
342
- }
343
-
344
- let expectedLevel = 999;
345
- // const framerate = this.context.time.smoothedFps;
346
- if (lods && state.lastScreenCoverage > 0) {
347
- for (let l = 0; l < lods.length; l++) {
348
- const densityForThisLevel = lods[l].density;
349
- if (densityForThisLevel / state.lastScreenCoverage < desiredDensity) {
350
- expectedLevel = l;
351
- break;
352
- }
353
- }
354
- }
355
-
356
- // expectedLevel -= meshDensity - 5;
357
- // expectedLevel += meshDensity;
358
- const isLowerLod = expectedLevel < level;
359
- if (isLowerLod) {
360
- level = expectedLevel;
361
- }
362
- }
363
- // }
364
- }
365
-
366
-
367
- // if (this._lastLodLevel != level) {
368
- // this._nextLodTestTime = this.context.time.realtimeSinceStartup + .5;
369
- // if (debugProgressiveLoading) {
370
- // if (debugProgressiveLoading == "verbose") console.warn(`LOD Level changed from ${this._lastLodLevel} to ${level} for ${this.name}`);
371
- // this.drawGizmoLodLevel(true);
372
- // }
373
- // }
374
-
375
- return level;
376
- }
377
- }
378
-
379
-
380
-
381
-
382
- class LOD_state {
383
- lastLodLevel: number = 0;
384
- lastScreenCoverage: number = 0;
385
- readonly lastScreenspaceVolume: Vector3 = new Vector3();
386
- lastCentrality: number = 0;
387
- }
1
+ import { Box3, Frustum, Matrix4, Mesh, Sphere, Vector3 } from "three";
2
+ import { NEEDLE_progressive } from "./extension.js";
3
+ import { createLoaders } from "./loaders.js";
4
+ import { getParam } from "./utils.js";
5
+ const debugProgressiveLoading = getParam("debugprogressive");
6
+ const suppressProgressiveLoading = getParam("noprogressive");
7
+ /**
8
+ * The LODsManager class is responsible for managing the LODs and progressive assets in the scene. It will automatically update the LODs based on the camera position, screen coverage and mesh density of the objects.
9
+ * It must be enabled by calling the `enable` method.
10
+ *
11
+ * Instead of using the LODs manager directly you can also call `useNeedleProgressive` to enable progressive loading for a GLTFLoader
12
+ */
13
+ export class LODsManager {
14
+ /** 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.
15
+ */
16
+ static debugDrawLine;
17
+ /** @internal */
18
+ static getObjectLODState(object) {
19
+ return object.userData?.LOD_state;
20
+ }
21
+ renderer;
22
+ projectionScreenMatrix = new Matrix4();
23
+ cameraFrustrum = new Frustum();
24
+ /**
25
+ * 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.
26
+ */
27
+ updateInterval = 0;
28
+ /**
29
+ * If set to true, the LODsManager will not update the LODs.
30
+ */
31
+ pause = false;
32
+ plugins = [];
33
+ constructor(renderer) {
34
+ this.renderer = renderer;
35
+ }
36
+ _frame = 0;
37
+ _originalRender;
38
+ /**
39
+ * Enable the LODsManager. This will replace the render method of the renderer with a method that updates the LODs.
40
+ */
41
+ enable() {
42
+ if (this._originalRender)
43
+ return;
44
+ let stack = 0;
45
+ // Save the original render method
46
+ this._originalRender = this.renderer.render;
47
+ const self = this;
48
+ createLoaders(this.renderer);
49
+ this.renderer.render = function (scene, camera) {
50
+ // check if this render call is rendering to a texture or the canvas
51
+ // if it's rendering to a texture we don't want to update the LODs
52
+ // This might need to be loosened later - e.g. we might want to update LODs for a render texture - but then we need to store the last LOD level differently and we also might not want to perform all the plugin calls?
53
+ const renderTarget = self.renderer.getRenderTarget();
54
+ if (renderTarget == null) {
55
+ stack = 0;
56
+ self._frame += 1;
57
+ }
58
+ const frame = self._frame;
59
+ const stack_level = stack++;
60
+ self.onBeforeRender(scene, camera, stack_level, frame);
61
+ self._originalRender.call(this, scene, camera);
62
+ self.onAfterRender(scene, camera, stack_level, frame);
63
+ };
64
+ }
65
+ disable() {
66
+ if (!this._originalRender)
67
+ return;
68
+ this.renderer.render = this._originalRender;
69
+ this._originalRender = undefined;
70
+ }
71
+ onBeforeRender(_scene, _camera, _stack, _frame) {
72
+ }
73
+ onAfterRender(scene, camera, stack, frame) {
74
+ if (this.pause)
75
+ return;
76
+ // we only want to update LODs during the main render call
77
+ if (stack == 0) {
78
+ if (suppressProgressiveLoading)
79
+ return;
80
+ if (this.updateInterval > 0 && frame % this.updateInterval != 0)
81
+ return;
82
+ this.projectionScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
83
+ this.cameraFrustrum.setFromProjectionMatrix(this.projectionScreenMatrix, this.renderer.coordinateSystem);
84
+ const desiredDensity = 100_000;
85
+ // const isLowPerformanceDevice = false;// isMobileDevice();
86
+ // Experiment: quick & dirty performance-adaptive LODs
87
+ /*
88
+ if (this.context.time.smoothedFps < 59) {
89
+ currentAllowedDensity *= 0.5;
90
+ }
91
+ else if (this.context.time.smoothedFps >= 59) {
92
+ currentAllowedDensity *= 1.25;
93
+ }
94
+ */
95
+ const renderList = this.renderer.renderLists.get(scene, stack);
96
+ const opaque = renderList.opaque;
97
+ for (const entry of opaque) {
98
+ if (entry.material && (entry.geometry?.type === "BoxGeometry" || entry.geometry?.type === "BufferGeometry")) {
99
+ // Ignore the skybox
100
+ if (entry.material.name === "SphericalGaussianBlur" || entry.material.name == "BackgroundCubeMaterial" || entry.material.name === "CubemapFromEquirect" || entry.material.name === "EquirectangularToCubeUV") {
101
+ if (debugProgressiveLoading) {
102
+ if (!entry.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]) {
103
+ entry.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"] = true;
104
+ console.warn("Ignoring skybox or BLIT object", entry, entry.material.name, entry.material.type);
105
+ }
106
+ }
107
+ continue;
108
+ }
109
+ }
110
+ const object = entry.object;
111
+ if (object instanceof Mesh || (object.isMesh)) {
112
+ this.updateLODs(scene, camera, object, desiredDensity);
113
+ }
114
+ }
115
+ const transparent = renderList.transparent;
116
+ for (const entry of transparent) {
117
+ const object = entry.object;
118
+ if (object instanceof Mesh || (object.isMesh)) {
119
+ this.updateLODs(scene, camera, object, desiredDensity);
120
+ }
121
+ }
122
+ }
123
+ }
124
+ /** Update the LOD levels for the renderer. */
125
+ updateLODs(scene, camera, object, desiredDensity) {
126
+ for (const plugin of this.plugins) {
127
+ plugin.onBeforeUpdateLOD?.(this.renderer, scene, camera, object);
128
+ }
129
+ let state = object.userData.LOD_state;
130
+ if (!state) {
131
+ state = new LOD_state();
132
+ object.userData.LOD_state = state;
133
+ }
134
+ let level = this.calculateLodLevel(camera, object, state, desiredDensity);
135
+ level = Math.round(level);
136
+ // we currently only support auto LOD changes for meshes
137
+ if (level >= 0) {
138
+ this.loadProgressiveMeshes(object, level);
139
+ }
140
+ // TODO: we currently can not switch texture lods because we need better caching for the textures internally (see copySettings in progressive + NE-4431)
141
+ let textureLOD = 0; // Math.max(0, LODlevel - 2)
142
+ if (object.material) {
143
+ const debugLevel = object["DEBUG:LOD"];
144
+ if (debugLevel != undefined)
145
+ textureLOD = debugLevel;
146
+ if (Array.isArray(object.material)) {
147
+ for (const mat of object.material) {
148
+ this.loadProgressiveTextures(mat, textureLOD);
149
+ }
150
+ }
151
+ else {
152
+ this.loadProgressiveTextures(object.material, textureLOD);
153
+ }
154
+ }
155
+ for (const plugin of this.plugins) {
156
+ plugin.onAfterUpdatedLOD?.(this.renderer, scene, camera, object, level);
157
+ }
158
+ state.lastLodLevel = level;
159
+ }
160
+ /** Load progressive textures for the given material
161
+ * @param material the material to load the textures for
162
+ * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
163
+ * @returns Promise with true if the LOD was loaded, false if not
164
+ */
165
+ loadProgressiveTextures(material, level) {
166
+ if (!material)
167
+ return Promise.resolve(null);
168
+ if (material.userData && material.userData.LOD !== level) {
169
+ material.userData.LOD = level;
170
+ return NEEDLE_progressive.assignTextureLOD(material, level);
171
+ }
172
+ return Promise.resolve(null);
173
+ }
174
+ /** Load progressive meshes for the given mesh
175
+ * @param mesh the mesh to load the LOD for
176
+ * @param index the index of the mesh if it's part of a group
177
+ * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
178
+ * @returns Promise with true if the LOD was loaded, false if not
179
+ */
180
+ loadProgressiveMeshes(mesh, level) {
181
+ if (!mesh)
182
+ return Promise.resolve(null);
183
+ if (!mesh.userData)
184
+ mesh.userData = {};
185
+ if (mesh.userData.LOD !== level) {
186
+ mesh.userData.LOD = level;
187
+ const originalGeometry = mesh.geometry;
188
+ return NEEDLE_progressive.assignMeshLOD(mesh, level).then(res => {
189
+ if (res && mesh.userData.LOD == level && originalGeometry != mesh.geometry) {
190
+ // update the lightmap
191
+ // this.applyLightmapping();
192
+ // if (this.handles) {
193
+ // for (const inst of this.handles) {
194
+ // // if (inst["LOD"] < level) continue;
195
+ // // inst["LOD"] = level;
196
+ // inst.setGeometry(mesh.geometry);
197
+ // }
198
+ // }
199
+ }
200
+ return res;
201
+ });
202
+ }
203
+ return Promise.resolve(null);
204
+ }
205
+ // private testIfLODLevelsAreAvailable() {
206
+ _sphere = new Sphere();
207
+ _tempBox = new Box3();
208
+ tempMatrix = new Matrix4();
209
+ _tempWorldPosition = new Vector3();
210
+ _tempBoxSize = new Vector3();
211
+ _tempBox2Size = new Vector3();
212
+ static corner0 = new Vector3();
213
+ static corner1 = new Vector3();
214
+ static corner2 = new Vector3();
215
+ static corner3 = new Vector3();
216
+ calculateLodLevel(camera, mesh, state, desiredDensity) {
217
+ if (!mesh)
218
+ return -1;
219
+ // if this is using instancing we always load level 0
220
+ // if (this.isInstancingActive) return 0;
221
+ /** rough measure of "triangles on quadratic screen" – we're switching LODs based on this metric. */
222
+ /** highest LOD level we'd ever expect to be generated */
223
+ const maxLevel = 10;
224
+ let level = maxLevel + 1;
225
+ if (camera) {
226
+ if (debugProgressiveLoading && mesh["DEBUG:LOD"] != undefined) {
227
+ return mesh["DEBUG:LOD"];
228
+ }
229
+ // The mesh info contains also the density for all available LOD level so we can use this for selecting which level to show
230
+ const lodsInfo = NEEDLE_progressive.getMeshLODInformation(mesh.geometry);
231
+ const lods = lodsInfo?.lods;
232
+ // We can skip all this if we dont have any LOD information - we can ask the progressive extension for that
233
+ if (!lods || lods.length <= 0) {
234
+ return 99;
235
+ }
236
+ if (!this.cameraFrustrum?.intersectsObject(mesh)) {
237
+ // console.log("Mesh not visible");
238
+ // if (debugProgressiveLoading && mesh.geometry.boundingSphere) {
239
+ // const bounds = mesh.geometry.boundingSphere;
240
+ // this._sphere.copy(bounds);
241
+ // this._sphere.applyMatrix4(mesh.matrixWorld);
242
+ // Gizmos.DrawWireSphere(this._sphere.center, this._sphere.radius * 1.01, 0xff5555, .5);
243
+ // }
244
+ // the object is not visible by the camera
245
+ return 99;
246
+ }
247
+ const box = mesh.geometry.boundingBox;
248
+ if (box && camera.isPerspectiveCamera) {
249
+ const cam = camera;
250
+ // hack: if the mesh has vertex colors, has less than 100 vertices we always select the highest LOD
251
+ if (mesh.geometry.attributes.color && mesh.geometry.attributes.color.count < 100) {
252
+ if (mesh.geometry.boundingSphere) {
253
+ this._sphere.copy(mesh.geometry.boundingSphere);
254
+ this._sphere.applyMatrix4(mesh.matrixWorld);
255
+ const worldPosition = camera.getWorldPosition(this._tempWorldPosition);
256
+ if (this._sphere.containsPoint(worldPosition)) {
257
+ return 0;
258
+ }
259
+ }
260
+ }
261
+ // calculate size on screen
262
+ this._tempBox.copy(box);
263
+ this._tempBox.applyMatrix4(mesh.matrixWorld);
264
+ // Converting into projection space has the disadvantage that objects further to the side
265
+ // will have a much larger coverage, especially with high-field-of-view situations like in VR.
266
+ // Alternatively, we could attempt to calculate angular coverage (some kind of polar coordinates maybe?)
267
+ // or introduce a correction factor based on "expected distortion" of the object.
268
+ // High distortions would lead to lower LOD levels.
269
+ // "Centrality" of the calculated screen-space bounding box could be a factor here –
270
+ // what's the distance of the bounding box to the center of the screen?
271
+ this._tempBox.applyMatrix4(this.projectionScreenMatrix);
272
+ // TODO might need to be adjusted for cameras that are rendered during an XR session but are
273
+ // actually not XR cameras (e.g. a render texture)
274
+ if (this.renderer.xr.enabled && cam.fov > 70) {
275
+ // calculate centrality of the bounding box - how close is it to the screen center
276
+ const min = this._tempBox.min;
277
+ const max = this._tempBox.max;
278
+ let minX = min.x;
279
+ let minY = min.y;
280
+ let maxX = max.x;
281
+ let maxY = max.y;
282
+ // enlarge
283
+ const enlargementFactor = 2.0;
284
+ const centerBoost = 1.5;
285
+ const centerX = (min.x + max.x) * 0.5;
286
+ const centerY = (min.y + max.y) * 0.5;
287
+ minX = (minX - centerX) * enlargementFactor + centerX;
288
+ minY = (minY - centerY) * enlargementFactor + centerY;
289
+ maxX = (maxX - centerX) * enlargementFactor + centerX;
290
+ maxY = (maxY - centerY) * enlargementFactor + centerY;
291
+ const xCentrality = minX < 0 && maxX > 0 ? 0 : Math.min(Math.abs(min.x), Math.abs(max.x));
292
+ const yCentrality = minY < 0 && maxY > 0 ? 0 : Math.min(Math.abs(min.y), Math.abs(max.y));
293
+ const centrality = Math.max(xCentrality, yCentrality);
294
+ // heuristically determined to lower quality for objects at the edges of vision
295
+ state.lastCentrality = (centerBoost - centrality) * (centerBoost - centrality) * (centerBoost - centrality);
296
+ }
297
+ else {
298
+ state.lastCentrality = 1;
299
+ }
300
+ const boxSize = this._tempBox.getSize(this._tempBoxSize);
301
+ boxSize.multiplyScalar(0.5); // goes from -1..1, we want -0.5..0.5 for coverage in percent
302
+ if (screen.availHeight > 0)
303
+ boxSize.multiplyScalar(this.renderer.domElement.clientHeight / screen.availHeight); // correct for size of context on screen
304
+ boxSize.x *= cam.aspect;
305
+ const matView = camera.matrixWorldInverse;
306
+ const box2 = new Box3();
307
+ box2.copy(box);
308
+ box2.applyMatrix4(mesh.matrixWorld);
309
+ box2.applyMatrix4(matView);
310
+ const boxSize2 = box2.getSize(this._tempBox2Size);
311
+ // approximate depth coverage in relation to screenspace size
312
+ const max2 = Math.max(boxSize2.x, boxSize2.y);
313
+ const max1 = Math.max(boxSize.x, boxSize.y);
314
+ if (max1 != 0 && max2 != 0)
315
+ boxSize.z = boxSize2.z / Math.max(boxSize2.x, boxSize2.y) * Math.max(boxSize.x, boxSize.y);
316
+ state.lastScreenCoverage = Math.max(boxSize.x, boxSize.y, boxSize.z);
317
+ state.lastScreenspaceVolume.copy(boxSize);
318
+ state.lastScreenCoverage *= state.lastCentrality;
319
+ // draw screen size box
320
+ if (debugProgressiveLoading && LODsManager.debugDrawLine) {
321
+ const mat = this.tempMatrix.copy(this.projectionScreenMatrix);
322
+ mat.invert();
323
+ const corner0 = LODsManager.corner0;
324
+ const corner1 = LODsManager.corner1;
325
+ const corner2 = LODsManager.corner2;
326
+ const corner3 = LODsManager.corner3;
327
+ // get box corners, transform with camera space, and draw as quad lines
328
+ corner0.copy(this._tempBox.min);
329
+ corner1.copy(this._tempBox.max);
330
+ corner1.x = corner0.x;
331
+ corner2.copy(this._tempBox.max);
332
+ corner2.y = corner0.y;
333
+ corner3.copy(this._tempBox.max);
334
+ // draw outlines at the center of the box
335
+ const z = (corner0.z + corner3.z) * 0.5;
336
+ // all outlines should have the same depth in screen space
337
+ corner0.z = corner1.z = corner2.z = corner3.z = z;
338
+ corner0.applyMatrix4(mat);
339
+ corner1.applyMatrix4(mat);
340
+ corner2.applyMatrix4(mat);
341
+ corner3.applyMatrix4(mat);
342
+ LODsManager.debugDrawLine(corner0, corner1, 0x0000ff);
343
+ LODsManager.debugDrawLine(corner0, corner2, 0x0000ff);
344
+ LODsManager.debugDrawLine(corner1, corner3, 0x0000ff);
345
+ LODsManager.debugDrawLine(corner2, corner3, 0x0000ff);
346
+ }
347
+ let expectedLevel = 999;
348
+ // const framerate = this.context.time.smoothedFps;
349
+ if (lods && state.lastScreenCoverage > 0) {
350
+ for (let l = 0; l < lods.length; l++) {
351
+ const densityForThisLevel = lods[l].density;
352
+ const resultingDensity = densityForThisLevel / state.lastScreenCoverage;
353
+ if (resultingDensity < desiredDensity) {
354
+ expectedLevel = l;
355
+ break;
356
+ }
357
+ }
358
+ }
359
+ const isLowerLod = expectedLevel < level;
360
+ if (isLowerLod) {
361
+ level = expectedLevel;
362
+ }
363
+ }
364
+ // }
365
+ }
366
+ // if (this._lastLodLevel != level) {
367
+ // this._nextLodTestTime = this.context.time.realtimeSinceStartup + .5;
368
+ // if (debugProgressiveLoading) {
369
+ // if (debugProgressiveLoading == "verbose") console.warn(`LOD Level changed from ${this._lastLodLevel} to ${level} for ${this.name}`);
370
+ // this.drawGizmoLodLevel(true);
371
+ // }
372
+ // }
373
+ return level;
374
+ }
375
+ }
376
+ class LOD_state {
377
+ lastLodLevel = 0;
378
+ lastScreenCoverage = 0;
379
+ lastScreenspaceVolume = new Vector3();
380
+ lastCentrality = 0;
381
+ }