DRACOLoader.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. /**
  2. * @author Don McCurdy / https://www.donmccurdy.com
  3. */
  4. THREE.DRACOLoader = function ( manager ) {
  5. THREE.Loader.call( this, 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. THREE.DRACOLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  28. constructor: THREE.DRACOLoader,
  29. setDecoderPath: function ( path ) {
  30. this.decoderPath = path;
  31. return this;
  32. },
  33. setDecoderConfig: function ( config ) {
  34. this.decoderConfig = config;
  35. return this;
  36. },
  37. setWorkerLimit: function ( workerLimit ) {
  38. this.workerLimit = workerLimit;
  39. return this;
  40. },
  41. /** @deprecated */
  42. setVerbosity: function () {
  43. console.warn( 'THREE.DRACOLoader: The .setVerbosity() method has been removed.' );
  44. },
  45. /** @deprecated */
  46. setDrawMode: function () {
  47. console.warn( 'THREE.DRACOLoader: The .setDrawMode() method has been removed.' );
  48. },
  49. /** @deprecated */
  50. setSkipDequantization: function () {
  51. console.warn( 'THREE.DRACOLoader: The .setSkipDequantization() method has been removed.' );
  52. },
  53. load: function ( url, onLoad, onProgress, onError ) {
  54. var loader = new THREE.FileLoader( this.manager );
  55. loader.setPath( this.path );
  56. loader.setResponseType( 'arraybuffer' );
  57. if ( this.crossOrigin === 'use-credentials' ) {
  58. loader.setWithCredentials( true );
  59. }
  60. loader.load( url, ( buffer ) => {
  61. var taskConfig = {
  62. attributeIDs: this.defaultAttributeIDs,
  63. attributeTypes: this.defaultAttributeTypes,
  64. useUniqueIDs: false
  65. };
  66. this.decodeGeometry( buffer, taskConfig )
  67. .then( onLoad )
  68. .catch( onError );
  69. }, onProgress, onError );
  70. },
  71. /** @deprecated Kept for backward-compatibility with previous DRACOLoader versions. */
  72. decodeDracoFile: function ( buffer, callback, attributeIDs, attributeTypes ) {
  73. var taskConfig = {
  74. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  75. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  76. useUniqueIDs: !! attributeIDs
  77. };
  78. this.decodeGeometry( buffer, taskConfig ).then( callback );
  79. },
  80. decodeGeometry: function ( buffer, taskConfig ) {
  81. var worker;
  82. var taskID = this.workerNextTaskID ++;
  83. var taskCost = buffer.byteLength;
  84. // TODO: For backward-compatibility, support 'attributeTypes' objects containing
  85. // references (rather than names) to typed array constructors. These must be
  86. // serialized before sending them to the worker.
  87. for ( var attribute in taskConfig.attributeTypes ) {
  88. var type = taskConfig.attributeTypes[ attribute ];
  89. if ( type.BYTES_PER_ELEMENT !== undefined ) {
  90. taskConfig.attributeTypes[ attribute ] = type.name;
  91. }
  92. }
  93. // Obtain a worker and assign a task, and construct a geometry instance
  94. // when the task completes.
  95. var geometryPending = this._getWorker( taskID, taskCost )
  96. .then( ( _worker ) => {
  97. worker = _worker;
  98. return new Promise( ( resolve, reject ) => {
  99. worker._callbacks[ taskID ] = { resolve, reject };
  100. worker.postMessage( { type: 'decode', id: taskID, taskConfig, buffer }, [ buffer ] );
  101. // this.debug();
  102. } );
  103. } )
  104. .then( ( message ) => this._createGeometry( message.geometry ) );
  105. // Remove task from the task list.
  106. geometryPending
  107. .finally( () => {
  108. if ( worker && taskID ) {
  109. this._releaseTask( worker, taskID );
  110. // this.debug();
  111. }
  112. } );
  113. return geometryPending;
  114. },
  115. _createGeometry: function ( geometryData ) {
  116. var geometry = new THREE.BufferGeometry();
  117. if ( geometryData.index ) {
  118. geometry.setIndex( new THREE.BufferAttribute( geometryData.index.array, 1 ) );
  119. }
  120. for ( var i = 0; i < geometryData.attributes.length; i ++ ) {
  121. var attribute = geometryData.attributes[ i ];
  122. var name = attribute.name;
  123. var array = attribute.array;
  124. var itemSize = attribute.itemSize;
  125. geometry.setAttribute( name, new THREE.BufferAttribute( array, itemSize ) );
  126. }
  127. return geometry;
  128. },
  129. _loadLibrary: function ( url, responseType ) {
  130. var loader = new THREE.FileLoader( this.manager );
  131. loader.setPath( this.decoderPath );
  132. loader.setResponseType( responseType );
  133. return new Promise( ( resolve, reject ) => {
  134. loader.load( url, resolve, undefined, reject );
  135. } );
  136. },
  137. _initDecoder: function () {
  138. if ( this.decoderPending ) return this.decoderPending;
  139. var useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  140. var librariesPending = [];
  141. if ( useJS ) {
  142. librariesPending.push( this._loadLibrary( 'draco_decoder.js', 'text' ) );
  143. } else {
  144. librariesPending.push( this._loadLibrary( 'draco_wasm_wrapper.js', 'text' ) );
  145. librariesPending.push( this._loadLibrary( 'draco_decoder.wasm', 'arraybuffer' ) );
  146. }
  147. this.decoderPending = Promise.all( librariesPending )
  148. .then( ( libraries ) => {
  149. var jsContent = libraries[ 0 ];
  150. if ( ! useJS ) {
  151. this.decoderConfig.wasmBinary = libraries[ 1 ];
  152. }
  153. var fn = THREE.DRACOLoader.DRACOWorker.toString();
  154. var body = [
  155. '/* draco decoder */',
  156. jsContent,
  157. '',
  158. '/* worker */',
  159. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  160. ].join( '\n' );
  161. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  162. } );
  163. return this.decoderPending;
  164. },
  165. _getWorker: function ( taskID, taskCost ) {
  166. return this._initDecoder().then( () => {
  167. if ( this.workerPool.length < this.workerLimit ) {
  168. var worker = new Worker( this.workerSourceURL );
  169. worker._callbacks = {};
  170. worker._taskCosts = {};
  171. worker._taskLoad = 0;
  172. worker.postMessage( { type: 'init', decoderConfig: this.decoderConfig } );
  173. worker.onmessage = function ( e ) {
  174. var message = e.data;
  175. switch ( message.type ) {
  176. case 'decode':
  177. worker._callbacks[ message.id ].resolve( message );
  178. break;
  179. case 'error':
  180. worker._callbacks[ message.id ].reject( message );
  181. break;
  182. default:
  183. console.error( 'THREE.DRACOLoader: Unexpected message, "' + message.type + '"' );
  184. }
  185. };
  186. this.workerPool.push( worker );
  187. } else {
  188. this.workerPool.sort( function ( a, b ) {
  189. return a._taskLoad > b._taskLoad ? - 1 : 1;
  190. } );
  191. }
  192. var worker = this.workerPool[ this.workerPool.length - 1 ];
  193. worker._taskCosts[ taskID ] = taskCost;
  194. worker._taskLoad += taskCost;
  195. return worker;
  196. } );
  197. },
  198. _releaseTask: function ( worker, taskID ) {
  199. worker._taskLoad -= worker._taskCosts[ taskID ];
  200. delete worker._callbacks[ taskID ];
  201. delete worker._taskCosts[ taskID ];
  202. },
  203. debug: function () {
  204. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  205. },
  206. dispose: function () {
  207. for ( var i = 0; i < this.workerPool.length; ++ i ) {
  208. this.workerPool[ i ].terminate();
  209. }
  210. this.workerPool.length = 0;
  211. return this;
  212. }
  213. } );
  214. /* WEB WORKER */
  215. THREE.DRACOLoader.DRACOWorker = function () {
  216. var decoderConfig;
  217. var decoderPending;
  218. onmessage = function ( e ) {
  219. var message = e.data;
  220. switch ( message.type ) {
  221. case 'init':
  222. decoderConfig = message.decoderConfig;
  223. decoderPending = new Promise( function ( resolve/*, reject*/ ) {
  224. decoderConfig.onModuleLoaded = function ( draco ) {
  225. // Module is Promise-like. Wrap before resolving to avoid loop.
  226. resolve( { draco: draco } );
  227. };
  228. DracoDecoderModule( decoderConfig );
  229. } );
  230. break;
  231. case 'decode':
  232. var buffer = message.buffer;
  233. var taskConfig = message.taskConfig;
  234. decoderPending.then( ( module ) => {
  235. var draco = module.draco;
  236. var decoder = new draco.Decoder();
  237. var decoderBuffer = new draco.DecoderBuffer();
  238. decoderBuffer.Init( new Int8Array( buffer ), buffer.byteLength );
  239. try {
  240. var geometry = decodeGeometry( draco, decoder, decoderBuffer, taskConfig );
  241. var buffers = geometry.attributes.map( ( attr ) => attr.array.buffer );
  242. if ( geometry.index ) buffers.push( geometry.index.array.buffer );
  243. self.postMessage( { type: 'decode', id: message.id, geometry }, buffers );
  244. } catch ( error ) {
  245. console.error( error );
  246. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  247. } finally {
  248. draco.destroy( decoderBuffer );
  249. draco.destroy( decoder );
  250. }
  251. } );
  252. break;
  253. }
  254. };
  255. function decodeGeometry( draco, decoder, decoderBuffer, taskConfig ) {
  256. var attributeIDs = taskConfig.attributeIDs;
  257. var attributeTypes = taskConfig.attributeTypes;
  258. var dracoGeometry;
  259. var decodingStatus;
  260. var geometryType = decoder.GetEncodedGeometryType( decoderBuffer );
  261. if ( geometryType === draco.TRIANGULAR_MESH ) {
  262. dracoGeometry = new draco.Mesh();
  263. decodingStatus = decoder.DecodeBufferToMesh( decoderBuffer, dracoGeometry );
  264. } else if ( geometryType === draco.POINT_CLOUD ) {
  265. dracoGeometry = new draco.PointCloud();
  266. decodingStatus = decoder.DecodeBufferToPointCloud( decoderBuffer, dracoGeometry );
  267. } else {
  268. throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );
  269. }
  270. if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {
  271. throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );
  272. }
  273. var geometry = { index: null, attributes: [] };
  274. // Gather all vertex attributes.
  275. for ( var attributeName in attributeIDs ) {
  276. var attributeType = self[ attributeTypes[ attributeName ] ];
  277. var attribute;
  278. var attributeID;
  279. // A Draco file may be created with default vertex attributes, whose attribute IDs
  280. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  281. // a Draco file may contain a custom set of attributes, identified by known unique
  282. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  283. if ( taskConfig.useUniqueIDs ) {
  284. attributeID = attributeIDs[ attributeName ];
  285. attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );
  286. } else {
  287. attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );
  288. if ( attributeID === - 1 ) continue;
  289. attribute = decoder.GetAttribute( dracoGeometry, attributeID );
  290. }
  291. geometry.attributes.push( decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) );
  292. }
  293. // Add index.
  294. if ( geometryType === draco.TRIANGULAR_MESH ) {
  295. // Generate mesh faces.
  296. var numFaces = dracoGeometry.num_faces();
  297. var numIndices = numFaces * 3;
  298. var index = new Uint32Array( numIndices );
  299. var indexArray = new draco.DracoInt32Array();
  300. for ( var i = 0; i < numFaces; ++ i ) {
  301. decoder.GetFaceFromMesh( dracoGeometry, i, indexArray );
  302. for ( var j = 0; j < 3; ++ j ) {
  303. index[ i * 3 + j ] = indexArray.GetValue( j );
  304. }
  305. }
  306. geometry.index = { array: index, itemSize: 1 };
  307. draco.destroy( indexArray );
  308. }
  309. draco.destroy( dracoGeometry );
  310. return geometry;
  311. }
  312. function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {
  313. var numComponents = attribute.num_components();
  314. var numPoints = dracoGeometry.num_points();
  315. var numValues = numPoints * numComponents;
  316. var dracoArray;
  317. var array;
  318. switch ( attributeType ) {
  319. case Float32Array:
  320. dracoArray = new draco.DracoFloat32Array();
  321. decoder.GetAttributeFloatForAllPoints( dracoGeometry, attribute, dracoArray );
  322. array = new Float32Array( numValues );
  323. break;
  324. case Int8Array:
  325. dracoArray = new draco.DracoInt8Array();
  326. decoder.GetAttributeInt8ForAllPoints( dracoGeometry, attribute, dracoArray );
  327. array = new Int8Array( numValues );
  328. break;
  329. case Int16Array:
  330. dracoArray = new draco.DracoInt16Array();
  331. decoder.GetAttributeInt16ForAllPoints( dracoGeometry, attribute, dracoArray );
  332. array = new Int16Array( numValues );
  333. break;
  334. case Int32Array:
  335. dracoArray = new draco.DracoInt32Array();
  336. decoder.GetAttributeInt32ForAllPoints( dracoGeometry, attribute, dracoArray );
  337. array = new Int32Array( numValues );
  338. break;
  339. case Uint8Array:
  340. dracoArray = new draco.DracoUInt8Array();
  341. decoder.GetAttributeUInt8ForAllPoints( dracoGeometry, attribute, dracoArray );
  342. array = new Uint8Array( numValues );
  343. break;
  344. case Uint16Array:
  345. dracoArray = new draco.DracoUInt16Array();
  346. decoder.GetAttributeUInt16ForAllPoints( dracoGeometry, attribute, dracoArray );
  347. array = new Uint16Array( numValues );
  348. break;
  349. case Uint32Array:
  350. dracoArray = new draco.DracoUInt32Array();
  351. decoder.GetAttributeUInt32ForAllPoints( dracoGeometry, attribute, dracoArray );
  352. array = new Uint32Array( numValues );
  353. break;
  354. default:
  355. throw new Error( 'THREE.DRACOLoader: Unexpected attribute type.' );
  356. }
  357. for ( var i = 0; i < numValues; i ++ ) {
  358. array[ i ] = dracoArray.GetValue( i );
  359. }
  360. draco.destroy( dracoArray );
  361. return {
  362. name: attributeName,
  363. array: array,
  364. itemSize: numComponents
  365. };
  366. }
  367. };
  368. /** Deprecated static methods */
  369. /** @deprecated */
  370. THREE.DRACOLoader.setDecoderPath = function () {
  371. console.warn( 'THREE.DRACOLoader: The .setDecoderPath() method has been removed. Use instance methods.' );
  372. };
  373. /** @deprecated */
  374. THREE.DRACOLoader.setDecoderConfig = function () {
  375. console.warn( 'THREE.DRACOLoader: The .setDecoderConfig() method has been removed. Use instance methods.' );
  376. };
  377. /** @deprecated */
  378. THREE.DRACOLoader.releaseDecoderModule = function () {
  379. console.warn( 'THREE.DRACOLoader: The .releaseDecoderModule() method has been removed. Use instance methods.' );
  380. };
  381. /** @deprecated */
  382. THREE.DRACOLoader.getDecoderModule = function () {
  383. console.warn( 'THREE.DRACOLoader: The .getDecoderModule() method has been removed. Use instance methods.' );
  384. };