Esempio n. 1
0
    inline Tags parseTags(DBFHandle dbfFile, int k) const
    {
        char title[12];
        int fieldCount = DBFGetFieldCount(dbfFile);
        Tags tags;
        tags.reserve(fieldCount);
        for (int i = 0; i < fieldCount; i++)
        {
            if (DBFIsAttributeNULL(dbfFile, k, i))
                continue;

            utymap::formats::Tag tag;
            int width, decimals;
            DBFFieldType eType = DBFGetFieldInfo(dbfFile, i, title, &width, &decimals);
            tag.key = std::string(title);
            {
                switch (eType)
                {
                    case FTString:
                        tag.value = DBFReadStringAttribute(dbfFile, k, i);
                        break;
                    case FTInteger:
                        tag.value = to_string(DBFReadIntegerAttribute(dbfFile, k, i));
                        break;
                    case FTDouble:
                        tag.value = to_string(DBFReadDoubleAttribute(dbfFile, k, i));
                        break;
                    default:
                        break;
                }
            }
            tags.push_back(tag);
        }
        return std::move(tags);
    }
Esempio n. 2
0
bool ShapelibProxy::getFieldAttributes(const ShapelibHandle &handle, std::string &name,
                                       std::string &type, std::string &value, int field, int feature)
{
   char cname[12]; // defined as maximum length
   DBFFieldType fieldType = DBFGetFieldInfo(handle.getDbfHandle(), field, cname, NULL, NULL);
   
   name = cname;

   switch (fieldType)
   {
   case FTString:
      type = "String";
      value = DBFReadStringAttribute(handle.getDbfHandle(), feature, field);
      break;
   case FTInteger:
      type = "Integer";
      value = boost::lexical_cast<std::string>(
         DBFReadIntegerAttribute(handle.getDbfHandle(), feature, field));
      break;
   case FTDouble:
      type = "Double";
      value = boost::lexical_cast<std::string>(
         DBFReadDoubleAttribute(handle.getDbfHandle(), feature, field));
      break;
   default:
      type = "Unknown";
      value = "[Error: Not stringable]";
      return false;
   }

   return true;
}
Esempio n. 3
0
int selectrec()
{
    long int value, ty;

    ty = DBFGetFieldInfo( hDBF, iselectitem, NULL, &iWidth, &iDecimals);
    switch(ty)
    {
      case FTString:
        puts("Invalid Item");
        iselect=FALSE;
	break;
      case FTInteger:
        value = DBFReadIntegerAttribute( hDBF, iRecord, iselectitem );
        for (j = 0; j<selcount; j++)
        {
            if (selectvalues[j] == value)
            {
                if (iunselect) return(0);  /* Keep this record */
                else  return(1);  /* Skip this record */
            }
        }
	break;
      case FTDouble:
        puts("Invalid Item");
        iselect=FALSE;
        break;
    }
    if (iunselect) return(1);  /* Skip this record */
    else  return(0);  /* Keep this record */
}
Esempio n. 4
0
//  Function to read outlets from a shapefile - overloaded to return an array of integer ID's
int readoutlets(char *outletsfile, int *noutlets, double*& x, double*& y, int*& id)
{
	SHPHandle shp = SHPOpen(outletsfile, "rb");
	char dbffile[MAXLN];
	nameadd(dbffile, outletsfile, ".dbf");
	DBFHandle dbf = DBFOpen(dbffile, "rb");
	if ((shp != NULL) && (dbf != NULL)) {
		int nEntities = 0;
		int nShapeType = 0;
		SHPGetInfo(shp, &nEntities, &nShapeType, NULL, NULL );
		if (nShapeType != SHPT_POINT)
		{
			fprintf(stderr, "Outlets shapefile %s is not a point shapefile\n", outletsfile);
			fflush(stderr);
			return 1;
		}
	long p_size;
	long countPts = 0;

	int nfld = DBFGetFieldCount(dbf);
	//int idfld = DBFGetFieldIndex(dbf, "id");
	int idfld = DBFGetFieldIndex(dbf, "OBJECTID"); // ZhuLJ, 2015/6/16
	for( int i=0; i<nEntities; i++) {
		SHPObject * shape = SHPReadObject(shp, i);
		countPts += shape->nVertices;
		SHPDestroyObject(shape);
	}
	x = new double[countPts];
	y = new double[countPts];
	if (idfld >= 0)
		id = new int[countPts];
    int nxy=0;
	for( int i=0; i<nEntities; i++) {
		SHPObject * shape = SHPReadObject(shp, i);
		p_size = shape->nVertices;
		for( int j=0; j<p_size; j++) {
			x[nxy] = shape->padfX[j];
			y[nxy] = shape->padfY[j];
			if (idfld >= 0)
			{
				id[nxy] = DBFReadIntegerAttribute(dbf, i, idfld);
			}
			nxy++;
		}
		SHPDestroyObject(shape);
	}
	*noutlets=nxy;
	SHPClose(shp);
	return 0;
	}
	else { 
		fprintf(stderr, "Error opening outlets shapefile: %s\n", outletsfile);
		fflush(stderr);
		return 1;
	}	
}
// ---------------------------------------------------------------------------
// 
// -----------
int	bDBFTable::ReadVal(int o, int f, void* val){
int	sgn;
	(void)FieldSign(f,&sgn);
	switch(sgn){
		case _int:
			(*(int*)val)=DBFReadIntegerAttribute(_dbf,o-1,f-1);
			break;
		case _double:
			(*(double*)val)=DBFReadDoubleAttribute(_dbf,o-1,f-1);
			break;
		case _char:
			strcpy((char*)val,DBFReadStringAttribute(_dbf,o-1,f-1));
			break;
		default:
			return(-1);
	}
	return(0);
}
Esempio n. 6
0
static Tcl_Obj *
NewAttributeObj (DBFHandle const dbfHandle, int const record, int const field)
{
  if (DBFIsAttributeNULL (dbfHandle, record, field))
    {
      return Tcl_NewObj ();
    }
  switch (DBFGetFieldInfo (dbfHandle, field, NULL, NULL, NULL))
    {
    case FTInteger:
      return Tcl_NewIntObj (DBFReadIntegerAttribute (dbfHandle, record, field));
    case FTDouble:
      return
        Tcl_NewDoubleObj (DBFReadDoubleAttribute (dbfHandle, record, field));
    default:
      return
        Tcl_NewStringObj (DBFReadStringAttribute (dbfHandle, record, field),
                          -1);
    }
}
Esempio n. 7
0
static void
SetAttributeObj (Tcl_Obj * const objPtr, DBFHandle const dbfHandle,
                 int const record, int const field)
{
  if (DBFIsAttributeNULL (dbfHandle, record, field))
    {
      return;
    }
  switch (DBFGetFieldInfo (dbfHandle, field, NULL, NULL, NULL))
    {
    case FTInteger:
      Tcl_SetIntObj (objPtr,
                     DBFReadIntegerAttribute (dbfHandle, record, field));
      break;
    case FTDouble:
      Tcl_SetDoubleObj (objPtr,
                        DBFReadDoubleAttribute (dbfHandle, record, field));
      break;
    default:
      Tcl_SetStringObj (objPtr,
                        DBFReadStringAttribute (dbfHandle, record, field), -1);
    }
}
Esempio n. 8
0
static void SplitCoastlines2( int show, struct source *arc, SHPHandle shp_arc_out, DBFHandle dbf_arc_out )
{
  int count = arc->shape_count;
  for( int i=0; i<count; i++ )
  {
    SHPObject *obj = source_get_shape( arc, i );
    int way_id = DBFReadIntegerAttribute( arc->dbf, i, 2 );
    
    if( obj->nVertices <= MAX_NODES_PER_ARC )
    {
      int new_id = SHPWriteObject( shp_arc_out, -1, obj );
      if( new_id < 0 ) { fprintf( stderr, "Output failure: %m\n"); exit(1); }
      DBFWriteIntegerAttribute( dbf_arc_out, new_id, 0, way_id );
      DBFWriteIntegerAttribute( dbf_arc_out, new_id, 1, show );
      DBFWriteIntegerAttribute( dbf_arc_out, new_id, 2, obj->nVertices < 4 );  /* Flag not real objects */
      source_release_shape(arc, obj);
      continue;
    }
    int arcs = (obj->nVertices / MAX_NODES_PER_ARC) + 1;
    int len = (obj->nVertices / arcs) + 1;
//    printf( "Splitting object with %d vertices, len=%d, arcs=%d\n", obj->nVertices, len, arcs );
    
    for( int j=0; j<arcs; j++ )
    {
      int this_len = (j==arcs-1)? obj->nVertices - (j*len): len+1;
//      printf( "Subobject start=%d, length=%d\n", j*len, this_len );
      SHPObject *new_obj = SHPCreateSimpleObject( SHPT_ARC, this_len, &obj->padfX[j*len], &obj->padfY[j*len], &obj->padfZ[j*len] );
      int new_id = SHPWriteObject( shp_arc_out, -1, new_obj );
      if( new_id < 0 ) { fprintf( stderr, "Output failure: %m\n"); exit(1); }
      DBFWriteIntegerAttribute( dbf_arc_out, new_id, 0, way_id );
      DBFWriteIntegerAttribute( dbf_arc_out, new_id, 1, show );
      DBFWriteIntegerAttribute( dbf_arc_out, new_id, 2, 0 );
      SHPDestroyObject(new_obj);
    }
    source_release_shape(arc, obj);
  }
}
Esempio n. 9
0
std::ostream& rspfShapeDatabase::print(std::ostream& out)const
{
    if(isOpen())
    {
        out << std::setw(15)<<setiosflags(std::ios::left)
            <<"DB filename:" << theFilename << std::endl
            << std::setw(15)<<setiosflags(std::ios::left)
            <<"records:" << theHandle->nRecords << std::endl
            << std::setw(15)<<setiosflags(std::ios::left)
            <<"fields:" << theHandle->nFields << std::endl;
        char name[1024] = {'\0'};
        int width       = 0;
        int decimals    = 0;
        int iField      = 0;
        std::vector<int>         fieldWidths;

        for(iField = 0; iField < theHandle->nFields; ++iField)
        {
            DBFFieldType fieldType = DBFGetFieldInfo(theHandle,
                                     iField,
                                     name,
                                     &width,
                                     &decimals);
            rspfString s = "field " + rspfString::toString(iField+1) + " name:";
            switch(fieldType)
            {
            case FTString:
            case FTInteger:
            case FTDouble:
            {
                out << std::setw(15) << setiosflags(std::ios::left) << s.c_str() << name << std::endl;
                break;
            }
            default:
            {
                out << std::setw(15) << setiosflags(std::ios::left) << s.c_str() << "INVALID"<<std::endl;
                break;
            }
            }
        }
        for(int iShape = 0; iShape < theHandle->nRecords; ++iShape)
        {
            for(iField = 0; iField < theHandle->nFields; ++iField)
            {
                DBFFieldType fieldType = DBFGetFieldInfo(theHandle,
                                         iField,
                                         name,
                                         &width,
                                         &decimals);

                rspfString key = "field";
                key+=rspfString::toString(iField+1);
                key+=(rspfString(".")+name+":");

                switch(fieldType)
                {
                case FTString:
                {

                    out << std::setw(25) << setiosflags(std::ios::left) << key.c_str()
                        << DBFReadStringAttribute(theHandle, iShape, iField) <<std::endl;

                    break;
                }
                case FTInteger:
                {
                    out << std::setw(25) << setiosflags(std::ios::left) << key.c_str()
                        << DBFReadIntegerAttribute(theHandle, iShape, iField) << std::endl;

                    break;
                }
                case FTDouble:
                {
                    out << std::setw(25) << setiosflags(std::ios::left) << key.c_str()
                        << DBFReadDoubleAttribute(theHandle, iShape, iField) << std::endl;

                    break;
                }
                case FTLogical:
                {
                    break;
                }
                case FTInvalid:
                {
                    break;
                }
                }
            }
            out << "_________________________________"<<std::endl;
        }
    }
    return out;
}
Esempio n. 10
0
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 );
}
Esempio n. 11
0
bool rspfShapeDatabase::getRecord(rspfShapeDatabaseRecord& result)
{
    if(isOpen()&&( (theRecordNumber < theHandle->nRecords) ))
    {
        if(result.getNumberOfFields() != theHandle->nFields)
        {
            result.setNumberOfFields(theHandle->nFields);
        }

        char name[1024] = {'\0'};
        int width       = 0;
        int decimals    = 0;
        int iField      = 0;
        std::vector<int>         fieldWidths;

        for(iField = 0; iField < theHandle->nFields; ++iField)
        {
            DBFFieldType fieldType = DBFGetFieldInfo(theHandle,
                                     iField,
                                     name,
                                     &width,
                                     &decimals);
            rspfShapeDatabaseField field;
            field.theName = name;
            field.theWidth = width;
            field.theDecimals = decimals;
            field.theFieldType = fieldType;

            rspfString key = "field";
            key+=rspfString::toString(iField+1);
            key+=(rspfString(".")+name+":");

            switch(fieldType)
            {
            case FTString:
            {
                field.theValue = DBFReadStringAttribute(theHandle, theRecordNumber, iField);
                break;
            }
            case FTInteger:
            {
                field.theValue = rspfString::toString(DBFReadIntegerAttribute(theHandle, theRecordNumber, iField));
                break;
            }
            case FTDouble:
            {
                field.theValue = rspfString::toString(DBFReadDoubleAttribute(theHandle, theRecordNumber, iField));
                break;
            }
            case FTLogical:
            {
                break;
            }
            case FTInvalid:
            {
                break;
            }
            }
            result.setField(field,
                            iField);
        }
        return true;
    }
    return false;
}
Esempio n. 12
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 );
}
Esempio n. 13
0
uint64_t dbf_get_uint_by_field(DBFHandle handle, int row, const char *field_name) {
    return DBFReadIntegerAttribute(handle, row, dbf_get_field_index(handle, row, field_name));
}
Esempio n. 14
0
int load_table(int t)
{
    int i, j, ncols, nrows, dbfcol;
    DBFHandle dbf;
    char *buf;
    ROW *rows;
    VALUE *val;

    G_debug(2, "load_table(): tab = %d", t);

    if (db.tables[t].loaded == TRUE)	/*already loaded */
        return DB_OK;

    dbf = DBFOpen(db.tables[t].file, "r");
    if (dbf == NULL) {
        append_error("Cannot open dbf file.\n");
        return DB_FAILED;
    }

    ncols = db.tables[t].ncols;
    nrows = DBFGetRecordCount(dbf);
    rows = db.tables[t].rows;
    rows = (ROW *) G_malloc(nrows * sizeof(ROW));
    db.tables[t].arows = nrows;

    G_debug(2, "  ncols = %d nrows = %d", ncols, nrows);

    for (i = 0; i < nrows; i++) {
        rows[i].alive = TRUE;
        rows[i].values = (VALUE *) G_calloc(ncols, sizeof(VALUE));

        for (j = 0; j < ncols; j++) {
            val = &(rows[i].values[j]);

            dbfcol = j;

            val->is_null = DBFIsAttributeNULL(dbf, i, dbfcol);
            if (!(val->is_null)) {
                switch (db.tables[t].cols[j].type) {
                case DBF_INT:
                    val->i = DBFReadIntegerAttribute(dbf, i, dbfcol);
                    break;
                case DBF_CHAR:
                    buf = (char *)DBFReadStringAttribute(dbf, i, dbfcol);
                    save_string(val, buf);
                    break;
                case DBF_DOUBLE:
                    val->d = DBFReadDoubleAttribute(dbf, i, dbfcol);
                    break;
                }
            }
        }
    }

    DBFClose(dbf);

    db.tables[t].rows = rows;
    db.tables[t].nrows = nrows;
    db.tables[t].loaded = TRUE;

    return DB_OK;
}
Esempio n. 15
0
//----------------------------------------------------------------------------
int ShapefileReader::RequestData(
                                 vtkInformation* vtkNotUsed( request ),
                                 vtkInformationVector** vtkNotUsed(inputVector),
                                 vtkInformationVector* outputVector)
{
  vtkInformation* outInfo = outputVector->GetInformationObject(0);
  vtkPolyData* polydata = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));

  if (illegalFileName()){
    return 0;
  }

  if (incompleteSrcFiles()){
    return 0;
  }

  SHPHandle shpHandle = SHPOpen(this->FileName, "rb");
  int fileType = 0;

  if (shpHandle == NULL){
    vtkErrorMacro("shp file read failed.");
    return 0;
  }

  vtkDebugMacro("file type: " << shpHandle->nShapeType);

  switch (shpHandle->nShapeType) {
    case SHPT_NULL:
      vtkErrorMacro("NULL Object type." << this->FileName);
      SHPClose(shpHandle);
      return 0;
      break;
    case SHPT_POINT:
    case SHPT_POINTZ:
    case SHPT_POINTM:
    case SHPT_MULTIPOINT:
    case SHPT_MULTIPOINTZ:
    case SHPT_MULTIPOINTM:
      fileType = POINTOBJ;
      break;
    case SHPT_ARC:
    case SHPT_ARCZ:
    case SHPT_ARCM:
      fileType = LINEOBJ;
      break;
    case SHPT_POLYGON:
    case SHPT_POLYGONZ:
    case SHPT_POLYGONM:
      fileType = FACEOBJ;
      break;
    case SHPT_MULTIPATCH:
      fileType = MESHOBJ;
      break;
    default:
      vtkErrorMacro("Unknown Object type." << this->FileName);
      SHPClose(shpHandle);
      return 0;
  }

  int pCount=0, pStart=0, pEnd=0;
  int vTracker = 0, pid=0;
  SHPObject* shpObj;

  vtkSmartPointer<vtkPoints> pts = vtkSmartPointer<vtkPoints>::New();
  vtkSmartPointer<vtkCellArray> polys = vtkSmartPointer<vtkCellArray>::New();
  vtkSmartPointer<vtkCellArray> strips = vtkSmartPointer<vtkCellArray>::New();
  vtkSmartPointer<vtkCellArray> pLines = vtkSmartPointer<vtkCellArray>::New();
  vtkSmartPointer<vtkCellArray> verts = vtkSmartPointer<vtkCellArray>::New();
  vtkSmartPointer<vtkTriangleFilter> tFilter = vtkSmartPointer<vtkTriangleFilter>::New();
  vtkSmartPointer<vtkStripper> stripper = vtkSmartPointer<vtkStripper>::New();
  vtkSmartPointer<vtkPolyData> pdRaw = vtkSmartPointer<vtkPolyData>::New();
  vtkSmartPointer<vtkPolyData> pdRefined = vtkSmartPointer<vtkPolyData>::New();

  //looping through all records in file
  for (int rIndex = 0; rIndex < shpHandle->nRecords; rIndex++){
    
    shpObj = SHPReadObject(shpHandle, rIndex);

    //making sure shp object type is consistent with file type
    if (shpObj->nSHPType != shpHandle->nShapeType){
      vtkErrorMacro("Inconsistent shape type of record: " << rIndex 
        << " in file " << this->FileName);
      continue;
    }

    pCount = shpObj->nParts;
    
    switch (fileType){
    case POINTOBJ:{

      vtkIdType *ids = new vtkIdType[shpObj->nVertices];

      for (int vIndex = 0; vIndex < shpObj->nVertices; vIndex++){
        pts->InsertPoint(pid,shpObj->padfX[vIndex],
                             shpObj->padfY[vIndex],
                             shpObj->padfZ[vIndex]);
        ids[vIndex] = pid++;
      }
      verts->InsertNextCell(shpObj->nVertices, ids);
      delete ids;
      ids = NULL;
      break;

    }
    case LINEOBJ:{
      
      for (int pIndex = 0; pIndex < pCount; pIndex++){
        pStart = shpObj->panPartStart[pIndex];

        if (pIndex == (pCount-1)){
          pEnd = shpObj->nVertices;
        }else{
          pEnd = shpObj->panPartStart[pIndex+1];
        }

        vtkSmartPointer<vtkPolyLine> pLine = vtkSmartPointer<vtkPolyLine>::New();
        pLine->GetPointIds()->SetNumberOfIds(pEnd-pStart); 

        for (int vIndex = pStart; vIndex < pEnd; vIndex++){
          pts->InsertNextPoint(shpObj->padfX[vIndex],
                               shpObj->padfY[vIndex],
                               shpObj->padfZ[vIndex]);
          pLine->GetPointIds()->SetId(vIndex-pStart, vTracker+vIndex-pStart);
        }
        pLines->InsertNextCell(pLine);
        vTracker += pEnd-pStart;
      }
      break;

    }
    case FACEOBJ:{

      for (int pIndex = 0; pIndex < pCount; pIndex++){
        pStart = shpObj->panPartStart[pIndex];

        if (pIndex == (pCount-1)){
          pEnd = shpObj->nVertices;
        }else{
          pEnd = shpObj->panPartStart[pIndex+1];
        }
        vtkSmartPointer<vtkPolygon> poly = vtkSmartPointer<vtkPolygon>::New();
        vtkSmartPointer<vtkPolyLine> pLine = vtkSmartPointer<vtkPolyLine>::New();
        poly->GetPointIds()->SetNumberOfIds(pEnd-pStart); 
        pLine->GetPointIds()->SetNumberOfIds(pEnd-pStart); 

        for (int vIndex = pStart; vIndex < pEnd; vIndex++){
          pts->InsertNextPoint(shpObj->padfX[vIndex],
                               shpObj->padfY[vIndex],
                               shpObj->padfZ[vIndex]);
          poly->GetPointIds()->SetId(vIndex-pStart, vTracker+vIndex-pStart);
          pLine->GetPointIds()->SetId(vIndex-pStart, vTracker+vIndex-pStart);
        }

        polys->InsertNextCell(poly);
        pLines->InsertNextCell(pLine);
        vTracker += pEnd-pStart;
      }
      break;

    }
    case MESHOBJ:{

      switch (*(shpObj->panPartType)){

      case SHPP_TRISTRIP:{
        for (int pIndex = 0; pIndex < pCount; pIndex++){
          pStart = shpObj->panPartStart[pIndex];

          if (pIndex == (pCount-1)){
            pEnd = shpObj->nVertices;
          }else{
            pEnd = shpObj->panPartStart[pIndex+1];
          }

          vtkSmartPointer<vtkTriangleStrip> strip = vtkSmartPointer<vtkTriangleStrip>::New();
          strip->GetPointIds()->SetNumberOfIds(pEnd-pStart);

          for (int vIndex = pStart; vIndex < pEnd; vIndex++){
            pts->InsertNextPoint(shpObj->padfX[vIndex],
                                 shpObj->padfY[vIndex],
                                 shpObj->padfZ[vIndex]);
            strip->GetPointIds()->SetId(vIndex-pStart, vTracker+vIndex-pStart);
          }

          strips->InsertNextCell(strip);
          vTracker += pEnd-pStart;
        }
        break;
      }//SHPP_TRISTRIP
      case SHPP_TRIFAN:{
        for (int pIndex = 0; pIndex < pCount; pIndex++){
          pStart = shpObj->panPartStart[pIndex];

          if (pIndex == (pCount-1)){
            pEnd = shpObj->nVertices;
          }else{
            pEnd = shpObj->panPartStart[pIndex+1];
          }

          vtkSmartPointer<vtkTriangleStrip> strip = vtkSmartPointer<vtkTriangleStrip>::New();
          strip->GetPointIds()->SetNumberOfIds(pEnd-pStart);

          for (int vIndex = pStart; vIndex < pEnd; vIndex++){
            pts->InsertNextPoint(shpObj->padfX[vIndex],
                                 shpObj->padfY[vIndex],
                                 shpObj->padfZ[vIndex]);
            strip->GetPointIds()->SetId(vIndex-pStart, vTracker+vIndex-pStart);
          }

          strips->InsertNextCell(strip);
          vTracker += pEnd-pStart;
        }
        break;
      }//SHPP_TRIFAN
      case SHPP_OUTERRING:
      case SHPP_INNERRING:
      case SHPP_FIRSTRING:
      case SHPP_RING:{
        for (int pIndex = 0; pIndex < pCount; pIndex++){
        pStart = shpObj->panPartStart[pIndex];

        if (pIndex == (pCount-1)){
          pEnd = shpObj->nVertices;
        }else{
          pEnd = shpObj->panPartStart[pIndex+1];
        }
        vtkSmartPointer<vtkPolygon> poly = vtkSmartPointer<vtkPolygon>::New();
        vtkSmartPointer<vtkPolyLine> pLine = vtkSmartPointer<vtkPolyLine>::New();
        poly->GetPointIds()->SetNumberOfIds(pEnd-pStart); 
        pLine->GetPointIds()->SetNumberOfIds(pEnd-pStart); 

        for (int vIndex = pStart; vIndex < pEnd; vIndex++){
          pts->InsertNextPoint(shpObj->padfX[vIndex],
                               shpObj->padfY[vIndex],
                               shpObj->padfZ[vIndex]);
          poly->GetPointIds()->SetId(vIndex-pStart, vTracker+vIndex-pStart);
          pLine->GetPointIds()->SetId(vIndex-pStart, vTracker+vIndex-pStart);
        }

        polys->InsertNextCell(poly);
        pLines->InsertNextCell(pLine);
        vTracker += pEnd-pStart;
      }
      break;
      }//rings
      }//panPartType
      break;
    
    }//MESHOBJ
    }//fileType

    SHPDestroyObject(shpObj);
  }// rIndex
  SHPClose(shpHandle);
  
  DBFHandle dbfHandle = DBFOpen(this->FileName, "rb");
  int fieldCount = DBFGetFieldCount(dbfHandle);
  
  for (int fieldIndex = 0; fieldIndex < fieldCount; fieldIndex++){
    
    DBFFieldType fieldType;
    const char *typeName;
    char nativeFieldType;
    char pszFieldName[12];
    int pnWidth=0, pnDecimals=0, recordCount=0;

    nativeFieldType = DBFGetNativeFieldType(dbfHandle, fieldIndex);
    fieldType = DBFGetFieldInfo(dbfHandle, fieldIndex, pszFieldName, &pnWidth, &pnDecimals);
    recordCount = DBFGetRecordCount(dbfHandle);

    vtkDebugMacro("record count: " << recordCount);

    switch (fieldType){
    case FTString:{

      vtkSmartPointer<vtkStringArray> cellData = vtkSmartPointer<vtkStringArray>::New();

      cellData->SetName(pszFieldName);
      
      for (int recordIndex = 0; recordIndex < recordCount; recordIndex++){
        if (DBFIsAttributeNULL(dbfHandle, recordIndex, fieldIndex)){
          cellData->InsertNextValue("NULL");
        }else{
          cellData->InsertNextValue(DBFReadStringAttribute(dbfHandle, recordIndex, fieldIndex));
        }
      }
      
      polydata->GetCellData()->AddArray(cellData);

      break;
    }
    case FTInteger:{

      vtkSmartPointer<vtkIntArray> cellData = vtkSmartPointer<vtkIntArray>::New();

      cellData->SetName(pszFieldName);
      
      for (int recordIndex = 0; recordIndex < recordCount; recordIndex++){
        if (DBFIsAttributeNULL(dbfHandle, recordIndex, fieldIndex)){
          cellData->InsertNextValue(0);
        }else{
          cellData->InsertNextValue(DBFReadIntegerAttribute(dbfHandle, recordIndex, fieldIndex));
        }
      }
      
      polydata->GetCellData()->AddArray(cellData);

      break;
    }
    case FTDouble:{

      vtkSmartPointer<vtkDoubleArray> cellData = vtkSmartPointer<vtkDoubleArray>::New();

      cellData->SetName(pszFieldName);
      
      for (int recordIndex = 0; recordIndex < recordCount; recordIndex++){
        if (DBFIsAttributeNULL(dbfHandle, recordIndex, fieldIndex)){
          cellData->InsertNextValue(0.0);
        }else{
          cellData->InsertNextValue(DBFReadDoubleAttribute(dbfHandle, recordIndex, fieldIndex));
        }
      }
      
      polydata->GetCellData()->AddArray(cellData);

      break;
    }
    case FTLogical:{
      //what is this? lack of sample data!
      break;
    }
    case FTInvalid:{
      vtkErrorMacro("Invalid DBF field type");
      break;
    }    
    }
  }

  DBFClose(dbfHandle);

  
  //pdRaw->SetPoints(pts);
  //pdRaw->SetPolys(polys);
  //pdRaw->SetLines(pLines);
  //pdRaw->SetVerts(verts);

  //tFilter->SetInput(pdRaw);
  //tFilter->Update();
  //pdRefined = tFilter->GetOutput();

  //polydata->SetPoints(pdRefined->GetPoints());
  //polydata->SetPolys(pdRefined->GetPolys());
  //polydata->SetLines(pdRefined->GetLines());
  //polydata->SetVerts(pdRefined->GetVerts());
  
  
  polydata->SetPoints(pts);
  polydata->SetLines(pLines);
  polydata->SetVerts(verts);
  polydata->SetStrips(strips);

  return 1;
}
Esempio n. 16
0
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;

}
Esempio n. 17
0
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] ) { 

	/* Pointer to temporary matlab array */
	const mxArray *mx;
	mxArray *m_shape_type;

	int	nShapeType, nEntities, i, j, k, iPart, nFields, nStructElem, isPoint, firstInPoints = 1;
	int	num_dbf_fields, num_dbf_records; /* number of DBF attributes, records */
	int	buflen;		/* length of input shapefile name */
	int	status;		/* success or failure */
	char	*shapefile;	/* holder for input shapefile name */
	const	char *pszPartType = "";

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

	/* pointer to the shapefile */
	SHPHandle	hSHP;
	SHPObject	*psShape;
	DBFHandle	dbh;	/* handle for DBF file */

	/* 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.  */
	int	dbf_integer_val, dims[2], *p_parts_ptr, nNaNs, c, i_start, i_stop;
	char	*dbf_char_val, error_buffer[500];
	char	*fnames[100];  /* holds name of fields */
	mxArray *out_struct, *x_out, *y_out, *z_out, *bbox, *p_parts;
	double	*x_out_ptr, *y_out_ptr, *z_out_ptr, *bb_ptr, nan, dbf_double_val;
	size_t	sizebuf;

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

	/* Check for proper number of arguments */
	if (nrhs != 1)
		mexErrMsgTxt("One input arguments are required."); 

	if (nlhs != 2)
		mexErrMsgTxt("Two output arguments 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 )
		mxErrMsgTxt( "Not enough space for shapefile argument.\n" );

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

	/* -------------------------------------------------------------------- */
	/*      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_POINT:
			break;
		case SHPT_POINTZ:
			break;
		case SHPT_ARC:
			break;
		case SHPT_ARCZ:
			break;
		case SHPT_POLYGON:
			break;
		case SHPT_POLYGONZ:
			break;
		case SHPT_MULTIPOINT:		/* JL */
			break;
		default:
			sprintf ( error_buffer, "Unhandled shape code %d (%s)", nShapeType, SHPTypeName ( nShapeType ) );
	        	mexErrMsgTxt( error_buffer ); 
	}
    
	/* Create the output shape type parameter. */
	plhs[1] = mxCreateString ( SHPTypeName ( nShapeType ) );

	/* Open the DBF, and 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. */
	nFields = 3;
	if ( (nShapeType == SHPT_POLYGONZ) || (nShapeType == SHPT_ARCZ) || (nShapeType == SHPT_POINTZ) ) nFields++;
	dbf_field = (DBF_Field_Descriptor *) mxMalloc ( (num_dbf_fields+nFields) * 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+nFields].field_type = DBFGetFieldInfo ( dbh, j, dbf_field[j+nFields].pszFieldName, NULL, NULL );

	fnames[0] = strdup ( "X" );
	fnames[1] = strdup ( "Y" );
	if ( (nShapeType == SHPT_POLYGONZ) || (nShapeType == SHPT_ARCZ) || (nShapeType == SHPT_POINTZ) ) {
		fnames[2] = strdup ( "Z" );
		fnames[3] = strdup ( "BoundingBox" );
	}
	else
		fnames[2] = strdup ( "BoundingBox" );

	for ( j = 0; j < num_dbf_fields; ++j )
		fnames[j+nFields] = strdup ( dbf_field[j+nFields].pszFieldName );

	/* To hold information on eventual polygons with rings */
	/*fnames[num_dbf_fields+3] = strdup ( "nParts" );*/
	/*fnames[num_dbf_fields+4] = strdup ( "PartsIndex" );*/

	/* Allocate space for the output structure. */
	isPoint = ( nShapeType == SHPT_POINT || nShapeType == SHPT_POINTZ ) ? 1: 0;
	nStructElem = ( nShapeType == SHPT_POINT || nShapeType == SHPT_POINTZ ) ? 1: nEntities;
	out_struct = mxCreateStructMatrix ( nStructElem, 1, nFields + num_dbf_fields, (const char **)fnames );

	/* create the BoundingBox */
	dims[0] = 4;		dims[1] = 2;
	bbox = mxCreateNumericArray ( 2, dims, mxDOUBLE_CLASS, mxREAL );
	bb_ptr = mxGetData ( bbox );
	for (i = 0; i < 4; i++) bb_ptr[i]   = adfMinBound[i];
	for (i = 0; i < 4; i++) bb_ptr[i+4] = adfMaxBound[i];
	mxSetField ( out_struct, 0, "BoundingBox", bbox );

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

		/* Create the fields in this struct element.  */
		if ( !isPoint ) {
			nNaNs = psShape->nParts > 1 ? psShape->nParts : 0;
			dims[0] = psShape->nVertices + nNaNs;
			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 );
			if ( (nShapeType == SHPT_POLYGONZ) || (nShapeType == SHPT_POINTZ) || (nShapeType == SHPT_ARCZ)) {
				z_out = mxCreateNumericArray ( 2, dims, mxDOUBLE_CLASS, mxREAL );
				z_out_ptr = mxGetData ( z_out );
			}
		}
		else if (firstInPoints) {	/* Allocate all memory we'll need */
			x_out = mxCreateDoubleMatrix (nEntities, 1, mxREAL);
			x_out_ptr = mxGetPr ( x_out );
			y_out = mxCreateDoubleMatrix (nEntities, 1, mxREAL);
			y_out_ptr = mxGetPr ( y_out );
			if (nShapeType == SHPT_POINTZ) {
				z_out = mxCreateDoubleMatrix (nEntities, 1, mxREAL);
				z_out_ptr = mxGetPr ( z_out );
			}
			firstInPoints = 0;
		}

		if (!isPoint && psShape->nParts > 1) {
			for (k = c = 0; k < psShape->nParts; k++) {
				i_start = psShape->panPartStart[k];
				if (k < psShape->nParts - 1)
					i_stop = psShape->panPartStart[k+1];
				else
					i_stop = psShape->nVertices;

				if ( nShapeType == SHPT_POLYGONZ ) {
					for (j = i_start; j < i_stop; c++, j++) {
						x_out_ptr[c] = psShape->padfX[j];
						y_out_ptr[c] = psShape->padfY[j];
						z_out_ptr[c] = psShape->padfZ[j];
					}
					x_out_ptr[c] = nan;
					y_out_ptr[c] = nan;
					z_out_ptr[c] = nan;
				}
				else {
					for (j = i_start; j < i_stop; c++, j++) {
						x_out_ptr[c] = psShape->padfX[j];
						y_out_ptr[c] = psShape->padfY[j];
					}
					x_out_ptr[c] = nan;
					y_out_ptr[c] = nan;
				}
				c++;
			}
		}
		else if ( isPoint ) {
			x_out_ptr[i] = *psShape->padfX;
			y_out_ptr[i] = *psShape->padfY;
			if (nShapeType == SHPT_POINTZ) z_out_ptr[i] = *psShape->padfZ;
			if (i > 0) {
        			SHPDestroyObject( psShape );
				continue;
			}
		}
		else {		/* Just copy the vertices over. */
			sizebuf = mxGetElementSize ( x_out ) * psShape->nVertices;
			memcpy ( (void *) x_out_ptr, (void *) psShape->padfX, sizebuf );
			memcpy ( (void *) y_out_ptr, (void *) psShape->padfY, sizebuf );
			if ( (nShapeType == SHPT_POLYGONZ)  || (nShapeType == SHPT_ARCZ))
				memcpy ( (void *) z_out_ptr, (void *) psShape->padfZ, sizebuf );
		}

		mxSetField ( out_struct, i, "X", x_out );
		mxSetField ( out_struct, i, "Y", y_out );
		if ( (nShapeType == SHPT_POLYGONZ) || (nShapeType == SHPT_ARCZ) )
			mxSetField ( out_struct, i, "Z", z_out );

		bbox = mxCreateNumericMatrix ( 4, 2, mxDOUBLE_CLASS, mxREAL );
		bb_ptr = (double *)mxGetData ( bbox );
		bb_ptr[0] = psShape->dfXMin;		bb_ptr[1] = psShape->dfYMin;
		bb_ptr[2] = psShape->dfZMin;		bb_ptr[3] = psShape->dfMMin;
		bb_ptr[4] = psShape->dfXMax;		bb_ptr[5] = psShape->dfYMax;
		bb_ptr[6] = psShape->dfZMax;		bb_ptr[7] = psShape->dfMMax;
		if (i > 0)	/* First BB contains the ensemble extent */
			mxSetField ( out_struct, i, "BoundingBox", bbox );

		for ( j = 0; j < num_dbf_fields; ++j ) {
			switch ( dbf_field[j+nFields].field_type ) {
				case FTString:
					dbf_char_val = (char *) DBFReadStringAttribute ( dbh, i, j );
					mxSetField ( out_struct, i, dbf_field[j+nFields].pszFieldName, mxCreateString ( dbf_char_val ) );
					break;
				case FTDouble:
					dbf_double_val = DBFReadDoubleAttribute ( dbh, i, j );
					mxSetField ( out_struct, i, dbf_field[j+nFields].pszFieldName, mxCreateDoubleScalar ( dbf_double_val ) );
					break;
				case FTInteger:
				case FTLogical:
					dbf_integer_val = DBFReadIntegerAttribute ( dbh, i, j );
					dbf_double_val = dbf_integer_val;
					mxSetField ( out_struct, i, dbf_field[j+nFields].pszFieldName, mxCreateDoubleScalar ( dbf_double_val ) );
					break;
				default:
					sprintf ( error_buffer, "Unhandled code %d, shape %d, record %d\n", dbf_field[j+nFields].field_type, i, j );
	        			mexErrMsgTxt("Unhandled code"); 
			}
		}
        	SHPDestroyObject( psShape );
	}

	if ( isPoint ) {	/* In this case we still need to "send the true data out" */
		mxSetField ( out_struct, 0, "X", x_out );
		mxSetField ( out_struct, 0, "Y", y_out );
		if (nShapeType == SHPT_POINTZ)
			mxSetField ( out_struct, 0, "Z", z_out );
	}

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

	if ( dbf_field != NULL )
		mxFree ( (void *)dbf_field );

	plhs[0] = out_struct;
}
Esempio n. 18
0
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;
}
Esempio n. 19
0
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;
}
Esempio n. 20
0
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" );
    }
Esempio n. 21
0
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");
}
Esempio n. 22
0
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 );
}
Esempio n. 23
0
/**
 * 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;
}
Esempio n. 24
0
/**
 * 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;
}