DRACOLoader.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. import {
  2. BufferAttribute,
  3. BufferGeometry,
  4. Color,
  5. ColorManagement,
  6. FileLoader,
  7. Loader,
  8. LinearSRGBColorSpace,
  9. SRGBColorSpace
  10. } from 'three';
  11. const _taskCache = new WeakMap();
  12. /**
  13. * A loader for the Draco format.
  14. *
  15. * [Draco]{@link https://google.github.io/draco/} is an open source library for compressing
  16. * and decompressing 3D meshes and point clouds. Compressed geometry can be significantly smaller,
  17. * at the cost of additional decoding time on the client device.
  18. *
  19. * Standalone Draco files have a `.drc` extension, and contain vertex positions, normals, colors,
  20. * and other attributes. Draco files do not contain materials, textures, animation, or node hierarchies –
  21. * to use these features, embed Draco geometry inside of a glTF file. A normal glTF file can be converted
  22. * to a Draco-compressed glTF file using [glTF-Pipeline]{@link https://github.com/CesiumGS/gltf-pipeline}.
  23. * When using Draco with glTF, an instance of `DRACOLoader` will be used internally by {@link GLTFLoader}.
  24. *
  25. * It is recommended to create one DRACOLoader instance and reuse it to avoid loading and creating
  26. * multiple decoder instances.
  27. *
  28. * `DRACOLoader` will automatically use either the JS or the WASM decoding library, based on
  29. * browser capabilities.
  30. *
  31. * ```js
  32. * const loader = new DRACOLoader();
  33. * loader.setDecoderPath( '/examples/jsm/libs/draco/' );
  34. *
  35. * const geometry = await dracoLoader.loadAsync( 'models/draco/bunny.drc' );
  36. * geometry.computeVertexNormals(); // optional
  37. *
  38. * dracoLoader.dispose();
  39. * ```
  40. *
  41. * @augments Loader
  42. */
  43. class DRACOLoader extends Loader {
  44. /**
  45. * Constructs a new Draco loader.
  46. *
  47. * @param {LoadingManager} [manager] - The loading manager.
  48. */
  49. constructor( manager ) {
  50. super( manager );
  51. this.decoderPath = '';
  52. this.decoderConfig = {};
  53. this.decoderBinary = null;
  54. this.decoderPending = null;
  55. this.workerLimit = 4;
  56. this.workerPool = [];
  57. this.workerNextTaskID = 1;
  58. this.workerSourceURL = '';
  59. this.defaultAttributeIDs = {
  60. position: 'POSITION',
  61. normal: 'NORMAL',
  62. color: 'COLOR',
  63. uv: 'TEX_COORD'
  64. };
  65. this.defaultAttributeTypes = {
  66. position: 'Float32Array',
  67. normal: 'Float32Array',
  68. color: 'Float32Array',
  69. uv: 'Float32Array'
  70. };
  71. }
  72. /**
  73. * Provides configuration for the decoder libraries. Configuration cannot be changed after decoding begins.
  74. *
  75. * @param {string} path - The decoder path.
  76. * @return {DRACOLoader} A reference to this loader.
  77. */
  78. setDecoderPath( path ) {
  79. this.decoderPath = path;
  80. return this;
  81. }
  82. /**
  83. * Provides configuration for the decoder libraries. Configuration cannot be changed after decoding begins.
  84. *
  85. * @param {{type:('js'|'wasm')}} config - The decoder config.
  86. * @return {DRACOLoader} A reference to this loader.
  87. */
  88. setDecoderConfig( config ) {
  89. this.decoderConfig = config;
  90. return this;
  91. }
  92. /**
  93. * Sets the maximum number of Web Workers to be used during decoding.
  94. * A lower limit may be preferable if workers are also for other tasks in the application.
  95. *
  96. * @param {number} workerLimit - The worker limit.
  97. * @return {DRACOLoader} A reference to this loader.
  98. */
  99. setWorkerLimit( workerLimit ) {
  100. this.workerLimit = workerLimit;
  101. return this;
  102. }
  103. /**
  104. * Starts loading from the given URL and passes the loaded Draco asset
  105. * to the `onLoad()` callback.
  106. *
  107. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  108. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  109. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  110. * @param {onErrorCallback} onError - Executed when errors occur.
  111. */
  112. load( url, onLoad, onProgress, onError ) {
  113. const loader = new FileLoader( this.manager );
  114. loader.setPath( this.path );
  115. loader.setResponseType( 'arraybuffer' );
  116. loader.setRequestHeader( this.requestHeader );
  117. loader.setWithCredentials( this.withCredentials );
  118. loader.load( url, ( buffer ) => {
  119. this.parse( buffer, onLoad, onError );
  120. }, onProgress, onError );
  121. }
  122. /**
  123. * Parses the given Draco data.
  124. *
  125. * @param {ArrayBuffer} buffer - The raw Draco data as an array buffer.
  126. * @param {function(BufferGeometry)} onLoad - Executed when the loading/parsing process has been finished.
  127. * @param {onErrorCallback} onError - Executed when errors occur.
  128. */
  129. parse( buffer, onLoad, onError = ()=>{} ) {
  130. this.decodeDracoFile( buffer, onLoad, null, null, SRGBColorSpace, onError ).catch( onError );
  131. }
  132. //
  133. decodeDracoFile( buffer, callback, attributeIDs, attributeTypes, vertexColorSpace = LinearSRGBColorSpace, onError = () => {} ) {
  134. const taskConfig = {
  135. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  136. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  137. useUniqueIDs: !! attributeIDs,
  138. vertexColorSpace: vertexColorSpace,
  139. };
  140. return this.decodeGeometry( buffer, taskConfig ).then( callback ).catch( onError );
  141. }
  142. decodeGeometry( buffer, taskConfig ) {
  143. const taskKey = JSON.stringify( taskConfig );
  144. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  145. // again from this thread.
  146. if ( _taskCache.has( buffer ) ) {
  147. const cachedTask = _taskCache.get( buffer );
  148. if ( cachedTask.key === taskKey ) {
  149. return cachedTask.promise;
  150. } else if ( buffer.byteLength === 0 ) {
  151. // Technically, it would be possible to wait for the previous task to complete,
  152. // transfer the buffer back, and decode again with the second configuration. That
  153. // is complex, and I don't know of any reason to decode a Draco buffer twice in
  154. // different ways, so this is left unimplemented.
  155. throw new Error(
  156. 'THREE.DRACOLoader: Unable to re-decode a buffer with different ' +
  157. 'settings. Buffer has already been transferred.'
  158. );
  159. }
  160. }
  161. //
  162. let worker;
  163. const taskID = this.workerNextTaskID ++;
  164. const taskCost = buffer.byteLength;
  165. // Obtain a worker and assign a task, and construct a geometry instance
  166. // when the task completes.
  167. const geometryPending = this._getWorker( taskID, taskCost )
  168. .then( ( _worker ) => {
  169. worker = _worker;
  170. return new Promise( ( resolve, reject ) => {
  171. worker._callbacks[ taskID ] = { resolve, reject };
  172. worker.postMessage( { type: 'decode', id: taskID, taskConfig, buffer }, [ buffer ] );
  173. // this.debug();
  174. } );
  175. } )
  176. .then( ( message ) => this._createGeometry( message.geometry ) );
  177. // Remove task from the task list.
  178. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  179. geometryPending
  180. .catch( () => true )
  181. .then( () => {
  182. if ( worker && taskID ) {
  183. this._releaseTask( worker, taskID );
  184. // this.debug();
  185. }
  186. } );
  187. // Cache the task result.
  188. _taskCache.set( buffer, {
  189. key: taskKey,
  190. promise: geometryPending
  191. } );
  192. return geometryPending;
  193. }
  194. _createGeometry( geometryData ) {
  195. const geometry = new BufferGeometry();
  196. if ( geometryData.index ) {
  197. geometry.setIndex( new BufferAttribute( geometryData.index.array, 1 ) );
  198. }
  199. for ( let i = 0; i < geometryData.attributes.length; i ++ ) {
  200. const result = geometryData.attributes[ i ];
  201. const name = result.name;
  202. const array = result.array;
  203. const itemSize = result.itemSize;
  204. const attribute = new BufferAttribute( array, itemSize );
  205. if ( name === 'color' ) {
  206. this._assignVertexColorSpace( attribute, result.vertexColorSpace );
  207. attribute.normalized = ( array instanceof Float32Array ) === false;
  208. }
  209. geometry.setAttribute( name, attribute );
  210. }
  211. return geometry;
  212. }
  213. _assignVertexColorSpace( attribute, inputColorSpace ) {
  214. // While .drc files do not specify colorspace, the only 'official' tooling
  215. // is PLY and OBJ converters, which use sRGB. We'll assume sRGB when a .drc
  216. // file is passed into .load() or .parse(). GLTFLoader uses internal APIs
  217. // to decode geometry, and vertex colors are already Linear-sRGB in there.
  218. if ( inputColorSpace !== SRGBColorSpace ) return;
  219. const _color = new Color();
  220. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  221. _color.fromBufferAttribute( attribute, i );
  222. ColorManagement.toWorkingColorSpace( _color, SRGBColorSpace );
  223. attribute.setXYZ( i, _color.r, _color.g, _color.b );
  224. }
  225. }
  226. _loadLibrary( url, responseType ) {
  227. const loader = new FileLoader( this.manager );
  228. loader.setPath( this.decoderPath );
  229. loader.setResponseType( responseType );
  230. loader.setWithCredentials( this.withCredentials );
  231. return new Promise( ( resolve, reject ) => {
  232. loader.load( url, resolve, undefined, reject );
  233. } );
  234. }
  235. preload() {
  236. this._initDecoder();
  237. return this;
  238. }
  239. _initDecoder() {
  240. if ( this.decoderPending ) return this.decoderPending;
  241. const useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  242. const librariesPending = [];
  243. if ( useJS ) {
  244. librariesPending.push( this._loadLibrary( 'draco_decoder.js', 'text' ) );
  245. } else {
  246. librariesPending.push( this._loadLibrary( 'draco_wasm_wrapper.js', 'text' ) );
  247. librariesPending.push( this._loadLibrary( 'draco_decoder.wasm', 'arraybuffer' ) );
  248. }
  249. this.decoderPending = Promise.all( librariesPending )
  250. .then( ( libraries ) => {
  251. const jsContent = libraries[ 0 ];
  252. if ( ! useJS ) {
  253. this.decoderConfig.wasmBinary = libraries[ 1 ];
  254. }
  255. const fn = DRACOWorker.toString();
  256. const body = [
  257. '/* draco decoder */',
  258. jsContent,
  259. '',
  260. '/* worker */',
  261. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  262. ].join( '\n' );
  263. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  264. } );
  265. return this.decoderPending;
  266. }
  267. _getWorker( taskID, taskCost ) {
  268. return this._initDecoder().then( () => {
  269. if ( this.workerPool.length < this.workerLimit ) {
  270. const worker = new Worker( this.workerSourceURL );
  271. worker._callbacks = {};
  272. worker._taskCosts = {};
  273. worker._taskLoad = 0;
  274. worker.postMessage( { type: 'init', decoderConfig: this.decoderConfig } );
  275. worker.onmessage = function ( e ) {
  276. const message = e.data;
  277. switch ( message.type ) {
  278. case 'decode':
  279. worker._callbacks[ message.id ].resolve( message );
  280. break;
  281. case 'error':
  282. worker._callbacks[ message.id ].reject( message );
  283. break;
  284. default:
  285. console.error( 'THREE.DRACOLoader: Unexpected message, "' + message.type + '"' );
  286. }
  287. };
  288. this.workerPool.push( worker );
  289. } else {
  290. this.workerPool.sort( function ( a, b ) {
  291. return a._taskLoad > b._taskLoad ? - 1 : 1;
  292. } );
  293. }
  294. const worker = this.workerPool[ this.workerPool.length - 1 ];
  295. worker._taskCosts[ taskID ] = taskCost;
  296. worker._taskLoad += taskCost;
  297. return worker;
  298. } );
  299. }
  300. _releaseTask( worker, taskID ) {
  301. worker._taskLoad -= worker._taskCosts[ taskID ];
  302. delete worker._callbacks[ taskID ];
  303. delete worker._taskCosts[ taskID ];
  304. }
  305. debug() {
  306. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  307. }
  308. dispose() {
  309. for ( let i = 0; i < this.workerPool.length; ++ i ) {
  310. this.workerPool[ i ].terminate();
  311. }
  312. this.workerPool.length = 0;
  313. if ( this.workerSourceURL !== '' ) {
  314. URL.revokeObjectURL( this.workerSourceURL );
  315. }
  316. return this;
  317. }
  318. }
  319. /* WEB WORKER */
  320. function DRACOWorker() {
  321. let decoderConfig;
  322. let decoderPending;
  323. onmessage = function ( e ) {
  324. const message = e.data;
  325. switch ( message.type ) {
  326. case 'init':
  327. decoderConfig = message.decoderConfig;
  328. decoderPending = new Promise( function ( resolve/*, reject*/ ) {
  329. decoderConfig.onModuleLoaded = function ( draco ) {
  330. // Module is Promise-like. Wrap before resolving to avoid loop.
  331. resolve( { draco: draco } );
  332. };
  333. DracoDecoderModule( decoderConfig ); // eslint-disable-line no-undef
  334. } );
  335. break;
  336. case 'decode':
  337. const buffer = message.buffer;
  338. const taskConfig = message.taskConfig;
  339. decoderPending.then( ( module ) => {
  340. const draco = module.draco;
  341. const decoder = new draco.Decoder();
  342. try {
  343. const geometry = decodeGeometry( draco, decoder, new Int8Array( buffer ), taskConfig );
  344. const buffers = geometry.attributes.map( ( attr ) => attr.array.buffer );
  345. if ( geometry.index ) buffers.push( geometry.index.array.buffer );
  346. self.postMessage( { type: 'decode', id: message.id, geometry }, buffers );
  347. } catch ( error ) {
  348. console.error( error );
  349. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  350. } finally {
  351. draco.destroy( decoder );
  352. }
  353. } );
  354. break;
  355. }
  356. };
  357. function decodeGeometry( draco, decoder, array, taskConfig ) {
  358. const attributeIDs = taskConfig.attributeIDs;
  359. const attributeTypes = taskConfig.attributeTypes;
  360. let dracoGeometry;
  361. let decodingStatus;
  362. const geometryType = decoder.GetEncodedGeometryType( array );
  363. if ( geometryType === draco.TRIANGULAR_MESH ) {
  364. dracoGeometry = new draco.Mesh();
  365. decodingStatus = decoder.DecodeArrayToMesh( array, array.byteLength, dracoGeometry );
  366. } else if ( geometryType === draco.POINT_CLOUD ) {
  367. dracoGeometry = new draco.PointCloud();
  368. decodingStatus = decoder.DecodeArrayToPointCloud( array, array.byteLength, dracoGeometry );
  369. } else {
  370. throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );
  371. }
  372. if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {
  373. throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );
  374. }
  375. const geometry = { index: null, attributes: [] };
  376. // Gather all vertex attributes.
  377. for ( const attributeName in attributeIDs ) {
  378. const attributeType = self[ attributeTypes[ attributeName ] ];
  379. let attribute;
  380. let attributeID;
  381. // A Draco file may be created with default vertex attributes, whose attribute IDs
  382. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  383. // a Draco file may contain a custom set of attributes, identified by known unique
  384. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  385. if ( taskConfig.useUniqueIDs ) {
  386. attributeID = attributeIDs[ attributeName ];
  387. attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );
  388. } else {
  389. attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );
  390. if ( attributeID === - 1 ) continue;
  391. attribute = decoder.GetAttribute( dracoGeometry, attributeID );
  392. }
  393. const attributeResult = decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute );
  394. if ( attributeName === 'color' ) {
  395. attributeResult.vertexColorSpace = taskConfig.vertexColorSpace;
  396. }
  397. geometry.attributes.push( attributeResult );
  398. }
  399. // Add index.
  400. if ( geometryType === draco.TRIANGULAR_MESH ) {
  401. geometry.index = decodeIndex( draco, decoder, dracoGeometry );
  402. }
  403. draco.destroy( dracoGeometry );
  404. return geometry;
  405. }
  406. function decodeIndex( draco, decoder, dracoGeometry ) {
  407. const numFaces = dracoGeometry.num_faces();
  408. const numIndices = numFaces * 3;
  409. const byteLength = numIndices * 4;
  410. const ptr = draco._malloc( byteLength );
  411. decoder.GetTrianglesUInt32Array( dracoGeometry, byteLength, ptr );
  412. const index = new Uint32Array( draco.HEAPF32.buffer, ptr, numIndices ).slice();
  413. draco._free( ptr );
  414. return { array: index, itemSize: 1 };
  415. }
  416. function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {
  417. const numComponents = attribute.num_components();
  418. const numPoints = dracoGeometry.num_points();
  419. const numValues = numPoints * numComponents;
  420. const byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
  421. const dataType = getDracoDataType( draco, attributeType );
  422. const ptr = draco._malloc( byteLength );
  423. decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, dataType, byteLength, ptr );
  424. const array = new attributeType( draco.HEAPF32.buffer, ptr, numValues ).slice();
  425. draco._free( ptr );
  426. return {
  427. name: attributeName,
  428. array: array,
  429. itemSize: numComponents
  430. };
  431. }
  432. function getDracoDataType( draco, attributeType ) {
  433. switch ( attributeType ) {
  434. case Float32Array: return draco.DT_FLOAT32;
  435. case Int8Array: return draco.DT_INT8;
  436. case Int16Array: return draco.DT_INT16;
  437. case Int32Array: return draco.DT_INT32;
  438. case Uint8Array: return draco.DT_UINT8;
  439. case Uint16Array: return draco.DT_UINT16;
  440. case Uint32Array: return draco.DT_UINT32;
  441. }
  442. }
  443. }
  444. export { DRACOLoader };
粤ICP备19079148号