DRACOLoader.js 19 KB

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