OBJLoader.js 19 KB

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