BasisTextureLoader.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  89. // again from this thread.
  90. if ( BasisTextureLoader.taskCache.has( buffer ) ) {
  91. var cachedTask = BasisTextureLoader.taskCache.get( buffer );
  92. if ( cachedTask.url === url ) {
  93. return cachedTask.promise.then( onLoad ).catch( onError );
  94. }
  95. }
  96. this._createTexture( buffer, url )
  97. .then( onLoad )
  98. .catch( onError );
  99. }, onProgress, onError );
  100. },
  101. /**
  102. * @param {ArrayBuffer} buffer
  103. * @param {string} url
  104. * @return {Promise<CompressedTexture>}
  105. */
  106. _createTexture: function ( buffer, url ) {
  107. var worker;
  108. var taskID;
  109. var taskCost = buffer.byteLength;
  110. var texturePending = this._allocateWorker( taskCost )
  111. .then( ( _worker ) => {
  112. worker = _worker;
  113. taskID = this.workerNextTaskID ++;
  114. return new Promise( ( resolve, reject ) => {
  115. worker._callbacks[ taskID ] = { resolve, reject };
  116. worker.postMessage( { type: 'transcode', id: taskID, buffer }, [ buffer ] );
  117. } );
  118. } )
  119. .then( ( message ) => {
  120. var config = this.workerConfig;
  121. var { width, height, mipmaps, format } = message;
  122. var texture;
  123. switch ( format ) {
  124. case BasisTextureLoader.BASIS_FORMAT.cTFASTC_4x4:
  125. texture = new CompressedTexture( mipmaps, width, height, RGBA_ASTC_4x4_Format );
  126. break;
  127. case BasisTextureLoader.BASIS_FORMAT.cTFBC7_M5:
  128. texture = new CompressedTexture( mipmaps, width, height, RGBA_BPTC_Format );
  129. break;
  130. case BasisTextureLoader.BASIS_FORMAT.cTFBC1:
  131. case BasisTextureLoader.BASIS_FORMAT.cTFBC3:
  132. texture = new CompressedTexture( mipmaps, width, height, BasisTextureLoader.DXT_FORMAT_MAP[ config.format ], UnsignedByteType );
  133. break;
  134. case BasisTextureLoader.BASIS_FORMAT.cTFETC1:
  135. texture = new CompressedTexture( mipmaps, width, height, RGB_ETC1_Format );
  136. break;
  137. case BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGB:
  138. texture = new CompressedTexture( mipmaps, width, height, RGB_PVRTC_4BPPV1_Format );
  139. break;
  140. case BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGBA:
  141. texture = new CompressedTexture( mipmaps, width, height, RGBA_PVRTC_4BPPV1_Format );
  142. break;
  143. default:
  144. throw new Error( 'THREE.BasisTextureLoader: No supported format available.' );
  145. }
  146. texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter;
  147. texture.magFilter = LinearFilter;
  148. texture.generateMipmaps = false;
  149. texture.needsUpdate = true;
  150. return texture;
  151. } );
  152. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  153. texturePending
  154. .catch( () => true )
  155. .then( () => {
  156. if ( worker && taskID ) {
  157. worker._taskLoad -= taskCost;
  158. delete worker._callbacks[ taskID ];
  159. }
  160. } );
  161. // Cache the task result.
  162. BasisTextureLoader.taskCache.set( buffer, {
  163. url: url,
  164. promise: texturePending
  165. } );
  166. return texturePending;
  167. },
  168. _initTranscoder: function () {
  169. if ( ! this.transcoderPending ) {
  170. // Load transcoder wrapper.
  171. var jsLoader = new FileLoader( this.manager );
  172. jsLoader.setPath( this.transcoderPath );
  173. var jsContent = new Promise( ( resolve, reject ) => {
  174. jsLoader.load( 'basis_transcoder.js', resolve, undefined, reject );
  175. } );
  176. // Load transcoder WASM binary.
  177. var binaryLoader = new FileLoader( this.manager );
  178. binaryLoader.setPath( this.transcoderPath );
  179. binaryLoader.setResponseType( 'arraybuffer' );
  180. var binaryContent = new Promise( ( resolve, reject ) => {
  181. binaryLoader.load( 'basis_transcoder.wasm', resolve, undefined, reject );
  182. } );
  183. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] )
  184. .then( ( [ jsContent, binaryContent ] ) => {
  185. var fn = BasisTextureLoader.BasisWorker.toString();
  186. var body = [
  187. '/* basis_transcoder.js */',
  188. jsContent,
  189. '/* worker */',
  190. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  191. ].join( '\n' );
  192. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  193. this.transcoderBinary = binaryContent;
  194. } );
  195. }
  196. return this.transcoderPending;
  197. },
  198. _allocateWorker: function ( taskCost ) {
  199. return this._initTranscoder().then( () => {
  200. if ( this.workerPool.length < this.workerLimit ) {
  201. var worker = new Worker( this.workerSourceURL );
  202. worker._callbacks = {};
  203. worker._taskLoad = 0;
  204. worker.postMessage( {
  205. type: 'init',
  206. config: this.workerConfig,
  207. transcoderBinary: this.transcoderBinary,
  208. } );
  209. worker.onmessage = function ( e ) {
  210. var message = e.data;
  211. switch ( message.type ) {
  212. case 'transcode':
  213. worker._callbacks[ message.id ].resolve( message );
  214. break;
  215. case 'error':
  216. worker._callbacks[ message.id ].reject( message );
  217. break;
  218. default:
  219. console.error( 'THREE.BasisTextureLoader: Unexpected message, "' + message.type + '"' );
  220. }
  221. };
  222. this.workerPool.push( worker );
  223. } else {
  224. this.workerPool.sort( function ( a, b ) {
  225. return a._taskLoad > b._taskLoad ? - 1 : 1;
  226. } );
  227. }
  228. var worker = this.workerPool[ this.workerPool.length - 1 ];
  229. worker._taskLoad += taskCost;
  230. return worker;
  231. } );
  232. },
  233. dispose: function () {
  234. for ( var i = 0; i < this.workerPool.length; i ++ ) {
  235. this.workerPool[ i ].terminate();
  236. }
  237. this.workerPool.length = 0;
  238. return this;
  239. }
  240. } );
  241. /* CONSTANTS */
  242. BasisTextureLoader.BASIS_FORMAT = {
  243. cTFETC1: 0,
  244. cTFETC2: 1,
  245. cTFBC1: 2,
  246. cTFBC3: 3,
  247. cTFBC4: 4,
  248. cTFBC5: 5,
  249. cTFBC7_M6_OPAQUE_ONLY: 6,
  250. cTFBC7_M5: 7,
  251. cTFPVRTC1_4_RGB: 8,
  252. cTFPVRTC1_4_RGBA: 9,
  253. cTFASTC_4x4: 10,
  254. cTFATC_RGB: 11,
  255. cTFATC_RGBA_INTERPOLATED_ALPHA: 12,
  256. cTFRGBA32: 13,
  257. cTFRGB565: 14,
  258. cTFBGR565: 15,
  259. cTFRGBA4444: 16,
  260. };
  261. // DXT formats, from:
  262. // http://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/
  263. BasisTextureLoader.DXT_FORMAT = {
  264. COMPRESSED_RGB_S3TC_DXT1_EXT: 0x83F0,
  265. COMPRESSED_RGBA_S3TC_DXT1_EXT: 0x83F1,
  266. COMPRESSED_RGBA_S3TC_DXT3_EXT: 0x83F2,
  267. COMPRESSED_RGBA_S3TC_DXT5_EXT: 0x83F3,
  268. };
  269. BasisTextureLoader.DXT_FORMAT_MAP = {};
  270. BasisTextureLoader.DXT_FORMAT_MAP[ BasisTextureLoader.BASIS_FORMAT.cTFBC1 ] =
  271. BasisTextureLoader.DXT_FORMAT.COMPRESSED_RGB_S3TC_DXT1_EXT;
  272. BasisTextureLoader.DXT_FORMAT_MAP[ BasisTextureLoader.BASIS_FORMAT.cTFBC3 ] =
  273. BasisTextureLoader.DXT_FORMAT.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  274. /* WEB WORKER */
  275. BasisTextureLoader.BasisWorker = function () {
  276. var config;
  277. var transcoderPending;
  278. var _BasisFile;
  279. onmessage = function ( e ) {
  280. var message = e.data;
  281. switch ( message.type ) {
  282. case 'init':
  283. config = message.config;
  284. init( message.transcoderBinary );
  285. break;
  286. case 'transcode':
  287. transcoderPending.then( () => {
  288. try {
  289. var { width, height, hasAlpha, mipmaps, format } = transcode( message.buffer );
  290. var buffers = [];
  291. for ( var i = 0; i < mipmaps.length; ++ i ) {
  292. buffers.push( mipmaps[ i ].data.buffer );
  293. }
  294. self.postMessage( { type: 'transcode', id: message.id, width, height, hasAlpha, mipmaps, format }, buffers );
  295. } catch ( error ) {
  296. console.error( error );
  297. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  298. }
  299. } );
  300. break;
  301. }
  302. };
  303. function init( wasmBinary ) {
  304. var BasisModule;
  305. transcoderPending = new Promise( ( resolve ) => {
  306. BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
  307. BASIS( BasisModule );
  308. } ).then( () => {
  309. var { BasisFile, initializeBasis } = BasisModule;
  310. _BasisFile = BasisFile;
  311. initializeBasis();
  312. } );
  313. }
  314. function transcode( buffer ) {
  315. var basisFile = new _BasisFile( new Uint8Array( buffer ) );
  316. var width = basisFile.getImageWidth( 0, 0 );
  317. var height = basisFile.getImageHeight( 0, 0 );
  318. var levels = basisFile.getNumLevels( 0 );
  319. var hasAlpha = basisFile.getHasAlpha();
  320. function cleanup() {
  321. basisFile.close();
  322. basisFile.delete();
  323. }
  324. if ( ! hasAlpha ) {
  325. switch ( config.format ) {
  326. case 9: // Hardcoded: BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGBA
  327. config.format = 8; // Hardcoded: BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGB;
  328. break;
  329. default:
  330. break;
  331. }
  332. }
  333. if ( ! width || ! height || ! levels ) {
  334. cleanup();
  335. throw new Error( 'THREE.BasisTextureLoader: Invalid .basis file' );
  336. }
  337. if ( ! basisFile.startTranscoding() ) {
  338. cleanup();
  339. throw new Error( 'THREE.BasisTextureLoader: .startTranscoding failed' );
  340. }
  341. var mipmaps = [];
  342. for ( var mip = 0; mip < levels; mip ++ ) {
  343. var mipWidth = basisFile.getImageWidth( 0, mip );
  344. var mipHeight = basisFile.getImageHeight( 0, mip );
  345. var dst = new Uint8Array( basisFile.getImageTranscodedSizeInBytes( 0, mip, config.format ) );
  346. var status = basisFile.transcodeImage(
  347. dst,
  348. 0,
  349. mip,
  350. config.format,
  351. 0,
  352. hasAlpha
  353. );
  354. if ( ! status ) {
  355. cleanup();
  356. throw new Error( 'THREE.BasisTextureLoader: .transcodeImage failed.' );
  357. }
  358. mipmaps.push( { data: dst, width: mipWidth, height: mipHeight } );
  359. }
  360. cleanup();
  361. return { width, height, hasAlpha, mipmaps, format: config.format };
  362. }
  363. };
  364. export { BasisTextureLoader };