1
0

XYZLoader.js 1.9 KB

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