コード例 #1
0
ファイル: shpsort.c プロジェクト: ArielleBassanelli/gempak
static struct DataStruct * build_index (SHPHandle shp, DBFHandle dbf) {
  struct DataStruct *data;
  SHPObject  *feat;
  int i;
  int j;

  /* make array */
  data = malloc (sizeof *data * nShapes);
  if (!data) {
    fputs("malloc failed!\n", stderr);
    exit(EXIT_FAILURE);
  }

  /* populate array */
  for (i = 0; i < nShapes; i++) {
    data[i].value = malloc(sizeof data[0].value[0] * nFields);
    if (0 == data[i].value) {
      fputs("malloc failed!\n", stderr);
      exit(EXIT_FAILURE);
    }
    data[i].record = i;
    for (j = 0; j < nFields; j++) {
      data[i].value[j].null = 0;
      switch (fldType[j]) {
      case FIDType:
	data[i].value[j].u.i = i;
	break;
      case SHPType:
	feat = SHPReadObject(shp, i);
	switch (feat->nSHPType) {
	case SHPT_NULL:
	  fprintf(stderr, "Shape %d is a null feature!\n", i);
	  data[i].value[j].null = 1;
	  break;
	case SHPT_POINT:
	case SHPT_POINTZ:
	case SHPT_POINTM:
	case SHPT_MULTIPOINT:
	case SHPT_MULTIPOINTZ:
	case SHPT_MULTIPOINTM:
	case SHPT_MULTIPATCH:
	  /* Y-sort bounds */
	  data[i].value[j].u.d = feat->dfYMax;
	  break;
	case SHPT_ARC:
	case SHPT_ARCZ:
	case SHPT_ARCM:
	  data[i].value[j].u.d = shp_length(feat);
	  break;
	case SHPT_POLYGON:
	case SHPT_POLYGONZ:
	case SHPT_POLYGONM:
	  data[i].value[j].u.d = shp_area(feat);
	  break;
	default:
	  fputs("Can't sort on Shapefile feature type!\n", stderr);
	  exit(EXIT_FAILURE);
	}
	SHPDestroyObject(feat);
	break;
      case FTString:
	data[i].value[j].null = DBFIsAttributeNULL(dbf, i, fldIdx[j]);
	if (!data[i].value[j].null) {
	  data[i].value[j].u.s = dupstr(DBFReadStringAttribute(dbf, i, fldIdx[j]));
	}
	break;
      case FTInteger:
      case FTLogical:
	data[i].value[j].null = DBFIsAttributeNULL(dbf, i, fldIdx[j]);
	if (!data[i].value[j].null) {
	  data[i].value[j].u.i  = DBFReadIntegerAttribute(dbf, i, fldIdx[j]);
	}
	break;
      case FTDouble:
	data[i].value[j].null = DBFIsAttributeNULL(dbf, i, fldIdx[j]);
	if (!data[i].value[j].null) {
	  data[i].value[j].u.d = DBFReadDoubleAttribute(dbf, i, fldIdx[j]);	
	}
	break;
      }
    }
  }
  
#ifdef DEBUG
  PrintDataStruct(data);
  fputs("build_index: sorting array\n", stdout);
#endif

  qsort (data, nShapes, sizeof data[0], compare);

#ifdef DEBUG
  PrintDataStruct(data);
  fputs("build_index: returning array\n", stdout);
#endif

  return data;
}
コード例 #2
0
ファイル: Rdbfread.c プロジェクト: csilles/cxxr
SEXP Rdbfread(SEXP dbfnm)
{
    DBFHandle hDBF;
    int i, iRecord, nflds, nrecs, nRvar, pc=0;
    char labelbuff[81];
    const char *pszFilename = NULL;
    int nWidth, nDecimals, val;
    char szTitle[12], buf[2];
    const char *p;
    DBFFieldType eType;
    SEXP df, tmp, varlabels, row_names, DataTypes;
    short *types;

/* -------------------------------------------------------------------- */
/*      Handle arguments.                                               */
/* -------------------------------------------------------------------- */

    pszFilename = CHAR(STRING_ELT(dbfnm, 0));


/* -------------------------------------------------------------------- */
/*      Open the file.                                                  */
/* -------------------------------------------------------------------- */
    hDBF = DBFOpen(pszFilename, "rb" );
    if( hDBF == NULL ) error(_("unable to open DBF file"));

/* -------------------------------------------------------------------- */
/*	If there is no data in this file let the user know.		*/
/* -------------------------------------------------------------------- */
    if( DBFGetFieldCount(hDBF) == 0 )
    {
	DBFClose( hDBF );
	error(_("no fields in DBF table"));
    }

    nRvar = 0;
    nflds = DBFGetFieldCount(hDBF);
    nrecs = DBFGetRecordCount(hDBF);
    types = (short *) R_alloc(nflds, sizeof(short));
    PROTECT(DataTypes = allocVector(STRSXP, nflds)); pc++;
    for( i = 0; i < nflds; i++ ) {
	eType = DBFGetFieldInfo( hDBF, i, szTitle, &nWidth, &nDecimals );
	switch(eType) {
	case FTString:
	    types[i] = 1;
	    nRvar++;
	    break;
	case FTInteger:
	    types[i] = 2;
	    nRvar++;
	    break;
	case FTDouble:
	    types[i] = 3;
	    nRvar++;
	    break;
	case FTLogical:
	    types[i] = 4;
	    nRvar++;
	    break;
	default: /* doesn't seem to be possible */
	    types[i] = 0;
	}
	buf[0] = hDBF->pachFieldType[i]; buf[1] = '\0';
	SET_STRING_ELT(DataTypes, i, mkChar(buf));
    }

    PROTECT(df = allocVector(VECSXP, nRvar)); pc++;
    PROTECT(varlabels = allocVector(STRSXP, nRvar)); pc++;
    for(i = 0, nRvar = 0; i < nflds; i++)
    {
	eType = DBFGetFieldInfo( hDBF, i, szTitle, &nWidth, &nDecimals );
	switch(types[i]) {
	case 1:
	    SET_VECTOR_ELT(df, nRvar, allocVector(STRSXP,nrecs));
	    break;
	case 2:
	    SET_VECTOR_ELT(df, nRvar, allocVector(INTSXP,nrecs));
	    break;
	case 3:
	    SET_VECTOR_ELT(df, nRvar, allocVector(REALSXP,nrecs));
	    break;
	case 4:
	    SET_VECTOR_ELT(df, nRvar, allocVector(LGLSXP,nrecs));
	    break;
	default:
	    continue;
	}
	SET_STRING_ELT(varlabels, nRvar, mkChar(szTitle));
	nRvar++;
    }

    for(iRecord = 0; iRecord < nrecs; iRecord++)
    {
	nRvar = 0;
	for(i = 0; i < nflds; i++)
	    switch(types[i]) {
	    case 1:
		if( DBFIsAttributeNULL( hDBF, iRecord, i ))
		    SET_STRING_ELT(VECTOR_ELT(df, nRvar), iRecord, NA_STRING);
		else
		    SET_STRING_ELT(VECTOR_ELT(df, nRvar), iRecord,
				   mkChar(DBFReadStringAttribute( hDBF, iRecord, i)));
		nRvar++;
		break;

	    case 2:
		if( DBFIsAttributeNULL( hDBF, iRecord, i ))
		    INTEGER(VECTOR_ELT(df, nRvar))[iRecord] = NA_INTEGER;
		else {
		    double dtmp = DBFReadDoubleAttribute( hDBF, iRecord, i );
		    if((dtmp > 2147483647.0) || (dtmp < -2147483646.0)) {
			int ii, *it; double *r;
			/* allow for NA_INTEGER = -(2^31 -1)*/
			PROTECT(tmp = VECTOR_ELT(df, nRvar));
			it = INTEGER(tmp);
			SET_VECTOR_ELT(df, nRvar, allocVector(REALSXP, nrecs));
			r = REAL(VECTOR_ELT(df, nRvar));
			for (ii = 0; ii < iRecord; ii++) {
			    int itmp = it[ii];
			    r[ii] = (itmp == NA_INTEGER) ? NA_REAL : itmp;
			}
			UNPROTECT(1);
			r[iRecord] = dtmp;
			types[i] = 3;
		    } else
			INTEGER(VECTOR_ELT(df, nRvar))[iRecord] = (int) dtmp;
		}
		nRvar++;
		break;

	    case 3:
		if( DBFIsAttributeNULL( hDBF, iRecord, i ))
		    REAL(VECTOR_ELT(df, nRvar))[iRecord] = NA_REAL;
		else
		    REAL(VECTOR_ELT(df, nRvar))[iRecord] =
			DBFReadDoubleAttribute( hDBF, iRecord, i );
		nRvar++;
		break;

	    case 4:
		if( DBFIsAttributeNULL( hDBF, iRecord, i ))
		    LOGICAL(VECTOR_ELT(df, nRvar))[iRecord] = NA_LOGICAL;
		else {
		    p = DBFReadStringAttribute( hDBF, iRecord, i );
		    switch(*p){
		    case 'f':
		    case 'F':
		    case 'n':
		    case 'N':
			val = 0;
			break;
		    case 't':
		    case 'T':
		    case 'y':
		    case 'Y':
			val = 1;
			break;
		    case '?':
			val = NA_LOGICAL;
			break;
		    default:
			warning(_("value |%d| found in logical field"), *p);
			val = NA_LOGICAL;
			break;
		    }
		    LOGICAL(VECTOR_ELT(df, nRvar))[iRecord] = val;
		}
		nRvar++;
		break;
	    default:
		break;
	    }
    }
    DBFClose( hDBF );
    PROTECT(tmp = mkString("data.frame")); pc++;
    setAttrib(df, R_ClassSymbol, tmp);
    setAttrib(df, R_NamesSymbol, varlabels);
    setAttrib(df, install("data_types"), DataTypes);
    PROTECT(row_names = allocVector(STRSXP, nrecs)); pc++;
    for (i = 0; i < nrecs; i++) {
	sprintf(labelbuff, "%d", i+1);
	SET_STRING_ELT(row_names, i, mkChar(labelbuff));
    }
    setAttrib(df, R_RowNamesSymbol, row_names);

    UNPROTECT(pc);
    return(df);
}
コード例 #3
0
int main( int argc, char ** argv )

{
    DBFHandle	hDBF;
    int		*panWidth, i, iRecord;
    char	szFormat[32], *pszFilename = NULL;
    int		nWidth, nDecimals;
    int		bHeader = 0;
    int		bRaw = 0;
    int		bMultiLine = 0;
    char	szTitle[12];

/* -------------------------------------------------------------------- */
/*      Handle arguments.                                               */
/* -------------------------------------------------------------------- */
    for( i = 1; i < argc; i++ )
    {
        if( strcmp(argv[i],"-h") == 0 )
            bHeader = 1;
        else if( strcmp(argv[i],"-r") == 0 )
            bRaw = 1;
        else if( strcmp(argv[i],"-m") == 0 )
            bMultiLine = 1;
        else
            pszFilename = argv[i];
    }

/* -------------------------------------------------------------------- */
/*      Display a usage message.                                        */
/* -------------------------------------------------------------------- */
    if( pszFilename == NULL )
    {
	printf( "dbfdump [-h] [-r] [-m] xbase_file\n" );
        printf( "        -h: Write header info (field descriptions)\n" );
        printf( "        -r: Write raw field info, numeric values not reformatted\n" );
        printf( "        -m: Multiline, one line per field.\n" );
	exit( 1 );
    }

/* -------------------------------------------------------------------- */
/*      Open the file.                                                  */
/* -------------------------------------------------------------------- */
    hDBF = DBFOpen( pszFilename, "rb" );
    if( hDBF == NULL )
    {
	printf( "DBFOpen(%s,\"r\") failed.\n", argv[1] );
	exit( 2 );
    }
    
/* -------------------------------------------------------------------- */
/*	If there is no data in this file let the user know.		*/
/* -------------------------------------------------------------------- */
    if( DBFGetFieldCount(hDBF) == 0 )
    {
	printf( "There are no fields in this table!\n" );
	exit( 3 );
    }

/* -------------------------------------------------------------------- */
/*	Dump header definitions.					*/
/* -------------------------------------------------------------------- */
    if( bHeader )
    {
        for( i = 0; i < DBFGetFieldCount(hDBF); i++ )
        {
            DBFFieldType	eType;
            const char	 	*pszTypeName;

            eType = DBFGetFieldInfo( hDBF, i, szTitle, &nWidth, &nDecimals );
            if( eType == FTString )
                pszTypeName = "String";
            else if( eType == FTInteger )
                pszTypeName = "Integer";
            else if( eType == FTDouble )
                pszTypeName = "Double";
            else if( eType == FTInvalid )
                pszTypeName = "Invalid";

            printf( "Field %d: Type=%s, Title=`%s', Width=%d, Decimals=%d\n",
                    i, pszTypeName, szTitle, nWidth, nDecimals );
        }
    }

/* -------------------------------------------------------------------- */
/*	Compute offsets to use when printing each of the field 		*/
/*	values. We make each field as wide as the field title+1, or 	*/
/*	the field value + 1. 						*/
/* -------------------------------------------------------------------- */
    panWidth = (int *) malloc( DBFGetFieldCount( hDBF ) * sizeof(int) );

    for( i = 0; i < DBFGetFieldCount(hDBF) && !bMultiLine; i++ )
    {
	DBFFieldType	eType;

	eType = DBFGetFieldInfo( hDBF, i, szTitle, &nWidth, &nDecimals );
	if( strlen(szTitle) > nWidth )
	    panWidth[i] = strlen(szTitle);
	else
	    panWidth[i] = nWidth;

	if( eType == FTString )
	    sprintf( szFormat, "%%-%ds ", panWidth[i] );
	else
	    sprintf( szFormat, "%%%ds ", panWidth[i] );
	printf( szFormat, szTitle );
    }
    printf( "\n" );

/* -------------------------------------------------------------------- */
/*	Read all the records 						*/
/* -------------------------------------------------------------------- */
    for( iRecord = 0; iRecord < DBFGetRecordCount(hDBF); iRecord++ )
    {
        if( bMultiLine )
            printf( "Record: %d\n", iRecord );
        
	for( i = 0; i < DBFGetFieldCount(hDBF); i++ )
	{
            DBFFieldType	eType;
            
            eType = DBFGetFieldInfo( hDBF, i, szTitle, &nWidth, &nDecimals );

            if( bMultiLine )
            {
                printf( "%s: ", szTitle );
            }
            
/* -------------------------------------------------------------------- */
/*      Print the record according to the type and formatting           */
/*      information implicit in the DBF field description.              */
/* -------------------------------------------------------------------- */
            if( !bRaw )
            {
                if( DBFIsAttributeNULL( hDBF, iRecord, i ) )
                {
                    if( eType == FTString )
                        sprintf( szFormat, "%%-%ds", nWidth );
                    else
                        sprintf( szFormat, "%%%ds", nWidth );

                    printf( szFormat, "(NULL)" );
                }
                else
                {
                    switch( eType )
                    {
                      case FTString:
                        sprintf( szFormat, "%%-%ds", nWidth );
                        printf( szFormat, 
                                DBFReadStringAttribute( hDBF, iRecord, i ) );
                        break;
                        
                      case FTInteger:
                        sprintf( szFormat, "%%%dd", nWidth );
                        printf( szFormat, 
                                DBFReadIntegerAttribute( hDBF, iRecord, i ) );
                        break;
                        
                      case FTDouble:
                        sprintf( szFormat, "%%%d.%dlf", nWidth, nDecimals );
                        printf( szFormat, 
                                DBFReadDoubleAttribute( hDBF, iRecord, i ) );
                        break;
                        
                      default:
                        break;
                    }
                }
            }

/* -------------------------------------------------------------------- */
/*      Just dump in raw form (as formatted in the file).               */
/* -------------------------------------------------------------------- */
            else
            {
                sprintf( szFormat, "%%-%ds", nWidth );
                printf( szFormat, 
                        DBFReadStringAttribute( hDBF, iRecord, i ) );
            }

/* -------------------------------------------------------------------- */
/*      Write out any extra spaces required to pad out the field        */
/*      width.                                                          */
/* -------------------------------------------------------------------- */
	    if( !bMultiLine )
	    {
		sprintf( szFormat, "%%%ds", panWidth[i] - nWidth + 1 );
		printf( szFormat, "" );
	    }

            if( bMultiLine )
                printf( "\n" );

	    fflush( stdout );
	}
	printf( "\n" );
    }

    DBFClose( hDBF );

    return( 0 );
}
コード例 #4
0
ファイル: shputils.c プロジェクト: OpendTect/shapelib
void showitems()
{
    char      stmp[40],slow[40],shigh[40];
    double    dtmp,dlow,dhigh,dsum,mean;
    long int  itmp,ilow,ihigh,isum;
    long int  maxrec;
    char      *pt;

    printf("Available Items: (%d)",ti);
    maxrec = DBFGetRecordCount(hDBF);
    if (maxrec > 5000 && ! iall) 
    { maxrec=5000; printf("  ** ESTIMATED RANGES (MEAN)  For more records use \"All\""); }
    else  { printf("          RANGES (MEAN)"); }
          
    for( i = 0; i < ti; i++ )
    {
        switch( DBFGetFieldInfo( hDBF, i, iszTitle, &iWidth, &iDecimals ) )
        {
          case FTString:
          case FTLogical:
            strcpy(slow, "~");
            strcpy(shigh,"\0");
            printf("\n  String  %3d  %-16s",iWidth,iszTitle);
            for( iRecord = 0; iRecord < maxrec; iRecord++ ) {
                strncpy(stmp,DBFReadStringAttribute( hDBF, iRecord, i ),39);
                if (strcmp(stmp,"!!") > 0) {
                    if (strncasecmp2(stmp,slow,0)  < 0) strncpy(slow, stmp,39);
                    if (strncasecmp2(stmp,shigh,0) > 0) strncpy(shigh,stmp,39);
                }
            }
            pt=slow+strlen(slow)-1; 
            while(*pt == ' ') { *pt='\0'; pt--; }
            pt=shigh+strlen(shigh)-1;
            while(*pt == ' ') { *pt='\0'; pt--; }
            if (strncasecmp2(slow,shigh,0) < 0)		printf("%s to %s",slow,shigh);
            else if (strncasecmp2(slow,shigh,0) == 0)	printf("= %s",slow);
            else	printf("No Values");
            break;
          case FTInteger:
            printf("\n  Integer %3d  %-16s",iWidth,iszTitle);
            ilow =  1999999999;
            ihigh= -1999999999;
            isum =  0;
            for( iRecord = 0; iRecord < maxrec; iRecord++ ) {
                itmp = DBFReadIntegerAttribute( hDBF, iRecord, i );
                if (ilow > itmp)  ilow = itmp;
                if (ihigh < itmp) ihigh = itmp;
                isum = isum + itmp;
            }
            mean=isum/maxrec;
            if (ilow < ihigh)       printf("%ld to %ld \t(%.1f)",ilow,ihigh,mean);
            else if (ilow == ihigh) printf("= %ld",ilow);
            else printf("No Values");
            break;

          case FTDouble:
            printf("\n  Real  %3d,%d  %-16s",iWidth,iDecimals,iszTitle);
            dlow =  999999999999999.0;
            dhigh= -999999999999999.0;
            dsum =  0;
            for( iRecord = 0; iRecord < maxrec; iRecord++ ) {
                dtmp = DBFReadDoubleAttribute( hDBF, iRecord, i );
                if (dlow > dtmp) dlow = dtmp;
                if (dhigh < dtmp) dhigh = dtmp;
                dsum = dsum + dtmp;
            }
            mean=dsum/maxrec;
            sprintf(stmp,"%%.%df to %%.%df \t(%%.%df)",iDecimals,iDecimals,iDecimals);
            if (dlow < dhigh)       printf(stmp,dlow,dhigh,mean);
            else if (dlow == dhigh) {
                sprintf(stmp,"= %%.%df",iDecimals);
                printf(stmp,dlow);
            }
            else printf("No Values");
            break;

          case FTInvalid:
            break;

        }

    }
    printf("\n");
}
コード例 #5
0
ファイル: pnts_shp.cpp プロジェクト: mdmitr/surfit
d_points * _pnts_load_shp(const char * filename, const char * pntsname, const char * param) {

	SHPHandle hSHP;
	DBFHandle hDBF;
	
	hSHP = SHPOpen(filename, "rb");
	if( hSHP == NULL ) {
		writelog(LOG_ERROR, "Unable to open:%s", filename );
		return NULL;
	}

	int shpType;
	int Entities;
	SHPGetInfo(hSHP, &Entities, &shpType, NULL, NULL);

	if (shpType != SHPT_POINT) {
		SHPClose( hSHP );
		writelog(LOG_ERROR, "%s : Wrong shape type!", filename);
		return NULL;
	}

	hDBF = DBFOpen(filename, "rb");
	if( hDBF == NULL ) {
		SHPClose(hSHP);
		writelog(LOG_ERROR, "Unable to open DBF for %s", filename );
		return NULL;
	}

	int name_field = DBFGetFieldIndex( hDBF, "NAME" );
	if (name_field == -1)
		writelog(LOG_WARNING,"can't find field named \"NAME\"");

	int val_field = DBFGetFieldIndex( hDBF, param );
	
	if (val_field == -1) 
		writelog(LOG_WARNING, "Cannot find parameter \"%s\" in DBF file", param);
		
	int dbf_records = DBFGetRecordCount( hDBF );

	Entities = MIN(dbf_records, Entities);

	vec * X = create_vec(Entities, 0, 0);
	vec * Y = create_vec(Entities, 0, 0);
	
	int i;
	for (i = 0; i < Entities; i++) {
		SHPObject * shpObject = SHPReadObject( hSHP, i );
		if (shpObject == NULL)
			continue;

		const char * name = NULL;
		if (name_field != -1) {
			name = DBFReadStringAttribute( hDBF, i, name_field );
			if (pntsname != NULL) {
				if ( StringMatch(pntsname, name) == false )
					continue;
			}
		}

		(*X)(i) = *(shpObject->padfX);
		(*Y)(i) = *(shpObject->padfY);
		SHPDestroyObject(shpObject);
	}

	vec * Z = create_vec(Entities, 0, 0);
	for (i = 0; i < Entities; i++) {
		if (val_field != -1)
			(*Z)(i) = DBFReadDoubleAttribute( hDBF, i, val_field );
		else
			(*Z)(i) = 0;
	}

	DBFClose( hDBF );
	SHPClose( hSHP );

	char * fname = get_name(filename);
	d_points * res = create_points(X, Y, Z, fname);
	sstuff_free_char(fname);
	return res;

};
コード例 #6
0
ファイル: VegLayer.cpp プロジェクト: kamalsirsa/vtp
/**
 * Extract point data from a SHP/DBF file and intepret it as a vegetation
 * layer.  This produces a set of vegetation instances.
 *
 * The 'opt' parameter contains a description of how the fields in the
 * imported file are to be interpreted.
 */
bool vtVegLayer::AddElementsFromSHP_Points(const wxString &filename,
										   const vtProjection &proj,
										   VegPointOptions &opt)
{
	// We will be creating plant instances
	SetVegType(VLT_Instances);

	vtSpeciesList *pSpeciesList = g_bld->GetSpeciesList();
	vtBioRegion *pBioRegion = g_bld->GetBioRegion();
	GetPIA()->SetSpeciesList(pSpeciesList);

	// SHPOpen doesn't yet support utf-8 or wide filenames, so convert
	vtString fname_local = UTF8ToLocal(filename.mb_str(wxConvUTF8));

	// Open the SHP File
	SHPHandle hSHP = SHPOpen(fname_local, "rb");
	if (hSHP == NULL)
		return false;

	// Get number of points and type of data
	int		nElem;
	int		nShapeType;
	SHPGetInfo(hSHP, &nElem, &nShapeType, NULL, NULL);

	// Check Shape Type, Veg Layer should be Point data
	if (nShapeType != SHPT_POINT)
		return false;

	// Open DBF File
	DBFHandle db = DBFOpen(fname_local, "rb");
	if (db == NULL)
		return false;

	// Confirm that the field types are correct
	int *pnWidth = 0, *pnDecimals = 0;
	char pszFieldName[80];
	DBFFieldType fieldtype;

	if (!opt.bFixedSpecies)
	{
		// we're going to get species info from a field
		fieldtype = DBFGetFieldInfo(db, opt.iSpeciesFieldIndex, pszFieldName,
			pnWidth, pnDecimals);
		if (opt.iInterpretSpeciesField == 0 || opt.iInterpretSpeciesField == 3)
		{
			if ((fieldtype != FTInteger) && (fieldtype != FTDouble))
			{
				DisplayAndLog("Can't import field '%hs' as an integer, it is type %d.",
					pszFieldName, fieldtype);
				return false;
			}
		}
		else
		{
			if (fieldtype != FTString)
			{
				DisplayAndLog("Can't import field '%hs' as a string, it is type %d.",
					pszFieldName, fieldtype);
				return false;
			}
		}
	}

	// Set projection
	SetProjection(proj);

	// Initialize arrays
	m_pSet->Reserve(nElem);

	// Read Points from SHP and intepret fields
	SHPObject *psShape;
	const char *str;
	int biotype;
	vtBioType *pBioType;
	DPoint2 pos;

	int unfound = 0;

	for (int i = 0; i < nElem; i++)
	{
		// Get the i-th Point in the SHP file
		psShape = SHPReadObject(hSHP, i);
		pos.x = psShape->padfX[0];
		pos.y = psShape->padfY[0];
		SHPDestroyObject(psShape);

		// Read DBF Attributes per point
		int species_id = -1;
		if (opt.bFixedSpecies)
			species_id = pSpeciesList->GetSpeciesIdByName(opt.strFixedSpeciesName.mb_str(wxConvUTF8));
		else
		{
			switch (opt.iInterpretSpeciesField)
			{
			case 0:
				species_id = DBFReadIntegerAttribute(db, i, opt.iSpeciesFieldIndex);
				break;
			case 1:
				str = DBFReadStringAttribute(db, i, opt.iSpeciesFieldIndex);
				species_id = pSpeciesList->GetSpeciesIdByName(str);
				if (species_id == -1)
					unfound++;
				break;
			case 2:
				str = DBFReadStringAttribute(db, i, opt.iSpeciesFieldIndex);
				species_id = pSpeciesList->GetSpeciesIdByCommonName(str);
				if (species_id == -1)
					unfound++;
				break;
			case 3:
				biotype = DBFReadIntegerAttribute(db, i, opt.iSpeciesFieldIndex);
				pBioType = pBioRegion->GetBioType(biotype);
				if (pBioType)
					species_id = pBioType->GetWeightedRandomPlant();
				break;
			case 4:
				str = DBFReadStringAttribute(db, i, opt.iSpeciesFieldIndex);
				biotype = pBioRegion->FindBiotypeIdByName(str);
				pBioType = pBioRegion->GetBioType(biotype);
				if (pBioType)
					species_id = pBioType->GetWeightedRandomPlant();
				break;
			}
		}

		// Make sure we have a valid species
		if (species_id == -1)
			continue;
		vtPlantSpecies *pSpecies = pSpeciesList->GetSpecies(species_id);
		if (!pSpecies)
			continue;

		// Set height
		float size;
		if (opt.bHeightRandom)
			size = random(pSpecies->GetMaxHeight());
		else if (opt.iHeightFieldIndex != -1)
			size = (float) DBFReadDoubleAttribute(db, i, opt.iHeightFieldIndex);
		else
			// fixed height
			size = opt.fHeightFixed;

		// If we get here, there is a valid plant to append
		GetPIA()->AddPlant(pos, size, species_id);
	}
	if (unfound)
		DisplayAndLog("Couldn't find species for %d out of %d instances.", unfound, nElem);
	else
		DisplayAndLog("Imported %d plant instances.", nElem);

	DBFClose(db);
	SHPClose(hSHP);
	return true;
}
コード例 #7
0
ファイル: shputils.c プロジェクト: OpendTect/shapelib
int main( int argc, char ** argv )
{

/* -------------------------------------------------------------------- */
/*      Check command line usage.                                       */
/* -------------------------------------------------------------------- */
    if( argc < 2 ) error();
    strcpy(infile, argv[1]);
    if (argc > 2) {
        strcpy(outfile,argv[2]);
        if (strncasecmp2(outfile, "LIST",0) == 0) { ilist = TRUE; }
        if (strncasecmp2(outfile, "ALL",0) == 0)  { iall  = TRUE; }
    } 
    if (ilist || iall || argc == 2 ) {
        setext(infile, "shp");
        printf("DESCRIBE: %s\n",infile);
        strcpy(outfile,"");
    }
/* -------------------------------------------------------------------- */
/*	Look for other functions on the command line. (SELECT, UNIT)  	*/
/* -------------------------------------------------------------------- */
    for (i = 3; i < argc; i++)
    {
    	if ((strncasecmp2(argv[i],  "SEL",3) == 0) ||
            (strncasecmp2(argv[i],  "UNSEL",5) == 0))
    	{
            if (strncasecmp2(argv[i],  "UNSEL",5) == 0) iunselect=TRUE;
    	    i++;
    	    if (i >= argc) error();
    	    strcpy(selectitem,argv[i]);
    	    i++;
    	    if (i >= argc) error();
    	    selcount=0;
    	    strcpy(temp,argv[i]);
    	    cpt=temp;
    	    tj = atoi(cpt);
    	    ti = 0;
    	    while (tj>0) {
                selectvalues[selcount] = tj;
                while( *cpt >= '0' && *cpt <= '9')
                    cpt++; 
                while( *cpt > '\0' && (*cpt < '0' || *cpt > '9') )
                    cpt++; 
                tj=atoi(cpt);
                selcount++;
    	    }
    	    iselect=TRUE;
    	}  /*** End SEL & UNSEL ***/
    	else
            if ((strncasecmp2(argv[i], "CLIP",4) == 0) ||
                (strncasecmp2(argv[i],  "ERASE",5) == 0))
            {
                if (strncasecmp2(argv[i],  "ERASE",5) == 0) ierase=TRUE;
                i++;
                if (i >= argc) error();
                strcpy(clipfile,argv[i]);
                sscanf(argv[i],"%lf",&cxmin);
                i++;
                if (i >= argc) error();
                if (strncasecmp2(argv[i],  "BOUND",5) == 0) {
                    setext(clipfile, "shp");
                    hSHP = SHPOpen( clipfile, "rb" );
                    if( hSHP == NULL )
                    {
                        printf( "ERROR: Unable to open the clip shape file:%s\n", clipfile );
                        exit( 1 );
                    }
                    SHPGetInfo( hSHPappend, NULL, NULL,
                                adfBoundsMin, adfBoundsMax );
                    cxmin = adfBoundsMin[0];
                    cymin = adfBoundsMin[1];
                    cxmax = adfBoundsMax[0];
                    cymax = adfBoundsMax[1];
                    printf("Theme Clip Boundary: (%lf,%lf) - (%lf,%lf)\n",
                           cxmin, cymin, cxmax, cymax);
                    ibound=TRUE;
                } else {  /*** xmin,ymin,xmax,ymax ***/
                    sscanf(argv[i],"%lf",&cymin);
                    i++;
                    if (i >= argc) error();
                    sscanf(argv[i],"%lf",&cxmax);
                    i++;
                    if (i >= argc) error();
                    sscanf(argv[i],"%lf",&cymax);
                    printf("Clip Box: (%lf,%lf) - (%lf,%lf)\n",cxmin, cymin, cxmax, cymax);
                }
                i++;
                if (i >= argc) error();
                if      (strncasecmp2(argv[i], "CUT",3) == 0)    icut=TRUE;
                else if (strncasecmp2(argv[i], "TOUCH",5) == 0)  itouch=TRUE;
                else if (strncasecmp2(argv[i], "INSIDE",6) == 0) iinside=TRUE;
                else error();
                iclip=TRUE;
            } /*** End CLIP & ERASE ***/
            else if (strncasecmp2(argv[i],  "FACTOR",0) == 0)
            {
                i++;
    	        if (i >= argc) error();
    	        infactor=findunit(argv[i]);
    	        if (infactor == 0) error();
                iunit=TRUE;
                i++;
    	        if (i >= argc) error();
    	        outfactor=findunit(argv[i]);
    	        if (outfactor == 0)
    	        {
                    sscanf(argv[i],"%lf",&factor);
                    if (factor == 0) error();
                }
                if (factor == 0)
                {
                    if (infactor ==0)
                    { puts("ERROR: Input unit must be defined before output unit"); exit(1); }
                    factor=infactor/outfactor;
                }
                printf("Output file coordinate values will be factored by %lg\n",factor);
                ifactor=(factor != 1); /* True if a valid factor */
            } /*** End FACTOR ***/
            else if (strncasecmp2(argv[i],"SHIFT",5) == 0)
            {
                i++;
                if (i >= argc) error();
                sscanf(argv[i],"%lf",&xshift);
                i++;
                if (i >= argc) error();
                sscanf(argv[i],"%lf",&yshift);
                iunit=TRUE;
                printf("X Shift: %lg   Y Shift: %lg\n",xshift,yshift);
            } /*** End SHIFT ***/
            else {
                printf("ERROR: Unknown function %s\n",argv[i]);  error();
            }
    }
/* -------------------------------------------------------------------- */
/*	If there is no data in this file let the user know.		*/
/* -------------------------------------------------------------------- */
    openfiles();  /* Open the infile and the outfile for shape and dbf. */
    if( DBFGetFieldCount(hDBF) == 0 )
    {
	puts( "There are no fields in this table!" );
	exit( 1 );
    }
/* -------------------------------------------------------------------- */
/*      Print out the file bounds.                                      */
/* -------------------------------------------------------------------- */
    iRecord = DBFGetRecordCount( hDBF );
    SHPGetInfo( hSHP, NULL, NULL, adfBoundsMin, adfBoundsMax );

    printf( "Input Bounds:  (%lg,%lg) - (%lg,%lg)   Entities: %d   DBF: %d\n",
	    adfBoundsMin[0], adfBoundsMin[1],
            adfBoundsMax[0], adfBoundsMax[1],
            nEntities, iRecord );
	    
    if (strcmp(outfile,"") == 0) /* Describe the shapefile; No other functions */
    {
    	ti = DBFGetFieldCount( hDBF );
	showitems();
	exit(0);
    }
     
    if (iclip) check_theme_bnd();
    
    jRecord = DBFGetRecordCount( hDBFappend );
    SHPGetInfo( hSHPappend, NULL, NULL, adfBoundsMin, adfBoundsMax );
    if (nEntitiesAppend == 0)
        puts("New Output File\n");
    else
        printf( "Append Bounds: (%lg,%lg)-(%lg,%lg)   Entities: %d  DBF: %d\n",
                adfBoundsMin[0], adfBoundsMin[1],
                adfBoundsMax[0], adfBoundsMax[1],
                nEntitiesAppend, jRecord );
    
/* -------------------------------------------------------------------- */
/*	Find matching fields in the append file or add new items.       */
/* -------------------------------------------------------------------- */
    mergefields();
/* -------------------------------------------------------------------- */
/*	Find selection field if needed.                                 */
/* -------------------------------------------------------------------- */
    if (iselect)    findselect();

/* -------------------------------------------------------------------- */
/*  Read all the records 						*/
/* -------------------------------------------------------------------- */
    jRecord = DBFGetRecordCount( hDBFappend );
    for( iRecord = 0; iRecord < nEntities; iRecord++)  /** DBFGetRecordCount(hDBF) **/
    {
/* -------------------------------------------------------------------- */
/*      SELECT for values if needed. (Can the record be skipped.)       */
/* -------------------------------------------------------------------- */
        if (iselect)
            if (selectrec() == 0) goto SKIP_RECORD;   /** SKIP RECORD **/

/* -------------------------------------------------------------------- */
/*      Read a Shape record                                             */
/* -------------------------------------------------------------------- */
        psCShape = SHPReadObject( hSHP, iRecord );

/* -------------------------------------------------------------------- */
/*      Clip coordinates of shapes if needed.                           */
/* -------------------------------------------------------------------- */
        if (iclip)
            if (clip_boundary() == 0) goto SKIP_RECORD; /** SKIP RECORD **/

/* -------------------------------------------------------------------- */
/*      Read a DBF record and copy each field.                          */
/* -------------------------------------------------------------------- */
	for( i = 0; i < DBFGetFieldCount(hDBF); i++ )
	{
/* -------------------------------------------------------------------- */
/*      Store the record according to the type and formatting           */
/*      information implicit in the DBF field description.              */
/* -------------------------------------------------------------------- */
            if (pt[i] > -1)  /* if the current field exists in output file */
            {
                switch( DBFGetFieldInfo( hDBF, i, NULL, &iWidth, &iDecimals ) )
                {
                  case FTString:
                  case FTLogical:
                    DBFWriteStringAttribute(hDBFappend, jRecord, pt[i],
                                            (DBFReadStringAttribute( hDBF, iRecord, i )) );
                    break;

                  case FTInteger:
                    DBFWriteIntegerAttribute(hDBFappend, jRecord, pt[i],
                                             (DBFReadIntegerAttribute( hDBF, iRecord, i )) );
                    break;

                  case FTDouble:
                    DBFWriteDoubleAttribute(hDBFappend, jRecord, pt[i],
                                            (DBFReadDoubleAttribute( hDBF, iRecord, i )) );
                    break;

                  case FTInvalid:
                    break;
                }
            }
	}
	jRecord++;
/* -------------------------------------------------------------------- */
/*      Change FACTOR and SHIFT coordinates of shapes if needed.        */
/* -------------------------------------------------------------------- */
        if (iunit)
        {
	    for( j = 0; j < psCShape->nVertices; j++ ) 
	    {
                psCShape->padfX[j] = psCShape->padfX[j] * factor + xshift;
                psCShape->padfY[j] = psCShape->padfY[j] * factor + yshift;
	    }
        }
        
/* -------------------------------------------------------------------- */
/*      Write the Shape record after recomputing current extents.       */
/* -------------------------------------------------------------------- */
        SHPComputeExtents( psCShape );
        SHPWriteObject( hSHPappend, -1, psCShape );

      SKIP_RECORD:
        SHPDestroyObject( psCShape );
        psCShape = NULL;
        j=0;
    }

/* -------------------------------------------------------------------- */
/*      Print out the # of Entities and the file bounds.                */
/* -------------------------------------------------------------------- */
    jRecord = DBFGetRecordCount( hDBFappend );
    SHPGetInfo( hSHPappend, &nEntitiesAppend, &nShapeTypeAppend,
                adfBoundsMin, adfBoundsMax );
    
    printf( "Output Bounds: (%lg,%lg) - (%lg,%lg)   Entities: %d  DBF: %d\n\n",
	    adfBoundsMin[0], adfBoundsMin[1],
            adfBoundsMax[0], adfBoundsMax[1],
            nEntitiesAppend, jRecord );

/* -------------------------------------------------------------------- */
/*      Close the both shapefiles.                                      */
/* -------------------------------------------------------------------- */
    SHPClose( hSHP );
    SHPClose( hSHPappend );
    DBFClose( hDBF );
    DBFClose( hDBFappend );
    if (nEntitiesAppend == 0) {
        puts("Remove the output files.");
        setext(outfile, "dbf");
        remove(outfile);
        setext(outfile, "shp");
        remove(outfile);
        setext(outfile, "shx");
        remove(outfile);
    }
    return( 0 );
}
コード例 #8
0
ファイル: libdarxenShapefiles.c プロジェクト: darxen/Darxen
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;
}
コード例 #9
0
ファイル: VegLayer.cpp プロジェクト: kamalsirsa/vtp
/**
 * Extract data from a SHP/DBF file and intepret it as a vegetation layer.
 * This produces a single-valued polygonal coverage.
 *
 * 'iField' is the index of the field from which to pull the single value.
 * 'datatype' is either 0, 1, or 2 for whether the indicated field should be
 *		intepreted as a density value (double), the name of a biotype
 *		(string), or the ID of a biotype (int).
 */
bool vtVegLayer::AddElementsFromSHP_Polys(const wxString &filename,
										  const vtProjection &proj,
										  int iField, VegImportFieldType datatype)
{
	// When working with float field data, must use C locale
	ScopedLocale normal_numbers(LC_NUMERIC, "C");

	// SHPOpen doesn't yet support utf-8 or wide filenames, so convert
	vtString fname_local = UTF8ToLocal(filename.mb_str(wxConvUTF8));

	// Open the SHP File
	SHPHandle hSHP = SHPOpen(fname_local, "rb");
	if (hSHP == NULL)
		return false;

	// Get number of polys and type of data
	int		nElem;
	int		nShapeType;
	SHPGetInfo(hSHP, &nElem, &nShapeType, NULL, NULL);

	// Check Shape Type, Veg Layer should be Poly data
	if (nShapeType != SHPT_POLYGON)
		return false;

	// Open DBF File
	DBFHandle db = DBFOpen(fname_local, "rb");
	if (db == NULL)
		return false;

	// Check for field of poly id, current default field in dbf is Id
	int *pnWidth = 0, *pnDecimals = 0;
	char *pszFieldName = NULL;

	DBFFieldType fieldtype = DBFGetFieldInfo(db, iField,
		pszFieldName, pnWidth, pnDecimals );

	if (datatype == VIFT_Density)
	{
		if (fieldtype != FTDouble)
		{
			VTLOG(" Expected the DBF field '%s' to be of type 'Double', but found '%s' instead.\n",
				pszFieldName, DescribeFieldType(fieldtype));
			return false;
		}
	}
	if (datatype == VIFT_BiotypeName)
	{
		if (fieldtype != FTString)
		{
			VTLOG(" Expected the DBF field '%s' to be of type 'String', but found '%s' instead.\n",
				pszFieldName, DescribeFieldType(fieldtype));
			return false;
		}
	}
	if (datatype == VIFT_BiotypeID)
	{
		if (fieldtype != FTInteger)
		{
			VTLOG(" Expected the DBF field '%s' to be of type 'Integer', but found '%s' instead.\n",
				pszFieldName, DescribeFieldType(fieldtype));
			return false;
		}
	}

	// OK, ready to allocate our featureset
	if (datatype == VIFT_Density)
	{
		SetVegType(VLT_Density);
		m_field_density = m_pSet->AddField("Density", FT_Float);
	}
	if (datatype == VIFT_BiotypeName || datatype == VIFT_BiotypeID)
	{
		SetVegType(VLT_BioMap);
		m_field_biotype = m_pSet->AddField("Biotype", FT_Integer);
	}

	SetProjection(proj);

	// Read Polys from SHP into Veg Poly
	m_pSet->LoadGeomFromSHP(hSHP);
	SHPClose(hSHP);

	// Read fields
	int biotype_id;
	for (uint i = 0; i < (uint) nElem; i++)
	{
		int record = m_pSet->AddRecord();
		// Read DBF Attributes per poly
		if (datatype == VIFT_Density)
		{
			// density
			m_pSet->SetValue(record, m_field_density, (float) DBFReadDoubleAttribute(db, i, iField));
		}
		if (datatype == VIFT_BiotypeName)
		{
			const char *str = DBFReadStringAttribute(db, i, iField);
			biotype_id = g_bld->GetBioRegion()->FindBiotypeIdByName(str);
			m_pSet->SetValue(record, m_field_biotype, biotype_id);
		}
		if (datatype == VIFT_BiotypeID)
		{
			biotype_id = DBFReadIntegerAttribute(db, i, iField);
			m_pSet->SetValue(record, m_field_biotype, biotype_id);
		}
	}
	DBFClose(db);
	return true;
}
コード例 #10
0
ファイル: saca_records.c プロジェクト: alffore/SHP2INT
int SacaInfObjeto(char *nomarch, FILE *ae, FILE *aex, int objeto) {

    DBFHandle dbfh = NULL;
    int numcampos, i;
    PInfC pinfc = NULL;
    char *archdbf = NULL;

    char *buff = (char *) calloc(1000, sizeof (char));
    char *buffaux;

    //abre el dbf para lectura
    archdbf = (char*) calloc(strlen(nomarch) + 5, sizeof (char));
    sprintf(archdbf, "%s.dbf", nomarch);
    dbfh = DBFOpen(archdbf, "rb");

    if (dbfh == NULL) {
        fprintf(stderr, "Error no se puede consultar el archivo: %s\n", archdbf);
        if (archdbf)free(archdbf);
        return 0;
    }

    //determina el numero de campos (columnas)
    numcampos = DBFGetFieldCount(dbfh);

    //crea un array de las estructuras InfCampos
    pinfc = (PInfC) calloc(numcampos, sizeof (InfC));

    //recupera la informacion de los campos para cada uno
    for (i = 0; i < numcampos; i++) {
        (pinfc + i)->dbfft = DBFGetFieldInfo(dbfh, i, pinfc->nombre, &(pinfc->largo), &(pinfc->decimales));



        //Imprime el separador de campo
        fprintf(ae, SEP);

        if ((pinfc + i)->dbfft == 0) {
            

            buffaux=(char *)calloc(strlen(DBFReadStringAttribute(dbfh, objeto, i)),sizeof(char));
            fprintf(ae, "%s", limpiaCadena(DBFReadStringAttribute(dbfh, objeto, i),buffaux));
            free(buffaux);

            
/*
            fprintf(ae, "%s", DBFReadStringAttribute(dbfh, objeto, i));
*/
            
            if (bimp_tc == 0) {
                sprintf(buff, "nombre=\"%s\" tipo=\"string\" largo=\"%i\" pos=\"%i\"", pinfc->nombre, (pinfc->largo), numpos);
                imprimeTagMA(aex, "campo", "", buff);
            }
        } else if ((pinfc + i)->dbfft == 1) {
            fprintf(ae, "%i", DBFReadIntegerAttribute(dbfh, objeto, i));
            if (bimp_tc == 0) {
                sprintf(buff, "nombre=\"%s\" tipo=\"int\" largo=\"%i\" deci=\"%i\" pos=\"%i\"", pinfc->nombre, (pinfc->largo), (pinfc->decimales), numpos);
                imprimeTagMA(aex, "campo", "", buff);
            }
        } else if ((pinfc + i)->dbfft == 2) {
            fprintf(ae, "%20.6f", DBFReadDoubleAttribute(dbfh, objeto, i));
            if (bimp_tc == 0) {
                sprintf(buff, "nombre=\"%s\" tipo=\"double\" largo=\"%i\" deci=\"%i\" pos=\"%i\"", pinfc->nombre, (pinfc->largo), (pinfc->decimales), numpos);
                imprimeTagMA(aex, "campo", "", buff);
            }
        }else{
        
        }

        numpos++;
    }

    bimp_tc = 1;



    if (bimp_nc == 0) {
        sprintf(buff, "%i", (numcampos + 3));
        imprimeTag(aex, "ncampos", buff);
        bimp_nc = 1;
    }

    if (pinfc)free(pinfc);

    DBFClose(dbfh);
    if (archdbf)free(archdbf);

    free(buff);

    return 1;
}
コード例 #11
0
ファイル: mex_shape.c プロジェクト: feigl/gipht
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] )
     
{ 

	/* 
	 * Construct error and warning messages using this buffer.  
	 * */
	char error_msg[500];



	int nShapeType, nEntities, i, j;


	int buflen;            /* length of input shapefile name */
	char *shapefile;       /* holder for input shapefile name */
	int status;            /* success or failure */

	/*
	 * Not used.
	 * */
	double adfMinBound[4], adfMaxBound[4];

	/*
	 * pointer to the shapefile
	 * */
	SHPHandle	hSHP;
	SHPObject	*psShape;



	/*
	 * handle for DBF file
	 * */
	DBFHandle     dbh;

	/*
	 * number of DBF attributes, records
	 * */
	int num_dbf_fields, num_dbf_records;


	/*
	 * This structure will hold a description of each field in the DBF file.
	 * */
	typedef struct DBF_Field_Descriptor {
		char          pszFieldName[12];
		DBFFieldType  field_type;
	} DBF_Field_Descriptor;


	DBF_Field_Descriptor *dbf_field;


	/*
	 * stores individual values from the DBF.
	 * */
	double dbf_double_val;
	int dbf_integer_val;
	char *dbf_char_val;

	char error_buffer[500];


	char **att_fnames;             /* holds name of fie */

	/* holds name of fields for the shape structure */
	char *shape_fnames[2] = { "x", "y" };      

	/* holds name of fields for the shape structure */
	char *outstruct_fnames[3]
		= { "Shape", "Attribute", "Type" };  


	/*
	 * Matlab structure to hold all output information.
	 * */
	mxArray *out_struct;

	/*
	 * Matlab structure that holds the point information.
	 *
	 * */
	mxArray *data_struct;
	
	/*
	 * Matlab structure that holds the attribute information.
	 * */
	mxArray *att_struct;
	
	/*
	 * 
	 * */
	mxArray *x_out, *y_out;

	/*
	 * temporary matlab array
	 * */
	mxArray *mxtmp;


	double *x_out_ptr, *y_out_ptr;

	/*
	 * Shortcuts into the output arrays.
	 * */
	double *mx_ptr, *my_ptr;

	int part_start;        /* start of a polygon part */
	int part_count;        /* how many vertices in a polygon part. */

	int dims[2];
	size_t sizebuf;

	/*
	 * This string will describe the type of shapefile.
	 * The possibilities are currently
	 *
	 *     MultiPoint
	 *     Point
	 *     Arc
	 *     Polygon
	 * */
	char *shapeTypeString;

	/*
	 * Initialize the dbf record.
	 * */
	dbf_field = NULL;



	/* Check for proper number of arguments */
	if (nrhs != 1) { 
		mexErrMsgTxt("One input argument is required."); 
	}
	if (nlhs != 1) { 
		mexErrMsgTxt("One output argument is required."); 
	}


	/*
	 * Make sure the input is a proper string.
	 * */
	if ( mxIsChar(prhs[0]) != 1 ) {
		mexErrMsgTxt("Shapefile parameter must be a string\n" );
	}
	if ( mxGetM(prhs[0]) != 1 ) {
		mexErrMsgTxt("Shapefile parameter must be a row vector, not a column string\n" );
	}

	buflen = mxGetN(prhs[0]) + 1; 
	shapefile = mxCalloc ( buflen, sizeof(char) );

	/*
	 * copy the string data from prhs[0] into a C string.
	 * */
	status = mxGetString ( prhs[0], shapefile, buflen );
	if ( status != 0 ) {
		mexErrMsgTxt ( "Not enough space for shapefile argument.\n" );
	}







	/* -------------------------------------------------------------------- */
	/*      Open the passed shapefile.                                      */
	/* -------------------------------------------------------------------- */
	hSHP = SHPOpen( shapefile, "rb" );
	if( hSHP == NULL ) {
		sprintf ( error_msg, "Unable to open:%s\n", shapefile );
		mexErrMsgTxt( error_msg );
	}




	/* -------------------------------------------------------------------- */
	/*      Get the needed information about the shapefile.                 */
	/* -------------------------------------------------------------------- */
	SHPGetInfo( hSHP, &nEntities, &nShapeType, adfMinBound, adfMaxBound );

	

	/*
	 * Make sure that we can handle the type.
	 * */
	switch ( nShapeType ) {
		case SHPT_MULTIPOINT:
		case SHPT_POINT:
		case SHPT_ARC:
		case SHPT_POLYGON:
			break;

		default:
			sprintf ( error_buffer, "Unhandled shape code %d (%s)\n", nShapeType, SHPTypeName ( nShapeType ) );
	        	mexErrMsgTxt( error_buffer ); 

	}
    
	/*
	 * Create the output shape type parameter.  
	 * */
	shapeTypeString = (char *) SHPTypeName ( nShapeType );


	/*
	 * Open the DBF in order to retrieve the number of fields and records.
	 * */
	dbh = DBFOpen (shapefile, "rb");
	num_dbf_fields = DBFGetFieldCount ( dbh );
	num_dbf_records = DBFGetRecordCount ( dbh );


	/*
	 * Allocate space for a description of each record, and populate it.
	 * I allocate space for two extra "dummy" records that go in positions
	 * 0 and 1.  These I reserve for the xy data.
	 * */
	dbf_field = (DBF_Field_Descriptor *) mxCalloc ( num_dbf_fields, sizeof ( DBF_Field_Descriptor ) );
	if ( dbf_field == NULL ) {
		mexErrMsgTxt("Memory allocation for DBF_Field_Descriptor failed."); 
	}


	for ( j = 0; j < num_dbf_fields; ++j ) {
		dbf_field[j].field_type = DBFGetFieldInfo ( dbh, j, dbf_field[j].pszFieldName, NULL, NULL );
	}




	/*
	 * Allocate space for the datapoint structure.
	 * */
	data_struct = mxCreateStructMatrix ( nEntities, 1, 2, (const char **)shape_fnames );


	/*
	 * Allocate space for the field names for the attributes.
	 * According to the API, each field name can have up to 12
	 * characters.
	 * */
	att_fnames = (char **) mxCalloc ( num_dbf_fields, sizeof(char *) );
	if ( att_fnames == NULL ) {
		mexErrMsgTxt("Memory allocation for attribute field names failed."); 
	}

	/*
	 * Copy the attribute names, create the matlab structure.
	 * */
	for ( j = 0; j < num_dbf_fields; ++j ) {
		att_fnames[j] = dbf_field[j].pszFieldName;
	}
	att_struct = mxCreateStructMatrix ( nEntities, 1, num_dbf_fields, (const char **)att_fnames );

    
	/* -------------------------------------------------------------------- */
	/*	Skim over the list of shapes, printing all the vertices.	*/
	/* -------------------------------------------------------------------- */
	for( i = 0; i < nEntities; i++ ) {

		psShape = SHPReadObject( hSHP, i );
		/*
		fprintf ( stdout, "Num parts = %d\n", psShape->nParts );
		*/


		/*
		 * Create the fields in this struct element.
		 * We will stick in one nan for each shape part.
		 */
		dims[0] = psShape->nVertices + psShape->nParts;
		dims[1] = 1;
		x_out = mxCreateNumericArray ( 2, dims, mxDOUBLE_CLASS, mxREAL );
		x_out_ptr = mxGetData ( x_out );
		y_out = mxCreateNumericArray ( 2, dims, mxDOUBLE_CLASS, mxREAL );
		y_out_ptr = mxGetData ( y_out );



		/*
		 * Just copy the verticies over.
		 * */
		sizebuf = mxGetElementSize ( x_out ) * psShape->nVertices;

		mx_ptr = x_out_ptr;
		my_ptr = y_out_ptr;


		for ( j = 0; j < psShape->nParts-1; ++j ) {

			part_count = psShape->panPartStart[j+1] - psShape->panPartStart[j];
			sizebuf = mxGetElementSize ( x_out ) * part_count;

			part_start = psShape->panPartStart[j];
			memcpy ( (void *) (mx_ptr), (void *) &(psShape->padfX[part_start]), sizebuf );
			memcpy ( (void *) (my_ptr), (void *) &(psShape->padfY[part_start]), sizebuf );

			/*
			 * Stick a nan here to separate the parts.
			 * */
			mx_ptr[part_count] = mxGetNaN();
			my_ptr[part_count] = mxGetNaN();

			/*
			 * Update the pointers to the next part.
			 * */
			mx_ptr += (part_count+1);
			my_ptr += (part_count+1);

		}


		/*
		 * Do the last one
		 *
		 * Special case if there is only a single point?  
		 * */
		if ( psShape->nParts == 0 ) {
			memcpy ( (void *) (mx_ptr), (void *) &(psShape->padfX[0]), sizebuf );
			memcpy ( (void *) (my_ptr), (void *) &(psShape->padfY[0]), sizebuf );
		} else {

			part_count = psShape->nVertices - psShape->panPartStart[psShape->nParts-1];
			sizebuf = mxGetElementSize ( x_out ) * part_count;
	
			part_start = psShape->panPartStart[psShape->nParts-1];
			memcpy ( (void *) (mx_ptr), (void *) &(psShape->padfX[part_start]), sizebuf );
			memcpy ( (void *) (my_ptr), (void *) &(psShape->padfY[part_start]), sizebuf );

			/*
			 * Stick a nan here to separate the parts.
			 * */
			mx_ptr[part_count] = mxGetNaN();
			my_ptr[part_count] = mxGetNaN();

		}


		mxSetField ( data_struct, i, "x", x_out );
		mxSetField ( data_struct, i, "y", y_out );






		/*
		 * Now do the attributes
		 * */
		for ( j = 0; j < num_dbf_fields; ++j ) {
			switch ( dbf_field[j].field_type ) {
				case FTString:
					dbf_char_val = (char *) DBFReadStringAttribute ( dbh, i, j );
					mxtmp = mxCreateString ( dbf_char_val );
					mxSetField ( att_struct, i, dbf_field[j].pszFieldName, mxtmp );
					break;

				case FTDouble:
					dbf_double_val = DBFReadDoubleAttribute ( dbh, i, j );
					mxtmp = mxCreateDoubleScalar ( dbf_double_val );
					mxSetField ( att_struct, i, dbf_field[j].pszFieldName, mxtmp );
					break;

				case FTInteger:
				case FTLogical:
					dbf_integer_val = DBFReadIntegerAttribute ( dbh, i, j );
					dbf_double_val = dbf_integer_val;
					mxtmp = mxCreateDoubleScalar ( dbf_double_val );
					mxSetField ( att_struct, i, dbf_field[j].pszFieldName, mxtmp );
					break;

				default:
					sprintf ( error_buffer, "Unhandled code %d, shape %d, record %d\n", dbf_field[j].field_type, i, j );
	        			mexErrMsgTxt("Unhandled code"); 

			}
		}


        SHPDestroyObject( psShape );

	}



	/*
	 * Clean up, close up shop.
	 * */
	SHPClose( hSHP );

	DBFClose ( dbh );




	/*
	 * Allocate space for the output structure.
	 * */
	out_struct = mxCreateStructMatrix ( 1, 1, 3, (const char **)outstruct_fnames );

	/*
	 * Set the fields properly.
	 * */
	mxSetField ( out_struct, 0, "Shape", data_struct );
	mxSetField ( out_struct, 0, "Attribute", att_struct );
	mxSetField ( out_struct, 0, "Type", mxCreateString ( shapeTypeString ) );

	plhs[0] = out_struct;
	return;

}
コード例 #12
0
ファイル: dbfcat.c プロジェクト: OpendTect/shapelib
int main( int argc, char ** argv )

{
    DBFHandle	hDBF;
    int		*panWidth, i, iRecord;
    char	szFormat[32], szField[1024];
    char	cTitle[32], nTitle[32];
    int		nWidth, nDecimals;
    int		cnWidth, cnDecimals;
    DBFHandle	cDBF;
    DBFFieldType	hType,cType;
    int		ci, ciRecord;
    char	tfile[160];
    int		hflds, j, cflds;
    int 	verbose				= 0;
    int		force 				= 0;
    int		mismatch			= 0;
    int		matches				= 0;
    char	fld_m[256];
    int		shift = 0;
    char	type_names[4][15] = {"integer", "string", "double", "double"};

    if( argc < 3 )
    {
	printf( "dbfcat [-v] [-f] from_DBFfile to_DBFfile\n" );
	exit( 1 );
    }


    if ( strcmp ("-v", argv[1] ) == 0 ) { shift = 1; verbose = 1; }
    if ( strcmp ("-f", argv[1 + shift] ) == 0 ) { shift ++; force = 1; }
    if ( strcmp ("-v", argv[1 + shift] ) == 0 ) { shift ++; verbose = 1; }
    strcpy (tfile, argv[1 + shift]);
    strcat (tfile, ".dbf"); 
    hDBF = DBFOpen( tfile, "rb" );
    if( hDBF == NULL )
    {
	printf( "DBFOpen(%s.dbf,\"r\") failed for From_DBF.\n", tfile );
	exit( 2 );
    }

    strcpy (tfile, argv[2 + shift]);
    strcat (tfile, ".dbf"); 

    cDBF = DBFOpen( tfile, "rb+" );
    if( cDBF == NULL )
    {
	printf( "DBFOpen(%s.dbf,\"rb+\") failed for To_DBF.\n", tfile );
	exit( 2 );
    }
    
    
    if( DBFGetFieldCount(hDBF) == 0 )
    {
	printf( "There are no fields in this table!\n" );
	exit( 3 );
    }

    hflds = DBFGetFieldCount(hDBF);
    cflds = DBFGetFieldCount(cDBF);

    matches = 0;
    for( i = 0; i < hflds; i++ )
    {
	char		szTitle[18];
	char		cname[18];
	int		j;
	hType = DBFGetFieldInfo( hDBF, i, szTitle, &nWidth, &nDecimals );
	fld_m[i] = -1;
        for ( j = 0; j < cflds; j ++ )
          { 
            cType = DBFGetFieldInfo( cDBF, j, cname, &cnWidth, &cnDecimals );
            if ( strcmp (cname, szTitle) == 0 ) 
	     { 
        	if ( hType != cType ) 
            	{ printf ("Incompatible fields %s(%s) != %s(%s),\n",
             	   type_names[hType],nTitle,type_names[cType],cTitle);
			mismatch = 1;
              		}
	        fld_m[i] = j;
		if ( verbose ) 
         	  { printf("%s  %s(%d,%d) <- %s  %s(%d,%d)\n", cname, type_names[cType],
         	  		cnWidth, cnDecimals,
         	       szTitle, type_names[hType], nWidth, nDecimals); }
	        j = cflds;
	        matches = 1;
	      }
	  }
    }

    if ( (matches == 0 ) && !force ) {
      printf ("ERROR: No field names match for tables, cannot proceed\n   use -f to force processing using blank records\n");
      exit(-1); }
    if ( mismatch && !force ) {
      printf ("ERROR: field type mismatch cannot proceed\n    use -f to force processing using attempted conversions\n");
      exit(-1); }

    for( iRecord = 0; iRecord < DBFGetRecordCount(hDBF); iRecord++ )
    {
      ciRecord = DBFGetRecordCount( cDBF );
      for ( i = 0; i < hflds;i ++ )
	{	
	double	cf;
	ci = fld_m[i];
	if ( ci != -1 )
	{
	cType = DBFGetFieldInfo( cDBF, ci, cTitle, &cnWidth, &cnDecimals );
	hType = DBFGetFieldInfo( hDBF, i, nTitle, &nWidth, &nDecimals );

	    switch( cType )
	    {
	      case FTString:
	        DBFWriteStringAttribute(cDBF, ciRecord, ci,
     			(char *) DBFReadStringAttribute( hDBF, iRecord, i ) );
		break;

	      case FTInteger:
	    	DBFWriteIntegerAttribute(cDBF, ciRecord, ci, 
			(int) DBFReadIntegerAttribute( hDBF, iRecord, i ) );
		break;

	      case FTDouble:
/*	        cf = DBFReadDoubleAttribute( hDBF, iRecord, i );
	        printf ("%s <-  %s (%f)\n", cTitle, nTitle, cf);
*/
	    	DBFWriteDoubleAttribute(cDBF, ciRecord, ci, 
			(double) DBFReadDoubleAttribute( hDBF, iRecord, i ) );
		break;
	    }
	  }
	}   /* fields names match */
    }

    if ( verbose ) { printf (" %d records appended \n\n", iRecord); }
    DBFClose( hDBF );
    DBFClose( cDBF );

    return( 0 );
}
コード例 #13
0
ファイル: shptriangle.c プロジェクト: sdteffen/dcwaterdesign
/**
 * Create Delaunay shape files using Triangle.
 * @param argc is the number of arguments provided from the command line 
 * (including the command name).
 * @param argv is an array of strings that contains the argc arguments.
 * @return An error code if something goes wrong or 0 if there was no error
 * during the conversion process.
 */
int main( int argc, char **argv ) {
  int error;
  char line[MAXLINE];
  char wline[MAXLINE];
  char *textpointer = NULL, *prev_textpointer = NULL;
  int nPolygons;
  int nShapeType, nEntities, nVertices, nParts, *panParts, i, j, iPart;
  int nNodes, nNodeRef;
  SHPObject *psCShape;
  int byRing = 1;
  char boolWriteShape;
  int nShapes = 0;
  double padfMinBound[4];
  double padfMaxBound[4];
  int nDcidIndex = -1;
  char *pDCID;
  /**
   * Vectors to calculate plane parameters
   */
  double vector0[3];
  double vector1[3];
  /**
   * Plane parameters
   */
  double a,b,c,d;
  /**
   * Slope of the plane
   */
  double slope;
  /**
   * Elevation field (if provided)
   */
  int nElevationField = -1; 
 
  strcpy(vertex_line_name, "");
  num_vertices = 0;
  
  /* parameter check */
  if((((argc != 3)||
    ((!str_is_shp(argv[1])||(!str_is_shp(argv[2]))))))&&((argc != 4)||
    ((!str_is_shp(argv[1])||(!str_is_shp(argv[2])))))) {
    printf("shptriangle 0.1.0 (c) 2005,2006 Steffen Macke\n");
    printf("usage: shptriangle input_shapefile delaunay_shapefile [elevationfield]\n");
    exit(1);
  }
  remove_shp(argv[2]);
  
  hPointSHP = SHPOpen(argv[1], "rb" );
  hPointDBF = DBFOpen(argv[1], "rb");
  if(hPointSHP == NULL || hPointDBF == NULL ) {
    printf("FATAL ERROR: Unable to open input file:%s\n", argv[1] );
    exit(1);
  }
  SHPGetInfo(hPointSHP, &nEntities, &nShapeType, padfMinBound, padfMaxBound);
  if(nShapeType != SHPT_POINT) {
    printf("FATAL ERROR: Input is not a point shapefile:%s\n", argv[1]);
    SHPClose(hPointSHP);
    DBFClose(hPointDBF);
    exit(1);
  }
  if(4 == argc) {
    nElevationField = DBFGetFieldIndex(hPointDBF, argv[3]);
    if(-1 == nElevationField) {
      printf("WARNING: Could not find elevation field '%s'.\n", argv[3]);
    }
  }
  if(nEntities > MAXNUMNODES) {
    printf("FATAL ERROR: Too many nodes. Please recompile.\n");
    SHPClose(hPointSHP);
    DBFClose(hPointDBF);
    exit(1);
  }
  /**
   * \todo Dynamic filename
   */
  hTextFile = fopen("shptriangle.node", "wt");
  if(hTextFile == NULL) {
    printf("FATAL ERROR: Cannot open output file:%s\n", "shptriangle.node");
    SHPClose(hPointSHP);
    DBFClose(hPointDBF);
    exit(1);
  }
  fprintf(hTextFile, "%d 2 0 0\n", nEntities);
  for(i=0; i<nEntities;i++) {
    psCShape = SHPReadObject(hPointSHP, i);
    fprintf(hTextFile, "%d %f %f\n", i+1, psCShape->dfXMin, psCShape->dfYMin);
    node_x[i] = psCShape->dfXMin;
    node_y[i] = psCShape->dfYMin;
    if(nElevationField > -1) {
      node_z[i] = DBFReadDoubleAttribute(hPointDBF, i, nElevationField);
    } else {
      node_z[i] = 0.0;
    }
  }
 
  fclose(hTextFile);
  SHPClose(hPointSHP);
  DBFClose(hPointDBF);
  system("triangle.exe -I shptriangle");
  
  hTextFile = fopen("shptriangle.ele", "rt");
  if(hTextFile == NULL) {
    printf("FATAL ERROR: Cannot open input file:%s\n", "shptriangle.ele");
    exit(1);
  }
  if(fgets(line, MAXLINE, hTextFile) == NULL) {
    printf("FATAL ERROR: Reading first line of shptriangle.ele\n");
    fclose(hTextFile);
    exit(1);
  }
  nPolygons = atoi(line);
  textpointer = strchr(line, ' ');
  num_vertices = atoi(textpointer);
  if(num_vertices != 3) {
    printf("FATAL ERROR: Wrong node count in first line of shptriangle.ele\n");
    fclose(hTextFile);
    exit(1);
  }
  //printf("%s\n", line);
  
  if(num_vertices > MAXNUMNODES) {
    printf("FATAL ERROR: Too many nodes, please recompile: %d\n", num_vertices);
    fclose(hTextFile);
    exit(1);
  }
  //printf("%d nodes\n", num_vertices);
  //printf("%d polygons\n", nPolygons);
  
  hVoronoiSHP = SHPCreate(argv[2], SHPT_POLYGONZ);
  hVoronoiDBF = DBFCreate(argv[2]);
  hPointDBF = DBFOpen(argv[1], "rb");
  if(hVoronoiSHP == NULL || hVoronoiDBF == NULL || hPointDBF == NULL) {
    fprintf(stderr, "FATAL ERROR: Unable to create file '%s'.\n", 
      argv[2]);
    fclose(hTextFile);  
    exit(1);
  }
  DBFAddField(hVoronoiDBF, "dc_id", FTString, 16, 0);
  DBFAddField(hVoronoiDBF, "slope", FTDouble, 16, 8);
  for(i=0; i < nPolygons; i++) {
    //printf("Polygon %d\n", i);
    if(fgets(line, MAXLINE, hTextFile) == NULL) {
      printf("FATAL ERROR: shptriangle.ele does not contain enough polygons.\n");
      SHPClose(hVoronoiSHP);
      DBFClose(hVoronoiDBF);
      DBFClose(hPointDBF);
      fclose(hTextFile);
      exit(1);
    }
    nNodes = 0;
    textpointer = line;
    textpointer = strchr(strpbrk(line, "1234567890"), ' ');
    boolWriteShape = 1;
    for(j=0; j < num_vertices; j++) {
      textpointer = strpbrk(strchr(textpointer+1, ' '), "1234567890");
      nNodes++;
      nNodeRef = atoi(textpointer);
      if((nNodeRef < 0)||(nNodeRef > nEntities)) {
        printf("FATAL ERROR: shptriangle.ele contains illegal node reference.\n");
        SHPClose(hVoronoiSHP);
        DBFClose(hVoronoiDBF);
	DBFClose(hPointDBF);
        fclose(hTextFile);
        exit(1);
      }
      //printf("Node reference %d\n", nNodeRef);
      polygon_x[nNodes-1] = node_x[nNodeRef-1];
      polygon_y[nNodes-1] = node_y[nNodeRef-1];
      polygon_z[nNodes-1] = node_z[nNodeRef-1];
    }
    if(boolWriteShape == 1) {
      nNodes++;
      polygon_x[nNodes-1] = polygon_x[0];
      polygon_y[nNodes-1] = polygon_y[0];
      polygon_z[nNodes-1] = polygon_z[0];
      //printf("Polygon %d with %d nodes\n", i, nNodes);
      psCShape = SHPCreateSimpleObject( SHPT_POLYGONZ, nNodes, polygon_x, 
        polygon_y, polygon_z );
      SHPWriteObject(hVoronoiSHP, -1, psCShape);
      SHPDestroyObject(psCShape);
      DBFWriteStringAttribute(hVoronoiDBF, nShapes, 0, "");
      /**
       * Calculate slope.
       * Plane equation 0 = a*x + b*y + c*z + d
       * Sea level plane 0 = 0*x + 0*y + 1*z - 0 
       */
      vector0[0] = polygon_x[1] - polygon_x[0];
      vector0[1] = polygon_y[1] - polygon_y[0];
      vector0[2] = polygon_z[1] - polygon_z[0];
      
      vector1[0] = polygon_x[2] - polygon_x[0];
      vector1[1] = polygon_y[2] - polygon_y[0];
      vector1[2] = polygon_z[2] - polygon_z[0];

      /**
       * Use cross product to find plane equation. 
       */
      a = vector0[1] * vector1[2] - vector0[2] * vector1[1];
      b = -(vector0[0] * vector1[2] - vector0[2] * vector1[0]);
      c = vector0[0] * vector1[1] - vector0[1] * vector1[0];
      d = -(a * polygon_x[0] + b * polygon_y[0] + c * polygon_z[0]);
      /**
       * Calculate dihedral angle between sea level plane and triangle plane
       */
      slope = acos(c/(sqrt(a*a+b*b+c*c)))/3.141592654*180;
      DBFWriteDoubleAttribute(hVoronoiDBF, nShapes, 1, slope);
      nShapes++;
    }
 }
 SHPClose(hVoronoiSHP);
 DBFClose(hVoronoiDBF);
 DBFClose(hPointDBF);
 fclose(hTextFile);
}  
コード例 #14
0
ファイル: load_shapefile.cpp プロジェクト: julian1/shell
int load_shape_attributes( const std::string & filename, IShapeAttributeLoadCallback & callback ) 
{
	std::vector< std::string>	fields;   

    DBFHandle	hDBF;
    int		*panWidth, i, iRecord;
    char	szFormat[32];

	const char * pszFilename = NULL;

    int		nWidth, nDecimals;
//    int		bHeader = 0;
//    int		bRaw = 0;
//    int		bMultiLine = 0;
    char	szTitle[12];

//	fprintf( stdout, "load_shape_attributes\n" );
//	fflush( stdout);


/* -------------------------------------------------------------------- */
/*      Handle arguments.                                               */
/* -------------------------------------------------------------------- */

//	bMultiLine = 1;
#if 0
    for( i = 1; i < argc; i++ )
    {
        if( strcmp(argv[i],"-h") == 0 )
            bHeader = 1;
        else if( strcmp(argv[i],"-r") == 0 )
            bRaw = 1;
        else if( strcmp(argv[i],"-m") == 0 )
            bMultiLine = 1;
        else
            pszFilename = argv[i];
    }
#endif

/* -------------------------------------------------------------------- */
/*      Display a usage message.                                        */
/* -------------------------------------------------------------------- */



     pszFilename = filename.c_str(); 
#if 0
    if( pszFilename == NULL )
    {
	printf( "dbfdump [-h] [-r] [-m] xbase_file\n" );
        printf( "        -h: Write header info (field descriptions)\n" );
        printf( "        -r: Write raw field info, numeric values not reformatted\n" );
        printf( "        -m: Multiline, one line per field.\n" );
	exit( 1 );
    }
#endif
/* -------------------------------------------------------------------- */
/*      Open the file.                                                  */
/* -------------------------------------------------------------------- */
    hDBF = DBFOpen( pszFilename, "rb" );
    if( hDBF == NULL )
    {
	printf( "DBFOpen(\"r\") failed.\n" );
	exit( 2 );
    }
	else
	{
	//	fprintf( stdout, "opened dbf file\n"  ); 
	} 
/* -------------------------------------------------------------------- */
/*	If there is no data in this file let the user know.		*/
/* -------------------------------------------------------------------- */
    if( DBFGetFieldCount(hDBF) == 0 )
    {
		printf( "There are no fields in this table!\n" );
		exit( 3 );
    }

/* -------------------------------------------------------------------- */
/*	Dump header definitions.					*/
/* -------------------------------------------------------------------- */

#if 0
    if( bHeader )
    {
        for( i = 0; i < DBFGetFieldCount(hDBF); i++ )
        {
            DBFFieldType	eType;
            const char	 	*pszTypeName;

            eType = DBFGetFieldInfo( hDBF, i, szTitle, &nWidth, &nDecimals );
            if( eType == FTString )
                pszTypeName = "String";
            else if( eType == FTInteger )
                pszTypeName = "Integer";
            else if( eType == FTDouble )
                pszTypeName = "Double";
            else if( eType == FTInvalid )
                pszTypeName = "Invalid";

            printf( "Field %d: Type=%s, Title=`%s', Width=%d, Decimals=%d\n",
                    i, pszTypeName, szTitle, nWidth, nDecimals );
        }
    }
#endif
/* -------------------------------------------------------------------- */
/*	Compute offsets to use when printing each of the field 		*/
/*	values. We make each field as wide as the field title+1, or 	*/
/*	the field value + 1. 						*/
/* -------------------------------------------------------------------- */

#if 0
    panWidth = (int *) malloc( DBFGetFieldCount( hDBF ) * sizeof(int) );

    for( i = 0; i < DBFGetFieldCount(hDBF) && !bMultiLine; i++ )
    {
	DBFFieldType	eType;

	eType = DBFGetFieldInfo( hDBF, i, szTitle, &nWidth, &nDecimals );
	if( strlen(szTitle) > nWidth )
	    panWidth[i] = strlen(szTitle);
	else
	    panWidth[i] = nWidth;

	if( eType == FTString )
	    sprintf( szFormat, "%%-%ds ", panWidth[i] );
	else
	    sprintf( szFormat, "%%%ds ", panWidth[i] );
	printf( szFormat, szTitle );
    }
    printf( "\n" );

#endif

/* -------------------------------------------------------------------- */
/*	Read all the records 						*/
/* -------------------------------------------------------------------- */

	// loop the field names       
	for( i = 0; i < DBFGetFieldCount(hDBF); i++ )
	{
		DBFFieldType	eType;
		eType = DBFGetFieldInfo( hDBF, i, szTitle, &nWidth, &nDecimals );
	//	 printf( "name %s: ", szTitle );

		fields.push_back( szTitle  ) ; 
	}	

 

    for( iRecord = 0; iRecord < DBFGetRecordCount(hDBF); iRecord++ )
    {

//		std::cout << "iRecord " << iRecord << std::endl;

		//records.push_back( std::vector< std::string> ()  ) ; 

//        if( bMultiLine )
       
//		 printf( "Record: %d\n", iRecord );
 
		// loop the fields       
		for( i = 0; i < DBFGetFieldCount(hDBF); i++ )
		{
			DBFFieldType	eType;
            
            eType = DBFGetFieldInfo( hDBF, i, szTitle, &nWidth, &nDecimals );

        //      printf( "name %s: ", szTitle );

 //           if( bMultiLine )
  //          {
   //         }
            
/* -------------------------------------------------------------------- */
/*      Print the record according to the type and formatting           */
/*      information implicit in the DBF field description.              */
/* -------------------------------------------------------------------- */
            //if( !bRaw )

			if( DBFIsAttributeNULL( hDBF, iRecord, i ) )
			{

				//	callback.add_attr( iRecord, fields.at( i), (void *)0 );  

			}
			else
			{
				switch( eType )
				{
					case FTString:
					{
						// sprintf( szFormat, "string %%-%ds", nWidth );

						const char *value  =  DBFReadStringAttribute( hDBF, iRecord, i );
						//fprintf( stdout, "str '%s'", s );
						//printf( szFormat, DBFReadStringAttribute( hDBF, iRecord, i ) );
	
						// do we have to free the memory....
			
						callback.add_attr( iRecord, fields.at( i), std::string( value ));  
						break;
					}
					case FTInteger:
					{
					/*	
						sprintf( szFormat, "integer %%%dd", nWidth );
						printf( szFormat, DBFReadIntegerAttribute( hDBF, iRecord, i ) );
					*/
						int value = DBFReadIntegerAttribute( hDBF, iRecord, i ); 
						callback.add_attr( iRecord, fields.at( i), value );  
						break;
					}
					case FTDouble:
					{
						/*
						sprintf( szFormat, "double %%%d.%dlf", nWidth, nDecimals );
						printf( szFormat, DBFReadDoubleAttribute( hDBF, iRecord, i ) );
						*/

						double value = DBFReadDoubleAttribute( hDBF, iRecord, i ); 
						callback.add_attr( iRecord, fields.at( i), value );  
						break;
					}	
					 default:
						assert( 0);
					break;
				}
			}
            

/* -------------------------------------------------------------------- */
/*      Just dump in raw form (as formatted in the file).               */
/* -------------------------------------------------------------------- */
#if 0
            else
            {
                sprintf( szFormat, "%%-%ds", nWidth );
                printf( szFormat, 
                        DBFReadStringAttribute( hDBF, iRecord, i ) );
            }
#endif
/* -------------------------------------------------------------------- */
/*      Write out any extra spaces required to pad out the field        */
/*      width.                                                          */
/* -------------------------------------------------------------------- */
#if 0
	    if( !bMultiLine )
	    {
		sprintf( szFormat, "%%%ds", panWidth[i] - nWidth + 1 );
		printf( szFormat, "" );
	    }

            if( bMultiLine )
#endif

#if 0
		printf( "\n" );
	    fflush( stdout );
#endif
		}
//	printf( "\n" );
    }