void OGR::writeDensity(hexer::HexGrid *grid) { int counter(0); for (hexer::HexIter iter = grid->hexBegin(); iter != grid->hexEnd(); ++iter) { hexer::HexInfo hi = *iter; OGRGeometryH polygon = collectHexagon(hi, grid); OGRFeatureH hFeature; hFeature = OGR_F_Create(OGR_L_GetLayerDefn(m_layer)); OGR_F_SetFieldInteger( hFeature, OGR_F_GetFieldIndex(hFeature, "ID"), counter); OGR_F_SetFieldInteger( hFeature, OGR_F_GetFieldIndex(hFeature, "COUNT"), hi.m_density); OGR_F_SetGeometry(hFeature, polygon); OGR_G_DestroyGeometry(polygon); if( OGR_L_CreateFeature( m_layer, hFeature ) != OGRERR_NONE ) { std::ostringstream oss; oss << "Unable to create feature for multipolygon with error '" << CPLGetLastErrorMsg() << "'"; throw pdal::pdal_error(oss.str()); } OGR_F_Destroy( hFeature ); counter++; } }
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); }
void OGR::writeBoundary(hexer::HexGrid *grid) { OGRGeometryH multi = OGR_G_CreateGeometry(wkbMultiPolygon); const std::vector<hexer::Path *>& paths = grid->rootPaths(); for (auto pi = paths.begin(); pi != paths.end(); ++pi) { OGRGeometryH polygon = OGR_G_CreateGeometry(wkbPolygon); collectPath(*pi, polygon); if( OGR_G_AddGeometryDirectly(multi, polygon ) != OGRERR_NONE ) { std::ostringstream oss; oss << "Unable to add polygon to multipolygon with error '" << CPLGetLastErrorMsg() << "'"; throw pdal::pdal_error(oss.str()); } } OGRFeatureH hFeature; hFeature = OGR_F_Create(OGR_L_GetLayerDefn(m_layer)); OGR_F_SetFieldInteger( hFeature, OGR_F_GetFieldIndex(hFeature, "ID"), 0); OGR_F_SetGeometry(hFeature, multi); OGR_G_DestroyGeometry(multi); if( OGR_L_CreateFeature( m_layer, hFeature ) != OGRERR_NONE ) { std::ostringstream oss; oss << "Unable to create feature for multipolygon with error '" << CPLGetLastErrorMsg() << "'"; throw pdal::pdal_error(oss.str()); } OGR_F_Destroy( hFeature ); }
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); }
int main(int argc, char* argv[]) { int rc = 0; #ifdef HAVE_GDAL try { ::OGRRegisterAll(); // Parse command-line options std::string in_file; std::string out_file; std::string out_frmt; { int on_arg = 1; while (on_arg < argc) { std::string arg(argv[on_arg]); if (arg == "-h") { usage(); return 0; } else if (arg == "-formats") { report_ogr_formats(std::cout); return 0; } else if (arg == "-i" && (on_arg + 1 < argc)) { ++on_arg; assert(on_arg < argc); in_file = argv[on_arg]; } else if (arg == "-o" && (on_arg + 1 < argc)) { ++on_arg; assert(on_arg < argc); out_file = argv[on_arg]; out_frmt = "ESRI Shapefile"; // default output format } else if (arg == "-f" && (on_arg + 1 < argc)) { ++on_arg; assert(on_arg < argc); out_frmt = argv[on_arg]; } else { throw std::runtime_error(std::string("unrecognized parameter: ") + arg); } ++on_arg; } if (in_file.empty() || out_file.empty() || out_frmt.empty()) { throw std::runtime_error("missing input paremeters"); } } // // Source // std::cout << "Source:" << "\n - dataset: " << in_file << std::endl; std::ifstream ifs; if (!liblas::Open(ifs, in_file.c_str())) { throw std::runtime_error(std::string("Can not open \'") + in_file + "\'"); } liblas::Reader reader(ifs); // // Target // std::string const lyrname(out_file.substr(0, out_file.find_last_of('.'))); std::cout << "Target:" << "\n - format: " << out_frmt << "\n - dataset: " << out_file << "\n - layer: " << lyrname << std::endl; OGRSFDriverH drv = OGRGetDriverByName(out_frmt.c_str()); if (0 == drv) { throw std::runtime_error(out_frmt + " driver not available"); } ogr_wrapper<OGRDataSourceH> ds(OGR_Dr_CreateDataSource(drv, out_file.c_str(), 0), OGR_DS_Destroy); if (0 == ds.get()) { throw std::runtime_error(out_file + " datasource creation failed"); } OGRLayerH lyr = OGR_DS_CreateLayer(ds, lyrname.c_str(), 0, wkbPoint25D, 0); if (0 == lyr) { throw std::runtime_error(out_file + " layer creation failed"); } // Prepare layer schema create_layer_def(lyr); // // Translation of points cloud to features set // boost::uint32_t i = 0; boost::uint32_t const size = reader.GetHeader().GetPointRecordsCount(); std::cout << "Translating " << size << " points:\n"; ogr_wrapper<OGRFeatureH> feat(OGR_F_Create(OGR_L_GetLayerDefn(lyr)), OGR_F_Destroy); while (reader.ReadNextPoint()) { liblas::Point const& p = reader.GetPoint(); OGR_F_SetFieldInteger(feat, 0, p.GetReturnNumber()); OGR_F_SetFieldInteger(feat, 1, p.GetScanAngleRank()); OGR_F_SetFieldInteger(feat, 2, p.GetIntensity()); std::ostringstream os; os << p.GetClassification(); OGR_F_SetFieldString(feat, 3, os.str().c_str()); OGR_F_SetFieldInteger(feat, 4, p.GetNumberOfReturns()); OGR_F_SetFieldDouble(feat, 5, p.GetTime()); ogr_wrapper<OGRGeometryH> geom(OGR_G_CreateGeometry(wkbPoint25D), OGR_G_DestroyGeometry); OGR_G_SetPoint(geom, 0, p.GetX(), p.GetY(), p.GetZ()); if (OGRERR_NONE != OGR_F_SetGeometry(feat, geom)) { throw std::runtime_error("geometry creation failed"); } if (OGRERR_NONE != OGR_L_CreateFeature(lyr, feat)) { throw std::runtime_error("feature creation failed"); } term_progress(std::cout, (i + 1) / static_cast<double>(size)); i++; } std::cout << std::endl; } catch (std::exception const& e) { std::cerr << "Error: " << e.what() << std::endl; rc = -1; } catch (...) { std::cerr << "Unknown error\n"; rc = -1; } #else std::cout << "Missing GDAL/OGR support built-in las2ogr. Aborted." << std::endl; #endif // #ifdef HAVE_GDAL ::OGRCleanupAll(); return rc; }
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 ); }
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; }
int tindex(maps*& conf, maps*& inputs,maps*& outputs) { char *index_filename = NULL; const char *tile_index = "location"; 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; char* index_filename_mod; int bExists; VSIStatBuf sStatBuf; /* 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) { char tmp[1024]; sprintf(tmp, "At least, GDAL >= 1.4.0 is required for this version of" "tindex, which was compiled against GDAL %s\n", GDAL_RELEASE_NAME); return SERVICE_FAILED; } GDALAllRegister(); OGRRegisterAll(); /* -------------------------------------------------------------------- */ /* Get the directory name to search for raster file to index. */ /* -------------------------------------------------------------------- */ char *tmpDataDir; char *pszDataDir; map* tmpMap=getMapFromMaps(conf,"main","isTrial"); map* tmpMap1=getMapFromMaps(conf,"main","dataPath"); map* tmpInputMap=getMapFromMaps(inputs,"dir","value"); if(tmpMap!=NULL && strcasecmp(tmpMap->value,"true")==0){ pszDataDir=(char*) malloc((strlen(tmpInputMap->value)+strlen(tmpMap1->value)+5+1)*sizeof(char)); sprintf(pszDataDir,"%s/ftp/%s",tmpMap1->value,tmpInputMap->value); }else{ pszDataDir=(char*) malloc(((strlen(tmpInputMap->value)+1)*sizeof(char))); sprintf(pszDataDir,"%s",tmpInputMap->value); } tmpMap=getMapFromMaps(inputs,"iname","value"); tmpMap1=getMapFromMaps(inputs,"idir","value"); map* tmpMap2=getMapFromMaps(conf,"main","dataPath"); if(tmpMap!=NULL && tmpMap1!=NULL && tmpMap2!=NULL){ index_filename = (char*) malloc((strlen(tmpMap->value)+strlen(tmpMap1->value)+strlen(tmpMap2->value)+12)*sizeof(char)); sprintf(index_filename,"%s/dirs/%s/%s.shp",tmpMap2->value,tmpMap1->value,tmpMap->value); } fprintf(stderr,"Filename %s\n",index_filename); /* -------------------------------------------------------------------- */ /* Open or create the target shapefile and DBF file. */ /* -------------------------------------------------------------------- */ index_filename_mod = CPLStrdup(CPLResetExtension(index_filename, "shp")); bExists = (VSIStat(index_filename_mod, &sStatBuf) == 0); if (!bExists) { CPLFree(index_filename_mod); index_filename_mod = CPLStrdup(CPLResetExtension(index_filename, "SHP")); bExists = (VSIStat(index_filename_mod, &sStatBuf) == 0); } CPLFree(index_filename_mod); if (bExists) { hTileIndexDS = OGROpen( index_filename, TRUE, NULL ); if (hTileIndexDS != NULL) { hLayer = OGR_DS_GetLayer(hTileIndexDS, 0); } } else { OGRSFDriverH hDriver; const char* pszDriverName = "ESRI Shapefile"; fprintf( stderr,"Creating new index file...\n" ); hDriver = OGRGetDriverByName( pszDriverName ); if( hDriver == NULL ) { char msg[1024]; sprintf( msg, "%s driver not available.", pszDriverName ); setMapInMaps(conf,"lenv","message",msg); return SERVICE_FAILED; } hTileIndexDS = OGR_Dr_CreateDataSource( hDriver, index_filename, NULL ); if (hTileIndexDS) { char* pszLayerName = CPLStrdup(CPLGetBasename(index_filename)); OGRSpatialReferenceH hSpatialRef = NULL; GDALDatasetH hDS = GDALOpen( index_filename, GA_ReadOnly ); if (hDS) { const char* pszWKT = GDALGetProjectionRef(hDS); if (pszWKT != NULL && pszWKT[0] != '\0') { hSpatialRef = OSRNewSpatialReference(pszWKT); } GDALClose(hDS); } DIR *dirp = opendir(pszDataDir); if(dirp==NULL){ char tmp1[1024]; sprintf(tmp1,_ss("The specified path %s doesn't exist."),pszDataDir); setMapInMaps(conf,"lenv","message",tmp1); return SERVICE_FAILED; } char *res=NULL; struct dirent *dp; tmpMap=getMapFromMaps(inputs,"ext","value"); char *ext; if(tmpMap!=NULL) ext=tmpMap->value; while ((dp = readdir(dirp)) != NULL){ if(strncmp(dp->d_name,".",1)!=0&&strncmp(dp->d_name,"..",2)!=0){ char* argv=(char*) malloc((strlen(dp->d_name)+strlen(pszDataDir)+2)*sizeof(char)); sprintf(argv,"%s/%s",pszDataDir,dp->d_name); GDALDatasetH hDS0 = GDALOpen( argv, GA_ReadOnly ); if (hDS0) { const char* pszWKT = GDALGetProjectionRef(hDS0); fprintf(stderr,"SRS %s \n",pszWKT); if (pszWKT != NULL && pszWKT[0] != '\0') { if (hSpatialRef) OSRRelease(hSpatialRef); hSpatialRef = OSRNewSpatialReference(pszWKT); } GDALClose(hDS); } break; } } closedir(dirp); 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 ); OGR_Fld_SetWidth( hFieldDefn, 255); OGR_L_CreateField( hLayer, hFieldDefn, TRUE ); OGR_Fld_Destroy(hFieldDefn); } } } if( hTileIndexDS == NULL || hLayer == NULL ) { char msg[1024]; sprintf( msg, "Unable to open/create shapefile `%s'.", index_filename ); setMapInMaps(conf,"lenv","message",msg); } hFDefn = OGR_L_GetLayerDefn(hLayer); for( ti_field = 0; ti_field < OGR_FD_GetFieldCount(hFDefn); ti_field++ ) { OGRFieldDefnH hFieldDefn = OGR_FD_GetFieldDefn( hFDefn, ti_field ); if( strcmp(OGR_Fld_GetNameRef(hFieldDefn), tile_index) == 0 ) break; } if( ti_field == OGR_FD_GetFieldCount(hFDefn) ) { char msg[1024]; sprintf( msg, "Unable to find field `%s' in DBF file `%s'.\n", tile_index, index_filename ); setMapInMaps(conf,"lenv","message",msg); return SERVICE_FAILED; } /* Load in memory existing file names in SHP */ nExistingFiles = OGR_L_GetFeatureCount(hLayer, FALSE); if (nExistingFiles) { 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. */ /* -------------------------------------------------------------------- */ DIR *dirp = opendir(pszDataDir); if(dirp==NULL){ char tmp1[1024]; sprintf(tmp1,_ss("The specified path %s doesn't exist."),pszDataDir); setMapInMaps(conf,"lenv","message",tmp1); return SERVICE_FAILED; } char *res=NULL; struct dirent *dp; tmpMap=getMapFromMaps(inputs,"ext","value"); char *ext; if(tmpMap!=NULL) ext=tmpMap->value; while ((dp = readdir(dirp)) != NULL){ if(strlen(dp->d_name)>2 && strstr(dp->d_name,".")!=0 && strstr(dp->d_name,ext)>0){ char* argv=(char*) malloc((strlen(dp->d_name)+strlen(pszDataDir)+2)*sizeof(char)); sprintf(argv,"%s/%s",pszDataDir,dp->d_name); 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; /* Make sure it is a file before building absolute path name */ if (write_absolute_path && CPLIsFilenameRelative( argv ) && VSIStat( argv, &sStatBuf ) == 0) { fileNameToWrite = CPLStrdup(CPLProjectRelativeFilename(current_path, argv)); } else { fileNameToWrite = CPLStrdup(argv); } /* 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, GA_ReadOnly ); if( hDS == NULL ) { fprintf( stderr, "Unable to open %s, skipping.\n", argv ); 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 ); GDALClose( hDS ); CPLFree(fileNameToWrite); continue; } projectionRef = GDALGetProjectionRef(hDS); 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. This may cause problems when " "using it in MapServer for example.%s\n", argv, (skip_different_projection) ? " Skipping it" : ""); 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]; hFeature = OGR_F_Create( OGR_L_GetLayerDefn( hLayer ) ); OGR_F_SetFieldString( hFeature, ti_field, fileNameToWrite ); 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 ) { fprintf( stderr, "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); OGR_DS_Destroy( hTileIndexDS ); GDALDestroyDriverManager(); OGRCleanupAll(); setMapInMaps(outputs,"Result","value","Tile index successfully created."); //CSLDestroy(argv); return SERVICE_SUCCEEDED; }
static CPLErr EmitPolygonToLayer( OGRLayerH hOutLayer, int iPixValField, RPolygonF *poRPoly, double *padfGeoTransform ) { OGRFeatureH hFeat; OGRGeometryH hPolygon; /* -------------------------------------------------------------------- */ /* Turn bits of lines into coherent rings. */ /* -------------------------------------------------------------------- */ poRPoly->Coalesce(); /* -------------------------------------------------------------------- */ /* Create the polygon geometry. */ /* -------------------------------------------------------------------- */ size_t iString; hPolygon = OGR_G_CreateGeometry( wkbPolygon ); for( iString = 0; iString < poRPoly->aanXY.size(); iString++ ) { std::vector<int> &anString = poRPoly->aanXY[iString]; OGRGeometryH hRing = OGR_G_CreateGeometry( wkbLinearRing ); int iVert; // we go last to first to ensure the linestring is allocated to // the proper size on the first try. for( iVert = anString.size()/2 - 1; iVert >= 0; iVert-- ) { double dfX, dfY; int nPixelX, nPixelY; nPixelX = anString[iVert*2]; nPixelY = anString[iVert*2+1]; dfX = padfGeoTransform[0] + nPixelX * padfGeoTransform[1] + nPixelY * padfGeoTransform[2]; dfY = padfGeoTransform[3] + nPixelX * padfGeoTransform[4] + nPixelY * padfGeoTransform[5]; OGR_G_SetPoint_2D( hRing, iVert, dfX, dfY ); } OGR_G_AddGeometryDirectly( hPolygon, hRing ); } /* -------------------------------------------------------------------- */ /* Create the feature object. */ /* -------------------------------------------------------------------- */ hFeat = OGR_F_Create( OGR_L_GetLayerDefn( hOutLayer ) ); OGR_F_SetGeometryDirectly( hFeat, hPolygon ); if( iPixValField >= 0 ) OGR_F_SetFieldDouble( hFeat, iPixValField, (double)poRPoly->fPolyValue ); /* -------------------------------------------------------------------- */ /* Write the to the layer. */ /* -------------------------------------------------------------------- */ CPLErr eErr = CE_None; if( OGR_L_CreateFeature( hOutLayer, hFeat ) != OGRERR_NONE ) eErr = CE_Failure; OGR_F_Destroy( hFeat ); return eErr; }
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; }
int create_grid(char *infile, char *outfile, int gridsize, char *format, char *layer) { OGRSFDriverH out_driver; OGRDataSourceH out_ds; OGRLayerH out_layer; OGRFieldDefnH field; OGRFeatureH feat; OGRGeometryH geom; morph *mgrid; int xstep, ystep, step; double topleftx, toplefty, weres, nsres, rot1, rot2; int i,j, fid, row, col; OGRRegisterAll(); // Read the morph grid file. mgrid = read_grid(infile); if (mgrid == NULL) { fprintf(stderr, "Error. Unable to read input morph file '%s'.\n", infile); exit(1); } // Create the ouptut layer. out_driver = OGRGetDriverByName(format); if (out_driver == NULL) { fprintf(stderr, "Error. Driver for format '%s' not available.\n", format); exit(1); } out_ds = OGR_Dr_CreateDataSource(out_driver, outfile, NULL); if (out_ds == NULL) { fprintf(stderr, "Error. Unable to create output data source.\n"); exit(1); } out_layer = OGR_DS_CreateLayer(out_ds, layer, NULL, wkbLineString, NULL); if (out_layer == NULL) { fprintf(stderr, "Error. Unable to create output layer.\n"); exit(1); } // Add the attributes to the new layer. field = OGR_Fld_Create("ID", OFTInteger); OGR_Fld_SetWidth(field, 11); if (OGR_L_CreateField(out_layer, field, TRUE) != OGRERR_NONE) { fprintf(stderr, "Error. Creating ID attribute failed.\n"); exit(1); } OGR_Fld_Destroy(field); field = OGR_Fld_Create("ROW", OFTInteger); OGR_Fld_SetWidth(field, 6); if (OGR_L_CreateField(out_layer, field, TRUE) != OGRERR_NONE) { fprintf(stderr, "Error. Creating ROW attribute failed.\n"); exit(1); } OGR_Fld_Destroy(field); field = OGR_Fld_Create("COL", OFTInteger); OGR_Fld_SetWidth(field, 6); if (OGR_L_CreateField(out_layer, field, TRUE) != OGRERR_NONE) { fprintf(stderr, "Error. Creating COL attribute failed.\n"); exit(1); } OGR_Fld_Destroy(field); // Compute the step size. xstep = mgrid->xsize / gridsize; if (xstep < 1) { xstep = 1; } if (xstep > (mgrid->xsize / 2)) { xstep = mgrid->xsize / 2; } ystep = mgrid->ysize / gridsize; if (ystep < 1) { ystep = 1; } if (ystep > (mgrid->ysize / 2)) { ystep = mgrid->ysize / 2; } if (xstep < ystep) { step = ystep; } else { step = xstep; } // Read the georeference topleftx = mgrid->georef[0]; weres = mgrid->georef[1]; rot1 = mgrid->georef[2]; toplefty = mgrid->georef[3]; rot2 = mgrid->georef[4]; nsres = mgrid->georef[5]; // Write all horizontal lines. fid = 1; row = 1; for (j = 0; j < mgrid->ysize; j += step) { // Create a new Feature with the projected coordinates. feat = OGR_F_Create(OGR_L_GetLayerDefn(out_layer)); OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "ID"), fid); OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "ROW"), row); OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "COL"), 0); // Create a new geometry object. geom = OGR_G_CreateGeometry(wkbLineString); for (i = 0; i < mgrid->xsize; i++) { OGR_G_SetPoint_2D( geom, i, topleftx + mgrid->x[i][j]*weres + mgrid->y[i][j]*rot1, toplefty + mgrid->x[i][j]*rot2 + mgrid->y[i][j]*nsres); } OGR_F_SetGeometry(feat, geom); OGR_G_DestroyGeometry(geom); // Write the feature to the output vector layer. if (OGR_L_CreateFeature(out_layer, feat) != OGRERR_NONE) { fprintf(stderr, "Error. Unable to create new feature.\n"); exit(1); } OGR_F_Destroy(feat); row++; fid++; } // Write all vertical lines. col = 1; for (i = 0; i < mgrid->xsize; i += step) { // Create a new Feature with the projected coordinates. feat = OGR_F_Create(OGR_L_GetLayerDefn(out_layer)); OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "ID"), fid); OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "ROW"), 0); OGR_F_SetFieldInteger(feat, OGR_F_GetFieldIndex(feat, "COL"), col); // Create a new geometry object. geom = OGR_G_CreateGeometry(wkbLineString); for (j = 0; j < mgrid->ysize; j++) { OGR_G_SetPoint_2D( geom, j, topleftx + mgrid->x[i][j]*weres + mgrid->y[i][j]*rot1, toplefty + mgrid->x[i][j]*rot2 + mgrid->y[i][j]*nsres); } OGR_F_SetGeometry(feat, geom); OGR_G_DestroyGeometry(geom); // Write the feature to the output vector layer. if (OGR_L_CreateFeature(out_layer, feat) != OGRERR_NONE) { fprintf(stderr, "Error. Unable to create new feature.\n"); exit(1); } OGR_F_Destroy(feat); col++; fid++; } // Close the datasources and free the memory. OGR_DS_Destroy(out_ds); free_morph(mgrid); return 0; }
static CPLErr OGRPolygonContourWriter( double dfLevelMin, double dfLevelMax, const OGRMultiPolygon& multipoly, void *pInfo ) { OGRContourWriterInfo *poInfo = static_cast<OGRContourWriterInfo *>(pInfo); OGRFeatureDefnH hFDefn = OGR_L_GetLayerDefn( static_cast<OGRLayerH>(poInfo->hLayer) ); OGRFeatureH hFeat = OGR_F_Create( hFDefn ); if( poInfo->nIDField != -1 ) OGR_F_SetFieldInteger( hFeat, poInfo->nIDField, poInfo->nNextID++ ); if( poInfo->nElevFieldMin != -1 ) OGR_F_SetFieldDouble( hFeat, poInfo->nElevFieldMin, dfLevelMin ); if( poInfo->nElevFieldMax != -1 ) OGR_F_SetFieldDouble( hFeat, poInfo->nElevFieldMax, dfLevelMax ); const bool bHasZ = wkbHasZ(OGR_FD_GetGeomType(hFDefn)); OGRGeometryH hGeom = OGR_G_CreateGeometry( bHasZ ? wkbMultiPolygon25D : wkbMultiPolygon ); for ( int iPart = 0; iPart < multipoly.getNumGeometries(); iPart++ ) { OGRPolygon* poNewPoly = new OGRPolygon(); const OGRPolygon* poPolygon = static_cast<const OGRPolygon*>(multipoly.getGeometryRef(iPart)); for ( int iRing = 0; iRing < poPolygon->getNumInteriorRings() + 1; iRing++ ) { const OGRLinearRing* poRing = iRing == 0 ? poPolygon->getExteriorRing() : poPolygon->getInteriorRing(iRing - 1); OGRLinearRing* poNewRing = new OGRLinearRing(); for ( int iPoint = 0; iPoint < poRing->getNumPoints(); iPoint++ ) { const double dfX = poInfo->adfGeoTransform[0] + poInfo->adfGeoTransform[1] * poRing->getX(iPoint) + poInfo->adfGeoTransform[2] * poRing->getY(iPoint); const double dfY = poInfo->adfGeoTransform[3] + poInfo->adfGeoTransform[4] * poRing->getX(iPoint) + poInfo->adfGeoTransform[5] * poRing->getY(iPoint); if( bHasZ ) OGR_G_SetPoint( OGRGeometry::ToHandle( poNewRing ), iPoint, dfX, dfY, dfLevelMax ); else OGR_G_SetPoint_2D( OGRGeometry::ToHandle( poNewRing ), iPoint, dfX, dfY ); } poNewPoly->addRingDirectly( poNewRing ); } OGR_G_AddGeometryDirectly( hGeom, OGRGeometry::ToHandle( poNewPoly ) ); } OGR_F_SetGeometryDirectly( hFeat, hGeom ); const OGRErr eErr = OGR_L_CreateFeature(static_cast<OGRLayerH>(poInfo->hLayer), hFeat); OGR_F_Destroy( hFeat ); return eErr == OGRERR_NONE ? CE_None : CE_Failure; }
int main(int argc, char *argv[]) { const char *index_filename = NULL; const char *tile_index = "location"; 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; char* index_filename_mod; int bExists; VSIStatBuf sStatBuf; const char *pszTargetSRS = ""; int bSetTargetSRS = FALSE; OGRSpatialReferenceH hTargetSRS = NULL; /* 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( strcmp(argv[i_arg],"-tileindex") == 0 ) { tile_index = argv[++i_arg]; } else if( strcmp(argv[i_arg],"-t_srs") == 0 ) { 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( argv[i_arg][0] == '-' ) Usage(); else if( index_filename == NULL ) { index_filename = argv[i_arg]; i_arg++; break; } } if( index_filename == NULL || i_arg == argc ) Usage(); /* -------------------------------------------------------------------- */ /* 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 shapefile and DBF file. */ /* -------------------------------------------------------------------- */ index_filename_mod = CPLStrdup(CPLResetExtension(index_filename, "shp")); bExists = (VSIStat(index_filename_mod, &sStatBuf) == 0); if (!bExists) { CPLFree(index_filename_mod); index_filename_mod = CPLStrdup(CPLResetExtension(index_filename, "SHP")); bExists = (VSIStat(index_filename_mod, &sStatBuf) == 0); } CPLFree(index_filename_mod); if (bExists) { hTileIndexDS = OGROpen( index_filename, TRUE, NULL ); if (hTileIndexDS != NULL) { hLayer = OGR_DS_GetLayer(hTileIndexDS, 0); } } else { OGRSFDriverH hDriver; const char* pszDriverName = "ESRI Shapefile"; 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) { char* pszLayerName = CPLStrdup(CPLGetBasename(index_filename)); /* get spatial reference for output file from target SRS (if set) */ /* or from first input file */ OGRSpatialReferenceH hSpatialRef = NULL; 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 ); OGR_Fld_SetWidth( hFieldDefn, 255); 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); for( ti_field = 0; ti_field < OGR_FD_GetFieldCount(hFDefn); ti_field++ ) { OGRFieldDefnH hFieldDefn = OGR_FD_GetFieldDefn( hFDefn, ti_field ); if( strcmp(OGR_Fld_GetNameRef(hFieldDefn), tile_index) == 0 ) break; } if( ti_field == OGR_FD_GetFieldCount(hFDefn) ) { fprintf( stderr, "Unable to find field `%s' in DBF file `%s'.\n", tile_index, index_filename ); exit(2); } /* Load in memory existing file names in SHP */ nExistingFiles = OGR_L_GetFeatureCount(hLayer, FALSE); if (nExistingFiles) { 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; /* 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 set target srs, do the forward transformation of all points */ if( bSetTargetSRS ) { OGRSpatialReferenceH hSourceSRS = NULL; OGRCoordinateTransformationH hCT = NULL; hSourceSRS = OSRNewSpatialReference( projectionRef ); 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 ); } if ( hSourceSRS ) OSRDestroySpatialReference( hSourceSRS ); } hFeature = OGR_F_Create( OGR_L_GetLayerDefn( hLayer ) ); OGR_F_SetFieldString( hFeature, ti_field, fileNameToWrite ); 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 Delaunay(maps*& conf,maps*& inputs,maps*& outputs){ #ifdef DEBUG fprintf(stderr,"\nService internal print\nStarting\n"); #endif maps* cursor=inputs; OGRGeometryH geometry,res; int bufferDistance; map* tmpm=NULL; OGRRegisterAll(); std::vector<Point> points; if(int res=parseInput(conf,inputs,&points,"/vsimem/tmp")!=SERVICE_SUCCEEDED) return res; DelaunayT T; T.insert(points.begin(), points.end()); /* -------------------------------------------------------------------- */ /* Try opening the output datasource as an existing, writable */ /* -------------------------------------------------------------------- */ #if GDAL_VERSION_MAJOR >= 2 GDALDataset *poODS; GDALDriverManager* poR=GetGDALDriverManager(); GDALDriver *poDriver = NULL; #else OGRDataSource *poODS; OGRSFDriverRegistrar *poR = OGRSFDriverRegistrar::GetRegistrar(); OGRSFDriver *poDriver = NULL; #endif int iDriver; map *tmpMap=getMapFromMaps(outputs,"Result","mimeType"); const char *oDriver; oDriver="GeoJSON"; if(tmpMap!=NULL){ if(strcmp(tmpMap->value,"text/xml")==0){ oDriver="GML"; } } for( iDriver = 0; iDriver < poR->GetDriverCount() && poDriver == NULL; iDriver++ ) { #ifdef DEBUG #if GDAL_VERSION_MAJOR >= 2 fprintf(stderr,"D:%s\n",poR->GetDriver(iDriver)->GetDescription()); #else fprintf(stderr,"D:%s\n",poR->GetDriver(iDriver)->GetName()); #endif #endif if( EQUAL( #if GDAL_VERSION_MAJOR >= 2 poR->GetDriver(iDriver)->GetDescription() #else poR->GetDriver(iDriver)->GetName() #endif , oDriver) ) { poDriver = poR->GetDriver(iDriver); } } if( poDriver == NULL ) { char emessage[8192]; sprintf( emessage, "Unable to find driver `%s'.\n", oDriver ); sprintf( emessage, "%sThe following drivers are available:\n",emessage ); for( iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ ) { #if GDAL_VERSION_MAJOR >= 2 sprintf( emessage, "%s -> `%s'\n", emessage, poR->GetDriver(iDriver)->GetDescription() ); #else sprintf( emessage, "%s -> `%s'\n", emessage, poR->GetDriver(iDriver)->GetName() ); #endif } setMapInMaps(conf,"lenv","message",emessage); return SERVICE_FAILED; } #if GDAL_VERSION_MAJOR >=2 if( !CPLTestBool( CSLFetchNameValueDef(poDriver->GetMetadata(), GDAL_DCAP_CREATE, "FALSE") ) ) #else if( !poDriver->TestCapability( ODrCCreateDataSource ) ) #endif { char emessage[1024]; sprintf( emessage, "%s driver does not support data source creation.\n", "json" ); setMapInMaps(conf,"lenv","message",emessage); return SERVICE_FAILED; } /* -------------------------------------------------------------------- */ /* Create the output data source. */ /* -------------------------------------------------------------------- */ char *pszDestDataSource=(char*)malloc(100); char **papszDSCO=NULL; sprintf(pszDestDataSource,"/vsimem/result_%d",getpid()); #if GDAL_VERSION_MAJOR >=2 poODS = poDriver->Create( pszDestDataSource, 0, 0, 0, GDT_Unknown, papszDSCO ); #else poODS = poDriver->CreateDataSource( pszDestDataSource, papszDSCO ); #endif if( poODS == NULL ){ char emessage[1024]; sprintf( emessage, "%s driver failed to create %s\n", "json", pszDestDataSource ); setMapInMaps(conf,"lenv","message",emessage); return SERVICE_FAILED; } /* -------------------------------------------------------------------- */ /* Create the layer. */ /* -------------------------------------------------------------------- */ if( !poODS->TestCapability( ODsCCreateLayer ) ) { char emessage[1024]; sprintf( emessage, "Layer %s not found, and CreateLayer not supported by driver.", "Result" ); setMapInMaps(conf,"lenv","message",emessage); return SERVICE_FAILED; } CPLErrorReset(); OGRLayer *poDstLayer = poODS->CreateLayer( "Result", NULL,wkbPolygon,NULL); if( poDstLayer == NULL ){ setMapInMaps(conf,"lenv","message","Layer creation failed.\n"); return SERVICE_FAILED; } for(DelaunayT::Finite_faces_iterator fit = T.finite_faces_begin(); fit != T.finite_faces_end(); ++fit) { DelaunayT::Face_handle face = fit; OGRFeatureH hFeature = OGR_F_Create( OGR_L_GetLayerDefn( poDstLayer ) ); OGRGeometryH hCollection = OGR_G_CreateGeometry( wkbGeometryCollection ); OGRGeometryH currLine=OGR_G_CreateGeometry(wkbLinearRing); OGRGeometryH currPoly=OGR_G_CreateGeometry(wkbPolygon); OGR_G_AddPoint_2D(currLine,T.triangle(face)[0].x(),T.triangle(face)[0].y()); OGR_G_AddPoint_2D(currLine,T.triangle(face)[1].x(),T.triangle(face)[1].y()); OGR_G_AddPoint_2D(currLine,T.triangle(face)[2].x(),T.triangle(face)[2].y()); OGR_G_AddPoint_2D(currLine,T.triangle(face)[0].x(),T.triangle(face)[0].y()); OGR_G_AddGeometryDirectly( currPoly, currLine ); OGR_G_AddGeometryDirectly( hCollection, currPoly ); OGR_F_SetGeometry( hFeature, hCollection ); OGR_G_DestroyGeometry(hCollection); if( OGR_L_CreateFeature( poDstLayer, hFeature ) != OGRERR_NONE ){ setMapInMaps(conf,"lenv","message","Failed to create feature in file.\n"); return SERVICE_FAILED; } OGR_F_Destroy( hFeature ); } OGR_DS_Destroy( poODS ); #ifdef DEBUG std::cerr << "The Voronoi diagram has " << ns << " finite edges " << " and " << nr << " rays" << std::endl; #endif char *res1=readVSIFile(conf,pszDestDataSource); if(res1==NULL) return SERVICE_FAILED; setMapInMaps(outputs,"Result","value",res1); free(res1); if(strcmp(oDriver,"GML")==0) setMapInMaps(outputs,"Result","mimeType","text/xml"); else setMapInMaps(outputs,"Result","mimeType","application/json"); setMapInMaps(outputs,"Result","encoding","UTF-8"); OGRCleanupAll(); return SERVICE_SUCCEEDED; }
int main(int argc, char* argv[]) { const char *pszFormat = "ESRI Shapefile"; char *pszLayerName = NULL; const char *pszSrcFilename = NULL, *pszDstFilename = NULL; int iBand = 1; GDALDatasetH hDS; GDALRasterBandH hBand; int nXSize, nYSize; int i, j; FILE *fOut = NULL; double *padfBuffer; double adfGeotransform[6]; OGRSFDriverH hOGRDriver; OGRDataSourceH hOGRDS; OGRLayerH hOGRLayer; OGRwkbGeometryType eType = wkbPoint25D; int xStep = 1, yStep = 1; OGRRegisterAll(); GDALAllRegister(); argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 ); if( argc < 1 ) exit( -argc ); /* -------------------------------------------------------------------- */ /* Parse arguments. */ /* -------------------------------------------------------------------- */ for( i = 1; i < argc; i++ ) { if ( EQUAL(argv[i], "-b") && i < argc - 1) iBand = atoi(argv[++i]); else if ( EQUAL(argv[i], "-f") && i < argc - 1) pszFormat = argv[++i]; else if ( EQUAL(argv[i], "-l") && i < argc - 1) pszLayerName = CPLStrdup(argv[++i]); else if ( EQUAL(argv[i], "-t") && i < argc - 1) { i++; if (EQUAL(argv[i], "POLYGON")) eType = wkbPolygon; else if (EQUAL(argv[i], "POINT")) eType = wkbPoint; else if (EQUAL(argv[i], "POINT25D")) eType = wkbPoint25D; else { fprintf(stderr, "unhandled geometry type : %s\n", argv[i]); } } else if ( EQUAL(argv[i], "-step") && i < argc - 1) xStep = yStep = atoi(argv[++i]); else if ( argv[i][0] == '-') Usage(); else if( pszSrcFilename == NULL ) pszSrcFilename = argv[i]; else if( pszDstFilename == NULL ) pszDstFilename = argv[i]; else Usage(); } if( pszSrcFilename == NULL || pszDstFilename == NULL) Usage(); /* -------------------------------------------------------------------- */ /* Open GDAL source dataset */ /* -------------------------------------------------------------------- */ hDS = GDALOpen(pszSrcFilename, GA_ReadOnly); if (hDS == NULL) { fprintf(stderr, "Can't open %s\n", pszSrcFilename); exit(1); } hBand = GDALGetRasterBand(hDS, iBand); if (hBand == NULL) { fprintf(stderr, "Can't get band %d\n", iBand); exit(1); } if (GDALGetGeoTransform(hDS, adfGeotransform) != CE_None) { fprintf(stderr, "Can't get geotransform\n"); exit(1); } nXSize = GDALGetRasterXSize(hDS); nYSize = GDALGetRasterYSize(hDS); /* -------------------------------------------------------------------- */ /* Create OGR destination dataset */ /* -------------------------------------------------------------------- */ /* Special case for CSV : we generate the appropriate VRT file in the same time */ if (EQUAL(pszFormat, "CSV") && EQUAL(CPLGetExtension(pszDstFilename), "CSV")) { FILE* fOutCSVT; FILE* fOutVRT; char* pszDstFilenameCSVT; char* pszDstFilenameVRT; fOut = fopen(pszDstFilename, "wt"); if (fOut == NULL) { fprintf(stderr, "Can't open %s for writing\n", pszDstFilename); exit(1); } fprintf(fOut, "x,y,z\n"); pszDstFilenameCSVT = CPLMalloc(strlen(pszDstFilename) + 2); strcpy(pszDstFilenameCSVT, pszDstFilename); strcat(pszDstFilenameCSVT, "t"); fOutCSVT = fopen(pszDstFilenameCSVT, "wt"); if (fOutCSVT == NULL) { fprintf(stderr, "Can't open %s for writing\n", pszDstFilenameCSVT); exit(1); } CPLFree(pszDstFilenameCSVT); fprintf(fOutCSVT, "Real,Real,Real\n"); fclose(fOutCSVT); fOutCSVT = NULL; pszDstFilenameVRT = CPLStrdup(pszDstFilename); strcpy(pszDstFilenameVRT + strlen(pszDstFilename) - 3, "vrt"); fOutVRT = fopen(pszDstFilenameVRT, "wt"); if (fOutVRT == NULL) { fprintf(stderr, "Can't open %s for writing\n", pszDstFilenameVRT); exit(1); } CPLFree(pszDstFilenameVRT); fprintf(fOutVRT, "<OGRVRTDataSource>\n"); fprintf(fOutVRT, " <OGRVRTLayer name=\"%s\">\n", CPLGetBasename(pszDstFilename)); fprintf(fOutVRT, " <SrcDataSource>%s</SrcDataSource> \n", pszDstFilename); fprintf(fOutVRT, " <GeometryType>wkbPoint</GeometryType>\n"); fprintf(fOutVRT, " <GeometryField encoding=\"PointFromColumns\" x=\"x\" y=\"y\" z=\"z\"/>\n"); fprintf(fOutVRT, " </OGRVRTLayer>\n"); fprintf(fOutVRT, "</OGRVRTDataSource>\n"); fclose(fOutVRT); fOutVRT = NULL; } else { OGRSpatialReferenceH hSRS = NULL; const char* pszWkt; hOGRDriver = OGRGetDriverByName(pszFormat); if (hOGRDriver == NULL) { fprintf(stderr, "Can't find OGR driver %s\n", pszFormat); exit(1); } hOGRDS = OGR_Dr_CreateDataSource(hOGRDriver, pszDstFilename, NULL); if (hOGRDS == NULL) { fprintf(stderr, "Can't create OGR datasource %s\n", pszDstFilename); exit(1); } pszWkt = GDALGetProjectionRef(hDS); if (pszWkt && pszWkt[0]) { hSRS = OSRNewSpatialReference(pszWkt); } if (pszLayerName == NULL) pszLayerName = CPLStrdup(CPLGetBasename(pszDstFilename)); hOGRLayer = OGR_DS_CreateLayer( hOGRDS, pszLayerName, hSRS, eType, NULL); if (hSRS) OSRDestroySpatialReference(hSRS); if (hOGRLayer == NULL) { fprintf(stderr, "Can't create layer %s\n", pszLayerName); exit(1); } if (eType != wkbPoint25D) { OGRFieldDefnH hFieldDefn = OGR_Fld_Create( "z", OFTReal ); OGR_L_CreateField(hOGRLayer, hFieldDefn, 0); OGR_Fld_Destroy( hFieldDefn ); } } padfBuffer = (double*)CPLMalloc(nXSize * sizeof(double)); #define GET_X(j, i) adfGeotransform[0] + (j) * adfGeotransform[1] + (i) * adfGeotransform[2] #define GET_Y(j, i) adfGeotransform[3] + (j) * adfGeotransform[4] + (i) * adfGeotransform[5] #define GET_XY(j, i) GET_X(j, i), GET_Y(j, i) /* -------------------------------------------------------------------- */ /* "Translate" the source dataset */ /* -------------------------------------------------------------------- */ for(i=0;i<nYSize;i+=yStep) { GDALRasterIO( hBand, GF_Read, 0, i, nXSize, 1, padfBuffer, nXSize, 1, GDT_Float64, 0, 0); for(j=0;j<nXSize;j+=xStep) { if (fOut) { fprintf(fOut, "%f,%f,%f\n", GET_XY(j + .5, i + .5), padfBuffer[j]); } else { OGRFeatureH hFeature = OGR_F_Create(OGR_L_GetLayerDefn(hOGRLayer)); OGRGeometryH hGeometry = OGR_G_CreateGeometry(eType); if (eType == wkbPoint25D) { OGR_G_SetPoint(hGeometry, 0, GET_XY(j + .5, i + .5), padfBuffer[j]); } else if (eType == wkbPoint) { OGR_G_SetPoint_2D(hGeometry, 0, GET_XY(j + .5, i + .5)); OGR_F_SetFieldDouble(hFeature, 0, padfBuffer[j]); } else { OGRGeometryH hLinearRing = OGR_G_CreateGeometry(wkbLinearRing); OGR_G_SetPoint_2D(hLinearRing, 0, GET_XY(j + 0, i + 0)); OGR_G_SetPoint_2D(hLinearRing, 1, GET_XY(j + 1, i + 0)); OGR_G_SetPoint_2D(hLinearRing, 2, GET_XY(j + 1, i + 1)); OGR_G_SetPoint_2D(hLinearRing, 3, GET_XY(j + 0, i + 1)); OGR_G_SetPoint_2D(hLinearRing, 4, GET_XY(j + 0, i + 0)); OGR_G_AddGeometryDirectly(hGeometry, hLinearRing); OGR_F_SetFieldDouble(hFeature, 0, padfBuffer[j]); } OGR_F_SetGeometryDirectly(hFeature, hGeometry); OGR_L_CreateFeature(hOGRLayer, hFeature); OGR_F_Destroy(hFeature); } } } /* -------------------------------------------------------------------- */ /* Cleanup */ /* -------------------------------------------------------------------- */ if (fOut) fclose(fOut); else OGR_DS_Destroy(hOGRDS); GDALClose(hDS); CPLFree(padfBuffer); CPLFree(pszLayerName); GDALDumpOpenDatasets( stderr ); GDALDestroyDriverManager(); OGRCleanupAll(); CSLDestroy( argv ); return 0; }
int export_areas_multi(struct Map_info *In, int field, int donocat, OGRFeatureDefnH Ogr_featuredefn,OGRLayerH Ogr_layer, struct field_info *Fi, dbDriver *driver, int ncol, int *colctype, const char **colname, int doatt, int nocat, int *n_noatt, int *n_nocat) { int i, n_exported, area; int cat, ncats_field, line, type, findex, ipart; struct line_pnts *Points; struct line_cats *Cats; struct ilist *cat_list, *line_list, *lcats; OGRGeometryH Ogr_geometry, Ogr_geometry_part; OGRFeatureH Ogr_feature; OGRwkbGeometryType wkbtype, wkbtype_part; Points = Vect_new_line_struct(); Cats = Vect_new_cats_struct(); cat_list = Vect_new_list(); line_list = Vect_new_list(); lcats = Vect_new_list(); n_exported = 0; /* check if category index is available for given field */ findex = Vect_cidx_get_field_index(In, field); if (findex == -1) G_fatal_error(_("Unable to export multi-features. No category index for layer %d."), field); /* determine type */ wkbtype_part = wkbPolygon; wkbtype = get_multi_wkbtype(wkbtype_part); ncats_field = Vect_cidx_get_unique_cats_by_index(In, findex, cat_list); G_debug(1, "n_cats = %d for layer %d", ncats_field, field); if (donocat) G_message(_("Exporting features with category...")); for (i = 0; i < cat_list->n_values; i++) { G_percent(i, cat_list->n_values - 1, 5); cat = cat_list->value[i]; /* find all centroids with given category */ Vect_cidx_find_all(In, field, GV_CENTROID, cat, line_list); /* create multi-feature */ Ogr_geometry = OGR_G_CreateGeometry(wkbtype); /* build simple features geometry, go through all parts */ for (ipart = 0; ipart < line_list->n_values; ipart++) { line = line_list->value[ipart]; G_debug(3, "cat=%d, line=%d -> part=%d", cat, line, ipart); /* get centroid's category */ Vect_read_line(In, NULL, Cats, line); /* check for category consistency */ Vect_field_cat_get(Cats, field, lcats); if (!Vect_val_in_list(lcats, cat)) G_fatal_error(_("Unable to create multi-feature. " "Category %d not found in line %d, field %d"), cat, line, field); /* find correspoding area */ area = Vect_get_centroid_area(In, line); if (area == 0) continue; /* create polygon from area */ Ogr_geometry_part = create_polygon(In, area, Points); /* add part */ OGR_G_AddGeometryDirectly(Ogr_geometry, Ogr_geometry_part); } if (!OGR_G_IsEmpty(Ogr_geometry)) { /* write multi-feature */ Ogr_feature = OGR_F_Create(Ogr_featuredefn); OGR_F_SetGeometry(Ogr_feature, Ogr_geometry); mk_att(cat, Fi, driver, ncol, colctype, colname, doatt, nocat, Ogr_feature, n_noatt); OGR_L_CreateFeature(Ogr_layer, Ogr_feature); OGR_F_Destroy(Ogr_feature); n_exported++; } else { /* skip empty features */ G_debug(3, "multi-feature is empty -> skipped"); } OGR_G_DestroyGeometry(Ogr_geometry); } if (donocat) G_message(_("Exporting features without category...")); /* check lines without category, if -c flag is given write them as * one multi-feature */ Ogr_geometry = OGR_G_CreateGeometry(wkbtype); Vect_rewind(In); Vect_set_constraint_type(In, GV_CENTROID); while(TRUE) { type = Vect_read_next_line(In, NULL, Cats); if (type < 0) break; /* get centroid's category */ Vect_cat_get(Cats, field, &cat); if (cat > 0) continue; /* skip features with category */ if (cat < 0 && !donocat) { (*n_nocat)++; continue; /* skip lines without category, do not export * not labeled */ } /* find correspoding area */ line = Vect_get_next_line_id(In); area = Vect_get_centroid_area(In, line); if (area == 0) continue; /* create polygon from area */ Ogr_geometry_part = create_polygon(In, area, Points); /* add part */ OGR_G_AddGeometryDirectly(Ogr_geometry, Ogr_geometry_part); (*n_nocat)++; } if (!OGR_G_IsEmpty(Ogr_geometry)) { /* write multi-feature */ Ogr_feature = OGR_F_Create(Ogr_featuredefn); OGR_F_SetGeometry(Ogr_feature, Ogr_geometry); mk_att(cat, Fi, driver, ncol, colctype, colname, doatt, nocat, Ogr_feature, n_noatt); OGR_L_CreateFeature(Ogr_layer, Ogr_feature); OGR_F_Destroy(Ogr_feature); n_exported++; } else { /* skip empty features */ G_debug(3, "multi-feature is empty -> skipped"); } OGR_G_DestroyGeometry(Ogr_geometry); Vect_destroy_line_struct(Points); Vect_destroy_cats_struct(Cats); Vect_destroy_list(cat_list); Vect_destroy_list(line_list); Vect_destroy_list(lcats); return n_exported; }
void object::test<3>() { OGRErr err = OGRERR_NONE; OGRDataSourceH ds = NULL; ds = OGR_Dr_CreateDataSource(drv_, data_tmp_.c_str(), NULL); ensure("Can't open or create data source", NULL != ds); // Create memory Layer OGRLayerH lyr = NULL; lyr = OGR_DS_CreateLayer(ds, "tpoly", NULL, wkbPolygon, NULL); ensure("Can't create layer", NULL != lyr); // Create schema OGRFieldDefnH fld = NULL; fld = OGR_Fld_Create("AREA", OFTReal); err = OGR_L_CreateField(lyr, fld, true); OGR_Fld_Destroy(fld); ensure_equals("Can't create field", OGRERR_NONE, err); fld = OGR_Fld_Create("EAS_ID", OFTInteger); err = OGR_L_CreateField(lyr, fld, true); OGR_Fld_Destroy(fld); ensure_equals("Can't create field", OGRERR_NONE, err); fld = OGR_Fld_Create("PRFEDEA", OFTString); err = OGR_L_CreateField(lyr, fld, true); OGR_Fld_Destroy(fld); ensure_equals("Can't create field", OGRERR_NONE, err); // Check schema OGRFeatureDefnH featDefn = OGR_L_GetLayerDefn(lyr); ensure("Layer schema is NULL", NULL != featDefn); ensure_equals("Fields creation failed", 3, OGR_FD_GetFieldCount(featDefn)); // Copy ogr/poly.shp to temporary layer OGRFeatureH featDst = OGR_F_Create(featDefn); ensure("Can't create empty feature", NULL != featDst); std::string source(data_); source += SEP; source += "poly.shp"; OGRDataSourceH dsSrc = OGR_Dr_Open(drv_, source.c_str(), false); ensure("Can't open source layer", NULL != dsSrc); OGRLayerH lyrSrc = OGR_DS_GetLayer(dsSrc, 0); ensure("Can't get source layer", NULL != lyrSrc); OGRFeatureH featSrc = NULL; while (NULL != (featSrc = OGR_L_GetNextFeature(lyrSrc))) { err = OGR_F_SetFrom(featDst, featSrc, true); ensure_equals("Can't set festure from source", OGRERR_NONE, err); err = OGR_L_CreateFeature(lyr, featDst); ensure_equals("Can't write feature to layer", OGRERR_NONE, err); OGR_F_Destroy(featSrc); } // Release and close resources OGR_F_Destroy(featDst); OGR_DS_Destroy(dsSrc); OGR_DS_Destroy(ds); }
int export_areas_single(struct Map_info *In, int field, int donocat, OGRFeatureDefnH Ogr_featuredefn,OGRLayerH Ogr_layer, struct field_info *Fi, dbDriver *driver, int ncol, int *colctype, const char **colname, int doatt, int nocat, int *n_noatt, int *n_nocat) { int i, j; int centroid, cat, area, n_areas; int n_exported; struct line_pnts *Points; struct line_cats *Cats; OGRGeometryH Ogr_geometry; OGRFeatureH Ogr_feature; Points = Vect_new_line_struct(); Cats = Vect_new_cats_struct(); n_exported = 0; n_areas = Vect_get_num_areas(In); for (i = 1; i <= n_areas; i++) { G_percent(i, n_areas, 5); /* get centroid's category */ centroid = Vect_get_area_centroid(In, i); cat = -1; if (centroid > 0) { Vect_read_line(In, NULL, Cats, centroid); Vect_cat_get(Cats, field, &cat); } G_debug(3, "area = %d centroid = %d ncats = %d", i, centroid, Cats->n_cats); if (cat < 0 && !donocat) { (*n_nocat)++; continue; /* skip areas without category, do not export * not labeled */ } /* find correspoding area */ area = Vect_get_centroid_area(In, centroid); if (area == 0) continue; /* create polygon from area */ Ogr_geometry = create_polygon(In, area, Points); /* add feature */ Ogr_feature = OGR_F_Create(Ogr_featuredefn); OGR_F_SetGeometry(Ogr_feature, Ogr_geometry); /* output one feature for each category */ for (j = -1; j < Cats->n_cats; j++) { if (j == -1) { if (cat >= 0) continue; /* cat(s) exists */ (*n_nocat)++; } else { if (Cats->field[j] == field) cat = Cats->cat[j]; else continue; } mk_att(cat, Fi, driver, ncol, colctype, colname, doatt, nocat, Ogr_feature, n_noatt); OGR_L_CreateFeature(Ogr_layer, Ogr_feature); n_exported++; } OGR_G_DestroyGeometry(Ogr_geometry); OGR_F_Destroy(Ogr_feature); } Vect_destroy_line_struct(Points); Vect_destroy_cats_struct(Cats); return n_exported; }
int OGRCCreate(const char *pszFname) { OGRSFDriverH driver; int i, numDrivers; OGRDataSourceH datasource; OGRLayerH layer; OGRFeatureDefnH layerDefn; OGRFieldDefnH fieldDefn; OGRFeatureH feature; OGRGeometryH geometry, ring; /* Register all OGR drivers */ OGRRegisterAll(); /* Fetch MITAB driver - we want to create a TAB file */ numDrivers = OGRGetDriverCount(); for(i=0; i<numDrivers; i++) { driver = OGRGetDriver(i); if (EQUAL("MapInfo File", OGR_Dr_GetName(driver))) break; /* Found it! */ driver = NULL; } if (!driver) { printf("Driver not found!\n"); return -1; } /* Create new file using this driver */ datasource = OGR_Dr_CreateDataSource(driver, pszFname, NULL); if (datasource == NULL) { printf("Unable to create %s\n", pszFname); return -1; } /* MapInfo data sources are created with one empty layer. Fetch the layer handle */ layer = OGR_DS_GetLayer(datasource, 0); if (layer == NULL) { printf("Unable to create new layer in %s\n", pszFname); return -1; } /* Add a few fields to the layer defn */ fieldDefn = OGR_Fld_Create( "id", OFTInteger ); OGR_L_CreateField(layer, fieldDefn, 0); fieldDefn = OGR_Fld_Create( "area", OFTReal ); OGR_L_CreateField(layer, fieldDefn, 0); fieldDefn = OGR_Fld_Create( "name", OFTString ); OGR_L_CreateField(layer, fieldDefn, 0); /* We'll need the layerDefn handle to create new features in this layer */ layerDefn = OGR_L_GetLayerDefn( layer ); /* Create a new point */ feature = OGR_F_Create( layerDefn ); OGR_F_SetFieldInteger( feature, 0, 1); OGR_F_SetFieldDouble( feature, 1, 123.45); OGR_F_SetFieldString( feature, 2, "Feature #1"); geometry = OGR_G_CreateGeometry( wkbPoint ); OGR_G_SetPoint(geometry, 0, 123.45, 456.78, 0); OGR_F_SetGeometryDirectly(feature, geometry); OGR_L_CreateFeature( layer, feature ); /* Create a new line */ feature = OGR_F_Create( layerDefn ); OGR_F_SetFieldInteger( feature, 0, 2); OGR_F_SetFieldDouble( feature, 1, 42.45); OGR_F_SetFieldString( feature, 2, "Feature #2"); geometry = OGR_G_CreateGeometry( wkbLineString ); OGR_G_AddPoint(geometry, 123.45, 456.78, 0); OGR_G_AddPoint(geometry, 12.34, 45.67, 0); OGR_F_SetGeometryDirectly(feature, geometry); OGR_L_CreateFeature( layer, feature ); /* Create a new polygon (square) */ feature = OGR_F_Create( layerDefn ); OGR_F_SetFieldInteger( feature, 0, 3); OGR_F_SetFieldDouble( feature, 1, 49.71); OGR_F_SetFieldString( feature, 2, "Feature #3"); geometry = OGR_G_CreateGeometry( wkbPolygon ); ring = OGR_G_CreateGeometry( wkbLinearRing ); OGR_G_AddPoint(ring, 123.45, 456.78, 0); OGR_G_AddPoint(ring, 12.34, 456.78, 0); OGR_G_AddPoint(ring, 12.34, 45.67, 0); OGR_G_AddPoint(ring, 123.45, 45.67, 0); OGR_G_AddPoint(ring, 123.45, 456.78, 0); OGR_G_AddGeometryDirectly(geometry, ring); OGR_F_SetGeometryDirectly(feature, geometry); OGR_L_CreateFeature( layer, feature ); /* Close data source */ OGR_DS_Destroy( datasource ); return 0; }
/*! \brief Writes feature on level 1 (OGR interface) \param Map pointer to Map_info structure \param type feature type \param points pointer to line_pnts structure (feature geometry) \param cats pointer to line_cats structure (feature categories) \return feature offset into file \return -1 on error */ off_t V1_write_line_ogr(struct Map_info *Map, int type, const struct line_pnts *points, const struct line_cats *cats) { int i, cat, ret; struct field_info *Fi; struct Format_info_ogr *fInfo; OGRGeometryH Ogr_geometry; OGRFeatureH Ogr_feature; OGRFeatureDefnH Ogr_featuredefn; OGRwkbGeometryType Ogr_geom_type; if (!Map->fInfo.ogr.layer) { if (V2_open_new_ogr(Map, type) < 0) return -1; } cat = -1; /* no attributes to be written */ if (cats->n_cats > 0) { /* check for attributes */ Fi = Vect_get_dblink(Map, 0); if (Fi) { if (!Vect_cat_get(cats, Fi->number, &cat)) G_warning(_("No category defined for layer %d"), Fi->number); if (cats->n_cats > 1) { G_warning(_("Feature has more categories, using " "category %d (from layer %d)"), cat, cats->field[0]); } } } fInfo = &(Map->fInfo.ogr); Ogr_featuredefn = OGR_L_GetLayerDefn(fInfo->layer); Ogr_geom_type = OGR_FD_GetGeomType(Ogr_featuredefn); /* determine matching OGR feature geometry type */ /* NOTE: centroids are not supported in OGR, * pseudotopo holds virtual centroids */ /* NOTE: boundaries are not supported in OGR, * pseudotopo treats polygons as boundaries */ if (type & (GV_POINT | GV_KERNEL)) { if (Ogr_geom_type != wkbPoint && Ogr_geom_type != wkbPoint25D) { G_warning(_("Feature is not a point. Skipping.")); return -1; } Ogr_geometry = OGR_G_CreateGeometry(wkbPoint); } else if (type & GV_LINE) { if (Ogr_geom_type != wkbLineString && Ogr_geom_type != wkbLineString25D) { G_warning(_("Feature is not a line. Skipping.")); return -1; } Ogr_geometry = OGR_G_CreateGeometry(wkbLineString); } else if (type & GV_BOUNDARY) { if (Ogr_geom_type != wkbPolygon) { G_warning(_("Feature is not a polygon. Skipping.")); return -1; } Ogr_geometry = OGR_G_CreateGeometry(wkbPolygon); } else if (type & GV_FACE) { if (Ogr_geom_type != wkbPolygon25D) { G_warning(_("Feature is not a face. Skipping.")); return -1; } Ogr_geometry = OGR_G_CreateGeometry(wkbPolygon25D); } else { G_warning(_("Unsupported feature type (%d)"), type); return -1; } G_debug(3, "V1_write_line_ogr(): type = %d", type); if (Ogr_geom_type == wkbPolygon || Ogr_geom_type == wkbPolygon25D) { /* create exterior ring */ OGRGeometryH Ogr_ring; int npoints; npoints = points->n_points - 1; Ogr_ring = OGR_G_CreateGeometry(wkbLinearRing); if (points->x[0] != points->x[npoints] || points->y[0] != points->y[npoints] || points->z[0] != points->z[npoints]) { G_warning(_("Boundary is not closed. Skipping.")); return -1; } /* add points */ for (i = 0; i < points->n_points; i++) { OGR_G_AddPoint(Ogr_ring, points->x[i], points->y[i], points->z[i]); } OGR_G_AddGeometry(Ogr_geometry, Ogr_ring); } else { for (i = 0; i < points->n_points; i++) { OGR_G_AddPoint(Ogr_geometry, points->x[i], points->y[i], points->z[i]); } } G_debug(4, " n_points = %d", points->n_points); /* create feature & set geometry */ Ogr_feature = OGR_F_Create(Ogr_featuredefn); OGR_F_SetGeometry(Ogr_feature, Ogr_geometry); /* write attributes */ if (cat > -1 && fInfo->dbdriver) { write_attributes(fInfo->dbdriver, cat, Fi, fInfo->layer, Ogr_feature); G_free(Fi); } /* write feature into layer */ ret = OGR_L_CreateFeature(fInfo->layer, Ogr_feature); /* update offset array */ if (fInfo->offset_num >= fInfo->offset_alloc) { fInfo->offset_alloc += 1000; fInfo->offset = (int *) G_realloc(fInfo->offset, fInfo->offset_alloc * sizeof(int)); } /* how to deal with OGRNullFID ? */ fInfo->offset[fInfo->offset_num] = (int)OGR_F_GetFID(Ogr_feature); /* destroy */ OGR_G_DestroyGeometry(Ogr_geometry); OGR_F_Destroy(Ogr_feature); if (ret != OGRERR_NONE) return -1; return fInfo->offset_num++; }
void Shapefile::add_feature (const Feature &feature) { if( OGR_L_CreateFeature( layer, feature.handle() ) != OGRERR_NONE ) { throw runtime_error(name + " feature creation failed."); } }
/*! \brief Write OGR feature \param Map pointer to Map_info structure \param type feature type (GV_POINT, GV_LINE, ...) \param bpoints feature geometry \param cats feature categories \param ipoints isle geometry for polygons on NULL \param nisles number of isles \return feature offset into file \return -1 on error */ off_t write_feature(struct Map_info *Map, int type, const struct line_pnts **p_points, int nparts, const struct line_cats *cats) { int i, cat, ret; struct field_info *Fi; const struct line_pnts *points; struct Format_info_ogr *ogr_info; struct Format_info_offset *offset_info; off_t offset; OGRGeometryH Ogr_geometry; OGRFeatureH Ogr_feature; OGRFeatureDefnH Ogr_featuredefn; OGRwkbGeometryType Ogr_geom_type; ogr_info = &(Map->fInfo.ogr); offset_info = &(ogr_info->offset); if (nparts < 1) return -1; points = p_points[0]; /* feature geometry */ if (!ogr_info->layer) { /* create OGR layer if doesn't exist */ if (create_ogr_layer(Map, type) < 0) return -1; } if (!points) return 0; cat = -1; /* no attributes to be written */ if (cats->n_cats > 0 && Vect_get_num_dblinks(Map) > 0) { /* check for attributes */ Fi = Vect_get_dblink(Map, 0); if (Fi) { if (!Vect_cat_get(cats, Fi->number, &cat)) G_warning(_("No category defined for layer %d"), Fi->number); if (cats->n_cats > 1) { G_warning(_("Feature has more categories, using " "category %d (from layer %d)"), cat, cats->field[0]); } } } Ogr_featuredefn = OGR_L_GetLayerDefn(ogr_info->layer); Ogr_geom_type = OGR_FD_GetGeomType(Ogr_featuredefn); /* determine matching OGR feature geometry type */ if (type & (GV_POINT | GV_KERNEL)) { if (Ogr_geom_type != wkbPoint && Ogr_geom_type != wkbPoint25D) { G_warning(_("Feature is not a point. Skipping.")); return -1; } Ogr_geometry = OGR_G_CreateGeometry(wkbPoint); } else if (type & GV_LINE) { if (Ogr_geom_type != wkbLineString && Ogr_geom_type != wkbLineString25D) { G_warning(_("Feature is not a line. Skipping.")); return -1; } Ogr_geometry = OGR_G_CreateGeometry(wkbLineString); } else if (type & GV_BOUNDARY) { if (Ogr_geom_type != wkbPolygon) { G_warning(_("Feature is not a polygon. Skipping.")); return -1; } Ogr_geometry = OGR_G_CreateGeometry(wkbPolygon); } else if (type & GV_FACE) { if (Ogr_geom_type != wkbPolygon25D) { G_warning(_("Feature is not a face. Skipping.")); return -1; } Ogr_geometry = OGR_G_CreateGeometry(wkbPolygon25D); } else { G_warning(_("Unsupported feature type (%d)"), type); return -1; } G_debug(3, "V1_write_line_ogr(): type = %d", type); if (Ogr_geom_type == wkbPolygon || Ogr_geom_type == wkbPolygon25D) { int iring, npoints; /* add rings (first is exterior ring) */ for (iring = 0; iring < nparts; iring++) { OGRGeometryH Ogr_ring; points = p_points[iring]; npoints = points->n_points - 1; Ogr_ring = OGR_G_CreateGeometry(wkbLinearRing); if (points->x[0] != points->x[npoints] || points->y[0] != points->y[npoints] || points->z[0] != points->z[npoints]) { G_warning(_("Boundary is not closed. Feature skipped.")); return -1; } /* add points */ for (i = 0; i < npoints; i++) { OGR_G_AddPoint(Ogr_ring, points->x[i], points->y[i], points->z[i]); } G_debug(4, " ring(%d): n_points = %d", iring, npoints); OGR_G_AddGeometry(Ogr_geometry, Ogr_ring); } } else { for (i = 0; i < points->n_points; i++) { OGR_G_AddPoint(Ogr_geometry, points->x[i], points->y[i], points->z[i]); } G_debug(4, " n_points = %d", points->n_points); } /* create feature & set geometry */ Ogr_feature = OGR_F_Create(Ogr_featuredefn); OGR_F_SetGeometry(Ogr_feature, Ogr_geometry); /* write attributes */ if (cat > -1 && ogr_info->dbdriver) { if (0 > write_attributes(ogr_info->dbdriver, cat, Fi, ogr_info->layer, Ogr_feature)) G_warning(_("Unable to writes feature attributes")); G_free(Fi); } /* write feature into layer */ ret = OGR_L_CreateFeature(ogr_info->layer, Ogr_feature); /* update offset array */ if (offset_info->array_num >= offset_info->array_alloc) { offset_info->array_alloc += 1000; offset_info->array = (int *) G_realloc(offset_info->array, offset_info->array_alloc * sizeof(int)); } offset = offset_info->array_num; offset_info->array[offset_info->array_num++] = (int) OGR_F_GetFID(Ogr_feature); if (Ogr_geom_type == wkbPolygon || Ogr_geom_type == wkbPolygon25D) { /* register exterior ring in offset array */ offset_info->array[offset_info->array_num++] = 0; } /* destroy */ OGR_G_DestroyGeometry(Ogr_geometry); OGR_F_Destroy(Ogr_feature); if (ret != OGRERR_NONE) return -1; G_debug(3, "write_feature(): -> offset = %lu offset_num = %d cat = %d", (unsigned long) offset, offset_info->array_num, cat); return offset; }