KTX2Loader.js 23 KB

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