void object::test<6>() { // Create feature without geometry std::string tmp(data_tmp_); tmp += SEP; tmp += "tpoly.shp"; OGRDataSourceH ds = OGR_Dr_Open(drv_, tmp.c_str(), true); ensure("Can't open layer", NULL != ds); OGRLayerH lyr = OGR_DS_GetLayer(ds, 0); ensure("Can't get layer", NULL != lyr); OGRFeatureDefnH featDefn = OGR_L_GetLayerDefn(lyr); ensure("Layer schema is NULL", NULL != featDefn); OGRFeatureH featNonSpatial = OGR_F_Create(featDefn); ensure("Can't create non-spatial feature", NULL != featNonSpatial); int fldIndex = OGR_FD_GetFieldIndex(featDefn, "PRFEDEA"); ensure("Can't find field 'PRFEDEA'", fldIndex >= 0); OGR_F_SetFieldString(featNonSpatial, fldIndex, "nulled"); OGRErr err = OGR_L_CreateFeature(lyr, featNonSpatial); ensure_equals("Can't write non-spatial feature to layer", OGRERR_NONE, err); OGR_F_Destroy(featNonSpatial); OGR_DS_Destroy(ds); }
int Feature::index (const char *name) { int i = OGR_FD_GetFieldIndex(defn, name); if (i == -1) { throw runtime_error(string(name) + " field not found on feature."); } return i; }
/* 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; }
static CPLErr ProcessLayer( OGRLayerH hSrcLayer, int bSRSIsSet, GDALDatasetH hDstDS, std::vector<int> anBandList, const std::vector<double> &adfBurnValues, int b3D, int bInverse, const char *pszBurnAttribute, char **papszRasterizeOptions, GDALProgressFunc pfnProgress, void* pProgressData ) { /* -------------------------------------------------------------------- */ /* Checkout that SRS are the same. */ /* If -a_srs is specified, skip the test */ /* -------------------------------------------------------------------- */ OGRCoordinateTransformationH hCT = NULL; if (!bSRSIsSet) { OGRSpatialReferenceH hDstSRS = NULL; if( GDALGetProjectionRef( hDstDS ) != NULL ) { char *pszProjection; pszProjection = (char *) GDALGetProjectionRef( hDstDS ); hDstSRS = OSRNewSpatialReference(NULL); if( OSRImportFromWkt( hDstSRS, &pszProjection ) != OGRERR_NONE ) { OSRDestroySpatialReference(hDstSRS); hDstSRS = NULL; } } OGRSpatialReferenceH hSrcSRS = OGR_L_GetSpatialRef(hSrcLayer); if( hDstSRS != NULL && hSrcSRS != NULL ) { if( OSRIsSame(hSrcSRS, hDstSRS) == FALSE ) { hCT = OCTNewCoordinateTransformation(hSrcSRS, hDstSRS); if( hCT == NULL ) { CPLError(CE_Warning, CPLE_AppDefined, "The output raster dataset and the input vector layer do not have the same SRS.\n" "And reprojection of input data did not work. Results might be incorrect."); } } } else if( hDstSRS != NULL && hSrcSRS == NULL ) { CPLError(CE_Warning, CPLE_AppDefined, "The output raster dataset has a SRS, but the input vector layer SRS is unknown.\n" "Ensure input vector has the same SRS, otherwise results might be incorrect."); } else if( hDstSRS == NULL && hSrcSRS != NULL ) { CPLError(CE_Warning, CPLE_AppDefined, "The input vector layer has a SRS, but the output raster dataset SRS is unknown.\n" "Ensure output raster dataset has the same SRS, otherwise results might be incorrect."); } if( hDstSRS != NULL ) { OSRDestroySpatialReference(hDstSRS); } } /* -------------------------------------------------------------------- */ /* Get field index, and check. */ /* -------------------------------------------------------------------- */ int iBurnField = -1; if( pszBurnAttribute ) { iBurnField = OGR_FD_GetFieldIndex( OGR_L_GetLayerDefn( hSrcLayer ), pszBurnAttribute ); if( iBurnField == -1 ) { CPLError(CE_Failure, CPLE_AppDefined, "Failed to find field %s on layer %s, skipping.", pszBurnAttribute, OGR_FD_GetName( OGR_L_GetLayerDefn( hSrcLayer ) ) ); if( hCT != NULL ) OCTDestroyCoordinateTransformation(hCT); return CE_Failure; } } /* -------------------------------------------------------------------- */ /* Collect the geometries from this layer, and build list of */ /* burn values. */ /* -------------------------------------------------------------------- */ OGRFeatureH hFeat; std::vector<OGRGeometryH> ahGeometries; std::vector<double> adfFullBurnValues; OGR_L_ResetReading( hSrcLayer ); while( (hFeat = OGR_L_GetNextFeature( hSrcLayer )) != NULL ) { OGRGeometryH hGeom; if( OGR_F_GetGeometryRef( hFeat ) == NULL ) { OGR_F_Destroy( hFeat ); continue; } hGeom = OGR_G_Clone( OGR_F_GetGeometryRef( hFeat ) ); if( hCT != NULL ) { if( OGR_G_Transform(hGeom, hCT) != OGRERR_NONE ) { OGR_F_Destroy( hFeat ); OGR_G_DestroyGeometry(hGeom); continue; } } ahGeometries.push_back( hGeom ); for( unsigned int iBand = 0; iBand < anBandList.size(); iBand++ ) { if( adfBurnValues.size() > 0 ) adfFullBurnValues.push_back( adfBurnValues[MIN(iBand,adfBurnValues.size()-1)] ); else if( pszBurnAttribute ) { adfFullBurnValues.push_back( OGR_F_GetFieldAsDouble( hFeat, iBurnField ) ); } /* I have made the 3D option exclusive to other options since it can be used to modify the value from "-burn value" or "-a attribute_name" */ if( b3D ) { // TODO: get geometry "z" value /* Points and Lines will have their "z" values collected at the point and line levels respectively. However filled polygons (GDALdllImageFilledPolygon) can use some help by getting their "z" values here. */ adfFullBurnValues.push_back( 0.0 ); } } OGR_F_Destroy( hFeat ); } if( hCT != NULL ) OCTDestroyCoordinateTransformation(hCT); /* -------------------------------------------------------------------- */ /* If we are in inverse mode, we add one extra ring around the */ /* whole dataset to invert the concept of insideness and then */ /* merge everything into one geometry collection. */ /* -------------------------------------------------------------------- */ if( bInverse ) { if( ahGeometries.size() == 0 ) { for( unsigned int iBand = 0; iBand < anBandList.size(); iBand++ ) { if( adfBurnValues.size() > 0 ) adfFullBurnValues.push_back( adfBurnValues[MIN(iBand,adfBurnValues.size()-1)] ); else /* FIXME? Not sure what to do exactly in the else case, but we must insert a value */ adfFullBurnValues.push_back( 0.0 ); } } InvertGeometries( hDstDS, ahGeometries ); } /* -------------------------------------------------------------------- */ /* Perform the burn. */ /* -------------------------------------------------------------------- */ CPLErr eErr = GDALRasterizeGeometries( hDstDS, static_cast<int>(anBandList.size()), &(anBandList[0]), static_cast<int>(ahGeometries.size()), &(ahGeometries[0]), NULL, NULL, &(adfFullBurnValues[0]), papszRasterizeOptions, pfnProgress, pProgressData ); /* -------------------------------------------------------------------- */ /* Cleanup geometries. */ /* -------------------------------------------------------------------- */ int iGeom; for( iGeom = static_cast<int>(ahGeometries.size())-1; iGeom >= 0; iGeom-- ) OGR_G_DestroyGeometry( ahGeometries[iGeom] ); return eErr; }
MAIN_START(argc, argv) { // Check that we are running against at least GDAL 1.4. // Note to developers: if we use newer API, please change the requirement. if( atoi(GDALVersionInfo("VERSION_NUM")) < 1400 ) { fprintf(stderr, "At least, GDAL >= 1.4.0 is required for this version of %s, " "which was compiled against GDAL %s\n", argv[0], GDAL_RELEASE_NAME); exit(1); } GDALAllRegister(); OGRRegisterAll(); argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 ); if( argc < 1 ) exit( -argc ); /* -------------------------------------------------------------------- */ /* Get commandline arguments other than the GDAL raster filenames. */ /* -------------------------------------------------------------------- */ const char* pszIndexLayerName = nullptr; const char *index_filename = nullptr; const char *tile_index = "location"; const char* pszDriverName = nullptr; size_t nMaxFieldSize = 254; bool write_absolute_path = false; char* current_path = nullptr; bool skip_different_projection = false; const char *pszTargetSRS = ""; bool bSetTargetSRS = false; const char* pszSrcSRSName = nullptr; int i_SrcSRSName = -1; bool bSrcSRSFormatSpecified = false; SrcSRSFormat eSrcSRSFormat = FORMAT_AUTO; int iArg = 1; // Used after for. for( ; iArg < argc; iArg++ ) { if( EQUAL(argv[iArg], "--utility_version") ) { printf("%s was compiled against GDAL %s and is running against " "GDAL %s\n", argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME")); CSLDestroy( argv ); return 0; } else if( EQUAL(argv[iArg],"--help") ) Usage(nullptr); else if( (strcmp(argv[iArg],"-f") == 0 || strcmp(argv[iArg],"-of") == 0) ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszDriverName = argv[++iArg]; } else if( strcmp(argv[iArg],"-lyr_name") == 0 ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszIndexLayerName = argv[++iArg]; } else if( strcmp(argv[iArg],"-tileindex") == 0 ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); tile_index = argv[++iArg]; } else if( strcmp(argv[iArg],"-t_srs") == 0 ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszTargetSRS = argv[++iArg]; bSetTargetSRS = true; } else if ( strcmp(argv[iArg],"-write_absolute_path") == 0 ) { write_absolute_path = true; } else if ( strcmp(argv[iArg],"-skip_different_projection") == 0 ) { skip_different_projection = true; } else if( strcmp(argv[iArg], "-src_srs_name") == 0 ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszSrcSRSName = argv[++iArg]; } else if( strcmp(argv[iArg], "-src_srs_format") == 0 ) { const char* pszFormat; bSrcSRSFormatSpecified = true; CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszFormat = argv[++iArg]; if( EQUAL(pszFormat, "AUTO") ) eSrcSRSFormat = FORMAT_AUTO; else if( EQUAL(pszFormat, "WKT") ) eSrcSRSFormat = FORMAT_WKT; else if( EQUAL(pszFormat, "EPSG") ) eSrcSRSFormat = FORMAT_EPSG; else if( EQUAL(pszFormat, "PROJ") ) eSrcSRSFormat = FORMAT_PROJ; } else if( argv[iArg][0] == '-' ) Usage(CPLSPrintf("Unknown option name '%s'", argv[iArg])); else if( index_filename == nullptr ) { index_filename = argv[iArg]; iArg++; break; } } if( index_filename == nullptr ) Usage("No index filename specified."); if( iArg == argc ) Usage("No file to index specified."); if( bSrcSRSFormatSpecified && pszSrcSRSName == nullptr ) Usage("-src_srs_name must be specified when -src_srs_format is " "specified."); /* -------------------------------------------------------------------- */ /* Create and validate target SRS if given. */ /* -------------------------------------------------------------------- */ OGRSpatialReferenceH hTargetSRS = nullptr; if( bSetTargetSRS ) { if( skip_different_projection ) { fprintf( stderr, "Warning : -skip_different_projection does not apply " "when -t_srs is requested.\n" ); } hTargetSRS = OSRNewSpatialReference(""); OSRSetAxisMappingStrategy(hTargetSRS, OAMS_TRADITIONAL_GIS_ORDER); // coverity[tainted_data] if( OSRSetFromUserInput( hTargetSRS, pszTargetSRS ) != CE_None ) { OSRDestroySpatialReference( hTargetSRS ); fprintf( stderr, "Invalid target SRS `%s'.\n", pszTargetSRS ); exit(1); } } /* -------------------------------------------------------------------- */ /* Open or create the target datasource */ /* -------------------------------------------------------------------- */ GDALDatasetH hTileIndexDS = GDALOpenEx( index_filename, GDAL_OF_VECTOR | GDAL_OF_UPDATE, nullptr, nullptr, nullptr ); OGRLayerH hLayer = nullptr; CPLString osFormat; if( hTileIndexDS != nullptr ) { GDALDriverH hDriver = GDALGetDatasetDriver(hTileIndexDS); if( hDriver ) osFormat = GDALGetDriverShortName(hDriver); if( GDALDatasetGetLayerCount(hTileIndexDS) == 1 ) { hLayer = GDALDatasetGetLayer(hTileIndexDS, 0); } else { if( pszIndexLayerName == nullptr ) { printf( "-lyr_name must be specified.\n" ); exit( 1 ); } CPLPushErrorHandler(CPLQuietErrorHandler); hLayer = GDALDatasetGetLayerByName(hTileIndexDS, pszIndexLayerName); CPLPopErrorHandler(); } } else { printf( "Creating new index file...\n" ); if( pszDriverName == nullptr ) { std::vector<CPLString> aoDrivers = GetOutputDriversFor(index_filename, GDAL_OF_VECTOR); if( aoDrivers.empty() ) { CPLError( CE_Failure, CPLE_AppDefined, "Cannot guess driver for %s", index_filename); exit( 10 ); } else { if( aoDrivers.size() > 1 ) { CPLError( CE_Warning, CPLE_AppDefined, "Several drivers matching %s extension. Using %s", CPLGetExtension(index_filename), aoDrivers[0].c_str() ); } osFormat = aoDrivers[0]; } } else { osFormat = pszDriverName; } if( !EQUAL(osFormat, "ESRI Shapefile") ) nMaxFieldSize = 0; GDALDriverH hDriver = GDALGetDriverByName( osFormat.c_str() ); if( hDriver == nullptr ) { printf( "%s driver not available.\n", osFormat.c_str() ); exit( 1 ); } hTileIndexDS = GDALCreate( hDriver, index_filename, 0, 0, 0, GDT_Unknown, nullptr ); } if( hTileIndexDS != nullptr && hLayer == nullptr ) { OGRSpatialReferenceH hSpatialRef = nullptr; char* pszLayerName = nullptr; if( pszIndexLayerName == nullptr ) { VSIStatBuf sStat; if( EQUAL(osFormat, "ESRI Shapefile") || VSIStat(index_filename, &sStat) == 0 ) { pszLayerName = CPLStrdup(CPLGetBasename(index_filename)); } else { printf( "-lyr_name must be specified.\n" ); exit( 1 ); } } else { pszLayerName = CPLStrdup(pszIndexLayerName); } /* get spatial reference for output file from target SRS (if set) */ /* or from first input file */ if( bSetTargetSRS ) { hSpatialRef = OSRClone( hTargetSRS ); } else { GDALDatasetH hDS = GDALOpen( argv[iArg], GA_ReadOnly ); if( hDS ) { const char* pszWKT = GDALGetProjectionRef(hDS); if (pszWKT != nullptr && pszWKT[0] != '\0') { hSpatialRef = OSRNewSpatialReference(pszWKT); OSRSetAxisMappingStrategy(hSpatialRef, OAMS_TRADITIONAL_GIS_ORDER); } GDALClose(hDS); } } hLayer = GDALDatasetCreateLayer( hTileIndexDS, pszLayerName, hSpatialRef, wkbPolygon, nullptr ); CPLFree(pszLayerName); if( hSpatialRef ) OSRRelease(hSpatialRef); if( hLayer ) { OGRFieldDefnH hFieldDefn = OGR_Fld_Create( tile_index, OFTString ); if( nMaxFieldSize ) OGR_Fld_SetWidth( hFieldDefn, static_cast<int>(nMaxFieldSize)); OGR_L_CreateField( hLayer, hFieldDefn, TRUE ); OGR_Fld_Destroy(hFieldDefn); if( pszSrcSRSName != nullptr ) { hFieldDefn = OGR_Fld_Create( pszSrcSRSName, OFTString ); if( nMaxFieldSize ) OGR_Fld_SetWidth(hFieldDefn, static_cast<int>(nMaxFieldSize)); OGR_L_CreateField( hLayer, hFieldDefn, TRUE ); OGR_Fld_Destroy(hFieldDefn); } } } if( hTileIndexDS == nullptr || hLayer == nullptr ) { fprintf( stderr, "Unable to open/create shapefile `%s'.\n", index_filename ); exit(2); } OGRFeatureDefnH hFDefn = OGR_L_GetLayerDefn(hLayer); const int ti_field = OGR_FD_GetFieldIndex( hFDefn, tile_index ); if( ti_field < 0 ) { fprintf( stderr, "Unable to find field `%s' in file `%s'.\n", tile_index, index_filename ); exit(2); } if( pszSrcSRSName != nullptr ) i_SrcSRSName = OGR_FD_GetFieldIndex( hFDefn, pszSrcSRSName ); // Load in memory existing file names in SHP. int nExistingFiles = static_cast<int>(OGR_L_GetFeatureCount(hLayer, FALSE)); if( nExistingFiles < 0) nExistingFiles = 0; char** existingFilesTab = nullptr; bool alreadyExistingProjectionRefValid = false; char* alreadyExistingProjectionRef = nullptr; if( nExistingFiles > 0 ) { OGRFeatureH hFeature = nullptr; existingFilesTab = static_cast<char **>( CPLMalloc(nExistingFiles * sizeof(char*))); for( int i = 0; i < nExistingFiles; i++ ) { hFeature = OGR_L_GetNextFeature(hLayer); existingFilesTab[i] = CPLStrdup(OGR_F_GetFieldAsString( hFeature, ti_field )); if( i == 0 ) { GDALDatasetH hDS = GDALOpen(existingFilesTab[i], GA_ReadOnly ); if( hDS ) { alreadyExistingProjectionRefValid = true; alreadyExistingProjectionRef = CPLStrdup(GDALGetProjectionRef(hDS)); GDALClose(hDS); } } OGR_F_Destroy( hFeature ); } } if( write_absolute_path ) { current_path = CPLGetCurrentDir(); if (current_path == nullptr) { fprintf( stderr, "This system does not support the CPLGetCurrentDir call. " "The option -write_absolute_path will have no effect\n" ); write_absolute_path = FALSE; } } /* -------------------------------------------------------------------- */ /* loop over GDAL files, processing. */ /* -------------------------------------------------------------------- */ for( ; iArg < argc; iArg++ ) { char *fileNameToWrite = nullptr; VSIStatBuf sStatBuf; // Make sure it is a file before building absolute path name. if( write_absolute_path && CPLIsFilenameRelative( argv[iArg] ) && VSIStat( argv[iArg], &sStatBuf ) == 0 ) { fileNameToWrite = CPLStrdup(CPLProjectRelativeFilename(current_path, argv[iArg])); } else { fileNameToWrite = CPLStrdup(argv[iArg]); } // Checks that file is not already in tileindex. { int i = 0; // Used after for. for( ; i < nExistingFiles; i++ ) { if (EQUAL(fileNameToWrite, existingFilesTab[i])) { fprintf(stderr, "File %s is already in tileindex. Skipping it.\n", fileNameToWrite); break; } } if (i != nExistingFiles) { CPLFree(fileNameToWrite); continue; } } GDALDatasetH hDS = GDALOpen( argv[iArg], GA_ReadOnly ); if( hDS == nullptr ) { fprintf( stderr, "Unable to open %s, skipping.\n", argv[iArg] ); CPLFree(fileNameToWrite); continue; } double adfGeoTransform[6] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; GDALGetGeoTransform( hDS, adfGeoTransform ); if( adfGeoTransform[0] == 0.0 && adfGeoTransform[1] == 1.0 && adfGeoTransform[3] == 0.0 && std::abs(adfGeoTransform[5]) == 1.0 ) { fprintf( stderr, "It appears no georeferencing is available for\n" "`%s', skipping.\n", argv[iArg] ); GDALClose( hDS ); CPLFree(fileNameToWrite); continue; } const char *projectionRef = GDALGetProjectionRef(hDS); // If not set target srs, test that the current file uses same // projection as others. if( !bSetTargetSRS ) { if( alreadyExistingProjectionRefValid ) { int projectionRefNotNull, alreadyExistingProjectionRefNotNull; projectionRefNotNull = projectionRef && projectionRef[0]; alreadyExistingProjectionRefNotNull = alreadyExistingProjectionRef && alreadyExistingProjectionRef[0]; if ((projectionRefNotNull && alreadyExistingProjectionRefNotNull && EQUAL(projectionRef, alreadyExistingProjectionRef) == 0) || (projectionRefNotNull != alreadyExistingProjectionRefNotNull)) { fprintf( stderr, "Warning : %s is not using the same projection system " "as other files in the tileindex.\n" "This may cause problems when using it in MapServer " "for example.\n" "Use -t_srs option to set target projection system " "(not supported by MapServer).\n" "%s\n", argv[iArg], skip_different_projection ? "Skipping this file." : ""); if( skip_different_projection ) { CPLFree(fileNameToWrite); GDALClose( hDS ); continue; } } } else { alreadyExistingProjectionRefValid = true; alreadyExistingProjectionRef = CPLStrdup(projectionRef); } } const int nXSize = GDALGetRasterXSize( hDS ); const int nYSize = GDALGetRasterYSize( hDS ); double adfX[5] = { 0.0, 0.0, 0.0, 0.0, 0.0 }; double adfY[5] = { 0.0, 0.0, 0.0, 0.0, 0.0 }; adfX[0] = adfGeoTransform[0] + 0 * adfGeoTransform[1] + 0 * adfGeoTransform[2]; adfY[0] = adfGeoTransform[3] + 0 * adfGeoTransform[4] + 0 * adfGeoTransform[5]; adfX[1] = adfGeoTransform[0] + nXSize * adfGeoTransform[1] + 0 * adfGeoTransform[2]; adfY[1] = adfGeoTransform[3] + nXSize * adfGeoTransform[4] + 0 * adfGeoTransform[5]; adfX[2] = adfGeoTransform[0] + nXSize * adfGeoTransform[1] + nYSize * adfGeoTransform[2]; adfY[2] = adfGeoTransform[3] + nXSize * adfGeoTransform[4] + nYSize * adfGeoTransform[5]; adfX[3] = adfGeoTransform[0] + 0 * adfGeoTransform[1] + nYSize * adfGeoTransform[2]; adfY[3] = adfGeoTransform[3] + 0 * adfGeoTransform[4] + nYSize * adfGeoTransform[5]; adfX[4] = adfGeoTransform[0] + 0 * adfGeoTransform[1] + 0 * adfGeoTransform[2]; adfY[4] = adfGeoTransform[3] + 0 * adfGeoTransform[4] + 0 * adfGeoTransform[5]; OGRSpatialReferenceH hSourceSRS = nullptr; if( (bSetTargetSRS || i_SrcSRSName >= 0) && projectionRef != nullptr && projectionRef[0] != '\0' ) { hSourceSRS = OSRNewSpatialReference( projectionRef ); OSRSetAxisMappingStrategy(hSourceSRS, OAMS_TRADITIONAL_GIS_ORDER); } // If set target srs, do the forward transformation of all points. if( bSetTargetSRS && projectionRef != nullptr && projectionRef[0] != '\0' ) { OGRCoordinateTransformationH hCT = nullptr; if( hSourceSRS && !OSRIsSame( hSourceSRS, hTargetSRS ) ) { hCT = OCTNewCoordinateTransformation( hSourceSRS, hTargetSRS ); if( hCT == nullptr || !OCTTransform( hCT, 5, adfX, adfY, nullptr ) ) { fprintf( stderr, "Warning : unable to transform points from source " "SRS `%s' to target SRS `%s'\n" "for file `%s' - file skipped\n", projectionRef, pszTargetSRS, fileNameToWrite ); if( hCT ) OCTDestroyCoordinateTransformation( hCT ); if( hSourceSRS ) OSRDestroySpatialReference( hSourceSRS ); continue; } if( hCT ) OCTDestroyCoordinateTransformation( hCT ); } } OGRFeatureH hFeature = OGR_F_Create( OGR_L_GetLayerDefn( hLayer ) ); OGR_F_SetFieldString( hFeature, ti_field, fileNameToWrite ); if( i_SrcSRSName >= 0 && hSourceSRS != nullptr ) { const char* pszAuthorityCode = OSRGetAuthorityCode(hSourceSRS, nullptr); const char* pszAuthorityName = OSRGetAuthorityName(hSourceSRS, nullptr); if( eSrcSRSFormat == FORMAT_AUTO ) { if( pszAuthorityName != nullptr && pszAuthorityCode != nullptr ) { OGR_F_SetFieldString( hFeature, i_SrcSRSName, CPLSPrintf("%s:%s", pszAuthorityName, pszAuthorityCode) ); } else if( nMaxFieldSize == 0 || strlen(projectionRef) <= nMaxFieldSize ) { OGR_F_SetFieldString(hFeature, i_SrcSRSName, projectionRef); } else { char* pszProj4 = nullptr; if( OSRExportToProj4(hSourceSRS, &pszProj4) == OGRERR_NONE ) { OGR_F_SetFieldString( hFeature, i_SrcSRSName, pszProj4 ); CPLFree(pszProj4); } else { OGR_F_SetFieldString( hFeature, i_SrcSRSName, projectionRef ); } } } else if( eSrcSRSFormat == FORMAT_WKT ) { if( nMaxFieldSize == 0 || strlen(projectionRef) <= nMaxFieldSize ) { OGR_F_SetFieldString( hFeature, i_SrcSRSName, projectionRef ); } else { fprintf(stderr, "Cannot write WKT for file %s as it is too long!\n", fileNameToWrite); } } else if( eSrcSRSFormat == FORMAT_PROJ ) { char* pszProj4 = nullptr; if( OSRExportToProj4(hSourceSRS, &pszProj4) == OGRERR_NONE ) { OGR_F_SetFieldString( hFeature, i_SrcSRSName, pszProj4 ); CPLFree(pszProj4); } } else if( eSrcSRSFormat == FORMAT_EPSG ) { if( pszAuthorityName != nullptr && pszAuthorityCode != nullptr ) OGR_F_SetFieldString( hFeature, i_SrcSRSName, CPLSPrintf("%s:%s", pszAuthorityName, pszAuthorityCode) ); } } if( hSourceSRS ) OSRDestroySpatialReference( hSourceSRS ); OGRGeometryH hPoly = OGR_G_CreateGeometry(wkbPolygon); OGRGeometryH hRing = OGR_G_CreateGeometry(wkbLinearRing); for( int k = 0; k < 5; k++ ) OGR_G_SetPoint_2D(hRing, k, adfX[k], adfY[k]); OGR_G_AddGeometryDirectly( hPoly, hRing ); OGR_F_SetGeometryDirectly( hFeature, hPoly ); if( OGR_L_CreateFeature( hLayer, hFeature ) != OGRERR_NONE ) { printf( "Failed to create feature in shapefile.\n" ); break; } OGR_F_Destroy( hFeature ); CPLFree(fileNameToWrite); GDALClose( hDS ); } CPLFree(current_path); if (nExistingFiles) { for( int i = 0; i < nExistingFiles; i++ ) { CPLFree(existingFilesTab[i]); } CPLFree(existingFilesTab); } CPLFree(alreadyExistingProjectionRef); if ( hTargetSRS ) OSRDestroySpatialReference( hTargetSRS ); GDALClose( hTileIndexDS ); GDALDestroyDriverManager(); OGRCleanupAll(); CSLDestroy(argv); exit( 0 ); }
static CPLErr ProcessLayer( OGRLayerH hSrcLayer, GDALDatasetH hDstDS, OGRGeometry *poClipSrc, GUInt32 nXSize, GUInt32 nYSize, int nBand, int& bIsXExtentSet, int& bIsYExtentSet, double& dfXMin, double& dfXMax, double& dfYMin, double& dfYMax, const char *pszBurnAttribute, const double dfIncreaseBurnValue, const double dfMultiplyBurnValue, GDALDataType eType, GDALGridAlgorithm eAlgorithm, void *pOptions, int bQuiet, GDALProgressFunc pfnProgress ) { /* -------------------------------------------------------------------- */ /* Get field index, and check. */ /* -------------------------------------------------------------------- */ int iBurnField = -1; if ( pszBurnAttribute ) { iBurnField = OGR_FD_GetFieldIndex( OGR_L_GetLayerDefn( hSrcLayer ), pszBurnAttribute ); if( iBurnField == -1 ) { printf( "Failed to find field %s on layer %s, skipping.\n", pszBurnAttribute, OGR_FD_GetName( OGR_L_GetLayerDefn( hSrcLayer ) ) ); return CE_Failure; } } /* -------------------------------------------------------------------- */ /* Collect the geometries from this layer, and build list of */ /* values to be interpolated. */ /* -------------------------------------------------------------------- */ OGRFeature *poFeat; std::vector<double> adfX, adfY, adfZ; OGR_L_ResetReading( hSrcLayer ); while( (poFeat = (OGRFeature *)OGR_L_GetNextFeature( hSrcLayer )) != NULL ) { OGRGeometry *poGeom = poFeat->GetGeometryRef(); double dfBurnValue = 0.0; if ( iBurnField >= 0 ) dfBurnValue = poFeat->GetFieldAsDouble( iBurnField ); ProcessCommonGeometry(poGeom, poClipSrc, iBurnField, dfBurnValue, dfIncreaseBurnValue, dfMultiplyBurnValue, adfX, adfY, adfZ); OGRFeature::DestroyFeature( poFeat ); } if ( adfX.size() == 0 ) { printf( "No point geometry found on layer %s, skipping.\n", OGR_FD_GetName( OGR_L_GetLayerDefn( hSrcLayer ) ) ); return CE_None; } /* -------------------------------------------------------------------- */ /* Compute grid geometry. */ /* -------------------------------------------------------------------- */ if ( !bIsXExtentSet || !bIsYExtentSet ) { OGREnvelope sEnvelope; OGR_L_GetExtent( hSrcLayer, &sEnvelope, TRUE ); if ( !bIsXExtentSet ) { dfXMin = sEnvelope.MinX; dfXMax = sEnvelope.MaxX; bIsXExtentSet = TRUE; } if ( !bIsYExtentSet ) { dfYMin = sEnvelope.MinY; dfYMax = sEnvelope.MaxY; bIsYExtentSet = TRUE; } } /* -------------------------------------------------------------------- */ /* Perform gridding. */ /* -------------------------------------------------------------------- */ const double dfDeltaX = ( dfXMax - dfXMin ) / nXSize; const double dfDeltaY = ( dfYMax - dfYMin ) / nYSize; if ( !bQuiet ) { printf( "Grid data type is \"%s\"\n", GDALGetDataTypeName(eType) ); printf( "Grid size = (%lu %lu).\n", (unsigned long)nXSize, (unsigned long)nYSize ); printf( "Corner coordinates = (%f %f)-(%f %f).\n", dfXMin - dfDeltaX / 2, dfYMax + dfDeltaY / 2, dfXMax + dfDeltaX / 2, dfYMin - dfDeltaY / 2 ); printf( "Grid cell size = (%f %f).\n", dfDeltaX, dfDeltaY ); printf( "Source point count = %lu.\n", (unsigned long)adfX.size() ); PrintAlgorithmAndOptions( eAlgorithm, pOptions ); printf("\n"); } GDALRasterBandH hBand = GDALGetRasterBand( hDstDS, nBand ); if (adfX.size() == 0) { // FIXME: Shoulda' set to nodata value instead GDALFillRaster( hBand, 0.0 , 0.0 ); return CE_None; } GUInt32 nXOffset, nYOffset; int nBlockXSize, nBlockYSize; int nDataTypeSize = GDALGetDataTypeSize(eType) / 8; // Try to grow the work buffer up to 16 MB if it is smaller GDALGetBlockSize( hBand, &nBlockXSize, &nBlockYSize ); const GUInt32 nDesiredBufferSize = 16*1024*1024; if( (GUInt32)nBlockXSize < nXSize && (GUInt32)nBlockYSize < nYSize && (GUInt32)nBlockXSize < nDesiredBufferSize / (nBlockYSize * nDataTypeSize) ) { int nNewBlockXSize = nDesiredBufferSize / (nBlockYSize * nDataTypeSize); nBlockXSize = (nNewBlockXSize / nBlockXSize) * nBlockXSize; if( (GUInt32)nBlockXSize > nXSize ) nBlockXSize = nXSize; } else if( (GUInt32)nBlockXSize == nXSize && (GUInt32)nBlockYSize < nYSize && (GUInt32)nBlockYSize < nDesiredBufferSize / (nXSize * nDataTypeSize) ) { int nNewBlockYSize = nDesiredBufferSize / (nXSize * nDataTypeSize); nBlockYSize = (nNewBlockYSize / nBlockYSize) * nBlockYSize; if( (GUInt32)nBlockYSize > nYSize ) nBlockYSize = nYSize; } CPLDebug("GDAL_GRID", "Work buffer: %d * %d", nBlockXSize, nBlockYSize); void *pData = VSIMalloc3( nBlockXSize, nBlockYSize, nDataTypeSize ); if( pData == NULL ) { CPLError(CE_Failure, CPLE_OutOfMemory, "Cannot allocate work buffer"); return CE_Failure; } GUInt32 nBlock = 0; GUInt32 nBlockCount = ((nXSize + nBlockXSize - 1) / nBlockXSize) * ((nYSize + nBlockYSize - 1) / nBlockYSize); CPLErr eErr = CE_None; for ( nYOffset = 0; nYOffset < nYSize && eErr == CE_None; nYOffset += nBlockYSize ) { for ( nXOffset = 0; nXOffset < nXSize && eErr == CE_None; nXOffset += nBlockXSize ) { void *pScaledProgress; pScaledProgress = GDALCreateScaledProgress( (double)nBlock / nBlockCount, (double)(nBlock + 1) / nBlockCount, pfnProgress, NULL ); nBlock ++; int nXRequest = nBlockXSize; if (nXOffset + nXRequest > nXSize) nXRequest = nXSize - nXOffset; int nYRequest = nBlockYSize; if (nYOffset + nYRequest > nYSize) nYRequest = nYSize - nYOffset; eErr = GDALGridCreate( eAlgorithm, pOptions, adfX.size(), &(adfX[0]), &(adfY[0]), &(adfZ[0]), dfXMin + dfDeltaX * nXOffset, dfXMin + dfDeltaX * (nXOffset + nXRequest), dfYMin + dfDeltaY * nYOffset, dfYMin + dfDeltaY * (nYOffset + nYRequest), nXRequest, nYRequest, eType, pData, GDALScaledProgress, pScaledProgress ); if( eErr == CE_None ) eErr = GDALRasterIO( hBand, GF_Write, nXOffset, nYOffset, nXRequest, nYRequest, pData, nXRequest, nYRequest, eType, 0, 0 ); GDALDestroyScaledProgress( pScaledProgress ); } } CPLFree( pData ); return eErr; }
// Create and add a placement to the current lithograph if it doesn't overlap // with current labels. void simplet_lithograph_add_placement(simplet_lithograph_t *litho, OGRFeatureH feature, simplet_list_t *styles, cairo_t *proj_ctx) { simplet_style_t *field = simplet_lookup_style(styles, "text-field"); if(!field) return; OGRFeatureDefnH defn; if(!(defn = OGR_F_GetDefnRef(feature))) return; int idx = OGR_FD_GetFieldIndex(defn, (const char*) field->arg); if(idx < 0) return; // Find the largest sub geometry of a particular multi-geometry. OGRGeometryH super = OGR_F_GetGeometryRef(feature); OGRGeometryH geom = super; double area = 0.0; switch(wkbFlatten(OGR_G_GetGeometryType(super))) { case wkbMultiPolygon: case wkbGeometryCollection: for(int i = 0; i < OGR_G_GetGeometryCount(super); i++) { OGRGeometryH subgeom = OGR_G_GetGeometryRef(super, i); if(subgeom == NULL) continue; double ar = OGR_G_Area(subgeom); if(ar > area) { geom = subgeom; area = ar; } } break; default: ; } // Find the center of our geometry. This sometimes throws an invalid geometry // error, so there is a slight bug here somehow. OGRGeometryH center; if(!(center = OGR_G_CreateGeometry(wkbPoint))) return; if(OGR_G_Centroid(geom, center) == OGRERR_FAILURE) { OGR_G_DestroyGeometry(center); return; } // Turn font hinting off cairo_font_options_t *opts; if(!(opts = cairo_font_options_create())){ OGR_G_DestroyGeometry(center); return; } cairo_font_options_set_hint_style(opts, CAIRO_HINT_STYLE_NONE); cairo_font_options_set_hint_metrics(opts, CAIRO_HINT_METRICS_OFF); pango_cairo_context_set_font_options(litho->pango_ctx, opts); cairo_font_options_destroy(opts); // Get the field containing the text for the label. char *txt = simplet_copy_string(OGR_F_GetFieldAsString(feature, idx)); PangoLayout *layout = pango_layout_new(litho->pango_ctx); pango_layout_set_text(layout, txt, -1); free(txt); // Grab the font to use and apply tracking. simplet_style_t *font = simplet_lookup_style(styles, "font"); simplet_apply_styles(layout, styles, "letter-spacing", NULL); const char *font_family; if(!font) font_family = "helvetica 12px"; else font_family = font->arg; PangoFontDescription *desc = pango_font_description_from_string(font_family); pango_layout_set_font_description(layout, desc); pango_font_description_free(desc); double x = OGR_G_GetX(center, 0), y = OGR_G_GetY(center, 0); cairo_user_to_device(proj_ctx, &x, &y); // Finally try the placement and test for overlaps. try_and_insert_placement(litho, layout, x, y); OGR_G_DestroyGeometry(center); }
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; }
static int msContourLayerGenerateContour(layerObj *layer) { OGRSFDriverH hDriver; OGRFieldDefnH hFld; OGRLayerH hLayer; const char *elevItem; char *option; double interval = 1.0, levels[1000]; int levelCount = 0; GDALRasterBandH hBand = NULL; CPLErr eErr; contourLayerInfo *clinfo = (contourLayerInfo *) layer->layerinfo; OGRRegisterAll(); if (clinfo == NULL) { msSetError(MS_MISCERR, "Assertion failed: Contour layer not opened!!!", "msContourLayerCreateOGRDataSource()"); return MS_FAILURE; } if (!clinfo->hDS) { /* no overlap */ return MS_SUCCESS; } hBand = GDALGetRasterBand(clinfo->hDS, 1); if (hBand == NULL) { msSetError(MS_IMGERR, "Band %d does not exist on dataset.", "msContourLayerGenerateContour()", 1); return MS_FAILURE; } /* Create the OGR DataSource */ hDriver = OGRGetDriverByName("Memory"); if (hDriver == NULL) { msSetError(MS_OGRERR, "Unable to get OGR driver 'Memory'.", "msContourLayerCreateOGRDataSource()"); return MS_FAILURE; } clinfo->hOGRDS = OGR_Dr_CreateDataSource(hDriver, NULL, NULL); if (clinfo->hOGRDS == NULL) { msSetError(MS_OGRERR, "Unable to create OGR DataSource.", "msContourLayerCreateOGRDataSource()"); return MS_FAILURE; } hLayer = OGR_DS_CreateLayer(clinfo->hOGRDS, clinfo->ogrLayer.name, NULL, wkbLineString, NULL ); hFld = OGR_Fld_Create("ID", OFTInteger); OGR_Fld_SetWidth(hFld, 8); OGR_L_CreateField(hLayer, hFld, FALSE); OGR_Fld_Destroy(hFld); /* Check if we have a coutour item specified */ elevItem = CSLFetchNameValue(layer->processing,"CONTOUR_ITEM"); if (elevItem && strlen(elevItem) > 0) { hFld = OGR_Fld_Create(elevItem, OFTReal); OGR_Fld_SetWidth(hFld, 12); OGR_Fld_SetPrecision(hFld, 3); OGR_L_CreateField(hLayer, hFld, FALSE); OGR_Fld_Destroy(hFld); } else { elevItem = NULL; } option = msContourGetOption(layer, "CONTOUR_INTERVAL"); if (option) { interval = atof(option); free(option); } option = msContourGetOption(layer, "CONTOUR_LEVELS"); if (option) { int i,c; char **levelsTmp; levelsTmp = CSLTokenizeStringComplex(option, ",", FALSE, FALSE); c = CSLCount(levelsTmp); for (i=0;i<c && i<(int)(sizeof(levels)/sizeof(double)) ;++i) levels[levelCount++] = atof(levelsTmp[i]); CSLDestroy(levelsTmp); free(option); } eErr = GDALContourGenerate( hBand, interval, 0.0, levelCount, levels, FALSE, 0.0, hLayer, OGR_FD_GetFieldIndex(OGR_L_GetLayerDefn( hLayer), "ID" ), (elevItem == NULL) ? -1 : OGR_FD_GetFieldIndex(OGR_L_GetLayerDefn( hLayer), elevItem ), NULL, NULL ); if (eErr != CE_None) { msSetError( MS_IOERR, "GDALContourGenerate() failed: %s", "msContourLayerGenerateContour()", CPLGetLastErrorMsg() ); return MS_FAILURE; } msConnPoolRegister(&clinfo->ogrLayer, clinfo->hOGRDS, msContourOGRCloseConnection); return MS_SUCCESS; }
dbDriver *create_table(OGRLayerH hLayer, const struct field_info *Fi) { int col, ncols; int sqltype, ogrtype, length; const char *colname; dbDriver *driver; dbHandle handle; dbCursor cursor; dbTable *table; dbColumn *column; dbString sql; OGRFieldDefnH hFieldDefn; OGRFeatureDefnH hFeatureDefn; db_init_string(&sql); db_init_handle(&handle); driver = db_start_driver(Fi->driver); if (!driver) { G_warning(_("Unable to start driver <%s>"), Fi->driver); return NULL; } db_set_handle(&handle, Fi->database, NULL); if (db_open_database(driver, &handle) != DB_OK) { G_warning(_("Unable to open database <%s> by driver <%s>"), Fi->database, Fi->driver); db_close_database_shutdown_driver(driver); return NULL; } /* to get no data */ db_set_string(&sql, "select * from "); db_append_string(&sql, Fi->table); db_append_string(&sql, " where 0 = 1"); if (db_open_select_cursor(driver, &sql, &cursor, DB_SEQUENTIAL) != DB_OK) { G_warning(_("Unable to open select cursor: '%s'"), db_get_string(&sql)); db_close_database_shutdown_driver(driver); return NULL; } table = db_get_cursor_table(&cursor); ncols = db_get_table_number_of_columns(table); hFeatureDefn = OGR_L_GetLayerDefn(hLayer); for (col = 0; col < ncols; col++) { column = db_get_table_column(table, col); colname = db_get_column_name(column); sqltype = db_get_column_sqltype(column); ogrtype = sqltype_to_ogrtype(sqltype); length = db_get_column_length(column); if (strcmp(OGR_L_GetFIDColumn(hLayer), colname) == 0 || OGR_FD_GetFieldIndex(hFeatureDefn, colname) > -1) { /* field already exists */ continue; } hFieldDefn = OGR_Fld_Create(colname, ogrtype); /* GDAL 1.9.0 (r22968) uses VARCHAR instead of CHAR */ if (ogrtype == OFTString && length > 0) OGR_Fld_SetWidth(hFieldDefn, length); if (OGR_L_CreateField(hLayer, hFieldDefn, TRUE) != OGRERR_NONE) { G_warning(_("Creating field <%s> failed"), colname); db_close_database_shutdown_driver(driver); return NULL; } OGR_Fld_Destroy(hFieldDefn); } return driver; }
int main(int argc, char *argv[]) { const char* pszIndexLayerName = NULL; const char *index_filename = NULL; const char *tile_index = "location"; const char* pszDriverName = "ESRI Shapefile"; size_t nMaxFieldSize = 254; int i_arg, ti_field; OGRDataSourceH hTileIndexDS; OGRLayerH hLayer = NULL; OGRFeatureDefnH hFDefn; int write_absolute_path = FALSE; char* current_path = NULL; int i; int nExistingFiles; int skip_different_projection = FALSE; char** existingFilesTab = NULL; int alreadyExistingProjectionRefValid = FALSE; char* alreadyExistingProjectionRef = NULL; const char *pszTargetSRS = ""; int bSetTargetSRS = FALSE; OGRSpatialReferenceH hTargetSRS = NULL; const char* pszSrcSRSName = NULL; int i_SrcSRSName = -1; int bSrcSRSFormatSpecified = FALSE; SrcSRSFormat eSrcSRSFormat = FORMAT_AUTO; /* Check that we are running against at least GDAL 1.4 */ /* Note to developers : if we use newer API, please change the requirement */ if (atoi(GDALVersionInfo("VERSION_NUM")) < 1400) { fprintf(stderr, "At least, GDAL >= 1.4.0 is required for this version of %s, " "which was compiled against GDAL %s\n", argv[0], GDAL_RELEASE_NAME); exit(1); } GDALAllRegister(); OGRRegisterAll(); argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 ); if( argc < 1 ) exit( -argc ); /* -------------------------------------------------------------------- */ /* Get commandline arguments other than the GDAL raster filenames. */ /* -------------------------------------------------------------------- */ for( i_arg = 1; i_arg < argc; i_arg++ ) { if( EQUAL(argv[i_arg], "--utility_version") ) { printf("%s was compiled against GDAL %s and is running against GDAL %s\n", argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME")); return 0; } else if( EQUAL(argv[i_arg],"--help") ) Usage(NULL); else if( strcmp(argv[i_arg],"-f") == 0 ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszDriverName = argv[++i_arg]; if( !EQUAL(pszDriverName, "ESRI Shapefile") ) nMaxFieldSize = 0; } else if( strcmp(argv[i_arg],"-lyr_name") == 0 ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszIndexLayerName = argv[++i_arg]; } else if( strcmp(argv[i_arg],"-tileindex") == 0 ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); tile_index = argv[++i_arg]; } else if( strcmp(argv[i_arg],"-t_srs") == 0 ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszTargetSRS = argv[++i_arg]; bSetTargetSRS = TRUE; } else if ( strcmp(argv[i_arg],"-write_absolute_path") == 0 ) { write_absolute_path = TRUE; } else if ( strcmp(argv[i_arg],"-skip_different_projection") == 0 ) { skip_different_projection = TRUE; } else if( strcmp(argv[i_arg], "-src_srs_name") == 0 ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszSrcSRSName = argv[++i_arg]; } else if( strcmp(argv[i_arg], "-src_srs_format") == 0 ) { const char* pszFormat; bSrcSRSFormatSpecified = TRUE; CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszFormat = argv[++i_arg]; if( EQUAL(pszFormat, "AUTO") ) eSrcSRSFormat = FORMAT_AUTO; else if( EQUAL(pszFormat, "WKT") ) eSrcSRSFormat = FORMAT_WKT; else if( EQUAL(pszFormat, "EPSG") ) eSrcSRSFormat = FORMAT_EPSG; else if( EQUAL(pszFormat, "PROJ") ) eSrcSRSFormat = FORMAT_PROJ; } else if( argv[i_arg][0] == '-' ) Usage(CPLSPrintf("Unknown option name '%s'", argv[i_arg])); else if( index_filename == NULL ) { index_filename = argv[i_arg]; i_arg++; break; } } if( index_filename == NULL ) Usage("No index filename specified."); if( i_arg == argc ) Usage("No file to index specified."); if( bSrcSRSFormatSpecified && pszSrcSRSName == NULL ) Usage("-src_srs_name must be specified when -src_srs_format is specified."); /* -------------------------------------------------------------------- */ /* Create and validate target SRS if given. */ /* -------------------------------------------------------------------- */ if( bSetTargetSRS ) { if ( skip_different_projection ) { fprintf( stderr, "Warning : -skip_different_projection does not apply " "when -t_srs is requested.\n" ); } hTargetSRS = OSRNewSpatialReference(""); if( OSRSetFromUserInput( hTargetSRS, pszTargetSRS ) != CE_None ) { OSRDestroySpatialReference( hTargetSRS ); fprintf( stderr, "Invalid target SRS `%s'.\n", pszTargetSRS ); exit(1); } } /* -------------------------------------------------------------------- */ /* Open or create the target datasource */ /* -------------------------------------------------------------------- */ hTileIndexDS = OGROpen( index_filename, TRUE, NULL ); if (hTileIndexDS != NULL) { if( OGR_DS_GetLayerCount(hTileIndexDS) == 1 ) hLayer = OGR_DS_GetLayer(hTileIndexDS, 0); else { if( pszIndexLayerName == NULL ) { printf( "-lyr_name must be specified.\n" ); exit( 1 ); } CPLPushErrorHandler(CPLQuietErrorHandler); hLayer = OGR_DS_GetLayerByName(hTileIndexDS, pszIndexLayerName); CPLPopErrorHandler(); } } else { OGRSFDriverH hDriver; printf( "Creating new index file...\n" ); hDriver = OGRGetDriverByName( pszDriverName ); if( hDriver == NULL ) { printf( "%s driver not available.\n", pszDriverName ); exit( 1 ); } hTileIndexDS = OGR_Dr_CreateDataSource( hDriver, index_filename, NULL ); } if( hTileIndexDS != NULL && hLayer == NULL ) { OGRSpatialReferenceH hSpatialRef = NULL; char* pszLayerName; if( pszIndexLayerName == NULL ) { VSIStatBuf sStat; if( EQUAL(pszDriverName, "ESRI Shapefile") || VSIStat(index_filename, &sStat) == 0 ) pszLayerName = CPLStrdup(CPLGetBasename(index_filename)); else { printf( "-lyr_name must be specified.\n" ); exit( 1 ); } } else pszLayerName = CPLStrdup(pszIndexLayerName); /* get spatial reference for output file from target SRS (if set) */ /* or from first input file */ if( bSetTargetSRS ) { hSpatialRef = OSRClone( hTargetSRS ); } else { GDALDatasetH hDS = GDALOpen( argv[i_arg], GA_ReadOnly ); if (hDS) { const char* pszWKT = GDALGetProjectionRef(hDS); if (pszWKT != NULL && pszWKT[0] != '\0') { hSpatialRef = OSRNewSpatialReference(pszWKT); } GDALClose(hDS); } } hLayer = OGR_DS_CreateLayer( hTileIndexDS, pszLayerName, hSpatialRef, wkbPolygon, NULL ); CPLFree(pszLayerName); if (hSpatialRef) OSRRelease(hSpatialRef); if (hLayer) { OGRFieldDefnH hFieldDefn = OGR_Fld_Create( tile_index, OFTString ); if( nMaxFieldSize ) OGR_Fld_SetWidth( hFieldDefn, nMaxFieldSize); OGR_L_CreateField( hLayer, hFieldDefn, TRUE ); OGR_Fld_Destroy(hFieldDefn); if( pszSrcSRSName != NULL ) { hFieldDefn = OGR_Fld_Create( pszSrcSRSName, OFTString ); if( nMaxFieldSize ) OGR_Fld_SetWidth( hFieldDefn, nMaxFieldSize); OGR_L_CreateField( hLayer, hFieldDefn, TRUE ); OGR_Fld_Destroy(hFieldDefn); } } } if( hTileIndexDS == NULL || hLayer == NULL ) { fprintf( stderr, "Unable to open/create shapefile `%s'.\n", index_filename ); exit(2); } hFDefn = OGR_L_GetLayerDefn(hLayer); ti_field = OGR_FD_GetFieldIndex( hFDefn, tile_index ); if( ti_field < 0 ) { fprintf( stderr, "Unable to find field `%s' in file `%s'.\n", tile_index, index_filename ); exit(2); } if( pszSrcSRSName != NULL ) i_SrcSRSName = OGR_FD_GetFieldIndex( hFDefn, pszSrcSRSName ); /* Load in memory existing file names in SHP */ nExistingFiles = (int)OGR_L_GetFeatureCount(hLayer, FALSE); if( nExistingFiles < 0) nExistingFiles = 0; if (nExistingFiles > 0) { OGRFeatureH hFeature; existingFilesTab = (char**)CPLMalloc(nExistingFiles * sizeof(char*)); for(i=0;i<nExistingFiles;i++) { hFeature = OGR_L_GetNextFeature(hLayer); existingFilesTab[i] = CPLStrdup(OGR_F_GetFieldAsString( hFeature, ti_field )); if (i == 0) { GDALDatasetH hDS = GDALOpen(existingFilesTab[i], GA_ReadOnly ); if (hDS) { alreadyExistingProjectionRefValid = TRUE; alreadyExistingProjectionRef = CPLStrdup(GDALGetProjectionRef(hDS)); GDALClose(hDS); } } OGR_F_Destroy( hFeature ); } } if (write_absolute_path) { current_path = CPLGetCurrentDir(); if (current_path == NULL) { fprintf( stderr, "This system does not support the CPLGetCurrentDir call. " "The option -write_absolute_path will have no effect\n"); write_absolute_path = FALSE; } } /* -------------------------------------------------------------------- */ /* loop over GDAL files, processing. */ /* -------------------------------------------------------------------- */ for( ; i_arg < argc; i_arg++ ) { GDALDatasetH hDS; double adfGeoTransform[6]; double adfX[5], adfY[5]; int nXSize, nYSize; char* fileNameToWrite; const char* projectionRef; VSIStatBuf sStatBuf; int k; OGRFeatureH hFeature; OGRGeometryH hPoly, hRing; OGRSpatialReferenceH hSourceSRS = NULL; /* Make sure it is a file before building absolute path name */ if (write_absolute_path && CPLIsFilenameRelative( argv[i_arg] ) && VSIStat( argv[i_arg], &sStatBuf ) == 0) { fileNameToWrite = CPLStrdup(CPLProjectRelativeFilename(current_path, argv[i_arg])); } else { fileNameToWrite = CPLStrdup(argv[i_arg]); } /* Checks that file is not already in tileindex */ for(i=0;i<nExistingFiles;i++) { if (EQUAL(fileNameToWrite, existingFilesTab[i])) { fprintf(stderr, "File %s is already in tileindex. Skipping it.\n", fileNameToWrite); break; } } if (i != nExistingFiles) { CPLFree(fileNameToWrite); continue; } hDS = GDALOpen( argv[i_arg], GA_ReadOnly ); if( hDS == NULL ) { fprintf( stderr, "Unable to open %s, skipping.\n", argv[i_arg] ); CPLFree(fileNameToWrite); continue; } GDALGetGeoTransform( hDS, adfGeoTransform ); if( adfGeoTransform[0] == 0.0 && adfGeoTransform[1] == 1.0 && adfGeoTransform[3] == 0.0 && ABS(adfGeoTransform[5]) == 1.0 ) { fprintf( stderr, "It appears no georeferencing is available for\n" "`%s', skipping.\n", argv[i_arg] ); GDALClose( hDS ); CPLFree(fileNameToWrite); continue; } projectionRef = GDALGetProjectionRef(hDS); /* if not set target srs, test that the current file uses same projection as others */ if( !bSetTargetSRS ) { if (alreadyExistingProjectionRefValid) { int projectionRefNotNull, alreadyExistingProjectionRefNotNull; projectionRefNotNull = projectionRef && projectionRef[0]; alreadyExistingProjectionRefNotNull = alreadyExistingProjectionRef && alreadyExistingProjectionRef[0]; if ((projectionRefNotNull && alreadyExistingProjectionRefNotNull && EQUAL(projectionRef, alreadyExistingProjectionRef) == 0) || (projectionRefNotNull != alreadyExistingProjectionRefNotNull)) { fprintf(stderr, "Warning : %s is not using the same projection system as " "other files in the tileindex.\n" "This may cause problems when using it in MapServer for example.\n" "Use -t_srs option to set target projection system (not supported by MapServer).\n" "%s\n", argv[i_arg], (skip_different_projection) ? "Skipping this file." : ""); if (skip_different_projection) { CPLFree(fileNameToWrite); GDALClose( hDS ); continue; } } } else { alreadyExistingProjectionRefValid = TRUE; alreadyExistingProjectionRef = CPLStrdup(projectionRef); } } nXSize = GDALGetRasterXSize( hDS ); nYSize = GDALGetRasterYSize( hDS ); adfX[0] = adfGeoTransform[0] + 0 * adfGeoTransform[1] + 0 * adfGeoTransform[2]; adfY[0] = adfGeoTransform[3] + 0 * adfGeoTransform[4] + 0 * adfGeoTransform[5]; adfX[1] = adfGeoTransform[0] + nXSize * adfGeoTransform[1] + 0 * adfGeoTransform[2]; adfY[1] = adfGeoTransform[3] + nXSize * adfGeoTransform[4] + 0 * adfGeoTransform[5]; adfX[2] = adfGeoTransform[0] + nXSize * adfGeoTransform[1] + nYSize * adfGeoTransform[2]; adfY[2] = adfGeoTransform[3] + nXSize * adfGeoTransform[4] + nYSize * adfGeoTransform[5]; adfX[3] = adfGeoTransform[0] + 0 * adfGeoTransform[1] + nYSize * adfGeoTransform[2]; adfY[3] = adfGeoTransform[3] + 0 * adfGeoTransform[4] + nYSize * adfGeoTransform[5]; adfX[4] = adfGeoTransform[0] + 0 * adfGeoTransform[1] + 0 * adfGeoTransform[2]; adfY[4] = adfGeoTransform[3] + 0 * adfGeoTransform[4] + 0 * adfGeoTransform[5]; if( (bSetTargetSRS || i_SrcSRSName >= 0) && projectionRef != NULL && projectionRef[0] != '\0' ) hSourceSRS = OSRNewSpatialReference( projectionRef ); /* if set target srs, do the forward transformation of all points */ if( bSetTargetSRS && projectionRef != NULL && projectionRef[0] != '\0' ) { OGRCoordinateTransformationH hCT = NULL; if( hSourceSRS && !OSRIsSame( hSourceSRS, hTargetSRS ) ) { hCT = OCTNewCoordinateTransformation( hSourceSRS, hTargetSRS ); if( hCT == NULL || !OCTTransform( hCT, 5, adfX, adfY, NULL ) ) { fprintf( stderr, "Warning : unable to transform points from source SRS `%s' to target SRS `%s'\n" "for file `%s' - file skipped\n", projectionRef, pszTargetSRS, fileNameToWrite ); if ( hCT ) OCTDestroyCoordinateTransformation( hCT ); if ( hSourceSRS ) OSRDestroySpatialReference( hSourceSRS ); continue; } if ( hCT ) OCTDestroyCoordinateTransformation( hCT ); } } hFeature = OGR_F_Create( OGR_L_GetLayerDefn( hLayer ) ); OGR_F_SetFieldString( hFeature, ti_field, fileNameToWrite ); if( i_SrcSRSName >= 0 && hSourceSRS != NULL ) { const char* pszAuthorityCode = OSRGetAuthorityCode(hSourceSRS, NULL); const char* pszAuthorityName = OSRGetAuthorityName(hSourceSRS, NULL); if( eSrcSRSFormat == FORMAT_AUTO ) { if( pszAuthorityName != NULL && pszAuthorityCode != NULL ) OGR_F_SetFieldString( hFeature, i_SrcSRSName, CPLSPrintf("%s:%s", pszAuthorityName, pszAuthorityCode) ); else if( nMaxFieldSize == 0 || strlen(projectionRef) <= nMaxFieldSize ) OGR_F_SetFieldString( hFeature, i_SrcSRSName, projectionRef ); else { char* pszProj4 = NULL; if( OSRExportToProj4(hSourceSRS, &pszProj4) == OGRERR_NONE ) { OGR_F_SetFieldString( hFeature, i_SrcSRSName, pszProj4 ); CPLFree(pszProj4); } else OGR_F_SetFieldString( hFeature, i_SrcSRSName, projectionRef ); } } else if( eSrcSRSFormat == FORMAT_WKT ) { if( nMaxFieldSize == 0 || strlen(projectionRef) <= nMaxFieldSize ) OGR_F_SetFieldString( hFeature, i_SrcSRSName, projectionRef ); } else if( eSrcSRSFormat == FORMAT_PROJ ) { char* pszProj4 = NULL; if( OSRExportToProj4(hSourceSRS, &pszProj4) == OGRERR_NONE ) { OGR_F_SetFieldString( hFeature, i_SrcSRSName, pszProj4 ); CPLFree(pszProj4); } } else if( eSrcSRSFormat == FORMAT_EPSG ) { if( pszAuthorityName != NULL && pszAuthorityCode != NULL ) OGR_F_SetFieldString( hFeature, i_SrcSRSName, CPLSPrintf("%s:%s", pszAuthorityName, pszAuthorityCode) ); } } if( hSourceSRS ) OSRDestroySpatialReference( hSourceSRS ); hPoly = OGR_G_CreateGeometry(wkbPolygon); hRing = OGR_G_CreateGeometry(wkbLinearRing); for(k=0;k<5;k++) OGR_G_SetPoint_2D(hRing, k, adfX[k], adfY[k]); OGR_G_AddGeometryDirectly( hPoly, hRing ); OGR_F_SetGeometryDirectly( hFeature, hPoly ); if( OGR_L_CreateFeature( hLayer, hFeature ) != OGRERR_NONE ) { printf( "Failed to create feature in shapefile.\n" ); break; } OGR_F_Destroy( hFeature ); CPLFree(fileNameToWrite); GDALClose( hDS ); } CPLFree(current_path); if (nExistingFiles) { for(i=0;i<nExistingFiles;i++) { CPLFree(existingFilesTab[i]); } CPLFree(existingFilesTab); } CPLFree(alreadyExistingProjectionRef); if ( hTargetSRS ) OSRDestroySpatialReference( hTargetSRS ); OGR_DS_Destroy( hTileIndexDS ); GDALDestroyDriverManager(); OGRCleanupAll(); CSLDestroy(argv); exit( 0 ); }
int Gdal_Contour(maps*& conf,maps*& inputs,maps*& outputs) #endif { fprintf(stderr,"DEBUG HELLO %f %d\n",__FILE__,__LINE__); fflush(stderr); GDALDatasetH hSrcDS; int i, b3D = FALSE, bNoDataSet = FALSE, bIgnoreNoData = FALSE; int nBandIn = 1; double dfInterval = 0.0, dfNoData = 0.0, dfOffset = 0.0; const char *pszSrcFilename = NULL; const char *pszDstFilename = NULL; const char *pszElevAttrib = NULL; const char *pszFormat = "ESRI Shapefile"; char **papszDSCO = NULL, **papszLCO = NULL; double adfFixedLevels[1000]; int nFixedLevelCount = 0; const char *pszNewLayerName = "contour"; int bQuiet = FALSE; GDALProgressFunc pfnProgress = NULL; fprintf(stderr,"DEBUG HELLO %f %d\n",__FILE__,__LINE__); fflush(stderr); #ifndef ZOO_SERVICE /* Check that we are running against at least GDAL 1.4 */ /* Note to developers : if we use newer API, please change the requirement */ if (atoi(GDALVersionInfo("VERSION_NUM")) < 1400) { fprintf(stderr, "At least, GDAL >= 1.4.0 is required for this version of %s, " "which was compiled against GDAL %s\n", argv[0], GDAL_RELEASE_NAME); exit(1); } #endif GDALAllRegister(); OGRRegisterAll(); #ifndef ZOO_SERVICE argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 ); /* -------------------------------------------------------------------- */ /* Parse arguments. */ /* -------------------------------------------------------------------- */ for( i = 1; i < argc; i++ ) { if( EQUAL(argv[i], "--utility_version") ) { printf("%s was compiled against GDAL %s and is running against GDAL %s\n", argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME")); return 0; } else if( EQUAL(argv[i], "--help") ) Usage(); else if( EQUAL(argv[i],"-a") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszElevAttrib = argv[++i]; } else if( EQUAL(argv[i],"-off") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); dfOffset = atof(argv[++i]); } else if( EQUAL(argv[i],"-i") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); dfInterval = atof(argv[++i]); } else if( EQUAL(argv[i],"-fl") ) { if( i >= argc-1 ) Usage(CPLSPrintf("%s option requires at least 1 argument", argv[i])); while( i < argc-1 && nFixedLevelCount < (int)(sizeof(adfFixedLevels)/sizeof(double)) && ArgIsNumeric(argv[i+1]) ) adfFixedLevels[nFixedLevelCount++] = atof(argv[++i]); } else if( EQUAL(argv[i],"-b") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); nBandIn = atoi(argv[++i]); } else if( EQUAL(argv[i],"-f") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszFormat = argv[++i]; } else if( EQUAL(argv[i],"-dsco") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); papszDSCO = CSLAddString(papszDSCO, argv[++i] ); } else if( EQUAL(argv[i],"-lco") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); papszLCO = CSLAddString(papszLCO, argv[++i] ); } else if( EQUAL(argv[i],"-3d") ) { b3D = TRUE; } else if( EQUAL(argv[i],"-snodata") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); bNoDataSet = TRUE; dfNoData = atof(argv[++i]); } else if( EQUAL(argv[i],"-nln") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszNewLayerName = argv[++i]; } else if( EQUAL(argv[i],"-inodata") ) { bIgnoreNoData = TRUE; } else if ( EQUAL(argv[i],"-q") || EQUAL(argv[i],"-quiet") ) { bQuiet = TRUE; } else if( pszSrcFilename == NULL ) { pszSrcFilename = argv[i]; } else if( pszDstFilename == NULL ) { pszDstFilename = argv[i]; } else Usage("Too many command options."); } #else bQuiet = TRUE; bIgnoreNoData = TRUE; map* tmpMap=NULL; tmpMap=NULL; tmpMap=getMapFromMaps(inputs,"a","value"); if(tmpMap!=NULL && strncmp(tmpMap->value,"NULL",4)!=0){ pszElevAttrib = strdup(tmpMap->value); } tmpMap=getMapFromMaps(inputs,"off","value"); if(tmpMap!=NULL && strncmp(tmpMap->value,"NULL",4)!=0){ dfOffset = atof(tmpMap->value); } tmpMap=getMapFromMaps(inputs,"i","value"); if(tmpMap!=NULL && strncmp(tmpMap->value,"NULL",4)!=0){ dfInterval = atof(tmpMap->value); } tmpMap=getMapFromMaps(inputs,"b","value"); if(tmpMap!=NULL && strncmp(tmpMap->value,"NULL",4)!=0){ nBandIn = atoi(tmpMap->value); } tmpMap=getMapFromMaps(inputs,"InputDSN","value"); if(tmpMap!=NULL && strncmp(tmpMap->value,"NULL",4)!=0){ pszSrcFilename = strdup(tmpMap->value); } tmpMap=getMapFromMaps(inputs,"OutputDSN","value"); if(tmpMap!=NULL && strncmp(tmpMap->value,"NULL",4)!=0){ pszDstFilename = strdup(tmpMap->value); } #endif if( dfInterval == 0.0 && nFixedLevelCount == 0 ) { Usage("Neither -i nor -fl are specified."); } if (pszSrcFilename == NULL) { Usage("Missing source filename."); } if (pszDstFilename == NULL) { Usage("Missing destination filename."); } if (!bQuiet) pfnProgress = GDALTermProgress; /* -------------------------------------------------------------------- */ /* Open source raster file. */ /* -------------------------------------------------------------------- */ GDALRasterBandH hBand; hSrcDS = GDALOpen( pszSrcFilename, GA_ReadOnly ); if( hSrcDS == NULL ){ #ifndef ZOO_SERVICE exit( 2 ); #else setMapInMaps(conf,"lenv","message","Unable to open the file"); #endif } hBand = GDALGetRasterBand( hSrcDS, nBandIn ); if( hBand == NULL ) { #ifndef ZOO_SERVICE CPLError( CE_Failure, CPLE_AppDefined, "Band %d does not exist on dataset.", nBandIn ); exit(2); #else char tmp[1024]; sprintf(tmp,"Band %d does not exist on dataset.",nBandIn); setMapInMaps(conf,"lenv","message",tmp); return SERVICE_FAILED; #endif } if( !bNoDataSet && !bIgnoreNoData ) dfNoData = GDALGetRasterNoDataValue( hBand, &bNoDataSet ); /* -------------------------------------------------------------------- */ /* Try to get a coordinate system from the raster. */ /* -------------------------------------------------------------------- */ OGRSpatialReferenceH hSRS = NULL; const char *pszWKT = GDALGetProjectionRef( hSrcDS ); if( pszWKT != NULL && strlen(pszWKT) != 0 ) hSRS = OSRNewSpatialReference( pszWKT ); /* -------------------------------------------------------------------- */ /* Create the outputfile. */ /* -------------------------------------------------------------------- */ OGRDataSourceH hDS; OGRSFDriverH hDriver = OGRGetDriverByName( pszFormat ); OGRFieldDefnH hFld; OGRLayerH hLayer; if( hDriver == NULL ) { #ifndef ZOO_SERVICE fprintf( stderr, "Unable to find format driver named %s.\n", pszFormat ); exit( 10 ); #else char tmp[1024]; sprintf( tmp, "Unable to find format driver named %s.\n", pszFormat ); setMapInMaps(conf,"lenv","message",tmp); return SERVICE_FAILED; #endif } hDS = OGR_Dr_CreateDataSource( hDriver, pszDstFilename, papszDSCO ); if( hDS == NULL ){ #ifndef ZOO_SERVICE exit( 1 ); #else setMapInMaps(conf,"lenv","message","Unable to create the file"); return SERVICE_FAILED; #endif } hLayer = OGR_DS_CreateLayer( hDS, pszNewLayerName, hSRS, b3D ? wkbLineString25D : wkbLineString, papszLCO ); if( hLayer == NULL ) exit( 1 ); hFld = OGR_Fld_Create( "ID", OFTInteger ); OGR_Fld_SetWidth( hFld, 8 ); OGR_L_CreateField( hLayer, hFld, FALSE ); OGR_Fld_Destroy( hFld ); if( pszElevAttrib ) { hFld = OGR_Fld_Create( pszElevAttrib, OFTReal ); OGR_Fld_SetWidth( hFld, 12 ); OGR_Fld_SetPrecision( hFld, 3 ); OGR_L_CreateField( hLayer, hFld, FALSE ); OGR_Fld_Destroy( hFld ); } /* -------------------------------------------------------------------- */ /* Invoke. */ /* -------------------------------------------------------------------- */ CPLErr eErr; eErr = GDALContourGenerate( hBand, dfInterval, dfOffset, nFixedLevelCount, adfFixedLevels, bNoDataSet, dfNoData, hLayer, OGR_FD_GetFieldIndex( OGR_L_GetLayerDefn( hLayer ), "ID" ), (pszElevAttrib == NULL) ? -1 : OGR_FD_GetFieldIndex( OGR_L_GetLayerDefn( hLayer ), pszElevAttrib ), pfnProgress, NULL ); OGR_DS_Destroy( hDS ); GDALClose( hSrcDS ); if (hSRS) OSRDestroySpatialReference( hSRS ); #ifndef ZOO_SERVICE CSLDestroy( argv ); CSLDestroy( papszDSCO ); CSLDestroy( papszLCO ); GDALDestroyDriverManager(); OGRCleanupAll(); return 0; #else GDALDestroyDriverManager(); OGRCleanupAll(); char tmp[1024]; sprintf(tmp,"File %s successfully created.",pszDstFilename); setMapInMaps(outputs,"Result","value",tmp); return SERVICE_SUCCEEDED; #endif }
int db__driver_execute_immediate(dbString * sql) { char *where, *table; int res, ncols, i; column_info *cols; OGRLayerH hLayer; OGRFeatureH hFeature; OGRFeatureDefnH hFeatureDefn; OGRFieldDefnH hFieldDefn; G_debug(1, "db__driver_execute_immediate():"); G_debug(3, "\tSQL: '%s'", db_get_string(sql)); /* try RDBMS SQL */ OGR_DS_ExecuteSQL(hDs, db_get_string(sql), NULL, NULL); if (CPLGetLastErrorType() == CE_None) return DB_OK; /* parse UPDATE statement */ res = parse_sql_update(db_get_string(sql), &table, &cols, &ncols, &where); G_debug(3, "\tUPDATE: table=%s, where=%s, ncols=%d", table, where ? where : "", ncols); if (res != 0) return DB_FAILED; /* get OGR layer */ hLayer = OGR_DS_GetLayerByName(hDs, table); if (!hLayer) { db_d_append_error(_("OGR layer <%s> not found"), table); db_d_report_error(); return DB_FAILED; } if (where) OGR_L_SetAttributeFilter(hLayer, where); /* get columns info */ hFeatureDefn = OGR_L_GetLayerDefn(hLayer); for (i = 0; i < ncols; i++) { cols[i].index = OGR_FD_GetFieldIndex(hFeatureDefn, cols[i].name); if (cols[i].index < 0) { db_d_append_error(_("Column <%s> not found in table <%s>"), cols[i].name, table); db_d_report_error(); return DB_FAILED; } cols[i].qindex = OGR_FD_GetFieldIndex(hFeatureDefn, cols[i].value); hFieldDefn = OGR_FD_GetFieldDefn(hFeatureDefn, cols[i].index); cols[i].type = OGR_Fld_GetType(hFieldDefn); G_debug(3, "\t\tcol=%s, val=%s, idx=%d, type=%d, qidx=%d", cols[i].name, cols[i].value, cols[i].index, cols[i].type, cols[i].qindex); } /* update features */ OGR_L_ResetReading(hLayer); while(TRUE) { char *value; hFeature = OGR_L_GetNextFeature(hLayer); if (!hFeature) break; G_debug(5, "\tfid=%ld", OGR_F_GetFID(hFeature)); for (i = 0; i < ncols; i++) { if (cols[i].qindex > -1) { value = (char *)OGR_F_GetFieldAsString(hFeature, cols[i].qindex); } else { if ((cols[i].type != OFTInteger || cols[i].type != OFTReal) && *(cols[i].value) == '\'') { value = G_strchg(cols[i].value, '\'', ' '); G_strip(value); } else { value = cols[i].value; } } OGR_F_SetFieldString(hFeature, cols[i].index, value); } OGR_L_SetFeature(hLayer, hFeature); OGR_F_Destroy(hFeature); } G_free(table); G_free(where); for (i = 0; i < ncols; i++) { G_free(cols[i].name); G_free(cols[i].value); } return DB_OK; }