@combeenation/3d-viewer 9.0.1 → 9.0.2-alpha2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +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 +667 -667
  8. package/dist/lib-cjs/api/classes/event.d.ts +401 -401
  9. package/dist/lib-cjs/api/classes/event.js +424 -424
  10. package/dist/lib-cjs/api/classes/eventBroadcaster.d.ts +26 -26
  11. package/dist/lib-cjs/api/classes/eventBroadcaster.js +49 -49
  12. package/dist/lib-cjs/api/classes/fuzzyMap.d.ts +7 -7
  13. package/dist/lib-cjs/api/classes/fuzzyMap.js +21 -21
  14. package/dist/lib-cjs/api/classes/parameter.d.ts +410 -410
  15. package/dist/lib-cjs/api/classes/parameter.js +642 -642
  16. package/dist/lib-cjs/api/classes/parameterObservable.d.ts +36 -36
  17. package/dist/lib-cjs/api/classes/parameterObservable.js +72 -72
  18. package/dist/lib-cjs/api/classes/parameterizable.d.ts +15 -15
  19. package/dist/lib-cjs/api/classes/parameterizable.js +102 -102
  20. package/dist/lib-cjs/api/classes/placementAnimation.d.ts +45 -45
  21. package/dist/lib-cjs/api/classes/placementAnimation.js +176 -176
  22. package/dist/lib-cjs/api/classes/variant.d.ts +261 -261
  23. package/dist/lib-cjs/api/classes/variant.js +870 -870
  24. package/dist/lib-cjs/api/classes/variantInstance.d.ts +53 -53
  25. package/dist/lib-cjs/api/classes/variantInstance.js +125 -125
  26. package/dist/lib-cjs/api/classes/variantParameterizable.d.ts +17 -17
  27. package/dist/lib-cjs/api/classes/variantParameterizable.js +86 -86
  28. package/dist/lib-cjs/api/classes/viewer.d.ts +213 -213
  29. package/dist/lib-cjs/api/classes/viewer.js +717 -717
  30. package/dist/lib-cjs/api/classes/viewerError.d.ts +43 -43
  31. package/dist/lib-cjs/api/classes/viewerError.js +55 -55
  32. package/dist/lib-cjs/api/classes/viewerLight.d.ts +66 -66
  33. package/dist/lib-cjs/api/classes/viewerLight.js +348 -348
  34. package/dist/lib-cjs/api/internal/lensRendering.d.ts +8 -8
  35. package/dist/lib-cjs/api/internal/lensRendering.js +11 -11
  36. package/dist/lib-cjs/api/internal/sceneSetup.d.ts +13 -13
  37. package/dist/lib-cjs/api/internal/sceneSetup.js +226 -226
  38. package/dist/lib-cjs/api/manager/animationManager.d.ts +30 -30
  39. package/dist/lib-cjs/api/manager/animationManager.js +126 -126
  40. package/dist/lib-cjs/api/manager/gltfExportManager.d.ts +103 -103
  41. package/dist/lib-cjs/api/manager/gltfExportManager.js +331 -325
  42. package/dist/lib-cjs/api/manager/gltfExportManager.js.map +1 -1
  43. package/dist/lib-cjs/api/manager/sceneManager.d.ts +33 -33
  44. package/dist/lib-cjs/api/manager/sceneManager.js +128 -128
  45. package/dist/lib-cjs/api/manager/tagManager.d.ts +118 -118
  46. package/dist/lib-cjs/api/manager/tagManager.js +535 -522
  47. package/dist/lib-cjs/api/manager/tagManager.js.map +1 -1
  48. package/dist/lib-cjs/api/manager/textureLoadManager.d.ts +22 -22
  49. package/dist/lib-cjs/api/manager/textureLoadManager.js +97 -97
  50. package/dist/lib-cjs/api/manager/variantInstanceManager.d.ts +106 -106
  51. package/dist/lib-cjs/api/manager/variantInstanceManager.js +290 -290
  52. package/dist/lib-cjs/api/store/specStorage.d.ts +32 -32
  53. package/dist/lib-cjs/api/store/specStorage.js +65 -65
  54. package/dist/lib-cjs/api/util/babylonHelper.d.ts +237 -237
  55. package/dist/lib-cjs/api/util/babylonHelper.js +825 -825
  56. package/dist/lib-cjs/api/util/globalTypes.d.ts +479 -479
  57. package/dist/lib-cjs/api/util/globalTypes.js +1 -1
  58. package/dist/lib-cjs/api/util/resourceHelper.d.ts +58 -58
  59. package/dist/lib-cjs/api/util/resourceHelper.js +214 -211
  60. package/dist/lib-cjs/api/util/resourceHelper.js.map +1 -1
  61. package/dist/lib-cjs/api/util/sceneLoaderHelper.d.ts +44 -44
  62. package/dist/lib-cjs/api/util/sceneLoaderHelper.js +175 -175
  63. package/dist/lib-cjs/api/util/stringHelper.d.ts +13 -13
  64. package/dist/lib-cjs/api/util/stringHelper.js +32 -32
  65. package/dist/lib-cjs/api/util/structureHelper.d.ts +9 -9
  66. package/dist/lib-cjs/api/util/structureHelper.js +60 -60
  67. package/dist/lib-cjs/buildinfo.json +3 -3
  68. package/dist/lib-cjs/commonjs.tsconfig.tsbuildinfo +1 -1
  69. package/dist/lib-cjs/index.d.ts +54 -54
  70. package/dist/lib-cjs/index.js +117 -117
  71. package/package.json +82 -82
  72. package/src/api/classes/animationInterface.ts +10 -10
  73. package/src/api/classes/dottedPath.ts +181 -181
  74. package/src/api/classes/element.ts +723 -723
  75. package/src/api/classes/event.ts +457 -457
  76. package/src/api/classes/eventBroadcaster.ts +52 -52
  77. package/src/api/classes/fuzzyMap.ts +21 -21
  78. package/src/api/classes/parameter.ts +686 -686
  79. package/src/api/classes/parameterObservable.ts +73 -73
  80. package/src/api/classes/parameterizable.ts +87 -87
  81. package/src/api/classes/placementAnimation.ts +162 -162
  82. package/src/api/classes/variant.ts +963 -963
  83. package/src/api/classes/variantInstance.ts +123 -123
  84. package/src/api/classes/variantParameterizable.ts +83 -83
  85. package/src/api/classes/viewer.ts +770 -770
  86. package/src/api/classes/viewerError.ts +63 -63
  87. package/src/api/classes/viewerLight.ts +339 -339
  88. package/src/api/internal/debugViewer.ts +90 -90
  89. package/src/api/internal/lensRendering.ts +9 -9
  90. package/src/api/internal/sceneSetup.ts +205 -205
  91. package/src/api/manager/animationManager.ts +143 -143
  92. package/src/api/manager/gltfExportManager.ts +310 -302
  93. package/src/api/manager/sceneManager.ts +134 -134
  94. package/src/api/manager/tagManager.ts +576 -564
  95. package/src/api/manager/textureLoadManager.ts +95 -95
  96. package/src/api/manager/variantInstanceManager.ts +306 -306
  97. package/src/api/store/specStorage.ts +68 -68
  98. package/src/api/util/babylonHelper.ts +913 -913
  99. package/src/api/util/globalTypes.ts +555 -555
  100. package/src/api/util/resourceHelper.ts +201 -198
  101. package/src/api/util/sceneLoaderHelper.ts +170 -170
  102. package/src/api/util/stringHelper.ts +30 -30
  103. package/src/api/util/structureHelper.ts +60 -60
  104. package/src/buildinfo.json +3 -3
  105. package/src/dev.ts +62 -62
  106. package/src/index.ts +103 -103
  107. package/src/types.d.ts +38 -38
@@ -1,326 +1,332 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
- var __rest = (this && this.__rest) || function (s, e) {
35
- var t = {};
36
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
37
- t[p] = s[p];
38
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
39
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
40
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
41
- t[p[i]] = s[p[i]];
42
- }
43
- return t;
44
- };
45
- Object.defineProperty(exports, "__esModule", { value: true });
46
- exports.GltfExportManager = void 0;
47
- const viewer_1 = require("../classes/viewer");
48
- const babylonHelper_1 = require("../util/babylonHelper");
49
- const structureHelper_1 = require("../util/structureHelper");
50
- const engine_1 = require("@babylonjs/core/Engines/engine");
51
- const sceneLoader_1 = require("@babylonjs/core/Loading/sceneLoader");
52
- const pbrMaterial_1 = require("@babylonjs/core/Materials/PBR/pbrMaterial");
53
- const math_color_1 = require("@babylonjs/core/Maths/math.color");
54
- const math_vector_1 = require("@babylonjs/core/Maths/math.vector");
55
- const abstractMesh_1 = require("@babylonjs/core/Meshes/abstractMesh");
56
- const mesh_1 = require("@babylonjs/core/Meshes/mesh");
57
- const transformNode_1 = require("@babylonjs/core/Meshes/transformNode");
58
- const sceneSerializer_1 = require("@babylonjs/core/Misc/sceneSerializer");
59
- const _2_0_1 = require("@babylonjs/serializers/glTF/2.0");
60
- const lodash_es_1 = require("lodash-es");
61
- class GltfExportManager {
62
- /**
63
- * Constructor.
64
- */
65
- constructor(viewer) {
66
- this.viewer = viewer;
67
- }
68
- /**
69
- * Creates an {@link GltfExportManager}.
70
- */
71
- static create(viewer) {
72
- return __awaiter(this, void 0, void 0, function* () {
73
- return new GltfExportManager(viewer);
74
- });
75
- }
76
- /**
77
- * Exports selected nodes to a file.
78
- * @param filename optional name of the exported .GLB file.
79
- * @param exportOptions export options to be merged with default options.\
80
- * `exportOptions.exchangeRefractionMaterials` defaults to `true` if not given.
81
- * @param optimizeForAR adjusts the exported GLB so that known AR issues get fixed automatically
82
- * @param excluded optional list of geometry (meshes, elements, variants, variantInstances) to be excluded from export
83
- */
84
- exportGlb(filename = 'glb-export.glb', _a = {}, optimizeForAR, excluded) {
85
- var { exchangeRefractionMaterials = true } = _a, exportOptions = __rest(_a, ["exchangeRefractionMaterials"]);
86
- if (optimizeForAR === void 0) { optimizeForAR = false; }
87
- return __awaiter(this, void 0, void 0, function* () {
88
- const { scene, sceneCopied } = yield this.exportPreProcess(exchangeRefractionMaterials, optimizeForAR);
89
- const glbData = yield _2_0_1.GLTF2Export.GLBAsync(scene, 'dummy', this.gltfExportOptions(exportOptions, excluded));
90
- this.exportPostProcess(scene, sceneCopied);
91
- const resBlob = glbData.glTFFiles['dummy.glb'];
92
- // check if result is valid, according to the typings this could also be a string
93
- if (resBlob instanceof Blob) {
94
- if (!filename.endsWith('.glb')) {
95
- filename += '.glb';
96
- }
97
- return new File([resBlob], filename);
98
- }
99
- else {
100
- // result was not a valid blob
101
- return undefined;
102
- }
103
- });
104
- }
105
- /**
106
- * Exports selected nodes to GLTF. This may result in more than one file, since textures are exported separately.
107
- * @param filename name of the main (text-based) .GLTF file referring to separate texture files.
108
- * @param exportOptions export options to be merged with default options.\
109
- * `exportOptions.exchangeRefractionMaterials` defaults to `true` if not given.
110
- * @param optimizeForAR adjusts the exported GLB so that known AR issues get fixed automatically
111
- * @param excluded optional list of geometry (meshes, elements, variants, variantInstances) to be excluded from export
112
- */
113
- exportGltfToFile(filename, _a = {}, optimizeForAR, excluded) {
114
- var { exchangeRefractionMaterials = true } = _a, exportOptions = __rest(_a, ["exchangeRefractionMaterials"]);
115
- if (optimizeForAR === void 0) { optimizeForAR = false; }
116
- return __awaiter(this, void 0, void 0, function* () {
117
- const { scene, sceneCopied } = yield this.exportPreProcess(exchangeRefractionMaterials, optimizeForAR);
118
- const gltf = yield _2_0_1.GLTF2Export.GLTFAsync(scene, filename, this.gltfExportOptions(exportOptions, excluded));
119
- gltf.downloadFiles();
120
- this.exportPostProcess(scene, sceneCopied);
121
- });
122
- }
123
- /**
124
- * Exports selected nodes to GLB. This results in one binary file.
125
- * @param filename name of the .GLB file.
126
- * @param exportOptions export options to be merged with default options.\
127
- * `exportOptions.exchangeRefractionMaterials` defaults to `true` if not given.
128
- * @param optimizeForAR adjusts the exported GLB so that known AR issues get fixed automatically
129
- * @param excluded optional list of geometry (meshes, elements, variants, variantInstances) to be excluded from export
130
- */
131
- exportGlbToFile(filename, _a = {}, optimizeForAR, excluded) {
132
- var { exchangeRefractionMaterials = true } = _a, exportOptions = __rest(_a, ["exchangeRefractionMaterials"]);
133
- if (optimizeForAR === void 0) { optimizeForAR = false; }
134
- return __awaiter(this, void 0, void 0, function* () {
135
- const { scene, sceneCopied } = yield this.exportPreProcess(exchangeRefractionMaterials, optimizeForAR);
136
- const glb = yield _2_0_1.GLTF2Export.GLBAsync(scene, filename, this.gltfExportOptions(exportOptions, excluded));
137
- glb.downloadFiles();
138
- this.exportPostProcess(scene, sceneCopied);
139
- });
140
- }
141
- /**
142
- * Gets predefined {@link IExportOptions } merged with given ones.
143
- */
144
- gltfExportOptions(mergeWithOptions = {}, excluded) {
145
- const defaultOptions = {
146
- shouldExportNode: function (node) {
147
- if (!node.isEnabled()) {
148
- return false;
149
- }
150
- if (node.name.startsWith(viewer_1.Viewer.BOUNDING_BOX_NAME)) {
151
- return false;
152
- }
153
- if (excluded && node instanceof transformNode_1.TransformNode && (0, structureHelper_1.isNodeIncludedInExclusionList)(node, excluded)) {
154
- return false;
155
- }
156
- return true;
157
- },
158
- };
159
- return (0, lodash_es_1.merge)({}, defaultOptions, mergeWithOptions);
160
- }
161
- /**
162
- * Stuff to be done before exporting to GLTF
163
- *
164
- * @returns Either the original scene if no adjustments have been made or a copied scene (which can be disposed after
165
- * the export) if adjustments have been made
166
- */
167
- exportPreProcess(exchangeRefractionMaterials, optimizeForAR) {
168
- return __awaiter(this, void 0, void 0, function* () {
169
- if (!exchangeRefractionMaterials && !optimizeForAR) {
170
- // no need to copy the scene if no adjustments have to be made
171
- return { scene: this.viewer.scene, sceneCopied: false };
172
- }
173
- // copy the scene for the GLB export improvements, so that the original viewer scene remains untouched
174
- const copiedScene = yield this.copyViewerScene();
175
- if (exchangeRefractionMaterials) {
176
- this.exchangeRefractionMaterials(copiedScene);
177
- }
178
- if (optimizeForAR) {
179
- this.setUniqueMeshNames(copiedScene);
180
- this.bakeTransformations(copiedScene);
181
- }
182
- return { scene: copiedScene, sceneCopied: true };
183
- });
184
- }
185
- /**
186
- * Create a copy of the viewer scene, which can be further processed and optimized for the GLB export.
187
- * There is no "scene.clone" function, therefore the scene is serialized and loaded again to achieve this result.
188
- */
189
- copyViewerScene() {
190
- return __awaiter(this, void 0, void 0, function* () {
191
- // required by the scene serializer
192
- yield Promise.resolve().then(() => __importStar(require(/* webpackChunkName: "physicsenginecomponent" */ '@babylonjs/core/Physics/physicsEngineComponent')));
193
- // copy scene function uses scene serializer, which can't handle "complex" data like classes, function or recursive
194
- // data structures in metadata
195
- // it basically does a `JSON.stringify` on the metadata
196
- // therefore the metadata has to be removed from the nodes before the copy process
197
- const metadataArr = this.extractMetadataOfAllNodes();
198
- // serialize the scene
199
- const serializedScene = yield sceneSerializer_1.SceneSerializer.SerializeAsync(this.viewer.scene);
200
- // set the cropped metadata back to the viewer scene nodes
201
- this.restoreMetadataOfAllNodes(metadataArr);
202
- // load the scene into an invisible "dummy" canvas
203
- const offscreenCanvas = new OffscreenCanvas(0, 0);
204
- const engine = new engine_1.Engine(offscreenCanvas);
205
- sceneLoader_1.SceneLoader.ShowLoadingScreen = false;
206
- const newScene = yield sceneLoader_1.SceneLoader.LoadAsync('', 'data:' + JSON.stringify(serializedScene), engine);
207
- // this is required for offscreen canvas, otherwise the scene dispose code throws when trying to remove the cursor
208
- // events
209
- newScene.doNotHandleCursors = true;
210
- return newScene;
211
- });
212
- }
213
- /**
214
- * Stuff to be done after the GLTF export
215
- */
216
- exportPostProcess(scene, disposeScene) {
217
- if (disposeScene) {
218
- // copied scene for GLB export is not needed anymore, therefore it can be removed
219
- scene.getEngine().dispose();
220
- }
221
- }
222
- /**
223
- * Remove all node metadata and return them in a map
224
- */
225
- extractMetadataOfAllNodes() {
226
- return this.viewer.scene.getNodes().reduce((accMetadataObj, curNode) => {
227
- const metadata = curNode.metadata;
228
- delete curNode.metadata;
229
- return Object.assign(Object.assign({}, accMetadataObj), { [curNode.uniqueId.toString()]: metadata });
230
- }, {});
231
- }
232
- /**
233
- * Restore node metadata from previously cropped metadata map
234
- */
235
- restoreMetadataOfAllNodes(metadataMap) {
236
- this.viewer.scene.getNodes().forEach(node => {
237
- const metadata = metadataMap[node.uniqueId.toString()];
238
- if (metadata) {
239
- node.metadata = metadata;
240
- }
241
- });
242
- }
243
- /**
244
- * Materials with refraction set are not exported properly.
245
- * Exchange all such (relevant) materials with a more export-friendly version
246
- */
247
- exchangeRefractionMaterials(scene) {
248
- for (const n of scene.getNodes()) {
249
- if (!(n instanceof abstractMesh_1.AbstractMesh))
250
- continue;
251
- if (!(n.material instanceof pbrMaterial_1.PBRMaterial))
252
- continue;
253
- if (!n.material.subSurface.isRefractionEnabled)
254
- continue;
255
- if (n.material.transparencyMode !== pbrMaterial_1.PBRMaterial.PBRMATERIAL_OPAQUE)
256
- continue;
257
- // if we're here, we have a node holding a material with set refraction whose transparencyMode is set to
258
- // PBRMATERIAL_OPAQUE
259
- n.material = this.createRefractionMaterialReplacement(n.material);
260
- }
261
- }
262
- /**
263
- * Create an export-friendly replacement material for a material using refraction.
264
- * @param mat Material to be replaced
265
- */
266
- createRefractionMaterialReplacement(mat) {
267
- // if we're dealing with a clone already, return it instead of cloning
268
- if (this.isMaterialClonedForExport(mat))
269
- return mat;
270
- // change material according to https://www.notion.so/combeenation/Glas-materials-don-t-look-glasy-after-export-d5fda2c6515e4420a8772744d3e6b460
271
- const clonedMaterial = mat.clone(mat.name); // clone material. clone uses same name
272
- clonedMaterial.metadata = Object.assign(Object.assign({}, mat.metadata), { [GltfExportManager._CLONED_FROM_MAT_METADATA_PROPERTY]: mat.uniqueId }); // create shallow copy of metadata on clone. see https://forum.babylonjs.com/t/the-metadata-of-the-mesh-cloned-by-the-instantiatemodelstoscene-method-is-a-shallow-copy/21563
273
- clonedMaterial.refractionTexture = null;
274
- clonedMaterial.metallicReflectanceTexture = null; // is this the correct one for metallic roughness?
275
- clonedMaterial.alpha = 0.7;
276
- clonedMaterial.albedoColor = new math_color_1.Color3(0.3, 0.3, 0.3);
277
- clonedMaterial.transparencyMode = pbrMaterial_1.PBRMaterial.PBRMATERIAL_ALPHABLEND;
278
- clonedMaterial.metallic = 0.65;
279
- clonedMaterial.roughness = 0.15;
280
- return clonedMaterial;
281
- }
282
- /**
283
- * Inspect if a material was temporarily cloned for GLB export
284
- * @param mat Material to be inspected
285
- */
286
- isMaterialClonedForExport(mat) {
287
- return (0, lodash_es_1.has)(mat.metadata, GltfExportManager._CLONED_FROM_MAT_METADATA_PROPERTY);
288
- }
289
- /**
290
- * Set unique mesh names for GLB export.
291
- * Duplicate names lead to problems in AR on iOS devices.
292
- */
293
- setUniqueMeshNames(scene) {
294
- const allNodes = scene.getNodes().filter(node => node instanceof transformNode_1.TransformNode);
295
- allNodes.forEach(currMesh => {
296
- (0, babylonHelper_1.injectMetadata)(currMesh, { [GltfExportManager.NAME_BEFORE_EXPORT_METADATA_PROPERTY]: currMesh.name }, false);
297
- currMesh.name = `${currMesh.name}_${currMesh.uniqueId}`;
298
- });
299
- }
300
- /**
301
- * Stores the effect of all mesh transformations in their geometry and reset the transformation afterwards.
302
- * In this way negative scalings which lead to problems in AR on iOS devices can be eliminated.
303
- */
304
- bakeTransformations(scene) {
305
- scene.meshes.forEach(mesh => {
306
- if (mesh instanceof mesh_1.Mesh && mesh.geometry) {
307
- // geometries can be shared across multiple meshes, first make them unique to avoid side-effects
308
- mesh.makeGeometryUnique();
309
- // this is the core functionality for storing the transformation data in the mesh geometry
310
- mesh.bakeCurrentTransformIntoVertices();
311
- }
312
- });
313
- // some nodes (mostly transform nodes), are not affected by the baking algorithm since they have no geometry
314
- // => reset their transformation manually
315
- const allNodes = scene.getNodes().filter(node => node instanceof transformNode_1.TransformNode);
316
- allNodes.forEach(node => {
317
- node.position = new math_vector_1.Vector3(0, 0, 0);
318
- node.rotation = new math_vector_1.Vector3(0, 0, 0);
319
- node.scaling = new math_vector_1.Vector3(1, 1, 1);
320
- });
321
- }
322
- }
323
- exports.GltfExportManager = GltfExportManager;
324
- GltfExportManager._CLONED_FROM_MAT_METADATA_PROPERTY = 'clonedFrom';
325
- GltfExportManager.NAME_BEFORE_EXPORT_METADATA_PROPERTY = 'nameBeforeExport';
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __rest = (this && this.__rest) || function (s, e) {
35
+ var t = {};
36
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
37
+ t[p] = s[p];
38
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
39
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
40
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
41
+ t[p[i]] = s[p[i]];
42
+ }
43
+ return t;
44
+ };
45
+ Object.defineProperty(exports, "__esModule", { value: true });
46
+ exports.GltfExportManager = void 0;
47
+ const viewer_1 = require("../classes/viewer");
48
+ const babylonHelper_1 = require("../util/babylonHelper");
49
+ const structureHelper_1 = require("../util/structureHelper");
50
+ const engine_1 = require("@babylonjs/core/Engines/engine");
51
+ const sceneLoader_1 = require("@babylonjs/core/Loading/sceneLoader");
52
+ const pbrMaterial_1 = require("@babylonjs/core/Materials/PBR/pbrMaterial");
53
+ const math_color_1 = require("@babylonjs/core/Maths/math.color");
54
+ const math_vector_1 = require("@babylonjs/core/Maths/math.vector");
55
+ const abstractMesh_1 = require("@babylonjs/core/Meshes/abstractMesh");
56
+ const mesh_1 = require("@babylonjs/core/Meshes/mesh");
57
+ const transformNode_1 = require("@babylonjs/core/Meshes/transformNode");
58
+ const sceneSerializer_1 = require("@babylonjs/core/Misc/sceneSerializer");
59
+ const _2_0_1 = require("@babylonjs/serializers/glTF/2.0");
60
+ const lodash_es_1 = require("lodash-es");
61
+ class GltfExportManager {
62
+ /**
63
+ * Constructor.
64
+ */
65
+ constructor(viewer) {
66
+ this.viewer = viewer;
67
+ }
68
+ /**
69
+ * Creates an {@link GltfExportManager}.
70
+ */
71
+ static create(viewer) {
72
+ return __awaiter(this, void 0, void 0, function* () {
73
+ return new GltfExportManager(viewer);
74
+ });
75
+ }
76
+ /**
77
+ * Exports selected nodes to a file.
78
+ * @param filename optional name of the exported .GLB file.
79
+ * @param exportOptions export options to be merged with default options.\
80
+ * `exportOptions.exchangeRefractionMaterials` defaults to `true` if not given.
81
+ * @param optimizeForAR adjusts the exported GLB so that known AR issues get fixed automatically
82
+ * @param excluded optional list of geometry (meshes, elements, variants, variantInstances) to be excluded from export
83
+ */
84
+ exportGlb(filename = 'glb-export.glb', _a = {}, optimizeForAR, excluded) {
85
+ var { exchangeRefractionMaterials = true } = _a, exportOptions = __rest(_a, ["exchangeRefractionMaterials"]);
86
+ if (optimizeForAR === void 0) { optimizeForAR = false; }
87
+ return __awaiter(this, void 0, void 0, function* () {
88
+ const { scene, sceneCopied } = yield this.exportPreProcess(exchangeRefractionMaterials, optimizeForAR);
89
+ const glbData = yield _2_0_1.GLTF2Export.GLBAsync(scene, 'dummy', this.gltfExportOptions(exportOptions, excluded));
90
+ this.exportPostProcess(scene, sceneCopied);
91
+ const resBlob = glbData.glTFFiles['dummy.glb'];
92
+ // check if result is valid, according to the typings this could also be a string
93
+ if (resBlob instanceof Blob) {
94
+ if (!filename.endsWith('.glb')) {
95
+ filename += '.glb';
96
+ }
97
+ return new File([resBlob], filename);
98
+ }
99
+ else {
100
+ // result was not a valid blob
101
+ return undefined;
102
+ }
103
+ });
104
+ }
105
+ /**
106
+ * Exports selected nodes to GLTF. This may result in more than one file, since textures are exported separately.
107
+ * @param filename name of the main (text-based) .GLTF file referring to separate texture files.
108
+ * @param exportOptions export options to be merged with default options.\
109
+ * `exportOptions.exchangeRefractionMaterials` defaults to `true` if not given.
110
+ * @param optimizeForAR adjusts the exported GLB so that known AR issues get fixed automatically
111
+ * @param excluded optional list of geometry (meshes, elements, variants, variantInstances) to be excluded from export
112
+ */
113
+ exportGltfToFile(filename, _a = {}, optimizeForAR, excluded) {
114
+ var { exchangeRefractionMaterials = true } = _a, exportOptions = __rest(_a, ["exchangeRefractionMaterials"]);
115
+ if (optimizeForAR === void 0) { optimizeForAR = false; }
116
+ return __awaiter(this, void 0, void 0, function* () {
117
+ const { scene, sceneCopied } = yield this.exportPreProcess(exchangeRefractionMaterials, optimizeForAR);
118
+ const gltf = yield _2_0_1.GLTF2Export.GLTFAsync(scene, filename, this.gltfExportOptions(exportOptions, excluded));
119
+ gltf.downloadFiles();
120
+ this.exportPostProcess(scene, sceneCopied);
121
+ });
122
+ }
123
+ /**
124
+ * Exports selected nodes to GLB. This results in one binary file.
125
+ * @param filename name of the .GLB file.
126
+ * @param exportOptions export options to be merged with default options.\
127
+ * `exportOptions.exchangeRefractionMaterials` defaults to `true` if not given.
128
+ * @param optimizeForAR adjusts the exported GLB so that known AR issues get fixed automatically
129
+ * @param excluded optional list of geometry (meshes, elements, variants, variantInstances) to be excluded from export
130
+ */
131
+ exportGlbToFile(filename, _a = {}, optimizeForAR, excluded) {
132
+ var { exchangeRefractionMaterials = true } = _a, exportOptions = __rest(_a, ["exchangeRefractionMaterials"]);
133
+ if (optimizeForAR === void 0) { optimizeForAR = false; }
134
+ return __awaiter(this, void 0, void 0, function* () {
135
+ const { scene, sceneCopied } = yield this.exportPreProcess(exchangeRefractionMaterials, optimizeForAR);
136
+ const glb = yield _2_0_1.GLTF2Export.GLBAsync(scene, filename, this.gltfExportOptions(exportOptions, excluded));
137
+ glb.downloadFiles();
138
+ this.exportPostProcess(scene, sceneCopied);
139
+ });
140
+ }
141
+ /**
142
+ * Gets predefined {@link IExportOptions } merged with given ones.
143
+ */
144
+ gltfExportOptions(mergeWithOptions = {}, excluded) {
145
+ const defaultOptions = {
146
+ shouldExportNode: function (node) {
147
+ if (!node.isEnabled()) {
148
+ return false;
149
+ }
150
+ if (node.name.startsWith(viewer_1.Viewer.BOUNDING_BOX_NAME)) {
151
+ return false;
152
+ }
153
+ if (excluded && node instanceof transformNode_1.TransformNode && (0, structureHelper_1.isNodeIncludedInExclusionList)(node, excluded)) {
154
+ return false;
155
+ }
156
+ return true;
157
+ },
158
+ };
159
+ return (0, lodash_es_1.merge)({}, defaultOptions, mergeWithOptions);
160
+ }
161
+ /**
162
+ * Stuff to be done before exporting to GLTF
163
+ *
164
+ * @returns Either the original scene if no adjustments have been made or a copied scene (which can be disposed after
165
+ * the export) if adjustments have been made
166
+ */
167
+ exportPreProcess(exchangeRefractionMaterials, optimizeForAR) {
168
+ return __awaiter(this, void 0, void 0, function* () {
169
+ if (!exchangeRefractionMaterials && !optimizeForAR) {
170
+ // no need to copy the scene if no adjustments have to be made
171
+ return { scene: this.viewer.scene, sceneCopied: false };
172
+ }
173
+ // copy the scene for the GLB export improvements, so that the original viewer scene remains untouched
174
+ const copiedScene = yield this.copyViewerScene();
175
+ if (exchangeRefractionMaterials) {
176
+ this.exchangeRefractionMaterials(copiedScene);
177
+ }
178
+ if (optimizeForAR) {
179
+ this.setUniqueMeshNames(copiedScene);
180
+ this.bakeTransformations(copiedScene);
181
+ }
182
+ return { scene: copiedScene, sceneCopied: true };
183
+ });
184
+ }
185
+ /**
186
+ * Create a copy of the viewer scene, which can be further processed and optimized for the GLB export.
187
+ * There is no "scene.clone" function, therefore the scene is serialized and loaded again to achieve this result.
188
+ */
189
+ copyViewerScene() {
190
+ return __awaiter(this, void 0, void 0, function* () {
191
+ // required by the scene serializer
192
+ yield Promise.resolve().then(() => __importStar(require(/* webpackChunkName: "physicsenginecomponent" */ '@babylonjs/core/Physics/physicsEngineComponent')));
193
+ // copy scene function uses scene serializer, which can't handle "complex" data like classes, function or recursive
194
+ // data structures in metadata
195
+ // it basically does a `JSON.stringify` on the metadata
196
+ // therefore the metadata has to be removed from the nodes before the copy process
197
+ const metadataArr = this.extractMetadataOfAllNodes();
198
+ // serialize the scene
199
+ const serializedScene = yield sceneSerializer_1.SceneSerializer.SerializeAsync(this.viewer.scene);
200
+ // set the cropped metadata back to the viewer scene nodes
201
+ this.restoreMetadataOfAllNodes(metadataArr);
202
+ // load the scene into an invisible "dummy" canvas
203
+ const offscreenCanvas = new HTMLCanvasElement();
204
+ const engine = new engine_1.Engine(offscreenCanvas);
205
+ // engine.getCaps().maxTextureSize = 1024;
206
+ console.log('!!! using HTML Canvas for Export !!!');
207
+ sceneLoader_1.SceneLoader.ShowLoadingScreen = false;
208
+ const newScene = yield sceneLoader_1.SceneLoader.LoadAsync('', 'data:' + JSON.stringify(serializedScene), engine);
209
+ // this is required for offscreen canvas, otherwise the scene dispose code throws when trying to remove the cursor
210
+ // events
211
+ newScene.doNotHandleCursors = true;
212
+ console.log('old scene');
213
+ this.viewer.scene.textures.map(texture => { var _a; return console.log((_a = texture._texture) === null || _a === void 0 ? void 0 : _a.width); });
214
+ console.log('new scene');
215
+ newScene.textures.map(texture => { var _a; return console.log((_a = texture._texture) === null || _a === void 0 ? void 0 : _a.width); });
216
+ return newScene;
217
+ });
218
+ }
219
+ /**
220
+ * Stuff to be done after the GLTF export
221
+ */
222
+ exportPostProcess(scene, disposeScene) {
223
+ if (disposeScene) {
224
+ // copied scene for GLB export is not needed anymore, therefore it can be removed
225
+ scene.getEngine().dispose();
226
+ }
227
+ }
228
+ /**
229
+ * Remove all node metadata and return them in a map
230
+ */
231
+ extractMetadataOfAllNodes() {
232
+ return this.viewer.scene.getNodes().reduce((accMetadataObj, curNode) => {
233
+ const metadata = curNode.metadata;
234
+ delete curNode.metadata;
235
+ return Object.assign(Object.assign({}, accMetadataObj), { [curNode.uniqueId.toString()]: metadata });
236
+ }, {});
237
+ }
238
+ /**
239
+ * Restore node metadata from previously cropped metadata map
240
+ */
241
+ restoreMetadataOfAllNodes(metadataMap) {
242
+ this.viewer.scene.getNodes().forEach(node => {
243
+ const metadata = metadataMap[node.uniqueId.toString()];
244
+ if (metadata) {
245
+ node.metadata = metadata;
246
+ }
247
+ });
248
+ }
249
+ /**
250
+ * Materials with refraction set are not exported properly.
251
+ * Exchange all such (relevant) materials with a more export-friendly version
252
+ */
253
+ exchangeRefractionMaterials(scene) {
254
+ for (const n of scene.getNodes()) {
255
+ if (!(n instanceof abstractMesh_1.AbstractMesh))
256
+ continue;
257
+ if (!(n.material instanceof pbrMaterial_1.PBRMaterial))
258
+ continue;
259
+ if (!n.material.subSurface.isRefractionEnabled)
260
+ continue;
261
+ if (n.material.transparencyMode !== pbrMaterial_1.PBRMaterial.PBRMATERIAL_OPAQUE)
262
+ continue;
263
+ // if we're here, we have a node holding a material with set refraction whose transparencyMode is set to
264
+ // PBRMATERIAL_OPAQUE
265
+ n.material = this.createRefractionMaterialReplacement(n.material);
266
+ }
267
+ }
268
+ /**
269
+ * Create an export-friendly replacement material for a material using refraction.
270
+ * @param mat Material to be replaced
271
+ */
272
+ createRefractionMaterialReplacement(mat) {
273
+ // if we're dealing with a clone already, return it instead of cloning
274
+ if (this.isMaterialClonedForExport(mat))
275
+ return mat;
276
+ // change material according to https://www.notion.so/combeenation/Glas-materials-don-t-look-glasy-after-export-d5fda2c6515e4420a8772744d3e6b460
277
+ const clonedMaterial = mat.clone(mat.name); // clone material. clone uses same name
278
+ clonedMaterial.metadata = Object.assign(Object.assign({}, mat.metadata), { [GltfExportManager._CLONED_FROM_MAT_METADATA_PROPERTY]: mat.uniqueId }); // create shallow copy of metadata on clone. see https://forum.babylonjs.com/t/the-metadata-of-the-mesh-cloned-by-the-instantiatemodelstoscene-method-is-a-shallow-copy/21563
279
+ clonedMaterial.refractionTexture = null;
280
+ clonedMaterial.metallicReflectanceTexture = null; // is this the correct one for metallic roughness?
281
+ clonedMaterial.alpha = 0.7;
282
+ clonedMaterial.albedoColor = new math_color_1.Color3(0.3, 0.3, 0.3);
283
+ clonedMaterial.transparencyMode = pbrMaterial_1.PBRMaterial.PBRMATERIAL_ALPHABLEND;
284
+ clonedMaterial.metallic = 0.65;
285
+ clonedMaterial.roughness = 0.15;
286
+ return clonedMaterial;
287
+ }
288
+ /**
289
+ * Inspect if a material was temporarily cloned for GLB export
290
+ * @param mat Material to be inspected
291
+ */
292
+ isMaterialClonedForExport(mat) {
293
+ return (0, lodash_es_1.has)(mat.metadata, GltfExportManager._CLONED_FROM_MAT_METADATA_PROPERTY);
294
+ }
295
+ /**
296
+ * Set unique mesh names for GLB export.
297
+ * Duplicate names lead to problems in AR on iOS devices.
298
+ */
299
+ setUniqueMeshNames(scene) {
300
+ const allNodes = scene.getNodes().filter(node => node instanceof transformNode_1.TransformNode);
301
+ allNodes.forEach(currMesh => {
302
+ (0, babylonHelper_1.injectMetadata)(currMesh, { [GltfExportManager.NAME_BEFORE_EXPORT_METADATA_PROPERTY]: currMesh.name }, false);
303
+ currMesh.name = `${currMesh.name}_${currMesh.uniqueId}`;
304
+ });
305
+ }
306
+ /**
307
+ * Stores the effect of all mesh transformations in their geometry and reset the transformation afterwards.
308
+ * In this way negative scalings which lead to problems in AR on iOS devices can be eliminated.
309
+ */
310
+ bakeTransformations(scene) {
311
+ scene.meshes.forEach(mesh => {
312
+ if (mesh instanceof mesh_1.Mesh && mesh.geometry) {
313
+ // geometries can be shared across multiple meshes, first make them unique to avoid side-effects
314
+ mesh.makeGeometryUnique();
315
+ // this is the core functionality for storing the transformation data in the mesh geometry
316
+ mesh.bakeCurrentTransformIntoVertices();
317
+ }
318
+ });
319
+ // some nodes (mostly transform nodes), are not affected by the baking algorithm since they have no geometry
320
+ // => reset their transformation manually
321
+ const allNodes = scene.getNodes().filter(node => node instanceof transformNode_1.TransformNode);
322
+ allNodes.forEach(node => {
323
+ node.position = new math_vector_1.Vector3(0, 0, 0);
324
+ node.rotation = new math_vector_1.Vector3(0, 0, 0);
325
+ node.scaling = new math_vector_1.Vector3(1, 1, 1);
326
+ });
327
+ }
328
+ }
329
+ exports.GltfExportManager = GltfExportManager;
330
+ GltfExportManager._CLONED_FROM_MAT_METADATA_PROPERTY = 'clonedFrom';
331
+ GltfExportManager.NAME_BEFORE_EXPORT_METADATA_PROPERTY = 'nameBeforeExport';
326
332
  //# sourceMappingURL=gltfExportManager.js.map