DRACOLoader.js 13 KB

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