BasisTextureLoader.js 12 KB

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