BasisTextureLoader.js 11 KB

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