DRACOLoader.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. // User defined unique id for attributes.
  27. this.attributeUniqueIdMap = {};
  28. // Native Draco attribute type to Three.JS attribute type.
  29. this.nativeAttributeMap = {
  30. 'position' : 'POSITION',
  31. 'normal' : 'NORMAL',
  32. 'color' : 'COLOR',
  33. 'uv' : 'TEX_COORD'
  34. };
  35. };
  36. THREE.DRACOLoader.prototype = {
  37. constructor: THREE.DRACOLoader,
  38. load: function(url, onLoad, onProgress, onError) {
  39. var scope = this;
  40. var loader = new THREE.FileLoader(scope.manager);
  41. loader.setPath(this.path);
  42. loader.setResponseType('arraybuffer');
  43. if (this.crossOrigin !== undefined) {
  44. loader.crossOrigin = this.crossOrigin;
  45. }
  46. loader.load(url, function(blob) {
  47. scope.decodeDracoFile(blob, onLoad);
  48. }, onProgress, onError);
  49. },
  50. setPath: function(value) {
  51. this.path = value;
  52. },
  53. setCrossOrigin: function(value) {
  54. this.crossOrigin = value;
  55. },
  56. setVerbosity: function(level) {
  57. this.verbosity = level;
  58. },
  59. /**
  60. * Sets desired mode for generated geometry indices.
  61. * Can be either:
  62. * THREE.TrianglesDrawMode
  63. * THREE.TriangleStripDrawMode
  64. */
  65. setDrawMode: function(drawMode) {
  66. this.drawMode = drawMode;
  67. },
  68. /**
  69. * Skips dequantization for a specific attribute.
  70. * |attributeName| is the THREE.js name of the given attribute type.
  71. * The only currently supported |attributeName| is 'position', more may be
  72. * added in future.
  73. */
  74. setSkipDequantization: function(attributeName, skip) {
  75. var skipDequantization = true;
  76. if (typeof skip !== 'undefined')
  77. skipDequantization = skip;
  78. this.getAttributeOptions(attributeName).skipDequantization =
  79. skipDequantization;
  80. },
  81. /**
  82. * |attributeUniqueIdMap| specifies attribute unique id for an attribute in
  83. * the geometry to be decoded. The name of the attribute must be one of the
  84. * supported attribute type in Three.JS, including:
  85. * 'position',
  86. * 'color',
  87. * 'normal',
  88. * 'uv',
  89. * 'uv2',
  90. * 'skinIndex',
  91. * 'skinWeight'.
  92. * The format is:
  93. * attributeUniqueIdMap[attributeName] = attributeId
  94. */
  95. decodeDracoFile: function(rawBuffer, callback, attributeUniqueIdMap) {
  96. var scope = this;
  97. this.attributeUniqueIdMap = attributeUniqueIdMap || {};
  98. THREE.DRACOLoader.getDecoderModule()
  99. .then( function ( module ) {
  100. scope.decodeDracoFileInternal( rawBuffer, module.decoder, callback );
  101. });
  102. },
  103. decodeDracoFileInternal: function(rawBuffer, dracoDecoder, callback) {
  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));
  129. },
  130. addAttributeToGeometry: function(dracoDecoder, decoder, dracoGeometry,
  131. attributeName, attribute, geometry,
  132. 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 attributeData = new dracoDecoder.DracoFloat32Array();
  140. decoder.GetAttributeFloatForAllPoints(
  141. dracoGeometry, attribute, attributeData);
  142. var numPoints = dracoGeometry.num_points();
  143. var numValues = numPoints * numComponents;
  144. // Allocate space for attribute.
  145. geometryBuffer[attributeName] = new Float32Array(numValues);
  146. // Copy data from decoder.
  147. for (var i = 0; i < numValues; i++) {
  148. geometryBuffer[attributeName][i] = attributeData.GetValue(i);
  149. }
  150. // Add attribute to THREEJS geometry for rendering.
  151. geometry.addAttribute(attributeName,
  152. new THREE.Float32BufferAttribute(geometryBuffer[attributeName],
  153. numComponents));
  154. dracoDecoder.destroy(attributeData);
  155. },
  156. convertDracoGeometryTo3JS: function(dracoDecoder, decoder, geometryType,
  157. buffer) {
  158. if (this.getAttributeOptions('position').skipDequantization === true) {
  159. decoder.SkipAttributeTransform(dracoDecoder.POSITION);
  160. }
  161. var dracoGeometry;
  162. var decodingStatus;
  163. const start_time = performance.now();
  164. if (geometryType === dracoDecoder.TRIANGULAR_MESH) {
  165. dracoGeometry = new dracoDecoder.Mesh();
  166. decodingStatus = decoder.DecodeBufferToMesh(buffer, dracoGeometry);
  167. } else {
  168. dracoGeometry = new dracoDecoder.PointCloud();
  169. decodingStatus =
  170. decoder.DecodeBufferToPointCloud(buffer, dracoGeometry);
  171. }
  172. if (!decodingStatus.ok() || dracoGeometry.ptr == 0) {
  173. var errorMsg = 'THREE.DRACOLoader: Decoding failed: ';
  174. errorMsg += decodingStatus.error_msg();
  175. console.error(errorMsg);
  176. dracoDecoder.destroy(decoder);
  177. dracoDecoder.destroy(dracoGeometry);
  178. throw new Error(errorMsg);
  179. }
  180. var decode_end = performance.now();
  181. dracoDecoder.destroy(buffer);
  182. /*
  183. * Example on how to retrieve mesh and attributes.
  184. */
  185. var numFaces;
  186. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  187. numFaces = dracoGeometry.num_faces();
  188. if (this.verbosity > 0) {
  189. console.log('Number of faces loaded: ' + numFaces.toString());
  190. }
  191. } else {
  192. numFaces = 0;
  193. }
  194. var numPoints = dracoGeometry.num_points();
  195. var numAttributes = dracoGeometry.num_attributes();
  196. if (this.verbosity > 0) {
  197. console.log('Number of points loaded: ' + numPoints.toString());
  198. console.log('Number of attributes loaded: ' +
  199. numAttributes.toString());
  200. }
  201. // Verify if there is position attribute.
  202. var posAttId = decoder.GetAttributeId(dracoGeometry,
  203. dracoDecoder.POSITION);
  204. if (posAttId == -1) {
  205. var errorMsg = 'THREE.DRACOLoader: No position attribute found.';
  206. console.error(errorMsg);
  207. dracoDecoder.destroy(decoder);
  208. dracoDecoder.destroy(dracoGeometry);
  209. throw new Error(errorMsg);
  210. }
  211. var posAttribute = decoder.GetAttribute(dracoGeometry, posAttId);
  212. // Structure for converting to THREEJS geometry later.
  213. var geometryBuffer = {};
  214. // Import data to Three JS geometry.
  215. var geometry = new THREE.BufferGeometry();
  216. // Add native Draco attribute type to geometry.
  217. for (var attributeName in this.nativeAttributeMap) {
  218. // The native attribute type is only used when no unique Id is
  219. // provided. For example, loading .drc files.
  220. if (this.attributeUniqueIdMap[attributeName] === undefined) {
  221. var attId = decoder.GetAttributeId(dracoGeometry,
  222. dracoDecoder[this.nativeAttributeMap[attributeName]]);
  223. if (attId !== -1) {
  224. if (this.verbosity > 0) {
  225. console.log('Loaded ' + attributeName + ' attribute.');
  226. }
  227. var attribute = decoder.GetAttribute(dracoGeometry, attId);
  228. this.addAttributeToGeometry(dracoDecoder, decoder, dracoGeometry,
  229. attributeName, attribute, geometry, geometryBuffer);
  230. }
  231. }
  232. }
  233. // Add attributes of user specified unique id. E.g. GLTF models.
  234. for (var attributeName in this.attributeUniqueIdMap) {
  235. var attributeId = this.attributeUniqueIdMap[attributeName];
  236. var attribute = decoder.GetAttributeByUniqueId(dracoGeometry,
  237. attributeId);
  238. this.addAttributeToGeometry(dracoDecoder, decoder, dracoGeometry,
  239. attributeName, attribute, geometry, geometryBuffer);
  240. }
  241. // For mesh, we need to generate the faces.
  242. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  243. if (this.drawMode === THREE.TriangleStripDrawMode) {
  244. var stripsArray = new dracoDecoder.DracoInt32Array();
  245. var numStrips = decoder.GetTriangleStripsFromMesh(
  246. dracoGeometry, stripsArray);
  247. geometryBuffer.indices = new Uint32Array(stripsArray.size());
  248. for (var i = 0; i < stripsArray.size(); ++i) {
  249. geometryBuffer.indices[i] = stripsArray.GetValue(i);
  250. }
  251. dracoDecoder.destroy(stripsArray);
  252. } else {
  253. var numIndices = numFaces * 3;
  254. geometryBuffer.indices = new Uint32Array(numIndices);
  255. var ia = new dracoDecoder.DracoInt32Array();
  256. for (var i = 0; i < numFaces; ++i) {
  257. decoder.GetFaceFromMesh(dracoGeometry, i, ia);
  258. var index = i * 3;
  259. geometryBuffer.indices[index] = ia.GetValue(0);
  260. geometryBuffer.indices[index + 1] = ia.GetValue(1);
  261. geometryBuffer.indices[index + 2] = ia.GetValue(2);
  262. }
  263. dracoDecoder.destroy(ia);
  264. }
  265. }
  266. geometry.drawMode = this.drawMode;
  267. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  268. geometry.setIndex(new(geometryBuffer.indices.length > 65535 ?
  269. THREE.Uint32BufferAttribute : THREE.Uint16BufferAttribute)
  270. (geometryBuffer.indices, 1));
  271. }
  272. var posTransform = new dracoDecoder.AttributeQuantizationTransform();
  273. if (posTransform.InitFromAttribute(posAttribute)) {
  274. // Quantized attribute. Store the quantization parameters into the
  275. // THREE.js attribute.
  276. geometry.attributes['position'].isQuantized = true;
  277. geometry.attributes['position'].maxRange = posTransform.range();
  278. geometry.attributes['position'].numQuantizationBits =
  279. posTransform.quantization_bits();
  280. geometry.attributes['position'].minValues = new Float32Array(3);
  281. for (var i = 0; i < 3; ++i) {
  282. geometry.attributes['position'].minValues[i] =
  283. posTransform.min_value(i);
  284. }
  285. }
  286. dracoDecoder.destroy(posTransform);
  287. dracoDecoder.destroy(decoder);
  288. dracoDecoder.destroy(dracoGeometry);
  289. this.decode_time = decode_end - start_time;
  290. this.import_time = performance.now() - decode_end;
  291. if (this.verbosity > 0) {
  292. console.log('Decode time: ' + this.decode_time);
  293. console.log('Import time: ' + this.import_time);
  294. }
  295. return geometry;
  296. },
  297. isVersionSupported: function(version, callback) {
  298. THREE.DRACOLoader.getDecoderModule()
  299. .then( function ( module ) {
  300. callback( module.decoder.isVersionSupported( version ) );
  301. });
  302. },
  303. getAttributeOptions: function(attributeName) {
  304. if (typeof this.attributeOptions[attributeName] === 'undefined')
  305. this.attributeOptions[attributeName] = {};
  306. return this.attributeOptions[attributeName];
  307. }
  308. };
  309. THREE.DRACOLoader.decoderPath = './';
  310. THREE.DRACOLoader.decoderConfig = {};
  311. THREE.DRACOLoader.decoderModulePromise = null;
  312. /**
  313. * Sets the base path for decoder source files.
  314. * @param {string} path
  315. */
  316. THREE.DRACOLoader.setDecoderPath = function ( path ) {
  317. THREE.DRACOLoader.decoderPath = path;
  318. };
  319. /**
  320. * Sets decoder configuration and releases singleton decoder module. Module
  321. * will be recreated with the next decoding call.
  322. * @param {Object} config
  323. */
  324. THREE.DRACOLoader.setDecoderConfig = function ( config ) {
  325. var wasmBinary = THREE.DRACOLoader.decoderConfig.wasmBinary;
  326. THREE.DRACOLoader.decoderConfig = config || {};
  327. THREE.DRACOLoader.decoderModulePromise = null;
  328. // Reuse WASM binary.
  329. if ( wasmBinary ) THREE.DRACOLoader.decoderConfig.wasmBinary = wasmBinary;
  330. };
  331. /**
  332. * Gets WebAssembly or asm.js singleton instance of DracoDecoderModule
  333. * after testing for browser support. Returns Promise that resolves when
  334. * module is available.
  335. * @return {Promise<{decoder: DracoDecoderModule}>}
  336. */
  337. THREE.DRACOLoader.getDecoderModule = function () {
  338. var scope = this;
  339. var path = THREE.DRACOLoader.decoderPath;
  340. var config = THREE.DRACOLoader.decoderConfig;
  341. var promise = THREE.DRACOLoader.decoderModulePromise;
  342. if ( promise ) return promise;
  343. // Load source files.
  344. if ( typeof DracoDecoderModule !== 'undefined' ) {
  345. // Loaded externally.
  346. promise = Promise.resolve();
  347. } else if ( typeof WebAssembly !== 'object' || config.type === 'js' ) {
  348. // Load with asm.js.
  349. promise = THREE.DRACOLoader._loadScript( path + 'draco_decoder.js' );
  350. } else {
  351. // Load with WebAssembly.
  352. config.wasmBinaryFile = path + 'draco_decoder.wasm';
  353. promise = THREE.DRACOLoader._loadScript( path + 'draco_wasm_wrapper.js' )
  354. .then( function () {
  355. return THREE.DRACOLoader._loadArrayBuffer( config.wasmBinaryFile );
  356. } )
  357. .then( function ( wasmBinary ) {
  358. config.wasmBinary = wasmBinary;
  359. } );
  360. }
  361. // Wait for source files, then create and return a decoder.
  362. promise = promise.then( function () {
  363. return new Promise( function ( resolve ) {
  364. config.onModuleLoaded = function ( decoder ) {
  365. scope.timeLoaded = performance.now();
  366. // Module is Promise-like. Wrap before resolving to avoid loop.
  367. resolve( { decoder: decoder } );
  368. };
  369. DracoDecoderModule( config );
  370. } );
  371. } );
  372. THREE.DRACOLoader.decoderModulePromise = promise;
  373. return promise;
  374. };
  375. /**
  376. * @param {string} src
  377. * @return {Promise}
  378. */
  379. THREE.DRACOLoader._loadScript = function ( src ) {
  380. var prevScript = document.getElementById( 'decoder_script' );
  381. if ( prevScript !== null ) {
  382. prevScript.parentNode.removeChild( prevScript );
  383. }
  384. var head = document.getElementsByTagName( 'head' )[ 0 ];
  385. var script = document.createElement( 'script' );
  386. script.id = 'decoder_script';
  387. script.type = 'text/javascript';
  388. script.src = src;
  389. return new Promise( function ( resolve ) {
  390. script.onload = resolve;
  391. head.appendChild( script );
  392. });
  393. };
  394. /**
  395. * @param {string} src
  396. * @return {Promise}
  397. */
  398. THREE.DRACOLoader._loadArrayBuffer = function ( src ) {
  399. var loader = new THREE.FileLoader();
  400. loader.setResponseType( 'arraybuffer' );
  401. return new Promise( function( resolve, reject ) {
  402. loader.load( src, resolve, undefined, reject );
  403. });
  404. };