BasisTextureLoader.js 11 KB

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