@combeenation/3d-viewer 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/LICENSE +13 -0
  2. package/README.md +111 -0
  3. package/dist/types/api/classes/animationInterface.d.ts +8 -0
  4. package/dist/types/api/classes/dottedPath.d.ts +79 -0
  5. package/dist/types/api/classes/element.d.ts +153 -0
  6. package/dist/types/api/classes/event.d.ts +396 -0
  7. package/dist/types/api/classes/eventBroadcaster.d.ts +26 -0
  8. package/dist/types/api/classes/fuzzyMap.d.ts +7 -0
  9. package/dist/types/api/classes/parameter.d.ts +351 -0
  10. package/dist/types/api/classes/parameterObservable.d.ts +36 -0
  11. package/dist/types/api/classes/parameterizable.d.ts +15 -0
  12. package/dist/types/api/classes/placementAnimation.d.ts +45 -0
  13. package/dist/types/api/classes/variant.d.ts +253 -0
  14. package/dist/types/api/classes/variantInstance.d.ts +53 -0
  15. package/dist/types/api/classes/variantParameterizable.d.ts +17 -0
  16. package/dist/types/api/classes/viewer.d.ts +200 -0
  17. package/dist/types/api/classes/viewerLight.d.ts +66 -0
  18. package/dist/types/api/internal/lensRendering.d.ts +8 -0
  19. package/dist/types/api/internal/sceneSetup.d.ts +13 -0
  20. package/dist/types/api/manager/animationManager.d.ts +30 -0
  21. package/dist/types/api/manager/gltfExportManager.d.ts +78 -0
  22. package/dist/types/api/manager/sceneManager.d.ts +33 -0
  23. package/dist/types/api/manager/tagManager.d.ts +108 -0
  24. package/dist/types/api/manager/textureLoadManager.d.ts +22 -0
  25. package/dist/types/api/manager/variantInstanceManager.d.ts +103 -0
  26. package/dist/types/api/store/specStorage.d.ts +32 -0
  27. package/dist/types/api/util/babylonHelper.d.ts +235 -0
  28. package/dist/types/api/util/globalTypes.d.ts +436 -0
  29. package/dist/types/api/util/resourceHelper.d.ts +58 -0
  30. package/dist/types/api/util/sceneLoaderHelper.d.ts +44 -0
  31. package/dist/types/api/util/stringHelper.d.ts +13 -0
  32. package/dist/types/api/util/structureHelper.d.ts +9 -0
  33. package/dist/types/declaration.tsconfig.tsbuildinfo +1 -0
  34. package/dist/types/index.d.ts +27 -0
  35. package/package.json +87 -0
  36. package/src/api/classes/animationInterface.ts +10 -0
  37. package/src/api/classes/dottedPath.ts +181 -0
  38. package/src/api/classes/element.ts +731 -0
  39. package/src/api/classes/event.ts +452 -0
  40. package/src/api/classes/eventBroadcaster.ts +52 -0
  41. package/src/api/classes/fuzzyMap.ts +21 -0
  42. package/src/api/classes/parameter.ts +554 -0
  43. package/src/api/classes/parameterObservable.ts +73 -0
  44. package/src/api/classes/parameterizable.ts +87 -0
  45. package/src/api/classes/placementAnimation.ts +162 -0
  46. package/src/api/classes/variant.ts +933 -0
  47. package/src/api/classes/variantInstance.ts +123 -0
  48. package/src/api/classes/variantParameterizable.ts +85 -0
  49. package/src/api/classes/viewer.ts +742 -0
  50. package/src/api/classes/viewerLight.ts +339 -0
  51. package/src/api/internal/debugViewer.ts +90 -0
  52. package/src/api/internal/lensRendering.ts +9 -0
  53. package/src/api/internal/sceneSetup.ts +205 -0
  54. package/src/api/manager/animationManager.ts +143 -0
  55. package/src/api/manager/gltfExportManager.ts +236 -0
  56. package/src/api/manager/sceneManager.ts +136 -0
  57. package/src/api/manager/tagManager.ts +451 -0
  58. package/src/api/manager/textureLoadManager.ts +95 -0
  59. package/src/api/manager/variantInstanceManager.ts +298 -0
  60. package/src/api/store/specStorage.ts +68 -0
  61. package/src/api/util/babylonHelper.ts +822 -0
  62. package/src/api/util/globalTypes.ts +503 -0
  63. package/src/api/util/resourceHelper.ts +191 -0
  64. package/src/api/util/sceneLoaderHelper.ts +170 -0
  65. package/src/api/util/stringHelper.ts +30 -0
  66. package/src/api/util/structureHelper.ts +49 -0
  67. package/src/buildinfo.json +3 -0
  68. package/src/dev.ts +62 -0
  69. package/src/index.ts +79 -0
  70. package/src/types.d.ts +36 -0
@@ -0,0 +1,742 @@
1
+ import buildInfo from '../../buildinfo.json';
2
+ import { sceneSetup } from '../internal/sceneSetup';
3
+ import { AnimationManager } from '../manager/animationManager';
4
+ import { GltfExportManager } from '../manager/gltfExportManager';
5
+ import { SceneManager } from '../manager/sceneManager';
6
+ import { TagManager } from '../manager/tagManager';
7
+ import { VariantInstanceManager } from '../manager/variantInstanceManager';
8
+ import { SpecStorage } from '../store/specStorage';
9
+ import { backgroundDomeName, envHelperMetadataName } from '../util/babylonHelper';
10
+ import { debounce, loadJavascript, loadJson } from '../util/resourceHelper';
11
+ import { getCustomCbnBabylonLoaderPlugin } from '../util/sceneLoaderHelper';
12
+ import { replaceDots } from '../util/stringHelper';
13
+ import { isMeshIncludedInExclusionList } from '../util/structureHelper';
14
+ import { AnimationInterface } from './animationInterface';
15
+ import { Event } from './event';
16
+ import { EventBroadcaster } from './eventBroadcaster';
17
+ import { Parameter } from './parameter';
18
+ import { VariantInstance } from './variantInstance';
19
+ import { ArcRotateCamera } from '@babylonjs/core/Cameras/arcRotateCamera';
20
+ import { PickingInfo } from '@babylonjs/core/Collisions/pickingInfo';
21
+ import { BoundingInfo } from '@babylonjs/core/Culling/boundingInfo';
22
+ import { DebugLayer } from '@babylonjs/core/Debug/debugLayer';
23
+ import { Engine } from '@babylonjs/core/Engines/engine';
24
+ import { IPointerEvent } from '@babylonjs/core/Events/deviceInputEvents';
25
+ import { EnvironmentHelper } from '@babylonjs/core/Helpers/environmentHelper';
26
+ import { PhotoDome } from '@babylonjs/core/Helpers/photoDome';
27
+ import { HighlightLayer } from '@babylonjs/core/Layers/highlightLayer';
28
+ import { ISceneLoaderPlugin, SceneLoader } from '@babylonjs/core/Loading/sceneLoader';
29
+ import { DynamicTexture } from '@babylonjs/core/Materials/Textures/dynamicTexture';
30
+ import { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial';
31
+ import { Color3 } from '@babylonjs/core/Maths/math.color';
32
+ import { Vector3 } from '@babylonjs/core/Maths/math.vector';
33
+ import { Mesh } from '@babylonjs/core/Meshes/mesh';
34
+ import { ScreenshotTools } from '@babylonjs/core/Misc/screenshotTools';
35
+ import { WebXRSessionManager } from '@babylonjs/core/XR/webXRSessionManager';
36
+ import { Scene } from '@babylonjs/core/scene';
37
+ import { isString } from 'lodash-es';
38
+
39
+ /**
40
+ * The main exposed object. This is the entry point into the application
41
+ *
42
+ * ```js
43
+ * const canvas = document.getElementById( 'babylon-canvas' );
44
+ * const viewer = Viewer( canvas, '/path/to/index.json' );
45
+ * ```
46
+ * The class does nothing on its own and needs to {@link bootstrap}
47
+ */
48
+ export class Viewer extends EventBroadcaster {
49
+ protected _scene: Scene | null = null;
50
+
51
+ protected _animationManager: AnimationManager | null = null;
52
+
53
+ protected _sceneManager: SceneManager | null = null;
54
+
55
+ protected _tagManager: TagManager | null = null;
56
+
57
+ protected _gltfExportManager: GltfExportManager | null = null;
58
+
59
+ protected _variantInstances: VariantInstanceManager | null = null;
60
+
61
+ // defaults to `false` as material cloning should be the edge case
62
+ protected _cloneMaterialsOnMutation: boolean = false;
63
+
64
+ protected _isRenderLoopPaused: boolean = false;
65
+
66
+ protected _inspectorLoaded: boolean = false;
67
+
68
+ protected _nodeNamingStrategyHandler: NodeNamingStrategyHandler | null = null;
69
+
70
+ static version = buildInfo.version;
71
+
72
+ // these are constants for calculating the camera settings, depending on the bounding box size of the meshes to zoom
73
+ // the algorithms and constant values are directly taken from the Babylon.js repository
74
+ private static readonly _autofocusConstants = {
75
+ minZ: 100,
76
+ wheelPrecision: 100,
77
+ panningSensibility: 5000,
78
+ pinchPrecision: 200,
79
+ };
80
+
81
+ /**
82
+ * Help function for automatically creating a valid Spec from a list of variant names and dedicated GLB/babylon URLs.
83
+ * This data is most likely coming from babylon assets from the Combeenation system but other sources are also valid.
84
+ */
85
+ public static generateSpec(genData: SpecGenerationData[]): AutoSpecStructureJson {
86
+ // dots in the variant name indicate inheritance, but this should not be the case for an auto-generated spec
87
+ // therefore dots are exchanged with slashes
88
+ const safeGenData: SpecGenerationData[] = genData.map(data => ({ ...data, name: replaceDots(data.name) }));
89
+
90
+ const spec: AutoSpecStructureJson = {
91
+ // common scene settings as suggested in the viewer docs
92
+ scene: {
93
+ engine: {
94
+ antialiasing: true,
95
+ options: {
96
+ preserveDrawingBuffer: true,
97
+ stencil: true,
98
+ xrCompatible: false,
99
+ },
100
+ },
101
+ scene: {
102
+ globals: {},
103
+ },
104
+ },
105
+ setup: {
106
+ // create one instance for each input entry
107
+ // name and variant are named accordingly from the input, instance will be hidden by default and lazy loading
108
+ // is activated
109
+ instances: safeGenData.map(instanceData => ({
110
+ name: instanceData.name,
111
+ variant: instanceData.name,
112
+ lazy: true,
113
+ parameters: {
114
+ [Parameter.VISIBLE]: false,
115
+ },
116
+ })),
117
+ },
118
+ // variants definition is also mapped to the input array, using the name as key and url as glTF source
119
+ // no elements are created here, since this should be done automatically from the system
120
+ // => create one element which contains all root nodes of the imported 3d file (GLB or babylon)
121
+ variants: safeGenData.reduce((accVariants, curVariant) => {
122
+ accVariants[curVariant.name] = {
123
+ glTF: curVariant.url,
124
+ };
125
+
126
+ return accVariants;
127
+ }, {} as { [id: string]: StructureJson }),
128
+ };
129
+
130
+ return spec;
131
+ }
132
+
133
+ /**
134
+ * Constructor
135
+ */
136
+ public constructor(public readonly canvas: HTMLCanvasElement, protected structureJson: string | StructureJson) {
137
+ super();
138
+ this._tagManager = new TagManager(this);
139
+ this._nodeNamingStrategyHandler = (node, payload) => {
140
+ const suffix: string[] = [];
141
+ if (payload.variant.elements.length > 0) {
142
+ const nodeElements = payload.variant.elements.filter(
143
+ e => e.nodesFlat.filter(n => n.metadata?.cloneSource?.id === node.id).length > 0
144
+ );
145
+ if (nodeElements.length > 0) {
146
+ suffix.push(payload.variantParameterizable.name);
147
+ }
148
+ }
149
+ const variantInstances = this.variantInstances.allWithVariantName(payload.variant.name);
150
+ if (variantInstances.length > 0) {
151
+ suffix.push(payload.variantInstance.name);
152
+ }
153
+ const originalName = node.metadata?.originalName || node.name;
154
+ return [originalName, ...suffix.filter(s => !!s)].join('.');
155
+ };
156
+ }
157
+
158
+ /**
159
+ * Gets the Babylon.js Scene that is attached to the instance.
160
+ *
161
+ * @throws Error if the `scene` has not been initialized.
162
+ */
163
+ get scene(): Scene {
164
+ if (!this._scene) {
165
+ throw new Error(`Scene has not been initialized.`);
166
+ }
167
+ return this._scene;
168
+ }
169
+
170
+ /**
171
+ * Gets the {@link SceneManager} attached to the viewer.
172
+ *
173
+ * @throws Error if the {@link SceneManager} has not been initialized.
174
+ */
175
+ get sceneManager(): SceneManager {
176
+ if (!this._sceneManager) {
177
+ throw new Error(`SceneManager has not been initialized.`);
178
+ }
179
+ return this._sceneManager;
180
+ }
181
+
182
+ /**
183
+ * Gets the {@link GltfExportManager} attached to the viewer.
184
+ *
185
+ * @throws Error if the {@link GltfExportManager} has not been initialized.
186
+ */
187
+ get gltfExportManager(): GltfExportManager {
188
+ if (!this._gltfExportManager) {
189
+ throw new Error(`GltfExportManager has not been initialized.`);
190
+ }
191
+ return this._gltfExportManager;
192
+ }
193
+
194
+ /**
195
+ * Gets the Babylon.js Engine that is attached to the viewer.
196
+ */
197
+ get engine(): Engine {
198
+ return this.scene.getEngine();
199
+ }
200
+
201
+ /**
202
+ * Gets the {@link VariantInstanceManager} attached to the viewer.
203
+ *
204
+ * @throws Error if the {@link VariantInstanceManager} has not been initialized.
205
+ */
206
+ get variantInstances(): VariantInstanceManager {
207
+ if (!this._variantInstances) {
208
+ throw Error(`There is no variantInstanceManager.`);
209
+ }
210
+ return this._variantInstances;
211
+ }
212
+
213
+ /**
214
+ * Gets the {@link AnimationManager} attached to the viewer.
215
+ *
216
+ * @throws Error if the {@link AnimationManager} has not been initialized.
217
+ */
218
+ get animationManager(): AnimationManager {
219
+ if (!this._animationManager) {
220
+ throw new Error(`There is no animationManager instance.`);
221
+ }
222
+ return this._animationManager;
223
+ }
224
+
225
+ get tagManager(): TagManager {
226
+ if (!this._tagManager) {
227
+ throw new Error(`There is no tagManager instance.`);
228
+ }
229
+ return this._tagManager;
230
+ }
231
+
232
+ /**
233
+ * Gets the `cloneMaterialsOnMutation` flag, as defined in the spec
234
+ */
235
+ get cloneMaterialsOnMutation(): boolean {
236
+ return this._cloneMaterialsOnMutation;
237
+ }
238
+
239
+ /**
240
+ * Gets the strategy handler for naming cloned nodes.
241
+ */
242
+ get nodeNamingStrategyHandler(): NodeNamingStrategyHandler {
243
+ if (!this._nodeNamingStrategyHandler) {
244
+ throw new Error(`The NodeNamingStrategyHandler has not been registered yet.`);
245
+ }
246
+ return this._nodeNamingStrategyHandler;
247
+ }
248
+
249
+ /**
250
+ * Sets the strategy handler for naming cloned nodes.\
251
+ * Check the docs of the tag managers
252
+ * [renaming](./../pages/documentation/Tag-Manager.html#uniqueness-of-node-and-tag-names)
253
+ * chapter for further details.
254
+ */
255
+ set nodeNamingStrategyHandler(value: NodeNamingStrategyHandler) {
256
+ if (!value || typeof value !== 'function') {
257
+ throw new Error(`The NodeNamingStrategyHandler is not a callable function.`);
258
+ }
259
+ this._nodeNamingStrategyHandler = value;
260
+ }
261
+
262
+ /**
263
+ * Starts the application. This will
264
+ * * load the given "index" JSON file
265
+ * * setup the scene with the "scene" JSON file
266
+ * * create an (optional) default setup with different variant settings
267
+ * * sets up resizing by attaching a debounced version of {@link resize}
268
+ *
269
+ * @throws Error if any of the files is not found/valid
270
+ *
271
+ * @emits {@link Event.BOOTSTRAP_START}
272
+ * @emits {@link Event.BOOTSTRAP_END}
273
+ */
274
+ public async bootstrap(tagManagerParameterValues: TagManagerParameterValue[]): Promise<Viewer> {
275
+ this.broadcastEvent(Event.BOOTSTRAP_START, this);
276
+ let indexJson;
277
+ if (isString(this.structureJson)) {
278
+ indexJson = await loadJson<StructureJson>(this.structureJson);
279
+ } else {
280
+ indexJson = this.structureJson;
281
+ }
282
+ if (!indexJson.scene) {
283
+ throw new Error(`No "scene" property found for bootstrapping.`);
284
+ }
285
+ // fill spec store
286
+ SpecStorage.createFromSpec(indexJson);
287
+ // init custom loader plugin
288
+ this.initCbnBabylonLoaderPlugin();
289
+ // load scene
290
+ if (isString(indexJson.scene)) {
291
+ const sceneJson = await loadJson<SceneJson>(indexJson.scene);
292
+ indexJson.scene = sceneJson;
293
+ }
294
+ this._scene = await this.initScene();
295
+ // create instance manager
296
+ this._variantInstances = await VariantInstanceManager.create(this);
297
+ // create optional default instances
298
+ if (indexJson.setup) {
299
+ if (isString(indexJson.setup)) {
300
+ const setupJson = await loadJson<SetupJson>(indexJson.setup);
301
+ indexJson.setup = setupJson;
302
+ }
303
+ await this.createVariantInstances();
304
+ }
305
+ this.broadcastEvent(Event.VARIANT_INSTANCES_READY, this);
306
+ // create gltf export manager
307
+ this._gltfExportManager = await GltfExportManager.create(this);
308
+ // resize handler
309
+ window.addEventListener('resize', debounce(this.resize.bind(this), 100));
310
+ // wait until scene is completely ready
311
+ await this.scene.whenReadyAsync();
312
+ // set tag manager values
313
+ if (tagManagerParameterValues) {
314
+ await this.tagManager.setParameterValues(tagManagerParameterValues);
315
+ }
316
+ // event broadcasting
317
+ this.broadcastEvent(Event.BOOTSTRAP_END, this);
318
+ // render loop
319
+ this.engine.runRenderLoop(() => {
320
+ if (!this._isRenderLoopPaused) this.scene.render();
321
+ });
322
+ return this;
323
+ }
324
+
325
+ /**
326
+ * Enables the Babylon.js [Inspector](https://doc.babylonjs.com/toolsAndResources/tools/inspector).\
327
+ * Due to the additional size of the inspector, the CDN version is used instead of shipping the required code with
328
+ * the viewer.\
329
+ * This means that the code will be downloaded only when needed and calling `enableDebugLayer` can take a little while
330
+ * depending on your internet connection etc.
331
+ */
332
+ public async enableDebugLayer(options?: IInspectorOptions) {
333
+ if (!window.BABYLON?.Inspector) {
334
+ // CDN version of inspector requires the Babylon.js core to be available as CDN module as well
335
+ await loadJavascript('https://cdn.jsdelivr.net/npm/babylonjs@5.27.1/babylon.min.js');
336
+
337
+ DebugLayer.InspectorURL =
338
+ 'https://cdn.jsdelivr.net/npm/babylonjs-inspector@5.27.1/babylon.inspector.bundle.max.min.js';
339
+ }
340
+
341
+ await this.scene.debugLayer.show(options);
342
+ }
343
+
344
+ /**
345
+ * Destroys all registered {@link VariantInstance}s that are registered
346
+ */
347
+ public destroyVariantInstances(): Viewer {
348
+ this.variantInstances.all.forEach(variantInstance => {
349
+ this.variantInstances.destroy(variantInstance.name);
350
+ });
351
+ return this;
352
+ }
353
+
354
+ /**
355
+ * Trigger a resize event for the `Engine`
356
+ */
357
+ public resize(): Viewer {
358
+ this.engine.resize();
359
+ return this;
360
+ }
361
+
362
+ /**
363
+ * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
364
+ * {@link DottedPath}s.
365
+ */
366
+ public async getNode(
367
+ variantInstanceName: string,
368
+ elementDottedPath: DottedPathArgument,
369
+ nodeDottedPath: DottedPathArgument
370
+ ): Promise<TransformNode> {
371
+ const variantInstance = await this.variantInstances.get(variantInstanceName);
372
+ return variantInstance.getNode(elementDottedPath, nodeDottedPath);
373
+ }
374
+
375
+ /**
376
+ * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
377
+ * {@link DottedPath}s.
378
+ */
379
+ public async getMesh(
380
+ variantInstanceName: string,
381
+ elementDottedPath: DottedPathArgument,
382
+ meshDottedPath: DottedPathArgument
383
+ ): Promise<Mesh | null> {
384
+ const variantInstance = await this.variantInstances.get(variantInstanceName);
385
+ return variantInstance.getMesh(elementDottedPath, meshDottedPath);
386
+ }
387
+
388
+ /**
389
+ * Switches the camera
390
+ *
391
+ * @emits {@link Event.CAMERA_SWITCHED}
392
+ */
393
+ public switchCamera(newCamera: string, reset: boolean = true): Viewer {
394
+ const camera = this.scene.getCameraByName(newCamera);
395
+ if (camera) {
396
+ const activeCamera = this.scene.activeCamera;
397
+ if (activeCamera) {
398
+ activeCamera.detachControl(this.engine.getRenderingCanvas()!);
399
+ }
400
+ if (reset) {
401
+ camera.restoreState();
402
+ }
403
+ this.scene.setActiveCameraByName(newCamera);
404
+ camera.attachControl(this.engine.getRenderingCanvas()!);
405
+ this.broadcastEvent(Event.CAMERA_SWITCHED, camera);
406
+ } else {
407
+ throw new Error(`Given camera "${newCamera}" not found.`);
408
+ }
409
+ // TODO: put traceable observers to new camera (@see element)
410
+ return this;
411
+ }
412
+
413
+ /**
414
+ * Moves or animates the active camera to given `placement`.
415
+ */
416
+ public async moveActiveCameraTo(
417
+ placement: string | PlacementDefinition,
418
+ animation?: string | AnimationDefinition
419
+ ): Promise<AnimationInterface> {
420
+ return this.animationManager.animateToPlacement(this.sceneManager.activeCamera, placement, animation);
421
+ }
422
+
423
+ /**
424
+ * Takes a sceenshot the the current scene. The result is a string containing a base64 encoded image
425
+ */
426
+ public screenshot(settings?: ScreenshotSettings): Promise<string> {
427
+ return new Promise((resolve, reject) => {
428
+ if (!this.engine) {
429
+ return reject('Engine is null');
430
+ }
431
+ if (!this.scene) {
432
+ return reject('Scene is null');
433
+ }
434
+ this.scene.render(); // in combination with a render target, we need to refresh the scene manually to get the latest view
435
+ ScreenshotTools.CreateScreenshotUsingRenderTarget(
436
+ this.engine,
437
+ this.sceneManager.activeCamera,
438
+ settings?.size ?? { width: this.canvas.clientWidth, height: this.canvas.clientHeight },
439
+ resolve,
440
+ settings?.mimeType ?? 'image/png',
441
+ settings?.samples ?? 1,
442
+ settings?.antialiasing ?? false,
443
+ settings?.fileName ?? 'screenshot.png',
444
+ settings?.renderSprites ?? false
445
+ );
446
+ });
447
+ }
448
+
449
+ /**
450
+ * Checks whether the browser is capable of handling XR.
451
+ */
452
+ public async isBrowserARCapable(): Promise<boolean> {
453
+ return await WebXRSessionManager.IsSessionSupportedAsync('immersive-ar');
454
+ }
455
+
456
+ /**
457
+ * Calculates the bounding box from all visible meshes on the scene.
458
+ */
459
+ public async calculateBoundingBox(excludeGeometry?: ExcludedGeometryList): Promise<Mesh> {
460
+ if (this.scene.meshes.length === 0) {
461
+ throw new Error('There are currently no meshes on the scene.');
462
+ }
463
+ this.scene.render(); // CB-6062: workaround for BoundingBox not respecting render loop
464
+ const bbName = '__bounding_box__';
465
+
466
+ const { max, min } = this.scene.meshes
467
+ .filter(mesh => {
468
+ const isEnabled = mesh.isEnabled();
469
+ // ignore the existing bounding box mesh for calculating the current one
470
+ const isNotBBoxMesh = bbName !== mesh.id;
471
+ // ignore meshes with invalid bounding infos
472
+ const hasValidBBoxInfo = mesh.getBoundingInfo().boundingSphere.radius > 0;
473
+ // ignore excluded meshes
474
+ const isExcluded = excludeGeometry ? isMeshIncludedInExclusionList(mesh as Mesh, excludeGeometry) : false;
475
+ return isEnabled && isNotBBoxMesh && hasValidBBoxInfo && !isExcluded;
476
+ })
477
+ .reduce(
478
+ (accBBoxMinMax, curMesh, idx) => {
479
+ const bBox = curMesh.getBoundingInfo().boundingBox;
480
+ // use the first entry in the array as default value and get the resulting maximum/minimum values
481
+ const max = idx === 0 ? bBox.maximumWorld : Vector3.Maximize(accBBoxMinMax.max, bBox.maximumWorld);
482
+ const min = idx === 0 ? bBox.minimumWorld : Vector3.Minimize(accBBoxMinMax.min, bBox.minimumWorld);
483
+ return { max, min };
484
+ },
485
+ { max: new Vector3(), min: new Vector3() }
486
+ );
487
+
488
+ let boundingBox = this.scene.getMeshByName(bbName) as Mesh;
489
+ if (!boundingBox) {
490
+ boundingBox = new Mesh(bbName, this.scene);
491
+ }
492
+ boundingBox.setBoundingInfo(new BoundingInfo(min, max));
493
+ return boundingBox;
494
+ }
495
+
496
+ /**
497
+ * Focuses the camera to see every visible mesh in scene and tries to optimize wheel precision and panning
498
+ */
499
+ public async autofocusActiveCamera(settings?: AutofocusSettings) {
500
+ // first check some preconditions
501
+ const activeCamera = this.scene.activeCamera;
502
+ if (!activeCamera) {
503
+ throw new Error('No active camera found when using autofocus feature.');
504
+ }
505
+ if (!(activeCamera instanceof ArcRotateCamera)) {
506
+ const cameraClsName = activeCamera.getClassName();
507
+ throw new Error(`Camera of type "${cameraClsName}" is not implemented yet to use autofocus feature.`);
508
+ }
509
+
510
+ let exclude = settings?.exclude || [];
511
+
512
+ // Exclude shown photo dome or environment helper from bounding box calculation
513
+ const photoDome = this.scene.getNodeByName(backgroundDomeName) as undefined | PhotoDome;
514
+ const photoDomeMeshes = photoDome?.getChildMeshes();
515
+ if (photoDomeMeshes?.length) {
516
+ exclude = [...exclude, ...photoDomeMeshes];
517
+ }
518
+
519
+ const envHelper = this.scene.metadata?.[envHelperMetadataName] as undefined | EnvironmentHelper;
520
+ if (envHelper?.rootMesh) {
521
+ exclude = [...exclude, envHelper.rootMesh];
522
+ }
523
+
524
+ // get bounding box of all visible meshes, this is the base for the autofocus algorithm
525
+ const boundingBox = await this.calculateBoundingBox(exclude);
526
+
527
+ const radius = boundingBox.getBoundingInfo().boundingSphere.radius;
528
+ const center = boundingBox.getBoundingInfo().boundingSphere.center;
529
+ const diameter = radius * 2;
530
+
531
+ // set lower radius limit on edge of bounding sphere to make sure that we can't dive into the meshes
532
+ activeCamera.lowerRadiusLimit = radius;
533
+
534
+ // additional settings
535
+ // constants for division are taken directly from Babylon.js repository
536
+ activeCamera.minZ = Math.min(radius / Viewer._autofocusConstants.minZ, 1);
537
+ if (settings?.adjustWheelPrecision !== false) {
538
+ activeCamera.wheelPrecision = Viewer._autofocusConstants.wheelPrecision / radius;
539
+ }
540
+ if (settings?.adjustPanningSensibility !== false) {
541
+ activeCamera.panningSensibility = Viewer._autofocusConstants.panningSensibility / diameter;
542
+ }
543
+ if (settings?.adjustPinchPrecision !== false) {
544
+ activeCamera.pinchPrecision = Viewer._autofocusConstants.pinchPrecision / radius;
545
+ }
546
+
547
+ const radiusFactor = settings?.radiusFactor ?? 1.5;
548
+ const alpha = (settings?.alpha ?? -90) * (Math.PI / 180);
549
+ const beta = (settings?.beta ?? 90) * (Math.PI / 180);
550
+
551
+ const newCameraPosition = {
552
+ alpha: alpha,
553
+ beta: beta,
554
+ // this calculation is a bit "simplified", as it doesn't consider the viewport ratio or the frustum angle
555
+ // but it's also done this way in the Babylon.js repository, so it should be fine for us
556
+ radius: diameter * radiusFactor,
557
+ target: center,
558
+ };
559
+
560
+ await this.animationManager.animateToPlacement(activeCamera, newCameraPosition, settings?.animation);
561
+ }
562
+
563
+ /**
564
+ * Resets everything by calling {@link destroy} to clear all references and {@link bootstrap} to setup a clean
565
+ * environment
566
+ */
567
+ public async reset(tagManagerParameterValues: TagManagerParameterValue[]): Promise<Viewer> {
568
+ await this.destroy();
569
+ return this.bootstrap(tagManagerParameterValues);
570
+ }
571
+
572
+ /**
573
+ * Destroys
574
+ *
575
+ * * all {@link VariantInstance}s using {@link destroyVariantInstances}
576
+ * * calling `dispose` on the `Engine` and `Scene`
577
+ */
578
+ public destroy(): Viewer {
579
+ this.destroyVariantInstances();
580
+ this.scene.dispose();
581
+ SpecStorage.destroy();
582
+ return this;
583
+ }
584
+
585
+ /**
586
+ * Show coordinate system with given dimension (for debugging purpose).
587
+ */
588
+ public showWorldCoordinates(dimension: number) {
589
+ const scene = this.scene;
590
+ const makeTextPlane = function (text: string, color: string, size: number) {
591
+ const dynamicTexture = new DynamicTexture('DynamicTexture', 50, scene, true);
592
+ dynamicTexture.hasAlpha = true;
593
+ dynamicTexture.drawText(text, 5, 40, 'bold 36px Arial', color, 'transparent', true);
594
+ const plane = Mesh.CreatePlane('TextPlane', size, scene, true);
595
+ plane.material = new StandardMaterial('TextPlaneMaterial', scene);
596
+ plane.material.backFaceCulling = false;
597
+ (plane.material as StandardMaterial).specularColor = new Color3(0, 0, 0);
598
+ (plane.material as StandardMaterial).diffuseTexture = dynamicTexture;
599
+ return plane;
600
+ };
601
+
602
+ const axisX = Mesh.CreateLines(
603
+ 'axisX',
604
+ [
605
+ Vector3.Zero(),
606
+ new Vector3(dimension, 0, 0),
607
+ new Vector3(dimension * 0.95, 0.05 * dimension, 0),
608
+ new Vector3(dimension, 0, 0),
609
+ new Vector3(dimension * 0.95, -0.05 * dimension, 0),
610
+ ],
611
+ scene,
612
+ false
613
+ );
614
+ axisX.color = new Color3(1, 0, 0);
615
+ const xChar = makeTextPlane('X', 'red', dimension / 10);
616
+ xChar.position = new Vector3(0.9 * dimension, -0.05 * dimension, 0);
617
+ const axisY = Mesh.CreateLines(
618
+ 'axisY',
619
+ [
620
+ Vector3.Zero(),
621
+ new Vector3(0, dimension, 0),
622
+ new Vector3(-0.05 * dimension, dimension * 0.95, 0),
623
+ new Vector3(0, dimension, 0),
624
+ new Vector3(0.05 * dimension, dimension * 0.95, 0),
625
+ ],
626
+ scene,
627
+ false
628
+ );
629
+ axisY.color = new Color3(0, 1, 0);
630
+ const yChar = makeTextPlane('Y', 'green', dimension / 10);
631
+ yChar.position = new Vector3(0, 0.9 * dimension, -0.05 * dimension);
632
+ const axisZ = Mesh.CreateLines(
633
+ 'axisZ',
634
+ [
635
+ Vector3.Zero(),
636
+ new Vector3(0, 0, dimension),
637
+ new Vector3(0, -0.05 * dimension, dimension * 0.95),
638
+ new Vector3(0, 0, dimension),
639
+ new Vector3(0, 0.05 * dimension, dimension * 0.95),
640
+ ],
641
+ scene,
642
+ false
643
+ );
644
+ axisZ.color = new Color3(0, 0, 1);
645
+ const zChar = makeTextPlane('Z', 'blue', dimension / 10);
646
+ zChar.position = new Vector3(0, 0.05 * dimension, 0.9 * dimension);
647
+ }
648
+
649
+ /**
650
+ * Pause render loop.
651
+ */
652
+ public pauseRendering() {
653
+ this._isRenderLoopPaused = true;
654
+ }
655
+
656
+ /**
657
+ * Resume render loop when paused.
658
+ */
659
+ public resumeRendering() {
660
+ this._isRenderLoopPaused = false;
661
+ }
662
+
663
+ /**
664
+ * @emits {@link Event.SCENE_PROCESSING_START}
665
+ * @emits {@link Event.SCENE_PROCESSING_END}
666
+ */
667
+ protected async initScene(): Promise<Scene> {
668
+ const sceneJson = SpecStorage.get<SceneJson>('scene');
669
+ this.broadcastEvent(Event.SCENE_PROCESSING_START, sceneJson);
670
+ const engine = new Engine(
671
+ this.canvas as HTMLCanvasElement,
672
+ sceneJson.engine?.antialiasing ?? false,
673
+ sceneJson.engine?.options
674
+ );
675
+ const scene = await sceneSetup(engine, sceneJson);
676
+ if (sceneJson.meshPicking) {
677
+ new HighlightLayer('default', scene);
678
+ scene.onPointerPick = (pointerEvent: IPointerEvent, pickInfo: PickingInfo) => {
679
+ if (!pickInfo.hit) {
680
+ return;
681
+ }
682
+ const mesh = pickInfo.pickedMesh;
683
+ this.broadcastEvent(Event.MESH_PICKED, mesh, mesh?.metadata.element, mesh?.metadata.variant);
684
+ if (mesh?.metadata.element) {
685
+ this.broadcastEvent(Event.ELEMENT_PICKED, mesh.metadata.element);
686
+ }
687
+ if (mesh?.metadata.variant) {
688
+ if (mesh.metadata.variant.inheritedParameters[Parameter.HIGHLIGHT_ENABLED]) {
689
+ mesh.metadata.variant.toggleHighlight();
690
+ }
691
+ this.broadcastEvent(Event.VARIANT_PICKED, mesh.metadata.variant);
692
+ }
693
+ };
694
+ }
695
+ this._sceneManager = await SceneManager.create(scene);
696
+ this._animationManager = await AnimationManager.create(scene);
697
+ if (sceneJson.cloneMaterialsOnMutation !== undefined) {
698
+ this._cloneMaterialsOnMutation = sceneJson.cloneMaterialsOnMutation;
699
+ }
700
+ // register observers for tag manager
701
+ this.tagManager.registerNewTransformNodeObservers(scene);
702
+ this.broadcastEvent(Event.SCENE_PROCESSING_END, scene);
703
+ return scene;
704
+ }
705
+
706
+ /**
707
+ * Register custom file loader for babylon files which adds "missing-material" metadata to meshes which reference
708
+ * materials that are not present in the `materials` section of the given babylon file.
709
+ *
710
+ * Required for babylon files & materials loaded from "Combeenation configurator assets".
711
+ */
712
+ protected initCbnBabylonLoaderPlugin() {
713
+ const previousLoaderPlugin = SceneLoader.GetPluginForExtension('babylon') as ISceneLoaderPlugin;
714
+ const customLoaderPlugin = getCustomCbnBabylonLoaderPlugin(previousLoaderPlugin);
715
+ SceneLoader.RegisterPlugin(customLoaderPlugin);
716
+ }
717
+
718
+ /**
719
+ * Batch creation of multiple {@link VariantInstance} objects with a {@link SetupJson} object passed
720
+ */
721
+ protected async createVariantInstances(): Promise<VariantInstance[]> {
722
+ const setupJson = SpecStorage.get<SetupJson>('setup');
723
+ const instances: VariantInstance[] = [];
724
+ for (const instanceDefinition of setupJson.instances) {
725
+ // don't create the instance right away if `lazy` is set, register it for later creation (on first usage) instead
726
+ // however if the variant should be `visible` by default, `lazy` loading doesn't make sense and should therefore
727
+ // be overruled by the `visible` flag
728
+ if (instanceDefinition.lazy && instanceDefinition.parameters?.visible !== true) {
729
+ this.variantInstances.register(instanceDefinition);
730
+ continue;
731
+ }
732
+ instances.push(
733
+ await this.variantInstances.create(
734
+ instanceDefinition.variant,
735
+ instanceDefinition.name,
736
+ instanceDefinition.parameters
737
+ )
738
+ );
739
+ }
740
+ return instances;
741
+ }
742
+ }