DRACOLoader.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. ( function () {
  2. var DRACOLoader = function ( manager ) {
  3. THREE.Loader.call( this, manager );
  4. this.decoderPath = '';
  5. this.decoderConfig = {};
  6. this.decoderBinary = null;
  7. this.decoderPending = null;
  8. this.workerLimit = 4;
  9. this.workerPool = [];
  10. this.workerNextTaskID = 1;
  11. this.workerSourceURL = '';
  12. this.defaultAttributeIDs = {
  13. position: 'POSITION',
  14. normal: 'NORMAL',
  15. color: 'COLOR',
  16. uv: 'TEX_COORD'
  17. };
  18. this.defaultAttributeTypes = {
  19. position: 'Float32Array',
  20. normal: 'Float32Array',
  21. color: 'Float32Array',
  22. uv: 'Float32Array'
  23. };
  24. };
  25. DRACOLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  26. constructor: DRACOLoader,
  27. setDecoderPath: function ( path ) {
  28. this.decoderPath = path;
  29. return this;
  30. },
  31. setDecoderConfig: function ( config ) {
  32. this.decoderConfig = config;
  33. return this;
  34. },
  35. setWorkerLimit: function ( workerLimit ) {
  36. this.workerLimit = workerLimit;
  37. return this;
  38. },
  39. /** @deprecated */
  40. setVerbosity: function () {
  41. console.warn( 'THREE.DRACOLoader: The .setVerbosity() method has been removed.' );
  42. },
  43. /** @deprecated */
  44. setDrawMode: function () {
  45. console.warn( 'THREE.DRACOLoader: The .setDrawMode() method has been removed.' );
  46. },
  47. /** @deprecated */
  48. setSkipDequantization: function () {
  49. console.warn( 'THREE.DRACOLoader: The .setSkipDequantization() method has been removed.' );
  50. },
  51. load: function ( url, onLoad, onProgress, onError ) {
  52. var loader = new THREE.FileLoader( this.manager );
  53. loader.setPath( this.path );
  54. loader.setResponseType( 'arraybuffer' );
  55. loader.setRequestHeader( this.requestHeader );
  56. loader.setWithCredentials( this.withCredentials );
  57. loader.load( url, buffer => {
  58. var taskConfig = {
  59. attributeIDs: this.defaultAttributeIDs,
  60. attributeTypes: this.defaultAttributeTypes,
  61. useUniqueIDs: false
  62. };
  63. this.decodeGeometry( buffer, taskConfig ).then( onLoad ).catch( onError );
  64. }, onProgress, onError );
  65. },
  66. /** @deprecated Kept for backward-compatibility with previous DRACOLoader versions. */
  67. decodeDracoFile: function ( buffer, callback, attributeIDs, attributeTypes ) {
  68. var taskConfig = {
  69. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  70. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  71. useUniqueIDs: !! attributeIDs
  72. };
  73. this.decodeGeometry( buffer, taskConfig ).then( callback );
  74. },
  75. decodeGeometry: function ( buffer, taskConfig ) {
  76. // TODO: For backward-compatibility, support 'attributeTypes' objects containing
  77. // references (rather than names) to typed array constructors. These must be
  78. // serialized before sending them to the worker.
  79. for ( var attribute in taskConfig.attributeTypes ) {
  80. var type = taskConfig.attributeTypes[ attribute ];
  81. if ( type.BYTES_PER_ELEMENT !== undefined ) {
  82. taskConfig.attributeTypes[ attribute ] = type.name;
  83. }
  84. } //
  85. var taskKey = JSON.stringify( taskConfig ); // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  86. // again from this thread.
  87. if ( DRACOLoader.taskCache.has( buffer ) ) {
  88. var cachedTask = DRACOLoader.taskCache.get( buffer );
  89. if ( cachedTask.key === taskKey ) {
  90. return cachedTask.promise;
  91. } else if ( buffer.byteLength === 0 ) {
  92. // Technically, it would be possible to wait for the previous task to complete,
  93. // transfer the buffer back, and decode again with the second configuration. That
  94. // is complex, and I don't know of any reason to decode a Draco buffer twice in
  95. // different ways, so this is left unimplemented.
  96. throw new Error( 'THREE.DRACOLoader: Unable to re-decode a buffer with different ' + 'settings. Buffer has already been transferred.' );
  97. }
  98. } //
  99. var worker;
  100. var taskID = this.workerNextTaskID ++;
  101. var taskCost = buffer.byteLength; // Obtain a worker and assign a task, and construct a geometry instance
  102. // when the task completes.
  103. var geometryPending = this._getWorker( taskID, taskCost ).then( _worker => {
  104. worker = _worker;
  105. return new Promise( ( resolve, reject ) => {
  106. worker._callbacks[ taskID ] = {
  107. resolve,
  108. reject
  109. };
  110. worker.postMessage( {
  111. type: 'decode',
  112. id: taskID,
  113. taskConfig,
  114. buffer
  115. }, [ buffer ] ); // this.debug();
  116. } );
  117. } ).then( message => this._createGeometry( message.geometry ) ); // Remove task from the task list.
  118. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  119. geometryPending.catch( () => true ).then( () => {
  120. if ( worker && taskID ) {
  121. this._releaseTask( worker, taskID ); // this.debug();
  122. }
  123. } ); // Cache the task result.
  124. DRACOLoader.taskCache.set( buffer, {
  125. key: taskKey,
  126. promise: geometryPending
  127. } );
  128. return geometryPending;
  129. },
  130. _createGeometry: function ( geometryData ) {
  131. var geometry = new THREE.BufferGeometry();
  132. if ( geometryData.index ) {
  133. geometry.setIndex( new THREE.BufferAttribute( geometryData.index.array, 1 ) );
  134. }
  135. for ( var i = 0; i < geometryData.attributes.length; i ++ ) {
  136. var attribute = geometryData.attributes[ i ];
  137. var name = attribute.name;
  138. var array = attribute.array;
  139. var itemSize = attribute.itemSize;
  140. geometry.setAttribute( name, new THREE.BufferAttribute( array, itemSize ) );
  141. }
  142. return geometry;
  143. },
  144. _loadLibrary: function ( url, responseType ) {
  145. var loader = new THREE.FileLoader( this.manager );
  146. loader.setPath( this.decoderPath );
  147. loader.setResponseType( responseType );
  148. loader.setWithCredentials( this.withCredentials );
  149. return new Promise( ( resolve, reject ) => {
  150. loader.load( url, resolve, undefined, reject );
  151. } );
  152. },
  153. preload: function () {
  154. this._initDecoder();
  155. return this;
  156. },
  157. _initDecoder: function () {
  158. if ( this.decoderPending ) return this.decoderPending;
  159. var useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  160. var librariesPending = [];
  161. if ( useJS ) {
  162. librariesPending.push( this._loadLibrary( 'draco_decoder.js', 'text' ) );
  163. } else {
  164. librariesPending.push( this._loadLibrary( 'draco_wasm_wrapper.js', 'text' ) );
  165. librariesPending.push( this._loadLibrary( 'draco_decoder.wasm', 'arraybuffer' ) );
  166. }
  167. this.decoderPending = Promise.all( librariesPending ).then( libraries => {
  168. var jsContent = libraries[ 0 ];
  169. if ( ! useJS ) {
  170. this.decoderConfig.wasmBinary = libraries[ 1 ];
  171. }
  172. var fn = DRACOLoader.DRACOWorker.toString();
  173. var body = [ '/* draco decoder */', jsContent, '', '/* worker */', fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) ) ].join( '\n' );
  174. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  175. } );
  176. return this.decoderPending;
  177. },
  178. _getWorker: function ( taskID, taskCost ) {
  179. return this._initDecoder().then( () => {
  180. if ( this.workerPool.length < this.workerLimit ) {
  181. var worker = new Worker( this.workerSourceURL );
  182. worker._callbacks = {};
  183. worker._taskCosts = {};
  184. worker._taskLoad = 0;
  185. worker.postMessage( {
  186. type: 'init',
  187. decoderConfig: this.decoderConfig
  188. } );
  189. worker.onmessage = function ( e ) {
  190. var message = e.data;
  191. switch ( message.type ) {
  192. case 'decode':
  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.DRACOLoader: 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. var worker = this.workerPool[ this.workerPool.length - 1 ];
  209. worker._taskCosts[ taskID ] = taskCost;
  210. worker._taskLoad += taskCost;
  211. return worker;
  212. } );
  213. },
  214. _releaseTask: function ( worker, taskID ) {
  215. worker._taskLoad -= worker._taskCosts[ taskID ];
  216. delete worker._callbacks[ taskID ];
  217. delete worker._taskCosts[ taskID ];
  218. },
  219. debug: function () {
  220. console.log( 'Task load: ', this.workerPool.map( worker => worker._taskLoad ) );
  221. },
  222. dispose: function () {
  223. for ( var i = 0; i < this.workerPool.length; ++ i ) {
  224. this.workerPool[ i ].terminate();
  225. }
  226. this.workerPool.length = 0;
  227. return this;
  228. }
  229. } );
  230. /* WEB WORKER */
  231. DRACOLoader.DRACOWorker = function () {
  232. var decoderConfig;
  233. var decoderPending;
  234. onmessage = function ( e ) {
  235. var message = e.data;
  236. switch ( message.type ) {
  237. case 'init':
  238. decoderConfig = message.decoderConfig;
  239. decoderPending = new Promise( function ( resolve
  240. /*, reject*/
  241. ) {
  242. decoderConfig.onModuleLoaded = function ( draco ) {
  243. // Module is Promise-like. Wrap before resolving to avoid loop.
  244. resolve( {
  245. draco: draco
  246. } );
  247. };
  248. DracoDecoderModule( decoderConfig ); // eslint-disable-line no-undef
  249. } );
  250. break;
  251. case 'decode':
  252. var buffer = message.buffer;
  253. var taskConfig = message.taskConfig;
  254. decoderPending.then( module => {
  255. var draco = module.draco;
  256. var decoder = new draco.Decoder();
  257. var decoderBuffer = new draco.DecoderBuffer();
  258. decoderBuffer.Init( new Int8Array( buffer ), buffer.byteLength );
  259. try {
  260. var geometry = decodeGeometry( draco, decoder, decoderBuffer, taskConfig );
  261. var buffers = geometry.attributes.map( attr => attr.array.buffer );
  262. if ( geometry.index ) buffers.push( geometry.index.array.buffer );
  263. self.postMessage( {
  264. type: 'decode',
  265. id: message.id,
  266. geometry
  267. }, buffers );
  268. } catch ( error ) {
  269. console.error( error );
  270. self.postMessage( {
  271. type: 'error',
  272. id: message.id,
  273. error: error.message
  274. } );
  275. } finally {
  276. draco.destroy( decoderBuffer );
  277. draco.destroy( decoder );
  278. }
  279. } );
  280. break;
  281. }
  282. };
  283. function decodeGeometry( draco, decoder, decoderBuffer, taskConfig ) {
  284. var attributeIDs = taskConfig.attributeIDs;
  285. var attributeTypes = taskConfig.attributeTypes;
  286. var dracoGeometry;
  287. var decodingStatus;
  288. var geometryType = decoder.GetEncodedGeometryType( decoderBuffer );
  289. if ( geometryType === draco.TRIANGULAR_MESH ) {
  290. dracoGeometry = new draco.Mesh();
  291. decodingStatus = decoder.DecodeBufferToMesh( decoderBuffer, dracoGeometry );
  292. } else if ( geometryType === draco.POINT_CLOUD ) {
  293. dracoGeometry = new draco.PointCloud();
  294. decodingStatus = decoder.DecodeBufferToPointCloud( decoderBuffer, dracoGeometry );
  295. } else {
  296. throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );
  297. }
  298. if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {
  299. throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );
  300. }
  301. var geometry = {
  302. index: null,
  303. attributes: []
  304. }; // Gather all vertex attributes.
  305. for ( var attributeName in attributeIDs ) {
  306. var attributeType = self[ attributeTypes[ attributeName ] ];
  307. var attribute;
  308. var attributeID; // A Draco file may be created with default vertex attributes, whose attribute IDs
  309. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  310. // a Draco file may contain a custom set of attributes, identified by known unique
  311. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  312. if ( taskConfig.useUniqueIDs ) {
  313. attributeID = attributeIDs[ attributeName ];
  314. attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );
  315. } else {
  316. attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );
  317. if ( attributeID === - 1 ) continue;
  318. attribute = decoder.GetAttribute( dracoGeometry, attributeID );
  319. }
  320. geometry.attributes.push( decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) );
  321. } // Add index.
  322. if ( geometryType === draco.TRIANGULAR_MESH ) {
  323. geometry.index = decodeIndex( draco, decoder, dracoGeometry );
  324. }
  325. draco.destroy( dracoGeometry );
  326. return geometry;
  327. }
  328. function decodeIndex( draco, decoder, dracoGeometry ) {
  329. var numFaces = dracoGeometry.num_faces();
  330. var numIndices = numFaces * 3;
  331. var byteLength = numIndices * 4;
  332. var ptr = draco._malloc( byteLength );
  333. decoder.GetTrianglesUInt32Array( dracoGeometry, byteLength, ptr );
  334. var index = new Uint32Array( draco.HEAPF32.buffer, ptr, numIndices ).slice();
  335. draco._free( ptr );
  336. return {
  337. array: index,
  338. itemSize: 1
  339. };
  340. }
  341. function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {
  342. var numComponents = attribute.num_components();
  343. var numPoints = dracoGeometry.num_points();
  344. var numValues = numPoints * numComponents;
  345. var byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
  346. var dataType = getDracoDataType( draco, attributeType );
  347. var ptr = draco._malloc( byteLength );
  348. decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, dataType, byteLength, ptr );
  349. var array = new attributeType( draco.HEAPF32.buffer, ptr, numValues ).slice();
  350. draco._free( ptr );
  351. return {
  352. name: attributeName,
  353. array: array,
  354. itemSize: numComponents
  355. };
  356. }
  357. function getDracoDataType( draco, attributeType ) {
  358. switch ( attributeType ) {
  359. case Float32Array:
  360. return draco.DT_FLOAT32;
  361. case Int8Array:
  362. return draco.DT_INT8;
  363. case Int16Array:
  364. return draco.DT_INT16;
  365. case Int32Array:
  366. return draco.DT_INT32;
  367. case Uint8Array:
  368. return draco.DT_UINT8;
  369. case Uint16Array:
  370. return draco.DT_UINT16;
  371. case Uint32Array:
  372. return draco.DT_UINT32;
  373. }
  374. }
  375. };
  376. DRACOLoader.taskCache = new WeakMap();
  377. /** Deprecated static methods */
  378. /** @deprecated */
  379. DRACOLoader.setDecoderPath = function () {
  380. console.warn( 'THREE.DRACOLoader: The .setDecoderPath() method has been removed. Use instance methods.' );
  381. };
  382. /** @deprecated */
  383. DRACOLoader.setDecoderConfig = function () {
  384. console.warn( 'THREE.DRACOLoader: The .setDecoderConfig() method has been removed. Use instance methods.' );
  385. };
  386. /** @deprecated */
  387. DRACOLoader.releaseDecoderModule = function () {
  388. console.warn( 'THREE.DRACOLoader: The .releaseDecoderModule() method has been removed. Use instance methods.' );
  389. };
  390. /** @deprecated */
  391. DRACOLoader.getDecoderModule = function () {
  392. console.warn( 'THREE.DRACOLoader: The .getDecoderModule() method has been removed. Use instance methods.' );
  393. };
  394. THREE.DRACOLoader = DRACOLoader;
  395. } )();