babylon.volumetricLightScatteringPostProcess.ts 16 KB

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