babylon.volumetricLightScatteringPostProcess.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. var needUV: boolean = false;
  69. // Render this.mesh as default
  70. if (mesh === this.mesh) {
  71. defines.push("#define BASIC_RENDER");
  72. defines.push("#define NEED_UV");
  73. needUV = true;
  74. }
  75. // Alpha test
  76. if (material) {
  77. if (material.needAlphaTesting() || mesh === this.mesh)
  78. defines.push("#define ALPHATEST");
  79. if (material.opacityTexture !== undefined) {
  80. defines.push("#define OPACITY");
  81. if (material.opacityTexture.getAlphaFromRGB)
  82. defines.push("#define OPACITYRGB");
  83. if (!needUV)
  84. defines.push("#define NEED_UV");
  85. }
  86. if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  87. attribs.push(VertexBuffer.UVKind);
  88. defines.push("#define UV1");
  89. }
  90. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  91. attribs.push(VertexBuffer.UV2Kind);
  92. defines.push("#define UV2");
  93. }
  94. }
  95. // Bones
  96. if (mesh.useBones) {
  97. attribs.push(VertexBuffer.MatricesIndicesKind);
  98. attribs.push(VertexBuffer.MatricesWeightsKind);
  99. defines.push("#define BONES");
  100. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  101. }
  102. // Instances
  103. if (useInstances) {
  104. defines.push("#define INSTANCES");
  105. attribs.push("world0");
  106. attribs.push("world1");
  107. attribs.push("world2");
  108. attribs.push("world3");
  109. }
  110. // Get correct effect
  111. var join = defines.join("\n");
  112. if (this._cachedDefines !== join) {
  113. this._cachedDefines = join;
  114. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect(
  115. { vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" },
  116. attribs,
  117. ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"],
  118. ["diffuseSampler", "opacitySampler"], join);
  119. }
  120. return this._volumetricLightScatteringPass.isReady();
  121. }
  122. /**
  123. * Sets the new light position for light scattering effect
  124. * @param {BABYLON.Vector3} The new custom light position
  125. */
  126. public setCustomMeshPosition(position: Vector3): void {
  127. this._customMeshPosition = position;
  128. }
  129. /**
  130. * Returns the light position for light scattering effect
  131. * @return {BABYLON.Vector3} The custom light position
  132. */
  133. public getCustomMeshPosition(): Vector3 {
  134. return this._customMeshPosition;
  135. }
  136. /**
  137. * Disposes the internal assets and detaches the post-process from the camera
  138. */
  139. public dispose(camera: Camera): void {
  140. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  141. if (rttIndex !== -1) {
  142. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  143. }
  144. this._volumetricLightScatteringRTT.dispose();
  145. super.dispose(camera);
  146. }
  147. /**
  148. * Returns the render target texture used by the post-process
  149. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  150. */
  151. public getPass(): RenderTargetTexture {
  152. return this._volumetricLightScatteringRTT;
  153. }
  154. // Private methods
  155. private _meshExcluded(mesh: AbstractMesh) {
  156. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  157. return true;
  158. }
  159. return false;
  160. }
  161. private _createPass(scene: Scene, ratio: number): void {
  162. var engine = scene.getEngine();
  163. this._volumetricLightScatteringRTT = new RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, Engine.TEXTURETYPE_UNSIGNED_INT);
  164. this._volumetricLightScatteringRTT.wrapU = Texture.CLAMP_ADDRESSMODE;
  165. this._volumetricLightScatteringRTT.wrapV = Texture.CLAMP_ADDRESSMODE;
  166. this._volumetricLightScatteringRTT.renderList = null;
  167. this._volumetricLightScatteringRTT.renderParticles = false;
  168. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  169. // Custom render function for submeshes
  170. var renderSubMesh = (subMesh: SubMesh): void => {
  171. var mesh = subMesh.getRenderingMesh();
  172. if (this._meshExcluded(mesh)) {
  173. return;
  174. }
  175. var scene = mesh.getScene();
  176. var engine = scene.getEngine();
  177. // Culling
  178. engine.setState(subMesh.getMaterial().backFaceCulling);
  179. // Managing instances
  180. var batch = mesh._getInstancesRenderList(subMesh._id);
  181. if (batch.mustReturn) {
  182. return;
  183. }
  184. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  185. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  186. engine.enableEffect(this._volumetricLightScatteringPass);
  187. mesh._bind(subMesh, this._volumetricLightScatteringPass, Material.TriangleFillMode);
  188. var material: any = subMesh.getMaterial();
  189. this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  190. // Alpha test
  191. if (material && (mesh === this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  192. var alphaTexture = material.getAlphaTestTexture();
  193. this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  194. if (alphaTexture) {
  195. this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  196. }
  197. if (material.opacityTexture !== undefined) {
  198. this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  199. this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  200. }
  201. }
  202. // Bones
  203. if (mesh.useBones) {
  204. this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  205. }
  206. // Draw
  207. mesh._processRendering(subMesh, this._volumetricLightScatteringPass, Material.TriangleFillMode, batch, hardwareInstancedRendering,
  208. (isInstance, world) => this._volumetricLightScatteringPass.setMatrix("world", world));
  209. }
  210. };
  211. // Render target texture callbacks
  212. var savedSceneClearColor: Color4;
  213. var sceneClearColor = new Color4(0.0, 0.0, 0.0, 1.0);
  214. this._volumetricLightScatteringRTT.onBeforeRender = (): void => {
  215. savedSceneClearColor = scene.clearColor;
  216. scene.clearColor = sceneClearColor;
  217. };
  218. this._volumetricLightScatteringRTT.onAfterRender = (): void => {
  219. scene.clearColor = savedSceneClearColor;
  220. };
  221. this._volumetricLightScatteringRTT.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>): void => {
  222. var engine = scene.getEngine();
  223. var index: number;
  224. for (index = 0; index < opaqueSubMeshes.length; index++) {
  225. renderSubMesh(opaqueSubMeshes.data[index]);
  226. }
  227. engine.setAlphaTesting(true);
  228. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  229. renderSubMesh(alphaTestSubMeshes.data[index]);
  230. }
  231. engine.setAlphaTesting(false);
  232. if (transparentSubMeshes.length) {
  233. // Sort sub meshes
  234. for (index = 0; index < transparentSubMeshes.length; index++) {
  235. var submesh = transparentSubMeshes.data[index];
  236. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  237. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  238. }
  239. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  240. sortedArray.sort((a, b) => {
  241. // Alpha index first
  242. if (a._alphaIndex > b._alphaIndex) {
  243. return 1;
  244. }
  245. if (a._alphaIndex < b._alphaIndex) {
  246. return -1;
  247. }
  248. // Then distance to camera
  249. if (a._distanceToCamera < b._distanceToCamera) {
  250. return 1;
  251. }
  252. if (a._distanceToCamera > b._distanceToCamera) {
  253. return -1;
  254. }
  255. return 0;
  256. });
  257. // Render sub meshes
  258. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  259. for (index = 0; index < sortedArray.length; index++) {
  260. renderSubMesh(sortedArray[index]);
  261. }
  262. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  263. }
  264. };
  265. }
  266. private _updateMeshScreenCoordinates(scene: Scene): void {
  267. var transform = scene.getTransformMatrix();
  268. var pos = Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, Matrix.Identity(), transform, this._viewPort);
  269. this._screenCoordinates.x = pos.x / this._viewPort.width;
  270. this._screenCoordinates.y = pos.y / this._viewPort.height;
  271. if (this.invert)
  272. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  273. }
  274. // Static methods
  275. /**
  276. * Creates a default mesh for the Volumeric Light Scattering post-process
  277. * @param {string} The mesh name
  278. * @param {BABYLON.Scene} The scene where to create the mesh
  279. * @return {BABYLON.Mesh} the default mesh
  280. */
  281. public static CreateDefaultMesh(name: string, scene: Scene): Mesh {
  282. var mesh = Mesh.CreatePlane(name, 1, scene);
  283. mesh.billboardMode = AbstractMesh.BILLBOARDMODE_ALL;
  284. mesh.material = new StandardMaterial(name + "Material", scene);
  285. return mesh;
  286. }
  287. }
  288. }