DRACOLoader.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. var scope = this;
  95. THREE.DRACOLoader.getDecoderModule()
  96. .then( function ( module ) {
  97. scope.decodeDracoFileInternal( rawBuffer, module.decoder, callback,
  98. attributeUniqueIdMap || {});
  99. });
  100. },
  101. decodeDracoFileInternal: function(rawBuffer, dracoDecoder, callback,
  102. attributeUniqueIdMap) {
  103. /*
  104. * Here is how to use Draco Javascript decoder and get the geometry.
  105. */
  106. var buffer = new dracoDecoder.DecoderBuffer();
  107. buffer.Init(new Int8Array(rawBuffer), rawBuffer.byteLength);
  108. var decoder = new dracoDecoder.Decoder();
  109. /*
  110. * Determine what type is this file: mesh or point cloud.
  111. */
  112. var geometryType = decoder.GetEncodedGeometryType(buffer);
  113. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  114. if (this.verbosity > 0) {
  115. console.log('Loaded a mesh.');
  116. }
  117. } else if (geometryType == dracoDecoder.POINT_CLOUD) {
  118. if (this.verbosity > 0) {
  119. console.log('Loaded a point cloud.');
  120. }
  121. } else {
  122. var errorMsg = 'THREE.DRACOLoader: Unknown geometry type.'
  123. console.error(errorMsg);
  124. throw new Error(errorMsg);
  125. }
  126. callback(this.convertDracoGeometryTo3JS(dracoDecoder, decoder,
  127. geometryType, buffer, attributeUniqueIdMap));
  128. },
  129. addAttributeToGeometry: function(dracoDecoder, decoder, dracoGeometry,
  130. attributeName, attribute, geometry,
  131. geometryBuffer) {
  132. if (attribute.ptr === 0) {
  133. var errorMsg = 'THREE.DRACOLoader: No attribute ' + attributeName;
  134. console.error(errorMsg);
  135. throw new Error(errorMsg);
  136. }
  137. var numComponents = attribute.num_components();
  138. var attributeData = new dracoDecoder.DracoFloat32Array();
  139. decoder.GetAttributeFloatForAllPoints(
  140. dracoGeometry, attribute, attributeData);
  141. var numPoints = dracoGeometry.num_points();
  142. var numValues = numPoints * numComponents;
  143. // Allocate space for attribute.
  144. geometryBuffer[attributeName] = new Float32Array(numValues);
  145. // Copy data from decoder.
  146. for (var i = 0; i < numValues; i++) {
  147. geometryBuffer[attributeName][i] = attributeData.GetValue(i);
  148. }
  149. // Add attribute to THREEJS geometry for rendering.
  150. geometry.addAttribute(attributeName,
  151. new THREE.Float32BufferAttribute(geometryBuffer[attributeName],
  152. numComponents));
  153. dracoDecoder.destroy(attributeData);
  154. },
  155. convertDracoGeometryTo3JS: function(dracoDecoder, decoder, geometryType,
  156. buffer, attributeUniqueIdMap) {
  157. if (this.getAttributeOptions('position').skipDequantization === true) {
  158. decoder.SkipAttributeTransform(dracoDecoder.POSITION);
  159. }
  160. var dracoGeometry;
  161. var decodingStatus;
  162. const start_time = performance.now();
  163. if (geometryType === dracoDecoder.TRIANGULAR_MESH) {
  164. dracoGeometry = new dracoDecoder.Mesh();
  165. decodingStatus = decoder.DecodeBufferToMesh(buffer, dracoGeometry);
  166. } else {
  167. dracoGeometry = new dracoDecoder.PointCloud();
  168. decodingStatus =
  169. decoder.DecodeBufferToPointCloud(buffer, dracoGeometry);
  170. }
  171. if (!decodingStatus.ok() || dracoGeometry.ptr == 0) {
  172. var errorMsg = 'THREE.DRACOLoader: Decoding failed: ';
  173. errorMsg += decodingStatus.error_msg();
  174. console.error(errorMsg);
  175. dracoDecoder.destroy(decoder);
  176. dracoDecoder.destroy(dracoGeometry);
  177. throw new Error(errorMsg);
  178. }
  179. var decode_end = performance.now();
  180. dracoDecoder.destroy(buffer);
  181. /*
  182. * Example on how to retrieve mesh and attributes.
  183. */
  184. var numFaces;
  185. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  186. numFaces = dracoGeometry.num_faces();
  187. if (this.verbosity > 0) {
  188. console.log('Number of faces loaded: ' + numFaces.toString());
  189. }
  190. } else {
  191. numFaces = 0;
  192. }
  193. var numPoints = dracoGeometry.num_points();
  194. var numAttributes = dracoGeometry.num_attributes();
  195. if (this.verbosity > 0) {
  196. console.log('Number of points loaded: ' + numPoints.toString());
  197. console.log('Number of attributes loaded: ' +
  198. numAttributes.toString());
  199. }
  200. // Verify if there is position attribute.
  201. var posAttId = decoder.GetAttributeId(dracoGeometry,
  202. dracoDecoder.POSITION);
  203. if (posAttId == -1) {
  204. var errorMsg = 'THREE.DRACOLoader: No position attribute found.';
  205. console.error(errorMsg);
  206. dracoDecoder.destroy(decoder);
  207. dracoDecoder.destroy(dracoGeometry);
  208. throw new Error(errorMsg);
  209. }
  210. var posAttribute = decoder.GetAttribute(dracoGeometry, posAttId);
  211. // Structure for converting to THREEJS geometry later.
  212. var geometryBuffer = {};
  213. // Import data to Three JS geometry.
  214. var geometry = new THREE.BufferGeometry();
  215. // Add native Draco attribute type to geometry.
  216. for (var attributeName in this.nativeAttributeMap) {
  217. // The native attribute type is only used when no unique Id is
  218. // provided. For example, loading .drc files.
  219. if (attributeUniqueIdMap[attributeName] === undefined) {
  220. var attId = decoder.GetAttributeId(dracoGeometry,
  221. dracoDecoder[this.nativeAttributeMap[attributeName]]);
  222. if (attId !== -1) {
  223. if (this.verbosity > 0) {
  224. console.log('Loaded ' + attributeName + ' attribute.');
  225. }
  226. var attribute = decoder.GetAttribute(dracoGeometry, attId);
  227. this.addAttributeToGeometry(dracoDecoder, decoder, dracoGeometry,
  228. attributeName, attribute, geometry, geometryBuffer);
  229. }
  230. }
  231. }
  232. // Add attributes of user specified unique id. E.g. GLTF models.
  233. for (var attributeName in attributeUniqueIdMap) {
  234. var attributeId = attributeUniqueIdMap[attributeName];
  235. var attribute = decoder.GetAttributeByUniqueId(dracoGeometry,
  236. attributeId);
  237. this.addAttributeToGeometry(dracoDecoder, decoder, dracoGeometry,
  238. attributeName, attribute, geometry, geometryBuffer);
  239. }
  240. // For mesh, we need to generate the faces.
  241. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  242. if (this.drawMode === THREE.TriangleStripDrawMode) {
  243. var stripsArray = new dracoDecoder.DracoInt32Array();
  244. var numStrips = decoder.GetTriangleStripsFromMesh(
  245. dracoGeometry, stripsArray);
  246. geometryBuffer.indices = new Uint32Array(stripsArray.size());
  247. for (var i = 0; i < stripsArray.size(); ++i) {
  248. geometryBuffer.indices[i] = stripsArray.GetValue(i);
  249. }
  250. dracoDecoder.destroy(stripsArray);
  251. } else {
  252. var numIndices = numFaces * 3;
  253. geometryBuffer.indices = new Uint32Array(numIndices);
  254. var ia = new dracoDecoder.DracoInt32Array();
  255. for (var i = 0; i < numFaces; ++i) {
  256. decoder.GetFaceFromMesh(dracoGeometry, i, ia);
  257. var index = i * 3;
  258. geometryBuffer.indices[index] = ia.GetValue(0);
  259. geometryBuffer.indices[index + 1] = ia.GetValue(1);
  260. geometryBuffer.indices[index + 2] = ia.GetValue(2);
  261. }
  262. dracoDecoder.destroy(ia);
  263. }
  264. }
  265. geometry.drawMode = this.drawMode;
  266. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  267. geometry.setIndex(new(geometryBuffer.indices.length > 65535 ?
  268. THREE.Uint32BufferAttribute : THREE.Uint16BufferAttribute)
  269. (geometryBuffer.indices, 1));
  270. }
  271. var posTransform = new dracoDecoder.AttributeQuantizationTransform();
  272. if (posTransform.InitFromAttribute(posAttribute)) {
  273. // Quantized attribute. Store the quantization parameters into the
  274. // THREE.js attribute.
  275. geometry.attributes['position'].isQuantized = true;
  276. geometry.attributes['position'].maxRange = posTransform.range();
  277. geometry.attributes['position'].numQuantizationBits =
  278. posTransform.quantization_bits();
  279. geometry.attributes['position'].minValues = new Float32Array(3);
  280. for (var i = 0; i < 3; ++i) {
  281. geometry.attributes['position'].minValues[i] =
  282. posTransform.min_value(i);
  283. }
  284. }
  285. dracoDecoder.destroy(posTransform);
  286. dracoDecoder.destroy(decoder);
  287. dracoDecoder.destroy(dracoGeometry);
  288. this.decode_time = decode_end - start_time;
  289. this.import_time = performance.now() - decode_end;
  290. if (this.verbosity > 0) {
  291. console.log('Decode time: ' + this.decode_time);
  292. console.log('Import time: ' + this.import_time);
  293. }
  294. return geometry;
  295. },
  296. isVersionSupported: function(version, callback) {
  297. THREE.DRACOLoader.getDecoderModule()
  298. .then( function ( module ) {
  299. callback( module.decoder.isVersionSupported( version ) );
  300. });
  301. },
  302. getAttributeOptions: function(attributeName) {
  303. if (typeof this.attributeOptions[attributeName] === 'undefined')
  304. this.attributeOptions[attributeName] = {};
  305. return this.attributeOptions[attributeName];
  306. }
  307. };
  308. THREE.DRACOLoader.decoderPath = './';
  309. THREE.DRACOLoader.decoderConfig = {};
  310. THREE.DRACOLoader.decoderModulePromise = null;
  311. /**
  312. * Sets the base path for decoder source files.
  313. * @param {string} path
  314. */
  315. THREE.DRACOLoader.setDecoderPath = function ( path ) {
  316. THREE.DRACOLoader.decoderPath = path;
  317. };
  318. /**
  319. * Sets decoder configuration and releases singleton decoder module. Module
  320. * will be recreated with the next decoding call.
  321. * @param {Object} config
  322. */
  323. THREE.DRACOLoader.setDecoderConfig = function ( config ) {
  324. var wasmBinary = THREE.DRACOLoader.decoderConfig.wasmBinary;
  325. THREE.DRACOLoader.decoderConfig = config || {};
  326. THREE.DRACOLoader.releaseDecoderModule();
  327. // Reuse WASM binary.
  328. if ( wasmBinary ) THREE.DRACOLoader.decoderConfig.wasmBinary = wasmBinary;
  329. };
  330. /**
  331. * Releases the singleton DracoDecoderModule instance. Module will be recreated
  332. * with the next decoding call.
  333. */
  334. THREE.DRACOLoader.releaseDecoderModule = function () {
  335. THREE.DRACOLoader.decoderModulePromise = null;
  336. };
  337. /**
  338. * Gets WebAssembly or asm.js singleton instance of DracoDecoderModule
  339. * after testing for browser support. Returns Promise that resolves when
  340. * module is available.
  341. * @return {Promise<{decoder: DracoDecoderModule}>}
  342. */
  343. THREE.DRACOLoader.getDecoderModule = function () {
  344. var scope = this;
  345. var path = THREE.DRACOLoader.decoderPath;
  346. var config = THREE.DRACOLoader.decoderConfig;
  347. var promise = THREE.DRACOLoader.decoderModulePromise;
  348. if ( promise ) return promise;
  349. // Load source files.
  350. if ( typeof DracoDecoderModule !== 'undefined' ) {
  351. // Loaded externally.
  352. promise = Promise.resolve();
  353. } else if ( typeof WebAssembly !== 'object' || config.type === 'js' ) {
  354. // Load with asm.js.
  355. promise = THREE.DRACOLoader._loadScript( path + 'draco_decoder.js' );
  356. } else {
  357. // Load with WebAssembly.
  358. config.wasmBinaryFile = path + 'draco_decoder.wasm';
  359. promise = THREE.DRACOLoader._loadScript( path + 'draco_wasm_wrapper.js' )
  360. .then( function () {
  361. return THREE.DRACOLoader._loadArrayBuffer( config.wasmBinaryFile );
  362. } )
  363. .then( function ( wasmBinary ) {
  364. config.wasmBinary = wasmBinary;
  365. } );
  366. }
  367. // Wait for source files, then create and return a decoder.
  368. promise = promise.then( function () {
  369. return new Promise( function ( resolve ) {
  370. config.onModuleLoaded = function ( decoder ) {
  371. scope.timeLoaded = performance.now();
  372. // Module is Promise-like. Wrap before resolving to avoid loop.
  373. resolve( { decoder: decoder } );
  374. };
  375. DracoDecoderModule( config );
  376. } );
  377. } );
  378. THREE.DRACOLoader.decoderModulePromise = promise;
  379. return promise;
  380. };
  381. /**
  382. * @param {string} src
  383. * @return {Promise}
  384. */
  385. THREE.DRACOLoader._loadScript = function ( src ) {
  386. var prevScript = document.getElementById( 'decoder_script' );
  387. if ( prevScript !== null ) {
  388. prevScript.parentNode.removeChild( prevScript );
  389. }
  390. var head = document.getElementsByTagName( 'head' )[ 0 ];
  391. var script = document.createElement( 'script' );
  392. script.id = 'decoder_script';
  393. script.type = 'text/javascript';
  394. script.src = src;
  395. return new Promise( function ( resolve ) {
  396. script.onload = resolve;
  397. head.appendChild( script );
  398. });
  399. };
  400. /**
  401. * @param {string} src
  402. * @return {Promise}
  403. */
  404. THREE.DRACOLoader._loadArrayBuffer = function ( src ) {
  405. var loader = new THREE.FileLoader();
  406. loader.setResponseType( 'arraybuffer' );
  407. return new Promise( function( resolve, reject ) {
  408. loader.load( src, resolve, undefined, reject );
  409. });
  410. };