KTX2Loader.js 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276
  1. import {
  2. CompressedArrayTexture,
  3. CompressedCubeTexture,
  4. CompressedTexture,
  5. Data3DTexture,
  6. DataTexture,
  7. FileLoader,
  8. FloatType,
  9. HalfFloatType,
  10. LinearFilter,
  11. LinearMipmapLinearFilter,
  12. NearestFilter,
  13. NearestMipmapNearestFilter,
  14. LinearSRGBColorSpace,
  15. Loader,
  16. NoColorSpace,
  17. RGBAFormat,
  18. RGBA_ASTC_4x4_Format,
  19. RGBA_ASTC_6x6_Format,
  20. RGBA_BPTC_Format,
  21. RGBA_ETC2_EAC_Format,
  22. R11_EAC_Format,
  23. SIGNED_R11_EAC_Format,
  24. RG11_EAC_Format,
  25. SIGNED_RG11_EAC_Format,
  26. RGBA_PVRTC_4BPPV1_Format,
  27. RGBA_PVRTC_2BPPV1_Format,
  28. RGBA_S3TC_DXT1_Format,
  29. RGBA_S3TC_DXT5_Format,
  30. RGB_BPTC_UNSIGNED_Format,
  31. RGB_ETC1_Format,
  32. RGB_ETC2_Format,
  33. RGB_PVRTC_4BPPV1_Format,
  34. RGB_S3TC_DXT1_Format,
  35. SIGNED_RED_GREEN_RGTC2_Format,
  36. SIGNED_RED_RGTC1_Format,
  37. RED_GREEN_RGTC2_Format,
  38. RED_RGTC1_Format,
  39. RGBFormat,
  40. RGFormat,
  41. RedFormat,
  42. SRGBColorSpace,
  43. UnsignedByteType,
  44. UnsignedInt5999Type,
  45. UnsignedInt101111Type,
  46. UnsignedShortType
  47. } from 'three';
  48. import { WorkerPool } from '../utils/WorkerPool.js';
  49. import {
  50. read,
  51. KHR_DF_FLAG_ALPHA_PREMULTIPLIED,
  52. KHR_DF_PRIMARIES_BT709,
  53. KHR_DF_PRIMARIES_DISPLAYP3,
  54. KHR_DF_PRIMARIES_UNSPECIFIED,
  55. KHR_DF_TRANSFER_SRGB,
  56. KHR_SUPERCOMPRESSION_NONE,
  57. KHR_SUPERCOMPRESSION_ZSTD,
  58. VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT,
  59. VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT,
  60. VK_FORMAT_ASTC_4x4_SRGB_BLOCK,
  61. VK_FORMAT_ASTC_4x4_UNORM_BLOCK,
  62. VK_FORMAT_ASTC_6x6_SRGB_BLOCK,
  63. VK_FORMAT_ASTC_6x6_UNORM_BLOCK,
  64. VK_FORMAT_BC1_RGBA_SRGB_BLOCK,
  65. VK_FORMAT_BC1_RGBA_UNORM_BLOCK,
  66. VK_FORMAT_BC1_RGB_SRGB_BLOCK,
  67. VK_FORMAT_BC1_RGB_UNORM_BLOCK,
  68. VK_FORMAT_BC3_SRGB_BLOCK,
  69. VK_FORMAT_BC3_UNORM_BLOCK,
  70. VK_FORMAT_BC4_SNORM_BLOCK,
  71. VK_FORMAT_BC4_UNORM_BLOCK,
  72. VK_FORMAT_BC5_SNORM_BLOCK,
  73. VK_FORMAT_BC5_UNORM_BLOCK,
  74. VK_FORMAT_BC7_SRGB_BLOCK,
  75. VK_FORMAT_BC7_UNORM_BLOCK,
  76. VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK,
  77. VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK,
  78. VK_FORMAT_EAC_R11_UNORM_BLOCK,
  79. VK_FORMAT_EAC_R11_SNORM_BLOCK,
  80. VK_FORMAT_EAC_R11G11_UNORM_BLOCK,
  81. VK_FORMAT_EAC_R11G11_SNORM_BLOCK,
  82. VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG,
  83. VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG,
  84. VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG,
  85. VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG,
  86. VK_FORMAT_R16G16B16A16_SFLOAT,
  87. VK_FORMAT_R16G16B16A16_UNORM,
  88. VK_FORMAT_R16G16_SFLOAT,
  89. VK_FORMAT_R16_SFLOAT,
  90. VK_FORMAT_R32G32B32A32_SFLOAT,
  91. VK_FORMAT_R32G32_SFLOAT,
  92. VK_FORMAT_R32_SFLOAT,
  93. VK_FORMAT_R8G8B8A8_SRGB,
  94. VK_FORMAT_R8G8B8A8_UNORM,
  95. VK_FORMAT_R8G8_SRGB,
  96. VK_FORMAT_R8G8_UNORM,
  97. VK_FORMAT_R8_SRGB,
  98. VK_FORMAT_R8_UNORM,
  99. VK_FORMAT_E5B9G9R9_UFLOAT_PACK32,
  100. VK_FORMAT_B10G11R11_UFLOAT_PACK32,
  101. VK_FORMAT_UNDEFINED
  102. } from '../libs/ktx-parse.module.js';
  103. import { ZSTDDecoder } from '../libs/zstddec.module.js';
  104. import { DisplayP3ColorSpace, LinearDisplayP3ColorSpace } from '../math/ColorSpaces.js';
  105. const WASM_BIN_URL = new URL( '../libs/basis/basis_transcoder.wasm', import.meta.url ).toString();
  106. const WASM_JS_URL = new URL( '../libs/basis/basis_transcoder.js', import.meta.url ).toString();
  107. const _taskCache = new WeakMap();
  108. let _activeLoaders = 0;
  109. let _zstd;
  110. /**
  111. * A loader for KTX 2.0 GPU Texture containers.
  112. *
  113. * KTX 2.0 is a container format for various GPU texture formats. The loader supports Basis Universal GPU textures,
  114. * which can be quickly transcoded to a wide variety of GPU texture compression formats. While KTX 2.0 also allows
  115. * other hardware-specific formats, this loader does not yet parse them.
  116. *
  117. * This loader parses the KTX 2.0 container and transcodes to a supported GPU compressed texture format.
  118. * The required WASM transcoder and JS wrapper are available from the `examples/jsm/libs/basis` directory.
  119. *
  120. * This loader relies on Web Assembly which is not supported in older browsers.
  121. *
  122. * References:
  123. * - [KTX specification](http://github.khronos.org/KTX-Specification/)
  124. * - [DFD](https://www.khronos.org/registry/DataFormat/specs/1.3/dataformat.1.3.html#basicdescriptor)
  125. * - [BasisU HDR](https://github.com/BinomialLLC/basis_universal/wiki/UASTC-HDR-Texture-Specification-v1.0)
  126. *
  127. * ```js
  128. * const loader = new KTX2Loader();
  129. * loader.setTranscoderPath( 'examples/jsm/libs/basis/' );
  130. * loader.detectSupport( renderer );
  131. * const texture = loader.loadAsync( 'diffuse.ktx2' );
  132. * ```
  133. *
  134. * @augments Loader
  135. * @three_import import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';
  136. */
  137. class KTX2Loader extends Loader {
  138. /**
  139. * Constructs a new KTX2 loader.
  140. *
  141. * @param {LoadingManager} [manager] - The loading manager.
  142. */
  143. constructor( manager ) {
  144. super( manager );
  145. this.transcoderPath = '';
  146. this.transcoderBinary = null;
  147. this.transcoderPending = null;
  148. this.workerPool = new WorkerPool();
  149. this.workerSourceURL = '';
  150. this.workerConfig = null;
  151. if ( typeof MSC_TRANSCODER !== 'undefined' ) {
  152. console.warn(
  153. 'THREE.KTX2Loader: Please update to latest "basis_transcoder".'
  154. + ' "msc_basis_transcoder" is no longer supported in three.js r125+.'
  155. );
  156. }
  157. }
  158. /**
  159. * Sets the transcoder path to optionally set the decoder load path from a CDN.
  160. *
  161. * By default The WASM transcoder and JS wrapper are loaded from the `examples/jsm/libs/basis` directory.
  162. *
  163. * @param {string} path - The transcoder path to set.
  164. * @return {KTX2Loader} A reference to this loader.
  165. */
  166. setTranscoderPath( path ) {
  167. this.transcoderPath = path;
  168. return this;
  169. }
  170. /**
  171. * Sets the maximum number of Web Workers to be allocated by this instance.
  172. *
  173. * @param {number} workerLimit - The worker limit.
  174. * @return {KTX2Loader} A reference to this loader.
  175. */
  176. setWorkerLimit( workerLimit ) {
  177. this.workerPool.setWorkerLimit( workerLimit );
  178. return this;
  179. }
  180. /**
  181. * Async version of {@link KTX2Loader#detectSupport}.
  182. *
  183. * @async
  184. * @deprecated
  185. * @param {WebGPURenderer} renderer - The renderer.
  186. * @return {Promise} A Promise that resolves when the support has been detected.
  187. */
  188. async detectSupportAsync( renderer ) {
  189. console.warn( 'KTX2Loader: "detectSupportAsync()" has been deprecated. Use "detectSupport()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  190. await renderer.init();
  191. return this.detectSupport( renderer );
  192. }
  193. /**
  194. * Detects hardware support for available compressed texture formats, to determine
  195. * the output format for the transcoder. Must be called before loading a texture.
  196. *
  197. * @param {WebGPURenderer|WebGLRenderer} renderer - The renderer.
  198. * @return {KTX2Loader} A reference to this loader.
  199. */
  200. detectSupport( renderer ) {
  201. if ( renderer.isWebGPURenderer === true ) {
  202. this.workerConfig = {
  203. astcSupported: renderer.hasFeature( 'texture-compression-astc' ),
  204. astcHDRSupported: false, // https://github.com/gpuweb/gpuweb/issues/3856
  205. etc1Supported: renderer.hasFeature( 'texture-compression-etc1' ),
  206. etc2Supported: renderer.hasFeature( 'texture-compression-etc2' ),
  207. dxtSupported: renderer.hasFeature( 'texture-compression-s3tc' ),
  208. bptcSupported: renderer.hasFeature( 'texture-compression-bc' ),
  209. pvrtcSupported: renderer.hasFeature( 'texture-compression-pvrtc' )
  210. };
  211. } else {
  212. this.workerConfig = {
  213. astcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_astc' ),
  214. astcHDRSupported: renderer.extensions.has( 'WEBGL_compressed_texture_astc' )
  215. && renderer.extensions.get( 'WEBGL_compressed_texture_astc' ).getSupportedProfiles().includes( 'hdr' ),
  216. etc1Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc1' ),
  217. etc2Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc' ),
  218. dxtSupported: renderer.extensions.has( 'WEBGL_compressed_texture_s3tc' ),
  219. bptcSupported: renderer.extensions.has( 'EXT_texture_compression_bptc' ),
  220. pvrtcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_pvrtc' )
  221. || renderer.extensions.has( 'WEBKIT_WEBGL_compressed_texture_pvrtc' )
  222. };
  223. if ( typeof navigator !== 'undefined' &&
  224. typeof navigator.platform !== 'undefined' && typeof navigator.userAgent !== 'undefined' &&
  225. navigator.platform.indexOf( 'Linux' ) >= 0 && navigator.userAgent.indexOf( 'Android' ) < 0 &&
  226. this.workerConfig.astcSupported && this.workerConfig.etc2Supported &&
  227. this.workerConfig.bptcSupported && this.workerConfig.dxtSupported ) {
  228. // On Linux, Mesa drivers for AMD and Intel GPUs expose ETC1,ETC2 and ASTC even though the hardware doesn't support these.
  229. // Using these extensions will result in expensive software decompression on the main thread inside the driver, causing performance issues.
  230. // In general, browsers should not expose extensions for emulated formats, but Chrome and Firefox currently do so on Linux.
  231. // Since a granular filter is a little too fragile and we can transcode into other GPU formats, disable formats that are likely to be emulated.
  232. this.workerConfig.astcSupported = false;
  233. this.workerConfig.etc1Supported = false;
  234. this.workerConfig.etc2Supported = false;
  235. }
  236. }
  237. return this;
  238. }
  239. // TODO: Make this method private
  240. init() {
  241. if ( ! this.transcoderPending ) {
  242. const jsLoader = new FileLoader( this.manager );
  243. jsLoader.setWithCredentials( this.withCredentials );
  244. const binaryLoader = new FileLoader( this.manager );
  245. binaryLoader.setWithCredentials( this.withCredentials );
  246. binaryLoader.setResponseType( 'arraybuffer' );
  247. let jsContent, binaryContent;
  248. if ( this.transcoderPath === '' ) {
  249. jsContent = jsLoader.loadAsync( WASM_JS_URL );
  250. binaryContent = binaryLoader.loadAsync( WASM_BIN_URL );
  251. } else {
  252. // Load transcoder wrapper.
  253. jsLoader.setPath( this.transcoderPath );
  254. jsContent = jsLoader.loadAsync( 'basis_transcoder.js' );
  255. // Load transcoder WASM binary.
  256. binaryLoader.setPath( this.transcoderPath );
  257. binaryContent = binaryLoader.loadAsync( 'basis_transcoder.wasm' );
  258. }
  259. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] )
  260. .then( ( [ jsContent, binaryContent ] ) => {
  261. const fn = KTX2Loader.BasisWorker.toString();
  262. const body = [
  263. '/* constants */',
  264. 'let _EngineFormat = ' + JSON.stringify( KTX2Loader.EngineFormat ),
  265. 'let _EngineType = ' + JSON.stringify( KTX2Loader.EngineType ),
  266. 'let _TranscoderFormat = ' + JSON.stringify( KTX2Loader.TranscoderFormat ),
  267. 'let _BasisFormat = ' + JSON.stringify( KTX2Loader.BasisFormat ),
  268. '/* basis_transcoder.js */',
  269. jsContent,
  270. '/* worker */',
  271. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  272. ].join( '\n' );
  273. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  274. this.transcoderBinary = binaryContent;
  275. this.workerPool.setWorkerCreator( () => {
  276. const worker = new Worker( this.workerSourceURL );
  277. const transcoderBinary = this.transcoderBinary.slice( 0 );
  278. worker.postMessage( { type: 'init', config: this.workerConfig, transcoderBinary }, [ transcoderBinary ] );
  279. return worker;
  280. } );
  281. } );
  282. if ( _activeLoaders > 0 ) {
  283. // Each instance loads a transcoder and allocates workers, increasing network and memory cost.
  284. console.warn(
  285. 'THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues.'
  286. + ' Use a single KTX2Loader instance, or call .dispose() on old instances.'
  287. );
  288. }
  289. _activeLoaders ++;
  290. }
  291. return this.transcoderPending;
  292. }
  293. /**
  294. * Starts loading from the given URL and passes the loaded KTX2 texture
  295. * to the `onLoad()` callback.
  296. *
  297. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  298. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  299. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  300. * @param {onErrorCallback} onError - Executed when errors occur.
  301. */
  302. load( url, onLoad, onProgress, onError ) {
  303. if ( this.workerConfig === null ) {
  304. throw new Error( 'THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.' );
  305. }
  306. const loader = new FileLoader( this.manager );
  307. loader.setPath( this.path );
  308. loader.setCrossOrigin( this.crossOrigin );
  309. loader.setWithCredentials( this.withCredentials );
  310. loader.setRequestHeader( this.requestHeader );
  311. loader.setResponseType( 'arraybuffer' );
  312. loader.load( url, ( buffer ) => {
  313. this.parse( buffer, onLoad, onError );
  314. }, onProgress, onError );
  315. }
  316. /**
  317. * Parses the given KTX2 data.
  318. *
  319. * @param {ArrayBuffer} buffer - The raw KTX2 data as an array buffer.
  320. * @param {function(CompressedTexture)} onLoad - Executed when the loading/parsing process has been finished.
  321. * @param {onErrorCallback} onError - Executed when errors occur.
  322. * @returns {Promise} A Promise that resolves when the parsing has been finished.
  323. */
  324. parse( buffer, onLoad, onError ) {
  325. if ( this.workerConfig === null ) {
  326. throw new Error( 'THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.' );
  327. }
  328. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  329. // again from this thread.
  330. if ( _taskCache.has( buffer ) ) {
  331. const cachedTask = _taskCache.get( buffer );
  332. return cachedTask.promise.then( onLoad ).catch( onError );
  333. }
  334. this._createTexture( buffer )
  335. .then( ( texture ) => onLoad ? onLoad( texture ) : null )
  336. .catch( onError );
  337. }
  338. _createTextureFrom( transcodeResult, container ) {
  339. const { type: messageType, error, data: { faces, width, height, format, type, dfdFlags } } = transcodeResult;
  340. if ( messageType === 'error' ) return Promise.reject( error );
  341. let texture;
  342. if ( container.faceCount === 6 ) {
  343. texture = new CompressedCubeTexture( faces, format, type );
  344. } else {
  345. const mipmaps = faces[ 0 ].mipmaps;
  346. texture = container.layerCount > 1
  347. ? new CompressedArrayTexture( mipmaps, width, height, container.layerCount, format, type )
  348. : new CompressedTexture( mipmaps, width, height, format, type );
  349. }
  350. texture.minFilter = faces[ 0 ].mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter;
  351. texture.magFilter = LinearFilter;
  352. texture.generateMipmaps = false;
  353. texture.needsUpdate = true;
  354. texture.colorSpace = parseColorSpace( container );
  355. texture.premultiplyAlpha = !! ( dfdFlags & KHR_DF_FLAG_ALPHA_PREMULTIPLIED );
  356. return texture;
  357. }
  358. /**
  359. * @private
  360. * @param {ArrayBuffer} buffer
  361. * @param {?Object} config
  362. * @return {Promise<CompressedTexture|CompressedArrayTexture|DataTexture|Data3DTexture>}
  363. */
  364. async _createTexture( buffer, config = {} ) {
  365. const container = read( new Uint8Array( buffer ) );
  366. // Basis UASTC HDR is a subset of ASTC, which can be transcoded efficiently
  367. // to BC6H. To detect whether a KTX2 file uses Basis UASTC HDR, or default
  368. // ASTC, inspect the DFD color model.
  369. //
  370. // Source: https://github.com/BinomialLLC/basis_universal/issues/381
  371. const isBasisHDR = container.vkFormat === VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT
  372. && container.dataFormatDescriptor[ 0 ].colorModel === 0xA7;
  373. // If the device supports ASTC, Basis UASTC HDR requires no transcoder.
  374. const needsTranscoder = container.vkFormat === VK_FORMAT_UNDEFINED
  375. || isBasisHDR && ! this.workerConfig.astcHDRSupported;
  376. if ( ! needsTranscoder ) {
  377. return createRawTexture( container );
  378. }
  379. //
  380. const taskConfig = config;
  381. const texturePending = this.init().then( () => {
  382. return this.workerPool.postMessage( { type: 'transcode', buffer, taskConfig: taskConfig }, [ buffer ] );
  383. } ).then( ( e ) => this._createTextureFrom( e.data, container ) );
  384. // Cache the task result.
  385. _taskCache.set( buffer, { promise: texturePending } );
  386. return texturePending;
  387. }
  388. /**
  389. * Frees internal resources. This method should be called
  390. * when the loader is no longer required.
  391. */
  392. dispose() {
  393. this.workerPool.dispose();
  394. if ( this.workerSourceURL ) URL.revokeObjectURL( this.workerSourceURL );
  395. _activeLoaders --;
  396. }
  397. }
  398. /* CONSTANTS */
  399. KTX2Loader.BasisFormat = {
  400. ETC1S: 0,
  401. UASTC: 1,
  402. UASTC_HDR: 2,
  403. };
  404. // Source: https://github.com/BinomialLLC/basis_universal/blob/master/webgl/texture_test/index.html
  405. KTX2Loader.TranscoderFormat = {
  406. ETC1: 0,
  407. ETC2: 1,
  408. BC1: 2,
  409. BC3: 3,
  410. BC4: 4,
  411. BC5: 5,
  412. BC7_M6_OPAQUE_ONLY: 6,
  413. BC7_M5: 7,
  414. PVRTC1_4_RGB: 8,
  415. PVRTC1_4_RGBA: 9,
  416. ASTC_4x4: 10,
  417. ATC_RGB: 11,
  418. ATC_RGBA_INTERPOLATED_ALPHA: 12,
  419. RGBA32: 13,
  420. RGB565: 14,
  421. BGR565: 15,
  422. RGBA4444: 16,
  423. BC6H: 22,
  424. RGB_HALF: 24,
  425. RGBA_HALF: 25,
  426. };
  427. KTX2Loader.EngineFormat = {
  428. RGBAFormat: RGBAFormat,
  429. RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
  430. RGB_BPTC_UNSIGNED_Format: RGB_BPTC_UNSIGNED_Format,
  431. RGBA_BPTC_Format: RGBA_BPTC_Format,
  432. RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
  433. RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
  434. RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format,
  435. RGB_ETC1_Format: RGB_ETC1_Format,
  436. RGB_ETC2_Format: RGB_ETC2_Format,
  437. RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
  438. RGBA_S3TC_DXT1_Format: RGBA_S3TC_DXT1_Format,
  439. };
  440. KTX2Loader.EngineType = {
  441. UnsignedByteType: UnsignedByteType,
  442. HalfFloatType: HalfFloatType,
  443. FloatType: FloatType,
  444. };
  445. /* WEB WORKER */
  446. KTX2Loader.BasisWorker = function () {
  447. let config;
  448. let transcoderPending;
  449. let BasisModule;
  450. const EngineFormat = _EngineFormat; // eslint-disable-line no-undef
  451. const EngineType = _EngineType; // eslint-disable-line no-undef
  452. const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef
  453. const BasisFormat = _BasisFormat; // eslint-disable-line no-undef
  454. self.addEventListener( 'message', function ( e ) {
  455. const message = e.data;
  456. switch ( message.type ) {
  457. case 'init':
  458. config = message.config;
  459. init( message.transcoderBinary );
  460. break;
  461. case 'transcode':
  462. transcoderPending.then( () => {
  463. try {
  464. const { faces, buffers, width, height, hasAlpha, format, type, dfdFlags } = transcode( message.buffer );
  465. self.postMessage( { type: 'transcode', id: message.id, data: { faces, width, height, hasAlpha, format, type, dfdFlags } }, buffers );
  466. } catch ( error ) {
  467. console.error( error );
  468. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  469. }
  470. } );
  471. break;
  472. }
  473. } );
  474. function init( wasmBinary ) {
  475. transcoderPending = new Promise( ( resolve ) => {
  476. BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
  477. BASIS( BasisModule ); // eslint-disable-line no-undef
  478. } ).then( () => {
  479. BasisModule.initializeBasis();
  480. if ( BasisModule.KTX2File === undefined ) {
  481. console.warn( 'THREE.KTX2Loader: Please update Basis Universal transcoder.' );
  482. }
  483. } );
  484. }
  485. function transcode( buffer ) {
  486. const ktx2File = new BasisModule.KTX2File( new Uint8Array( buffer ) );
  487. function cleanup() {
  488. ktx2File.close();
  489. ktx2File.delete();
  490. }
  491. if ( ! ktx2File.isValid() ) {
  492. cleanup();
  493. throw new Error( 'THREE.KTX2Loader: Invalid or unsupported .ktx2 file' );
  494. }
  495. let basisFormat;
  496. if ( ktx2File.isUASTC() ) {
  497. basisFormat = BasisFormat.UASTC;
  498. } else if ( ktx2File.isETC1S() ) {
  499. basisFormat = BasisFormat.ETC1S;
  500. } else if ( ktx2File.isHDR() ) {
  501. basisFormat = BasisFormat.UASTC_HDR;
  502. } else {
  503. throw new Error( 'THREE.KTX2Loader: Unknown Basis encoding' );
  504. }
  505. const width = ktx2File.getWidth();
  506. const height = ktx2File.getHeight();
  507. const layerCount = ktx2File.getLayers() || 1;
  508. const levelCount = ktx2File.getLevels();
  509. const faceCount = ktx2File.getFaces();
  510. const hasAlpha = ktx2File.getHasAlpha();
  511. const dfdFlags = ktx2File.getDFDFlags();
  512. const { transcoderFormat, engineFormat, engineType } = getTranscoderFormat( basisFormat, width, height, hasAlpha );
  513. if ( ! width || ! height || ! levelCount ) {
  514. cleanup();
  515. throw new Error( 'THREE.KTX2Loader: Invalid texture' );
  516. }
  517. if ( ! ktx2File.startTranscoding() ) {
  518. cleanup();
  519. throw new Error( 'THREE.KTX2Loader: .startTranscoding failed' );
  520. }
  521. const faces = [];
  522. const buffers = [];
  523. for ( let face = 0; face < faceCount; face ++ ) {
  524. const mipmaps = [];
  525. for ( let mip = 0; mip < levelCount; mip ++ ) {
  526. const layerMips = [];
  527. let mipWidth, mipHeight;
  528. for ( let layer = 0; layer < layerCount; layer ++ ) {
  529. const levelInfo = ktx2File.getImageLevelInfo( mip, layer, face );
  530. if ( face === 0 && mip === 0 && layer === 0 && ( levelInfo.origWidth % 4 !== 0 || levelInfo.origHeight % 4 !== 0 ) ) {
  531. console.warn( 'THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions.' );
  532. }
  533. if ( levelCount > 1 ) {
  534. mipWidth = levelInfo.origWidth;
  535. mipHeight = levelInfo.origHeight;
  536. } else {
  537. // Handles non-multiple-of-four dimensions in textures without mipmaps. Textures with
  538. // mipmaps must use multiple-of-four dimensions, for some texture formats and APIs.
  539. // See mrdoob/three.js#25908.
  540. mipWidth = levelInfo.width;
  541. mipHeight = levelInfo.height;
  542. }
  543. let dst = new Uint8Array( ktx2File.getImageTranscodedSizeInBytes( mip, layer, 0, transcoderFormat ) );
  544. const status = ktx2File.transcodeImage( dst, mip, layer, face, transcoderFormat, 0, - 1, - 1 );
  545. if ( engineType === EngineType.HalfFloatType ) {
  546. dst = new Uint16Array( dst.buffer, dst.byteOffset, dst.byteLength / Uint16Array.BYTES_PER_ELEMENT );
  547. }
  548. if ( ! status ) {
  549. cleanup();
  550. throw new Error( 'THREE.KTX2Loader: .transcodeImage failed.' );
  551. }
  552. layerMips.push( dst );
  553. }
  554. const mipData = concat( layerMips );
  555. mipmaps.push( { data: mipData, width: mipWidth, height: mipHeight } );
  556. buffers.push( mipData.buffer );
  557. }
  558. faces.push( { mipmaps, width, height, format: engineFormat, type: engineType } );
  559. }
  560. cleanup();
  561. return { faces, buffers, width, height, hasAlpha, dfdFlags, format: engineFormat, type: engineType };
  562. }
  563. //
  564. // Optimal choice of a transcoder target format depends on the Basis format (ETC1S, UASTC, or
  565. // UASTC HDR), device capabilities, and texture dimensions. The list below ranks the formats
  566. // separately for each format. Currently, priority is assigned based on:
  567. //
  568. // high quality > low quality > uncompressed
  569. //
  570. // Prioritization may be revisited, or exposed for configuration, in the future.
  571. //
  572. // Reference: https://github.com/KhronosGroup/3D-Formats-Guidelines/blob/main/KTXDeveloperGuide.md
  573. const FORMAT_OPTIONS = [
  574. {
  575. if: 'astcSupported',
  576. basisFormat: [ BasisFormat.UASTC ],
  577. transcoderFormat: [ TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4 ],
  578. engineFormat: [ EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format ],
  579. engineType: [ EngineType.UnsignedByteType ],
  580. priorityETC1S: Infinity,
  581. priorityUASTC: 1,
  582. needsPowerOfTwo: false,
  583. },
  584. {
  585. if: 'bptcSupported',
  586. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC ],
  587. transcoderFormat: [ TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5 ],
  588. engineFormat: [ EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format ],
  589. engineType: [ EngineType.UnsignedByteType ],
  590. priorityETC1S: 3,
  591. priorityUASTC: 2,
  592. needsPowerOfTwo: false,
  593. },
  594. {
  595. if: 'dxtSupported',
  596. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC ],
  597. transcoderFormat: [ TranscoderFormat.BC1, TranscoderFormat.BC3 ],
  598. engineFormat: [ EngineFormat.RGBA_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format ],
  599. engineType: [ EngineType.UnsignedByteType ],
  600. priorityETC1S: 4,
  601. priorityUASTC: 5,
  602. needsPowerOfTwo: false,
  603. },
  604. {
  605. if: 'etc2Supported',
  606. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC ],
  607. transcoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC2 ],
  608. engineFormat: [ EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format ],
  609. engineType: [ EngineType.UnsignedByteType ],
  610. priorityETC1S: 1,
  611. priorityUASTC: 3,
  612. needsPowerOfTwo: false,
  613. },
  614. {
  615. if: 'etc1Supported',
  616. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC ],
  617. transcoderFormat: [ TranscoderFormat.ETC1 ],
  618. engineFormat: [ EngineFormat.RGB_ETC1_Format ],
  619. engineType: [ EngineType.UnsignedByteType ],
  620. priorityETC1S: 2,
  621. priorityUASTC: 4,
  622. needsPowerOfTwo: false,
  623. },
  624. {
  625. if: 'pvrtcSupported',
  626. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC ],
  627. transcoderFormat: [ TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA ],
  628. engineFormat: [ EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format ],
  629. engineType: [ EngineType.UnsignedByteType ],
  630. priorityETC1S: 5,
  631. priorityUASTC: 6,
  632. needsPowerOfTwo: true,
  633. },
  634. {
  635. if: 'bptcSupported',
  636. basisFormat: [ BasisFormat.UASTC_HDR ],
  637. transcoderFormat: [ TranscoderFormat.BC6H ],
  638. engineFormat: [ EngineFormat.RGB_BPTC_UNSIGNED_Format ],
  639. engineType: [ EngineType.HalfFloatType ],
  640. priorityHDR: 1,
  641. needsPowerOfTwo: false,
  642. },
  643. // Uncompressed fallbacks.
  644. {
  645. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC ],
  646. transcoderFormat: [ TranscoderFormat.RGBA32, TranscoderFormat.RGBA32 ],
  647. engineFormat: [ EngineFormat.RGBAFormat, EngineFormat.RGBAFormat ],
  648. engineType: [ EngineType.UnsignedByteType, EngineType.UnsignedByteType ],
  649. priorityETC1S: 100,
  650. priorityUASTC: 100,
  651. needsPowerOfTwo: false,
  652. },
  653. {
  654. basisFormat: [ BasisFormat.UASTC_HDR ],
  655. transcoderFormat: [ TranscoderFormat.RGBA_HALF ],
  656. engineFormat: [ EngineFormat.RGBAFormat ],
  657. engineType: [ EngineType.HalfFloatType ],
  658. priorityHDR: 100,
  659. needsPowerOfTwo: false,
  660. }
  661. ];
  662. const OPTIONS = {
  663. [ BasisFormat.ETC1S ]: FORMAT_OPTIONS
  664. .filter( ( opt ) => opt.basisFormat.includes( BasisFormat.ETC1S ) )
  665. .sort( ( a, b ) => a.priorityETC1S - b.priorityETC1S ),
  666. [ BasisFormat.UASTC ]: FORMAT_OPTIONS
  667. .filter( ( opt ) => opt.basisFormat.includes( BasisFormat.UASTC ) )
  668. .sort( ( a, b ) => a.priorityUASTC - b.priorityUASTC ),
  669. [ BasisFormat.UASTC_HDR ]: FORMAT_OPTIONS
  670. .filter( ( opt ) => opt.basisFormat.includes( BasisFormat.UASTC_HDR ) )
  671. .sort( ( a, b ) => a.priorityHDR - b.priorityHDR ),
  672. };
  673. function getTranscoderFormat( basisFormat, width, height, hasAlpha ) {
  674. const options = OPTIONS[ basisFormat ];
  675. for ( let i = 0; i < options.length; i ++ ) {
  676. const opt = options[ i ];
  677. if ( opt.if && ! config[ opt.if ] ) continue;
  678. if ( ! opt.basisFormat.includes( basisFormat ) ) continue;
  679. if ( hasAlpha && opt.transcoderFormat.length < 2 ) continue;
  680. if ( opt.needsPowerOfTwo && ! ( isPowerOfTwo( width ) && isPowerOfTwo( height ) ) ) continue;
  681. const transcoderFormat = opt.transcoderFormat[ hasAlpha ? 1 : 0 ];
  682. const engineFormat = opt.engineFormat[ hasAlpha ? 1 : 0 ];
  683. const engineType = opt.engineType[ 0 ];
  684. return { transcoderFormat, engineFormat, engineType };
  685. }
  686. throw new Error( 'THREE.KTX2Loader: Failed to identify transcoding target.' );
  687. }
  688. function isPowerOfTwo( value ) {
  689. if ( value <= 2 ) return true;
  690. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  691. }
  692. /**
  693. * Concatenates N byte arrays.
  694. *
  695. * @param {Uint8Array[]} arrays
  696. * @return {Uint8Array}
  697. */
  698. function concat( arrays ) {
  699. if ( arrays.length === 1 ) return arrays[ 0 ];
  700. let totalByteLength = 0;
  701. for ( let i = 0; i < arrays.length; i ++ ) {
  702. const array = arrays[ i ];
  703. totalByteLength += array.byteLength;
  704. }
  705. const result = new Uint8Array( totalByteLength );
  706. let byteOffset = 0;
  707. for ( let i = 0; i < arrays.length; i ++ ) {
  708. const array = arrays[ i ];
  709. result.set( array, byteOffset );
  710. byteOffset += array.byteLength;
  711. }
  712. return result;
  713. }
  714. };
  715. // Parsing for non-Basis textures. These textures may have supercompression
  716. // like Zstd, but they do not require transcoding.
  717. const UNCOMPRESSED_FORMATS = new Set( [ RGBAFormat, RGBFormat, RGFormat, RedFormat ] );
  718. const NORMALIZED_VK_FORMATS = new Set( [ VK_FORMAT_R16G16B16A16_UNORM ] );
  719. const FORMAT_MAP = {
  720. [ VK_FORMAT_R32G32B32A32_SFLOAT ]: RGBAFormat,
  721. [ VK_FORMAT_R32G32_SFLOAT ]: RGFormat,
  722. [ VK_FORMAT_R32_SFLOAT ]: RedFormat,
  723. [ VK_FORMAT_R16G16B16A16_SFLOAT ]: RGBAFormat,
  724. [ VK_FORMAT_R16G16_SFLOAT ]: RGFormat,
  725. [ VK_FORMAT_R16_SFLOAT ]: RedFormat,
  726. [ VK_FORMAT_R16G16B16A16_UNORM ]: RGBAFormat,
  727. [ VK_FORMAT_R8G8B8A8_SRGB ]: RGBAFormat,
  728. [ VK_FORMAT_R8G8B8A8_UNORM ]: RGBAFormat,
  729. [ VK_FORMAT_R8G8_SRGB ]: RGFormat,
  730. [ VK_FORMAT_R8G8_UNORM ]: RGFormat,
  731. [ VK_FORMAT_R8_SRGB ]: RedFormat,
  732. [ VK_FORMAT_R8_UNORM ]: RedFormat,
  733. [ VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 ]: RGBFormat,
  734. [ VK_FORMAT_B10G11R11_UFLOAT_PACK32 ]: RGBFormat,
  735. [ VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK ]: RGBA_ETC2_EAC_Format,
  736. [ VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK ]: RGB_ETC2_Format,
  737. [ VK_FORMAT_EAC_R11_UNORM_BLOCK ]: R11_EAC_Format,
  738. [ VK_FORMAT_EAC_R11_SNORM_BLOCK ]: SIGNED_R11_EAC_Format,
  739. [ VK_FORMAT_EAC_R11G11_UNORM_BLOCK ]: RG11_EAC_Format,
  740. [ VK_FORMAT_EAC_R11G11_SNORM_BLOCK ]: SIGNED_RG11_EAC_Format,
  741. [ VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT ]: RGBA_ASTC_4x4_Format,
  742. [ VK_FORMAT_ASTC_4x4_SRGB_BLOCK ]: RGBA_ASTC_4x4_Format,
  743. [ VK_FORMAT_ASTC_4x4_UNORM_BLOCK ]: RGBA_ASTC_4x4_Format,
  744. [ VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT ]: RGBA_ASTC_6x6_Format,
  745. [ VK_FORMAT_ASTC_6x6_SRGB_BLOCK ]: RGBA_ASTC_6x6_Format,
  746. [ VK_FORMAT_ASTC_6x6_UNORM_BLOCK ]: RGBA_ASTC_6x6_Format,
  747. [ VK_FORMAT_BC1_RGBA_SRGB_BLOCK ]: RGBA_S3TC_DXT1_Format,
  748. [ VK_FORMAT_BC1_RGBA_UNORM_BLOCK ]: RGBA_S3TC_DXT1_Format,
  749. [ VK_FORMAT_BC1_RGB_SRGB_BLOCK ]: RGB_S3TC_DXT1_Format,
  750. [ VK_FORMAT_BC1_RGB_UNORM_BLOCK ]: RGB_S3TC_DXT1_Format,
  751. [ VK_FORMAT_BC3_SRGB_BLOCK ]: RGBA_S3TC_DXT5_Format,
  752. [ VK_FORMAT_BC3_UNORM_BLOCK ]: RGBA_S3TC_DXT5_Format,
  753. [ VK_FORMAT_BC4_SNORM_BLOCK ]: SIGNED_RED_RGTC1_Format,
  754. [ VK_FORMAT_BC4_UNORM_BLOCK ]: RED_RGTC1_Format,
  755. [ VK_FORMAT_BC5_SNORM_BLOCK ]: SIGNED_RED_GREEN_RGTC2_Format,
  756. [ VK_FORMAT_BC5_UNORM_BLOCK ]: RED_GREEN_RGTC2_Format,
  757. [ VK_FORMAT_BC7_SRGB_BLOCK ]: RGBA_BPTC_Format,
  758. [ VK_FORMAT_BC7_UNORM_BLOCK ]: RGBA_BPTC_Format,
  759. [ VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG ]: RGBA_PVRTC_4BPPV1_Format,
  760. [ VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG ]: RGBA_PVRTC_4BPPV1_Format,
  761. [ VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG ]: RGBA_PVRTC_2BPPV1_Format,
  762. [ VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG ]: RGBA_PVRTC_2BPPV1_Format,
  763. };
  764. const TYPE_MAP = {
  765. [ VK_FORMAT_R32G32B32A32_SFLOAT ]: FloatType,
  766. [ VK_FORMAT_R32G32_SFLOAT ]: FloatType,
  767. [ VK_FORMAT_R32_SFLOAT ]: FloatType,
  768. [ VK_FORMAT_R16G16B16A16_SFLOAT ]: HalfFloatType,
  769. [ VK_FORMAT_R16G16_SFLOAT ]: HalfFloatType,
  770. [ VK_FORMAT_R16_SFLOAT ]: HalfFloatType,
  771. [ VK_FORMAT_R16G16B16A16_UNORM ]: UnsignedShortType,
  772. [ VK_FORMAT_R8G8B8A8_SRGB ]: UnsignedByteType,
  773. [ VK_FORMAT_R8G8B8A8_UNORM ]: UnsignedByteType,
  774. [ VK_FORMAT_R8G8_SRGB ]: UnsignedByteType,
  775. [ VK_FORMAT_R8G8_UNORM ]: UnsignedByteType,
  776. [ VK_FORMAT_R8_SRGB ]: UnsignedByteType,
  777. [ VK_FORMAT_R8_UNORM ]: UnsignedByteType,
  778. [ VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 ]: UnsignedInt5999Type,
  779. [ VK_FORMAT_B10G11R11_UFLOAT_PACK32 ]: UnsignedInt101111Type,
  780. [ VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK ]: UnsignedByteType,
  781. [ VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK ]: UnsignedByteType,
  782. [ VK_FORMAT_EAC_R11_UNORM_BLOCK ]: UnsignedByteType,
  783. [ VK_FORMAT_EAC_R11_SNORM_BLOCK ]: UnsignedByteType,
  784. [ VK_FORMAT_EAC_R11G11_UNORM_BLOCK ]: UnsignedByteType,
  785. [ VK_FORMAT_EAC_R11G11_SNORM_BLOCK ]: UnsignedByteType,
  786. [ VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT ]: HalfFloatType,
  787. [ VK_FORMAT_ASTC_4x4_SRGB_BLOCK ]: UnsignedByteType,
  788. [ VK_FORMAT_ASTC_4x4_UNORM_BLOCK ]: UnsignedByteType,
  789. [ VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT ]: HalfFloatType,
  790. [ VK_FORMAT_ASTC_6x6_SRGB_BLOCK ]: UnsignedByteType,
  791. [ VK_FORMAT_ASTC_6x6_UNORM_BLOCK ]: UnsignedByteType,
  792. [ VK_FORMAT_BC1_RGBA_SRGB_BLOCK ]: UnsignedByteType,
  793. [ VK_FORMAT_BC1_RGBA_UNORM_BLOCK ]: UnsignedByteType,
  794. [ VK_FORMAT_BC1_RGB_SRGB_BLOCK ]: UnsignedByteType,
  795. [ VK_FORMAT_BC1_RGB_UNORM_BLOCK ]: UnsignedByteType,
  796. [ VK_FORMAT_BC3_SRGB_BLOCK ]: UnsignedByteType,
  797. [ VK_FORMAT_BC3_UNORM_BLOCK ]: UnsignedByteType,
  798. [ VK_FORMAT_BC4_SNORM_BLOCK ]: UnsignedByteType,
  799. [ VK_FORMAT_BC4_UNORM_BLOCK ]: UnsignedByteType,
  800. [ VK_FORMAT_BC5_SNORM_BLOCK ]: UnsignedByteType,
  801. [ VK_FORMAT_BC5_UNORM_BLOCK ]: UnsignedByteType,
  802. [ VK_FORMAT_BC7_SRGB_BLOCK ]: UnsignedByteType,
  803. [ VK_FORMAT_BC7_UNORM_BLOCK ]: UnsignedByteType,
  804. [ VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG ]: UnsignedByteType,
  805. [ VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG ]: UnsignedByteType,
  806. [ VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG ]: UnsignedByteType,
  807. [ VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG ]: UnsignedByteType,
  808. };
  809. async function createRawTexture( container ) {
  810. const { vkFormat } = container;
  811. if ( FORMAT_MAP[ vkFormat ] === undefined ) {
  812. throw new Error( 'THREE.KTX2Loader: Unsupported vkFormat: ' + vkFormat );
  813. }
  814. // TODO: Merge the TYPE_MAP warning into the thrown error above, after r190.
  815. if ( TYPE_MAP[ vkFormat ] === undefined ) {
  816. console.warn( 'THREE.KTX2Loader: Missing ".type" for vkFormat: ' + vkFormat );
  817. }
  818. //
  819. let zstd;
  820. if ( container.supercompressionScheme === KHR_SUPERCOMPRESSION_ZSTD ) {
  821. if ( ! _zstd ) {
  822. _zstd = new Promise( async ( resolve ) => {
  823. const zstd = new ZSTDDecoder();
  824. await zstd.init();
  825. resolve( zstd );
  826. } );
  827. }
  828. zstd = await _zstd;
  829. }
  830. //
  831. const mipmaps = [];
  832. for ( let levelIndex = 0; levelIndex < container.levels.length; levelIndex ++ ) {
  833. const levelWidth = Math.max( 1, container.pixelWidth >> levelIndex );
  834. const levelHeight = Math.max( 1, container.pixelHeight >> levelIndex );
  835. const levelDepth = container.pixelDepth ? Math.max( 1, container.pixelDepth >> levelIndex ) : 0;
  836. const level = container.levels[ levelIndex ];
  837. let levelData;
  838. if ( container.supercompressionScheme === KHR_SUPERCOMPRESSION_NONE ) {
  839. levelData = level.levelData;
  840. } else if ( container.supercompressionScheme === KHR_SUPERCOMPRESSION_ZSTD ) {
  841. levelData = zstd.decode( level.levelData, level.uncompressedByteLength );
  842. } else {
  843. throw new Error( 'THREE.KTX2Loader: Unsupported supercompressionScheme.' );
  844. }
  845. let data;
  846. if ( TYPE_MAP[ vkFormat ] === FloatType ) {
  847. data = new Float32Array(
  848. levelData.buffer,
  849. levelData.byteOffset,
  850. levelData.byteLength / Float32Array.BYTES_PER_ELEMENT
  851. );
  852. } else if ( TYPE_MAP[ vkFormat ] === HalfFloatType || TYPE_MAP[ vkFormat ] === UnsignedShortType ) {
  853. data = new Uint16Array(
  854. levelData.buffer,
  855. levelData.byteOffset,
  856. levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT
  857. );
  858. } else if ( TYPE_MAP[ vkFormat ] === UnsignedInt5999Type || TYPE_MAP[ vkFormat ] === UnsignedInt101111Type ) {
  859. data = new Uint32Array(
  860. levelData.buffer,
  861. levelData.byteOffset,
  862. levelData.byteLength / Uint32Array.BYTES_PER_ELEMENT
  863. );
  864. } else {
  865. data = levelData;
  866. }
  867. mipmaps.push( {
  868. data: data,
  869. width: levelWidth,
  870. height: levelHeight,
  871. depth: levelDepth,
  872. } );
  873. }
  874. // levelCount = 0 implies runtime-generated mipmaps.
  875. const useMipmaps = container.levelCount === 0 || mipmaps.length > 1;
  876. let texture;
  877. if ( UNCOMPRESSED_FORMATS.has( FORMAT_MAP[ vkFormat ] ) ) {
  878. texture = container.pixelDepth === 0
  879. ? new DataTexture( mipmaps[ 0 ].data, container.pixelWidth, container.pixelHeight )
  880. : new Data3DTexture( mipmaps[ 0 ].data, container.pixelWidth, container.pixelHeight, container.pixelDepth );
  881. texture.minFilter = useMipmaps ? NearestMipmapNearestFilter : NearestFilter;
  882. texture.magFilter = NearestFilter;
  883. texture.generateMipmaps = container.levelCount === 0;
  884. texture.normalized = NORMALIZED_VK_FORMATS.has( vkFormat );
  885. } else {
  886. if ( container.pixelDepth > 0 ) throw new Error( 'THREE.KTX2Loader: Unsupported pixelDepth.' );
  887. texture = new CompressedTexture( mipmaps, container.pixelWidth, container.pixelHeight );
  888. texture.minFilter = useMipmaps ? LinearMipmapLinearFilter : LinearFilter;
  889. texture.magFilter = LinearFilter;
  890. }
  891. texture.mipmaps = mipmaps;
  892. texture.type = TYPE_MAP[ vkFormat ];
  893. texture.format = FORMAT_MAP[ vkFormat ];
  894. texture.colorSpace = parseColorSpace( container );
  895. texture.needsUpdate = true;
  896. //
  897. return Promise.resolve( texture );
  898. }
  899. function parseColorSpace( container ) {
  900. const dfd = container.dataFormatDescriptor[ 0 ];
  901. if ( dfd.colorPrimaries === KHR_DF_PRIMARIES_BT709 ) {
  902. return dfd.transferFunction === KHR_DF_TRANSFER_SRGB ? SRGBColorSpace : LinearSRGBColorSpace;
  903. } else if ( dfd.colorPrimaries === KHR_DF_PRIMARIES_DISPLAYP3 ) {
  904. return dfd.transferFunction === KHR_DF_TRANSFER_SRGB ? DisplayP3ColorSpace : LinearDisplayP3ColorSpace;
  905. } else if ( dfd.colorPrimaries === KHR_DF_PRIMARIES_UNSPECIFIED ) {
  906. return NoColorSpace;
  907. } else {
  908. console.warn( `THREE.KTX2Loader: Unsupported color primaries, "${ dfd.colorPrimaries }"` );
  909. return NoColorSpace;
  910. }
  911. }
  912. export { KTX2Loader };
粤ICP备19079148号