OBJMTLLoader.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. /**
  2. * Loads a Wavefront .obj file with materials
  3. *
  4. * @author mrdoob / http://mrdoob.com/
  5. * @author angelxuanchang
  6. */
  7. THREE.OBJMTLLoader = function ( ) {
  8. THREE.EventTarget.call( this );
  9. };
  10. THREE.OBJMTLLoader.prototype = {
  11. constructor: THREE.OBJMTLLoader,
  12. /**
  13. * Load a Wavefront OBJ file with materials (MTL file)
  14. *
  15. * Loading progress is indicated by the following events:
  16. * "load" event (successful loading): type = 'load', content = THREE.Object3D
  17. * "error" event (error loading): type = 'load', message
  18. * "progress" event (progress loading): type = 'progress', loaded, total
  19. *
  20. * If the MTL file cannot be loaded, then a MeshLambertMaterial is used as a default
  21. * @param url - Location of OBJ file to load
  22. * @param mtlfileurl - MTL file to load (optional, if not specified, attempts to use MTL specified in OBJ file)
  23. * @param options - Options on how to interpret the material (see THREE.MTLLoader.MaterialCreator )
  24. *
  25. */
  26. load: function ( url, mtlfileurl, options ) {
  27. var scope = this;
  28. var xhr = new XMLHttpRequest();
  29. var mtlDone; // Is the MTL done (true if no MTL, error loading MTL, or MTL actually loaded)
  30. var obj3d; // Loaded model (from obj file)
  31. var materialsCreator; // Material creator is created when MTL file is loaded
  32. // Loader for MTL
  33. var mtlLoader = new THREE.MTLLoader( url.substr( 0, url.lastIndexOf( "/" ) + 1 ), options );
  34. mtlLoader.addEventListener( 'load', waitReady );
  35. mtlLoader.addEventListener( 'error', waitReady );
  36. // Try to load mtlfile
  37. if ( mtlfileurl ) {
  38. mtlLoader.load( mtlfileurl );
  39. mtlDone = false;
  40. } else {
  41. mtlDone = true;
  42. }
  43. function waitReady( event ) {
  44. if ( event.type === 'load' ) {
  45. if ( event.content instanceof THREE.MTLLoader.MaterialCreator ) {
  46. // MTL file is loaded
  47. mtlDone = true;
  48. materialsCreator = event.content;
  49. materialsCreator.preload();
  50. } else {
  51. // OBJ file is loaded
  52. if ( event.target.status === 200 || event.target.status === 0 ) {
  53. var objContent = event.target.responseText;
  54. if ( mtlfileurl ) {
  55. // Parse with passed in MTL file
  56. obj3d = scope.parse( objContent );
  57. } else {
  58. // No passed in MTL file, look for mtlfile in obj file
  59. obj3d = scope.parse( objContent, function( mtlfile ) {
  60. mtlDone = false;
  61. mtlLoader.load( mtlLoader.baseUrl + mtlfile );
  62. } );
  63. }
  64. } else {
  65. // Error loading OBJ file....
  66. scope.dispatchEvent( {
  67. type: 'error',
  68. message: 'Couldn\'t load URL [' + url + ']',
  69. response: event.target.responseText } );
  70. }
  71. }
  72. } else if ( event.type === 'error' ) {
  73. // MTL failed to load -- oh well, we will just not have material ...
  74. mtlDone = true;
  75. }
  76. if ( mtlDone && obj3d ) {
  77. // MTL file is loaded and OBJ file is loaded
  78. // Apply materials to model
  79. if ( materialsCreator ) {
  80. THREE.SceneUtils.traverseHierarchy( obj3d, function( node ) {
  81. if ( node instanceof THREE.Mesh ) {
  82. if ( node.material.name ) {
  83. var material = materialsCreator.create( node.material.name );
  84. if (material ) node.material = material;
  85. }
  86. }
  87. } );
  88. }
  89. // Notify listeners
  90. scope.dispatchEvent( { type: 'load', content: obj3d } );
  91. }
  92. }
  93. xhr.addEventListener( 'load', waitReady, false );
  94. xhr.addEventListener( 'progress', function ( event ) {
  95. scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } );
  96. }, false );
  97. xhr.addEventListener( 'error', function () {
  98. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  99. }, false );
  100. xhr.open( 'GET', url, true );
  101. xhr.send( null );
  102. },
  103. /**
  104. * Parses loaded .obj file
  105. * @param data - content of .obj file
  106. * @param mtllibCallback - callback to handle mtllib declaration (optional)
  107. * @return {THREE.Object3D} - Object3D (with default material)
  108. */
  109. parse: function ( data, mtllibCallback ) {
  110. function vector( x, y, z ) {
  111. return new THREE.Vector3( x, y, z );
  112. }
  113. function uv( u, v ) {
  114. return new THREE.UV( u, v );
  115. }
  116. function face3( a, b, c, normals ) {
  117. return new THREE.Face3( a, b, c, normals );
  118. }
  119. function face4( a, b, c, d, normals ) {
  120. return new THREE.Face4( a, b, c, d, normals );
  121. }
  122. function finalize_mesh( group, mesh_info ) {
  123. mesh_info.geometry.computeCentroids();
  124. mesh_info.geometry.computeFaceNormals();
  125. mesh_info.geometry.computeBoundingSphere();
  126. group.add( new THREE.Mesh( mesh_info.geometry, mesh_info.material ) );
  127. }
  128. var vertices = [];
  129. var normals = [];
  130. var uvs = [];
  131. // v float float float
  132. var vertex_pattern = /v( +[\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)/;
  133. // vn float float float
  134. var normal_pattern = /vn( +[\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)/;
  135. // vt float float
  136. var uv_pattern = /vt( +[\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)/;
  137. // f vertex vertex vertex ...
  138. var face_pattern1 = /f( +[\d]+)( [\d]+)( [\d]+)( [\d]+)?/;
  139. // f vertex/uv vertex/uv vertex/uv ...
  140. var face_pattern2 = /f( +([\d]+)\/([\d]+))( ([\d]+)\/([\d]+))( ([\d]+)\/([\d]+))( ([\d]+)\/([\d]+))?/;
  141. // f vertex/uv/normal vertex/uv/normal vertex/uv/normal ...
  142. var face_pattern3 = /f( +([\d]+)\/([\d]+)\/([\d]+))( ([\d]+)\/([\d]+)\/([\d]+))( ([\d]+)\/([\d]+)\/([\d]+))( ([\d]+)\/([\d]+)\/([\d]+))?/;
  143. // f vertex//normal vertex//normal vertex//normal ...
  144. var face_pattern4 = /f( +([\d]+)\/\/([\d]+))( ([\d]+)\/\/([\d]+))( ([\d]+)\/\/([\d]+))( ([\d]+)\/\/([\d]+))?/;
  145. var final_model = new THREE.Object3D();
  146. var geometry = new THREE.Geometry();
  147. geometry.vertices = vertices;
  148. var cur_mesh = {
  149. material: new THREE.MeshLambertMaterial(),
  150. geometry: geometry
  151. };
  152. var lines = data.split( "\n" );
  153. for ( var i = 0; i < lines.length; i ++ ) {
  154. var line = lines[ i ];
  155. line = line.trim();
  156. // temporary variable storing pattern matching result
  157. var result;
  158. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  159. continue;
  160. } else if ( ( result = vertex_pattern.exec( line ) ) !== null ) {
  161. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  162. vertices.push( vector(
  163. parseFloat( result[ 1 ] ),
  164. parseFloat( result[ 2 ] ),
  165. parseFloat( result[ 3 ] )
  166. ) );
  167. } else if ( ( result = normal_pattern.exec( line ) ) !== null ) {
  168. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  169. normals.push( vector(
  170. parseFloat( result[ 1 ] ),
  171. parseFloat( result[ 2 ] ),
  172. parseFloat( result[ 3 ] )
  173. ) );
  174. } else if ( ( result = uv_pattern.exec( line ) ) !== null ) {
  175. // ["vt 0.1 0.2", "0.1", "0.2"]
  176. uvs.push( uv(
  177. parseFloat( result[ 1 ] ),
  178. parseFloat( result[ 2 ] )
  179. ) );
  180. } else if ( ( result = face_pattern1.exec( line ) ) !== null ) {
  181. // ["f 1 2 3", "1", "2", "3", undefined]
  182. if ( result[ 4 ] === undefined ) {
  183. geometry.faces.push( face3(
  184. parseInt( result[ 1 ] ) - 1,
  185. parseInt( result[ 2 ] ) - 1,
  186. parseInt( result[ 3 ] ) - 1
  187. ) );
  188. } else {
  189. geometry.faces.push( face4(
  190. parseInt( result[ 1 ] ) - 1,
  191. parseInt( result[ 2 ] ) - 1,
  192. parseInt( result[ 3 ] ) - 1,
  193. parseInt( result[ 4 ] ) - 1
  194. ) );
  195. }
  196. } else if ( ( result = face_pattern2.exec( line ) ) !== null ) {
  197. // ["f 1/1 2/2 3/3", " 1/1", "1", "1", " 2/2", "2", "2", " 3/3", "3", "3", undefined, undefined, undefined]
  198. if ( result[ 10 ] === undefined ) {
  199. geometry.faces.push( face3(
  200. parseInt( result[ 2 ] ) - 1,
  201. parseInt( result[ 5 ] ) - 1,
  202. parseInt( result[ 8 ] ) - 1
  203. ) );
  204. geometry.faceVertexUvs[ 0 ].push( [
  205. uvs[ parseInt( result[ 3 ] ) - 1 ],
  206. uvs[ parseInt( result[ 6 ] ) - 1 ],
  207. uvs[ parseInt( result[ 9 ] ) - 1 ]
  208. ] );
  209. } else {
  210. geometry.faces.push( face4(
  211. parseInt( result[ 2 ] ) - 1,
  212. parseInt( result[ 5 ] ) - 1,
  213. parseInt( result[ 8 ] ) - 1,
  214. parseInt( result[ 11 ] ) - 1
  215. ) );
  216. geometry.faceVertexUvs[ 0 ].push( [
  217. uvs[ parseInt( result[ 3 ] ) - 1 ],
  218. uvs[ parseInt( result[ 6 ] ) - 1 ],
  219. uvs[ parseInt( result[ 9 ] ) - 1 ],
  220. uvs[ parseInt( result[ 12 ] ) - 1 ]
  221. ] );
  222. }
  223. } else if ( ( result = face_pattern3.exec( line ) ) !== null ) {
  224. // ["f 1/1/1 2/2/2 3/3/3", " 1/1/1", "1", "1", "1", " 2/2/2", "2", "2", "2", " 3/3/3", "3", "3", "3", undefined, undefined, undefined, undefined]
  225. if ( result[ 13 ] === undefined ) {
  226. geometry.faces.push( face3(
  227. parseInt( result[ 2 ] ) - 1,
  228. parseInt( result[ 6 ] ) - 1,
  229. parseInt( result[ 10 ] ) - 1,
  230. [
  231. normals[ parseInt( result[ 4 ] ) - 1 ],
  232. normals[ parseInt( result[ 8 ] ) - 1 ],
  233. normals[ parseInt( result[ 12 ] ) - 1 ]
  234. ]
  235. ) );
  236. geometry.faceVertexUvs[ 0 ].push( [
  237. uvs[ parseInt( result[ 3 ] ) - 1 ],
  238. uvs[ parseInt( result[ 7 ] ) - 1 ],
  239. uvs[ parseInt( result[ 11 ] ) - 1 ]
  240. ] );
  241. } else {
  242. geometry.faces.push( face4(
  243. parseInt( result[ 2 ] ) - 1,
  244. parseInt( result[ 6 ] ) - 1,
  245. parseInt( result[ 10 ] ) - 1,
  246. parseInt( result[ 14 ] ) - 1,
  247. [
  248. normals[ parseInt( result[ 4 ] ) - 1 ],
  249. normals[ parseInt( result[ 8 ] ) - 1 ],
  250. normals[ parseInt( result[ 12 ] ) - 1 ],
  251. normals[ parseInt( result[ 16 ] ) - 1 ]
  252. ]
  253. ) );
  254. geometry.faceVertexUvs[ 0 ].push( [
  255. uvs[ parseInt( result[ 3 ] ) - 1 ],
  256. uvs[ parseInt( result[ 7 ] ) - 1 ],
  257. uvs[ parseInt( result[ 11 ] ) - 1 ],
  258. uvs[ parseInt( result[ 15 ] ) - 1 ]
  259. ] );
  260. }
  261. } else if ( ( result = face_pattern4.exec( line ) ) !== null ) {
  262. // ["f 1//1 2//2 3//3", " 1//1", "1", "1", " 2//2", "2", "2", " 3//3", "3", "3", undefined, undefined, undefined]
  263. if ( result[ 10 ] === undefined ) {
  264. geometry.faces.push( face3(
  265. parseInt( result[ 2 ] ) - 1,
  266. parseInt( result[ 5 ] ) - 1,
  267. parseInt( result[ 8 ] ) - 1,
  268. [
  269. normals[ parseInt( result[ 3 ] ) - 1 ],
  270. normals[ parseInt( result[ 6 ] ) - 1 ],
  271. normals[ parseInt( result[ 9 ] ) - 1 ]
  272. ]
  273. ) );
  274. } else {
  275. geometry.faces.push( face4(
  276. parseInt( result[ 2 ] ) - 1,
  277. parseInt( result[ 5 ] ) - 1,
  278. parseInt( result[ 8 ] ) - 1,
  279. parseInt( result[ 11 ] ) - 1,
  280. [
  281. normals[ parseInt( result[ 3 ] ) - 1 ],
  282. normals[ parseInt( result[ 6 ] ) - 1 ],
  283. normals[ parseInt( result[ 9 ] ) - 1 ],
  284. normals[ parseInt( result[ 12 ] ) - 1 ]
  285. ]
  286. ) );
  287. }
  288. } else if ( line.startsWith( "usemtl " ) ) {
  289. var material_name = line.substring( 7 );
  290. material_name = material_name.trim();
  291. var material = new THREE.MeshLambertMaterial();
  292. material.name = material_name;
  293. if ( geometry.faces.length > 0 ) {
  294. // Finalize previous geometry and add to model
  295. finalize_mesh( final_model, cur_mesh );
  296. geometry = new THREE.Geometry();
  297. geometry.vertices = vertices;
  298. cur_mesh = { geometry: geometry };
  299. }
  300. cur_mesh.material = material;
  301. //material_index = materialsCreator.getIndex( material_name );
  302. } else if ( line.startsWith( "g " ) ) {
  303. // Polygon group for object
  304. var group_name = line.substring( 2 );
  305. group_name = group_name.trim();
  306. } else if ( line.startsWith( "o " ) ) {
  307. // Object
  308. var object_name = line.substring(2);
  309. //object_name = $.trim(object_name);
  310. } else if (line.startsWith("s ")) {
  311. // Smooth shading
  312. } else if (line.startsWith("mtllib ")) {
  313. // mtl file
  314. if (mtllibCallback) {
  315. var mtlfile = line.substring(7);
  316. mtlfile = $.trim(mtlfile);
  317. mtllibCallback(mtlfile);
  318. }
  319. } else {
  320. console.error("Unhandled line " + line);
  321. }
  322. }
  323. finalize_mesh(final_model, cur_mesh);
  324. return final_model;
  325. }
  326. };