@combeenation/3d-viewer 7.1.0 → 7.1.2

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