DRACOLoader.js 17 KB

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