environmentTextureTools.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. import { Nullable } from "../types";
  2. import { Tools } from "./tools";
  3. import { Vector3 } from "../Maths/math.vector";
  4. import { Scalar } from "../Maths/math.scalar";
  5. import { SphericalPolynomial } from "../Maths/sphericalPolynomial";
  6. import { InternalTexture } from "../Materials/Textures/internalTexture";
  7. import { BaseTexture } from "../Materials/Textures/baseTexture";
  8. import { CubeTexture } from "../Materials/Textures/cubeTexture";
  9. import { Constants } from "../Engines/constants";
  10. import { Scene } from "../scene";
  11. import { PostProcess } from "../PostProcesses/postProcess";
  12. import { Logger } from "../Misc/logger";
  13. import "../Engines/Extensions/engine.renderTarget";
  14. import "../Shaders/rgbdEncode.fragment";
  15. import "../Shaders/rgbdDecode.fragment";
  16. import { Engine } from '../Engines/engine';
  17. /**
  18. * Raw texture data and descriptor sufficient for WebGL texture upload
  19. */
  20. export interface EnvironmentTextureInfo {
  21. /**
  22. * Version of the environment map
  23. */
  24. version: number;
  25. /**
  26. * Width of image
  27. */
  28. width: number;
  29. /**
  30. * Irradiance information stored in the file.
  31. */
  32. irradiance: any;
  33. /**
  34. * Specular information stored in the file.
  35. */
  36. specular: any;
  37. }
  38. /**
  39. * Defines One Image in the file. It requires only the position in the file
  40. * as well as the length.
  41. */
  42. interface BufferImageData {
  43. /**
  44. * Length of the image data.
  45. */
  46. length: number;
  47. /**
  48. * Position of the data from the null terminator delimiting the end of the JSON.
  49. */
  50. position: number;
  51. }
  52. /**
  53. * Defines the specular data enclosed in the file.
  54. * This corresponds to the version 1 of the data.
  55. */
  56. export interface EnvironmentTextureSpecularInfoV1 {
  57. /**
  58. * Defines where the specular Payload is located. It is a runtime value only not stored in the file.
  59. */
  60. specularDataPosition?: number;
  61. /**
  62. * This contains all the images data needed to reconstruct the cubemap.
  63. */
  64. mipmaps: Array<BufferImageData>;
  65. /**
  66. * Defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness.
  67. */
  68. lodGenerationScale: number;
  69. }
  70. /**
  71. * Defines the required storage to save the environment irradiance information.
  72. */
  73. interface EnvironmentTextureIrradianceInfoV1 {
  74. x: Array<number>;
  75. y: Array<number>;
  76. z: Array<number>;
  77. xx: Array<number>;
  78. yy: Array<number>;
  79. zz: Array<number>;
  80. yz: Array<number>;
  81. zx: Array<number>;
  82. xy: Array<number>;
  83. }
  84. /**
  85. * Sets of helpers addressing the serialization and deserialization of environment texture
  86. * stored in a BabylonJS env file.
  87. * Those files are usually stored as .env files.
  88. */
  89. export class EnvironmentTextureTools {
  90. /**
  91. * Magic number identifying the env file.
  92. */
  93. private static _MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  94. /**
  95. * Gets the environment info from an env file.
  96. * @param data The array buffer containing the .env bytes.
  97. * @returns the environment file info (the json header) if successfully parsed.
  98. */
  99. public static GetEnvInfo(data: ArrayBuffer): Nullable<EnvironmentTextureInfo> {
  100. let dataView = new DataView(data);
  101. let pos = 0;
  102. for (let i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  103. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  104. Logger.Error('Not a babylon environment map');
  105. return null;
  106. }
  107. }
  108. // Read json manifest - collect characters up to null terminator
  109. let manifestString = '';
  110. let charCode = 0x00;
  111. while ((charCode = dataView.getUint8(pos++))) {
  112. manifestString += String.fromCharCode(charCode);
  113. }
  114. let manifest: EnvironmentTextureInfo = JSON.parse(manifestString);
  115. if (manifest.specular) {
  116. // Extend the header with the position of the payload.
  117. manifest.specular.specularDataPosition = pos;
  118. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  119. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  120. }
  121. return manifest;
  122. }
  123. /**
  124. * Creates an environment texture from a loaded cube texture.
  125. * @param texture defines the cube texture to convert in env file
  126. * @return a promise containing the environment data if succesfull.
  127. */
  128. public static CreateEnvTextureAsync(texture: CubeTexture): Promise<ArrayBuffer> {
  129. let internalTexture = texture.getInternalTexture();
  130. if (!internalTexture) {
  131. return Promise.reject("The cube texture is invalid.");
  132. }
  133. if (!texture._prefiltered) {
  134. return Promise.reject("The cube texture is invalid (not prefiltered).");
  135. }
  136. let engine = internalTexture.getEngine() as Engine;
  137. if (engine && engine.premultipliedAlpha) {
  138. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  139. }
  140. if (texture.textureType === Constants.TEXTURETYPE_UNSIGNED_INT) {
  141. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  142. }
  143. let canvas = engine.getRenderingCanvas();
  144. if (!canvas) {
  145. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  146. }
  147. let textureType = Constants.TEXTURETYPE_FLOAT;
  148. if (!engine.getCaps().textureFloatRender) {
  149. textureType = Constants.TEXTURETYPE_HALF_FLOAT;
  150. if (!engine.getCaps().textureHalfFloatRender) {
  151. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  152. }
  153. }
  154. let cubeWidth = internalTexture.width;
  155. let hostingScene = new Scene(engine);
  156. let specularTextures: { [key: number]: ArrayBuffer } = {};
  157. let promises: Promise<void>[] = [];
  158. // Read and collect all mipmaps data from the cube.
  159. let mipmapsCount = Scalar.Log2(internalTexture.width);
  160. mipmapsCount = Math.round(mipmapsCount);
  161. for (let i = 0; i <= mipmapsCount; i++) {
  162. let faceWidth = Math.pow(2, mipmapsCount - i);
  163. // All faces of the cube.
  164. for (let face = 0; face < 6; face++) {
  165. let data = texture.readPixels(face, i);
  166. // Creates a temp texture with the face data.
  167. let tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, Constants.TEXTUREFORMAT_RGBA, false, false, Constants.TEXTURE_NEAREST_SAMPLINGMODE, null, textureType);
  168. // And rgbdEncode them.
  169. let promise = new Promise<void>((resolve, reject) => {
  170. let rgbdPostProcess = new PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, Constants.TEXTURE_NEAREST_SAMPLINGMODE, engine, false, undefined, Constants.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  171. rgbdPostProcess.getEffect().executeWhenCompiled(() => {
  172. rgbdPostProcess.onApply = (effect) => {
  173. effect._bindTexture("textureSampler", tempTexture);
  174. };
  175. // As the process needs to happen on the main canvas, keep track of the current size
  176. let currentW = engine.getRenderWidth();
  177. let currentH = engine.getRenderHeight();
  178. // Set the desired size for the texture
  179. engine.setSize(faceWidth, faceWidth);
  180. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  181. // Reading datas from WebGL
  182. Tools.ToBlob(canvas!, (blob) => {
  183. let fileReader = new FileReader();
  184. fileReader.onload = (event: any) => {
  185. let arrayBuffer = event.target!.result as ArrayBuffer;
  186. specularTextures[i * 6 + face] = arrayBuffer;
  187. resolve();
  188. };
  189. fileReader.readAsArrayBuffer(blob!);
  190. });
  191. // Reapply the previous canvas size
  192. engine.setSize(currentW, currentH);
  193. });
  194. });
  195. promises.push(promise);
  196. }
  197. }
  198. // Once all the textures haves been collected as RGBD stored in PNGs
  199. return Promise.all(promises).then(() => {
  200. // We can delete the hosting scene keeping track of all the creation objects
  201. hostingScene.dispose();
  202. // Creates the json header for the env texture
  203. let info: EnvironmentTextureInfo = {
  204. version: 1,
  205. width: cubeWidth,
  206. irradiance: this._CreateEnvTextureIrradiance(texture),
  207. specular: {
  208. mipmaps: [],
  209. lodGenerationScale: texture.lodGenerationScale
  210. }
  211. };
  212. // Sets the specular image data information
  213. let position = 0;
  214. for (let i = 0; i <= mipmapsCount; i++) {
  215. for (let face = 0; face < 6; face++) {
  216. let byteLength = specularTextures[i * 6 + face].byteLength;
  217. info.specular.mipmaps.push({
  218. length: byteLength,
  219. position: position
  220. });
  221. position += byteLength;
  222. }
  223. }
  224. // Encode the JSON as an array buffer
  225. let infoString = JSON.stringify(info);
  226. let infoBuffer = new ArrayBuffer(infoString.length + 1);
  227. let infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  228. for (let i = 0, strLen = infoString.length; i < strLen; i++) {
  229. infoView[i] = infoString.charCodeAt(i);
  230. }
  231. // Ends up with a null terminator for easier parsing
  232. infoView[infoString.length] = 0x00;
  233. // Computes the final required size and creates the storage
  234. let totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  235. let finalBuffer = new ArrayBuffer(totalSize);
  236. let finalBufferView = new Uint8Array(finalBuffer);
  237. let dataView = new DataView(finalBuffer);
  238. // Copy the magic bytes identifying the file in
  239. let pos = 0;
  240. for (let i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  241. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  242. }
  243. // Add the json info
  244. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  245. pos += infoBuffer.byteLength;
  246. // Finally inserts the texture data
  247. for (let i = 0; i <= mipmapsCount; i++) {
  248. for (let face = 0; face < 6; face++) {
  249. let dataBuffer = specularTextures[i * 6 + face];
  250. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  251. pos += dataBuffer.byteLength;
  252. }
  253. }
  254. // Voila
  255. return finalBuffer;
  256. });
  257. }
  258. /**
  259. * Creates a JSON representation of the spherical data.
  260. * @param texture defines the texture containing the polynomials
  261. * @return the JSON representation of the spherical info
  262. */
  263. private static _CreateEnvTextureIrradiance(texture: CubeTexture): Nullable<EnvironmentTextureIrradianceInfoV1> {
  264. let polynmials = texture.sphericalPolynomial;
  265. if (polynmials == null) {
  266. return null;
  267. }
  268. return {
  269. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  270. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  271. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  272. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  273. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  274. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  275. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  276. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  277. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  278. } as any;
  279. }
  280. /**
  281. * Creates the ArrayBufferViews used for initializing environment texture image data.
  282. * @param arrayBuffer the underlying ArrayBuffer to which the views refer
  283. * @param info parameters that determine what views will be created for accessing the underlying buffer
  284. * @return the views described by info providing access to the underlying buffer
  285. */
  286. public static CreateImageDataArrayBufferViews(arrayBuffer: any, info: EnvironmentTextureInfo): Array<Array<ArrayBufferView>> {
  287. if (info.version !== 1) {
  288. throw new Error(`Unsupported babylon environment map version "${info.version}"`);
  289. }
  290. const specularInfo = info.specular as EnvironmentTextureSpecularInfoV1;
  291. // Double checks the enclosed info
  292. let mipmapsCount = Scalar.Log2(info.width);
  293. mipmapsCount = Math.round(mipmapsCount) + 1;
  294. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  295. throw new Error(`Unsupported specular mipmaps number "${specularInfo.mipmaps.length}"`);
  296. }
  297. const imageData = new Array<Array<ArrayBufferView>>(mipmapsCount);
  298. for (let i = 0; i < mipmapsCount; i++) {
  299. imageData[i] = new Array<ArrayBufferView>(6);
  300. for (let face = 0; face < 6; face++) {
  301. const imageInfo = specularInfo.mipmaps[i * 6 + face];
  302. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition! + imageInfo.position, imageInfo.length);
  303. }
  304. }
  305. return imageData;
  306. }
  307. /**
  308. * Uploads the texture info contained in the env file to the GPU.
  309. * @param texture defines the internal texture to upload to
  310. * @param arrayBuffer defines the buffer cotaining the data to load
  311. * @param info defines the texture info retrieved through the GetEnvInfo method
  312. * @returns a promise
  313. */
  314. public static UploadEnvLevelsAsync(texture: InternalTexture, arrayBuffer: any, info: EnvironmentTextureInfo): Promise<void> {
  315. if (info.version !== 1) {
  316. throw new Error(`Unsupported babylon environment map version "${info.version}"`);
  317. }
  318. const specularInfo = info.specular as EnvironmentTextureSpecularInfoV1;
  319. if (!specularInfo) {
  320. // Nothing else parsed so far
  321. return Promise.resolve();
  322. }
  323. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  324. const imageData = EnvironmentTextureTools.CreateImageDataArrayBufferViews(arrayBuffer, info);
  325. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  326. }
  327. /**
  328. * Uploads the levels of image data to the GPU.
  329. * @param texture defines the internal texture to upload to
  330. * @param imageData defines the array buffer views of image data [mipmap][face]
  331. * @returns a promise
  332. */
  333. public static UploadLevelsAsync(texture: InternalTexture, imageData: ArrayBufferView[][]): Promise<void> {
  334. if (!Tools.IsExponentOfTwo(texture.width)) {
  335. throw new Error("Texture size must be a power of two");
  336. }
  337. const mipmapsCount = Math.round(Scalar.Log2(texture.width)) + 1;
  338. // Gets everything ready.
  339. let engine = texture.getEngine() as Engine;
  340. let expandTexture = false;
  341. let generateNonLODTextures = false;
  342. let rgbdPostProcess: Nullable<PostProcess> = null;
  343. let cubeRtt: Nullable<InternalTexture> = null;
  344. let lodTextures: Nullable<{ [lod: number]: BaseTexture }> = null;
  345. let caps = engine.getCaps();
  346. texture.format = Constants.TEXTUREFORMAT_RGBA;
  347. texture.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  348. texture.generateMipMaps = true;
  349. engine.updateTextureSamplingMode(Constants.TEXTURE_TRILINEAR_SAMPLINGMODE, texture);
  350. // Add extra process if texture lod is not supported
  351. if (!caps.textureLOD) {
  352. expandTexture = false;
  353. generateNonLODTextures = true;
  354. lodTextures = {};
  355. }
  356. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  357. else if (engine.webGLVersion < 2) {
  358. expandTexture = false;
  359. }
  360. // If half float available we can uncompress the texture
  361. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  362. expandTexture = true;
  363. texture.type = Constants.TEXTURETYPE_HALF_FLOAT;
  364. }
  365. // If full float available we can uncompress the texture
  366. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  367. expandTexture = true;
  368. texture.type = Constants.TEXTURETYPE_FLOAT;
  369. }
  370. // Expand the texture if possible
  371. if (expandTexture) {
  372. // Simply run through the decode PP
  373. rgbdPostProcess = new PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, Constants.TEXTURE_TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  374. texture._isRGBD = false;
  375. texture.invertY = false;
  376. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  377. generateDepthBuffer: false,
  378. generateMipMaps: true,
  379. generateStencilBuffer: false,
  380. samplingMode: Constants.TEXTURE_TRILINEAR_SAMPLINGMODE,
  381. type: texture.type,
  382. format: Constants.TEXTUREFORMAT_RGBA
  383. });
  384. }
  385. else {
  386. texture._isRGBD = true;
  387. texture.invertY = true;
  388. // In case of missing support, applies the same patch than DDS files.
  389. if (generateNonLODTextures) {
  390. let mipSlices = 3;
  391. let scale = texture._lodGenerationScale;
  392. let offset = texture._lodGenerationOffset;
  393. for (let i = 0; i < mipSlices; i++) {
  394. //compute LOD from even spacing in smoothness (matching shader calculation)
  395. let smoothness = i / (mipSlices - 1);
  396. let roughness = 1 - smoothness;
  397. let minLODIndex = offset; // roughness = 0
  398. let maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  399. let lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  400. let mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  401. let glTextureFromLod = new InternalTexture(engine, InternalTexture.DATASOURCE_TEMP);
  402. glTextureFromLod.isCube = true;
  403. glTextureFromLod.invertY = true;
  404. glTextureFromLod.generateMipMaps = false;
  405. engine.updateTextureSamplingMode(Constants.TEXTURE_LINEAR_LINEAR, glTextureFromLod);
  406. // Wrap in a base texture for easy binding.
  407. let lodTexture = new BaseTexture(null);
  408. lodTexture.isCube = true;
  409. lodTexture._texture = glTextureFromLod;
  410. lodTextures![mipmapIndex] = lodTexture;
  411. switch (i) {
  412. case 0:
  413. texture._lodTextureLow = lodTexture;
  414. break;
  415. case 1:
  416. texture._lodTextureMid = lodTexture;
  417. break;
  418. case 2:
  419. texture._lodTextureHigh = lodTexture;
  420. break;
  421. }
  422. }
  423. }
  424. }
  425. let promises: Promise<void>[] = [];
  426. // All mipmaps up to provided number of images
  427. for (let i = 0; i < imageData.length; i++) {
  428. // All faces
  429. for (let face = 0; face < 6; face++) {
  430. // Constructs an image element from image data
  431. let bytes = imageData[i][face];
  432. let blob = new Blob([bytes], { type: 'image/png' });
  433. let url = URL.createObjectURL(blob);
  434. let image = new Image();
  435. image.src = url;
  436. // Enqueue promise to upload to the texture.
  437. let promise = new Promise<void>((resolve, reject) => {
  438. image.onload = () => {
  439. if (expandTexture) {
  440. let tempTexture = engine.createTexture(null, true, true, null, Constants.TEXTURE_NEAREST_SAMPLINGMODE, null,
  441. (message) => {
  442. reject(message);
  443. },
  444. image);
  445. rgbdPostProcess!.getEffect().executeWhenCompiled(() => {
  446. // Uncompress the data to a RTT
  447. rgbdPostProcess!.onApply = (effect) => {
  448. effect._bindTexture("textureSampler", tempTexture);
  449. effect.setFloat2("scale", 1, 1);
  450. };
  451. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess!], cubeRtt, true, face, i);
  452. // Cleanup
  453. engine.restoreDefaultFramebuffer();
  454. tempTexture.dispose();
  455. window.URL.revokeObjectURL(url);
  456. resolve();
  457. });
  458. }
  459. else {
  460. engine._uploadImageToTexture(texture, image, face, i);
  461. // Upload the face to the non lod texture support
  462. if (generateNonLODTextures) {
  463. let lodTexture = lodTextures![i];
  464. if (lodTexture) {
  465. engine._uploadImageToTexture(lodTexture._texture!, image, face, 0);
  466. }
  467. }
  468. resolve();
  469. }
  470. };
  471. image.onerror = (error) => {
  472. reject(error);
  473. };
  474. });
  475. promises.push(promise);
  476. }
  477. }
  478. // Fill remaining mipmaps with black textures.
  479. if (imageData.length < mipmapsCount) {
  480. let data: ArrayBufferView;
  481. const size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  482. const dataLength = size * size * 4;
  483. switch (texture.type) {
  484. case Constants.TEXTURETYPE_UNSIGNED_INT: {
  485. data = new Uint8Array(dataLength);
  486. break;
  487. }
  488. case Constants.TEXTURETYPE_HALF_FLOAT: {
  489. data = new Uint16Array(dataLength);
  490. break;
  491. }
  492. case Constants.TEXTURETYPE_FLOAT: {
  493. data = new Float32Array(dataLength);
  494. break;
  495. }
  496. }
  497. for (let i = imageData.length; i < mipmapsCount; i++) {
  498. for (let face = 0; face < 6; face++) {
  499. engine._uploadArrayBufferViewToTexture(texture, data!, face, i);
  500. }
  501. }
  502. }
  503. // Once all done, finishes the cleanup and return
  504. return Promise.all(promises).then(() => {
  505. // Release temp RTT.
  506. if (cubeRtt) {
  507. engine._releaseFramebufferObjects(cubeRtt);
  508. engine._releaseTexture(texture);
  509. cubeRtt._swapAndDie(texture);
  510. }
  511. // Release temp Post Process.
  512. if (rgbdPostProcess) {
  513. rgbdPostProcess.dispose();
  514. }
  515. // Flag internal texture as ready in case they are in use.
  516. if (generateNonLODTextures) {
  517. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  518. texture._lodTextureHigh._texture.isReady = true;
  519. }
  520. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  521. texture._lodTextureMid._texture.isReady = true;
  522. }
  523. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  524. texture._lodTextureLow._texture.isReady = true;
  525. }
  526. }
  527. });
  528. }
  529. /**
  530. * Uploads spherical polynomials information to the texture.
  531. * @param texture defines the texture we are trying to upload the information to
  532. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  533. */
  534. public static UploadEnvSpherical(texture: InternalTexture, info: EnvironmentTextureInfo): void {
  535. if (info.version !== 1) {
  536. Logger.Warn('Unsupported babylon environment map version "' + info.version + '"');
  537. }
  538. let irradianceInfo = info.irradiance as EnvironmentTextureIrradianceInfoV1;
  539. if (!irradianceInfo) {
  540. return;
  541. }
  542. const sp = new SphericalPolynomial();
  543. Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  544. Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  545. Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  546. Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  547. Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  548. Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  549. Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  550. Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  551. Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  552. texture._sphericalPolynomial = sp;
  553. }
  554. /** @hidden */
  555. public static _UpdateRGBDAsync(internalTexture: InternalTexture, data: ArrayBufferView[][], sphericalPolynomial: Nullable<SphericalPolynomial>, lodScale: number, lodOffset: number): Promise<void> {
  556. internalTexture._dataSource = InternalTexture.DATASOURCE_CUBERAW_RGBD;
  557. internalTexture._bufferViewArrayArray = data;
  558. internalTexture._lodGenerationScale = lodScale;
  559. internalTexture._lodGenerationOffset = lodOffset;
  560. internalTexture._sphericalPolynomial = sphericalPolynomial;
  561. return EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(() => {
  562. internalTexture.isReady = true;
  563. });
  564. }
  565. }
  566. // References the dependencies.
  567. InternalTexture._UpdateRGBDAsync = EnvironmentTextureTools._UpdateRGBDAsync;