BasisTextureLoader.js 12 KB

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