KTX2Loader.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  1. /**
  2. * Loader for KTX 2.0 GPU Texture containers.
  3. *
  4. * KTX 2.0 is a container format for various GPU texture formats. The loader
  5. * supports Basis Universal GPU textures, which can be quickly transcoded to
  6. * a wide variety of GPU texture compression formats, as well as some
  7. * uncompressed DataTexture and Data3DTexture formats.
  8. *
  9. * References:
  10. * - KTX: http://github.khronos.org/KTX-Specification/
  11. * - DFD: https://www.khronos.org/registry/DataFormat/specs/1.3/dataformat.1.3.html#basicdescriptor
  12. */
  13. import {
  14. CompressedTexture,
  15. CompressedArrayTexture,
  16. CompressedCubeTexture,
  17. Data3DTexture,
  18. DataTexture,
  19. DisplayP3ColorSpace,
  20. FileLoader,
  21. FloatType,
  22. HalfFloatType,
  23. NoColorSpace,
  24. LinearFilter,
  25. LinearMipmapLinearFilter,
  26. LinearDisplayP3ColorSpace,
  27. LinearSRGBColorSpace,
  28. Loader,
  29. RedFormat,
  30. RGB_ETC1_Format,
  31. RGB_ETC2_Format,
  32. RGB_PVRTC_4BPPV1_Format,
  33. RGB_S3TC_DXT1_Format,
  34. RGBA_ASTC_4x4_Format,
  35. RGBA_ASTC_6x6_Format,
  36. RGBA_BPTC_Format,
  37. RGBA_ETC2_EAC_Format,
  38. RGBA_PVRTC_4BPPV1_Format,
  39. RGBA_S3TC_DXT5_Format,
  40. RGBAFormat,
  41. RGFormat,
  42. SRGBColorSpace,
  43. UnsignedByteType,
  44. } from 'three';
  45. import { WorkerPool } from '../utils/WorkerPool.js';
  46. import {
  47. read,
  48. KHR_DF_FLAG_ALPHA_PREMULTIPLIED,
  49. KHR_DF_TRANSFER_SRGB,
  50. KHR_SUPERCOMPRESSION_NONE,
  51. KHR_SUPERCOMPRESSION_ZSTD,
  52. VK_FORMAT_UNDEFINED,
  53. VK_FORMAT_R16_SFLOAT,
  54. VK_FORMAT_R16G16_SFLOAT,
  55. VK_FORMAT_R16G16B16A16_SFLOAT,
  56. VK_FORMAT_R32_SFLOAT,
  57. VK_FORMAT_R32G32_SFLOAT,
  58. VK_FORMAT_R32G32B32A32_SFLOAT,
  59. VK_FORMAT_R8_SRGB,
  60. VK_FORMAT_R8_UNORM,
  61. VK_FORMAT_R8G8_SRGB,
  62. VK_FORMAT_R8G8_UNORM,
  63. VK_FORMAT_R8G8B8A8_SRGB,
  64. VK_FORMAT_R8G8B8A8_UNORM,
  65. VK_FORMAT_ASTC_6x6_SRGB_BLOCK,
  66. VK_FORMAT_ASTC_6x6_UNORM_BLOCK,
  67. KHR_DF_PRIMARIES_UNSPECIFIED,
  68. KHR_DF_PRIMARIES_BT709,
  69. KHR_DF_PRIMARIES_DISPLAYP3
  70. } from '../libs/ktx-parse.module.js';
  71. import { ZSTDDecoder } from '../libs/zstddec.module.js';
  72. const _taskCache = new WeakMap();
  73. let _activeLoaders = 0;
  74. let _zstd;
  75. class KTX2Loader extends Loader {
  76. constructor( manager ) {
  77. super( manager );
  78. this.transcoderPath = '';
  79. this.transcoderBinary = null;
  80. this.transcoderPending = null;
  81. this.workerPool = new WorkerPool();
  82. this.workerSourceURL = '';
  83. this.workerConfig = null;
  84. if ( typeof MSC_TRANSCODER !== 'undefined' ) {
  85. console.warn(
  86. 'THREE.KTX2Loader: Please update to latest "basis_transcoder".'
  87. + ' "msc_basis_transcoder" is no longer supported in three.js r125+.'
  88. );
  89. }
  90. }
  91. setTranscoderPath( path ) {
  92. this.transcoderPath = path;
  93. return this;
  94. }
  95. setWorkerLimit( num ) {
  96. this.workerPool.setWorkerLimit( num );
  97. return this;
  98. }
  99. detectSupport( renderer ) {
  100. if ( renderer.isWebGPURenderer === true ) {
  101. this.workerConfig = {
  102. astcSupported: renderer.hasFeature( 'texture-compression-astc' ),
  103. etc1Supported: false,
  104. etc2Supported: renderer.hasFeature( 'texture-compression-etc2' ),
  105. dxtSupported: renderer.hasFeature( 'texture-compression-bc' ),
  106. bptcSupported: false,
  107. pvrtcSupported: false
  108. };
  109. } else {
  110. this.workerConfig = {
  111. astcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_astc' ),
  112. etc1Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc1' ),
  113. etc2Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc' ),
  114. dxtSupported: renderer.extensions.has( 'WEBGL_compressed_texture_s3tc' ),
  115. bptcSupported: renderer.extensions.has( 'EXT_texture_compression_bptc' ),
  116. pvrtcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_pvrtc' )
  117. || renderer.extensions.has( 'WEBKIT_WEBGL_compressed_texture_pvrtc' )
  118. };
  119. if ( renderer.capabilities.isWebGL2 ) {
  120. // https://github.com/mrdoob/three.js/pull/22928
  121. this.workerConfig.etc1Supported = false;
  122. }
  123. }
  124. return this;
  125. }
  126. init() {
  127. if ( ! this.transcoderPending ) {
  128. // Load transcoder wrapper.
  129. const jsLoader = new FileLoader( this.manager );
  130. jsLoader.setPath( this.transcoderPath );
  131. jsLoader.setWithCredentials( this.withCredentials );
  132. const jsContent = jsLoader.loadAsync( 'basis_transcoder.js' );
  133. // Load transcoder WASM binary.
  134. const binaryLoader = new FileLoader( this.manager );
  135. binaryLoader.setPath( this.transcoderPath );
  136. binaryLoader.setResponseType( 'arraybuffer' );
  137. binaryLoader.setWithCredentials( this.withCredentials );
  138. const binaryContent = binaryLoader.loadAsync( 'basis_transcoder.wasm' );
  139. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] )
  140. .then( ( [ jsContent, binaryContent ] ) => {
  141. const fn = KTX2Loader.BasisWorker.toString();
  142. const body = [
  143. '/* constants */',
  144. 'let _EngineFormat = ' + JSON.stringify( KTX2Loader.EngineFormat ),
  145. 'let _TranscoderFormat = ' + JSON.stringify( KTX2Loader.TranscoderFormat ),
  146. 'let _BasisFormat = ' + JSON.stringify( KTX2Loader.BasisFormat ),
  147. '/* basis_transcoder.js */',
  148. jsContent,
  149. '/* worker */',
  150. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  151. ].join( '\n' );
  152. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  153. this.transcoderBinary = binaryContent;
  154. this.workerPool.setWorkerCreator( () => {
  155. const worker = new Worker( this.workerSourceURL );
  156. const transcoderBinary = this.transcoderBinary.slice( 0 );
  157. worker.postMessage( { type: 'init', config: this.workerConfig, transcoderBinary }, [ transcoderBinary ] );
  158. return worker;
  159. } );
  160. } );
  161. if ( _activeLoaders > 0 ) {
  162. // Each instance loads a transcoder and allocates workers, increasing network and memory cost.
  163. console.warn(
  164. 'THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues.'
  165. + ' Use a single KTX2Loader instance, or call .dispose() on old instances.'
  166. );
  167. }
  168. _activeLoaders ++;
  169. }
  170. return this.transcoderPending;
  171. }
  172. load( url, onLoad, onProgress, onError ) {
  173. if ( this.workerConfig === null ) {
  174. throw new Error( 'THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.' );
  175. }
  176. const loader = new FileLoader( this.manager );
  177. loader.setResponseType( 'arraybuffer' );
  178. loader.setWithCredentials( this.withCredentials );
  179. loader.load( url, ( buffer ) => {
  180. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  181. // again from this thread.
  182. if ( _taskCache.has( buffer ) ) {
  183. const cachedTask = _taskCache.get( buffer );
  184. return cachedTask.promise.then( onLoad ).catch( onError );
  185. }
  186. this._createTexture( buffer )
  187. .then( ( texture ) => onLoad ? onLoad( texture ) : null )
  188. .catch( onError );
  189. }, onProgress, onError );
  190. }
  191. _createTextureFrom( transcodeResult, container ) {
  192. const { faces, width, height, format, type, error, dfdFlags } = transcodeResult;
  193. if ( type === 'error' ) return Promise.reject( error );
  194. let texture;
  195. if ( container.faceCount === 6 ) {
  196. texture = new CompressedCubeTexture( faces, format, UnsignedByteType );
  197. } else {
  198. const mipmaps = faces[ 0 ].mipmaps;
  199. texture = container.layerCount > 1
  200. ? new CompressedArrayTexture( mipmaps, width, height, container.layerCount, format, UnsignedByteType )
  201. : new CompressedTexture( mipmaps, width, height, format, UnsignedByteType );
  202. }
  203. texture.minFilter = faces[ 0 ].mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter;
  204. texture.magFilter = LinearFilter;
  205. texture.generateMipmaps = false;
  206. texture.needsUpdate = true;
  207. texture.colorSpace = parseColorSpace( container );
  208. texture.premultiplyAlpha = !! ( dfdFlags & KHR_DF_FLAG_ALPHA_PREMULTIPLIED );
  209. return texture;
  210. }
  211. /**
  212. * @param {ArrayBuffer} buffer
  213. * @param {object?} config
  214. * @return {Promise<CompressedTexture|CompressedArrayTexture|DataTexture|Data3DTexture>}
  215. */
  216. async _createTexture( buffer, config = {} ) {
  217. const container = read( new Uint8Array( buffer ) );
  218. if ( container.vkFormat !== VK_FORMAT_UNDEFINED ) {
  219. return createRawTexture( container );
  220. }
  221. //
  222. const taskConfig = config;
  223. const texturePending = this.init().then( () => {
  224. return this.workerPool.postMessage( { type: 'transcode', buffer, taskConfig: taskConfig }, [ buffer ] );
  225. } ).then( ( e ) => this._createTextureFrom( e.data, container ) );
  226. // Cache the task result.
  227. _taskCache.set( buffer, { promise: texturePending } );
  228. return texturePending;
  229. }
  230. dispose() {
  231. this.workerPool.dispose();
  232. if ( this.workerSourceURL ) URL.revokeObjectURL( this.workerSourceURL );
  233. _activeLoaders --;
  234. return this;
  235. }
  236. }
  237. /* CONSTANTS */
  238. KTX2Loader.BasisFormat = {
  239. ETC1S: 0,
  240. UASTC_4x4: 1,
  241. };
  242. KTX2Loader.TranscoderFormat = {
  243. ETC1: 0,
  244. ETC2: 1,
  245. BC1: 2,
  246. BC3: 3,
  247. BC4: 4,
  248. BC5: 5,
  249. BC7_M6_OPAQUE_ONLY: 6,
  250. BC7_M5: 7,
  251. PVRTC1_4_RGB: 8,
  252. PVRTC1_4_RGBA: 9,
  253. ASTC_4x4: 10,
  254. ATC_RGB: 11,
  255. ATC_RGBA_INTERPOLATED_ALPHA: 12,
  256. RGBA32: 13,
  257. RGB565: 14,
  258. BGR565: 15,
  259. RGBA4444: 16,
  260. };
  261. KTX2Loader.EngineFormat = {
  262. RGBAFormat: RGBAFormat,
  263. RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
  264. RGBA_BPTC_Format: RGBA_BPTC_Format,
  265. RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
  266. RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
  267. RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format,
  268. RGB_ETC1_Format: RGB_ETC1_Format,
  269. RGB_ETC2_Format: RGB_ETC2_Format,
  270. RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
  271. RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format,
  272. };
  273. /* WEB WORKER */
  274. KTX2Loader.BasisWorker = function () {
  275. let config;
  276. let transcoderPending;
  277. let BasisModule;
  278. const EngineFormat = _EngineFormat; // eslint-disable-line no-undef
  279. const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef
  280. const BasisFormat = _BasisFormat; // eslint-disable-line no-undef
  281. self.addEventListener( 'message', function ( e ) {
  282. const message = e.data;
  283. switch ( message.type ) {
  284. case 'init':
  285. config = message.config;
  286. init( message.transcoderBinary );
  287. break;
  288. case 'transcode':
  289. transcoderPending.then( () => {
  290. try {
  291. const { faces, buffers, width, height, hasAlpha, format, dfdFlags } = transcode( message.buffer );
  292. self.postMessage( { type: 'transcode', id: message.id, faces, width, height, hasAlpha, format, dfdFlags }, buffers );
  293. } catch ( error ) {
  294. console.error( error );
  295. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  296. }
  297. } );
  298. break;
  299. }
  300. } );
  301. function init( wasmBinary ) {
  302. transcoderPending = new Promise( ( resolve ) => {
  303. BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
  304. BASIS( BasisModule ); // eslint-disable-line no-undef
  305. } ).then( () => {
  306. BasisModule.initializeBasis();
  307. if ( BasisModule.KTX2File === undefined ) {
  308. console.warn( 'THREE.KTX2Loader: Please update Basis Universal transcoder.' );
  309. }
  310. } );
  311. }
  312. function transcode( buffer ) {
  313. const ktx2File = new BasisModule.KTX2File( new Uint8Array( buffer ) );
  314. function cleanup() {
  315. ktx2File.close();
  316. ktx2File.delete();
  317. }
  318. if ( ! ktx2File.isValid() ) {
  319. cleanup();
  320. throw new Error( 'THREE.KTX2Loader: Invalid or unsupported .ktx2 file' );
  321. }
  322. const basisFormat = ktx2File.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S;
  323. const width = ktx2File.getWidth();
  324. const height = ktx2File.getHeight();
  325. const layerCount = ktx2File.getLayers() || 1;
  326. const levelCount = ktx2File.getLevels();
  327. const faceCount = ktx2File.getFaces();
  328. const hasAlpha = ktx2File.getHasAlpha();
  329. const dfdFlags = ktx2File.getDFDFlags();
  330. const { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha );
  331. if ( ! width || ! height || ! levelCount ) {
  332. cleanup();
  333. throw new Error( 'THREE.KTX2Loader: Invalid texture' );
  334. }
  335. if ( ! ktx2File.startTranscoding() ) {
  336. cleanup();
  337. throw new Error( 'THREE.KTX2Loader: .startTranscoding failed' );
  338. }
  339. const faces = [];
  340. const buffers = [];
  341. for ( let face = 0; face < faceCount; face ++ ) {
  342. const mipmaps = [];
  343. for ( let mip = 0; mip < levelCount; mip ++ ) {
  344. const layerMips = [];
  345. let mipWidth, mipHeight;
  346. for ( let layer = 0; layer < layerCount; layer ++ ) {
  347. const levelInfo = ktx2File.getImageLevelInfo( mip, layer, face );
  348. if ( face === 0 && mip === 0 && layer === 0 && ( levelInfo.origWidth % 4 !== 0 || levelInfo.origHeight % 4 !== 0 ) ) {
  349. console.warn( 'THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions.' );
  350. }
  351. if ( levelCount > 1 ) {
  352. mipWidth = levelInfo.origWidth;
  353. mipHeight = levelInfo.origHeight;
  354. } else {
  355. // Handles non-multiple-of-four dimensions in textures without mipmaps. Textures with
  356. // mipmaps must use multiple-of-four dimensions, for some texture formats and APIs.
  357. // See mrdoob/three.js#25908.
  358. mipWidth = levelInfo.width;
  359. mipHeight = levelInfo.height;
  360. }
  361. const dst = new Uint8Array( ktx2File.getImageTranscodedSizeInBytes( mip, layer, 0, transcoderFormat ) );
  362. const status = ktx2File.transcodeImage( dst, mip, layer, face, transcoderFormat, 0, - 1, - 1 );
  363. if ( ! status ) {
  364. cleanup();
  365. throw new Error( 'THREE.KTX2Loader: .transcodeImage failed.' );
  366. }
  367. layerMips.push( dst );
  368. }
  369. const mipData = concat( layerMips );
  370. mipmaps.push( { data: mipData, width: mipWidth, height: mipHeight } );
  371. buffers.push( mipData.buffer );
  372. }
  373. faces.push( { mipmaps, width, height, format: engineFormat } );
  374. }
  375. cleanup();
  376. return { faces, buffers, width, height, hasAlpha, format: engineFormat, dfdFlags };
  377. }
  378. //
  379. // Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC),
  380. // device capabilities, and texture dimensions. The list below ranks the formats separately
  381. // for ETC1S and UASTC.
  382. //
  383. // In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at
  384. // significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently
  385. // chooses RGBA32 only as a last resort and does not expose that option to the caller.
  386. const FORMAT_OPTIONS = [
  387. {
  388. if: 'astcSupported',
  389. basisFormat: [ BasisFormat.UASTC_4x4 ],
  390. transcoderFormat: [ TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4 ],
  391. engineFormat: [ EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format ],
  392. priorityETC1S: Infinity,
  393. priorityUASTC: 1,
  394. needsPowerOfTwo: false,
  395. },
  396. {
  397. if: 'bptcSupported',
  398. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  399. transcoderFormat: [ TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5 ],
  400. engineFormat: [ EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format ],
  401. priorityETC1S: 3,
  402. priorityUASTC: 2,
  403. needsPowerOfTwo: false,
  404. },
  405. {
  406. if: 'dxtSupported',
  407. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  408. transcoderFormat: [ TranscoderFormat.BC1, TranscoderFormat.BC3 ],
  409. engineFormat: [ EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format ],
  410. priorityETC1S: 4,
  411. priorityUASTC: 5,
  412. needsPowerOfTwo: false,
  413. },
  414. {
  415. if: 'etc2Supported',
  416. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  417. transcoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC2 ],
  418. engineFormat: [ EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format ],
  419. priorityETC1S: 1,
  420. priorityUASTC: 3,
  421. needsPowerOfTwo: false,
  422. },
  423. {
  424. if: 'etc1Supported',
  425. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  426. transcoderFormat: [ TranscoderFormat.ETC1 ],
  427. engineFormat: [ EngineFormat.RGB_ETC1_Format ],
  428. priorityETC1S: 2,
  429. priorityUASTC: 4,
  430. needsPowerOfTwo: false,
  431. },
  432. {
  433. if: 'pvrtcSupported',
  434. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  435. transcoderFormat: [ TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA ],
  436. engineFormat: [ EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format ],
  437. priorityETC1S: 5,
  438. priorityUASTC: 6,
  439. needsPowerOfTwo: true,
  440. },
  441. ];
  442. const ETC1S_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  443. return a.priorityETC1S - b.priorityETC1S;
  444. } );
  445. const UASTC_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  446. return a.priorityUASTC - b.priorityUASTC;
  447. } );
  448. function getTranscoderFormat( basisFormat, width, height, hasAlpha ) {
  449. let transcoderFormat;
  450. let engineFormat;
  451. const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS;
  452. for ( let i = 0; i < options.length; i ++ ) {
  453. const opt = options[ i ];
  454. if ( ! config[ opt.if ] ) continue;
  455. if ( ! opt.basisFormat.includes( basisFormat ) ) continue;
  456. if ( hasAlpha && opt.transcoderFormat.length < 2 ) continue;
  457. if ( opt.needsPowerOfTwo && ! ( isPowerOfTwo( width ) && isPowerOfTwo( height ) ) ) continue;
  458. transcoderFormat = opt.transcoderFormat[ hasAlpha ? 1 : 0 ];
  459. engineFormat = opt.engineFormat[ hasAlpha ? 1 : 0 ];
  460. return { transcoderFormat, engineFormat };
  461. }
  462. console.warn( 'THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32.' );
  463. transcoderFormat = TranscoderFormat.RGBA32;
  464. engineFormat = EngineFormat.RGBAFormat;
  465. return { transcoderFormat, engineFormat };
  466. }
  467. function isPowerOfTwo( value ) {
  468. if ( value <= 2 ) return true;
  469. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  470. }
  471. /** Concatenates N byte arrays. */
  472. function concat( arrays ) {
  473. if ( arrays.length === 1 ) return arrays[ 0 ];
  474. let totalByteLength = 0;
  475. for ( let i = 0; i < arrays.length; i ++ ) {
  476. const array = arrays[ i ];
  477. totalByteLength += array.byteLength;
  478. }
  479. const result = new Uint8Array( totalByteLength );
  480. let byteOffset = 0;
  481. for ( let i = 0; i < arrays.length; i ++ ) {
  482. const array = arrays[ i ];
  483. result.set( array, byteOffset );
  484. byteOffset += array.byteLength;
  485. }
  486. return result;
  487. }
  488. };
  489. //
  490. // Parsing for non-Basis textures. These textures are may have supercompression
  491. // like Zstd, but they do not require transcoding.
  492. const UNCOMPRESSED_FORMATS = new Set( [ RGBAFormat, RGFormat, RedFormat ] );
  493. const FORMAT_MAP = {
  494. [ VK_FORMAT_R32G32B32A32_SFLOAT ]: RGBAFormat,
  495. [ VK_FORMAT_R16G16B16A16_SFLOAT ]: RGBAFormat,
  496. [ VK_FORMAT_R8G8B8A8_UNORM ]: RGBAFormat,
  497. [ VK_FORMAT_R8G8B8A8_SRGB ]: RGBAFormat,
  498. [ VK_FORMAT_R32G32_SFLOAT ]: RGFormat,
  499. [ VK_FORMAT_R16G16_SFLOAT ]: RGFormat,
  500. [ VK_FORMAT_R8G8_UNORM ]: RGFormat,
  501. [ VK_FORMAT_R8G8_SRGB ]: RGFormat,
  502. [ VK_FORMAT_R32_SFLOAT ]: RedFormat,
  503. [ VK_FORMAT_R16_SFLOAT ]: RedFormat,
  504. [ VK_FORMAT_R8_SRGB ]: RedFormat,
  505. [ VK_FORMAT_R8_UNORM ]: RedFormat,
  506. [ VK_FORMAT_ASTC_6x6_SRGB_BLOCK ]: RGBA_ASTC_6x6_Format,
  507. [ VK_FORMAT_ASTC_6x6_UNORM_BLOCK ]: RGBA_ASTC_6x6_Format,
  508. };
  509. const TYPE_MAP = {
  510. [ VK_FORMAT_R32G32B32A32_SFLOAT ]: FloatType,
  511. [ VK_FORMAT_R16G16B16A16_SFLOAT ]: HalfFloatType,
  512. [ VK_FORMAT_R8G8B8A8_UNORM ]: UnsignedByteType,
  513. [ VK_FORMAT_R8G8B8A8_SRGB ]: UnsignedByteType,
  514. [ VK_FORMAT_R32G32_SFLOAT ]: FloatType,
  515. [ VK_FORMAT_R16G16_SFLOAT ]: HalfFloatType,
  516. [ VK_FORMAT_R8G8_UNORM ]: UnsignedByteType,
  517. [ VK_FORMAT_R8G8_SRGB ]: UnsignedByteType,
  518. [ VK_FORMAT_R32_SFLOAT ]: FloatType,
  519. [ VK_FORMAT_R16_SFLOAT ]: HalfFloatType,
  520. [ VK_FORMAT_R8_SRGB ]: UnsignedByteType,
  521. [ VK_FORMAT_R8_UNORM ]: UnsignedByteType,
  522. [ VK_FORMAT_ASTC_6x6_SRGB_BLOCK ]: UnsignedByteType,
  523. [ VK_FORMAT_ASTC_6x6_UNORM_BLOCK ]: UnsignedByteType,
  524. };
  525. async function createRawTexture( container ) {
  526. const { vkFormat } = container;
  527. if ( FORMAT_MAP[ vkFormat ] === undefined ) {
  528. throw new Error( 'THREE.KTX2Loader: Unsupported vkFormat.' );
  529. }
  530. //
  531. let zstd;
  532. if ( container.supercompressionScheme === KHR_SUPERCOMPRESSION_ZSTD ) {
  533. if ( ! _zstd ) {
  534. _zstd = new Promise( async ( resolve ) => {
  535. const zstd = new ZSTDDecoder();
  536. await zstd.init();
  537. resolve( zstd );
  538. } );
  539. }
  540. zstd = await _zstd;
  541. }
  542. //
  543. const mipmaps = [];
  544. for ( let levelIndex = 0; levelIndex < container.levels.length; levelIndex ++ ) {
  545. const levelWidth = Math.max( 1, container.pixelWidth >> levelIndex );
  546. const levelHeight = Math.max( 1, container.pixelHeight >> levelIndex );
  547. const levelDepth = container.pixelDepth ? Math.max( 1, container.pixelDepth >> levelIndex ) : 0;
  548. const level = container.levels[ levelIndex ];
  549. let levelData;
  550. if ( container.supercompressionScheme === KHR_SUPERCOMPRESSION_NONE ) {
  551. levelData = level.levelData;
  552. } else if ( container.supercompressionScheme === KHR_SUPERCOMPRESSION_ZSTD ) {
  553. levelData = zstd.decode( level.levelData, level.uncompressedByteLength );
  554. } else {
  555. throw new Error( 'THREE.KTX2Loader: Unsupported supercompressionScheme.' );
  556. }
  557. let data;
  558. if ( TYPE_MAP[ vkFormat ] === FloatType ) {
  559. data = new Float32Array(
  560. levelData.buffer,
  561. levelData.byteOffset,
  562. levelData.byteLength / Float32Array.BYTES_PER_ELEMENT
  563. );
  564. } else if ( TYPE_MAP[ vkFormat ] === HalfFloatType ) {
  565. data = new Uint16Array(
  566. levelData.buffer,
  567. levelData.byteOffset,
  568. levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT
  569. );
  570. } else {
  571. data = levelData;
  572. }
  573. mipmaps.push( {
  574. data: data,
  575. width: levelWidth,
  576. height: levelHeight,
  577. depth: levelDepth,
  578. } );
  579. }
  580. let texture;
  581. if ( UNCOMPRESSED_FORMATS.has( FORMAT_MAP[ vkFormat ] ) ) {
  582. texture = container.pixelDepth === 0
  583. ? new DataTexture( mipmaps[ 0 ].data, container.pixelWidth, container.pixelHeight )
  584. : new Data3DTexture( mipmaps[ 0 ].data, container.pixelWidth, container.pixelHeight, container.pixelDepth );
  585. } else {
  586. if ( container.pixelDepth > 0 ) throw new Error( 'THREE.KTX2Loader: Unsupported pixelDepth.' );
  587. texture = new CompressedTexture( mipmaps, container.pixelWidth, container.pixelHeight );
  588. }
  589. texture.mipmaps = mipmaps;
  590. texture.type = TYPE_MAP[ vkFormat ];
  591. texture.format = FORMAT_MAP[ vkFormat ];
  592. texture.colorSpace = parseColorSpace( container );
  593. texture.needsUpdate = true;
  594. //
  595. return Promise.resolve( texture );
  596. }
  597. function parseColorSpace( container ) {
  598. const dfd = container.dataFormatDescriptor[ 0 ];
  599. if ( dfd.colorPrimaries === KHR_DF_PRIMARIES_BT709 ) {
  600. return dfd.transferFunction === KHR_DF_TRANSFER_SRGB ? SRGBColorSpace : LinearSRGBColorSpace;
  601. } else if ( dfd.colorPrimaries === KHR_DF_PRIMARIES_DISPLAYP3 ) {
  602. return dfd.transferFunction === KHR_DF_TRANSFER_SRGB ? DisplayP3ColorSpace : LinearDisplayP3ColorSpace;
  603. } else if ( dfd.colorPrimaries === KHR_DF_PRIMARIES_UNSPECIFIED ) {
  604. return NoColorSpace;
  605. } else {
  606. console.warn( `THREE.KTX2Loader: Unsupported color primaries, "${ dfd.colorPrimaries }"` );
  607. return NoColorSpace;
  608. }
  609. }
  610. export { KTX2Loader };