BasisTextureLoader.js 12 KB

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