KTX2Loader.js 17 KB

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