renderTargetTexture.ts 42 KB

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