prePassRenderer.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. import { MultiRenderTarget } from "../Materials/Textures/multiRenderTarget";
  2. import { Scene } from "../scene";
  3. import { Engine } from "../Engines/engine";
  4. import { Constants } from "../Engines/constants";
  5. import { ImageProcessingPostProcess } from "../PostProcesses/imageProcessingPostProcess";
  6. import { PostProcess } from "../PostProcesses/postProcess";
  7. import { Effect } from "../Materials/effect";
  8. import { _DevTools } from '../Misc/devTools';
  9. import { Color4 } from "../Maths/math.color";
  10. import { PrePassEffectConfiguration } from "./prePassEffectConfiguration";
  11. import { Nullable } from "../types";
  12. import { AbstractMesh } from '../Meshes/abstractMesh';
  13. import { Material } from '../Materials/material';
  14. import { SubMesh } from '../Meshes/subMesh';
  15. import { GeometryBufferRenderer } from '../Rendering/geometryBufferRenderer';
  16. /**
  17. * Renders a pre pass of the scene
  18. * This means every mesh in the scene will be rendered to a render target texture
  19. * And then this texture will be composited to the rendering canvas with post processes
  20. * It is necessary for effects like subsurface scattering or deferred shading
  21. */
  22. export class PrePassRenderer {
  23. /** @hidden */
  24. public static _SceneComponentInitialization: (scene: Scene) => void = (_) => {
  25. throw _DevTools.WarnImport("PrePassRendererSceneComponent");
  26. }
  27. private _textureFormats = [
  28. {
  29. type: Constants.PREPASS_IRRADIANCE_TEXTURE_TYPE,
  30. format: Constants.TEXTURETYPE_HALF_FLOAT,
  31. },
  32. {
  33. type: Constants.PREPASS_POSITION_TEXTURE_TYPE,
  34. format: Constants.TEXTURETYPE_HALF_FLOAT,
  35. },
  36. {
  37. type: Constants.PREPASS_VELOCITY_TEXTURE_TYPE,
  38. format: Constants.TEXTURETYPE_HALF_FLOAT,
  39. },
  40. {
  41. type: Constants.PREPASS_REFLECTIVITY_TEXTURE_TYPE,
  42. format: Constants.TEXTURETYPE_UNSIGNED_INT,
  43. },
  44. {
  45. type: Constants.PREPASS_COLOR_TEXTURE_TYPE,
  46. format: Constants.TEXTURETYPE_HALF_FLOAT,
  47. },
  48. {
  49. type: Constants.PREPASS_DEPTHNORMAL_TEXTURE_TYPE,
  50. format: Constants.TEXTURETYPE_HALF_FLOAT,
  51. },
  52. {
  53. type: Constants.PREPASS_ALBEDO_TEXTURE_TYPE,
  54. format: Constants.TEXTURETYPE_UNSIGNED_INT,
  55. },
  56. ];
  57. /**
  58. * To save performance, we can excluded skinned meshes from the prepass
  59. */
  60. public excludedSkinnedMesh: AbstractMesh[] = [];
  61. /**
  62. * Force material to be excluded from the prepass
  63. * Can be useful when `useGeometryBufferFallback` is set to `true`
  64. * and you don't want a material to show in the effect.
  65. */
  66. public excludedMaterials: Material[] = [];
  67. private _textureIndices: number[] = [];
  68. private _scene: Scene;
  69. private _engine: Engine;
  70. private _isDirty: boolean = false;
  71. /**
  72. * Number of textures in the multi render target texture where the scene is directly rendered
  73. */
  74. public mrtCount: number = 0;
  75. /**
  76. * The render target where the scene is directly rendered
  77. */
  78. public prePassRT: MultiRenderTarget;
  79. private _multiRenderAttachments: number[];
  80. private _defaultAttachments: number[];
  81. private _clearAttachments: number[];
  82. private _postProcesses: PostProcess[] = [];
  83. private readonly _clearColor = new Color4(0, 0, 0, 0);
  84. /**
  85. * Image processing post process for composition
  86. */
  87. public imageProcessingPostProcess: ImageProcessingPostProcess;
  88. /**
  89. * Configuration for prepass effects
  90. */
  91. private _effectConfigurations: PrePassEffectConfiguration[] = [];
  92. private _mrtFormats: number[] = [];
  93. private _mrtLayout: number[];
  94. private _enabled: boolean = false;
  95. /**
  96. * Indicates if the prepass is enabled
  97. */
  98. public get enabled() {
  99. return this._enabled;
  100. }
  101. /**
  102. * How many samples are used for MSAA of the scene render target
  103. */
  104. public get samples() {
  105. return this.prePassRT.samples;
  106. }
  107. public set samples(n: number) {
  108. if (!this.imageProcessingPostProcess) {
  109. this._createCompositionEffect();
  110. }
  111. this.prePassRT.samples = n;
  112. }
  113. private _geometryBuffer: Nullable<GeometryBufferRenderer>;
  114. private _useGeometryBufferFallback = true;
  115. /**
  116. * Uses the geometry buffer renderer as a fallback for non prepass capable effects
  117. */
  118. public get useGeometryBufferFallback() : boolean {
  119. return this._useGeometryBufferFallback;
  120. }
  121. public set useGeometryBufferFallback(value: boolean) {
  122. this._useGeometryBufferFallback = value;
  123. if (value) {
  124. this._geometryBuffer = this._scene.enableGeometryBufferRenderer();
  125. if (!this._geometryBuffer) {
  126. // Not supported
  127. this._useGeometryBufferFallback = false;
  128. return;
  129. }
  130. this._geometryBuffer.renderList = [];
  131. this._geometryBuffer.linkPrePassRenderer(this);
  132. this._updateGeometryBufferLayout();
  133. } else {
  134. if (this._geometryBuffer) {
  135. this._geometryBuffer.unlinkPrePassRenderer();
  136. }
  137. this._geometryBuffer = null;
  138. this._scene.disableGeometryBufferRenderer();
  139. }
  140. }
  141. /**
  142. * Instanciates a prepass renderer
  143. * @param scene The scene
  144. */
  145. constructor(scene: Scene) {
  146. this._scene = scene;
  147. this._engine = scene.getEngine();
  148. PrePassRenderer._SceneComponentInitialization(this._scene);
  149. this._resetLayout();
  150. }
  151. private _initializeAttachments() {
  152. let gl = this._engine._gl;
  153. this._multiRenderAttachments = [];
  154. this._clearAttachments = [gl.NONE];
  155. this._defaultAttachments = [gl.COLOR_ATTACHMENT0];
  156. for (let i = 0; i < this.mrtCount; i++) {
  157. this._multiRenderAttachments.push((<any>gl)["COLOR_ATTACHMENT" + i]);
  158. if (i > 0) {
  159. this._clearAttachments.push((<any>gl)["COLOR_ATTACHMENT" + i]);
  160. this._defaultAttachments.push(gl.NONE);
  161. }
  162. }
  163. }
  164. private _createCompositionEffect() {
  165. this.prePassRT = new MultiRenderTarget("sceneprePassRT", { width: this._engine.getRenderWidth(), height: this._engine.getRenderHeight() }, this.mrtCount, this._scene,
  166. { generateMipMaps: false, generateDepthTexture: true, defaultType: Constants.TEXTURETYPE_UNSIGNED_INT, types: this._mrtFormats });
  167. this.prePassRT.samples = 1;
  168. this._initializeAttachments();
  169. if (this._useGeometryBufferFallback && !this._geometryBuffer) {
  170. // Initializes the link with geometry buffer
  171. this.useGeometryBufferFallback = true;
  172. }
  173. this.imageProcessingPostProcess = new ImageProcessingPostProcess("sceneCompositionPass", 1, null, undefined, this._engine);
  174. this.imageProcessingPostProcess.autoClear = false;
  175. }
  176. /**
  177. * Indicates if rendering a prepass is supported
  178. */
  179. public get isSupported() {
  180. return this._engine.webGLVersion > 1;
  181. }
  182. /**
  183. * Sets the proper output textures to draw in the engine.
  184. * @param effect The effect that is drawn. It can be or not be compatible with drawing to several output textures.
  185. * @param subMesh Submesh on which the effect is applied
  186. */
  187. public bindAttachmentsForEffect(effect: Effect, subMesh: SubMesh) {
  188. if (this.enabled) {
  189. if (effect._multiTarget) {
  190. this._engine.bindAttachments(this._multiRenderAttachments);
  191. } else {
  192. this._engine.bindAttachments(this._defaultAttachments);
  193. if (this._geometryBuffer) {
  194. const material = subMesh.getMaterial();
  195. if (material && this.excludedMaterials.indexOf(material) === -1) {
  196. this._geometryBuffer.renderList!.push(subMesh.getRenderingMesh());
  197. }
  198. }
  199. }
  200. }
  201. }
  202. /**
  203. * @hidden
  204. */
  205. public _beforeCameraDraw() {
  206. if (this._isDirty) {
  207. this._update();
  208. }
  209. if (this._geometryBuffer) {
  210. this._geometryBuffer.renderList!.length = 0;
  211. }
  212. this._bindFrameBuffer();
  213. }
  214. /**
  215. * @hidden
  216. */
  217. public _afterCameraDraw() {
  218. if (this._enabled) {
  219. const firstCameraPP = this._scene.activeCamera && this._scene.activeCamera._getFirstPostProcess();
  220. if (firstCameraPP) {
  221. this._scene.postProcessManager._prepareFrame();
  222. }
  223. this._scene.postProcessManager.directRender(this._postProcesses, firstCameraPP ? firstCameraPP.inputTexture : null);
  224. }
  225. }
  226. private _checkRTSize() {
  227. var requiredWidth = this._engine.getRenderWidth(true);
  228. var requiredHeight = this._engine.getRenderHeight(true);
  229. var width = this.prePassRT.getRenderWidth();
  230. var height = this.prePassRT.getRenderHeight();
  231. if (width !== requiredWidth || height !== requiredHeight) {
  232. this.prePassRT.resize({ width: requiredWidth, height: requiredHeight });
  233. this._updateGeometryBufferLayout();
  234. this._bindPostProcessChain();
  235. }
  236. }
  237. private _bindFrameBuffer() {
  238. if (this._enabled) {
  239. this._checkRTSize();
  240. var internalTexture = this.prePassRT.getInternalTexture();
  241. if (internalTexture) {
  242. this._engine.bindFramebuffer(internalTexture);
  243. }
  244. }
  245. }
  246. /**
  247. * Clears the scene render target (in the sense of settings pixels to the scene clear color value)
  248. */
  249. public clear() {
  250. if (this._enabled) {
  251. this._bindFrameBuffer();
  252. // Regular clear color with the scene clear color of the 1st attachment
  253. this._engine.clear(this._scene.clearColor,
  254. this._scene.autoClear || this._scene.forceWireframe || this._scene.forcePointsCloud,
  255. this._scene.autoClearDepthAndStencil,
  256. this._scene.autoClearDepthAndStencil);
  257. // Clearing other attachment with 0 on all other attachments
  258. this._engine.bindAttachments(this._clearAttachments);
  259. this._engine.clear(this._clearColor, true, false, false);
  260. this._engine.bindAttachments(this._defaultAttachments);
  261. }
  262. }
  263. private _setState(enabled: boolean) {
  264. this._enabled = enabled;
  265. this._scene.prePass = enabled;
  266. if (this.imageProcessingPostProcess) {
  267. this.imageProcessingPostProcess.imageProcessingConfiguration.applyByPostProcess = enabled;
  268. }
  269. }
  270. private _updateGeometryBufferLayout() {
  271. if (this._geometryBuffer) {
  272. this._geometryBuffer.resetLayout();
  273. const attachments = this._defaultAttachments.slice();
  274. const gl = this._scene.getEngine()._gl;
  275. attachments[0] = gl.NONE;
  276. // Depth + normal is always index 0 in geometry buffer
  277. let index = this.getIndex(Constants.PREPASS_DEPTHNORMAL_TEXTURE_TYPE);
  278. if (index !== -1) {
  279. this._geometryBuffer.linkInternalTexture(this.prePassRT.getInternalTexture()!);
  280. } else {
  281. this._geometryBuffer.linkInternalTexture(this.prePassRT.getInternalTexture()!);
  282. }
  283. const matches = [
  284. {
  285. prePassConstant: Constants.PREPASS_DEPTHNORMAL_TEXTURE_TYPE,
  286. geometryBufferConstant: GeometryBufferRenderer.DEPTHNORMAL_TEXTURE_TYPE,
  287. },
  288. {
  289. prePassConstant: Constants.PREPASS_POSITION_TEXTURE_TYPE,
  290. geometryBufferConstant: GeometryBufferRenderer.POSITION_TEXTURE_TYPE,
  291. },
  292. {
  293. prePassConstant: Constants.PREPASS_REFLECTIVITY_TEXTURE_TYPE,
  294. geometryBufferConstant: GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE,
  295. },
  296. {
  297. prePassConstant: Constants.PREPASS_VELOCITY_TEXTURE_TYPE,
  298. geometryBufferConstant: GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE,
  299. }
  300. ];
  301. // replace textures in the geometryBuffer RT
  302. for (let i = 0; i < matches.length; i++) {
  303. const index = this._mrtLayout.indexOf(matches[i].prePassConstant);
  304. if (index !== -1) {
  305. this._geometryBuffer.replaceTexture(this.prePassRT.textures[index], matches[i].geometryBufferConstant, index);
  306. attachments[index] = (<any>gl)["COLOR_ATTACHMENT" + index];
  307. }
  308. }
  309. this._geometryBuffer.setAttachments(attachments);
  310. }
  311. }
  312. /**
  313. * Adds an effect configuration to the prepass.
  314. * If an effect has already been added, it won't add it twice and will return the configuration
  315. * already present.
  316. * @param cfg the effect configuration
  317. * @return the effect configuration now used by the prepass
  318. */
  319. public addEffectConfiguration(cfg: PrePassEffectConfiguration) : PrePassEffectConfiguration {
  320. // Do not add twice
  321. for (let i = 0; i < this._effectConfigurations.length; i++) {
  322. if (this._effectConfigurations[i].name === cfg.name) {
  323. return this._effectConfigurations[i];
  324. }
  325. }
  326. this._effectConfigurations.push(cfg);
  327. return cfg;
  328. }
  329. /**
  330. * Returns the index of a texture in the multi render target texture array.
  331. * @param type Texture type
  332. * @return The index
  333. */
  334. public getIndex(type: number) : number {
  335. return this._textureIndices[type];
  336. }
  337. private _enable() {
  338. const previousMrtCount = this.mrtCount;
  339. for (let i = 0; i < this._effectConfigurations.length; i++) {
  340. if (this._effectConfigurations[i].enabled) {
  341. this._enableTextures(this._effectConfigurations[i].texturesRequired);
  342. }
  343. }
  344. if (this.prePassRT && this.mrtCount !== previousMrtCount) {
  345. this.prePassRT.updateCount(this.mrtCount, { types: this._mrtFormats });
  346. }
  347. this._updateGeometryBufferLayout();
  348. this._resetPostProcessChain();
  349. for (let i = 0; i < this._effectConfigurations.length; i++) {
  350. if (this._effectConfigurations[i].enabled) {
  351. if (!this._effectConfigurations[i].postProcess && this._effectConfigurations[i].createPostProcess) {
  352. this._effectConfigurations[i].createPostProcess!();
  353. }
  354. if (this._effectConfigurations[i].postProcess) {
  355. this._postProcesses.push(this._effectConfigurations[i].postProcess!);
  356. }
  357. }
  358. }
  359. this._initializeAttachments();
  360. if (!this.imageProcessingPostProcess) {
  361. this._createCompositionEffect();
  362. }
  363. this._postProcesses.push(this.imageProcessingPostProcess);
  364. this._bindPostProcessChain();
  365. this._setState(true);
  366. }
  367. private _disable() {
  368. this._setState(false);
  369. this._resetLayout();
  370. for (let i = 0; i < this._effectConfigurations.length; i++) {
  371. this._effectConfigurations[i].enabled = false;
  372. }
  373. }
  374. private _resetLayout() {
  375. for (let i = 0 ; i < this._textureFormats.length; i++) {
  376. this._textureIndices[this._textureFormats[i].type] = -1;
  377. }
  378. this._textureIndices[Constants.PREPASS_COLOR_TEXTURE_TYPE] = 0;
  379. this._mrtLayout = [Constants.PREPASS_COLOR_TEXTURE_TYPE];
  380. this._mrtFormats = [Constants.TEXTURETYPE_HALF_FLOAT];
  381. this.mrtCount = 1;
  382. }
  383. private _resetPostProcessChain() {
  384. this._postProcesses = [];
  385. if (this.imageProcessingPostProcess) {
  386. this.imageProcessingPostProcess.restoreDefaultInputTexture();
  387. }
  388. for (let i = 0; i < this._effectConfigurations.length; i++) {
  389. if (this._effectConfigurations[i].postProcess) {
  390. this._effectConfigurations[i].postProcess!.restoreDefaultInputTexture();
  391. }
  392. }
  393. }
  394. private _bindPostProcessChain() {
  395. this._postProcesses[0].inputTexture = this.prePassRT.getInternalTexture()!;
  396. }
  397. /**
  398. * Marks the prepass renderer as dirty, triggering a check if the prepass is necessary for the next rendering.
  399. */
  400. public markAsDirty() {
  401. this._isDirty = true;
  402. }
  403. /**
  404. * Enables a texture on the MultiRenderTarget for prepass
  405. */
  406. private _enableTextures(types: number[]) {
  407. for (let i = 0; i < types.length; i++) {
  408. let type = types[i];
  409. if (this._textureIndices[type] === -1) {
  410. this._textureIndices[type] = this._mrtLayout.length;
  411. this._mrtLayout.push(type);
  412. this._mrtFormats.push(this._textureFormats[type].format);
  413. this.mrtCount++;
  414. }
  415. }
  416. }
  417. private _update() {
  418. this._disable();
  419. let enablePrePass = false;
  420. for (let i = 0; i < this._scene.materials.length; i++) {
  421. if (this._scene.materials[i].setPrePassRenderer(this)) {
  422. enablePrePass = true;
  423. }
  424. }
  425. const camera = this._scene.activeCamera;
  426. if (!camera) {
  427. return;
  428. }
  429. const postProcesses = (<Nullable<PostProcess[]>>camera._postProcesses.filter((pp) => { return pp != null; }));
  430. if (postProcesses) {
  431. for (let i = 0; i < postProcesses.length; i++) {
  432. if (postProcesses[i].setPrePassRenderer(this)) {
  433. enablePrePass = true;
  434. }
  435. }
  436. }
  437. this._markAllMaterialsAsPrePassDirty();
  438. this._isDirty = false;
  439. if (enablePrePass) {
  440. this._enable();
  441. }
  442. if (!this.enabled) {
  443. // Prepass disabled, we render only on 1 color attachment
  444. this._engine.bindAttachments([this._engine._gl.BACK]);
  445. }
  446. }
  447. private _markAllMaterialsAsPrePassDirty() {
  448. const materials = this._scene.materials;
  449. for (let i = 0; i < materials.length; i++) {
  450. materials[i].markAsDirty(Material.PrePassDirtyFlag);
  451. }
  452. }
  453. /**
  454. * Disposes the prepass renderer.
  455. */
  456. public dispose() {
  457. for (let i = 0; i < this._effectConfigurations.length; i++) {
  458. if (this._effectConfigurations[i].dispose) {
  459. this._effectConfigurations[i].dispose!();
  460. }
  461. }
  462. this.imageProcessingPostProcess.dispose();
  463. this.prePassRT.dispose();
  464. }
  465. }