KTX2Loader.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. ( function () {
  2. /**
  3. * THREE.Loader for KTX 2.0 GPU Texture containers.
  4. *
  5. * KTX 2.0 is a container format for various GPU texture formats. The loader
  6. * supports Basis Universal GPU textures, which can be quickly transcoded to
  7. * a wide variety of GPU texture compression formats. While KTX 2.0 also allows
  8. * other hardware-specific formats, this loader does not yet parse them.
  9. *
  10. * References:
  11. * - KTX: http://github.khronos.org/KTX-Specification/
  12. * - DFD: https://www.khronos.org/registry/DataFormat/specs/1.3/dataformat.1.3.html#basicdescriptor
  13. */
  14. const KTX2TransferSRGB = 2;
  15. const KTX2_ALPHA_PREMULTIPLIED = 1;
  16. const _taskCache = new WeakMap();
  17. let _activeLoaders = 0;
  18. class KTX2Loader extends THREE.Loader {
  19. constructor( manager ) {
  20. super( manager );
  21. this.transcoderPath = '';
  22. this.transcoderBinary = null;
  23. this.transcoderPending = null;
  24. this.workerPool = new THREE.WorkerPool();
  25. this.workerSourceURL = '';
  26. this.workerConfig = null;
  27. if ( typeof MSC_TRANSCODER !== 'undefined' ) {
  28. console.warn( 'THREE.KTX2Loader: Please update to latest "basis_transcoder".' + ' "msc_basis_transcoder" is no longer supported in three.js r125+.' );
  29. }
  30. }
  31. setTranscoderPath( path ) {
  32. this.transcoderPath = path;
  33. return this;
  34. }
  35. setWorkerLimit( num ) {
  36. this.workerPool.setWorkerLimit( num );
  37. return this;
  38. }
  39. detectSupport( renderer ) {
  40. this.workerConfig = {
  41. astcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_astc' ),
  42. etc1Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc1' ),
  43. etc2Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc' ),
  44. dxtSupported: renderer.extensions.has( 'WEBGL_compressed_texture_s3tc' ),
  45. bptcSupported: renderer.extensions.has( 'EXT_texture_compression_bptc' ),
  46. pvrtcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_pvrtc' ) || renderer.extensions.has( 'WEBKIT_WEBGL_compressed_texture_pvrtc' )
  47. };
  48. return this;
  49. }
  50. dispose() {
  51. this.workerPool.dispose();
  52. if ( this.workerSourceURL ) URL.revokeObjectURL( this.workerSourceURL );
  53. return this;
  54. }
  55. init() {
  56. if ( ! this.transcoderPending ) {
  57. // Load transcoder wrapper.
  58. const jsLoader = new THREE.FileLoader( this.manager );
  59. jsLoader.setPath( this.transcoderPath );
  60. jsLoader.setWithCredentials( this.withCredentials );
  61. const jsContent = jsLoader.loadAsync( 'basis_transcoder.js' ); // Load transcoder WASM binary.
  62. const binaryLoader = new THREE.FileLoader( this.manager );
  63. binaryLoader.setPath( this.transcoderPath );
  64. binaryLoader.setResponseType( 'arraybuffer' );
  65. binaryLoader.setWithCredentials( this.withCredentials );
  66. const binaryContent = binaryLoader.loadAsync( 'basis_transcoder.wasm' );
  67. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] ).then( ( [ jsContent, binaryContent ] ) => {
  68. const fn = KTX2Loader.BasisWorker.toString();
  69. const body = [ '/* constants */', 'let _EngineFormat = ' + JSON.stringify( KTX2Loader.EngineFormat ), 'let _TranscoderFormat = ' + JSON.stringify( KTX2Loader.TranscoderFormat ), 'let _BasisFormat = ' + JSON.stringify( KTX2Loader.BasisFormat ), '/* basis_transcoder.js */', jsContent, '/* worker */', fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) ) ].join( '\n' );
  70. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  71. this.transcoderBinary = binaryContent;
  72. this.workerPool.setWorkerCreator( () => {
  73. const worker = new Worker( this.workerSourceURL );
  74. const transcoderBinary = this.transcoderBinary.slice( 0 );
  75. worker.postMessage( {
  76. type: 'init',
  77. config: this.workerConfig,
  78. transcoderBinary
  79. }, [ transcoderBinary ] );
  80. return worker;
  81. } );
  82. } );
  83. if ( _activeLoaders > 0 ) {
  84. // Each instance loads a transcoder and allocates workers, increasing network and memory cost.
  85. console.warn( 'THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues.' + ' Use a single KTX2Loader instance, or call .dispose() on old instances.' );
  86. }
  87. _activeLoaders ++;
  88. }
  89. return this.transcoderPending;
  90. }
  91. load( url, onLoad, onProgress, onError ) {
  92. if ( this.workerConfig === null ) {
  93. throw new Error( 'THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.' );
  94. }
  95. const loader = new THREE.FileLoader( this.manager );
  96. loader.setResponseType( 'arraybuffer' );
  97. loader.setWithCredentials( this.withCredentials );
  98. const texture = new THREE.CompressedTexture();
  99. loader.load( url, buffer => {
  100. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  101. // again from this thread.
  102. if ( _taskCache.has( buffer ) ) {
  103. const cachedTask = _taskCache.get( buffer );
  104. return cachedTask.promise.then( onLoad ).catch( onError );
  105. }
  106. this._createTexture( [ buffer ] ).then( function ( _texture ) {
  107. texture.copy( _texture );
  108. texture.needsUpdate = true;
  109. if ( onLoad ) onLoad( texture );
  110. } ).catch( onError );
  111. }, onProgress, onError );
  112. return texture;
  113. }
  114. _createTextureFrom( transcodeResult ) {
  115. const {
  116. mipmaps,
  117. width,
  118. height,
  119. format,
  120. type,
  121. error,
  122. dfdTransferFn,
  123. dfdFlags
  124. } = transcodeResult;
  125. if ( type === 'error' ) return Promise.reject( error );
  126. const texture = new THREE.CompressedTexture( mipmaps, width, height, format, THREE.UnsignedByteType );
  127. texture.minFilter = mipmaps.length === 1 ? THREE.LinearFilter : THREE.LinearMipmapLinearFilter;
  128. texture.magFilter = THREE.LinearFilter;
  129. texture.generateMipmaps = false;
  130. texture.needsUpdate = true;
  131. texture.encoding = dfdTransferFn === KTX2TransferSRGB ? THREE.sRGBEncoding : THREE.LinearEncoding;
  132. texture.premultiplyAlpha = !! ( dfdFlags & KTX2_ALPHA_PREMULTIPLIED );
  133. return texture;
  134. }
  135. /**
  136. * @param {ArrayBuffer[]} buffers
  137. * @param {object?} config
  138. * @return {Promise<CompressedTexture>}
  139. */
  140. _createTexture( buffers, config = {} ) {
  141. const taskConfig = config;
  142. const texturePending = this.init().then( () => {
  143. return this.workerPool.postMessage( {
  144. type: 'transcode',
  145. buffers,
  146. taskConfig: taskConfig
  147. }, buffers );
  148. } ).then( e => this._createTextureFrom( e.data ) ); // Cache the task result.
  149. _taskCache.set( buffers[ 0 ], {
  150. promise: texturePending
  151. } );
  152. return texturePending;
  153. }
  154. dispose() {
  155. URL.revokeObjectURL( this.workerSourceURL );
  156. this.workerPool.dispose();
  157. _activeLoaders --;
  158. return this;
  159. }
  160. }
  161. /* CONSTANTS */
  162. KTX2Loader.BasisFormat = {
  163. ETC1S: 0,
  164. UASTC_4x4: 1
  165. };
  166. KTX2Loader.TranscoderFormat = {
  167. ETC1: 0,
  168. ETC2: 1,
  169. BC1: 2,
  170. BC3: 3,
  171. BC4: 4,
  172. BC5: 5,
  173. BC7_M6_OPAQUE_ONLY: 6,
  174. BC7_M5: 7,
  175. PVRTC1_4_RGB: 8,
  176. PVRTC1_4_RGBA: 9,
  177. ASTC_4x4: 10,
  178. ATC_RGB: 11,
  179. ATC_RGBA_INTERPOLATED_ALPHA: 12,
  180. RGBA32: 13,
  181. RGB565: 14,
  182. BGR565: 15,
  183. RGBA4444: 16
  184. };
  185. KTX2Loader.EngineFormat = {
  186. RGBAFormat: THREE.RGBAFormat,
  187. RGBA_ASTC_4x4_Format: THREE.RGBA_ASTC_4x4_Format,
  188. RGBA_BPTC_Format: THREE.RGBA_BPTC_Format,
  189. RGBA_ETC2_EAC_Format: THREE.RGBA_ETC2_EAC_Format,
  190. RGBA_PVRTC_4BPPV1_Format: THREE.RGBA_PVRTC_4BPPV1_Format,
  191. RGBA_S3TC_DXT5_Format: THREE.RGBA_S3TC_DXT5_Format,
  192. RGB_ETC1_Format: THREE.RGB_ETC1_Format,
  193. RGB_ETC2_Format: THREE.RGB_ETC2_Format,
  194. RGB_PVRTC_4BPPV1_Format: THREE.RGB_PVRTC_4BPPV1_Format,
  195. RGB_S3TC_DXT1_Format: THREE.RGB_S3TC_DXT1_Format
  196. };
  197. /* WEB WORKER */
  198. KTX2Loader.BasisWorker = function () {
  199. let config;
  200. let transcoderPending;
  201. let BasisModule;
  202. const EngineFormat = _EngineFormat; // eslint-disable-line no-undef
  203. const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef
  204. const BasisFormat = _BasisFormat; // eslint-disable-line no-undef
  205. self.addEventListener( 'message', function ( e ) {
  206. const message = e.data;
  207. switch ( message.type ) {
  208. case 'init':
  209. config = message.config;
  210. init( message.transcoderBinary );
  211. break;
  212. case 'transcode':
  213. transcoderPending.then( () => {
  214. try {
  215. const {
  216. width,
  217. height,
  218. hasAlpha,
  219. mipmaps,
  220. format,
  221. dfdTransferFn,
  222. dfdFlags
  223. } = transcode( message.buffers[ 0 ] );
  224. const buffers = [];
  225. for ( let i = 0; i < mipmaps.length; ++ i ) {
  226. buffers.push( mipmaps[ i ].data.buffer );
  227. }
  228. self.postMessage( {
  229. type: 'transcode',
  230. id: message.id,
  231. width,
  232. height,
  233. hasAlpha,
  234. mipmaps,
  235. format,
  236. dfdTransferFn,
  237. dfdFlags
  238. }, buffers );
  239. } catch ( error ) {
  240. console.error( error );
  241. self.postMessage( {
  242. type: 'error',
  243. id: message.id,
  244. error: error.message
  245. } );
  246. }
  247. } );
  248. break;
  249. }
  250. } );
  251. function init( wasmBinary ) {
  252. transcoderPending = new Promise( resolve => {
  253. BasisModule = {
  254. wasmBinary,
  255. onRuntimeInitialized: resolve
  256. };
  257. BASIS( BasisModule ); // eslint-disable-line no-undef
  258. } ).then( () => {
  259. BasisModule.initializeBasis();
  260. if ( BasisModule.KTX2File === undefined ) {
  261. console.warn( 'THREE.KTX2Loader: Please update Basis Universal transcoder.' );
  262. }
  263. } );
  264. }
  265. function transcode( buffer ) {
  266. const ktx2File = new BasisModule.KTX2File( new Uint8Array( buffer ) );
  267. function cleanup() {
  268. ktx2File.close();
  269. ktx2File.delete();
  270. }
  271. if ( ! ktx2File.isValid() ) {
  272. cleanup();
  273. throw new Error( 'THREE.KTX2Loader: Invalid or unsupported .ktx2 file' );
  274. }
  275. const basisFormat = ktx2File.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S;
  276. const width = ktx2File.getWidth();
  277. const height = ktx2File.getHeight();
  278. const levels = ktx2File.getLevels();
  279. const hasAlpha = ktx2File.getHasAlpha();
  280. const dfdTransferFn = ktx2File.getDFDTransferFunc();
  281. const dfdFlags = ktx2File.getDFDFlags();
  282. const {
  283. transcoderFormat,
  284. engineFormat
  285. } = getTranscoderFormat( basisFormat, width, height, hasAlpha );
  286. if ( ! width || ! height || ! levels ) {
  287. cleanup();
  288. throw new Error( 'THREE.KTX2Loader: Invalid texture' );
  289. }
  290. if ( ! ktx2File.startTranscoding() ) {
  291. cleanup();
  292. throw new Error( 'THREE.KTX2Loader: .startTranscoding failed' );
  293. }
  294. const mipmaps = [];
  295. for ( let mip = 0; mip < levels; mip ++ ) {
  296. const levelInfo = ktx2File.getImageLevelInfo( mip, 0, 0 );
  297. const mipWidth = levelInfo.origWidth;
  298. const mipHeight = levelInfo.origHeight;
  299. const dst = new Uint8Array( ktx2File.getImageTranscodedSizeInBytes( mip, 0, 0, transcoderFormat ) );
  300. const status = ktx2File.transcodeImage( dst, mip, 0, 0, transcoderFormat, 0, - 1, - 1 );
  301. if ( ! status ) {
  302. cleanup();
  303. throw new Error( 'THREE.KTX2Loader: .transcodeImage failed.' );
  304. }
  305. mipmaps.push( {
  306. data: dst,
  307. width: mipWidth,
  308. height: mipHeight
  309. } );
  310. }
  311. cleanup();
  312. return {
  313. width,
  314. height,
  315. hasAlpha,
  316. mipmaps,
  317. format: engineFormat,
  318. dfdTransferFn,
  319. dfdFlags
  320. };
  321. } //
  322. // Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC),
  323. // device capabilities, and texture dimensions. The list below ranks the formats separately
  324. // for ETC1S and UASTC.
  325. //
  326. // In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at
  327. // significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently
  328. // chooses RGBA32 only as a last resort and does not expose that option to the caller.
  329. const FORMAT_OPTIONS = [ {
  330. if: 'astcSupported',
  331. basisFormat: [ BasisFormat.UASTC_4x4 ],
  332. transcoderFormat: [ TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4 ],
  333. engineFormat: [ EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format ],
  334. priorityETC1S: Infinity,
  335. priorityUASTC: 1,
  336. needsPowerOfTwo: false
  337. }, {
  338. if: 'bptcSupported',
  339. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  340. transcoderFormat: [ TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5 ],
  341. engineFormat: [ EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format ],
  342. priorityETC1S: 3,
  343. priorityUASTC: 2,
  344. needsPowerOfTwo: false
  345. }, {
  346. if: 'dxtSupported',
  347. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  348. transcoderFormat: [ TranscoderFormat.BC1, TranscoderFormat.BC3 ],
  349. engineFormat: [ EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format ],
  350. priorityETC1S: 4,
  351. priorityUASTC: 5,
  352. needsPowerOfTwo: false
  353. }, {
  354. if: 'etc2Supported',
  355. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  356. transcoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC2 ],
  357. engineFormat: [ EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format ],
  358. priorityETC1S: 1,
  359. priorityUASTC: 3,
  360. needsPowerOfTwo: false
  361. }, {
  362. if: 'etc1Supported',
  363. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  364. transcoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC1 ],
  365. engineFormat: [ EngineFormat.RGB_ETC1_Format, EngineFormat.RGB_ETC1_Format ],
  366. priorityETC1S: 2,
  367. priorityUASTC: 4,
  368. needsPowerOfTwo: false
  369. }, {
  370. if: 'pvrtcSupported',
  371. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  372. transcoderFormat: [ TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA ],
  373. engineFormat: [ EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format ],
  374. priorityETC1S: 5,
  375. priorityUASTC: 6,
  376. needsPowerOfTwo: true
  377. } ];
  378. const ETC1S_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  379. return a.priorityETC1S - b.priorityETC1S;
  380. } );
  381. const UASTC_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  382. return a.priorityUASTC - b.priorityUASTC;
  383. } );
  384. function getTranscoderFormat( basisFormat, width, height, hasAlpha ) {
  385. let transcoderFormat;
  386. let engineFormat;
  387. const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS;
  388. for ( let i = 0; i < options.length; i ++ ) {
  389. const opt = options[ i ];
  390. if ( ! config[ opt.if ] ) continue;
  391. if ( ! opt.basisFormat.includes( basisFormat ) ) continue;
  392. if ( opt.needsPowerOfTwo && ! ( isPowerOfTwo( width ) && isPowerOfTwo( height ) ) ) continue;
  393. transcoderFormat = opt.transcoderFormat[ hasAlpha ? 1 : 0 ];
  394. engineFormat = opt.engineFormat[ hasAlpha ? 1 : 0 ];
  395. return {
  396. transcoderFormat,
  397. engineFormat
  398. };
  399. }
  400. console.warn( 'THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32.' );
  401. transcoderFormat = TranscoderFormat.RGBA32;
  402. engineFormat = EngineFormat.RGBAFormat;
  403. return {
  404. transcoderFormat,
  405. engineFormat
  406. };
  407. }
  408. function isPowerOfTwo( value ) {
  409. if ( value <= 2 ) return true;
  410. return ( value & value - 1 ) === 0 && value !== 0;
  411. }
  412. };
  413. THREE.KTX2Loader = KTX2Loader;
  414. } )();