DRACOLoader.js 12 KB

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