BasisTextureLoader.js 11 KB

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