DRACOLoader.js 14 KB

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