@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,933 +1,933 @@
1
- import {
2
- deactivateTransformNode,
3
- getDottedPathForNode,
4
- injectNodeMetadata,
5
- intersectingNodeNames,
6
- reportDuplicateNodeNames,
7
- } from '../util/babylonHelper';
8
- import { loadJson, mergeMaps } from '../util/resourceHelper';
9
- import { DottedPath } from './dottedPath';
10
- import { Element } from './element';
11
- import { Event } from './event';
12
- import { Parameter } from './parameter';
13
- import { ParameterObservable } from './parameterObservable';
14
- import { Parameterizable } from './parameterizable';
15
- import { VariantParameterizable } from './variantParameterizable';
16
- import { Viewer } from './viewer';
17
- import { ViewerLight } from './viewerLight';
18
- import { Light } from '@babylonjs/core/Lights/light';
19
- import '@babylonjs/core/Loading/Plugins/babylonFileLoader';
20
- import { SceneLoader } from '@babylonjs/core/Loading/sceneLoader';
21
- import { Material } from '@babylonjs/core/Materials/material';
22
- import { Mesh } from '@babylonjs/core/Meshes/mesh';
23
- import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
24
- import { AssetContainer } from '@babylonjs/core/assetContainer';
25
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_draco_mesh_compression';
26
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_clearcoat';
27
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_ior';
28
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness';
29
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_sheen';
30
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_specular';
31
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_translucency';
32
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_transmission';
33
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_unlit';
34
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_variants';
35
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_texture_basisu';
36
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_texture_transform';
37
- import '@babylonjs/loaders/glTF/2.0/glTFLoader';
38
- import { cloneDeep, concat, get, isEmpty, isEqual, isString, merge, set } from 'lodash-es';
39
-
40
- /**
41
- * A concrete "Variant". Most of these are handled by either the {@link Viewer} or {@link VariantInstance}.
42
- */
43
- export class Variant extends Parameterizable {
44
- public assetContainer: AssetContainer;
45
-
46
- public readonly elements: Element[] = [];
47
-
48
- public readonly viewerLights: ViewerLight[] = [];
49
-
50
- public structureJson: StructureJson;
51
-
52
- protected _dottedNodes: Map<DottedPath, TransformNode> | undefined;
53
-
54
- protected readonly _children: Map<string, Variant> = new Map();
55
-
56
- protected readonly _parameterObservers: Map<string, ParameterObserver[]> = new Map();
57
-
58
- /**
59
- * @internal
60
- */
61
- private parametersInitialized: boolean = false;
62
-
63
- /**
64
- * Constructor.
65
- */
66
- protected constructor(
67
- protected readonly _variantInstance: VariantInstance | null,
68
- public readonly name: string,
69
- protected readonly _structureJson: StructureJson,
70
- public readonly viewer: Viewer,
71
- public readonly parent?: Variant
72
- ) {
73
- super(cloneDeep(_structureJson.parameterDeclaration), cloneDeep(_structureJson.parameters));
74
- for (const parameter in _structureJson.parameterDeclaration) {
75
- if (!(parameter in (_structureJson.parameters || []))) {
76
- throw new Error(`No default value for parameter "${parameter}" defined.`);
77
- }
78
- }
79
- this.assetContainer = new AssetContainer(viewer.scene);
80
- this.structureJson = cloneDeep(_structureJson);
81
- }
82
-
83
- /**
84
- * Creates the root {@link Variant}.
85
- */
86
- public static async createRoot(structureJson: StructureJson, viewer: Viewer): Promise<Variant> {
87
- return Variant.create(null, '_', structureJson, viewer);
88
- }
89
-
90
- /**
91
- * Creates a {@link Variant} based on given parameters.
92
- *
93
- * @throws Error if "gltf" property is provided without a filename
94
- */
95
- public static async create(
96
- variantInstance: VariantInstance | null,
97
- name: string,
98
- structureJson: StructureJson,
99
- viewer: Viewer,
100
- parent?: Variant
101
- ): Promise<Variant> {
102
- const variant = new Variant(variantInstance, name, structureJson, viewer, parent);
103
- await variant.loadAssets();
104
- return variant;
105
- }
106
-
107
- /**
108
- * The ancestor {@link Variant}s ordered from top to bottom in the built tree.
109
- */
110
- get ancestors(): Variant[] {
111
- const ancestors = [];
112
- let variant: Variant = this;
113
- while (variant.parent) {
114
- ancestors.unshift(variant.parent);
115
- variant = variant.parent;
116
- }
117
- return ancestors;
118
- }
119
-
120
- /**
121
- * The root {@link Variant}.
122
- */
123
- get root(): Variant {
124
- return this.ancestors[0] ?? this;
125
- }
126
-
127
- /**
128
- * The {@link DottedPath} in the built tree of {@link Variant}s.
129
- * E.g. "_.top-1.sub-2.sub-sub-3"
130
- */
131
- get dottedPath(): DottedPath {
132
- const parentIds = this.ancestors.map(ancestor => {
133
- return ancestor.name;
134
- });
135
- return DottedPath.createFromParts(parentIds).addPart(this.name);
136
- }
137
-
138
- /**
139
- * Gets the {@link VariantInstance} this variant was created for. There are variants without an instance (the "ghost"
140
- * ones used for bootstrapping instances). The usage of {@link Variant}s without an instance is an absolute edge-case
141
- * when deeply using the viewer api and working abroad best practices.
142
- */
143
- get variantInstance(): VariantInstance | null {
144
- return this._variantInstance;
145
- }
146
-
147
- /**
148
- * The id representing a {@link DottedPath}.
149
- */
150
- get id(): string {
151
- const dottedPath = DottedPath.create(this.dottedPath);
152
- dottedPath.shiftPart(); // remove root
153
- return dottedPath.path || '_';
154
- }
155
-
156
- /**
157
- * The defined glTF Asset.
158
- */
159
- get glTF(): Asset | undefined {
160
- if (this.structureJson.glTF) {
161
- if (isString(this.structureJson.glTF)) {
162
- return {
163
- rootUrl: this.structureJson.glTF,
164
- fileName: undefined,
165
- };
166
- }
167
- if (isEmpty(this.structureJson.glTF.rootUrl)) {
168
- throw new Error(`No "rootUrl" defined in "glTF" definition for variant "${this.id}".`);
169
- }
170
- return this.structureJson.glTF;
171
- }
172
- }
173
-
174
- /**
175
- * The defined glTF URI.
176
- */
177
- get glTFUri(): string | undefined {
178
- if (this.glTF) {
179
- return [this.glTF.rootUrl, this.glTF.fileName].join('');
180
- }
181
- }
182
-
183
- /**
184
- * The inherited defined glTF URI.
185
- */
186
- get inheritedGlTFUri(): string | undefined {
187
- if (!this.glTFUri && this.parent) {
188
- return this.parent.inheritedGlTFUri;
189
- }
190
- return this.glTFUri;
191
- }
192
-
193
- /**
194
- * The TransformNodes of the {@link Variant}.
195
- */
196
- get nodes(): TransformNode[] {
197
- const rootNodes = this.assetContainer
198
- .getNodes()
199
- .filter(n => n instanceof TransformNode && !n.parent) as TransformNode[];
200
- return rootNodes;
201
- }
202
-
203
- /**
204
- * The {@link ViewerLight}s of the {@link Variant}.
205
- */
206
- get lights(): Light[] {
207
- return this.assetContainer.lights;
208
- }
209
-
210
- /**
211
- * All TransformNodes of the {@link Variant} mapped flat with a {@link DottedPath}.
212
- */
213
- get dottedNodes(): Map<DottedPath, TransformNode> {
214
- if (!this._dottedNodes) {
215
- const nodes = this.assetContainer.getNodes().filter(n => n instanceof TransformNode);
216
- const dottedNodes = new Map();
217
- nodes.forEach(node => {
218
- dottedNodes.set(node.metadata.dottedPath, node);
219
- });
220
- this._dottedNodes = dottedNodes;
221
- }
222
- return this._dottedNodes;
223
- }
224
-
225
- /**
226
- * The Materials of the {@link Variant}.
227
- */
228
- get materials(): Material[] {
229
- return this.assetContainer.materials;
230
- }
231
-
232
- /**
233
- * The cloned TransformNodes of all {@link Element}s created for this {@link Variant}.
234
- */
235
- get elementNodes(): TransformNode[] {
236
- return this.elements.reduce((a, c) => a.concat(c.nodes), [] as TransformNode[]);
237
- }
238
-
239
- /**
240
- * The cloned TransformNodes of all {@link Element}s created for this {@link Variant} flattened.
241
- */
242
- get elementNodesFlat(): TransformNode[] {
243
- return this.elements.reduce((a, c) => [...a, ...c.nodesFlat], [] as TransformNode[]);
244
- }
245
-
246
- /**
247
- * All {@link Element}s from this {@link Variant}'s parents.
248
- */
249
- get inheritedElements(): Element[] {
250
- let elements: Element[] = [];
251
- this.ancestors.forEach(ancestor => {
252
- elements = concat(elements, ancestor.elements);
253
- });
254
- return concat(elements, this.elements);
255
- }
256
-
257
- /**
258
- * All {@link ViewerLight}s inherited from this {@link Variant}'s parents.
259
- */
260
- get inheritedViewerLights(): ViewerLight[] {
261
- let viewerLights: ViewerLight[] = [];
262
- this.ancestors.forEach(ancestor => {
263
- viewerLights = concat(viewerLights, ancestor.viewerLights);
264
- });
265
- return concat(viewerLights, this.viewerLights);
266
- }
267
-
268
- /**
269
- * All TransformNodes inherited from this {@link Variant}'s parents.
270
- */
271
- get inheritedNodes(): TransformNode[] {
272
- let nodes: TransformNode[] = [];
273
- this.ancestors.forEach(ancestor => {
274
- nodes = concat(nodes, ancestor.nodes);
275
- });
276
- return concat(nodes, this.nodes);
277
- }
278
-
279
- /**
280
- * All TransformNodes inherited from this {@link Variant}'s parents mapped flat with a {@link DottedPath}.
281
- */
282
- get inheritedDottedNodes(): Map<DottedPath, TransformNode> {
283
- let dottedNodes = this.dottedNodes;
284
- this.ancestors.forEach(ancestor => {
285
- dottedNodes = mergeMaps(dottedNodes, ancestor.dottedNodes);
286
- });
287
- return dottedNodes;
288
- }
289
-
290
- /**
291
- * All Lights inherited from this {@link Variant}'s parents.
292
- */
293
- get inheritedLights(): Light[] {
294
- let lights: Light[] = [];
295
- this.ancestors.forEach(ancestor => {
296
- lights = concat(lights, ancestor.lights);
297
- });
298
- return concat(lights, this.lights);
299
- }
300
-
301
- /**
302
- * The {@link ParameterDeclarations} inherited from this {@link Variant}'s parents.
303
- */
304
- get inheritedParameterDeclaration(): ParameterDeclarations {
305
- const declaration = {};
306
- this.ancestors.forEach(ancestor => {
307
- merge(declaration, ancestor.parameterDeclaration);
308
- });
309
- return merge(declaration, this.parameterDeclaration);
310
- }
311
-
312
- /**
313
- * The {@link ParameterBag} inherited from this {@link Variant}'s parents.
314
- */
315
- get inheritedParameters(): ParameterBag {
316
- const parameters = {};
317
- this.ancestors.forEach(ancestor => {
318
- merge(parameters, ancestor.parameters);
319
- });
320
- return merge(parameters, this.parameters);
321
- }
322
-
323
- /**
324
- * All Materials from this {@link Variant}'s parents.
325
- */
326
- get inheritedMaterials(): Material[] {
327
- let materials: Material[] = [];
328
- this.ancestors.forEach(ancestor => {
329
- materials = concat(materials, ancestor.materials);
330
- });
331
- return concat(materials, this.materials);
332
- }
333
-
334
- /**
335
- * Gets the direct children of the current {@link Variant}.
336
- */
337
- public async getChildren(): Promise<Variant[]> {
338
- const children: Variant[] = [];
339
- for (const name in this.structureJson.variants) {
340
- children.push(await this.getDescendant(name));
341
- }
342
- return children;
343
- }
344
-
345
- /**
346
- * Gets a descendant {@link Variant} of the current {@link Variant} relative to its {@link DottedPath}.
347
- * If you have the dotted path `_.product_x.variant_blue.with_yellow_highlight` in a tree and you operate on the
348
- * `product_x`, you can call `this.getDescendant('variant_blue.with_yellow_highlight')` to get the lowermost
349
- * {@link Variant}.
350
- */
351
- public async getDescendant(dottedPath: DottedPathArgument): Promise<Variant> {
352
- const _dottedPath = DottedPath.create(dottedPath);
353
- const [name, ...descendantParts] = _dottedPath.parts;
354
- let variant;
355
- if (this._children.has(name)) {
356
- variant = this._children.get(name);
357
- } else {
358
- if (!this.structureJson.variants) {
359
- throw new Error(`Missing key "variants" in JSON structure for variant "${this.id}".`);
360
- }
361
- if (!this.structureJson.variants[name]) {
362
- throw new Error(`Variant "${_dottedPath.path}" not defined in JSON structure for variant "${this.id}".`);
363
- }
364
- if (this.structureJson.variants[name].file) {
365
- const file = this.structureJson.variants[name].file as string;
366
- variant = await Variant.create(
367
- this.variantInstance,
368
- name,
369
- await loadJson<StructureJson>(file),
370
- this.viewer,
371
- this
372
- );
373
- } else {
374
- variant = await Variant.create(
375
- this.variantInstance,
376
- name,
377
- this.structureJson.variants[name],
378
- this.viewer,
379
- this
380
- );
381
- }
382
- this._children.set(name, variant);
383
- }
384
- if (!variant) {
385
- throw new Error(`Variant "${_dottedPath.path}" was not created.`);
386
- }
387
- if (descendantParts.length > 0) {
388
- return await variant.getDescendant(DottedPath.createFromParts(descendantParts));
389
- }
390
- return variant;
391
- }
392
-
393
- /**
394
- * Gets the desired {@link Element} of the current {@link Variant} relative to its {@link DottedPath}.
395
- * Uses the mechanism of {@link getDescendant} to resolve the appropriate variant in tree.
396
- */
397
- public async getElement(dottedPath: DottedPathArgument): Promise<Element> {
398
- const _dottedPath = DottedPath.create(dottedPath);
399
- const elementName = _dottedPath.popPart();
400
- let variant: Variant = this;
401
- if (_dottedPath.parts.length > 0) {
402
- variant = await this.getDescendant(_dottedPath);
403
- }
404
- if (variant.inheritedElements.length === 0) {
405
- throw new Error(
406
- `No elements for variant "${variant.id}" found. ` +
407
- `Either none are defined or they are not initialized (are you operating on the appropriate living?).`
408
- );
409
- }
410
- let element;
411
- variant.inheritedElements.forEach(_element => {
412
- if (_element.name === elementName) {
413
- element = _element;
414
- }
415
- });
416
- if (!element) {
417
- throw new Error(`Element with name "${elementName}" does not exist for variant "${variant.id}".`);
418
- }
419
- return element;
420
- }
421
-
422
- /**
423
- * Gets the desired {@link ViewerLight} of the current {@link Variant} relative to its {@link DottedPath}.
424
- * Uses the mechanism of {@link getDescendant} to resolve the appropriate variant in tree.
425
- */
426
- public async getViewerLight(dottedPath: DottedPathArgument): Promise<ViewerLight> {
427
- const _dottedPath = DottedPath.create(dottedPath);
428
- const viewerLightName = _dottedPath.popPart();
429
- let variant: Variant = this;
430
- if (_dottedPath.parts.length > 0) {
431
- variant = await this.getDescendant(_dottedPath);
432
- }
433
- if (variant.inheritedViewerLights.length === 0) {
434
- throw new Error(
435
- `No viewerLights for variant "${variant.id}" found. ` +
436
- `Either none are defined or they are not initialized (are you operating on the appropriate living?).`
437
- );
438
- }
439
- let viewerLight;
440
- variant.inheritedViewerLights.forEach(_viewerLight => {
441
- if (_viewerLight.name === viewerLightName) {
442
- viewerLight = _viewerLight;
443
- }
444
- });
445
- if (!viewerLight) {
446
- throw new Error(`ViewerLight with name "${viewerLightName}" does not exist for variant "${variant.id}".`);
447
- }
448
- return viewerLight;
449
- }
450
-
451
- /**
452
- * A proxy for directly getting a Node from an {@link Element} by its {@link DottedPath}s.
453
- */
454
- public async getNode(
455
- elementDottedPath: DottedPathArgument,
456
- nodeDottedPath: DottedPathArgument
457
- ): Promise<TransformNode> {
458
- const element = await this.getElement(elementDottedPath);
459
- return element.getNode(nodeDottedPath);
460
- }
461
-
462
- /**
463
- * A proxy for directly getting a Mesh from an {@link Element} by its {@link DottedPath}s.
464
- */
465
- public async getMesh(
466
- elementDottedPath: DottedPathArgument,
467
- meshDottedPath: DottedPathArgument
468
- ): Promise<Mesh | null> {
469
- const element = await this.getElement(elementDottedPath);
470
- return element.getMesh(meshDottedPath);
471
- }
472
-
473
- /**
474
- * Creates a living clone of this {@link Variant}. Will clone all parent {@link Variant}s in tree.
475
- *
476
- * @emit {@link Event.VARIANT_CREATED}
477
- * @ignore
478
- */
479
- public async createLiving(variantInstance: VariantInstance, parameters?: ParameterBag): Promise<Variant> {
480
- const parent = await this.parent?.createLiving(variantInstance);
481
- const variant = new Variant(variantInstance, this.name, this._structureJson, this.viewer, parent);
482
- parent?._children.set(variant.name, variant);
483
- variant.assetContainer = this.assetContainer;
484
- variant.parameterObservers = cloneDeep(this.parameterObservers);
485
- await variant.createElements();
486
- await variant.createViewerLights();
487
- variant.addParameterObservers();
488
- await variant.bootstrapParameters(parameters);
489
- this.viewer.broadcastEvent(Event.VARIANT_CREATED, variant);
490
- return variant;
491
- }
492
-
493
- /**
494
- * Destroys this {@link Variant}, all parents and destroy the {@link Element}s.
495
- */
496
- public destroy(): Variant {
497
- this.elements.forEach(element => element.destroy());
498
- if (this.parent) {
499
- this.parent.destroy();
500
- }
501
- this.broadcastEvent(Event.VARIANT_DESTROYED, this);
502
- return this;
503
- }
504
-
505
- /**
506
- * Places the given {@link ParameterBag} in the {@link Variant}'s parameters, replaces all patterns in the
507
- * {@link StructureJson}, broadcasts all {@link ParameterObserver}s and delegates them to its {@link Element}s.
508
- *
509
- * @emit {@link Event.VARIANT_PARAMETER_COMMITTED}
510
- */
511
- public async commitParameters(parameters?: ParameterBag): Promise<Variant> {
512
- parameters = merge({}, parameters);
513
-
514
- // remember old parameter values for later comparison
515
- const oldParameters = cloneDeep(this.inheritedParameters);
516
-
517
- // replace patterns in given parameters
518
- let _parameters = JSON.stringify(parameters);
519
- for (const parameter in this.inheritedParameters) {
520
- const value = this.inheritedParameters[parameter];
521
- const search = new RegExp(`\\$\\{${parameter}\\}`, 'g');
522
- _parameters = _parameters.replace(search, value.toString());
523
- }
524
- merge(parameters, JSON.parse(_parameters));
525
-
526
- // merge inherited parameters and replaced given parameters
527
- const mergedParameters = merge({}, this.inheritedParameters, parameters);
528
-
529
- // replace patterns in structure parameters
530
- const structureParameters = this._structureJson.parameters || {};
531
- let _structureParameters = JSON.stringify(structureParameters);
532
- for (const parameter in mergedParameters) {
533
- const value = mergedParameters[parameter];
534
- const search = new RegExp(`\\$\\{${parameter}\\}`, 'g');
535
- _structureParameters = _structureParameters.replace(search, value.toString());
536
- }
537
- const replacedStructureParameters = JSON.parse(_structureParameters);
538
-
539
- // calculate which replaced structure parameters have changed and should overload given parameters
540
- const differentStructureParameters: ParameterBag = {};
541
- for (const parameter in replacedStructureParameters) {
542
- if (!isEqual(structureParameters[parameter], replacedStructureParameters[parameter])) {
543
- differentStructureParameters[parameter] = replacedStructureParameters[parameter];
544
- }
545
- }
546
-
547
- // merge replaced structure parameters and given inherited parameters to structure parameters
548
- merge(this.parameters, mergedParameters, differentStructureParameters);
549
-
550
- // inherited parameters are now the new parameters to process
551
- const newParameters = this.inheritedParameters;
552
-
553
- // replace all parameter patterns in structure json
554
- let structure = JSON.stringify(this._structureJson);
555
- for (const parameter in newParameters) {
556
- const value = newParameters[parameter];
557
- const search = new RegExp(`\\$\\{${parameter}\\}`, 'g');
558
- structure = structure.replace(search, value.toString());
559
- }
560
- this.structureJson = JSON.parse(structure);
561
-
562
- // handle parameter observers
563
- let observerPromises: Promise<void | ParameterObserver>[] = [];
564
- for (const parameter in newParameters) {
565
- const oldParameterValue = oldParameters[parameter];
566
- const newParameterValue = newParameters[parameter];
567
- this.assertParameter(this.inheritedParameterDeclaration, parameter, newParameterValue);
568
- if (oldParameterValue === newParameterValue && this.parametersInitialized) {
569
- continue;
570
- }
571
- // parameter changed
572
- const parameterObservers = mergeMaps(this._parameterObservers, this.parameterObservers);
573
- if (parameterObservers.has(parameter)) {
574
- const observers = parameterObservers.get(parameter)!;
575
- observerPromises = concat(
576
- observerPromises,
577
- observers.map(observer => {
578
- const observerResult = observer(this, oldParameterValue, newParameterValue);
579
- return Promise.resolve(observerResult).then(() => {
580
- if (this.parametersInitialized) {
581
- this.broadcastEvent(
582
- Event.VARIANT_PARAMETER_COMMITTED,
583
- this,
584
- parameter,
585
- oldParameterValue,
586
- newParameterValue
587
- );
588
- }
589
- });
590
- })
591
- );
592
- }
593
- }
594
- await Promise.all(observerPromises);
595
-
596
- // broadcast that bag has been committed
597
- this.broadcastEvent(Event.VARIANT_PARAMETER_BAG_COMMITTED, this, oldParameters, newParameters);
598
-
599
- // commit parameters to elements
600
- await this.commitParametersToElements(newParameters);
601
-
602
- // commit parameters to lights
603
- await this.commitParametersToViewerLights(newParameters);
604
-
605
- // propagate parameters to parent
606
- if (this.parent) {
607
- await this.parent.commitParameters(this.parameters);
608
- }
609
-
610
- return this;
611
- }
612
-
613
- /**
614
- * Adds an observer function for camera matrix changes for given `dottedPath` representing the {@link Element}
615
- * and the `traceable`. The `observer` gets 2 parameters: the `AbstractMesh` and a `ClientRect` object.
616
- */
617
- public async addTraceableObserver(
618
- dottedPath: DottedPathArgument,
619
- observer: CallableFunction,
620
- payload?: any
621
- ): Promise<Element> {
622
- const _dottedPath = DottedPath.create(dottedPath);
623
- const traceableName = _dottedPath.popPart();
624
- if (!traceableName) {
625
- throw new Error(
626
- `The dottedPath must consist of the element and the name of the defined corresponding ` +
627
- `traceable ("${_dottedPath.path}" given).`
628
- );
629
- }
630
- const element = await this.getElement(_dottedPath);
631
- return element.addTraceableObserver(traceableName, observer, payload);
632
- }
633
-
634
- /**
635
- * Loads {@link glTFUri} with assets, adds them to the {@link Variant}'s `assetContainer` and deactivates the meshes.
636
- * (for further processing).
637
- * @emits {@link Event.ASSET_LOADING_START}
638
- * @emits {@link Event.ASSET_LOADING_END}
639
- */
640
- protected async loadAssets(): Promise<Variant> {
641
- this.broadcastEvent(Event.ASSET_LOADING_START, this);
642
- return new Promise<Variant>(resolve => {
643
- if (!this.structureJson) {
644
- this.broadcastEvent(Event.ASSET_LOADING_END, this);
645
- return resolve(this);
646
- }
647
- if (!this.glTF) {
648
- this.broadcastEvent(Event.ASSET_LOADING_END, this);
649
- return resolve(this);
650
- }
651
- SceneLoader.LoadAssetContainer(
652
- this.glTF.rootUrl,
653
- this.glTF.fileName,
654
- this.viewer.scene,
655
- // on success
656
- container => {
657
- this.assetContainer = container;
658
- const nodes = this.assetContainer.getNodes().filter(n => n instanceof TransformNode) as TransformNode[];
659
- reportDuplicateNodeNames(
660
- intersectingNodeNames(nodes, this.viewer.scene.getNodes(), n => n instanceof TransformNode)
661
- );
662
- nodes.forEach(node => {
663
- deactivateTransformNode(node, false);
664
- injectNodeMetadata(node, { dottedPath: getDottedPathForNode(node), originalName: node.name }, false);
665
- });
666
- this.assetContainer.lights.forEach(light => {
667
- light.setEnabled(false);
668
- injectNodeMetadata(light, { dottedPath: getDottedPathForNode(light), originalName: light.name }, false);
669
- this.viewer.scene.addLight(light);
670
- });
671
- this.assetContainer.cameras.forEach(camera => {
672
- camera.setEnabled(false);
673
- injectNodeMetadata(camera, { dottedPath: getDottedPathForNode(camera), originalName: camera.name }, false);
674
- this.viewer.scene.addCamera(camera);
675
- });
676
- this.assetContainer.materials.forEach(material => this.viewer.scene.materials.push(material));
677
- this.broadcastEvent(Event.ASSET_LOADING_END, this);
678
- resolve(this);
679
- },
680
- // on progress
681
- undefined,
682
- // on error
683
- reason => {
684
- this.broadcastEvent(Event.ASSET_LOADING_END, this);
685
- throw new Error(`Error loading assets for variant "${this.id}": ${reason}.`);
686
- }
687
- );
688
- });
689
- }
690
-
691
- /**
692
- * Commits given parameters to all {@link Element}s.
693
- */
694
- protected async commitParametersToElements(parameters: ParameterBag) {
695
- await Promise.all(
696
- this.elements.map(element => this.commitParametersToVariantParameterizable(parameters, element, 'elements'))
697
- );
698
- }
699
-
700
- /**
701
- * Commits given parameters to all {@link ViewerLight}s.
702
- */
703
- protected async commitParametersToViewerLights(parameters: ParameterBag) {
704
- await Promise.all(
705
- this.viewerLights.map(viewerLight =>
706
- this.commitParametersToVariantParameterizable(parameters, viewerLight, 'lights')
707
- )
708
- );
709
- }
710
-
711
- /**
712
- * Commits given parameters to a {@link VariantParameterizable} and updates the according definition with given
713
- * key in the {@link StructureJson}. The `definitionKey` "elements" for example will update the definition in
714
- * `this.structureJson.elements`.
715
- */
716
- protected async commitParametersToVariantParameterizable(
717
- parameters: ParameterBag,
718
- parameterizable: VariantParameterizable,
719
- definitionKey: string
720
- ): Promise<ParameterObservable> {
721
- const initialDefinition = get(this._structureJson, definitionKey)[parameterizable.name];
722
- let initialDefinitionStr = JSON.stringify(initialDefinition);
723
- const _parameters: ParameterBag = {};
724
- for (const parameter in parameters) {
725
- const dpp = DottedPath.create(parameter);
726
- if (dpp.shiftPart() !== parameterizable.name) {
727
- continue;
728
- }
729
- // we got a parameterizable ("element") parameter
730
- let parameterValue = parameters[parameter];
731
- const parameterizableParameter = dpp.path;
732
- // If the variant is explicitly hidden, we must not override the visibility with element parameters. We need
733
- // an exception for visibility to avoid overloading already applied element parameters with element parameters
734
- // defined in the variant spec ("dotted parameters").
735
- // @see https://github.com/Combeenation/3d-viewer/issues/44
736
- if (parameterizableParameter === Parameter.VISIBLE && parameters[Parameter.VISIBLE] === false) {
737
- parameterValue = false;
738
- }
739
- _parameters[parameterizableParameter] = parameterValue;
740
- const search = new RegExp(`\\$\\{${parameterizableParameter}\\}`, 'g');
741
- initialDefinitionStr = initialDefinitionStr.replace(search, parameterValue.toString());
742
- }
743
- const definition = get(this.structureJson, definitionKey);
744
- definition[this.name] = JSON.parse(initialDefinitionStr);
745
- set(this.structureJson, definitionKey, definition);
746
- return await parameterizable.commitParameters(_parameters);
747
- }
748
-
749
- /**
750
- * Commits given {@link Parameter} to the {@link Variant}'s {@link Element}s.
751
- */
752
- protected async commitParameterToElements(parameter: string, value: ParameterValue): Promise<Variant> {
753
- const promises = [];
754
- for (const element of this.elements) {
755
- const paramShowsVariant = Parameter.VISIBLE === parameter && value;
756
-
757
- // Fixes https://combeenation.youtrack.cloud/issue/CB-7773
758
- // Don't enable/show the variants element if it is explicitly hidden via its element parameters.
759
- // E.g. via spec:
760
- // ```
761
- // variants: {
762
- // theVariant: {
763
- // elements: {
764
- // Main: ['root.main'],
765
- // Secondary: ['root.secondary'],
766
- // },
767
- // parameters: {
768
- // // !!! The element `Secondary` should **not** be enabled when its containing variant is enabled !!!
769
- // 'Secondary.visible': false,
770
- // }
771
- // }
772
- // }
773
- // ```
774
- const elVisibleParamPath = DottedPath.create([element.name, Parameter.VISIBLE]).toString();
775
- const elVisibleParamValue = this.inheritedParameters[elVisibleParamPath];
776
- const elVisibleParamValueParsed = elVisibleParamValue && Parameter.parseBoolean(elVisibleParamValue);
777
- const elIsHiddenViaParams = elVisibleParamValueParsed === false;
778
- if (paramShowsVariant && elIsHiddenViaParams) continue;
779
-
780
- // Fixes https://combeenation.youtrack.cloud/issue/CB-7809
781
- // Apply element material before showing the element to prevent loading of the elements "original" material which
782
- // is never shown when "overwritten" by elements material param.
783
- const elMaterialParamPath = DottedPath.create([element.name, Parameter.MATERIAL]).toString();
784
- const elMaterialParamValue = this.inheritedParameters[elMaterialParamPath];
785
- if (paramShowsVariant && elMaterialParamValue) {
786
- await element.commitParameter(Parameter.MATERIAL, elMaterialParamValue);
787
- }
788
-
789
- promises.push(element.commitParameter(parameter, value));
790
- }
791
- await Promise.all(promises);
792
- return this;
793
- }
794
-
795
- /**
796
- * Commits given {@link Parameter} to the {@link Variant}'s {@link Element}s.
797
- */
798
- protected async commitParameterToViewerLights(parameter: string, value: ParameterValue): Promise<Variant> {
799
- const promises = [];
800
- for (const viewerLight of this.viewerLights) {
801
- promises.push(viewerLight.commitParameter(parameter, value));
802
- }
803
- await Promise.all(promises);
804
- return this;
805
- }
806
-
807
- /**
808
- * Adds the default {@link ParameterObserver}s which are called every time {@link commitParameters} is called.
809
- */
810
- protected addParameterObservers(): Variant {
811
- this._parameterObservers.set(Parameter.VISIBLE, [
812
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
813
- await variant.commitParameterToElements(Parameter.VISIBLE, newValue);
814
- await variant.commitParameterToViewerLights(Parameter.VISIBLE, newValue);
815
- },
816
- ]);
817
- this._parameterObservers.set(Parameter.SCALING, [
818
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
819
- await variant.commitParameterToElements(Parameter.SCALING, newValue);
820
- await variant.commitParameterToViewerLights(Parameter.SCALING, newValue);
821
- },
822
- ]);
823
- this._parameterObservers.set(Parameter.MATERIAL, [
824
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
825
- await variant.commitParameterToElements(Parameter.MATERIAL, newValue);
826
- },
827
- ]);
828
- this._parameterObservers.set(Parameter.MATERIAL_COLOR, [
829
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
830
- await variant.commitParameterToElements(Parameter.MATERIAL_COLOR, newValue);
831
- },
832
- ]);
833
- this._parameterObservers.set(Parameter.MATERIAL_METALLNESS, [
834
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
835
- await variant.commitParameterToElements(Parameter.MATERIAL_METALLNESS, newValue);
836
- },
837
- ]);
838
- this._parameterObservers.set(Parameter.MATERIAL_ROUGHNESS, [
839
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
840
- await variant.commitParameterToElements(Parameter.MATERIAL_ROUGHNESS, newValue);
841
- },
842
- ]);
843
- this._parameterObservers.set(Parameter.HIGHLIGHT_COLOR, [
844
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
845
- await variant.commitParameterToElements(Parameter.HIGHLIGHT_COLOR, newValue);
846
- },
847
- ]);
848
- this._parameterObservers.set(Parameter.HIGHLIGHTED, [
849
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
850
- await variant.commitParameterToElements(Parameter.HIGHLIGHTED, newValue);
851
- },
852
- ]);
853
- this._parameterObservers.set(Parameter.POSITION, [
854
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
855
- await variant.commitParameterToElements(Parameter.POSITION, newValue);
856
- await variant.commitParameterToViewerLights(Parameter.POSITION, newValue);
857
- },
858
- ]);
859
- this._parameterObservers.set(Parameter.ROTATION, [
860
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
861
- await variant.commitParameterToElements(Parameter.ROTATION, newValue);
862
- await variant.commitParameterToViewerLights(Parameter.ROTATION, newValue);
863
- },
864
- ]);
865
- this._parameterObservers.set(Parameter.CAST_SHADOW, [
866
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
867
- await variant.commitParameterToElements(Parameter.CAST_SHADOW, newValue);
868
- },
869
- ]);
870
- this._parameterObservers.set(Parameter.CAST_SHADOW_FROM_LIGHTS, [
871
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
872
- await variant.commitParameterToElements(Parameter.CAST_SHADOW_FROM_LIGHTS, newValue);
873
- },
874
- ]);
875
- this._parameterObservers.set(Parameter.RECEIVE_SHADOWS, [
876
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
877
- await variant.commitParameterToElements(Parameter.RECEIVE_SHADOWS, newValue);
878
- },
879
- ]);
880
- return this;
881
- }
882
-
883
- /**
884
- * Creates {@link Element}s and clones nodes into them.
885
- */
886
- protected async createElements(forInstance?: string): Promise<Variant> {
887
- this.createElementDefinitionsIfNotExist();
888
- for (const name in this.structureJson.elements || {}) {
889
- this.elements.push(await Element.create(this, name));
890
- }
891
- // inject node meta to all inherited elements
892
- // we do this to inject the deepest and most concrete variant information to all cloned nodes in the tree
893
- this.inheritedElements.forEach(element =>
894
- element.nodes.forEach(node => injectNodeMetadata(node, { variant: this, variantParameterizable: element }))
895
- );
896
- return this;
897
- }
898
-
899
- /**
900
- * Creates {@link ViewerLight}s.
901
- */
902
- protected async createViewerLights(): Promise<Variant> {
903
- for (const name in this.structureJson.lights || {}) {
904
- this.viewerLights.push(await ViewerLight.create(this, name));
905
- }
906
- this.inheritedViewerLights.forEach(viewerLight => {
907
- injectNodeMetadata(viewerLight.light, { variant: this, variantParameterizable: viewerLight });
908
- });
909
- return this;
910
- }
911
-
912
- /**
913
- * Bootstrapping for parameters. It sets the `parametersInitialized` to true for all ancestors.
914
- */
915
- protected async bootstrapParameters(parameters?: ParameterBag): Promise<Variant> {
916
- await this.commitParameters(merge(cloneDeep(this.parameters), parameters));
917
- concat(this.ancestors, this).forEach(ancestor => (ancestor.parametersInitialized = true));
918
- return this;
919
- }
920
-
921
- /**
922
- * Ensures there is at least one "Main" {@link Element} for the {@link Variant} with all "root nodes" defined in path.
923
- */
924
- protected createElementDefinitionsIfNotExist() {
925
- if (this._structureJson.elements || this.inheritedNodes.length === 0) {
926
- return;
927
- }
928
- this._structureJson.elements = {
929
- Main: { paths: { include: this.inheritedNodes.map(node => node.metadata.dottedPath.path) } },
930
- };
931
- this.structureJson.elements = cloneDeep(this._structureJson.elements);
932
- }
933
- }
1
+ import {
2
+ deactivateTransformNode,
3
+ getDottedPathForNode,
4
+ injectNodeMetadata,
5
+ intersectingNodeNames,
6
+ reportDuplicateNodeNames,
7
+ } from '../util/babylonHelper';
8
+ import { loadJson, mergeMaps } from '../util/resourceHelper';
9
+ import { DottedPath } from './dottedPath';
10
+ import { Element } from './element';
11
+ import { Event } from './event';
12
+ import { Parameter } from './parameter';
13
+ import { ParameterObservable } from './parameterObservable';
14
+ import { Parameterizable } from './parameterizable';
15
+ import { VariantParameterizable } from './variantParameterizable';
16
+ import { Viewer } from './viewer';
17
+ import { ViewerLight } from './viewerLight';
18
+ import { Light } from '@babylonjs/core/Lights/light';
19
+ import '@babylonjs/core/Loading/Plugins/babylonFileLoader';
20
+ import { SceneLoader } from '@babylonjs/core/Loading/sceneLoader';
21
+ import { Material } from '@babylonjs/core/Materials/material';
22
+ import { Mesh } from '@babylonjs/core/Meshes/mesh';
23
+ import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
24
+ import { AssetContainer } from '@babylonjs/core/assetContainer';
25
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_draco_mesh_compression';
26
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_clearcoat';
27
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_ior';
28
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness';
29
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_sheen';
30
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_specular';
31
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_translucency';
32
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_transmission';
33
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_unlit';
34
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_variants';
35
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_texture_basisu';
36
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_texture_transform';
37
+ import '@babylonjs/loaders/glTF/2.0/glTFLoader';
38
+ import { cloneDeep, concat, get, isEmpty, isEqual, isString, merge, set } from 'lodash-es';
39
+
40
+ /**
41
+ * A concrete "Variant". Most of these are handled by either the {@link Viewer} or {@link VariantInstance}.
42
+ */
43
+ export class Variant extends Parameterizable {
44
+ public assetContainer: AssetContainer;
45
+
46
+ public readonly elements: Element[] = [];
47
+
48
+ public readonly viewerLights: ViewerLight[] = [];
49
+
50
+ public structureJson: StructureJson;
51
+
52
+ protected _dottedNodes: Map<DottedPath, TransformNode> | undefined;
53
+
54
+ protected readonly _children: Map<string, Variant> = new Map();
55
+
56
+ protected readonly _parameterObservers: Map<string, ParameterObserver[]> = new Map();
57
+
58
+ /**
59
+ * @internal
60
+ */
61
+ private parametersInitialized: boolean = false;
62
+
63
+ /**
64
+ * Constructor.
65
+ */
66
+ protected constructor(
67
+ protected readonly _variantInstance: VariantInstance | null,
68
+ public readonly name: string,
69
+ protected readonly _structureJson: StructureJson,
70
+ public readonly viewer: Viewer,
71
+ public readonly parent?: Variant
72
+ ) {
73
+ super(cloneDeep(_structureJson.parameterDeclaration), cloneDeep(_structureJson.parameters));
74
+ for (const parameter in _structureJson.parameterDeclaration) {
75
+ if (!(parameter in (_structureJson.parameters || []))) {
76
+ throw new Error(`No default value for parameter "${parameter}" defined.`);
77
+ }
78
+ }
79
+ this.assetContainer = new AssetContainer(viewer.scene);
80
+ this.structureJson = cloneDeep(_structureJson);
81
+ }
82
+
83
+ /**
84
+ * Creates the root {@link Variant}.
85
+ */
86
+ public static async createRoot(structureJson: StructureJson, viewer: Viewer): Promise<Variant> {
87
+ return Variant.create(null, '_', structureJson, viewer);
88
+ }
89
+
90
+ /**
91
+ * Creates a {@link Variant} based on given parameters.
92
+ *
93
+ * @throws Error if "gltf" property is provided without a filename
94
+ */
95
+ public static async create(
96
+ variantInstance: VariantInstance | null,
97
+ name: string,
98
+ structureJson: StructureJson,
99
+ viewer: Viewer,
100
+ parent?: Variant
101
+ ): Promise<Variant> {
102
+ const variant = new Variant(variantInstance, name, structureJson, viewer, parent);
103
+ await variant.loadAssets();
104
+ return variant;
105
+ }
106
+
107
+ /**
108
+ * The ancestor {@link Variant}s ordered from top to bottom in the built tree.
109
+ */
110
+ get ancestors(): Variant[] {
111
+ const ancestors = [];
112
+ let variant: Variant = this;
113
+ while (variant.parent) {
114
+ ancestors.unshift(variant.parent);
115
+ variant = variant.parent;
116
+ }
117
+ return ancestors;
118
+ }
119
+
120
+ /**
121
+ * The root {@link Variant}.
122
+ */
123
+ get root(): Variant {
124
+ return this.ancestors[0] ?? this;
125
+ }
126
+
127
+ /**
128
+ * The {@link DottedPath} in the built tree of {@link Variant}s.
129
+ * E.g. "_.top-1.sub-2.sub-sub-3"
130
+ */
131
+ get dottedPath(): DottedPath {
132
+ const parentIds = this.ancestors.map(ancestor => {
133
+ return ancestor.name;
134
+ });
135
+ return DottedPath.createFromParts(parentIds).addPart(this.name);
136
+ }
137
+
138
+ /**
139
+ * Gets the {@link VariantInstance} this variant was created for. There are variants without an instance (the "ghost"
140
+ * ones used for bootstrapping instances). The usage of {@link Variant}s without an instance is an absolute edge-case
141
+ * when deeply using the viewer api and working abroad best practices.
142
+ */
143
+ get variantInstance(): VariantInstance | null {
144
+ return this._variantInstance;
145
+ }
146
+
147
+ /**
148
+ * The id representing a {@link DottedPath}.
149
+ */
150
+ get id(): string {
151
+ const dottedPath = DottedPath.create(this.dottedPath);
152
+ dottedPath.shiftPart(); // remove root
153
+ return dottedPath.path || '_';
154
+ }
155
+
156
+ /**
157
+ * The defined glTF Asset.
158
+ */
159
+ get glTF(): Asset | undefined {
160
+ if (this.structureJson.glTF) {
161
+ if (isString(this.structureJson.glTF)) {
162
+ return {
163
+ rootUrl: this.structureJson.glTF,
164
+ fileName: undefined,
165
+ };
166
+ }
167
+ if (isEmpty(this.structureJson.glTF.rootUrl)) {
168
+ throw new Error(`No "rootUrl" defined in "glTF" definition for variant "${this.id}".`);
169
+ }
170
+ return this.structureJson.glTF;
171
+ }
172
+ }
173
+
174
+ /**
175
+ * The defined glTF URI.
176
+ */
177
+ get glTFUri(): string | undefined {
178
+ if (this.glTF) {
179
+ return [this.glTF.rootUrl, this.glTF.fileName].join('');
180
+ }
181
+ }
182
+
183
+ /**
184
+ * The inherited defined glTF URI.
185
+ */
186
+ get inheritedGlTFUri(): string | undefined {
187
+ if (!this.glTFUri && this.parent) {
188
+ return this.parent.inheritedGlTFUri;
189
+ }
190
+ return this.glTFUri;
191
+ }
192
+
193
+ /**
194
+ * The TransformNodes of the {@link Variant}.
195
+ */
196
+ get nodes(): TransformNode[] {
197
+ const rootNodes = this.assetContainer
198
+ .getNodes()
199
+ .filter(n => n instanceof TransformNode && !n.parent) as TransformNode[];
200
+ return rootNodes;
201
+ }
202
+
203
+ /**
204
+ * The {@link ViewerLight}s of the {@link Variant}.
205
+ */
206
+ get lights(): Light[] {
207
+ return this.assetContainer.lights;
208
+ }
209
+
210
+ /**
211
+ * All TransformNodes of the {@link Variant} mapped flat with a {@link DottedPath}.
212
+ */
213
+ get dottedNodes(): Map<DottedPath, TransformNode> {
214
+ if (!this._dottedNodes) {
215
+ const nodes = this.assetContainer.getNodes().filter(n => n instanceof TransformNode);
216
+ const dottedNodes = new Map();
217
+ nodes.forEach(node => {
218
+ dottedNodes.set(node.metadata.dottedPath, node);
219
+ });
220
+ this._dottedNodes = dottedNodes;
221
+ }
222
+ return this._dottedNodes;
223
+ }
224
+
225
+ /**
226
+ * The Materials of the {@link Variant}.
227
+ */
228
+ get materials(): Material[] {
229
+ return this.assetContainer.materials;
230
+ }
231
+
232
+ /**
233
+ * The cloned TransformNodes of all {@link Element}s created for this {@link Variant}.
234
+ */
235
+ get elementNodes(): TransformNode[] {
236
+ return this.elements.reduce((a, c) => a.concat(c.nodes), [] as TransformNode[]);
237
+ }
238
+
239
+ /**
240
+ * The cloned TransformNodes of all {@link Element}s created for this {@link Variant} flattened.
241
+ */
242
+ get elementNodesFlat(): TransformNode[] {
243
+ return this.elements.reduce((a, c) => [...a, ...c.nodesFlat], [] as TransformNode[]);
244
+ }
245
+
246
+ /**
247
+ * All {@link Element}s from this {@link Variant}'s parents.
248
+ */
249
+ get inheritedElements(): Element[] {
250
+ let elements: Element[] = [];
251
+ this.ancestors.forEach(ancestor => {
252
+ elements = concat(elements, ancestor.elements);
253
+ });
254
+ return concat(elements, this.elements);
255
+ }
256
+
257
+ /**
258
+ * All {@link ViewerLight}s inherited from this {@link Variant}'s parents.
259
+ */
260
+ get inheritedViewerLights(): ViewerLight[] {
261
+ let viewerLights: ViewerLight[] = [];
262
+ this.ancestors.forEach(ancestor => {
263
+ viewerLights = concat(viewerLights, ancestor.viewerLights);
264
+ });
265
+ return concat(viewerLights, this.viewerLights);
266
+ }
267
+
268
+ /**
269
+ * All TransformNodes inherited from this {@link Variant}'s parents.
270
+ */
271
+ get inheritedNodes(): TransformNode[] {
272
+ let nodes: TransformNode[] = [];
273
+ this.ancestors.forEach(ancestor => {
274
+ nodes = concat(nodes, ancestor.nodes);
275
+ });
276
+ return concat(nodes, this.nodes);
277
+ }
278
+
279
+ /**
280
+ * All TransformNodes inherited from this {@link Variant}'s parents mapped flat with a {@link DottedPath}.
281
+ */
282
+ get inheritedDottedNodes(): Map<DottedPath, TransformNode> {
283
+ let dottedNodes = this.dottedNodes;
284
+ this.ancestors.forEach(ancestor => {
285
+ dottedNodes = mergeMaps(dottedNodes, ancestor.dottedNodes);
286
+ });
287
+ return dottedNodes;
288
+ }
289
+
290
+ /**
291
+ * All Lights inherited from this {@link Variant}'s parents.
292
+ */
293
+ get inheritedLights(): Light[] {
294
+ let lights: Light[] = [];
295
+ this.ancestors.forEach(ancestor => {
296
+ lights = concat(lights, ancestor.lights);
297
+ });
298
+ return concat(lights, this.lights);
299
+ }
300
+
301
+ /**
302
+ * The {@link ParameterDeclarations} inherited from this {@link Variant}'s parents.
303
+ */
304
+ get inheritedParameterDeclaration(): ParameterDeclarations {
305
+ const declaration = {};
306
+ this.ancestors.forEach(ancestor => {
307
+ merge(declaration, ancestor.parameterDeclaration);
308
+ });
309
+ return merge(declaration, this.parameterDeclaration);
310
+ }
311
+
312
+ /**
313
+ * The {@link ParameterBag} inherited from this {@link Variant}'s parents.
314
+ */
315
+ get inheritedParameters(): ParameterBag {
316
+ const parameters = {};
317
+ this.ancestors.forEach(ancestor => {
318
+ merge(parameters, ancestor.parameters);
319
+ });
320
+ return merge(parameters, this.parameters);
321
+ }
322
+
323
+ /**
324
+ * All Materials from this {@link Variant}'s parents.
325
+ */
326
+ get inheritedMaterials(): Material[] {
327
+ let materials: Material[] = [];
328
+ this.ancestors.forEach(ancestor => {
329
+ materials = concat(materials, ancestor.materials);
330
+ });
331
+ return concat(materials, this.materials);
332
+ }
333
+
334
+ /**
335
+ * Gets the direct children of the current {@link Variant}.
336
+ */
337
+ public async getChildren(): Promise<Variant[]> {
338
+ const children: Variant[] = [];
339
+ for (const name in this.structureJson.variants) {
340
+ children.push(await this.getDescendant(name));
341
+ }
342
+ return children;
343
+ }
344
+
345
+ /**
346
+ * Gets a descendant {@link Variant} of the current {@link Variant} relative to its {@link DottedPath}.
347
+ * If you have the dotted path `_.product_x.variant_blue.with_yellow_highlight` in a tree and you operate on the
348
+ * `product_x`, you can call `this.getDescendant('variant_blue.with_yellow_highlight')` to get the lowermost
349
+ * {@link Variant}.
350
+ */
351
+ public async getDescendant(dottedPath: DottedPathArgument): Promise<Variant> {
352
+ const _dottedPath = DottedPath.create(dottedPath);
353
+ const [name, ...descendantParts] = _dottedPath.parts;
354
+ let variant;
355
+ if (this._children.has(name)) {
356
+ variant = this._children.get(name);
357
+ } else {
358
+ if (!this.structureJson.variants) {
359
+ throw new Error(`Missing key "variants" in JSON structure for variant "${this.id}".`);
360
+ }
361
+ if (!this.structureJson.variants[name]) {
362
+ throw new Error(`Variant "${_dottedPath.path}" not defined in JSON structure for variant "${this.id}".`);
363
+ }
364
+ if (this.structureJson.variants[name].file) {
365
+ const file = this.structureJson.variants[name].file as string;
366
+ variant = await Variant.create(
367
+ this.variantInstance,
368
+ name,
369
+ await loadJson<StructureJson>(file),
370
+ this.viewer,
371
+ this
372
+ );
373
+ } else {
374
+ variant = await Variant.create(
375
+ this.variantInstance,
376
+ name,
377
+ this.structureJson.variants[name],
378
+ this.viewer,
379
+ this
380
+ );
381
+ }
382
+ this._children.set(name, variant);
383
+ }
384
+ if (!variant) {
385
+ throw new Error(`Variant "${_dottedPath.path}" was not created.`);
386
+ }
387
+ if (descendantParts.length > 0) {
388
+ return await variant.getDescendant(DottedPath.createFromParts(descendantParts));
389
+ }
390
+ return variant;
391
+ }
392
+
393
+ /**
394
+ * Gets the desired {@link Element} of the current {@link Variant} relative to its {@link DottedPath}.
395
+ * Uses the mechanism of {@link getDescendant} to resolve the appropriate variant in tree.
396
+ */
397
+ public async getElement(dottedPath: DottedPathArgument): Promise<Element> {
398
+ const _dottedPath = DottedPath.create(dottedPath);
399
+ const elementName = _dottedPath.popPart();
400
+ let variant: Variant = this;
401
+ if (_dottedPath.parts.length > 0) {
402
+ variant = await this.getDescendant(_dottedPath);
403
+ }
404
+ if (variant.inheritedElements.length === 0) {
405
+ throw new Error(
406
+ `No elements for variant "${variant.id}" found. ` +
407
+ `Either none are defined or they are not initialized (are you operating on the appropriate living?).`
408
+ );
409
+ }
410
+ let element;
411
+ variant.inheritedElements.forEach(_element => {
412
+ if (_element.name === elementName) {
413
+ element = _element;
414
+ }
415
+ });
416
+ if (!element) {
417
+ throw new Error(`Element with name "${elementName}" does not exist for variant "${variant.id}".`);
418
+ }
419
+ return element;
420
+ }
421
+
422
+ /**
423
+ * Gets the desired {@link ViewerLight} of the current {@link Variant} relative to its {@link DottedPath}.
424
+ * Uses the mechanism of {@link getDescendant} to resolve the appropriate variant in tree.
425
+ */
426
+ public async getViewerLight(dottedPath: DottedPathArgument): Promise<ViewerLight> {
427
+ const _dottedPath = DottedPath.create(dottedPath);
428
+ const viewerLightName = _dottedPath.popPart();
429
+ let variant: Variant = this;
430
+ if (_dottedPath.parts.length > 0) {
431
+ variant = await this.getDescendant(_dottedPath);
432
+ }
433
+ if (variant.inheritedViewerLights.length === 0) {
434
+ throw new Error(
435
+ `No viewerLights for variant "${variant.id}" found. ` +
436
+ `Either none are defined or they are not initialized (are you operating on the appropriate living?).`
437
+ );
438
+ }
439
+ let viewerLight;
440
+ variant.inheritedViewerLights.forEach(_viewerLight => {
441
+ if (_viewerLight.name === viewerLightName) {
442
+ viewerLight = _viewerLight;
443
+ }
444
+ });
445
+ if (!viewerLight) {
446
+ throw new Error(`ViewerLight with name "${viewerLightName}" does not exist for variant "${variant.id}".`);
447
+ }
448
+ return viewerLight;
449
+ }
450
+
451
+ /**
452
+ * A proxy for directly getting a Node from an {@link Element} by its {@link DottedPath}s.
453
+ */
454
+ public async getNode(
455
+ elementDottedPath: DottedPathArgument,
456
+ nodeDottedPath: DottedPathArgument
457
+ ): Promise<TransformNode> {
458
+ const element = await this.getElement(elementDottedPath);
459
+ return element.getNode(nodeDottedPath);
460
+ }
461
+
462
+ /**
463
+ * A proxy for directly getting a Mesh from an {@link Element} by its {@link DottedPath}s.
464
+ */
465
+ public async getMesh(
466
+ elementDottedPath: DottedPathArgument,
467
+ meshDottedPath: DottedPathArgument
468
+ ): Promise<Mesh | null> {
469
+ const element = await this.getElement(elementDottedPath);
470
+ return element.getMesh(meshDottedPath);
471
+ }
472
+
473
+ /**
474
+ * Creates a living clone of this {@link Variant}. Will clone all parent {@link Variant}s in tree.
475
+ *
476
+ * @emit {@link Event.VARIANT_CREATED}
477
+ * @ignore
478
+ */
479
+ public async createLiving(variantInstance: VariantInstance, parameters?: ParameterBag): Promise<Variant> {
480
+ const parent = await this.parent?.createLiving(variantInstance);
481
+ const variant = new Variant(variantInstance, this.name, this._structureJson, this.viewer, parent);
482
+ parent?._children.set(variant.name, variant);
483
+ variant.assetContainer = this.assetContainer;
484
+ variant.parameterObservers = cloneDeep(this.parameterObservers);
485
+ await variant.createElements();
486
+ await variant.createViewerLights();
487
+ variant.addParameterObservers();
488
+ await variant.bootstrapParameters(parameters);
489
+ this.viewer.broadcastEvent(Event.VARIANT_CREATED, variant);
490
+ return variant;
491
+ }
492
+
493
+ /**
494
+ * Destroys this {@link Variant}, all parents and destroy the {@link Element}s.
495
+ */
496
+ public destroy(): Variant {
497
+ this.elements.forEach(element => element.destroy());
498
+ if (this.parent) {
499
+ this.parent.destroy();
500
+ }
501
+ this.broadcastEvent(Event.VARIANT_DESTROYED, this);
502
+ return this;
503
+ }
504
+
505
+ /**
506
+ * Places the given {@link ParameterBag} in the {@link Variant}'s parameters, replaces all patterns in the
507
+ * {@link StructureJson}, broadcasts all {@link ParameterObserver}s and delegates them to its {@link Element}s.
508
+ *
509
+ * @emit {@link Event.VARIANT_PARAMETER_COMMITTED}
510
+ */
511
+ public async commitParameters(parameters?: ParameterBag): Promise<Variant> {
512
+ parameters = merge({}, parameters);
513
+
514
+ // remember old parameter values for later comparison
515
+ const oldParameters = cloneDeep(this.inheritedParameters);
516
+
517
+ // replace patterns in given parameters
518
+ let _parameters = JSON.stringify(parameters);
519
+ for (const parameter in this.inheritedParameters) {
520
+ const value = this.inheritedParameters[parameter];
521
+ const search = new RegExp(`\\$\\{${parameter}\\}`, 'g');
522
+ _parameters = _parameters.replace(search, value.toString());
523
+ }
524
+ merge(parameters, JSON.parse(_parameters));
525
+
526
+ // merge inherited parameters and replaced given parameters
527
+ const mergedParameters = merge({}, this.inheritedParameters, parameters);
528
+
529
+ // replace patterns in structure parameters
530
+ const structureParameters = this._structureJson.parameters || {};
531
+ let _structureParameters = JSON.stringify(structureParameters);
532
+ for (const parameter in mergedParameters) {
533
+ const value = mergedParameters[parameter];
534
+ const search = new RegExp(`\\$\\{${parameter}\\}`, 'g');
535
+ _structureParameters = _structureParameters.replace(search, value.toString());
536
+ }
537
+ const replacedStructureParameters = JSON.parse(_structureParameters);
538
+
539
+ // calculate which replaced structure parameters have changed and should overload given parameters
540
+ const differentStructureParameters: ParameterBag = {};
541
+ for (const parameter in replacedStructureParameters) {
542
+ if (!isEqual(structureParameters[parameter], replacedStructureParameters[parameter])) {
543
+ differentStructureParameters[parameter] = replacedStructureParameters[parameter];
544
+ }
545
+ }
546
+
547
+ // merge replaced structure parameters and given inherited parameters to structure parameters
548
+ merge(this.parameters, mergedParameters, differentStructureParameters);
549
+
550
+ // inherited parameters are now the new parameters to process
551
+ const newParameters = this.inheritedParameters;
552
+
553
+ // replace all parameter patterns in structure json
554
+ let structure = JSON.stringify(this._structureJson);
555
+ for (const parameter in newParameters) {
556
+ const value = newParameters[parameter];
557
+ const search = new RegExp(`\\$\\{${parameter}\\}`, 'g');
558
+ structure = structure.replace(search, value.toString());
559
+ }
560
+ this.structureJson = JSON.parse(structure);
561
+
562
+ // handle parameter observers
563
+ let observerPromises: Promise<void | ParameterObserver>[] = [];
564
+ for (const parameter in newParameters) {
565
+ const oldParameterValue = oldParameters[parameter];
566
+ const newParameterValue = newParameters[parameter];
567
+ this.assertParameter(this.inheritedParameterDeclaration, parameter, newParameterValue);
568
+ if (oldParameterValue === newParameterValue && this.parametersInitialized) {
569
+ continue;
570
+ }
571
+ // parameter changed
572
+ const parameterObservers = mergeMaps(this._parameterObservers, this.parameterObservers);
573
+ if (parameterObservers.has(parameter)) {
574
+ const observers = parameterObservers.get(parameter)!;
575
+ observerPromises = concat(
576
+ observerPromises,
577
+ observers.map(observer => {
578
+ const observerResult = observer(this, oldParameterValue, newParameterValue);
579
+ return Promise.resolve(observerResult).then(() => {
580
+ if (this.parametersInitialized) {
581
+ this.broadcastEvent(
582
+ Event.VARIANT_PARAMETER_COMMITTED,
583
+ this,
584
+ parameter,
585
+ oldParameterValue,
586
+ newParameterValue
587
+ );
588
+ }
589
+ });
590
+ })
591
+ );
592
+ }
593
+ }
594
+ await Promise.all(observerPromises);
595
+
596
+ // broadcast that bag has been committed
597
+ this.broadcastEvent(Event.VARIANT_PARAMETER_BAG_COMMITTED, this, oldParameters, newParameters);
598
+
599
+ // commit parameters to elements
600
+ await this.commitParametersToElements(newParameters);
601
+
602
+ // commit parameters to lights
603
+ await this.commitParametersToViewerLights(newParameters);
604
+
605
+ // propagate parameters to parent
606
+ if (this.parent) {
607
+ await this.parent.commitParameters(this.parameters);
608
+ }
609
+
610
+ return this;
611
+ }
612
+
613
+ /**
614
+ * Adds an observer function for camera matrix changes for given `dottedPath` representing the {@link Element}
615
+ * and the `traceable`. The `observer` gets 2 parameters: the `AbstractMesh` and a `ClientRect` object.
616
+ */
617
+ public async addTraceableObserver(
618
+ dottedPath: DottedPathArgument,
619
+ observer: CallableFunction,
620
+ payload?: any
621
+ ): Promise<Element> {
622
+ const _dottedPath = DottedPath.create(dottedPath);
623
+ const traceableName = _dottedPath.popPart();
624
+ if (!traceableName) {
625
+ throw new Error(
626
+ `The dottedPath must consist of the element and the name of the defined corresponding ` +
627
+ `traceable ("${_dottedPath.path}" given).`
628
+ );
629
+ }
630
+ const element = await this.getElement(_dottedPath);
631
+ return element.addTraceableObserver(traceableName, observer, payload);
632
+ }
633
+
634
+ /**
635
+ * Loads {@link glTFUri} with assets, adds them to the {@link Variant}'s `assetContainer` and deactivates the meshes.
636
+ * (for further processing).
637
+ * @emits {@link Event.ASSET_LOADING_START}
638
+ * @emits {@link Event.ASSET_LOADING_END}
639
+ */
640
+ protected async loadAssets(): Promise<Variant> {
641
+ this.broadcastEvent(Event.ASSET_LOADING_START, this);
642
+ return new Promise<Variant>(resolve => {
643
+ if (!this.structureJson) {
644
+ this.broadcastEvent(Event.ASSET_LOADING_END, this);
645
+ return resolve(this);
646
+ }
647
+ if (!this.glTF) {
648
+ this.broadcastEvent(Event.ASSET_LOADING_END, this);
649
+ return resolve(this);
650
+ }
651
+ SceneLoader.LoadAssetContainer(
652
+ this.glTF.rootUrl,
653
+ this.glTF.fileName,
654
+ this.viewer.scene,
655
+ // on success
656
+ container => {
657
+ this.assetContainer = container;
658
+ const nodes = this.assetContainer.getNodes().filter(n => n instanceof TransformNode) as TransformNode[];
659
+ reportDuplicateNodeNames(
660
+ intersectingNodeNames(nodes, this.viewer.scene.getNodes(), n => n instanceof TransformNode)
661
+ );
662
+ nodes.forEach(node => {
663
+ deactivateTransformNode(node, false);
664
+ injectNodeMetadata(node, { dottedPath: getDottedPathForNode(node), originalName: node.name }, false);
665
+ });
666
+ this.assetContainer.lights.forEach(light => {
667
+ light.setEnabled(false);
668
+ injectNodeMetadata(light, { dottedPath: getDottedPathForNode(light), originalName: light.name }, false);
669
+ this.viewer.scene.addLight(light);
670
+ });
671
+ this.assetContainer.cameras.forEach(camera => {
672
+ camera.setEnabled(false);
673
+ injectNodeMetadata(camera, { dottedPath: getDottedPathForNode(camera), originalName: camera.name }, false);
674
+ this.viewer.scene.addCamera(camera);
675
+ });
676
+ this.assetContainer.materials.forEach(material => this.viewer.scene.materials.push(material));
677
+ this.broadcastEvent(Event.ASSET_LOADING_END, this);
678
+ resolve(this);
679
+ },
680
+ // on progress
681
+ undefined,
682
+ // on error
683
+ reason => {
684
+ this.broadcastEvent(Event.ASSET_LOADING_END, this);
685
+ throw new Error(`Error loading assets for variant "${this.id}": ${reason}.`);
686
+ }
687
+ );
688
+ });
689
+ }
690
+
691
+ /**
692
+ * Commits given parameters to all {@link Element}s.
693
+ */
694
+ protected async commitParametersToElements(parameters: ParameterBag) {
695
+ await Promise.all(
696
+ this.elements.map(element => this.commitParametersToVariantParameterizable(parameters, element, 'elements'))
697
+ );
698
+ }
699
+
700
+ /**
701
+ * Commits given parameters to all {@link ViewerLight}s.
702
+ */
703
+ protected async commitParametersToViewerLights(parameters: ParameterBag) {
704
+ await Promise.all(
705
+ this.viewerLights.map(viewerLight =>
706
+ this.commitParametersToVariantParameterizable(parameters, viewerLight, 'lights')
707
+ )
708
+ );
709
+ }
710
+
711
+ /**
712
+ * Commits given parameters to a {@link VariantParameterizable} and updates the according definition with given
713
+ * key in the {@link StructureJson}. The `definitionKey` "elements" for example will update the definition in
714
+ * `this.structureJson.elements`.
715
+ */
716
+ protected async commitParametersToVariantParameterizable(
717
+ parameters: ParameterBag,
718
+ parameterizable: VariantParameterizable,
719
+ definitionKey: string
720
+ ): Promise<ParameterObservable> {
721
+ const initialDefinition = get(this._structureJson, definitionKey)[parameterizable.name];
722
+ let initialDefinitionStr = JSON.stringify(initialDefinition);
723
+ const _parameters: ParameterBag = {};
724
+ for (const parameter in parameters) {
725
+ const dpp = DottedPath.create(parameter);
726
+ if (dpp.shiftPart() !== parameterizable.name) {
727
+ continue;
728
+ }
729
+ // we got a parameterizable ("element") parameter
730
+ let parameterValue = parameters[parameter];
731
+ const parameterizableParameter = dpp.path;
732
+ // If the variant is explicitly hidden, we must not override the visibility with element parameters. We need
733
+ // an exception for visibility to avoid overloading already applied element parameters with element parameters
734
+ // defined in the variant spec ("dotted parameters").
735
+ // @see https://github.com/Combeenation/3d-viewer/issues/44
736
+ if (parameterizableParameter === Parameter.VISIBLE && parameters[Parameter.VISIBLE] === false) {
737
+ parameterValue = false;
738
+ }
739
+ _parameters[parameterizableParameter] = parameterValue;
740
+ const search = new RegExp(`\\$\\{${parameterizableParameter}\\}`, 'g');
741
+ initialDefinitionStr = initialDefinitionStr.replace(search, parameterValue.toString());
742
+ }
743
+ const definition = get(this.structureJson, definitionKey);
744
+ definition[this.name] = JSON.parse(initialDefinitionStr);
745
+ set(this.structureJson, definitionKey, definition);
746
+ return await parameterizable.commitParameters(_parameters);
747
+ }
748
+
749
+ /**
750
+ * Commits given {@link Parameter} to the {@link Variant}'s {@link Element}s.
751
+ */
752
+ protected async commitParameterToElements(parameter: string, value: ParameterValue): Promise<Variant> {
753
+ const promises = [];
754
+ for (const element of this.elements) {
755
+ const paramShowsVariant = Parameter.VISIBLE === parameter && value;
756
+
757
+ // Fixes https://combeenation.youtrack.cloud/issue/CB-7773
758
+ // Don't enable/show the variants element if it is explicitly hidden via its element parameters.
759
+ // E.g. via spec:
760
+ // ```
761
+ // variants: {
762
+ // theVariant: {
763
+ // elements: {
764
+ // Main: ['root.main'],
765
+ // Secondary: ['root.secondary'],
766
+ // },
767
+ // parameters: {
768
+ // // !!! The element `Secondary` should **not** be enabled when its containing variant is enabled !!!
769
+ // 'Secondary.visible': false,
770
+ // }
771
+ // }
772
+ // }
773
+ // ```
774
+ const elVisibleParamPath = DottedPath.create([element.name, Parameter.VISIBLE]).toString();
775
+ const elVisibleParamValue = this.inheritedParameters[elVisibleParamPath];
776
+ const elVisibleParamValueParsed = elVisibleParamValue && Parameter.parseBoolean(elVisibleParamValue);
777
+ const elIsHiddenViaParams = elVisibleParamValueParsed === false;
778
+ if (paramShowsVariant && elIsHiddenViaParams) continue;
779
+
780
+ // Fixes https://combeenation.youtrack.cloud/issue/CB-7809
781
+ // Apply element material before showing the element to prevent loading of the elements "original" material which
782
+ // is never shown when "overwritten" by elements material param.
783
+ const elMaterialParamPath = DottedPath.create([element.name, Parameter.MATERIAL]).toString();
784
+ const elMaterialParamValue = this.inheritedParameters[elMaterialParamPath];
785
+ if (paramShowsVariant && elMaterialParamValue) {
786
+ await element.commitParameter(Parameter.MATERIAL, elMaterialParamValue);
787
+ }
788
+
789
+ promises.push(element.commitParameter(parameter, value));
790
+ }
791
+ await Promise.all(promises);
792
+ return this;
793
+ }
794
+
795
+ /**
796
+ * Commits given {@link Parameter} to the {@link Variant}'s {@link Element}s.
797
+ */
798
+ protected async commitParameterToViewerLights(parameter: string, value: ParameterValue): Promise<Variant> {
799
+ const promises = [];
800
+ for (const viewerLight of this.viewerLights) {
801
+ promises.push(viewerLight.commitParameter(parameter, value));
802
+ }
803
+ await Promise.all(promises);
804
+ return this;
805
+ }
806
+
807
+ /**
808
+ * Adds the default {@link ParameterObserver}s which are called every time {@link commitParameters} is called.
809
+ */
810
+ protected addParameterObservers(): Variant {
811
+ this._parameterObservers.set(Parameter.VISIBLE, [
812
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
813
+ await variant.commitParameterToElements(Parameter.VISIBLE, newValue);
814
+ await variant.commitParameterToViewerLights(Parameter.VISIBLE, newValue);
815
+ },
816
+ ]);
817
+ this._parameterObservers.set(Parameter.SCALING, [
818
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
819
+ await variant.commitParameterToElements(Parameter.SCALING, newValue);
820
+ await variant.commitParameterToViewerLights(Parameter.SCALING, newValue);
821
+ },
822
+ ]);
823
+ this._parameterObservers.set(Parameter.MATERIAL, [
824
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
825
+ await variant.commitParameterToElements(Parameter.MATERIAL, newValue);
826
+ },
827
+ ]);
828
+ this._parameterObservers.set(Parameter.MATERIAL_COLOR, [
829
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
830
+ await variant.commitParameterToElements(Parameter.MATERIAL_COLOR, newValue);
831
+ },
832
+ ]);
833
+ this._parameterObservers.set(Parameter.MATERIAL_METALLNESS, [
834
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
835
+ await variant.commitParameterToElements(Parameter.MATERIAL_METALLNESS, newValue);
836
+ },
837
+ ]);
838
+ this._parameterObservers.set(Parameter.MATERIAL_ROUGHNESS, [
839
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
840
+ await variant.commitParameterToElements(Parameter.MATERIAL_ROUGHNESS, newValue);
841
+ },
842
+ ]);
843
+ this._parameterObservers.set(Parameter.HIGHLIGHT_COLOR, [
844
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
845
+ await variant.commitParameterToElements(Parameter.HIGHLIGHT_COLOR, newValue);
846
+ },
847
+ ]);
848
+ this._parameterObservers.set(Parameter.HIGHLIGHTED, [
849
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
850
+ await variant.commitParameterToElements(Parameter.HIGHLIGHTED, newValue);
851
+ },
852
+ ]);
853
+ this._parameterObservers.set(Parameter.POSITION, [
854
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
855
+ await variant.commitParameterToElements(Parameter.POSITION, newValue);
856
+ await variant.commitParameterToViewerLights(Parameter.POSITION, newValue);
857
+ },
858
+ ]);
859
+ this._parameterObservers.set(Parameter.ROTATION, [
860
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
861
+ await variant.commitParameterToElements(Parameter.ROTATION, newValue);
862
+ await variant.commitParameterToViewerLights(Parameter.ROTATION, newValue);
863
+ },
864
+ ]);
865
+ this._parameterObservers.set(Parameter.CAST_SHADOW, [
866
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
867
+ await variant.commitParameterToElements(Parameter.CAST_SHADOW, newValue);
868
+ },
869
+ ]);
870
+ this._parameterObservers.set(Parameter.CAST_SHADOW_FROM_LIGHTS, [
871
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
872
+ await variant.commitParameterToElements(Parameter.CAST_SHADOW_FROM_LIGHTS, newValue);
873
+ },
874
+ ]);
875
+ this._parameterObservers.set(Parameter.RECEIVE_SHADOWS, [
876
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
877
+ await variant.commitParameterToElements(Parameter.RECEIVE_SHADOWS, newValue);
878
+ },
879
+ ]);
880
+ return this;
881
+ }
882
+
883
+ /**
884
+ * Creates {@link Element}s and clones nodes into them.
885
+ */
886
+ protected async createElements(forInstance?: string): Promise<Variant> {
887
+ this.createElementDefinitionsIfNotExist();
888
+ for (const name in this.structureJson.elements || {}) {
889
+ this.elements.push(await Element.create(this, name));
890
+ }
891
+ // inject node meta to all inherited elements
892
+ // we do this to inject the deepest and most concrete variant information to all cloned nodes in the tree
893
+ this.inheritedElements.forEach(element =>
894
+ element.nodes.forEach(node => injectNodeMetadata(node, { variant: this, variantParameterizable: element }))
895
+ );
896
+ return this;
897
+ }
898
+
899
+ /**
900
+ * Creates {@link ViewerLight}s.
901
+ */
902
+ protected async createViewerLights(): Promise<Variant> {
903
+ for (const name in this.structureJson.lights || {}) {
904
+ this.viewerLights.push(await ViewerLight.create(this, name));
905
+ }
906
+ this.inheritedViewerLights.forEach(viewerLight => {
907
+ injectNodeMetadata(viewerLight.light, { variant: this, variantParameterizable: viewerLight });
908
+ });
909
+ return this;
910
+ }
911
+
912
+ /**
913
+ * Bootstrapping for parameters. It sets the `parametersInitialized` to true for all ancestors.
914
+ */
915
+ protected async bootstrapParameters(parameters?: ParameterBag): Promise<Variant> {
916
+ await this.commitParameters(merge(cloneDeep(this.parameters), parameters));
917
+ concat(this.ancestors, this).forEach(ancestor => (ancestor.parametersInitialized = true));
918
+ return this;
919
+ }
920
+
921
+ /**
922
+ * Ensures there is at least one "Main" {@link Element} for the {@link Variant} with all "root nodes" defined in path.
923
+ */
924
+ protected createElementDefinitionsIfNotExist() {
925
+ if (this._structureJson.elements || this.inheritedNodes.length === 0) {
926
+ return;
927
+ }
928
+ this._structureJson.elements = {
929
+ Main: { paths: { include: this.inheritedNodes.map(node => node.metadata.dottedPath.path) } },
930
+ };
931
+ this.structureJson.elements = cloneDeep(this._structureJson.elements);
932
+ }
933
+ }