DRACOLoader.js 14 KB

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