OBJLoader.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. THREE.OBJLoader = function ( manager ) {
  5. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6. this.materials = null;
  7. this.regexp = {
  8. // v float float float
  9. vertex_pattern : /^v\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
  10. // vn float float float
  11. normal_pattern : /^vn\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
  12. // vt float float
  13. uv_pattern : /^vt\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
  14. // f vertex vertex vertex
  15. face_vertex : /^f\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)(?:\s+(-?\d+))?/,
  16. // f vertex/uv vertex/uv vertex/uv
  17. face_vertex_uv : /^f\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+))?/,
  18. // f vertex/uv/normal vertex/uv/normal vertex/uv/normal
  19. face_vertex_uv_normal : /^f\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+)\/(-?\d+))?/,
  20. // f vertex//normal vertex//normal vertex//normal
  21. face_vertex_normal : /^f\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)(?:\s+(-?\d+)\/\/(-?\d+))?/,
  22. // o object_name | g group_name
  23. object_pattern : /^[og]\s*(.+)?/,
  24. // s boolean
  25. smoothing_pattern : /^s\s+(\d+|on|off)/,
  26. // mtllib file_reference
  27. material_library_pattern : /^mtllib /,
  28. // usemtl material_name
  29. material_use_pattern : /^usemtl /
  30. };
  31. };
  32. THREE.OBJLoader.prototype = {
  33. constructor: THREE.OBJLoader,
  34. load: function ( url, onLoad, onProgress, onError ) {
  35. var scope = this;
  36. var loader = new THREE.XHRLoader( scope.manager );
  37. loader.setPath( this.path );
  38. loader.load( url, function ( text ) {
  39. onLoad( scope.parse( text ) );
  40. }, onProgress, onError );
  41. },
  42. setPath: function ( value ) {
  43. this.path = value;
  44. },
  45. setMaterials: function ( materials ) {
  46. this.materials = materials;
  47. },
  48. _createParserState : function () {
  49. var state = {
  50. objects : [],
  51. object : {},
  52. vertices : [],
  53. normals : [],
  54. uvs : [],
  55. materialLibraries : [],
  56. startObject: function ( name, fromDeclaration ) {
  57. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  58. // file. We need to use it for the first parsed g/o to keep things in sync.
  59. if ( this.object && this.object.fromDeclaration === false ) {
  60. this.object.name = name;
  61. this.object.fromDeclaration = ( fromDeclaration !== false );
  62. return;
  63. }
  64. this.object = {
  65. name : name || '',
  66. geometry : {
  67. vertices : [],
  68. normals : [],
  69. uvs : []
  70. },
  71. material : {
  72. name : '',
  73. smooth : true
  74. },
  75. fromDeclaration : ( fromDeclaration !== false )
  76. };
  77. this.objects.push( this.object );
  78. },
  79. parseVertexIndex: function ( value, len ) {
  80. var index = parseInt( value, 10 );
  81. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  82. },
  83. parseNormalIndex: function ( value, len ) {
  84. var index = parseInt( value, 10 );
  85. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  86. },
  87. parseUVIndex: function ( value, len ) {
  88. var index = parseInt( value, 10 );
  89. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  90. },
  91. addVertex: function ( a, b, c ) {
  92. var src = this.vertices;
  93. var dst = this.object.geometry.vertices;
  94. dst.push( src[ a + 0 ] );
  95. dst.push( src[ a + 1 ] );
  96. dst.push( src[ a + 2 ] );
  97. dst.push( src[ b + 0 ] );
  98. dst.push( src[ b + 1 ] );
  99. dst.push( src[ b + 2 ] );
  100. dst.push( src[ c + 0 ] );
  101. dst.push( src[ c + 1 ] );
  102. dst.push( src[ c + 2 ] );
  103. },
  104. addVertexLine: function ( a ) {
  105. var src = this.vertices;
  106. var dst = this.object.geometry.vertices;
  107. dst.push( src[ a + 0 ] );
  108. dst.push( src[ a + 1 ] );
  109. dst.push( src[ a + 2 ] );
  110. },
  111. addNormal : function ( a, b, c ) {
  112. var src = this.normals;
  113. var dst = this.object.geometry.normals;
  114. dst.push( src[ a + 0 ] );
  115. dst.push( src[ a + 1 ] );
  116. dst.push( src[ a + 2 ] );
  117. dst.push( src[ b + 0 ] );
  118. dst.push( src[ b + 1 ] );
  119. dst.push( src[ b + 2 ] );
  120. dst.push( src[ c + 0 ] );
  121. dst.push( src[ c + 1 ] );
  122. dst.push( src[ c + 2 ] );
  123. },
  124. addUV: function ( a, b, c ) {
  125. var src = this.uvs;
  126. var dst = this.object.geometry.uvs;
  127. dst.push( src[ a + 0 ] );
  128. dst.push( src[ a + 1 ] );
  129. dst.push( src[ b + 0 ] );
  130. dst.push( src[ b + 1 ] );
  131. dst.push( src[ c + 0 ] );
  132. dst.push( src[ c + 1 ] );
  133. },
  134. addUVLine: function ( a ) {
  135. var src = this.uvs;
  136. var dst = this.object.geometry.uvs;
  137. dst.push( src[ a + 0 ] );
  138. dst.push( src[ a + 1 ] );
  139. },
  140. addFace: function ( a, b, c, d, ua, ub, uc, ud, na, nb, nc, nd ) {
  141. var vLen = this.vertices.length;
  142. var ia = this.parseVertexIndex( a, vLen );
  143. var ib = this.parseVertexIndex( b, vLen );
  144. var ic = this.parseVertexIndex( c, vLen );
  145. var id;
  146. if ( d === undefined ) {
  147. this.addVertex( ia, ib, ic );
  148. } else {
  149. id = this.parseVertexIndex( d, vLen );
  150. this.addVertex( ia, ib, id );
  151. this.addVertex( ib, ic, id );
  152. }
  153. if ( ua !== undefined ) {
  154. var uvLen = this.uvs.length;
  155. ia = this.parseUVIndex( ua, uvLen );
  156. ib = this.parseUVIndex( ub, uvLen );
  157. ic = this.parseUVIndex( uc, uvLen );
  158. if ( d === undefined ) {
  159. this.addUV( ia, ib, ic );
  160. } else {
  161. id = this.parseUVIndex( ud, uvLen );
  162. this.addUV( ia, ib, id );
  163. this.addUV( ib, ic, id );
  164. }
  165. }
  166. if ( na !== undefined ) {
  167. // Normals are many times the same. If so, skip function call and parseInt.
  168. var nLen = this.normals.length;
  169. ia = this.parseNormalIndex( na, nLen );
  170. ib = na === nb ? ia : this.parseNormalIndex( nb, nLen );
  171. ic = na === nc ? ia : this.parseNormalIndex( nc, nLen );
  172. if ( d === undefined ) {
  173. this.addNormal( ia, ib, ic );
  174. } else {
  175. id = this.parseNormalIndex( nd, nLen );
  176. this.addNormal( ia, ib, id );
  177. this.addNormal( ib, ic, id );
  178. }
  179. }
  180. },
  181. addLineGeometry: function ( vertices, uvs ) {
  182. this.object.geometry.type = 'Line';
  183. var vLen = this.vertices.length;
  184. var uvLen = this.uvs.length;
  185. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  186. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  187. }
  188. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  189. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  190. }
  191. }
  192. };
  193. state.startObject( '', false );
  194. return state;
  195. },
  196. parse: function ( text ) {
  197. console.time( 'OBJLoader' );
  198. var state = this._createParserState();
  199. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  200. // This is faster than String.split with regex that splits on both
  201. text = text.replace( '\r\n', '\n' );
  202. }
  203. var lines = text.split( '\n' );
  204. var line = '', lineFirstChar = '', lineSecondChar = '';
  205. var lineLength = 0;
  206. var result = [];
  207. // Faster to just trim left side of the line. Use if available.
  208. var trimLeft = ( typeof ''.trimLeft === 'function' );
  209. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  210. line = lines[ i ];
  211. line = trimLeft ? line.trimLeft() : line.trim();
  212. lineLength = line.length;
  213. if ( lineLength === 0 ) continue;
  214. lineFirstChar = line.charAt( 0 );
  215. // @todo invoke passed in handler if any
  216. if ( lineFirstChar === '#' ) continue;
  217. if ( lineFirstChar === 'v' ) {
  218. lineSecondChar = line.charAt( 1 );
  219. if ( lineSecondChar === ' ' && ( result = this.regexp.vertex_pattern.exec( line ) ) !== null ) {
  220. // 0 1 2 3
  221. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  222. state.vertices.push(
  223. parseFloat( result[ 1 ] ),
  224. parseFloat( result[ 2 ] ),
  225. parseFloat( result[ 3 ] )
  226. );
  227. } else if ( lineSecondChar === 'n' && ( result = this.regexp.normal_pattern.exec( line ) ) !== null ) {
  228. // 0 1 2 3
  229. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  230. state.normals.push(
  231. parseFloat( result[ 1 ] ),
  232. parseFloat( result[ 2 ] ),
  233. parseFloat( result[ 3 ] )
  234. );
  235. } else if ( lineSecondChar === 't' && ( result = this.regexp.uv_pattern.exec( line ) ) !== null ) {
  236. // 0 1 2
  237. // ["vt 0.1 0.2", "0.1", "0.2"]
  238. state.uvs.push(
  239. parseFloat( result[ 1 ] ),
  240. parseFloat( result[ 2 ] )
  241. );
  242. } else {
  243. throw new Error( "Unexpected vertex/normal/uv line: '" + line + "'" );
  244. }
  245. } else if ( lineFirstChar === "f" ) {
  246. if ( ( result = this.regexp.face_vertex_uv_normal.exec( line ) ) !== null ) {
  247. // f vertex/uv/normal vertex/uv/normal vertex/uv/normal
  248. // 0 1 2 3 4 5 6 7 8 9 10 11 12
  249. // ["f 1/1/1 2/2/2 3/3/3", "1", "1", "1", "2", "2", "2", "3", "3", "3", undefined, undefined, undefined]
  250. state.addFace(
  251. result[ 1 ], result[ 4 ], result[ 7 ], result[ 10 ],
  252. result[ 2 ], result[ 5 ], result[ 8 ], result[ 11 ],
  253. result[ 3 ], result[ 6 ], result[ 9 ], result[ 12 ]
  254. );
  255. } else if ( ( result = this.regexp.face_vertex_uv.exec( line ) ) !== null ) {
  256. // f vertex/uv vertex/uv vertex/uv
  257. // 0 1 2 3 4 5 6 7 8
  258. // ["f 1/1 2/2 3/3", "1", "1", "2", "2", "3", "3", undefined, undefined]
  259. state.addFace(
  260. result[ 1 ], result[ 3 ], result[ 5 ], result[ 7 ],
  261. result[ 2 ], result[ 4 ], result[ 6 ], result[ 8 ]
  262. );
  263. } else if ( ( result = this.regexp.face_vertex_normal.exec( line ) ) !== null ) {
  264. // f vertex//normal vertex//normal vertex//normal
  265. // 0 1 2 3 4 5 6 7 8
  266. // ["f 1//1 2//2 3//3", "1", "1", "2", "2", "3", "3", undefined, undefined]
  267. state.addFace(
  268. result[ 1 ], result[ 3 ], result[ 5 ], result[ 7 ],
  269. undefined, undefined, undefined, undefined,
  270. result[ 2 ], result[ 4 ], result[ 6 ], result[ 8 ]
  271. );
  272. } else if ( ( result = this.regexp.face_vertex.exec( line ) ) !== null ) {
  273. // f vertex vertex vertex
  274. // 0 1 2 3 4
  275. // ["f 1 2 3", "1", "2", "3", undefined]
  276. state.addFace(
  277. result[ 1 ], result[ 2 ], result[ 3 ], result[ 4 ]
  278. );
  279. } else {
  280. throw new Error( "Unexpected face line: '" + line + "'" );
  281. }
  282. } else if ( lineFirstChar === "l" ) {
  283. var lineParts = line.substring( 1 ).trim().split( " " );
  284. var lineVertices = [], lineUVs = [];
  285. if ( line.indexOf( "/" ) === - 1 ) {
  286. lineVertices = lineParts;
  287. } else {
  288. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  289. var parts = lineParts[ li ].split( "/" );
  290. if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] );
  291. if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] );
  292. }
  293. }
  294. state.addLineGeometry( lineVertices, lineUVs );
  295. } else if ( ( result = this.regexp.object_pattern.exec( line ) ) !== null ) {
  296. // o object_name
  297. // or
  298. // g group_name
  299. var name = result[ 0 ].substr( 1 ).trim();
  300. state.startObject( name );
  301. } else if ( this.regexp.material_use_pattern.test( line ) ) {
  302. // material
  303. state.object.material.name = line.substring( 7 ).trim();
  304. } else if ( this.regexp.material_library_pattern.test( line ) ) {
  305. // mtl file
  306. state.materialLibraries.push( line.substring( 7 ).trim() );
  307. } else if ( ( result = this.regexp.smoothing_pattern.exec( line ) ) !== null ) {
  308. // smooth shading
  309. var value = result[ 1 ].trim().toLowerCase();
  310. state.object.material.smooth = ( value === '1' || value === 'on' );
  311. } else {
  312. // Handle null terminated files without exception
  313. if ( line === '\0' ) continue;
  314. throw new Error( "Unexpected line: '" + line + "'" );
  315. }
  316. }
  317. var container = new THREE.Group();
  318. container.materialLibraries = [].concat( state.materialLibraries );
  319. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  320. var object = state.objects[ i ];
  321. var geometry = object.geometry;
  322. var isLine = ( geometry.type === 'Line' );
  323. // Skip o/g line declarations that did not follow with any faces
  324. if ( geometry.vertices.length === 0 ) continue;
  325. var buffergeometry = new THREE.BufferGeometry();
  326. buffergeometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( geometry.vertices ), 3 ) );
  327. if ( geometry.normals.length > 0 ) {
  328. buffergeometry.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( geometry.normals ), 3 ) );
  329. } else {
  330. buffergeometry.computeVertexNormals();
  331. }
  332. if ( geometry.uvs.length > 0 ) {
  333. buffergeometry.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( geometry.uvs ), 2 ) );
  334. }
  335. var material;
  336. if ( this.materials !== null ) {
  337. material = this.materials.create( object.material.name );
  338. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  339. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  340. var materialLine = new THREE.LineBasicMaterial();
  341. materialLine.copy( material );
  342. material = materialLine;
  343. }
  344. }
  345. if ( ! material ) {
  346. material = ( ! isLine ? new THREE.MeshPhongMaterial() : new THREE.LineBasicMaterial() );
  347. material.name = object.material.name;
  348. }
  349. material.shading = object.material.smooth ? THREE.SmoothShading : THREE.FlatShading;
  350. var mesh = ( ! isLine ? new THREE.Mesh( buffergeometry, material ) : new THREE.Line( buffergeometry, material ) );
  351. mesh.name = object.name;
  352. container.add( mesh );
  353. }
  354. console.timeEnd( 'OBJLoader' );
  355. return container;
  356. }
  357. };