static void Test_WriteMultiPoints( int nSHPType, const char *pszFilename ) { SHPHandle hSHPHandle; SHPObject *psShape; double x[4], y[4], z[4], m[4]; int i, iShape; hSHPHandle = SHPCreate( pszFilename, nSHPType ); for( iShape = 0; iShape < 3; iShape++ ) { for( i = 0; i < 4; i++ ) { x[i] = iShape * 10 + i + 1.15; y[i] = iShape * 10 + i + 2.25; z[i] = iShape * 10 + i + 3.35; m[i] = iShape * 10 + i + 4.45; } psShape = SHPCreateObject( nSHPType, -1, 0, NULL, NULL, 4, x, y, z, m ); SHPWriteObject( hSHPHandle, -1, psShape ); SHPDestroyObject( psShape ); } SHPClose( hSHPHandle ); }
bool surfaceVectorField::CreateShape() { char DataBaseID[64]=""; hSHP=SHPCreate(ShapeFileName.c_str(), SHPT_POINT); if(hSHP==NULL) return false; SHPClose( hSHP ); // Create the database. hDBF=DBFCreate(DataBaseName.c_str()); if(hDBF==NULL) return false; //sprintf(DataBaseID, "%s", "Xcoord"); //DBFAddField(hDBF, DataBaseID, FTDouble, 16, 6); //sprintf(DataBaseID, "%s", "Ycoord"); //DBFAddField(hDBF, DataBaseID, FTDouble, 16, 6); sprintf(DataBaseID, "%s", "Windspd"); DBFAddField(hDBF, DataBaseID, FTDouble, 16, 6 ); sprintf(DataBaseID, "%s", "Winddir"); DBFAddField(hDBF, DataBaseID, FTInteger, 8, 0); sprintf(DataBaseID, "%s", "AV_dir"); DBFAddField(hDBF, DataBaseID, FTInteger, 8, 0 ); sprintf(DataBaseID, "%s", "AM_dir"); DBFAddField(hDBF, DataBaseID, FTInteger, 8, 0 ); DBFClose(hDBF); return true; }
static void Test_WritePoints( int nSHPType, const char *pszFilename ) { SHPHandle hSHPHandle; SHPObject *psShape; double x, y, z, m; hSHPHandle = SHPCreate( pszFilename, nSHPType ); x = 1.0; y = 2.0; z = 3.0; m = 4.0; psShape = SHPCreateObject( nSHPType, -1, 0, NULL, NULL, 1, &x, &y, &z, &m ); SHPWriteObject( hSHPHandle, -1, psShape ); SHPDestroyObject( psShape ); x = 10.0; y = 20.0; z = 30.0; m = 40.0; psShape = SHPCreateObject( nSHPType, -1, 0, NULL, NULL, 1, &x, &y, &z, &m ); SHPWriteObject( hSHPHandle, -1, psShape ); SHPDestroyObject( psShape ); SHPClose( hSHPHandle ); }
/** * Vectoriza todos los trazos de una imagen binaria. Los trazos deben estar completamente adelgazados * @param imgBase Imagen binaria CV_8U * @param filename Nombre del archivo de salida (sin extensión) * @param deltaRDP Delta de reducción de puntos Ramen-Douglas-Peucker, entre más grande más agresivo, en 0 no se hace reducción de puntos (valores ejemplo: 0.5, 1, 2...) * @param suavizado Nivel de suavizado con interpolación spline Catmull-Rom, en 0 no se suavizan los trazos (valores ejemplo: 0, 1, 2, 4...) */ void vect::execVectorize(Mat &imgBase, const char *filename, float deltaRDP, short int suavizado) { SHPHandle sh = SHPCreate(filename, SHPT_ARC); int imgAncho = imgBase.cols; int imgAlto = imgBase.rows; // recorremos toda la imagen buscando puntos finales vector<Point> punFinales; vect::puntosFinales(imgBase, punFinales); // para cada punto final, recorremos el trazo correspondiente y guardamos el vector Point pun; vector<Point2f> trazo; vector<Point2f> trazoSuave; for(vector<Point>::iterator it = punFinales.begin(); it != punFinales.end(); ++it) { pun = *it; recorrerTrazo(imgBase, pun, trazo, false); if (trazo.size() > 1) { vec_RDP::reducirPuntos(trazo, deltaRDP); // aplicamos reducción de puntos Ramer-Douglas-Peucker catmull::interpolar(trazo, trazoSuave, suavizado); agregarShape(((suavizado > 0) ? trazoSuave : trazo), imgAlto, sh); } } // Buscamos en toda la imagen, si aún hay pixeles sin borrar, son de trayectos cerrados unsigned int x, y; uchar* fila; uchar intensidad; for (y = 1 ; y < (imgAlto - 1) ; ++y) { fila = imgBase.ptr<uchar>(y); for (x = 1 ; x < (imgAncho - 1) ; ++x) { intensidad = fila[x]; if (intensidad == 0) { pun = Point(x, y); recorrerTrazo(imgBase, pun, trazo, true); if (trazo.size() > 1) { vec_RDP::reducirPuntos(trazo, deltaRDP); // aplicamos reducción de puntos Ramer-Douglas-Peucker catmull::interpolar(trazo, trazoSuave, suavizado); agregarShape(((suavizado > 0) ? trazoSuave : trazo), imgAlto, sh); } } } } SHPClose(sh); }
// --------------------------------------------------------------------------- // 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; }
int main( int argc, char ** argv ) { SHPHandle hSHP; int nShapeType; /* -------------------------------------------------------------------- */ /* Display a usage message. */ /* -------------------------------------------------------------------- */ if( argc != 3 ) { printf( "shpcreate shp_file [point/arc/polygon/multipoint]\n" ); exit( 1 ); } /* -------------------------------------------------------------------- */ /* Figure out the shape type. */ /* -------------------------------------------------------------------- */ if( strcmp(argv[2],"POINT") == 0 || strcmp(argv[2],"point") == 0 ) nShapeType = SHPT_POINT; else if( strcmp(argv[2],"ARC") == 0 || strcmp(argv[2],"arc") == 0 ) nShapeType = SHPT_ARC; else if( strcmp(argv[2],"POLYGON") == 0 || strcmp(argv[2],"polygon") == 0 ) nShapeType = SHPT_POLYGON; else if( strcmp(argv[2],"MULTIPOINT")==0 ||strcmp(argv[2],"multipoint")==0) nShapeType = SHPT_MULTIPOINT; else { printf( "Shape Type `%s' not recognised.\n", argv[2] ); exit( 2 ); } /* -------------------------------------------------------------------- */ /* Create the requested layer. */ /* -------------------------------------------------------------------- */ hSHP = SHPCreate( argv[1], nShapeType ); if( hSHP == NULL ) { printf( "Unable to create:%s\n", argv[1] ); exit( 3 ); } SHPClose( hSHP ); return 0; }
jboolean Java_org_maptools_shapelib_android_util_TestUtils_createShapefile(JNIEnv * env, jclass clazz, jstring file, jobject listObject) { // create a shapefile and dbf (e.g. /sdcard/foo/bar) const char *fileStr = (*env)->GetStringUTFChars(env, file, 0); SHPHandle hSHP = SHPCreate(fileStr, SHPT_POINT); DBFHandle hDBF = DBFCreate(fileStr); // define the shapefile attributes DBFAddField(hDBF, "name", FTString, 25, 0); DBFAddField(hDBF, "height", FTDouble, 8, 8); DBFAddField(hDBF, "apples", FTInteger, 1, 0); process(env, hSHP, hDBF, file, listObject); SHPClose(hSHP); DBFClose(hDBF); }
static int shapelib_create(lua_State *ls) { const char *filename = luaL_checkstring(ls, 1); int type = (int)luaL_checknumber(ls, 2); SHPHandle shp = SHPCreate(filename, type); if (shp) { SHPHandle *shp_ptr = lua_newuserdata(ls, sizeof(SHPHandle *)); *shp_ptr = shp; luaL_getmetatable(ls, "shapelib.shphandle"); lua_setmetatable(ls, -2); return 1; } return luaL_error(ls, "could not create shapefile: %s", filename); }
/** * Open and initialize all files belonging to shapefile (.shp/shx/dbf/prj/cpg). * Uses m_filename_base and m_sequence_number plus suffix to build filename. */ void open() { std::ostringstream filename; filename << m_filename_base; if (m_sequence_number) { filename << "_" << m_sequence_number; } m_shp_handle = SHPCreate(filename.str().c_str(), m_type); if (m_shp_handle == 0) { throw std::runtime_error("Can't open shapefile: " + filename.str() + ".shp/shx"); } m_dbf_handle = DBFCreate(filename.str().c_str()); if (m_dbf_handle == 0) { throw std::runtime_error("Can't open shapefile: " + filename.str() + ".dbf"); } std::ofstream file; file.open((filename.str() + ".prj").c_str()); if (file.fail()) { throw std::runtime_error("Can't open shapefile: " + filename.str() + ".prj"); } file << "GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]]" << std::endl; file.close(); file.open((filename.str() + ".cpg").c_str()); if (file.fail()) { throw std::runtime_error("Can't open shapefile: " + filename.str() + ".cpg"); } file << "UTF-8" << std::endl; file.close(); // If any fields are defined already, add them here. This will do nothing if // called from the constructor. for (std::vector<Field>::const_iterator it = m_fields.begin(); it != m_fields.end(); ++it) { DBFAddField(m_dbf_handle, it->name().c_str(), it->type(), it->width(), it->decimals()); } }
char* darxen_shapefiles_filter_shp(DarxenShapefile* shapefile, int dataLevel, const char* site, float latCenter, float lonCenter, float radius) { GSList* lstNewDBFs = NULL; GSList* lstNewSHPs = NULL; DBFHandle hDBF; SHPHandle hSHP; SHPHandle hNewSHP = NULL; DBFHandle hNewDBF = NULL; int pnEntities; int pnShapeType; int i; SHPObject *psObject = NULL; char* filteredPath; g_assert(shapefile->file); g_assert(!shapefile->dataLevels || shapefile->dataLevels->field); g_assert(!shapefile->dataLevels || (dataLevel >= 0 && dataLevel < g_slist_length(shapefile->dataLevels->levels))); gchar* gfilteredFile; if (shapefile->dataLevels) gfilteredFile = g_strdup_printf("%s_%s_%i", shapefile->file, site, dataLevel); else gfilteredFile = g_strdup_printf("%s_%s", shapefile->file, site); gchar* gfilteredPath = g_build_filename(darxen_file_support_get_app_path(), "shapefiles", "cache", gfilteredFile, NULL); filteredPath = strdup(gfilteredPath); g_free(gfilteredFile); g_free(gfilteredPath); //don't recreate the file, just return the path gchar* shpFile = g_strdup_printf("%s.shp", filteredPath); gchar* dbfFile = g_strdup_printf("%s.dbf", filteredPath); if (g_file_test(shpFile, G_FILE_TEST_EXISTS) && g_file_test(dbfFile, G_FILE_TEST_EXISTS)) { g_free(shpFile); g_free(dbfFile); return filteredPath; } g_free(shpFile); g_free(dbfFile); gchar* pathPart = g_strdup_printf("%s.shp", shapefile->file); gchar* pathPart2 = g_build_filename("shapefiles", pathPart, NULL); gchar* shapefilePath = darxen_file_support_get_overridable_file_path(pathPart2); //g_build_filename(darxen_file_support_get_app_path(), "shapefiles", shapefile->file, NULL); g_free(pathPart); g_free(pathPart2); g_assert(shapefilePath); shapefilePath[strlen(shapefilePath)-4] = '\0'; hSHP = SHPOpen(shapefilePath, "rb"); if (!hSHP) { g_free(shapefilePath); g_critical("Invalid shapefile path: %s", shapefile->file); return NULL; } hDBF = DBFOpen(shapefilePath, "rb"); if (!hDBF) { g_free(shapefilePath); g_critical("Invalid shapefile dbf path: %s", shapefile->file); return NULL; } g_free(shapefilePath); int dbfCount = DBFGetRecordCount(hDBF); SHPGetInfo(hSHP, &pnEntities, &pnShapeType, NULL, NULL); if (dbfCount != pnEntities) { g_critical("dbf and shp have a differing number of records!"); SHPClose(hSHP); DBFClose(hDBF); return NULL; } if (shapefile->dataLevels) { GSList* pLevel = shapefile->dataLevels->levels; i = 0; while (pLevel) { gfilteredFile = g_strdup_printf("%s_%s_%i", shapefile->file, site, i); gfilteredPath = g_build_filename(darxen_file_support_get_app_path(), "shapefiles", "cache", gfilteredFile, NULL); hNewDBF = DBFCreate(gfilteredPath); hNewSHP = SHPCreate(gfilteredPath, pnShapeType); if (!hNewDBF || !hNewSHP || !create_required_fields(shapefile, hDBF, hNewDBF)) { SHPClose(hSHP); DBFClose(hDBF); if (hNewDBF) DBFClose(hNewDBF); if (hNewSHP) SHPClose(hNewSHP); GSList* plstNewDBFs = lstNewDBFs; while (plstNewDBFs) { DBFClose((DBFHandle)plstNewDBFs->data); plstNewDBFs = plstNewDBFs->next; } g_slist_free(lstNewDBFs); GSList* plstNewSHPs = lstNewSHPs; while (plstNewSHPs) { SHPClose((SHPHandle)plstNewSHPs->data); plstNewSHPs = plstNewSHPs->next; } g_slist_free(lstNewSHPs); g_critical("Unable to create filtered shapefile lists: (level %i)", i); return NULL; } lstNewDBFs = g_slist_append(lstNewDBFs, hNewDBF); lstNewSHPs = g_slist_append(lstNewSHPs, hNewSHP); g_free(gfilteredPath); g_free(gfilteredFile); i++; pLevel = pLevel->next; } hNewDBF = NULL; hNewSHP = NULL; } else { hNewSHP = SHPCreate(filteredPath, pnShapeType); if (!hNewSHP) { SHPClose(hSHP); DBFClose(hDBF); g_critical("Unable to create filtered shapefile: %s", filteredPath); return NULL; } hNewDBF = DBFCreate(filteredPath); if (!hNewDBF || !create_required_fields(shapefile, hDBF, hNewDBF)) { SHPClose(hSHP); DBFClose(hDBF); SHPClose(hNewSHP); g_critical("Unable to create filtered dbf shapefile: %s", filteredPath); return NULL; } } float filterRegionX1 = lonCenter - radius; float filterRegionX2 = lonCenter + radius; float filterRegionY1 = latCenter - radius; float filterRegionY2 = latCenter + radius; for (i = 0; i < pnEntities; i++) { psObject = SHPReadObject(hSHP, i); if (((filterRegionX1 >= psObject->dfXMin && filterRegionX1 <= psObject->dfXMax) || (filterRegionX2 >= psObject->dfXMin && filterRegionX2 <= psObject->dfXMax) || (psObject->dfXMin >= filterRegionX1 && psObject->dfXMin <= filterRegionX2) || (psObject->dfXMax >= filterRegionX1 && psObject->dfXMax <= filterRegionX2)) && ((filterRegionY1 >= psObject->dfYMin && filterRegionY1 <= psObject->dfYMax) || (filterRegionY2 >= psObject->dfYMin && filterRegionY2 <= psObject->dfYMax) || (psObject->dfYMin >= filterRegionY1 && psObject->dfYMin <= filterRegionY2) || (psObject->dfYMax >= filterRegionY1 && psObject->dfYMax <= filterRegionY2))) { psObject->nShapeId = -1; if (shapefile->dataLevels) { int fieldIndex = DBFGetFieldIndex(hDBF, shapefile->dataLevels->field); GSList* pDataLevels = shapefile->dataLevels->levels; GSList* pLstNewSHPs = lstNewSHPs; GSList* pLstNewDBFs = lstNewDBFs; while (pDataLevels) { DarxenShapefileDataLevel* level = (DarxenShapefileDataLevel*)pDataLevels->data; hNewSHP = (SHPHandle)pLstNewSHPs->data; hNewDBF = (DBFHandle)pLstNewDBFs->data; double value = DBFReadDoubleAttribute(hDBF, i, fieldIndex); gboolean cond; switch (shapefile->dataLevels->comparisonType) { case DATALEVELS_COMPARISON_TYPE_MIN: cond = (level->value < value); break; case DATALEVELS_COMPARISON_TYPE_MAX: cond = (level->value > value); break; default: g_warning("Invalid comparison type: %i", shapefile->dataLevels->comparisonType); cond = TRUE; } if (cond) { int index = SHPWriteObject(hNewSHP, -1, psObject); write_fields(shapefile, i, index, hDBF, hNewDBF); break; } pDataLevels = pDataLevels->next; pLstNewDBFs = pLstNewDBFs->next; pLstNewSHPs = pLstNewSHPs->next; } hNewDBF = NULL; hNewSHP = NULL; } else { int index = SHPWriteObject(hNewSHP, -1, psObject); write_fields(shapefile, i, index, hDBF, hNewDBF); } } SHPDestroyObject(psObject); } SHPClose(hSHP); DBFClose(hDBF); if (hNewDBF) DBFClose(hNewDBF); if (hNewSHP) SHPClose(hNewSHP); GSList* plstNewDBFs = lstNewDBFs; while (plstNewDBFs) { DBFClose((DBFHandle)plstNewDBFs->data); plstNewDBFs = plstNewDBFs->next; } g_slist_free(lstNewDBFs); GSList* plstNewSHPs = lstNewSHPs; while (plstNewSHPs) { SHPClose((SHPHandle)plstNewSHPs->data); plstNewSHPs = plstNewSHPs->next; } g_slist_free(lstNewSHPs); // g_assert(g_file_test(filteredPath, G_FILE_TEST_EXISTS)); return filteredPath; }
void init_baseline_shape(char *inFile, int sensor_count) { char *dbaseFile; DBFHandle dbase; SHPHandle shape; // Open database for initialization dbaseFile = (char *) MALLOC(sizeof(char)*(strlen(inFile)+5)); sprintf(dbaseFile, "%s.dbf", inFile); dbase = DBFCreate(dbaseFile); if (!dbase) asfPrintError("Could not create database file '%s'\n", dbaseFile); // Add fields to database if (sensor_count == 1) { if (DBFAddField(dbase, "Sensor", FTString, 15, 0) == -1) asfPrintError("Could not add sensor field to database file\n"); } else { if (DBFAddField(dbase, "Master_sensor", FTString, 15, 0) == -1) asfPrintError("Could not add sensor field to database file\n"); if (DBFAddField(dbase, "Slave_sensor", FTString, 15, 0) == -1) asfPrintError("Could not add sensor field to database file\n"); } if (DBFAddField(dbase, "Beam_mode", FTString, 5, 0) == -1) asfPrintError("Could not add beam mode to database file\n"); if (DBFAddField(dbase, "Frame", FTInteger, 4, 0) == -1) asfPrintError("Could not add frame field to database file\n"); if (DBFAddField(dbase, "Direction", FTString, 15, 0) == -1) asfPrintError("Could not add orbit direction field to database file\n"); if (DBFAddField(dbase, "Master", FTInteger, 5, 0) == -1) asfPrintError("Could not add master field to database file\n"); if (DBFAddField(dbase, "Master_date", FTString, 20, 0) == -1) asfPrintError("Could not add master acquisition date field" " to database file\n"); if (DBFAddField(dbase, "Slave", FTInteger, 5, 0) == -1) asfPrintError("Could not add slave field to database file\n"); if (DBFAddField(dbase, "Slave_date", FTString, 20, 0) == -1) asfPrintError("Could not add slave acquisition date field" " to database file\n"); if (DBFAddField(dbase, "B_par", FTInteger, 5, 0) == -1) asfPrintError("Could not add parallel baseline field to database file\n"); if (DBFAddField(dbase, "B_perp", FTInteger, 5, 0) == -1) asfPrintError("Could not add perpendicular baseline field" " to database file\n"); if (DBFAddField(dbase, "B_temp", FTInteger, 5, 0) == -1) asfPrintError("Could not add temporal baseline field to database file\n"); if (DBFAddField(dbase, "Center_Lat", FTDouble, 9, 4) == -1) asfPrintError("Could not add center latitude field to database file\n"); if (DBFAddField(dbase, "Center_Lon", FTDouble, 9, 4) == -1) asfPrintError("Could not add center longitude field to database file\n"); if (DBFAddField(dbase, "Lat1", FTDouble, 9, 4) == -1) asfPrintError("Could not add latitude field to database file\n"); if (DBFAddField(dbase, "Lon1", FTDouble, 9, 4) == -1) asfPrintError("Could not add longitude field to database file\n"); if (DBFAddField(dbase, "Lat2", FTDouble, 9, 4) == -1) asfPrintError("Could not add latitude field to database file\n"); if (DBFAddField(dbase, "Lon2", FTDouble, 9, 4) == -1) asfPrintError("Could not add longitude field to database file\n"); if (DBFAddField(dbase, "Lat3", FTDouble, 9, 4) == -1) asfPrintError("Could not add latitude field to database file\n"); if (DBFAddField(dbase, "Lon3", FTDouble, 9, 4) == -1) asfPrintError("Could not add longitude field to database file\n"); if (DBFAddField(dbase, "Lat4", FTDouble, 9, 4) == -1) asfPrintError("Could not add latitude field to database file\n"); if (DBFAddField(dbase, "Lon4", FTDouble, 9, 4) == -1) asfPrintError("Could not add longitude field to database file\n"); // Close the database for initialization DBFClose(dbase); // Open shapefile for initialization shape = SHPCreate(inFile, SHPT_POLYGON); if (!shape) asfPrintError("Could not create shapefile '%s'\n", inFile); // Close shapefile for initialization SHPClose(shape); FREE(dbaseFile); return; }
int main( int argc, char ** argv ) { SHPHandle old_SHP, new_SHP; DBFHandle old_DBF, new_DBF; int nShapeType, nEntities, nVertices, nParts, *panParts, i, iPart, j; double *padVertices, adBounds[4]; const char *pszPlus; DBFFieldType idfld_type; SHPObject *psCShape; FILE *ifp = NULL; int idfld, nflds; char kv[257] = ""; char idfldName[120] = ""; char fldName[120] = ""; char shpFileName[120] = ""; char dbfFileName[120] = ""; char prjFileName[120] = ""; char parg[1024]; double apeture[4]; int inarg, outarg; char *DBFRow = NULL; /* for testing only char *in_args[] = { "init=nad83:1002", "units=us-ft" }; char *out_args[] = { "proj=utm", "zone=16", "units=m" }; */ char *in_args[16]; char *out_args[16]; int in_argc = 0 , out_argc = 0, outf_arg; char *arglst; projPJ orig_prj, new_prj; va_list myargs, moargs; if( argc < 4) { printf( "shpproj shp_file new_shp ( -i=in_proj_file | -i=\"in_params\" | -i=geographic ) ( -o=out_info_file | -o=\"out_params\" | -o=geographic ) \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 ); } outf_arg = 2; inarg = 0; outarg = 0; for ( i = 3; i < argc; i++ ) { if ( !strncmp ("-i=", argv[i], 3 )) inarg = i; if ( !strncmp ("-o=", argv[i], 3 )) outarg = i; } /* if shapefile has a prj component then use that else try for a file then read args as list */ if( inarg == 0 ) { strcpy( prjFileName, argv[1] ); ifp = fopen( asFileName ( prjFileName, "prj" ),"rt"); } else { ifp = fopen( asFileName ( argv[inarg] + 3, "prj" ),"rt"); } i = 0; if ( ifp ) { if( inarg == 0 ) printf ("using default file proj params from <- %s\n", asFileName ( prjFileName, "prj" ) ); else printf ("using file proj params from <- %s\n", asFileName ( argv[inarg] + 3, "prj" ) ); while( fscanf( ifp, "%s", parg) != EOF ) { in_args[i] = malloc ( strlen(parg)+1 ); strcpy ( in_args[i], parg); i++; } in_argc = i; fclose (ifp); } else { if ( inarg > 0 ) { arglst = argv[inarg] + 3; j = 0; i = 0; while ( j < strlen (arglst) ) { in_argc += sscanf ( arglst + j, "%s", parg); in_args[i] = malloc( strlen (parg)+1024); strcpy (in_args[i], parg); i++; j += strlen (parg) +1; if ( arglst[j] + 1 == 0 ) j = strlen (argv[inarg]); } } } i = 0; if ( outarg > 0 ) ifp = fopen( asFileName ( argv[outarg] + 3, "prj" ),"rt"); if ( ifp ) { while( fscanf( ifp, "%s", parg) != EOF ) { out_args[i] = malloc ( strlen(parg)); strcpy ( out_args[i], parg); i++; } out_argc = i; fclose (ifp); } else { if ( outarg > 0 ) { arglst = argv[outarg] + 3; j = 0; i = 0; while ( j < strlen (arglst) ) { out_argc += sscanf ( arglst + j, "%s", parg); out_args[i] = malloc( strlen (parg)+1); strcpy (out_args[i], parg); i++; j += strlen (parg) +1; if ( arglst[j] + 1 == 0 ) j = strlen (argv[outarg]); } } } if ( !strcmp( argv[inarg], "-i=geographic" )) in_argc = 0; if ( !strcmp( argv[outarg], "-o=geographic" )) out_argc = 0; orig_prj = SHPSetProjection ( in_argc, in_args ); new_prj = SHPSetProjection ( out_argc, out_args ); if ( !(( (!in_argc) || orig_prj) && ( (!out_argc) || new_prj) )) { fprintf (stderr, "unable to process projection, exiting...\n"); exit(1); } SHPGetInfo( old_SHP, &nEntities, &nShapeType, NULL, NULL); new_SHP = SHPCreate ( argv[outf_arg], nShapeType ); new_DBF = DBFCloneEmpty (old_DBF, argv[outf_arg]); if( new_SHP == NULL || new_DBF == NULL ) { printf( "Unable to create new files:%s\n", argv[outf_arg] ); exit( 1 ); } DBFRow = (char *) malloc ( (old_DBF->nRecordLength) + 15 ); for( i = 0; i < nEntities; i++ ) { int j; psCShape = SHPReadObject ( old_SHP, i ); SHPProject (psCShape, orig_prj, new_prj ); SHPWriteObject ( new_SHP, -1, psCShape ); SHPDestroyObject ( psCShape ); memcpy ( DBFRow, DBFReadTuple ( old_DBF, i ), old_DBF->nRecordLength ); DBFWriteTuple ( new_DBF, new_DBF->nRecords, DBFRow ); } SHPFreeProjection ( orig_prj ); SHPFreeProjection ( new_prj ); /* store projection params into prj file */ ifp = fopen( asFileName ( argv[outf_arg], "prj" ),"wt"); if ( ifp ) { if ( out_argc == 0 ) { fprintf( ifp, "proj=geographic\n" ); } else { for ( i = 0; i < out_argc; i++ ) fprintf( ifp, "%s\n", out_args[i]); } fclose (ifp); } SHPClose( old_SHP ); SHPClose( new_SHP ); DBFClose( old_DBF ); DBFClose( new_DBF ); printf ("\n"); }
} panSuccess[i] = TRUE; } } /* -------------------------------------------------------------------- */ /* geox/geoy to pixel/line using search algorithm. */ /* -------------------------------------------------------------------- */ #ifdef notdef else { int i; int nStartX = -1, nStartY = -1; #ifdef SHAPE_DEBUG hSHP = SHPCreate( "tracks.shp", SHPT_ARC ); hDBF = DBFCreate( "tracks.dbf" ); DBFAddField( hDBF, "GEOX", FTDouble, 10, 4 ); DBFAddField( hDBF, "GEOY", FTDouble, 10, 4 ); #endif for( i = 0; i < nPointCount; i++ ) { double dfGeoLocX, dfGeoLocY; if( padfX[i] == HUGE_VAL || padfY[i] == HUGE_VAL ) { panSuccess[i] = FALSE; continue; } if( !FindGeoLocPosition( psTransform, padfX[i], padfY[i],
/** * Vectoriza todos los trazos de una imagen binaria. Los trazos deben estar completamente adelgazados * @param imgBase Imagen binaria CV_8U * @param filename Nombre del archivo de salida (sin extensión) * @param deltaRDP Delta de reducción de puntos Ramen-Douglas-Peucker, entre más grande más agresivo, en 0 no se hace reducción de puntos (valores ejemplo: 0.5, 1, 2...) * @param suavizado Nivel de suavizado con interpolación spline Catmull-Rom, en 0 no se suavizan los trazos (valores ejemplo: 0, 1, 2, 4...) */ void vect::execVectorize(Mat &imgBase, const char *filename, float deltaRDP, short int suavizado, InfoMapa *iMapa) { SHPHandle sh = SHPCreate(filename, SHPT_ARC); DBFHandle dbf = DBFCreate(filename); int res = DBFAddField(dbf,"T_ALT", FTDouble, 12, 4); DBFClose(dbf); DBFHandle hDBF = DBFOpen(filename,"rb+"); cout<<res<<",,,,,,,,,,,,,,,,,,,,,,,"<<endl; int imgAncho = imgBase.cols; int imgAlto = imgBase.rows; Point pA = Point(iMapa->recXmin,iMapa->recYmin); cout<<"XMIN"<<iMapa->recXmin<<endl; cout<<"YMIN"<<iMapa->recYmin<<endl; /* Point pA = Point(492, 372); iMapa->setCoordsPuntosRef(1060000, 770000, 1075000, 770000, 1075000, 760000, 1060000, 760000); iMapa->setPosPuntosRef(522, 371,9957, 475, 9882, 6799, 453, 6701); */ transformGeo *objGeo = new transformGeo(); objGeo->setCoeficients(iMapa); // recorremos toda la imagen buscando puntos finales int altop = 0; vector<Point> punFinales; vect::puntosFinales(imgBase, punFinales); // para cada punto final, recorremos el trazo correspondiente y guardamos el vector Point pun; vector<Point2f> trazo; vector<Point2f> trazoSuave; for(vector<Point>::iterator it = punFinales.begin(); it != punFinales.end(); ++it) { pun = *it; cout << "recorrerTrazo() " << pun << endl; recorrerTrazo(imgBase, pun, trazo, false); if (trazo.size() > 1) { vec_RDP::reducirPuntos(trazo, deltaRDP); // aplicamos reducción de puntos Ramer-Douglas-Peucker catmull::interpolar(trazo, trazoSuave, suavizado); agregarShape(((suavizado > 0) ? trazoSuave : trazo), altop, sh, objGeo, pA, hDBF); } } // Buscamos en toda la imagen, si aún hay pixeles sin borrar, son de trayectos cerrados unsigned int x, y; uchar* fila; uchar intensidad; for (y = 1 ; y < (imgAlto - 1) ; ++y) { fila = imgBase.ptr<uchar>(y); for (x = 1 ; x < (imgAncho - 1) ; ++x) { intensidad = fila[x]; if (intensidad == 0) { pun = Point(x, y); recorrerTrazo(imgBase, pun, trazo, true); if (trazo.size() > 1) { vec_RDP::reducirPuntos(trazo, deltaRDP); // aplicamos reducción de puntos Ramer-Douglas-Peucker catmull::interpolar(trazo, trazoSuave, suavizado); agregarShape(((suavizado > 0) ? trazoSuave : trazo), imgAlto, sh, objGeo, pA, hDBF); } } } } DBFClose(hDBF); SHPClose(sh); }
OGRLayer * OGRShapeDataSource::CreateLayer( const char * pszLayerName, OGRSpatialReference *poSRS, OGRwkbGeometryType eType, char ** papszOptions ) { SHPHandle hSHP; DBFHandle hDBF; int nShapeType; /* -------------------------------------------------------------------- */ /* Verify we are in update mode. */ /* -------------------------------------------------------------------- */ if( !bDSUpdate ) { CPLError( CE_Failure, CPLE_NoWriteAccess, "Data source %s opened read-only.\n" "New layer %s cannot be created.\n", pszName, pszLayerName ); return NULL; } /* -------------------------------------------------------------------- */ /* Figure out what type of layer we need. */ /* -------------------------------------------------------------------- */ if( eType == wkbUnknown || eType == wkbLineString ) nShapeType = SHPT_ARC; else if( eType == wkbPoint ) nShapeType = SHPT_POINT; else if( eType == wkbPolygon ) nShapeType = SHPT_POLYGON; else if( eType == wkbMultiPoint ) nShapeType = SHPT_MULTIPOINT; else if( eType == wkbPoint25D ) nShapeType = SHPT_POINTZ; else if( eType == wkbLineString25D ) nShapeType = SHPT_ARCZ; else if( eType == wkbMultiLineString ) nShapeType = SHPT_ARC; else if( eType == wkbMultiLineString25D ) nShapeType = SHPT_ARCZ; else if( eType == wkbPolygon25D ) nShapeType = SHPT_POLYGONZ; else if( eType == wkbMultiPolygon ) nShapeType = SHPT_POLYGON; else if( eType == wkbMultiPolygon25D ) nShapeType = SHPT_POLYGONZ; else if( eType == wkbMultiPoint25D ) nShapeType = SHPT_MULTIPOINTZ; else if( eType == wkbNone ) nShapeType = SHPT_NULL; else nShapeType = -1; /* -------------------------------------------------------------------- */ /* Has the application overridden this with a special creation */ /* option? */ /* -------------------------------------------------------------------- */ const char *pszOverride = CSLFetchNameValue( papszOptions, "SHPT" ); if( pszOverride == NULL ) /* ignore */; else if( EQUAL(pszOverride,"POINT") ) { nShapeType = SHPT_POINT; eType = wkbPoint; } else if( EQUAL(pszOverride,"ARC") ) { nShapeType = SHPT_ARC; eType = wkbLineString; } else if( EQUAL(pszOverride,"POLYGON") ) { nShapeType = SHPT_POLYGON; eType = wkbPolygon; } else if( EQUAL(pszOverride,"MULTIPOINT") ) { nShapeType = SHPT_MULTIPOINT; eType = wkbMultiPoint; } else if( EQUAL(pszOverride,"POINTZ") ) { nShapeType = SHPT_POINTZ; eType = wkbPoint25D; } else if( EQUAL(pszOverride,"ARCZ") ) { nShapeType = SHPT_ARCZ; eType = wkbLineString25D; } else if( EQUAL(pszOverride,"POLYGONZ") ) { nShapeType = SHPT_POLYGONZ; eType = wkbPolygon25D; } else if( EQUAL(pszOverride,"MULTIPOINTZ") ) { nShapeType = SHPT_MULTIPOINTZ; eType = wkbMultiPoint25D; } else if( EQUAL(pszOverride,"NONE") ) { nShapeType = SHPT_NULL; } else { CPLError( CE_Failure, CPLE_NotSupported, "Unknown SHPT value of `%s' passed to Shapefile layer\n" "creation. Creation aborted.\n", pszOverride ); return NULL; } if( nShapeType == -1 ) { CPLError( CE_Failure, CPLE_NotSupported, "Geometry type of `%s' not supported in shapefiles.\n" "Type can be overridden with a layer creation option\n" "of SHPT=POINT/ARC/POLYGON/MULTIPOINT/POINTZ/ARCZ/POLYGONZ/MULTIPOINTZ.\n", OGRGeometryTypeToName(eType) ); return NULL; } /* -------------------------------------------------------------------- */ /* What filename do we use, excluding the extension? */ /* -------------------------------------------------------------------- */ char *pszBasename; if( bSingleNewFile && nLayers == 0 ) { char *pszPath = CPLStrdup(CPLGetPath(pszName)); char *pszFBasename = CPLStrdup(CPLGetBasename(pszName)); pszBasename = CPLStrdup(CPLFormFilename(pszPath, pszFBasename, NULL)); CPLFree( pszFBasename ); CPLFree( pszPath ); } else if( bSingleNewFile ) { char *pszPath = CPLStrdup(CPLGetPath(pszName)); pszBasename = CPLStrdup(CPLFormFilename(pszPath,pszLayerName,NULL)); CPLFree( pszPath ); } else pszBasename = CPLStrdup(CPLFormFilename(pszName,pszLayerName,NULL)); /* -------------------------------------------------------------------- */ /* Create the shapefile. */ /* -------------------------------------------------------------------- */ char *pszFilename; if( nShapeType != SHPT_NULL ) { pszFilename = CPLStrdup(CPLFormFilename( NULL, pszBasename, "shp" )); hSHP = SHPCreate( pszFilename, nShapeType ); if( hSHP == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Failed to open Shapefile `%s'.\n", pszFilename ); CPLFree( pszFilename ); CPLFree( pszBasename ); return NULL; } CPLFree( pszFilename ); } else hSHP = NULL; /* -------------------------------------------------------------------- */ /* Create a DBF file. */ /* -------------------------------------------------------------------- */ pszFilename = CPLStrdup(CPLFormFilename( NULL, pszBasename, "dbf" )); hDBF = DBFCreate( pszFilename ); if( hDBF == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Failed to open Shape DBF file `%s'.\n", pszFilename ); CPLFree( pszFilename ); CPLFree( pszBasename ); return NULL; } CPLFree( pszFilename ); /* -------------------------------------------------------------------- */ /* Create the .prj file, if required. */ /* -------------------------------------------------------------------- */ if( poSRS != NULL ) { char *pszWKT = NULL; CPLString osPrjFile = CPLFormFilename( NULL, pszBasename, "prj"); FILE *fp; /* the shape layer needs it's own copy */ poSRS = poSRS->Clone(); poSRS->morphToESRI(); if( poSRS->exportToWkt( &pszWKT ) == OGRERR_NONE && (fp = VSIFOpen( osPrjFile, "wt" )) != NULL ) { VSIFWrite( pszWKT, strlen(pszWKT), 1, fp ); VSIFClose( fp ); } CPLFree( pszWKT ); poSRS->morphFromESRI(); } /* -------------------------------------------------------------------- */ /* Create the layer object. */ /* -------------------------------------------------------------------- */ OGRShapeLayer *poLayer; poLayer = new OGRShapeLayer( pszBasename, hSHP, hDBF, poSRS, TRUE, eType ); poLayer->InitializeIndexSupport( pszBasename ); CPLFree( pszBasename ); /* -------------------------------------------------------------------- */ /* Add layer to data source layer list. */ /* -------------------------------------------------------------------- */ papoLayers = (OGRShapeLayer **) CPLRealloc( papoLayers, sizeof(OGRShapeLayer *) * (nLayers+1) ); papoLayers[nLayers++] = poLayer; return poLayer; }
bool TeExportQuerierToShapefile(TeQuerier* querier, const std::string& base) { // check initial conditions if (!querier) return false; if (!querier->loadInstances()) return false; // Get the list of attributes defined by the input querier bool onlyObjId = false; TeAttributeList qAttList = querier->getAttrList(); if (qAttList.empty()) { TeAttributeList qAttList; TeAttribute at; at.rep_.type_ = TeSTRING; at.rep_.numChar_ = 100; at.rep_.name_ = "ID"; at.rep_.isPrimaryKey_ = true; qAttList.push_back(at); onlyObjId = true; } // Handles to each type of geometries that will be created if necessary DBFHandle hDBFPol = 0; SHPHandle hSHPPol = 0; DBFHandle hDBFLin = 0; SHPHandle hSHPLin = 0; DBFHandle hDBFPt = 0; SHPHandle hSHPPt = 0; // Some auxiliary variables int totpoints; double* padfX; double* padfY; unsigned int nVertices; int* panPart; SHPObject *psObject; unsigned int posXY, npoints, nelem; int shpRes; // progress information if (TeProgress::instance()) TeProgress::instance()->setTotalSteps(querier->numElemInstances()); clock_t t0, t1, t2; t2 = clock(); t0 = t1 = t2; int dt = CLOCKS_PER_SEC/2; int dt2 = CLOCKS_PER_SEC; //* .000001; // Loop through the instances writting their geometries and attributes unsigned int iRecPol=0, iRecLin=0, iRecPt=0; unsigned int n, l, m; unsigned int nIProcessed = 0; TeSTInstance st; while(querier->fetchInstance(st)) { totpoints = 0; nVertices = 0; if (st.hasPolygons()) { TePolygonSet& polSet = st.getPolygons(); TePolygonSet::iterator itps; int nVerticesCount = 0; for (itps = polSet.begin(); itps != polSet.end(); ++itps) { nVertices = (*itps).size(); nVerticesCount += nVertices; for (n=0; n<nVertices;++n) totpoints += (*itps)[n].size(); } panPart = (int *) malloc(sizeof(int) * nVerticesCount); padfX = (double *) malloc(sizeof(double) * totpoints); padfY = (double *) malloc(sizeof(double) * totpoints); posXY = 0; nelem = 0; for (itps = polSet.begin(); itps != polSet.end(); ++itps) { TePolygon poly = *itps; for (l=0; l<poly.size(); ++l) { if (l==0) { if (TeOrientation(poly[l]) == TeCOUNTERCLOCKWISE) TeReverseLine(poly[l]); } else { if (TeOrientation(poly[l]) == TeCLOCKWISE) TeReverseLine(poly[l]); } npoints = poly[l].size(); panPart[nelem]=posXY; for (m=0; m<npoints; ++m) { padfX[posXY] = poly[l][m].x_; padfY[posXY] = poly[l][m].y_; posXY++; } nelem++; } } psObject = SHPCreateObject(SHPT_POLYGON, -1, nelem, panPart, NULL, posXY, padfX, padfY, NULL, NULL); if (hSHPPol == 0) { string fname = base + "_pol.shp"; hSHPPol = SHPCreate(fname.c_str(), SHPT_POLYGON); assert (hSHPPol != 0); } shpRes = SHPWriteObject(hSHPPol, -1, psObject); SHPDestroyObject(psObject); free(panPart); free(padfX); free(padfY); assert(shpRes != -1); if (hDBFPol == 0) { hDBFPol = TeCreateDBFFile(base + "_pol.dbf", qAttList); assert (hDBFPol != 0); } if (onlyObjId) { DBFWriteStringAttribute(hDBFPol, iRecPol, 0, st.objectId().c_str()); } else { string val; for (n=0; n<qAttList.size();++n) { st.getPropertyValue(val,n); if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME) { DBFWriteStringAttribute(hDBFPol, iRecPol, n, val.c_str()); } else if (qAttList[n].rep_.type_ == TeINT) { DBFWriteIntegerAttribute(hDBFPol, iRecPol, n, atoi(val.c_str())); } else if (qAttList[n].rep_.type_ == TeREAL) { DBFWriteDoubleAttribute(hDBFPol, iRecPol, n, atof(val.c_str())); } } } ++iRecPol; } if (st.hasCells()) { TeCellSet& cellSet = st.getCells(); nVertices = cellSet.size(); totpoints = nVertices*5; panPart = (int *) malloc(sizeof(int) * nVertices); padfX = (double *) malloc(sizeof(double) * totpoints); padfY = (double *) malloc(sizeof(double) * totpoints); posXY = 0; nelem = 0; TeCellSet::iterator itcs; for (itcs=cellSet.begin(); itcs!=cellSet.end(); ++itcs) { panPart[nelem]=posXY; padfX[posXY] = (*itcs).box().lowerLeft().x(); padfY[posXY] = (*itcs).box().lowerLeft().y(); posXY++; padfX[posXY] = (*itcs).box().upperRight().x(); padfY[posXY] = (*itcs).box().lowerLeft().y(); posXY++; padfX[posXY] = (*itcs).box().upperRight().x(); padfY[posXY] = (*itcs).box().upperRight().y(); posXY++; padfX[posXY] = (*itcs).box().lowerLeft().x(); padfY[posXY] = (*itcs).box().upperRight().y(); posXY++; padfX[posXY] = (*itcs).box().lowerLeft().x(); padfY[posXY] = (*itcs).box().lowerLeft().y(); ++posXY; ++nelem; } psObject = SHPCreateObject(SHPT_POLYGON, -1, nelem, panPart, NULL,posXY, padfX, padfY, NULL, NULL); if (hSHPPol == 0) { string fname = base + "_pol.shp"; hSHPPol = SHPCreate(fname.c_str(), SHPT_POLYGON); assert (hSHPPol != 0); } shpRes = SHPWriteObject(hSHPPol, -1, psObject); SHPDestroyObject(psObject); free(panPart); free(padfX); free(padfY); assert(shpRes != -1); if (hDBFPol == 0) { hDBFPol = TeCreateDBFFile(base + "_pol.dbf", qAttList); assert (hDBFPol != 0); } if (onlyObjId) { DBFWriteStringAttribute(hDBFPol, iRecPol, 0, st.objectId().c_str()); } else { string val; for (n=0; n<qAttList.size();++n) { st.getPropertyValue(val,n); if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME) { DBFWriteStringAttribute(hDBFPol, iRecPol, n, val.c_str()); } else if (qAttList[n].rep_.type_ == TeINT) { DBFWriteIntegerAttribute(hDBFPol, iRecPol, n, atoi(val.c_str())); } else if (qAttList[n].rep_.type_ == TeREAL) { DBFWriteDoubleAttribute(hDBFPol, iRecPol, n, atof(val.c_str())); } } } ++iRecPol; } if (st.hasLines()) { TeLineSet& lineSet = st.getLines(); nVertices = lineSet.size(); TeLineSet::iterator itls; for (itls=lineSet.begin(); itls!=lineSet.end(); ++itls) totpoints += (*itls).size(); panPart = (int *) malloc(sizeof(int) * nVertices); padfX = (double *) malloc(sizeof(double) * totpoints); padfY = (double *) malloc(sizeof(double) * totpoints); posXY = 0; nelem = 0; for (itls=lineSet.begin(); itls!=lineSet.end(); ++itls) { panPart[nelem]=posXY; for (l=0; l<(*itls).size(); ++l) { padfX[posXY] = (*itls)[l].x(); padfY[posXY] = (*itls)[l].y(); ++posXY; } ++nelem; } psObject = SHPCreateObject(SHPT_ARC, -1, nVertices, panPart, NULL, posXY, padfX, padfY, NULL, NULL); if (hSHPLin == 0) { string fname = base + "_lin.shp"; hSHPLin = SHPCreate(fname.c_str(), SHPT_ARC); assert (hSHPLin != 0); } shpRes = SHPWriteObject(hSHPLin, -1, psObject); SHPDestroyObject(psObject); free(panPart); free(padfX); free(padfY); assert(shpRes != -1); if (hDBFLin == 0) { hDBFLin = TeCreateDBFFile(base + "_lin.dbf", qAttList); assert (hDBFLin != 0); } if (onlyObjId) { DBFWriteStringAttribute(hDBFLin, iRecLin, 0, st.objectId().c_str()); } else { string val; for (n=0; n<qAttList.size();++n) { st.getPropertyValue(val,n); if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME) { DBFWriteStringAttribute(hDBFLin, iRecLin, n, val.c_str()); } else if (qAttList[n].rep_.type_ == TeINT) { DBFWriteIntegerAttribute(hDBFLin, iRecLin, n, atoi(val.c_str())); } else if (qAttList[n].rep_.type_ == TeREAL) { DBFWriteDoubleAttribute(hDBFLin, iRecLin, n, atof(val.c_str())); } } } ++iRecLin; } if (st.hasPoints()) { TePointSet& pointSet = st.getPoints(); nVertices = pointSet.size(); panPart = (int *) malloc(sizeof(int) * nVertices); padfX = (double *) malloc(sizeof(double) * nVertices); padfY = (double *) malloc(sizeof(double) * nVertices); nelem = 0; TePointSet::iterator itpts; for (itpts=pointSet.begin(); itpts!=pointSet.end(); ++itpts) { panPart[nelem] = nelem; padfX[nelem] = (*itpts).location().x(); padfY[nelem] = (*itpts).location().y(); ++nelem; } psObject = SHPCreateObject(SHPT_POINT, -1, nVertices, panPart, NULL, nVertices, padfX, padfY, NULL, NULL ); if (hSHPPt == 0) { string fname = base + "_pt.shp"; hSHPPt = SHPCreate(fname.c_str(), SHPT_POINT); assert (hSHPPt != 0); } shpRes = SHPWriteObject(hSHPPt, -1, psObject); SHPDestroyObject(psObject); free(panPart); free(padfX); free(padfY); assert(shpRes != -1); if (hDBFPt == 0) { hDBFPt = TeCreateDBFFile(base + "_pt.dbf", qAttList); assert (hDBFPt != 0); } if (onlyObjId) { DBFWriteStringAttribute(hDBFPt, iRecPt, 0, st.objectId().c_str()); } else { string val; for (n=0; n<qAttList.size();++n) { st.getPropertyValue(val,n); if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME) { DBFWriteStringAttribute(hDBFPt, iRecPt, n, val.c_str()); } else if (qAttList[n].rep_.type_ == TeINT) { DBFWriteIntegerAttribute(hDBFPt, iRecPt, n, atoi(val.c_str())); } else if (qAttList[n].rep_.type_ == TeREAL) { DBFWriteDoubleAttribute(hDBFPt, iRecPt, n, atof(val.c_str())); } } } ++iRecPt; } ++nIProcessed; if (TeProgress::instance() && int(t2-t1) > dt) { t1 = t2; if(((int)(t2-t0) > dt2)) { if (TeProgress::instance()->wasCancelled()) break; else TeProgress::instance()->setProgress(nIProcessed); } } } if (hDBFPol != 0) DBFClose(hDBFPol); if (hSHPPol != 0) SHPClose(hSHPPol); if (hDBFLin != 0) DBFClose(hDBFLin); if (hSHPLin != 0) SHPClose(hSHPLin); if (hDBFPt != 0) DBFClose(hDBFPt); if (hSHPPt != 0) SHPClose(hSHPPt); if (TeProgress::instance()) TeProgress::instance()->reset(); return true; }
void openfiles() { /* -------------------------------------------------------------------- */ /* Open the DBF file. */ /* -------------------------------------------------------------------- */ setext(infile, "dbf"); hDBF = DBFOpen( infile, "rb" ); if( hDBF == NULL ) { printf( "ERROR: Unable to open the input DBF:%s\n", infile ); exit( 1 ); } /* -------------------------------------------------------------------- */ /* Open the append DBF file. */ /* -------------------------------------------------------------------- */ if (strcmp(outfile,"")) { setext(outfile, "dbf"); hDBFappend = DBFOpen( outfile, "rb+" ); newdbf=0; if( hDBFappend == NULL ) { newdbf=1; hDBFappend = DBFCreate( outfile ); if( hDBFappend == NULL ) { printf( "ERROR: Unable to open the append DBF:%s\n", outfile ); exit( 1 ); } } } /* -------------------------------------------------------------------- */ /* Open the passed shapefile. */ /* -------------------------------------------------------------------- */ setext(infile, "shp"); hSHP = SHPOpen( infile, "rb" ); if( hSHP == NULL ) { printf( "ERROR: Unable to open the input shape file:%s\n", infile ); exit( 1 ); } SHPGetInfo( hSHP, &nEntities, &nShapeType, NULL, NULL ); /* -------------------------------------------------------------------- */ /* Open the passed append shapefile. */ /* -------------------------------------------------------------------- */ if (strcmp(outfile,"")) { setext(outfile, "shp"); hSHPappend = SHPOpen( outfile, "rb+" ); if( hSHPappend == NULL ) { hSHPappend = SHPCreate( outfile, nShapeType ); if( hSHPappend == NULL ) { printf( "ERROR: Unable to open the append shape file:%s\n", outfile ); exit( 1 ); } } SHPGetInfo( hSHPappend, &nEntitiesAppend, &nShapeTypeAppend, NULL, NULL ); if (nShapeType != nShapeTypeAppend) { puts( "ERROR: Input and Append shape files are of different types."); exit( 1 ); } } }
void Builder::print_shpObjects() { QgsDebugMsg( QString( "Number of primitives: %1" ).arg( shpObjects.size() ) ); QgsDebugMsg( QString( "Number of text fields: %1" ).arg( textObjects.size() ) ); QgsDebugMsg( QString( "Number of inserts fields: %1" ).arg( insertObjects.size() ) ); SHPHandle hSHP; if ( fname.endsWith( ".shp", Qt::CaseInsensitive ) ) { QString fn( fname.mid( fname.length() - 4 ) ); outputdbf = fn + ".dbf"; outputshp = fn + ".shp"; outputtdbf = fn + "_texts.dbf"; outputtshp = fn + "_texts.shp"; outputidbf = fn + "_inserts.dbf"; outputishp = fn + "_inserts.shp"; } else { outputdbf = outputtdbf = outputidbf = fname + ".dbf"; outputshp = outputtshp = outputishp = fname + ".shp"; } DBFHandle dbffile = DBFCreate( outputdbf.toUtf8() ); DBFAddField( dbffile, "myid", FTInteger, 10, 0 ); hSHP = SHPCreate( outputshp.toUtf8(), shapefileType ); QgsDebugMsg( "Writing to main shp file..." ); for ( int i = 0; i < shpObjects.size(); i++ ) { SHPWriteObject( hSHP, -1, shpObjects[i] ); SHPDestroyObject( shpObjects[i] ); DBFWriteIntegerAttribute( dbffile, i, 0, i ); } SHPClose( hSHP ); DBFClose( dbffile ); QgsDebugMsg( "Done!" ); if ( !textObjects.isEmpty() ) { SHPHandle thSHP; DBFHandle Tdbffile = DBFCreate( outputtdbf.toUtf8() ); thSHP = SHPCreate( outputtshp.toUtf8(), SHPT_POINT ); DBFAddField( Tdbffile, "tipx", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "tipy", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "tipz", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "tapx", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "tapy", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "tapz", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "height", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "scale", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "flags", FTInteger, 10, 0 ); DBFAddField( Tdbffile, "hjust", FTInteger, 10, 0 ); DBFAddField( Tdbffile, "vjust", FTInteger, 10, 0 ); DBFAddField( Tdbffile, "text", FTString, 50, 0 ); DBFAddField( Tdbffile, "style", FTString, 50, 0 ); DBFAddField( Tdbffile, "angle", FTDouble, 20, 10 ); QgsDebugMsg( "Writing Texts' shp File..." ); for ( int i = 0; i < textObjects.size(); i++ ) { SHPObject *psObject; double x = textObjects[i].ipx; double y = textObjects[i].ipy; double z = textObjects[i].ipz; psObject = SHPCreateObject( SHPT_POINT, i, 0, NULL, NULL, 1, &x, &y, &z, NULL ); SHPWriteObject( thSHP, -1, psObject ); DBFWriteDoubleAttribute( Tdbffile, i, 0, textObjects[i].ipx ); DBFWriteDoubleAttribute( Tdbffile, i, 1, textObjects[i].ipy ); DBFWriteDoubleAttribute( Tdbffile, i, 2, textObjects[i].ipz ); DBFWriteDoubleAttribute( Tdbffile, i, 3, textObjects[i].apx ); DBFWriteDoubleAttribute( Tdbffile, i, 4, textObjects[i].apy ); DBFWriteDoubleAttribute( Tdbffile, i, 5, textObjects[i].apz ); DBFWriteDoubleAttribute( Tdbffile, i, 6, textObjects[i].height ); DBFWriteDoubleAttribute( Tdbffile, i, 7, textObjects[i].xScaleFactor ); DBFWriteIntegerAttribute( Tdbffile, i, 8, textObjects[i].textGenerationFlags ); DBFWriteIntegerAttribute( Tdbffile, i, 9, textObjects[i].hJustification ); DBFWriteIntegerAttribute( Tdbffile, i, 10, textObjects[i].vJustification ); DBFWriteStringAttribute( Tdbffile, i, 11, textObjects[i].text.c_str() ); DBFWriteStringAttribute( Tdbffile, i, 12, textObjects[i].style.c_str() ); DBFWriteDoubleAttribute( Tdbffile, i, 13, textObjects[i].angle ); SHPDestroyObject( psObject ); } SHPClose( thSHP ); DBFClose( Tdbffile ); QgsDebugMsg( "Done!" ); } if ( !insertObjects.isEmpty() ) { SHPHandle ihSHP; DBFHandle Idbffile = DBFCreate( outputidbf.toUtf8() ); ihSHP = SHPCreate( outputishp.toUtf8(), SHPT_POINT ); DBFAddField( Idbffile, "name", FTString, 200, 0 ); DBFAddField( Idbffile, "ipx", FTDouble, 20, 10 ); DBFAddField( Idbffile, "ipy", FTDouble, 20, 10 ); DBFAddField( Idbffile, "ipz", FTDouble, 20, 10 ); DBFAddField( Idbffile, "sx", FTDouble, 20, 10 ); DBFAddField( Idbffile, "sy", FTDouble, 20, 10 ); DBFAddField( Idbffile, "sz", FTDouble, 20, 10 ); DBFAddField( Idbffile, "angle", FTDouble, 20, 10 ); DBFAddField( Idbffile, "cols", FTInteger, 20, 0 ); DBFAddField( Idbffile, "rows", FTInteger, 20, 0 ); DBFAddField( Idbffile, "colsp", FTDouble, 20, 10 ); DBFAddField( Idbffile, "rowsp", FTDouble, 20, 10 ); QgsDebugMsg( "Writing Insert' shp File..." ); for ( int i = 0; i < insertObjects.size(); i++ ) { SHPObject *psObject; double &x = insertObjects[i].ipx; double &y = insertObjects[i].ipy; double &z = insertObjects[i].ipz; psObject = SHPCreateObject( SHPT_POINT, i, 0, NULL, NULL, 1, &x, &y, &z, NULL ); SHPWriteObject( ihSHP, -1, psObject ); int c = 0; DBFWriteStringAttribute( Idbffile, i, c++, insertObjects[i].name.c_str() ); DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].ipx ); DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].ipy ); DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].ipz ); DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].sx ); DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].sy ); DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].sz ); DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].angle ); DBFWriteIntegerAttribute( Idbffile, i, c++, insertObjects[i].cols ); DBFWriteIntegerAttribute( Idbffile, i, c++, insertObjects[i].rows ); DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].colSp ); DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].rowSp ); SHPDestroyObject( psObject ); } SHPClose( ihSHP ); DBFClose( Idbffile ); QgsDebugMsg( "Done!" ); } }
bool TeExportPolygonSet2SHP( const TePolygonSet& ps,const std::string& base_file_name ) { // creating files names std::string dbfFilename = base_file_name + ".dbf"; std::string shpFilename = base_file_name + ".shp"; // creating polygons attribute list ( max attribute size == 25 ) TeAttributeList attList; TeAttribute at; at.rep_.type_ = TeSTRING; //the id of the cell at.rep_.numChar_ = 25; at.rep_.name_ = "object_id_"; at.rep_.isPrimaryKey_ = true; attList.push_back(at); /* DBF output file handle creation */ DBFHandle hDBF = TeCreateDBFFile (dbfFilename, attList); if ( hDBF == 0 ) return false; /* SHP output file handle creation */ SHPHandle hSHP = SHPCreate( shpFilename.c_str(), SHPT_POLYGON ); if( hSHP == 0 ) { DBFClose( hDBF ); return false; } /* Writing polygons */ int iRecord = 0; int totpoints = 0; double *padfX, *padfY; SHPObject *psObject; int posXY, npoints, nelem; int nVertices; int* panParts; TePolygonSet::iterator itps; TePolygon poly; for (itps = ps.begin() ; itps != ps.end() ; itps++ ) { poly=(*itps); totpoints = 0; nVertices = poly.size(); for (unsigned int n=0; n<poly.size();n++) { totpoints += poly[n].size(); } panParts = (int *) malloc(sizeof(int) * nVertices); padfX = (double *) malloc(sizeof(double) * totpoints); padfY = (double *) malloc(sizeof(double) * totpoints); posXY = 0; nelem = 0; for (unsigned int l=0; l<poly.size(); ++l) { if (l==0) { if (TeOrientation(poly[l]) == TeCOUNTERCLOCKWISE) { TeReverseLine(poly[l]); } } else { if (TeOrientation(poly[l]) == TeCLOCKWISE) { TeReverseLine(poly[l]); } } npoints = poly[l].size(); panParts[nelem]=posXY; for (int m=0; m<npoints; m++ ) { padfX[posXY] = poly[l][m].x_; padfY[posXY] = poly[l][m].y_; posXY++; } nelem++; } psObject = SHPCreateObject( SHPT_POLYGON, -1, nelem, panParts, NULL, posXY, padfX, padfY, NULL, NULL ); int shpRes = SHPWriteObject( hSHP, -1, psObject ); if (shpRes == -1 ) { DBFClose( hDBF ); SHPClose( hSHP ); return false; } SHPDestroyObject( psObject ); free( panParts ); free( padfX ); free( padfY ); // writing attributes - same creation order DBFWriteStringAttribute(hDBF, iRecord, 0, poly.objectId().c_str() ); iRecord++; } DBFClose( hDBF ); SHPClose( hSHP ); return true; }
static void WritePointShapefile( const char * pszShapefile, SDTSTransfer * poTransfer, const char * pszMODN ) { SDTSPointReader *poPointReader; /* -------------------------------------------------------------------- */ /* Fetch a reference to the indexed Pointgon reader. */ /* -------------------------------------------------------------------- */ poPointReader = (SDTSPointReader *) poTransfer->GetLayerIndexedReader( poTransfer->FindLayer( pszMODN ) ); if( poPointReader == NULL ) { fprintf( stderr, "Failed to open %s.\n", poTransfer->GetCATD()->GetModuleFilePath( pszMODN ) ); return; } poPointReader->Rewind(); /* -------------------------------------------------------------------- */ /* Create the Shapefile. */ /* -------------------------------------------------------------------- */ SHPHandle hSHP; hSHP = SHPCreate( pszShapefile, SHPT_POINT ); if( hSHP == NULL ) { fprintf( stderr, "Unable to create shapefile `%s'\n", pszShapefile ); return; } /* -------------------------------------------------------------------- */ /* Create the database file, and our basic set of attributes. */ /* -------------------------------------------------------------------- */ DBFHandle hDBF; int nAreaField, nSDTSRecordField; char szDBFFilename[1024]; sprintf( szDBFFilename, "%s.dbf", pszShapefile ); hDBF = DBFCreate( szDBFFilename ); if( hDBF == NULL ) { fprintf( stderr, "Unable to create shapefile .dbf for `%s'\n", pszShapefile ); return; } nSDTSRecordField = DBFAddField( hDBF, "SDTSRecId", FTInteger, 8, 0 ); nAreaField = DBFAddField( hDBF, "AreaId", FTString, 12, 0 ); char **papszModRefs = poPointReader->ScanModuleReferences(); AddPrimaryAttrToDBFSchema( hDBF, poTransfer, papszModRefs ); CSLDestroy( papszModRefs ); /* ==================================================================== */ /* Process all the line features in the module. */ /* ==================================================================== */ SDTSRawPoint *poRawPoint; while( (poRawPoint = poPointReader->GetNextPoint()) != NULL ) { int iShape; /* -------------------------------------------------------------------- */ /* Write out a shape with the vertices. */ /* -------------------------------------------------------------------- */ SHPObject *psShape; psShape = SHPCreateSimpleObject( SHPT_POINT, 1, &(poRawPoint->dfX), &(poRawPoint->dfY), &(poRawPoint->dfZ) ); iShape = SHPWriteObject( hSHP, -1, psShape ); SHPDestroyObject( psShape ); /* -------------------------------------------------------------------- */ /* Write out the attributes. */ /* -------------------------------------------------------------------- */ char szID[13]; DBFWriteIntegerAttribute( hDBF, iShape, nSDTSRecordField, poRawPoint->oModId.nRecord ); sprintf( szID, "%s:%ld", poRawPoint->oAreaId.szModule, poRawPoint->oAreaId.nRecord ); DBFWriteStringAttribute( hDBF, iShape, nAreaField, szID ); WritePrimaryAttrToDBF( hDBF, iShape, poTransfer, poRawPoint ); if( !poPointReader->IsIndexed() ) delete poRawPoint; } /* -------------------------------------------------------------------- */ /* Close, and cleanup. */ /* -------------------------------------------------------------------- */ DBFClose( hDBF ); SHPClose( hSHP ); }
bool _pnts_save_shp(const d_points * pnts, const char * filename) { if (!pnts) { writelog(LOG_WARNING, "NULL pointer to points."); return false; }; DBFHandle hDBF; SHPHandle hSHP; hSHP = SHPOpen( filename, "rb+" ); hDBF = DBFOpen( filename, "rb+" ); if (hSHP == NULL || hDBF == NULL) { if (hSHP) SHPClose( hSHP ); if (hDBF) DBFClose( hDBF ); hSHP = SHPCreate( filename, SHPT_POINT ); if( hSHP == NULL ) { writelog(LOG_ERROR, "Unable to create:%s", filename ); return false; } hDBF = DBFCreate( filename ); } int shpType; SHPGetInfo(hSHP, NULL, &shpType, NULL, NULL); if (shpType != SHPT_POINT) { writelog(LOG_ERROR, "%s : Wrong shape type!", filename); SHPClose( hSHP ); DBFClose( hDBF ); return false; } int name_field = DBFGetFieldIndex( hDBF, "NAME" ); int val_field = DBFGetFieldIndex( hDBF, "VALUE" ); if (name_field == -1) { if( DBFAddField( hDBF, "NAME", FTString, 50, 0 ) == -1 ) { writelog(LOG_ERROR, "DBFAddField(%s,FTString) failed.", "NAME"); SHPClose( hSHP ); DBFClose( hDBF ); return false; } name_field = DBFGetFieldIndex( hDBF, "NAME" ); } if (val_field == -1) { if( DBFAddField( hDBF, "VALUE", FTDouble, 50, 0 ) == -1 ) { writelog(LOG_ERROR, "DBFAddField(%s,FTString) failed.", "VALUE"); SHPClose( hSHP ); DBFClose( hDBF ); return false; } val_field = DBFGetFieldIndex( hDBF, "VALUE" ); } char buf[1024]; size_t i; for (i = 0; i < pnts->size(); i++) { double x = (*(pnts->X))(i); double y = (*(pnts->Y))(i); SHPObject * psObject = SHPCreateObject(SHPT_POINT, -1, 0, NULL, NULL, 1, &x, &y, NULL, NULL); SHPComputeExtents(psObject); int pos = SHPWriteObject(hSHP, -1, psObject); SHPDestroyObject(psObject); if (pnts->names) DBFWriteStringAttribute(hDBF, pos, name_field, (*(pnts->names))(i) ); else { sprintf(buf,"%d",(int)i); DBFWriteStringAttribute(hDBF, pos, name_field, buf ); } REAL val = (*(pnts->Z))(i); DBFWriteDoubleAttribute(hDBF, pos, val_field, val); } SHPClose( hSHP ); DBFClose( hDBF ); return true; };
/* * Write the geometry for a set of polygons to a shape file * This needs to map between our internal structure for the * shape polygons and that expected by the shape file writer. */ int polyShapeWrite(PolyObject * poly /* set of polygons */ , char *name /* name of file to write to */ ) { SHPHandle hSHP; SHPObject *psObject; Vertex *v; PolyShape *ps; PolyShapeList *plist; static int v_size; static int p_size; int i, j, k, n; int np, nv; int nShapeType; int m; int nVertices; int *partsStart; double *vx, *vy; if(v_size == 0) { v_size = 1024; /* * allocate space for each of the vertices */ vx = (double *) malloc(2 * v_size * sizeof(double)); if(vx == NULL) { WARN("Memory allocation error in polyShapeWrite"); return 1; } vy = vx + v_size; } if(p_size == 0) { p_size = 1024; partsStart = (int *) malloc(p_size * sizeof(int)); if(partsStart == NULL) { WARN("Memory allocation error in polyShapeWrite"); return 1; } } nShapeType = poly->nSHPType; hSHP = SHPCreate(name, nShapeType); if(hSHP == NULL) { WARN2("Unable to create ", name); return 1; } /* * make sure space is available for all vertices - if it gets full, * reallocate with double the size */ n = poly->nObjects; plist = poly->plist; /* * loop over all polygons */ for(i = 0; i < n; i++) { ps = plist->ps; /* debug code BDB */ /*if(PolyArea(ps) < 0) printf("In polyShapeWrite area is negative for shape %d\n", i); */ np = ps->num_contours; nVertices = 0; while(np > p_size) { p_size *= 2; partsStart = (int *) realloc(partsStart, 2 * p_size * sizeof(int)); if(partsStart == NULL) { WARN("Memory allocation error in polyShapeWrite"); return 1; } } partsStart[0] = 0; /* * population of parts field for ShapeFiles */ for(j = 0; j < np; j++) { nv = ps->contour[j].num_vertices; nVertices += nv; partsStart[j + 1] = nVertices; } while(nVertices > v_size) { v_size *= 2; vx = (double *) realloc(vx, 2 * v_size * sizeof(double)); if(vx == NULL) { WARN("Memory allocation error in polyShapeWrite"); return 1; } vy = vx + v_size; } /* * population of vertices field for ShapeFiles */ m = 0; for(j = 0; j < np; j++) { nv = ps->contour[j].num_vertices; v = ps->contour[j].vertex; for(k = 0; k < nv; k++) { vx[m] = v[k].x; vy[m] = v[k].y; m++; } } /* * write a polygon to the .shp file */ psObject = SHPCreateObject(nShapeType, -1, np, partsStart, NULL, nVertices, vx, vy, NULL, NULL); SHPWriteObject(hSHP, -1, psObject); SHPDestroyObject(psObject); plist = plist->next; /* go to next polygon */ } /* end loop over polygons */ SHPClose(hSHP); return 0; } /* end of polyShapeWrite function */
static void Test_WriteArcPoly( int nSHPType, const char *pszFilename ) { SHPHandle hSHPHandle; SHPObject *psShape; double x[100], y[100], z[100], m[100]; int anPartStart[100]; int anPartType[100], *panPartType; int i, iShape; hSHPHandle = SHPCreate( pszFilename, nSHPType ); if( nSHPType == SHPT_MULTIPATCH ) panPartType = anPartType; else panPartType = NULL; for( iShape = 0; iShape < 3; iShape++ ) { x[0] = 1.0; y[0] = 1.0+iShape*3; x[1] = 2.0; y[1] = 1.0+iShape*3; x[2] = 2.0; y[2] = 2.0+iShape*3; x[3] = 1.0; y[3] = 2.0+iShape*3; x[4] = 1.0; y[4] = 1.0+iShape*3; for( i = 0; i < 5; i++ ) { z[i] = iShape * 10 + i + 3.35; m[i] = iShape * 10 + i + 4.45; } psShape = SHPCreateObject( nSHPType, -1, 0, NULL, NULL, 5, x, y, z, m ); SHPWriteObject( hSHPHandle, -1, psShape ); SHPDestroyObject( psShape ); } /* -------------------------------------------------------------------- */ /* Do a multi part polygon (shape). We close it, and have two */ /* inner rings. */ /* -------------------------------------------------------------------- */ x[0] = 0.0; y[0] = 0.0; x[1] = 0; y[1] = 100; x[2] = 100; y[2] = 100; x[3] = 100; y[3] = 0; x[4] = 0; y[4] = 0; x[5] = 10; y[5] = 20; x[6] = 30; y[6] = 20; x[7] = 30; y[7] = 40; x[8] = 10; y[8] = 40; x[9] = 10; y[9] = 20; x[10] = 60; y[10] = 20; x[11] = 90; y[11] = 20; x[12] = 90; y[12] = 40; x[13] = 60; y[13] = 40; x[14] = 60; y[14] = 20; for( i = 0; i < 15; i++ ) { z[i] = i; m[i] = i*2; } anPartStart[0] = 0; anPartStart[1] = 5; anPartStart[2] = 10; anPartType[0] = SHPP_RING; anPartType[1] = SHPP_INNERRING; anPartType[2] = SHPP_INNERRING; psShape = SHPCreateObject( nSHPType, -1, 3, anPartStart, panPartType, 15, x, y, z, m ); SHPWriteObject( hSHPHandle, -1, psShape ); SHPDestroyObject( psShape ); SHPClose( hSHPHandle ); }
static void write_shapefile (local_data_t *local_data) { guint npolys; char *shape_filename; SHPHandle shape_file = NULL; SHPObject *shape; double *vertex_x, *vertex_y; guint i, j; projUV p; char *dbf_filename; DBFHandle dbf_file = NULL; int nunits_field_index; int avg_ninfected_field_index; int avg_ndestroyed_field_index; int avg_nvaccinated_field_index; int avg_frinfected_field_index; int avg_frdestroyed_field_index; int avg_frvaccinated_field_index; #if DEBUG g_debug ("----- ENTER write_shapefile (%s)", MODEL_NAME); #endif vertex_x = g_new (double, local_data->max_nvertices); vertex_y = g_new (double, local_data->max_nvertices); /* We are going to write 2 files: the .shp file, containing the geometry of * the polygons, and the .dbf file, containing the numeric attributes * attached to the polygons. */ shape_filename = g_strdup_printf ("%s.shp", local_data->base_filename); #if DEBUG g_debug ("creating new shapefile \"%s\"", shape_filename); #endif shape_file = SHPCreate (shape_filename, SHPT_POLYGON); g_assert (shape_file != NULL); npolys = local_data->polys->len; for (i = 0; i < npolys; i++) { gpc_polygon *poly; gpc_vertex_list *contour; poly = (gpc_polygon *) g_ptr_array_index (local_data->polys, i); g_assert (poly->num_contours == 1); contour = &(poly->contour[0]); for (j = 0; j < contour->num_vertices; j++) { /* The polygon vertices are in x-y coordinates. We need to * "unproject" them back to lat-long. */ p.u = contour->vertex[j].x; p.v = contour->vertex[j].y; p = pj_inv (p, local_data->projection); vertex_x[j] = p.u * RAD_TO_DEG; vertex_y[j] = p.v * RAD_TO_DEG; } shape = SHPCreateSimpleObject (SHPT_POLYGON, j, vertex_x, vertex_y, NULL); SHPWriteObject (shape_file, -1, shape); SHPDestroyObject (shape); } if (shape_file != NULL) SHPClose (shape_file); g_free (shape_filename); /* Now the attribute file */ dbf_filename = g_strdup_printf ("%s.dbf", local_data->base_filename); #if DEBUG g_debug ("creating new attributes file \"%s\"", dbf_filename); #endif dbf_file = DBFCreate (dbf_filename); g_assert (dbf_file != NULL); /* Add attribute definitions. */ #if DEBUG g_debug ("adding field definitions to DBF file \"%s\": nunits, avgninf, avgndest, avgnvacc, avgfrinf, avgfrdest, avgfrvacc", dbf_filename); #endif /* 9-digit integers should be enough to count # of units in a polygon. */ nunits_field_index = DBFAddField (dbf_file, "nunits", FTInteger, 9, 0); /* 1 decimal place for average # of units infected or destroyed, 3 for * average fraction of units. */ avg_ninfected_field_index = DBFAddField (dbf_file, "avgninf", FTDouble, 9, 1); avg_ndestroyed_field_index = DBFAddField (dbf_file, "avgndest", FTDouble, 9, 1); avg_nvaccinated_field_index = DBFAddField (dbf_file, "avgnvacc", FTDouble, 9, 1); avg_frinfected_field_index = DBFAddField (dbf_file, "avgfrinf", FTDouble, 9, 3); avg_frdestroyed_field_index = DBFAddField (dbf_file, "avgfrdest", FTDouble, 9, 3); avg_frvaccinated_field_index = DBFAddField (dbf_file, "avgfrvacc", FTDouble, 9, 3); /* Write the attributes to the file. */ #if DEBUG g_debug ("writing attributes to \"%s\"", dbf_filename); #endif for (i = 0; i < npolys; i++) { guint nunits; /* Divide the counts by the number of runs to get the mean */ local_data->ninfected[i] /= local_data->nruns; local_data->ndestroyed[i] /= local_data->nruns; local_data->nvaccinated[i] /= local_data->nruns; nunits = local_data->unit_count[i]; DBFWriteIntegerAttribute (dbf_file, i, nunits_field_index, nunits); DBFWriteDoubleAttribute (dbf_file, i, avg_ninfected_field_index, local_data->ninfected[i]); DBFWriteDoubleAttribute (dbf_file, i, avg_ndestroyed_field_index, local_data->ndestroyed[i]); DBFWriteDoubleAttribute (dbf_file, i, avg_nvaccinated_field_index, local_data->nvaccinated[i]); DBFWriteDoubleAttribute (dbf_file, i, avg_frinfected_field_index, local_data->ninfected[i] / nunits); DBFWriteDoubleAttribute (dbf_file, i, avg_frdestroyed_field_index, local_data->ndestroyed[i] / nunits); DBFWriteDoubleAttribute (dbf_file, i, avg_frvaccinated_field_index, local_data->nvaccinated[i] / nunits); } if (dbf_file != NULL) DBFClose (dbf_file); g_free (dbf_filename); /* Clean up. */ g_free (vertex_y); g_free (vertex_x); #if DEBUG g_debug ("----- EXIT write_shapefile (%s)", MODEL_NAME); #endif return; }
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] = ""; double apeture[4]; char *DBFRow = NULL; int Cpan[2] = { 0,0 }; int byRing = 1; PT Centrd; SHPObject *psCShape, *cent_pt; if( argc < 3 ) { printf( "shpcentrd shp_file new_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 ); new_SHP = SHPCreate ( argv[2], SHPT_POINT ); new_DBF = DBFCloneEmpty (old_DBF, argv[2]); if( new_SHP == NULL || new_DBF == NULL ) { printf( "Unable to create new files:%s\n", argv[2] ); exit( 1 ); } DBFRow = (char *) malloc ( (old_DBF->nRecordLength) + 15 ); #ifdef DEBUG printf ("ShpCentrd using shpgeo \n"); #endif for( i = 0; i < nEntities; i++ ) { int res ; psCShape = SHPReadObject( old_SHP, i ); if ( byRing == 1 ) { int ring; for ( ring = 0; ring < psCShape->nParts; ring ++ ) { SHPObject *psO; psO = SHPClone ( psCShape, ring, ring + 1 ); Centrd = SHPCentrd_2d ( psO ); cent_pt = SHPCreateSimpleObject ( SHPT_POINT, 1, (double*) &(Centrd.x), (double*) &(Centrd.y), NULL ); SHPWriteObject ( new_SHP, -1, cent_pt ); memcpy ( DBFRow, DBFReadTuple ( old_DBF, i ), old_DBF->nRecordLength ); DBFWriteTuple ( new_DBF, new_DBF->nRecords, DBFRow ); SHPDestroyObject ( cent_pt ); SHPDestroyObject ( psO ); } } else { Centrd = SHPCentrd_2d ( psCShape ); cent_pt = SHPCreateSimpleObject ( SHPT_POINT, 1, (double*) &(Centrd.x), (double*) &(Centrd.y), NULL ); SHPWriteObject ( new_SHP, -1, cent_pt ); memcpy ( DBFRow, DBFReadTuple ( old_DBF, i ), old_DBF->nRecordLength ); DBFWriteTuple ( new_DBF, new_DBF->nRecords, DBFRow ); SHPDestroyObject ( cent_pt ); } } SHPClose( old_SHP ); SHPClose( new_SHP ); DBFClose( old_DBF ); DBFClose( new_DBF ); printf ("\n"); }
void shape_ursa_init(char *inFile, char *header) { char *dbaseFile; DBFHandle dbase; SHPHandle shape; dbf_header_t *dbf; int ii, nCols, length=50; // Read configuration file read_header_config("URSA", &dbf, &nCols); // Open database for initialization dbaseFile = appendExt(inFile, ".dbf"); dbase = DBFCreate(dbaseFile); if (!dbase) asfPrintError("Could not create database file '%s'\n", dbaseFile); // Add fields to database for (ii=0; ii<nCols; ii++) { if (strcmp(dbf[ii].header, "Granule_Name") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "GRAN_NAME", FTString, length, 0) == -1) asfPrintError("Could not add GRAN_NAME field to database file\n"); } else if (strcmp(dbf[ii].header, "Granule_Type") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "GRAN_TYPE", FTString, length, 0) == -1) asfPrintError("Could not add GRAN_TYPE field to database file\n"); } else if (strcmp(dbf[ii].header, "Platform") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "PLATFORM", FTString, length, 0) == -1) asfPrintError("Could not add PLATFORM field to database file\n"); } else if (strcmp(dbf[ii].header, "Sensor") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "SENSOR", FTString, length, 0) == -1) asfPrintError("Could not add SENSOR field to database file\n"); } else if (strcmp(dbf[ii].header, "Orbit") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "ORBIT", FTInteger, 7, 0) == -1) asfPrintError("Could not add ORBIT field to database file\n"); } else if (strcmp(dbf[ii].header, "Beam_Mode") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "BEAM_MODE", FTString, length, 0) == -1) asfPrintError("Could not add BEAM_MODE field to database file\n"); } else if (strcmp(dbf[ii].header, "Off_Nadir_Angle") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "OFF_NADIR", FTDouble, 16, 4) == -1) asfPrintError("Could not add OFF_NADIR field to database file\n"); } else if (strcmp(dbf[ii].header, "Start_Time") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "START_TIME", FTString, length, 0) == -1) asfPrintError("Could not add START_TIME field to database file\n"); } else if (strcmp(dbf[ii].header, "End_Time") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "END_TIME", FTString, length, 0) == -1) asfPrintError("Could not add END_TIME field to database file\n"); } else if (strcmp(dbf[ii].header, "Near_Start_Lat") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "NSTART_LAT", FTDouble, 16, 4) == -1) asfPrintError("Could not add NSTART_LAT field to database file\n"); } else if (strcmp(dbf[ii].header, "Near_Start_Lon") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "NSTART_LON", FTDouble, 16, 4) == -1) asfPrintError("Could not add NSTART_LON field to database file\n"); } else if (strcmp(dbf[ii].header, "Far_Start_Lat") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "FSTART_LAT", FTDouble, 16, 4) == -1) asfPrintError("Could not add FSTART_LAT field to database file\n"); } else if (strcmp(dbf[ii].header, "Far_Start_Lon") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "FSTART_LON", FTDouble, 16, 4) == -1) asfPrintError("Could not add FSTART_LON field to database file\n"); } else if (strcmp(dbf[ii].header, "Near_End_Lat") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "N_END_LAT", FTDouble, 16, 4) == -1) asfPrintError("Could not add N_END_LAT field to database file\n"); } else if (strcmp(dbf[ii].header, "Near_End_Lon") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "N_END_LON", FTDouble, 16, 4) == -1) asfPrintError("Could not add N_END_LON field to database file\n"); } else if (strcmp(dbf[ii].header, "Far_End_Lat") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "F_END_LAT", FTDouble, 16, 4) == -1) asfPrintError("Could not add F_END_LAT field to database file\n"); } else if (strcmp(dbf[ii].header, "Far_End_Lon") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "F_END_LON", FTDouble, 16, 4) == -1) asfPrintError("Could not add F_END_LON field to database file\n"); } else if (strcmp(dbf[ii].header, "Center_Lat") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "CENTER_LAT", FTDouble, 16, 4) == -1) asfPrintError("Could not add CENTER_LAT field to database file\n"); } else if (strcmp(dbf[ii].header, "Center_Lon") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "CENTER_LON", FTDouble, 16, 4) == -1) asfPrintError("Could not add CENTER_LON field to database file\n"); } else if (strcmp(dbf[ii].header, "Path_Number") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "PATH_NUM", FTInteger, 10, 0) == -1) asfPrintError("Could not add PATH_NUM field to database file\n"); } else if (strcmp(dbf[ii].header, "Frame_Number") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "FRAME_NUM", FTInteger, 10, 0) == -1) asfPrintError("Could not add FRAME_NUM field to database file\n"); } else if (strcmp(dbf[ii].header, "Cloud_Cover") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "CLOUDCOVER", FTInteger, 5, 0) == -1) asfPrintError("Could not add CLOUDCOVER field to database file\n"); } else if (strcmp(dbf[ii].header, "Faraday_Rotation") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "FARADAYROT", FTDouble, 16, 1) == -1) asfPrintError("Could not add FARADAYROT field to database file\n"); } } // Close the database for initialization DBFClose(dbase); // Open shapefile for initialization shape = SHPCreate(inFile, SHPT_POLYGON); if (!shape) asfPrintError("Could not create shapefile '%s'\n", inFile); // Close shapefile for initialization SHPClose(shape); FREE(dbaseFile); return; }
static void WritePolygonShapefile( const char * pszShapefile, SDTSTransfer * poTransfer, const char * pszMODN ) { SDTSPolygonReader *poPolyReader; /* -------------------------------------------------------------------- */ /* Fetch a reference to the indexed polygon reader. */ /* -------------------------------------------------------------------- */ poPolyReader = (SDTSPolygonReader *) poTransfer->GetLayerIndexedReader( poTransfer->FindLayer( pszMODN ) ); if( poPolyReader == NULL ) { fprintf( stderr, "Failed to open %s.\n", poTransfer->GetCATD()->GetModuleFilePath( pszMODN ) ); return; } /* -------------------------------------------------------------------- */ /* Assemble polygon geometries from all the line layers. */ /* -------------------------------------------------------------------- */ poPolyReader->AssembleRings( poTransfer, poTransfer->FindLayer(pszMODN) ); /* -------------------------------------------------------------------- */ /* Create the Shapefile. */ /* -------------------------------------------------------------------- */ SHPHandle hSHP; hSHP = SHPCreate( pszShapefile, SHPT_POLYGON ); if( hSHP == NULL ) { fprintf( stderr, "Unable to create shapefile `%s'\n", pszShapefile ); return; } /* -------------------------------------------------------------------- */ /* Create the database file, and our basic set of attributes. */ /* -------------------------------------------------------------------- */ DBFHandle hDBF; int nSDTSRecordField; char szDBFFilename[1024]; sprintf( szDBFFilename, "%s.dbf", pszShapefile ); hDBF = DBFCreate( szDBFFilename ); if( hDBF == NULL ) { fprintf( stderr, "Unable to create shapefile .dbf for `%s'\n", pszShapefile ); return; } nSDTSRecordField = DBFAddField( hDBF, "SDTSRecId", FTInteger, 8, 0 ); char **papszModRefs = poPolyReader->ScanModuleReferences(); AddPrimaryAttrToDBFSchema( hDBF, poTransfer, papszModRefs ); CSLDestroy( papszModRefs ); /* ==================================================================== */ /* Process all the polygon features in the module. */ /* ==================================================================== */ SDTSRawPolygon *poRawPoly; poPolyReader->Rewind(); while( (poRawPoly = (SDTSRawPolygon *) poPolyReader->GetNextFeature()) != NULL ) { int iShape; /* -------------------------------------------------------------------- */ /* Write out a shape with the vertices. */ /* -------------------------------------------------------------------- */ SHPObject *psShape; psShape = SHPCreateObject( SHPT_POLYGON, -1, poRawPoly->nRings, poRawPoly->panRingStart, NULL, poRawPoly->nVertices, poRawPoly->padfX, poRawPoly->padfY, poRawPoly->padfZ, NULL ); iShape = SHPWriteObject( hSHP, -1, psShape ); SHPDestroyObject( psShape ); /* -------------------------------------------------------------------- */ /* Write out the attributes. */ /* -------------------------------------------------------------------- */ DBFWriteIntegerAttribute( hDBF, iShape, nSDTSRecordField, poRawPoly->oModId.nRecord ); WritePrimaryAttrToDBF( hDBF, iShape, poTransfer, poRawPoly ); if( !poPolyReader->IsIndexed() ) delete poRawPoly; } /* -------------------------------------------------------------------- */ /* Close, and cleanup. */ /* -------------------------------------------------------------------- */ DBFClose( hDBF ); SHPClose( hSHP ); }
void shape_datapool_init(char *inFile, char *header) { char *dbaseFile; DBFHandle dbase; SHPHandle shape; dbf_header_t *dbf; int ii, nCols, length=32, length2=255; // Read configuration file read_header_config("DATAPOOL", &dbf, &nCols); // Open database for initialization dbaseFile = appendExt(inFile, ".dbf"); dbase = DBFCreate(dbaseFile); if (!dbase) asfPrintError("Could not create database file '%s'\n", dbaseFile); // Add fields to database for (ii=0; ii<nCols; ii++) { if (strcmp(dbf[ii].header, "Granule_Name") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "GRAN_NAME", FTString, length, 0) == -1) asfPrintError("Could not add GRAN_NAME field to database file\n"); } else if (strcmp(dbf[ii].header, "Platform") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "PLATFORM", FTString, length, 0) == -1) asfPrintError("Could not add PLATFORM field to database file\n"); } else if (strcmp(dbf[ii].header, "Sensor") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "SENSOR", FTString, length, 0) == -1) asfPrintError("Could not add SENSOR field to database file\n"); } else if (strcmp(dbf[ii].header, "Beam_Mode") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "BEAM_MODE", FTString, length2, 0) == -1) asfPrintError("Could not add BEAM_MODE field to database file\n"); } else if (strcmp(dbf[ii].header, "Beam_Mode_Description") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "BEAM_MODE_D", FTString, length, 0) == -1) asfPrintError("Could not add BEAM_MODE_D field to database file\n"); } else if (strcmp(dbf[ii].header, "Orbit") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "ORBIT", FTInteger, 7, 0) == -1) asfPrintError("Could not add ORBIT field to database file\n"); } else if (strcmp(dbf[ii].header, "Path_Number") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "PATH_NUM", FTInteger, 10, 0) == -1) asfPrintError("Could not add PATH_NUM field to database file\n"); } else if (strcmp(dbf[ii].header, "Frame_Number") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "FRAME_NUM", FTInteger, 10, 0) == -1) asfPrintError("Could not add FRAME_NUM field to database file\n"); } else if (strcmp(dbf[ii].header, "Acquisition_Date") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "ACQ_DATE", FTString, length, 0) == -1) asfPrintError("Could not add ACQ_TIME field to database file\n"); } else if (strcmp(dbf[ii].header, "Processing_Date") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "PROC_DATE", FTString, length, 0) == -1) asfPrintError("Could not add PROC_TIME field to database file\n"); } else if (strcmp(dbf[ii].header, "Processing_Level") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "PROC_LEVEL", FTString, 10, 0) == -1) asfPrintError("Could not add PROC_LEVEL field to database file\n"); } else if (strcmp(dbf[ii].header, "Start_Time") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "START_TIME", FTString, length, 0) == -1) asfPrintError("Could not add START_TIME field to database file\n"); } else if (strcmp(dbf[ii].header, "End_Time") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "END_TIME", FTString, length, 0) == -1) asfPrintError("Could not add END_TIME field to database file\n"); } else if (strcmp(dbf[ii].header, "Center_Lat") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "CENTER_LAT", FTDouble, 16, 4) == -1) asfPrintError("Could not add CENTER_LAT field to database file\n"); } else if (strcmp(dbf[ii].header, "Center_Lon") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "CENTER_LON", FTDouble, 16, 4) == -1) asfPrintError("Could not add CENTER_LON field to database file\n"); } else if (strcmp(dbf[ii].header, "Near_Start_Lat") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "NSTART_LAT", FTDouble, 16, 4) == -1) asfPrintError("Could not add NSTART_LAT field to database file\n"); } else if (strcmp(dbf[ii].header, "Near_Start_Lon") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "NSTART_LON", FTDouble, 16, 4) == -1) asfPrintError("Could not add NSTART_LON field to database file\n"); } else if (strcmp(dbf[ii].header, "Far_Start_Lat") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "FSTART_LAT", FTDouble, 16, 4) == -1) asfPrintError("Could not add FSTART_LAT field to database file\n"); } else if (strcmp(dbf[ii].header, "Far_Start_Lon") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "FSTART_LON", FTDouble, 16, 4) == -1) asfPrintError("Could not add FSTART_LON field to database file\n"); } else if (strcmp(dbf[ii].header, "Near_End_Lat") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "N_END_LAT", FTDouble, 16, 4) == -1) asfPrintError("Could not add N_END_LAT field to database file\n"); } else if (strcmp(dbf[ii].header, "Near_End_Lon") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "N_END_LON", FTDouble, 16, 4) == -1) asfPrintError("Could not add N_END_LON field to database file\n"); } else if (strcmp(dbf[ii].header, "Far_End_Lat") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "F_END_LAT", FTDouble, 16, 4) == -1) asfPrintError("Could not add F_END_LAT field to database file\n"); } else if (strcmp(dbf[ii].header, "Far_End_Lon") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "F_END_LON", FTDouble, 16, 4) == -1) asfPrintError("Could not add F_END_LON field to database file\n"); } else if (strcmp(dbf[ii].header, "Faraday_Rotation") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "FARADAYROT", FTDouble, 16, 1) == -1) asfPrintError("Could not add FARADAYROT field to database file\n"); } else if (strcmp(dbf[ii].header, "Orbit_Direction") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "ORBIT_DIR", FTString, length, 0) == -1) asfPrintError("Could not add ORBIT_DIR field to database file\n"); } else if (strcmp(dbf[ii].header, "Url") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "URL", FTString, length2, 0) == -1) asfPrintError("Could not add URL field to database file\n"); } else if (strcmp(dbf[ii].header, "Size") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "SIZE_MB", FTDouble, 16, 2) == -1) asfPrintError("Could not add SIZE_MB field to database file\n"); } else if (strcmp(dbf[ii].header, "Off_Nadir_Angle") == 0 && dbf[ii].visible) { if (DBFAddField(dbase, "OFF_NADIR", FTDouble, 16, 2) == -1) asfPrintError("Could not add OFF_NADIR field to database file\n"); } } // Close the database for initialization DBFClose(dbase); // Open shapefile for initialization shape = SHPCreate(inFile, SHPT_POLYGON); if (!shape) asfPrintError("Could not create shapefile '%s'\n", inFile); // Close shapefile for initialization SHPClose(shape); FREE(dbaseFile); return; }
OGRErr OGRShapeLayer::Repack() { if( !bUpdateAccess ) { CPLError( CE_Failure, CPLE_AppDefined, "The REPACK operation is not permitted on a read-only shapefile." ); return OGRERR_FAILURE; } if( hDBF == NULL ) { CPLError( CE_Failure, CPLE_NotSupported, "Attempt to repack a shapefile with no .dbf file not supported."); return OGRERR_FAILURE; } /* -------------------------------------------------------------------- */ /* Build a list of records to be dropped. */ /* -------------------------------------------------------------------- */ int *panRecordsToDelete = (int *) CPLMalloc(sizeof(int)*(nTotalShapeCount+1)); int nDeleteCount = 0; int iShape = 0; OGRErr eErr = OGRERR_NONE; for( iShape = 0; iShape < nTotalShapeCount; iShape++ ) { if( DBFIsRecordDeleted( hDBF, iShape ) ) panRecordsToDelete[nDeleteCount++] = iShape; } panRecordsToDelete[nDeleteCount] = -1; /* -------------------------------------------------------------------- */ /* If there are no records marked for deletion, we take no */ /* action. */ /* -------------------------------------------------------------------- */ if( nDeleteCount == 0 ) { CPLFree( panRecordsToDelete ); return OGRERR_NONE; } /* -------------------------------------------------------------------- */ /* Find existing filenames with exact case (see #3293). */ /* -------------------------------------------------------------------- */ CPLString osDirname(CPLGetPath(pszFullName)); CPLString osBasename(CPLGetBasename(pszFullName)); CPLString osDBFName, osSHPName, osSHXName; char **papszCandidates = CPLReadDir( osDirname ); int i = 0; while(papszCandidates != NULL && papszCandidates[i] != NULL) { CPLString osCandidateBasename = CPLGetBasename(papszCandidates[i]); CPLString osCandidateExtension = CPLGetExtension(papszCandidates[i]); if (osCandidateBasename.compare(osBasename) == 0) { if (EQUAL(osCandidateExtension, "dbf")) osDBFName = CPLFormFilename(osDirname, papszCandidates[i], NULL); else if (EQUAL(osCandidateExtension, "shp")) osSHPName = CPLFormFilename(osDirname, papszCandidates[i], NULL); else if (EQUAL(osCandidateExtension, "shx")) osSHXName = CPLFormFilename(osDirname, papszCandidates[i], NULL); } i++; } CSLDestroy(papszCandidates); papszCandidates = NULL; if (osDBFName.size() == 0) { /* Should not happen, really */ CPLFree( panRecordsToDelete ); return OGRERR_FAILURE; } /* -------------------------------------------------------------------- */ /* Cleanup any existing spatial index. It will become */ /* meaningless when the fids change. */ /* -------------------------------------------------------------------- */ if( CheckForQIX() ) DropSpatialIndex(); /* -------------------------------------------------------------------- */ /* Create a new dbf file, matching the old. */ /* -------------------------------------------------------------------- */ DBFHandle hNewDBF = NULL; CPLString oTempFile(CPLFormFilename(osDirname, osBasename, NULL)); oTempFile += "_packed.dbf"; hNewDBF = DBFCloneEmpty( hDBF, oTempFile ); if( hNewDBF == NULL ) { CPLFree( panRecordsToDelete ); CPLError( CE_Failure, CPLE_OpenFailed, "Failed to create temp file %s.", oTempFile.c_str() ); return OGRERR_FAILURE; } /* -------------------------------------------------------------------- */ /* Copy over all records that are not deleted. */ /* -------------------------------------------------------------------- */ int iDestShape = 0; int iNextDeletedShape = 0; for( iShape = 0; iShape < nTotalShapeCount && eErr == OGRERR_NONE; iShape++ ) { if( panRecordsToDelete[iNextDeletedShape] == iShape ) iNextDeletedShape++; else { void *pTuple = (void *) DBFReadTuple( hDBF, iShape ); if( pTuple == NULL ) eErr = OGRERR_FAILURE; else if( !DBFWriteTuple( hNewDBF, iDestShape++, pTuple ) ) eErr = OGRERR_FAILURE; } } if( eErr != OGRERR_NONE ) { CPLFree( panRecordsToDelete ); VSIUnlink( oTempFile ); return eErr; } /* -------------------------------------------------------------------- */ /* Cleanup the old .dbf and rename the new one. */ /* -------------------------------------------------------------------- */ DBFClose( hDBF ); DBFClose( hNewDBF ); hDBF = hNewDBF = NULL; VSIUnlink( osDBFName ); if( VSIRename( oTempFile, osDBFName ) != 0 ) { CPLDebug( "Shape", "Can not rename DBF file: %s", VSIStrerror( errno ) ); CPLFree( panRecordsToDelete ); return OGRERR_FAILURE; } /* -------------------------------------------------------------------- */ /* Now create a shapefile matching the old one. */ /* -------------------------------------------------------------------- */ if( hSHP != NULL ) { SHPHandle hNewSHP = NULL; if (osSHPName.size() == 0 || osSHXName.size() == 0) { /* Should not happen, really */ CPLFree( panRecordsToDelete ); return OGRERR_FAILURE; } oTempFile = CPLFormFilename(osDirname, osBasename, NULL); oTempFile += "_packed.shp"; hNewSHP = SHPCreate( oTempFile, hSHP->nShapeType ); if( hNewSHP == NULL ) { CPLFree( panRecordsToDelete ); return OGRERR_FAILURE; } /* -------------------------------------------------------------------- */ /* Copy over all records that are not deleted. */ /* -------------------------------------------------------------------- */ iNextDeletedShape = 0; for( iShape = 0; iShape < nTotalShapeCount && eErr == OGRERR_NONE; iShape++ ) { if( panRecordsToDelete[iNextDeletedShape] == iShape ) iNextDeletedShape++; else { SHPObject *hObject; hObject = SHPReadObject( hSHP, iShape ); if( hObject == NULL ) eErr = OGRERR_FAILURE; else if( SHPWriteObject( hNewSHP, -1, hObject ) == -1 ) eErr = OGRERR_FAILURE; if( hObject ) SHPDestroyObject( hObject ); } } if( eErr != OGRERR_NONE ) { CPLFree( panRecordsToDelete ); VSIUnlink( CPLResetExtension( oTempFile, "shp" ) ); VSIUnlink( CPLResetExtension( oTempFile, "shx" ) ); return eErr; } /* -------------------------------------------------------------------- */ /* Cleanup the old .shp/.shx and rename the new one. */ /* -------------------------------------------------------------------- */ SHPClose( hSHP ); SHPClose( hNewSHP ); hSHP = hNewSHP = NULL; VSIUnlink( osSHPName ); VSIUnlink( osSHXName ); oTempFile = CPLResetExtension( oTempFile, "shp" ); if( VSIRename( oTempFile, osSHPName ) != 0 ) { CPLDebug( "Shape", "Can not rename SHP file: %s", VSIStrerror( errno ) ); CPLFree( panRecordsToDelete ); return OGRERR_FAILURE; } oTempFile = CPLResetExtension( oTempFile, "shx" ); if( VSIRename( oTempFile, osSHXName ) != 0 ) { CPLDebug( "Shape", "Can not rename SHX file: %s", VSIStrerror( errno ) ); CPLFree( panRecordsToDelete ); return OGRERR_FAILURE; } } CPLFree( panRecordsToDelete ); panRecordsToDelete = NULL; /* -------------------------------------------------------------------- */ /* Reopen the shapefile */ /* */ /* We do not need to reimplement OGRShapeDataSource::OpenFile() here */ /* with the fully featured error checking. */ /* If all operations above succeeded, then all necessery files are */ /* in the right place and accessible. */ /* -------------------------------------------------------------------- */ CPLAssert( NULL == hSHP ); CPLAssert( NULL == hDBF && NULL == hNewDBF ); CPLPushErrorHandler( CPLQuietErrorHandler ); const char* pszAccess = NULL; if( bUpdateAccess ) pszAccess = "r+"; else pszAccess = "r"; hSHP = SHPOpen ( CPLResetExtension( pszFullName, "shp" ) , pszAccess ); hDBF = DBFOpen ( CPLResetExtension( pszFullName, "dbf" ) , pszAccess ); CPLPopErrorHandler(); if( NULL == hSHP || NULL == hDBF ) { CPLString osMsg(CPLGetLastErrorMsg()); CPLError( CE_Failure, CPLE_OpenFailed, "%s", osMsg.c_str() ); return OGRERR_FAILURE; } /* -------------------------------------------------------------------- */ /* Update total shape count. */ /* -------------------------------------------------------------------- */ nTotalShapeCount = hDBF->nRecords; return OGRERR_NONE; }
int main (int argc, char *argv[]) { SHPHandle inSHP, outSHP; DBFHandle inDBF, outDBF; int len; int i; char **fieldNames; char **strOrder = 0; struct DataStruct *index; int width; int decimals; SHPObject *feat; void *tuple; if (argc < 4) { printf("USAGE: shpsort <infile> <outfile> <field[;...]> [<(ASCENDING|DESCENDING)[;...]>]\n"); exit(EXIT_FAILURE); } inSHP = SHPOpen (argv[1], "rb"); if (!inSHP) { fputs("Couldn't open shapefile for reading!\n", stderr); exit(EXIT_FAILURE); } SHPGetInfo(inSHP, &nShapes, &shpType, NULL, NULL); /* If we can open the inSHP, open its DBF */ inDBF = DBFOpen (argv[1], "rb"); if (!inDBF) { fputs("Couldn't open dbf file for reading!\n", stderr); exit(EXIT_FAILURE); } /* Parse fields and validate existence */ fieldNames = split(argv[3], ";"); if (!fieldNames) { fputs("ERROR: parsing field names!\n", stderr); exit(EXIT_FAILURE); } for (nFields = 0; fieldNames[nFields] ; nFields++) { continue; } fldIdx = malloc(sizeof *fldIdx * nFields); if (!fldIdx) { fputs("malloc failed!\n", stderr); exit(EXIT_FAILURE); } for (i = 0; i < nFields; i++) { len = (int)strlen(fieldNames[i]); while(len > 0) { --len; fieldNames[i][len] = (char)toupper((unsigned char)fieldNames[i][len]); } fldIdx[i] = DBFGetFieldIndex(inDBF, fieldNames[i]); if (fldIdx[i] < 0) { /* try "SHAPE" */ if (strcmp(fieldNames[i], "SHAPE") == 0) { fldIdx[i] = -1; } else if (strcmp(fieldNames[i], "FID") == 0) { fldIdx[i] = -2; } else { fprintf(stderr, "ERROR: field '%s' not found!\n", fieldNames[i]); exit(EXIT_FAILURE); } } } /* set up field type array */ fldType = malloc(sizeof *fldType * nFields); if (!fldType) { fputs("malloc failed!\n", stderr); exit(EXIT_FAILURE); } for (i = 0; i < nFields; i++) { if (fldIdx[i] < 0) { fldType[i] = fldIdx[i]; } else { fldType[i] = DBFGetFieldInfo(inDBF, fldIdx[i], NULL, &width, &decimals); if (fldType[i] == FTInvalid) { fputs("Unrecognized field type in dBASE file!\n", stderr); exit(EXIT_FAILURE); } } } /* set up field order array */ fldOrder = malloc(sizeof *fldOrder * nFields); if (!fldOrder) { fputs("malloc failed!\n", stderr); exit(EXIT_FAILURE); } for (i = 0; i < nFields; i++) { /* default to ascending order */ fldOrder[i] = ASCENDING; } if (argc > 4) { strOrder = split(argv[4], ";"); if (!strOrder) { fputs("ERROR: parsing fields ordering!\n", stderr); exit(EXIT_FAILURE); } for (i = 0; i < nFields && strOrder[i]; i++) { if (strcmp(strOrder[i], "DESCENDING") == 0) { fldOrder[i] = DESCENDING; } } } /* build the index */ index = build_index (inSHP, inDBF); /* Create output shapefile */ outSHP = SHPCreate(argv[2], shpType); if (!outSHP) { fprintf(stderr, "%s:%d: couldn't create output shapefile!\n", __FILE__, __LINE__); exit(EXIT_FAILURE); } /* Create output dbf */ outDBF = DBFCloneEmpty(inDBF, argv[2]); if (!outDBF) { fprintf(stderr, "%s:%d: couldn't create output dBASE file!\n", __FILE__, __LINE__); exit(EXIT_FAILURE); } /* Copy projection file, if any */ copy_related(argv[1], argv[2], ".shp", ".prj"); /* Copy metadata file, if any */ copy_related(argv[1], argv[2], ".shp", ".shp.xml"); /* Write out sorted results */ for (i = 0; i < nShapes; i++) { feat = SHPReadObject(inSHP, index[i].record); if (SHPWriteObject(outSHP, -1, feat) < 0) { fprintf(stderr, "%s:%d: error writing shapefile!\n", __FILE__, __LINE__); exit(EXIT_FAILURE); } tuple = (void *) DBFReadTuple(inDBF, index[i].record); if (DBFWriteTuple(outDBF, i, tuple) < 0) { fprintf(stderr, "%s:%d: error writing dBASE file!\n", __FILE__, __LINE__); exit(EXIT_FAILURE); } } SHPClose(inSHP); SHPClose(outSHP); DBFClose(inDBF); DBFClose(outDBF); return EXIT_SUCCESS; }