BasisTextureLoader.js 11 KB

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