BasisTextureLoader.js 12 KB

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