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. 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. if ( face === 0 && mip === 0 && layer === 0 && ( levelInfo.origWidth % 4 !== 0 || levelInfo.origHeight % 4 !== 0 ) ) {
  361. console.warn( 'THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions.' );
  362. }
  363. if ( levelCount > 1 ) {
  364. mipWidth = levelInfo.origWidth;
  365. mipHeight = levelInfo.origHeight;
  366. } else {
  367. // Handles non-multiple-of-four dimensions in textures without mipmaps. Textures with
  368. // mipmaps must use multiple-of-four dimensions, for some texture formats and APIs.
  369. // See mrdoob/three.js#25908.
  370. mipWidth = levelInfo.width;
  371. mipHeight = levelInfo.height;
  372. }
  373. const dst = new Uint8Array( ktx2File.getImageTranscodedSizeInBytes( mip, layer, 0, transcoderFormat ) );
  374. const status = ktx2File.transcodeImage( dst, mip, layer, face, transcoderFormat, 0, - 1, - 1 );
  375. if ( ! status ) {
  376. cleanup();
  377. throw new Error( 'THREE.KTX2Loader: .transcodeImage failed.' );
  378. }
  379. layerMips.push( dst );
  380. }
  381. const mipData = concat( layerMips );
  382. mipmaps.push( { data: mipData, width: mipWidth, height: mipHeight } );
  383. buffers.push( mipData.buffer );
  384. }
  385. faces.push( { mipmaps, width, height, format: engineFormat } );
  386. }
  387. cleanup();
  388. return { faces, buffers, width, height, hasAlpha, format: engineFormat, dfdTransferFn, dfdFlags };
  389. }
  390. //
  391. // Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC),
  392. // device capabilities, and texture dimensions. The list below ranks the formats separately
  393. // for ETC1S and UASTC.
  394. //
  395. // In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at
  396. // significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently
  397. // chooses RGBA32 only as a last resort and does not expose that option to the caller.
  398. const FORMAT_OPTIONS = [
  399. {
  400. if: 'astcSupported',
  401. basisFormat: [ BasisFormat.UASTC_4x4 ],
  402. transcoderFormat: [ TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4 ],
  403. engineFormat: [ EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format ],
  404. priorityETC1S: Infinity,
  405. priorityUASTC: 1,
  406. needsPowerOfTwo: false,
  407. },
  408. {
  409. if: 'bptcSupported',
  410. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  411. transcoderFormat: [ TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5 ],
  412. engineFormat: [ EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format ],
  413. priorityETC1S: 3,
  414. priorityUASTC: 2,
  415. needsPowerOfTwo: false,
  416. },
  417. {
  418. if: 'dxtSupported',
  419. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  420. transcoderFormat: [ TranscoderFormat.BC1, TranscoderFormat.BC3 ],
  421. engineFormat: [ EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format ],
  422. priorityETC1S: 4,
  423. priorityUASTC: 5,
  424. needsPowerOfTwo: false,
  425. },
  426. {
  427. if: 'etc2Supported',
  428. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  429. transcoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC2 ],
  430. engineFormat: [ EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format ],
  431. priorityETC1S: 1,
  432. priorityUASTC: 3,
  433. needsPowerOfTwo: false,
  434. },
  435. {
  436. if: 'etc1Supported',
  437. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  438. transcoderFormat: [ TranscoderFormat.ETC1 ],
  439. engineFormat: [ EngineFormat.RGB_ETC1_Format ],
  440. priorityETC1S: 2,
  441. priorityUASTC: 4,
  442. needsPowerOfTwo: false,
  443. },
  444. {
  445. if: 'pvrtcSupported',
  446. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  447. transcoderFormat: [ TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA ],
  448. engineFormat: [ EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format ],
  449. priorityETC1S: 5,
  450. priorityUASTC: 6,
  451. needsPowerOfTwo: true,
  452. },
  453. ];
  454. const ETC1S_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  455. return a.priorityETC1S - b.priorityETC1S;
  456. } );
  457. const UASTC_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  458. return a.priorityUASTC - b.priorityUASTC;
  459. } );
  460. function getTranscoderFormat( basisFormat, width, height, hasAlpha ) {
  461. let transcoderFormat;
  462. let engineFormat;
  463. const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS;
  464. for ( let i = 0; i < options.length; i ++ ) {
  465. const opt = options[ i ];
  466. if ( ! config[ opt.if ] ) continue;
  467. if ( ! opt.basisFormat.includes( basisFormat ) ) continue;
  468. if ( hasAlpha && opt.transcoderFormat.length < 2 ) continue;
  469. if ( opt.needsPowerOfTwo && ! ( isPowerOfTwo( width ) && isPowerOfTwo( height ) ) ) continue;
  470. transcoderFormat = opt.transcoderFormat[ hasAlpha ? 1 : 0 ];
  471. engineFormat = opt.engineFormat[ hasAlpha ? 1 : 0 ];
  472. return { transcoderFormat, engineFormat };
  473. }
  474. console.warn( 'THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32.' );
  475. transcoderFormat = TranscoderFormat.RGBA32;
  476. engineFormat = EngineFormat.RGBAFormat;
  477. return { transcoderFormat, engineFormat };
  478. }
  479. function isPowerOfTwo( value ) {
  480. if ( value <= 2 ) return true;
  481. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  482. }
  483. /** Concatenates N byte arrays. */
  484. function concat( arrays ) {
  485. if ( arrays.length === 1 ) return arrays[ 0 ];
  486. let totalByteLength = 0;
  487. for ( let i = 0; i < arrays.length; i ++ ) {
  488. const array = arrays[ i ];
  489. totalByteLength += array.byteLength;
  490. }
  491. const result = new Uint8Array( totalByteLength );
  492. let byteOffset = 0;
  493. for ( let i = 0; i < arrays.length; i ++ ) {
  494. const array = arrays[ i ];
  495. result.set( array, byteOffset );
  496. byteOffset += array.byteLength;
  497. }
  498. return result;
  499. }
  500. };
  501. //
  502. // DataTexture and Data3DTexture parsing.
  503. const FORMAT_MAP = {
  504. [ VK_FORMAT_R32G32B32A32_SFLOAT ]: RGBAFormat,
  505. [ VK_FORMAT_R16G16B16A16_SFLOAT ]: RGBAFormat,
  506. [ VK_FORMAT_R8G8B8A8_UNORM ]: RGBAFormat,
  507. [ VK_FORMAT_R8G8B8A8_SRGB ]: RGBAFormat,
  508. [ VK_FORMAT_R32G32_SFLOAT ]: RGFormat,
  509. [ VK_FORMAT_R16G16_SFLOAT ]: RGFormat,
  510. [ VK_FORMAT_R8G8_UNORM ]: RGFormat,
  511. [ VK_FORMAT_R8G8_SRGB ]: RGFormat,
  512. [ VK_FORMAT_R32_SFLOAT ]: RedFormat,
  513. [ VK_FORMAT_R16_SFLOAT ]: RedFormat,
  514. [ VK_FORMAT_R8_SRGB ]: RedFormat,
  515. [ VK_FORMAT_R8_UNORM ]: RedFormat,
  516. };
  517. const TYPE_MAP = {
  518. [ VK_FORMAT_R32G32B32A32_SFLOAT ]: FloatType,
  519. [ VK_FORMAT_R16G16B16A16_SFLOAT ]: HalfFloatType,
  520. [ VK_FORMAT_R8G8B8A8_UNORM ]: UnsignedByteType,
  521. [ VK_FORMAT_R8G8B8A8_SRGB ]: UnsignedByteType,
  522. [ VK_FORMAT_R32G32_SFLOAT ]: FloatType,
  523. [ VK_FORMAT_R16G16_SFLOAT ]: HalfFloatType,
  524. [ VK_FORMAT_R8G8_UNORM ]: UnsignedByteType,
  525. [ VK_FORMAT_R8G8_SRGB ]: UnsignedByteType,
  526. [ VK_FORMAT_R32_SFLOAT ]: FloatType,
  527. [ VK_FORMAT_R16_SFLOAT ]: HalfFloatType,
  528. [ VK_FORMAT_R8_SRGB ]: UnsignedByteType,
  529. [ VK_FORMAT_R8_UNORM ]: UnsignedByteType,
  530. };
  531. const COLOR_SPACE_MAP = {
  532. [ VK_FORMAT_R8G8B8A8_SRGB ]: SRGBColorSpace,
  533. [ VK_FORMAT_R8G8_SRGB ]: SRGBColorSpace,
  534. [ VK_FORMAT_R8_SRGB ]: SRGBColorSpace,
  535. };
  536. async function createDataTexture( container, levelIndex = 0 ) {
  537. const { vkFormat } = container;
  538. const pixelWidth = Math.max( 1, container.pixelWidth >> levelIndex );
  539. const pixelHeight = Math.max( 1, container.pixelHeight >> levelIndex );
  540. const pixelDepth = Math.max( 1, container.pixelDepth >> levelIndex );
  541. if ( FORMAT_MAP[ vkFormat ] === undefined ) {
  542. throw new Error( 'THREE.KTX2Loader: Unsupported vkFormat.' );
  543. }
  544. const level = container.levels[ levelIndex ];
  545. let levelData;
  546. let view;
  547. if ( container.supercompressionScheme === KHR_SUPERCOMPRESSION_NONE ) {
  548. levelData = level.levelData;
  549. } else if ( container.supercompressionScheme === KHR_SUPERCOMPRESSION_ZSTD ) {
  550. if ( ! _zstd ) {
  551. _zstd = new Promise( async ( resolve ) => {
  552. const zstd = new ZSTDDecoder();
  553. await zstd.init();
  554. resolve( zstd );
  555. } );
  556. }
  557. levelData = ( await _zstd ).decode( level.levelData, level.uncompressedByteLength );
  558. } else {
  559. throw new Error( 'THREE.KTX2Loader: Unsupported supercompressionScheme.' );
  560. }
  561. if ( TYPE_MAP[ vkFormat ] === FloatType ) {
  562. view = new Float32Array(
  563. levelData.buffer,
  564. levelData.byteOffset,
  565. levelData.byteLength / Float32Array.BYTES_PER_ELEMENT
  566. );
  567. } else if ( TYPE_MAP[ vkFormat ] === HalfFloatType ) {
  568. view = new Uint16Array(
  569. levelData.buffer,
  570. levelData.byteOffset,
  571. levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT
  572. );
  573. } else {
  574. view = levelData;
  575. }
  576. //
  577. const texture = pixelDepth === 0
  578. ? new DataTexture( view, pixelWidth, pixelHeight )
  579. : new Data3DTexture( view, pixelWidth, pixelHeight, pixelDepth );
  580. texture.type = TYPE_MAP[ vkFormat ];
  581. texture.format = FORMAT_MAP[ vkFormat ];
  582. texture.colorSpace = COLOR_SPACE_MAP[ vkFormat ] || NoColorSpace;
  583. texture.needsUpdate = true;
  584. //
  585. return Promise.resolve( texture );
  586. }
  587. export { KTX2Loader };