assetContainer.ts 19 KB

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