OBJLoader.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. THREE.OBJLoader = ( function () {
  5. // o object_name | g group_name
  6. var object_pattern = /^[og]\s*(.+)?/;
  7. // mtllib file_reference
  8. var material_library_pattern = /^mtllib /;
  9. // usemtl material_name
  10. var material_use_pattern = /^usemtl /;
  11. function ParserState() {
  12. var state = {
  13. objects : [],
  14. object : {},
  15. vertices : [],
  16. normals : [],
  17. uvs : [],
  18. materialLibraries : [],
  19. startObject: function ( name, fromDeclaration ) {
  20. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  21. // file. We need to use it for the first parsed g/o to keep things in sync.
  22. if ( this.object && this.object.fromDeclaration === false ) {
  23. this.object.name = name;
  24. this.object.fromDeclaration = ( fromDeclaration !== false );
  25. return;
  26. }
  27. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  28. if ( this.object && typeof this.object._finalize === 'function' ) {
  29. this.object._finalize( true );
  30. }
  31. this.object = {
  32. name : name || '',
  33. fromDeclaration : ( fromDeclaration !== false ),
  34. geometry : {
  35. vertices : [],
  36. normals : [],
  37. uvs : []
  38. },
  39. materials : [],
  40. smooth : true,
  41. startMaterial: function ( name, libraries ) {
  42. var previous = this._finalize( false );
  43. // New usemtl declaration overwrites an inherited material, except if faces were declared
  44. // after the material, then it must be preserved for proper MultiMaterial continuation.
  45. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  46. this.materials.splice( previous.index, 1 );
  47. }
  48. var material = {
  49. index : this.materials.length,
  50. name : name || '',
  51. mtllib : ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  52. smooth : ( previous !== undefined ? previous.smooth : this.smooth ),
  53. groupStart : ( previous !== undefined ? previous.groupEnd : 0 ),
  54. groupEnd : -1,
  55. groupCount : -1,
  56. inherited : false,
  57. clone: function ( index ) {
  58. var cloned = {
  59. index : ( typeof index === 'number' ? index : this.index ),
  60. name : this.name,
  61. mtllib : this.mtllib,
  62. smooth : this.smooth,
  63. groupStart : 0,
  64. groupEnd : -1,
  65. groupCount : -1,
  66. inherited : false
  67. };
  68. cloned.clone = this.clone.bind(cloned);
  69. return cloned;
  70. }
  71. };
  72. this.materials.push( material );
  73. return material;
  74. },
  75. currentMaterial: function () {
  76. if ( this.materials.length > 0 ) {
  77. return this.materials[ this.materials.length - 1 ];
  78. }
  79. return undefined;
  80. },
  81. _finalize: function ( end ) {
  82. var lastMultiMaterial = this.currentMaterial();
  83. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === -1 ) {
  84. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  85. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  86. lastMultiMaterial.inherited = false;
  87. }
  88. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  89. if ( end && this.materials.length > 1 ) {
  90. for ( var mi = this.materials.length - 1; mi >= 0; mi-- ) {
  91. if ( this.materials[ mi ].groupCount <= 0 ) {
  92. this.materials.splice( mi, 1 );
  93. }
  94. }
  95. }
  96. // Guarantee at least one empty material, this makes the creation later more straight forward.
  97. if ( end && this.materials.length === 0 ) {
  98. this.materials.push({
  99. name : '',
  100. smooth : this.smooth
  101. });
  102. }
  103. return lastMultiMaterial;
  104. }
  105. };
  106. // Inherit previous objects material.
  107. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  108. // If a usemtl declaration is encountered while this new object is being parsed, it will
  109. // overwrite the inherited material. Exception being that there was already face declarations
  110. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  111. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  112. var declared = previousMaterial.clone( 0 );
  113. declared.inherited = true;
  114. this.object.materials.push( declared );
  115. }
  116. this.objects.push( this.object );
  117. },
  118. finalize: function () {
  119. if ( this.object && typeof this.object._finalize === 'function' ) {
  120. this.object._finalize( true );
  121. }
  122. },
  123. parseVertexIndex: function ( value, len ) {
  124. var index = parseInt( value, 10 );
  125. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  126. },
  127. parseNormalIndex: function ( value, len ) {
  128. var index = parseInt( value, 10 );
  129. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  130. },
  131. parseUVIndex: function ( value, len ) {
  132. var index = parseInt( value, 10 );
  133. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  134. },
  135. addVertex: function ( a, b, c ) {
  136. var src = this.vertices;
  137. var dst = this.object.geometry.vertices;
  138. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  139. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  140. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  141. },
  142. addVertexLine: function ( a ) {
  143. var src = this.vertices;
  144. var dst = this.object.geometry.vertices;
  145. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  146. },
  147. addNormal: function ( a, b, c ) {
  148. var src = this.normals;
  149. var dst = this.object.geometry.normals;
  150. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  151. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  152. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  153. },
  154. addUV: function ( a, b, c ) {
  155. var src = this.uvs;
  156. var dst = this.object.geometry.uvs;
  157. dst.push( src[ a + 0 ], src[ a + 1 ] );
  158. dst.push( src[ b + 0 ], src[ b + 1 ] );
  159. dst.push( src[ c + 0 ], src[ c + 1 ] );
  160. },
  161. addUVLine: function ( a ) {
  162. var src = this.uvs;
  163. var dst = this.object.geometry.uvs;
  164. dst.push( src[ a + 0 ], src[ a + 1 ] );
  165. },
  166. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  167. var vLen = this.vertices.length;
  168. var ia = this.parseVertexIndex( a, vLen );
  169. var ib = this.parseVertexIndex( b, vLen );
  170. var ic = this.parseVertexIndex( c, vLen );
  171. this.addVertex( ia, ib, ic );
  172. if ( ua !== undefined ) {
  173. var uvLen = this.uvs.length;
  174. ia = this.parseUVIndex( ua, uvLen );
  175. ib = this.parseUVIndex( ub, uvLen );
  176. ic = this.parseUVIndex( uc, uvLen );
  177. this.addUV( ia, ib, ic );
  178. }
  179. if ( na !== undefined ) {
  180. // Normals are many times the same. If so, skip function call and parseInt.
  181. var nLen = this.normals.length;
  182. ia = this.parseNormalIndex( na, nLen );
  183. ib = na === nb ? ia : this.parseNormalIndex( nb, nLen );
  184. ic = na === nc ? ia : this.parseNormalIndex( nc, nLen );
  185. this.addNormal( ia, ib, ic );
  186. }
  187. },
  188. addLineGeometry: function ( vertices, uvs ) {
  189. this.object.geometry.type = 'Line';
  190. var vLen = this.vertices.length;
  191. var uvLen = this.uvs.length;
  192. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  193. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  194. }
  195. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  196. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  197. }
  198. }
  199. };
  200. state.startObject( '', false );
  201. return state;
  202. }
  203. //
  204. function OBJLoader( manager ) {
  205. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  206. this.materials = null;
  207. };
  208. OBJLoader.prototype = {
  209. constructor: OBJLoader,
  210. load: function ( url, onLoad, onProgress, onError ) {
  211. var scope = this;
  212. var loader = new THREE.FileLoader( scope.manager );
  213. loader.setPath( this.path );
  214. loader.load( url, function ( text ) {
  215. onLoad( scope.parse( text ) );
  216. }, onProgress, onError );
  217. },
  218. setPath: function ( value ) {
  219. this.path = value;
  220. },
  221. setMaterials: function ( materials ) {
  222. this.materials = materials;
  223. return this;
  224. },
  225. parse: function ( text ) {
  226. console.time( 'OBJLoader' );
  227. var state = new ParserState();
  228. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  229. // This is faster than String.split with regex that splits on both
  230. text = text.replace( /\r\n/g, '\n' );
  231. }
  232. if ( text.indexOf( '\\\n' ) !== - 1) {
  233. // join lines separated by a line continuation character (\)
  234. text = text.replace( /\\\n/g, '' );
  235. }
  236. var lines = text.split( '\n' );
  237. var line = '', lineFirstChar = '';
  238. var lineLength = 0;
  239. var result = [];
  240. // Faster to just trim left side of the line. Use if available.
  241. var trimLeft = ( typeof ''.trimLeft === 'function' );
  242. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  243. line = lines[ i ];
  244. line = trimLeft ? line.trimLeft() : line.trim();
  245. lineLength = line.length;
  246. if ( lineLength === 0 ) continue;
  247. lineFirstChar = line.charAt( 0 );
  248. // @todo invoke passed in handler if any
  249. if ( lineFirstChar === '#' ) continue;
  250. if ( lineFirstChar === 'v' ) {
  251. var data = line.split( /\s+/ );
  252. switch ( data[ 0 ] ) {
  253. case 'v':
  254. state.vertices.push(
  255. parseFloat( data[ 1 ] ),
  256. parseFloat( data[ 2 ] ),
  257. parseFloat( data[ 3 ] )
  258. );
  259. break;
  260. case 'vn':
  261. state.normals.push(
  262. parseFloat( data[ 1 ] ),
  263. parseFloat( data[ 2 ] ),
  264. parseFloat( data[ 3 ] )
  265. );
  266. break;
  267. case 'vt':
  268. state.uvs.push(
  269. parseFloat( data[ 1 ] ),
  270. parseFloat( data[ 2 ] )
  271. );
  272. break;
  273. }
  274. } else if ( lineFirstChar === 'f' ) {
  275. var lineData = line.substr( 1 ).trim();
  276. var vertexData = lineData.split( /\s+/ );
  277. var faceVertices = [];
  278. // Parse the face vertex data into an easy to work with format
  279. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  280. var vertex = vertexData[ j ];
  281. if ( vertex.length > 0 ) {
  282. var vertexParts = vertex.split( '/' );
  283. faceVertices.push( vertexParts );
  284. }
  285. }
  286. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  287. var v1 = faceVertices[ 0 ];
  288. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  289. var v2 = faceVertices[ j ];
  290. var v3 = faceVertices[ j + 1 ];
  291. state.addFace(
  292. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  293. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  294. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  295. );
  296. }
  297. } else if ( lineFirstChar === 'l' ) {
  298. var lineParts = line.substring( 1 ).trim().split( " " );
  299. var lineVertices = [], lineUVs = [];
  300. if ( line.indexOf( "/" ) === - 1 ) {
  301. lineVertices = lineParts;
  302. } else {
  303. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  304. var parts = lineParts[ li ].split( "/" );
  305. if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] );
  306. if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] );
  307. }
  308. }
  309. state.addLineGeometry( lineVertices, lineUVs );
  310. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  311. // o object_name
  312. // or
  313. // g group_name
  314. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  315. // var name = result[ 0 ].substr( 1 ).trim();
  316. var name = ( " " + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  317. state.startObject( name );
  318. } else if ( material_use_pattern.test( line ) ) {
  319. // material
  320. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  321. } else if ( material_library_pattern.test( line ) ) {
  322. // mtl file
  323. state.materialLibraries.push( line.substring( 7 ).trim() );
  324. } else if ( lineFirstChar === 's' ) {
  325. result = line.split( ' ' );
  326. // smooth shading
  327. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  328. // but does not define a usemtl for each face set.
  329. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  330. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  331. // where explicit usemtl defines geometry groups.
  332. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  333. /*
  334. * http://paulbourke.net/dataformats/obj/
  335. * or
  336. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  337. *
  338. * From chapter "Grouping" Syntax explanation "s group_number":
  339. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  340. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  341. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  342. * than 0."
  343. */
  344. if ( result.length > 1 ) {
  345. var value = result[ 1 ].trim().toLowerCase();
  346. state.object.smooth = ( value !== '0' && value !== 'off' );
  347. } else {
  348. // ZBrush can produce "s" lines #11707
  349. state.object.smooth = true;
  350. }
  351. var material = state.object.currentMaterial();
  352. if ( material ) material.smooth = state.object.smooth;
  353. } else {
  354. // Handle null terminated files without exception
  355. if ( line === '\0' ) continue;
  356. throw new Error( "Unexpected line: '" + line + "'" );
  357. }
  358. }
  359. state.finalize();
  360. var container = new THREE.Group();
  361. container.materialLibraries = [].concat( state.materialLibraries );
  362. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  363. var object = state.objects[ i ];
  364. var geometry = object.geometry;
  365. var materials = object.materials;
  366. var isLine = ( geometry.type === 'Line' );
  367. // Skip o/g line declarations that did not follow with any faces
  368. if ( geometry.vertices.length === 0 ) continue;
  369. var buffergeometry = new THREE.BufferGeometry();
  370. buffergeometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( geometry.vertices ), 3 ) );
  371. if ( geometry.normals.length > 0 ) {
  372. buffergeometry.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( geometry.normals ), 3 ) );
  373. } else {
  374. buffergeometry.computeVertexNormals();
  375. }
  376. if ( geometry.uvs.length > 0 ) {
  377. buffergeometry.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( geometry.uvs ), 2 ) );
  378. }
  379. // Create materials
  380. var createdMaterials = [];
  381. for ( var mi = 0, miLen = materials.length; mi < miLen ; mi++ ) {
  382. var sourceMaterial = materials[ mi ];
  383. var material = undefined;
  384. if ( this.materials !== null ) {
  385. material = this.materials.create( sourceMaterial.name );
  386. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  387. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  388. var materialLine = new THREE.LineBasicMaterial();
  389. materialLine.copy( material );
  390. material = materialLine;
  391. }
  392. }
  393. if ( ! material ) {
  394. material = ( ! isLine ? new THREE.MeshPhongMaterial() : new THREE.LineBasicMaterial() );
  395. material.name = sourceMaterial.name;
  396. }
  397. material.flatShading = sourceMaterial.smooth ? false : true;
  398. createdMaterials.push(material);
  399. }
  400. // Create mesh
  401. var mesh;
  402. if ( createdMaterials.length > 1 ) {
  403. for ( var mi = 0, miLen = materials.length; mi < miLen ; mi++ ) {
  404. var sourceMaterial = materials[ mi ];
  405. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  406. }
  407. mesh = ( ! isLine ? new THREE.Mesh( buffergeometry, createdMaterials ) : new THREE.LineSegments( buffergeometry, createdMaterials ) );
  408. } else {
  409. mesh = ( ! isLine ? new THREE.Mesh( buffergeometry, createdMaterials[ 0 ] ) : new THREE.LineSegments( buffergeometry, createdMaterials[ 0 ] ) );
  410. }
  411. mesh.name = object.name;
  412. container.add( mesh );
  413. }
  414. console.timeEnd( 'OBJLoader' );
  415. return container;
  416. }
  417. };
  418. return OBJLoader;
  419. } )();