-
Notifications
You must be signed in to change notification settings - Fork 39
/
NormalCalculator.icpp
399 lines (345 loc) · 12.1 KB
/
NormalCalculator.icpp
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
/***********************************************************************
NormalCalculator - Functor classes to calculate a normal vector for each
point in a LiDAR data set.
Copyright (c) 2008-2014 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
***********************************************************************/
#define NORMALCALCULATOR_IMPLEMENTATION
#include "NormalCalculator.h"
#include <iostream>
#include <iomanip>
#include <Misc/ThrowStdErr.h>
#include <Misc/File.h>
#include <Math/Math.h>
namespace {
/**************
Helper classes:
**************/
class FindPoint // Class to find a point inside an octree node
{
/* Elements: */
private:
Point queryPoint; // The position of the point to find
const LidarPoint* foundPoint; // The found LiDAR point
/* Constructors and destructors: */
public:
FindPoint(const Point& sQueryPoint)
:queryPoint(sQueryPoint),
foundPoint(0)
{
}
/* Methods: */
void operator()(const LidarPoint& lp)
{
if(Geometry::sqrDist(lp,queryPoint)==Scalar(0))
foundPoint=&lp;
}
const Point& getQueryPoint(void) const
{
return queryPoint;
}
Scalar getQueryRadius2(void) const
{
return Scalar(0);
}
const LidarPoint* getFoundPoint(void) const
{
return foundPoint;
}
};
class NormalAverager // Class to average normal vectors of collapsed points during subsampling
{
/* Elements: */
private:
Point queryPoint; // The LiDAR point whose neighbors to find
Scalar radius2; // Squared radius of search sphere around query point
const Vector& pointNormal; // Normal vector onto which to project near normals before averaging
const LidarPoint* pointBase; // Base pointer of processed node's point array
const Vector* normalBase; // Base pointer of processed node's normal vector array
Vector normal; // The averaged normal vector
/* Constructors and destructors: */
public:
NormalAverager(const Point& sQueryPoint,Scalar sRadius2,const Vector& sPointNormal)
:queryPoint(sQueryPoint),
radius2(sRadius2),
pointNormal(sPointNormal),
pointBase(0),normalBase(0),
normal(Vector::zero)
{
}
/* Methods: */
void setArrays(const LidarPoint* sPointBase,const Vector* sNormalBase) // Sets the point and normal vector arrays for the next process
{
pointBase=sPointBase;
normalBase=sNormalBase;
}
void operator()(const LidarPoint& lp)
{
/* Check if the point is inside the search radius: */
if(Geometry::sqrDist(lp,queryPoint)<=radius2)
{
/* Get the point's normal vector by mapping its index into the normal array: */
const Vector& nearNormal=normalBase[&lp-pointBase];
/* Accumulate the result normal: */
Scalar nearNormalLen=Geometry::mag(nearNormal);
if(nearNormalLen>Scalar(0))
{
if(nearNormal*pointNormal>=Scalar(0))
normal+=nearNormal/nearNormalLen;
else
normal-=nearNormal/nearNormalLen;
}
}
}
const Point& getQueryPoint(void) const
{
return queryPoint;
}
Scalar getQueryRadius2(void) const
{
return radius2;
}
const Vector& getNormal(void) const // Returns the averaged normal vector
{
return normal;
}
};
}
/*************************************
Methods of class NodeNormalCalculator:
*************************************/
template <class NormalCalculatorParam>
inline
void*
NodeNormalCalculator<NormalCalculatorParam>::calcThreadMethod(
unsigned int threadIndex)
{
Threads::Thread::setCancelState(Threads::Thread::CANCEL_ENABLE);
/* Create this thread's normal calculator: */
NormalCalculator nc(normalCalculator);
while(true)
{
/* Wait on the calculation barrier until there is a job: */
calcBarrier.synchronize();
if(shutdownThreads)
break;
/* Process the current node: */
unsigned int firstI=(threadIndex*currentNode->getNumPoints())/numThreads;
unsigned int lastI=((threadIndex+1)*currentNode->getNumPoints())/numThreads;
for(unsigned int i=firstI;i<lastI;++i)
{
/* Prepare the normal calculator: */
nc.prepare((*currentNode)[i]);
/* Process the point's neighborhood: */
lpo.processPointsDirected(nc);
/* Get the point's normal vector: */
if(nc.getNumPoints()>=3)
{
/* Get the fitted plane's normal vector: */
normalBuffer[i]=nc.calcPlane().getNormal();
/* Scale the normal vector by distance to the closest non-identical neighbor: */
normalBuffer[i]*=nc.getClosestDist();
}
else
{
/* Solitary point; assign dummy normal vector: */
normalBuffer[i]=Vector::zero;
if(saveOutliers)
{
Threads::Mutex::Lock outlierLock(outlierMutex);
outliers[numOutliers]=(*currentNode)[i];
++numOutliers;
}
}
}
/* Synchronize on the calculation barrier to signal job completion: */
calcBarrier.synchronize();
}
return 0;
}
template <class NormalCalculatorParam>
inline
void*
NodeNormalCalculator<NormalCalculatorParam>::subsampleThreadMethod(
unsigned int threadIndex)
{
Threads::Thread::setCancelState(Threads::Thread::CANCEL_ENABLE);
while(true)
{
/* Wait on the subsampling barrier until there is a job: */
subsampleBarrier.synchronize();
if(shutdownThreads)
break;
/* Find the points that were collapsed onto each node point and average their normal vectors: */
Scalar averageRadius2=Math::sqr(currentNode->getDetailSize()*Scalar(1.5));
unsigned int firstI=(threadIndex*currentNode->getNumPoints())/numThreads;
unsigned int lastI=((threadIndex+1)*currentNode->getNumPoints())/numThreads;
for(unsigned int i=firstI;i<lastI;++i)
{
/*****************************************************************
Find the exact normal vector of this point's "ancestor" to
properly average normals:
*****************************************************************/
/* Find the child node containing this point's ancestor: */
int pointChildIndex=currentNode->getDomain().findChild((*currentNode)[i]);
LidarProcessOctree::Node* pointChild=currentChildren[pointChildIndex];
/* Find the point's ancestor: */
FindPoint fp((*currentNode)[i]);
lpo.processNodePointsDirected(pointChild,fp);
if(fp.getFoundPoint()==0)
{
/* This is an internal corruption in the octree file. Print a helpful and non-offensive error message: */
Misc::throwStdErr("Fatal error: Octree file corrupted around position (%f, %f, %f)",(*currentNode)[i][0],(*currentNode)[i][1],(*currentNode)[i][2]);
}
/* Retrieve the ancestor's normal vector: */
const Vector& pointNormal=childNormalBuffers[pointChildIndex][fp.getFoundPoint()-pointChild->getPoints()];
/* Create a functor to average normal vectors from the point's neighborhood: */
NormalAverager normalAverager((*currentNode)[i],averageRadius2,pointNormal);
for(int childIndex=0;childIndex<8;++childIndex)
{
/* Check if the child node's domain overlaps the search sphere: */
if(currentChildren[childIndex]->getDomain().sqrDist((*currentNode)[i])<=averageRadius2)
{
/* Search for neighbors in this child node: */
normalAverager.setArrays(currentChildren[childIndex]->getPoints(),childNormalBuffers[childIndex]);
lpo.processNodePointsDirected(currentChildren[childIndex],normalAverager);
}
}
/* Store the averaged normal vector: */
normalBuffer[i]=normalAverager.getNormal();
normalBuffer[i]*=(Geometry::mag(pointNormal)-pointChild->getDetailSize()+currentNode->getDetailSize())/Geometry::mag(normalBuffer[i]);
}
/* Synchronize on the subsampling barrier to signal job completion: */
subsampleBarrier.synchronize();
}
return 0;
}
template <class NormalCalculatorParam>
inline
NodeNormalCalculator<NormalCalculatorParam>::NodeNormalCalculator(
LidarProcessOctree& sLpo,
const typename NodeNormalCalculator<NormalCalculatorParam>::NormalCalculator& sNormalCalculator,
const char* normalFileName,
unsigned int sNumThreads)
:lpo(sLpo),
normalCalculator(sNormalCalculator),
normalBuffer(new Vector[lpo.getMaxNumPointsPerNode()]),
normalDataSize(sizeof(Scalar)*3),
normalFile(normalFileName,LidarFile::ReadWrite),
saveOutliers(false),numOutliers(0),outliers(0),outlierFile(0),
numThreads(sNumThreads),shutdownThreads(false),
calcThreads(new Threads::Thread[numThreads]),calcBarrier(numThreads+1),
subsampleThreads(new Threads::Thread[numThreads]),subsampleBarrier(numThreads+1),
currentNode(0),
numProcessedNodes(0)
{
/* Create the child normal buffers: */
for(int i=0;i<8;++i)
childNormalBuffers[i]=new Vector[lpo.getMaxNumPointsPerNode()];
/* Write the normal file's header: */
normalFile.setEndianness(Misc::LittleEndian);
LidarDataFileHeader dfh((unsigned int)(normalDataSize));
dfh.write(normalFile);
/* Start the worker threads: */
for(unsigned int i=0;i<numThreads;++i)
{
calcThreads[i].start(this,&NodeNormalCalculator::calcThreadMethod,i);
subsampleThreads[i].start(this,&NodeNormalCalculator::subsampleThreadMethod,i);
}
}
template <class NormalCalculatorParam>
inline
NodeNormalCalculator<NormalCalculatorParam>::~NodeNormalCalculator(
void)
{
/* Shut down all threads: */
shutdownThreads=true;
calcBarrier.synchronize();
subsampleBarrier.synchronize();
for(unsigned int i=0;i<numThreads;++i)
{
calcThreads[i].join();
subsampleThreads[i].join();
}
delete[] calcThreads;
delete[] subsampleThreads;
/* Delete all buffers: */
delete[] normalBuffer;
for(int i=0;i<8;++i)
delete[] childNormalBuffers[i];
delete[] outliers;
delete outlierFile;
}
template <class NormalCalculatorParam>
inline
void
NodeNormalCalculator<NormalCalculatorParam>::saveOutlierPoints(
const char* outlierFileName)
{
saveOutliers=true;
numOutliers=0;
outliers=new Point[lpo.getMaxNumPointsPerNode()];
outlierFile=new Misc::File(outlierFileName,"wt");
}
template <class NormalCalculatorParam>
inline
void
NodeNormalCalculator<NormalCalculatorParam>::operator()(
LidarProcessOctree::Node& node,
unsigned int nodeLevel)
{
currentNode=&node;
/* Check if this node is a leaf or an interior node: */
if(node.isLeaf())
{
/* Wake up the calculation threads: */
calcBarrier.synchronize();
/* Wait for their completion: */
calcBarrier.synchronize();
if(saveOutliers)
{
/* Write all outlier points to the file: */
for(size_t i=0;i<numOutliers;++i)
fprintf(outlierFile->getFilePtr(),"%.6f %.6f %.6f\n",outliers[i][0],outliers[i][1],outliers[i][2]);
numOutliers=0;
}
}
else
{
/* Get pointers to the node's children and load their normal vector arrays: */
normalFile.flush();
for(int childIndex=0;childIndex<8;++childIndex)
{
currentChildren[childIndex]=lpo.getChild(currentNode,childIndex);
if(currentChildren[childIndex]->getNumPoints()>0)
{
normalFile.setReadPosAbs(LidarDataFileHeader::getFileSize()+normalDataSize*currentChildren[childIndex]->getDataOffset());
normalFile.read(childNormalBuffers[childIndex],currentChildren[childIndex]->getNumPoints());
}
}
/* Wake up the subsampling threads: */
subsampleBarrier.synchronize();
/* Wait for their completion: */
subsampleBarrier.synchronize();
}
/* Write the node's normal vectors to the normal file: */
normalFile.setWritePosAbs(LidarDataFileHeader::getFileSize()+normalDataSize*currentNode->getDataOffset());
normalFile.write(normalBuffer,currentNode->getNumPoints());
normalFile.flush();
/* Update the progress counter: */
++numProcessedNodes;
int percent=int((numProcessedNodes*100+lpo.getNumNodes()/2)/lpo.getNumNodes());
std::cout<<"\b\b\b\b"<<std::setw(3)<<percent<<"%"<<std::flush;
}