BasisTextureLoader.js 11 KB

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