void GDALWPrintRecords(GDALWConnection conn) { char * wkt; int i; OGRFeatureH feature; OGRGeometryH geometry; OGRFeatureDefnH featureDefn; featureDefn = OGR_L_GetLayerDefn(conn.layer); OGR_L_ResetReading(conn.layer); while( (feature = OGR_L_GetNextFeature(conn.layer)) != NULL ) { for(i = 0; i < OGR_FD_GetFieldCount(featureDefn); i++ ) { OGRFieldDefnH hFieldDefn = OGR_FD_GetFieldDefn( featureDefn, i ); if( OGR_Fld_GetType(hFieldDefn) == OFTInteger ) printf( "%d,", OGR_F_GetFieldAsInteger( feature, i ) ); else if( OGR_Fld_GetType(hFieldDefn) == OFTReal ) printf( "%.3f,", OGR_F_GetFieldAsDouble( feature, i) ); else printf( "%s,", OGR_F_GetFieldAsString( feature, i) ); } geometry = OGR_F_GetGeometryRef(feature); OGR_G_ExportToWkt(geometry, &wkt); printf("%s", wkt); printf("\n"); CPLFree(wkt); OGR_F_Destroy(feature); } }
void QgsOgrFeatureIterator::getFeatureAttribute( OGRFeatureH ogrFet, QgsFeature & f, int attindex ) { OGRFieldDefnH fldDef = OGR_F_GetFieldDefnRef( ogrFet, attindex ); if ( ! fldDef ) { QgsDebugMsg( "ogrFet->GetFieldDefnRef(attindex) returns NULL" ); return; } QVariant value; if ( OGR_F_IsFieldSet( ogrFet, attindex ) ) { switch ( P->mAttributeFields[attindex].type() ) { case QVariant::String: value = QVariant( P->mEncoding->toUnicode( OGR_F_GetFieldAsString( ogrFet, attindex ) ) ); break; case QVariant::Int: value = QVariant( OGR_F_GetFieldAsInteger( ogrFet, attindex ) ); break; case QVariant::Double: value = QVariant( OGR_F_GetFieldAsDouble( ogrFet, attindex ) ); break; //case QVariant::DateTime: value = QVariant(QDateTime::fromString(str)); break; default: assert( NULL && "unsupported field type" ); } } else { value = QVariant( QString::null ); } f.setAttribute( attindex, value ); }
void QgsOgrFeatureIterator::getFeatureAttribute( OGRFeatureH ogrFet, QgsFeature & f, int attindex ) { OGRFieldDefnH fldDef = OGR_F_GetFieldDefnRef( ogrFet, attindex ); if ( ! fldDef ) { QgsDebugMsg( "ogrFet->GetFieldDefnRef(attindex) returns NULL" ); return; } QVariant value; if ( OGR_F_IsFieldSet( ogrFet, attindex ) ) { switch ( mSource->mFields.at( attindex ).type() ) { case QVariant::String: value = QVariant( mSource->mEncoding->toUnicode( OGR_F_GetFieldAsString( ogrFet, attindex ) ) ); break; case QVariant::Int: value = QVariant( OGR_F_GetFieldAsInteger( ogrFet, attindex ) ); break; #if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 2000000 case QVariant::LongLong: value = QVariant( OGR_F_GetFieldAsInteger64( ogrFet, attindex ) ); break; #endif case QVariant::Double: value = QVariant( OGR_F_GetFieldAsDouble( ogrFet, attindex ) ); break; case QVariant::Date: case QVariant::DateTime: { int year, month, day, hour, minute, second, tzf; OGR_F_GetFieldAsDateTime( ogrFet, attindex, &year, &month, &day, &hour, &minute, &second, &tzf ); if ( mSource->mFields.at( attindex ).type() == QVariant::Date ) value = QDate( year, month, day ); else value = QDateTime( QDate( year, month, day ), QTime( hour, minute, second ) ); } break; default: assert( 0 && "unsupported field type" ); } } else { value = QVariant( QString::null ); } f.setAttribute( attindex, value ); }
/* {ok, DataSource} = lgeo_ogr:open("test/polygon.shp"), {ok, Layer} = lgeo_ogr:ds_get_layer(DataSource, 0), {ok, Feature} = lgeo_ogr:l_get_feature(Layer, 0), {ok, Fields} = lgeo_ogr:f_get_fields(Feature). {1,"first"} */ static ERL_NIF_TERM f_get_fields(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { EnvFeature_t **feature; ERL_NIF_TERM eterm; if (argc != 1) { return enif_make_badarg(env); } if(!enif_get_resource(env, argv[0], OGR_F_RESOURCE, (void**)&feature)) { return enif_make_badarg(env); } OGRFeatureDefnH feature_defn = OGR_F_GetDefnRef((**feature).obj); int count = OGR_FD_GetFieldCount(feature_defn); ERL_NIF_TERM *arr = (ERL_NIF_TERM *) malloc(sizeof(ERL_NIF_TERM)*count); int index; for(index=0; index<count; index++) { OGRFieldDefnH field_defn = OGR_FD_GetFieldDefn(feature_defn, index); if(OGR_Fld_GetType(field_defn) == OFTInteger) { arr[index] = enif_make_int(env, OGR_F_GetFieldAsInteger((**feature).obj, index)); } else if(OGR_Fld_GetType(field_defn) == OFTReal) { arr[index] = enif_make_double(env, OGR_F_GetFieldAsDouble((**feature).obj, index)); } else if(OGR_Fld_GetType(field_defn) == OFTString) { arr[index] = enif_make_string(env, OGR_F_GetFieldAsString((**feature).obj, index), ERL_NIF_LATIN1); } else { arr[index] = enif_make_string(env, OGR_F_GetFieldAsString((**feature).obj, index), ERL_NIF_LATIN1); } } eterm = enif_make_tuple_from_array(env, arr, index); free(arr); return enif_make_tuple2(env, enif_make_atom(env, "ok"), eterm); }
int readoutlets(char *outletsds,char *lyrname, int uselayername,int outletslyr,OGRSpatialReferenceH hSRSRaster,int *noutlets, double*& x, double*& y,int*& id) { // initializing datasoruce,layer,feature, geomtery, spatial reference OGRSFDriverH driver; OGRDataSourceH hDS1; OGRLayerH hLayer1; OGRFeatureDefnH hFDefn1; OGRFieldDefnH hFieldDefn1; OGRFeatureH hFeature1; OGRGeometryH geometry, line; OGRSpatialReferenceH hRSOutlet; // register all ogr driver related to OGR OGRRegisterAll(); // open data source hDS1 = OGROpen(outletsds, FALSE, NULL ); if( hDS1 == NULL ) { printf( "Error Opening OGR Data Source .\n" ); return 1; } //get layer from layer name if(uselayername==1) { hLayer1 = OGR_DS_GetLayerByName(hDS1,lyrname);} //get layerinfo from layer number else { hLayer1 = OGR_DS_GetLayer(hDS1,outletslyr);} // get layerinfo from layername if(hLayer1 == NULL)getlayerfail(hDS1,outletsds,outletslyr); OGRwkbGeometryType gtype; gtype=OGR_L_GetGeomType(hLayer1); // Test that the type is a point if(gtype != wkbPoint)getlayerfail(hDS1,outletsds,outletslyr); const char* RasterProjectionName; const char* sprs; const char* sprso; const char* OutletProjectionName; int pj_raster,pj_outlet; // Spatial reference of outlet hRSOutlet = OGR_L_GetSpatialRef(hLayer1); if(hSRSRaster!=NULL){ pj_raster=OSRIsProjected(hSRSRaster); // find if projected or not if(pj_raster==0) {sprs="GEOGCS";} else { sprs="PROJCS"; } RasterProjectionName = OSRGetAttrValue(hSRSRaster,sprs,0); // get projection name } if(hRSOutlet!=NULL){ pj_outlet=OSRIsProjected(hRSOutlet); if(pj_outlet==0) {sprso="GEOGCS";} else { sprso="PROJCS"; } OutletProjectionName = OSRGetAttrValue(hRSOutlet,sprso,0); } //Write warnings where projections may not match if(hRSOutlet!=NULL && hSRSRaster!=NULL){ if (pj_raster==pj_outlet){ int rc= strcmp(RasterProjectionName,OutletProjectionName); // compare string if(rc!=0){ printf( "Warning: Projection of Outlet feature and Raster data may be different.\n" ); printf("Projection of Raster datasource %s.\n",RasterProjectionName); printf("Projection of Outlet feature %s.\n",OutletProjectionName); } } else { printf( "Warning: Spatial References of Outlet feature and Raster data are different.\n" ); printf("Projection of Raster datasource %s.\n",RasterProjectionName); printf("Projection of Outlet feature %s.\n",OutletProjectionName); } } else if(hSRSRaster==NULL && hRSOutlet!=NULL) { printf( "Warning: Spatial Reference of Raster is missing.\n" ); printf("Projection of Outlet feature %s.\n",OutletProjectionName); } else if(hSRSRaster!=NULL && hRSOutlet==NULL) { printf( "Warning: Spatial Reference of Outlet feature is missing.\n" ); printf("Projection of Raster datasource %s.\n",RasterProjectionName); } else { printf( "Warning: Spatial References of Outlet feature and Raster data are missing.\n" ); } long countPts=0; // count number of feature countPts=OGR_L_GetFeatureCount(hLayer1,0); // get schema i.e geometry, properties (e.g. ID) hFDefn1 = OGR_L_GetLayerDefn(hLayer1); x = new double[countPts]; y = new double[countPts]; int iField; int nxy=0; id = new int[countPts]; // loop through each feature and get lat,lon and id information OGR_L_ResetReading(hLayer1); while( (hFeature1 = OGR_L_GetNextFeature(hLayer1)) != NULL ) { //hFeature1=OGR_L_GetFeature(hLayer1,j); // get feature info geometry = OGR_F_GetGeometryRef(hFeature1); // get geometry x[nxy] = OGR_G_GetX(geometry, 0); y[nxy] = OGR_G_GetY(geometry, 0); int idfld =OGR_F_GetFieldIndex(hFeature1,"id"); if (idfld >= 0) { hFieldDefn1 = OGR_FD_GetFieldDefn( hFDefn1,idfld); // get field definiton based on index if( OGR_Fld_GetType(hFieldDefn1) == OFTInteger ) { id[nxy] =OGR_F_GetFieldAsInteger( hFeature1, idfld );} // get id value } else { id[nxy]=1;// if there is no id field } nxy++; // count number of outlets point OGR_F_Destroy( hFeature1 ); // destroy feature } *noutlets=nxy; OGR_DS_Destroy( hDS1); // destroy data source return 0; }
/* What we need: specific condition, is walk in , tactic, distance elevation * minsteps, maxsteps, waterdrops, pump/roll, fwa id. */ int main( int argc, char *argv[] ) { GDALAllRegister(); OGRRegisterAll(); const char *pszInputfile = NULL; const char *pszOutputfile = NULL; const char *pszOutputFormat = "CSV"; char **papszCreateOptions = NULL; const char *pszDataPath = NULL; const char *pszFpuCode = NULL; int nLimit = 0; int bProgress = TRUE; double dfMaxX, dfMinX, dfMaxY, dfMinY; int bLimit = FALSE; double dfBuffer = 0.0; int i = 1; while( i < argc ) { if( EQUAL( argv[i], "-p" ) ) { bProgress = TRUE; } else if( EQUAL( argv[i], "-d" ) ) { pszDataPath = argv[++i]; } else if( EQUAL( argv[i], "-of" ) ) { pszOutputFormat = argv[++i]; } else if( EQUAL( argv[i], "-co" ) ) { papszCreateOptions = CSLAddString( papszCreateOptions, argv[++i] ); } else if( EQUAL( argv[i], "-sl" ) ) { dfMaxX = atof(argv[++i]); dfMinX = atof(argv[++i]); dfMaxY = atof(argv[++i]); dfMinY = atof(argv[++i]); bLimit = TRUE; } else if( EQUAL( argv[i], "-fpu" ) ) { pszFpuCode = argv[++i]; } else if( EQUAL( argv[i], "-b" ) ) { dfBuffer = atof( argv[++i] ); } else if( EQUAL( argv[i], "-l" ) ) { nLimit = atoi( argv[++i] ); } else if( EQUAL( argv[i], "-h" ) ) { Usage(); } else if( pszInputfile == NULL ) { pszInputfile = argv[i]; } else if( pszOutputfile == NULL ) { pszOutputfile = argv[i]; } else { Usage(); } i++; } if( pszInputfile == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "No input file provided\n"); Usage(); } if( pszOutputfile == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Invalid output selected, " "use database and table or output file\n" ); Usage(); } pszDataPath = CPLGetConfigOption( "OMFFR_DATA", NULL ); OGRDataSourceH hInputDS = OGROpen( pszInputfile, FALSE, NULL ); if( hInputDS == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Cannot open input file\n" ); Usage(); } int year, num, day; const char *dow, *disc_time; int bi; double ros; int fuel; const char *spec_cond; int slope, walkin; const char *tactic; double dist; int elev; double ltow; int minsteps = 250; int maxsteps = 10000; const char *sunrise, *sunset; int waterdrops, pumproll; char *abyFwa; const char *fwaid; double lon, lat; OGRLayerH hInputLayer; hInputLayer = OGR_DS_GetLayerByName( hInputDS, CPLGetBasename( pszInputfile ) ); OGRFeatureDefnH hInputFeatureDefn; OGRFeatureH hInputFeature; OGRGeometryH hGeometry; hInputFeatureDefn = OGR_L_GetLayerDefn( hInputLayer ); const char *pszTmpFilename =CPLFormFilename( pszDataPath, "irs/FWA", ".dat" ); std::vector<CFWA>fwas = LoadFwas( pszTmpFilename ); int nFeatures = OGR_L_GetFeatureCount( hInputLayer, TRUE ); FILE *fout = fopen( pszOutputfile, "w" ); //CFWA *fwa; Random random; char pszDb[8192]; sprintf( pszDb, "%s/omffr.sqlite", pszDataPath ); IRSDataAccess *poDA = IRSDataAccess::Create( 0, pszDb ); int rc; sqlite3 *db; rc = sqlite3_open_v2( pszDb, &db, SQLITE_OPEN_READONLY, NULL ); rc = sqlite3_enable_load_extension( db, 1 ); rc = sqlite3_load_extension( db, "/usr/local/lib/libspatialite.so", 0, NULL ); sqlite3_stmt *stmt; rc = sqlite3_prepare_v2( db, "SELECT * from fwa join fwa_bndry USING(fwa_gis_id) " \ "WHERE ST_Contains(fwa_bndry.geometry, MakePoint(?, ?, 4269))", -1, &stmt, NULL ); if(rc) { CPLError( CE_Failure, CPLE_AppDefined, "Could not open DB"); } GDALTermProgress( 0.0, NULL, NULL ); OGR_L_ResetReading( hInputLayer ); const char *pszFwaName; int nDone = 0; while( ( hInputFeature = OGR_L_GetNextFeature( hInputLayer ) ) != NULL ) { /* fwaid = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "fwa_name" ) ); abyFwa = CPLStrdup( fwaid ); LaunderFwaName( abyFwa ); fwa = FindFwa( fwas, abyFwa ); if( fwa == NULL ) { CPLError( CE_Warning, CPLE_FileIO, "Could not load fwa (%s)from file, missing\n", abyFwa ); continue; } */ /* Get fwa by point */ hGeometry = OGR_F_GetGeometryRef( hInputFeature ); /* Try to handle non-geometry types (csv) */ if( hGeometry != NULL ) { lat = OGR_G_GetY( hGeometry, 0 ); lon = OGR_G_GetX( hGeometry, 0 ); } else { lat = OGR_F_GetFieldAsDouble( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "Y") ); lon = OGR_F_GetFieldAsDouble( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "X") ); } std::string oFwaName = poDA->PointQuery( "fwa_bndry", "fwa_lndr_name", lon, lat ); rc = sqlite3_bind_double( stmt, 1, lon ); rc = sqlite3_bind_double( stmt, 2, lat ); //sqlite3_bind_text( stmt, 1, oFwaName.c_str(), -1, SQLITE_TRANSIENT); rc = sqlite3_step( stmt ); if( rc != SQLITE_ROW && rc != SQLITE_DONE ) { CPLError( CE_Warning, CPLE_FileIO, "Could not load fwa (%s)from file, missing\n", oFwaName.c_str() ); sqlite3_reset(stmt); continue; } int nFwaWalkIn, nFwaHead, nFwaTail, nFwaPara, nFwaAttackD; int nFwaWaterDrop, nFwaPumpRoll; nFwaWalkIn = sqlite3_column_int( stmt, 4 ); nFwaHead = sqlite3_column_int( stmt, 6 ); nFwaTail = sqlite3_column_int( stmt, 7 ); nFwaPara = sqlite3_column_int( stmt, 8 ); nFwaAttackD = sqlite3_column_int( stmt, 9 ); nFwaWaterDrop = sqlite3_column_int( stmt, 10 ); nFwaPumpRoll = sqlite3_column_int( stmt, 5 ); year = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "year" ) ); num = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "fire_num" ) ); day = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "day" ) ); dow = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "week_day" ) ); disc_time = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "disc_time" ) ); bi = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "bi" ) ); ros = OGR_F_GetFieldAsDouble( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "ros" ) ); fuel = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "fuel" ) ); spec_cond = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "spec_cond" ) ); slope = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "slope_perc" ) ); //if( random.rand3() * 100 > fwa->GetWalkInPct() ) if( random.rand3() * 100 > nFwaWalkIn ) walkin = 0; else walkin = 1; //if( fwa->GetHead() == 100 ) if( nFwaHead == 100 ) tactic = "HEAD\0"; //else if( fwa->GetTail() == 100 ) else if( nFwaTail == 100 ) tactic = "TAIL\0"; //else if( fwa->GetParallel() == 100 ) else if( nFwaTail == 100 ) tactic = "PARALLEL\0"; else { int r = (int)(random.rand3() * 100 ); int total = 0; if( r < nFwaHead ) tactic = "HEAD\0"; else if( r < nFwaTail + nFwaTail ) tactic = "TAIL\0"; else tactic = "PARALLEL\0"; } //dist = fwa->GetAttackDist(); dist = nFwaAttackD; elev = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "elev" ) ); ltow = OGR_F_GetFieldAsDouble( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "ratio" ) ); sunrise = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "sunrise" ) ); sunset = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "sunset" ) ); //if( fwa->GetWaterDrops() ) if( nFwaWaterDrop ) waterdrops = TRUE; else waterdrops = FALSE; //if( fwa->GetPumpnRoll() ) if( nFwaPumpRoll ) pumproll = TRUE; else pumproll = FALSE; fprintf( fout, "%d %d %d %s %s " "%d %lf %d %s %d " "%d %s %lf %d %lf " "%d %d %s %s %d " "%d %s %lf %lf\n", year, num, day, dow, disc_time, bi, ros, fuel, spec_cond, slope, walkin, tactic, dist, elev, ltow, minsteps, maxsteps, sunrise, sunset, waterdrops, pumproll, /* abyFwa */ oFwaName.c_str(), lat, lon ); sqlite3_reset(stmt); nDone++; GDALTermProgress( (float)nDone / (float)nFeatures, NULL, NULL ); } GDALTermProgress( 1.0, NULL, NULL ); fclose( fout ); OGR_DS_Destroy( hInputDS ); return 0; }
QVariant QgsOgrUtils::getOgrFeatureAttribute( OGRFeatureH ogrFet, const QgsFields& fields, int attIndex, QTextCodec* encoding , bool* ok ) { if ( !ogrFet || attIndex < 0 || attIndex >= fields.count() ) { if ( ok ) *ok = false; return QVariant(); } OGRFieldDefnH fldDef = OGR_F_GetFieldDefnRef( ogrFet, attIndex ); if ( ! fldDef ) { if ( ok ) *ok = false; QgsDebugMsg( "ogrFet->GetFieldDefnRef(attindex) returns NULL" ); return QVariant(); } QVariant value; if ( ok ) *ok = true; if ( OGR_F_IsFieldSet( ogrFet, attIndex ) ) { switch ( fields.at( attIndex ).type() ) { case QVariant::String: { if ( encoding ) value = QVariant( encoding->toUnicode( OGR_F_GetFieldAsString( ogrFet, attIndex ) ) ); else value = QVariant( QString::fromUtf8( OGR_F_GetFieldAsString( ogrFet, attIndex ) ) ); break; } case QVariant::Int: value = QVariant( OGR_F_GetFieldAsInteger( ogrFet, attIndex ) ); break; #if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 2000000 case QVariant::LongLong: value = QVariant( OGR_F_GetFieldAsInteger64( ogrFet, attIndex ) ); break; #endif case QVariant::Double: value = QVariant( OGR_F_GetFieldAsDouble( ogrFet, attIndex ) ); break; case QVariant::Date: case QVariant::DateTime: case QVariant::Time: { int year, month, day, hour, minute, second, tzf; OGR_F_GetFieldAsDateTime( ogrFet, attIndex, &year, &month, &day, &hour, &minute, &second, &tzf ); if ( fields.at( attIndex ).type() == QVariant::Date ) value = QDate( year, month, day ); else if ( fields.at( attIndex ).type() == QVariant::Time ) value = QTime( hour, minute, second ); else value = QDateTime( QDate( year, month, day ), QTime( hour, minute, second ) ); } break; default: Q_ASSERT_X( false, "QgsOgrUtils::getOgrFeatureAttribute", "unsupported field type" ); if ( ok ) *ok = false; } } else { value = QVariant( QString::null ); } return value; }
CPLErr RasterliteDataset::CreateOverviewLevel(int nOvrFactor, GDALProgressFunc pfnProgress, void * pProgressData) { double dfXResolution = padfXResolutions[0] * nOvrFactor; double dfYResolution = padfXResolutions[0] * nOvrFactor; CPLString osSQL; int nBlockXSize = 256; int nBlockYSize = 256; int nOvrXSize = nRasterXSize / nOvrFactor; int nOvrYSize = nRasterYSize / nOvrFactor; if (nOvrXSize == 0 || nOvrYSize == 0) return CE_Failure; int nXBlocks = (nOvrXSize + nBlockXSize - 1) / nBlockXSize; int nYBlocks = (nOvrYSize + nBlockYSize - 1) / nBlockYSize; const char* pszDriverName = "GTiff"; GDALDriverH hTileDriver = GDALGetDriverByName(pszDriverName); if (hTileDriver == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot load GDAL %s driver", pszDriverName); return CE_Failure; } GDALDriverH hMemDriver = GDALGetDriverByName("MEM"); if (hMemDriver == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot load GDAL MEM driver"); return CE_Failure; } GDALDataType eDataType = GetRasterBand(1)->GetRasterDataType(); int nDataTypeSize = GDALGetDataTypeSize(eDataType) / 8; GByte* pabyMEMDSBuffer = (GByte*)VSIMalloc3(nBlockXSize, nBlockYSize, nBands * nDataTypeSize); if (pabyMEMDSBuffer == NULL) { return CE_Failure; } char** papszTileDriverOptions = NULL; CPLString osTempFileName; osTempFileName.Printf("/vsimem/%p", hDS); int nTileId = 0; int nBlocks = 0; int nTotalBlocks = nXBlocks * nYBlocks; CPLString osRasterLayer; osRasterLayer.Printf("%s_rasters", osTableName.c_str()); CPLString osMetatadataLayer; osMetatadataLayer.Printf("%s_metadata", osTableName.c_str()); OGRLayerH hRasterLayer = OGR_DS_GetLayerByName(hDS, osRasterLayer.c_str()); OGRLayerH hMetadataLayer = OGR_DS_GetLayerByName(hDS, osMetatadataLayer.c_str()); CPLString osSourceName = "unknown"; osSQL.Printf("SELECT source_name FROM \"%s\" WHERE " "pixel_x_size >= %.15f AND pixel_x_size <= %.15f AND " "pixel_y_size >= %.15f AND pixel_y_size <= %.15f LIMIT 1", osMetatadataLayer.c_str(), padfXResolutions[0] - 1e-15, padfXResolutions[0] + 1e-15, padfYResolutions[0] - 1e-15, padfYResolutions[0] + 1e-15); OGRLayerH hSQLLyr = OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); if (hSQLLyr) { OGRFeatureH hFeat = OGR_L_GetNextFeature(hSQLLyr); if (hFeat) { const char* pszVal = OGR_F_GetFieldAsString(hFeat, 0); if (pszVal) osSourceName = pszVal; OGR_F_Destroy(hFeat); } OGR_DS_ReleaseResultSet(hDS, hSQLLyr); } /* -------------------------------------------------------------------- */ /* Compute up to which existing overview level we can use for */ /* computing the requested overview */ /* -------------------------------------------------------------------- */ int iLev; nLimitOvrCount = 0; for(iLev=1;iLev<nResolutions;iLev++) { if (!(padfXResolutions[iLev] < dfXResolution - 1e-10 && padfYResolutions[iLev] < dfYResolution - 1e-10)) { break; } nLimitOvrCount++; } /* -------------------------------------------------------------------- */ /* Iterate over blocks to add data into raster and metadata tables */ /* -------------------------------------------------------------------- */ OGR_DS_ExecuteSQL(hDS, "BEGIN", NULL, NULL); CPLErr eErr = CE_None; int nBlockXOff, nBlockYOff; for(nBlockYOff=0;eErr == CE_None && nBlockYOff<nYBlocks;nBlockYOff++) { for(nBlockXOff=0;eErr == CE_None && nBlockXOff<nXBlocks;nBlockXOff++) { /* -------------------------------------------------------------------- */ /* Create in-memory tile */ /* -------------------------------------------------------------------- */ int nReqXSize = nBlockXSize, nReqYSize = nBlockYSize; if ((nBlockXOff+1) * nBlockXSize > nOvrXSize) nReqXSize = nOvrXSize - nBlockXOff * nBlockXSize; if ((nBlockYOff+1) * nBlockYSize > nOvrYSize) nReqYSize = nOvrYSize - nBlockYOff * nBlockYSize; eErr = RasterIO(GF_Read, nBlockXOff * nBlockXSize * nOvrFactor, nBlockYOff * nBlockYSize * nOvrFactor, nReqXSize * nOvrFactor, nReqYSize * nOvrFactor, pabyMEMDSBuffer, nReqXSize, nReqYSize, eDataType, nBands, NULL, 0, 0, 0); if (eErr != CE_None) { break; } GDALDatasetH hMemDS = GDALCreate(hMemDriver, "MEM:::", nReqXSize, nReqYSize, 0, eDataType, NULL); if (hMemDS == NULL) { eErr = CE_Failure; break; } int iBand; for(iBand = 0; iBand < nBands; iBand ++) { char** papszOptions = NULL; char szTmp[64]; memset(szTmp, 0, sizeof(szTmp)); CPLPrintPointer(szTmp, pabyMEMDSBuffer + iBand * nDataTypeSize * nReqXSize * nReqYSize, sizeof(szTmp)); papszOptions = CSLSetNameValue(papszOptions, "DATAPOINTER", szTmp); GDALAddBand(hMemDS, eDataType, papszOptions); CSLDestroy(papszOptions); } GDALDatasetH hOutDS = GDALCreateCopy(hTileDriver, osTempFileName.c_str(), hMemDS, FALSE, papszTileDriverOptions, NULL, NULL); GDALClose(hMemDS); if (hOutDS) GDALClose(hOutDS); else { eErr = CE_Failure; break; } /* -------------------------------------------------------------------- */ /* Insert new entry into raster table */ /* -------------------------------------------------------------------- */ vsi_l_offset nDataLength; GByte *pabyData = VSIGetMemFileBuffer( osTempFileName.c_str(), &nDataLength, FALSE); OGRFeatureH hFeat = OGR_F_Create( OGR_L_GetLayerDefn(hRasterLayer) ); OGR_F_SetFieldBinary(hFeat, 0, (int)nDataLength, pabyData); OGR_L_CreateFeature(hRasterLayer, hFeat); /* Query raster ID to set it as the ID of the associated metadata */ int nRasterID = (int)OGR_F_GetFID(hFeat); OGR_F_Destroy(hFeat); VSIUnlink(osTempFileName.c_str()); /* -------------------------------------------------------------------- */ /* Insert new entry into metadata table */ /* -------------------------------------------------------------------- */ hFeat = OGR_F_Create( OGR_L_GetLayerDefn(hMetadataLayer) ); OGR_F_SetFID(hFeat, nRasterID); OGR_F_SetFieldString(hFeat, 0, osSourceName); OGR_F_SetFieldInteger(hFeat, 1, nTileId ++); OGR_F_SetFieldInteger(hFeat, 2, nReqXSize); OGR_F_SetFieldInteger(hFeat, 3, nReqYSize); OGR_F_SetFieldDouble(hFeat, 4, dfXResolution); OGR_F_SetFieldDouble(hFeat, 5, dfYResolution); double minx, maxx, maxy, miny; minx = adfGeoTransform[0] + (nBlockXSize * nBlockXOff) * dfXResolution; maxx = adfGeoTransform[0] + (nBlockXSize * nBlockXOff + nReqXSize) * dfXResolution; maxy = adfGeoTransform[3] + (nBlockYSize * nBlockYOff) * (-dfYResolution); miny = adfGeoTransform[3] + (nBlockYSize * nBlockYOff + nReqYSize) * (-dfYResolution); OGRGeometryH hRectangle = OGR_G_CreateGeometry(wkbPolygon); OGRGeometryH hLinearRing = OGR_G_CreateGeometry(wkbLinearRing); OGR_G_AddPoint_2D(hLinearRing, minx, miny); OGR_G_AddPoint_2D(hLinearRing, minx, maxy); OGR_G_AddPoint_2D(hLinearRing, maxx, maxy); OGR_G_AddPoint_2D(hLinearRing, maxx, miny); OGR_G_AddPoint_2D(hLinearRing, minx, miny); OGR_G_AddGeometryDirectly(hRectangle, hLinearRing); OGR_F_SetGeometryDirectly(hFeat, hRectangle); OGR_L_CreateFeature(hMetadataLayer, hFeat); OGR_F_Destroy(hFeat); nBlocks++; if (pfnProgress && !pfnProgress(1.0 * nBlocks / nTotalBlocks, NULL, pProgressData)) eErr = CE_Failure; } } nLimitOvrCount = -1; if (eErr == CE_None) OGR_DS_ExecuteSQL(hDS, "COMMIT", NULL, NULL); else OGR_DS_ExecuteSQL(hDS, "ROLLBACK", NULL, NULL); VSIFree(pabyMEMDSBuffer); /* -------------------------------------------------------------------- */ /* Update raster_pyramids table */ /* -------------------------------------------------------------------- */ if (eErr == CE_None) { OGRLayerH hRasterPyramidsLyr = OGR_DS_GetLayerByName(hDS, "raster_pyramids"); if (hRasterPyramidsLyr == NULL) { osSQL.Printf ("CREATE TABLE raster_pyramids (" "table_prefix TEXT NOT NULL," "pixel_x_size DOUBLE NOT NULL," "pixel_y_size DOUBLE NOT NULL," "tile_count INTEGER NOT NULL)"); OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); /* Re-open the DB to take into account the new tables*/ OGRReleaseDataSource(hDS); CPLString osOldVal = CPLGetConfigOption("SQLITE_LIST_ALL_TABLES", "FALSE"); CPLSetThreadLocalConfigOption("SQLITE_LIST_ALL_TABLES", "TRUE"); hDS = OGROpen(osFileName.c_str(), TRUE, NULL); CPLSetThreadLocalConfigOption("SQLITE_LIST_ALL_TABLES", osOldVal.c_str()); } /* Insert base resolution into raster_pyramids if not already done */ int bHasBaseResolution = FALSE; osSQL.Printf("SELECT * FROM raster_pyramids WHERE " "table_prefix = '%s' AND pixel_x_size >= %.15f AND pixel_x_size <= %.15f AND " "pixel_y_size >= %.15f AND pixel_y_size <= %.15f", osTableName.c_str(), padfXResolutions[0] - 1e-15, padfXResolutions[0] + 1e-15, padfYResolutions[0] - 1e-15, padfYResolutions[0] + 1e-15); hSQLLyr = OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); if (hSQLLyr) { OGRFeatureH hFeat = OGR_L_GetNextFeature(hSQLLyr); if (hFeat) { bHasBaseResolution = TRUE; OGR_F_Destroy(hFeat); } OGR_DS_ReleaseResultSet(hDS, hSQLLyr); } if (!bHasBaseResolution) { osSQL.Printf("SELECT COUNT(*) FROM \"%s\" WHERE " "pixel_x_size >= %.15f AND pixel_x_size <= %.15f AND " "pixel_y_size >= %.15f AND pixel_y_size <= %.15f", osMetatadataLayer.c_str(), padfXResolutions[0] - 1e-15, padfXResolutions[0] + 1e-15, padfYResolutions[0] - 1e-15, padfYResolutions[0] + 1e-15); int nBlocksMainRes = 0; hSQLLyr = OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); if (hSQLLyr) { OGRFeatureH hFeat = OGR_L_GetNextFeature(hSQLLyr); if (hFeat) { nBlocksMainRes = OGR_F_GetFieldAsInteger(hFeat, 0); OGR_F_Destroy(hFeat); } OGR_DS_ReleaseResultSet(hDS, hSQLLyr); } osSQL.Printf("INSERT INTO raster_pyramids " "( table_prefix, pixel_x_size, pixel_y_size, tile_count ) " "VALUES ( '%s', %.18f, %.18f, %d )", osTableName.c_str(), padfXResolutions[0], padfYResolutions[0], nBlocksMainRes); OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); } osSQL.Printf("INSERT INTO raster_pyramids " "( table_prefix, pixel_x_size, pixel_y_size, tile_count ) " "VALUES ( '%s', %.18f, %.18f, %d )", osTableName.c_str(), dfXResolution, dfYResolution, nTotalBlocks); OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); } return eErr; }
void AttributeFilter::UpdateGEOSBuffer(PointBuffer& buffer, AttributeInfo& info) { QuadIndex idx(buffer); idx.build(); if (!info.lyr) // wake up the layer { if (info.layer.size()) info.lyr = OGR_DS_GetLayerByName(info.ds.get(), info.layer.c_str()); else if (info.query.size()) { info.lyr = OGR_DS_ExecuteSQL(info.ds.get(), info.query.c_str(), 0, 0); } else info.lyr = OGR_DS_GetLayer(info.ds.get(), 0); if (!info.lyr) { std::ostringstream oss; oss << "Unable to select layer '" << info.layer << "'"; throw pdal_error(oss.str()); } } OGRFeaturePtr feature = OGRFeaturePtr(OGR_L_GetNextFeature(info.lyr), OGRFeatureDeleter()); int field_index(1); // default to first column if nothing was set if (info.column.size()) { field_index = OGR_F_GetFieldIndex(feature.get(), info.column.c_str()); if (field_index == -1) { std::ostringstream oss; oss << "No column name '" << info.column << "' was found."; throw pdal_error(oss.str()); } } while(feature) { OGRGeometryH geom = OGR_F_GetGeometryRef(feature.get()); OGRwkbGeometryType t = OGR_G_GetGeometryType(geom); int f_count = OGR_F_GetFieldCount (feature.get()); if (!(t == wkbPolygon || t == wkbMultiPolygon || t == wkbPolygon25D || t == wkbMultiPolygon25D)) { std::ostringstream oss; oss << "Geometry is not Polygon or MultiPolygon!"; throw pdal::pdal_error(oss.str()); } OGRGeometry* ogr_g = (OGRGeometry*) geom; GEOSGeometry* geos_g (0); if (!m_geosEnvironment) { #if (GDAL_VERSION_MINOR < 11) && (GDAL_VERSION_MAJOR == 1) geos_g = ogr_g->exportToGEOS(); #else m_geosEnvironment = ogr_g->createGEOSContext(); geos_g = ogr_g->exportToGEOS(m_geosEnvironment); #endif } GEOSPreparedGeometry const* geos_pg = GEOSPrepare_r(m_geosEnvironment, geos_g); if (!geos_pg) throw pdal_error("unable to prepare geometry for index-accelerated intersection"); // Compute a total bounds for the geometry. Query the QuadTree to // find out the points that are inside the bbox. Then test each // point in the bbox against the prepared geometry. BOX3D box = computeBounds(m_geosEnvironment, geos_g); std::vector<std::size_t> ids = idx.getPoints(box); for (const auto& i : ids) { double x = buffer.getFieldAs<double>(Dimension::Id::X, i); double y = buffer.getFieldAs<double>(Dimension::Id::Y, i); double z = buffer.getFieldAs<double>(Dimension::Id::Z, i); GEOSGeometry* p = createGEOSPoint(m_geosEnvironment, x, y ,z); if (static_cast<bool>(GEOSPreparedContains_r(m_geosEnvironment, geos_pg, p))) { // We're in the poly, write the attribute value int32_t v = OGR_F_GetFieldAsInteger(feature.get(), field_index); buffer.setField(info.dim, i, v); // log()->get(LogLevel::Debug) << "Setting value: " << v << std::endl; } GEOSGeom_destroy_r(m_geosEnvironment, p); } feature = OGRFeaturePtr(OGR_L_GetNextFeature(info.lyr), OGRFeatureDeleter()); } }
GDALDataset * RasterliteCreateCopy( const char * pszFilename, GDALDataset *poSrcDS, int bStrict, char ** papszOptions, GDALProgressFunc pfnProgress, void * pProgressData ) { int nBands = poSrcDS->GetRasterCount(); if (nBands == 0) { CPLError(CE_Failure, CPLE_NotSupported, "nBands == 0"); return NULL; } const char* pszDriverName = CSLFetchNameValueDef(papszOptions, "DRIVER", "GTiff"); GDALDriverH hTileDriver = GDALGetDriverByName(pszDriverName); if ( hTileDriver == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot load GDAL %s driver", pszDriverName); return NULL; } GDALDriverH hMemDriver = GDALGetDriverByName("MEM"); if (hMemDriver == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot load GDAL MEM driver"); return NULL; } int nXSize = GDALGetRasterXSize(poSrcDS); int nYSize = GDALGetRasterYSize(poSrcDS); double adfGeoTransform[6]; if (poSrcDS->GetGeoTransform(adfGeoTransform) != CE_None) { adfGeoTransform[0] = 0; adfGeoTransform[1] = 1; adfGeoTransform[2] = 0; adfGeoTransform[3] = 0; adfGeoTransform[4] = 0; adfGeoTransform[5] = -1; } else if (adfGeoTransform[2] != 0.0 || adfGeoTransform[4] != 0.0) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot use geotransform with rotational terms"); return NULL; } int bTiled = CSLTestBoolean(CSLFetchNameValueDef(papszOptions, "TILED", "YES")); int nBlockXSize, nBlockYSize; if (bTiled) { nBlockXSize = atoi(CSLFetchNameValueDef(papszOptions, "BLOCKXSIZE", "256")); nBlockYSize = atoi(CSLFetchNameValueDef(papszOptions, "BLOCKYSIZE", "256")); if (nBlockXSize < 64) nBlockXSize = 64; else if (nBlockXSize > 4096) nBlockXSize = 4096; if (nBlockYSize < 64) nBlockYSize = 64; else if (nBlockYSize > 4096) nBlockYSize = 4096; } else { nBlockXSize = nXSize; nBlockYSize = nYSize; } /* -------------------------------------------------------------------- */ /* Analyze arguments */ /* -------------------------------------------------------------------- */ CPLString osDBName; CPLString osTableName; VSIStatBuf sBuf; int bExists; /* Skip optionnal RASTERLITE: prefix */ const char* pszFilenameWithoutPrefix = pszFilename; if (EQUALN(pszFilename, "RASTERLITE:", 11)) pszFilenameWithoutPrefix += 11; char** papszTokens = CSLTokenizeStringComplex( pszFilenameWithoutPrefix, ", ", FALSE, FALSE ); int nTokens = CSLCount(papszTokens); if (nTokens == 0) { osDBName = pszFilenameWithoutPrefix; osTableName = CPLGetBasename(pszFilenameWithoutPrefix); } else { osDBName = papszTokens[0]; int i; for(i=1;i<nTokens;i++) { if (EQUALN(papszTokens[i], "table=", 6)) osTableName = papszTokens[i] + 6; else { CPLError(CE_Warning, CPLE_AppDefined, "Invalid option : %s", papszTokens[i]); } } } CSLDestroy(papszTokens); papszTokens = NULL; bExists = (VSIStat(osDBName.c_str(), &sBuf) == 0); if (osTableName.size() == 0) { if (bExists) { CPLError(CE_Failure, CPLE_AppDefined, "Database already exists. Explicit table name must be specified"); return NULL; } osTableName = CPLGetBasename(osDBName.c_str()); } CPLString osRasterLayer; osRasterLayer.Printf("%s_rasters", osTableName.c_str()); CPLString osMetatadataLayer; osMetatadataLayer.Printf("%s_metadata", osTableName.c_str()); /* -------------------------------------------------------------------- */ /* Create or open the SQLite DB */ /* -------------------------------------------------------------------- */ if (OGRGetDriverCount() == 0) OGRRegisterAll(); OGRSFDriverH hSQLiteDriver = OGRGetDriverByName("SQLite"); if (hSQLiteDriver == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot load OGR SQLite driver"); return NULL; } OGRDataSourceH hDS; CPLString osOldVal = CPLGetConfigOption("SQLITE_LIST_ALL_TABLES", "FALSE"); CPLSetConfigOption("SQLITE_LIST_ALL_TABLES", "TRUE"); if (!bExists) { char** papszOGROptions = CSLAddString(NULL, "SPATIALITE=YES"); hDS = OGR_Dr_CreateDataSource(hSQLiteDriver, osDBName.c_str(), papszOGROptions); CSLDestroy(papszOGROptions); } else { hDS = OGROpen(osDBName.c_str(), TRUE, NULL); } CPLSetConfigOption("SQLITE_LIST_ALL_TABLES", osOldVal.c_str()); if (hDS == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot load or create SQLite database"); return NULL; } CPLString osSQL; /* -------------------------------------------------------------------- */ /* Get the SRID for the SRS */ /* -------------------------------------------------------------------- */ int nSRSId = RasterliteInsertSRID(hDS, poSrcDS->GetProjectionRef()); /* -------------------------------------------------------------------- */ /* Create or wipe existing tables */ /* -------------------------------------------------------------------- */ int bWipeExistingData = CSLTestBoolean(CSLFetchNameValueDef(papszOptions, "WIPE", "NO")); hDS = RasterliteCreateTables(hDS, osTableName.c_str(), nSRSId, bWipeExistingData); if (hDS == NULL) return NULL; OGRLayerH hRasterLayer = OGR_DS_GetLayerByName(hDS, osRasterLayer.c_str()); OGRLayerH hMetadataLayer = OGR_DS_GetLayerByName(hDS, osMetatadataLayer.c_str()); if (hRasterLayer == NULL || hMetadataLayer == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find metadata and/or raster tables"); OGRReleaseDataSource(hDS); return NULL; } /* -------------------------------------------------------------------- */ /* Check if there is overlapping data and warn the user */ /* -------------------------------------------------------------------- */ double minx = adfGeoTransform[0]; double maxx = adfGeoTransform[0] + nXSize * adfGeoTransform[1]; double maxy = adfGeoTransform[3]; double miny = adfGeoTransform[3] + nYSize * adfGeoTransform[5]; osSQL.Printf("SELECT COUNT(geometry) FROM \"%s\" " "WHERE rowid IN " "(SELECT pkid FROM \"idx_%s_metadata_geometry\" " "WHERE xmin < %.15f AND xmax > %.15f " "AND ymin < %.15f AND ymax > %.15f) " "AND pixel_x_size >= %.15f AND pixel_x_size <= %.15f AND " "pixel_y_size >= %.15f AND pixel_y_size <= %.15f", osMetatadataLayer.c_str(), osTableName.c_str(), maxx, minx, maxy, miny, adfGeoTransform[1] - 1e-15, adfGeoTransform[1] + 1e-15, - adfGeoTransform[5] - 1e-15, - adfGeoTransform[5] + 1e-15); int nOverlappingGeoms = 0; OGRLayerH hCountLyr = OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); if (hCountLyr) { OGRFeatureH hFeat = OGR_L_GetNextFeature(hCountLyr); if (hFeat) { nOverlappingGeoms = OGR_F_GetFieldAsInteger(hFeat, 0); OGR_F_Destroy(hFeat); } OGR_DS_ReleaseResultSet(hDS, hCountLyr); } if (nOverlappingGeoms != 0) { CPLError(CE_Warning, CPLE_AppDefined, "Raster tiles already exist in the %s table within " "the extent of the data to be inserted in", osTableName.c_str()); } /* -------------------------------------------------------------------- */ /* Iterate over blocks to add data into raster and metadata tables */ /* -------------------------------------------------------------------- */ int nXBlocks = (nXSize + nBlockXSize - 1) / nBlockXSize; int nYBlocks = (nYSize + nBlockYSize - 1) / nBlockYSize; GDALDataType eDataType = poSrcDS->GetRasterBand(1)->GetRasterDataType(); int nDataTypeSize = GDALGetDataTypeSize(eDataType) / 8; GByte* pabyMEMDSBuffer = (GByte*)VSIMalloc3(nBlockXSize, nBlockYSize, nBands * nDataTypeSize); if (pabyMEMDSBuffer == NULL) { OGRReleaseDataSource(hDS); return NULL; } CPLString osTempFileName; osTempFileName.Printf("/vsimem/%p", hDS); int nTileId = 0; int nBlocks = 0; int nTotalBlocks = nXBlocks * nYBlocks; char** papszTileDriverOptions = RasterliteGetTileDriverOptions(papszOptions); OGR_DS_ExecuteSQL(hDS, "BEGIN", NULL, NULL); CPLErr eErr = CE_None; int nBlockXOff, nBlockYOff; for(nBlockYOff=0;eErr == CE_None && nBlockYOff<nYBlocks;nBlockYOff++) { for(nBlockXOff=0;eErr == CE_None && nBlockXOff<nXBlocks;nBlockXOff++) { /* -------------------------------------------------------------------- */ /* Create in-memory tile */ /* -------------------------------------------------------------------- */ int nReqXSize = nBlockXSize, nReqYSize = nBlockYSize; if ((nBlockXOff+1) * nBlockXSize > nXSize) nReqXSize = nXSize - nBlockXOff * nBlockXSize; if ((nBlockYOff+1) * nBlockYSize > nYSize) nReqYSize = nYSize - nBlockYOff * nBlockYSize; eErr = poSrcDS->RasterIO(GF_Read, nBlockXOff * nBlockXSize, nBlockYOff * nBlockYSize, nReqXSize, nReqYSize, pabyMEMDSBuffer, nReqXSize, nReqYSize, eDataType, nBands, NULL, 0, 0, 0); if (eErr != CE_None) { break; } GDALDatasetH hMemDS = GDALCreate(hMemDriver, "MEM:::", nReqXSize, nReqYSize, 0, eDataType, NULL); if (hMemDS == NULL) { eErr = CE_Failure; break; } int iBand; for(iBand = 0; iBand < nBands; iBand ++) { char** papszMEMDSOptions = NULL; char szTmp[64]; memset(szTmp, 0, sizeof(szTmp)); CPLPrintPointer(szTmp, pabyMEMDSBuffer + iBand * nDataTypeSize * nReqXSize * nReqYSize, sizeof(szTmp)); papszMEMDSOptions = CSLSetNameValue(papszMEMDSOptions, "DATAPOINTER", szTmp); GDALAddBand(hMemDS, eDataType, papszMEMDSOptions); CSLDestroy(papszMEMDSOptions); } GDALDatasetH hOutDS = GDALCreateCopy(hTileDriver, osTempFileName.c_str(), hMemDS, FALSE, papszTileDriverOptions, NULL, NULL); GDALClose(hMemDS); if (hOutDS) GDALClose(hOutDS); else { eErr = CE_Failure; break; } /* -------------------------------------------------------------------- */ /* Insert new entry into raster table */ /* -------------------------------------------------------------------- */ vsi_l_offset nDataLength; GByte *pabyData = VSIGetMemFileBuffer( osTempFileName.c_str(), &nDataLength, FALSE); OGRFeatureH hFeat = OGR_F_Create( OGR_L_GetLayerDefn(hRasterLayer) ); OGR_F_SetFieldBinary(hFeat, 0, (int)nDataLength, pabyData); OGR_L_CreateFeature(hRasterLayer, hFeat); /* Query raster ID to set it as the ID of the associated metadata */ int nRasterID = (int)OGR_F_GetFID(hFeat); OGR_F_Destroy(hFeat); VSIUnlink(osTempFileName.c_str()); /* -------------------------------------------------------------------- */ /* Insert new entry into metadata table */ /* -------------------------------------------------------------------- */ hFeat = OGR_F_Create( OGR_L_GetLayerDefn(hMetadataLayer) ); OGR_F_SetFID(hFeat, nRasterID); OGR_F_SetFieldString(hFeat, 0, GDALGetDescription(poSrcDS)); OGR_F_SetFieldInteger(hFeat, 1, nTileId ++); OGR_F_SetFieldInteger(hFeat, 2, nReqXSize); OGR_F_SetFieldInteger(hFeat, 3, nReqYSize); OGR_F_SetFieldDouble(hFeat, 4, adfGeoTransform[1]); OGR_F_SetFieldDouble(hFeat, 5, -adfGeoTransform[5]); minx = adfGeoTransform[0] + (nBlockXSize * nBlockXOff) * adfGeoTransform[1]; maxx = adfGeoTransform[0] + (nBlockXSize * nBlockXOff + nReqXSize) * adfGeoTransform[1]; maxy = adfGeoTransform[3] + (nBlockYSize * nBlockYOff) * adfGeoTransform[5]; miny = adfGeoTransform[3] + (nBlockYSize * nBlockYOff + nReqYSize) * adfGeoTransform[5]; OGRGeometryH hRectangle = OGR_G_CreateGeometry(wkbPolygon); OGRGeometryH hLinearRing = OGR_G_CreateGeometry(wkbLinearRing); OGR_G_AddPoint_2D(hLinearRing, minx, miny); OGR_G_AddPoint_2D(hLinearRing, minx, maxy); OGR_G_AddPoint_2D(hLinearRing, maxx, maxy); OGR_G_AddPoint_2D(hLinearRing, maxx, miny); OGR_G_AddPoint_2D(hLinearRing, minx, miny); OGR_G_AddGeometryDirectly(hRectangle, hLinearRing); OGR_F_SetGeometryDirectly(hFeat, hRectangle); OGR_L_CreateFeature(hMetadataLayer, hFeat); OGR_F_Destroy(hFeat); nBlocks++; if (pfnProgress && !pfnProgress(1.0 * nBlocks / nTotalBlocks, NULL, pProgressData)) eErr = CE_Failure; } } if (eErr == CE_None) OGR_DS_ExecuteSQL(hDS, "COMMIT", NULL, NULL); else OGR_DS_ExecuteSQL(hDS, "ROLLBACK", NULL, NULL); CSLDestroy(papszTileDriverOptions); VSIFree(pabyMEMDSBuffer); OGRReleaseDataSource(hDS); return (GDALDataset*) GDALOpen(pszFilename, GA_Update); }
OGRDataSourceH RasterliteCreateTables(OGRDataSourceH hDS, const char* pszTableName, int nSRSId, int bWipeExistingData) { CPLString osSQL; CPLString osOldVal = CPLGetConfigOption("SQLITE_LIST_ALL_TABLES", "FALSE"); CPLString osDBName = OGR_DS_GetName(hDS); CPLString osRasterLayer; osRasterLayer.Printf("%s_rasters", pszTableName); CPLString osMetatadataLayer; osMetatadataLayer.Printf("%s_metadata", pszTableName); OGRLayerH hLyr; if (OGR_DS_GetLayerByName(hDS, osRasterLayer.c_str()) == NULL) { /* -------------------------------------------------------------------- */ /* The table don't exist. Create them */ /* -------------------------------------------------------------------- */ /* Create _rasters table */ osSQL.Printf ("CREATE TABLE \"%s\" (" "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," "raster BLOB NOT NULL)", osRasterLayer.c_str()); OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); /* Create _metadata table */ osSQL.Printf ("CREATE TABLE \"%s\" (" "id INTEGER NOT NULL PRIMARY KEY," "source_name TEXT NOT NULL," "tile_id INTEGER NOT NULL," "width INTEGER NOT NULL," "height INTEGER NOT NULL," "pixel_x_size DOUBLE NOT NULL," "pixel_y_size DOUBLE NOT NULL)", osMetatadataLayer.c_str()); OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); /* Add geometry column to _metadata table */ osSQL.Printf("SELECT AddGeometryColumn('%s', 'geometry', %d, 'POLYGON', 2)", osMetatadataLayer.c_str(), nSRSId); if ((hLyr = OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL)) == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Check that the OGR SQLite driver has Spatialite support"); OGRReleaseDataSource(hDS); return NULL; } OGR_DS_ReleaseResultSet(hDS, hLyr); /* Create spatial index on _metadata table */ osSQL.Printf("SELECT CreateSpatialIndex('%s', 'geometry')", osMetatadataLayer.c_str()); if ((hLyr = OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL)) == NULL) { OGRReleaseDataSource(hDS); return NULL; } OGR_DS_ReleaseResultSet(hDS, hLyr); /* Re-open the DB to take into account the new tables*/ OGRReleaseDataSource(hDS); CPLSetConfigOption("SQLITE_LIST_ALL_TABLES", "TRUE"); hDS = OGROpen(osDBName.c_str(), TRUE, NULL); CPLSetConfigOption("SQLITE_LIST_ALL_TABLES", osOldVal.c_str()); } else { /* Check that the existing SRS is consistent with the one of the new */ /* data to be inserted */ osSQL.Printf("SELECT srid FROM geometry_columns WHERE f_table_name = '%s'", osMetatadataLayer.c_str()); hLyr = OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); if (hLyr) { int nExistingSRID = -1; OGRFeatureH hFeat = OGR_L_GetNextFeature(hLyr); if (hFeat) { nExistingSRID = OGR_F_GetFieldAsInteger(hFeat, 0); OGR_F_Destroy(hFeat); } OGR_DS_ReleaseResultSet(hDS, hLyr); if (nExistingSRID != nSRSId) { if (bWipeExistingData) { osSQL.Printf("UPDATE geometry_columns SET srid = %d " "WHERE f_table_name = \"%s\"", nSRSId, osMetatadataLayer.c_str()); OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); /* Re-open the DB to take into account the change of SRS */ OGRReleaseDataSource(hDS); CPLSetConfigOption("SQLITE_LIST_ALL_TABLES", "TRUE"); hDS = OGROpen(osDBName.c_str(), TRUE, NULL); CPLSetConfigOption("SQLITE_LIST_ALL_TABLES", osOldVal.c_str()); } else { CPLError(CE_Failure, CPLE_NotSupported, "New data has not the same SRS as existing data"); OGRReleaseDataSource(hDS); return NULL; } } } if (bWipeExistingData) { osSQL.Printf("DELETE FROM \"%s\"", osRasterLayer.c_str()); OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); osSQL.Printf("DELETE FROM \"%s\"", osMetatadataLayer.c_str()); OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); } } return hDS; }
static int RasterliteInsertSRID(OGRDataSourceH hDS, const char* pszWKT) { CPLString osSQL; int nAuthorityCode = 0; CPLString osAuthorityName, osProjCS, osProj4; if (pszWKT != NULL && strlen(pszWKT) != 0) { OGRSpatialReferenceH hSRS = OSRNewSpatialReference(pszWKT); if (hSRS) { const char* pszAuthorityName = OSRGetAuthorityName(hSRS, NULL); if (pszAuthorityName) osAuthorityName = pszAuthorityName; const char* pszProjCS = OSRGetAttrValue(hSRS, "PROJCS", 0); if (pszProjCS) osProjCS = pszProjCS; const char* pszAuthorityCode = OSRGetAuthorityCode(hSRS, NULL); if (pszAuthorityCode) nAuthorityCode = atoi(pszAuthorityCode); char *pszProj4 = NULL; if( OSRExportToProj4( hSRS, &pszProj4 ) != OGRERR_NONE ) pszProj4 = CPLStrdup(""); osProj4 = pszProj4; CPLFree(pszProj4); } OSRDestroySpatialReference(hSRS); } int nSRSId = -1; if (nAuthorityCode != 0 && osAuthorityName.size() != 0) { osSQL.Printf ("SELECT srid FROM spatial_ref_sys WHERE auth_srid = %d", nAuthorityCode); OGRLayerH hLyr = OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); if (hLyr == NULL) { nSRSId = nAuthorityCode; if ( osProjCS.size() != 0 ) osSQL.Printf( "INSERT INTO spatial_ref_sys " "(srid, auth_name, auth_srid, ref_sys_name, proj4text) " "VALUES (%d, '%s', '%d', '%s', '%s')", nSRSId, osAuthorityName.c_str(), nAuthorityCode, osProjCS.c_str(), osProj4.c_str() ); else osSQL.Printf( "INSERT INTO spatial_ref_sys " "(srid, auth_name, auth_srid, proj4text) " "VALUES (%d, '%s', '%d', '%s')", nSRSId, osAuthorityName.c_str(), nAuthorityCode, osProj4.c_str() ); OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); } else { OGRFeatureH hFeat = OGR_L_GetNextFeature(hLyr); if (hFeat) { nSRSId = OGR_F_GetFieldAsInteger(hFeat, 0); OGR_F_Destroy(hFeat); } OGR_DS_ReleaseResultSet(hDS, hLyr); } } return nSRSId; }
CPLErr RasterliteDataset::CreateOverviewLevel(const char * pszResampling, int nOvrFactor, char** papszOptions, GDALProgressFunc pfnProgress, void * pProgressData) { double dfXResolution = padfXResolutions[0] * nOvrFactor; double dfYResolution = padfXResolutions[0] * nOvrFactor; CPLString osSQL; int nOvrXSize = nRasterXSize / nOvrFactor; int nOvrYSize = nRasterYSize / nOvrFactor; if (nOvrXSize == 0 || nOvrYSize == 0) return CE_Failure; int bTiled = CSLTestBoolean(CSLFetchNameValueDef(papszOptions, "TILED", "YES")); int nBlockXSize, nBlockYSize; if (bTiled) { nBlockXSize = atoi(CSLFetchNameValueDef(papszOptions, "BLOCKXSIZE", "256")); nBlockYSize = atoi(CSLFetchNameValueDef(papszOptions, "BLOCKYSIZE", "256")); if (nBlockXSize < 64) nBlockXSize = 64; else if (nBlockXSize > 4096) nBlockXSize = 4096; if (nBlockYSize < 64) nBlockYSize = 64; else if (nBlockYSize > 4096) nBlockYSize = 4096; } else { nBlockXSize = nOvrXSize; nBlockYSize = nOvrYSize; } int nXBlocks = (nOvrXSize + nBlockXSize - 1) / nBlockXSize; int nYBlocks = (nOvrYSize + nBlockYSize - 1) / nBlockYSize; const char* pszDriverName = CSLFetchNameValueDef(papszOptions, "DRIVER", "GTiff"); if (EQUAL(pszDriverName, "MEM") || EQUAL(pszDriverName, "VRT")) { CPLError(CE_Failure, CPLE_AppDefined, "GDAL %s driver cannot be used as underlying driver", pszDriverName); return CE_Failure; } GDALDriverH hTileDriver = GDALGetDriverByName(pszDriverName); if (hTileDriver == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot load GDAL %s driver", pszDriverName); return CE_Failure; } GDALDriverH hMemDriver = GDALGetDriverByName("MEM"); if (hMemDriver == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot load GDAL MEM driver"); return CE_Failure; } GDALDataType eDataType = GetRasterBand(1)->GetRasterDataType(); int nDataTypeSize = GDALGetDataTypeSize(eDataType) / 8; GByte* pabyMEMDSBuffer = (GByte*)VSIMalloc3(nBlockXSize, nBlockYSize, nBands * nDataTypeSize); if (pabyMEMDSBuffer == NULL) { return CE_Failure; } CPLString osTempFileName; osTempFileName.Printf("/vsimem/%p", hDS); int nTileId = 0; int nBlocks = 0; int nTotalBlocks = nXBlocks * nYBlocks; CPLString osRasterLayer; osRasterLayer.Printf("%s_rasters", osTableName.c_str()); CPLString osMetatadataLayer; osMetatadataLayer.Printf("%s_metadata", osTableName.c_str()); OGRLayerH hRasterLayer = OGR_DS_GetLayerByName(hDS, osRasterLayer.c_str()); OGRLayerH hMetadataLayer = OGR_DS_GetLayerByName(hDS, osMetatadataLayer.c_str()); CPLString osSourceName = "unknown"; osSQL.Printf("SELECT source_name FROM \"%s\" WHERE " "%s LIMIT 1", osMetatadataLayer.c_str(), RasterliteGetPixelSizeCond(padfXResolutions[0], padfYResolutions[0]).c_str()); OGRLayerH hSQLLyr = OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); if (hSQLLyr) { OGRFeatureH hFeat = OGR_L_GetNextFeature(hSQLLyr); if (hFeat) { const char* pszVal = OGR_F_GetFieldAsString(hFeat, 0); if (pszVal) osSourceName = pszVal; OGR_F_Destroy(hFeat); } OGR_DS_ReleaseResultSet(hDS, hSQLLyr); } /* -------------------------------------------------------------------- */ /* Compute up to which existing overview level we can use for */ /* computing the requested overview */ /* -------------------------------------------------------------------- */ int iLev; nLimitOvrCount = 0; for(iLev=1;iLev<nResolutions;iLev++) { if (!(padfXResolutions[iLev] < dfXResolution - 1e-10 && padfYResolutions[iLev] < dfYResolution - 1e-10)) { break; } nLimitOvrCount++; } /* -------------------------------------------------------------------- */ /* Allocate buffer for tile of previous overview level */ /* -------------------------------------------------------------------- */ GDALDataset* poPrevOvrLevel = (papoOverviews != NULL && iLev >= 2 && iLev <= nResolutions && papoOverviews[iLev-2]) ? papoOverviews[iLev-2] : this; double dfRatioPrevOvr = poPrevOvrLevel->GetRasterBand(1)->GetXSize() / nOvrXSize; int nPrevOvrBlockXSize = (int)(nBlockXSize * dfRatioPrevOvr + 0.5); int nPrevOvrBlockYSize = (int)(nBlockYSize * dfRatioPrevOvr + 0.5); GByte* pabyPrevOvrMEMDSBuffer = NULL; if( !EQUALN(pszResampling, "NEAR", 4)) { pabyPrevOvrMEMDSBuffer = (GByte*)VSIMalloc3(nPrevOvrBlockXSize, nPrevOvrBlockYSize, nBands * nDataTypeSize); if (pabyPrevOvrMEMDSBuffer == NULL) { VSIFree(pabyMEMDSBuffer); return CE_Failure; } } /* -------------------------------------------------------------------- */ /* Iterate over blocks to add data into raster and metadata tables */ /* -------------------------------------------------------------------- */ char** papszTileDriverOptions = RasterliteGetTileDriverOptions(papszOptions); OGR_DS_ExecuteSQL(hDS, "BEGIN", NULL, NULL); CPLErr eErr = CE_None; int nBlockXOff, nBlockYOff; for(nBlockYOff=0;eErr == CE_None && nBlockYOff<nYBlocks;nBlockYOff++) { for(nBlockXOff=0;eErr == CE_None && nBlockXOff<nXBlocks;nBlockXOff++) { GDALDatasetH hPrevOvrMemDS = NULL; /* -------------------------------------------------------------------- */ /* Create in-memory tile */ /* -------------------------------------------------------------------- */ int nReqXSize = nBlockXSize, nReqYSize = nBlockYSize; if ((nBlockXOff+1) * nBlockXSize > nOvrXSize) nReqXSize = nOvrXSize - nBlockXOff * nBlockXSize; if ((nBlockYOff+1) * nBlockYSize > nOvrYSize) nReqYSize = nOvrYSize - nBlockYOff * nBlockYSize; if( pabyPrevOvrMEMDSBuffer != NULL ) { int nPrevOvrReqXSize = (int)(nReqXSize * dfRatioPrevOvr + 0.5); int nPrevOvrReqYSize = (int)(nReqYSize * dfRatioPrevOvr + 0.5); eErr = RasterIO(GF_Read, nBlockXOff * nBlockXSize * nOvrFactor, nBlockYOff * nBlockYSize * nOvrFactor, nReqXSize * nOvrFactor, nReqYSize * nOvrFactor, pabyPrevOvrMEMDSBuffer, nPrevOvrReqXSize, nPrevOvrReqYSize, eDataType, nBands, NULL, 0, 0, 0, NULL); if (eErr != CE_None) { break; } hPrevOvrMemDS = GDALCreate(hMemDriver, "MEM:::", nPrevOvrReqXSize, nPrevOvrReqYSize, 0, eDataType, NULL); if (hPrevOvrMemDS == NULL) { eErr = CE_Failure; break; } int iBand; for(iBand = 0; iBand < nBands; iBand ++) { char** papszOptions = NULL; char szTmp[64]; memset(szTmp, 0, sizeof(szTmp)); CPLPrintPointer(szTmp, pabyPrevOvrMEMDSBuffer + iBand * nDataTypeSize * nPrevOvrReqXSize * nPrevOvrReqYSize, sizeof(szTmp)); papszOptions = CSLSetNameValue(papszOptions, "DATAPOINTER", szTmp); GDALAddBand(hPrevOvrMemDS, eDataType, papszOptions); CSLDestroy(papszOptions); } } else { eErr = RasterIO(GF_Read, nBlockXOff * nBlockXSize * nOvrFactor, nBlockYOff * nBlockYSize * nOvrFactor, nReqXSize * nOvrFactor, nReqYSize * nOvrFactor, pabyMEMDSBuffer, nReqXSize, nReqYSize, eDataType, nBands, NULL, 0, 0, 0, NULL); if (eErr != CE_None) { break; } } GDALDatasetH hMemDS = GDALCreate(hMemDriver, "MEM:::", nReqXSize, nReqYSize, 0, eDataType, NULL); if (hMemDS == NULL) { eErr = CE_Failure; break; } int iBand; for(iBand = 0; iBand < nBands; iBand ++) { char** papszOptions = NULL; char szTmp[64]; memset(szTmp, 0, sizeof(szTmp)); CPLPrintPointer(szTmp, pabyMEMDSBuffer + iBand * nDataTypeSize * nReqXSize * nReqYSize, sizeof(szTmp)); papszOptions = CSLSetNameValue(papszOptions, "DATAPOINTER", szTmp); GDALAddBand(hMemDS, eDataType, papszOptions); CSLDestroy(papszOptions); } if( hPrevOvrMemDS != NULL ) { for(iBand = 0; iBand < nBands; iBand ++) { GDALRasterBandH hDstOvrBand = GDALGetRasterBand(hMemDS, iBand+1); eErr = GDALRegenerateOverviews( GDALGetRasterBand(hPrevOvrMemDS, iBand+1), 1, &hDstOvrBand, pszResampling, NULL, NULL ); if( eErr != CE_None ) break; } GDALClose(hPrevOvrMemDS); } GDALDatasetH hOutDS = GDALCreateCopy(hTileDriver, osTempFileName.c_str(), hMemDS, FALSE, papszTileDriverOptions, NULL, NULL); GDALClose(hMemDS); if (hOutDS) GDALClose(hOutDS); else { eErr = CE_Failure; break; } /* -------------------------------------------------------------------- */ /* Insert new entry into raster table */ /* -------------------------------------------------------------------- */ vsi_l_offset nDataLength; GByte *pabyData = VSIGetMemFileBuffer( osTempFileName.c_str(), &nDataLength, FALSE); OGRFeatureH hFeat = OGR_F_Create( OGR_L_GetLayerDefn(hRasterLayer) ); OGR_F_SetFieldBinary(hFeat, 0, (int)nDataLength, pabyData); OGR_L_CreateFeature(hRasterLayer, hFeat); /* Query raster ID to set it as the ID of the associated metadata */ int nRasterID = (int)OGR_F_GetFID(hFeat); OGR_F_Destroy(hFeat); VSIUnlink(osTempFileName.c_str()); /* -------------------------------------------------------------------- */ /* Insert new entry into metadata table */ /* -------------------------------------------------------------------- */ hFeat = OGR_F_Create( OGR_L_GetLayerDefn(hMetadataLayer) ); OGR_F_SetFID(hFeat, nRasterID); OGR_F_SetFieldString(hFeat, 0, osSourceName); OGR_F_SetFieldInteger(hFeat, 1, nTileId ++); OGR_F_SetFieldInteger(hFeat, 2, nReqXSize); OGR_F_SetFieldInteger(hFeat, 3, nReqYSize); OGR_F_SetFieldDouble(hFeat, 4, dfXResolution); OGR_F_SetFieldDouble(hFeat, 5, dfYResolution); double minx, maxx, maxy, miny; minx = adfGeoTransform[0] + (nBlockXSize * nBlockXOff) * dfXResolution; maxx = adfGeoTransform[0] + (nBlockXSize * nBlockXOff + nReqXSize) * dfXResolution; maxy = adfGeoTransform[3] + (nBlockYSize * nBlockYOff) * (-dfYResolution); miny = adfGeoTransform[3] + (nBlockYSize * nBlockYOff + nReqYSize) * (-dfYResolution); OGRGeometryH hRectangle = OGR_G_CreateGeometry(wkbPolygon); OGRGeometryH hLinearRing = OGR_G_CreateGeometry(wkbLinearRing); OGR_G_AddPoint_2D(hLinearRing, minx, miny); OGR_G_AddPoint_2D(hLinearRing, minx, maxy); OGR_G_AddPoint_2D(hLinearRing, maxx, maxy); OGR_G_AddPoint_2D(hLinearRing, maxx, miny); OGR_G_AddPoint_2D(hLinearRing, minx, miny); OGR_G_AddGeometryDirectly(hRectangle, hLinearRing); OGR_F_SetGeometryDirectly(hFeat, hRectangle); OGR_L_CreateFeature(hMetadataLayer, hFeat); OGR_F_Destroy(hFeat); nBlocks++; if (pfnProgress && !pfnProgress(1.0 * nBlocks / nTotalBlocks, NULL, pProgressData)) eErr = CE_Failure; } } nLimitOvrCount = -1; if (eErr == CE_None) OGR_DS_ExecuteSQL(hDS, "COMMIT", NULL, NULL); else OGR_DS_ExecuteSQL(hDS, "ROLLBACK", NULL, NULL); VSIFree(pabyMEMDSBuffer); VSIFree(pabyPrevOvrMEMDSBuffer); CSLDestroy(papszTileDriverOptions); papszTileDriverOptions = NULL; /* -------------------------------------------------------------------- */ /* Update raster_pyramids table */ /* -------------------------------------------------------------------- */ if (eErr == CE_None) { OGRLayerH hRasterPyramidsLyr = OGR_DS_GetLayerByName(hDS, "raster_pyramids"); if (hRasterPyramidsLyr == NULL) { osSQL.Printf ("CREATE TABLE raster_pyramids (" "table_prefix TEXT NOT NULL," "pixel_x_size DOUBLE NOT NULL," "pixel_y_size DOUBLE NOT NULL," "tile_count INTEGER NOT NULL)"); OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); /* Re-open the DB to take into account the new tables*/ OGRReleaseDataSource(hDS); hDS = RasterliteOpenSQLiteDB(osFileName.c_str(), GA_Update); hRasterPyramidsLyr = OGR_DS_GetLayerByName(hDS, "raster_pyramids"); if (hRasterPyramidsLyr == NULL) return CE_Failure; } OGRFeatureDefnH hFDefn = OGR_L_GetLayerDefn(hRasterPyramidsLyr); /* Insert base resolution into raster_pyramids if not already done */ int bHasBaseResolution = FALSE; osSQL.Printf("SELECT * FROM raster_pyramids WHERE " "table_prefix = '%s' AND %s", osTableName.c_str(), RasterliteGetPixelSizeCond(padfXResolutions[0], padfYResolutions[0]).c_str()); hSQLLyr = OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); if (hSQLLyr) { OGRFeatureH hFeat = OGR_L_GetNextFeature(hSQLLyr); if (hFeat) { bHasBaseResolution = TRUE; OGR_F_Destroy(hFeat); } OGR_DS_ReleaseResultSet(hDS, hSQLLyr); } if (!bHasBaseResolution) { osSQL.Printf("SELECT COUNT(*) FROM \"%s\" WHERE %s", osMetatadataLayer.c_str(), RasterliteGetPixelSizeCond(padfXResolutions[0], padfYResolutions[0]).c_str()); int nBlocksMainRes = 0; hSQLLyr = OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); if (hSQLLyr) { OGRFeatureH hFeat = OGR_L_GetNextFeature(hSQLLyr); if (hFeat) { nBlocksMainRes = OGR_F_GetFieldAsInteger(hFeat, 0); OGR_F_Destroy(hFeat); } OGR_DS_ReleaseResultSet(hDS, hSQLLyr); } OGRFeatureH hFeat = OGR_F_Create( hFDefn ); OGR_F_SetFieldString(hFeat, OGR_FD_GetFieldIndex(hFDefn, "table_prefix"), osTableName.c_str()); OGR_F_SetFieldDouble(hFeat, OGR_FD_GetFieldIndex(hFDefn, "pixel_x_size"), padfXResolutions[0]); OGR_F_SetFieldDouble(hFeat, OGR_FD_GetFieldIndex(hFDefn, "pixel_y_size"), padfYResolutions[0]); OGR_F_SetFieldInteger(hFeat, OGR_FD_GetFieldIndex(hFDefn, "tile_count"), nBlocksMainRes); OGR_L_CreateFeature(hRasterPyramidsLyr, hFeat); OGR_F_Destroy(hFeat); } OGRFeatureH hFeat = OGR_F_Create( hFDefn ); OGR_F_SetFieldString(hFeat, OGR_FD_GetFieldIndex(hFDefn, "table_prefix"), osTableName.c_str()); OGR_F_SetFieldDouble(hFeat, OGR_FD_GetFieldIndex(hFDefn, "pixel_x_size"), dfXResolution); OGR_F_SetFieldDouble(hFeat, OGR_FD_GetFieldIndex(hFDefn, "pixel_y_size"), dfYResolution); OGR_F_SetFieldInteger(hFeat, OGR_FD_GetFieldIndex(hFDefn, "tile_count"), nTotalBlocks); OGR_L_CreateFeature(hRasterPyramidsLyr, hFeat); OGR_F_Destroy(hFeat); } return eErr; }
void AttributeFilter::UpdateGEOSBuffer(PointView& view) { QuadIndex idx(view); if (m_layer.size()) m_lyr = OGR_DS_GetLayerByName(m_ds.get(), m_layer.c_str()); else if (m_query.size()) m_lyr = OGR_DS_ExecuteSQL(m_ds.get(), m_query.c_str(), 0, 0); else m_lyr = OGR_DS_GetLayer(m_ds.get(), 0); if (!m_lyr) { std::ostringstream oss; oss << getName() << ": Unable to select layer '" << m_layer << "'"; throw pdal_error(oss.str()); } OGRFeaturePtr feature = OGRFeaturePtr(OGR_L_GetNextFeature(m_lyr), OGRFeatureDeleter()); int field_index(1); // default to first column if nothing was set if (m_column.size()) { field_index = OGR_F_GetFieldIndex(feature.get(), m_column.c_str()); if (field_index == -1) { std::ostringstream oss; oss << getName() << ": No column name '" << m_column << "' was found."; throw pdal_error(oss.str()); } } while (feature) { OGRGeometryH geom = OGR_F_GetGeometryRef(feature.get()); OGRwkbGeometryType t = OGR_G_GetGeometryType(geom); int32_t fieldVal = OGR_F_GetFieldAsInteger(feature.get(), field_index); if (!(t == wkbPolygon || t == wkbMultiPolygon || t == wkbPolygon25D || t == wkbMultiPolygon25D)) { std::ostringstream oss; oss << getName() << ": Geometry is not Polygon or MultiPolygon!"; throw pdal::pdal_error(oss.str()); } pdal::Polygon p(geom, view.spatialReference(), GlobalEnvironment::get().geos()); // Compute a total bounds for the geometry. Query the QuadTree to // find out the points that are inside the bbox. Then test each // point in the bbox against the prepared geometry. BOX3D box = p.bounds(); std::vector<PointId> ids = idx.getPoints(box); for (const auto& i : ids) { PointRef ref(view, i); if (p.covers(ref)) view.setField(m_dim, i, fieldVal); } feature = OGRFeaturePtr(OGR_L_GetNextFeature(m_lyr), OGRFeatureDeleter()); } }
/*! \brief Fetch record \param cn pointer to dbCursor \param position position indicator (DB_NEXT, DB_FIRST, DB_LAST, etc) \param[out] more 0 for no record fetched otherwise 1 \return DB_OK on success \return DB_FAILED on error */ int db__driver_fetch(dbCursor * cn, int position, int *more) { int i, col; int ogrType, sqlType; dbToken token; dbTable *table; dbColumn *column; dbValue *value; cursor *c; G_debug(3, "db_driver_fetch()"); /* get cursor token */ token = db_get_cursor_token(cn); /* get the cursor by its token */ if (!(c = (cursor *) db_find_token(token))) { append_error(_("Cursor not found")); report_error(); return DB_FAILED; } /* fetch on position */ switch (position) { case DB_NEXT: G_debug(4, "DB_NEXT:"); if (c->hFeature) OGR_F_Destroy(c->hFeature); c->hFeature = OGR_L_GetNextFeature(c->hLayer); break; case DB_CURRENT: break; case DB_PREVIOUS: append_error(_("DB_PREVIOUS not supported")); report_error(); return DB_FAILED; break; case DB_FIRST: OGR_L_ResetReading(c->hLayer); if (c->hFeature) OGR_F_Destroy(c->hFeature); c->hFeature = OGR_L_GetNextFeature(c->hLayer); break; case DB_LAST: append_error(_("DB_LAST not supported")); report_error(); return DB_FAILED; break; }; if (c->hFeature == NULL) { *more = 0; return DB_OK; } *more = 1; /* get the data out of the descriptor into the table */ table = db_get_cursor_table(cn); /* check fid column */ if (strlen(OGR_L_GetFIDColumn(c->hLayer)) > 0) { column = db_get_table_column(table, 0); ogrType = db_get_column_host_type(column); sqlType = db_get_column_sqltype(column); value = db_get_column_value(column); value->i = OGR_F_GetFID(c->hFeature); G_debug(3, "fidcol '%s': ogrType %d, sqlType %d: val = %d", db_get_column_name(column), ogrType, sqlType, value->i); col = 0; } else { col = -1; } /* loop attributes */ for (i = 0; i < c->ncols; i++) { if (!(c->cols[i])) { continue; } /* unknown type */ col++; column = db_get_table_column(table, col); ogrType = db_get_column_host_type(column); sqlType = db_get_column_sqltype(column); value = db_get_column_value(column); db_zero_string(&value->s); /* Is null? */ if (OGR_F_IsFieldSet(c->hFeature, i)) { value->isNull = 0; } else { value->isNull = 1; continue; } G_debug(3, "col %d, ogrType %d, sqlType %d: val = '%s'", col, ogrType, sqlType, OGR_F_GetFieldAsString(c->hFeature, i)); switch (ogrType) { case OFTInteger: value->i = OGR_F_GetFieldAsInteger(c->hFeature, i); break; case OFTReal: value->d = OGR_F_GetFieldAsDouble(c->hFeature, i); break; case OFTString: case OFTDate: case OFTTime: case OFTDateTime: db_set_string(&(value->s), (char *)OGR_F_GetFieldAsString(c->hFeature, i)); break; default: G_warning(_("Unknown type")); break; } } G_debug(4, "Row fetched"); return DB_OK; }