DRACOLoader.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. /** Copyright 2016 The Draco Authors.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. import {
  16. BufferGeometry,
  17. DefaultLoadingManager,
  18. FileLoader,
  19. Float32BufferAttribute,
  20. Int16BufferAttribute,
  21. Int32BufferAttribute,
  22. Int8BufferAttribute,
  23. TriangleStripDrawMode,
  24. TrianglesDrawMode,
  25. Uint16BufferAttribute,
  26. Uint32BufferAttribute,
  27. Uint8BufferAttribute
  28. } from "../../../build/three.module.js";
  29. "use strict";
  30. /**
  31. * @param {THREE.LoadingManager} manager
  32. */
  33. var DRACOLoader = function ( manager ) {
  34. this.timeLoaded = 0;
  35. this.manager = manager || DefaultLoadingManager;
  36. this.materials = null;
  37. this.verbosity = 0;
  38. this.attributeOptions = {};
  39. this.drawMode = TrianglesDrawMode;
  40. // Native Draco attribute type to Three.JS attribute type.
  41. this.nativeAttributeMap = {
  42. position: "POSITION",
  43. normal: "NORMAL",
  44. color: "COLOR",
  45. uv: "TEX_COORD"
  46. };
  47. };
  48. DRACOLoader.prototype = {
  49. constructor: DRACOLoader,
  50. load: function ( url, onLoad, onProgress, onError ) {
  51. var scope = this;
  52. var loader = new FileLoader( scope.manager );
  53. loader.setPath( this.path );
  54. loader.setResponseType( "arraybuffer" );
  55. loader.load(
  56. url,
  57. function ( blob ) {
  58. scope.decodeDracoFile( blob, onLoad );
  59. },
  60. onProgress,
  61. onError
  62. );
  63. },
  64. setPath: function ( value ) {
  65. this.path = value;
  66. return this;
  67. },
  68. setVerbosity: function ( level ) {
  69. this.verbosity = level;
  70. return this;
  71. },
  72. /**
  73. * Sets desired mode for generated geometry indices.
  74. * Can be either:
  75. * TrianglesDrawMode
  76. * TriangleStripDrawMode
  77. */
  78. setDrawMode: function ( drawMode ) {
  79. this.drawMode = drawMode;
  80. return this;
  81. },
  82. /**
  83. * Skips dequantization for a specific attribute.
  84. * |attributeName| is the js name of the given attribute type.
  85. * The only currently supported |attributeName| is 'position', more may be
  86. * added in future.
  87. */
  88. setSkipDequantization: function ( attributeName, skip ) {
  89. var skipDequantization = true;
  90. if ( typeof skip !== "undefined" ) skipDequantization = skip;
  91. this.getAttributeOptions(
  92. attributeName
  93. ).skipDequantization = skipDequantization;
  94. return this;
  95. },
  96. /**
  97. * Decompresses a Draco buffer. Names of attributes (for ID and type maps)
  98. * must be one of the supported three.js types, including: position, color,
  99. * normal, uv, uv2, skinIndex, skinWeight.
  100. *
  101. * @param {ArrayBuffer} rawBuffer
  102. * @param {Function} callback
  103. * @param {Object|undefined} attributeUniqueIdMap Provides a pre-defined ID
  104. * for each attribute in the geometry to be decoded. If given,
  105. * `attributeTypeMap` is required and `nativeAttributeMap` will be
  106. * ignored.
  107. * @param {Object|undefined} attributeTypeMap Provides a predefined data
  108. * type (as a typed array constructor) for each attribute in the
  109. * geometry to be decoded.
  110. */
  111. decodeDracoFile: function (
  112. rawBuffer,
  113. callback,
  114. attributeUniqueIdMap,
  115. attributeTypeMap
  116. ) {
  117. var scope = this;
  118. DRACOLoader.getDecoderModule().then( function ( module ) {
  119. scope.decodeDracoFileInternal(
  120. rawBuffer,
  121. module.decoder,
  122. callback,
  123. attributeUniqueIdMap,
  124. attributeTypeMap
  125. );
  126. } );
  127. },
  128. decodeDracoFileInternal: function (
  129. rawBuffer,
  130. dracoDecoder,
  131. callback,
  132. attributeUniqueIdMap,
  133. attributeTypeMap
  134. ) {
  135. /*
  136. * Here is how to use Draco Javascript decoder and get the geometry.
  137. */
  138. var buffer = new dracoDecoder.DecoderBuffer();
  139. buffer.Init( new Int8Array( rawBuffer ), rawBuffer.byteLength );
  140. var decoder = new dracoDecoder.Decoder();
  141. /*
  142. * Determine what type is this file: mesh or point cloud.
  143. */
  144. var geometryType = decoder.GetEncodedGeometryType( buffer );
  145. if ( geometryType == dracoDecoder.TRIANGULAR_MESH ) {
  146. if ( this.verbosity > 0 ) {
  147. console.log( "Loaded a mesh." );
  148. }
  149. } else if ( geometryType == dracoDecoder.POINT_CLOUD ) {
  150. if ( this.verbosity > 0 ) {
  151. console.log( "Loaded a point cloud." );
  152. }
  153. } else {
  154. var errorMsg = "DRACOLoader: Unknown geometry type.";
  155. console.error( errorMsg );
  156. throw new Error( errorMsg );
  157. }
  158. callback(
  159. this.convertDracoGeometryTo3JS(
  160. dracoDecoder,
  161. decoder,
  162. geometryType,
  163. buffer,
  164. attributeUniqueIdMap,
  165. attributeTypeMap
  166. )
  167. );
  168. },
  169. addAttributeToGeometry: function (
  170. dracoDecoder,
  171. decoder,
  172. dracoGeometry,
  173. attributeName,
  174. attributeType,
  175. attribute,
  176. geometry,
  177. geometryBuffer
  178. ) {
  179. if ( attribute.ptr === 0 ) {
  180. var errorMsg = "DRACOLoader: No attribute " + attributeName;
  181. console.error( errorMsg );
  182. throw new Error( errorMsg );
  183. }
  184. var numComponents = attribute.num_components();
  185. var numPoints = dracoGeometry.num_points();
  186. var numValues = numPoints * numComponents;
  187. var attributeData;
  188. var TypedBufferAttribute;
  189. switch ( attributeType ) {
  190. case Float32Array:
  191. attributeData = new dracoDecoder.DracoFloat32Array();
  192. decoder.GetAttributeFloatForAllPoints(
  193. dracoGeometry,
  194. attribute,
  195. attributeData
  196. );
  197. geometryBuffer[ attributeName ] = new Float32Array( numValues );
  198. TypedBufferAttribute = Float32BufferAttribute;
  199. break;
  200. case Int8Array:
  201. attributeData = new dracoDecoder.DracoInt8Array();
  202. decoder.GetAttributeInt8ForAllPoints(
  203. dracoGeometry,
  204. attribute,
  205. attributeData
  206. );
  207. geometryBuffer[ attributeName ] = new Int8Array( numValues );
  208. TypedBufferAttribute = Int8BufferAttribute;
  209. break;
  210. case Int16Array:
  211. attributeData = new dracoDecoder.DracoInt16Array();
  212. decoder.GetAttributeInt16ForAllPoints(
  213. dracoGeometry,
  214. attribute,
  215. attributeData
  216. );
  217. geometryBuffer[ attributeName ] = new Int16Array( numValues );
  218. TypedBufferAttribute = Int16BufferAttribute;
  219. break;
  220. case Int32Array:
  221. attributeData = new dracoDecoder.DracoInt32Array();
  222. decoder.GetAttributeInt32ForAllPoints(
  223. dracoGeometry,
  224. attribute,
  225. attributeData
  226. );
  227. geometryBuffer[ attributeName ] = new Int32Array( numValues );
  228. TypedBufferAttribute = Int32BufferAttribute;
  229. break;
  230. case Uint8Array:
  231. attributeData = new dracoDecoder.DracoUInt8Array();
  232. decoder.GetAttributeUInt8ForAllPoints(
  233. dracoGeometry,
  234. attribute,
  235. attributeData
  236. );
  237. geometryBuffer[ attributeName ] = new Uint8Array( numValues );
  238. TypedBufferAttribute = Uint8BufferAttribute;
  239. break;
  240. case Uint16Array:
  241. attributeData = new dracoDecoder.DracoUInt16Array();
  242. decoder.GetAttributeUInt16ForAllPoints(
  243. dracoGeometry,
  244. attribute,
  245. attributeData
  246. );
  247. geometryBuffer[ attributeName ] = new Uint16Array( numValues );
  248. TypedBufferAttribute = Uint16BufferAttribute;
  249. break;
  250. case Uint32Array:
  251. attributeData = new dracoDecoder.DracoUInt32Array();
  252. decoder.GetAttributeUInt32ForAllPoints(
  253. dracoGeometry,
  254. attribute,
  255. attributeData
  256. );
  257. geometryBuffer[ attributeName ] = new Uint32Array( numValues );
  258. TypedBufferAttribute = Uint32BufferAttribute;
  259. break;
  260. default:
  261. var errorMsg = "DRACOLoader: Unexpected attribute type.";
  262. console.error( errorMsg );
  263. throw new Error( errorMsg );
  264. }
  265. // Copy data from decoder.
  266. for ( var i = 0; i < numValues; i ++ ) {
  267. geometryBuffer[ attributeName ][ i ] = attributeData.GetValue( i );
  268. }
  269. // Add attribute to THREEJS geometry for rendering.
  270. geometry.addAttribute(
  271. attributeName,
  272. new TypedBufferAttribute( geometryBuffer[ attributeName ], numComponents )
  273. );
  274. dracoDecoder.destroy( attributeData );
  275. },
  276. convertDracoGeometryTo3JS: function (
  277. dracoDecoder,
  278. decoder,
  279. geometryType,
  280. buffer,
  281. attributeUniqueIdMap,
  282. attributeTypeMap
  283. ) {
  284. // TODO: Should not assume native Draco attribute IDs apply.
  285. if ( this.getAttributeOptions( "position" ).skipDequantization === true ) {
  286. decoder.SkipAttributeTransform( dracoDecoder.POSITION );
  287. }
  288. var dracoGeometry;
  289. var decodingStatus;
  290. var start_time = performance.now();
  291. if ( geometryType === dracoDecoder.TRIANGULAR_MESH ) {
  292. dracoGeometry = new dracoDecoder.Mesh();
  293. decodingStatus = decoder.DecodeBufferToMesh( buffer, dracoGeometry );
  294. } else {
  295. dracoGeometry = new dracoDecoder.PointCloud();
  296. decodingStatus = decoder.DecodeBufferToPointCloud( buffer, dracoGeometry );
  297. }
  298. if ( ! decodingStatus.ok() || dracoGeometry.ptr == 0 ) {
  299. var errorMsg = "DRACOLoader: Decoding failed: ";
  300. errorMsg += decodingStatus.error_msg();
  301. console.error( errorMsg );
  302. dracoDecoder.destroy( decoder );
  303. dracoDecoder.destroy( dracoGeometry );
  304. throw new Error( errorMsg );
  305. }
  306. var decode_end = performance.now();
  307. dracoDecoder.destroy( buffer );
  308. /*
  309. * Example on how to retrieve mesh and attributes.
  310. */
  311. var numFaces;
  312. if ( geometryType == dracoDecoder.TRIANGULAR_MESH ) {
  313. numFaces = dracoGeometry.num_faces();
  314. if ( this.verbosity > 0 ) {
  315. console.log( "Number of faces loaded: " + numFaces.toString() );
  316. }
  317. } else {
  318. numFaces = 0;
  319. }
  320. var numPoints = dracoGeometry.num_points();
  321. var numAttributes = dracoGeometry.num_attributes();
  322. if ( this.verbosity > 0 ) {
  323. console.log( "Number of points loaded: " + numPoints.toString() );
  324. console.log( "Number of attributes loaded: " + numAttributes.toString() );
  325. }
  326. // Verify if there is position attribute.
  327. // TODO: Should not assume native Draco attribute IDs apply.
  328. var posAttId = decoder.GetAttributeId( dracoGeometry, dracoDecoder.POSITION );
  329. if ( posAttId == - 1 ) {
  330. var errorMsg = "DRACOLoader: No position attribute found.";
  331. console.error( errorMsg );
  332. dracoDecoder.destroy( decoder );
  333. dracoDecoder.destroy( dracoGeometry );
  334. throw new Error( errorMsg );
  335. }
  336. var posAttribute = decoder.GetAttribute( dracoGeometry, posAttId );
  337. // Structure for converting to THREEJS geometry later.
  338. var geometryBuffer = {};
  339. // Import data to Three JS geometry.
  340. var geometry = new BufferGeometry();
  341. // Do not use both the native attribute map and a provided (e.g. glTF) map.
  342. if ( attributeUniqueIdMap ) {
  343. // Add attributes of user specified unique id. E.g. GLTF models.
  344. for ( var attributeName in attributeUniqueIdMap ) {
  345. var attributeType = attributeTypeMap[ attributeName ];
  346. var attributeId = attributeUniqueIdMap[ attributeName ];
  347. var attribute = decoder.GetAttributeByUniqueId(
  348. dracoGeometry,
  349. attributeId
  350. );
  351. this.addAttributeToGeometry(
  352. dracoDecoder,
  353. decoder,
  354. dracoGeometry,
  355. attributeName,
  356. attributeType,
  357. attribute,
  358. geometry,
  359. geometryBuffer
  360. );
  361. }
  362. } else {
  363. // Add native Draco attribute type to geometry.
  364. for ( var attributeName in this.nativeAttributeMap ) {
  365. var attId = decoder.GetAttributeId(
  366. dracoGeometry,
  367. dracoDecoder[ this.nativeAttributeMap[ attributeName ] ]
  368. );
  369. if ( attId !== - 1 ) {
  370. if ( this.verbosity > 0 ) {
  371. console.log( "Loaded " + attributeName + " attribute." );
  372. }
  373. var attribute = decoder.GetAttribute( dracoGeometry, attId );
  374. this.addAttributeToGeometry(
  375. dracoDecoder,
  376. decoder,
  377. dracoGeometry,
  378. attributeName,
  379. Float32Array,
  380. attribute,
  381. geometry,
  382. geometryBuffer
  383. );
  384. }
  385. }
  386. }
  387. // For mesh, we need to generate the faces.
  388. if ( geometryType == dracoDecoder.TRIANGULAR_MESH ) {
  389. if ( this.drawMode === TriangleStripDrawMode ) {
  390. var stripsArray = new dracoDecoder.DracoInt32Array();
  391. var numStrips = decoder.GetTriangleStripsFromMesh(
  392. dracoGeometry,
  393. stripsArray
  394. );
  395. geometryBuffer.indices = new Uint32Array( stripsArray.size() );
  396. for ( var i = 0; i < stripsArray.size(); ++ i ) {
  397. geometryBuffer.indices[ i ] = stripsArray.GetValue( i );
  398. }
  399. dracoDecoder.destroy( stripsArray );
  400. } else {
  401. var numIndices = numFaces * 3;
  402. geometryBuffer.indices = new Uint32Array( numIndices );
  403. var ia = new dracoDecoder.DracoInt32Array();
  404. for ( var i = 0; i < numFaces; ++ i ) {
  405. decoder.GetFaceFromMesh( dracoGeometry, i, ia );
  406. var index = i * 3;
  407. geometryBuffer.indices[ index ] = ia.GetValue( 0 );
  408. geometryBuffer.indices[ index + 1 ] = ia.GetValue( 1 );
  409. geometryBuffer.indices[ index + 2 ] = ia.GetValue( 2 );
  410. }
  411. dracoDecoder.destroy( ia );
  412. }
  413. }
  414. geometry.drawMode = this.drawMode;
  415. if ( geometryType == dracoDecoder.TRIANGULAR_MESH ) {
  416. geometry.setIndex(
  417. new ( geometryBuffer.indices.length > 65535
  418. ? Uint32BufferAttribute
  419. : Uint16BufferAttribute )( geometryBuffer.indices, 1 )
  420. );
  421. }
  422. // TODO: Should not assume native Draco attribute IDs apply.
  423. // TODO: Can other attribute types be quantized?
  424. var posTransform = new dracoDecoder.AttributeQuantizationTransform();
  425. if ( posTransform.InitFromAttribute( posAttribute ) ) {
  426. // Quantized attribute. Store the quantization parameters into the
  427. // js attribute.
  428. geometry.attributes[ "position" ].isQuantized = true;
  429. geometry.attributes[ "position" ].maxRange = posTransform.range();
  430. geometry.attributes[
  431. "position"
  432. ].numQuantizationBits = posTransform.quantization_bits();
  433. geometry.attributes[ "position" ].minValues = new Float32Array( 3 );
  434. for ( var i = 0; i < 3; ++ i ) {
  435. geometry.attributes[ "position" ].minValues[ i ] = posTransform.min_value(
  436. i
  437. );
  438. }
  439. }
  440. dracoDecoder.destroy( posTransform );
  441. dracoDecoder.destroy( decoder );
  442. dracoDecoder.destroy( dracoGeometry );
  443. this.decode_time = decode_end - start_time;
  444. this.import_time = performance.now() - decode_end;
  445. if ( this.verbosity > 0 ) {
  446. console.log( "Decode time: " + this.decode_time );
  447. console.log( "Import time: " + this.import_time );
  448. }
  449. return geometry;
  450. },
  451. isVersionSupported: function ( version, callback ) {
  452. DRACOLoader.getDecoderModule().then( function ( module ) {
  453. callback( module.decoder.isVersionSupported( version ) );
  454. } );
  455. },
  456. getAttributeOptions: function ( attributeName ) {
  457. if ( typeof this.attributeOptions[ attributeName ] === "undefined" )
  458. this.attributeOptions[ attributeName ] = {};
  459. return this.attributeOptions[ attributeName ];
  460. }
  461. };
  462. DRACOLoader.decoderPath = "./";
  463. DRACOLoader.decoderConfig = {};
  464. DRACOLoader.decoderModulePromise = null;
  465. /**
  466. * Sets the base path for decoder source files.
  467. * @param {string} path
  468. */
  469. DRACOLoader.setDecoderPath = function ( path ) {
  470. DRACOLoader.decoderPath = path;
  471. };
  472. /**
  473. * Sets decoder configuration and releases singleton decoder module. Module
  474. * will be recreated with the next decoding call.
  475. * @param {Object} config
  476. */
  477. DRACOLoader.setDecoderConfig = function ( config ) {
  478. var wasmBinary = DRACOLoader.decoderConfig.wasmBinary;
  479. DRACOLoader.decoderConfig = config || {};
  480. DRACOLoader.releaseDecoderModule();
  481. // Reuse WASM binary.
  482. if ( wasmBinary ) DRACOLoader.decoderConfig.wasmBinary = wasmBinary;
  483. };
  484. /**
  485. * Releases the singleton DracoDecoderModule instance. Module will be recreated
  486. * with the next decoding call.
  487. */
  488. DRACOLoader.releaseDecoderModule = function () {
  489. DRACOLoader.decoderModulePromise = null;
  490. };
  491. /**
  492. * Gets WebAssembly or asm.js singleton instance of DracoDecoderModule
  493. * after testing for browser support. Returns Promise that resolves when
  494. * module is available.
  495. * @return {Promise<{decoder: DracoDecoderModule}>}
  496. */
  497. DRACOLoader.getDecoderModule = function () {
  498. var scope = this;
  499. var path = DRACOLoader.decoderPath;
  500. var config = DRACOLoader.decoderConfig;
  501. var promise = DRACOLoader.decoderModulePromise;
  502. if ( promise ) return promise;
  503. // Load source files.
  504. if ( typeof DracoDecoderModule !== "undefined" ) {
  505. // Loaded externally.
  506. promise = Promise.resolve();
  507. } else if ( typeof WebAssembly !== "object" || config.type === "js" ) {
  508. // Load with asm.js.
  509. promise = DRACOLoader._loadScript( path + "draco_decoder.js" );
  510. } else {
  511. // Load with WebAssembly.
  512. config.wasmBinaryFile = path + "draco_decoder.wasm";
  513. promise = DRACOLoader._loadScript( path + "draco_wasm_wrapper.js" )
  514. .then( function () {
  515. return DRACOLoader._loadArrayBuffer( config.wasmBinaryFile );
  516. } )
  517. .then( function ( wasmBinary ) {
  518. config.wasmBinary = wasmBinary;
  519. } );
  520. }
  521. // Wait for source files, then create and return a decoder.
  522. promise = promise.then( function () {
  523. return new Promise( function ( resolve ) {
  524. config.onModuleLoaded = function ( decoder ) {
  525. scope.timeLoaded = performance.now();
  526. // Module is Promise-like. Wrap before resolving to avoid loop.
  527. resolve( { decoder: decoder } );
  528. };
  529. DracoDecoderModule( config );
  530. } );
  531. } );
  532. DRACOLoader.decoderModulePromise = promise;
  533. return promise;
  534. };
  535. /**
  536. * @param {string} src
  537. * @return {Promise}
  538. */
  539. DRACOLoader._loadScript = function ( src ) {
  540. var prevScript = document.getElementById( "decoder_script" );
  541. if ( prevScript !== null ) {
  542. prevScript.parentNode.removeChild( prevScript );
  543. }
  544. var head = document.getElementsByTagName( "head" )[ 0 ];
  545. var script = document.createElement( "script" );
  546. script.id = "decoder_script";
  547. script.type = "text/javascript";
  548. script.src = src;
  549. return new Promise( function ( resolve ) {
  550. script.onload = resolve;
  551. head.appendChild( script );
  552. } );
  553. };
  554. /**
  555. * @param {string} src
  556. * @return {Promise}
  557. */
  558. DRACOLoader._loadArrayBuffer = function ( src ) {
  559. var loader = new FileLoader();
  560. loader.setResponseType( "arraybuffer" );
  561. return new Promise( function ( resolve, reject ) {
  562. loader.load( src, resolve, undefined, reject );
  563. } );
  564. };
  565. export { DRACOLoader };