volumetricLightScatteringPostProcess.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. import { serializeAsVector3, serialize, serializeAsMeshReference } from "../Misc/decorators";
  2. import { SmartArray } from "../Misc/smartArray";
  3. import { Logger } from "../Misc/logger";
  4. import { Color4, Color3, Vector2, Vector3, Matrix, Viewport } from "../Maths/math";
  5. import { VertexBuffer } from "../Meshes/buffer";
  6. import { AbstractMesh } from "../Meshes/abstractMesh";
  7. import { SubMesh } from "../Meshes/subMesh";
  8. import { Mesh } from "../Meshes/mesh";
  9. import { Camera } from "../Cameras/camera";
  10. import { Effect } from "../Materials/effect";
  11. import { Material } from "../Materials/material";
  12. import { StandardMaterial } from "../Materials/standardMaterial";
  13. import { Texture } from "../Materials/Textures/texture";
  14. import { RenderTargetTexture } from "../Materials/Textures/renderTargetTexture";
  15. import { PostProcess } from "./postProcess";
  16. import { Constants } from "../Engines/constants";
  17. import { Scene } from "../scene";
  18. import "../Shaders/depth.vertex";
  19. import "../Shaders/volumetricLightScattering.fragment";
  20. import "../Shaders/volumetricLightScatteringPass.fragment";
  21. declare type Engine = import("../Engines/engine").Engine;
  22. /**
  23. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  24. */
  25. export class VolumetricLightScatteringPostProcess extends PostProcess {
  26. // Members
  27. private _volumetricLightScatteringPass: Effect;
  28. private _volumetricLightScatteringRTT: RenderTargetTexture;
  29. private _viewPort: Viewport;
  30. private _screenCoordinates: Vector2 = Vector2.Zero();
  31. private _cachedDefines: string;
  32. /**
  33. * If not undefined, the mesh position is computed from the attached node position
  34. */
  35. public attachedNode: { position: Vector3 };
  36. /**
  37. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  38. */
  39. @serializeAsVector3()
  40. public customMeshPosition: Vector3 = Vector3.Zero();
  41. /**
  42. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  43. */
  44. @serialize()
  45. public useCustomMeshPosition: boolean = false;
  46. /**
  47. * If the post-process should inverse the light scattering direction
  48. */
  49. @serialize()
  50. public invert: boolean = true;
  51. /**
  52. * The internal mesh used by the post-process
  53. */
  54. @serializeAsMeshReference()
  55. public mesh: Mesh;
  56. /**
  57. * @hidden
  58. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  59. */
  60. public get useDiffuseColor(): boolean {
  61. Logger.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  62. return false;
  63. }
  64. public set useDiffuseColor(useDiffuseColor: boolean) {
  65. Logger.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  66. }
  67. /**
  68. * Array containing the excluded meshes not rendered in the internal pass
  69. */
  70. @serialize()
  71. public excludedMeshes = new Array<AbstractMesh>();
  72. /**
  73. * Controls the overall intensity of the post-process
  74. */
  75. @serialize()
  76. public exposure = 0.3;
  77. /**
  78. * Dissipates each sample's contribution in range [0, 1]
  79. */
  80. @serialize()
  81. public decay = 0.96815;
  82. /**
  83. * Controls the overall intensity of each sample
  84. */
  85. @serialize()
  86. public weight = 0.58767;
  87. /**
  88. * Controls the density of each sample
  89. */
  90. @serialize()
  91. public density = 0.926;
  92. /**
  93. * @constructor
  94. * @param name The post-process name
  95. * @param ratio The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  96. * @param camera The camera that the post-process will be attached to
  97. * @param mesh The mesh used to create the light scattering
  98. * @param samples The post-process quality, default 100
  99. * @param samplingModeThe post-process filtering mode
  100. * @param engine The babylon engine
  101. * @param reusable If the post-process is reusable
  102. * @param scene The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  103. */
  104. constructor(name: string, ratio: any, camera: Camera, mesh?: Mesh, samples: number = 100, samplingMode: number = Texture.BILINEAR_SAMPLINGMODE, engine?: Engine, reusable?: boolean, scene?: Scene) {
  105. super(name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  106. scene = <Scene>((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  107. engine = scene.getEngine();
  108. this._viewPort = new Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  109. // Configure mesh
  110. this.mesh = (<Mesh>((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene)));
  111. // Configure
  112. this._createPass(scene, ratio.passRatio || ratio);
  113. this.onActivate = (camera: Camera) => {
  114. if (!this.isSupported) {
  115. this.dispose(camera);
  116. }
  117. this.onActivate = null;
  118. };
  119. this.onApplyObservable.add((effect: Effect) => {
  120. this._updateMeshScreenCoordinates(<Scene>scene);
  121. effect.setTexture("lightScatteringSampler", this._volumetricLightScatteringRTT);
  122. effect.setFloat("exposure", this.exposure);
  123. effect.setFloat("decay", this.decay);
  124. effect.setFloat("weight", this.weight);
  125. effect.setFloat("density", this.density);
  126. effect.setVector2("meshPositionOnScreen", this._screenCoordinates);
  127. });
  128. }
  129. /**
  130. * Returns the string "VolumetricLightScatteringPostProcess"
  131. * @returns "VolumetricLightScatteringPostProcess"
  132. */
  133. public getClassName(): string {
  134. return "VolumetricLightScatteringPostProcess";
  135. }
  136. private _isReady(subMesh: SubMesh, useInstances: boolean): boolean {
  137. var mesh = subMesh.getMesh();
  138. // Render this.mesh as default
  139. if (mesh === this.mesh && mesh.material) {
  140. return mesh.material.isReady(mesh);
  141. }
  142. var defines = [];
  143. var attribs = [VertexBuffer.PositionKind];
  144. var material: any = subMesh.getMaterial();
  145. // Alpha test
  146. if (material) {
  147. if (material.needAlphaTesting()) {
  148. defines.push("#define ALPHATEST");
  149. }
  150. if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  151. attribs.push(VertexBuffer.UVKind);
  152. defines.push("#define UV1");
  153. }
  154. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  155. attribs.push(VertexBuffer.UV2Kind);
  156. defines.push("#define UV2");
  157. }
  158. }
  159. // Bones
  160. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  161. attribs.push(VertexBuffer.MatricesIndicesKind);
  162. attribs.push(VertexBuffer.MatricesWeightsKind);
  163. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  164. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  165. } else {
  166. defines.push("#define NUM_BONE_INFLUENCERS 0");
  167. }
  168. // Instances
  169. if (useInstances) {
  170. defines.push("#define INSTANCES");
  171. attribs.push("world0");
  172. attribs.push("world1");
  173. attribs.push("world2");
  174. attribs.push("world3");
  175. }
  176. // Get correct effect
  177. var join = defines.join("\n");
  178. if (this._cachedDefines !== join) {
  179. this._cachedDefines = join;
  180. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect(
  181. { vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" },
  182. attribs,
  183. ["world", "mBones", "viewProjection", "diffuseMatrix"],
  184. ["diffuseSampler"], join);
  185. }
  186. return this._volumetricLightScatteringPass.isReady();
  187. }
  188. /**
  189. * Sets the new light position for light scattering effect
  190. * @param position The new custom light position
  191. */
  192. public setCustomMeshPosition(position: Vector3): void {
  193. this.customMeshPosition = position;
  194. }
  195. /**
  196. * Returns the light position for light scattering effect
  197. * @return Vector3 The custom light position
  198. */
  199. public getCustomMeshPosition(): Vector3 {
  200. return this.customMeshPosition;
  201. }
  202. /**
  203. * Disposes the internal assets and detaches the post-process from the camera
  204. */
  205. public dispose(camera: Camera): void {
  206. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  207. if (rttIndex !== -1) {
  208. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  209. }
  210. this._volumetricLightScatteringRTT.dispose();
  211. super.dispose(camera);
  212. }
  213. /**
  214. * Returns the render target texture used by the post-process
  215. * @return the render target texture used by the post-process
  216. */
  217. public getPass(): RenderTargetTexture {
  218. return this._volumetricLightScatteringRTT;
  219. }
  220. // Private methods
  221. private _meshExcluded(mesh: AbstractMesh) {
  222. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  223. return true;
  224. }
  225. return false;
  226. }
  227. private _createPass(scene: Scene, ratio: number): void {
  228. var engine = scene.getEngine();
  229. this._volumetricLightScatteringRTT = new RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, Constants.TEXTURETYPE_UNSIGNED_INT);
  230. this._volumetricLightScatteringRTT.wrapU = Texture.CLAMP_ADDRESSMODE;
  231. this._volumetricLightScatteringRTT.wrapV = Texture.CLAMP_ADDRESSMODE;
  232. this._volumetricLightScatteringRTT.renderList = null;
  233. this._volumetricLightScatteringRTT.renderParticles = false;
  234. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  235. var camera = this.getCamera();
  236. if (camera) {
  237. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  238. } else {
  239. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  240. }
  241. // Custom render function for submeshes
  242. var renderSubMesh = (subMesh: SubMesh): void => {
  243. var mesh = subMesh.getRenderingMesh();
  244. if (this._meshExcluded(mesh)) {
  245. return;
  246. }
  247. let material = subMesh.getMaterial();
  248. if (!material) {
  249. return;
  250. }
  251. var scene = mesh.getScene();
  252. var engine = scene.getEngine();
  253. // Culling
  254. engine.setState(material.backFaceCulling);
  255. // Managing instances
  256. var batch = mesh._getInstancesRenderList(subMesh._id);
  257. if (batch.mustReturn) {
  258. return;
  259. }
  260. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  261. if (this._isReady(subMesh, hardwareInstancedRendering)) {
  262. var effect: Effect = this._volumetricLightScatteringPass;
  263. if (mesh === this.mesh) {
  264. if (subMesh.effect) {
  265. effect = subMesh.effect;
  266. } else {
  267. effect = <Effect>material.getEffect();
  268. }
  269. }
  270. engine.enableEffect(effect);
  271. mesh._bind(subMesh, effect, Material.TriangleFillMode);
  272. if (mesh === this.mesh) {
  273. material.bind(mesh.getWorldMatrix(), mesh);
  274. }
  275. else {
  276. this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  277. // Alpha test
  278. if (material && material.needAlphaTesting()) {
  279. var alphaTexture = material.getAlphaTestTexture();
  280. this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  281. if (alphaTexture) {
  282. this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  283. }
  284. }
  285. // Bones
  286. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  287. this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  288. }
  289. }
  290. // Draw
  291. mesh._processRendering(subMesh, this._volumetricLightScatteringPass, Material.TriangleFillMode, batch, hardwareInstancedRendering,
  292. (isInstance, world) => effect.setMatrix("world", world));
  293. }
  294. };
  295. // Render target texture callbacks
  296. var savedSceneClearColor: Color4;
  297. var sceneClearColor = new Color4(0.0, 0.0, 0.0, 1.0);
  298. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((): void => {
  299. savedSceneClearColor = scene.clearColor;
  300. scene.clearColor = sceneClearColor;
  301. });
  302. this._volumetricLightScatteringRTT.onAfterRenderObservable.add((): void => {
  303. scene.clearColor = savedSceneClearColor;
  304. });
  305. this._volumetricLightScatteringRTT.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>, depthOnlySubMeshes: SmartArray<SubMesh>): void => {
  306. var engine = scene.getEngine();
  307. var index: number;
  308. if (depthOnlySubMeshes.length) {
  309. engine.setColorWrite(false);
  310. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  311. renderSubMesh(depthOnlySubMeshes.data[index]);
  312. }
  313. engine.setColorWrite(true);
  314. }
  315. for (index = 0; index < opaqueSubMeshes.length; index++) {
  316. renderSubMesh(opaqueSubMeshes.data[index]);
  317. }
  318. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  319. renderSubMesh(alphaTestSubMeshes.data[index]);
  320. }
  321. if (transparentSubMeshes.length) {
  322. // Sort sub meshes
  323. for (index = 0; index < transparentSubMeshes.length; index++) {
  324. var submesh = transparentSubMeshes.data[index];
  325. let boundingInfo = submesh.getBoundingInfo();
  326. if (boundingInfo && scene.activeCamera) {
  327. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  328. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  329. }
  330. }
  331. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  332. sortedArray.sort((a, b) => {
  333. // Alpha index first
  334. if (a._alphaIndex > b._alphaIndex) {
  335. return 1;
  336. }
  337. if (a._alphaIndex < b._alphaIndex) {
  338. return -1;
  339. }
  340. // Then distance to camera
  341. if (a._distanceToCamera < b._distanceToCamera) {
  342. return 1;
  343. }
  344. if (a._distanceToCamera > b._distanceToCamera) {
  345. return -1;
  346. }
  347. return 0;
  348. });
  349. // Render sub meshes
  350. engine.setAlphaMode(Constants.ALPHA_COMBINE);
  351. for (index = 0; index < sortedArray.length; index++) {
  352. renderSubMesh(sortedArray[index]);
  353. }
  354. engine.setAlphaMode(Constants.ALPHA_DISABLE);
  355. }
  356. };
  357. }
  358. private _updateMeshScreenCoordinates(scene: Scene): void {
  359. var transform = scene.getTransformMatrix();
  360. var meshPosition: Vector3;
  361. if (this.useCustomMeshPosition) {
  362. meshPosition = this.customMeshPosition;
  363. }
  364. else if (this.attachedNode) {
  365. meshPosition = this.attachedNode.position;
  366. }
  367. else {
  368. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  369. }
  370. var pos = Vector3.Project(meshPosition, Matrix.Identity(), transform, this._viewPort);
  371. this._screenCoordinates.x = pos.x / this._viewPort.width;
  372. this._screenCoordinates.y = pos.y / this._viewPort.height;
  373. if (this.invert) {
  374. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  375. }
  376. }
  377. // Static methods
  378. /**
  379. * Creates a default mesh for the Volumeric Light Scattering post-process
  380. * @param name The mesh name
  381. * @param scene The scene where to create the mesh
  382. * @return the default mesh
  383. */
  384. public static CreateDefaultMesh(name: string, scene: Scene): Mesh {
  385. var mesh = Mesh.CreatePlane(name, 1, scene);
  386. mesh.billboardMode = AbstractMesh.BILLBOARDMODE_ALL;
  387. var material = new StandardMaterial(name + "Material", scene);
  388. material.emissiveColor = new Color3(1, 1, 1);
  389. mesh.material = material;
  390. return mesh;
  391. }
  392. }