DRACOLoader.js 14 KB

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