BasisTextureLoader.js 12 KB

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