KTX2Loader.js 21 KB

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