BasisTextureLoader.js 12 KB

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