XYZLoader.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. } )();