MAIN_START(nArgc, papszArgv) { // Check strict compilation and runtime library version as we use C++ API. if( !GDAL_CHECK_VERSION(papszArgv[0]) ) exit(1); EarlySetConfigOptions(nArgc, papszArgv); OGRRegisterAll(); /* -------------------------------------------------------------------- */ /* Processing command line arguments. */ /* -------------------------------------------------------------------- */ nArgc = OGRGeneralCmdLineProcessor(nArgc, &papszArgv, 0); if( nArgc < 1 ) exit(-nArgc); char *pszWHERE = nullptr; const char *pszDataSource = nullptr; char **papszLayers = nullptr; OGRGeometry *poSpatialFilter = nullptr; int nRepeatCount = 1; bool bAllLayers = false; char *pszSQLStatement = nullptr; const char *pszDialect = nullptr; int nRet = 0; const char* pszGeomField = nullptr; char **papszOpenOptions = nullptr; char **papszExtraMDDomains = nullptr; bool bListMDD = false; bool bShowMetadata = true; bool bFeatureCount = true; bool bExtent = true; bool bDatasetGetNextFeature = false; bool bReadOnly = false; bool bUpdate = false; const char* pszWKTFormat = "WKT2"; for( int iArg = 1; iArg < nArgc; iArg++ ) { if( EQUAL(papszArgv[iArg], "--utility_version") ) { printf("%s was compiled against GDAL %s and " "is running against GDAL %s\n", papszArgv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME")); CSLDestroy(papszArgv); return 0; } else if( EQUAL(papszArgv[iArg], "--help") ) { Usage(); } else if( EQUAL(papszArgv[iArg], "-ro") ) { bReadOnly = true; } else if( EQUAL(papszArgv[iArg], "-update") ) { bUpdate = true; } else if( EQUAL(papszArgv[iArg], "-q") || EQUAL(papszArgv[iArg], "-quiet")) { bVerbose = false; } else if( EQUAL(papszArgv[iArg], "-qq") ) { /* Undocumented: mainly only useful for AFL testing */ bVerbose = false; bSuperQuiet = true; } else if( EQUAL(papszArgv[iArg], "-fid") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); nFetchFID = CPLAtoGIntBig(papszArgv[++iArg]); } else if( EQUAL(papszArgv[iArg], "-spat") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(4); OGRLinearRing oRing; oRing.addPoint(CPLAtof(papszArgv[iArg+1]), CPLAtof(papszArgv[iArg+2])); oRing.addPoint(CPLAtof(papszArgv[iArg+1]), CPLAtof(papszArgv[iArg+4])); oRing.addPoint(CPLAtof(papszArgv[iArg+3]), CPLAtof(papszArgv[iArg+4])); oRing.addPoint(CPLAtof(papszArgv[iArg+3]), CPLAtof(papszArgv[iArg+2])); oRing.addPoint(CPLAtof(papszArgv[iArg+1]), CPLAtof(papszArgv[iArg+2])); poSpatialFilter = new OGRPolygon(); static_cast<OGRPolygon *>(poSpatialFilter)->addRing(&oRing); iArg += 4; } else if( EQUAL(papszArgv[iArg], "-geomfield") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszGeomField = papszArgv[++iArg]; } else if( EQUAL(papszArgv[iArg], "-where") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); iArg++; CPLFree(pszWHERE); GByte* pabyRet = nullptr; if( papszArgv[iArg][0] == '@' && VSIIngestFile(nullptr, papszArgv[iArg] + 1, &pabyRet, nullptr, 1024*1024) ) { RemoveBOM(pabyRet); pszWHERE = reinterpret_cast<char *>(pabyRet); } else { pszWHERE = CPLStrdup(papszArgv[iArg]); } } else if( EQUAL(papszArgv[iArg], "-sql") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); iArg++; CPLFree(pszSQLStatement); GByte* pabyRet = nullptr; if( papszArgv[iArg][0] == '@' && VSIIngestFile(nullptr, papszArgv[iArg] + 1, &pabyRet, nullptr, 1024*1024) ) { RemoveBOM(pabyRet); pszSQLStatement = reinterpret_cast<char *>(pabyRet); RemoveSQLComments(pszSQLStatement); } else { pszSQLStatement = CPLStrdup(papszArgv[iArg]); } } else if( EQUAL(papszArgv[iArg], "-dialect") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszDialect = papszArgv[++iArg]; } else if( EQUAL(papszArgv[iArg], "-rc") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); nRepeatCount = atoi(papszArgv[++iArg]); } else if( EQUAL(papszArgv[iArg], "-al") ) { bAllLayers = true; } else if( EQUAL(papszArgv[iArg], "-so") || EQUAL(papszArgv[iArg], "-summary") ) { bSummaryOnly = true; } else if( STARTS_WITH_CI(papszArgv[iArg], "-fields=") ) { char* pszTemp = static_cast<char *>(CPLMalloc(32 + strlen(papszArgv[iArg]))); snprintf(pszTemp, 32 + strlen(papszArgv[iArg]), "DISPLAY_FIELDS=%s", papszArgv[iArg] + strlen("-fields=")); papszOptions = CSLAddString(papszOptions, pszTemp); CPLFree(pszTemp); } else if( STARTS_WITH_CI(papszArgv[iArg], "-geom=") ) { char* pszTemp = static_cast<char *>(CPLMalloc(32 + strlen(papszArgv[iArg]))); snprintf(pszTemp, 32 + strlen(papszArgv[iArg]), "DISPLAY_GEOMETRY=%s", papszArgv[iArg] + strlen("-geom=")); papszOptions = CSLAddString(papszOptions, pszTemp); CPLFree(pszTemp); } else if( EQUAL(papszArgv[iArg], "-oo") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); papszOpenOptions = CSLAddString(papszOpenOptions, papszArgv[++iArg]); } else if( EQUAL(papszArgv[iArg], "-nomd") ) { bShowMetadata = false; } else if( EQUAL(papszArgv[iArg], "-listmdd") ) { bListMDD = true; } else if( EQUAL(papszArgv[iArg], "-mdd") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); papszExtraMDDomains = CSLAddString(papszExtraMDDomains, papszArgv[++iArg]); } else if( EQUAL(papszArgv[iArg], "-nocount") ) { bFeatureCount = false; } else if( EQUAL(papszArgv[iArg], "-noextent") ) { bExtent = false; } else if( EQUAL(papszArgv[iArg], "-rl")) { bDatasetGetNextFeature = true; } else if( EQUAL(papszArgv[iArg], "-wkt_format") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszWKTFormat = papszArgv[++iArg]; } else if( papszArgv[iArg][0] == '-' ) { Usage(CPLSPrintf("Unknown option name '%s'", papszArgv[iArg])); } else if( pszDataSource == nullptr ) { pszDataSource = papszArgv[iArg]; } else { papszLayers = CSLAddString(papszLayers, papszArgv[iArg]); bAllLayers = false; } } if( pszDataSource == nullptr ) Usage("No datasource specified."); if( pszDialect != nullptr && pszWHERE != nullptr && pszSQLStatement == nullptr ) printf("Warning: -dialect is ignored with -where. Use -sql instead"); if( bDatasetGetNextFeature && pszSQLStatement ) { Usage("-rl is incompatible with -sql"); } #ifdef __AFL_HAVE_MANUAL_CONTROL while (__AFL_LOOP(1000)) { #endif /* -------------------------------------------------------------------- */ /* Open data source. */ /* -------------------------------------------------------------------- */ GDALDataset *poDS = static_cast<GDALDataset *>(GDALOpenEx( pszDataSource, ((bReadOnly || pszSQLStatement == nullptr) && !bUpdate ? GDAL_OF_READONLY : GDAL_OF_UPDATE) | GDAL_OF_VECTOR, nullptr, papszOpenOptions, nullptr)); if( poDS == nullptr && !bReadOnly && !bUpdate && pszSQLStatement == nullptr ) { // In some cases (empty geopackage for example), opening in read-only // mode fails, so retry in update mode if( GDALIdentifyDriverEx(pszDataSource, GDAL_OF_VECTOR, nullptr, nullptr) ) { poDS = static_cast<GDALDataset *>(GDALOpenEx( pszDataSource, GDAL_OF_UPDATE | GDAL_OF_VECTOR, nullptr, papszOpenOptions, nullptr)); } } if( poDS == nullptr && !bReadOnly && !bUpdate && pszSQLStatement != nullptr ) { poDS = static_cast<GDALDataset *>(GDALOpenEx( pszDataSource, GDAL_OF_READONLY | GDAL_OF_VECTOR, nullptr, papszOpenOptions, nullptr)); if( poDS != nullptr && bVerbose ) { printf("Had to open data source read-only.\n"); #ifdef __AFL_HAVE_MANUAL_CONTROL bReadOnly = true; #endif } } GDALDriver *poDriver = nullptr; if( poDS != nullptr ) poDriver = poDS->GetDriver(); /* -------------------------------------------------------------------- */ /* Report failure */ /* -------------------------------------------------------------------- */ if( poDS == nullptr ) { printf("FAILURE:\n" "Unable to open datasource `%s' with the following drivers.\n", pszDataSource); #ifdef __AFL_HAVE_MANUAL_CONTROL continue; #else OGRSFDriverRegistrar *poR = OGRSFDriverRegistrar::GetRegistrar(); for( int iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ ) { printf(" -> %s\n", poR->GetDriver(iDriver)->GetDescription()); } nRet = 1; goto end; #endif } CPLAssert(poDriver != nullptr); /* -------------------------------------------------------------------- */ /* Some information messages. */ /* -------------------------------------------------------------------- */ if( bVerbose ) printf("INFO: Open of `%s'\n" " using driver `%s' successful.\n", pszDataSource, poDriver->GetDescription()); if( bVerbose && !EQUAL(pszDataSource,poDS->GetDescription()) ) { printf("INFO: Internal data source name `%s'\n" " different from user name `%s'.\n", poDS->GetDescription(), pszDataSource); } GDALInfoReportMetadata(static_cast<GDALMajorObjectH>(poDS), bListMDD, bShowMetadata, papszExtraMDDomains); if( bDatasetGetNextFeature ) { nRepeatCount = 0; // skip layer reporting. /* -------------------------------------------------------------------- */ /* Set filters if provided. */ /* -------------------------------------------------------------------- */ if( pszWHERE != nullptr || poSpatialFilter != nullptr ) { for( int iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ ) { OGRLayer *poLayer = poDS->GetLayer(iLayer); if( poLayer == nullptr ) { printf("FAILURE: Couldn't fetch advertised layer %d!\n", iLayer); exit(1); } if( pszWHERE != nullptr ) { if( poLayer->SetAttributeFilter(pszWHERE) != OGRERR_NONE ) { printf("WARNING: SetAttributeFilter(%s) " "failed on layer %s.\n", pszWHERE, poLayer->GetName()); } } if( poSpatialFilter != nullptr ) { if( pszGeomField != nullptr ) { OGRFeatureDefn *poDefn = poLayer->GetLayerDefn(); const int iGeomField = poDefn->GetGeomFieldIndex(pszGeomField); if( iGeomField >= 0 ) poLayer->SetSpatialFilter(iGeomField, poSpatialFilter); else printf("WARNING: Cannot find geometry field %s.\n", pszGeomField); } else { poLayer->SetSpatialFilter(poSpatialFilter); } } } } std::set<OGRLayer*> oSetLayers; while( true ) { OGRLayer* poLayer = nullptr; OGRFeature* poFeature = poDS->GetNextFeature(&poLayer, nullptr, nullptr, nullptr); if( poFeature == nullptr ) break; if( papszLayers == nullptr || poLayer == nullptr || CSLFindString(papszLayers, poLayer->GetName()) >= 0 ) { if( bVerbose && poLayer != nullptr && oSetLayers.find(poLayer) == oSetLayers.end() ) { oSetLayers.insert(poLayer); const bool bSummaryOnlyBackup = bSummaryOnly; bSummaryOnly = true; ReportOnLayer(poLayer, nullptr, nullptr, nullptr, bListMDD, bShowMetadata, papszExtraMDDomains, bFeatureCount, bExtent, pszWKTFormat); bSummaryOnly = bSummaryOnlyBackup; } if( !bSuperQuiet && !bSummaryOnly ) poFeature->DumpReadable(nullptr, papszOptions); } OGRFeature::DestroyFeature(poFeature); } } /* -------------------------------------------------------------------- */ /* Special case for -sql clause. No source layers required. */ /* -------------------------------------------------------------------- */ else if( pszSQLStatement != nullptr ) { nRepeatCount = 0; // skip layer reporting. if( CSLCount(papszLayers) > 0 ) printf("layer names ignored in combination with -sql.\n"); OGRLayer *poResultSet = poDS->ExecuteSQL( pszSQLStatement, pszGeomField == nullptr ? poSpatialFilter : nullptr, pszDialect); if( poResultSet != nullptr ) { if( pszWHERE != nullptr ) { if( poResultSet->SetAttributeFilter(pszWHERE) != OGRERR_NONE ) { printf("FAILURE: SetAttributeFilter(%s) failed.\n", pszWHERE); exit(1); } } if( pszGeomField != nullptr ) ReportOnLayer(poResultSet, nullptr, pszGeomField, poSpatialFilter, bListMDD, bShowMetadata, papszExtraMDDomains, bFeatureCount, bExtent, pszWKTFormat); else ReportOnLayer(poResultSet, nullptr, nullptr, nullptr, bListMDD, bShowMetadata, papszExtraMDDomains, bFeatureCount, bExtent, pszWKTFormat); poDS->ReleaseResultSet(poResultSet); } } // coverity[tainted_data] for( int iRepeat = 0; iRepeat < nRepeatCount; iRepeat++ ) { if( papszLayers == nullptr || *papszLayers == nullptr ) { if( iRepeat == 0 ) CPLDebug("OGR", "GetLayerCount() = %d\n", poDS->GetLayerCount()); /* -------------------------------------------------------------------- */ /* Process each data source layer. */ /* -------------------------------------------------------------------- */ for( int iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ ) { OGRLayer *poLayer = poDS->GetLayer(iLayer); if( poLayer == nullptr ) { printf("FAILURE: Couldn't fetch advertised layer %d!\n", iLayer); exit(1); } if( !bAllLayers ) { printf("%d: %s", iLayer + 1, poLayer->GetName()); const int nGeomFieldCount = poLayer->GetLayerDefn()->GetGeomFieldCount(); if( nGeomFieldCount > 1 ) { printf(" ("); for( int iGeom = 0; iGeom < nGeomFieldCount; iGeom++ ) { if( iGeom > 0 ) printf(", "); OGRGeomFieldDefn* poGFldDefn = poLayer->GetLayerDefn()-> GetGeomFieldDefn(iGeom); printf( "%s", OGRGeometryTypeToName( poGFldDefn->GetType())); } printf(")"); } else if( poLayer->GetGeomType() != wkbUnknown ) printf(" (%s)", OGRGeometryTypeToName( poLayer->GetGeomType())); printf("\n"); } else { if( iRepeat != 0 ) poLayer->ResetReading(); ReportOnLayer(poLayer, pszWHERE, pszGeomField, poSpatialFilter, bListMDD, bShowMetadata, papszExtraMDDomains, bFeatureCount, bExtent, pszWKTFormat); } } } else { /* -------------------------------------------------------------------- */ /* Process specified data source layers. */ /* -------------------------------------------------------------------- */ for( char** papszIter = papszLayers; *papszIter != nullptr; ++papszIter ) { OGRLayer *poLayer = poDS->GetLayerByName(*papszIter); if( poLayer == nullptr ) { printf("FAILURE: Couldn't fetch requested layer %s!\n", *papszIter); exit(1); } if( iRepeat != 0 ) poLayer->ResetReading(); ReportOnLayer(poLayer, pszWHERE, pszGeomField, poSpatialFilter, bListMDD, bShowMetadata, papszExtraMDDomains, bFeatureCount, bExtent, pszWKTFormat); } } } /* -------------------------------------------------------------------- */ /* Close down. */ /* -------------------------------------------------------------------- */ GDALClose(poDS); #ifdef __AFL_HAVE_MANUAL_CONTROL } #else end: #endif CSLDestroy(papszArgv); CSLDestroy(papszLayers); CSLDestroy(papszOptions); CSLDestroy(papszOpenOptions); CSLDestroy(papszExtraMDDomains); if( poSpatialFilter ) OGRGeometryFactory::destroyGeometry(poSpatialFilter); CPLFree(pszSQLStatement); CPLFree(pszWHERE); OGRCleanupAll(); return nRet; }
int OGRPolygonLabelPoint(OGRPolygon *poPoly, OGRPoint *poLabelPoint) { double slope; OGRRawPoint point1, point2; int i, j, k, nfound; double x, y, *xintersect, temp; double hi_y, lo_y; int wrong_order, n; double len, max_len=0; double skip; OGREnvelope oEnv; if (poPoly == NULL) return OGRERR_FAILURE; poPoly->getEnvelope(&oEnv); poLabelPoint->setX((oEnv.MaxX + oEnv.MinX)/2.0); poLabelPoint->setY((oEnv.MaxY + oEnv.MinY)/2.0); //if(get_centroid(p, lp, &miny, &maxy) == -1) return(-1); if(OGRIntersectPointPolygon(poLabelPoint, poPoly) == TRUE) /* cool, done */ return OGRERR_NONE; /* do it the hard way - scanline */ skip = (oEnv.MaxY - oEnv.MinY)/NUM_SCANLINES; n=0; for(j=0; j<OGR_NUM_RINGS(poPoly); j++) { /* count total number of points */ n += OGR_GET_RING(poPoly, j)->getNumPoints(); } xintersect = (double *)calloc(n, sizeof(double)); if (xintersect == NULL) return OGRERR_FAILURE; for(k=1; k<=NUM_SCANLINES; k++) { /* sample the shape in the y direction */ y = oEnv.MaxY - k*skip; /* need to find a y that won't intersect any vertices exactly */ hi_y = y - 1; /* first initializing lo_y, hi_y to be any 2 pnts on either side of lp->y */ lo_y = y + 1; for(j=0; j<OGR_NUM_RINGS(poPoly); j++) { OGRLinearRing *poRing = OGR_GET_RING(poPoly,j); if((lo_y < y) && (hi_y >= y)) break; /* already initialized */ for(i=0; i < poRing->getNumPoints(); i++) { if((lo_y < y) && (hi_y >= y)) break; /* already initialized */ if(poRing->getY(i) < y) lo_y = poRing->getY(i); if(poRing->getY(i) >= y) hi_y = poRing->getY(i); } } n=0; for(j=0; j<OGR_NUM_RINGS(poPoly); j++) { OGRLinearRing *poRing = OGR_GET_RING(poPoly,j); for(i=0; i < poRing->getNumPoints(); i++) { if((poRing->getY(i) < y) && ((y - poRing->getY(i)) < (y - lo_y))) lo_y = poRing->getY(i); if((poRing->getY(i) >= y) && ((poRing->getY(i) - y) < (hi_y - y))) hi_y = poRing->getY(i); } } if(lo_y == hi_y) return OGRERR_FAILURE; else y = (hi_y + lo_y)/2.0; nfound = 0; for(j=0; j<OGR_NUM_RINGS(poPoly); j++) /* for each line */ { OGRLinearRing *poRing = OGR_GET_RING(poPoly,j); point1.x = poRing->getX(poRing->getNumPoints()-1); point1.y = poRing->getY(poRing->getNumPoints()-1); for(i=0; i < poRing->getNumPoints(); i++) { point2.x = poRing->getX(i); point2.y = poRing->getY(i); if(EDGE_CHECK(point1.y, y, point2.y) == CLIP_MIDDLE) { if(point1.y == point2.y) continue; /* ignore horizontal edges */ else slope = (point2.x - point1.x) / (point2.y - point1.y); x = point1.x + (y - point1.y)*slope; xintersect[nfound++] = x; } /* End of checking this edge */ point1 = point2; /* Go on to next edge */ } } /* Finished the scanline */ /* First, sort the intersections */ do { wrong_order = 0; for(i=0; i < nfound-1; i++) { if(xintersect[i] > xintersect[i+1]) { wrong_order = 1; SWAP(xintersect[i], xintersect[i+1], temp); } } } while(wrong_order); /* Great, now find longest span */ point1.y = point2.y = y; for(i=0; i < nfound; i += 2) { point1.x = xintersect[i]; point2.x = xintersect[i+1]; /* len = length(point1, point2); */ len = ABS((point2.x - point1.x)); if(len > max_len) { max_len = len; poLabelPoint->setX( (point1.x + point2.x)/2 ); poLabelPoint->setY( y ); } } } free(xintersect); /* __TODO__ Bug 673 * There seem to be some polygons for which the label is returned * completely outside of the polygon's MBR and this messes the * file bounds, etc. * Until we find the source of the problem, we'll at least validate * the label point to make sure that it overlaps the polygon MBR. */ if( poLabelPoint->getX() < oEnv.MinX || poLabelPoint->getY() < oEnv.MinY || poLabelPoint->getX() > oEnv.MaxX || poLabelPoint->getY() > oEnv.MaxY ) { // Reset label coordinates to center of MBR, just in case poLabelPoint->setX((oEnv.MaxX + oEnv.MinX)/2.0); poLabelPoint->setY((oEnv.MaxY + oEnv.MinY)/2.0); // And return an error return OGRERR_FAILURE; } if(max_len > 0) return OGRERR_NONE; else return OGRERR_FAILURE; }
OGRGeometry *OGRIngresLayer::TranslateGeometry( const char *pszGeom ) { OGRGeometry *poGeom = NULL; /* -------------------------------------------------------------------- */ /* Parse the tuple list into an array of x/y vertices. The */ /* input may look like "(2,3)" or "((2,3),(4,5),...)". Extra */ /* spaces may occur between tokens. */ /* -------------------------------------------------------------------- */ double *padfXY = NULL; int nVertMax = 0, nVertCount = 0; int nDepth = 0; const char *pszNext = pszGeom; while( *pszNext != '\0' ) { while( *pszNext == ' ' ) pszNext++; if( *pszNext == '(' ) { pszNext++; nDepth++; continue; } if( *pszNext == ')' ) { pszNext++; CPLAssert( nDepth == 1 ); nDepth--; break; } if( *pszNext == ',' ) { pszNext++; CPLAssert( nDepth == 1 ); continue; } if( nVertCount == nVertMax ) { nVertMax = nVertMax * 2 + 1; padfXY = (double *) CPLRealloc(padfXY, sizeof(double) * nVertMax * 2 ); } if( !ParseXY( &pszNext, padfXY + nVertCount*2 ) ) { CPLDebug( "INGRES", "Error parsing geometry: %s", pszGeom ); CPLFree( padfXY ); return NULL; } CPLAssert( *pszNext == ')' ); nVertCount++; pszNext++; nDepth--; while( *pszNext == ' ' ) pszNext++; } CPLAssert( nDepth == 0 ); /* -------------------------------------------------------------------- */ /* Handle Box/IBox. */ /* -------------------------------------------------------------------- */ if( EQUAL(osIngresGeomType,"BOX") || EQUAL(osIngresGeomType,"IBOX") ) { CPLAssert( nVertCount == 2 ); OGRLinearRing *poRing = new OGRLinearRing(); poRing->addPoint( padfXY[0], padfXY[1] ); poRing->addPoint( padfXY[2], padfXY[1] ); poRing->addPoint( padfXY[2], padfXY[3] ); poRing->addPoint( padfXY[0], padfXY[3] ); poRing->addPoint( padfXY[0], padfXY[1] ); OGRPolygon *poPolygon = new OGRPolygon(); poPolygon->addRingDirectly( poRing ); poGeom = poPolygon; } /* -------------------------------------------------------------------- */ /* Handle Point/IPoint */ /* -------------------------------------------------------------------- */ else if( EQUAL(osIngresGeomType,"POINT") || EQUAL(osIngresGeomType,"IPOINT") ) { CPLAssert( nVertCount == 1 ); poGeom = new OGRPoint( padfXY[0], padfXY[1] ); } /* -------------------------------------------------------------------- */ /* Handle various linestring types. */ /* -------------------------------------------------------------------- */ else if( EQUAL(osIngresGeomType,"LSEG") || EQUAL(osIngresGeomType,"ILSEG") || EQUAL(osIngresGeomType,"LINE") || EQUAL(osIngresGeomType,"LONG LINE") || EQUAL(osIngresGeomType,"ILINE") ) { OGRLineString *poLine = new OGRLineString(); int iVert; poLine->setNumPoints( nVertCount ); for( iVert = 0; iVert < nVertCount; iVert++ ) poLine->setPoint( iVert, padfXY[iVert*2+0], padfXY[iVert*2+1] ); poGeom = poLine; } /* -------------------------------------------------------------------- */ /* Handle Polygon/IPolygon/LongPolygon. */ /* -------------------------------------------------------------------- */ else if( EQUAL(osIngresGeomType,"POLYGON") || EQUAL(osIngresGeomType,"IPOLYGON") || EQUAL(osIngresGeomType,"LONG POLYGON") ) { OGRLinearRing *poLine = new OGRLinearRing(); int iVert; poLine->setNumPoints( nVertCount ); for( iVert = 0; iVert < nVertCount; iVert++ ) poLine->setPoint( iVert, padfXY[iVert*2+0], padfXY[iVert*2+1] ); // INGRES polygons are implicitly closed, but OGR expects explicit if( poLine->getX(nVertCount-1) != poLine->getX(0) || poLine->getY(nVertCount-1) != poLine->getY(0) ) poLine->addPoint( poLine->getX(0), poLine->getY(0) ); OGRPolygon *poPolygon = new OGRPolygon(); poPolygon->addRingDirectly( poLine ); poGeom = poPolygon; } return poGeom; }
OGRGeometryH OGRBuildPolygonFromEdges( OGRGeometryH hLines, int bBestEffort, int bAutoClose, double dfTolerance, OGRErr * peErr ) { int bSuccess = TRUE; OGRGeometryCollection *poLines = (OGRGeometryCollection *) hLines; OGRPolygon *poPolygon = new OGRPolygon(); (void) bBestEffort; /* -------------------------------------------------------------------- */ /* Setup array of line markers indicating if they have been */ /* added to a ring yet. */ /* -------------------------------------------------------------------- */ int nEdges = poLines->getNumGeometries(); int *panEdgeConsumed, nRemainingEdges = nEdges; panEdgeConsumed = (int *) CPLCalloc(sizeof(int),nEdges); /* ==================================================================== */ /* Loop generating rings. */ /* ==================================================================== */ while( nRemainingEdges > 0 ) { int iEdge; OGRLineString *poLine; /* -------------------------------------------------------------------- */ /* Find the first unconsumed edge. */ /* -------------------------------------------------------------------- */ for( iEdge = 0; panEdgeConsumed[iEdge]; iEdge++ ) {} poLine = (OGRLineString *) poLines->getGeometryRef(iEdge); /* -------------------------------------------------------------------- */ /* Start a new ring, copying in the current line directly */ /* -------------------------------------------------------------------- */ OGRLinearRing *poRing = new OGRLinearRing(); AddEdgeToRing( poRing, poLine, FALSE ); panEdgeConsumed[iEdge] = TRUE; nRemainingEdges--; /* ==================================================================== */ /* Loop adding edges to this ring until we make a whole pass */ /* within finding anything to add. */ /* ==================================================================== */ int bWorkDone = TRUE; double dfBestDist = dfTolerance; while( !CheckPoints(poRing,0,poRing,poRing->getNumPoints()-1,NULL) && nRemainingEdges > 0 && bWorkDone ) { int iBestEdge = -1, bReverse = FALSE; bWorkDone = FALSE; dfBestDist = dfTolerance; // We consider linking the end to the beginning. If this is // closer than any other option we will just close the loop. //CheckPoints(poRing,0,poRing,poRing->getNumPoints()-1,&dfBestDist); // Find unused edge with end point closest to our loose end. for( iEdge = 0; iEdge < nEdges; iEdge++ ) { if( panEdgeConsumed[iEdge] ) continue; poLine = (OGRLineString *) poLines->getGeometryRef(iEdge); if( CheckPoints(poLine,0,poRing,poRing->getNumPoints()-1, &dfBestDist) ) { iBestEdge = iEdge; bReverse = FALSE; } if( CheckPoints(poLine,poLine->getNumPoints()-1, poRing,poRing->getNumPoints()-1, &dfBestDist) ) { iBestEdge = iEdge; bReverse = TRUE; } } // We found one within tolerance - add it. if( iBestEdge != -1 ) { poLine = (OGRLineString *) poLines->getGeometryRef(iBestEdge); AddEdgeToRing( poRing, poLine, bReverse ); panEdgeConsumed[iBestEdge] = TRUE; nRemainingEdges--; bWorkDone = TRUE; } } /* -------------------------------------------------------------------- */ /* Did we fail to complete the ring? */ /* -------------------------------------------------------------------- */ dfBestDist = dfTolerance; if( !CheckPoints(poRing,0,poRing,poRing->getNumPoints()-1, &dfBestDist) ) { CPLDebug( "OGR", "Failed to close ring %d.\n" "End Points are: (%.8f,%.7f) and (%.7f,%.7f)\n", poPolygon->getNumInteriorRings()+1, poRing->getX(0), poRing->getY(0), poRing->getX(poRing->getNumPoints()-1), poRing->getY(poRing->getNumPoints()-1) ); bSuccess = FALSE; } /* -------------------------------------------------------------------- */ /* Do we need to auto-close this ring? */ /* -------------------------------------------------------------------- */ if( bAutoClose && !CheckPoints(poRing,0,poRing,poRing->getNumPoints()-1,NULL) ) { poRing->addPoint( poRing->getX(0), poRing->getY(0), poRing->getZ(0)); } poPolygon->addRingDirectly( poRing ); } /* next ring */ /* -------------------------------------------------------------------- */ /* Cleanup. */ /* -------------------------------------------------------------------- */ CPLFree( panEdgeConsumed ); // Eventually we should at least identify the external ring properly, // perhaps even ordering the direction of rings, though this isn't // required by the OGC geometry model. if( peErr != NULL ) { if( bSuccess ) *peErr = OGRERR_NONE; else *peErr = OGRERR_FAILURE; } return (OGRGeometryH) poPolygon; }
int main( int nArgc, char ** papszArgv ) { int nFirstSourceDataset = -1, bLayersWildcarded = TRUE, iArg; const char *pszFormat = "ESRI Shapefile"; const char *pszTileIndexField = "LOCATION"; const char *pszOutputName = NULL; int write_absolute_path = FALSE; int skip_different_projection = FALSE; char* current_path = NULL; int accept_different_schemas = FALSE; int bFirstWarningForNonMatchingAttributes = TRUE; /* Check strict compilation and runtime library version as we use C++ API */ if (! GDAL_CHECK_VERSION(papszArgv[0])) exit(1); /* -------------------------------------------------------------------- */ /* Register format(s). */ /* -------------------------------------------------------------------- */ OGRRegisterAll(); /* -------------------------------------------------------------------- */ /* Processing command line arguments. */ /* -------------------------------------------------------------------- */ for( iArg = 1; iArg < nArgc; iArg++ ) { if( EQUAL(papszArgv[iArg], "--utility_version") ) { printf("%s was compiled against GDAL %s and is running against GDAL %s\n", papszArgv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME")); return 0; } else if( EQUAL(papszArgv[iArg],"-f") && iArg < nArgc-1 ) { pszFormat = papszArgv[++iArg]; } else if( EQUAL(papszArgv[iArg],"-write_absolute_path")) { write_absolute_path = TRUE; } else if( EQUAL(papszArgv[iArg],"-skip_different_projection")) { skip_different_projection = TRUE; } else if( EQUAL(papszArgv[iArg],"-accept_different_schemas")) { accept_different_schemas = TRUE; } else if( EQUAL(papszArgv[iArg],"-tileindex") && iArg < nArgc-1 ) { pszTileIndexField = papszArgv[++iArg]; } else if( EQUAL(papszArgv[iArg],"-lnum") || EQUAL(papszArgv[iArg],"-lname") ) { iArg++; bLayersWildcarded = FALSE; } else if( papszArgv[iArg][0] == '-' ) Usage(); else if( pszOutputName == NULL ) pszOutputName = papszArgv[iArg]; else if( nFirstSourceDataset == -1 ) nFirstSourceDataset = iArg; } if( pszOutputName == NULL || nFirstSourceDataset == -1 ) Usage(); /* -------------------------------------------------------------------- */ /* Try to open as an existing dataset for update access. */ /* -------------------------------------------------------------------- */ GDALDataset *poDstDS; OGRLayer *poDstLayer = NULL; poDstDS = (GDALDataset*) OGROpen( pszOutputName, TRUE, NULL ); /* -------------------------------------------------------------------- */ /* If that failed, find the driver so we can create the tile index.*/ /* -------------------------------------------------------------------- */ if( poDstDS == NULL ) { OGRSFDriverRegistrar *poR = OGRSFDriverRegistrar::GetRegistrar(); GDALDriver *poDriver = NULL; int iDriver; for( iDriver = 0; iDriver < poR->GetDriverCount() && poDriver == NULL; iDriver++ ) { if( EQUAL(poR->GetDriver(iDriver)->GetDescription(),pszFormat) ) { poDriver = poR->GetDriver(iDriver); } } if( poDriver == NULL ) { fprintf( stderr, "Unable to find driver `%s'.\n", pszFormat ); fprintf( stderr, "The following drivers are available:\n" ); for( iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ ) { fprintf( stderr, " -> `%s'\n", poR->GetDriver(iDriver)->GetDescription() ); } exit( 1 ); } if( !CSLTestBoolean( CSLFetchNameValueDef(poDriver->GetMetadata(), GDAL_DCAP_CREATE, "FALSE") ) ) { fprintf( stderr, "%s driver does not support data source creation.\n", pszFormat ); exit( 1 ); } /* -------------------------------------------------------------------- */ /* Now create it. */ /* -------------------------------------------------------------------- */ poDstDS = poDriver->Create( pszOutputName, 0, 0, 0, GDT_Unknown, NULL ); if( poDstDS == NULL ) { fprintf( stderr, "%s driver failed to create %s\n", pszFormat, pszOutputName ); exit( 1 ); } if( poDstDS->GetLayerCount() == 0 ) { OGRFieldDefn oLocation( pszTileIndexField, OFTString ); oLocation.SetWidth( 200 ); if( nFirstSourceDataset < nArgc && papszArgv[nFirstSourceDataset][0] == '-' ) { nFirstSourceDataset++; } OGRSpatialReference* poSrcSpatialRef = NULL; /* Fetches the SRS of the first layer and use it when creating the tileindex layer */ if (nFirstSourceDataset < nArgc) { GDALDataset* poDS = (GDALDataset*) OGROpen(papszArgv[nFirstSourceDataset], FALSE, NULL); if (poDS) { int iLayer; for( iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ ) { int bRequested = bLayersWildcarded; OGRLayer *poLayer = poDS->GetLayer(iLayer); for( iArg = 1; iArg < nArgc && !bRequested; iArg++ ) { if( EQUAL(papszArgv[iArg],"-lnum") && atoi(papszArgv[iArg+1]) == iLayer ) bRequested = TRUE; else if( EQUAL(papszArgv[iArg],"-lname") && EQUAL(papszArgv[iArg+1], poLayer->GetLayerDefn()->GetName()) ) bRequested = TRUE; } if( !bRequested ) continue; if ( poLayer->GetSpatialRef() ) poSrcSpatialRef = poLayer->GetSpatialRef()->Clone(); break; } } GDALClose( (GDALDatasetH)poDS ); } poDstLayer = poDstDS->CreateLayer( "tileindex", poSrcSpatialRef ); poDstLayer->CreateField( &oLocation, OFTString ); OGRSpatialReference::DestroySpatialReference( poSrcSpatialRef ); } } /* -------------------------------------------------------------------- */ /* Identify target layer and field. */ /* -------------------------------------------------------------------- */ int iTileIndexField; poDstLayer = poDstDS->GetLayer(0); if( poDstLayer == NULL ) { fprintf( stderr, "Can't find any layer in output tileindex!\n" ); exit( 1 ); } iTileIndexField = poDstLayer->GetLayerDefn()->GetFieldIndex( pszTileIndexField ); if( iTileIndexField == -1 ) { fprintf( stderr, "Can't find %s field in tile index dataset.\n", pszTileIndexField ); exit( 1 ); } OGRFeatureDefn* poFeatureDefn = NULL; /* Load in memory existing file names in SHP */ int nExistingLayers = 0; char** existingLayersTab = NULL; OGRSpatialReference* alreadyExistingSpatialRef = NULL; int alreadyExistingSpatialRefValid = FALSE; nExistingLayers = (int)poDstLayer->GetFeatureCount(); if (nExistingLayers) { int i; existingLayersTab = (char**)CPLMalloc(nExistingLayers * sizeof(char*)); for(i=0;i<nExistingLayers;i++) { OGRFeature* feature = poDstLayer->GetNextFeature(); existingLayersTab[i] = CPLStrdup(feature->GetFieldAsString( iTileIndexField)); if (i == 0) { GDALDataset *poDS; char* filename = CPLStrdup(existingLayersTab[i]); int j; for(j=strlen(filename)-1;j>=0;j--) { if (filename[j] == ',') break; } if (j >= 0) { int iLayer = atoi(filename + j + 1); filename[j] = 0; poDS = (GDALDataset*) OGROpen(filename, FALSE, NULL); if (poDS) { OGRLayer *poLayer = poDS->GetLayer(iLayer); if (poLayer) { alreadyExistingSpatialRefValid = TRUE; alreadyExistingSpatialRef = (poLayer->GetSpatialRef()) ? poLayer->GetSpatialRef()->Clone() : NULL; if (poFeatureDefn == NULL) poFeatureDefn = poLayer->GetLayerDefn()->Clone(); } GDALClose( (GDALDatasetH)poDS ); } } } } } 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; } } /* ==================================================================== */ /* Process each input datasource in turn. */ /* ==================================================================== */ for(; nFirstSourceDataset < nArgc; nFirstSourceDataset++ ) { int i; GDALDataset *poDS; if( papszArgv[nFirstSourceDataset][0] == '-' ) { nFirstSourceDataset++; continue; } char* fileNameToWrite; VSIStatBuf sStatBuf; if (write_absolute_path && CPLIsFilenameRelative( papszArgv[nFirstSourceDataset] ) && VSIStat( papszArgv[nFirstSourceDataset], &sStatBuf ) == 0) { fileNameToWrite = CPLStrdup(CPLProjectRelativeFilename(current_path,papszArgv[nFirstSourceDataset])); } else { fileNameToWrite = CPLStrdup(papszArgv[nFirstSourceDataset]); } poDS = (GDALDataset*) OGROpen( papszArgv[nFirstSourceDataset], FALSE, NULL ); if( poDS == NULL ) { fprintf( stderr, "Failed to open dataset %s, skipping.\n", papszArgv[nFirstSourceDataset] ); CPLFree(fileNameToWrite); continue; } /* -------------------------------------------------------------------- */ /* Check all layers, and see if they match requests. */ /* -------------------------------------------------------------------- */ int iLayer; for( iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ ) { int bRequested = bLayersWildcarded; OGRLayer *poLayer = poDS->GetLayer(iLayer); for( iArg = 1; iArg < nArgc && !bRequested; iArg++ ) { if( EQUAL(papszArgv[iArg],"-lnum") && atoi(papszArgv[iArg+1]) == iLayer ) bRequested = TRUE; else if( EQUAL(papszArgv[iArg],"-lname") && EQUAL(papszArgv[iArg+1], poLayer->GetLayerDefn()->GetName()) ) bRequested = TRUE; } if( !bRequested ) continue; /* Checks that the layer is not already in tileindex */ for(i=0;i<nExistingLayers;i++) { char szLocation[5000]; sprintf( szLocation, "%s,%d", fileNameToWrite, iLayer ); if (EQUAL(szLocation, existingLayersTab[i])) { fprintf(stderr, "Layer %d of %s is already in tileindex. Skipping it.\n", iLayer, papszArgv[nFirstSourceDataset]); break; } } if (i != nExistingLayers) { continue; } OGRSpatialReference* spatialRef = poLayer->GetSpatialRef(); if (alreadyExistingSpatialRefValid) { if ((spatialRef != NULL && alreadyExistingSpatialRef != NULL && spatialRef->IsSame(alreadyExistingSpatialRef) == FALSE) || ((spatialRef != NULL) != (alreadyExistingSpatialRef != NULL))) { fprintf(stderr, "Warning : layer %d of %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", iLayer, papszArgv[nFirstSourceDataset], (skip_different_projection) ? " Skipping it" : ""); if (skip_different_projection) { continue; } } } else { alreadyExistingSpatialRefValid = TRUE; alreadyExistingSpatialRef = (spatialRef) ? spatialRef->Clone() : NULL; } /* -------------------------------------------------------------------- */ /* Check if all layers in dataset have the same attributes schema. */ /* -------------------------------------------------------------------- */ if( poFeatureDefn == NULL ) { poFeatureDefn = poLayer->GetLayerDefn()->Clone(); } else if ( !accept_different_schemas ) { OGRFeatureDefn* poFeatureDefnCur = poLayer->GetLayerDefn(); assert(NULL != poFeatureDefnCur); int fieldCount = poFeatureDefnCur->GetFieldCount(); if( fieldCount != poFeatureDefn->GetFieldCount()) { fprintf( stderr, "Number of attributes of layer %s of %s does not match ... skipping it.\n", poLayer->GetLayerDefn()->GetName(), papszArgv[nFirstSourceDataset]); if (bFirstWarningForNonMatchingAttributes) { fprintf( stderr, "Note : you can override this behaviour with -accept_different_schemas option\n" "but this may result in a tileindex incompatible with MapServer\n"); bFirstWarningForNonMatchingAttributes = FALSE; } continue; } int bSkip = FALSE; for( int fn = 0; fn < poFeatureDefnCur->GetFieldCount(); fn++ ) { OGRFieldDefn* poField = poFeatureDefn->GetFieldDefn(fn); OGRFieldDefn* poFieldCur = poFeatureDefnCur->GetFieldDefn(fn); /* XXX - Should those pointers be checked against NULL? */ assert(NULL != poField); assert(NULL != poFieldCur); if( poField->GetType() != poFieldCur->GetType() || poField->GetWidth() != poFieldCur->GetWidth() || poField->GetPrecision() != poFieldCur->GetPrecision() || !EQUAL( poField->GetNameRef(), poFieldCur->GetNameRef() ) ) { fprintf( stderr, "Schema of attributes of layer %s of %s does not match ... skipping it.\n", poLayer->GetLayerDefn()->GetName(), papszArgv[nFirstSourceDataset]); if (bFirstWarningForNonMatchingAttributes) { fprintf( stderr, "Note : you can override this behaviour with -accept_different_schemas option\n" "but this may result in a tileindex incompatible with MapServer\n"); bFirstWarningForNonMatchingAttributes = FALSE; } bSkip = TRUE; break; } } if (bSkip) continue; } /* -------------------------------------------------------------------- */ /* Get layer extents, and create a corresponding polygon */ /* geometry. */ /* -------------------------------------------------------------------- */ OGREnvelope sExtents; OGRPolygon oRegion; OGRLinearRing oRing; if( poLayer->GetExtent( &sExtents, TRUE ) != OGRERR_NONE ) { fprintf( stderr, "GetExtent() failed on layer %s of %s, skipping.\n", poLayer->GetLayerDefn()->GetName(), papszArgv[nFirstSourceDataset] ); continue; } oRing.addPoint( sExtents.MinX, sExtents.MinY ); oRing.addPoint( sExtents.MinX, sExtents.MaxY ); oRing.addPoint( sExtents.MaxX, sExtents.MaxY ); oRing.addPoint( sExtents.MaxX, sExtents.MinY ); oRing.addPoint( sExtents.MinX, sExtents.MinY ); oRegion.addRing( &oRing ); /* -------------------------------------------------------------------- */ /* Add layer to tileindex. */ /* -------------------------------------------------------------------- */ char szLocation[5000]; OGRFeature oTileFeat( poDstLayer->GetLayerDefn() ); sprintf( szLocation, "%s,%d", fileNameToWrite, iLayer ); oTileFeat.SetGeometry( &oRegion ); oTileFeat.SetField( iTileIndexField, szLocation ); if( poDstLayer->CreateFeature( &oTileFeat ) != OGRERR_NONE ) { fprintf( stderr, "Failed to create feature on tile index ... terminating." ); GDALClose( (GDALDatasetH) poDstDS ); exit( 1 ); } } /* -------------------------------------------------------------------- */ /* Cleanup this data source. */ /* -------------------------------------------------------------------- */ CPLFree(fileNameToWrite); GDALClose( (GDALDatasetH)poDS ); } /* -------------------------------------------------------------------- */ /* Close tile index and clear buffers. */ /* -------------------------------------------------------------------- */ GDALClose( (GDALDatasetH) poDstDS ); OGRFeatureDefn::DestroyFeatureDefn( poFeatureDefn ); if (alreadyExistingSpatialRef != NULL) OGRSpatialReference::DestroySpatialReference( alreadyExistingSpatialRef ); CPLFree(current_path); if (nExistingLayers) { int i; for(i=0;i<nExistingLayers;i++) { CPLFree(existingLayersTab[i]); } CPLFree(existingLayersTab); } OGRCleanupAll(); return 0; }
OGRFeature *OGRPCIDSKLayer::GetFeature( GIntBig nFID ) { /* -------------------------------------------------------------------- */ /* Create the OGR feature. */ /* -------------------------------------------------------------------- */ OGRFeature *poFeature = new OGRFeature( poFeatureDefn ); poFeature->SetFID( static_cast<int>( nFID ) ); /* -------------------------------------------------------------------- */ /* Set attributes for any indicated attribute records. */ /* -------------------------------------------------------------------- */ try { std::vector<PCIDSK::ShapeField> aoFields; poVecSeg->GetFields( static_cast<int>( nFID ), aoFields ); for( unsigned int i=0; i < aoFields.size(); i++ ) { if( static_cast<int>( i ) == iRingStartField ) continue; switch( aoFields[i].GetType() ) { case PCIDSK::FieldTypeNone: // null field value. break; case PCIDSK::FieldTypeInteger: poFeature->SetField( i, aoFields[i].GetValueInteger() ); break; case PCIDSK::FieldTypeFloat: poFeature->SetField( i, aoFields[i].GetValueFloat() ); break; case PCIDSK::FieldTypeDouble: poFeature->SetField( i, aoFields[i].GetValueDouble() ); break; case PCIDSK::FieldTypeString: poFeature->SetField( i, aoFields[i].GetValueString().c_str() ); break; case PCIDSK::FieldTypeCountedInt: std::vector<PCIDSK::int32> list = aoFields[i].GetValueCountedInt(); poFeature->SetField( i, static_cast<int>(list.size()), &(list[0]) ); break; } } /* -------------------------------------------------------------------- */ /* Translate the geometry. */ /* -------------------------------------------------------------------- */ std::vector<PCIDSK::ShapeVertex> aoVertices; poVecSeg->GetVertices( static_cast<int>( nFID ), aoVertices ); /* -------------------------------------------------------------------- */ /* Point */ /* -------------------------------------------------------------------- */ if( poFeatureDefn->GetGeomType() == wkbPoint25D || (wkbFlatten(poFeatureDefn->GetGeomType()) == wkbUnknown && aoVertices.size() == 1) ) { if( aoVertices.size() == 1 ) { OGRPoint* poPoint = new OGRPoint( aoVertices[0].x, aoVertices[0].y, aoVertices[0].z ); if (poSRS) poPoint->assignSpatialReference(poSRS); poFeature->SetGeometryDirectly(poPoint); } else { // report issue? } } /* -------------------------------------------------------------------- */ /* LineString */ /* -------------------------------------------------------------------- */ else if( poFeatureDefn->GetGeomType() == wkbLineString25D || (wkbFlatten(poFeatureDefn->GetGeomType()) == wkbUnknown && aoVertices.size() > 1) ) { // We should likely be applying ringstart to break things into // a multilinestring in some cases. if( aoVertices.size() > 1 ) { OGRLineString *poLS = new OGRLineString(); poLS->setNumPoints( static_cast<int>(aoVertices.size()) ); for( unsigned int i = 0; i < aoVertices.size(); i++ ) poLS->setPoint( i, aoVertices[i].x, aoVertices[i].y, aoVertices[i].z ); if (poSRS) poLS->assignSpatialReference(poSRS); poFeature->SetGeometryDirectly( poLS ); } else { // report issue? } } /* -------------------------------------------------------------------- */ /* Polygon - Currently we have no way to recognise if we are */ /* dealing with a multipolygon when we have more than one */ /* ring. Also, PCIDSK allows the rings to be in arbitrary */ /* order, not necessarily outside first which we are not yet */ /* ready to address in the following code. */ /* -------------------------------------------------------------------- */ else if( poFeatureDefn->GetGeomType() == wkbPolygon25D ) { std::vector<PCIDSK::int32> anRingStart; OGRPolygon *poPoly = new OGRPolygon(); if( iRingStartField != -1 ) anRingStart = aoFields[iRingStartField].GetValueCountedInt(); for( unsigned int iRing = 0; iRing < anRingStart.size()+1; iRing++ ) { int iStartVertex; if( iRing == 0 ) iStartVertex = 0; else iStartVertex = anRingStart[iRing-1]; int iEndVertex; if( iRing == anRingStart.size() ) iEndVertex = static_cast<int>(aoVertices.size()) - 1; else iEndVertex = anRingStart[iRing] - 1; int iVertex; OGRLinearRing *poRing = new OGRLinearRing(); poRing->setNumPoints( iEndVertex - iStartVertex + 1 ); for( iVertex = iStartVertex; iVertex <= iEndVertex; iVertex++ ) { poRing->setPoint( iVertex - iStartVertex, aoVertices[iVertex].x, aoVertices[iVertex].y, aoVertices[iVertex].z ); } poPoly->addRingDirectly( poRing ); } if (poSRS) poPoly->assignSpatialReference(poSRS); poFeature->SetGeometryDirectly( poPoly ); } } /* -------------------------------------------------------------------- */ /* Trap exceptions and report as CPL errors. */ /* -------------------------------------------------------------------- */ catch( PCIDSK::PCIDSKException ex ) { delete poFeature; CPLError( CE_Failure, CPLE_AppDefined, "%s", ex.what() ); return NULL; } catch(...) { delete poFeature; CPLError( CE_Failure, CPLE_AppDefined, "Non-PCIDSK exception trapped." ); return NULL; } m_nFeaturesRead++; return poFeature; }
static int TestSpatialFilter( OGRLayer *poLayer ) { int bRet = TRUE; OGRFeature *poFeature, *poTargetFeature; OGRPolygon oInclusiveFilter, oExclusiveFilter; OGRLinearRing oRing; OGREnvelope sEnvelope; int nInclusiveCount; /* -------------------------------------------------------------------- */ /* Read the target feature. */ /* -------------------------------------------------------------------- */ poLayer->ResetReading(); poTargetFeature = poLayer->GetNextFeature(); if( poTargetFeature == NULL ) { printf( "INFO: Skipping Spatial Filter test for %s.\n" " No features in layer.\n", poLayer->GetName() ); return bRet; } if( poTargetFeature->GetGeometryRef() == NULL ) { printf( "INFO: Skipping Spatial Filter test for %s,\n" " target feature has no geometry.\n", poTargetFeature->GetDefnRef()->GetName() ); OGRFeature::DestroyFeature(poTargetFeature); return bRet; } poTargetFeature->GetGeometryRef()->getEnvelope( &sEnvelope ); /* -------------------------------------------------------------------- */ /* Construct inclusive filter. */ /* -------------------------------------------------------------------- */ oRing.setPoint( 0, sEnvelope.MinX - 20.0, sEnvelope.MinY - 20.0 ); oRing.setPoint( 1, sEnvelope.MinX - 20.0, sEnvelope.MaxY + 10.0 ); oRing.setPoint( 2, sEnvelope.MaxX + 10.0, sEnvelope.MaxY + 10.0 ); oRing.setPoint( 3, sEnvelope.MaxX + 10.0, sEnvelope.MinY - 20.0 ); oRing.setPoint( 4, sEnvelope.MinX - 20.0, sEnvelope.MinY - 20.0 ); oInclusiveFilter.addRing( &oRing ); poLayer->SetSpatialFilter( &oInclusiveFilter ); /* -------------------------------------------------------------------- */ /* Verify that we can find the target feature. */ /* -------------------------------------------------------------------- */ poLayer->ResetReading(); while( (poFeature = poLayer->GetNextFeature()) != NULL ) { if( poFeature->Equal(poTargetFeature) ) { OGRFeature::DestroyFeature(poFeature); break; } else OGRFeature::DestroyFeature(poFeature); } if( poFeature == NULL ) { bRet = FALSE; printf( "ERROR: Spatial filter eliminated a feature unexpectedly!\n"); } else if( bVerbose ) { printf( "INFO: Spatial filter inclusion seems to work.\n" ); } nInclusiveCount = poLayer->GetFeatureCount(); /* -------------------------------------------------------------------- */ /* Construct exclusive filter. */ /* -------------------------------------------------------------------- */ oRing.setPoint( 0, sEnvelope.MinX - 20.0, sEnvelope.MinY - 20.0 ); oRing.setPoint( 1, sEnvelope.MinX - 10.0, sEnvelope.MinY - 20.0 ); oRing.setPoint( 2, sEnvelope.MinX - 10.0, sEnvelope.MinY - 10.0 ); oRing.setPoint( 3, sEnvelope.MinX - 20.0, sEnvelope.MinY - 10.0 ); oRing.setPoint( 4, sEnvelope.MinX - 20.0, sEnvelope.MinY - 20.0 ); oExclusiveFilter.addRing( &oRing ); poLayer->SetSpatialFilter( &oExclusiveFilter ); /* -------------------------------------------------------------------- */ /* Verify that we can find the target feature. */ /* -------------------------------------------------------------------- */ poLayer->ResetReading(); while( (poFeature = poLayer->GetNextFeature()) != NULL ) { if( poFeature->Equal(poTargetFeature) ) { OGRFeature::DestroyFeature(poFeature); break; } else OGRFeature::DestroyFeature(poFeature); } if( poFeature != NULL ) { bRet = FALSE; printf( "ERROR: Spatial filter failed to eliminate" "a feature unexpectedly!\n"); } else if( poLayer->GetFeatureCount() >= nInclusiveCount ) { bRet = FALSE; printf( "ERROR: GetFeatureCount() may not be taking spatial " "filter into account.\n" ); } else if( bVerbose ) { printf( "INFO: Spatial filter exclusion seems to work.\n" ); } OGRFeature::DestroyFeature(poTargetFeature); poLayer->SetSpatialFilter( NULL ); return bRet; }
OGRFeature *OGROGDILayer::GetNextRawFeature() { /* -------------------------------------------------------------------- */ /* Retrieve object from OGDI server and create new feature */ /* -------------------------------------------------------------------- */ ecs_Result *psResult = cln_GetNextObject(m_nClientID); if (! ECSSUCCESS(psResult)) { if( ECSERROR( psResult ) && (psResult->message == nullptr || strstr(psResult->message, "End of selection") == nullptr) ) { CPLError( CE_Failure, CPLE_AppDefined, "Access to next object of layer '%s' failed: %s\n", m_pszOGDILayerName, psResult->message ? psResult->message : "(no error string)" ); } // We probably reached EOF... keep track of shape count. m_nTotalShapeCount = m_iNextShapeId - m_nFilteredOutShapes; return nullptr; } OGRFeature *poFeature = new OGRFeature(m_poFeatureDefn); poFeature->SetFID( m_iNextShapeId++ ); m_nFeaturesRead++; /* -------------------------------------------------------------------- */ /* Process geometry */ /* -------------------------------------------------------------------- */ if (m_eFamily == Point) { ecs_Point *psPoint = &(ECSGEOM(psResult).point); OGRPoint *poOGRPoint = new OGRPoint(psPoint->c.x, psPoint->c.y); poOGRPoint->assignSpatialReference(m_poSpatialRef); poFeature->SetGeometryDirectly(poOGRPoint); } else if (m_eFamily == Line) { ecs_Line *psLine = &(ECSGEOM(psResult).line); OGRLineString *poOGRLine = new OGRLineString(); poOGRLine->setNumPoints( psLine->c.c_len ); for( int i = 0; i < (int) psLine->c.c_len; i++ ) { poOGRLine->setPoint(i, psLine->c.c_val[i].x, psLine->c.c_val[i].y); } poOGRLine->assignSpatialReference(m_poSpatialRef); poFeature->SetGeometryDirectly(poOGRLine); } else if (m_eFamily == Area) { ecs_Area *psArea = &(ECSGEOM(psResult).area); OGRPolygon *poOGRPolygon = new OGRPolygon(); for( int iRing = 0; iRing < (int) psArea->ring.ring_len; iRing++ ) { ecs_FeatureRing *psRing = &(psArea->ring.ring_val[iRing]); OGRLinearRing *poOGRRing = new OGRLinearRing(); poOGRRing->setNumPoints( psRing->c.c_len ); for( int i = 0; i < (int) psRing->c.c_len; i++ ) { poOGRRing->setPoint(i, psRing->c.c_val[i].x, psRing->c.c_val[i].y); } poOGRPolygon->addRingDirectly(poOGRRing); } // __TODO__ // When OGR supports polygon centroids then we should carry them here poOGRPolygon->assignSpatialReference(m_poSpatialRef); poFeature->SetGeometryDirectly(poOGRPolygon); } else if (m_eFamily == Text) { // __TODO__ // For now text is treated as a point and string is lost // ecs_Text *psText = &(ECSGEOM(psResult).text); OGRPoint *poOGRPoint = new OGRPoint(psText->c.x, psText->c.y); poOGRPoint->assignSpatialReference(m_poSpatialRef); poFeature->SetGeometryDirectly(poOGRPoint); } else { CPLAssert(false); } /* -------------------------------------------------------------------- */ /* Set attributes */ /* -------------------------------------------------------------------- */ char *pszAttrList = ECSOBJECTATTR(psResult); for( int iField = 0; iField < m_poFeatureDefn->GetFieldCount(); iField++ ) { char *pszFieldStart = nullptr; int nNameLen = 0; /* parse out the next attribute value */ if( !ecs_FindElement( pszAttrList, &pszFieldStart, &pszAttrList, &nNameLen, nullptr ) ) { nNameLen = 0; pszFieldStart = pszAttrList; } /* Skip any trailing white space (for string constants). */ if( nNameLen > 0 && pszFieldStart[nNameLen-1] == ' ' ) nNameLen--; /* skip leading white space */ while( pszFieldStart[0] == ' ' && nNameLen > 0 ) { pszFieldStart++; nNameLen--; } /* zero terminate the single field value, but save the */ /* character we overwrote, so we can restore it when done. */ char chSavedChar = pszFieldStart[nNameLen]; pszFieldStart[nNameLen] = '\0'; /* OGR takes care of all field type conversions for us! */ poFeature->SetField(iField, pszFieldStart); pszFieldStart[nNameLen] = chSavedChar; } /* -------------------------------------------------------------------- */ /* Apply the text associated with text features if appropriate. */ /* -------------------------------------------------------------------- */ if( m_eFamily == Text ) { poFeature->SetField( "text", ECSGEOM(psResult).text.desc ); } return poFeature; }
OGRErr OGROCIWritableLayer::TranslateElementGroup( OGRGeometry *poGeometry ) { switch( wkbFlatten(poGeometry->getGeometryType()) ) { case wkbPoint: { OGRPoint *poPoint = (OGRPoint *) poGeometry; PushElemInfo( nOrdinalCount+1, 1, 1 ); PushOrdinal( poPoint->getX() ); PushOrdinal( poPoint->getY() ); if( nDimension == 3 ) PushOrdinal( poPoint->getZ() ); return OGRERR_NONE; } case wkbLineString: { OGRLineString *poLine = (OGRLineString *) poGeometry; int iVert; PushElemInfo( nOrdinalCount+1, 2, 1 ); for( iVert = 0; iVert < poLine->getNumPoints(); iVert++ ) { PushOrdinal( poLine->getX(iVert) ); PushOrdinal( poLine->getY(iVert) ); if( nDimension == 3 ) PushOrdinal( poLine->getZ(iVert) ); } return OGRERR_NONE; } case wkbPolygon: { OGRPolygon *poPoly = (OGRPolygon *) poGeometry; int iRing; for( iRing = -1; iRing < poPoly->getNumInteriorRings(); iRing++ ) { OGRLinearRing *poRing; int iVert; if( iRing == -1 ) poRing = poPoly->getExteriorRing(); else poRing = poPoly->getInteriorRing(iRing); if( iRing == -1 ) PushElemInfo( nOrdinalCount+1, 1003, 1 ); else PushElemInfo( nOrdinalCount+1, 2003, 1 ); if( (iRing == -1 && poRing->isClockwise()) || (iRing != -1 && !poRing->isClockwise()) ) { for( iVert = poRing->getNumPoints()-1; iVert >= 0; iVert-- ) { PushOrdinal( poRing->getX(iVert) ); PushOrdinal( poRing->getY(iVert) ); if( nDimension == 3 ) PushOrdinal( poRing->getZ(iVert) ); } } else { for( iVert = 0; iVert < poRing->getNumPoints(); iVert++ ) { PushOrdinal( poRing->getX(iVert) ); PushOrdinal( poRing->getY(iVert) ); if( nDimension == 3 ) PushOrdinal( poRing->getZ(iVert) ); } } } return OGRERR_NONE; } default: { return OGRERR_FAILURE; } } }
int NBHeightMapper::loadShapeFile(const std::string& file) { #ifdef HAVE_GDAL #if GDAL_VERSION_MAJOR < 2 OGRRegisterAll(); OGRDataSource* ds = OGRSFDriverRegistrar::Open(file.c_str(), FALSE); #else GDALAllRegister(); GDALDataset* ds = (GDALDataset*)GDALOpenEx(file.c_str(), GDAL_OF_VECTOR | GA_ReadOnly, NULL, NULL, NULL); #endif if (ds == NULL) { throw ProcessError("Could not open shape file '" + file + "'."); } // begin file parsing OGRLayer* layer = ds->GetLayer(0); layer->ResetReading(); // triangle coordinates are stored in WGS84 and later matched with network coordinates in WGS84 // build coordinate transformation OGRSpatialReference* sr_src = layer->GetSpatialRef(); OGRSpatialReference sr_dest; sr_dest.SetWellKnownGeogCS("WGS84"); OGRCoordinateTransformation* toWGS84 = OGRCreateCoordinateTransformation(sr_src, &sr_dest); if (toWGS84 == 0) { WRITE_WARNING("Could not create geocoordinates converter; check whether proj.4 is installed."); } int numFeatures = 0; OGRFeature* feature; layer->ResetReading(); while ((feature = layer->GetNextFeature()) != NULL) { OGRGeometry* geom = feature->GetGeometryRef(); assert(geom != 0); // @todo gracefull handling of shapefiles with unexpected contents or any error handling for that matter assert(std::string(geom->getGeometryName()) == std::string("POLYGON")); // try transform to wgs84 geom->transform(toWGS84); OGRLinearRing* cgeom = ((OGRPolygon*) geom)->getExteriorRing(); // assume TIN with with 4 points and point0 == point3 assert(cgeom->getNumPoints() == 4); PositionVector corners; for (int j = 0; j < 3; j++) { Position pos((double) cgeom->getX(j), (double) cgeom->getY(j), (double) cgeom->getZ(j)); corners.push_back(pos); myBoundary.add(pos); } addTriangle(corners); numFeatures++; /* OGRwkbGeometryType gtype = geom->getGeometryType(); switch (gtype) { case wkbPolygon: { break; } case wkbPoint: { WRITE_WARNING("got wkbPoint"); break; } case wkbLineString: { WRITE_WARNING("got wkbLineString"); break; } case wkbMultiPoint: { WRITE_WARNING("got wkbMultiPoint"); break; } case wkbMultiLineString: { WRITE_WARNING("got wkbMultiLineString"); break; } case wkbMultiPolygon: { WRITE_WARNING("got wkbMultiPolygon"); break; } default: WRITE_WARNING("Unsupported shape type occurred"); break; } */ OGRFeature::DestroyFeature(feature); } #if GDAL_VERSION_MAJOR < 2 OGRDataSource::DestroyDataSource(ds); #else GDALClose(ds); #endif OCTDestroyCoordinateTransformation(toWGS84); OGRCleanupAll(); return numFeatures; #else UNUSED_PARAMETER(file); WRITE_ERROR("Cannot load shape file since SUMO was compiled without GDAL support."); return 0; #endif }
OGRErr OGRIngresTableLayer::PrepareOldStyleGeometry( OGRGeometry *poGeom, CPLString &osRetGeomText ) { osRetGeomText = ""; if( poGeom == NULL ) return OGRERR_FAILURE; /* -------------------------------------------------------------------- */ /* Point */ /* -------------------------------------------------------------------- */ if( EQUAL(osIngresGeomType,"POINT") && wkbFlatten(poGeom->getGeometryType()) == wkbPoint ) { OGRPoint *poPoint = (OGRPoint *) poGeom; osRetGeomText.Printf( "(%.15g,%.15g)", poPoint->getX(), poPoint->getY() ); return OGRERR_NONE; } if( EQUAL(osIngresGeomType,"IPOINT") && wkbFlatten(poGeom->getGeometryType()) == wkbPoint ) { OGRPoint *poPoint = (OGRPoint *) poGeom; osRetGeomText.Printf( "(%d,%d)", (int) floor(poPoint->getX()), (int) floor(poPoint->getY()) ); return OGRERR_NONE; } /* -------------------------------------------------------------------- */ /* Line */ /* -------------------------------------------------------------------- */ if( wkbFlatten(poGeom->getGeometryType()) == wkbLineString ) { OGRLineString *poLS = (OGRLineString *) poGeom; CPLString osLastPoint; int i; if( (EQUAL(osIngresGeomType,"LSEG") || EQUAL(osIngresGeomType,"ILSEG")) && poLS->getNumPoints() != 2 ) { CPLError( CE_Failure, CPLE_AppDefined, "Attempt to place %d vertex linestring in %s field.", poLS->getNumPoints(), osIngresGeomType.c_str() ); return OGRERR_FAILURE; } else if( EQUAL(osIngresGeomType,"LINESTRING") && poLS->getNumPoints() > 124 ) { CPLError( CE_Failure, CPLE_AppDefined, "Attempt to place %d vertex linestring in %s field.", poLS->getNumPoints(), osIngresGeomType.c_str() ); return OGRERR_FAILURE; } else if( EQUAL(osIngresGeomType,"ILINESTRING") && poLS->getNumPoints() > 248 ) { CPLError( CE_Failure, CPLE_AppDefined, "Attempt to place %d vertex linestring in %s field.", poLS->getNumPoints(), osIngresGeomType.c_str() ); return OGRERR_FAILURE; } osRetGeomText = "("; for( i = 0; i < poLS->getNumPoints(); i++ ) { CPLString osPoint; if( i > 0 && poLS->getX(i) == poLS->getX(i-1) && poLS->getY(i) == poLS->getY(i-1) ) { CPLDebug( "INGRES", "Dropping duplicate point in linestring."); continue; } if( STARTS_WITH_CI(osIngresGeomType, "I") ) osPoint.Printf( "(%d,%d)", (int) floor(poLS->getX(i)), (int) floor(poLS->getY(i)) ); else osPoint.Printf( "(%.15g,%.15g)", poLS->getX(i), poLS->getY(i) ); if( osPoint == osLastPoint ) { CPLDebug( "INGRES", "Dropping duplicate point in linestring(2)."); continue; } osLastPoint = osPoint; if( osRetGeomText.size() > 1 ) osRetGeomText += "," + osPoint; else osRetGeomText += osPoint; } osRetGeomText += ")"; return OGRERR_NONE; } /* -------------------------------------------------------------------- */ /* Polygon */ /* -------------------------------------------------------------------- */ if( wkbFlatten(poGeom->getGeometryType()) == wkbPolygon ) { OGRPolygon *poPoly = (OGRPolygon *) poGeom; OGRLinearRing *poLS = poPoly->getExteriorRing(); int i, nPoints; if( poLS == NULL ) return OGRERR_FAILURE; if( poPoly->getNumInteriorRings() > 0 ) { CPLError( CE_Warning, CPLE_AppDefined, "%d inner rings discarded from polygon being converted\n" "to old ingres spatial data type '%s'.", poPoly->getNumInteriorRings(), osIngresGeomType.c_str() ); } if( EQUAL(osIngresGeomType,"POLYGON") && poLS->getNumPoints() > 124 ) { CPLError( CE_Failure, CPLE_AppDefined, "Attempt to place %d vertex linestring in %s field.", poLS->getNumPoints(), osIngresGeomType.c_str() ); return OGRERR_FAILURE; } else if( EQUAL(osIngresGeomType,"IPOLYGON") && poLS->getNumPoints() > 248 ) { CPLError( CE_Failure, CPLE_AppDefined, "Attempt to place %d vertex linestring in %s field.", poLS->getNumPoints(), osIngresGeomType.c_str() ); return OGRERR_FAILURE; } // INGRES geometries use *implied* closure of rings. nPoints = poLS->getNumPoints(); if( poLS->getX(0) == poLS->getX(nPoints-1) && poLS->getY(0) == poLS->getY(nPoints-1) && nPoints > 1 ) nPoints--; osRetGeomText = "("; for( i = 0; i < nPoints; i++ ) { CPLString osPoint; if( i > 0 && poLS->getX(i) == poLS->getX(i-1) && poLS->getY(i) == poLS->getY(i-1) ) { CPLDebug( "INGRES", "Dropping duplicate point in linestring."); continue; } if( STARTS_WITH_CI(osIngresGeomType, "I") ) osPoint.Printf( "(%d,%d)", (int) floor(poLS->getX(i)), (int) floor(poLS->getY(i)) ); else osPoint.Printf( "(%.15g,%.15g)", poLS->getX(i), poLS->getY(i) ); if( osRetGeomText.size() > 1 ) osRetGeomText += "," + osPoint; else osRetGeomText += osPoint; } osRetGeomText += ")"; return OGRERR_NONE; } return OGRERR_FAILURE; }
OGRErr OGRPGeoLayer::createFromShapeBin( GByte *pabyShape, OGRGeometry **ppoGeom, int nBytes ) { *ppoGeom = NULL; if( nBytes < 1 ) return OGRERR_FAILURE; int nSHPType = pabyShape[0]; // CPLDebug( "PGeo", // "Shape type read from PGeo data is nSHPType = %d", // nSHPType ); /* -------------------------------------------------------------------- */ /* type 50 appears to just be an alias for normal line */ /* strings. (#1484) */ /* Type 51 appears to just be an alias for normal polygon. (#3100) */ /* TODO: These types include additional attributes including */ /* non-linear segments and such. They should be handled. */ /* -------------------------------------------------------------------- */ switch( nSHPType ) { case 50: nSHPType = SHPT_ARC; break; case 51: nSHPType = SHPT_POLYGON; break; case 52: nSHPType = SHPT_POINT; break; case 53: nSHPType = SHPT_MULTIPOINT; break; case 54: nSHPType = SHPT_MULTIPATCH; } /* ==================================================================== */ /* Extract vertices for a Polygon or Arc. */ /* ==================================================================== */ if( nSHPType == SHPT_ARC || nSHPType == SHPT_ARCZ || nSHPType == SHPT_ARCM || nSHPType == SHPT_ARCZM || nSHPType == SHPT_POLYGON || nSHPType == SHPT_POLYGONZ || nSHPType == SHPT_POLYGONM || nSHPType == SHPT_POLYGONZM || nSHPType == SHPT_MULTIPATCH || nSHPType == SHPT_MULTIPATCHM) { GInt32 nPoints, nParts; int i, nOffset; GInt32 *panPartStart; if (nBytes < 44) { CPLError(CE_Failure, CPLE_AppDefined, "Corrupted Shape : nBytes=%d, nSHPType=%d", nBytes, nSHPType); return OGRERR_FAILURE; } /* -------------------------------------------------------------------- */ /* Extract part/point count, and build vertex and part arrays */ /* to proper size. */ /* -------------------------------------------------------------------- */ memcpy( &nPoints, pabyShape + 40, 4 ); memcpy( &nParts, pabyShape + 36, 4 ); CPL_LSBPTR32( &nPoints ); CPL_LSBPTR32( &nParts ); if (nPoints < 0 || nParts < 0 || nPoints > 50 * 1000 * 1000 || nParts > 10 * 1000 * 1000) { CPLError(CE_Failure, CPLE_AppDefined, "Corrupted Shape : nPoints=%d, nParts=%d.", nPoints, nParts); return OGRERR_FAILURE; } int bHasZ = ( nSHPType == SHPT_POLYGONZ || nSHPType == SHPT_POLYGONZM || nSHPType == SHPT_ARCZ || nSHPType == SHPT_ARCZM || nSHPType == SHPT_MULTIPATCH || nSHPType == SHPT_MULTIPATCHM ); int bIsMultiPatch = ( nSHPType == SHPT_MULTIPATCH || nSHPType == SHPT_MULTIPATCHM ); /* With the previous checks on nPoints and nParts, */ /* we should not overflow here and after */ /* since 50 M * (16 + 8 + 8) = 1 600 MB */ int nRequiredSize = 44 + 4 * nParts + 16 * nPoints; if ( bHasZ ) { nRequiredSize += 16 + 8 * nPoints; } if( bIsMultiPatch ) { nRequiredSize += 4 * nParts; } if (nRequiredSize > nBytes) { CPLError(CE_Failure, CPLE_AppDefined, "Corrupted Shape : nPoints=%d, nParts=%d, nBytes=%d, nSHPType=%d", nPoints, nParts, nBytes, nSHPType); return OGRERR_FAILURE; } panPartStart = (GInt32 *) VSICalloc(nParts,sizeof(GInt32)); if (panPartStart == NULL) { CPLError(CE_Failure, CPLE_OutOfMemory, "Not enough memory for shape (nPoints=%d, nParts=%d)", nPoints, nParts); return OGRERR_FAILURE; } /* -------------------------------------------------------------------- */ /* Copy out the part array from the record. */ /* -------------------------------------------------------------------- */ memcpy( panPartStart, pabyShape + 44, 4 * nParts ); for( i = 0; i < nParts; i++ ) { CPL_LSBPTR32( panPartStart + i ); /* We check that the offset is inside the vertex array */ if (panPartStart[i] < 0 || panPartStart[i] >= nPoints) { CPLError(CE_Failure, CPLE_AppDefined, "Corrupted Shape : panPartStart[%d] = %d, nPoints = %d", i, panPartStart[i], nPoints); CPLFree(panPartStart); return OGRERR_FAILURE; } if (i > 0 && panPartStart[i] <= panPartStart[i-1]) { CPLError(CE_Failure, CPLE_AppDefined, "Corrupted Shape : panPartStart[%d] = %d, panPartStart[%d] = %d", i, panPartStart[i], i - 1, panPartStart[i - 1]); CPLFree(panPartStart); return OGRERR_FAILURE; } } nOffset = 44 + 4*nParts; /* -------------------------------------------------------------------- */ /* If this is a multipatch, we will also have parts types. For */ /* now we ignore and skip past them. */ /* -------------------------------------------------------------------- */ if( bIsMultiPatch ) nOffset += 4*nParts; /* -------------------------------------------------------------------- */ /* Copy out the vertices from the record. */ /* -------------------------------------------------------------------- */ double *padfX = (double *) VSIMalloc(sizeof(double)*nPoints); double *padfY = (double *) VSIMalloc(sizeof(double)*nPoints); double *padfZ = (double *) VSICalloc(sizeof(double),nPoints); if (padfX == NULL || padfY == NULL || padfZ == NULL) { CPLFree( panPartStart ); CPLFree( padfX ); CPLFree( padfY ); CPLFree( padfZ ); CPLError(CE_Failure, CPLE_OutOfMemory, "Not enough memory for shape (nPoints=%d, nParts=%d)", nPoints, nParts); return OGRERR_FAILURE; } for( i = 0; i < nPoints; i++ ) { memcpy(padfX + i, pabyShape + nOffset + i * 16, 8 ); memcpy(padfY + i, pabyShape + nOffset + i * 16 + 8, 8 ); CPL_LSBPTR64( padfX + i ); CPL_LSBPTR64( padfY + i ); } nOffset += 16*nPoints; /* -------------------------------------------------------------------- */ /* If we have a Z coordinate, collect that now. */ /* -------------------------------------------------------------------- */ if( bHasZ ) { for( i = 0; i < nPoints; i++ ) { memcpy( padfZ + i, pabyShape + nOffset + 16 + i*8, 8 ); CPL_LSBPTR64( padfZ + i ); } nOffset += 16 + 8*nPoints; } /* -------------------------------------------------------------------- */ /* Build corresponding OGR objects. */ /* -------------------------------------------------------------------- */ if( nSHPType == SHPT_ARC || nSHPType == SHPT_ARCZ || nSHPType == SHPT_ARCM || nSHPType == SHPT_ARCZM ) { /* -------------------------------------------------------------------- */ /* Arc - As LineString */ /* -------------------------------------------------------------------- */ if( nParts == 1 ) { OGRLineString *poLine = new OGRLineString(); *ppoGeom = poLine; poLine->setPoints( nPoints, padfX, padfY, padfZ ); } /* -------------------------------------------------------------------- */ /* Arc - As MultiLineString */ /* -------------------------------------------------------------------- */ else { OGRMultiLineString *poMulti = new OGRMultiLineString; *ppoGeom = poMulti; for( i = 0; i < nParts; i++ ) { OGRLineString *poLine = new OGRLineString; int nVerticesInThisPart; if( i == nParts-1 ) nVerticesInThisPart = nPoints - panPartStart[i]; else nVerticesInThisPart = panPartStart[i+1] - panPartStart[i]; poLine->setPoints( nVerticesInThisPart, padfX + panPartStart[i], padfY + panPartStart[i], padfZ + panPartStart[i] ); poMulti->addGeometryDirectly( poLine ); } } } /* ARC */ /* -------------------------------------------------------------------- */ /* Polygon */ /* -------------------------------------------------------------------- */ else if( nSHPType == SHPT_POLYGON || nSHPType == SHPT_POLYGONZ || nSHPType == SHPT_POLYGONM || nSHPType == SHPT_POLYGONZM ) { OGRPolygon *poMulti = new OGRPolygon; *ppoGeom = poMulti; for( i = 0; i < nParts; i++ ) { OGRLinearRing *poRing = new OGRLinearRing; int nVerticesInThisPart; if( i == nParts-1 ) nVerticesInThisPart = nPoints - panPartStart[i]; else nVerticesInThisPart = panPartStart[i+1] - panPartStart[i]; poRing->setPoints( nVerticesInThisPart, padfX + panPartStart[i], padfY + panPartStart[i], padfZ + panPartStart[i] ); poMulti->addRingDirectly( poRing ); } } /* polygon */ /* -------------------------------------------------------------------- */ /* Multipatch */ /* -------------------------------------------------------------------- */ else if( bIsMultiPatch ) { /* return to this later */ } CPLFree( panPartStart ); CPLFree( padfX ); CPLFree( padfY ); CPLFree( padfZ ); if( !bHasZ ) (*ppoGeom)->setCoordinateDimension( 2 ); return OGRERR_NONE; } /* ==================================================================== */ /* Extract vertices for a MultiPoint. */ /* ==================================================================== */ else if( nSHPType == SHPT_MULTIPOINT || nSHPType == SHPT_MULTIPOINTM || nSHPType == SHPT_MULTIPOINTZ || nSHPType == SHPT_MULTIPOINTZM ) { #ifdef notdef int32 nPoints; int i, nOffset; memcpy( &nPoints, psSHP->pabyRec + 44, 4 ); if( bBigEndian ) SwapWord( 4, &nPoints ); psShape->nVertices = nPoints; psShape->padfX = (double *) calloc(nPoints,sizeof(double)); psShape->padfY = (double *) calloc(nPoints,sizeof(double)); psShape->padfZ = (double *) calloc(nPoints,sizeof(double)); psShape->padfM = (double *) calloc(nPoints,sizeof(double)); for( i = 0; i < nPoints; i++ ) { memcpy(psShape->padfX+i, psSHP->pabyRec + 48 + 16 * i, 8 ); memcpy(psShape->padfY+i, psSHP->pabyRec + 48 + 16 * i + 8, 8 ); if( bBigEndian ) SwapWord( 8, psShape->padfX + i ); if( bBigEndian ) SwapWord( 8, psShape->padfY + i ); } nOffset = 48 + 16*nPoints; /* -------------------------------------------------------------------- */ /* Get the X/Y bounds. */ /* -------------------------------------------------------------------- */ memcpy( &(psShape->dfXMin), psSHP->pabyRec + 8 + 4, 8 ); memcpy( &(psShape->dfYMin), psSHP->pabyRec + 8 + 12, 8 ); memcpy( &(psShape->dfXMax), psSHP->pabyRec + 8 + 20, 8 ); memcpy( &(psShape->dfYMax), psSHP->pabyRec + 8 + 28, 8 ); if( bBigEndian ) SwapWord( 8, &(psShape->dfXMin) ); if( bBigEndian ) SwapWord( 8, &(psShape->dfYMin) ); if( bBigEndian ) SwapWord( 8, &(psShape->dfXMax) ); if( bBigEndian ) SwapWord( 8, &(psShape->dfYMax) ); /* -------------------------------------------------------------------- */ /* If we have a Z coordinate, collect that now. */ /* -------------------------------------------------------------------- */ if( psShape->nSHPType == SHPT_MULTIPOINTZ || psShape->nSHPType == SHPT_MULTIPOINTZM ) { memcpy( &(psShape->dfZMin), psSHP->pabyRec + nOffset, 8 ); memcpy( &(psShape->dfZMax), psSHP->pabyRec + nOffset + 8, 8 ); if( bBigEndian ) SwapWord( 8, &(psShape->dfZMin) ); if( bBigEndian ) SwapWord( 8, &(psShape->dfZMax) ); for( i = 0; i < nPoints; i++ ) { memcpy( psShape->padfZ + i, psSHP->pabyRec + nOffset + 16 + i*8, 8 ); if( bBigEndian ) SwapWord( 8, psShape->padfZ + i ); } nOffset += 16 + 8*nPoints; } /* -------------------------------------------------------------------- */ /* If we have a M measure value, then read it now. We assume */ /* that the measure can be present for any shape if the size is */ /* big enough, but really it will only occur for the Z shapes */ /* (options), and the M shapes. */ /* -------------------------------------------------------------------- */ if( psSHP->panRecSize[hEntity]+8 >= nOffset + 16 + 8*nPoints ) { memcpy( &(psShape->dfMMin), psSHP->pabyRec + nOffset, 8 ); memcpy( &(psShape->dfMMax), psSHP->pabyRec + nOffset + 8, 8 ); if( bBigEndian ) SwapWord( 8, &(psShape->dfMMin) ); if( bBigEndian ) SwapWord( 8, &(psShape->dfMMax) ); for( i = 0; i < nPoints; i++ ) { memcpy( psShape->padfM + i, psSHP->pabyRec + nOffset + 16 + i*8, 8 ); if( bBigEndian ) SwapWord( 8, psShape->padfM + i ); } } #endif } /* ==================================================================== */ /* Extract vertices for a point. */ /* ==================================================================== */ else if( nSHPType == SHPT_POINT || nSHPType == SHPT_POINTM || nSHPType == SHPT_POINTZ || nSHPType == SHPT_POINTZM ) { int nOffset; double dfX, dfY, dfZ = 0; int bHasZ = (nSHPType == SHPT_POINTZ || nSHPType == SHPT_POINTZM); if (nBytes < 4 + 8 + 8 + ((nSHPType == SHPT_POINTZ) ? 8 : 0)) { CPLError(CE_Failure, CPLE_AppDefined, "Corrupted Shape : nBytes=%d, nSHPType=%d", nBytes, nSHPType); return OGRERR_FAILURE; } memcpy( &dfX, pabyShape + 4, 8 ); memcpy( &dfY, pabyShape + 4 + 8, 8 ); CPL_LSBPTR64( &dfX ); CPL_LSBPTR64( &dfY ); nOffset = 20 + 8; if( bHasZ ) { memcpy( &dfZ, pabyShape + 4 + 16, 8 ); CPL_LSBPTR64( &dfZ ); } *ppoGeom = new OGRPoint( dfX, dfY, dfZ ); if( !bHasZ ) (*ppoGeom)->setCoordinateDimension( 2 ); return OGRERR_NONE; } char* pszHex = CPLBinaryToHex( nBytes, pabyShape ); CPLDebug( "PGEO", "Unsupported geometry type:%d\nnBytes=%d, hex=%s", nSHPType, nBytes, pszHex ); CPLFree(pszHex); return OGRERR_FAILURE; }
OGRFeature *OGRBNALayer::BuildFeatureFromBNARecord (BNARecord* record, long fid) { OGRFeature *poFeature = new OGRFeature( poFeatureDefn ); for( int i = 0; i < nIDs; i++ ) { poFeature->SetField( i, record->ids[i] ? record->ids[i] : ""); } poFeature->SetFID( fid ); if (bnaFeatureType == BNA_POINT) { poFeature->SetGeometryDirectly( new OGRPoint( record->tabCoords[0][0], record->tabCoords[0][1] ) ); } else if (bnaFeatureType == BNA_POLYLINE) { OGRLineString* lineString = new OGRLineString (); lineString->setCoordinateDimension(2); lineString->setNumPoints(record->nCoords); for( int i = 0; i < record->nCoords; i++) { lineString->setPoint( i, record->tabCoords[i][0], record->tabCoords[i][1] ); } poFeature->SetGeometryDirectly(lineString); } else if (bnaFeatureType == BNA_POLYGON) { double firstX = record->tabCoords[0][0]; double firstY = record->tabCoords[0][1]; int isFirstPolygon = 1; double secondaryFirstX = 0, secondaryFirstY = 0; OGRLinearRing* ring = new OGRLinearRing (); ring->setCoordinateDimension(2); ring->addPoint(record->tabCoords[0][0], record->tabCoords[0][1] ); /* record->nCoords is really a safe upper bound */ int nbPolygons = 0; OGRPolygon** tabPolygons = static_cast<OGRPolygon**>( CPLMalloc( record->nCoords * sizeof(OGRPolygon*) ) ); int i = 1; for( ; i < record->nCoords; i++ ) { ring->addPoint(record->tabCoords[i][0], record->tabCoords[i][1] ); if (isFirstPolygon == 1 && record->tabCoords[i][0] == firstX && record->tabCoords[i][1] == firstY) { OGRPolygon* polygon = new OGRPolygon (); polygon->addRingDirectly(ring); tabPolygons[nbPolygons] = polygon; nbPolygons++; if (i == record->nCoords - 1) { break; } isFirstPolygon = 0; i++; secondaryFirstX = record->tabCoords[i][0]; secondaryFirstY = record->tabCoords[i][1]; ring = new OGRLinearRing (); ring->setCoordinateDimension(2); ring->addPoint( record->tabCoords[i][0], record->tabCoords[i][1] ); } else if (isFirstPolygon == 0 && record->tabCoords[i][0] == secondaryFirstX && record->tabCoords[i][1] == secondaryFirstY) { OGRPolygon* polygon = new OGRPolygon (); polygon->addRingDirectly(ring); tabPolygons[nbPolygons] = polygon; nbPolygons++; if (i < record->nCoords - 1) { // After the closing of a subpolygon, the first // coordinates of the first polygon should be // recalled... in theory if (record->tabCoords[i+1][0] == firstX && record->tabCoords[i+1][1] == firstY) { if (i + 1 == record->nCoords - 1) break; i ++; } else { #if 0 CPLError(CE_Warning, CPLE_AppDefined, "Geometry of polygon of fid %d starting at " "line %d is not strictly conformant. " "Trying to go on...\n", fid, offsetAndLineFeaturesTable[fid].line + 1); #endif } i ++; secondaryFirstX = record->tabCoords[i][0]; secondaryFirstY = record->tabCoords[i][1]; ring = new OGRLinearRing (); ring->setCoordinateDimension(2); ring->addPoint( record->tabCoords[i][0], record->tabCoords[i][1] ); } else { #if 0 CPLError( CE_Warning, CPLE_AppDefined, "Geometry of polygon of fid %d starting at " "line %d is not strictly conformant. " "Trying to go on...\n", fid, offsetAndLineFeaturesTable[fid].line + 1); #endif } } } if (i == record->nCoords) { /* Let's be a bit tolerant about non-closing polygons. */ if (isFirstPolygon) { ring->addPoint( record->tabCoords[0][0], record->tabCoords[0][1] ); OGRPolygon* polygon = new OGRPolygon (); polygon->addRingDirectly(ring); tabPolygons[nbPolygons] = polygon; nbPolygons++; } } if (nbPolygons == 1) { // Special optimization here : we directly put the polygon into // the multipolygon. This should save quite a few useless copies OGRMultiPolygon* multipolygon = new OGRMultiPolygon(); multipolygon->addGeometryDirectly(tabPolygons[0]); poFeature->SetGeometryDirectly(multipolygon); } else { int isValidGeometry; poFeature->SetGeometryDirectly( OGRGeometryFactory::organizePolygons( reinterpret_cast<OGRGeometry**>( tabPolygons ), nbPolygons, &isValidGeometry, NULL ) ); if (!isValidGeometry) { CPLError( CE_Warning, CPLE_AppDefined, "Geometry of polygon of fid %ld starting at line %d " "cannot be translated to Simple Geometry. " "All polygons will be contained in a multipolygon.\n", fid, offsetAndLineFeaturesTable[fid].line + 1); } } CPLFree(tabPolygons); } else { // Circle or ellipses are not part of the OGR Simple Geometry, so we // discretize them into polygons by 1 degree step. OGRPolygon* polygon = new OGRPolygon (); OGRLinearRing* ring = new OGRLinearRing (); ring->setCoordinateDimension(2); double center_x = record->tabCoords[0][0]; double center_y = record->tabCoords[0][1]; double major_radius = record->tabCoords[1][0]; double minor_radius = record->tabCoords[1][1]; if (minor_radius == 0) minor_radius = major_radius; for( int i = 0; i < 360; i++ ) { ring->addPoint(center_x + major_radius * cos(i * (M_PI / 180)), center_y + minor_radius * sin(i * (M_PI / 180)) ); } ring->addPoint(center_x + major_radius, center_y); polygon->addRingDirectly ( ring ); poFeature->SetGeometryDirectly(polygon); poFeature->SetField( nIDs, major_radius); poFeature->SetField( nIDs+1, minor_radius); } return poFeature; }
OGRErr OGRBNALayer::ICreateFeature( OGRFeature *poFeature ) { OGRGeometry *poGeom = poFeature->GetGeometryRef(); char eol[3]; const char* partialEol = (poDS->GetMultiLine()) ? eol : poDS->GetCoordinateSeparator(); if (poGeom == NULL || poGeom->IsEmpty() ) { CPLError(CE_Failure, CPLE_AppDefined, "OGR BNA driver cannot write features with empty geometries."); return OGRERR_FAILURE; } if (poDS->GetUseCRLF()) { eol[0] = 13; eol[1] = 10; eol[2] = 0; } else { eol[0] = 10; eol[1] = 0; } if ( ! bWriter ) { return OGRERR_FAILURE; } if( poFeature->GetFID() == OGRNullFID ) poFeature->SetFID( nFeatures++ ); VSILFILE* fp = poDS->GetOutputFP(); int nbPairPerLine = poDS->GetNbPairPerLine(); switch( poGeom->getGeometryType() ) { case wkbPoint: case wkbPoint25D: { OGRPoint* point = (OGRPoint*)poGeom; WriteFeatureAttributes(fp, poFeature); CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "1")); CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "%s", partialEol)); WriteCoord(fp, point->getX(), point->getY()); CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "%s", eol)); break; } case wkbPolygon: case wkbPolygon25D: { OGRPolygon* polygon = (OGRPolygon*)poGeom; OGRLinearRing* ring = polygon->getExteriorRing(); if (ring == NULL) { return OGRERR_FAILURE; } double firstX = ring->getX(0); double firstY = ring->getY(0); int nBNAPoints = ring->getNumPoints(); int is_ellipse = FALSE; /* This code tries to detect an ellipse in a polygon geometry */ /* This will only work presumably on ellipses already read from a BNA file */ /* Mostly a BNA to BNA feature... */ if (poDS->GetEllipsesAsEllipses() && polygon->getNumInteriorRings() == 0 && nBNAPoints == 361) { double oppositeX = ring->getX(180); double oppositeY = ring->getY(180); double quarterX = ring->getX(90); double quarterY = ring->getY(90); double antiquarterX = ring->getX(270); double antiquarterY = ring->getY(270); double center1X = 0.5*(firstX + oppositeX); double center1Y = 0.5*(firstY + oppositeY); double center2X = 0.5*(quarterX + antiquarterX); double center2Y = 0.5*(quarterY + antiquarterY); if (fabs(center1X - center2X) < 1e-5 && fabs(center1Y - center2Y) < 1e-5 && fabs(oppositeY - firstY) < 1e-5 && fabs(quarterX - antiquarterX) < 1e-5) { double major_radius = fabs(firstX - center1X); double minor_radius = fabs(quarterY - center1Y); is_ellipse = TRUE; for(int i=0;i<360;i++) { if (!(fabs(center1X + major_radius * cos(i * (M_PI / 180)) - ring->getX(i)) < 1e-5 && fabs(center1Y + minor_radius * sin(i * (M_PI / 180)) - ring->getY(i)) < 1e-5)) { is_ellipse = FALSE; break; } } if ( is_ellipse == TRUE ) { WriteFeatureAttributes(fp, poFeature); CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "2")); CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "%s", partialEol)); WriteCoord(fp, center1X, center1Y); CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "%s", partialEol)); WriteCoord(fp, major_radius, minor_radius); CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "%s", eol)); } } } if ( is_ellipse == FALSE) { int nInteriorRings = polygon->getNumInteriorRings(); for(int i=0;i<nInteriorRings;i++) { nBNAPoints += polygon->getInteriorRing(i)->getNumPoints() + 1; } if (nBNAPoints <= 3) { CPLError( CE_Failure, CPLE_AppDefined, "Invalid geometry" ); return OGRERR_FAILURE; } WriteFeatureAttributes(fp, poFeature); CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "%d", nBNAPoints)); int n = ring->getNumPoints(); int nbPair = 0; for(int i=0;i<n;i++) { CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "%s", ((nbPair % nbPairPerLine) == 0) ? partialEol : " ")); WriteCoord(fp, ring->getX(i), ring->getY(i)); nbPair++; } for(int i=0;i<nInteriorRings;i++) { ring = polygon->getInteriorRing(i); n = ring->getNumPoints(); for(int j=0;j<n;j++) { CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "%s", ((nbPair % nbPairPerLine) == 0) ? partialEol : " ")); WriteCoord(fp, ring->getX(j), ring->getY(j)); nbPair++; } CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "%s", ((nbPair % nbPairPerLine) == 0) ? partialEol : " ")); WriteCoord(fp, firstX, firstY); nbPair++; } CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "%s", eol)); } break; } case wkbMultiPolygon: case wkbMultiPolygon25D: { OGRMultiPolygon* multipolygon = (OGRMultiPolygon*)poGeom; int N = multipolygon->getNumGeometries(); int nBNAPoints = 0; double firstX = 0, firstY = 0; for(int i=0;i<N;i++) { OGRPolygon* polygon = (OGRPolygon*)multipolygon->getGeometryRef(i); OGRLinearRing* ring = polygon->getExteriorRing(); if (ring == NULL) continue; if (nBNAPoints) nBNAPoints ++; else { firstX = ring->getX(0); firstY = ring->getY(0); } nBNAPoints += ring->getNumPoints(); int nInteriorRings = polygon->getNumInteriorRings(); for(int j=0;j<nInteriorRings;j++) { nBNAPoints += polygon->getInteriorRing(j)->getNumPoints() + 1; } } if (nBNAPoints <= 3) { CPLError( CE_Failure, CPLE_AppDefined, "Invalid geometry" ); return OGRERR_FAILURE; } WriteFeatureAttributes(fp, poFeature); CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "%d", nBNAPoints)); int nbPair = 0; for(int i=0;i<N;i++) { OGRPolygon* polygon = (OGRPolygon*)multipolygon->getGeometryRef(i); OGRLinearRing* ring = polygon->getExteriorRing(); if (ring == NULL) continue; int n = ring->getNumPoints(); int nInteriorRings = polygon->getNumInteriorRings(); for(int j=0;j<n;j++) { CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "%s", ((nbPair % nbPairPerLine) == 0) ? partialEol : " ")); WriteCoord(fp, ring->getX(j), ring->getY(j)); nbPair++; } if (i != 0) { CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "%s", ((nbPair % nbPairPerLine) == 0) ? partialEol : " ")); WriteCoord(fp, firstX, firstY); nbPair++; } for(int j=0;j<nInteriorRings;j++) { ring = polygon->getInteriorRing(j); n = ring->getNumPoints(); for(int k=0;k<n;k++) { CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "%s", ((nbPair % nbPairPerLine) == 0) ? partialEol : " ")); WriteCoord(fp, ring->getX(k), ring->getY(k)); nbPair++; } CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "%s", ((nbPair % nbPairPerLine) == 0) ? partialEol : " ")); WriteCoord(fp, firstX, firstY); nbPair++; } } CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "%s", eol)); break; } case wkbLineString: case wkbLineString25D: { OGRLineString* line = (OGRLineString*)poGeom; int n = line->getNumPoints(); if (n < 2) { CPLError( CE_Failure, CPLE_AppDefined, "Invalid geometry" ); return OGRERR_FAILURE; } WriteFeatureAttributes(fp, poFeature); CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "-%d", n)); int nbPair = 0; for(int i=0;i<n;i++) { CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "%s", partialEol)); WriteCoord(fp, line->getX(i), line->getY(i)); nbPair++; } CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "%s", eol)); break; } default: { CPLError( CE_Failure, CPLE_AppDefined, "Unsupported geometry type : %s.", poGeom->getGeometryName() ); return OGRERR_UNSUPPORTED_GEOMETRY_TYPE; } } return OGRERR_NONE; }
OGRGeometry *OGRGRASSLayer::GetFeatureGeometry ( long nFeatureId, int *cat ) { CPLDebug ( "GRASS", "OGRGRASSLayer::GetFeatureGeometry nFeatureId = %d", nFeatureId ); int cidx = paFeatureIndex[(int)nFeatureId]; int type, id; Vect_cidx_get_cat_by_index ( poMap, iLayerIndex, cidx, cat, &type, &id ); //CPLDebug ( "GRASS", "cat = %d type = %d id = %d", *cat, type, id ); OGRGeometry *poOGR = NULL; int bIs3D = Vect_is_3d(poMap); switch ( type ) { case GV_POINT: { Vect_read_line ( poMap, poPoints, poCats, id); if (bIs3D) poOGR = new OGRPoint( poPoints->x[0], poPoints->y[0], poPoints->z[0] ); else poOGR = new OGRPoint( poPoints->x[0], poPoints->y[0] ); } break; case GV_LINE: case GV_BOUNDARY: { Vect_read_line ( poMap, poPoints, poCats, id); OGRLineString *poOGRLine = new OGRLineString(); if (bIs3D) poOGRLine->setPoints( poPoints->n_points, poPoints->x, poPoints->y, poPoints->z ); else poOGRLine->setPoints( poPoints->n_points, poPoints->x, poPoints->y ); poOGR = poOGRLine; } break; case GV_AREA: { Vect_get_area_points ( poMap, id, poPoints ); OGRPolygon *poOGRPoly; poOGRPoly = new OGRPolygon(); OGRLinearRing *poRing; poRing = new OGRLinearRing(); if (bIs3D) poRing->setPoints( poPoints->n_points, poPoints->x, poPoints->y, poPoints->z ); else poRing->setPoints( poPoints->n_points, poPoints->x, poPoints->y ); poOGRPoly->addRingDirectly( poRing ); // Islands int nisles = Vect_get_area_num_isles ( poMap, id ); for ( int i = 0; i < nisles; i++ ) { int isle = Vect_get_area_isle ( poMap, id, i ); Vect_get_isle_points ( poMap, isle, poPoints ); poRing = new OGRLinearRing(); if (bIs3D) poRing->setPoints( poPoints->n_points, poPoints->x, poPoints->y, poPoints->z ); else poRing->setPoints( poPoints->n_points, poPoints->x, poPoints->y ); poOGRPoly->addRingDirectly( poRing ); } poOGR = poOGRPoly; } break; default: // Should not happen { CPLError( CE_Failure, CPLE_AppDefined, "Unknown GRASS feature type."); return NULL; } } return poOGR; }
PolygonView::PolygonView(MapPolygon* mapPolygon,bool polygonFill,osg::Vec4 color) { this->mapPolygon=mapPolygon; this->geometryEdgePolygon=new osg::Geometry; /*this->geometryPolygon=new osg::Geometry;*/ this->vertices=new osg::Vec3Array; /*this->geometryPolygon->setVertexArray(this->vertices);*/ this->geometryEdgePolygon->setVertexArray(this->vertices); OGRLinearRing *poExteriorRing=mapPolygon->getExteriorRing(); normals=new osg::Vec3Array; normals->push_back(osg::Vec3(0.0f,-1.0f,0.0f)); this->polygonFillColor=new osg::Vec4Array; this->polygonEdgeColor=new osg::Vec4Array; this->polygonFillColor->push_back(color); this->polygonEdgeColor->push_back(edgeColor); { OGRPoint point; for(int i = 0; i < poExteriorRing->getNumPoints(); i++) { poExteriorRing->getPoint(i, &point); vertices->push_back(osg::Vec3(point.getX(), 0, point.getY())); } this->geometryEdgePolygon->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINE_LOOP, 0, vertices->size())); /*this->geometryPolygon->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINE_LOOP, 0, vertices->size()));*/ } if (mapPolygon->getNumInteriorRings()) { for (int i = 0; i < mapPolygon->getNumInteriorRings(); i++) { OGRLinearRing *ring = mapPolygon->getInteriorRing(i); OGRPoint point; for (int j = 0; j < ring->getNumPoints(); j++) { ring->getPoint(j, &point); vertices->push_back(osg::Vec3(point.getX(), 0, point.getY())); } this->geometryEdgePolygon->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINE_LOOP, vertices->size()-ring->getNumPoints() , ring->getNumPoints())); /*this->geometryPolygon->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINE_LOOP, vertices->size()-ring->getNumPoints() , ring->getNumPoints()));*/ } } this->geometryEdgePolygon->setNormalArray(normals); this->geometryEdgePolygon->setNormalBinding(osg::Geometry::BIND_OVERALL); this->geometryEdgePolygon->setColorArray(this->polygonEdgeColor); this->geometryEdgePolygon->setColorBinding(osg::Geometry::BIND_OVERALL); if (polygonFill==true) { this->geometryPolygon=new osg::Geometry; this->geometryPolygon->setVertexArray(this->vertices); for(int i=0;i<this->geometryEdgePolygon->getNumPrimitiveSets();i++) { this->geometryPolygon->addPrimitiveSet(this->geometryEdgePolygon->getPrimitiveSet(i)); } osgUtil::Tessellator tsl; tsl.setTessellationType(osgUtil::Tessellator::TESS_TYPE_GEOMETRY); tsl.setBoundaryOnly(false); tsl.retessellatePolygons(*this->geometryPolygon); osg::Vec3Array* array = triangulizeGeometry(this->geometryPolygon); this->geometryPolygon->setVertexArray(array); this->geometryPolygon->removePrimitiveSet(0,this->geometryPolygon->getNumPrimitiveSets()); this->geometryPolygon->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLES, 0, array->size())); this->geometryPolygon->setNormalArray(normals); this->geometryPolygon->setNormalBinding(osg::Geometry::BIND_OVERALL); this->geometryPolygon->setColorArray(this->polygonFillColor); this->geometryPolygon->setColorBinding(osg::Geometry::BIND_OVERALL); } }
/*! \brief Set feature geometry Also checks if given geometry is valid \param poGeom pointer to OGRGeometry \param ftype geometry VFK type \return TRUE on valid feature or otherwise FALSE */ bool IVFKFeature::SetGeometry(OGRGeometry *poGeom, const char *ftype) { m_bGeometry = TRUE; delete m_paGeom; m_paGeom = NULL; m_bValid = TRUE; if (!poGeom) { return m_bValid; } /* check empty geometries */ if (m_nGeometryType == wkbNone && poGeom->IsEmpty()) { CPLError(CE_Warning, CPLE_AppDefined, "%s: empty geometry fid = " CPL_FRMT_GIB, m_poDataBlock->GetName(), m_nFID); m_bValid = FALSE; } /* check coordinates */ if (m_nGeometryType == wkbPoint) { double x, y; x = ((OGRPoint *) poGeom)->getX(); y = ((OGRPoint *) poGeom)->getY(); if (x > -430000 || x < -910000 || y > -930000 || y < -1230000) { CPLDebug("OGR-VFK", "%s: invalid point fid = " CPL_FRMT_GIB, m_poDataBlock->GetName(), m_nFID); m_bValid = FALSE; } } /* check degenerated polygons */ if (m_nGeometryType == wkbPolygon) { OGRLinearRing *poRing; poRing = ((OGRPolygon *) poGeom)->getExteriorRing(); if (!poRing || poRing->getNumPoints() < 3) { CPLDebug("OGR-VFK", "%s: invalid polygon fid = " CPL_FRMT_GIB, m_poDataBlock->GetName(), m_nFID); m_bValid = FALSE; } } if (m_bValid) { if (ftype) { OGRPoint pt; OGRGeometry *poGeomCurved; OGRCircularString poGeomString; poGeomCurved = NULL; if (EQUAL(ftype, "15") || EQUAL(ftype, "16")) { /* -> circle or arc */ int npoints; npoints = ((OGRLineString *) poGeom)->getNumPoints(); for (int i = 0; i < npoints; i++) { ((OGRLineString *) poGeom)->getPoint(i, &pt); poGeomString.addPoint(&pt); } if (EQUAL(ftype, "15")) { /* compute center and radius of a circle */ double x[3], y[3]; double m1, n1, m2, n2, c1, c2, mx; double c_x, c_y; for (int i = 0; i < npoints; i++) { ((OGRLineString *) poGeom)->getPoint(i, &pt); x[i] = pt.getX(); y[i] = pt.getY(); } m1 = (x[0] + x[1]) / 2.0; n1 = (y[0] + y[1]) / 2.0; m2 = (x[0] + x[2]) / 2.0; n2 = (y[0] + y[2]) / 2.0; c1 = (x[1] - x[0]) * m1 + (y[1] - y[0]) * n1; c2 = (x[2] - x[0]) * m2 + (y[2] - y[0]) * n2; mx = (x[1] - x[0]) * (y[2] - y[0]) + (y[1] - y[0]) * (x[0] - x[2]); c_x = (c1 * (y[2] - y[0]) + c2 * (y[0] - y[1])) / mx; c_y = (c1 * (x[0] - x[2]) + c2 * (x[1] - x[0])) / mx; /* compute a new intermediate point */ pt.setX(c_x - (x[1] - c_x)); pt.setY(c_y - (y[1] - c_y)); poGeomString.addPoint(&pt); /* add last point */ ((OGRLineString *) poGeom)->getPoint(0, &pt); poGeomString.addPoint(&pt); } } else if (strlen(ftype) > 2 && EQUALN(ftype, "15", 2)) { /* -> circle with radius */ float r; char s[3]; /* 15 */ r = 0; if (2 != sscanf(ftype, "%s %f", s, &r) || r < 0) { CPLDebug("OGR-VFK", "%s: invalid circle (unknown or negative radius) " "fid = " CPL_FRMT_GIB, m_poDataBlock->GetName(), m_nFID); m_bValid = FALSE; } else { double c_x, c_y; ((OGRLineString *) poGeom)->getPoint(0, &pt); c_x = pt.getX(); c_y = pt.getY(); /* define first point on a circle */ pt.setX(c_x + r); pt.setY(c_y); poGeomString.addPoint(&pt); /* define second point on a circle */ pt.setX(c_x); pt.setY(c_y + r); poGeomString.addPoint(&pt); /* define third point on a circle */ pt.setX(c_x - r); pt.setY(c_y); poGeomString.addPoint(&pt); /* define fourth point on a circle */ pt.setX(c_x); pt.setY(c_y - r); poGeomString.addPoint(&pt); /* define last point (=first) on a circle */ pt.setX(c_x + r); pt.setY(c_y); poGeomString.addPoint(&pt); } } else if (EQUAL(ftype, "11")) { /* curve */ int npoints; npoints = ((OGRLineString *) poGeom)->getNumPoints(); if (npoints > 2) { /* circular otherwise line string */ for (int i = 0; i < npoints; i++) { ((OGRLineString *) poGeom)->getPoint(i, &pt); poGeomString.addPoint(&pt); } } } if (!poGeomString.IsEmpty()) poGeomCurved = poGeomString.CurveToLine(); if (poGeomCurved) { int npoints; npoints = ((OGRLineString *) poGeomCurved)->getNumPoints(); CPLDebug("OGR-VFK", "%s: curve (type=%s) to linestring (npoints=%d) fid = " CPL_FRMT_GIB, m_poDataBlock->GetName(), ftype, npoints, m_nFID); if (npoints > 1) m_paGeom = (OGRGeometry *) poGeomCurved->clone(); delete poGeomCurved; } } if (!m_paGeom) { /* check degenerated linestrings */ if (m_nGeometryType == wkbLineString) { int npoints; npoints = ((OGRLineString *) poGeom)->getNumPoints(); if (npoints < 2) { CPLError(CE_Warning, CPLE_AppDefined, "%s: invalid linestring (%d vertices) fid = " CPL_FRMT_GIB, m_poDataBlock->GetName(), npoints, m_nFID); m_bValid = FALSE; } } if (m_bValid) m_paGeom = (OGRGeometry *) poGeom->clone(); /* make copy */ } } return m_bValid; }
OGRErr OGRPolygon::exportToWkb( OGRwkbByteOrder eByteOrder, unsigned char * pabyData, OGRwkbVariant eWkbVariant ) const { /* -------------------------------------------------------------------- */ /* Set the byte order. */ /* -------------------------------------------------------------------- */ pabyData[0] = DB2_V72_UNFIX_BYTE_ORDER((unsigned char) eByteOrder); /* -------------------------------------------------------------------- */ /* Set the geometry feature type. */ /* -------------------------------------------------------------------- */ GUInt32 nGType = getGeometryType(); if( eWkbVariant == wkbVariantPostGIS1 ) { nGType = wkbFlatten(nGType); if( Is3D() ) nGType = (OGRwkbGeometryType)(nGType | wkb25DBitInternalUse); /* yes we explicitly set wkb25DBit */ if( IsMeasured() ) nGType = (OGRwkbGeometryType)(nGType | 0x40000000); } else if ( eWkbVariant == wkbVariantIso ) nGType = getIsoGeometryType(); if( eByteOrder == wkbNDR ) nGType = CPL_LSBWORD32( nGType ); else nGType = CPL_MSBWORD32( nGType ); memcpy( pabyData + 1, &nGType, 4 ); /* -------------------------------------------------------------------- */ /* Copy in the raw data. */ /* -------------------------------------------------------------------- */ if( OGR_SWAP( eByteOrder ) ) { int nCount; nCount = CPL_SWAP32( oCC.nCurveCount ); memcpy( pabyData+5, &nCount, 4 ); } else { memcpy( pabyData+5, &oCC.nCurveCount, 4 ); } /* ==================================================================== */ /* Serialize each of the rings. */ /* ==================================================================== */ int nOffset = 9; for( int iRing = 0; iRing < oCC.nCurveCount; iRing++ ) { OGRLinearRing* poLR = (OGRLinearRing*) oCC.papoCurves[iRing]; poLR->_exportToWkb( eByteOrder, flags, pabyData + nOffset ); nOffset += poLR->_WkbSize( flags ); } return OGRERR_NONE; }
OGRErr OGRMultiPolygon::importFromWkt( char ** ppszInput ) { char szToken[OGR_WKT_TOKEN_MAX]; const char *pszInput = *ppszInput; OGRErr eErr = OGRERR_NONE; /* -------------------------------------------------------------------- */ /* Clear existing rings. */ /* -------------------------------------------------------------------- */ empty(); /* -------------------------------------------------------------------- */ /* Read and verify the MULTIPOLYGON keyword token. */ /* -------------------------------------------------------------------- */ pszInput = OGRWktReadToken( pszInput, szToken ); if( !EQUAL(szToken,getGeometryName()) ) return OGRERR_CORRUPT_DATA; /* -------------------------------------------------------------------- */ /* The next character should be a ( indicating the start of the */ /* list of polygons. */ /* -------------------------------------------------------------------- */ pszInput = OGRWktReadToken( pszInput, szToken ); if( EQUAL(szToken,"EMPTY") ) { *ppszInput = (char *) pszInput; return OGRERR_NONE; } if( szToken[0] != '(' ) return OGRERR_CORRUPT_DATA; /* -------------------------------------------------------------------- */ /* If the next token is EMPTY, then verify that we have proper */ /* EMPTY format will a trailing closing bracket. */ /* -------------------------------------------------------------------- */ OGRWktReadToken( pszInput, szToken ); if( EQUAL(szToken,"EMPTY") ) { pszInput = OGRWktReadToken( pszInput, szToken ); pszInput = OGRWktReadToken( pszInput, szToken ); *ppszInput = (char *) pszInput; if( !EQUAL(szToken,")") ) return OGRERR_CORRUPT_DATA; else return OGRERR_NONE; } /* ==================================================================== */ /* Read each polygon in turn. Note that we try to reuse the same */ /* point list buffer from ring to ring to cut down on */ /* allocate/deallocate overhead. */ /* ==================================================================== */ OGRRawPoint *paoPoints = NULL; int nMaxPoints = 0; double *padfZ = NULL; do { OGRPolygon *poPolygon = new OGRPolygon(); /* -------------------------------------------------------------------- */ /* The next character should be a ( indicating the start of the */ /* list of polygons. */ /* -------------------------------------------------------------------- */ pszInput = OGRWktReadToken( pszInput, szToken ); if( szToken[0] != '(' ) { eErr = OGRERR_CORRUPT_DATA; delete poPolygon; break; } /* -------------------------------------------------------------------- */ /* Loop over each ring in this polygon. */ /* -------------------------------------------------------------------- */ do { int nPoints = 0; /* -------------------------------------------------------------------- */ /* Read points for one line from input. */ /* -------------------------------------------------------------------- */ pszInput = OGRWktReadPoints( pszInput, &paoPoints, &padfZ, &nMaxPoints, &nPoints ); if( pszInput == NULL ) { eErr = OGRERR_CORRUPT_DATA; break; } /* -------------------------------------------------------------------- */ /* Create the new line, and add to collection. */ /* -------------------------------------------------------------------- */ OGRLinearRing *poLine; poLine = new OGRLinearRing(); poLine->setPoints( nPoints, paoPoints, padfZ ); poPolygon->addRingDirectly( poLine ); /* -------------------------------------------------------------------- */ /* Read the delimeter following the ring. */ /* -------------------------------------------------------------------- */ pszInput = OGRWktReadToken( pszInput, szToken ); } while( szToken[0] == ',' && eErr == OGRERR_NONE ); /* -------------------------------------------------------------------- */ /* Verify that we have a closing bracket. */ /* -------------------------------------------------------------------- */ if( eErr == OGRERR_NONE ) { if( szToken[0] != ')' ) eErr = OGRERR_CORRUPT_DATA; else pszInput = OGRWktReadToken( pszInput, szToken ); } /* -------------------------------------------------------------------- */ /* Add the polygon to the MULTIPOLYGON. */ /* -------------------------------------------------------------------- */ if( eErr == OGRERR_NONE ) eErr = addGeometryDirectly( poPolygon ); else delete poPolygon; } while( szToken[0] == ',' && eErr == OGRERR_NONE ); /* -------------------------------------------------------------------- */ /* freak if we don't get a closing bracket. */ /* -------------------------------------------------------------------- */ CPLFree( paoPoints ); CPLFree( padfZ ); if( eErr != OGRERR_NONE ) return eErr; if( szToken[0] != ')' ) return OGRERR_CORRUPT_DATA; *ppszInput = (char *) pszInput; return OGRERR_NONE; }
OGRErr OGRPolygon::importFromWKTListOnly( char ** ppszInput, int bHasZ, int bHasM, OGRRawPoint*& paoPoints, int& nMaxPoints, double*& padfZ ) { char szToken[OGR_WKT_TOKEN_MAX]; const char *pszInput = *ppszInput; /* Skip first '(' */ pszInput = OGRWktReadToken( pszInput, szToken ); if( EQUAL(szToken, "EMPTY") ) { *ppszInput = (char*) pszInput; return OGRERR_NONE; } if( !EQUAL(szToken, "(") ) return OGRERR_CORRUPT_DATA; /* ==================================================================== */ /* Read each ring in turn. Note that we try to reuse the same */ /* point list buffer from ring to ring to cut down on */ /* allocate/deallocate overhead. */ /* ==================================================================== */ int nMaxRings = 0; double *padfM = NULL; do { const char* pszNext = OGRWktReadToken( pszInput, szToken ); if (EQUAL(szToken,"EMPTY")) { /* -------------------------------------------------------------------- */ /* Do we need to grow the ring array? */ /* -------------------------------------------------------------------- */ if( oCC.nCurveCount == nMaxRings ) { nMaxRings = nMaxRings * 2 + 1; oCC.papoCurves = (OGRCurve **) CPLRealloc(oCC.papoCurves, nMaxRings * sizeof(OGRLinearRing*)); } oCC.papoCurves[oCC.nCurveCount] = new OGRLinearRing(); oCC.nCurveCount++; pszInput = OGRWktReadToken( pszNext, szToken ); if ( !EQUAL(szToken, ",") ) break; continue; } /* -------------------------------------------------------------------- */ /* Read points for one ring from input. */ /* -------------------------------------------------------------------- */ int nPoints = 0; int flagsFromInput = flags; if( flagsFromInput == 0 ) /* flags was not set, this is not called by us */ { if( bHasM ) flagsFromInput |= OGR_G_MEASURED; if( bHasZ ) flagsFromInput |= OGR_G_3D; } pszInput = OGRWktReadPointsM( pszInput, &paoPoints, &padfZ, &padfM, &flagsFromInput, &nMaxPoints, &nPoints ); if( pszInput == NULL || nPoints == 0 ) { return OGRERR_CORRUPT_DATA; } if( (flagsFromInput & OGR_G_3D) && !(flags & OGR_G_3D) ) { flags |= OGR_G_3D; bHasZ = TRUE; } if( (flagsFromInput & OGR_G_MEASURED) && !(flags & OGR_G_MEASURED) ) { flags |= OGR_G_MEASURED; bHasM = TRUE; } /* -------------------------------------------------------------------- */ /* Do we need to grow the ring array? */ /* -------------------------------------------------------------------- */ if( oCC.nCurveCount == nMaxRings ) { nMaxRings = nMaxRings * 2 + 1; oCC.papoCurves = (OGRCurve **) CPLRealloc(oCC.papoCurves, nMaxRings * sizeof(OGRLinearRing*)); } /* -------------------------------------------------------------------- */ /* Create the new ring, and assign to ring list. */ /* -------------------------------------------------------------------- */ OGRLinearRing* poLR = new OGRLinearRing(); oCC.papoCurves[oCC.nCurveCount] = poLR; if (bHasM && bHasZ) poLR->setPoints( nPoints, paoPoints, padfZ, padfM ); else if (bHasM) poLR->setPointsM( nPoints, paoPoints, padfM ); else if (bHasZ) poLR->setPoints( nPoints, paoPoints, padfZ ); else poLR->setPoints( nPoints, paoPoints, padfZ ); oCC.nCurveCount++; /* -------------------------------------------------------------------- */ /* Read the delimiter following the ring. */ /* -------------------------------------------------------------------- */ pszInput = OGRWktReadToken( pszInput, szToken ); } while( szToken[0] == ',' ); CPLFree( padfM ); /* -------------------------------------------------------------------- */ /* freak if we don't get a closing bracket. */ /* -------------------------------------------------------------------- */ if( szToken[0] != ')' ) return OGRERR_CORRUPT_DATA; *ppszInput = (char *) pszInput; return OGRERR_NONE; }
int main( int argc, char ** argv ) { GDALDriverH hDriver; const char *pszSource=NULL, *pszDest=NULL, *pszFormat = "GTiff"; int bFormatExplicitlySet = FALSE; char **papszLayers = NULL; const char *pszBurnAttribute = NULL; double dfIncreaseBurnValue = 0.0; double dfMultiplyBurnValue = 1.0; const char *pszWHERE = NULL, *pszSQL = NULL; GDALDataType eOutputType = GDT_Float64; char **papszCreateOptions = NULL; GUInt32 nXSize = 0, nYSize = 0; double dfXMin = 0.0, dfXMax = 0.0, dfYMin = 0.0, dfYMax = 0.0; int bIsXExtentSet = FALSE, bIsYExtentSet = FALSE; GDALGridAlgorithm eAlgorithm = GGA_InverseDistanceToAPower; void *pOptions = NULL; char *pszOutputSRS = NULL; int bQuiet = FALSE; GDALProgressFunc pfnProgress = GDALTermProgress; int i; OGRGeometry *poSpatialFilter = NULL; int bClipSrc = FALSE; OGRGeometry *poClipSrc = NULL; const char *pszClipSrcDS = NULL; const char *pszClipSrcSQL = NULL; const char *pszClipSrcLayer = NULL; const char *pszClipSrcWhere = NULL; int bNoDataSet = FALSE; double dfNoDataValue = 0; /* Check strict compilation and runtime library version as we use C++ API */ if (! GDAL_CHECK_VERSION(argv[0])) exit(1); GDALAllRegister(); OGRRegisterAll(); argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 ); if( argc < 1 ) exit( -argc ); /* -------------------------------------------------------------------- */ /* Parse arguments. */ /* -------------------------------------------------------------------- */ for( i = 1; i < argc; i++ ) { if( EQUAL(argv[i], "--utility_version") ) { printf("%s was compiled against GDAL %s and is running against GDAL %s\n", argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME")); return 0; } else if( EQUAL(argv[i],"--help") ) Usage(); else if( EQUAL(argv[i],"-of") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszFormat = argv[++i]; bFormatExplicitlySet = TRUE; } else if( EQUAL(argv[i],"-q") || EQUAL(argv[i],"-quiet") ) { bQuiet = TRUE; pfnProgress = GDALDummyProgress; } else if( EQUAL(argv[i],"-ot") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); int iType; for( iType = 1; iType < GDT_TypeCount; iType++ ) { if( GDALGetDataTypeName((GDALDataType)iType) != NULL && EQUAL(GDALGetDataTypeName((GDALDataType)iType), argv[i+1]) ) { eOutputType = (GDALDataType) iType; } } if( eOutputType == GDT_Unknown ) { Usage(CPLSPrintf("Unknown output pixel type: %s.", argv[i + 1] )); } i++; } else if( EQUAL(argv[i],"-txe") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(2); dfXMin = CPLAtof(argv[++i]); dfXMax = CPLAtof(argv[++i]); bIsXExtentSet = TRUE; } else if( EQUAL(argv[i],"-tye") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(2); dfYMin = CPLAtof(argv[++i]); dfYMax = CPLAtof(argv[++i]); bIsYExtentSet = TRUE; } else if( EQUAL(argv[i],"-outsize") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(2); nXSize = atoi(argv[++i]); nYSize = atoi(argv[++i]); } else if( EQUAL(argv[i],"-co") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); papszCreateOptions = CSLAddString( papszCreateOptions, argv[++i] ); } else if( EQUAL(argv[i],"-zfield") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszBurnAttribute = argv[++i]; } else if( EQUAL(argv[i],"-z_increase") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); dfIncreaseBurnValue = CPLAtof(argv[++i]); } else if( EQUAL(argv[i],"-z_multiply") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); dfMultiplyBurnValue = CPLAtof(argv[++i]); } else if( EQUAL(argv[i],"-where") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszWHERE = argv[++i]; } else if( EQUAL(argv[i],"-l") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); papszLayers = CSLAddString( papszLayers, argv[++i] ); } else if( EQUAL(argv[i],"-sql") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszSQL = argv[++i]; } else if( EQUAL(argv[i],"-spat") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(4); OGRLinearRing oRing; oRing.addPoint( CPLAtof(argv[i+1]), CPLAtof(argv[i+2]) ); oRing.addPoint( CPLAtof(argv[i+1]), CPLAtof(argv[i+4]) ); oRing.addPoint( CPLAtof(argv[i+3]), CPLAtof(argv[i+4]) ); oRing.addPoint( CPLAtof(argv[i+3]), CPLAtof(argv[i+2]) ); oRing.addPoint( CPLAtof(argv[i+1]), CPLAtof(argv[i+2]) ); poSpatialFilter = new OGRPolygon(); ((OGRPolygon *) poSpatialFilter)->addRing( &oRing ); i += 4; } else if ( EQUAL(argv[i],"-clipsrc") ) { if (i + 1 >= argc) Usage(CPLSPrintf("%s option requires 1 or 4 arguments", argv[i])); bClipSrc = TRUE; errno = 0; const double unused = strtod( argv[i + 1], NULL ); // XXX: is it a number or not? if ( errno != 0 && argv[i + 2] != NULL && argv[i + 3] != NULL && argv[i + 4] != NULL) { OGRLinearRing oRing; oRing.addPoint( CPLAtof(argv[i + 1]), CPLAtof(argv[i + 2]) ); oRing.addPoint( CPLAtof(argv[i + 1]), CPLAtof(argv[i + 4]) ); oRing.addPoint( CPLAtof(argv[i + 3]), CPLAtof(argv[i + 4]) ); oRing.addPoint( CPLAtof(argv[i + 3]), CPLAtof(argv[i + 2]) ); oRing.addPoint( CPLAtof(argv[i + 1]), CPLAtof(argv[i + 2]) ); poClipSrc = new OGRPolygon(); ((OGRPolygon *) poClipSrc)->addRing( &oRing ); i += 4; (void)unused; } else if (EQUALN(argv[i + 1], "POLYGON", 7) || EQUALN(argv[i + 1], "MULTIPOLYGON", 12)) { OGRGeometryFactory::createFromWkt(&argv[i + 1], NULL, &poClipSrc); if ( poClipSrc == NULL ) { Usage("Invalid geometry. " "Must be a valid POLYGON or MULTIPOLYGON WKT."); } i++; } else if (EQUAL(argv[i + 1], "spat_extent") ) { i++; } else { pszClipSrcDS = argv[i + 1]; i++; } } else if ( EQUAL(argv[i], "-clipsrcsql") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszClipSrcSQL = argv[i + 1]; i++; } else if ( EQUAL(argv[i], "-clipsrclayer") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszClipSrcLayer = argv[i + 1]; i++; } else if ( EQUAL(argv[i], "-clipsrcwhere") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszClipSrcWhere = argv[i + 1]; i++; } else if( EQUAL(argv[i],"-a_srs") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); OGRSpatialReference oOutputSRS; if( oOutputSRS.SetFromUserInput( argv[i+1] ) != OGRERR_NONE ) { fprintf( stderr, "Failed to process SRS definition: %s\n", argv[i+1] ); GDALDestroyDriverManager(); exit( 1 ); } oOutputSRS.exportToWkt( &pszOutputSRS ); i++; } else if( EQUAL(argv[i],"-a") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); const char* pszAlgorithm = argv[++i]; if ( ParseAlgorithmAndOptions( pszAlgorithm, &eAlgorithm, &pOptions ) != CE_None ) { fprintf( stderr, "Failed to process algorithm name and parameters.\n" ); exit( 1 ); } char **papszParms = CSLTokenizeString2( pszAlgorithm, ":", FALSE ); const char* pszNoDataValue = CSLFetchNameValue( papszParms, "nodata" ); if( pszNoDataValue != NULL ) { bNoDataSet = TRUE; dfNoDataValue = CPLAtofM(pszNoDataValue); } CSLDestroy(papszParms); } else if( argv[i][0] == '-' ) { Usage(CPLSPrintf("Unknown option name '%s'", argv[i])); } else if( pszSource == NULL ) { pszSource = argv[i]; } else if( pszDest == NULL ) { pszDest = argv[i]; } else { Usage("Too many command options."); } } if( pszSource == NULL ) { Usage("Source datasource is not specified."); } if( pszDest == NULL ) { Usage("Target dataset is not specified."); } if( pszSQL == NULL && papszLayers == NULL ) { Usage("Neither -sql nor -l are specified."); } if ( bClipSrc && pszClipSrcDS != NULL ) { poClipSrc = LoadGeometry( pszClipSrcDS, pszClipSrcSQL, pszClipSrcLayer, pszClipSrcWhere ); if ( poClipSrc == NULL ) { Usage("Cannot load source clip geometry."); } } else if ( bClipSrc && poClipSrc == NULL && !poSpatialFilter ) { Usage("-clipsrc must be used with -spat option or \n" "a bounding box, WKT string or datasource must be " "specified."); } if ( poSpatialFilter ) { if ( poClipSrc ) { OGRGeometry *poTemp = poSpatialFilter->Intersection( poClipSrc ); if ( poTemp ) { OGRGeometryFactory::destroyGeometry( poSpatialFilter ); poSpatialFilter = poTemp; } OGRGeometryFactory::destroyGeometry( poClipSrc ); poClipSrc = NULL; } } else { if ( poClipSrc ) { poSpatialFilter = poClipSrc; poClipSrc = NULL; } } /* -------------------------------------------------------------------- */ /* Find the output driver. */ /* -------------------------------------------------------------------- */ hDriver = GDALGetDriverByName( pszFormat ); if( hDriver == NULL ) { int iDr; fprintf( stderr, "FAILURE: Output driver `%s' not recognised.\n", pszFormat ); fprintf( stderr, "The following format drivers are configured and support output:\n" ); for( iDr = 0; iDr < GDALGetDriverCount(); iDr++ ) { GDALDriverH hDriver = GDALGetDriver(iDr); if( GDALGetMetadataItem( hDriver, GDAL_DCAP_RASTER, NULL) != NULL && ( GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) != NULL || GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATECOPY, NULL ) != NULL) ) { fprintf( stderr, " %s: %s\n", GDALGetDriverShortName( hDriver ), GDALGetDriverLongName( hDriver ) ); } } printf( "\n" ); Usage(); } /* -------------------------------------------------------------------- */ /* Open input datasource. */ /* -------------------------------------------------------------------- */ OGRDataSourceH hSrcDS; hSrcDS = OGROpen( pszSource, FALSE, NULL ); if( hSrcDS == NULL ) { fprintf( stderr, "Unable to open input datasource \"%s\".\n", pszSource ); fprintf( stderr, "%s\n", CPLGetLastErrorMsg() ); exit( 3 ); } /* -------------------------------------------------------------------- */ /* Create target raster file. */ /* -------------------------------------------------------------------- */ GDALDatasetH hDstDS; int nLayerCount = CSLCount(papszLayers); int nBands = nLayerCount; if ( pszSQL ) nBands++; // FIXME if ( nXSize == 0 ) nXSize = 256; if ( nYSize == 0 ) nYSize = 256; if (!bQuiet && !bFormatExplicitlySet) CheckExtensionConsistency(pszDest, pszFormat); hDstDS = GDALCreate( hDriver, pszDest, nXSize, nYSize, nBands, eOutputType, papszCreateOptions ); if ( hDstDS == NULL ) { fprintf( stderr, "Unable to create target dataset \"%s\".\n", pszDest ); fprintf( stderr, "%s\n", CPLGetLastErrorMsg() ); exit( 3 ); } if( bNoDataSet ) { for( i = 1; i <= nBands; i++ ) { GDALRasterBandH hBand = GDALGetRasterBand( hDstDS, i ); GDALSetRasterNoDataValue( hBand, dfNoDataValue ); } } /* -------------------------------------------------------------------- */ /* If algorithm was not specified assigh default one. */ /* -------------------------------------------------------------------- */ if ( !pOptions ) ParseAlgorithmAndOptions( szAlgNameInvDist, &eAlgorithm, &pOptions ); /* -------------------------------------------------------------------- */ /* Process SQL request. */ /* -------------------------------------------------------------------- */ if( pszSQL != NULL ) { OGRLayerH hLayer; hLayer = OGR_DS_ExecuteSQL( hSrcDS, pszSQL, (OGRGeometryH)poSpatialFilter, NULL ); if( hLayer != NULL ) { // Custom layer will be rasterized in the first band. ProcessLayer( hLayer, hDstDS, poSpatialFilter, nXSize, nYSize, 1, bIsXExtentSet, bIsYExtentSet, dfXMin, dfXMax, dfYMin, dfYMax, pszBurnAttribute, dfIncreaseBurnValue, dfMultiplyBurnValue, eOutputType, eAlgorithm, pOptions, bQuiet, pfnProgress ); } } /* -------------------------------------------------------------------- */ /* Process each layer. */ /* -------------------------------------------------------------------- */ for( i = 0; i < nLayerCount; i++ ) { OGRLayerH hLayer = OGR_DS_GetLayerByName( hSrcDS, papszLayers[i]); if( hLayer == NULL ) { fprintf( stderr, "Unable to find layer \"%s\", skipping.\n", papszLayers[i] ); continue; } if( pszWHERE ) { if( OGR_L_SetAttributeFilter( hLayer, pszWHERE ) != OGRERR_NONE ) break; } if ( poSpatialFilter != NULL ) OGR_L_SetSpatialFilter( hLayer, (OGRGeometryH)poSpatialFilter ); // Fetch the first meaningful SRS definition if ( !pszOutputSRS ) { OGRSpatialReferenceH hSRS = OGR_L_GetSpatialRef( hLayer ); if ( hSRS ) OSRExportToWkt( hSRS, &pszOutputSRS ); } ProcessLayer( hLayer, hDstDS, poSpatialFilter, nXSize, nYSize, i + 1 + nBands - nLayerCount, bIsXExtentSet, bIsYExtentSet, dfXMin, dfXMax, dfYMin, dfYMax, pszBurnAttribute, dfIncreaseBurnValue, dfMultiplyBurnValue, eOutputType, eAlgorithm, pOptions, bQuiet, pfnProgress ); } /* -------------------------------------------------------------------- */ /* Apply geotransformation matrix. */ /* -------------------------------------------------------------------- */ double adfGeoTransform[6]; adfGeoTransform[0] = dfXMin; adfGeoTransform[1] = (dfXMax - dfXMin) / nXSize; adfGeoTransform[2] = 0.0; adfGeoTransform[3] = dfYMin; adfGeoTransform[4] = 0.0; adfGeoTransform[5] = (dfYMax - dfYMin) / nYSize; GDALSetGeoTransform( hDstDS, adfGeoTransform ); /* -------------------------------------------------------------------- */ /* Apply SRS definition if set. */ /* -------------------------------------------------------------------- */ if ( pszOutputSRS ) { GDALSetProjection( hDstDS, pszOutputSRS ); CPLFree( pszOutputSRS ); } /* -------------------------------------------------------------------- */ /* Cleanup */ /* -------------------------------------------------------------------- */ OGR_DS_Destroy( hSrcDS ); GDALClose( hDstDS ); OGRGeometryFactory::destroyGeometry( poSpatialFilter ); CPLFree( pOptions ); CSLDestroy( papszCreateOptions ); CSLDestroy( argv ); CSLDestroy( papszLayers ); OGRCleanupAll(); GDALDestroyDriverManager(); return 0; }
OGRErr OGRPolygon::exportToWkt( char ** ppszDstText, OGRwkbVariant eWkbVariant ) const { OGRErr eErr; bool bMustWriteComma = false; /* -------------------------------------------------------------------- */ /* If we have no valid exterior ring, return POLYGON EMPTY. */ /* -------------------------------------------------------------------- */ if (getExteriorRing() == NULL || getExteriorRing()->IsEmpty() ) { if( eWkbVariant == wkbVariantIso ) { if( (flags & OGR_G_3D) && (flags & OGR_G_MEASURED) ) *ppszDstText = CPLStrdup("POLYGON ZM EMPTY"); else if( flags & OGR_G_MEASURED ) *ppszDstText = CPLStrdup("POLYGON M EMPTY"); else if( flags & OGR_G_3D ) *ppszDstText = CPLStrdup("POLYGON Z EMPTY"); else *ppszDstText = CPLStrdup("POLYGON EMPTY"); } else *ppszDstText = CPLStrdup("POLYGON EMPTY"); return OGRERR_NONE; } /* -------------------------------------------------------------------- */ /* Build a list of strings containing the stuff for each ring. */ /* -------------------------------------------------------------------- */ char **papszRings = (char **) CPLCalloc(sizeof(char *),oCC.nCurveCount); size_t nCumulativeLength = 0; size_t nNonEmptyRings = 0; size_t *pnRingBeginning = (size_t *) CPLCalloc(sizeof(size_t),oCC.nCurveCount); for( int iRing = 0; iRing < oCC.nCurveCount; iRing++ ) { OGRLinearRing* poLR = (OGRLinearRing*) oCC.papoCurves[iRing]; //poLR->setFlags( getFlags() ); poLR->set3D(Is3D()); poLR->setMeasured(IsMeasured()); if( poLR->getNumPoints() == 0 ) { papszRings[iRing] = NULL; continue; } eErr = poLR->exportToWkt( &(papszRings[iRing]), eWkbVariant ); if( eErr != OGRERR_NONE ) goto error; if( STARTS_WITH_CI(papszRings[iRing], "LINEARRING ZM (") ) pnRingBeginning[iRing] = 14; else if( STARTS_WITH_CI(papszRings[iRing], "LINEARRING M (") ) pnRingBeginning[iRing] = 13; else if( STARTS_WITH_CI(papszRings[iRing], "LINEARRING Z (") ) pnRingBeginning[iRing] = 13; else if( STARTS_WITH_CI(papszRings[iRing], "LINEARRING (") ) pnRingBeginning[iRing] = 11; else { CPLAssert( 0 ); } nCumulativeLength += strlen(papszRings[iRing] + pnRingBeginning[iRing]); nNonEmptyRings++; } /* -------------------------------------------------------------------- */ /* Allocate exactly the right amount of space for the */ /* aggregated string. */ /* -------------------------------------------------------------------- */ *ppszDstText = (char *) VSI_MALLOC_VERBOSE(nCumulativeLength + nNonEmptyRings + 16); if( *ppszDstText == NULL ) { eErr = OGRERR_NOT_ENOUGH_MEMORY; goto error; } /* -------------------------------------------------------------------- */ /* Build up the string, freeing temporary strings as we go. */ /* -------------------------------------------------------------------- */ if( eWkbVariant == wkbVariantIso ) { if( (flags & OGR_G_3D) && (flags & OGR_G_MEASURED) ) strcpy( *ppszDstText, "POLYGON ZM (" ); else if( flags & OGR_G_MEASURED ) strcpy( *ppszDstText, "POLYGON M (" ); else if( flags & OGR_G_3D ) strcpy( *ppszDstText, "POLYGON Z (" ); else strcpy( *ppszDstText, "POLYGON (" ); } else strcpy( *ppszDstText, "POLYGON (" ); nCumulativeLength = strlen(*ppszDstText); for( int iRing = 0; iRing < oCC.nCurveCount; iRing++ ) { if( papszRings[iRing] == NULL ) { CPLDebug( "OGR", "OGRPolygon::exportToWkt() - skipping empty ring."); continue; } if( bMustWriteComma ) (*ppszDstText)[nCumulativeLength++] = ','; bMustWriteComma = true; size_t nRingLen = strlen(papszRings[iRing] + pnRingBeginning[iRing]); memcpy( *ppszDstText + nCumulativeLength, papszRings[iRing] + pnRingBeginning[iRing], nRingLen ); nCumulativeLength += nRingLen; VSIFree( papszRings[iRing] ); } (*ppszDstText)[nCumulativeLength++] = ')'; (*ppszDstText)[nCumulativeLength] = '\0'; CPLFree( papszRings ); CPLFree( pnRingBeginning ); return OGRERR_NONE; error: for( int iRing = 0; iRing < oCC.nCurveCount; iRing++ ) CPLFree(papszRings[iRing]); CPLFree(papszRings); return eErr; }
static void GDALCollectRingsFromGeometry( OGRGeometry *poShape, std::vector<double> &aPointX, std::vector<double> &aPointY, std::vector<double> &aPointVariant, std::vector<int> &aPartSize, GDALBurnValueSrc eBurnValueSrc) { if( poShape == NULL ) return; OGRwkbGeometryType eFlatType = wkbFlatten(poShape->getGeometryType()); int i; if ( eFlatType == wkbPoint ) { OGRPoint *poPoint = (OGRPoint *) poShape; int nNewCount = aPointX.size() + 1; aPointX.reserve( nNewCount ); aPointY.reserve( nNewCount ); aPointX.push_back( poPoint->getX() ); aPointY.push_back( poPoint->getY() ); aPartSize.push_back( 1 ); if( eBurnValueSrc != GBV_UserBurnValue ) { /*switch( eBurnValueSrc ) { case GBV_Z:*/ aPointVariant.reserve( nNewCount ); aPointVariant.push_back( poPoint->getZ() ); /*break; case GBV_M: aPointVariant.reserve( nNewCount ); aPointVariant.push_back( poPoint->getM() ); }*/ } } else if ( eFlatType == wkbLineString ) { OGRLineString *poLine = (OGRLineString *) poShape; int nCount = poLine->getNumPoints(); int nNewCount = aPointX.size() + nCount; aPointX.reserve( nNewCount ); aPointY.reserve( nNewCount ); if( eBurnValueSrc != GBV_UserBurnValue ) aPointVariant.reserve( nNewCount ); for ( i = nCount - 1; i >= 0; i-- ) { aPointX.push_back( poLine->getX(i) ); aPointY.push_back( poLine->getY(i) ); if( eBurnValueSrc != GBV_UserBurnValue ) { /*switch( eBurnValueSrc ) { case GBV_Z:*/ aPointVariant.push_back( poLine->getZ(i) ); /*break; case GBV_M: aPointVariant.push_back( poLine->getM(i) ); }*/ } } aPartSize.push_back( nCount ); } else if ( EQUAL(poShape->getGeometryName(),"LINEARRING") ) { OGRLinearRing *poRing = (OGRLinearRing *) poShape; int nCount = poRing->getNumPoints(); int nNewCount = aPointX.size() + nCount; aPointX.reserve( nNewCount ); aPointY.reserve( nNewCount ); if( eBurnValueSrc != GBV_UserBurnValue ) aPointVariant.reserve( nNewCount ); for ( i = nCount - 1; i >= 0; i-- ) { aPointX.push_back( poRing->getX(i) ); aPointY.push_back( poRing->getY(i) ); } if( eBurnValueSrc != GBV_UserBurnValue ) { /*switch( eBurnValueSrc ) { case GBV_Z:*/ aPointVariant.push_back( poRing->getZ(i) ); /*break; case GBV_M: aPointVariant.push_back( poRing->getM(i) ); }*/ } aPartSize.push_back( nCount ); } else if( eFlatType == wkbPolygon ) { OGRPolygon *poPolygon = (OGRPolygon *) poShape; GDALCollectRingsFromGeometry( poPolygon->getExteriorRing(), aPointX, aPointY, aPointVariant, aPartSize, eBurnValueSrc ); for( i = 0; i < poPolygon->getNumInteriorRings(); i++ ) GDALCollectRingsFromGeometry( poPolygon->getInteriorRing(i), aPointX, aPointY, aPointVariant, aPartSize, eBurnValueSrc ); } else if( eFlatType == wkbMultiPoint || eFlatType == wkbMultiLineString || eFlatType == wkbMultiPolygon || eFlatType == wkbGeometryCollection ) { OGRGeometryCollection *poGC = (OGRGeometryCollection *) poShape; for( i = 0; i < poGC->getNumGeometries(); i++ ) GDALCollectRingsFromGeometry( poGC->getGeometryRef(i), aPointX, aPointY, aPointVariant, aPartSize, eBurnValueSrc ); } else { CPLDebug( "GDAL", "Rasterizer ignoring non-polygonal geometry." ); } }
void PCLoaderArcView::load(const std::string& file, OptionsCont& oc, PCPolyContainer& toFill, PCTypeMap&) { #ifdef HAVE_GDAL GeoConvHelper& geoConvHelper = GeoConvHelper::getProcessing(); // get defaults std::string prefix = oc.getString("prefix"); std::string type = oc.getString("type"); RGBColor color = RGBColor::parseColor(oc.getString("color")); int layer = oc.getInt("layer"); std::string idField = oc.getString("shapefile.id-column"); // start parsing std::string shpName = file + ".shp"; OGRRegisterAll(); OGRDataSource* poDS = OGRSFDriverRegistrar::Open(shpName.c_str(), FALSE); if (poDS == NULL) { throw ProcessError("Could not open shape description '" + shpName + "'."); } // begin file parsing OGRLayer* poLayer = poDS->GetLayer(0); poLayer->ResetReading(); // build coordinate transformation OGRSpatialReference* origTransf = poLayer->GetSpatialRef(); OGRSpatialReference destTransf; // use wgs84 as destination destTransf.SetWellKnownGeogCS("WGS84"); OGRCoordinateTransformation* poCT = OGRCreateCoordinateTransformation(origTransf, &destTransf); if (poCT == NULL) { if (oc.isSet("shapefile.guess-projection")) { OGRSpatialReference origTransf2; origTransf2.SetWellKnownGeogCS("WGS84"); poCT = OGRCreateCoordinateTransformation(&origTransf2, &destTransf); } if (poCT == 0) { WRITE_WARNING("Could not create geocoordinates converter; check whether proj.4 is installed."); } } OGRFeature* poFeature; poLayer->ResetReading(); while ((poFeature = poLayer->GetNextFeature()) != NULL) { // read in edge attributes std::string id = poFeature->GetFieldAsString(idField.c_str()); id = StringUtils::prune(id); if (id == "") { throw ProcessError("Missing id under '" + idField + "'"); } id = prefix + id; // read in the geometry OGRGeometry* poGeometry = poFeature->GetGeometryRef(); if (poGeometry != 0) { // try transform to wgs84 poGeometry->transform(poCT); } OGRwkbGeometryType gtype = poGeometry->getGeometryType(); switch (gtype) { case wkbPoint: { OGRPoint* cgeom = (OGRPoint*) poGeometry; Position pos((SUMOReal) cgeom->getX(), (SUMOReal) cgeom->getY()); if (!geoConvHelper.x2cartesian(pos)) { WRITE_ERROR("Unable to project coordinates for POI '" + id + "'."); } PointOfInterest* poi = new PointOfInterest(id, type, pos, color); if (!toFill.insert(id, poi, layer)) { WRITE_ERROR("POI '" + id + "' could not been added."); delete poi; } } break; case wkbLineString: { OGRLineString* cgeom = (OGRLineString*) poGeometry; PositionVector shape; for (int j = 0; j < cgeom->getNumPoints(); j++) { Position pos((SUMOReal) cgeom->getX(j), (SUMOReal) cgeom->getY(j)); if (!geoConvHelper.x2cartesian(pos)) { WRITE_ERROR("Unable to project coordinates for polygon '" + id + "'."); } shape.push_back_noDoublePos(pos); } Polygon* poly = new Polygon(id, type, color, shape, false); if (!toFill.insert(id, poly, layer)) { WRITE_ERROR("Polygon '" + id + "' could not been added."); delete poly; } } break; case wkbPolygon: { OGRLinearRing* cgeom = ((OGRPolygon*) poGeometry)->getExteriorRing(); PositionVector shape; for (int j = 0; j < cgeom->getNumPoints(); j++) { Position pos((SUMOReal) cgeom->getX(j), (SUMOReal) cgeom->getY(j)); if (!geoConvHelper.x2cartesian(pos)) { WRITE_ERROR("Unable to project coordinates for polygon '" + id + "'."); } shape.push_back_noDoublePos(pos); } Polygon* poly = new Polygon(id, type, color, shape, true); if (!toFill.insert(id, poly, layer)) { WRITE_ERROR("Polygon '" + id + "' could not been added."); delete poly; } } break; case wkbMultiPoint: { OGRMultiPoint* cgeom = (OGRMultiPoint*) poGeometry; for (int i = 0; i < cgeom->getNumGeometries(); ++i) { OGRPoint* cgeom2 = (OGRPoint*) cgeom->getGeometryRef(i); Position pos((SUMOReal) cgeom2->getX(), (SUMOReal) cgeom2->getY()); std::string tid = id + "#" + toString(i); if (!geoConvHelper.x2cartesian(pos)) { WRITE_ERROR("Unable to project coordinates for POI '" + tid + "'."); } PointOfInterest* poi = new PointOfInterest(tid, type, pos, color); if (!toFill.insert(tid, poi, layer)) { WRITE_ERROR("POI '" + tid + "' could not been added."); delete poi; } } } break; case wkbMultiLineString: { OGRMultiLineString* cgeom = (OGRMultiLineString*) poGeometry; for (int i = 0; i < cgeom->getNumGeometries(); ++i) { OGRLineString* cgeom2 = (OGRLineString*) cgeom->getGeometryRef(i); PositionVector shape; std::string tid = id + "#" + toString(i); for (int j = 0; j < cgeom2->getNumPoints(); j++) { Position pos((SUMOReal) cgeom2->getX(j), (SUMOReal) cgeom2->getY(j)); if (!geoConvHelper.x2cartesian(pos)) { WRITE_ERROR("Unable to project coordinates for polygon '" + tid + "'."); } shape.push_back_noDoublePos(pos); } Polygon* poly = new Polygon(tid, type, color, shape, false); if (!toFill.insert(tid, poly, layer)) { WRITE_ERROR("Polygon '" + tid + "' could not been added."); delete poly; } } } break; case wkbMultiPolygon: { OGRMultiPolygon* cgeom = (OGRMultiPolygon*) poGeometry; for (int i = 0; i < cgeom->getNumGeometries(); ++i) { OGRLinearRing* cgeom2 = ((OGRPolygon*) cgeom->getGeometryRef(i))->getExteriorRing(); PositionVector shape; std::string tid = id + "#" + toString(i); for (int j = 0; j < cgeom2->getNumPoints(); j++) { Position pos((SUMOReal) cgeom2->getX(j), (SUMOReal) cgeom2->getY(j)); if (!geoConvHelper.x2cartesian(pos)) { WRITE_ERROR("Unable to project coordinates for polygon '" + tid + "'."); } shape.push_back_noDoublePos(pos); } Polygon* poly = new Polygon(tid, type, color, shape, true); if (!toFill.insert(tid, poly, layer)) { WRITE_ERROR("Polygon '" + tid + "' could not been added."); delete poly; } } } break; default: WRITE_WARNING("Unsupported shape type occured (id='" + id + "')."); break; } OGRFeature::DestroyFeature(poFeature); } PROGRESS_DONE_MESSAGE(); #else WRITE_ERROR("SUMO was compiled without GDAL support."); #endif }
OGRFeature *OGRSUALayer::GetNextRawFeature() { if( bEOF ) return nullptr; CPLString osTYPE; CPLString osCLASS; CPLString osTITLE; CPLString osTOPS; CPLString osBASE; OGRLinearRing oLR; double dfLastLat = 0.0; double dfLastLon = 0.0; bool bFirst = true; while( true ) { const char* pszLine = nullptr; if( bFirst && bHasLastLine ) { pszLine = osLastLine.c_str(); bFirst = false; } else { pszLine = CPLReadLine2L(fpSUA, 1024, nullptr); if (pszLine == nullptr) { bEOF = true; if (oLR.getNumPoints() == 0) return nullptr; break; } osLastLine = pszLine; bHasLastLine = true; } if (pszLine[0] == '#' || pszLine[0] == '\0') continue; if (STARTS_WITH_CI(pszLine, "TYPE=")) { if (!osTYPE.empty()) break; osTYPE = pszLine + 5; } else if (STARTS_WITH_CI(pszLine, "CLASS=")) { if (!osCLASS.empty()) break; osCLASS = pszLine + 6; } else if (STARTS_WITH_CI(pszLine, "TITLE=")) { if (!osTITLE.empty()) break; osTITLE = pszLine + 6; } else if (STARTS_WITH_CI(pszLine, "TOPS=")) osTOPS = pszLine + 5; else if (STARTS_WITH_CI(pszLine, "BASE=")) osBASE = pszLine + 5; else if (STARTS_WITH_CI(pszLine, "POINT=")) { pszLine += 6; if (strlen(pszLine) != 16) continue; double dfLat = 0.0; double dfLon = 0.0; if (!GetLatLon(pszLine, dfLat, dfLon)) continue; oLR.addPoint(dfLon, dfLat); dfLastLat = dfLat; dfLastLon = dfLon; } else if (STARTS_WITH_CI(pszLine, "CLOCKWISE") || STARTS_WITH_CI(pszLine, "ANTI-CLOCKWISE")) { if (oLR.getNumPoints() == 0) continue; int bClockWise = STARTS_WITH_CI(pszLine, "CLOCKWISE"); /*const char* pszRADIUS = strstr(pszLine, "RADIUS="); if (pszRADIUS == NULL) continue; double dfRADIUS = CPLAtof(pszRADIUS + 7) * 1852;*/ const char* pszCENTRE = strstr(pszLine, "CENTRE="); if (pszCENTRE == nullptr) continue; pszCENTRE += 7; if (strlen(pszCENTRE) < 17 || pszCENTRE[16] != ' ') continue; double dfCenterLat = 0.0; double dfCenterLon = 0.0; if (!GetLatLon(pszCENTRE, dfCenterLat, dfCenterLon)) continue; const char* pszTO = strstr(pszLine, "TO="); if (pszTO == nullptr) continue; pszTO += 3; if (strlen(pszTO) != 16) continue; double dfToLat = 0.0; double dfToLon = 0.0; if (!GetLatLon(pszTO, dfToLat, dfToLon)) continue; const double dfStartDistance = OGR_GreatCircle_Distance(dfCenterLat, dfCenterLon, dfLastLat, dfLastLon); const double dfEndDistance = OGR_GreatCircle_Distance(dfCenterLat, dfCenterLon, dfToLat, dfToLon); const double dfStartAngle = OGR_GreatCircle_InitialHeading(dfCenterLat, dfCenterLon, dfLastLat, dfLastLon); double dfEndAngle = OGR_GreatCircle_InitialHeading(dfCenterLat, dfCenterLon, dfToLat, dfToLon); if( bClockWise && dfEndAngle < dfStartAngle ) dfEndAngle += 360; else if (!bClockWise && dfStartAngle < dfEndAngle) dfEndAngle -= 360; int nSign = (bClockWise) ? 1 : -1; for( double dfAngle = dfStartAngle; (dfAngle - dfEndAngle) * nSign < 0; dfAngle += nSign ) { const double pct = (dfAngle - dfStartAngle) / (dfEndAngle - dfStartAngle); const double dfDist = dfStartDistance * (1-pct) + dfEndDistance * pct; double dfLat = 0.0; double dfLon = 0.0; OGR_GreatCircle_ExtendPosition(dfCenterLat, dfCenterLon, dfDist, dfAngle, &dfLat, &dfLon); oLR.addPoint(dfLon, dfLat); } oLR.addPoint(dfToLon, dfToLat); dfLastLat = oLR.getY(oLR.getNumPoints() - 1); dfLastLon = oLR.getX(oLR.getNumPoints() - 1); } else if (STARTS_WITH_CI(pszLine, "CIRCLE")) { const char* pszRADIUS = strstr(pszLine, "RADIUS="); if (pszRADIUS == nullptr) continue; double dfRADIUS = CPLAtof(pszRADIUS + 7) * 1852; const char* pszCENTRE = strstr(pszLine, "CENTRE="); if (pszCENTRE == nullptr) continue; pszCENTRE += 7; if (strlen(pszCENTRE) != 16) continue; double dfCenterLat = 0.0; double dfCenterLon = 0.0; if (!GetLatLon(pszCENTRE, dfCenterLat, dfCenterLon)) continue; double dfLat = 0.0; double dfLon = 0.0; for( double dfAngle = 0; dfAngle < 360; dfAngle += 1 ) { OGR_GreatCircle_ExtendPosition(dfCenterLat, dfCenterLon, dfRADIUS, dfAngle, &dfLat, &dfLon); oLR.addPoint(dfLon, dfLat); } OGR_GreatCircle_ExtendPosition(dfCenterLat, dfCenterLon, dfRADIUS, 0, &dfLat, &dfLon); oLR.addPoint(dfLon, dfLat); dfLastLat = oLR.getY(oLR.getNumPoints() - 1); dfLastLon = oLR.getX(oLR.getNumPoints() - 1); } else if (STARTS_WITH_CI(pszLine, "INCLUDE") || STARTS_WITH_CI(pszLine, "END")) { } else { CPLDebug("SUA", "Unexpected content : %s", pszLine); } } OGRFeature* poFeature = new OGRFeature(poFeatureDefn); poFeature->SetField(0, osTYPE.c_str()); poFeature->SetField(1, osCLASS.c_str()); poFeature->SetField(2, osTITLE.c_str()); poFeature->SetField(3, osTOPS.c_str()); poFeature->SetField(4, osBASE.c_str()); OGRPolygon* poPoly = new OGRPolygon(); poPoly->assignSpatialReference(poSRS); oLR.closeRings(); poPoly->addRing(&oLR); poFeature->SetGeometryDirectly(poPoly); poFeature->SetFID(nNextFID++); return poFeature; }
OGRFeature *OGRSOSILayer::GetNextFeature() { short nName, nNumLines; long nNumCoo; unsigned short nInfo; /* iterate through the SOSI groups*/ while (LC_NextBgr(poNextSerial,LC_FRAMGR)) { nName = LC_RxGr(&oNextSerial, LES_OPTIMALT, &nNumLines, &nNumCoo, &nInfo); S2S oHeaders; S2S::iterator iHeaders; /* extract reference strings from group header */ CPLString osKey, osValue; for (short i=1; i<=nNumLines; i++) { char *pszLine = LC_GetGi(i); if (pszLine[0] == '!') continue; /* If we have a comment line, skip it. */ if ((pszLine[0] == ':')||(pszLine[0] == '(')) { /* if we have a continued REF line... */ osValue.append(CPLString(pszLine)); /* append to previous line. */ oHeaders.insert(std::pair<CPLString,CPLString>(osKey,osValue)); continue; } while (pszLine[0] == '.') pszLine++; /* skipping the dots at the beginning of a SOSI line */ char *pszUTFLine = CPLRecode(pszLine, poParent->pszEncoding, CPL_ENC_UTF8); /* switch to UTF encoding here */ char *pszPos = strstr(pszUTFLine, " "); if (pszPos != NULL) { osKey = CPLString(std::string(pszUTFLine,pszPos)); osValue = CPLString(pszPos+1); oHeaders.insert(std::pair<CPLString,CPLString>(osKey,osValue)); } CPLFree(pszUTFLine); } /* get Feature from fyba, according to feature definition */ OGRGeometry *poGeom = NULL; OGRwkbGeometryType oGType = wkbUnknown; switch (nName) { case INGEN_GRUPPE: { /* No group */ CPLDebug( "[GetNextFeature]", "Could not load further groups - FYBA reported INGEN_GRUPPE."); break; } case L_FLATE: { /* Area */ oGType = wkbPolygon; OGRLinearRing *poOuter = new OGRLinearRing(); /* Initialize a new closed polygon */ long nRefNr; unsigned char nRefStatus; long nRefCount; bool correct = true; LC_GRF_STATUS oGrfStat; // Iterate through all objects that constitute this area. LC_InitGetRefFlate(&oGrfStat); nRefCount = LC_GetRefFlate(&oGrfStat, GRF_YTRE, &nRefNr, &nRefStatus, 1); while (nRefCount > 0) { if (poParent->papoBuiltGeometries[nRefNr] == NULL) { // This should not happen under normal operation. CPLError( CE_Warning, CPLE_AppDefined, "Feature %li referenced by %li, but it was not initialized. Geometry may be broken.", nRefNr, oNextSerial.lNr); correct = false; //return NULL; break; } OGRGeometry *geom = poParent->papoBuiltGeometries[nRefNr]; if (geom->getGeometryType() == wkbLineString) { OGRLineString *poCurve = (OGRLineString*)geom; if (nRefStatus == LC_MED_DIG) { /* clockwise */ poOuter->addSubLineString(poCurve); } else if (nRefStatus == LC_MOT_DIG) { /* counter-clockwise */ poOuter->addSubLineString(poCurve,poCurve->getNumPoints()-1,0); } else { CPLError( CE_Failure, CPLE_OpenFailed, "Internal error: GRF_*_OY encountered."); return NULL; } } else { CPLError( CE_Warning, CPLE_AppDefined, "Element %li composed of non-linestrings (REF %li of type %i). Ignored.", oNextSerial.lNr, nRefNr, geom->getGeometryType()); } nRefCount = LC_GetRefFlate(&oGrfStat, GRF_YTRE, &nRefNr, &nRefStatus, 1); } if (correct) { OGRPolygon *poLy = new OGRPolygon(); poOuter->closeRings(); poLy->addRingDirectly(poOuter); OGRLinearRing *poInner = 0; nRefCount = LC_GetRefFlate(&oGrfStat, GRF_INDRE, &nRefNr, &nRefStatus, 1); while (nRefCount > 0) { if (nRefNr == -1) { if (poInner && (poInner->getNumPoints()>2)) { /* If this is not the first polygon, terminate and add the last */ poInner->closeRings(); poLy->addRingDirectly(poInner); } poInner = new OGRLinearRing(); /* Initialize a new closed polygon */ } else { if (poParent->papoBuiltGeometries[nRefNr] == NULL) { /* this shouldn't happen under normal operation */ CPLError( CE_Fatal, CPLE_AppDefined, "Feature %li referenced by %li, but it was not initialized.", nRefNr, oNextSerial.lNr); return NULL; } OGRGeometry *geom = poParent->papoBuiltGeometries[nRefNr]; if (geom->getGeometryType() == wkbLineString) { OGRLineString *poCurve = (OGRLineString*)geom; if (nRefStatus == LC_MED_DIG) { /* clockwise */ poInner->addSubLineString(poCurve); } else if (nRefStatus == LC_MOT_DIG) { /* counter-clockwise */ poInner->addSubLineString(poCurve,poCurve->getNumPoints()-1,0); } else { CPLError( CE_Failure, CPLE_OpenFailed, "Internal error: GRF_*_OY encountered."); return NULL; } } else { CPLError( CE_Warning, CPLE_AppDefined, "Element %li composed of non-linestrings (REF %li of type %i). Ignored.", oNextSerial.lNr, nRefNr, geom->getGeometryType()); } } nRefCount = LC_GetRefFlate(&oGrfStat, GRF_INDRE, &nRefNr, &nRefStatus, 1); } poGeom = poLy; } break; } case L_KURVE: /* curve */ case L_LINJE: /* curve, not simplifyable */ case L_BUEP: { /* curve, interpolated from circular arc */ oGType = wkbLineString; OGRLineString *poCurve = (OGRLineString*)(poParent->papoBuiltGeometries[oNextSerial.lNr]); if (poCurve == NULL) { CPLError( CE_Fatal, CPLE_AppDefined, "Curve %li was not initialized.", oNextSerial.lNr); return NULL; } poGeom = poCurve->clone(); break; } case L_TEKST: { /* text */ oGType = wkbMultiPoint; OGRMultiPoint *poMP = (OGRMultiPoint*)(poParent->papoBuiltGeometries[oNextSerial.lNr]); if (poMP == NULL) { CPLError( CE_Fatal, CPLE_AppDefined, "Tekst %li was not initialized.", oNextSerial.lNr); return NULL; } poGeom = poMP->clone(); break; } case L_SYMBOL: { //CPLError( CE_Warning, CPLE_OpenFailed, "Geometry of type SYMBOL treated as point (PUNKT)."); } case L_PUNKT: { /* point */ oGType = wkbPoint; OGRPoint *poPoint = (OGRPoint*)(poParent->papoBuiltGeometries[oNextSerial.lNr]); if (poPoint == NULL) { CPLError( CE_Fatal, CPLE_AppDefined, "Point %li was not initialized.", oNextSerial.lNr); return NULL; } poGeom = poPoint->clone(); break; } case L_DEF: /* skip user definitions and headers here */ case L_HODE: { break; } default: { /* complain a bit about anything else that is not implemented */ CPLError( CE_Failure, CPLE_OpenFailed, "Unrecognized geometry of type %i.", nName); break; } } if (poGeom == NULL) continue; /* skipping L_HODE and unrecognized groups */ if (oGType != poFeatureDefn->GetGeomType()) { if (poGeom != NULL) delete poGeom; continue; /* skipping features that are not the correct geometry */ } OGRFeature *poFeature = new OGRFeature( poFeatureDefn ); /* set all headers found in this group - we export everything, just in case */ for (iHeaders = oHeaders.begin(); iHeaders != oHeaders.end(); iHeaders++) { OGRSOSIDataType *poType = SOSIGetType(iHeaders->first); OGRSOSISimpleDataType *poElements = poType->getElements(); const char *pszLine = iHeaders->second.c_str(); char** tokens = CSLTokenizeString(iHeaders->second.c_str()); for (int k=0; k<poType->getElementCount(); k++) { if (tokens[k] == 0) break; if (strcmp(poElements[k].GetName(),"")==0) continue; int iHNr = poHeaderDefn->find(poElements[k].GetName())->second; if (iHNr == -1) { CPLError( CE_Warning, CPLE_AppDefined, "Could not find field definition for %s.", poElements[k].GetName()); continue; } OGRFieldType nType = poElements[k].GetType(); switch (nType) { case OFTInteger: { poFeature->SetField( iHNr, SOSITypeToInt(tokens[k])); break; } case OFTDate: { int date[3]; SOSITypeToDate(tokens[k], date); poFeature->SetField( iHNr, date[0], date[1], date[2]); break; } case OFTDateTime: { int date[6]; SOSITypeToDateTime(tokens[k], date); if (date[0]>0) poFeature->SetField( iHNr, date[0], date[1], date[2], date[3], date[4], static_cast<float>(date[5]), 1); break; } case OFTReal: { poFeature->SetField( iHNr, SOSITypeToReal(tokens[k])); break; } default: { if ((k==0)&&((pszLine[0] == '\'')||(pszLine[0] == '\"'))) { /* If the value is quoted, ignore these */ int nLen = static_cast<int>(strlen(pszLine)); char *pszNline = (char*)CPLMalloc(nLen-1); strncpy(pszNline, pszLine+1, nLen-2); pszNline[nLen-2] = '\0'; poFeature->SetField( iHNr, pszNline); CPLFree(pszNline); } else { poFeature->SetField( iHNr, tokens[k]); } break; } } } CSLDestroy(tokens); } if( poGeom != NULL ) poGeom->assignSpatialReference(poParent->poSRS); poFeature->SetGeometryDirectly( poGeom ); poFeature->SetFID( nNextFID++ ); /* Loop until we have a feature that matches the definition */ if ( (m_poFilterGeom == NULL || FilterGeometry( poFeature->GetGeometryRef() ) ) && (m_poAttrQuery == NULL || m_poAttrQuery->Evaluate( poFeature )) ) return poFeature; delete poFeature; } return NULL; }
/*! \brief Load geometry (polygon BUD/PAR layers) \return number of invalid features */ int VFKDataBlockSQLite::LoadGeometryPolygon() { int nInvalidNoLines, nInvalidNoRings, nGeometries, nBridges; int rowId, nCount, nCountMax; size_t nLines; long iFID; bool bIsPar, bNewRing, bFound; CPLString osSQL; const char *vrColumn[2]; GUIntBig vrValue[2]; GUIntBig id, idOb; sqlite3_stmt *hStmt; VFKReaderSQLite *poReader; VFKDataBlockSQLite *poDataBlockLines1, *poDataBlockLines2; VFKFeatureSQLite *poFeature; VFKFeatureSQLiteList poLineList; /* first is to be considered as exterior */ PointListArray poRingList; std::vector<OGRLinearRing *> poLinearRingList; OGRPolygon ogrPolygon; OGRLinearRing *poOgrRing; nInvalidNoLines = nInvalidNoRings = nGeometries = 0; poReader = (VFKReaderSQLite*) m_poReader; if (EQUAL (m_pszName, "PAR")) { poDataBlockLines1 = (VFKDataBlockSQLite *) m_poReader->GetDataBlock("HP"); poDataBlockLines2 = poDataBlockLines1; bIsPar = TRUE; } else { poDataBlockLines1 = (VFKDataBlockSQLite *) m_poReader->GetDataBlock("OB"); poDataBlockLines2 = (VFKDataBlockSQLite *) m_poReader->GetDataBlock("SBP"); bIsPar = FALSE; } if (NULL == poDataBlockLines1) { CPLError(CE_Warning, CPLE_FileIO, "Data block %s not found. Unable to build geometry for %s.", bIsPar ? "HP" : "OB", m_pszName); return -1; } if (NULL == poDataBlockLines2) { CPLError(CE_Warning, CPLE_FileIO, "Data block %s not found. Unable to build geometry for %s.", "SBP", m_pszName); return -1; } poDataBlockLines1->LoadGeometry(); poDataBlockLines2->LoadGeometry(); if (LoadGeometryFromDB()) /* try to load geometry from DB */ return 0; if (bIsPar) { vrColumn[0] = "PAR_ID_1"; vrColumn[1] = "PAR_ID_2"; } else { vrColumn[0] = "OB_ID"; vrColumn[1] = "PORADOVE_CISLO_BODU"; vrValue[1] = 1; } osSQL.Printf("SELECT ID,%s,rowid FROM %s", FID_COLUMN, m_pszName); hStmt = poReader->PrepareStatement(osSQL.c_str()); if (poReader->IsSpatial()) poReader->ExecuteSQL("BEGIN"); while(poReader->ExecuteSQL(hStmt) == OGRERR_NONE) { nBridges = 0; /* read values */ id = sqlite3_column_int64(hStmt, 0); iFID = static_cast<long>(sqlite3_column_int64(hStmt, 1)); rowId = sqlite3_column_int(hStmt, 2); poFeature = (VFKFeatureSQLite *) GetFeatureByIndex(rowId - 1); CPLAssert(NULL != poFeature && poFeature->GetFID() == iFID); if (bIsPar) { vrValue[0] = vrValue[1] = id; poLineList = poDataBlockLines1->GetFeatures(vrColumn, vrValue, 2); } else { VFKFeatureSQLite *poLineSbp; std::vector<VFKFeatureSQLite *> poLineListOb; sqlite3_stmt *hStmtOb; osSQL.Printf("SELECT ID FROM %s WHERE BUD_ID = " CPL_FRMT_GUIB, poDataBlockLines1->GetName(), id); if (poReader->IsSpatial()) { CPLString osColumn; osColumn.Printf(" AND %s IS NULL", GEOM_COLUMN); osSQL += osColumn; } hStmtOb = poReader->PrepareStatement(osSQL.c_str()); while(poReader->ExecuteSQL(hStmtOb) == OGRERR_NONE) { idOb = sqlite3_column_int64(hStmtOb, 0); vrValue[0] = idOb; poLineSbp = poDataBlockLines2->GetFeature(vrColumn, vrValue, 2); if (poLineSbp) poLineList.push_back(poLineSbp); } } nLines = poLineList.size(); if (nLines < 1) { CPLDebug("OGR-VFK", "%s: unable to collect rings for polygon fid = %ld (no lines)", m_pszName, iFID); nInvalidNoLines++; continue; } /* clear */ ogrPolygon.empty(); poRingList.clear(); /* collect rings from lines */ bFound = FALSE; nCount = 0; nCountMax = static_cast<int>(nLines) * 2; while (poLineList.size() > 0 && nCount < nCountMax) { bNewRing = !bFound ? TRUE : FALSE; bFound = FALSE; int i = 1; for (VFKFeatureSQLiteList::iterator iHp = poLineList.begin(), eHp = poLineList.end(); iHp != eHp; ++iHp, ++i) { const OGRLineString *pLine = (OGRLineString *) (*iHp)->GetGeometry(); if (pLine && AppendLineToRing(&poRingList, pLine, bNewRing)) { bFound = TRUE; poLineList.erase(iHp); break; } } nCount++; } CPLDebug("OGR-VFK", "%s: fid = %ld nlines = %d -> nrings = %d", m_pszName, iFID, (int)nLines, (int)poRingList.size()); if (poLineList.size() > 0) { CPLDebug("OGR-VFK", "%s: unable to collect rings for polygon fid = %ld", m_pszName, iFID); nInvalidNoRings++; continue; } /* build rings */ poLinearRingList.clear(); int i = 1; for (PointListArray::const_iterator iRing = poRingList.begin(), eRing = poRingList.end(); iRing != eRing; ++iRing) { OGRPoint *poPoint; PointList *poList = *iRing; poLinearRingList.push_back(new OGRLinearRing()); poOgrRing = poLinearRingList.back(); CPLAssert(NULL != poOgrRing); for (PointList::iterator iPoint = poList->begin(), ePoint = poList->end(); iPoint != ePoint; ++iPoint) { poPoint = &(*iPoint); poOgrRing->addPoint(poPoint); } i++; } /* find exterior ring */ if (poLinearRingList.size() > 1) { double dArea, dMaxArea; std::vector<OGRLinearRing *>::iterator exteriorRing; exteriorRing = poLinearRingList.begin(); dMaxArea = -1.; for (std::vector<OGRLinearRing *>::iterator iRing = poLinearRingList.begin(), eRing = poLinearRingList.end(); iRing != eRing; ++iRing) { poOgrRing = *iRing; if (!IsRingClosed(poOgrRing)) continue; /* skip unclosed rings */ dArea = poOgrRing->get_Area(); if (dArea > dMaxArea) { dMaxArea = dArea; exteriorRing = iRing; } } if (exteriorRing != poLinearRingList.begin()) { std::swap(*poLinearRingList.begin(), *exteriorRing); } } /* build polygon from rings */ for (std::vector<OGRLinearRing *>::iterator iRing = poLinearRingList.begin(), eRing = poLinearRingList.end(); iRing != eRing; ++iRing) { poOgrRing = *iRing; /* check if ring is closed */ if (IsRingClosed(poOgrRing)) { ogrPolygon.addRing(poOgrRing); } else { if (poOgrRing->getNumPoints() == 2) { CPLDebug("OGR-VFK", "%s: Polygon (fid = %ld) bridge removed", m_pszName, iFID); nBridges++; } else { CPLDebug("OGR-VFK", "%s: Polygon (fid = %ld) unclosed ring skipped", m_pszName, iFID); } } delete poOgrRing; *iRing = NULL; } /* set polygon */ ogrPolygon.setCoordinateDimension(2); /* force 2D */ if (ogrPolygon.getNumInteriorRings() + nBridges != (int) poLinearRingList.size() - 1 || !poFeature->SetGeometry(&ogrPolygon)) { nInvalidNoRings++; continue; } /* store also geometry in DB */ if (poReader->IsSpatial() && SaveGeometryToDB(&ogrPolygon, rowId) != OGRERR_FAILURE) nGeometries++; } /* free ring list */ for (PointListArray::iterator iRing = poRingList.begin(), eRing = poRingList.end(); iRing != eRing; ++iRing) { delete (*iRing); *iRing = NULL; } CPLDebug("OGR-VFK", "%s: nolines = %d norings = %d", m_pszName, nInvalidNoLines, nInvalidNoRings); /* update number of geometries in VFK_DB_TABLE table */ UpdateVfkBlocks(nGeometries); if (poReader->IsSpatial()) poReader->ExecuteSQL("COMMIT"); return nInvalidNoLines + nInvalidNoRings; }
OGRFeature *OGROpenAirLayer::GetNextRawFeature() { const char* pszLine; CPLString osCLASS, osNAME, osFLOOR, osCEILING; OGRLinearRing oLR; double dfLastLat = 0, dfLastLon = 0; int bFirst = TRUE; int bClockWise = TRUE; double dfCenterLat = 0, dfCenterLon = 0; int bHasCenter = FALSE; OpenAirStyle sStyle; sStyle.penStyle = -1; sStyle.penWidth = -1; sStyle.penR = sStyle.penG = sStyle.penB = -1; sStyle.fillR = sStyle.fillG = sStyle.fillB = -1; if (bEOF) return NULL; while(TRUE) { if (bFirst && bHasLastLine) { pszLine = osLastLine.c_str(); bFirst = FALSE; } else { pszLine = CPLReadLine2L(fpOpenAir, 1024, NULL); if (pszLine == NULL) { bEOF = TRUE; if (oLR.getNumPoints() == 0) return NULL; if (osCLASS.size() != 0 && oStyleMap.find(osCLASS) != oStyleMap.end()) { memcpy(&sStyle, oStyleMap[osCLASS], sizeof(sStyle)); } break; } osLastLine = pszLine; bHasLastLine = TRUE; } if (pszLine[0] == '*' || pszLine[0] == '\0') continue; if (EQUALN(pszLine, "AC ", 3) || EQUALN(pszLine, "AC,", 3)) { if (osCLASS.size() != 0) { if (sStyle.penStyle != -1 || sStyle.fillR != -1) { if (oLR.getNumPoints() == 0) { OpenAirStyle* psStyle; if (oStyleMap.find(osCLASS) == oStyleMap.end()) { psStyle = (OpenAirStyle*)CPLMalloc( sizeof(OpenAirStyle)); oStyleMap[osCLASS] = psStyle; } else psStyle = oStyleMap[osCLASS]; memcpy(psStyle, &sStyle, sizeof(sStyle)); } else break; } else if (oStyleMap.find(osCLASS) != oStyleMap.end()) { memcpy(&sStyle, oStyleMap[osCLASS], sizeof(sStyle)); break; } else break; } sStyle.penStyle = -1; sStyle.penWidth = -1; sStyle.penR = sStyle.penG = sStyle.penB = -1; sStyle.fillR = sStyle.fillG = sStyle.fillB = -1; osCLASS = pszLine + 3; bClockWise = TRUE; bHasCenter = FALSE; } else if (EQUALN(pszLine, "AN ", 3)) { if (osNAME.size() != 0) break; osNAME = pszLine + 3; } else if (EQUALN(pszLine, "AH ", 3)) osCEILING = pszLine + 3; else if (EQUALN(pszLine, "AL ", 3)) osFLOOR = pszLine + 3; else if (EQUALN(pszLine, "AT ", 3)) { /* Ignored for that layer*/ } else if (EQUALN(pszLine, "SP ", 3)) { if (osCLASS.size() != 0) { char** papszTokens = CSLTokenizeString2(pszLine+3, ", ", 0); if (CSLCount(papszTokens) == 5) { sStyle.penStyle = atoi(papszTokens[0]); sStyle.penWidth = atoi(papszTokens[1]); sStyle.penR = atoi(papszTokens[2]); sStyle.penG = atoi(papszTokens[3]); sStyle.penB = atoi(papszTokens[4]); } CSLDestroy(papszTokens); } } else if (EQUALN(pszLine, "SB ", 3)) { if (osCLASS.size() != 0) { char** papszTokens = CSLTokenizeString2(pszLine+3, ", ", 0); if (CSLCount(papszTokens) == 3) { sStyle.fillR = atoi(papszTokens[0]); sStyle.fillG = atoi(papszTokens[1]); sStyle.fillB = atoi(papszTokens[2]); } CSLDestroy(papszTokens); } } else if (EQUALN(pszLine, "DP ", 3)) { pszLine += 3; double dfLat, dfLon; if (!OGROpenAirGetLatLon(pszLine, dfLat, dfLon)) continue; oLR.addPoint(dfLon, dfLat); dfLastLat = dfLat; dfLastLon = dfLon; } else if (EQUALN(pszLine, "DA ", 3)) { pszLine += 3; char* pszStar = strchr((char*)pszLine, '*'); if (pszStar) *pszStar = 0; char** papszTokens = CSLTokenizeString2(pszLine, ",", 0); if (bHasCenter && CSLCount(papszTokens) == 3) { double dfRadius = atof(papszTokens[0]) * 1852; double dfStartAngle = atof(papszTokens[1]); double dfEndAngle = atof(papszTokens[2]); if (bClockWise && dfEndAngle < dfStartAngle) dfEndAngle += 360; else if (!bClockWise && dfStartAngle < dfEndAngle) dfEndAngle -= 360; double dfStartDistance = dfRadius; double dfEndDistance = dfRadius; int nSign = (bClockWise) ? 1 : -1; double dfAngle; double dfLat, dfLon; for(dfAngle = dfStartAngle; (dfAngle - dfEndAngle) * nSign < 0; dfAngle += nSign) { double pct = (dfAngle - dfStartAngle) / (dfEndAngle - dfStartAngle); double dfDist = dfStartDistance * (1-pct) + dfEndDistance * pct; OGRXPlane_ExtendPosition(dfCenterLat, dfCenterLon, dfDist, dfAngle, &dfLat, &dfLon); oLR.addPoint(dfLon, dfLat); } OGRXPlane_ExtendPosition(dfCenterLat, dfCenterLon, dfEndDistance, dfEndAngle, &dfLat, &dfLon); oLR.addPoint(dfLon, dfLat); dfLastLat = oLR.getY(oLR.getNumPoints() - 1); dfLastLon = oLR.getX(oLR.getNumPoints() - 1); } CSLDestroy(papszTokens); } else if (EQUALN(pszLine, "DB ", 3)) { pszLine += 3; char* pszStar = strchr((char*)pszLine, '*'); if (pszStar) *pszStar = 0; char** papszTokens = CSLTokenizeString2(pszLine, ",", 0); double dfFirstLat, dfFirstLon; double dfSecondLat, dfSecondLon; if (bHasCenter && CSLCount(papszTokens) == 2 && OGROpenAirGetLatLon(papszTokens[0], dfFirstLat, dfFirstLon) && OGROpenAirGetLatLon(papszTokens[1], dfSecondLat, dfSecondLon)) { double dfStartDistance =OGRXPlane_Distance(dfCenterLat, dfCenterLon, dfFirstLat, dfFirstLon); double dfEndDistance = OGRXPlane_Distance(dfCenterLat, dfCenterLon, dfSecondLat, dfSecondLon); double dfStartAngle = OGRXPlane_Track(dfCenterLat, dfCenterLon, dfFirstLat, dfFirstLon); double dfEndAngle = OGRXPlane_Track(dfCenterLat, dfCenterLon, dfSecondLat, dfSecondLon); if (bClockWise && dfEndAngle < dfStartAngle) dfEndAngle += 360; else if (!bClockWise && dfStartAngle < dfEndAngle) dfEndAngle -= 360; int nSign = (bClockWise) ? 1 : -1; double dfAngle; for(dfAngle = dfStartAngle; (dfAngle - dfEndAngle) * nSign < 0; dfAngle += nSign) { double dfLat, dfLon; double pct = (dfAngle - dfStartAngle) / (dfEndAngle - dfStartAngle); double dfDist = dfStartDistance * (1-pct) + dfEndDistance * pct; OGRXPlane_ExtendPosition(dfCenterLat, dfCenterLon, dfDist, dfAngle, &dfLat, &dfLon); oLR.addPoint(dfLon, dfLat); } oLR.addPoint(dfSecondLon, dfSecondLat); dfLastLat = oLR.getY(oLR.getNumPoints() - 1); dfLastLon = oLR.getX(oLR.getNumPoints() - 1); } CSLDestroy(papszTokens); } else if ((EQUALN(pszLine, "DC ", 3) || EQUALN(pszLine, "DC=", 3)) && (bHasCenter || strstr(pszLine, "V X=") != NULL)) { if (!bHasCenter) { const char* pszVX = strstr(pszLine, "V X="); bHasCenter = OGROpenAirGetLatLon(pszVX, dfCenterLat, dfCenterLon); } if (bHasCenter) { pszLine += 3; double dfRADIUS = atof(pszLine) * 1852; double dfAngle; double dfLat, dfLon; for(dfAngle = 0; dfAngle < 360; dfAngle += 1) { OGRXPlane_ExtendPosition(dfCenterLat, dfCenterLon, dfRADIUS, dfAngle, &dfLat, &dfLon); oLR.addPoint(dfLon, dfLat); } OGRXPlane_ExtendPosition(dfCenterLat, dfCenterLon, dfRADIUS, 0, &dfLat, &dfLon); oLR.addPoint(dfLon, dfLat); dfLastLat = oLR.getY(oLR.getNumPoints() - 1); dfLastLon = oLR.getX(oLR.getNumPoints() - 1); } } else if (EQUALN(pszLine, "V X=", 4)) { bHasCenter = OGROpenAirGetLatLon(pszLine + 4, dfCenterLat, dfCenterLon); } else if (EQUALN(pszLine, "V D=-", 5)) { bClockWise = FALSE; } else if (EQUALN(pszLine, "V D=+", 5)) { bClockWise = TRUE; } else { //CPLDebug("OpenAir", "Unexpected content : %s", pszLine); } } OGRFeature* poFeature = new OGRFeature(poFeatureDefn); poFeature->SetField(0, osCLASS.c_str()); poFeature->SetField(1, osNAME.c_str()); poFeature->SetField(2, osFLOOR.c_str()); poFeature->SetField(3, osCEILING.c_str()); if (sStyle.penStyle != -1 || sStyle.fillR != -1) { CPLString osStyle; if (sStyle.penStyle != -1) { osStyle += CPLString().Printf("PEN(c:#%02X%02X%02X,w:%dpt", sStyle.penR, sStyle.penG, sStyle.penB, sStyle.penWidth); if (sStyle.penStyle == 1) osStyle += ",p:\"5px 5px\""; osStyle += ")"; } if (sStyle.fillR != -1) { if (osStyle.size() != 0) osStyle += ";"; osStyle += CPLString().Printf("BRUSH(fc:#%02X%02X%02X)", sStyle.fillR, sStyle.fillG, sStyle.fillB); } else { if (osStyle.size() != 0) osStyle += ";"; osStyle += "BRUSH(fc:#00000000,id:\"ogr-brush-1\")"; } if (osStyle.size() != 0) poFeature->SetStyleString(osStyle); } OGRPolygon* poPoly = new OGRPolygon(); oLR.closeRings(); poPoly->addRing(&oLR); poPoly->assignSpatialReference(poSRS); poFeature->SetGeometryDirectly(poPoly); poFeature->SetFID(nNextFID++); return poFeature; }
OGRFeature * OGRSDTSLayer::GetNextUnfilteredFeature() { /* -------------------------------------------------------------------- */ /* If not done before we need to assemble the geometry for a */ /* polygon layer. */ /* -------------------------------------------------------------------- */ if( poTransfer->GetLayerType(iLayer) == SLTPoly ) { ((SDTSPolygonReader *) poReader)->AssembleRings(poTransfer,iLayer); } /* -------------------------------------------------------------------- */ /* Fetch the next sdts style feature object from the reader. */ /* -------------------------------------------------------------------- */ SDTSFeature *poSDTSFeature = poReader->GetNextFeature(); OGRFeature *poFeature; if( poSDTSFeature == NULL ) return NULL; /* -------------------------------------------------------------------- */ /* Create the OGR feature. */ /* -------------------------------------------------------------------- */ poFeature = new OGRFeature( poFeatureDefn ); m_nFeaturesRead++; switch( poTransfer->GetLayerType(iLayer) ) { /* -------------------------------------------------------------------- */ /* Translate point feature specific information and geometry. */ /* -------------------------------------------------------------------- */ case SLTPoint: { SDTSRawPoint *poPoint = (SDTSRawPoint *) poSDTSFeature; poFeature->SetGeometryDirectly( new OGRPoint( poPoint->dfX, poPoint->dfY, poPoint->dfZ ) ); } break; /* -------------------------------------------------------------------- */ /* Translate line feature specific information and geometry. */ /* -------------------------------------------------------------------- */ case SLTLine: { SDTSRawLine *poLine = (SDTSRawLine *) poSDTSFeature; OGRLineString *poOGRLine = new OGRLineString(); poOGRLine->setPoints( poLine->nVertices, poLine->padfX, poLine->padfY, poLine->padfZ ); poFeature->SetGeometryDirectly( poOGRLine ); poFeature->SetField( "SNID", (int) poLine->oStartNode.nRecord ); poFeature->SetField( "ENID", (int) poLine->oEndNode.nRecord ); } break; /* -------------------------------------------------------------------- */ /* Translate polygon feature specific information and geometry. */ /* -------------------------------------------------------------------- */ case SLTPoly: { SDTSRawPolygon *poPoly = (SDTSRawPolygon *) poSDTSFeature; OGRPolygon *poOGRPoly = new OGRPolygon(); for( int iRing = 0; iRing < poPoly->nRings; iRing++ ) { OGRLinearRing *poRing = new OGRLinearRing(); int nVertices; if( iRing == poPoly->nRings - 1 ) nVertices = poPoly->nVertices - poPoly->panRingStart[iRing]; else nVertices = poPoly->panRingStart[iRing+1] - poPoly->panRingStart[iRing]; poRing->setPoints( nVertices, poPoly->padfX + poPoly->panRingStart[iRing], poPoly->padfY + poPoly->panRingStart[iRing], poPoly->padfZ + poPoly->panRingStart[iRing] ); poOGRPoly->addRingDirectly( poRing ); } poFeature->SetGeometryDirectly( poOGRPoly ); } break; default: break; } /* -------------------------------------------------------------------- */ /* Set attributes for any indicated attribute records. */ /* -------------------------------------------------------------------- */ int iAttrRecord; for( iAttrRecord = 0; iAttrRecord < poSDTSFeature->nAttributes; iAttrRecord++) { DDFField *poSR; poSR = poTransfer->GetAttr( poSDTSFeature->paoATID+iAttrRecord ); if( poSR != NULL ) AssignAttrRecordToFeature( poFeature, poTransfer, poSR ); } /* -------------------------------------------------------------------- */ /* If this record is an attribute record, attach the local */ /* attributes. */ /* -------------------------------------------------------------------- */ if( poTransfer->GetLayerType(iLayer) == SLTAttr ) { AssignAttrRecordToFeature( poFeature, poTransfer, ((SDTSAttrRecord *) poSDTSFeature)->poATTR); } /* -------------------------------------------------------------------- */ /* Translate the record id. */ /* -------------------------------------------------------------------- */ poFeature->SetFID( poSDTSFeature->oModId.nRecord ); poFeature->SetField( 0, (int) poSDTSFeature->oModId.nRecord ); if( poFeature->GetGeometryRef() != NULL ) poFeature->GetGeometryRef()->assignSpatialReference( poDS->GetSpatialRef() ); if( !poReader->IsIndexed() ) delete poSDTSFeature; return poFeature; }
void CDlg_GISDataExchange::ExportToGISFile(LPCTSTR lpszCSVFileName,LPCTSTR lpszShapeFileName, CString GISTypeString ) { #ifndef _WIN64 m_MessageList.ResetContent (); CWaitCursor wait; CCSVParser parser; int i= 0; // open csv file if (parser.OpenCSVFile(lpszCSVFileName)) { CString message_str; OGRSFDriver *poDriver; OGRRegisterAll(); poDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(GISTypeString ); if( poDriver == NULL ) { message_str.Format ( "%s driver not available.", GISTypeString ); m_MessageList.AddString (message_str); return; } OGRDataSource *poDS; poDS = poDriver->CreateDataSource(lpszShapeFileName, NULL ); if( poDS == NULL ) { message_str.Format ( "Creation of GIS output file %s failed.\nPlease do not overwrite the exiting file and please select a new file name.", lpszShapeFileName ); m_MessageList.AddString (message_str); return; } ///// export to link layer // link layer OGRLayer *poLayer; poLayer = poDS->CreateLayer( "link", NULL, wkbLineString, NULL ); if( poLayer == NULL ) { m_MessageList.AddString ("link Layer creation failed"); return; } vector<string> HeaderVector = parser.GetHeaderVector(); std::vector <CString> LongFieldVector; for(unsigned int i = 0; i < HeaderVector.size(); i++) { if(HeaderVector[i].find ("geometry") != string::npos|| HeaderVector[i].find ("name") != string::npos || HeaderVector[i].find ("code") != string::npos) { OGRFieldDefn oField (HeaderVector[i].c_str (), OFTString); CString str; if( poLayer->CreateField( &oField ) != OGRERR_NONE ) { str.Format("Creating field %s failed", oField.GetNameRef()); m_MessageList.AddString (str); return; } }else { CString field_string = HeaderVector[i].c_str (); OGRFieldDefn oField (field_string, OFTReal); CString str; if( poLayer->CreateField( &oField ) != OGRERR_NONE ) { str.Format("Creating field %s failed", oField.GetNameRef()); m_MessageList.AddString (str); return; } } if(HeaderVector[i].size()>=11) { LongFieldVector.push_back (HeaderVector[i].c_str ()); } } message_str.Format ("%d fields have been created.",HeaderVector.size()); m_MessageList.AddString (message_str); if(LongFieldVector.size() >=1) { message_str.Format("Warning: Arc GIS file only supports field names with not more than 10 characters.\nThe following fields have long field names. "); m_MessageList.AddString (message_str); for(unsigned l = 0; l< LongFieldVector.size(); l++) { message_str.Format ("%s",LongFieldVector[l]); m_MessageList.AddString (message_str); } } int count = 0 ; while(parser.ReadRecord()) { //create feature OGRFeature *poFeature; poFeature = OGRFeature::CreateFeature( poLayer->GetLayerDefn() ); //step 1: write all fields except geometry for(unsigned int i = 0; i < HeaderVector.size(); i++) { if(HeaderVector[i]!="geometry") { if(HeaderVector[i].find ("name") != string::npos || HeaderVector[i].find ("code") != string::npos) { std::string str_value; parser.GetValueByFieldName(HeaderVector[i],str_value); // TRACE("field: %s, value = %s\n",HeaderVector[i].c_str (),str_value.c_str ()); poFeature->SetField(i,str_value.c_str ()); }else { double value = 0; parser.GetValueByFieldName(HeaderVector[i],value); // TRACE("field: %s, value = %f\n",HeaderVector[i].c_str (),value); CString field_name = HeaderVector[i].c_str (); poFeature->SetField(i,value); } } } string geo_string; std::vector<CCoordinate> CoordinateVector; if(parser.GetValueByFieldName("geometry",geo_string)) { // overwrite when the field "geometry" exists CGeometry geometry(geo_string); CoordinateVector = geometry.GetCoordinateList(); if( m_GIS_data_type == GIS_Point_Type && CoordinateVector.size ()==1) { OGRPoint pt; pt.setX( CoordinateVector[0].X ); pt.setY( CoordinateVector[0].Y); poFeature->SetGeometry( &pt ); } if( m_GIS_data_type == GIS_Line_Type) { OGRLineString line; for(unsigned int si = 0; si< CoordinateVector.size(); si++) { line.addPoint (CoordinateVector[si].X , CoordinateVector[si].Y); } poFeature->SetGeometry( &line ); } if( m_GIS_data_type == GIS_Polygon_Type) { OGRPolygon polygon; OGRLinearRing ring; for(unsigned int si = 0; si< CoordinateVector.size(); si++) { ring.addPoint (CoordinateVector[si].X , CoordinateVector[si].Y,1); } polygon.addRing(&ring); poFeature->SetGeometry( &polygon ); } } else { // no geometry field /// create geometry data from m_GIS_data_type == GIS_Point_Type if( m_GIS_data_type == GIS_Point_Type ) { double x, y; if(parser.GetValueByFieldName("x",x) && parser.GetValueByFieldName("y",y) ) { OGRPoint pt; pt.setX( CoordinateVector[0].X ); pt.setY( CoordinateVector[0].Y); poFeature->SetGeometry( &pt ); }else { AfxMessageBox("Pleaes prepare fields x and y in the csv file in order to create a node GIS layer.", MB_ICONINFORMATION); return; } } ///create geometry if( m_GIS_data_type == GIS_Line_Type) { int number_of_shape_points = 0; if(parser.GetValueByFieldName("number_of_shape_points", number_of_shape_points)) { if(number_of_shape_points>=2) { OGRLineString line; for(int s= 1; s<= number_of_shape_points; s++) { CString str_x, str_y; str_x.Format ("x%d",s); str_y.Format ("y%d",s); double x = 0; double y = 0; string string_x, string_y; string_x = m_pDoc->CString2StdString (str_x); string_y = m_pDoc->CString2StdString (str_y); if(parser.GetValueByFieldName(string_x, x) && parser.GetValueByFieldName(string_y, y)) { line.addPoint(x,y); }else { AfxMessageBox("Pleaes prepare fields x1,y1,x2,y2,...,xn,yn in the csv file in order to create a link GIS layer.", MB_ICONINFORMATION); return; } } poFeature->SetGeometry( &line ); } }else { AfxMessageBox("Pleaes prepare fields number_of_shape_points, x1,y1,x2,y2,...,xn,yn in the csv file in order to create a link GIS layer.", MB_ICONINFORMATION); return; } } // if( m_GIS_data_type == GIS_Polygon_Type) { OGRPolygon polygon; OGRLinearRing ring; int number_of_shape_points = 0; if(parser.GetValueByFieldName("number_of_shape_points", number_of_shape_points)) { if(number_of_shape_points>=2) { OGRLineString line; for(int s= 0; s< number_of_shape_points; s++) { CString str_x, str_y; str_x.Format ("x%d",str_x); str_y.Format ("y%d",str_y); double x = 0; double y = 0; string string_x, string_y; string_x = m_pDoc->CString2StdString (str_x); string_y = m_pDoc->CString2StdString (str_y); if(parser.GetValueByFieldName(string_x, x) && parser.GetValueByFieldName(string_y, y)) { ring.addPoint (x,y,1); }else { AfxMessageBox("Pleaes prepare fields x1,y1,x2,y2,...,xn,yn in the csv file in order to create a zone GIS layer.", MB_ICONINFORMATION); return; } } polygon.addRing(&ring); poFeature->SetGeometry( &polygon ); } } } } if( poLayer->CreateFeature( poFeature ) != OGRERR_NONE ) { AfxMessageBox("Failed to create line feature in shapefile.\n"); return; } OGRFeature::DestroyFeature( poFeature ); count++; } message_str.Format ("%d records have been created.",count); m_MessageList.AddString (message_str); OGRDataSource::DestroyDataSource( poDS ); CString ShapeFile = lpszShapeFileName; CString ShapeFileFolder = ShapeFile.Left(ShapeFile.ReverseFind('\\') + 1); ShellExecute( NULL, "explore", ShapeFileFolder, NULL, NULL, SW_SHOWNORMAL ); } #endif }