renderTargetTexture.ts 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  1. import { Observer, Observable } from "../../Misc/observable";
  2. import { Tools } from "../../Misc/tools";
  3. import { SmartArray } from "../../Misc/smartArray";
  4. import { Nullable } from "../../types";
  5. import { Camera } from "../../Cameras/camera";
  6. import { Scene } from "../../scene";
  7. import { Matrix, Vector3, Color4 } from "../../Maths/math";
  8. import { RenderTargetCreationOptions } from "../../Materials/Textures/renderTargetCreationOptions";
  9. import { AbstractMesh } from "../../Meshes/abstractMesh";
  10. import { SubMesh } from "../../Meshes/subMesh";
  11. import { InternalTexture } from "../../Materials/Textures/internalTexture";
  12. import { Texture } from "../../Materials/Textures/texture";
  13. import { PostProcessManager } from "../../PostProcesses/postProcessManager";
  14. import { PostProcess } from "../../PostProcesses/postProcess";
  15. import { RenderingManager } from "../../Rendering/renderingManager";
  16. import { Constants } from "../../Engines/constants";
  17. declare type Engine = import("../../Engines/engine").Engine;
  18. /**
  19. * This Helps creating a texture that will be created from a camera in your scene.
  20. * It is basically a dynamic texture that could be used to create special effects for instance.
  21. * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...
  22. */
  23. export class RenderTargetTexture extends Texture {
  24. /**
  25. * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.
  26. */
  27. public static readonly REFRESHRATE_RENDER_ONCE: number = 0;
  28. /**
  29. * The texture will only be rendered rendered every frame and is recomended for dynamic contents.
  30. */
  31. public static readonly REFRESHRATE_RENDER_ONEVERYFRAME: number = 1;
  32. /**
  33. * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not
  34. * the central point of your effect and can save a lot of performances.
  35. */
  36. public static readonly REFRESHRATE_RENDER_ONEVERYTWOFRAMES: number = 2;
  37. /**
  38. * Use this predicate to dynamically define the list of mesh you want to render.
  39. * If set, the renderList property will be overwritten.
  40. */
  41. public renderListPredicate: (AbstractMesh: AbstractMesh) => boolean;
  42. private _renderList: Nullable<Array<AbstractMesh>>;
  43. /**
  44. * Use this list to define the list of mesh you want to render.
  45. */
  46. public get renderList(): Nullable<Array<AbstractMesh>> {
  47. return this._renderList;
  48. }
  49. public set renderList(value: Nullable<Array<AbstractMesh>>) {
  50. this._renderList = value;
  51. if (this._renderList) {
  52. this._hookArray(this._renderList);
  53. }
  54. }
  55. private _hookArray(array: AbstractMesh[]): void {
  56. var oldPush = array.push;
  57. array.push = (...items: AbstractMesh[]) => {
  58. let wasEmpty = array.length === 0;
  59. var result = oldPush.apply(array, items);
  60. if (wasEmpty) {
  61. this.getScene()!.meshes.forEach((mesh) => {
  62. mesh._markSubMeshesAsLightDirty();
  63. });
  64. }
  65. return result;
  66. };
  67. var oldSplice = array.splice;
  68. array.splice = (index: number, deleteCount?: number) => {
  69. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70. if (array.length === 0) {
  71. this.getScene()!.meshes.forEach((mesh) => {
  72. mesh._markSubMeshesAsLightDirty();
  73. });
  74. }
  75. return deleted;
  76. };
  77. }
  78. /**
  79. * Define if particles should be rendered in your texture.
  80. */
  81. public renderParticles = true;
  82. /**
  83. * Define if sprites should be rendered in your texture.
  84. */
  85. public renderSprites = false;
  86. /**
  87. * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures.
  88. */
  89. public coordinatesMode = Texture.PROJECTION_MODE;
  90. /**
  91. * Define the camera used to render the texture.
  92. */
  93. public activeCamera: Nullable<Camera>;
  94. /**
  95. * Override the render function of the texture with your own one.
  96. */
  97. public customRenderFunction: (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>, depthOnlySubMeshes: SmartArray<SubMesh>, beforeTransparents?: () => void) => void;
  98. /**
  99. * Define if camera post processes should be use while rendering the texture.
  100. */
  101. public useCameraPostProcesses: boolean;
  102. /**
  103. * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.
  104. */
  105. public ignoreCameraViewport: boolean = false;
  106. private _postProcessManager: Nullable<PostProcessManager>;
  107. private _postProcesses: PostProcess[];
  108. private _resizeObserver: Nullable<Observer<Engine>>;
  109. /**
  110. * An event triggered when the texture is unbind.
  111. */
  112. public onBeforeBindObservable = new Observable<RenderTargetTexture>();
  113. /**
  114. * An event triggered when the texture is unbind.
  115. */
  116. public onAfterUnbindObservable = new Observable<RenderTargetTexture>();
  117. private _onAfterUnbindObserver: Nullable<Observer<RenderTargetTexture>>;
  118. /**
  119. * Set a after unbind callback in the texture.
  120. * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.
  121. */
  122. public set onAfterUnbind(callback: () => void) {
  123. if (this._onAfterUnbindObserver) {
  124. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  125. }
  126. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  127. }
  128. /**
  129. * An event triggered before rendering the texture
  130. */
  131. public onBeforeRenderObservable = new Observable<number>();
  132. private _onBeforeRenderObserver: Nullable<Observer<number>>;
  133. /**
  134. * Set a before render callback in the texture.
  135. * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.
  136. */
  137. public set onBeforeRender(callback: (faceIndex: number) => void) {
  138. if (this._onBeforeRenderObserver) {
  139. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  140. }
  141. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  142. }
  143. /**
  144. * An event triggered after rendering the texture
  145. */
  146. public onAfterRenderObservable = new Observable<number>();
  147. private _onAfterRenderObserver: Nullable<Observer<number>>;
  148. /**
  149. * Set a after render callback in the texture.
  150. * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.
  151. */
  152. public set onAfterRender(callback: (faceIndex: number) => void) {
  153. if (this._onAfterRenderObserver) {
  154. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  155. }
  156. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  157. }
  158. /**
  159. * An event triggered after the texture clear
  160. */
  161. public onClearObservable = new Observable<Engine>();
  162. private _onClearObserver: Nullable<Observer<Engine>>;
  163. /**
  164. * Set a clear callback in the texture.
  165. * This has been kept for backward compatibility and use of onClearObservable is recommended.
  166. */
  167. public set onClear(callback: (Engine: Engine) => void) {
  168. if (this._onClearObserver) {
  169. this.onClearObservable.remove(this._onClearObserver);
  170. }
  171. this._onClearObserver = this.onClearObservable.add(callback);
  172. }
  173. /**
  174. * Define the clear color of the Render Target if it should be different from the scene.
  175. */
  176. public clearColor: Color4;
  177. protected _size: number | { width: number, height: number };
  178. protected _initialSizeParameter: number | { width: number, height: number } | { ratio: number };
  179. protected _sizeRatio: Nullable<number>;
  180. /** @hidden */
  181. public _generateMipMaps: boolean;
  182. protected _renderingManager: RenderingManager;
  183. /** @hidden */
  184. public _waitingRenderList: string[];
  185. protected _doNotChangeAspectRatio: boolean;
  186. protected _currentRefreshId = -1;
  187. protected _refreshRate = 1;
  188. protected _textureMatrix: Matrix;
  189. protected _samples = 1;
  190. protected _renderTargetOptions: RenderTargetCreationOptions;
  191. /**
  192. * Gets render target creation options that were used.
  193. */
  194. public get renderTargetOptions(): RenderTargetCreationOptions {
  195. return this._renderTargetOptions;
  196. }
  197. protected _engine: Engine;
  198. protected _onRatioRescale(): void {
  199. if (this._sizeRatio) {
  200. this.resize(this._initialSizeParameter);
  201. }
  202. }
  203. /**
  204. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  205. * It must define where the camera used to render the texture is set
  206. */
  207. public boundingBoxPosition = Vector3.Zero();
  208. private _boundingBoxSize: Vector3;
  209. /**
  210. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  211. * When defined, the cubemap will switch to local mode
  212. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  213. * @example https://www.babylonjs-playground.com/#RNASML
  214. */
  215. public set boundingBoxSize(value: Vector3) {
  216. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  217. return;
  218. }
  219. this._boundingBoxSize = value;
  220. let scene = this.getScene();
  221. if (scene) {
  222. scene.markAllMaterialsAsDirty(Constants.MATERIAL_TextureDirtyFlag);
  223. }
  224. }
  225. public get boundingBoxSize(): Vector3 {
  226. return this._boundingBoxSize;
  227. }
  228. /**
  229. * In case the RTT has been created with a depth texture, get the associated
  230. * depth texture.
  231. * Otherwise, return null.
  232. */
  233. public depthStencilTexture: Nullable<InternalTexture>;
  234. /**
  235. * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse
  236. * or used a shadow, depth texture...
  237. * @param name The friendly name of the texture
  238. * @param size The size of the RTT (number if square, or {width: number, height:number} or {ratio:} to define a ratio from the main scene)
  239. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  240. * @param generateMipMaps True if mip maps need to be generated after render.
  241. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  242. * @param type The type of the buffer in the RTT (int, half float, float...)
  243. * @param isCube True if a cube texture needs to be created
  244. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  245. * @param generateDepthBuffer True to generate a depth buffer
  246. * @param generateStencilBuffer True to generate a stencil buffer
  247. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  248. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  249. * @param delayAllocation if the texture allocation should be delayed (default: false)
  250. */
  251. constructor(name: string, size: number | { width: number, height: number } | { ratio: number }, scene: Nullable<Scene>, generateMipMaps?: boolean, doNotChangeAspectRatio: boolean = true, type: number = Constants.TEXTURETYPE_UNSIGNED_INT, public isCube = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, generateDepthBuffer = true, generateStencilBuffer = false, isMulti = false, format = Constants.TEXTUREFORMAT_RGBA, delayAllocation = false) {
  252. super(null, scene, !generateMipMaps);
  253. scene = this.getScene();
  254. if (!scene) {
  255. return;
  256. }
  257. this.renderList = new Array<AbstractMesh>();
  258. this._engine = scene.getEngine();
  259. this.name = name;
  260. this.isRenderTarget = true;
  261. this._initialSizeParameter = size;
  262. this._processSizeParameter(size);
  263. this._resizeObserver = this.getScene()!.getEngine().onResizeObservable.add(() => {
  264. });
  265. this._generateMipMaps = generateMipMaps ? true : false;
  266. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  267. // Rendering groups
  268. this._renderingManager = new RenderingManager(scene);
  269. this._renderingManager._useSceneAutoClearSetup = true;
  270. if (isMulti) {
  271. return;
  272. }
  273. this._renderTargetOptions = {
  274. generateMipMaps: generateMipMaps,
  275. type: type,
  276. format: format,
  277. samplingMode: samplingMode,
  278. generateDepthBuffer: generateDepthBuffer,
  279. generateStencilBuffer: generateStencilBuffer
  280. };
  281. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  282. this.wrapU = Texture.CLAMP_ADDRESSMODE;
  283. this.wrapV = Texture.CLAMP_ADDRESSMODE;
  284. }
  285. if (!delayAllocation) {
  286. if (isCube) {
  287. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  288. this.coordinatesMode = Texture.INVCUBIC_MODE;
  289. this._textureMatrix = Matrix.Identity();
  290. } else {
  291. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  292. }
  293. }
  294. }
  295. /**
  296. * Creates a depth stencil texture.
  297. * This is only available in WebGL 2 or with the depth texture extension available.
  298. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  299. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  300. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  301. */
  302. public createDepthStencilTexture(comparisonFunction: number = 0, bilinearFiltering: boolean = true, generateStencil: boolean = false): void {
  303. if (!this.getScene()) {
  304. return;
  305. }
  306. var engine = this.getScene()!.getEngine();
  307. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  308. bilinearFiltering,
  309. comparisonFunction,
  310. generateStencil,
  311. isCube: this.isCube
  312. });
  313. engine.setFrameBufferDepthStencilTexture(this);
  314. }
  315. private _processSizeParameter(size: number | { width: number, height: number } | { ratio: number }): void {
  316. if ((<{ ratio: number }>size).ratio) {
  317. this._sizeRatio = (<{ ratio: number }>size).ratio;
  318. this._size = {
  319. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  320. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  321. };
  322. } else {
  323. this._size = <number | { width: number, height: number }>size;
  324. }
  325. }
  326. /**
  327. * Define the number of samples to use in case of MSAA.
  328. * It defaults to one meaning no MSAA has been enabled.
  329. */
  330. public get samples(): number {
  331. return this._samples;
  332. }
  333. public set samples(value: number) {
  334. if (this._samples === value) {
  335. return;
  336. }
  337. let scene = this.getScene();
  338. if (!scene) {
  339. return;
  340. }
  341. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  342. }
  343. /**
  344. * Resets the refresh counter of the texture and start bak from scratch.
  345. * Could be useful to regenerate the texture if it is setup to render only once.
  346. */
  347. public resetRefreshCounter(): void {
  348. this._currentRefreshId = -1;
  349. }
  350. /**
  351. * Define the refresh rate of the texture or the rendering frequency.
  352. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  353. */
  354. public get refreshRate(): number {
  355. return this._refreshRate;
  356. }
  357. public set refreshRate(value: number) {
  358. this._refreshRate = value;
  359. this.resetRefreshCounter();
  360. }
  361. /**
  362. * Adds a post process to the render target rendering passes.
  363. * @param postProcess define the post process to add
  364. */
  365. public addPostProcess(postProcess: PostProcess): void {
  366. if (!this._postProcessManager) {
  367. let scene = this.getScene();
  368. if (!scene) {
  369. return;
  370. }
  371. this._postProcessManager = new PostProcessManager(scene);
  372. this._postProcesses = new Array<PostProcess>();
  373. }
  374. this._postProcesses.push(postProcess);
  375. this._postProcesses[0].autoClear = false;
  376. }
  377. /**
  378. * Clear all the post processes attached to the render target
  379. * @param dispose define if the cleared post processesshould also be disposed (false by default)
  380. */
  381. public clearPostProcesses(dispose: boolean = false): void {
  382. if (!this._postProcesses) {
  383. return;
  384. }
  385. if (dispose) {
  386. for (var postProcess of this._postProcesses) {
  387. postProcess.dispose();
  388. }
  389. }
  390. this._postProcesses = [];
  391. }
  392. /**
  393. * Remove one of the post process from the list of attached post processes to the texture
  394. * @param postProcess define the post process to remove from the list
  395. */
  396. public removePostProcess(postProcess: PostProcess): void {
  397. if (!this._postProcesses) {
  398. return;
  399. }
  400. var index = this._postProcesses.indexOf(postProcess);
  401. if (index === -1) {
  402. return;
  403. }
  404. this._postProcesses.splice(index, 1);
  405. if (this._postProcesses.length > 0) {
  406. this._postProcesses[0].autoClear = false;
  407. }
  408. }
  409. /** @hidden */
  410. public _shouldRender(): boolean {
  411. if (this._currentRefreshId === -1) { // At least render once
  412. this._currentRefreshId = 1;
  413. return true;
  414. }
  415. if (this.refreshRate === this._currentRefreshId) {
  416. this._currentRefreshId = 1;
  417. return true;
  418. }
  419. this._currentRefreshId++;
  420. return false;
  421. }
  422. /**
  423. * Gets the actual render size of the texture.
  424. * @returns the width of the render size
  425. */
  426. public getRenderSize(): number {
  427. return this.getRenderWidth();
  428. }
  429. /**
  430. * Gets the actual render width of the texture.
  431. * @returns the width of the render size
  432. */
  433. public getRenderWidth(): number {
  434. if ((<{ width: number, height: number }>this._size).width) {
  435. return (<{ width: number, height: number }>this._size).width;
  436. }
  437. return <number>this._size;
  438. }
  439. /**
  440. * Gets the actual render height of the texture.
  441. * @returns the height of the render size
  442. */
  443. public getRenderHeight(): number {
  444. if ((<{ width: number, height: number }>this._size).width) {
  445. return (<{ width: number, height: number }>this._size).height;
  446. }
  447. return <number>this._size;
  448. }
  449. /**
  450. * Get if the texture can be rescaled or not.
  451. */
  452. public get canRescale(): boolean {
  453. return true;
  454. }
  455. /**
  456. * Resize the texture using a ratio.
  457. * @param ratio the ratio to apply to the texture size in order to compute the new target size
  458. */
  459. public scale(ratio: number): void {
  460. var newSize = this.getRenderSize() * ratio;
  461. this.resize(newSize);
  462. }
  463. /**
  464. * Get the texture reflection matrix used to rotate/transform the reflection.
  465. * @returns the reflection matrix
  466. */
  467. public getReflectionTextureMatrix(): Matrix {
  468. if (this.isCube) {
  469. return this._textureMatrix;
  470. }
  471. return super.getReflectionTextureMatrix();
  472. }
  473. /**
  474. * Resize the texture to a new desired size.
  475. * Be carrefull as it will recreate all the data in the new texture.
  476. * @param size Define the new size. It can be:
  477. * - a number for squared texture,
  478. * - an object containing { width: number, height: number }
  479. * - or an object containing a ratio { ratio: number }
  480. */
  481. public resize(size: number | { width: number, height: number } | { ratio: number }): void {
  482. this.releaseInternalTexture();
  483. let scene = this.getScene();
  484. if (!scene) {
  485. return;
  486. }
  487. this._processSizeParameter(size);
  488. if (this.isCube) {
  489. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  490. } else {
  491. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  492. }
  493. }
  494. /**
  495. * Renders all the objects from the render list into the texture.
  496. * @param useCameraPostProcess Define if camera post processes should be used during the rendering
  497. * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose
  498. */
  499. public render(useCameraPostProcess: boolean = false, dumpForDebug: boolean = false): void {
  500. var scene = this.getScene();
  501. if (!scene) {
  502. return;
  503. }
  504. var engine = scene.getEngine();
  505. if (this.useCameraPostProcesses !== undefined) {
  506. useCameraPostProcess = this.useCameraPostProcesses;
  507. }
  508. if (this._waitingRenderList) {
  509. this.renderList = [];
  510. for (var index = 0; index < this._waitingRenderList.length; index++) {
  511. var id = this._waitingRenderList[index];
  512. let mesh = scene.getMeshByID(id);
  513. if (mesh) {
  514. this.renderList.push(mesh);
  515. }
  516. }
  517. delete this._waitingRenderList;
  518. }
  519. // Is predicate defined?
  520. if (this.renderListPredicate) {
  521. if (this.renderList) {
  522. this.renderList.length = 0; // Clear previous renderList
  523. } else {
  524. this.renderList = [];
  525. }
  526. var scene = this.getScene();
  527. if (!scene) {
  528. return;
  529. }
  530. var sceneMeshes = scene.meshes;
  531. for (var index = 0; index < sceneMeshes.length; index++) {
  532. var mesh = sceneMeshes[index];
  533. if (this.renderListPredicate(mesh)) {
  534. this.renderList.push(mesh);
  535. }
  536. }
  537. }
  538. this.onBeforeBindObservable.notifyObservers(this);
  539. // Set custom projection.
  540. // Needs to be before binding to prevent changing the aspect ratio.
  541. let camera: Nullable<Camera>;
  542. if (this.activeCamera) {
  543. camera = this.activeCamera;
  544. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  545. if (this.activeCamera !== scene.activeCamera) {
  546. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  547. }
  548. }
  549. else {
  550. camera = scene.activeCamera;
  551. if (camera) {
  552. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  553. }
  554. }
  555. // Prepare renderingManager
  556. this._renderingManager.reset();
  557. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  558. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  559. var sceneRenderId = scene.getRenderId();
  560. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  561. var mesh = currentRenderList[meshIndex];
  562. if (mesh) {
  563. if (!mesh.isReady(this.refreshRate === 0)) {
  564. this.resetRefreshCounter();
  565. continue;
  566. }
  567. mesh._preActivateForIntermediateRendering(sceneRenderId);
  568. let isMasked;
  569. if (!this.renderList && camera) {
  570. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  571. } else {
  572. isMasked = false;
  573. }
  574. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  575. mesh._activate(sceneRenderId);
  576. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  577. var subMesh = mesh.subMeshes[subIndex];
  578. scene._activeIndices.addCount(subMesh.indexCount, false);
  579. this._renderingManager.dispatch(subMesh, mesh);
  580. }
  581. }
  582. }
  583. }
  584. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  585. var particleSystem = scene.particleSystems[particleIndex];
  586. let emitter: any = particleSystem.emitter;
  587. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  588. continue;
  589. }
  590. if (currentRenderList.indexOf(emitter) >= 0) {
  591. this._renderingManager.dispatchParticles(particleSystem);
  592. }
  593. }
  594. if (this.isCube) {
  595. for (var face = 0; face < 6; face++) {
  596. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  597. scene.incrementRenderId();
  598. scene.resetCachedMaterial();
  599. }
  600. } else {
  601. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  602. }
  603. this.onAfterUnbindObservable.notifyObservers(this);
  604. if (scene.activeCamera) {
  605. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  606. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  607. }
  608. engine.setViewport(scene.activeCamera.viewport);
  609. }
  610. scene.resetCachedMaterial();
  611. }
  612. private _bestReflectionRenderTargetDimension(renderDimension: number, scale: number): number {
  613. let minimum = 128;
  614. let x = renderDimension * scale;
  615. let curved = Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  616. // Ensure we don't exceed the render dimension (while staying POT)
  617. return Math.min(Tools.FloorPOT(renderDimension), curved);
  618. }
  619. public _bindFrameBuffer(faceIndex: number = 0) {
  620. var scene = this.getScene();
  621. if (!scene) {
  622. return;
  623. }
  624. var engine = scene.getEngine();
  625. if (this._texture) {
  626. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  627. }
  628. }
  629. protected unbindFrameBuffer(engine: Engine, faceIndex: number): void {
  630. if (!this._texture) {
  631. return;
  632. }
  633. engine.unBindFramebuffer(this._texture, this.isCube, () => {
  634. this.onAfterRenderObservable.notifyObservers(faceIndex);
  635. });
  636. }
  637. private renderToTarget(faceIndex: number, currentRenderList: AbstractMesh[], useCameraPostProcess: boolean, dumpForDebug: boolean): void {
  638. var scene = this.getScene();
  639. if (!scene) {
  640. return;
  641. }
  642. var engine = scene.getEngine();
  643. if (!this._texture) {
  644. return;
  645. }
  646. // Bind
  647. if (this._postProcessManager) {
  648. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  649. }
  650. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  651. this._bindFrameBuffer(faceIndex);
  652. }
  653. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  654. // Clear
  655. if (this.onClearObservable.hasObservers()) {
  656. this.onClearObservable.notifyObservers(engine);
  657. } else {
  658. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  659. }
  660. if (!this._doNotChangeAspectRatio) {
  661. scene.updateTransformMatrix(true);
  662. }
  663. // Before Camera Draw
  664. for (let step of scene._beforeRenderTargetDrawStage) {
  665. step.action(this);
  666. }
  667. // Render
  668. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  669. // After Camera Draw
  670. for (let step of scene._afterRenderTargetDrawStage) {
  671. step.action(this);
  672. }
  673. if (this._postProcessManager) {
  674. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  675. }
  676. else if (useCameraPostProcess) {
  677. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  678. }
  679. if (!this._doNotChangeAspectRatio) {
  680. scene.updateTransformMatrix(true);
  681. }
  682. // Dump ?
  683. if (dumpForDebug) {
  684. Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  685. }
  686. // Unbind
  687. if (!this.isCube || faceIndex === 5) {
  688. if (this.isCube) {
  689. if (faceIndex === 5) {
  690. engine.generateMipMapsForCubemap(this._texture);
  691. }
  692. }
  693. this.unbindFrameBuffer(engine, faceIndex);
  694. } else {
  695. this.onAfterRenderObservable.notifyObservers(faceIndex);
  696. }
  697. }
  698. /**
  699. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  700. * This allowed control for front to back rendering or reversly depending of the special needs.
  701. *
  702. * @param renderingGroupId The rendering group id corresponding to its index
  703. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  704. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  705. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  706. */
  707. public setRenderingOrder(renderingGroupId: number,
  708. opaqueSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  709. alphaTestSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  710. transparentSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null): void {
  711. this._renderingManager.setRenderingOrder(renderingGroupId,
  712. opaqueSortCompareFn,
  713. alphaTestSortCompareFn,
  714. transparentSortCompareFn);
  715. }
  716. /**
  717. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  718. *
  719. * @param renderingGroupId The rendering group id corresponding to its index
  720. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  721. */
  722. public setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean): void {
  723. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  724. this._renderingManager._useSceneAutoClearSetup = false;
  725. }
  726. /**
  727. * Clones the texture.
  728. * @returns the cloned texture
  729. */
  730. public clone(): RenderTargetTexture {
  731. var textureSize = this.getSize();
  732. var newTexture = new RenderTargetTexture(
  733. this.name,
  734. textureSize,
  735. this.getScene(),
  736. this._renderTargetOptions.generateMipMaps,
  737. this._doNotChangeAspectRatio,
  738. this._renderTargetOptions.type,
  739. this.isCube,
  740. this._renderTargetOptions.samplingMode,
  741. this._renderTargetOptions.generateDepthBuffer,
  742. this._renderTargetOptions.generateStencilBuffer
  743. );
  744. // Base texture
  745. newTexture.hasAlpha = this.hasAlpha;
  746. newTexture.level = this.level;
  747. // RenderTarget Texture
  748. newTexture.coordinatesMode = this.coordinatesMode;
  749. if (this.renderList) {
  750. newTexture.renderList = this.renderList.slice(0);
  751. }
  752. return newTexture;
  753. }
  754. /**
  755. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  756. * @returns The JSON representation of the texture
  757. */
  758. public serialize(): any {
  759. if (!this.name) {
  760. return null;
  761. }
  762. var serializationObject = super.serialize();
  763. serializationObject.renderTargetSize = this.getRenderSize();
  764. serializationObject.renderList = [];
  765. if (this.renderList) {
  766. for (var index = 0; index < this.renderList.length; index++) {
  767. serializationObject.renderList.push(this.renderList[index].id);
  768. }
  769. }
  770. return serializationObject;
  771. }
  772. /**
  773. * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  774. */
  775. public disposeFramebufferObjects(): void {
  776. let objBuffer = this.getInternalTexture();
  777. let scene = this.getScene();
  778. if (objBuffer && scene) {
  779. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  780. }
  781. }
  782. /**
  783. * Dispose the texture and release its associated resources.
  784. */
  785. public dispose(): void {
  786. if (this._postProcessManager) {
  787. this._postProcessManager.dispose();
  788. this._postProcessManager = null;
  789. }
  790. this.clearPostProcesses(true);
  791. if (this._resizeObserver) {
  792. this.getScene()!.getEngine().onResizeObservable.remove(this._resizeObserver);
  793. this._resizeObserver = null;
  794. }
  795. this.renderList = null;
  796. // Remove from custom render targets
  797. var scene = this.getScene();
  798. if (!scene) {
  799. return;
  800. }
  801. var index = scene.customRenderTargets.indexOf(this);
  802. if (index >= 0) {
  803. scene.customRenderTargets.splice(index, 1);
  804. }
  805. for (var camera of scene.cameras) {
  806. index = camera.customRenderTargets.indexOf(this);
  807. if (index >= 0) {
  808. camera.customRenderTargets.splice(index, 1);
  809. }
  810. }
  811. super.dispose();
  812. }
  813. /** @hidden */
  814. public _rebuild(): void {
  815. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  816. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  817. }
  818. if (this._postProcessManager) {
  819. this._postProcessManager._rebuild();
  820. }
  821. }
  822. /**
  823. * Clear the info related to rendering groups preventing retention point in material dispose.
  824. */
  825. public freeRenderingGroups(): void {
  826. if (this._renderingManager) {
  827. this._renderingManager.freeRenderingGroups();
  828. }
  829. }
  830. /**
  831. * Gets the number of views the corrisponding to the texture (eg. a MultiviewRenderTarget will have > 1)
  832. */
  833. public getViewCount() {
  834. return 1;
  835. }
  836. }
  837. Texture._CreateRenderTargetTexture = (name: string, renderTargetSize: number, scene: Scene, generateMipMaps: boolean) => {
  838. return new RenderTargetTexture(name, renderTargetSize, scene, generateMipMaps);
  839. };
  840. /**
  841. * Renders to multiple views with a single draw call
  842. * @see https://www.khronos.org/registry/webgl/extensions/WEBGL_multiview/
  843. */
  844. export class MultiviewRenderTarget extends RenderTargetTexture {
  845. private _multiviewColorTexture: Nullable<WebGLTexture>;
  846. private _multivewDepthStencilTexture: Nullable<WebGLTexture>;
  847. /**
  848. * Creates a multiview render target
  849. * @param scene scene used with the render target
  850. * @param size the size of the render target (used for each view)
  851. */
  852. constructor(public scene: Scene, size: number | { width: number, height: number } | { ratio: number } = 512) {
  853. super("multiview rtt", size, scene, false, true, InternalTexture.DATASOURCE_UNKNOWN, false, undefined, false, false, true, undefined, true);
  854. if (!this.scene.getEngine().getCaps().multiview) {
  855. this.dispose();
  856. throw "Multiview is not supported";
  857. }
  858. var gl = scene.getEngine()._gl;
  859. this._multiviewColorTexture = gl.createTexture();
  860. gl.bindTexture(gl.TEXTURE_2D_ARRAY, this._multiviewColorTexture);
  861. (gl as any).texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.RGBA8, this.getRenderWidth(), this.getRenderHeight(), 2);
  862. this._multivewDepthStencilTexture = gl.createTexture();
  863. gl.bindTexture(gl.TEXTURE_2D_ARRAY, this._multivewDepthStencilTexture);
  864. (gl as any).texStorage3D(gl.TEXTURE_2D_ARRAY, 1, (gl as any).DEPTH32F_STENCIL8, this.getRenderWidth(), this.getRenderHeight(), 2);
  865. var internalTexture = new InternalTexture(scene.getEngine(), InternalTexture.DATASOURCE_UNKNOWN, true);
  866. internalTexture.width = this.getRenderWidth();
  867. internalTexture.height = this.getRenderHeight();
  868. internalTexture._framebuffer = gl.createFramebuffer();
  869. this._texture = internalTexture;
  870. }
  871. /**
  872. * @hidden
  873. * @param faceIndex the face index, if its a cube texture
  874. */
  875. public _bindFrameBuffer(faceIndex: number = 0) {
  876. if (!this._texture) {
  877. return;
  878. }
  879. var gl: any = this.scene.getEngine()._gl;
  880. var ext = this.scene.getEngine().getCaps().multiview;
  881. this.scene.getEngine().bindFramebuffer(this._texture, undefined, undefined, undefined, this.ignoreCameraViewport);
  882. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, this._texture._framebuffer);
  883. ext.framebufferTextureMultiviewWEBGL(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, this._multiviewColorTexture, 0, 0, 2);
  884. ext.framebufferTextureMultiviewWEBGL(gl.DRAW_FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, this._multivewDepthStencilTexture, 0, 0, 2);
  885. }
  886. /**
  887. * Gets the number of views the corrisponding to the texture (eg. a MultiviewRenderTarget will have > 1)
  888. */
  889. public getViewCount() {
  890. return 2;
  891. }
  892. }