babylon.volumetricLightScatteringPostProcess.ts 13 KB

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