KTX2Loader.js 34 KB

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