previewManager.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. import { GlobalState } from '../../globalState';
  2. import { NodeMaterial } from 'babylonjs/Materials/Node/nodeMaterial';
  3. import { Nullable } from 'babylonjs/types';
  4. import { Observer } from 'babylonjs/Misc/observable';
  5. import { Engine } from 'babylonjs/Engines/engine';
  6. import { Scene } from 'babylonjs/scene';
  7. import { Mesh } from 'babylonjs/Meshes/mesh';
  8. import { Vector3 } from 'babylonjs/Maths/math.vector';
  9. import { HemisphericLight } from 'babylonjs/Lights/hemisphericLight';
  10. import { ArcRotateCamera } from 'babylonjs/Cameras/arcRotateCamera';
  11. import { PreviewMeshType } from './previewMeshType';
  12. import { Animation } from 'babylonjs/Animations/animation';
  13. import { SceneLoader } from 'babylonjs/Loading/sceneLoader';
  14. import { TransformNode } from 'babylonjs/Meshes/transformNode';
  15. import { AbstractMesh } from 'babylonjs/Meshes/abstractMesh';
  16. import { FramingBehavior } from 'babylonjs/Behaviors/Cameras/framingBehavior';
  17. import { DirectionalLight } from 'babylonjs/Lights/directionalLight';
  18. export class PreviewManager {
  19. private _nodeMaterial: NodeMaterial;
  20. private _onBuildObserver: Nullable<Observer<NodeMaterial>>;
  21. private _onPreviewCommandActivatedObserver: Nullable<Observer<void>>;
  22. private _onAnimationCommandActivatedObserver: Nullable<Observer<void>>;
  23. private _onUpdateRequiredObserver: Nullable<Observer<void>>;
  24. private _onPreviewBackgroundChangedObserver: Nullable<Observer<void>>;
  25. private _onBackFaceCullingChangedObserver: Nullable<Observer<void>>;
  26. private _onLightUpdatedObserver: Nullable<Observer<void>>;
  27. private _engine: Engine;
  28. private _scene: Scene;
  29. private _meshes: AbstractMesh[];
  30. private _camera: ArcRotateCamera;
  31. private _material: NodeMaterial;
  32. private _globalState: GlobalState;
  33. private _currentType: number;
  34. public constructor(targetCanvas: HTMLCanvasElement, globalState: GlobalState) {
  35. this._nodeMaterial = globalState.nodeMaterial;
  36. this._globalState = globalState;
  37. this._onBuildObserver = this._nodeMaterial.onBuildObservable.add((nodeMaterial) => {
  38. let serializationObject = nodeMaterial.serialize();
  39. this._updatePreview(serializationObject);
  40. });
  41. this._onPreviewCommandActivatedObserver = globalState.onPreviewCommandActivated.add(() => {
  42. this._refreshPreviewMesh();
  43. });
  44. this._onLightUpdatedObserver = globalState.onLightUpdated.add(() => {
  45. this._prepareLights();
  46. });
  47. this._onUpdateRequiredObserver = globalState.onUpdateRequiredObservable.add(() => {
  48. let serializationObject = this._nodeMaterial.serialize();
  49. this._updatePreview(serializationObject);
  50. });
  51. this._onPreviewBackgroundChangedObserver = globalState.onPreviewBackgroundChanged.add(() => {
  52. this._scene.clearColor = this._globalState.backgroundColor;
  53. });
  54. this._onAnimationCommandActivatedObserver = globalState.onAnimationCommandActivated.add(() => {
  55. this._handleAnimations();
  56. });
  57. this._onBackFaceCullingChangedObserver = globalState.onBackFaceCullingChanged.add(() => {
  58. let serializationObject = this._nodeMaterial.serialize();
  59. this._updatePreview(serializationObject);
  60. });
  61. this._engine = new Engine(targetCanvas, true);
  62. this._scene = new Scene(this._engine);
  63. this._camera = new ArcRotateCamera("Camera", 0, 0.8, 4, Vector3.Zero(), this._scene);
  64. this._camera.lowerRadiusLimit = 3;
  65. this._camera.upperRadiusLimit = 10;
  66. this._camera.wheelPrecision = 20;
  67. this._camera.minZ = 0.1;
  68. this._camera.attachControl(targetCanvas, false);
  69. this._refreshPreviewMesh();
  70. this._engine.runRenderLoop(() => {
  71. this._engine.resize();
  72. this._scene.render();
  73. });
  74. }
  75. private _handleAnimations() {
  76. this._scene.stopAllAnimations();
  77. if (this._globalState.rotatePreview) {
  78. for (var root of this._scene.rootNodes) {
  79. let transformNode = root as TransformNode;
  80. if (transformNode.getClassName() === "TransformNode" || transformNode.getClassName() === "Mesh" || transformNode.getClassName() === "GroundMesh") {
  81. if (transformNode.rotationQuaternion) {
  82. transformNode.rotation = transformNode.rotationQuaternion.toEulerAngles();
  83. transformNode.rotationQuaternion = null;
  84. }
  85. Animation.CreateAndStartAnimation("turnTable", root, "rotation.y", 60, 1200, transformNode.rotation.y, transformNode.rotation.y + 2 * Math.PI, 1);
  86. }
  87. }
  88. }
  89. }
  90. private _prepareLights() {
  91. // Remove current lights
  92. let currentLights = this._scene.lights.slice(0);
  93. for (var light of currentLights) {
  94. light.dispose();
  95. }
  96. // Create new lights based on settings
  97. if (this._globalState.hemisphericLight) {
  98. new HemisphericLight("Hemispheric light", new Vector3(0, 1, 0), this._scene);
  99. }
  100. if (this._globalState.directionalLight0) {
  101. new DirectionalLight("Directional light #0", new Vector3(-1, -1, 0), this._scene);
  102. }
  103. }
  104. private _prepareMeshes() {
  105. this._prepareLights();
  106. // Framing
  107. this._camera.useFramingBehavior = true;
  108. var framingBehavior = this._camera.getBehaviorByName("Framing") as FramingBehavior;
  109. framingBehavior.framingTime = 0;
  110. framingBehavior.elevationReturnTime = -1;
  111. if (this._scene.meshes.length) {
  112. var worldExtends = this._scene.getWorldExtends();
  113. this._camera.lowerRadiusLimit = null;
  114. this._camera.upperRadiusLimit = null;
  115. framingBehavior.zoomOnBoundingInfo(worldExtends.min, worldExtends.max);
  116. }
  117. this._camera.pinchPrecision = 200 / this._camera.radius;
  118. this._camera.upperRadiusLimit = 5 * this._camera.radius;
  119. this._camera.wheelDeltaPercentage = 0.01;
  120. this._camera.pinchDeltaPercentage = 0.01;
  121. // Animations
  122. this._handleAnimations();
  123. // Material
  124. let serializationObject = this._nodeMaterial.serialize();
  125. this._updatePreview(serializationObject);
  126. }
  127. private _refreshPreviewMesh() {
  128. if (this._currentType !== this._globalState.previewMeshType || this._currentType === PreviewMeshType.Custom) {
  129. this._currentType = this._globalState.previewMeshType;
  130. if (this._meshes && this._meshes.length) {
  131. for (var mesh of this._meshes) {
  132. mesh.dispose();
  133. }
  134. }
  135. this._meshes = [];
  136. let lights = this._scene.lights.slice(0);
  137. for (var light of lights) {
  138. light.dispose();
  139. }
  140. this._engine.releaseEffects();
  141. switch (this._globalState.previewMeshType) {
  142. case PreviewMeshType.Box:
  143. this._meshes.push(Mesh.CreateBox("dummy-box", 2, this._scene));
  144. break;
  145. case PreviewMeshType.Sphere:
  146. this._meshes.push(Mesh.CreateSphere("dummy-sphere", 32, 2, this._scene));
  147. break;
  148. case PreviewMeshType.Torus:
  149. this._meshes.push(Mesh.CreateTorus("dummy-torus", 2, 0.5, 32, this._scene));
  150. break;
  151. case PreviewMeshType.Cylinder:
  152. SceneLoader.AppendAsync("https://models.babylonjs.com/", "roundedCylinder.glb", this._scene).then(() => {
  153. this._meshes.push(...this._scene.meshes);
  154. this._prepareMeshes();
  155. });
  156. return;
  157. case PreviewMeshType.Plane:
  158. this._meshes.push(Mesh.CreateGround("dummy-plane", 2, 2, 128, this._scene));
  159. break;
  160. case PreviewMeshType.ShaderBall:
  161. SceneLoader.AppendAsync("https://models.babylonjs.com/", "shaderBall.glb", this._scene).then(() => {
  162. this._meshes.push(...this._scene.meshes);
  163. this._prepareMeshes();
  164. });
  165. return;
  166. case PreviewMeshType.Custom:
  167. SceneLoader.AppendAsync("file:", this._globalState.previewMeshFile, this._scene).then(() => {
  168. this._meshes.push(...this._scene.meshes);
  169. this._prepareMeshes();
  170. });
  171. return;
  172. }
  173. this._prepareMeshes();
  174. }
  175. }
  176. private _forceCompilationAsync(material: NodeMaterial, mesh: AbstractMesh): Promise<void> {
  177. return material.forceCompilationAsync(mesh);
  178. }
  179. private _updatePreview(serializationObject: any) {
  180. try {
  181. let tempMaterial = NodeMaterial.Parse(serializationObject, this._scene);
  182. tempMaterial.backFaceCulling = this._globalState.backFaceCulling;
  183. if (this._meshes.length) {
  184. let tasks = this._meshes.map(m => this._forceCompilationAsync(tempMaterial, m));
  185. Promise.all(tasks).then(() => {
  186. for (var mesh of this._meshes) {
  187. mesh.material = tempMaterial;
  188. }
  189. if (this._material) {
  190. this._material.dispose();
  191. }
  192. this._material = tempMaterial;
  193. });
  194. } else {
  195. this._material = tempMaterial;
  196. }
  197. } catch(err) {
  198. // Ignore the error
  199. }
  200. }
  201. public dispose() {
  202. this._nodeMaterial.onBuildObservable.remove(this._onBuildObserver);
  203. this._globalState.onPreviewCommandActivated.remove(this._onPreviewCommandActivatedObserver);
  204. this._globalState.onUpdateRequiredObservable.remove(this._onUpdateRequiredObserver);
  205. this._globalState.onAnimationCommandActivated.remove(this._onAnimationCommandActivatedObserver);
  206. this._globalState.onPreviewBackgroundChanged.remove(this._onPreviewBackgroundChangedObserver);
  207. this._globalState.onBackFaceCullingChanged.remove(this._onBackFaceCullingChangedObserver);
  208. this._globalState.onLightUpdated.remove(this._onLightUpdatedObserver);
  209. if (this._material) {
  210. this._material.dispose();
  211. }
  212. this._camera.dispose();
  213. for (var mesh of this._meshes) {
  214. mesh.dispose();
  215. }
  216. this._scene.dispose();
  217. this._engine.dispose();
  218. }
  219. }