KTX2Loader.js 14 KB

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