XYZLoader.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. ( function () {
  2. class XYZLoader extends THREE.Loader {
  3. load( url, onLoad, onProgress, onError ) {
  4. const scope = this;
  5. const loader = new THREE.FileLoader( this.manager );
  6. loader.setPath( this.path );
  7. loader.setRequestHeader( this.requestHeader );
  8. loader.setWithCredentials( this.withCredentials );
  9. loader.load( url, function ( text ) {
  10. try {
  11. onLoad( scope.parse( text ) );
  12. } catch ( e ) {
  13. if ( onError ) {
  14. onError( e );
  15. } else {
  16. console.error( e );
  17. }
  18. scope.manager.itemError( url );
  19. }
  20. }, onProgress, onError );
  21. }
  22. parse( text ) {
  23. const lines = text.split( '\n' );
  24. const vertices = [];
  25. const colors = [];
  26. for ( let line of lines ) {
  27. line = line.trim();
  28. if ( line.charAt( 0 ) === '#' ) continue; // skip comments
  29. const lineValues = line.split( /\s+/ );
  30. if ( lineValues.length === 3 ) {
  31. // XYZ
  32. vertices.push( parseFloat( lineValues[ 0 ] ) );
  33. vertices.push( parseFloat( lineValues[ 1 ] ) );
  34. vertices.push( parseFloat( lineValues[ 2 ] ) );
  35. }
  36. if ( lineValues.length === 6 ) {
  37. // XYZRGB
  38. vertices.push( parseFloat( lineValues[ 0 ] ) );
  39. vertices.push( parseFloat( lineValues[ 1 ] ) );
  40. vertices.push( parseFloat( lineValues[ 2 ] ) );
  41. colors.push( parseFloat( lineValues[ 3 ] ) / 255 );
  42. colors.push( parseFloat( lineValues[ 4 ] ) / 255 );
  43. colors.push( parseFloat( lineValues[ 5 ] ) / 255 );
  44. }
  45. }
  46. const geometry = new THREE.BufferGeometry();
  47. geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  48. if ( colors.length > 0 ) {
  49. geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( colors, 3 ) );
  50. }
  51. return geometry;
  52. }
  53. }
  54. THREE.XYZLoader = XYZLoader;
  55. } )();