BasisTextureLoader.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. /**
  2. * Loader for Basis Universal GPU Texture Codec.
  3. *
  4. * Basis Universal is a "supercompressed" GPU texture and texture video
  5. * compression system that outputs a highly compressed intermediate file format
  6. * (.basis) that can be quickly transcoded to a wide variety of GPU texture
  7. * compression formats.
  8. *
  9. * This loader parallelizes the transcoding process across a configurable number
  10. * of web workers, before transferring the transcoded compressed texture back
  11. * to the main thread.
  12. */
  13. THREE.BasisTextureLoader = function ( manager ) {
  14. THREE.Loader.call( this, manager );
  15. this.transcoderPath = '';
  16. this.transcoderBinary = null;
  17. this.transcoderPending = null;
  18. this.workerLimit = 4;
  19. this.workerPool = [];
  20. this.workerNextTaskID = 1;
  21. this.workerSourceURL = '';
  22. this.workerConfig = {
  23. format: null,
  24. astcSupported: false,
  25. bptcSupported: false,
  26. etcSupported: false,
  27. dxtSupported: false,
  28. pvrtcSupported: false,
  29. };
  30. };
  31. THREE.BasisTextureLoader.taskCache = new WeakMap();
  32. THREE.BasisTextureLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  33. constructor: THREE.BasisTextureLoader,
  34. setTranscoderPath: function ( path ) {
  35. this.transcoderPath = path;
  36. return this;
  37. },
  38. setWorkerLimit: function ( workerLimit ) {
  39. this.workerLimit = workerLimit;
  40. return this;
  41. },
  42. detectSupport: function ( renderer ) {
  43. var config = this.workerConfig;
  44. config.astcSupported = renderer.extensions.has( 'WEBGL_compressed_texture_astc' );
  45. config.bptcSupported = renderer.extensions.has( 'EXT_texture_compression_bptc' );
  46. config.etcSupported = renderer.extensions.has( 'WEBGL_compressed_texture_etc1' );
  47. config.dxtSupported = renderer.extensions.has( 'WEBGL_compressed_texture_s3tc' );
  48. config.pvrtcSupported = renderer.extensions.has( 'WEBGL_compressed_texture_pvrtc' )
  49. || renderer.extensions.has( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  50. if ( config.astcSupported ) {
  51. config.format = THREE.BasisTextureLoader.BASIS_FORMAT.cTFASTC_4x4;
  52. } else if ( config.bptcSupported ) {
  53. config.format = THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC7_M5;
  54. } else if ( config.dxtSupported ) {
  55. config.format = THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC3;
  56. } else if ( config.pvrtcSupported ) {
  57. config.format = THREE.BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGBA;
  58. } else if ( config.etcSupported ) {
  59. config.format = THREE.BasisTextureLoader.BASIS_FORMAT.cTFETC1;
  60. } else {
  61. throw new Error( 'THREE.BasisTextureLoader: No suitable compressed texture format found.' );
  62. }
  63. return this;
  64. },
  65. load: function ( url, onLoad, onProgress, onError ) {
  66. var loader = new THREE.FileLoader( this.manager );
  67. loader.setResponseType( 'arraybuffer' );
  68. loader.setWithCredentials( this.withCredentials );
  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. jsLoader.setWithCredentials( this.withCredentials );
  154. var jsContent = new Promise( ( resolve, reject ) => {
  155. jsLoader.load( 'basis_transcoder.js', resolve, undefined, reject );
  156. } );
  157. // Load transcoder WASM binary.
  158. var binaryLoader = new THREE.FileLoader( this.manager );
  159. binaryLoader.setPath( this.transcoderPath );
  160. binaryLoader.setResponseType( 'arraybuffer' );
  161. binaryLoader.setWithCredentials( this.withCredentials );
  162. var binaryContent = new Promise( ( resolve, reject ) => {
  163. binaryLoader.load( 'basis_transcoder.wasm', resolve, undefined, reject );
  164. } );
  165. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] )
  166. .then( ( [ jsContent, binaryContent ] ) => {
  167. var fn = THREE.BasisTextureLoader.BasisWorker.toString();
  168. var body = [
  169. '/* basis_transcoder.js */',
  170. jsContent,
  171. '/* worker */',
  172. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  173. ].join( '\n' );
  174. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  175. this.transcoderBinary = binaryContent;
  176. } );
  177. }
  178. return this.transcoderPending;
  179. },
  180. _allocateWorker: function ( taskCost ) {
  181. return this._initTranscoder().then( () => {
  182. if ( this.workerPool.length < this.workerLimit ) {
  183. var worker = new Worker( this.workerSourceURL );
  184. worker._callbacks = {};
  185. worker._taskLoad = 0;
  186. worker.postMessage( {
  187. type: 'init',
  188. config: this.workerConfig,
  189. transcoderBinary: this.transcoderBinary,
  190. } );
  191. worker.onmessage = function ( e ) {
  192. var message = e.data;
  193. switch ( message.type ) {
  194. case 'transcode':
  195. worker._callbacks[ message.id ].resolve( message );
  196. break;
  197. case 'error':
  198. worker._callbacks[ message.id ].reject( message );
  199. break;
  200. default:
  201. console.error( 'THREE.BasisTextureLoader: Unexpected message, "' + message.type + '"' );
  202. }
  203. };
  204. this.workerPool.push( worker );
  205. } else {
  206. this.workerPool.sort( function ( a, b ) {
  207. return a._taskLoad > b._taskLoad ? - 1 : 1;
  208. } );
  209. }
  210. var worker = this.workerPool[ this.workerPool.length - 1 ];
  211. worker._taskLoad += taskCost;
  212. return worker;
  213. } );
  214. },
  215. dispose: function () {
  216. for ( var i = 0; i < this.workerPool.length; i ++ ) {
  217. this.workerPool[ i ].terminate();
  218. }
  219. this.workerPool.length = 0;
  220. return this;
  221. }
  222. } );
  223. /* CONSTANTS */
  224. THREE.BasisTextureLoader.BASIS_FORMAT = {
  225. cTFETC1: 0,
  226. cTFETC2: 1,
  227. cTFBC1: 2,
  228. cTFBC3: 3,
  229. cTFBC4: 4,
  230. cTFBC5: 5,
  231. cTFBC7_M6_OPAQUE_ONLY: 6,
  232. cTFBC7_M5: 7,
  233. cTFPVRTC1_4_RGB: 8,
  234. cTFPVRTC1_4_RGBA: 9,
  235. cTFASTC_4x4: 10,
  236. cTFATC_RGB: 11,
  237. cTFATC_RGBA_INTERPOLATED_ALPHA: 12,
  238. cTFRGBA32: 13,
  239. cTFRGB565: 14,
  240. cTFBGR565: 15,
  241. cTFRGBA4444: 16,
  242. };
  243. // DXT formats, from:
  244. // http://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/
  245. THREE.BasisTextureLoader.DXT_FORMAT = {
  246. COMPRESSED_RGB_S3TC_DXT1_EXT: 0x83F0,
  247. COMPRESSED_RGBA_S3TC_DXT1_EXT: 0x83F1,
  248. COMPRESSED_RGBA_S3TC_DXT3_EXT: 0x83F2,
  249. COMPRESSED_RGBA_S3TC_DXT5_EXT: 0x83F3,
  250. };
  251. THREE.BasisTextureLoader.DXT_FORMAT_MAP = {};
  252. THREE.BasisTextureLoader.DXT_FORMAT_MAP[ THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC1 ] =
  253. THREE.BasisTextureLoader.DXT_FORMAT.COMPRESSED_RGB_S3TC_DXT1_EXT;
  254. THREE.BasisTextureLoader.DXT_FORMAT_MAP[ THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC3 ] =
  255. THREE.BasisTextureLoader.DXT_FORMAT.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  256. /* WEB WORKER */
  257. THREE.BasisTextureLoader.BasisWorker = function () {
  258. var config;
  259. var transcoderPending;
  260. var _BasisFile;
  261. onmessage = function ( e ) {
  262. var message = e.data;
  263. switch ( message.type ) {
  264. case 'init':
  265. config = message.config;
  266. init( message.transcoderBinary );
  267. break;
  268. case 'transcode':
  269. transcoderPending.then( () => {
  270. try {
  271. var { width, height, hasAlpha, mipmaps, format } = transcode( message.buffer );
  272. var buffers = [];
  273. for ( var i = 0; i < mipmaps.length; ++ i ) {
  274. buffers.push( mipmaps[ i ].data.buffer );
  275. }
  276. self.postMessage( { type: 'transcode', id: message.id, width, height, hasAlpha, mipmaps, format }, buffers );
  277. } catch ( error ) {
  278. console.error( error );
  279. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  280. }
  281. } );
  282. break;
  283. }
  284. };
  285. function init( wasmBinary ) {
  286. var BasisModule;
  287. transcoderPending = new Promise( ( resolve ) => {
  288. BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
  289. BASIS( BasisModule ); // eslint-disable-line no-undef
  290. } ).then( () => {
  291. var { BasisFile, initializeBasis } = BasisModule;
  292. _BasisFile = BasisFile;
  293. initializeBasis();
  294. } );
  295. }
  296. function transcode( buffer ) {
  297. var basisFile = new _BasisFile( new Uint8Array( buffer ) );
  298. var width = basisFile.getImageWidth( 0, 0 );
  299. var height = basisFile.getImageHeight( 0, 0 );
  300. var levels = basisFile.getNumLevels( 0 );
  301. var hasAlpha = basisFile.getHasAlpha();
  302. function cleanup() {
  303. basisFile.close();
  304. basisFile.delete();
  305. }
  306. if ( ! hasAlpha ) {
  307. switch ( config.format ) {
  308. case 9: // Hardcoded: THREE.BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGBA
  309. config.format = 8; // Hardcoded: THREE.BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGB;
  310. break;
  311. default:
  312. break;
  313. }
  314. }
  315. if ( ! width || ! height || ! levels ) {
  316. cleanup();
  317. throw new Error( 'THREE.BasisTextureLoader: Invalid .basis file' );
  318. }
  319. if ( ! basisFile.startTranscoding() ) {
  320. cleanup();
  321. throw new Error( 'THREE.BasisTextureLoader: .startTranscoding failed' );
  322. }
  323. var mipmaps = [];
  324. for ( var mip = 0; mip < levels; mip ++ ) {
  325. var mipWidth = basisFile.getImageWidth( 0, mip );
  326. var mipHeight = basisFile.getImageHeight( 0, mip );
  327. var dst = new Uint8Array( basisFile.getImageTranscodedSizeInBytes( 0, mip, config.format ) );
  328. var status = basisFile.transcodeImage(
  329. dst,
  330. 0,
  331. mip,
  332. config.format,
  333. 0,
  334. hasAlpha
  335. );
  336. if ( ! status ) {
  337. cleanup();
  338. throw new Error( 'THREE.BasisTextureLoader: .transcodeImage failed.' );
  339. }
  340. mipmaps.push( { data: dst, width: mipWidth, height: mipHeight } );
  341. }
  342. cleanup();
  343. return { width, height, hasAlpha, mipmaps, format: config.format };
  344. }
  345. };