dds.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  1. import { Scalar } from "../Maths/math.scalar";
  2. import { SphericalPolynomial } from "../Maths/sphericalPolynomial";
  3. import { Constants } from "../Engines/constants";
  4. import { Engine } from "../Engines/engine";
  5. import { InternalTexture } from "../Materials/Textures/internalTexture";
  6. import { Nullable } from "../types";
  7. import { Logger } from "../Misc/logger";
  8. import { CubeMapToSphericalPolynomialTools } from "../Misc/HighDynamicRange/cubemapToSphericalPolynomial";
  9. import { Scene } from '../scene';
  10. import { BaseTexture } from '../Materials/Textures/baseTexture';
  11. import "../Engines/Extensions/engine.cubeTexture";
  12. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  13. // All values and structures referenced from:
  14. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15. var DDS_MAGIC = 0x20534444;
  16. var
  17. //DDSD_CAPS = 0x1,
  18. //DDSD_HEIGHT = 0x2,
  19. //DDSD_WIDTH = 0x4,
  20. //DDSD_PITCH = 0x8,
  21. //DDSD_PIXELFORMAT = 0x1000,
  22. DDSD_MIPMAPCOUNT = 0x20000;
  23. //DDSD_LINEARSIZE = 0x80000,
  24. //DDSD_DEPTH = 0x800000;
  25. // var DDSCAPS_COMPLEX = 0x8,
  26. // DDSCAPS_MIPMAP = 0x400000,
  27. // DDSCAPS_TEXTURE = 0x1000;
  28. var DDSCAPS2_CUBEMAP = 0x200;
  29. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  30. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  31. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  32. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  33. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  34. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  35. // DDSCAPS2_VOLUME = 0x200000;
  36. var
  37. //DDPF_ALPHAPIXELS = 0x1,
  38. //DDPF_ALPHA = 0x2,
  39. DDPF_FOURCC = 0x4,
  40. DDPF_RGB = 0x40,
  41. //DDPF_YUV = 0x200,
  42. DDPF_LUMINANCE = 0x20000;
  43. function FourCCToInt32(value: string) {
  44. return value.charCodeAt(0) +
  45. (value.charCodeAt(1) << 8) +
  46. (value.charCodeAt(2) << 16) +
  47. (value.charCodeAt(3) << 24);
  48. }
  49. function Int32ToFourCC(value: number) {
  50. return String.fromCharCode(
  51. value & 0xff,
  52. (value >> 8) & 0xff,
  53. (value >> 16) & 0xff,
  54. (value >> 24) & 0xff
  55. );
  56. }
  57. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  58. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  59. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  60. var FOURCC_DX10 = FourCCToInt32("DX10");
  61. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  62. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  63. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  64. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  65. var headerLengthInt = 31; // The header length in 32 bit ints
  66. // Offsets into the header array
  67. var off_magic = 0;
  68. var off_size = 1;
  69. var off_flags = 2;
  70. var off_height = 3;
  71. var off_width = 4;
  72. var off_mipmapCount = 7;
  73. var off_pfFlags = 20;
  74. var off_pfFourCC = 21;
  75. var off_RGBbpp = 22;
  76. var off_RMask = 23;
  77. var off_GMask = 24;
  78. var off_BMask = 25;
  79. var off_AMask = 26;
  80. // var off_caps1 = 27;
  81. var off_caps2 = 28;
  82. // var off_caps3 = 29;
  83. // var off_caps4 = 30;
  84. var off_dxgiFormat = 32;
  85. /**
  86. * Direct draw surface info
  87. * @see https://docs.microsoft.com/en-us/windows/desktop/direct3ddds/dx-graphics-dds-pguide
  88. */
  89. export interface DDSInfo {
  90. /**
  91. * Width of the texture
  92. */
  93. width: number;
  94. /**
  95. * Width of the texture
  96. */
  97. height: number;
  98. /**
  99. * Number of Mipmaps for the texture
  100. * @see https://en.wikipedia.org/wiki/Mipmap
  101. */
  102. mipmapCount: number;
  103. /**
  104. * If the textures format is a known fourCC format
  105. * @see https://www.fourcc.org/
  106. */
  107. isFourCC: boolean;
  108. /**
  109. * If the texture is an RGB format eg. DXGI_FORMAT_B8G8R8X8_UNORM format
  110. */
  111. isRGB: boolean;
  112. /**
  113. * If the texture is a lumincance format
  114. */
  115. isLuminance: boolean;
  116. /**
  117. * If this is a cube texture
  118. * @see https://docs.microsoft.com/en-us/windows/desktop/direct3ddds/dds-file-layout-for-cubic-environment-maps
  119. */
  120. isCube: boolean;
  121. /**
  122. * If the texture is a compressed format eg. FOURCC_DXT1
  123. */
  124. isCompressed: boolean;
  125. /**
  126. * The dxgiFormat of the texture
  127. * @see https://docs.microsoft.com/en-us/windows/desktop/api/dxgiformat/ne-dxgiformat-dxgi_format
  128. */
  129. dxgiFormat: number;
  130. /**
  131. * Texture type eg. Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT
  132. */
  133. textureType: number;
  134. /**
  135. * Sphericle polynomial created for the dds texture
  136. */
  137. sphericalPolynomial?: SphericalPolynomial;
  138. }
  139. /**
  140. * Class used to provide DDS decompression tools
  141. */
  142. export class DDSTools {
  143. /**
  144. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  145. */
  146. public static StoreLODInAlphaChannel = false;
  147. /**
  148. * Gets DDS information from an array buffer
  149. * @param arrayBuffer defines the array buffer to read data from
  150. * @returns the DDS information
  151. */
  152. public static GetDDSInfo(arrayBuffer: any): DDSInfo {
  153. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  154. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  155. var mipmapCount = 1;
  156. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  157. mipmapCount = Math.max(1, header[off_mipmapCount]);
  158. }
  159. var fourCC = header[off_pfFourCC];
  160. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  161. var textureType = Constants.TEXTURETYPE_UNSIGNED_INT;
  162. switch (fourCC) {
  163. case FOURCC_D3DFMT_R16G16B16A16F:
  164. textureType = Constants.TEXTURETYPE_HALF_FLOAT;
  165. break;
  166. case FOURCC_D3DFMT_R32G32B32A32F:
  167. textureType = Constants.TEXTURETYPE_FLOAT;
  168. break;
  169. case FOURCC_DX10:
  170. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  171. textureType = Constants.TEXTURETYPE_HALF_FLOAT;
  172. break;
  173. }
  174. }
  175. return {
  176. width: header[off_width],
  177. height: header[off_height],
  178. mipmapCount: mipmapCount,
  179. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  180. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  181. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  182. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  183. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  184. dxgiFormat: dxgiFormat,
  185. textureType: textureType
  186. };
  187. }
  188. // ref: http://stackoverflow.com/questions/32633585/how-do-you-convert-to-half-floats-in-javascript
  189. private static _FloatView: Float32Array;
  190. private static _Int32View: Int32Array;
  191. private static _ToHalfFloat(value: number): number {
  192. if (!DDSTools._FloatView) {
  193. DDSTools._FloatView = new Float32Array(1);
  194. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  195. }
  196. DDSTools._FloatView[0] = value;
  197. var x = DDSTools._Int32View[0];
  198. var bits = (x >> 16) & 0x8000; /* Get the sign */
  199. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  200. var e = (x >> 23) & 0xff; /* Using int is faster here */
  201. /* If zero, or denormal, or exponent underflows too much for a denormal
  202. * half, return signed zero. */
  203. if (e < 103) {
  204. return bits;
  205. }
  206. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  207. if (e > 142) {
  208. bits |= 0x7c00;
  209. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  210. * not Inf, so make sure we set one mantissa bit too. */
  211. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  212. return bits;
  213. }
  214. /* If exponent underflows but not too much, return a denormal */
  215. if (e < 113) {
  216. m |= 0x0800;
  217. /* Extra rounding may overflow and set mantissa to 0 and exponent
  218. * to 1, which is OK. */
  219. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  220. return bits;
  221. }
  222. bits |= ((e - 112) << 10) | (m >> 1);
  223. bits += m & 1;
  224. return bits;
  225. }
  226. private static _FromHalfFloat(value: number): number {
  227. var s = (value & 0x8000) >> 15;
  228. var e = (value & 0x7C00) >> 10;
  229. var f = value & 0x03FF;
  230. if (e === 0) {
  231. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  232. } else if (e == 0x1F) {
  233. return f ? NaN : ((s ? -1 : 1) * Infinity);
  234. }
  235. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  236. }
  237. private static _GetHalfFloatAsFloatRGBAArrayBuffer(width: number, height: number, dataOffset: number, dataLength: number, arrayBuffer: ArrayBuffer, lod: number): Float32Array {
  238. var destArray = new Float32Array(dataLength);
  239. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  240. var index = 0;
  241. for (var y = 0; y < height; y++) {
  242. for (var x = 0; x < width; x++) {
  243. var srcPos = (x + y * width) * 4;
  244. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  245. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  246. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  247. if (DDSTools.StoreLODInAlphaChannel) {
  248. destArray[index + 3] = lod;
  249. } else {
  250. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  251. }
  252. index += 4;
  253. }
  254. }
  255. return destArray;
  256. }
  257. private static _GetHalfFloatRGBAArrayBuffer(width: number, height: number, dataOffset: number, dataLength: number, arrayBuffer: ArrayBuffer, lod: number): Uint16Array {
  258. if (DDSTools.StoreLODInAlphaChannel) {
  259. var destArray = new Uint16Array(dataLength);
  260. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  261. var index = 0;
  262. for (var y = 0; y < height; y++) {
  263. for (var x = 0; x < width; x++) {
  264. var srcPos = (x + y * width) * 4;
  265. destArray[index] = srcData[srcPos];
  266. destArray[index + 1] = srcData[srcPos + 1];
  267. destArray[index + 2] = srcData[srcPos + 2];
  268. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  269. index += 4;
  270. }
  271. }
  272. return destArray;
  273. }
  274. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  275. }
  276. private static _GetFloatRGBAArrayBuffer(width: number, height: number, dataOffset: number, dataLength: number, arrayBuffer: ArrayBuffer, lod: number): Float32Array {
  277. if (DDSTools.StoreLODInAlphaChannel) {
  278. var destArray = new Float32Array(dataLength);
  279. var srcData = new Float32Array(arrayBuffer, dataOffset);
  280. var index = 0;
  281. for (var y = 0; y < height; y++) {
  282. for (var x = 0; x < width; x++) {
  283. var srcPos = (x + y * width) * 4;
  284. destArray[index] = srcData[srcPos];
  285. destArray[index + 1] = srcData[srcPos + 1];
  286. destArray[index + 2] = srcData[srcPos + 2];
  287. destArray[index + 3] = lod;
  288. index += 4;
  289. }
  290. }
  291. return destArray;
  292. }
  293. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  294. }
  295. private static _GetFloatAsUIntRGBAArrayBuffer(width: number, height: number, dataOffset: number, dataLength: number, arrayBuffer: ArrayBuffer, lod: number): Float32Array {
  296. var destArray = new Uint8Array(dataLength);
  297. var srcData = new Float32Array(arrayBuffer, dataOffset);
  298. var index = 0;
  299. for (var y = 0; y < height; y++) {
  300. for (var x = 0; x < width; x++) {
  301. var srcPos = (x + y * width) * 4;
  302. destArray[index] = Scalar.Clamp(srcData[srcPos]) * 255;
  303. destArray[index + 1] = Scalar.Clamp(srcData[srcPos + 1]) * 255;
  304. destArray[index + 2] = Scalar.Clamp(srcData[srcPos + 2]) * 255;
  305. if (DDSTools.StoreLODInAlphaChannel) {
  306. destArray[index + 3] = lod;
  307. } else {
  308. destArray[index + 3] = Scalar.Clamp(srcData[srcPos + 3]) * 255;
  309. }
  310. index += 4;
  311. }
  312. }
  313. return destArray;
  314. }
  315. private static _GetHalfFloatAsUIntRGBAArrayBuffer(width: number, height: number, dataOffset: number, dataLength: number, arrayBuffer: ArrayBuffer, lod: number): Float32Array {
  316. var destArray = new Uint8Array(dataLength);
  317. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  318. var index = 0;
  319. for (var y = 0; y < height; y++) {
  320. for (var x = 0; x < width; x++) {
  321. var srcPos = (x + y * width) * 4;
  322. destArray[index] = Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  323. destArray[index + 1] = Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  324. destArray[index + 2] = Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  325. if (DDSTools.StoreLODInAlphaChannel) {
  326. destArray[index + 3] = lod;
  327. } else {
  328. destArray[index + 3] = Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  329. }
  330. index += 4;
  331. }
  332. }
  333. return destArray;
  334. }
  335. private static _GetRGBAArrayBuffer(width: number, height: number, dataOffset: number, dataLength: number, arrayBuffer: ArrayBuffer, rOffset: number, gOffset: number, bOffset: number, aOffset: number): Uint8Array {
  336. var byteArray = new Uint8Array(dataLength);
  337. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  338. var index = 0;
  339. for (var y = 0; y < height; y++) {
  340. for (var x = 0; x < width; x++) {
  341. var srcPos = (x + y * width) * 4;
  342. byteArray[index] = srcData[srcPos + rOffset];
  343. byteArray[index + 1] = srcData[srcPos + gOffset];
  344. byteArray[index + 2] = srcData[srcPos + bOffset];
  345. byteArray[index + 3] = srcData[srcPos + aOffset];
  346. index += 4;
  347. }
  348. }
  349. return byteArray;
  350. }
  351. private static _ExtractLongWordOrder(value: number): number {
  352. if (value === 0 || value === 255 || value === -16777216) {
  353. return 0;
  354. }
  355. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  356. }
  357. private static _GetRGBArrayBuffer(width: number, height: number, dataOffset: number, dataLength: number, arrayBuffer: ArrayBuffer, rOffset: number, gOffset: number, bOffset: number): Uint8Array {
  358. var byteArray = new Uint8Array(dataLength);
  359. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  360. var index = 0;
  361. for (var y = 0; y < height; y++) {
  362. for (var x = 0; x < width; x++) {
  363. var srcPos = (x + y * width) * 3;
  364. byteArray[index] = srcData[srcPos + rOffset];
  365. byteArray[index + 1] = srcData[srcPos + gOffset];
  366. byteArray[index + 2] = srcData[srcPos + bOffset];
  367. index += 3;
  368. }
  369. }
  370. return byteArray;
  371. }
  372. private static _GetLuminanceArrayBuffer(width: number, height: number, dataOffset: number, dataLength: number, arrayBuffer: ArrayBuffer): Uint8Array {
  373. var byteArray = new Uint8Array(dataLength);
  374. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  375. var index = 0;
  376. for (var y = 0; y < height; y++) {
  377. for (var x = 0; x < width; x++) {
  378. var srcPos = (x + y * width);
  379. byteArray[index] = srcData[srcPos];
  380. index++;
  381. }
  382. }
  383. return byteArray;
  384. }
  385. /**
  386. * Uploads DDS Levels to a Babylon Texture
  387. * @hidden
  388. */
  389. public static UploadDDSLevels(engine: Engine, texture: InternalTexture, arrayBuffer: any, info: DDSInfo, loadMipmaps: boolean, faces: number, lodIndex = -1, currentFace?: number) {
  390. var sphericalPolynomialFaces: Nullable<Array<ArrayBufferView>> = null;
  391. if (info.sphericalPolynomial) {
  392. sphericalPolynomialFaces = new Array<ArrayBufferView>();
  393. }
  394. var ext = engine.getCaps().s3tc;
  395. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  396. var fourCC: number, width: number, height: number, dataLength: number = 0, dataOffset: number;
  397. var byteArray: Uint8Array, mipmapCount: number, mip: number;
  398. let internalCompressedFormat = 0;
  399. let blockBytes = 1;
  400. if (header[off_magic] !== DDS_MAGIC) {
  401. Logger.Error("Invalid magic number in DDS header");
  402. return;
  403. }
  404. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  405. Logger.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  406. return;
  407. }
  408. if (info.isCompressed && !ext) {
  409. Logger.Error("Compressed textures are not supported on this platform.");
  410. return;
  411. }
  412. var bpp = header[off_RGBbpp];
  413. dataOffset = header[off_size] + 4;
  414. let computeFormats = false;
  415. if (info.isFourCC) {
  416. fourCC = header[off_pfFourCC];
  417. switch (fourCC) {
  418. case FOURCC_DXT1:
  419. blockBytes = 8;
  420. internalCompressedFormat = (<WEBGL_compressed_texture_s3tc>ext).COMPRESSED_RGBA_S3TC_DXT1_EXT;
  421. break;
  422. case FOURCC_DXT3:
  423. blockBytes = 16;
  424. internalCompressedFormat = (<WEBGL_compressed_texture_s3tc>ext).COMPRESSED_RGBA_S3TC_DXT3_EXT;
  425. break;
  426. case FOURCC_DXT5:
  427. blockBytes = 16;
  428. internalCompressedFormat = (<WEBGL_compressed_texture_s3tc>ext).COMPRESSED_RGBA_S3TC_DXT5_EXT;
  429. break;
  430. case FOURCC_D3DFMT_R16G16B16A16F:
  431. computeFormats = true;
  432. break;
  433. case FOURCC_D3DFMT_R32G32B32A32F:
  434. computeFormats = true;
  435. break;
  436. case FOURCC_DX10:
  437. // There is an additionnal header so dataOffset need to be changed
  438. dataOffset += 5 * 4; // 5 uints
  439. let supported = false;
  440. switch (info.dxgiFormat) {
  441. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  442. computeFormats = true;
  443. supported = true;
  444. break;
  445. case DXGI_FORMAT_B8G8R8X8_UNORM:
  446. info.isRGB = true;
  447. info.isFourCC = false;
  448. bpp = 32;
  449. supported = true;
  450. break;
  451. }
  452. if (supported) {
  453. break;
  454. }
  455. default:
  456. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  457. return;
  458. }
  459. }
  460. let rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  461. let gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  462. let bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  463. let aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  464. if (computeFormats) {
  465. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  466. }
  467. mipmapCount = 1;
  468. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  469. mipmapCount = Math.max(1, header[off_mipmapCount]);
  470. }
  471. const startFace = currentFace || 0;
  472. for (var face = startFace; face < faces; face++) {
  473. width = header[off_width];
  474. height = header[off_height];
  475. for (mip = 0; mip < mipmapCount; ++mip) {
  476. if (lodIndex === -1 || lodIndex === mip) {
  477. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  478. const i = (lodIndex === -1) ? mip : 0;
  479. if (!info.isCompressed && info.isFourCC) {
  480. texture.format = Constants.TEXTUREFORMAT_RGBA;
  481. dataLength = width * height * 4;
  482. var floatArray: Nullable<ArrayBufferView> = null;
  483. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  484. if (bpp === 128) {
  485. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  486. if (sphericalPolynomialFaces && i == 0) {
  487. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  488. }
  489. }
  490. else if (bpp === 64) {
  491. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  492. if (sphericalPolynomialFaces && i == 0) {
  493. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  494. }
  495. }
  496. texture.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  497. }
  498. else {
  499. if (bpp === 128) {
  500. texture.type = Constants.TEXTURETYPE_FLOAT;
  501. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  502. if (sphericalPolynomialFaces && i == 0) {
  503. sphericalPolynomialFaces.push(floatArray);
  504. }
  505. } else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  506. texture.type = Constants.TEXTURETYPE_FLOAT;
  507. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  508. if (sphericalPolynomialFaces && i == 0) {
  509. sphericalPolynomialFaces.push(floatArray);
  510. }
  511. } else { // 64
  512. texture.type = Constants.TEXTURETYPE_HALF_FLOAT;
  513. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  514. if (sphericalPolynomialFaces && i == 0) {
  515. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  516. }
  517. }
  518. }
  519. if (floatArray) {
  520. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  521. }
  522. } else if (info.isRGB) {
  523. texture.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  524. if (bpp === 24) {
  525. texture.format = Constants.TEXTUREFORMAT_RGB;
  526. dataLength = width * height * 3;
  527. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  528. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  529. } else { // 32
  530. texture.format = Constants.TEXTUREFORMAT_RGBA;
  531. dataLength = width * height * 4;
  532. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  533. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  534. }
  535. } else if (info.isLuminance) {
  536. var unpackAlignment = engine._getUnpackAlignement();
  537. var unpaddedRowSize = width;
  538. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  539. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  540. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  541. texture.format = Constants.TEXTUREFORMAT_LUMINANCE;
  542. texture.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  543. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  544. } else {
  545. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  546. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  547. texture.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  548. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  549. }
  550. }
  551. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  552. width *= 0.5;
  553. height *= 0.5;
  554. width = Math.max(1.0, width);
  555. height = Math.max(1.0, height);
  556. }
  557. if (currentFace !== undefined) {
  558. // Loading a single face
  559. break;
  560. }
  561. }
  562. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  563. info.sphericalPolynomial = CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  564. size: header[off_width],
  565. right: sphericalPolynomialFaces[0],
  566. left: sphericalPolynomialFaces[1],
  567. up: sphericalPolynomialFaces[2],
  568. down: sphericalPolynomialFaces[3],
  569. front: sphericalPolynomialFaces[4],
  570. back: sphericalPolynomialFaces[5],
  571. format: Constants.TEXTUREFORMAT_RGBA,
  572. type: Constants.TEXTURETYPE_FLOAT,
  573. gammaSpace: false,
  574. });
  575. } else {
  576. info.sphericalPolynomial = undefined;
  577. }
  578. }
  579. }
  580. declare module "../Engines/engine" {
  581. export interface Engine {
  582. /**
  583. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  584. * @param rootUrl defines the url where the file to load is located
  585. * @param scene defines the current scene
  586. * @param lodScale defines scale to apply to the mip map selection
  587. * @param lodOffset defines offset to apply to the mip map selection
  588. * @param onLoad defines an optional callback raised when the texture is loaded
  589. * @param onError defines an optional callback raised if there is an issue to load the texture
  590. * @param format defines the format of the data
  591. * @param forcedExtension defines the extension to use to pick the right loader
  592. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  593. * @returns the cube texture as an InternalTexture
  594. */
  595. createPrefilteredCubeTexture(rootUrl: string, scene: Nullable<Scene>, lodScale: number, lodOffset: number,
  596. onLoad?: Nullable<(internalTexture: Nullable<InternalTexture>) => void>,
  597. onError?: Nullable<(message?: string, exception?: any) => void>,
  598. format?: number, forcedExtension?: any,
  599. createPolynomials?: boolean): InternalTexture;
  600. }
  601. }
  602. /**
  603. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  604. * @param rootUrl defines the url where the file to load is located
  605. * @param scene defines the current scene
  606. * @param lodScale defines scale to apply to the mip map selection
  607. * @param lodOffset defines offset to apply to the mip map selection
  608. * @param onLoad defines an optional callback raised when the texture is loaded
  609. * @param onError defines an optional callback raised if there is an issue to load the texture
  610. * @param format defines the format of the data
  611. * @param forcedExtension defines the extension to use to pick the right loader
  612. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  613. * @returns the cube texture as an InternalTexture
  614. */
  615. Engine.prototype.createPrefilteredCubeTexture = function(rootUrl: string, scene: Nullable<Scene>, lodScale: number, lodOffset: number,
  616. onLoad: Nullable<(internalTexture: Nullable<InternalTexture>) => void> = null,
  617. onError: Nullable<(message?: string, exception?: any) => void> = null,
  618. format?: number, forcedExtension: any = null,
  619. createPolynomials: boolean = true): InternalTexture {
  620. var callback = (loadData: any) => {
  621. if (!loadData) {
  622. if (onLoad) {
  623. onLoad(null);
  624. }
  625. return;
  626. }
  627. let texture = loadData.texture as InternalTexture;
  628. if (!createPolynomials) {
  629. texture._sphericalPolynomial = new SphericalPolynomial();
  630. }
  631. else if (loadData.info.sphericalPolynomial) {
  632. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  633. }
  634. texture._dataSource = InternalTexture.DATASOURCE_CUBEPREFILTERED;
  635. if (this.getCaps().textureLOD) {
  636. // Do not add extra process if texture lod is supported.
  637. if (onLoad) {
  638. onLoad(texture);
  639. }
  640. return;
  641. }
  642. const mipSlices = 3;
  643. var gl = this._gl;
  644. const width = loadData.width;
  645. if (!width) {
  646. return;
  647. }
  648. const textures: BaseTexture[] = [];
  649. for (let i = 0; i < mipSlices; i++) {
  650. //compute LOD from even spacing in smoothness (matching shader calculation)
  651. let smoothness = i / (mipSlices - 1);
  652. let roughness = 1 - smoothness;
  653. let minLODIndex = lodOffset; // roughness = 0
  654. let maxLODIndex = Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  655. let lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  656. let mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  657. var glTextureFromLod = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  658. glTextureFromLod.type = texture.type;
  659. glTextureFromLod.format = texture.format;
  660. glTextureFromLod.width = Math.pow(2, Math.max(Scalar.Log2(width) - mipmapIndex, 0));
  661. glTextureFromLod.height = glTextureFromLod.width;
  662. glTextureFromLod.isCube = true;
  663. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  664. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  665. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  666. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  667. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  668. if (loadData.isDDS) {
  669. var info: DDSInfo = loadData.info;
  670. var data: any = loadData.data;
  671. this._unpackFlipY(info.isCompressed);
  672. DDSTools.UploadDDSLevels(this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  673. }
  674. else {
  675. Logger.Warn("DDS is the only prefiltered cube map supported so far.");
  676. }
  677. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  678. // Wrap in a base texture for easy binding.
  679. const lodTexture = new BaseTexture(scene);
  680. lodTexture.isCube = true;
  681. lodTexture._texture = glTextureFromLod;
  682. glTextureFromLod.isReady = true;
  683. textures.push(lodTexture);
  684. }
  685. texture._lodTextureHigh = textures[2];
  686. texture._lodTextureMid = textures[1];
  687. texture._lodTextureLow = textures[0];
  688. if (onLoad) {
  689. onLoad(texture);
  690. }
  691. };
  692. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  693. };