environmentTextureTools.ts 27 KB

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