volumetricLightScatteringPostProcess.ts 18 KB

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