DRACOLoader.js 14 KB

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