KTX2Loader.js 19 KB

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