renderTargetTexture.ts 38 KB

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