ssao2RenderingPipeline.ts 21 KB

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