renderTargetTexture.ts 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  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. */
  270. 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) {
  271. super(null, scene, !generateMipMaps);
  272. scene = this.getScene();
  273. if (!scene) {
  274. return;
  275. }
  276. this._coordinatesMode = Texture.PROJECTION_MODE;
  277. this.renderList = new Array<AbstractMesh>();
  278. this.name = name;
  279. this.isRenderTarget = true;
  280. this._initialSizeParameter = size;
  281. this._processSizeParameter(size);
  282. this._resizeObserver = this.getScene()!.getEngine().onResizeObservable.add(() => {
  283. });
  284. this._generateMipMaps = generateMipMaps ? true : false;
  285. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  286. // Rendering groups
  287. this._renderingManager = new RenderingManager(scene);
  288. this._renderingManager._useSceneAutoClearSetup = true;
  289. if (isMulti) {
  290. return;
  291. }
  292. this._renderTargetOptions = {
  293. generateMipMaps: generateMipMaps,
  294. type: type,
  295. format: format,
  296. samplingMode: samplingMode,
  297. generateDepthBuffer: generateDepthBuffer,
  298. generateStencilBuffer: generateStencilBuffer
  299. };
  300. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  301. this.wrapU = Texture.CLAMP_ADDRESSMODE;
  302. this.wrapV = Texture.CLAMP_ADDRESSMODE;
  303. }
  304. if (!delayAllocation) {
  305. if (isCube) {
  306. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  307. this.coordinatesMode = Texture.INVCUBIC_MODE;
  308. this._textureMatrix = Matrix.Identity();
  309. } else {
  310. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  311. }
  312. }
  313. }
  314. /**
  315. * Creates a depth stencil texture.
  316. * This is only available in WebGL 2 or with the depth texture extension available.
  317. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  318. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  319. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  320. */
  321. public createDepthStencilTexture(comparisonFunction: number = 0, bilinearFiltering: boolean = true, generateStencil: boolean = false): void {
  322. const internalTexture = this.getInternalTexture();
  323. if (!this.getScene() || !internalTexture) {
  324. return;
  325. }
  326. var engine = this.getScene()!.getEngine();
  327. internalTexture._depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  328. bilinearFiltering,
  329. comparisonFunction,
  330. generateStencil,
  331. isCube: this.isCube
  332. });
  333. }
  334. private _processSizeParameter(size: number | { width: number, height: number } | { ratio: number }): void {
  335. if ((<{ ratio: number }>size).ratio) {
  336. this._sizeRatio = (<{ ratio: number }>size).ratio;
  337. const engine = this._getEngine()!;
  338. this._size = {
  339. width: this._bestReflectionRenderTargetDimension(engine.getRenderWidth(), this._sizeRatio),
  340. height: this._bestReflectionRenderTargetDimension(engine.getRenderHeight(), this._sizeRatio)
  341. };
  342. } else {
  343. this._size = <number | { width: number, height: number, layers?: number }>size;
  344. }
  345. }
  346. /**
  347. * Define the number of samples to use in case of MSAA.
  348. * It defaults to one meaning no MSAA has been enabled.
  349. */
  350. public get samples(): number {
  351. return this._samples;
  352. }
  353. public set samples(value: number) {
  354. if (this._samples === value) {
  355. return;
  356. }
  357. let scene = this.getScene();
  358. if (!scene) {
  359. return;
  360. }
  361. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  362. }
  363. /**
  364. * Resets the refresh counter of the texture and start bak from scratch.
  365. * Could be useful to regenerate the texture if it is setup to render only once.
  366. */
  367. public resetRefreshCounter(): void {
  368. this._currentRefreshId = -1;
  369. }
  370. /**
  371. * Define the refresh rate of the texture or the rendering frequency.
  372. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  373. */
  374. public get refreshRate(): number {
  375. return this._refreshRate;
  376. }
  377. public set refreshRate(value: number) {
  378. this._refreshRate = value;
  379. this.resetRefreshCounter();
  380. }
  381. /**
  382. * Adds a post process to the render target rendering passes.
  383. * @param postProcess define the post process to add
  384. */
  385. public addPostProcess(postProcess: PostProcess): void {
  386. if (!this._postProcessManager) {
  387. let scene = this.getScene();
  388. if (!scene) {
  389. return;
  390. }
  391. this._postProcessManager = new PostProcessManager(scene);
  392. this._postProcesses = new Array<PostProcess>();
  393. }
  394. this._postProcesses.push(postProcess);
  395. this._postProcesses[0].autoClear = false;
  396. }
  397. /**
  398. * Clear all the post processes attached to the render target
  399. * @param dispose define if the cleared post processesshould also be disposed (false by default)
  400. */
  401. public clearPostProcesses(dispose: boolean = false): void {
  402. if (!this._postProcesses) {
  403. return;
  404. }
  405. if (dispose) {
  406. for (var postProcess of this._postProcesses) {
  407. postProcess.dispose();
  408. }
  409. }
  410. this._postProcesses = [];
  411. }
  412. /**
  413. * Remove one of the post process from the list of attached post processes to the texture
  414. * @param postProcess define the post process to remove from the list
  415. */
  416. public removePostProcess(postProcess: PostProcess): void {
  417. if (!this._postProcesses) {
  418. return;
  419. }
  420. var index = this._postProcesses.indexOf(postProcess);
  421. if (index === -1) {
  422. return;
  423. }
  424. this._postProcesses.splice(index, 1);
  425. if (this._postProcesses.length > 0) {
  426. this._postProcesses[0].autoClear = false;
  427. }
  428. }
  429. /** @hidden */
  430. public _shouldRender(): boolean {
  431. if (this._currentRefreshId === -1) { // At least render once
  432. this._currentRefreshId = 1;
  433. return true;
  434. }
  435. if (this.refreshRate === this._currentRefreshId) {
  436. this._currentRefreshId = 1;
  437. return true;
  438. }
  439. this._currentRefreshId++;
  440. return false;
  441. }
  442. /**
  443. * Gets the actual render size of the texture.
  444. * @returns the width of the render size
  445. */
  446. public getRenderSize(): number {
  447. return this.getRenderWidth();
  448. }
  449. /**
  450. * Gets the actual render width of the texture.
  451. * @returns the width of the render size
  452. */
  453. public getRenderWidth(): number {
  454. if ((<{ width: number, height: number }>this._size).width) {
  455. return (<{ width: number, height: number }>this._size).width;
  456. }
  457. return <number>this._size;
  458. }
  459. /**
  460. * Gets the actual render height of the texture.
  461. * @returns the height of the render size
  462. */
  463. public getRenderHeight(): number {
  464. if ((<{ width: number, height: number }>this._size).width) {
  465. return (<{ width: number, height: number }>this._size).height;
  466. }
  467. return <number>this._size;
  468. }
  469. /**
  470. * Gets the actual number of layers of the texture.
  471. * @returns the number of layers
  472. */
  473. public getRenderLayers(): number {
  474. const layers = (<{ width: number, height: number, layers?: number }>this._size).layers;
  475. if (layers) {
  476. return layers;
  477. }
  478. return 0;
  479. }
  480. /**
  481. * Get if the texture can be rescaled or not.
  482. */
  483. public get canRescale(): boolean {
  484. return true;
  485. }
  486. /**
  487. * Resize the texture using a ratio.
  488. * @param ratio the ratio to apply to the texture size in order to compute the new target size
  489. */
  490. public scale(ratio: number): void {
  491. var newSize = Math.max(1, this.getRenderSize() * ratio);
  492. this.resize(newSize);
  493. }
  494. /**
  495. * Get the texture reflection matrix used to rotate/transform the reflection.
  496. * @returns the reflection matrix
  497. */
  498. public getReflectionTextureMatrix(): Matrix {
  499. if (this.isCube) {
  500. return this._textureMatrix;
  501. }
  502. return super.getReflectionTextureMatrix();
  503. }
  504. /**
  505. * Resize the texture to a new desired size.
  506. * Be carrefull as it will recreate all the data in the new texture.
  507. * @param size Define the new size. It can be:
  508. * - a number for squared texture,
  509. * - an object containing { width: number, height: number }
  510. * - or an object containing a ratio { ratio: number }
  511. */
  512. public resize(size: number | { width: number, height: number } | { ratio: number }): void {
  513. var wasCube = this.isCube;
  514. this.releaseInternalTexture();
  515. let scene = this.getScene();
  516. if (!scene) {
  517. return;
  518. }
  519. this._processSizeParameter(size);
  520. if (wasCube) {
  521. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  522. } else {
  523. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  524. }
  525. if (this.onResizeObservable.hasObservers()) {
  526. this.onResizeObservable.notifyObservers(this);
  527. }
  528. }
  529. private _defaultRenderListPrepared: boolean;
  530. /**
  531. * Renders all the objects from the render list into the texture.
  532. * @param useCameraPostProcess Define if camera post processes should be used during the rendering
  533. * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose
  534. */
  535. public render(useCameraPostProcess: boolean = false, dumpForDebug: boolean = false): void {
  536. var scene = this.getScene();
  537. if (!scene) {
  538. return;
  539. }
  540. var engine = scene.getEngine();
  541. if (this.useCameraPostProcesses !== undefined) {
  542. useCameraPostProcess = this.useCameraPostProcesses;
  543. }
  544. if (this._waitingRenderList) {
  545. this.renderList = [];
  546. for (var index = 0; index < this._waitingRenderList.length; index++) {
  547. var id = this._waitingRenderList[index];
  548. let mesh = scene.getMeshByID(id);
  549. if (mesh) {
  550. this.renderList.push(mesh);
  551. }
  552. }
  553. this._waitingRenderList = undefined;
  554. }
  555. // Is predicate defined?
  556. if (this.renderListPredicate) {
  557. if (this.renderList) {
  558. this.renderList.length = 0; // Clear previous renderList
  559. } else {
  560. this.renderList = [];
  561. }
  562. var scene = this.getScene();
  563. if (!scene) {
  564. return;
  565. }
  566. var sceneMeshes = scene.meshes;
  567. for (var index = 0; index < sceneMeshes.length; index++) {
  568. var mesh = sceneMeshes[index];
  569. if (this.renderListPredicate(mesh)) {
  570. this.renderList.push(mesh);
  571. }
  572. }
  573. }
  574. this.onBeforeBindObservable.notifyObservers(this);
  575. // Set custom projection.
  576. // Needs to be before binding to prevent changing the aspect ratio.
  577. let camera: Nullable<Camera>;
  578. if (this.activeCamera) {
  579. camera = this.activeCamera;
  580. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  581. if (this.activeCamera !== scene.activeCamera) {
  582. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  583. }
  584. }
  585. else {
  586. camera = scene.activeCamera;
  587. if (camera) {
  588. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  589. }
  590. }
  591. this._defaultRenderListPrepared = false;
  592. if (this.is2DArray) {
  593. for (let layer = 0; layer < this.getRenderLayers(); layer++) {
  594. this.renderToTarget(0, useCameraPostProcess, dumpForDebug, layer, camera);
  595. scene.incrementRenderId();
  596. scene.resetCachedMaterial();
  597. }
  598. }
  599. else if (this.isCube) {
  600. for (var face = 0; face < 6; face++) {
  601. this.renderToTarget(face, useCameraPostProcess, dumpForDebug, undefined, camera);
  602. scene.incrementRenderId();
  603. scene.resetCachedMaterial();
  604. }
  605. } else {
  606. this.renderToTarget(0, useCameraPostProcess, dumpForDebug, undefined, camera);
  607. }
  608. this.onAfterUnbindObservable.notifyObservers(this);
  609. if (scene.activeCamera) {
  610. // Do not avoid setting uniforms when multiple scenes are active as another camera may have overwrite these
  611. if (scene.getEngine().scenes.length > 1 || (this.activeCamera && this.activeCamera !== scene.activeCamera)) {
  612. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  613. }
  614. engine.setViewport(scene.activeCamera.viewport);
  615. }
  616. scene.resetCachedMaterial();
  617. }
  618. private _bestReflectionRenderTargetDimension(renderDimension: number, scale: number): number {
  619. let minimum = 128;
  620. let x = renderDimension * scale;
  621. let curved = Engine.NearestPOT(x + (minimum * minimum / (minimum + x)));
  622. // Ensure we don't exceed the render dimension (while staying POT)
  623. return Math.min(Engine.FloorPOT(renderDimension), curved);
  624. }
  625. private _prepareRenderingManager(currentRenderList: Array<AbstractMesh>, currentRenderListLength: number, camera: Nullable<Camera>, checkLayerMask: boolean): void {
  626. var scene = this.getScene();
  627. if (!scene) {
  628. return;
  629. }
  630. this._renderingManager.reset();
  631. var sceneRenderId = scene.getRenderId();
  632. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  633. var mesh = currentRenderList[meshIndex];
  634. if (mesh) {
  635. if (this.customIsReadyFunction) {
  636. if (!this.customIsReadyFunction(mesh, this.refreshRate)) {
  637. this.resetRefreshCounter();
  638. continue;
  639. }
  640. }
  641. else if (!mesh.isReady(this.refreshRate === 0)) {
  642. this.resetRefreshCounter();
  643. continue;
  644. }
  645. mesh._preActivateForIntermediateRendering(sceneRenderId);
  646. let isMasked;
  647. if (checkLayerMask && camera) {
  648. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  649. } else {
  650. isMasked = false;
  651. }
  652. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  653. if (mesh._activate(sceneRenderId, true) && mesh.subMeshes.length) {
  654. if (!mesh.isAnInstance) {
  655. mesh._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = false;
  656. } else {
  657. if (!mesh._internalAbstractMeshDataInfo._actAsRegularMesh) {
  658. mesh = (mesh as InstancedMesh).sourceMesh;
  659. }
  660. }
  661. mesh._internalAbstractMeshDataInfo._isActiveIntermediate = true;
  662. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  663. var subMesh = mesh.subMeshes[subIndex];
  664. this._renderingManager.dispatch(subMesh, mesh);
  665. }
  666. }
  667. }
  668. }
  669. }
  670. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  671. var particleSystem = scene.particleSystems[particleIndex];
  672. let emitter: any = particleSystem.emitter;
  673. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  674. continue;
  675. }
  676. if (currentRenderList.indexOf(emitter) >= 0) {
  677. this._renderingManager.dispatchParticles(particleSystem);
  678. }
  679. }
  680. }
  681. /**
  682. * @hidden
  683. * @param faceIndex face index to bind to if this is a cubetexture
  684. * @param layer defines the index of the texture to bind in the array
  685. */
  686. public _bindFrameBuffer(faceIndex: number = 0, layer = 0) {
  687. var scene = this.getScene();
  688. if (!scene) {
  689. return;
  690. }
  691. var engine = scene.getEngine();
  692. if (this._texture) {
  693. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, 0, layer);
  694. }
  695. }
  696. protected unbindFrameBuffer(engine: Engine, faceIndex: number): void {
  697. if (!this._texture) {
  698. return;
  699. }
  700. engine.unBindFramebuffer(this._texture, this.isCube, () => {
  701. this.onAfterRenderObservable.notifyObservers(faceIndex);
  702. });
  703. }
  704. private renderToTarget(faceIndex: number, useCameraPostProcess: boolean, dumpForDebug: boolean, layer = 0, camera: Nullable<Camera> = null): void {
  705. var scene = this.getScene();
  706. if (!scene) {
  707. return;
  708. }
  709. var engine = scene.getEngine();
  710. if (!this._texture) {
  711. return;
  712. }
  713. // Bind
  714. if (this._postProcessManager) {
  715. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  716. }
  717. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  718. this._bindFrameBuffer(faceIndex, layer);
  719. }
  720. if (this.is2DArray) {
  721. this.onBeforeRenderObservable.notifyObservers(layer);
  722. }
  723. else {
  724. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  725. }
  726. // Get the list of meshes to render
  727. let currentRenderList: Nullable<Array<AbstractMesh>> = null;
  728. let defaultRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  729. let defaultRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  730. if (this.getCustomRenderList) {
  731. currentRenderList = this.getCustomRenderList(this.is2DArray ? layer : faceIndex, defaultRenderList, defaultRenderListLength);
  732. }
  733. if (!currentRenderList) {
  734. // No custom render list provided, we prepare the rendering for the default list, but check
  735. // first if we did not already performed the preparation before so as to avoid re-doing it several times
  736. if (!this._defaultRenderListPrepared) {
  737. this._prepareRenderingManager(defaultRenderList, defaultRenderListLength, camera, !this.renderList);
  738. this._defaultRenderListPrepared = true;
  739. }
  740. currentRenderList = defaultRenderList;
  741. } else {
  742. // Prepare the rendering for the custom render list provided
  743. this._prepareRenderingManager(currentRenderList, currentRenderList.length, camera, false);
  744. }
  745. // Clear
  746. if (this.onClearObservable.hasObservers()) {
  747. this.onClearObservable.notifyObservers(engine);
  748. } else {
  749. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  750. }
  751. if (!this._doNotChangeAspectRatio) {
  752. scene.updateTransformMatrix(true);
  753. }
  754. // Before Camera Draw
  755. for (let step of scene._beforeRenderTargetDrawStage) {
  756. step.action(this);
  757. }
  758. // Render
  759. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  760. // After Camera Draw
  761. for (let step of scene._afterRenderTargetDrawStage) {
  762. step.action(this);
  763. }
  764. if (this._postProcessManager) {
  765. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  766. }
  767. else if (useCameraPostProcess) {
  768. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  769. }
  770. if (!this._doNotChangeAspectRatio) {
  771. scene.updateTransformMatrix(true);
  772. }
  773. // Dump ?
  774. if (dumpForDebug) {
  775. Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  776. }
  777. // Unbind
  778. if (!this.isCube || faceIndex === 5) {
  779. if (this.isCube) {
  780. if (faceIndex === 5) {
  781. engine.generateMipMapsForCubemap(this._texture);
  782. }
  783. }
  784. this.unbindFrameBuffer(engine, faceIndex);
  785. } else {
  786. this.onAfterRenderObservable.notifyObservers(faceIndex);
  787. }
  788. }
  789. /**
  790. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  791. * This allowed control for front to back rendering or reversly depending of the special needs.
  792. *
  793. * @param renderingGroupId The rendering group id corresponding to its index
  794. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  795. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  796. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  797. */
  798. public setRenderingOrder(renderingGroupId: number,
  799. opaqueSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  800. alphaTestSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  801. transparentSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null): void {
  802. this._renderingManager.setRenderingOrder(renderingGroupId,
  803. opaqueSortCompareFn,
  804. alphaTestSortCompareFn,
  805. transparentSortCompareFn);
  806. }
  807. /**
  808. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  809. *
  810. * @param renderingGroupId The rendering group id corresponding to its index
  811. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  812. */
  813. public setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean): void {
  814. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  815. this._renderingManager._useSceneAutoClearSetup = false;
  816. }
  817. /**
  818. * Clones the texture.
  819. * @returns the cloned texture
  820. */
  821. public clone(): RenderTargetTexture {
  822. var textureSize = this.getSize();
  823. var newTexture = new RenderTargetTexture(
  824. this.name,
  825. textureSize,
  826. this.getScene(),
  827. this._renderTargetOptions.generateMipMaps,
  828. this._doNotChangeAspectRatio,
  829. this._renderTargetOptions.type,
  830. this.isCube,
  831. this._renderTargetOptions.samplingMode,
  832. this._renderTargetOptions.generateDepthBuffer,
  833. this._renderTargetOptions.generateStencilBuffer
  834. );
  835. // Base texture
  836. newTexture.hasAlpha = this.hasAlpha;
  837. newTexture.level = this.level;
  838. // RenderTarget Texture
  839. newTexture.coordinatesMode = this.coordinatesMode;
  840. if (this.renderList) {
  841. newTexture.renderList = this.renderList.slice(0);
  842. }
  843. return newTexture;
  844. }
  845. /**
  846. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  847. * @returns The JSON representation of the texture
  848. */
  849. public serialize(): any {
  850. if (!this.name) {
  851. return null;
  852. }
  853. var serializationObject = super.serialize();
  854. serializationObject.renderTargetSize = this.getRenderSize();
  855. serializationObject.renderList = [];
  856. if (this.renderList) {
  857. for (var index = 0; index < this.renderList.length; index++) {
  858. serializationObject.renderList.push(this.renderList[index].id);
  859. }
  860. }
  861. return serializationObject;
  862. }
  863. /**
  864. * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  865. */
  866. public disposeFramebufferObjects(): void {
  867. let objBuffer = this.getInternalTexture();
  868. let scene = this.getScene();
  869. if (objBuffer && scene) {
  870. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  871. }
  872. }
  873. /**
  874. * Dispose the texture and release its associated resources.
  875. */
  876. public dispose(): void {
  877. this.onResizeObservable.clear();
  878. this.onClearObservable.clear();
  879. this.onAfterRenderObservable.clear();
  880. this.onAfterUnbindObservable.clear();
  881. this.onBeforeBindObservable.clear();
  882. this.onBeforeRenderObservable.clear();
  883. if (this._postProcessManager) {
  884. this._postProcessManager.dispose();
  885. this._postProcessManager = null;
  886. }
  887. this.clearPostProcesses(true);
  888. if (this._resizeObserver) {
  889. this.getScene()!.getEngine().onResizeObservable.remove(this._resizeObserver);
  890. this._resizeObserver = null;
  891. }
  892. this.renderList = null;
  893. // Remove from custom render targets
  894. var scene = this.getScene();
  895. if (!scene) {
  896. return;
  897. }
  898. var index = scene.customRenderTargets.indexOf(this);
  899. if (index >= 0) {
  900. scene.customRenderTargets.splice(index, 1);
  901. }
  902. for (var camera of scene.cameras) {
  903. index = camera.customRenderTargets.indexOf(this);
  904. if (index >= 0) {
  905. camera.customRenderTargets.splice(index, 1);
  906. }
  907. }
  908. if (this.depthStencilTexture) {
  909. this.getScene()!.getEngine()._releaseTexture(this.depthStencilTexture);
  910. }
  911. super.dispose();
  912. }
  913. /** @hidden */
  914. public _rebuild(): void {
  915. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  916. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  917. }
  918. if (this._postProcessManager) {
  919. this._postProcessManager._rebuild();
  920. }
  921. }
  922. /**
  923. * Clear the info related to rendering groups preventing retention point in material dispose.
  924. */
  925. public freeRenderingGroups(): void {
  926. if (this._renderingManager) {
  927. this._renderingManager.freeRenderingGroups();
  928. }
  929. }
  930. /**
  931. * Gets the number of views the corresponding to the texture (eg. a MultiviewRenderTarget will have > 1)
  932. * @returns the view count
  933. */
  934. public getViewCount() {
  935. return 1;
  936. }
  937. }
  938. Texture._CreateRenderTargetTexture = (name: string, renderTargetSize: number, scene: Scene, generateMipMaps: boolean) => {
  939. return new RenderTargetTexture(name, renderTargetSize, scene, generateMipMaps);
  940. };