/
filegdbindex_write.cpp
1443 lines (1286 loc) · 54.8 KB
/
filegdbindex_write.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
/******************************************************************************
*
* Project: OpenGIS Simple Features Reference Implementation
* Purpose: Implements writing of FileGDB indices
* Author: Even Rouault, <even dot rouault at spatialys.com>
*
******************************************************************************
* Copyright (c) 2022, Even Rouault <even dot rouault at spatialys.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "cpl_port.h"
#include "filegdbtable.h"
#include "filegdbtable_priv.h"
#include <cctype>
#include <cstdint>
#include <algorithm>
#include <limits>
#include "cpl_string.h"
namespace OpenFileGDB
{
/************************************************************************/
/* RemoveIndices() */
/************************************************************************/
void FileGDBTable::RemoveIndices()
{
if( !m_bUpdate )
return;
CPLString osUCGeomFieldName;
if( m_iGeomField >= 0 )
{
osUCGeomFieldName = m_apoFields[m_iGeomField]->GetName();
osUCGeomFieldName.toupper();
}
GetIndexCount();
for( const auto& poIndex: m_apoIndexes )
{
if( m_iObjectIdField >= 0 &&
m_apoFields[m_iObjectIdField]->m_poIndex == poIndex.get() )
{
continue;
}
CPLString osUCIndexFieldName(poIndex->GetExpression());
osUCIndexFieldName.toupper();
if( osUCIndexFieldName == osUCGeomFieldName )
{
VSIUnlink( CPLResetExtension( m_osFilename.c_str(), "spx") );
}
else
{
VSIUnlink( CPLResetExtension( m_osFilename.c_str(),
(poIndex->GetIndexName() + ".atx").c_str()) );
}
}
m_nHasSpatialIndex = false;
}
/************************************************************************/
/* RefreshIndices() */
/************************************************************************/
void FileGDBTable::RefreshIndices()
{
if( !m_bUpdate )
return;
RemoveIndices();
for( const auto& poIndex: m_apoIndexes )
{
if( m_iObjectIdField >= 0 &&
m_apoFields[m_iObjectIdField]->m_poIndex == poIndex.get() )
{
continue;
}
if( m_iGeomField >= 0 &&
m_apoFields[m_iGeomField]->m_poIndex == poIndex.get() &&
m_eTableGeomType != FGTGT_MULTIPATCH )
{
CreateSpatialIndex();
}
else
{
const std::string osFieldName = poIndex->GetFieldName();
const int iField = GetFieldIdx(osFieldName);
if( iField >= 0 )
{
const auto eFieldType = m_apoFields[iField]->GetType();
if( eFieldType == FGFT_INT16 ||
eFieldType == FGFT_INT32 ||
eFieldType == FGFT_FLOAT32 ||
eFieldType == FGFT_FLOAT64 ||
eFieldType == FGFT_STRING ||
eFieldType == FGFT_DATETIME )
{
CreateAttributeIndex(poIndex.get());
}
}
}
}
}
/************************************************************************/
/* CreateIndex() */
/************************************************************************/
bool FileGDBTable::CreateIndex(const std::string& osIndexName,
const std::string& osExpression)
{
if( !m_bUpdate )
return false;
if( osIndexName.empty() || !(
(osIndexName[0] >= 'a' && osIndexName[0] <= 'z') ||
(osIndexName[0] >= 'A' && osIndexName[0] <= 'Z')) )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Invalid index name: must start with a letter");
return false;
}
for( const char ch: osIndexName )
{
if( !isalnum(ch) && ch != '_' )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Invalid index name: must contain only alpha numeric character or _");
return false;
}
}
if( osIndexName.size() > 16 )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Invalid index name: cannot be greater than 16 characters");
return false;
}
for( const auto& poIndex: m_apoIndexes )
{
if( EQUAL(poIndex->GetIndexName().c_str(), osIndexName.c_str()) )
{
CPLError(CE_Failure, CPLE_AppDefined,
"An index with same name already exists");
return false;
}
}
const std::string osFieldName =
FileGDBIndex::GetFieldNameFromExpression(osExpression);
const int iField = GetFieldIdx(osFieldName);
if( iField < 0 )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot find field %s", osFieldName.c_str());
return false;
}
if( m_apoFields[iField]->m_poIndex != nullptr )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Field %s has already a registered index",
osFieldName.c_str());
return false;
}
const auto eFieldType = m_apoFields[iField]->GetType();
if( eFieldType != FGFT_OBJECTID &&
eFieldType != FGFT_GEOMETRY &&
eFieldType != FGFT_INT16 &&
eFieldType != FGFT_INT32 &&
eFieldType != FGFT_FLOAT32 &&
eFieldType != FGFT_FLOAT64 &&
eFieldType != FGFT_STRING &&
eFieldType != FGFT_DATETIME )
{
// FGFT_GUID could potentially be added (cf a00000007.gdbindexes / GDBItemRelationshipTypes )
// Not sure about FGFT_GLOBALID, FGFT_XML or FGFT_RASTER
CPLError(CE_Failure, CPLE_AppDefined,
"Unsupported field type for index creation");
return false;
}
m_bDirtyGdbIndexesFile = true;
auto poIndex = cpl::make_unique<FileGDBIndex>();
poIndex->m_osIndexName = osIndexName;
poIndex->m_osExpression = osExpression;
if( iField != m_iObjectIdField && iField != m_iGeomField )
{
if( !CreateAttributeIndex(poIndex.get()) )
return false;
}
m_apoFields[iField]->m_poIndex = poIndex.get();
m_apoIndexes.push_back(std::move(poIndex));
return true;
}
/************************************************************************/
/* CreateGdbIndexesFile() */
/************************************************************************/
void FileGDBTable::CreateGdbIndexesFile()
{
std::vector<GByte> abyBuffer;
WriteUInt32(abyBuffer, static_cast<uint32_t>(m_apoIndexes.size()));
for( const auto& poIndex: m_apoIndexes )
{
const FileGDBField* poField = nullptr;
for(size_t i=0;i<m_apoFields.size();i++)
{
if( CPLString(poIndex->GetFieldName()).toupper() ==
CPLString(m_apoFields[i]->GetName()).toupper() )
{
poField = m_apoFields[i].get();
break;
}
}
if( poField == nullptr )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot find field corresponding to index field name %s",
poIndex->GetFieldName().c_str());
return;
}
WriteUTF16String(abyBuffer, poIndex->GetIndexName().c_str(), NUMBER_OF_CHARS_ON_UINT32);
WriteUInt16(abyBuffer, 0); // unknown semantics
if( poField->GetType() == FGFT_OBJECTID )
{
WriteUInt32(abyBuffer, 16); // unknown semantics
WriteUInt16(abyBuffer, 0xFFFF); // unknown semantics
}
else if( poField->GetType() == FGFT_GEOMETRY )
{
WriteUInt32(abyBuffer, 4); // unknown semantics
WriteUInt16(abyBuffer, 0); // unknown semantics
}
else
{
WriteUInt32(abyBuffer, 2); // unknown semantics
WriteUInt16(abyBuffer, 0); // unknown semantics
}
WriteUInt32(abyBuffer, 1); // unknown semantics
WriteUTF16String(abyBuffer, poIndex->GetExpression().c_str(), NUMBER_OF_CHARS_ON_UINT32);
WriteUInt16(abyBuffer, 0); // unknown semantics
}
VSILFILE* fp = VSIFOpenL( CPLResetExtension( m_osFilename.c_str(), "gdbindexes"), "wb" );
if( fp == nullptr )
return;
CPL_IGNORE_RET_VAL(VSIFWriteL(abyBuffer.data(), abyBuffer.size(), 1, fp));
VSIFCloseL(fp);
}
/************************************************************************/
/* ComputeOptimalSpatialIndexGridResolution() */
/************************************************************************/
void FileGDBTable::ComputeOptimalSpatialIndexGridResolution()
{
if( m_nValidRecordCount == 0 || m_iGeomField < 0 ||
m_adfSpatialIndexGridResolution.size() != 1 )
{
return;
}
auto poGeomField = cpl::down_cast<FileGDBGeomField*>(m_apoFields[m_iGeomField].get());
if( m_eTableGeomType == FGTGT_POINT )
{
// For point, use the density as the grid resolution
int nValid = 0;
for( int iCurFeat = 0; iCurFeat < m_nTotalRecordCount; ++iCurFeat )
{
iCurFeat = GetAndSelectNextNonEmptyRow(iCurFeat);
if( iCurFeat < 0 )
break;
const OGRField* psField = GetFieldValue(m_iGeomField);
if( psField != nullptr )
nValid ++;
}
if( nValid > 0 )
{
const double dfArea =
(poGeomField->GetXMax() - poGeomField->GetXMin()) *
(poGeomField->GetYMax() - poGeomField->GetYMin());
if( dfArea != 0 )
{
m_adfSpatialIndexGridResolution[0] = sqrt(dfArea / nValid);
}
else if( poGeomField->GetXMax() > poGeomField->GetXMin() )
{
m_adfSpatialIndexGridResolution[0] = (poGeomField->GetXMax() - poGeomField->GetXMin()) / nValid;
}
else if( poGeomField->GetYMax() > poGeomField->GetYMin() )
{
m_adfSpatialIndexGridResolution[0] = (poGeomField->GetYMax() - poGeomField->GetYMin()) / nValid;
}
else
{
return;
}
m_bDirtyGeomFieldSpatialIndexGridRes = true;
poGeomField->m_adfSpatialIndexGridResolution = m_adfSpatialIndexGridResolution;
}
}
else if( m_eTableGeomType == FGTGT_MULTIPOINT )
{
// For multipoint, use the density as the grid resolution
int64_t nValid = 0;
auto poGeomConverter = std::unique_ptr<FileGDBOGRGeometryConverter>(
FileGDBOGRGeometryConverter::BuildConverter(poGeomField));
for( int iCurFeat = 0; iCurFeat < m_nTotalRecordCount; ++iCurFeat )
{
iCurFeat = GetAndSelectNextNonEmptyRow(iCurFeat);
if( iCurFeat < 0 )
break;
const OGRField* psField = GetFieldValue(m_iGeomField);
if( psField != nullptr )
{
auto poGeom = std::unique_ptr<OGRGeometry>(poGeomConverter->GetAsGeometry(psField));
if( poGeom != nullptr && wkbFlatten(poGeom->getGeometryType()) == wkbMultiPoint )
{
nValid += poGeom->toMultiPoint()->getNumGeometries();
}
}
}
if( nValid > 0 )
{
const double dfArea =
(poGeomField->GetXMax() - poGeomField->GetXMin()) *
(poGeomField->GetYMax() - poGeomField->GetYMin());
if( dfArea != 0 )
{
m_adfSpatialIndexGridResolution[0] = sqrt(dfArea / nValid);
}
else if( poGeomField->GetXMax() > poGeomField->GetXMin() )
{
m_adfSpatialIndexGridResolution[0] = (poGeomField->GetXMax() - poGeomField->GetXMin()) / nValid;
}
else if( poGeomField->GetYMax() > poGeomField->GetYMin() )
{
m_adfSpatialIndexGridResolution[0] = (poGeomField->GetYMax() - poGeomField->GetYMin()) / nValid;
}
else
{
return;
}
m_bDirtyGeomFieldSpatialIndexGridRes = true;
poGeomField->m_adfSpatialIndexGridResolution = m_adfSpatialIndexGridResolution;
}
}
else
{
CPLDebug("OpenFileGDB", "Computing optimal grid size...");
// For other types of geometries, just take the maximum extent along x/y
// of all geometries
double dfMaxSize = 0;
OGREnvelope sEnvelope;
for( int iCurFeat = 0; iCurFeat < m_nTotalRecordCount; ++iCurFeat )
{
iCurFeat = GetAndSelectNextNonEmptyRow(iCurFeat);
if( iCurFeat < 0 )
break;
const OGRField* psField = GetFieldValue(m_iGeomField);
if( psField != nullptr )
{
if( GetFeatureExtent(psField, &sEnvelope) )
{
dfMaxSize = std::max(dfMaxSize, sEnvelope.MaxX - sEnvelope.MinX);
dfMaxSize = std::max(dfMaxSize, sEnvelope.MaxY - sEnvelope.MinY);
}
}
}
CPLDebug("OpenFileGDB", "Optimal grid size = %f", dfMaxSize);
if( dfMaxSize > 0 )
{
m_bDirtyGeomFieldSpatialIndexGridRes = true;
m_adfSpatialIndexGridResolution[0] = dfMaxSize;
poGeomField->m_adfSpatialIndexGridResolution = m_adfSpatialIndexGridResolution;
}
}
}
/************************************************************************/
/* WriteIndex() */
/************************************************************************/
template<class ValueOIDPair> static bool WriteIndex(
VSILFILE* fp,
std::vector<ValueOIDPair>& asValues,
void (*writeValueFunc)(std::vector<GByte>& abyPage,
const typename ValueOIDPair::first_type& value,
int maxStrSize),
int& nDepth,
int maxStrSize = 0)
{
constexpr int IDX_PAGE_SIZE = 4096;
constexpr int HEADER_SIZE_PAGE_REFERENCING_FEATURES = 12; // 3 * int32
constexpr int SIZEOF_FEATURE_ID = 4; // sizeof(int)
const int SIZEOF_INDEXED_VALUE = maxStrSize ? sizeof(uint16_t) * maxStrSize : sizeof(typename ValueOIDPair::first_type);
const int NUM_MAX_FEATURES_PER_PAGE =
(IDX_PAGE_SIZE - HEADER_SIZE_PAGE_REFERENCING_FEATURES) / (SIZEOF_FEATURE_ID + SIZEOF_INDEXED_VALUE);
// static_assert(NUM_MAX_FEATURES_PER_PAGE == 340, "NUM_MAX_FEATURES_PER_PAGE == 340");
const int OFFSET_FIRST_VAL_IN_PAGE =
HEADER_SIZE_PAGE_REFERENCING_FEATURES +
NUM_MAX_FEATURES_PER_PAGE * SIZEOF_FEATURE_ID;
// Configurable only for debugging & autotest purposes
const int numMaxFeaturesPerPage = [NUM_MAX_FEATURES_PER_PAGE]() {
const int nVal = atoi(CPLGetConfigOption(
"OPENFILEGDB_MAX_FEATURES_PER_SPX_PAGE", CPLSPrintf("%d", NUM_MAX_FEATURES_PER_PAGE)));
if( nVal < 2 )
return 2;
if( nVal > NUM_MAX_FEATURES_PER_PAGE )
return NUM_MAX_FEATURES_PER_PAGE;
return nVal;
} ();
if( asValues.size() > static_cast<size_t>(INT_MAX) ||
// Maximum number of values for depth == 4: this evaluates to ~ 13 billion values (~ features)
asValues.size() >
(((static_cast<uint64_t>(numMaxFeaturesPerPage) + 1) * numMaxFeaturesPerPage + 1) * numMaxFeaturesPerPage + 1) * numMaxFeaturesPerPage )
{
CPLError(CE_Failure, CPLE_NotSupported,
"More values in spatial index than can be handled");
return false;
}
// Sort by ascending values, and for same value by ascending OID
std::sort(asValues.begin(), asValues.end(),
[](const ValueOIDPair& a, const ValueOIDPair& b)
{
return a.first < b.first || (a.first == b.first && a.second < b.second);
});
bool bRet = true;
std::vector<GByte> abyPage;
abyPage.reserve(IDX_PAGE_SIZE);
const auto WriteRootPageNonLeaf = [=, &bRet, &asValues, &abyPage]
(int nNumDirectChildren, int nSubPageIdxToFeatIdxMultiplier)
{
// Write root page (level 1)
WriteUInt32(abyPage, 0); // id of next page at same level
WriteUInt32(abyPage, nNumDirectChildren == 1 ? 1 : nNumDirectChildren-1);
for( int i = 0; i < nNumDirectChildren; i++ )
{
WriteUInt32(abyPage, 2 + i); // id of subpage
}
// Add padding
abyPage.resize(OFFSET_FIRST_VAL_IN_PAGE);
if( nNumDirectChildren == 1 )
{
// Should only happen if OPENFILEGDB_FORCE_SPX_DEPTH is forced
writeValueFunc(abyPage, asValues.back().first, maxStrSize);
}
else
{
for( int i = 0; i < nNumDirectChildren-1; i++ )
{
const int nFeatIdx = (i+1) * nSubPageIdxToFeatIdxMultiplier - 1;
writeValueFunc(abyPage,asValues[nFeatIdx].first, maxStrSize);
}
}
abyPage.resize(IDX_PAGE_SIZE);
bRet &= VSIFWriteL(abyPage.data(), abyPage.size(), 1, fp) == 1;
};
const auto WriteLeafPages = [=, &bRet, &asValues, &abyPage]
(int pageBaseOffset, int nNumFeaturePages)
{
// Write leaf pages
for( int i = 0; i < nNumFeaturePages; ++i )
{
abyPage.clear();
int nNumFeaturesInPage = numMaxFeaturesPerPage;
if( i + 1 < nNumFeaturePages )
{
WriteUInt32(abyPage, pageBaseOffset + i + 1); // id of next page at same level
}
else
{
WriteUInt32(abyPage, 0);
nNumFeaturesInPage = static_cast<int>(asValues.size() - i * numMaxFeaturesPerPage);
}
CPLAssert(nNumFeaturesInPage > 0 && nNumFeaturesInPage <= NUM_MAX_FEATURES_PER_PAGE);
WriteUInt32(abyPage, nNumFeaturesInPage);
WriteUInt32(abyPage, 0); // unknown semantics
// Write features' ID
for( int j = 0; j < nNumFeaturesInPage; j++ )
{
WriteUInt32(abyPage, static_cast<uint32_t>(asValues[i * numMaxFeaturesPerPage + j].second));
}
// Add padding
abyPage.resize(OFFSET_FIRST_VAL_IN_PAGE);
// Write features' spatial index value
for( int j = 0; j < nNumFeaturesInPage; j++ )
{
writeValueFunc(abyPage, asValues[i * numMaxFeaturesPerPage + j].first, maxStrSize);
}
abyPage.resize(IDX_PAGE_SIZE);
bRet &= VSIFWriteL(abyPage.data(), abyPage.size(), 1, fp) == 1;
}
};
const auto WriteIntermediatePages = [=, &bRet, &asValues, &abyPage]
(int pageBaseOffset, int nNumPagesThisLevel, int nNumPagesNextLevel, int nSubPageIdxToFeatIdxMultiplier)
{
for( int i = 0; i < nNumPagesThisLevel; ++i )
{
abyPage.clear();
int nNumItemsInPage = numMaxFeaturesPerPage;
if( i + 1 < nNumPagesThisLevel )
{
WriteUInt32(abyPage, pageBaseOffset + i + 1); // id of next page at same level
}
else
{
WriteUInt32(abyPage, 0);
nNumItemsInPage = nNumPagesNextLevel - i * numMaxFeaturesPerPage;
CPLAssert(nNumItemsInPage > 1 && nNumItemsInPage <= NUM_MAX_FEATURES_PER_PAGE + 1);
nNumItemsInPage --;
}
CPLAssert(nNumItemsInPage > 0 && nNumItemsInPage <= NUM_MAX_FEATURES_PER_PAGE);
WriteUInt32(abyPage, nNumItemsInPage);
// Write subpages' ID
for( int j = 0; j < 1 + nNumItemsInPage; j++ )
{
WriteUInt32(abyPage, pageBaseOffset + nNumPagesThisLevel + i * numMaxFeaturesPerPage + j);
}
// Add padding
abyPage.resize(OFFSET_FIRST_VAL_IN_PAGE);
// Write features' spatial index value
for( int j = 0; j < nNumItemsInPage; j++ )
{
const int nFeatIdx = (i * numMaxFeaturesPerPage + j + 1) * nSubPageIdxToFeatIdxMultiplier - 1;
writeValueFunc(abyPage, asValues[nFeatIdx].first, maxStrSize);
}
abyPage.resize(IDX_PAGE_SIZE);
bRet &= VSIFWriteL(abyPage.data(), abyPage.size(), 1, fp) == 1;
}
};
const auto WriteLastTwoLevelPages =
[numMaxFeaturesPerPage, WriteIntermediatePages, WriteLeafPages]
(int pageBaseOffset, int nNumPagesBeforeLastLevel, int nNumFeaturePages)
{
// Write pages at level depth-1 (referencing pages of level depth)
WriteIntermediatePages(pageBaseOffset, nNumPagesBeforeLastLevel, nNumFeaturePages, numMaxFeaturesPerPage);
// Write leaf pages
WriteLeafPages(pageBaseOffset + nNumPagesBeforeLastLevel, nNumFeaturePages);
};
if( asValues.empty() || nDepth == 1 ||
(nDepth == 0 && static_cast<int>(asValues.size()) <= numMaxFeaturesPerPage) )
{
nDepth = 1;
WriteUInt32(abyPage, 0); // id of next page
WriteUInt32(abyPage, static_cast<uint32_t>(asValues.size()));
WriteUInt32(abyPage, 0); // unknown semantics
// Write features' ID
for( const auto& pair: asValues )
WriteUInt32(abyPage, static_cast<uint32_t>(pair.second));
// Add padding
abyPage.resize(OFFSET_FIRST_VAL_IN_PAGE);
// Write features' spatial index value
for( const auto& pair: asValues )
writeValueFunc(abyPage,pair.first, maxStrSize);
abyPage.resize(IDX_PAGE_SIZE);
bRet &= VSIFWriteL(abyPage.data(), abyPage.size(), 1, fp) == 1;
}
else if( nDepth == 2 ||
(nDepth == 0 && static_cast<int>(asValues.size()) <=
(numMaxFeaturesPerPage + 1) * numMaxFeaturesPerPage) )
{
nDepth = 2;
const int nNumFeaturePages = static_cast<int>(DIV_ROUND_UP(
asValues.size(), numMaxFeaturesPerPage));
CPLAssert(nNumFeaturePages-1 <= NUM_MAX_FEATURES_PER_PAGE);
// Write root page (level 1)
WriteRootPageNonLeaf(nNumFeaturePages, numMaxFeaturesPerPage);
// Write leaf pages (level 2)
WriteLeafPages(2, nNumFeaturePages);
}
else if( nDepth == 3 ||
(nDepth == 0 && static_cast<int>(asValues.size()) <=
((numMaxFeaturesPerPage + 1) * numMaxFeaturesPerPage + 1) * numMaxFeaturesPerPage) )
{
nDepth = 3;
// imagine simpler case: NUM_MAX_FEATURES_PER_PAGE = 2 and 9 values
// ==> nNumFeaturePages = ceil(9 / 2) = 5
// ==> nNumPagesLevel2 = ceil((5-1) / 2) = 2
// level 1:
// page 1: point to page 2(, 3)
// level 2:
// page 2: point to page 4, 5(, 6)
// page 3: point to page 6, 7(, 8)
// level 3:
// page 4: point to feature 1, 2
// page 5: point to feature 3, 4
// page 6: point to feature 5, 6
// page 7: point to feature 7, 8
// page 8: point to feature 9
// or NUM_MAX_FEATURES_PER_PAGE = 2 and 11 values
// ==> nNumFeaturePages = ceil(11 / 2) = 6
// ==> nNumPagesLevel2 = ceil((6-1) / 2) = 3
// level 1:
// page 1: point to page 2, 3(, 4)
// level 2:
// page 2: point to page 5, 6(, 7)
// page 3: point to page 7, 8(, 9)
// page 4: point to page 9(, 10)
// level 3:
// page 5: point to feature 1, 2
// page 6: point to feature 3, 4
// page 7: point to feature 5, 6
// page 8: point to feature 7, 8
// page 9: point to feature 9, 10
// page 10: point to feature 11
// or NUM_MAX_FEATURES_PER_PAGE = 2 and 14 values
// ==> nNumFeaturePages = ceil(14 / 2) = 7
// ==> nNumPagesLevel2 = ceil((7-1) / 2) = 3
// level 1:
// page 1: point to page 2, 3(, 4)
// level 2:
// page 2: point to page 5, 6(, 7)
// page 3: point to page 7, 8(, 9)
// page 4: point to page 9, 10(, 11)
// level 3:
// page 5: point to feature 1, 2
// page 6: point to feature 3, 4
// page 7: point to feature 5, 6
// page 8: point to feature 7, 8
// page 9: point to feature 9, 10
// page 10: point to feature 11, 12
// page 11: point to feature 13, 14
const int nNumFeaturePages = static_cast<int>(DIV_ROUND_UP(
asValues.size(), numMaxFeaturesPerPage));
const int nNumPagesLevel2 = nNumFeaturePages == 1 ? 1:
DIV_ROUND_UP(nNumFeaturePages-1, numMaxFeaturesPerPage);
CPLAssert(nNumPagesLevel2-1 <= NUM_MAX_FEATURES_PER_PAGE);
// Write root page (level 1)
WriteRootPageNonLeaf(nNumPagesLevel2, numMaxFeaturesPerPage * numMaxFeaturesPerPage);
// Write level 2 and level 3 pages
WriteLastTwoLevelPages(2, nNumPagesLevel2, nNumFeaturePages);
}
else
{
nDepth = 4;
const int nNumFeaturePages = static_cast<int>(DIV_ROUND_UP(
asValues.size(), numMaxFeaturesPerPage));
const int nNumPagesLevel3 = nNumFeaturePages == 1 ? 1:
DIV_ROUND_UP(nNumFeaturePages-1, numMaxFeaturesPerPage);
const int nNumPagesLevel2 = nNumPagesLevel3 == 1 ? 1 :
DIV_ROUND_UP(nNumPagesLevel3 - 1, numMaxFeaturesPerPage);
CPLAssert(nNumPagesLevel2-1 <= NUM_MAX_FEATURES_PER_PAGE);
// Write root page (level 1)
WriteRootPageNonLeaf(nNumPagesLevel2, numMaxFeaturesPerPage * numMaxFeaturesPerPage * numMaxFeaturesPerPage);
// Write pages at level 2 (referencing pages of level 3)
WriteIntermediatePages(2, nNumPagesLevel2, nNumPagesLevel3, numMaxFeaturesPerPage * numMaxFeaturesPerPage);
// Write pages at level 3 and 4
WriteLastTwoLevelPages(2 + nNumPagesLevel2, nNumPagesLevel3, nNumFeaturePages);
}
// Write trailer
std::vector<GByte> abyTrailer;
CPLAssert(SIZEOF_INDEXED_VALUE <= 255);
WriteUInt8(abyTrailer, static_cast<uint8_t>(SIZEOF_INDEXED_VALUE));
WriteUInt8(abyTrailer, maxStrSize ? 0x20 : 0x40); // unknown semantics
WriteUInt32(abyTrailer, 1); // unknown semantics
WriteUInt32(abyTrailer, nDepth); // index depth
WriteUInt32(abyTrailer, static_cast<uint32_t>(asValues.size()));
WriteUInt32(abyTrailer, 0); // unknown semantics
WriteUInt32(abyTrailer, 1); // unknown semantics
bRet &= VSIFWriteL(abyTrailer.data(), abyTrailer.size(), 1, fp) == 1;
return bRet;
}
/************************************************************************/
/* CreateSpatialIndex() */
/************************************************************************/
bool FileGDBTable::CreateSpatialIndex()
{
if( m_iGeomField < 0 ||
m_adfSpatialIndexGridResolution.empty() ||
m_adfSpatialIndexGridResolution.size() > 3 )
{
return false;
}
if( m_eTableGeomType == FGTGT_MULTIPATCH )
{
CPLError(CE_Failure, CPLE_NotSupported,
"Multipatch not supported for spatial index generation");
return false;
}
auto poGeomField = cpl::down_cast<FileGDBGeomField*>(m_apoFields[m_iGeomField].get());
if( m_adfSpatialIndexGridResolution.size() == 1 )
{
// Debug only
const char* pszGridSize = CPLGetConfigOption("OPENFILEGDB_GRID_SIZE", nullptr);
if( pszGridSize )
{
m_bDirtyGeomFieldSpatialIndexGridRes = true;
m_adfSpatialIndexGridResolution[0] = CPLAtof(pszGridSize);
poGeomField->m_adfSpatialIndexGridResolution = m_adfSpatialIndexGridResolution;
}
else
{
ComputeOptimalSpatialIndexGridResolution();
if( m_adfSpatialIndexGridResolution[0] == 0 )
return false;
}
}
auto poGeomConverter = std::unique_ptr<FileGDBOGRGeometryConverter>(
FileGDBOGRGeometryConverter::BuildConverter(poGeomField));
typedef std::pair<int64_t, int> ValueOIDPair;
std::vector<ValueOIDPair> asValues;
const double dfGridStep = m_adfSpatialIndexGridResolution.back();
const double dfShift = (1 << 29) / (dfGridStep / m_adfSpatialIndexGridResolution[0]);
double dfYMinClamped;
double dfYMaxClamped;
GetMinMaxProjYForSpatialIndex(dfYMinClamped, dfYMaxClamped);
const auto AddPointToIndex = [this, dfGridStep, dfShift, dfYMinClamped, dfYMaxClamped](
double dfX, double dfY,
std::vector<int64_t>& aSetValues)
{
dfY = std::min(std::max(dfY, dfYMinClamped), dfYMaxClamped);
const double dfXShifted = dfX / dfGridStep + dfShift;
const double dfYShifted = dfY / dfGridStep + dfShift;
// Each value must fit on 31 bit (sign included)
if( std::abs(dfXShifted) < (1 << 30) && std::abs(dfYShifted) < (1 << 30) )
{
const unsigned nX = static_cast<unsigned>(static_cast<int>(std::floor(dfXShifted)));
const unsigned nY = static_cast<unsigned>(static_cast<int>(std::floor(dfYShifted)));
const uint64_t nVal =
((static_cast<uint64_t>(m_adfSpatialIndexGridResolution.size() - 1)) << 62 ) |
((static_cast<uint64_t>(nX)) << 31) |
nY;
aSetValues.push_back(static_cast<int64_t>(nVal));
return true;
}
return false;
};
// Adapted from GDALdllImageLineAllTouched() of alg/llrasterize.cpp
const auto AddLineStringToIndex = [this, dfGridStep, dfShift, dfYMinClamped, dfYMaxClamped](
const OGRLineString* poLS, std::vector<int64_t>& aSetValues)
{
const int nNumPoints = poLS->getNumPoints();
if( nNumPoints < 2 )
return;
OGREnvelope sEnvelope;
poLS->getEnvelope(&sEnvelope);
double dfYShift = 0;
if( sEnvelope.MaxY > dfYMaxClamped )
dfYShift = dfYMaxClamped - sEnvelope.MaxY;
else if( sEnvelope.MinY < dfYMinClamped )
dfYShift = dfYMinClamped - sEnvelope.MinY;
for( int i = 0; i < nNumPoints - 1; i++ )
{
double dfX = poLS->getX(i) / dfGridStep + dfShift;
double dfY = (poLS->getY(i) + dfYShift) / dfGridStep + dfShift;
double dfXEnd = poLS->getX(i+1) / dfGridStep + dfShift;
double dfYEnd = (poLS->getY(i+1) + dfYShift) / dfGridStep + dfShift;
if( !(std::abs(dfX) < (1 << 30) && std::abs(dfY) < (1 << 30) &&
std::abs(dfXEnd) < (1 << 30) && std::abs(dfYEnd) < (1 << 30)) )
{
return;
}
// Swap if needed so we can proceed from left2right (X increasing)
if( dfX > dfXEnd )
{
std::swap(dfX, dfXEnd);
std::swap(dfY, dfYEnd );
}
// Special case for vertical lines.
if( floor(dfX) == floor(dfXEnd) || fabs(dfX - dfXEnd) < .01 )
{
if( dfYEnd < dfY )
{
std::swap(dfY, dfYEnd );
}
const int iX = static_cast<int>(floor(dfXEnd));
int iY = static_cast<int>(floor(dfY));
int iYEnd = static_cast<int>(floor(dfYEnd));
for( ; iY <= iYEnd; iY++ )
{
const unsigned nX = static_cast<unsigned>(iX);
const unsigned nY = static_cast<unsigned>(iY);
const uint64_t nVal =
((static_cast<uint64_t>(m_adfSpatialIndexGridResolution.size() - 1)) << 62 ) |
((static_cast<uint64_t>(nX)) << 31) |
nY;
aSetValues.push_back(static_cast<int64_t>(nVal));
}
continue; // Next segment.
}
// Special case for horizontal lines.
if( floor(dfY) == floor(dfYEnd) || fabs(dfY - dfYEnd) < .01 )
{
if( dfXEnd < dfX )
{
std::swap(dfX, dfXEnd);
}
int iX = static_cast<int>(floor(dfX));
const int iY = static_cast<int>(floor(dfY));
int iXEnd = static_cast<int>(floor(dfXEnd));
for( ; iX <= iXEnd; iX++ )
{
const unsigned nX = static_cast<unsigned>(iX);
const unsigned nY = static_cast<unsigned>(iY);
const uint64_t nVal =
((static_cast<uint64_t>(m_adfSpatialIndexGridResolution.size() - 1)) << 62 ) |
((static_cast<uint64_t>(nX)) << 31) |
nY;
aSetValues.push_back(static_cast<int64_t>(nVal));
}
continue; // Next segment.
}
/* -------------------------------------------------------------------- */
/* General case - left to right sloped. */
/* -------------------------------------------------------------------- */
// Recenter coordinates to avoid numeric precision issues
// particularly the tests against a small epsilon below that could
// lead to infinite looping otherwise.
const int nXShift = static_cast<int>(floor(dfX));
const int nYShift = static_cast<int>(floor(dfY));
dfX -= nXShift;
dfY -= nYShift;
dfXEnd -= nXShift;
dfYEnd -= nYShift;
const double dfSlope = (dfYEnd - dfY) / (dfXEnd - dfX);
// Step from pixel to pixel.
while( dfX < dfXEnd )
{
const int iX = static_cast<int>(floor(dfX));
const int iY = static_cast<int>(floor(dfY));
// Burn in the current point.
const unsigned nX = static_cast<unsigned>(iX + nXShift);
const unsigned nY = static_cast<unsigned>(iY + nYShift);
const uint64_t nVal =
((static_cast<uint64_t>(m_adfSpatialIndexGridResolution.size() - 1)) << 62 ) |
((static_cast<uint64_t>(nX)) << 31) |
nY;
aSetValues.push_back(static_cast<int64_t>(nVal));
double dfStepX = floor(dfX+1.0) - dfX;
double dfStepY = dfStepX * dfSlope;
// Step to right pixel without changing scanline?
if( static_cast<int>(floor(dfY + dfStepY)) == iY )
{
dfX += dfStepX;
dfY += dfStepY;
}
else if( dfSlope < 0 )
{
dfStepY = iY - dfY;
if( dfStepY > -0.000000001 )
dfStepY = -0.000000001;
dfStepX = dfStepY / dfSlope;
dfX += dfStepX;
dfY += dfStepY;
}
else
{
dfStepY = (iY + 1) - dfY;
if( dfStepY < 0.000000001 )
dfStepY = 0.000000001;
dfStepX = dfStepY / dfSlope;
dfX += dfStepX;
dfY += dfStepY;
}
} // Next step along segment.
}
};
// Adapted from GDALdllImageFilledPolygon() of alg/llrasterize.cpp
const auto AddPolygonToIndex = [this, dfGridStep, dfShift, dfYMinClamped, dfYMaxClamped, AddLineStringToIndex](
const OGRPolygon* poPoly, std::vector<int64_t>& aSetValues)
{
if( poPoly->IsEmpty() )
return;
// Burn contour of exterior ring, because burning the interior
// can often result in nothing
AddLineStringToIndex(poPoly->getExteriorRing(), aSetValues);
OGREnvelope sEnvelope;
poPoly->getEnvelope(&sEnvelope);
double dfYShift = 0;
if( sEnvelope.MaxY > dfYMaxClamped )
dfYShift = dfYMaxClamped - sEnvelope.MaxY;
else if( sEnvelope.MinY < dfYMinClamped )
dfYShift = dfYMinClamped - sEnvelope.MinY;
const int miny = static_cast<int>(floor((sEnvelope.MinY + dfYShift)/ dfGridStep + dfShift));
const int maxy = static_cast<int>(floor((sEnvelope.MaxY + dfYShift)/ dfGridStep + dfShift));
std::vector<double> intersections;
// Burn interior of polygon
for( int iY = miny; iY <= maxy; iY++ )
{
const double dy = iY + 0.5;
intersections.clear();
for( const auto* poRing: *poPoly )
{