-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLidarPreprocessor.cpp
More file actions
1999 lines (1786 loc) · 59.4 KB
/
Copy pathLidarPreprocessor.cpp
File metadata and controls
1999 lines (1786 loc) · 59.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***********************************************************************
New version of LiDAR data preprocessor.
Copyright (c) 2005-2025 Oliver Kreylos
This file is part of the LiDAR processing and analysis package.
The LiDAR processing and analysis package is free software; you can
redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
The LiDAR processing and analysis package is distributed in the hope
that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with the LiDAR processing and analysis package; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
***********************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <Misc/SizedTypes.h>
#include <Misc/StdError.h>
#include <Misc/Endianness.h>
#include <Misc/FileNameExtensions.h>
#include <Misc/Timer.h>
#include <Misc/StandardValueCoders.h>
#include <Misc/ConfigurationFile.h>
#include <IO/File.h>
#include <IO/SeekableFile.h>
#include <IO/OpenFile.h>
#include <IO/ReadAheadFilter.h>
#include <IO/ValueSource.h>
#include <IO/OpenFile.h>
#include <IO/ZipArchive.h>
#include <IO/XMLDocument.h>
#include <Math/Math.h>
#include <Math/Constants.h>
#include <Geometry/OrthogonalTransformation.h>
#include <Geometry/GeometryValueCoders.h>
#include <Images/BaseImage.h>
#include <Images/ImageReaderBIL.h>
#include <Images/GeoTIFFMetadata.h>
#include <Images/TIFFReader.h>
#include "Config.h"
#include "LidarTypes.h"
#include "PointAccumulator.h"
#include "ReadPlyFile.h"
#include "LidarProcessOctree.h"
#include "LidarOctreeCreator.h"
class TIFFDEMLoader // Helper class to convert DEMs in TIFF format into a point cloud
{
/* Elements: */
private:
Images::TIFFReader tiffReader; // TIFF image file reader object
Images::GeoTIFFMetadata mapData; // Map transformation defined in the TIFF image file
PointAccumulator& pa; // Accumulator for 3D points
PointAccumulator::Color color; // Color to assign to all points
/* Private methods: */
static void streamingCallback(uint32_t x,uint32_t y,uint32_t width,uint16_t channel,const uint8_t* pixels,void* userData) // Callback receiving pixel or channel data from the TIFF file
{
TIFFDEMLoader* thisPtr=static_cast<TIFFDEMLoader*>(userData);
Images::GeoTIFFMetadata& md=thisPtr->mapData;
/* Convert all elevation postings into 3D points and add them to the point accumulator: */
const float* pPtr=reinterpret_cast<const float*>(pixels);
PointAccumulator::Point p;
p[0]=double(x)*md.dim[0]+md.map[0];
p[1]=double(y)*md.dim[1]+md.map[1];
while(width>0)
{
/* Convert and add the current pixel: */
p[2]=double(*pPtr);
if(p[2]!=md.noData)
thisPtr->pa.addPoint(p,thisPtr->color);
/* Go to the next pixel: */
p[0]+=md.dim[0];
--width;
++pPtr;
}
}
/* Constructors and destructors: */
public:
TIFFDEMLoader(PointAccumulator& sPa,const char* fileName,unsigned int imageIndex)
:tiffReader(*IO::openFile(fileName),imageIndex),
pa(sPa),color(1.0,1.0,1.0)
{
/* Check if the TIFF image has a compatible format: */
if(tiffReader.getNumSamples()!=1||tiffReader.getNumBits()!=32||!tiffReader.hasFloatSamples())
throw Misc::makeStdErr(__PRETTY_FUNCTION__,"Image %u in TIFF file %s does not define a DEM",imageIndex,fileName);
std::cout<<"Reading "<<tiffReader.getWidth()<<" x "<<tiffReader.getHeight()<<" DEM pixels"<<std::endl;
/* Read the TIFF image's map transformation, if it defines one: */
tiffReader.readMetadata(mapData);
/* OK, the input file doesn't have GeoTIFF tags: */
mapData.haveMap=true;
mapData.map[0]=8127993.99279;
mapData.map[1]=-244781.57519;
mapData.haveDim=true;
mapData.dim[0]=1.0;
mapData.dim[1]=-1.0;
mapData.haveNoData=true;
mapData.noData=-32767.0;
/* Flip the map data: */
mapData.map[1]=mapData.map[1]+mapData.dim[1]*double(tiffReader.getHeight()-1);
mapData.dim[1]=-mapData.dim[1];
if(mapData.haveMap)
std::cout<<"Map position of upper-left DEM pixel: "<<mapData.map[0]<<", "<<mapData.map[1]<<std::endl;
if(mapData.haveDim)
std::cout<<"Map dimensions of DEM pixels: "<<mapData.dim[0]<<" x "<<mapData.dim[1]<<std::endl;
}
/* Methods: */
void collectPoints(void) // Collects all 3D points defined by the DEM into the point accumulator
{
/* Stream the image's pixels into the streaming callback, which in turn adds them to the point accumulator: */
tiffReader.streamImage(&TIFFDEMLoader::streamingCallback,this);
}
};
inline bool startsNumber(int c)
{
return (c>='0'&&c<='9')||c=='+'||c=='-'||c=='.';
}
std::string readNumber(IO::ValueSource& header)
{
/* Read the number as a string: */
std::string result=header.readString();
/* Skip a potential unit name: */
if(header.peekc()=='<')
{
while(header.getChar()!='>')
;
header.skipWs();
}
return result;
}
std::string readList(IO::ValueSource& header,bool root)
{
std::string result;
/* Read the opening parenthesis: */
result.push_back(header.readChar());
if(root)
header.setWhitespace('\n',true);
/* Read list elements until the closing parenthesis: */
while(header.peekc()!=')')
{
/* Check the type of the next element: */
if(header.peekc()=='(')
result.append(readList(header,false));
else if(header.peekc()=='"')
{
result.push_back('"');
result.append(header.readString());
result.push_back('"');
}
else if(startsNumber(header.peekc()))
result.append(readNumber(header));
else
result.append(header.readString());
/* Check for the item separator: */
if(header.peekc()!=')')
{
if(!header.isLiteral(','))
throw std::runtime_error("Missing comma separator in list value");
result.push_back(',');
}
}
if(root)
header.setWhitespace('\n',false);
/* Read the closing parenthesis: */
result.push_back(header.readChar());
return result;
}
void loadXYZBILImage(PointAccumulator& pa,const char* fileName)
{
/* Open the image file: */
IO::SeekableFilePtr file=IO::openSeekableFile(fileName);
/* Read the embedded file header as plain text: */
size_t recordSize=0;
size_t imageOffset=0;
bool inImageObject=false;
Images::ImageReaderBIL::FileLayout fileLayout;
fileLayout.size=Images::Size(0,0);
fileLayout.numBands=3;
fileLayout.numBits=32;
fileLayout.pixelSigned=true;
fileLayout.byteOrder=Misc::BigEndian;
fileLayout.bandLayout=Images::ImageReaderBIL::FileLayout::BSQ;
fileLayout.skipBytes=0;
fileLayout.bandRowBytes=0;
fileLayout.totalRowBytes=0;
fileLayout.bandGapBytes=0;
{
IO::ValueSource header(file);
header.setPunctuation("=,()<>\n");
header.setQuote('"',true);
header.skipWs();
/* Check if the file is an ODL3 data product: */
if(!header.isLiteral("ODL_VERSION_ID")||!header.isLiteral('=')||!header.isLiteral("ODL3")||!header.isLiteral('\n'))
throw Misc::makeStdErr(__PRETTY_FUNCTION__,"File %s is not an ODL3 data product",fileName);
/* Read the header line-by-line: */
while(true)
{
/* Check for comment lines: */
if(header.peekc()!='\n'&&(header.peekc()!='/'||header.getChar()!='/'||header.peekc()!='*'))
{
/* Read the line tag: */
std::string tag=header.readString();
if(tag=="END")
{
/* Done with the header: */
break;
}
/* Check for the equal sign: */
if(!header.isLiteral('='))
throw Misc::makeStdErr(__PRETTY_FUNCTION__,"File %s has a malformed ODL3 header",fileName);
/* Read the line value: */
std::string value;
if(header.peekc()=='(')
value=readList(header,true);
else if(header.peekc()=='"')
{
header.setQuotedString('\n',true);
value.push_back('"');
value.append(header.readString());
value.push_back('"');
header.setQuotedString('\n',false);
}
else if(startsNumber(header.peekc()))
value=readNumber(header);
else
value=header.readString();
/* Parse relevant tags: */
if(inImageObject)
{
if(tag=="INTERCHANGE_FORMAT")
{
if(value!="BINARY")
throw Misc::makeStdErr(__PRETTY_FUNCTION__,"Unsupported interchange format %s in file %s",value.c_str(),fileName);
}
else if(tag=="LINES")
fileLayout.size[1]=Misc::ValueCoder<unsigned int>::decode(value.data(),value.data()+value.length());
else if(tag=="LINE_SAMPLES")
fileLayout.size[0]=Misc::ValueCoder<unsigned int>::decode(value.data(),value.data()+value.length());
else if(tag=="SAMPLE_TYPE")
{
if(value!="IEEE_REAL")
throw Misc::makeStdErr(__PRETTY_FUNCTION__,"Unsupported sample type %s in file %s",value.c_str(),fileName);
}
else if(tag=="SAMPLE_BITS")
{
fileLayout.numBits=Misc::ValueCoder<unsigned int>::decode(value.data(),value.data()+value.length());
if(fileLayout.numBits!=32)
throw Misc::makeStdErr(__PRETTY_FUNCTION__,"Unsupported sample size %u in file %s",(unsigned int)(fileLayout.numBits),fileName);
}
else if(tag=="BANDS")
{
fileLayout.numBands=Misc::ValueCoder<unsigned int>::decode(value.data(),value.data()+value.length());
if(fileLayout.numBands!=3)
throw Misc::makeStdErr(__PRETTY_FUNCTION__,"Unsupported number of bands %u in file %s",(unsigned int)(fileLayout.numBands),fileName);
}
else if(tag=="BAND_STORAGE_TYPE")
{
if(value!="BAND_SEQUENTIAL")
throw Misc::makeStdErr(__PRETTY_FUNCTION__,"Unsupported band storage type %s in file %s",value.c_str(),fileName);
}
else if(tag=="END_OBJECT")
inImageObject=value!="IMAGE";
}
else
{
if(tag=="RECORD_TYPE")
{
if(value!="FIXED_LENGTH")
throw Misc::makeStdErr(__PRETTY_FUNCTION__,"Unsupported record type %s in file %s",value.c_str(),fileName);
}
else if(tag=="RECORD_BYTES")
recordSize=Misc::ValueCoder<unsigned int>::decode(value.data(),value.data()+value.length());
else if(tag=="^IMAGE")
imageOffset=Misc::ValueCoder<unsigned int>::decode(value.data(),value.data()+value.length())-1;
else if(tag=="OBJECT")
inImageObject=value=="IMAGE";
}
}
/* Skip the rest of the line: */
header.skipLine();
header.skipWs();
}
}
/* Seek the file to the beginning of the image data: */
file->setReadPosAbs(recordSize*imageOffset);
/* Read the image: */
Images::BaseImage xyzImage=Images::ImageReaderBIL(fileLayout,*file).readImage();
/* Check that the image has three floating-point bands: */
if(xyzImage.getNumChannels()!=3||xyzImage.getChannelSize()!=sizeof(float)||xyzImage.getScalarType()!=GL_FLOAT)
throw Misc::makeStdErr(__PRETTY_FUNCTION__,"File %s is not an XYZ image file",fileName);
/* Add all non-zero image pixels to the point accumulator: */
const float* pPtr=static_cast<const float*>(xyzImage.getPixels());
for(size_t numPixels=xyzImage.getHeight()*xyzImage.getWidth();numPixels>0;--numPixels,pPtr+=3)
if(pPtr[0]!=0.0f||pPtr[1]!=0.0f||pPtr[2]!=0.0f)
pa.addPoint(PointAccumulator::Point(-pPtr[0],pPtr[1],-pPtr[2]),PointAccumulator::Color(1,1,1)); // X and Z coordinates must be negated!
}
void loadPointFileBin(PointAccumulator& pa,const char* fileName)
{
/* Open the binary input file: */
IO::FilePtr file(new IO::ReadAheadFilter(IO::openFile(fileName)));
file->setEndianness(Misc::LittleEndian);
/* Read the number of points in the file: */
size_t numPoints=file->read<unsigned int>();
/* Read all points: */
for(size_t i=0;i<numPoints;++i)
{
/* Read the point position and intensity from the input file: */
float rp[4];
file->read(rp,4);
/* Store the point: */
pa.addPoint(PointAccumulator::Point(rp),PointAccumulator::Color(rp[3],rp[3],rp[3]));
}
}
void loadPointFileBinRgb(PointAccumulator& pa,const char* fileName)
{
/* Open the binary input file: */
IO::FilePtr file(new IO::ReadAheadFilter(IO::openFile(fileName)));
file->setEndianness(Misc::LittleEndian);
/* Read the number of points in the file: */
size_t numPoints=file->read<unsigned int>();
/* Read all points: */
for(size_t i=0;i<numPoints;++i)
{
/* Read the point position and color from the input file: */
float rp[3];
file->read(rp,3);
Color::Scalar rcol[4];
file->read(rcol,4);
/* Store the point: */
pa.addPoint(PointAccumulator::Point(rp),PointAccumulator::Color(rcol));
}
}
void loadPointFileLas(PointAccumulator& pa,const char* fileName,unsigned int classMask)
{
/* Open the LAS input file: */
IO::FilePtr file(new IO::ReadAheadFilter(IO::openFile(fileName)));
file->setEndianness(Misc::LittleEndian);
/* Read the LAS file header: */
char signature[4];
file->read(signature,4);
if(memcmp(signature,"LASF",4)!=0)
return;
file->skip<unsigned short>(1); // Ignore file source ID
file->skip<unsigned short>(1); // Ignore reserved field
file->skip<unsigned int>(1); // Ignore project ID
file->skip<unsigned short>(1); // Ignore project ID
file->skip<unsigned short>(1); // Ignore project ID
file->skip<char>(8); // Ignore project ID
file->skip<char>(2); // Ignore file version number
file->skip<char>(32); // Ignore system identifier
file->skip<char>(32); // Ignore generating software
file->skip<unsigned short>(1); // Ignore file creation day of year
file->skip<unsigned short>(1); // Ignore file creation year
file->skip<unsigned short>(1); // Ignore header size
unsigned int pointDataOffset=file->read<unsigned int>();
file->skip<unsigned int>(1); // Ignore number of variable-length records
unsigned char pointDataFormat=file->read<unsigned char>();
unsigned short pointDataRecordLength=file->read<unsigned short>();
size_t numPointRecords=file->read<unsigned int>();
unsigned int numPointsByReturn[5];
file->read(numPointsByReturn,5);
double scale[3];
file->read(scale,3);
PointAccumulator::Vector offset;
file->read(offset.getComponents(),3);
double min[3],max[3];
for(int i=0;i<3;++i)
{
max[i]=file->read<double>();
min[i]=file->read<double>();
}
/* Check the point record format for sanity: */
static const unsigned short expectedPointDataRecordLengths[]=
{
20,28,26,34,57,63
};
if(pointDataFormat<6U&&pointDataRecordLength<expectedPointDataRecordLengths[pointDataFormat])
{
std::cout<<"Ignoring LAS file "<<fileName<<" with point data format "<<int(pointDataFormat)<<" due to wrong point record length ("<<pointDataRecordLength<<" instead of "<<expectedPointDataRecordLengths[pointDataFormat]<<")"<<std::endl;
return;
}
else if(pointDataFormat>=6U)
{
std::cout<<"Ignoring LAS file "<<fileName<<" due to unknown point data format "<<int(pointDataFormat)<<std::endl;
return;
}
/* Arrays of point data record features by point data format: */
static const bool haveTimes[]=
{
false,true,false,true,true,true
};
static const bool haveRgb[]=
{
false,false,true,true,false,false
};
size_t skipToClass=sizeof(char);
size_t skipToColor=2*sizeof(unsigned char)+sizeof(unsigned short);
if(haveTimes[pointDataFormat])
skipToColor+=sizeof(double);
size_t skipToEnd=pointDataRecordLength-expectedPointDataRecordLengths[pointDataFormat];
/* Skip to the beginning of the point records: */
if(pointDataOffset<227)
{
std::cout<<"Ignoring LAS file "<<fileName<<" due to short file header ("<<pointDataOffset<<" bytes)"<<std::endl;
return;
}
file->skip<unsigned char>(pointDataOffset-227);
/* Apply the LAS offset to the point accumulator's point offset: */
PointAccumulator::Vector originalPointOffset=pa.getPointOffset();
pa.setPointOffset(originalPointOffset+offset);
/* Read all points: */
for(size_t i=0;i<numPointRecords;++i)
{
/* Read the point position: */
int pos[3];
file->read(pos,3);
PointAccumulator::Point p;
for(int j=0;j<3;++j)
p[j]=double(pos[j])*scale[j];
/* Read the point intensity: */
float intensity=float(file->read<unsigned short>());
/* Skip to the point classification: */
file->skip<char>(skipToClass);
/* Read the point classification: */
unsigned int classBit=0x1U<<(file->read<unsigned char>()&0x1fU);
/* Skip to the (optional) point color: */
file->skip<char>(skipToColor);
PointAccumulator::Color c;
if(haveRgb[pointDataFormat])
{
/* Assign point color from stored RGB data: */
unsigned short rgb[3];
file->read(rgb,3);
for(int j=0;j<3;++j)
c[j]=float(rgb[j]);
}
else
{
/* Assign point color from intensity: */
for(int j=0;j<3;++j)
c[j]=float(intensity);
}
/* Skip any extra data at the end of the point record: */
file->skip<char>(skipToEnd);
if(classMask&classBit)
{
/* Store the point: */
pa.addPoint(p,c);
}
}
/* Reset the point accumulator's point offset: */
pa.setPointOffset(originalPointOffset);
}
void loadPointFileXyzi(PointAccumulator& pa,const char* fileName)
{
/* Open the ASCII input file: */
IO::ValueSource reader(new IO::ReadAheadFilter(IO::openFile(fileName)));
reader.setPunctuation('#',true);
reader.setPunctuation('\n',true);
reader.skipWs();
/* Read all lines from the input file: */
size_t lineNumber=1;
while(!reader.eof())
{
/* Check for comment or empty lines: */
if(reader.peekc()!='#'&&reader.peekc()!='\n')
{
try
{
/* Parse the point coordinates and intensity from the line: */
PointAccumulator::Point p;
for(int i=0;i<3;++i)
p[i]=reader.readNumber();
float intensity=float(reader.readNumber());
PointAccumulator::Color c(intensity,intensity,intensity);
/* Store the point: */
pa.addPoint(p,c);
}
catch(const IO::ValueSource::NumberError& err)
{
std::cerr<<"loadPointFileXyzi: Point parsing error in line "<<lineNumber<<std::endl;
}
}
/* Skip the rest of the line: */
reader.skipLine();
++lineNumber;
reader.skipWs();
}
}
void loadPointFileXyzrgb(PointAccumulator& pa,const char* fileName)
{
/* Open the ASCII input file: */
IO::ValueSource reader(new IO::ReadAheadFilter(IO::openFile(fileName)));
reader.setPunctuation('#',true);
reader.setPunctuation('\n',true);
reader.skipWs();
/* Read all lines from the input file: */
size_t lineNumber=1;
while(!reader.eof())
{
/* Check for comment or empty lines: */
if(reader.peekc()!='#'&&reader.peekc()!='\n')
{
try
{
/* Parse the point coordinates and color from the line: */
PointAccumulator::Point p;
for(int i=0;i<3;++i)
p[i]=reader.readNumber();
PointAccumulator::Color c;
for(int i=0;i<3;++i)
c[i]=float(reader.readNumber());
/* Store the point: */
pa.addPoint(p,c);
}
catch(const IO::ValueSource::NumberError& err)
{
std::cerr<<"loadPointFileXyzrgb: Point parsing error in line "<<lineNumber<<std::endl;
}
}
/* Skip the rest of the line: */
reader.skipLine();
++lineNumber;
reader.skipWs();
}
}
void loadPointFileGenericASCII(PointAccumulator& pa,const char* fileName,int numHeaderLines,bool strictCsv,bool rgb,const int columnIndices[6])
{
/* Create the mapping from column indices to point components: */
int maxColumnIndex=columnIndices[0];
for(int i=1;i<6;++i)
if(maxColumnIndex<columnIndices[i])
maxColumnIndex=columnIndices[i];
int* componentColumnIndices=new int[maxColumnIndex+1];
for(int i=0;i<=maxColumnIndex;++i)
componentColumnIndices[i]=-1;
int numComponents=0;
for(int i=0;i<6;++i)
if(columnIndices[i]>=0)
{
componentColumnIndices[columnIndices[i]]=i;
++numComponents;
}
/* Create color components if they are not given: */
if(rgb)
{
if(numComponents<6)
numComponents=6;
}
else
{
if(numComponents<4)
numComponents=4;
}
double* componentValues=new double[numComponents];
/* Initialize the color components: */
for(int i=3;i<numComponents;++i)
componentValues[i]=255.0;
/* Open the ASCII input file: */
IO::ValueSource reader(new IO::ReadAheadFilter(IO::openFile(fileName)));
if(strictCsv)
reader.setWhitespace("");
reader.setPunctuation("#,\n");
reader.skipWs();
size_t lineNumber=1;
/* Skip the header lines: */
for(int i=0;i<numHeaderLines;++i)
{
reader.skipLine();
reader.skipWs();
++lineNumber;
}
/* Read all lines from the input file: */
try
{
while(!reader.eof())
{
/* Check for comments or empty lines: */
if(reader.peekc()!='#'&&reader.peekc()!='\n')
{
/* Read all columns: */
for(int columnIndex=0;columnIndex<=maxColumnIndex;++columnIndex)
{
if(componentColumnIndices[columnIndex]>=0)
{
/* Read the next value: */
componentValues[componentColumnIndices[columnIndex]]=reader.readNumber();
}
else
reader.skipString();
if(columnIndex<maxColumnIndex)
{
/* Check for separator: */
if(reader.peekc()==',')
reader.skipString();
}
}
/* Store the point position: */
PointAccumulator::Point p(componentValues);
PointAccumulator::Color c;
if(rgb)
{
/* Modify the read RGB color according to the color mask: */
for(int i=0;i<3;++i)
c[i]=componentValues[3+i];
}
else
{
/* Convert the read intensity to an RGB color according to the color mask: */
for(int i=0;i<3;++i)
c[i]=componentValues[3];
}
/* Store the point: */
pa.addPoint(p,c);
}
/* Skip to the next line: */
reader.skipLine();
reader.skipWs();
++lineNumber;
}
}
catch(const std::runtime_error& err)
{
std::cerr<<"Caught exception "<<err.what()<<" in line "<<lineNumber<<" in input file "<<fileName<<std::endl;
}
/* Clean up: */
delete[] componentColumnIndices;
delete[] componentValues;
}
void loadPointFileBlockedASCII(PointAccumulator& pa,const char* fileName,int numHeaderLines,bool rgb,const int columnIndices[6])
{
/* Create the mapping from column indices to point components: */
int maxColumnIndex=columnIndices[0];
for(int i=1;i<6;++i)
if(maxColumnIndex<columnIndices[i])
maxColumnIndex=columnIndices[i];
int* componentColumnIndices=new int[maxColumnIndex+1];
for(int i=0;i<=maxColumnIndex;++i)
componentColumnIndices[i]=-1;
int numComponents=0;
for(int i=0;i<6;++i)
if(columnIndices[i]>=0)
{
componentColumnIndices[columnIndices[i]]=i;
++numComponents;
}
double* componentValues=new double[numComponents];
/* Open the ASCII input file: */
IO::ValueSource reader(new IO::ReadAheadFilter(IO::openFile(fileName)));
reader.setPunctuation("#,\n");
reader.skipWs();
size_t lineNumber=1;
/* Skip the header lines: */
for(int i=0;i<numHeaderLines;++i)
{
reader.skipLine();
reader.skipWs();
++lineNumber;
}
/* Read all lines from the input file: */
try
{
while(!reader.eof())
{
/* Read the number of points in the next block: */
int numPoints=reader.readInteger();
reader.skipLine();
reader.skipWs();
++lineNumber;
/* Read all points in the block: */
for(int blockIndex=0;blockIndex<numPoints;++blockIndex)
{
/* Read all columns: */
for(int columnIndex=0;columnIndex<=maxColumnIndex;++columnIndex)
{
if(componentColumnIndices[columnIndex]>=0)
{
/* Read the next value: */
componentValues[componentColumnIndices[columnIndex]]=reader.readNumber();
}
else
reader.skipString();
if(columnIndex<maxColumnIndex)
{
/* Check for separator: */
if(reader.peekc()==',')
reader.skipString();
}
}
/* Store the point position: */
PointAccumulator::Point p(componentValues);
/* Store the point color: */
PointAccumulator::Color c;
if(rgb)
{
/* Modify the read RGB color according to the color mask: */
for(int i=0;i<3;++i)
c[i]=float(componentValues[3+i]);
}
else
{
/* Convert the read intensity to an RGB color according to the color mask: */
for(int i=0;i<3;++i)
c[i]=float(componentValues[3]);
}
/* Store the point: */
pa.addPoint(p,c);
/* Skip to the next line: */
reader.skipLine();
reader.skipWs();
++lineNumber;
}
}
}
catch(const std::runtime_error& err)
{
std::cerr<<"Caught exception "<<err.what()<<" in line "<<lineNumber<<" in input file "<<fileName<<std::endl;
}
/* Clean up: */
delete[] componentColumnIndices;
delete[] componentValues;
}
/**********************************
Helper structure to load IDL files:
**********************************/
struct IDLFileRecord // Structure describing a record in an IDL file
{
/* Elements: */
public:
unsigned int galID[2]; // Galaxy ID (64-bit integer)
unsigned int haloID[2]; // Halo ID (64-bit integer)
unsigned int recordType; // 0=central, 1=sat, 2=orphan
float position[3];
float velocity[3];
float spin[3];
float ra;
float dec;
float z_obs;
float z;
float centralMVir;
float mVir;
float rVir;
float vVir;
float vMax;
float velDisp;
float stellarMass;
float bulgeMass;
float coldGas;
float hotGas;
float ejectedMass;
float blackHoleMass;
float sfr;
float cooling;
float heating;
float appMagSdss[5];
float appMagSdssBulge[5];
float absMagSdss[5];
float appMagDeep[4];
float appMagDeepBulge[4];
float absMagBvrik[5];
float absMagBvrikBulge[5];
float absMagBvrikNoDust[5];
};
namespace Misc {
template <>
class EndiannessSwapper<IDLFileRecord>
{
/* Methods: */
public:
static void swap(IDLFileRecord& value)
{
swapEndianness(value.galID,2);
swapEndianness(value.haloID,2);
swapEndianness(value.recordType);
swapEndianness(value.position,3);
swapEndianness(value.velocity,3);
swapEndianness(value.spin,3);
swapEndianness(value.ra);
swapEndianness(value.dec);
swapEndianness(value.z_obs);
swapEndianness(value.z);
swapEndianness(value.centralMVir);
swapEndianness(value.mVir);
swapEndianness(value.rVir);
swapEndianness(value.vVir);
swapEndianness(value.vMax);
swapEndianness(value.velDisp);
swapEndianness(value.stellarMass);
swapEndianness(value.bulgeMass);
swapEndianness(value.coldGas);
swapEndianness(value.hotGas);
swapEndianness(value.ejectedMass);
swapEndianness(value.blackHoleMass);
swapEndianness(value.sfr);
swapEndianness(value.cooling);
swapEndianness(value.heating);
swapEndianness(value.appMagSdss,5);
swapEndianness(value.appMagSdssBulge,5);
swapEndianness(value.absMagSdss,5);
swapEndianness(value.appMagDeep,4);
swapEndianness(value.appMagDeepBulge,4);
swapEndianness(value.absMagBvrik,5);
swapEndianness(value.absMagBvrikBulge,5);
swapEndianness(value.absMagBvrikNoDust,5);
}
};
}
double angdiadistscaled(double z)
{
double h0=71.0;
double oM=0.3;
double oL=0.7;
double oR=1.0-(oM+oL);
double sum1=0.0;
double dz=z/100.0;
double id=1.0;
for(int i=0;i<100;++i,id+=dz)
{
double ez=Math::sqrt((oM*id+oR)*id*id+oL);
sum1+=dz/ez;
}
double dh=3.0e5/h0;
double dc=dh*sum1;
if(oR==0.0)
return dh*sum1;
else
{
double sqrtOR=Math::sqrt(Math::abs(oR));
return dh*(1.0/sqrtOR)*sinh(sqrtOR*(sum1));
}
}
void loadPointFileIdl(PointAccumulator& pa,const char* fileName)
{
/* Open the IDL input file: */
IO::FilePtr file(new IO::ReadAheadFilter(IO::openFile(fileName)));
file->setEndianness(Misc::LittleEndian);
/* Read the IDL file header: */
size_t numRecords=file->read<unsigned int>();
/* Read all records: */
float massMin=Math::Constants<float>::max;
float massMax=Math::Constants<float>::min;
for(size_t i=0;i<numRecords;++i)
{
/* Read the next record: */
IDLFileRecord record;
file->read(record);
/* Create a point: */
PointAccumulator::Point p;
#if 0
for(int i=0;i<3;++i)
p[i]=record.position[i];
#else
/* New formula using redshift to calculate galaxy position in Cartesian coordinates: */
double z=3200.0*double(record.z);
// double z=angdiadistscaled(record.z);
p[0]=double(record.dec)*z;
p[1]=double(record.ra)*z;
p[2]=z;
#endif
if(massMin>record.mVir)
massMin=record.mVir;
if(massMax<record.mVir)
massMax=record.mVir;
float rgbFactor=(record.mVir/32565.4f)*0.5f+0.5f;
/* Calculate false color from absolute SDSS magnitudes: */
PointAccumulator::Color c;
c[0]=(record.absMagSdss[2]-record.absMagSdss[3]+1.13f);
c[1]=((-record.absMagSdss[2]-14.62f)*0.3);
c[2]=(record.absMagSdss[1]-record.absMagSdss[2]+0.73f);
// if(record.recordType==0)
{
/* Store the point: */
pa.addPoint(p,c);
}
}
std::cout<<"mVir range: "<<massMin<<" - "<<massMax<<std::endl;
}
/***********************************
Helper structures to load X3P files:
***********************************/