DRACOLoader.js 13 KB

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