previewManager.ts 25 KB

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