bool ShapelibProxy::getTypeAndCount(const ShapelibHandle &handle, std::string &errorMessage, ArcProxyLib::FeatureType &featureType, int &count) { int type; SHPGetInfo(handle.getShpHandle(), &count, &type, NULL, NULL); featureType = ArcProxyLib::UNKNOWN; switch (type) { case SHPT_POINT: // fall through case SHPT_POINTZ: featureType = ArcProxyLib::POINT; break; case SHPT_MULTIPOINT: // fall through case SHPT_MULTIPOINTZ: featureType = ArcProxyLib::MULTIPOINT; break; case SHPT_ARC: // fall through case SHPT_ARCZ: featureType = ArcProxyLib::POLYLINE; break; case SHPT_POLYGON: // fall through case SHPT_POLYGONZ: featureType = ArcProxyLib::POLYGON; break; default: errorMessage = "Unknown shape type"; return false; } return true; }
void loadMapData(std::string path, QPolygonF* poly) { SHPHandle shp = SHPOpen(path.c_str(), "rb"); if (shp != 0) { qDebug() << "Loaded map: " << path.c_str(); } else { qDebug() << "Could not load map: " << path.c_str(); return; } int entities, type; double minBound[4], maxBound[4]; SHPGetInfo(shp, &entities, &type, minBound, maxBound); // qDebug() << "Type: " << type << " Entities: " << entities; SHPObject* o = SHPReadObject(shp, 0); int parts = o->nParts; // qDebug() << "Parts: " << parts; int currentPart = 0; int start = o->panPartStart[currentPart]; int end = parts == 1 ? o->nVertices : o->panPartStart[currentPart + 1]; // qDebug() << "Start: " << start << " End: " << end << " Vertices: " << o->nVertices; for(int i = start; i < end; i++) { double x = o->padfX[i]; double y = o->padfY[i]; *poly << QPointF(x, y); } }
bool vtUtilityMap::ImportPolesFromSHP(const char *fname) { SHPHandle hSHP; int nEntities, nShapeType; DPoint2 point; // SHPOpen doesn't yet support utf-8 or wide filenames, so convert vtString fname_local = UTF8ToLocal(fname); hSHP = SHPOpen(fname_local, "rb"); if (!hSHP) return false; SHPGetInfo(hSHP, &nEntities, &nShapeType, NULL, NULL); if (nShapeType != SHPT_POINT) return false; for (int i = 0; i < nEntities; i++) { SHPObject *psShape = SHPReadObject(hSHP, i); point.x = psShape->padfX[0]; point.y = psShape->padfY[0]; vtPole *pole = new vtPole; pole->m_p = point; m_Poles.Append(pole); SHPDestroyObject(psShape); } SHPClose(hSHP); return true; }
//CAREFUL: note how adding things to the tree can change the root // Must not ever use cache a value of the root pointer if there's any // chance that the tree needs to be expanded! void build_rtree (struct Node **root, SHPHandle sHP) { int nEntities; intptr_t i; SHPObject *psCShape; struct Rect bbox_shape; SHPGetInfo(sHP, &nEntities, NULL, NULL, NULL); for( i = 0; i < nEntities; i++ ) { psCShape = SHPReadObject ( sHP, i ); if (psCShape != NULL) { bbox_shape.boundary[0]=(RectReal) psCShape->dfXMin; bbox_shape.boundary[1]=(RectReal) psCShape->dfYMin; bbox_shape.boundary[2]=(RectReal) psCShape->dfXMax; bbox_shape.boundary[3]=(RectReal) psCShape->dfYMax; SHPDestroyObject ( psCShape ); // Only insert the rect if it will not fail the assertion in // Xastir_RTreeInsertRect --- this will cause us to ignore any shapes that // have invalid bboxes (or that return invalid bboxes from shapelib // for whatever reason if (bbox_shape.boundary[0] <= bbox_shape.boundary[2] && bbox_shape.boundary[1] <= bbox_shape.boundary[3]) { Xastir_RTreeInsertRect(&bbox_shape, (void *)(i+1), root, 0); } } } }
void parse(const std::string& path, Visitor& visitor) const { SHPHandle shpFile = SHPOpen(path.c_str(), "rb"); if (shpFile == NULL) throw std::domain_error("Cannot open shp file."); int shapeType, entityCount; double adfMinBound[4], adfMaxBound[4]; SHPGetInfo(shpFile, &entityCount, &shapeType, adfMinBound, adfMaxBound); DBFHandle dbfFile = DBFOpen(path.c_str(), "rb"); if (dbfFile == NULL) throw std::domain_error("Cannot open dbf file."); if (DBFGetFieldCount(dbfFile) == 0) throw std::domain_error("There are no fields in dbf table."); if (entityCount != DBFGetRecordCount(dbfFile)) throw std::domain_error("dbf file has different entity count."); for (int k = 0; k < entityCount; k++) { SHPObject* shape = SHPReadObject(shpFile, k); if (shape == NULL) throw std::domain_error("Unable to read shape:" + to_string(k)); Tags tags = parseTags(dbfFile, k); visitShape(*shape, tags, visitor); SHPDestroyObject(shape); } DBFClose(dbfFile); SHPClose(shpFile); }
// --------------------------------------------------------------------------- // // ----------- SHPObject* bSHPTable::vxs2shape(int o, ivertices* vxs){ int count; int ptype; double bmin[4],bmax[4]; SHPObject* obj; SHPGetInfo(_shp,&count,&ptype,bmin,bmax); if(ptype==SHPT_NULL){ obj=SHPCreateSimpleObject(ptype,0,NULL,NULL,NULL); } else{ double* x=(double*)malloc(ivs_n_vxs(vxs)*sizeof(double)); double* y=(double*)malloc(ivs_n_vxs(vxs)*sizeof(double)); int np=(ivs_n_parts(vxs)>1)?ivs_n_parts(vxs):0; int* p=(ivs_n_parts(vxs)>1)?(int*)malloc(ivs_n_parts(vxs)*sizeof(int)):NULL; int* pt=(ivs_n_parts(vxs)>1)?(int*)malloc(ivs_n_parts(vxs)*sizeof(int)):NULL; dvertices* dvxs=NULL; vxs_i2d(&dvxs,vxs,_reso); dvs_move(dvxs,_ox,_oy); transform_a2t(dvxs); if(p){ memmove(p,vxs->offs,vxs->no*sizeof(int)); memset(pt,SHPP_RING,vxs->no*sizeof(int)); } for(int i=0;i<ivs_n_vxs(vxs);i++){ x[i]=dvxs->vx.vx2[i].x; y[i]=dvxs->vx.vx2[i].y; } dvs_free(dvxs); obj=SHPCreateObject(ptype,o-1,np,p,pt,ivs_n_vxs(vxs),x,y,NULL,NULL); } return(obj); }
int count_shape_points(char *shape_name) { int entidades; SHPHandle arquivo_shp; arquivo_shp=SHPOpen(shape_name, "r"); SHPGetInfo(arquivo_shp,&entidades,NULL,NULL,NULL); return entidades; }
// Function to read outlets from a shapefile - overloaded to return an array of integer ID's int readoutlets(char *outletsfile, int *noutlets, double*& x, double*& y, int*& id) { SHPHandle shp = SHPOpen(outletsfile, "rb"); char dbffile[MAXLN]; nameadd(dbffile, outletsfile, ".dbf"); DBFHandle dbf = DBFOpen(dbffile, "rb"); if ((shp != NULL) && (dbf != NULL)) { int nEntities = 0; int nShapeType = 0; SHPGetInfo(shp, &nEntities, &nShapeType, NULL, NULL ); if (nShapeType != SHPT_POINT) { fprintf(stderr, "Outlets shapefile %s is not a point shapefile\n", outletsfile); fflush(stderr); return 1; } long p_size; long countPts = 0; int nfld = DBFGetFieldCount(dbf); //int idfld = DBFGetFieldIndex(dbf, "id"); int idfld = DBFGetFieldIndex(dbf, "OBJECTID"); // ZhuLJ, 2015/6/16 for( int i=0; i<nEntities; i++) { SHPObject * shape = SHPReadObject(shp, i); countPts += shape->nVertices; SHPDestroyObject(shape); } x = new double[countPts]; y = new double[countPts]; if (idfld >= 0) id = new int[countPts]; int nxy=0; for( int i=0; i<nEntities; i++) { SHPObject * shape = SHPReadObject(shp, i); p_size = shape->nVertices; for( int j=0; j<p_size; j++) { x[nxy] = shape->padfX[j]; y[nxy] = shape->padfY[j]; if (idfld >= 0) { id[nxy] = DBFReadIntegerAttribute(dbf, i, idfld); } nxy++; } SHPDestroyObject(shape); } *noutlets=nxy; SHPClose(shp); return 0; } else { fprintf(stderr, "Error opening outlets shapefile: %s\n", outletsfile); fflush(stderr); return 1; } }
// --------------------------------------------------------------------------- // // ----------- int bSHPTable::CountRecords(){ if(!_shp){ return(0); } int count; int ptype; double bmin[4],bmax[4]; SHPGetInfo(_shp,&count,&ptype,bmin,bmax); return(count); }
shapes_v shape_load_globe(const char* filename) { shapes_v globe; kv_init(globe); double adfMinBound[4], adfMaxBound[4]; // Read file SHPHandle hSHP = SHPOpen( filename, "rb" ); if(hSHP == NULL) goto end_loading; // Print shape bounds int country_count, shapes_vype; SHPGetInfo( hSHP, &country_count, &shapes_vype, adfMinBound, adfMaxBound ); fprintf(stderr, "Load %d countries\n", country_count); // Iterate through countries for(int i = 0; i < country_count; i++ ) { SHPObject *shp = SHPReadObject(hSHP, i); if(shp == NULL) goto end_loading; if(shp->nParts == 0) continue; // first part starts at point 0 if(shp->panPartStart[0] != 0) goto end_loading; // collect parts of country uint32_t parts = shp->nParts; for (uint32_t j=0; j<parts; j++) { // start index uint32_t s = shp->panPartStart[j]; // end index - start of next minus one, or end uint32_t e = (j+1 < parts) ? shp->panPartStart[j+1]: shp->nVertices; shape_v shape; kv_init(shape); // collect points of part for(uint32_t i=s; i<e; i++){ point_t p = (point_t){shp->padfX[i], shp->padfY[i]}; kv_push(point_t, shape, p); } kv_push(shape_v, globe, shape); } SHPDestroyObject( shp ); } SHPClose( hSHP ); end_loading: return globe; }
static int shapelib_len(lua_State *ls) { SHPHandle shp = checkshphandle(ls); int entcount; SHPGetInfo(shp, &entcount, 0, 0, 0); lua_pushnumber(ls, entcount); return 1; }
bool vtUtilityMap::ImportLinesFromSHP(const char *fname) { SHPHandle hSHP; int nEntities, nShapeType; int i, j, verts; // SHPOpen doesn't yet support utf-8 or wide filenames, so convert vtString fname_local = UTF8ToLocal(fname); hSHP = SHPOpen(fname_local, "rb"); if (!hSHP) return false; SHPGetInfo(hSHP, &nEntities, &nShapeType, NULL, NULL); if (nShapeType != SHPT_ARC) return false; for (i = 0; i < nEntities; i++) { SHPObject *psShape = SHPReadObject(hSHP, i); verts = psShape->nVertices; vtLine *line = new vtLine; line->SetSize(verts); // Store each SHP Poly Coord in Line for (j = 0; j < verts; j++) { line->GetAt(j).x = psShape->padfX[j]; line->GetAt(j).y = psShape->padfY[j]; } SHPDestroyObject(psShape); // Guess source and destination poles by using location line->m_src = ClosestPole(line->GetAt(0)); line->m_dst = ClosestPole(line->GetAt(verts-1)); // avoid degenerate lines if (line->m_src == line->m_dst) { delete line; continue; } // tweak start and end of line to match poles line->SetAt(0, line->m_src->m_p); line->SetAt(verts-1, line->m_dst->m_p); m_Lines.Append(line); } SHPClose(hSHP); return true; }
shape_reader(std::string const& name) { m_shp = ::SHPOpen((name + ".shp").c_str(), "rb"); m_dbf = ::DBFOpen((name + ".dbf").c_str(), "rb"); if (m_shp == NULL || m_dbf == NULL) { throw shapelib_file_open_exception(name); } double adfMinBound[4], adfMaxBound[4]; SHPGetInfo(m_shp, &m_count, &m_shape_type, adfMinBound, adfMaxBound ); }
int GetSHPType(const char *filename) { // SHPOpen doesn't yet support utf-8 or wide filenames, so convert vtString fname_local = UTF8ToLocal(filename); SHPHandle hSHP = SHPOpen(fname_local, "rb"); if (hSHP == NULL) return SHPT_NULL; int nEntities, nShapeType; SHPGetInfo(hSHP, &nEntities, &nShapeType, NULL, NULL); SHPClose(hSHP); return nShapeType; }
// --------------------------------------------------------------------------- // Constructeur // ------------ bSHPTable ::bSHPTable( const char* path, const char* name, bool create, double* reso, double* ox, double* oy, int* tsrid, int* asrid, int* status) :bStdTable(*reso,*ox,*oy,*tsrid,*asrid,status){ _bTrace_("bSHPTable::bSHPTable",false); int ptype=db2shp(*status); char fpath[1024]; sprintf(fpath,"%s%s",path,name); //_tm_(fpath); _shp=SHPOpen(fpath,"rb+"); if(!_shp){ //_te_("SHPOpen failed for rb+"); _shp=SHPOpen(fpath,"rb"); } //_tm_("SHPOpen passed"); if(_shp){ int count; double bmin[4],bmax[4]; //_tm_("SHPGetInfo"); SHPGetInfo(_shp,&count,&ptype,bmin,bmax); //_tm_(count+" objects of "+ptype+" kind"); *status=shp2db(ptype); return; } //_te_("SHPOpen failed for rb"); if(!create){ *status=-1; _te_(fpath+" : table not found"); return; } _shp=SHPCreate(fpath,ptype); if(!_shp){ _te_(fpath+" : creation failed"); *status=-1; return; } *status=0; }
SEXP Rshapeinfo1(SEXP shpname) { SEXP res, nms; SHPHandle hSHP; int nShapeType, nEntities, i, pc=0; double adfMinBound[4], adfMaxBound[4]; PROTECT(res = NEW_LIST(5)); pc++; PROTECT(nms = NEW_CHARACTER(5)); pc++; SET_STRING_ELT(nms, 0, COPY_TO_USER_STRING("fname")); SET_STRING_ELT(nms, 1, COPY_TO_USER_STRING("type")); SET_STRING_ELT(nms, 2, COPY_TO_USER_STRING("entities")); SET_STRING_ELT(nms, 3, COPY_TO_USER_STRING("minbounds")); SET_STRING_ELT(nms, 4, COPY_TO_USER_STRING("maxbounds")); setAttrib(res, R_NamesSymbol, nms); SET_VECTOR_ELT(res, 0, NEW_CHARACTER(1)); SET_VECTOR_ELT(res, 1, NEW_INTEGER(1)); SET_VECTOR_ELT(res, 2, NEW_INTEGER(1)); SET_VECTOR_ELT(res, 3, NEW_NUMERIC(4)); SET_VECTOR_ELT(res, 4, NEW_NUMERIC(4)); SET_STRING_ELT(VECTOR_ELT(res, 0), 0, STRING_ELT(shpname, 0)); /* const char *pszPlus; */ /* -------------------------------------------------------------------- */ /* Open the passed shapefile. */ /* -------------------------------------------------------------------- */ hSHP = SHPOpen(CHAR(STRING_ELT(shpname, 0)), "rb" ); if( hSHP == NULL ) error("Error opening SHP file"); /* -------------------------------------------------------------------- */ /* Print out the file bounds. */ /* -------------------------------------------------------------------- */ SHPGetInfo( hSHP, &nEntities, &nShapeType, adfMinBound, adfMaxBound ); INTEGER_POINTER(VECTOR_ELT(res, 1))[0] = nShapeType; INTEGER_POINTER(VECTOR_ELT(res, 2))[0] = nEntities; for (i=0; i<4; i++) { NUMERIC_POINTER(VECTOR_ELT(res, 3))[i] = adfMinBound[i]; NUMERIC_POINTER(VECTOR_ELT(res, 4))[i] = adfMaxBound[i]; } SHPClose( hSHP ); UNPROTECT(pc); return(res); }
static int shapelib_getinfo(lua_State *ls) { SHPHandle shp = checkshphandle(ls); int entcount; int shptype; double min[4]; double max[4]; SHPGetInfo(shp, &entcount, &shptype, min, max); lua_pushnumber(ls, entcount); lua_pushnumber(ls, shptype); for (int i = 0; i < 4; ++i) lua_pushnumber(ls, min[i]); for (int i = 0; i < 4; ++i) lua_pushnumber(ls, max[i]); return 10; }
OGRErr OGRShapeLayer::GetExtent (OGREnvelope *psExtent, int bForce) { UNREFERENCED_PARAM( bForce ); double adMin[4], adMax[4]; if( hSHP == NULL ) return OGRERR_FAILURE; SHPGetInfo(hSHP, NULL, NULL, adMin, adMax); psExtent->MinX = adMin[0]; psExtent->MinY = adMin[1]; psExtent->MaxX = adMax[0]; psExtent->MaxY = adMax[1]; return OGRERR_NONE; }
// Function to read outlets from a shapefile int readoutlets(char *outletsfile, int *noutlets, double*& x, double*& y) { SHPHandle shp; shp = SHPOpen(outletsfile, "rb"); if (shp != NULL) { int nEntities = 0; int nShapeType = 0; SHPGetInfo(shp, &nEntities, &nShapeType, NULL, NULL ); if (nShapeType != SHPT_POINT) { fprintf(stderr, "Outlets shapefile %s is not a point shapefile\n", outletsfile); fflush(stderr); return 1; } long p_size; long countPts = 0; for( int i=0; i<nEntities; i++) { SHPObject * shape = SHPReadObject(shp, i); countPts += shape->nVertices; SHPDestroyObject(shape); } x = new double[countPts]; y = new double[countPts]; int nxy=0; for( int i=0; i<nEntities; i++) { SHPObject * shape = SHPReadObject(shp, i); p_size = shape->nVertices; for( int j=0; j<p_size; j++) { x[nxy] = shape->padfX[j]; y[nxy] = shape->padfY[j]; nxy++; } SHPDestroyObject(shape); } *noutlets=nxy; SHPClose(shp); return 0; } else { fprintf(stderr, "Error opening outlets shapefile %s.\n", outletsfile); fflush(stderr); return 1; } }
void Rshapeinfo(char **shpnm, int *Shapetype, int *Entities, double *MinBound, double *MaxBound) { SHPHandle hSHP; int nShapeType, nEntities, i; double adfMinBound[4], adfMaxBound[4]; /* const char *pszPlus; */ /* -------------------------------------------------------------------- */ /* Open the passed shapefile. */ /* -------------------------------------------------------------------- */ hSHP = SHPOpen( shpnm[0] , "rb" ); if( hSHP == NULL ) { /* REprintf( "Unable to open:%s\n", shpnm[0] ); exit( 1 ); */ error("No such file"); } /* -------------------------------------------------------------------- */ /* Print out the file bounds. */ /* -------------------------------------------------------------------- */ SHPGetInfo( hSHP, &nEntities, &nShapeType, adfMinBound, adfMaxBound ); *Entities = nEntities; *Shapetype = nShapeType; for (i=0;i<4;i++){ MinBound[i]=adfMinBound[i]; MaxBound[i]=adfMaxBound[i]; } /* Rprintf ("Info for %s\n", shpnm[0]); Rprintf("Shapefile Type: %s(%d) # of Shapes: %ld\n\n", SHPTypeName( nShapeType ), nShapeType, nEntities ); Rprintf("File Bounds: (%15.10lg,%15.10lg)\n\t(%15.10lg,%15.10lg)\n", MinBound[0], MinBound[1], MaxBound[0], MaxBound[1] );*/ SHPClose( hSHP ); return; }
/////////////////////////////////////////////////////////////////////////////// // Liefert Objekttyp des Layers OBJECTTYPE CArcViewLayer::GetType() { OBJECTTYPE rgType = OBJECTTYPE_Unknown; #if defined(_DEBUG) int iCnt = 0; int nShapeType = 0; SHPGetInfo (m_hSHP, &iCnt, &nShapeType, NULL, NULL); _ASSERTE(m_nShapeType == nShapeType); #endif // defined(_DEBUG) switch (m_nShapeType) { case SHPT_POINT: case SHPT_POINTM: case SHPT_POINTZ: rgType = OBJECTTYPE_Point; break; case SHPT_MULTIPOINT: case SHPT_MULTIPOINTM: case SHPT_MULTIPOINTZ: break; case SHPT_ARC: case SHPT_ARCM: case SHPT_ARCZ: rgType = OBJECTTYPE_Line; break; case SHPT_POLYGON: case SHPT_POLYGONZ: case SHPT_POLYGONM: rgType = OBJECTTYPE_Area; break; } _ASSERTE(OBJECTTYPE_Unknown != rgType || iCnt == 0); return rgType; }
int isshape(char *inFile) { char *ext = findExt(inFile); if (ext && strcmp_case(ext,".shp")!=0) { return FALSE; } char *dbaseFile, *basename; int isShape = 0; int nEntities, pointType; DBFHandle dbase; SHPHandle shape; dbaseFile = (char *)MALLOC(sizeof(char)*(strlen(inFile)+5)); basename = get_basename(inFile); sprintf(dbaseFile, "%s.dbf", basename); dbase = DBFOpen(dbaseFile, "r+b"); shape = SHPOpen(inFile, "r+b"); if (dbase != NULL && shape != NULL) { SHPGetInfo(shape, &nEntities, &pointType, NULL, NULL); if (nEntities >= 1 && (pointType == SHPT_POLYGON || pointType == SHPT_POINT || pointType == SHPT_ARC || pointType == SHPT_MULTIPOINT ) ) { isShape = 1; } } if (shape) SHPClose(shape); if (dbase) DBFClose(dbase); FREE(basename); FREE(dbaseFile); return isShape; }
/* -------------------------------------------------------------------- */ void printHeader(DBFHandle xDBF, SHPHandle xSHP) { double adfMinBound[4], adfMaxBound[4]; int xEntities; int xShapeType; int nWidth, nDecimals; int i; char szTitle[12]; SHPGetInfo( xSHP, &xEntities, &xShapeType, adfMinBound, adfMaxBound ); printf( "Shapefile Type: %s, %d shapes ", SHPTypeName( xShapeType ), xEntities ); printf( "%d database records\n", DBFGetRecordCount(xDBF) ); if( bVerbose ) { for( i = 0; i < DBFGetFieldCount(xDBF); i++ ) { DBFFieldType eType; const char *pszTypeName; eType = DBFGetFieldInfo( xDBF, i, szTitle, &nWidth, &nDecimals ); if( eType == FTString ) pszTypeName = "String"; else if( eType == FTInteger ) pszTypeName = "Integer"; else if( eType == FTDouble ) pszTypeName = "Double"; else if( eType == FTInvalid ) pszTypeName = "Invalid"; printf( "Field %d: Type=%s, Title=`%s', Width=%d, Decimals=%d\n", i, pszTypeName, szTitle, nWidth, nDecimals ); } } }
int main( int argc, char ** argv ) { SHPHandle hSHP; // SHPHandle cSHP; int nShapeType, nEntities; // int nVertices, nParts, *panParts, i, iPart; double adfBndsMin[4], adfBndsMax[4]; // double *padVertices; // const char *pszPlus; // int cShapeType, cEntities, cVertices, cParts, *cpanParts, ci, cPart; // double *cpadVertices, cadBounds[4]; // const char *cpszPlus; char sType [15]= ""; /* -------------------------------------------------------------------- */ /* Display a usage message. */ /* -------------------------------------------------------------------- */ if( argc != 2 ) { printf( "shpinfo shp_file\n" ); exit( 1 ); } /* -------------------------------------------------------------------- */ /* Open the passed shapefile. */ /* -------------------------------------------------------------------- */ hSHP = SHPOpen( argv[1], "rb" ); if( hSHP == NULL ) { printf( "Unable to open:%s\n", argv[1] ); exit( 1 ); } SHPGetInfo( hSHP, &nEntities, &nShapeType, adfBndsMin, adfBndsMax ); switch ( nShapeType ) { case SHPT_POINT: strcpy(sType,"Point"); break; case SHPT_ARC: strcpy(sType,"Polyline"); break; case SHPT_POLYGON: strcpy(sType,"Polygon"); break; case SHPT_MULTIPOINT: strcpy(sType,"MultiPoint"); break; } /* -------------------------------------------------------------------- */ printf ("Info for %s\n",argv[1]); printf ("%s(%d), %d Records in file\n",sType,nShapeType,nEntities); /* -------------------------------------------------------------------- */ /* Print out the file bounds. */ /* -------------------------------------------------------------------- */ printf( "File Bounds: (%15.10lg,%15.10lg)\n\t(%15.10lg,%15.10lg)\n", adfBndsMin[0], adfBndsMin[1], adfBndsMax[0], adfBndsMax[1] ); SHPClose( hSHP ); return(0); }
SHPCreateTree( SHPHandle hSHP, int nDimension, int nMaxDepth, double *padfBoundsMin, double *padfBoundsMax ) { SHPTree *psTree; if( padfBoundsMin == NULL && hSHP == NULL ) return NULL; /* -------------------------------------------------------------------- */ /* Allocate the tree object */ /* -------------------------------------------------------------------- */ psTree = (SHPTree *) malloc(sizeof(SHPTree)); psTree->hSHP = hSHP; psTree->nMaxDepth = nMaxDepth; psTree->nDimension = nDimension; /* -------------------------------------------------------------------- */ /* If no max depth was defined, try to select a reasonable one */ /* that implies approximately 8 shapes per node. */ /* -------------------------------------------------------------------- */ if( psTree->nMaxDepth == 0 && hSHP != NULL ) { int nMaxNodeCount = 1; int nShapeCount; SHPGetInfo( hSHP, &nShapeCount, NULL, NULL, NULL ); while( nMaxNodeCount*4 < nShapeCount ) { psTree->nMaxDepth += 1; nMaxNodeCount = nMaxNodeCount * 2; } } /* -------------------------------------------------------------------- */ /* Allocate the root node. */ /* -------------------------------------------------------------------- */ psTree->psRoot = SHPTreeNodeCreate( padfBoundsMin, padfBoundsMax ); /* -------------------------------------------------------------------- */ /* Assign the bounds to the root node. If none are passed in, */ /* use the bounds of the provided file otherwise the create */ /* function will have already set the bounds. */ /* -------------------------------------------------------------------- */ if( padfBoundsMin == NULL ) { SHPGetInfo( hSHP, NULL, NULL, psTree->psRoot->adfBoundsMin, psTree->psRoot->adfBoundsMax ); } /* -------------------------------------------------------------------- */ /* If we have a file, insert all it's shapes into the tree. */ /* -------------------------------------------------------------------- */ if( hSHP != NULL ) { int iShape, nShapeCount; SHPGetInfo( hSHP, &nShapeCount, NULL, NULL, NULL ); for( iShape = 0; iShape < nShapeCount; iShape++ ) { SHPObject *psShape; psShape = SHPReadObject( hSHP, iShape ); SHPTreeAddShapeId( psTree, psShape ); SHPDestroyObject( psShape ); } } return psTree; }
countries_v shape_load_countries(const char* filename) { countries_v countries; kv_init(countries); double adfMinBound[4], adfMaxBound[4]; // Read file SHPHandle hSHP = SHPOpen( filename, "rb" ); if(hSHP == NULL) goto end_loading; // Print shape bounds int country_count, shapes_vype; SHPGetInfo( hSHP, &country_count, &shapes_vype, adfMinBound, adfMaxBound ); fprintf(stderr, "Load %d countries\n", country_count); // Iterate through countries for(int i = 0; i < country_count; i++ ) { SHPObject *shp = SHPReadObject(hSHP, i); if(shp == NULL) goto end_loading; if(shp->nParts == 0) continue; // first part starts at point 0 if(shp->panPartStart[0] != 0) goto end_loading; // collect parts of country shapes_v shapes; kv_init(shapes); shapes.min = (point_t){shp->dfXMin, shp->dfYMin}; shapes.max = (point_t){shp->dfXMax, shp->dfYMax}; uint32_t parts = shp->nParts; double k = 0.0; for (uint32_t j=0; j<parts; j++) { // start index uint32_t s = shp->panPartStart[j]; // end index - start of next minus one, or end uint32_t e = (j+1 < parts) ? shp->panPartStart[j+1]: shp->nVertices; shape_v shape; kv_init(shape); // collect points of part for(uint32_t i=s; i<e; i++){ point_t p = (point_t){shp->padfX[i], shp->padfY[i]}; kv_push(point_t, shape, p); // cumulitive average for center if(k>=1.0) { shapes.center.x = (k-1.0)/k*shapes.center.x + p.x/k; shapes.center.y = (k-1.0)/k*shapes.center.y + p.y/k; }else { shapes.center.x = p.x; shapes.center.y = p.y; } k+=1.0; } kv_push(shape_v, shapes, shape); } SHPDestroyObject( shp ); kv_push(shapes_v, countries, shapes); } SHPClose( hSHP ); end_loading: return countries; }
SHPCreateTree( SHPHandle hSHP, int nDimension, int nMaxDepth, double *padfBoundsMin, double *padfBoundsMax ) { SHPTree *psTree; if( padfBoundsMin == NULL && hSHP == NULL ) return NULL; /* -------------------------------------------------------------------- */ /* Allocate the tree object */ /* -------------------------------------------------------------------- */ psTree = (SHPTree *) malloc(sizeof(SHPTree)); if( NULL == psTree ) { return NULL; } psTree->hSHP = hSHP; psTree->nMaxDepth = nMaxDepth; psTree->nDimension = nDimension; psTree->nTotalCount = 0; /* -------------------------------------------------------------------- */ /* If no max depth was defined, try to select a reasonable one */ /* that implies approximately 8 shapes per node. */ /* -------------------------------------------------------------------- */ if( psTree->nMaxDepth == 0 && hSHP != NULL ) { int nMaxNodeCount = 1; int nShapeCount; SHPGetInfo( hSHP, &nShapeCount, NULL, NULL, NULL ); while( nMaxNodeCount*4 < nShapeCount ) { psTree->nMaxDepth += 1; nMaxNodeCount = nMaxNodeCount * 2; } #ifdef USE_CPL CPLDebug( "Shape", "Estimated spatial index tree depth: %d", psTree->nMaxDepth ); #endif /* NOTE: Due to problems with memory allocation for deep trees, * automatically estimated depth is limited up to 12 levels. * See Ticket #1594 for detailed discussion. */ if( psTree->nMaxDepth > MAX_DEFAULT_TREE_DEPTH ) { psTree->nMaxDepth = MAX_DEFAULT_TREE_DEPTH; #ifdef USE_CPL CPLDebug( "Shape", "Falling back to max number of allowed index tree levels (%d).", MAX_DEFAULT_TREE_DEPTH ); #endif } } /* -------------------------------------------------------------------- */ /* Allocate the root node. */ /* -------------------------------------------------------------------- */ psTree->psRoot = SHPTreeNodeCreate( padfBoundsMin, padfBoundsMax ); if( NULL == psTree->psRoot ) { return NULL; } /* -------------------------------------------------------------------- */ /* Assign the bounds to the root node. If none are passed in, */ /* use the bounds of the provided file otherwise the create */ /* function will have already set the bounds. */ /* -------------------------------------------------------------------- */ assert( NULL != psTree ); assert( NULL != psTree->psRoot ); if( padfBoundsMin == NULL ) { SHPGetInfo( hSHP, NULL, NULL, psTree->psRoot->adfBoundsMin, psTree->psRoot->adfBoundsMax ); } /* -------------------------------------------------------------------- */ /* If we have a file, insert all it's shapes into the tree. */ /* -------------------------------------------------------------------- */ if( hSHP != NULL ) { int iShape, nShapeCount; SHPGetInfo( hSHP, &nShapeCount, NULL, NULL, NULL ); for( iShape = 0; iShape < nShapeCount; iShape++ ) { SHPObject *psShape; psShape = SHPReadObject( hSHP, iShape ); if( psShape != NULL ) { SHPTreeAddShapeId( psTree, psShape ); SHPDestroyObject( psShape ); } } } return psTree; }
int main( int argc, char ** argv ) { SHPHandle hSHP; int nShapeType, nEntities, i, iPart, bValidate = 0,nInvalidCount=0; int bHeaderOnly = 0; const char *pszPlus; double adfMinBound[4], adfMaxBound[4]; if( argc > 1 && strcmp(argv[1],"-validate") == 0 ) { bValidate = 1; argv++; argc--; } if( argc > 1 && strcmp(argv[1],"-ho") == 0 ) { bHeaderOnly = 1; argv++; argc--; } /* -------------------------------------------------------------------- */ /* Display a usage message. */ /* -------------------------------------------------------------------- */ if( argc != 2 ) { printf( "shpdump [-validate] [-ho] shp_file\n" ); exit( 1 ); } /* -------------------------------------------------------------------- */ /* Open the passed shapefile. */ /* -------------------------------------------------------------------- */ hSHP = SHPOpen( argv[1], "rb" ); if( hSHP == NULL ) { printf( "Unable to open:%s\n", argv[1] ); exit( 1 ); } /* -------------------------------------------------------------------- */ /* Print out the file bounds. */ /* -------------------------------------------------------------------- */ SHPGetInfo( hSHP, &nEntities, &nShapeType, adfMinBound, adfMaxBound ); printf( "Shapefile Type: %s # of Shapes: %d\n\n", SHPTypeName( nShapeType ), nEntities ); printf( "File Bounds: (%.15g,%.15g,%.15g,%.15g)\n" " to (%.15g,%.15g,%.15g,%.15g)\n", adfMinBound[0], adfMinBound[1], adfMinBound[2], adfMinBound[3], adfMaxBound[0], adfMaxBound[1], adfMaxBound[2], adfMaxBound[3] ); /* -------------------------------------------------------------------- */ /* Skim over the list of shapes, printing all the vertices. */ /* -------------------------------------------------------------------- */ for( i = 0; i < nEntities && !bHeaderOnly; i++ ) { int j; SHPObject *psShape; psShape = SHPReadObject( hSHP, i ); if( psShape == NULL ) { fprintf( stderr, "Unable to read shape %d, terminating object reading.\n", i ); break; } if( psShape->bMeasureIsUsed ) printf( "\nShape:%d (%s) nVertices=%d, nParts=%d\n" " Bounds:(%.15g,%.15g, %.15g, %.15g)\n" " to (%.15g,%.15g, %.15g, %.15g)\n", i, SHPTypeName(psShape->nSHPType), psShape->nVertices, psShape->nParts, psShape->dfXMin, psShape->dfYMin, psShape->dfZMin, psShape->dfMMin, psShape->dfXMax, psShape->dfYMax, psShape->dfZMax, psShape->dfMMax ); else printf( "\nShape:%d (%s) nVertices=%d, nParts=%d\n" " Bounds:(%.15g,%.15g, %.15g)\n" " to (%.15g,%.15g, %.15g)\n", i, SHPTypeName(psShape->nSHPType), psShape->nVertices, psShape->nParts, psShape->dfXMin, psShape->dfYMin, psShape->dfZMin, psShape->dfXMax, psShape->dfYMax, psShape->dfZMax ); if( psShape->nParts > 0 && psShape->panPartStart[0] != 0 ) { fprintf( stderr, "panPartStart[0] = %d, not zero as expected.\n", psShape->panPartStart[0] ); } for( j = 0, iPart = 1; j < psShape->nVertices; j++ ) { const char *pszPartType = ""; if( j == 0 && psShape->nParts > 0 ) pszPartType = SHPPartTypeName( psShape->panPartType[0] ); if( iPart < psShape->nParts && psShape->panPartStart[iPart] == j ) { pszPartType = SHPPartTypeName( psShape->panPartType[iPart] ); iPart++; pszPlus = "+"; } else pszPlus = " "; if( psShape->bMeasureIsUsed ) printf(" %s (%.15g,%.15g, %.15g, %.15g) %s \n", pszPlus, psShape->padfX[j], psShape->padfY[j], psShape->padfZ[j], psShape->padfM[j], pszPartType ); else printf(" %s (%.15g,%.15g, %.15g) %s \n", pszPlus, psShape->padfX[j], psShape->padfY[j], psShape->padfZ[j], pszPartType ); } if( bValidate ) { int nAltered = SHPRewindObject( hSHP, psShape ); if( nAltered > 0 ) { printf( " %d rings wound in the wrong direction.\n", nAltered ); nInvalidCount++; } } SHPDestroyObject( psShape ); } SHPClose( hSHP ); if( bValidate ) { printf( "%d object has invalid ring orderings.\n", nInvalidCount ); } #ifdef USE_DBMALLOC malloc_dump(2); #endif exit( 0 ); }
int main( int argc, char ** argv ) { SHPHandle old_SHP, new_SHP; DBFHandle old_DBF, new_DBF; int nShapeType, nEntities, nVertices, nParts, *panParts, i, iPart; double *padVertices, adBounds[4]; const char *pszPlus; DBFFieldType idfld_type; int idfld, nflds; char kv[257] = ""; char idfldName[120] = ""; char fldName[120] = ""; char shpFileName[120] = ""; char dbfFileName[120] = ""; char *DBFRow = NULL; int Cpan[2] = { 0,0 }; int byRing = 1; PT oCentrd, ringCentrd; SHPObject *psCShape, *cent_pt; double oArea = 0.0, oLen = 0.0; if( argc < 2 ) { printf( "shpdata shp_file \n" ); exit( 1 ); } old_SHP = SHPOpen (argv[1], "rb" ); old_DBF = DBFOpen (argv[1], "rb"); if( old_SHP == NULL || old_DBF == NULL ) { printf( "Unable to open old files:%s\n", argv[1] ); exit( 1 ); } SHPGetInfo( old_SHP, &nEntities, &nShapeType, NULL, NULL ); for( i = 0; i < nEntities; i++ ) { int res ; psCShape = SHPReadObject( old_SHP, i ); if ( byRing == 1 ) { int ring, prevStart, ringDir; double ringArea; prevStart = psCShape->nVertices; for ( ring = (psCShape->nParts - 1); ring >= 0; ring-- ) { SHPObject *psO; int j, numVtx, rStart; rStart = psCShape->panPartStart[ring]; if ( ring == (psCShape->nParts -1) ) { numVtx = psCShape->nVertices - rStart; } else { numVtx = psCShape->panPartStart[ring+1] - rStart; } printf ("(shpdata) Ring(%d) (%d for %d) \n", ring, rStart, numVtx); psO = SHPClone ( psCShape, ring, ring + 1 ); ringDir = SHPRingDir_2d ( psO, 0 ); ringArea = RingArea_2d (psO->nVertices,(double*) psO->padfX, (double*) psO->padfY); RingCentroid_2d ( psO->nVertices, (double*) psO->padfX, (double*) psO->padfY, &ringCentrd, &ringArea); printf ("(shpdata) Ring %d, %f Area %d dir \n", ring, ringArea, ringDir ); SHPDestroyObject ( psO ); printf ("(shpdata) End Ring \n"); } /* (ring) [0,nParts */ } /* by ring */ oArea = SHPArea_2d ( psCShape ); oLen = SHPLength_2d ( psCShape ); oCentrd = SHPCentrd_2d ( psCShape ); printf ("(shpdata) Part (%d) %f Area %f length, C (%f,%f)\n", i, oArea, oLen, oCentrd.x, oCentrd.y ); } SHPClose( old_SHP ); DBFClose( old_DBF ); printf ("\n"); }
int main(){ int entityCount; int shapeType; double padfMinBound[4]; double padfMaxBound[4]; int i; int use_gal = 1; int use_dist = 0; //For josh //char sf_name[] = "/home/joshua/FultonCoData/Fultoncombinednd_10.shp"; //for sumanth //char sf_name[] = "/home/sumanth/Documents/eDemocracy/Files/Fultoncombinednd.shp"; //for alice char sf_name[]= "/home/altheacynara/Documents/saltLakeData/tl_2008_49035_tabblock.shp"; // char sf_name[]="/home/altheacynara/Documents/fultonData/Fultoncombinednd.shp"; //Eventually, this won't be hardcoded SHPHandle handle = SHPOpen(sf_name, "rb"); int fn_len = strlen(sf_name); char svg_filename[fn_len]; char gal_filename[fn_len]; char dst_filename[fn_len]; FILE *svg; strcpy(svg_filename, sf_name); strcpy(gal_filename, sf_name); strcpy(dst_filename, sf_name); svg_filename[fn_len-2] = 'v'; svg_filename[fn_len-1] = 'g'; gal_filename[fn_len-3] = 'G'; gal_filename[fn_len-2] = 'A'; gal_filename[fn_len-1] = 'L'; dst_filename[fn_len-3] = 'd'; dst_filename[fn_len-2] = 's'; dst_filename[fn_len-1] = 't'; //I know, the above isn't really robust enough. //Should be improved upon when the file name is no longer hardcoded SHPGetInfo(handle, &entityCount, &shapeType, padfMinBound, padfMaxBound); SHPObject **shapeList = malloc(entityCount*sizeof(SHPObject *)); //neighborList neighbors[entityCount]; struct neighbor_list *NLIST; double xCentList[entityCount]; double yCentList[entityCount]; double areaList[entityCount]; //populate the shapeList for(i=0; i<entityCount; i++){ shapeList[i] = SHPReadObject(handle,i); } printf("Shapelist populated.\n"); //delete file if it exists remove(svg_filename); //set up the SVG file pointer svg = fopen(svg_filename, "a+"); printf("SVG file opened for writing.\n"); //write header svg_header(svg); printf("SVG header printed.\n"); //Call colorArrange: int ndists=5; int *colorArray = malloc(entityCount*sizeof(int)); colorArrange(colorArray,entityCount,ndists, dst_filename); //write individual polygons for(i=0; i<entityCount; i++){ svg_polygon(*shapeList[i], svg, use_dist, colorArray); } printf("Polygons all printed.\n"); if(use_gal){ FILE *gal; int block, num_neigh, nblocks, temp_neigh; int count=0; gal= fopen(gal_filename, "r"); if(gal==NULL){ printf("Error: Could not open GAL file.\n"); return -1; } fscanf(gal, "%d", &nblocks); if(nblocks==entityCount){ printf("GAL block count matches shapefile block count. Proceeding...\n"); }else{ printf("GAL block count does not match. Exiting...\n"); exit(EXIT_FAILURE); } NLIST = malloc(nblocks * sizeof(struct neighbor_list)); while(fscanf(gal, "%d %d", &block, &num_neigh) != EOF) { NLIST[block].num_neighbors = num_neigh; if(num_neigh != 0) { count=0; NLIST[block].neighbors = malloc(num_neigh * sizeof(int)); while(count < num_neigh) { fscanf(gal, "%d", &temp_neigh); NLIST[block].neighbors[count] = temp_neigh; count++; } } } //Debugging: print the neighbor list of all blocks /*int i,j; for(i=0;i<nblocks;i++) { printf("%d %d\n", i, NLIST[i].num_neighbors); if(NLIST[i].num_neighbors > 0) for(j=0;j<NLIST[i].num_neighbors;j++) printf("%d ", NLIST[i].neighbors[j]); printf("\n"); }*/ //find centroids for every block for(i=0; i<entityCount; i++){ int lastPoint; int status; SHPObject block = *shapeList[i]; //Note that we're going to disregard holes, etc. if(block.nParts>1){ lastPoint = block.panPartStart[1]-1; }else{ lastPoint = block.nVertices-1; } status = polyCentroid(block.padfX, block.padfY, lastPoint, xCentList+i, yCentList+i, areaList+i); } printf("Centroids calculated.\n"); //write paths from centroid to centroid fputs("\t</g>\n", svg); fputs("\t<g\n\t\tid=\"layer2\">\n", svg); for(i=0; i<entityCount; i++){ svg_neighbors(*shapeList[i], NLIST[i], xCentList, yCentList, svg); } //svg_neighbors(*shapeList[20], NLIST[20], xCentList, yCentList, svg); printf("Contiguity paths drawn.\n"); //this is the section that's screwing up //Free NLIST for(i=0; i<entityCount; i++) { printf("i is %d\n", i); printf("NLIST[i]\n"); free(NLIST[i].neighbors); NLIST[i].neighbors = NULL; } free(NLIST); NLIST = NULL; fclose(gal); //end section that's screwing up } //write footer svg_footer(svg); printf("SVG footer printed.\n"); for(i=0; i<entityCount; i++){ SHPDestroyObject(shapeList[i]); } SHPClose(handle); fclose(svg); free(colorArray); return 0; }