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