@combeenation/3d-viewer 7.0.0 → 7.1.0

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