OBJMTLLoader.js 12 KB

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