previewManager.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. import { LogEntry } from '../log/logComponent';
  19. import { PointerEventTypes } from 'babylonjs/Events/pointerEvents';
  20. import { Color3, Color4 } from 'babylonjs/Maths/math.color';
  21. import { PostProcess } from 'babylonjs/PostProcesses/postProcess';
  22. import { Constants } from 'babylonjs/Engines/constants';
  23. import { CurrentScreenBlock } from 'babylonjs/Materials/Node/Blocks/Dual/currentScreenBlock';
  24. import { NodeMaterialModes } from 'babylonjs/Materials/Node/Enums/nodeMaterialModes';
  25. import { ParticleSystem } from 'babylonjs/Particles/particleSystem';
  26. import { ParticleHelper } from 'babylonjs/Particles/particleHelper';
  27. import { Texture } from 'babylonjs/Materials/Textures/texture';
  28. import { ParticleTextureBlock } from 'babylonjs/Materials/Node/Blocks/Particle/particleTextureBlock';
  29. import { Effect } from 'babylonjs/Materials/effect';
  30. import { FileTools } from 'babylonjs/Misc/fileTools';
  31. export class PreviewManager {
  32. private _nodeMaterial: NodeMaterial;
  33. private _onBuildObserver: Nullable<Observer<NodeMaterial>>;
  34. private _onPreviewCommandActivatedObserver: Nullable<Observer<boolean>>;
  35. private _onAnimationCommandActivatedObserver: Nullable<Observer<void>>;
  36. private _onUpdateRequiredObserver: Nullable<Observer<void>>;
  37. private _onPreviewBackgroundChangedObserver: Nullable<Observer<void>>;
  38. private _onBackFaceCullingChangedObserver: Nullable<Observer<void>>;
  39. private _onDepthPrePassChangedObserver: Nullable<Observer<void>>;
  40. private _onLightUpdatedObserver: Nullable<Observer<void>>;
  41. private _engine: Engine;
  42. private _scene: Scene;
  43. private _meshes: AbstractMesh[];
  44. private _camera: ArcRotateCamera;
  45. private _material: NodeMaterial;
  46. private _globalState: GlobalState;
  47. private _currentType: number;
  48. private _lightParent: TransformNode;
  49. private _postprocess: Nullable<PostProcess>;
  50. private _particleSystem: Nullable<ParticleSystem>;
  51. private _particleSystemDrawObserver: Nullable<Observer<Effect>>;
  52. public constructor(targetCanvas: HTMLCanvasElement, globalState: GlobalState) {
  53. this._nodeMaterial = globalState.nodeMaterial;
  54. this._globalState = globalState;
  55. this._particleSystemDrawObserver = null;
  56. this._onBuildObserver = this._nodeMaterial.onBuildObservable.add((nodeMaterial) => {
  57. let serializationObject = nodeMaterial.serialize();
  58. this._updatePreview(serializationObject);
  59. });
  60. this._onPreviewCommandActivatedObserver = globalState.onPreviewCommandActivated.add((forceRefresh: boolean) => {
  61. if (forceRefresh) {
  62. this._currentType = -1;
  63. }
  64. this._refreshPreviewMesh();
  65. });
  66. this._onLightUpdatedObserver = globalState.onLightUpdated.add(() => {
  67. this._prepareLights();
  68. });
  69. this._onUpdateRequiredObserver = globalState.onUpdateRequiredObservable.add(() => {
  70. let serializationObject = this._nodeMaterial.serialize();
  71. this._updatePreview(serializationObject);
  72. });
  73. this._onPreviewBackgroundChangedObserver = globalState.onPreviewBackgroundChanged.add(() => {
  74. this._scene.clearColor = this._globalState.backgroundColor;
  75. });
  76. this._onAnimationCommandActivatedObserver = globalState.onAnimationCommandActivated.add(() => {
  77. this._handleAnimations();
  78. });
  79. this._onBackFaceCullingChangedObserver = globalState.onBackFaceCullingChanged.add(() => {
  80. this._material.backFaceCulling = this._globalState.backFaceCulling;
  81. });
  82. this._onDepthPrePassChangedObserver = globalState.onDepthPrePassChanged.add(() => {
  83. this._material.needDepthPrePass = this._globalState.depthPrePass;
  84. });
  85. this._engine = new Engine(targetCanvas, true);
  86. this._scene = new Scene(this._engine);
  87. this._scene.clearColor = this._globalState.backgroundColor;
  88. this._camera = new ArcRotateCamera("Camera", 0, 0.8, 4, Vector3.Zero(), this._scene);
  89. this._camera.lowerRadiusLimit = 3;
  90. this._camera.upperRadiusLimit = 10;
  91. this._camera.wheelPrecision = 20;
  92. this._camera.minZ = 0.1;
  93. this._camera.attachControl(targetCanvas, false);
  94. this._lightParent = new TransformNode("LightParent", this._scene);
  95. this._refreshPreviewMesh();
  96. this._engine.runRenderLoop(() => {
  97. this._engine.resize();
  98. this._scene.render();
  99. });
  100. let lastOffsetX: number | undefined = undefined;
  101. const lightRotationSpeed = 0.01;
  102. this._scene.onPointerObservable.add((evt) => {
  103. if (this._globalState.controlCamera) {
  104. return;
  105. }
  106. if (evt.type === PointerEventTypes.POINTERUP) {
  107. lastOffsetX = undefined;
  108. return;
  109. }
  110. if (evt.event.buttons !== 1) {
  111. return;
  112. }
  113. if (lastOffsetX === undefined) {
  114. lastOffsetX = evt.event.offsetX;
  115. }
  116. var rotateLighting = (lastOffsetX - evt.event.offsetX) * lightRotationSpeed;
  117. this._lightParent.rotation.y += rotateLighting;
  118. lastOffsetX = evt.event.offsetX;
  119. });
  120. // this._scene.registerBeforeRender(() => {
  121. // if (this._camera.alpha === cameraLastRotation) {
  122. // return;
  123. // }
  124. // if (!this._globalState.controlCamera) {
  125. // return;
  126. // }
  127. // var rotateLighting = (this._camera.alpha - cameraLastRotation) * lightRotationParallaxSpeed;
  128. // this._lightParent.rotate(Vector3.Up(), rotateLighting);
  129. // cameraLastRotation = this._camera.alpha;
  130. // });
  131. }
  132. private _handleAnimations() {
  133. this._scene.stopAllAnimations();
  134. if (this._globalState.rotatePreview) {
  135. for (var root of this._scene.rootNodes) {
  136. let transformNode = root as TransformNode;
  137. if (transformNode.getClassName() === "TransformNode" || transformNode.getClassName() === "Mesh" || transformNode.getClassName() === "GroundMesh") {
  138. if (transformNode.rotationQuaternion) {
  139. transformNode.rotation = transformNode.rotationQuaternion.toEulerAngles();
  140. transformNode.rotationQuaternion = null;
  141. }
  142. Animation.CreateAndStartAnimation("turnTable", root, "rotation.y", 60, 1200, transformNode.rotation.y, transformNode.rotation.y + 2 * Math.PI, 1);
  143. }
  144. }
  145. }
  146. }
  147. private _prepareLights() {
  148. // Remove current lights
  149. let currentLights = this._scene.lights.slice(0);
  150. for (var light of currentLights) {
  151. light.dispose();
  152. }
  153. // Create new lights based on settings
  154. if (this._globalState.hemisphericLight) {
  155. new HemisphericLight("Hemispheric light", new Vector3(0, 1, 0), this._scene);
  156. }
  157. if (this._globalState.directionalLight0) {
  158. let dir0 = new DirectionalLight("Directional light #0", new Vector3(0.841626576496605, -0.2193391004130599, -0.49351298337996535), this._scene);
  159. dir0.intensity = 0.9;
  160. dir0.diffuse = new Color3(0.9294117647058824, 0.9725490196078431, 0.996078431372549);
  161. dir0.specular = new Color3(0.9294117647058824, 0.9725490196078431, 0.996078431372549);
  162. dir0.parent = this._lightParent;
  163. }
  164. if (this._globalState.directionalLight1) {
  165. let dir1 = new DirectionalLight("Directional light #1", new Vector3(-0.9519937437504213, -0.24389315636999764, -0.1849974057546125), this._scene);
  166. dir1.intensity = 1.2;
  167. dir1.specular = new Color3(0.9803921568627451, 0.9529411764705882, 0.7725490196078432);
  168. dir1.diffuse = new Color3(0.9803921568627451, 0.9529411764705882, 0.7725490196078432);
  169. dir1.parent = this._lightParent;
  170. }
  171. }
  172. private _prepareScene() {
  173. this._camera.useFramingBehavior = this._globalState.mode === NodeMaterialModes.Material;
  174. switch (this._globalState.mode) {
  175. case NodeMaterialModes.Material: {
  176. this._prepareLights();
  177. var framingBehavior = this._camera.getBehaviorByName("Framing") as FramingBehavior;
  178. setTimeout(() => { // Let the behavior activate first
  179. framingBehavior.framingTime = 0;
  180. framingBehavior.elevationReturnTime = -1;
  181. if (this._scene.meshes.length) {
  182. var worldExtends = this._scene.getWorldExtends();
  183. this._camera.lowerRadiusLimit = null;
  184. this._camera.upperRadiusLimit = null;
  185. framingBehavior.zoomOnBoundingInfo(worldExtends.min, worldExtends.max);
  186. }
  187. this._camera.pinchPrecision = 200 / this._camera.radius;
  188. this._camera.upperRadiusLimit = 5 * this._camera.radius;
  189. });
  190. this._camera.wheelDeltaPercentage = 0.01;
  191. this._camera.pinchDeltaPercentage = 0.01;
  192. // Animations
  193. this._handleAnimations();
  194. break;
  195. }
  196. case NodeMaterialModes.PostProcess: {
  197. this._camera.radius = 4;
  198. this._camera.upperRadiusLimit = 10;
  199. break;
  200. }
  201. case NodeMaterialModes.Particle: {
  202. this._camera.radius = this._globalState.previewMeshType === PreviewMeshType.Explosion ? 50 : 20;
  203. this._camera.upperRadiusLimit = 500;
  204. break;
  205. }
  206. }
  207. // Material
  208. let serializationObject = this._nodeMaterial.serialize();
  209. this._updatePreview(serializationObject);
  210. }
  211. private _refreshPreviewMesh() {
  212. if (this._currentType !== this._globalState.previewMeshType || this._currentType === PreviewMeshType.Custom) {
  213. this._currentType = this._globalState.previewMeshType;
  214. if (this._meshes && this._meshes.length) {
  215. for (var mesh of this._meshes) {
  216. mesh.dispose();
  217. }
  218. }
  219. this._meshes = [];
  220. let lights = this._scene.lights.slice(0);
  221. for (var light of lights) {
  222. light.dispose();
  223. }
  224. this._engine.releaseEffects();
  225. if (this._particleSystem) {
  226. if (this._particleSystemDrawObserver) {
  227. this._particleSystem.onBeforeDrawParticlesObservable.remove(this._particleSystemDrawObserver);
  228. }
  229. this._particleSystem.onDisposeObservable.clear();
  230. this._particleSystem.customEffect = null;
  231. this._particleSystem.stop();
  232. this._particleSystem.dispose();
  233. this._particleSystem = null;
  234. this._particleSystemDrawObserver = null;
  235. }
  236. SceneLoader.ShowLoadingScreen = false;
  237. this._globalState.onIsLoadingChanged.notifyObservers(true);
  238. if (this._globalState.mode === NodeMaterialModes.Material) {
  239. switch (this._globalState.previewMeshType) {
  240. case PreviewMeshType.Box:
  241. SceneLoader.AppendAsync("https://models.babylonjs.com/", "roundedCube.glb", this._scene).then(() => {
  242. this._meshes.push(...this._scene.meshes);
  243. this._prepareScene();
  244. });
  245. return;
  246. case PreviewMeshType.Sphere:
  247. this._meshes.push(Mesh.CreateSphere("dummy-sphere", 32, 2, this._scene));
  248. break;
  249. case PreviewMeshType.Torus:
  250. this._meshes.push(Mesh.CreateTorus("dummy-torus", 2, 0.5, 32, this._scene));
  251. break;
  252. case PreviewMeshType.Cylinder:
  253. SceneLoader.AppendAsync("https://models.babylonjs.com/", "roundedCylinder.glb", this._scene).then(() => {
  254. this._meshes.push(...this._scene.meshes);
  255. this._prepareScene();
  256. });
  257. return;
  258. case PreviewMeshType.Plane:
  259. let plane = Mesh.CreateGround("dummy-plane", 2, 2, 128, this._scene);
  260. plane.scaling.y = -1;
  261. plane.rotation.x = Math.PI;
  262. this._meshes.push(plane);
  263. break;
  264. case PreviewMeshType.ShaderBall:
  265. SceneLoader.AppendAsync("https://models.babylonjs.com/", "shaderBall.glb", this._scene).then(() => {
  266. this._meshes.push(...this._scene.meshes);
  267. this._prepareScene();
  268. });
  269. return;
  270. case PreviewMeshType.Custom:
  271. SceneLoader.AppendAsync("file:", this._globalState.previewMeshFile, this._scene).then(() => {
  272. this._meshes.push(...this._scene.meshes);
  273. this._prepareScene();
  274. });
  275. return;
  276. }
  277. } else if (this._globalState.mode === NodeMaterialModes.Particle) {
  278. switch (this._globalState.previewMeshType) {
  279. case PreviewMeshType.Bubbles:
  280. this._particleSystem = new ParticleSystem("particles", 4000, this._scene);
  281. this._particleSystem.particleTexture = new Texture("https://assets.babylonjs.com/particles/textures/explosion/Flare.png", this._scene);
  282. this._particleSystem.minSize = 0.1;
  283. this._particleSystem.maxSize = 1.0;
  284. this._particleSystem.minLifeTime = 0.5;
  285. this._particleSystem.maxLifeTime = 5.0;
  286. this._particleSystem.minEmitPower = 0.5;
  287. this._particleSystem.maxEmitPower = 3.0;
  288. this._particleSystem.createBoxEmitter(new Vector3(-1, 1, -1), new Vector3(1, 1, 1), new Vector3(-0.1, -0.1, -0.1), new Vector3(0.1, 0.1, 0.1));
  289. this._particleSystem.emitRate = 100;
  290. this._particleSystem.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  291. this._particleSystem.color1 = new Color4(1, 1, 0, 1);
  292. this._particleSystem.color2 = new Color4(1, 0.5, 0, 1);
  293. this._particleSystem.gravity = new Vector3(0, -1.0, 0);
  294. this._particleSystem.start();
  295. break;
  296. case PreviewMeshType.Explosion:
  297. this._loadParticleSystem(this._globalState.previewMeshType, 1);
  298. return;
  299. case PreviewMeshType.Fire:
  300. case PreviewMeshType.Rain:
  301. case PreviewMeshType.Smoke:
  302. this._loadParticleSystem(this._globalState.previewMeshType);
  303. return;
  304. case PreviewMeshType.Custom:
  305. FileTools.ReadFile(this._globalState.previewMeshFile, (json) => {
  306. this._particleSystem = ParticleSystem.Parse(JSON.parse(json), this._scene, "");
  307. this._particleSystem.start();
  308. this._prepareScene();
  309. }, undefined, false, (error) => {
  310. console.log(error);
  311. });
  312. return;
  313. }
  314. }
  315. this._prepareScene();
  316. }
  317. }
  318. private _loadParticleSystem(particleNumber: number, systemIndex = 0, prepareScene = true) {
  319. let name = "";
  320. switch (particleNumber) {
  321. case PreviewMeshType.Explosion:
  322. name = "explosion";
  323. break;
  324. case PreviewMeshType.Fire:
  325. name = "fire";
  326. break;
  327. case PreviewMeshType.Rain:
  328. name = "rain";
  329. break;
  330. case PreviewMeshType.Smoke:
  331. name = "smoke";
  332. break;
  333. }
  334. ParticleHelper.CreateAsync(name, this._scene).then((set) => {
  335. for (let i = 0; i < set.systems.length; ++i) {
  336. if (i == systemIndex) {
  337. this._particleSystem = set.systems[i] as ParticleSystem;
  338. this._particleSystem.disposeOnStop = true;
  339. this._particleSystem.onDisposeObservable.add(() => {
  340. if (this._globalState.mode === NodeMaterialModes.Particle && this._globalState.previewMeshType === particleNumber) {
  341. this._loadParticleSystem(particleNumber, systemIndex, false);
  342. }
  343. });
  344. this._particleSystem.start();
  345. } else {
  346. set.systems[i].dispose();
  347. }
  348. }
  349. if (prepareScene) {
  350. this._prepareScene();
  351. }
  352. });
  353. }
  354. private _forceCompilationAsync(material: NodeMaterial, mesh: AbstractMesh): Promise<void> {
  355. return material.forceCompilationAsync(mesh);
  356. }
  357. private _updatePreview(serializationObject: any) {
  358. try {
  359. let tempMaterial = NodeMaterial.Parse(serializationObject, this._scene);
  360. tempMaterial.backFaceCulling = this._globalState.backFaceCulling;
  361. tempMaterial.needDepthPrePass = this._globalState.depthPrePass;
  362. if (this._postprocess) {
  363. this._postprocess.dispose(this._camera);
  364. this._postprocess = null;
  365. }
  366. switch (this._globalState.mode) {
  367. case NodeMaterialModes.PostProcess: {
  368. this._globalState.onIsLoadingChanged.notifyObservers(false);
  369. this._postprocess = tempMaterial.createPostProcess(this._camera, 1.0, Constants.TEXTURE_NEAREST_SAMPLINGMODE, this._engine);
  370. const currentScreen = tempMaterial.getBlockByPredicate((block) => block instanceof CurrentScreenBlock);
  371. if (currentScreen) {
  372. this._postprocess!.onApplyObservable.add((effect) => {
  373. effect.setTexture("textureSampler", (currentScreen as CurrentScreenBlock).texture);
  374. });
  375. }
  376. if (this._material) {
  377. this._material.dispose();
  378. }
  379. this._material = tempMaterial;
  380. break;
  381. }
  382. case NodeMaterialModes.Particle: {
  383. this._globalState.onIsLoadingChanged.notifyObservers(false);
  384. if (this._particleSystemDrawObserver) {
  385. this._particleSystem.onBeforeDrawParticlesObservable.remove(this._particleSystemDrawObserver);
  386. }
  387. this._particleSystemDrawObserver = this._particleSystem.onBeforeDrawParticlesObservable.add((effect) => {
  388. const textureBlock = tempMaterial.getBlockByPredicate((block) => block instanceof ParticleTextureBlock);
  389. if (textureBlock && (textureBlock as ParticleTextureBlock).texture) {
  390. effect.setTexture("diffuseSampler", (textureBlock as ParticleTextureBlock).texture);
  391. }
  392. });
  393. tempMaterial.createEffectForParticles(this._particleSystem);
  394. break;
  395. }
  396. default: {
  397. if (this._meshes.length) {
  398. let tasks = this._meshes.map((m) => this._forceCompilationAsync(tempMaterial, m));
  399. Promise.all(tasks).then(() => {
  400. for (var mesh of this._meshes) {
  401. mesh.material = tempMaterial;
  402. }
  403. if (this._material) {
  404. this._material.dispose();
  405. }
  406. this._material = tempMaterial;
  407. this._globalState.onIsLoadingChanged.notifyObservers(false);
  408. }).catch((reason) => {
  409. this._globalState.onLogRequiredObservable.notifyObservers(new LogEntry("Shader compilation error:\r\n" + reason, true));
  410. this._globalState.onIsLoadingChanged.notifyObservers(false);
  411. });
  412. } else {
  413. this._material = tempMaterial;
  414. }
  415. break;
  416. }
  417. }
  418. } catch (err) {
  419. // Ignore the error
  420. this._globalState.onIsLoadingChanged.notifyObservers(false);
  421. }
  422. }
  423. public dispose() {
  424. this._nodeMaterial.onBuildObservable.remove(this._onBuildObserver);
  425. this._globalState.onPreviewCommandActivated.remove(this._onPreviewCommandActivatedObserver);
  426. this._globalState.onUpdateRequiredObservable.remove(this._onUpdateRequiredObserver);
  427. this._globalState.onAnimationCommandActivated.remove(this._onAnimationCommandActivatedObserver);
  428. this._globalState.onPreviewBackgroundChanged.remove(this._onPreviewBackgroundChangedObserver);
  429. this._globalState.onBackFaceCullingChanged.remove(this._onBackFaceCullingChangedObserver);
  430. this._globalState.onDepthPrePassChanged.remove(this._onDepthPrePassChangedObserver);
  431. this._globalState.onLightUpdated.remove(this._onLightUpdatedObserver);
  432. if (this._material) {
  433. this._material.dispose();
  434. }
  435. this._camera.dispose();
  436. for (var mesh of this._meshes) {
  437. mesh.dispose();
  438. }
  439. this._scene.dispose();
  440. this._engine.dispose();
  441. }
  442. }