PCDLoader.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. import {
  2. BufferGeometry,
  3. Color,
  4. FileLoader,
  5. Float32BufferAttribute,
  6. Int32BufferAttribute,
  7. Loader,
  8. Points,
  9. PointsMaterial,
  10. SRGBColorSpace
  11. } from 'three';
  12. /**
  13. * A loader for the Point Cloud Data (PCD) format.
  14. *
  15. * PCDLoader supports ASCII and (compressed) binary files as well as the following PCD fields:
  16. * - x y z
  17. * - rgb
  18. * - normal_x normal_y normal_z
  19. * - intensity
  20. * - label
  21. *
  22. * ```js
  23. * const loader = new PCDLoader();
  24. *
  25. * const points = await loader.loadAsync( './models/pcd/binary/Zaghetto.pcd' );
  26. * points.geometry.center(); // optional
  27. * points.geometry.rotateX( Math.PI ); // optional
  28. * scene.add( points );
  29. * ```
  30. *
  31. * @augments Loader
  32. */
  33. class PCDLoader extends Loader {
  34. /**
  35. * Constructs a new PCD loader.
  36. *
  37. * @param {LoadingManager} [manager] - The loading manager.
  38. */
  39. constructor( manager ) {
  40. super( manager );
  41. /**
  42. * Whether to use little Endian or not.
  43. *
  44. * @type {boolean}
  45. * @default true
  46. */
  47. this.littleEndian = true;
  48. }
  49. /**
  50. * Starts loading from the given URL and passes the loaded PCD asset
  51. * to the `onLoad()` callback.
  52. *
  53. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  54. * @param {function(Points)} onLoad - Executed when the loading process has been finished.
  55. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  56. * @param {onErrorCallback} onError - Executed when errors occur.
  57. */
  58. load( url, onLoad, onProgress, onError ) {
  59. const scope = this;
  60. const loader = new FileLoader( scope.manager );
  61. loader.setPath( scope.path );
  62. loader.setResponseType( 'arraybuffer' );
  63. loader.setRequestHeader( scope.requestHeader );
  64. loader.setWithCredentials( scope.withCredentials );
  65. loader.load( url, function ( data ) {
  66. try {
  67. onLoad( scope.parse( data ) );
  68. } catch ( e ) {
  69. if ( onError ) {
  70. onError( e );
  71. } else {
  72. console.error( e );
  73. }
  74. scope.manager.itemError( url );
  75. }
  76. }, onProgress, onError );
  77. }
  78. /**
  79. * Parses the given PCD data and returns a point cloud.
  80. *
  81. * @param {ArrayBuffer} data - The raw PCD data as an array buffer.
  82. * @return {Points} The parsed point cloud.
  83. */
  84. parse( data ) {
  85. // from https://gitlab.com/taketwo/three-pcd-loader/blob/master/decompress-lzf.js
  86. function decompressLZF( inData, outLength ) {
  87. const inLength = inData.length;
  88. const outData = new Uint8Array( outLength );
  89. let inPtr = 0;
  90. let outPtr = 0;
  91. let ctrl;
  92. let len;
  93. let ref;
  94. do {
  95. ctrl = inData[ inPtr ++ ];
  96. if ( ctrl < ( 1 << 5 ) ) {
  97. ctrl ++;
  98. if ( outPtr + ctrl > outLength ) throw new Error( 'Output buffer is not large enough' );
  99. if ( inPtr + ctrl > inLength ) throw new Error( 'Invalid compressed data' );
  100. do {
  101. outData[ outPtr ++ ] = inData[ inPtr ++ ];
  102. } while ( -- ctrl );
  103. } else {
  104. len = ctrl >> 5;
  105. ref = outPtr - ( ( ctrl & 0x1f ) << 8 ) - 1;
  106. if ( inPtr >= inLength ) throw new Error( 'Invalid compressed data' );
  107. if ( len === 7 ) {
  108. len += inData[ inPtr ++ ];
  109. if ( inPtr >= inLength ) throw new Error( 'Invalid compressed data' );
  110. }
  111. ref -= inData[ inPtr ++ ];
  112. if ( outPtr + len + 2 > outLength ) throw new Error( 'Output buffer is not large enough' );
  113. if ( ref < 0 ) throw new Error( 'Invalid compressed data' );
  114. if ( ref >= outPtr ) throw new Error( 'Invalid compressed data' );
  115. do {
  116. outData[ outPtr ++ ] = outData[ ref ++ ];
  117. } while ( -- len + 2 );
  118. }
  119. } while ( inPtr < inLength );
  120. return outData;
  121. }
  122. function parseHeader( data ) {
  123. const PCDheader = {};
  124. const result1 = data.search( /[\r\n]DATA\s(\S*)\s/i );
  125. const result2 = /[\r\n]DATA\s(\S*)\s/i.exec( data.slice( result1 - 1 ) );
  126. PCDheader.data = result2[ 1 ];
  127. PCDheader.headerLen = result2[ 0 ].length + result1;
  128. PCDheader.str = data.slice( 0, PCDheader.headerLen );
  129. // remove comments
  130. PCDheader.str = PCDheader.str.replace( /#.*/gi, '' );
  131. // parse
  132. PCDheader.version = /^VERSION (.*)/im.exec( PCDheader.str );
  133. PCDheader.fields = /^FIELDS (.*)/im.exec( PCDheader.str );
  134. PCDheader.size = /^SIZE (.*)/im.exec( PCDheader.str );
  135. PCDheader.type = /^TYPE (.*)/im.exec( PCDheader.str );
  136. PCDheader.count = /^COUNT (.*)/im.exec( PCDheader.str );
  137. PCDheader.width = /^WIDTH (.*)/im.exec( PCDheader.str );
  138. PCDheader.height = /^HEIGHT (.*)/im.exec( PCDheader.str );
  139. PCDheader.viewpoint = /^VIEWPOINT (.*)/im.exec( PCDheader.str );
  140. PCDheader.points = /^POINTS (.*)/im.exec( PCDheader.str );
  141. // evaluate
  142. if ( PCDheader.version !== null )
  143. PCDheader.version = parseFloat( PCDheader.version[ 1 ] );
  144. PCDheader.fields = ( PCDheader.fields !== null ) ? PCDheader.fields[ 1 ].split( ' ' ) : [];
  145. if ( PCDheader.type !== null )
  146. PCDheader.type = PCDheader.type[ 1 ].split( ' ' );
  147. if ( PCDheader.width !== null )
  148. PCDheader.width = parseInt( PCDheader.width[ 1 ] );
  149. if ( PCDheader.height !== null )
  150. PCDheader.height = parseInt( PCDheader.height[ 1 ] );
  151. if ( PCDheader.viewpoint !== null )
  152. PCDheader.viewpoint = PCDheader.viewpoint[ 1 ];
  153. if ( PCDheader.points !== null )
  154. PCDheader.points = parseInt( PCDheader.points[ 1 ], 10 );
  155. if ( PCDheader.points === null )
  156. PCDheader.points = PCDheader.width * PCDheader.height;
  157. if ( PCDheader.size !== null ) {
  158. PCDheader.size = PCDheader.size[ 1 ].split( ' ' ).map( function ( x ) {
  159. return parseInt( x, 10 );
  160. } );
  161. }
  162. if ( PCDheader.count !== null ) {
  163. PCDheader.count = PCDheader.count[ 1 ].split( ' ' ).map( function ( x ) {
  164. return parseInt( x, 10 );
  165. } );
  166. } else {
  167. PCDheader.count = [];
  168. for ( let i = 0, l = PCDheader.fields.length; i < l; i ++ ) {
  169. PCDheader.count.push( 1 );
  170. }
  171. }
  172. PCDheader.offset = {};
  173. let sizeSum = 0;
  174. for ( let i = 0, l = PCDheader.fields.length; i < l; i ++ ) {
  175. if ( PCDheader.data === 'ascii' ) {
  176. PCDheader.offset[ PCDheader.fields[ i ] ] = i;
  177. } else {
  178. PCDheader.offset[ PCDheader.fields[ i ] ] = sizeSum;
  179. sizeSum += PCDheader.size[ i ] * PCDheader.count[ i ];
  180. }
  181. }
  182. // for binary only
  183. PCDheader.rowSize = sizeSum;
  184. return PCDheader;
  185. }
  186. const textData = new TextDecoder().decode( data );
  187. // parse header (always ascii format)
  188. const PCDheader = parseHeader( textData );
  189. // parse data
  190. const position = [];
  191. const normal = [];
  192. const color = [];
  193. const intensity = [];
  194. const label = [];
  195. const c = new Color();
  196. // ascii
  197. if ( PCDheader.data === 'ascii' ) {
  198. const offset = PCDheader.offset;
  199. const pcdData = textData.slice( PCDheader.headerLen );
  200. const lines = pcdData.split( '\n' );
  201. for ( let i = 0, l = lines.length; i < l; i ++ ) {
  202. if ( lines[ i ] === '' ) continue;
  203. const line = lines[ i ].split( ' ' );
  204. if ( offset.x !== undefined ) {
  205. position.push( parseFloat( line[ offset.x ] ) );
  206. position.push( parseFloat( line[ offset.y ] ) );
  207. position.push( parseFloat( line[ offset.z ] ) );
  208. }
  209. if ( offset.rgb !== undefined ) {
  210. const rgb_field_index = PCDheader.fields.findIndex( ( field ) => field === 'rgb' );
  211. const rgb_type = PCDheader.type[ rgb_field_index ];
  212. const float = parseFloat( line[ offset.rgb ] );
  213. let rgb = float;
  214. if ( rgb_type === 'F' ) {
  215. // treat float values as int
  216. // https://github.com/daavoo/pyntcloud/pull/204/commits/7b4205e64d5ed09abe708b2e91b615690c24d518
  217. const farr = new Float32Array( 1 );
  218. farr[ 0 ] = float;
  219. rgb = new Int32Array( farr.buffer )[ 0 ];
  220. }
  221. const r = ( ( rgb >> 16 ) & 0x0000ff ) / 255;
  222. const g = ( ( rgb >> 8 ) & 0x0000ff ) / 255;
  223. const b = ( ( rgb >> 0 ) & 0x0000ff ) / 255;
  224. c.setRGB( r, g, b, SRGBColorSpace );
  225. color.push( c.r, c.g, c.b );
  226. }
  227. if ( offset.normal_x !== undefined ) {
  228. normal.push( parseFloat( line[ offset.normal_x ] ) );
  229. normal.push( parseFloat( line[ offset.normal_y ] ) );
  230. normal.push( parseFloat( line[ offset.normal_z ] ) );
  231. }
  232. if ( offset.intensity !== undefined ) {
  233. intensity.push( parseFloat( line[ offset.intensity ] ) );
  234. }
  235. if ( offset.label !== undefined ) {
  236. label.push( parseInt( line[ offset.label ] ) );
  237. }
  238. }
  239. }
  240. // binary-compressed
  241. // normally data in PCD files are organized as array of structures: XYZRGBXYZRGB
  242. // binary compressed PCD files organize their data as structure of arrays: XXYYZZRGBRGB
  243. // that requires a totally different parsing approach compared to non-compressed data
  244. if ( PCDheader.data === 'binary_compressed' ) {
  245. const sizes = new Uint32Array( data.slice( PCDheader.headerLen, PCDheader.headerLen + 8 ) );
  246. const compressedSize = sizes[ 0 ];
  247. const decompressedSize = sizes[ 1 ];
  248. const decompressed = decompressLZF( new Uint8Array( data, PCDheader.headerLen + 8, compressedSize ), decompressedSize );
  249. const dataview = new DataView( decompressed.buffer );
  250. const offset = PCDheader.offset;
  251. for ( let i = 0; i < PCDheader.points; i ++ ) {
  252. if ( offset.x !== undefined ) {
  253. const xIndex = PCDheader.fields.indexOf( 'x' );
  254. const yIndex = PCDheader.fields.indexOf( 'y' );
  255. const zIndex = PCDheader.fields.indexOf( 'z' );
  256. position.push( dataview.getFloat32( ( PCDheader.points * offset.x ) + PCDheader.size[ xIndex ] * i, this.littleEndian ) );
  257. position.push( dataview.getFloat32( ( PCDheader.points * offset.y ) + PCDheader.size[ yIndex ] * i, this.littleEndian ) );
  258. position.push( dataview.getFloat32( ( PCDheader.points * offset.z ) + PCDheader.size[ zIndex ] * i, this.littleEndian ) );
  259. }
  260. if ( offset.rgb !== undefined ) {
  261. const rgbIndex = PCDheader.fields.indexOf( 'rgb' );
  262. const r = dataview.getUint8( ( PCDheader.points * offset.rgb ) + PCDheader.size[ rgbIndex ] * i + 2 ) / 255.0;
  263. const g = dataview.getUint8( ( PCDheader.points * offset.rgb ) + PCDheader.size[ rgbIndex ] * i + 1 ) / 255.0;
  264. const b = dataview.getUint8( ( PCDheader.points * offset.rgb ) + PCDheader.size[ rgbIndex ] * i + 0 ) / 255.0;
  265. c.setRGB( r, g, b, SRGBColorSpace );
  266. color.push( c.r, c.g, c.b );
  267. }
  268. if ( offset.normal_x !== undefined ) {
  269. const xIndex = PCDheader.fields.indexOf( 'normal_x' );
  270. const yIndex = PCDheader.fields.indexOf( 'normal_y' );
  271. const zIndex = PCDheader.fields.indexOf( 'normal_z' );
  272. normal.push( dataview.getFloat32( ( PCDheader.points * offset.normal_x ) + PCDheader.size[ xIndex ] * i, this.littleEndian ) );
  273. normal.push( dataview.getFloat32( ( PCDheader.points * offset.normal_y ) + PCDheader.size[ yIndex ] * i, this.littleEndian ) );
  274. normal.push( dataview.getFloat32( ( PCDheader.points * offset.normal_z ) + PCDheader.size[ zIndex ] * i, this.littleEndian ) );
  275. }
  276. if ( offset.intensity !== undefined ) {
  277. const intensityIndex = PCDheader.fields.indexOf( 'intensity' );
  278. intensity.push( dataview.getFloat32( ( PCDheader.points * offset.intensity ) + PCDheader.size[ intensityIndex ] * i, this.littleEndian ) );
  279. }
  280. if ( offset.label !== undefined ) {
  281. const labelIndex = PCDheader.fields.indexOf( 'label' );
  282. label.push( dataview.getInt32( ( PCDheader.points * offset.label ) + PCDheader.size[ labelIndex ] * i, this.littleEndian ) );
  283. }
  284. }
  285. }
  286. // binary
  287. if ( PCDheader.data === 'binary' ) {
  288. const dataview = new DataView( data, PCDheader.headerLen );
  289. const offset = PCDheader.offset;
  290. for ( let i = 0, row = 0; i < PCDheader.points; i ++, row += PCDheader.rowSize ) {
  291. if ( offset.x !== undefined ) {
  292. position.push( dataview.getFloat32( row + offset.x, this.littleEndian ) );
  293. position.push( dataview.getFloat32( row + offset.y, this.littleEndian ) );
  294. position.push( dataview.getFloat32( row + offset.z, this.littleEndian ) );
  295. }
  296. if ( offset.rgb !== undefined ) {
  297. const r = dataview.getUint8( row + offset.rgb + 2 ) / 255.0;
  298. const g = dataview.getUint8( row + offset.rgb + 1 ) / 255.0;
  299. const b = dataview.getUint8( row + offset.rgb + 0 ) / 255.0;
  300. c.setRGB( r, g, b, SRGBColorSpace );
  301. color.push( c.r, c.g, c.b );
  302. }
  303. if ( offset.normal_x !== undefined ) {
  304. normal.push( dataview.getFloat32( row + offset.normal_x, this.littleEndian ) );
  305. normal.push( dataview.getFloat32( row + offset.normal_y, this.littleEndian ) );
  306. normal.push( dataview.getFloat32( row + offset.normal_z, this.littleEndian ) );
  307. }
  308. if ( offset.intensity !== undefined ) {
  309. intensity.push( dataview.getFloat32( row + offset.intensity, this.littleEndian ) );
  310. }
  311. if ( offset.label !== undefined ) {
  312. label.push( dataview.getInt32( row + offset.label, this.littleEndian ) );
  313. }
  314. }
  315. }
  316. // build geometry
  317. const geometry = new BufferGeometry();
  318. if ( position.length > 0 ) geometry.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  319. if ( normal.length > 0 ) geometry.setAttribute( 'normal', new Float32BufferAttribute( normal, 3 ) );
  320. if ( color.length > 0 ) geometry.setAttribute( 'color', new Float32BufferAttribute( color, 3 ) );
  321. if ( intensity.length > 0 ) geometry.setAttribute( 'intensity', new Float32BufferAttribute( intensity, 1 ) );
  322. if ( label.length > 0 ) geometry.setAttribute( 'label', new Int32BufferAttribute( label, 1 ) );
  323. geometry.computeBoundingSphere();
  324. // build material
  325. const material = new PointsMaterial( { size: 0.005 } );
  326. if ( color.length > 0 ) {
  327. material.vertexColors = true;
  328. }
  329. // build point cloud
  330. return new Points( geometry, material );
  331. }
  332. }
  333. export { PCDLoader };
粤ICP备19079148号