assetContainer.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. import { AbstractScene } from "./abstractScene";
  2. import { Scene } from "./scene";
  3. import { Mesh } from "./Meshes/mesh";
  4. import { TransformNode } from './Meshes/transformNode';
  5. import { Skeleton } from './Bones/skeleton';
  6. import { AnimationGroup } from './Animations/animationGroup';
  7. import { Animatable } from './Animations/animatable';
  8. import { AbstractMesh } from './Meshes/abstractMesh';
  9. import { MultiMaterial } from './Materials/multiMaterial';
  10. import { Material } from './Materials/material';
  11. import { Logger } from './Misc/logger';
  12. import { EngineStore } from './Engines/engineStore';
  13. import { Nullable } from './types';
  14. import { Node } from './node';
  15. /**
  16. * Set of assets to keep when moving a scene into an asset container.
  17. */
  18. export class KeepAssets extends AbstractScene { }
  19. /**
  20. * Class used to store the output of the AssetContainer.instantiateAllMeshesToScene function
  21. */
  22. export class InstantiatedEntries {
  23. /**
  24. * List of new root nodes (eg. nodes with no parent)
  25. */
  26. public rootNodes: TransformNode[] = [];
  27. /**
  28. * List of new skeletons
  29. */
  30. public skeletons: Skeleton[] = [];
  31. /**
  32. * List of new animation groups
  33. */
  34. public animationGroups: AnimationGroup[] = [];
  35. }
  36. /**
  37. * Container with a set of assets that can be added or removed from a scene.
  38. */
  39. export class AssetContainer extends AbstractScene {
  40. private _wasAddedToScene = false;
  41. /**
  42. * The scene the AssetContainer belongs to.
  43. */
  44. public scene: Scene;
  45. /**
  46. * Instantiates an AssetContainer.
  47. * @param scene The scene the AssetContainer belongs to.
  48. */
  49. constructor(scene: Scene) {
  50. super();
  51. this.scene = scene;
  52. this["sounds"] = [];
  53. this["effectLayers"] = [];
  54. this["layers"] = [];
  55. this["lensFlareSystems"] = [];
  56. this["proceduralTextures"] = [];
  57. this["reflectionProbes"] = [];
  58. scene.onDisposeObservable.add(() => {
  59. if (!this._wasAddedToScene) {
  60. this.dispose();
  61. }
  62. });
  63. }
  64. /**
  65. * Instantiate or clone all meshes and add the new ones to the scene.
  66. * Skeletons and animation groups will all be cloned
  67. * @param nameFunction defines an optional function used to get new names for clones
  68. * @param cloneMaterials defines an optional boolean that defines if materials must be cloned as well (false by default)
  69. * @returns a list of rootNodes, skeletons and aniamtion groups that were duplicated
  70. */
  71. public instantiateModelsToScene(nameFunction?: (sourceName: string) => string, cloneMaterials = false): InstantiatedEntries {
  72. let convertionMap: {[key: number]: number} = {};
  73. let storeMap: {[key: number]: any} = {};
  74. let result = new InstantiatedEntries();
  75. let alreadySwappedSkeletons: Skeleton[] = [];
  76. let alreadySwappedMaterials: Material[] = [];
  77. let options = {
  78. doNotInstantiate: true
  79. };
  80. let onClone = (source: TransformNode, clone: TransformNode) => {
  81. convertionMap[source.uniqueId] = clone.uniqueId;
  82. storeMap[clone.uniqueId] = clone;
  83. if (nameFunction) {
  84. clone.name = nameFunction(source.name);
  85. }
  86. if (clone instanceof Mesh) {
  87. let clonedMesh = clone as Mesh;
  88. if (clonedMesh.morphTargetManager) {
  89. let oldMorphTargetManager = (source as Mesh).morphTargetManager!;
  90. clonedMesh.morphTargetManager = oldMorphTargetManager.clone();
  91. for (var index = 0; index < oldMorphTargetManager.numTargets; index++) {
  92. let oldTarget = oldMorphTargetManager.getTarget(index);
  93. let newTarget = clonedMesh.morphTargetManager.getTarget(index);
  94. convertionMap[oldTarget.uniqueId] = newTarget.uniqueId;
  95. storeMap[newTarget.uniqueId] = newTarget;
  96. }
  97. }
  98. }
  99. };
  100. this.transformNodes.forEach((o) => {
  101. if (!o.parent) {
  102. let newOne = o.instantiateHierarchy(null, options, (source, clone) => {
  103. onClone(source, clone);
  104. });
  105. if (newOne) {
  106. result.rootNodes.push(newOne);
  107. }
  108. }
  109. });
  110. this.meshes.forEach((o) => {
  111. if (!o.parent) {
  112. let newOne = o.instantiateHierarchy(null, options, (source, clone) => {
  113. onClone(source, clone);
  114. if ((clone as any).material) {
  115. let mesh = clone as AbstractMesh;
  116. if (mesh.material) {
  117. if (cloneMaterials) {
  118. let sourceMaterial = (source as AbstractMesh).material!;
  119. if (alreadySwappedMaterials.indexOf(sourceMaterial) === -1) {
  120. let swap = sourceMaterial.clone(nameFunction ? nameFunction(sourceMaterial.name) : "Clone of " + sourceMaterial.name)!;
  121. alreadySwappedMaterials.push(sourceMaterial);
  122. convertionMap[sourceMaterial.uniqueId] = swap.uniqueId;
  123. storeMap[swap.uniqueId] = swap;
  124. if (sourceMaterial.getClassName() === "MultiMaterial") {
  125. let multi = sourceMaterial as MultiMaterial;
  126. for (var material of multi.subMaterials) {
  127. if (!material) {
  128. continue;
  129. }
  130. swap = material.clone(nameFunction ? nameFunction(material.name) : "Clone of " + material.name)!;
  131. alreadySwappedMaterials.push(material);
  132. convertionMap[material.uniqueId] = swap.uniqueId;
  133. storeMap[swap.uniqueId] = swap;
  134. }
  135. }
  136. }
  137. mesh.material = storeMap[convertionMap[sourceMaterial.uniqueId]];
  138. } else {
  139. if (mesh.material.getClassName() === "MultiMaterial") {
  140. if (this.scene.multiMaterials.indexOf(mesh.material as MultiMaterial) === -1) {
  141. this.scene.addMultiMaterial(mesh.material as MultiMaterial);
  142. }
  143. } else {
  144. if (this.scene.materials.indexOf(mesh.material) === -1) {
  145. this.scene.addMaterial(mesh.material);
  146. }
  147. }
  148. }
  149. }
  150. }
  151. });
  152. if (newOne) {
  153. result.rootNodes.push(newOne);
  154. }
  155. }
  156. });
  157. this.skeletons.forEach((s) => {
  158. let clone = s.clone(nameFunction ? nameFunction(s.name) : "Clone of " + s.name);
  159. if (s.overrideMesh) {
  160. clone.overrideMesh = storeMap[convertionMap[s.overrideMesh.uniqueId]];
  161. }
  162. for (var m of this.meshes) {
  163. if (m.skeleton === s && !m.isAnInstance) {
  164. let copy = storeMap[convertionMap[m.uniqueId]];
  165. (copy as Mesh).skeleton = clone;
  166. if (alreadySwappedSkeletons.indexOf(clone) !== -1) {
  167. continue;
  168. }
  169. alreadySwappedSkeletons.push(clone);
  170. // Check if bones are mesh linked
  171. for (var bone of clone.bones) {
  172. if (bone._linkedTransformNode) {
  173. bone._linkedTransformNode = storeMap[convertionMap[bone._linkedTransformNode.uniqueId]];
  174. }
  175. }
  176. }
  177. }
  178. result.skeletons.push(clone);
  179. });
  180. this.animationGroups.forEach((o) => {
  181. let clone = o.clone(o.name, (oldTarget) => {
  182. let newTarget = storeMap[convertionMap[oldTarget.uniqueId]];
  183. return newTarget || oldTarget;
  184. });
  185. result.animationGroups.push(clone);
  186. });
  187. return result;
  188. }
  189. /**
  190. * Adds all the assets from the container to the scene.
  191. */
  192. public addAllToScene() {
  193. this._wasAddedToScene = true;
  194. this.cameras.forEach((o) => {
  195. this.scene.addCamera(o);
  196. });
  197. this.lights.forEach((o) => {
  198. this.scene.addLight(o);
  199. });
  200. this.meshes.forEach((o) => {
  201. this.scene.addMesh(o);
  202. });
  203. this.skeletons.forEach((o) => {
  204. this.scene.addSkeleton(o);
  205. });
  206. this.animations.forEach((o) => {
  207. this.scene.addAnimation(o);
  208. });
  209. this.animationGroups.forEach((o) => {
  210. this.scene.addAnimationGroup(o);
  211. });
  212. this.multiMaterials.forEach((o) => {
  213. this.scene.addMultiMaterial(o);
  214. });
  215. this.materials.forEach((o) => {
  216. this.scene.addMaterial(o);
  217. });
  218. this.morphTargetManagers.forEach((o) => {
  219. this.scene.addMorphTargetManager(o);
  220. });
  221. this.geometries.forEach((o) => {
  222. this.scene.addGeometry(o);
  223. });
  224. this.transformNodes.forEach((o) => {
  225. this.scene.addTransformNode(o);
  226. });
  227. this.actionManagers.forEach((o) => {
  228. this.scene.addActionManager(o);
  229. });
  230. this.textures.forEach((o) => {
  231. this.scene.addTexture(o);
  232. });
  233. this.reflectionProbes.forEach((o) => {
  234. this.scene.addReflectionProbe(o);
  235. });
  236. if (this.environmentTexture) {
  237. this.scene.environmentTexture = this.environmentTexture;
  238. }
  239. for (let component of this.scene._serializableComponents) {
  240. component.addFromContainer(this);
  241. }
  242. }
  243. /**
  244. * Removes all the assets in the container from the scene
  245. */
  246. public removeAllFromScene() {
  247. this._wasAddedToScene = false;
  248. this.cameras.forEach((o) => {
  249. this.scene.removeCamera(o);
  250. });
  251. this.lights.forEach((o) => {
  252. this.scene.removeLight(o);
  253. });
  254. this.meshes.forEach((o) => {
  255. this.scene.removeMesh(o);
  256. });
  257. this.skeletons.forEach((o) => {
  258. this.scene.removeSkeleton(o);
  259. });
  260. this.animations.forEach((o) => {
  261. this.scene.removeAnimation(o);
  262. });
  263. this.animationGroups.forEach((o) => {
  264. this.scene.removeAnimationGroup(o);
  265. });
  266. this.multiMaterials.forEach((o) => {
  267. this.scene.removeMultiMaterial(o);
  268. });
  269. this.materials.forEach((o) => {
  270. this.scene.removeMaterial(o);
  271. });
  272. this.morphTargetManagers.forEach((o) => {
  273. this.scene.removeMorphTargetManager(o);
  274. });
  275. this.geometries.forEach((o) => {
  276. this.scene.removeGeometry(o);
  277. });
  278. this.transformNodes.forEach((o) => {
  279. this.scene.removeTransformNode(o);
  280. });
  281. this.actionManagers.forEach((o) => {
  282. this.scene.removeActionManager(o);
  283. });
  284. this.textures.forEach((o) => {
  285. this.scene.removeTexture(o);
  286. });
  287. this.reflectionProbes.forEach((o) => {
  288. this.scene.removeReflectionProbe(o);
  289. });
  290. if (this.environmentTexture === this.scene.environmentTexture) {
  291. this.scene.environmentTexture = null;
  292. }
  293. for (let component of this.scene._serializableComponents) {
  294. component.removeFromContainer(this);
  295. }
  296. }
  297. /**
  298. * Disposes all the assets in the container
  299. */
  300. public dispose() {
  301. this.cameras.forEach((o) => {
  302. o.dispose();
  303. });
  304. this.cameras = [];
  305. this.lights.forEach((o) => {
  306. o.dispose();
  307. });
  308. this.lights = [];
  309. this.meshes.forEach((o) => {
  310. o.dispose();
  311. });
  312. this.meshes = [];
  313. this.skeletons.forEach((o) => {
  314. o.dispose();
  315. });
  316. this.skeletons = [];
  317. this.animationGroups.forEach((o) => {
  318. o.dispose();
  319. });
  320. this.animationGroups = [];
  321. this.multiMaterials.forEach((o) => {
  322. o.dispose();
  323. });
  324. this.multiMaterials = [];
  325. this.materials.forEach((o) => {
  326. o.dispose();
  327. });
  328. this.materials = [];
  329. this.geometries.forEach((o) => {
  330. o.dispose();
  331. });
  332. this.geometries = [];
  333. this.transformNodes.forEach((o) => {
  334. o.dispose();
  335. });
  336. this.transformNodes = [];
  337. this.actionManagers.forEach((o) => {
  338. o.dispose();
  339. });
  340. this.actionManagers = [];
  341. this.textures.forEach((o) => {
  342. o.dispose();
  343. });
  344. this.textures = [];
  345. this.reflectionProbes.forEach((o) => {
  346. o.dispose();
  347. });
  348. this.reflectionProbes = [];
  349. if (this.environmentTexture) {
  350. this.environmentTexture.dispose();
  351. this.environmentTexture = null;
  352. }
  353. for (let component of this.scene._serializableComponents) {
  354. component.removeFromContainer(this, true);
  355. }
  356. }
  357. private _moveAssets<T>(sourceAssets: T[], targetAssets: T[], keepAssets: T[]): void {
  358. if (!sourceAssets) {
  359. return;
  360. }
  361. for (let asset of sourceAssets) {
  362. let move = true;
  363. if (keepAssets) {
  364. for (let keepAsset of keepAssets) {
  365. if (asset === keepAsset) {
  366. move = false;
  367. break;
  368. }
  369. }
  370. }
  371. if (move) {
  372. targetAssets.push(asset);
  373. }
  374. }
  375. }
  376. /**
  377. * Removes all the assets contained in the scene and adds them to the container.
  378. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  379. */
  380. public moveAllFromScene(keepAssets?: KeepAssets): void {
  381. this._wasAddedToScene = false;
  382. if (keepAssets === undefined) {
  383. keepAssets = new KeepAssets();
  384. }
  385. for (let key in this) {
  386. if (this.hasOwnProperty(key)) {
  387. (<any>this)[key] = (<any>this)[key] || (key === "environmentTexture" ? null : []);
  388. this._moveAssets((<any>this.scene)[key], (<any>this)[key], (<any>keepAssets)[key]);
  389. }
  390. }
  391. this.removeAllFromScene();
  392. }
  393. /**
  394. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  395. * @returns the root mesh
  396. */
  397. public createRootMesh() {
  398. var rootMesh = new Mesh("assetContainerRootMesh", this.scene);
  399. this.meshes.forEach((m) => {
  400. if (!m.parent) {
  401. rootMesh.addChild(m);
  402. }
  403. });
  404. this.meshes.unshift(rootMesh);
  405. return rootMesh;
  406. }
  407. /**
  408. * Merge animations from this asset container into a scene
  409. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  410. * @param animatables set of animatables to retarget to a node from the scene
  411. * @param targetConverter defines a function used to convert animation targets from the asset container to the scene (default: search node by name)
  412. */
  413. public mergeAnimationsTo(scene: Nullable<Scene> = EngineStore.LastCreatedScene, animatables: Animatable[], targetConverter: Nullable<(target: any) => Nullable<Node>> = null): void {
  414. if (!scene) {
  415. Logger.Error("No scene available to merge animations to");
  416. return;
  417. }
  418. let _targetConverter = targetConverter ? targetConverter : (target: any) => { return scene.getBoneByName(target.name) || scene.getNodeByName(target.name); };
  419. // Copy new node animations
  420. let nodesInAC = this.getNodes();
  421. nodesInAC.forEach((nodeInAC) => {
  422. let nodeInScene = _targetConverter(nodeInAC);
  423. if (nodeInScene !== null) {
  424. // Remove old animations with same target property as a new one
  425. for (let animationInAC of nodeInAC.animations) {
  426. // Doing treatment on an array for safety measure
  427. let animationsWithSameProperty = nodeInScene.animations.filter((animationInScene) => {
  428. return animationInScene.targetProperty === animationInAC.targetProperty;
  429. });
  430. for (let animationWithSameProperty of animationsWithSameProperty) {
  431. const index = nodeInScene.animations.indexOf(animationWithSameProperty, 0);
  432. if (index > -1) {
  433. nodeInScene.animations.splice(index, 1);
  434. }
  435. }
  436. }
  437. // Append new animations
  438. nodeInScene.animations = nodeInScene.animations.concat(nodeInAC.animations);
  439. }
  440. });
  441. // Copy new animation groups
  442. this.animationGroups.slice().forEach((animationGroupInAC) => {
  443. // Clone the animation group and all its animatables
  444. animationGroupInAC.clone(animationGroupInAC.name, _targetConverter);
  445. // Remove animatables related to the asset container
  446. animationGroupInAC.animatables.forEach((animatable) => {
  447. animatable.stop();
  448. });
  449. });
  450. // Retarget animatables
  451. animatables.forEach((animatable) => {
  452. let target = _targetConverter(animatable.target);
  453. if (target) {
  454. // Clone the animatable and retarget it
  455. scene.beginAnimation(target, animatable.fromFrame, animatable.toFrame, animatable.loopAnimation, animatable.speedRatio, animatable.onAnimationEnd ? animatable.onAnimationEnd : undefined, undefined, true, undefined, animatable.onAnimationLoop ? animatable.onAnimationLoop : undefined);
  456. // Stop animation for the target in the asset container
  457. scene.stopAnimation(animatable.target);
  458. }
  459. });
  460. }
  461. }