ssao2RenderingPipeline.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. import { Logger } from "../../../Misc/logger";
  2. import { serialize, SerializationHelper } from "../../../Misc/decorators";
  3. import { Vector3, TmpVectors } from "../../../Maths/math.vector";
  4. import { Camera } from "../../../Cameras/camera";
  5. import { Effect } from "../../../Materials/effect";
  6. import { Texture } from "../../../Materials/Textures/texture";
  7. import { DynamicTexture } from "../../../Materials/Textures/dynamicTexture";
  8. import { PostProcess } from "../../../PostProcesses/postProcess";
  9. import { PostProcessRenderPipeline } from "../../../PostProcesses/RenderPipeline/postProcessRenderPipeline";
  10. import { PostProcessRenderEffect } from "../../../PostProcesses/RenderPipeline/postProcessRenderEffect";
  11. import { PassPostProcess } from "../../../PostProcesses/passPostProcess";
  12. import { GeometryBufferRenderer } from "../../../Rendering/geometryBufferRenderer";
  13. import { Scene } from "../../../scene";
  14. import { _TypeStore } from '../../../Misc/typeStore';
  15. import { EngineStore } from '../../../Engines/engineStore';
  16. import "../../../PostProcesses/RenderPipeline/postProcessRenderPipelineManagerSceneComponent";
  17. import "../../../Shaders/ssao2.fragment";
  18. import "../../../Shaders/ssaoCombine.fragment";
  19. /**
  20. * Render pipeline to produce ssao effect
  21. */
  22. export class SSAO2RenderingPipeline extends PostProcessRenderPipeline {
  23. // Members
  24. /**
  25. * @ignore
  26. * The PassPostProcess id in the pipeline that contains the original scene color
  27. */
  28. public SSAOOriginalSceneColorEffect: string = "SSAOOriginalSceneColorEffect";
  29. /**
  30. * @ignore
  31. * The SSAO PostProcess id in the pipeline
  32. */
  33. public SSAORenderEffect: string = "SSAORenderEffect";
  34. /**
  35. * @ignore
  36. * The horizontal blur PostProcess id in the pipeline
  37. */
  38. public SSAOBlurHRenderEffect: string = "SSAOBlurHRenderEffect";
  39. /**
  40. * @ignore
  41. * The vertical blur PostProcess id in the pipeline
  42. */
  43. public SSAOBlurVRenderEffect: string = "SSAOBlurVRenderEffect";
  44. /**
  45. * @ignore
  46. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  47. */
  48. public SSAOCombineRenderEffect: string = "SSAOCombineRenderEffect";
  49. /**
  50. * The output strength of the SSAO post-process. Default value is 1.0.
  51. */
  52. @serialize()
  53. public totalStrength: number = 1.0;
  54. /**
  55. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  56. */
  57. @serialize()
  58. public maxZ: number = 100.0;
  59. /**
  60. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  61. */
  62. @serialize()
  63. public minZAspect: number = 0.2;
  64. @serialize("samples")
  65. private _samples: number = 8;
  66. /**
  67. * Number of samples used for the SSAO calculations. Default value is 8
  68. */
  69. public set samples(n: number) {
  70. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  71. this._samples = n;
  72. this._sampleSphere = this._generateHemisphere();
  73. this._firstUpdate = true;
  74. }
  75. public get samples(): number {
  76. return this._samples;
  77. }
  78. @serialize("textureSamples")
  79. private _textureSamples: number = 1;
  80. /**
  81. * Number of samples to use for antialiasing
  82. */
  83. public set textureSamples(n: number) {
  84. this._textureSamples = n;
  85. this._originalColorPostProcess.samples = n;
  86. this._blurHPostProcess.samples = n;
  87. this._blurVPostProcess.samples = n;
  88. this._ssaoPostProcess.samples = n;
  89. this._ssaoCombinePostProcess.samples = n;
  90. }
  91. public get textureSamples(): number {
  92. return this._textureSamples;
  93. }
  94. /**
  95. * Ratio object used for SSAO ratio and blur ratio
  96. */
  97. @serialize()
  98. private _ratio: any;
  99. /**
  100. * Dynamically generated sphere sampler.
  101. */
  102. private _sampleSphere: number[];
  103. /**
  104. * Blur filter offsets
  105. */
  106. private _samplerOffsets: number[];
  107. @serialize("expensiveBlur")
  108. private _expensiveBlur: boolean = true;
  109. /**
  110. * If bilateral blur should be used
  111. */
  112. public set expensiveBlur(b: boolean) {
  113. this._blurHPostProcess.updateEffect("#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n",
  114. null, ["textureSampler", "depthSampler"]);
  115. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n",
  116. null, ["textureSampler", "depthSampler"]);
  117. this._expensiveBlur = b;
  118. this._firstUpdate = true;
  119. }
  120. public get expensiveBlur(): boolean {
  121. return this._expensiveBlur;
  122. }
  123. /**
  124. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  125. */
  126. @serialize()
  127. public radius: number = 2.0;
  128. /**
  129. * The base color of the SSAO post-process
  130. * The final result is "base + ssao" between [0, 1]
  131. */
  132. @serialize()
  133. public base: number = 0;
  134. /**
  135. * Support test.
  136. */
  137. public static get IsSupported(): boolean {
  138. var engine = EngineStore.LastCreatedEngine;
  139. if (!engine) {
  140. return false;
  141. }
  142. return engine.getCaps().drawBuffersExtension;
  143. }
  144. private _scene: Scene;
  145. private _depthTexture: Texture;
  146. private _normalTexture: Texture;
  147. private _randomTexture: DynamicTexture;
  148. private _originalColorPostProcess: PassPostProcess;
  149. private _ssaoPostProcess: PostProcess;
  150. private _blurHPostProcess: PostProcess;
  151. private _blurVPostProcess: PostProcess;
  152. private _ssaoCombinePostProcess: PostProcess;
  153. private _firstUpdate: boolean = true;
  154. /**
  155. * Gets active scene
  156. */
  157. public get scene(): Scene {
  158. return this._scene;
  159. }
  160. /**
  161. * @constructor
  162. * @param name The rendering pipeline name
  163. * @param scene The scene linked to this pipeline
  164. * @param ratio The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  165. * @param cameras The array of cameras that the rendering pipeline will be attached to
  166. */
  167. constructor(name: string, scene: Scene, ratio: any, cameras?: Camera[]) {
  168. super(scene.getEngine(), name);
  169. this._scene = scene;
  170. this._ratio = ratio;
  171. if (!this.isSupported) {
  172. Logger.Error("SSAO 2 needs WebGL 2 support.");
  173. return;
  174. }
  175. var ssaoRatio = this._ratio.ssaoRatio || ratio;
  176. var blurRatio = this._ratio.blurRatio || ratio;
  177. // Set up assets
  178. let geometryBufferRenderer = <GeometryBufferRenderer>scene.enableGeometryBufferRenderer();
  179. this._createRandomTexture();
  180. this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  181. this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  182. this._originalColorPostProcess = new PassPostProcess("SSAOOriginalSceneColor", 1.0, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  183. this._originalColorPostProcess.samples = this.textureSamples;
  184. this._createSSAOPostProcess(1.0);
  185. this._createBlurPostProcess(ssaoRatio, blurRatio);
  186. this._createSSAOCombinePostProcess(blurRatio);
  187. // Set up pipeline
  188. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, () => { return this._originalColorPostProcess; }, true));
  189. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, () => { return this._ssaoPostProcess; }, true));
  190. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, () => { return this._blurHPostProcess; }, true));
  191. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, () => { return this._blurVPostProcess; }, true));
  192. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, () => { return this._ssaoCombinePostProcess; }, true));
  193. // Finish
  194. scene.postProcessRenderPipelineManager.addPipeline(this);
  195. if (cameras) {
  196. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  197. }
  198. }
  199. // Public Methods
  200. /**
  201. * Get the class name
  202. * @returns "SSAO2RenderingPipeline"
  203. */
  204. public getClassName(): string {
  205. return "SSAO2RenderingPipeline";
  206. }
  207. /**
  208. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  209. */
  210. public dispose(disableGeometryBufferRenderer: boolean = false): void {
  211. for (var i = 0; i < this._scene.cameras.length; i++) {
  212. var camera = this._scene.cameras[i];
  213. this._originalColorPostProcess.dispose(camera);
  214. this._ssaoPostProcess.dispose(camera);
  215. this._blurHPostProcess.dispose(camera);
  216. this._blurVPostProcess.dispose(camera);
  217. this._ssaoCombinePostProcess.dispose(camera);
  218. }
  219. this._randomTexture.dispose();
  220. if (disableGeometryBufferRenderer) {
  221. this._scene.disableGeometryBufferRenderer();
  222. }
  223. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  224. super.dispose();
  225. }
  226. // Private Methods
  227. private _createBlurPostProcess(ssaoRatio: number, blurRatio: number): void {
  228. this._samplerOffsets = [];
  229. var expensive = this.expensiveBlur;
  230. for (var i = -8; i < 8; i++) {
  231. this._samplerOffsets.push(i * 2 + 0.5);
  232. }
  233. this._blurHPostProcess = new PostProcess("BlurH", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], ssaoRatio, null, Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  234. this._blurHPostProcess.onApply = (effect: Effect) => {
  235. if (!this._scene.activeCamera) {
  236. return;
  237. }
  238. effect.setFloat("outSize", this._ssaoCombinePostProcess.width > 0 ? this._ssaoCombinePostProcess.width : this._originalColorPostProcess.width);
  239. effect.setFloat("near", this._scene.activeCamera.minZ);
  240. effect.setFloat("far", this._scene.activeCamera.maxZ);
  241. effect.setFloat("radius", this.radius);
  242. effect.setTexture("depthSampler", this._depthTexture);
  243. if (this._firstUpdate) {
  244. effect.setArray("samplerOffsets", this._samplerOffsets);
  245. }
  246. };
  247. this._blurVPostProcess = new PostProcess("BlurV", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], blurRatio, null, Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  248. this._blurVPostProcess.onApply = (effect: Effect) => {
  249. if (!this._scene.activeCamera) {
  250. return;
  251. }
  252. effect.setFloat("outSize", this._ssaoCombinePostProcess.height > 0 ? this._ssaoCombinePostProcess.height : this._originalColorPostProcess.height);
  253. effect.setFloat("near", this._scene.activeCamera.minZ);
  254. effect.setFloat("far", this._scene.activeCamera.maxZ);
  255. effect.setFloat("radius", this.radius);
  256. effect.setTexture("depthSampler", this._depthTexture);
  257. if (this._firstUpdate) {
  258. effect.setArray("samplerOffsets", this._samplerOffsets);
  259. this._firstUpdate = false;
  260. }
  261. };
  262. this._blurHPostProcess.samples = this.textureSamples;
  263. this._blurVPostProcess.samples = this.textureSamples;
  264. }
  265. /** @hidden */
  266. public _rebuild() {
  267. this._firstUpdate = true;
  268. super._rebuild();
  269. }
  270. private _bits = new Uint32Array(1);
  271. //Van der Corput radical inverse
  272. private _radicalInverse_VdC(i: number) {
  273. this._bits[0] = i;
  274. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  275. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  276. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  277. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  278. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  279. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  280. }
  281. private _hammersley(i: number, n: number) {
  282. return [i / n, this._radicalInverse_VdC(i)];
  283. }
  284. private _hemisphereSample_uniform(u: number, v: number): Vector3 {
  285. var phi = v * 2.0 * Math.PI;
  286. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  287. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  288. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  289. return new Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  290. }
  291. private _generateHemisphere(): number[] {
  292. var numSamples = this.samples;
  293. var result = [];
  294. var vector;
  295. var i = 0;
  296. while (i < numSamples) {
  297. if (numSamples < 16) {
  298. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  299. } else {
  300. var rand = this._hammersley(i, numSamples);
  301. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  302. }
  303. result.push(vector.x, vector.y, vector.z);
  304. i++;
  305. }
  306. return result;
  307. }
  308. private _createSSAOPostProcess(ratio: number): void {
  309. var numSamples = this.samples;
  310. this._sampleSphere = this._generateHemisphere();
  311. this._ssaoPostProcess = new PostProcess("ssao2", "ssao2",
  312. [
  313. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  314. "base", "range", "projection", "near", "far", "texelSize",
  315. "xViewport", "yViewport", "maxZ", "minZAspect"
  316. ],
  317. ["randomSampler", "normalSampler"],
  318. ratio, null, Texture.BILINEAR_SAMPLINGMODE,
  319. this._scene.getEngine(), false,
  320. "#define SAMPLES " + numSamples + "\n#define SSAO");
  321. this._ssaoPostProcess.onApply = (effect: Effect) => {
  322. if (this._firstUpdate) {
  323. effect.setArray3("sampleSphere", this._sampleSphere);
  324. effect.setFloat("randTextureTiles", 32.0);
  325. }
  326. if (!this._scene.activeCamera) {
  327. return;
  328. }
  329. effect.setFloat("samplesFactor", 1 / this.samples);
  330. effect.setFloat("totalStrength", this.totalStrength);
  331. effect.setFloat2("texelSize", 1 / this._ssaoPostProcess.width, 1 / this._ssaoPostProcess.height);
  332. effect.setFloat("radius", this.radius);
  333. effect.setFloat("maxZ", this.maxZ);
  334. effect.setFloat("minZAspect", this.minZAspect);
  335. effect.setFloat("base", this.base);
  336. effect.setFloat("near", this._scene.activeCamera.minZ);
  337. effect.setFloat("far", this._scene.activeCamera.maxZ);
  338. effect.setFloat("xViewport", Math.tan(this._scene.activeCamera.fov / 2) * this._scene.getEngine().getAspectRatio(this._scene.activeCamera, true));
  339. effect.setFloat("yViewport", Math.tan(this._scene.activeCamera.fov / 2));
  340. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  341. effect.setTexture("textureSampler", this._depthTexture);
  342. effect.setTexture("normalSampler", this._normalTexture);
  343. effect.setTexture("randomSampler", this._randomTexture);
  344. };
  345. this._ssaoPostProcess.samples = this.textureSamples;
  346. }
  347. private _createSSAOCombinePostProcess(ratio: number): void {
  348. this._ssaoCombinePostProcess = new PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"],
  349. ratio, null, Texture.BILINEAR_SAMPLINGMODE,
  350. this._scene.getEngine(), false);
  351. this._ssaoCombinePostProcess.onApply = (effect: Effect) => {
  352. let viewport = this._scene.activeCamera!.viewport;
  353. effect.setVector4("viewport", TmpVectors.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  354. effect.setTextureFromPostProcess("originalColor", this._originalColorPostProcess);
  355. };
  356. this._ssaoCombinePostProcess.samples = this.textureSamples;
  357. }
  358. private _createRandomTexture(): void {
  359. var size = 128;
  360. this._randomTexture = new DynamicTexture("SSAORandomTexture", size, this._scene, false, Texture.TRILINEAR_SAMPLINGMODE);
  361. this._randomTexture.wrapU = Texture.WRAP_ADDRESSMODE;
  362. this._randomTexture.wrapV = Texture.WRAP_ADDRESSMODE;
  363. var context = this._randomTexture.getContext();
  364. var rand = (min: number, max: number) => {
  365. return Math.random() * (max - min) + min;
  366. };
  367. var randVector = Vector3.Zero();
  368. for (var x = 0; x < size; x++) {
  369. for (var y = 0; y < size; y++) {
  370. randVector.x = rand(0.0, 1.0);
  371. randVector.y = rand(0.0, 1.0);
  372. randVector.z = 0.0;
  373. randVector.normalize();
  374. randVector.scaleInPlace(255);
  375. randVector.x = Math.floor(randVector.x);
  376. randVector.y = Math.floor(randVector.y);
  377. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  378. context.fillRect(x, y, 1, 1);
  379. }
  380. }
  381. this._randomTexture.update(false);
  382. }
  383. /**
  384. * Serialize the rendering pipeline (Used when exporting)
  385. * @returns the serialized object
  386. */
  387. public serialize(): any {
  388. var serializationObject = SerializationHelper.Serialize(this);
  389. serializationObject.customType = "SSAO2RenderingPipeline";
  390. return serializationObject;
  391. }
  392. /**
  393. * Parse the serialized pipeline
  394. * @param source Source pipeline.
  395. * @param scene The scene to load the pipeline to.
  396. * @param rootUrl The URL of the serialized pipeline.
  397. * @returns An instantiated pipeline from the serialized object.
  398. */
  399. public static Parse(source: any, scene: Scene, rootUrl: string): SSAO2RenderingPipeline {
  400. return SerializationHelper.Parse(() => new SSAO2RenderingPipeline(source._name, scene, source._ratio), source, scene, rootUrl);
  401. }
  402. }
  403. _TypeStore.RegisteredTypes["BABYLON.SSAO2RenderingPipeline"] = SSAO2RenderingPipeline;