DRACOLoader.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. // |dracoPath| sets the path for the Draco decoder source files. The default
  17. // path is "./". If |dracoDecoderType|.type is set to "js", then DRACOLoader
  18. // will load the Draco JavaScript decoder.
  19. THREE.DRACOLoader = function(dracoPath, dracoDecoderType, manager) {
  20. this.timeLoaded = 0;
  21. this.manager = (manager !== undefined) ? manager :
  22. THREE.DefaultLoadingManager;
  23. this.materials = null;
  24. this.verbosity = 0;
  25. this.attributeOptions = {};
  26. this.dracoDecoderType =
  27. (dracoDecoderType !== undefined) ? dracoDecoderType : {};
  28. this.drawMode = THREE.TrianglesDrawMode;
  29. this.dracoSrcPath = (dracoPath !== undefined) ? dracoPath : './';
  30. if (typeof DracoDecoderModule === 'undefined') {
  31. THREE.DRACOLoader.loadDracoDecoder(this);
  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. decodeDracoFile: function(rawBuffer, callback) {
  80. var scope = this;
  81. THREE.DRACOLoader.getDecoder(this,
  82. function(dracoDecoder) {
  83. scope.decodeDracoFileInternal(rawBuffer, dracoDecoder, callback);
  84. });
  85. },
  86. decodeDracoFileInternal : function(rawBuffer, dracoDecoder, callback) {
  87. /*
  88. * Here is how to use Draco Javascript decoder and get the geometry.
  89. */
  90. var buffer = new dracoDecoder.DecoderBuffer();
  91. buffer.Init(new Int8Array(rawBuffer), rawBuffer.byteLength);
  92. var decoder = new dracoDecoder.Decoder();
  93. /*
  94. * Determine what type is this file: mesh or point cloud.
  95. */
  96. var geometryType = decoder.GetEncodedGeometryType(buffer);
  97. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  98. if (this.verbosity > 0) {
  99. console.log('Loaded a mesh.');
  100. }
  101. } else if (geometryType == dracoDecoder.POINT_CLOUD) {
  102. if (this.verbosity > 0) {
  103. console.log('Loaded a point cloud.');
  104. }
  105. } else {
  106. var errorMsg = 'THREE.DRACOLoader: Unknown geometry type.'
  107. console.error(errorMsg);
  108. throw new Error(errorMsg);
  109. }
  110. callback(this.convertDracoGeometryTo3JS(dracoDecoder, decoder,
  111. geometryType, buffer));
  112. },
  113. convertDracoGeometryTo3JS: function(dracoDecoder, decoder, geometryType,
  114. buffer) {
  115. if (this.getAttributeOptions('position').skipDequantization === true) {
  116. decoder.SkipAttributeTransform(dracoDecoder.POSITION);
  117. }
  118. var dracoGeometry;
  119. var decodingStatus;
  120. const start_time = performance.now();
  121. if (geometryType === dracoDecoder.TRIANGULAR_MESH) {
  122. dracoGeometry = new dracoDecoder.Mesh();
  123. decodingStatus = decoder.DecodeBufferToMesh(buffer, dracoGeometry);
  124. } else {
  125. dracoGeometry = new dracoDecoder.PointCloud();
  126. decodingStatus =
  127. decoder.DecodeBufferToPointCloud(buffer, dracoGeometry);
  128. }
  129. if (!decodingStatus.ok() || dracoGeometry.ptr == 0) {
  130. var errorMsg = 'THREE.DRACOLoader: Decoding failed: ';
  131. errorMsg += decodingStatus.error_msg();
  132. console.error(errorMsg);
  133. dracoDecoder.destroy(decoder);
  134. dracoDecoder.destroy(dracoGeometry);
  135. throw new Error(errorMsg);
  136. }
  137. var decode_end = performance.now();
  138. dracoDecoder.destroy(buffer);
  139. /*
  140. * Example on how to retrieve mesh and attributes.
  141. */
  142. var numFaces, numPoints;
  143. var numVertexCoordinates, numTextureCoordinates, numColorCoordinates;
  144. var numAttributes;
  145. var numColorCoordinateComponents = 3;
  146. // For output basic geometry information.
  147. var geometryInfoStr;
  148. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  149. numFaces = dracoGeometry.num_faces();
  150. if (this.verbosity > 0) {
  151. console.log('Number of faces loaded: ' + numFaces.toString());
  152. }
  153. } else {
  154. numFaces = 0;
  155. }
  156. numPoints = dracoGeometry.num_points();
  157. numVertexCoordinates = numPoints * 3;
  158. numTextureCoordinates = numPoints * 2;
  159. numColorCoordinates = numPoints * 3;
  160. numAttributes = dracoGeometry.num_attributes();
  161. if (this.verbosity > 0) {
  162. console.log('Number of points loaded: ' + numPoints.toString());
  163. console.log('Number of attributes loaded: ' +
  164. numAttributes.toString());
  165. }
  166. // Get position attribute. Must exists.
  167. var posAttId = decoder.GetAttributeId(dracoGeometry,
  168. dracoDecoder.POSITION);
  169. if (posAttId == -1) {
  170. var errorMsg = 'THREE.DRACOLoader: No position attribute found.';
  171. console.error(errorMsg);
  172. dracoDecoder.destroy(decoder);
  173. dracoDecoder.destroy(dracoGeometry);
  174. throw new Error(errorMsg);
  175. }
  176. var posAttribute = decoder.GetAttribute(dracoGeometry, posAttId);
  177. var posAttributeData = new dracoDecoder.DracoFloat32Array();
  178. decoder.GetAttributeFloatForAllPoints(
  179. dracoGeometry, posAttribute, posAttributeData);
  180. // Get color attributes if exists.
  181. var colorAttId = decoder.GetAttributeId(dracoGeometry,
  182. dracoDecoder.COLOR);
  183. var colAttributeData;
  184. if (colorAttId != -1) {
  185. if (this.verbosity > 0) {
  186. console.log('Loaded color attribute.');
  187. }
  188. var colAttribute = decoder.GetAttribute(dracoGeometry, colorAttId);
  189. if (colAttribute.num_components() === 4) {
  190. numColorCoordinates = numPoints * 4;
  191. numColorCoordinateComponents = 4;
  192. }
  193. colAttributeData = new dracoDecoder.DracoFloat32Array();
  194. decoder.GetAttributeFloatForAllPoints(dracoGeometry, colAttribute,
  195. colAttributeData);
  196. }
  197. // Get normal attributes if exists.
  198. var normalAttId =
  199. decoder.GetAttributeId(dracoGeometry, dracoDecoder.NORMAL);
  200. var norAttributeData;
  201. if (normalAttId != -1) {
  202. if (this.verbosity > 0) {
  203. console.log('Loaded normal attribute.');
  204. }
  205. var norAttribute = decoder.GetAttribute(dracoGeometry, normalAttId);
  206. norAttributeData = new dracoDecoder.DracoFloat32Array();
  207. decoder.GetAttributeFloatForAllPoints(dracoGeometry, norAttribute,
  208. norAttributeData);
  209. }
  210. // Get texture coord attributes if exists.
  211. var texCoordAttId =
  212. decoder.GetAttributeId(dracoGeometry, dracoDecoder.TEX_COORD);
  213. var textCoordAttributeData;
  214. if (texCoordAttId != -1) {
  215. if (this.verbosity > 0) {
  216. console.log('Loaded texture coordinate attribute.');
  217. }
  218. var texCoordAttribute = decoder.GetAttribute(dracoGeometry,
  219. texCoordAttId);
  220. textCoordAttributeData = new dracoDecoder.DracoFloat32Array();
  221. decoder.GetAttributeFloatForAllPoints(dracoGeometry,
  222. texCoordAttribute,
  223. textCoordAttributeData);
  224. }
  225. // Structure for converting to THREEJS geometry later.
  226. var geometryBuffer = {
  227. vertices: new Float32Array(numVertexCoordinates),
  228. normals: new Float32Array(numVertexCoordinates),
  229. uvs: new Float32Array(numTextureCoordinates),
  230. colors: new Float32Array(numColorCoordinates)
  231. };
  232. for (var i = 0; i < numVertexCoordinates; i += 3) {
  233. geometryBuffer.vertices[i] = posAttributeData.GetValue(i);
  234. geometryBuffer.vertices[i + 1] = posAttributeData.GetValue(i + 1);
  235. geometryBuffer.vertices[i + 2] = posAttributeData.GetValue(i + 2);
  236. // Add normal.
  237. if (normalAttId != -1) {
  238. geometryBuffer.normals[i] = norAttributeData.GetValue(i);
  239. geometryBuffer.normals[i + 1] = norAttributeData.GetValue(i + 1);
  240. geometryBuffer.normals[i + 2] = norAttributeData.GetValue(i + 2);
  241. }
  242. }
  243. // Add color.
  244. for (var i = 0; i < numColorCoordinates; i += 1) {
  245. if (colorAttId != -1) {
  246. // Draco colors are already normalized.
  247. geometryBuffer.colors[i] = colAttributeData.GetValue(i);
  248. } else {
  249. // Default is white. This is faster than TypedArray.fill().
  250. geometryBuffer.colors[i] = 1.0;
  251. }
  252. }
  253. // Add texture coordinates.
  254. if (texCoordAttId != -1) {
  255. for (var i = 0; i < numTextureCoordinates; i += 2) {
  256. geometryBuffer.uvs[i] = textCoordAttributeData.GetValue(i);
  257. geometryBuffer.uvs[i + 1] = textCoordAttributeData.GetValue(i + 1);
  258. }
  259. }
  260. dracoDecoder.destroy(posAttributeData);
  261. if (colorAttId != -1)
  262. dracoDecoder.destroy(colAttributeData);
  263. if (normalAttId != -1)
  264. dracoDecoder.destroy(norAttributeData);
  265. if (texCoordAttId != -1)
  266. dracoDecoder.destroy(textCoordAttributeData);
  267. // For mesh, we need to generate the faces.
  268. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  269. if (this.drawMode === THREE.TriangleStripDrawMode) {
  270. var stripsArray = new dracoDecoder.DracoInt32Array();
  271. var numStrips = decoder.GetTriangleStripsFromMesh(
  272. dracoGeometry, stripsArray);
  273. geometryBuffer.indices = new Uint32Array(stripsArray.size());
  274. for (var i = 0; i < stripsArray.size(); ++i) {
  275. geometryBuffer.indices[i] = stripsArray.GetValue(i);
  276. }
  277. dracoDecoder.destroy(stripsArray);
  278. } else {
  279. var numIndices = numFaces * 3;
  280. geometryBuffer.indices = new Uint32Array(numIndices);
  281. var ia = new dracoDecoder.DracoInt32Array();
  282. for (var i = 0; i < numFaces; ++i) {
  283. decoder.GetFaceFromMesh(dracoGeometry, i, ia);
  284. var index = i * 3;
  285. geometryBuffer.indices[index] = ia.GetValue(0);
  286. geometryBuffer.indices[index + 1] = ia.GetValue(1);
  287. geometryBuffer.indices[index + 2] = ia.GetValue(2);
  288. }
  289. dracoDecoder.destroy(ia);
  290. }
  291. }
  292. // Import data to Three JS geometry.
  293. var geometry = new THREE.BufferGeometry();
  294. geometry.drawMode = this.drawMode;
  295. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  296. geometry.setIndex(new(geometryBuffer.indices.length > 65535 ?
  297. THREE.Uint32BufferAttribute : THREE.Uint16BufferAttribute)
  298. (geometryBuffer.indices, 1));
  299. }
  300. geometry.addAttribute('position',
  301. new THREE.Float32BufferAttribute(geometryBuffer.vertices, 3));
  302. var posTransform = new dracoDecoder.AttributeQuantizationTransform();
  303. if (posTransform.InitFromAttribute(posAttribute)) {
  304. // Quantized attribute. Store the quantization parameters into the
  305. // THREE.js attribute.
  306. geometry.attributes['position'].isQuantized = true;
  307. geometry.attributes['position'].maxRange = posTransform.range();
  308. geometry.attributes['position'].numQuantizationBits =
  309. posTransform.quantization_bits();
  310. geometry.attributes['position'].minValues = new Float32Array(3);
  311. for (var i = 0; i < 3; ++i) {
  312. geometry.attributes['position'].minValues[i] =
  313. posTransform.min_value(i);
  314. }
  315. }
  316. dracoDecoder.destroy(posTransform);
  317. geometry.addAttribute('color',
  318. new THREE.Float32BufferAttribute(geometryBuffer.colors,
  319. numColorCoordinateComponents));
  320. if (normalAttId != -1) {
  321. geometry.addAttribute('normal',
  322. new THREE.Float32BufferAttribute(geometryBuffer.normals, 3));
  323. }
  324. if (texCoordAttId != -1) {
  325. geometry.addAttribute('uv',
  326. new THREE.Float32BufferAttribute(geometryBuffer.uvs, 2));
  327. }
  328. dracoDecoder.destroy(decoder);
  329. dracoDecoder.destroy(dracoGeometry);
  330. this.decode_time = decode_end - start_time;
  331. this.import_time = performance.now() - decode_end;
  332. if (this.verbosity > 0) {
  333. console.log('Decode time: ' + this.decode_time);
  334. console.log('Import time: ' + this.import_time);
  335. }
  336. return geometry;
  337. },
  338. isVersionSupported: function(version, callback) {
  339. THREE.DRACOLoader.getDecoder(this,
  340. function(decoder) {
  341. callback(decoder.isVersionSupported(version));
  342. });
  343. },
  344. getAttributeOptions: function(attributeName) {
  345. if (typeof this.attributeOptions[attributeName] === 'undefined')
  346. this.attributeOptions[attributeName] = {};
  347. return this.attributeOptions[attributeName];
  348. }
  349. };
  350. // This function loads a JavaScript file and adds it to the page. "path"
  351. // is the path to the JavaScript file. "onLoadFunc" is the function to be
  352. // called when the JavaScript file has been loaded.
  353. THREE.DRACOLoader.loadJavaScriptFile = function(path, onLoadFunc,
  354. dracoDecoder) {
  355. var head = document.getElementsByTagName('head')[0];
  356. var element = document.createElement('script');
  357. element.id = "decoder_script";
  358. element.type = 'text/javascript';
  359. element.src = path;
  360. if (onLoadFunc !== null) {
  361. element.onload = onLoadFunc(dracoDecoder);
  362. } else {
  363. element.onload = function(dracoDecoder) {
  364. dracoDecoder.timeLoaded = performance.now();
  365. };
  366. }
  367. var previous_decoder_script = document.getElementById("decoder_script");
  368. if (previous_decoder_script !== null) {
  369. previous_decoder_script.parentNode.removeChild(previous_decoder_script);
  370. }
  371. head.appendChild(element);
  372. }
  373. THREE.DRACOLoader.loadWebAssemblyDecoder = function(dracoDecoder) {
  374. dracoDecoder.dracoDecoderType['wasmBinaryFile'] =
  375. dracoDecoder.dracoSrcPath + 'draco_decoder.wasm';
  376. var xhr = new XMLHttpRequest();
  377. xhr.open('GET', dracoDecoder.dracoSrcPath + 'draco_decoder.wasm', true);
  378. xhr.responseType = 'arraybuffer';
  379. xhr.onload = function() {
  380. // draco_wasm_wrapper.js must be loaded before DracoDecoderModule is
  381. // created. The object passed into DracoDecoderModule() must contain a
  382. // property with the name of wasmBinary and the value must be an
  383. // ArrayBuffer containing the contents of the .wasm file.
  384. dracoDecoder.dracoDecoderType['wasmBinary'] = xhr.response;
  385. dracoDecoder.timeLoaded = performance.now();
  386. };
  387. xhr.send(null)
  388. }
  389. // This function will test if the browser has support for WebAssembly. If
  390. // it does it will download the WebAssembly Draco decoder, if not it will
  391. // download the asmjs Draco decoder.
  392. THREE.DRACOLoader.loadDracoDecoder = function(dracoDecoder) {
  393. if (typeof WebAssembly !== 'object' ||
  394. dracoDecoder.dracoDecoderType.type === 'js') {
  395. // No WebAssembly support
  396. THREE.DRACOLoader.loadJavaScriptFile(dracoDecoder.dracoSrcPath +
  397. 'draco_decoder.js', null, dracoDecoder);
  398. } else {
  399. THREE.DRACOLoader.loadJavaScriptFile(dracoDecoder.dracoSrcPath +
  400. 'draco_wasm_wrapper.js',
  401. function (dracoDecoder) {
  402. THREE.DRACOLoader.loadWebAssemblyDecoder(dracoDecoder);
  403. }, dracoDecoder);
  404. }
  405. }
  406. /**
  407. * Creates and returns a singleton instance of the DracoDecoderModule.
  408. * The module loading is done asynchronously for WebAssembly. Initialized module
  409. * can be accessed through the callback function
  410. * |onDracoDecoderModuleLoadedCallback|.
  411. */
  412. THREE.DRACOLoader.getDecoder = (function() {
  413. var decoder;
  414. var decoderCreationCalled = false;
  415. return function(dracoDecoder, onDracoDecoderModuleLoadedCallback) {
  416. if (typeof decoder !== 'undefined') {
  417. // Module already initialized.
  418. if (typeof onDracoDecoderModuleLoadedCallback !== 'undefined') {
  419. onDracoDecoderModuleLoadedCallback(decoder);
  420. }
  421. } else {
  422. if (typeof DracoDecoderModule === 'undefined') {
  423. // Wait until the Draco decoder is loaded before starting the error
  424. // timer.
  425. if (dracoDecoder.timeLoaded > 0) {
  426. var waitMs = performance.now() - dracoDecoder.timeLoaded;
  427. // After loading the Draco JavaScript decoder file, there is still
  428. // some time before the DracoDecoderModule is defined. So start a
  429. // loop to check when the DracoDecoderModule gets defined. If the
  430. // time is hit throw an error.
  431. if (waitMs > 5000) {
  432. throw new Error(
  433. 'THREE.DRACOLoader: DracoDecoderModule not found.');
  434. }
  435. }
  436. } else {
  437. if (!decoderCreationCalled) {
  438. decoderCreationCalled = true;
  439. dracoDecoder.dracoDecoderType['onModuleLoaded'] =
  440. function(module) {
  441. if (typeof onDracoDecoderModuleLoadedCallback ===
  442. 'function') {
  443. decoder = module;
  444. }
  445. };
  446. DracoDecoderModule(dracoDecoder.dracoDecoderType);
  447. }
  448. }
  449. // Either the DracoDecoderModule has not been defined or the decoder
  450. // has not been created yet. Call getDecoder() again.
  451. setTimeout(function() {
  452. THREE.DRACOLoader.getDecoder(dracoDecoder,
  453. onDracoDecoderModuleLoadedCallback);
  454. }, 10);
  455. }
  456. };
  457. })();