DRACOLoader.js 12 KB

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