babylon.volumetricLightScatteringPostProcess.ts 10 KB

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