khronosTextureContainer2.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. import { InternalTexture } from "../Materials/Textures/internalTexture";
  2. import { ThinEngine } from "../Engines/thinEngine";
  3. import { Constants } from '../Engines/constants';
  4. import { WorkerPool } from './workerPool';
  5. declare var KTX2DECODER: any;
  6. /**
  7. * Class for loading KTX2 files
  8. */
  9. export class KhronosTextureContainer2 {
  10. private static _WorkerPoolPromise?: Promise<WorkerPool>;
  11. private static _Initialized: boolean;
  12. private static _Ktx2Decoder: any; // used when no worker pool is used
  13. /**
  14. * URLs to use when loading the KTX2 decoder module as well as its dependencies
  15. * If a url is null, the default url is used (pointing to https://preview.babylonjs.com)
  16. * Note that jsDecoderModule can't be null and that the other dependencies will only be loaded if necessary
  17. * Urls you can change:
  18. * URLConfig.jsDecoderModule
  19. * URLConfig.wasmUASTCToASTC
  20. * URLConfig.wasmUASTCToBC7
  21. * URLConfig.wasmUASTCToRGBA_UNORM
  22. * URLConfig.wasmUASTCToRGBA_SRGB
  23. * URLConfig.jsMSCTranscoder
  24. * URLConfig.wasmMSCTranscoder
  25. * You can see their default values in this PG: https://playground.babylonjs.com/#EIJH8L#9
  26. */
  27. public static URLConfig = {
  28. jsDecoderModule: "https://preview.babylonjs.com/babylon.ktx2Decoder.js",
  29. wasmUASTCToASTC: null,
  30. wasmUASTCToBC7: null,
  31. wasmUASTCToRGBA_UNORM: null,
  32. wasmUASTCToRGBA_SRGB: null,
  33. jsMSCTranscoder: null,
  34. wasmMSCTranscoder: null,
  35. };
  36. /**
  37. * Default number of workers used to handle data decoding
  38. */
  39. public static DefaultNumWorkers = KhronosTextureContainer2.GetDefaultNumWorkers();
  40. private static GetDefaultNumWorkers(): number {
  41. if (typeof navigator !== "object" || !navigator.hardwareConcurrency) {
  42. return 1;
  43. }
  44. // Use 50% of the available logical processors but capped at 4.
  45. return Math.min(Math.floor(navigator.hardwareConcurrency * 0.5), 4);
  46. }
  47. private _engine: ThinEngine;
  48. private static _CreateWorkerPool(numWorkers: number) {
  49. this._Initialized = true;
  50. if (numWorkers && typeof Worker === "function") {
  51. KhronosTextureContainer2._WorkerPoolPromise = new Promise((resolve) => {
  52. const workerContent = `(${workerFunc})()`;
  53. const workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: "application/javascript" }));
  54. const workerPromises = new Array<Promise<Worker>>(numWorkers);
  55. for (let i = 0; i < workerPromises.length; i++) {
  56. workerPromises[i] = new Promise((resolve, reject) => {
  57. const worker = new Worker(workerBlobUrl);
  58. const onError = (error: ErrorEvent) => {
  59. worker.removeEventListener("error", onError);
  60. worker.removeEventListener("message", onMessage);
  61. reject(error);
  62. };
  63. const onMessage = (message: MessageEvent) => {
  64. if (message.data.action === "init") {
  65. worker.removeEventListener("error", onError);
  66. worker.removeEventListener("message", onMessage);
  67. resolve(worker);
  68. }
  69. };
  70. worker.addEventListener("error", onError);
  71. worker.addEventListener("message", onMessage);
  72. worker.postMessage({
  73. action: "init",
  74. urls: KhronosTextureContainer2.URLConfig
  75. });
  76. });
  77. }
  78. Promise.all(workerPromises).then((workers) => {
  79. resolve(new WorkerPool(workers));
  80. });
  81. });
  82. } else {
  83. KTX2DECODER.MSCTranscoder.UseFromWorkerThread = false;
  84. KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread = true;
  85. }
  86. }
  87. /**
  88. * Constructor
  89. * @param engine The engine to use
  90. * @param numWorkers The number of workers for async operations. Specify `0` to disable web workers and run synchronously in the current context.
  91. */
  92. public constructor(engine: ThinEngine, numWorkers = KhronosTextureContainer2.DefaultNumWorkers) {
  93. this._engine = engine;
  94. if (!KhronosTextureContainer2._Initialized) {
  95. KhronosTextureContainer2._CreateWorkerPool(numWorkers);
  96. }
  97. }
  98. /** @hidden */
  99. public uploadAsync(data: ArrayBufferView, internalTexture: InternalTexture, options?: any): Promise<void> {
  100. const caps = this._engine.getCaps();
  101. const compressedTexturesCaps = {
  102. astc: !!caps.astc,
  103. bptc: !!caps.bptc,
  104. s3tc: !!caps.s3tc,
  105. pvrtc: !!caps.pvrtc,
  106. etc2: !!caps.etc2,
  107. etc1: !!caps.etc1,
  108. };
  109. if (KhronosTextureContainer2._WorkerPoolPromise) {
  110. return KhronosTextureContainer2._WorkerPoolPromise.then((workerPool) => {
  111. return new Promise((resolve, reject) => {
  112. workerPool.push((worker, onComplete) => {
  113. const onError = (error: ErrorEvent) => {
  114. worker.removeEventListener("error", onError);
  115. worker.removeEventListener("message", onMessage);
  116. reject(error);
  117. onComplete();
  118. };
  119. const onMessage = (message: MessageEvent) => {
  120. if (message.data.action === "decoded") {
  121. worker.removeEventListener("error", onError);
  122. worker.removeEventListener("message", onMessage);
  123. if (!message.data.success) {
  124. reject({ message: message.data.msg });
  125. } else {
  126. try {
  127. this._createTexture(message.data.decodedData, internalTexture, options);
  128. resolve();
  129. } catch (err) {
  130. reject({ message: err });
  131. }
  132. }
  133. onComplete();
  134. }
  135. };
  136. worker.addEventListener("error", onError);
  137. worker.addEventListener("message", onMessage);
  138. // note: we can't transfer the ownership of data.buffer because if using a fallback texture the data.buffer buffer will be used by the current thread
  139. worker.postMessage({ action: "decode", data, caps: compressedTexturesCaps, options }/*, [data.buffer]*/);
  140. });
  141. });
  142. });
  143. }
  144. return new Promise((resolve, reject) => {
  145. if (!KhronosTextureContainer2._Ktx2Decoder) {
  146. KhronosTextureContainer2._Ktx2Decoder = new KTX2DECODER.KTX2Decoder();
  147. }
  148. KhronosTextureContainer2._Ktx2Decoder.decode(data, caps).then((data: any) => {
  149. this._createTexture(data, internalTexture);
  150. resolve();
  151. }).catch((reason: any) => {
  152. reject({ message: reason });
  153. });
  154. });
  155. }
  156. /**
  157. * Stop all async operations and release resources.
  158. */
  159. public dispose(): void {
  160. if (KhronosTextureContainer2._WorkerPoolPromise) {
  161. KhronosTextureContainer2._WorkerPoolPromise.then((workerPool) => {
  162. workerPool.dispose();
  163. });
  164. }
  165. delete KhronosTextureContainer2._WorkerPoolPromise;
  166. }
  167. protected _createTexture(data: any /* IDecodedData */, internalTexture: InternalTexture, options?: any) {
  168. this._engine._bindTextureDirectly(this._engine._gl.TEXTURE_2D, internalTexture);
  169. if (options) {
  170. // return back some information about the decoded data
  171. options.transcodedFormat = data.transcodedFormat;
  172. options.isInGammaSpace = data.isInGammaSpace;
  173. options.hasAlpha = data.hasAlpha;
  174. options.transcoderName = data.transcoderName;
  175. }
  176. if (data.transcodedFormat === 0x8058 /* RGBA8 */) {
  177. internalTexture.type = Constants.TEXTURETYPE_UNSIGNED_BYTE;
  178. internalTexture.format = Constants.TEXTUREFORMAT_RGBA;
  179. } else {
  180. internalTexture.format = data.transcodedFormat;
  181. }
  182. internalTexture._gammaSpace = data.isInGammaSpace;
  183. internalTexture._hasAlpha = data.hasAlpha;
  184. if (data.errors) {
  185. throw new Error("KTX2 container - could not transcode the data. " + data.errors);
  186. }
  187. for (let t = 0; t < data.mipmaps.length; ++t) {
  188. let mipmap = data.mipmaps[t];
  189. if (!mipmap || !mipmap.data) {
  190. throw new Error("KTX2 container - could not transcode one of the image");
  191. }
  192. if (data.transcodedFormat === 0x8058 /* RGBA8 */) {
  193. // uncompressed RGBA
  194. internalTexture.width = mipmap.width; // need to set width/height so that the call to _uploadDataToTextureDirectly uses the right dimensions
  195. internalTexture.height = mipmap.height;
  196. this._engine._uploadDataToTextureDirectly(internalTexture, mipmap.data, 0, t, undefined, true);
  197. } else {
  198. this._engine._uploadCompressedDataToTextureDirectly(internalTexture, data.transcodedFormat, mipmap.width, mipmap.height, mipmap.data, 0, t);
  199. }
  200. }
  201. internalTexture.width = data.mipmaps[0].width;
  202. internalTexture.height = data.mipmaps[0].height;
  203. internalTexture.generateMipMaps = data.mipmaps.length > 1;
  204. internalTexture.isReady = true;
  205. this._engine._bindTextureDirectly(this._engine._gl.TEXTURE_2D, null);
  206. }
  207. /**
  208. * Checks if the given data starts with a KTX2 file identifier.
  209. * @param data the data to check
  210. * @returns true if the data is a KTX2 file or false otherwise
  211. */
  212. public static IsValid(data: ArrayBufferView): boolean {
  213. if (data.byteLength >= 12) {
  214. // '«', 'K', 'T', 'X', ' ', '2', '0', '»', '\r', '\n', '\x1A', '\n'
  215. const identifier = new Uint8Array(data.buffer, data.byteOffset, 12);
  216. if (identifier[0] === 0xAB && identifier[1] === 0x4B && identifier[2] === 0x54 && identifier[3] === 0x58 && identifier[4] === 0x20 && identifier[5] === 0x32 &&
  217. identifier[6] === 0x30 && identifier[7] === 0xBB && identifier[8] === 0x0D && identifier[9] === 0x0A && identifier[10] === 0x1A && identifier[11] === 0x0A) {
  218. return true;
  219. }
  220. }
  221. return false;
  222. }
  223. }
  224. declare function importScripts(...urls: string[]): void;
  225. declare function postMessage(message: any, transfer?: any[]): void;
  226. declare var KTX2DECODER: any;
  227. function workerFunc(): void {
  228. let ktx2Decoder: any;
  229. onmessage = (event) => {
  230. switch (event.data.action) {
  231. case "init":
  232. const urls = event.data.urls;
  233. importScripts(urls.jsDecoderModule);
  234. if (urls.wasmUASTCToASTC !== null) {
  235. KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL = urls.wasmUASTCToASTC;
  236. }
  237. if (urls.wasmUASTCToBC7 !== null) {
  238. KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL = urls.wasmUASTCToBC7;
  239. }
  240. if (urls.wasmUASTCToRGBA_UNORM !== null) {
  241. KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL = urls.wasmUASTCToRGBA_UNORM;
  242. }
  243. if (urls.wasmUASTCToRGBA_SRGB !== null) {
  244. KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL = urls.wasmUASTCToRGBA_SRGB;
  245. }
  246. if (urls.jsMSCTranscoder !== null) {
  247. KTX2DECODER.MSCTranscoder.JSModuleURL = urls.jsMSCTranscoder;
  248. }
  249. if (urls.wasmMSCTranscoder !== null) {
  250. KTX2DECODER.MSCTranscoder.WasmModuleURL = urls.wasmMSCTranscoder;
  251. }
  252. ktx2Decoder = new KTX2DECODER.KTX2Decoder();
  253. postMessage({ action: "init" });
  254. break;
  255. case "decode":
  256. ktx2Decoder.decode(event.data.data, event.data.caps, event.data.options).then((data: any) => {
  257. const buffers = [];
  258. for (let mip = 0; mip < data.mipmaps.length; ++mip) {
  259. const mipmap = data.mipmaps[mip];
  260. if (mipmap && mipmap.data) {
  261. buffers.push(mipmap.data.buffer);
  262. }
  263. }
  264. postMessage({ action: "decoded", success: true, decodedData: data }, buffers);
  265. }).catch((reason: any) => {
  266. postMessage({ action: "decoded", success: false, msg: reason });
  267. });
  268. break;
  269. }
  270. };
  271. }