babylon.volumetricLightScatteringPostProcess.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. module BABYLON {
  2. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  3. export class VolumetricLightScatteringPostProcess extends PostProcess {
  4. // Members
  5. private _volumetricLightScatteringPass: Effect;
  6. private _volumetricLightScatteringRTT: RenderTargetTexture;
  7. private _viewPort: Viewport;
  8. private _screenCoordinates: Vector2 = Vector2.Zero();
  9. private _cachedDefines: string;
  10. private _customMeshPosition: Vector3;
  11. /**
  12. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  13. * @type {boolean}
  14. */
  15. public useCustomMeshPosition: boolean = false;
  16. /**
  17. * If the post-process should inverse the light scattering direction
  18. * @type {boolean}
  19. */
  20. public invert: boolean = true;
  21. /**
  22. * The internal mesh used by the post-process
  23. * @type {boolean}
  24. */
  25. public mesh: Mesh;
  26. /**
  27. * Array containing the excluded meshes not rendered in the internal pass
  28. */
  29. public excludedMeshes = new Array<AbstractMesh>();
  30. public exposure = 0.3;
  31. public decay = 0.96815;
  32. public weight = 0.58767;
  33. public density = 0.926;
  34. /**
  35. * @constructor
  36. * @param {string} name - The post-process name
  37. * @param {any} 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)
  38. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  39. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  40. * @param {number} samples - The post-process quality, default 100
  41. * @param {number} samplingMode - The post-process filtering mode
  42. * @param {BABYLON.Engine} engine - The babylon engine
  43. * @param {boolean} reusable - If the post-process is reusable
  44. */
  45. constructor(name: string, ratio: any, camera: Camera, mesh?: Mesh, samples: number = 100, samplingMode: number = Texture.BILINEAR_SAMPLINGMODE, engine?: Engine, reusable?: boolean) {
  46. super(name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  47. var scene = camera.getScene();
  48. this._viewPort = new Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  49. // Configure mesh
  50. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  51. // Configure
  52. this._createPass(scene, ratio.passRatio || ratio);
  53. this.onApply = (effect: Effect) => {
  54. this._updateMeshScreenCoordinates(scene);
  55. effect.setTexture("lightScatteringSampler", this._volumetricLightScatteringRTT);
  56. effect.setFloat("exposure", this.exposure);
  57. effect.setFloat("decay", this.decay);
  58. effect.setFloat("weight", this.weight);
  59. effect.setFloat("density", this.density);
  60. effect.setVector2("meshPositionOnScreen", this._screenCoordinates);
  61. };
  62. }
  63. public isReady(subMesh: SubMesh, useInstances: boolean): boolean {
  64. var mesh = subMesh.getMesh();
  65. var defines = [];
  66. var attribs = [VertexBuffer.PositionKind];
  67. var material: any = subMesh.getMaterial();
  68. // Render this.mesh as default
  69. if (mesh === this.mesh) {
  70. defines.push("#define BASIC_RENDER");
  71. }
  72. // Alpha test
  73. if (material) {
  74. if (material.needAlphaTesting() || mesh === this.mesh)
  75. defines.push("#define ALPHATEST");
  76. if (material.opacityTexture !== undefined)
  77. defines.push("#define OPACITY");
  78. if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  79. attribs.push(VertexBuffer.UVKind);
  80. defines.push("#define UV1");
  81. }
  82. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  83. attribs.push(VertexBuffer.UV2Kind);
  84. defines.push("#define UV2");
  85. }
  86. }
  87. // Bones
  88. if (mesh.useBones) {
  89. attribs.push(VertexBuffer.MatricesIndicesKind);
  90. attribs.push(VertexBuffer.MatricesWeightsKind);
  91. defines.push("#define BONES");
  92. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  93. }
  94. // Instances
  95. if (useInstances) {
  96. defines.push("#define INSTANCES");
  97. attribs.push("world0");
  98. attribs.push("world1");
  99. attribs.push("world2");
  100. attribs.push("world3");
  101. }
  102. // Get correct effect
  103. var join = defines.join("\n");
  104. if (this._cachedDefines !== join) {
  105. this._cachedDefines = join;
  106. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect(
  107. { vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" },
  108. attribs,
  109. ["world", "mBones", "viewProjection", "diffuseMatrix", "far"],
  110. ["diffuseSampler", "opacitySampler"], join);
  111. }
  112. return this._volumetricLightScatteringPass.isReady();
  113. }
  114. /**
  115. * Sets the new light position for light scattering effect
  116. * @param {BABYLON.Vector3} The new custom light position
  117. */
  118. public setCustomMeshPosition(position: Vector3): void {
  119. this._customMeshPosition = position;
  120. }
  121. /**
  122. * Returns the light position for light scattering effect
  123. * @return {BABYLON.Vector3} The custom light position
  124. */
  125. public getCustomMeshPosition(): Vector3 {
  126. return this._customMeshPosition;
  127. }
  128. /**
  129. * Disposes the internal assets and detaches the post-process from the camera
  130. */
  131. public dispose(camera: Camera): void {
  132. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  133. if (rttIndex !== -1) {
  134. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  135. }
  136. this._volumetricLightScatteringRTT.dispose();
  137. super.dispose(camera);
  138. }
  139. /**
  140. * Returns the render target texture used by the post-process
  141. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  142. */
  143. public getPass(): RenderTargetTexture {
  144. return this._volumetricLightScatteringRTT;
  145. }
  146. // Private methods
  147. private _meshExcluded(mesh: AbstractMesh) {
  148. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  149. return true;
  150. }
  151. return false;
  152. }
  153. private _createPass(scene: Scene, ratio: number): void {
  154. var engine = scene.getEngine();
  155. this._volumetricLightScatteringRTT = new RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, Engine.TEXTURETYPE_UNSIGNED_INT);
  156. this._volumetricLightScatteringRTT.wrapU = Texture.CLAMP_ADDRESSMODE;
  157. this._volumetricLightScatteringRTT.wrapV = Texture.CLAMP_ADDRESSMODE;
  158. this._volumetricLightScatteringRTT.renderList = null;
  159. this._volumetricLightScatteringRTT.renderParticles = false;
  160. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  161. // Custom render function for submeshes
  162. var renderSubMesh = (subMesh: SubMesh): void => {
  163. var mesh = subMesh.getRenderingMesh();
  164. if (this._meshExcluded(mesh)) {
  165. return;
  166. }
  167. var scene = mesh.getScene();
  168. var engine = scene.getEngine();
  169. // Culling
  170. engine.setState(subMesh.getMaterial().backFaceCulling);
  171. // Managing instances
  172. var batch = mesh._getInstancesRenderList(subMesh._id);
  173. if (batch.mustReturn) {
  174. return;
  175. }
  176. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  177. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  178. engine.enableEffect(this._volumetricLightScatteringPass);
  179. mesh._bind(subMesh, this._volumetricLightScatteringPass, Material.TriangleFillMode);
  180. var material: any = subMesh.getMaterial();
  181. this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  182. // Alpha test
  183. if (material && (mesh === this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  184. var alphaTexture = material.getAlphaTestTexture();
  185. this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  186. if (this.mesh.material && alphaTexture)
  187. this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  188. if (material.opacityTexture !== undefined)
  189. this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  190. }
  191. // Bones
  192. if (mesh.useBones) {
  193. this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  194. }
  195. // Draw
  196. mesh._processRendering(subMesh, this._volumetricLightScatteringPass, Material.TriangleFillMode, batch, hardwareInstancedRendering,
  197. (isInstance, world) => this._volumetricLightScatteringPass.setMatrix("world", world));
  198. }
  199. };
  200. // Render target texture callbacks
  201. var savedSceneClearColor: Color3;
  202. var sceneClearColor = new Color3(0.0, 0.0, 0.0);
  203. this._volumetricLightScatteringRTT.onBeforeRender = (): void => {
  204. savedSceneClearColor = scene.clearColor;
  205. scene.clearColor = sceneClearColor;
  206. };
  207. this._volumetricLightScatteringRTT.onAfterRender = (): void => {
  208. scene.clearColor = savedSceneClearColor;
  209. };
  210. this._volumetricLightScatteringRTT.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>): void => {
  211. var index;
  212. for (index = 0; index < opaqueSubMeshes.length; index++) {
  213. renderSubMesh(opaqueSubMeshes.data[index]);
  214. }
  215. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  216. renderSubMesh(alphaTestSubMeshes.data[index]);
  217. }
  218. for (index = 0; index < transparentSubMeshes.length; index++) {
  219. renderSubMesh(transparentSubMeshes.data[index]);
  220. }
  221. };
  222. }
  223. private _updateMeshScreenCoordinates(scene: Scene): void {
  224. var transform = scene.getTransformMatrix();
  225. var pos = Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, Matrix.Identity(), transform, this._viewPort);
  226. this._screenCoordinates.x = pos.x / this._viewPort.width;
  227. this._screenCoordinates.y = pos.y / this._viewPort.height;
  228. if (this.invert)
  229. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  230. }
  231. // Static methods
  232. /**
  233. * Creates a default mesh for the Volumeric Light Scattering post-process
  234. * @param {string} The mesh name
  235. * @param {BABYLON.Scene} The scene where to create the mesh
  236. * @return {BABYLON.Mesh} the default mesh
  237. */
  238. public static CreateDefaultMesh(name: string, scene: Scene): Mesh {
  239. var mesh = Mesh.CreatePlane(name, 1, scene);
  240. mesh.billboardMode = AbstractMesh.BILLBOARDMODE_ALL;
  241. mesh.material = new StandardMaterial(name + "Material", scene);
  242. return mesh;
  243. }
  244. }
  245. }