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