BasisTextureLoader.js 11 KB

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