DRACOLoader.js 19 KB

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