BasisTextureLoader.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. import {
  2. CompressedTexture,
  3. FileLoader,
  4. LinearFilter,
  5. LinearMipmapLinearFilter,
  6. Loader,
  7. RGBAFormat,
  8. RGBA_ASTC_4x4_Format,
  9. RGBA_BPTC_Format,
  10. RGBA_ETC2_EAC_Format,
  11. RGBA_PVRTC_4BPPV1_Format,
  12. RGBA_S3TC_DXT5_Format,
  13. RGB_ETC1_Format,
  14. RGB_ETC2_Format,
  15. RGB_PVRTC_4BPPV1_Format,
  16. RGB_S3TC_DXT1_Format,
  17. UnsignedByteType
  18. } from '../../../build/three.module.js';
  19. /**
  20. * Loader for Basis Universal GPU Texture Codec.
  21. *
  22. * Basis Universal is a "supercompressed" GPU texture and texture video
  23. * compression system that outputs a highly compressed intermediate file format
  24. * (.basis) that can be quickly transcoded to a wide variety of GPU texture
  25. * compression formats.
  26. *
  27. * This loader parallelizes the transcoding process across a configurable number
  28. * of web workers, before transferring the transcoded compressed texture back
  29. * to the main thread.
  30. */
  31. const _taskCache = new WeakMap();
  32. class BasisTextureLoader extends Loader {
  33. constructor( manager ) {
  34. super( manager );
  35. this.transcoderPath = '';
  36. this.transcoderBinary = null;
  37. this.transcoderPending = null;
  38. this.workerLimit = 4;
  39. this.workerPool = [];
  40. this.workerNextTaskID = 1;
  41. this.workerSourceURL = '';
  42. this.workerConfig = null;
  43. }
  44. setTranscoderPath( path ) {
  45. this.transcoderPath = path;
  46. return this;
  47. }
  48. setWorkerLimit( workerLimit ) {
  49. this.workerLimit = workerLimit;
  50. return this;
  51. }
  52. detectSupport( renderer ) {
  53. this.workerConfig = {
  54. astcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_astc' ),
  55. etc1Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc1' ),
  56. etc2Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc' ),
  57. dxtSupported: renderer.extensions.has( 'WEBGL_compressed_texture_s3tc' ),
  58. bptcSupported: renderer.extensions.has( 'EXT_texture_compression_bptc' ),
  59. pvrtcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_pvrtc' )
  60. || renderer.extensions.has( 'WEBKIT_WEBGL_compressed_texture_pvrtc' )
  61. };
  62. return this;
  63. }
  64. load( url, onLoad, onProgress, onError ) {
  65. const loader = new FileLoader( this.manager );
  66. loader.setResponseType( 'arraybuffer' );
  67. loader.setWithCredentials( this.withCredentials );
  68. const texture = new CompressedTexture();
  69. loader.load( url, ( buffer ) => {
  70. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  71. // again from this thread.
  72. if ( _taskCache.has( buffer ) ) {
  73. const cachedTask = _taskCache.get( buffer );
  74. return cachedTask.promise.then( onLoad ).catch( onError );
  75. }
  76. this._createTexture( [ buffer ] )
  77. .then( function ( _texture ) {
  78. texture.copy( _texture );
  79. texture.needsUpdate = true;
  80. if ( onLoad ) onLoad( texture );
  81. } )
  82. .catch( onError );
  83. }, onProgress, onError );
  84. return texture;
  85. }
  86. /** Low-level transcoding API, exposed for use by KTX2Loader. */
  87. parseInternalAsync( options ) {
  88. const { levels } = options;
  89. const buffers = new Set();
  90. for ( let i = 0; i < levels.length; i ++ ) {
  91. buffers.add( levels[ i ].data.buffer );
  92. }
  93. return this._createTexture( Array.from( buffers ), { ...options, lowLevel: true } );
  94. }
  95. /**
  96. * @param {ArrayBuffer[]} buffers
  97. * @param {object?} config
  98. * @return {Promise<CompressedTexture>}
  99. */
  100. _createTexture( buffers, config = {} ) {
  101. let worker;
  102. let taskID;
  103. const taskConfig = config;
  104. let taskCost = 0;
  105. for ( let i = 0; i < buffers.length; i ++ ) {
  106. taskCost += buffers[ i ].byteLength;
  107. }
  108. const texturePending = this._allocateWorker( taskCost )
  109. .then( ( _worker ) => {
  110. worker = _worker;
  111. taskID = this.workerNextTaskID ++;
  112. return new Promise( ( resolve, reject ) => {
  113. worker._callbacks[ taskID ] = { resolve, reject };
  114. worker.postMessage( { type: 'transcode', id: taskID, buffers: buffers, taskConfig: taskConfig }, buffers );
  115. } );
  116. } )
  117. .then( ( message ) => {
  118. const { mipmaps, width, height, format } = message;
  119. const texture = new CompressedTexture( mipmaps, width, height, format, UnsignedByteType );
  120. texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter;
  121. texture.magFilter = LinearFilter;
  122. texture.generateMipmaps = false;
  123. texture.needsUpdate = true;
  124. return texture;
  125. } );
  126. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  127. texturePending
  128. .catch( () => true )
  129. .then( () => {
  130. if ( worker && taskID ) {
  131. worker._taskLoad -= taskCost;
  132. delete worker._callbacks[ taskID ];
  133. }
  134. } );
  135. // Cache the task result.
  136. _taskCache.set( buffers[ 0 ], { promise: texturePending } );
  137. return texturePending;
  138. }
  139. _initTranscoder() {
  140. if ( ! this.transcoderPending ) {
  141. // Load transcoder wrapper.
  142. const jsLoader = new FileLoader( this.manager );
  143. jsLoader.setPath( this.transcoderPath );
  144. jsLoader.setWithCredentials( this.withCredentials );
  145. const jsContent = new Promise( ( resolve, reject ) => {
  146. jsLoader.load( 'basis_transcoder.js', resolve, undefined, reject );
  147. } );
  148. // Load transcoder WASM binary.
  149. const binaryLoader = new FileLoader( this.manager );
  150. binaryLoader.setPath( this.transcoderPath );
  151. binaryLoader.setResponseType( 'arraybuffer' );
  152. binaryLoader.setWithCredentials( this.withCredentials );
  153. const binaryContent = new Promise( ( resolve, reject ) => {
  154. binaryLoader.load( 'basis_transcoder.wasm', resolve, undefined, reject );
  155. } );
  156. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] )
  157. .then( ( [ jsContent, binaryContent ] ) => {
  158. const fn = BasisTextureLoader.BasisWorker.toString();
  159. const body = [
  160. '/* constants */',
  161. 'let _EngineFormat = ' + JSON.stringify( BasisTextureLoader.EngineFormat ),
  162. 'let _TranscoderFormat = ' + JSON.stringify( BasisTextureLoader.TranscoderFormat ),
  163. 'let _BasisFormat = ' + JSON.stringify( BasisTextureLoader.BasisFormat ),
  164. '/* basis_transcoder.js */',
  165. jsContent,
  166. '/* worker */',
  167. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  168. ].join( '\n' );
  169. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  170. this.transcoderBinary = binaryContent;
  171. } );
  172. }
  173. return this.transcoderPending;
  174. }
  175. _allocateWorker( taskCost ) {
  176. return this._initTranscoder().then( () => {
  177. if ( this.workerPool.length < this.workerLimit ) {
  178. const worker = new Worker( this.workerSourceURL );
  179. worker._callbacks = {};
  180. worker._taskLoad = 0;
  181. worker.postMessage( {
  182. type: 'init',
  183. config: this.workerConfig,
  184. transcoderBinary: this.transcoderBinary,
  185. } );
  186. worker.onmessage = function ( e ) {
  187. const message = e.data;
  188. switch ( message.type ) {
  189. case 'transcode':
  190. worker._callbacks[ message.id ].resolve( message );
  191. break;
  192. case 'error':
  193. worker._callbacks[ message.id ].reject( message );
  194. break;
  195. default:
  196. console.error( 'THREE.BasisTextureLoader: Unexpected message, "' + message.type + '"' );
  197. }
  198. };
  199. this.workerPool.push( worker );
  200. } else {
  201. this.workerPool.sort( function ( a, b ) {
  202. return a._taskLoad > b._taskLoad ? - 1 : 1;
  203. } );
  204. }
  205. const worker = this.workerPool[ this.workerPool.length - 1 ];
  206. worker._taskLoad += taskCost;
  207. return worker;
  208. } );
  209. }
  210. dispose() {
  211. for ( let i = 0; i < this.workerPool.length; i ++ ) {
  212. this.workerPool[ i ].terminate();
  213. }
  214. this.workerPool.length = 0;
  215. return this;
  216. }
  217. }
  218. /* CONSTANTS */
  219. BasisTextureLoader.BasisFormat = {
  220. ETC1S: 0,
  221. UASTC_4x4: 1,
  222. };
  223. BasisTextureLoader.TranscoderFormat = {
  224. ETC1: 0,
  225. ETC2: 1,
  226. BC1: 2,
  227. BC3: 3,
  228. BC4: 4,
  229. BC5: 5,
  230. BC7_M6_OPAQUE_ONLY: 6,
  231. BC7_M5: 7,
  232. PVRTC1_4_RGB: 8,
  233. PVRTC1_4_RGBA: 9,
  234. ASTC_4x4: 10,
  235. ATC_RGB: 11,
  236. ATC_RGBA_INTERPOLATED_ALPHA: 12,
  237. RGBA32: 13,
  238. RGB565: 14,
  239. BGR565: 15,
  240. RGBA4444: 16,
  241. };
  242. BasisTextureLoader.EngineFormat = {
  243. RGBAFormat: RGBAFormat,
  244. RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
  245. RGBA_BPTC_Format: RGBA_BPTC_Format,
  246. RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
  247. RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
  248. RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format,
  249. RGB_ETC1_Format: RGB_ETC1_Format,
  250. RGB_ETC2_Format: RGB_ETC2_Format,
  251. RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
  252. RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format,
  253. };
  254. /* WEB WORKER */
  255. BasisTextureLoader.BasisWorker = function () {
  256. let config;
  257. let transcoderPending;
  258. let BasisModule;
  259. const EngineFormat = _EngineFormat; // eslint-disable-line no-undef
  260. const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef
  261. const BasisFormat = _BasisFormat; // eslint-disable-line no-undef
  262. onmessage = function ( e ) {
  263. const message = e.data;
  264. switch ( message.type ) {
  265. case 'init':
  266. config = message.config;
  267. init( message.transcoderBinary );
  268. break;
  269. case 'transcode':
  270. transcoderPending.then( () => {
  271. try {
  272. const { width, height, hasAlpha, mipmaps, format } = message.taskConfig.lowLevel
  273. ? transcodeLowLevel( message.taskConfig )
  274. : transcode( message.buffers[ 0 ] );
  275. const buffers = [];
  276. for ( let i = 0; i < mipmaps.length; ++ i ) {
  277. buffers.push( mipmaps[ i ].data.buffer );
  278. }
  279. self.postMessage( { type: 'transcode', id: message.id, width, height, hasAlpha, mipmaps, format }, buffers );
  280. } catch ( error ) {
  281. console.error( error );
  282. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  283. }
  284. } );
  285. break;
  286. }
  287. };
  288. function init( wasmBinary ) {
  289. transcoderPending = new Promise( ( resolve ) => {
  290. BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
  291. BASIS( BasisModule ); // eslint-disable-line no-undef
  292. } ).then( () => {
  293. BasisModule.initializeBasis();
  294. } );
  295. }
  296. function transcodeLowLevel( taskConfig ) {
  297. const { basisFormat, width, height, hasAlpha } = taskConfig;
  298. const { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha );
  299. const blockByteLength = BasisModule.getBytesPerBlockOrPixel( transcoderFormat );
  300. assert( BasisModule.isFormatSupported( transcoderFormat ), 'THREE.BasisTextureLoader: Unsupported format.' );
  301. const mipmaps = [];
  302. if ( basisFormat === BasisFormat.ETC1S ) {
  303. const transcoder = new BasisModule.LowLevelETC1SImageTranscoder();
  304. const { endpointCount, endpointsData, selectorCount, selectorsData, tablesData } = taskConfig.globalData;
  305. try {
  306. let ok;
  307. ok = transcoder.decodePalettes( endpointCount, endpointsData, selectorCount, selectorsData );
  308. assert( ok, 'THREE.BasisTextureLoader: decodePalettes() failed.' );
  309. ok = transcoder.decodeTables( tablesData );
  310. assert( ok, 'THREE.BasisTextureLoader: decodeTables() failed.' );
  311. for ( let i = 0; i < taskConfig.levels.length; i ++ ) {
  312. const level = taskConfig.levels[ i ];
  313. const imageDesc = taskConfig.globalData.imageDescs[ i ];
  314. const dstByteLength = getTranscodedImageByteLength( transcoderFormat, level.width, level.height );
  315. const dst = new Uint8Array( dstByteLength );
  316. ok = transcoder.transcodeImage(
  317. transcoderFormat,
  318. dst, dstByteLength / blockByteLength,
  319. level.data,
  320. getWidthInBlocks( transcoderFormat, level.width ),
  321. getHeightInBlocks( transcoderFormat, level.height ),
  322. level.width, level.height, level.index,
  323. imageDesc.rgbSliceByteOffset, imageDesc.rgbSliceByteLength,
  324. imageDesc.alphaSliceByteOffset, imageDesc.alphaSliceByteLength,
  325. imageDesc.imageFlags,
  326. hasAlpha,
  327. false,
  328. 0, 0
  329. );
  330. assert( ok, 'THREE.BasisTextureLoader: transcodeImage() failed for level ' + level.index + '.' );
  331. mipmaps.push( { data: dst, width: level.width, height: level.height } );
  332. }
  333. } finally {
  334. transcoder.delete();
  335. }
  336. } else {
  337. for ( let i = 0; i < taskConfig.levels.length; i ++ ) {
  338. const level = taskConfig.levels[ i ];
  339. const dstByteLength = getTranscodedImageByteLength( transcoderFormat, level.width, level.height );
  340. const dst = new Uint8Array( dstByteLength );
  341. const ok = BasisModule.transcodeUASTCImage(
  342. transcoderFormat,
  343. dst, dstByteLength / blockByteLength,
  344. level.data,
  345. getWidthInBlocks( transcoderFormat, level.width ),
  346. getHeightInBlocks( transcoderFormat, level.height ),
  347. level.width, level.height, level.index,
  348. 0,
  349. level.data.byteLength,
  350. 0,
  351. hasAlpha,
  352. false,
  353. 0, 0,
  354. - 1, - 1
  355. );
  356. assert( ok, 'THREE.BasisTextureLoader: transcodeUASTCImage() failed for level ' + level.index + '.' );
  357. mipmaps.push( { data: dst, width: level.width, height: level.height } );
  358. }
  359. }
  360. return { width, height, hasAlpha, mipmaps, format: engineFormat };
  361. }
  362. function transcode( buffer ) {
  363. const basisFile = new BasisModule.BasisFile( new Uint8Array( buffer ) );
  364. const basisFormat = basisFile.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S;
  365. const width = basisFile.getImageWidth( 0, 0 );
  366. const height = basisFile.getImageHeight( 0, 0 );
  367. const levels = basisFile.getNumLevels( 0 );
  368. const hasAlpha = basisFile.getHasAlpha();
  369. function cleanup() {
  370. basisFile.close();
  371. basisFile.delete();
  372. }
  373. const { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha );
  374. if ( ! width || ! height || ! levels ) {
  375. cleanup();
  376. throw new Error( 'THREE.BasisTextureLoader: Invalid texture' );
  377. }
  378. if ( ! basisFile.startTranscoding() ) {
  379. cleanup();
  380. throw new Error( 'THREE.BasisTextureLoader: .startTranscoding failed' );
  381. }
  382. const mipmaps = [];
  383. for ( let mip = 0; mip < levels; mip ++ ) {
  384. const mipWidth = basisFile.getImageWidth( 0, mip );
  385. const mipHeight = basisFile.getImageHeight( 0, mip );
  386. const dst = new Uint8Array( basisFile.getImageTranscodedSizeInBytes( 0, mip, transcoderFormat ) );
  387. const status = basisFile.transcodeImage(
  388. dst,
  389. 0,
  390. mip,
  391. transcoderFormat,
  392. 0,
  393. hasAlpha
  394. );
  395. if ( ! status ) {
  396. cleanup();
  397. throw new Error( 'THREE.BasisTextureLoader: .transcodeImage failed.' );
  398. }
  399. mipmaps.push( { data: dst, width: mipWidth, height: mipHeight } );
  400. }
  401. cleanup();
  402. return { width, height, hasAlpha, mipmaps, format: engineFormat };
  403. }
  404. //
  405. // Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC),
  406. // device capabilities, and texture dimensions. The list below ranks the formats separately
  407. // for ETC1S and UASTC.
  408. //
  409. // In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at
  410. // significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently
  411. // chooses RGBA32 only as a last resort and does not expose that option to the caller.
  412. const FORMAT_OPTIONS = [
  413. {
  414. if: 'astcSupported',
  415. basisFormat: [ BasisFormat.UASTC_4x4 ],
  416. transcoderFormat: [ TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4 ],
  417. engineFormat: [ EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format ],
  418. priorityETC1S: Infinity,
  419. priorityUASTC: 1,
  420. needsPowerOfTwo: false,
  421. },
  422. {
  423. if: 'bptcSupported',
  424. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  425. transcoderFormat: [ TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5 ],
  426. engineFormat: [ EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format ],
  427. priorityETC1S: 3,
  428. priorityUASTC: 2,
  429. needsPowerOfTwo: false,
  430. },
  431. {
  432. if: 'dxtSupported',
  433. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  434. transcoderFormat: [ TranscoderFormat.BC1, TranscoderFormat.BC3 ],
  435. engineFormat: [ EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format ],
  436. priorityETC1S: 4,
  437. priorityUASTC: 5,
  438. needsPowerOfTwo: false,
  439. },
  440. {
  441. if: 'etc2Supported',
  442. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  443. transcoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC2 ],
  444. engineFormat: [ EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format ],
  445. priorityETC1S: 1,
  446. priorityUASTC: 3,
  447. needsPowerOfTwo: false,
  448. },
  449. {
  450. if: 'etc1Supported',
  451. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  452. transcoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC1 ],
  453. engineFormat: [ EngineFormat.RGB_ETC1_Format, EngineFormat.RGB_ETC1_Format ],
  454. priorityETC1S: 2,
  455. priorityUASTC: 4,
  456. needsPowerOfTwo: false,
  457. },
  458. {
  459. if: 'pvrtcSupported',
  460. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  461. transcoderFormat: [ TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA ],
  462. engineFormat: [ EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format ],
  463. priorityETC1S: 5,
  464. priorityUASTC: 6,
  465. needsPowerOfTwo: true,
  466. },
  467. ];
  468. const ETC1S_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  469. return a.priorityETC1S - b.priorityETC1S;
  470. } );
  471. const UASTC_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  472. return a.priorityUASTC - b.priorityUASTC;
  473. } );
  474. function getTranscoderFormat( basisFormat, width, height, hasAlpha ) {
  475. let transcoderFormat;
  476. let engineFormat;
  477. const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS;
  478. for ( let i = 0; i < options.length; i ++ ) {
  479. const opt = options[ i ];
  480. if ( ! config[ opt.if ] ) continue;
  481. if ( ! opt.basisFormat.includes( basisFormat ) ) continue;
  482. if ( opt.needsPowerOfTwo && ! ( isPowerOfTwo( width ) && isPowerOfTwo( height ) ) ) continue;
  483. transcoderFormat = opt.transcoderFormat[ hasAlpha ? 1 : 0 ];
  484. engineFormat = opt.engineFormat[ hasAlpha ? 1 : 0 ];
  485. return { transcoderFormat, engineFormat };
  486. }
  487. console.warn( 'THREE.BasisTextureLoader: No suitable compressed texture format found. Decoding to RGBA32.' );
  488. transcoderFormat = TranscoderFormat.RGBA32;
  489. engineFormat = EngineFormat.RGBAFormat;
  490. return { transcoderFormat, engineFormat };
  491. }
  492. function assert( ok, message ) {
  493. if ( ! ok ) throw new Error( message );
  494. }
  495. function getWidthInBlocks( transcoderFormat, width ) {
  496. return Math.ceil( width / BasisModule.getFormatBlockWidth( transcoderFormat ) );
  497. }
  498. function getHeightInBlocks( transcoderFormat, height ) {
  499. return Math.ceil( height / BasisModule.getFormatBlockHeight( transcoderFormat ) );
  500. }
  501. function getTranscodedImageByteLength( transcoderFormat, width, height ) {
  502. const blockByteLength = BasisModule.getBytesPerBlockOrPixel( transcoderFormat );
  503. if ( BasisModule.formatIsUncompressed( transcoderFormat ) ) {
  504. return width * height * blockByteLength;
  505. }
  506. if ( transcoderFormat === TranscoderFormat.PVRTC1_4_RGB
  507. || transcoderFormat === TranscoderFormat.PVRTC1_4_RGBA ) {
  508. // GL requires extra padding for very small textures:
  509. // https://www.khronos.org/registry/OpenGL/extensions/IMG/IMG_texture_compression_pvrtc.txt
  510. const paddedWidth = ( width + 3 ) & ~ 3;
  511. const paddedHeight = ( height + 3 ) & ~ 3;
  512. return ( Math.max( 8, paddedWidth ) * Math.max( 8, paddedHeight ) * 4 + 7 ) / 8;
  513. }
  514. return ( getWidthInBlocks( transcoderFormat, width )
  515. * getHeightInBlocks( transcoderFormat, height )
  516. * blockByteLength );
  517. }
  518. function isPowerOfTwo( value ) {
  519. if ( value <= 2 ) return true;
  520. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  521. }
  522. };
  523. export { BasisTextureLoader };