previewManager.ts 23 KB

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