renderTargetTexture.ts 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  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) {
  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. * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures.
  102. */
  103. public coordinatesMode = Texture.PROJECTION_MODE;
  104. /**
  105. * Define the camera used to render the texture.
  106. */
  107. public activeCamera: Nullable<Camera>;
  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 _engine: Engine;
  216. protected _onRatioRescale(): void {
  217. if (this._sizeRatio) {
  218. this.resize(this._initialSizeParameter);
  219. }
  220. }
  221. /**
  222. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  223. * It must define where the camera used to render the texture is set
  224. */
  225. public boundingBoxPosition = Vector3.Zero();
  226. private _boundingBoxSize: Vector3;
  227. /**
  228. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  229. * When defined, the cubemap will switch to local mode
  230. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  231. * @example https://www.babylonjs-playground.com/#RNASML
  232. */
  233. public set boundingBoxSize(value: Vector3) {
  234. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  235. return;
  236. }
  237. this._boundingBoxSize = value;
  238. let scene = this.getScene();
  239. if (scene) {
  240. scene.markAllMaterialsAsDirty(Constants.MATERIAL_TextureDirtyFlag);
  241. }
  242. }
  243. public get boundingBoxSize(): Vector3 {
  244. return this._boundingBoxSize;
  245. }
  246. /**
  247. * In case the RTT has been created with a depth texture, get the associated
  248. * depth texture.
  249. * Otherwise, return null.
  250. */
  251. public get depthStencilTexture(): Nullable<InternalTexture> {
  252. return this.getInternalTexture()?._depthStencilTexture || null;
  253. }
  254. /**
  255. * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse
  256. * or used a shadow, depth texture...
  257. * @param name The friendly name of the texture
  258. * @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)
  259. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  260. * @param generateMipMaps True if mip maps need to be generated after render.
  261. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  262. * @param type The type of the buffer in the RTT (int, half float, float...)
  263. * @param isCube True if a cube texture needs to be created
  264. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  265. * @param generateDepthBuffer True to generate a depth buffer
  266. * @param generateStencilBuffer True to generate a stencil buffer
  267. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  268. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  269. * @param delayAllocation if the texture allocation should be delayed (default: false)
  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, public isCube = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, generateDepthBuffer = true, generateStencilBuffer = false, isMulti = false, format = Constants.TEXTUREFORMAT_RGBA, delayAllocation = false) {
  272. super(null, scene, !generateMipMaps);
  273. scene = this.getScene();
  274. if (!scene) {
  275. return;
  276. }
  277. this.renderList = new Array<AbstractMesh>();
  278. this._engine = scene.getEngine();
  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. };
  301. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  302. this.wrapU = Texture.CLAMP_ADDRESSMODE;
  303. this.wrapV = Texture.CLAMP_ADDRESSMODE;
  304. }
  305. if (!delayAllocation) {
  306. if (isCube) {
  307. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  308. this.coordinatesMode = Texture.INVCUBIC_MODE;
  309. this._textureMatrix = Matrix.Identity();
  310. } else {
  311. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  312. }
  313. }
  314. }
  315. /**
  316. * Creates a depth stencil texture.
  317. * This is only available in WebGL 2 or with the depth texture extension available.
  318. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  319. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  320. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  321. */
  322. public createDepthStencilTexture(comparisonFunction: number = 0, bilinearFiltering: boolean = true, generateStencil: boolean = false): void {
  323. const internalTexture = this.getInternalTexture();
  324. if (!this.getScene() || !internalTexture) {
  325. return;
  326. }
  327. var engine = this.getScene()!.getEngine();
  328. internalTexture._depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  329. bilinearFiltering,
  330. comparisonFunction,
  331. generateStencil,
  332. isCube: this.isCube
  333. });
  334. }
  335. private _processSizeParameter(size: number | { width: number, height: number } | { ratio: number }): void {
  336. if ((<{ ratio: number }>size).ratio) {
  337. this._sizeRatio = (<{ ratio: number }>size).ratio;
  338. this._size = {
  339. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  340. height: this._bestReflectionRenderTargetDimension(this._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. delete this._waitingRenderList;
  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 (!mesh.isReady(this.refreshRate === 0)) {
  636. this.resetRefreshCounter();
  637. continue;
  638. }
  639. mesh._preActivateForIntermediateRendering(sceneRenderId);
  640. let isMasked;
  641. if (checkLayerMask && camera) {
  642. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  643. } else {
  644. isMasked = false;
  645. }
  646. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  647. if (mesh._activate(sceneRenderId, true) && mesh.subMeshes.length) {
  648. if (!mesh.isAnInstance) {
  649. mesh._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = false;
  650. } else {
  651. mesh = (mesh as InstancedMesh).sourceMesh;
  652. }
  653. mesh._internalAbstractMeshDataInfo._isActiveIntermediate = true;
  654. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  655. var subMesh = mesh.subMeshes[subIndex];
  656. this._renderingManager.dispatch(subMesh, mesh);
  657. }
  658. }
  659. }
  660. }
  661. }
  662. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  663. var particleSystem = scene.particleSystems[particleIndex];
  664. let emitter: any = particleSystem.emitter;
  665. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  666. continue;
  667. }
  668. if (currentRenderList.indexOf(emitter) >= 0) {
  669. this._renderingManager.dispatchParticles(particleSystem);
  670. }
  671. }
  672. }
  673. /**
  674. * @hidden
  675. * @param faceIndex face index to bind to if this is a cubetexture
  676. * @param layer defines the index of the texture to bind in the array
  677. */
  678. public _bindFrameBuffer(faceIndex: number = 0, layer = 0) {
  679. var scene = this.getScene();
  680. if (!scene) {
  681. return;
  682. }
  683. var engine = scene.getEngine();
  684. if (this._texture) {
  685. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, 0, layer);
  686. }
  687. }
  688. protected unbindFrameBuffer(engine: Engine, faceIndex: number): void {
  689. if (!this._texture) {
  690. return;
  691. }
  692. engine.unBindFramebuffer(this._texture, this.isCube, () => {
  693. this.onAfterRenderObservable.notifyObservers(faceIndex);
  694. });
  695. }
  696. private renderToTarget(faceIndex: number, useCameraPostProcess: boolean, dumpForDebug: boolean, layer = 0, camera: Nullable<Camera> = null): void {
  697. var scene = this.getScene();
  698. if (!scene) {
  699. return;
  700. }
  701. var engine = scene.getEngine();
  702. if (!this._texture) {
  703. return;
  704. }
  705. // Bind
  706. if (this._postProcessManager) {
  707. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  708. }
  709. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  710. this._bindFrameBuffer(faceIndex, layer);
  711. }
  712. if (this.is2DArray) {
  713. this.onBeforeRenderObservable.notifyObservers(layer);
  714. }
  715. else {
  716. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  717. }
  718. // Get the list of meshes to render
  719. let currentRenderList: Nullable<Array<AbstractMesh>> = null;
  720. let defaultRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  721. let defaultRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  722. if (this.getCustomRenderList) {
  723. currentRenderList = this.getCustomRenderList(this.is2DArray ? layer : faceIndex, defaultRenderList, defaultRenderListLength);
  724. }
  725. if (!currentRenderList) {
  726. // No custom render list provided, we prepare the rendering for the default list, but check
  727. // first if we did not already performed the preparation before so as to avoid re-doing it several times
  728. if (!this._defaultRenderListPrepared) {
  729. this._prepareRenderingManager(defaultRenderList, defaultRenderListLength, camera, !this.renderList);
  730. this._defaultRenderListPrepared = true;
  731. }
  732. currentRenderList = defaultRenderList;
  733. } else {
  734. // Prepare the rendering for the custom render list provided
  735. this._prepareRenderingManager(currentRenderList, currentRenderList.length, camera, false);
  736. }
  737. // Clear
  738. if (this.onClearObservable.hasObservers()) {
  739. this.onClearObservable.notifyObservers(engine);
  740. } else {
  741. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  742. }
  743. if (!this._doNotChangeAspectRatio) {
  744. scene.updateTransformMatrix(true);
  745. }
  746. // Before Camera Draw
  747. for (let step of scene._beforeRenderTargetDrawStage) {
  748. step.action(this);
  749. }
  750. // Render
  751. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  752. // After Camera Draw
  753. for (let step of scene._afterRenderTargetDrawStage) {
  754. step.action(this);
  755. }
  756. if (this._postProcessManager) {
  757. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  758. }
  759. else if (useCameraPostProcess) {
  760. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  761. }
  762. if (!this._doNotChangeAspectRatio) {
  763. scene.updateTransformMatrix(true);
  764. }
  765. // Dump ?
  766. if (dumpForDebug) {
  767. Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  768. }
  769. // Unbind
  770. if (!this.isCube || faceIndex === 5) {
  771. if (this.isCube) {
  772. if (faceIndex === 5) {
  773. engine.generateMipMapsForCubemap(this._texture);
  774. }
  775. }
  776. this.unbindFrameBuffer(engine, faceIndex);
  777. } else {
  778. this.onAfterRenderObservable.notifyObservers(faceIndex);
  779. }
  780. }
  781. /**
  782. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  783. * This allowed control for front to back rendering or reversly depending of the special needs.
  784. *
  785. * @param renderingGroupId The rendering group id corresponding to its index
  786. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  787. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  788. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  789. */
  790. public setRenderingOrder(renderingGroupId: number,
  791. opaqueSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  792. alphaTestSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  793. transparentSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null): void {
  794. this._renderingManager.setRenderingOrder(renderingGroupId,
  795. opaqueSortCompareFn,
  796. alphaTestSortCompareFn,
  797. transparentSortCompareFn);
  798. }
  799. /**
  800. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  801. *
  802. * @param renderingGroupId The rendering group id corresponding to its index
  803. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  804. */
  805. public setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean): void {
  806. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  807. this._renderingManager._useSceneAutoClearSetup = false;
  808. }
  809. /**
  810. * Clones the texture.
  811. * @returns the cloned texture
  812. */
  813. public clone(): RenderTargetTexture {
  814. var textureSize = this.getSize();
  815. var newTexture = new RenderTargetTexture(
  816. this.name,
  817. textureSize,
  818. this.getScene(),
  819. this._renderTargetOptions.generateMipMaps,
  820. this._doNotChangeAspectRatio,
  821. this._renderTargetOptions.type,
  822. this.isCube,
  823. this._renderTargetOptions.samplingMode,
  824. this._renderTargetOptions.generateDepthBuffer,
  825. this._renderTargetOptions.generateStencilBuffer
  826. );
  827. // Base texture
  828. newTexture.hasAlpha = this.hasAlpha;
  829. newTexture.level = this.level;
  830. // RenderTarget Texture
  831. newTexture.coordinatesMode = this.coordinatesMode;
  832. if (this.renderList) {
  833. newTexture.renderList = this.renderList.slice(0);
  834. }
  835. return newTexture;
  836. }
  837. /**
  838. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  839. * @returns The JSON representation of the texture
  840. */
  841. public serialize(): any {
  842. if (!this.name) {
  843. return null;
  844. }
  845. var serializationObject = super.serialize();
  846. serializationObject.renderTargetSize = this.getRenderSize();
  847. serializationObject.renderList = [];
  848. if (this.renderList) {
  849. for (var index = 0; index < this.renderList.length; index++) {
  850. serializationObject.renderList.push(this.renderList[index].id);
  851. }
  852. }
  853. return serializationObject;
  854. }
  855. /**
  856. * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  857. */
  858. public disposeFramebufferObjects(): void {
  859. let objBuffer = this.getInternalTexture();
  860. let scene = this.getScene();
  861. if (objBuffer && scene) {
  862. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  863. }
  864. }
  865. /**
  866. * Dispose the texture and release its associated resources.
  867. */
  868. public dispose(): void {
  869. this.onResizeObservable.clear();
  870. this.onClearObservable.clear();
  871. this.onAfterRenderObservable.clear();
  872. this.onAfterUnbindObservable.clear();
  873. this.onBeforeBindObservable.clear();
  874. this.onBeforeRenderObservable.clear();
  875. if (this._postProcessManager) {
  876. this._postProcessManager.dispose();
  877. this._postProcessManager = null;
  878. }
  879. this.clearPostProcesses(true);
  880. if (this._resizeObserver) {
  881. this.getScene()!.getEngine().onResizeObservable.remove(this._resizeObserver);
  882. this._resizeObserver = null;
  883. }
  884. this.renderList = null;
  885. // Remove from custom render targets
  886. var scene = this.getScene();
  887. if (!scene) {
  888. return;
  889. }
  890. var index = scene.customRenderTargets.indexOf(this);
  891. if (index >= 0) {
  892. scene.customRenderTargets.splice(index, 1);
  893. }
  894. for (var camera of scene.cameras) {
  895. index = camera.customRenderTargets.indexOf(this);
  896. if (index >= 0) {
  897. camera.customRenderTargets.splice(index, 1);
  898. }
  899. }
  900. if (this.depthStencilTexture) {
  901. this.getScene()!.getEngine()._releaseTexture(this.depthStencilTexture);
  902. }
  903. super.dispose();
  904. }
  905. /** @hidden */
  906. public _rebuild(): void {
  907. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  908. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  909. }
  910. if (this._postProcessManager) {
  911. this._postProcessManager._rebuild();
  912. }
  913. }
  914. /**
  915. * Clear the info related to rendering groups preventing retention point in material dispose.
  916. */
  917. public freeRenderingGroups(): void {
  918. if (this._renderingManager) {
  919. this._renderingManager.freeRenderingGroups();
  920. }
  921. }
  922. /**
  923. * Gets the number of views the corresponding to the texture (eg. a MultiviewRenderTarget will have > 1)
  924. * @returns the view count
  925. */
  926. public getViewCount() {
  927. return 1;
  928. }
  929. }
  930. Texture._CreateRenderTargetTexture = (name: string, renderTargetSize: number, scene: Scene, generateMipMaps: boolean) => {
  931. return new RenderTargetTexture(name, renderTargetSize, scene, generateMipMaps);
  932. };