KTX2Loader.js 23 KB

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