KTX2Loader.js 18 KB

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