KTX2Loader.js 21 KB

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