babylon.volumetricLightScatteringPostProcess.ts 18 KB

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