KTX2Loader.js 19 KB

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