-
Notifications
You must be signed in to change notification settings - Fork 39
/
LidarOctree.cpp
1493 lines (1310 loc) · 46.3 KB
/
LidarOctree.cpp
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
/***********************************************************************
LidarOctree - Class to render multiresolution LiDAR point sets.
Copyright (c) 2005-2013 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 "LidarOctree.h"
#include <string.h>
#include <string>
#include <iostream>
#include <iomanip>
#include <Misc/ThrowStdErr.h>
#include <Misc/SelfDestructArray.h>
#include <Geometry/Ray.h>
#include <Geometry/Box.h>
#include <GL/gl.h>
#include <GL/GLVertexTemplates.h>
#include <GL/GLContextData.h>
#include <GL/GLExtensionManager.h>
#include <GL/Extensions/GLARBPointParameters.h>
#include <GL/Extensions/GLARBVertexBufferObject.h>
#include <GL/GLFrustum.h>
#include "CoarseningHeap.h"
#include "PointBasedLightingShader.h"
/**********************************
Methods of class LidarOctree::Node:
**********************************/
LidarOctree::Node::~Node(void)
{
/* Delete point array: */
if(haveNormals)
delete[] static_cast<NVertex*>(points);
else
delete[] static_cast<Vertex*>(points);
/* Delete selected point flag mask: */
delete[] selectedPoints;
delete[] selectedPointColors;
/* Delete children: */
delete[] children;
}
namespace {
/***************
Helper function:
***************/
template <class VertexParam>
inline
void
intersectConeWithPoints(
LidarOctree::ConeIntersection& cone,
const VertexParam* points,
unsigned int numPoints)
{
/* Intersect the cone with all points in this node: */
for(unsigned int i=0;i<numPoints;++i)
{
/* Check if the point is inside the cone: */
Vector sp=points[i].position-cone.ray.getOrigin();
Scalar sp2=Geometry::sqr(sp);
Scalar xd=sp*cone.ray.getDirection();
if(xd>=Scalar(0)&&Math::sqr(xd)>=cone.coneAngleCos2*cone.d2*sp2)
{
/* Calculate the point's adjusted ray parameter: */
Scalar lambda=xd/cone.d2;
Scalar y2=sp2-Math::sqr(xd)/cone.d2;
Scalar testLambda=lambda;
if(y2>Scalar(0))
testLambda+=Math::sqrt(y2*cone.d2*Scalar(2.0));
/* Check against the parameter range: */
if(testLambda>=cone.testLambda1&&testLambda<cone.testLambdaMin)
{
cone.testLambdaMin=testLambda;
cone.lambdaMin=lambda;
}
}
}
}
}
void LidarOctree::Node::intersectCone(LidarOctree::ConeIntersection& cone) const
{
if(children!=0)
{
#if 1
/* Store the query's original ray parameter range: */
Scalar testLambda1=cone.testLambda1;
Scalar testLambda2=cone.testLambda2;
/* Process all children: */
for(int childIndex=0;childIndex<8;++childIndex)
{
/* Convert the child's domain into a box: */
Geometry::Box<Scalar,3> childDomainBox(children[childIndex].domain.getMin(),children[childIndex].domain.getMax());
/* Intersect the ray with the child's domain: */
std::pair<Scalar,Scalar> lambdas=childDomainBox.getRayParameters(cone.ray);
if(lambdas.first<testLambda1)
lambdas.first=testLambda1;
if(lambdas.second>cone.testLambdaMin)
lambdas.second=cone.testLambdaMin;
/* Recurse into the child if the ray intersects its domain: */
if(lambdas.first<lambdas.second)
{
/* Run the intersection test on the reduced parameter range: */
cone.testLambda1=lambdas.first;
cone.testLambda2=lambdas.second;
children[childIndex].intersectCone(cone);
}
}
#else
/* Determine the child node containing the ray's start point and the ray parameters at which the ray intersects the child node's separating planes: */
int childIndex=0x0;
Scalar planeLambdas[3];
for(int i=0;i<3;++i)
{
Scalar center=domain.getCenter(i);
if(ray.getOrigin()[i]>=center)
{
childIndex|=0x1<<i;
if(ray.getDirection()[i]<Scalar(0))
planeLambdas[i]=(center-ray.getOrigin()[i])/ray.getDirection()[i];
else
planeLambdas[i]=Scalar(-1);
}
else
{
if(ray.getDirection()[i]>Scalar(0))
planeLambdas[i]=(center-ray.getOrigin()[i])/ray.getDirection()[i];
else
planeLambdas[i]=Scalar(-1);
}
}
/* Traverse the children in the order they are intersected by the ray: */
while(lambda1<lambda2)
{
/* Determine the next plane crossing: */
int planeIndex=-1;
Scalar nextLambda=lambda2;
for(int i=0;i<3;++i)
if(planeLambdas[i]>lambda1&&planeLambdas[i]<nextLambda)
{
planeIndex=i;
nextLambda=planeLambdas[i];
}
/* Check the current child: */
Scalar childLambda=children[childIndex].intersectRay(ray,coneAngleCos2,lambda1,nextLambda);
/* If the current child reported an intersection, return it: */
if(childLambda<nextLambda)
return childLambda;
/* Otherwise, go to the next child: */
childIndex^=0x1<<planeIndex;
lambda1=nextLambda;
}
/* No intersections found: */
return lambda2;
#endif
}
else
{
/* Intersect the cone with all points in this node: */
if(haveNormals)
intersectConeWithPoints(cone,static_cast<const NVertex*>(points),numPoints);
else
intersectConeWithPoints(cone,static_cast<const Vertex*>(points),numPoints);
}
}
/**************************************
Methods of class LidarOctree::DataItem:
**************************************/
LidarOctree::DataItem::DataItem(unsigned int sCacheSize)
:hasVertexBufferObjectExtension(GLARBVertexBufferObject::isSupported()),
cacheSize(sCacheSize-1),
cacheSlots(new CacheSlot[cacheSize]),
cacheNodeMap(cacheSize+cacheSize/4),
lruHead(0),lruTail(0),
bypassVertexBufferObjectId(0),
hasPointParametersExtension(GLARBPointParameters::isSupported()),
numRenderedNodes(0),numCacheMisses(0),numCacheBypasses(0),numRenderedPoints(0),numBypassedPoints(0)
{
/* Allocate the cache objects: */
if(hasVertexBufferObjectExtension)
{
/* Initialize the vertex buffer object extension: */
GLARBVertexBufferObject::initExtension();
/* Create vertex buffer objects: */
GLuint* vertexBufferObjectIds=new GLuint[cacheSize+1];
glGenBuffersARB(cacheSize+1,vertexBufferObjectIds);
for(unsigned int i=0;i<cacheSize;++i)
cacheSlots[i].vertexBufferObjectId=vertexBufferObjectIds[i];
bypassVertexBufferObjectId=vertexBufferObjectIds[cacheSize];
delete[] vertexBufferObjectIds;
}
/* Initialize the LRU cache slot list: */
lruHead=&cacheSlots[0];
cacheSlots[0].pred=0;
for(int i=1;i<cacheSize;++i)
{
cacheSlots[i-1].succ=&cacheSlots[i];
cacheSlots[i].pred=&cacheSlots[i-1];
}
cacheSlots[cacheSize-1].succ=0;
lruTail=&cacheSlots[cacheSize-1];
if(hasPointParametersExtension)
{
/* Initialize the point parameters extension: */
GLARBPointParameters::initExtension();
}
}
LidarOctree::DataItem::~DataItem(void)
{
if(hasVertexBufferObjectExtension)
{
/* Delete vertex buffer objects: */
GLuint* vertexBufferObjectIds=new GLuint[cacheSize+1];
for(unsigned int i=0;i<cacheSize;++i)
vertexBufferObjectIds[i]=cacheSlots[i].vertexBufferObjectId;
vertexBufferObjectIds[cacheSize]=bypassVertexBufferObjectId;
glDeleteBuffersARB(cacheSize+1,vertexBufferObjectIds);
delete[] vertexBufferObjectIds;
}
/* Delete the cache slots: */
delete[] cacheSlots;
}
/****************************
Methods of class LidarOctree:
****************************/
void LidarOctree::renderSubTree(const LidarOctree::Node* node,const LidarOctree::Frustum& frustum,PointBasedLightingShader& pbls,LidarOctree::DataItem* dataItem) const
{
/* Bail out if the node is empty: */
if(node->numPoints==0)
return;
/* Check if this node intersects the view frustum: */
for(int plane=0;plane<6;++plane)
{
const Frustum::Plane::Vector& normal=frustum.getFrustumPlane(plane).getNormal();
/* Find the point on the node's bounding box which is closest to the frustum plane: */
Point p;
for(int i=0;i<3;++i)
p[i]=normal[i]>Scalar(0)?node->domain.getMax()[i]:node->domain.getMin()[i];
/* Bail out if the point is not inside the view frustum: */
if(frustum.getFrustumPlane(plane).contains(p))
return;
}
/* Find the point inside the node that is closest to the focus+context center: */
Point nodeFncPoint=fncCenter;
for(int i=0;i<3;++i)
{
if(nodeFncPoint[i]<node->domain.getMin()[i])
nodeFncPoint[i]=node->domain.getMin()[i];
if(nodeFncPoint[i]>node->domain.getMax()[i])
nodeFncPoint[i]=node->domain.getMax()[i];
}
/* Calculate the node's projected detail size: */
Scalar projectedDetailSize=frustum.calcProjectedRadius(nodeFncPoint,node->detailSize);
if(projectedDetailSize>=Scalar(0))
{
/* Adjust the projected detail size based on the focus+context rule: */
if(fncWeight>Scalar(0))
{
/* Calculate the distance from the node to the focus region: */
Scalar fncDist=Geometry::dist(nodeFncPoint,fncCenter)-node->radius;
if(fncDist>fncRadius)
{
/* Adjust the node's projected detail size: */
projectedDetailSize*=Math::pow(fncRadius/fncDist,fncWeight);
}
}
}
else
projectedDetailSize=Math::Constants<Scalar>::max; // Temporary workaround until GLFrustum is fixed
/* Update node's rendering traversal state: */
{
Threads::Mutex::Lock nodeLock(node->nodeMutex);
bool nodeStateChanged=false;
if(node->renderPass!=renderPass)
{
/* Store the node's LOD value from this rendering pass: */
node->maxLOD=projectedDetailSize;
node->renderPass=renderPass;
nodeStateChanged=true;
}
else
{
/* Update the node's maximum LOD value: */
if(node->maxLOD<projectedDetailSize)
{
node->maxLOD=projectedDetailSize;
nodeStateChanged=true;
}
}
if(node->coarseningHeapIndex!=~0x0U&&nodeStateChanged)
{
/* Update the node's data in the coarsening heap: */
{
Threads::Mutex::Lock coarseningHeapLock(coarseningHeapMutex);
coarseningHeap->move(const_cast<Node*>(node));
}
}
}
/* Check whether to render this node or its children: */
if(projectedDetailSize>=maxRenderLOD)
{
if(node->children!=0)
{
/* Use the view point for a view-ordered traversal of the child nodes: */
int childIndex=0x0;
Point nodeCenter=node->domain.getCenter();
Point eye=frustum.getEye().toPoint();
for(int i=0;i<3;++i)
if(eye[i]>=nodeCenter[i])
childIndex|=0x1<<i;
/* Render the node's children: */
// for(int i=7;i>=0;--i) // Back-to-front rendering
for(int i=0;i<8;++i) // Front-to-back rendering
renderSubTree(&node->children[i^childIndex],frustum,pbls,dataItem);
/* Done here... */
return;
}
else if(node->childrenOffset!=LidarFile::Offset(0))
{
/* Try inserting this node into the node loader thread's request queue: */
Threads::Mutex::Lock loadRequestLock(loadRequestMutex);
if(node->subdivisionQueueIndex<subdivisionRequestQueueLength)
{
/* Update the node's position in the subdivision queue if necessary: */
if(subdivisionRequestQueue[node->subdivisionQueueIndex].LOD<projectedDetailSize)
{
/* Adjust the node's position in the queue: */
for(;node->subdivisionQueueIndex>0&&subdivisionRequestQueue[node->subdivisionQueueIndex-1].LOD<projectedDetailSize;--node->subdivisionQueueIndex)
{
subdivisionRequestQueue[node->subdivisionQueueIndex]=subdivisionRequestQueue[node->subdivisionQueueIndex-1];
subdivisionRequestQueue[node->subdivisionQueueIndex].node->subdivisionQueueIndex=node->subdivisionQueueIndex;
}
/* Update the node's LOD value in the queue: */
subdivisionRequestQueue[node->subdivisionQueueIndex].node=const_cast<Node*>(node);
subdivisionRequestQueue[node->subdivisionQueueIndex].LOD=projectedDetailSize;
}
}
else if(node->subdivisionQueueIndex==subdivisionRequestQueueLength&&subdivisionRequestQueue[subdivisionRequestQueueLength-1].LOD<projectedDetailSize)
{
/* Remove the node from the last queue slot: */
if(subdivisionRequestQueue[subdivisionRequestQueueLength-1].node!=0)
subdivisionRequestQueue[subdivisionRequestQueueLength-1].node->subdivisionQueueIndex=subdivisionRequestQueueLength;
/* Insert the node into the subdivision request queue: */
unsigned int insertIndex;
for(insertIndex=subdivisionRequestQueueLength-1;insertIndex>0&&subdivisionRequestQueue[insertIndex-1].LOD<projectedDetailSize;--insertIndex)
{
if(subdivisionRequestQueue[insertIndex-1].node!=0)
subdivisionRequestQueue[insertIndex-1].node->subdivisionQueueIndex=insertIndex;
if(insertIndex<subdivisionRequestQueueLength)
subdivisionRequestQueue[insertIndex]=subdivisionRequestQueue[insertIndex-1];
}
node->subdivisionQueueIndex=insertIndex;
subdivisionRequestQueue[insertIndex].node=const_cast<Node*>(node);
subdivisionRequestQueue[insertIndex].LOD=projectedDetailSize;
/* Wake up the node loader thread: */
loadRequestCond.signal();
}
}
}
/* Retrieve the cache slot containing this node's vertex array: */
GLuint vertexBufferObjectId=0;
DataItem::CacheSlot* slot=0;
bool mustUploadData=false;
DataItem::NodeHasher::Iterator cnIt=dataItem->cacheNodeMap.findEntry(node);
if(cnIt.isFinished()) // Cache miss
{
/*******************************************************************
We use an LRU cache replacement strategy, but do not replace cache
slots that were already used in the same rendering pass to prevent
cache thrashing. If the cache is full for a rendering pass,
additional nodes will be rendered straight from the main memory data
structures.
*******************************************************************/
/* Check if the head of the LRU list is from a previous rendering pass: */
if(dataItem->lruHead->lastUsed!=renderPass)
{
/* Replace the cache slot: */
slot=dataItem->lruHead;
if(slot->node!=0)
{
/* Remove the currently cached node: */
dataItem->cacheNodeMap.removeEntry(slot->node);
}
slot->node=node;
dataItem->cacheNodeMap.setEntry(DataItem::NodeHasher::Entry(node,slot));
/* Remember to upload the node's data later: */
mustUploadData=true;
}
else
++dataItem->numCacheBypasses;
++dataItem->numCacheMisses;
}
else // Cache hit
{
/* Use the previously used cache slot: */
slot=cnIt->getDest();
/* Check if the cached point set is out-of-date: */
if(slot->version!=node->pointsVersion)
{
/* Remember to upload the node's data later: */
mustUploadData=true;
}
}
if(slot!=0)
{
/* Install the cache slot's buffer object (and upload data if required): */
if(dataItem->hasVertexBufferObjectExtension)
{
vertexBufferObjectId=slot->vertexBufferObjectId;
glBindBufferARB(GL_ARRAY_BUFFER_ARB,vertexBufferObjectId);
if(mustUploadData)
{
size_t arraySize=node->numPoints*(node->haveNormals?sizeof(NVertex):sizeof(Vertex));
glBufferDataARB(GL_ARRAY_BUFFER_ARB,arraySize,node->points,GL_DYNAMIC_DRAW_ARB);
}
}
/* Mark the cache slot as used and move it to the end of the LRU list: */
slot->version=node->pointsVersion;
slot->lastUsed=renderPass;
if(slot->pred!=0)
slot->pred->succ=slot->succ;
else
dataItem->lruHead=slot->succ;
if(slot->succ!=0)
slot->succ->pred=slot->pred;
else
dataItem->lruTail=slot->pred;
slot->pred=dataItem->lruTail;
dataItem->lruTail->succ=slot;
slot->succ=0;
dataItem->lruTail=slot;
}
else
{
/* Prepare for rendering directly from main memory: */
if(dataItem->hasVertexBufferObjectExtension)
{
vertexBufferObjectId=dataItem->bypassVertexBufferObjectId;
glBindBufferARB(GL_ARRAY_BUFFER_ARB,vertexBufferObjectId);
size_t arraySize=node->numPoints*(node->haveNormals?sizeof(NVertex):sizeof(Vertex));
glBufferDataARB(GL_ARRAY_BUFFER_ARB,arraySize,node->points,GL_STREAM_DRAW_ARB);
}
dataItem->numBypassedPoints+=node->numPoints;
}
/* Set this node's splat size: */
#if 0
pbls.setSurfelSize((baseSurfelSize+node->detailSize)*surfelScale); // For old fixed-size surfels
#else
pbls.setSurfelSize(baseSurfelSize*surfelScale); // For new adaptive surfels
#endif
/* Render this node's point set: */
if(vertexBufferObjectId!=0)
{
/* Render from the vertex buffer: */
if(node->haveNormals)
glVertexPointer(static_cast<const NVertex*>(0));
else
glVertexPointer(static_cast<const Vertex*>(0));
}
else
{
/* Render straight from the node vertex array (only happens if GL_ARB_vertex_buffer_object not supported): */
if(node->haveNormals)
glVertexPointer(static_cast<const NVertex*>(node->points));
else
glVertexPointer(static_cast<const Vertex*>(node->points));
}
glDrawArrays(GL_POINTS,0,node->numPoints);
#if 0
glColor3f(1.0f,0.0f,0.0f);
glBegin(GL_LINE_STRIP);
glVertex3f(node->domain.getMin()[0],node->domain.getMin()[1],node->domain.getMin()[2]);
glVertex3f(node->domain.getMax()[0],node->domain.getMin()[1],node->domain.getMin()[2]);
glVertex3f(node->domain.getMax()[0],node->domain.getMax()[1],node->domain.getMin()[2]);
glVertex3f(node->domain.getMin()[0],node->domain.getMax()[1],node->domain.getMin()[2]);
glVertex3f(node->domain.getMin()[0],node->domain.getMin()[1],node->domain.getMin()[2]);
glVertex3f(node->domain.getMin()[0],node->domain.getMin()[1],node->domain.getMax()[2]);
glVertex3f(node->domain.getMax()[0],node->domain.getMin()[1],node->domain.getMax()[2]);
glVertex3f(node->domain.getMax()[0],node->domain.getMax()[1],node->domain.getMax()[2]);
glVertex3f(node->domain.getMin()[0],node->domain.getMax()[1],node->domain.getMax()[2]);
glVertex3f(node->domain.getMin()[0],node->domain.getMin()[1],node->domain.getMax()[2]);
glEnd();
glBegin(GL_LINES);
glVertex3f(node->domain.getMax()[0],node->domain.getMin()[1],node->domain.getMin()[2]);
glVertex3f(node->domain.getMax()[0],node->domain.getMin()[1],node->domain.getMax()[2]);
glVertex3f(node->domain.getMax()[0],node->domain.getMax()[1],node->domain.getMin()[2]);
glVertex3f(node->domain.getMax()[0],node->domain.getMax()[1],node->domain.getMax()[2]);
glVertex3f(node->domain.getMin()[0],node->domain.getMax()[1],node->domain.getMin()[2]);
glVertex3f(node->domain.getMin()[0],node->domain.getMax()[1],node->domain.getMax()[2]);
glEnd();
#endif
++dataItem->numRenderedNodes;
dataItem->numRenderedPoints+=node->numPoints;
}
void LidarOctree::interactWithSubTree(LidarOctree::Node* node,const LidarOctree::Interactor& interactor)
{
/* Bail out if the node is empty: */
if(node->numPoints==0)
return;
/* Calculate the node's distance from the interactor: */
Scalar interactorDist2=node->domain.sqrDist(interactor.center);
if(interactorDist2>=Math::sqr(interactor.radius))
return;
/* Calculate an appropriate LOD value for the node: */
Scalar interactorLOD=(node->radius*maxRenderLOD)/interactor.radius; // This could use some tweaking
/* Update node's rendering traversal state: */
{
Threads::Mutex::Lock nodeLock(node->nodeMutex);
bool nodeStateChanged=false;
if(node->renderPass!=renderPass)
{
/* Store the node's LOD value from this rendering pass: */
node->maxLOD=interactorLOD;
node->renderPass=renderPass;
nodeStateChanged=true;
}
else
{
/* Update the node's maximum LOD value: */
if(node->maxLOD<interactorLOD)
{
node->maxLOD=interactorLOD;
nodeStateChanged=true;
}
}
if(node->coarseningHeapIndex!=~0x0U&&nodeStateChanged)
{
/* Update the node's data in the coarsening heap: */
{
Threads::Mutex::Lock coarseningHeapLock(coarseningHeapMutex);
coarseningHeap->move(node);
}
}
}
/* Check if the node should be subdivided: */
if(node->children==0)
{
/* Subdivide if the node is not a leaf: */
if(node->childrenOffset!=LidarFile::Offset(0))
{
/* Try inserting this node into the node loader thread's request queue: */
Threads::Mutex::Lock loadRequestLock(loadRequestMutex);
if(node->subdivisionQueueIndex<subdivisionRequestQueueLength)
{
/* Update the node's position in the subdivision queue if necessary: */
if(subdivisionRequestQueue[node->subdivisionQueueIndex].LOD<interactorLOD)
{
/* Adjust the node's position in the queue: */
for(;node->subdivisionQueueIndex>0&&subdivisionRequestQueue[node->subdivisionQueueIndex-1].LOD<interactorLOD;--node->subdivisionQueueIndex)
{
subdivisionRequestQueue[node->subdivisionQueueIndex]=subdivisionRequestQueue[node->subdivisionQueueIndex-1];
subdivisionRequestQueue[node->subdivisionQueueIndex].node->subdivisionQueueIndex=node->subdivisionQueueIndex;
}
/* Update the node's LOD value in the queue: */
subdivisionRequestQueue[node->subdivisionQueueIndex].node=node;
subdivisionRequestQueue[node->subdivisionQueueIndex].LOD=interactorLOD;
}
}
else if(node->subdivisionQueueIndex==subdivisionRequestQueueLength&&subdivisionRequestQueue[subdivisionRequestQueueLength-1].LOD<interactorLOD)
{
/* Remove the node from the last queue slot: */
if(subdivisionRequestQueue[subdivisionRequestQueueLength-1].node!=0)
subdivisionRequestQueue[subdivisionRequestQueueLength-1].node->subdivisionQueueIndex=subdivisionRequestQueueLength;
/* Insert the node into the subdivision request queue: */
unsigned int insertIndex;
for(insertIndex=subdivisionRequestQueueLength-1;insertIndex>0&&subdivisionRequestQueue[insertIndex-1].LOD<interactorLOD;--insertIndex)
{
if(subdivisionRequestQueue[insertIndex-1].node!=0)
subdivisionRequestQueue[insertIndex-1].node->subdivisionQueueIndex=insertIndex;
if(insertIndex<subdivisionRequestQueueLength)
subdivisionRequestQueue[insertIndex]=subdivisionRequestQueue[insertIndex-1];
}
node->subdivisionQueueIndex=insertIndex;
subdivisionRequestQueue[insertIndex].node=node;
subdivisionRequestQueue[insertIndex].LOD=interactorLOD;
/* Wake up the node loader thread: */
loadRequestCond.signal();
}
}
}
else
{
/* Recurse into the node's children: */
for(int i=0;i<8;++i)
interactWithSubTree(&node->children[i],interactor);
}
}
void LidarOctree::selectPoints(LidarOctree::Node* node,const LidarOctree::Interactor& interactor)
{
/* Check if the interactor's region of influence intersects the node's domain: */
Scalar dist2=node->domain.sqrDist(interactor.center);
Scalar ir2=Math::sqr(interactor.radius);
if(dist2<ir2)
{
{
Threads::Mutex::Lock selectionLock(node->selectionMutex);
bool selectionEmpty=node->selectedPoints==0;
/* Select points in this node: */
if(node->haveNormals)
selectPointsInNode<NVertex>(node,interactor);
else
selectPointsInNode<Vertex>(node,interactor);
/* Check if this node just had its first points selected: */
if(selectionEmpty&&node->selectedPoints!=0)
{
/* Check if the node's parent is in the coarsening heap: */
if(node->parent!=0&&node->parent->coarseningHeapIndex!=~0x0)
{
Threads::Mutex::Lock coarseningHeapLock(coarseningHeapMutex);
coarseningHeap->remove(node->parent);
}
}
}
if(node->children!=0)
{
/* Recurse into the node's children: */
for(int childIndex=0;childIndex<8;++childIndex)
selectPoints(&node->children[childIndex],interactor);
}
}
}
bool LidarOctree::deselectPoints(LidarOctree::Node* node,const LidarOctree::Interactor& interactor)
{
/* Check if the interactor's region of influence intersects the node's domain: */
Scalar dist2=node->domain.sqrDist(interactor.center);
Scalar ir2=Math::sqr(interactor.radius);
if(dist2<ir2)
{
if(node->selectedPoints!=0)
{
Threads::Mutex::Lock selectionLock(node->selectionMutex);
/* Deselect points in this node: */
if(node->haveNormals)
deselectPointsInNode<NVertex>(node,interactor);
else
deselectPointsInNode<Vertex>(node,interactor);
}
if(node->children!=0)
{
/* Recurse into the node's children: */
bool canCoarsen=true;
for(int childIndex=0;childIndex<8;++childIndex)
canCoarsen=deselectPoints(&node->children[childIndex],interactor)&&canCoarsen;
if(canCoarsen&&node->coarseningHeapIndex==~0x0)
{
/* Insert the node into the coarsening heap: */
Threads::Mutex::Lock coarseningHeapLock(coarseningHeapMutex);
coarseningHeap->insert(node);
}
}
}
return node->children==0&&node->selectedPoints==0;
}
bool LidarOctree::clearSelection(LidarOctree::Node* node)
{
if(node->selectedPoints!=0)
{
Threads::Mutex::Lock selectionLock(node->selectionMutex);
/* Deselect all selected points: */
bool pointsChanged=false;
if(node->haveNormals)
{
NVertex* points=static_cast<NVertex*>(node->points);
for(unsigned int i=0;i<node->numPoints;++i)
{
if(node->selectedPoints[i])
{
GLubyte intensity=node->selectedPoints[i];
points[i].color=node->selectedPointColors[i];
pointsChanged=true;
}
}
}
else
{
Vertex* points=static_cast<Vertex*>(node->points);
for(unsigned int i=0;i<node->numPoints;++i)
{
if(node->selectedPoints[i])
{
GLubyte intensity=node->selectedPoints[i];
points[i].color=node->selectedPointColors[i];
pointsChanged=true;
}
}
}
/* Destroy the selection mask: */
delete[] node->selectedPoints;
node->selectedPoints=0;
delete[] node->selectedPointColors;
node->selectedPointColors=0;
/* Check if the points array has to be invalidated: */
if(pointsChanged)
++node->pointsVersion;
}
if(node->children!=0)
{
/* Recurse into the node's children: */
bool canCoarsen=true;
for(int childIndex=0;childIndex<8;++childIndex)
canCoarsen=clearSelection(&node->children[childIndex])&&canCoarsen;
if(canCoarsen&&node->coarseningHeapIndex==~0x0)
{
/* Insert the node into the coarsening heap: */
Threads::Mutex::Lock coarseningHeapLock(coarseningHeapMutex);
coarseningHeap->insert(node);
}
}
return node->children==0;
}
void LidarOctree::loadNodePoints(LidarOctree::Node* node)
{
if(node->haveNormals)
{
/* Create the node's point array (always allocate the maximum size to prevent memory fragmentation): */
Misc::SelfDestructArray<NVertex> points(maxNumPointsPerNode);
/* Load the node's points into a temporary point buffer: */
Misc::SelfDestructArray<LidarPoint> pointsBuffer(maxNumPointsPerNode);
pointsFile.setReadPosAbs(LidarDataFileHeader::getFileSize()+pointsRecordSize*node->dataOffset);
pointsFile.read(pointsBuffer.getArray(),node->numPoints);
Misc::SelfDestructArray<Vector> normalsBuffer(maxNumPointsPerNode);
normalsFile->setReadPosAbs(LidarDataFileHeader::getFileSize()+normalsRecordSize*node->dataOffset);
normalsFile->read(normalsBuffer.getArray(),node->numPoints);
if(colorsFile!=0)
{
/* Load the node's colors into a temporary buffer: */
Misc::SelfDestructArray<Color> colorsBuffer(maxNumPointsPerNode);
colorsFile->setReadPosAbs(LidarDataFileHeader::getFileSize()+colorsRecordSize*node->dataOffset);
colorsFile->read(colorsBuffer.getArray(),node->numPoints);
/* Copy the colors into the point buffer: */
LidarPoint* pPtr=pointsBuffer.getArray();
Color* cPtr=colorsBuffer.getArray();
for(unsigned int i=0;i<node->numPoints;++i,++pPtr,++cPtr)
for(int j=0;j<4;++j)
pPtr->value[j]=(*cPtr)[j];
}
/* Convert the LiDAR points to render points: */
NVertex* npPtr=points.getArray();
const LidarPoint* pPtr=pointsBuffer.getArray();
const Vector* nPtr=normalsBuffer.getArray();
for(unsigned int i=0;i<node->numPoints;++i,++npPtr,++pPtr,++nPtr)
{
/* Copy the point color: */
for(int j=0;j<4;++j)
npPtr->color[j]=pPtr->value[j];
/* Copy the normal vector: */
npPtr->normal=*nPtr;
/* Copy the point position: */
npPtr->position=*pPtr;
#if RECENTER_OCTREE
/* Offset the points so that the root node's center is the origin: */
npPtr->position-=pointOffset;
#endif
}
/* Store the new point array in the node: */
node->points=points.releaseTarget();
}
else
{
/* Create the node's point array (always allocate the maximum size to prevent memory fragmentation): */
Misc::SelfDestructArray<Vertex> points(maxNumPointsPerNode);
/* Load the node's points into a temporary point buffer: */
Misc::SelfDestructArray<LidarPoint> pointsBuffer(maxNumPointsPerNode);
pointsFile.setReadPosAbs(LidarDataFileHeader::getFileSize()+pointsRecordSize*node->dataOffset);
pointsFile.read(pointsBuffer.getArray(),node->numPoints);
if(colorsFile!=0)
{
/* Load the node's colors into a temporary buffer: */
Misc::SelfDestructArray<Color> colorsBuffer(maxNumPointsPerNode);
colorsFile->setReadPosAbs(LidarDataFileHeader::getFileSize()+colorsRecordSize*node->dataOffset);
colorsFile->read(colorsBuffer.getArray(),node->numPoints);
/* Copy the colors into the point buffer: */
LidarPoint* pPtr=pointsBuffer.getArray();
Color* cPtr=colorsBuffer.getArray();
for(unsigned int i=0;i<node->numPoints;++i,++pPtr,++cPtr)
for(int j=0;j<4;++j)
pPtr->value[j]=(*cPtr)[j];
}
/* Convert the LiDAR points to render points: */
Vertex* npPtr=points.getArray();
const LidarPoint* pPtr=pointsBuffer.getArray();
for(unsigned int i=0;i<node->numPoints;++i,++npPtr,++pPtr)
{
/* Copy the point color: */
for(int j=0;j<4;++j)
npPtr->color[j]=pPtr->value[j];
/* Copy the point position: */
npPtr->position=*pPtr;
#if RECENTER_OCTREE
/* Offset the points so that the root node's center is the origin: */
npPtr->position-=pointOffset;
#endif
}
/* Store the new point array in the node: */
node->points=points.releaseTarget();
}
}
template <class VertexParam>
inline
void
LidarOctree::selectCloseNeighbors(
LidarOctree::Node* node,
unsigned int left,
unsigned int right,
int splitDimension,
const VertexParam& point,
Scalar maxDist)
{
/* Calculate the index of the current point: */
unsigned int mid=(left+right)>>1;
VertexParam& np=static_cast<VertexParam*>(node->points)[mid];
int childSplitDimension=splitDimension+1;
if(childSplitDimension==3)
childSplitDimension=0;
/* Traverse into child closer to query point: */
if(point.position[splitDimension]<np.position[splitDimension])
{
/* Traverse left child: */
if(left<mid)
selectCloseNeighbors(node,left,mid-1,childSplitDimension,point,maxDist);
/* Process the current point: */
if(Geometry::sqrDist(point.position,np.position)<=Math::sqr(maxDist))
{
/* Select the point: */
selectPoint<VertexParam>(node,mid);
}
/* Traverse the right child: */
if(point.position[splitDimension]+maxDist>=np.position[splitDimension]&&right>mid)
selectCloseNeighbors(node,mid+1,right,childSplitDimension,point,maxDist);
}
else
{
/* Traverse right child: */
if(right>mid)
selectCloseNeighbors(node,mid+1,right,childSplitDimension,point,maxDist);
/* Process the current point: */
if(Geometry::sqrDist(point.position,np.position)<=Math::sqr(maxDist))
{
/* Select the point: */
selectPoint<VertexParam>(node,mid);
}
/* Traverse the left child: */
if(point.position[splitDimension]-maxDist<=np.position[splitDimension]&&left<mid)
selectCloseNeighbors(node,left,mid-1,childSplitDimension,point,maxDist);
}
}
template <class VertexParam>
inline
void
LidarOctree::propagateSelectedPoints(
LidarOctree::Node* node,
LidarOctree::Node* children)
{
VertexParam* nodePoints=static_cast<VertexParam*>(node->points);
for(int childIndex=0;childIndex<8;++childIndex)
if(children[childIndex].numPoints!=0)
{
VertexParam* childPoints=static_cast<VertexParam*>(children[childIndex].points);
/* Process each selected point in the node: */
for(unsigned int i=0;i<node->numPoints;++i)
if(node->selectedPoints[i])
{
/* Select the point's close neighbors in the child node: */
selectCloseNeighbors<VertexParam>(&children[childIndex],0,children[childIndex].numPoints-1,0,nodePoints[i],node->detailSize);
}
}
}
void* LidarOctree::nodeLoaderThreadMethod(void)
{
while(true)
{
/* Get the next subdivision request: */
Node* node;
{
Threads::Mutex::Lock loadRequestLock(loadRequestMutex);
while(subdivisionRequestQueue[0].node==0)
loadRequestCond.wait(loadRequestMutex);
node=subdivisionRequestQueue[0].node;