BasisTextureLoader.js 12 KB

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