@combeenation/3d-viewer 5.1.2 → 5.2.0-alpha4

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 (221) 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 -1
  4. package/dist/lib-cjs/api/classes/dottedPath.d.ts +79 -79
  5. package/dist/lib-cjs/api/classes/dottedPath.js +166 -187
  6. package/dist/lib-cjs/api/classes/dottedPath.js.map +1 -1
  7. package/dist/lib-cjs/api/classes/element.d.ts +149 -149
  8. package/dist/lib-cjs/api/classes/element.js +668 -823
  9. package/dist/lib-cjs/api/classes/element.js.map +1 -1
  10. package/dist/lib-cjs/api/classes/event.d.ts +326 -326
  11. package/dist/lib-cjs/api/classes/event.js +349 -371
  12. package/dist/lib-cjs/api/classes/event.js.map +1 -1
  13. package/dist/lib-cjs/api/classes/eventBroadcaster.d.ts +26 -26
  14. package/dist/lib-cjs/api/classes/eventBroadcaster.js +49 -53
  15. package/dist/lib-cjs/api/classes/eventBroadcaster.js.map +1 -1
  16. package/dist/lib-cjs/api/classes/parameter.d.ts +336 -336
  17. package/dist/lib-cjs/api/classes/parameter.js +461 -471
  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 +97 -101
  21. package/dist/lib-cjs/api/classes/parameterObservable.js.map +1 -1
  22. package/dist/lib-cjs/api/classes/parameterizable.d.ts +15 -15
  23. package/dist/lib-cjs/api/classes/parameterizable.js +102 -149
  24. package/dist/lib-cjs/api/classes/parameterizable.js.map +1 -1
  25. package/dist/lib-cjs/api/classes/placementAnimation.d.ts +45 -44
  26. package/dist/lib-cjs/api/classes/placementAnimation.js +175 -163
  27. package/dist/lib-cjs/api/classes/placementAnimation.js.map +1 -1
  28. package/dist/lib-cjs/api/classes/variant.d.ts +234 -234
  29. package/dist/lib-cjs/api/classes/variant.js +836 -1203
  30. package/dist/lib-cjs/api/classes/variant.js.map +1 -1
  31. package/dist/lib-cjs/api/classes/variantInstance.d.ts +45 -45
  32. package/dist/lib-cjs/api/classes/variantInstance.js +101 -108
  33. package/dist/lib-cjs/api/classes/variantInstance.js.map +1 -1
  34. package/dist/lib-cjs/api/classes/variantParameterizable.d.ts +17 -17
  35. package/dist/lib-cjs/api/classes/variantParameterizable.js +88 -99
  36. package/dist/lib-cjs/api/classes/variantParameterizable.js.map +1 -1
  37. package/dist/lib-cjs/api/classes/viewer.d.ts +187 -184
  38. package/dist/lib-cjs/api/classes/viewer.js +593 -731
  39. package/dist/lib-cjs/api/classes/viewer.js.map +1 -1
  40. package/dist/lib-cjs/api/classes/viewerLight.d.ts +66 -66
  41. package/dist/lib-cjs/api/classes/viewerLight.js +343 -392
  42. package/dist/lib-cjs/api/classes/viewerLight.js.map +1 -1
  43. package/dist/lib-cjs/api/internal/lensRendering.d.ts +8 -8
  44. package/dist/lib-cjs/api/internal/lensRendering.js +11 -11
  45. package/dist/lib-cjs/api/internal/lensRendering.js.map +1 -1
  46. package/dist/lib-cjs/api/internal/sceneSetup.d.ts +13 -13
  47. package/dist/lib-cjs/api/internal/sceneSetup.js +225 -238
  48. package/dist/lib-cjs/api/internal/sceneSetup.js.map +1 -1
  49. package/dist/lib-cjs/api/manager/animationManager.d.ts +30 -29
  50. package/dist/lib-cjs/api/manager/animationManager.js +126 -130
  51. package/dist/lib-cjs/api/manager/animationManager.js.map +1 -1
  52. package/dist/lib-cjs/api/manager/gltfExportManager.d.ts +65 -65
  53. package/dist/lib-cjs/api/manager/gltfExportManager.js +196 -223
  54. package/dist/lib-cjs/api/manager/gltfExportManager.js.map +1 -1
  55. package/dist/lib-cjs/api/manager/sceneManager.d.ts +31 -31
  56. package/dist/lib-cjs/api/manager/sceneManager.js +127 -152
  57. package/dist/lib-cjs/api/manager/sceneManager.js.map +1 -1
  58. package/dist/lib-cjs/api/manager/variantInstanceManager.d.ts +92 -92
  59. package/dist/lib-cjs/api/manager/variantInstanceManager.js +260 -335
  60. package/dist/lib-cjs/api/manager/variantInstanceManager.js.map +1 -1
  61. package/dist/lib-cjs/api/store/specStorage.d.ts +24 -24
  62. package/dist/lib-cjs/api/store/specStorage.js +50 -51
  63. package/dist/lib-cjs/api/store/specStorage.js.map +1 -1
  64. package/dist/lib-cjs/api/util/babylonHelper.d.ts +174 -174
  65. package/dist/lib-cjs/api/util/babylonHelper.js +591 -611
  66. package/dist/lib-cjs/api/util/babylonHelper.js.map +1 -1
  67. package/dist/lib-cjs/api/util/globalTypes.d.ts +366 -366
  68. package/dist/lib-cjs/api/util/globalTypes.js +1 -1
  69. package/dist/lib-cjs/api/util/resourceHelper.d.ts +58 -58
  70. package/dist/lib-cjs/api/util/resourceHelper.js +201 -257
  71. package/dist/lib-cjs/api/util/resourceHelper.js.map +1 -1
  72. package/dist/lib-cjs/api/util/sceneLoaderHelper.d.ts +35 -35
  73. package/dist/lib-cjs/api/util/sceneLoaderHelper.js +141 -140
  74. package/dist/lib-cjs/api/util/sceneLoaderHelper.js.map +1 -1
  75. package/dist/lib-cjs/api/util/stringHelper.d.ts +9 -9
  76. package/dist/lib-cjs/api/util/stringHelper.js +23 -25
  77. package/dist/lib-cjs/api/util/stringHelper.js.map +1 -1
  78. package/dist/lib-cjs/api/util/structureHelper.d.ts +9 -9
  79. package/dist/lib-cjs/api/util/structureHelper.js +48 -48
  80. package/dist/lib-cjs/api/util/structureHelper.js.map +1 -1
  81. package/dist/lib-cjs/buildinfo.json +3 -3
  82. package/dist/lib-cjs/index.d.ts +51 -49
  83. package/dist/lib-cjs/index.js +110 -89
  84. package/dist/lib-cjs/index.js.map +1 -1
  85. package/dist/lib-es6/api/classes/animationInterface.d.ts +8 -8
  86. package/dist/lib-es6/api/classes/animationInterface.js +1 -1
  87. package/dist/lib-es6/api/classes/dottedPath.d.ts +79 -79
  88. package/dist/lib-es6/api/classes/dottedPath.js +162 -184
  89. package/dist/lib-es6/api/classes/dottedPath.js.map +1 -1
  90. package/dist/lib-es6/api/classes/element.d.ts +149 -149
  91. package/dist/lib-es6/api/classes/element.js +664 -820
  92. package/dist/lib-es6/api/classes/element.js.map +1 -1
  93. package/dist/lib-es6/api/classes/event.d.ts +326 -326
  94. package/dist/lib-es6/api/classes/event.js +345 -368
  95. package/dist/lib-es6/api/classes/event.js.map +1 -1
  96. package/dist/lib-es6/api/classes/eventBroadcaster.d.ts +26 -26
  97. package/dist/lib-es6/api/classes/eventBroadcaster.js +42 -50
  98. package/dist/lib-es6/api/classes/eventBroadcaster.js.map +1 -1
  99. package/dist/lib-es6/api/classes/parameter.d.ts +336 -336
  100. package/dist/lib-es6/api/classes/parameter.js +457 -468
  101. package/dist/lib-es6/api/classes/parameter.js.map +1 -1
  102. package/dist/lib-es6/api/classes/parameterObservable.d.ts +36 -36
  103. package/dist/lib-es6/api/classes/parameterObservable.js +93 -98
  104. package/dist/lib-es6/api/classes/parameterObservable.js.map +1 -1
  105. package/dist/lib-es6/api/classes/parameterizable.d.ts +15 -15
  106. package/dist/lib-es6/api/classes/parameterizable.js +98 -146
  107. package/dist/lib-es6/api/classes/parameterizable.js.map +1 -1
  108. package/dist/lib-es6/api/classes/placementAnimation.d.ts +45 -44
  109. package/dist/lib-es6/api/classes/placementAnimation.js +171 -160
  110. package/dist/lib-es6/api/classes/placementAnimation.js.map +1 -1
  111. package/dist/lib-es6/api/classes/variant.d.ts +234 -234
  112. package/dist/lib-es6/api/classes/variant.js +832 -1198
  113. package/dist/lib-es6/api/classes/variant.js.map +1 -1
  114. package/dist/lib-es6/api/classes/variantInstance.d.ts +45 -45
  115. package/dist/lib-es6/api/classes/variantInstance.js +97 -105
  116. package/dist/lib-es6/api/classes/variantInstance.js.map +1 -1
  117. package/dist/lib-es6/api/classes/variantParameterizable.d.ts +17 -17
  118. package/dist/lib-es6/api/classes/variantParameterizable.js +84 -96
  119. package/dist/lib-es6/api/classes/variantParameterizable.js.map +1 -1
  120. package/dist/lib-es6/api/classes/viewer.d.ts +187 -184
  121. package/dist/lib-es6/api/classes/viewer.js +586 -728
  122. package/dist/lib-es6/api/classes/viewer.js.map +1 -1
  123. package/dist/lib-es6/api/classes/viewerLight.d.ts +66 -66
  124. package/dist/lib-es6/api/classes/viewerLight.js +316 -389
  125. package/dist/lib-es6/api/classes/viewerLight.js.map +1 -1
  126. package/dist/lib-es6/api/internal/lensRendering.d.ts +8 -8
  127. package/dist/lib-es6/api/internal/lensRendering.js +8 -8
  128. package/dist/lib-es6/api/internal/lensRendering.js.map +1 -1
  129. package/dist/lib-es6/api/internal/sceneSetup.d.ts +13 -13
  130. package/dist/lib-es6/api/internal/sceneSetup.js +197 -233
  131. package/dist/lib-es6/api/internal/sceneSetup.js.map +1 -1
  132. package/dist/lib-es6/api/manager/animationManager.d.ts +30 -29
  133. package/dist/lib-es6/api/manager/animationManager.js +122 -127
  134. package/dist/lib-es6/api/manager/animationManager.js.map +1 -1
  135. package/dist/lib-es6/api/manager/gltfExportManager.d.ts +65 -65
  136. package/dist/lib-es6/api/manager/gltfExportManager.js +192 -220
  137. package/dist/lib-es6/api/manager/gltfExportManager.js.map +1 -1
  138. package/dist/lib-es6/api/manager/sceneManager.d.ts +31 -31
  139. package/dist/lib-es6/api/manager/sceneManager.js +123 -149
  140. package/dist/lib-es6/api/manager/sceneManager.js.map +1 -1
  141. package/dist/lib-es6/api/manager/variantInstanceManager.d.ts +92 -92
  142. package/dist/lib-es6/api/manager/variantInstanceManager.js +256 -332
  143. package/dist/lib-es6/api/manager/variantInstanceManager.js.map +1 -1
  144. package/dist/lib-es6/api/store/specStorage.d.ts +24 -24
  145. package/dist/lib-es6/api/store/specStorage.js +46 -48
  146. package/dist/lib-es6/api/store/specStorage.js.map +1 -1
  147. package/dist/lib-es6/api/util/babylonHelper.d.ts +174 -174
  148. package/dist/lib-es6/api/util/babylonHelper.js +561 -581
  149. package/dist/lib-es6/api/util/babylonHelper.js.map +1 -1
  150. package/dist/lib-es6/api/util/globalTypes.d.ts +366 -366
  151. package/dist/lib-es6/api/util/globalTypes.js +1 -1
  152. package/dist/lib-es6/api/util/resourceHelper.d.ts +58 -58
  153. package/dist/lib-es6/api/util/resourceHelper.js +191 -247
  154. package/dist/lib-es6/api/util/resourceHelper.js.map +1 -1
  155. package/dist/lib-es6/api/util/sceneLoaderHelper.d.ts +35 -35
  156. package/dist/lib-es6/api/util/sceneLoaderHelper.js +131 -133
  157. package/dist/lib-es6/api/util/sceneLoaderHelper.js.map +1 -1
  158. package/dist/lib-es6/api/util/stringHelper.d.ts +9 -9
  159. package/dist/lib-es6/api/util/stringHelper.js +19 -21
  160. package/dist/lib-es6/api/util/stringHelper.js.map +1 -1
  161. package/dist/lib-es6/api/util/structureHelper.d.ts +9 -9
  162. package/dist/lib-es6/api/util/structureHelper.js +45 -45
  163. package/dist/lib-es6/api/util/structureHelper.js.map +1 -1
  164. package/dist/lib-es6/buildinfo.json +3 -3
  165. package/dist/lib-es6/index.d.ts +51 -49
  166. package/dist/lib-es6/index.js +48 -50
  167. package/dist/lib-es6/index.js.map +1 -1
  168. package/dist/lib-full/lens-rendering.js +2 -0
  169. package/dist/lib-full/lens-rendering.js.map +1 -0
  170. package/dist/lib-full/main.js +3 -0
  171. package/dist/lib-full/main.js.LICENSE.txt +9 -0
  172. package/dist/lib-full/main.js.map +1 -0
  173. package/package.json +76 -88
  174. package/src/api/classes/animationInterface.ts +10 -10
  175. package/src/api/classes/dottedPath.ts +181 -181
  176. package/src/api/classes/element.ts +716 -716
  177. package/src/api/classes/event.ts +367 -367
  178. package/src/api/classes/eventBroadcaster.ts +52 -52
  179. package/src/api/classes/parameter.ts +494 -494
  180. package/src/api/classes/parameterObservable.ts +100 -100
  181. package/src/api/classes/parameterizable.ts +87 -87
  182. package/src/api/classes/placementAnimation.ts +161 -160
  183. package/src/api/classes/variant.ts +904 -905
  184. package/src/api/classes/variantInstance.ts +97 -97
  185. package/src/api/classes/variantParameterizable.ts +85 -85
  186. package/src/api/classes/viewer.ts +669 -668
  187. package/src/api/classes/viewerLight.ts +334 -334
  188. package/src/api/internal/debugViewer.ts +90 -90
  189. package/src/api/internal/lensRendering.ts +9 -10
  190. package/src/api/internal/sceneSetup.ts +204 -204
  191. package/src/api/manager/animationManager.ts +143 -142
  192. package/src/api/manager/gltfExportManager.ts +191 -191
  193. package/src/api/manager/sceneManager.ts +127 -127
  194. package/src/api/manager/variantInstanceManager.ts +265 -265
  195. package/src/api/store/specStorage.ts +51 -51
  196. package/src/api/util/babylonHelper.ts +663 -663
  197. package/src/api/util/globalTypes.ts +413 -413
  198. package/src/api/util/resourceHelper.ts +189 -189
  199. package/src/api/util/sceneLoaderHelper.ts +148 -147
  200. package/src/api/util/stringHelper.ts +23 -23
  201. package/src/api/util/structureHelper.ts +49 -49
  202. package/src/buildinfo.json +3 -3
  203. package/src/dev.ts +61 -64
  204. package/src/index.ts +96 -94
  205. package/src/types.d.ts +28 -28
  206. package/dist/lib-cjs/api/classes/elementParameterizable.d.ts +0 -14
  207. package/dist/lib-cjs/api/classes/elementParameterizable.js +0 -135
  208. package/dist/lib-cjs/api/classes/elementParameterizable.js.map +0 -1
  209. package/dist/lib-cjs/api/internal/debugViewer.d.ts +0 -13
  210. package/dist/lib-cjs/api/internal/debugViewer.js +0 -87
  211. package/dist/lib-cjs/api/internal/debugViewer.js.map +0 -1
  212. package/dist/lib-es6/api/internal/debugViewer.d.ts +0 -13
  213. package/dist/lib-es6/api/internal/debugViewer.js +0 -84
  214. package/dist/lib-es6/api/internal/debugViewer.js.map +0 -1
  215. package/dist/webpack-stats.json +0 -0
  216. package/src/commonjs.tsconfig.json +0 -10
  217. package/src/declaration.tsconfig.json +0 -8
  218. package/src/es6.tsconfig.json +0 -10
  219. package/src/pagesconfig.json +0 -81
  220. package/src/tsconfig.json +0 -33
  221. package/src/tsconfig.types.json +0 -9
@@ -1,716 +1,716 @@
1
- import { PBRMaterial } from '@babylonjs/core/Materials/PBR/pbrMaterial';
2
- import { HighlightLayer } from '@babylonjs/core/Layers/highlightLayer';
3
- import { Light } from '@babylonjs/core/Lights/light';
4
- import { ShadowGenerator } from '@babylonjs/core/Lights/Shadows/shadowGenerator';
5
- import { Material } from '@babylonjs/core/Materials/material';
6
- import { DynamicTexture } from '@babylonjs/core/Materials/Textures/dynamicTexture';
7
- import { Color3 } from '@babylonjs/core/Maths/math.color';
8
- import { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh';
9
- import { InstancedMesh } from '@babylonjs/core/Meshes/instancedMesh';
10
- import { Mesh } from '@babylonjs/core/Meshes/mesh';
11
- import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
12
- import { has, isArray, isNumber, isPlainObject, merge, union } from 'lodash-es';
13
- import {
14
- activateTransformNode as activate,
15
- addToHighlightLayer,
16
- addToShadowGenerator,
17
- assertTransformNode,
18
- cloneTransformNode,
19
- cloneTransformNodeMaterial,
20
- deactivateTransformNode as deactivate,
21
- getClientRectFromMesh,
22
- injectNodeMetadata,
23
- mapToDottedNodes,
24
- removeFromHighlightLayer,
25
- removeFromShadowGenerator,
26
- setMaterial,
27
- setMaterialColor,
28
- setMaterialMetallness,
29
- setMaterialRoughness,
30
- setMaterialTexture,
31
- setReceiveShadows,
32
- transformTransformNode,
33
- } from '../util/babylonHelper';
34
- import { createImageFromImgSrc, createImageFromSvg } from '../util/resourceHelper';
35
- import { VariantParameterizable } from './../classes/variantParameterizable';
36
- import { DottedPath } from './dottedPath';
37
- import { Parameter } from './parameter';
38
- import { Variant } from './variant';
39
- import { addMissingMaterialObserver } from '../util/sceneLoaderHelper';
40
-
41
- /**
42
- * An {@link Element} of a {@link Variant}. Acts as a container for diverse definitions. Lives only in the context of a
43
- * {@link Variant}.
44
- *
45
- * When used in typings, refer to via its alias {@link VariantElement} to prevent name clashes with the web APIs
46
- * [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) class
47
- */
48
- export class Element extends VariantParameterizable {
49
- public readonly nodes: TransformNode[] = [];
50
-
51
- protected readonly _dottedNodes: Map<DottedPath, TransformNode> = new Map();
52
-
53
- protected _highlightLayer?: HighlightLayer;
54
-
55
- /**
56
- * Constructor.
57
- */
58
- protected constructor(public readonly variant: Variant, public readonly name: string) {
59
- super(variant, name);
60
- if (process.env.NODE_ENV?.toLowerCase().includes('dev')) {
61
- this.assertPathDefinitions();
62
- }
63
- const nodes = this.variant.inheritedNodes.map(node => cloneTransformNode(node, this.filterNode.bind(this)));
64
- this.nodes = nodes.filter(node => !!node) as TransformNode[];
65
- this._dottedNodes = mapToDottedNodes<TransformNode>(this.nodes, node => node instanceof TransformNode);
66
- this.addMissingMaterialObservers();
67
- this.addParameterObservers();
68
- }
69
-
70
- /**
71
- * Creates an {@link Element} with given name.
72
- */
73
- public static async create(variant: Variant, name: string): Promise<Element> {
74
- return new Element(variant, name);
75
- }
76
-
77
- /**
78
- * The {@link DottedPath} in the built tree of {@link Element}s.
79
- * E.g. "_.top-1.sub-2.sub-sub-3.el-1"
80
- */
81
- get dottedPath(): DottedPath {
82
- return DottedPath.create(this.variant.dottedPath).addPart(this.name);
83
- }
84
-
85
- /**
86
- * The id representing a {@link DottedPath}.
87
- */
88
- get id(): string {
89
- const dottedPath = DottedPath.create(this.dottedPath);
90
- dottedPath.shiftPart(); // remove root
91
- return dottedPath.path;
92
- }
93
-
94
- /**
95
- * The {@link ElementDefinition} of the {@link Element}.
96
- */
97
- get definition(): ElementDefinition {
98
- const definition = this.variant.structureJson.elements![this.name];
99
- if (isArray(definition)) {
100
- return {
101
- paths: {
102
- include: definition,
103
- },
104
- } as ElementDefinition;
105
- }
106
- return definition as ElementDefinition;
107
- }
108
-
109
- /**
110
- * The {@link PathDefinitions} of the {@link Element}.
111
- */
112
- get pathDefinitions(): PathDefinitions {
113
- return this.definition.paths;
114
- }
115
-
116
- /**
117
- * The {@link TraceableDefinitions} of the {@link Element}.
118
- */
119
- get traceableDefinitions(): TraceableDefinitions {
120
- return this.definition.traceables || {};
121
- }
122
-
123
- /**
124
- * The {@link PaintableDefinition} of the {@link Element}.
125
- */
126
- get paintableDefinitions(): PaintableDefinitions {
127
- return this.definition.paintables || {};
128
- }
129
-
130
- /**
131
- * The inherited {@link ParameterBag}.
132
- * Merges the {@link Variant}'s parameters and those from the {@link Element}.
133
- */
134
- get inheritedParameters(): ParameterBag {
135
- return merge({}, this.variant.inheritedParameters, this.parameters);
136
- }
137
-
138
- /**
139
- * The actual {@link Mesh}es that make up this {@link Element}.
140
- * Handy for e.g. creating a bounding box around an entire element.
141
- */
142
- get meshesFlat(): Mesh[] {
143
- const flatMeshes = this.nodes.reduce((accFlatMeshes, curNode) => {
144
- const currMeshes = curNode.getChildMeshes(false, n => n instanceof Mesh) as Mesh[];
145
- return [...accFlatMeshes, ...currMeshes];
146
- }, [] as Mesh[]);
147
- return flatMeshes;
148
- }
149
-
150
- /**
151
- * The actual {@link AbstractMesh}es that make up this {@link Element}.
152
- * I.e. (real) Meshes as well as InstancedMeshes.
153
- */
154
- get abstractMeshesFlat(): AbstractMesh[] {
155
- const allAbstractMeshes = this.nodes.reduce((acc, currNode) => {
156
- const currAbstractMeshes = currNode.getChildMeshes(false, n => n instanceof AbstractMesh);
157
- if (currNode instanceof AbstractMesh) {
158
- currAbstractMeshes.unshift(currNode);
159
- }
160
- return [...acc, ...currAbstractMeshes];
161
- }, [] as AbstractMesh[]); // initial accumulator value
162
- return allAbstractMeshes;
163
- }
164
-
165
- /**
166
- * The meshes of this {@link Element}.
167
- */
168
- get meshes(): Mesh[] {
169
- return this.nodes.filter(node => node instanceof Mesh) as Mesh[];
170
- }
171
-
172
- /**
173
- * @protected
174
- */
175
- set highlightLayer(layer: HighlightLayer | undefined) {
176
- this._highlightLayer = layer;
177
- }
178
-
179
- get highlightLayer(): HighlightLayer | undefined {
180
- return this._highlightLayer;
181
- }
182
-
183
- /**
184
- * Destroys this {@link Element} and dispose all nodes.
185
- */
186
- public destroy(): Element {
187
- this.nodes.forEach(node => {
188
- node.dispose();
189
- });
190
- return this;
191
- }
192
-
193
- /**
194
- * Gets a node by its {@link DottedPath}.
195
- */
196
- public getNode(dottedPath: DottedPathArgument): TransformNode {
197
- const _dottedPath = DottedPath.create(dottedPath);
198
- const keys = Array.from(this._dottedNodes.keys()).map(dp => dp.path);
199
- const values = Array.from(this._dottedNodes.values());
200
- const node = values[keys.indexOf(_dottedPath.path)];
201
- if (!node) {
202
- throw new Error(`Node with path "${_dottedPath.path}" does not exist for element "${this.id}".`);
203
- }
204
- return node;
205
- }
206
-
207
- /**
208
- * Gets a mesh by its {@link DottedPath}.
209
- */
210
- public async getMesh(dottedPath: DottedPathArgument): Promise<Mesh | null> {
211
- const node = await this.getNode(dottedPath);
212
- if (node instanceof Mesh) {
213
- return node;
214
- }
215
- return null;
216
- }
217
-
218
- /**
219
- * Gets a {@link PaintableDefinition} by its name.
220
- */
221
- public getPaintableDefinition(name: string): PaintableDefinition {
222
- if (!this.paintableDefinitions || !this.paintableDefinitions[name]) {
223
- throw new Error(`No paintable "${name}" defined for element "${this.id}".`);
224
- }
225
- return this.paintableDefinitions[name];
226
- }
227
-
228
- /**
229
- * Gets a {@link TraceableDefinition} by its name.
230
- */
231
- public getTraceableDefinition(name: string): TraceableDefinition {
232
- if (!this.traceableDefinitions || !this.traceableDefinitions[name]) {
233
- throw new Error(`No traceable "${name}" defined to add observer in element "${this.id}".`);
234
- }
235
- return this.traceableDefinitions[name];
236
- }
237
-
238
- /**
239
- * Gets the paintable Node by its name.
240
- */
241
- public getPaintableNode(name: string): TransformNode {
242
- return this.getNode(this.getPaintableDefinition(name).path);
243
- }
244
-
245
- /**
246
- * Gets the traceable Node by its name.
247
- */
248
- public getTraceableNode(name: string): TransformNode {
249
- return this.getNode(this.getTraceableDefinition(name).path);
250
- }
251
-
252
- /**
253
- * @see {@link VariantParameterizable.commitParameters}
254
- * @emit {@link Event.ELEMENT_PARAMETER_COMMITTED}
255
- */
256
- public async commitParameters(parameters?: ParameterBag): Promise<VariantParameterizable> {
257
- return super.commitParameters(parameters);
258
- }
259
-
260
- /**
261
- * Adds an observer function for camera matrix changes.
262
- * The `observer` gets 2 parameters: the `AbstractMesh` and a `ClientRect` object.
263
- */
264
- public addTraceableObserver(traceable: string, observer: CallableFunction, payload?: any): Element {
265
- if (payload && !(payload instanceof HTMLElement)) {
266
- throw new Error(`Payload for camera observer must be an instance of "HTMLElement" in element "${this.id}".`);
267
- }
268
- if (!this.traceableDefinitions || !this.traceableDefinitions[traceable]) {
269
- throw new Error(`No traceable "${traceable}" defined to add observer in element "${this.id}".`);
270
- }
271
- const node = this.getTraceableNode(traceable);
272
- if (!(node instanceof AbstractMesh)) {
273
- throw new Error(`The path must be an instance of "AbstractMesh" for camera observer in element "${this.id}".`);
274
- }
275
- this.variant.viewer.sceneManager.activeCamera.onViewMatrixChangedObservable.add((eventData, eventState) => {
276
- const position = getClientRectFromMesh(node, this.variant.viewer.scene, this.variant.viewer.canvas);
277
- if (payload) {
278
- payload.style.top = `${position.top}px`;
279
- payload.style.left = `${position.left}px`;
280
- }
281
- observer(node, position);
282
- });
283
- return this;
284
- }
285
-
286
- /**
287
- * Draws a `ImageBitmap` or `OffscreenCanvas` onto a `paintable` defined via {@link PaintableDefinition}.
288
- */
289
- public drawPaintable(paintable: string, imageSource: CanvasImageSource): Element {
290
- // node and material checks and preperation
291
- const node = this.getPaintableNode(paintable);
292
- if (!(node instanceof AbstractMesh)) {
293
- throw new Error(
294
- `The path must be an instance of "AbstractMesh" for paintable "${paintable}" ` + `in element "${this.id}".`
295
- );
296
- }
297
-
298
- if (node.material && this.variant.viewer.cloneMaterialsOnMutation) {
299
- if (node.material && !has(node.metadata, 'dirty.material')) {
300
- cloneTransformNodeMaterial(node);
301
- }
302
- if (!has(node.metadata, 'dirty.material.texture')) {
303
- // inject initial value and mark as dirty
304
- injectNodeMetadata(node, { dirty: { material: { texture: true } } });
305
- }
306
- } else if (!node.material) {
307
- // paintables should also work if no material is assigned to the node per default
308
- // in this case a certain fallback material with fitting default values is defined
309
- const pbrMat = new PBRMaterial(`${this.id}.${paintable}.material`, this.variant.viewer.scene);
310
- pbrMat.roughness = 1.0;
311
- pbrMat.metallic = 1.0;
312
- node.material = pbrMat;
313
- }
314
-
315
- // TODO: Not sure if this really should be overwritten every time the paintable is redrawn.
316
- // Maybe the 3D artist had something in mind when setting a certain transparency mode, which would get overwritten in this case.
317
- // Applying it as a default if no material is set is fine though (see roughness/metallic some lines above).
318
- // Removing this line will most likely break existing configurators, so be cautios!
319
- node.material.transparencyMode = Material.MATERIAL_ALPHATESTANDBLEND;
320
-
321
- // consider width and height of the paintable
322
- const widthAndHeight = {
323
- width: imageSource.width,
324
- height: imageSource.height,
325
- };
326
- const paintableDefinition = this.getPaintableDefinition(paintable);
327
- if (isNumber(paintableDefinition.textureOptions)) {
328
- widthAndHeight.width = paintableDefinition.textureOptions;
329
- widthAndHeight.height = paintableDefinition.textureOptions;
330
- } else if (isPlainObject(paintableDefinition.textureOptions)) {
331
- widthAndHeight.width = paintableDefinition.textureOptions.width;
332
- widthAndHeight.height = paintableDefinition.textureOptions.height;
333
- }
334
-
335
- // create dynamic texture on which the image can be drawn
336
- const texture = new DynamicTexture(
337
- `${this.id}.${paintable}.texture`,
338
- widthAndHeight,
339
- this.variant.viewer.scene,
340
- false
341
- );
342
-
343
- // draw image on texture
344
- const ctx = texture.getContext();
345
- ctx.drawImage(imageSource, 0, 0);
346
- texture.update(false);
347
-
348
- // finally apply the texture on the desired node material
349
- setMaterialTexture(node, texture, false);
350
-
351
- return this;
352
- }
353
-
354
- /**
355
- * Draws a SVG string onto a `paintable` defined via {@link PaintableDefinition}.
356
- */
357
- public async drawPaintableFromSvg(paintable: string, svgSource: string): Promise<Element> {
358
- const image = await createImageFromSvg(svgSource);
359
- return this.drawPaintable(paintable, image);
360
- }
361
-
362
- /**
363
- * Draws an Image from source (URL/URI) onto a `paintable` defined via {@link PaintableDefinition}.
364
- */
365
- public async drawPaintableFromImgSrc(paintable: string, imgSource: string): Promise<Element> {
366
- const image = await createImageFromImgSrc(imgSource);
367
- return this.drawPaintable(paintable, image);
368
- }
369
-
370
- /**
371
- * Adds observers for loading missing materials where needed
372
- */
373
- protected addMissingMaterialObservers() {
374
- for (const abstractMesh of this.abstractMeshesFlat) {
375
- addMissingMaterialObserver(abstractMesh);
376
- }
377
- }
378
-
379
- /**
380
- * Adds the default {@link ParameterObserver}s which are called every time {@link commitParameters} is called.
381
- */
382
- protected addParameterObservers(): Element {
383
- this._parameterObservers.set(Parameter.VISIBLE, [
384
- async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
385
- let visible;
386
- try {
387
- visible = Parameter.parseBoolean(newValue);
388
- } catch (e) {
389
- return;
390
- }
391
- if (visible === true) {
392
- element.nodes.forEach(node => {
393
- injectNodeMetadata(node, { visibility: node.isEnabled() });
394
- activate(node);
395
- });
396
- } else if (visible === false) {
397
- element.nodes.forEach(node => {
398
- injectNodeMetadata(node, { visibility: node.isEnabled() });
399
- deactivate(node);
400
- });
401
- }
402
- },
403
- ]);
404
- this._parameterObservers.set(Parameter.SCALING, [
405
- async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
406
- // we have to deal just with root nodes here due to relative impacts in a node tree
407
- element.nodes.forEach(node =>
408
- transformTransformNode(node, {
409
- scaling: Parameter.parseVector(newValue),
410
- position: Parameter.parseVector(element.inheritedParameters[Parameter.POSITION] || '(0, 0, 0)'),
411
- rotation: Parameter.parseRotation(element.inheritedParameters[Parameter.ROTATION] || '(0, 0, 0)'),
412
- })
413
- );
414
- },
415
- ]);
416
- this._parameterObservers.set(Parameter.POSITION, [
417
- async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
418
- // we have to deal just with root nodes here due to relative impacts in a node tree
419
- element.nodes.forEach(node =>
420
- transformTransformNode(node, {
421
- scaling: Parameter.parseVector(element.inheritedParameters[Parameter.SCALING] || '(1, 1, 1)'),
422
- position: Parameter.parseVector(newValue),
423
- rotation: Parameter.parseRotation(element.inheritedParameters[Parameter.ROTATION] || '(0, 0, 0)'),
424
- })
425
- );
426
- },
427
- ]);
428
- this._parameterObservers.set(Parameter.ROTATION, [
429
- async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
430
- // we have to deal just with root nodes here due to relative impacts in a node tree
431
- element.nodes.forEach(node =>
432
- transformTransformNode(node, {
433
- scaling: Parameter.parseVector(element.inheritedParameters[Parameter.SCALING] || '(1, 1, 1)'),
434
- position: Parameter.parseVector(element.inheritedParameters[Parameter.POSITION] || '(0, 0, 0)'),
435
- rotation: Parameter.parseRotation(newValue),
436
- })
437
- );
438
- },
439
- ]);
440
- this._parameterObservers.set(Parameter.MATERIAL, [
441
- async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
442
- const materialName = newValue.toString();
443
- element.nodes.forEach(node => {
444
- assertTransformNode(node, (node: AbstractMesh) => {
445
- if (node instanceof InstancedMesh) {
446
- throw new Error(
447
- `Changing parameter "${Parameter.MATERIAL}" ` +
448
- `of an InstancedMesh is not supported. ` +
449
- `Tried to change node "${node.id}" on element "${element.id}".`
450
- );
451
- }
452
- });
453
- setMaterial(element.variant, node, materialName);
454
- });
455
- },
456
- ]);
457
- this._parameterObservers.set(Parameter.MATERIAL_COLOR, [
458
- async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
459
- const color = Parameter.parseColor(newValue);
460
- element.nodes.forEach(node => {
461
- assertTransformNode(node, (node: AbstractMesh) => {
462
- if (node instanceof InstancedMesh) {
463
- throw new Error(
464
- `Changing parameter "${Parameter.MATERIAL_COLOR}" ` +
465
- `of an InstancedMesh is not supported. ` +
466
- `Tried to change node "${node.id}" on element "${element.id}".`
467
- );
468
- }
469
- });
470
- if (this.variant.viewer.cloneMaterialsOnMutation) {
471
- if (!has(node.metadata, 'dirty.material')) {
472
- cloneTransformNodeMaterial(node);
473
- }
474
- if (!has(node.metadata, 'dirty.material.color')) {
475
- // inject initial value and mark as dirty
476
- injectNodeMetadata(node, { dirty: { material: { color: oldValue } } });
477
- }
478
- }
479
- setMaterialColor(node, color);
480
- });
481
- },
482
- ]);
483
- this._parameterObservers.set(Parameter.MATERIAL_METALLNESS, [
484
- async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
485
- const metallness = Parameter.parseNumber(newValue);
486
- element.nodes.forEach(node => {
487
- assertTransformNode(node, (node: AbstractMesh) => {
488
- if (node instanceof InstancedMesh) {
489
- throw new Error(
490
- `Changing parameter "${Parameter.MATERIAL_METALLNESS}" ` +
491
- `of an InstancedMesh is not supported. ` +
492
- `Tried to change node "${node.id}" on element "${element.id}".`
493
- );
494
- }
495
- });
496
- if (this.variant.viewer.cloneMaterialsOnMutation) {
497
- if (!has(node.metadata, 'dirty.material')) {
498
- cloneTransformNodeMaterial(node);
499
- }
500
- if (!has(node.metadata, 'dirty.material.metallness')) {
501
- // inject initial value and mark as dirty
502
- injectNodeMetadata(node, { dirty: { material: { metallness: oldValue } } });
503
- }
504
- }
505
- setMaterialMetallness(node, metallness);
506
- });
507
- },
508
- ]);
509
- this._parameterObservers.set(Parameter.MATERIAL_ROUGHNESS, [
510
- async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
511
- const roughness = Parameter.parseNumber(newValue);
512
- element.nodes.forEach(node => {
513
- assertTransformNode(node, (node: AbstractMesh) => {
514
- if (node instanceof InstancedMesh) {
515
- throw new Error(
516
- `Changing parameter "${Parameter.MATERIAL_ROUGHNESS}" ` +
517
- `of an InstancedMesh is not supported. ` +
518
- `Tried to change node "${node.id}" on element "${element.id}".`
519
- );
520
- }
521
- });
522
- if (this.variant.viewer.cloneMaterialsOnMutation) {
523
- if (!has(node.metadata, 'dirty.material')) {
524
- cloneTransformNodeMaterial(node);
525
- }
526
- if (!has(node.metadata, 'dirty.material.roughness')) {
527
- // inject initial value and mark as dirty
528
- injectNodeMetadata(node, { dirty: { material: { roughness: oldValue } } });
529
- }
530
- }
531
- setMaterialRoughness(node, roughness);
532
- });
533
- },
534
- ]);
535
- this._parameterObservers.set(Parameter.HIGHLIGHT_COLOR, [
536
- async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
537
- // trigger Parameter.HIGHLIGHTED observers
538
- this._parameterObservers.get(Parameter.HIGHLIGHTED)?.forEach(observer => {
539
- observer(element, !!element.highlighted, !!element.highlighted);
540
- });
541
- },
542
- ]);
543
- this._parameterObservers.set(Parameter.HIGHLIGHT_ENABLED, [
544
- async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
545
- let curr;
546
- try {
547
- curr = Parameter.parseBoolean(newValue);
548
- } catch (e) {
549
- return;
550
- }
551
- switch (curr) {
552
- case true:
553
- if (element._highlightLayer) {
554
- break;
555
- }
556
- element.highlightLayer = new HighlightLayer(
557
- DottedPath.create(element.id).addPart('highlight').path,
558
- element.variant.viewer.scene
559
- );
560
- break;
561
- case false:
562
- element.highlightLayer?.dispose();
563
- break;
564
- }
565
- },
566
- ]);
567
- this._parameterObservers.set(Parameter.HIGHLIGHTED, [
568
- async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
569
- if (!element.inheritedParameters[Parameter.HIGHLIGHT_ENABLED]) {
570
- return;
571
- }
572
- // trigger Parameter.HIGHLIGHT_ENABLED observers to ensure HighlightLayer
573
- this._parameterObservers.get(Parameter.HIGHLIGHT_ENABLED)?.forEach(observer => {
574
- observer(element, this.parameters[Parameter.HIGHLIGHT_ENABLED], true);
575
- });
576
- let highlighted;
577
- try {
578
- highlighted = Parameter.parseBoolean(newValue);
579
- } catch (e) {
580
- return;
581
- }
582
- // Add/Remove meshes to previously created highlight layers.
583
- if (highlighted === true) {
584
- element.nodes.forEach(node => {
585
- assertTransformNode(node, (node: AbstractMesh) => {
586
- if (node instanceof InstancedMesh) {
587
- throw new Error(
588
- `Changing parameter "${Parameter.HIGHLIGHTED}" ` +
589
- `of an InstancedMesh is not supported. ` +
590
- `Tried to change node "${node.id}" on element "${element.id}".`
591
- );
592
- }
593
- });
594
- let color = Color3.Green();
595
- if (element.inheritedParameters[Parameter.HIGHLIGHT_COLOR]) {
596
- color = Parameter.parseColor(element.inheritedParameters[Parameter.HIGHLIGHT_COLOR]);
597
- }
598
- if (typeof element._highlightLayer !== 'undefined') {
599
- addToHighlightLayer(element._highlightLayer, color, node);
600
- }
601
- });
602
- } else if (highlighted === false) {
603
- element.nodes.forEach(node => {
604
- if (typeof element._highlightLayer !== 'undefined') {
605
- removeFromHighlightLayer(element._highlightLayer, node);
606
- }
607
- });
608
- }
609
- },
610
- ]);
611
- this._parameterObservers.set(Parameter.CAST_SHADOW, [
612
- async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
613
- let castShadow;
614
- try {
615
- castShadow = Parameter.parseBoolean(newValue);
616
- } catch (e) {
617
- return;
618
- }
619
- let lightCsl = element.inheritedParameters[Parameter.CAST_SHADOW_FROM_LIGHTS];
620
- if (!lightCsl) {
621
- lightCsl = element.variant.inheritedViewerLights.map(l => l.name).join(',');
622
- }
623
- if (castShadow === true) {
624
- await this.castShadowValueHandler(lightCsl, addToShadowGenerator);
625
- }
626
- if (castShadow === false) {
627
- await this.castShadowValueHandler(lightCsl, removeFromShadowGenerator);
628
- }
629
- },
630
- ]);
631
- this._parameterObservers.set(Parameter.CAST_SHADOW_FROM_LIGHTS, [
632
- async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
633
- // TODO: Possible performance issue in combination with CAST_SHADOW, since both observers are initially called
634
- // when CAST_SHADOW and CAST_SHADOW_FROM_LIGHTS are defined in the spec.
635
- const lightCsl = element.variant.inheritedViewerLights.map(l => l.name).join(',');
636
- // cleanup all shadow generators
637
- await this.castShadowValueHandler(lightCsl, removeFromShadowGenerator);
638
- if (element.castShadow === true) {
639
- // if newValue is undefined or '' then set newValue to lightCsl (use all lights)
640
- if (!newValue) {
641
- newValue = lightCsl;
642
- }
643
- await this.castShadowValueHandler(newValue, addToShadowGenerator);
644
- }
645
- },
646
- ]);
647
- this._parameterObservers.set(Parameter.RECEIVE_SHADOWS, [
648
- async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
649
- element.nodes.forEach(node => setReceiveShadows(node, Parameter.parseBoolean(newValue)));
650
- },
651
- ]);
652
- return this;
653
- }
654
-
655
- /**
656
- * Filter for nodes that are not defined or excluded in the `pathDefinitions`.
657
- */
658
- protected filterNode(node: TransformNode): boolean {
659
- let includeTokens: string[] = [];
660
- this.pathDefinitions.include.forEach(dottedPath => {
661
- includeTokens = union(includeTokens, DottedPath.create(dottedPath).leafTokens);
662
- });
663
- const shallKeep = (dp: DottedPath) => {
664
- const isDirectlyIncluded = !!includeTokens.find(_dp => _dp === dp.path);
665
- const isSubOfIncluded = !!this.pathDefinitions.include.find(_dp => {
666
- return dp.path.startsWith(`${_dp}${DottedPath.DELIMITER}`);
667
- });
668
- return isDirectlyIncluded || isSubOfIncluded;
669
- };
670
- const shallExclude = (dp: DottedPath) => {
671
- if (!this.pathDefinitions.exclude) {
672
- return false;
673
- }
674
- return !!this.pathDefinitions.exclude.find(_dp => dp.path === _dp);
675
- };
676
- return shallKeep(node.metadata.dottedPath) && !shallExclude(node.metadata.dottedPath);
677
- }
678
-
679
- /**
680
- * Asserts whether all {@link pathDefinitions} link to a valid `Node` path.
681
- * @protected
682
- */
683
- protected assertPathDefinitions() {
684
- const dottedNodes = this.variant.inheritedDottedNodes;
685
- if (dottedNodes.size === 0) {
686
- throw new Error(`There are no mapped nodes for element "${this.id}".`);
687
- }
688
- const include = this.pathDefinitions.include.map(path => DottedPath.create(path).path);
689
- const exclude = this.pathDefinitions.exclude?.map(path => DottedPath.create(path).path);
690
- const keys = Array.from(dottedNodes.keys()).map(dottedPath => dottedPath.path);
691
- union<string>(include, exclude).forEach(path => {
692
- if (keys.indexOf(path) === -1) {
693
- throw new Error(`Node with path "${path}" does not exist for element "${this.id}".`);
694
- }
695
- });
696
- }
697
-
698
- /**
699
- * Handles callback for given light parameter.
700
- */
701
- private async castShadowValueHandler(lightCsl: ParameterValue, mutator: CallableFunction) {
702
- let lights: Light[] = [];
703
- for (const lightName of Parameter.parseCommaSeparatedList(lightCsl)) {
704
- const viewerLight = await this.variant.getViewerLight(lightName);
705
- if (viewerLight) {
706
- lights.push(viewerLight.light);
707
- }
708
- }
709
- const shadowGenerators = lights.map(light => light?.getShadowGenerator() as ShadowGenerator).filter(Boolean);
710
- shadowGenerators.forEach(generator => {
711
- this.nodes.forEach(node => {
712
- mutator(generator, node);
713
- });
714
- });
715
- }
716
- }
1
+ import {
2
+ activateTransformNode as activate,
3
+ addToHighlightLayer,
4
+ addToShadowGenerator,
5
+ assertTransformNode,
6
+ cloneTransformNode,
7
+ cloneTransformNodeMaterial,
8
+ deactivateTransformNode as deactivate,
9
+ getClientRectFromMesh,
10
+ injectNodeMetadata,
11
+ mapToDottedNodes,
12
+ removeFromHighlightLayer,
13
+ removeFromShadowGenerator,
14
+ setMaterial,
15
+ setMaterialColor,
16
+ setMaterialMetallness,
17
+ setMaterialRoughness,
18
+ setMaterialTexture,
19
+ setReceiveShadows,
20
+ transformTransformNode,
21
+ } from '../util/babylonHelper';
22
+ import { createImageFromImgSrc, createImageFromSvg } from '../util/resourceHelper';
23
+ import { addMissingMaterialObserver } from '../util/sceneLoaderHelper';
24
+ import { VariantParameterizable } from './../classes/variantParameterizable';
25
+ import { DottedPath } from './dottedPath';
26
+ import { Parameter } from './parameter';
27
+ import { Variant } from './variant';
28
+ import { HighlightLayer } from '@babylonjs/core/Layers/highlightLayer';
29
+ import { ShadowGenerator } from '@babylonjs/core/Lights/Shadows/shadowGenerator';
30
+ import { Light } from '@babylonjs/core/Lights/light';
31
+ import { PBRMaterial } from '@babylonjs/core/Materials/PBR/pbrMaterial';
32
+ import { DynamicTexture } from '@babylonjs/core/Materials/Textures/dynamicTexture';
33
+ import { Material } from '@babylonjs/core/Materials/material';
34
+ import { Color3 } from '@babylonjs/core/Maths/math.color';
35
+ import { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh';
36
+ import { InstancedMesh } from '@babylonjs/core/Meshes/instancedMesh';
37
+ import { Mesh } from '@babylonjs/core/Meshes/mesh';
38
+ import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
39
+ import { has, isArray, isNumber, isPlainObject, merge, union } from 'lodash-es';
40
+
41
+ /**
42
+ * An {@link Element} of a {@link Variant}. Acts as a container for diverse definitions. Lives only in the context of a
43
+ * {@link Variant}.
44
+ *
45
+ * When used in typings, refer to via its alias {@link VariantElement} to prevent name clashes with the web APIs
46
+ * [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) class
47
+ */
48
+ export class Element extends VariantParameterizable {
49
+ public readonly nodes: TransformNode[] = [];
50
+
51
+ protected readonly _dottedNodes: Map<DottedPath, TransformNode> = new Map();
52
+
53
+ protected _highlightLayer?: HighlightLayer;
54
+
55
+ /**
56
+ * Constructor.
57
+ */
58
+ protected constructor(public readonly variant: Variant, public readonly name: string) {
59
+ super(variant, name);
60
+ if (process.env.NODE_ENV?.toLowerCase().includes('dev')) {
61
+ this.assertPathDefinitions();
62
+ }
63
+ const nodes = this.variant.inheritedNodes.map(node => cloneTransformNode(node, this.filterNode.bind(this)));
64
+ this.nodes = nodes.filter(node => !!node) as TransformNode[];
65
+ this._dottedNodes = mapToDottedNodes<TransformNode>(this.nodes, node => node instanceof TransformNode);
66
+ this.addMissingMaterialObservers();
67
+ this.addParameterObservers();
68
+ }
69
+
70
+ /**
71
+ * Creates an {@link Element} with given name.
72
+ */
73
+ public static async create(variant: Variant, name: string): Promise<Element> {
74
+ return new Element(variant, name);
75
+ }
76
+
77
+ /**
78
+ * The {@link DottedPath} in the built tree of {@link Element}s.
79
+ * E.g. "_.top-1.sub-2.sub-sub-3.el-1"
80
+ */
81
+ get dottedPath(): DottedPath {
82
+ return DottedPath.create(this.variant.dottedPath).addPart(this.name);
83
+ }
84
+
85
+ /**
86
+ * The id representing a {@link DottedPath}.
87
+ */
88
+ get id(): string {
89
+ const dottedPath = DottedPath.create(this.dottedPath);
90
+ dottedPath.shiftPart(); // remove root
91
+ return dottedPath.path;
92
+ }
93
+
94
+ /**
95
+ * The {@link ElementDefinition} of the {@link Element}.
96
+ */
97
+ get definition(): ElementDefinition {
98
+ const definition = this.variant.structureJson.elements![this.name];
99
+ if (isArray(definition)) {
100
+ return {
101
+ paths: {
102
+ include: definition,
103
+ },
104
+ } as ElementDefinition;
105
+ }
106
+ return definition as ElementDefinition;
107
+ }
108
+
109
+ /**
110
+ * The {@link PathDefinitions} of the {@link Element}.
111
+ */
112
+ get pathDefinitions(): PathDefinitions {
113
+ return this.definition.paths;
114
+ }
115
+
116
+ /**
117
+ * The {@link TraceableDefinitions} of the {@link Element}.
118
+ */
119
+ get traceableDefinitions(): TraceableDefinitions {
120
+ return this.definition.traceables || {};
121
+ }
122
+
123
+ /**
124
+ * The {@link PaintableDefinition} of the {@link Element}.
125
+ */
126
+ get paintableDefinitions(): PaintableDefinitions {
127
+ return this.definition.paintables || {};
128
+ }
129
+
130
+ /**
131
+ * The inherited {@link ParameterBag}.
132
+ * Merges the {@link Variant}'s parameters and those from the {@link Element}.
133
+ */
134
+ get inheritedParameters(): ParameterBag {
135
+ return merge({}, this.variant.inheritedParameters, this.parameters);
136
+ }
137
+
138
+ /**
139
+ * The actual {@link Mesh}es that make up this {@link Element}.
140
+ * Handy for e.g. creating a bounding box around an entire element.
141
+ */
142
+ get meshesFlat(): Mesh[] {
143
+ const flatMeshes = this.nodes.reduce((accFlatMeshes, curNode) => {
144
+ const currMeshes = curNode.getChildMeshes(false, n => n instanceof Mesh) as Mesh[];
145
+ return [...accFlatMeshes, ...currMeshes];
146
+ }, [] as Mesh[]);
147
+ return flatMeshes;
148
+ }
149
+
150
+ /**
151
+ * The actual {@link AbstractMesh}es that make up this {@link Element}.
152
+ * I.e. (real) Meshes as well as InstancedMeshes.
153
+ */
154
+ get abstractMeshesFlat(): AbstractMesh[] {
155
+ const allAbstractMeshes = this.nodes.reduce((acc, currNode) => {
156
+ const currAbstractMeshes = currNode.getChildMeshes(false, n => n instanceof AbstractMesh);
157
+ if (currNode instanceof AbstractMesh) {
158
+ currAbstractMeshes.unshift(currNode);
159
+ }
160
+ return [...acc, ...currAbstractMeshes];
161
+ }, [] as AbstractMesh[]); // initial accumulator value
162
+ return allAbstractMeshes;
163
+ }
164
+
165
+ /**
166
+ * The meshes of this {@link Element}.
167
+ */
168
+ get meshes(): Mesh[] {
169
+ return this.nodes.filter(node => node instanceof Mesh) as Mesh[];
170
+ }
171
+
172
+ /**
173
+ * @protected
174
+ */
175
+ set highlightLayer(layer: HighlightLayer | undefined) {
176
+ this._highlightLayer = layer;
177
+ }
178
+
179
+ get highlightLayer(): HighlightLayer | undefined {
180
+ return this._highlightLayer;
181
+ }
182
+
183
+ /**
184
+ * Destroys this {@link Element} and dispose all nodes.
185
+ */
186
+ public destroy(): Element {
187
+ this.nodes.forEach(node => {
188
+ node.dispose();
189
+ });
190
+ return this;
191
+ }
192
+
193
+ /**
194
+ * Gets a node by its {@link DottedPath}.
195
+ */
196
+ public getNode(dottedPath: DottedPathArgument): TransformNode {
197
+ const _dottedPath = DottedPath.create(dottedPath);
198
+ const keys = Array.from(this._dottedNodes.keys()).map(dp => dp.path);
199
+ const values = Array.from(this._dottedNodes.values());
200
+ const node = values[keys.indexOf(_dottedPath.path)];
201
+ if (!node) {
202
+ throw new Error(`Node with path "${_dottedPath.path}" does not exist for element "${this.id}".`);
203
+ }
204
+ return node;
205
+ }
206
+
207
+ /**
208
+ * Gets a mesh by its {@link DottedPath}.
209
+ */
210
+ public async getMesh(dottedPath: DottedPathArgument): Promise<Mesh | null> {
211
+ const node = await this.getNode(dottedPath);
212
+ if (node instanceof Mesh) {
213
+ return node;
214
+ }
215
+ return null;
216
+ }
217
+
218
+ /**
219
+ * Gets a {@link PaintableDefinition} by its name.
220
+ */
221
+ public getPaintableDefinition(name: string): PaintableDefinition {
222
+ if (!this.paintableDefinitions || !this.paintableDefinitions[name]) {
223
+ throw new Error(`No paintable "${name}" defined for element "${this.id}".`);
224
+ }
225
+ return this.paintableDefinitions[name];
226
+ }
227
+
228
+ /**
229
+ * Gets a {@link TraceableDefinition} by its name.
230
+ */
231
+ public getTraceableDefinition(name: string): TraceableDefinition {
232
+ if (!this.traceableDefinitions || !this.traceableDefinitions[name]) {
233
+ throw new Error(`No traceable "${name}" defined to add observer in element "${this.id}".`);
234
+ }
235
+ return this.traceableDefinitions[name];
236
+ }
237
+
238
+ /**
239
+ * Gets the paintable Node by its name.
240
+ */
241
+ public getPaintableNode(name: string): TransformNode {
242
+ return this.getNode(this.getPaintableDefinition(name).path);
243
+ }
244
+
245
+ /**
246
+ * Gets the traceable Node by its name.
247
+ */
248
+ public getTraceableNode(name: string): TransformNode {
249
+ return this.getNode(this.getTraceableDefinition(name).path);
250
+ }
251
+
252
+ /**
253
+ * @see {@link VariantParameterizable.commitParameters}
254
+ * @emit {@link Event.ELEMENT_PARAMETER_COMMITTED}
255
+ */
256
+ public async commitParameters(parameters?: ParameterBag): Promise<VariantParameterizable> {
257
+ return super.commitParameters(parameters);
258
+ }
259
+
260
+ /**
261
+ * Adds an observer function for camera matrix changes.
262
+ * The `observer` gets 2 parameters: the `AbstractMesh` and a `ClientRect` object.
263
+ */
264
+ public addTraceableObserver(traceable: string, observer: CallableFunction, payload?: any): Element {
265
+ if (payload && !(payload instanceof HTMLElement)) {
266
+ throw new Error(`Payload for camera observer must be an instance of "HTMLElement" in element "${this.id}".`);
267
+ }
268
+ if (!this.traceableDefinitions || !this.traceableDefinitions[traceable]) {
269
+ throw new Error(`No traceable "${traceable}" defined to add observer in element "${this.id}".`);
270
+ }
271
+ const node = this.getTraceableNode(traceable);
272
+ if (!(node instanceof AbstractMesh)) {
273
+ throw new Error(`The path must be an instance of "AbstractMesh" for camera observer in element "${this.id}".`);
274
+ }
275
+ this.variant.viewer.sceneManager.activeCamera.onViewMatrixChangedObservable.add((eventData, eventState) => {
276
+ const position = getClientRectFromMesh(node, this.variant.viewer.scene, this.variant.viewer.canvas);
277
+ if (payload) {
278
+ payload.style.top = `${position.top}px`;
279
+ payload.style.left = `${position.left}px`;
280
+ }
281
+ observer(node, position);
282
+ });
283
+ return this;
284
+ }
285
+
286
+ /**
287
+ * Draws a `ImageBitmap` or `OffscreenCanvas` onto a `paintable` defined via {@link PaintableDefinition}.
288
+ */
289
+ public drawPaintable(paintable: string, imageSource: CanvasImageSource): Element {
290
+ // node and material checks and preperation
291
+ const node = this.getPaintableNode(paintable);
292
+ if (!(node instanceof AbstractMesh)) {
293
+ throw new Error(
294
+ `The path must be an instance of "AbstractMesh" for paintable "${paintable}" ` + `in element "${this.id}".`
295
+ );
296
+ }
297
+
298
+ if (node.material && this.variant.viewer.cloneMaterialsOnMutation) {
299
+ if (node.material && !has(node.metadata, 'dirty.material')) {
300
+ cloneTransformNodeMaterial(node);
301
+ }
302
+ if (!has(node.metadata, 'dirty.material.texture')) {
303
+ // inject initial value and mark as dirty
304
+ injectNodeMetadata(node, { dirty: { material: { texture: true } } });
305
+ }
306
+ } else if (!node.material) {
307
+ // paintables should also work if no material is assigned to the node per default
308
+ // in this case a certain fallback material with fitting default values is defined
309
+ const pbrMat = new PBRMaterial(`${this.id}.${paintable}.material`, this.variant.viewer.scene);
310
+ pbrMat.roughness = 1.0;
311
+ pbrMat.metallic = 1.0;
312
+ node.material = pbrMat;
313
+ }
314
+
315
+ // TODO: Not sure if this really should be overwritten every time the paintable is redrawn.
316
+ // Maybe the 3D artist had something in mind when setting a certain transparency mode, which would get overwritten in this case.
317
+ // Applying it as a default if no material is set is fine though (see roughness/metallic some lines above).
318
+ // Removing this line will most likely break existing configurators, so be cautios!
319
+ node.material.transparencyMode = Material.MATERIAL_ALPHATESTANDBLEND;
320
+
321
+ // consider width and height of the paintable
322
+ const widthAndHeight = {
323
+ width: imageSource.width,
324
+ height: imageSource.height,
325
+ };
326
+ const paintableDefinition = this.getPaintableDefinition(paintable);
327
+ if (isNumber(paintableDefinition.textureOptions)) {
328
+ widthAndHeight.width = paintableDefinition.textureOptions;
329
+ widthAndHeight.height = paintableDefinition.textureOptions;
330
+ } else if (isPlainObject(paintableDefinition.textureOptions)) {
331
+ widthAndHeight.width = paintableDefinition.textureOptions.width;
332
+ widthAndHeight.height = paintableDefinition.textureOptions.height;
333
+ }
334
+
335
+ // create dynamic texture on which the image can be drawn
336
+ const texture = new DynamicTexture(
337
+ `${this.id}.${paintable}.texture`,
338
+ widthAndHeight,
339
+ this.variant.viewer.scene,
340
+ false
341
+ );
342
+
343
+ // draw image on texture
344
+ const ctx = texture.getContext();
345
+ ctx.drawImage(imageSource, 0, 0);
346
+ texture.update(false);
347
+
348
+ // finally apply the texture on the desired node material
349
+ setMaterialTexture(node, texture, false);
350
+
351
+ return this;
352
+ }
353
+
354
+ /**
355
+ * Draws a SVG string onto a `paintable` defined via {@link PaintableDefinition}.
356
+ */
357
+ public async drawPaintableFromSvg(paintable: string, svgSource: string): Promise<Element> {
358
+ const image = await createImageFromSvg(svgSource);
359
+ return this.drawPaintable(paintable, image);
360
+ }
361
+
362
+ /**
363
+ * Draws an Image from source (URL/URI) onto a `paintable` defined via {@link PaintableDefinition}.
364
+ */
365
+ public async drawPaintableFromImgSrc(paintable: string, imgSource: string): Promise<Element> {
366
+ const image = await createImageFromImgSrc(imgSource);
367
+ return this.drawPaintable(paintable, image);
368
+ }
369
+
370
+ /**
371
+ * Adds observers for loading missing materials where needed
372
+ */
373
+ protected addMissingMaterialObservers() {
374
+ for (const abstractMesh of this.abstractMeshesFlat) {
375
+ addMissingMaterialObserver(abstractMesh);
376
+ }
377
+ }
378
+
379
+ /**
380
+ * Adds the default {@link ParameterObserver}s which are called every time {@link commitParameters} is called.
381
+ */
382
+ protected addParameterObservers(): Element {
383
+ this._parameterObservers.set(Parameter.VISIBLE, [
384
+ async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
385
+ let visible;
386
+ try {
387
+ visible = Parameter.parseBoolean(newValue);
388
+ } catch (e) {
389
+ return;
390
+ }
391
+ if (visible === true) {
392
+ element.nodes.forEach(node => {
393
+ injectNodeMetadata(node, { visibility: node.isEnabled() });
394
+ activate(node);
395
+ });
396
+ } else if (visible === false) {
397
+ element.nodes.forEach(node => {
398
+ injectNodeMetadata(node, { visibility: node.isEnabled() });
399
+ deactivate(node);
400
+ });
401
+ }
402
+ },
403
+ ]);
404
+ this._parameterObservers.set(Parameter.SCALING, [
405
+ async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
406
+ // we have to deal just with root nodes here due to relative impacts in a node tree
407
+ element.nodes.forEach(node =>
408
+ transformTransformNode(node, {
409
+ scaling: Parameter.parseVector(newValue),
410
+ position: Parameter.parseVector(element.inheritedParameters[Parameter.POSITION] || '(0, 0, 0)'),
411
+ rotation: Parameter.parseRotation(element.inheritedParameters[Parameter.ROTATION] || '(0, 0, 0)'),
412
+ })
413
+ );
414
+ },
415
+ ]);
416
+ this._parameterObservers.set(Parameter.POSITION, [
417
+ async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
418
+ // we have to deal just with root nodes here due to relative impacts in a node tree
419
+ element.nodes.forEach(node =>
420
+ transformTransformNode(node, {
421
+ scaling: Parameter.parseVector(element.inheritedParameters[Parameter.SCALING] || '(1, 1, 1)'),
422
+ position: Parameter.parseVector(newValue),
423
+ rotation: Parameter.parseRotation(element.inheritedParameters[Parameter.ROTATION] || '(0, 0, 0)'),
424
+ })
425
+ );
426
+ },
427
+ ]);
428
+ this._parameterObservers.set(Parameter.ROTATION, [
429
+ async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
430
+ // we have to deal just with root nodes here due to relative impacts in a node tree
431
+ element.nodes.forEach(node =>
432
+ transformTransformNode(node, {
433
+ scaling: Parameter.parseVector(element.inheritedParameters[Parameter.SCALING] || '(1, 1, 1)'),
434
+ position: Parameter.parseVector(element.inheritedParameters[Parameter.POSITION] || '(0, 0, 0)'),
435
+ rotation: Parameter.parseRotation(newValue),
436
+ })
437
+ );
438
+ },
439
+ ]);
440
+ this._parameterObservers.set(Parameter.MATERIAL, [
441
+ async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
442
+ const materialName = newValue.toString();
443
+ element.nodes.forEach(node => {
444
+ assertTransformNode(node, (node: AbstractMesh) => {
445
+ if (node instanceof InstancedMesh) {
446
+ throw new Error(
447
+ `Changing parameter "${Parameter.MATERIAL}" ` +
448
+ `of an InstancedMesh is not supported. ` +
449
+ `Tried to change node "${node.id}" on element "${element.id}".`
450
+ );
451
+ }
452
+ });
453
+ setMaterial(element.variant, node, materialName);
454
+ });
455
+ },
456
+ ]);
457
+ this._parameterObservers.set(Parameter.MATERIAL_COLOR, [
458
+ async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
459
+ const color = Parameter.parseColor(newValue);
460
+ element.nodes.forEach(node => {
461
+ assertTransformNode(node, (node: AbstractMesh) => {
462
+ if (node instanceof InstancedMesh) {
463
+ throw new Error(
464
+ `Changing parameter "${Parameter.MATERIAL_COLOR}" ` +
465
+ `of an InstancedMesh is not supported. ` +
466
+ `Tried to change node "${node.id}" on element "${element.id}".`
467
+ );
468
+ }
469
+ });
470
+ if (this.variant.viewer.cloneMaterialsOnMutation) {
471
+ if (!has(node.metadata, 'dirty.material')) {
472
+ cloneTransformNodeMaterial(node);
473
+ }
474
+ if (!has(node.metadata, 'dirty.material.color')) {
475
+ // inject initial value and mark as dirty
476
+ injectNodeMetadata(node, { dirty: { material: { color: oldValue } } });
477
+ }
478
+ }
479
+ setMaterialColor(node, color);
480
+ });
481
+ },
482
+ ]);
483
+ this._parameterObservers.set(Parameter.MATERIAL_METALLNESS, [
484
+ async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
485
+ const metallness = Parameter.parseNumber(newValue);
486
+ element.nodes.forEach(node => {
487
+ assertTransformNode(node, (node: AbstractMesh) => {
488
+ if (node instanceof InstancedMesh) {
489
+ throw new Error(
490
+ `Changing parameter "${Parameter.MATERIAL_METALLNESS}" ` +
491
+ `of an InstancedMesh is not supported. ` +
492
+ `Tried to change node "${node.id}" on element "${element.id}".`
493
+ );
494
+ }
495
+ });
496
+ if (this.variant.viewer.cloneMaterialsOnMutation) {
497
+ if (!has(node.metadata, 'dirty.material')) {
498
+ cloneTransformNodeMaterial(node);
499
+ }
500
+ if (!has(node.metadata, 'dirty.material.metallness')) {
501
+ // inject initial value and mark as dirty
502
+ injectNodeMetadata(node, { dirty: { material: { metallness: oldValue } } });
503
+ }
504
+ }
505
+ setMaterialMetallness(node, metallness);
506
+ });
507
+ },
508
+ ]);
509
+ this._parameterObservers.set(Parameter.MATERIAL_ROUGHNESS, [
510
+ async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
511
+ const roughness = Parameter.parseNumber(newValue);
512
+ element.nodes.forEach(node => {
513
+ assertTransformNode(node, (node: AbstractMesh) => {
514
+ if (node instanceof InstancedMesh) {
515
+ throw new Error(
516
+ `Changing parameter "${Parameter.MATERIAL_ROUGHNESS}" ` +
517
+ `of an InstancedMesh is not supported. ` +
518
+ `Tried to change node "${node.id}" on element "${element.id}".`
519
+ );
520
+ }
521
+ });
522
+ if (this.variant.viewer.cloneMaterialsOnMutation) {
523
+ if (!has(node.metadata, 'dirty.material')) {
524
+ cloneTransformNodeMaterial(node);
525
+ }
526
+ if (!has(node.metadata, 'dirty.material.roughness')) {
527
+ // inject initial value and mark as dirty
528
+ injectNodeMetadata(node, { dirty: { material: { roughness: oldValue } } });
529
+ }
530
+ }
531
+ setMaterialRoughness(node, roughness);
532
+ });
533
+ },
534
+ ]);
535
+ this._parameterObservers.set(Parameter.HIGHLIGHT_COLOR, [
536
+ async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
537
+ // trigger Parameter.HIGHLIGHTED observers
538
+ this._parameterObservers.get(Parameter.HIGHLIGHTED)?.forEach(observer => {
539
+ observer(element, !!element.highlighted, !!element.highlighted);
540
+ });
541
+ },
542
+ ]);
543
+ this._parameterObservers.set(Parameter.HIGHLIGHT_ENABLED, [
544
+ async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
545
+ let curr;
546
+ try {
547
+ curr = Parameter.parseBoolean(newValue);
548
+ } catch (e) {
549
+ return;
550
+ }
551
+ switch (curr) {
552
+ case true:
553
+ if (element._highlightLayer) {
554
+ break;
555
+ }
556
+ element.highlightLayer = new HighlightLayer(
557
+ DottedPath.create(element.id).addPart('highlight').path,
558
+ element.variant.viewer.scene
559
+ );
560
+ break;
561
+ case false:
562
+ element.highlightLayer?.dispose();
563
+ break;
564
+ }
565
+ },
566
+ ]);
567
+ this._parameterObservers.set(Parameter.HIGHLIGHTED, [
568
+ async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
569
+ if (!element.inheritedParameters[Parameter.HIGHLIGHT_ENABLED]) {
570
+ return;
571
+ }
572
+ // trigger Parameter.HIGHLIGHT_ENABLED observers to ensure HighlightLayer
573
+ this._parameterObservers.get(Parameter.HIGHLIGHT_ENABLED)?.forEach(observer => {
574
+ observer(element, this.parameters[Parameter.HIGHLIGHT_ENABLED], true);
575
+ });
576
+ let highlighted;
577
+ try {
578
+ highlighted = Parameter.parseBoolean(newValue);
579
+ } catch (e) {
580
+ return;
581
+ }
582
+ // Add/Remove meshes to previously created highlight layers.
583
+ if (highlighted === true) {
584
+ element.nodes.forEach(node => {
585
+ assertTransformNode(node, (node: AbstractMesh) => {
586
+ if (node instanceof InstancedMesh) {
587
+ throw new Error(
588
+ `Changing parameter "${Parameter.HIGHLIGHTED}" ` +
589
+ `of an InstancedMesh is not supported. ` +
590
+ `Tried to change node "${node.id}" on element "${element.id}".`
591
+ );
592
+ }
593
+ });
594
+ let color = Color3.Green();
595
+ if (element.inheritedParameters[Parameter.HIGHLIGHT_COLOR]) {
596
+ color = Parameter.parseColor(element.inheritedParameters[Parameter.HIGHLIGHT_COLOR]);
597
+ }
598
+ if (typeof element._highlightLayer !== 'undefined') {
599
+ addToHighlightLayer(element._highlightLayer, color, node);
600
+ }
601
+ });
602
+ } else if (highlighted === false) {
603
+ element.nodes.forEach(node => {
604
+ if (typeof element._highlightLayer !== 'undefined') {
605
+ removeFromHighlightLayer(element._highlightLayer, node);
606
+ }
607
+ });
608
+ }
609
+ },
610
+ ]);
611
+ this._parameterObservers.set(Parameter.CAST_SHADOW, [
612
+ async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
613
+ let castShadow;
614
+ try {
615
+ castShadow = Parameter.parseBoolean(newValue);
616
+ } catch (e) {
617
+ return;
618
+ }
619
+ let lightCsl = element.inheritedParameters[Parameter.CAST_SHADOW_FROM_LIGHTS];
620
+ if (!lightCsl) {
621
+ lightCsl = element.variant.inheritedViewerLights.map(l => l.name).join(',');
622
+ }
623
+ if (castShadow === true) {
624
+ await this.castShadowValueHandler(lightCsl, addToShadowGenerator);
625
+ }
626
+ if (castShadow === false) {
627
+ await this.castShadowValueHandler(lightCsl, removeFromShadowGenerator);
628
+ }
629
+ },
630
+ ]);
631
+ this._parameterObservers.set(Parameter.CAST_SHADOW_FROM_LIGHTS, [
632
+ async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
633
+ // TODO: Possible performance issue in combination with CAST_SHADOW, since both observers are initially called
634
+ // when CAST_SHADOW and CAST_SHADOW_FROM_LIGHTS are defined in the spec.
635
+ const lightCsl = element.variant.inheritedViewerLights.map(l => l.name).join(',');
636
+ // cleanup all shadow generators
637
+ await this.castShadowValueHandler(lightCsl, removeFromShadowGenerator);
638
+ if (element.castShadow === true) {
639
+ // if newValue is undefined or '' then set newValue to lightCsl (use all lights)
640
+ if (!newValue) {
641
+ newValue = lightCsl;
642
+ }
643
+ await this.castShadowValueHandler(newValue, addToShadowGenerator);
644
+ }
645
+ },
646
+ ]);
647
+ this._parameterObservers.set(Parameter.RECEIVE_SHADOWS, [
648
+ async (element: Element, oldValue: ParameterValue, newValue: ParameterValue) => {
649
+ element.nodes.forEach(node => setReceiveShadows(node, Parameter.parseBoolean(newValue)));
650
+ },
651
+ ]);
652
+ return this;
653
+ }
654
+
655
+ /**
656
+ * Filter for nodes that are not defined or excluded in the `pathDefinitions`.
657
+ */
658
+ protected filterNode(node: TransformNode): boolean {
659
+ let includeTokens: string[] = [];
660
+ this.pathDefinitions.include.forEach(dottedPath => {
661
+ includeTokens = union(includeTokens, DottedPath.create(dottedPath).leafTokens);
662
+ });
663
+ const shallKeep = (dp: DottedPath) => {
664
+ const isDirectlyIncluded = !!includeTokens.find(_dp => _dp === dp.path);
665
+ const isSubOfIncluded = !!this.pathDefinitions.include.find(_dp => {
666
+ return dp.path.startsWith(`${_dp}${DottedPath.DELIMITER}`);
667
+ });
668
+ return isDirectlyIncluded || isSubOfIncluded;
669
+ };
670
+ const shallExclude = (dp: DottedPath) => {
671
+ if (!this.pathDefinitions.exclude) {
672
+ return false;
673
+ }
674
+ return !!this.pathDefinitions.exclude.find(_dp => dp.path === _dp);
675
+ };
676
+ return shallKeep(node.metadata.dottedPath) && !shallExclude(node.metadata.dottedPath);
677
+ }
678
+
679
+ /**
680
+ * Asserts whether all {@link pathDefinitions} link to a valid `Node` path.
681
+ * @protected
682
+ */
683
+ protected assertPathDefinitions() {
684
+ const dottedNodes = this.variant.inheritedDottedNodes;
685
+ if (dottedNodes.size === 0) {
686
+ throw new Error(`There are no mapped nodes for element "${this.id}".`);
687
+ }
688
+ const include = this.pathDefinitions.include.map(path => DottedPath.create(path).path);
689
+ const exclude = this.pathDefinitions.exclude?.map(path => DottedPath.create(path).path);
690
+ const keys = Array.from(dottedNodes.keys()).map(dottedPath => dottedPath.path);
691
+ union<string>(include, exclude).forEach(path => {
692
+ if (keys.indexOf(path) === -1) {
693
+ throw new Error(`Node with path "${path}" does not exist for element "${this.id}".`);
694
+ }
695
+ });
696
+ }
697
+
698
+ /**
699
+ * Handles callback for given light parameter.
700
+ */
701
+ private async castShadowValueHandler(lightCsl: ParameterValue, mutator: CallableFunction) {
702
+ let lights: Light[] = [];
703
+ for (const lightName of Parameter.parseCommaSeparatedList(lightCsl)) {
704
+ const viewerLight = await this.variant.getViewerLight(lightName);
705
+ if (viewerLight) {
706
+ lights.push(viewerLight.light);
707
+ }
708
+ }
709
+ const shadowGenerators = lights.map(light => light?.getShadowGenerator() as ShadowGenerator).filter(Boolean);
710
+ shadowGenerators.forEach(generator => {
711
+ this.nodes.forEach(node => {
712
+ mutator(generator, node);
713
+ });
714
+ });
715
+ }
716
+ }