DRACOLoader.js 13 KB

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