featureset_ptr ogr_datasource::features_at_point(coord2d const& pt) const { if (!is_bound_) bind(); if (dataset_ && layer_.is_valid()) { OGRLayer* layer = layer_.layer(); if (indexed_) { filter_at_point filter(pt); return featureset_ptr(new ogr_index_featureset<filter_at_point> (*dataset_, *layer, filter, index_name_, desc_.get_encoding(), multiple_geometries_)); } else { OGRPoint point; point.setX (pt.x); point.setY (pt.y); return featureset_ptr(new ogr_featureset (*dataset_, *layer, point, desc_.get_encoding(), multiple_geometries_)); } } return featureset_ptr(); }
OGRPoint *getARCCenter(OGRPoint *ptStart, OGRPoint *ptArc, OGRPoint *ptEnd) { // FIXME precision double bx = ptStart->getX(); double by = ptStart->getY(); double cx = ptArc->getX(); double cy = ptArc->getY(); double dx = ptEnd->getX(); double dy = ptEnd->getY(); double temp, bc, cd, det, x, y; temp = cx*cx+cy*cy; bc = (bx*bx + by*by - temp)/2.0; cd = (temp - dx*dx - dy*dy)/2.0; det = (bx-cx)*(cy-dy)-(cx-dx)*(by-cy); OGRPoint *center = new OGRPoint(); if (fabs(det) < 1.0e-6) { // could not determin the determinante: too small return center; } det = 1/det; x = (bc*(cy-dy)-cd*(by-cy))*det; y = ((bx-cx)*cd-(cx-dx)*bc)*det; center->setX(x); center->setY(y); return center; }
ogrfeature(const xyh point): poFeature(OGRFeature::CreateFeature( poLayer->getLayerDefn() )) { poFeature->SetField( "Height", point.value); OGRPoint pt; // destroy ?? pt.setX( point.row ); pt.setY( point.col ); poFeature->SetGeometry( &pt ); }
OGRCircularString *ILI2Reader::getArc(DOMElement *elem) { // elem -> ARC OGRCircularString *arc = new OGRCircularString(); // previous point -> start point OGRPoint *ptStart = getPoint((DOMElement *)elem->getPreviousSibling()); // COORD or ARC // end point OGRPoint *ptEnd = new OGRPoint(); // point on the arc OGRPoint *ptOnArc = new OGRPoint(); // double radius = 0; // radius DOMElement *arcElem = (DOMElement *)elem->getFirstChild(); while (arcElem != NULL) { char* pszTagName = XMLString::transcode(arcElem->getTagName()); char* pszObjValue = getObjValue(arcElem); if (cmpStr("C1", pszTagName) == 0) ptEnd->setX(CPLAtof(pszObjValue)); else if (cmpStr("C2", pszTagName) == 0) ptEnd->setY(CPLAtof(pszObjValue)); else if (cmpStr("C3", pszTagName) == 0) ptEnd->setZ(CPLAtof(pszObjValue)); else if (cmpStr("A1", pszTagName) == 0) ptOnArc->setX(CPLAtof(pszObjValue)); else if (cmpStr("A2", pszTagName) == 0) ptOnArc->setY(CPLAtof(pszObjValue)); else if (cmpStr("A3", pszTagName) == 0) ptOnArc->setZ(CPLAtof(pszObjValue)); else if (cmpStr("R", pszTagName) == 0) { // radius = CPLAtof(pszObjValue); } CPLFree(pszObjValue); XMLString::release(&pszTagName); arcElem = (DOMElement *)arcElem->getNextSibling(); } arc->addPoint(ptStart); arc->addPoint(ptOnArc); arc->addPoint(ptEnd); delete ptStart; delete ptOnArc; delete ptEnd; return arc; }
OGRLineString *ILI2Reader::getArc(DOMElement *elem) { // elem -> ARC OGRLineString *ls = new OGRLineString(); // previous point -> start point OGRPoint *ptStart = getPoint((DOMElement *)elem->getPreviousSibling()); // COORD or ARC // end point OGRPoint *ptEnd = new OGRPoint(); // point on the arc OGRPoint *ptOnArc = new OGRPoint(); double radius = 0; // radius DOMElement *arcElem = (DOMElement *)elem->getFirstChild(); while (arcElem != NULL) { char* pszTagName = XMLString::transcode(arcElem->getTagName()); char* pszObjValue = getObjValue(arcElem); if (cmpStr("C1", pszTagName) == 0) ptEnd->setX(atof(pszObjValue)); else if (cmpStr("C2", pszTagName) == 0) ptEnd->setY(atof(pszObjValue)); else if (cmpStr("C3", pszTagName) == 0) ptEnd->setZ(atof(pszObjValue)); else if (cmpStr("A1", pszTagName) == 0) ptOnArc->setX(atof(pszObjValue)); else if (cmpStr("A2", pszTagName) == 0) ptOnArc->setY(atof(pszObjValue)); else if (cmpStr("A3", pszTagName) == 0) ptOnArc->setZ(atof(pszObjValue)); else if (cmpStr("R", pszTagName) == 0) radius = atof(pszObjValue); CPLFree(pszObjValue); XMLString::release(&pszTagName); arcElem = (DOMElement *)arcElem->getNextSibling(); } ptEnd->flattenTo2D(); ptOnArc->flattenTo2D(); interpolateArc(ls, ptStart, ptOnArc, ptEnd, arcIncr); delete ptStart; delete ptOnArc; delete ptEnd; return ls; }
void GDALAddComponentViewContainer::run() { int counter = 0; for (int i = 0; i < elements; i++) { OGRFeature * f = this->components.createFeature(); f->SetField("persons", "that is me"); OGRPoint pt; pt.setX( i ); pt.setY( i ); f->SetGeometry(&pt); if (counter == 100000) { counter = 0; } counter++; } }
featureset_ptr ogr_datasource::features_at_point(coord2d const& pt, double tol) const { if (!is_bound_) bind(); #ifdef MAPNIK_STATS mapnik::progress_timer __stats__(std::clog, "ogr_datasource::features_at_point"); #endif if (dataset_ && layer_.is_valid()) { std::vector<attribute_descriptor> const& desc_ar = desc_.get_descriptors(); // feature context (schema) mapnik::context_ptr ctx = boost::make_shared<mapnik::context_type>(); std::vector<attribute_descriptor>::const_iterator itr = desc_ar.begin(); std::vector<attribute_descriptor>::const_iterator end = desc_ar.end(); for (; itr!=end; ++itr) ctx->push(itr->get_name()); OGRLayer* layer = layer_.layer(); if (indexed_) { filter_at_point filter(pt); return featureset_ptr(new ogr_index_featureset<filter_at_point> (ctx, *layer, filter, index_name_, desc_.get_encoding())); } else { OGRPoint point; point.setX (pt.x); point.setY (pt.y); return featureset_ptr(new ogr_featureset (ctx, *layer, point, desc_.get_encoding())); } } return featureset_ptr(); }
static int AddPoint( OGRGeometry *poGeometry, double dfX, double dfY, double dfZ, int nDimension ) { if( poGeometry->getGeometryType() == wkbPoint || poGeometry->getGeometryType() == wkbPoint25D ) { OGRPoint *poPoint = (OGRPoint *) poGeometry; if( poPoint->getX() != 0.0 || poPoint->getY() != 0.0 ) { CPLError( CE_Failure, CPLE_AppDefined, "More than one coordinate for <Point> element."); return FALSE; } poPoint->setX( dfX ); poPoint->setY( dfY ); if( nDimension == 3 ) poPoint->setZ( dfZ ); return TRUE; } else if( poGeometry->getGeometryType() == wkbLineString || poGeometry->getGeometryType() == wkbLineString25D ) { if( nDimension == 3 ) ((OGRLineString *) poGeometry)->addPoint( dfX, dfY, dfZ ); else ((OGRLineString *) poGeometry)->addPoint( dfX, dfY ); return TRUE; } else { CPLAssert( FALSE ); return FALSE; } }
OGRPoint *getPoint(DOMElement *elem) { // elem -> COORD (or ARC) OGRPoint *pt = new OGRPoint(); DOMElement *coordElem = (DOMElement *)elem->getFirstChild(); while (coordElem != NULL) { char* pszTagName = XMLString::transcode(coordElem->getTagName()); char* pszObjValue = getObjValue(coordElem); if (cmpStr("C1", pszTagName) == 0) pt->setX(atof(pszObjValue)); else if (cmpStr("C2", pszTagName) == 0) pt->setY(atof(pszObjValue)); else if (cmpStr("C3", pszTagName) == 0) pt->setZ(atof(pszObjValue)); CPLFree(pszObjValue); XMLString::release(&pszTagName); coordElem = (DOMElement *)coordElem->getNextSibling(); } pt->flattenTo2D(); return pt; }
void report_raster_data_within_polygon(Raster* raster, OGRPolygon* poPolygon, int feature_num, string feature_name) { if (raster->rasterBBox->Intersects( poPolygon ) ) { OGRPolygon *poIntersection = (OGRPolygon*) raster->rasterBBox->Intersection( poPolygon ); OGREnvelope* envl = new OGREnvelope; poIntersection->getEnvelope(envl); //printf ("Bounding rect (minX, maxX; minY, maxY): %.3f, %.3f; %.3f, %.3f\n", envl->MinX, envl->MaxX, envl->MinY, envl->MaxY); const double pw = raster->pixel_width; const double ph = raster->pixel_height; int pixelOffset_X = round((envl->MinX - raster->upper_left_x) / pw); int pixelOffset_Y = round((raster->upper_left_y - envl->MaxY) / ph); int nCellsX = round((envl->MaxX - raster->upper_left_x) / pw) - pixelOffset_X; int nCellsY = round((raster->upper_left_y - envl->MinY) / ph) - pixelOffset_Y; OGRPoint* pixelPoint = new OGRPoint(0,0); float* pPixelValue = (float *) CPLMalloc(sizeof(float)); cerr << "Feature size: " << nCellsX << "x" << nCellsY << endl; for ( int row = 0; row < nCellsY; ++row ) { for ( int col = 0; col < nCellsX; ++col ) { double xcenter = (col + pixelOffset_X + 0.5)*pw + raster->upper_left_x; double ycenter = raster->upper_left_y - (row + pixelOffset_Y + 0.5)*ph; pixelPoint->setX(xcenter); pixelPoint->setY(ycenter); if ( pixelPoint->Intersects(poPolygon)) { raster->band->RasterIO( GF_Read, pixelOffset_X + col, pixelOffset_Y + row, 1,1, pPixelValue, 1,1, GDT_Float32, 0, 0 ); cout << setprecision(10) << xcenter << "," << setprecision(10) << ycenter << "," << *pPixelValue << "," << feature_num << "," << feature_name << endl; } } } delete envl; CPLFree(pPixelValue); } else { cerr << "Feature does not intersect raster" << endl; } return; }
void GDALAddComponent::run() { DM::GDALSystem * sys = this->getGDALData("city"); sys->updateView(components); this->components.setCurrentGDALSystem(sys); int counter = 0; for (int i = 0; i < elements; i++) { OGRFeature * f = this->components.createFeature(); if (addAttributes) { std::vector<double> double_vector; f->SetField("double_attribute", 10.5); double_vector.push_back(10.5); double_vector.push_back(20.5); double_vector.push_back(30.5); DM::DMFeature::SetDoubleList( f, "double_vector_attribute", double_vector); } //f->SetField("persons", "that is me"); OGRPoint pt; pt.setX( i ); pt.setY( i ); f->SetGeometry(&pt); if (counter == 100000) { components.syncAlteredFeatures(); counter = 0; } counter++; } this->components.syncAlteredFeatures(); }
OGRFeature *OGRCADLayer::GetFeature( GIntBig nFID ) { if( poCADLayer.getGeometryCount() <= static_cast<size_t>(nFID) || nFID < 0 ) { return nullptr; } OGRFeature *poFeature = nullptr; CADGeometry *poCADGeometry = poCADLayer.getGeometry( static_cast<size_t>(nFID) ); if( nullptr == poCADGeometry || GetLastErrorCode() != CADErrorCodes::SUCCESS ) { CPLError( CE_Failure, CPLE_NotSupported, "Failed to get geometry with ID = " CPL_FRMT_GIB " from layer \"%s\". Libopencad errorcode: %d", nFID, poCADLayer.getName().c_str(), GetLastErrorCode() ); return nullptr; } poFeature = new OGRFeature( poFeatureDefn ); poFeature->SetFID( nFID ); poFeature->SetField( FIELD_NAME_THICKNESS, poCADGeometry->getThickness() ); if( !poCADGeometry->getEED().empty() ) { std::vector<std::string> asGeometryEED = poCADGeometry->getEED(); std::string sEEDAsOneString = ""; for ( std::vector<std::string>::const_iterator iter = asGeometryEED.cbegin(); iter != asGeometryEED.cend(); ++iter ) { sEEDAsOneString += *iter; sEEDAsOneString += ' '; } poFeature->SetField( FIELD_NAME_EXT_DATA, sEEDAsOneString.c_str() ); } RGBColor stRGB = poCADGeometry->getColor(); CPLString sHexColor; sHexColor.Printf("#%02X%02X%02X%02X", stRGB.R, stRGB.G, stRGB.B, 255); poFeature->SetField( FIELD_NAME_COLOR, sHexColor ); CPLString sStyle; sStyle.Printf("PEN(c:%s,w:5px)", sHexColor.c_str()); poFeature->SetStyleString( sStyle ); std::vector< CADAttrib > oBlockAttrs = poCADGeometry->getBlockAttributes(); for( const CADAttrib& oAttrib : oBlockAttrs ) { CPLString osTag = oAttrib.getTag(); auto featureAttrIt = asFeaturesAttributes.find( osTag ); if( featureAttrIt != asFeaturesAttributes.end()) { poFeature->SetField(*featureAttrIt, oAttrib.getTextValue().c_str()); } } switch( poCADGeometry->getType() ) { case CADGeometry::POINT: { CADPoint3D * const poCADPoint = ( CADPoint3D* ) poCADGeometry; CADVector stPositionVector = poCADPoint->getPosition(); poFeature->SetGeometryDirectly( new OGRPoint( stPositionVector.getX(), stPositionVector.getY(), stPositionVector.getZ() ) ); poFeature->SetField( FIELD_NAME_GEOMTYPE, "CADPoint" ); break; } case CADGeometry::LINE: { CADLine * const poCADLine = ( CADLine* ) poCADGeometry; OGRLineString *poLS = new OGRLineString(); poLS->addPoint( poCADLine->getStart().getPosition().getX(), poCADLine->getStart().getPosition().getY(), poCADLine->getStart().getPosition().getZ() ); poLS->addPoint( poCADLine->getEnd().getPosition().getX(), poCADLine->getEnd().getPosition().getY(), poCADLine->getEnd().getPosition().getZ() ); poFeature->SetGeometryDirectly( poLS ); poFeature->SetField( FIELD_NAME_GEOMTYPE, "CADLine" ); break; } case CADGeometry::SOLID: { CADSolid * const poCADSolid = ( CADSolid* ) poCADGeometry; OGRPolygon * poPoly = new OGRPolygon(); OGRLinearRing * poLR = new OGRLinearRing(); std::vector<CADVector> astSolidCorners = poCADSolid->getCorners(); for( size_t i = 0; i < astSolidCorners.size(); ++i ) { poLR->addPoint( astSolidCorners[i].getX(), astSolidCorners[i].getY(), astSolidCorners[i].getZ()); } poPoly->addRingDirectly( poLR ); poPoly->closeRings(); poFeature->SetGeometryDirectly( poPoly ); poFeature->SetField( FIELD_NAME_GEOMTYPE, "CADSolid" ); break; } case CADGeometry::CIRCLE: { CADCircle * poCADCircle = static_cast<CADCircle*>(poCADGeometry); OGRCircularString * poCircle = new OGRCircularString(); CADVector stCircleCenter = poCADCircle->getPosition(); OGRPoint oCirclePoint1; oCirclePoint1.setX( stCircleCenter.getX() - poCADCircle->getRadius() ); oCirclePoint1.setY( stCircleCenter.getY() ); oCirclePoint1.setZ( stCircleCenter.getZ() ); poCircle->addPoint( &oCirclePoint1 ); OGRPoint oCirclePoint2; oCirclePoint2.setX( stCircleCenter.getX() ); oCirclePoint2.setY( stCircleCenter.getY() + poCADCircle->getRadius() ); oCirclePoint2.setZ( stCircleCenter.getZ() ); poCircle->addPoint( &oCirclePoint2 ); OGRPoint oCirclePoint3; oCirclePoint3.setX( stCircleCenter.getX() + poCADCircle->getRadius() ); oCirclePoint3.setY( stCircleCenter.getY() ); oCirclePoint3.setZ( stCircleCenter.getZ() ); poCircle->addPoint( &oCirclePoint3 ); OGRPoint oCirclePoint4; oCirclePoint4.setX( stCircleCenter.getX() ); oCirclePoint4.setY( stCircleCenter.getY() - poCADCircle->getRadius() ); oCirclePoint4.setZ( stCircleCenter.getZ() ); poCircle->addPoint( &oCirclePoint4 ); // Close the circle poCircle->addPoint( &oCirclePoint1 ); /*NOTE: The alternative way: OGRGeometry *poCircle = OGRGeometryFactory::approximateArcAngles( poCADCircle->getPosition().getX(), poCADCircle->getPosition().getY(), poCADCircle->getPosition().getZ(), poCADCircle->getRadius(), poCADCircle->getRadius(), 0.0, 0.0, 360.0, 0.0 ); */ poFeature->SetGeometryDirectly( poCircle ); poFeature->SetField( FIELD_NAME_GEOMTYPE, "CADCircle" ); break; } case CADGeometry::ARC: { CADArc * poCADArc = static_cast<CADArc*>(poCADGeometry); OGRCircularString * poCircle = new OGRCircularString(); // Need at least 3 points in arc double dfStartAngle = poCADArc->getStartingAngle() * DEG2RAD; double dfEndAngle = poCADArc->getEndingAngle() * DEG2RAD; double dfMidAngle = (dfEndAngle + dfStartAngle) / 2; CADVector stCircleCenter = poCADArc->getPosition(); OGRPoint oCirclePoint; oCirclePoint.setX( stCircleCenter.getX() + poCADArc->getRadius() * cos( dfStartAngle ) ); oCirclePoint.setY( stCircleCenter.getY() + poCADArc->getRadius() * sin( dfStartAngle ) ); oCirclePoint.setZ( stCircleCenter.getZ() ); poCircle->addPoint( &oCirclePoint ); oCirclePoint.setX( stCircleCenter.getX() + poCADArc->getRadius() * cos( dfMidAngle ) ); oCirclePoint.setY( stCircleCenter.getY() + poCADArc->getRadius() * sin( dfMidAngle ) ); oCirclePoint.setZ( stCircleCenter.getZ() ); poCircle->addPoint( &oCirclePoint ); oCirclePoint.setX( stCircleCenter.getX() + poCADArc->getRadius() * cos( dfEndAngle ) ); oCirclePoint.setY( stCircleCenter.getY() + poCADArc->getRadius() * sin( dfEndAngle ) ); oCirclePoint.setZ( stCircleCenter.getZ() ); poCircle->addPoint( &oCirclePoint ); /*NOTE: alternative way: OGRGeometry * poArc = OGRGeometryFactory::approximateArcAngles( poCADArc->getPosition().getX(), poCADArc->getPosition().getY(), poCADArc->getPosition().getZ(), poCADArc->getRadius(), poCADArc->getRadius(), 0.0, dfStartAngle, dfStartAngle > dfEndAngle ? ( dfEndAngle + 360.0f ) : dfEndAngle, 0.0 ); */ poFeature->SetGeometryDirectly( poCircle ); poFeature->SetField( FIELD_NAME_GEOMTYPE, "CADArc" ); break; } case CADGeometry::FACE3D: { CADFace3D * const poCADFace = ( CADFace3D* ) poCADGeometry; OGRPolygon * poPoly = new OGRPolygon(); OGRLinearRing * poLR = new OGRLinearRing(); for ( size_t i = 0; i < 3; ++i ) { poLR->addPoint( poCADFace->getCorner( i ).getX(), poCADFace->getCorner( i ).getY(), poCADFace->getCorner( i ).getZ() ); } if ( !(poCADFace->getCorner( 2 ) == poCADFace->getCorner( 3 )) ) { poLR->addPoint( poCADFace->getCorner( 3 ).getX(), poCADFace->getCorner( 3 ).getY(), poCADFace->getCorner( 3 ).getZ() ); } poPoly->addRingDirectly( poLR ); poPoly->closeRings(); poFeature->SetGeometryDirectly( poPoly ); poFeature->SetField( FIELD_NAME_GEOMTYPE, "CADFace3D" ); break; } case CADGeometry::LWPOLYLINE: { CADLWPolyline * const poCADLWPolyline = ( CADLWPolyline* ) poCADGeometry; poFeature->SetField( FIELD_NAME_GEOMTYPE, "CADLWPolyline" ); /* * Excessive check, like in DXF driver. * I tried to make a single-point polyline, but couldn't make it. * Probably this check should be removed. */ if( poCADLWPolyline->getVertexCount() == 1 ) { poFeature->SetGeometryDirectly( new OGRPoint( poCADLWPolyline->getVertex(0).getX(), poCADLWPolyline->getVertex(0).getY(), poCADLWPolyline->getVertex(0).getZ() ) ); break; } /* * If polyline has no arcs, handle it in easy way. */ OGRLineString * poLS = new OGRLineString(); if( poCADLWPolyline->getBulges().empty() ) { for( size_t i = 0; i < poCADLWPolyline->getVertexCount(); ++i ) { CADVector stVertex = poCADLWPolyline->getVertex( i ); poLS->addPoint( stVertex.getX(), stVertex.getY(), stVertex.getZ() ); } poFeature->SetGeometryDirectly( poLS ); break; } /* * Last case - if polyline has mixed arcs and lines. */ bool bLineStringStarted = false; std::vector< double > adfBulges = poCADLWPolyline->getBulges(); const size_t nCount = std::min(adfBulges.size(), poCADLWPolyline->getVertexCount()); for( size_t iCurrentVertex = 0; iCurrentVertex + 1 < nCount; iCurrentVertex++ ) { CADVector stCurrentVertex = poCADLWPolyline->getVertex( iCurrentVertex ); CADVector stNextVertex = poCADLWPolyline->getVertex( iCurrentVertex + 1 ); double dfLength = sqrt( pow( stNextVertex.getX() - stCurrentVertex.getX(), 2 ) + pow( stNextVertex.getY() - stCurrentVertex.getY(), 2 ) ); /* * Handling straight polyline segment. */ if( ( dfLength == 0 ) || ( adfBulges[iCurrentVertex] == 0 ) ) { if( !bLineStringStarted ) { poLS->addPoint( stCurrentVertex.getX(), stCurrentVertex.getY(), stCurrentVertex.getZ() ); bLineStringStarted = true; } poLS->addPoint( stNextVertex.getX(), stNextVertex.getY(), stNextVertex.getZ() ); } else { double dfSegmentBulge = adfBulges[iCurrentVertex]; double dfH = ( dfSegmentBulge * dfLength ) / 2; if( dfH == 0.0 ) dfH = 1.0; // just to avoid a division by zero double dfRadius = ( dfH / 2 ) + ( dfLength * dfLength / ( 8 * dfH ) ); double dfOgrArcRotation = 0, dfOgrArcRadius = fabs( dfRadius ); /* * Set arc's direction and keep bulge positive. */ bool bClockwise = ( dfSegmentBulge < 0 ); if( bClockwise ) dfSegmentBulge *= -1; /* * Get arc's center point. */ double dfSaggita = fabs( dfSegmentBulge * ( dfLength / 2.0 ) ); double dfApo = bClockwise ? -( dfOgrArcRadius - dfSaggita ) : -( dfSaggita - dfOgrArcRadius ); CADVector stVertex; stVertex.setX( stCurrentVertex.getX() - stNextVertex.getX() ); stVertex.setY( stCurrentVertex.getY() - stNextVertex.getY() ); stVertex.setZ( stCurrentVertex.getZ() ); CADVector stMidPoint; stMidPoint.setX( stNextVertex.getX() + 0.5 * stVertex.getX() ); stMidPoint.setY( stNextVertex.getY() + 0.5 * stVertex.getY() ); stMidPoint.setZ( stVertex.getZ() ); CADVector stPperp; stPperp.setX( stVertex.getY() ); stPperp.setY( -stVertex.getX() ); double dfStPperpLength = sqrt( stPperp.getX() * stPperp.getX() + stPperp.getY() * stPperp.getY() ); // TODO: Check that length isnot 0 stPperp.setX( stPperp.getX() / dfStPperpLength ); stPperp.setY( stPperp.getY() / dfStPperpLength ); CADVector stOgrArcCenter; stOgrArcCenter.setX( stMidPoint.getX() + ( stPperp.getX() * dfApo ) ); stOgrArcCenter.setY( stMidPoint.getY() + ( stPperp.getY() * dfApo ) ); /* * Get the line's general vertical direction ( -1 = down, +1 = up ). */ double dfLineDir = stNextVertex.getY() > stCurrentVertex.getY() ? 1.0f : -1.0f; /* * Get arc's starting angle. */ double dfA = atan2( ( stOgrArcCenter.getY() - stCurrentVertex.getY() ), ( stOgrArcCenter.getX() - stCurrentVertex.getX() ) ) * DEG2RAD; if( bClockwise && ( dfLineDir == 1.0 ) ) dfA += ( dfLineDir * 180.0 ); double dfOgrArcStartAngle = dfA > 0.0 ? -( dfA - 180.0 ) : -( dfA + 180.0 ); /* * Get arc's ending angle. */ dfA = atan2( ( stOgrArcCenter.getY() - stNextVertex.getY() ), ( stOgrArcCenter.getX() - stNextVertex.getX() ) ) * DEG2RAD; if( bClockwise && ( dfLineDir == 1.0 ) ) dfA += ( dfLineDir * 180.0 ); double dfOgrArcEndAngle = dfA > 0.0 ? -( dfA - 180.0 ) : -( dfA + 180.0 ); if( !bClockwise && ( dfOgrArcStartAngle < dfOgrArcEndAngle) ) dfOgrArcEndAngle = -180.0 + ( dfLineDir * dfA ); if( bClockwise && ( dfOgrArcStartAngle > dfOgrArcEndAngle ) ) dfOgrArcEndAngle += 360.0; /* * Flip arc's rotation if necessary. */ if( bClockwise && ( dfLineDir == 1.0 ) ) dfOgrArcRotation = dfLineDir * 180.0; /* * Tessellate the arc segment and append to the linestring. */ OGRLineString * poArcpoLS = ( OGRLineString * ) OGRGeometryFactory::approximateArcAngles( stOgrArcCenter.getX(), stOgrArcCenter.getY(), stOgrArcCenter.getZ(), dfOgrArcRadius, dfOgrArcRadius, dfOgrArcRotation, dfOgrArcStartAngle,dfOgrArcEndAngle, 0.0 ); poLS->addSubLineString( poArcpoLS ); delete( poArcpoLS ); } } if( poCADLWPolyline->isClosed() ) { poLS->addPoint( poCADLWPolyline->getVertex(0).getX(), poCADLWPolyline->getVertex(0).getY(), poCADLWPolyline->getVertex(0).getZ() ); } poFeature->SetGeometryDirectly( poLS ); poFeature->SetField( FIELD_NAME_GEOMTYPE, "CADLWPolyline" ); break; } // TODO: Unsupported smooth lines case CADGeometry::POLYLINE3D: { CADPolyline3D * const poCADPolyline3D = ( CADPolyline3D* ) poCADGeometry; OGRLineString * poLS = new OGRLineString(); for( size_t i = 0; i < poCADPolyline3D->getVertexCount(); ++i ) { CADVector stVertex = poCADPolyline3D->getVertex( i ); poLS->addPoint( stVertex.getX(), stVertex.getY(), stVertex.getZ() ); } poFeature->SetGeometryDirectly( poLS ); poFeature->SetField( FIELD_NAME_GEOMTYPE, "CADPolyline3D" ); break; } case CADGeometry::TEXT: { CADText * const poCADText = ( CADText * ) poCADGeometry; OGRPoint * poPoint = new OGRPoint( poCADText->getPosition().getX(), poCADText->getPosition().getY(), poCADText->getPosition().getZ() ); CPLString sTextValue = CADRecode( poCADText->getTextValue(), nDWGEncoding ); poFeature->SetField( FIELD_NAME_TEXT, sTextValue ); poFeature->SetGeometryDirectly( poPoint ); poFeature->SetField( FIELD_NAME_GEOMTYPE, "CADText" ); sStyle.Printf("LABEL(f:\"Arial\",t:\"%s\",c:%s)", sTextValue.c_str(), sHexColor.c_str()); poFeature->SetStyleString( sStyle ); break; } case CADGeometry::MTEXT: { CADMText * const poCADMText = ( CADMText * ) poCADGeometry; OGRPoint * poPoint = new OGRPoint( poCADMText->getPosition().getX(), poCADMText->getPosition().getY(), poCADMText->getPosition().getZ() ); CPLString sTextValue = CADRecode( poCADMText->getTextValue(), nDWGEncoding ); poFeature->SetField( FIELD_NAME_TEXT, sTextValue ); poFeature->SetGeometryDirectly( poPoint ); poFeature->SetField( FIELD_NAME_GEOMTYPE, "CADMText" ); sStyle.Printf("LABEL(f:\"Arial\",t:\"%s\",c:%s)", sTextValue.c_str(), sHexColor.c_str()); poFeature->SetStyleString( sStyle ); break; } case CADGeometry::SPLINE: { CADSpline * const poCADSpline = ( CADSpline * ) poCADGeometry; OGRLineString * poLS = new OGRLineString(); // TODO: Interpolate spline as points or curves for( size_t i = 0; i < poCADSpline->getControlPoints().size(); ++i ) { poLS->addPoint( poCADSpline->getControlPoints()[i].getX(), poCADSpline->getControlPoints()[i].getY(), poCADSpline->getControlPoints()[i].getZ() ); } poFeature->SetGeometryDirectly( poLS ); poFeature->SetField( FIELD_NAME_GEOMTYPE, "CADSpline" ); break; } case CADGeometry::ELLIPSE: { CADEllipse * poCADEllipse = static_cast<CADEllipse*>(poCADGeometry); // FIXME: Start/end angles should be swapped to work exactly as DXF driver. // is it correct? double dfStartAngle = -1 * poCADEllipse->getEndingAngle() * DEG2RAD; double dfEndAngle = -1 * poCADEllipse->getStartingAngle() * DEG2RAD; double dfAxisRatio = poCADEllipse->getAxisRatio(); dfStartAngle = fmod(dfStartAngle, 360.0); dfEndAngle = fmod(dfEndAngle, 360.0); if( dfStartAngle > dfEndAngle ) dfEndAngle += 360.0; CADVector vectPosition = poCADEllipse->getPosition(); CADVector vectSMAxis = poCADEllipse->getSMAxis(); double dfPrimaryRadius, dfSecondaryRadius; double dfRotation; dfPrimaryRadius = sqrt( vectSMAxis.getX() * vectSMAxis.getX() + vectSMAxis.getY() * vectSMAxis.getY() + vectSMAxis.getZ() * vectSMAxis.getZ() ); dfSecondaryRadius = dfAxisRatio * dfPrimaryRadius; dfRotation = -1 * atan2( vectSMAxis.getY(), vectSMAxis.getX() ) * DEG2RAD; OGRGeometry *poEllipse = OGRGeometryFactory::approximateArcAngles( vectPosition.getX(), vectPosition.getY(), vectPosition.getZ(), dfPrimaryRadius, dfSecondaryRadius, dfRotation, dfStartAngle, dfEndAngle, 0.0 ); poFeature->SetGeometryDirectly( poEllipse ); poFeature->SetField( FIELD_NAME_GEOMTYPE, "CADEllipse" ); break; } case CADGeometry::ATTDEF: { CADAttdef * const poCADAttdef = ( CADAttdef* ) poCADGeometry; OGRPoint * poPoint = new OGRPoint( poCADAttdef->getPosition().getX(), poCADAttdef->getPosition().getY(), poCADAttdef->getPosition().getZ() ); CPLString sTextValue = CADRecode( poCADAttdef->getTag(), nDWGEncoding ); poFeature->SetField( FIELD_NAME_TEXT, sTextValue ); poFeature->SetGeometryDirectly( poPoint ); poFeature->SetField( FIELD_NAME_GEOMTYPE, "CADAttdef" ); sStyle.Printf("LABEL(f:\"Arial\",t:\"%s\",c:%s)", sTextValue.c_str(), sHexColor.c_str()); poFeature->SetStyleString( sStyle ); break; } default: { CPLError( CE_Warning, CPLE_NotSupported, "Unhandled feature. Skipping it." ); poFeature->SetField( FIELD_NAME_GEOMTYPE, "CADUnknown" ); delete poCADGeometry; return poFeature; } } delete poCADGeometry; poFeature->GetGeometryRef()->assignSpatialReference( poSpatialRef ); return poFeature; }
void LevelTerrainCallback::loaded(osgTerrain::TerrainTile *tile, const osgDB::ReaderWriter::Options *options) const { //Change TerrainTechnique tile->setTerrainTechnique(new DecoratedGeometryTechnique(voidBoundingAreaVector, treeStateSet.get(), buildingStateSet.get(), shapeFileVector)); std::stringstream nameStream; nameStream << "tile_L" << tile->getTileID().level << "_X" << tile->getTileID().x << "_Y" << tile->getTileID().y; tile->setName(nameStream.str()); /*tile->setName("TerrainTile"); osg::Vec3d model; tile->getLocator()->convertLocalToModel(osg::Vec3d(0.0,0.0,0.0), model); char name[1000]; sprintf(name,"X%f_Y%f_Z%f", model.x(), model.y(), model.z()); tile->setName(name);*/ //MTRand mt(10101); osgTerrain::HeightFieldLayer *hflayer = dynamic_cast<osgTerrain::HeightFieldLayer *>(tile->getElevationLayer()); osg::HeightField *field = NULL; if (hflayer) { field = hflayer->getHeightField(); } else { return; } double tileXInterval = field->getXInterval(); double tileYInterval = field->getYInterval(); double tileElementArea = tileXInterval * tileYInterval; double tileXMin = offset.x() + field->getOrigin().x(); double tileXMax = tileXMin + tileXInterval * (double)field->getNumColumns(); double tileYMin = offset.y() + field->getOrigin().y(); double tileYMax = tileYMin + tileYInterval * (double)field->getNumRows(); //osg::BoundingBox tileBB(tileXMin, tileYMin, -10.000, tileXMax, tileYMax, 10.000); if (tileXInterval > 10.0 && tileYInterval > 10.0) { return; } for (int i = 0; i < RoadSystem::Instance()->getNumRoads(); ++i) { Road *road = RoadSystem::Instance()->getRoad(i); double roadLength = road->getLength(); const osg::BoundingBox &roadBB = road->getRoadGeode()->getBoundingBox(); //if(roadBB.intersects(tileBB)) { if (((roadBB.xMax() >= tileXMin && roadBB.xMax() <= tileXMax) || (roadBB.xMin() >= tileXMin && roadBB.xMin() <= tileXMax) || (roadBB.xMin() <= tileXMin && roadBB.xMax() >= tileXMax)) && (roadBB.yMax() >= tileYMin && roadBB.yMin() <= tileYMax)) { //double h = sqrt(tileXInterval*tileXInterval + tileYInterval*tileYInterval); double h = 20.0; std::deque<RoadPoint> pointDeque(4); double widthRight, widthLeft; road->getRoadSideWidths(0.0, widthRight, widthLeft); pointDeque.pop_front(); pointDeque.pop_front(); pointDeque.push_back(road->getRoadPoint(0.0, widthLeft + 10.0)); pointDeque.push_back(road->getRoadPoint(0.0, widthRight - 10.0)); std::map<std::pair<int, int>, double> coordHeightMap; for (double s_ = h; s_ < roadLength + h; s_ = s_ + h) { double s = s_; if (s > roadLength) s = roadLength; road->getRoadSideWidths(s, widthRight, widthLeft); pointDeque.pop_front(); pointDeque.pop_front(); pointDeque.push_back(road->getRoadPoint(s, widthLeft + 10.0)); pointDeque.push_back(road->getRoadPoint(s, widthRight - 10.0)); //Bresenham // y x z std::map<int, std::map<int, double> > fillBorderMap; //iteration over four lines for (int i = 0; i < 4; ++i) { int j; switch (i) { case 0: j = 1; break; case 1: j = 3; break; case 2: j = 0; break; case 3: j = 2; break; } double fx0 = (pointDeque[i].x() - tileXMin) / tileXInterval; double fy0 = (pointDeque[i].y() - tileYMin) / tileYInterval; double fx1 = (pointDeque[j].x() - tileXMin) / tileXInterval; double fy1 = (pointDeque[j].y() - tileYMin) / tileYInterval; double dir_x = (fx0 - fx1) < 0.0 ? -1.0 : 1.0; double dir_y = (fy0 - fy1) < 0.0 ? -1.0 : 1.0; int x0 = (int)floor(fx0 + dir_x + 0.5); //if(x0<0) x0=0; else if(x0>=field->getNumColumns()) x0=field->getNumColumns()-1; int y0 = (int)floor(fy0 + dir_y + 0.5); //if(y0<0) y0=0; else if(y0>=field->getNumRows()) y0=field->getNumRows()-1; int x1 = (int)floor(fx1 - dir_x + 0.5); //if(x1<0) x1=0; else if(x1>=field->getNumColumns()) x1=field->getNumColumns()-1; int y1 = (int)floor(fy1 - dir_y + 0.5); //if(y1<0) y1=0; else if(y1>=field->getNumRows()) y1=field->getNumRows()-1; double z = 0.5 * (pointDeque[i].z() + pointDeque[j].z()); //wikipedia implementation int dx = abs(x1 - x0); int sx = x0 < x1 ? 1 : -1; int dy = -abs(y1 - y0); int sy = y0 < y1 ? 1 : -1; int err = dx + dy; int e2; /* error value e_xy */ do { /* loop */ //setPixel(x0,y0); fillBorderMap[y0][x0] = z; //fillBorderMap[y0][x0] = 0.5; //if (x0==x1 && y0==y1) break; e2 = 2 * err; if (e2 >= dy) { err += dy; x0 += sx; } /* e_xy+e_x > 0 */ if (e2 <= dx) { err += dx; y0 += sy; } /* e_xy+e_y < 0 */ } while (!(x0 == x1 && y0 == y1)); } for (std::map<int, std::map<int, double> >::iterator yScanlineIt = fillBorderMap.begin(); yScanlineIt != fillBorderMap.end(); ++yScanlineIt) { int x0 = (yScanlineIt->second.begin())->first; double z0 = (yScanlineIt->second.begin())->second; int x1 = (--(yScanlineIt->second.end()))->first; double z1 = (--(yScanlineIt->second.end()))->second; unsigned int y = yScanlineIt->first; //if(y==field->getNumRows()-1) continue; for (int x = x0; x <= x1; ++x) { if (x >= 0 && x < (int)field->getNumColumns() && y >= 0 && y < field->getNumRows()) { //field->setHeight(x,y,0.5*(z0+z1)-0.5); //double z = field->getHeight(x,y); double rl_x = 0.5 * (pointDeque[0].x() + pointDeque[1].x()); double rl_y = 0.5 * (pointDeque[0].y() + pointDeque[1].y()); double ru_x = 0.5 * (pointDeque[2].x() + pointDeque[3].x()); double ru_y = 0.5 * (pointDeque[2].y() + pointDeque[3].y()); double t_x = ru_x - rl_x; double t_y = ru_y - rl_y; double mag_t = sqrt(t_x * t_x + t_y * t_y); if (mag_t != mag_t) continue; t_x /= mag_t; t_y /= mag_t; double rp_x = tileXInterval * ((double)(x)) + tileXMin - rl_x; double rp_y = tileYInterval * ((double)(y)) + tileYMin - rl_y; double d_x = -t_y * t_x * rp_y + t_y * t_y * rp_x; double d_y = t_x * t_x * rp_y - t_x * t_y * rp_x; double d = sqrt(d_x * d_x + d_y * d_y); //double mag_d = sqrt(d_x*d_x + d_y*d_y); //double d = 0.0; //if(mag_d==mag_d) { // d = (d_x*d_x+d_y*d_y)/mag_d; //} double s_x = rp_x - d_x; double s_y = rp_y - d_y; double s = sqrt(s_x * s_x + s_y * s_y); double wl = sqrt(pow(pointDeque[0].x() - pointDeque[1].x(), 2) + pow(pointDeque[0].y() - pointDeque[1].y(), 2)); double wu = sqrt(pow(pointDeque[2].x() - pointDeque[3].x(), 2) + pow(pointDeque[2].y() - pointDeque[3].y(), 2)); double l = sqrt(pow(0.5 * (pointDeque[0].x() - pointDeque[2].x() + pointDeque[1].x() - pointDeque[3].x()), 2) + pow(0.5 * (pointDeque[0].y() - pointDeque[2].y() + pointDeque[1].y() - pointDeque[3].y()), 2)); double zt; std::map<std::pair<int, int>, double>::iterator coordHeightMapIt = coordHeightMap.find(std::make_pair(x, y)); if (coordHeightMapIt == coordHeightMap.end()) { zt = (double)field->getHeight(x, y); coordHeightMap[std::make_pair(x, y)] = zt; } else { zt = coordHeightMapIt->second; } double zf0 = 7.0; double zf = 0.5 * (z0 + z1) - zf0; double kt0 = 50.0; double kt = (d / (0.5 * (wl + (wu - wl) * s / l))) * kt0; double kf0 = 10.0; double kf = (1.0 - d / (0.5 * (wl + (wu - wl) * s / l))) * kf0; double zl = (zt * kt + zf * kf) / (kt + kf); double z_field = field->getHeight(x, y); if (z_field > zl) { field->setHeight(x, y, zl); } //std::cout << "(x,y): (" << x << "," << y << "), zt: " << zt << ", zf: " << zf << ", kt: " << kt << ", kf: " << kf << std::endl; //field->setHeight(x,y, std::min(zf, 0.5*(z0+z1) - 1.0*(1.0- d/(wl+(wu-wl)*s/l)) ) ); //std::cout << "(x,y): (" << x << "," << y << "), z0: " << z0 << ", z1: " << z1 << ", d: " << d << ", wl: " << wl << ", wu: " << wu << ", s: " << s << ", l: " << l << std::endl; } } } /*Vector3D roadCenterPoint = road->getCenterLinePoint(s); int x = floor((roadCenterPoint.x() - tileXMin)/tileXInterval + 0.5); int y = floor((roadCenterPoint.y() - tileYMin)/tileYInterval + 0.5); if(x>=0 && x<field->getNumColumns() && y>=0 && y<field->getNumRows()) { field->setHeight(x,y,0.0); }*/ } } } #if 0 //osg::Group* treeGroup = new osg::Group(); //tile->addChild(treeGroup); //treeGroup->setName("TreeGroup"); osg::PositionAttitudeTransform* treeGeodeTransform = new osg::PositionAttitudeTransform; tile->addChild(treeGeodeTransform); treeGeodeTransform->setName("TreeGeodeTransform"); osg::Vec3 tileMin(tileXMin, tileYMin, 0.0); treeGeodeTransform->setPosition(-offset + tileMin); osg::Geode* treeGeode = new osg::Geode(); //tile->addChild(treeGeode); treeGeodeTransform->addChild(treeGeode); treeGeode->setName("TreeGeode"); treeGeode->setStateSet(treeStateSet); #endif #if 0 for(int layerIt = 0; layerIt < layers.size(); ++layerIt) { OGRLayer* layer = layers[layerIt]; layer->ResetReading(); OGRFeature* poFeature = NULL; while((poFeature = layer->GetNextFeature()) != NULL) { OGRGeometry *poGeometry = poFeature->GetGeometryRef(); if(poGeometry != NULL && wkbFlatten(poGeometry->getGeometryType()) == wkbPolygon) { OGRPolygon *poPolygon = dynamic_cast<OGRPolygon*>(poGeometry); //std::cout << "Geometry name: " << poPolygon->getGeometryName() << std::endl; //std::cout << "Polgon area: " << poPolygon->get_Area() << std::endl; OGRSpatialReference *poSource = layer->GetSpatialRef(); OGRSpatialReference *poTarget = new OGRSpatialReference(); poTarget->importFromProj4("+proj=utm +zone=32"); OGRCoordinateTransformation* poCoordTrans = OGRCreateCoordinateTransformation(poSource, poTarget); poPolygon->transform(poCoordTrans); OGRLinearRing* poRing = poPolygon->getExteriorRing(); /*for(int pointIt = 0; pointIt<poRing->getNumPoints(); ++pointIt) { std::cout << "Point " << pointIt << ": (" << poRing->getX(pointIt) + offset.x() << ", " << poRing->getY(pointIt) + offset.y() << ", " << poRing->getZ(pointIt) << ")" << std::endl; }*/ /*double interval = 10.0*sqrt(tileXInterval*tileXInterval + tileYInterval*tileYInterval); OGRPoint point; poRing->Value(0, &point); OGRPoint point_next; for(double s = 0; s<poRing->get_Length(); s += interval*mt()) { double s_next = s+interval; if(s_next>poRing->get_Length()) s_next = poRing->get_Length(); poRing->Value(s_next, &point_next); double ccw = poRing->isClockwise() ? -1.0 : 1.0; double t_x = point_next.getX() - point.getX(); double t_y = point_next.getY() - point.getY(); double n_x = -t_y*ccw; double n_y = t_x*ccw; double mag_n = sqrt(n_x*n_x+n_y*n_y); if(mag_n>1e-3) { n_x /= mag_n; n_y /= mag_n; } double n_mt = mt(); double x = point.getX()+offset.x() + 0.5*t_x + 10.0*n_mt*n_x; double y = point.getY()+offset.y() + 0.5*t_y + 10.0*n_mt*n_y; //std::cout << "t_x: " << t_x << ", t_y: " << t_y << ", n_x: " << 10.0*n_mt*n_x << ", n_y: " << 10.0*n_mt*n_y << std::endl; std::cout << "x: " << x << ", y: " << y << std::endl; point = point_next; //std::cout << "Boundary trace: s: " << s << ", x: " << x << ", y:" << y << ", tile min: (" << tileXMin << ", " << tileYMin << "), max: (" << tileXMax << ", " << tileYMax << ")" << std::endl; osg::BoundingBox tileBB(tileXMin, tileYMin, -1.0, tileXMax, tileYMax, 1.0); if(tileBB.contains(osg::Vec3(x,y,0.0))) { osg::PositionAttitudeTransform* treeTrans = new osg::PositionAttitudeTransform(); treeGroup->addChild(treeTrans); //hflayer->getInterpolatedValue(x,y,z); int x_int = floor((x-tileXMin)/tileXInterval+0.5); if(x_int<0) x_int=0; else if(x_int>=field->getNumColumns()) x_int=field->getNumColumns()-1; int y_int = floor((y-tileYMin)/tileYInterval+0.5); if(y_int<0) y_int=0; else if(y_int>=field->getNumRows()) y_int=field->getNumRows()-1; double z = field->getHeight(x_int,y_int); //osg::Vec3 treePos(x,y,z); osg::Vec3 treePos(point.getX(),point.getY(),z); treeTrans->setPosition(treePos); int treeIt = (int)floor(mt()*(double)treeNodeVector.size()); treeTrans->addChild(treeNodeVector[treeIt].get()); treeTrans->setName("TreeTransform"); } }*/ OGREnvelope psEnvelope; poPolygon->getEnvelope(&psEnvelope); int nTrees = (int)((psEnvelope.MaxX-psEnvelope.MinX)*(psEnvelope.MaxY-psEnvelope.MinY)*1e-5/tileElementArea); for(int i = 0; i<nTrees; ++i) { OGRPoint point; //point.setX(mt()*(psEnvelope.MaxX-psEnvelope.MinX) + psEnvelope.MinX); //point.setY(mt()*(psEnvelope.MaxY-psEnvelope.MinY) + psEnvelope.MinY); point.setX(mt()*(tileXMax-tileXMin) + tileXMin); point.setY(mt()*(tileYMax-tileYMin) + tileYMin); //if(poPolygon->Contains(&point)) { osg::PositionAttitudeTransform* treeTrans = new osg::PositionAttitudeTransform(); treeGroup->addChild(treeTrans); //hflayer->getInterpolatedValue(x,y,z); double x = point.getX() + offset.x(); double y = point.getY() + offset.y(); int x_int = floor((x-tileXMin)/tileXInterval+0.5); if(x_int<0) x_int=0; else if(x_int>=field->getNumColumns()) x_int=field->getNumColumns()-1; int y_int = floor((y-tileYMin)/tileYInterval+0.5); if(y_int<0) y_int=0; else if(y_int>=field->getNumRows()) y_int=field->getNumRows()-1; double z = field->getHeight(x_int,y_int); std::cout << "int x: " << x_int << ", x: " << x-tileXMin << ", y: " << y_int << ", y: " << y-tileYMin << std::endl; //osg::Vec3 treePos(x,y,z); osg::Vec3 treePos(x,y,z); treeTrans->setPosition(treePos); int treeIt = (int)floor(mt()*(double)treeNodeVector.size()); treeTrans->addChild(treeNodeVector[treeIt].get()); treeTrans->setName("TreeTransform"); //} } } } } #endif #if 0 typedef gaalet::algebra< gaalet::signature<3,0> > em; typedef em::mv<1, 2, 4>::type Vector; typedef em::mv<3, 5, 6>::type Bivector; typedef em::mv<0, 3, 5, 6>::type Rotor; static const em::mv<0>::type one(1.0); static const em::mv<1>::type e1(1.0); static const em::mv<2>::type e2(1.0); static const em::mv<4>::type e3(1.0); static const em::mv<7>::type e123(1.0); osgTerrain::Layer* colorLayer = tile->getColorLayer(0); if(colorLayer) { osg::Image* inputImage = colorLayer->getImage(); /*static int tileLoadCounter = 0; osg::Image* outputImage = NULL; if(tileLoadCounter==0) { outputImage = new osg::Image(); outputImage->allocateImage(inputImage->s(), inputImage->t(), 1, 0x1907, 0x1401); } tileLoadCounter += 1;*/ em::mv<0,6>::type *fftwImag1 = (em::mv<0,6>::type*) fftw_malloc(sizeof(em::mv<0,6>::type)*inputImage->s()*inputImage->t()); em::mv<0,3>::type *fftwImag2 = (em::mv<0,3>::type*) fftw_malloc(sizeof(em::mv<0,3>::type)*inputImage->s()*inputImage->t()); em::mv<0,6>::type *fftwFreq1 = (em::mv<0,6>::type*) fftw_malloc(sizeof(em::mv<0,6>::type)*inputImage->s()*inputImage->t()); em::mv<0,3>::type *fftwFreq2 = (em::mv<0,3>::type*) fftw_malloc(sizeof(em::mv<0,3>::type)*inputImage->s()*inputImage->t()); fftw_plan fftwForward1 = fftw_plan_dft_2d(inputImage->s(), inputImage->t(), reinterpret_cast<fftw_complex*>(fftwImag1), reinterpret_cast<fftw_complex*>(fftwFreq1), FFTW_FORWARD, FFTW_ESTIMATE); fftw_plan fftwForward2 = fftw_plan_dft_2d(inputImage->s(), inputImage->t(), reinterpret_cast<fftw_complex*>(fftwImag2), reinterpret_cast<fftw_complex*>(fftwFreq2), FFTW_FORWARD, FFTW_ESTIMATE); fftw_plan fftwBackward1 = fftw_plan_dft_2d(inputImage->s(), inputImage->t(), reinterpret_cast<fftw_complex*>(fftwFreq1), reinterpret_cast<fftw_complex*>(fftwImag1), FFTW_BACKWARD, FFTW_ESTIMATE); fftw_plan fftwBackward2 = fftw_plan_dft_2d(inputImage->s(), inputImage->t(), reinterpret_cast<fftw_complex*>(fftwFreq2), reinterpret_cast<fftw_complex*>(fftwImag2), FFTW_BACKWARD, FFTW_ESTIMATE); for(int x=0; x<inputImage->s(); ++x) { for(int y=0; y<inputImage->t(); ++y) { if(inputImage->getPixelFormat()==0x83f0) { //COMPRESSED_RGB_S3TC_DXT1_EXT decompression unsigned int blocksize = 8; unsigned char* data = inputImage->data(); unsigned char* block = data + (blocksize*(unsigned int)(ceil(double(inputImage->s()/4.0)*floor(y/4.0) + floor(x/4.0)))); int rel_x = x % 4; int rel_y = y % 4; unsigned char& c0_lo = *(block+0); unsigned char& c0_hi = *(block+1); unsigned char& c1_lo = *(block+2); unsigned char& c1_hi = *(block+3); unsigned char& bits_0 = *(block+4); unsigned char& bits_1 = *(block+5); unsigned char& bits_2 = *(block+6); unsigned char& bits_3 = *(block+7); unsigned short color0 = c0_lo + c0_hi * 256; unsigned short color1 = c1_lo + c1_hi * 256; unsigned int bits = bits_0 + 256 * (bits_1 + 256 * (bits_2 + 256 * bits_3)); unsigned int code_bits_pos = 2*(4*rel_y+rel_x); unsigned int code = (bits>>code_bits_pos) & 0x03; unsigned char r0 = ((color0>>11) & 0x1f); unsigned char g0 = ((color0>>5) & 0x3f); unsigned char b0 = ((color0>>0) & 0x1f); unsigned char r1 = ((color1>>11) & 0x1f); unsigned char g1 = ((color1>>5) & 0x3f); unsigned char b1 = ((color1>>0) & 0x1f); unsigned char r = 0; unsigned char g = 0; unsigned char b = 0; if(color0>color1) { switch(code) { case 0: r = r0; g = g0; b = b0; break; case 1: r = r1; g = g1; b = b1; break; case 2: r = (2*r0+r1)/3; g = (2*g0+g1)/3; b = (2*b0+b1)/3; break; case 3: r = (r0+2*r1)/3; g = (g0+2*g1)/3; b = (b0+2*b1)/3; break; }; } else { switch(code) { case 0: r = r0; g = g0; b = b0; break; case 1: r = r1; g = g1; b = b1; break; case 2: r = (r0+r1)/2; g = (g0+g1)/2; b = (b0+b1)/2; break; case 3: r = 0; g = 0; b = 0; break; }; } (*(fftwImag1+inputImage->t()*x+y)) = (0.0*one)+((double)r*(double)0xff/(double)0x1f*e2*e3); (*(fftwImag2+inputImage->t()*x+y)) = ((double)g*(double)0xff/(double)0x3f*e3*e1)*e3*e1 + ((double)b*(double)0xff/(double)0x1f*e1*e2); /*if(outputImage) { *(outputImage->data(x,y)+0) = (unsigned int)((double)r*(double)0xff/(double)0x1f); *(outputImage->data(x,y)+1) = (unsigned int)((double)g*(double)0xff/(double)0x3f); *(outputImage->data(x,y)+2) = (unsigned int)((double)b*(double)0xff/(double)0x1f); }*/ } else { unsigned char& r = *(inputImage->data(x,y)+0); unsigned char& g = *(inputImage->data(x,y)+1); unsigned char& b = *(inputImage->data(x,y)+2); (*(fftwImag1+inputImage->t()*x+y)) = (0.0*one)+((double)r*e2*e3); (*(fftwImag2+inputImage->t()*x+y)) = ((double)g*e3*e1)*e3*e1 + ((double)b*e1*e2); //if(x==0 && y==0) std::cout << "(0,0): r: " << (int)r << ", g: " << (int)g << ", b: " << (int)b << std::endl; } } }
OGRLineString *getLineString(DOMElement *elem, int bAsLinearRing) { // elem -> POLYLINE OGRLineString *ls; if (bAsLinearRing) ls = new OGRLinearRing(); else ls = new OGRLineString(); DOMElement *lineElem = (DOMElement *)elem->getFirstChild(); while (lineElem != NULL) { char* pszTagName = XMLString::transcode(lineElem->getTagName()); if (cmpStr(ILI2_COORD, pszTagName) == 0) { OGRPoint* poPoint = getPoint(lineElem); ls->addPoint(poPoint); delete poPoint; } else if (cmpStr(ILI2_ARC, pszTagName) == 0) { // end point OGRPoint *ptEnd = new OGRPoint(); // point on the arc OGRPoint *ptOnArc = new OGRPoint(); // radius double radius = 0; DOMElement *arcElem = (DOMElement *)lineElem->getFirstChild(); while (arcElem != NULL) { char* pszTagName = XMLString::transcode(arcElem->getTagName()); char* pszObjValue = getObjValue(arcElem); if (cmpStr("C1", pszTagName) == 0) ptEnd->setX(atof(pszObjValue)); else if (cmpStr("C2", pszTagName) == 0) ptEnd->setY(atof(pszObjValue)); else if (cmpStr("C3", pszTagName) == 0) ptEnd->setZ(atof(pszObjValue)); else if (cmpStr("A1", pszTagName) == 0) ptOnArc->setX(atof(pszObjValue)); else if (cmpStr("A2", pszTagName) == 0) ptOnArc->setY(atof(pszObjValue)); else if (cmpStr("A3", pszTagName) == 0) ptOnArc->setZ(atof(pszObjValue)); else if (cmpStr("R", pszTagName) == 0) radius = atof(pszObjValue); CPLFree(pszObjValue); XMLString::release(&pszTagName); arcElem = (DOMElement *)arcElem->getNextSibling(); } ptEnd->flattenTo2D(); ptOnArc->flattenTo2D(); OGRPoint *ptStart = getPoint((DOMElement *)lineElem->getPreviousSibling()); // COORD or ARC interpolateArc(ls, ptStart, ptOnArc, ptEnd, PI/180); delete ptStart; delete ptEnd; delete ptOnArc; } /* else { // FIXME StructureValue in Polyline not yet supported } */ XMLString::release(&pszTagName); lineElem = (DOMElement *)lineElem->getNextSibling(); } return ls; }
void DrawShape::featuredetect(int XPoint,int YPoint) { if(!sfile.empty() && XPoint>=(x_pos_shift-increase_width/2)*6.40 && XPoint<=(x_pos_shift-increase_width/2)*6.40+(100+increase_width)*6.4 && YPoint>=(y_pos_shift-increase_height/2)*4.8 && YPoint<=(y_pos_shift-increase_height/2)*4.8+(100+increase_height)*4.8 )//check if point is inside the view area { OGRDataSource *poDS; string dfile = sfile + ".shp"; string shp = "g_4326/" + sfile + ".shp"; poDS = OGRSFDriverRegistrar::Open(shp.c_str(), FALSE ); //comment till here if( poDS == NULL ) { WApplication::instance()->doJavaScript("alert('Open failed')"); cout << "Open failed"; } OGRLayer *poLayer; poLayer = poDS->GetLayerByName( sfile.c_str() ); // comment here OGRFeature *poFeature; OGREnvelope * psExtent = new OGREnvelope(); poLayer->GetExtent(psExtent); double xMin = psExtent->MinX; double yMin = psExtent->MinY; double xMax = psExtent->MaxX; double yMax = psExtent->MaxY; stringstream strm; strm << xMin; string exp; double scaleFactor; string bound_string = strm.str(); int size = bound_string.size(); size_t found=bound_string.find("+"); if (found!=string::npos) { exp = bound_string.substr(found+1,size); } if(exp.empty()) { stringstream strExtent; strExtent << yMin; bound_string = strExtent.str(); size = bound_string.size(); found = bound_string.find("+"); if(found!=string::npos) { exp = bound_string.substr(found+1,size); } } if(exp.empty()) { stringstream strExtent; strExtent << xMax; bound_string = strExtent.str(); size = bound_string.size(); found = bound_string.find("+"); if(found!=string::npos) { exp = bound_string.substr(found+1,size); } } if(exp.empty()) { stringstream strExtent; strExtent << yMax; bound_string = strExtent.str(); size = bound_string.size(); found = bound_string.find("+"); if(found!=string::npos) { exp = bound_string.substr(found+1,size); } } if(!exp.empty()) { int exponent = boost::lexical_cast<int>(exp); exponent-=3; scaleFactor = pow (10,exponent); } else { scaleFactor = 1; } xMin/=scaleFactor; xMax/=scaleFactor; yMin/=scaleFactor; yMax/=scaleFactor; double gWidth = xMax - xMin; double gHeight = yMax - yMin; double widthFactor = 1; double pwidth = abs(gWidth-gHeight); double s = gWidth - gHeight; if(s<0.16) gWidth = gHeight + 0.16; double scaledX=(XPoint*(gWidth* widthFactor*(100-increase_width)/100)/640 + (xMin+(-x_pos_shift+increase_width/2)/100*gWidth* widthFactor))*scaleFactor; double scaledY=(YPoint*(gHeight*widthFactor*(-1+increase_height/100))/480 + (yMax+(y_pos_shift-increase_height/2)/100*gHeight*widthFactor))*scaleFactor; OGRPoint *poPoint =new OGRPoint(); poPoint->setX(scaledX); poPoint->setY(scaledY); poLayer->ResetReading(); int index=0;bool flagFeature=false; while( (poFeature = poLayer->GetNextFeature()) != NULL ) { OGRGeometry *poGeometry; poGeometry = poFeature->GetGeometryRef(); if(poGeometry->Distance(poPoint)/scaleFactor<=0.01*gWidth*widthFactor) { flagFeature=true; //std::cerr<<index<<" " <<flagFeature<<" "<<poGeometry->Distance(poPoint); break; } index++; } if(flagFeature) DBFDialog *attrtable =new DBFDialog(cfile,sfile,flagFeature,index); } }
OGRFeature *OGRDGNLayer::ElementToFeature( DGNElemCore *psElement ) { OGRFeature *poFeature = new OGRFeature( poFeatureDefn ); poFeature->SetFID( psElement->element_id ); poFeature->SetField( "Type", psElement->type ); poFeature->SetField( "Level", psElement->level ); poFeature->SetField( "GraphicGroup", psElement->graphic_group ); poFeature->SetField( "ColorIndex", psElement->color ); poFeature->SetField( "Weight", psElement->weight ); poFeature->SetField( "Style", psElement->style ); m_nFeaturesRead++; /* -------------------------------------------------------------------- */ /* Collect linkage information */ /* -------------------------------------------------------------------- */ #define MAX_LINK 100 int anEntityNum[MAX_LINK], anMSLink[MAX_LINK]; unsigned char *pabyData; int iLink=0, nLinkCount=0; anEntityNum[0] = 0; anMSLink[0] = 0; pabyData = DGNGetLinkage( hDGN, psElement, iLink, NULL, anEntityNum+iLink, anMSLink+iLink, NULL ); while( pabyData && nLinkCount < MAX_LINK ) { iLink++; if( anEntityNum[nLinkCount] != 0 || anMSLink[nLinkCount] != 0 ) nLinkCount++; anEntityNum[nLinkCount] = 0; anMSLink[nLinkCount] = 0; pabyData = DGNGetLinkage( hDGN, psElement, iLink, NULL, anEntityNum+nLinkCount, anMSLink+nLinkCount, NULL ); } /* -------------------------------------------------------------------- */ /* Apply attribute linkage to feature. */ /* -------------------------------------------------------------------- */ if( nLinkCount > 0 ) { if( EQUAL(pszLinkFormat,"FIRST") ) { poFeature->SetField( "EntityNum", anEntityNum[0] ); poFeature->SetField( "MSLink", anMSLink[0] ); } else if( EQUAL(pszLinkFormat,"LIST") ) { poFeature->SetField( "EntityNum", nLinkCount, anEntityNum ); poFeature->SetField( "MSLink", nLinkCount, anMSLink ); } else if( EQUAL(pszLinkFormat,"STRING") ) { char szEntityList[MAX_LINK*9], szMSLinkList[MAX_LINK*9]; int nEntityLen = 0, nMSLinkLen = 0; for( iLink = 0; iLink < nLinkCount; iLink++ ) { if( iLink != 0 ) { szEntityList[nEntityLen++] = ','; szMSLinkList[nMSLinkLen++] = ','; } sprintf( szEntityList + nEntityLen, "%d", anEntityNum[iLink]); sprintf( szMSLinkList + nMSLinkLen, "%d", anMSLink[iLink] ); nEntityLen += strlen(szEntityList + nEntityLen ); nMSLinkLen += strlen(szMSLinkList + nMSLinkLen ); } poFeature->SetField( "EntityNum", szEntityList ); poFeature->SetField( "MSLink", szMSLinkList ); } } /* -------------------------------------------------------------------- */ /* Lookup color. */ /* -------------------------------------------------------------------- */ char gv_color[128]; int gv_red, gv_green, gv_blue; char szFSColor[128], szPen[256]; szFSColor[0] = '\0'; if( DGNLookupColor( hDGN, psElement->color, &gv_red, &gv_green, &gv_blue ) ) { sprintf( gv_color, "%f %f %f 1.0", gv_red / 255.0, gv_green / 255.0, gv_blue / 255.0 ); sprintf( szFSColor, "c:#%02x%02x%02x", gv_red, gv_green, gv_blue ); } /* -------------------------------------------------------------------- */ /* Generate corresponding PEN style. */ /* -------------------------------------------------------------------- */ if( psElement->style == DGNS_SOLID ) sprintf( szPen, "PEN(id:\"ogr-pen-0\"" ); else if( psElement->style == DGNS_DOTTED ) sprintf( szPen, "PEN(id:\"ogr-pen-5\"" ); else if( psElement->style == DGNS_MEDIUM_DASH ) sprintf( szPen, "PEN(id:\"ogr-pen-2\"" ); else if( psElement->style == DGNS_LONG_DASH ) sprintf( szPen, "PEN(id:\"ogr-pen-4\"" ); else if( psElement->style == DGNS_DOT_DASH ) sprintf( szPen, "PEN(id:\"ogr-pen-6\"" ); else if( psElement->style == DGNS_SHORT_DASH ) sprintf( szPen, "PEN(id:\"ogr-pen-3\"" ); else if( psElement->style == DGNS_DASH_DOUBLE_DOT ) sprintf( szPen, "PEN(id:\"ogr-pen-7\"" ); else if( psElement->style == DGNS_LONG_DASH_SHORT_DASH ) sprintf( szPen, "PEN(p:\"10px 5px 4px 5px\"" ); else sprintf( szPen, "PEN(id:\"ogr-pen-0\"" ); if( strlen(szFSColor) > 0 ) sprintf( szPen+strlen(szPen), ",%s", szFSColor ); if( psElement->weight > 1 ) sprintf( szPen+strlen(szPen), ",w:%dpx", psElement->weight ); strcat( szPen, ")" ); switch( psElement->stype ) { case DGNST_MULTIPOINT: if( psElement->type == DGNT_SHAPE ) { OGRLinearRing *poLine = new OGRLinearRing(); OGRPolygon *poPolygon = new OGRPolygon(); DGNElemMultiPoint *psEMP = (DGNElemMultiPoint *) psElement; poLine->setNumPoints( psEMP->num_vertices ); for( int i = 0; i < psEMP->num_vertices; i++ ) { poLine->setPoint( i, psEMP->vertices[i].x, psEMP->vertices[i].y, psEMP->vertices[i].z ); } poPolygon->addRingDirectly( poLine ); poFeature->SetGeometryDirectly( poPolygon ); ConsiderBrush( psElement, szPen, poFeature ); } else if( psElement->type == DGNT_CURVE ) { DGNElemMultiPoint *psEMP = (DGNElemMultiPoint *) psElement; OGRLineString *poLine = new OGRLineString(); DGNPoint *pasPoints; int nPoints; nPoints = 5 * psEMP->num_vertices; pasPoints = (DGNPoint *) CPLMalloc(sizeof(DGNPoint) * nPoints); DGNStrokeCurve( hDGN, psEMP, nPoints, pasPoints ); poLine->setNumPoints( nPoints ); for( int i = 0; i < nPoints; i++ ) { poLine->setPoint( i, pasPoints[i].x, pasPoints[i].y, pasPoints[i].z ); } poFeature->SetGeometryDirectly( poLine ); CPLFree( pasPoints ); poFeature->SetStyleString( szPen ); } else { OGRLineString *poLine = new OGRLineString(); DGNElemMultiPoint *psEMP = (DGNElemMultiPoint *) psElement; if( psEMP->num_vertices > 0 ) { poLine->setNumPoints( psEMP->num_vertices ); for( int i = 0; i < psEMP->num_vertices; i++ ) { poLine->setPoint( i, psEMP->vertices[i].x, psEMP->vertices[i].y, psEMP->vertices[i].z ); } poFeature->SetGeometryDirectly( poLine ); } poFeature->SetStyleString( szPen ); } break; case DGNST_ARC: { OGRLineString *poLine = new OGRLineString(); DGNElemArc *psArc = (DGNElemArc *) psElement; DGNPoint asPoints[90]; int nPoints; nPoints = (int) (MAX(1,ABS(psArc->sweepang) / 5) + 1); DGNStrokeArc( hDGN, psArc, nPoints, asPoints ); poLine->setNumPoints( nPoints ); for( int i = 0; i < nPoints; i++ ) { poLine->setPoint( i, asPoints[i].x, asPoints[i].y, asPoints[i].z ); } poFeature->SetGeometryDirectly( poLine ); poFeature->SetStyleString( szPen ); } break; case DGNST_TEXT: { OGRPoint *poPoint = new OGRPoint(); DGNElemText *psText = (DGNElemText *) psElement; char *pszOgrFS; poPoint->setX( psText->origin.x ); poPoint->setY( psText->origin.y ); poPoint->setZ( psText->origin.z ); poFeature->SetGeometryDirectly( poPoint ); pszOgrFS = (char *) CPLMalloc(strlen(psText->string) + 150); // setup the basic label. sprintf( pszOgrFS, "LABEL(t:\"%s\"", psText->string ); // set the color if we have it. if( strlen(szFSColor) > 0 ) sprintf( pszOgrFS+strlen(pszOgrFS), ",%s", szFSColor ); // Add the size info in ground units. if( ABS(psText->height_mult) >= 6.0 ) sprintf( pszOgrFS+strlen(pszOgrFS), ",s:%dg", (int) psText->height_mult ); else if( ABS(psText->height_mult) > 0.1 ) sprintf( pszOgrFS+strlen(pszOgrFS), ",s:%.3fg", psText->height_mult ); else sprintf( pszOgrFS+strlen(pszOgrFS), ",s:%.12fg", psText->height_mult ); // Add the font name. Name it MstnFont<FONTNUMBER> if not available // in the font list. #3392 static const char *papszFontList[] = { "STANDARD", "WORKING", "FANCY", "ENGINEERING", "NEWZERO", "STENCEL", //0-5 "USTN_FANCY", "COMPRESSED", "STENCEQ", NULL, "hand", "ARCH", //6-11 "ARCHB", NULL, NULL, "IGES1001", "IGES1002", "IGES1003", //12-17 "CENTB", "MICROS", NULL, NULL, "ISOFRACTIONS", "ITALICS", //18-23 "ISO30", NULL, "GREEK", "ISOREC", "Isoeq", NULL, //24-29 "ISO_FONTLEFT", "ISO_FONTRIGHT", "INTL_ENGINEERING", "INTL_WORKING", "ISOITEQ", NULL, //30-35 "USTN FONT 26", NULL, NULL, NULL, NULL, "ARCHITECTURAL", //36-41 "BLOCK_OUTLINE", "LOW_RES_FILLED", NULL, NULL, NULL, NULL, //42-47 NULL, NULL, "UPPERCASE", NULL, NULL, NULL, //48-53 NULL, NULL, NULL, NULL, NULL, NULL, //54-49 "FONT060", "din", "dinit", "helvl", "HELVLIT", "helv", //60-65 "HELVIT", "cent", "CENTIT", "SCRIPT", NULL, NULL, //66-71 NULL, NULL, NULL, NULL, "MICROQ", "dotfont", //72-77 "DOTIT", NULL, NULL, NULL, NULL, NULL, //78-83 NULL, NULL, NULL, NULL, NULL, NULL, //84-89 NULL, NULL, "FONT092", NULL, "FONT094", NULL, //90-95 NULL, NULL, NULL, NULL, "ANSI_SYMBOLS", "FEATURE_CONTROL_SYSMBOLS", //96-101 "SYMB_FAST", NULL, NULL, "INTL_ISO", "INTL_ISO_EQUAL", "INTL_ISO_ITALIC", //102-107 "INTL_ISO_ITALIC_EQUAL" }; //108 if(psText->font_id <= 108 && papszFontList[psText->font_id] != NULL ) { sprintf( pszOgrFS+strlen(pszOgrFS), ",f:%s", papszFontList[psText->font_id] ); } else { sprintf( pszOgrFS+strlen(pszOgrFS), ",f:MstnFont%d", psText->font_id ); } // Add the angle, if not horizontal if( psText->rotation != 0.0 ) sprintf( pszOgrFS+strlen(pszOgrFS), ",a:%d", (int) (psText->rotation+0.5) ); strcat( pszOgrFS, ")" ); poFeature->SetStyleString( pszOgrFS ); CPLFree( pszOgrFS ); poFeature->SetField( "Text", psText->string ); } break; case DGNST_COMPLEX_HEADER: { DGNElemComplexHeader *psHdr = (DGNElemComplexHeader *) psElement; int iChild; OGRMultiLineString oChildren; /* collect subsequent child geometries. */ // we should disable the spatial filter ... add later. for( iChild = 0; iChild < psHdr->numelems; iChild++ ) { OGRFeature *poChildFeature = NULL; DGNElemCore *psChildElement; psChildElement = DGNReadElement( hDGN ); // should verify complex bit set, not another header. if( psChildElement != NULL ) { poChildFeature = ElementToFeature( psChildElement ); DGNFreeElement( hDGN, psChildElement ); } if( poChildFeature != NULL && poChildFeature->GetGeometryRef() != NULL ) { OGRGeometry *poGeom; poGeom = poChildFeature->GetGeometryRef(); if( wkbFlatten(poGeom->getGeometryType()) == wkbLineString ) oChildren.addGeometry( poGeom ); } if( poChildFeature != NULL ) delete poChildFeature; } // Try to assemble into polygon geometry. OGRGeometry *poGeom; if( psElement->type == DGNT_COMPLEX_SHAPE_HEADER ) poGeom = (OGRPolygon *) OGRBuildPolygonFromEdges( (OGRGeometryH) &oChildren, TRUE, TRUE, 100000, NULL ); else poGeom = oChildren.clone(); if( poGeom != NULL ) poFeature->SetGeometryDirectly( poGeom ); ConsiderBrush( psElement, szPen, poFeature ); } break; default: break; } /* -------------------------------------------------------------------- */ /* Fixup geometry dimension. */ /* -------------------------------------------------------------------- */ if( poFeature->GetGeometryRef() != NULL ) poFeature->GetGeometryRef()->setCoordinateDimension( DGNGetDimension( hDGN ) ); return poFeature; }
//--------------------------------------------------------- bool COGR_DataSource::_Write_Geometry(CSG_Shape *pShape, OGRFeature *pFeature) { if( pShape && pFeature ) { int iPoint, iPart; TSG_Point sgPoint; OGRPoint Point; OGRMultiPoint Points; OGRLineString Line; OGRMultiLineString Lines; OGRLinearRing Ring; OGRPolygon Polygon; switch( pShape->Get_Type() ) { //------------------------------------------------- case SHAPE_TYPE_Point: sgPoint = pShape->Get_Point(0); Point.setX(sgPoint.x); Point.setY(sgPoint.y); return( pFeature->SetGeometry(&Point) == OGRERR_NONE ); //------------------------------------------------- case SHAPE_TYPE_Points: for(iPart=0; iPart<pShape->Get_Part_Count(); iPart++) { for(iPoint=0; iPoint<pShape->Get_Point_Count(iPart); iPoint++) { sgPoint = pShape->Get_Point(iPoint, iPart); Point.setX(sgPoint.x); Point.setY(sgPoint.y); Points.addGeometry(&Point); } } return( pFeature->SetGeometry(&Points) == OGRERR_NONE ); //------------------------------------------------- case SHAPE_TYPE_Line: if( pShape->Get_Part_Count() == 1 ) { _Write_Line(pShape, &Line, 0); return( pFeature->SetGeometry(&Line) == OGRERR_NONE ); } else { for(iPart=0; iPart<pShape->Get_Part_Count(); iPart++) { if( _Write_Line(pShape, &Line, iPart) ) { Lines.addGeometry(&Line); } } return( pFeature->SetGeometry(&Lines) == OGRERR_NONE ); } //------------------------------------------------- case SHAPE_TYPE_Polygon: for(iPart=0; iPart<pShape->Get_Part_Count(); iPart++) { if( _Write_Line(pShape, &Ring, iPart) ) { Polygon.addRing(&Ring); } } return( pFeature->SetGeometry(&Polygon) == OGRERR_NONE ); //------------------------------------------------- default: break; } } return( false ); }
void ILI1Reader::ReadGeom( char **stgeom, int geomIdx, OGRwkbGeometryType eType, OGRFeature *feature ) { #ifdef DEBUG_VERBOSE CPLDebug( "OGR_ILI", "ILI1Reader::ReadGeom geomIdx: %d OGRGeometryType: %s", geomIdx, OGRGeometryTypeToName(eType) ); #endif if (eType == wkbNone) { CPLError( CE_Warning, CPLE_AppDefined, "Calling ILI1Reader::ReadGeom with wkbNone" ); } // Initialize geometry. OGRCompoundCurve *ogrCurve = new OGRCompoundCurve(); OGRCurvePolygon *ogrPoly = NULL; //current polygon OGRMultiCurve *ogrMultiLine = NULL; //current multi line if (eType == wkbMultiCurve || eType == wkbMultiLineString) { ogrMultiLine = new OGRMultiCurve(); } else if (eType == wkbPolygon || eType == wkbCurvePolygon) { ogrPoly = new OGRCurvePolygon(); } OGRPoint ogrPoint; // Current point. ogrPoint.setX(CPLAtof(stgeom[1])); ogrPoint.setY(CPLAtof(stgeom[2])); OGRLineString *ogrLine = new OGRLineString(); ogrLine->addPoint(&ogrPoint); // Parse geometry. char **tokens = NULL; bool end = false; OGRCircularString *arc = NULL; //current arc while (!end && (tokens = ReadParseLine()) != NULL) { const char *firsttok = CSLGetField(tokens, 0); if( firsttok == NULL ) { // do nothing } else if (EQUAL(firsttok, "LIPT") && CSLCount(tokens) >= 3) { ogrPoint.setX(CPLAtof(tokens[1])); ogrPoint.setY(CPLAtof(tokens[2])); if (arc) { arc->addPoint(&ogrPoint); OGRErr error = ogrCurve->addCurveDirectly(arc); if (error != OGRERR_NONE) { char* pszJSon = arc->exportToJson(); CPLError(CE_Warning, CPLE_AppDefined, "Could not add geometry: %s", pszJSon ? pszJSon : "(null)" ); CPLFree(pszJSon); delete arc; } arc = NULL; } ogrLine->addPoint(&ogrPoint); } else if (EQUAL(firsttok, "ARCP") && CSLCount(tokens) >= 3) { //Finish line and start arc if (ogrLine->getNumPoints() > 1) { OGRErr error = ogrCurve->addCurveDirectly(ogrLine); if (error != OGRERR_NONE) { char* pszJSon = ogrLine->exportToJson(); CPLError(CE_Warning, CPLE_AppDefined, "Could not add geometry: %s", pszJSon ? pszJSon : "(null)" ); CPLFree(pszJSon); delete ogrLine; } ogrLine = new OGRLineString(); } else { ogrLine->empty(); } delete arc; arc = new OGRCircularString(); arc->addPoint(&ogrPoint); ogrPoint.setX(CPLAtof(tokens[1])); ogrPoint.setY(CPLAtof(tokens[2])); arc->addPoint(&ogrPoint); } else if (EQUAL(firsttok, "ELIN")) { if (ogrLine->getNumPoints() > 1) { // Ignore single LIPT after ARCP OGRErr error = ogrCurve->addCurveDirectly(ogrLine); if (error != OGRERR_NONE) { char* pszJSon = ogrLine->exportToJson(); CPLError(CE_Warning, CPLE_AppDefined, "Could not add geometry: %s", pszJSon ? pszJSon : "(null)" ); CPLFree(pszJSon); delete ogrLine; } ogrLine = NULL; } if (!ogrCurve->IsEmpty()) { if (ogrMultiLine) { OGRErr error = ogrMultiLine->addGeometryDirectly(ogrCurve); if (error != OGRERR_NONE) { char* pszJSon = ogrCurve->exportToJson(); CPLError(CE_Warning, CPLE_AppDefined, "Could not add geometry: %s", pszJSon ? pszJSon : "(null)" ); CPLFree(pszJSon); delete ogrCurve; } ogrCurve = NULL; } if (ogrPoly) { OGRErr error = ogrPoly->addRingDirectly(ogrCurve); if (error != OGRERR_NONE) { char* pszJSon = ogrCurve->exportToJson(); CPLError(CE_Warning, CPLE_AppDefined, "Could not add geometry: %s", pszJSon ? pszJSon : "(null)" ); CPLFree(pszJSon); delete ogrCurve; } ogrCurve = NULL; } } end = true; } else if (EQUAL(firsttok, "EEDG")) { end = true; } else if (EQUAL(firsttok, "LATT")) { //Line Attributes (ignored) } else if (EQUAL(firsttok, "EFLA")) { end = true; } else if (EQUAL(firsttok, "ETAB")) { end = true; } else { CPLError( CE_Warning, CPLE_AppDefined, "Unexpected token: %s", firsttok ); } CSLDestroy(tokens); } delete arc; delete ogrLine; //Set feature geometry if (eType == wkbMultiCurve) { feature->SetGeomFieldDirectly(geomIdx, ogrMultiLine); delete ogrCurve; } else if (eType == wkbMultiLineString) { feature->SetGeomFieldDirectly(geomIdx, ogrMultiLine->getLinearGeometry()); delete ogrMultiLine; delete ogrCurve; } else if (eType == wkbCurvePolygon) { feature->SetGeomFieldDirectly(geomIdx, ogrPoly); delete ogrCurve; } else if (eType == wkbPolygon) { feature->SetGeomFieldDirectly(geomIdx, ogrPoly->getLinearGeometry()); delete ogrPoly; delete ogrCurve; } else { feature->SetGeomFieldDirectly(geomIdx, ogrCurve); } }
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 }
// export bool ImportExportGdal::export_(const QList<Feature *>& featList) { const char *pszDriverName = "SQLite"; OGRSFDriver *poDriver; OGRRegisterAll(); poDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(pszDriverName); if( poDriver == NULL ) { qDebug( "%s driver not available.", pszDriverName ); return false; } OGRDataSource *poDS; QFile::remove(QString(HOMEDIR + "/test.sqlite")); poDS = poDriver->CreateDataSource( QString(HOMEDIR + "/test.sqlite").toUtf8().constData(), NULL ); if( poDS == NULL ) { qDebug( "Creation of output file failed." ); return false; } poDS->ExecuteSQL("PRAGMA synchronous = OFF", NULL, NULL); OGRSpatialReference *poSRS; poSRS = new OGRSpatialReference(); poSRS->importFromEPSG(4326); char **papszOptions = NULL; papszOptions = CSLSetNameValue( papszOptions, "SPATIALITE", "YES" ); papszOptions = CSLSetNameValue( papszOptions, "FORMAT", "SPATIALITE" ); papszOptions = CSLSetNameValue( papszOptions, "SPATIAL_INDEX", "YES" ); OGRLayer *poLayer; poLayer = poDS->CreateLayer( "osm", poSRS, wkbUnknown, papszOptions); CSLDestroy( papszOptions ); if( poLayer == NULL ) { qDebug( "Layer creation failed." ); return false; } OGRFieldDefn oField("osm_id", OFTReal); if( poLayer->CreateField( &oField ) != OGRERR_NONE ) { qDebug( "Creating field failed." ); return false; } oField.Set("osm_version", OFTInteger ); poLayer->CreateField( &oField ); oField.Set("osm_timestamp", OFTInteger ); poLayer->CreateField( &oField ); OGRFeature *poFeature; foreach (Feature* F, featList) { poFeature = OGRFeature::CreateFeature( poLayer->GetLayerDefn() ); poFeature->SetField( "osm_id", (qreal)(F->id().numId)); #ifndef FRISIUS_BUILD poFeature->SetField( "osm_version", F->versionNumber()); poFeature->SetField( "osm_timestamp", (int)F->time().toTime_t()); #endif if (CHECK_NODE(F)) { Node* N = STATIC_CAST_NODE(F); OGRPoint pt; pt.setX(N->position().x()); pt.setY(N->position().y()); poFeature->SetGeometry( &pt ); } else if (CHECK_WAY(F)) { Way* W = STATIC_CAST_WAY(F); OGRLineString ls; ls.setNumPoints(W->size()); for (int i=0; i<W->size(); ++i) { ls.setPoint(i, W->getNode(i)->position().x(), W->getNode(i)->position().y(), 0); } poFeature->SetGeometry( &ls ); } if( poLayer->CreateFeature( poFeature ) != OGRERR_NONE ) { qDebug( "Failed to create feature in output." ); return false; } OGRFeature::DestroyFeature( poFeature ); }
/*! \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; }
static OGRCompoundCurve *getPolyline(DOMElement *elem) { // elem -> POLYLINE OGRCompoundCurve *ogrCurve = new OGRCompoundCurve(); OGRLineString *ls = new OGRLineString(); DOMElement *lineElem = (DOMElement *)elem->getFirstChild(); while (lineElem != NULL) { char* pszTagName = XMLString::transcode(lineElem->getTagName()); if (cmpStr(ILI2_COORD, pszTagName) == 0) { OGRPoint* poPoint = getPoint(lineElem); ls->addPoint(poPoint); delete poPoint; } else if (cmpStr(ILI2_ARC, pszTagName) == 0) { //Finish line and start arc if (ls->getNumPoints() > 1) { ogrCurve->addCurveDirectly(ls); ls = new OGRLineString(); } else { ls->empty(); } OGRCircularString *arc = new OGRCircularString(); // end point OGRPoint *ptEnd = new OGRPoint(); // point on the arc OGRPoint *ptOnArc = new OGRPoint(); // radius // double radius = 0; DOMElement *arcElem = (DOMElement *)lineElem->getFirstChild(); while (arcElem != NULL) { char* pszTagName2 = XMLString::transcode(arcElem->getTagName()); char* pszObjValue = getObjValue(arcElem); if (cmpStr("C1", pszTagName2) == 0) ptEnd->setX(CPLAtof(pszObjValue)); else if (cmpStr("C2", pszTagName2) == 0) ptEnd->setY(CPLAtof(pszObjValue)); else if (cmpStr("C3", pszTagName2) == 0) ptEnd->setZ(CPLAtof(pszObjValue)); else if (cmpStr("A1", pszTagName2) == 0) ptOnArc->setX(CPLAtof(pszObjValue)); else if (cmpStr("A2", pszTagName2) == 0) ptOnArc->setY(CPLAtof(pszObjValue)); else if (cmpStr("A3", pszTagName2) == 0) ptOnArc->setZ(CPLAtof(pszObjValue)); else if (cmpStr("R", pszTagName2) == 0) { // radius = CPLAtof(pszObjValue); } CPLFree(pszObjValue); XMLString::release(&pszTagName2); arcElem = (DOMElement *)arcElem->getNextSibling(); } OGRPoint *ptStart = getPoint((DOMElement *)lineElem->getPreviousSibling()); // COORD or ARC arc->addPoint(ptStart); arc->addPoint(ptOnArc); arc->addPoint(ptEnd); ogrCurve->addCurveDirectly(arc); delete ptStart; delete ptEnd; delete ptOnArc; } /* else { // TODO: StructureValue in Polyline not yet supported } */ XMLString::release(&pszTagName); lineElem = (DOMElement *)lineElem->getNextSibling(); } if (ls->getNumPoints() > 1) { ogrCurve->addCurveDirectly(ls); } else { delete ls; } return ogrCurve; }
OGRFeature *OGRDODSGridLayer::GetFeature( GIntBig nFeatureId ) { if( nFeatureId < 0 || nFeatureId >= nMaxRawIndex ) return NULL; /* -------------------------------------------------------------------- */ /* Ensure we have the dataset. */ /* -------------------------------------------------------------------- */ if( !ProvideDataDDS() ) return NULL; /* -------------------------------------------------------------------- */ /* Create the feature being read. */ /* -------------------------------------------------------------------- */ OGRFeature *poFeature = new OGRFeature( poFeatureDefn ); poFeature->SetFID( nFeatureId ); m_nFeaturesRead++; /* -------------------------------------------------------------------- */ /* Establish the values for the various dimension indices. */ /* -------------------------------------------------------------------- */ int iDim; int nRemainder = static_cast<int>(nFeatureId); for( iDim = nDimCount-1; iDim >= 0; iDim-- ) { paoDimensions[iDim].iLastValue = (nRemainder % paoDimensions[iDim].nDimEntries) * paoDimensions[iDim].nDimStride + paoDimensions[iDim].nDimStart; nRemainder = nRemainder / paoDimensions[iDim].nDimEntries; if( poTargetGrid == NULL ) poFeature->SetField( iDim, paoDimensions[iDim].iLastValue ); } CPLAssert( nRemainder == 0 ); /* -------------------------------------------------------------------- */ /* For grids, we need to apply the values of the dimensions */ /* looked up in the corresponding map. */ /* -------------------------------------------------------------------- */ if( poTargetGrid != NULL ) { for( iDim = 0; iDim < nDimCount; iDim++ ) { ArrayEntryToField( paoDimensions[iDim].poMap, paoDimensions[iDim].pRawData, paoDimensions[iDim].iLastValue, poFeature, iDim ); } } /* -------------------------------------------------------------------- */ /* Process all the regular data fields. */ /* -------------------------------------------------------------------- */ int iArray; for( iArray = 0; iArray < nArrayRefCount; iArray++ ) { OGRDODSArrayRef *poRef = paoArrayRefs + iArray; ArrayEntryToField( poRef->poArray, poRef->pRawData, static_cast<int>(nFeatureId), poFeature, poRef->iFieldIndex ); } /* -------------------------------------------------------------------- */ /* Do we have geometry information? */ /* -------------------------------------------------------------------- */ if( oXField.iFieldIndex >= 0 && oYField.iFieldIndex >= 0 ) { OGRPoint *poPoint = new OGRPoint(); poPoint->setX( poFeature->GetFieldAsDouble( oXField.iFieldIndex ) ); poPoint->setY( poFeature->GetFieldAsDouble( oYField.iFieldIndex ) ); if( oZField.iFieldIndex >= 0 ) poPoint->setZ( poFeature->GetFieldAsDouble(oZField.iFieldIndex) ); poFeature->SetGeometryDirectly( poPoint ); } return poFeature; }
bool Shape::save(const std::string& filename) { if (shapeType == -1) { std::cout << "Shape type is not set." << std::endl; return false; } if (shapeObjects.size() == 0) { std::cout << "No shape exists." << std::endl; return false; } const char *pszDriverName = "ESRI Shapefile"; GDALDriver *poDriver; GDALAllRegister(); poDriver = GetGDALDriverManager()->GetDriverByName(pszDriverName); if (poDriver == NULL) { printf("%s driver not available.\n", pszDriverName); return false; } GDALDataset *poDS; poDS = poDriver->Create(filename.c_str(), 0, 0, 0, GDT_Unknown, NULL); if (poDS == NULL) { printf("Creation of output file failed.\n"); return false; } OGRLayer *poLayer; if (shapeType == wkbPoint) { poLayer = poDS->CreateLayer("point_out", NULL, wkbPoint, NULL); } else if (shapeType == wkbLineString) { poLayer = poDS->CreateLayer("point_out", NULL, wkbLineString, NULL); } else if (shapeType == wkbPolygon) { poLayer = poDS->CreateLayer("point_out", NULL, wkbPolygon, NULL); } if (poLayer == NULL) { printf("Layer creation failed.\n"); return false; } for (auto it = shapeObjects[0].attributes.begin(); it != shapeObjects[0].attributes.end(); ++it) { OGRFieldDefn oField(it->first.c_str(), static_cast<OGRFieldType>(it->second.type)); if (it->second.type == OFTString) { oField.SetWidth(it->second.stringValue().size()); } if (poLayer->CreateField(&oField) != OGRERR_NONE) { printf("Creating Name field failed.\n"); return false; } } for (int i = 0; i < shapeObjects.size(); ++i) { if (shapeObjects[i].parts.size() == 0) continue; OGRFeature *poFeature; poFeature = OGRFeature::CreateFeature(poLayer->GetLayerDefn()); // 属性をセット for (auto it = shapeObjects[i].attributes.begin(); it != shapeObjects[i].attributes.end(); ++it) { poFeature->SetField(it->first.c_str(), it->second.stringValue().c_str()); } // ジオメトリ情報をセット if (shapeType == wkbPoint) { OGRPoint point; point.setX(shapeObjects[i].parts[0].points[0].x); point.setY(shapeObjects[i].parts[0].points[0].y); point.setZ(shapeObjects[i].parts[0].points[0].z); poFeature->SetGeometry(&point); } else if (shapeType == wkbLineString) { OGRLineString lineString; for (int k = 0; k < shapeObjects[i].parts[0].points.size(); ++k) { lineString.addPoint(shapeObjects[i].parts[0].points[k].x, shapeObjects[i].parts[0].points[k].y, shapeObjects[i].parts[0].points[k].z); } poFeature->SetGeometry(&lineString); } else if (shapeType == wkbPolygon) { OGRPolygon polygon; for (int j = 0; j < shapeObjects[i].parts.size(); ++j) { OGRLinearRing linearRing; for (int k = 0; k < shapeObjects[i].parts[j].points.size(); ++k) { linearRing.addPoint(shapeObjects[i].parts[j].points[k].x, shapeObjects[i].parts[j].points[k].y, shapeObjects[i].parts[j].points[k].z); } polygon.addRing(&linearRing); } poFeature->SetGeometry(&polygon); } if (poLayer->CreateFeature(poFeature) != OGRERR_NONE) { printf("Failed to create feature in shapefile.\n"); return false; } OGRFeature::DestroyFeature(poFeature); } GDALClose(poDS); return true; }
void ILI1Reader::ReadGeom(char **stgeom, int geomIdx, OGRwkbGeometryType eType, OGRFeature *feature) { char **tokens = NULL; const char *firsttok = NULL; int end = FALSE; OGRCompoundCurve *ogrCurve = NULL; //current compound curve OGRLineString *ogrLine = NULL; //current line OGRCircularString *arc = NULL; //current arc OGRCurvePolygon *ogrPoly = NULL; //current polygon OGRPoint ogrPoint; //current point OGRMultiCurve *ogrMultiLine = NULL; //current multi line //CPLDebug( "OGR_ILI", "ILI1Reader::ReadGeom geomIdx: %d OGRGeometryType: %s", geomIdx, OGRGeometryTypeToName(eType)); if (eType == wkbNone) { CPLError(CE_Warning, CPLE_AppDefined, "Calling ILI1Reader::ReadGeom with wkbNone" ); } //Initialize geometry ogrCurve = new OGRCompoundCurve(); if (eType == wkbMultiCurve || eType == wkbMultiLineString) { ogrMultiLine = new OGRMultiCurve(); } else if (eType == wkbPolygon || eType == wkbCurvePolygon) { ogrPoly = new OGRCurvePolygon(); } //tokens = ["STPT", "1111", "22222"] ogrPoint.setX(CPLAtof(stgeom[1])); ogrPoint.setY(CPLAtof(stgeom[2])); ogrLine = new OGRLineString(); ogrLine->addPoint(&ogrPoint); //Parse geometry while (!end && (tokens = ReadParseLine())) { firsttok = CSLGetField(tokens, 0); if (EQUAL(firsttok, "LIPT")) { ogrPoint.setX(CPLAtof(tokens[1])); ogrPoint.setY(CPLAtof(tokens[2])); if (arc) { arc->addPoint(&ogrPoint); ogrCurve->addCurveDirectly(arc); arc = NULL; } ogrLine->addPoint(&ogrPoint); } else if (EQUAL(firsttok, "ARCP")) { //Finish line and start arc if (ogrLine->getNumPoints() > 1) { ogrCurve->addCurveDirectly(ogrLine); ogrLine = new OGRLineString(); } else { ogrLine->empty(); } arc = new OGRCircularString(); arc->addPoint(&ogrPoint); ogrPoint.setX(CPLAtof(tokens[1])); ogrPoint.setY(CPLAtof(tokens[2])); arc->addPoint(&ogrPoint); } else if (EQUAL(firsttok, "ELIN")) { if (!ogrLine->IsEmpty()) { ogrCurve->addCurveDirectly(ogrLine); } if (!ogrCurve->IsEmpty()) { if (ogrMultiLine) { ogrMultiLine->addGeometryDirectly(ogrCurve); } if (ogrPoly) { ogrPoly->addRingDirectly(ogrCurve); } } end = TRUE; } else if (EQUAL(firsttok, "EEDG")) { end = TRUE; } else if (EQUAL(firsttok, "LATT")) { //Line Attributes (ignored) } else if (EQUAL(firsttok, "EFLA")) { end = TRUE; } else if (EQUAL(firsttok, "ETAB")) { end = TRUE; } else { CPLError(CE_Warning, CPLE_AppDefined, "Unexpected token: %s", firsttok ); } CSLDestroy(tokens); } //Set feature geometry if (eType == wkbMultiCurve) { feature->SetGeomFieldDirectly(geomIdx, ogrMultiLine); } else if (eType == wkbMultiLineString) { feature->SetGeomFieldDirectly(geomIdx, ogrMultiLine->getLinearGeometry()); delete ogrMultiLine; } else if (eType == wkbCurvePolygon) { feature->SetGeomFieldDirectly(geomIdx, ogrPoly); } else if (eType == wkbPolygon) { feature->SetGeomFieldDirectly(geomIdx, ogrPoly->getLinearGeometry()); delete ogrPoly; } else { feature->SetGeomFieldDirectly(geomIdx, ogrCurve); } }