BasisTextureLoader.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. /**
  2. * @author Don McCurdy / https://www.donmccurdy.com
  3. * @author Austin Eng / https://github.com/austinEng
  4. * @author Shrek Shao / https://github.com/shrekshao
  5. * @author Senya Pugach / https://upisfr.ee
  6. */
  7. import {
  8. CompressedTexture,
  9. FileLoader,
  10. LinearFilter,
  11. LinearMipmapLinearFilter,
  12. Loader,
  13. RGBA_ASTC_4x4_Format,
  14. RGBA_BPTC_Format,
  15. RGBA_PVRTC_4BPPV1_Format,
  16. RGB_ETC1_Format,
  17. RGB_PVRTC_4BPPV1_Format,
  18. UnsignedByteType
  19. } from "../../../build/three.module.js";
  20. /**
  21. * Loader for Basis Universal GPU Texture Codec.
  22. *
  23. * Basis Universal is a "supercompressed" GPU texture and texture video
  24. * compression system that outputs a highly compressed intermediate file format
  25. * (.basis) that can be quickly transcoded to a wide variety of GPU texture
  26. * compression formats.
  27. *
  28. * This loader parallelizes the transcoding process across a configurable number
  29. * of web workers, before transferring the transcoded compressed texture back
  30. * to the main thread.
  31. */
  32. var BasisTextureLoader = function ( manager ) {
  33. Loader.call( this, manager );
  34. this.transcoderPath = '';
  35. this.transcoderBinary = null;
  36. this.transcoderPending = null;
  37. this.workerLimit = 4;
  38. this.workerPool = [];
  39. this.workerNextTaskID = 1;
  40. this.workerSourceURL = '';
  41. this.workerConfig = {
  42. format: null,
  43. astcSupported: false,
  44. bptcSupported: false,
  45. etcSupported: false,
  46. dxtSupported: false,
  47. pvrtcSupported: false,
  48. };
  49. };
  50. BasisTextureLoader.taskCache = new WeakMap();
  51. BasisTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  52. constructor: BasisTextureLoader,
  53. setTranscoderPath: function ( path ) {
  54. this.transcoderPath = path;
  55. return this;
  56. },
  57. setWorkerLimit: function ( workerLimit ) {
  58. this.workerLimit = workerLimit;
  59. return this;
  60. },
  61. detectSupport: function ( renderer ) {
  62. var config = this.workerConfig;
  63. config.astcSupported = !! renderer.extensions.get( 'WEBGL_compressed_texture_astc' );
  64. config.bptcSupported = !! renderer.extensions.get( 'EXT_texture_compression_bptc' );
  65. config.etcSupported = !! renderer.extensions.get( 'WEBGL_compressed_texture_etc1' );
  66. config.dxtSupported = !! renderer.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  67. config.pvrtcSupported = !! renderer.extensions.get( 'WEBGL_compressed_texture_pvrtc' )
  68. || !! renderer.extensions.get( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  69. if ( config.astcSupported ) {
  70. config.format = BasisTextureLoader.BASIS_FORMAT.cTFASTC_4x4;
  71. } else if ( config.bptcSupported ) {
  72. config.format = BasisTextureLoader.BASIS_FORMAT.cTFBC7_M5;
  73. } else if ( config.dxtSupported ) {
  74. config.format = BasisTextureLoader.BASIS_FORMAT.cTFBC3;
  75. } else if ( config.pvrtcSupported ) {
  76. config.format = BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGBA;
  77. } else if ( config.etcSupported ) {
  78. config.format = BasisTextureLoader.BASIS_FORMAT.cTFETC1;
  79. } else {
  80. throw new Error( 'THREE.BasisTextureLoader: No suitable compressed texture format found.' );
  81. }
  82. return this;
  83. },
  84. load: function ( url, onLoad, onProgress, onError ) {
  85. var loader = new FileLoader( this.manager );
  86. loader.setResponseType( 'arraybuffer' );
  87. loader.load( url, ( buffer ) => {
  88. var taskKey = JSON.stringify( url );
  89. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  90. // again from this thread.
  91. if ( BasisTextureLoader.taskCache.has( buffer ) ) {
  92. var cachedTask = BasisTextureLoader.taskCache.get( buffer );
  93. if ( cachedTask.key === taskKey ) {
  94. return cachedTask.promise.then( onLoad ).catch( onError );
  95. } else if ( buffer.byteLength === 0 ) {
  96. // Technically, it would be possible to wait for the previous task to complete,
  97. // transfer the buffer back, and decode again with the second configuration. That
  98. // is complex, and I don't know of any reason to decode a Basis buffer twice in
  99. // different ways, so this is left unimplemented.
  100. throw new Error(
  101. 'THREE.BasisTextureLoader: Unable to re-decode a buffer with different ' +
  102. 'settings. Buffer has already been transferred.'
  103. );
  104. }
  105. }
  106. this._createTexture( buffer, url )
  107. .then( onLoad )
  108. .catch( onError );
  109. }, onProgress, onError );
  110. },
  111. /**
  112. * @param {ArrayBuffer} buffer
  113. * @param {string} url
  114. * @return {Promise<CompressedTexture>}
  115. */
  116. _createTexture: function ( buffer, url ) {
  117. var worker;
  118. var taskID;
  119. var taskCost = buffer.byteLength;
  120. var texturePending = this._allocateWorker( taskCost )
  121. .then( ( _worker ) => {
  122. worker = _worker;
  123. taskID = this.workerNextTaskID ++;
  124. return new Promise( ( resolve, reject ) => {
  125. worker._callbacks[ taskID ] = { resolve, reject };
  126. worker.postMessage( { type: 'transcode', id: taskID, buffer }, [ buffer ] );
  127. } );
  128. } )
  129. .then( ( message ) => {
  130. var config = this.workerConfig;
  131. var { width, height, mipmaps, format } = message;
  132. var texture;
  133. switch ( format ) {
  134. case BasisTextureLoader.BASIS_FORMAT.cTFASTC_4x4:
  135. texture = new CompressedTexture( mipmaps, width, height, RGBA_ASTC_4x4_Format );
  136. break;
  137. case BasisTextureLoader.BASIS_FORMAT.cTFBC7_M5:
  138. texture = new CompressedTexture( mipmaps, width, height, RGBA_BPTC_Format );
  139. break;
  140. case BasisTextureLoader.BASIS_FORMAT.cTFBC1:
  141. case BasisTextureLoader.BASIS_FORMAT.cTFBC3:
  142. texture = new CompressedTexture( mipmaps, width, height, BasisTextureLoader.DXT_FORMAT_MAP[ config.format ], UnsignedByteType );
  143. break;
  144. case BasisTextureLoader.BASIS_FORMAT.cTFETC1:
  145. texture = new CompressedTexture( mipmaps, width, height, RGB_ETC1_Format );
  146. break;
  147. case BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGB:
  148. texture = new CompressedTexture( mipmaps, width, height, RGB_PVRTC_4BPPV1_Format );
  149. break;
  150. case BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGBA:
  151. texture = new CompressedTexture( mipmaps, width, height, RGBA_PVRTC_4BPPV1_Format );
  152. break;
  153. default:
  154. throw new Error( 'THREE.BasisTextureLoader: No supported format available.' );
  155. }
  156. texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter;
  157. texture.magFilter = LinearFilter;
  158. texture.generateMipmaps = false;
  159. texture.needsUpdate = true;
  160. return texture;
  161. } );
  162. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  163. texturePending
  164. .catch( () => true )
  165. .then( () => {
  166. if ( worker && taskID ) {
  167. worker._taskLoad -= taskCost;
  168. delete worker._callbacks[ taskID ];
  169. }
  170. } );
  171. var taskKey = JSON.stringify( url );
  172. // Cache the task result.
  173. BasisTextureLoader.taskCache.set( buffer, {
  174. key: taskKey,
  175. promise: texturePending
  176. } );
  177. return texturePending;
  178. },
  179. _initTranscoder: function () {
  180. if ( ! this.transcoderPending ) {
  181. // Load transcoder wrapper.
  182. var jsLoader = new FileLoader( this.manager );
  183. jsLoader.setPath( this.transcoderPath );
  184. var jsContent = new Promise( ( resolve, reject ) => {
  185. jsLoader.load( 'basis_transcoder.js', resolve, undefined, reject );
  186. } );
  187. // Load transcoder WASM binary.
  188. var binaryLoader = new FileLoader( this.manager );
  189. binaryLoader.setPath( this.transcoderPath );
  190. binaryLoader.setResponseType( 'arraybuffer' );
  191. var binaryContent = new Promise( ( resolve, reject ) => {
  192. binaryLoader.load( 'basis_transcoder.wasm', resolve, undefined, reject );
  193. } );
  194. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] )
  195. .then( ( [ jsContent, binaryContent ] ) => {
  196. var fn = BasisTextureLoader.BasisWorker.toString();
  197. var body = [
  198. '/* basis_transcoder.js */',
  199. jsContent,
  200. '/* worker */',
  201. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  202. ].join( '\n' );
  203. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  204. this.transcoderBinary = binaryContent;
  205. } );
  206. }
  207. return this.transcoderPending;
  208. },
  209. _allocateWorker: function ( taskCost ) {
  210. return this._initTranscoder().then( () => {
  211. if ( this.workerPool.length < this.workerLimit ) {
  212. var worker = new Worker( this.workerSourceURL );
  213. worker._callbacks = {};
  214. worker._taskLoad = 0;
  215. worker.postMessage( {
  216. type: 'init',
  217. config: this.workerConfig,
  218. transcoderBinary: this.transcoderBinary,
  219. } );
  220. worker.onmessage = function ( e ) {
  221. var message = e.data;
  222. switch ( message.type ) {
  223. case 'transcode':
  224. worker._callbacks[ message.id ].resolve( message );
  225. break;
  226. case 'error':
  227. worker._callbacks[ message.id ].reject( message );
  228. break;
  229. default:
  230. console.error( 'THREE.BasisTextureLoader: Unexpected message, "' + message.type + '"' );
  231. }
  232. };
  233. this.workerPool.push( worker );
  234. } else {
  235. this.workerPool.sort( function ( a, b ) {
  236. return a._taskLoad > b._taskLoad ? - 1 : 1;
  237. } );
  238. }
  239. var worker = this.workerPool[ this.workerPool.length - 1 ];
  240. worker._taskLoad += taskCost;
  241. return worker;
  242. } );
  243. },
  244. dispose: function () {
  245. for ( var i = 0; i < this.workerPool.length; i ++ ) {
  246. this.workerPool[ i ].terminate();
  247. }
  248. this.workerPool.length = 0;
  249. return this;
  250. }
  251. } );
  252. /* CONSTANTS */
  253. BasisTextureLoader.BASIS_FORMAT = {
  254. cTFETC1: 0,
  255. cTFETC2: 1,
  256. cTFBC1: 2,
  257. cTFBC3: 3,
  258. cTFBC4: 4,
  259. cTFBC5: 5,
  260. cTFBC7_M6_OPAQUE_ONLY: 6,
  261. cTFBC7_M5: 7,
  262. cTFPVRTC1_4_RGB: 8,
  263. cTFPVRTC1_4_RGBA: 9,
  264. cTFASTC_4x4: 10,
  265. cTFATC_RGB: 11,
  266. cTFATC_RGBA_INTERPOLATED_ALPHA: 12,
  267. cTFRGBA32: 13,
  268. cTFRGB565: 14,
  269. cTFBGR565: 15,
  270. cTFRGBA4444: 16,
  271. };
  272. // DXT formats, from:
  273. // http://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/
  274. BasisTextureLoader.DXT_FORMAT = {
  275. COMPRESSED_RGB_S3TC_DXT1_EXT: 0x83F0,
  276. COMPRESSED_RGBA_S3TC_DXT1_EXT: 0x83F1,
  277. COMPRESSED_RGBA_S3TC_DXT3_EXT: 0x83F2,
  278. COMPRESSED_RGBA_S3TC_DXT5_EXT: 0x83F3,
  279. };
  280. BasisTextureLoader.DXT_FORMAT_MAP = {};
  281. BasisTextureLoader.DXT_FORMAT_MAP[ BasisTextureLoader.BASIS_FORMAT.cTFBC1 ] =
  282. BasisTextureLoader.DXT_FORMAT.COMPRESSED_RGB_S3TC_DXT1_EXT;
  283. BasisTextureLoader.DXT_FORMAT_MAP[ BasisTextureLoader.BASIS_FORMAT.cTFBC3 ] =
  284. BasisTextureLoader.DXT_FORMAT.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  285. /* WEB WORKER */
  286. BasisTextureLoader.BasisWorker = function () {
  287. var config;
  288. var transcoderPending;
  289. var _BasisFile;
  290. onmessage = function ( e ) {
  291. var message = e.data;
  292. switch ( message.type ) {
  293. case 'init':
  294. config = message.config;
  295. init( message.transcoderBinary );
  296. break;
  297. case 'transcode':
  298. transcoderPending.then( () => {
  299. try {
  300. var { width, height, hasAlpha, mipmaps, format } = transcode( message.buffer );
  301. var buffers = [];
  302. for ( var i = 0; i < mipmaps.length; ++ i ) {
  303. buffers.push( mipmaps[ i ].data.buffer );
  304. }
  305. self.postMessage( { type: 'transcode', id: message.id, width, height, hasAlpha, mipmaps, format }, buffers );
  306. } catch ( error ) {
  307. console.error( error );
  308. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  309. }
  310. } );
  311. break;
  312. }
  313. };
  314. function init( wasmBinary ) {
  315. var BasisModule;
  316. transcoderPending = new Promise( ( resolve ) => {
  317. BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
  318. BASIS( BasisModule );
  319. } ).then( () => {
  320. var { BasisFile, initializeBasis } = BasisModule;
  321. _BasisFile = BasisFile;
  322. initializeBasis();
  323. } );
  324. }
  325. function transcode( buffer ) {
  326. var basisFile = new _BasisFile( new Uint8Array( buffer ) );
  327. var width = basisFile.getImageWidth( 0, 0 );
  328. var height = basisFile.getImageHeight( 0, 0 );
  329. var levels = basisFile.getNumLevels( 0 );
  330. var hasAlpha = basisFile.getHasAlpha();
  331. function cleanup() {
  332. basisFile.close();
  333. basisFile.delete();
  334. }
  335. if ( ! hasAlpha ) {
  336. switch ( config.format ) {
  337. case 9: // Hardcoded: BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGBA
  338. config.format = 8; // Hardcoded: BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGB;
  339. break;
  340. default:
  341. break;
  342. }
  343. }
  344. if ( ! width || ! height || ! levels ) {
  345. cleanup();
  346. throw new Error( 'THREE.BasisTextureLoader: Invalid .basis file' );
  347. }
  348. if ( ! basisFile.startTranscoding() ) {
  349. cleanup();
  350. throw new Error( 'THREE.BasisTextureLoader: .startTranscoding failed' );
  351. }
  352. var mipmaps = [];
  353. for ( var mip = 0; mip < levels; mip ++ ) {
  354. var mipWidth = basisFile.getImageWidth( 0, mip );
  355. var mipHeight = basisFile.getImageHeight( 0, mip );
  356. var dst = new Uint8Array( basisFile.getImageTranscodedSizeInBytes( 0, mip, config.format ) );
  357. var status = basisFile.transcodeImage(
  358. dst,
  359. 0,
  360. mip,
  361. config.format,
  362. 0,
  363. hasAlpha
  364. );
  365. if ( ! status ) {
  366. cleanup();
  367. throw new Error( 'THREE.BasisTextureLoader: .transcodeImage failed.' );
  368. }
  369. mipmaps.push( { data: dst, width: mipWidth, height: mipHeight } );
  370. }
  371. cleanup();
  372. return { width, height, hasAlpha, mipmaps, format: config.format };
  373. }
  374. };
  375. export { BasisTextureLoader };