OBJLoader.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. THREE.OBJLoader = function () {};
  5. THREE.OBJLoader.prototype.load = function ( url, callback ) {
  6. var xhr = new XMLHttpRequest();
  7. xhr.onreadystatechange = function () {
  8. if ( xhr.readyState == 4 ) {
  9. if ( xhr.status == 200 || xhr.status == 0 ) {
  10. THREE.OBJLoader.prototype.parse( xhr.responseText, callback );
  11. } else {
  12. console.error( 'THREE.OBJLoader: Couldn\'t load ' + url + ' (' + xhr.status + ')' );
  13. }
  14. }
  15. };
  16. xhr.open( "GET", url, true );
  17. xhr.send( null );
  18. };
  19. THREE.OBJLoader.prototype.parse = function ( data, callback ) {
  20. var geometry = new THREE.Geometry();
  21. var pattern, result;
  22. // vertices
  23. pattern = /v ([\-|\d|.]+) ([\-|\d|.]+) ([\-|\d|.]+)/g;
  24. while ( ( result = pattern.exec( data ) ) != null ) {
  25. var vertex = new THREE.Vector3( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ), parseFloat( result[ 3 ] ) );
  26. geometry.vertices.push( vertex );
  27. }
  28. // faces: vertex/uv/normal
  29. pattern = /f ([\d]+)\/([\d]+)\/([\d]+) ([\d]+)\/([\d]+)\/([\d]+) ([\d]+)\/([\d]+)\/([\d]+)/g;
  30. while ( ( result = pattern.exec( data ) ) != null ) {
  31. var face = new THREE.Face3( parseInt( result[ 1 ] ) - 1, parseInt( result[ 4 ] ) - 1, parseInt( result[ 7 ] ) - 1 );
  32. geometry.faces.push( face );
  33. }
  34. // faces: vertex/normal
  35. pattern = /f ([\d]+)\/\/([\d]+) ([\d]+)\/\/([\d]+) ([\d]+)\/\/([\d]+)/g;
  36. while ( ( result = pattern.exec( data ) ) != null ) {
  37. var face = new THREE.Face3( parseInt( result[ 1 ] ) - 1, parseInt( result[ 3 ] ) - 1, parseInt( result[ 5 ] ) - 1 );
  38. geometry.faces.push( face );
  39. }
  40. geometry.computeCentroids();
  41. callback( geometry );
  42. }