forked from mongodb/mongo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2d.cpp
2978 lines (2289 loc) · 104 KB
/
2d.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
// geo2d.cpp
/**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pch.h"
#include "../namespace-inl.h"
#include "../jsobj.h"
#include "../index.h"
#include "../../util/unittest.h"
#include "../commands.h"
#include "../pdfile.h"
#include "../btree.h"
#include "../curop-inl.h"
#include "../matcher.h"
#include "core.h"
// Note: we use indexinterface herein to talk to the btree code. In the future it would be nice to
// be able to use the V1 key class (see key.h) instead of toBson() which has some cost.
// toBson() is new with v1 so this could be slower than it used to be? a quick profiling
// might make sense.
namespace mongo {
class GeoKeyNode {
GeoKeyNode();
public:
GeoKeyNode(DiskLoc r, BSONObj k) : recordLoc(r), _key(k) { }
const DiskLoc recordLoc;
const BSONObj _key;
};
// just use old indexes for geo for now. todo.
// typedef BtreeBucket<V0> GeoBtreeBucket;
// typedef GeoBtreeBucket::KeyNode GeoKeyNode;
//#define BTREE btree<V0>
#if 0
# define GEODEBUGGING
# define GEODEBUG(x) cout << x << endl;
# define GEODEBUGPRINT(x) PRINT(x)
inline void PREFIXDEBUG(GeoHash prefix, const GeoConvert* g) {
if (!prefix.constrains()) {
cout << "\t empty prefix" << endl;
return ;
}
Point ll (g, prefix); // lower left
prefix.move(1,1);
Point tr (g, prefix); // top right
Point center ( (ll._x+tr._x)/2, (ll._y+tr._y)/2 );
double radius = fabs(ll._x - tr._x) / 2;
cout << "\t ll: " << ll.toString() << " tr: " << tr.toString()
<< " center: " << center.toString() << " radius: " << radius << endl;
}
#else
# define GEODEBUG(x)
# define GEODEBUGPRINT(x)
# define PREFIXDEBUG(x, y)
#endif
const double EARTH_RADIUS_KM = 6371;
const double EARTH_RADIUS_MILES = EARTH_RADIUS_KM * 0.621371192;
enum GeoDistType {
GEO_PLAIN,
GEO_SPHERE
};
inline double computeXScanDistance(double y, double maxDistDegrees) {
// TODO: this overestimates for large madDistDegrees far from the equator
return maxDistDegrees / min(cos(deg2rad(min(+89.0, y + maxDistDegrees))),
cos(deg2rad(max(-89.0, y - maxDistDegrees))));
}
GeoBitSets geoBitSets;
const string GEO2DNAME = "2d";
class Geo2dType : public IndexType , public GeoConvert {
public:
virtual ~Geo2dType() { }
Geo2dType( const IndexPlugin * plugin , const IndexSpec* spec )
: IndexType( plugin , spec ) {
BSONObjBuilder orderBuilder;
BSONObjIterator i( spec->keyPattern );
while ( i.more() ) {
BSONElement e = i.next();
if ( e.type() == String && GEO2DNAME == e.valuestr() ) {
uassert( 13022 , "can't have 2 geo field" , _geo.size() == 0 );
uassert( 13023 , "2d has to be first in index" , _other.size() == 0 );
_geo = e.fieldName();
}
else {
_other.push_back( e.fieldName() );
}
orderBuilder.append( "" , 1 );
}
uassert( 13024 , "no geo field specified" , _geo.size() );
double bits = _configval( spec , "bits" , 26 ); // for lat/long, ~ 1ft
uassert( 13028 , "bits in geo index must be between 1 and 32" , bits > 0 && bits <= 32 );
_bits = (unsigned) bits;
_max = _configval( spec , "max" , 180.0 );
_min = _configval( spec , "min" , -180.0 );
double numBuckets = (1024 * 1024 * 1024 * 4.0);
_scaling = numBuckets / ( _max - _min );
_order = orderBuilder.obj();
GeoHash a(0, 0, _bits);
GeoHash b = a;
b.move(1, 1);
// Epsilon is 1/100th of a bucket size
// TODO: Can we actually find error bounds for the sqrt function?
double epsilon = 0.001 / _scaling;
_error = distance(a, b) + epsilon;
// Error in radians
_errorSphere = deg2rad( _error );
}
double _configval( const IndexSpec* spec , const string& name , double def ) {
BSONElement e = spec->info[name];
if ( e.isNumber() ) {
return e.numberDouble();
}
return def;
}
virtual BSONObj fixKey( const BSONObj& in ) {
if ( in.firstElement().type() == BinData )
return in;
BSONObjBuilder b(in.objsize()+16);
if ( in.firstElement().isABSONObj() )
_hash( in.firstElement().embeddedObject() ).append( b , "" );
else if ( in.firstElement().type() == String )
GeoHash( in.firstElement().valuestr() ).append( b , "" );
else if ( in.firstElement().type() == RegEx )
GeoHash( in.firstElement().regex() ).append( b , "" );
else
return in;
BSONObjIterator i(in);
i.next();
while ( i.more() )
b.append( i.next() );
return b.obj();
}
/** Finds the key objects to put in an index */
virtual void getKeys( const BSONObj& obj, BSONObjSet& keys ) const {
getKeys( obj, &keys, NULL );
}
/** Finds all locations in a geo-indexed object */
// TODO: Can we just return references to the locs, if they won't change?
void getKeys( const BSONObj& obj, vector< BSONObj >& locs ) const {
getKeys( obj, NULL, &locs );
}
/** Finds the key objects and/or locations for a geo-indexed object */
void getKeys( const BSONObj &obj, BSONObjSet* keys, vector< BSONObj >* locs ) const {
BSONElementMSet bSet;
// Get all the nested location fields, but don't return individual elements from
// the last array, if it exists.
obj.getFieldsDotted(_geo.c_str(), bSet, false);
if( bSet.empty() )
return;
for( BSONElementMSet::iterator setI = bSet.begin(); setI != bSet.end(); ++setI ) {
BSONElement geo = *setI;
GEODEBUG( "Element " << geo << " found for query " << _geo.c_str() );
if ( geo.eoo() || ! geo.isABSONObj() )
continue;
//
// Grammar for location lookup:
// locs ::= [loc,loc,...,loc]|{<k>:loc,<k>:loc}|loc
// loc ::= { <k1> : #, <k2> : # }|[#, #]|{}
//
// Empty locations are ignored, preserving single-location semantics
//
BSONObj embed = geo.embeddedObject();
if ( embed.isEmpty() )
continue;
// Differentiate between location arrays and locations
// by seeing if the first element value is a number
bool singleElement = embed.firstElement().isNumber();
BSONObjIterator oi(embed);
while( oi.more() ) {
BSONObj locObj;
if( singleElement ) locObj = embed;
else {
BSONElement locElement = oi.next();
uassert( 13654, str::stream() << "location object expected, location array not in correct format",
locElement.isABSONObj() );
locObj = locElement.embeddedObject();
if( locObj.isEmpty() )
continue;
}
BSONObjBuilder b(64);
// Remember the actual location object if needed
if( locs )
locs->push_back( locObj );
// Stop if we don't need to get anything but location objects
if( ! keys ) {
if( singleElement ) break;
else continue;
}
_hash( locObj ).append( b , "" );
// Go through all the other index keys
for ( vector<string>::const_iterator i = _other.begin(); i != _other.end(); ++i ) {
// Get *all* fields for the index key
BSONElementSet eSet;
obj.getFieldsDotted( *i, eSet );
if ( eSet.size() == 0 )
b.appendAs( _spec->missingField(), "" );
else if ( eSet.size() == 1 )
b.appendAs( *(eSet.begin()), "" );
else {
// If we have more than one key, store as an array of the objects
BSONArrayBuilder aBuilder;
for( BSONElementSet::iterator ei = eSet.begin(); ei != eSet.end(); ++ei ) {
aBuilder.append( *ei );
}
BSONArray arr = aBuilder.arr();
b.append( "", arr );
}
}
keys->insert( b.obj() );
if( singleElement ) break;
}
}
}
BSONObj _fromBSONHash( const BSONElement& e ) const {
return _unhash( _tohash( e ) );
}
BSONObj _fromBSONHash( const BSONObj& o ) const {
return _unhash( _tohash( o.firstElement() ) );
}
GeoHash _tohash( const BSONElement& e ) const {
if ( e.isABSONObj() )
return _hash( e.embeddedObject() );
return GeoHash( e , _bits );
}
GeoHash _hash( const BSONObj& o ) const {
BSONObjIterator i(o);
uassert( 13067 , "geo field is empty" , i.more() );
BSONElement x = i.next();
uassert( 13068 , "geo field only has 1 element" , i.more() );
BSONElement y = i.next();
uassert( 13026 , "geo values have to be numbers: " + o.toString() , x.isNumber() && y.isNumber() );
return hash( x.number() , y.number() );
}
GeoHash hash( const Point& p ) const {
return hash( p._x, p._y );
}
GeoHash hash( double x , double y ) const {
return GeoHash( _convert(x), _convert(y) , _bits );
}
BSONObj _unhash( const GeoHash& h ) const {
unsigned x , y;
h.unhash( x , y );
BSONObjBuilder b;
b.append( "x" , _unconvert( x ) );
b.append( "y" , _unconvert( y ) );
return b.obj();
}
unsigned _convert( double in ) const {
uassert( 13027 , str::stream() << "point not in interval of [ " << _min << ", " << _max << " )", in < _max && in >= _min );
in -= _min;
assert( in >= 0 );
return (unsigned)(in * _scaling);
}
double _unconvert( unsigned in ) const {
double x = in;
x /= _scaling;
x += _min;
return x;
}
void unhash( const GeoHash& h , double& x , double& y ) const {
unsigned a,b;
h.unhash(a,b);
x = _unconvert( a );
y = _unconvert( b );
}
double distance( const GeoHash& a , const GeoHash& b ) const {
double ax,ay,bx,by;
unhash( a , ax , ay );
unhash( b , bx , by );
double dx = bx - ax;
double dy = by - ay;
return sqrt( ( dx * dx ) + ( dy * dy ) );
}
double sizeDiag( const GeoHash& a ) const {
GeoHash b = a;
b.move( 1 , 1 );
return distance( a , b );
}
double sizeEdge( const GeoHash& a ) const {
if( ! a.constrains() )
return _max - _min;
double ax,ay,bx,by;
GeoHash b = a;
b.move( 1 , 1 );
unhash( a, ax, ay );
unhash( b, bx, by );
// _min and _max are a singularity
if (bx == _min)
bx = _max;
return (fabs(ax-bx));
}
const IndexDetails* getDetails() const {
return _spec->getDetails();
}
virtual shared_ptr<Cursor> newCursor( const BSONObj& query , const BSONObj& order , int numWanted ) const;
virtual IndexSuitability suitability( const BSONObj& query , const BSONObj& order ) const {
BSONElement e = query.getFieldDotted(_geo.c_str());
switch ( e.type() ) {
case Object: {
BSONObj sub = e.embeddedObject();
switch ( sub.firstElement().getGtLtOp() ) {
case BSONObj::opNEAR:
case BSONObj::opWITHIN:
return OPTIMAL;
default:
// We can try to match if there's no other indexing defined,
// this is assumed a point
return HELPFUL;
}
}
case Array:
// We can try to match if there's no other indexing defined,
// this is assumed a point
return HELPFUL;
default:
return USELESS;
}
}
string _geo;
vector<string> _other;
unsigned _bits;
double _max;
double _min;
double _scaling;
BSONObj _order;
double _error;
double _errorSphere;
};
class Box {
public:
Box( const Geo2dType * g , const GeoHash& hash )
: _min( g , hash ) ,
_max( _min._x + g->sizeEdge( hash ) , _min._y + g->sizeEdge( hash ) ) {
}
Box( double x , double y , double size )
: _min( x , y ) ,
_max( x + size , y + size ) {
}
Box( Point min , Point max )
: _min( min ) , _max( max ) {
}
Box() {}
BSONArray toBSON() const {
return BSON_ARRAY( BSON_ARRAY( _min._x << _min._y ) << BSON_ARRAY( _max._x << _max._y ) );
}
string toString() const {
StringBuilder buf(64);
buf << _min.toString() << " -->> " << _max.toString();
return buf.str();
}
bool between( double min , double max , double val , double fudge=0) const {
return val + fudge >= min && val <= max + fudge;
}
bool onBoundary( double bound, double val, double fudge = 0 ) const {
return ( val >= bound - fudge && val <= bound + fudge );
}
bool mid( double amin , double amax , double bmin , double bmax , bool min , double& res ) const {
assert( amin <= amax );
assert( bmin <= bmax );
if ( amin < bmin ) {
if ( amax < bmin )
return false;
res = min ? bmin : amax;
return true;
}
if ( amin > bmax )
return false;
res = min ? amin : bmax;
return true;
}
double intersects( const Box& other ) const {
Point boundMin(0,0);
Point boundMax(0,0);
if ( mid( _min._x , _max._x , other._min._x , other._max._x , true , boundMin._x ) == false ||
mid( _min._x , _max._x , other._min._x , other._max._x , false , boundMax._x ) == false ||
mid( _min._y , _max._y , other._min._y , other._max._y , true , boundMin._y ) == false ||
mid( _min._y , _max._y , other._min._y , other._max._y , false , boundMax._y ) == false )
return 0;
Box intersection( boundMin , boundMax );
return intersection.area() / area();
}
double area() const {
return ( _max._x - _min._x ) * ( _max._y - _min._y );
}
double maxDim() const {
return max( _max._x - _min._x, _max._y - _min._y );
}
Point center() const {
return Point( ( _min._x + _max._x ) / 2 ,
( _min._y + _max._y ) / 2 );
}
void truncate( const Geo2dType* g ) {
if( _min._x < g->_min ) _min._x = g->_min;
if( _min._y < g->_min ) _min._y = g->_min;
if( _max._x > g->_max ) _max._x = g->_max;
if( _max._y > g->_max ) _max._y = g->_max;
}
void fudge( const Geo2dType* g ) {
_min._x -= g->_error;
_min._y -= g->_error;
_max._x += g->_error;
_max._y += g->_error;
}
bool onBoundary( Point p, double fudge = 0 ) {
return onBoundary( _min._x, p._x, fudge ) ||
onBoundary( _max._x, p._x, fudge ) ||
onBoundary( _min._y, p._y, fudge ) ||
onBoundary( _max._y, p._y, fudge );
}
bool inside( Point p , double fudge = 0 ) {
bool res = inside( p._x , p._y , fudge );
//cout << "is : " << p.toString() << " in " << toString() << " = " << res << endl;
return res;
}
bool inside( double x , double y , double fudge = 0 ) {
return
between( _min._x , _max._x , x , fudge ) &&
between( _min._y , _max._y , y , fudge );
}
bool contains(const Box& other, double fudge=0) {
return inside(other._min, fudge) && inside(other._max, fudge);
}
Point _min;
Point _max;
};
class Polygon {
public:
Polygon( void ) : _centroidCalculated( false ) {}
Polygon( vector<Point> points ) : _centroidCalculated( false ),
_points( points ) { }
void add( Point p ) {
_centroidCalculated = false;
_points.push_back( p );
}
int size( void ) const {
return _points.size();
}
/**
* Determine if the point supplied is contained by the current polygon.
*
* The algorithm uses a ray casting method.
*/
bool contains( const Point& p ) const {
return contains( p, 0 ) > 0;
}
int contains( const Point &p, double fudge ) const {
Box fudgeBox( Point( p._x - fudge, p._y - fudge ), Point( p._x + fudge, p._y + fudge ) );
int counter = 0;
Point p1 = _points[0];
for ( int i = 1; i <= size(); i++ ) {
Point p2 = _points[i % size()];
GEODEBUG( "Doing intersection check of " << fudgeBox.toString() << " with seg " << p1.toString() << " to " << p2.toString() );
// We need to check whether or not this segment intersects our error box
if( fudge > 0 &&
// Points not too far below box
fudgeBox._min._y <= std::max( p1._y, p2._y ) &&
// Points not too far above box
fudgeBox._max._y >= std::min( p1._y, p2._y ) &&
// Points not too far to left of box
fudgeBox._min._x <= std::max( p1._x, p2._x ) &&
// Points not too far to right of box
fudgeBox._max._x >= std::min( p1._x, p2._x ) ) {
GEODEBUG( "Doing detailed check" );
// If our box contains one or more of these points, we need to do an exact check.
if( fudgeBox.inside(p1) ) {
GEODEBUG( "Point 1 inside" );
return 0;
}
if( fudgeBox.inside(p2) ) {
GEODEBUG( "Point 2 inside" );
return 0;
}
// Do intersection check for vertical sides
if ( p1._y != p2._y ) {
double invSlope = ( p2._x - p1._x ) / ( p2._y - p1._y );
double xintersT = ( fudgeBox._max._y - p1._y ) * invSlope + p1._x;
if( fudgeBox._min._x <= xintersT && fudgeBox._max._x >= xintersT ) {
GEODEBUG( "Top intersection @ " << xintersT );
return 0;
}
double xintersB = ( fudgeBox._min._y - p1._y ) * invSlope + p1._x;
if( fudgeBox._min._x <= xintersB && fudgeBox._max._x >= xintersB ) {
GEODEBUG( "Bottom intersection @ " << xintersB );
return 0;
}
}
// Do intersection check for horizontal sides
if( p1._x != p2._x ) {
double slope = ( p2._y - p1._y ) / ( p2._x - p1._x );
double yintersR = ( p1._x - fudgeBox._max._x ) * slope + p1._y;
if( fudgeBox._min._y <= yintersR && fudgeBox._max._y >= yintersR ) {
GEODEBUG( "Right intersection @ " << yintersR );
return 0;
}
double yintersL = ( p1._x - fudgeBox._min._x ) * slope + p1._y;
if( fudgeBox._min._y <= yintersL && fudgeBox._max._y >= yintersL ) {
GEODEBUG( "Left intersection @ " << yintersL );
return 0;
}
}
}
else if( fudge == 0 ){
// If this is an exact vertex, we won't intersect, so check this
if( p._y == p1._y && p._x == p1._x ) return 1;
else if( p._y == p2._y && p._x == p2._x ) return 1;
// If this is a horizontal line we won't intersect, so check this
if( p1._y == p2._y && p._y == p1._y ){
// Check that the x-coord lies in the line
if( p._x >= std::min( p1._x, p2._x ) && p._x <= std::max( p1._x, p2._x ) ) return 1;
}
}
// Normal intersection test.
// TODO: Invert these for clearer logic?
if ( p._y > std::min( p1._y, p2._y ) ) {
if ( p._y <= std::max( p1._y, p2._y ) ) {
if ( p._x <= std::max( p1._x, p2._x ) ) {
if ( p1._y != p2._y ) {
double xinters = (p._y-p1._y)*(p2._x-p1._x)/(p2._y-p1._y)+p1._x;
// Special case of point on vertical line
if ( p1._x == p2._x && p._x == p1._x ){
// Need special case for the vertical edges, for example:
// 1) \e pe/----->
// vs.
// 2) \ep---e/----->
//
// if we count exact as intersection, then 1 is in but 2 is out
// if we count exact as no-int then 1 is out but 2 is in.
return 1;
}
else if( p1._x == p2._x || p._x <= xinters ) {
counter++;
}
}
}
}
}
p1 = p2;
}
if ( counter % 2 == 0 ) {
return -1;
}
else {
return 1;
}
}
/**
* Calculate the centroid, or center of mass of the polygon object.
*/
Point centroid( void ) {
/* Centroid is cached, it won't change betwen points */
if ( _centroidCalculated ) {
return _centroid;
}
Point cent;
double signedArea = 0.0;
double area = 0.0; // Partial signed area
/// For all vertices except last
int i = 0;
for ( i = 0; i < size() - 1; ++i ) {
area = _points[i]._x * _points[i+1]._y - _points[i+1]._x * _points[i]._y ;
signedArea += area;
cent._x += ( _points[i]._x + _points[i+1]._x ) * area;
cent._y += ( _points[i]._y + _points[i+1]._y ) * area;
}
// Do last vertex
area = _points[i]._x * _points[0]._y - _points[0]._x * _points[i]._y;
cent._x += ( _points[i]._x + _points[0]._x ) * area;
cent._y += ( _points[i]._y + _points[0]._y ) * area;
signedArea += area;
signedArea *= 0.5;
cent._x /= ( 6 * signedArea );
cent._y /= ( 6 * signedArea );
_centroidCalculated = true;
_centroid = cent;
return cent;
}
Box bounds( void ) {
// TODO: Cache this
_bounds._max = _points[0];
_bounds._min = _points[0];
for ( int i = 1; i < size(); i++ ) {
_bounds._max._x = max( _bounds._max._x, _points[i]._x );
_bounds._max._y = max( _bounds._max._y, _points[i]._y );
_bounds._min._x = min( _bounds._min._x, _points[i]._x );
_bounds._min._y = min( _bounds._min._y, _points[i]._y );
}
return _bounds;
}
private:
bool _centroidCalculated;
Point _centroid;
Box _bounds;
vector<Point> _points;
};
class Geo2dPlugin : public IndexPlugin {
public:
Geo2dPlugin() : IndexPlugin( GEO2DNAME ) {
}
virtual IndexType* generate( const IndexSpec* spec ) const {
return new Geo2dType( this , spec );
}
} geo2dplugin;
void __forceLinkGeoPlugin() {
geo2dplugin.getName();
}
class GeoHopper;
class GeoPoint {
public:
GeoPoint() : _distance( -1 ), _exact( false )
{}
//// Distance not used ////
GeoPoint( const GeoKeyNode& node )
: _key( node._key ) , _loc( node.recordLoc ) , _o( node.recordLoc.obj() ), _distance( -1 ) , _exact( false ) {
}
//// Immediate initialization of distance ////
GeoPoint( const GeoKeyNode& node, double distance, bool exact )
: _key( node._key ) , _loc( node.recordLoc ) , _o( node.recordLoc.obj() ), _distance( distance ), _exact( exact ) {
}
GeoPoint( const GeoPoint& pt, double distance, bool exact )
: _key( pt.key() ) , _loc( pt.loc() ) , _o( pt.obj() ), _distance( distance ), _exact( exact ) {
}
bool operator<( const GeoPoint& other ) const {
if( _distance != other._distance ) return _distance < other._distance;
if( _exact != other._exact ) return _exact < other._exact;
return _loc < other._loc;
}
double distance() const {
return _distance;
}
bool isExact() const {
return _exact;
}
BSONObj key() const {
return _key;
}
DiskLoc loc() const {
return _loc;
}
BSONObj obj() const {
return _o;
}
BSONObj pt() const {
return _pt;
}
bool isEmpty() {
return _o.isEmpty();
}
string toString() const {
return str::stream() << "Point from " << _o << " dist : " << _distance << ( _exact ? " (ex)" : " (app)" );
}
BSONObj _key;
DiskLoc _loc;
BSONObj _o;
BSONObj _pt;
double _distance;
bool _exact;
};
// GeoBrowse subclasses this
class GeoAccumulator {
public:
GeoAccumulator( const Geo2dType * g , const BSONObj& filter, bool uniqueDocs, bool needDistance )
: _g(g) ,
_keysChecked(0) ,
_lookedAt(0) ,
_matchesPerfd(0) ,
_objectsLoaded(0) ,
_pointsLoaded(0) ,
_found(0) ,
_uniqueDocs( uniqueDocs ) ,
_needDistance( needDistance )
{
if ( ! filter.isEmpty() ) {
_matcher.reset( new CoveredIndexMatcher( filter , g->keyPattern() ) );
GEODEBUG( "Matcher is now " << _matcher->docMatcher().toString() );
}
}
virtual ~GeoAccumulator() { }
/** Check if we've already looked at a key. ALSO marks as seen, anticipating a follow-up call
to add(). This is broken out to avoid some work extracting the key bson if it's an
already seen point.
*/
private:
set< pair<DiskLoc,int> > _seen;
public:
bool seen(DiskLoc bucket, int pos) {
_keysChecked++;
pair< set<pair<DiskLoc,int> >::iterator, bool > seenBefore = _seen.insert( make_pair(bucket,pos) );
if ( ! seenBefore.second ) {
GEODEBUG( "\t\t\t\t already seen : " << bucket.toString() << ' ' << pos ); // node.key.toString() << " @ " << Point( _g, GeoHash( node.key.firstElement() ) ).toString() << " with " << node.recordLoc.obj()["_id"] );
return true;
}
return false;
}
enum KeyResult { BAD, BORDER, GOOD };
virtual void add( const GeoKeyNode& node ) {
GEODEBUG( "\t\t\t\t checking key " << node._key.toString() )
_lookedAt++;
////
// Approximate distance check using key data
////
double keyD = 0;
Point keyP( _g, GeoHash( node._key.firstElement(), _g->_bits ) );
KeyResult keyOk = approxKeyCheck( keyP, keyD );
if ( keyOk == BAD ) {
GEODEBUG( "\t\t\t\t bad distance : " << node.recordLoc.obj() << "\t" << keyD );
return;
}
GEODEBUG( "\t\t\t\t good distance : " << node.recordLoc.obj() << "\t" << keyD );
////
// Check for match using other key (and potentially doc) criteria
////
// Remember match results for each object
map<DiskLoc, bool>::iterator match = _matched.find( node.recordLoc );
bool newDoc = match == _matched.end();
if( newDoc ) {
GEODEBUG( "\t\t\t\t matching new doc with " << (_matcher ? _matcher->docMatcher().toString() : "(empty)" ) );
// matcher
MatchDetails details;
if ( _matcher.get() ) {
bool good = _matcher->matchesWithSingleKeyIndex( node._key , node.recordLoc , &details );
_matchesPerfd++;
if ( details._loadedObject )
_objectsLoaded++;
if ( ! good ) {
GEODEBUG( "\t\t\t\t didn't match : " << node.recordLoc.obj()["_id"] );
_matched[ node.recordLoc ] = false;
return;
}
}
_matched[ node.recordLoc ] = true;
if ( ! details._loadedObject ) // don't double count
_objectsLoaded++;
}
else if( !((*match).second) ) {
GEODEBUG( "\t\t\t\t previously didn't match : " << node.recordLoc.obj()["_id"] );
return;
}
////
// Exact check with particular data fields
////
// Can add multiple points
int diff = addSpecific( node , keyP, keyOk == BORDER, keyD, newDoc );
if( diff > 0 ) _found += diff;
else _found -= -diff;
}
virtual void getPointsFor( const BSONObj& key, const BSONObj& obj, vector< BSONObj >& locsForNode, bool allPoints = false ){
// Find all the location objects from the keys
vector< BSONObj > locs;
_g->getKeys( obj, allPoints ? locsForNode : locs );
_pointsLoaded++;
if( allPoints ) return;
if( locs.size() == 1 ){
locsForNode.push_back( locs[0] );
return;
}
// Find the particular location we want
GeoHash keyHash( key.firstElement(), _g->_bits );
// log() << "Hash: " << node.key << " and " << keyHash.getHash() << " unique " << _uniqueDocs << endl;
for( vector< BSONObj >::iterator i = locs.begin(); i != locs.end(); ++i ) {