babylon.volumetricLightScatteringPostProcess.ts 16 KB

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