2
0

KTX2Loader.js 23 KB

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