DRACOLoader.js 19 KB

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