BasisTextureLoader.js 13 KB

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