KTX2Loader.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  1. import {
  2. CompressedArrayTexture,
  3. CompressedCubeTexture,
  4. CompressedTexture,
  5. Data3DTexture,
  6. DataTexture,
  7. FileLoader,
  8. FloatType,
  9. HalfFloatType,
  10. LinearFilter,
  11. LinearMipmapLinearFilter,
  12. NearestFilter,
  13. NearestMipmapNearestFilter,
  14. LinearSRGBColorSpace,
  15. Loader,
  16. NoColorSpace,
  17. RGBAFormat,
  18. RGBA_ASTC_4x4_Format,
  19. RGBA_ASTC_6x6_Format,
  20. RGBA_BPTC_Format,
  21. RGBA_S3TC_DXT3_Format,
  22. RGBA_ETC2_EAC_Format,
  23. R11_EAC_Format,
  24. SIGNED_R11_EAC_Format,
  25. RG11_EAC_Format,
  26. SIGNED_RG11_EAC_Format,
  27. RGBA_PVRTC_4BPPV1_Format,
  28. RGBA_PVRTC_2BPPV1_Format,
  29. RGBA_S3TC_DXT1_Format,
  30. RGBA_S3TC_DXT5_Format,
  31. RGB_BPTC_UNSIGNED_Format,
  32. RGB_ETC1_Format,
  33. RGB_ETC2_Format,
  34. RGB_PVRTC_4BPPV1_Format,
  35. RGB_S3TC_DXT1_Format,
  36. SIGNED_RED_GREEN_RGTC2_Format,
  37. SIGNED_RED_RGTC1_Format,
  38. RED_GREEN_RGTC2_Format,
  39. RED_RGTC1_Format,
  40. RGBFormat,
  41. RGFormat,
  42. RedFormat,
  43. SRGBColorSpace,
  44. UnsignedByteType,
  45. UnsignedInt5999Type,
  46. UnsignedInt101111Type
  47. } from 'three';
  48. import { WorkerPool } from '../utils/WorkerPool.js';
  49. import {
  50. read,
  51. KHR_DF_FLAG_ALPHA_PREMULTIPLIED,
  52. KHR_DF_PRIMARIES_BT709,
  53. KHR_DF_PRIMARIES_DISPLAYP3,
  54. KHR_DF_PRIMARIES_UNSPECIFIED,
  55. KHR_DF_TRANSFER_SRGB,
  56. KHR_SUPERCOMPRESSION_NONE,
  57. KHR_SUPERCOMPRESSION_ZSTD,
  58. VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT,
  59. VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT,
  60. VK_FORMAT_ASTC_4x4_SRGB_BLOCK,
  61. VK_FORMAT_ASTC_4x4_UNORM_BLOCK,
  62. VK_FORMAT_ASTC_6x6_SRGB_BLOCK,
  63. VK_FORMAT_ASTC_6x6_UNORM_BLOCK,
  64. VK_FORMAT_BC1_RGBA_SRGB_BLOCK,
  65. VK_FORMAT_BC1_RGBA_UNORM_BLOCK,
  66. VK_FORMAT_BC1_RGB_SRGB_BLOCK,
  67. VK_FORMAT_BC1_RGB_UNORM_BLOCK,
  68. VK_FORMAT_BC3_SRGB_BLOCK,
  69. VK_FORMAT_BC3_UNORM_BLOCK,
  70. VK_FORMAT_BC4_SNORM_BLOCK,
  71. VK_FORMAT_BC4_UNORM_BLOCK,
  72. VK_FORMAT_BC5_SNORM_BLOCK,
  73. VK_FORMAT_BC5_UNORM_BLOCK,
  74. VK_FORMAT_BC7_SRGB_BLOCK,
  75. VK_FORMAT_BC7_UNORM_BLOCK,
  76. VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK,
  77. VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK,
  78. VK_FORMAT_EAC_R11_UNORM_BLOCK,
  79. VK_FORMAT_EAC_R11_SNORM_BLOCK,
  80. VK_FORMAT_EAC_R11G11_UNORM_BLOCK,
  81. VK_FORMAT_EAC_R11G11_SNORM_BLOCK,
  82. VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG,
  83. VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG,
  84. VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG,
  85. VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG,
  86. VK_FORMAT_R16G16B16A16_SFLOAT,
  87. VK_FORMAT_R16G16_SFLOAT,
  88. VK_FORMAT_R16_SFLOAT,
  89. VK_FORMAT_R32G32B32A32_SFLOAT,
  90. VK_FORMAT_R32G32_SFLOAT,
  91. VK_FORMAT_R32_SFLOAT,
  92. VK_FORMAT_R8G8B8A8_SRGB,
  93. VK_FORMAT_R8G8B8A8_UNORM,
  94. VK_FORMAT_R8G8_SRGB,
  95. VK_FORMAT_R8G8_UNORM,
  96. VK_FORMAT_R8_SRGB,
  97. VK_FORMAT_R8_UNORM,
  98. VK_FORMAT_E5B9G9R9_UFLOAT_PACK32,
  99. VK_FORMAT_B10G11R11_UFLOAT_PACK32,
  100. VK_FORMAT_UNDEFINED
  101. } from '../libs/ktx-parse.module.js';
  102. import { ZSTDDecoder } from '../libs/zstddec.module.js';
  103. import { DisplayP3ColorSpace, LinearDisplayP3ColorSpace } from '../math/ColorSpaces.js';
  104. const _taskCache = new WeakMap();
  105. let _activeLoaders = 0;
  106. let _zstd;
  107. /**
  108. * A loader for KTX 2.0 GPU Texture containers.
  109. *
  110. * KTX 2.0 is a container format for various GPU texture formats. The loader supports Basis Universal GPU textures,
  111. * which can be quickly transcoded to a wide variety of GPU texture compression formats. While KTX 2.0 also allows
  112. * other hardware-specific formats, this loader does not yet parse them.
  113. *
  114. * This loader parses the KTX 2.0 container and transcodes to a supported GPU compressed texture format.
  115. * The required WASM transcoder and JS wrapper are available from the `examples/jsm/libs/basis` directory.
  116. *
  117. * This loader relies on Web Assembly which is not supported in older browsers.
  118. *
  119. * References:
  120. * - [KTX specification](http://github.khronos.org/KTX-Specification/)
  121. * - [DFD](https://www.khronos.org/registry/DataFormat/specs/1.3/dataformat.1.3.html#basicdescriptor)
  122. * - [BasisU HDR](https://github.com/BinomialLLC/basis_universal/wiki/UASTC-HDR-Texture-Specification-v1.0)
  123. *
  124. * ```js
  125. * const loader = new KTX2Loader();
  126. * loader.setTranscoderPath( 'examples/jsm/libs/basis/' );
  127. * loader.detectSupport( renderer );
  128. * const texture = loader.loadAsync( 'diffuse.ktx2' );
  129. * ```
  130. *
  131. * @augments Loader
  132. * @three_import import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';
  133. */
  134. class KTX2Loader extends Loader {
  135. /**
  136. * Constructs a new KTX2 loader.
  137. *
  138. * @param {LoadingManager} [manager] - The loading manager.
  139. */
  140. constructor( manager ) {
  141. super( manager );
  142. this.transcoderPath = '';
  143. this.transcoderBinary = null;
  144. this.transcoderPending = null;
  145. this.workerPool = new WorkerPool();
  146. this.workerSourceURL = '';
  147. this.workerConfig = null;
  148. if ( typeof MSC_TRANSCODER !== 'undefined' ) {
  149. console.warn(
  150. 'THREE.KTX2Loader: Please update to latest "basis_transcoder".'
  151. + ' "msc_basis_transcoder" is no longer supported in three.js r125+.'
  152. );
  153. }
  154. }
  155. /**
  156. * Sets the transcoder path.
  157. *
  158. * The WASM transcoder and JS wrapper are available from the `examples/jsm/libs/basis` directory.
  159. *
  160. * @param {string} path - The transcoder path to set.
  161. * @return {KTX2Loader} A reference to this loader.
  162. */
  163. setTranscoderPath( path ) {
  164. this.transcoderPath = path;
  165. return this;
  166. }
  167. /**
  168. * Sets the maximum number of Web Workers to be allocated by this instance.
  169. *
  170. * @param {number} workerLimit - The worker limit.
  171. * @return {KTX2Loader} A reference to this loader.
  172. */
  173. setWorkerLimit( workerLimit ) {
  174. this.workerPool.setWorkerLimit( workerLimit );
  175. return this;
  176. }
  177. /**
  178. * Async version of {@link KTX2Loader#detectSupport}.
  179. *
  180. * @async
  181. * @deprecated
  182. * @param {WebGPURenderer} renderer - The renderer.
  183. * @return {Promise} A Promise that resolves when the support has been detected.
  184. */
  185. async detectSupportAsync( renderer ) {
  186. console.warn( 'KTX2Loader: "detectSupportAsync()" has been deprecated. Use "detectSupport()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  187. await renderer.init();
  188. return this.detectSupport( renderer );
  189. }
  190. /**
  191. * Detects hardware support for available compressed texture formats, to determine
  192. * the output format for the transcoder. Must be called before loading a texture.
  193. *
  194. * @param {WebGPURenderer|WebGLRenderer} renderer - The renderer.
  195. * @return {KTX2Loader} A reference to this loader.
  196. */
  197. detectSupport( renderer ) {
  198. if ( renderer.isWebGPURenderer === true ) {
  199. this.workerConfig = {
  200. astcSupported: renderer.hasFeature( 'texture-compression-astc' ),
  201. astcHDRSupported: false, // https://github.com/gpuweb/gpuweb/issues/3856
  202. etc1Supported: renderer.hasFeature( 'texture-compression-etc1' ),
  203. etc2Supported: renderer.hasFeature( 'texture-compression-etc2' ),
  204. dxtSupported: renderer.hasFeature( 'texture-compression-s3tc' ),
  205. bptcSupported: renderer.hasFeature( 'texture-compression-bc' ),
  206. pvrtcSupported: renderer.hasFeature( 'texture-compression-pvrtc' )
  207. };
  208. } else {
  209. this.workerConfig = {
  210. astcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_astc' ),
  211. astcHDRSupported: renderer.extensions.has( 'WEBGL_compressed_texture_astc' )
  212. && renderer.extensions.get( 'WEBGL_compressed_texture_astc' ).getSupportedProfiles().includes( 'hdr' ),
  213. etc1Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc1' ),
  214. etc2Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc' ),
  215. dxtSupported: renderer.extensions.has( 'WEBGL_compressed_texture_s3tc' ),
  216. bptcSupported: renderer.extensions.has( 'EXT_texture_compression_bptc' ),
  217. pvrtcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_pvrtc' )
  218. || renderer.extensions.has( 'WEBKIT_WEBGL_compressed_texture_pvrtc' )
  219. };
  220. if ( typeof navigator !== 'undefined' &&
  221. navigator.platform.indexOf( 'Linux' ) >= 0 && navigator.userAgent.indexOf( 'Firefox' ) >= 0 &&
  222. this.workerConfig.astcSupported && this.workerConfig.etc2Supported &&
  223. this.workerConfig.bptcSupported && this.workerConfig.dxtSupported ) {
  224. // On Linux, Mesa drivers for AMD and Intel GPUs expose ETC2 and ASTC even though the hardware doesn't support these.
  225. // Using these extensions will result in expensive software decompression on the main thread inside the driver, causing performance issues.
  226. // When using ANGLE (e.g. via Chrome), these extensions are not exposed except for some specific Intel GPU models - however, Firefox doesn't perform this filtering.
  227. // Since a granular filter is a little too fragile and we can transcode into other GPU formats, disable formats that are likely to be emulated.
  228. this.workerConfig.astcSupported = false;
  229. this.workerConfig.etc2Supported = false;
  230. }
  231. }
  232. return this;
  233. }
  234. // TODO: Make this method private
  235. init() {
  236. if ( ! this.transcoderPending ) {
  237. // Load transcoder wrapper.
  238. const jsLoader = new FileLoader( this.manager );
  239. jsLoader.setPath( this.transcoderPath );
  240. jsLoader.setWithCredentials( this.withCredentials );
  241. const jsContent = jsLoader.loadAsync( 'basis_transcoder.js' );
  242. // Load transcoder WASM binary.
  243. const binaryLoader = new FileLoader( this.manager );
  244. binaryLoader.setPath( this.transcoderPath );
  245. binaryLoader.setResponseType( 'arraybuffer' );
  246. binaryLoader.setWithCredentials( this.withCredentials );
  247. const binaryContent = binaryLoader.loadAsync( 'basis_transcoder.wasm' );
  248. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] )
  249. .then( ( [ jsContent, binaryContent ] ) => {
  250. const fn = KTX2Loader.BasisWorker.toString();
  251. const body = [
  252. '/* constants */',
  253. 'let _EngineFormat = ' + JSON.stringify( KTX2Loader.EngineFormat ),
  254. 'let _EngineType = ' + JSON.stringify( KTX2Loader.EngineType ),
  255. 'let _TranscoderFormat = ' + JSON.stringify( KTX2Loader.TranscoderFormat ),
  256. 'let _BasisFormat = ' + JSON.stringify( KTX2Loader.BasisFormat ),
  257. '/* basis_transcoder.js */',
  258. jsContent,
  259. '/* worker */',
  260. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  261. ].join( '\n' );
  262. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  263. this.transcoderBinary = binaryContent;
  264. this.workerPool.setWorkerCreator( () => {
  265. const worker = new Worker( this.workerSourceURL );
  266. const transcoderBinary = this.transcoderBinary.slice( 0 );
  267. worker.postMessage( { type: 'init', config: this.workerConfig, transcoderBinary }, [ transcoderBinary ] );
  268. return worker;
  269. } );
  270. } );
  271. if ( _activeLoaders > 0 ) {
  272. // Each instance loads a transcoder and allocates workers, increasing network and memory cost.
  273. console.warn(
  274. 'THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues.'
  275. + ' Use a single KTX2Loader instance, or call .dispose() on old instances.'
  276. );
  277. }
  278. _activeLoaders ++;
  279. }
  280. return this.transcoderPending;
  281. }
  282. /**
  283. * Starts loading from the given URL and passes the loaded KTX2 texture
  284. * to the `onLoad()` callback.
  285. *
  286. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  287. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  288. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  289. * @param {onErrorCallback} onError - Executed when errors occur.
  290. */
  291. load( url, onLoad, onProgress, onError ) {
  292. if ( this.workerConfig === null ) {
  293. throw new Error( 'THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.' );
  294. }
  295. const loader = new FileLoader( this.manager );
  296. loader.setPath( this.path );
  297. loader.setCrossOrigin( this.crossOrigin );
  298. loader.setWithCredentials( this.withCredentials );
  299. loader.setRequestHeader( this.requestHeader );
  300. loader.setResponseType( 'arraybuffer' );
  301. loader.load( url, ( buffer ) => {
  302. this.parse( buffer, onLoad, onError );
  303. }, onProgress, onError );
  304. }
  305. /**
  306. * Parses the given KTX2 data.
  307. *
  308. * @param {ArrayBuffer} buffer - The raw KTX2 data as an array buffer.
  309. * @param {function(CompressedTexture)} onLoad - Executed when the loading/parsing process has been finished.
  310. * @param {onErrorCallback} onError - Executed when errors occur.
  311. * @returns {Promise} A Promise that resolves when the parsing has been finished.
  312. */
  313. parse( buffer, onLoad, onError ) {
  314. if ( this.workerConfig === null ) {
  315. throw new Error( 'THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.' );
  316. }
  317. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  318. // again from this thread.
  319. if ( _taskCache.has( buffer ) ) {
  320. const cachedTask = _taskCache.get( buffer );
  321. return cachedTask.promise.then( onLoad ).catch( onError );
  322. }
  323. this._createTexture( buffer )
  324. .then( ( texture ) => onLoad ? onLoad( texture ) : null )
  325. .catch( onError );
  326. }
  327. _createTextureFrom( transcodeResult, container ) {
  328. const { type: messageType, error, data: { faces, width, height, format, type, dfdFlags } } = transcodeResult;
  329. if ( messageType === 'error' ) return Promise.reject( error );
  330. let texture;
  331. if ( container.faceCount === 6 ) {
  332. texture = new CompressedCubeTexture( faces, format, type );
  333. } else {
  334. const mipmaps = faces[ 0 ].mipmaps;
  335. texture = container.layerCount > 1
  336. ? new CompressedArrayTexture( mipmaps, width, height, container.layerCount, format, type )
  337. : new CompressedTexture( mipmaps, width, height, format, type );
  338. }
  339. texture.minFilter = faces[ 0 ].mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter;
  340. texture.magFilter = LinearFilter;
  341. texture.generateMipmaps = false;
  342. texture.needsUpdate = true;
  343. texture.colorSpace = parseColorSpace( container );
  344. texture.premultiplyAlpha = !! ( dfdFlags & KHR_DF_FLAG_ALPHA_PREMULTIPLIED );
  345. return texture;
  346. }
  347. /**
  348. * @private
  349. * @param {ArrayBuffer} buffer
  350. * @param {?Object} config
  351. * @return {Promise<CompressedTexture|CompressedArrayTexture|DataTexture|Data3DTexture>}
  352. */
  353. async _createTexture( buffer, config = {} ) {
  354. const container = read( new Uint8Array( buffer ) );
  355. // Basis UASTC HDR is a subset of ASTC, which can be transcoded efficiently
  356. // to BC6H. To detect whether a KTX2 file uses Basis UASTC HDR, or default
  357. // ASTC, inspect the DFD color model.
  358. //
  359. // Source: https://github.com/BinomialLLC/basis_universal/issues/381
  360. const isBasisHDR = container.vkFormat === VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT
  361. && container.dataFormatDescriptor[ 0 ].colorModel === 0xA7;
  362. // If the device supports ASTC, Basis UASTC HDR requires no transcoder.
  363. const needsTranscoder = container.vkFormat === VK_FORMAT_UNDEFINED
  364. || isBasisHDR && ! this.workerConfig.astcHDRSupported;
  365. if ( ! needsTranscoder ) {
  366. return createRawTexture( container );
  367. }
  368. //
  369. const taskConfig = config;
  370. const texturePending = this.init().then( () => {
  371. return this.workerPool.postMessage( { type: 'transcode', buffer, taskConfig: taskConfig }, [ buffer ] );
  372. } ).then( ( e ) => this._createTextureFrom( e.data, container ) );
  373. // Cache the task result.
  374. _taskCache.set( buffer, { promise: texturePending } );
  375. return texturePending;
  376. }
  377. /**
  378. * Frees internal resources. This method should be called
  379. * when the loader is no longer required.
  380. */
  381. dispose() {
  382. this.workerPool.dispose();
  383. if ( this.workerSourceURL ) URL.revokeObjectURL( this.workerSourceURL );
  384. _activeLoaders --;
  385. }
  386. }
  387. /* CONSTANTS */
  388. KTX2Loader.BasisFormat = {
  389. ETC1S: 0,
  390. UASTC: 1,
  391. UASTC_HDR: 2,
  392. };
  393. // Source: https://github.com/BinomialLLC/basis_universal/blob/master/webgl/texture_test/index.html
  394. KTX2Loader.TranscoderFormat = {
  395. ETC1: 0,
  396. ETC2: 1,
  397. BC1: 2,
  398. BC3: 3,
  399. BC4: 4,
  400. BC5: 5,
  401. BC7_M6_OPAQUE_ONLY: 6,
  402. BC7_M5: 7,
  403. PVRTC1_4_RGB: 8,
  404. PVRTC1_4_RGBA: 9,
  405. ASTC_4x4: 10,
  406. ATC_RGB: 11,
  407. ATC_RGBA_INTERPOLATED_ALPHA: 12,
  408. RGBA32: 13,
  409. RGB565: 14,
  410. BGR565: 15,
  411. RGBA4444: 16,
  412. BC6H: 22,
  413. RGB_HALF: 24,
  414. RGBA_HALF: 25,
  415. };
  416. KTX2Loader.EngineFormat = {
  417. RGBAFormat: RGBAFormat,
  418. RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
  419. RGB_BPTC_UNSIGNED_Format: RGB_BPTC_UNSIGNED_Format,
  420. RGBA_BPTC_Format: RGBA_BPTC_Format,
  421. RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
  422. RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
  423. RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format,
  424. RGB_ETC1_Format: RGB_ETC1_Format,
  425. RGB_ETC2_Format: RGB_ETC2_Format,
  426. RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
  427. RGBA_S3TC_DXT1_Format: RGBA_S3TC_DXT1_Format,
  428. };
  429. KTX2Loader.EngineType = {
  430. UnsignedByteType: UnsignedByteType,
  431. HalfFloatType: HalfFloatType,
  432. FloatType: FloatType,
  433. };
  434. /* WEB WORKER */
  435. KTX2Loader.BasisWorker = function () {
  436. let config;
  437. let transcoderPending;
  438. let BasisModule;
  439. const EngineFormat = _EngineFormat; // eslint-disable-line no-undef
  440. const EngineType = _EngineType; // eslint-disable-line no-undef
  441. const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef
  442. const BasisFormat = _BasisFormat; // eslint-disable-line no-undef
  443. self.addEventListener( 'message', function ( e ) {
  444. const message = e.data;
  445. switch ( message.type ) {
  446. case 'init':
  447. config = message.config;
  448. init( message.transcoderBinary );
  449. break;
  450. case 'transcode':
  451. transcoderPending.then( () => {
  452. try {
  453. const { faces, buffers, width, height, hasAlpha, format, type, dfdFlags } = transcode( message.buffer );
  454. self.postMessage( { type: 'transcode', id: message.id, data: { faces, width, height, hasAlpha, format, type, dfdFlags } }, buffers );
  455. } catch ( error ) {
  456. console.error( error );
  457. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  458. }
  459. } );
  460. break;
  461. }
  462. } );
  463. function init( wasmBinary ) {
  464. transcoderPending = new Promise( ( resolve ) => {
  465. BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
  466. BASIS( BasisModule ); // eslint-disable-line no-undef
  467. } ).then( () => {
  468. BasisModule.initializeBasis();
  469. if ( BasisModule.KTX2File === undefined ) {
  470. console.warn( 'THREE.KTX2Loader: Please update Basis Universal transcoder.' );
  471. }
  472. } );
  473. }
  474. function transcode( buffer ) {
  475. const ktx2File = new BasisModule.KTX2File( new Uint8Array( buffer ) );
  476. function cleanup() {
  477. ktx2File.close();
  478. ktx2File.delete();
  479. }
  480. if ( ! ktx2File.isValid() ) {
  481. cleanup();
  482. throw new Error( 'THREE.KTX2Loader: Invalid or unsupported .ktx2 file' );
  483. }
  484. let basisFormat;
  485. if ( ktx2File.isUASTC() ) {
  486. basisFormat = BasisFormat.UASTC;
  487. } else if ( ktx2File.isETC1S() ) {
  488. basisFormat = BasisFormat.ETC1S;
  489. } else if ( ktx2File.isHDR() ) {
  490. basisFormat = BasisFormat.UASTC_HDR;
  491. } else {
  492. throw new Error( 'THREE.KTX2Loader: Unknown Basis encoding' );
  493. }
  494. const width = ktx2File.getWidth();
  495. const height = ktx2File.getHeight();
  496. const layerCount = ktx2File.getLayers() || 1;
  497. const levelCount = ktx2File.getLevels();
  498. const faceCount = ktx2File.getFaces();
  499. const hasAlpha = ktx2File.getHasAlpha();
  500. const dfdFlags = ktx2File.getDFDFlags();
  501. const { transcoderFormat, engineFormat, engineType } = getTranscoderFormat( basisFormat, width, height, hasAlpha );
  502. if ( ! width || ! height || ! levelCount ) {
  503. cleanup();
  504. throw new Error( 'THREE.KTX2Loader: Invalid texture' );
  505. }
  506. if ( ! ktx2File.startTranscoding() ) {
  507. cleanup();
  508. throw new Error( 'THREE.KTX2Loader: .startTranscoding failed' );
  509. }
  510. const faces = [];
  511. const buffers = [];
  512. for ( let face = 0; face < faceCount; face ++ ) {
  513. const mipmaps = [];
  514. for ( let mip = 0; mip < levelCount; mip ++ ) {
  515. const layerMips = [];
  516. let mipWidth, mipHeight;
  517. for ( let layer = 0; layer < layerCount; layer ++ ) {
  518. const levelInfo = ktx2File.getImageLevelInfo( mip, layer, face );
  519. if ( face === 0 && mip === 0 && layer === 0 && ( levelInfo.origWidth % 4 !== 0 || levelInfo.origHeight % 4 !== 0 ) ) {
  520. console.warn( 'THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions.' );
  521. }
  522. if ( levelCount > 1 ) {
  523. mipWidth = levelInfo.origWidth;
  524. mipHeight = levelInfo.origHeight;
  525. } else {
  526. // Handles non-multiple-of-four dimensions in textures without mipmaps. Textures with
  527. // mipmaps must use multiple-of-four dimensions, for some texture formats and APIs.
  528. // See mrdoob/three.js#25908.
  529. mipWidth = levelInfo.width;
  530. mipHeight = levelInfo.height;
  531. }
  532. let dst = new Uint8Array( ktx2File.getImageTranscodedSizeInBytes( mip, layer, 0, transcoderFormat ) );
  533. const status = ktx2File.transcodeImage( dst, mip, layer, face, transcoderFormat, 0, - 1, - 1 );
  534. if ( engineType === EngineType.HalfFloatType ) {
  535. dst = new Uint16Array( dst.buffer, dst.byteOffset, dst.byteLength / Uint16Array.BYTES_PER_ELEMENT );
  536. }
  537. if ( ! status ) {
  538. cleanup();
  539. throw new Error( 'THREE.KTX2Loader: .transcodeImage failed.' );
  540. }
  541. layerMips.push( dst );
  542. }
  543. const mipData = concat( layerMips );
  544. mipmaps.push( { data: mipData, width: mipWidth, height: mipHeight } );
  545. buffers.push( mipData.buffer );
  546. }
  547. faces.push( { mipmaps, width, height, format: engineFormat, type: engineType } );
  548. }
  549. cleanup();
  550. return { faces, buffers, width, height, hasAlpha, dfdFlags, format: engineFormat, type: engineType };
  551. }
  552. //
  553. // Optimal choice of a transcoder target format depends on the Basis format (ETC1S, UASTC, or
  554. // UASTC HDR), device capabilities, and texture dimensions. The list below ranks the formats
  555. // separately for each format. Currently, priority is assigned based on:
  556. //
  557. // high quality > low quality > uncompressed
  558. //
  559. // Prioritization may be revisited, or exposed for configuration, in the future.
  560. //
  561. // Reference: https://github.com/KhronosGroup/3D-Formats-Guidelines/blob/main/KTXDeveloperGuide.md
  562. const FORMAT_OPTIONS = [
  563. {
  564. if: 'astcSupported',
  565. basisFormat: [ BasisFormat.UASTC ],
  566. transcoderFormat: [ TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4 ],
  567. engineFormat: [ EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format ],
  568. engineType: [ EngineType.UnsignedByteType ],
  569. priorityETC1S: Infinity,
  570. priorityUASTC: 1,
  571. needsPowerOfTwo: false,
  572. },
  573. {
  574. if: 'bptcSupported',
  575. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC ],
  576. transcoderFormat: [ TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5 ],
  577. engineFormat: [ EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format ],
  578. engineType: [ EngineType.UnsignedByteType ],
  579. priorityETC1S: 3,
  580. priorityUASTC: 2,
  581. needsPowerOfTwo: false,
  582. },
  583. {
  584. if: 'dxtSupported',
  585. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC ],
  586. transcoderFormat: [ TranscoderFormat.BC1, TranscoderFormat.BC3 ],
  587. engineFormat: [ EngineFormat.RGBA_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format ],
  588. engineType: [ EngineType.UnsignedByteType ],
  589. priorityETC1S: 4,
  590. priorityUASTC: 5,
  591. needsPowerOfTwo: false,
  592. },
  593. {
  594. if: 'etc2Supported',
  595. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC ],
  596. transcoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC2 ],
  597. engineFormat: [ EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format ],
  598. engineType: [ EngineType.UnsignedByteType ],
  599. priorityETC1S: 1,
  600. priorityUASTC: 3,
  601. needsPowerOfTwo: false,
  602. },
  603. {
  604. if: 'etc1Supported',
  605. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC ],
  606. transcoderFormat: [ TranscoderFormat.ETC1 ],
  607. engineFormat: [ EngineFormat.RGB_ETC1_Format ],
  608. engineType: [ EngineType.UnsignedByteType ],
  609. priorityETC1S: 2,
  610. priorityUASTC: 4,
  611. needsPowerOfTwo: false,
  612. },
  613. {
  614. if: 'pvrtcSupported',
  615. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC ],
  616. transcoderFormat: [ TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA ],
  617. engineFormat: [ EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format ],
  618. engineType: [ EngineType.UnsignedByteType ],
  619. priorityETC1S: 5,
  620. priorityUASTC: 6,
  621. needsPowerOfTwo: true,
  622. },
  623. {
  624. if: 'bptcSupported',
  625. basisFormat: [ BasisFormat.UASTC_HDR ],
  626. transcoderFormat: [ TranscoderFormat.BC6H ],
  627. engineFormat: [ EngineFormat.RGB_BPTC_UNSIGNED_Format ],
  628. engineType: [ EngineType.HalfFloatType ],
  629. priorityHDR: 1,
  630. needsPowerOfTwo: false,
  631. },
  632. // Uncompressed fallbacks.
  633. {
  634. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC ],
  635. transcoderFormat: [ TranscoderFormat.RGBA32, TranscoderFormat.RGBA32 ],
  636. engineFormat: [ EngineFormat.RGBAFormat, EngineFormat.RGBAFormat ],
  637. engineType: [ EngineType.UnsignedByteType, EngineType.UnsignedByteType ],
  638. priorityETC1S: 100,
  639. priorityUASTC: 100,
  640. needsPowerOfTwo: false,
  641. },
  642. {
  643. basisFormat: [ BasisFormat.UASTC_HDR ],
  644. transcoderFormat: [ TranscoderFormat.RGBA_HALF ],
  645. engineFormat: [ EngineFormat.RGBAFormat ],
  646. engineType: [ EngineType.HalfFloatType ],
  647. priorityHDR: 100,
  648. needsPowerOfTwo: false,
  649. }
  650. ];
  651. const OPTIONS = {
  652. [ BasisFormat.ETC1S ]: FORMAT_OPTIONS
  653. .filter( ( opt ) => opt.basisFormat.includes( BasisFormat.ETC1S ) )
  654. .sort( ( a, b ) => a.priorityETC1S - b.priorityETC1S ),
  655. [ BasisFormat.UASTC ]: FORMAT_OPTIONS
  656. .filter( ( opt ) => opt.basisFormat.includes( BasisFormat.UASTC ) )
  657. .sort( ( a, b ) => a.priorityUASTC - b.priorityUASTC ),
  658. [ BasisFormat.UASTC_HDR ]: FORMAT_OPTIONS
  659. .filter( ( opt ) => opt.basisFormat.includes( BasisFormat.UASTC_HDR ) )
  660. .sort( ( a, b ) => a.priorityHDR - b.priorityHDR ),
  661. };
  662. function getTranscoderFormat( basisFormat, width, height, hasAlpha ) {
  663. const options = OPTIONS[ basisFormat ];
  664. for ( let i = 0; i < options.length; i ++ ) {
  665. const opt = options[ i ];
  666. if ( opt.if && ! config[ opt.if ] ) continue;
  667. if ( ! opt.basisFormat.includes( basisFormat ) ) continue;
  668. if ( hasAlpha && opt.transcoderFormat.length < 2 ) continue;
  669. if ( opt.needsPowerOfTwo && ! ( isPowerOfTwo( width ) && isPowerOfTwo( height ) ) ) continue;
  670. const transcoderFormat = opt.transcoderFormat[ hasAlpha ? 1 : 0 ];
  671. const engineFormat = opt.engineFormat[ hasAlpha ? 1 : 0 ];
  672. const engineType = opt.engineType[ 0 ];
  673. return { transcoderFormat, engineFormat, engineType };
  674. }
  675. throw new Error( 'THREE.KTX2Loader: Failed to identify transcoding target.' );
  676. }
  677. function isPowerOfTwo( value ) {
  678. if ( value <= 2 ) return true;
  679. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  680. }
  681. /**
  682. * Concatenates N byte arrays.
  683. *
  684. * @param {Uint8Array[]} arrays
  685. * @return {Uint8Array}
  686. */
  687. function concat( arrays ) {
  688. if ( arrays.length === 1 ) return arrays[ 0 ];
  689. let totalByteLength = 0;
  690. for ( let i = 0; i < arrays.length; i ++ ) {
  691. const array = arrays[ i ];
  692. totalByteLength += array.byteLength;
  693. }
  694. const result = new Uint8Array( totalByteLength );
  695. let byteOffset = 0;
  696. for ( let i = 0; i < arrays.length; i ++ ) {
  697. const array = arrays[ i ];
  698. result.set( array, byteOffset );
  699. byteOffset += array.byteLength;
  700. }
  701. return result;
  702. }
  703. };
  704. // Parsing for non-Basis textures. These textures may have supercompression
  705. // like Zstd, but they do not require transcoding.
  706. const UNCOMPRESSED_FORMATS = new Set( [ RGBAFormat, RGBFormat, RGFormat, RedFormat ] );
  707. const FORMAT_MAP = {
  708. [ VK_FORMAT_R32G32B32A32_SFLOAT ]: RGBAFormat,
  709. [ VK_FORMAT_R32G32_SFLOAT ]: RGFormat,
  710. [ VK_FORMAT_R32_SFLOAT ]: RedFormat,
  711. [ VK_FORMAT_R16G16B16A16_SFLOAT ]: RGBAFormat,
  712. [ VK_FORMAT_R16G16_SFLOAT ]: RGFormat,
  713. [ VK_FORMAT_R16_SFLOAT ]: RedFormat,
  714. [ VK_FORMAT_R8G8B8A8_SRGB ]: RGBAFormat,
  715. [ VK_FORMAT_R8G8B8A8_UNORM ]: RGBAFormat,
  716. [ VK_FORMAT_R8G8_SRGB ]: RGFormat,
  717. [ VK_FORMAT_R8G8_UNORM ]: RGFormat,
  718. [ VK_FORMAT_R8_SRGB ]: RedFormat,
  719. [ VK_FORMAT_R8_UNORM ]: RedFormat,
  720. [ VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 ]: RGBFormat,
  721. [ VK_FORMAT_B10G11R11_UFLOAT_PACK32 ]: RGBFormat,
  722. [ VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK ]: RGBA_ETC2_EAC_Format,
  723. [ VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK ]: RGB_ETC2_Format,
  724. [ VK_FORMAT_EAC_R11_UNORM_BLOCK ]: R11_EAC_Format,
  725. [ VK_FORMAT_EAC_R11_SNORM_BLOCK ]: SIGNED_R11_EAC_Format,
  726. [ VK_FORMAT_EAC_R11G11_UNORM_BLOCK ]: RG11_EAC_Format,
  727. [ VK_FORMAT_EAC_R11G11_SNORM_BLOCK ]: SIGNED_RG11_EAC_Format,
  728. [ VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT ]: RGBA_ASTC_4x4_Format,
  729. [ VK_FORMAT_ASTC_4x4_SRGB_BLOCK ]: RGBA_ASTC_4x4_Format,
  730. [ VK_FORMAT_ASTC_4x4_UNORM_BLOCK ]: RGBA_ASTC_4x4_Format,
  731. [ VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT ]: RGBA_ASTC_6x6_Format,
  732. [ VK_FORMAT_ASTC_6x6_SRGB_BLOCK ]: RGBA_ASTC_6x6_Format,
  733. [ VK_FORMAT_ASTC_6x6_UNORM_BLOCK ]: RGBA_ASTC_6x6_Format,
  734. [ VK_FORMAT_BC1_RGBA_SRGB_BLOCK ]: RGBA_S3TC_DXT1_Format,
  735. [ VK_FORMAT_BC1_RGBA_UNORM_BLOCK ]: RGBA_S3TC_DXT1_Format,
  736. [ VK_FORMAT_BC1_RGB_SRGB_BLOCK ]: RGB_S3TC_DXT1_Format,
  737. [ VK_FORMAT_BC1_RGB_UNORM_BLOCK ]: RGB_S3TC_DXT1_Format,
  738. [ VK_FORMAT_BC3_SRGB_BLOCK ]: RGBA_S3TC_DXT3_Format,
  739. [ VK_FORMAT_BC3_UNORM_BLOCK ]: RGBA_S3TC_DXT3_Format,
  740. [ VK_FORMAT_BC4_SNORM_BLOCK ]: SIGNED_RED_RGTC1_Format,
  741. [ VK_FORMAT_BC4_UNORM_BLOCK ]: RED_RGTC1_Format,
  742. [ VK_FORMAT_BC5_SNORM_BLOCK ]: SIGNED_RED_GREEN_RGTC2_Format,
  743. [ VK_FORMAT_BC5_UNORM_BLOCK ]: RED_GREEN_RGTC2_Format,
  744. [ VK_FORMAT_BC7_SRGB_BLOCK ]: RGBA_BPTC_Format,
  745. [ VK_FORMAT_BC7_UNORM_BLOCK ]: RGBA_BPTC_Format,
  746. [ VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG ]: RGBA_PVRTC_4BPPV1_Format,
  747. [ VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG ]: RGBA_PVRTC_4BPPV1_Format,
  748. [ VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG ]: RGBA_PVRTC_2BPPV1_Format,
  749. [ VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG ]: RGBA_PVRTC_2BPPV1_Format,
  750. };
  751. const TYPE_MAP = {
  752. [ VK_FORMAT_R32G32B32A32_SFLOAT ]: FloatType,
  753. [ VK_FORMAT_R32G32_SFLOAT ]: FloatType,
  754. [ VK_FORMAT_R32_SFLOAT ]: FloatType,
  755. [ VK_FORMAT_R16G16B16A16_SFLOAT ]: HalfFloatType,
  756. [ VK_FORMAT_R16G16_SFLOAT ]: HalfFloatType,
  757. [ VK_FORMAT_R16_SFLOAT ]: HalfFloatType,
  758. [ VK_FORMAT_R8G8B8A8_SRGB ]: UnsignedByteType,
  759. [ VK_FORMAT_R8G8B8A8_UNORM ]: UnsignedByteType,
  760. [ VK_FORMAT_R8G8_SRGB ]: UnsignedByteType,
  761. [ VK_FORMAT_R8G8_UNORM ]: UnsignedByteType,
  762. [ VK_FORMAT_R8_SRGB ]: UnsignedByteType,
  763. [ VK_FORMAT_R8_UNORM ]: UnsignedByteType,
  764. [ VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 ]: UnsignedInt5999Type,
  765. [ VK_FORMAT_B10G11R11_UFLOAT_PACK32 ]: UnsignedInt101111Type,
  766. [ VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK ]: UnsignedByteType,
  767. [ VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK ]: UnsignedByteType,
  768. [ VK_FORMAT_EAC_R11_UNORM_BLOCK ]: UnsignedByteType,
  769. [ VK_FORMAT_EAC_R11_UNORM_BLOCK ]: UnsignedByteType,
  770. [ VK_FORMAT_EAC_R11G11_UNORM_BLOCK ]: UnsignedByteType,
  771. [ VK_FORMAT_EAC_R11G11_UNORM_BLOCK ]: UnsignedByteType,
  772. [ VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT ]: HalfFloatType,
  773. [ VK_FORMAT_ASTC_4x4_SRGB_BLOCK ]: UnsignedByteType,
  774. [ VK_FORMAT_ASTC_4x4_UNORM_BLOCK ]: UnsignedByteType,
  775. [ VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT ]: HalfFloatType,
  776. [ VK_FORMAT_ASTC_6x6_SRGB_BLOCK ]: UnsignedByteType,
  777. [ VK_FORMAT_ASTC_6x6_UNORM_BLOCK ]: UnsignedByteType,
  778. [ VK_FORMAT_BC1_RGBA_SRGB_BLOCK ]: UnsignedByteType,
  779. [ VK_FORMAT_BC1_RGBA_UNORM_BLOCK ]: UnsignedByteType,
  780. [ VK_FORMAT_BC1_RGB_SRGB_BLOCK ]: UnsignedByteType,
  781. [ VK_FORMAT_BC1_RGB_UNORM_BLOCK ]: UnsignedByteType,
  782. [ VK_FORMAT_BC3_SRGB_BLOCK ]: UnsignedByteType,
  783. [ VK_FORMAT_BC3_UNORM_BLOCK ]: UnsignedByteType,
  784. [ VK_FORMAT_BC4_SNORM_BLOCK ]: UnsignedByteType,
  785. [ VK_FORMAT_BC4_UNORM_BLOCK ]: UnsignedByteType,
  786. [ VK_FORMAT_BC5_SNORM_BLOCK ]: UnsignedByteType,
  787. [ VK_FORMAT_BC5_UNORM_BLOCK ]: UnsignedByteType,
  788. [ VK_FORMAT_BC7_SRGB_BLOCK ]: UnsignedByteType,
  789. [ VK_FORMAT_BC7_UNORM_BLOCK ]: UnsignedByteType,
  790. [ VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG ]: UnsignedByteType,
  791. [ VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG ]: UnsignedByteType,
  792. [ VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG ]: UnsignedByteType,
  793. [ VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG ]: UnsignedByteType,
  794. };
  795. async function createRawTexture( container ) {
  796. const { vkFormat } = container;
  797. if ( FORMAT_MAP[ vkFormat ] === undefined ) {
  798. throw new Error( 'THREE.KTX2Loader: Unsupported vkFormat: ' + vkFormat );
  799. }
  800. // TODO: Merge the TYPE_MAP warning into the thrown error above, after r190.
  801. if ( TYPE_MAP[ vkFormat ] === undefined ) {
  802. console.warn( 'THREE.KTX2Loader: Missing ".type" for vkFormat: ' + vkFormat );
  803. }
  804. //
  805. let zstd;
  806. if ( container.supercompressionScheme === KHR_SUPERCOMPRESSION_ZSTD ) {
  807. if ( ! _zstd ) {
  808. _zstd = new Promise( async ( resolve ) => {
  809. const zstd = new ZSTDDecoder();
  810. await zstd.init();
  811. resolve( zstd );
  812. } );
  813. }
  814. zstd = await _zstd;
  815. }
  816. //
  817. const mipmaps = [];
  818. for ( let levelIndex = 0; levelIndex < container.levels.length; levelIndex ++ ) {
  819. const levelWidth = Math.max( 1, container.pixelWidth >> levelIndex );
  820. const levelHeight = Math.max( 1, container.pixelHeight >> levelIndex );
  821. const levelDepth = container.pixelDepth ? Math.max( 1, container.pixelDepth >> levelIndex ) : 0;
  822. const level = container.levels[ levelIndex ];
  823. let levelData;
  824. if ( container.supercompressionScheme === KHR_SUPERCOMPRESSION_NONE ) {
  825. levelData = level.levelData;
  826. } else if ( container.supercompressionScheme === KHR_SUPERCOMPRESSION_ZSTD ) {
  827. levelData = zstd.decode( level.levelData, level.uncompressedByteLength );
  828. } else {
  829. throw new Error( 'THREE.KTX2Loader: Unsupported supercompressionScheme.' );
  830. }
  831. let data;
  832. if ( TYPE_MAP[ vkFormat ] === FloatType ) {
  833. data = new Float32Array(
  834. levelData.buffer,
  835. levelData.byteOffset,
  836. levelData.byteLength / Float32Array.BYTES_PER_ELEMENT
  837. );
  838. } else if ( TYPE_MAP[ vkFormat ] === HalfFloatType ) {
  839. data = new Uint16Array(
  840. levelData.buffer,
  841. levelData.byteOffset,
  842. levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT
  843. );
  844. } else if ( TYPE_MAP[ vkFormat ] === UnsignedInt5999Type || TYPE_MAP[ vkFormat ] === UnsignedInt101111Type ) {
  845. data = new Uint32Array(
  846. levelData.buffer,
  847. levelData.byteOffset,
  848. levelData.byteLength / Uint32Array.BYTES_PER_ELEMENT
  849. );
  850. } else {
  851. data = levelData;
  852. }
  853. mipmaps.push( {
  854. data: data,
  855. width: levelWidth,
  856. height: levelHeight,
  857. depth: levelDepth,
  858. } );
  859. }
  860. // levelCount = 0 implies runtime-generated mipmaps.
  861. const useMipmaps = container.levelCount === 0 || mipmaps.length > 1;
  862. let texture;
  863. if ( UNCOMPRESSED_FORMATS.has( FORMAT_MAP[ vkFormat ] ) ) {
  864. texture = container.pixelDepth === 0
  865. ? new DataTexture( mipmaps[ 0 ].data, container.pixelWidth, container.pixelHeight )
  866. : new Data3DTexture( mipmaps[ 0 ].data, container.pixelWidth, container.pixelHeight, container.pixelDepth );
  867. texture.minFilter = useMipmaps ? NearestMipmapNearestFilter : NearestFilter;
  868. texture.magFilter = NearestFilter;
  869. texture.generateMipmaps = container.levelCount === 0;
  870. } else {
  871. if ( container.pixelDepth > 0 ) throw new Error( 'THREE.KTX2Loader: Unsupported pixelDepth.' );
  872. texture = new CompressedTexture( mipmaps, container.pixelWidth, container.pixelHeight );
  873. texture.minFilter = useMipmaps ? LinearMipmapLinearFilter : LinearFilter;
  874. texture.magFilter = LinearFilter;
  875. }
  876. texture.mipmaps = mipmaps;
  877. texture.type = TYPE_MAP[ vkFormat ];
  878. texture.format = FORMAT_MAP[ vkFormat ];
  879. texture.colorSpace = parseColorSpace( container );
  880. texture.needsUpdate = true;
  881. //
  882. return Promise.resolve( texture );
  883. }
  884. function parseColorSpace( container ) {
  885. const dfd = container.dataFormatDescriptor[ 0 ];
  886. if ( dfd.colorPrimaries === KHR_DF_PRIMARIES_BT709 ) {
  887. return dfd.transferFunction === KHR_DF_TRANSFER_SRGB ? SRGBColorSpace : LinearSRGBColorSpace;
  888. } else if ( dfd.colorPrimaries === KHR_DF_PRIMARIES_DISPLAYP3 ) {
  889. return dfd.transferFunction === KHR_DF_TRANSFER_SRGB ? DisplayP3ColorSpace : LinearDisplayP3ColorSpace;
  890. } else if ( dfd.colorPrimaries === KHR_DF_PRIMARIES_UNSPECIFIED ) {
  891. return NoColorSpace;
  892. } else {
  893. console.warn( `THREE.KTX2Loader: Unsupported color primaries, "${ dfd.colorPrimaries }"` );
  894. return NoColorSpace;
  895. }
  896. }
  897. export { KTX2Loader };
粤ICP备19079148号