DRACOLoader.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. THREE.DRACOLoader = function(manager) {
  17. this.manager = (manager !== undefined) ? manager :
  18. THREE.DefaultLoadingManager;
  19. this.materials = null;
  20. this.verbosity = 0;
  21. this.dracoDecoderType = {};
  22. };
  23. THREE.DRACOLoader.prototype = {
  24. constructor: THREE.DRACOLoader,
  25. load: function(url, onLoad, onProgress, onError) {
  26. const scope = this;
  27. const loader = new THREE.FileLoader(scope.manager);
  28. loader.setPath(this.path);
  29. loader.setResponseType('arraybuffer');
  30. loader.load(url, function(blob) {
  31. scope.decodeDracoFile(blob, onLoad);
  32. }, onProgress, onError);
  33. },
  34. setPath: function(value) {
  35. this.path = value;
  36. },
  37. setVerbosity: function(level) {
  38. this.verbosity = level;
  39. },
  40. setDracoDecoderType: function(dracoDecoderType) {
  41. this.dracoDecoderType = dracoDecoderType;
  42. },
  43. decodeDracoFile: function(rawBuffer, callback) {
  44. const scope = this;
  45. THREE.DRACOLoader.getDecoder(this.dracoDecoderType,
  46. function(dracoDecoder) {
  47. scope.decodeDracoFileInternal(rawBuffer, dracoDecoder, callback);
  48. });
  49. },
  50. decodeDracoFileInternal : function(rawBuffer, dracoDecoder, callback) {
  51. /*
  52. * Here is how to use Draco Javascript decoder and get the geometry.
  53. */
  54. const buffer = new dracoDecoder.DecoderBuffer();
  55. buffer.Init(new Int8Array(rawBuffer), rawBuffer.byteLength);
  56. const wrapper = new dracoDecoder.WebIDLWrapper();
  57. /*
  58. * Determine what type is this file: mesh or point cloud.
  59. */
  60. const geometryType = wrapper.GetEncodedGeometryType(buffer);
  61. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  62. if (this.verbosity > 0) {
  63. console.log('Loaded a mesh.');
  64. }
  65. } else if (geometryType == dracoDecoder.POINT_CLOUD) {
  66. if (this.verbosity > 0) {
  67. console.log('Loaded a point cloud.');
  68. }
  69. } else {
  70. const errorMsg = 'THREE.DRACOLoader: Unknown geometry type.'
  71. console.error(errorMsg);
  72. throw new Error(errorMsg);
  73. }
  74. callback(this.convertDracoGeometryTo3JS(dracoDecoder, wrapper,
  75. geometryType, buffer));
  76. },
  77. convertDracoGeometryTo3JS: function(dracoDecoder, wrapper, geometryType,
  78. buffer) {
  79. let dracoGeometry;
  80. const start_time = performance.now();
  81. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  82. dracoGeometry = wrapper.DecodeMeshFromBuffer(buffer);
  83. } else {
  84. dracoGeometry = wrapper.DecodePointCloudFromBuffer(buffer);
  85. }
  86. const decode_end = performance.now();
  87. dracoDecoder.destroy(buffer);
  88. /*
  89. * Example on how to retrieve mesh and attributes.
  90. */
  91. let numFaces, numPoints;
  92. let numVertexCoordinates, numTextureCoordinates, numAttributes;
  93. // For output basic geometry information.
  94. let geometryInfoStr;
  95. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  96. numFaces = dracoGeometry.num_faces();
  97. if (this.verbosity > 0) {
  98. console.log('Number of faces loaded: ' + numFaces.toString());
  99. }
  100. } else {
  101. numFaces = 0;
  102. }
  103. numPoints = dracoGeometry.num_points();
  104. numVertexCoordinates = numPoints * 3;
  105. numTextureCoordinates = numPoints * 2;
  106. numAttributes = dracoGeometry.num_attributes();
  107. if (this.verbosity > 0) {
  108. console.log('Number of points loaded: ' + numPoints.toString());
  109. console.log('Number of attributes loaded: ' +
  110. numAttributes.toString());
  111. }
  112. // Get position attribute. Must exists.
  113. const posAttId = wrapper.GetAttributeId(dracoGeometry,
  114. dracoDecoder.POSITION);
  115. if (posAttId == -1) {
  116. const errorMsg = 'THREE.DRACOLoader: No position attribute found.';
  117. console.error(errorMsg);
  118. dracoDecoder.destroy(wrapper);
  119. dracoDecoder.destroy(dracoGeometry);
  120. throw new Error(errorMsg);
  121. }
  122. const posAttribute = wrapper.GetAttribute(dracoGeometry, posAttId);
  123. const posAttributeData = new dracoDecoder.DracoFloat32Array();
  124. wrapper.GetAttributeFloatForAllPoints(
  125. dracoGeometry, posAttribute, posAttributeData);
  126. // Get color attributes if exists.
  127. const colorAttId = wrapper.GetAttributeId(dracoGeometry,
  128. dracoDecoder.COLOR);
  129. let colAttributeData;
  130. if (colorAttId != -1) {
  131. if (this.verbosity > 0) {
  132. console.log('Loaded color attribute.');
  133. }
  134. const colAttribute = wrapper.GetAttribute(dracoGeometry, colorAttId);
  135. colAttributeData = new dracoDecoder.DracoFloat32Array();
  136. wrapper.GetAttributeFloatForAllPoints(dracoGeometry, colAttribute,
  137. colAttributeData);
  138. }
  139. // Get normal attributes if exists.
  140. const normalAttId =
  141. wrapper.GetAttributeId(dracoGeometry, dracoDecoder.NORMAL);
  142. let norAttributeData;
  143. if (normalAttId != -1) {
  144. if (this.verbosity > 0) {
  145. console.log('Loaded normal attribute.');
  146. }
  147. const norAttribute = wrapper.GetAttribute(dracoGeometry, normalAttId);
  148. norAttributeData = new dracoDecoder.DracoFloat32Array();
  149. wrapper.GetAttributeFloatForAllPoints(dracoGeometry, norAttribute,
  150. norAttributeData);
  151. }
  152. // Get texture coord attributes if exists.
  153. const texCoordAttId =
  154. wrapper.GetAttributeId(dracoGeometry, dracoDecoder.TEX_COORD);
  155. let textCoordAttributeData;
  156. if (texCoordAttId != -1) {
  157. if (this.verbosity > 0) {
  158. console.log('Loaded texture coordinate attribute.');
  159. }
  160. const texCoordAttribute = wrapper.GetAttribute(dracoGeometry,
  161. texCoordAttId);
  162. textCoordAttributeData = new dracoDecoder.DracoFloat32Array();
  163. wrapper.GetAttributeFloatForAllPoints(dracoGeometry,
  164. texCoordAttribute,
  165. textCoordAttributeData);
  166. }
  167. // Structure for converting to THREEJS geometry later.
  168. const numIndices = numFaces * 3;
  169. const geometryBuffer = {
  170. indices: new Uint32Array(numIndices),
  171. vertices: new Float32Array(numVertexCoordinates),
  172. normals: new Float32Array(numVertexCoordinates),
  173. uvs: new Float32Array(numTextureCoordinates),
  174. colors: new Float32Array(numVertexCoordinates)
  175. };
  176. for (let i = 0; i < numVertexCoordinates; i += 3) {
  177. geometryBuffer.vertices[i] = posAttributeData.GetValue(i);
  178. geometryBuffer.vertices[i + 1] = posAttributeData.GetValue(i + 1);
  179. geometryBuffer.vertices[i + 2] = posAttributeData.GetValue(i + 2);
  180. // Add color.
  181. // ThreeJS vertex colors need to be normalized to properly display
  182. if (colorAttId != -1) {
  183. geometryBuffer.colors[i] = colAttributeData.GetValue(i) / 255;
  184. geometryBuffer.colors[i + 1] =
  185. colAttributeData.GetValue(i + 1) / 255;
  186. geometryBuffer.colors[i + 2] =
  187. colAttributeData.GetValue(i + 2) / 255;
  188. } else {
  189. // Default is white. This is faster than TypedArray.fill().
  190. geometryBuffer.colors[i] = 1.0;
  191. geometryBuffer.colors[i + 1] = 1.0;
  192. geometryBuffer.colors[i + 2] = 1.0;
  193. }
  194. // Add normal.
  195. if (normalAttId != -1) {
  196. geometryBuffer.normals[i] = norAttributeData.GetValue(i);
  197. geometryBuffer.normals[i + 1] = norAttributeData.GetValue(i + 1);
  198. geometryBuffer.normals[i + 2] = norAttributeData.GetValue(i + 2);
  199. }
  200. }
  201. // Add texture coordinates.
  202. if (texCoordAttId != -1) {
  203. for (let i = 0; i < numTextureCoordinates; i += 2) {
  204. geometryBuffer.uvs[i] = textCoordAttributeData.GetValue(i);
  205. geometryBuffer.uvs[i + 1] = textCoordAttributeData.GetValue(i + 1);
  206. }
  207. }
  208. dracoDecoder.destroy(posAttributeData);
  209. if (colorAttId != -1)
  210. dracoDecoder.destroy(colAttributeData);
  211. if (normalAttId != -1)
  212. dracoDecoder.destroy(norAttributeData);
  213. if (texCoordAttId != -1)
  214. dracoDecoder.destroy(textCoordAttributeData);
  215. // For mesh, we need to generate the faces.
  216. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  217. const ia = new dracoDecoder.DracoInt32Array();
  218. for (let i = 0; i < numFaces; ++i) {
  219. wrapper.GetFaceFromMesh(dracoGeometry, i, ia);
  220. const index = i * 3;
  221. geometryBuffer.indices[index] = ia.GetValue(0);
  222. geometryBuffer.indices[index + 1] = ia.GetValue(1);
  223. geometryBuffer.indices[index + 2] = ia.GetValue(2);
  224. }
  225. dracoDecoder.destroy(ia);
  226. }
  227. dracoDecoder.destroy(wrapper);
  228. dracoDecoder.destroy(dracoGeometry);
  229. // Import data to Three JS geometry.
  230. const geometry = new THREE.BufferGeometry();
  231. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  232. geometry.setIndex(new(geometryBuffer.indices.length > 65535 ?
  233. THREE.Uint32BufferAttribute : THREE.Uint16BufferAttribute)
  234. (geometryBuffer.indices, 1));
  235. }
  236. geometry.addAttribute('position',
  237. new THREE.Float32BufferAttribute(geometryBuffer.vertices, 3));
  238. geometry.addAttribute('color',
  239. new THREE.Float32BufferAttribute(geometryBuffer.colors, 3));
  240. if (normalAttId != -1) {
  241. geometry.addAttribute('normal',
  242. new THREE.Float32BufferAttribute(geometryBuffer.normals, 3));
  243. }
  244. if (texCoordAttId != -1) {
  245. geometry.addAttribute('uv',
  246. new THREE.Float32BufferAttribute(geometryBuffer.uvs, 2));
  247. }
  248. this.decode_time = decode_end - start_time;
  249. this.import_time = performance.now() - decode_end;
  250. if (this.verbosity > 0) {
  251. console.log('Decode time: ' + this.decode_time);
  252. console.log('Import time: ' + this.import_time);
  253. }
  254. return geometry;
  255. },
  256. isVersionSupported: function(version, callback) {
  257. return THREE.DRACOLoader.getDecoder(this.dracoDecoderType,
  258. function(decoder) { return decoder.isVersionSupported(version); });
  259. }
  260. };
  261. /**
  262. * Creates and returns a singleton instance of the DracoModule decoder.
  263. * The module loading is done asynchronously for WebAssembly. Initialized module
  264. * can be accessed through the callback function |onDracoModuleLoadedCallback|.
  265. */
  266. THREE.DRACOLoader.getDecoder = (function() {
  267. let decoder;
  268. return function(dracoDecoderType, onDracoModuleLoadedCallback) {
  269. if (typeof DracoModule === 'undefined') {
  270. throw new Error('THREE.DRACOLoader: DracoModule not found.');
  271. }
  272. if (typeof decoder !== 'undefined') {
  273. // Module already initialized.
  274. if (typeof onDracoModuleLoadedCallback !== 'undefined') {
  275. onDracoModuleLoadedCallback(decoder);
  276. }
  277. } else {
  278. dracoDecoderType['onModuleLoaded'] = function(module) {
  279. if (typeof onDracoModuleLoadedCallback === 'function') {
  280. decoder = module;
  281. onDracoModuleLoadedCallback(module);
  282. }
  283. };
  284. DracoModule(dracoDecoderType);
  285. }
  286. };
  287. })();