DRACOLoader.js 15 KB

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